diff --git "a/6223.jsonl" "b/6223.jsonl" new file mode 100644--- /dev/null +++ "b/6223.jsonl" @@ -0,0 +1,1773 @@ +{"seq_id":"36729714315","text":"from __future__ import print_function, absolute_import\nimport time\nfrom collections import OrderedDict\n\nimport torch\n\nfrom .evaluation_metrics import cmc, mean_ap\nfrom .feature_extraction import extract_cnn_feature\nfrom .utils.meters import AverageMeter\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nfrom torch.backends import cudnn\n\ndef extract_features(model, data_loader):\n model.eval()\n features = []\n print(\"Begin to extract features...\")\n for k, imgs in enumerate(data_loader):\n inputs, ids = imgs\n fcs, _ = extract_cnn_feature(model, inputs)\n fnorm = torch.norm(fcs,p=2,dim=1,keepdim=True)\n out = fcs.div(fnorm.expand_as(fcs))\n# features += _fcs\n out = out[0].numpy()\n# print('sample:{0:2d}, shape:({1:4d},{2: 4d})'.format(k,out.shape[0],out.shape[1]))\n features.append(out)\n\n#v for fname, fc, pool5, pid in zip(fnames, _fcs, pool5s, pids):\n# features[fname] = pool5\n# fcs[fname] = fc\n# labels[fname] = pid\n\n# cudnn.benchmark = True\n return features\n\n\ndef pairwise_distance(query_feats, gallery_feats, metric=None):\n dist = np.zeros((len(query_feats),len(gallery_feats)))\n avg_query_fea = []\n for fea in query_feats:\n# fea = fea.numpy()\n temp = np.mean(fea, axis=0)[np.newaxis,:]\n avg_query_fea.append(temp)\n# for fea in gallery_feats:\n## fea = fea.numpy()\n# gallery_numpy_feats.append(fea)\n \n for i in range(len(query_feats)):\n for j in range(len(gallery_feats)):\n d = np.min(cdist(avg_query_fea[i],gallery_feats[j]))\n dist[i][j]=d\n\n# x = torch.cat([features[\"\".join(f)].unsqueeze(0) for f, _, _, _ in query], 0)\n# y = torch.cat([features[\"\".join(f)].unsqueeze(0) for f, _, _, _ in gallery], 0)\n# m, n = x.size(0), y.size(0)\n# x = x.view(m, -1)\n# y = y.view(n, -1)\n# if metric is not None:\n# x = metric.transform(x)\n# y = metric.transform(y)\n# x = torch.from_numpy(x)\n# y = torch.from_numpy(y)\n# dist = torch.pow(x, 2).sum(dim=1, keepdim=True).expand(m, n) + \\\n# torch.pow(y, 2).sum(dim=1, keepdim=True).expand(n, m).t()\n# dist.addmm_(1, -2, x, y.t())\n return dist\n\ndef evaluate_all(distmat, query=None, gallery=None,\n query_ids=None, gallery_ids=None,\n query_cams=None, gallery_cams=None,\n cmc_topk=(1, 5, 10, 20, 50)):\n \n # Compute mean AP\n mAP = mean_ap(distmat, query_ids, gallery_ids, query_cams, gallery_cams) \n\n # Compute all kinds of CMC scores\n cmc_configs = {\n 'mars': dict(separate_camera_set=False,\n single_gallery_shot=False,\n first_match_break=True)}\n cmc_scores = {name: cmc(distmat, query_ids, gallery_ids,\n query_cams, gallery_cams, **params)\n for name, params in cmc_configs.items()}\n\n print('Mean AP: {:4.1%}'.format(mAP))\n print('CMC Scores:')\n for k in cmc_topk:\n print(' top-{:<4}{:12.1%}'\n .format(k, \n cmc_scores['mars'][k - 1]))\n\n # Use the allshots cmc top-1 score for validation criterion\n return cmc_scores['mars'][0]\n\nclass Evaluator(object):\n def __init__(self, model):\n super(Evaluator, self).__init__()\n self.model = model\n def evaluate(self, query_data_loader, gallery_data_loader, query_ids, gallery_ids, metric=None):\n query_features = extract_features(self.model, query_data_loader)\n# print(len(query_features))\n# np.save('queryppp.npy',query_features)\n gallery_features = extract_features(self.model,gallery_data_loader)\n distmat = pairwise_distance(query_features, gallery_features, metric=metric)\n# np.save('galleryyy.npy',gallery_features)\n return evaluate_all(distmat, query_ids=query_ids, gallery_ids=gallery_ids)\n","repo_name":"xueping187/weakly-supervised-person-re-id","sub_path":"reid/evaluators.py","file_name":"evaluators.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"88"} +{"seq_id":"28428005857","text":"import random\nfrom Cube import Cube2x2\nfrom Scrambler import Scrambler\nimport time\nimport json\n\ntimer = time.time()\nrandom.seed(1)\nPOSSIBLE_NUMBER_OF_KEYS = 5670\n\n\n############################################################################################################################\nruns = 99999\nscramble = Scrambler.scramble(2)\ncube = Cube2x2(scramble=scramble)\ndct = {cube.colorPositions(\"G\") : scramble}\nwhile True:\n\tscramble = Scrambler.scramble(2)\n\tcube = Cube2x2(scramble=scramble)\n\tcolorThing = cube.colorPositions(\"G\")\n\tif (colorThing not in dct):\n\t\tdct[colorThing] = scramble\n\tif(len(dct) >= POSSIBLE_NUMBER_OF_KEYS):\n\t\tbreak\n\nprint(time.time() - timer)\ntimer = time.time()\n############################################################################################################################\n\n\nmoves = \"F\",\"R\",\"U\",\"B\",\"L\",\"D\",\"F'\",\"R'\",\"U'\",\"B'\",\"L'\",\"D'\",\"F2\",\"R2\",\"U2\",\"B2\",\"L2\",\"D2\"\nGENERATIONS = 1000\nCREATURES_PER_GENERATION = 100\nTEST_PER_CREATURE = 100\nCREATURE_MOVESET_LENGTH = 5\n\n\t\t\t\nmoveSet = {}\nfor key in dct:\n\tmoveSet[key] = [moves[random.randrange(18)] for n in range(10)]\n\nfor i in range(1,10):\n\t# test for one key to randomly get better\n\toutput = {}\n\tstart = i * 567\n\toverallCount = start\n\tfor testKey in sorted(dct)[start:start + 567]:\n\t\t#CREATURE_MOVESET_LENGTH = 5\n\t\ttestCount = 1\n\t\twhile True:\n\t\t\tcube = Cube2x2(scramble=dct[testKey])\n\t\t\tcount = 0\n\t\t\tfor move in moveSet[testKey]:\n\t\t\t\tcube.move(move)\n\t\t\t\ttemp = cube.colorWithMostSolved()\n\t\t\t\tif (temp[1] == \"G\"):\n\t\t\t\t\tif (temp[2] == 4):\n\t\t\t\t\t\tbreak\n\t\t\t\tcount += 1\n\t\t\t\tif(count >= CREATURE_MOVESET_LENGTH):\n\t\t\t\t\tbreak\n\t\t\tcurrentScore = count\n\n\t\t\tcube = Cube2x2(scramble=dct[testKey])\n\t\t\tcount = 0\n\t\t\trandomMoveSet = [moves[random.randrange(18)] for n in range(CREATURE_MOVESET_LENGTH)]\n\t\t\tfor move in randomMoveSet:\n\t\t\t\tcube.move(move)\n\t\t\t\ttemp = cube.colorWithMostSolved()\n\t\t\t\tif (temp[1] == \"G\"):\n\t\t\t\t\tif (temp[2] == 4):\n\t\t\t\t\t\tbreak\n\t\t\t\tcount += 1\n\t\t\tnewScore = count\n\t\t\tif(newScore < currentScore):\n\t\t\t\tmoveSet[testKey] = randomMoveSet\n\t\t\t\toutput[testKey] = randomMoveSet\n\t\t\t\toverallCount += 1\n\t\t\t\tprint(i, testKey, testCount, (overallCount/POSSIBLE_NUMBER_OF_KEYS)*100, time.time() - timer, output[testKey])\n\t\t\t\tbreak\n\t\t\ttestCount += 1\n\t\t\tif(testCount == 200000):\n\t\t\t\tworks = False\n\t\t\t\twhile True:\n\t\t\t\t\tprint(\"Having trouble with this one\")\n\t\t\t\t\tprint(\"Scramble =\", dct[testKey])\n\t\t\t\t\tprint(\"Position =\", testKey)\n\t\t\t\t\tuserIn = input(\"Enter in a Solution: \")\n\t\t\t\t\tmoveSet[testKey] = userIn.split(\",\")\n\t\t\t\t\tprint(moveSet[testKey])\n\t\t\t\t\tcube = Cube2x2(scramble=dct[testKey])\n\t\t\t\t\tfor move in moveSet[testKey]:\n\t\t\t\t\t\tcube.move(move)\n\t\t\t\t\t\ttemp = cube.colorWithMostSolved()\n\t\t\t\t\t\tif (temp[1] == \"G\"):\n\t\t\t\t\t\t\tif (temp[2] == 4):\n\t\t\t\t\t\t\t\tworks = True\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif(works):\n\t\t\t\t\t\tprint(\"That works!\")\n\t\t\t\t\t\toutput[testKey] = moveSet[testKey]\n\t\t\t\t\t\toverallCount += 1\n\t\t\t\t\t\tprint(i, testKey, testCount, (overallCount/POSSIBLE_NUMBER_OF_KEYS)*100, time.time() - timer, output[testKey])\n\t\t\t\t\t\tbreak\n\t\t\t\tif(works):\n\t\t\t\t\tbreak\n\t\t\telif(testCount == 100000):\n\t\t\t\tprint(\"CREATURE_MOVESET_LENGTH has been changed to 10 for this creature\")\n\t\t\t\tCREATURE_MOVESET_LENGTH = 10\n\t\t\telif(testCount == 10000):\n\t\t\t\tprint(\"CREATURE_MOVESET_LENGTH has been changed to 8 for this creature\")\n\t\t\t\tCREATURE_MOVESET_LENGTH = 8\n\t\t\telif(testCount == 2500):\n\t\t\t\tprint(\"CREATURE_MOVESET_LENGTH has been changed to 7 for this creature\")\n\t\t\t\tCREATURE_MOVESET_LENGTH = 7\n\t\t\telif(testCount == 1000):\n\t\t\t\tprint(\"CREATURE_MOVESET_LENGTH has been changed to 6 for this creature\")\n\t\t\t\tCREATURE_MOVESET_LENGTH = 6\n\t\t\t\t\n\n\twith open(\"PerfectMoveSet\" + str(i) + \".json\", 'w') as f:\n\t\tf.write(json.dumps(output))\n\tprint(\"Batch of 567 have been saved to a new .json file\")\n\t\t\nprint(time.time() - timer)\n\n\n","repo_name":"dstaatz/ACM-SIGAI-Hackathon-2017","sub_path":"Generations_First_Side.py","file_name":"Generations_First_Side.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"35977383255","text":"import os,shutil,subprocess,re,logging,json\n\n# 获取日志记录器\nlogger = logging.getLogger('cka')\n\nclass CKATools:\n # 初始化-获取所有环境配置\n def __init__(self, config):\n # 配置服务模板\n self.BASE_DIR = 'files/template/'\n\n self.ETCD_ONE = 'etcd/etcd-one.service'\n self.ETCD_MORE = 'etcd/etcd.service'\n self.ETCD_NETWORK = 'etcd/etcd_flannel.sh'\n\n self.MASTER_APISERVER = 'master/kube-apiserver.service'\n self.MASTER_CONTROLLER = 'master/kube-controller-manager.service'\n self.MASTER_SCHEDULER = 'master/kube-scheduler.service'\n self.NODE_FLANNELD = 'node/flanneld.service'\n self.NODE_PROXY = 'node/kube-proxy.service'\n self.NODE_KUBELET = 'node/kubelet.service'\n\n self.CONFIG_KUBELET = 'config/kubelet.kubeconfig'\n self.CONFIG_KUBEPROXY = 'config/kube-proxy.kubeconfig'\n self.CONFIG_KUBECTL = 'config/kubectl.kubeconfig'\n\n\n self.BOOTSTRAP_TOKEN = config['cka']['BOOTSTRAP_TOKEN']\n self.SERVICE_CIDR = config['cka']['SERVICE_CIDR']\n self.CLUSTER_CIDR = config['cka']['CLUSTER_CIDR']\n\n self.CLUSTER_KUBERNETES_SVC_IP = config['cka']['CLUSTER_KUBERNETES_SVC_IP']\n self.CLUSTER_DNS_SVC_IP = config['cka']['CLUSTER_DNS_SVC_IP']\n self.CLUSTER_DNS_DOMAIN = config['cka']['CLUSTER_DNS_DOMAIN']\n\n self.FLANNEL_ETCD_PREFIX = config['cka']['FLANNEL_ETCD_PREFIX']\n self.ETCD_ENDPOINTS = config['cka']['ETCD_ENDPOINTS']\n self.NODE_PORT_RANGE = config['cka']['NODE_PORT_RANGE']\n self.MASTER_IP = config['cka']['MASTER_IP']\n self.NODE_IP = config['cka']['NODE_IP']\n self.PAUSE_IMAGE = config['cka']['PAUSE_IMAGE']\n\n # 生成 ca 证书文件\n def InitSSL(self, action='clear'):\n SSL_DIR = 'gen/ssl/'\n if not os.path.exists(SSL_DIR):\n shutil.copytree('files/ssl/', SSL_DIR)\n\n if action == 'clear':\n rm_cmd = \"cd \" + SSL_DIR +\" && ls | grep -v json | xargs rm -rf\"\n subprocess.run(rm_cmd, shell=True)\n logger.info('Step1. 证书清理完毕..')\n elif action == 'init':\n # 生成 token 文件\n with open(SSL_DIR+'/token.csv', 'w') as file:\n file.write(self.BOOTSTRAP_TOKEN+',kubelet-bootstrap,10001,\"system:kubelet-bootstrap\"')\n\n with open(SSL_DIR + \"kubernetes-csr.json\", encoding='utf8') as file:\n content = file.read()\n csr = json.loads(content)\n ips = re.findall(r'\\d+.\\d+.\\d+.\\d+', self.ETCD_ENDPOINTS)\n if len(ips)==1:\n if ips[0] == self.MASTER_IP:\n csr['hosts'].insert(1, self.MASTER_IP)\n csr['hosts'].insert(2, self.CLUSTER_KUBERNETES_SVC_IP)\n else:\n # 设置步进,用于指定插入位置\n setp = 0\n for ip in ips:\n setp += 1\n if ip == self.MASTER_IP:\n csr['hosts'].insert(1, self.MASTER_IP)\n else:\n csr['hosts'].insert(setp, ip)\n csr['hosts'].insert(setp+1, self.CLUSTER_KUBERNETES_SVC_IP)\n\n # print(csr['hosts'])\n with open(SSL_DIR + \"kubernetes-csr.json\", 'w') as file:\n json.dump(csr, file, sort_keys=True, indent=4, ensure_ascii=False)\n\n init_ssl = '''\ncd gen/ssl && echo -e 'admin,admin,1\\nsystem,system,2' >> basic_auth_file\ncfssl gencert -initca csr.json | cfssljson -bare ca\nfor target in kubernetes admin kube-proxy flanneld; do\n cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=config.json -profile=kubernetes $target-csr.json | cfssljson -bare $target\ndone\n'''\n subprocess.run(init_ssl, shell=True)\n logger.info('Step1. 证书生成完毕..')\n\n # 生成 kubeconfig\n def InitConfig(self):\n CONFIG_DIR = 'gen/config/'\n if not os.path.exists(CONFIG_DIR):\n os.makedirs(CONFIG_DIR)\n\n # 生成 kubelet 配置命令 - Create kubelet bootstrapping kubeconfig...\n with open(self.BASE_DIR + self.CONFIG_KUBELET, encoding='utf8') as file:\n kubelet_content = file.read()\n kubelet_content = re.sub('\\$\\{KUBE_APISERVER\\}', 'https://'+self.MASTER_IP+':6443', kubelet_content)\n kubelet_content = re.sub('\\$\\{BOOTSTRAP_TOKEN\\}', self.BOOTSTRAP_TOKEN, kubelet_content)\n\n # 生成 kube-proxy 配置命令 - Create kube-proxy kubeconfig...\n with open(self.BASE_DIR + self.CONFIG_KUBEPROXY, encoding='utf8') as file:\n kubeproxy_content = file.read()\n kubeproxy_content = re.sub('\\$\\{KUBE_APISERVER\\}', 'https://' + self.MASTER_IP + ':6443', kubeproxy_content)\n\n # 生成 kubectl 配置命令 - 集群管理员 admin kubeconfig 配置-供 kubectl 调用使用\n with open(self.BASE_DIR + self.CONFIG_KUBECTL, encoding='utf8') as file:\n kubectl_content = file.read()\n kubectl_content = re.sub('\\$\\{KUBE_APISERVER\\}', 'https://' + self.MASTER_IP + ':6443', kubectl_content)\n\n with open(CONFIG_DIR + 'kubeconfig', 'w') as file:\n file.write(kubelet_content+'\\n\\n'+kubeproxy_content+'\\n\\n'+kubectl_content)\n\n # 生成配置 xx.kubeconfig\n with open(CONFIG_DIR +'kubeconfig', encoding='utf8') as file:\n content = file.read()\n subprocess.run('cd gen/ssl &&'+content, shell=True)\n\n logger.info('Step2. kubeconfig 配置命令生成完毕..')\n \n # one 单 etcd ,more etcd cluster\n def etcd_tools(self):\n etcd_status = []\n ips = re.findall(r'\\d+.\\d+.\\d+.\\d+', self.ETCD_ENDPOINTS)\n if len(ips) == 1:\n etcd_list = self.ETCD_ENDPOINTS\n\n etcd_status.append('one')\n etcd_status.append(etcd_list)\n else:\n temp=[]\n endponts = self.ETCD_ENDPOINTS.split(',')\n for end in endponts:\n endpoint = end.split('=')\n temp.append(endpoint[1]) \n etcd_list = \",\".join(temp)\n \n etcd_status.append('more')\n etcd_status.append(etcd_list)\n return etcd_status\n\n # 生成 etcd 配置文件\n def InitETCD(self):\n ETCD_DIR='gen/etcd/'\n # 自动生成路径\n if not os.path.exists(ETCD_DIR):\n os.makedirs(ETCD_DIR)\n\n eds = self.etcd_tools()\n if eds[0] == 'one': # 生成单节点的 ETCD\n with open(self.BASE_DIR+self.ETCD_ONE, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{ETCD_IP\\}', self.MASTER_IP, content)\n\n with open(ETCD_DIR+'etcd.service', 'w', encoding='utf8') as file:\n file.write(content)\n logger.info('init one etcd')\n elif eds[0] == 'more': # 生成集群 ETCD\n etcds = self.ETCD_ENDPOINTS.split(',')\n for node in etcds:\n etcd = node.split('=')\n etcd_name = etcd[0]\n etcd_ip = re.findall(r'\\d+.\\d+.\\d+.\\d+',etcd[1])[0]\n with open(self.BASE_DIR+self.ETCD_MORE, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{ETCD_NAME\\}', etcd_name, content)\n content = re.sub('\\$\\{ETCD_IP\\}', etcd_ip, content)\n content = re.sub('\\$\\{ETCD_NODES\\}', re.sub('2379', '2380',self.ETCD_ENDPOINTS), content)\n with open(ETCD_DIR+etcd_name+'.service', 'w', encoding='utf8') as file:\n file.write(content)\n\n # ETCD Flanneld 网段生成\n with open(self.BASE_DIR+self.ETCD_NETWORK, encoding='utf8') as file:\n flannel = file.read()\n flannel = re.sub('\\$\\{ETCD_ENDPOINTS\\}', eds[1], flannel)\n flannel = re.sub('\\$\\{FLANNEL_ETCD_PREFIX\\}', self.FLANNEL_ETCD_PREFIX, flannel)\n flannel = re.sub('\\$\\{CLUSTER_CIDR\\}', self.CLUSTER_CIDR, flannel)\n\n with open(ETCD_DIR+'etcd_flannel.sh', 'w', encoding='utf8') as file:\n file.write(flannel)\n\n logger.info('init more etcd')\n\n def InitMaster(self):\n MASTER_DIR = 'gen/master/'\n # 自动生成路径\n if not os.path.exists(MASTER_DIR):\n os.makedirs(MASTER_DIR)\n\n eds = self.etcd_tools()\n\n # 生成 Master 配置文件\n # 生成 apiserver 服务配置\n with open(self.BASE_DIR+self.MASTER_APISERVER, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{MASTER_IP\\}', self.MASTER_IP, content)\n content = re.sub('\\$\\{SERVICE_CIDR\\}', self.SERVICE_CIDR, content)\n content = re.sub('\\$\\{NODE_PORT_RANGE\\}', self.NODE_PORT_RANGE, content)\n content = re.sub('\\$\\{ETCD_ENDPOINTS\\}', eds[1], content)\n\n with open(MASTER_DIR+'kube-apiserver.service', 'w') as file:\n file.write(content)\n\n # 生成 controller-manager 配置\n with open(self.BASE_DIR+self.MASTER_CONTROLLER, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{MASTER_IP\\}', self.MASTER_IP, content)\n content = re.sub('\\$\\{SERVICE_CIDR\\}', self.SERVICE_CIDR, content)\n content = re.sub('\\$\\{CLUSTER_CIDR\\}', self.CLUSTER_CIDR, content)\n\n with open(MASTER_DIR+'kube-controller-manager.service', 'w') as file:\n file.write(content)\n\n # 生成 scheduler 配置\n with open(self.BASE_DIR+self.MASTER_SCHEDULER, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{MASTER_IP\\}', self.MASTER_IP, content)\n\n with open(MASTER_DIR+'kube-scheduler.service', 'w') as file:\n file.write(content)\n\n logger.info('init master')\n\n def InitNode(self):\n nodes = self.NODE_IP.split(',')\n for i in range(0, len(nodes)):\n NODE_DIR = 'gen/node'+str(i)+'/'\n node_ip = nodes[i]\n if i == 0:\n node_name = 'kube-master'\n else:\n node_name = 'kube-node'+str(i)\n # 自动生成路径\n if not os.path.exists(NODE_DIR):\n os.makedirs(NODE_DIR)\n\n # 生成 Node 配置文件\n # 生成 kubelet 服务配置\n with open(self.BASE_DIR + self.NODE_KUBELET, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{NODE_NAME\\}', node_name, content)\n content = re.sub('\\$\\{NODE_IP\\}', node_ip, content)\n content = re.sub('\\$\\{PAUSE_IMAGE\\}', self.PAUSE_IMAGE, content)\n content = re.sub('\\$\\{CLUSTER_DNS_SVC_IP\\}', self.CLUSTER_DNS_SVC_IP, content)\n content = re.sub('\\$\\{CLUSTER_DNS_DOMAIN\\}', self.CLUSTER_DNS_DOMAIN, content)\n\n with open(NODE_DIR + 'kubelet.service', 'w') as file:\n file.write(content)\n\n # 生成 kube-proxy 配置\n with open(self.BASE_DIR + self.NODE_PROXY, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{NODE_NAME\\}', node_name, content)\n content = re.sub('\\$\\{NODE_IP\\}', node_ip, content)\n content = re.sub('\\$\\{CLUSTER_CIDR\\}', self.CLUSTER_CIDR, content)\n\n with open(NODE_DIR + 'kube-proxy.service', 'w') as file:\n file.write(content)\n\n # 生成 flanneld 配置\n eds = self.etcd_tools()\n with open(self.BASE_DIR + self.NODE_FLANNELD, encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{NODE_IP\\}', node_ip, content)\n content = re.sub('\\$\\{ETCD_ENDPOINTS\\}', eds[1], content)\n content = re.sub('\\$\\{FLANNEL_ETCD_PREFIX\\}', self.FLANNEL_ETCD_PREFIX, content)\n\n with open(NODE_DIR + 'flanneld.service', 'w') as file:\n file.write(content)\n logger.info('init node')\n\n def InitCoreDNS(self):\n YAML_DIR = 'gen/yaml/'\n if not os.path.exists(YAML_DIR):\n shutil.copytree('files/yaml/', YAML_DIR)\n\n with open(YAML_DIR + \"coredns.yaml\", encoding='utf8') as file:\n content = file.read()\n content = re.sub('\\$\\{CLUSTER_DNS_DOMAIN\\}', self.CLUSTER_DNS_DOMAIN, content)\n content = re.sub('\\$\\{SERVICE_CIDR\\}', self.SERVICE_CIDR, content)\n content = re.sub('\\$\\{CLUSTER_DNS_SVC_IP\\}', self.CLUSTER_DNS_SVC_IP, content)\n\n with open(YAML_DIR+'coredns.yaml', 'w') as file:\n file.write(content)\n logger.info('init coredns')\n\n # 分发二进制文件与配置文件\n def BinCopy(self):\n # mkdir -p down/flannel && cd down\\\n # wget https://dl.k8s.io/v1.10.0/kubernetes-server-linux-amd64.tar.gz\n # wget https://github.com/coreos/etcd/releases/download/v3.2.18/etcd-v3.2.18-linux-amd64.tar.gz\n # wget https://github.com/coreos/flannel/releases/download/v0.10.0/flannel-v0.10.0-linux-amd64.tar.gz\n # tar -xf flannel-v0.10.0-linux-amd64.tar.gz -C flannel \\\n # tar -xf etcd-v3.2.18-linux-amd64.tar.gz \\\n # tar -xf kubernetes-server-linux-amd64-v1.10.0.tar.gz \\\n # 生成指定的目录\n for path in ['etcd','master','node']:\n file_path = 'deploy/'+path\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n\n shutil.copy('../down/kubernetes/server/bin/kubelet','deploy/node/')\n shutil.copy('../down/kubernetes/server/bin/kube-proxy','deploy/node/')\n shutil.copy('../down/flannel/mk-docker-opts.sh','deploy/node/')\n shutil.copy('../down/flannel/flanneld','deploy/node/')\n shutil.copy('../down/kubernetes/server/bin/kube-apiserver','deploy/master/')\n shutil.copy('../down/kubernetes/server/bin/kube-controller-manager','deploy/master/')\n shutil.copy('../down/kubernetes/server/bin/kube-scheduler','deploy/master/')\n shutil.copy('../down/kubernetes/server/bin/kubectl','deploy/master/')\n shutil.copy('../down/etcd-v3.2.18-linux-amd64/etcd','deploy/etcd/')\n shutil.copy('../down/etcd-v3.2.18-linux-amd64/etcdctl','deploy/etcd/')\n\n logger.info('Bin Copy')\n\n # 下发二进制文件\n def BinDeploy(self):\n deploy = '''\nfor etcd in master node1 node2 ;do\n rsync -avzP deploy/etcd/ ${etcd}:/usr/local/bin/\ndone\nfor master in master ;do\n rsync -avzP deploy/master/ ${master}:/usr/local/bin/\ndone\nfor node in master node1 node2 ;do\n rsync -avzP deploy/node/ ${node}:/usr/local/bin/\ndone\n'''\n subprocess.run(deploy, shell=True)\n logger.info('Bin Copy')\n\n def VerifyService(self):\n eds = self.etcd_tools()\n if eds[0] == 'one':\n etcd = '''\nrsync -avzP gen/etcd/etcd.service master:/etc/systemd/system/etcd.service\n'''\n elif eds[0] == 'more':\n etcd = '''\nrsync -avzP gen/etcd/infra1.service master:/etc/systemd/system/etcd.service\nrsync -avzP gen/etcd/infra2.service node1:/etc/systemd/system/etcd.service\nrsync -avzP gen/etcd/infra3.service node2:/etc/systemd/system/etcd.service\n'''\n service = '''\nfor node in master node1 node2 ;do\n ssh ${node} \"mkdir -p /etc/kubernetes/ssl/ \"\n ssh ${node} \"mkdir -p /var/lib/etcd/\"\n ssh ${node} \"mkdir -p /var/lib/kubelet/\"\n ssh ${node} \"mkdir -p /var/lib/kube-proxy/\"\ndone\n\nfor node in master node1 node2 ;do\n rsync -avzP gen/ssl/ ${node}:/etc/kubernetes/ssl/\ndone\n\nfor master in master ;do\n ssh ${master} \"mkdir -p /root/.kube ; \\cp -f /etc/kubernetes/ssl/kubeconfig /root/.kube/config \"\ndone\n\nrsync -avzP gen/node0/ master:/etc/systemd/system/\nrsync -avzP gen/node1/ node1:/etc/systemd/system/\nrsync -avzP gen/node2/ node2:/etc/systemd/system/\n\nfor master in master ;do\n rsync -avzP gen/master/ ${master}:/etc/systemd/system/\ndone\n'''\n subprocess.run(etcd + service, shell=True)\n # 写入 etcd 网段信息-需要手动在 Master 节点执行\n with open('gen/etcd/etcd_flannel.sh', encoding='utf8') as file:\n network = file.read()\n # 检测 etcd 状态\n etcd_check = '''\nsystemctl daemon-reload && systemctl start etcd && systemctl enable etcd\n\nMaster Run: \nETCDCTL_API=3 etcdctl --endpoints=${ETCD_ENDPOINTS} --cacert=/etc/kubernetes/ssl/ca.pem --cert=/etc/kubernetes/ssl/kubernetes.pem --key=/etc/kubernetes/ssl/kubernetes-key.pem endpoint health;\netcdctl --endpoints=${ETCD_ENDPOINTS} --ca-file=/etc/kubernetes/ssl/ca.pem --cert-file=/etc/kubernetes/ssl/kubernetes.pem --key-file=/etc/kubernetes/ssl/kubernetes-key.pem get /kubernetes/network/config\n '''\n print(re.sub('\\$\\{ETCD_ENDPOINTS\\}', eds[1], etcd_check) + \"\\n\" + network)\n\n def RetDeploy(self, action='flannel'):\n\n if action == 'flannel':\n content = '''\nfor node in master node1 node2 ;do\n ssh ${node} \"systemctl daemon-reload && systemctl stop docker && systemctl start flanneld docker && systemctl enable flanneld\"\ndone\n '''\n elif action == 'master':\n content = '''\nfor master in master ;do\n ssh ${master} \"systemctl daemon-reload && systemctl start kube-apiserver kube-controller-manager kube-scheduler && systemctl enable kube-apiserver kube-controller-manager kube-scheduler\"\ndone\n '''\n # kubelet 依赖于 bootstrap 角色绑定\n bootstrap = '''\necho -e \"192.168.20.151 kube-master\\n192.168.20.152 kube-node1\\n192.168.20.153 kube-node2\" >> /etc/hosts\nkubectl create clusterrolebinding kubelet-bootstrap --clusterrole=system:node-bootstrapper --user=kubelet-bootstrap \n'''\n print(bootstrap)\n elif action == 'node':\n content = '''\nfor node in master node1 node2 ;do\n ssh ${node} \"systemctl daemon-reload && systemctl start kubelet kube-proxy && systemctl enable kubelet kube-proxy\"\ndone\n '''\n # 验证集群\n verify_cluster = '''\nkubectl get csr | awk '/Pending/ {print $1}' | xargs kubectl certificate approve\n'''\n print(verify_cluster)\n\n subprocess.run(content, shell=True)\n logger.info('complete cluster')\n\n # 环境清理脚本\n def DownKube(self):\n ips = re.findall(r'\\d+.\\d+.\\d+.\\d+', self.ETCD_ENDPOINTS)\n if len(ips) == 1:\n etcd = '''\nssh master \"rm -rf /etc/systemd/system/etcd.service\"\n'''\n else:\n etcd = '''\nfor etcd in master node1 node2; do\n ssh ${etcd} \"rm -rf /etc/systemd/system/etcd.service\"\ndone\n'''\n init = '''\nfor node in master node1 node2; do\n ssh ${node} \"systemctl daemon-reload && systemctl stop kublet kube-proxy\"\ndone\n\nfor master in master; do\n ssh ${master} \"systemctl stop kube-scheduler kube-controller-manager kube-apiserver flanneld docker\"\ndone\n\nfor etcd in master; do\n ssh ${etcd} \"systemctl stop etcd\"\ndone\n\nfor node in master node1 node2 ;do\n ssh ${node} \"rm -rf /etc/kubernetes/ssl/ /etc/systemd/system/flanneld.service /etc/systemd/system/flanneld.service /etc/systemd/system/kube-proxy.service /etc/systemd/system/kubelet.service\"\ndone\nfor master in master ;do\n ssh ${master} \"rm -rf /etc/systemd/system/kube-apiserver.service /etc/systemd/system/kube-controller-manager.service /etc/systemd/system/kube-scheduler.service\"\ndone\n'''\n\n dirname = '''\nfor node in master node1 node2 ;do\n ssh ${node} \"systemctl daemon-reload && rm -rf /etc/kubernetes/ssl/ /var/lib/etcd/ /var/lib/kubelet/ /var/lib/kube-proxy/\" \ndone\n'''\n # 清理 ssl 证书与服务文件\n # print(init+etcd+dirname)\n subprocess.run(init+etcd+dirname, shell=True)\n logger.info('clear cluster')\n","repo_name":"markthink/cka-kubernetes","sub_path":"service/tools/cka_tools.py","file_name":"cka_tools.py","file_ext":"py","file_size_in_byte":19743,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"88"} +{"seq_id":"1042573696","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nimport re\n\n\nclass IobEncoder(object):\n \"\"\"\n Utility class for encoding tagged token streams using IOB2 encoding.\n\n Encode input tokens using ``encode`` method::\n\n >>> iob_encoder = IobEncoder()\n >>> input_tokens = [\"__START_PER__\", \"John\", \"__END_PER__\", \"said\"]\n >>> def encode(encoder, tokens): return [p for p in IobEncoder.from_indices(encoder.encode(tokens), tokens)]\n >>> encode(iob_encoder, input_tokens)\n [('John', 'B-PER'), ('said', 'O')]\n\n\n >>> input_tokens = [\"hello\", \"__START_PER__\", \"John\", \"Doe\", \"__END_PER__\", \"__START_PER__\", \"Mary\", \"__END_PER__\", \"said\"]\n >>> tokens = encode(iob_encoder, input_tokens)\n >>> tokens, tags = iob_encoder.split(tokens)\n >>> tokens, tags\n (['hello', 'John', 'Doe', 'Mary', 'said'], ['O', 'B-PER', 'I-PER', 'B-PER', 'O'])\n\n Note that IobEncoder is stateful. This means you can encode incomplete\n stream and continue the encoding later::\n\n >>> iob_encoder = IobEncoder()\n >>> input_tokens_partial = [\"__START_PER__\", \"John\"]\n >>> encode(iob_encoder, input_tokens_partial)\n [('John', 'B-PER')]\n >>> input_tokens_partial = [\"Mayer\", \"__END_PER__\", \"said\"]\n >>> encode(iob_encoder, input_tokens_partial)\n [('Mayer', 'I-PER'), ('said', 'O')]\n\n To reset internal state, use ``reset method``::\n\n >>> iob_encoder.reset()\n\n Group results to entities::\n\n >>> iob_encoder.group(encode(iob_encoder, input_tokens))\n [(['hello'], 'O'), (['John', 'Doe'], 'PER'), (['Mary'], 'PER'), (['said'], 'O')]\n\n Input token stream is processed by ``InputTokenProcessor()`` by default;\n you can pass other token processing class to customize which tokens\n are considered start/end tags.\n \"\"\"\n\n def __init__(self, token_processor=None):\n self.token_processor = token_processor or InputTokenProcessor()\n self.reset()\n\n def reset(self):\n \"\"\" Reset the sequence \"\"\"\n self.tag = 'O'\n\n def iter_encode(self, input_tokens):\n for number, token in enumerate(input_tokens):\n token_type, value = self.token_processor.classify(token)\n\n if token_type == 'start':\n self.tag = \"B-\" + value\n\n elif token_type == 'end':\n if value != self.tag[2:]:\n raise ValueError(\n \"Invalid tag sequence: close tag '%s' \"\n \"doesn't match open tag '%s'.\" % (value, self.tag)\n )\n self.tag = \"O\"\n\n elif token_type == 'token':\n yield number, self.tag\n if self.tag[0] == 'B':\n self.tag = \"I\" + self.tag[1:]\n\n elif token_type == 'drop':\n continue\n\n else:\n raise ValueError(\"Unknown token type '%s' for token '%s'\" % (token_type, token))\n\n def encode(self, input_tokens):\n return list(self.iter_encode(input_tokens))\n\n def split(self, tokens):\n \"\"\" split ``[(token, tag)]`` to ``([token], [tags])`` tuple \"\"\"\n return [t[0] for t in tokens], [t[1] for t in tokens]\n\n @classmethod\n def from_indices(cls, indices, input_tokens):\n for idx, tag in indices:\n yield input_tokens[idx], tag\n\n @classmethod\n def group(cls, data, strict=False):\n \"\"\"\n Group IOB2-encoded entities. ``data`` should be an iterable\n of ``(info, iob_tag)`` tuples. ``info`` could be any Python object,\n ``iob_tag`` should be a string with a tag.\n\n Example::\n\n >>>\n >>> data = [(\"hello\", \"O\"), (\",\", \"O\"), (\"John\", \"B-PER\"),\n ... (\"Doe\", \"I-PER\"), (\"Mary\", \"B-PER\"), (\"said\", \"O\")]\n >>> for items, tag in IobEncoder.iter_group(data):\n ... print(\"%s %s\" % (items, tag))\n ['hello', ','] O\n ['John', 'Doe'] PER\n ['Mary'] PER\n ['said'] O\n\n By default, invalid sequences are fixed::\n\n >>> data = [(\"hello\", \"O\"), (\"John\", \"I-PER\"), (\"Doe\", \"I-PER\")]\n >>> for items, tag in IobEncoder.iter_group(data):\n ... print(\"%s %s\" % (items, tag))\n ['hello'] O\n ['John', 'Doe'] PER\n\n Pass 'strict=True' argument to raise an exception for\n invalid sequences::\n\n >>> for items, tag in IobEncoder.iter_group(data, strict=True):\n ... print(\"%s %s\" % (items, tag))\n Traceback (most recent call last):\n ...\n ValueError: Invalid sequence: I-PER tag can't start sequence\n \"\"\"\n return list(cls.iter_group(data, strict))\n\n @classmethod\n def iter_group(cls, data, strict=False):\n buf, tag = [], 'O'\n\n for info, iob_tag in data:\n if iob_tag.startswith('I-') and tag != iob_tag[2:]:\n if strict:\n raise ValueError(\"Invalid sequence: %s tag can't start sequence\" % iob_tag)\n else:\n iob_tag = 'B-' + iob_tag[2:] # fix bad tag\n\n if iob_tag.startswith('B-'):\n if buf:\n yield buf, tag\n buf = []\n\n elif iob_tag == 'O':\n if buf and tag != 'O':\n yield buf, tag\n buf = []\n\n tag = 'O' if iob_tag == 'O' else iob_tag[2:]\n buf.append(info)\n\n if buf:\n yield buf, tag\n\n\n# FIXME: this hook is incomplete: __START_TAG__ tokens are assumed everywhere.\nclass InputTokenProcessor(object):\n def __init__(self, tagset=None):\n if tagset is not None:\n tag_re = '|'.join(tagset)\n else:\n tag_re = '\\w+?'\n self.tag_re = re.compile('__(START|END)_(%s)__' % tag_re)\n\n def classify(self, token):\n \"\"\"\n >>> tp = InputTokenProcessor()\n >>> tp.classify('foo')\n ('token', 'foo')\n >>> tp.classify('__START_ORG__')\n ('start', 'ORG')\n >>> tp.classify('__END_ORG__')\n ('end', 'ORG')\n \"\"\"\n\n # start/end tags\n m = self.tag_re.match(token)\n if m:\n return m.group(1).lower(), m.group(2)\n\n # # drop standalone commas and semicolons by default?\n # if token in {',', ';'}:\n # return 'drop', token\n\n # regular token\n return 'token', token\n","repo_name":"scrapinghub/webstruct","sub_path":"webstruct/sequence_encoding.py","file_name":"sequence_encoding.py","file_ext":"py","file_size_in_byte":6469,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"88"} +{"seq_id":"4739580648","text":"# -*- coding: utf-8 -*-\nimport bpy\nfrom xml.etree import cElementTree as ElementTree\nfrom ast import literal_eval as make_tuple\nimport os\nfrom datetime import datetime\nimportBaseDir = r'D:/SC313/Data/'\n\ndef read_MTL_data(context, filepath, use_some_setting):\n print(\"Importing from \" + filepath)\n createMaterialsFromMTL(filepath)\n print(\"Finished\")\n\n return {'FINISHED'}\n\n# ImportHelper is a helper class, defines filename and\n# invoke() function which calls the file selector.\nfrom bpy_extras.io_utils import ImportHelper\nfrom bpy.props import StringProperty, BoolProperty, EnumProperty, CollectionProperty\nfrom bpy.types import Operator, OperatorFileListElement\n\n\nclass ImportMTL(Operator, ImportHelper):\n \"\"\"This appears in the tooltip of the operator and in the generated docs\"\"\"\n bl_idname = \"import_test.some_data\" # important since its how bpy.ops.import_test.some_data is constructed\n bl_label = \"Import SC Materials\"\n \n files = CollectionProperty(\n name=\"File Path\",\n type=OperatorFileListElement,\n )\n directory = StringProperty(\n subtype='DIR_PATH',\n )\n \n # ImportHelper mixin class uses this\n filename_ext = \".mtl\"\n\n filter_glob: StringProperty(\n default=\"*.mtl\",\n options={'HIDDEN'},\n maxlen=255, # Max internal buffer length, longer would be clamped.\n )\n\n importBaseDir: StringProperty(\n default=importBaseDir,\n )\n\n # List of operator properties, the attributes will be assigned\n # to the class instance from the operator settings before calling.\n use_setting: BoolProperty(\n name=\"Overwrite Materials\",\n description=\"Overwrite materials that have the same name (UNIMPLMENTED)\",\n default=True, \n )\n\n\n def execute(self, context):\n #for file in self.files:\n # filepath = os.path.join(self.directory, file.name)\n # return read_MTL_data(context, self.filepath, self.use_setting)\n #filepath = os.path.join(self.directory, self.files.name)\n return read_MTL_data(context, self.filepath, self.use_setting)\n\n\n# Only needed if you want to add into a dynamic menu\ndef menu_func_import(self, context):\n self.layout.operator(ImportMTL.bl_idname, text=\"Import SC Materials\")\n\n\ndef register():\n bpy.utils.register_class(ImportMTL)\n bpy.types.TOPBAR_MT_file_import.append(menu_func_import)\n\n\ndef unregister():\n bpy.utils.unregister_class(ImportMTL)\n bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)\n\n\ndef createMaterialsFromMTL(xmlPath):\n try:\n parser = ElementTree.XMLParser(encoding='utf-8')\n xmlRoot = ElementTree.parse(xmlPath, parser=parser).iter('Material')\n #xmlRoot = ElementTree.parse(xmlPath).iter('Material')\n except Exception as e:\n writetoLog(\"XML not found: \" + xmlPath, 'Error')\n writetoLog(\"Error: \" + str(e), 'Error')\n #print('XML can\\'t be opened')\n return False\n \n xmlPath = xmlPath.replace('\\\\', '/')\n xmlName = xmlPath.rsplit('/',1)[1]\n xmlName = xmlName.rsplit('.',1)[0] \n writetoLog(\"Opening: \" + xmlPath)\n \n for element in xmlRoot:\n if element.get('Name') == None: element.set('Name', xmlName) \n writetoLog(\"Material Name: \" + str(element.get('Name')))\n writetoLog(\"Shader type: \" + str(element.get('Shader')))\n mtlvalues = element.attrib \n \n for subelement in element:\n #print(\" \" + subelement.tag)\n mtlvalues[subelement.tag] = subelement\n for key, value in subelement.attrib.items():\n continue\n #print(\" \" + key + \": \" + value)\n #for texture in subelement.getchildren():\n #print(\" Texture: \")\n #print(texture.attrib)\n if bpy.data.materials.get('Name') and use_setting == False:\n if bpy.data.materials['Name']['Filename']:\n writetoLog(\"Skipping\")\n continue\n \n if element.get('Name') in (\"proxy\", \"Proxy\"):\n mat = createNoSurface(**mtlvalues) \n elif element.get('Shader') in (\"Ilum\", \"Illum\", \"MeshDecal\"): \n mat = createIlumSurface(**mtlvalues)\n elif element.get('Shader') == \"HardSurface\":\n mat = createHardSurface(**mtlvalues) \n elif element.get('Shader') in (\"Glass\", \"GlassPBR\"):\n mat = createGlassSurface(**mtlvalues)\n elif element.get('Shader') == \"LayerBlend\":\n mat = createLayerBlendSurface(**mtlvalues)\n elif element.get('Shader') == \"Layer\":\n mat = createLayerNode(**mtlvalues) \n elif element.get('Shader') == \"NoDraw\":\n mat = createNoSurface(**mtlvalues)\n else:\n writetoLog(\"Shader type not found \" + str(element.get('Shader')))\n #mat = createUnknownSurface(**mtlvalues)\n continue \n if mat != None:\n mat['Filename'] = xmlPath\n print('Imported material ' + str(element.get('Name'))) \n return True\n\n \ndef createIlumSurface(**mtl):\n writetoLog(mtl[\"Shader\"] + \" - \" + mtl[\"SurfaceType\"])\n mat = (bpy.data.materials.get(mtl[\"Name\"]) or bpy.data.materials.new(mtl[\"Name\"]))\n \n setViewport(mat, mtl)\n \n #Shader \n mat.use_nodes = True\n nodes = mat.node_tree.nodes\n nodes.clear()\n shaderout = nodes.new(type=\"ShaderNodeOutputMaterial\")\n shadergroup = nodes.new(type=\"ShaderNodeGroup\")\n writeAttribs(mat, mtl, \"PublicParams\")\n \n if \"pom\" in mtl[\"Name\"]:\n shadergroup.node_tree = bpy.data.node_groups['_Illum.pom']\n setViewport(mat, mtl, True)\n elif \"decal\" in mtl[\"Name\"]:\n shadergroup.node_tree = bpy.data.node_groups['_Illum.decal']\n setViewport(mat, mtl, True)\n elif \"glow\" in mtl[\"Name\"]:\n shadergroup.node_tree = bpy.data.node_groups['_Illum.emit'] \n else:\n shadergroup.node_tree = bpy.data.node_groups['_Illum']\n \n mat.node_tree.links.new(shadergroup.outputs['BSDF'], shaderout.inputs['Surface'])\n mat.node_tree.links.new(shadergroup.outputs['Displacement'], shaderout.inputs['Displacement'])\n \n if \"pom\" in mtl[\"Name\"]:\n shadergroup.inputs['Base Color'].default_value = (0.5,0.5,0.5,1)\n shadergroup.inputs['n Strength'].default_value = .1\n else:\n shadergroup.inputs['Base Color'].default_value = mat.diffuse_color\n \n shadergroup.inputs['ddna Alpha'].default_value = mat.roughness \n shadergroup.inputs['spec Color'].default_value = mat.specular_color[0]\n \n shaderout.location.x += 200\n \n loadTextures(mtl[\"Textures\"], nodes, mat, shadergroup) \n\n \n if not mtl.get(\"MatLayers\"): return mat\n\n for submat in mtl[\"MatLayers\"]:\n if \"WearLayer\" in submat.get(\"Name\"): continue\n path = importBaseDir + submat.get(\"Path\")\n writetoLog(stripPath(path))\n newbasegroup=nodes.new(\"ShaderNodeGroup\") \n if createMaterialsFromMTL(path) == False:\n writetoLog(\"MTL not found: \" + str(path),\"Error\")\n continue \n newbasegroup.node_tree = bpy.data.node_groups[stripPath(path)] \n newbasegroup.name = submat.get(\"Name\")\n #newbasegroup.node_tree.label = submat.get(\"Name\")\n newbasegroup.inputs['tint Color'].default_value = make_tuple(str(submat.get(\"TintColor\")) + \",1\")\n newbasegroup.inputs['UV Scale'].default_value = [float(submat.get(\"UVTiling\")), float(submat.get(\"UVTiling\")), float(submat.get(\"UVTiling\"))]\n newbasegroup.location.x = -600\n newbasegroup.location.y += y\n y -= 260\n mat.node_tree.links.new(newbasegroup.outputs['diff Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'diff Color'])\n mat.node_tree.links.new(newbasegroup.outputs['diff Alpha'], shadergroup.inputs[newbasegroup.name + ' ' + 'diff Alpha'])\n mat.node_tree.links.new(newbasegroup.outputs['ddna Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'ddna Color'])\n mat.node_tree.links.new(newbasegroup.outputs['ddna Alpha'], shadergroup.inputs[newbasegroup.name + ' ' + 'ddna Alpha'])\n mat.node_tree.links.new(newbasegroup.outputs['spec Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'spec Color'])\n mat.node_tree.links.new(newbasegroup.outputs['disp Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'disp Alpha'])\n mat.node_tree.links.new(newbasegroup.outputs['metal Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'metal Alpha'])\n mat.node_tree.links.new(newbasegroup.outputs['blend Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'blend Alpha']) \n return mat\n\n\ndef createHardSurface(**mtl):\n writetoLog(\"Material: \" + mtl[\"Name\"])\n mat = (bpy.data.materials.get(mtl[\"Name\"]) or bpy.data.materials.new(mtl[\"Name\"]))\n \n setViewport(mat, mtl)\n \n #Shader \n mat.use_nodes = True\n nodes = mat.node_tree.nodes\n nodes.clear()\n shaderout = nodes.new(type=\"ShaderNodeOutputMaterial\")\n shadergroup = nodes.new(type=\"ShaderNodeGroup\")\n shadergroup.node_tree = bpy.data.node_groups['_HardSurface']\n mat.node_tree.links.new(shadergroup.outputs['BSDF'], shaderout.inputs['Surface'])\n mat.node_tree.links.new(shadergroup.outputs['Displacement'], shaderout.inputs['Displacement'])\n shadergroup.inputs['Base Color'].default_value = mat.diffuse_color\n shadergroup.inputs['Primary ddna Alpha'].default_value = mat.roughness\n shadergroup.inputs['Metallic'].default_value = 0\n shadergroup.inputs['Anisotropic'].default_value = .5\n shadergroup.inputs['Emission'].default_value = make_tuple(mtl[\"Emissive\"] + \",1\")\n \n \n shaderout.location.x += 200\n \n writeAttribs(mat, mtl, \"PublicParams\")\n loadTextures(mtl[\"Textures\"], nodes, mat, shadergroup) \n \n if not mtl.get(\"MatLayers\"): return mat\n\n y=-300\n \n for submat in mtl[\"MatLayers\"]:\n #if \"WearLayer\" in submat.get(\"Name\"): continue\n path = importBaseDir + submat.get(\"Path\")\n writetoLog(\"MTL: \" + stripPath(path))\n newbasegroup = nodes.new(\"ShaderNodeGroup\") \n if createMaterialsFromMTL(path) == False:\n writetoLog(\"MTL not found: \" + str(path),\"Error\")\n continue \n newbasegroup.node_tree = bpy.data.node_groups[stripPath(path)] \n if 'Wear' in submat.get(\"Name\"):\n newbasegroup.name = 'Secondary'\n else:\n newbasegroup.name = submat.get(\"Name\")\n \n #newbasegroup.node_tree.label = submat.get(\"Name\")\n newbasegroup.inputs['tint Color'].default_value = make_tuple(str(submat.get(\"TintColor\")) + \",1\")\n newbasegroup.inputs['UV Scale'].default_value = [float(submat.get(\"UVTiling\")), float(submat.get(\"UVTiling\")), float(submat.get(\"UVTiling\"))]\n newbasegroup.location.x = -600\n newbasegroup.location.y += y\n y -= 300\n mat.node_tree.links.new(newbasegroup.outputs['diff Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'diff Color'])\n mat.node_tree.links.new(newbasegroup.outputs['diff Alpha'], shadergroup.inputs[newbasegroup.name + ' ' + 'diff Alpha'])\n mat.node_tree.links.new(newbasegroup.outputs['ddna Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'ddna Color'])\n mat.node_tree.links.new(newbasegroup.outputs['ddna Alpha'], shadergroup.inputs[newbasegroup.name + ' ' + 'ddna Alpha'])\n mat.node_tree.links.new(newbasegroup.outputs['spec Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'spec Color'])\n mat.node_tree.links.new(newbasegroup.outputs['disp Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'disp Color'])\n mat.node_tree.links.new(newbasegroup.outputs['blend Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'blend Color']) \n \n return mat\n\n\ndef createGlassSurface(**mtl):\n writetoLog(\"Material: \" + mtl[\"Name\"])\n mat = (bpy.data.materials.get(mtl[\"Name\"]) or bpy.data.materials.new(mtl[\"Name\"]))\n \n #Viewport material values\n setViewport(mat, mtl, True)\n \n #Shader \n mat.use_nodes = True\n nodes = mat.node_tree.nodes\n nodes.clear()\n shaderout = nodes.new(type=\"ShaderNodeOutputMaterial\")\n shadergroup = nodes.new(type=\"ShaderNodeGroup\")\n shadergroup.node_tree = bpy.data.node_groups['_Glass']\n mat.node_tree.links.new(shadergroup.outputs['BSDF'], shaderout.inputs['Surface'])\n mat.node_tree.links.new(shadergroup.outputs['Displacement'], shaderout.inputs['Displacement'])\n shadergroup.inputs['Base Color'].default_value = mat.diffuse_color\n shadergroup.inputs['ddna Alpha'].default_value = mat.roughness\n shadergroup.inputs['spec Color'].default_value = mat.specular_color[0]\n shaderout.location.x += 200\n \n loadTextures(mtl[\"Textures\"], nodes, mat, shadergroup) \n \n return mat\n\n \ndef createLayerBlendSurface(**mtl):\n writetoLog(\"Material: \" + mtl[\"Name\"])\n mat = (bpy.data.materials.get(mtl[\"Name\"]) or bpy.data.materials.new(mtl[\"Name\"]))\n \n #Viewport material values\n setViewport(mat, mtl)\n \n #Shader \n mat.use_nodes = True\n nodes = mat.node_tree.nodes\n nodes.clear()\n shaderout = nodes.new(type=\"ShaderNodeOutputMaterial\")\n shadergroup = nodes.new(type=\"ShaderNodeGroup\")\n shadergroup.node_tree = bpy.data.node_groups['_LayerBlend']\n mat.node_tree.links.new(shadergroup.outputs['BSDF'], shaderout.inputs['Surface'])\n mat.node_tree.links.new(shadergroup.outputs['Displacement'], shaderout.inputs['Displacement'])\n shadergroup.inputs['Base Color'].default_value = mat.diffuse_color\n shadergroup.inputs['ddna Alpha'].default_value = mat.roughness\n shaderout.location.x += 200\n \n #loadMaterials(mtl[\"MatLayers\"])\n\n loadTextures(mtl[\"Textures\"], nodes, mat, shadergroup) \n \n y=-300\n \n \n\n mats = (mtl.get(\"MatLayers\") or mtl.get(\"MatReferences\"))\n \n if mats == None: return\n \n for submat in mats:\n #if submat.get(\"Name\") in \"WearLayer\": continue\n path = str(submat.get(\"Path\") or submat.get(\"File\"))\n path = importBaseDir + path\n writetoLog(stripPath(path))\n newbasegroup=nodes.new(\"ShaderNodeGroup\") \n if createMaterialsFromMTL(path) == False:\n writetoLog(\"MTL not found: \" + str(path),\"Error\")\n continue \n newbasegroup.node_tree = bpy.data.node_groups[stripPath(path)] \n if submat.get(\"Name\"):\n newbasegroup.name = submat.get(\"Name\")\n elif submat.get(\"Slot\"):\n newbasegroup.name = 'BaseLayer' + str(int(submat.get(\"Slot\"))+1)\n else:\n newbasegroup.name = 'Unknown'\n #newbasegroup.node_tree.label = submat.get(\"Name\")\n if submat.get(\"TintColor\"):\n newbasegroup.inputs['tint Color'].default_value = make_tuple(str(submat.get(\"TintColor\")) + \",1\")\n if submat.get(\"UVTiling\"): \n newbasegroup.inputs['UV Scale'].default_value = [float(submat.get(\"UVTiling\")), float(submat.get(\"UVTiling\")), float(submat.get(\"UVTiling\"))]\n \n newbasegroup.location.x = -600\n newbasegroup.location.y += y\n y -= 260\n try: \n mat.node_tree.links.new(newbasegroup.outputs['diff Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'diff Color'])\n mat.node_tree.links.new(newbasegroup.outputs['diff Alpha'], shadergroup.inputs[newbasegroup.name + ' ' + 'diff Alpha']) \n mat.node_tree.links.new(newbasegroup.outputs['ddna Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'ddna Color'])\n mat.node_tree.links.new(newbasegroup.outputs['ddna Alpha'], shadergroup.inputs[newbasegroup.name + ' ' + 'ddna Alpha'])\n mat.node_tree.links.new(newbasegroup.outputs['spec Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'spec Color'])\n mat.node_tree.links.new(newbasegroup.outputs['disp Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'disp Color'])\n mat.node_tree.links.new(newbasegroup.outputs['blend Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'blend Color'])\n mat.node_tree.links.new(newbasegroup.outputs['metal Color'], shadergroup.inputs[newbasegroup.name + ' ' + 'metal Color'])\n except:\n writetoLog(\"Unable to link layer \" + newbasegroup.name) \n return mat\n\n\ndef createLayerNode(**mtl):\n writetoLog(\"Layer node: \" + str(mtl[\"Name\"])) \n if bpy.data.node_groups.get(mtl[\"Name\"]): return bpy.data.node_groups.get(mtl[\"Name\"])\n mat = (bpy.data.node_groups.get(mtl[\"Name\"]) or bpy.data.node_groups['_MaterialLayer'].copy())\n mat.name = mtl[\"Name\"]\n nodes = mat.nodes\n loadTextures(mtl[\"Textures\"], nodes, mat, nodes['Material Output'])\n #manually connect everything for now\n mapnodeout = mat.nodes['Mapping'].outputs['Vector']\n for node in mat.nodes:\n if node.type == 'TEX_IMAGE':\n imagenodein = node.inputs['Vector']\n imagenodecolorout = node.outputs['Color']\n imagenodealphaout = node.outputs['Alpha']\n mat.links.new(imagenodein, mapnodeout) \n if node.name in ['TexSlot12', 'Blendmap']:\n mat.links.new(imagenodecolorout, mat.nodes['Material Output'].inputs['blend Color'])\n elif node.name in ['TexSlot1', '_diff']:\n mat.links.new(imagenodecolorout, mat.nodes['Tint'].inputs['diff Color'])\n mat.links.new(imagenodealphaout, mat.nodes['Tint'].inputs['diff Alpha'])\n elif node.name in ['TexSlot2', '_ddna']:\n mat.links.new(imagenodecolorout, mat.nodes['Material Output'].inputs['ddna Color'])\n mat.links.new(imagenodealphaout, mat.nodes['Material Output'].inputs['ddna Alpha'])\n elif node.name in ['TexSlot4', '_spec']:\n mat.links.new(imagenodecolorout, mat.nodes['Material Output'].inputs['spec Color'])\n elif node.name in ['TexSlot8', 'Heightmap']:\n mat.links.new(imagenodecolorout, mat.nodes['Material Output'].inputs['disp Color']) \n \n mat['Filename'] = str(mtl['Name']) \n return mat\n\n\ndef createNoSurface(**mtl):\n writetoLog(\"Material: \" + mtl[\"Name\"])\n mat = (bpy.data.materials.get(mtl[\"Name\"]) or bpy.data.materials.new(mtl[\"Name\"]))\n #Viewport\n mat.blend_method = 'CLIP'\n mat.shadow_method = 'NONE'\n #Shader \n mat.use_nodes = True\n nodes = mat.node_tree.nodes\n nodes.clear()\n shaderout = nodes.new(type=\"ShaderNodeOutputMaterial\")\n shadernode = nodes.new('ShaderNodeBsdfTransparent')\n mat.node_tree.links.new(shadernode.outputs['BSDF'], shaderout.inputs['Surface'])\n return\n\n\ndef createUnknownSurface(**mtl):\n writetoLog(\"Material: \" + mtl[\"Name\"])\n mat = (bpy.data.materials.get(mtl[\"Name\"]) or bpy.data.materials.new(mtl[\"Name\"]))\n \n #Viewport material values\n setViewport(mat, mtl)\n \n mat.use_nodes = True\n nodes = mat.node_tree.nodes\n nodes.clear()\n shaderout = nodes.new(type=\"ShaderNodeOutputMaterial\")\n shadergroup = nodes.new(type=\"ShaderNodeGroup\")\n shadergroup.node_tree = (bpy.data.node_groups['_'+element.get('Shader')] or bpy.data.node_groups.new('_'+element.get('Shader')))\n\n return mat\n\ndef createAttribNode(mat, attrs, name):\n return\n\ndef loadTextures(textures, nodes, mat, shadergroup = None):\n imglist = []\n y = 0\n #writetoLog(\"Count of textures: \" + str(len(textures))) \n for tex in textures: \n writetoLog(\"Texture\" + str(tex.attrib) + \" \" + tex.get(\"File\"))\n path = importBaseDir + tex.get(\"File\")\n path.replace('.dds', '.tif')\n try:\n img = (bpy.data.images.get(tex.get(\"File\")) or bpy.data.images.load(path))\n except:\n writetoLog(\"Texture not found: \" + path, \"Error\")\n writetoList(path, \"Missing Textures\")\n continue \n if 'diff' in img.name:\n img.colorspace_settings.name = 'sRGB'\n else:\n img.colorspace_settings.name = 'sRGB'\n\n img.alpha_mode = 'PREMUL'\n texnode = (nodes.get(img.name) or nodes.new(type='ShaderNodeTexImage'))\n texnode.image = img\n texnode.label = img.name\n texnode.name = tex.get(\"Map\")\n \n texnode.location.x -= 300\n texnode.location.y = y\n y -= 330 \n \n if list(tex):\n texmod = tex[0]\n writetoLog(\"Texture mod found\", 'Debug')\n mapnode = nodes.new(type = 'ShaderNodeMapping')\n if (texmod.get('TileU') and texmod.get('TileV')):\n mapnode.inputs['Scale'].default_value = (float(texmod.get('TileU')), float(texmod.get('TileV')), 1) \n if mapnode.inputs['Scale'].default_value == [0,0,1]: mapnode.inputs['Scale'].default_value = [1,1,1]\n try: \n mat.node_tree.links.new(mapnode.outputs['Vector'], texnode.inputs['Vector'])\n except:\n pass \n mapnode.location = texnode.location\n mapnode.location.x -= 300\n #mat.node_tree.links.new(mapnode.outputs['Vector'], texnode.inputs['Vector'])\n\n if hasattr(mat, 'node_tree') == False: \n writetoLog(\"Shader node tree doesn't exist\")\n continue \n \n \n #link everything up\n if tex.get(\"Map\") in ['TexSlot1', 'Diffuse']:\n texnode.image.colorspace_settings.name = 'sRGB'\n try: \n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['diff Color'])\n mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['diff Alpha'])\n except:\n try:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['Primary diff Color'])\n mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['Primary diff Alpha'])\n except:\n writetoLog(\"Failed to link Diffuse Map\")\n elif tex.get(\"Map\") in ['TexSlot2', 'Bumpmap']: \n try: \n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['ddna Color'])\n #mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['ddna Alpha'])\n except:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['Primary ddna Color'])\n continue\n elif tex.get(\"Map\") in ['TexSlot3']:\n try: \n #mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['ddna Color'])\n mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['ddna Alpha'])\n except:\n try:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['Primary ddna Color'])\n mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['Primary ddna Alpha']) \n except:\n writetoLog(\"Failed to link DDNA Map\")\n elif tex.get(\"Map\") in ['TexSlot4', 'Specular']:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['spec Color'])\n elif tex.get(\"Map\") in ['TexSlot6']:\n try:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['detail Color'])\n mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['detail Alpha'])\n except:\n writetoLog(\"Failed to link detail Map\")\n continue \n elif tex.get(\"Map\") in ['TexSlot8', 'Heightmap']:\n try:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['disp Color'])\n except:\n pass \n elif tex.get(\"Map\") in ['TexSlot9', 'Decalmap']:\n try:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['decal Color'])\n mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['decal Alpha'])\n except:\n writetoLog(\"Failed to link Decal Map\")\n continue\n elif tex.get(\"Map\") in ['TexSlot11', 'WDA']:\n try:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['wda Color'])\n mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['wda Alpha'])\n except:\n writetoLog(\"Failed to link WDA Map\")\n continue\n elif tex.get(\"Map\") in ['TexSlot12', 'Blendmap']:\n try:\n mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['blend Color'])\n except:\n writetoLog(\"Failed to link Blend Map\")\n continue\n elif tex.get(\"Map\") in ['TexSlot13', 'Blendmap']:\n try:\n #mat.node_tree.links.new(texnode.outputs['Color'], shadergroup.inputs['detail Color'])\n #mat.node_tree.links.new(texnode.outputs['Alpha'], shadergroup.inputs['detail Alpha'])\n pass\n except:\n writetoLog(\"Failed to link detail Map\")\n continue \n \n return mat\n\n \ndef loadMaterials(materials): \n for mat in materials:\n path = importBaseDir + mat.get(\"Path\")\n writetoLog(\"Path: \" + path) \n createMaterialsFromMTL(path)\n\n\ndef setViewport(mat, mtl, trans=False):\n #Viewport material values\n mat.diffuse_color = make_tuple(mtl[\"Diffuse\"] + \",1\") \n #mat.specular_color = make_tuple(mtl[\"Specular\"],.5)\n #mat.roughness = 1-(float(mtl[\"Shininess\"].5)/255)\n if trans:\n mat.blend_method = 'BLEND'\n mat.shadow_method = 'NONE'\n mat.show_transparent_back = True\n mat.cycles.use_transparent_shadow = True\n mat.use_screen_refraction = True \n mat.refraction_depth = .0001\n else:\n mat.blend_method = 'OPAQUE'\n mat.shadow_method = 'CLIP'\n mat.cycles.use_transparent_shadow = False\n mat.show_transparent_back = False\n return\n\n \n\ndef writeAttribs(mat, mtl, attr):\n #if not mtl.get(attr): return False\n for name, value in mtl[attr].attrib.items():\n writetoLog(name + \" \" + value, 'Debug')\n mat[name] = value\n if mat.node_tree.nodes['Group'].inputs.get(name):\n mat.node_tree.nodes['Group'].inputs[name].default_value = float(value)\n return \n\ndef makeTuple(input):\n if input == None: return False\n output = input.rsplit(',')\n for i in range(0, len(output)): \n output[i] = float(str(output[i])[0:6])\n return output\n\n\ndef stripPath(path):\n path = path.replace('\\\\', '/')\n path = path.rsplit('/',1)[1]\n path = path.rsplit('.',1)[0]\n return path \n\n\ndef writetoLog(log_text, log_name = 'Output'):\n log_file = (bpy.data.texts.get(log_name) or bpy.data.texts.new(log_name))\n log_file.write('[' + str(datetime.now()) + '] ' + log_text + '\\n')\n #print('[' + str(datetime.now()) + '] ' + log_text + '\\n')\n\n\ndef writetoList(log_text, log_name = 'Output'):\n log_file = (bpy.data.texts.get(log_name) or bpy.data.texts.new(log_name))\n if log_text in log_file.as_string():\n return\n log_file.write(log_text)\n log_file.write('\\n')\n \n #a = split('\\n', log_file.as_string())\n #a.sort()\n #log_file.clear()\n #log_file.write(join('\\n', a))\n \n\n\nif __name__ == \"__main__\":\n #unregister()\n register()\n \n if bpy.data.texts.get(\"Materials\"):\n for matfile in bpy.data.texts.get(\"Materials\").lines:\n createMaterialsFromMTL(matfile.body)\n \n\n # test call\n bpy.ops.import_test.some_data('INVOKE_DEFAULT')\n\n","repo_name":"vmxeo/SCTools","sub_path":"BuildMaterials.py","file_name":"BuildMaterials.py","file_ext":"py","file_size_in_byte":28114,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"88"} +{"seq_id":"17004606126","text":"# -*- coding: UTF-8 -*-\n\n# 入力\nn = int(input())\na = list(map(int, input().split()))\nm = int(input())\nb = list(map(int, input().split()))\nans = None\nfor i in range(min(n, m)):\n if a[i] < b[i]:\n ans = 1\n elif a[i] > b[i]:\n ans = 0\n if not ans is None:\n break\n# 出力\n# Sample Input 3 のような場合\nif ans is None:\n if n < m:\n print(1)\n else:\n print(0)\nelse:\n print(ans)","repo_name":"nishiwakki/aoj","sub_path":"itp2/lexicographical_comparison.py","file_name":"lexicographical_comparison.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"73247451167","text":"import random\ndef knapsack(items, K):\n table = [[\"\"] * (K + 1) for _ in range(len(items))]\n table[0][0] = \"O\" # OMIT\n table[0][items[0]] = \"I\" # INCLUDE\n for i in range(1, len(items)):\n table[i][0] = \"O\"\n for k in range(1, K + 1):\n if k >= items[i] and table[i - 1][k - items[i]] != \"\": \n table[i][k] += \"I\"\n if table[i - 1][k] != \"\":\n table[i][k] += \"O\"\n return table\n\ndef algorithm(L):\n k = 0\n for i in range(L):\n x = random.randint(0,1000)/1000\n y = random.randint(0,1000)/1000\n if x**2 + y**2 < 1: k = k + 1\n return 4 * k / L\n\n#print(algorithm(10000))\nfor x in knapsack([5,2,3,7,1], 8):\n print(x)","repo_name":"jepuli124/DataSturcturesAndAlgorithms","sub_path":"week8/quiz1.py","file_name":"quiz1.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"39570973087","text":"#!/bin/python\nimport openpyxl\n\nexcel = openpyxl.load_workbook(filename=\"./MACH_emaili.xlsx\")\n\nsheet = excel.active\n\n\nimport json\ncache = {}\n\n\nwith open(\"./parsed-config.json\") as file: \n configs = json.load(file) \n for c in configs:\n machId = c[\"machId\"]\n timestamp = c[\"timestamp\"]\n model = c[\"config\"][\"system\"][\"vehicle\"][\"model\"]\n # print(machId, timestamp, model)\n if machId not in cache:\n cache[machId] = [machId, timestamp, model]\n elif timestamp > cache[machId][1]:\n cache[machId] = [machId, timestamp, model]\n\n\n for c in cache:\n mach = cache[c]\n # print(mach[0], mach[2])\n\nprint(\"Found\", len(cache), \"MACHs in configs\")\nprint(\"Found\", (sheet.max_row), \"rows in XLSX\")\n# ignore header\nfor i in range(2,sheet.max_row+1):\n machId = sheet.cell(row=i, column=4).value\n if machId in cache:\n sheet.cell(row=i, column=6).value = cache[machId][2]\n else:\n sheet.cell(row=i, column=6).value = \"Unknown\"\n\n\nexcel.save(filename=\"parsed.xlsx\")","repo_name":"tinesubic/python_projects","sub_path":"mach/model-id.py","file_name":"model-id.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"23640642380","text":"import pygame\r\nimport sys\r\nfrom pygame.sprite import Sprite\r\nfrom random import randint\r\nfrom pygame.sprite import Group\r\ndef run():\r\n pygame.init()\r\n screen=pygame.display.set_mode((500,500))\r\n\r\n class Bullet(Sprite):\r\n def __init__(self,screen):\r\n super(Bullet, self).__init__()\r\n self.screen = screen\r\n # 在(0,0)处创建一个表示子弹的矩形,再设置正确的位置\r\n self.rect = pygame.Rect(0, 0, 10,10)\r\n self.rect.x = randint(0,500)\r\n self.color = 60, 60, 60\r\n\r\n\r\n def update(self):\r\n \"\"\"向上移动子弹\"\"\"\r\n # 更新表示子弹位置的小数值\r\n self.rect.y -= 1\r\n\r\n def draw_bullet(self):\r\n \"\"\"在屏幕上绘制子弹\"\"\"\r\n pygame.draw.rect(self.screen, self.color, self.rect)\r\n\r\n bullets = Group()\r\n while True:\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n exit()\r\n screen.fill((200, 200, 200))\r\n\r\n\r\n pygame.display.flip()\r\n\r\n for bullet in bullets.sprites():\r\n bullet = Bullet()\r\n\r\n bullet.draw_bullet()\r\n\r\nrun()","repo_name":"jinglebelly/alien_invasion-py","sub_path":"alien_invasion/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"3283704158","text":"# Code by Tajrina Promela\n# Date 28th September 2022, 10:20 AM\n# Program to find the parity outlier in Python\n\n'''def find_outlier(integers):\n if integers[0] % 2 == 0 and integers[1] % 2 == 0:\n for i in integers[2::]:\n if i % 2 == 1:\n return i \n elif integers[0] % 2 == 1 and integers[1] % 2 == 1:\n for i in integers[2::]:\n if i % 2 == 0:\n return i\n elif integers[-1] % 2 == 0 and integers[-2] % 2 == 0:\n for i in integers[:-2]:\n if i % 2 == 1:\n return i\n elif integers[-1] % 2 == 1 and integers[-2] % 2 == 1:\n for i in integers[:-2]:\n if i % 2 == 0:\n return i\n else: \n for i in integers:\n if (i % 2 == 0 and i % 2 != 1) or (i % 2 == 1 and i % 2 != 0):\n return None \n\nlist = []\nlist = [161, 3, 1719, 19, 11, 13, -21]\nprint(find_outlier(list))'''\n\n\nintegers = []\n\ndef find_outlier(integers):\n evens = []\n odds = []\n for i in integers:\n if i % 2 > 0:\n odds.append(i)\n if i % 2 == 0:\n evens.append(i)\n if len(evens) > len(odds):\n return odds[0]\n else:\n return evens[0]\n\nprint(find_outlier([160, 3, 1719, 19, 11, 13, -21]))\nprint(find_outlier([2, 4, 0, 100, 4, 11, 2602, 36]))\n","repo_name":"TeeZeeeh/CodeWars-katas","sub_path":"6 Kyu Kata/find_parity_outlier.py","file_name":"find_parity_outlier.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"12884394929","text":"\"\"\"Defines Streamlit web app.\"\"\"\n\nimport io\nimport os\nimport copy\nimport math\nimport requests\nfrom os.path import join, dirname\n\nimport pandas as pd\nfrom PIL import Image\nfrom dotenv import load_dotenv\nfrom google.cloud import storage\nimport streamlit as st\nimport streamlit.components.v1 as components\n\n\ndef main():\n # Downloading env variables\n env_path = join(dirname(__file__),'.env')\n load_dotenv(dotenv_path=env_path)\n api_url = os.getenv('API_URL')\n\n # Download our catalogue\n if not os.path.exists(join(dirname(__file__),'catalog.csv')):\n storage_client = storage.Client('vincent-van-bot')\n bucket = storage_client.get_bucket('vincent-van-bot-bucket')\n blob = bucket.blob('data/catalog.csv')\n blob.download_to_filename(join(dirname(__file__),'catalog.csv'))\n\n # Open our catalogue + add first empty row to have empty pre-selection for a user\n db = pd.read_csv('catalog.csv', encoding='unicode_escape')\n db = db[db['FORM'] == 'painting']\n db['Title_author_date'] = db['TITLE'] + '; ' + db['AUTHOR'] + '; ' + db['DATE']\n empty_row = pd.DataFrame([[\" \"] * len(db.columns)], columns=db.columns)\n db = empty_row.append(db, ignore_index=True)\n\n # Rendering the page starts here\n st.set_page_config(page_title = 'Vincent van Bot', layout = 'wide')\n st.markdown(\"## Found something beautiful? Take a picture of it, upload it here, and enjoy the magic of art\")\n st.markdown(\"\")\n\n # Rendering the input zone\n with st.beta_expander(\"Input zone\", expanded = True):\n input_col, _, image_col = st.beta_columns([1, 0.05, 2])\n\n # Left column (user input)\n with input_col:\n st.markdown(\"### First:\")\n nsimilar = st.number_input(\"Choose amount of similar paintings you would like to see\", value=3, min_value=1, max_value=9)\n st.markdown(\"### Second:\")\n img = st.file_uploader(\"Upload an image\", type=['png', 'jpg', 'jpeg', 'heic'])\n st.markdown(\"#### or\")\n st.markdown(\"\")\n \n pic_name = st.selectbox(\"Tell us what is your favorite painting (and remove your downloaded pic beforehand, if any)\", db['Title_author_date'])\n \n # Right column (where user pic is displayed)\n with image_col:\n st.markdown(\"Your picture / favorite painting:\")\n img_location = st.empty()\n \n # If users downloade their own pic\n if img:\n img_copy = copy.deepcopy(img)\n img_resized = Image.open(img_copy)\n img_resized = resize_image(img_resized)\n img_location.image(img_resized)\n \n # If users enter their fav pic\n elif pic_name != \" \":\n url_to_fetch = db.loc[db['Title_author_date'] == pic_name, 'URL'].values[0].replace('html','art', 1).replace('html','jpg')\n user_painting_bytes = requests.get(url_to_fetch).content\n user_painting = Image.open(io.BytesIO(user_painting_bytes))\n img_resized = resize_image(user_painting)\n img_location.image(img_resized)\n else:\n pass\n \n \n # Just adding some spacing between input and output \n st.markdown(\"\")\n\n # Rendering output\n with st.beta_expander(\"You will probably like these paintings:\", expanded = (img is not None or pic_name != \" \")):\n # User pic\n if img:\n files = {\"file\": (img.name, img, img.type)}\n form_data = {\"nsimilar\" : nsimilar,\n \"rmfirst\": False}\n render_response(api_url, files, form_data)\n \n # User's fav painting\n elif pic_name != \" \":\n files = {\"file\": (\"user_pic.jpg\", user_painting_bytes, 'image/jpeg')}\n form_data = {\"nsimilar\" : nsimilar,\n \"rmfirst\" : True}\n render_response(api_url, files, form_data) \n else:\n pass\n\n\ndef render_response(api_url, file_to_send, form_data):\n \n response = requests.post(api_url, files=file_to_send, data=form_data).json()\n \n if response:\n st.markdown(\"\")\n \n # Rendering in a grid\n n_items = len(response)\n rows = math.ceil(n_items / 3)\n \n for n_row in range(rows):\n cols = st.beta_columns(3)\n # API stricture: {img_url, html_url, author, title, created, museum}\n for n_col in range(3 if n_row < rows - 1 else n_items - n_row * 3):\n response_item = response[3 * n_row + n_col]\n pic_received = Image.open(requests.get(response_item['img_url'], stream = True).raw)\n pic_resized = resize_image(pic_received)\n cols[n_col].markdown(f\"\"\"*Title:* [{response_item['title']}]({response_item['html_url']}) \n *Author:* {response_item['author']} \n *Created:* {response_item['created']} \n *Museum: * {response_item['museum']}\"\"\")\n cols[n_col].image(pic_resized)\n cols[n_col].markdown(\"\")\n else:\n st.markdown(\"#### Looks like we were not able to find similar paintings 😭\") \n \n\n# Custom image resize function\ndef resize_image(image, max_h = 500):\n pic_w, pic_h = image.size\n if pic_h <= max_h:\n return image\n \n ratio = pic_w / pic_h\n pic_h = max_h\n pic_w = int(pic_h * ratio)\n img_resized = image.resize((pic_w, pic_h))\n \n return img_resized\n\n\n# Run the script\nif __name__ == \"__main__\":\n main()\n \n\n \n \n \n \n\n \n\n \n","repo_name":"seve-26/vincentvanbot","sub_path":"frontend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"6189705912","text":"from apps.db.db import SessionLocal\nfrom fastapi import APIRouter, Body, Depends\nfrom fastapi.responses import JSONResponse\nfrom sqlalchemy.orm import Session\n\nfrom .models import Person\nfrom .shemas import PersonCreateSchema, PersonResponseSchema, PersonSchema\n\napp = APIRouter(prefix=\"/person\", tags=[\"person\"])\n\n# определяем зависимость\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n\n@app.get(\"/api/users\", response_model=PersonResponseSchema)\ndef get_people(db: Session = Depends(get_db)):\n # получаем пользователей\n person_results = db.query(Person).all()\n if person_results is None:\n return JSONResponse(status_code=404, content={\"message\": \"Пользователь не найден\"})\n person: list[PersonSchema] = [PersonSchema.from_orm(person) for person in person_results]\n return PersonResponseSchema(results=person)\n\n\n@app.get(\"/api/users/{id}\", response_model=PersonResponseSchema)\ndef get_person(id, db: Session = Depends(get_db)):\n # получаем пользователя по id\n person_results = db.query(Person).filter(Person.id == id).first()\n # если не найден, отправляем статусный код и сообщение об ошибке\n if person_results == None:\n return JSONResponse(status_code=404, content={\"message\": \"Пользователь не найден\"})\n # если пользователь найден, отправляем его\n person: list[PersonSchema] = [PersonSchema.from_orm(person_results)]\n return PersonResponseSchema(results=person)\n\n\n@app.post(\"/api/users\", response_model=PersonResponseSchema)\ndef create_person(person: PersonCreateSchema = Body(...), db: Session = Depends(get_db)):\n person_results = Person(name=person.name, age=person.age)\n db.add(person_results)\n db.commit()\n db.refresh(person_results)\n return PersonResponseSchema(results=[person_results])\n\n\n@app.put(\"/api/users\", response_model=PersonSchema)\ndef edit_person(id: int, date: PersonCreateSchema = Body(...), db: Session = Depends(get_db)):\n up_date = date.dict(exclude_unset=True)\n # получаем пользователя по id\n person = db.query(Person).filter(Person.id == id).first()\n # если не найден, отправляем статусный код и сообщение об ошибке\n if person == None:\n return JSONResponse(status_code=404, content={\"message\": \"Пользователь не найден\"})\n # если пользователь найден, изменяем его данные и отправляем обратно клиенту\n # person.age = data.age\n # person.name = data.name\n update_percon = date.dict(exclude_unset=True)\n for key, value in update_percon.items():\n setattr(person, key, value)\n db.commit() # комитим изменения\n db.refresh(person) # обновляем объект в базе данных.\n return person\n\n\n@app.delete(\"/api/users/{id}\")\ndef delete_person(id, db: Session = Depends(get_db)):\n # получаем пользователя по id\n person = db.query(Person).filter(Person.id == id).first()\n\n # если не найден, отправляем статусный код и сообщение об ошибке\n if person == None:\n return JSONResponse(status_code=404, content={\"message\": \"Пользователь не найден\"})\n\n # если пользователь найден, удаляем его\n db.delete(person) # удаляем объект\n db.commit() # сохраняем изменения\n return JSONResponse(status_code=200, content={\"message\": \"Пользователь удален\"})\n","repo_name":"Andriinef/trading_app","sub_path":"apps/person/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"27760299373","text":"# syslib\nimport os\nimport time\nfrom pathlib import Path\n\n# data processing\nimport pandas as pd\n\n# pyas\nfrom pyas.transcoder import Transcoder\nfrom pyas.prober import Prober\nfrom pyas.variant_generator import VariantGenerator\nfrom pyas.error import raise_exception\nfrom pyas.profiler import Profiler\n\nclass Experimenter:\n __instance = None\n transcoder = Transcoder.get_instance()\n prober = Prober.get_instance()\n variant_generator = VariantGenerator.get_instance()\n\n @staticmethod\n def get_instance():\n if Experimenter.__instance is None:\n Experimenter.__instance = Experimenter()\n return Experimenter.__instance\n\n\n def __init__(self):\n if Experimenter.__instance is not None:\n raise Exception(\"singleton violation, use get_instance\")\n\n\n def create_dir(self, output_dir, video_name, codec):\n output_dir = Path(output_dir)\n dir_path = output_dir / video_name / codec\n dir_path.mkdir(parents=True, exist_ok=True)\n return dir_path\n\n\n def do_experiment(self, input_dir='input', output_dir='output',\n codecs='libx264', containers='mp4', acceleration=False):\n input_dir = Path(input_dir)\n output_dir = Path(output_dir)\n if not input_dir.isdir():\n raise_exception(Experimenter.__name__, sys._getframe().f_code.co_name,\n \"input dir does not exist\")\n if not os.listdir(input_dir):\n raise_exception(Experimenter.__name__, sys._getframe().f_code.co_name,\n \"input dir is empty\")\n output_dir.mkdir(parents=True, exist_ok=True)\n\n input_videos = (input_video.name for input_video in input_dir.iterdir())\n buf_size = '8M'\n success_result = {}\n failed_result = {}\n # (videos)*(codecs)*(bitrates)*(resolutions) = total variants\n for input_video in input_videos:\n video_name_with_path = input_dir / input_video\n resolutions, zipped_brs = \\\n self.variant_generator.get_variant_list(video_name_with_path)\n\n for container in containers:\n for codec in codecs:\n video_name = input_video.split('.')[0]\n target_dir = self.create_dir(output_dir, video_name, codec)\n width, height, framerate, bitrate = \\\n self.prober.get_video_info(video_name_with_path)\n\n for resolution, zipped_br in zip(resolutions, zipped_brs):\n #i = len(zipped_br) # for the order of exported data\n for br_set in zipped_br:\n if(acceleration is True):\n output_fn = \"acc_\" + resolution + \"_\" + \"_\" \\\n + br_set['avg'] + \".\" + container\n else:\n output_fn = resolution + \"_\" + br_set['avg'] \\\n + \".\" + container\n #i -= 1\n\n target_output = target_dir / output_fn\n\n start_time = time.time()\n if(acceleration is True):\n self.transcoder.gpu_transcode(video_name_with_path, codec,\n container, br_set['avg'], br_set['min'], br_set['max'],\n buf_size, resolution, target_output)\n else:\n self.transcoder.sw_transcode(video_name_with_path, codec,\n container, br_set['avg'], br_set['min'], br_set['max'],\n buf_size, resolution, target_output)\n elapsed_time = time.time() - start_time\n\n result_key = video_name + \"_\" + codec + \"_\" + container + \"_\" + \\\n resolution + \"_\" + br_set['avg']\n\n if(elapsed_time > 1): # success\n success_result[result_key] = elapsed_time\n else:\n failed_result[result_key]\n\n return success_result, failed_result\n\n\n def export_result(self, res_dict, out_fn):\n if not bool(res_dict):\n raise_exception(Experimenter.__name__, sys._getframe().f_code.co_name,\n \"the given dictionary is empty\")\n repo_home = Path(os.environ['REPO_HOME'])\n output_dir = repo_home / 'output'\n output_dir.mkdir(parents=True, exist_ok=True)\n output_res = output_dir / out_fn\n keys = list(res_dict.keys())\n values = list(res_dict.values())\n data = pd.DataFrame({\n 'keys': keys,\n 'transcoding time': values\n })\n data.to_csv(output_res, index=False)\n\n\nif __name__ == \"__main__\":\n repo_home = Path(os.environ['REPO_HOME'])\n input_dir = repo_home / 'input'\n output_dir = repo_hom / 'output'\n\n experimenter = Experimenter.get_instance()\n codecs = ['libx264']\n containers = ['mp4']\n\n sw_sucess_res, sw_failed_res = \\\n experimenter.do_experiment(input_dir, output_dir, codecs, containers,\n acceleration=False)\n\n acc_success_res, acc_failed_res = \\\n experimenter.do_experiment(input_dir, output_dir, codecs, containers,\n acceleration=True)\n\n experimenter.export_result(sw_sucess_res, \"sw_res.csv\")\n experimenter.export_result(acc_success_res, \"acc_res.csv\")\n\n print(\"* * * * * * SW Transcoder * * * * * *\")\n print(\"\\tSuccess * * * * * * * * * * * * *\")\n keys = sw_sucess_res.keys()\n for key in keys:\n print(\"\\t\", key, \": {0:.3f}s\".format(sw_sucess_res[key]))\n print(\"\\tFailure * * * * * * * * * * * * *\")\n keys = sw_failed_res.keys()\n for key in keys:\n print(\"\\t\", key, \": {0:.3f}s\".format(sw_failed_res[key]))\n\n print(\"* * * * * * HW Transcoder * * * * * *\")\n print(\"\\tSuccess * * * * * * * * * * * * *\")\n keys = acc_success_res.keys()\n for key in keys:\n print(\"\\t\", key, \": {0:.3f}s\".format(acc_success_res[key]))\n print(\"\\tFailure * * * * * * * * * * * * *\")\n keys = acc_failed_res.keys()\n for key in keys:\n print(\"\\t\", key, \": {0:.3f}s\".format(acc_failed_res[key]))\n print(\"* * * * * * * * * * * * * * * * *\")\n\n prober = Prober.get_instance()\n videos = (input_videos for input_videos in os.listdir(input_dir))\n for video in videos:\n fn = video.split('.')[0]\n for codec in codecs:\n target_dir = output_dir / fn\n target_dir = target_dir / codec\n prober.print_video_info(target_dir)\n\n\n profiler = Profiler.get_instance()\n res, datapoints, columns, values = profiler.profile_cpu(30,\n experimenter.do_experiment,\n [input_dir, output_dir, codecs, containers, False])\n","repo_name":"jheo4/ffmpeg_streaming","sub_path":"python/experimenter.py","file_name":"experimenter.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"33504218635","text":"from sympy import nsimplify\nfrom sympy.core import *\nfrom sympy.printing.latex import LatexPrinter\nfrom sympy.core.function import _coeff_isneg\nimport numpy as np\n\nfrom generator.tree import create_tree, SYM, UNK\n\n\nclass MyLatexPrinter(LatexPrinter):\n \"\"\"Class for better-looking printing.\"\"\"\n\n add_settings = {'order': 'normal'}\n\n def __init__(self, settings={}, add_settings={}):\n super().__init__(settings)\n for k in add_settings:\n self.add_settings[k] = add_settings[k]\n\n def _print_Add(self, expr, order=None):\n terms = self._as_ordered_terms(expr)\n if self.add_settings['order'] == 'reversed':\n terms = terms[::-1]\n elif self.add_settings['order'] == 'shuffle' or len(terms) == 2:\n np.random.shuffle(terms)\n\n tex = \"\"\n for i, term in enumerate(terms):\n if i == 0:\n pass\n elif _coeff_isneg(term):\n tex += \" - \"\n term = -term\n else:\n tex += \" + \"\n term_tex = self._print(term)\n if self._needs_add_brackets(term):\n term_tex = r\"\\left(%s\\right)\" % term_tex\n tex += term_tex\n\n return tex\n\n\ndef print_my_latex(expr, centered=False):\n \"\"\"\n LaTeX print ot pdflatex\n :param centered: place formula on center\n :param expr: expression\n :return: LaTeX expression\n \"\"\"\n if centered:\n return '\\[' + MyLatexPrinter().doprint(expr) + '\\]'\n return '$ \\displaystyle{' + MyLatexPrinter().doprint(expr) + '} $'\n\n\ndef print_my_latex_html(expr, answer=None):\n \"\"\"\n LaTeX print for HTML usage (KaTEX)\n :param expr: expression\n :param answer: simplified expression\n :return:\n \"\"\"\n if answer:\n return MyLatexPrinter().doprint(Eq(expr, answer))\n else:\n return MyLatexPrinter().doprint(expr)\n\n\ndef make_fractions_pretty(expr, check=True):\n \"\"\"\n a/c + b/c -> (a+b)/c\n :param expr: expression\n :param check: debug option\n :return: transformed expression\n \"\"\"\n if type(expr) is not mul.Mul:\n return expr\n d = {}\n try:\n for memb in expr.as_coeff_mul()[1][-1].as_coeff_add()[1]:\n num, denom = memb.as_numer_denom()\n if denom in d:\n d[denom] += num\n else:\n d[denom] = num\n res = expr.as_coeff_mul()[0] * np.prod(expr.as_coeff_mul()[1][:-1]) * (\n expr.as_coeff_mul()[1][-1].as_coeff_add()[0] + np.sum([d[k] / k for k in d]))\n assert (res.simplify() == expr.simplify())\n return res\n except AssertionError:\n print('error while making pretty', res.simplify(), expr.simplify(), expr.as_coeff_mul()[1][-1],\n np.sum([d[k] / k for k in d]))\n return expr\n except:\n return expr\n\n\ndef remove_float_one(expr):\n \"\"\"\n Solve the 1.0 problem of SymPy (1*x != 1.0*x)\n :param expr: expression\n :return: transformed expression\n \"\"\"\n return remove_floats(create_tree(expr)).get_expr()\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except TypeError:\n return False\n\n\ndef remove_floats(tree):\n if tree.operation in (SYM, UNK):\n if is_number(tree.children[0]):\n if tree.children[0] == int(tree.children[0]):\n tree.children[0] = int(tree.children[0])\n elif len(str(tree.children[0]).rstrip('0')) > 5:\n tree.children[0] = nsimplify(tree.children[0])\n else:\n for i in range(len(tree.children)):\n remove_floats(tree.children[i])\n return tree\n\n\ndef make_pretty(expr, check=False):\n \"\"\"\n Combines all methods of making expression pretty\n :param expr: expression\n :param check: debug purposes\n :return: prettier expression\n \"\"\"\n\n p1 = make_fractions_pretty(expr, check)\n p2 = remove_float_one(p1)\n return p2\n\n\ndef print_tex_on_html(taskset, show_answers=False):\n \"\"\"\n Prints expressions on HTML page\n :param taskset: list of Tasks\n :param show_answers: show answers for tasks\n :return: HTML code\n \"\"\"\n texts = [task.get_condition() for task in taskset]\n tasks = [task.get_task() for task in taskset]\n answers = [task.get_answer() for task in taskset]\n s = \"\\n\".join(\n [\"{}
The expression was overcomplex

\".format(texts[i] + '\\n' if texts[i] else '', i)\n for i in range(len(tasks))])\n s += \"\"\"\"\"\"\n return s\n\n\ndef print_tex(taskset, num):\n \"\"\"\n Prints expressions on LaTeX page\n :param num: variant number\n :param taskset: list of Tasks\n :return: LaTeX code\n \"\"\"\n texts = [task.get_condition() for task in taskset]\n tasks = [task.get_task() for task in taskset]\n content = r\"\"\"\\documentclass{0}\n \\usepackage[utf8]{6}\n \\usepackage[T2A,T1]{7}\n \\usepackage[english,russian]{1}\n \\begin{2}\n \\begin{3} Вариант {4} \\end{3} \n \\begin{5}\n {8}\n \\end{5}\n \\end{2}\n \"\"\".format('{article}', '{babel}', '{document}', '{center}', num, '{enumerate}', '{inputenc}', '{fontenc}',\n '\\n'.join(['\\\\item ' + texts[i] + ' ' +\n (print_my_latex(tasks[i], centered=True) if tasks[i] != '' else '') for i in\n range(len(tasks))]))\n return content\n\n\ndef print_tex_answers(taskset):\n \"\"\"\n Prints answers on LaTeX document\n :param taskset: list of Tasks\n :return: LaTeX code\n \"\"\"\n answers = [[task.get_answer() for task in taskset[i]] for i in range(len(taskset))]\n content = r\"\"\"\\documentclass{0}\n \\usepackage[utf8]{1}\n \\usepackage[T2A,T1]{2}\n \\usepackage[english,russian]{3}\n \\begin{4}\n {5}\n \\end{4}\n \"\"\".format('{article}', '{inputenc}', '{fontenc}', '{babel}', '{document}',\n '\\n'.join([r\"\"\"\\begin{0} Вариант {1} \\end {0}\n\\begin{2}\n{3}\n\\end{2}\n\\clearpage\"\"\".format('{center}', i+1, '{enumerate}',\n '\\n'.join(['\\\\item ' + (answers[i][j] if (type(answers[i][j]) is str)\n else print_my_latex(answers[i][j]))\n for j in range(len(answers[i]))]))\n for i in range(len(taskset))]))\n\n return content\n\n\ndef print_tex_tasks(taskset):\n \"\"\"\n Prints tasks on single LaTeX document\n :param taskset: list of Tasks\n :return: LaTeX code\n \"\"\"\n texts = [[task.get_condition() for task in taskset[i]] for i in range(len(taskset))]\n tasks = [[task.get_task() for task in taskset[i]] for i in range(len(taskset))]\n content = r\"\"\"\\documentclass{0}\n \\usepackage[utf8]{1}\n \\usepackage[T2A,T1]{2}\n \\usepackage[english,russian]{3}\n \\begin{4}\n {5}\n \\end{4}\n \"\"\".format('{article}', '{inputenc}', '{fontenc}', '{babel}', '{document}',\n '\\n'.join([r\"\"\"\\begin{0} Вариант {1} \\end {0}\n\\begin{2}\n{3}\n\\end{2}\n\\clearpage\"\"\".format('{center}', i+1, '{enumerate}',\n '\\n'.join(['\\\\item ' + texts[i][j] + ' ' +\n (print_my_latex(tasks[i][j], centered=True) if tasks[i][j] != '' else '')\n for j in range(len(tasks[i]))]))\n for i in range(len(taskset))]))\n\n return content\n","repo_name":"top2know/TaskGenerator","sub_path":"printer/printing.py","file_name":"printing.py","file_ext":"py","file_size_in_byte":7779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"30457608027","text":"import requests\n\nAPI_BASE_URL = 'http://api.vgcollect.com/'\nAPI_KEY = 'abcdefg'\n\n\ndef search_items(args):\n r = requests.get('/'.join([API_BASE_URL, 'search', '+'.join(args),\n API_KEY]))\n if r.status_code == 200 and len(r.json()):\n return r.json()\n else:\n return None\n\n\ndef get_item(item_id):\n r = requests.get('/'.join([API_BASE_URL, 'items', item_id, API_KEY]))\n if r.status_code == 200 and len(r.json()):\n return r.json()['results']\n","repo_name":"numkem/pycollect-web","sub_path":"application/lib/vgcollect.py","file_name":"vgcollect.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"5477748997","text":"from django.urls import path\r\nfrom .views import LoginView, OTPView, LogoutView, UserView, UpdateView, AuthenticationCheck\r\n\r\nurlpatterns = [\r\n path('login', LoginView.as_view()),\r\n path('otp', OTPView.as_view()),\r\n path('logout', LogoutView.as_view()),\r\n path('viewprofile', UserView.as_view()),\r\n path('editprofile', UpdateView.as_view()),\r\n path('userauth', AuthenticationCheck.as_view())\r\n]\r\n","repo_name":"anamdc/G4Growth_backend","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"38300746879","text":"#!/usr/bin/env python3\nimport json\nimport datetime\nfrom functools import lru_cache\nimport requests\nfrom pandas.io.json import json_normalize\nimport matplotlib.pyplot as plt\nimport hashlib\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\npool = ThreadPool(4)\n\n\ndef parse_full_date(row):\n date = datetime.datetime.strptime(row[\"BreachDate\"], \"%Y-%m-%d\")\n return date\n\n\n@lru_cache()\ndef download_file(url,filename=None):\n if not filename:\n md5=hashlib.md5()\n md5.update(url.encode())\n filename='paste_'+md5.hexdigest()\n try:\n r = requests.get(url, allow_redirects=True, verify=False, timeout=5)\n if r.status_code==200:\n with open(filename, 'wb') as download_filename:\n download_filename.write(r.content)\n print(\"{} : Paste writen to File\".format(md5.hexdigest()))\n else:\n print(\"{} : File not found\".format(url))\n except:\n print(\"{} : could not download\".format(url))\n\n\n\n@lru_cache()\ndef pastebin_download(id):\n base_url_meta=\"https://scrape.pastebin.com/api_scrape_item_meta.php\"\n base_url_item=\"https://scrape.pastebin.com/api_scrape_item.php\"\n params={ \"i\" : id }\n try:\n # r = requests.get(url, allow_redirects=True, verify=False, timeout=5)\n r = requests.get(base_url_meta, params=params, allow_redirects=False, verify=False, timeout=5)\n if \"Error, we cannot find this paste\" in r.text:\n print(\"{} : Paste no longer available\".format(id))\n else:\n r = requests.get(base_url_item, params=params, allow_redirects=False, verify=False, timeout=5)\n with open('paste_'+id, 'wb') as download_filename:\n download_filename.write(r.content)\n print(\"{} : Paste writen to File\".format(id))\n except JSONDecodeError:\n print(\"no json response\")\n except Exception as e:\n print(type(e))\n\n\njson_file=open(\"json.json\",'r')\ndata=json.load(json_file)\nbreaches=data[\"BreachSearchResults\"]\npastes=data[\"PasteSearchResults\"]\n\nwd=json_normalize(data=breaches, record_path='Breaches', meta=['Alias','DomainName'] )\nwd[\"BreachDate\"] = wd.apply(parse_full_date, axis=1)\n\nfor user in pastes:\n for paste in user[\"Pastes\"]:\n # print(\"{}:{} = {}\".format(paste[\"Source\"],paste[\"Id\"],paste[\"Title\"]))\n if paste[\"Source\"] == \"Pastebin\":\n pass\n # pastebin_download(paste[\"Id\"])\n elif paste[\"Source\"] == \"AdHocUrl\":\n download_file(paste[\"Id\"])\n else:\n print(paste[\"Source\"])\n\n# results = pool.map(my_function, my_array)\n\n# plt.hist(wd[\"BreachDate\"])\n# plt.show()\n\n# plt.hist(wd[\"Name\"])\n# plt.xticks(rotation=\"vertical\")\n# plt.show()\n","repo_name":"tkessels/hibpparser","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"41406225585","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport time\nimport gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import GObject\n\nimport Pages.Accueil as Accueil\nimport Pages.ChoixProduit as ChoixProduit\nimport Pages.Administrateur as Admin\nimport Pages.Quantite as Quant\nimport Pages.Paiement as Paie\nimport Indisponible as Indispo\nimport GestionProduits as GProd\nimport GestionFIchier as GFichier\n\n\ndef new_page(nom):\n b=True\n while b:\n page=Accueil.PageAccueil()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=ChoixProduit.PageChoixProduit()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Admin.PageAdmin()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Admin.PageRechargement()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Admin.PageAdminProd()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Admin.PageAddProduct()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Quant.PageChoixQuantiteVrac()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Quant.PageChoixQuantiteNonVrac()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Paie.PageChoixPaiement()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Paie.PageMonnaie()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Paie.PageCarte()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Paie.PageAttenteVrac()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Paie.PageFinale()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n page=Indispo.PageIndisponible()\n if nom==page.page_name:\n dico_pages[nom]=page\n break\n b=False\n if not b:\n print(\"Page non trouvée\")\n\narduino=\"\"\n\ncentrale_de_paiement=\"\"\n\nwindow=\"\"\ntaille_x=0\ntaille_y=0\nbottom_size=150\nheader_size=80\nspacing=10\nmode_admin=True\n\nliste_pages=[\"Accueil\",\"Admin_p1\",\"Rechargement\",\"Admin Produit\",\"Ajouter un produit\",\"Choix du produit\",\"Choix Mode de Paiement\",\"Paiement par Pièces / Billets\",\"Paiement par Carte Bancaire\"\n ,\"Choix de la quantité non vrac\",\"Choix de la quantité vrac\",\"Servez-vous !\",\"Attente Produit Vrac\",\"Problème\"]\ndico_pages={}\nnew_page(liste_pages[0])\ndico_pagenb={}\nprevious_pages=[]\nnumber_pages=len(dico_pages)\ncurrent_page_nb=0\ntime_switch_page=0\ntime_begin_paiement=0\ntimeout_paiement=60\ntime_begin_produit=0\ntimeout_produit=240\ntime_session_begin=0\ntimeout_session=1200\ntimeout_inactive_session=300\naffiche_page_probleme=False\n\ndico_prod={}\nlist_button_prod_choix=[]\nlist_button_prod_admin1=[]\nlist_button_prod_admin2=[]\nlist_rapid=[]\n\nrapid_choice_quantity=[2.5,5,10]\nm_min=1.5\nm_max=25\n\norder=GProd.Commande()\nmasseactuelle=0\nmassefinale=0\ncredit=0\ndelivered=False\nfin=True\n\nmonnaiedispo=True\ncartedispo=True\n\ndef actualise_page(nomcurrent):\n return dico_pages[nomcurrent].actualise()\n \ndef set_current_page(nom):\n if type(nom)==str:\n if not(nom in dico_pages.keys()):\n new_page(nom)\n number_pages=len(dico_pages)\n for key in dico_pages.keys():\n if not (key in dico_pagenb.keys()):\n dico_pagenb[nom]=window.notebook.insert_page(dico_pages[nom],None,-1)\n window.actualiser_pages()\n window.notebook.set_current_page(dico_pagenb[nom])\n elif type(nom)==int:\n window.actualiser_pages()\n window.notebook.set_current_page(nom)\n \n\ndef delete_page(nom):\n if not(nom in previous_pages):\n dico_pages.pop(nom)\n dico_pagenb.pop(nom)\n number_pages=len(dico_pages)\n else:\n print(\"Page présente dans les pages précédentes\")\n\ndef get_size(axe,pourcentage):\n if (axe==0 or axe=='h'):\n return pourcentage*taille_y\n if (axe==1 or axe==\"l\"):\n return pourcentage*taille_x\n\ndef set_size():\n couple=window.get_size()\n if couple==(0,0):\n return True\n else:\n global taille_x\n global taille_y\n global spacing\n global bottom_size\n global header_size\n taille_x=couple[0]\n taille_y=couple[1]\n spacing=taille_y*0.05\n bottom_size=taille_y*0.2\n header_size=taille_y*0.1\n return False\n\ndef session_begin():\n time_session_begin=time.time()\n GObject.idle_add(check_session_timeout)\n\ndef check_session_timeout():\n #TODO a faire si page actuelle différente de accueil et si mode admin=False et si mode indispo =False\n if (time.time()-time_session_begin)>timeout_session:\n #TODO\n return False\n if (itme.time()-time_switch_page)>timeout_inactive_session:\n #TODO\n return False\n return True\n ","repo_name":"Henri2018/DistributeurRepo","sub_path":"Interface/v2/General.py","file_name":"General.py","file_ext":"py","file_size_in_byte":5099,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"10950801475","text":"class Solution(object):\n def trap(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n max_left=[]\n max_right=[]\n N=len(height)\n left = 0\n right = 0\n for i in range(N):\n left = max(left,height[i])\n max_left.append(left)\n for i in range(N-1,-1,-1):\n right = max(right,height[i])\n max_right.insert(0,right)\n ans = 0\n for i in range(N):\n ans += min(max_left[i],max_right[i])-height[i]\n return ans\n \n '''\n #brute force\n ans = 0\n N=len(height)\n for i in range(N):\n max_left,max_right = 0,0\n for j in range(i,-1,-1):\n max_left=max(max_left,height[j])\n for j in range(i,N):\n max_right=max(max_right,height[j])\n ans+=min(max_left,max_right)-height[i]\n return ans\n '''\n","repo_name":"liuspencersjtu/MyLeetCode","sub_path":"42-Trapping-Rain-Water.py","file_name":"42-Trapping-Rain-Water.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"3993923473","text":"# -*- coding: utf-8 -*-\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 datetime\nimport json\n\nimport flask\nimport flask_login\nimport pytz\nimport sqlalchemy as sa\nimport werkzeug.exceptions\n\nimport backend_common.auth\nimport backend_common.cache\nimport cli_common.log\nimport treestatus_api.config\nimport treestatus_api.models\n\nUNSET = object()\nTREE_SUMMARY_LOG_LIMIT = 5\n\nlog = cli_common.log.get_logger(__name__)\n\n\ndef _get(item, field, default=UNSET):\n return item.get(field, default)\n\n\ndef _is_unset(item, field):\n return item.get(field, UNSET) == UNSET\n\n\ndef _now():\n return datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)\n\n\ndef _notify_status_change(trees_changes, tags=[]):\n if flask.current_app.config.get('PULSE_TREESTATUS_ENABLE'):\n routing_key_pattern = 'tree/{0}/status_change'\n exchange = flask.current_app.config.get('PULSE_TREESTATUS_EXCHANGE')\n\n for tree_change in trees_changes:\n tree, status_from, status_to = tree_change\n\n payload = {'status_from': status_from,\n 'status_to': status_to,\n 'tree': tree.to_dict(),\n 'tags': tags}\n routing_key = routing_key_pattern.format(tree.tree)\n\n log.info(\n 'Sending pulse to {} for tree: {}'.format(\n exchange,\n tree.tree,\n ))\n\n try:\n flask.current_app.pulse.publish(exchange, routing_key, payload)\n except Exception as e:\n import traceback\n msg = 'Can\\'t send notification to pulse.'\n trace = traceback.format_exc()\n log.error('{0}\\nException:{1}\\nTraceback: {2}'.format(msg, e, trace)) # noqa\n\n\ndef _update_tree_status(session, tree, status=None, reason=None, tags=[],\n message_of_the_day=None):\n '''Update the given tree's status; note that this does not commit\n the session. Supply a tree object or name.\n '''\n if status is not None:\n tree.status = status\n if reason is not None:\n tree.reason = reason\n if message_of_the_day is not None:\n tree.message_of_the_day = message_of_the_day\n\n # log it if the reason or status have changed\n if status or reason:\n if status is None:\n status = 'no change'\n if reason is None:\n reason = 'no change'\n log = treestatus_api.models.Log(tree=tree.tree,\n when=_now(),\n who=flask_login.current_user.get_id(),\n status=status,\n reason=reason,\n tags=tags,\n )\n session.add(log)\n\n backend_common.cache.cache.delete_memoized(v0_get_tree, tree.tree)\n\n\n@backend_common.cache.cache.memoize()\ndef v0_get_tree(tree, format=None):\n t = flask.current_app.db.session.query(treestatus_api.models.Tree).get(tree)\n if not t:\n raise werkzeug.exceptions.NotFound('No such tree')\n return t.to_dict()\n\n\ndef get_trees():\n session = flask.current_app.db.session\n return dict(result={\n t.tree: t.to_dict()\n for t in session.query(treestatus_api.models.Tree)\n })\n\n\ndef get_trees2():\n return dict(result=[i for i in get_trees()['result'].values()])\n\n\n@backend_common.auth.auth.require_permissions([treestatus_api.config.SCOPE_TREES_UPDATE])\ndef update_trees(body):\n session = flask.current_app.db.session\n trees = [\n session.query(treestatus_api.models.Tree).get(t)\n for t in body['trees']\n ]\n if not all(trees):\n raise werkzeug.exceptions.NotFound('one or more trees not found')\n\n if _is_unset(body, 'tags') \\\n and _get(body, 'status') == 'closed':\n raise werkzeug.exceptions.BadRequest('tags are required when closing a tree')\n\n if not _is_unset(body, 'remember') and body['remember'] is True:\n if _is_unset(body, 'status') or _is_unset(body, 'reason'):\n raise werkzeug.exceptions.BadRequest(\n 'must specify status and reason to remember the change')\n # add a new stack entry with the new and existing states\n ch = treestatus_api.models.StatusChange(who=flask_login.current_user.get_id(),\n reason=body['reason'],\n when=_now(),\n status=body['status'],\n )\n for tree in trees:\n stt = treestatus_api.models.StatusChangeTree(tree=tree.tree,\n last_state=json.dumps({\n 'status': tree.status,\n 'reason': tree.reason\n }),\n )\n ch.trees.append(stt)\n session.add(ch)\n\n # update the trees as requested\n new_status = _get(body, 'status', None)\n new_reason = _get(body, 'reason', None)\n new_motd = _get(body, 'message_of_the_day', None)\n new_tags = _get(body, 'tags', [])\n\n trees_status_change = []\n\n for tree in trees:\n current_status = tree.status\n _update_tree_status(session, tree,\n status=new_status,\n reason=new_reason,\n message_of_the_day=new_motd,\n tags=new_tags,\n )\n if new_status and current_status != new_status:\n trees_status_change.append((tree, current_status, new_status))\n\n session.commit()\n\n _notify_status_change(trees_status_change, new_tags)\n\n return None, 204\n\n\n@backend_common.auth.auth.require_permissions([treestatus_api.config.SCOPE_TREES_CREATE])\ndef make_tree(tree, body):\n session = flask.current_app.db.session\n if body['tree'] != tree:\n raise werkzeug.exceptions.BadRequest('Tree names must match')\n t = treestatus_api.models.Tree(tree=tree,\n status=body['status'],\n reason=body['reason'],\n message_of_the_day=body['message_of_the_day'],\n )\n try:\n session.add(t)\n session.commit()\n except (sa.exc.IntegrityError, sa.exc.ProgrammingError):\n raise werkzeug.exceptions.BadRequest('tree already exists')\n return None, 204\n\n\ndef _kill_tree(tree):\n session = flask.current_app.db.session\n t = session.query(treestatus_api.models.Tree).get(tree)\n if not t:\n raise werkzeug.exceptions.NotFound('No such tree')\n session.delete(t)\n # delete from logs and change stack, too\n treestatus_api.models.Log.query.filter_by(tree=tree).delete()\n treestatus_api.models.StatusChangeTree.query.filter_by(tree=tree).delete()\n session.commit()\n backend_common.cache.cache.delete_memoized(v0_get_tree, tree)\n\n\n@backend_common.auth.auth.require_permissions([treestatus_api.config.SCOPE_TREES_DELETE])\ndef kill_tree(tree):\n _kill_tree(tree)\n return None, 204\n\n\n@backend_common.auth.auth.require_permissions([treestatus_api.config.SCOPE_TREES_DELETE])\ndef kill_trees(trees):\n for tree in trees:\n _kill_tree(tree)\n return None, 204\n\n\ndef get_logs(tree, all=0):\n session = flask.current_app.db.session\n\n # verify the tree exists first\n t = session.query(treestatus_api.models.Tree).get(tree)\n if not t:\n raise werkzeug.exceptions.NotFound('No such tree')\n\n logs = []\n q = session.query(treestatus_api.models.Log).filter_by(tree=tree)\n q = q.order_by(treestatus_api.models.Log.when.desc())\n if not all:\n q = q.limit(TREE_SUMMARY_LOG_LIMIT)\n\n logs = [l.to_dict() for l in q]\n return dict(result=logs)\n\n\ndef v0_get_trees(format):\n return get_trees()\n\n\ndef get_tree(tree):\n return dict(result=v0_get_tree(tree))\n\n\ndef get_stack():\n return dict(\n result=[\n i.to_dict()\n for i in treestatus_api.models.StatusChange.query.order_by(\n treestatus_api.models.StatusChange.when.desc())\n ]\n )\n\n\ndef _revert_change(id, revert=None):\n if revert not in (0, 1, None):\n raise werkzeug.exceptions.BadRequest('Unexpected value for `revert`')\n\n session = flask.current_app.db.session\n ch = session.query(treestatus_api.models.StatusChange).get(id)\n if not ch:\n raise werkzeug.exceptions.NotFound\n\n trees_status_change = []\n\n if revert:\n for chtree in ch.trees:\n\n last_state = json.loads(chtree.last_state)\n tree = treestatus_api.models.Tree.query.get(chtree.tree)\n if tree is None:\n # if there's no tree to update, don't worry about it\n pass\n\n current_status = tree.status\n _update_tree_status(session, tree,\n status=last_state['status'],\n reason=last_state['reason'],\n )\n\n if last_state['status'] and current_status != last_state['status']:\n trees_status_change.append(\n (tree, current_status, last_state['status']))\n\n session.delete(ch)\n session.commit()\n\n _notify_status_change(trees_status_change)\n\n return None, 204\n\n\n@backend_common.auth.auth.require_permissions([treestatus_api.config.SCOPE_REVERT_CHANGES])\ndef revert_change(id, revert=None):\n return _revert_change(id, revert)\n\n\n@backend_common.auth.auth.require_permissions([treestatus_api.config.SCOPE_REVERT_CHANGES])\ndef restore_change(id):\n return _revert_change(id, 1)\n\n\n@backend_common.auth.auth.require_permissions([treestatus_api.config.SCOPE_REVERT_CHANGES])\ndef discard_change(id):\n return _revert_change(id, 0)\n","repo_name":"clokep/release-services","sub_path":"src/treestatus/api/treestatus_api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":10226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"88"} +{"seq_id":"38447201379","text":"import iterm2\n\n\nasync def main(connection):\n # Define the configuration knobs:\n vl = \"variable_length_demo\"\n knobs = [iterm2.CheckboxKnob(\"Variable-Length Demo\", False, vl)]\n component = iterm2.StatusBarComponent(\n short_description=\"Status Bar Demo\",\n detailed_description=\"Tests script-provided status bar components\",\n knobs=knobs,\n exemplar=\"row x cols\",\n update_cadence=None,\n identifier=\"com.iterm2.example.status-bar-demo\",\n )\n\n # This function gets called whenever any of the paths named in defaults (below) changes\n # or its configuration changes.\n # References specify paths to external variables (like rows) and binds them to\n # arguments to the registered function (coro). When any of those variables' values\n # change the function gets called.\n @iterm2.StatusBarRPC\n async def coro(\n knobs, rows=iterm2.Reference(\"rows\"), cols=iterm2.Reference(\"columns\")\n ):\n if vl in knobs and knobs[vl]:\n return [\n \"This is an example of variable-length status bar components\",\n \"This is a demo of variable-length status bar components\",\n \"This demo status bar component has variable length\",\n \"Demonstrate variable-length status bar component\",\n \"Shows variable-length status bar component\",\n \"Shows variable-length text in status bar\",\n \"Variable-length text in status bar\",\n \"Variable-length text demo\",\n \"Var. length text demo\",\n \"It's getting tight\",\n ]\n return \"{}x{}\".format(rows, cols)\n\n # Register the component.\n await component.async_register(connection, coro)\n\n\niterm2.run_forever(main)","repo_name":"delphinus/dotfiles","sub_path":"iterm2/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"88"} +{"seq_id":"878152904","text":"import requests\nfrom flask import Flask\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n url = \"http://kuku:8080/\"\n x = requests.get(url)\n return \"maya ----==== \" + str(x.text) + \" ====----\"\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=8989)","repo_name":"teperwoman/merde","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"30198509989","text":"class PairEntry(object):\n \"\"\"Represent a single pair registered to play in a semi-final flight\n \"\"\"\n\n def __init__(self,a,b,req_ns=False,email=None):\n self.player_a = a\n self.player_b = b\n self.req_ns = req_ns\n self.email = email\n return\n\n\n\n","repo_name":"morrisjones/nap","sub_path":"nap/prereg/pairentry.py","file_name":"pairentry.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"8891918376","text":"import numpy as np\nfrom math import log\nimport sys\nimport opticalgrid as og\nimport getopt\nfrom time import perf_counter\nfrom datetime import timedelta\n\n# Parameters used in Section VII.C\nm1 = 40\nn2 = 4\nrhos = [2, 10, 50]\n\n# This boolean parameter determines whether or not we want to\n# use LGMRES or the Empirical approximation method.\nuse_lgmres = False\n\nreduced_st_sp = False\n\ntext_file = 'output.txt'\n\nmaxit = 10**6\n\nmu1 = 1\nmu2 = mu1\n\nif len(sys.argv) < 2:\n print(\"No output file specified, using the default \"+text_file)\nelse:\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"dr\",\n [\"detailed\", \"reduced\", \"m1=\", \"n2=\", \"rhos=\", \"rhommn=\",\n \"method=\", \"maxit=\", \"out=\"])\n except getopt.GetoptError as err:\n # print help information and exit:\n print(err) # will print something like \"option -a not recognized\"\n sys.exit(2)\n\n for o, a in opts:\n if o in (\"-d\", \"--detailed\"):\n reduced_st_sp = False\n elif o in (\"-r\", \"--reduced\"):\n reduced_st_sp = True\n elif o == \"--m1\":\n m1 = int(a)\n elif o == \"--n2\":\n n2 = int(a)\n elif o == \"--rhos\":\n rhos = [float(r) for r in a.split(',')]\n elif o == \"--rhommn\":\n rhos = a.split(',')\n rhomin = float(rhos[0])\n rhomax = float(rhos[1])\n numrhos = int(rhos[2])\n # One way to get evenly spaced x-axis in a logarithmic plot\n if numrhos is 2:\n rhos = [rhomin, rhomax]\n else:\n logmin = log(rhomin, 10)\n logmax = log(rhomax, 10)\n rhos = [10 ** (logmin + (logmax - logmin) * _i / (numrhos-1))\n for _i in range(numrhos)]\n elif o == \"--method\":\n if a == \"lgmres\":\n use_lgmres = True\n elif o == \"--maxit\":\n maxit = int(a)\n elif o == \"--out\":\n text_file = a\n\nprint(\"Output is written out to {}\".format(text_file))\n\ntic = perf_counter()\nstateSpace = og.StateSpace(m1, n2, reduced=reduced_st_sp)\ntoc = timedelta(seconds=perf_counter() - tic)\n\nf = open(text_file, 'a')\nprint(\"Generating the state space took {}\".format(toc), file=f)\nf.close()\n\nog.print_header(\n \"m1 = {}, n2 = {}\".format(m1, n2), text_file)\n\n#################################################\n# Actual computations\n#################################################\nf = open(text_file, 'a')\nprint(\"Using the precise chain\", file=f)\nprint(\"Using the {} approximation method\".format(\n 'LGMRES' if use_lgmres else\n 'iterative'), file=f)\nprint(\"Using the {} state space\".format(\n 'reduced' if reduced_st_sp else 'detailed'), file=f)\nprint(\"The state space has {} states\".format(stateSpace.dim), file=f)\nprint(\"Running simulations for rho = {}\".format(rhos), file=f)\nf.close()\n\nog.print_header(\"mu_1 = {}, mu_2 = {}\".format(mu1, mu2), text_file)\n\nif not reduced_st_sp:\n policies = ['RA', 'LF', 'MF']\n # policies = ['RA']\nelse:\n policies = ['R', 'LM']\n # policies = ['LM']\n\nBPs = [1, 2]\n\nheader = [\"rho\"]\nif use_lgmres:\n for pol in policies:\n base = pol+\":BP\"\n header.extend([base+\"1_SS\", base+\"2_SS\"])\nelse:\n for pol in policies:\n for bp in BPs:\n base = pol+\":BP\"+str(bp)\n header.extend([base, base+\"_d\", base+\"_p\", base+\"_n\"])\nf = open(text_file, 'a')\nprint(\",\".join(header), file=f)\nf.close()\n\nfor rho in rhos:\n lambda1 = rho * mu1\n lambda2 = rho * mu2\n total_dur = perf_counter()\n\n row = [str(rho)]\n if use_lgmres:\n for pol in policies:\n Q, normQ = stateSpace.construct_Q_matrix(\n mu1, mu2, lambda1, lambda2, pol=pol)\n bp1, bp2, dur_su2, dur_c = og.steady_state_numerical(\n Q, stateSpace.g_BP1, stateSpace.g_BP2, tol=1e-9,\n method='ILU-LGMRes')\n row.extend([str(bp1), str(bp2), str(dur_su), str(dur_c)])\n else:\n for pol in policies:\n apply_ltro, normQ = stateSpace.construct_ltro(\n mu1, mu2, lambda1, lambda2, pol=pol, impr=False)\n # Usually 2 / normQ, but we go for a safe margin\n delta = .9 * 2 / normQ\n phi = 1e-3\n for bp in BPs:\n if bp is 1:\n gamb = np.copy(stateSpace.g_BP1)\n elif bp is 2:\n gamb = np.copy(stateSpace.g_BP2)\n BP, act_phi, numi, dur_c = og.empirical(\n apply_ltro, gamb, delta, phi, 'P', maxit=maxit)\n row.extend([str(a) for a in\n [BP, delta, max(phi, act_phi), numi]])\n f = open(text_file, 'a')\n print(\",\".join(row), file=f)\n f.close()\n","repo_name":"alexander-e/iCTMC-flexi-grid-allocation-policies","sub_path":"OpticalGridPrecise.py","file_name":"OpticalGridPrecise.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"9078927181","text":"import argparse\nimport os\nimport sys\nimport time\nfrom itertools import chain\n\nfrom rdkit import Chem\nfrom rdkit import rdBase\nfrom rdkit.Chem import AllChem\nfrom tqdm import tqdm\n\nfrom pyflow.mol.mol_utils import valid_smiles\n\nrdBase.DisableLog('rdApp.warning')\n\n\"\"\"\nThis is a script which substitutes a given core molecule with the standard set\nof spacers and linkers developed by Biruk Abreha and Steven Lopez. The script\nwill perform substitutions on the core at position indicated using Uranium (U).\nThe conformers are written to PDB files in a folder named after the given\nmolecule name.\n\nUSAGE: python pymolgen.py molecule_name smiles\n\"\"\"\n\n# reaction SMILES for linkers\nlinker_rxns = {'unsubstituted': '[*:1]([U])>>[*:1]([H])',\n 'benzene': '[*:1]([U])>>[*:1](c2ccc([Y])cc2)',\n 'pyridine': '[*:1]([U])>>[*:1](c2ncc([Y])cc2)',\n 'pyrimidine': '[*:1]([U])>>[*:1](c2ncc([Y])cn2)',\n 'tetrazine': '[*:1]([U])>>[*:1](c2nnc([Y])nn2)',\n 'cyclopentadiene': '[*:1]([U])>>[*:1]C2=CC=C([Y])C2',\n 'pyrrole (2,5)': '[*:1]([U])>>[*:1](c2ccc([Y])N2)',\n 'pyrrole (2,4)': '[*:1]([U])>>[*:1](c2cc([Y])cN2)',\n 'pyrrole(N-methyl)': '[*:1]([U])>>[*:1](c2ccc([Y])N(C)2)',\n 'pyrrole(N-COH)': '[*:1]([U])>>[*:1](c2ccc([Y])N(C=O)2)',\n 'imidazole': '[*:1]([U])>>[*:1](c1cnc([Y])N1)',\n 'furan': '[*:1]([U])>>[*:1]c2ccc([Y])O2',\n 'thiophene': '[*:1]([U])>>[*:1]c2ccc([Y])S2',\n 'thiophene(dioxide)': '[*:1]([U])>>[*:1](c2ccc([Y])S(=O)(=O)2)',\n 'thiazole (2,5)': '[*:1]([U])>>[*:1](c2sc([Y])cn2)',\n 'thiazole (2,4)': '[*:1]([U])>>[*:1](c2scc([Y])n2)',\n 'oxazole (2,5)': '[*:1]([U])>>[*:1](c1ncc([Y])o1)',\n 'oxazole (2,4)': '[*:1]([U])>>[*:1](c1nc([Y])co1)',\n 'acetylene': '[*:1]([U])>>[*:1](C#C[Y])',\n 'ethylene(trans)': '[*:1]([U])>>[*:1]/C=C/[Y]',\n 'imine': '[*:1]([U])>>[*:1](C=N[Y])'}\n\n# placeholder for linker addition\nlinker_placeholder = '[*:1]([U])'\nlinker_placeholder_mol = Chem.MolFromSmarts(linker_placeholder)\n\n# reaction SMILES for terminal groups\nterminal_rxns = {'hydrogen': '[*:1]([Y])>>[*:1]([H])',\n 'hydroxy': '[*:1]([Y])>>[*:1]([OH])',\n 'trifluoromethyl': '[*:1]([Y])>>[*:1][C](F)(F)F',\n 'trifluoromethoxy': '[*:1]([Y])>>[*:1][O][C](F)(F)F',\n 'methyl': '[*:1]([Y])>>[*:1][C]',\n 'methoxy': '[*:1]([Y])>>[*:1][O][C]',\n 'nitro': '[*:1]([Y])>>[*:1][N+]([O-])=O',\n 'thiol': '[*:1]([Y])>>[*:1]([SH])',\n 'fluoro': '[*:1]([Y])>>[*:1][F]',\n 'chloro': '[*:1]([Y])>>[*:1][Cl]',\n 'cyano': '[*:1]([Y])>>[*:1]C#N'}\n\nterminal_placeholder = '[*:1]([Y])'\nterminal_placeholder_mol = Chem.MolFromSmarts(terminal_placeholder)\n\n\n# generates SMILES strings for the given core smiles\ndef generate_library(parent_smiles):\n parent_mol = Chem.MolFromSmiles(parent_smiles, sanitize=False)\n\n # append linkers to parent molecule to generate unsubstituted cores\n unsubstituted_cores = []\n place_holder_count = len(\n parent_mol.GetSubstructMatches(linker_placeholder_mol))\n for linker in linker_rxns:\n rxn = AllChem.ReactionFromSmarts(linker_rxns[linker])\n core = parent_mol\n for i in range(place_holder_count):\n new_mols = list(chain.from_iterable(rxn.RunReactants((core,))))\n core = new_mols[0]\n Chem.SanitizeMol(core)\n unsubstituted_cores.append(core)\n\n # append terminal groups\n all_mols = []\n for core in unsubstituted_cores:\n place_holder_count = len(\n core.GetSubstructMatches(terminal_placeholder_mol))\n if place_holder_count == 0:\n all_mols.append(core)\n continue\n for terminal in terminal_rxns:\n new_mol = core\n rxn = AllChem.ReactionFromSmarts(terminal_rxns[terminal])\n for i in range(place_holder_count):\n new_mols = list(\n chain.from_iterable(rxn.RunReactants((new_mol,))))\n new_mol = new_mols[0]\n Chem.Cleanup(new_mol)\n all_mols.append(Chem.MolFromSmiles(Chem.MolToSmiles(new_mol)))\n\n # canonicalize smiles to remove duplicates\n all_mols = [Chem.MolFromSmiles(smiles) for smiles in\n [Chem.MolToSmiles(mol) for mol in all_mols]]\n all_smiles = list(set([Chem.MolToSmiles(mol) for mol in all_mols]))\n\n return all_smiles\n\n\n# generates conformers for the given list of smiles strings\ndef generate_conformers(list_of_smiles, library_name, num_confs):\n # create directory to store molecules\n if not os.path.exists(library_name):\n os.makedirs(library_name)\n out_folder = os.path.abspath(library_name)\n\n # write list of SMILES to text file\n with open(os.path.join(out_folder, library_name + \".txt\"), \"w\") as f:\n for smiles in list_of_smiles:\n f.write(smiles + \"\\n\")\n\n start_time = time.time()\n\n good_conformers = 0\n no_rotatable_bonds = 0\n no_conformers = 0\n for smile in tqdm(list_of_smiles, desc=\"Generating conformers...\"):\n print(smile)\n mol = Chem.AddHs(Chem.MolFromSmiles(smile))\n\n num_rotatable_bonds = AllChem.CalcNumRotatableBonds(mol)\n\n if num_rotatable_bonds == 0:\n target_num_confs = 1\n else:\n target_num_confs = num_confs\n\n # generate conformers\n num_generated_confs = 0\n rms_threshold = 0.005\n\n while num_generated_confs < target_num_confs and rms_threshold > 0:\n confs = AllChem.EmbedMultipleConfs(mol,\n numConfs=target_num_confs,\n useRandomCoords=False,\n pruneRmsThresh=rms_threshold,\n numThreads=0,\n useBasicKnowledge=True,\n forceTol=0.001)\n num_generated_confs = len(confs)\n rms_threshold -= 0.001\n print(\"RMS threshold updated to: {}\".format(rms_threshold))\n\n # track number of successfully generated conformers\n if num_generated_confs == 0:\n no_conformers += 1\n continue\n elif num_generated_confs == 1:\n no_rotatable_bonds += 1\n else:\n good_conformers += target_num_confs\n\n # optimize conformers\n # opt = AllChem.UFFOptimizeMoleculeConfs(mol, numThreads=0, maxIters=1000, vdwThresh=10, ignoreInterfragInteractions=True)\n opt = AllChem.MMFFOptimizeMoleculeConfs(mol, numThreads=0, maxIters=10000, nonBondedThresh=10,\n ignoreInterfragInteractions=True)\n print(opt)\n\n # write conformers to PDB files\n inchi_key = Chem.InchiToInchiKey(Chem.MolToInchi(mol))\n for conf_id in range(num_generated_confs):\n conf_name = f\"{inchi_key}_{conf_id}.pdb\"\n pdb_file = os.path.join(out_folder, conf_name)\n pdb_writer = Chem.PDBWriter(pdb_file)\n pdb_writer.write(mol, conf_id)\n pdb_writer.close()\n\n # reporting\n time_taken = round(time.time() - start_time, 2)\n total_num_confs = no_rotatable_bonds + good_conformers\n\n return (total_num_confs, no_rotatable_bonds, no_conformers), time_taken\n\n\ndef main(args):\n # parse SMILES strings\n if args[\"smiles\"]:\n if \".\" in args[\"smiles\"][0]: # split multiple molecule SMILES string\n parent_smiles = args[\"smiles\"][0].split(\".\")\n else:\n parent_smiles = args[\"smiles\"]\n elif args[\"file\"]:\n parent_smiles = []\n with open(args[\"file\"], \"r\") as f:\n for line in f:\n smiles = line.strip()\n if \".\" in smiles:\n for s in smiles.split(\".\"):\n parent_smiles.append(s)\n else:\n parent_smiles.append(smiles)\n\n # validate the SMILES strings\n invalid_smiles = list(filter(lambda x: not valid_smiles(x), parent_smiles))\n if invalid_smiles:\n message = \"Error: the following {} SMILES strings are invalid:\\n\".format(\n len(invalid_smiles))\n for i in invalid_smiles:\n message += i + \"\\n\"\n print(message.strip())\n sys.exit()\n\n # generate library\n all_smiles = []\n for smiles in tqdm(parent_smiles, desc=\"Generating molecules...\"):\n new_smiles = generate_library(smiles)\n all_smiles += new_smiles\n\n # generate conformers\n report, time_taken = generate_conformers(all_smiles,\n args[\"name\"],\n args[\"num_confs\"])\n\n # reporting\n total_num_confs = report[0]\n no_rotatable_bonds = report[1]\n no_conformers = report[2]\n\n print(\"Successfully generated {} conformer(s) \\\n in {} seconds.\".format(total_num_confs, time_taken))\n if no_rotatable_bonds > 0:\n print(\"Generated one conformer for {} molecule(s) with no \\\n rotatable bonds.\".format(no_rotatable_bonds))\n if no_conformers > 0:\n print(\"Failed to generate conformers for {} \\\n molecule(s).\".format(no_conformers))\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description=\"Script for generating HTVS libraries for VERDE Materials DB.\")\n\n smiles_group = parser.add_mutually_exclusive_group(required=True)\n smiles_group.add_argument(\"-s\", \"--smiles\",\n type=str,\n nargs=1,\n help=\"the SMILES string of the core molecule\")\n smiles_group.add_argument(\"-f\", \"--file\",\n type=str,\n help=\"file with a SMILES string on each line\")\n\n parser.add_argument(\"-n\", \"--name\",\n type=str,\n required=True,\n help=\"the name of the library\")\n parser.add_argument(\"-c\", \"--num_confs\",\n type=int,\n default=4,\n help=\"number of conformers to generate for each unique molecule\")\n\n args = vars(parser.parse_args())\n\n return args\n\n\nif __name__ == \"__main__\":\n # parse arguments\n args = parse_args()\n\n # generate molecules\n main(args)\n","repo_name":"kuriba/PyFlow","sub_path":"pyflow/mol/pymolgen.py","file_name":"pymolgen.py","file_ext":"py","file_size_in_byte":10609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"42076794103","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport gymnasium as gym\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.tri import Triangulation\nimport time\nimport random\n\ndef get_return(state_list, gamma):\n \"\"\"\n @param statelist : list of (state, reward) pairs from current state until the terminal state\n @param gamma : discount factor\n @return : value of the state.\n Takes a list of (state, reward) pairs and computes the return\n \"\"\"\n\n counter = 0\n return_value = 0\n for visit in state_list:\n # (observation, action, reward) = visit. we just care about observation.\n _, _, reward = visit\n return_value += reward * np.power(gamma, counter)\n\n return return_value\n\n\ndef update_policy(episode_list,policy, average_state_action_return):\n for visit in episode_list:\n observation, _, _ = visit\n # update policy to be the one with the highest value for each state\n policy[observation] = np.argmax(average_state_action_return[:, observation])\n \n\n return policy\n \n\ndef plot_policies(policy_array, shape, epoch):\n # Example action dictionary mapping\n action_dict = {0: \"^\", 1: \">\", 2: \"v\", 3: \"<\"}\n # Convert numbers to arrows\n convert_to_arrow = np.vectorize(lambda x: action_dict[x])\n arrow_array = convert_to_arrow(policy_array)\n arrow_array[37:48] = \"\"\n\n # Reshape the array to (4, 12) and reverse the order of rows\n reshaped_arrows = np.flipud(arrow_array.reshape(4, 12))\n\n # Create a figure and subplot\n fig, ax = plt.subplots(figsize=(8, 2))\n\n # Set a gray background\n ax.imshow([[0]], cmap='Greys', extent=(0, 12, 0, 4))\n\n # Iterate over the reshaped array and plot the arrows in each cell\n for i in range(shape[0]):\n for j in range(shape[1]):\n arrow = reshaped_arrows[i, j]\n ax.text(j + 0.5, i + 0.5, arrow, fontsize=12, ha='center', va='center')\n rect = Rectangle((j, i), 1, 1, linewidth=1, edgecolor='black', facecolor='none')\n ax.add_patch(rect)\n\n ax.axis('off')\n plt.savefig(f\"plots/Optimal-policy-for-epoch-{epoch}.png\")\n plt.clf()\n\n\ndef triangulation_for_triheatmap(col, row):\n xv, yv = np.meshgrid(np.arange(-0.5, col), np.arange(-0.5, row)) # vertices of the little squares\n xc, yc = np.meshgrid(np.arange(0, col), np.arange(0, row)) # centers of the little squares\n x = np.concatenate([xv.ravel(), xc.ravel()])\n y = np.concatenate([yv.ravel(), yc.ravel()])\n cstart = (col + 1) * (row + 1) # indices of the centers\n\n trianglesN = [(i + j * (col + 1), i + 1 + j * (col + 1), cstart + i + j * col)\n for j in range(row) for i in range(col)]\n trianglesE = [(i + 1 + j * (col + 1), i + 1 + (j + 1) * (col + 1), cstart + i + j * col)\n for j in range(row) for i in range(col)]\n trianglesS = [(i + 1 + (j + 1) * (col + 1), i + (j + 1) * (col + 1), cstart + i + j * col)\n for j in range(row) for i in range(col)]\n trianglesW = [(i + (j + 1) * (col + 1), i + j * (col + 1), cstart + i + j * col)\n for j in range(row) for i in range(col)]\n return [Triangulation(x, y, triangles) for triangles in [trianglesN, trianglesE, trianglesS, trianglesW]]\n\n\n# your function\ndef normalize_list(non_normalized_list, shape=(4, 12)):\n non_normalized_list = non_normalized_list.copy()\n\n\n \"\"\"\n Takes a 2d list and normalizes it's values.\n \"\"\"\n max_value = np.amax(non_normalized_list)\n min_value = np.amin(non_normalized_list)\n \n for i in range(shape[0]):\n non_normalized_list[i] = (non_normalized_list[i] - min_value) / (max_value - min_value)\n return non_normalized_list\n\ndef plot_state_action(state_action_values, action_len, epoch):\n # normalize state action values\n state_action_values = normalize_list(state_action_values)\n col, row = 12, 4 # e.g. 5 columns, 4 rows\n values = state_action_values.reshape((action_len, col, row))\n triangul = triangulation_for_triheatmap(col, row)\n fig, ax = plt.subplots(figsize=(20, 16))\n imgs = [ax.tripcolor(t, val.ravel(), cmap='RdYlGn', vmin=0, vmax=1, ec='white')\n for t, val in zip(triangul, values)]\n \n # Add text annotations\n # for val, dir in zip(values, [(-1, 0), (0, 1), (1, 0), (0, -1)]):\n # for i in range(col):\n # for j in range(row):\n # for k in range(action_len):\n # v = round(values[k, i, j], 2)\n # ax.text(i + 0.3 * dir[1], j + 0.3 * dir[0], f'{v}', color='b', ha='center', va='center')\n \n\n ax.set_xticks(range(col))\n ax.set_yticks(range(row))\n ax.invert_yaxis()\n ax.margins(x=0, y=0)\n ax.set_aspect('equal', 'box') # square cells\n cbar = fig.colorbar(imgs[0], ax=ax)\n ax.axis('off')\n plt.savefig(f\"plots/normalized-q-values-heatmap-{epoch}.png\")\n plt.close()\n\ndef get_policy(state_action_values, state_len):\n policy = np.zeros(state_len, dtype=\"int64\")\n for i in range(state_len):\n policy[i] = np.argmax(state_action_values[:, i])\n \n return policy\n\ndef play_game(optimal_policy):\n env = gym.make('CliffWalking-v0', render_mode=\"human\")\n observation, info = env.reset(seed=42)\n num_actions = 0\n time.sleep(5)\n while True:\n action = int(optimal_policy[observation]) # take action based on policy.\n new_observation, _, terminated, truncated, _ = env.step(action)\n num_actions += 1\n while observation == new_observation:\n # take random action\n action = env.action_space.sample()\n new_observation, _, terminated, truncated, _ = env.step(action)\n num_actions += 1\n\n if num_actions > 50:\n print(f\"Terminated without optimal policy\\n\")\n observation, _ = env.reset()\n break\n\n if terminated or truncated:\n print(f\"Terminated normally\")\n observation, _ = env.reset()\n break\n \n observation = new_observation\n env.close()\n\n\ndef calculate_state_value_first_visit(episode_list, state_action_values, running_mean_matrix, gamma, action_len, state_len):\n # The episode is finished, now estimating the utilities\n counter = 0\n # Checkup to identify if it is the first visit to a state-action\n checkup_matrix = np.zeros((action_len,state_len))\n # For each visit in the episode\n for visit in episode_list:\n observation, action, _ = visit\n # If it is the first visit to the state-action, estimate the return\n if(checkup_matrix[action, observation] == 0):\n # get the return value of that episode\n return_value = get_return(episode_list[counter:], gamma)\n # Update the running mean matrix\n running_mean_matrix[action, observation] += 1\n # Update the state-action matrix\n state_action_values[action, observation] += return_value\n # update the check up matrix to visited\n checkup_matrix[action, observation] = 1\n\n counter += 1\n\n return state_action_values / running_mean_matrix\n\n\n\ndef simulate_explore_starts(env):\n # reset the environment.\n observation, info = env.reset()\n # simulate exploring starts\n for _ in range(50):\n action = np.random.randint(0, high=4, dtype='int32')\n new_observation, _, terminated, truncated, _ = env.step(action)\n observation = new_observation\n if terminated or truncated: \n observation, info = env.reset()\n\n return observation\n\ndef main():\n \"\"\"\n At each step, the agent records the reward obtained \n and saves a history of all states visited until reaching a terminal state.\n\n we call an episode the sequence of states from the starting state to the terminal state. \n \"\"\"\n\n ## discount factor\n gamma = 0.9\n ## initialize episodes\n tot_epoch = 1000000\n # e-greedy policy\n epsilon = 0.5\n # make the environment\n env = gym.make('CliffWalking-v0', render_mode=\"None\")\n state_len = env.nS\n action_len = env.nA\n # state-action values\n state_action_values = np.zeros((action_len, state_len))\n # random policy\n policy = np.random.randint(low=0, high=action_len, size=state_len, dtype=\"int64\")\n # init with low numbers to avoid division by zero.\n running_mean_matrix = np.full((action_len, state_len), 1.0e-10)\n ## for each episode:\n for epoch in range(tot_epoch + 1):\n # reset the environment.\n observation = simulate_explore_starts(env)\n # save episodes in a list\n episode_list = list()\n # a thousand random actions e-greedy\n for i in range(1000):\n action = policy[observation]\n # randomly take an action sometimes.\n if random.random() > epsilon: \n action = env.action_space.sample()\n\n new_observation, reward, terminated, truncated, info = env.step(action)\n #Append the visit in the episode list\n episode_list.append((observation, action, reward))\n observation = new_observation\n if terminated or truncated: break\n\n\n # episode ended, calculate the state-action values\n average_state_action_return = calculate_state_value_first_visit(episode_list, state_action_values, running_mean_matrix, gamma, action_len, state_len)\n # update the policy matrices\n policy = update_policy(episode_list, policy, average_state_action_return)\n # graph state action values.\n if epoch % (tot_epoch / 10) == 0:\n ## minimize state action values of terminal states\n \n print(\"****** Plot state action values ******\")\n plot_state_action(average_state_action_return, action_len, epoch)\n print(\"****** Plot policy ******\")\n plot_policies(policy, (4, 12), epoch)\n\n \n print(f\"Episode {epoch} done...\")\n \n # get the correct policy\n plot_policies(policy, (4, 12), 'final')\n\n\n # close environment\n env.close()\n\n\n ## play the game\n print(\"************ Playing game with optimal policies ************\")\n print(policy)\n play_game(policy)\n\nif __name__ == \"__main__\":\n main()","repo_name":"ngacho/CliffWalkingSolutions","sub_path":"model-free/monte-carlo/mc-active/active-mc.py","file_name":"active-mc.py","file_ext":"py","file_size_in_byte":10261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"24424570314","text":"import os\nimport requests\nfrom collections import defaultdict\nfrom terminaltables import DoubleTable\nfrom dotenv import load_dotenv\nfrom itertools import count\n\nLANGUAGES = [\n 'JavaScript', 'Java', 'Python', 'Ruby',\n 'PHP', 'C++', 'C#', 'C', 'Go', 'Scala',\n]\n\nAREA = 1 # Moscow\nPERIOD = 30 # Days\nPROFESSIONAL_ROLE = 96 # 'Programmer, developer'\nPER_PAGE = 100\nHH_API_URL = 'https://api.hh.ru/vacancies/'\n\nTOWN = 4 # Moscow\nPROFESSION = 48 # 'Programmer, developer'\nSJ_API_URL = 'https://api.superjob.ru/2.0/vacancies/'\n\n\ndef predict_rub_salary(vacancy):\n \"\"\"Returns average salary for a vacancy in RUB\"\"\"\n salary_from = vacancy.get('payment_from') or vacancy.get('salary', dict()).get('from')\n salary_to = vacancy.get('payment_to') or vacancy.get('salary', dict()).get('to')\n if salary_from and salary_to:\n predicted_salary = (salary_from + salary_to) / 2\n elif salary_from:\n predicted_salary = salary_from * 1.2\n elif salary_to:\n predicted_salary = salary_to * 0.8\n else:\n return 0, 0\n return predicted_salary, 1\n\n\ndef currency_check(vacancy):\n \"\"\"Checking a type of currency\"\"\"\n if not vacancy.get('salary'):\n return vacancy.get('currency') == 'rub'\n else:\n return vacancy['salary']['currency'] == 'RUR'\n\n\ndef get_average_salary(vacancies):\n \"\"\"Get average salary for a language in RUB\"\"\"\n average_salaries = []\n vacancies_processed = 0\n for vacancy in vacancies:\n if not currency_check(vacancy):\n continue\n salary, counter = predict_rub_salary(vacancy)\n average_salaries.append(salary)\n vacancies_processed += counter\n try:\n return int(sum(average_salaries) / len(average_salaries)), vacancies_processed\n except ZeroDivisionError:\n return 0, 0\n\n\ndef get_response(url, headers, params):\n \"\"\"Get a response from a service\"\"\"\n response = requests.get(url, headers=headers, params=params)\n response.raise_for_status()\n raw_vacancies = response.json()\n vacancies = raw_vacancies.get('items') or raw_vacancies.get('objects')\n vacancies_found = raw_vacancies.get('total') or raw_vacancies.get('found') or 0\n available_vacancies_check = raw_vacancies.get('pages') or raw_vacancies.get('more')\n return vacancies, available_vacancies_check, vacancies_found\n\n\ndef get_sj_vacancies(language, sj_api_key):\n \"\"\"Get all vacancies for a language from the SuperJob\"\"\"\n headers = {'X-Api-App-Id': sj_api_key}\n vacancies_roster = []\n params = {'catalogues': PROFESSION, 'keyword': language, 'town': TOWN,\n 'count': PER_PAGE}\n for page in count(0):\n params['page'] = page\n vacancies, available_vacancies_check, vacancies_found = get_response(SJ_API_URL, headers, params)\n vacancies_roster.extend(vacancies)\n if not available_vacancies_check:\n break\n return vacancies_roster, vacancies_found\n\n\ndef get_hh_vacancies(language):\n \"\"\"Get all vacancies for a language from the HeadHunter\"\"\"\n params = {'professional_role': PROFESSIONAL_ROLE, 'area': AREA, 'text': language, 'period': PERIOD,\n 'per_page': PER_PAGE}\n vacancies_roster = []\n for page in count(0):\n params['page'] = page\n vacancies, available_vacancies_check, vacancies_found = get_response(HH_API_URL, {}, params)\n vacancies_roster.extend(vacancies)\n if page >= available_vacancies_check - 1:\n break\n return vacancies_roster, vacancies_found\n\n\ndef get_hh_vacancies_stats():\n \"\"\"Get a stats for LANGUAGES\"\"\"\n vacancies_stats = defaultdict(dict)\n for language in LANGUAGES:\n vacancies, vacancies_found = get_hh_vacancies(language)\n average_salary, vacancies_processed = get_average_salary(vacancies)\n vacancies_stats[language]['vacancies_found'] = vacancies_found\n vacancies_stats[language]['vacancies_processed'] = vacancies_processed\n vacancies_stats[language]['average_salary'] = average_salary\n return dict(vacancies_stats)\n\n\ndef get_sj_vacancies_stats(sj_api_key):\n \"\"\"Get a stats for LANGUAGES\"\"\"\n vacancies_stats = defaultdict(dict)\n for language in LANGUAGES:\n vacancies, vacancies_found = get_sj_vacancies(language, sj_api_key)\n average_salary, vacancies_processed = get_average_salary(vacancies)\n vacancies_stats[language]['vacancies_found'] = vacancies_found\n vacancies_stats[language]['vacancies_processed'] = vacancies_processed\n vacancies_stats[language]['average_salary'] = average_salary\n return dict(vacancies_stats)\n\n\ndef main():\n env_path = os.path.join(os.path.dirname(__file__), '.env')\n if not os.path.exists(env_path):\n raise FileNotFoundError('.env does not exist')\n load_dotenv(env_path)\n sj_api_key = os.environ.get('SJ_SECRET_KEY')\n hh_vacancies_stats = get_hh_vacancies_stats()\n sj_vacancies_stats = get_sj_vacancies_stats(sj_api_key)\n for index, stats in enumerate((hh_vacancies_stats, sj_vacancies_stats)):\n table_title = ('+HeadHunter Moscow+', '+SuperJob Moscow+')[index]\n table_values = [['Язык программирования', 'Найдено вакансий', 'Обработано вакансий', 'Средняя зарплата'],\n *[[k, *v.values()] for k, v in stats.items()]]\n table_instance = DoubleTable(table_values, table_title)\n print(table_instance.table)\n print()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"EarlHikky/hh-sj-salary-api","sub_path":"get_stats.py","file_name":"get_stats.py","file_ext":"py","file_size_in_byte":5500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"599781002","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDifferent utility related to Git\n\"\"\"\n\nimport importlib\nimport os\nimport subprocess\nimport sys\nfrom typing import Optional, Tuple\n\n\nclass GitStatusException(RuntimeError):\n pass\n\n\ndef get_git_status(module: Optional[str] = None) -> Tuple[str, bool]:\n \"\"\"\n Returns last git commit hash and wether current git checkout is dirty or not.\n Use this function with Python packages that are managed locally under Git.\n\n Parameters\n ----------\n module : Optional[str], optional\n Python module name to check, by default None - this module is used\n\n Returns\n -------\n Tuple[str, bool]\n git commit hash, dirty or not\n \"\"\"\n\n if module is None:\n module = __name__\n else:\n importlib.import_module(module)\n\n curdir = os.getcwd()\n os.chdir(os.path.dirname(sys.modules[module].__file__))\n\n try:\n commit = subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode('utf-8').rstrip()\n dirty = subprocess.check_output(['git', 'status', '--porcelain']\n ).decode('utf-8').rstrip() != ''\n finally:\n os.chdir(curdir)\n\n return commit, dirty\n","repo_name":"areshytko/ml-toolset","sub_path":"mllab/submit/runbook/git_utils.py","file_name":"git_utils.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"73336466528","text":"# 7. Написати функцію, яка приймає на вхід список (через кому), підраховує кількість однакових елементів у ньомy і виводить результат.\n# Елементами списку можуть бути дані будь-яких типів.\n# Наприклад:\n# 1, 1, 'foo', [1, 2], True, 'foo', 1, [1, 2] ----> \"1 -> 3, foo -> 2, [1, 2] -> 2, True -> 1\"\n\ndef count_same_elements(input_list: list):\n\n while len(input_list) > 0:\n counter = 1\n value = input_list.pop(0)\n for j in input_list:\n if isinstance(value, (bool, int)):\n if value is j:\n input_list.remove(j)\n counter += 1\n else:\n if value == j:\n input_list.remove(j)\n counter += 1\n print(f'{value} -> {counter}')\n\n\nprint(count_same_elements([1, 1, 'foo', (1, 2),{'key': 'val'}, [1, 2], 'foo', 1, [1, 2], 'True', True, {1, 2}, (1, 2), {1, 2},{'key': 'val'}]))\n","repo_name":"miraelno/geekhub_homework","sub_path":"HT_6/task_7.py","file_name":"task_7.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"8550008686","text":"#!/usr/bin/env python\r\n# encoding: utf-8\r\n\r\nimport tweepy\r\nimport csv\r\nfrom datetime import date, datetime\r\nimport pandas as pd\r\n\r\n# Twitter API credentials\r\nconsumer_key = \"CRp24sWA9VRSVEBK7vLzDuezb\"\r\nconsumer_secret = \"AOEizPaqxxuY0zDqM3VNXTlSLmjArdR8xmC6VLysfymzhB4A1x\"\r\naccess_key = \"3176539950-H8T72Oqr4K8JtDrtDqnEffgElrEriIRckU9AZFZ\"\r\naccess_secret = \"h28tZlqQYqa9FufnPtoTcCq950zQahkESZUkJlHB3A6gh\"\r\n\r\n\r\ndef get_all_tweets(screen_name):\r\n # hint:Twitter only allows access to a users most recent 3240 tweets with this method\r\n\r\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\n auth.set_access_token(access_key, access_secret)\r\n api = tweepy.API(auth)\r\n\r\n # initialize a list to hold all the tweepy Tweets\r\n alltweets = []\r\n\r\n # make initial request for most recent tweets (200 is the maximum allowed count)\r\n new_tweets = api.user_timeline(screen_name=screen_name, count=200)\r\n\r\n # save most recent tweets\r\n alltweets.extend(new_tweets)\r\n\r\n # save the id of the oldest tweet less one\r\n oldest = alltweets[-1].id - 1\r\n\r\n # keep grabbing tweets until reach the date limit.\r\n while len(new_tweets) > 0:\r\n print(\"getting tweets before %s\" % (oldest))\r\n\r\n # all subsiquent requests use the max_id param to prevent duplicates\r\n new_tweets = api.user_timeline(screen_name=screen_name, count=200, max_id=oldest)\r\n\r\n # save most recent tweets\r\n alltweets.extend(new_tweets)\r\n\r\n # update the id of the oldest tweet\r\n oldest = alltweets[-1].id - 1\r\n\r\n print(\"...%s tweets downloaded so far\" % (len(alltweets)))\r\n\r\n loop_label = 0\r\n earliest_limit = datetime(2017, 1, 20, 0, 0, 0)\r\n\r\n for tweet in new_tweets:\r\n raw_date = tweet.created_at\r\n if raw_date < earliest_limit:\r\n loop_label = 1\r\n else:\r\n continue\r\n if loop_label == 1:\r\n break\r\n\r\n\r\n\r\n\r\n # transform the tweepy tweets into a 2D array that will populate the csv\r\n outtweets = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets]\r\n\r\n # write the csv, see to encoding method.\r\n with open('%s_tweets.csv' % screen_name, 'w', encoding='GB18030') as f:\r\n writer = csv.writer(f)\r\n writer.writerow([\"id\", \"created_at\", \"text\"])\r\n writer.writerows(outtweets)\r\n\r\n pass\r\n print(\"Done with %s\" % screen_name)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n # pass in the @username of the account you want to download\r\n get_all_tweets(\"elonmusk\")\r\n","repo_name":"pillumina/stock-prediction","sub_path":"tweets_user.py","file_name":"tweets_user.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"25286744772","text":"# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\nclass Solution(object):\n def merge(self, intervals):\n \"\"\"\n :type intervals: List[Interval]\n :rtype: List[Interval]\n \"\"\"\n res = []\n intervals.sort(key=lambda x: x.start)\n if(len(intervals) == 0):\n return intervals\n single = intervals[0];\n index = 1\n while(index < len(intervals)):\n if(single.end < intervals[index].start):\n res.append(single)\n single = intervals[index]\n else:\n single.end = max(single.end, intervals[index].end)\n index += 1\n res.append(single)\n return res\n\ns = Solution()\nres = s.merge([Interval(1,4),Interval(3,5),Interval(6,9),Interval(10,13)])\nprint(res)\n","repo_name":"meteora211/SelfLearning","sub_path":"Leetcode/Array/056.MergeIntervals/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"7849492344","text":"\"\"\"\n덩치\nhttps://www.acmicpc.net/problem/7568\n\"\"\"\nanswer = []\nn = int(input())\ndata = [list(map(int, input().split())) for _ in range(n)]\n\nfor i in range(n):\n count = 1\n for j in range(n):\n if i != j:\n if data[i][0] < data[j][0] and data[i][1] < data[j][1]:\n count += 1\n answer.append(count)\n\nprint(\" \".join(list(map(str, answer))))\n","repo_name":"Dev-Guccin/PythonAlgorithmStudy","sub_path":"2021/11주차 완전탐색/덩치/하현준.py","file_name":"하현준.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"74271471327","text":"# 混淆矩阵\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\n\ndef plot_confusion_matrix(matrix, label_info=None,\n xlabel='预测标签', ylabel='真实标签', title='混淆矩阵',\n font_size_num=20, font_size_xticks=13, font_size_yticks=13,\n save='a.png', show=True):\n \"\"\"绘制混淆矩阵\"\"\"\n assert matrix is not None\n assert label_info is not None\n num_classes = len(label_info)\n labels_name = label_info.keys()\n plt.imshow(matrix, cmap=plt.cm.Blues)\n plt.xticks(range(num_classes), labels_name,\n rotation=0, fontsize=font_size_xticks)\n plt.yticks(range(num_classes), labels_name, fontsize=font_size_yticks)\n plt.colorbar()\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n plt.title(title)\n thresh = matrix.max() / 2\n for x in range(num_classes):\n for y in range(num_classes):\n info = int(matrix[y, x])\n plt.text(x, y, info, fontsize=font_size_num,\n verticalalignment='center',\n horizontalalignment='center',\n color=\"white\" if info > thresh else \"black\")\n plt.tight_layout()\n if save:\n plt.savefig(save)\n if show:\n plt.show()\n\n\nif __name__ == '__main__':\n matrix = np.array([\n [40, 0, 0, 0, 1],\n [2, 13, 3, 1, 0],\n [5, 5, 4, 0, 2],\n [5, 1, 0, 4, 2],\n [1, 1, 0, 1, 6]\n ])\n plot_confusion_matrix(matrix,\n label_info={\n '神经源性瘤': 0,\n '骨髓瘤': 1,\n '骨巨细胞瘤': 2,\n '脊索瘤': 3,\n 'langerhans': 4\n }\n )\n","repo_name":"yang-ze-kang/PythonTools","sub_path":"PlotTools/matplotlib/confusion_matrix.py","file_name":"confusion_matrix.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"4544006887","text":"import github\n\nfrom . import Framework\n\n\nclass Issue134(Framework.BasicTestCase): # https://github.com/jacquev6/PyGithub/pull/134\n def testGetAuthorizationsFailsWhenAutenticatedThroughOAuth(self):\n g = github.Github(auth=self.oauth_token)\n with self.assertRaises(github.GithubException) as raisedexp:\n list(g.get_user().get_authorizations())\n self.assertEqual(raisedexp.exception.status, 404)\n\n def testGetAuthorizationsSucceedsWhenAutenticatedThroughLoginPassword(self):\n g = github.Github(auth=self.login)\n self.assertListKeyEqual(\n g.get_user().get_authorizations(),\n lambda a: a.note,\n [None, None, \"cligh\", None, None, \"GitHub Android App\"],\n )\n\n def testGetOAuthScopesFromHeader(self):\n g = github.Github(auth=self.oauth_token)\n self.assertEqual(g.oauth_scopes, None)\n g.get_user().name\n self.assertEqual(g.oauth_scopes, [\"repo\", \"user\", \"gist\"])\n","repo_name":"PyGithub/PyGithub","sub_path":"tests/Issue134.py","file_name":"Issue134.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":6382,"dataset":"github-code","pt":"88"} +{"seq_id":"603065427","text":"import sys\nimport numpy as np\nimport pandas as pd\nimport warnings\nfrom sklearn.metrics import f1_score\nfrom joblib import dump, load\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom mlxtend.classifier import EnsembleVoteClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nimport os\n# Add path to project source code to access dataset and model code\nproject_path = '/Users/ishareef7/Springboard/Capstone2'\nsys.path.append(project_path)\nfrom src.features import build_dataset\n\nX_train, X_test, y_train, y_test = build_dataset.get_processed_dataset()\nX_train2, X_test2, y_train2, y_test2 = build_dataset.get_processed_dataset(crnn_predictions=False)\n\n\ndef baseline_model():\n \"\"\"Method for creating an Ensemble voting classifier with 3 equally weighted models:\n -Logistic Regression (default parameters)\n -Gradient Boosting (preset parameters\n -SVC (default parameters)\"\"\"\n clf1 = LogisticRegression(random_state=7)\n clf2 = GradientBoostingClassifier(n_estimators=750, max_depth=5, max_features='sqrt', random_state=7)\n clf3 = SVC(random_state=7, probability=True)\n\n eclf = EnsembleVoteClassifier(clfs=[clf1, clf2, clf3], weights=[1, 1, 1],\n voting='soft', refit=True)\n return eclf\n\n\ndef stacked_model():\n \"\"\"Method for creating a Stacked Ensemble voting classifier with 3 equally weighted models:\n -Logistic Regression (default parameters)\n -Gradient Boosting (preset parameters\n -SVC (default parameters)\"\"\"\n clf1 = LogisticRegression(random_state=7)\n clf2 = GradientBoostingClassifier(n_estimators=750, max_depth=5, max_features='sqrt', random_state=7)\n clf3 = SVC(random_state=7, probability=True)\n eclf = EnsembleVoteClassifier(clfs=[clf1, clf2, clf3], weights=[1, 1, 1], voting='soft', refit=True)\n\n return eclf\n\n\ndef train_model(eclf, model):\n assert (model == 'baseline') or (model == 'stacked'), 'Invalid model argument, must be baseline or stacked'\n\n if model == 'baseline':\n print('Training Baseline Model')\n eclf = eclf.fit(X_train2, y_train2)\n else:\n print('Training Stacked Model')\n eclf = eclf.fit(X_train, y_train)\n return eclf\n\n\ndef get_f1_scores(train_predictions, test_predictions, model, f1_average = 'macro'):\n assert (f1_average == 'macro') or (f1_average is None), 'Invalid f1_average argument. Must be macro or ' \\\n 'None'\n assert (model == 'baseline') or (model == 'stacked'), 'Invalid model argument, must be baseline or stacked'\n\n if model == 'baseline':\n y_train_true = y_train2\n y_test_true = y_test2\n else:\n y_train_true = y_train\n y_test_true = y_test\n\n if f1_average == 'macro':\n train_f1 = f1_score(y_train_true, train_predictions, average = f1_average)\n test_f1 = f1_score(y_test_true, test_predictions, average=f1_average)\n\n f1_scores = pd.Series({'Training': train_f1, 'Testing': test_f1})\n f1_scores.name = model\n else:\n labels = ['International', 'Pop', 'Rock', 'Electronic', 'Folk', 'Hip-Hop', 'Experimental', 'Instrumental']\n train_f1 = f1_score(y_train_true, train_predictions, average=f1_average)\n test_f1 = f1_score(y_test_true, test_predictions, average=f1_average)\n\n f1_dict = {'Training': dict(zip(labels, train_f1)), 'Testing': dict(zip(labels, test_f1))}\n\n f1_scores = pd.DataFrame(f1_dict)\n\n return f1_scores\n\n\ndef predict_model(eclf, model):\n\n if model == 'baseline':\n train_predictions = eclf.predict(X_train2)\n test_predictions = eclf.predict(X_test2)\n\n else:\n train_predictions = eclf.predict(X_train)\n test_predictions = eclf.predict(X_test)\n\n return train_predictions, test_predictions\n\n\n\n","repo_name":"ishareef7/Springboard","sub_path":"Capstone2/src/models/ensemble_models.py","file_name":"ensemble_models.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"72987403807","text":"#!c:\\users\\chong\\documents\\code\\carousell-price-tracker-website\\virtual\\scripts\\python.exe\n# EASY-INSTALL-ENTRY-SCRIPT: 'autopep8==1.3.4','console_scripts','autopep8'\n__requires__ = 'autopep8==1.3.4'\nimport sys\nfrom pkg_resources import load_entry_point\n\nif __name__ == '__main__':\n sys.exit(\n load_entry_point('autopep8==1.3.4', 'console_scripts', 'autopep8')()\n )\n","repo_name":"chrispch/carousell-price-tracker-website-v2","sub_path":"virtual/Scripts/autopep8-script.py","file_name":"autopep8-script.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"17976147911","text":"print('\\033[0;33m=-\\033[0;33m' * 35)\nprint(' ')\nprint('\\033[1;33m CALCULADORA DE IMPOSTO DE RENDA\\033[1;33m')\nprint(' ')\nprint('\\033[0;33m=-\\033[0;33m' * 35)\nNumDepend = int(input(\"Informe o número de dependentes: \"))\nSalarioBruto = float(input(\"Informe o salário bruto: \"))\n\ndef calcular_aliquota_inss(salario_bruto):\n switch = {\n salario_bruto < 1045.00: 0.075,\n salario_bruto < 2089.60: 0.09,\n salario_bruto < 3134.40: 0.12,\n True: 0.14\n }\n return switch.get(True)\n\nAliquotaINSS = calcular_aliquota_inss(SalarioBruto)\n\nBaseCalculoIRPF = SalarioBruto - (AliquotaINSS * SalarioBruto) - (189.59 * NumDepend)\n\ndef calcular_aliquota_irpf(base_calculo):\n switch = {\n base_calculo < 1903.98: (0, 0),\n base_calculo < 2826.65: (0.075, 142.80),\n base_calculo < 3751.05: (0.15, 354.80),\n base_calculo < 4664.68: (0.225, 636.13),\n True: (0.275, 869.36)\n }\n return switch.get(True)\n\nAliquotaIRPF, parcela_dedutivel = calcular_aliquota_irpf(BaseCalculoIRPF)\nValorIRPF = (BaseCalculoIRPF * AliquotaIRPF) - parcela_dedutivel\n\nValorMensalIRPF = ValorIRPF / 12\n\nprint(f'Você pagará {ValorMensalIRPF:.2f} de Imposto de Renda por mês.')","repo_name":"joaovitorcidralv/Imposto-de-Renda","sub_path":"SeuIRPF.py","file_name":"SeuIRPF.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"21464354369","text":"import logging\nimport random\nimport uuid\nfrom datetime import date\nfrom typing import List, Tuple\n\nfrom django.db.models.fields import settings\nfrom elasticsearch_dsl import Search\n\nfrom connections.enums import ApartmentStateOfSale\nfrom users.models import Profile\n\n_logger = logging.getLogger(__name__)\n\n\ndef get_elastic_apartments_uuids() -> Tuple[uuid.UUID, List[uuid.UUID]]:\n s_obj = (\n Search(index=settings.APARTMENT_INDEX_NAME)\n .filter(\"term\", _language__keyword=\"fi\")\n .filter(\"term\", apartment_state_of_sale__keyword=ApartmentStateOfSale.FOR_SALE)\n )\n s_obj.execute()\n scan = s_obj.scan()\n uuids = []\n project_uuid = None\n for hit in scan:\n if not project_uuid:\n project_uuid = uuid.UUID(hit.project_uuid)\n if project_uuid == uuid.UUID(hit.project_uuid):\n uuids.append(uuid.UUID(hit.uuid))\n return project_uuid, uuids\n\n\ndef calculate_ssn_suffix(date_of_birth: date) -> str:\n date_string = date_of_birth.strftime(\"%d%m%y\")\n century_sign = \"+-A\"[date_of_birth.year // 100 - 18]\n individual_number = f\"{random.randint(3, 899):03d}\"\n index = int(date_string + individual_number) % 31\n control_character = \"0123456789ABCDEFHJKLMNPRSTUVWXY\"[index]\n ssn_suffix = century_sign + individual_number + control_character\n return ssn_suffix\n\n\ndef assert_profile_match_data(profile: Profile, data: dict):\n for field in (\n \"first_name\",\n \"last_name\",\n \"email\",\n \"phone_number\",\n \"street_address\",\n \"city\",\n \"postal_code\",\n \"contact_language\",\n \"ssn_suffix\",\n ):\n if field in data:\n assert data[field] == str(getattr(profile, field))\n","repo_name":"City-of-Helsinki/apartment-application-service","sub_path":"application_form/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"7537812730","text":"from collections import defaultdict\nfrom typing import Callable\n\nimport pandas as pd\nfrom spacy.tokens import Doc\n\nfrom .combo_basic import combo_basic\nfrom .term_extraction import TermExtraction\n\n\nclass TermExtractionPipeline:\n def __init__(\n self,\n func: Callable[..., pd.Series] = combo_basic,\n force: bool = True,\n *args,\n **kwargs\n ) -> None:\n self.func = func\n self.args = args\n self.kwargs = kwargs\n Doc.set_extension(self.func.__name__, default=None, force=force)\n\n def __call__(self, doc: Doc):\n term_counter = defaultdict(int)\n\n def add_to_counter(matcher, doc, i, matches) -> Doc:\n match_id, start, end = matches[i]\n candidate = str(doc[start:end])\n if TermExtraction.word_length(candidate) <= TermExtraction.MAX_WORD_LENGTH:\n term_counter[candidate] += 1\n\n for i, pattern in enumerate(TermExtraction.patterns):\n TermExtraction.matcher.add(\"term{}\".format(i), add_to_counter, pattern)\n matches = TermExtraction.matcher(doc)\n terms = self.func(\n str(doc),\n technical_counts=pd.Series(term_counter),\n *self.args,\n **self.kwargs\n )\n setattr(doc._, self.func.__name__, terms)\n return doc\n","repo_name":"krantirk/pyate","sub_path":"src/pyate/term_extraction_pipeline.py","file_name":"term_extraction_pipeline.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"36739737188","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport urllib\nfrom libplayer.http import HttpRetriever\n\ndef extractParameters(actions):\n ret = None\n if actions != '':\n actions = actions[1:]\n actionStrs = actions.split('&')\n for action in actionStrs:\n pair = action.split('=')\n if len(pair) > 1:\n if ret == None:\n ret = dict() \n ret[pair[0]] = pair[1]\n return ret\n\ndef getVideoLink(url):\n http = HttpRetriever()\n page = http.get(url)\n video = None\n \n # HR3 video\n ix = page.find('type=\"video/mp4')\n if ix != -1:\n ix = page.find('src=\"', ix)\n if ix != -1:\n ex = page.find('\"', ix + 5)\n video = page[ix+5:ex]\n return video\n # Check for Hessenschau link\n ix = page.find('videoUrl')\n if ix != -1:\n ex = page.find('\"', ix + 11)\n video = page[ix+11:ex]\n return video\n # Check for WDR video\n ix = page.find('//wdrmedien') \n if ix != -1:\n ex = page.find(chr(34), ix)\n if ex != -1:\n video = 'https:' + page[ix:ex]\n return video\n \n return video\n\ndef getShowId(context, index):\n return context['showList'][index]['id']\n\ndef getShowIndex(context, id):\n shows = len(context['showList'])\n for show in range(0, shows):\n if context['showList'][show]['id'] == id:\n return show\n return -1\n\ndef encode(string):\n return urllib.quote_plus(string)\n \ndef decode(string):\n return urllib.unquote_plus(string)\n\ndef isDebug(context):\n if 'debug' in context:\n return context['debug']\n else:\n return False\n\n","repo_name":"extramundane/hrmagplayer","sub_path":"libplayer/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"7412141312","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport nltk\nimport re\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nps=PorterStemmer()\ndf = pd.read_csv('train.csv',engine='python')\nclean_review=[]\nl=len(df.index)\nfor i in range(l):\n word=re.sub('[^a-zA-Z]',' ',df['tweet'][i])\n word=word.lower()\n word=word.split()\n word=[ps.stem(text) for text in word if not text in set(stopwords.words('english'))]\n word=' '.join(word)\n clean_review.append(word)\n\nfrom sklearn.feature_extraction.text import CountVectorizer\ncv=CountVectorizer(max_features=1000)\nX=cv.fit_transform(clean_review)\nX=X.toarray()\ny=df['label']\n\n\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y,random_state=0)\n\n\n\n\nfrom sklearn.linear_model import LogisticRegression\nlog_reg=LogisticRegression()\nfrom sklearn.neighbors import KNeighborsClassifier\nknn=KNeighborsClassifier()\n\nfrom sklearn.svm import SVC\nsvm=SVC()\nfrom sklearn.naive_bayes import GaussianNB\nnb = GaussianNB()\nfrom sklearn.tree import DecisionTreeClassifier\ndtf=DecisionTreeClassifier()\n\n\nlog_reg.fit(X_train,y_train)\nknn.fit(X_train,y_train)\nsvm.fit(X_train,y_train)\nnb.fit(X_train,y_train)\ndtf.fit(X_train,y_train)\n\nlog_reg.score(X_train,y_train)\nknn.score(X_train,y_train)\nsvm.score(X_train,y_train)\nnb.score(X_train,y_train)\ndtf.score(X_train,y_train)\n\n\nlog_reg.score(X_test,y_test)\nknn.score(X_test,y_test)\nsvm.score(X_test,y_test)\nnb.score(X_test,y_test)\ndtf.score(X_test,y_test)","repo_name":"Neeraj0001/Machine-Learning-Python-","sub_path":"NLP/tweet_NLP(Review).py","file_name":"tweet_NLP(Review).py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"42912929553","text":"\n# coding: utf-8\n\n# In[49]:\n\n\ndef load_nonces(partition):\n with open('./eval_data/data-nonces/n2v.definitional.dataset.'+partition+'.txt', 'r') as f:\n return zip(*((n, [w for w in d.split() if not w == '___']) for n, d in (line.split('\\t') for line in f if not line[0] in {'#', '\\n'})))\n\ndef load_nonce_vocab(vocab_f):\n with open(vocab_f) as f:\n return {line.split('\\t')[0]:line.split('\\t')[1] for line in f if not line.startswith('sentence total')}\n\ndef load_crw(crw_data):\n with open(crw_data) as f:\n return {line.split(' ')[0]:line.split(' ')[1] for line in f if not line.startswith('sentence total')}\n \n\n\n# In[44]:\n\n\n# [w for w in load_nonces('test')[0]]\nnonce2freq=load_nonce_vocab('../corpora/corpora/wiki.all.utf8.sent.split.tokenized.vocab')\nnonces=load_nonces('test')[0]\n\n\n# In[50]:\n\n\ncrws=load_crw('./eval_data/CRW/rarevocab.txt').keys()\n\n\n# In[55]:\n\n\nnonce_freq=[int(nonce2freq[nonce]) if nonce in nonce2freq else 0 for nonce in nonces ]\ncrws_freq=[int(nonce2freq[crw]) if crw in nonce2freq else 0 for crw in crws ]\n\n\n# In[67]:\n\n\n# len(crws_freq)\nimport numpy as np\nnp.mean(crws_freq)\n\n\n# In[66]:\n\n\nnp.mean(nonce_freq)\n\n","repo_name":"qianchu/rare_we","sub_path":"eval/nonce_crw_data_analysis.py","file_name":"nonce_crw_data_analysis.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"33114381249","text":"import sys\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\noldx = oldy = -1\r\n\r\ndef on_mouse(event, x, y, flags, param):\r\n global oldx, oldy\r\n\r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n oldx, oldy = x, y\r\n print('EVENT_LBUTTONDOWN: %d, %d' % (x, y))\r\n\r\n elif event == cv2.EVENT_LBUTTONUP:\r\n print('EVENT_LBUTTONUP: %d, %d' % (x, y))\r\n\r\n elif event == cv2.EVENT_MOUSEMOVE:\r\n if flags & cv2.EVENT_FLAG_LBUTTON:\r\n cv2.line(img, (oldx, oldy), (x, y), (0, 0, 255), 4, cv2.LINE_AA)\r\n cv2.imshow('image', img)\r\n oldx, oldy = x, y\r\n\r\n\r\nimg = np.ones((480, 640, 3), dtype=np.uint8) * 255\r\n\r\ncv2.namedWindow('image')\r\ncv2.setMouseCallback('image', on_mouse, img)\r\n\r\ncv2.imshow('image', img)\r\ncv2.waitKey()\r\n\r\ncv2.destroyAllWindows()\r\n","repo_name":"hajunho/repo_hajunho.slack.com","sub_path":"MAC/python3/tron_transmit/basic_examples/openCV/mouse.py","file_name":"mouse.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"9"} +{"seq_id":"1991514261","text":"import cv2\nfrom path import Path\n\nimport click\n\n\ndef class_divider(frame_list, class_dir, image_crop):\n crop_x, crop_y, crop_w, crop_h = [int(i) for i in image_crop.split(',')]\n\n anomaly_dir = class_dir / \"anomaly\"\n normal_dir = class_dir / \"normal\"\n anomaly_dir.makedirs_p()\n normal_dir.makedirs_p()\n\n frame_list = sorted(frame_list)\n anomaly_list = [0 for i in range(0, frame_list.__len__())]\n\n i = 0\n while i < frame_list.__len__():\n img = cv2.imread(frame_list[i])\n \n to_view = img.copy()\n cv2.rectangle(to_view,(crop_x,crop_y),(crop_x+crop_w,crop_y+crop_h),[0,0,255], 1)\n cv2.imshow(\"\", to_view)\n k = cv2.waitKey()\n\n if k == 83: # RightKey\n if i == frame_list.__len__() - 1:\n continue # gli faccio premere per forza 'a' o 'n'\n i = i + 1\n elif k == 81: # LeftKey\n i = i - 1 if i > 0 else 0\n elif k == ord('a'):\n anomaly_list[i] = 1\n i = i + 1\n elif k == ord('n'):\n anomaly_list[i] = 0\n i = i + 1\n elif k == ord('q'):\n print(\"exiting\")\n quit()\n\n print(f\"\\r{i / frame_list.__len__() * 100}\", end='')\n\n cv2.destroyAllWindows()\n print(\"writing frames\")\n\n for i, vi in enumerate(anomaly_list):\n nm = frame_list[i].name\n if vi == 0:\n nm = nm.replace(\".jpg\",\"_normal_.jpg\")\n frame_list[i].copy(normal_dir/nm)\n elif vi == 1:\n nm = nm.replace(\".jpg\", \"_anomaly_.jpg\")\n frame_list[i].copy(anomaly_dir / nm)\n\n print(\"exited\")\n\n\n@click.command()\n@click.option('--frames_path', type=str, required=True)\n@click.option('--image_crop', type=str, default='-1,-1,-1,-1')\ndef main(frames_path, image_crop):\n frames_path = Path(frames_path)\n frames_list = frames_path.files('*.jpg')\n class_dir = frames_path.parent\n\n class_divider(frames_list, class_dir, image_crop)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"berserkrambo/MagicoAnnotatore","sub_path":"anonano_divider.py","file_name":"anonano_divider.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"4050375699","text":"#!/usr/bin/env python3\n\nimport pandas\nimport numpy\n\n# Configure which columns need to be summed and collapsed when finding duplicate rows\ncolumns_to_sum = [\n 'Pageviews',\n 'Unique Pageviews',\n]\n\nnodes = pandas.read_csv('nodes.csv')\nga = pandas.read_csv('ga.csv')\n\n# Merge Drupal and GA data\nga = ga.merge(nodes, how='left', left_on='Page', right_on='Path')\nga = ga.merge(nodes, how='left', left_on='Page', right_on='Path - NID')\n\n# Collapse _x and _y columns via data presence heuristic\nfor column in nodes:\n ga[column] = ga[column+'_x'].combine(ga[column+'_y'], lambda a, b: a if isinstance(a, str) or not numpy.isnan(a) else b, None)\n ga = ga.drop(columns=[\n column + '_x',\n column + '_y'\n ])\n\n# Find rows in GA data that are actually duplicates\nfor index, row in nodes.iterrows():\n rows = ga.loc[ga['Path - NID'] == row['Path - NID']]\n # Look for rows in GA that are for /node/ but actually have an alias\n if rows.shape[0] > 1 and not row['Path'].startswith('/node/'):\n path_index = ga.loc[ga['Page'] == row['Path']].index\n node_index = ga.loc[ga['Page'] == row['Path - NID']].index\n total = rows.sum()\n # Insert the summed data for the to-sum columns\n for column in columns_to_sum:\n ga.loc[path_index, column] = total[column]\n # Drop the duplicate, unaliased row\n ga = ga.drop(node_index)\n\n# Dump to CSV\nga.to_csv('out.csv')\n","repo_name":"uoregon-libraries/ga-csv-merge","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"28980206250","text":"from test_framework.kubernetes import Kubernetes, KubernetesResource\nfrom test_framework.logging import log\nfrom typing import List, Any\nfrom kubernetes import client\nfrom tabulate import tabulate\nfrom datetime import datetime, timezone\nfrom pangu_lib.util import strfdelta\nimport json\nimport sys\nfrom pangu_lib.util import NodeType\nfrom pangu_lib.util import TX_EMITTER_TYPE\n\n\nclass PanguTestnet:\n name: str\n phase: str\n age: str\n namespace: KubernetesResource\n node_statefulsets: List[KubernetesResource]\n node_pods: List[KubernetesResource]\n num_validators: int\n num_validator_fullnodes: int\n num_public_fullnodes: int\n num_validators_active: int\n num_validator_fullnodes_active: int\n num_public_fullnodes_active: int\n\n\ndef get_testnet_main(testnet_name: str, output_format: str, kubernetes: Kubernetes):\n \"\"\"get testnet main\n\n Args:\n testnet_name (str): testnet name\n json_flag (bool): whether to print in json or not\n kubernetes (Kubernetes): kubernetes abstraction\n \"\"\"\n #\n # Get all testnets\n log.info(\"Getting testnet(s)...\")\n if testnet_name == \"\":\n print_all_testnets(output_format, kubernetes)\n else:\n print_singular_testnet(testnet_name, output_format, kubernetes)\n\n\ndef print_all_testnets(output_format: str, kubernetes: Kubernetes):\n \"\"\"print all testnets\n\n Args:\n kubernetes (Kubernetes): kubernetes abstraction\n output_format (str): whether to print in json or not\n \"\"\"\n namespaces: List[KubernetesResource] = kubernetes.get_resources(\n type=client.V1Namespace\n )\n pangu_testnets: List[PanguTestnet] = []\n for namespace in namespaces:\n if namespace.metadata.name.startswith(\"pangu-\"): # type: ignore\n pangu_testnet: PanguTestnet = get_singular_testnet(namespace.metadata.name, kubernetes) # type: ignore\n pangu_testnets.append(pangu_testnet) # type: ignore\n\n live_testnets: List[tuple[str, str, str, str]] = [\n (\n pangu_testnet.name,\n pangu_testnet.phase,\n pangu_testnet.age,\n str(\n pangu_testnet.num_validators_active\n + pangu_testnet.num_validator_fullnodes_active\n + pangu_testnet.num_public_fullnodes_active\n )\n + \"/\"\n + str(\n pangu_testnet.num_validators\n + pangu_testnet.num_validator_fullnodes\n + pangu_testnet.num_public_fullnodes\n ),\n )\n for pangu_testnet in pangu_testnets\n ]\n\n table_headers = [\"NAME\", \"STATUS\", \"AGE\", \"NODES\"]\n if output_format == \"json\":\n data = {\"headers\": table_headers, \"testnets\": live_testnets} # type: ignore\n print(json.dumps(data), file=sys.stdout)\n else:\n table = tabulate(live_testnets, headers=table_headers) # type: ignore\n print(\"\\n\\n\" + table + \"\\n\")\n\n\ndef print_singular_testnet(\n testnet_name: str, output_format: str, kubernetes: Kubernetes\n):\n \"\"\"print testnet info\n\n Args:\n testnet_name (str): testnet name\n output_format (str): whether to print in json or not\n kubernetes (Kubernetes): kubernetes abstraction\n \"\"\"\n try:\n pangu_testnet: PanguTestnet = get_singular_testnet(testnet_name, kubernetes)\n except Exception as e:\n raise e\n live_pods: Any = [\n (\n sts.metadata.name, # type: ignore\n sts.spec.replicas, # type: ignore\n strfdelta(datetime.now(timezone.utc) - sts.metadata.creation_timestamp), # type: ignore\n sts.metadata.labels[\"type\"], # type: ignore\n )\n for sts in pangu_testnet.node_statefulsets\n ]\n table_headers = [\"NAME\", \"READY\", \"AGE\", \"TYPE\"]\n if output_format == \"json\":\n data: Any = {\"headers\": table_headers, \"pods\": live_pods}\n print(json.dumps(data), file=sys.stdout)\n else:\n table = tabulate(live_pods, headers=table_headers)\n print(\"\\n\\n\" + table + \"\\n\")\n\n\ndef get_singular_testnet(testnet_name: str, kubernetes: Kubernetes) -> PanguTestnet:\n \"\"\"get singular testnet\n\n Args:\n testnet_name (str): testnet name\n kubernetes (Kubernetes): kubernetes abstraction\n\n Returns:\n PanguTestnet: PanguTestnet object\n \"\"\"\n #\n # Get all namespaces\n namespaces: List[KubernetesResource] = kubernetes.get_resources(\n type=client.V1Namespace\n )\n #\n # Find the namespace that corrisponds to the testnet name\n namespace: client.V1Namespace = None # type: ignore\n for curr_namespace in namespaces:\n if (\n curr_namespace.metadata is not None\n and curr_namespace.metadata.name == testnet_name\n ):\n namespace = curr_namespace # type: ignore\n break\n #\n # If the namespace does not exist, or the namespace does not start with \"pangu-\", then the testnet does not exist\n if not namespace or not testnet_name.startswith(\"pangu-\"):\n log.error(f\"Testnet {testnet_name} does not exist\")\n raise Exception(f\"Testnet {testnet_name} does not exist\")\n\n #\n # Create the PanguTestnet object\n pangu_testnet = PanguTestnet()\n pangu_testnet.namespace = namespace\n pangu_testnet.name = namespace.metadata.name # type: ignore\n pangu_testnet.phase = namespace.status.phase # type: ignore\n pangu_testnet.age = strfdelta(datetime.now(timezone.utc) - namespace.metadata.creation_timestamp) # type: ignore\n pangu_testnet.num_validators = 0\n pangu_testnet.num_validator_fullnodes = 0\n pangu_testnet.num_public_fullnodes = 0\n pangu_testnet.num_validators_active = 0\n pangu_testnet.num_validator_fullnodes_active = 0\n pangu_testnet.num_public_fullnodes_active = 0\n\n #\n # Get all statefulsets, and count the number of each type of node\n sts_objects: List[KubernetesResource] = kubernetes.get_resources(\n type=client.V1StatefulSet, namespace=testnet_name\n )\n for sts in sts_objects:\n type: str = sts.metadata.labels[\"type\"] # type: ignore\n if type == NodeType.VALIDATOR.value:\n pangu_testnet.num_validators += 1\n elif type == NodeType.VFN.value:\n pangu_testnet.num_validator_fullnodes += 1\n elif type == NodeType.PFN.value:\n pangu_testnet.num_public_fullnodes += 1\n elif type == TX_EMITTER_TYPE:\n pass\n else:\n raise Exception(f\"Unknown type: {type}\")\n pangu_testnet.node_statefulsets = sts_objects\n\n #\n # Get all pods, and count the number of each type of node\n pod_objects: List[KubernetesResource] = kubernetes.get_resources(\n type=client.V1Pod, namespace=testnet_name\n )\n for pod in pod_objects:\n # type : str = pod.spec.template.metadata.labels[\"type\"] #type: ignore\n type: str = pod.metadata.labels[\"type\"] # type: ignore\n if type == NodeType.VALIDATOR.value:\n pangu_testnet.num_validators_active += 1\n elif type == NodeType.VFN.value:\n pangu_testnet.num_validator_fullnodes_active += 1\n elif type == NodeType.PFN.value:\n pangu_testnet.num_public_fullnodes_active += 1\n elif type == TX_EMITTER_TYPE:\n pass\n else:\n raise Exception(f\"Unknown type: {type}\")\n pangu_testnet.node_pods = pod_objects\n\n return pangu_testnet\n","repo_name":"aptos-labs/aptos-core","sub_path":"testsuite/pangu_lib/testnet_commands/get_testnet.py","file_name":"get_testnet.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","stars":5526,"dataset":"github-code","pt":"9"} +{"seq_id":"15476425240","text":"import os, sys, torch, json, csv, argparse\nimport numpy as np\nimport pandas as pd \nfrom transformers import BertTokenizerFast\nfrom utils import *\n\n#############\n### PATHS ###\n#############\n\ndef data_dir(root_dir):\n return os.path.join(root_dir, 'yelp', 'data')\n\ndef token_length_path(data_dir):\n return os.path.join(preprocessing_dir(data_dir), f'token_counts.csv') \n\n############\n### LOAD ###\n############\n\ndef parse(path):\n with open(path, 'r') as f:\n for l in f:\n yield json.loads(l)\n\ndef load_business_data(data_dir):\n keys = ['business_id', 'city', 'state', 'categories']\n df = {}\n for k in keys:\n df[k] = []\n with open(os.path.join(raw_data_dir(data_dir), 'yelp_academic_dataset_business.json'), 'r') as f:\n for i, line in enumerate(f):\n data = json.loads(line)\n for k in keys:\n df[k].append(data[k])\n business_df = pd.DataFrame(df)\n return business_df\n\n#####################\n### PREPROCESSING ###\n#####################\n\ndef compute_token_length(data_dir):\n tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased')\n token_counts = []\n with open(os.path.join(raw_data_dir(data_dir), 'yelp_academic_dataset_review.json'), 'r') as f:\n text_list = []\n for i, line in enumerate(f):\n if i % 100000==0:\n print(f'Processed {i} reviews')\n data = json.loads(line)\n text = data['text']\n text_list.append(text)\n if len(text_list)==1024:\n tokens = tokenizer(text_list,\n padding='do_not_pad',\n truncation='do_not_truncate',\n return_token_type_ids=False,\n return_attention_mask=False,\n return_overflowing_tokens=False,\n return_special_tokens_mask=False,\n return_offsets_mapping=False,\n return_length=True)\n token_counts += tokens['length']\n text_list = []\n if len(text_list)>0:\n tokens = tokenizer(text_list,\n padding='do_not_pad',\n truncation='do_not_truncate',\n return_token_type_ids=False,\n return_attention_mask=False,\n return_overflowing_tokens=False,\n return_special_tokens_mask=False,\n return_offsets_mapping=False,\n return_length=True)\n token_counts += tokens['length']\n\n csv_path = token_length_path(data_dir) \n df = pd.DataFrame({'token_counts': token_counts})\n df.to_csv(csv_path, index=False, quoting=csv.QUOTE_NONNUMERIC)\n\ndef process_reviews(data_dir):\n # load pre-computed token length\n assert os.path.exists(token_length_path(data_dir)), 'pre-compute token length first'\n token_length = pd.read_csv(token_length_path(data_dir))['token_counts'].values\n\n # filter and export\n with open(reviews_path(data_dir), 'w') as f:\n fields = ['review_id', 'user_id', 'business_id', 'stars', 'useful', 'funny', 'cool', 'text', 'date']\n writer = csv.DictWriter(f, fields, quoting=csv.QUOTE_NONNUMERIC)\n\n for i, review in enumerate(parse(os.path.join(raw_data_dir(data_dir), 'yelp_academic_dataset_review.json'))):\n if 'text' not in review:\n continue\n if len(review['text'].strip())==0:\n continue\n if token_length[i] > 512:\n continue\n row = {}\n for field in fields:\n row[field] = review[field]\n writer.writerow(row)\n # compute year\n df = pd.read_csv(reviews_path(data_dir), names=fields,\n dtype={'review_id': str, 'user_id': str, 'business_id':str, 'stars': int, \n 'useful': int, 'funny': int, 'cool':int, 'text': str, 'date':str},\n keep_default_na=False, na_values=[])\n print(f'Before deduplication: {df.shape}')\n df['year'] = df['date'].apply(lambda x: int(x.split('-')[0]))\n # remove duplicates\n duplicated_within_user = df[['user_id','text']].duplicated()\n df_deduplicated_within_user = df[~duplicated_within_user]\n duplicated_text = df_deduplicated_within_user[df_deduplicated_within_user['text'].apply(lambda x: x.lower()).duplicated(keep=False)]['text']\n duplicated_text = set(duplicated_text.values)\n if len(duplicated_text)>0:\n print('Eliminating reviews with the following duplicate texts:')\n print('\\n'.join(list(duplicated_text)))\n print('')\n df['duplicate'] = ((df['text'].isin(duplicated_text)) | duplicated_within_user)\n df = df[~df['duplicate']]\n print(f'After deduplication: {df[~df[\"duplicate\"]].shape}')\n business_df = load_business_data(data_dir)\n df = pd.merge(df, business_df, on='business_id', how='left')\n df = df.drop(columns=['duplicate'])\n df.to_csv(reviews_path(data_dir), index=False, quoting=csv.QUOTE_NONNUMERIC)\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--root_dir', required=True)\n args = parser.parse_args()\n\n for dirpath in [splits_dir(data_dir(args.root_dir)), preprocessing_dir(data_dir(args.root_dir))]:\n if not os.path.exists(dirpath):\n os.mkdir(dirpath)\n \n compute_token_length(data_dir(args.root_dir))\n process_reviews(data_dir(args.root_dir))\n\nif __name__=='__main__':\n main() \n","repo_name":"p-lambda/wilds","sub_path":"dataset_preprocessing/amazon_yelp/process_yelp.py","file_name":"process_yelp.py","file_ext":"py","file_size_in_byte":5652,"program_lang":"python","lang":"en","doc_type":"code","stars":505,"dataset":"github-code","pt":"9"} +{"seq_id":"21703083824","text":"import json\n\nfrom flask import Flask, jsonify, request\nfrom werkzeug.exceptions import HTTPException\n\nfrom .services import deploy_contract\n\n\ndef create_app(test_config=None) -> Flask:\n app = Flask(__name__)\n\n @app.errorhandler(HTTPException)\n def handle_exception(e):\n \"\"\"Return JSON instead of HTML for HTTP errors.\"\"\"\n # start with the correct headers and status code from the error\n response = e.get_response()\n # replace the body with JSON\n response.data = json.dumps(\n {\n \"code\": e.code,\n \"name\": e.name,\n \"description\": e.description,\n }\n )\n response.content_type = \"application/json\"\n return response\n\n @app.route(\"/\", methods=[\"POST\"])\n def deploy():\n request_data = request.get_json()\n tx_hash = deploy_contract(request_data[\"rpc\"])\n return jsonify(txHash=tx_hash.hex())\n\n return app\n","repo_name":"Uxio0/safe-singleton-factory-deployer","sub_path":"flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"18608838620","text":"import asyncio\nimport datetime\nimport uuid\nfrom typing import List\n\nfrom fastapi import APIRouter\nfrom fastapi.requests import Request\nfrom pydantic import BaseModel\n\nfrom modules.authentication import requires_auth, to_short_jwt\nfrom modules.coins import ALL_COINS\nfrom modules.config import get_app_secret\nfrom modules.helpers import JSONResponse, NOT_FOUND, left_pad\nfrom modules.models import database, Invoice, Payment\nfrom modules.payments import parse_notes\nfrom views.api_models import InvoiceReadModel, PaymentAdminReadModel, InvoiceCreationModel\n\nrouter = APIRouter(prefix='/api')\n\n\nclass AdminInvoiceLookupResponse(BaseModel):\n invoice: InvoiceReadModel\n payments: List[PaymentAdminReadModel]\n\n\nclass AdminInvoiceCreationResponse(BaseModel):\n invoice: InvoiceReadModel\n\n\n\n@router.get('/admin/invoice/{invoice_id}', response_model=AdminInvoiceLookupResponse, tags=['admin', 'invoice'])\n@requires_auth\nasync def admin_invoice_get(invoice_id: int, _: Request):\n \"\"\"\n Returns an invoice and all associated payment details\n \"\"\"\n invoice, payments = await asyncio.gather(\n database.fetch_one((Invoice.select().where(Invoice.c.id == invoice_id))),\n database.fetch_all((Payment.select().where(Payment.c.invoice_id == invoice_id))),\n )\n if invoice is None:\n return NOT_FOUND\n\n invoice = dict(invoice)\n invoice['token'] = to_short_jwt({\"id\": invoice['id']})\n\n payments = [dict(x) for x in payments]\n for x in payments:\n x['amount_coin'] = ALL_COINS[x['symbol']].sats_to_coin(x['amount_sats'])\n x['paid_amount_coin'] = ALL_COINS[x['symbol']].sats_to_coin(x['paid_amount_sats'])\n return JSONResponse({\"invoice\": invoice, \"payments\": payments})\n\n\n\n@router.get('/admin/invoice', response_model=List[InvoiceReadModel], tags=['admin', 'invoice'])\n@requires_auth\nasync def admin_invoices( _: Request, limit: int = 50, offset: int = 0):\n \"\"\"\n Fetches a list of invoices\n \"\"\"\n invoices = await database.fetch_all(Invoice.select()\n .order_by(Invoice.c.creation_date.desc())\n .limit(limit)\n .offset(offset * limit))\n out = []\n for i, inv in enumerate(invoices):\n inv = dict(inv)\n inv['token'] = to_short_jwt({\"id\": inv['id']})\n out.append(inv)\n return JSONResponse(out)\n\n\nasync def create_invoice_from_payload(payload: InvoiceCreationModel):\n app_secret = get_app_secret()\n if not app_secret:\n raise KeyError(\"application secret not set, cannot issue partial invoice\")\n\n inv_uuid = str(uuid.uuid4())\n expiry = datetime.datetime.utcfromtimestamp(payload.expiry_date) if payload.expiry_date else None\n\n currency = payload.currency\n amount_cents = payload.amount_cents\n\n notes = parse_notes(payload.notes, payload.notes_html)\n contents = parse_notes(payload.contents, payload.contents_html)\n inv = dict(\n uuid=inv_uuid,\n amount_cents=amount_cents,\n currency=currency,\n creation_date=datetime.datetime.utcnow(),\n expiry_date=expiry,\n status=\"pending\",\n name=payload.name or None,\n customer_name=payload.customer_name or None,\n customer_email=payload.customer_email or None,\n notes=notes['raw'],\n notes_html=notes['html'],\n contents=contents['raw'],\n contents_html=contents['html'],\n )\n\n inv['id'] = await database.execute(Invoice.insert().values(**inv))\n if inv['name'] is None:\n inv['name'] = f\"#INV-{left_pad(str(inv['id']), 5)}\"\n await database.execute(Invoice.update().where(Invoice.c.id == inv['id'])\n .values(name=f\"#INV-{left_pad(str(inv['id']), 5)}\"))\n return inv\n\n\n\n@router.post('/admin/invoice', response_model=AdminInvoiceCreationResponse, tags=['admin', 'invoice'])\n@requires_auth\nasync def admin_invoice_creation(payload: InvoiceCreationModel, _: Request):\n \"\"\"\n Creates an Invoice\n \"\"\"\n inv = await create_invoice_from_payload(payload)\n inv['token'] = to_short_jwt({\"id\": inv['id']})\n return JSONResponse({\"invoice\": inv})\n","repo_name":"blakebjorn/tuxpay","sub_path":"views/admin_invoice.py","file_name":"admin_invoice.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"9"} +{"seq_id":"37772998652","text":"# 11.24 (Check Sudoku solution) Listing 11.7 checks whether a solution is valid by checking\n# whether every number is valid in the grid. Rewrite the program by checking\n# whether every row, column, and box has the numbers 1 to 9.\n\ndef main():\n # Read a Sudoku solution\n grid = readASolution()\n\n if isValidGrid(grid):\n print(\"Valid solution\")\n else:\n print(\"Invalid solution\")\n\n\n# Read a Sudoku solution from the console\ndef readASolution():\n print(\"Enter a Sudoku puzzle solution:\")\n grid = []\n for i in range(9):\n line = input().strip().split()\n grid.append([eval(x) for x in line])\n\n return grid\n\n\n# Check whether the fixed cells are valid in the grid\ndef isValidGrid(grid):\n # Check whether each row has numbers 1 to 9\n for i in range(9):\n if not is1To9(grid[i]): # If grid[i] does not contain 1 to 9\n return False\n\n # Check whether each column has numbers 1 to 9\n for j in range(9):\n # Obtain a column in the one-dimensional array\n column = []\n for i in range(9):\n column.append(grid[i][j])\n\n if not is1To9(column): # If column does not contain 1 to 9\n return False\n\n # Check whether each 3 by 3 box has numbers 1 to 9\n for i in range(3):\n for j in range(3):\n # The starting element in a small 3 by 3 box\n k = 0\n list = 9 * [0] # Get all number in the box to list\n for row in range(i * 3, i * 3 + 3):\n for column in range(j * 3, j * 3 + 3):\n list[k] = grid[row][column]\n k += 1\n\n if not is1To9(list): # If list does not contain 1 to 9\n return False\n\n return True # The fixed cells are valid\n\n\n# Check whether the one-dimensional array contains 1 to 9\ndef is1To9(list):\n # Make a copy of the array\n temp = [x for x in list]\n\n # Sort the array\n temp.sort()\n\n # Check if list contains 1, 2, 3, ..., 9\n return temp == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\nmain()\n","repo_name":"OmarAlmighty/Introduction-to-Programming-Using-Python-Liang-1st-edtion","sub_path":"CH11/EX11.24.py","file_name":"EX11.24.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"9"} +{"seq_id":"12413636889","text":"import os\nimport json\nfrom django.shortcuts import render\nfrom chatbot.models import chat_user,chatbot_style\nfrom chatbot_admin.models import datasetpreguntas,cliente,configuraciones\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response \nfrom rest_framework.decorators import api_view\nfrom chatbot.serializers import historialChatSerializers,personalizarChatSerializers,datasetSerializers\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ListTrainer\nfrom difflib import SequenceMatcher\nfrom pathlib import Path\nfrom django.conf import settings\nfrom rest_framework import status\nimport base64\nfrom django.http import HttpRequest,HttpResponse\nfrom django.core import serializers\nfrom os import remove\nimport time\nimport csv\n# import xlwt\nimport datetime\nimport json\nimport base64\n\n\n# Variable global para mantener el seguimiento de la conversación\nexpecting_dni = False\nBASE_DIR = Path(__file__).resolve().parent.parent\nruta_actual = os.path.join(BASE_DIR,'set_datos').replace('\\\\', '/')\n''' =============================================\n CHATTERBOT\n============================================= '''\nACCEPTANCE = 0.70 # Una validación de la respuesta mas óptima\n''' ======= CARGANDO ARCHIVOS JSON ==== '''\ndef conversation_directory(id_entrada):\n global CONVERSATION_SETTINGS\n CONVERSATION_SETTINGS = []\n with os.scandir(ruta_actual + '/empresa_'+id_entrada) as ficheros:\n ficheros = [fichero.name for fichero in ficheros if fichero.is_file()]\n ruta2 = ruta_actual + '/empresa_'+id_entrada+'/'\n for x in ficheros:\n CONVERSATION_SETTINGS.append(ruta2 + x)\n''' ======= INICIANDO LIBRERIA CHATTERBOT ==== '''\nglobal bot\nbot = {}\ndef initialize(id_user_create):\n global trainer\n nombre_bd = 'midbaprendida_'+id_user_create\n bot[id_user_create] = ChatBot(\n \"Chatbot INGyTAL\",\n read_only=True,\n statement_comparison_function=comparate_messages,\n response_selection_method=select_response,\n storage_adapter='chatterbot.storage.SQLStorageAdapter',\n database_uri='sqlite:///'+nombre_bd+'.sqlite3',\n logic_adapters=[\n {\n \"import_path\":\"chatterbot.logic.BestMatch\",\n }\n ])\n trainer = ListTrainer(bot[id_user_create])\n return nombre_bd\n''' ======= CARGAR CONVERSACIÓN ==== '''\ndef load_conversations():\n conversation = []\n for setting_file in CONVERSATION_SETTINGS:\n with open(setting_file, 'r',encoding=\"utf-8\") as file:\n configured_conversations = json.load(file)\n conversation.append(configured_conversations[\"conversations\"])\n file.close()\n return conversation\n''' ======= ENTRENAR ==== '''\ndef train_bot(conversations):\n global trainer\n for conversation in conversations:\n for message_response in conversation:\n messages = message_response[\"messages\"]\n response = message_response[\"response\"]\n print(\"Entrenando al robot para que responda:'\",messages, \"' con la respuesta'\",response,\"'\")\n for message in messages:\n trainer.train([message,response])\n''' ======= RESPONSABLE DE LA SELECCION LA MEJOR RESPUESTA PARA CADA PREGUNTA ==== '''\ndef comparate_messages(message, candidate_message):\n similarity = 0.0\n if message.text and candidate_message.text:\n message_text = message.text\n candidate_text = candidate_message.text\n similarity = SequenceMatcher(\n None,\n message_text.lower(),\n candidate_text.lower()\n )\n similarity = round(similarity.ratio(),2)\n if similarity < ACCEPTANCE:\n similarity = 0.0\n else:\n print(\"Mensaje de usuario:\",message_text,\", mensaje candidato:\",candidate_message,\", nível de confianza:\", similarity)\n return similarity\ndef select_response(message, list_response, storage=None):\n response = list_response[0]\n print(\"respuesta elegida:\", response)\n return response\n''' =============================================\n END CHATTERBOT\n============================================= '''\nusers__={} #contendra todos los usuarios conectados\nentradatmp2=''\n#A traves de funciones\ndef HomeChatbot(request):\n return render(request, 'chatbot/index.html')\n\n# ==== VALIDAR SESION CAPTURANDO NOMBRE ===\ndef getnombre(request):\n \n user = globals()['users__']\n user_alias = request.GET.get('user_alias')\n user_nom = request.GET.get('nomb')\n user[user_alias]={'nombre': user_nom.lower(), 'bol': 0, 'entradatmp': entradatmp2}\n return HttpResponse(status=201)\n\n# ==== EJECUTAR CONVERSACIÓN ===\ndef getchat(request):\n global expecting_dni\n\n if request.GET['msg']:\n entradatmp=''\n\n nombre_chat = request.GET.get('nombre_chat')\n email_chat = request.GET.get('email_chat')\n phone_chat = request.GET.get('phone_chat')\n usuario_chat = request.GET.get('user_chat')\n #nombre_chat getchat : anthony\n user_cook = request.GET.get('user_alias')\n #user_cook getchat : rynyshe55uhli6eaqei7k8b65bw5du\n session_cook = {user_cook: {'nombre':nombre_chat, 'bol': 0, 'entradatmp': ''}}\n user = session_cook\n #user getchat : {'rynyshe55uhli6eaqei7k8b65bw5du': {'nombre': 'olazabal', 'bol': 0, 'entradatmp': ''}}\n myuser = user[user_cook]\n #myuser getchat : {'nombre': 'olazabal', 'bol': 0, 'entradatmp': ''}\n bol=myuser['bol']\n #bol getchat : 0\n nombre_nombre=myuser['nombre']+'-'+user_cook\n nombre_sin_alias=myuser['nombre']\n #nombre_nombre getchat : olazabal-rynyshe55uhli6eaqei7k8b65bw5du\n entradatmp=myuser['entradatmp']\n #entradatmp getchat :\n chat_input = request.GET.get('msg')\n id_empresa_id = request.GET.get('id_empresa_id')\n id_user_create = request.GET.get('id_user_create')\n user_autenticate = request.GET.get('user_autenticate')\n initialize(id_user_create)\n if(bol==1):\n trainer = ListTrainer(bot[id_user_create])\n trainer.train([str(entradatmp),str(chat_input)])\n rpta2 = \"He aprendiendo que cuando digas -> {} <- debo responder -> {} <- \".format(str(entradatmp),str(chat_input))\n myuser['bol']=0\n user[user_cook] = myuser\n session_cook = user\n return HttpResponse(str(rpta2))\n else:\n if chat_input!='adios':\n \n # response2 = bot[id_user_create].get_response(chat_input)\n # response2 = str(response2).encode('utf-8')\n \n # decoded_string = base64.b64decode(response2)\n \n # print(\"clase2\")\n # response2 = json.loads(decoded_string)\n \n # response2 = reemplazar_texto(response2, \"usuario_chat\", usuario_chat)\n\n # print(response2)\n # response2 = json.dumps(response2)\n # response2 = base64.b64encode(response2.encode('utf-8')).decode()\n # print(\"clase codificada\")\n # print(response2)\n\n response = bot[id_user_create].get_response(chat_input)\n \n\n\n if response.confidence > 0.0:\n myuser['bol']= 0\n user[user_cook] = myuser\n session_cook = user\n # === GUARDA LAS SESSIONES EN LA BD\n n__ow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n print(\"FECHA DE REGISTRO2 :\",n__ow)\n user_chat = chat_user(\n pregunta=chat_input,\n key_session_alias=user_cook,\n respuesta=response,\n nombre_persona=nombre_nombre,\n nombre_persona_sin_alias=nombre_sin_alias,\n fecha_historial_chat=n__ow,\n estado_chat='novisto',\n email_persona=email_chat,\n telefono_persona=phone_chat,\n cliente_empresa_id=cliente.objects.get(pk=id_empresa_id))\n user_chat.save()\n\n return HttpResponse(str(response)) \n else:\n # if user_autenticate == 'True':\n # # rpta1 = \"Discula no entendí lo que quisiste decir, aún estoy aprendiendo \\n ¿Qué debería haber dicho?\"\n # cda = '{\"respuesta_tipo\": [{\"tipo\": \"texto\",\"rpta\": [{\"respueta_sl_texto\": \"Discula no entendí lo que quisiste decir, aún estoy aprendiendo ¿Qué debería haber dicho?\"}]}]}'\n # rpta1 = base64.b64encode(cda.encode('utf-8'))\n # print('rptaaaaaaaaaaaaaaaaaaaa: ',rpta1)\n # myuser['bol']=1\n # myuser['entradatmp']=chat_input\n # user[user_cook] = myuser\n # session_cook = user\n # else:\n # rpta1 = 'Disculpa no te entendí!'\n cda = '{\"respuesta_tipo\": [{\"tipo\": \"no-entendi\",\"rpta\": [{\"respueta_sl_texto\": \"null\"}]}]}'\n rpta1 = base64.b64encode(cda.encode('utf-8'))\n return HttpResponse(rpta1,'utf-8') \n else:\n rpta_final = \"Espero haber atendido tus dudas\"\n return HttpResponse(str(rpta_final))\n return HttpResponse(str('ok'))\n\n# def getjson(request):\n# if request.GET['json_rpt']:\n# estado_rpta = request.GET.get('estado')\n# json_rpt = request.GET.get('json_rpt')\n# json_nombre = request.GET.get('json_nombre')\n# id_empresa = request.GET.get('id_empresa')\n# id_user_create = request.GET.get('id_usu')\n# nombre_bd = request.GET.get('nombre_bd')\n# id_registro = request.GET.get('id_registro')\n# arrayRecibido = json.loads(json_rpt)\n\n# print(\"estado_rpta:\",estado_rpta)\n# print(\"json_rpt:\",json_rpt)\n# print(\"json_nombrewww:\",json_nombre)\n# print(\"id_empresa:\",id_empresa)\n# print(\"id_user_create:\",id_user_create)\n# print(\"nombre_bd:\",nombre_bd)\n# print(\"id_registro:\",id_registro)\n# print(\"arrayRecibidoarrayRecibido:\",arrayRecibido)\n\n# # 1. Eliminamos el json para reemplazar\n# # with os.scandir(ruta_actual + '/empresa_'+id_empresa) as ficheros:\n# # for fichero in ficheros:\n# # if fichero.name == nombre_bd+'_'+id_empresa+'.json':\n# # eliminar = ruta_actual + '/empresa_'+id_empresa+'/'+fichero.name\n# # os.remove(eliminar)\n# # print(\"ELIMINADO\")\n\n# # # 2. Eliminamos la base de datos para entrenar con los nuevos datos\n# # bd_deleted = os.path.join(BASE_DIR)\n# # delee = bd_deleted+\"/\"+\"midbaprendida_\"+id_user_create+\".sqlite3\"\n# # os.remove(delee)\n# # print(\"ELIMINADO BD\")\n\n# # # 3. Crea el nuevo archivo JSON\n# # arrayRecibido = json.loads(json_rpt)\n# # #Editamos\n# # datasetpreguntas.objects.filter(pk=id_registro).update(nombre=json_nombre,conversacion=json_rpt)\n# # data = {}\n# # data[\"conversations\"] = []\n# # for x in range(0,len(arrayRecibido)):\n# # data['conversations'].append({\n# # 'messages': arrayRecibido[x][0]['preguntas_new'],\n# # 'response': arrayRecibido[x][0]['respuesta_new'],\n# # })\n# # with open(ruta_actual+'/empresa_'+id_empresa+'/'+json_nombre+'_'+id_empresa+'.json', 'w', encoding='utf8') as file:\n# # json.dump(data, file, indent=4,ensure_ascii=False)\n\n# # # 4. Entrena y crea la nueva base de datos\n# # conversation_directory(id_empresa)\n# # initialize(id_user_create)\n# # train_bot(load_conversations())\n\n# return render(request, 'chatbot_admin/layouts/inicio.html')\n\ndef getjson(request):\n if request.GET['json_rpt']:\n estado_rpta = request.GET.get('estado')\n json_rpt = request.GET.get('json_rpt')\n json_nombre = request.GET.get('json_nombre')\n id_empresa = request.GET.get('id_empresa')\n id_user_create = request.GET.get('id_usu')\n nombre_bd = request.GET.get('nombre_bd')\n id_registro = request.GET.get('id_registro')\n\n\n if estado_rpta == \"Registrar\":\n\n try:\n # CREAR EL ARCHIVO JSON\n # arrayRecibido = json.loads(json_rpt)\n arrayRecibido = json.loads(json_rpt, strict=False)\n print(\"nombre_bdarrayRecibido:\",arrayRecibido)\n set_datosAdd = datasetpreguntas(nombre=json_nombre,conversacion=json_rpt,id_cliente=cliente.objects.get(pk=id_empresa))\n set_datosAdd.save()\n data = {}\n data[\"conversations\"] = []\n for x in range(0,len(arrayRecibido)):\n data['conversations'].append({\n 'messages': arrayRecibido[x][0]['preguntas_new'],\n 'response': arrayRecibido[x][0]['respuesta_new'],\n })\n with open(ruta_actual+'/empresa_'+id_empresa+'/'+json_nombre+'_'+id_empresa+'.json', 'w', encoding='utf8') as file:\n json.dump(data, file, indent=4,ensure_ascii=False)\n conversation_directory(id_empresa)\n initialize(id_user_create)\n train_bot(load_conversations())\n\n return HttpResponse(str(\"Registrado\"))\n \n except Exception as inst:\n\n return HttpResponse(inst)\n\n\n if estado_rpta == \"Editar\":\n \n try:\n # 1. Eliminamos el json para reemplazar\n print(\"Ingresamos a editar\")\n with os.scandir(ruta_actual + '/empresa_'+id_empresa) as ficheros:\n for fichero in ficheros:\n if fichero.name == nombre_bd+'_'+id_empresa+'.json':\n eliminar = ruta_actual + '/empresa_'+id_empresa+'/'+fichero.name\n os.remove(eliminar)\n print(\"ELIMINADO\")\n\n # 2. Eliminamos la base de datos para entrenar con los nuevos datos\n bd_deleted = os.path.join(BASE_DIR)\n delee = bd_deleted+\"/\"+\"midbaprendida_\"+id_user_create+\".sqlite3\"\n os.remove(delee)\n print(\"ELIMINADO BD\")\n\n # 3. Crea el nuevo archivo JSON\n arrayRecibido = json.loads(json_rpt)\n #Editamos\n datasetpreguntas.objects.filter(pk=id_registro).update(nombre=json_nombre,conversacion=json_rpt,registrado=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))\n data = {}\n data[\"conversations\"] = []\n for x in range(0,len(arrayRecibido)):\n data['conversations'].append({\n 'messages': arrayRecibido[x][0]['preguntas_new'],\n 'response': arrayRecibido[x][0]['respuesta_new'],\n })\n with open(ruta_actual+'/empresa_'+id_empresa+'/'+json_nombre+'_'+id_empresa+'.json', 'w', encoding='utf8') as file:\n json.dump(data, file, indent=4,ensure_ascii=False)\n\n # 4. Entrena y crea la nueva base de datos\n conversation_directory(id_empresa)\n initialize(id_user_create)\n train_bot(load_conversations())\n\n return HttpResponse(str(\"Registrado\"))\n \n except Exception as inst:\n\n return HttpResponse(inst)\n\n\ndef getjsondelet(request):\n if request.GET['id_reg']:\n id_reg = request.GET.get('id_reg')\n empresa = request.GET.get('empresa')\n nom = request.GET.get('nom')\n id_usu = request.GET.get('id_usu')\n\n # 1. Eliminamos el json \n with os.scandir(ruta_actual + '/empresa_'+empresa) as ficheros:\n for fichero in ficheros:\n if fichero.name == nom+'_'+empresa+'.json':\n eliminar = ruta_actual + '/empresa_'+empresa+'/'+fichero.name\n os.remove(eliminar)\n print(\"Eliminado\")\n\n # 2. Eliminar el registro\n record = datasetpreguntas.objects.get(pk = id_reg)\n record.delete()\n print(\"Registro eliminado\")\n \n # 3. Eliminamos la base de datos para entrenar con los nuevos datos\n bd_deleted = os.path.join(BASE_DIR)\n delee = bd_deleted+\"/\"+\"midbaprendida_\"+id_usu+\".sqlite3\"\n os.remove(delee)\n print(\"Eliminado BD\")\n\n # 4. Entrena y crea la nueva base de datos\n conversation_directory(empresa)\n initialize(id_usu)\n train_bot(load_conversations())\n print(\"Entrenado\")\n\n return HttpResponse(str(\"EliminadoOk\"))\n \n'''=============================================\n RECIBIENDO RANGO DE FECHAS\n============================================= '''\nclass historialChatApiView(APIView):\n def get(self, request, format=None):\n desde = request.GET.get('desde')\n hasta = request.GET.get('hasta')\n id_empresa = request.GET.get('id_empresa')\n #POSTGRESQL\n rpta = chat_user.objects.raw(\"SELECT DISTINCT ON (nombre_persona) nombre_persona,id,key_session_alias,cliente_empresa_id_id,email_persona,telefono_persona,registrado,pregunta,respuesta FROM historial_chat WHERE cliente_empresa_id_id=\"+str(id_empresa)+\" AND registrado BETWEEN SYMMETRIC '\"+str(desde)+\"' AND '\"+str(hasta)+\"' ORDER BY nombre_persona DESC\")\n serializer_historial = historialChatSerializers(rpta, many=True)\n return Response(serializer_historial.data)\n\n\n\n \n'''=============================================\n REPORTES DE INICIO\n============================================= '''\nclass reportesInicio(APIView):\n def get(self, request, format=None):\n id_empresa = request.GET.get('id')\n obj_idcl = cliente.objects.get(pk=id_empresa)\n \n #REPORTE DE CHAT SIN FECHAS\n rpta = chat_user.objects.raw(\"SELECT DISTINCT ON (nombre_persona) nombre_persona,id FROM historial_chat WHERE cliente_empresa_id_id=\"+str(obj_idcl.id)+\"\")\n \n serializer_historial = historialChatSerializers(rpta, many=True)\n return Response(serializer_historial.data)\n\n\nclass reportes_pendientes_ver(APIView):\n def get(self, request, format=None):\n id_empresa = request.GET.get('id')\n obj_idcl = cliente.objects.get(pk=id_empresa)\n \n #REPORTE DE CHAT SIN FECHAS\n rpta_vistos = chat_user.objects.raw(\"SELECT DISTINCT ON (nombre_persona) nombre_persona,estado_chat,id FROM historial_chat WHERE cliente_empresa_id_id=\"+str(obj_idcl.id)+\" AND estado_chat='novisto'\")\n \n \n serializer_historial = historialChatSerializers(rpta_vistos, many=True)\n return Response(serializer_historial.data)\n\n\n\n\n\n\n\n'''=============================================\n MOSTRAR HISTORIAL POR USUARIOS\n============================================= '''\nclass conversacionesApiView(APIView):\n def get(self, request, format=None):\n alias_nom = request.GET.get('usuario_alias')\n datos = chat_user.objects.filter(nombre_persona=alias_nom)\n serializer_conversacion = historialChatSerializers(datos, many=True)\n return Response(serializer_conversacion.data)\n\n'''=============================================\n REGISTRAR / EDITAR PERSONALIZACIÓN\n============================================= '''\nclass personalizarApiView(APIView):\n\n def get(self, request, format=None):\n \n id_empresa = request.GET.get('id_empr')\n rpta_pr = chatbot_style.objects.filter(id_empresa_cliente=id_empresa)\n\n serializer_historial = personalizarChatSerializers(rpta_pr, many=True)\n\n return Response(serializer_historial.data)\n\n\n def post(self, request, format=None):\n serializer = personalizarChatSerializers(data=request.data)\n\n print('serializeree :',serializer)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n # def put(self, request, pk, format=None):\n\n # dt = chatbot_style.objects.get(pk=pk)\n # serializer = personalizarChatSerializers(dt, data=request.data)\n\n # if serializer.is_valid():\n # serializer.save()\n # return Response(serializer.data)\n\n # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n'''=============================================\n ERROR 404\n============================================= '''\ndef error404(request,exception):\n return render(request, 'chatbot_admin/layouts/404.html')\n\n\n\n\ndef personalizar_edit(request):\n\n try:\n json_datos = request.GET.get('datos')\n arrayRecibido = json.loads(json_datos)\n\n if arrayRecibido[0]['tipo_color_header']==\"paleta\":\n rpta_chatbot_color = \"#\"+arrayRecibido[0]['rpta_color_header']\n if arrayRecibido[0]['tipo_color_header']==\"personalizado\":\n rpta_chatbot_color = arrayRecibido[0]['rpta_color_header'].replace('*','#')\n \n\n if arrayRecibido[0]['tipo_color_botones']==\"paleta\":\n rpta_botones_color = \"#\"+arrayRecibido[0]['rpta_color_botones']\n if arrayRecibido[0]['tipo_color_botones']==\"personalizado\":\n rpta_botones_color = arrayRecibido[0]['rpta_color_botones'].replace('*','#')\n\n\n id_empresa = cliente.objects.get(pk=arrayRecibido[0]['id_empresa_cliente'])\n chatbot_style.objects.filter(id_empresa_cliente=id_empresa).update(\n titulo_cuerpo=arrayRecibido[0]['titulo_cuerpo'],\n nombre_chatbot=arrayRecibido[0]['nombre_chatbot'],\n terminos_y_condiciones=arrayRecibido[0]['terminos_condiciones'],\n terminos_y_condiciones_aceptar=arrayRecibido[0]['t_y_c_aceptar'],\n terminos_y_condiciones_link=arrayRecibido[0]['terminos_condiciones_link'],\n terminos_y_condiciones_rechazar=arrayRecibido[0]['t_y_c_rechazar'],\n tipo_color_header=arrayRecibido[0]['tipo_color_header'],\n rpta_color_header=rpta_chatbot_color,\n tipo_color_botones=arrayRecibido[0]['tipo_color_botones'],\n rpta_color_botones=rpta_botones_color,\n )\n rpta = str(\"ok\")\n except Exception as inst:\n rpta = str(\"nook\")\n\n return HttpResponse(rpta)\n\n\n\nfrom django.core.files.storage import FileSystemStorage\nclass mod_slider(HttpRequest):\n def guardar_imagen_slider(request):\n\n if request.method == 'POST':\n\n print(\"hola\")\n upload = request.FILES['file']\n fss = FileSystemStorage()\n file = fss.save('slider/' + upload.name, upload)\n\n print('upload.name file:',file)\n\n # # upload = request.FILES.get('images2')\n\n return HttpResponse(str(file))\n\n def guardarlogochatbot(request):\n if request.method == 'POST':\n try:\n upload = request.FILES['file']\n fss = FileSystemStorage()\n file = fss.save('logo_chatbot/' + upload.name, upload)\n empresa_id = request.POST.get('empresa_id')\n #ACTUALIZAMOS\n id_empresa = cliente.objects.get(pk=empresa_id)\n chatbot_style.objects.filter(id_empresa_cliente=id_empresa).update(\n foto_logo=file,\n )\n rpta = str(\"ok\")\n except Exception as inst:\n rpta = str(\"nook\")\n\n return HttpResponse(rpta)\n\n\nclass obtener_prg(HttpRequest):\n def getprg(request):\n if request.GET['prg']:\n empr = request.GET.get('prg')\n rpta_prg = datasetpreguntas.objects.filter(pk=empr)\n return HttpResponse(str(empr)) \n\n \n'''=============================================\n EDITAR SET DATA\n============================================= '''\nclass data__set_all(APIView):\n def get(self, request, format=None):\n \n id__pregunta = request.GET.get('prg')\n rpta_pr = datasetpreguntas.objects.filter(pk=id__pregunta)\n\n serializer_historial = datasetSerializers(rpta_pr, many=True)\n\n return Response(serializer_historial.data)\n \n'''=============================================\n ELIMINAR HISTORIAL POR CHAT\n============================================= '''\ndef delete___chat(request):\n if request.GET['id']:\n id__his = request.GET.get('id')\n print(\"id__his :\",id__his)\n # 2. Eliminar el registro\n record = chat_user.objects.filter(nombre_persona = str(id__his))\n record.delete()\n print(\"Registro eliminado\")\n\n return HttpResponse(str(\"ChatEliminado\")) \n \ndef all_chat_ver(request):\n if request.GET['id']:\n id__his = request.GET.get('id')\n # record = chat_user.objects.filter(nombre_persona=str(id__his)).filter(estado_chat='novisto').count()\n record = chat_user.objects.filter(nombre_persona=str(id__his), estado_chat='novisto').count()\n\n return HttpResponse(str(record)) \n \ndef visto__chat(request):\n if request.GET['alias']:\n alias = request.GET.get('alias')\n # record = chat_user.objects.filter(nombre_persona=str(id__his)).filter(estado_chat='novisto').count()\n chat_user.objects.filter(nombre_persona=str(alias), estado_chat='novisto').update(estado_chat=\"visto\")\n print(\"Visto chat\")\n\n return HttpResponse(str(\"visto\")) \n\n'''=============================================\n REPORTES DE EXPORTAR\n============================================= '''\n\nclass r_exportar(HttpRequest):\n\n # FORMATO CSV\n def export_csv(request):\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition']='attachment; filename=Expenses' + \\\n str(datetime.datetime.now())+'.csv'\n\n writer=csv.writer(response)\n # writer.writerow(['#','Campos requeridos','Nombre','Correo Electrónico','Teléfono'])\n writer.writerow(['nombre_persona','email_persona','telefono_persona','nombre_persona_sin_alias','estado_chat'])\n\n expenses=chat_user.objects.filter()\n\n print(\"RPTAAAA :\",expenses)\n\n for expense in expenses:\n writer.writerow([expense.nombre_persona,expense.email_persona,expense.telefono_persona,expense.nombre_persona_sin_alias,expense.estado_chat])\n\n return response\n\n\n # FORMATO XLS -> pip install xlwt\n # def export_excel(request):\n # response = HttpResponse(content_type='application/ms-excel')\n # response['Content-Disposition']='attachment; filename=Expenses' + \\\n # str(datetime.datetime.now())+'.xls'\n\n # wb = xlwt.Workbook(encoding='utf-8')\n # ws = wb.add_sheet('Expenses')\n # row_num = 0\n\n # font_style=xlwt.XFStyle()\n # font_style.font.bold = True\n\n # colums = ['nombre_persona','email_persona','telefono_persona','nombre_persona_sin_alias','estado_chat']\n\n # for col_num in range(len(colums)):\n # ws.write(row_num, col_num, colums[col_num],font_style)\n\n # font_style = xlwt.XFStyle()\n\n # # rows = chat_user.objects.raw(\"SELECT DISTINCT ON (nombre_persona) nombre_persona,id,key_session_alias,cliente_empresa_id_id,email_persona,telefono_persona,registrado,pregunta,respuesta FROM historial_chat WHERE cliente_empresa_id_id=5 AND registrado BETWEEN SYMMETRIC '2022-09-10' AND '2022-09-09'\")\n\n # rows = chat_user.objects.filter().values_list('nombre_persona','email_persona','telefono_persona','nombre_persona_sin_alias','estado_chat')\n\n # for row in rows:\n # row_num+=1\n\n # for col_num in range(len(row)):\n # ws.write(row_num, col_num, str(row[col_num]),font_style)\n # wb.save(response)\n\n # return response\n\n\n\n\n'''=============================================\n API CONFIGURACIONES\n============================================= '''\n# from rest_framework import viewsets\n# from .serializers import ConfiguracionesSerializer\n# class ConfiguracionesViewSet(viewsets.ModelViewSet):\n# queryset = configuraciones.objects.all()\n# serializer_class = ConfiguracionesSerializer\n# def get_queryset(self):\n# Configuraciones = configuraciones.objects.all()\n# id_empresa = self.request.GET.get('id')\n# print(\"MY IDDDD:\",id_empresa)\n# if id_empresa:\n# Configuraciones = configuraciones.objects.filter(cliente_empresa_id=cliente.objects.get(pk=id_empresa))\n# return Configuraciones\n\n# def create(self, request):\n# serializer = self.serializer_class(data=request.data)\n# print(\"recibiendo_datos123 post :\",serializer)\n# if serializer.is_valid():\n# serializer.save()\n# return Response({\"message\": \"Configuración realizada correctamente\"}, status=status.HTTP_201_CREATED)\n\n# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \n# def update(self, request, pk):\n\n# serializer = self.serializer_class(data=request.data)\n\n# print(\"recibiendo_datos123 :\",serializer)\n\n# return Response({\"message\": \"Haciendo un put correctamente\"}, status=status.HTTP_201_CREATED)\n\n'''=============================================\n Utilitarios\n============================================= '''\n\n# def reemplazar_texto(json_obj, texto_a_reemplazar, nuevo_texto):\n# if isinstance(json_obj, dict):\n# for key in json_obj:\n# if isinstance(json_obj[key], (dict, list)):\n# reemplazar_texto(json_obj[key], texto_a_reemplazar, nuevo_texto)\n# elif isinstance(json_obj[key], str):\n# json_obj[key] = json_obj[key].replace(texto_a_reemplazar, nuevo_texto)\n# elif isinstance(json_obj, list):\n# for item in json_obj:\n# reemplazar_texto(item, texto_a_reemplazar, nuevo_texto)\n# return json_obj","repo_name":"Anthonyhernandezolazabal/Django_chatbot","sub_path":"app/chatbot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":27836,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"15476476350","text":"# Adapted from https://github.com/GuanLab/Leopard/blob/master/data/quantile_normalize_bigwig.py\n\nimport argparse, time\nimport numpy as np\nimport pyBigWig\n\n# Human chromosomes in hg19, and their sizes in bp\nchrom_sizes = {'chr1': 249250621, 'chr10': 135534747, 'chr11': 135006516, 'chr12': 133851895, 'chr13': 115169878, 'chr14': 107349540, 'chr15': 102531392, 'chr16': 90354753, 'chr17': 81195210, 'chr18': 78077248, 'chr19': 59128983, 'chr2': 243199373, 'chr20': 63025520, 'chr21': 48129895, 'chr22': 51304566, 'chr3': 198022430, 'chr4': 191154276, 'chr5': 180915260, 'chr6': 171115067, 'chr7': 159138663, 'chr8': 146364022, 'chr9': 141213431, 'chrX': 155270560}\n\n\ndef qn_sample_to_array(\n input_celltypes,\n input_chroms=None,\n subsampling_ratio=1000,\n data_pfx = '/users/abalsubr/wilds/examples/data/encode_v1.0/'\n):\n \"\"\"\n Compute and write distribution of DNase bigwigs corresponding to input celltypes.\n \"\"\"\n if input_chroms is None:\n input_chroms = chrom_sizes.keys()\n qn_chrom_sizes = { k: chrom_sizes[k] for k in input_chroms }\n # Initialize chromosome-specific seeds for subsampling\n chr_to_seed = {}\n i = 0\n for the_chr in qn_chrom_sizes:\n chr_to_seed[the_chr] = i\n i += 1\n\n # subsampling\n sample_len = np.ceil(np.array(list(qn_chrom_sizes.values()))/subsampling_ratio).astype(int)\n sample = np.zeros(sum(sample_len))\n start = 0\n j = 0\n for the_chr in qn_chrom_sizes:\n np.random.seed(chr_to_seed[the_chr])\n for ct in input_celltypes:\n path = data_pfx + 'DNASE.{}.fc.signal.bigwig'.format(ct)\n bw = pyBigWig.open(path)\n signal = np.nan_to_num(np.array(bw.values(the_chr, 0, qn_chrom_sizes[the_chr])))\n index = np.random.randint(0, len(signal), sample_len[j])\n sample[start:(start+sample_len[j])] += (1.0/len(input_celltypes))*signal[index]\n start += sample_len[j]\n j += 1\n print(the_chr, ct)\n sample.sort()\n np.save(data_pfx + \"qn.{}.npy\".format('.'.join(input_celltypes)), sample)\n\n\nif __name__ == '__main__':\n train_chroms = ['chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr10', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr22', 'chrX']\n all_celltypes = ['H1-hESC', 'HCT116', 'HeLa-S3', 'K562', 'A549', 'GM12878', 'MCF-7', 'HepG2', 'liver']\n for ct in all_celltypes:\n qn_sample_to_array([ct], input_chroms=train_chroms)\n","repo_name":"p-lambda/wilds","sub_path":"dataset_preprocessing/encode/prep_accessibility.py","file_name":"prep_accessibility.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":505,"dataset":"github-code","pt":"9"} +{"seq_id":"74447493092","text":"from django.urls import reverse\nfrom rest_framework.test import APITestCase\nfrom rest_framework import status\n\nfrom chessproject.chessapi.models import Piece\n\n\nclass PiecesViewTestCase(APITestCase):\n def test_create_a_new_piece(self):\n \"\"\"\n Ensures that is possible to create a new piece\n \"\"\"\n url = reverse('pieces')\n data = {'type': 'Knight', 'color': 'white'}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(Piece.objects.count(), 1)\n\n def test_that_is_not_possible_create_an_invalid_piece(self):\n \"\"\"\n Ensures that is not possible to create an invalid piece\n \"\"\"\n url = reverse('pieces')\n data = {'type': 'Turtle', 'color': 'purple'}\n response = self.client.post(url, data, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_that_the_moves_for_a_knight_are_returned_correctly(self):\n \"\"\"\n Ensures that the moves for piece of the type Knight are returned\n \"\"\"\n piece = Piece.objects.create(type='Knight', color='white')\n url = reverse('moves', kwargs={'pk': piece.id})\n data = {'coordinate': 'h1'}\n response = self.client.get(url, data=data, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(['d3', 'e2', 'e4', 'f2', 'f5', 'g3', 'g4', 'h3', 'h5'], response.data)\n\n def test_that_the_moves_for_a_different_piece_are_not_returned(self):\n \"\"\"\n Ensures that the moves are not returned from a piece that is not a Knight\n \"\"\"\n piece = Piece.objects.create(type='Queen', color='white')\n url = reverse('moves', kwargs={'pk': piece.id})\n data = {'coordinate': 'h1'}\n response = self.client.get(url, data=data, format='json')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual([], response.data)\n\n def test_that_the_an_error_is_returned_when_a_position_is_not_provided(self):\n \"\"\"\n Ensures that an status code 400 is returned when the argument position is not provided\n \"\"\"\n piece = Piece.objects.create(type='Knight', color='white')\n url = reverse('moves', kwargs={'pk': piece.id})\n response = self.client.get(url, format='json')\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n","repo_name":"alysonbg/chessapi","sub_path":"chessproject/chessapi/tests/tests_views.py","file_name":"tests_views.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"8255765844","text":"from typing import Optional\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nfrom segmentation_models_pytorch.base import ClassificationHead\nfrom segmentation_models_pytorch.encoders import get_encoder\nfrom segmentation_models_pytorch.base import initialization as init\n\n\nclass UnetClassifier(nn.Module):\n def __init__(self, encoder_name='timm-efficientnet-b0', encoder_depth=5, encoder_weights='imagenet',\n in_channels=3, num_classes=3):\n super(UnetClassifier, self).__init__()\n\n # Encoder half of unet\n self.encoder = get_encoder(encoder_name, in_channels=in_channels, depth=encoder_depth, weights=encoder_weights,)\n self.num_classes = num_classes\n\n # Parameters for the classification head - at some point we might want these as class attributes\n # Currently, all are their default's except activation\n aux_params = {\n 'pooling': 'avg',\n 'dropout': 0.0,\n 'activation': None,\n 'classes': num_classes\n }\n self.classification_head = ClassificationHead(in_channels=self.encoder.out_channels[-1], **aux_params)\n init.initialize_head(self.classification_head)\n\n def forward(self, x):\n features = self.encoder(x)\n logits = self.classification_head(features[-1])\n\n return logits\n","repo_name":"mattswatson/learning-to-mimic","sub_path":"UnetClassifier.py","file_name":"UnetClassifier.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"9"} +{"seq_id":"21374274454","text":"import math\n'''\nAs coordenadas (x, y) de um ponto no plano podem ser armazenadas em uma tupla, como mostrado abaixo:\n ponto1 = (10.4, 5.5)\nSalve em uma lista um conjunto de n tuplas, representando n pontos informados pelo usuário. Mostre na tela quais são os dois pontos deste conjunto que apresentam a maior distância entre si. A distância entre dois pontos é dado pela Norma Euclidiana\n'''\nn = int(input())\npontos = []\nmaior = 0\n\nfor num in range(n):\n x = float(input())\n y = float(input())\n tupla = (x,y)\n pontos.append(tupla)\nfor p1 in range(len(pontos)):\n for p2 in range(len(pontos)):\n distancia = math.sqrt((pontos[p2][0]-pontos[p1][0])**2+(pontos[p2][1]-pontos[p1][1])**2)\n if distancia > maior:\n P1=pontos[p1]\n P2=pontos[p2]\nprint(f'Mais distantes: {P1} {P2}')","repo_name":"Natanael-Azevedo/linguagem_de_programacao_2022","sub_path":"12_09/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"3714612667","text":"from flaskr import celery, db\nfrom .models import Alert\nfrom celery import chain\nfrom datetime import datetime\nfrom .GPUWU_server import fetchData, fetchDataMulti\n\n\n@celery.on_after_configure.connect\ndef setup_periodic_tasks(sender, **kwargs):\n sender.add_periodic_task(15.0, update_stock.s(), expires=10)\n\n\n@celery.task(name='update_stock')\ndef update_stock():\n g = chain(fetch_stock_info.s() | store_stock_info.s())\n g()\n\n\n@celery.task(name='fetch_stock_info')\ndef fetch_stock_info():\n res = fetchDataMulti(\n 'https://www.bestbuy.com/site/computer-cards-components/computer-pc-processors/abcat0507010.c?id=abcat0507010')\n return res\n\n\n@celery.task(name='store_stock_info')\ndef store_stock_info(stock):\n for item in stock:\n alert = Alert(sku=item['sku'], product=item['product'], atc_url=item['atc_url'], product_url=item['product_url'])\n db.session.add(alert)\n db.session.commit()\n\n print(\"Successfully stored stock info\")\n","repo_name":"AlexJ-Cole/GPUWU","sub_path":"flaskr/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"10118076968","text":"# 생각해보니 result 배열을 따로 쓰지않고 바로 찍으면 되는 문제였던거 같다.\n\n# n = int(input())\n# result = []\n# i = 2\n\n# while n > 1:\n# if n % i == 0:\n# result.append(i)\n# n //= i\n# continue\n#\n# i += 1\n#\n# result.sort()\n#\n# for i in result:\n# print(i)\n\n# 그래서 줄여서 다시 제출해 보았다~\n\nn = int(input())\ni = 2\n\nwhile n > 1:\n if n % i == 0:\n print(i)\n n //= i\n continue\n\n i += 1","repo_name":"CASY82/CHH_StudyRoom","sub_path":"Algo/etc/Baek_11653.py","file_name":"Baek_11653.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"27201083366","text":"# This file represents the quiz settings for ALL quizzes.\nimport os\nfrom discord.ext.commands import bot\nfrom discord.ext import commands\nimport sqlite3\n\n\n# Important note: Any updates to the database require the binding variable to be a tuple. Even if you're only adding one\n# thing, you must surround the statement with parenthesis and add a comma after the variable.\n# Example: val = (\",\".join(args),)\nclass QuizSettings(commands.Cog):\n def __init__(self, client):\n self.client = client\n\n # Database initializes on ready.\n @bot.Cog.listener()\n async def on_ready(self):\n print('Quiz potion loaded')\n # If the database for quiz_settings doesn't exist, create it.\n try:\n os.chdir(os.getcwd() + \"\\\\database\")\n if not os.path.exists(\"quiz_settings.sqlite\"): # May be useless since cursor makes db if it doesn't exist.\n print(\"Missing quiz_setting database, making\")\n db = sqlite3.connect('quiz_settings.sqlite')\n cursor = db.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS quiz_settings(\n level TEXT,\n time_limit INTEGER,\n acc_flag INTEGER,\n end_kanji_flag INTEGER,\n time_elapsed_flag INTEGER,\n strike_limit INTEGER,\n compound_range TEXT\n )\n ''')\n # Insert generic quiz settings if none exist.\n cursor.execute(\n f\"INSERT INTO quiz_settings(level, time_limit, acc_flag, end_kanji_flag, time_elapsed_flag, strike_limit, compound_range)\"\n f\"VALUES (5, 15, 1, 1, 1, 3, '1,500')\")\n db.commit()\n cursor.close()\n db.close()\n except FileNotFoundError:\n print(\"Database folder doesn't exist! Should have initialized on bot boot.\")\n\n # Displays quiz settings\n @commands.command(name='qs', help='Displays quiz settings')\n async def quiz_settings(self, ctx):\n # Options for users to change quiz settings.\n db = sqlite3.connect('quiz_settings.sqlite')\n cursor = db.cursor()\n await ctx.send(\":tools: Quiz Settings: :tools:\\n\"\n \"Change levels: JLPT level(s) **{}** (.setkqlevel)\\n\"\n \"Change time limit (in sec) per question: **{}** (.settime)\\n\"\n \"Toggle show accuracy at the end of a quiz: **{}** (.toggleacc)\\n\"\n \"Toggle show kanji at the end of a quiz: **{}** (.togglekanji)\\n\"\n \"Toggle show total elapsed time at the end of a quiz: **{}** (.toggletime)\\n\"\n \"Change the total strike allowed for a quiz: **{}** (.setstrike)\\n\"\n \"Change range: **{}** (.setcqlevel)\"\n .format(cursor.execute(\"SELECT level FROM quiz_settings\").fetchone()[0],\n cursor.execute(\"SELECT time_limit FROM quiz_settings\").fetchone()[0],\n cursor.execute(\"SELECT acc_flag FROM quiz_settings\").fetchone()[0],\n cursor.execute(\"SELECT end_kanji_flag FROM quiz_settings\").fetchone()[0],\n cursor.execute(\"SELECT time_elapsed_flag FROM quiz_settings\").fetchone()[0],\n cursor.execute(\"SELECT strike_limit FROM quiz_settings\").fetchone()[0],\n cursor.execute(\"SELECT compound_range FROM quiz_settings\").fetchone()[0]))\n\n @commands.command(name='setkqlevel', help='Change which Kanji show up on the kanji quiz')\n async def set_kq_level(self, ctx, *args):\n possible_levels = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\"]\n if len(args) > 0 and (len(set(args)) == len(args)):\n for i in args:\n if i not in possible_levels: # Invalid Arguments\n await ctx.send(\n \"This command allows a user to change the amount of kanji (based on the JLPT) that show\"\n \"up on the kanji quiz.\\n\\n\"\n \"**.setkqlevel 5**: Kanji quizzes will only show kanji from JLPT N5\\n\\n\"\n \"**.setkqlevel 4**: Kanji quizzes will only show kanji from JLPT N4\\n\\n\"\n \"**.setkqlevel 3**: Kanji quizzes will only show kanji from JLPT N3\\n\\n\"\n \"**.setkqlevel 2**: Kanji quizzes will only show kanji from JLPT N2\\n\\n\"\n \"**.setkqlevel 1**: Kanji quizzes will only show kanji from JLPT N1\\n\\n\"\n \"**.setkqlevel 0**: Kanji quizzes will only show kanji not on the JLPT\\n\\n\"\n \"A user can also append more arguments to their command to include kanji from more than\"\n \"one level.\\n\"\n \"Example: **.setkqlevel 5 3**: Kanji quizzes will show kanji from ONLY JLPT N5 and N3\")\n break\n # Update database with the given arguments.\n sql = \"UPDATE quiz_settings SET level = ?\"\n val = (\",\".join(args),)\n update_setting(sql, val)\n await ctx.send(\"Level changed.\")\n\n else: # Arguments don't exist\n await ctx.send(\n \"This command allows a user to change the amount of kanji (based on the JLPT) that show\"\n \"up on the kanji quiz.\\n\\n\"\n \"**.setkqlevel 5**: Kanji quizzes will only show kanji from JLPT N5\\n\\n\"\n \"**.setkqlevel 4**: Kanji quizzes will only show kanji from JLPT N4\\n\\n\"\n \"**.setkqlevel 3**: Kanji quizzes will only show kanji from JLPT N3\\n\\n\"\n \"**.setkqlevel 2**: Kanji quizzes will only show kanji from JLPT N2\\n\\n\"\n \"**.setkqlevel 1**: Kanji quizzes will only show kanji from JLPT N1\\n\\n\"\n \"**.setkqlevel 0**: Kanji quizzes will only show kanji not on the JLPT\\n\\n\"\n \"A user can also append more arguments to their command to include kanji from more than\"\n \"one level.\\n\"\n \"Example: **.setkqlevel 5 3**: Kanji quizzes will show kanji from ONLY JLPT N5 and N3\")\n\n @commands.command(name='setcqlevel', help='Change the range of which words show up on the compound quiz')\n async def set_cq_level(self, ctx, *args):\n db = sqlite3.connect('kanji.sqlite')\n cursor = db.cursor()\n max_freq = cursor.execute(\"SELECT Frequency FROM compounds LIMIT 1\").fetchone()[0]\n if len(args) > 0 and all(x.isnumeric() for x in args):\n if (len(args) == 2 and int(args[0]) <= int(args[1])) or (len(args) == 1 and int(args[0]) <= max_freq):\n # Query\n sql = \"UPDATE quiz_settings SET compound_range = ?\"\n if len(args) == 2: # Arg is a 2 side range\n val = (\",\".join(args),)\n else: # Arg is a one side range.\n val = ((\"1,\" + args[0]),)\n update_setting(sql, val)\n\n else:\n await ctx.send(\n \"This command allows a user to change the range of which words show up on the compound quiz. \"\n \"The lower the range, the higher the frequency. (Min = 1, Max = {})\\n\\n\"\n \"**.setcqlevel 5000**: Compound quizzes will show the most common 5000 words\\n\\n\"\n \"**.setcqlevel 5000 5050**: Compound quizzes will show the 5000th most \"\n \"common word to the 5050th (first arg must be less than second).\".format(max_freq))\n else:\n await ctx.send(\"This command allows a user to change the range of which words show up on the compound \"\n \"quiz. The lower the range, the higher the frequency. (Min = 1, Max = {})\\n\\n\"\n \"**.setcqlevel 5000**: Compound quizzes will show the most common 5000 words\\n\\n\"\n \"**.setcqlevel 5000 5050**: Compound quizzes will show the 5000th most \"\n \"common word to the 5050th (first arg must be less than second).\".format(max_freq))\n\n @commands.command(name='settime', help='Change time limit (in sec) per quiz question')\n async def set_time(self, ctx, arg):\n if 25 >= int(arg) > 2:\n sql = \"UPDATE quiz_settings SET time_limit = ?\"\n val = (arg,)\n update_setting(sql, val)\n await ctx.send(\"Time changed.\", delete_after=5)\n else: # Invalid argument\n await ctx.send(\"This command allows a user to change the amount of time that elapses between each quiz \"\n \"question (max time limit = 25 seconds and min = 3 seconds).\\n\\n\"\n \"Example: **.settime 5**: 5 seconds will elapse between each quiz question\")\n\n @commands.command(name='setstrike', help='Set how may strikes are allowed for a quiz.')\n async def set_strike(self, ctx, arg):\n if 5 >= int(arg) > 0:\n sql = \"UPDATE quiz_settings SET strike_limit = ?\"\n val = (arg,)\n update_setting(sql, val)\n await ctx.send(\"Strike limit changed.\", delete_after=5)\n else: # Invalid Argument\n await ctx.send(\"This command allows a user to change the amount of strikes they can accumulate during a \"\n \"quiz. When the strike limit is reached, the quiz ends. (max strikes = 5, min = 1)\\n\\n\"\n \"Example: **.setstrike 5**: User is allowed to get 5 questions wrong before the quiz ends.\")\n\n @commands.command(name='toggleacc', help='Toggle show accuracy at the end of a quiz')\n async def toggle_accuracy(self, ctx, arg):\n if int(arg) == 0 or int(arg) == 1:\n sql = \"UPDATE quiz_settings SET acc_flag = ?\"\n val = arg\n update_setting(sql, val)\n await ctx.send(\"Accuracy toggled.\", delete_after=5)\n else: # Invalid arguments.\n await ctx.send(\"This command allows a user to change whether or not to show overall accuracy at the \"\n \"end of a quiz.\\n\\n\"\n \"**.toggleacc 1**: Shows accuracy at the end.\\n\\n\"\n \"**.toggleacc 0**: Does not show accuracy at the end.\")\n\n @commands.command(name='togglekanji', help='Toggle show kanji at the end of a quiz')\n async def toggle_kanji(self, ctx, arg):\n if int(arg) == 0 or int(arg) == 1:\n sql = \"UPDATE quiz_settings SET end_kanji_flag = ?\"\n val = arg\n update_setting(sql, val)\n await ctx.send(\"Kanji toggled.\", delete_after=5)\n else: # Invalid arguments.\n await ctx.send(\"This command allows a user to change whether or not to show all kanji that appeared at the \"\n \"end of a quiz.\\n\\n\"\n \"**.togglekanji 1**: Shows kanji at the end.\\n\\n\"\n \"**.togglekanji 0**: Does not show kanji at the end.\")\n\n @commands.command(name='toggletime', help='Toggle show total elapsed time at the end of a quiz')\n async def toggle_time(self, ctx, arg):\n if int(arg) == 0 or int(arg) == 1:\n sql = \"UPDATE quiz_settings SET time_elapsed_flag = ?\"\n val = arg\n update_setting(sql, val)\n await ctx.send(\"Time toggled.\", delete_after=5)\n else: # Invalid arguments.\n await ctx.send(\"This command allows a user to change whether or not to show total elapsed time at the \"\n \"end of a quiz.\\n\\n\"\n \"**.toggletime 1**: Shows time at the end.\\n\\n\"\n \"**.toggletime 0**: Does not show time at the end.\")\n\n # Catches errors that appear during runtime for the commands above.\n @toggle_kanji.error\n async def toggle_kanji_error(self, ctx, error):\n await ctx.send(\"This command allows a user to change whether or not to show all kanji that appeared at the \"\n \"end of a quiz.\\n\\n\"\n \"**.togglekanji 1**: Shows kanji at the end.\\n\\n\"\n \"**.togglekanji 0**: Does not show kanji at the end.\")\n\n @toggle_time.error\n async def toggle_time_error(self, ctx, error):\n await ctx.send(\"This command allows a user to change whether or not to show total elapsed time at the \"\n \"end of a quiz.\\n\\n\"\n \"**.toggletime 1**: Shows time at the end.\\n\\n\"\n \"**.toggletime 0**: Does not show time at the end.\")\n\n @set_time.error\n async def set_time_error(self, ctx, error):\n await ctx.send(\"This command allows a user to change the amount of time that elapses between each quiz\"\n \"question (max time limit = 25 seconds and min = 3 seconds).\\n\\n\"\n \"Example: **.settime 5**: 5 seconds will elapse between each quiz question\")\n\n @set_strike.error\n async def set_strike_error(self, ctx, error):\n await ctx.send(\"This command allows a user to change the amount of strikes they can accumulate during a \"\n \"quiz. When the strike limit is reached, the quiz ends. (max strikes = 5, min = 1)\\n\\n\"\n \"Example: **.setstrike 5**: User is allowed to get 5 questions wrong before the quiz ends.\")\n\n @toggle_accuracy.error\n async def toggle_accuracy_error(self, ctx, error):\n await ctx.send(\"This command allows a user to change whether or not to show overall accuracy at the \"\n \"end of a quiz.\\n\\n\"\n \"**.toggleacc 1**: Shows accuracy at the end.\\n\\n\"\n \"**.toggleacc 0**: Does not show accuracy at the end.\")\n\n @set_kq_level.error\n async def set_kq_level_error(self, ctx, error):\n await ctx.send(\"This command allows a user to change the amount of kanji (based on the JLPT) that show\"\n \"up on the kanji quiz given quiz.\\n\\n\"\n \"**.setlevel 5**: Kanji quizzes will only show kanji from JLPT N5\\n\\n\"\n \"**.setlevel 4**: Kanji quizzes will only show kanji from JLPT N4\\n\\n\"\n \"**.setlevel 3**: Kanji quizzes will only show kanji from JLPT N3\\n\\n\"\n \"**.setlevel 2**: Kanji quizzes will only show kanji from JLPT N2\\n\\n\"\n \"**.setlevel 1**: Kanji quizzes will only show kanji from JLPT N1\\n\\n\"\n \"A user can also append more arguments to their command to include kanji from more than\"\n \"one level.\\n\"\n \"Example: **setlevel 5 3**: Kanji quizzes will show kanji from ONLY JLPT N5 and N3\")\n\n\ndef setup(client):\n client.add_cog(QuizSettings(client))\n\n\ndef update_setting(sql, val):\n db = sqlite3.connect('quiz_settings.sqlite')\n cursor = db.cursor()\n cursor.execute(sql, val)\n db.commit()\n cursor.close()\n db.close()\n","repo_name":"Xronier/Sakuranbot","sub_path":"Lib/cogs/QuizSettings.py","file_name":"QuizSettings.py","file_ext":"py","file_size_in_byte":15055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"19819475884","text":"# %% [markdown]\n# # Setup\n\n# %%\n# importing required modules\nimport pandas as pd\nfrom IPython.display import display\nfrom SuperBudget import get_pdf_totals, display_totals, display_df_split_by_time\n\n\n# %% [markdown]\n# ## Validation Outputs\ndf_spend = get_pdf_totals(\n pdf_file_paths=\"file_paths.csv\",\n vendor_categories=\"vendor_category.csv\",\n)\ndf_spend.to_csv(\"Total Costs.csv\", index=False)\n\n# %% [markdown]\n# ### Receipts\ndisplay(df_spend.sort_values(\"total\", ascending=False))\n\n# %% [markdown]\n# ## Balance\ndisplay_totals(\n df_spend=df_spend,\n df_income=pd.read_csv(\"income.csv\"),\n str_carry_over_tag=\"CarryOver\",\n)\n\n# %% [markdown]\n# ## Vendor Breakdown\ndisplay(\n df_spend[[\"vendor\", \"total\"]]\n .groupby(\"vendor\")\n .sum()\n .sort_values(\"total\", ascending=False)\n)\n\n# %% [markdown]\n# ## Vendor Category Breakdown\ndisplay(df_spend.groupby(\"category\").sum().sort_values(\"total\", ascending=False))\n\n# %% [markdown]\n# ## Reimbursement Calculations\ndisplay_df_split_by_time(df_spend=df_spend, date_cutoff=\"3/1/22\")\n","repo_name":"FRCTeam3255/SuperBudget","sub_path":"examples/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"37646592778","text":"import cv2\nimport streamlink\nimport time\n\n# Replace this with the URL of the YouTube live stream\nstream_url = \"https://www.youtube.com/watch?v=sUKwTVAc0Vo\"\n\n# Replace this with the desired location to save tickers\nsave_directory = \"assets/tickers/tem/\"\n\n# Open the stream using streamlink\nstreams = streamlink.streams(stream_url)\nstream = streams[\"best\"]\n\nframe_number = 0\nwhile True:\n try:\n # OpenCV video capture from streamlink\n cap = cv2.VideoCapture(stream.url)\n\n ret, frame = cap.read()\n if ret:\n # Get the dimensions of the frame\n height, width, _ = frame.shape\n\n # Define cropping coordinates (top, bottom, left, right)\n crop_top = int(0.84 * height) # Cut from the top\n crop_bottom = int(0.03 * height) # Cut from the bottom\n crop_left = int(0.05 * width) # Cut from the left\n crop_right = int(0.17 * width) # Cut from the right\n\n # Crop the frame based on the defined coordinates\n cropped_frame = frame[crop_top:-crop_bottom, crop_left:-crop_right]\n\n # Check if the cropped frame is empty\n if cropped_frame.size == 0:\n print(\"Empty frame captured\")\n\n else:\n # Save the cropped frame\n frame_filename = f\"{save_directory}frame_{frame_number:04d}.jpg\"\n cv2.imwrite(frame_filename, cropped_frame)\n\n frame_number += 1\n\n else:\n print(\"Error capturing frame\")\n\n cap.release()\n\n except Exception as e:\n print(f\"An error occurred: {str(e)}\")\n\n # Wait for 2 seconds before capturing the next frame\n time.sleep(2)\n","repo_name":"haseebmohsin/tickers-server","sub_path":"scripts/oneChannelTickers.py","file_name":"oneChannelTickers.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"29394676150","text":"import ctypes\nfrom time import sleep\nfrom pyA20.gpio import gpio\nfrom pyA20.gpio import port\n\nmod = ctypes.cdll.LoadLibrary('/root/OneWire/onewire.so')\nwire = mod.new_(15)\n\ndef getTemp(device):\n list = (ctypes.c_uint8 * 9)()\n\n while True:\n mod.setDevice(wire, ctypes.c_uint64(device))\n mod.writeByte(wire, 68) #CONVERTEMP\n sleep(1)\n mod.setDevice(wire, ctypes.c_uint64(device))\n mod.writeByte(wire, 16*11+14)\n\n for i in range(0, 9):\n list[i] = mod.readByte(wire)\n\n c_8 = mod.crc8_(wire, list, 8)\n\n if c_8 == list[8]:\n break\n\n\n return ((list[1] << 8) + list[0]) * 0.0625 \n\ndef blink3():\n gpio.init()\n blink = port.PA7\n gpio.setcfg(blink, gpio.OUTPUT)\n\n gpio.output(blink, gpio.HIGH)\n\n sleep(0.03)\n gpio.output(blink, gpio.LOW)\n sleep(0.03)\n\n\ntry:\n mod.oneWireInit(wire)\n therm = 0.0\n c_n = ctypes.c_int(100)\n list = (ctypes.c_uint64 * 100)()\n mod.searchRom(wire, list, ctypes.byref(c_n))\n print('----------------------')\n print('devices = %s' % c_n.value)\n print('----------------------')\n for i in range(0, c_n.value):\n print ('addr T[%s] = %s' % (i + 1, list[i])) \n print('----------------------')\n while True:\n for i in range(0, c_n.value):\n temperature = getTemp(list[i])\n print(\"T[%s] = %s C\" % (i + 1, temperature))\n blink3()\n sleep(1)\n\nexcept:\n print(\"Incorect temperature\")\n\n\n \n\n\n","repo_name":"PeterIanush/OrangePiZeroH2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"17753458966","text":"from django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponseRedirect\nfrom django.http import JsonResponse\nfrom cart.models import Cart\nfrom checkout.models import ContactInfo, PaymentInfo\nfrom checkout.forms import ContactInfoForm, PaymentForm\nfrom django_countries import countries\n\n# Create your views here.\n\n\n# helper function to get the cart to all views in check-out process\n@login_required\ndef getcart(request):\n if request.user.is_authenticated:\n try:\n cart = Cart.objects.get(customer=request.user.Profile, complete=False)\n items = cart.cartitem_set.all()\n except ObjectDoesNotExist:\n cart = 'empty'\n items = []\n else:\n items = []\n cart = 'empty'\n context = {'item': items, 'cart': cart}\n return context\n\n# GET and POST for creditcart input site\n# GET renders page and POST does little\n# becasue we dont keep CC data\n@login_required\ndef creditcard(request):\n if request.method == 'GET':\n context = getcart(request)\n if context['cart'] != 'empty':\n form = ContactInfoForm()\n context['form'] = form\n else:\n return redirect('/')\n form = PaymentForm()\n context['form'] = form\n if request.method == 'POST':\n form = PaymentForm(request.POST or None)\n if form.is_valid():\n print('Credit Card form is valid')\n nameOnCC = form.cleaned_data.get('name_on_the_card')\n expDate = form.cleaned_data.get('cc_expiry')\n paymentInfo = PaymentInfo(user=request.user.Profile, nameOnCC=nameOnCC, expDate=expDate)\n paymentInfo.save()\n return redirect('checkout-confirmation')\n else:\n context = getcart(request)\n form = PaymentForm()\n context['form'] = form\n context['error'] = 'Input invalid'\n return render(request, 'checkout/creditcard.html', context)\n\n\n# GET and POST for shipping address and contact details\n# GET renders page and form\n# POST adds the shipping info into the contact model\n@login_required\ndef contact(request):\n if request.method == 'GET':\n context = getcart(request)\n if context['cart'] != 'empty':\n form = ContactInfoForm()\n context['form'] = form\n return render(request, 'checkout/contact.html', context)\n else:\n return redirect('/')\n if request.method == 'POST':\n form = ContactInfoForm(request.POST or None)\n try:\n cart = Cart.objects.get(customer=request.user.Profile, complete=False)\n if form.is_valid():\n first_name = form.cleaned_data.get('first_name')\n last_name = form.cleaned_data.get('last_name')\n email = form.cleaned_data.get('email')\n address = form.cleaned_data.get('address')\n apartment_number = form.cleaned_data.get('apartment_number')\n additional_information = form.cleaned_data.get('additional_information')\n country = form.cleaned_data.get('country')\n city = form.cleaned_data.get('city')\n zip = form.cleaned_data.get('zip')\n contactinfo = ContactInfo(\n user=request.user.Profile, first_name=first_name, last_name=last_name, email=email,\n address=address, apartment_number=apartment_number, additional_information=additional_information,\n country=country, city=city, zip=zip\n )\n contactinfo.save()\n cart.contactinfo = contactinfo\n cart.save()\n return redirect('checkout-creditcard')\n except ObjectDoesNotExist:\n print('User does not have an active order')\n return redirect('/')\n\n\n# GET and POST for the overview confirmation site\n# GET renders Site with order summary\n# POST empties the cart and \"processes\" the payment and shipping\n@login_required\ndef confirmation(request):\n if request.method == 'GET':\n context = getcart(request)\n if context['cart'] != 'empty':\n contactinfo = ContactInfo.objects.filter(user=request.user.Profile).last() #saekir nyjasta contact info\n paymentinfo = PaymentInfo.objects.filter(user=request.user.Profile).last()\n country = dict(countries)[contactinfo.country[0]]\n context['contact'] = contactinfo\n context['country'] = country\n context['payment'] = paymentinfo\n return render(request, 'checkout/confirmation.html', context)\n else:\n return redirect('/')\n if request.method == 'POST':\n cart = Cart.objects.get(customer=request.user.Profile, complete=False)\n cart.transactionId = cart.id\n cart.complete = True\n cart.save()\n return redirect('checkout-receipt')\n\n\n# GET: renders the reciept site and returns all info of last order\n@login_required\ndef receipt(request):\n cart = Cart.objects.filter(customer=request.user.Profile).last()\n items = cart.cartitem_set.all()\n paymentinfo = PaymentInfo.objects.filter(user=request.user.Profile).last()\n context = {'item':items, 'payment':paymentinfo}\n return render(request, 'checkout/receipt.html', context)\n","repo_name":"sindrirafn/ship-o-cereal","sub_path":"ship_o_cereal/checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"34756381459","text":"def fib(n):\n if n < 2:\n return n\n else:\n # fn = fn-1 + fn-2\n return fib(n-1) + fib(n-2)\n\nfibonacci = []\nfor x in range(10):\n fibonacci.append(fib(x))\n\nprint(fibonacci)","repo_name":"rigobertosanchez/langchain_examples","sub_path":"example_data/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"9905935584","text":"\"\"\"random data generator module.\"\"\"\nfrom datetime import datetime\nfrom random import uniform\nfrom typing import Protocol\n\nfrom kink import inject\nfrom sensor.model import RandomConfig, SensorData, SensorMetadata\n\n\nclass IRandomDataGenerator(Protocol):\n def generate_sensor_data(self) -> SensorData:\n ...\n\n\n@inject(alias=IRandomDataGenerator)\nclass RandomDataGenerator:\n def __init__(self,\n random_config: RandomConfig,\n metadata: SensorMetadata) -> None:\n self.__config = random_config\n self.__sensor_metadata = metadata\n self.__buffer: list = [self.__generate_random_number()]\n\n def __generate_random_number(self) -> float:\n return uniform(self.__config.min_value, self.__config.max_value)\n\n def __generate_approximate_random_number(self) -> float:\n \"\"\" Generate a random number between min_value and max_value.\n The number will be close to the average of the last buffer numbers. \"\"\"\n avg = sum(self.__buffer) / len(self.__buffer)\n new_value = uniform(max(avg - 1, self.__config.min_value),\n min(avg + 1, self.__config.max_value))\n\n new_value = round(new_value, 3)\n self.__buffer.append(new_value)\n # slice the list to keep only the last buffer_size elements, sliding the window\n self.__buffer = self.__buffer[-self.__config.max_buffer_size:]\n return new_value\n\n def generate_sensor_data(self) -> SensorData:\n return SensorData(\n value=self.__generate_approximate_random_number(),\n timestamp=datetime.now(),\n metadata=self.__sensor_metadata\n )\n","repo_name":"rcbop/python-timeseries-exercise","sub_path":"data-sensor/sensor/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"72967764454","text":"#coding utf-8\nclass PID(object):\n \"\"\"docstring for PID.\"\"\"\n\n def __init__(self, Kp, Ti, Td, minOut, maxOut):\n super(PID, self).__init__()\n self.Kp = Kp\n self.Ti = Ti\n self.Td = Td\n self.integral = 0.\n self.last_error = 0.\n\n self.minOut = minOut\n self.maxOut = maxOut\n\n def update(self, error):\n proportional = error*self.Kp\n derivate = (error - self.last_error)*self.Td\n self.integral += error*self.Ti\n self.last_error = error\n if self.integral > self.maxOut:\n self.integral = self.maxOut\n elif self.integral < self.minOut:\n self.integral = self.minOut\n output = proportional + derivate + self.integral\n if output > self.maxOut:\n output = self.maxOut\n elif output < self.minOut:\n output = self.minOut\n return output\n\n def setPID(self, Kp, Ti, Td):\n self.Kp = Kp\n self.Ti = Ti\n self.Td = Td\n","repo_name":"Starfunx/Robot_Simulation","sub_path":"PID.py","file_name":"PID.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"72888233254","text":"\n\nfrom queue import Queue\n\nclass Duilie():\n \"\"\"队列的使用\"\"\"\n\n\n\n def q_duilie(self):\n \"\"\"队列的基本操作\"\"\"\n q = Queue()\n for i in range(10):\n print(\"队列存入10个数\")\n q.put(i)\n\n print(\"打印队列里面的消息\")\n while not q.empty():\n print(q.get())\n\n\nif __name__ == \"__main__\":\n duilie = Duilie()\n duilie.q_duilie()","repo_name":"xiejian1/yunwei","sub_path":"selenium/selenium_demo/duilie/demo_duilie.py","file_name":"demo_duilie.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"16379393684","text":"# Basic infrastructure for Bubble Shooter\n\nimport simplegui\nimport random\nimport math\n\n# Global constants\nWIDTH = 800\nHEIGHT = 600\nFIRING_POSITION = [WIDTH // 2, HEIGHT]\nFIRING_LINE_LENGTH = 60\nFIRING_ANGLE_VEL_INC = 0.02\nBUBBLE_RADIUS = 20\nCOLOR_LIST = [\"Red\", \"Green\", \"Blue\", \"White\"]\n\n# global variables\nfiring_angle = math.pi / 2\nfiring_angle_vel = 0\nbubble_stuck = True\nleft = False\nright = False\n# helper functions to handle transformations\ndef angle_to_vector(ang):\n return [math.cos(ang), math.sin(ang)]\n\ndef dist(p,q):\n return math.sqrt((p[0]-q[0])**2+(p[1]-q[1])**2)\n\n\n# class defintion for Bubbles\nclass Bubble:\n global firing_angle\n def __init__(self):\n self.pos = [WIDTH // 2, HEIGHT]\n self.vel = [0.0, 0.0]\n self.color = random.choice(COLOR_LIST)\n self.sound = simplegui.load_sound('http://commondatastorage.googleapis.com/codeskulptor-assets/Epoq-Lepidoptera.ogg')\n \n def update(self):\n self.pos[0] += self.vel[0]\n self.pos[1] += self.vel[1]\n if self.pos[0] < BUBBLE_RADIUS or self.pos[0] > WIDTH-BUBBLE_RADIUS:\n self.vel[0] = -self.vel[0]\n if self.pos[1] < BUBBLE_RADIUS or self.pos[1] > HEIGHT:\n self.vel[1] = -self.vel[1]\n \n \n def fire_bubble(self, vel):\n self.vel = vel\n self.sound.play()\n def is_stuck(self): \n pass\n\n def collide(self, bubble):\n pass\n \n def draw(self, canvas):\n canvas.draw_circle(self.pos, BUBBLE_RADIUS, 2, self.color)\n \n\n# define keyhandlers to control firing_angle\ndef keydown(key):\n global a_bubble, firing_angle, firing_angle_vel, bubble_stuck, left, right\n if key == simplegui.KEY_MAP['left']:\n left = True\n if key == simplegui.KEY_MAP['right']:\n right = True\n if key == simplegui.KEY_MAP['space']:\n a_bubble.fire_bubble(angle_to_vector(firing_angle)*2)\n\ndef keyup(key):\n global firing_angle_vel, left, right, a_bubble\n if key == simplegui.KEY_MAP['left']:\n left = False\n firing_angle_vel = 0\n if key == simplegui.KEY_MAP['right']:\n right = False\n firing_angle_vel = 0\n \n# define draw handler\ndef draw(canvas):\n global left, firing_angle, a_bubble, bubble_stuck, firing_angle_vel, FIRING_ANGLE_VEL_INC\n \n # update firing angle\n if left:\n firing_angle_vel += FIRING_ANGLE_VEL_INC\n firing_angle += firing_angle_vel\n if right:\n firing_angle_vel += FIRING_ANGLE_VEL_INC\n firing_angle -= firing_angle_vel\n # draw firing line\n endpoint = [FIRING_POSITION[0]+FIRING_LINE_LENGTH*angle_to_vector(firing_angle)[0],FIRING_POSITION[1]-FIRING_LINE_LENGTH*angle_to_vector(firing_angle)[1]]\n canvas.draw_line(FIRING_POSITION, endpoint, 5, 'Blue')\n # update a_bubble and check for sticking \n a_bubble.update()\n a_bubble.draw(canvas)\n # draw a bubble and stuck bubbles\n \n# create frame and register handlers\nframe = simplegui.create_frame(\"Bubble Shooter\", WIDTH, HEIGHT)\nframe.set_keydown_handler(keydown)\nframe.set_keyup_handler(keyup)\nframe.set_draw_handler(draw)\na_bubble = Bubble()\n# create initial buble and start frame\nframe.start()\n","repo_name":"angiayeah/LearnPython","sub_path":"bubble_shoot/bubble_shoot.py","file_name":"bubble_shoot.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"23003491784","text":"# coding=utf-8\nimport json\nimport os\nimport cv2\nimport numpy as np\nimport sys\n'''\nmax min\n判断在地上的坐标才是有效的\n最大值的y坐标表示距离图片底部最近的距离\n最小值通过对小于中心值的点做聚类并且与最大值到中心的距离相等。比例缩放和平移\n计算 source ankle的平均值、最大最小值,\nankle positions\n对最大和最小的脚踝位置计算高度,\n'''\nlist_name = [\"Nose\",\"Neck\",\"RShoulder\",\"RElbow\",\"RWrist\",\"LShoulder\",\n \"LElbow\",\"LWrist\",\"MidHip\",\"RHip\",\"RKnee\",\"RAnkle\",\"LHip\",\n \"LKnee\",\"LAnkle\",\"REye\",\"LEye\",\"REar\",\"LEar\",\"LBigToe\",\n \"LSmallToe\",\"LHeel\",\"RBigToe\",\"RSmallToe\",\"RHeel\",\"Background\"]\n\n\npose_Candidate = [17,0,18,4,3,2,7,6,5,9,8,12,10,13,11,14]\npose_Candidate = [list_name[i] for i in pose_Candidate]\nmiddle_Candidate = ['MidHip','RHip','LHip','LKnee','RKnee']\nlow_Candidate = ['LAnkle','RAnkle','LBigToe','LSmallToe','LHeel','RBigToe','RSmallToe','RHeel']\ntop_Candidate = ['Nose','REye','LEye','REar','LEar']\n\ndef Get_List(path):\n files = os.listdir(path);\n dirList = []\n fileList = []\n for f in files:\n if (os.path.isdir(path + '/' + f)):\n if (f[0] == '.'):\n pass\n else:\n dirList.append(f)\n if (os.path.isfile(path + '/' + f)):\n fileList.append(f)\n return [dirList, fileList]\n\n\n\ndef text_save(filename, data):\n file = open(filename,'a')\n if len(data) == 2:\n file.write(str(data[0]))\n file.write('\\t')\n file.write(str(data[1]))\n file.write('\\n')\n else:\n file.write(str(data[0]))\n file.write('\\n')\n file.close()\n\ndef read_json_file(body_json_name):\n pose_dict = {}\n flag_dele = False\n with open(body_json_name, 'r') as load_f:\n load_dict = json.load(load_f)\n try:\n pose_list = load_dict['people'][0]['pose_keypoints_2d']\n except:\n flag_dele = True\n print(\"no pose\")\n return {}\n if not flag_dele and len(load_dict['people'][0]['pose_keypoints_2d']) != 75:\n print(\"no pose\")\n return {}\n for i in range(0, 75, 3):\n tmp = int(i / 3)\n pose_dict[list_name[tmp]] = [int(pose_list[i]), int((pose_list[i + 1]))]\n return pose_dict\n\ntarget_body_json_path = \"/media/kun/Dataset/Pose/DataSet/new_data/机械哥_bilibili/DensePoseProcess/body_json\"\ntarget_img_path = \"/media/kun/Dataset/Pose/DataSet/new_data/机械哥_bilibili/DensePoseProcess/cut_expend\"\n\nsource_body_json_path = \"/media/kun/Dataset/Pose/DataSet/new_data/video_06/DensePoseProcess/body_json\"\nsource_img_path = \"/media/kun/Dataset/Pose/DataSet/new_data/video_06/DensePoseProcess/cut_expend\"\n\n# 文件路径确定\n_,body_json_name_list = Get_List(source_body_json_path)\nbody_json_name_list.sort()\n_,source_img_name_list = Get_List(source_img_path)\nsource_img_name_list.sort()\n\n_,target_body_json_name_list = Get_List(target_body_json_path)\ntarget_body_json_name_list.sort()\n_,target_img_name_list = Get_List(target_img_path)\ntarget_img_name_list.sort()\n\n\nall_pose = []\nfor name_index in range(0,len(body_json_name_list),1):\n\n body_json_name = os.path.join(source_body_json_path, body_json_name_list[name_index])\n pose_dict = read_json_file(body_json_name)\n if len(pose_dict) == 0:\n continue\n # 坐标筛选\n tmp = [pose_dict[i] for i in pose_Candidate]\n all_pose.append(tmp)\n print(1.0*name_index/len(body_json_name_list))\nindex = 1000\nprint(\"start_test\")\nwhile 1:\n print(\"waity key please in put index for 0 ~ %d\"%len(target_img_name_list))\n test_path = index\n index+=1\n if test_path == 'break':\n break\n print(test_path)\n test_path = int(test_path)\n target_img = cv2.imread(os.path.join(target_img_path,target_img_name_list[test_path]))\n cv2.imshow('target_img',target_img)\n cv2.waitKey(0)\n\n print(\"start chack\")\n json_path = os.path.join(target_body_json_path,target_body_json_name_list[test_path])\n if os.path.isfile(json_path):\n pose_dict = read_json_file(json_path)\n else:\n print(\"file not exist\")\n continue\n tmp = [pose_dict[i] for i in pose_Candidate]\n dist_all = []\n for i in all_pose:\n dist = 0\n for j in range(len(i)):\n dist += abs(tmp[j][0]-i[j][0]) + abs(tmp[j][1]-i[j][1])\n dist_all.append(dist)\n index = dist_all.index(min(dist_all))\n print(\"get close img \" + body_json_name_list[index])\n source_img = cv2.imread(os.path.join(source_img_path,source_img_name_list[index]))\n cv2.imshow('source_img',source_img)\n cv2.waitKey(0)\nprint(\"finish all\")\n\n\n\n\n\n","repo_name":"Zhangkunyao/Opencv_Code","sub_path":"body_json.py","file_name":"body_json.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"23124724620","text":"import json\r\n\r\ndef save_room_wip(r:dict) -> str:\r\n \"\"\"saves the inputed form 'create_room()' (in 'main.py') to 'saved rooms'\r\n and increases the count in 'amount.json' (in 'saved rooms')\"\"\"\r\n\r\n with open(\"templates/admin_create_room.html\", \"r\") as d:\r\n raw_html = d.read()\r\n\r\n raw_html = part1(raw_html, r)\r\n raw_html = part2(raw_html, r)\r\n raw_html = part3(raw_html, r)\r\n raw_html = part4(raw_html, r)\r\n\r\n with open(\"saved rooms/amount.json\", \"r\") as d:\r\n file_name = json.loads(d.read()) + 1\r\n\r\n with open(\"saved rooms/amount.json\", \"w\") as d:\r\n d.write(json.dumps(file_name))\r\n\r\n file_name = str(file_name)\r\n\r\n x = r.get(\"roomname\")\r\n if x == \"\":\r\n file_name += \" no name\"\r\n else:\r\n file_name += \" \"\r\n file_name += x\r\n\r\n with open(f\"saved rooms/{file_name}.html\", \"w\") as d:\r\n d.write(raw_html)\r\n\r\n return file_name\r\n\r\n# the other functions are for helping ^\r\n\r\ndef part1(raw_html:str, r:dict) -> str:\r\n # find str ')\r\n # add f' value=\"{x}\"' infront of the '>'\r\n x = r.get(\"roomname\")\r\n if (x != \"\") and (x is not None):\r\n pos = 0\r\n to_find = '= len(to_find):\r\n p1 = raw_html[:pos]\r\n p2 = f' value=\"{x}\"'\r\n p3 = raw_html[pos:]\r\n\r\n raw_html = p1 + p2 + p3\r\n break\r\n else:\r\n found = 0\r\n\r\n return raw_html\r\n\r\ndef part2(raw_html:str, r:dict) -> str:\r\n def comile_question(nr:int) -> str:\r\n if f\"type{nr}\" in r:\r\n change_type = \"\"\r\n else:\r\n change_type = f\"change_input_type({nr});\"\r\n\r\n return f\"\"\"const par{nr} = document.createElement(\"P\");\r\npar{nr}.id = \"paragraph\" + {nr};\r\nconst question_input{nr} = document.createElement(\"INPUT\");\r\nquestion_input{nr}.type = \"text\";\r\nquestion_input{nr}.name = \"question\" + {nr};\r\nquestion_input{nr}.id = question_input{nr}.name;\r\nquestion_input{nr}.placeholder = \"Please enter question.\";\r\nquestion_input{nr}.value = \"{r[f\"question{nr}\"]}\"\r\nconst button_remove{nr} = document.createElement(\"BUTTON\");\r\nbutton_remove{nr}.addEventListener('click', () => {\"{\"}\r\n remove(\"paragraph\" + {nr});\r\n for(let i = 0; i < question_ids.length; i++){\"{\"} \r\n if( question_ids[i] == {nr}){\"{\"} \r\n question_ids.splice(i, 1); \r\n {\"}\"}\r\n {\"}\"}\r\n document.getElementById(\"ids_list\").value = question_ids;\r\n event.preventDefault();\r\n{\"}\"});\r\nbutton_remove{nr}.innerHTML = \"×\";\r\nconst input_type{nr} = document.createElement(\"INPUT\");\r\ninput_type{nr}.type = \"range\";\r\ninput_type{nr}.min = \"0\";\r\ninput_type{nr}.max = \"{r[f\"numbers{nr}\"]}\";\r\ninput_type{nr}.value = \"0\";\r\ninput_type{nr}.id = \"type\" + {nr};\r\ninput_type{nr}.name = \"type\" + {nr};\r\nconst range_numbers{nr} = document.createElement(\"INPUT\");\r\nrange_numbers{nr}.type = \"number\";\r\nrange_numbers{nr}.min = \"2\";\r\nrange_numbers{nr}.value = \"{r[f\"numbers{nr}\"]}\";\r\nrange_numbers{nr}.id = \"numbers\" + {nr};\r\nrange_numbers{nr}.name = \"numbers\" + {nr};\r\nrange_numbers{nr}.oninput = () => {\"{\"}\r\n if(input_type{nr}.type == \"range\"){\"{\"}\r\n input_type{nr}.max = range_numbers{nr}.value;\r\n {\"}\"};\r\n{\"}\"};\r\nconst button_change_input_type{nr} = document.createElement(\"BUTTON\");\r\nbutton_change_input_type{nr}.addEventListener('click', () => {\"{\"}\r\n change_input_type({nr});\r\n event.preventDefault();\r\n{\"}\"});\r\nbutton_change_input_type{nr}.innerText = \"Change input type\";\r\npar{nr}.appendChild(document.createElement(\"HR\"))\r\npar{nr}.appendChild(question_input{nr});\r\npar{nr}.appendChild(button_remove{nr});\r\npar{nr}.appendChild(document.createElement(\"BR\"));\r\npar{nr}.appendChild(input_type{nr});\r\npar{nr}.appendChild(document.createElement(\"BR\"));\r\npar{nr}.appendChild(range_numbers{nr});\r\npar{nr}.appendChild(document.createElement(\"BR\"));\r\npar{nr}.appendChild(button_change_input_type{nr});\r\ndocument.getElementById(\"questions\").appendChild(par{nr});\r\n{change_type}\r\n\"\"\"\r\n # add questions\r\n x = r.get(\"ids_list\")\r\n if (x != \"\"):\r\n try:\r\n x = list(x)\r\n to_remove = []\r\n for i in x:\r\n if i == \",\":\r\n to_remove.append(i)\r\n for i in to_remove:\r\n x.remove(i)\r\n except:\r\n return raw_html\r\n\r\n script = \"\\n\"\r\n for i in x:\r\n try:\r\n i = int(i)\r\n except:\r\n return raw_html\r\n\r\n script += comile_question(i)\r\n script += \"\\n\"\r\n\r\n script += 'document.getElementById(\"ids_list\").value = question_ids;\\n'\r\n script += \"\\n\"\r\n\r\n l = len(raw_html) - len(\"\\t\\n{% endblock %}\")\r\n p1 = raw_html[:l]\r\n raw_html = p1 + script + \"{% endblock %}\"\r\n\r\n return raw_html\r\n\r\ndef part3(raw_html:str, r:dict):\r\n # change \"question_id = 0;\" to f\"question_id = {int(x[-1])};\"\r\n x = r.get(\"ids_list\")\r\n if (x != \"\"):\r\n try:\r\n x = list(x)\r\n except:\r\n return raw_html\r\n\r\n pos = 0\r\n to_find = 'question_id = 0;'\r\n found = 0\r\n for i in raw_html:\r\n pos += 1\r\n if i == to_find[found]:\r\n found += 1\r\n if found >= len(to_find):\r\n p1 = raw_html[:(pos - len(to_find))]\r\n p2 = f\"question_id = {int(x[-1])};\"\r\n p3 = raw_html[pos:]\r\n\r\n raw_html = p1 + p2 + p3\r\n break\r\n else:\r\n found = 0\r\n\r\n return raw_html\r\n\r\ndef part4(raw_html:str, r:dict):\r\n # change \"question_ids = [];\" to f\"question_ids = {r.get(\"ids_list\")};\"\r\n x = r.get(\"ids_list\")\r\n\r\n pos = 0\r\n to_find = 'question_ids = [];'\r\n found = 0\r\n for i in raw_html:\r\n pos += 1\r\n if i == to_find[found]:\r\n found += 1\r\n if found >= len(to_find):\r\n p1 = raw_html[:(pos - len(to_find))]\r\n p2 = f'question_ids = [{r.get(\"ids_list\")}];'\r\n p3 = raw_html[pos:]\r\n\r\n raw_html = p1 + p2 + p3\r\n break\r\n else:\r\n found = 0\r\n\r\n return raw_html","repo_name":"Samuel-Risner/voter","sub_path":"save/save_room_wip.py","file_name":"save_room_wip.py","file_ext":"py","file_size_in_byte":6481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"23136186712","text":"\n# coding: utf-8\n\n# In[11]:\n\n\nimport gc\nimport numpy as np\nimport matplotlib.pyplot as plt\n#get_ipython().magic(u'matplotlib inline')\nimport skimage\nfrom skimage import data, io, filters, morphology, feature, util, transform\n#from skimage.feature import register_translation\n#from skimage.feature.register_translation import _upsampled_dft\nfrom scipy.ndimage import fourier_shift\n\n#user var\n#basePath = \"/home/francesco/Downloads/imgs_orig32bit_orig8bit_outFeat/output_feat_linee/\"\nbasePath = \"/home/francesco/Seafile/PHD/imageAlign/testPy/output_feat_lines/\"\nimgNum1 = 5 # riferimento per Y\nimgNum2 = 6 # Immagine da registrare su una pre-esistente \n#imgNum3 = 6 # riferimento X\n\nImgPath1 = \"featExt\" + str(imgNum1) + \".png\"\nImgPath2 = \"featExt\" + str(imgNum2) + \".png\"\n#ImgPath3 = \"featExt\" + str(imgNum3) + \".png\"\nprint(\"Loading images\")\nimage1 = io.imread(basePath+ImgPath1)\nimage2 = io.imread(basePath+ImgPath2)\n#image3 = io.imread(basePath+ImgPath3)\n#fig setup\nfig = plt.figure(figsize=(12, 9))\nax1 = plt.subplot(1, 3, 1, adjustable='box-forced')\nax2 = plt.subplot(1, 3, 2, sharex=ax1, sharey=ax1, adjustable='box-forced')\nax3 = plt.subplot(1, 3, 3, sharex=ax1, sharey=ax1, adjustable='box-forced')\n\nax1.imshow(image1, cmap='gray')\nax1.set_axis_off()\nax1.set_title('Reference Image:'+str(imgNum1))\n\nax2.imshow(image2, cmap='gray')\nax2.set_axis_off()\nax2.set_title('Image to align:' + str(imgNum2))\n\n\"\"\"\nax3.imshow(image3, cmap='gray')\nax3.set_axis_off()\nax3.set_title('Image3 X')\n\"\"\"\n\n\n\nprint(\"Detecting...\")\nshiftY, errorY, diffphaseY = skimage.feature.register_translation(image1, image2, 1)\n#shiftX, errorX, diffphaseX = skimage.feature.register_translation(image3, image2, 1000)\nprint(\"Detected subpixel offset (y, x): {}\".format(shiftY))\nprint(\"Shifting...\")\n\noffset_imageY = fourier_shift(np.fft.fftn(image2), shiftY)\noffset_imageY = np.fft.ifftn(offset_imageY)\noffset_imageY = offset_imageY.real\n#image1 = image1.astype(np.float)\noffset_imageY = (offset_imageY-np.amin(offset_imageY))/np.amax(offset_imageY)\n\n\"\"\"\noffset_imageX = fourier_shift(np.fft.fftn(image3), shiftX)\noffset_imageX = np.fft.ifftn(offset_imageX)\noffset_imageX = offset_imageX.real\n\"\"\"\n\n'''\ntform = skimage.transform.SimilarityTransform(translation = [shift[1],shift[0]])\noffset_image1 = skimage.transform.warp(image2,tform)\n'''\n\nimage1 = image1.astype(np.float)\nimage1 = (image1-np.amin(image1))/np.amax(image1)\n\n#offset_imageX = offset_imageX.astype(np.float)\n#offset_imageX = offset_imageX/np.amax(offset_imageX)\n\nax3.imshow(offset_imageY, cmap='gray')\nax3.set_axis_off()\nax3.set_title('Image translated')\n\nplt.show()\n\n\"\"\"\noffset_imageY = offset_imageY.astype(np.float)\noffset_imageY = offset_imageY/np.amax(offset_imageY)\n\"\"\"\n#io.imsave('tmpOffset.png',offset_image1)\n#offset_image = io.imread('tmpOffset.png')\n#offset_image = offset_image1.astype(np.float)/np.amax(offset_image)\n'''\noffset_image_color = skimage.color.gray2rgb(offset_image1) * [1,0,0]\noffset_image_color = offset_image1_color.astype(np.float)\nimage1color = skimage.color.gray2rgb(image1) * [0,0,1]\nimage1color = image1Color.astype(np.float)\n'''\n\n#Overlapped = (offset_imageY + image1 + offset_imageX)*0.0 + (offset_imageY * image1 * offset_imageX)*0.99\nZeroTensor = np.zeros((image1.shape[0],image1.shape[1],3)) #color image\nredTensor = ZeroTensor.copy()\nblueTensor = ZeroTensor.copy()\n\nredTensor[:,:,0] = ((offset_imageY/np.amax(offset_imageY)) >0.1).astype(np.float)\nblueTensor[:,:,2] = ((image1/np.amax(image1)) >0.1).astype(np.float)\n\nOverlapped = redTensor + blueTensor\n#Overlapped = (offset_imageY + image1)*0.2 + (offset_imageY * image1)*0.8\n#Overlapped = Overlapped/np.amax(Overlapped)\n#Overlapped = Overlapped.astype(np.float)\n\nfig2 = plt.figure(figsize=(24, 18))\nax4 = plt.subplot(1, 3, 3,sharex=ax1, sharey=ax1, adjustable='box-forced')\n#ax4.imshow(Overlapped, cmap = 'gray')\nax4.imshow(Overlapped)\n#ax3.imshow(image1color)\nax4.set_axis_off()\nax4.set_title('Ref. Image x Shifted image2')\nplt.show()\nio.imsave(\"overlapped_lines/im_\" + str(imgNum1) + \"_\" + str(imgNum2) + \".png\",Overlapped)\n\ntransFileId = open(\"overlapped_lines/pos_\" + str(imgNum1) + \"_\" + str(imgNum2) + \".txt\",\"w\") \ntransFileId.write(\"[{x};{y}]\".format(x=shiftY[1],y=shiftY[0])) \ntransFileId.close()\n\ngc.collect()\n\nprint('done')\n\n#xraw = [0, 229.0, 229.0, 27.0, 0, 228.0, 229.0, 227.0, 0, 228.0, 229.0, 228.0]\n#yraw = [0, 0.0, -1.0, -186.0, 0, -2.0, -3.0, 0.0, 0, 0.0, 1.0, 1.0]\n\n\n","repo_name":"LonglonWu/PtychoAlignTools","sub_path":"src/auto/edge/test_registerTranslation.py","file_name":"test_registerTranslation.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"27651940815","text":"import cv2\nimport mediapipe as mp\nimport pyglet\nfrom pyglet import shapes\nimport threading\nfrom gameClasses import Dot\nmp_hands = mp.solutions.hands\nmp_drawing = mp.solutions.drawing_utils\nmp_drawing_styles = mp.solutions.drawing_styles\n\n\n\n\n\n\n\n\n\nclass FingerObject(pyglet.window.Window):\n\n def __init__(self, width, height):\n super().__init__(width, height, \"Fingers\")\n self.height = height\n self.width = width\n self.window = super()\n self.batch = pyglet.graphics.Batch()\n self.circle = shapes.Circle(360, 240, 10, color=(100, 255, 0), batch=self.batch)\n self.circle.opacity = 100\n self.webcam = cv2.VideoCapture(0)\n self.count = 0\n\n self.apple_list = list() #Todo replace with clever matrix\n print(\"inited\")\n\n def on_draw(self):\n self.window.clear()\n self.batch.draw()\n for apple in self.apple_list:\n apple.draw()\n\n def update(self, delta_time):\n if cv2.waitKey(1) & 0xFF == 27:\n self.quit()\n\n self.check_collisions()\n if self.count == 30:\n self.apple_list.append(Dot(self.width, self.height))\n self.apple_list[-1].draw()\n self.count = 0\n frame = self.getFrame()\n if frame == -1:\n return\n frame.x = 1 - frame.x\n frame.y = 1 - frame.y\n self.circle.position = (frame.x * self.width, frame.y * self.height)\n\n self.count += 1\n print(self.count)\n\n def quit(self):\n\n self.webcam.release()\n cv2.destroyAllWindows()\n\n def check_collisions(self):\n for apple in self.apple_list:\n if apple.collision(self.circle.position, self.circle.radius):\n self.apple_list.remove(apple)\n self.circle.radius += 5\n\n def getFrame(self):\n\n pointer = -1\n with mp_hands.Hands(\n static_image_mode=False,\n max_num_hands=1,\n min_detection_confidence=0.3,\n min_tracking_confidence=0.5) as hands:\n success, image = self.webcam.read()\n\n if not success:\n print(\"Try reading again\")\n return pointer\n\n image.flags.writeable = False\n results = hands.process(image)\n\n image.flags.writeable = True\n\n if results.multi_hand_landmarks:\n pointer = results.multi_hand_landmarks[0].landmark[8]\n for hand_landmarks in results.multi_hand_landmarks:\n mp_drawing.draw_landmarks(\n image,\n hand_landmarks,\n mp_hands.HAND_CONNECTIONS,\n mp_drawing_styles.get_default_hand_landmarks_style(),\n mp_drawing_styles.get_default_hand_connections_style())\n\n cv2.imshow('MediaPipe Hands', cv2.flip(image, 1))\n\n\n\n return pointer\n\n\n\n\n# def vision(finger):\n# with mp_hands.Hands(\n# static_image_mode=False,\n# max_num_hands=2,\n# min_detection_confidence=0.2,\n# min_tracking_confidence=0.5) as hands:\n#\n# while webcam.isOpened():\n# success, image = webcam.read()\n# if not success:\n# print(\"Ignoring empty frame\")\n# continue\n#\n# image.flags.writeable = False\n# results = hands.process(image)\n#\n# image.flags.writeable = True\n#\n# if results.multi_hand_landmarks:\n# x = results.multi_hand_landmarks[0].landmark[8]\n# for hand_landmarks in results.multi_hand_landmarks:\n# mp_drawing.draw_landmarks(\n# image,\n# hand_landmarks,\n# mp_hands.HAND_CONNECTIONS,\n# mp_drawing_styles.get_default_hand_landmarks_style(),\n# mp_drawing_styles.get_default_hand_connections_style())\n#\n# finger.update(x.x, x.y)\n#\n# cv2.imshow('MediaPipe Hands', cv2.flip(image, 1))\n#\n# if cv2.waitKey(1) & 0xFF == 27:\n# break\n#\n# webcam.release()\n# cv2.destroyAllWindows()\n\nif __name__ == \"__main__\":\n fingy = FingerObject(720, 480)\n\n pyglet.clock.schedule_interval(fingy.update, 1/30)\n pyglet.app.run()","repo_name":"edwardburns1/HandGun","sub_path":"src/handgun.py","file_name":"handgun.py","file_ext":"py","file_size_in_byte":4386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"71081397414","text":"import re\nfrom collections import UserDict\nfrom datetime import datetime\nfrom datetime import date\nimport pickle\n\n\nclass Field:\n def __init__(self, value) -> None:\n self.value = value\n\n def __str__(self) -> str:\n return f'{self.value}'\n\n\nclass Name(Field):\n pass\n\n\nclass Phone(Field):\n def __init__(self, value) -> None:\n super().__init__(value)\n self._value = None\n self.value = value\n\n @property\n def value(self) -> str:\n return self._value\n\n @value.setter\n def value(self, value):\n value = (\n value.strip()\n .removeprefix(\"+\")\n .replace(\"-\", \"\")\n .replace(\" \", \"\")\n .replace(\"(\", \"\")\n .replace(\")\", \"\")\n )\n self._value = value\n\n\nclass Birthday(Field):\n\n def __init__(self, value):\n super().__init__(value)\n self._value = None\n self.value = value\n\n @property\n def value(self):\n return self._value\n\n @value.setter\n def value(self, value):\n if value:\n try:\n datetime.strptime(value, \"%d.%m.%Y\")\n except ValueError:\n raise ValueError(\"Incorrect data format, should be DD.MM.YYYY\")\n self._value = value\n\n\nclass Record:\n def __init__(self, name: Name, phones=[], birthday: Birthday = None):\n self.name = name\n self.phone_list = phones\n self.birthday = birthday\n\n def __str__(self) -> str:\n return f'User {self.name} - Phones: {\", \".join([phone.value for phone in self.phone_list])}' \\\n f' - Birthday: {self.birthday} '\n\n def add_phone(self, phone: Phone):\n self.phone_list.append(phone)\n\n def del_phone(self, phone: Phone):\n self.phone_list.remove(phone)\n\n def edit_phone(self, old_number: Phone, new_number: Phone):\n self.phone_list.remove(old_number)\n self.phone_list.append(new_number)\n\n def days_to_birthday(self):\n if self.birthday:\n start = date.today()\n birthday_date = datetime.strptime(str(self.birthday), '%d.%m.%Y')\n end = date(year=start.year, month=birthday_date.month,\n day=birthday_date.day)\n count_days = (end - start).days\n if count_days < 0:\n count_days += 365\n return count_days\n else:\n return 'Unknown birthday'\n\n def delete_phone(self, phone):\n self.phone.remove(phone)\n\n\nclass AddressBook(UserDict):\n def __init__(self):\n super().__init__()\n self.n = None\n\n def add_record(self, record: Record) -> None:\n self.data[record.name.value] = record\n\n def iterator(self, n=2, days=0):\n self.n = n\n index = 1\n print_block = '-' * 50 + '\\n'\n for record in self.data.values():\n if days == 0 or (record.birthday.value is not None and record.days_to_birthday(record.birthday) <= days):\n print_block += str(record) + '\\n'\n if index < n:\n index += 1\n else:\n yield print_block\n index, print_block = 1, '-' * 50 + '\\n'\n yield print_block\n\n\nclass InputError:\n def __init__(self, func):\n self.func = func\n\n def __call__(self, contacts, *args):\n try:\n return self.func(contacts, *args)\n except IndexError as e:\n return str(e)\n except KeyError as e:\n return str(e)\n except ValueError as e:\n return str(e)\n\n\ndef say_hello(*args):\n return 'Hello! Can I help you?'\n\n\n@InputError\ndef add(contacts, *args):\n name = Name(args[0])\n phone = Phone(args[1])\n try:\n birthday = Birthday(args[2])\n except IndexError:\n birthday = None\n if name.value in contacts:\n contacts[name.value].add_phone(phone)\n writing_db(contacts)\n return f'Add phone {phone} to user {name}'\n else:\n contacts[name.value] = Record(name, [phone], birthday)\n writing_db(contacts)\n return f'Add user {name} with phone number {phone}'\n\n\n@InputError\ndef change(contacts, *args):\n name, old_phone, new_phone = args[0], args[1], args[2]\n contacts[name].edit_phone(Phone(old_phone), Phone(new_phone))\n writing_db(contacts)\n return \"Number is changed!\"\n\n\n@InputError\ndef get_phone(contacts, *args):\n name = args[0]\n number = contacts[name]\n return f\"User number is {number}\"\n\n\n@InputError\ndef del_phone(contacts, *args):\n name, phone = args[0], args[1]\n contacts[name].del_phone(Phone(phone))\n writing_db(contacts)\n return f'Delete phone {phone} from user {name}'\n\n\ndef show_all(contacts, *args):\n if not contacts:\n return 'Address book is empty'\n result = 'List of all users:\\n'\n # print_list = contacts.iterator()\n for username, phone in contacts.items():\n return (f\"{username} number {phone}\")\n return result\n\n\ndef birthday(contacts, *args):\n if args:\n name = args[0]\n return f'{contacts[name].birthday}'\n\n\ndef show_birthday_30_days(contacts, *args):\n result = 'List of users with birthday in 30 days:'\n for key in contacts:\n if contacts[key].days_to_birthday() <= 30:\n result += f'\\n{contacts[key]}'\n return result\n\n\ndef say_good_bye(*args):\n return 'Good bye!'\n\n\ndef unknown_command(*args):\n return 'Unknown command! Enter again!'\n\n\nfile_name = 'contact_book.txt'\n\n\ndef reading_db(file_name):\n with open(file_name, \"rb\") as fh:\n try:\n unpacked = pickle.load(fh)\n except EOFError:\n unpacked = AddressBook()\n return unpacked\n\n\ndef writing_db(contacts):\n with open(file_name, \"wb\") as fh:\n pickle.dump(contacts, fh)\n\n\n@InputError\ndef find(contacts, *args):\n args_str = ''\n for i in args:\n args_str += i + ' '\n user_request = '[' + args_str.lower()[:-1] + ']{2,}'\n reg_exp = fr'{user_request}'\n result = f'List with matches:\\n'\n for value in contacts.values():\n match = re.findall(reg_exp, str(value).lower())\n if str(value).find(str(match)) and len(match):\n result += f'{str(value)}'+'\\n'\n return result\n\n\ncontact_command = {say_hello: ['hello'], add: ['add '], change: ['change '], get_phone: ['phone '],\n show_all: ['show all'], say_good_bye: ['good bye', 'close', 'exit'],\n del_phone: ['del '], birthday: ['birthday '],\n find: ['find ']}\n\n\ndef command_parser(user_command: str):\n for key, list_value in contact_command.items():\n for value in list_value:\n if user_command.lower().startswith(value):\n args = user_command[len(value):].split()\n return key, args\n else:\n return unknown_command, []\n\n\ndef main():\n contacts = reading_db(file_name)\n while True:\n user_command = input(\"Please input command: \")\n command, data = command_parser(user_command)\n print(command(contacts, *data))\n if command is say_good_bye:\n break\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Itehnolog/Home_works","sub_path":"Home_work_12/HW_12.py","file_name":"HW_12.py","file_ext":"py","file_size_in_byte":7130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"13342765578","text":"import time\nimport random\n\nPACE=30 #Pace command use for n seconds between use\nprevtime = 0 #Previous time of use\n\nNAME=\"Choice bot command\"\nDESC=\"Picks from a user-supplied, comma-delineated list of things\"\n\ndef initModule(cod):\n cod.addBotCommand(\"CHOICE\", commandCHOICE)\n\ndef destroyModule(cod):\n del cod.botcommands[\"CHOICE\"]\n\ndef commandCHOICE(cod, line, splitline, source, destination):\n global prevtime, PACE\n\n choices = \" \".join(splitline[1:])\n choices = choices.split(\", \")\n\n if len(choices) == 0 or len(choices) == 1:\n cod.reply(source, destination, \"BAD \" + source)\n return\n\n choice = random.choice(choices)\n\n cod.reply(source, destination, \"Result: \" + choice)\n\n","repo_name":"Xe/code","sub_path":"irc/asparagus/modules/choice.py","file_name":"choice.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"9"} +{"seq_id":"10868170022","text":"'''https://github.com/sniklaus/pytorch-hed/\n'''\n\nfrom PIL import Image\nimport torch\nimport torchvision.transforms.functional as TF\n\nimport matplotlib.pyplot as plt\n\n\nclass Network(torch.nn.Module):\n def __init__(self):\n super().__init__()\n\n self.netVggOne = torch.nn.Sequential(\n torch.nn.Conv2d(\n in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n )\n\n self.netVggTwo = torch.nn.Sequential(\n torch.nn.MaxPool2d(kernel_size=2, stride=2),\n torch.nn.Conv2d(\n in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n )\n\n self.netVggThr = torch.nn.Sequential(\n torch.nn.MaxPool2d(kernel_size=2, stride=2),\n torch.nn.Conv2d(\n in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n )\n\n self.netVggFou = torch.nn.Sequential(\n torch.nn.MaxPool2d(kernel_size=2, stride=2),\n torch.nn.Conv2d(\n in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n )\n\n self.netVggFiv = torch.nn.Sequential(\n torch.nn.MaxPool2d(kernel_size=2, stride=2),\n torch.nn.Conv2d(\n in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n torch.nn.Conv2d(\n in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1\n ),\n torch.nn.ReLU(inplace=False),\n )\n\n self.netScoreOne = torch.nn.Conv2d(\n in_channels=64, out_channels=1, kernel_size=1, stride=1, padding=0\n )\n self.netScoreTwo = torch.nn.Conv2d(\n in_channels=128, out_channels=1, kernel_size=1, stride=1, padding=0\n )\n self.netScoreThr = torch.nn.Conv2d(\n in_channels=256, out_channels=1, kernel_size=1, stride=1, padding=0\n )\n self.netScoreFou = torch.nn.Conv2d(\n in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0\n )\n self.netScoreFiv = torch.nn.Conv2d(\n in_channels=512, out_channels=1, kernel_size=1, stride=1, padding=0\n )\n\n self.netCombine = torch.nn.Sequential(\n torch.nn.Conv2d(\n in_channels=5, out_channels=1, kernel_size=1, stride=1, padding=0\n ),\n torch.nn.Sigmoid(),\n )\n # end\n\n def forward(self, image):\n tenBlue = (image[:, 0:1, :, :] * 255.0) - 104.00698793\n tenGreen = (image[:, 1:2, :, :] * 255.0) - 116.66876762\n tenRed = (image[:, 2:3, :, :] * 255.0) - 122.67891434\n\n image = torch.cat([tenBlue, tenGreen, tenRed], 1)\n\n tenVggOne = self.netVggOne(image)\n tenVggTwo = self.netVggTwo(tenVggOne)\n tenVggThr = self.netVggThr(tenVggTwo)\n tenVggFou = self.netVggFou(tenVggThr)\n tenVggFiv = self.netVggFiv(tenVggFou)\n\n tenScoreOne = self.netScoreOne(tenVggOne)\n tenScoreTwo = self.netScoreTwo(tenVggTwo)\n tenScoreThr = self.netScoreThr(tenVggThr)\n tenScoreFou = self.netScoreFou(tenVggFou)\n tenScoreFiv = self.netScoreFiv(tenVggFiv)\n\n tenScoreOne = torch.nn.functional.interpolate(\n input=tenScoreOne,\n size=(image.shape[2], image.shape[3]),\n mode=\"bilinear\",\n align_corners=False,\n )\n tenScoreTwo = torch.nn.functional.interpolate(\n input=tenScoreTwo,\n size=(image.shape[2], image.shape[3]),\n mode=\"bilinear\",\n align_corners=False,\n )\n tenScoreThr = torch.nn.functional.interpolate(\n input=tenScoreThr,\n size=(image.shape[2], image.shape[3]),\n mode=\"bilinear\",\n align_corners=False,\n )\n tenScoreFou = torch.nn.functional.interpolate(\n input=tenScoreFou,\n size=(image.shape[2], image.shape[3]),\n mode=\"bilinear\",\n align_corners=False,\n )\n tenScoreFiv = torch.nn.functional.interpolate(\n input=tenScoreFiv,\n size=(image.shape[2], image.shape[3]),\n mode=\"bilinear\",\n align_corners=False,\n )\n\n return self.netCombine(\n torch.cat(\n [tenScoreOne, tenScoreTwo, tenScoreThr, tenScoreFou, tenScoreFiv], 1\n )\n )\n # end\n# end\n\n\n##########################################################\nif __name__ == '__main__':\n image = Image.open('example.png').resize((650, 650)).convert('RGB')\n image = TF.to_tensor(image)\n image.unsqueeze_(0)\n print(image.shape)\n\n model = Network()\n model.load_state_dict(\n {\n strKey.replace(\"module\", \"net\"): tenWeight\n for strKey, tenWeight in torch.hub.load_state_dict_from_url(\n url=\"http://content.sniklaus.com/github/pytorch-hed/network-bsds500.pytorch\",\n file_name=\"hed-bsds500\",\n ).items()\n }\n )\n model.eval()\n result = model(image)\n plt.imshow(result.detach().numpy()[0][0], 'binary')\n plt.savefig('result.jpg')\n","repo_name":"whatever60/w_SNN","sub_path":"hed.py","file_name":"hed.py","file_ext":"py","file_size_in_byte":6633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"24282610822","text":"import copy\n\n\n'''\nNOTE: This function is taken straight from\nhttps://stackoverflow.com/questions/45471152/how-to-create-a-sudoku-puzzle-in-python\nThis was not part of the scope that I wanted to practise but I still wanted to generate a new puzzle every time to \nreduce risk of having bugs.\n'''\ndef createBoard(base):\n side = base * base\n\n # pattern for a baseline valid solution\n def pattern(r, c): return (base * (r % base) + r // base + c) % side\n\n # randomize rows, columns and numbers (of valid base pattern)\n from random import sample\n def shuffle(s): return sample(s, len(s))\n\n rBase = range(base)\n # g is 0,1,2 randomised order --> g*base = 0,3,6 randomized order + 0,1,2 randomized order\n rows = [g * base + r for g in shuffle(rBase) for r in shuffle(rBase)]\n cols = [g * base + c for g in shuffle(rBase) for c in shuffle(rBase)]\n nums = shuffle(range(1, base * base + 1))\n\n # produce board using randomized baseline pattern\n board = [[nums[pattern(r, c)] for c in cols] for r in rows]\n\n squares = side * side\n empties = squares * 3 // 4\n for p in sample(range(squares), empties):\n board[p // side][p % side] = 0\n return board\n\n\ndef test(colIndex, rowIndex, num, board):\n if num in board[rowIndex]:\n return False\n if num in [row[colIndex] for row in board]:\n return False\n # Find left corner in current square\n squareRowStart = rowIndex - rowIndex % 3\n squareColStart = colIndex - colIndex % 3\n # Loop from left corner of current square to left corner+3 using slicing\n for row in board[squareRowStart:squareRowStart + 3]:\n if num in row[squareColStart:squareColStart + 3]:\n return False\n return True\n\n\ndef findEmptySpace(board):\n for rowIndex, row in enumerate(board):\n for colIndex, colValue in enumerate(row):\n if board[rowIndex][colIndex] == 0:\n return [rowIndex, colIndex]\n return [-1, -1]\n\n\n# The solver function, using recursion and backtracking\ndef solve(board):\n emptyCoordinates = findEmptySpace(board)\n # if no more empty coordinates we are done\n if emptyCoordinates == [-1, -1]:\n return True\n rowIndex, colIndex = emptyCoordinates[0], emptyCoordinates[1]\n for num in range(1, 10):\n if test(colIndex, rowIndex, num, board):\n board[rowIndex][colIndex] = num\n '''Try to solve the board recursively with our new cells, when the next one could not find a number \n (returned False) we try with the next number in the loop. If none of the numbers led to a solution we set\n the index to 0 and return False to trigger the backtracking'''\n if solve(board):\n return True\n board[rowIndex][colIndex] = 0\n return False\n\n\ndef getSolvedBoard(_board):\n # So both boards in UI doesn't get solved when we call this function\n board = copy.deepcopy(_board)\n solve(board)\n return board\n","repo_name":"Wholmgren95/Sudoku","sub_path":"Logic.py","file_name":"Logic.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"71466754215","text":"\"\"\"\nPC-BASIC - arrays.py\nArray variable management\n\n(c) 2013--2023 Rob Hagemans\nThis file is released under the GNU GPL version 3 or later.\n\"\"\"\n\nimport binascii\nimport struct\n\nfrom ...compat import iteritems, iterkeys\n\nfrom ..base import error\nfrom .. import values\nfrom .scalars import get_name_in_memory\n\n\nclass Arrays(object):\n\n def __init__(self, memory, values):\n \"\"\"Initialise arrays.\"\"\"\n self._memory = memory\n self._values = values\n self.clear()\n self.clear_base()\n\n def __contains__(self, varname):\n \"\"\"Check if a scalar has been defined.\"\"\"\n return varname in self._dims\n\n def __iter__(self):\n \"\"\"Return an iterable over all scalar names.\"\"\"\n return iterkeys(self._dims)\n\n def __repr__(self):\n \"\"\"Debugging representation of variable dictionary.\"\"\"\n return '\\n'.join(\n '%s%s: %s' % (\n n.decode('ascii'),\n v,\n binascii.hexlify(bytes(self._buffers[n])).decode('ascii')\n )\n for n, v in iteritems(self._dims)\n )\n\n def clear(self):\n \"\"\"Clear arrays.\"\"\"\n self._dims = {}\n self._buffers = {}\n self._array_memory = {}\n self.current = 0\n\n def erase_(self, args):\n \"\"\"Remove an array from memory.\"\"\"\n for name in args:\n name = self._memory.complete_name(name)\n if name not in self._dims:\n # IFC if array does not exist\n raise error.BASICError(error.IFC)\n dimensions = self._dims[name]\n record_len = 1 + max(3, len(name)) + 3 + 2*len(dimensions)\n freed_bytes = self._buffer_size(name, dimensions) + record_len\n erased_name_ptr, _ = self._array_memory[name]\n # delete buffers\n del self._dims[name]\n del self._buffers[name]\n del self._array_memory[name]\n # update memory model\n for name in self._array_memory:\n name_ptr, array_ptr = self._array_memory[name]\n if name_ptr > erased_name_ptr:\n self._array_memory[name] = name_ptr - freed_bytes, array_ptr - freed_bytes\n self.current -= freed_bytes\n # if all arrays have been cleared and array base was set to 0 implicitly by DIM, unset it\n # however, if array base was set explicitly by OPTION BASE, it remains set.\n if not self._dims and self._base_set_by_dim:\n self.clear_base()\n\n def index(self, index, dimensions):\n \"\"\"Return the flat index for a given dimensioned index.\"\"\"\n bigindex = 0\n area = 1\n for i in range(len(index)):\n # dimensions is the *maximum index number*, regardless of self._base\n bigindex += area * (index[i] - self._base)\n area *= dimensions[i] + 1 - self._base\n return bigindex\n\n def view_full_buffer(self, name):\n \"\"\"Return a memoryview to a full array.\"\"\"\n return memoryview(self._buffers[name])\n\n def dimensions(self, name):\n \"\"\"Return the dimensions of an array.\"\"\"\n return self._dims[name]\n\n def dim_(self, args):\n \"\"\"DIM: dimension arrays.\"\"\"\n for a in args:\n name, indices = a\n self.allocate(self._memory.complete_name(name), indices)\n\n @staticmethod\n def _record_size(name, dimensions):\n \"\"\"Calculate size of array record in bytes.\"\"\"\n # first two bytes: chars of name or 0 if name is one byte long\n return 1 + max(3, len(name)) + 3 + 2*len(dimensions)\n\n def flat_length(self, dimensions):\n \"\"\"Total number of elements.\"\"\"\n return self.index(dimensions, dimensions) + 1\n\n def _buffer_size(self, name, dimensions):\n \"\"\"Calculate size of array buffer in bytes.\"\"\"\n return self.flat_length(dimensions) * values.size_bytes(name)\n\n def memory_size(self, name, dimensions):\n \"\"\"Calculate size of array record and buffer in bytes.\"\"\"\n return self._record_size(name, dimensions) + self._buffer_size(name, dimensions)\n\n def allocate(self, name, dimensions):\n \"\"\"\n Allocate array space for an array of given dimensioned size.\n Raise errors if duplicate name or illegal index value.\n \"\"\"\n if not dimensions:\n # DIM A does nothing\n return\n if name in self._dims:\n raise error.BASICError(error.DUPLICATE_DEFINITION)\n # a call that raises ifc does not implicitly set the array base\n if any(_d < 0 for _d in dimensions):\n raise error.BASICError(error.IFC)\n # implicitly set array base\n if self._base is None:\n self._base = 0\n self._base_set_by_dim = True\n elif any(_d < self._base for _d in dimensions):\n raise error.BASICError(error.SUBSCRIPT_OUT_OF_RANGE)\n # update memory model\n name_ptr = self.current\n record_len = self._record_size(name, dimensions)\n array_bytes = self._buffer_size(name, dimensions)\n array_ptr = name_ptr + record_len\n total_bytes = record_len + array_bytes\n self._memory.check_free(total_bytes, error.OUT_OF_MEMORY)\n self.current += total_bytes\n self._array_memory[name] = (name_ptr, array_ptr)\n self._buffers[name] = bytearray(array_bytes)\n self._dims[name] = dimensions\n\n def check_dim(self, name, index):\n \"\"\"\n Check if an array has been allocated.\n If not, auto-allocate if indices are <= 10; raise error otherwise.\n \"\"\"\n try:\n dimensions = self._dims[name]\n except KeyError:\n # auto-dimension - 0..10 or 1..10\n # this even fixes the dimensions if the index turns out to be out of range\n dimensions = [10] * len(index)\n self.allocate(name, dimensions)\n lst = self._buffers[name]\n if len(index) != len(dimensions):\n raise error.BASICError(error.SUBSCRIPT_OUT_OF_RANGE)\n for i, d in zip(index, dimensions):\n if i < 0:\n raise error.BASICError(error.IFC)\n elif i < self._base or i > d:\n # dimensions is the *maximum index number*, regardless of self._base\n raise error.BASICError(error.SUBSCRIPT_OUT_OF_RANGE)\n return dimensions, lst\n\n def clear_base(self):\n \"\"\"Unset the array base.\"\"\"\n # OPTION BASE value. NONE: unset\n self._base = None\n # OPTION BASE set by DIM rather than explicitly\n self._base_set_by_dim = False\n\n def option_base_(self, args):\n \"\"\"Set the array base to 0 or 1 (OPTION BASE). Raise error if already set.\"\"\"\n base, = args\n base = int(base)\n if self._base is not None and base != self._base:\n # duplicate definition\n raise error.BASICError(error.DUPLICATE_DEFINITION)\n self._base = base\n\n def view_buffer(self, name, index):\n \"\"\"Return a memoryview to an array element.\"\"\"\n dimensions, lst = self.check_dim(name, index)\n bigindex = self.index(index, dimensions)\n bytesize = values.size_bytes(name)\n return memoryview(lst)[bigindex*bytesize:(bigindex+1)*bytesize]\n\n def get(self, name, index):\n \"\"\"Retrieve a view of the value of an array element.\"\"\"\n # do not make a copy - we may end up with stale string pointers\n # due to garbage collection\n return self._values.create(self.view_buffer(name, index))\n\n def set(self, name, index, value):\n \"\"\"Assign a value to an array element.\"\"\"\n if isinstance(value, values.String):\n self._memory.strings.fix_temporaries()\n # copy value into array\n self.view_buffer(name, index)[:] = values.to_type(name[-1:], value).to_bytes()\n # drop cache here\n\n def varptr(self, name, indices):\n \"\"\"Retrieve the address of an array.\"\"\"\n dimensions = self._dims[name]\n _, array_ptr = self._array_memory[name]\n # arrays are kept at the end of the var list\n return (\n self._memory.var_current() + array_ptr +\n values.size_bytes(name) * self.index(indices, dimensions)\n )\n\n def dereference(self, address):\n \"\"\"Get a value for an array given its pointer address.\"\"\"\n found_addr = -1\n found_name = None\n for name, data in iteritems(self._array_memory):\n addr = self._memory.var_current() + data[1]\n if addr > found_addr and addr <= address:\n found_addr = addr\n found_name = name\n if not found_name:\n return None\n lst = self._buffers[name]\n offset = address - found_addr\n return self._values.from_bytes(lst[offset : offset+values.size_bytes(name)])\n\n def get_memory(self, address):\n \"\"\"Retrieve data from data memory: array space \"\"\"\n name_addr = -1\n arr_addr = -1\n for name in self._array_memory:\n name_try, arr_try = self._array_memory[name]\n if name_try <= address and name_try > name_addr:\n name_addr, arr_addr = name_try, arr_try\n the_arr = name\n break\n else: # pragma: no cover\n return -1\n var_current = self._memory.var_current()\n dimensions = self._dims[the_arr]\n if address >= var_current + arr_addr:\n offset = address - arr_addr - var_current\n if offset >= self._buffer_size(the_arr, dimensions): # pragma: no cover\n return -1\n byte_array = self._buffers[the_arr]\n return ord(byte_array[offset:offset+1])\n else:\n offset = address - name_addr - var_current\n if offset < max(3, len(the_arr))+1:\n return get_name_in_memory(the_arr, offset)\n else:\n offset -= max(3, len(the_arr))+1\n data_rep = struct.pack(\n ' eps:\n nvals = ((val / avg) ** prob for val, prob in pointers)\n else:\n return 0\n\n coeff = gini(nvals)\n\n weight = sum(starmap(mul, pointers)) / sum(probs)\n\n wedge_print(\"Wedge: Decide: vals = %s, probs = %s\" % (str(vals), str(probs)))\n wedge_print(\"Wedge: Decide: coeff = %f, weight = %f\" % (coeff, weight))\n\n return coeff * weight\n\n def gini(arr):\n arr = sorted(arr, reverse=True)\n dividend = sum(starmap(mul, izip(arr, xrange(1, 2 * len(arr), 2))))\n divisor = len(arr) * sum(arr)\n return float(dividend) / divisor\n\n def compare_to_final_bounds(score1, score2):\n return score1 + score2 > bconfig.WEDGE_THRESHOLD\n\n def edge_sorting(edge):\n '''\n probability + certainty / 10\n '''\n return edge[2][0] + edge[2][1] / 10.\n\n if bconfig.DEBUG_CHECKS:\n assert cluster_set._debug_test_hate_relation()\n assert cluster_set._debug_duplicated_recs(mapping)\n bib_map = create_bib_2_cluster_dict(cluster_set)\n\n plus_edges, minus_edges, edges = group_edges(cluster_set)\n\n for i, (bib1, bib2) in enumerate(plus_edges):\n update_status(float(i) / len(plus_edges), \"Agglomerating obvious clusters...\")\n cl1 = bib_map[bib1]\n cl2 = bib_map[bib2]\n if cl1 != cl2 and not cl1.hates(cl2):\n join(cl1, cl2)\n cluster_set.clusters.remove(cl2)\n for v in cl2.bibs:\n bib_map[v] = cl1\n if bconfig.DEBUG_CHECKS:\n assert cluster_set._debug_test_hate_relation()\n assert cluster_set._debug_duplicated_recs(mapping)\n update_status_final(\"Agglomerating obvious clusters done.\")\n\n for i, (bib1, bib2) in enumerate(minus_edges):\n update_status(float(i) / len(minus_edges), \"Dividing obvious clusters...\")\n cl1 = bib_map[bib1]\n cl2 = bib_map[bib2]\n if cl1 != cl2 and not cl1.hates(cl2):\n cl1.quarrel(cl2)\n update_status_final(\"Dividing obvious clusters done.\")\n\n bibauthor_print(\"Sorting the value edges.\")\n edges = sorted(edges, key=edge_sorting, reverse=True)\n\n interval = 1000\n wedge_print(\"Wedge: New wedge, %d edges.\" % len(edges))\n for current, (v1, v2, unused) in enumerate(edges):\n if (current % interval) == 0:\n update_status(float(current) / len(edges), \"Wedge...\")\n\n assert unused != '+' and unused != '-'\n if bconfig.DEBUG_CHECKS:\n assert cluster_set._debug_test_hate_relation()\n assert cluster_set._debug_duplicated_recs(mapping)\n\n wedge_print(\"Wedge: poped new edge: Verts = %s, %s Value = (%f, %f)\" % (v1, v2, unused[0], unused[1]))\n cl1 = bib_map[v1]\n cl2 = bib_map[v2]\n if cl1 != cl2 and not cl1.hates(cl2):\n if deep_debug:\n export_to_dot(cluster_set, \"/tmp/%s%d.dot\" % (cluster_set.last_name, current), mapping, (v1, v2, unused))\n\n if decide(cl1, cl2):\n wedge_print(\"Wedge: Joined!\")\n join(cl1, cl2)\n cluster_set.clusters.remove(cl2)\n for v in cl2.bibs:\n bib_map[v] = cl1\n else:\n wedge_print(\"Wedge: Quarreled!\")\n cl1.quarrel(cl2)\n elif cl1 == cl2:\n wedge_print(\"Wedge: Clusters already joined!\")\n else:\n wedge_print(\"Wedge: Clusters hate each other!\")\n\n update_status_final(\"Wedge done.\")\n bibauthor_print(\"\")\n\n if deep_debug:\n export_to_dot(cluster_set, \"/tmp/%sfinal.dot\" % cluster_set.last_name, mapping)\n\ndef meld_edges(p1, p2):\n '''\n Creates one out_edges set from two.\n The operation is associative and commutative.\n The objects are: (out_edges for in a cluster, number of vertices in the same cluster)\n '''\n out_edges1, verts1 = p1\n out_edges2, verts2 = p2\n\n def median(e1, e2):\n if e1[0] in special_numbers:\n return e1\n\n if e2[0] in special_numbers:\n return e2\n\n inter_cert = e1[1] * verts1 + e2[1] * verts2\n inter_prob = e1[0] * e1[1] * verts1 + e2[0] * e2[1] * verts2\n return (inter_prob / inter_cert, inter_cert / (verts1 + verts2))\n\n assert len(out_edges1) == len(out_edges2)\n size = len(out_edges1)\n\n result = numpy.ndarray(shape=(size, 2), dtype=float, order='C')\n for i in xrange(size):\n result[i] = median(out_edges1[i], out_edges2[i])\n\n return (result, verts1 + verts2)\n\ndef convert_cluster_set(cs, prob_matr):\n '''\n Convertes a normal cluster set to a wedge clsuter set.\n @param cs: a cluster set to be converted\n @param type: cluster set\n @return: a mapping from a number to a bibrefrec.\n '''\n\n # step 1:\n # + Assign a number to each bibrefrec.\n # + Replace the arrays of bibrefrecs with arrays of numbers.\n # + Store the result and prepare it to be returned.\n\n result_mapping = []\n for clus in cs.clusters:\n start = len(result_mapping)\n result_mapping += list(clus.bibs)\n end = len(result_mapping)\n clus.bibs = range(start, end)\n\n assert len(result_mapping) == len(set(result_mapping))\n\n # step 2:\n # + Using the prob matrix create a vector values to all other bibs.\n # + Meld those vectors into one for each cluster.\n\n for current, c1 in enumerate(cs.clusters):\n update_status(float(current) / len(cs.clusters), \"Converting the cluster set...\")\n\n assert len(c1.bibs) > 0\n pointers = []\n\n for v1 in c1.bibs:\n pointer = numpy.ndarray(shape=(len(result_mapping), 2), dtype=float, order='C')\n pointer.fill(special_symbols[None])\n for c2 in cs.clusters:\n if c1 != c2 and not c1.hates(c2):\n for v2 in c2.bibs:\n val = prob_matr[result_mapping[v1], result_mapping[v2]]\n if val in special_symbols:\n numb = special_symbols[val]\n val = (numb, numb)\n assert len(val) == 2\n pointer[v2] = val\n pointers.append((pointer, 1))\n\n c1.out_edges = reduce(meld_edges, pointers)[0]\n\n update_status_final(\"Converting the cluster set done.\")\n\n return result_mapping\n\ndef restore_cluster_set(cs, new2old):\n for cl in cs.clusters:\n cl.bibs = set(new2old[b] for b in cl.bibs)\n del cl.out_edges\n\ndef create_bib_2_cluster_dict(cs):\n '''\n Creates and returns a dictionary bibrefrec -> cluster.\n The cluster set must be converted!\n '''\n size = sum(len(cl.bibs) for cl in cs.clusters)\n ret = range(size)\n for cl in cs.clusters:\n for bib in cl.bibs:\n ret[bib] = cl\n return ret\n\ndef group_edges(cs):\n plus = []\n minus = []\n pairs = []\n\n for current, cl1 in enumerate(cs.clusters):\n update_status(float(current) / len(cs.clusters), \"Grouping all edges...\")\n\n bib1 = tuple(cl1.bibs)[0]\n pointers = cl1.out_edges\n for bib2 in xrange(len(cl1.out_edges)):\n val = pointers[bib2]\n if val[0] not in special_numbers:\n if val[0] > edge_cut_prob:\n pairs.append((bib1, bib2, val))\n elif val[0] == special_symbols['+']:\n plus.append((bib1, bib2))\n elif val[0] == special_symbols['-']:\n minus.append((bib1, bib2))\n else:\n assert val[0] == special_symbols[None]\n\n update_status_final(\"Finished with the edge grouping.\")\n\n bibauthor_print(\"Positive edges: %d, Negative edges: %d, Value edges: %d.\"\n % (len(plus), len(minus), len(pairs)))\n return plus, minus, pairs\n\n\ndef join(cl1, cl2):\n '''\n Joins two clusters from a cluster set in the first.\n '''\n cl1.out_edges = meld_edges((cl1.out_edges, len(cl1.bibs)),\n (cl2.out_edges, len(cl2.bibs)))[0]\n cl1.bibs += cl2.bibs\n\n assert not cl1.hates(cl1)\n assert not cl2.hates(cl2)\n\n cl1.hate |= cl2.hate\n for cl in cl2.hate:\n cl.hate.remove(cl2)\n cl.hate.add(cl1)\n\n\ndef export_to_dot(cs, fname, graph_info, extra_edge=None):\n from bibauthorid_dbinterface import get_name_by_bibrecref\n\n fptr = open(fname, \"w\")\n fptr.write(\"graph wedgy {\\n\")\n fptr.write(\" overlap=prism\\n\")\n\n for idx, bib in enumerate(graph_info):\n fptr.write(' %d [color=black label=\"%s\"];\\n' % (idx, get_name_by_bibrecref(bib)))\n\n if extra_edge:\n v1, v2, (prob, cert) = extra_edge\n fptr.write(' %d -- %d [color=green label=\"p: %.2f, c: %.2f\"];\\n' % (v1, v2, prob, cert))\n\n for clus in cs.clusters:\n fptr.write(\" %s [color=blue];\\n\" % \" -- \".join(str(x) for x in clus.bibs))\n\n fptr.write(\"\".join(\" %d -- %d [color=red]\\n\" % (b1, b2)\n for b1 in clus.bibs for h in clus.hate for b2 in h.bibs))\n\n fptr.write(\"}\")\n\n\n","repo_name":"jrbl/invenio","sub_path":"modules/bibauthorid/lib/bibauthorid_wedge.py","file_name":"bibauthorid_wedge.py","file_ext":"py","file_size_in_byte":10926,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"9"} +{"seq_id":"9193120385","text":"#!/usr/bin/env python3\n\"\"\"\nChecks Satisfactory save games for containing invalid objects.\n\nBased on bitowl's sav2json.py (https://github.com/bitowl/satisfactory-save-format)\nwith json export being replaced by validity checkers.\n\"\"\"\n\nimport struct\nimport functools\nimport itertools\nimport csv\nimport binascii\nimport sys\nimport argparse\nimport pathlib\nimport math\n\n\nparser = argparse.ArgumentParser(\n\tdescription='Checks Satisfactory save games for containing invalid objects')\nparser.add_argument('file', metavar='FILE', type=str,\n\t\t\t\t\thelp='save game to process (.sav file extension)')\nparser.add_argument('--verbose', '-v', help='verbose output', action='store_true')\n\nargs = parser.parse_args()\n\nextension = pathlib.Path(args.file).suffix\nif extension != '.sav':\n\tprint('error: extension of save file should be .sav', file=sys.stderr)\n\texit(1)\n\nf = open(args.file, 'rb')\n\n# determine the file size so that we can\nf.seek(0, 2)\nfileSize = f.tell()\nf.seek(0, 0)\n\nbytesRead = 0\n\n\ndef assertFail(message):\n\tprint('assertion failed: ' + message, file=sys.stderr)\n\t# show the next bytes to help debugging\n\tprint(readHex(32))\n\tinput()\n\tassert False\n\n\ndef readInt():\n\tglobal bytesRead\n\tbytesRead += 4\n\treturn struct.unpack('i', f.read(4))[0]\n\n\ndef readFloat():\n\tglobal bytesRead\n\tbytesRead += 4\n\treturn struct.unpack('f', f.read(4))[0]\n\n\ndef readLong():\n\tglobal bytesRead\n\tbytesRead += 8\n\treturn struct.unpack('q', f.read(8))[0]\n\n\ndef readByte():\n\tglobal bytesRead\n\tbytesRead += 1\n\treturn struct.unpack('b', f.read(1))[0]\n\n\ndef assertNullByte():\n\tglobal bytesRead\n\tbytesRead += 1\n\tzero = f.read(1)\n\tif zero != b'\\x00':\n\t\tassertFail('not null but ' + str(zero))\n\n\ndef readLengthPrefixedString():\n\t\"\"\"\n\tReads a string that is prefixed with its length\n\t\"\"\"\n\tglobal bytesRead\n\tlength = readInt()\n\t\n\tsz = \"\"\n\n\tif length < 0:\n\t # Read unicode string\n\t\t\n\t\tlength = length * -2\n\n\t\ttry:\n\t\t\tchars = f.read(length-2)\n\t\texcept:\n\t\t\tassertFail(\"Error reading string at pos {} with length {}\".format(f.tell(), length))\n\n\t\tzero = f.read(2)\n\t\tbytesRead += length\n\n\t\tif zero != b'\\x00\\x00': # We assume that the last byte of a string is alway \\x00\n\t\t\tif length > 100:\n\t\t\t\tassertFail('zero is ' + str(zero) + ' in ' + str(chars[0:100]))\n\t\t\telse:\n\t\t\t\tassertFail('zero is ' + str(zero) + ' in ' + str(chars))\n\t\tsz = chars.decode('utf-16')\n\n\telif length > 0:\n\t\t# Read 8bit-ASCII\n\t\t\n\t\ttry:\n\t\t\tchars = f.read(length-1)\n\t\texcept:\n\t\t\tassertFail(\"Error reading string at pos {} with length {}\".format(f.tell(), length))\n\n\t\tzero = f.read(1)\n\t\tbytesRead += length\n\n\t\tif zero != b'\\x00': # We assume that the last byte of a string is alway \\x00\n\t\t\tif length > 100:\n\t\t\t\tassertFail('zero is ' + str(zero) + ' in ' + str(chars[0:100]))\n\t\t\telse:\n\t\t\t\tassertFail('zero is ' + str(zero) + ' in ' + str(chars))\n\t\tsz = chars.decode('ascii')\n\n\treturn sz\n\ndef readHex(count):\n\t\"\"\"\n\tReads count bytes and returns their hex form\n\t\"\"\"\n\tglobal bytesRead\n\tbytesRead += count\n\n\tchars = f.read(count)\n\tc = 0\n\tresult = ''\n\tfor i in chars:\n\t\tresult += format(i, '02x') + ' '\n\t\tc += 1\n\t\tif (c % 4 == 0 and c < count - 1):\n\t\t\tresult += ' '\n\n\treturn result\n\n\n\"\"\"\nActual error checking\n\"\"\"\n\nerrors = []\n\nLOWER_BOUND = -1.0e+10\nUPPER_BOUND = +1.0e+10\n\ndef isValid(val, lowerbounds=None, upperbounds=None):\n\t#global LOWER_BOUND, UPPER_BOUND\n\tif val is None or val == math.inf or val == math.nan:\n\t\treturn False\n\tlimit = lowerbounds or LOWER_BOUND\n\tif val <= limit:\n\t\treturn False\n\tlimit = upperbounds or UPPER_BOUND\n\tif val >= limit:\n\t\treturn False\n\treturn True\n\t\ndef isValidVec3(a,b,c, lowerbounds=None, upperbounds=None):\n\treturn isValid(a, lowerbounds, upperbounds)\\\n\t\tand isValid(b, lowerbounds, upperbounds)\\\n\t\tand\tisValid(c, lowerbounds, upperbounds)\n\t\ndef isValidVec4(a,b,c,d, lowerbounds=None, upperbounds=None):\n\treturn isValid(a, lowerbounds, upperbounds)\\\n\t\tand isValid(b, lowerbounds, upperbounds)\\\n\t\tand\tisValid(c, lowerbounds, upperbounds)\\\n\t\tand\tisValid(d, lowerbounds, upperbounds)\n\n\t\ndef addError(desc):\t\n\terrors.append(desc)\n\t\n\tif 'pathName' in desc:\n\t\tprint(\"\\n- pathName='{}'\".format(desc['pathName']))\n\t#elif 'name' in desc: # We'll have to see if this holds enough info for finding it later on, meawhile: print all\n\t#\tprint(\"\\n- name='{}'\".format(desc['name']))\n\telse:\n\t\tprint(\"\\n- Object {}\".format(desc))\n\ndef checkRot(desc, a,b,c,d=None):\n\tif d is None:\n\t\tif not isValidVec3(a,b,c):\n\t\t\taddError(desc)\n\t\t\tprint(\"\\t-> Invalid rot: {} | {} | {}\".format(a,b,c))\n\t\t\treturn False\n\telse:\n\t\tif not isValidVec4(a,b,c,d):\n\t\t\taddError(desc)\n\t\t\tprint(\"\\t-> Invalid rot: {} | {} | {} | {}\".format(a,b,c,d))\n\t\t\treturn False\n\treturn True\n\ndef checkTrans(desc, x,y,z):\n\tif not isValidVec3(x,y,z):\n\t\taddError(desc)\n\t\tprint(\"\\t-> Invalid trans: {} | {} | {}\".format(x,y,z))\n\t\treturn False\n\treturn True\n\ndef checkScale(desc, sx,sy,sz):\n\tif not isValidVec3(sx,sy,sz, 1.0e-10): # For now, we do ignore negative scales and let them print as errors\n\t\taddError(desc)\n\t\tprint(\"\\t-> Invalid scale: {} | {} | {}\".format(sx,sy,sz))\n\t\treturn False\n\treturn True\n\t\t\n\n\n# Read the file header\nsaveHeaderType = readInt()\nsaveVersion = readInt() # Save Version\nbuildVersion = readInt() # BuildVersion\n\nmapName = readLengthPrefixedString() # MapName\nmapOptions = readLengthPrefixedString() # MapOptions\nsessionName = readLengthPrefixedString() # SessionName\nplayDurationSeconds = readInt() # PlayDurationSeconds\n\nsaveDateTime = readLong() # SaveDateTime\n'''\nto convert this FDateTime to a unix timestamp use:\nsaveDateSeconds = saveDateTime / 10000000\n# see https://stackoverflow.com/a/1628018\nprint(saveDateSeconds-62135596800)\n'''\nsessionVisibility = readByte() # SessionVisibility\n\nentryCount = readInt() # total entries\nhierarchy = {\n\t'saveHeaderType': saveHeaderType,\n\t'saveVersion': saveVersion,\n\t'buildVersion': buildVersion,\n\t'mapName': mapName,\n\t'mapOptions': mapOptions,\n\t'sessionName': sessionName,\n\t'playDurationSeconds': playDurationSeconds,\n\t'saveDateTime': saveDateTime,\n\t'sessionVisibility': sessionVisibility,\n\t'objects': [],\n\t'collected': []\n}\n\n\ndef readActor():\n\tclassName = readLengthPrefixedString()\n\tlevelName = readLengthPrefixedString()\n\tpathName = readLengthPrefixedString()\n\tneedTransform = readInt()\n\n\ta = readFloat()\n\tb = readFloat()\n\tc = readFloat()\n\td = readFloat()\n\tx = readFloat()\n\ty = readFloat()\n\tz = readFloat()\n\tsx = readFloat()\n\tsy = readFloat()\n\tsz = readFloat()\n\n\twasPlacedInLevel = readInt()\n\n\n\tdesc = {\n\t\t'className': className,\n\t\t'levelName': levelName,\n\t\t'pathName': pathName,\n\t}\n\toverallCheckState = checkRot (desc, a,b,c,d)\n\toverallCheckState &= checkTrans(desc, x,y,z)\n\toverallCheckState &= checkScale(desc, sx,sy,sz)\n\t\n\treturn {\n\t\t'type': 1,\n\t\t'className': className,\n\t\t'levelName': levelName,\n\t\t'pathName': pathName,\n\t\t'needTransform': needTransform,\n\t\t'transform': {\n\t\t\t'rotation': [a, b, c, d],\n\t\t\t'translation': [x, y, z],\n\t\t\t'scale3d': [sx, sy, sz],\n\n\t\t},\n\t\t'wasPlacedInLevel': wasPlacedInLevel\n\t},overallCheckState\n\n\ndef readObject():\n\tclassName = readLengthPrefixedString()\n\tlevelName = readLengthPrefixedString()\n\tpathName = readLengthPrefixedString()\n\touterPathName = readLengthPrefixedString()\n\n\treturn {\n\t\t'type': 0,\n\t\t'className': className,\n\t\t'levelName': levelName,\n\t\t'pathName': pathName,\n\t\t'outerPathName': outerPathName\n\t},True#overallCheckState\n\n\nfor i in range(0, entryCount):\n\ttype = readInt()\n\tobj = None\n\toverallCheckState = True\n\tif type == 1:\n\t\tobj,overallCheckState = readActor()\n\t\tif not overallCheckState:\n\t\t\tprint(\" in actor, pathName='{pathName}', className='{className}'\".format(**obj))\n\telif type == 0:\n\t\tobj,overallCheckState = readObject()\n\t\tif not overallCheckState:\n\t\t\tprint(\" in object, pathName='{pathName}', outerPathName='{outerPathName}'\".format(**obj))\n\telse:\n\t\tassertFail('unknown type {} at filepos {}'.format(type, ftell(f)-4))\n\thierarchy['objects'].append(obj)\n\n\nelementCount = readInt()\n\n# So far these counts have always been the same and the entities seem to belong 1 to 1 to the actors/objects read above\nif elementCount != entryCount:\n\tassertFail('elementCount ('+str(elementCount) +\n\t\t\t ') != entryCount('+str(entryCount)+')')\n\n\ndef readProperty(properties):\n\toverallCheckState = True\n\n\tname = readLengthPrefixedString()\n\tif name == 'None':\n\t\treturn\n\n\tprop = readLengthPrefixedString()\n\tlength = readInt()\n\tindex = readInt()\n\n\tproperty = {\n\t\t'name': name,\n\t\t'type': prop,\n\t\t'_length': length,\n\t 'index': index\n\t}\n\n\tif prop == 'IntProperty':\n\t\tassertNullByte()\n\t\tproperty['value'] = readInt()\n\n\telif prop == 'StrProperty':\n\t\tassertNullByte()\n\t\tproperty['value'] = readLengthPrefixedString()\n\n\telif prop == 'StructProperty':\n\t\ttype = readLengthPrefixedString()\n\n\t\tproperty['structUnknown'] = readHex(17) # TODO\n\n\t\tif type == 'Vector' or type == 'Rotator':\n\t\t\tx = readFloat()\n\t\t\ty = readFloat()\n\t\t\tz = readFloat()\n\t\t\tproperty['value'] = {\n\t\t\t\t'type': type,\n\t\t\t\t'x': x,\n\t\t\t\t'y': y,\n\t\t\t\t'z': z\n\t\t\t}\n\t\t\tif type == 'Vector':\n\t\t\t\toverallCheckState &= checkTrans(property, x,y,z)\n\t\t\telse:\n\t\t\t\toverallCheckState &= checkRot(property, x,y,z)\n\t\t\tif not overallCheckState:\n\t\t\t\tprint(\" in StructProperty.{}\".format(type))\n\t\t\t\t\n\t\telif type == 'Box':\n\t\t\tminX = readFloat()\n\t\t\tminY = readFloat()\n\t\t\tminZ = readFloat()\n\t\t\tmaxX = readFloat()\n\t\t\tmaxY = readFloat()\n\t\t\tmaxZ = readFloat()\n\t\t\tisValid = readByte()\n\t\t\tproperty['value'] = {\n\t\t\t\t'type': type,\n\t\t\t\t'min': [minX, minY, minZ],\n\t\t\t\t'max': [maxX, maxY, maxZ],\n\t\t\t\t'isValid': isValid\n\t\t\t}\n\t\t\t#TODO: Add checking corners\n\t\t\t\n\t\telif type == 'LinearColor':\n\t\t\tr = readFloat()\n\t\t\tg = readFloat()\n\t\t\tb = readFloat()\n\t\t\ta = readFloat()\n\t\t\tproperty['value'] = {\n\t\t\t\t'type': type,\n\t\t\t\t'r': r,\n\t\t\t\t'g': g,\n\t\t\t\t'b': b,\n\t\t\t\t'a': a\n\t\t\t}\n\t\t\t#INVESTIGATE: Invalid colors even came up as an issue yet?\n\t\t\t\n\t\telif type == 'Transform':\n\t\t\tprops = []\n\t\t\t#TODO: Add checkers\n\t\t\t#while (readProperty(props)):\n\t\t\t#\tpass\n\t\t\twhile (True):\n\t\t\t\tt = readProperty(props)\n\t\t\t\tif not t or not t[0]:\n\t\t\t\t\tbreak\n\t\t\t\tif not t[1]:\n\t\t\t\t\tprint(\" in StructProperty.Transform[{}]\".format(len(props)))\n\t\t\t\t\toverallCheckState = False\n\t\t\t#if overallCheckState == False:\n\t\t\t#\tprint(\" at name='{}', type='{}'\".format(property['name'], property['type']))\n\t\t\t\n\t\t\tproperty['value'] = {\n\t\t\t\t'type': type,\n\t\t\t\t'properties': props\n\t\t\t}\n\n\t\telif type == 'Quat':\n\t\t\ta = readFloat()\n\t\t\tb = readFloat()\n\t\t\tc = readFloat()\n\t\t\td = readFloat()\n\t\t\tproperty['value'] = {\n\t\t\t\t'type': type,\n\t\t\t\t'a': a,\n\t\t\t\t'b': b,\n\t\t\t\t'c': c,\n\t\t\t\t'd': d\n\t\t\t}\n\t\t\toverallCheckState &= checkRot(property, a,b,c,d)\n\t\t\tif not overallCheckState:\n\t\t\t\tprint(\" in StructProperty.Quat\")\n\n\t\telif type == 'RemovedInstanceArray' or type == 'InventoryStack':\n\t\t\tprops = []\n\t\t\t#TODO: Add checkers\n\t\t\t#while (readProperty(props)):\n\t\t\t#\tpass\n\t\t\twhile (True):\n\t\t\t\tt = readProperty(props)\n\t\t\t\tif not t or not t[0]:\n\t\t\t\t\tbreak\n\t\t\t\tif not t[1]:\n\t\t\t\t\tprint(\" in {}[{}]\".format(type, len(props)))\n\t\t\t\t\toverallCheckState = False\n\t\t\t#if overallCheckState == False:\n\t\t\t#\tprint(\" at name='{}', type='{}'\".format(property['name'], property['type']))\n\n\t\t\tproperty['value'] = {\n\t\t\t\t'type': type,\n\t\t\t\t'properties': props\n\t\t\t}\n\t\t\t\n\t\telif type == 'InventoryItem':\n\t\t\tunk1 = readLengthPrefixedString() # TODO\n\t\t\titemName = readLengthPrefixedString()\n\t\t\tlevelName = readLengthPrefixedString()\n\t\t\tpathName = readLengthPrefixedString()\n\n\t\t\tprops = []\n\t\t\t#TODO: Add checkers\n\t\t\t#readProperty(props)\n\t\t\tt = readProperty(props)\n\t\t\tif t and not t[1]:\n\t\t\t\tprint(\" in StructProperty.InventoryItem, itemName='{}'\".format(itemName))\n\t\t\t\toverallCheckState = False\n\t\t\t\n\t\t\t# can't consume null here because it is needed by the entaingling struct\n\n\t\t\tproperty['value'] = {\n\t\t\t\t'type': type,\n\t\t\t\t'unk1': unk1,\n\t\t\t\t'itemName': itemName,\n\t\t\t\t'levelName': levelName,\n\t\t\t\t'pathName': pathName,\n\t\t\t\t'properties': props\n\t\t\t}\n\t\t\t\n\t\telse:\n\t\t\tassertFail('Unknown type: ' + type)\n\n\telif prop == 'ArrayProperty':\n\t\titemType = readLengthPrefixedString()\n\t\tassertNullByte()\n\t\tcount = readInt()\n\t\tvalues = []\n\n\t\tif itemType == 'ObjectProperty':\n\t\t\tfor j in range(0, count):\n\t\t\t\tvalues.append({\n\t\t\t\t\t'levelName': readLengthPrefixedString(),\n\t\t\t\t\t'pathName': readLengthPrefixedString()\n\t\t\t\t})\n\t\t\t\t\n\t\telif itemType == 'StructProperty':\n\t\t\tstructName = readLengthPrefixedString()\n\t\t\tstructType = readLengthPrefixedString()\n\t\t\tstructSize = readInt()\n\t\t\tzero = readInt()\n\t\t\tif zero != 0:\n\t\t\t\tassertFail('not zero: ' + str(zero))\n\n\t\t\ttype = readLengthPrefixedString()\n\n\t\t\tproperty['structName'] = structName\n\t\t\tproperty['structType'] = structType\n\t\t\tproperty['structInnerType'] = type\n\n\t\t\tproperty['structUnknown'] = readHex(17) # TODO what are those?\n\t\t\tproperty['_structLength'] = structSize\n\t\t\tfor i in range(0, count):\n\t\t\t\tprops = []\n\t\t\t\t#TODO: Add checkers\n\t\t\t\t#while (readProperty(props)):\n\t\t\t\t#\tpass\n\t\t\t\twhile (True):\n\t\t\t\t\tt = readProperty(props)\n\t\t\t\t\tif not t or not t[0]:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif not t[1]:\n\t\t\t\t\t\tprint(\" at property {}[{}]\".format(property['type'],i))\n\t\t\t\t\t\toverallCheckState = False\n\t\t\t\tif not overallCheckState:\n\t\t\t\t\tprint(\" in ArrayProperty[{}].StructProperty, structName='{}', structType='{}'\".format(len(values),structName,structType))\n\n\t\t\t\tvalues.append({\n\t\t\t\t\t'properties': props\n\t\t\t\t})\n\n\t\telif itemType == 'IntProperty':\n\t\t\tfor i in range(0, count):\n\t\t\t\tvalues.append(readInt())\n\n\t\telif itemType == 'ByteProperty':\n\t\t\tfor i in range(0, count):\n\t\t\t\tvalues.append(readByte())\n\n\t\telse:\n\t\t\tassertFail('unknown itemType ' + itemType + ' in name ' + name)\n\n\t\tproperty['value'] = {\n\t\t\t'type': itemType,\n\t\t\t'values': values\n\t\t}\n\t\t\n\telif prop == 'ObjectProperty':\n\t\tassertNullByte()\n\t\tproperty['value'] = {\n\t\t\t'levelName': readLengthPrefixedString(),\n\t\t\t'pathName': readLengthPrefixedString()\n\t\t}\n\t\t\n\telif prop == 'BoolProperty':\n\t\tproperty['value'] = readByte()\n\t\tassertNullByte()\n\t\t\n\telif prop == 'FloatProperty': # TimeStamps that are FloatProperties are negative to the current time in seconds?\n\t\tassertNullByte()\n\t\tproperty['value'] = readFloat()\n\t\t\n\telif prop == 'EnumProperty':\n\t\tenumName = readLengthPrefixedString()\n\t\tassertNullByte()\n\t\tvalueName = readLengthPrefixedString()\n\t\tproperty['value'] = {\n\t\t\t'enum': enumName,\n\t\t\t'value': valueName,\n\t\t}\n\t\t\n\telif prop == 'NameProperty':\n\t\tassertNullByte()\n\t\tproperty['value'] = readLengthPrefixedString()\n\t\t\n\telif prop == 'MapProperty':\n\t\tname = readLengthPrefixedString()\n\t\tvalueType = readLengthPrefixedString()\n\t\tfor i in range(0, 5):\n\t\t\tassertNullByte()\n\t\tcount = readInt()\n\t\tvalues = {\n\t\t}\n\t\tfor i in range(0, count):\n\t\t\tkey = readInt()\n\t\t\tprops = []\n\t\t\t#TODO: Add checkers\n\t\t\t#while readProperty(props):\n\t\t\t#\tpass\n\t\t\twhile (True):\n\t\t\t\tt = readProperty(props)\n\t\t\t\tif not t or not t[0]:\n\t\t\t\t\tbreak\n\t\t\t\tif not t[1]:\n\t\t\t\t\tprint(\" in MapProperty[{}], property '{}'\".format(len(props),property['name']))\n\t\t\t\t\toverallCheckState = False\n\t\t\tvalues[key] = props\n\n\t\tproperty['value'] = {\n\t\t\t'name': name,\n\t\t\t'type': valueType,\n\t\t\t'values': values\n\t\t}\n\t\t\n\telif prop == 'ByteProperty': # TODO\n\n\t\tunk1 = readLengthPrefixedString() # TODO\n\t\tif unk1 == 'None':\n\t\t\tassertNullByte()\n\t\t\tproperty['value'] = {\n\t\t\t\t'unk1': unk1,\n\t\t\t\t'unk2': readByte()\n\t\t\t}\n\t\telse:\n\t\t\tassertNullByte()\n\t\t\tunk2 = readLengthPrefixedString() # TODO\n\t\t\tproperty['value'] = {\n\t\t\t\t'unk1': unk1,\n\t\t\t\t'unk2': unk2\n\t\t\t}\n\t\t\n\telif prop == 'TextProperty':\n\t\tassertNullByte()\n\t\tproperty['textUnknown'] = readHex(13) # TODO\n\t\tproperty['value'] = readLengthPrefixedString()\n\t\t\n\telse:\n\t\tassertFail('Unknown property type: ' + prop)\n\n\tproperties.append(property)\n\treturn True,overallCheckState\n\n\ndef readEntity(withNames, length):\n\tglobal bytesRead\n\tbytesRead = 0\n\n\tentity = {}\n\n\tif withNames:\n\t\tentity['levelName'] = readLengthPrefixedString()\n\t\tentity['pathName'] = readLengthPrefixedString()\n\t\tentity['children'] = []\n\n\t\tchildCount = readInt()\n\t\tif childCount > 0:\n\t\t\tfor i in range(0, childCount):\n\t\t\t\tlevelName = readLengthPrefixedString()\n\t\t\t\tpathName = readLengthPrefixedString()\n\t\t\t\tentity['children'].append({\n\t\t\t\t\t'levelName': levelName,\n\t\t\t\t\t'pathName': pathName\n\t\t\t\t})\n\tentity['properties'] = []\n\t#TODO: Add checkers\n\t#while (readProperty(entity['properties'])):\n\t#\tpass\n\toverallCheckState = True\n\twhile (True):\n\t\tt = readProperty(entity['properties'])\n\t\tif not t or not t[0]:\n\t\t\tbreak\n\t\tif not t[1]:\n\t\t\tprint(\" at property '{}'\".format(t[0]['name']))\t\t\t\n\t\t\toverallCheckState = False\n\tif not overallCheckState:\n\t\tif withNames:\n\t\t\tprint(\" in entity '{}'\".format(entity['pathName']))\t\t\t\n\t\telse:\n\t\t\tprint(\" in entity\")\n\n\t# read missing bytes at the end of this entity.\n\t# maybe we missed something while parsing the properties?\n\tmissing = length - bytesRead\n\tif missing > 0:\n\t\tentity['missing'] = readHex(missing)\n\telif missing < 0:\n\t\tassertFail('negative missing amount: ' + str(missing))\n\n\treturn entity\n\n\nfor i in range(0, elementCount):\n\tlength = readInt() # length of this entry\n\tif hierarchy['objects'][i]['type'] == 1:\n\t\thierarchy['objects'][i]['entity'] = readEntity(True, length)\n\telse:\n\t\thierarchy['objects'][i]['entity'] = readEntity(False, length)\n\n\ncollectedCount = readInt()\n\nfor i in range(0, collectedCount):\n\tlevelName = readLengthPrefixedString()\n\tpathName = readLengthPrefixedString()\n\thierarchy['collected'].append({'levelName': levelName, 'pathName': pathName})\n\n# store the remaining bytes as well so that we can recreate the exact same save file\nhierarchy['missing'] = readHex(fileSize - f.tell())\n\n\nprint(\"\\nInspected a total of {} objects.\".format(elementCount+collectedCount))\nif len(errors):\n\tprint(\"A total of {} errors were found!\".format(len(errors)))\nelse:\n\tprint(\"NO errors found at all.\")\n","repo_name":"SillyBits/satisfactory-save-checker","sub_path":"checksav.py","file_name":"checksav.py","file_ext":"py","file_size_in_byte":17413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"12829809395","text":"import threading\nimport time\n\nfrom datetime import datetime\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.chrome.options import Options\n\n# Login not required for Tock. Leave it as false to decrease reservation delay\nENABLE_LOGIN = False\nTOCK_USERNAME = \"SET_YOUR_USER_NAME_HERE\"\nTOCK_PASSWORD = \"SET_YOUR_PASSWORD_HERE\"\n\n# Set your specific reservation month and days\nRESERVATION_MONTH = 'November'\nRESERVATION_DAYS = ['23', '24', '25']\nRESERVATION_YEAR = '2021'\nRESERVATION_TIME_FORMAT = \"%I:%M %p\"\n\n# Set the time range for acceptable reservation times.\n# I.e., any available slots between 5:00 PM and 8:30 PM\nEARLIEST_TIME = \"3:00 PM\"\nLATEST_TIME = \"8:30 PM\"\nRESERVATION_TIME_MIN = datetime.strptime(EARLIEST_TIME, RESERVATION_TIME_FORMAT)\nRESERVATION_TIME_MAX = datetime.strptime(LATEST_TIME, RESERVATION_TIME_FORMAT)\n\n# Set the party size for the reservation\nRESERVATION_SIZE = 4\n\n# Multithreading configurations\nNUM_THREADS = 1\nTHREAD_DELAY_SEC = 1\nRESERVATION_FOUND = False\n\n# Time between each page refresh in milliseconds. Decrease this time to\n# increase the number of reservation attempts\nREFRESH_DELAY_MSEC = 500\n\n# Chrome extension configurations that are used with Luminati.io proxy.\n# Enable proxy to avoid getting IP potentially banned. This should be enabled only if the REFRESH_DELAY_MSEC\n# is extremely low (sub hundred) and NUM_THREADS > 1.\nENABLE_PROXY = False\nUSER_DATA_DIR = '~/Library/Application Support/Google/Chrome'\nPROFILE_DIR = 'Default'\n# https://chrome.google.com/webstore/detail/luminati/efohiadmkaogdhibjbmeppjpebenaool\nEXTENSION_PATH = USER_DATA_DIR + '/' + PROFILE_DIR + '/Extensions/efohiadmkaogdhibjbmeppjpebenaool/1.149.316_0'\n\n# Delay for how long the browser remains open so that the reservation can be finalized. Tock holds the reservation\n# for 10 minutes before releasing.\nBROWSER_CLOSE_DELAY_SEC = 600\n\nWEBDRIVER_TIMEOUT_DELAY_MS = 3000\n\nMONTH_NUM = {\n 'january': '01',\n 'february': '02',\n 'march': '03',\n 'april': '04',\n 'may': '05',\n 'june': '06',\n 'july': '07',\n 'august': '08',\n 'september': '09',\n 'october': '10',\n 'november': '11',\n 'december': '12'\n}\n\n\nclass ReserveTFL():\n def __init__(self):\n options = Options()\n if ENABLE_PROXY:\n options.add_argument('--load-extension={}'.format(EXTENSION_PATH))\n options.add_argument('--user-data-dir={}'.format(USER_DATA_DIR))\n options.add_argument('--profile-directory=Default')\n\n self.driver = webdriver.Chrome(options=options)\n\n def teardown(self):\n self.driver.quit()\n\n def reserve(self):\n global RESERVATION_FOUND\n print(\"Looking for availability on month: %s, days: %s, between times: %s and %s\" % (RESERVATION_MONTH, RESERVATION_DAYS, EARLIEST_TIME, LATEST_TIME))\n\n if ENABLE_LOGIN:\n self.login_tock()\n\n while not RESERVATION_FOUND:\n time.sleep(REFRESH_DELAY_MSEC / 1000)\n self.driver.get(\"https://www.exploretock.com/tfl/search?date=%s-%s-02&size=%s&time=%s\" % (RESERVATION_YEAR, month_num(RESERVATION_MONTH), RESERVATION_SIZE, \"22%3A00\"))\n WebDriverWait(self.driver, WEBDRIVER_TIMEOUT_DELAY_MS).until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"div.ConsumerCalendar-month\")))\n\n if not self.search_month():\n print(\"No available days found. Continuing next search iteration\")\n continue\n\n WebDriverWait(self.driver, WEBDRIVER_TIMEOUT_DELAY_MS).until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"button.Consumer-resultsListItem.is-available\")))\n\n print(\"Found availability. Sleeping for 10 minutes to complete reservation...\")\n RESERVATION_FOUND = True\n time.sleep(BROWSER_CLOSE_DELAY_SEC)\n\n def login_tock(self):\n self.driver.get(\"https://www.exploretock.com/tfl/login\")\n WebDriverWait(self.driver, WEBDRIVER_TIMEOUT_DELAY_MS).until(expected_conditions.presence_of_element_located((By.NAME, \"email\")))\n self.driver.find_element(By.NAME, \"email\").send_keys(TOCK_USERNAME)\n self.driver.find_element(By.NAME, \"password\").send_keys(TOCK_PASSWORD)\n self.driver.find_element(By.CSS_SELECTOR, \".Button\").click()\n WebDriverWait(self.driver, WEBDRIVER_TIMEOUT_DELAY_MS).until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, \".MainHeader-accountName\")))\n\n def search_month(self):\n month_object = None\n\n for month in self.driver.find_elements(By.CSS_SELECTOR, \"div.ConsumerCalendar-month\"):\n header = month.find_element(By.CSS_SELECTOR, \"div.ConsumerCalendar-monthHeading\")\n span = header.find_element(By.CSS_SELECTOR, \"span.H1\")\n print(\"Encountered month\", span.text)\n\n if RESERVATION_MONTH in span.text:\n month_object = month\n print(\"Month\", RESERVATION_MONTH, \"found\")\n break\n\n if month_object is None:\n print(\"Month\", RESERVATION_MONTH, \"not found. Ending search\")\n return False\n\n for day in month_object.find_elements(By.CSS_SELECTOR, \"button.ConsumerCalendar-day.is-in-month.is-available\"):\n span = day.find_element(By.CSS_SELECTOR, \"span.B2\")\n print(\"Encountered day: \" + span.text)\n if span.text in RESERVATION_DAYS:\n print(\"Day %s found. Clicking button\" % span.text)\n day.click()\n\n if self.search_time():\n print(\"Time found\")\n return True\n\n return False\n\n def search_time(self):\n for item in self.driver.find_elements(By.CSS_SELECTOR, \"button.Consumer-resultsListItem.is-available\"):\n span = item.find_element(By.CSS_SELECTOR, \"span.Consumer-resultsListItemTime\")\n span2 = span.find_element(By.CSS_SELECTOR, \"span\")\n print(\"Encountered time\", span2.text)\n\n available_time = datetime.strptime(span2.text, RESERVATION_TIME_FORMAT)\n if RESERVATION_TIME_MIN <= available_time <= RESERVATION_TIME_MAX:\n print(\"Time %s found. Clicking button\" % span2.text)\n item.click()\n return True\n\n return False\n\n\ndef month_num(month):\n # TODO error handling\n return MONTH_NUM[month.lower()]\n\n\ndef run_reservation():\n r = ReserveTFL()\n r.reserve()\n r.teardown()\n\n\ndef execute_reservations():\n threads = []\n for _ in range(NUM_THREADS):\n t = threading.Thread(target=run_reservation)\n threads.append(t)\n t.start()\n time.sleep(THREAD_DELAY_SEC)\n\n for t in threads:\n t.join()\n\n\ndef continuous_reservations():\n while True:\n execute_reservations()\n\n\ncontinuous_reservations()\n","repo_name":"chinhtle/reserve-tfl","sub_path":"reserve_tfl.py","file_name":"reserve_tfl.py","file_ext":"py","file_size_in_byte":6977,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"9"} +{"seq_id":"75348677732","text":"import typer\nfrom typing import Optional\nfrom repositories.files import get_file_id\nfrom services.gcs import download_blob\nfrom services.db import get_conn\napp=typer.Typer()\n\n@app.command()\ndef download(id:str, destination_filename : Optional[str] = typer.Argument(None)):\n\n\n # buscar db cartagena \n conn1 = get_conn('sifincactg')\n file = get_file_id(id, conn1)\n \n if not file:\n conn2 = get_conn('sifincamon')\n file = get_file_id(id, conn2)\n if not file:\n # no encontrado error \n typer.echo(f'ID no existe {id}')\n else:\n bucket_name ='monteria-files'\n # elseif monteria\n else:\n bucket_name = 'sifinca-files' \n\n\n if dest==None or dest=='':\n dest = file['originalname']\n path = file['path']\n typer.echo(bucket_name,file['path'])\n\n download_blob(bucket_name, path, dest)\n \n typer.echo(f'Archivo id {id} descargado en {dest}')\n\n\nif __name__=='__main__':\n app()\n ","repo_name":"hherrera/py_gcs","sub_path":"commands/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"5013487159","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision\r\n\r\n\r\nclass VSPSR(nn.Module):\r\n def __init__(self, vspm, postprocess=None):\r\n super(VSPSR, self).__init__()\r\n self.vspm = vspm\r\n\r\n if postprocess is not None:\r\n self.postprocess = postprocess\r\n else:\r\n self.postprocess = None\r\n\r\n def forward(self, x):\r\n result_dict = {}\r\n e, kl_z, kl_w, explore = self.vspm(x)\r\n output = e\r\n result_dict.update({'kl_z': kl_z, 'kl_w': kl_w, 'e': explore})\r\n\r\n if self.postprocess is not None:\r\n output = self.postprocess(output, x)\r\n result_dict.update({'pred': output})\r\n\r\n return result_dict\r\n\r\n\r\nclass Discriminator(nn.Module):\r\n def __init__(self, in_chans=3):\r\n super(Discriminator, self).__init__()\r\n self.in_chans = in_chans\r\n self.layers = nn.Sequential(\r\n nn.Conv2d(self.in_chans, 64, 4, 2),\r\n nn.BatchNorm2d(64),\r\n nn.LeakyReLU(),\r\n\r\n nn.Conv2d(64, 128, 4, 2),\r\n nn.BatchNorm2d(128),\r\n nn.LeakyReLU(),\r\n\r\n nn.Conv2d(128, 256, 1, 1),\r\n nn.BatchNorm2d(256),\r\n nn.LeakyReLU(),\r\n\r\n nn.Conv2d(256, 512, 1, 1),\r\n nn.BatchNorm2d(512),\r\n nn.LeakyReLU(),\r\n\r\n nn.Conv2d(512, 1, 1, 1),\r\n nn.Sigmoid()\r\n )\r\n\r\n def forward(self, x):\r\n x = self.layers(x)\r\n return torch.mean(x, dim=(1, 2, 3))\r\n\r\n\r\nclass TruncatedVGG19(nn.Module):\r\n \"\"\"\r\n truncated VGG19, to calculate MSE loss in the VGG space\r\n \"\"\"\r\n\r\n def __init__(self, i, j):\r\n super(TruncatedVGG19, self).__init__()\r\n\r\n vgg19 = torchvision.models.vgg19(pretrained=True)\r\n\r\n maxpool_counter = 0\r\n conv_counter = 0\r\n truncate_at = 0\r\n for layer in vgg19.features.children():\r\n truncate_at += 1\r\n\r\n if isinstance(layer, nn.Conv2d):\r\n conv_counter += 1\r\n if isinstance(layer, nn.MaxPool2d):\r\n maxpool_counter += 1\r\n conv_counter = 0\r\n\r\n if maxpool_counter == i - 1 and conv_counter == j:\r\n break\r\n\r\n self.truncated_vgg19 = nn.Sequential(*list(vgg19.features.children())[:truncate_at + 1])\r\n\r\n def forward(self, input):\r\n \"\"\"\r\n input: HR or SR,size is (N, 3, w * scaling factor, h * scaling factor)\r\n output: VGG19 features,size is (N, feature_map_channels, feature_map_w, feature_map_h)\r\n \"\"\"\r\n output = self.truncated_vgg19(input)\r\n return output\r\n\r\n\r\nclass SetCriterion(nn.Module):\r\n \"\"\"\r\n This class computes the loss for Super-Resolution.\r\n \"\"\"\r\n\r\n def __init__(self, losses, weight_dict, args):\r\n super().__init__()\r\n self.losses = losses\r\n self.weight_dict = weight_dict\r\n self.args = args\r\n if args.GAN:\r\n self.Discriminator = Discriminator()\r\n if args.VGG:\r\n self.truncated_vgg19 = TruncatedVGG19(i=args.VGG_i, j=args.VGG_j)\r\n self.MSE = torch.nn.MSELoss()\r\n\r\n def loss_MSE(self, outputs, hr):\r\n \"\"\"\r\n Compute the MSE loss\r\n \"\"\"\r\n pred = outputs[\"pred\"]\r\n losses = {\r\n \"loss_MSE\": self.MSE(pred, hr),\r\n }\r\n return losses\r\n\r\n def loss_KL_z(self, outputs, hr):\r\n kl_z = outputs[\"kl_z\"]\r\n losses = {\r\n \"loss_KL_z\": torch.mean(kl_z)\r\n }\r\n\r\n return losses\r\n\r\n def loss_KL_w(self, outputs, hr):\r\n kl_w = outputs[\"kl_w\"]\r\n losses = {\r\n \"loss_KL_w\": torch.mean(kl_w)\r\n }\r\n return losses\r\n\r\n def loss_G(self, outputs, hr):\r\n pred = outputs[\"pred\"]\r\n real = self.Discriminator(pred)\r\n label = torch.ones_like(real)\r\n losses = {\r\n \"loss_G\": self.MSE(real, label)\r\n }\r\n return losses\r\n\r\n def loss_D(self, outputs, hr):\r\n pred = outputs[\"pred\"].detach()\r\n real = self.Discriminator(hr)\r\n real_label = torch.ones_like(real)\r\n fake = self.Discriminator(pred)\r\n fake_label = torch.zeros_like(fake)\r\n losses = {\r\n \"loss_D\": 0.5 * self.MSE(fake, fake_label) + 0.5 * self.MSE(real, real_label)\r\n }\r\n return losses\r\n\r\n def loss_C(self, outputs, hr):\r\n pred = outputs[\"pred\"]\r\n pred_in_vgg_space = self.truncated_vgg19(pred)\r\n hr_in_vgg_space = self.truncated_vgg19(hr)\r\n losses = {\r\n \"loss_C\": self.MSE(pred_in_vgg_space, hr_in_vgg_space)\r\n }\r\n return losses\r\n\r\n def get_loss(self, loss, outputs, hr):\r\n loss_map = {'KL_z': self.loss_KL_z,\r\n 'KL_w': self.loss_KL_w,\r\n 'MSE': self.loss_MSE,\r\n 'G': self.loss_G,\r\n 'D': self.loss_D,\r\n 'C': self.loss_C}\r\n assert loss in loss_map, f'do you really want to compute {loss} loss?'\r\n return loss_map[loss](outputs, hr)\r\n\r\n def forward(self, outputs, hr):\r\n losses = {}\r\n for loss in self.losses:\r\n losses.update(self.get_loss(loss, outputs, hr))\r\n return losses\r\n","repo_name":"zzhwfy/VSpSR","sub_path":"models/vspsr.py","file_name":"vspsr.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"11442751244","text":"# encoding: UTF-8\n\"\"\"\n账户数据\n\"\"\"\nfrom heron.lib.vnpy.constant import EMPTY_FLOAT, EMPTY_STRING\n\nfrom base import Base\n\n\nclass Account(Base):\n\n def __init__(self):\n \"\"\"Constructor\"\"\"\n super(Account, self).__init__()\n\n # 账号代码相关\n self.accountID = EMPTY_STRING # 账户代码\n self.vtAccountID = EMPTY_STRING # 账户在vt中的唯一代码,通常是 Gateway名.账户代码\n\n # 数值相关\n self.preBalance = EMPTY_FLOAT # 昨日账户结算净值\n self.balance = EMPTY_FLOAT # 账户净值\n self.available = EMPTY_FLOAT # 可用资金\n self.commission = EMPTY_FLOAT # 今日手续费\n self.margin = EMPTY_FLOAT # 保证金占用\n self.closeProfit = EMPTY_FLOAT # 平仓盈亏\n self.positionProfit = EMPTY_FLOAT # 持仓盈亏","repo_name":"MeiQuant/heron","sub_path":"heron/lib/vnpy/model/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"9"} +{"seq_id":"18879974561","text":"import logging\nimport urllib\nimport uuid\nimport hashlib\nimport base64\n\nimport sqlalchemy as sa\n\nimport ckan.plugins as p\nimport ckan.logic as logic\nimport ckan.lib.helpers as h\nfrom ckan.common import g\nfrom ckanext.drupal8 import views\nfrom ckan import model\n\nif p.toolkit.check_ckan_version(min_version='2.10.0'):\n from flask_login import login_user, logout_user\nelse:\n from ckan.common import session\n\n\nlog = logging.getLogger('ckanext.saml2')\n\n\ndef _no_permissions(context, msg):\n user = context['user']\n return {'success': False, 'msg': msg.format(user=user)}\n\n\n@logic.auth_sysadmins_check\ndef user_create(context, data_dict):\n msg = p.toolkit._('Users cannot be created.')\n return _no_permissions(context, msg)\n\n\n@logic.auth_sysadmins_check\ndef user_update(context, data_dict):\n msg = p.toolkit._('Users cannot be edited.')\n return _no_permissions(context, msg)\n\n\n@logic.auth_sysadmins_check\ndef user_reset(context, data_dict):\n msg = p.toolkit._('Users cannot reset passwords.')\n return _no_permissions(context, msg)\n\n\n@logic.auth_sysadmins_check\ndef request_reset(context, data_dict):\n msg = p.toolkit._('Users cannot reset passwords.')\n return _no_permissions(context, msg)\n\n\nclass Drupal8Plugin(p.SingletonPlugin):\n\n p.implements(p.IAuthenticator, inherit=True)\n p.implements(p.IAuthFunctions, inherit=True)\n p.implements(p.IConfigurer)\n p.implements(p.IConfigurable)\n p.implements(p.ITemplateHelpers)\n p.implements(p.IBlueprint)\n\n drupal_session_names = None\n\n def get_helpers(self):\n return {'ckanext_drupal8_domain': self.get_domain}\n\n def get_domain(self):\n return self.domain\n\n def update_config(self, config):\n p.toolkit.add_template_directory(config, 'templates')\n\n def configure(self, config):\n domain = config.get('ckanext.drupal8.domain')\n self.sysadmin_role = config.get('ckanext.drupal8.sysadmin_role')\n drupal_database_address = config.get('ckanext.drupal8.connection')\n self.allow_edit = config.get(\n 'ckanext.drupal8.allow_edit', 'false') == 'true'\n\n if not (domain and self.sysadmin_role and drupal_database_address):\n raise Exception('Drupal8 extension has not been configured')\n\n if len(domain.split(':')) > 2:\n raise Exception('Unexpected domain format. We expect at most one colon (example.com or example.com:port)')\n\n self.domains = [item.strip() for item in domain.split(\",\")]\n self.domain = self.domains[0]\n\n self.drupal_database_engine = sa.create_engine(drupal_database_address)\n\n def make_password(self):\n # create a hard to guess password\n out = ''\n for n in range(8):\n out += str(uuid.uuid4())\n return out\n\n def create_drupal_session_names(self):\n self.drupal_session_names = []\n domains = self.domains + [p.toolkit.request.environ['HTTP_HOST']]\n for domain in domains:\n domain_hash = hashlib.sha256(domain.encode('utf-8')).hexdigest()[:32]\n self.drupal_session_names.append('SESS%s' % domain_hash)\n self.drupal_session_names.append('SSESS%s' % domain_hash) # https\n\n def identify(self):\n ''' This does work around saml2 authorization.\n c.user contains the saml2 id of the logged in user we need to\n convert this to represent the ckan user. '''\n\n # If no drupal sesssion name create one\n if self.drupal_session_names in (None, []):\n self.create_drupal_session_names()\n # Can we find the user?\n cookies = p.toolkit.request.cookies\n\n user = None\n for drupal_session_name in self.drupal_session_names:\n drupal_sid = cookies.get(drupal_session_name)\n if drupal_sid:\n # Drupal session ids now need to be unquoted\n drupal_sid = urllib.parse.unquote(drupal_sid)\n sid_hash = hashlib.sha256(drupal_sid.encode('utf-8')).digest()\n encoded_sid_hash = base64.urlsafe_b64encode(sid_hash).replace(b\"=\", b'')\n encoded_sid_hash_str = encoded_sid_hash.decode('utf-8')\n with self.drupal_database_engine.begin() as conn:\n rows = conn.execute('SELECT u.name, u.mail, t.entity_id as uid FROM users_field_data u '\n 'JOIN sessions s on s.uid=u.uid LEFT OUTER JOIN '\n '(SELECT r.roles_target_id as role_name, r.entity_id FROM user__roles r '\n ' WHERE r.roles_target_id=%s '\n ') AS t ON t.entity_id = u.uid '\n 'WHERE s.sid=%s AND u.name != \\'\\'',\n [self.sysadmin_role, encoded_sid_hash_str])\n\n for row in rows:\n user = self.user(row)\n break\n\n g.user = user\n g.userobj = model.User.by_name(user)\n\n if p.toolkit.check_ckan_version(min_version='2.10.0'):\n if g.userobj:\n login_user(g.userobj)\n else:\n logout_user()\n elif g.user:\n session.save()\n \n def _email_hash(self, email):\n return hashlib.md5(email.strip().lower().encode('utf8')).hexdigest()\n\n def user(self, user_data):\n try:\n user = p.toolkit.get_action('user_show')(\n {'keep_email': True, 'ignore_auth': True}, {'id': user_data.name})\n except p.toolkit.ObjectNotFound:\n user = None\n\n if user:\n # update the user in ckan if not matching drupal data\n email_hash = user.get(\"email_hash\", None)\n\n if not email_hash:\n email_hash = self._email_hash(user.get(\"email\"))\n\n if (self._email_hash(user_data.mail) != email_hash\n or bool(user_data.uid) != user['sysadmin']):\n user['email'] = user_data.mail\n user['sysadmin'] = bool(user_data.uid)\n user['id'] = user_data.name\n user['fullname'] = user_data.name\n user = p.toolkit.get_action('user_update')(\n {'user': user['id'], 'ignore_auth': True}, user)\n else:\n user = {'email': user_data.mail,\n 'name': user_data.name,\n 'password': self.make_password(),\n 'sysadmin': bool(user_data.uid), }\n user = p.toolkit.get_action('user_create')(\n {'user': None, 'ignore_auth': True}, user)\n return user['name']\n\n def abort(self, status_code, detail, headers, comment):\n # HTTP Status 401 causes a login redirect. We need to prevent this unless we are actually trying to login.\n # The original ckanext-drupal8 aborts redirects, we actually want to be redirected to login page in case a user has not\n # been logged in yet.\n # self.identify()\n if (status_code == 401 and p.toolkit.c.user is not None):\n h.redirect_to('drupal8_unauthorized')\n return (status_code, detail, headers, comment)\n\n def get_auth_functions(self):\n # we need to prevent some actions being authorized.\n auth_functions = {\n 'user_create': user_create,\n 'user_reset': user_reset,\n 'request_reset': request_reset,\n }\n if not self.allow_edit:\n auth_functions['user_update'] = user_update\n return auth_functions\n\n # IBlueprint\n\n def get_blueprint(self):\n return views.get_blueprints()\n","repo_name":"vrk-kpa/ckanext-drupal8","sub_path":"ckanext/drupal8/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":7631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"22145400614","text":"def lower_bound(array, key):\n n = len(array)\n start = 0\n end = n - 1\n mid = 0\n while start < end:\n mid = int((start + end) / 2)\n if array[mid] < key:\n start = mid + 1\n else:\n end = mid - 1\n ans = 0\n while mid >= 0 and array[mid] >= key:\n mid -= 1\n mid = max(mid, 0)\n while mid < n and array[mid] < key:\n mid += 1\n # return mid is a lower_bound\n while mid < n and key == array[mid]:\n mid += 1\n ans += 1\n return ans\n\n\ndef many(array, temp):\n ans = 0\n for x in temp:\n ans += lower_bound(array, x)\n return ans\n\n\ndef solve():\n num = tuple([int(x) for x in input().split(\" \")])\n array = sorted([int(x) for x in input().split(\" \")])\n A = [int(x) for x in input().split(\" \")]\n B = [int(x) for x in input().split(\" \")]\n a = many(array, A)\n b = many(array, B)\n print(a - b)\n\n\nsolve()","repo_name":"nayan32biswas/problem-solving","sub_path":"Hackerrank/No Idea.py","file_name":"No Idea.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"9597887376","text":"__doc__ = 'Renames all sheets to UPPERCASE.'\n\nfrom Autodesk.Revit.DB import Transaction, FilteredElementCollector, BuiltInCategory\n\nuidoc = __revit__.ActiveUIDocument\ndoc = __revit__.ActiveUIDocument.Document\n\ncl_views = FilteredElementCollector(doc)\nviews = cl_views.OfCategory(BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToElements()\nsheets = sorted(views, key=lambda x: x.SheetNumber)\n\nt = Transaction(doc, 'Rename Sheets to Upper')\nt.Start()\n\nfor el in sheets:\n sheetnameparam = el.LookupParameter('Sheet Name')\n name = sheetnameparam.AsString()\n name = name.upper()\n print('RENAMING:\\t{0}\\n'\n ' to:\\t{1}\\n'.format(name, name.upper()))\n sheetnameparam.Set(name)\n\nt.Commit()\n","repo_name":"ErwinMeulman/Python","sub_path":"Sheets_renameAllSheetsToUpperCase.py","file_name":"Sheets_renameAllSheetsToUpperCase.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"9"} +{"seq_id":"23468043938","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport getopt\nimport sys\n\nclass FileExtModification(object):\n\tdef __init__(self, fileinfos):\n\t\tassert(len(fileinfos) == 3)\n\t\tself.__modifyPath = fileinfos[0] #需要修改文件后缀的路径\n\t\tself.__needModifyExt = fileinfos[1] #需要修改的后缀名\n\t\tself.__modifiedExt = fileinfos[2] #修改后的后缀名\n\n\tdef __change_word_dir(self):\n\t\tos.chdir(self.__modifyPath)\n\n\tdef __get_all_files(self):\n\t\tself.__change_word_dir()\n\t\tfiles = os.listdir(self.__modifyPath)\n\t\treturn files\n\t\t\n\tdef __find_files(self):\n\t\tfiles = []\n\t\tfor file in self.__get_all_files():\n\t\t\tif file.split(\".\")[1] == self.__needModifyExt:\n\t\t\t\tfiles.append(file)\n\t\treturn files\n\t\t\t\t\n\tdef change_file_ext(self):\n\t\ttry:\n\t\t\tfor file in self.__find_files():\n\t\t\t\tos.renames(file, file.split(\".\")[0] + \".\" + self.__modifiedExt)\n\t\texcept:\n\t\t\tpass\n\t\t\t\ndef parseCmdLine():\n\t#只输入脚本名称时的默认参数\n\tmodifyPath = os.path.abspath(\"./files\") # 需要修改文件后缀的路径\n\tneedModifyExt = \"txt\" # 需要修改的后缀名\n\tmodifiedExt = \"bat\" # 修改后的后缀名\n\t#解析命令行参数,参数格式为 python modify_file_ext.py modify_path need_modify_file_ext modified_file_ext\n\topts, args = getopt.getopt(sys.argv[1:], \"\")\n\tif len(args) == 1:\n\t\tmodifyPath = os.path.abspath(args[0])\n\telif len(args) == 2:\n\t\tmodifyPath = os.path.abspath(args[0])\n\t\tneedModifyExt = args[1]\n\telif len(args) == 3:\n\t\tmodifyPath = os.path.abspath(args[0])\n\t\tneedModifyExt = args[1]\n\t\tmodifiedExt = args[2]\n\telif len(args) > 3:\n\t\tprint(\"Too many argumens!!!\")\n\n\treturn [modifyPath, needModifyExt, modifiedExt]\n\n\nif __name__ == \"__main__\":\n\tfile_infos = parseCmdLine()\n\tfile_ext_modification = FileExtModification(file_infos)\n\tfile_ext_modification.change_file_ext()","repo_name":"yalong0424/learnPython","sub_path":"Demos/modify_file_ext/modify_file_ext.py","file_name":"modify_file_ext.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"10743980792","text":"import anchorpoint as ap\nimport apsync as aps\n\nfrom git_project import add_git_ignore\n\ndef on_is_action_enabled(path: str, type: ap.Type, ctx: ap.Context) -> bool:\n try:\n if type != ap.Type.JoinProjectFiles: return False\n project = aps.get_project_by_id(ctx.project_id, ctx.workspace_id)\n if not project: return False\n channel = aps.get_timeline_channel(project, \"Git\")\n return channel is not None\n except Exception as e:\n return False\n\nif __name__ == \"__main__\":\n import sys, os\n script_dir = os.path.join(os.path.dirname(__file__), \"..\")\n sys.path.insert(0, script_dir)\n\n try:\n from vc.apgit.repository import * \n except Warning as e:\n sys.exit(0)\n\n import platform\n import git_repository_helper as helper\n if script_dir in sys.path: sys.path.remove(script_dir)\n\n ctx = ap.get_context()\n ui = ap.UI()\n\n if ctx.type != ap.Type.JoinProjectFiles:\n sys.exit(0)\n\n project_id = ctx.project_id\n workspace_id = ctx.workspace_id\n project = aps.get_project_by_id(project_id, workspace_id)\n if not project:\n ui.show_error(\"Cannot create git repository\", \"You must create a project first\")\n sys.exit(0) \n\n timeline_channel = aps.get_timeline_channel(project, helper.CHANNEL_ID)\n settings = aps.Settings(\"git_repository\") \n\n def clone_repo_async(repo_path: str, url: str, join_project_files, project, timeline_channel, workspace_id, patch_channel):\n with os.scandir(repo_path) as it:\n if any(it):\n ap.UI().show_info(\"Cannot Clone Git repository\", \"Folder must be empty\")\n return\n \n try:\n progress = ap.Progress(\"Cloning Git Repository\", show_loading_screen = True)\n repo = GitRepository.clone(url, repo_path, ctx.username, ctx.email, progress=helper.CloneProgress(progress))\n progress.finish()\n helper.update_project(repo_path, url, join_project_files, timeline_channel, project, True)\n add_git_ignore(repo, ctx, repo_path)\n if patch_channel:\n patch_timeline_channel(project, timeline_channel, workspace_id, url)\n\n except Exception as e:\n print(e)\n d = ap.Dialog()\n d.title = \"Could not clone Git Repository\"\n d.icon = \":/icons/versioncontrol.svg\"\n\n remote_name = \"\"\n if \"azure\" in url or \"visualstudio\" in url:\n remote_name = \"Azure DevOps\"\n elif \"github\" in url:\n remote_name = \"GitHub\"\n elif \"gitlab\" in url:\n remote_name = \"GitLab\"\n elif \"bitbucket\" in url:\n remote_name = \"Bitbucket\"\n else:\n remote_name = \"remote\"\n\n d.add_info(f\"You might have entered a wrong username / password, or you don't
have access to the {remote_name} repository. Read more\")\n\n def retry():\n ctx.run_async(clone_repo_async, repo_path, url, join_project_files, project, timeline_channel, workspace_id, patch_channel)\n d.close()\n\n d.add_button(\"Retry\", callback=lambda d: retry()).add_button(\"Close\", callback=lambda d: d.close(), primary=False)\n d.show()\n raise e\n\n def patch_timeline_channel(project, timeline_channel, workspace_id, url):\n access = aps.get_workspace_access(workspace_id)\n if access == aps.AccessLevel.Owner or access == aps.AccessLevel.Admin:\n try:\n metadata = timeline_channel.metadata\n metadata[\"gitRemoteUrl\"] = url\n timeline_channel.metadata = metadata\n aps.update_timeline_channel(project, timeline_channel)\n except:\n \"Could not patch timeline channel\"\n\n def is_location_same_repo(path: str, url: str):\n try:\n repo = GitRepository.load(path)\n if repo and url == repo.get_remote_url():\n return True\n return False\n except: \n return False\n \n\n def join_repo(dialog: ap.Dialog, url, project, timeline_channel, ctx):\n location = dialog.get_value(\"location\")\n if not url:\n url = dialog.get_value(\"url\")\n patch_channel = True\n else:\n patch_channel = False\n\n dialog.close()\n \n if is_location_same_repo(location, url):\n repo = GitRepository.load(location)\n repo.set_username(ctx.username, ctx.email, location)\n helper.update_project(location, url, True, timeline_channel, project)\n add_git_ignore(repo, ctx, location)\n else:\n ctx.run_async(clone_repo_async, location, url, True, project, timeline_channel, ctx.workspace_id, patch_channel)\n\n def validate_path(dialog: ap.Dialog, value: str, url: str):\n if not value or len(value) == 0:\n return \"Please add a folder for your project files\"\n if not os.path.exists(value):\n return \"Please add a real folder\"\n if not helper.folder_empty(value):\n if not url:\n url = dialog.get_value(\"url\")\n if is_location_same_repo(value, url):\n return\n return \"Please pick an empty folder\"\n return\n\n def validate_url(dialog: ap.Dialog, value: str):\n if not value or len(value) == 0:\n return \"Please add a Git repository URL\"\n return\n\n def update_dialog(dialog: ap.Dialog, value):\n dialog.set_enabled(\"join\", dialog.is_valid())\n\n dialog = ap.Dialog()\n dialog.title = \"Join Git Repository\"\n dialog.icon = ctx.icon\n \n path_placeholder = \"Z:\\\\Projects\\\\ACME_Commercial\"\n if platform.system() == \"Darwin\":\n path_placeholder = \"/Projects/ACME_Commercial\" \n\n try:\n remote_url = timeline_channel.metadata[\"gitRemoteUrl\"]\n except:\n remote_url = None\n\n dialog.add_text(\"Project Folder\")\n dialog.add_info(\"Pick an empty folder to download the project files or tell Anchorpoint where your
repository is located\")\n dialog.add_input(placeholder=path_placeholder, var=\"location\", width=400, browse=ap.BrowseType.Folder, validate_callback=lambda d,v: validate_path(d,v,remote_url), callback=update_dialog)\n \n if not remote_url:\n dialog.add_text(\"Repository URL\")\n dialog.add_input(placeholder=\"https://github.com/Anchorpoint-Software/ap-actions.git\", var=\"url\", width=400, validate_callback=validate_url, callback=update_dialog)\n dialog.set_valid(False)\n\n browse_path = settings.get(\"browse_path\")\n if browse_path is not None:\n dialog.set_browse_path(var=\"location\", path=browse_path)\n \n dialog.add_button(\"Join\", var=\"join\", callback=lambda d: join_repo(d, remote_url, project, timeline_channel, ctx), enabled=False)\n dialog.show()","repo_name":"Anchorpoint-Software/ap-actions","sub_path":"versioncontrol/actions/git_join_repository.py","file_name":"git_join_repository.py","file_ext":"py","file_size_in_byte":7046,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"9"} +{"seq_id":"9400094369","text":"#! /usr/bin/python2\n#-*- coding: iso-8859-15 -*-\n\n\"\"\"-------------------------------------------------------------------------\n Pinguino Bootloader Auto Detection\n\n Author: Regis Blanchot \n Last release: 2012-12-15\n\n This library is free software you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library 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 GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n-------------------------------------------------------------------------\"\"\"\n\n#import sys\n#import os\n#import usb # checked in check.py\n\nfrom uploader import baseUploader\n\nclass autodetect(baseUploader):\n \"\"\" detect bootloader version \"\"\"\n\n # General Data Packet Structure (usbBuf)\n # --------------------------------------------------------------------------\n # __________________\n # | COMMAND | 0 [CMD]\n # | LEN | 1 [LEN]\n # | ADDRL | 2 [ ] [addrl]\n # | ADDRH | 3 [ADR.pAdr]: [addrh]\n # | ADDRU | 4 [ ] [addru]\n # | | 5 [DATA]\n # | |\n # . DATA .\n # . .\n # | | 62\n # |________________| 63\n #\n # --------------------------------------------------------------------------\n BOOT_CMD = 0\n BOOT_CMD_LEN = 1\n BOOT_ADDR_LO = 2\n BOOT_ADDR_HI = 3\n BOOT_ADDR_UP = 4\n BOOT_DATA_START = 5\n\n BOOT_DEV1 = 5\n BOOT_DEV2 = 6\n\n BOOT_VER_MINOR = 2\n BOOT_VER_MAJOR = 3\n\n BOOT_SIZE = 1\n\n # Bootloader commands\n # --------------------------------------------------------------------------\n READ_VERSION_CMD = 0x00\n READ_FLASH_CMD = 0x01\n WRITE_FLASH_CMD = 0x02\n ERASE_FLASH_CMD = 0x03\n #READ_EEDATA_CMD = 0x04\n #WRITE_EEDATA_CMD = 0x05\n #READ_CONFIG_CMD = 0x06\n #WRITE_CONFIG_CMD = 0x07\n RESET_CMD = 0xFF\n\n # Data Block's size to write\n # --------------------------------------------------------------------------\n DATABLOCKSIZE = 32\n\n # USB Packet size\n # --------------------------------------------------------------------------\n MAXPACKETSIZE = 64\n\n # bulk endpoints\n # --------------------------------------------------------------------------\n IN_EP = 0x81 # endpoint for Bulk reads\n OUT_EP = 0x01 # endpoint for Bulk writes\n\n # configuration\n # --------------------------------------------------------------------------\n ACTIVE_CONFIG = 0x01\n INTERFACE_ID = 0x00\n TIMEOUT = 1200\n\n# ------------------------------------------------------------------------------\n def initDevice(self):\n# ------------------------------------------------------------------------------\n# TODO: to move in uploader.py ?\n# ------------------------------------------------------------------------------\n \"\"\" init pinguino device \"\"\"\n #conf = self.device.configurations[0]\n #iface = conf.interfaces[0][0]\n handle = self.device.open()\n if handle:\n ##handle.detachKernelDriver(iface.interfaceNumber)\n #handle.setConfiguration(conf)\n #handle.claimInterface(iface)\n ##handle.setAltInterface(iface)\n handle.setConfiguration(self.ACTIVE_CONFIG)\n handle.claimInterface(self.INTERFACE_ID)\n return handle\n return self.ERR_USB_INIT1\n# ------------------------------------------------------------------------------\n def sendCMD(self, usbBuf):\n# ------------------------------------------------------------------------------\n \"\"\" send command to the bootloader \"\"\"\n sent_bytes = self.handle.bulkWrite(self.OUT_EP, usbBuf, self.TIMEOUT)\n #print sent_bytes\n if sent_bytes == len(usbBuf):\n #print \"Block issued without problem.\"\n # whatever is returned, USB packet size is always 64 bytes long in high speed mode\n return self.handle.bulkRead(self.IN_EP, self.MAXPACKETSIZE, self.TIMEOUT)\n else:\n return self.ERR_USB_WRITE\n# ------------------------------------------------------------------------------\n def detect(self):\n# ------------------------------------------------------------------------------\n\n # search for a Pinguino board\n # ----------------------------------------------------------------------\n\n self.device = self.getDevice()\n if self.device == self.ERR_DEVICE_NOT_FOUND:\n self.add_report(\"Pinguino not found\\n\")\n self.add_report(\"Is your device connected and/or in bootloader mode ?\\n\")\n return\n else:\n self.add_report(\"Pinguino found ...\\n\")\n\n self.handle = self.initDevice()\n if self.handle == self.ERR_USB_INIT1:\n # wrong active config\n # bootloader version is 1.x or 2.x\n return (2,12)\n\n # find out bootloader version\n # ----------------------------------------------------------------------\n\n usbBuf = [0] * self.MAXPACKETSIZE\n # command code\n usbBuf[self.BOOT_CMD] = self.READ_VERSION_CMD\n # write data packet and get response\n usbBuf = self.sendCMD(usbBuf)\n if usbBuf != self.ERR_USB_WRITE:\n # major.minor\n version = ( usbBuf[self.BOOT_VER_MAJOR], \\\n usbBuf[self.BOOT_VER_MINOR] )\n self.closeDevice()\n return version\n# ------------------------------------------------------------------------------\n","repo_name":"PinguinoIDE/pinguino-ide","sub_path":"pinguino/qtgui/pinguino_core/uploader/autodetect.py","file_name":"autodetect.py","file_ext":"py","file_size_in_byte":6708,"program_lang":"python","lang":"en","doc_type":"code","stars":79,"dataset":"github-code","pt":"9"} +{"seq_id":"70155218213","text":"def test_tasks_config_plan():\n from netnir.core.tasks.config_plan import ConfigPlan\n from netnir.helpers.common.args import (\n filter_group,\n filter_host,\n filter_hosts,\n output,\n verbose,\n num_workers,\n make_changes,\n )\n import argparse\n\n parser = argparse.ArgumentParser()\n filter_host(parser)\n filter_hosts(parser)\n filter_group(parser)\n output(parser)\n verbose(parser)\n num_workers(parser)\n make_changes(parser)\n parser.add_argument(\"--compile\", const=True, nargs=\"?\")\n parser.add_argument(\"--include-tags\", action=\"append\")\n parser.add_argument(\"--exclude-tags\", action=\"append\")\n args = parser.parse_args()\n cp = ConfigPlan(args=args)\n cp.args.compile = True\n cp.args.host = \"router.dc1\"\n\n assert isinstance(cp.nr, object)\n assert cp.args.verbose == \"INFO\"\n assert cp.args.compile is True\n assert cp.args.host == \"router.dc1\"\n assert isinstance(cp.parser, object)\n result = cp.run()\n assert (\n result.get(\"router.dc1\").result\n == \"hostname router.dc1\\nos iosxr\\nbb_asn 64512\\ndc_asn 64513\"\n )\n","repo_name":"netdevops/netnir","sub_path":"tests/netnir/core/tasks/test_tasks_config_plan.py","file_name":"test_tasks_config_plan.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"17262405010","text":"from sys import modules, platform\n\n\n\nwebp_download_repository = \"https://storage.googleapis.com/downloads.webmproject.org/releases/webp/index.html\"\nsys_platform_value = ''\ndict_sys_platform_value = {\"darwin\":\"MAC OS X\", \"cygwin\":\"Windows / Cygwin\", \"win32\":\"Windows\",\"linux\": \"Linux Distribution\"}\nLINKTOCLICK = None\nLibWebPVersion = \"1.1.1\"\nbuild_webp_from_source = { \"darwin\":[ \"port self update\", \" sudo port selfupdate\", \"install dependencies\", \" sudo port install jpeg libpng tiff giflib\",],\n\"cygwin\":[\"The most recent version of the Cygwin DLL is {LINKTOCLICK}\",],\n\"win32\":[\"download then extract file then run the following f-string in windows cli\", \"nmake /f Makefile.vc CFG=release-static RTLIBCFG=static OBJDIR=output\",],\n\"linux\": [\" sudo apt-get install libjpeg-dev libpng-dev libtiff-dev libgif-dev\",]}\n\ndef python_module_check():\n if module['PIL']:\n check_system_platform()\n\ndef check_system_platform():\n sys_platform_value = platform\ndef post_system_check_build():\n F\" tar xvzf libwebp-{LibWebPVersion}.tar.gz\"\n f\"cd libwebp-{LibWebPVersion}\"\n f\"./configure\"\n f\"make\"\n f\"sudo make install\"\n\n\n\n\n # CLI for linux/mac to convert all files to webp\n # $ for F in *.jpg; do cwebp $F -o `basename ${F%.jpg}`.webp; done\n # CLI for Windows to convert all files to webp\n # > for /R . %I in (*.jpg) do ( cwebp.exe %I -o %~fnI.webp )\n # CLI to convert from webp to other formats\n # f \"dwebp {image}.webp -o {image}.png\"\n # cli to convert files into webp format.\n # f\"cwebp -q {70} {picture_with_alpha}.png -o {picture_with_alpha}.webp\"\n # -q is a float specifying quality rating for new photo Higher numbers mean greater compression and less immage quality.\n # -z integer to turn lossless compression on defaul to 6, 9 is fast but larger file size. Using it with -m wil invalidate the effect of -z.\n # -preset string\n # Specify a set of pre-defined parameters to suit a particular type of source material. Possible values are: default, photo, picture, drawing, icon, text.\n # Since -preset overwrites the other parameters' values (except the -q one), this option should preferably appear first in the order of the arguments.\n # WebP is bitstream-compatible with VP8 and uses 14 bits for width and height. The maximum pixel dimensions of a WebP image is 16383 x 16383.\n # Consistent with the VP8 bitstream, lossy WebP works exclusively with an 8-bit Y'CbCr 4:2:0 (often called YUV420) image format. Please refer to Section 2, \"Format Overview\" of RFC 6386, VP8 Data Format and Decoding Guide for more detail.\n\n # Lossless WebP works exclusively with the RGBA format. See the WebP Lossless Bitstream specification.\n # #//javascript version\n # // check_webp_feature:\n # // 'feature' can be one of 'lossy', 'lossless', 'alpha' or 'animation'.\n # // 'callback(feature, result)' will be passed back the detection result (in an asynchronous way!)\n # function check_webp_feature(feature, callback) {\n # var kTestImages = {\n # lossy: \"UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA\",\n # lossless: \"UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==\",\n # alpha: \"UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==\",\n # animation: \"UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA\"\n # };\n # var img = new Image();\n # img.onload = function () {\n # var result = (img.width > 0) && (img.height > 0);\n # callback(feature, result);\n # };\n # img.onerror = function () {\n # callback(feature, false);\n # };\n # img.src = \"data:image/webp;base64,\" + kTestImages[feature];\n # }\n # WebM does not currently incorporate all the compression techniques from WebP. As a result, this image compresses significantly better with WebP than the alternatives:\n\n # GIF (85 KB)\n # WebM with alpha (32 KB)\n # Lossless animated WebP (5 KB) 4\n\n","repo_name":"wearypossum4770/group_project","sub_path":"config/webp.py","file_name":"webp.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"25680039086","text":"# Calculate the equilibrium mass based on initialising\n# a monodisperse population\nimport numpy as np\n\n#Avogadros number\nNA=6.0221409e+23\n\n# Implement equation 2.8\ndef partitioning(Cstar,abundance,COA_c,core):\n # Partitioning coefficient\n epsilon = np.power(1.0+(Cstar/(COA_c+core)),-1.0)\n # Partitionined mass\n COA_c = np.sum(epsilon*abundance)\n return COA_c\n\n# Implement equation 2.13\ndef partitioning_dash(Cstar,abundance,COA_c,core):\n epsilon = np.power(1.0+(Cstar/(COA_c+core)),-2.0)*(Cstar/((COA_c+core)**2.0))\n COA_dash = np.sum(epsilon*abundance)\n return COA_dash\n\n# Implement Newtons method\ndef Newtons_method(Cstar,abundance,COA_init,core):\n\n COA_c = partitioning(Cstar,abundance,COA_init,core)\n f = COA_c - (partitioning(Cstar,abundance,COA_c,core))\n f_dash = 1.0 - partitioning_dash(Cstar,abundance,COA_c,core)\n COA_new = COA_c - f/f_dash\n\n while (abs((COA_new-COA_c)/COA_new) > 1.0e-3):\n\n COA_c = COA_new\n f = COA_c - (partitioning(Cstar,abundance,COA_c,core))\n f_dash = 1.0 - partitioning_dash(Cstar,abundance,COA_c,core)\n COA_new = COA_c - f/f_dash\n\n return COA_c\n\n# Define the gaseous and condensed phase components\n# Number of condensing species from the gas phase\nnum_species = 10\n# Number of size bins\nnum_bins = 1\n# The volatility of each specie, using the mass based C* convention\n# Here we assuming a linear seperation in Log10 space\nlog_c_star = np.linspace(-6, 3, num_species)\nCstar = np.power(10.0,log_c_star)\n\n# Populate volatility basis set with gas phase abundance\nabundance = np.zeros((num_species), dtype = float)\nabundance[0] = 0.1\nabundance[1] = 0.1\nabundance[2] = 0.15\nabundance[3] = 0.22\nabundance[4] = 0.36\nabundance[5] = 0.47\nabundance[6] = 0.58\nabundance[7] = 0.69\nabundance[8] = 0.84\nabundance[9] = 1.0\n\n# Define a monodisperse size distribution\n# Assume each particle starts with an involatile core\n# of absorptive organic with a mass of 200 g/mol and\n# density 1400 km/m3. We store this information in an array\n# as 'core'. This will ensure, in this example, that we do\n# not get 100% evaporative loss\n\n# Define total number of particles [per cc]\nN_total = 300.0\n\n# We carry an inert and involatile in each size bin\ncore = np.zeros((num_bins), dtype=float)\ncore_abundance = np.zeros((num_bins), dtype=float)\ndensity_core = np.zeros((num_bins), dtype=float)\ncore_mw = np.zeros((num_bins), dtype=float)\ndensity_core[:] = 1400.0 #kg.m-3\n\n# The number of particles is only carried in one bin\nN_per_bin = np.zeros((num_bins), dtype=float)\nN_per_bin[0] = N_total\n\n# Define the diameter of our particles [microns]\nsize_array = np.zeros((num_bins), dtype=float)\nsize_array[0] = 0.150 #microns\n\n# Use the size to now calculate a concentration of a 'core' in molecules / cc\n# This aligns with the units used for volatile species\ncore_abundance[0] = (N_per_bin[0])*((4.0/3.0)*\n np.pi*np.power(size_array[0]*0.5e-6,3.0)*\n density_core[0]*1.0e3)\n\n# What is our existing dry mass in micrograms per cubic metre?\ndry_mass = np.sum((core_abundance)*(1.0e12))\n\nprint(\"Initial mass = \", dry_mass)\n\n# Initialise a value for COA\nCOA_first_guess = 1.0\n# Now use Newtons method for iterating to a final mass\nCOA_final = Newtons_method(Cstar,abundance,COA_first_guess,dry_mass)\n\nprint(\"Secondary mass = \", COA_final)\n\n# We can also calculate the partitioning coefficients for all volatility bins\nepsilon = np.power(1.0+(Cstar/(COA_final+dry_mass)),-1.0)\nprint(\"Partitioning coefficients = \", epsilon)\n","repo_name":"aerosol-modelling/Book-Code","sub_path":"ch02/Answer_2_1.py","file_name":"Answer_2_1.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"9"} +{"seq_id":"13677971939","text":"from dash.dependencies import Input, Output\nimport dash_html_components as html\nimport dash_core_components as dcc\nimport plotly.graph_objs as go\nimport pandas as pd\n\nfrom app import app\nfrom header import header\n#from flask_caching import Cache\n\n#cache = app.cache\n\ndf = pd.read_csv('./data/df_th.csv', index_col=0).groupby([\"state\"], as_index=False).sum()\nnew_cols = ['state', '02HC01_VC03', '02HC01_VC04', '02HC01_VC05']\ndf = df[new_cols]\nfor col in df.columns:\n df[col] = df[col].astype(str)\n\nscl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\\\n [0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]\n\ndf['text'] = df['state'] + '
' +\\\n 'Total Household '+df['02HC01_VC03']+' Family households (families) '+df['02HC01_VC04']+'
'+\\\n 'Family households (families) - With own children of the householder under 18 years '+df['02HC01_VC05']\n\nlayout = html.Div([\n header,\n html.H2('Choropleth Map - states layout'),\n dcc.Graph(\n id = 'states-choropleth',\n figure={\n 'data':[\n go.Choropleth(\n colorscale = scl,\n autocolorscale = True,\n locations = df['state'],\n z = df['02HC01_VC03'].astype(float),\n locationmode = 'USA-states',\n text = df['text'],\n marker = dict(\n line = dict (\n color = 'rgb(255,255,255)',\n width = 2\n ) ),\n colorbar = dict(\n title = \"Total Household\")\n )\n ],\n 'layout': go.Layout(\n title = 'Total Household
(Hover for breakdown)',\n geo = dict(\n scope='usa',\n projection=dict( type='albers usa' ),\n showlakes = True,\n lakecolor = 'rgb(255, 255, 255)')\n )\n }\n )\n]) ######## END OF LAYOUT ########\n#@cache.memoize()\n","repo_name":"DistrictDataLabs/city-dash","sub_path":"multi-city-dash/apps/app4.py","file_name":"app4.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"9"} +{"seq_id":"3127509494","text":"import ePYt\n\n\nclass Class1:\n prop = \"asdf\"\n\n def __init__(self):\n self.a = 1\n\n def method(self):\n print(self.prop)\n\n\nanalysis_result = ePYt.analysis.Analyzer(\"./sample_target\")\nprint(analysis_result.table)\n_ = input()\n","repo_name":"luxroot/ePYt","sub_path":"sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"71081228455","text":"\"\"\"\r\nCode adapted from the Mathis Lab\r\nMIT License Copyright (c) 2022 Mackenzie Mathis\r\nDataJoint Schema for DeepLabCut 2.x, Supports 2D and 3D DLC via triangulation.\r\n\"\"\"\r\nimport datajoint as dj\r\nimport os\r\nimport cv2\r\nimport csv\r\nimport yaml\r\nimport inspect\r\nimport importlib\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom pathlib import Path\r\nfrom typing import Optional\r\nfrom datetime import datetime\r\nfrom element_interface.utils import find_full_path, find_root_directory\r\nfrom .readers import dlc_reader\r\n\r\nschema = dj.schema()\r\n_linking_module = None\r\n\r\n\r\ndef activate(\r\n model_schema_name: str,\r\n *,\r\n create_schema: bool = True,\r\n create_tables: bool = True,\r\n linking_module: bool = None,\r\n):\r\n \"\"\"Activate this schema.\r\n\r\n Args:\r\n model_schema_name (str): schema name on the database server\r\n create_schema (bool): when True (default), create schema in the database if it\r\n does not yet exist.\r\n create_tables (bool): when True (default), create schema tables in the database\r\n if they do not yet exist.\r\n linking_module (str): a module (or name) containing the required dependencies.\r\n\r\n Dependencies:\r\n Upstream tables:\r\n Session: A parent table to VideoRecording, identifying a recording session.\r\n Equipment: A parent table to VideoRecording, identifying a recording device.\r\n Functions:\r\n get_dlc_root_data_dir(): Returns absolute path for root data director(y/ies)\r\n with all behavioral recordings, as (list of) string(s).\r\n get_dlc_processed_data_dir(): Optional. Returns absolute path for processed\r\n data. Defaults to session video subfolder.\r\n \"\"\"\r\n\r\n if isinstance(linking_module, str):\r\n linking_module = importlib.import_module(linking_module)\r\n assert inspect.ismodule(\r\n linking_module\r\n ), \"The argument 'dependency' must be a module's name or a module\"\r\n assert hasattr(\r\n linking_module, \"get_dlc_root_data_dir\"\r\n ), \"The linking module must specify a lookup function for a root data directory\"\r\n\r\n global _linking_module\r\n _linking_module = linking_module\r\n\r\n # activate\r\n schema.activate(\r\n model_schema_name,\r\n create_schema=create_schema,\r\n create_tables=create_tables,\r\n add_objects=_linking_module.__dict__,\r\n )\r\n\r\n\r\n# -------------- Functions required by element-deeplabcut ---------------\r\n\r\n\r\ndef get_dlc_root_data_dir() -> list:\r\n \"\"\"Pulls relevant func from parent namespace to specify root data dir(s).\r\n\r\n It is recommended that all paths in DataJoint Elements stored as relative\r\n paths, with respect to some user-configured \"root\" director(y/ies). The\r\n root(s) may vary between data modalities and user machines. Returns a full path\r\n string or list of strings for possible root data directories.\r\n \"\"\"\r\n root_directories = _linking_module.get_dlc_root_data_dir()\r\n if isinstance(root_directories, (str, Path)):\r\n root_directories = [root_directories]\r\n\r\n if (\r\n hasattr(_linking_module, \"get_dlc_processed_data_dir\")\r\n and get_dlc_processed_data_dir() not in root_directories\r\n ):\r\n root_directories.append(_linking_module.get_dlc_processed_data_dir())\r\n\r\n return root_directories\r\n\r\n\r\ndef get_dlc_processed_data_dir() -> Optional[str]:\r\n \"\"\"Pulls relevant func from parent namespace. Defaults to DLC's project /videos/.\r\n\r\n Method in parent namespace should provide a string to a directory where DLC output\r\n files will be stored. If unspecified, output files will be stored in the\r\n session directory 'videos' folder, per DeepLabCut default.\r\n \"\"\"\r\n if hasattr(_linking_module, \"get_dlc_processed_data_dir\"):\r\n return _linking_module.get_dlc_processed_data_dir()\r\n else:\r\n return None\r\n\r\n\r\n# ----------------------------- Table declarations ----------------------\r\n\r\n\r\n@schema\r\nclass VideoRecording(dj.Manual):\r\n \"\"\"Set of video recordings for DLC inferences.\r\n\r\n Attributes:\r\n Session (foreign key): Session primary key.\r\n recording_id (int): Unique recording ID.\r\n Device (foreign key): Device table primary key, used for default output\r\n directory path information.\r\n \"\"\"\r\n\r\n definition = \"\"\"\r\n -> Session\r\n recording_id: int\r\n ---\r\n -> Device\r\n \"\"\"\r\n\r\n class File(dj.Part):\r\n \"\"\"File IDs and paths associated with a given recording_id\r\n\r\n Attributes:\r\n VideoRecording (foreign key): Video recording primary key.\r\n file_path ( varchar(255) ): file path of video, relative to root data dir.\r\n \"\"\"\r\n\r\n definition = \"\"\"\r\n -> master\r\n file_id: int\r\n ---\r\n file_path: varchar(255) # filepath of video, relative to root data directory\r\n \"\"\"\r\n\r\n\r\n@schema\r\nclass RecordingInfo(dj.Imported):\r\n \"\"\"Automated table with video file metadata.\r\n\r\n Attributes:\r\n VideoRecording (foreign key): Video recording key.\r\n px_height (smallint): Height in pixels.\r\n px_width (smallint): Width in pixels.\r\n nframes (int): Number of frames.\r\n fps (int): Optional. Frames per second, Hz.\r\n recording_datetime (datetime): Optional. Datetime for the start of recording.\r\n recording_duration (float): video duration (s) from nframes / fps.\"\"\"\r\n\r\n definition = \"\"\"\r\n -> VideoRecording\r\n ---\r\n px_height : smallint # height in pixels\r\n px_width : smallint # width in pixels\r\n nframes : int # number of frames \r\n fps = NULL : int # (Hz) frames per second\r\n recording_datetime = NULL : datetime # Datetime for the start of the recording\r\n recording_duration : float # video duration (s) from nframes / fps\r\n \"\"\"\r\n\r\n @property\r\n def key_source(self):\r\n \"\"\"Defines order of keys for make function when called via `populate()`\"\"\"\r\n return VideoRecording & VideoRecording.File\r\n\r\n def make(self, key):\r\n \"\"\"Populates table with video metadata using CV2.\"\"\"\r\n file_paths = (VideoRecording.File & key).fetch(\"file_path\")\r\n\r\n nframes = 0\r\n px_height, px_width, fps = None, None, None\r\n\r\n for file_path in file_paths:\r\n file_path = (find_full_path(get_dlc_root_data_dir(), file_path)).as_posix()\r\n\r\n cap = cv2.VideoCapture(file_path)\r\n info = (\r\n int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),\r\n int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),\r\n int(cap.get(cv2.CAP_PROP_FPS)),\r\n )\r\n if px_height is not None:\r\n assert (px_height, px_width, fps) == info\r\n px_height, px_width, fps = info\r\n nframes += int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\r\n cap.release()\r\n\r\n self.insert1(\r\n {\r\n **key,\r\n \"px_height\": px_height,\r\n \"px_width\": px_width,\r\n \"nframes\": nframes,\r\n \"fps\": fps,\r\n \"recording_duration\": nframes / fps,\r\n }\r\n )\r\n\r\n\r\n@schema\r\nclass BodyPart(dj.Lookup):\r\n \"\"\"Body parts tracked by DeepLabCut models\r\n\r\n Attributes:\r\n body_part ( varchar(32) ): Body part short name.\r\n body_part_description ( varchar(1000),optional ): Full description\r\n\r\n \"\"\"\r\n\r\n definition = \"\"\"\r\n body_part : varchar(32)\r\n ---\r\n body_part_description='' : varchar(1000)\r\n \"\"\"\r\n\r\n @classmethod\r\n def extract_new_body_parts(cls, dlc_config: dict, verbose: bool = True):\r\n \"\"\"Returns list of body parts present in dlc config, but not BodyPart table.\r\n\r\n Args:\r\n dlc_config (str or dict): path to a config.y*ml, or dict of such contents.\r\n verbose (bool): Default True. Print both existing and new items to console.\r\n \"\"\"\r\n if not isinstance(dlc_config, dict):\r\n dlc_config_fp = find_full_path(get_dlc_root_data_dir(), Path(dlc_config))\r\n assert dlc_config_fp.exists() and dlc_config_fp.suffix in (\r\n \".yml\",\r\n \".yaml\",\r\n ), f\"dlc_config is neither dict nor filepath\\n Check: {dlc_config_fp}\"\r\n if dlc_config_fp.suffix in (\".yml\", \".yaml\"):\r\n with open(dlc_config_fp, \"rb\") as f:\r\n dlc_config = yaml.safe_load(f)\r\n # -- Check and insert new BodyPart --\r\n assert \"bodyparts\" in dlc_config, f\"Found no bodyparts section in {dlc_config}\"\r\n tracked_body_parts = cls.fetch(\"body_part\")\r\n new_body_parts = np.setdiff1d(dlc_config[\"bodyparts\"], tracked_body_parts)\r\n if verbose: # Added to silence duplicate prompt during `insert_new_model`\r\n print(f\"Existing body parts: {tracked_body_parts}\")\r\n print(f\"New body parts: {new_body_parts}\")\r\n return new_body_parts\r\n\r\n @classmethod\r\n def insert_from_config(\r\n cls, dlc_config: dict, descriptions: list = None, prompt=True\r\n ):\r\n \"\"\"Insert all body parts from a config file.\r\n\r\n Args:\r\n dlc_config (str or dict): path to a config.y*ml, or dict of such contents.\r\n descriptions (list): Optional. List of strings describing new body parts.\r\n prompt (bool): Optional, default True. Prompt for confirmation before insert.\r\n \"\"\"\r\n\r\n # handle dlc_config being a yaml file\r\n new_body_parts = cls.extract_new_body_parts(dlc_config, verbose=False)\r\n if new_body_parts is not None: # Required bc np.array is ambiguous as bool\r\n if descriptions:\r\n assert len(descriptions) == len(new_body_parts), (\r\n \"Descriptions list does not match \"\r\n + \" the number of new_body_parts\"\r\n )\r\n print(f\"New descriptions: {descriptions}\")\r\n if descriptions is None:\r\n descriptions = [\"\" for x in range(len(new_body_parts))]\r\n\r\n if (\r\n prompt\r\n and dj.utils.user_choice(\r\n f\"Insert {len(new_body_parts)} new body \" + \"part(s)?\"\r\n )\r\n != \"yes\"\r\n ):\r\n print(\"Canceled insert.\")\r\n return\r\n cls.insert(\r\n [\r\n {\"body_part\": b, \"body_part_description\": d}\r\n for b, d in zip(new_body_parts, descriptions)\r\n ]\r\n )\r\n\r\n\r\n@schema\r\nclass Model(dj.Manual):\r\n \"\"\"DeepLabCut Models applied to generate pose estimations.\r\n\r\n Attributes:\r\n model_name ( varchar(64) ): User-friendly model name.\r\n task ( varchar(32) ): Task in the config yaml.\r\n date ( varchar(16) ): Date in the config yaml.\r\n iteration (int): Iteration/version of this model.\r\n snapshotindex (int): Which snapshot for prediction (if -1, latest).\r\n shuffle (int): Which shuffle of the training dataset.\r\n trainingsetindex (int): Which training set fraction to generate model.\r\n scorer ( varchar(64) ): Scorer/network name - DLC's GetScorerName().\r\n config_template (longblob): Dictionary of the config for analyze_videos().\r\n project_path ( varchar(255) ): DLC's project_path in config relative to root.\r\n model_prefix ( varchar(32) ): Optional. Prefix for model files.\r\n model_description ( varchar(1000) ): Optional. User-entered description.\r\n TrainingParamSet (foreign key): Optional. Training parameters primary key.\r\n\r\n Note:\r\n Models are uniquely identified by the union of task, date, iteration, shuffle,\r\n snapshotindex, and trainingsetindex.\r\n \"\"\"\r\n\r\n definition = \"\"\"\r\n model_name : varchar(64) # User-friendly model name\r\n ---\r\n task : varchar(32) # Task in the config yaml\r\n date : varchar(16) # Date in the config yaml\r\n iteration : int # Iteration/version of this model\r\n snapshotindex : int # which snapshot for prediction (if -1, latest)\r\n shuffle : int # Shuffle (1) or not (0)\r\n trainingsetindex : int # Index of training fraction list in config.yaml\r\n unique index (task, date, iteration, shuffle, snapshotindex, trainingsetindex)\r\n scorer : varchar(64) # Scorer/network name - DLC's GetScorerName()\r\n config_template : longblob # Dictionary of the config for analyze_videos()\r\n project_path : varchar(255) # DLC's project_path in config relative to root\r\n model_prefix='' : varchar(32)\r\n model_description='' : varchar(300)\r\n -> [nullable] train.TrainingParamSet\r\n \"\"\"\r\n # project_path is the only item required downstream in the pose schema\r\n\r\n class BodyPart(dj.Part):\r\n \"\"\"Body parts associated with a given model\r\n\r\n Attributes:\r\n body_part ( varchar(32) ): Short name. Also called joint.\r\n body_part_description ( varchar(1000) ): Optional. Longer description.\"\"\"\r\n\r\n definition = \"\"\"\r\n -> master\r\n -> BodyPart\r\n \"\"\"\r\n\r\n @classmethod\r\n def insert_new_model(\r\n cls,\r\n model_name: str,\r\n dlc_config,\r\n *,\r\n shuffle: int,\r\n trainingsetindex,\r\n project_path=None,\r\n model_description=\"\",\r\n model_prefix=\"\",\r\n paramset_idx: int = None,\r\n prompt=True,\r\n params=None,\r\n ):\r\n \"\"\"Insert new model into the dlc.Model table.\r\n\r\n Args:\r\n model_name (str): User-friendly name for this model.\r\n dlc_config (str or dict): path to a config.y*ml, or dict of such contents.\r\n shuffle (int): Shuffled or not as 1 or 0.\r\n trainingsetindex (int): Index of training fraction list in config.yaml.\r\n model_description (str): Optional. Description of this model.\r\n model_prefix (str): Optional. Filename prefix used across DLC project\r\n paramset_idx (int): Optional. Index from the TrainingParamSet table\r\n prompt (bool): Optional. Prompt the user with all info before inserting.\r\n params (dict): Optional. If dlc_config is path, dict of override items\r\n \"\"\"\r\n from deeplabcut.utils.auxiliaryfunctions import GetScorerName # isort:skip\r\n\r\n # handle dlc_config being a yaml file\r\n if not isinstance(dlc_config, dict):\r\n dlc_config_fp = find_full_path(get_dlc_root_data_dir(), Path(dlc_config))\r\n assert dlc_config_fp.exists(), (\r\n \"dlc_config is neither dict nor filepath\" + f\"\\n Check: {dlc_config_fp}\"\r\n )\r\n if dlc_config_fp.suffix in (\".yml\", \".yaml\"):\r\n with open(dlc_config_fp, \"rb\") as f:\r\n dlc_config = yaml.safe_load(f)\r\n if isinstance(params, dict):\r\n dlc_config.update(params)\r\n\r\n # ---- Get and resolve project path ----\r\n project_path = find_full_path(\r\n get_dlc_root_data_dir(), dlc_config.get(\"project_path\", project_path)\r\n )\r\n dlc_config[\"project_path\"] = project_path.as_posix() # update if different\r\n root_dir = find_root_directory(get_dlc_root_data_dir(), project_path)\r\n\r\n # ---- Verify config ----\r\n needed_attributes = [\r\n \"Task\",\r\n \"date\",\r\n \"iteration\",\r\n \"snapshotindex\",\r\n \"TrainingFraction\",\r\n ]\r\n for attribute in needed_attributes:\r\n assert attribute in dlc_config, f\"Couldn't find {attribute} in config\"\r\n\r\n # ---- Get scorer name ----\r\n # \"or 'f'\" below covers case where config returns None. str_to_bool handles else\r\n scorer_legacy = str_to_bool(dlc_config.get(\"scorer_legacy\", \"f\"))\r\n\r\n dlc_scorer = GetScorerName(\r\n cfg=dlc_config,\r\n shuffle=shuffle,\r\n trainFraction=dlc_config[\"TrainingFraction\"][int(trainingsetindex)],\r\n modelprefix=model_prefix,\r\n )[scorer_legacy]\r\n if dlc_config[\"snapshotindex\"] == -1:\r\n dlc_scorer = \"\".join(dlc_scorer.split(\"_\")[:-1])\r\n\r\n # ---- Insert ----\r\n model_dict = {\r\n \"model_name\": model_name,\r\n \"model_description\": model_description,\r\n \"scorer\": dlc_scorer,\r\n \"task\": dlc_config[\"Task\"],\r\n \"date\": dlc_config[\"date\"],\r\n \"iteration\": dlc_config[\"iteration\"],\r\n \"snapshotindex\": dlc_config[\"snapshotindex\"],\r\n \"shuffle\": shuffle,\r\n \"trainingsetindex\": int(trainingsetindex),\r\n \"project_path\": project_path.relative_to(root_dir).as_posix(),\r\n \"paramset_idx\": paramset_idx,\r\n \"config_template\": dlc_config,\r\n }\r\n\r\n # -- prompt for confirmation --\r\n if prompt:\r\n print(\"--- DLC Model specification to be inserted ---\")\r\n for k, v in model_dict.items():\r\n if k != \"config_template\":\r\n print(\"\\t{}: {}\".format(k, v))\r\n else:\r\n print(\"\\t-- Template/Contents of config.yaml --\")\r\n for k, v in model_dict[\"config_template\"].items():\r\n print(\"\\t\\t{}: {}\".format(k, v))\r\n\r\n if (\r\n prompt\r\n and dj.utils.user_choice(\"Proceed with new DLC model insert?\") != \"yes\"\r\n ):\r\n print(\"Canceled insert.\")\r\n return\r\n # ---- Save DJ-managed config ----\r\n try:\r\n _ = dlc_reader.save_yaml(project_path, dlc_config)\r\n except PermissionError:\r\n pass\r\n # ____ Insert into table ----\r\n with cls.connection.transaction:\r\n cls.insert1(model_dict)\r\n # Returns array, so check size for unambiguous truth value\r\n if BodyPart.extract_new_body_parts(dlc_config, verbose=False).size > 0:\r\n BodyPart.insert_from_config(dlc_config, prompt=prompt)\r\n cls.BodyPart.insert((model_name, bp) for bp in dlc_config[\"bodyparts\"])\r\n\r\n\r\n@schema\r\nclass ModelEvaluation(dj.Computed):\r\n \"\"\"Performance characteristics model calculated by `deeplabcut.evaluate_network`\r\n\r\n Attributes:\r\n Model (foreign key): Model name.\r\n train_iterations (int): Training iterations.\r\n train_error (float): Optional. Train error (px).\r\n test_error (float): Optional. Test error (px).\r\n p_cutoff (float): Optional. p-cutoff used.\r\n train_error_p (float): Optional. Train error with p-cutoff.\r\n test_error_p (float): Optional. Test error with p-cutoff.\"\"\"\r\n\r\n definition = \"\"\"\r\n -> Model\r\n ---\r\n train_iterations : int # Training iterations\r\n train_error=null : float # Train error (px)\r\n test_error=null : float # Test error (px)\r\n p_cutoff=null : float # p-cutoff used\r\n train_error_p=null : float # Train error with p-cutoff\r\n test_error_p=null : float # Test error with p-cutoff\r\n \"\"\"\r\n\r\n def make(self, key):\r\n from deeplabcut import evaluate_network # isort:skip\r\n from deeplabcut.utils.auxiliaryfunctions import (\r\n get_evaluation_folder,\r\n ) # isort:skip\r\n\r\n \"\"\".populate() method will launch evaluation for each unique entry in Model.\"\"\"\r\n dlc_config, project_path, model_prefix, shuffle, trainingsetindex = (\r\n Model & key\r\n ).fetch1(\r\n \"config_template\",\r\n \"project_path\",\r\n \"model_prefix\",\r\n \"shuffle\",\r\n \"trainingsetindex\",\r\n )\r\n\r\n project_path = find_full_path(get_dlc_root_data_dir(), project_path)\r\n yml_path, _ = dlc_reader.read_yaml(project_path)\r\n\r\n evaluate_network(\r\n yml_path,\r\n Shuffles=[shuffle], # this needs to be a list\r\n trainingsetindex=trainingsetindex,\r\n comparisonbodyparts=\"all\",\r\n )\r\n\r\n eval_folder = get_evaluation_folder(\r\n trainFraction=dlc_config[\"TrainingFraction\"][trainingsetindex],\r\n shuffle=shuffle,\r\n cfg=dlc_config,\r\n modelprefix=model_prefix,\r\n )\r\n eval_path = project_path / eval_folder\r\n assert eval_path.exists(), f\"Couldn't find evaluation folder:\\n{eval_path}\"\r\n\r\n eval_csvs = list(eval_path.glob(\"*csv\"))\r\n max_modified_time = 0\r\n for eval_csv in eval_csvs:\r\n modified_time = os.path.getmtime(eval_csv)\r\n if modified_time > max_modified_time:\r\n eval_csv_latest = eval_csv\r\n with open(eval_csv_latest, newline=\"\") as f:\r\n results = list(csv.DictReader(f, delimiter=\",\"))[0]\r\n # in testing, test_error_p returned empty string\r\n self.insert1(\r\n dict(\r\n key,\r\n train_iterations=results[\"Training iterations:\"],\r\n train_error=results[\" Train error(px)\"],\r\n test_error=results[\" Test error(px)\"],\r\n p_cutoff=results[\"p-cutoff used\"],\r\n train_error_p=results[\"Train error with p-cutoff\"],\r\n test_error_p=results[\"Test error with p-cutoff\"],\r\n )\r\n )\r\n\r\n\r\n@schema\r\nclass PoseEstimationTask(dj.Manual):\r\n \"\"\"Staging table for pairing of video recording and model before inference.\r\n\r\n Attributes:\r\n VideoRecording (foreign key): Video recording key.\r\n Model (foreign key): Model name.\r\n task_mode (load or trigger): Optional. Default load. Or trigger computation.\r\n pose_estimation_output_dir ( varchar(255) ): Optional. Output dir relative to\r\n get_dlc_root_data_dir.\r\n pose_estimation_params (longblob): Optional. Params for DLC's analyze_videos\r\n params, if not default.\"\"\"\r\n\r\n definition = \"\"\"\r\n -> VideoRecording # Session -> Recording + File part table\r\n -> Model # Must specify a DLC project_path\r\n ---\r\n task_mode='load' : enum('load', 'trigger') # load results or trigger computation\r\n pose_estimation_output_dir='': varchar(255) # output dir relative to the root dir\r\n pose_estimation_params=null : longblob # analyze_videos params, if not default\r\n \"\"\"\r\n\r\n @classmethod\r\n def infer_output_dir(cls, key: dict, relative: bool = False, mkdir: bool = False):\r\n \"\"\"Return the expected pose_estimation_output_dir.\r\n\r\n Spaces in model name are replaced with hyphens.\r\n Based on convention: / video_dir / Device_{}_Recording_{}_Model_{}\r\n\r\n Args:\r\n key: DataJoint key specifying a pairing of VideoRecording and Model.\r\n relative (bool): Report directory relative to get_dlc_processed_data_dir().\r\n mkdir (bool): Default False. Make directory if it doesn't exist.\r\n \"\"\"\r\n video_filepath = find_full_path(\r\n get_dlc_root_data_dir(),\r\n (VideoRecording.File & key).fetch(\"file_path\", limit=1)[0],\r\n )\r\n root_dir = find_root_directory(get_dlc_root_data_dir(), video_filepath.parent)\r\n recording_key = VideoRecording & key\r\n device = \"-\".join(\r\n str(v)\r\n for v in (_linking_module.Device & recording_key).fetch1(\"KEY\").values()\r\n )\r\n if get_dlc_processed_data_dir():\r\n processed_dir = Path(get_dlc_processed_data_dir())\r\n else: # if processed not provided, default to where video is\r\n processed_dir = root_dir\r\n\r\n output_dir = (\r\n processed_dir\r\n / video_filepath.parent.relative_to(root_dir)\r\n / (\r\n f'device_{device}_recording_{key[\"recording_id\"]}_model_'\r\n + key[\"model_name\"].replace(\" \", \"-\")\r\n )\r\n )\r\n if mkdir:\r\n output_dir.mkdir(parents=True, exist_ok=True)\r\n return output_dir.relative_to(processed_dir) if relative else output_dir\r\n\r\n @classmethod\r\n def generate(\r\n cls,\r\n video_recording_key: dict,\r\n model_name: str,\r\n *,\r\n task_mode: str = None,\r\n analyze_videos_params: dict = None,\r\n ):\r\n \"\"\"Insert PoseEstimationTask in inferred output dir.\r\n\r\n Based on the convention / video_dir / device_{}_recording_{}_model_{}\r\n\r\n Args:\r\n video_recording_key (dict): DataJoint key specifying a VideoRecording.\r\n\r\n model_name (str): Name of DLC model (from Model table) to be used for inference.\r\n task_mode (str): Default 'trigger' computation. Or 'load' existing results.\r\n analyze_videos_params (dict): Optional. Parameters passed to DLC's analyze_videos:\r\n videotype, gputouse, save_as_csv, batchsize, cropping, TFGPUinference,\r\n dynamic, robust_nframes, allow_growth, use_shelve\r\n \"\"\"\r\n processed_dir = get_dlc_processed_data_dir()\r\n output_dir = cls.infer_output_dir(\r\n {**video_recording_key, \"model_name\": model_name},\r\n relative=False,\r\n mkdir=True,\r\n )\r\n\r\n if task_mode is None:\r\n try:\r\n _ = dlc_reader.PoseEstimation(output_dir)\r\n except FileNotFoundError:\r\n task_mode = \"trigger\"\r\n else:\r\n task_mode = \"load\"\r\n\r\n cls.insert1(\r\n {\r\n **video_recording_key,\r\n \"model_name\": model_name,\r\n \"task_mode\": task_mode,\r\n \"pose_estimation_params\": analyze_videos_params,\r\n \"pose_estimation_output_dir\": output_dir.relative_to(\r\n processed_dir\r\n ).as_posix(),\r\n }\r\n )\r\n\r\n insert_estimation_task = generate\r\n\r\n\r\n@schema\r\nclass PoseEstimation(dj.Computed):\r\n \"\"\"Results of pose estimation.\r\n\r\n Attributes:\r\n PoseEstimationTask (foreign key): Pose Estimation Task key.\r\n post_estimation_time (datetime): time of generation of this set of DLC results.\r\n \"\"\"\r\n\r\n definition = \"\"\"\r\n -> PoseEstimationTask\r\n ---\r\n pose_estimation_time: datetime # time of generation of this set of DLC results\r\n \"\"\"\r\n\r\n class BodyPartPosition(dj.Part):\r\n \"\"\"Position of individual body parts by frame index\r\n\r\n Attributes:\r\n PoseEstimation (foreign key): Pose Estimation key.\r\n Model.BodyPart (foreign key): Body Part key.\r\n frame_index (longblob): Frame index in model.\r\n x_pos (longblob): X position.\r\n y_pos (longblob): Y position.\r\n z_pos (longblob): Optional. Z position.\r\n likelihood (longblob): Model confidence.\"\"\"\r\n\r\n definition = \"\"\" # uses DeepLabCut h5 output for body part position\r\n -> master\r\n -> Model.BodyPart\r\n ---\r\n frame_index : longblob # frame index in model\r\n x_pos : longblob\r\n y_pos : longblob\r\n z_pos=null : longblob\r\n likelihood : longblob\r\n \"\"\"\r\n\r\n def make(self, key):\r\n \"\"\".populate() method will launch training for each PoseEstimationTask\"\"\"\r\n # ID model and directories\r\n dlc_model = (Model & key).fetch1()\r\n task_mode, output_dir = (PoseEstimationTask & key).fetch1(\r\n \"task_mode\", \"pose_estimation_output_dir\"\r\n )\r\n\r\n output_dir = find_full_path(get_dlc_root_data_dir(), output_dir)\r\n\r\n # Triger PoseEstimation\r\n if task_mode == \"trigger\":\r\n # Triggering dlc for pose estimation required:\r\n # - project_path: full path to the directory containing the trained model\r\n # - video_filepaths: full paths to the video files for inference\r\n # - analyze_video_params: optional parameters to analyze video\r\n project_path = find_full_path(\r\n get_dlc_root_data_dir(), dlc_model[\"project_path\"]\r\n )\r\n video_filepaths = [\r\n find_full_path(get_dlc_root_data_dir(), fp).as_posix()\r\n for fp in (VideoRecording.File & key).fetch(\"file_path\")\r\n ]\r\n analyze_video_params = (PoseEstimationTask & key).fetch1(\r\n \"pose_estimation_params\"\r\n ) or {}\r\n\r\n dlc_reader.do_pose_estimation(\r\n key,\r\n video_filepaths,\r\n dlc_model,\r\n project_path,\r\n output_dir,\r\n **analyze_video_params,\r\n )\r\n\r\n dlc_result = dlc_reader.PoseEstimation(output_dir)\r\n creation_time = datetime.fromtimestamp(dlc_result.creation_time).strftime(\r\n \"%Y-%m-%d %H:%M:%S\"\r\n )\r\n\r\n body_parts = [\r\n {\r\n **key,\r\n \"body_part\": k,\r\n \"frame_index\": np.arange(dlc_result.nframes),\r\n \"x_pos\": v[\"x\"],\r\n \"y_pos\": v[\"y\"],\r\n \"z_pos\": v.get(\"z\"),\r\n \"likelihood\": v[\"likelihood\"],\r\n }\r\n for k, v in dlc_result.data.items()\r\n ]\r\n\r\n self.insert1({**key, \"pose_estimation_time\": creation_time})\r\n self.BodyPartPosition.insert(body_parts)\r\n\r\n @classmethod\r\n def get_trajectory(cls, key: dict, body_parts: list = \"all\") -> pd.DataFrame:\r\n \"\"\"Returns a pandas dataframe of coordinates of the specified body_part(s)\r\n\r\n Args:\r\n key (dict): A DataJoint query specifying one PoseEstimation entry.\r\n body_parts (list, optional): Body parts as a list. If \"all\", all joints\r\n\r\n Returns:\r\n df: multi index pandas dataframe with DLC scorer names, body_parts\r\n and x/y coordinates of each joint name for a camera_id, similar to\r\n output of DLC dataframe. If 2D, z is set of zeros\r\n \"\"\"\r\n model_name = key[\"model_name\"]\r\n\r\n if body_parts == \"all\":\r\n body_parts = (cls.BodyPartPosition & key).fetch(\"body_part\")\r\n elif not isinstance(body_parts, list):\r\n body_parts = list(body_parts)\r\n\r\n df = None\r\n for body_part in body_parts:\r\n x_pos, y_pos, z_pos, likelihood = (\r\n cls.BodyPartPosition & {\"body_part\": body_part}\r\n ).fetch1(\"x_pos\", \"y_pos\", \"z_pos\", \"likelihood\")\r\n if not z_pos:\r\n z_pos = np.zeros_like(x_pos)\r\n\r\n a = np.vstack((x_pos, y_pos, z_pos, likelihood))\r\n a = a.T\r\n pdindex = pd.MultiIndex.from_product(\r\n [[model_name], [body_part], [\"x\", \"y\", \"z\", \"likelihood\"]],\r\n names=[\"scorer\", \"bodyparts\", \"coords\"],\r\n )\r\n frame = pd.DataFrame(a, columns=pdindex, index=range(0, a.shape[0]))\r\n df = pd.concat([df, frame], axis=1)\r\n return df\r\n\r\n\r\ndef str_to_bool(value) -> bool:\r\n \"\"\"Return whether the provided string represents true. Otherwise false.\r\n\r\n Args:\r\n value (any): Any input\r\n\r\n Returns:\r\n bool (bool): True if value in (\"y\", \"yes\", \"t\", \"true\", \"on\", \"1\")\r\n \"\"\"\r\n # Due to distutils equivalent depreciation in 3.10\r\n # Adopted from github.com/PostHog/posthog/blob/master/posthog/utils.py\r\n if not value:\r\n return False\r\n return str(value).lower() in (\"y\", \"yes\", \"t\", \"true\", \"on\", \"1\")\r\n","repo_name":"datajoint/element-deeplabcut","sub_path":"element_deeplabcut/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":31632,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"9"} +{"seq_id":"43089616705","text":"import os\nimport subprocess\nfrom pathlib import Path\nfrom typing import Dict, List, Mapping, Optional, Tuple\n\nfrom docker import DockerClient\nfrom docker.models.containers import Container\nfrom docker.models.images import Image\n\n\ndef run_privileged_container(\n docker_client: DockerClient,\n image: Image,\n command: List[str],\n volumes: Dict[str, Dict[str, str]] = None,\n auto_remove=True,\n **extra_kwargs,\n) -> Tuple[Optional[Container], str]:\n if volumes is None:\n volumes = {}\n container_or_logs = docker_client.containers.run(\n image,\n command,\n privileged=True,\n network_mode=\"host\",\n pid_mode=\"host\",\n userns_mode=\"host\",\n volumes=volumes,\n auto_remove=auto_remove,\n stderr=True,\n **extra_kwargs,\n )\n if isinstance(container_or_logs, Container):\n container, logs = container_or_logs, container_or_logs.logs().decode()\n else:\n assert isinstance(container_or_logs, bytes), container_or_logs\n container, logs = None, container_or_logs.decode()\n\n # print, so failing tests display it\n print(\n \"Container logs:\",\n logs if len(logs) > 0 else \"(empty, possibly because container was detached and is running now)\",\n )\n return container, logs\n\n\ndef _no_errors(logs: str):\n # example line: [2021-06-12 10:13:57,528] ERROR: gprofiler: ruby profiling failed\n assert \"] ERROR: \" not in logs, \"found ERRORs in gProfiler logs!\"\n\n\ndef run_gprofiler_in_container(\n docker_client: DockerClient, image: Image, command: List[str], **kwargs\n) -> Tuple[Optional[Container], str]:\n \"\"\"\n Wrapper around run_privileged_container() that also verifies there are not ERRORs in gProfiler's output log.\n \"\"\"\n assert \"-v\" in command, \"plesae run with -v!\" # otherwise there are no loglevel prints\n container, logs = run_privileged_container(docker_client, image, command, **kwargs)\n if container is not None:\n _no_errors(container.logs().decode())\n else:\n _no_errors(logs)\n return container, logs\n\n\ndef copy_file_from_image(image: Image, container_path: str, host_path: str) -> None:\n os.makedirs(os.path.dirname(host_path), exist_ok=True)\n # I tried writing it with the docker-py API, but retrieving large files with container.get_archive() just hangs...\n subprocess.run(\n f\"c=$(docker container create {image.id}) && \"\n f\"{{ docker cp $c:{container_path} {host_path}; ret=$?; docker rm $c > /dev/null; exit $ret; }}\",\n shell=True,\n check=True,\n )\n\n\ndef chmod_path_parts(path: Path, add_mode: int) -> None:\n \"\"\"\n Adds 'add_mode' to all parts in 'path'.\n \"\"\"\n for i in range(1, len(path.parts)):\n subpath = os.path.join(*path.parts[:i])\n os.chmod(subpath, os.stat(subpath).st_mode | add_mode)\n\n\ndef assert_function_in_collapsed(\n function_name: str, runtime: str, collapsed: Mapping[str, int], check_comm: bool = False\n) -> None:\n print(f\"collapsed: {collapsed}\")\n assert any(\n (function_name in record) for record in collapsed.keys()\n ), f\"function {function_name!r} missing in collapsed data!\"\n","repo_name":"ekmixon/gprofiler","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"9"} +{"seq_id":"6063418257","text":"from .fake_upnp_service import UpnpServiceMock\n\n\nclass FakeRenderingControlService(UpnpServiceMock):\n\n def __init__(self, device):\n super().__init__(service_type=\"urn:schemas-upnp-org:service:RenderingControl:1\", device=device)\n self.add_async_action('GetVolume', self._get_volume)\n self.add_async_action('SetVolume', self._set_volume)\n self._volume = 42\n\n @property\n def volume(self):\n return self._volume\n\n async def _set_volume(self, DesiredVolume, InstanceID=0, Channel='Master'):\n self._volume = DesiredVolume\n await self.trigger_notification(instance_xml_namespace='{urn:schemas-upnp-org:metadata-1-0/RCS/}',\n variables={'Volume': self._volume})\n\n async def _get_volume(self, InstanceID, Channel):\n return {'CurrentVolume': self._volume}\n","repo_name":"mikedevnull/upnp-av-control","sub_path":"tests/bdd/fake_upnp/rendering_control.py","file_name":"rendering_control.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"28511869131","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.5.2\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# ## Boston Housing Price Prediction\n\n# +\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom keras.datasets import boston_housing\n# -\n\n(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()\n\n# 404 samples, 13 features\ntrain_data.shape\n\ntest_data.shape\n\n# Targets are the median values of owner-ocupied homes, in thousands of dollars\ntrain_targets.shape\n\n# ### Preparing the data\n\n# Feature-wise normalization: for each feature in the input data, subtract the mean of the feature and divide by the standard deviation, so that the feature is centered around 0 and has a unit standard deviation. \n\n# +\nmean = train_data.mean(axis=0)\ntrain_data -= mean\nstd = train_data.std(axis=0)\ntrain_data /= std\n\n# OBS: the quantities used for normalizing the test data are computed using the training\n# data. You should never use in your workflow any quantity computed on the test data, even\n# for something as simple as data normalization\ntest_data -= mean\ntest_data /= std\n# -\n\n# ### Network architecture\n\n# If we don’t have much training data, we should use a small network with only one or two hidden layers, to avoid severe overfitting.\n\n# +\nfrom keras import models\nfrom keras import layers\n\ndef build_model():\n model = models.Sequential()\n model.add(layers.Dense(64, activation=\"relu\", input_shape=(train_data.shape[1],)))\n model.add(layers.Dense(64, activation=\"relu\"))\n # No activation in the output layer, linear layer, so we don't constrain the output values\n model.add(layers.Dense(1))\n model.compile(optimizer=\"rmsprop\",\n loss=\"mse\",\n metrics=['mae'])\n return model\n\n\n# -\n\n# ### Model validation using k-fold\n\n# To evaluate the network while we keep adjusting its parameters (such as the number of epochs used for training), we could split the data into a training set and a valida- tion set. But because we have so few data points, the validation set would end up being very small (for instance, about 100 examples). As a consequence, the validation scores might change a lot depending on which data points we chose to use for validation and which we chose for training: the validation scores might have a high variance with regard to the validation split. This would prevent us from reliably evaluating the model.\n#\n\nk = 4\nnum_val_samples = len(train_data) // k\nnum_epochs = 100\nall_scores = []\n\nfor i in range(k):\n print(\"Processing fold #\", i)\n val_data = train_data[i * num_val_samples : (i + 1) * num_val_samples]\n val_targets = train_targets[i * num_val_samples : (i + 1) * num_val_samples]\n \n partial_train_data = np.concatenate(\n [train_data[: i * num_val_samples],\n train_data[(i+1) * num_val_samples :]],\n axis=0\n )\n partial_train_targets = np.concatenate(\n [train_targets[: i * num_val_samples],\n train_targets[(i+1) * num_val_samples :]]\n )\n \n model = build_model()\n model.fit(partial_train_data, partial_train_targets,\n epochs = num_epochs, batch_size=1, verbose=0)\n\n val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)\n all_scores.append(val_mae)\n\nall_scores\n\nnp.mean(all_scores)\n\n# We will try with longer epochs\n\n# **QUESTION: AM I USING THE RIGHT METRIC BELOW? IT SEEMS THAT THE VALIDATION LOSS IS \n# CONSTANTLY DECREASING**\n\n# +\nnum_epochs = 500\nall_mae_histories = []\n\nfor i in range(k):\n print(\"Processing fold #\", i)\n val_data = train_data[i * num_val_samples : (i + 1) * num_val_samples]\n val_targets = train_targets[i * num_val_samples : (i + 1) * num_val_samples]\n \n partial_train_data = np.concatenate(\n [train_data[: i * num_val_samples],\n train_data[(i+1) * num_val_samples :]],\n axis=0\n )\n partial_train_targets = np.concatenate(\n [train_targets[: i * num_val_samples],\n train_targets[(i+1) * num_val_samples :]]\n )\n \n model = build_model()\n history = model.fit(partial_train_data, partial_train_targets,\n epochs = num_epochs, batch_size=1, verbose=0)\n mae_history = history.history['mae']\n all_mae_histories.append(mae_history)\n# -\n\naverage_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]\n\nplt.plot(range(1, len(average_mae_history) + 1), average_mae_history)\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Validation MAE\")\n\n\n# +\n# For better plotting we apply an exponential moving average to smooth the curve\n\ndef smooth_curve(points, factor=0.9):\n smoothed_points = []\n for point in points:\n if smoothed_points:\n previous = smoothed_points[-1]\n smoothed_points.append(previous * factor + point * (1 - factor))\n else:\n smoothed_points.append(point)\n return smoothed_points\n\n\n# -\n\nsmoothed_mae_history = smooth_curve(average_mae_history[10:])\n\nplt.plot(range(1, len(smoothed_mae_history) + 1), smoothed_mae_history)\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Validation MAE\")\n\n# It seems that the model starts overfitting after 80 epochs\n\n# ### Final model\n\n# +\n# OBS: Before training the final model we should optimize other parameters such us epochs,\n# or number of hidden layers\n\nmodel = build_model()\nmodel.fit(train_data, train_targets,\n epochs=80, batch_size=16, verbose=0)\n\ntest_mse_score, test_mae_score = model.evaluate(test_data, test_targets)\n# -\n\ntest_mae_score\n","repo_name":"C-Laborde/Deep-Learning_Learning","sub_path":"chollet/Ch3 - Regression.py","file_name":"Ch3 - Regression.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"36603859932","text":"import socket\nimport os\nimport json\nimport hashlib\n\nSEPARATOR = \"\"\nBUFFER_SIZE = 1024\n\n# the ip address or hostname of the server, the receiver\nhost = \"34.74.0.126\"\n# the port, let's use 5001\nport = 5001\n# the name of file we want to send, make sure it exists\nfilename = \"tests/test.mp4\"\n# get the file size\nfilesize = os.path.getsize(filename)\n\n# create the client socket\ns = socket.socket()\n\nprint(f\"[+] Connecting to {host}:{port}\")\ns.connect((host, port))\nprint(\"[+] Connected.\")\n\n# json object\ninfo = {\n \"filename\" : filename,\n \"filesize\" : filesize,\n \"filetype\" : \"temp\",\n \"filehash\" : \"fxsrysyws55ws57e\",\n \"fileaddr\" : \"104.196.106.117\",\n }\n\n# send the filename and filesize\ns.sendall(pickle.dumps(info))\n# s.sendall(f\"{filename}{SEPARATOR}{filesize}{SEPARATOR}{'temp'}{SEPARATOR}{'fxsrysyws55ws57e'}{SEPARATOR}{'104.196.106.117'}\".encode('utf-32'))\n\n# start sending the file\n# progress = tqdm.tqdm(range(filesize), f\"Sending {filename}\", unit=\"B\", unit_scale=True, unit_divisor=1024)\nwith open(filename, \"rb\") as f:\n while True:\n # read the bytes from the file\n bytes_read = f.read(BUFFER_SIZE)\n if not bytes_read:\n # file transmitting is done\n break\n # we use sendall to assure transimission in \n # busy networks\n s.sendall(bytes_read)\n # update the progress bar\n # progress.update(len(bytes_read))\n# close the socket\ns.close()\n\n# # Importing libraries\n# import socket\n# import sys\n\n# # Lets catch the 1st argument as server ip\n# if (len(sys.argv) > 1):\n# ServerIp = sys.argv[1]\n# else:\n# print(\"\\n\\n Run like \\n python3 client.py < serverip address > \\n\\n\")\n# exit(1)\n\n\n# # Now we can create socket object\n# s = socket.socket()\n\n# # Lets choose one port and connect to that port\n# PORT = 9898\n\n# # Lets connect to that port where server may be running\n# s.connect((ServerIp, PORT))\n\n# # We can send file sample.txt\n# file = open(\"/home/rishav4101/12345.mkv\", \"rb\")\n# SendData = file.read(1024)\n\n\n# while SendData:\n# # Now we can receive data from server\n# print(\"\\n\\n################## Below message is received from server ################## \\n\\n \", s.recv(1024).decode(\"utf-8\"))\n# #Now send the content of sample.txt to server\n# s.send(SendData)\n# SendData = file.read(1024) \n\n# # Close the connection from client side\n# s.close()\n\ndef file_split(filename, n):\n file_list = []\n filesize = os.path.getsize(filename)\n SPLIT_SIZE = filesize / n\n with open(filename, \"rb\") as f:\n i = 0\n while True:\n bytes_read = f.read(SPLIT_SIZE)\n if not bytes_read:\n break\n hash = hashlib.sha256(json.dumps(bytes_read).encode(\"utf-8\")).hexdigest()\n file_list.append({\"index\": i, \"key\" : hash, \"value\": bytes_read})\n i = i + 1\n \n for i in range(0,n):\n filename = \"output\" + i + \".mkv\"\n with open(filename, \"wb\") as f:\n f.write(file_list[i].value)\n\ndef file_join(file_list):\n filename = \"output.txt\"\n for file in file_list.items():\n with open(filename, \"wb\") as f:\n while True:\n bytes_read = file.value\n if not bytes_read: \n break\n f.write(bytes_read)\n \n","repo_name":"dotscoin/dotscoin-core","sub_path":"tests/sendfiletest.py","file_name":"sendfiletest.py","file_ext":"py","file_size_in_byte":3311,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"26602291926","text":"from tqdm import tqdm\nfrom transformers import GPT2LMHeadModel, GPT2TokenizerFast\nimport argparse\nimport os\nimport torch\nimport logging\nlogging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',\n datefmt='%d-%m-%Y:%H:%M:%S')\nlogging.getLogger().setLevel(logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\ndef get_files(path):\n paths = []\n if os.path.isfile(path):\n # Simple file\n if 'iternums' not in path:\n paths.append(path)\n elif os.path.isdir(path):\n # Directory\n for (dirpath, _, fnames) in os.walk(path):\n for fname in fnames:\n if 'iternums' not in fname and fname.endswith('.txt'):\n paths.append(os.path.join(dirpath, fname))\n else:\n # Assume glob\n paths = glob.glob(path)\n return paths\n@torch.no_grad()\ndef cal_ppl(filenames, model_file):\n ppl_dir = {}\n for filename in filenames:\n with open(filename, 'r') as f:\n sents = []\n for line in f.readlines():\n line_split = line.strip('\\n').strip().lower()\n if len(line_split) != 0:\n sents.append(line_split)\n model = GPT2LMHeadModel.from_pretrained(model_file).cuda()\n tokenizer = GPT2TokenizerFast.from_pretrained(model_file)\n model.eval()\n ppl = torch.FloatTensor(len(sents)).cuda()\n max_length = model.config.n_positions\n for index, sent in tqdm(enumerate(sents)):\n encodings = tokenizer(sent, return_tensors='pt')\n input_ids = encodings.input_ids[:, :max_length].cuda()\n target_ids = input_ids.clone()\n outputs = model(input_ids, labels=target_ids)\n ppl[index] = torch.exp(outputs[0]).tolist()\n ppl_dir[filename] = torch.mean(ppl)\n for i in ppl_dir.keys():\n logger.info('{:<65}{:.3f}'.format(os.path.basename(i), ppl_dir[i]))\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument('--top-p',type=float, default=0.9)\n parser.add_argument('--top-k',type=int, default=0)\n parser.add_argument('--model_file', type=str, default=\"~/pretrained_model/gpt2-base\")\n parser.add_argument('--cuda_num', type=str, default='1')\n parser.add_argument('--folderpath', type=str, default=\"checkpoints/ptb/samples/\")\n return parser.parse_args()\n\nif __name__ == '__main__':\n args = get_parser()\n os.environ['CUDA_VISIBLE_DEVICES'] = args.cuda_num\n # folderpath = os.path.join(args.folderpath, \"topp-{p}-topk-{k}\".format(p=args.top_p, k=args.top_k))\n folderpath = args.folderpath\n # print(\"=\" * 20 + \"topp-{p}-topk-{k}-temp-1\".format(p=args.top_p, k=args.top_k) + \"=\" * 20)\n filenames = sorted(get_files(folderpath))\n logger.info(filenames)\n cal_ppl(filenames, args.model_file)","repo_name":"FadedCosine/Dependency-Guided-Neural-Text-Generation","sub_path":"DPLM-Transformer/eval_ppl_by_gpt2.py","file_name":"eval_ppl_by_gpt2.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"86"} +{"seq_id":"43159594323","text":"#!/usr/bin/env python3\n\n\"\"\"This migration reflects the 1.1 release of SpreadRED,\nand adds a Description column to the torrent database.\n\"\"\"\n\nimport os\nimport sys\nimport sqlite3\n\nif len(sys.argv) != 2:\n exit('You must specify the .db directory as an argument.')\ndatabase_path = os.path.abspath(sys.argv[1])\nif not os.path.exists(database_path):\n exit('{} does not exist, please verify that it is the correct'\n 'path to the database.'.format(database_path))\n\nconn = sqlite3.connect(database_path)\ncursor = conn.cursor()\ncursor.execute('ALTER TABLE Torrents ADD Column Description TEXT')\nconn.commit()\nconn.close()\n\nprint('Upgraded database to version 1.1')\n","repo_name":"ligh7s/spread-red","sub_path":"migrations/release-1.1.py","file_name":"release-1.1.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"86"} +{"seq_id":"20889339929","text":"\"\"\"\nGiven a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). \n\nIf the character ch does not exist in word, do nothing.\n - For example, if word = \"abcdefd\" and ch = \"d\", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be \"dcbaefd\".\n\nReturn the resulting string.\n\"\"\"\n\nclass ReversePrefixOfWord(object):\n def reversePrefix(self, word, ch):\n if ch not in word:\n return word\n index_of_ch = word.index(ch)\n to_reverse = word[:index_of_ch + 1]\n to_keep = word[index_of_ch + 1:]\n to_reverse = to_reverse[::-1]\n return to_reverse + to_keep","repo_name":"jasonwang7517/Interview-Prep","sub_path":"ReversePrefixOfWord.py","file_name":"ReversePrefixOfWord.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"19125517633","text":"import clr\nclr.AddReference(\"RevitAPI\")\nfrom Autodesk.Revit.DB import UnitUtils, DisplayUnitType, Transaction\nclr.AddReference('RevitAPIUI')\nfrom Autodesk.Revit.UI.Selection import ObjectType, Selection\nclr.AddReference(\"RevitServices\")\nfrom RevitServices.Persistence import DocumentManager\n\n\ndoc = DocumentManager.Instance.CurrentDBDocument\nuidoc = DocumentManager.Instance.CurrentUIDocument\nuiapp = DocumentManager.Instance.CurrentUIApplication\napp = uiapp.Application\n\nt = Transaction(doc, 'Получаение бокса')\nt.Start()\n\nel_p = uidoc.Selection.PickObject(ObjectType.Element, 'Выбрать элемент')\nel = doc.GetElement(el_p)\n\ne = el.get_BoundingBox(doc.ActiveView)\ne_min = e.Min.X\ne_max = e.Max.X\n\ndis = UnitUtils.ConvertFromInternalUnits(e_max - e_min, DisplayUnitType.DUT_MILLIMETERS)\nt.Commit()\n\nOUT = el, dis\n","repo_name":"more600D/Dynamo","sub_path":"Element_BoundingBox.py","file_name":"Element_BoundingBox.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"10586343908","text":"import copy\nimport logging\nimport threading\n\n# Pelix beans\nfrom pelix.constants import BundleActivator, BundleException\nfrom pelix.internals.events import ServiceEvent\n\n# iPOPO constants\nimport pelix.ipopo.constants as ipopo_constants\nimport pelix.ipopo.handlers.constants as constants\n\n# ------------------------------------------------------------------------------\n\n# Module version\n__version_info__ = (1, 0, 1)\n__version__ = \".\".join(str(x) for x in __version_info__)\n\n# Documentation strings format\n__docformat__ = \"restructuredtext en\"\n\n# ------------------------------------------------------------------------------\n\n\nclass _HandlerFactory(constants.HandlerFactory):\n # pylint: disable=R0903\n \"\"\"\n Factory service for service registration handlers\n \"\"\"\n\n @staticmethod\n def _prepare_requirements(configs, requires_filters):\n \"\"\"\n Overrides the filters specified in the decorator with the given ones\n\n :param configs: Field → (Requirement, key, allow_none) dictionary\n :param requires_filters: Content of the 'requires.filter' component\n property (field → string)\n :return: The new configuration dictionary\n \"\"\"\n if not requires_filters or not isinstance(requires_filters, dict):\n # No explicit filter configured\n return configs\n\n # We need to change a part of the requirements\n new_requirements = {}\n for field, config in configs.items():\n # Extract values from tuple\n requirement, key, allow_none = config\n\n try:\n explicit_filter = requires_filters[field]\n\n # Store an updated copy of the requirement\n requirement_copy = requirement.copy()\n requirement_copy.set_filter(explicit_filter)\n new_requirements[field] = (requirement_copy, key, allow_none)\n\n except (KeyError, TypeError, ValueError):\n # No information for this one, or invalid filter:\n # keep the factory requirement\n new_requirements[field] = config\n\n return new_requirements\n\n def get_handlers(self, component_context, instance):\n \"\"\"\n Sets up service providers for the given component\n\n :param component_context: The ComponentContext bean\n :param instance: The component instance\n :return: The list of handlers associated to the given component\n \"\"\"\n # Extract information from the context\n configs = component_context.get_handler(\n ipopo_constants.HANDLER_REQUIRES_MAP\n )\n requires_filters = component_context.properties.get(\n ipopo_constants.IPOPO_REQUIRES_FILTERS, None\n )\n\n # Prepare requirements\n configs = self._prepare_requirements(configs, requires_filters)\n\n # Set up the runtime dependency handlers\n handlers = []\n for field, config in configs.items():\n # Extract values from tuple\n requirement, key, allow_none = config\n\n # Construct the handler\n if requirement.aggregate:\n handlers.append(\n AggregateDependency(field, requirement, key, allow_none)\n )\n else:\n handlers.append(\n SimpleDependency(field, requirement, key, allow_none)\n )\n\n return handlers\n\n\n@BundleActivator\nclass _Activator(object):\n \"\"\"\n The bundle activator\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Sets up members\n \"\"\"\n self._registration = None\n\n def start(self, context):\n \"\"\"\n Bundle started\n \"\"\"\n # Set up properties\n properties = {\n constants.PROP_HANDLER_ID: ipopo_constants.HANDLER_REQUIRES_MAP\n }\n\n # Register the handler factory service\n self._registration = context.register_service(\n constants.SERVICE_IPOPO_HANDLER_FACTORY,\n _HandlerFactory(),\n properties,\n )\n\n def stop(self, _):\n \"\"\"\n Bundle stopped\n \"\"\"\n # Unregister the service\n self._registration.unregister()\n self._registration = None\n\n\n# ------------------------------------------------------------------------------\n\n\nclass _RuntimeDependency(constants.DependencyHandler):\n \"\"\"\n Manages a required dependency field when a component is running\n \"\"\"\n\n def __init__(self, field, requirement, key, allow_none):\n \"\"\"\n Sets up the dependency\n\n :param field: The injected field name\n :param requirement: The Requirement describing this dependency\n :param key: The property used as key in the dictionary\n :param allow_none: Allow None property as key\n \"\"\"\n # The internal state lock\n self._lock = threading.RLock()\n\n # The iPOPO StoredInstance object (given during manipulation)\n self._ipopo_instance = None\n\n # The bundle context\n self._context = None\n\n # The associated field\n self._field = field\n\n # The underlying requirement\n self.requirement = requirement\n\n # The property name\n self._key = key\n\n # Accept None values\n self._allow_none = allow_none\n\n # Reference -> Service\n self.services = {}\n\n # Future injected dictionary\n self._future_value = {}\n\n def manipulate(self, stored_instance, component_instance):\n \"\"\"\n Stores the given StoredInstance bean.\n\n :param stored_instance: The iPOPO component StoredInstance\n :param component_instance: The component instance\n \"\"\"\n # Store the stored instance...\n self._ipopo_instance = stored_instance\n\n # ... and the bundle context\n self._context = stored_instance.bundle_context\n\n # Set the default value for the field: an empty dictionary\n setattr(component_instance, self._field, {})\n\n def clear(self):\n \"\"\"\n Cleans up the manager. The manager can't be used after this method has\n been called\n \"\"\"\n self.services.clear()\n self._future_value.clear()\n\n self.services = None\n self._lock = None\n self._ipopo_instance = None\n self._context = None\n self.requirement = None\n self._key = None\n self._allow_none = None\n self._future_value = None\n self._field = None\n\n def get_bindings(self):\n \"\"\"\n Retrieves the list of the references to the bound services\n\n :return: A list of ServiceReferences objects\n \"\"\"\n with self._lock:\n return list(self.services.keys())\n\n def get_field(self):\n \"\"\"\n Returns the name of the field handled by this handler\n \"\"\"\n return self._field\n\n def get_kinds(self):\n \"\"\"\n Retrieves the kinds of this handler: 'dependency'\n\n :return: the kinds of this handler\n \"\"\"\n return (constants.KIND_DEPENDENCY,)\n\n def get_value(self):\n \"\"\"\n Retrieves the value to inject in the component\n\n :return: The value to inject\n \"\"\"\n # Return a copy of the future value\n with self._lock:\n # IronPython can't copy dictionary with a None key\n return copy.copy(self._future_value)\n\n def is_valid(self):\n \"\"\"\n Tests if the dependency is in a valid state\n \"\"\"\n return (\n self.requirement is not None and self.requirement.optional\n ) or bool(self._future_value)\n\n def on_service_arrival(self, svc_ref):\n \"\"\"\n Called when a service has been registered in the framework\n\n :param svc_ref: A service reference\n \"\"\"\n raise NotImplementedError\n\n def on_service_departure(self, svc_ref):\n \"\"\"\n Called when a service has been registered in the framework\n\n :param svc_ref: A service reference\n \"\"\"\n raise NotImplementedError\n\n def on_service_modify(self, svc_ref, old_properties):\n \"\"\"\n Called when a service has been registered in the framework\n\n :param svc_ref: A service reference\n :param old_properties: Previous properties values\n \"\"\"\n raise NotImplementedError\n\n def service_changed(self, event):\n \"\"\"\n Called by the framework when a service event occurs\n \"\"\"\n if (\n self._ipopo_instance is None\n or not self._ipopo_instance.check_event(event)\n ):\n # stop() and clean() may have been called after we have been put\n # inside a listener list copy...\n # or we've been told to ignore this event\n return\n\n # Call sub-methods\n kind = event.get_kind()\n svc_ref = event.get_service_reference()\n\n if kind == ServiceEvent.REGISTERED:\n # Service coming\n self.on_service_arrival(svc_ref)\n\n elif kind in (\n ServiceEvent.UNREGISTERING,\n ServiceEvent.MODIFIED_ENDMATCH,\n ):\n # Service gone or not matching anymore\n self.on_service_departure(svc_ref)\n\n elif kind == ServiceEvent.MODIFIED:\n # Modified properties (can be a new injection)\n self.on_service_modify(svc_ref, event.get_previous_properties())\n\n def start(self):\n \"\"\"\n Starts the dependency manager\n \"\"\"\n self._context.add_service_listener(\n self, self.requirement.filter, self.requirement.specification\n )\n\n def stop(self):\n \"\"\"\n Stops the dependency manager (must be called before clear())\n\n :return: The removed bindings (list) or None\n \"\"\"\n self._context.remove_service_listener(self)\n if self.services:\n return [\n (service, reference)\n for reference, service in self.services.items()\n ]\n\n return None\n\n def try_binding(self):\n \"\"\"\n Searches for the required service if needed\n\n :raise BundleException: Invalid ServiceReference found\n \"\"\"\n with self._lock:\n if self.services:\n # We already are alive (not our first call)\n # => we are updated through service events\n return\n\n # Get all matching services\n refs = self._context.get_all_service_references(\n self.requirement.specification, self.requirement.filter\n )\n if not refs:\n # No match found\n return\n\n results = []\n try:\n # Bind all new reference\n for reference in refs:\n added = self.on_service_arrival(reference)\n if added:\n results.append(reference)\n except BundleException as ex:\n # Get the logger for this instance\n logger = logging.getLogger(\n \"-\".join((self._ipopo_instance.name, \"RequiresMap-Runtime\"))\n )\n logger.debug(\"Error binding multiple references: %s\", ex)\n\n # Undo what has just been done, ignoring errors\n for reference in results:\n try:\n self.on_service_departure(reference)\n\n except BundleException as ex2:\n logger.debug(\"Error cleaning up: %s\", ex2)\n\n del results[:]\n raise\n\n\nclass SimpleDependency(_RuntimeDependency):\n \"\"\"\n Manages a simple dependency field: one service per dictionary key\n \"\"\"\n\n def on_service_arrival(self, svc_ref):\n \"\"\"\n Called when a service has been registered in the framework\n\n :param svc_ref: A service reference\n \"\"\"\n with self._lock:\n if svc_ref not in self.services:\n # Get the key property\n prop_value = svc_ref.get_property(self._key)\n if (\n prop_value not in self._future_value\n and prop_value is not None\n or self._allow_none\n ):\n # Matching new property value\n service = self._context.get_service(svc_ref)\n\n # Store the information\n self._future_value[prop_value] = service\n self.services[svc_ref] = service\n\n # Call back iPOPO\n self._ipopo_instance.bind(self, service, svc_ref)\n return True\n\n return None\n\n def on_service_departure(self, svc_ref):\n \"\"\"\n Called when a service has been unregistered from the framework\n\n :param svc_ref: A service reference\n \"\"\"\n with self._lock:\n if svc_ref in self.services:\n # Get the service instance\n service = self.services.pop(svc_ref)\n\n # Get the key property\n prop_value = svc_ref.get_property(self._key)\n\n # Remove the injected service\n del self._future_value[prop_value]\n\n self._ipopo_instance.unbind(self, service, svc_ref)\n return True\n\n return None\n\n def on_service_modify(self, svc_ref, old_properties):\n \"\"\"\n Called when a service has been modified in the framework\n\n :param svc_ref: A service reference\n :param old_properties: Previous properties values\n \"\"\"\n with self._lock:\n if svc_ref not in self.services:\n # A previously registered service now matches our filter\n return self.on_service_arrival(svc_ref)\n else:\n # Get the property values\n old_value = old_properties.get(self._key)\n prop_value = svc_ref.get_property(self._key)\n service = self.services[svc_ref]\n\n if old_value != prop_value:\n if (\n prop_value is not None\n or self._allow_none\n and prop_value not in self._future_value\n ):\n # New property accepted and not yet in use\n del self._future_value[old_value]\n self._future_value[prop_value] = service\n\n # Notify the property modification, with a value change\n self._ipopo_instance.update(\n self, service, svc_ref, old_properties, True\n )\n else:\n # Consider the service as gone\n del self._future_value[old_value]\n del self.services[svc_ref]\n self._ipopo_instance.unbind(self, service, svc_ref)\n else:\n # Notify the property modification\n self._ipopo_instance.update(\n self, service, svc_ref, old_properties, False\n )\n\n return None\n\n\nclass AggregateDependency(_RuntimeDependency):\n \"\"\"\n Manages an aggregated dependency field: multiple services per dictionary\n key\n \"\"\"\n\n def __store_service(self, key, service):\n \"\"\"\n Stores the given service in the dictionary\n\n :param key: Dictionary key\n :param service: Service to add to the dictionary\n \"\"\"\n self._future_value.setdefault(key, []).append(service)\n\n def __remove_service(self, key, service):\n \"\"\"\n Removes the given service from the future dictionary\n\n :param key: Dictionary key\n :param service: Service to remove from the dictionary\n \"\"\"\n try:\n # Remove the injected service\n prop_services = self._future_value[key]\n prop_services.remove(service)\n\n # Clean up\n if not prop_services:\n del self._future_value[key]\n\n except KeyError:\n # Ignore: can occur when removing a service with a None property,\n # if allow_none is False\n pass\n\n def get_value(self):\n \"\"\"\n Retrieves the value to inject in the component\n\n :return: The value to inject\n \"\"\"\n with self._lock:\n # The value field must be a deep copy of our dictionary\n if self._future_value is not None:\n return {\n key: value[:] for key, value in self._future_value.items()\n }\n\n return None\n\n def on_service_arrival(self, svc_ref):\n \"\"\"\n Called when a service has been registered in the framework\n\n :param svc_ref: A service reference\n :return: True if the service is consumed\n \"\"\"\n with self._lock:\n if svc_ref not in self.services:\n # Get the key property\n prop_value = svc_ref.get_property(self._key)\n if prop_value is not None or self._allow_none:\n # Get the new service\n service = self._context.get_service(svc_ref)\n\n # Store the information\n self.__store_service(prop_value, service)\n self.services[svc_ref] = service\n\n self._ipopo_instance.bind(self, service, svc_ref)\n return True\n\n return None\n\n def on_service_departure(self, svc_ref):\n \"\"\"\n Called when a service has been unregistered from the framework\n\n :param svc_ref: A service reference\n :return: A tuple (service, reference) if the service has been lost,\n else None\n \"\"\"\n with self._lock:\n if svc_ref in self.services:\n # Get the service instance\n service = self.services.pop(svc_ref)\n\n # Get the key property\n prop_value = svc_ref.get_property(self._key)\n\n # Remove the injected service\n self.__remove_service(prop_value, service)\n\n self._ipopo_instance.unbind(self, service, svc_ref)\n return True\n\n return None\n\n def on_service_modify(self, svc_ref, old_properties):\n \"\"\"\n Called when a service has been modified in the framework\n\n :param svc_ref: A service reference\n :param old_properties: Previous properties values\n :return: A tuple (added, (service, reference)) if the dependency has\n been changed, else None\n \"\"\"\n with self._lock:\n if svc_ref not in self.services:\n # A previously registered service now matches our filter\n return self.on_service_arrival(svc_ref)\n else:\n # Get the property values\n service = self.services[svc_ref]\n old_value = old_properties.get(self._key)\n prop_value = svc_ref.get_property(self._key)\n\n if old_value != prop_value:\n # Key changed\n if prop_value is not None or self._allow_none:\n # New property accepted\n if old_value is not None or self._allow_none:\n self.__remove_service(old_value, service)\n\n self.__store_service(prop_value, service)\n\n # Notify the property modification, with a value change\n self._ipopo_instance.update(\n self, service, svc_ref, old_properties, True\n )\n else:\n # Consider the service as gone\n self.__remove_service(old_value, service)\n del self.services[svc_ref]\n self._ipopo_instance.unbind(self, service, svc_ref)\n else:\n # Simple property update\n self._ipopo_instance.update(\n self, service, svc_ref, old_properties, False\n )\n\n return None\n","repo_name":"tcalmant/ipopo","sub_path":"pelix/ipopo/handlers/requiresmap.py","file_name":"requiresmap.py","file_ext":"py","file_size_in_byte":20309,"program_lang":"python","lang":"en","doc_type":"code","stars":69,"dataset":"github-code","pt":"86"} +{"seq_id":"34929910483","text":"# Importing cmd line argument modules\nimport argparse\nimport sys\nimport os\nimport math\n\n# For phone number validation\nimport phonenumbers\n\n# Import version number\nimport phomber.__init__ as i\n\n# Imports needed for loading animation\nfrom itertools import cycle\nfrom shutil import get_terminal_size\nfrom threading import Thread\nfrom time import sleep\n\n\n\n# https://stackoverflow.com/questions/22029562/python-how-to-make-simple-animated-loading-while-process-is-running?answertab=trending#tab-top\nclass Loader:\n def __init__(self, desc=\"Loading...\", end=f\" [prog=\\033[1m{i.__project__}\\033[0m; dev=\\033[1m{i.__dev__}\\033[0m; ver=\\033[1m{i.__version__}\\033[0m]\\n\", timeout=0.1):\n self.desc = desc\n self.end = end\n self.timeout = timeout\n\n self._thread = Thread(target=self._animate, daemon=True)\n self.steps = [\"⢿\", \"⣻\", \"⣽\", \"⣾\", \"⣷\", \"⣯\", \"⣟\", \"⡿\"]\n self.done = False\n\n def start(self):\n self._thread.start()\n return self\n\n def _animate(self):\n for c in cycle(self.steps):\n if self.done:\n break\n print(f\"\\r{self.desc} {c}\", flush=True, end=\"\")\n sleep(self.timeout)\n\n def __enter__(self):\n self.start()\n\n def stop(self):\n self.done = True\n cols = get_terminal_size((80, 20)).columns\n print(\"\\r\" + \" \" * cols, end=\"\", flush=True)\n print(f\"\\r{self.end}\", flush=True)\n\n def __exit__(self, exc_type, exc_value, tb):\n # handle exceptions with those variables ^\n self.stop()\n\n\ndef loading(text, range_value, sleep_time):\n with Loader(text):\n for z in range(range_value):\n sleep(sleep_time)\n \n\ndef display_help():\n global parser\n parser.print_help(sys.stderr)\n\n\ndef parser():\n\n # specific_api_help = '''\n # \\t 1) Abstract Api [abstractapi.com]\n # \\t 2) Apilayer [apilayer.com]\n # \\t 3) Find and Trace [findandtrace.com]\n # \\t 4) Numlookup Api [numlookupapi.com]\n # \\t 5) Veriphone [veriphone.io]\n # '''\n \n global parser\n \n parser = argparse.ArgumentParser(description='PH0MBER — reverse phone number lookup')\n \n parser.add_argument('phone_number', metavar='Phone Number', \n type=str, nargs='?',\n help='Phone number to which perform reverse lookup')\n \n parser.add_argument('-c', '--config_editor', dest='config_editor', \n action='store_true',\n help='Opens config editor for entering apis keys')\n\n parser.add_argument('-l', '--logo', dest='display_logo', \n action='store_true',\n help='Display random `PH0MBER` logo')\n\n parser.add_argument('-a', '--all_apis', dest='all_apis', \n action='store_true',\n help='Run all API scans')\n\n # parser.add_argument('-s', '--specific_api', dest='s_api', \n # action='store_true',\n # help=specific_api_help)\n \n # -- API start --\n parser.add_argument('-abs', '--abstractapi', dest='abstractapi', \n action='store_true',\n help=\"Abstract Api [abstractapi.com]\")\n\n parser.add_argument('-lyr', '--apilayer', dest='apilayer', \n action='store_true',\n help=\"Apilayer [apilayer.com]\")\n\n parser.add_argument('-fnt', '--findandtrace', dest='findandtrace', \n action='store_true',\n help=\"Find and Trace [findandtrace.com]\")\n\n parser.add_argument('-nlu', '--numlookupapi', dest='numlookupapi', \n action='store_true',\n help=\"Numlookup Api [numlookupapi.com]\")\n\n parser.add_argument('-vp', '--veriphone', dest='veriphone', \n action='store_true',\n help=\"Veriphone [veriphone.io]\")\n # -- API end --\n \n return parser.parse_args() \n\n\n\ndef get_width():\n return os.get_terminal_size()[0]\n\n\ndef decorate(func, title, value, api_code=False):\n \n def wrapper():\n print('—'*get_width())\n half_width = math.floor((get_width() - len(title))/2)-1\n print('~'*half_width, title, '~'*half_width)\n print('—'*get_width())\n\n try:\n data = func(value)\n if data != 'status-code-non-200' and api_code:\n process_data(data, api_code)\n except:\n print('err-decorator')\n\n print('—'*get_width(), '\\n') \n \n return wrapper\n\n\n# Function to process json data retrived from apis \ndef process_data(data, api_code):\n if api_code == 'abs':\n print('[+] Phone Number\\n |—[ International format:', data['format']['international'], ']\\n |—[ Local format:', data['format']['local'],']')\n print('\\n[+] Validity\\n |—[ The provide numeber is', 'VALID' if data['valid'] else 'INVALID',']')\n print('\\n[+] Country\\n |—[ Code:', data['country']['code'], ']\\n |—[ Name:', data['country']['name'], ']\\n |—[ Prefix:', data['country']['prefix'],']')\n print('\\n[+] Other details\\n |—[ Line type:', data['type'], ']\\n |—[ Carrier:', data['carrier'], ']')\n \n elif api_code == 'lyr' or api_code == 'nlu':\n print('[+] Phone Number\\n |—[ International format:', data['international_format'], ']\\n |—[ Local format:', data['local_format'],']')\n print('\\n[+] Validity\\n |—[ The provide numeber is', 'VALID' if data['valid'] else 'INVALID',']')\n print('\\n[+] Country\\n |—[ Code:', data['country_code'], ']\\n |—[ Name:', data['country_name'], ']\\n |—[ Prefix:', data['country_prefix'], ']\\n |—[ Location:', data['location'],']')\n print('\\n[+] Other details\\n |—[ Line type:', data['line_type'], ']\\n |—[ Carrier:', data['carrier'],']')\n\n elif api_code == 'vp':\n print('[+] Phone Number\\n |—[ International format:', data['international_number'], ']\\n |—[ Local format:', data['local_number'],']')\n print('\\n[+] Validity\\n |—[ The provide numeber is', 'VALID' if data['phone_valid'] else 'INVALID',']')\n print('\\n[+] Country\\n |—[ Code:', data['country_code'], ']\\n |—[ Name:', data['country'], ']\\n |—[ Prefix:', data['country_prefix'], ']\\n |—[ Location:', data['phone_region'],']')\n print('\\n[+] Other details\\n |—[ Line type:', data['phone_type'], ']\\n |—[ Carrier:', data['carrier'],']')\n\n\n\n# Number valid or invalid\ndef is_valid(phone_number):\n phone_number_details = phonenumbers.parse(phone_number)\n valid = phonenumbers.is_valid_number(phone_number_details)\n possible = phonenumbers.is_possible_number(phone_number_details)\n\n if valid and possible:\n return True\n else:\n return False","repo_name":"s41r4j/phomber","sub_path":".archive/unreleasedv3/phomber/modules/basic/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":6707,"program_lang":"python","lang":"en","doc_type":"code","stars":256,"dataset":"github-code","pt":"86"} +{"seq_id":"38741468382","text":"\ndef kasiski_examination(ciphertext):\n \"\"\"Determines the key length of a Vigenere ciphertext using Kasiski examination\"\"\"\n # Find all repeated sequences of at least three letters in the ciphertext\n repeats = {}\n for i in range(len(ciphertext) - 2):\n seq = ciphertext[i:i+3]\n if seq in repeats:\n repeats[seq].append(i)\n else:\n repeats[seq] = [i]\n\n # Calculate the distance between each pair of repeated sequences\n distances = []\n for seq, indices in repeats.items():\n if len(indices) > 1:\n for i in range(1, len(indices)):\n distances.append(indices[i] - indices[i-1])\n\n # Find the most common factors among the distances\n factors = {}\n for distance in distances:\n for i in range(2, distance):\n if distance % i == 0:\n if i in factors:\n factors[i] += 1\n else:\n factors[i] = 1\n\n # Sort the factors by frequency\n factors = {k: v for k, v in sorted(factors.items(), key=lambda item: item[1], reverse=True)}\n\n return factors\n\n# Read the ciphertext from a file\nwith open(\"Ctext-2.txt\", \"r\") as file:\n ciphertext = file.read().replace('\\n', '')\n #convert to upper case\n ciphertext=ciphertext.upper()\n\n# Determine the key length using Kasiski examination\nfactors = kasiski_examination(ciphertext)\n\n# Print the most common factors\nfor factor, count in factors.items():\n print(factor, \":\", count)\n\n\n\n\n","repo_name":"itsAdee/CryptoAnalysisTasks","sub_path":"Vigenere Cipher/Python Code/kasiski.py","file_name":"kasiski.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"73719420443","text":"# you need requests library install first.\n# use this command: pip3 install requests\nimport requests\n\nendpoint = input(\"Enter your endpoint: \")\n\ndatas = {}\ndataLenMax = False\n\nwhile not dataLenMax:\n\tdatas[input(\"Enter datas 'key': \")] = input(\"enter datas 'value': \")\n\tif str(input(\"are you have another datas? (N/Y): \")).lower() == \"n\":\n\t\tdataLenMax = True\n\n\nresponse = requests.post(endpoint, data=datas)\nprint(response)","repo_name":"asghara04/api-requester","sub_path":"requester.py","file_name":"requester.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"23331429411","text":"import sys; input = sys.stdin.readline\r\nfrom collections import deque\r\nN = int(input())\r\ngraph = [list(map(int,input().rstrip())) for _ in range(N)]\r\n\r\ndef dfs(x, y):\r\n global num\r\n\r\n if x<0 or x >= N or y < 0 or y >= N:\r\n return False\r\n\r\n if graph[x][y] == 1:\r\n graph[x][y] = 0\r\n num+=1\r\n dfs(x + 1, y)\r\n dfs(x - 1, y)\r\n dfs(x, y + 1)\r\n dfs(x, y - 1)\r\n\r\n return True\r\n return False\r\n\r\nresult = 0\r\nans = []\r\nnum = 0\r\nfor i in range(N):\r\n for j in range(N):\r\n if dfs(i,j) == True:\r\n result += 1\r\n ans.append(num)\r\n num = 0\r\nprint(result)\r\nans.sort()\r\nprint(*ans,sep = '\\n')\r\n\r\n","repo_name":"juhyun-99/Baekjoon_algorithm","sub_path":"백준/Silver/2667. 단지번호붙이기/단지번호붙이기.py","file_name":"단지번호붙이기.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"14558449017","text":"\ndef currency_options(base_curr: str):\n \"\"\"Print out a table of options for converting base_curr to all other currencies\"\"\"\n # print(f'GBP USD EUR CAD CHF NZD AUD JPY')\n\n input_value = input(\"What is your home currency: \")\n print(f\"{input_value}\")\n for value in range(10, 91, 10):\n print(value)\n\n\n\ncurrency_options(\"KKK\")","repo_name":"mrudula-pb/Foothill-Spring2021","sub_path":"CS3A/Module_5/sample_assignmentfive.py","file_name":"sample_assignmentfive.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"20125108181","text":"# 用title_as_append模型来强调新闻\nfrom title_as_append import Sector_Title_Append_CRF\nimport roberta\nfrom roberta import Sector_Roberta_Title_Append_Crf\nfrom t_test import get_checkpoint_paths\nimport torch\nfrom functools import lru_cache\n\ndef read_raw_lines(path = '/home/taku/research/honda/data_five/news_exp.ds'):\n f = open(path)\n lines = f.readlines()\n f.close()\n return lines\n\ndef raw_lines_to_cases(raw_lines = None):\n if not raw_lines:\n raw_lines = read_raw_lines()\n ds = []\n counter = 0\n item = None\n for idx, line in enumerate(raw_lines):\n if len(line.strip()) == 0: \n if item is not None: # Maybe END of case, but maybe not\n ds.append(item)\n item = None\n elif item is None: # Title\n item = {'idx': counter, 'title': line.strip(), 'paras': []}\n counter += 1\n else:\n ss = line.strip().split('。')\n for i in range(len(ss) - 1):\n ss[i] = ss[i] + '。'\n if len(ss[-1]) < 1:\n del ss[-1]\n item['paras'].append(ss)\n # 收尾工作\n if item is not None: # Maybe END of case, but maybe not\n ds.append(item)\n return ds\n\n\nclass Model(Sector_Title_Append_CRF):\n def test(self):\n print('NOT SUPPORT NOW')\n def get_ids_and_heads(self, item):\n toker = self.toker\n title = item['title']\n text = item['text']\n ids_text = toker.encode(text ,add_special_tokens = False)\n ids_title = toker.encode(title ,add_special_tokens = False)\n ids = [toker.cls_token_id] + ids_text + [toker.sep_token_id] + ids_title + [toker.sep_token_id]\n ids = torch.LongTensor(ids)\n heads = [idx + 1 for idx in list(range(len(ids_text)))]\n return ids, heads\n\nclass Model_Roberta(Sector_Roberta_Title_Append_Crf):\n def test(self):\n print('NOT SUPPORT NOW')\n def get_ids_and_heads(self, item):\n toker = self.toker\n ids_text = roberta.roberta_encode_token(item['text'], toker)\n ids_title = roberta.roberta_encode_token(item['title'], toker)\n ids = [toker.cls_token_id] + ids_text + [toker.sep_token_id] + ids_title + [toker.sep_token_id]\n ids = torch.LongTensor(ids)\n heads = [idx + 1 for idx in list(range(len(ids_text)))]\n return ids, heads\n\n\ndef flatten(l):\n return [item for sublist in l for item in sublist]\n\nfirst_process_ds = raw_lines_to_cases\n\ndef second_process_ds(ds_org = None):\n if ds_org is None:\n ds_org = first_process_ds()\n ds = []\n for item_org in ds_org:\n title = item_org['title']\n paras = item_org['paras']\n items = [{'title': title, 'text': s} for s in flatten(paras)]\n ds += items\n return ds\n\ndef second_process_ds_by_path(path = '/home/taku/research/honda/data_five/news_exp2.ds'):\n lines = read_raw_lines(path)\n cases = raw_lines_to_cases(lines)\n return second_process_ds(cases)\n\n# 稍微打印一下,从printer.py复制过来的\ndef token_transfer_by_emphasizes(tokens, emphasizes, i, last, then):\n last_is_emphasize = emphasizes[last] if last > -1 else False\n next_is_emphasize = emphasizes[then] if then < len(tokens) else False\n current_is_emphasize = emphasizes[i]\n if current_is_emphasize:\n if not last_is_emphasize: # 唯一需要特殊对待的情况\n # False True 的情况,增加左标记\n tokens[i] = '【' + tokens[i]\n if not next_is_emphasize:\n # True False 的情况,增加右标记\n tokens[i] = tokens[i] + '】'\n\ndef print_sentence(tokens, emphasizes):\n tokens = tokens.copy()\n for i in range(len(tokens)):\n last = i - 1\n then = i + 1\n token_transfer_by_emphasizes(tokens, emphasizes, i, last, then)\n text = ''.join(tokens)\n return text\n\ndef get_model_for_test(key = 'SECTOR_TITLE_APPEND_CRF', instance_func = Model):\n checkpoints = get_checkpoint_paths(key)\n path = checkpoints[0][0]\n checkpoint = torch.load(path)\n model = instance_func()\n model.load_state_dict(checkpoint['model_state_dict'])\n return model\n\n\n\ndef emphasize(model = None, ds = None):\n if model is None:\n model = get_model_for_test()\n if ds is None:\n ds = second_process_ds()\n texts = []\n for item in ds:\n emphasizes = model.emphasize(item)\n ids, heads = model.get_ids_and_heads(item)\n ids = ids[heads]\n tokens = [model.toker.decode(idx) for idx in ids] \n texts.append(print_sentence(tokens, emphasizes))\n text = ''.join(texts).replace(' ', '').replace('##', '')\n return text\n\n\ndef ds_without_title(ds):\n res = []\n for item in ds:\n res.append({'title': '', 'text': item['text']})\n return res\n\ndef common_script(model, ds, need_title = True):\n if not need_title:\n ds = ds_without_title(ds)\n texts = []\n for item in ds:\n emphasizes = model.emphasize(item)\n ids, heads = model.get_ids_and_heads(item)\n ids = ids[heads]\n tokens = [model.toker.decode(idx) for idx in ids] \n texts.append(print_sentence(tokens, emphasizes))\n text = ''.join(texts).replace(' ', '').replace('##', '')\n return text\n\ndef run_bert():\n model = get_model_for_test()\n ds = second_process_ds_by_path(path = '/home/taku/research/honda/data_five/news_exp2.ds')\n text = common_script(model, ds, need_title = True)\n text2 = common_script(model, ds, need_title = False)\n\ndef run_roberta():\n model = get_model_for_test(key = 'ROBERTA_TITLE_APPEND_CRF', instance_func = Model_Roberta)\n ds = second_process_ds_by_path(path = '/home/taku/research/honda/data_five/news_exp2.ds')\n text = common_script(model, ds, need_title = True)\n text2 = common_script(model, ds, need_title = False)\n\n\n\n\n\n\n\n","repo_name":"zhuobinggang/honda","sub_path":"exp_model_for_news_emphasize.py","file_name":"exp_model_for_news_emphasize.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"35393082865","text":"from sparksubmitter import SparkSubmitter\nfrom execo_g5k import g5k_configuration\nfrom execo import Remote\nimport sys\n\n# We inherit because the behaviour of spark submit changes depending on the resource manager\nclass SparkSubmitterYarn(SparkSubmitter):\n\n def __init__(self,master_node,default_master,root_to_spark_submit):\n SparkSubmitter.__init__(self,master_node,default_master, root_to_spark_submit)\n\n def generate_scheduler_options(self,scheduler_options):\n # For the moment and since we don't know how different are the resource manager options\n # we only return an empty space\n return \"\"\n\n ## This will build the necessary string to submit the application. it uses the spark-submit option.\n # ./bin/spark-submit \\\n # --class \\\n # --master \\\n # --deploy-mode \\\n # --conf = \\\n # --packages\n # ... # other options\n # \\\n # [application-arguments]\n ## FUTURE: We might add an option in submit that indicates if we want to monitor this application or not\n def submit(self,class_in_jar, class_params, jar, master, submit_conf,scheduler_options):\n \"\"\"\n :param class_in_jar: the class we want to launch inside the jar\n :param class_params: the parameters expected by that class\n :param jar: the jar where the class is bundled\n :param master: the master that is going to take care of launching the app. (\"yarn\",\"spark:/192.168.0.1\", etc..)\n :param submit_conf: a list of tuples with the form [[\"spark.executor.memory\",\"2g\"],[\"spark.executor.cores\",\"1\"]]\n :param scheduler_options: options that are only applicable to that resource manager e.g. (Mesos tags, yarn labels...)\n \"\"\"\n if master is None:\n master = self.default_master\n if scheduler_options is None:\n scheduler_options = \"\"\n scheduler_str = self.generate_scheduler_options(scheduler_options)\n conf_str = self.generate_conf(submit_conf)\n cmd = \"{0} --class {1} --master {2} --deploy-mode client {3} {4} {5} {6}\".format(\n self.root_to_spark_submit,\n class_in_jar,\n master,\n conf_str,\n jar,\n \" \".join(class_params),\n scheduler_str\n )\n Remote(cmd, hosts=self.master_node, connection_params={'user':g5k_configuration.get('g5k_user')}\n , process_args={'stdout_handlers': [sys.stdout], 'stderr_handlers': [sys.stderr]} ).run()\n\n\n","repo_name":"Brandonage/execo-g5k-benchmarks","sub_path":"spark/sparksubmitteryarn.py","file_name":"sparksubmitteryarn.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"20782670612","text":"\"\"\"\nfetch_tiles.py\n\n0.0.1 20220614\n\nglen.rice@noaa.gov 20220614\n\nAn example script for downloading BlueTopo (and Modeling) datasets from AWS.\n\n\"\"\"\n\nimport concurrent.futures\nimport datetime\nimport hashlib\nimport os\nimport platform\nimport random\nimport sqlite3\nimport sys\n\nimport boto3\nimport numpy as np\nfrom botocore import UNSIGNED\nfrom botocore.client import Config\nfrom osgeo import gdal, ogr, osr\nfrom tqdm import tqdm\n\nfrom nbs.bluetopo.core.build_vrt import connect_to_survey_registry\n\ndebug_info = f\"\"\"\nPython {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}\nGDAL {gdal.VersionInfo()}\nSQLite {sqlite3.sqlite_version}\nDate {datetime.datetime.now()}\n\"\"\"\n\n\ndef get_tessellation(\n conn: sqlite3.Connection,\n project_dir: str,\n prefix: str,\n data_source: str,\n bucket: str = \"noaa-ocs-nationalbathymetry-pds\",\n) -> str:\n \"\"\"\n Download the tessellation scheme geopackage from AWS.\n\n Parameters\n ----------\n conn : sqlite3.Connection\n database connection object.\n project_dir : str\n destination directory for project.\n prefix : str\n the prefix for the geopackage on AWS to find the file.\n data_source : str\n the data source for the project e.g. 'BlueTopo' or 'Modeling'.\n bucket : str\n AWS bucket for the National Bathymetric Source project.\n\n Returns\n -------\n destination_name : str\n the downloaded file path string.\n \"\"\"\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM tileset\")\n for tilescheme in [dict(row) for row in cursor.fetchall()]:\n try:\n os.remove(os.path.join(project_dir, tilescheme[\"location\"]))\n except (OSError, PermissionError):\n continue\n cred = {\n \"aws_access_key_id\": \"\",\n \"aws_secret_access_key\": \"\",\n \"config\": Config(signature_version=UNSIGNED),\n }\n client = boto3.client(\"s3\", **cred)\n pageinator = client.get_paginator(\"list_objects_v2\")\n objs = pageinator.paginate(Bucket=bucket, Prefix=prefix).build_full_result()\n if \"Contents\" not in objs:\n print(\n f\"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {datetime.datetime.now().astimezone().tzname()}] {data_source}: No geometry found in {prefix}\"\n )\n return None\n tileschemes = objs[\"Contents\"]\n tileschemes.sort(key=lambda x: x[\"LastModified\"], reverse=True)\n source_name = tileschemes[0][\"Key\"]\n filename = os.path.basename(source_name)\n relative = os.path.join(data_source, f\"Tessellation\", filename)\n if len(tileschemes) > 1:\n print(\n f\"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {datetime.datetime.now().astimezone().tzname()}] {data_source}: More than one geometry found in {prefix}, using {filename}\"\n )\n destination_name = os.path.join(project_dir, relative)\n if not os.path.exists(os.path.dirname(destination_name)):\n os.makedirs(os.path.dirname(destination_name))\n try:\n client.download_file(bucket, source_name, destination_name)\n except (OSError, PermissionError) as e:\n print(\n f\"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {datetime.datetime.now().astimezone().tzname()}] {data_source}: \"\n \"Failed to download tile scheme \"\n \"possibly due to conflict with an open existing file. \"\n \"Please close all files and attempt again\"\n )\n sys.exit(1)\n print(\n f\"[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {datetime.datetime.now().astimezone().tzname()}] {data_source}: Downloaded {filename}\"\n )\n cursor.execute(\n \"\"\"REPLACE INTO tileset(tilescheme, location, downloaded)\n VALUES(?, ?, ?)\"\"\",\n (\"Tessellation\", relative, datetime.datetime.now()),\n )\n conn.commit()\n return destination_name\n\n\ndef download_tiles(\n conn: sqlite3.Connection,\n project_dir: str,\n tile_prefix: str,\n data_source: str,\n bucket: str = \"noaa-ocs-nationalbathymetry-pds\",\n) -> [[str], [str], [str]]:\n \"\"\"\n Download tiles' files (geotiff and aux per tile).\n\n Parameters\n ----------\n conn : sqlite3.Connection\n database connection object.\n project_dir : str\n destination directory for project.\n tile_prefix : str\n s3 prefix for tiles.\n data_source : str\n the data source for the project e.g. 'BlueTopo' or 'Modeling'.\n bucket : str\n AWS bucket for the National Bathymetric Source project.\n\n Returns\n -------\n existing_tiles : list\n tiles already existing locally.\n tiles_found : list\n tiles found in s3 bucket.\n tiles_not_found : list\n tiles not found in s3 bucket.\n \"\"\"\n download_tile_list = all_db_tiles(conn)\n # better tqdm download time estimate?\n random.shuffle(download_tile_list)\n new_tile_list = [\n download_tile\n for download_tile in download_tile_list\n if download_tile[\"geotiff_disk\"] is None or download_tile[\"rat_disk\"] is None\n ]\n cred = {\n \"aws_access_key_id\": \"\",\n \"aws_secret_access_key\": \"\",\n \"config\": Config(signature_version=UNSIGNED),\n }\n print(\"\\nResolving fetch list...\")\n client = boto3.client(\"s3\", **cred)\n pageinator = client.get_paginator(\"list_objects_v2\")\n existing_tiles = []\n missing_tiles = []\n tiles_found = []\n tiles_not_found = []\n download_dict = {}\n for fields in download_tile_list:\n if fields[\"geotiff_disk\"] and fields[\"rat_disk\"]:\n if os.path.isfile(\n os.path.join(project_dir, fields[\"geotiff_disk\"])\n ) and os.path.isfile(os.path.join(project_dir, fields[\"rat_disk\"])):\n if fields[\"geotiff_verified\"] != \"True\" or fields[\"rat_verified\"] != \"True\":\n missing_tiles.append(fields[\"tilename\"])\n else:\n existing_tiles.append(fields[\"tilename\"])\n continue\n if (\n os.path.isfile(os.path.join(project_dir, fields[\"geotiff_disk\"]))\n is False\n or os.path.isfile(os.path.join(project_dir, fields[\"rat_disk\"]))\n is False\n ):\n missing_tiles.append(fields[\"tilename\"])\n\n tilename = fields[\"tilename\"]\n pfx = tile_prefix + f\"/{tilename}/\"\n objs = pageinator.paginate(Bucket=bucket, Prefix=pfx).build_full_result()\n if len(objs) > 0:\n download_dict[tilename] = {\n \"tile\": tilename,\n \"bucket\": bucket,\n \"client\": client,\n \"subregion\": fields[\"subregion\"],\n \"utm\": fields[\"utm\"],\n }\n for object_name in objs[\"Contents\"]:\n source_name = object_name[\"Key\"]\n relative = os.path.join(\n data_source, f\"UTM{fields['utm']}\", os.path.basename(source_name)\n )\n destination_name = os.path.join(project_dir, relative)\n if not os.path.exists(os.path.dirname(destination_name)):\n os.makedirs(os.path.dirname(destination_name))\n if \".aux\" in source_name.lower():\n download_dict[tilename][\"rat\"] = source_name\n download_dict[tilename][\"rat_dest\"] = destination_name\n download_dict[tilename][\"rat_verified\"] = fields[\"rat_verified\"]\n download_dict[tilename][\"rat_disk\"] = relative \n download_dict[tilename][\"rat_sha256_checksum\"] = fields[\"rat_sha256_checksum\"] \n else:\n download_dict[tilename][\"geotiff\"] = source_name\n download_dict[tilename][\"geotiff_dest\"] = destination_name\n download_dict[tilename][\"geotiff_verified\"] = fields[\"geotiff_verified\"]\n download_dict[tilename][\"geotiff_disk\"] = relative\n download_dict[tilename][\"geotiff_sha256_checksum\"] = fields[\"geotiff_sha256_checksum\"] \n tiles_found.append(tilename)\n else:\n tiles_not_found.append(tilename)\n\n def pull(downloads: dict) -> dict:\n \"\"\"\n Download files and verify hash.\n\n Parameters\n ----------\n downloads : dict \n dict holding necessary values to execute download and checksum verification.\n\n Returns\n -------\n dict\n result of download attempt.\n \"\"\"\n try:\n downloads[\"client\"].download_file(downloads[\"bucket\"], downloads[\"geotiff\"], downloads[\"geotiff_dest\"])\n downloads[\"client\"].download_file(downloads[\"bucket\"], downloads[\"rat\"], downloads[\"rat_dest\"])\n if os.path.isfile(downloads[\"geotiff_dest\"]) is False or os.path.isfile(downloads[\"rat_dest\"]) is False:\n return {\"Tile\": downloads[\"tile\"], \"Result\": False, \"Reason\": \"missing download\"}\n geotiff_hash = hashlib.sha256(open(downloads[\"geotiff_dest\"], \"rb\").read()).hexdigest() \n rat_hash = hashlib.sha256(open(downloads[\"rat_dest\"], \"rb\").read()).hexdigest() \n if downloads[\"geotiff_sha256_checksum\"] != geotiff_hash or downloads[\"rat_sha256_checksum\"] != rat_hash:\n return {\"Tile\": downloads[\"tile\"], \"Result\": False, \"Reason\": \"incorrect hash\"} \n except Exception as e:\n return {\"Tile\": downloads[\"tile\"], \"Result\": False, \"Reason\": \"exception\"}\n return {\"Tile\": downloads[\"tile\"], \"Result\": True, \"Reason\": \"success\"}\n\n print(f\"{len(new_tile_list)} tile(s) with new data\")\n print(f\"{len(missing_tiles)} tile(s) already downloaded are missing locally\")\n download_length = len(download_dict.keys())\n results = []\n if download_length:\n print(f\"\\nFetching {download_length} tiles\")\n with tqdm(\n total=download_length,\n bar_format=\"{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} Tiles {elapsed}, {remaining} Est. Time Remaining\"\n \"{postfix}\",\n desc=f\"{data_source} Fetch\",\n colour=\"#0085CA\",\n position=0,\n leave=True,\n ) as progress:\n with concurrent.futures.ThreadPoolExecutor(\n max_workers=os.cpu_count() - 1\n ) as executor:\n for i in executor.map(pull, download_dict.values()):\n results.append(i)\n progress.update(1)\n successful_downloads = [\n download[\"Tile\"] for download in results if download[\"Result\"] == True\n ]\n failed_downloads = [\n download[\"Tile\"] for download in results if download[\"Result\"] == False\n ]\n failed_verifications = [\n download[\"Tile\"] for download in results if \n (download[\"Result\"] == False and download[\"Reason\"] == \"incorrect hash\")]\n\n if len(successful_downloads) > 0:\n update_records(conn, download_dict, successful_downloads)\n\n return (\n list(set(tiles_found)),\n list(set(tiles_not_found)),\n successful_downloads,\n failed_downloads,\n existing_tiles,\n missing_tiles,\n failed_verifications,\n new_tile_list,\n )\n\n\ndef get_tile_list(desired_area_filename: str, tile_scheme_filename: str) -> [str]:\n \"\"\"\n Get the list of tiles inside the given polygon(s).\n\n Parameters\n ----------\n desired_area_filename : str\n a gdal compatible file path denoting geometries that reflect the region\n of interest.\n tile_scheme_filename : str\n a gdal compatible file path denoting geometries that reflect the\n tessellation scheme with addressing information for the desired tiles.\n\n Returns\n -------\n feature_list : str\n list of tiles intersecting with the provided polygon(s).\n \"\"\"\n data_source = ogr.Open(desired_area_filename)\n if data_source is None:\n print(\"Unable to open desired area file\")\n return None\n source = ogr.Open(tile_scheme_filename)\n if source is None:\n print(\"Unable to open tile scheme file\")\n return None\n driver = ogr.GetDriverByName(\"MEMORY\")\n intersect = driver.CreateDataSource(\"memData\")\n intersect_lyr = intersect.CreateLayer(\"mem\", geom_type=ogr.wkbPolygon)\n source_layer = source.GetLayer(0)\n source_crs = source_layer.GetSpatialRef()\n num_target_layers = data_source.GetLayerCount()\n feature_list = []\n for layer_num in range(num_target_layers):\n target_layer = data_source.GetLayer(layer_num)\n target_crs = target_layer.GetSpatialRef()\n same_crs = target_crs.IsSame(source_crs)\n if not same_crs:\n transformed_input = transform_layer(target_layer, source_crs)\n target_layer = transformed_input.GetLayer(0)\n target_layer.Intersection(source_layer, intersect_lyr)\n if not same_crs:\n transformed_input = None\n lyr_defn = intersect_lyr.GetLayerDefn()\n for feature in intersect_lyr:\n fields = {}\n for idx in range(lyr_defn.GetFieldCount()):\n fields[lyr_defn.GetFieldDefn(idx).name] = feature.GetField(idx)\n feature_list.append(fields)\n return feature_list\n\n\ndef transform_layer(\n input_layer: ogr.Layer, desired_crs: osr.SpatialReference\n) -> ogr.DataSource:\n \"\"\"\n Transform a provided ogr layer to the provided coordinate reference system.\n\n Parameters\n ----------\n input_layer : ogr.Layer\n the ogr layer to be transformed.\n desired_crs : osr.SpatialReference\n the coordinate system for the transform.\n\n Returns\n -------\n out_ds : ogr.DataSource\n transformed ogr memory datasource.\n \"\"\"\n target_crs = input_layer.GetSpatialRef()\n coord_trans = osr.CoordinateTransformation(target_crs, desired_crs)\n driver = ogr.GetDriverByName(\"MEMORY\")\n out_ds = driver.CreateDataSource(\"memData\")\n out_lyr = out_ds.CreateLayer(\"out_lyr\", geom_type=input_layer.GetGeomType())\n out_defn = out_lyr.GetLayerDefn()\n in_feature = input_layer.GetNextFeature()\n while in_feature:\n geom = in_feature.GetGeometryRef()\n geom.Transform(coord_trans)\n out_feature = ogr.Feature(out_defn)\n out_feature.SetGeometry(geom)\n out_lyr.CreateFeature(out_feature)\n out_feature = None\n in_feature = input_layer.GetNextFeature()\n return out_ds\n\n\ndef update_records(conn: sqlite3.Connection, download_dict: dict, successful_downloads: list) -> None:\n \"\"\"\n Update tile record and associated tables in SQLite database.\n\n Parameters\n ----------\n conn : sqlite3.Connection\n database connection object.\n download_dict : dict\n relevant fields per tile\n successful_downloads : list\n list of tilenames successfully downloaded\n \"\"\"\n # TODO refactor more sensibly\n tiles_records = []\n subregion_records = []\n utm_records = [] \n for tilename in download_dict:\n if tilename in successful_downloads:\n tiles_records.append((\n download_dict[tilename][\"geotiff_disk\"],\n download_dict[tilename][\"rat_disk\"],\n \"True\",\n \"True\",\n tilename\n ))\n subregion_records.append((\n download_dict[tilename][\"subregion\"],\n download_dict[tilename][\"utm\"],\n None,\n None,\n None,\n None,\n None,\n None,\n None,\n None,\n 0,\n ))\n utm_records.append((\n download_dict[tilename][\"utm\"],\n None, \n None, \n 0\n ))\n if len(tiles_records) == 0:\n return\n cursor = conn.cursor()\n cursor.execute(\"BEGIN TRANSACTION;\")\n cursor.executemany(\"\"\"\n UPDATE tiles\n SET geotiff_disk = ?, rat_disk = ?,\n geotiff_verified = ?, rat_verified = ?\n WHERE tilename = ?\n \"\"\",\n tiles_records \n )\n cursor.executemany(\"\"\"\n INSERT INTO vrt_subregion(region, utm, res_2_vrt,\n res_2_ovr, res_4_vrt, res_4_ovr, res_8_vrt, res_8_ovr,\n complete_vrt, complete_ovr, built)\n VALUES(?, ?, ?, ?, ? ,? , ?, ? ,? ,? ,?)\n ON CONFLICT(region) DO UPDATE\n SET utm = EXCLUDED.utm,\n res_2_vrt = EXCLUDED.res_2_vrt,\n res_2_ovr = EXCLUDED.res_2_ovr,\n res_4_vrt = EXCLUDED.res_4_vrt,\n res_4_ovr = EXCLUDED.res_4_ovr,\n res_8_vrt = EXCLUDED.res_8_vrt,\n res_8_ovr = EXCLUDED.res_8_ovr,\n complete_vrt = EXCLUDED.complete_vrt,\n complete_ovr = EXCLUDED.complete_ovr,\n built = EXCLUDED.built\n \"\"\",\n subregion_records\n )\n cursor.executemany(\"\"\"\n INSERT INTO vrt_utm(utm, utm_vrt, utm_ovr, built)\n VALUES(?, ?, ?, ?)\n ON CONFLICT(utm) DO UPDATE\n SET utm_vrt = EXCLUDED.utm_vrt,\n utm_ovr = EXCLUDED.utm_ovr,\n built = EXCLUDED.built\n \"\"\",\n utm_records,\n )\n cursor.execute(\"COMMIT;\")\n conn.commit()\n\n\ndef insert_new(conn: sqlite3.Connection, tiles: list) -> int:\n \"\"\"\n Insert new tile records into SQLite database.\n\n Parameters\n ----------\n conn : sqlite3.Connection\n database connection object.\n tiles : list of dict\n list of tile records.\n\n Returns\n -------\n int\n amount of delivered tiles from input tiles.\n \"\"\"\n cursor = conn.cursor()\n tile_list = [\n (tile[\"tile\"],)\n for tile in tiles\n if tile[\"Delivered_Date\"] and tile[\"GeoTIFF_Link\"] and tile[\"RAT_Link\"]\n ]\n cursor.executemany(\n \"\"\"INSERT INTO tiles(tilename)\n VALUES(?) ON CONFLICT DO NOTHING\"\"\",\n tile_list,\n )\n conn.commit()\n return len(tile_list)\n\n\ndef all_db_tiles(conn: sqlite3.Connection) -> list:\n \"\"\"\n Retrieve all tile records in tiles table of SQLite database.\n\n Parameters\n ----------\n conn : sqlite3.Connection\n database connection object.\n\n Returns\n -------\n list\n all tile records as dictionaries.\n \"\"\"\n cursor = conn.cursor()\n cursor.execute(\"SELECT * FROM tiles\")\n return [dict(row) for row in cursor.fetchall()]\n\n\ndef upsert_tiles(conn: sqlite3.Connection, project_dir: str, tile_scheme: str) -> None:\n \"\"\"\n Update tile records in database with latest deliveries found in tilescheme.\n\n Parameters\n ----------\n conn : sqlite3.Connection\n database connection object.\n project_dir : str\n destination directory for project.\n tile_scheme : str\n a gdal compatible file path with the tessellation scheme.\n \"\"\"\n # database records holds current set\n # tilescheme polygons has latest set\n # use the two to see where new tiles or updates to existing tiles exist\n # use global tileset to map its region\n db_tiles = all_db_tiles(conn)\n ts_ds = ogr.Open(tile_scheme)\n ts_lyr = ts_ds.GetLayer()\n ts_defn = ts_lyr.GetLayerDefn()\n ts_tiles = []\n for ft in ts_lyr:\n field_list = {}\n geom = ft.GetGeometryRef()\n field_list[\"wkt_geom\"] = geom.ExportToWkt()\n for field_num in range(ts_defn.GetFieldCount()):\n field_name = ts_defn.GetFieldDefn(field_num).name\n field_list[field_name.lower()] = ft.GetField(field_name)\n ts_tiles.append(field_list)\n ts_ds = None\n global_tileset = global_region_tileset(1, \"1.2\")\n gs = ogr.Open(global_tileset)\n lyr = gs.GetLayer()\n insert_tiles = []\n for db_tile in db_tiles:\n ts_tile = [\n ts_tile for ts_tile in ts_tiles if db_tile[\"tilename\"] == ts_tile[\"tile\"]\n ]\n if len(ts_tile) == 0:\n print(\n f\"Warning: {db_tile['tilename']} in database appears to have \"\n \"been removed from latest tilescheme\"\n )\n continue\n if len(ts_tile) > 1:\n raise ValueError(\n f\"More than one tilename {db_tile['tilename']} \"\n \"found in tileset.\\n\"\n \"Please alert NBS.\\n\"\n \"{debug_info}\"\n )\n ts_tile = ts_tile[0]\n # inserted into db only when delivered_date exists\n # so value of None in ts_tile indicates delivered_date was removed\n if ts_tile[\"delivered_date\"] is None:\n print(\n \"Warning: Unexpected removal of delivered date \"\n f\"for tile {db_tile['tilename']}\"\n )\n continue\n if (db_tile[\"delivered_date\"] is None) or (\n ts_tile[\"delivered_date\"] > db_tile[\"delivered_date\"]\n ):\n try:\n if db_tile[\"geotiff_disk\"] and os.path.isfile(\n os.path.join(project_dir, db_tile[\"geotiff_disk\"])\n ):\n os.remove(os.path.join(project_dir, db_tile[\"geotiff_disk\"]))\n if db_tile[\"rat_disk\"] and os.path.isfile(\n os.path.join(project_dir, db_tile[\"rat_disk\"])\n ):\n os.remove(os.path.join(project_dir, db_tile[\"rat_disk\"]))\n except (OSError, PermissionError) as e:\n print(\n \"Failed to remove older files for tile \"\n f\"{db_tile['tilename']}. Please close all files and \"\n \"attempt fetch again.\"\n )\n gdal.Unlink(global_tileset)\n raise e\n lyr.SetSpatialFilter(ogr.CreateGeometryFromWkt(ts_tile[\"wkt_geom\"]))\n if lyr.GetFeatureCount() != 1:\n gdal.Unlink(global_tileset)\n raise ValueError(\n \"Error getting subregion for \"\n f\"{db_tile['tilename']}. \\n\"\n f\"{lyr.GetFeatureCount()} subregion(s). \\n\"\n f\"{debug_info}\"\n )\n region_ft = lyr.GetNextFeature()\n ts_tile[\"region\"] = region_ft.GetField(\"Region\")\n insert_tiles.append(\n (\n ts_tile[\"tile\"],\n ts_tile[\"geotiff_link\"],\n ts_tile[\"rat_link\"],\n ts_tile[\"delivered_date\"],\n ts_tile[\"resolution\"],\n ts_tile[\"utm\"],\n ts_tile[\"region\"],\n ts_tile[\"geotiff_sha256_checksum\"],\n ts_tile[\"rat_sha256_checksum\"],\n )\n )\n if insert_tiles:\n cursor = conn.cursor()\n for ins in insert_tiles:\n if len(ins) != 9:\n print(len(ins))\n raise ValueError()\n cursor.executemany(\n \"\"\"INSERT INTO tiles(tilename, geotiff_link, rat_link,\n delivered_date, resolution, utm, subregion, \n geotiff_sha256_checksum, rat_sha256_checksum)\n VALUES(?, ?, ? ,? ,? ,?, ?, ?, ?)\n ON CONFLICT(tilename) DO UPDATE\n SET geotiff_link = EXCLUDED.geotiff_link,\n rat_link = EXCLUDED.rat_link,\n delivered_date = EXCLUDED.delivered_date,\n resolution = EXCLUDED.resolution,\n utm = EXCLUDED.utm,\n subregion = EXCLUDED.subregion,\n geotiff_sha256_checksum = EXCLUDED.geotiff_sha256_checksum,\n rat_sha256_checksum = EXCLUDED.rat_sha256_checksum,\n geotiff_verified = Null,\n rat_verified = Null,\n geotiff_disk = Null,\n rat_disk = Null\n \"\"\",\n insert_tiles,\n )\n conn.commit()\n gdal.Unlink(global_tileset)\n\n\ndef convert_base(charset: str, input: int, minimum: int) -> str:\n \"\"\"\n Convert integer to new base system using the given symbols with a\n minimum length filled using leading characters of the lowest value in the\n given charset.\n\n Parameters\n ----------\n charset : str\n length of this str will be the new base system and characters\n given will be the symbols used.\n input : int\n integer to convert.\n minimum : int\n returned output will be adjusted to this desired length using\n leading characters of the lowest value in charset.\n\n Returns\n -------\n str\n converted value in given system.\n \"\"\"\n res = \"\"\n while input:\n res += charset[input % len(charset)]\n input //= len(charset)\n return (res[::-1] or charset[0]).rjust(minimum, charset[0])\n\n\ndef global_region_tileset(index: int, size: str) -> str:\n \"\"\"\n Generate a global tilescheme.\n\n Parameters\n ----------\n index : int\n index of tileset to determine tilescheme name.\n size : str\n length of the side of an individual tile in degrees.\n\n Returns\n -------\n location : str\n gdal memory filepath to global tilescheme.\n \"\"\"\n charset = \"BCDFGHJKLMNPQRSTVWXZ\"\n name = convert_base(charset, index, 2)\n roundnum = len(size.split(\".\")[1])\n size = float(size)\n location = \"/vsimem/global_tileset.gpkg\"\n ds = ogr.GetDriverByName(\"GPKG\").CreateDataSource(location)\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(4326)\n layer = ds.CreateLayer(\"global_tileset\", srs, ogr.wkbMultiPolygon)\n layer.CreateFields(\n [\n ogr.FieldDefn(\"Region\", ogr.OFTString),\n ogr.FieldDefn(\"UTM_Zone\", ogr.OFTInteger),\n ogr.FieldDefn(\"Hemisphere\", ogr.OFTString),\n ]\n )\n layer_defn = layer.GetLayerDefn()\n layer.StartTransaction()\n y = round(-90 + size, roundnum)\n y_count = 0\n while y <= 90:\n ns = \"N\"\n if y <= 0:\n ns = \"S\"\n x = -180\n x_count = 0\n while x < 180:\n current_utm = \"{:02d}\".format(int(np.ceil((180 + x + 0.00000001) / 6)))\n ring = ogr.Geometry(ogr.wkbLinearRing)\n ring.AddPoint_2D(x, y)\n ring.AddPoint_2D(round(x + size, roundnum), y)\n ring.AddPoint_2D(round(x + size, roundnum), round(y - size, roundnum))\n ring.AddPoint_2D(x, round(y - size, roundnum))\n ring.AddPoint_2D(x, y)\n poly = ogr.Geometry(ogr.wkbPolygon)\n poly.AddGeometry(ring)\n poly = poly.Buffer(-0.002)\n multipoly = ogr.Geometry(ogr.wkbMultiPolygon)\n multipoly.AddGeometry(poly)\n feat = ogr.Feature(layer_defn)\n feat.SetGeometry(multipoly)\n charset = \"2456789BCDFGHJKLMNPQRSTVWXZ\"\n x_rep = convert_base(charset, x_count, 3)\n y_rep = convert_base(charset, y_count, 3)\n feat.SetField(\"Region\", f\"{name}{x_rep}{y_rep}\")\n feat.SetField(\"UTM_Zone\", current_utm)\n feat.SetField(\"Hemisphere\", ns)\n layer.CreateFeature(feat)\n x = round(x + size, roundnum)\n x_count += 1\n y = round(y + size, roundnum)\n y_count += 1\n layer.CommitTransaction()\n return location\n\n\ndef sweep_files(conn: sqlite3.Connection, project_dir: str) -> None:\n \"\"\"\n Remove missing files from tracking.\n\n Parameters\n ----------\n conn : sqlite3.Connection\n database connection object.\n project_dir : str\n destination directory for project.\n \"\"\"\n db_tiles = all_db_tiles(conn)\n cursor = conn.cursor()\n untracked_tiles = 0\n untracked_subregions = 0\n untracked_utms = 0\n for fields in db_tiles:\n if (\n fields[\"geotiff_disk\"]\n and os.path.isfile(os.path.join(project_dir, fields[\"geotiff_disk\"]))\n == False\n ) or (\n fields[\"rat_disk\"]\n and os.path.isfile(os.path.join(project_dir, fields[\"rat_disk\"])) == False\n ):\n cursor.execute(\n \"DELETE FROM tiles where tilename = ? RETURNING *\",\n (fields[\"tilename\"],),\n )\n del_tile = cursor.fetchone()\n if del_tile:\n untracked_tiles += 1\n files = [\"geotiff_disk\", \"rat_disk\"]\n for file in files:\n try:\n if del_tile[file] and os.path.isfile(\n os.path.join(project_dir, del_tile[file])\n ):\n os.remove(os.path.join(project_dir, del_tile[file]))\n except (OSError, PermissionError):\n continue\n cursor.execute(\n \"\"\"DELETE FROM vrt_subregion\n WHERE region NOT IN\n (SELECT subregion\n FROM tiles\n WHERE geotiff_disk is not null\n AND rat_disk is not null)\n RETURNING *;\"\"\"\n )\n del_subregions = cursor.fetchall()\n untracked_subregions += len(del_subregions)\n for del_subregion in del_subregions:\n files = [\n \"res_2_vrt\",\n \"res_2_ovr\",\n \"res_4_vrt\",\n \"res_4_ovr\",\n \"res_8_vrt\",\n \"res_8_ovr\",\n \"complete_vrt\",\n \"complete_ovr\",\n ]\n for file in files:\n try:\n if del_subregion[file] and os.path.isfile(\n os.path.join(project_dir, del_subregion[file])\n ):\n os.remove(os.path.join(project_dir, del_subregion[file]))\n except (OSError, PermissionError):\n continue\n cursor.execute(\n \"\"\"DELETE FROM vrt_utm\n WHERE utm NOT IN\n (SELECT utm\n FROM tiles\n WHERE geotiff_disk is not null\n AND rat_disk is not null)\n RETURNING *;\"\"\"\n )\n del_utms = cursor.fetchall()\n untracked_utms += len(del_utms)\n for del_utm in del_utms:\n files = [\"utm_vrt\", \"utm_ovr\"]\n for file in files:\n try:\n if (del_utm[file]) and (\n os.path.isfile(os.path.join(project_dir, del_utm[file]))\n ):\n os.remove(os.path.join(project_dir, del_utm[file]))\n except (OSError, PermissionError):\n continue\n conn.commit()\n return untracked_tiles, untracked_subregions, untracked_utms\n\n\ndef main(\n project_dir: str,\n desired_area_filename: str = None,\n untrack_missing: bool = False,\n data_source: str = None,\n) -> [[str], [str]]:\n \"\"\"\n Track tiles. Download tiles. Update already tracked tiles.\n\n Parameters\n ----------\n project_dir : str\n The directory path to use. Will create if it does not currently exist.\n Required argument.\n desired_area_filename : str\n The geometry file to use to find intersecting available tiles.\n The returned tile ids at the time of intersection will be added to\n tracking. fetch_tiles will stay up to date with the latest data\n available from the NBS for all tracked tiles. This argument is\n not necessary if you do not want to add new tile ids to tracking.\n untrack_missing : bool\n This flag will untrack tiles that have missing files in your local\n download directory. fetch_tiles will no longer retrieve these tiles.\n data_source : str\n The NBS offers various products to different end-users. Some are available publicly.\n Use this argument to identify which product you want. BlueTopo is the default.\n\n Returns\n -------\n successful_downloads : list\n tiles downloaded.\n list\n tiles not found in s3 or failed during download.\n \"\"\"\n project_dir = os.path.expanduser(project_dir)\n if desired_area_filename:\n desired_area_filename = os.path.expanduser(desired_area_filename)\n if os.path.isabs(project_dir) is False or (\n desired_area_filename and os.path.isabs(desired_area_filename) is False\n ):\n print(\"Please use an absolute path for your project folder and geometry path.\")\n if \"windows\" not in platform.system().lower():\n print(\"Typically for non windows systems this means starting with '/'\")\n sys.exit(1)\n\n if data_source is None or data_source.lower() == \"bluetopo\":\n data_source = \"BlueTopo\"\n geom_prefix = \"BlueTopo/_BlueTopo_Tile_Scheme/BlueTopo_Tile_Scheme\"\n tile_prefix = \"BlueTopo\"\n\n elif data_source.lower() == \"modeling\":\n data_source = \"Modeling\"\n geom_prefix = (\n \"Test-and-Evaluation/Modeling/_Modeling_Tile_Scheme/Modeling_Tile_Scheme\"\n )\n tile_prefix = \"Test-and-Evaluation/Modeling\"\n\n else:\n raise ValueError(f\"Invalid data source: {data_source}\")\n\n start = datetime.datetime.now()\n print(\n f\"[{start.strftime('%Y-%m-%d %H:%M:%S')} {datetime.datetime.now().astimezone().tzname()}] {data_source}: Beginning work in project folder: {project_dir}\"\n )\n if not os.path.exists(project_dir):\n os.makedirs(project_dir)\n\n conn = connect_to_survey_registry(project_dir, data_source)\n geom_file = get_tessellation(conn, project_dir, geom_prefix, data_source)\n\n if untrack_missing:\n untracked_tiles, untracked_sr, untracked_utms = sweep_files(conn, project_dir)\n print(\n f\"Untracked {untracked_tiles} tile(s), \"\n f\"{untracked_sr} subregion vrt(s), \"\n f\"{untracked_utms} utm vrt(s)\"\n )\n\n if desired_area_filename:\n if not os.path.isfile(desired_area_filename):\n raise ValueError(\n f\"The geometry {desired_area_filename} for \"\n \"determining what to download does not exist.\"\n )\n tile_list = get_tile_list(desired_area_filename, geom_file)\n available_tile_count = insert_new(conn, tile_list)\n print(\n f\"\\nTracking {available_tile_count} available {data_source} tile(s) \"\n f\"discovered in a total of {len(tile_list)} intersected tile(s) \"\n \"with given polygon.\"\n )\n\n upsert_tiles(conn, project_dir, geom_file)\n\n (\n tiles_found,\n tiles_not_found,\n successful_downloads,\n failed_downloads,\n existing_tiles,\n missing_tiles,\n failed_verifications,\n new_tile_list,\n ) = download_tiles(conn, project_dir, tile_prefix, data_source)\n\n print(\n \"\\n___________________________________ SUMMARY ___________________________________\"\n )\n print(\"\\nExisting:\")\n print(\n \"Number of tiles already existing locally without updates:\",\n len(existing_tiles),\n )\n if new_tile_list or missing_tiles:\n print(\"\\nSearch:\")\n print(\n f\"Number of tiles to attempt to fetch: {len(new_tile_list) + len(missing_tiles)} [ {len(new_tile_list)} new data + {len(missing_tiles)} missing locally ]\"\n )\n if len(tiles_found) < (len(new_tile_list) + len(missing_tiles)):\n print(\n \"* Some tiles we wanted to fetch were not found in the S3 bucket.\"\n \"\\n* The NBS may be actively updating the tiles in question.\"\n \"\\n* You can rerun fetch_tiles at a later time to download these tiles.\"\n \"\\n* Please contact the NBS if this issue does not fix itself on subsequent later runs.\"\n )\n print(\"\\nFetch:\")\n print(\n f\"Number of tiles found in S3 successfully downloaded: {len(successful_downloads)}/{len(tiles_found)}\"\n )\n if len(failed_downloads):\n print(\n \"* Some tiles appear to have failed downloading.\"\n \"\\n* Please rerun fetch_tiles to retry.\"\n )\n if len(failed_verifications):\n print(\n f\"{len(failed_verifications)} tiles failed checksum verification: {failed_verifications}\"\n f\"\\nPlease contact the NBS if this issue does not fix itself on subsequent runs.\"\n )\n print(\n f\"\\n[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {datetime.datetime.now().astimezone().tzname()}] {data_source}: Operation complete after {datetime.datetime.now() - start}\"\n )\n return successful_downloads, list(set(tiles_not_found + failed_downloads))\n","repo_name":"noaa-ocs-hydrography/BlueTopo","sub_path":"nbs/bluetopo/core/fetch_tiles.py","file_name":"fetch_tiles.py","file_ext":"py","file_size_in_byte":37664,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"86"} +{"seq_id":"19019806008","text":"import os \ndir_path = os.path.dirname(os.path.realpath(__file__))\n\nproject_dir = \"app\"\n\nproject_name = \"cryptocurrency\"\n\napps = [\n \"blockchain\",\n \"account\"\n]\n\nfor app in apps:\n current_path = f\"{dir_path}/{project_dir}/{project_name}/{app}/migrations\"\n for filename in os.listdir(f\"{current_path}\"):\n if filename != \"__init__.py\":\n os.system(f\"rm -rf {current_path}/{filename}\")","repo_name":"alexandro591/CryptoBackend","sub_path":"delete_migrations.py","file_name":"delete_migrations.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"70449534043","text":"# Example: Reading a file line-by-line\n\n# Version 1: using readline in a while loop\n\"\"\"\nf = open(\"drawing.txt\", \"r\")\nwhile True:\n line = f.readline()\n if len(line)==0: break\n print(len(line), line)\nf.close() # REMEMBER to close!\n\"\"\"\n\n# Version 2: using a for loop to iterate the lines in the file\n\"\"\"\nf = open(\"drawing.txt\", \"r\")\nfor line in f:\n print(len(line), line)\nf.close() # REMEMBER to close!\n\"\"\"\n\n# Version 3: Same thing, but using a with statement\nwith open(\"drawing.txt\", \"r\") as f:\n print(\"Primeira\", f.readline())\n for line in f:\n line = line.rstrip()\n print(len(line), line)\n # NO NEED to call close()!\n\n","repo_name":"FranciscoRibeiro03/programming-fundamentals","sub_path":"aula06/examples/ex1fileread.py","file_name":"ex1fileread.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"86"} +{"seq_id":"86740646598","text":"from django.shortcuts import render, get_object_or_404\nfrom django.views.generic import ListView, DetailView, View\nfrom django.views.generic.edit import FormView, CreateView\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\n#from datetime import date\nfrom .models import Post, Comment\nfrom .forms import CommentForm\n# dummy data for the posts\n\n\n\n# def get_date(post):\n# return post['date'] # or post.get('date')\n\n# print(get_date(posts))\n# print(posts[0]['date'])\n\n# Create your views here\n\nclass AboutView(View):\n def get(self, request):\n return render(request, \"blog/about-me.html\")\n \n\nclass SkillsView(View):\n def get(self, request):\n return render(request, \"blog/my-skills.html\")\n\n\nclass StartingView(ListView):\n template_name = \"blog/index.html\"\n model = Post \n ordering = [\"-date\", \"-title\"]\n #context_object_name = \"posts\"\n\n def get_queryset(self):\n base_query = super().get_queryset()\n data = base_query[:3] \n return data \n\n\"\"\"\"\ndef starting_page(request):\n # get the latest posts\n # sort by date and returns a new list. if all_posts.sort(key) original list gets sorted\n latest_posts = Post.objects.all().order_by(\"-date\")[:3] #- makes it desc. django will convert this into sql so only the first 3 are fetched.\n #cannot do [:-3] it is not supportd\n #sorted_posts = sorted(all_posts, key=get_date)\n #latest_posts = sorted_posts[-3:]\n return render(request, \"blog/index.html\", {\n \"posts\": latest_posts\n # latest_posts can be used in index.html\n })\n\"\"\"\n\nclass PostsView(ListView):\n template_name = \"blog/all-posts.html\"\n model = Post\n ordering = [\"-date\"]\n #context_object_name = \"all_posts\"\n\n\"\"\"\ndef posts(request):\n all_posts = Post.objects.all().order_by(\"-date\")\n return render(request, \"blog/all-posts.html\", {\n \"all_posts\": all_posts # all_posts list of dictionary is passed to all-posts.html\n })\n\"\"\"\n\nclass PostDetailView(View):\n model = Post \n def get(self, request, slug):\n post = Post.objects.get(slug=slug) \n stored_posts = request.session.get(\"stored_posts\")\n has_read_later = True\n if stored_posts is None or len(stored_posts) == 0:\n has_read_later = False\n elif int(post.id) not in stored_posts:\n has_read_later = False\n elif int(post.id) in stored_posts:\n has_read_later = True\n\n return render(request, \"blog/post-detail.html\",{\n \"post\":post,\n \"comment_form\":CommentForm(),\n \"comments\":post.comments.all().order_by(\"-id\"),\n \"has_read_later\":has_read_later\n })\n \n \n #template_name = \"blog/post-detail.html\"\n # def get_context_data(self, **kwargs):\n # context = super().get_context_data(**kwargs)\n # context[\"comment_form\"] = CommentForm() #set up the form \n # return context\n \n def post(self, request, slug):\n post = Post.objects.get(slug=slug) \n comment_form= CommentForm(request.POST)\n if comment_form.is_valid():\n comment = comment_form.save(commit=False) #because post field in comment table was excluded \n comment.post = post #manually add which post it relates to\n comment.save()\n return HttpResponseRedirect(reverse(\"post-detail-page\", args=[slug])) #send get reqeuest to the same page\n else:\n return render(request, \"blog/post-detail.html\", {\n \"post\":post,\n \"comment_form\":comment_form,\n \"comments\":post.comments.all().order_by(\"-id\")\n })\n \n #context_object_name = \"selected_post\"\n #can automatically search for data by id/pk or slug\n #also raise 404 error automatically\n\n\n\n\"\"\"\ndef post_detail(request, slug):\n # finds next element matching certain condition\n #identified_post = next(post for post in all_posts if post['slug'] == slug)\n\n identified_post = get_object_or_404(Post, slug=slug)\n return render(request, \"blog/post-detail.html\", {\n \"post\": identified_post,\n \"post_tags\": identified_post.tag.all()\n }) # accepts slug parameter\n\"\"\"\n\nclass ReadLaterView(View):\n def getData(self, request):\n stored_posts = request.session.get(\"stored_posts\")\n context = {}\n if stored_posts is None or len(stored_posts) == 0:\n context[\"posts\"] = []\n context[\"has_posts\"] = False\n else:\n read_later = Post.objects.filter(id__in=stored_posts)\n context[\"posts\"]=read_later\n context[\"has_posts\"]=True\n return context\n \n def get(self, request):\n stored_posts = request.session.get(\"stored_posts\")\n context = {}\n if stored_posts is None or len(stored_posts) == 0:\n context[\"posts\"] = []\n context[\"has_posts\"] = False\n else:\n read_later = Post.objects.filter(id__in=stored_posts)\n context[\"posts\"]=read_later\n context[\"has_posts\"]=True\n return render(request, \"blog/stored-posts.html\", context)\n\n def post(self, request):\n context = self.getData(self.request)\n stored_posts = request.session.get(\"stored_posts\")\n if \"remove_id\" in request.POST:\n post_id=int(request.POST[\"remove_id\"])\n print(\"debug here stored_posts\" + str(stored_posts))\n print(\"debug here post_id\" + str(post_id))\n stored_posts.remove(post_id)\n request.session[\"stored_posts\"] = stored_posts\n \n return HttpResponseRedirect(reverse(\"read-later\")) #render(request, \"blog/stored-posts.html\", context)\n else:\n if stored_posts is None:\n stored_posts=[] #set it to empty list if there is no session \n post_id= int(request.POST[\"post_id\"])\n if post_id not in stored_posts:\n stored_posts.append(post_id) \n request.session[\"stored_posts\"] = stored_posts #session is created if did not exit, update if existed \n return HttpResponseRedirect(reverse(\"read-later\"))\n\n\n","repo_name":"AKoy-22/my_site","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"20663484833","text":"from .encoders import *\nfrom .decoders import *\n\n\nclass autoencoder_class(nn.Module):\n def __init__(self, args):\n super(autoencoder_class, self).__init__()\n from .encoders import encoder_dict\n from .decoders import decoder_dict\n\n arch_name = args.autoencoder_arch.replace(\"_autoencoder\", \"\")\n\n for decoder_name in [\"small\", \"deep\", \"resize\", \"identity\"]:\n if decoder_name in arch_name:\n decoder_class = decoder_name + \"_decoder\"\n encoder_class = arch_name.replace(\n \"_\" + decoder_name, \"\") + \"_encoder\"\n decoder_name = \"\"\n break\n\n if decoder_name != \"\":\n decoder_class = \"default_decoder\"\n encoder_class = arch_name + \"_encoder\"\n\n self.encoder = encoder_dict[encoder_class](args)\n self.decoder = decoder_dict[decoder_class](args)\n\n self.jump.requires_grad = False\n self.dictionary.requires_grad = False\n self.l1_norms.requires_grad = False\n\n def __getattr__(self, key):\n\n if (\n key == \"jump\"\n or key == \"dictionary\"\n or key == \"T\"\n or key == \"p\"\n or key == \"l1_norms\"\n or key == \"set_BPDA_type\"\n or key == \"fix_seed\"\n ):\n return getattr(self.encoder, key)\n else:\n return super(autoencoder_class, self).__getattr__(key)\n\n def forward(self, x):\n return self.decoder(self.encoder(x))\n\n def dictionary_update_off(self):\n for p in self.encoder.parameters():\n p.requires_grad = False\n\n def dictionary_update_on(self):\n self.dictionary_update_off()\n self.encoder.conv.weight.requires_grad = True\n","repo_name":"metehancekic/activation_sparsity","sub_path":"src/models/overcomplete_frontend/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"41329980059","text":"#Question: Given BST find inorder successor of node N\n\n'''\nOBSERVATION:\n1. In inorder traversal, next node value (successor) is > N\n2. Successor is the smallest of the largest value > N \n\nREFERENCES:\n1. https://discuss.leetcode.com/topic/25698/java-python-solution-o-h-time-and-o-1-space-iterative\n2. http://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/\n'''\n\nimport sys\nsys.path.append(\"./mylib\")\nimport BST\n\n#Create BST\nroot = BST.BSTNode(4)\ninput = [3,2,1,5,10,7,6,9,12,15]\nfor x in input:\n BST.insert(root, BST.BSTNode(x))\n\n\ndef nextNode(node,target):\n result = None\n while node:\n #if value > target, can be successor!\n if node.data > target:\n result = node.data\n #IMPORTANT: find smallest of the largest!\n node = node.left\n else:\n #go right!\n node = node.right\n return result\n\ntarget = 11\nprint(\"First value greater than \", target , \" = \", nextNode(root,target))\n","repo_name":"harishvc/challenges","sub_path":"binary-search-tree-first-value-greater-than-K.py","file_name":"binary-search-tree-first-value-greater-than-K.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"86"} +{"seq_id":"42093426326","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 17 15:34:23 2018\r\n\r\n@author: Jamee\r\n\"\"\"\r\n\r\ndef binpack(articles,bin_cap):\r\n my_team_number_or_name = \"2-11\"\r\n bin_contents = []\r\n \r\n a_list = [[k,v] for k,v in articles.items()]\r\n a_list.sort(key=lambda x:x[1], reverse=True)\r\n\r\n def newBin():\r\n return [[], 0.0]\r\n\r\n for a in a_list:\r\n added = False\r\n for thisBin in bin_contents:\r\n if a[1] + thisBin[1] <= bin_cap:\r\n thisBin[0].append(a[0])\r\n thisBin[1] += a[1]\r\n added = True\r\n break\r\n if not added:\r\n thisBin = newBin()\r\n thisBin[0].append(a[0])\r\n thisBin[1] += a[1]\r\n bin_contents.append(thisBin)\r\n\r\n for i in range(len(bin_contents)):\r\n bin_contents[i] = [k for k in bin_contents[i][0]]\r\n\r\n return my_team_number_or_name, bin_contents","repo_name":"jamee-allen/workspace","sub_path":"heuristic-algorithms/05 Speedy Algorithm/binpacking_fast.py","file_name":"binpacking_fast.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"28953220124","text":"\"\"\"change unique constraint for styles\n\nRevision ID: 2de84a0fe626\nRevises: 49229117b843\nCreate Date: 2022-10-16 11:04:28.059439\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nimport sqlmodel\n\n\n# revision identifiers, used by Alembic.\nrevision = '2de84a0fe626'\ndown_revision = '49229117b843'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('ix_style_name', table_name='style')\n op.create_index(op.f('ix_style_name'), 'style', ['name'], unique=False)\n op.create_unique_constraint(None, 'style', ['user_id', 'name'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'style', type_='unique')\n op.drop_index(op.f('ix_style_name'), table_name='style')\n op.create_index('ix_style_name', 'style', ['name'], unique=False)\n # ### end Alembic commands ###\n","repo_name":"tarodo/clouder","sub_path":"backend/migrations/versions/2de84a0fe626_change_unique_constraint_for_styles.py","file_name":"2de84a0fe626_change_unique_constraint_for_styles.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"18870621303","text":"#Functions\n\ndef sayHello(name):\n hi = 'Hi there, ' + name\n return hi\n\njim = sayHello('Jim')\nprint(jim)\n\ndef addOneToNum(num):\n num = num + 1\n print('Num inside function', num)\n return\n\n#Numbers are immuntable\nnum = 5\naddOneToNum(num)\nprint('Outside of num function', num)\n\ndef addToList(list):\n list.append(4)\n print('List inside of func', list)\n return\n\nlist = [1,2,3]\naddToList(list)\nprint('List outside of func', list)\n\n","repo_name":"Andyt-Nguyen/python-basics","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"38923331153","text":"from __future__ import absolute_import, unicode_literals\nimport codecs\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.parser import Parser\nfrom mock import (MagicMock, patch)\nimport os\nfrom pkg_resources import resource_filename\nfrom unittest import TestCase\nfrom gs.group.list.base.emailmessage import EmailMessage\nimport gs.group.list.store.messagestore # lint:ok\nfrom gs.group.list.store.messagestore import (EmailMessageStore)\n\n\nclass EmailMessageStoreTest(TestCase):\n m = '''From: Me \nSubject: Violence\nTo: Group \n\nTonight on Ethel the Frog we look at violence.\\n'''\n\n def setUp(self):\n self.message = EmailMessage(self.m, list_title='Ethel the Frog',\n group_id='ethel')\n context = MagicMock()\n self.messageStore = EmailMessageStore.from_email_message(\n context, self.message)\n\n def test_in_reply_to(self):\n 'Test the In-Reply-To header when it is unset'\n r = self.messageStore.inreplyto\n self.assertEqual('', r)\n\n def test_in_reply_to_set(self):\n e = 'person@example.com'\n self.messageStore.message['In-reply-to'] = e\n r = self.messageStore.inreplyto\n self.assertEqual(e, r)\n\n def test_attachment_count(self):\n 'Check that the text-body does not count as an attachment'\n r = self.messageStore.attachment_count\n self.assertEqual(0, r)\n\n def get_txt_html_msg(self):\n retval = MIMEMultipart()\n a = MIMEMultipart('alternative')\n retval.attach(a)\n tt = MIMEText(\n 'Tonight on Ethel the Frog\\u2026 we look at violence.\\n',\n 'plain', 'UTF-8')\n a .attach(tt)\n th = MIMEText(\n '

Tonight on Ethel the Frog… we look at '\n 'violence.\\n

', 'html', 'us-ascii')\n a.attach(th)\n\n for h, v in self.messageStore.message.items():\n retval.add_header(h, v)\n return retval\n\n def test_attachment_count_html_body(self):\n self.messageStore.message = self.get_txt_html_msg()\n r = self.messageStore.attachment_count\n self.assertEqual(0, r)\n\n def test_attachment_count_file(self):\n 'Can we see one file'\n m = self.get_txt_html_msg()\n textFile = MIMEText('The violence of British Gangland.')\n textFile.add_header('Content-Disposition', 'attachment',\n filename='gangland.txt')\n m.attach(textFile)\n self.messageStore.message = m\n\n r = self.messageStore.attachment_count\n self.assertEqual(1, r)\n\n def test_attachment_count_files(self):\n 'Can we see multiple files'\n m = self.get_txt_html_msg()\n textFile = MIMEText('The violence of British Gangland.')\n textFile.add_header('Content-Disposition', 'attachment',\n filename='gangland.txt')\n m.attach(textFile)\n textFile = MIMEText('When he grew up he took to putting the boot '\n 'in.')\n textFile.add_header('Content-Disposition', 'attachment',\n filename='durk.txt')\n m.attach(textFile)\n self.messageStore.message = m\n\n r = self.messageStore.attachment_count\n self.assertEqual(2, r)\n\n @staticmethod\n def get_attachment(payload='', fileId='', filename='', length=0,\n md5_sum='', encoding='utf-8', mimetype='text/plain',\n cid=''):\n maintype, subtype = mimetype.split('/')\n retval = {\n 'payload': payload,\n 'fileid': fileId,\n 'filename': filename,\n 'length': length,\n 'md5': md5_sum,\n 'charset': encoding,\n 'maintype': maintype,\n 'subtype': subtype,\n 'mimetype': mimetype,\n 'contentid': cid}\n return retval\n\n @patch('gs.group.list.store.messagestore.log')\n def test_store_attachment_text_body(self, l):\n 'Ensure we do not store anything that looks like the text body'\n p = 'Tonight on Ethel the Frog\\u2026 we look at violence.\\n'\n a = self.get_attachment(payload=p.encode('utf-8'), length=len(p))\n\n with patch.object(self.messageStore, 'add_file') as addFileMock:\n self.messageStore.store_attachment(a)\n self.assertEqual(0, addFileMock.call_count)\n\n @patch('gs.group.list.store.messagestore.log')\n def test_store_attachment_html_body(self, l):\n 'Ensure we do not store anything that looks like the HTML body'\n p = '

Tonight on Ethel the Frog… we look at violence.

'\n a = self.get_attachment(payload=p.encode('ascii'), length=len(p),\n mimetype='text/html')\n\n with patch.object(self.messageStore, 'add_file') as addFileMock:\n self.messageStore.store_attachment(a)\n self.assertEqual(0, addFileMock.call_count)\n\n @patch('gs.group.list.store.messagestore.log')\n def test_store_attachment_cid_only(self, l):\n '''Ensure we do not store anything that looks like a file that is\njust used in the HTML body'''\n p = b'This is not an image'\n a = self.get_attachment(payload=p, length=len(p),\n mimetype='image/jpeg', cid='something')\n\n with patch.object(self.messageStore, 'add_file') as addFileMock:\n self.messageStore.store_attachment(a)\n self.assertEqual(0, addFileMock.call_count)\n\n @patch('gs.group.list.store.messagestore.log')\n def test_store_attachment_cid(self, l):\n p = b'This is not an image'\n a = self.get_attachment(payload=p, length=len(p),\n mimetype='image/jpeg', cid='something',\n filename=\"foo.jpg\")\n\n with patch.object(self.messageStore, 'add_file') as addFileMock:\n self.messageStore.store_attachment(a)\n addFileMock.assert_called_once_with(a, 'Violence', '')\n\n @patch('gs.group.list.store.messagestore.log')\n def test_store_attachment_empty(self, l):\n p = b''\n a = self.get_attachment(payload=p, length=len(p),\n mimetype='image/jpeg', filename=\"foo.jpg\")\n\n with patch.object(self.messageStore, 'add_file') as addFileMock:\n self.messageStore.store_attachment(a)\n self.assertEqual(0, addFileMock.call_count)\n\n @patch('gs.group.list.store.messagestore.log')\n def test_store_attachment(self, l):\n '''Ensure we do not store anything that looks like a file that is\nused in the HTML body'''\n p = b'This is not an image'\n a = self.get_attachment(payload=p, length=len(p),\n mimetype='image/jpeg',\n filename=\"foo.jpg\")\n\n with patch.object(self.messageStore, 'add_file') as addFileMock:\n self.messageStore.store_attachment(a)\n addFileMock.assert_called_once_with(a, 'Violence', '')\n\n @patch('gs.group.list.store.messagestore.log')\n @patch('gs.group.list.store.messagestore.FileMetadataStorageQuery')\n @patch('gs.group.list.store.messagestore.EmailMessageStorageQuery')\n def test_full_message(self, EmailMessageStorageQuery,\n FileMetadataStorageQuery, l):\n 'Test the EmailMessageStore.store method with a full email'\n testFile = os.path.join('tests', 'Testing_all_the_things.mbox')\n filename = resource_filename('gs.group.list.store', testFile)\n with codecs.open(filename, encoding='utf-8') as infile:\n parser = Parser()\n m = parser.parse(infile)\n context = MagicMock()\n messageStore = EmailMessageStore(\n context, m, list_title='Ethel the Frog', group_id='ethel')\n\n self.assertEqual(3, messageStore.attachment_count)\n setFileIds = ['a', 'b', 'c']\n with patch.object(messageStore, 'add_file') as addFileMock:\n addFileMock.side_effect = setFileIds\n post_id, fileIds = messageStore.store()\n\n self.assertEqual(messageStore.post_id, post_id)\n self.assertEqual(3, addFileMock.call_count)\n EmailMessageStorageQuery().insert.called_once_with()\n self.assertEqual(3, len(fileIds))\n self.assertEqual(['a', 'b', 'c'], fileIds)\n a, kwargs = FileMetadataStorageQuery().insert_metadata.call_args\n args = a[0]\n self.assertEqual(3, len(args))\n filenames = [d['file_name'] for d in args]\n self.assertIn('gs-logo.svg', filenames)\n self.assertIn('mobile-email-file-link-test.jpg', filenames)\n self.assertIn('gs-14.11-announcement.txt', filenames)\n","repo_name":"groupserver/gs.group.list.store","sub_path":"gs/group/list/store/tests/messagestore.py","file_name":"messagestore.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"39599290552","text":"class Solution:\n def merge(self, intervals):\n intervals = sorted(intervals, key=lambda intervals:intervals[0])\n #print(intervals)\n if len(intervals) < 2:\n return intervals\n minv = intervals[0][0]\n maxv = intervals[0][1]\n vans = []\n for i in intervals[1:]:\n if i[0] >= minv and i[0] <= maxv:\n maxv = max(maxv, i[1])\n #print(\"now max=\" + str(maxv))\n else:\n vans.append([minv,maxv])\n minv = i[0]\n maxv = i[1]\n vans.append([minv,maxv])\n #print(vans)\n return vans\n\n#if __name__ == \"__main__\":\n# sol = Solution()\n# intervals = [[1,2],[3,4],[2,3]]\n# intervals = [[1,3],[2,6],[8,10],[15,18]]\n# intervals = [[1,4],[2,3]]\n# intervals = [[2,3],[4,5],[6,7],[8,9],[1,10]]\n# sol.merge(intervals)","repo_name":"JulianLaiCL/LeetCode","sub_path":"56.py","file_name":"56.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"22900190191","text":"from operator import ge\nfrom flask import Blueprint, render_template, request,session,url_for, redirect, flash\nfrom models.models import *\n\n\nbp = Blueprint('comment', __name__, url_prefix='/comment')\n\n'''\n 설명 : id 값에 맞는 책 정보를 가져온다.\n'''\n@bp.route('/')\ndef home(id):\n \n # id값에 맞는 책의 정보들\n book_info = rabbitBook.query.filter(rabbitBook.id == id).first()\n \n # 평가가 없을수도 있음.\n try:\n # 리스트로 반환됨.\n user_name = []\n comments = rabbitComment.query.filter(rabbitComment.book_id == id).all()\n for comment in comments:\n user_name.append(rabbitUser.query.filter(rabbitUser.id == comment.user_id).first().user_name)\n \n except:\n flash(\"평가가 없습니다.\")\n comments = None\n user_name = None\n\n return render_template(\n 'comment.html', \n book_info = book_info,\n user_name = user_name,\n comments = comments\n )\n\n@bp.route('/submit/',methods=[\"POST\"])\ndef submit(id):\n try:\n comment = request.form['comment']\n rating = request.form['rate']\n user_id = session['user_id']\n\n book_id = id\n\n postComment = rabbitComment(\n user_id= user_id, \n book_id= book_id, \n comment= comment, \n rating = rating\n )\n db.session.add(postComment)\n db.session.commit()\n except:\n flash(\"제출하시려면 평점과 댓글을 모두 작성해 주세요.\")\n\n \n return redirect(url_for('comment.home',id=id))","repo_name":"NohYeongHun/3th_library","sub_path":"views/comment_view.py","file_name":"comment_view.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"73582491483","text":"from db_operations import BotDB\r\nimport datetime\r\nimport requests\r\nimport telegram\r\nimport time\r\nimport logging\r\nimport os\r\nimport pytz\r\n\r\n# Enable logging\r\nlogging.basicConfig(\r\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\r\n level=logging.INFO\r\n)\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\nCHECK_MINTS = int(os.environ.get(\"CHECK_DELAY\", 1))\r\n\r\n\r\nclass Poller:\r\n def __init__(self, num_days=1, wait=15):\r\n self.db = BotDB()\r\n self.NUM_DAYS = num_days\r\n self.wait = wait\r\n self.bot = telegram.Bot(token=os.environ.get(\"BOT_TOKEN\"))\r\n self.ROLL_OVER_TIME = int(os.environ.get(\"ROLL_OVER_TIME\", 18))\r\n\r\n self.API_URL = \"https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id={\" \\\r\n \"0}&date={1} \"\r\n\r\n def __iter_chat_ids(self):\r\n data = self.db.get_all_data()\r\n for item in data:\r\n yield item[\"chat_id\"], item[\"district_id\"], item[\"district_name\"], item[\"age\"]\r\n\r\n @staticmethod\r\n def __parse_response(data, age):\r\n\r\n d_parsed_data = {}\r\n\r\n if len(data[\"sessions\"]) == 0:\r\n return {}\r\n\r\n for session in data[\"sessions\"]:\r\n\r\n if age >= int(session[\"min_age_limit\"]):\r\n d_parsed_data[session[\"name\"]] = {\r\n \"capacity\": session[\"available_capacity\"],\r\n \"fee\": session[\"fee\"],\r\n \"vaccine\": session[\"vaccine\"],\r\n \"slots\": \" \".join(session[\"slots\"])\r\n }\r\n return d_parsed_data\r\n\r\n def __extract_info(self, district, age):\r\n\r\n time_zone = pytz.timezone(\"Asia/Calcutta\")\r\n base = datetime.datetime.now(time_zone)\r\n if base.hour >= self.ROLL_OVER_TIME:\r\n logger.info(f\"Time is now past {self.ROLL_OVER_TIME} hours. Will check slots for next day\")\r\n base += datetime.timedelta(days=1)\r\n \r\n logger.info(f\"Date is {base}\")\r\n \r\n l_next_NUM_DAYS_days = \\\r\n [base + datetime.timedelta(days=x) for x in range(self.NUM_DAYS)]\r\n\r\n d_details = {}\r\n for date in l_next_NUM_DAYS_days:\r\n s_date = date.strftime(\"%d-%m-%Y\")\r\n url = self.API_URL.format(district, s_date)\r\n header = {\"accept\": \"application/json\", \"Accept-Language\": \"hi_IN\",\r\n \"user-agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \"\r\n \"Chrome/90.0.4430.93 Safari/537.36\"}\r\n response = requests.get(url, headers=header)\r\n if response.ok:\r\n data = response.json()\r\n d_details[date.strftime(\"%d-%B-%Y\")] = self.__parse_response(data, age)\r\n\r\n return d_details\r\n\r\n def __build_message(self, district, details, force=False):\r\n\r\n msg_yes = f\"You have a vaccine slot now available at {district} district.!!!\\nSee Details below.\\n\"\r\n msg_no = f\"You don't have a vaccine slot now available at {district} district.!!!\\n\\n\"\r\n \r\n if not force:\r\n msg_no += \"I will check again in {self.wait} minutes\\n\"\r\n\r\n available = False\r\n for date, data in details.items():\r\n if len(data) != 0:\r\n available = True\r\n msg_yes += f\"\\nDate : {date}\\n\\n\"\r\n for location, info in data.items():\r\n txt = f'Location : {location}\\nCapacity : {info[\"capacity\"]}\\nVaccine : {info[\"vaccine\"]}\\n' \\\r\n f'Fee : {info[\"fee\"]}\\nSlots : {info[\"slots\"]}\\n\\n'\r\n msg_yes += txt\r\n\r\n if not available:\r\n return False, msg_no\r\n\r\n return True, msg_yes\r\n\r\n def send(self, msg, chat_id):\r\n \"\"\"\r\n Send a message to a telegram user specified on chatId\r\n chat_id must be a number!\r\n \"\"\"\r\n self.bot.sendMessage(chat_id=chat_id, text=msg)\r\n \r\n def _send_notification(self, msg, chat_id):\r\n \r\n l_msg = [msg[i:i + 4000] for i in range(0, len(msg), 4000)]\r\n for m in l_msg:\r\n self.send(m, chat_id)\r\n \r\n \r\n def notify_one_user(self, district, age, district_name, chat_id,\r\n force=False):\r\n \r\n details = self.__extract_info(district, age)\r\n flag, msg = self.__build_message(district_name, details, force=force)\r\n \r\n if force:\r\n logger.info(f\"Notication will be send forcefully to {chat_id} at this time\")\r\n self._send_notification(msg, chat_id)\r\n return\r\n \r\n if os.environ.get(\"RUN_ENV\", \"DEV\") == \"DEV\":\r\n logger.info(f\"Notification will be send to {chat_id} at this time\")\r\n self._send_notification(msg, chat_id)\r\n if os.environ.get(\"RUN_ENV\", \"DEV\") == \"PROD\":\r\n if flag:\r\n logger.info(f\"Notification will be send to {chat_id} at this time\")\r\n self._send_notification(msg, chat_id)\r\n else:\r\n logger.info(f\"Notification will not be send to {chat_id} at this time\")\r\n \r\n def check_in_cowin(self):\r\n \r\n _iter = self.__iter_chat_ids()\r\n\r\n for chat_id, district, district_name, age in _iter:\r\n self.notify_one_user(district, age, district_name, chat_id)\r\n \r\n\r\ndef do_polling():\r\n poller = Poller(num_days=1, wait=CHECK_MINTS)\r\n while True:\r\n logger.info(\"Wokeup.!\")\r\n poller.check_in_cowin()\r\n logger.info(\"Going to sleep.!\")\r\n time.sleep(CHECK_MINTS * 60)\r\n \r\nif __name__ == \"__main__\":\r\n do_polling()","repo_name":"sreeram004/india-covid-vaccine-slots-telegram-bot","sub_path":"src/poller.py","file_name":"poller.py","file_ext":"py","file_size_in_byte":5725,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"24794017379","text":"import re\n\ndef get_md_file_content (md_file: str) -> list:\n \"\"\"\n Возвращает содержимое .md файла в виде списка строк.\n Пустые строки и пробелы с конца строк удаляются.\n \"\"\"\n with open(f'{md_file}','r', encoding=\"utf-8\") as md_file:\n md = [x.rstrip() for x in md_file]\n md_strip = [x for x in md if x != '']\n return md_strip\n\ndef md_to_yaml(file_content: list) -> list:\n \"\"\" Парсит .md файл и собирает список dict-ов, где каждый раздел (по уровню заголовка) - свой dict внутри списка, а текстовые строки содержатся списком в элементе content соответствующего раздела \"\"\"\n parsed_md = list()\n rownum = 0\n level_index = 1\n\n while rownum < len(file_content):\n\n # ищем заголовки\n match = re.search('(#+)(.*)', file_content[rownum])\n if match:\n level = len(match.group(1))\n section_key = f'H{level}_{level_index}'\n section_label = match.group(2).strip()\n\n rownum += 1\n start_rownum = rownum\n\n below = file_content [start_rownum:]\n\n for x in range(len(below)):\n\n # ищем диапазон строк с содержимым секции\n match_below = re.search('(#+)(.*)', below[x])\n if match_below:\n level_below = len(match_below.group(1).strip())\n if level_below <= level:\n break\n else:\n rownum += 1\n else:\n rownum += 1\n end_rownum = rownum\n # нашли номер строки, где заканчивается секция (либо дошли до конца)\n\n section_content = md_to_yaml (file_content[start_rownum:end_rownum])\n parsed_md.append ({section_key: {'label': section_label, 'content': section_content}})\n level_index += 1\n\n else:\n parsed_md.append (file_content[rownum])\n rownum += 1\n\n return parsed_md\n","repo_name":"medotkato/storybuilder","sub_path":"storybuilder/utils/md_handler.py","file_name":"md_handler.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"17694816973","text":"\"\"\"\nCP1404/CP5632 Practical\nStarter code for cumulative total income program\n\"\"\"\n\n\ndef print_report(month, months_int, incomes):\n total = 0\n print()\n print(\"Income Report\")\n print(\"-------------\")\n for month in range(1, months_int + 1):\n income = incomes[month - 1]\n total += income\n print(\"Month {:2} - Income: ${:10.2f} Total: ${:10.2f}\".format(month, income, total))\n\ndef main():\n \"\"\"Display income report for incomes over a given number of months.\"\"\"\n incomes = []\n months_int = int(input(\"How many months? \"))\n\n for month in range(1, months_int + 1):\n income = float(input('{} {} {}'.format(\"Enter income for month \", str(month), \": \")))\n incomes.append(income)\n print_report(month, months_int, incomes)\n\nmain()\n","repo_name":"GeoffreyDavidReid/CP1404","sub_path":"prac_04/total_income.py","file_name":"total_income.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"34996654761","text":"from collections import defaultdict\nimport random\nfrom typing import List, Set, Tuple\nfrom consts import *\nfrom pyswip import Prolog\n\n\ndef getSymbol(val, symbol, default_to='.'):\n return symbol if val else default_to\n\n\ndef getDir(dirIdx: int):\n direction = DIR_MAP[dirIdx]\n dir = []\n # think in terms of X, Y\n # not i, j\n if direction == RNORTH:\n dir = [0, 1]\n elif direction == RSOUTH:\n dir = [0, -1]\n elif direction == REAST:\n dir = [1, 0]\n else:\n dir = [-1, 0]\n\n return dir\n\n# for formatting output purposes\nclass Cell:\n \"\"\"\n 9 information for a cell\n \"\"\"\n\n # for symbol 5\n translate = {\n WUMPUS: 'W',\n CONFUNDUS_PORTAL: 'O',\n WUMPUS_AND_CONFUNDUS: 'U',\n RNORTH: '^',\n RSOUTH: 'V',\n REAST: '>',\n RWEST: '<',\n NOT_VISITED_SAFE: 's',\n VISITED_SAFE: 'S',\n UNKNOWN: '?',\n }\n\n is_wall = False\n confounded = False\n stench = False\n tingle = False\n isOccupied = False\n agentKnowledge = None # the agent's deduction on this cell\n coinIsOn = False\n bump = False\n scream = False\n\n def __init__(self, cell_info=[False, False, False, False, UNKNOWN, False, False, False, False], is_wall=False):\n self.confounded = cell_info[0]\n self.stench = cell_info[1]\n self.tingle = cell_info[2]\n self.isOccupied = cell_info[3]\n self.agentKnowledge = cell_info[4]\n self.isOccupied = cell_info[5]\n self.coinIsOn = cell_info[6]\n self.bump = cell_info[7]\n self.scream = cell_info[8]\n\n self.is_wall = is_wall\n\n def format_print_string(self) -> List[str]:\n if self.is_wall:\n return ['###', '###', '###']\n\n return [f\"{getSymbol(self.confounded, '%')}{getSymbol(self.stench, '=')}{getSymbol(self.tingle, 'T')}\", f\"{getSymbol(self.isOccupied, '-', ' ')}{getSymbol(True, self.translate[self.agentKnowledge])}{getSymbol(self.isOccupied, '-', ' ')}\", f\"{getSymbol(self.coinIsOn, '*')}{getSymbol(self.bump, 'B')}{getSymbol(self.scream, '@')}\"]\n\n def format_sensory_list(self):\n return [self.confounded, self.stench, self.tingle, self.coinIsOn, self.bump, self.scream]\n\nclass Sensory:\n \"\"\"\n Percepts: Prior to any movement, the Agent receives an vector of sensory indicators: Confounded, Stench,\n Tingle, Glitter, Bump, Scream. All indicators are Off, except in the following situations:\n • Confounded indicator is On at the start of the game and after the Agent stepped into a cell with a Confundus\n Portal.\n • Stench indicator is On in the cell next to one inhabited by the Wumpus.\n • Tingle indicator is On in the cell next to one inhabited by a Confundus Portal.\n • Glitter is On in the cell inhabited by a Coin.\n • Bump is On if the Agent attempted an action Forward and the next cell in that direction contained a Wall.\n • Scream indicator is On after the Agent shot an arrow and the Wumpus was in the direction of the shot.\n Notice that the agent does not perceive its exact location on the grid\n \"\"\"\n confounded = False\n stench = False\n tingle = False\n glitter = False\n bump = False\n scream = False\n\n translate = {\n 0: 'Confounded',\n 1: 'Stench',\n 2: 'Tingle',\n 3: 'Glitter',\n 4: 'Bump',\n 5: 'Scream'\n }\n\n def __init__(self, inputs):\n self.confounded, self.stench, self.tingle, self.glitter, self.bump, self.scream = inputs\n\n def as_bool_list(self):\n inputs = [self.confounded, self.stench, self.tingle, self.glitter, self.bump, self.scream]\n return inputs\n \n def as_display_list(self):\n return '-'.join([self.translate[idx] if on else self.translate[idx][0] for idx, on in enumerate(self.as_bool_list())])\n\n def as_str_list(self):\n \"\"\"\n returns self as [on, on, off, etc...]\n \"\"\"\n inputs = self.as_bool_list()\n a = ['on' if i else 'off' for i in inputs]\n return f\"[{','.join(a)}]\"\n\n\n# the driver class\nclass Driver:\n\n abs_map = None\n agent_position = None\n agent_direction_string = None\n prolog = None\n has_arrow = True\n death_count = None\n wumpus_killed = False\n\n def __init__(self, abs_map: defaultdict(dict), agent_origin, agent_direction_string, prolog: Prolog, coins: List[Tuple[int]], f) -> None:\n \"\"\"\n abs_map: the absolute map in [X][Y] notation, populated with the npcs\n agent_origin: the initial position where the agent spawns\n agent_direction_string: the relative direciton where agent is initially facing, relative to the absolute map,\n prolog: the prolog device\n coins: the initial coins position (in abs XY terms)\n f: the file to write logs to \n this relative string while appears to be the same as prolog agent, is relative to 2 different things\n thus, relative north in prolog might refer to relative south in absolute terms\n \"\"\"\n self.abs_map = abs_map # note we use [X][Y] notation\n self.spawn_point = agent_origin\n self.agent_position = agent_origin\n self.agent_direction_string = agent_direction_string\n self.prolog = prolog\n\n self.has_arrow = True\n\n # track initial coins positions for resetting\n self.total_coins = len(coins)\n self.coins_collected = 0\n self.coins_positions = coins\n self.death_count = 0\n self.wumpus_killed = False\n \n self.f = f\n\n def build_abs_map(self, display_confounded=False):\n res = defaultdict(dict)\n x_keys = list(self.abs_map.keys())\n for X in x_keys:\n y_keys = list(self.abs_map[X].keys())\n for Y in y_keys:\n value = self.abs_map[X].get(Y)\n \n cell = Cell()\n \n # populate indicators that are dependent on the surrounding, any thing of interest\n sur = self.check_surrounding(X, Y)\n\n # Stench indicator is On in the cell next to one inhabited by the Wumpus.\n if WUMPUS in sur:\n cell.stench = True\n\n # Tingle indicator is On in the cell next to one inhabited by a Confundus Portal.\n if CONFUNDUS_PORTAL in sur:\n cell.tingle = True\n\n # anything other than empty or wall is an npc\n if (self.agent_position[0] == X and self.agent_position[1] == Y) or (value != EMPTY and value != WALL):\n cell.isOccupied = True\n \n # the abs map has perfect driver knowledge to use for symbol 5\n if value == WUMPUS:\n cell.agentKnowledge = WUMPUS\n elif value == CONFUNDUS_PORTAL:\n cell.agentKnowledge = CONFUNDUS_PORTAL\n elif self.agent_position[0] == X and self.agent_position[1] == Y:\n cell.agentKnowledge = self.agent_direction_string\n # Confounded indicator is On at the start of the game and after the Agent stepped into a cell with a Confundus Portal.\n if display_confounded: \n cell.confounded = True\n elif value != WALL:\n cell.agentKnowledge = NOT_VISITED_SAFE\n \n # symbol 7, note we skip 6, it is the same as 4\n if value == COIN:\n cell.coinIsOn = True\n\n # ignore symbol 8 and 9 for absolute map, no transitory flags for initial absolute map\n\n # build the cell corresponding to this coord of X, Y in the abs map\n if value == WALL:\n cell.is_wall = True\n\n res[X][Y] = cell\n\n return res\n\n def check_surrounding(self, X, Y) -> Set[str]:\n \"\"\"\n Returns things of interest in the 4 directions where applicable\n Can be walls, coins, wumpus, portals. Does not return the exact count,\n it simply returns a set of distinct npcs' names.\n \"\"\"\n dirs = [[0, 1], [1, 0],[-1, 0], [0, -1]]\n res = set()\n for dir in dirs:\n val = self.abs_map[X+dir[0]].get(Y+dir[1])\n if val and val != WALL and val != EMPTY:\n res.add(val)\n \n return res\n\n def _get_current_sensory(self) -> Sensory:\n \"\"\"\n Gets the current sensory indicators based on where the agent currently is located on the abs map.\n This is a passive check, no actions are assumed to be taken, thus bump and scream will be False by default.\n \"\"\"\n confounded = False\n stench = False\n tingle = False\n glitter = False\n bump = False\n scream = False\n\n curX, curY = self.agent_position\n sur = self.check_surrounding(curX, curY)\n val = self.abs_map[curX][curY]\n if val == CONFUNDUS_PORTAL:\n confounded = True\n if WUMPUS in sur:\n stench = True\n if CONFUNDUS_PORTAL in sur:\n tingle = True\n if val == COIN:\n glitter = True\n \n return Sensory([confounded, stench, tingle, glitter, bump, scream])\n\n def _get_cell_infront(self):\n curX, curY = self.agent_position\n if self.agent_direction_string == RNORTH:\n return self.abs_map[curX][curY+1]\n elif self.agent_direction_string == RSOUTH:\n return self.abs_map[curX][curY-1]\n elif self.agent_direction_string == REAST:\n return self.abs_map[curX+1][curY]\n elif self.agent_direction_string == RWEST:\n return self.abs_map[curX-1][curY]\n \n # should never run\n print('illegal direction:', self.agent_position)\n return None \n\n def do_reborn(self):\n self.f.write('agent is reborning...\\n')\n # make sure the abs_map returns back to its original state\n self.agent_position = self.spawn_point\n for coin_xy in self.coins_positions:\n x, y = coin_xy\n self.abs_map[x][y] = COIN\n self.coins_collected = 0\n self.death_count += 1\n \n # tell prolog agent to reborn also\n list(self.prolog.query('reborn'))\n\n def _is_safe_cell(self, X, Y) -> bool:\n val = self.abs_map[X][Y]\n return val == EMPTY or val == COIN\n\n def get_random_safe_pos(self):\n while True:\n randomX = random.choice(list(self.abs_map.keys()))\n ys = list(self.abs_map[randomX].keys())\n if ys:\n randomY = random.choice(ys)\n if self._is_safe_cell(randomX, randomY):\n return [randomX, randomY]\n \n def do_reposition(self):\n self.f.write('agent is repositioning...\\n')\n self.agent_position = self.get_random_safe_pos()\n sensory = self._get_current_sensory()\n sensory.confounded = True\n\n # tell prolog agent to reposition and feed in new random spot's sensory\n list(self.prolog.query(f'reposition({sensory.as_str_list()})'))\n\n def do_move_forward(self):\n # this step is assured to be safe, no walls, wumpus or portals, just move forward\n if self.agent_direction_string == RNORTH:\n self.agent_position[1] += 1\n elif self.agent_direction_string == RSOUTH:\n self.agent_position[1] -= 1\n elif self.agent_direction_string == REAST:\n self.agent_position[0] += 1\n elif self.agent_direction_string == RWEST:\n self.agent_position[0] -= 1\n\n def do_turn_left(self):\n if self.agent_direction_string == RNORTH:\n self.agent_direction_string = RWEST\n elif self.agent_direction_string == RSOUTH:\n self.agent_direction_string = REAST\n elif self.agent_direction_string == REAST:\n self.agent_direction_string = RNORTH\n elif self.agent_direction_string == RWEST:\n self.agent_direction_string = RSOUTH\n \n def do_turn_right(self):\n if self.agent_direction_string == RNORTH:\n self.agent_direction_string = REAST\n elif self.agent_direction_string == RSOUTH:\n self.agent_direction_string = RWEST\n elif self.agent_direction_string == REAST:\n self.agent_direction_string = RSOUTH\n elif self.agent_direction_string == RWEST:\n self.agent_direction_string = RNORTH\n\n def do_pickup(self) -> bool:\n \"\"\"\n attempts to pick up a coin, returns if agent is successfull\n i.e. if there is a coin\n \"\"\"\n curX, curY = self.agent_position\n val = self.abs_map[curX][curY]\n if val == COIN:\n self.abs_map[curX][curY] = EMPTY\n return True\n \n return False\n\n def do_shoot(self) -> bool:\n \"\"\"\n attempts to shoot in the direction of the agent\n shot goes through all obstacles\n reports if the wumpus is killed,\n i.e. if the wumpus lies in the path of the shot\n \"\"\"\n xOffset, yOffset = [-1,-1]\n if self.agent_direction_string == RNORTH:\n xOffset, yOffset = [0, 1]\n elif self.agent_direction_string == RSOUTH:\n xOffset, yOffset = [0, -1]\n elif self.agent_direction_string == REAST:\n xOffset, yOffset = [1, 0]\n elif self.agent_direction_string == RWEST:\n xOffset, yOffset = [-1, 0]\n \n curX, curY = self.agent_position\n while curX in self.abs_map and curY in self.abs_map[curX]:\n val = self.abs_map[curX][curY]\n if val == WUMPUS:\n self.abs_map[curX][curY] = EMPTY\n return True\n \n curX += xOffset\n curY += yOffset\n \n return False\n \n\n def do_action(self, action) -> Sensory:\n \"\"\"\n The driver will determine the agent's sensory indicators from the agent's position and intended action\n \n action: the action the agent has chosen\n \"\"\"\n current_sensory = self._get_current_sensory()\n\n if action == MOVE_FORWARD:\n cell_in_front = self._get_cell_infront()\n if cell_in_front == WALL:\n current_sensory.bump = True\n return current_sensory\n elif cell_in_front == WUMPUS:\n # agent stepped into wumpus\n self.f.write('agent stepped into wumpus\\n')\n self.do_reborn()\n return self._get_current_sensory()\n elif cell_in_front == CONFUNDUS_PORTAL:\n self.f.write('agent stepped into portal\\n')\n self.do_reposition()\n sensory = self._get_current_sensory()\n sensory.confounded = True\n return sensory\n \n # can move forward with no weird interactions\n self.do_move_forward()\n\n return self._get_current_sensory()\n\n elif action == TURN_LEFT or action == TURN_RIGHT:\n if action == TURN_LEFT:\n self.do_turn_left()\n else:\n self.do_turn_right()\n\n return current_sensory # no need to retake sensory test\n \n elif action == PICKUP:\n success = self.do_pickup()\n if success:\n self.f.write('agent picked up a coin!\\n')\n self.coins_collected += 1\n if self.coins_collected == self.total_coins:\n self.f.write('agent collected all the coins possible!\\n')\n else:\n self.f.write('agent picked up nothing\\n')\n\n return self._get_current_sensory()\n \n elif action == SHOOT:\n success = False\n if self.has_arrow:\n success = self.do_shoot()\n if success:\n self.f.write('agent shot the wumpus!\\n')\n self.wumpus_killed = True\n else:\n self.f.write('agent shot but missed\\n')\n else:\n self.f.write('agent wants to shoot but has no arrow, ignoring...\\n')\n\n new_sensory = self._get_current_sensory()\n new_sensory.scream = success # indicate scream if applicable\n return new_sensory\n\n else:\n print('illegal action, not recognised:', action)\n return current_sensory\n\n\ndef build_relative_map(prolog: Prolog, confounded, bump, scream):\n \"\"\"\n Some indicators are not remembered by the agent but should be displayed when they are passed as \n sensory inputs such as confounded, bump and scream\n \"\"\"\n res = defaultdict(dict)\n \n # first mark all sensory inputs that are passed in\n # agent doesnt actually remember them but we need to display\n # nonetheless\n agent_current = list(prolog.query('current(X,Y,D)'))\n cur = agent_current[0]\n\n X, Y, D = cur['X'], cur['Y'], cur['D']\n res[X][Y] = Cell()\n # agent's current cell is always special\n # symbol 1, 8, 9\n res[X][Y].confounded = confounded\n res[X][Y].bump = bump\n res[X][Y].scream = scream\n res[X][Y].agentKnowledge = D\n res[X][Y].isOccupied = True\n\n # walls\n wallsXY = list(prolog.query('wall(X,Y)'))\n for xy in wallsXY:\n x, y = xy['X'], xy['Y']\n cell = res[x].get(y)\n if not cell:\n cell = Cell()\n cell.is_wall = True\n res[x][y] = cell\n\n # symbol 2 - stench\n stenchsXY = list(prolog.query('stench(X,Y)'))\n for xy in stenchsXY:\n x, y = xy['X'], xy['Y']\n cell = res[x].get(y)\n if not cell:\n cell = Cell()\n cell.stench = True\n res[x][y] = cell\n \n # symbol 3 - tingle\n tinglesXY = list(prolog.query('tingle(X,Y)'))\n for xy in tinglesXY:\n x, y = xy['X'], xy['Y']\n cell = res[x].get(y)\n if not cell:\n cell = Cell()\n cell.tingle = True\n res[x][y] = cell\n\n # symbol 4 and 6 (isOccupied) are handled among others, agent, wumpus, coins, portals\n\n # symbol 5 - agent knowledge/inference\n wumpusXY = list(prolog.query('wumpus(X,Y)'))\n for xy in wumpusXY:\n x, y = xy['X'], xy['Y']\n cell = res[x].get(y)\n if not cell:\n cell = Cell()\n cell.agentKnowledge = WUMPUS\n cell.isOccupied = True\n res[x][y] = cell\n\n confundusXY = list(prolog.query('confundus(X,Y)'))\n for xy in confundusXY:\n x, y = xy['X'], xy['Y']\n cell = res[x].get(y)\n if not cell:\n cell = Cell()\n if cell.agentKnowledge == WUMPUS:\n cell.agentKnowledge = WUMPUS_AND_CONFUNDUS\n else:\n cell.agentKnowledge = CONFUNDUS_PORTAL\n cell.isOccupied = True\n res[x][y] = cell\n \n safesXY = list(prolog.query('safe(X,Y)'))\n visitedsXY = list(prolog.query('visited(X,Y)'))\n\n for xy in safesXY:\n x, y = xy['X'], xy['Y']\n if x == X and y == Y:\n continue # without the Agent inhabiting it\n cell = res[x].get(y)\n if not cell:\n cell = Cell()\n # check if visited\n visited = False\n for xy2 in visitedsXY:\n x2, y2 = xy2['X'], xy2['Y']\n if x2 == x and y2 == y:\n visited = True\n break\n \n if visited:\n cell.agentKnowledge = VISITED_SAFE\n else:\n cell.agentKnowledge = NOT_VISITED_SAFE\n res[x][y] = cell\n \n # symbol 7\n glittersXY = list(prolog.query('glitter(X,Y)'))\n for xy in glittersXY:\n x, y = xy['X'], xy['Y']\n cell = res[x].get(y)\n if not cell:\n cell = Cell()\n cell.coinIsOn = True\n cell.isOccupied = True\n res[x][y] = cell\n\n return res","repo_name":"geraldywy/cz3005_lab2","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":19976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"36270708763","text":"# -*- coding: utf-8 -*-\n\"\"\"\nClass to estimate values for the model parameters using the simulation output resulting from Launcher.py and the\nacceptability region as bounded by BoundaryImposer.py.\n\n@author: Adrian Carro\n\"\"\"\n\nimport numpy as np\nfrom scipy.fftpack import fft\nimport platform\nfrom pathlib import Path\nimport os\nimport re\nimport pandas as pd\nimport glob\nimport time\n\n\ndef get_simulation_moments(_simulation_output_file, _n_skip):\n # Read results into pandas data frame, skipping first n_skip lines after the header\n _results = pd.read_csv(_simulation_output_file, delimiter=\";\", skipinitialspace=True,\n skiprows=range(1, _n_skip + 1), usecols={\"nRenting\", \"nOwnerOccupier\", \"Sale nSales\",\n \"nActiveBTL\"})\n return np.vstack((np.array([_results.mean()]).T, np.array([_results.std()]).T))\n\n\ndef get_all_simulation_moments(_simulation_output_folder, _n_skip):\n # First, read results from core indicator files and temporarily store them in lists\n rental_yield_mean = []\n with open(_simulation_output_folder + \"/coreIndicator-rentalYield.csv\") as _f:\n for _line in _f:\n rental_yield_mean.append(np.mean([float(element) for element in _line.split(\";\")[_n_skip + 1:]]))\n spread_mean = []\n with open(_simulation_output_folder + \"/coreIndicator-interestRateSpread.csv\") as _f:\n for _line in _f:\n spread_mean.append(np.mean([float(element) for element in _line.split(\";\")[_n_skip + 1:]]))\n \n # Then, read results from general output files and create a list of vectors of moments\n _all_simulation_moments = []\n for k, _simulation_output_file in enumerate(glob.glob(\"{}/Output-run*.csv\".format(_simulation_output_folder))):\n _results = pd.read_csv(_simulation_output_file, delimiter=\";\", skipinitialspace=True,\n skiprows=range(1, _n_skip + 1), usecols={\"nRenting\", \"nOwnerOccupier\", \"nActiveBTL\",\n \"TotalPopulation\", \"Sale HPI\", \"Rental HPI\"})\n _results[\"fHomeOwner\"] = (_results[\"nOwnerOccupier\"] + _results[\"nActiveBTL\"]) / _results[\"TotalPopulation\"]\n _results[\"fRenting\"] = _results[\"nRenting\"] / _results[\"TotalPopulation\"]\n _results[\"fActiveBTL\"] = _results[\"nActiveBTL\"] / _results[\"TotalPopulation\"]\n _all_simulation_moments.append(np.vstack([_results[\"Sale HPI\"].mean(), _results[\"Sale HPI\"].std(),\n get_period(_results[\"Sale HPI\"]), _results[\"Rental HPI\"].mean(),\n _results[\"fHomeOwner\"].mean(), _results[\"fRenting\"].mean(),\n _results[\"fActiveBTL\"].mean(),\n rental_yield_mean[k], spread_mean[k]]))\n return _all_simulation_moments\n\n\ndef get_period(_time_series):\n n = len(_time_series) # Number of sample points\n fast_fourier_transform_hpi = (1.0 / n) * np.abs(fft(_time_series)[1:int(n / 2)])\n frequency_domain = np.linspace(0.0, 1.0, n)[1:int(n / 2)] # This assumes sample spacing of 1\n return 1 / frequency_domain[fast_fourier_transform_hpi.argmax()]\n\n\nif __name__ == \"__main__\":\n # Control parameters\n parameters = [\"MARKET_AVERAGE_PRICE_DECAY\", \"BTL_PROBABILITY_MULTIPLIER\", \"BTL_CHOICE_INTENSITY\",\n \"PSYCHOLOGICAL_COST_OF_RENTING\", \"SENSITIVITY_RENT_OR_PURCHASE\"]\n experimentName = \"Output-Calibration-2020-11-17\"\n n_skip = 500 # Number of initial time steps to skip as burnout period\n # Target moments\n HPI_MEAN = 1.0\n HPI_STD = 0.3424\n HPI_PERIOD = 201.0\n RPI_MEAN = 1.0\n SHARE_HOUSEHOLDS_OWNING = 0.65\n SHARE_HOUSEHOLDS_RENTING = 0.17\n SHARE_HOUSEHOLDS_ACTIVE_BTL = 0.07526\n RENTAL_YIELD_MEAN = 5.10\n RESIDENTIAL_MORTGAGES_SPREAD_MEAN = 2.9985\n\n # Addresses (ADD HERE CORRECT PATHS)\n if platform.system() == \"Windows\":\n generalRoot = \"\"\n maxColWidth = -1\n else:\n generalRoot = \"\"\n maxColWidth = None\n rootExperiment = r\"{}/results/{}\".format(generalRoot, experimentName)\n \n # Read list of process numbers with acceptable moments (within boundaries imposed by BoundaryImposer)\n acceptableProcessNumbers = []\n with open(\"AcceptableProcessNumbersRelaxed.csv\", \"r\") as f:\n for line in f:\n acceptableProcessNumbers.append(line.strip(\"\\n\"))\n\n # Create sorted list of files to read\n sortedFolders = sorted([f.path for f in os.scandir(Path(\"{}/Results/\".format(rootExperiment)))\n if f.is_dir() and f.name.strip(\"Process\") in acceptableProcessNumbers])\n\n # Create vector of data moments from inputs given\n data_moments = np.array([[HPI_MEAN, HPI_STD, HPI_PERIOD, RPI_MEAN, SHARE_HOUSEHOLDS_OWNING,\n SHARE_HOUSEHOLDS_RENTING, SHARE_HOUSEHOLDS_ACTIVE_BTL,\n RENTAL_YIELD_MEAN, RESIDENTIAL_MORTGAGES_SPREAD_MEAN]]).T\n nMoments = len(data_moments)\n\n # Define the weighting matrix for the different moment errors\n w_hat = np.eye(nMoments)\n w_hat[0][0] = 5 # HPI_MEAN\n w_hat[1][1] = 5 # HPI_STD\n w_hat[2][2] = 5 # HPI_PERIOD\n w_hat[3][3] = 1 # RPI_MEAN\n w_hat[4][4] = 1 # SHARE_HOUSEHOLDS_OWNING\n w_hat[5][5] = 2 # SHARE_HOUSEHOLDS_RENTING\n w_hat[6][6] = 2 # SHARE_ACTIVE_BTL\n w_hat[7][7] = 5 # RENTAL_YIELD_MEAN\n w_hat[8][8] = 1 # RESIDENTIAL_MORTGAGES_SPREAD_MEAN\n\n # Run through results folder for each process\n t0 = time.time()\n criterionListDict = []\n nSimulations = None\n rex = re.compile(r\"\\d+$\")\n i = 0\n for processFolder in sortedFolders[0:]:\n i += 1\n if i % 10 == 0:\n print(i, time.time() - t0)\n # t0 = time.time()\n # if i == 50:\n # break\n # Find process number\n if rex.search(processFolder):\n processNumber = rex.search(processFolder).group(0)\n else:\n print(\"Unable to find process number for folder {}\".format(processFolder))\n processNumber = None\n exit()\n # Find process parameter values\n parameterValues = dict()\n with open(\"{}/config{}.properties\".format(processFolder, processNumber), \"r\") as f:\n for line in f:\n if len(line.split()) > 0 and line.split()[0] in parameters:\n parameterValues[line.split()[0]] = float(line.split()[2])\n \n # For each simulation within this process, and thus with these parameter values, read results and\n # the compute corresponding simulation moments vector\n all_simulation_moments = get_all_simulation_moments(processFolder, n_skip)\n nSimulations = len(all_simulation_moments)\n\n # Compute the error matrix, where each (r, s) element is the contribution of the sth simulated moment to the rth\n # moment error...\n error_matrix = ((np.column_stack(all_simulation_moments) - np.ones((nMoments, nSimulations)) * data_moments) /\n (np.ones((nMoments, nSimulations)) * data_moments))\n # ...the corresponding error vector\n error_vector = (1 / nSimulations) * error_matrix @ np.ones((nSimulations, 1))\n # ...and the corresponding criterion value (weighted sum of squared moment errors)\n criterion_value = error_vector.T @ w_hat @ error_vector\n \n # Finally, add this criterion value, as well as the moments and their errors, to the parameter values\n # dictionary and append it to the list of dicts\n parameterValues[\"Criterion Value\"] = criterion_value[0][0]\n for j, name in enumerate([\"HPI_MEAN\", \"HPI_STD\", \"HPI_PERIOD\", \"RPI_MEAN\", \"SHARE_HOUSEHOLDS_OWNING\",\n \"SHARE_HOUSEHOLDS_RENTING\", \"SHARE_HOUSEHOLDS_ACTIVE_BTL\",\n \"RENTAL_YIELD_MEAN\", \"RESIDENTIAL_MORTGAGES_SPREAD_MEAN\"]):\n parameterValues[name] = np.mean(all_simulation_moments, axis=0)[j][0]\n parameterValues[\"Error \" + name] = error_vector[j][0]\n criterionListDict.append(parameterValues)\n\n # Create a DataFrame from the criterion list of dicts\n criterionDF = pd.DataFrame(criterionListDict, columns=criterionListDict[0].keys())\n\n # Select and print minimum criterion value row\n min_row = criterionDF.loc[criterionDF[\"Criterion Value\"].idxmin(axis=0)]\n print(\"Minimum Criterion Value ({:.6f}) reached for \".format(min_row[\"Criterion Value\"])\n + \", \".join([\"{} = {}\".format(min_row.index[i], min_row[min_row.index[i]]) for i in range(5)]))\n\n # Write to file criterionDF\n criterionDF.to_csv(\".\\CriterionDF13.csv\", index=False, sep=\";\")\n","repo_name":"adrian-carro/housing-model-spain","sub_path":"src/main/resources/output-calibration/BoundedCalibrator.py","file_name":"BoundedCalibrator.py","file_ext":"py","file_size_in_byte":8792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"86"} +{"seq_id":"5119825499","text":"\r\n# Detlev Aschhoff info@vmais.de\r\n# The MIT License (MIT)\r\n#\r\n# Copyright (c) 2020\r\n#\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is\r\n# furnished to do so, subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be included in\r\n# all copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n# THE SOFTWARE.\r\n\r\n\r\nimport time\r\nimport serial\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nimport tkinter.scrolledtext as tkst\r\nimport tkinter.filedialog\r\nfrom tkinter.messagebox import *\r\n\r\nroot=Tk()\r\nroot.title(\"ESP config.py Editor\")\r\nerr=\"\"\r\ndef serialOn():\r\n global ser\r\n for port in range(3,9):\r\n comport=\"COM\"+str(port)+\":\"\r\n try:\r\n ser = serial.Serial(port=comport,baudrate=115200)\r\n serialopen=True\r\n except Exception as e:\r\n serialopen=False \r\n if serialopen == True:\r\n ESPsend(chr(3))\r\n time.sleep(1)\r\n ESPsend(chr(3))\r\n time.sleep(1) \r\n if ser.inWaiting() != 0:\r\n a=ser.read()\r\n print(a)\r\n return (comport)\r\n else:\r\n serialopen=False\r\n return (\"Error\") \r\n \r\n \r\ndef ESPsend(out):\r\n out+=\"\\r\\n\"\r\n out=out.encode(\"utf-8\")\r\n ser.write(out)\r\n time.sleep(0.05) # sonst verschluckt sich der ESP\r\n \r\ndef ESPsave(filename,t):\r\n ser.reset_input_buffer() # Input Buffer leer\r\n fileopen='file=open(\"'+filename+'\",\"w\")' # Kommando an ESP open File\r\n ESPsend(fileopen)\r\n tline=t.splitlines()\r\n\r\n for i in tline:\r\n out=i+\"\\\\r\" # Zeilenende escaped \\\\r\r\n ESPsend(\"dummy=file.write('\"+out+\"')\") # Zeile an ESP\r\n time.sleep(0.05) # sonst verschluckt sich der ESP\r\n ESPsend('file.close()')\r\n return(\"ok\")\r\n\r\ndef ESPloadfile(filename):\r\n ser.reset_input_buffer()\r\n fileopen='file = open(\"'+filename+'\")'\r\n ESPsend(fileopen)\r\n ser.reset_input_buffer() \r\n ESPsend(\"file.read()\") # Kommando an ESP\r\n txt1=ser.readline() # Echo vom gesendetem Befehle abholen\r\n txt2=ser.readline() # Daten vom ESP\r\n txt_dec=txt2.decode()\r\n txt=txt_dec[1:-3] # Zeichen ' an Anfang und 'cr lf am Ende weg\r\n out=txt.replace(\"\\\\r\",chr(10)) # \\\\r escaped CR nach LF\r\n save=open(filename,'w')\r\n save.write(out) \r\n ESPsend(\"file.close()\")\r\n return(\"ok\")\r\n \r\ndef ESPloaddir():\r\n ser.reset_input_buffer() \r\n ESPsend(\"import os\")\r\n ser.reset_input_buffer()\r\n ESPsend(\"os.listdir()\")\r\n time.sleep(0.5)\r\n txt1=ser.readline() # Echo vom gesendetem Befehle abholen\r\n txt2=ser.readline() # Daten vom ESP\r\n txt=txt2.decode()\r\n listdir=eval(txt) # Liste aus String \r\n return(listdir)\r\n \r\ndef saveconfig():\r\n hinweis.config(text=\"\")\r\n global textfeld\r\n t = textfeld.get(\"1.0\", \"end-1c\") # t= Text aus Textfeld vom Zeile1 col 0 bis Ende\r\n hinweis.config(text=\"File wird gespeichert\")\r\n err=ESPsave(filename,t) # File zum ESP schicken\r\n if err==\"ok\":\r\n hinweis.config(text=\"File auf ESP gespeichert\")\r\n else:\r\n hinweis.config(text=\"Fehler in der USB Verbindung\")\r\n\r\ndef loaddir(file):\r\n textfeld.delete('1.0', END) # Textfeld leer machen\r\n listdir=ESPloaddir()\r\n match=[]\r\n filename=\"Error\"\r\n for i in listdir:\r\n if i.find(file)!= -1: # match auf file in Listdir\r\n match.append(i)\r\n print(i)\r\n if match!=[]:filename=match[0] \r\n return(filename)\r\n \r\ndef loadconfig():\r\n textfeld.delete('1.0', END) # Textfeld leer machen\r\n err=ESPloadfile(filename)\r\n if err==\"ok\":\r\n file=open(filename)\r\n txt=file.read()\r\n file.close()\r\n textfeld.insert(\"1.0\",txt)\r\n hinweis.config(text=\"Datei: \"+filename)\r\n else:\r\n hinweis.config(text=\"Fehler in der USB Verbindung\")\r\n\r\ndef loadbackup():\r\n textfeld.delete('1.0', END)\r\n hinweis.config(text=\"\")\r\n file=open(filename)#+\"-backup\")\r\n txt=file.read()\r\n file.close()\r\n textfeld.insert(\"1.0\",txt)\r\n hinweis.config(text=\"Backup-Datei\")\r\n#---------------------------------------------------------------------------------- \r\n#---------- Witgets laden\r\n\r\n \r\ntextfeld=tkst.ScrolledText(root,bg=\"black\",fg=\"#4ede5a\",insertbackground=\"#4ede5a\")\r\ntextfeld.pack(expand=\"True\",fill=\"both\")\r\n\r\nbutton2=ttk.Button(root, text=\"Load Config Backup\", command=loadbackup)\r\nbutton2.pack(side=\"right\",padx=\"5\")\r\n\r\nbutton3=ttk.Button(root, text=\"Save Config ESP\", command=saveconfig)\r\nbutton3.pack(side=\"right\",padx=\"5\")\r\n\r\nbutton1=ttk.Button(root, text=\"Load Config ESP\", command=loadconfig)\r\nbutton1.pack(side=\"right\",padx=\"5\")\r\n\r\nhinweis = Label(root, fg = \"black\",bg = \"lightgray\")#, font = \"Verdana 10\")\r\nhinweis.pack(side=\"left\")\r\n\r\n#------------------------------------------------------------------------------------\r\n\r\nfile=\"config.py\" # Editor File\r\n\r\nwhile True:\r\n err=serialOn()\r\n if err!=\"Error\":\r\n statustxt=\"ESP connectet on: \"+err\r\n hinweis.config(text=statustxt)\r\n break\r\n else:\r\n if askyesno(\"Keinen ESP am COM Port gefunden!\", \"Nochmal versuchen?\"):\r\n\r\n continue\r\n else:\r\n exit()\r\nprint(\"--\",ser)\r\nfilename=loaddir(file)\r\nif filename==\"Error\":\r\n if showwarning(file+\" nicht gefunden!\\n Abbruch\"):\r\n exit()\r\nloadconfig()\r\n\r\nroot.mainloop() \r\n\r\n","repo_name":"Aschhoff/ESP32-433Mhz-Receiver-and-Tools","sub_path":"Win_Source/ESP_Config_Editor.py","file_name":"ESP_Config_Editor.py","file_ext":"py","file_size_in_byte":6288,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"86"} +{"seq_id":"17579765623","text":"def prepare_key(key):\n key = key.upper().replace(\" \", \"\").replace(\"J\", \"I\")\n key_unique = \"\"\n for char in key:\n if char not in key_unique:\n key_unique += char\n alphabet = \"ABCDEFGHIKLMNOPQRSTUVWXYZ\"\n for char in key_unique:\n alphabet = alphabet.replace(char, \"\")\n return key_unique + alphabet\n\ndef create_grid(key):\n grid = [[0]*5 for _ in range(5)]\n index = 0\n for i in range(5):\n for j in range(5):\n grid[i][j] = key[index]\n index += 1\n return grid\n\ndef display_grid(grid):\n for row in grid:\n print(\" \".join(row))\n\ndef find_position(grid, char):\n for i in range(5):\n for j in range(5):\n if grid[i][j] == char:\n return i, j\n\ndef encrypt_decrypt_pair(grid, a, b, encrypt=True):\n row_a, col_a = find_position(grid, a)\n row_b, col_b = find_position(grid, b)\n shift = 1 if encrypt else -1\n \n if row_a == row_b:\n col_a = (col_a + shift) % 5\n col_b = (col_b + shift) % 5\n elif col_a == col_b:\n row_a = (row_a + shift) % 5\n row_b = (row_b + shift) % 5\n else:\n col_a, col_b = col_b, col_a\n \n return grid[row_a][col_a], grid[row_b][col_b]\n\ndef encrypt_decrypt_message(key, text, encrypt=True):\n key = prepare_key(key)\n grid = create_grid(key)\n text = text.upper().replace(\" \", \"\").replace(\"J\", \"I\")\n processed_text = \"\"\n \n for i in range(0, len(text), 2):\n a, b = text[i], text[i+1]\n processed_a, processed_b = encrypt_decrypt_pair(grid, a, b, encrypt)\n processed_text += processed_a + processed_b\n\n return processed_text\n\nif __name__ == \"__main__\":\n key = input(\"Enter the key: \")\n choice = input(\"Encrypt or Decrypt? (E/D): \").upper()\n text = input(\"Enter the text: \")\n\n key = prepare_key(key)\n grid = create_grid(key)\n print(\"Playfair Matrix:\")\n display_grid(grid)\n\n if choice == 'E':\n encrypted_text = encrypt_decrypt_message(key, text)\n print(\"Encrypted Text:\", encrypted_text)\n elif choice == 'D':\n decrypted_text = encrypt_decrypt_message(key, text, encrypt=False)\n print(\"Decrypted Text:\", decrypted_text)\n else:\n print(\"Invalid choice.\")\n","repo_name":"DauDinhQuangAnh/Network_Security","sub_path":"PlayfairCiper2.py","file_name":"PlayfairCiper2.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"8145580538","text":"# import functions needed for the analysis\nfrom rohan.global_imports import *\n# paths to the files\nimport yaml\ncfgp=f\"{dirname(realpath(__file__))}/cfg.yml\"\ncfg=yaml.load(open(cfgp,'r'))\ncfg={k:f\"{dirname(realpath(__file__))}/{cfg[k]}\" for k in cfg}\ncfg['cfgp']=cfgp\n## gene information from pyensembl objects\nimport pyensembl\ncfg['ensembl75'] = pyensembl.EnsemblRelease(species=pyensembl.species.Species.register(\nlatin_name='homo_sapiens',\nsynonyms=['homo_sapiens'],\nreference_assemblies={\n 'GRCh37': (75, 75),\n}),release=75)\ncfg['ensembl'] = pyensembl.EnsemblRelease(species=pyensembl.species.Species.register(\nlatin_name='homo_sapiens',\nsynonyms=['homo_sapiens'],\nreference_assemblies={\n 'GRCh38': (95, 95),\n}),release=95)\n## gene annotations\nif exists(cfg['dgene_annotp']):\n ## get annotations\n from rohan.dandage.io_dfs import get_colsubset2stats\n cfg['dgene_annot']=read_table(cfg['dgene_annotp'])\n cfg['dgene_annot_stats']=read_table(cfg['dgene_annot_statsp'])\n cfg['dgene_annot_stats']=set_index(cfg['dgene_annot_stats'],'gene subset')\n # sample sizes in the legends\n cfg['colgene_subset2classes']=cfg['dgene_annot_stats'].apply(lambda x: x.index,axis=0)[cfg['dgene_annot_stats'].apply(lambda x: ~pd.isnull(x),axis=0)].apply(lambda x: dropna(x),axis=0).to_dict()\n cfg['colgene_subset2classns']=cfg['dgene_annot_stats'][cfg['dgene_annot_stats'].apply(lambda x: ~pd.isnull(x),axis=0)].apply(lambda x: dropna(x),axis=0).to_dict()\n cfg['colgene_subset2classns']={k:[int(i) for i in cfg['colgene_subset2classns'][k]] for k in cfg['colgene_subset2classns']}\n\n cfg['colgene_subsetpre2colxys']={'paralog or singleton': ['paralog', 'singleton', 'unclassified'],\n 'heteromer or not':['heteromer','not heteromer'],\n 'homomer or not':['homomer','not homomer'],\n 'heteromer or homomer':['heteromer and homomer','homomer'],\n }\n if exists(cfg['dparalog_annotp']):\n cfg['dparalog_annot']=read_table(cfg['dparalog_annotp'])\n cfg['dparalog_annot_stats'],cfg['colparalog_subset2classes'],cfg['colparalog_subset2classns']=get_colsubset2stats(cfg['dparalog_annot'],\n [c for c in cfg['dparalog_annot'] if c.startswith('heteromer ') or c.startswith('homomer ')])\n else:\n print('warning: dparalog_annotp does not exists')\n ##vars\n cfg['cols_gene_subset']=list(cfg['colgene_subset2classes'].keys())\n\n cfg['gene_subset2colors']={\n 'paralog':'#FF2A2A',\n 'singleton':'#2A7FFF',\n 'unclassified':'#C0C0C0',\n 'heteromer':'#FF6600',\n 'not heteromer':'#37C837',\n 'homomer':'#00FF00',\n 'not homomer':'#D4AA00',\n 'heteromer and homomer':'#D45500',\n 'essential':'#222222',\n 'non-essential':'#111111',\n }\n cfg['colgene_subset2classcolors']={k:[cfg['gene_subset2colors'][s] for s in cfg['colgene_subset2classes'][k]] for k in cfg['colgene_subset2classes']}\n cfg['colparalog_subset2classcolors']={k:[cfg['gene_subset2colors'][s] for s in cfg['colparalog_subset2classes'][k]] for k in cfg['colparalog_subset2classes']}\n## labels for merging\ncfg['dn2label']={ 'CS1','Wang et al.',\n 'CS2','DepMap: CERES',\n 'CS2.1','DepMap: unique alignments',\n 'CS3','Shifrut et al.',}\n## ints\ncfg['ppitypes']=['all PPI','direct PPI']\n## labels for subsets of data\ncfg['dataset_cs']=['CS1','CS2','CS2.1','CS3']\ncfg['dataset2cols']=ordereddict({\n'CS': [\n 'CS mean CS1',\n 'CS mean CS2',\n 'CS mean CS2.1',\n 'CS mean CS3',\n ],\n'FPKM (log2 scale)':['FPKM (log2 scale) mean'],\n })\ncfg['dataset_cols']=[]\nfor k in cfg['dataset2cols']:\n cfg['dataset_cols']+=cfg['dataset2cols'][k]\ncfg['colcellline']='cell line'\ncfg['colgenename']='gene name'\ncfg['cols_paralog_stats']=['evolutionary distance','% identity','dN/dS', 'dN', 'dS']\n## plotting colors\ncfg['dataset_cs2color']=dict(zip(cfg['dataset_cs'],['#FF00FF','#A9A9A9','#00FF00','#0000FF','#FF0000']))\nboxprops = {'edgecolor': 'k', 'linewidth': 2, 'facecolor': 'w'}\nlineprops = {'color': 'k', 'linewidth': 2}\ncfg['boxplot_kwargs'] = dict({'boxprops': boxprops, 'medianprops': lineprops,\n 'whiskerprops': lineprops, 'capprops': lineprops,},)\n# for jupyter notebook\nfor k in cfg:\n globals()[k] = cfg[k]","repo_name":"Landrylab/Dandage_and_Landry_2019","sub_path":"human_paralogs/global_vars.py","file_name":"global_vars.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"39054888348","text":"a = {\r\n \"name\": \"name\",\r\n \"val\": \"vvv\"\r\n}\r\n\r\nprint(a.get(\"name\"))\r\nprint(a[\"name\"])\r\n#print(a.get(\"aaa\")) # return None\r\n#print(a[\"aa\"]) # thorow error\r\n\r\n\r\na.update({'name': 'Makemake'})\r\nprint(a)\r\n\r\na[\"name\"] = \"abcs\"\r\na[\"aaa\"] = \"abcs\"\r\nprint(a)\r\n\r\na.pop('name')\r\nprint(a)\r\n\r\nrainfall = {\r\n 'october': 3.5,\r\n 'november': 4.2,\r\n 'december': 2.1\r\n}\r\n\r\nprint(rainfall.keys())\r\nprint(\"aaa\" in rainfall.keys())\r\n\r\nprint(rainfall.values())","repo_name":"rtr-x8/python-tutrial","sub_path":"src/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"70397184604","text":"import time\r\nimport smbus\r\n\r\n\r\nMCP4728_ADDR=0x60\r\nmcp4728=smbus.SMBus(1)\r\n\r\nIR_Channel=0\r\nWhite_Channel=1\r\n\r\n\r\ndef mcp4728_write(channel: int, value: int): \r\n command=0x40\r\n udac=0x00\r\n first_byte=(command | (channel<<1) | udac)\r\n vref=0x00\r\n power_down=0x00\r\n gain=0x00\r\n mcp4728.write_i2c_block_data(MCP4728_ADDR, first_byte, [(value>>8), (value & 0xFF)])\r\n\r\nfor i in range(0, 4095, 10):\r\n mcp4728_write(White_Channel, i)\r\n time.sleep(0.2)","repo_name":"Vivente-Yazilim/Entegre-Denemeleri","sub_path":"mcp4728.py","file_name":"mcp4728.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"74793075803","text":"\nimport math\n\nclass Solution:\n @staticmethod\n def solveByGauss(n, matrix):\n # 初始化\n for i in range(n):\n matrix[i] = [matrix[i][j] for j in range(n + 1)]\n isSolutionExists = True\n errorMessage = \"\"\n\n # 高斯主元消元\n for i in range(n):\n maxElementRow = i\n maxElement = abs(matrix[i][i])\n for j in range(i + 1, n):\n if abs(matrix[j][i]) > maxElement:\n maxElementRow = j\n maxElement = abs(matrix[j][i])\n if maxElement == 0:\n isSolutionExists = False\n errorMessage = \"The system has no roots of equations or has an infinite set of them.\"\n break\n if maxElementRow != i:\n matrix[i], matrix[maxElementRow] = matrix[maxElementRow], matrix[i]\n for j in range(i + 1, n):\n coef = -matrix[j][i] / matrix[i][i]\n for k in range(i + 1, n + 1):\n matrix[j][k] += coef * matrix[i][k]\n matrix[j][i] = 0\n\n # 回代求解\n result = [0] * n\n for i in range(n - 1, -1, -1):\n s = 0\n for j in range(i + 1, n):\n s += matrix[i][j] * result[j]\n result[i] = (matrix[i][n] - s) / matrix[i][i]\n\n # 计算残差\n residual_errors = [0] * n\n for i in range(n):\n s = 0\n for j in range(n):\n s += matrix[i][j] * result[j]\n residual_errors[i] = abs(matrix[i][n] - s)\n\n if isSolutionExists:\n return [matrix, *result, *residual_errors]\n else:\n return [errorMessage]\n\nif __name__ == '__main__':\n n = int(input().strip())\n\n matrix_rows = n\n matrix_columns = n + 1\n\n matrix = []\n\n for _ in range(matrix_rows):\n matrix.append(list(map(float, input().rstrip().split())))\n\n result = Solution.solveByGauss(n, matrix)\n if Solution.isSolutionExists:\n print('\\n'.join(map(str, result)))\n else:\n print(f\"{Solution.errorMessage}\\n\")\n print('\\n')","repo_name":"meimingze/pythonProject","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"17230471806","text":"#!/usr/bin/env python\n\nfrom collections import defaultdict, Counter\nfrom typing import Dict, Set, DefaultDict\n\nimport click\nfrom rich import print\nfrom rich.progress import track\n\nfrom paranames.util import read, orjson_dump\n\n\ndef compute_overlap_counts(\n df,\n wikidata_id_column=\"wikidata_id\",\n conll_type_column=\"type\",\n language_column=\"language\",\n) -> Dict[str, int]:\n counts: DefaultDict[str, Set[str]] = defaultdict(set)\n\n for wikidata_id, conll_type in track(\n zip(df[wikidata_id_column], df[conll_type_column]), total=df.shape[0]\n ):\n counts[wikidata_id].add(conll_type)\n\n overlap_counts = Counter(\"-\".join(sorted(types)) for types in track(counts.values(), total=len(counts)))\n\n return overlap_counts\n\n\n@click.command()\n@click.option(\n \"--input-file\",\n \"-i\",\n required=True,\n type=click.Path(\n exists=True, file_okay=True, dir_okay=False, readable=True, allow_dash=True\n ),\n)\n@click.option(\n \"--input-format\",\n required=True,\n type=click.Choice([\"tsv\", \"csv\"]),\n)\n@click.option(\n \"--output-file\",\n \"-o\",\n required=True,\n type=click.File(\n mode=\"w\", encoding=\"utf-8\"\n )\n)\n@click.option(\n \"--output-format\",\n default=\"json\",\n type=click.Choice([\"json\"]),\n)\n@click.option(\"--id-column\", default=\"wikidata_id\")\n@click.option(\"--type-column\", default=\"type\")\n@click.option(\"--language-column\", default=\"language\")\ndef main(\n input_file,\n input_format,\n output_file,\n output_format,\n id_column,\n type_column,\n language_column,\n):\n print(f\"[compute_overlap_counts] Loading dump from {input_file}\")\n df = read(input_file, input_format)\n print(\"[compute_overlap_counts] Computing overlap counts...\")\n overlap_counts = compute_overlap_counts(\n df,\n wikidata_id_column=id_column,\n conll_type_column=type_column,\n language_column=language_column,\n )\n print(f\"[compute_overlap_counts] Writing to {output_file}\")\n output_file.write(orjson_dump(overlap_counts))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bltlab/paranames","sub_path":"paranames/analysis/compute_overlap_counts.py","file_name":"compute_overlap_counts.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"86"} +{"seq_id":"14435268653","text":"#!/usr/bin/python3\nimport sys\n\n\"\"\"\nFile_name: rsa\nCreated: 28th of May, 2023\nAuth: David James Taiye (Official0mega)\nSize: undefined\nProject: RSA-Factoring-Challenge\nStatus: submitted.\n\"\"\"\n\n\ndef factorization():\n\n \"\"\"\n # RSA Laboratories states that: for each RSA number n\n # ...there exist prime numbers p and q such that\n # n = p × q. The problem is to find these two primes, given only n.\n # VARIABLE(\" \"):\n # factorize(int) Factorize all the things!\n # This task is the same as task 0, except:\n # .....p and q are always prime numbers\n # .....There is only one number in the files\n # .....How far can you go in less than 5 second? 🤔🤔🤔\n \"\"\"\n try:\n files = sys.argv[1]\n with open(files) as f:\n for numbs in f:\n numbs = int(numbs)\n if numbs % 2 == 0:\n print(\"{}={}*{}\".format(numbs, numbs // 2, 2))\n continue\n run = 3\n while run < numbs // 2:\n if numbs % run == 0:\n print(\"{}={}*{}\".format(numbs, numbs // run, run))\n break\n run = run + 2\n if run == (numbs // 2) + 1:\n print(\"{}={}*{}\".format(numbs, numbs, 1))\n except (IndexError):\n pass\n\n\nfactorization()\n","repo_name":"Badro-West/RSA-Factoring-Challenge","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"7223055853","text":"import mysql.connector\nimport os\n\n\ndef main():\n try:\n print(os.environ[\"MYSQL_ROOT_PASSWORD\"])\n except KeyError as e:\n print(\"Environment variables not found\")\n print(e)\n if not {\"Database\": dbName} in executeSQL(\"SHOW DATABASES\", use=False):\n createDB()\n\n\ndef createDB():\n executeSQL(\"CREATE DATABASE \" + dbName, use=False)\n executeSQL(\"\"\"\n CREATE TABLE IF NOT EXISTS customers (\n id VARCHAR(15) PRIMARY KEY,\n coolData VARCHAR(30) NOT NULL) engine=InnoDB;\n \"\"\")\n\n\ndef executeSQL(command, parameters=(), use=True):\n try:\n database = mysql.connector.connect(**config)\n database.get_warnings = True\n cursor = database.cursor(dictionary=True)\n except mysql.connector.errors.ProgrammingError as e:\n print(e)\n exit()\n except mysql.connector.errors.DatabaseError as e:\n print(\"FATAL - MySQL probably doesn't exist on this system - {0}\".format(e))\n exit()\n try:\n if use:\n cursor.execute(\"USE {0}\".format(dbName))\n cursor.execute(command, parameters)\n except mysql.connector.errors.ProgrammingError as e:\n print(\"FATAL - Try dropping the whole database and retrying - {0}\".format(e))\n exit()\n rows = cursor.fetchall()\n database.commit()\n database.close()\n return rows\n\n\nif __name__ == '__main__':\n config = {\n \"host\": \"telegramBot-mysql\",\n \"user\": \"root\",\n \"password\": \"cumcumcum\"\n }\n dbName = \"testDB\"\n main()\n","repo_name":"veryheavypickle/dockerMySQL","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"9852084317","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 10 20:44:46 2022\n\n@author: hellraiser\n\"\"\"\nimport matplotlib as plt\nclass PlotModel():\n def __init__(self, history, name='model'):\n super(PlotModel, self).__init__()\n self.history=history\n self.name=name\n\n # plot output function\n def plot_model(self): \n loss_values = self.history['train_loss']\n val_loss_values = self.history['val_loss']\n accuracy_values = self.history['train_acc']\n val_accuracy_values = self.history['val_acc']\n \n fig = plt.figure(figsize=(19,3))\n plt.subplot(1, 2, 1)\n plt.suptitle(self.name, fontsize=18)\n plt.title('loss')\n epoch = range(1,len(loss_values)+1)\n plt.plot(epoch,loss_values, '--',label='loss')\n plt.plot(epoch,val_loss_values, '--',label='val_loss')\n plt.legend()\n plt.xlabel('epoch')\n plt.ylabel('loss')\n \n plt.subplot(1, 2, 2)\n plt.suptitle(self.name, fontsize=18)\n plt.title('accuracy')\n epoch = range(1,len(loss_values)+1)\n plt.plot(epoch,accuracy_values, '--',label='accuracy')\n plt.plot(epoch,val_accuracy_values, '--',label='val_accuracy')\n plt.legend()\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.show()","repo_name":"georaiser/06_Facial_Expression_Recognition","sub_path":"Utils/PlotModelOutput.py","file_name":"PlotModelOutput.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"28563743085","text":"import os\nimport json\nfrom os.path import join\nimport io\nimport numpy as np\nimport scipy\n\nimport scipy.misc\nfrom tqdm import tqdm\nfrom PIL import Image\nfrom torchvision.transforms import transforms\nfrom torchvision.transforms import ToTensor\nimport imageio\nimport lmdb\nimport torch\nfrom multiprocessing import Pool\nfrom torch.utils.data import Dataset\nfrom pathlib import Path\nfrom torchvision.datasets import VisionDataset\nfrom torchvision.datasets.folder import default_loader\nfrom torchvision.datasets.utils import download_url, list_dir, check_integrity, extract_archive, verify_str_arg\nimport pickle\n\n\ndef pil_loader(imgname, crop=None):\n # maybe faster\n if crop is None:\n with open(imgname, \"rb\") as f:\n return Image.open(imgname).convert(\"RGB\")\n else:\n box = (crop[0].item(), crop[1].item(), crop[2].item() + crop[0].item(), crop[3].item() + crop[1].item())\n with open(imgname, \"rb\") as f:\n img = Image.open(imgname).convert(\"RGB\")\n im = img.crop(box)\n\n return im\n\n\ncolorjit = [transforms.RandomRotation(20), transforms.ColorJitter(0.2, 0.2, 0.1)]\nroot_dir = f'/data/home/tangzihao/dataset/nico'\n\n\ndef train_transform():\n return transforms.Compose(\n [\n transforms.RandomApply(colorjit),\n transforms.RandomResizedCrop(224, scale=(0.8, 1.2)),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225))\n ])\n\n\ndef test_transform():\n return transforms.Compose(\n [\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225))\n ])\n\n\ndef to_pil_image():\n mean = (0.485, 0.456, 0.406)\n std = (0.229, 0.224, 0.225)\n to_img = transforms.ToPILImage()\n\n def f(img):\n oimg = img * std + mean\n return to_img(oimg)\n\n return transforms.Compose(\n [\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.485, 0.456, 0.406),\n std=(0.229, 0.224, 0.225))\n ])\n\n\ndef default_transform(a):\n return ToTensor()(a)\n\n\ndef collate_fn_NICO():\n def f(data):\n path = []\n gt = []\n context = []\n img = []\n for d in tqdm(data):\n d_img = d[\"img\"]\n d_img = torch.stack([d_img[0], d_img[1], d_img[2]], dim=-1)\n d_img = Image.fromarray(np.uint8(255 * d_img))\n\n path.append(d[\"path\"])\n gt.append(d[\"gt\"])\n context.append(d[\"context\"])\n img.append(d_img)\n\n return {\n \"path\": path,\n \"gt\": torch.from_numpy(np.array(gt)).long(),\n \"context\": torch.from_numpy(np.array(context)).long(),\n \"img\": img\n }\n\n return f\n\n\nclass NICOAnimal_LmdbDataset(Dataset):\n context = [\"white\", \"in circus\", \"running\", \"eating\", \"at home\", \"on ground\", \"on snow\",\n \"lying\", \"in cage\", \"sitting\", \"aside people\", \"in street\", \"black\", \"climbing\",\n \"eating grass\", \"in forest\", \"spotted\", \"in zoo\", \"on tree\", \"standing\", \"flying\", \"in water\",\n \"in hand\", \"on grass\", \"in hole\", \"at sunset\", \"walking\", \"on beach\", \"brown\", \"on shoulder\",\n \"in river\", \"on branch\", \"on road\"]\n category = [\"bear\", \"bird\", \"cat\", \"cow\", \"dog\", \"elephant\", \"horse\", \"monkey\", \"rat\", \"sheep\"]\n\n def __init__(self, root, transform=default_transform):\n super().__init__()\n self.root = root\n self.env = None\n self.txn = None\n self.transform = transform\n if self.env is None:\n self._init_db()\n\n def _init_db(self):\n self.env = lmdb.open(self.root,\n readonly=True, lock=False,\n readahead=False, meminit=False)\n self.txn = self.env.begin()\n\n def __getitem__(self, index):\n if self.env is None:\n self._init_db()\n image_bin = self.txn.get(f\"{index}\".encode(\"utf-8\"))\n if image_bin is None:\n raise IndexError(\"Index out of range\")\n (img, path, ctgy, ctx) = pickle.loads(image_bin)\n img = Image.open(io.BytesIO(img))\n\n return {\n \"path\": path,\n \"img\": self.transform(img),\n \"gt\": self.category.index(ctgy),\n \"context\": self.context.index(ctx),\n }\n\n def __len__(self):\n if self.env is None:\n self._init_db()\n return self.env.stat()[\"entries\"]\n\n\ndef main():\n data = NICOAnimal_LmdbDataset(f'{root_dir}/nico_animal_prop_D4_DR3_S256_train.lmdb')\n\n for pt in data.category:\n for ctx in data.context:\n Path(f'{root_dir}/train/{pt}/{ctx}').mkdir(parents=True, exist_ok=True)\n\n for d in tqdm(data):\n _, gt, ctx, file_name = str(d[\"path\"]).split('\\\\')\n tmp = np.uint8(255 * torch.stack(list(d[\"img\"]), dim=-1))\n Image.fromarray(tmp).save(f'{root_dir}/train/{gt}/{ctx}/{file_name}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"IshiKura-a/Redac","sub_path":"nico_divider.py","file_name":"nico_divider.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"14072484494","text":"import os, shutil\r\n\r\n# NOTE: You can write every single extension inside tuples\r\ndict_extensions = {\r\n 'Audio_extensions' : ('.mp3', '.m4a', '.wav', '.flac'),\r\n 'Video_extensions' : ('.mp4', '.mkv', '.MKV', '.flv', '.mpeg', '.3gp'),\r\n 'Document_extensions' : ('.docx', '.pdf', '.txt', '.xlx'),\r\n 'Image_extensions' : ('.jpg', '.png', '.bmp', '.tiff')\r\n}\r\n\r\nfolderpath = input('Enter folder path : ')\r\n\r\ndef file_finder(path, file_extensions):\r\n files = []\r\n for file in os.listdir(path):\r\n for extension in file_extensions:\r\n if file.endswith(extension):\r\n files.append(file)\r\n return files\r\n\r\n# # print(file_finder(folderpath, video_extensions))\r\nfor extension_type, extension_tuple in dict_extensions.items():\r\n new_folder_name = extension_type.split('_')[0] + ' Files'\r\n new_folder_path = os.path.join(folderpath,new_folder_name) # new folder path\r\n for item in file_finder(folderpath, extension_tuple):\r\n if not os.path.exists(new_folder_path):\r\n os.mkdir(new_folder_path)\r\n item_path = os.path.join(folderpath, item)\r\n item_new_path = os.path.join(new_folder_path, item)\r\n shutil.move(item_path, item_new_path)\r\n\r\n","repo_name":"Yash25gupta/Python","sub_path":"Tutorial_Codes/22 - Seperate Files.py","file_name":"22 - Seperate Files.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"30039573927","text":"from search.common import exceptions\nfrom search.common import utils\nfrom search.plugin import coordinate_search_handler\nfrom search.plugin import geplaces_search_handler\n\n\nclass FederatedSearch(object):\n \"\"\"Class for performing the Federated search.\n\n We initially submit the search against the CoordinateSearch, stopping\n there if any positive results are returned. If not, we issue our search\n against the GEPlacesSearch.\n\n If there is a valid response from any of the searches, we use\n it. If not, then we can assume that 'location' doesn't exist and so we\n present a reasonable 'no results found' back to the caller.\n \"\"\"\n\n def __init__(self):\n \"\"\"Inits FederatedSearch.\n\n Initializes the logger \"ge_search\".\n \"\"\"\n self.utils = utils.SearchUtils()\n self.logger = self.utils.logger\n\n # Create coordinate and places search objects\n\n self._coordinate = coordinate_search_handler.CoordinateSearch()\n self._geplaces = geplaces_search_handler.PlacesSearch()\n\n # Get Style information from Places or Coordinate search handlers.\n self._style = self._geplaces.style\n\n def HandleSearchRequest(self, environ):\n \"\"\"Fetches the search tokens from form and performs the federated search.\n\n Args:\n environ: A list of environment variables as supplied by the\n WSGI interface to the federated search application interface.\n Returns:\n search_results: A KML/JSONP formatted string which contains search results.\n response_type: Response type can be KML or JSONP, depending on the client.\n \"\"\"\n search_results = \"\"\n search_status = False\n\n # Fetch all the attributes provided by the user.\n parameters = self.utils.GetParameters(environ)\n\n self._geplaces.parameters = parameters\n self._coordinate.parameters = parameters\n\n # Retrieve the function call back name for JSONP response.\n self.f_callback = self.utils.GetCallback(parameters)\n\n # Fetch additional query parameters 'flyToFirstElement' and\n # 'displayKeys' from URL.\n self.fly_to_first_element = self.utils.GetValue(\n parameters, \"flyToFirstElement\")\n self.display_keys_string = self.utils.GetValue(\n parameters, \"displayKeys\")\n\n response_type = self.utils.GetResponseType(environ)\n\n original_query = self.utils.GetValue(parameters, \"q\")\n\n if original_query:\n (search_status, search_results) = self.DoSearch(\n original_query, response_type)\n else:\n self.logger.debug(\"Empty search query received\")\n\n if not search_status:\n folder_name = \"No results were returned.\"\n search_results = self.utils.NoSearchResults(\n folder_name, self._style, response_type, self.f_callback)\n\n return (search_results, response_type)\n\n def DoSearch(self, original_query, response_type):\n \"\"\"Performs the federated search and return's the results.\n\n Args:\n original_query: search query as entered by the user.\n response_type: Response type can be KML or JSONP, depending on the client.\n Returns:\n tuple containing\n search_status: Whether search could be performed.\n search_results: A KML/JSONP formatted string which contains search results.\n \"\"\"\n search_status = False\n search_results = \"\"\n\n self._geplaces.f_callback = self.f_callback\n self._coordinate.f_callback = self.f_callback\n\n self._geplaces.fly_to_first_element = self.fly_to_first_element\n self._geplaces.display_keys_string = self.display_keys_string\n\n self.logger.debug(\"Performing coordinate search on %s\", original_query)\n\n try:\n (search_status, search_results) = self._coordinate.DoSearch(\n original_query, response_type)\n except exceptions.BadQueryException:\n # If 'BadQueryException' exception occurs, ignore it\n # and proceed with places search.\n pass\n\n if not search_status:\n self.logger.debug(\n \"No search results were returned by coordinate search.\"\n \"Proceeding with places search...\")\n (search_status, search_results) = self._geplaces.DoSearch(\n original_query, response_type)\n if not search_status:\n self.logger.debug(\n \"No search results were returned by coordinate and places search.\")\n\n return search_status, search_results\n\n\ndef main():\n fedobj = FederatedSearch()\n fedobj.DoSearch(\"santa clara\", \"KML\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"google/earthenterprise","sub_path":"earth_enterprise/src/server/wsgi/search/plugin/federated_search_handler.py","file_name":"federated_search_handler.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","stars":2622,"dataset":"github-code","pt":"86"} +{"seq_id":"21668646256","text":"import os\nimport numpy as np\nfrom pathlib import Path\nimport cmath\nimport pandas as pd\nimport pickle\nfrom scipy.interpolate import interp1d\nfrom scipy.stats import gmean\nfrom scipy.stats import lognorm\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\ndef _responseSpectrum(acc, dt, period, damping):\n if period == 0.0:\n period = 1e-20\n PGA = max(acc)\n pow = 1\n while 2 ** pow < len(acc):\n pow = pow + 1\n nPts = 2 ** pow\n fas = np.fft.fft(acc, nPts)\n dFreq = 1/(dt*(nPts - 1))\n freq = dFreq * np.array(range(nPts))\n if nPts%2 != 0:\n symIdx = int(np.ceil(nPts/2))\n else:\n symIdx = int(1 + nPts/2)\n natFreq = 1/period\n H = np.ones(len(fas), 'complex')\n H[np.int_(np.arange(1, symIdx))] = np.array([natFreq**2 * 1/((natFreq**2 -\\\n i**2) + 2*cmath.sqrt(-1) * damping * i * natFreq) for i in freq[1:symIdx]])\n if nPts%2 != 0:\n H[np.int_(np.arange(len(H)-symIdx+1, len(H)))] = \\\n np.flipud(np.conj(H[np.int_(np.arange(1, symIdx))]))\n else:\n H[np.int_(np.arange(len(H)-symIdx+2, len(H)))] = \\\n np.flipud(np.conj(H[np.int_(np.arange(1, symIdx-1))]))\n sa = max(abs(np.real(np.fft.ifft(np.multiply(H, fas)))))\n return {'PGA':PGA, 'sa':sa}\n\n\ndef text_read(name, col):\n f = open(name, 'r')\n lines = f.readlines()\n data = []\n for x in lines:\n data.append(float(x.split()[col]))\n f.close()\n data = np.array(data)\n return data\n\n\ndef mafe_direct_im_based(H, s, eta, beta):\n \"\"\"\n Details:\n Compute the MAFE of a limit state defined via a fitted lognormal\n distribution by integrating directly with the hazard curve\n Treat the hazard input to avoid errors.\n We strip out:\n 1. the negative H values (usually at the beginning)dy_model\n 2. the points with constant s (usually at the end)\n Information:\n Author: Gerard J. O'Reilly\n First Version: April 2020\n Notes:\n References:\n Porter KA, Beck JL, Shaikhutdinov R V. Simplified Estimation of Economic\n Seismic Risk for Buildings. Earthquake Spectra 2004; 20(4):\n 1239–1263. DOI: 10.1193/1.1809129.\n Inputs:\n H: List of values of annual probability of exceedance\n s: List of corresponding intensities for H\n eta: Fragility function median (intensity)\n beta: Fragility function dispersion (total)\n Returns:\n l: Mean annual frequency of exceedance\n \"\"\"\n from scipy import stats\n import numpy as np\n\n # Do first strip\n s_f = []\n H_f = []\n for aa, bb in zip(s, H):\n if bb > 0:\n s_f.append(aa)\n H_f.append(bb)\n\n # Do second strip\n s_ff = []\n H_ff = []\n for i in range(len(s_f) - 1):\n if H_f[i] - H[i + 1] > 0:\n s_ff.append(s_f[i])\n H_ff.append(H_f[i])\n s_ff.append(s_f[-1])\n H_ff.append(H_f[-1])\n\n # Overwrite the initial variable for convenience\n s = s_ff\n H = H_ff\n\n # First we compute the PDF value of the fragility at each of the discrete\n # hazard curve points\n p = stats.lognorm.cdf(s, beta, scale=eta)\n\n # This function computes the MAF using Method 1 outlined in\n # Porter et al. [2004]\n # This assumes that the hazard curve is linear in logspace between\n # discrete points among others\n\n # Initialise some arrays\n ds = []\n ms = []\n dHds = []\n dp = []\n dl = []\n\n for i in np.arange(len(s)-1):\n ds.append(s[i+1]-s[i])\n ms.append(s[i]+ds[i]*0.5)\n dHds.append(np.log(H[i+1]/H[i])/ds[i])\n dp.append(p[i+1]-p[i])\n dl.append(p[i]*H[i]*(1-np.exp(dHds[i]*ds[i]))-dp[i]/ds[i]*H[i]*(np.exp(dHds[i]*ds[i])*(ds[i]-1/dHds[i])+1/dHds[i]))\n\n # Compute the MAFE\n l = sum(dl)\n\n # Return the MAFE\n return l\n\n\ndirectory = Path(os.getcwd())\ngm_path = directory.parents[0] / '.applications/case1/GroundMotions'\nrs_path = directory.parents[0] / '.applications/case1/Output1/RS.pickle'\noutputDir = directory.parents[0] / \".applications/case1/Output1\"\n\nwith open(outputDir/\"Cache/modelOutputs.pickle\", 'rb') as file:\n spo = pickle.load(file)\n\nwith open(outputDir/\"RCMRF/ida_cache.pickle\", 'rb') as file:\n ida = pickle.load(file)\n\ndt_file = np.array(pd.read_csv(gm_path/'GMR_dts.txt',header=None)[0])\ngm_file = list(pd.read_csv(gm_path/'GMR_names1.txt',header=None)[0])\n\ndr_model = spo[\"SPO_idealized\"][0][-1]\nmtdisp = ida[\"mtdisp\"]\nim_spl = ida[\"im_spl\"]\n\nspl_interp = interp1d(mtdisp, im_spl)\nspl_mu = spl_interp(dr_model)\n\nwith open(rs_path, 'rb') as file:\n rs = pickle.load(file)\n\nT1 = 1.00\nsat1_list = np.array([])\nscaling_factors = np.array([])\nidx_t1 = int(T1 * 100)\nfor i in range(len(gm_file)):\n SaT1 = float(rs[i+1][idx_t1])\n sat1_list = np.append(sat1_list, SaT1)\n scaling_factors = np.append(scaling_factors, spl_mu[i] / SaT1)\n\nTbot = T1*0.2\nTup = T1*1.5\nc_range = np.arange(Tbot, Tup, 0.1)\nsa_avgs = np.array([])\nfor i in range(len(gm_file)):\n rs[i+1] = rs[i+1]*scaling_factors[i]\n spectrum = np.zeros(len(c_range))\n for j in range(len(c_range)):\n idx = int(c_range[j]*100)\n spectrum[j] = float(rs[i+1][idx])\n sa_avgs = np.append(sa_avgs, gmean(spectrum))\n\neta = np.median(sa_avgs)\nbeta = np.std(np.log(sa_avgs))\n\nprint(sa_avgs, eta, beta)\n\nhaz_dir = directory.parents[0]/'.applications'/'case1'\nwith open(haz_dir/'Hazard-LAquila-Soil-Csaavg.pkl', 'rb') as file:\n [im, s, apoe] = pickle.load(file)\n im = np.array(im)\n s = np.array(s)\n apoe = np.array(apoe)\n\nindx_T = int(T1*10)\nmafc = mafe_direct_im_based(apoe[indx_T], s[indx_T], eta, beta)\nprint(mafc)\n\n\n\n","repo_name":"davitshahnazaryan3/IPBSD","sub_path":"sample/saavg.py","file_name":"saavg.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"86"} +{"seq_id":"23377414963","text":"from typing import *\n\nclass Node:\n def __init__(self):\n self.dic=[None for i in range(26)]\n self.count=0\n\n def verify(self):\n for i in self.dic:\n if i!=None:\n return False\n if self.count>0:\n return False\n self.count+=1\n return True\n\ndef reverseList(word):\n return list(word)[::-1]\n\ndef char2Int(letter):\n return ord(letter)-ord('a')\n\nclass Solution:\n def minimumLengthEncoding(self, words: List[str]) -> int:\n head=Node()\n for word in words:\n word=reverseList(word)\n now=head\n for letter in word:\n if now.dic[char2Int(letter)]==None:\n tmp=Node()\n now.dic[char2Int(letter)]=tmp\n now=tmp\n else:\n now=now.dic[char2Int(letter)]\n out=''\n for word in words:\n wordList=reverseList(word)\n now=head\n for letter in wordList:\n now=now.dic[char2Int(letter)]\n if now.verify():\n out+=word+'#'\n return len(out)\n\nsl=Solution()\nwords = [\"time\", \"me\", \"bell\",\"time\"]\nprint(sl.minimumLengthEncoding(words))\n\n\n\n \n \n","repo_name":"zzz136454872/leetcode","sub_path":"minimumLengthEncoding.py","file_name":"minimumLengthEncoding.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"9795691156","text":"def solution(today, terms, privacies):\n answer = []\n # 테스트 14 틀림\n td = dict({t.split()[0]:int(t.split()[1]) for t in terms})\n tot_d = int(today[:4])*12*28 + int(today[5:7])*28 + int(today[8:])\n\n for i, p in enumerate(privacies):\n month, year, day = int(p[5:7]), int(p[:4]), int(p[8:10])\n m = (month+td[p[-1]])%12 if (month+td[p[-1]])%12 !=0 else 12\n add_y = (month+td[p[-1]])//12 if (month+td[p[-1]]) % 12 != 0 else (month+td[p[-1]])//12 - 1\n y = year + add_y\n d = day-1\n if d == 0:\n d = 28\n m = m - 1\n if m == 0:\n m = 12\n y = y-1\n print(y,m,d)\n tot_p = y*12*28 + m*28 + d\n if tot_p < tot_d:\n answer.append(i+1)\n return answer\n","repo_name":"ddolboghi/programmers","sub_path":"프로그래머스/unrated/150370. 개인정보 수집 유효기간/개인정보 수집 유효기간.py","file_name":"개인정보 수집 유효기간.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"30605455776","text":"# =============================================================================\n# Packages:\nfrom keras.utils import np_utils\n\n# Project Files:\nimport dataSetup as ds\nimport FeatureSelection as fs\nimport prediction as pred\n# =============================================================================\n# #%% Control Variables %%#\nDEBUG = False \nREINGEST_DATA = False #imports data from quandl, dumps data to data.pickle\nLOAD_DATA = False \nREGENERATE_TA = False #recalc features, dumps to indicators_norm.pickle\nLOAD_TA = False\nREGENERATE_MIC = False #recalc mic, dumps to mic.pickle \nLOAD_MIC = False\nPLOT_CORR = True #calc corr, plot heat map\nPREDICT = False #run prediction algs.\nRUN_MLP = False\nRUN_RFE = False\nPLOT_RFE = False\nGENTABLE_MLP = False\nLABEL2 = False\nTIMEPERIODNUM = 1\n#Add more control here\n# =============================================================================\nif(TIMEPERIODNUM == 1):\n T = 10 #2 weeks\nelse:\n print('Pick a valid TIMEPERIODNUM')\n exit()\n# =============================================================================\n#Reimport data from quandl\nif(REINGEST_DATA):\n data, y, dataTEST, yTEST = ds.ingestData()\n ds.dumpData(data, 'data')\n ds.dumpData(y, 'y')\n ds.dumpData(dataTEST, 'dataTEST')\n ds.dumpData(yTEST, 'yTEST')\nif(LOAD_DATA):\n data, y, dataTEST, yTEST = ds.loadQdata()\n# =============================================================================\n#Regenerate feature pickle files\nif(REGENERATE_TA):\n indicators_norm, indicators, y_ind = ds.genTA(data, y, t=T)\n xTestNorm, xTest, yTest = ds.genTA(dataTEST, yTEST, t=T)\n x_all, y_all = ds.reformat(indicators_norm, y_ind)\n x_test, y_test = ds.reformat(xTestNorm, yTest)\n \n #Dump Pickles\n ds.dumpData(indicators_norm, 'indicators_normT'+str(TIMEPERIODNUM))\n ds.dumpData(indicators, 'indicatorsT'+str(TIMEPERIODNUM))\n ds.dumpData(y_ind, 'y_indT'+str(TIMEPERIODNUM))\n ds.dumpData(xTestNorm, 'indicators_normT'+str(TIMEPERIODNUM)+'TEST')\n ds.dumpData(xTest, 'indicatorsT'+str(TIMEPERIODNUM)+'TEST')\n ds.dumpData(yTest, 'y_indT'+str(TIMEPERIODNUM)+'TEST')\nif(LOAD_TA): #Load data from pickles\n indicators_norm, indicators, y_ind, xTestNorm, xTest, yTest = ds.loadTAdata(tNum=TIMEPERIODNUM)\n x_all, y_all = ds.reformat(indicators_norm, y_ind)\n x_test, y_test = ds.reformat(xTestNorm, yTest)\n# =============================================================================\n#Plot corr\nif(PLOT_CORR):\n fs.crossCorr(indicators_norm, t=TIMEPERIODNUM) \n# =============================================================================\nif(RUN_RFE):\n #Normalized\n selSVM5, selF_SVM5_Acc = fs.RFE_SVM(x_all, y_all, 5)\n selSVM10, selF_SVM10_Acc = fs.RFE_SVM(x_all, y_all, 10)\n selSVM15, selF_SVM15_Acc = fs.RFE_SVM(x_all, y_all, 15)\n \n selAda5, selF_Ada5_Acc = fs.RFE_AdaBoost(x_all, y_all, 5)\n selAda10, selF_Ada10_Acc = fs.RFE_AdaBoost(x_all, y_all, 10)\n selAda15, selF_Ada15_Acc = fs.RFE_AdaBoost(x_all, y_all, 15)\nif(PLOT_RFE):\n selF_SVM5_Acc2 = selSVM5.score(x_test, y_test)\n selF_SVM10_Acc2 = selSVM10.score(x_test, y_test)\n selF_SVM15_Acc2 = selSVM15.score(x_test, y_test)\n selF_Ada5_Acc2 = selAda5.score(x_test, y_test)\n selF_Ada10_Acc2 = selAda10.score(x_test, y_test)\n selF_Ada15_Acc2 = selAda15.score(x_test, y_test)\n \n rfeSvmAcc1 = [selF_SVM5_Acc, selF_SVM10_Acc, selF_SVM15_Acc]\n rfeSvmAcc2 = [selF_SVM5_Acc2, selF_SVM10_Acc2, selF_SVM15_Acc2]\n rfeAdaAcc1 = [selF_Ada5_Acc, selF_Ada10_Acc, selF_Ada15_Acc]\n rfeAdaAcc2 = [selF_Ada5_Acc2, selF_Ada10_Acc2, selF_Ada15_Acc2]\n fs.plotRFE(rfeSvmAcc1, rfeSvmAcc2, rfeAdaAcc1, rfeAdaAcc2)\nif(RUN_MLP):\n y_test_keras = np_utils.to_categorical(y_test, 3)\n #All Features\n mlp, mlpAcc = pred.MLP(x_all, y_all)\n mlpAcc2 = mlp.evaluate(x_test, y_test_keras)[1]\n #Handpicked\n x_hand = x_all[['RSI', 'MACD', 'ATR', 'SAR', 'OBV']].copy()\n x_handTest = x_test[['RSI', 'MACD', 'ATR', 'SAR', 'OBV']].copy()\n mlpHand, mlpHandAcc = pred.MLP(x_hand, y_all)\n mlpHandAcc2 = mlpHand.evaluate(x_handTest, y_test_keras)[1]\n #RFE_Ada with 5 features selected\n x_ada5 = x_all[['ROC', 'MACD', 'OBV', 'ATR', 'VAR']].copy()\n x_ada5Test = x_test[['ROC', 'MACD', 'OBV', 'ATR', 'VAR']].copy()\n mlpAda5, mlpAda5Acc = pred.MLP(x_ada5, y_all)\n mlpAda5Acc2 = mlpAda5.evaluate(x_ada5Test, y_test_keras)[1]\nif(GENTABLE_MLP):\n mlpAccuracies = [[mlpAcc, mlpHandAcc, mlpAda5Acc],\n [mlpAcc2, mlpHandAcc2, mlpAda5Acc2]]\n pred.genMLPTable(mlpAccuracies)\nif(PREDICT):\n# pred.randomForest(x_all, y_all, switch=1, t=TIMEPERIODNUM)\n pred.pca(x_all, y_all, t=TIMEPERIODNUM)\n# =============================================================================\n#Regnerate mic pickle files\nif(REGENERATE_MIC):\n mic = fs.genMIC(indicators, y_ind, t=TIMEPERIODNUM)\n ds.dumpData(mic, 'MICT'+str(TIMEPERIODNUM))\nif(LOAD_MIC): #Load mic from pickle\n mic = fs.loadMIC(tNum=TIMEPERIODNUM)\n#============================================================================= \nif(LABEL2):\n dataLABEL2, yLABEL2 = ds.labelOut5(data)\n x_label2, y_label2 = ds.reformat(dataLABEL2, yLABEL2)\n mlpLabel2, mlpLabel2Acc = pred.MLP(x_label2, y_label2)\n","repo_name":"bschifman/ECE_523_Project","sub_path":"2_Software/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"351453492","text":"# -*- coding: utf-8 -*-\nimport sys, random\nimport pygame\n\n\n__author__ = ('Andry Kõre')\n\npygame.init()\npygame.mixer.init()\nWIDTH = 890\nHEIGHT = 660\ngameScreen = pygame.display.set_mode([WIDTH, HEIGHT])\npygame.display.set_caption('MemoryGame')\n\n'''Card pictures from www.pixabay.com'''\ncard_back = pygame.image.load('./resources/cardBack.png').convert_alpha()\ncard_fox = pygame.image.load('./resources/cardFox.png').convert_alpha()\ncard_dachshund = pygame.image.load('./resources/cardDachshund.png').convert_alpha()\ncard_moose = pygame.image.load('./resources/cardMoose.png').convert_alpha()\ncard_bear = pygame.image.load('./resources/cardBear.png').convert_alpha()\ncard_beaver = pygame.image.load('./resources/cardBeaver.png').convert_alpha()\ncard_cat = pygame.image.load('./resources/cardCat.png').convert_alpha()\ncard_duck = pygame.image.load('./resources/cardDuck.png').convert_alpha()\ncard_elephant = pygame.image.load('./resources/cardElephant.png').convert_alpha()\ncard_horse = pygame.image.load('./resources/cardHorse.png').convert_alpha()\ncard_leopard = pygame.image.load('./resources/cardLeopard.png').convert_alpha()\ncard_rabbit = pygame.image.load('./resources/cardRabbit.png').convert_alpha()\ncard_squirrel = pygame.image.load('./resources/cardSquirrel.png').convert_alpha()\nmenu_image = pygame.image.load('./resources/gameMenu.png').convert()\nend_image = pygame.image.load('./resources/gameEnd.png').convert()\nmemory_text = pygame.image.load('./resources/memoryGameText.png').convert_alpha()\n\nmusic_menu = './sound/menuMusic.wav'\nmusic_game = './sound/gameMusic.wav'\nsound_win = './sound/win.wav'\n\n\ncardSize = card_back.get_rect().size\n\nallCardsList = [card_fox, card_dachshund, card_bear, card_moose,\n card_beaver, card_cat, card_duck, card_elephant,\n card_horse, card_leopard, card_rabbit, card_squirrel\n ]\n\ndef Text(screen, text, size, color, coords):\n lfont = pygame.font.SysFont('Arial Bold', size)\n labl = lfont.render(text, 1, color)\n screen.blit(labl, coords)\n\n\nclass Card:\n def __init__(self, x, y, picture):\n global clickable, pause\n self.x = x\n self.y = y\n self.pic = picture\n self.card = card_back\n self.commenceaction = False\n clickable = True\n pause = False\n\n def mouse(self, pos, click):\n global last\n if not pause:\n if clickable:\n if self.x + cardSize[0] > pos[0] > self.x and self.y + cardSize[1] > pos[1] > self.y:\n if click[0]:\n last = pygame.time.get_ticks()\n self.card = self.pic\n if self in mouseClicks:\n pass\n elif self in openedCards:\n pass\n else:\n mouseClicks.append(self)\n\n def flipBack(self):\n self.card = card_back\n \n def drawCard(self, scren):\n scren.blit(self.card, [self.x, self.y])\n\n\nclass Button:\n def __init__(self, xpos, ypos, height, width, buttontext, regularcolor, hovercolor, clickcolor, function, size=30, textfont='Arial Bold'):\n global clickableButton\n self.function = function\n self.buttontext = buttontext\n self.currentcolor = regularcolor\n self.clickcolor = clickcolor\n self.hovercolor = hovercolor\n self.regularcolor = regularcolor\n self.width = width\n self.height = height\n self.ypos = ypos\n self.xpos = xpos\n self.commenceaction = False\n self.font = pygame.font.SysFont(textfont, size)\n self.textcontent = self.font.render(self.buttontext, 1, (10, 10, 10))\n self.textposition = pygame.Rect((self.xpos, self.ypos), (self.width, self.height))\n self.textposition[0] = self.xpos + ((self.width - self.textcontent.get_width()) / 2)\n self.textposition[1] = self.ypos + ((self.width - self.textcontent.get_height()) / 6)\n clickableButton = True\n\n def mousemovement(self, position, key):\n if clickableButton:\n if self.xpos < position[0] < self.xpos + self.width and self.ypos < position[1] < self.ypos + self.height:\n if key[0]:\n self.currentcolor = self.clickcolor\n self.commenceaction = True\n else:\n self.currentcolor = self.hovercolor\n if self.commenceaction:\n self.function()\n self.commenceaction = False\n else:\n self.currentcolor = self.regularcolor\n\n def drawbutton(self, scren):\n pygame.draw.rect(scren, self.currentcolor, pygame.Rect((self.xpos, self.ypos), (self.width, self.height)))\n scren.blit(self.textcontent, self.textposition)\n\n\nclass Cards:\n def __init__(self):\n self.cards = []\n\n def board(self, grid):\n for card in allCardsList:\n for i in range(2):\n position = random.randint(0, len(grid)-1)\n self.cards.append(Card(grid[position][0], grid[position][1], card))\n grid.pop(position)\n\n def click(self):\n for cardclick in self.cards:\n cardclick.opened()\n\n def mouse(self, pos, click):\n for cardmouse in self.cards:\n cardmouse.mouse(pos, click)\n\n def drawBoard(self, display):\n for draw in self.cards:\n draw.drawCard(display)\n\n def clearList(self):\n del self.cards[:]\n\n\nclass Allbuttons:\n def __init__(self, allthebuttons):\n self.buttons = allthebuttons\n\n def drawbutton(self, scren):\n for button in self.buttons:\n button.drawbutton(scren)\n\n def mousemovement(self, position, key):\n for button in self.buttons:\n button.mousemovement(position, key)\n\n\nclass Status():\n menu = 1\n game = 2\n fade = 3\n end = 4\n info = 5\n\n\nclass Game:\n def __init__(self, screen):\n global mouseClicks, openedCards\n self.currentStatus = Status.menu\n self.currentScreen = screen\n self.screenRect = self.currentScreen.get_rect()\n self.cards = Cards()\n self.correct = None\n self.clickNow = 0\n self.t1 = 0\n self.playtime = 0\n self.clickedTime = 0\n self.addTime = False\n self.timerPause = False\n self.clock = pygame.time.Clock()\n self.clock2 = pygame.time.Clock()\n self.clock3 = pygame.time.Clock()\n self.surface = pygame.Surface((WIDTH, HEIGHT))\n self.surface.fill((0, 200, 0))\n self.surfaceAlpha = 0\n self.currentSound = music_menu\n openedCards = []\n mouseClicks = []\n\n def makeGrid(self):\n gridList = []\n\n for i in range(4): # cards in vertical |\n y = 80 + (i*10)\n y += i*cardSize[1]\n for j in range(6): # cards in horizontal --\n x = 30 + (j*10)\n x += j*cardSize[0]\n f = x, y\n gridList.append(f)\n\n random.shuffle(gridList)\n\n return gridList\n\n def turnCards(self):\n global clickable, last\n if len(mouseClicks) == 2:\n pygame.display.flip()\n if mouseClicks[0].pic is mouseClicks[1].pic:\n self.correct = True\n openedCards.append(mouseClicks[0]); openedCards.append(mouseClicks[1])\n del mouseClicks[:]\n else:\n clickable = False\n self.correct = False\n self.clickNow = pygame.time.get_ticks()\n if self.clickNow - last >= 1200:\n self.correct = None\n last = self.clickNow\n clickable = True\n mouseClicks[0].flipBack(); mouseClicks[1].flipBack()\n del mouseClicks[:]\n\n def correctWrong(self):\n if self.correct:\n self.clickNow = pygame.time.get_ticks()\n Text(self.currentScreen, 'CORRECT', 50, (0, 220, 0), (self.screenRect.centerx-40, 26))\n if self.clickNow - last >= 1200:\n self.correct = None\n elif self.correct == False:\n Text(self.currentScreen, 'WRONG', 50, (255, 0, 0), (self.screenRect.centerx-40, 26))\n\n def ifOpened(self):\n if len(openedCards) == len(allCardsList)*2:\n if not self.addTime:\n if self.playtime < float(self.readFile()):\n self.writeFile(self.playtime)\n self.addTime = True\n self.currentStatus = Status.fade\n\n def timer(self):\n if not self.timerPause:\n if pause:\n self.t1 = self.clock2.tick()\n else:\n milliseconds = (self.now - self.t1)\n seconds = milliseconds / 1000\n self.playtime += seconds\n self.t1 = 0\n\n def writeFile(self, score):\n file = open('scores.txt', 'w')\n file.write(str(score))\n file.close()\n\n def readFile(self):\n file = open('scores.txt', 'r')\n score = file.readline()\n file.close()\n return score\n\n def showMenu(self):\n global buttons\n self.currentStatus = Status.menu\n self.cards.clearList()\n self.playtime = 0\n self.correct = None\n self.addTime = False\n self.timerPause = False\n self.surfaceAlpha = 0\n del openedCards[:]\n del mouseClicks[:]\n buttons = Allbuttons([\n Button(self.screenRect.centerx-50, self.screenRect.centery-80, 40, 100, 'PLAY', (0,210,0), (10,240,110), (160,245,225), self.startGame),\n Button(self.screenRect.centerx-50, self.screenRect.centery-30, 40, 100, 'INFO', (0,210,0), (10,240,110), (160,245,225), self.infoTab),\n Button(self.screenRect.centerx-50, self.screenRect.centery+20, 40, 100, 'EXIT', (0,210,0), (10,240,110), (160,245,225), self.quitGame)\n ])\n if self.currentSound == music_game:\n pygame.mixer.music.stop()\n self.currentSound = music_menu\n pygame.mixer.music.load(music_menu)\n pygame.mixer.music.play(-1)\n\n def startGame(self):\n global buttons\n self.currentStatus = Status.game\n self.cards.board(self.makeGrid())\n buttons = Allbuttons([\n Button(810, 25, 30, 70, 'EXIT', (0,210,00), (10,240,110), (160,245,225), self.quitGame, 26),\n Button(725, 25, 30, 70, 'PAUSE', (0,210,00), (10,240,110), (160,245,225), self.goPause, 26),\n Button(640, 25, 30, 70, 'BACK', (0,210,00), (10,240,110), (160,245,225), self.showMenu, 26)\n ])\n pygame.mixer.music.stop()\n self.currentSound = music_game\n pygame.mixer.music.load(self.currentSound)\n pygame.mixer.music.play(-1)\n\n def infoTab(self):\n global buttons\n self.currentStatus = Status.info\n buttons = Allbuttons([\n Button(self.screenRect.centerx-50, 600, 40, 100, 'BACK', (0,210,0), (10,240,110), (160,245,225), self.showMenu),\n ])\n\n def goPause(self):\n global pause\n if pause:\n pygame.mixer.music.unpause()\n pause = False\n else:\n pygame.mixer.music.pause()\n pause = True\n\n def goFade(self):\n global clickableButton\n self.surfaceAlpha = min(255, self.surfaceAlpha + (self.now/1000) * 210)\n self.surface.set_alpha(self.surfaceAlpha)\n self.currentScreen.blit(self.surface, (0, 0))\n self.timerPause = True\n clickableButton = False\n if self.surfaceAlpha == 255:\n self.gameEnd()\n sound = pygame.mixer.Sound(sound_win)\n sound.set_volume(.4)\n sound.play()\n\n\n def gameEnd(self):\n global buttons, clickableButton\n self.currentStatus = Status.end\n clickableButton = True\n buttons = Allbuttons([\n Button(self.screenRect.centerx-135, 580, 40, 90, 'MENU', (0,200,0), (10,240,110), (160,245,225), self.showMenu),\n Button(self.screenRect.centerx+45, 580, 40, 90, 'EXIT', (0,200,0), (10,240,110), (160,245,225), self.quitGame)\n ])\n pygame.mixer.music.stop()\n self.currentSound = music_menu\n pygame.mixer.music.load(music_menu)\n pygame.mixer.music.play(-1)\n\n def quitGame(self):\n pygame.quit()\n sys.exit()\n\n def updateScreen(self):\n global buttons\n self.now = self.clock.tick()\n\n if self.currentStatus == Status.menu:\n self.currentScreen.blit(menu_image, (0, 0))\n buttons.drawbutton(self.currentScreen)\n\n pygame.display.flip()\n\n elif self.currentStatus == Status.info:\n self.currentScreen.fill([255, 220, 153])\n buttons.drawbutton(self.currentScreen)\n self.currentScreen.blit(memory_text, (self.screenRect.centerx-120, 20))\n Text(self.currentScreen, 'INFO', 40, (0, 0, 0), (self.screenRect.centerx-20, 75))\n Text(self.currentScreen, 'Licences', 40, (200, 0, 0), (30, 110))\n Text(self.currentScreen, 'Card pictures from - www.pixabay.com', 30, (0, 0, 0), (30, 150))\n Text(self.currentScreen, 'Menu picture from - www.pixabay.com', 30, (0, 0, 0), (30, 180))\n Text(self.currentScreen, 'Game end trophy from - www.flaticon.com', 30, (0, 0, 0), (30, 230))\n Text(self.currentScreen, 'Trophy author: Freepik', 30, (0, 0, 0), (30, 260))\n Text(self.currentScreen, 'Trophy address: http://www.flaticon.com/free-icon/trophy_147210', 30, (0, 0, 0), (30, 290))\n Text(self.currentScreen, 'Menu music from - www.bensound.com', 30, (0, 0, 0), (30, 340))\n Text(self.currentScreen, 'Game music from - www.orangefreesounds.com', 30, (0, 0, 0), (30, 370))\n Text(self.currentScreen, 'Winning sound from - www.soundbible.com', 30, (0, 0, 0), (30, 400))\n Text(self.currentScreen, 'Game created by - Andry Kõre', 30, (0, 200, 0), (30, 460))\n Text(self.currentScreen, 'This game is made to learn Python and Pygame.', 30, (0, 200, 0), (30, 480))\n Text(self.currentScreen, 'Release - 18.06.2016', 30, (0, 200, 0), (30, 500))\n pygame.display.flip()\n\n elif self.currentStatus == Status.game or self.currentStatus == Status.fade:\n buttons.drawbutton(self.currentScreen)\n self.currentScreen.blit(memory_text, (10, 20))\n pygame.draw.line(self.currentScreen, [0, 0, 0], [0, 70], [WIDTH, 70])\n self.cards.drawBoard(self.currentScreen)\n self.timer()\n Text(self.currentScreen, str(round(self.playtime, 1)), 40, (225, 0, 0), (self.screenRect.centerx-140, 32))\n if pause:\n Text(self.currentScreen, 'GAME PAUSED', 70, (225, 0, 0), (self.screenRect.centerx-180, self.screenRect.centery))\n self.correctWrong()\n self.turnCards()\n self.ifOpened()\n if self.currentStatus == Status.fade:\n self.goFade()\n pygame.display.flip()\n self.currentScreen.fill([255, 220, 153])\n\n elif self.currentStatus == Status.end:\n self.currentScreen.blit(end_image, (0, 0))\n buttons.drawbutton(self.currentScreen)\n Text(self.currentScreen, 'Your time: '+str(round(self.playtime, 1)), 40, (0, 200, 0), (self.screenRect.centerx-90, 400))\n Text(self.currentScreen, 'Best time: '+str(round(float(self.readFile()), 1)), 40, (200, 0, 0), (self.screenRect.centerx-90, 450))\n\n pygame.display.flip()\n\n\ngame = Game(gameScreen)\ngame.showMenu()\npygame.mixer.music.load(music_menu)\npygame.mixer.music.play(-1)\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n if event.type == pygame.MOUSEMOTION or event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:\n buttons.mousemovement(pygame.mouse.get_pos(), pygame.mouse.get_pressed())\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n game.cards.mouse(pygame.mouse.get_pos(), pygame.mouse.get_pressed())\n\n game.updateScreen()\n\n\n\n","repo_name":"TheAndry/PygamePracticeGame","sub_path":"MemoryGame.py","file_name":"MemoryGame.py","file_ext":"py","file_size_in_byte":16236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"75057740763","text":"import sys\nsys.stdin = open('input.txt')\n\nT = int(input())\n\nfor test_case in range(1, T+1):\n\n N, M, L = map(int, input().split())\n numbers = list(map(int, input().split()))\n\n for _ in range(M):\n cmd = input().split()\n\n if cmd[0] == 'I':\n numbers.insert(int(cmd[1]), int(cmd[2]))\n elif cmd[0] == 'D':\n del numbers[int(cmd[1])]\n elif cmd[0] == 'C':\n numbers[int(cmd[1])] = int(cmd[2])\n \n if L < len(numbers):\n print(f'#{test_case}', numbers[L])\n else: # 인덱스 벗어날 때\n print(f'#{test_case}', -1)\n","repo_name":"algo-itzy/algo-itzy","sub_path":"SWEA/linked_list/L5122-수열_편집/L5122-수열_편집-seungkyu.py","file_name":"L5122-수열_편집-seungkyu.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"86"} +{"seq_id":"37026816654","text":"import jsonpickle\nfrom flask import request\n\nfrom app import app, userIdRepo\n\n\n@app.route('/userId/', methods=['GET'])\ndef get_userId_by_user(fhId: str):\n try:\n user = userIdRepo.get_userId_by_user(fhId)\n\n return jsonpickle.encode(user)\n except Exception as e:\n return jsonpickle.encode({'error': 'Unable to retrieve userId for user', 'details': str(e)}), 500\n\n\n@app.route('/userId', methods=['POST'])\ndef add_rfid_to_user():\n try:\n userIdDetails = request.get_json()\n userId = userIdRepo.add_rfid_to_user(userIdDetails)\n\n return jsonpickle.encode(userId)\n except Exception as e:\n return jsonpickle.encode({'error': 'Unable to add rfid to user', 'details': str(e)}), 500\n\n\n@app.route('/userId/lock/', methods=['PATCH'])\ndef update_lock_for_userId(isLocked: bool):\n try:\n userIdDetails = request.get_json()\n userIdDetails[\"letiltva\"] = int(isLocked)\n userId = userIdRepo.update_lock_for_userId(userIdDetails)\n\n return jsonpickle.encode(userId)\n except Exception as e:\n return jsonpickle.encode({'error': 'Unable to change lock state for userId', 'details': str(e)}), 500\n\n\n@app.route('/userId/', methods=['DELETE'])\ndef remove_rfid_from_user(rErtek: str):\n try:\n userIdRepo.remove_rfid_from_user(rErtek)\n\n\n return \"success\", 200\n except Exception as e:\n return jsonpickle.encode({'error': 'Unable to add rfid to user', 'details': str(e)}), 500\n","repo_name":"mark182182/GKLB_INTM020_mikroelektromechanikai_rendszerek","sub_path":"route/user_id_route.py","file_name":"user_id_route.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"949967671","text":"# Python 3.6\n\n\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nimg = cv2.imread('coins.jpg', 0)\n#th = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\\\n# cv2.THRESH_BINARY,5,3)\nplt.imshow(img,'gray')\nimg = cv2.resize(img,(int(img.shape[1] * 20 / 100),int(img.shape[0] * 20 / 100)))\nplt.show()\n#%%\nclasses = np.zeros(img.shape)\nd = 25\nk = 1\ndef g(arr,im,clas):\n a=0\n i,j = np.where(arr == clas)\n for k in zip(i,j):\n a+=im[k]\n return a/len(i)\nfor i in range(len(img)):\n for j in range(len(img[0])):\n if abs(int(img[i][j])-int(img[i][j-1]))>d and abs(int(img[i-1][j])-int(img[i][j]))>d:\n classes[i][j] = k\n k+=1\n elif abs(int(img[i][j])-int(img[i][j-1]))>d:\n classes[i][j] = classes[i-1][j]\n elif abs(int(img[i][j])-int(img[i-1][j]))>d:\n classes[i][j] = classes[i][j-1]\n else:\n if abs(g(classes,img,classes[i-1][j])-g(classes,img,classes[i][j-1])) < d:\n classes[classes == classes[i][j-1]] = classes[i-1][j]\n classes[i][j] = classes[i][j-1]\n elif abs(g(classes,img,classes[i-1][j])-g(classes,img,classes[i][j-1])) > d:\n classes[i][j] = min(abs(img[i][j] - g(classes,img,classes[i-1][j])),abs(img[i][j] - g(classes,img,classes[i][j-1])))\n\nimage = Image.fromarray(classes)\nplt.imshow(image)\nplt.show()\n","repo_name":"sureepoup/Image-recognition-algorithms","sub_path":"Task_5/Task_5.py","file_name":"Task_5.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"32254756646","text":"\nDATASET_ROOT = '/media/ml_data/projects/lyft_test'\n# DATASET_ROOT = '/root/data/lyft'\n\n\nIMG_SIZE = 1024\nVOXEL_SIZE = 0.2\nVOXEL_Z_SIZE = 0.7\nIMG_CHANNELS = 6\n\nIMG_SIZE_CROP = 512\n\nEPOCHS = 128\nBATCH_SIZE = 16\n\nREG_COEF = 0.05\nBOX_SCALE = 0.9\nZ_OFFSET = -2.0\n\nNUM_WORKERS = 16\n\nADJACENT = True\n\nif ADJACENT:\n ARTIFACTS_FOLDER = \"../artifacts_IMG_SIZE_{}_VOXEL_{:.2f}_VOXEL_Z_{:.2f}_HEIGHT_{:.2f}_BOX_SCALE_{:.2f}_ADJ_as_channels\".format(\n IMG_SIZE, VOXEL_SIZE, VOXEL_Z_SIZE, VOXEL_Z_SIZE * IMG_CHANNELS, BOX_SCALE)\nelse:\n ARTIFACTS_FOLDER = \"../artifacts_IMG_SIZE_{}_VOXEL_{:.2f}_VOXEL_Z_{:.2f}_HEIGHT_{:.2f}_BOX_SCALE_{:.2f}\".format(\n IMG_SIZE, VOXEL_SIZE, VOXEL_Z_SIZE, VOXEL_Z_SIZE * IMG_CHANNELS, BOX_SCALE)\n\n\nclasses = [\n \"car\", \"motorcycle\", \"bus\", \"bicycle\", \"truck\",\n \"pedestrian\", \"other_vehicle\", \"animal\", \"emergency_vehicle\"\n ]\n\n\nwhile_list_classes = [\n \"car\",\n \"bus\",\n \"truck\",\n \"other_vehicle\",\n \"emergency_vehicle\",\n \"motorcycle\",\n \"bicycle\",\n \"pedestrian\",\n \"animal\",\n]\n\nprint('while_list_classes', while_list_classes)\n\nclass_to_size = {\n \"car\": (1.93, 4.76, 1.72),\n \"motorcycle\": (0.96, 2.35, 1.59),\n \"bus\": (2.96, 12.34, 3.44),\n \"bicycle\": (0.63, 1.76, 1.44),\n \"truck\": (2.84, 10.24, 3.44),\n \"pedestrian\": (0.77, 0.81, 1.78),\n \"other_vehicle\": (2.79, 8.20, 3.23),\n \"animal\": (0.36, 0.73, 0.51),\n \"emergency_vehicle\": (2.45, 6.52, 2.39)\n}\n\nclass_to_width = {class_name: class_to_size[class_name][0] for class_name in class_to_size}\nclass_to_len = {class_name: class_to_size[class_name][1] for class_name in class_to_size}\nclass_to_height = {class_name: class_to_size[class_name][2] for class_name in class_to_size}\n\nprint('classes', classes)\n\nfrom apex.fp16_utils import FP16_Optimizer\nfrom apex import amp\nimport sparse\n\nfrom efficientnet_pytorch import EfficientNet\nfrom efficientnet_pytorch.utils import (\n Conv2dStaticSamePadding,\n round_filters,\n round_repeats,\n drop_connect,\n get_same_padding_conv2d,\n get_model_params,\n efficientnet_params,\n load_pretrained_weights,\n)\nfrom datetime import datetime\nfrom functools import partial\nimport glob\nfrom multiprocessing import Pool\n\n# Disable multiprocesing for numpy/opencv. We already multiprocess ourselves, this would mean every subprocess produces\n# even more threads which would lead to a lot of context switching, slowing things down a lot.\nimport os\nos.environ[\"OMP_NUM_THREADS\"] = \"1\"\n\nimport matplotlib.pyplot as plt\n\nimport pandas as pd\nimport cv2\nfrom PIL import Image\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom lyft_dataset_sdk.lyftdataset import LyftDataset\nfrom lyft_dataset_sdk.utils.data_classes import LidarPointCloud, Box, Quaternion\nfrom lyft_dataset_sdk.utils.geometry_utils import view_points, transform_matrix\nfrom lyft_dataset_sdk.eval.detection.mAP_evaluation import Box3D, recall_precision\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nlevel5data = LyftDataset(json_path=DATASET_ROOT + \"/test_data/\", data_path=DATASET_ROOT, verbose=True)\nos.makedirs(ARTIFACTS_FOLDER, exist_ok=True)\n\n\nrecords = [(level5data.get('sample', record['first_sample_token'])['timestamp'], record) for record in\n level5data.scene]\n\nentries = []\n\nfor start_time, record in sorted(records):\n start_time = level5data.get('sample', record['first_sample_token'])['timestamp'] / 1000000\n\n token = record['token']\n name = record['name']\n date = datetime.utcfromtimestamp(start_time)\n host = \"-\".join(record['name'].split(\"-\")[:2])\n first_sample_token = record[\"first_sample_token\"]\n\n entries.append((host, name, date, token, first_sample_token))\n \ntest_df = pd.DataFrame(entries, columns=[\"host\", \"scene_name\", \"date\", \"scene_token\", \"first_sample_token\"])\n\nsample_token = test_df.first_sample_token.values[0]\nsample = level5data.get(\"sample\", sample_token)\n\nsample_lidar_token = sample[\"data\"][\"LIDAR_TOP\"]\nlidar_data = level5data.get(\"sample_data\", sample_lidar_token)\nlidar_filepath = level5data.get_sample_data_path(sample_lidar_token)\n\nego_pose = level5data.get(\"ego_pose\", lidar_data[\"ego_pose_token\"])\ncalibrated_sensor = level5data.get(\"calibrated_sensor\", lidar_data[\"calibrated_sensor_token\"])\n\n# Homogeneous transformation matrix from car frame to world frame.\nglobal_from_car = transform_matrix(ego_pose['translation'],\n Quaternion(ego_pose['rotation']), inverse=False)\n\n# Homogeneous transformation matrix from sensor coordinate frame to ego car frame.\ncar_from_sensor = transform_matrix(calibrated_sensor['translation'], Quaternion(calibrated_sensor['rotation']),\n inverse=False)\n\nlidar_pointcloud = LidarPointCloud.from_file(lidar_filepath)\n\n# The lidar pointcloud is defined in the sensor's reference frame.\n# We want it in the car's reference frame, so we transform each point\nlidar_pointcloud.transform(car_from_sensor)\n\n# A sanity check, the points should be centered around 0 in car space.\nplt.hist(lidar_pointcloud.points[0], alpha=0.5, bins=30, label=\"X\")\nplt.hist(lidar_pointcloud.points[1], alpha=0.5, bins=30, label=\"Y\")\nplt.legend()\nplt.xlabel(\"Distance from car along axis\")\nplt.ylabel(\"Amount of points\")\nplt.show()\n\nmap_mask = level5data.map[0][\"mask\"]\n\n\ndef get_semantic_map_around_ego(map_mask, ego_pose, voxel_size, output_shape):\n\n def crop_image(image: np.array,\n x_px: int,\n y_px: int,\n axes_limit_px: int) -> np.array:\n x_min = int(x_px - axes_limit_px)\n x_max = int(x_px + axes_limit_px)\n y_min = int(y_px - axes_limit_px)\n y_max = int(y_px + axes_limit_px)\n\n cropped_image = image[y_min:y_max, x_min:x_max]\n\n return cropped_image\n\n pixel_coords = map_mask.to_pixel_coords(ego_pose['translation'][0], ego_pose['translation'][1])\n\n extent = voxel_size*output_shape[0]*0.5\n scaled_limit_px = int(extent * (1.0 / (map_mask.resolution)))\n mask_raster = map_mask.mask()\n\n cropped = crop_image(mask_raster, pixel_coords[0], pixel_coords[1], int(scaled_limit_px * np.sqrt(2)))\n\n ypr_rad = Quaternion(ego_pose['rotation']).yaw_pitch_roll\n yaw_deg = -np.degrees(ypr_rad[0])\n\n rotated_cropped = np.array(Image.fromarray(cropped).rotate(yaw_deg))\n ego_centric_map = crop_image(rotated_cropped, rotated_cropped.shape[1] / 2, rotated_cropped.shape[0] / 2,\n scaled_limit_px)[::-1]\n \n ego_centric_map = cv2.resize(ego_centric_map, output_shape[:2], cv2.INTER_NEAREST)\n return ego_centric_map.astype(np.float32)/255\n \nego_centric_map = get_semantic_map_around_ego(\n map_mask, ego_pose, voxel_size=VOXEL_SIZE, output_shape=(IMG_SIZE, IMG_SIZE)\n) \n\nplt.imshow(ego_centric_map)\nplt.show()\n\n\n# As input for our network we voxelize the LIDAR points. That means that we go from a list of coordinates of points, to a X by Y by Z space.\n\n# In[13]:\n\n\ndef create_transformation_matrix_to_voxel_space(shape, voxel_size, offset):\n \"\"\"\n Constructs a transformation matrix given an output voxel shape such that (0,0,0) ends up in the center.\n Voxel_size defines how large every voxel is in world coordinate, (1,1,1) would be the same as Minecraft voxels.\n \n An offset per axis in world coordinates (metric) can be provided, this is useful for Z (up-down) in lidar points.\n \"\"\"\n \n shape, voxel_size, offset = np.array(shape), np.array(voxel_size), np.array(offset)\n \n tm = np.eye(4, dtype=np.float32)\n translation = shape/2 + offset/voxel_size\n \n tm = tm * np.array(np.hstack((1/voxel_size, [1])))\n\n tm[:3, 3] = np.transpose(translation)\n return tm\n\n\ndef transform_points(points, transf_matrix):\n \"\"\"\n Transform (3,N) or (4,N) points using transformation matrix.\n \"\"\"\n if points.shape[0] not in [3,4]:\n raise Exception(\"Points input should be (3,N) or (4,N) shape, received {}\".format(points.shape))\n return transf_matrix.dot(np.vstack((points[:3, :], np.ones(points.shape[1]))))[:3, :]\n\n# Let's try it with some example values\ntm = create_transformation_matrix_to_voxel_space(shape=(100,100,4), voxel_size=(0.5,0.5,0.5), offset=(0,0,0.5))\np = transform_points(np.array([[10, 10, 0, 0, 0], [10, 5, 0, 0, 0],[0, 0, 0, 2, 0]], dtype=np.float32), tm)\nprint(p)\n\n\n# In[14]:\n\n\ndef car_to_voxel_coords(points, shape, voxel_size, z_offset=0):\n if len(shape) != 3:\n raise Exception(\"Voxel volume shape should be 3 dimensions (x,y,z)\")\n \n if len(points.shape) != 2 or points.shape[0] not in [3, 4]:\n raise Exception(\"Input points should be (3,N) or (4,N) in shape, found {}\".format(points.shape))\n\n tm = create_transformation_matrix_to_voxel_space(shape, voxel_size, (0, 0, z_offset))\n p = transform_points(points, tm)\n return p\n\n\ndef create_voxel_pointcloud(points, shape, voxel_size=(0.5,0.5,1), z_offset=0):\n\n points_voxel_coords = car_to_voxel_coords(points.copy(), shape, voxel_size, z_offset)\n points_voxel_coords = points_voxel_coords[:3].transpose(1,0)\n points_voxel_coords = np.int0(points_voxel_coords)\n \n bev = np.zeros(shape, dtype=np.float32)\n bev_shape = np.array(shape)\n\n within_bounds = (np.all(points_voxel_coords >= 0, axis=1) * np.all(points_voxel_coords < bev_shape, axis=1))\n \n points_voxel_coords = points_voxel_coords[within_bounds]\n coord, count = np.unique(points_voxel_coords, axis=0, return_counts=True)\n \n # Note X and Y are flipped:\n bev[coord[:,1], coord[:,0], coord[:,2]] = count\n \n return bev\n\ndef normalize_voxel_intensities(bev, max_intensity=16):\n return (bev/max_intensity).clip(0,1)\n\n\nvoxel_size = (VOXEL_SIZE, VOXEL_SIZE, VOXEL_Z_SIZE)\nz_offset = Z_OFFSET\nbev_shape = (IMG_SIZE, IMG_SIZE, IMG_CHANNELS)\n\nbev = create_voxel_pointcloud(lidar_pointcloud.points, bev_shape, voxel_size=voxel_size, z_offset=z_offset)\n\n# So that the values in the voxels range from 0,1 we set a maximum intensity.\nbev = normalize_voxel_intensities(bev)\n\n\nboxes = level5data.get_boxes(sample_lidar_token)\n\ntarget_im = np.zeros((*bev.shape[:2], 3), dtype=np.uint8)\n\n\ndef visualize_lidar_of_sample(sample_token, axes_limit=80):\n sample = level5data.get(\"sample\", sample_token)\n sample_lidar_token = sample[\"data\"][\"LIDAR_TOP\"]\n level5data.render_sample_data(sample_lidar_token, axes_limit=axes_limit)\nvisualize_lidar_of_sample(sample_token)\n\n\n# Now we will run this on all samples in the train and validation set, and write the input and target images to their respective folders.\n\n# In[23]:\n\n\n# Some hyperparameters we'll need to define for the system\nvoxel_size = (VOXEL_SIZE, VOXEL_SIZE, VOXEL_Z_SIZE)\nz_offset = Z_OFFSET\nbev_shape = (IMG_SIZE, IMG_SIZE, IMG_CHANNELS)\n\n# We scale down each box so they are more separated when projected into our coarse voxel space.\nbox_scale = BOX_SCALE\n\n\n# \"bev\" stands for birds eye view\ntest_data_folder = os.path.join(ARTIFACTS_FOLDER, \"bev_test_data\")\n\n\ndef get_global_point_cloud(sample_token):\n local_sample = level5data.get(\"sample\", sample_token)\n\n local_sample_lidar_token = local_sample[\"data\"][\"LIDAR_TOP\"]\n local_lidar_data = level5data.get(\"sample_data\", local_sample_lidar_token)\n local_lidar_filepath = level5data.get_sample_data_path(local_sample_lidar_token)\n\n local_ego_pose = level5data.get(\"ego_pose\", local_lidar_data[\"ego_pose_token\"])\n local_calibrated_sensor = level5data.get(\"calibrated_sensor\", local_lidar_data[\"calibrated_sensor_token\"])\n\n global_from_car = transform_matrix(local_ego_pose['translation'],\n Quaternion(local_ego_pose['rotation']),\n inverse=False)\n\n car_from_sensor = transform_matrix(local_calibrated_sensor['translation'],\n Quaternion(local_calibrated_sensor['rotation']),\n inverse=False)\n\n local_lidar_pointcloud = LidarPointCloud.from_file(local_lidar_filepath)\n\n local_lidar_pointcloud.transform(car_from_sensor)\n local_lidar_pointcloud.transform(global_from_car)\n\n return local_lidar_pointcloud\n\n\ndef prepare_training_data_for_scene(first_sample_token, output_folder, bev_shape, voxel_size, z_offset, box_scale):\n \"\"\"\n Given a first sample token (in a scene), output rasterized input volumes and targets in birds-eye-view perspective.\n \n\n \"\"\"\n sample_token = first_sample_token\n \n while sample_token:\n # print(sample_token)\n sample = level5data.get(\"sample\", sample_token)\n\n sample_lidar_token = sample[\"data\"][\"LIDAR_TOP\"]\n lidar_data = level5data.get(\"sample_data\", sample_lidar_token)\n ego_pose = level5data.get(\"ego_pose\", lidar_data[\"ego_pose_token\"])\n\n car_from_global = transform_matrix(\n ego_pose['translation'],\n Quaternion(ego_pose['rotation']), inverse=True\n )\n\n try:\n lidar_pointcloud = get_global_point_cloud(sample_token)\n lidar_pointcloud.transform(car_from_global)\n points = np.array(lidar_pointcloud.points)\n\n if ADJACENT:\n if sample['prev']:\n lidar_pointcloud = get_global_point_cloud(sample['prev'])\n lidar_pointcloud.transform(car_from_global)\n adj_points = np.array(lidar_pointcloud.points)\n else:\n sample_token = sample[\"next\"]\n continue\n\n if sample['next']:\n lidar_pointcloud = get_global_point_cloud(sample['next'])\n lidar_pointcloud.transform(car_from_global)\n next_points = np.array(lidar_pointcloud.points)\n adj_points = np.hstack((adj_points, next_points))\n else:\n sample_token = sample[\"next\"]\n continue\n\n except Exception as e:\n print(\"Failed to load Lidar Pointcloud for {}: {}:\".format(sample_token, e))\n sample_token = sample[\"next\"]\n continue\n\n bev = create_voxel_pointcloud(points, bev_shape, voxel_size=voxel_size, z_offset=z_offset)\n bev = normalize_voxel_intensities(bev)\n\n if ADJACENT:\n adj_bev = create_voxel_pointcloud(adj_points, bev_shape, voxel_size=voxel_size, z_offset=z_offset)\n adj_bev = normalize_voxel_intensities(adj_bev)\n bev = np.concatenate((bev, adj_bev), axis=2)\n\n bev_im = np.round(bev * 255).astype(np.uint8)\n\n semantic_im = get_semantic_map_around_ego(map_mask, ego_pose, voxel_size[0], target_im.shape)\n semantic_im = np.round(semantic_im * 255).astype(np.uint8)\n\n bev_im_sparse = sparse.COO(bev_im)\n sparse.save_npz(os.path.join(output_folder, \"{}_input.npz\".format(sample_token)), bev_im_sparse)\n cv2.imwrite(os.path.join(output_folder, \"{}_map.png\".format(sample_token)), semantic_im)\n \n sample_token = sample[\"next\"]\n\n \nif True: \n for df, data_folder in [(test_df, test_data_folder)]:\n print(\"Preparing data into {} using {} workers\".format(data_folder, NUM_WORKERS))\n first_samples = df.first_sample_token.values\n\n os.makedirs(data_folder, exist_ok=True)\n\n process_func = partial(prepare_training_data_for_scene,\n output_folder=data_folder, bev_shape=bev_shape, voxel_size=voxel_size, z_offset=z_offset, box_scale=box_scale)\n\n pool = Pool(NUM_WORKERS)\n for _ in tqdm(pool.imap_unordered(process_func, first_samples), total=len(first_samples)):\n pass\n pool.close()\n\n\n\n\n","repo_name":"iasawseen/lyft_unet","sub_path":"data/test_data_generator.py","file_name":"test_data_generator.py","file_ext":"py","file_size_in_byte":15770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"26175814002","text":"from django.urls import path, include\r\n\r\nfrom paragliding_shop.accounts.views import index, SignInView, SignUpView, \\\r\n SignOutView, UserDetailsView, \\\r\n UserEditView, UserDeleteView, show_order, AllUsers\r\n\r\nurlpatterns = (\r\n path('', index, name='index'),\r\n path('login/', SignInView.as_view(), name='login user'),\r\n path('register/', SignUpView.as_view(), name='register user'),\r\n path('logout/', SignOutView.as_view(), name='logout user'),\r\n path('all-users/', AllUsers.as_view(), name='all users'),\r\n path('profile//', include([\r\n path('', UserDetailsView.as_view(), name='details user'),\r\n path('edit/', UserEditView.as_view(), name='edit user'),\r\n path('delete/', UserDeleteView.as_view(), name='delete user'),\r\n path('basket/', show_order, name='basket'),\r\n # path('basket/', show_order, name='basket'),\r\n ])),\r\n)\r\n","repo_name":"AStoychev/django_paragliding_shop_project","sub_path":"paragliding_shop/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"70849098843","text":"# -*- coding: future_fstrings -*-\nimport Crasa.Crasa as crasa\nfrom scabha import config, parameters_dict, prun\nfrom casacore.table import table\nimport os\nimport numpy\n\nprint(f\"Running CASA task '{config.binary}'\")\n\nargs = parameters_dict\n\ntask = crasa.CasaTask(config.binary, **args)\ntask.run()\n\ngtab = args[\"caltable\"]\nif not os.path.exists(gtab):\n raise RuntimeError(f\"The gaintable was not created. Please refer to CASA {config.binary} logfile for further details\")\n\ntab = table(gtab)\nfield_ids = numpy.unique(tab.getcol(\"FIELD_ID\"))\ntab.close()\n\ntab = table(gtab+\"::FIELD\")\nfield_names = tab.getcol(\"NAME\")\ntab.close()\n\nfield_in = args[\"field\"].split(\",\")\n\ntry:\n ids = list(map(int, field_in))\nexcept ValueError:\n ids = list(map(lambda a: field_names.index(a), field_in))\n\nif not set(ids).issubset(field_ids):\n raise RuntimeError(f\"Some field(s) do not have solutions after the calibration. Please refer to CASA {config.binary} logfile for further details\")\n","repo_name":"ratt-ru/Stimela","sub_path":"stimela/cargo/cab/casa_gencal/src/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"86"} +{"seq_id":"8265987569","text":"from django.core.management.base import BaseCommand, CommandError\nfrom django.conf import settings\n\nimport json\nimport os\n\nVERSION = getattr(settings, \"VERSION\", \"\")\n\n\nclass Command(BaseCommand):\n help = \"Add setting to specific app\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"app_name\",\n type=str,\n help=\"the name of the app to add the setting, use pod for a global setting\",\n )\n parser.add_argument(\"setting_name\", type=str, help=\"the name of the setting\")\n\n def get_setting(self, options, config_part):\n data = app_settings = settings = []\n filename = os.path.join(\"pod\", \"main\", \"configuration.json\")\n with open(filename, \"r\", encoding=\"utf-8\") as json_file:\n data = json.load(json_file)\n\n if options[\"app_name\"] == \"pod\":\n app_settings = data[0][\"configuration_pod\"][\"description\"]\n app_name = config_part\n else:\n app_settings = data[0][\"configuration_apps\"][\"description\"]\n app_name = options[\"app_name\"]\n\n try:\n settings = app_settings[app_name][\"settings\"]\n except KeyError:\n raise CommandError(\n 'Application name \"%s\" not found in configuration file' % app_name\n )\n\n if settings.get(options[\"setting_name\"]):\n self.stdout.write(self.style.WARNING(20 * \"*\"))\n self.stdout.write(\n self.style.WARNING(\"Setting found in json file, you will modify it !\")\n )\n setting_json = json.dumps(\n settings[options[\"setting_name\"]],\n sort_keys=False,\n indent=2,\n ensure_ascii=False,\n )\n self.stdout.write(self.style.SUCCESS(setting_json))\n self.stdout.write(self.style.WARNING(20 * \"*\"))\n return settings[options[\"setting_name\"]]\n else:\n return {}\n\n def get_configuration_pod(self):\n filename = os.path.join(\"pod\", \"main\", \"configuration.json\")\n with open(filename, \"r\", encoding=\"utf-8\") as json_file:\n data = json.load(json_file)\n return data[0][\"configuration_pod\"][\"description\"].keys()\n\n def save_setting(self, options, config_part, setting):\n filename = os.path.join(\"pod\", \"main\", \"configuration.json\")\n with open(filename, \"r\", encoding=\"utf-8\") as json_file:\n data = json.load(json_file)\n\n if options[\"app_name\"] == \"pod\":\n data[0][\"configuration_pod\"][\"description\"][config_part][\"settings\"][\n options[\"setting_name\"]\n ] = setting\n else:\n data[0][\"configuration_apps\"][\"description\"][options[\"app_name\"]][\"settings\"][\n options[\"setting_name\"]\n ] = setting\n os.remove(filename)\n with open(filename, \"w\", encoding=\"utf-8\") as f:\n json.dump(data, f, sort_keys=True, indent=4, ensure_ascii=False)\n\n def fix_default_value(self, default_value):\n msg = \"Default value (leave blank to keep previous value : %s) : \" % default_value\n if default_value == \"\":\n msg = \"Default value : \"\n input_value = input(msg)\n if input_value != \"\":\n default_value = input_value\n if default_value == \"False\":\n default_value = False\n if default_value == \"True\":\n default_value = True\n if not isinstance(default_value, bool) and default_value.isdigit():\n default_value = int(default_value)\n return default_value\n\n def get_description(self, previous_description):\n if previous_description != [\"\"]:\n print(\"(--> Type enter directly to keep previous value !)\")\n description = [\"\"]\n while True:\n user_input = input()\n # 👇️ if user pressed Enter without a value, break out of loop\n if user_input == \"\":\n break\n else:\n description.append(user_input)\n if description == [\"\"]:\n description = previous_description\n return description\n\n def handle(self, *args, **options):\n self.stdout.write(\n self.style.SUCCESS('Setting name \"%s\"' % options[\"setting_name\"])\n )\n self.stdout.write(self.style.SUCCESS('App name \"%s\"' % options[\"app_name\"]))\n\n config_part = \"main\"\n if options[\"app_name\"] == \"pod\":\n list_conf = self.get_configuration_pod()\n print(\"Here is available configuration : %s\" % \", \".join(list_conf))\n config_part = input(\n \"Give configuration part in available configuration, \"\n + \"leave blank to use main: \"\n )\n if config_part == \"\":\n config_part = \"main\"\n if config_part not in list_conf:\n self.stdout.write(self.style.ERROR(\"Configuration not available !\"))\n return\n\n setting = self.get_setting(options, config_part)\n\n pod_version_init = input(\n \"Pod initial version (leave blank to put current version : %s): \" % VERSION\n )\n if pod_version_init == \"\":\n pod_version_init = VERSION\n\n pod_version_end = input(\n \"Pod last version (i.e : 2.9.0, deprecated or not use anymore): \"\n )\n\n default_value = self.fix_default_value(setting.get(\"default_value\", \"\"))\n\n print(\"Add a english description (leave blank and type enter to leave):\")\n previous_value = (\n setting[\"description\"].get(\"en\", [\"\"]) if setting.get(\"description\") else [\"\"]\n )\n description_en = self.get_description(previous_value)\n\n print(\"Add a french description (leave blank and type enter to leave):\")\n previous_value = (\n setting[\"description\"].get(\"fr\", [\"\"]) if setting.get(\"description\") else [\"\"]\n )\n description_fr = self.get_description(previous_value)\n\n setting = {\n \"pod_version_init\": pod_version_init,\n \"pod_version_end\": pod_version_end,\n \"default_value\": default_value,\n \"description\": {\"en\": description_en, \"fr\": description_fr},\n }\n setting_json = json.dumps(\n {options[\"setting_name\"]: setting},\n sort_keys=True,\n indent=2,\n ensure_ascii=False,\n )\n self.stdout.write(self.style.SUCCESS(setting_json))\n confirm = input(\"Save it to config file ? y/n : \")\n if confirm != \"y\":\n self.stdout.write(self.style.ERROR(\"Not saving, End !\"))\n return\n\n self.save_setting(options, config_part, setting)\n\n self.stdout.write(self.style.SUCCESS(\"End !\"))\n","repo_name":"EsupPortail/Esup-Pod","sub_path":"pod/main/management/commands/addsetting.py","file_name":"addsetting.py","file_ext":"py","file_size_in_byte":6765,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"86"} +{"seq_id":"23766620357","text":"'''\ni/p:[1, 2, 4, 7, 10, 11, 7, 12, 6, 7, 16, 18, 19]\no/p:[3, 9]\n'''\n\n\n\n\n\ndef subarraySort(array):\n\tminimum=float(\"inf\")\n\tmaximum=float(\"-inf\")\n\tout=0\n\t\n\tdef outOrder(i,array):\n\t\tif i==0:\n\t\t\treturn array[i+1] < array[i]\n\t\tif i==len(array)-1:\n\t\t\treturn array[i-1]>array[i]\n\t\treturn array[i+1] < array[i] or array[i-1]>array[i]\n\t\t\n\tfor i in range(len(array)):\n\t\tif (outOrder(i,array)):\n\t\t\tminimum=min(minimum,array[i])\n\t\t\tmaximum=max(maximum,array[i])\n\tif minimum==float('inf'):\n\t\treturn [-1,-1]\n\tleftIdx=0\n\trightIdx=len(array)-1\n\t\n\twhile minimum >= array[leftIdx]:\n\t\tleftIdx += 1\n\twhile maximum <= array[rightIdx]\t:\n\t\trightIdx -= 1\n\t\t\n\treturn [leftIdx,rightIdx]\t\n\t\t","repo_name":"Rajeshkumark26/Algorithms_coding_practice","sub_path":"subarraySort.py","file_name":"subarraySort.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"2713994350","text":"import os\nfrom sh import git\nimport shutil\nimport yaml\ntry:\n from yaml import CLoader as Loader, CDumper as Dumper\nexcept ImportError:\n from yaml import Loader, Dumper\nimport brainy.config\nimport logging\n\n\nlogger = logging.getLogger(__name__)\nuser_config = brainy.config.load_user_config()\n\n\ndef parse_frame(frame):\n '''Init with defaults. Guess empty fields from URL or fail.'''\n result = dict()\n result.update(frame)\n result['version'] = frame.get('version', 'master')\n result['access_method'] = frame.get('access_method', 'git')\n return result\n\n\nclass FramesError(Exception):\n '''High-level brainy frames error. Can be handled and reported.'''\n\n\nclass Frames(object):\n '''\n A frame is a package. Frames take care of frameworks installations\n (like iBRAIN) into user space.\n '''\n\n def __init__(self, framework, location):\n '''\n location is Framework location, e.g. ~/iBRAIN\n '''\n self.framework = framework\n self.location = location\n self._packages = None\n\n @property\n def cache_location(self):\n return os.path.join(self.location, '.frames')\n\n @property\n def package_list_path(self):\n '''A YAML list of installed packages'''\n return os.path.join(self.cache_location, '.packages')\n\n @property\n def packages(self):\n '''\n A proxy around YAML list of installed packages.\n Simplifies any direct YAML I/O.\n Returns a list of dicts.\n '''\n if self._packages is None:\n if not os.path.exists(self.package_list_path):\n self._packages = list()\n return self._packages\n logger.info('Loading list of installed packages: %s' %\n self.package_list_path)\n with open(self.package_list_path) as stream:\n self._packages = yaml.load(stream, Loader=Loader)\n return self._packages\n\n @packages.setter\n def packages(self, value):\n assert type(value) == list\n self._packages = value\n yaml_list = yaml.dump(value, default_flow_style=True)\n logging.info('Saving list of installed packaged: %s' %\n self.package_list_path)\n with open(self.package_list_path, 'w+') as output:\n output.write(yaml_list)\n\n def init(self):\n if not os.path.exists(self.location):\n logger.info('Initializing framework folders and caches at: %s' %\n self.location)\n os.makedirs(self.cache_location)\n logger.info('Creating empty list of installed packages: %s' %\n self.location)\n self.packages = list()\n\n def update_index(self):\n '''\n Brainy user configuration provides an URL to get\n project index.\n\n A value of framework can be `iBRAIN`.\n '''\n # TODO replace this hardcoded index by URL download\n packages_index = '''\n# iBRAIN Framework\nindex version: 1\npackages:\n -\n name: 'iBRAIN'\n\n # Default value 'master'\n version: 'master'\n\n # Namespace of the package is parsed from URL if possible.\n # In case of the GITHUB workflow it corresponds to the project owner.\n namespace: 'pelkmanslab'\n\n # Also see https://github.com/pelkmanslab/iBRAIN/blob/master/README.md\n # on how to get access to pelkmanslab_github\n\n # If URL does ends with .tar.gz or .zip then git is assumed.\n # url: 'https://github.com/pelkmanslab/iBRAIN'\n url: 'pelkmanslab_github:pelkmanslab/iBRAIN'\n\n # More keys: homepage, sha1, md5\n\n -\n name: iBRAINModules\n url: 'pelkmanslab_github:pelkmanslab/iBRAINModules'\n\n'''\n # Write index to ~/.brainy/.packages_index\n brainy.config.update_packages_index(self.framework,\n yaml_data=packages_index)\n\n def find_frames_in_index(self, name, partial_match=True):\n packages_index = brainy.config.load_packages_index(self.framework)\n found = list()\n for frame in packages_index['packages']:\n # Put in the default values.\n frame = parse_frame(frame)\n # Match.\n name_is_a_match = name in frame['name'] if partial_match \\\n else name == frame['name']\n if name_is_a_match:\n logger.info('Found frame: %s' % frame['name'])\n found.append(frame)\n return found\n\n def get_formula(self, formula_path):\n if not os.path.exists(formula_path):\n raise FramesError('Missing formula (%s) in the package!' %\n formula_path)\n try:\n # Attempt to execute package frame with class code.\n script_globals = {}\n script_locals = {}\n execfile(formula_path, script_globals, script_locals)\n # We expect it to instantiate formula object and define it as\n # formula variable.\n if 'formula' not in script_locals:\n FramesError('Package does not define a formula (%s)!' %\n formula_path)\n return script_locals['formula']\n except SystemExit:\n logger.error('Got SystemExit error')\n raise FramesError('Failed to execute frame installation formula.')\n\n def download_frame(self, frame, package_path):\n logger.info('Downloading (%s) %s <- %s', frame['access_method'],\n frame['name'], frame['url'])\n if frame['access_method'].lower() == 'git':\n res = git.clone(frame['url'], package_path)\n if res.exit_code != 0:\n raise FramesError('Git clone failed: %s' % frame['url'])\n else:\n raise FramesError('Unknown access method: %s' %\n frame['access_method'])\n\n def apply_formula(self, formula_path, frame):\n formula = self.get_formula(formula_path)\n\n # Compare with frame information.\n if frame:\n # Checked that formula version and name are correct.\n assert frame['name'] == formula.name\n # TODO: proper version comparison\n # assert frame.version >= formula.version\n\n # Install the frame from formula.\n formula.install(frames=self)\n return formula\n\n def install_frame(self, frame, force_reinstall):\n '''Download package and run frame installation formula.'''\n package_path = os.path.join(self.cache_location, frame['name'])\n if os.path.exists(package_path):\n if force_reinstall:\n logger.warn('Purging package from cache: %s' % package_path)\n shutil.rmtree(package_path)\n else:\n raise FramesError('Package is already installed: %s ' %\n package_path + ' (maybe --force ?)')\n # Download package.\n self.download_frame(frame, package_path)\n assert os.path.exists(package_path)\n # Get its formula.\n formula_path = os.path.join(package_path, frame['name'] + '_frame.py')\n formula = self.apply_formula(formula_path, frame)\n\n # Finally save it into list of installed packages.\n self.packages = self.packages + [frame]\n\n # Done.\n logger.info(('Package \"%s\" version \"%s\" was successfully '\n 'installed into: %s') %\n (formula.name, formula.version, package_path))\n\n\nclass FrameFormula(object):\n '''\n Describes how to install the frame. Place it inside framework.\n Note: more less equivalent to `Formula` in `brew`.\n\n Effectively a frame is just a piece of python code kept in each packaged.\n After downloading the package brainy frames try to execute this code and\n let it cook the rest of installation.\n\n Frames object is passed into the routine with information like location of\n the framework.\n\n Each derived object is called like: `FooFrame` where foo is a name of the\n package.\n '''\n\n def __init__(self, name, url, namespace='', version='',\n homepage='', sha1='', md5='', access_method='git'):\n self.name = name\n self.url = url\n self.namespace = namespace\n self.version = version\n self.homepage = homepage\n self.sha1 = sha1\n self.md5 = md5\n self.access_method = access_method\n\n def as_dict(self):\n return {\n 'name': self.name,\n 'url': self.url,\n 'namespace': self.namespace,\n 'version': self.version,\n 'homepage': self.homepage,\n 'sha1': self.sha1,\n 'md5': self.md5,\n 'access_method': self.access_method,\n }\n\n def install(self, frames):\n '''Implement it in derived classes of package formulas.'''\n","repo_name":"brainy-minds/brainy","sub_path":"src/brainy/packages.py","file_name":"packages.py","file_ext":"py","file_size_in_byte":8864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"45353458843","text":"def testNumberD():\r\n # note the 'D' in all the function names allows me to have variables of the same name (without the 'D')\r\n # tests if an input is a valid number\r\n while 1 == 1: # causes input request to repeat until a valid input is given\r\n Input = input()\r\n try:\r\n int = (format(float(Input), '.2f')) # tests if input can be put in ##.## format\r\n except:\r\n print(\"That was not a valid number. Please try again.\")\r\n else:\r\n return float(Input) # returns the value as a float\r\ndef testWordD(word1, word2):\r\n # tests if an input is valid (valid inputs are word1 and word2)\r\n while 1 == 1: # causes input request to repeat until a valid input is given\r\n Input = input()\r\n if word1 == Input or word2 == Input:\r\n return Input # returns the input\r\n else:\r\n print(\"That was not a valid response. Please try again.\")\r\ndef checkD(n):\r\n # checks if the user has entered the proper input\r\n print(\"You have entered '\" + str(n) + \"'. Is this correct? Please enter 'yes' or 'no'\")\r\n return testWordD(\"yes\", \"no\") # tests if the user entered yes or no\r\ndef productTitleD():\r\n # determines the product title\r\n while 1 == 1: # causes input request to repeat until a valid input is given\r\n productTitle = input(\"Please enter a product title: \")\r\n test = checkD(productTitle) # checks if the user entered the proper title\r\n if test == \"yes\":\r\n return productTitle\r\ndef productCostPerUnitD():\r\n # determines the CPU of the product\r\n print(\"Please enter the estimated cost per unit of the product: \")\r\n productCost = testNumberD() # tests if the input is a valid number\r\n print(\"Please enter the estimated tax percentage(for 7%, enter '7'): \")\r\n tax = testNumberD() / 100 # tests if the input is a valid number and divides by 100\r\n tax += 1 # adds 1 to tax\r\n return productCost, tax # returns both the product cost and tax\r\ndef smartPricingD():\r\n # determines if a user would like to enable smart pricing as described below\r\n print(\"Smart pricing will automatically decrease the cost of production based on the \"\r\n \"quantity being produced. 100+ units is 3% cheaper, 500+ is 5% and 1000+ is 10%.\"\r\n \"\\nWould you like to enable smart pricing? Please enter 'yes' or 'no'\")\r\n smartPricing = testWordD(\"yes\", \"no\") # tests if the user entered yes or no\r\n if smartPricing == \"yes\":\r\n print(\"Smart pricing is now enabled.\")\r\n return smartPricing\r\ndef productQuantityD():\r\n # determines the quantity of the product being bought\r\n print(\"Please enter the number of units you would like produced: \")\r\n productQuantity = testNumberD() # tests if the input is a valid number\r\n if smartPricing == \"yes\": # determines the discount given from smart pricing\r\n if productQuantity >= 1000:\r\n discount = .90\r\n elif productQuantity >= 500:\r\n discount = .95\r\n elif productQuantity >= 100:\r\n discount = .97\r\n else:\r\n discount = 1\r\n else:\r\n discount = 1\r\n return productQuantity, discount # returns both the product quantity and discount\r\ndef productDescriptionD():\r\n # collects a product description\r\n productDescription = input(\"Please enter a product description or press enter to cancel: \\n\")\r\n if not productDescription: # returns a null value if the user presses enter without an input\r\n return None\r\n else:\r\n test = checkD(productDescription) # checks if the user entered the proper description\r\n if test == \"yes\":\r\n return productDescription\r\ndef calculateCostD(CPU, units, tax, smartPricing, discount):\r\n # calculates the total price with and without tax\r\n if smartPricing != \"yes\":\r\n totalPriceNoTax = CPU * units # calculates the total price with tax\r\n totalPriceWithTax = totalPriceNoTax * tax # calculates the total price without tax\r\n elif smartPricing == \"yes\":\r\n totalPriceNoTax = CPU * units * discount # calculates the total price with tax\r\n totalPriceWithTax = totalPriceNoTax * tax # calculates the total price without tax\r\n return totalPriceNoTax, totalPriceWithTax # returns the total price with and without tax\r\n\r\nprint(\"Hello, welcome to this Program! It was designed to calculate the total cost of a wholesale purchase.\\n\"\r\n \"You may enter multiple items into the system; however, results will only be given for one product at a time.\")\r\nprint(\"To properly enter a product into the system, you will need a: product title, \"\r\n \"product cost, and production quantity.\\nYou may choose to add a product description as well.\")\r\n# welcome messages\r\n\r\nprint(\"How many products would you like to enter?\")\r\nnumberOfProducts = int(testNumberD()) # tests if the input is a valid number and turns it into an integer\r\n# determines the number of products the user would like to calculate the price for\r\n\r\nfor x in range(0, numberOfProducts):\r\n productTitle = productTitleD() # defines product title\r\n\r\n print(\"Would you like to enter a product description? Please enter 'yes' or 'no'\")\r\n preference = testWordD(\"yes\", \"no\")\r\n # determines if user would like to enter a product description\r\n\r\n if preference == \"yes\":\r\n productDescription = productDescriptionD()\r\n else:\r\n productDescription = None\r\n # defines product description\r\n\r\n placeHolder = productCostPerUnitD() # placeholder for defining product CPU and tax\r\n productCostPerUnit = placeHolder[0]\r\n tax = placeHolder[1]\r\n\r\n smartPricing = smartPricingD() # determines if user would like smart pricing\r\n\r\n placeHolder = productQuantityD() # placeholder for defining product quantity and discount\r\n productQuantity = placeHolder[0]\r\n discount = placeHolder[1]\r\n\r\n placeHolder = calculateCostD(productCostPerUnit, productQuantity, tax, smartPricing, discount)\r\n # placeholder for defining product cost with and without tax\r\n totalCostNoTax = placeHolder[0]\r\n totalCostWithTax = placeHolder[1]\r\n\r\n if productDescription != None:\r\n print(\"Your project description for\", productTitle, \"is: \", productDescription)\r\n # prints the product description if there is one\r\n\r\n print(\"If you were to purchase\", format(productQuantity, '.0f'), productTitle + \", it would cost $\"\r\n + format(totalCostNoTax, '.2f'), \"without tax and $\" + format(totalCostWithTax, '.2f'), \"with tax.\\n\")\r\n # prints the total price with and without tax\r\n","repo_name":"RebeccaSheffey/Wholesale-purchase-order","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":6631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"36156039492","text":"import argparse\nimport json\nimport logging\n\nimport asyncio\nimport typing\n\nimport tornado.web\n\nimport ts3_api\nimport handlers\n\n\nasync def main(listen_addresses: typing.List[str], listen_port: int, api: ts3_api.TeamSpeak3ServerAPI):\n\tapp = tornado.web.Application([\n\t\t(r\"/state\", handlers.StateHandler, {\"api\": api}),\n\t\t(r\"/clients/online\", handlers.OnlineClientsHandler, {\"api\": api}),\n\t\t(r\"/clients/online/(\\d+)\", handlers.OnlineClientInfoHandler, {\"api\": api}),\n\t\t(r\"/clients/known\", handlers.KnownClientsHandler, {\"api\": api}),\n\t\t(r\"/clients/known/(\\d+)\", handlers.KnownClientInfoHandler, {\"api\": api}),\n\t])\n\n\tfor listen_address in listen_addresses:\n\t\tapp.listen(listen_port, listen_address)\n\n\tawait asyncio.Event().wait()\n\n\ndef get_cli_args():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\n\t\t\"--config\", \"-c\", default=\"config.json\",\n\t\thelp=\"Path to the configuration JSON file for the exporter.\"\n\t)\n\tparser.add_argument(\"--verbose\", \"-v\", action=\"store_true\", help=\"Be verbose about what is done.\")\n\tparser.add_argument(\"--debug\", \"-d\", action=\"store_true\", help=\"Output debug information (implies -v).\")\n\n\treturn parser.parse_args()\n\n\ndef setup_logging(verbose: bool, debug: bool):\n\tif debug:\n\t\tlog_level = logging.DEBUG\n\telif verbose:\n\t\tlog_level = logging.INFO\n\telse:\n\t\tlog_level = logging.WARNING\n\n\tlogging.basicConfig(\n\t\tlevel=log_level,\n\t\tformat=\"[%(asctime)s] %(levelname)8s: %(message)s\",\n\t\tdatefmt=\"%Y-%m-%d %H:%M:%S\"\n\t)\n\n\ndef load_config(config_path: str):\n\twith open(config_path, \"r\") as config_fh:\n\t\treturn json.load(config_fh)\n\n\ndef setup_ts3_api(host: str, scheme: str, port: int, virtual_server_id: int, token: str):\n\tapi = ts3_api.TeamSpeak3ServerAPI(host, scheme, port, virtual_server_id, token)\n\n\tversion_data = api.get_version()\n\tlogging.info(f\"Connected to TeamSpeak3 Server at {host} ({version_data['platform']}, {version_data['version']})\")\n\n\treturn api\n\n\nif __name__ == \"__main__\":\n\targs = get_cli_args()\n\tsetup_logging(args.verbose, args.debug)\n\tconfig = load_config(args.config)\n\tts3_api = setup_ts3_api(\n\t\tconfig[\"api\"][\"server_hostname\"],\n\t\tconfig[\"api\"][\"scheme\"],\n\t\tconfig[\"api\"][\"webquery_port\"],\n\t\tconfig[\"api\"][\"virtual_server_id\"],\n\t\tconfig[\"api\"][\"webquery_token\"]\n\t)\n\tasyncio.run(main(config[\"server\"][\"listen_addresses\"], config[\"server\"][\"listen_port\"], ts3_api))\n","repo_name":"poettig/teamspeak3_json_exporter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"18624311386","text":"# coding=utf-8\n\n# This file contains some default configuration for the table_extractor. Please, be aware of customization!\n\n# SETTINGS FOR pyTableExtractor\n\n# When using a online service, number of seconds between two tries\nSECONDS_BTW_TRIES = 2\n\n# Max number of attempts to contact a web service.\nMAX_ATTEMPTS = 3\n\n# Timeout for url request (write that in seconds)\nREQUEST_TIMEOUT = 5\n\n# Following are values used to compose urls of web services.\nSPARQL_CALL_FORMAT = \"&format=application%2Fsparql-results%2Bjson&debug=on\"\n\n\n# comment to write in mapping_rules.py\nCOMMENT_MAPPING_RULES = \"# coding:utf-8 \\n# Mapping rules used to map table's data, topics are used to evaluate \" +\\\n \"functions with same name.\"\n\n# mapping rule's prefix\nMAPPING_RULE_PREFIX = \"MAPPING_RULES_\"\n\n# check if a particular property is defined\nSPARQL_CHECK_IN_ONTOLOGY = \"ASK { ?s ?o }\"\n\nPREFIX_MAPPING_RULE = \"MAPPING_RULES_\"\n\n# Path where the pyTableExtractor dictionary is located\nPATH_ACTUAL_DICTIONARY = \"table_extractor/mapping_rules.py\"\n\n# enable filter to table's data to delete rows that summarize previous ones. (Like career rows in athlete)\nAPPLY_FILTER_TO_TABLE_DATA = True\n\n# check if property wrote by user in domain_settings.py are already in dbpedia or not\n# if a property isn't in dbpedia ontology, user will receive a message and it won't be created related triple\nCHECK_USER_INPUT_PROPERTY = False\n\n# SETTINGS FOR pyDomainExplorer\n# strings for settings file's header\nCODING_DOMAIN = \"# coding:utf-8 \\n\"\nRESEARCH_TYPE = \"RESEACH_TYPE\"\nOUTPUT_FORMAT_TYPE = \"OUTPUT_FORMAT_VALUE\"\nDOMAIN_TITLE = \"DOMAIN_EXPLORED\"\nCHAPTER = \"CHAPTER\"\n# prefix of section variable in domain_settings.py\nSECTION_NAME = \"SECTION_\"\n# character that separate two or more similar section\nCHARACTER_SEPARATOR = \"_tte_\"\n# name associated to property section in domain_settings.py\nSECTION_NAME_PROPERTY = \"sectionProperty\"\n# comments for user\nFIRST_COMMENT = \"# Comments below will help you in filling this file settings. Remember to change only \" +\\\n SECTION_NAME + \" variables.\\n# Please do not modify pyDomainExplorer parameters. \\n\\n\" \\\n \"# pyDomainExplorer parameters \"\nCOMMENT_FOR_EXAMPLE_PAGE = \"# Example page where it was found this section: \"\n\nCOMMENT_SECTION_PROPERTY = \"# The entry named \" + SECTION_NAME_PROPERTY + \" represents ontology property associated \" +\\\n \"to table's section.\\n\" \\\n \"# (Eg. in basket domain, section named playoff can be mapped with something like 'playoff' or \"\\\n \" 'playoffMatch').\\n# Triple example: \" \\\n \"\\n# \"\n\nCOMMENT_FILLED_ELEMENT = \"# Elements already filled means that I have already found that header\" \\\n \" in pyTableExtractor dictionary\\n# or on dbpedia ontology.\\n\" \\\n \"# If you empty a field that was filled, you will delete that rule from dictionary.\"\n\nCOMMENT_STRUCTURE = \"# Writing mapping rules is simple --> you have to fill all empty field remembering this\" \\\n \" structure:\\n# 'table's header':'ontology property' (Example: 'year':'Year', \" \\\n \"'GP':'gamesPlayed','High school name':'nameSchool'). \"\n\nRESOURCE_FILE = \"RESOURCE_FILE\"\nEND_OF_FILE = \"\\n# END OF FILE \\n\"\n\n\nNAME_OF_DOMAIN_EXPLORER_RESULT_FILE = \"domain_settings.py\"\n\n# Path where pyDomainExplorer print the result file .py\nFILE_PATH_DOMAIN_EXPLORED = \"domain_explorer/\" + NAME_OF_DOMAIN_EXPLORER_RESULT_FILE\n\n# Help for output format input\nOUTPUT_FORMAT_DEFAULT = '1'\n# possible output format values\nOUTPUT_FORMAT_CHOISES = [1, 2]\n# Help user on output format choose\nOUTPUT_FORMAT_HELP = \" Output format value can be 1,2. Value 1 list all headers for each section, while value \" \\\n \"2 write only one time a header.( Eg. if two sections named 'playoff' and 'regular season' has header \" \\\n \"'Year', with output format 2 you will see 'Year' only one time in file settings) \"\n\n# Help for chapter input\nCHAPTER_DEFAULT = 'en'\n\nCHAPTER_HELP = \"Language of Wikipedia pages/resources to analyze. \\n \\\n Please ensure you are using an existing wikipedia chapter tag! \\n \\\n Eg: 'it' ---> it.wikipedia.org \\n \\\n 'en' ---> en.wikipedia.org \\n \\\n 'fr' ---> fr.wikipedia.org etc. etc. \\n \\\n DEFAULT = \"+CHAPTER_DEFAULT\n\n# Here you have a general description of what the script (pyTableExtraction.py) do\nGENERAL_DESCRIPTION = \"This script try to parse data from tables in wiki pages.\\n \" \\\n \" To do so, it uses a WYSIWYG approach, using mapping rules \" \\\n \"over cells of data depending on topic, wiki chapter and on some other parameters.\" \\\n \"Data found are reorganized in a RDF dataset and serialized in turtle format.\"\n\n# Help for topic input\nTOPIC_HELP = \"Topic input. In this field you have to one of the mapping classes defined on dbpedia. (Eg.\" \\\n \"BasketballPlayer, Broadcaster) Go there: http://mappings.dbpedia.org/server/ontology/classes/ \" \\\n \"to see all available classes.\"\n\n# Single clause message help\nSINGLE_HELP = \"Search for a single resource, named like wikipedia page. Remember to include\" \\\n \" underscore in resource's name. (Eg. Kobe_Bryant or Mick_Jagger)\"\n\n# Where clause message help\nWHERE_HELP = \"Define a correct SPARQL where clause. It's important to name '?s' results given by query.\" \\\n \"(Eg. -w ' ?s foaf:name ?name. FILTER(?name = \\\"Kobe Bryant\\\"@it) \"\n\n# define different topic selected by user\nTOPIC_WHERE = \"SPARQL where clause defined\"\n\n# path where a file with all resources will created\nPATH_FOLDER_RESOURCE_LIST = \"Resource_lists\"\n\n# languages available in scripts\nLANGUAGES_AVAILABLE = [\"en\", \"it\", \"fr\", \"de\", \"pt\", \"es\"]\n\n# Query for getting DBpedia class resources\nSPARQL_GET_RESOURCES = [\"select ?s where{ \", \"}\"]\n\n# Query for verifying if there is a resource with a particular property\nSPARQL_CHECK_PROPERTY = [\"select ?s where{\", \" ?s rdfs:label \", \" } LIMIT 10\"]\n\n# which property's type I have to pick - I have found three different types: 'resource','ontology','property'\nONTOLOGY_TYPE = [\"ontology\"]\n\n# Queries to select a list of resources and the number of resources involved\nSPARQL_RES_LIST_QUERY = [\"SELECT distinct ?s as ?res WHERE{\", \"} LIMIT 1000 OFFSET \"]\n\n# Query to get number of resources involved in an execution\nSPARQL_NUM_RES_QUERY = [\"select (count(distinct ?s) as ?res_num) where{\", \"}\"]\n\n# number of wikipedia pages example that will be printed over section variables in domain_settings.py\nNUMBER_OF_WIKI_EXAMPLES = 3\n","repo_name":"dbpedia/table-extractor","sub_path":"table_extractor/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6803,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"86"} +{"seq_id":"35675059306","text":"\"\"\"A simple game of pong... in Python\n\nFrom:\n https://www.freecodecamp.org/news/python-projects-for-beginners/#pong-python-project\n\nSkills:\n - Python Turtle\n\nAdded items:\n - Parse command-line arguments\n - Customizable player settings (color, size, name)\n - Customizable game settings (background color, size, speed)\n - Object-oriented design\n\"\"\"\nimport argparse\nimport turtle\n\nclass Pong():\n def __init__(self, width, height, bgcolor, fgcolor, speed):\n self.board = turtle.Screen()\n self.board.title(\"Pong\")\n self.board.bgcolor(bgcolor)\n self.board.setup(width=width,height=height)\n self.board.tracer(0) # Force us to manually update the window instead of auto-updating\n self._speed = speed\n self.height = height // 2\n self.players = {}\n self.pen = turtle.Turtle()\n self.pen.speed(0)\n self.pen.color(fgcolor)\n self.pen.penup()\n self.pen.hideturtle()\n self.pen.goto(0, int(height*0.85))\n \n def set_player(self,player:'PongPlayer',moves:list):\n player_id = len(self.players.items())\n self.players[player_id] = player\n self.board.onkeypress(self.players[player_id].move_up,moves[0])\n self.board.onkeypress(self.players[player_id].move_down,moves[1])\n\n def drop_puck(self,pucksize:int,puckcolor:str):\n self.puck = PongPuck(pucksize,puckcolor,self.board.window_width(),self.board.window_height(),self._speed)\n\n def update_score(self):\n self.pen.clear()\n self.pen.write(\"{}: {} {}: {}\".format(self.players[0].get_name(),self.players[0].get_score(),self.players[1].get_name(),self.players[1].get_score()),align=\"center\",font=(\"Courier\",24,\"normal\"))\n self.pen.goto(0, int(self.height*0.85))\n\n def play(self):\n while(True):\n self.board.update()\n score = self.puck.move(self.players)\n\n if score == -2:\n # player A scored\n self.players[0].score()\n if score == 2:\n # player B scored\n self.players[1].score()\n\n self.update_score()\n for player_id in self.players.keys():\n if self.players[player_id].get_score() == \"5\":\n print(\"{} has won!!\".format(self.players[player_id].get_name()))\n print(\"Final score: {}: {} {}: {}\".format(self.players[0].get_name(),self.players[0].get_score(),self.players[1].get_name(),self.players[1].get_score()))\n return\n\n def listen(self):\n self.board.listen()\n\nclass PongPuck():\n def __init__(self,pucksize,puckcolor,width,height,speed=1):\n self.puck = turtle.Turtle()\n self.puck.speed(0) # Fastest animation speed\n self.puck.shape(\"square\")\n self.puck.shapesize(stretch_wid=pucksize,stretch_len=pucksize)\n self.puck.color(puckcolor)\n self.puck.penup()\n self.puck.goto(0,0)\n self.dx = 2\n self.dy = 2\n self.speed = speed\n self.max_x = width // 2\n self.min_x = -width // 2\n self.max_y = height // 2\n self.min_y = -height // 2\n \n def move(self,players:dict) -> int:\n puck_x = self.puck.xcor()\n puck_y = self.puck.ycor()\n\n # Bounce off the ceiling or floor\n if puck_y >= self.max_y or puck_y <= self.min_y:\n self.dy *= -1\n\n # Bounce hit the left or right side\n if puck_x >= self.max_x or puck_x <= self.min_x:\n self.speed = 1\n self.puck.goto(0,0)\n self.dx *= -1\n # player A == -2, player B == 2\n return self.dx\n\n else:\n for (name,player) in players.items():\n (left,right) = player.get_x_range()\n (top,bottom) = player.get_y_range()\n if left < 0 and right < 0 and puck_x < 0:\n # player A bounces\n if left < (puck_x - 5) <= right and bottom <= puck_y <= top:\n self.dx *= -1\n self.speed *= 1.1\n\n \n if left > 0 and right > 0 and puck_x > 0:\n if left <= (puck_x + 5) < right and bottom <= puck_y <= top:\n self.dx *= -1\n self.speed *= 1.1\n\n self.puck.setx(puck_x + ( self.dx * self.speed))\n self.puck.sety(puck_y + ( self.dy * self.speed))\n\n return 0\n\n \nclass PongPlayer():\n def __init__(self,player_name,player_size,player_color,start,board_height,speed=1):\n self.player = turtle.Turtle()\n self.player.speed(0)\n self.player.shape(\"square\")\n self.player.shapesize(stretch_wid=player_size,stretch_len=1)\n self.player.color(player_color)\n self.player.penup()\n self.player.goto(start,0)\n self.name = player_name\n self.length = 20 * player_size\n self.max_y = board_height // 2\n self.min_y = -board_height // 2\n self.speed = speed\n self._score = 0\n\n def move_up(self):\n y = self.player.ycor()\n y += 10 * self.speed\n if y < self.max_y:\n self.player.sety(y)\n\n def move_down(self):\n y = self.player.ycor()\n y -= 10 * self.speed\n if y > self.min_y:\n self.player.sety(y)\n\n def get_y_range(self):\n return ( self.player.ycor() + (self.length // 2), self.player.ycor() - (self.length // 2 ) )\n\n def get_x_range(self):\n return ( self.player.xcor() - 10, self.player.xcor() + 10 )\n\n def get_name(self) -> str:\n return str(self.name)\n\n def get_score(self) -> str:\n return str(self._score)\n\n def score(self):\n self._score += 1\n self.speed *= 1.1\n\nparser = argparse.ArgumentParser(description=\"A 'simple' game of Pong... in Python.\")\n# Board options\nparser.add_argument(\"--height\",\"-y\",action=\"store\",type=int,help=\"Height (y dimension) of board.\",default=600)\nparser.add_argument(\"--width\",\"-x\",action=\"store\",type=int,help=\"Width (x dimension) of the board\",default=800)\nparser.add_argument(\"--bgcolor\",\"-b\",action=\"store\",help=\"Background color\",default=\"black\")\nparser.add_argument(\"--fgcolor\",\"-f\",action=\"store\",help=\"Color of the text on the screen\",default=\"white\")\n# Player 1 options\nparser.add_argument(\"--player1\",\"-1\",action=\"store\",help=\"Name of Player 1\", default=\"Player1\")\nparser.add_argument(\"--p1color\",\"-p\",action=\"store\",help=\"Player 1 color\",default=\"white\")\nparser.add_argument(\"--p1size\",\"-s\",action=\"store\",type=int,help=\"Player 1 paddle size multiplier\",default=5)\nparser.add_argument(\"--p1up\",\"-u\",action=\"store\",help=\"Key to move player 1 up\",default=\"w\")\nparser.add_argument(\"--p1down\",\"-l\",action=\"store\",help=\"Key to move player 1 down\",default=\"s\")\n# Player 2 options\nparser.add_argument(\"--player2\",\"-2\",action=\"store\",help=\"Name of Player 1\", default=\"Player2\")\nparser.add_argument(\"--p2color\",\"-P\",action=\"store\",help=\"Player 2 color\",default=\"white\")\nparser.add_argument(\"--p2size\",\"-S\",action=\"store\",type=int,help=\"Player 2 paddle size multiplier\",default=5)\nparser.add_argument(\"--p2up\",\"-U\",action=\"store\",help=\"Key to move player 1 up\",default=\"i\")\nparser.add_argument(\"--p2down\",\"-L\",action=\"store\",help=\"Key to move player 1 down\",default=\"k\")\n# Puck options\nparser.add_argument(\"--puck\",\"-k\",action=\"store\",help=\"Puck color\",default=\"white\")\nparser.add_argument(\"--pucksize\",\"-z\",action=\"store\",type=int,help=\"Puck size multiplier\",default=1)\nparser.add_argument(\"--speed\",\"-d\",action=\"store\",type=int,help=\"Speed of the puck\",default=1)\n\nargs = parser.parse_args()\n\nboard = Pong(width=args.width,height=args.height,bgcolor=args.bgcolor,fgcolor=args.fgcolor,speed=args.speed)\nboard.listen()\n\ntry:\n board.set_player(PongPlayer(args.player1,args.p1size,args.p1color,((-args.width//2) + 10),args.height),[args.p1up,args.p1down])\n board.set_player(PongPlayer(args.player2,args.p2size,args.p2color,(( args.width//2) - 10),args.height),[args.p2up,args.p2down])\n board.drop_puck(args.pucksize,args.puck)\nexcept Exception as e:\n print(\"Configuration error setting up the game.\" + str(e))\nelse:\n # Main game loop\n board.play()\n","repo_name":"mjbroekman/python-fcc","sub_path":"pong/pong.py","file_name":"pong.py","file_ext":"py","file_size_in_byte":8197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"15676636289","text":"import json\nfrom concurrent.futures import ThreadPoolExecutor\nfrom datetime import datetime\n\nfrom .memoryMonitor import MemoryMonitor\n\n\nclass loggable_operator(object):\n def __call__(self, f):\n def wrapped_f(*args, **kwargs):\n if \"logger\" in kwargs and kwargs[\"logger\"] != None:\n with ThreadPoolExecutor() as executor:\n monitor = MemoryMonitor()\n mem_thread = executor.submit(monitor.measure_usage)\n startTime = datetime.now()\n try:\n f_thread = executor.submit(f, *args, **kwargs)\n return f_thread.result()\n finally:\n monitor.keep_measuring = False\n log_data = {\n \"module\": f.__module__,\n \"operator\": f.__name__,\n \"start_time\": startTime.timestamp(),\n \"duration\": (datetime.now() - startTime).total_seconds(),\n \"peak_memory_usage\": mem_thread.result()\n }\n kwargs[\"logger\"].append_log(log_data)\n else:\n return f(*args, **kwargs)\n return wrapped_f\n\n\nclass Logger:\n def __init__(self):\n self.log_stack = []\n self.current_log_level = self.log_stack\n self.log_levels_stack = [self.log_stack]\n\n def start_running_log(self, log_data={}, new_level_name=\"\"):\n self.log_levels_stack.append(self.current_log_level)\n log_data[\"start_time\"] = datetime.now().timestamp()\n self.current_log_level.append(log_data)\n log_data[new_level_name] = []\n self.current_log_level = log_data[new_level_name]\n\n def append_log(self, log_data={}):\n self.current_log_level.append(log_data)\n\n def end_running_log(self, additional_log_data={}):\n self.current_log_level = self.log_levels_stack.pop()\n running_log = self.current_log_level[-1]\n running_log.update(additional_log_data)\n running_log[\"duration\"] = (datetime.now(\n ) - datetime.fromtimestamp(running_log[\"start_time\"])).total_seconds()\n\n def write_log(self, file_name=None):\n file_name = f\"./log/log_{datetime.now().strftime('%d-%m-%y-%H:%M:%S')}.json\" if file_name == None else file_name\n with open(file_name, \"w\") as log_file:\n json.dump(self.log_stack, log_file, indent=2)\n\n def print_log(self):\n print(self.log_stack)\n\n def concat_logger(self, logger):\n self.log_stack += logger.log_stack\n\n def log_error(self, error_data):\n while len(self.log_levels_stack) > 1:\n self.end_running_log(additional_log_data=error_data)\n","repo_name":"apersonnaz/EDA4Sum","sub_path":"app/pipelines/tools/operator_logging.py","file_name":"operator_logging.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"33445877942","text":"# -*- coding: utf-8 -*-\n\nfrom collections import Counter\nimport sys, getopt, argparse, re, math\n\n# This is the main function of the code which calculates the CITO scores\n# for a text and returns them and their variables as a tuple\n\ndef mainCITO(text):\n\n\t# Instantiates various variables\n\tcommon = 'database/common.txt' #text file of common words (hardcoded)\n\tlettersCount = 0\n\ttotLetters = 0\n\ttotSentences = 0\n\tavgWords = 0\n\ttotWords = 0\n\tavgLetters = 0\n\tallWords = \"\"\n\n\t# Loops through all sentences in the text, removes various punctuation marks\n\t# and counts the words and letters.\n\tsentences = text.splitlines()\t\n\tfor sentence in sentences:\n\t\tif sentence:\n\t\t\twordCount = 0\n\t\t\tif sentence:\n\t\t\t\ttotSentences += 1\n\t\t\twords = re.split('\\s+',sentence)\n\t\t\twordCount += len(words)\n\t\t\tfor word in words:\n\t\t\t\tlettersCount = len(word)\n\t\t\t\ttotLetters += lettersCount\n\t\t\t\tallWords += word + ' '\n\t\t\ttotWords += wordCount\n\t\n\t# Count up all unique words and calculate the type-token-frequency\n\tuniqueWords = Counter(allWords.split())\n\ttypeTokenFrequency = (len(uniqueWords) * 1.0) / totWords\n\t\n\t# Opens the text file of common words\n\tcommonFile = open(common)\n\tcommonText = commonFile.read()\n\tcommonWords = re.split(',', commonText)\n\ttotCommonWords = 0\n\t\n\t# Counts how many words in the text are common words\n\tfor commonWord in commonWords:\n\t\ttotCommonWords = totCommonWords + uniqueWords[commonWord]\n\n\t# Calculations for some of the variables in the CITO formulas\n\t# The '*1.0' are fixes for integer divisions\n\tfreqCommonWords = (totCommonWords * 1.0) / (totWords*1.0) \n\tavgWords = totWords/(totSentences * 1.0)\n\tavgLetters = totLetters/(totWords * 1.0)\n\n\tCLIB = round(46 - 6.603 * avgLetters + 0.474 * freqCommonWords - 0.365 * typeTokenFrequency + 1.425 * avgWords)\n\tCILT = round(105 - (114.49 + 0.28 * freqCommonWords - 12.33 * avgLetters))\n\t\n\treturn (CLIB, CILT, avgLetters, freqCommonWords, typeTokenFrequency, avgWords)\n\n\n# This function states the commandline arguments that are needed\n# for the program to run.\n# if __name__ == \"__main__\":\n# \tparser = argparse.ArgumentParser()\n# \tparser.add_argument(\"-corpus\", \"--corpus\", help=\"Textfile of corpus\", default=\"input.txt\")\n# \tparser.add_argument(\"-output\", \"--output\", help=\"Give the type of output, CLIB=CLIB score, CILT=CILT score, debug=info\", default=\"debug\")\n# \tparser.add_argument(\"-common\", \"--common\", help=\"Textfile of common words\", default=\"common.txt\")\n# \targs = parser.parse_args()\n# \tmain(args.corpus, args.output, args.common)\n","repo_name":"matthijsthoolen/leestmeer","sub_path":"Scripts/CITOscore_text.py","file_name":"CITOscore_text.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"72292865244","text":"from orders import Orders\nfrom drivers import Drivers\nfrom orderrepo import OrderRepo\nfrom driverrepo import DriverRepo\nimport validation as v \nclass Service:\n def __init__(self,drivers,orders):\n self.drivers = drivers\n self.orders = orders\n\n \n def add(self,id,distance):# we add an order and we validate first \n if v.add_validation(id,distance,self.drivers.get_list()) == True:\n order=Orders(id,distance)# we enter the oerder into the class order\n self.orders.append_function(order)# we add with the help of the repo\n return True\n else:\n return False\n\n def compute(self,id):\n price = 0\n driver=self.drivers.get_list()\n order= self.orders.get_list()\n for i in range(len(driver)):\n if driver[i].get_id() == int(id):\n for j in range(len(order)):\n if order[j].get_id() == int(id):\n price = float(price+2.5*order[j].get_distance())\n return price \n\n \n\n\n \n \n","repo_name":"filip-x/UniversityYear1","sub_path":"Year1Sem1/Fundamentele Programarii- altii/Test12-18-20019/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"30870961409","text":"import requests\nfrom telethon.tl.types import InputWebDocument\nfrom telethon import TelegramClient, events\nfrom starkfunc import check_if_subbed\nfrom telethon import custom, events, Button\nfrom telethon.tl.functions.users import GetFullUserRequest\nfrom telethon.tl.types import MessageEntityMentionName\nfrom Configs import Config\nfrom loggers import logging\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nimport os\nimport random\nimport re\nfrom math import ceil\nimport telethon\nfrom pymongo import MongoClient\nfrom main_startup.config_var import Config\nfrom pymongo.errors import ConnectionFailure\nfrom telethon import Button, custom, events, functions\nfrom dB import get_user_limit, add_user_to_db, get_all_users, dl_all_users, dl_one_user, add_hits_to_db, rm_all_hits, all_hit, rm_hit, hit_exists\n\nbot = TelegramClient(\"bot\", api_id=Config.API_ID, api_hash=Config.API_HASH)\nwarnerstarkbot = bot.start(bot_token=Config.BOT_TOKEN)\n\n\ntry:\n mongo_client = MongoClient(Config.MONGO_DB)\n mongo_client.server_info()\nexcept ConnectionFailure:\n print(\"Invalid Mongo DB URL. Please Check Your Credentials! Friday is Exiting...\")\n quit(1)\n\n@warnerstarkbot.on(events.NewMessage(pattern=\"^/start$\"))\nasync def hmm(event):\n if Config.JTU_ENABLE:\n \tstarky = await check_if_subbed(Config.CHANNEL_USERNAME, event, warnerstarkbot)\n \tif starky is False:\n \tawait event.reply(\"**I am Sorry To Say That, To Access Me You Have To Be The Member Of Our Channel To Use This Bot..!**\", buttons=[[custom.Button.url(\"Join Channel\", Config.CHANNEL_URL)]])\n \treturn\n st = await event.client(GetFullUserRequest(event.sender_id))\n user_text = f\"\"\"**Hello {st.user.first_name},\nWelcome To {Config.ACCOUNT_GEN_NAME} Account Generator Bot\n\nTo Know About commands type:\n/cmds\n\nBot Made With ❤️ By @DevseXpo**\n\"\"\" \n await event.reply(user_text) \n \n@warnerstarkbot.on(events.NewMessage(pattern=\"^/(help|cmds|commands|cmd|command)$\"))\nasync def cmds(event):\n if Config.JTU_ENABLE:\n \tstarky = await check_if_subbed(Config.CHANNEL_USERNAME, event, warnerstarkbot)\n \tif starky is False:\n \tawait event.reply(\"**I am Sorry To Say That, To Access Me You Have To Be The Member Of Our Channel To Use This Bot..!**\", buttons=[[custom.Button.url(\"Join Channel\", Config.CHANNEL_URL)]])\n \treturn\n st = await event.client(GetFullUserRequest(event.sender_id))\n help_text = f\"\"\"**Hello {st.user.first_name},\nMy Commands Are As Follows:\n\n/start - To Restart Bot..!\n/cmds - To Get Help Menu\n/generate - To Generate Zee5 Accounts\n/about - To Get Your Current Info\n\nShare And Support Us...❤️**\n\"\"\"\n await event.reply(help_text) \n \n@warnerstarkbot.on(events.NewMessage(pattern=\"^/(generate|gen|account)$\"))\nasync def hmm(event):\n if Config.JTU_ENABLE:\n \tstarky = await check_if_subbed(Config.CHANNEL_USERNAME, event, warnerstarkbot)\n \tif starky is False:\n \tawait event.reply(\"**I am Sorry To Say That, To Access Me You Have To Be The Member Of Our Channel To Use This Bot..!**\", buttons=[[custom.Button.url(\"Join Channel\", Config.CHANNEL_URL)]])\n \treturn\n hmmw = await event.reply(\"**Generating Account...Stay Tuned.**\")\n if get_user_limit(int(event.sender_id)) >= Config.GEN_LIMIT_PERDAY:\n await hmmw.edit(f\"**Your Daily Limit is exhausted, Kindly Contact the admins to increase ur limit\\n\\nBy The Way Daily Limit is {Config.GEN_LIMIT_PERDAY} accounts per day**\", buttons=[[custom.Button.url(\"Join Channel\", Config.CHANNEL_URL)]])\n return\n add_user_to_db(int(event.sender_id), int(1))\n hits = all_hit()\n sed = random.choice(hits)\n user_s = await warnerstarkbot.get_me()\n username = user_s.username\n email, password = sed.split(\":\")\n await hmmw.edit(\n f\"{Config.ACCOUNT_GEN_NAME} Account Generated. \\nEmail : {email} \\nPassword :{password} \\nYou Can Check Your Limit or Info By /about \\nGenerated By @{username}\",\n parse_mode=\"HTML\")\n \n@warnerstarkbot.on(events.NewMessage(pattern=\"^/reset$\"))\nasync def reset(event):\n if event.sender_id != Config.OWNER_ID:\n return\n dl_all_users()\n await event.reply(\"`Reset Sucessfull Done!`\") \n \n \n@warnerstarkbot.on(events.NewMessage(pattern=\"^/broadcast\"))\nasync def reset(event):\n if event.sender_id != Config.OWNER_ID:\n return\n error = 0\n ds = event.text.split(\" \", maxsplit=1)[1]\n ok = get_all_users()\n if not ok:\n await event.reply(\"Wut? No Users In Your Bot, But U Want To Broadcast. WTF\")\n return\n for s in ok:\n try:\n await warnerstarkbot.send_message(int(s['user']), ds)\n except:\n error += 1\n pass\n await event.reply(f\"Broadcast Done With {error} And Sucess in {len(ok) - error}!\") \n \nasync def clear_data():\n ok = get_all_users()\n if not ok:\n return\n for s in ok:\n try:\n await warnerstarkbot.send_message(int(s['user']), \"**Limit Has Been Reset , Generate Your Accounts Now !**\")\n except:\n error += 1\n pass\n dl_all_users()\n \n@warnerstarkbot.on(events.NewMessage(pattern=\"^/about$\"))\nasync def a(event):\n info_s = get_user_limit(event.sender_id)\n await event.reply(f\"**📡Your Account Information\\n\\nUser-ID : {event.sender_id} \\nLimit Used : {info_s} \\nLimit Left : {Config.GEN_LIMIT_PERDAY-info_s}**\")\n\n\nscheduler = AsyncIOScheduler(timezone=\"Asia/Kolkata\")\nscheduler.add_job(clear_data, trigger=\"cron\", hour=6)\nscheduler.start()\n\nprint(\"Bot Started Successfully\")\n\n\ndef startbot():\n warnerstarkbot.run_until_disconnected()\n\nif __name__ == \"__main__\":\n startbot()\n","repo_name":"DevsExpo/AccountGenBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5714,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"86"} +{"seq_id":"14807013203","text":"# -*- coding: utf-8 -*-\n\nfrom Common.Basic_method.httpbuild import RequestsUtils\nimport pytest\nimport allure\nfrom Common.Basic_method.get_yaml import ExtractYaml\n\n\n@allure.feature(\"许超测试\")\nclass Test_De:\n\n @pytest.mark.parametrize('yaml_data', ExtractYaml('xuchao', 'demo.yaml').get_yaml_value(),\n ids=['order/confirm/prescription'\n , 'order/index'\n , 'order/paging'\n , 'assistant/get/status'\n , 'order/detail'\n , '/assistant/assistant/list'\n , '/teacher/consult'\n , '/teacher/mine'\n , '/teacher/displayTab'\n , '/teacher/recommend'\n , '/project/getProjectAdvertising'\n , '/teacher/startChat'\n , '/teacher/isShowSwitch'\n , '/teacher/existRelate'\n , '/release/detail'\n , '/evaluate/choice'\n , '/teacher/advisorDetail'\n , '/teacher/relate'\n ,'/member/getPushLink'\n ,'/adviser/sendWaitPayNotice'\n # ,'/wx/isSub'\n ,'/adviser/toHomePushRel'])\n @pytest.mark.flaky(reruns=2, reruns_delay=5)\n def test_one(self, yaml_data):\n res = RequestsUtils.request(yaml_data['method'], yaml_data['url'], data=yaml_data['data'], key=yaml_data['key'])\n assert res['errno'] == yaml_data['Assert']['errno']\n\n\nif __name__ == '__main__':\n pytest.main()\n","repo_name":"chen-by-two/automan_master","sub_path":"testCase/xuchao/test_demo.py","file_name":"test_demo.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"15405099679","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n# url = 'https://archive.ics.uci.edu/ml/datasets.php'\n\n# # Lets use the requests get method to fetch the data from url\n\n# response = requests.get(url)\n# # lets check the status\n# status = response.status_code\n# print(status)\n\n# content = response.content # we get all the content from the website\n# soup = BeautifulSoup(content, 'html.parser') # beautiful soup will give a chance to parse\n\n\n# tables = soup.find_all('table', {'cellpadding':'3'})\n# # We are targeting the table with cellpadding attribute with the value of 3\n# # We can select using id, class or HTML tag , for more information check the beautifulsoup doc\n# table = tables[0] # the result is a list, we are taking out data from it\n# for td in table.find('tr').find_all('td'):\n# print(td.text)\n\nurl2 = 'http://www.bu.edu/president/boston-university-facts-stats/'\n\nresponse2 = requests.get(url2)\ncontent = response2.content # we get all the content from the website\nsoup = BeautifulSoup(content, 'html.parser')\n\ntables = soup.findAll('div', {\"class\": \"facts-wrapper\"})\n\nlist_of_tables = []\n\nfor i in tables:\n keys = []\n values = []\n temp_dict = {}\n i = str(i)\n category = i[i.find('
') + 4: i.find('
')]\n temp_dict['Category'] = category\n all_key_start_indexes = [x+7 for x in range(len(i)) if i.startswith('\"text\">', x)]\n all_key_end_indexes = [x for x in range(len(i)) if i.startswith('

', x)]\n\n for l in range(len(all_key_start_indexes)):\n keys.append(i[all_key_start_indexes[l]:all_key_end_indexes[l]])\n\n all_values_start_indexes = []\n for v in range(len(i)):\n if i.startswith('value\">', v):\n all_values_start_indexes.append(v+7)\n if i.startswith('value-text\">', v):\n all_values_start_indexes.append(v+12)\n all_values_end_indexes = [x for x in range(len(i)) if i.startswith('', x)]\n\n for m in range(len(all_values_end_indexes)):\n values.append(i[all_values_start_indexes[m]:all_values_end_indexes[m]])\n\n for r in range(len(keys)):\n temp_dict[keys[r]] = values[r]\n list_of_tables.append(temp_dict)\n\nwith open('data.json', 'w') as f:\n json.dump(list_of_tables, f)\n\n\n\n","repo_name":"zeerau/30DaysOfPython","sub_path":"day_022/web_scrapping.py","file_name":"web_scrapping.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"38183468287","text":"STEVILO_DOVOLJENIH_NAPAK = 10\n\nPRAVILNA_CRKA = '+'\nPONOVLJENA_CRKA = 'o'\nNAPACNA_CRKA = '-'\n\nZACETEK = 's'\nZMAGA = 'w'\nPORAZ = 'x'\n\nclass Igra:\n def __init__(self, geslo, crke=[]):\n self.geslo = geslo.upper()\n self.crke = crke\n\n # int vedno definiras ko odpres vlass, vse te sprem self. sahranis tuki ni dobra praksa kjer koli umes\n\n\n def pravilne_crke(self):\n return [crka for crka in self.crke if crka in self.geslo] \n \n def napacne_crke(self):\n return [crka for crka in self.crke if crka not in self.geslo]\n\n def stevilo_napak(self):\n return len(self.napacne_crke())\n\n def zmaga(self):\n for crka in self.geslo:\n if crka in self.crke:\n return False\n return True\n\n def poraz(self):\n return self.stevilo_napak() > STEVILO_DOVOLJENIH_NAPAK\n\n def pravilni_del_gesla(self):\n izpis = ''\n for crka in self.geslo:\n if crka in self.pravilne_crke():\n izpis += crka\n else:\n izpis += '_'\n return izpis\n\n def nepravilni_ugibi(self):\n return ' '.join(self.napacne_crke())\n\n def ugibaj(self, crka):\n velika_crka = crka.upper()\n if velika_crka in self.crke:\n return PONOVLJENA_CRKA\n self.crke.append(velika_crka)\n if self.zmaga():\n return ZMAGA\n elif self.poraz():\n return PORAZ\n else: \n if velika_crka in self.pravilne_crke():\n return PRAVILNA_CRKA\n elif velika_crka in self.napacne_crke():\n return NAPACNA_CRKA\n\nbazen_besed = []\nwith open('besede.txt') as f:\n for vrstica in f:\n bazen_besed.append(vrstica.strip())\n\ndef nova_igra():\n import random\n izbrana_beseda = random.choice(bazen_besed)\n return Igra(izbrana_beseda)\n\nclass Vislice:\n def __init__(self):\n #pogosta napaka pr intu napisat self _ metoda\n self.igre = {}\n\n def prost_id_igre(self):\n return len(self.igre)\n\n def nova_igra(self):\n id = self.prost_id_igre()\n igra = nova_igra()\n self.igre[id] = (igra, ZACETEK)\n # vislice sef ko hocm igrt novo igro poklicem to igro\n return id\n \n def ugibaj(self, id_igre, crka):\n (igra,stanje) = self.igre[id_igre]\n # dobimo katero stevilko igre klicemo (par)\n novo_stanje = igra.ugibaj(crka)\n # to mi vraca zmaga,...\n self.igre[id_igre] = (igra, novo_stanje)\n\n\n\n\n\n\n","repo_name":"Nina2809/Vislice1","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"sh","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"41185153208","text":"import matplotlib.pyplot as plt\n\nclass CyclicalLr:\n def __init__(self, schedule, half_cycle_length: int):\n self.schedule = schedule\n self.half_cycle_length = half_cycle_length\n self.forward = True\n \n def step(self, epoch = None):\n if epoch is not None:\n raise NotImplementedError\n \n inc = 1 if self.forward else -1\n \n self.schedule.step(self.schedule.last_epoch + inc)\n self.update_direction()\n \n def update_direction(self):\n if self.schedule.last_epoch == self.half_cycle_length:\n self.forward = False\n \n if self.schedule.last_epoch == 0:\n self.forward = True\n \nclass RestartsLr:\n def __init__(self, schedule_fn, step_size: int, step_size_multiplier: int = 1):\n self.schedule = schedule_fn(step_size)\n self.step_size = step_size\n self.schedule_fn = schedule_fn\n self.step_size_multiplier = step_size_multiplier\n \n def step(self, epoch = None):\n if epoch is not None:\n raise NotImplementedError\n \n epoch = self.schedule.last_epoch + 1\n \n if epoch > self.step_size:\n epoch = 0\n self.step_size = self.step_size * self.step_size_multiplier\n self.schedule = self.schedule_fn(self.step_size)\n \n self.schedule.step(epoch)\n \n\ndef get_lr(optim) -> float:\n return optim.state_dict()[\"param_groups\"][0][\"lr\"]\n\n\ndef test_scheduel(schedual, optim, ittrs):\n lrs = []\n\n for i in range(ittrs):\n schedual.step()\n lrs.append(get_lr(optim))\n\n plt.semilogy(range(len(lrs)), lrs)\n \n","repo_name":"iamhectorotero/generative-audio-inpainting","sub_path":"libraries/rml/utils/annealing.py","file_name":"annealing.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"86"} +{"seq_id":"32580071742","text":"from time import sleep\nfrom Adafruit_ADS1x15 import ADS1115\n\n################ CONFIGS ##################################\nsamples_per_sec = 4\nrun_time = 600 # Requested runtime in seconds\namps_channel = 0 # ADC channel for the current sensor on ADS1115\nvolts_channel = 1 # ADC channel for the voltage sensor on ADS1115\n###########################################################\n\ntime_array = [] # Time array\namps = [] # Amp array\nvolts = [] # Voltage array\n\nsample_rate = 1 / samples_per_sec # Sample rate in samples per second\ndata_file = 'data.txt' # File to save and read data\n\nads = ADS1115()\n\nwith open(data_file, 'w') as file:\n pass # This does nothing, but it effectively clears the file\n\ndef main():\n time = 0\n while time < (run_time * samples_per_sec):\n time_array.append(time)\n amps.append(get_amps())\n volts.append(get_voltage())\n time += sample_rate\n save_data()\n sleep(sample_rate)\n\ndef get_amps():\n try:\n print(\"Reading current sensor...\")\n value = ads.read_adc(amps_channel, gain=1)\n voltage = value / 32767.0 * 4.096 # Assuming gain=1 and VDD=4.096V\n return round(voltage, 2)\n except:\n print(\"An error occurred while reading current sensor\")\n return None\n\ndef get_voltage():\n try:\n print(\"Reading voltage sensor...\")\n value = ads.read_adc(volts_channel, gain=1)\n voltage = value / 32767.0 * 4.096 # Assuming gain=1 and VDD=4.096V\n return round(voltage, 2)\n except:\n print(\"An error occurred while reading voltage sensor\")\n return None\n\ndef save_data():\n with open(data_file, 'a') as file:\n latest_time = time_array[-1]\n latest_amp = amps[-1]\n latest_volt = volts[-1]\n file.write(f\"{latest_time}\\t{latest_amp}\\t{latest_volt}\\n\")\n\nif __name__ == \"__main__\":\n main()\n print(\"Telemetry Script Stopped Successfully\")","repo_name":"Cgilrein/Aeronautics","sub_path":"telemetry.py","file_name":"telemetry.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"12861099486","text":"# Estimator class\n# -------------------------------\n# Molecular Properties Prediction\n# -------------------------------\n# The 'self.properties' dict will contain OBJECTS to calculate properties and rewards.\n# Each of those objects must implement at least 2 methods: \n# 1) 'predict': Gets an RDKit Mol object and returns a property value; and\n# 2) 'reward' : Gets a property value and returns a reward. \n\nimport importlib\nimport rdkit.Chem as Chem\n\nclass Estimators:\n\n def __init__(self, properties_cfg):\n self.properties = {}\n self.n_mols = 0\n self.all_converged = False\n \n for prop in properties_cfg:\n print(\"-\"*80)\n print(f\"Loading Property: {prop.upper()}\")\t\n module = importlib.import_module(f'properties.{prop}')\n module = getattr(module, prop)\n self.properties[prop] = module(prop,**properties_cfg[prop])\n print(f\"Done Loading Property: {prop.upper()}\")\t\n\n # Maximum possible reward per molecule\n max_reward = 0.0\n for _prop, _cls in self.properties.items():\n max_reward += _cls.rew_coeff * _cls.max_reward\n self.max_reward = max_reward\n print(\"-\"*80)\n \n print(\"Done reading properties.\")\n print(f\"The maximum possible reward per molecule is: {self.max_reward:6.2f}\")\n print( \"Note: Maximum rewards only consider properties being optimized.\")\n print(\"=\"*80)\n print(\"\\n\")\n\n def estimate_properties(self,mols):\n \"\"\"Calculates the properties for a list of molecules\n\n Args:\n mols ([RDKit ROMol]): List of RDKit ROMol objects\n properies (dict): Dictionary with properties as keys and details\n of predictor functions as values.\n Returns:\n Dict: Dictionary of properties as keys and predictions (floats) as values\n \"\"\"\n pred = {}\n for _prop in self.properties.keys():\n pred[_prop] = []\n\n _mols = []\n _mols.extend(mols)\n self.n_mols = len(_mols)\n \n for _prop, _cls in self.properties.items():\n predictions = _cls.predict(mols)\n pred[_prop] = predictions\n return pred\n\n def estimate_rewards(self, predictions):\n \"\"\"Calculates the rewards, given a dict of pre-calculated properties.\n\n Args:\n predictions (dict): Dictionary with properties as keys and lists of\n predicted values as values.\n properties (_type_): Dictionary with properties as keys and details\n of the property pbjects as values\n\n Returns:\n dict: Dict with property names as keys and rewards as values.\n \"\"\"\n\n rew = {}\n for _prop, cls in self.properties.items():\n if cls.optimize:\n _values = predictions[_prop]\n\n if len(_values) != self.n_mols:\n msg = ( \"ERROR: Something went wrong...\\n\"\n f\"Expecting {self.n_mols} values, but got only {len(_values)}\"\n f\"for property {_prop}.\")\n quit(msg)\n \n rew[_prop] = cls.reward(_values)\n else:\n rew[_prop] = [0.0] * self.n_mols\n rew[\"TOTAL\"] = self.total_reward(rew)\n return rew\n\n def total_reward(self, rewards):\n\n total_rew = []\n for mol in range(self.n_mols):\n total_rew_mol = 0.0\n for _prop, cls in self.properties.items():\n if cls.optimize:\n this_rew = rewards[_prop][mol] * cls.rew_coeff\n total_rew_mol += this_rew\n \n total_rew.append(total_rew_mol)\n return total_rew\n\n def check_and_adjust_thresholds(self, predictions):\n \"\"\"Checks if the predictions are within the thresholds and adjusts them\"\"\"\n self.all_converged = True\n for _prop, cls in self.properties.items():\n if cls.optimize:\n _values = predictions[_prop]\n cls.check_and_adjust_property_threshold(_values)\n\n # If anly property has not converged yet, \n # then the whole process has not converged\n if not cls.converged:\n self.all_converged = False\n return\n\n def smiles_reward_pipeline(self, smis, kwargs):\n \"\"\"\n Sometimes the RL process needs to pass the molecules as SMILES and needs\n to get the reward. This function does that.\n \n In sequence, \n 1) Generate molecules from SMILES\n 2) Estimate properties\n 3) Estimate rewards\n 4) Calculate total reward\n Returns the total reward for each molecule in the list.\n\n Args:\n smis ([str]): SMILES for the molecules to be evaluated\n kwargs: Any other arguments to be passed to the property objects\n\n Returns:\n [float]: Total reward for each molecule in the list\n \"\"\"\n\n mols = [Chem.MolFromSmiles(smi) for smi in smis]\n predictions = self.estimate_properties(mols)\n rewards = self.estimate_rewards(predictions)\n total_reward = self.total_reward(rewards)\n return total_reward\n \n","repo_name":"gmseabra/elion","sub_path":"src/elion/properties/Estimators.py","file_name":"Estimators.py","file_ext":"py","file_size_in_byte":5366,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"86"} +{"seq_id":"13146013526","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom mpl_toolkits.mplot3d import axes3d # required for 3d\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection # 3d polygons\n\nplt.ion()\n\n'''\nlet write some functions to help us plot '''\n\ndef plot_edges(axis, P, E, *args, **kwargs):\n for e in E:\n axis.plot(P[e,0], P[e,1], P[e,2], *args, **kwargs)\n\ndef plot_poly(axis, P, F, *args, **kwargs):\n poly = Poly3DCollection([P[f] for f in F], *args, **kwargs)\n axis.add_collection3d(poly)\n '''\n small workaround:\n the alpha property does not work so we have to provide the alpha as\n the 4th entry of an rgba color tuple. '''\n plt.pause(0.1) # pause to let object plot\n if 'alpha' in kwargs:\n colors = poly.get_facecolor()\n for c in colors:\n c[3] = kwargs['alpha']\n poly.set_color(colors)\n '''\n same deal with edgecolor.\n honestly, 3d polygons kinda suck.'''\n if 'edgecolor' in kwargs:\n poly.set_edgecolor(kwargs['edgecolor'])\n plt.pause(0.1) # update plot after property change\n return poly\n\n\n'''\ncan't use plt.subplots with 3d.\nhave to make figure and axis objects manually. '''\nfig = plt.figure(1, figsize=(9,7))\nax = np.array([[plt.subplot(2,2,2*i+j, projection='3d') for j in range(1,3)] for i in range(2)])\n\n'''\nwe have four axes in one figure, accessed as an array:\n ax[0,0] - top left\n ax[0,1] - top right\n ax[1,0] - bottom left\n ax[1,1] - bottom right\n just like a numpy array. '''\n\nplt.tight_layout()\n\nif __name__ == '__main__':\n P = np.array([[0, 1, 0], # an array of points\n [-1, 0.5, 1],\n [0, 0, -1],\n [1, 0, 0.5]])\n\n E = np.array([[0, 1], # an array of edges as indices of points in P\n [1, 2],\n [0, 2],\n [1, 3],\n [2, 3],\n [3, 0]])\n\n F = np.array([[0, 1, 2], # an array of faces as indices of points in P\n [0, 1, 3],\n [0, 2, 3],\n [1, 2, 3]])\n\n '''\n the scatter function adds a nice depth blur '''\n ax[0,0].scatter(P[:,0], P[:,1], P[:,2])\n\n '''\n lets plot the edges using our plot_edges function.\n *args and **kwargs are any additional arguments that have not been specified.\n *args collects all extra arguments not specified that are not keyword arguments as a list.\n (after the specified arguments and before the keyword arguments).\n **kwargs collects all extra keyword arguments as a dictionary.\n here we pass the argument 'black' with keyword c for color.\n Because our function passes all *args and **kwargs to plt.plot this allows us to specify\n properties of our edges such as color, linewidth, linestyle etc. '''\n plot_edges(ax[0,1], P, E, c='black')\n\n '''\n lets add the faces of our polyhedron '''\n ax[1,0].scatter(P[:,0], P[:,1], P[:,2], c='black')\n poly = plot_poly(ax[1,0], P, F, alpha=0.5, edgecolor='black')\n","repo_name":"shirtd/plotting","sub_path":"plot3d.py","file_name":"plot3d.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"24962484069","text":"import pytest\nfrom webdriver.bidi.modules.input import Actions, get_element_origin\nfrom webdriver.bidi.modules.script import ContextTarget\n\nfrom tests.support.helpers import filter_dict, filter_supported_key_events\nfrom .. import get_events\n\npytestmark = pytest.mark.asyncio\n\n\nasync def test_release_char_sequence_sends_keyup_events_in_reverse(\n bidi_session, top_context, load_static_test_page, get_focused_key_input\n):\n await load_static_test_page(page=\"test_actions.html\")\n await get_focused_key_input()\n\n actions = Actions()\n actions.add_key().key_down(\"a\").key_down(\"b\")\n await bidi_session.input.perform_actions(\n actions=actions, context=top_context[\"context\"]\n )\n # Reset so we only see the release events\n await bidi_session.script.evaluate(\n expression=\"resetEvents()\",\n target=ContextTarget(top_context[\"context\"]),\n await_promise=False,\n )\n await bidi_session.input.release_actions(context=top_context[\"context\"])\n expected = [\n {\"code\": \"KeyB\", \"key\": \"b\", \"type\": \"keyup\"},\n {\"code\": \"KeyA\", \"key\": \"a\", \"type\": \"keyup\"},\n ]\n all_events = await get_events(bidi_session, top_context[\"context\"])\n (events, expected) = filter_supported_key_events(all_events, expected)\n assert events == expected\n\n\n@pytest.mark.parametrize(\n \"release_actions\",\n [True, False],\n ids=[\"with release actions\", \"without release actions\"],\n)\nasync def test_release_mouse_sequence_resets_dblclick_state(\n bidi_session,\n top_context,\n get_element,\n load_static_test_page,\n release_actions\n):\n await load_static_test_page(page=\"test_actions.html\")\n reporter = await get_element(\"#outer\")\n\n actions = Actions()\n actions.add_pointer(pointer_type=\"mouse\").pointer_move(\n x=0, y=0, origin=get_element_origin(reporter)\n ).pointer_down(button=0).pointer_up(button=0)\n await bidi_session.input.perform_actions(\n actions=actions, context=top_context[\"context\"]\n )\n\n if release_actions:\n await bidi_session.input.release_actions(context=top_context[\"context\"])\n\n await bidi_session.input.perform_actions(\n actions=actions, context=top_context[\"context\"]\n )\n events = await get_events(bidi_session, top_context[\"context\"])\n\n expected = [\n {\"type\": \"mousedown\", \"button\": 0},\n {\"type\": \"mouseup\", \"button\": 0},\n {\"type\": \"click\", \"button\": 0},\n {\"type\": \"mousedown\", \"button\": 0},\n {\"type\": \"mouseup\", \"button\": 0},\n {\"type\": \"click\", \"button\": 0},\n ]\n\n if not release_actions:\n expected.append({\"type\": \"dblclick\", \"button\": 0})\n\n filtered_events = [filter_dict(e, expected[0]) for e in events]\n assert expected == filtered_events[1:]\n","repo_name":"servo/servo","sub_path":"tests/wpt/tests/webdriver/tests/bidi/input/release_actions/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":24247,"dataset":"github-code","pt":"86"} +{"seq_id":"12154369238","text":"\nimport os\nimport cv2\nimport numpy as np\n\n\nkmeans_cluster_path = \"/Users/didi/Desktop/kmeans-cluster/\"\n\nslic_cluster_path = \"/Users/didi/Desktop/slic-cluster/\"\n\nlabel_img_path = \"/Users/didi/Desktop/car-images/\"\n\n\n\ndef ap_function(kmeans, gt):\n row = kmeans.shape[0]\n column = kmeans.shape[1]\n u = 0\n p = 0\n for i in range(row):\n for j in range(column):\n if kmeans[i][j] != 0 and gt[i][j] != 0:\n u += 1\n if kmeans[i][j] != 0 and gt[i][j] == 0:\n p += 1\n return u / (p + u)\n\n\n# iou算法\ndef iou_function(kmeans, gt):\n row = kmeans.shape[0]\n column = kmeans.shape[1]\n u = 0\n p = 0\n for i in range(row):\n for j in range(column):\n if kmeans[i][j] != 0 and gt[i][j] != 0:\n u += 1\n if kmeans[i][j] != 0 or gt[i][j] != 0:\n p += 1\n return u/p\n\n\ndef _simple_iou_score(gt_image, pre_image):\n\n u = 0\n p = 0\n\n for i in range(len(gt_image)):\n if gt_image[i] !=0:\n u += gt_image[i]\n\n for i in range(len(pre_image)):\n if pre_image[i] !=0:\n p += pre_image[i]\n\n return u / (p + u)\n\n\ndef _simple_ap_score(gt_image, pre_image):\n u = 0\n p = 0\n\n for i in range(len(gt_image)):\n if gt_image[i] != 0:\n u += gt_image[i]\n\n for i in range(len(pre_image)):\n if pre_image[i] != 0:\n p += pre_image[i]\n\n return u / p\n\n\ndef _cal_iou_score(gt_image, pre_image):\n intersection = np.logical_and(gt_image, pre_image)\n union = np.logical_or(gt_image, pre_image)\n iou_score = np.sum(intersection) / np.sum(union)\n return iou_score\n\n\n\ndef _read_file_float(full_name):\n img = cv2.imread(full_name, 0)\n rows, cols = img.shape[:]\n data = img.reshape((rows * cols, 1))\n return np.float32(data)\n\n\ndef _open_compare_file(filename):\n str_list = filename.split(\".\")\n label_data = _read_file_float(label_img_path+str_list[0]+\"/\"+'label_viz.png')\n kmeans_data = _read_file_float(kmeans_cluster_path+filename)\n slic_data = _read_file_float(slic_cluster_path+filename)\n kmeans_iou_score = _simple_ap_score(label_data, kmeans_data)\n slic_iou_score = _simple_ap_score(label_data, slic_data)\n print('filename:%s kmeans_ap_score:%s vs slic_ap_score:%s' %(filename, kmeans_iou_score, slic_iou_score))\n\n\nif __name__ == '__main__':\n files = os.listdir(kmeans_cluster_path)\n for file in files:\n _open_compare_file(file)\n\n\n\n","repo_name":"wanghaoListening/python-study-demo","sub_path":"cv/iou_score_evaluate.py","file_name":"iou_score_evaluate.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"37419325254","text":"import sys\n\nes_endings = ['ch', 'sh', 'x', 's', 'z', 'o']\nvowels = ['a', 'e', 'i', 'o', 'u']\n#defining plural function\ndef plural(s):\n if s[-2:] in es_endings or s[-1:] in es_endings:\n s = s + \"es\"\n elif s[-1] == \"y\" and s[-2] not in vowels:\n s = s[:-1] + \"ies\"\n elif s[-1:] == 'f':\n s = s[:-1] + 'ves'\n elif s[-2:] == 'fe':\n s = s[:-2] + 'ves'\n elif s[-1:] == 'o':\n s = s + 'es'\n else:\n s = s + 's'\n\n return s\n\n\ndef main():\n for line in sys.stdin:\n print(plural(line.strip()))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alexoneill1/CA116","sub_path":"semester2_labs/lab_012/plural_012.py","file_name":"plural_012.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"70141568926","text":"import torch\nimport numpy as np\n\n\nfrom copy import deepcopy\nfrom core.utils.example_utils import to_im\nfrom torchvision.transforms import Resize\nfrom PIL import ImageFont, Image\nfrom collections import OrderedDict\n\n\ndef morph_checkpoints(ckpt_l, ckpt_r, alpha):\n new_checkpoint = {k: v for k, v in ckpt_l.items() if k not in ('state_dict', 'style_latents')}\n new_checkpoint['state_dict'] = OrderedDict()\n \n for k in ckpt_l['state_dict']:\n v1, v2 = ckpt_l['state_dict'][k].clone(), ckpt_r['state_dict'][k].clone()\n new_checkpoint['state_dict'][k] = alpha * v1 + (1 - alpha) * v2\n \n if 'style_latents' in ckpt_l or 'style_latents' in ckpt_r:\n new_checkpoint['da_type'] = 'im2im'\n \n \n if 'style_latents' in ckpt_l and 'style_latents' in ckpt_r:\n v1, v2 = ckpt_l['style_latents'].clone(), ckpt_r['style_latents'].clone()\n new_checkpoint['style_latents'] = alpha * v1 + (1 - alpha) * v2\n elif 'style_latents' in ckpt_l:\n new_checkpoint['style_latents'] = ckpt_l['style_latents'].clone()\n elif 'style_latents' in ckpt_r:\n new_checkpoint['style_latents'] = ckpt_r['style_latents'].clone()\n \n return new_checkpoint\n\n\ndef text_centered(image, message, font, fontColor):\n W, H = image.size\n image = image.copy()\n draw = ImageDraw.Draw(image)\n _, _, w, h = draw.textbbox((0, 0), message, font=font)\n draw.text(((W - w) / 2, (H - h) / 2), message, fill=fontColor, font=myfont)\n return image\n\n\nclass GIF:\n def __init__(\n self, model, initial_latents, caption_mode=None,\n steps_per_stage=20, steps_between=20, randomize_noise=True, img_size=256,\n font_style_p=\"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf\",\n font_size=16\n ):\n self.stack = []\n self.model = model\n self.lats = initial_latents\n self.step_stage = steps_per_stage\n self.step_between = steps_between\n self.randomize_noise = randomize_noise\n \n self.font = ImageFont.truetype(font_style_p, font_size)\n self.img_size = img_size\n \n self.stylized = False\n self.current_style = None\n self.caption_mode = caption_mode\n \n def caption_image(self, image, info):\n if self.caption_mode == 'text':\n image = self._text_caption(image, info)\n elif self.caption_mode == 'images_arrow':\n image = self._im_arrow_caption(image, info)\n return image\n \n def _text_caption(self, image, caption, fontColor=(0, 0, 0)):\n W, H = im.size\n\n image = Image.fromarray(np.ones((H // 3, W, 3), np.uint8) * 255)\n capt = text_centered(image, caption, self.font, fontColor)\n return Image.fromarray(np.vstack([im, capt]))\n \n def add_stage(\n self, stage_type, stage_info\n ): \n tmp_stage = []\n \n for self.step, self.alpha in enumerate(np.linspace(0, 1, self.step_stage)):\n if stage_type == 'unstylize':\n im = self.unstylize_stage(stage_info)\n elif stage_type == 'stylize':\n im = self.stylize_stage(stage_info)\n capt_info = {\n 'stylization': stage_info\n }\n elif stage_type == 'style_morphing':\n im = self.style_morphing_stage(stage_info)\n elif stage_type == 'lat_morphing':\n im = self.lat_morphing_stage(stage_info)\n \n im = to_im(Resize(self.img_size, antialias=True)(im))\n \n capt_info = None\n self.caption_image(im, capt_info)\n \n tmp_stage.append(im)\n \n self.stack.extend(tmp_stage)\n\n if self.step_between > 0:\n t = [deepcopy(im) for _ in range(self.step_between)]\n self.stack.extend(t)\n \n return self\n \n def style_morphing_stage(self, info):\n if not self.stylized:\n raise ValueError(\"To Launch style morphing stylisation stage is needed\")\n \n if self.step == 0:\n self.next_style_ckpt = torch.load(info)\n \n tmp_ckpt = morph_checkpoints(self.next_style_ckpt, self.current_style_ckpt, self.alpha)\n self.model._reset_trainable(tmp_ckpt)\n \n if self.next_style_ckpt['da_type'] == 'im2im' and self.current_style_ckpt['da_type'] == 'td':\n mn = self.alpha\n elif self.next_style_ckpt['da_type'] == 'td' and self.current_style_ckpt['da_type'] == 'im2im':\n mn = 1 - self.alpha\n elif self.next_style_ckpt['da_type'] == 'im2im' and self.current_style_ckpt['da_type'] == 'im2im':\n mn = 1\n else:\n mn = 0\n \n _, t_im = self.model(\n self.lats, input_is_latent=True, \n offset_power=1., mx_n=mn,\n randomize_noise=self.randomize_noise\n )\n \n if self.step + 1 == self.step_stage:\n self.current_style_ckpt = self.next_style_ckpt\n \n return t_im\n \n def lat_morphing_stage(self, info):\n \n if self.step == 0:\n self.next_person, self.next_lat = info\n \n tmp_lat = [\n self.next_lat[0] * self.alpha + self.lats[0] * (1 - self.alpha) \n ]\n _, t_im = self.model(\n tmp_lat, input_is_latent=True, \n offset_power=1., \n randomize_noise=self.randomize_noise\n )\n \n if self.step + 1 == self.step_stage:\n self.lats = self.next_lat\n \n return t_im\n \n def unstylize_stage(self, info):\n if self.step == self.step_stage - 1:\n self.stylized = False\n \n if self.current_style_ckpt['da_type'] == 'td':\n mn = 0\n else:\n mn = 1 - self.alpha\n \n _, t_im = self.model(\n self.lats, input_is_latent=True, \n offset_power=(1 - self.alpha), mx_n=mn,\n randomize_noise=self.randomize_noise\n )\n return t_im\n \n def stylize_stage(self, info):\n if self.step == 0:\n self.current_style_ckpt = torch.load(info)\n self.model._reset_trainable(\n self.current_style_ckpt\n )\n self.stylized = True\n \n _, t_im = self.model(\n self.lats, input_is_latent=True, \n offset_power=self.alpha, mx_n=self.alpha,\n randomize_noise=self.randomize_noise\n )\n \n return t_im\n \n def render(self, fp_out, fps=25):\n self.stack[0].save(\n fp_out,\n save_all=True, \n append_images=self.stack[1:], \n optimize=False, duration=1000/fps, loop=0\n )\n \n\ndef get_white(size_h, size_w):\n return np.ones((size_h, size_w, 3), dtype=np.uint8) * 255\n\n\ndef text_centered(image, message, font, fontColor):\n W, H = image.size\n image = image.copy()\n draw = ImageDraw.Draw(image)\n _, _, w, h = draw.textbbox((0, 0), message, font=font)\n draw.text(((W - w) / 2, (H - h) / 2), message, fill=fontColor, font=myfont)\n return image","repo_name":"AIRI-Institute/StyleDomain","sub_path":"SimilarDomains/core/utils/gif.py","file_name":"gif.py","file_ext":"py","file_size_in_byte":7125,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"86"} +{"seq_id":"1606306209","text":"from importlib.resources import files\nfrom pathlib import Path\n\nfrom pr1.units.base import Metadata, MetadataIcon, logger as parent_logger\n\nnamespace = \"timer\"\nversion = 0\n\nmetadata = Metadata(\n description=\"Timer\",\n icon=MetadataIcon(kind='icon', value=\"schedule\"),\n title=\"Timer\",\n version=\"2.0\"\n)\n\nclient_path = Path(files(__name__ + '.client'))\nlogger = parent_logger.getChild(namespace)\n\nfrom .parser import Parser\n","repo_name":"slietar/automancer","sub_path":"units/core/src/pr1_timer/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"15562884378","text":"#sorting lists of tuples using items() and sorted() functions\n\nimport re\n\n#import re.search() or re.findall()\n\nd = {'a':12, 'b':22, 'c':35}\nd.items()\n\nx = sorted(d.items())\n\nprint(x)\n\n#(value,key)\nfor deez,nuts in x:\n print(deez,nuts)\n \ntmp = list()\nfor deez,nuts in x:\n tmp.append( (deez,nuts) )\n\nprint(tmp)\ntmp = sorted(tmp, reverse=True)\nprint(tmp)\n\n#how to use get literally pulls from tuple\ncar = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\n\nx = car.get(\"model\")\n\nprint(x)\n\n#top 10 most common words in the file\n\n#dictionary for counting\nfhand = open('balancesheet.txt')\nthecount = dict()\n\n#split up each line\nfor line in fhand:\n spaces = line.split()\n#idiom to count words\n for word in spaces:\n thecount[word] = thecount.get(word, 0) + 1\n\n#now sort our key, values \n \nlst = list()\nfor key, val in thecount.items():\n newtup = (val, key)\n lst.append(newtup)\n \n#now we have list of tuples in VK order\n\nlst = sorted(lst, reverse=True)\n\n#go through first 10 of list\nfor val, key in lst[:10] :\n print(key, val)\n \n\n#lambdas where it all happens in one line\n\n#create an expression that acts as a generator of all the elements\n\nprint( sorted( [ (v,k) for k,v in d.items() ] ) )\n\n#stamp stamp stamp and producing list, list manufactured in the moment, sorted moves the list around and gives the sorted list, now sorted by key\n\n#Regular Expressions\n\nghand = open('balancesheet.txt')\nfor line in ghand:\n line = line.rstrip()\n#if doesnt find will return -1\n if line.find('financial') >=0:\n print(line)\nprint('NEXT UP')\n#how to incorporate regex? ex \\s or ^ or *\nhand = open('balancesheet.txt')\nfor dweeb in hand:\n dweeb = dweeb.rstrip()\n if re.search('calculate', dweeb) :\n print(dweeb)\n \nprint('OK NOW WE GETTIN IT')\n\n\nghand = open('balancesheet.txt')\nfor line in ghand:\n line = line.rstrip()\n if line.startswith('The') >=0:\n print(line)\nprint('YOU SEE IT')\n#the current is like saying at the beginning of line\nhand = open('balancesheet.txt')\nfor dweeb in hand:\n dweeb = dweeb.rstrip()\n if re.search('^The.*', dweeb) :\n print(dweeb)\n\n#regex expressions are to look for something \n#^ - to match start of a line\n#. - to match any character\n#* - many times\n\n#^X.*: then include -\\S only if any non-whitespace character\n#for X-Sieve: CMU Sieve 2.3\n\n#use regex to pull data from strings","repo_name":"filipdasilva/dailygrind","sub_path":"2-21.py","file_name":"2-21.py","file_ext":"py","file_size_in_byte":2411,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"41455272193","text":"#! /usr/bin/env python\n\nimport rospy\nimport numpy as np\nimport tf\nfrom tf.transformations import quaternion_from_euler, quaternion_multiply\nfrom human_pose_ROS.msg import Skeleton, PoseEstimation\nfrom rospy_message_converter import message_converter\nfrom std_msgs.msg import Float32\nfrom vision_utils.logger import get_logger, get_printer\nfrom vision_utils.timing import CodeTimer\nfrom pose_utils.utils import get_points_centroid, angle_from_centroid, cam_to_world, distance_between_points, vector_from_2_points\nfrom visualization_msgs.msg import Marker, MarkerArray\nfrom human_pose_ROS.msg import Skeleton, PoseEstimation\nimport vg\nimport argparse\n\nfrom pose_utils.utils import get_points_centroid, angle_from_centroid, cam_to_world, distance_between_points, vector_from_2_points\n\nlogger = get_logger()\npp = get_printer()\n\nCAM_FRAME = \"/wrist_camera_depth_optical_frame\"\n\nar_point = []\npred_point = []\npred_updated = False\n\ncounter_msg = dict()\nn_frames = 0\n\ndef skel_cb(msg):\n global ar_point, pred_point, counter_msg, n_frames\n if len(msg.skeletons) and msg.skeletons[0].dummy:\n ar_point = msg.skeletons[0].centroid\n logger.debug(\"AR point: {}\".format(ar_point))\n else:\n if len(msg.skeletons):\n if len(msg.skeletons[0].right_wrist):\n pred_point = msg.skeletons[0].right_wrist\n logger.debug(\"Pred point: {}\".format(pred_point))\n msg_dict = message_converter.convert_ros_message_to_dictionary(msg.skeletons[0])\n for jnt,p in msg_dict.items():\n if isinstance(p, list) and len(p):\n counter_msg[jnt] = counter_msg.get(jnt,0) + 1\n n_frames += 1\n print(counter_msg)\n\n\ndef ar_cb(msg):\n # tf_listener.waitForTransform('/world', CAM_FRAME, rospy.Time(), rospy.Duration(0.5))\n # (trans, rot) = tf_listener.lookupTransform('/world', CAM_FRAME, rospy.Time())\n # world_to_cam = tf.transformations.compose_matrix(translate=trans, angles=tf.transformations.euler_from_quaternion(rot))\n\n marker_pos = msg.pose.position\n # marker_tf = cam_to_world([marker_pos.x, marker_pos.y, marker_pos.z], world_to_cam)\n skel = Skeleton()\n pose = PoseEstimation()\n skel.centroid = [marker_pos.x, marker_pos.y, marker_pos.z]\n pose.skeletons.append(skel)\n pose_pub.publish(pose)\n # print(skel)\n\n\nrospy.init_node(\"ar_test\")\n\ntf_listener = tf.TransformListener()\nrospy.Subscriber(\"visualization_marker\",Marker,ar_cb)\nrospy.Subscriber(\"openpifpaf_pose_transformed_pose_world\",PoseEstimation,skel_cb)\npose_pub = rospy.Publisher(\"ar_skeleton\",PoseEstimation, queue_size=1)\nar_distance_pub = rospy.Publisher(\"ar_distance\",Float32, queue_size=1)\n\nwhile not rospy.is_shutdown():\n if len(ar_point) and len(pred_point):\n distance = distance_between_points(ar_point, pred_point)\n ar_distance_pub.publish(distance)\n print(\"n_frames: {}\".format(n_frames))\n logger.debug({k:float(v)/n_frames for k,v in counter_msg.items()})\n rospy.sleep(0.05)\n","repo_name":"glhr/human-pose-ROS","sub_path":"src/pose_utils/ar_tracker.py","file_name":"ar_tracker.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"72997621725","text":"import sys\nimport client_utils\nfrom time import time\nimport _thread\n\ndef main():\n\n print (\"\\n\")\n client_utils.instructions()\n client_id = str(round(time() * 1000))\n # for caching\n file_version_map = {}\n\n while True:\n \n client_input = sys.stdin.readline()\n\n if \"\" in client_input:\n while not client_utils.check_valid_input(client_input): # error check the input\n client_input = sys.stdin.readline()\n \n filename = client_input.split()[1] # get the filename from the input\n\n # response = _thread.start_new_thread(client_utils.handle_write, (filename, client_id, file_version_map)) # handle the write request\n response = client_utils.handle_write(filename, client_id, file_version_map) # handle the write request\n # print(response)\n # if \"success\" not in response:\n # print(\"Try again\")\n print (\"Exiting mode...\\n\")\n \n\n elif \"\" in client_input:\n while not client_utils.check_valid_input(client_input): # error check the input\n client_input = sys.stdin.readline()\n filename = client_input.split()[1] # get file name from the input\n client_utils.handle_read(filename, file_version_map, client_id) # handle the read request \n print(\"Exiting mode...\\n\")\n\n elif \"\" in client_input:\n while not client_utils.check_valid_input(client_input): # error check the input\n client_input = sys.stdin.readline()\n filename = client_input.split()[1] # get file name from the input\n filename = filename.split('.')[0] + '.txt' # .txt is default for now\n client_utils.handle_create(filename, file_version_map, client_id) # handle the read request \n \n elif \"\" in client_input:\n client_socket = client_utils.create_socket()\n client_utils.send_directory_service(client_socket, \"\", \"w\", True)\n client_socket.close()\n\n elif \"\" in client_input:\n client_utils.instructions()\n\n\n elif \"\" in client_input:\n print(\"Exiting application...\")\n sys.exit()\n\nif __name__ == \"__main__\":\n main()","repo_name":"Abdus8Samad/dfsPython","sub_path":"client_app.py","file_name":"client_app.py","file_ext":"py","file_size_in_byte":2352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"70909314525","text":"# -*- coding: utf-8 -*-\n\nimport multiprocessing\nimport time\n\n\ndef process(index):\n time.sleep(index)\n print(\"process : {0}\".format(index))\n\n\nif __name__ == \"__main__\":\n for i in range(5):\n p = multiprocessing.Process(target=process, args=(i,))\n p.start()\n print(\"CPU number: {0}\".format(multiprocessing.cpu_count()))\n for p in multiprocessing.active_children():\n print(\"Child process name: {0} id: {1}\".format(p.name, p.pid))\n print(\"Process Ended\")\n","repo_name":"Gedanke/Reptile_study_notes","sub_path":"codes/Module_1/lecture_6/lecture_6_2.py","file_name":"lecture_6_2.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"86"} +{"seq_id":"6146143946","text":"import os\nimport uuid\nimport json\nimport re\nfrom os.path import join\nimport lineup_widget\n\ndef slugify(text):\n text = text.lower()\n return re.sub(r'[\\W_]+', '-', text)\n\ndef for_website(plot, nb_name=None, plot_name=None, df=None):\n save_dir = os.getenv(\"C19_SAVE_FOR_WEB_DIR\", None)\n should_save_for_web = (save_dir != None and str(save_dir) != '0')\n\n if nb_name == None:\n nb_name = str(uuid.uuid4())[:8]\n if plot_name == None:\n plot_name = str(uuid.uuid4())[:8]\n\n nb_name = slugify(nb_name)\n plot_name = slugify(plot_name)\n\n if should_save_for_web:\n\n if type(plot) == lineup_widget.lineup.LineUpWidget:\n plot_json = plot._data\n else:\n plot_json = plot.to_dict()\n\n plot_id = f\"{nb_name}_{plot_name}\"\n\n plot_out_file = f\"plot_{plot_id}.json\"\n df_out_file = f\"data_{plot_id}.csv\"\n\n with open(join(save_dir, plot_out_file), \"w\") as f:\n json.dump(plot_json, f)\n \n if df is not None:\n df.to_csv(join(save_dir, df_out_file))","repo_name":"covidclinical/visualization-notebooks","sub_path":"notebooks/web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"86"} +{"seq_id":"72593891163","text":"from collections import defaultdict\nfrom hamiltonian import *\nfrom scipy.sparse import csr_matrix, load_npz, save_npz\nimport os\nfrom utils import *\n\n\ndef setMatrix(S, N, dis, sdict, para, tag=''):\n\n sparse = para['sparse'] \n readM = para[\"readM\"]\n def checksparce():\n \n cnt = defaultdict(int)\n for row in M:\n cnt[len(np.argwhere(row))] += 1\n\n #print(cnt)\n\n frac = N // 100 if N >= 100 else 1\n cnt = 0\n\n sparse_M = 'M{}.npz'.format(tag)\n dense_M = 'M{}'.format(tag)\n\n if sparse:\n\n if os.path.exists(sparse_M) and readM:\n M = load_npz(sparse_M)\n\n else:\n row = []\n col = []\n val = []\n\n for i, state in enumerate(S):\n\n if i % frac == 0:\n print('setup complete {}%'.format(cnt))\n cnt += 1\n\n newstates = hamiltonian(state, dis, para)\n for j, newstate in enumerate(newstates[1]):\n row += [i]\n col += [sdict[str(newstate)]]\n val += [newstates[0][j]]\n\n M = csr_matrix((val, (row, col)), shape=(N, N))\n save_npz(sparse_M, M)\n\n else:\n\n if os.path.exists(dense_M) and readM:\n M = np.loadtxt(dense_M)\n\n else:\n M = np.zeros((N, N))\n\n for i, state in enumerate(S):\n\n if i % frac == 0:\n print('setup complete {}%'.format(cnt))\n cnt += 1\n \n newstates = hamiltonian(state, dis, para)\n for j, newstate in enumerate(newstates[1]):\n M[i, sdict[str(newstate)]] += newstates[0][j]\n\n np.savetxt(dense_M + 'readable', M, fmt='%.3f')\n np.savetxt(dense_M, M)\n \n #\\checkdiag(M, para)\n checksparce()\n\n #if os.path.exists(sparse_M) and os.path.exists(dense_M):\n # check_same(sparse_M, dense_M)\n \n return M\n \n\n\n\n","repo_name":"keyi-ray-liu/DisorderCNN","sub_path":"ED_src/set.py","file_name":"set.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"39430982571","text":"# http://www.growingwiththeweb.com/data-structures/binomial-heap/overview/\n\n\nclass Node(object):\n def __init__(self, key, degree=0, parent=None, child=None, sibling=None):\n self.key = key\n self.degree = degree\n self.parent = parent\n self.child = child\n self.sibling = sibling\n\n def compare_to(self, other):\n return self.key.compare_to(other.key)\n\n\n# ======= IMPLEMENTATAION 1 ========== #\nclass BinomialHeap1(object):\n def __init__(self, head=None):\n self.head = head\n\n def is_empty(self):\n return self.head is None\n\n def clear(self):\n self.head = None\n\n def insert(self, key):\n node = Node(key)\n tempHeap = BinomialHeap1(node)\n self.head = self.union(tempHeap)\n\n def find_minimum(self):\n if self.head is None:\n return None\n else:\n minimum = self.head\n nextt = minimum.sibling\n\n while nextt is not None:\n if nextt.compare_to(minimum) < 0:\n minimum = nextt\n nextt = nextt.sibling\n\n return minimum.key\n\n def search(self, key):\n \"\"\"Implemented to test delete/decrease key, runs in O(n) time\"\"\"\n nodes = [self.head]\n while len(nodes) != 0:\n curr = nodes[0]\n nodes.pop(0)\n\n if curr.key == key:\n return curr\n\n if curr.sibling is not None:\n nodes.append(curr.sibling)\n\n if curr.child is not None:\n nodes.append(curr.child)\n\n return None\n\n def decrease_key(self, node, newKey):\n node.key = newKey\n self.bubble_up(node, False)\n\n def delete(self, node):\n node = self.bubble_up(node, True)\n if self.head == node:\n self.remove_tree_root(node, None)\n else:\n prev = self.head\n while prev.sibling.compare_to(node) != 0:\n prev = prev.sibling\n self.remove_tree_root(node, prev)\n\n def bubble_up(self, node, toRoot):\n parent = node.parent\n while parent is not None and (toRoot or node.compareTo(parent) < 0):\n temp = node.key\n node.key = parent.key\n parent.key = temp\n node = parent\n parent = parent.parent\n\n return node\n\n def extract_min(self):\n if self.head is None:\n return None\n\n minimum = self.head\n minPrev = None\n next = minimum.sibling\n nextPrev = minimum\n\n while next is not None:\n if next.compare_to(minimum) < 0:\n minimum = next\n minPrev = nextPrev\n nextPrev = next\n next = next.sibling\n\n self.remove_tree_root(minimum, minPrev)\n return minimum.key\n\n def remove_tree_root(self, root, prev):\n # Remove root from the heap\n if root == self.head:\n self.head = root.sibling\n else:\n prev.sibling = root.sibling\n\n # Reverse the order of root's children and make a new heap\n new_head = None\n child = root.child\n while child is not None:\n nextt = child.sibling\n child.sibling = new_head\n child.parent = None\n new_head = child\n child = nextt\n\n newHeap = BinomialHeap(new_head)\n\n # Union the heaps and set its head as this.head\n self.head = self.union(newHeap)\n\n def link_tree(self, min_node_tree, other):\n \"\"\"Merge two binomial trees of the same order\"\"\"\n other.parent = min_node_tree\n other.sibling = min_node_tree.child\n min_node_tree.child = other\n min_node_tree.degree += 1\n\n def union(self, heap):\n \"\"\"Union two binomial heaps into one and return the head\"\"\"\n new_head = self.merge(self, heap)\n\n self.head = None\n heap.head = None\n\n if new_head is None:\n return None\n\n prev = None\n curr = new_head\n nextt = new_head.sibling\n\n while nextt is not None:\n if curr.degree != nextt.degree or \\\n (nextt.sibling is not None and nextt.sibling.degree == curr.degree):\n prev = curr\n curr = nextt\n else:\n if curr.compareTo(nextt) < 0:\n curr.sibling = nextt.sibling\n self.link_tree(curr, nextt)\n else:\n if prev is None:\n new_head = nextt\n else:\n prev.sibling = nextt\n\n self.link_tree(nextt, curr)\n curr = nextt\n\n nextt = curr.sibling\n\n return new_head\n\n def merge(self, heap1, heap2):\n if heap1.head is None:\n return heap2.head\n\n elif heap2.head is None:\n return heap1.head\n\n else:\n head = None\n heap1_next = heap1.head\n heap2_next = heap2.head\n\n if heap1.head.degree <= heap2.head.degree:\n head = heap1.head\n heap1_next = heap1_next.sibling\n else:\n head = heap2.head\n heap2_next = heap2_next.sibling\n\n tail = head\n\n while heap1_next is not None and heap2_next is not None:\n if heap1_next.degree <= heap2_next.degree:\n tail.sibling = heap1_next\n heap1_next = heap1_next.sibling\n else:\n tail.sibling = heap2_next\n heap2_next = heap2_next.sibling\n\n tail = tail.sibling\n\n if heap1_next is not None:\n tail.sibling = heap1_next\n else:\n tail.sibling = heap2_next\n\n return head\n\n def printer(self):\n print(\"Binomial heap:\", end=\" \")\n if self.head is not None:\n self.print_node(self.head, 0)\n\n def print_node(self, curr, level):\n while curr is not None:\n sb = \"\"\n for i in range(level):\n sb += \" \"\n sb += str(curr.key)\n print(sb)\n if curr.child is not None:\n curr.child.print(level + 1)\n curr = curr.sibling\n","repo_name":"sandyz1000/python-algorithm","sub_path":"heap/binomial_heap_blog.py","file_name":"binomial_heap_blog.py","file_ext":"py","file_size_in_byte":6285,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"1082288888","text":"import json\nimport os\nimport os.path\nimport time\nfrom run import run_codex_query, run_translate_query\nfrom argparse import ArgumentParser\nfrom queue import Queue, Empty\nfrom typing import Optional\nfrom uuid import uuid4, UUID\nfrom xml.etree import ElementTree as Etree\n\n\nfrom flask import Flask as Flask, request, Response\nfrom requests import RequestException\n\nfrom configuration.io_types import QuerySyntax, ResponseType\nfrom worker.communication import Instruction\nfrom worker.communication.instruction import get_request_file_path, ExecutionState, instruction_encoder, \\\n instruction_decoder\nfrom worker.communication.processing_event import ProcessingEvent\nfrom worker.queue_distributor import QueueDistributor\nfrom worker.threadedworker import ThreadedWorker\nfrom run import run\n\napp = Flask(__name__)\n\n# Setup worker thread\ninstruction_queue: 'Queue[Instruction]' = Queue()\nevent_queue: 'Queue[ProcessingEvent]' = Queue()\nqueue_consumers: 'list[Queue[ProcessingEvent]]' = []\n\nworker_thread = ThreadedWorker(instruction_queue, event_queue)\nevent_distributor_thread = QueueDistributor(event_queue, queue_consumers)\n\n\ndef build_response(result_set):\n x_result_set = Etree.Element(\"resultSet\")\n x_result = Etree.Element(\"patient_count\")\n x_result.attrib[\"value\"] = str(len(result_set))\n x_result_set.insert(0, x_result)\n return x_result_set\n\n\n@DeprecationWarning\n@app.route(\"/i2b2\", methods=[\"POST\"])\ndef handle_i2b2_query():\n \"\"\"\n Synchronous execution API (legacy)\n\n takes an I2B2 Query Definition in the body and executes it.\n :return: the number of matching patients found\n \"\"\"\n print(\"handling query\")\n # Execute and timestamp\n start_time = time.time()\n i2b2_request = request.data.decode(\"UTF-8\")\n try:\n result_set = run(Instruction(i2b2_request, str(uuid4()), time.time_ns()))\n response = build_response(result_set)\n except RequestException:\n return \"Connection error with upstream FHIR server\", 504\n\n end_time = time.time()\n delta = end_time - start_time\n\n # Insert timestamps into result_set\n x_start_time = Etree.Element(\"start_time\")\n x_start_time.attrib[\"value\"] = str(start_time)\n\n x_end_time = Etree.Element(\"end_time\")\n x_end_time.attrib[\"value\"] = str(end_time)\n\n x_delta = Etree.Element(\"delta\")\n x_delta.attrib[\"value\"] = str(delta)\n\n response.insert(0, x_end_time)\n response.insert(0, x_start_time)\n response.insert(0, x_delta)\n response = Etree.tostring(response).decode(\"UTF-8\")\n\n return str(response)\n\n\n@app.route(\"/query\", methods=[\"POST\"])\ndef create_query():\n \"\"\"\n Submit a query for execution\n\n :return: location header containing the url to the result/processing progress\n \"\"\"\n # Extract data from Request\n content_type = request.headers[\"Content-Type\"]\n query_syntax = content_type_to_query_syntax(content_type)\n accept = request.headers[\"Accept\"]\n response_type = accept_to_response_type(accept)\n i2b2_request: str = request.data.decode(\"UTF-8\")\n\n # Create Instruction\n queue_insertion_time: int = time.time_ns()\n uuid: UUID = uuid4()\n instruction: Instruction = Instruction(i2b2_request, str(uuid), queue_insertion_time,\n query_syntax=query_syntax, response_type=response_type)\n\n # Create execution flag\n with open(instruction.file_path(), \"x\") as flag:\n flag.write(instruction_encoder.encode(instruction))\n\n # Queue for execution\n instruction_queue.put(instruction)\n\n # Respond with location header\n response = app.make_response(\"\")\n response.status_code = 202\n response.headers[\"Location\"] = f\"/query/{str(instruction.request_id)}\"\n return response\n\n@app.route(\"/query-translate\", methods=[\"POST\"])\ndef create_query_translate():\n \"\"\"\n Submit a query for translation \n\n :return: translated query as string\n \"\"\"\n\n # Extract data from Request\n content_type = request.headers[\"Content-Type\"]\n query_syntax = content_type_to_query_syntax(content_type)\n accept = request.headers[\"Accept\"]\n response_type = accept_to_response_type(accept)\n query_input: str = request.data.decode(\"iso-8859-1\")\n\n # Create Instruction\n queue_insertion_time: int = time.time_ns()\n uuid: UUID = uuid4()\n instruction: Instruction = Instruction(query_input, str(uuid), queue_insertion_time,\n query_syntax=query_syntax, response_type=response_type)\n\n response: str = run_translate_query(instruction)\n # Respond with location header\n return response\n\n@app.route(\"/query-sync\", methods=[\"POST\"])\ndef create_query_sync():\n \"\"\"\n Submit a query for execution\n\n :return: location header containing the url to the result/processing progress\n \"\"\"\n\n # Extract data from Request\n content_type = request.headers[\"Content-Type\"]\n query_syntax = content_type_to_query_syntax(content_type)\n accept = request.headers[\"Accept\"]\n response_type = accept_to_response_type(accept)\n query_input: str = request.data.decode(\"iso-8859-1\")\n\n # Create Instruction\n queue_insertion_time: int = time.time_ns()\n uuid: UUID = uuid4()\n instruction: Instruction = Instruction(query_input, str(uuid), queue_insertion_time,\n query_syntax=query_syntax, response_type=response_type)\n\n response: str = run_codex_query(instruction)\n # Respond with location header\n return response\n\ndef get_query_from_persistence(query_id: str) -> Optional[Instruction]:\n \"\"\"\n Fetches a persisted query\n\n :param query_id:\n :return: if found the Instruction for a given query_id otherwise None\n \"\"\"\n request_path = get_request_file_path(query_id)\n\n # Make sure path exists\n if not os.path.exists(request_path):\n return None\n instruction = instruction_decoder.decode(open(request_path, \"r\").read())\n return instruction\n\n\n@app.route(\"/query//status\", methods=[\"GET\"])\ndef handle_query_state(query_id: str):\n \"\"\" \n Fetches the current processing state of a given query\n\n :param query_id: id of the query to be looked up\n :return: either 200 and the query state or 400 if query is not found\n \"\"\"\n query = get_query_from_persistence(query_id)\n if query is None:\n return \"No Query under this id\", 404\n\n return query.state.name\n\n\n@app.route(\"/query//results\", methods=[\"GET\"])\ndef handle_query_result(query_id: str):\n \"\"\"\n Fetches the response calculated for a query\n\n :param query_id: id of the query to fetch the response for\n :return: 404 if not found or the response calculated for the query\n \"\"\"\n query = get_query_from_persistence(query_id)\n if query is None:\n return \"No Query under this id\", 404\n\n if query.state != ExecutionState.DONE:\n return \"Still processing\", 102\n\n return query.response\n\n\n@app.route(\"/query/\", methods=[\"GET\"])\ndef get_query(query_id: str):\n \"\"\"\n Fetches the original request data for a given query\n\n :param query_id:\n :return: 404 if not found or the original request data\n \"\"\"\n query = get_query_from_persistence(query_id)\n if query is None:\n return \"No Query under this id\", 404\n\n return query.request_data, 200\n\n\n@app.route(\"/query\", methods=[\"GET\"])\ndef list_queries(): \n return \"Not Implemented\", 501\n\n\n@app.route(\"/query/\", methods=[\"DELETE\"])\ndef delete_query(query_id: str):\n \"\"\"\n Deletes a persisted query\n\n :param query_id: id of the query to be deleted\n :return:\n \"\"\"\n request_path = get_request_file_path(query_id)\n\n # Make sure path exists\n if not os.path.exists(request_path):\n return \"No Query under this id\", 404\n\n os.remove(request_path)\n return f\"Successfully deleted {query_id}\", 200\n\n\ndef send_events():\n consumer_queue = Queue()\n queue_consumers.append(consumer_queue)\n try:\n while True:\n try:\n yield json.dumps(consumer_queue.get(block=True).__dict__).encode(\"UTF-8\")\n except Empty:\n pass\n # Catch user terminating connection\n except GeneratorExit:\n # FIXME: somehow only gets thrown when attempting to write to an already closed connection\n queue_consumers.remove(consumer_queue)\n\n\n@app.route('/subscribe', methods=[\"GET\"])\ndef sse():\n \"\"\"\n API for server sent events that triggers when a query has been processed\n\n :return: Stream over all server events\n \"\"\"\n response = Response(send_events(), mimetype='text/event-stream')\n response.timeout = None\n return response\n\n\ndef refill_queue():\n \"\"\"\n Refills the instruction queue with instructions from persistence\n \"\"\"\n base_path = os.environ.get('PERSISTENCE') or \"worker/requests\"\n for file in os.listdir(base_path):\n # Make sure file is json\n file_ext = os.path.splitext(file)[1]\n if not file_ext == \"json\":\n continue\n\n # Decode instruction and skip finished ones\n instruction: Instruction = instruction_decoder.decode(open(f\"{base_path}/{file}\", \"r\").read())\n if instruction.state == ExecutionState.DONE:\n continue\n\n instruction_queue.put(instruction)\n\n\ndef content_type_to_query_syntax(content_type: str) -> QuerySyntax:\n \"\"\"\n For a given Content-Type header fetch the corresponding QuerySyntax\n\n :param content_type: string given in the header, values being e.g. codex/json or i2b2/xml\n :return: enum representing the input format\n \"\"\"\n # Get first part of media-type in uppercase, split of charset, boundary and\n content_type = content_type.split(\";\")[0].split(\"/\")[0].upper()\n return QuerySyntax[content_type]\n\n\ndef accept_to_response_type(accept: str) -> ResponseType:\n \"\"\"\n For a given Accept header fetch the corresponding ResponseType\n\n :param accept: string given in the header, values being e.g. result/xml or internal/json\n :return: enum representing the response type\n \"\"\"\n # Get first part of media-type in uppercase, split of charset, boundary and\n accept = accept.split(\";\")[0].split(\"/\")[0].upper()\n return ResponseType[accept]\n\n\nif __name__ == '__main__':\n # Setup the argument query_parser\n parser = ArgumentParser(description=\"FLARE, run feasibility queries via standard HL7 FHIR search requests\")\n parser.add_argument(\"--persistence\", type=str, help=\"path to the folder in which queries should be persisted\")\n parser.add_argument(\"--host\", \"-H\", type=str, help=\"host on which to listen\", default=\"0.0.0.0\")\n parser.add_argument(\"--port\", \"-P\", type=int, help=\"port on which to listen\", default=5000)\n parser.add_argument(\"--continue\", action=\"store_true\", dest=\"continue_from_persistence\")\n parser.add_argument(\"--debug\", action=\"store_true\")\n args = parser.parse_args()\n\n # Set application wide persistence folder\n if args.persistence:\n os.environ[\"PERSISTENCE\"] = args.persistence\n\n if args.continue_from_persistence:\n refill_queue()\n\n # Start application\n# worker_thread.start()\n# event_distributor_thread.start()\n\n app.run(host=args.host, port=args.port, threaded=True, debug=args.debug)\n","repo_name":"num-codex/codex-flare","sub_path":"src/run_server.py","file_name":"run_server.py","file_ext":"py","file_size_in_byte":11203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"11582502133","text":"''' Здоровье '''\nimport pygame\nimport random\nfrom os import path\n\n# определить местоположение папки img\nimg_dir = path.join(path.dirname(__file__), 'images')\nsnd_dir = path.join(path.dirname(__file__), 'sound')\n\n# 2. базовые настройки экрана\nWIDTH = 480\nHEIGHT = 600\nFPS = 60\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\n\n# Загрузка всей игровой графики\nbackground = pygame.image.load(path.join(img_dir, 'blue.png')).convert()\nbackground_rect = background.get_rect()\nplayer_img = pygame.image.load(path.join(img_dir, \"playerShip1_orange.png\")).convert()\nmeteor_img = pygame.image.load(path.join(img_dir, \"meteorBrown_med3.png\")).convert()\nbullet_img = pygame.image.load(path.join(img_dir, \"laserRed06.png\")).convert()\nmeteor_images = []\nmeteor_list =['meteorBrown_big1.png','meteorBrown_tiny2.png',\n 'meteorBrown_med1.png','meteorBrown_med3.png',\n 'meteorBrown_small1.png','meteorBrown_small2.png',\n 'meteorBrown_tiny1.png']\nfor img in meteor_list:\n meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert())\n\n# Загрузка мелодий игры\npygame.mixer.init()\nshoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'Laser_Shoot.wav'))\nexpl_sounds = []\nfor snd in ['expl3.wav', 'expl6.wav']:\n expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd)))\n# pygame.mixer.music.load(path.join(snd_dir, 'Pray1.mp3'))\n# pygame.mixer.music.set_volume(0.4)\n\n# Создание спрайта - базовые настройки\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = player_img\n self.image = pygame.transform.scale(player_img, (50, 30))\n self.image.set_colorkey(BLACK)\n self.rect = self.image.get_rect()\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 10\n self.speedx = 0\n self.shield = 100 # кредит очков\n self.radius = 20\n pygame.draw.circle(self.image, RED, self.rect.center, self.radius)\n\n # создание пули, с местом появления из середины верхней части игрока\n def shoot(self):\n bullet = Bullet(self.rect.centerx, self.rect.top)\n all_sprites.add(bullet)\n bullets.add(bullet)\n shoot_sound.play()\n\n # Движение / управление\n def update(self):\n self.speedx = 0\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_LEFT]:\n self.speedx = -8\n if keystate[pygame.K_RIGHT]:\n self.speedx = 8\n self.rect.x += self.speedx\n if self.rect.right > WIDTH:\n self.rect.right = WIDTH\n if self.rect.left < 0:\n self.rect.left = 0\n\n# определения свойств спрайта врага\nclass Mob(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image_orig = random.choice(meteor_images)\n self.image_orig.set_colorkey(BLACK)\n self.image = self.image_orig.copy()\n self.rect = self.image.get_rect()\n self.radius = int(self.rect.width * .85 / 2)\n self.rect.x = random.randrange(WIDTH - self.rect.width)\n self.rect.y = random.randrange(-150, -100)\n self.speedy = random.randrange(1, 8)\n self.speedx = random.randrange(-3, 3)\n self.rot = 0\n self.rot_speed = random.randrange(-8, 8)\n self.last_update = pygame.time.get_ticks()\n pygame.draw.circle(self.image, RED, self.rect.center, self.radius)\n\n # # вращение спрайтов\n def rotate(self):\n now = pygame.time.get_ticks()\n if now - self.last_update > 50:\n self.last_update = now\n self.rot = (self.rot + self.rot_speed) % 360\n new_image = pygame.transform.rotate(self.image_orig, self.rot)\n old_center = self.rect.center\n self.image = new_image\n self.rect = self.image.get_rect()\n self.rect.center = old_center\n\n # управление спрайтами врагов\n def update(self):\n self.rect.x += self.speedx\n self.rect.y += self.speedy\n if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right \\\n > WIDTH + 20:\n self.rect.x = random.randrange(WIDTH - self.rect.width)\n self.rect.y = random.randrange(-100, -40)\n self.speedy = random.randrange(1, 8)\n self.rotate()\n\n# определения свойств спрайта пули\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.image = bullet_img\n self.image.set_colorkey(BLACK)\n self.rect = self.image.get_rect()\n self.rect.bottom = y\n self.rect.centerx = x\n self.speedy = -10\n\n # управление спрайтами пуль\n def update(self):\n self.rect.y += self.speedy\n if self.rect.bottom < 0:\n self.kill()\n\nfont_name = pygame.font.match_font('arial')\ndef draw_text(surf, text, size, x, y):\n font = pygame.font.Font(font_name, size)\n text_surface = font.render(text, True, WHITE)\n text_rect = text_surface.get_rect()\n text_rect.midtop = (x, y)\n surf.blit(text_surface, text_rect)\n\n# логика создания новых мобов\ndef newmob(): \n m = Mob()\n all_sprites.add(m)\n mobs.add(m)\n\n# полоска здоровья на экране\ndef draw_shield_bar(surf, x, y, pct):\n if pct < 0:\n pct = 0\n BAR_LENGTH = 100\n BAR_HEIGHT = 10\n fill = (pct / 100) * BAR_LENGTH\n outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)\n fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)\n pygame.draw.rect(surf, GREEN, fill_rect)\n pygame.draw.rect(surf, WHITE, outline_rect, 2)\n\n# 3. Создание окна и запуск игры\npygame.init()\npygame.mixer.init()\npygame.display.set_caption(\"Shmup!\")\nclock = pygame.time.Clock()\nall_sprites = pygame.sprite.Group()\nmobs = pygame.sprite.Group()\nbullets = pygame.sprite.Group()\nplayer = Player()\nall_sprites.add(player)\nfor i in range(8):\n newmob() # появление новых мобов\nscore = 0\n#pygame.mixer.music.play(loops=-1)\n\n# 4. Цикл игры\nrunning = True\nwhile running:\n # 4.1 Ввод процесса (события)\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n player.shoot()\n\n # 4.2 Обновление\n all_sprites.update()\n\n # Проверка, не ударил ли моб игрока\n hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle)\n for hit in hits:\n player.shield -= hit.radius * 2 # расчет ущерба для здоровья\n newmob() # появление мобов после исчезновения\n if player.shield <= 0: # условие окончания игры\n running = False\n\n # Проверка, не столкнулись ли пуля и моб\n hits = pygame.sprite.groupcollide(mobs, bullets, True, True)\n for hit in hits:\n score += 50 - hit.radius\n random.choice(expl_sounds).play()\n newmob() # появление нового моба после сбития\n\n # 4.3 Визуализация (сборка)\n screen.fill(BLACK)\n screen.blit(background, background_rect)\n all_sprites.draw(screen)\n draw_text(screen, str(score), 18, WIDTH / 2, 10)\n draw_shield_bar(screen, 5, 5, player.shield) # отрисовка полоски здоровья\n pygame.display.flip() \n \n# 5. Окончание игры и закрытие окна\npygame.quit()","repo_name":"innTall/games","sub_path":"shmup/shmup9.py","file_name":"shmup9.py","file_ext":"py","file_size_in_byte":7615,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"8578145995","text":"kaki_hewan = {\n \"AY\": 2,\n \"SP\": 4,\n \"BB\": 2,\n \"KB\": 4\n}\n\ndef hitung_kaki(*arg):\n total = 0\n for a in arg:\n hewan = \"\"\n nums = []\n for n in a:\n if n.isalpha():\n hewan += n\n else:\n nums.append(n)\n\n joinNum = \"\".join(nums)\n total += int(joinNum) * kaki_hewan.get(hewan, 0)\n print(total)\n return total\n\nhitung_kaki('AY10', 'SP3', 'BB5', 'KB5') # 62\nhitung_kaki('AY1', 'BB2') # 6\nhitung_kaki('SP25', 'KB10') # 140\nhitung_kaki('BB15') # 30\n\n\"\"\"\nPak Budi adalah seorang pengusaha peternakan sukses yang mengelola banyak jenis peternakan seperti ayam, \nsapi, bebek dan kambing.\n\nUntuk mempermudah pencatatan, setiap hewan ternak sudah diberi kode sesuai dengan jenisnya:\n\nAY = Ayam\nSP = Sapi\nBB = Bebek\nKB = Kambing\nJadi ketika ada yang beli 100 ekor ayam maka beliau akan tulis AY100 di nota pembeliannya, \natau KB15 kalau ada yang beli kambing 15 ekor.\n\nTantangan:\nBantulah pak Budi menghitung total kaki hewan ternak yang dia jual, misalnya beliau menjual:\n\nAY10 = subtotal kaki 20 (2 x 10 ekor)\nSP3 = subtotal kaki 12 (4 x 3 ekor)\nBB5 = subtotal kaki 10 (2 x 5 ekor)\nKB5 = subtotal kaki 20 (4 x 5 ekor)\n-------------------------------------\nTotal kaki: 62\nBuatlah sebuah fungsi untuk mempermudah penghitungan total kaki hewan ternak berdasarkan informasi diatas, \ncontoh penggunaan fungsinya:\n\nhitung_kaki('AY10', 'SP3', 'BB5', 'KB5') # maka output: 62\nhitung_kaki('AY1', 'BB2') # maka output: 6\n\nPenting: fungsi hanya satu tetapi akan menerima jumlah input yang berbeda-beda.\n\"\"\"","repo_name":"badrunp/tantangan","sub_path":"peternak_dan_programmer.py","file_name":"peternak_dan_programmer.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"18174860812","text":"#!/usr/bin/env python3\n\n\"\"\"Setup packages.\"\"\"\n\nfrom distutils.core import setup\n\nPACKAGES = [\n 'fastkit',\n]\n\nwith open('requirements.txt') as f:\n REQUIREMENTS = [\n x.strip(' \\n')\n for x in f\n ]\n\nsetup(\n name='fastkit',\n version='0.1.4',\n description='Biological data preprocessing facility',\n author='Cameron Hyde',\n author_email='chyde@neoformit.com',\n url='https://github.com/neoformit/fastkit',\n packages=PACKAGES,\n install_requires=REQUIREMENTS,\n entry_points={\n 'console_scripts': ['fastkit=fastkit.cli:main'],\n }\n)\n","repo_name":"neoformit/fastkit","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"6453694332","text":"import numpy as np\nfrom sklearn.cluster import DBSCAN\n# import os\n# import sys\n# module_path = os.path.abspath(os.path.join('..'))\n# if module_path not in sys.path:\n# sys.path.append(module_path)\n\nimport library.geo_utils as geo_utils\nimport collections\nimport scipy\nfrom concurrent.futures import ProcessPoolExecutor\n\nfrom parallel_util import run_parallel\n\nimport library.cat_utils as cat_utils\nimport library.geo_utils as geo_utils\nimport metrics\n# (0.6118019290456039, 3.8000000000000003, 5), DBSCAN SILHOUETTE\n\nclass GeoDivPropensity():\n CHKS = 50 # chunk size for parallel pool executor\n _instance = None\n METHODS = ['walk'# ,'num_poi','num_cat','visits','walk_raw'\n # ,'ildg'\n # ,'inverse_walk'\n ,# 'dbscan','inv_dbscan','inv_wcluster','wcluster',\n # 'perfect'\n ]\n GEO_DIV_PROPENSITY_METHODS_PRETTY_NAME = {\n 'walk': 'Mean radius of visited POIs',\n 'num_poi': 'Number of visited POIs',\n 'ildg': 'Geographical ILD',\n 'inverse_walk': 'Inverse of mean radius of visited POIs',\n 'dbscan': 'Using clusters of visited pois',\n 'inv_dbscan': 'Inverse of dbscan',\n 'inv_wcluster': 'Inverse weighted clustering',\n 'wcluster': 'Weighted clustering',\n }\n\n @classmethod\n def getInstance(cls, *args, **kwargs):\n if cls._instance is None:\n cls._instance=cls(*args,**kwargs)\n elif len(args) > 0 or len(kwargs) > 0:\n cls._instance.__init__(*args,**kwargs)\n return cls._instance\n\n def __init__(self,training_matrix,poi_coos,poi_cats,undirected_category_tree,geo_div_method):\n self.training_matrix=training_matrix\n self.poi_coos=poi_coos\n self.poi_cats=poi_cats\n self.undirected_category_tree = undirected_category_tree\n self.users_categories_visits = cat_utils.get_users_cat_visits(self.training_matrix,\n self.poi_cats)\n self.mean_walk=self.cmean_dist_pois()\n self.users_mean_walk=self.cmean_dist_users()\n\n # import scipy.stats\n # print('mean walk',self.mean_walk)\n # print(scipy.stats.describe(self.users_mean_walk))\n import matplotlib.pyplot as plt\n num_bins = 50\n heights, bins, _ = plt.hist(self.users_mean_walk,bins=num_bins,color='k')\n bin_width = np.diff(bins)[0]\n bin_pos = bins[:-1] + bin_width / 2\n mask = (bin_pos <= self.mean_walk)\n fig, ax = plt.subplots(1,1)\n ax.bar(bin_pos[mask], heights[mask], width=bin_width, color='red')\n ax.bar(bin_pos[~mask], heights[~mask], width=bin_width, color='black')\n ax.spines['right'].set_visible(False)\n ax.spines['top'].set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.spines['bottom'].set_visible(False)\n ax.set_yticklabels([])\n ax.set_xticklabels([])\n ax.set_xticks([])\n ax.set_yticks([])\n fig.savefig('resultadotemp.png',bbox_inches='tight')\n fig.savefig('resultadotemp.eps',bbox_inches='tight')\n raise SystemExit\n \n self.geo_div_method = geo_div_method\n self.GEO_METHODS = {\n \"walk\": self.geo_div_walk,\n \"num_poi\": self.geo_div_num_poi,\n \"num_cat\": self.geo_div_num_cat,\n \"visits\": self.geo_div_visits,\n \"walk_raw\": self.geo_div_walk_raw,\n \"ildg\": self.geo_div_ildg,\n \"inverse_walk\": self.geo_div_inverse_walk,\n \"dbscan\": self.geo_div_dbscan,\n \"inv_dbscan\": self.geo_div_inv_dbscan,\n \"inv_wcluster\": self.geo_div_inv_wcluster,\n \"wcluster\": self.geo_div_wcluster,\n }\n\n\n self.max_user_visits = self.training_matrix.sum(axis=1).max()\n \n self.geo_div_propensity=None\n\n\n def cmean_dist_pois(self):\n lats=np.array([])\n longs=np.array([])\n for i,j in self.poi_coos.items():\n lats=np.append(lats,j[0])\n longs=np.append(longs,j[1])\n lat,lon = np.mean(lats),np.mean(longs)\n md=0\n for i in range(len(lats)):\n md+=geo_utils.dist((lat,lon),(lats[i],longs[i]))\n return md/len(lats)\n\n def cmean_dist_users(self):\n users_cmean=list()\n for i in range(self.training_matrix.shape[0]):\n lids=self.training_matrix[i].nonzero()[0]\n lats=np.array([])\n longs=np.array([])\n for lid in lids:\n lats=np.append(lats,self.poi_coos[lid][0])\n longs=np.append(longs,self.poi_coos[lid][1])\n lat,lon = np.mean(lats),np.mean(longs)\n md=0\n \n for i in range(len(lats)):\n md+=geo_utils.dist((lat,lon),(lats[i],longs[i]))\n users_cmean.append(md/len(lats))\n return users_cmean\n\n def cmedian_dist_pois(self):\n lats=np.array([])\n longs=np.array([])\n for i,j in self.poi_coos.items():\n lats=np.append(lats,j[0])\n longs=np.append(longs,j[1])\n lat,lon = np.median(lats),np.median(longs)\n md=0\n for i in range(len(lats)):\n md+=geo_utils.dist((lat,lon),(lats[i],longs[i]))\n return md/len(lats)\n\n def cmedian_dist_users(self):\n users_cmean=list()\n for i in range(self.training_matrix.shape[0]):\n lids=self.training_matrix[i].nonzero()[0]\n lats=np.array([])\n longs=np.array([])\n for lid in lids:\n lats=np.append(lats,self.poi_coos[lid][0])\n longs=np.append(longs,self.poi_coos[lid][1])\n lat,lon = np.median(lats),np.median(longs)\n md=0\n \n for i in range(len(lats)):\n md+=geo_utils.dist((lat,lon),(lats[i],longs[i]))\n users_cmean.append(md/len(lats))\n return users_cmean\n\n @classmethod\n def geo_div_walk(cls,uid):\n self = cls.getInstance()\n norm_prop=min((self.users_mean_walk[uid]/self.mean_walk),1)\n # self.geo_div_propensity=norm_prop\n return norm_prop\n\n @classmethod\n def geo_div_walk_raw(cls,uid):\n self = cls.getInstance()\n norm_prop=self.mean_walk.copy()\n # self.geo_div_propensity=norm_prop\n return norm_prop\n\n @classmethod\n def geo_div_num_cat(cls, uid):\n self = cls.getInstance()\n cats_visits = self.users_categories_visits[uid]\n return len(cats_visits)/(len(self.undirected_category_tree)-1)\n\n @classmethod\n def geo_div_num_poi(cls, uid):\n self = cls.getInstance()\n lids = self.training_matrix[uid].nonzero()[0]\n return len(lids)/self.training_matrix.shape[1]\n\n @classmethod\n def geo_div_ildg(cls, uid):\n self = cls.getInstance()\n lids = self.training_matrix[uid].nonzero()[0]\n ildg = metrics.ildgk(lids,self.poi_coos)\n return ildg\n\n @classmethod\n def geo_div_visits(cls, uid):\n self = cls.getInstance()\n lids = self.training_matrix[uid].nonzero()[0]\n visits = self.training_matrix[uid,lids].sum()\n return visits/self.max_user_visits\n\n @classmethod\n def geo_div_inverse_walk(cls, uid):\n self = cls.getInstance()\n norm_prop=min((self.users_mean_walk[uid]/self.mean_walk),1)\n # self.geo_div_propensity=norm_prop\n return 1-norm_prop\n\n @classmethod\n def geo_div_dbscan(cls, uid):\n self = cls.getInstance()\n km = 3.8\n min_samples = 5\n \n points = [self.poi_coos[lid]\n for lid in np.nonzero(self.training_matrix[uid])[0]\n # for _ in range(self.training_matrix[uid,lid])\n ]\n db = DBSCAN(eps=geo_utils.km_to_lat(km), min_samples=min_samples).fit(points)\n labels = db.labels_\n # Number of clusters in labels, ignoring noise if present.\n a = n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n b = n_noise_ = list(labels).count(-1)\n\n return ((b - a)/(max(a,b)) + 1)/2\n\n\n @classmethod\n def geo_div_inv_dbscan(cls, uid):\n self = cls.getInstance()\n km = 3.8\n min_samples = 5\n \n points = [self.poi_coos[lid]\n for lid in np.nonzero(self.training_matrix[uid])[0]\n # for _ in range(self.training_matrix[uid,lid])\n ]\n db = DBSCAN(eps=geo_utils.km_to_lat(km), min_samples=min_samples).fit(points)\n labels = db.labels_\n # Number of clusters in labels, ignoring noise if present.\n a = n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n b = n_noise_ = list(labels).count(-1)\n\n return 1-((b - a)/(max(a,b)) + 1)/2\n\n @classmethod\n def geo_div_inv_wcluster(cls, uid):\n self = cls.getInstance()\n km = 3.8\n min_samples = 5\n \n points = [self.poi_coos[lid]\n for lid in np.nonzero(self.training_matrix[uid])[0]\n # for _ in range(self.training_matrix[uid,lid])\n ]\n db = DBSCAN(eps=geo_utils.km_to_lat(km), min_samples=min_samples).fit(points)\n labels = db.labels_\n # Number of clusters in labels, ignoring noise if present.\n unique, counts = np.unique(labels, return_counts=True)\n u_c = dict(zip(unique, counts))\n wa = 0\n wb = 0\n for lab, amount in u_c.items():\n if lab != -1:\n wa += amount\n else:\n wb += amount\n a = n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n b = n_noise_ = list(labels).count(-1)\n a*= wa\n b*= wb\n\n return 1-((b - a)/(max(a,b)) + 1)/2\n\n\n @classmethod\n def geo_div_wcluster(cls, uid):\n self = cls.getInstance()\n km = 3.8\n min_samples = 5\n \n points = [self.poi_coos[lid]\n for lid in np.nonzero(self.training_matrix[uid])[0]\n # for _ in range(self.training_matrix[uid,lid])\n ]\n db = DBSCAN(eps=geo_utils.km_to_lat(km), min_samples=min_samples).fit(points)\n labels = db.labels_\n # Number of clusters in labels, ignoring noise if present.\n unique, counts = np.unique(labels, return_counts=True)\n u_c = dict(zip(unique, counts))\n wa = 0\n wb = 0\n for lab, amount in u_c.items():\n if lab != -1:\n wa += amount\n else:\n wb += amount\n a = n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n b = n_noise_ = list(labels).count(-1)\n a*= wa\n b*= wb\n\n return ((b - a)/(max(a,b)) + 1)/2\n\n def compute_div_propensity(self):\n func = self.GEO_METHODS.get(self.geo_div_method,\n lambda: \"Invalid method\")\n # self.geo_div_propensity = func()\n args=[(uid,) for uid in range(self.training_matrix.shape[0])]\n self.geo_div_propensity = run_parallel(func, args, self.CHKS)\n if self.geo_div_method == 'ildg':\n self.geo_div_propensity = self.geo_div_propensity/np.max(self.geo_div_propensity)\n self.geo_div_propensity = np.array(self.geo_div_propensity)\n\n # bins = np.append(np.arange(0,1,1/(3-1)),1)\n # centers = (bins[1:]+bins[:-1])/2\n # self.geo_div_propensity = bins[np.digitize(self.geo_div_propensity, centers)]\n\n # if self.geo_div_method == 'dbscan':\n # self.geo_div_propensity[self.geo_div_propensity>=0.5] = 1\n # self.geo_div_propensity[(self.geo_div_propensity<0.5) & (self.geo_div_propensity>=0.3)] = 0.5\n # self.geo_div_propensity[self.geo_div_propensity<0.3] = 0\n return self.geo_div_propensity\n","repo_name":"heitor57/poi-rss","sub_path":"algorithms/library/methods/pgc/GeoDivPropensity.py","file_name":"GeoDivPropensity.py","file_ext":"py","file_size_in_byte":11745,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"36225882651","text":"import os\nimport jsonlines\nimport re\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\n\n#lemmatize verbs to ignore tenses\ndef lemmatize_verb(verb):\n lemmatizer = WordNetLemmatizer()\n return lemmatizer.lemmatize(verb, pos='v')\n\ndef process_json_files(directory, target_verbs):\n verb_sentences = {verb: [] for verb in target_verbs}\n for root, _, files in os.walk(directory):\n for filename in files:\n if filename.endswith(\".json\"):\n filepath = os.path.join(root, filename)\n with jsonlines.open(filepath) as reader:\n for obj in reader:\n if \"text\" in obj and isinstance(obj[\"text\"], str):\n sentences = re.split(r\"[.!?]\", obj[\"text\"])\n for sentence in sentences:\n words = sentence.strip().split()\n if words and len(words) > 1:\n # Use nltk to get POS tags\n pos_tags = nltk.pos_tag(words)\n for word, pos in pos_tags:\n if pos.startswith('VB'): # Identify verbs (VB, VBD, VBG, VBN, VBP, VBZ)\n verb = lemmatize_verb(word.lower())\n if verb in target_verbs:\n verb_sentences[verb].append(sentence.strip())\n break # Only consider the first verb in the sentence\n elif re.match(r\"[.!?]\", word): # Skip if the word is a punctuation mark at the beginning\n continue\n return verb_sentences\n\ndef write_output(verb_sentences):\n for verb, sentences in verb_sentences.items():\n output_file = f\"{verb}_output.txt\"\n with open(output_file, \"w\") as writer:\n for sentence in sentences:\n writer.write(sentence + \"\\n\")\n\nif __name__ == \"__main__\":\n #download additional nltk resources\n nltk.download('wordnet')\n\n #project directory\n json_en_directory = \"./json_en\"\n #list of target verbs to parse\n target_verbs = [\"be\", \"become\", \"create\", \"develop\", \"direct\", \"establish\", \"lead\", \"make\", \"order\", \"produce\", \"publish\", \"receive\", \"reform\", \"secure\", \"set\", \"write\"] # Replace with your array of verbs\n\n verb_sentences = process_json_files(json_en_directory, target_verbs)\n write_output(verb_sentences)\n","repo_name":"Droidtown/AItlas","sub_path":"tools/group_verb.py","file_name":"group_verb.py","file_ext":"py","file_size_in_byte":2567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"29970166608","text":"def DFS():\n if len(s) == M:\n print(*s)\n return\n\n for i in range(1, N+1):\n if visited[i]: # 이미 방문했으면 건너뜀\n continue\n\n # 방문 안했으면 방문체크 후, 출력 리스트에 넣음\n visited[i] = True\n s.append(i)\n DFS() # 함수 다시 호출\n s.pop() # 원상복귀 과정 필요\n visited[i] = False\n\n\n \nN, M = map(int, input().split()) # N:주어진 수, M:수열의 길이\ns = [] # 출력 수열 넣을 리스트 (stack)\nvisited = [False] * (N+1) # 방문체크 할 리스트\nDFS()","repo_name":"Lee-YuGyeong/Algorithm-Study-Python","sub_path":"LeeYuGyeong/~211208/Baekjoon/15649.py","file_name":"15649.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"86"} +{"seq_id":"12177820649","text":"import logging\nimport json\nimport time\nimport unittest\nimport tagilmo.utils.mission_builder as mb\nfrom tagilmo.utils.vereya_wrapper import MCConnector, RobustObserver\nfrom base_test import BaseTest\nfrom tagilmo import VereyaPython\nfrom common import init_mission\nfrom test_motion_vereya import TestMotion\n\n\nlogger = logging.getLogger(__file__)\n\nclass TestMotionMob(TestMotion):\n\n mc = None\n obs = None\n\n @classmethod\n def setUpClass(cls, *args, **kwargs):\n start = (-151.0, -213.0)\n mc, obs = init_mission(None, start_x=start[0], start_z=start[1], forceReset='true', seed='43')\n cls.mc = mc\n cls.obs = obs\n assert mc.safeStart()\n time.sleep(4)\n # create mob above player\n x, y, z = obs.waitNotNoneObserve('getAgentPos')[:3]\n mc.sendCommand(f\"chat /summon minecraft:chicken {x} {y + 7} {z} {{NoAI:1}}\")\n time.sleep(3)\n key = None\n for key in mc.getControlledMobs():\n mc.agentId = key\n obs.agentId = key\n assert key is not None\n\n\ndel TestMotion\n\nif __name__ == '__main__':\n VereyaPython.setupLogger()\n unittest.main()\n","repo_name":"trueagi-io/minecraft-demo","sub_path":"tests/vereya/test_motion_mob.py","file_name":"test_motion_mob.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"9"} +{"seq_id":"37829881225","text":"# Una concesionaria de autos necesita un sistema para registrar y gestionar los trabajos que hacen en su taller.\n# Por cada trabajo se conoce:\n#\n# - Identificador del trabajo: un entero.\n# - Tipo de trabajo: un entero en el rango 100 a 350 (ambos incluídos).\n# - DNI del cliente: un entero.\n# - Patente del vehículo: una cadena.\n# - Monto cobrado: un flotante no negativo.\n#\n# Se solicita un programa, comandado por menú de opciones, que permita lo siguiente:\n#\n# 1) Cargar un arreglo con \"n\" trabajos de forma manual o generando los datos aleatoriamente.\n# Únicamente se debe programar una de las opciones.\n#\n# 2) Mostrar el arreglo ordenado por identificador de trabajo de forma ascendente.\n#\n# 3) Informar el monto acumulado que se cobró por cada tipo de trabajo.\n#\n# 4) Mostrar todos aquellos trabajos cuyo tipo sea \"t\" y el monto superior a \"m\", siendo \"t\" y \"m\" valores solicitados al usuario.\n#\n# 5) Informar si existe un trabajo para la patente \"p\", siendo \"p\" un valor cargado por el usuario.\n# Si existe, mostrar sus datos y modificar su monto descontándole el 10%. Si no existe, informar esta situación con un mensaje.\n#\n# 6) Mostrar el trabajo más caro cobrado para un cliente cuyo DNI es \"d\", siendo \"d\" un valor ingresado por teclado.\n\n\nimport random\n\n\nclass Trabajos:\n def __init__(self, id, tipo, dni, patente, monto):\n self.id = id\n self.tipo = tipo\n self.dni = dni\n self.patente = patente\n self.monto = monto\n\n def __str__(self):\n cad = '|Identificador del trabajo: ' + str(self.id) + ' |Tipo de trabajo: ' + str(self.tipo)\n cad += ' |DNI del cliente: ' + str(self.dni) + ' |Patente del vehículo: ' + str(self.patente)\n cad += ' |Monto cobrado: $' + str(self.monto)\n return cad\n\n\ndef validar_mayor_que(limite, mensaje):\n numero = int(input(mensaje))\n while numero <= limite:\n print('Error!!!! El numero ingresado debe ser mayor a', limite)\n numero = int(input(mensaje))\n\n return numero\n\n\ndef menu():\n cadena = 'Menu de Opciones:\\n' + \\\n '===========================================\\n' + \\\n '1 - Cargar trabajaos \\n' + \\\n '2 - Mostrar datos ordenados por identificador \\n' + \\\n '3 - Monto acumulado por tipo \\n' + \\\n '4 - Mostrar trabajos con filtro (tipo y monto) \\n' + \\\n '5 - Buscar trabajo por patente \\n' + \\\n '6 - Mostrar trabajo mas caro \\n' + \\\n '0 - Salir \\n' + \\\n 'Ingrese su opcion: '\n return int(input(cadena))\n\n\ndef cargar_vec(v):\n n = len(v)\n for i in range(n):\n id = random.randint(1, 100)\n tipo = random.randint(100, 350)\n dni = random.randint(20000000, 50000000)\n patente = \"Patente \" + str(i)\n monto = round(random.uniform(45000, 300000),2)\n v[i] = Trabajos(id, tipo, dni, patente, monto)\n\n\ndef selection_sort(v):\n n = len(v)\n for i in range(n - 1):\n for j in range(i + 1, n):\n if v[i].id > v[j].id:\n v[i], v[j] = v[j], v[i]\n\n\ndef mostrar_vec(v):\n n = len(v)\n for i in range(n):\n print(v[i])\n\n\ndef mostrar_vec_acu(acum):\n n = len(acum)\n for i in range(n):\n if acum[i] > 0:\n print('El tipo es', i + 100, ': ', acum[i])\n\n\ndef mont_acum(v, acum):\n n = len(v)\n for i in range(n):\n acum[v[i].tipo - 100] += v[i].monto\n\n\ndef pto_4(t, m, vec):\n n = len(vec)\n for i in range(n):\n if vec[i].tipo == t and vec[i].monto > m:\n print(vec[i])\n\n\ndef linear_search(p, v):\n for i in range(len(v)):\n if v[i].patente == p:\n return i\n return -1\n\n\ndef principal():\n opcion = -1\n n = int(input('Ingrese la cantidad de trabajos a procesar: '))\n v = [None] * n\n\n while opcion != 0:\n opcion = menu()\n\n if opcion == 0:\n print(\"Adios!!!\")\n\n elif opcion == 1:\n cargar_vec(v)\n\n elif v is not None:\n if opcion == 2:\n selection_sort(v)\n mostrar_vec(v)\n\n elif opcion == 3:\n acum = [0] * 251\n mont_acum(v, acum)\n mostrar_vec_acu(acum)\n\n elif opcion == 4:\n\n t = int(input('Ingrese el tipo de trabajo que busque: '))\n m = float(input('Monto a superar: '))\n print('Punto 4: ')\n print(pto_4(t, m, v))\n\n elif opcion == 5:\n p = int(input(\"ingrese una patente para ver si existe: \"))\n linear_search(p, v)\n elif opcion == 6:\n pass\n\n else:\n print(\"Primero debe ejecutar la opcion 1\")\n\n\nif __name__ == \"__main__\":\n principal()\n","repo_name":"Leandro-Montenegro/python","sub_path":"simulacro_parcial3.py","file_name":"simulacro_parcial3.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"20481237330","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nfrom distutils.command.install import INSTALL_SCHEMES\r\nfrom distutils.core import setup\r\n\r\nROOT_DIR = os.path.dirname(__file__)\r\nSOURCE_DIR = os.path.join(ROOT_DIR, 'videologue')\r\n\r\n# Tell distutils to put the data_files in platform-specific installation\r\n# locations. See here for an explanation:\r\n#http://groups.google.com/group/comp.lang.python/browse_thread/thread/35ec7b2fed36eaec/2105ee4d9e8042cb\r\nfor scheme in INSTALL_SCHEMES.values():\r\n scheme['data'] = scheme['purelib']\r\n\r\n# Dynamically calculate the version based on videologue.VERSION\r\nversion_tuple = __import__('videologue').VERSION\r\nif len(version_tuple) == 3:\r\n version = \"%d.%d_%s\" % version_tuple\r\nelse:\r\n version = \"%d.%d\" % version_tuple[:2]\r\n\r\n# Scan for and add any data files \r\ndata_files = []\r\n\r\nfor dirpath, dirnames, filenames in os.walk(SOURCE_DIR):\r\n # Ignore dirnames that start with '.'\r\n for i, dirname in enumerate(dirnames):\r\n if dirname.startswith('.'): del dirnames[i]\r\n if '__init__.py' in filenames:\r\n continue\r\n elif filenames:\r\n dirpath = dirpath.replace(ROOT_DIR, '').strip(os.path.sep)\r\n data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]])\r\n\r\nsetup(\r\n name = \"videologue\",\r\n version = version,\r\n description = \"Powerful video management for the Django web framework.\",\r\n author = \"Øyvind Saltvik\",\r\n author_email = \"oyvind.saltvikl@gmail.com\",\r\n url = \"http://github.com/fivethreeo/django-videologue/tree/master\",\r\n packages = ['videologue',\r\n 'videologue.management',\r\n 'videologue.management.commands',\r\n 'videologue.templatetags'],\r\n data_files = data_files,\r\n classifiers = ['Development Status :: 4 - Beta',\r\n 'Environment :: Web Environment',\r\n 'Framework :: Django',\r\n 'Intended Audience :: Developers',\r\n 'License :: OSI Approved :: BSD License',\r\n 'Operating System :: OS Independent',\r\n 'Programming Language :: Python',\r\n 'Topic :: Utilities'],\r\n)\r\n","repo_name":"vinodc/flink","sub_path":"plugins/videologue-html5/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"71966379173","text":"import turtle\n\nt=turtle.Turtle()\nangle=5\nsize=10\n\ndef square():\n for i in range(4):\n t.rt(90)\n t.fd(size)\n\ndef next():\n t.rt(7)\n \nfor a in range(30):\n square()\n next()\n #angle=angle-10\n size=size+7\n \nturtle.getscreen()._root.mainloop()\n ","repo_name":"tomasbm07/IPRP---FCTUC","sub_path":"2/squares rotation.py","file_name":"squares rotation.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"34868737461","text":"#!/usr/bin/env python3\n\nimport sys, time, argparse, subprocess, os.path, shutil, struct, pathlib\n\nimport checkFASTQ as checker\n\nDescription = \"\"\"Tool to compress FASTQ files in internal memory\n\nFor example\n {exe} INPUT.fastq -o OUTPUT -1\nwill produce the files OUTPUT.fq.7z\n \n--------------------------\nCommand line options:\n--------------------------\n\"\"\".format(exe=sys.argv[0])\n\ngsufsort_exe = \"external/gsufsort/gsufsort\"\nheader_split = \"sed -n 1~4p\"\nqs_split = \"sed -n 4~4p\"\ndna_split = \"sed -n 2~4p\"\nzip7_exe = \"7z a -mm=PPMd\"\nbsc_exe = \"external/libbsc/bsc\"\nspring_reorder_exe = \"external/SPRING/build/spring-reorder\"\n\nsmooth_exe = \"src_int_mem/bfq_int\"\n\nbwt_ext = \".bwt\"\nqs_ext = \".bwt.qs\"\n\ndef main():\n parser = argparse.ArgumentParser(description=Description, formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('input', help='input file name', type=str, nargs='+')\n parser.add_argument('-o','--out', help='output base name (def. input base name)', default=\"\", type=str) \n parser.add_argument('-T','--mcl', help='minimum context length', default=\"\", type=str)\n parser.add_argument('-Q','--rv', help='constant replacement value', default=\"\", type=str)\n parser.add_argument('--rebuild', help='force call step 1', action='store_true',default=False)\n parser.add_argument('--original', help='do not call step 3',action='store_true')\n parser.add_argument('-1', '--m1', help='mode 1: FASTQ', action='store_true',default=True)\n parser.add_argument('-2', '--m2', help='mode 2: DNA+QS', action='store_true')\n parser.add_argument('-3', '--m3', help='mode 3: DNA+QS+H', action='store_true')\n parser.add_argument('-0', '--m0', help='mode 0: do not compress', action='store_true')\n parser.add_argument('--headers', help='include the headers', action='store_true', default=False)\n parser.add_argument('--reorder', help='reorder reads (SPRING)', action='store_true', default=False)\n parser.add_argument('-c', '--check', help='Check if the FASTQ is valid', action='store_true', default=False)\n parser.add_argument('-v', help='verbose: extra info in the log file', default=0, type=int)\n args = parser.parse_args()\n # ---- check number of input files and define basename\n check_input(args)\n define_basename(args)\n # ---- create and open log file\n logfile_name = args.basename + \".log\"\n # get main directory\n args.dir = os.path.split(sys.argv[0])[0]\n print(\"Sending logging messages to file:\", logfile_name)\n\n with open(logfile_name,\"w\") as logfile:\n \n ##\n if(args.m2): args.m1 = args.m3 = False\n if(args.m3): \n args.m1 = args.m2 = False\n args.headers = True\n ##\n\n if(args.m1):\n print(\">>> mode 1: FASTQ\",file=logfile) \n print(\">>> mode 1: FASTQ\") \n if(args.m2):\n print(\">>> mode 2: DNA+QS\",file=logfile) \n print(\">>> mode 2: DNA+QS\")\n if(args.m3):\n print(\">>> mode 3: DNA+QS+H\",file=logfile) \n print(\">>> mode 3: DNA+QS+H\")\n\n show_command_line(logfile)\n logfile.flush()\n\n if(args.reorder):\n if(spring_reorder(args, logfile, logfile_name)==False):\n print(\"=== ERROR ===\")\n print(\"./spring-reorder not installed (run make SPRING=1)\")\n return False\n\n if len(args.out)==0 : args.out=args.input[0]\n\n # temporary files\n args.tmp = []\n args.stream = []\n\n #--- step1: compute BWT+QS\n \n exists = os.path.exists(args.out+bwt_ext) and\\\n os.path.exists(args.out+qs_ext);\n \n if(args.rebuild or not exists):\n if(args.v == 2): print(\"## STEP 1 ##\")\n start = time.time()\n if(step1(args, logfile, logfile_name)!=True):\n sys.exit(1)\n print(\"Elapsed time: {0:.4f}\".format(time.time()-start))\n else:\n args.tmp.append(args.out+bwt_ext)\n args.tmp.append(args.out+qs_ext)\n \n exists = os.path.exists(args.out+\".h\");\n \n if(args.headers and not exists):\n #--- step2: extract headers\n if(args.v == 2): print(\"## STEP 2 ##\")\n start = time.time()\n if(step2(args, logfile, logfile_name)!=True):\n sys.exit(1)\n print(\"Elapsed time: {0:.4f}\".format(time.time()-start))\n \n #--- step3: smooth BWT and QS sequences \n start = time.time()\n if(args.v == 2): print(\"## STEP 3 ##\")\n if(step3(args, logfile, logfile_name)!=True):\n sys.exit(1)\n print(\"Elapsed time: {0:.4f}\".format(time.time()-start))\n\n #--- step4: compute DNA+QS\n if(args.m2 or args.m3):\n if(args.v == 2): print(\"## STEP 4 ##\")\n start = time.time()\n if(step4(args, logfile, logfile_name)!=True):\n sys.exit(1)\n print(\"Elapsed time: {0:.4f}\".format(time.time()-start))\n\n\n if(not args.m0):#call compressors\n\n args.output = []\n args.output2 = []\n \n #--- step5: compress\n if(args.v == 2): print(\"## STEP 5 ##\")\n start = time.time()\n print(\"--- Step 5 ---\", file=logfile); logfile.flush()\n if(step5(args, logfile, logfile_name)!=True):\n sys.exit(1)\n if(step5b(args, logfile, logfile_name)!=True):\n sys.exit(1)\n print(\"Elapsed time: {0:.4f}\".format(time.time()-start))\n\n #---- final report\n if(args.v):\n insize = os.path.getsize(args.input[0])\n\n print(\"=== results ===\"); \n print(\"Original:\\t{0:.2f} MB\".format(insize/(1024*1024)))\n if(args.v == 2):\n print(args.input[0])\n print(\"== PPMd ==\")\n outsize = 0\n for f in args.output:\n outsize += os.path.getsize(f)\n print(\"Compressed:\\t{0:.2f} MB\".format(outsize/(1024*1024)))\n print(\"Ratio = {0:.2f}\".format(outsize/insize))\n if(args.v == 2):\n for f in args.output:\n print(f) \n print(\"== BSC ==\")\n outsize = 0\n for f in args.output2:\n outsize += os.path.getsize(f)\n print(\"Compressed:\\t{0:.2f} MB\".format(outsize/(1024*1024)))\n print(\"Ratio = {0:.2f}\".format(outsize/insize))\n if(args.v == 2):\n for f in args.output2:\n print(f) \n\n return True\n\n##\n\ndef step1(args, logfile, logfile_name):\n print(\"--- Step 1 ---\", file=logfile); logfile.flush()\n exe = os.path.join(args.dir, gsufsort_exe)\n options = \"\"\n if len(args.out)>0 : options+=\"-o \"+args.out\n else : options+=\" -o \"+args.input[0]\n command = \"{exe} {ifile} --bwt --qs {opt}\".format(exe=exe, ifile=args.input[0], opt=options)\n print(\"=== gsufsort ===\"); print(command)\n # tmp files\n args.tmp.append(args.basename+\".bwt\")\n args.tmp.append(args.basename+\".bwt.qs\")\n return execute_command(command, logfile, logfile_name)\n\n##\ndef step2(args, logfile, logfile_name):\n print(\"--- Step 2 ---\", file=logfile); logfile.flush()\n ##\n exe = header_split\n ifile = args.input[0]\n ofile = args.out+\".h\"\n command = \"{exe} {ifile} > {ofile}\".format(exe=exe, ifile=ifile, ofile=ofile)\n print(\"=== header ===\")\n print(command)\n os.system(command)\n if (args.m3): args.stream.append(args.out+\".h\")\n return True\n##\n\ndef step3(args, logfile, logfile_name):\n if args.original:\n print(\"--- Step 3 ---\", file=logfile); logfile.flush()\n command = \"cp \"+ args.input[0] +\" \"+args.out+\".fq\" \n print(command)\n os.system(command)\n else:\n print(\"--- Step 3 ---\", file=logfile); logfile.flush()\n exe = os.path.join(args.dir, smooth_exe)\n options = \"-e \" + args.tmp[0] + \" -q \" + args.tmp[1] + \" -o \"+args.out+\".fq\"+\" -m 5\"\n ##additional options\n if len(args.mcl)>0:\n options+=\" -k \"+args.mcl\n if len(args.rv)>0: \n options+=\" -v \"+str(ord(args.rv))\n if(args.headers): #not ignore headers\n options+=\" -H \"+args.out+\".h\"\n command = \"{exe} {opt}\".format(exe=exe, opt=options)\n print(\"=== smooth-qs ===\")\n print(command)\n if(args.m1): args.stream.append(args.out+\".fq\")\n return execute_command(command, logfile, logfile_name)\n return True\n##\n\ndef step4(args, logfile, logfile_name):\n print(\"--- Step 4 ---\", file=logfile); logfile.flush()\n exe = dna_split\n ifile = args.out+\".fq\"\n ofile = args.out+\".fq.dna\"\n command = \"{exe} {ifile} > {ofile}\".format(exe=exe, ifile=ifile, ofile=ofile)\n print(\"=== dna ===\")\n print(command)\n os.system(command)\n args.stream.append(args.out+\".fq.dna\")\n ##\n exe = qs_split\n ifile = args.out+\".fq\"\n ofile = args.out+\".fq.qs\"\n command = \"{exe} {ifile} > {ofile}\".format(exe=exe, ifile=ifile, ofile=ofile)\n print(\"=== qs ===\")\n print(command)\n os.system(command)\n args.stream.append(args.out+\".fq.qs\")\n\n return True\n\ndef step5(args, logfile, logfile_name):\n print(\"--- PPMd ---\", file=logfile); logfile.flush()\n exe = zip7_exe\n print(\"=== PPMd ===\")\n for f in args.stream:\n ofile = f+\".7z\"\n command = \"{exe} {ofile} {ifile}\".format(exe=exe, ifile=f, ofile=ofile)\n print(command)\n execute_command(command, logfile, logfile_name)\n args.output.append(ofile)\n return True\n\ndef step5b(args, logfile, logfile_name):\n print(\"=== BSC ===\", file=logfile); logfile.flush()\n exe = bsc_exe\n print(\"=== BSC ===\")\n for f in args.stream:\n ofile = f+\".bsc\"\n command = \"{exe} e {ifile} {ofile} -T\".format(exe=exe, ifile=f, ofile=ofile)\n print(command)\n execute_command(command, logfile, logfile_name)\n args.output2.append(ofile)\n return True\n\ndef spring_reorder(args, logfile, logfile_name):\n if(not os.path.exists(spring_reorder_exe)):\n return False\n print(\"=== SPRING (reorder-only) ===\", file=logfile); logfile.flush()\n ##\n exe = spring_reorder_exe\n ifile = args.input[0]\n filename, file_extension = os.path.splitext(ifile)\n ofile = filename+\".reordered\"+file_extension\n command = \"{exe} -i {ifile} -o {ofile}\".format(exe=exe, ifile=ifile, ofile=ofile)\n print(\"=== SPRING (reorder-only) ===\")\n print(command)\n execute_command(command, logfile, logfile_name)\n args.input[0] = ofile\n define_basename(args)\n return True\n\n########\n\n# check correctness of number of input file and define basename for output\ndef check_input(args):\n if args.check:\n print(\"=== checking FASTQ ===\"); \n if checker.checkFASTQ(args.input[0]):\n print(\"Valid FASTQ file!\")\n else:\n print(\"Invalid FASTQ file!\")\n return True\n \ndef define_basename(args):\n if len(args.out)==0:\n args.basename = args.input[0]\n elif args.out[-1]==\"/\": \n pathlib.Path(args.out).mkdir(parents=True, exist_ok=True) \n tmp = args.input[0].split(\"/\")\n args.basename = args.out+tmp[-1]\n else:\n args.basename = args.out\n return True\n\n# compute hash digest for a file \ndef file_digest(name,logfile):\n try:\n hash_command = \"{exe} {infile}\".format(exe=shasum_exe, infile=name)\n hashsum = subprocess.check_output(hash_command.split(),stderr=logfile)\n hashsum = hashsum.decode(\"utf-8\").split()[0]\n except:\n hashsum = \"Error!\" \n return hashsum \n\n# execute command: return True is everything OK, False otherwise\ndef execute_command(command,logfile,logfile_name):\n try:\n subprocess.check_call(command.split(),stdout=logfile,stderr=logfile)\n except subprocess.CalledProcessError:\n print(\"Error executing command line:\")\n print(\"\\t\"+ command)\n print(\"Check log file: \" + logfile_name)\n return False\n return True\n\ndef show_command_line(f):\n f.write(\"Python command line: \") \n for x in sys.argv:\n f.write(x+\" \")\n f.write(\"\\n\") \n\nif __name__ == '__main__':\n main()\n","repo_name":"veronicaguerrini/BFQzip","sub_path":"BFQzip.py","file_name":"BFQzip.py","file_ext":"py","file_size_in_byte":12290,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"9"} +{"seq_id":"390657600","text":"from flask import Flask, render_template, session\nfrom blueprints.profile.routes import profile_app\nfrom blueprints.authorization.routes import auth_app\nfrom blueprints.basket.routes import basket_app\nfrom sql_provider import SQLProvider\n\napp = Flask(__name__)\napp.register_blueprint(profile_app, url_prefix='/profile')#1 - приложение, которое к этому app привязать, 2 - то, как его идентифицировать\napp.register_blueprint(auth_app, url_prefix='/authorization')\napp.register_blueprint(basket_app, url_prefix='/basket')\n#все url, начинающиеся с profile, будут передаваться в routes - nfv ,eltn\ndb_config = {\n 'host': '127.0.0.1',\n 'user': 'root',\n 'password': 'Ansergart629009',\n 'db': 'rk6_vasilyan'\n}\n\nprovider = SQLProvider('blueprints/profile/sql/')\napp.config['SECRET_KEY'] = 'super secret key'\n\n@app.route('/')\ndef index():\n return render_template('menu.html')\n\n@app.route('/exit')\ndef exit_handler():\n session.clear()\n return render_template('exit.html')\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8000)","repo_name":"Archi-RK6/coursework","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"29205727938","text":"from flask import Flask, jsonify, request\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\ndevelopers = [\r\n {'id': '0',\r\n 'nome': 'Gabriel',\r\n 'habilidades': ['Python', 'Django']\r\n },\r\n {'id': '1',\r\n 'nome': 'Erike',\r\n 'habilidades': ['Python', 'Flask']\r\n }\r\n]\r\n\r\n\r\n@app.route('/dev//', methods=['GET', 'PUT', 'DELETE'])\r\ndef developer(id):\r\n if request.method == 'GET':\r\n try:\r\n response = developers[id]\r\n except IndexError:\r\n mensagem = 'Desenvolvedor de ID {} não existe'.format(id)\r\n response = {'status': 'erro', 'mensagem': mensagem}\r\n except Exception:\r\n mensagem = 'Erro desconhecido. Procure o administrador da API'\r\n response = {'status': 'erro', 'mensagem': mensagem}\r\n return jsonify(response)\r\n elif request.method == 'PUT':\r\n dados = json.loads(request.data)\r\n developers[id] = dados\r\n return jsonify(dados)\r\n elif request.method == 'DELETE':\r\n developers.pop(id)\r\n return jsonify({'status': 'sucesso', 'mensagen': 'registro excluido'})\r\n\r\n\r\n@app.route('/dev/', methods=['POST', 'GET'])\r\ndef lista_developers():\r\n if request.method == 'POST':\r\n dados = json.loads(request.data)\r\n dados['id'] = len(developers)\r\n developers.append(dados)\r\n return jsonify({'status': 'sucesso', 'mensagen': 'registro inserido'})\r\n elif request.method == 'GET':\r\n return jsonify(developers)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n","repo_name":"GabriellMiranda/Rest-APIs-Com-Python-e-Flask","sub_path":"dev_api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"7907523736","text":"'''\nTuning colsample_bytree\nNow, it's time to tune \"colsample_bytree\". You've already seen this if you've ever worked with scikit-learn's RandomForestClassifier or RandomForestRegressor, where it just was called max_features. In both xgboost and sklearn, this parameter (although named differently) simply specifies the fraction of features to choose from at every split in a given tree. In xgboost, colsample_bytree must be specified as a float between 0 and 1.\n\nInstructions\n100 XP\nCreate a list called colsample_bytree_vals to store the values 0.1, 0.5, 0.8, and 1.\nSystematically vary \"colsample_bytree\" and perform cross-validation, exactly as you did with max_depth and eta previously.\n'''\nSOLUTION\n# Create your housing DMatrix\nhousing_dmatrix = xgb.DMatrix(data=X,label=y)\n\n# Create the parameter dictionary\nparams={\"objective\":\"reg:linear\",\"max_depth\":3}\n\n# Create list of hyperparameter values: colsample_bytree_vals\ncolsample_bytree_vals = [0.1, 0.5, 0.8, 1]\nbest_rmse = []\n\n# Systematically vary the hyperparameter value \nfor curr_val in colsample_bytree_vals:\n\n params['colsample_bytree'] = curr_val\n \n # Perform cross-validation\n cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=2,\n num_boost_round=10, early_stopping_rounds=5,\n metrics=\"rmse\", as_pandas=True, seed=123)\n \n # Append the final round rmse to best_rmse\n best_rmse.append(cv_results[\"test-rmse-mean\"].tail().values[-1])\n\n# Print the resultant DataFrame\nprint(pd.DataFrame(list(zip(colsample_bytree_vals, best_rmse)), columns=[\"colsample_bytree\",\"best_rmse\"]))","repo_name":"DidiMilikina/DataCamp","sub_path":"Machine Learning Scientist with Python/05. Extreme Gradient Boosting with XGBoost/03. Fine-tuning your XGBoost model/05. Tuning colsample_bytree.py","file_name":"05. Tuning colsample_bytree.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"9"} +{"seq_id":"3878654329","text":"#kf_localization\nimport numpy as np\nimport scipy\nimport scipy.signal\n# import control\nimport random\nimport math\nimport matplotlib.pyplot as plt\nimport scipy.io as sio\nfrom IPython.core.debugger import set_trace\nfrom rob_2wh import rob_2wh\nfrom animator2 import animator\n\n\ndef main():\n\n rob = rob_2wh()\n animate = animator()\n # given = sio.loadmat('hw2_soln_data.mat')\n # set_trace()\n\n t = []\n vc = []\n wc = []\n x = []\n y = []\n th = []\n v = []\n w = []\n z = []\n mu = []\n Sig = []\n K = []\n xe = []\n ye = []\n the = []\n ve = []\n we = []\n mu_prev = np.array([[rob.x0], [rob.y0], [rob.th0]])\n Sig_prev = np.array([[1.0, 0.0, 0.0],[0.0, 1.0, 0.0],[0.0,0.0,0.1]])\n elements = int(rob.tf/rob.dt)\n\n #if given data is use these\n # t = rob.ttr[0]\n # w = rob.wtr[0]\n # th =rob.thtr[0]\n # v = rob.vtr[0]\n # x = rob.xtr[0]\n # y = rob.ytr[0]\n # set_trace()\n\n for i in range(0,elements+1):\n\n t.append(i*rob.dt) #coment out if t is given\n vc_new = 1+0.5*math.cos(2*math.pi*0.2*t[i])\n # vc_new = 2+.8*math.cos(2*math.pi*0.2*t[i])\n vc.append(vc_new)\n wc_new = -0.2+2*math.cos(2*math.pi*0.6*t[i])\n # wc_new = 1+2*math.cos(2*math.pi*0.6*t[i])\n wc.append(wc_new)\n\n # # if data needs to be generated\n if i == 0:\n (x_new, y_new, th_new, v_new, w_new) = rob.vel_motion_model(vc[i], wc[i], rob.x0, rob.y0, rob.th0)\n x.append(rob.x0)\n y.append(rob.y0)\n th.append(rob.th0)\n v.append(v_new)\n w.append(w_new)\n else:\n (x_new, y_new, th_new, v_new, w_new) = rob.vel_motion_model(vc[i], wc[i], x[i-1], y[i-1], th[i-1])\n x.append(x_new)\n y.append(y_new)\n th.append(th_new)\n v.append(v_new)\n w.append(w_new)\n\n z.append(rob.simulate_sensor(x[i], y[i], th[i]))\n z_now = np.array(z[i])\n u_now = np.array([vc[i],wc[i]])\n # set_trace()\n # z_now = rob.simulate_sensor(x[i], y[i], th[i])\n # set_trace()\n # z.append(z_now)\n\n mu_new, Sig_new, K_new = rob.EKF(mu_prev,Sig_prev,u_now,z_now)\n mu.append(mu_new)\n Sig.append(Sig_new)\n K.append(K_new)\n\n xe.append(mu_new[0]-x[i])\n ye.append(mu_new[1]-y[i])\n the.append(mu_new[2]-th[i])\n ve.append(vc_new-v[i])\n we.append(wc_new-w[i])\n\n\n mu_prev = np.array(mu_new)\n Sig_prev = np.array(Sig_new)\n\n\n \n size = len(mu)\n x_hat = []\n y_hat =[]\n th_hat = []\n sig_x = []\n sig_y = []\n sig_th = []\n for i in range(size):\n x_hat.append(mu[i][0])\n y_hat.append(mu[i][1])\n th_hat.append(mu[i][2])\n sig_x.append(Sig[i][0][0])\n sig_y.append(Sig[i][1][1])\n sig_th.append(Sig[i][2][2])\n animate.animator(x, y, th, x_hat,y_hat,th_hat, elements)\n\n rob.plotting(x_hat, x, y_hat, y, th_hat, th, vc, v, wc, w,\\\n t, xe, ye, the, ve, we, K, sig_x, sig_y, sig_th)\n\n return(x, y, th, z, mu, Sig)\n\n\n\n\n # tf = 50.0\n # t0 = 0\n # elements = int(tf/uuv.dt)\n # u_hist = []\n # z_hist = []\n # t_hist = []\n # truth = np.array([[0], [0]])\n # mu = np.array([[2], [2]])\n # muv_hist = []\n # mux_hist = []\n # Sig = np.array([[1, 0],[0,.1]])\n # Sig1_hi_hist = []\n # Sig2_hi_hist = []\n # Sig1_lo_hist = []\n # Sig2_lo_hist = []\n # Kv_hist = []\n # Kx_hist = []\n # erx_hist = [] #error in x\n # erv_hist = [] #error in v\n # trux_hist = []\n # truv_hist = []\n #\n # for i in range(0, elements):\n # t = i*uuv.dt\n # if(t<5):\n # u = 50\n # elif(t<25):\n # u = 0\n # elif(t<30):\n # u = -50\n # else:\n # u = 0\n # # if(t<25):\n # # u = 50\n # # elif(t<30):\n # # u = -300\n # # elif(t<45):\n # # u = -50\n # # else:\n # # u = 0\n #\n # # if sensory information is given you can use the following values\n # # set_trace()\n # z = uuv.z[0][i]\n # truth = [[uuv.vtr[0][i]],[uuv.xtr[0][i]]]\n # # if no sensory information is given you have to simulate it below.\n # # (z,truth) = uuv.simulate_sensor(u, truth)\n #\n # (mu,Sig,K) = uuv.kalman_filter(mu, Sig, u, z)\n # er = (mu-truth)\n #\n # mu = mu.tolist()\n # er = er.tolist()\n # K = K.tolist()\n # # tru = truth.tolist()\n # tru = truth\n # muv_hist.append(mu[0])\n # mux_hist.append(mu[1])\n # Sig1_hi_hist.append(2*np.sqrt(Sig[0,0]))\n # Sig2_hi_hist.append(2*np.sqrt(Sig[1,1]))\n # Sig1_lo_hist.append(-2*np.sqrt(Sig[0,0]))\n # Sig2_lo_hist.append(-2*np.sqrt(Sig[1,1]))\n # z_hist.append(z)\n # erx_hist.append(er[1])\n # erv_hist.append(er[0])\n # trux_hist.append(tru[1])\n # truv_hist.append(tru[0])\n # Kx_hist.append(K[1])\n # Kv_hist.append(K[0])\n # t_hist.append(t)\n #\n # #\n #\n # uuv.plotting(mux_hist, muv_hist, Sig1_hi_hist, Sig2_hi_hist, Sig1_lo_hist, Sig2_lo_hist, erx_hist, erv_hist, trux_hist, truv_hist, Kx_hist, Kv_hist, t_hist)\n #\n # return [muv_hist, mux_hist], t_hist\n#\n\nif __name__ == '__main__':\n\t [x, y, th, z, mu, Sig] = main()\n","repo_name":"matthewk-rydalch/Autonomous_Systems_hw","sub_path":"EKF_localization/ekf_localization.py","file_name":"ekf_localization.py","file_ext":"py","file_size_in_byte":5355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"39157694896","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n''' \n Assistance Certificate Generator\n\n You may use any Assistance Certificate Generator project under the terms\n of the GNU General Public License (GPL) Version 3.\n\n (c) 2019 Emilio Mariscal (emi420 [at] gmail.com)\n \n Module description:\n \n Assistance Certificate Generator\n \n A simple utility to make assistant certificates and save them on PDF. \n \n'''\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nimport os\nfrom PIL import Image, ImageDraw\nfrom urllib.parse import urlparse, parse_qs\nimport secrets\nimport csv\nimport re\nfrom config import *\n\nimport http.server\n\nHandler = http.server.SimpleHTTPRequestHandler\n\nSERVER = False\n\n'''\ncreate: generate certificate\n'''\ndef create(name, role, id_hash):\n\n img_base = Image.open(BASE_FILE, 'r')\n img = Image.new(\"RGB\", (IMAGE_WIDTH, IMAGE_HEIGHT), (255,255,255))\n\n img.paste(img_base, (0,0))\n draw = ImageDraw.Draw(img)\n\n name = NAME_PREFIX + name\n role = ROLE_PREFIX + role\n\n name_w, name_h = draw.textsize(name, NAME_FONT)\n role_w, role_h = draw.textsize(role, ROLE_FONT)\n id_w, id_h = draw.textsize(id_hash, ID_FONT)\n\n draw.text(( (IMAGE_WIDTH - id_w) / 2, ID_TOP_POSITION), id_hash, (170,170,170), font=ID_FONT)\n draw.text(( (IMAGE_WIDTH - name_w) / 2, NAME_TOP_POSITION), name, (0,0,0), font=NAME_FONT)\n draw.text(( (IMAGE_WIDTH - role_w) / 2, ROLE_TOP_POSITION), role, (0,0,0), font=ROLE_FONT)\n\n del draw\n\n normalized_name = re.sub('[^A-Za-z0-9]+', '', name)\n img.save(OUT_DIR + normalized_name + \"-\" + id_hash + \".pdf\", \"PDF\")\n\ndef create_from_csv(filename):\n with open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=';')\n line_count = 0\n for row in csv_reader:\n\n name = row[0]\n role = row[1]\n\n if line_count == 0:\n print(f'Column names are {\", \".join(row)}')\n line_count += 1\n else:\n print(f'\\t Name: {name} Role: {role}')\n create(name, role.upper(), OUT_PREFIX + secrets.token_hex(nbytes=2))\n line_count += 1\n print(f'Processed {line_count} lines.')\n\n'''\nAPIServer: web server \n'''\nclass APIServer(BaseHTTPRequestHandler):\n\n def do_GET(self):\n \n mime = \"text/html\"\n\n self.send_response(200)\n self.send_header(\"Content-type\", mime)\n self.send_header('Allow', 'GET, OPTIONS')\n self.send_header('Access-Control-Allow-Origin', '*')\n self.end_headers()\n\n params = parse_qs(urlparse(self.path).query)\n\n if params:\n name = params.get(\"name\")[0]\n role = params.get(\"role\")[0]\n create(name=name, role=role)\n return\n\ndef main():\n if SERVER:\n try:\n server = HTTPServer(('', PORT), APIServer)\n print ('Started httpserver on port ' + str(PORT))\n server.serve_forever()\n \n except KeyboardInterrupt:\n print ('^C received, shutting down server')\n server.socket.close()\n else:\n create_from_csv(\"./data/list.csv\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"emi420/assistancecert","sub_path":"certgen.py","file_name":"certgen.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"2520096652","text":"def solution(ingredient): # 스택구조\n answer = 0\n cook = []\n hambuger = [1,2,3,1]\n for i in ingredient:\n cook.append(i)\n if len(cook) >= 4:\n if cook[-4:] == hambuger:\n del cook[-4:]\n answer += 1\n return answer","repo_name":"seungjaejeon/Algorithm","sub_path":"프로그래머스/1/133502. 햄버거 만들기/햄버거 만들기.py","file_name":"햄버거 만들기.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"22576701680","text":"#\n# @lc app=leetcode.cn id=162 lang=python3\n#\n# [162] 寻找峰值\n#\n\n# 2022-04-30\n# 根据题目条件必然有一个峰值\n# 思路:\n# 画了个草图,如果当前不是峰值,那么在相邻的值更大的一边必然有峰值\n# 提交失败:\n# 没有考虑一个元素数组,而在Python里取负索引会变成引用倒数的元素。\n\nfrom typing import *\n\n\n# @lc code=start\nclass Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n f, t = 0, len(nums) - 1\n while f <= t:\n mid = (f + t) >> 1\n if mid == 0 or nums[mid] > nums[mid - 1]:\n if mid == t or nums[mid] > nums[mid + 1]:\n return mid\n else:\n f = mid + 1\n else:\n t = mid - 1\n\n\n# @lc code=end\n\nprint(Solution().findPeakElement([1]))\nprint(Solution().findPeakElement([1, 2]))\n","repo_name":"HuangZhuo/litcode","sub_path":"src/162.寻找峰值.py","file_name":"162.寻找峰值.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"9044702324","text":"MODEL_NAME = 'ted_hrlr_translate_pt_en_converter'\nMAX_TOKENS = 128\nBUFFER_SIZE = 20000\nBATCH_SIZE = 64\nEMBEDDING_DIM=512\n\nNUM_LAYERS = 4\nFORWARD_DIM = 512\nNUM_HEADS = 8\nDROPOUT_RATE = 0.1\nEPOCHS = 2","repo_name":"pchampion92/translater","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"18471282942","text":"from __future__ import absolute_import, division, print_function\n\nimport numpy as np\n\nfrom odl.discr.discr_space import uniform_discr_fromdiscr\nfrom odl.util.numerics import resize_array\n\n__all__ = (\n 'cuboid',\n 'defrise',\n 'ellipsoid_phantom',\n 'indicate_proj_axis',\n 'smooth_cuboid',\n 'tgv_phantom',\n)\n\n\ndef cuboid(space, min_pt=None, max_pt=None):\n \"\"\"Rectangular cuboid.\n\n Parameters\n ----------\n space : `DiscretizedSpace`\n Space in which the phantom should be created.\n min_pt : array-like of shape ``(space.ndim,)``, optional\n Lower left corner of the cuboid. If ``None`` is given, a quarter\n of the extent from ``space.min_pt`` towards the inside is chosen.\n max_pt : array-like of shape ``(space.ndim,)``, optional\n Upper right corner of the cuboid. If ``None`` is given, ``min_pt``\n plus half the extent is chosen.\n\n Returns\n -------\n phantom : `DiscretizedSpaceElement`\n The generated cuboid phantom in ``space``.\n\n Examples\n --------\n If both ``min_pt`` and ``max_pt`` are omitted, the cuboid lies in the\n middle of the space domain and extends halfway towards all sides:\n\n >>> space = odl.uniform_discr([0, 0], [1, 1], [4, 6])\n >>> odl.phantom.cuboid(space)\n uniform_discr([ 0., 0.], [ 1., 1.], (4, 6)).element(\n [[ 0., 0., 0., 0., 0., 0.],\n [ 0., 1., 1., 1., 1., 0.],\n [ 0., 1., 1., 1., 1., 0.],\n [ 0., 0., 0., 0., 0., 0.]]\n )\n\n By specifying the corners, the cuboid can be arbitrarily placed and\n scaled:\n\n >>> odl.phantom.cuboid(space, [0.25, 0], [0.75, 0.5])\n uniform_discr([ 0., 0.], [ 1., 1.], (4, 6)).element(\n [[ 0., 0., 0., 0., 0., 0.],\n [ 1., 1., 1., 0., 0., 0.],\n [ 1., 1., 1., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0.]]\n )\n \"\"\"\n dom_min_pt = np.asarray(space.domain.min())\n dom_max_pt = np.asarray(space.domain.max())\n\n if min_pt is None:\n min_pt = dom_min_pt * 0.75 + dom_max_pt * 0.25\n if max_pt is None:\n max_pt = dom_min_pt * 0.25 + dom_max_pt * 0.75\n\n min_pt = np.atleast_1d(min_pt)\n max_pt = np.atleast_1d(max_pt)\n\n if min_pt.shape != (space.ndim,):\n raise ValueError('shape of `min_pt` must be {}, got {}'\n ''.format((space.ndim,), min_pt.shape))\n if max_pt.shape != (space.ndim,):\n raise ValueError('shape of `max_pt` must be {}, got {}'\n ''.format((space.ndim,), max_pt.shape))\n\n def phantom(x):\n result = True\n\n for xi, xmin, xmax in zip(x, min_pt, max_pt):\n result = (result &\n np.less_equal(xmin, xi) & np.less_equal(xi, xmax))\n return result\n\n return space.element(phantom)\n\n\ndef defrise(space, nellipses=8, alternating=False, min_pt=None, max_pt=None):\n \"\"\"Phantom with regularily spaced ellipses.\n\n This phantom is often used to verify cone-beam algorithms.\n\n Parameters\n ----------\n space : `DiscretizedSpace`\n Space in which the phantom should be created, must be 2- or\n 3-dimensional.\n nellipses : int, optional\n Number of ellipses. If more ellipses are used, each ellipse becomes\n thinner.\n alternating : bool, optional\n True if the ellipses should have alternating densities (+1, -1),\n otherwise all ellipses have value +1.\n min_pt, max_pt : array-like, optional\n If provided, use these vectors to determine the bounding box of the\n phantom instead of ``space.min_pt`` and ``space.max_pt``.\n It is currently required that ``min_pt >= space.min_pt`` and\n ``max_pt <= space.max_pt``, i.e., shifting or scaling outside the\n original space is not allowed.\n\n Providing one of them results in a shift, e.g., for ``min_pt``::\n\n new_min_pt = min_pt\n new_max_pt = space.max_pt + (min_pt - space.min_pt)\n\n Providing both results in a scaled version of the phantom.\n\n Returns\n -------\n phantom : ``space`` element\n The generated phantom in ``space``.\n\n See Also\n --------\n odl.phantom.transmission.shepp_logan\n \"\"\"\n ellipses = defrise_ellipses(space.ndim, nellipses=nellipses,\n alternating=alternating)\n return ellipsoid_phantom(space, ellipses, min_pt, max_pt)\n\n\ndef defrise_ellipses(ndim, nellipses=8, alternating=False):\n \"\"\"Ellipses for the standard Defrise phantom in 2 or 3 dimensions.\n\n Parameters\n ----------\n ndim : {2, 3}\n Dimension of the space for the ellipses/ellipsoids.\n nellipses : int, optional\n Number of ellipses. If more ellipses are used, each ellipse becomes\n thinner.\n alternating : bool, optional\n True if the ellipses should have alternating densities (+1, -1),\n otherwise all ellipses have value +1.\n\n See Also\n --------\n odl.phantom.geometric.ellipsoid_phantom :\n Function for creating arbitrary ellipsoids phantoms\n odl.phantom.transmission.shepp_logan_ellipsoids\n \"\"\"\n ellipses = []\n if ndim == 2:\n for i in range(nellipses):\n if alternating:\n value = (-1.0 + 2.0 * (i % 2))\n else:\n value = 1.0\n\n axis_1 = 0.5\n axis_2 = 0.5 / (nellipses + 1)\n center_x = 0.0\n center_y = -1 + 2.0 / (nellipses + 1.0) * (i + 1)\n rotation = 0\n ellipses.append(\n [value, axis_1, axis_2, center_x, center_y, rotation])\n elif ndim == 3:\n for i in range(nellipses):\n if alternating:\n value = (-1.0 + 2.0 * (i % 2))\n else:\n value = 1.0\n\n axis_1 = axis_2 = 0.5\n axis_3 = 0.5 / (nellipses + 1)\n center_x = center_y = 0.0\n center_z = -1 + 2.0 / (nellipses + 1.0) * (i + 1)\n rotation_phi = rotation_theta = rotation_psi = 0\n\n ellipses.append(\n [value, axis_1, axis_2, axis_3,\n center_x, center_y, center_z,\n rotation_phi, rotation_theta, rotation_psi])\n\n return ellipses\n\n\ndef indicate_proj_axis(space, scale_structures=0.5):\n \"\"\"Phantom indicating along which axis it is projected.\n\n The number (n) of rectangles in a parallel-beam projection along a main\n axis (0, 1, or 2) indicates the projection to be along the (n-1)the\n dimension.\n\n Parameters\n ----------\n space : `DiscretizedSpace`\n Space in which the phantom should be created, must be 2- or\n 3-dimensional.\n scale_structures : positive float in (0, 1], optional\n Scales objects (cube, cuboids)\n\n Returns\n -------\n phantom : ``space`` element\n Projection helper phantom in ``space``.\n\n Examples\n --------\n Phantom in 2D space:\n\n >>> space = odl.uniform_discr([0, 0], [1, 1], shape=(8, 8))\n >>> phantom = indicate_proj_axis(space).asarray()\n >>> print(odl.util.array_str(phantom, nprint=10))\n [[ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 1., 1., 0., 0., 0.],\n [ 0., 0., 0., 1., 1., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 1., 0., 0., 0.],\n [ 0., 0., 0., 1., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.]]\n\n >>> space = odl.uniform_discr([0] * 3, [1] * 3, [8, 8, 8])\n >>> phantom = odl.phantom.indicate_proj_axis(space).asarray()\n >>> axis_sum_0 = np.sum(phantom, axis=0)\n >>> print(odl.util.array_str(axis_sum_0, nprint=10))\n [[ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 3., 3., 0., 0., 0.],\n [ 0., 0., 0., 3., 3., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.]]\n >>> axis_sum_1 = np.sum(phantom, axis=1)\n >>> print(odl.util.array_str(axis_sum_1, nprint=10))\n [[ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 2., 2., 0., 0., 0.],\n [ 0., 0., 0., 2., 2., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 1., 1., 0., 0., 0.],\n [ 0., 0., 0., 1., 1., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.]]\n >>> axis_sum_2 = np.sum(phantom, axis=2)\n >>> print(odl.util.array_str(axis_sum_2, nprint=10))\n [[ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 2., 2., 0., 0., 0.],\n [ 0., 0., 0., 2., 2., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 2., 0., 0., 0.],\n [ 0., 0., 0., 2., 0., 0., 0., 0.],\n [ 0., 0., 0., 0., 0., 0., 0., 0.]]\n \"\"\"\n if not 0 < scale_structures <= 1:\n raise ValueError('`scale_structures` ({}) is not in (0, 1]'\n ''.format(scale_structures))\n\n assert space.ndim in (2, 3)\n\n shape = space.shape\n phan = np.zeros(shape)\n shape = np.array(shape) - 1\n cen = np.round(0.5 * shape)\n dx = np.floor(scale_structures * 0.25 * shape)\n dx[dx == 0] = 1\n\n # cube of size 2 * dx, offset in x axis, symmetric in others\n ix0 = int((cen - 3 * dx)[0])\n if space.ndim == 2:\n ix, iy = (cen - 1 * dx).astype(int)\n phan[ix0:ix, iy:-iy] = 1\n elif space.ndim == 3:\n ix, iy, iz = (cen - 1 * dx).astype(int)\n phan[ix0:ix, iy:-iy, iz:-iz] = 1\n\n # 1st cuboid of size (dx[0], dx[1], 2 * dx[2]), offset in x and y axes,\n # symmetric in z axis\n ix0 = int((cen + 1 * dx)[1])\n ix1 = int((cen + 2 * dx)[1])\n iy0 = int(cen[1])\n if space.ndim == 2:\n phan[ix0:ix1, iy0:-iy] = 1\n elif space.ndim == 3:\n iz = int((cen - dx)[2])\n phan[ix0:ix1, iy0:-iy, iz:-iz] = 1\n\n # 2nd cuboid of (dx[0], dx[1], 2 * dx[2]) touching the first diagonally\n # at a long edge; offset in x and y axes, symmetric in z axis\n ix0 = int((cen + 2 * dx)[1])\n ix1 = int((cen + 3 * dx)[1])\n iy1 = int(cen[1])\n if space.ndim == 2:\n phan[ix0:ix1, iy:iy1] = 1\n elif space.ndim == 3:\n iz = int((cen - dx)[2])\n phan[ix0:ix1, iy:iy1, iz:-iz] = 1\n\n return space.element(phan)\n\n\ndef _getshapes_2d(center, max_radius, shape):\n \"\"\"Calculate indices and slices for the bounding box of a disk.\"\"\"\n index_mean = shape * center\n index_radius = max_radius / 2.0 * np.array(shape)\n\n # Avoid negative indices\n min_idx = np.maximum(np.floor(index_mean - index_radius), 0).astype(int)\n max_idx = np.ceil(index_mean + index_radius).astype(int)\n idx = [slice(minx, maxx) for minx, maxx in zip(min_idx, max_idx)]\n shapes = [(idx[0], slice(None)),\n (slice(None), idx[1])]\n return tuple(idx), tuple(shapes)\n\n\ndef _ellipse_phantom_2d(space, ellipses):\n \"\"\"Create a phantom of ellipses in 2d space.\n\n Parameters\n ----------\n space : `DiscretizedSpace`\n Uniformly discretized space in which the phantom should be generated.\n If ``space.shape`` is 1 in an axis, a corresponding slice of the\n phantom is created (instead of squashing the whole phantom into the\n slice).\n ellipses : list of lists\n Each row should contain the entries ::\n\n 'value',\n 'axis_1', 'axis_2',\n 'center_x', 'center_y',\n 'rotation'\n\n The provided ellipses need to be specified relative to the\n reference rectangle ``[-1, -1] x [1, 1]``. Angles are to be given\n in radians.\n\n Returns\n -------\n phantom : ``space`` element\n 2D ellipse phantom in ``space``.\n\n See Also\n --------\n shepp_logan : The typical use-case for this function.\n \"\"\"\n # Blank image\n p = np.zeros(space.shape, dtype=space.dtype)\n\n minp = space.grid.min_pt\n maxp = space.grid.max_pt\n\n # Create the pixel grid\n grid_in = space.grid.meshgrid\n\n # move points to [-1, 1]\n grid = []\n for i in range(2):\n mean_i = (minp[i] + maxp[i]) / 2.0\n # Where space.shape = 1, we have minp = maxp, so we set diff_i = 1\n # to avoid division by zero. Effectively, this allows constructing\n # a slice of a 2D phantom.\n diff_i = (maxp[i] - minp[i]) / 2.0 or 1.0\n grid.append((grid_in[i] - mean_i) / diff_i)\n\n for ellip in ellipses:\n assert len(ellip) == 6\n\n intensity = ellip[0]\n a_squared = ellip[1] ** 2\n b_squared = ellip[2] ** 2\n x0 = ellip[3]\n y0 = ellip[4]\n theta = ellip[5]\n\n scales = [1 / a_squared, 1 / b_squared]\n center = (np.array([x0, y0]) + 1.0) / 2.0\n\n # Create the offset x,y and z values for the grid\n if theta != 0:\n # Rotate the points to the expected coordinate system.\n ctheta = np.cos(theta)\n stheta = np.sin(theta)\n\n mat = np.array([[ctheta, stheta],\n [-stheta, ctheta]])\n\n # Calculate the points that could possibly be inside the volume\n # Since the points are rotated, we cannot do anything directional\n # without more logic\n max_radius = np.sqrt(\n np.abs(mat).dot([a_squared, b_squared]))\n idx, shapes = _getshapes_2d(center, max_radius, space.shape)\n\n subgrid = [g[idi] for g, idi in zip(grid, shapes)]\n offset_points = [vec * (xi - x0i)[..., None]\n for xi, vec, x0i in zip(subgrid,\n mat.T,\n [x0, y0])]\n rotated = offset_points[0] + offset_points[1]\n np.square(rotated, out=rotated)\n radius = np.dot(rotated, scales)\n else:\n # Calculate the points that could possibly be inside the volume\n max_radius = np.sqrt([a_squared, b_squared])\n idx, shapes = _getshapes_2d(center, max_radius, space.shape)\n\n subgrid = [g[idi] for g, idi in zip(grid, shapes)]\n squared_dist = [ai * (xi - x0i) ** 2\n for xi, ai, x0i in zip(subgrid,\n scales,\n [x0, y0])]\n\n # Parentheses to get best order for broadcasting\n radius = squared_dist[0] + squared_dist[1]\n\n # Find the points within the ellipse\n inside = radius <= 1\n\n # Add the ellipse intensity to those points\n p[idx][inside] += intensity\n\n return space.element(p)\n\n\ndef _getshapes_3d(center, max_radius, shape):\n \"\"\"Calculate indices and slices for the bounding box of a ball.\"\"\"\n index_mean = shape * center\n index_radius = max_radius / 2.0 * np.array(shape)\n\n min_idx = np.floor(index_mean - index_radius).astype(int)\n min_idx = np.maximum(min_idx, 0) # avoid negative indices\n max_idx = np.ceil(index_mean + index_radius).astype(int)\n idx = [slice(minx, maxx) for minx, maxx in zip(min_idx, max_idx)]\n shapes = [(idx[0], slice(None), slice(None)),\n (slice(None), idx[1], slice(None)),\n (slice(None), slice(None), idx[2])]\n return tuple(idx), tuple(shapes)\n\n\ndef _ellipsoid_phantom_3d(space, ellipsoids):\n \"\"\"Create an ellipsoid phantom in 3d space.\n\n Parameters\n ----------\n space : `DiscretizedSpace`\n Space in which the phantom should be generated. If ``space.shape`` is\n 1 in an axis, a corresponding slice of the phantom is created\n (instead of squashing the whole phantom into the slice).\n ellipsoids : list of lists\n Each row should contain the entries ::\n\n 'value',\n 'axis_1', 'axis_2', 'axis_3',\n 'center_x', 'center_y', 'center_z',\n 'rotation_phi', 'rotation_theta', 'rotation_psi'\n\n The provided ellipsoids need to be specified relative to the\n reference cube ``[-1, -1, -1] x [1, 1, 1]``. Angles are to be given\n in radians.\n\n Returns\n -------\n phantom : ``space`` element\n 3D ellipsoid phantom in ``space``.\n\n See Also\n --------\n shepp_logan : The typical use-case for this function.\n \"\"\"\n # Blank volume\n p = np.zeros(space.shape, dtype=space.dtype)\n\n minp = space.grid.min_pt\n maxp = space.grid.max_pt\n\n # Create the pixel grid\n grid_in = space.grid.meshgrid\n\n # Move points to [-1, 1]\n grid = []\n for i in range(3):\n mean_i = (minp[i] + maxp[i]) / 2.0\n # Where space.shape = 1, we have minp = maxp, so we set diff_i = 1\n # to avoid division by zero. Effectively, this allows constructing\n # a slice of a 3D phantom.\n diff_i = (maxp[i] - minp[i]) / 2.0 or 1.0\n grid.append((grid_in[i] - mean_i) / diff_i)\n\n for ellip in ellipsoids:\n assert len(ellip) == 10\n\n intensity = ellip[0]\n a_squared = ellip[1] ** 2\n b_squared = ellip[2] ** 2\n c_squared = ellip[3] ** 2\n x0 = ellip[4]\n y0 = ellip[5]\n z0 = ellip[6]\n phi = ellip[7]\n theta = ellip[8]\n psi = ellip[9]\n\n scales = [1 / a_squared, 1 / b_squared, 1 / c_squared]\n center = (np.array([x0, y0, z0]) + 1.0) / 2.0\n\n # Create the offset x,y and z values for the grid\n if any([phi, theta, psi]):\n # Rotate the points to the expected coordinate system.\n cphi = np.cos(phi)\n sphi = np.sin(phi)\n ctheta = np.cos(theta)\n stheta = np.sin(theta)\n cpsi = np.cos(psi)\n spsi = np.sin(psi)\n\n mat = np.array([[cpsi * cphi - ctheta * sphi * spsi,\n cpsi * sphi + ctheta * cphi * spsi,\n spsi * stheta],\n [-spsi * cphi - ctheta * sphi * cpsi,\n -spsi * sphi + ctheta * cphi * cpsi,\n cpsi * stheta],\n [stheta * sphi,\n -stheta * cphi,\n ctheta]])\n\n # Calculate the points that could possibly be inside the volume\n # Since the points are rotated, we cannot do anything directional\n # without more logic\n max_radius = np.sqrt(\n np.abs(mat).dot([a_squared, b_squared, c_squared]))\n idx, shapes = _getshapes_3d(center, max_radius, space.shape)\n\n subgrid = [g[idi] for g, idi in zip(grid, shapes)]\n offset_points = [vec * (xi - x0i)[..., None]\n for xi, vec, x0i in zip(subgrid,\n mat.T,\n [x0, y0, z0])]\n rotated = offset_points[0] + offset_points[1] + offset_points[2]\n np.square(rotated, out=rotated)\n radius = np.dot(rotated, scales)\n else:\n # Calculate the points that could possibly be inside the volume\n max_radius = np.sqrt([a_squared, b_squared, c_squared])\n idx, shapes = _getshapes_3d(center, max_radius, space.shape)\n\n subgrid = [g[idi] for g, idi in zip(grid, shapes)]\n squared_dist = [ai * (xi - x0i) ** 2\n for xi, ai, x0i in zip(subgrid,\n scales,\n [x0, y0, z0])]\n\n # Parentheses to get best order for broadcasting\n radius = squared_dist[0] + (squared_dist[1] + squared_dist[2])\n\n # Find the points within the ellipse\n inside = radius <= 1\n\n # Add the ellipse intensity to those points\n p[idx][inside] += intensity\n\n return space.element(p)\n\n\ndef ellipsoid_phantom(space, ellipsoids, min_pt=None, max_pt=None):\n \"\"\"Return a phantom given by ellipsoids.\n\n Parameters\n ----------\n space : `DiscretizedSpace`\n Space in which the phantom should be created, must be 2- or\n 3-dimensional. If ``space.shape`` is 1 in an axis, a corresponding\n slice of the phantom is created (instead of squashing the whole\n phantom into the slice).\n ellipsoids : sequence of sequences\n If ``space`` is 2-dimensional, each row should contain the entries ::\n\n 'value',\n 'axis_1', 'axis_2',\n 'center_x', 'center_y',\n 'rotation'\n\n If ``space`` is 3-dimensional, each row should contain the entries ::\n\n 'value',\n 'axis_1', 'axis_2', 'axis_3',\n 'center_x', 'center_y', 'center_z',\n 'rotation_phi', 'rotation_theta', 'rotation_psi'\n\n The provided ellipsoids need to be specified relative to the\n reference rectangle ``[-1, -1] x [1, 1]``, or analogously in 3d.\n The angles are to be given in radians.\n\n min_pt, max_pt : array-like, optional\n If provided, use these vectors to determine the bounding box of the\n phantom instead of ``space.min_pt`` and ``space.max_pt``.\n It is currently required that ``min_pt >= space.min_pt`` and\n ``max_pt <= space.max_pt``, i.e., shifting or scaling outside the\n original space is not allowed.\n\n Providing one of them results in a shift, e.g., for ``min_pt``::\n\n new_min_pt = min_pt\n new_max_pt = space.max_pt + (min_pt - space.min_pt)\n\n Providing both results in a scaled version of the phantom.\n\n Notes\n -----\n The phantom is created by adding the values of each ellipse. The\n ellipses are defined by a center point\n ``(center_x, center_y, [center_z])``, the lengths of its principial\n axes ``(axis_1, axis_2, [axis_2])``, and a rotation angle ``rotation``\n in 2D or Euler angles ``(rotation_phi, rotation_theta, rotation_psi)``\n in 3D.\n\n This function is heavily optimized, achieving runtimes about 20 times\n faster than \"trivial\" implementations. It is therefore recommended to use\n it in all phantoms where applicable.\n\n The main optimization is that it only considers a subset of all the\n points when updating for each ellipse. It does this by first finding\n a subset of points that could possibly be inside the ellipse. This\n optimization is very good for \"spherical\" ellipsoids, but not so\n much for elongated or rotated ones.\n\n It also does calculations wherever possible on the meshgrid instead of\n individual points.\n\n Examples\n --------\n Create a circle with a smaller circle inside:\n\n >>> space = odl.uniform_discr([-1, -1], [1, 1], [5, 5])\n >>> ellipses = [[1.0, 1.0, 1.0, 0.0, 0.0, 0.0],\n ... [1.0, 0.6, 0.6, 0.0, 0.0, 0.0]]\n >>> print(ellipsoid_phantom(space, ellipses))\n [[ 0., 0., 1., 0., 0.],\n [ 0., 1., 2., 1., 0.],\n [ 1., 2., 2., 2., 1.],\n [ 0., 1., 2., 1., 0.],\n [ 0., 0., 1., 0., 0.]]\n\n See Also\n --------\n odl.phantom.transmission.shepp_logan : Classical Shepp-Logan phantom,\n typically used for transmission imaging\n odl.phantom.transmission.shepp_logan_ellipsoids : Ellipses for the\n Shepp-Logan phantom\n odl.phantom.geometric.defrise_ellipses : Ellipses for the\n Defrise phantom\n \"\"\"\n if space.ndim == 2:\n _phantom = _ellipse_phantom_2d\n elif space.ndim == 3:\n _phantom = _ellipsoid_phantom_3d\n else:\n raise ValueError('dimension not 2 or 3, no phantom available')\n\n if min_pt is None and max_pt is None:\n return _phantom(space, ellipsoids)\n\n else:\n # Generate a temporary space with given `min_pt` and `max_pt`\n # (snapped to the cell grid), create the phantom in that space and\n # resize to the target size for `space`.\n # The snapped points are constructed by finding the index of\n # `min/max_pt` in the space partition, indexing the partition with\n # that index, yielding a single-cell partition, and then taking\n # the lower-left/upper-right corner of that cell.\n if min_pt is None:\n snapped_min_pt = space.min_pt\n else:\n min_pt_cell = space.partition[space.partition.index(min_pt)]\n snapped_min_pt = min_pt_cell.min_pt\n\n if max_pt is None:\n snapped_max_pt = space.max_pt\n else:\n max_pt_cell = space.partition[space.partition.index(max_pt)]\n snapped_max_pt = max_pt_cell.max_pt\n # Avoid snapping to the next cell where max_pt falls exactly on\n # a boundary\n for i in range(space.ndim):\n if max_pt[i] in space.partition.cell_boundary_vecs[i]:\n snapped_max_pt[i] = max_pt[i]\n\n tmp_space = uniform_discr_fromdiscr(\n space, min_pt=snapped_min_pt, max_pt=snapped_max_pt,\n cell_sides=space.cell_sides)\n\n tmp_phantom = _phantom(tmp_space, ellipsoids)\n offset = space.partition.index(tmp_space.min_pt)\n return space.element(\n resize_array(tmp_phantom, space.shape, offset))\n\n\ndef smooth_cuboid(space, min_pt=None, max_pt=None, axis=0):\n \"\"\"Cuboid with smooth variations.\n\n Parameters\n ----------\n space : `DiscretizedSpace`\n Discretized space in which the phantom is supposed to be created.\n min_pt : array-like of shape ``(space.ndim,)``, optional\n Lower left corner of the cuboid. If ``None`` is given, a quarter\n of the extent from ``space.min_pt`` towards the inside is chosen.\n max_pt : array-like of shape ``(space.ndim,)``, optional\n Upper right corner of the cuboid. If ``None`` is given, ``min_pt``\n plus half the extent is chosen.\n axis : int or sequence of int\n Dimension(s) along which the smooth variation should happen.\n\n Returns\n -------\n phantom : ``space``-element\n The generated cuboid phantom in ``space``. Values have range [0, 1].\n \"\"\"\n dom_min_pt = space.domain.min()\n dom_max_pt = space.domain.max()\n\n if min_pt is None:\n min_pt = dom_min_pt * 0.75 + dom_max_pt * 0.25\n if max_pt is None:\n max_pt = dom_min_pt * 0.25 + dom_max_pt * 0.75\n\n min_pt = np.atleast_1d(min_pt)\n max_pt = np.atleast_1d(max_pt)\n\n axis = np.array(axis, dtype=int, ndmin=1)\n\n if min_pt.shape != (space.ndim,):\n raise ValueError('shape of `min_pt` must be {}, got {}'\n ''.format((space.ndim,), min_pt.shape))\n if max_pt.shape != (space.ndim,):\n raise ValueError('shape of `max_pt` must be {}, got {}'\n ''.format((space.ndim,), max_pt.shape))\n\n sign = 0\n for i, coord in enumerate(space.meshgrid):\n sign = sign | (coord < min_pt[i]) | (coord > max_pt[i])\n\n values = 0\n for i in axis:\n coord = space.meshgrid[i]\n extent = (dom_max_pt[i] - dom_min_pt[i])\n values = values + 2 * (coord - dom_min_pt[i]) / extent - 1\n\n # Properly scale using sign\n sign = (3 * sign - 2) / axis.size\n\n # Fit in [0, 1]\n values = values * sign\n values = (values - np.min(values)) / (np.max(values) - np.min(values))\n\n return space.element(values)\n\n\ndef tgv_phantom(space, edge_smoothing=0.2):\n \"\"\"Piecewise affine phantom.\n\n This phantom is taken from [Bre+2010] and includes both linearly varying\n regions and sharp discontinuities. It is designed to work well with\n Total Generalized Variation (TGV) type regularization.\n\n Parameters\n ----------\n space : `DiscretizedSpace`, 2 dimensional\n Discretized space in which the phantom is supposed to be created.\n Needs to be two-dimensional.\n edge_smoothing : nonnegative float, optional\n Smoothing of the edges of the phantom, given as smoothing width in\n units of minimum pixel size.\n\n Returns\n -------\n phantom : ``space``-element\n The generated phantom in ``space``. Values have range [0, 1].\n\n Notes\n -----\n The original phantom is given by a specific image. In this implementation,\n we extracted the underlying parameters and the phantom thus works with\n spaces of any shape. Due to this, small variations may occur when compared\n to the original phantom.\n\n References\n ----------\n [Bre+2010] K. Bredies, K. Kunisch, and T. Pock.\n *Total Generalized Variation*. SIAM Journal on Imaging Sciences,\n 3(3):492-526, Jan. 2010\n \"\"\"\n if space.ndim != 2:\n raise ValueError('`space.ndim` must be 2, got {}'\n ''.format(space.ndim))\n\n y, x = space.meshgrid\n\n # Use a smooth sigmoid to get some anti-aliasing across edges.\n scale = edge_smoothing / np.min(space.shape)\n\n def sigmoid(val):\n if edge_smoothing != 0:\n val = val / scale\n with np.errstate(over=\"ignore\", under=\"ignore\"):\n return 1 / (1 + np.exp(-val))\n else:\n return (val > 0).astype(val.dtype)\n\n # Normalize to [0, 1]\n x = (x - np.min(x)) / (np.max(x) - np.min(x))\n y = (y - np.min(y)) / (np.max(y) - np.min(y))\n\n # Background\n values = -(x + y) / 2\n\n # Square-ish region\n indicator = np.ones(space.shape)\n indicator *= sigmoid(-(0.015199034981905914 * x - y + 0.13896260554885403))\n indicator *= sigmoid((0.3333333333333323 * y - x + 0.598958333333334))\n indicator *= sigmoid((-2.4193548387096726 * y - x + 2.684979838709672))\n\n values += indicator * 2 * (x + y - 1)\n\n # Ellipse part\n x_c = x - 0.71606842360499456\n y_c = y - 0.18357884949910641\n\n width = 0.55677657235995637\n height = 0.37279391542283741\n phi = 0.62911754900697558\n\n x_c_rot = (np.cos(phi) * x_c - np.sin(phi) * y_c) / width\n y_c_rot = (np.sin(phi) * x_c + np.cos(phi) * y_c) / height\n\n indicator = sigmoid(np.sqrt(x_c_rot ** 2 + y_c_rot ** 2) - 1)\n\n values = indicator * values + 1.5 * (1 - indicator) * (-x - 2 * y + 0.6)\n\n # Normalize values\n values = (values - np.min(values)) / (np.max(values) - np.min(values))\n\n return space.element(values)\n\n\nif __name__ == '__main__':\n # Show the phantoms\n import odl\n\n # cuboid 1D\n space = odl.uniform_discr(-1, 1, 300)\n cuboid(space).show('cuboid 1d')\n\n # cuboid 2D\n space = odl.uniform_discr([-1, -1], [1, 1], [300, 300])\n cuboid(space).show('cuboid 2d')\n\n # smooth cuboid\n smooth_cuboid(space).show('smooth_cuboid x 2d')\n smooth_cuboid(space, axis=[0, 1]).show('smooth_cuboid x-y 2d')\n\n # TGV phantom\n tgv_phantom(space).show('tgv_phantom')\n\n # cuboid 3D\n space = odl.uniform_discr([-1, -1, -1], [1, 1, 1], [300, 300, 300])\n cuboid(space).show('cuboid 3d')\n\n # Indicate proj axis 3D\n indicate_proj_axis(space).show('indicate_proj_axis 3d')\n\n # ellipsoid phantom 2D\n space = odl.uniform_discr([-1, -1], [1, 1], [300, 300])\n ellipses = [[1.0, 1.0, 1.0, 0.0, 0.0, 0.0],\n [1.0, 0.6, 0.6, 0.0, 0.0, 0.0]]\n ellipsoid_phantom(space, ellipses).show('ellipse phantom 2d')\n\n # ellipsoid phantom 3D\n space = odl.uniform_discr([-1, -1, -1], [1, 1, 1], [300, 300, 300])\n ellipsoids = [[1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],\n [1.0, 0.6, 0.6, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]\n ellipsoid_phantom(space, ellipsoids).show('ellipsoid phantom 3d')\n\n # Defrise phantom 2D\n space = odl.uniform_discr([-1, -1], [1, 1], [300, 300])\n defrise(space).show('defrise 2D')\n\n # Defrise phantom 2D\n space = odl.uniform_discr([-1, -1, -1], [1, 1, 1], [300, 300, 300])\n defrise(space).show('defrise 3D', coords=[0, None, None])\n\n # Run also the doctests\n from odl.util.testutils import run_doctests\n run_doctests()\n","repo_name":"odlgroup/odl","sub_path":"odl/phantom/geometric.py","file_name":"geometric.py","file_ext":"py","file_size_in_byte":31879,"program_lang":"python","lang":"en","doc_type":"code","stars":325,"dataset":"github-code","pt":"9"} +{"seq_id":"43397172558","text":"import numpy as np\nimport matplotlib.pyplot as plt\n#If using termux\n#import subprocess\n#import shlex\n#end if\n\nx=np.array([1.0,2.0,3.0,4.0,2.0,1.0])\ny=np.loadtxt('y.txt', dtype='double')\nk = 20\n\n#subplots\nplt.subplot(2, 1, 1)\nplt.stem(range(0,6),x)\nplt.ylabel('$x(n)$')\nplt.grid()# minor\n\nplt.subplot(2, 1, 2)\nplt.stem(range(0,k),y)\nplt.xlabel('$n$')\nplt.ylabel('$y(n)$')\nplt.grid()# minor\n\n#If using termux\nplt.savefig('../figs/3_2.png')\n#subprocess.run(shlex.split(\"termux-open ../figs/xnyn.pdf\"))\n#else\n#plt.show()\n","repo_name":"DarkWake9/EE3900","sub_path":"Assignment 1/codes/3_2.py","file_name":"3_2.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"9"} +{"seq_id":"1324918887","text":"\"\"\"\nDefine the main classes for managing the DokuWiki content in connection\nwith Airtable, i.e. creating new pages or updating the existing ones.\n\"\"\"\n\nimport os\nimport dokuwiki as dw\nimport wikicontents\nimport json\n\n\nclass WikiManager:\n \"\"\"Manager class that provides short-hand access to content editing functionality.\n\n Attributes:\n wiki (DokuWiki): wiki object that will be used to fetch and post content\n user_key: user API key to the Airtable\n table (Table): table object that will be instantiated and used to format content\n used_table_name (str): table name in the Airtable\n defined_tables (list): a list of tables that have defined formats\n\n \"\"\"\n def __init__(self, version):\n \"\"\"Instantiate a manager for a particular wiki version.\n This sets up a connection to the wiki, fetches Airtable API key and defines which tables\n in the Airtable database have their templates defined.\n\n Args:\n version (str): wiki version to interface with (official or test)\n \"\"\"\n with open('config.json', 'r') as f:\n config = json.load(f)\n if version not in [\"official\", \"test\"]:\n print('Unknown version specified, choose from: \"official\" or \"test\".')\n return\n else:\n self.wiki = dw.DokuWiki(config[version][\"wiki_url\"],\n config[version][\"username\"],\n os.environ[config[version][\"password_key\"]])\n self.user_key = os.environ['AIRTABLE_API_KEY']\n self.table = None\n self.used_table_name = None\n self.defined_tables = ['Tools', 'Charity_experiments', 'Giving_companies_ftse', 'Giving_companies_other',\n 'Experiences', 'Third_sector', 'papers_mass_qualitative',\n 'papers_mass_quantitative', 'Categories']\n self.maintained_tables = ['papers_mass_qualitative']\n\n def setup_table(self, table_name):\n \"\"\"Initialize the connection to a given table in Airtable.\n This is accomplished by instantiating a specific object of a Table class.\n\n Args:\n table_name: the name of the table in the Airtable database\n\n Returns:\n Table object\n \"\"\"\n if table_name == 'Tools':\n table_base = 'appBzOSifwBqSuVfH'\n self.table = wikicontents.ToolTable(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n elif table_name == 'Giving_companies_ftse':\n table_base = 'apprleNrkR7dTtW60'\n table_name = 'Giving_companies'\n self.table = wikicontents.FtseTable(self.wiki, table_base, table_name, self.user_key, 'FTSE100')\n self.used_table_name = table_name\n\n elif table_name == 'Giving_companies_other':\n table_base = 'apprleNrkR7dTtW60'\n table_name = 'Giving_companies'\n self.table = wikicontents.FtseTable(self.wiki, table_base, table_name, self.user_key, 'Other')\n self.used_table_name = table_name\n\n elif table_name == 'Charity_experiments':\n table_base = 'appBzOSifwBqSuVfH'\n self.table = wikicontents.ExperimentTable(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n elif table_name == 'Experiences':\n table_base = 'appBzOSifwBqSuVfH'\n self.table = wikicontents.ExperienceTable(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n elif table_name == 'Third_sector':\n table_base = 'appBzOSifwBqSuVfH'\n self.table = wikicontents.ThirdSectorTable(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n elif table_name == 'papers_mass_qualitative':\n table_base = 'appBzOSifwBqSuVfH'\n table_name = 'papers_mass'\n self.table = wikicontents.PapersTable(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n elif table_name == 'papers_mass_quantitative':\n table_base = 'appBzOSifwBqSuVfH'\n table_name = 'papers_mass'\n self.table = wikicontents.MetaAnalysisTable(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n elif table_name == 'Categories':\n table_base = 'appBzOSifwBqSuVfH'\n self.table = wikicontents.CategoryTable(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n elif table_name == 'effective_charities_rated':\n table_base = 'appBzOSifwBqSuVfH'\n self.table = wikicontents.EffectiveCharities(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n else:\n table_base = 'appBzOSifwBqSuVfH'\n self.table = wikicontents.Table(self.wiki, table_base, table_name, self.user_key)\n self.used_table_name = table_name\n\n def create_table(self):\n \"\"\"Create a new Wiki table from an Airtable table.\"\"\"\n self.table.set_table_page()\n print(\"Go to {} in your DokuWiki to see the table.\".format(self.table.dw_table_page))\n if self.used_table_name not in self.defined_tables:\n print(\"To change the table formatting, implement an appropriate class.\")\n\n def create_pages(self):\n \"\"\"Create a set of Wiki pages from an Airtable table.\"\"\"\n self.table.set_pages()\n if self.used_table_name not in self.defined_tables:\n print(\"Go to 'test:test_page' in your DokuWiki to see the possible page content. \"\n \"To change its formatting, please implement an appropriate class.\")\n else:\n print(\"Go to {} namespace in your DokuWiki to see the pages.\".format(self.table.root_namespace))\n\n def create_table_pages(self):\n \"\"\"Create a table and a set of pages on the Wiki from an Airtable table.\"\"\"\n self.table.set_table_page()\n print(\"Go to {} in your DokuWiki to see the table.\".format(self.table.dw_table_page))\n if self.table.linked_pages:\n self.table.set_pages()\n if self.used_table_name not in self.defined_tables:\n print(\"Go to 'test:test_page' in your DokuWiki to see the possible page content.\\n \"\n \"To change the formatting of this table and pages, implement an appropriate class.\")\n else:\n print(\"Go to {} namespace in your DokuWiki to see the pages.\".format(self.table.root_namespace))\n else:\n print(\"This table does not have associated pages. Only the table has been created.\")\n\n def update_table_source(self):\n for record in self.table.records:\n if 'Modified' in record['fields']:\n self.table.update_record(record)\n\n def update_table(self):\n \"\"\"Re-generate a full table on the Wiki if any record in Airtable table has been modified.\n When done, reset the 'Modified' fields in the Airtable.\"\"\"\n modified_records = 0\n for record in self.table.records:\n if 'Modified' in record['fields']:\n modified_records += 1\n self.table.airtable.update(record['id'], {'Modified': False})\n if modified_records > 0:\n self.table.set_table_page()\n\n def update_pages(self):\n \"\"\"Re-generate the pages on Wiki associated with any records that have been modified in the Airtable.\n When done, reset the 'Modified' fields in the Airtable.\"\"\"\n modified_records = []\n for record in self.table.records:\n if 'Modified' in record['fields']:\n modified_records.append(record)\n self.table.airtable.update(record['id'], {'Modified': False})\n if len(modified_records) > 0:\n self.table.records = modified_records\n self.table.set_pages()\n\n def update_table_pages(self):\n \"\"\"Re-generate the full table on the Wiki if any record has been modified, as well as associated pages.\n When done, reset the 'Modified' fields in the Airtable.\"\"\"\n modified_records = []\n for record in self.table.records:\n if 'Modified' in record['fields']:\n modified_records.append(record)\n self.table.airtable.update(record['id'], {'Modified': False})\n if len(modified_records) > 0:\n self.table.set_table_page()\n self.table.records = modified_records\n self.table.set_pages()\n print(\"Updated {} records in table {}.\".format(len(modified_records), self.used_table_name))\n","repo_name":"katsangati/fundingwiki","sub_path":"wikimanager.py","file_name":"wikimanager.py","file_ext":"py","file_size_in_byte":8798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"22287354600","text":"import numpy as np\nfrom matplotlib import pyplot\nfrom math import sqrt,log \nimport pickle\n\nk=10\nsteps = 100\nbandit_problem = [] \nnum_problems = 2000\n\nwith open ('testbed', 'rb') as fp:\n bandit_problem = pickle.load(fp)\n\nq_max = np.argmax(bandit_problem,axis=1)\n\n\nopt_actions = []\naverage_rewards = []\n\nepsilon_list = [0.1]\n# epsilon_list = [0.1,0.3]\nAvg_1000_steps = []\n\nError_list = []\n\nflag = False\n\nfor epsilon in epsilon_list:\n\t# epsilon = 1 is considered as decaying epsilon case\n\tif epsilon == 1:\n\t\tflag = True\n\terror = 0 \n\topt_action_count = np.zeros(steps+1)\n\tavg_eps_greedy = np.zeros(steps)\n\taverage = 0\n\tfor i in range(num_problems):\n\t\t# print (i)\n\t\tQ = np.zeros(k)\n\t\tN = np.zeros(k)\n\t\tq = bandit_problem[i]\n\t\taction = -1\t\t\n\t\ttemp = np.zeros(steps+1)\n\t\ttemp_rewards = []\n\n\t\tfor t in range(1,steps+1):\n\t\t\tif flag == True:\n\t\t\t\tepsilon = 1.0/t\n\t\t\t\n\t\t\t# Sample from distribution using idea of picking randomly uniformly from CDF\n\t\t\trand = np.random.uniform()\n\t\t\tif(rand >= epsilon):\n\t\t\t\taction = np.argmax(Q) # greedy choice\n\t\t\telse:\n\t\t\t\taction = np.random.randint(k) # random exploration\n\n\t\t\t# Maintain counts for optimal action taken\t\n\t\t\tif action == q_max[i]:\n\t\t\t\ttemp[t] = 1\n\t\t\telse:\n\t\t\t\ttemp[t] = 0\n\n\t\t\t# sample from rewrd distribution , variance =1 is implicit.\n\t\t\treward = np.random.normal(q[action])\n\t\t\ttemp_rewards += [reward]\n\t\t\tN[action]+= 1\n\t\t\t#incremental averages\n\t\t\tQ[action]+= (reward-Q[action])/N[action]\n\t\taverage += (np.sum(temp_rewards) - average) / (i+1)\n\t\tfor j in range(steps):\n\t\t\tavg_eps_greedy[j] += (temp_rewards[j]-avg_eps_greedy[j])/(i+1)\n\n\t\topt_action_count = np.add(opt_action_count,temp)\n\n\t\t# calculate how many times final arm is suboptimal\n\t\terror += (q_max[i] != np.argmax(Q))\n\tprint (\"Error for \"+str(epsilon)+\" is \",error/20.0)\n\tError_list += [error/20.0]\n\tAvg_1000_steps += [average]\n\n\t# print (opt_action_count)\n\n\topt_action_count = np.multiply(np.divide(opt_action_count,2000.0),100)\n\t\n\taverage_rewards += [avg_eps_greedy]\n\topt_actions += [opt_action_count[1:]]\n\nwith open('eps_greedy', 'wb') as fp:\n pickle.dump([average_rewards,opt_actions,epsilon_list,Avg_1000_steps,Error_list], fp)","repo_name":"cs15b047/Reinforcement_Learning","sub_path":"CS15B047_PA1/Code/Eps-greedy.py","file_name":"Eps-greedy.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"26679228748","text":"from datetime import datetime\nfrom typing import List, Optional\n\nfrom attrs import frozen\n\nfrom fixbackend.ids import InvitationId, WorkspaceId, UserId, ExternalId, SecurityTier\n\n\n@frozen\nclass Workspace:\n id: WorkspaceId\n slug: str\n name: str\n external_id: ExternalId\n owners: List[UserId]\n members: List[UserId]\n security_tier: SecurityTier\n\n def all_users(self) -> List[UserId]:\n return self.owners + self.members\n\n\n@frozen\nclass WorkspaceInvitation:\n id: InvitationId\n workspace_id: WorkspaceId\n email: str\n expires_at: datetime\n accepted_at: Optional[datetime]\n","repo_name":"someengineering/fixbackend","sub_path":"fixbackend/workspaces/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"23068078601","text":"import os\nimport re\nimport subprocess # nosec\n\nfrom django.core.management.base import BaseCommand, CommandError\n\n\nclass Command(BaseCommand):\n \"\"\"\n Load schema from remote Heroku PostgreSQL database.\n\n This command can be useful to load the Heroku Connect database schema into\n a local development environment.\n\n Example::\n\n python manage.py load_remote_schema --app ninja | psql -a\n\n .. note::\n\n This command requires the `Heroku CLI`_ and PostgreSQL_ to be installed.\n\n .. _`Heroku CLI`: https://cli.heroku.com/\n .. _PostgreSQL: https://www.postgresql.org/\n\n \"\"\"\n\n help = __doc__.strip().splitlines()[0]\n\n url_pattern = (\n r\"postgres://(?P[\\d\\w]*):(?P[\\d\\w]*)\"\n r\"@(?P[^:]+):(?P\\d+)/(?P[\\d\\w]+)\"\n )\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--app\",\n \"-a\",\n dest=\"HEROKU_APP\",\n type=str,\n help=\"Heroku app name that the schema will be pulled from.\",\n )\n parser.add_argument(\n \"--schema\",\n \"-s\",\n dest=\"SCHEMA_NAME\",\n type=str,\n default=\"salesforce\",\n help=\"Name of schema that you want to load.\",\n )\n\n def handle(self, *args, **options):\n heroku_app = options.get(\"HEROKU_APP\")\n schema_name = options[\"SCHEMA_NAME\"]\n url = self.get_database_url(heroku_app)\n credentials = self.parse_credentials(url)\n schema = self.get_schema(**credentials, schema_name=schema_name)\n self.stdout.write(schema)\n\n @staticmethod\n def get_database_url(heroku_app):\n run_args = [\"heroku\", \"pg:credentials:url\"]\n if heroku_app:\n run_args += [\"-a\", heroku_app]\n\n try:\n output = subprocess.check_output(run_args) # nosec\n except subprocess.SubprocessError as e:\n raise CommandError(\"Please provide the correct Heroku app name.\") from e\n else:\n return output.decode(\"utf-8\")\n\n def parse_credentials(self, url):\n match = re.search(self.url_pattern, url)\n if not match:\n raise CommandError(\"Could not parse DATABASE_URL.\")\n\n return match.groupdict()\n\n @staticmethod\n def get_schema(user, host, port, dbname, passwd, schema_name):\n env = os.environ.copy()\n env[\"PGPASSWORD\"] = passwd\n\n run_args = [\n \"pg_dump\",\n \"-sO\",\n \"-n\",\n schema_name,\n \"-U\",\n user,\n \"-h\",\n host,\n \"-p\",\n port,\n \"-d\",\n dbname,\n ]\n\n try:\n output = subprocess.check_output(run_args, env=env) # nosec\n except subprocess.SubprocessError as e:\n raise CommandError(\"Schema not found.\") from e\n else:\n return output.decode(\"utf-8\")\n","repo_name":"thermondo/django-heroku-connect","sub_path":"heroku_connect/management/commands/load_remote_schema.py","file_name":"load_remote_schema.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"9"} +{"seq_id":"18264029037","text":"# работает!!!\r\ndef sorter(point):\r\n return point[0]\r\n\r\nn = int(input())\r\ntowns = list(map(int, input().split()))\r\nm = int(input())\r\nshelters = list(map(int, input().split()))\r\nfor i in range(n):\r\n towns[i] = (towns[i], i + 1)\r\nfor i in range(m):\r\n shelters[i] = (shelters[i], i + 1)\r\ntowns.sort()\r\nshelters.sort()\r\ni = 0\r\nj = 0\r\nv = []\r\nwhile i < len(towns):\r\n if j == len(shelters) - 1:\r\n v.append((towns[i][1], shelters[j][1]))\r\n else:\r\n if towns[i][0] <= shelters[j][0] + ((shelters[j+1][0] - shelters[j][0])//2):\r\n v.append((towns[i][1], shelters[j][1]))\r\n elif towns[i][0] > shelters[j][0] + ((shelters[j+1][0] - shelters[j][0])//2):\r\n j += 1\r\n continue\r\n i += 1\r\nv.sort(key=sorter)\r\nfor i in range(len(v)):\r\n print(v[i][1], end=' ')","repo_name":"LjahinaSV/LSV","sub_path":"EDU/Coursera/Week6/task6_04_GO_proba.py","file_name":"task6_04_GO_proba.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"28536038910","text":"import unittest\nimport datetime\nimport json\nfrom simulator.domain.reefer_simulator import ReeferSimulator \n\n\nclass TestReeferSimulator(unittest.TestCase):\n \n def testCreation(self):\n print(\"should have one instance\")\n simul = ReeferSimulator()\n self.assertIsNotNone(simul)\n \n def testNormalRecords(self):\n simul = ReeferSimulator()\n df=simul.generateNormalRecords(nb_records = 4)\n self.assertIsNotNone(df)\n for idx, content in df.items():\n print(content)\n\n def testGeneratingPowerOff(self):\n simul = ReeferSimulator()\n df=simul.generatePowerOffRecords(cid=\"C01\",nb_records = 100, product_id= \"P02\")\n self.assertIsNotNone(df)\n self.assertEqual(df.size, 2000) # nb of rows x nbr of columns\n df2 = df.loc[df['maintenance_required'] == 1]\n for idx, content in df2.items():\n print(content)\n \n\n def testGeneratingCo2(self):\n simul = ReeferSimulator()\n df=simul.generateCo2Records(cid=\"C01\",nb_records = 100, product_id= \"P02\")\n self.assertIsNotNone(df)\n self.assertEqual(df.size, 2000) # nb of rows x nbr of columns\n\n\n def testGenerateO2(self):\n simul = ReeferSimulator()\n values = simul.generateO2Tuples(cid=\"C01\",nb_records = 100, product_id= \"P02\")\n \n\n def testGenerateCO2tuples(self):\n simul = ReeferSimulator()\n values = simul.generateCo2Tuples(cid=\"C02\",nb_records = 10, product_id= \"P03\")\n for value in values:\n print(value)\n\nif __name__ == '__main__':\n unittest.main()\n\n","repo_name":"ibm-cloud-architecture/refarch-reefer-ml","sub_path":"simulator/test/unit/TestSimulator.py","file_name":"TestSimulator.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"9"} +{"seq_id":"37344726442","text":"# Figure out which words appear most often in the headlines.\n\nimport read\nimport collections\n\ndf = read.load_data()\n#print(df.head())\n\n# Make headlines list\nheadlines = df['headline'].tolist()\n#print(headlines[0])\n\nresult = ''\n# Combine all headlines in list into one string\nfor h in headlines:\n result += str(h) + ' '\n# Change headlines string to lowercase and remove \"()\"\nresult = result.lower().replace('(', '').replace(')', '')\n\n# Split headline string into words list\nwords_list = result.split(' ')\n#print(words_list)\n\n# Use Counter class method\nmost_com = collections.Counter(words_list).most_common(100)\n\nprint(most_com)\n\n\n\n\n\n","repo_name":"llwang8/Data_Science_Portfolio","sub_path":"CommandLine/Project_ Transforming data with Python/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"9"} +{"seq_id":"2241178702","text":"from pathlib import Path\nfrom typing import Dict, List, Mapping, Optional, Set\n\nfrom kolga.utils.general import get_environment_vars_by_prefix, get_project_secret_var\nfrom kolga.utils.models import HelmValues\n\n\nclass Service:\n \"\"\"\n A service is a by Helm deployable software\n\n A service takes care of storing the configuration needed\n to deploy a service to Kubernetes. It also stores metadata\n about the service so that it can be shared with other services\n if need be.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n track: str,\n values: Optional[HelmValues] = None,\n artifact_name: Optional[str] = None,\n values_files: Optional[List[Path]] = None,\n chart: str = \"\",\n chart_path: Optional[Path] = None,\n chart_version: Optional[str] = None,\n depends_on: Optional[Set[\"Service\"]] = None,\n ) -> None:\n self.name = name\n self.track = track\n self.values = values or {}\n self.artifact_name = artifact_name\n self.values_files: List[Path] = values_files or []\n self.chart = chart\n self.chart_path = chart_path\n self.chart_version = chart_version\n self.depends_on: Set[\"Service\"] = depends_on or set()\n self._prerequisite_of: Set[\"Service\"] = set()\n self._validate_chart()\n self.service_specific_values = self._get_service_variables()\n\n def _validate_chart(self) -> None:\n if not self.chart and not self.chart_path:\n raise ValueError(\"Either chart or chart_name must be defined\")\n\n def _get_service_variables(self) -> Dict[str, str]:\n return get_environment_vars_by_prefix(f\"K8S_SERVICE_{self.name.upper()}_\")\n\n def add_dependency(self, service: \"Service\") -> None:\n self.depends_on.add(service)\n service.add_prerequisite(self)\n\n def add_prerequisite(self, service: \"Service\") -> None:\n self._prerequisite_of.add(service)\n if self not in service.depends_on:\n service.add_dependency(self)\n\n def setup_prerequisites(self) -> None:\n pass\n\n def get_artifacts(self) -> Mapping[str, str]:\n return {}\n\n def get_service_secret_artifact_name(self, service: \"Service\") -> str:\n if not self.artifact_name:\n raise ValueError(f\"No artifact name set for the service {self.name}\")\n\n return get_project_secret_var(\n project_name=service.name, value=self.artifact_name\n )\n","repo_name":"andersinno/kolga","sub_path":"kolga/libs/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"9"} +{"seq_id":"21477255559","text":"from random import choice #for a random number\nfrom turtle import * #turtle is a pre-installed Python library that enables users to create pictures and shapes by providing them with a virtual canvas\n\nfrom freegames import floor, vector\n\nstate = {'score': 0} #number of pellets eaten\npath = Turtle(visible=False) #turtle which removes pellets\nwriter = Turtle(visible=False) #turtle which changes the score\naim = vector(0, 0) #can be changed to give pacman an initial direction\npacman = vector(0, 0)#pacmans starting coordinates\nghosts = [\n [vector(-180, 160), vector(5, 0)],\n [vector(-180, -160), vector(0, 5)],\n [vector(100, 160), vector(0, -5)],\n [vector(100, -160), vector(-5, 0)],\n]#ghosts starting coordinates\n#self made maze 0:wall 1:path\ntiles = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0,\n 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0,\n 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0,\n 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0,\n 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0,\n 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0,\n 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0,\n 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0,\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0,\n 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0,\n 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0,\n 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0,\n 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0,\n 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0,\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n]\n\n\n\ndef square(x, y):\n #Draw square using path at (x, y)\n path.up()#pen up\n path.goto(x, y)#position change\n path.down()#pen down\n path.begin_fill()#called before filling begins for any closed object\n\n for count in range(4):#for drawing four sides of a square\n path.forward(20)#moves forward 20 units\n path.left(90)#turns 90 degrees\n\n path.end_fill()#called to end filling\n\n\ndef offset(point):\n \"Return offset of point in tiles.\"\n x = (floor(point.x, 20) + 200) / 20\n y = (180 - floor(point.y, 20)) / 20\n index = int(x + y * 20)\n return index\n\n\ndef valid(point):\n \"Return True if point is valid in tiles.\"\n index = offset(point)\n\n if tiles[index] == 0:\n return False\n\n index = offset(point + 19)\n\n if tiles[index] == 0:\n return False\n\n return point.x % 20 == 0 or point.y % 20 == 0\n\n\ndef world():\n \"Draw world using path.\"\n bgcolor('black')\n path.color('blue')\n\n for index in range(len(tiles)):\n tile = tiles[index]\n\n if tile > 0:\n x = (index % 20) * 20 - 200\n y = 180 - (index // 20) * 20\n square(x, y)\n\n if tile == 1:\n path.up()\n path.goto(x + 10, y + 10)\n path.dot(2, 'white')\n\n\ndef move():\n \"Move pacman and all ghosts.\"\n writer.undo()\n writer.write(state['score'])\n\n clear()\n\n if valid(pacman + aim):\n pacman.move(aim)\n\n index = offset(pacman)\n\n if tiles[index] == 1:\n tiles[index] = 2\n state['score'] += 1\n x = (index % 20) * 20 - 200\n y = 180 - (index // 20) * 20\n square(x, y)\n\n up()\n goto(pacman.x + 10, pacman.y + 10)\n dot(20, 'yellow')\n\n for point, course in ghosts:\n if valid(point + course):\n point.move(course)\n else:\n options = [\n vector(5, 0),\n vector(-5, 0),\n vector(0, 5),\n vector(0, -5),\n ]\n plan = choice(options)\n course.x = plan.x\n course.y = plan.y\n\n up()\n goto(point.x + 10, point.y + 10)\n dot(20, 'red')\n\n update()\n\n for point, course in ghosts:\n if abs(pacman - point) < 20:\n return\n\n ontimer(move, 100)\n\n\ndef change(x, y):\n \"Change pacman aim if valid.\"\n if valid(pacman + vector(x, y)):\n aim.x = x\n aim.y = y\n\n\nsetup(420, 420, 500, 200)\nhideturtle()\ntracer(False)\nwriter.goto(160, 160)\nwriter.color('white')\nwriter.write(state['score'])\nlisten()\nonkey(lambda: change(5, 0), 'Right')\nonkey(lambda: change(-5, 0), 'Left')\nonkey(lambda: change(0, 5), 'Up')\nonkey(lambda: change(0, -5), 'Down')\nworld()\nmove()\ndone()","repo_name":"Ash1129/Retro-Classics-Games-CG","sub_path":"Code/pacman.py","file_name":"pacman.py","file_ext":"py","file_size_in_byte":4767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"4505394581","text":"import argparse\nimport asyncio\nimport logging\n\nfrom wave_reader.wave import WaveDevice\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nasync def run(args):\n async with WaveDevice.create(args.address, args.serial) as conn:\n services = await conn.get_services()\n return services\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Wave sensor readings\")\n parser.add_argument(\"-a\", \"--address\", help=\"Device address\", required=True)\n parser.add_argument(\"-s\", \"--serial\", help=\"Device serial number\", required=True)\n\n args = parser.parse_args()\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run(args))\n","repo_name":"olliewalsh/wave-reader-utils","sub_path":"examples/get_services.py","file_name":"get_services.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"9"} +{"seq_id":"26510433857","text":"\"\"\"\nSelenium browser object creation with methods to completely run through\nprocess of searching for a product and adding it to the cart.\n\"\"\"\n\n# Use of manual sleeps unfortunately needed in certain methods due to\n# inconsistency of Selenium expected_conditions behavior with Amazon.\n# A custom exception class will be needed to address this.\n\nimport sys\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\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.common.exceptions import NoSuchElementException, TimeoutException\nimport config\n\nclass AmazonProductFinder():\n \"\"\"\n Create Selenium browser object based off of user browser choice.\n Executes search and add-to-cart of user's product search.\n \"\"\"\n def __init__ (self, browser, website_url, product_search):\n \"\"\"\n Accept 3 parameters: browser type, website URL and product to search.\n Create Selenium driver object, browse to website URL on specified\n browser.\n \"\"\"\n self.browser = browser\n self.website_url = website_url.lower()\n self.product_search = product_search.lower()\n\n if 'chrome' in self.browser:\n options = webdriver.ChromeOptions()\n options.add_experimental_option(\"detach\", True)\n self.web_driver = webdriver.Chrome(chrome_options=options)\n elif 'firefox' in self.browser:\n self.web_driver = webdriver.Firefox()\n else:\n self.web_driver = webdriver.Safari()\n self.web_driver.maximize_window()\n\n self.web_driver.get(website_url)\n self.wait = WebDriverWait(self.web_driver, 20)\n\n def user_login(self):\n \"\"\"\n Log into amazon. This method is UNUSED for now as logging in\n via Selenium requires granting authentication permission via email.\n \"\"\"\n self.web_driver.find_element(By.XPATH,\n \"//*[@id='nav-link-accountList']\").click()\n self.web_driver.find_element(\n By.XPATH, \"//*[@id='ap_email']\").send_keys(config.USERNAME,\n Keys.ENTER)\n self.web_driver.find_element(By.XPATH,\n \"//*[@id='ap_password']\").send_keys(config.PASSWORD, Keys.ENTER)\n\n def search_for_product(self):\n \"\"\"Search for the product that was specified in the user prompt.\"\"\"\n self.wait.until(ec.visibility_of_element_located((By.XPATH,\n \"//*[@id='twotabsearchtextbox']\"))).send_keys(\n self.product_search, Keys.ENTER)\n if self.check_search_validity() is not None:\n print(\"ERROR! Search did not yield results. Exiting program.\")\n self.close_browser_window()\n sys.exit()\n\n def check_search_validity(self):\n \"\"\"Verify that the search yielded at least one result.\"\"\"\n try:\n self.no_results = (self.web_driver.find_element(By.XPATH,\n \"//*[contains(text(), 'No results')]\"))\n return self.no_results\n except NoSuchElementException:\n pass\n\n def adjust_sort_order(self):\n \"\"\"Adjust search filter to filter by highest average review.\"\"\"\n # Loop logic needed here as occasionally Selenium will not find xpath\n # despite xpath exiting in page XML.\n while True:\n try:\n sleep(5)\n self.web_driver.find_element(By.XPATH,\n \"//*[@id='a-autoid-0-announce']\").click()\n sleep(3)\n self.web_driver.find_element(By.XPATH,\n \"//*[@id='s-result-sort-select_3']\").click()\n break\n except NoSuchElementException:\n continue\n\n def go_to_product_page(self):\n \"\"\"Click on first result for product page.\"\"\"\n # XML here is dynamic and the search result ID varies depending on\n # whether or not the item is tagged as a \"best seller\"\n sleep(5)\n best_seller = False\n try:\n product_result = self.web_driver.find_element(By.XPATH,\n \"//*[@data-cel-widget='search_result_1']//img\")\n except NoSuchElementException:\n best_seller = True\n if best_seller:\n product_result = self.web_driver.find_element(By.XPATH,\n \"//*[@data-cel-widget='search_result_2']//img\")\n product_result.click()\n\n def add_product_to_cart(self):\n \"\"\"Add product to cart and decline extended warranty if present.\"\"\"\n try:\n sleep(5)\n self.web_driver.find_element(By.XPATH,\n \"//*[@id='add-to-cart-button']\").click()\n sleep(5)\n self.decline_warranty_offer()\n except NoSuchElementException:\n print(\"ERROR! Item does not have an 'add to cart' button.\")\n print(\"Please re-run script and choose a product that can be \"\n \"added to an Amazon cart.\")\n print(\"Exiting program.\")\n sys.exit()\n\n def decline_warranty_offer(self):\n \"\"\"Decline warranty offer pop up.\"\"\"\n try:\n # Amazon does not always present warranty dialogue for all products\n # Javascript neccessary as there is a Selenium bug with modal interactions\n decline_warranty_offer = self.web_driver.find_element(By.XPATH,\n \"/html/body/div[4]/div/div/header/button\")\n self.web_driver.execute_script(\"arguments[0].click();\",\n decline_warranty_offer)\n except NoSuchElementException:\n pass\n\n def go_to_cart(self):\n \"\"\"Navigate to shopping cart.\"\"\"\n try:\n self.wait.until(ec.element_to_be_clickable((By.XPATH,\n \"//*[@id='hlb-view-cart-announce']\"))).click()\n except TimeoutException:\n sidesheet_view = True\n if sidesheet_view:\n try:\n self.wait.until(ec.element_to_be_clickable((By.XPATH,\n \"//*[@id='attach-sidesheet-view-cart-button']/span/input\"\n ))).click()\n except NoSuchElementException:\n print(\"Unexpected XML layout. Closing program.\")\n sys.exit()\n\n def close_browser_window(self):\n \"\"\"Issue quit against web driver object.\"\"\"\n self.web_driver.quit()\n","repo_name":"alpineaddict/amazon-product-finder","sub_path":"browser_webdriver.py","file_name":"browser_webdriver.py","file_ext":"py","file_size_in_byte":6404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"37242912548","text":"#!/usr/bin/env python2\nimport bluetooth, sys, argparse\n\n\ndef enumerate_rfcomm(**kw):\n svcs = bluetooth.find_service(address=kw['mac'])\n for serv in svcs:\n name = serv['name']\n proto = serv['protocol']\n port = serv['port']\n print(\"[+] Found: %s:%s:%s : %s\" % (kw['mac'], proto, port, name))\n\ndef getargs():\n ap = argparse.ArgumentParser(description=\"BT RFCOMM scanner\")\n ap.add_argument(\"-m\", '--mac', type=str, default=None, help=\"MAC address\")\n args, l = ap.parse_known_args()\n if args.mac == None:\n ap.print_help()\n sys.exit()\n else:\n return args\n\n\ndef main():\n kw = {}\n args = getargs()\n kw['mac'] = args.mac\n enumerate_rfcomm(**kw)\n\n\nif __name__==\"__main__\":\n main()\n\n","repo_name":"SYANiDE-/ViolentPython","sub_path":"wireless_rfcomm_detect2.py","file_name":"wireless_rfcomm_detect2.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"32814150433","text":"import requests\nfrom urllib.parse import urlparse\n# 페이지별 출력 : 함수로 묶기\n# API결과 반환하는 함수\n# get_api_result()\n\ndef get_api_result(keyword,display,start):\n url = \"https://openapi.naver.com/v1/search/blog?query=\" + keyword + \"&display=\" + str(display) + \"&start=\" + str(start)\n result = requests.get(urlparse(url).geturl(),\n headers={\"X-Naver-Client-Id\": \"j6BENMdhS0vjlJPel8et\",\n \"X-Naver-Client-Secret\": \"L5yAo_bfb3\"})\n json_obj = result.json()\n return json_obj\n\n\n# start값에 따라 페이지별로 쉽게 출력하기위해 출력부분을 함수로 묶기\n# call_and_print()\n\ndef call_and_print(json_obj,start):\n items = json_obj['items']\n list=[]\n for item in items:\n x = str(start) + \": \" + item['title'].replace('', \"\").replace('', \"\") + \" \" + item['link']\n print(x)\n list.append(x)\n start += 1\n return list\n\n# search_input()\n# 검색어, 출력수, 시작 숫자 입력 받아서 다른 함수 호출해서 결과 출력\ndef search_input():\n keyword = input('검색어: ')\n display = int(input('1회 출력수: '))\n start = int(input('시작숫자: '))\n json_obj = get_api_result(keyword, display, start)\n y = call_and_print(json_obj,start)\n with open('result.txt','w',encoding='utf-8') as outfile:\n for i in y:\n outfile.write(i+\"\\n\")\n\n# ===================================================================================\n\nsearch_input()\n\n","repo_name":"valborgs/pythonStudy","sub_path":"0808/API/06_naver_api_function_연습문제.py","file_name":"06_naver_api_function_연습문제.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"8521526916","text":"import struct\nfrom pathlib import Path\nfrom io import BytesIO\nfrom ot_types import *\nfrom table_COLR import *\nfrom table_fmtx import *\nfrom table_head import *\nfrom table_hhea import *\nfrom table_maxp import *\nfrom ot_file import *\n\nclass OTFont:\n \"\"\"Represents a font resource: one font within a TTC, or the font of an entire file if not a TTC.\"\"\"\n\n def __init__(self):\n self.offsetTable = None\n self.tables:dict = {}\n\n\n @staticmethod\n def createNewFont(offsetTable):\n \"\"\"Returns a new OTFont instance with the specified OffsetTable.\n \n The OffsetTable must have a supported sfntVersion tag: 0x0100, \"OTTO\" or \"true\".\n\n No other OffsetTable values are validated, and the OffsetTable does not need\n to be populated with TableRecords: these can be added or updated later.\n \"\"\"\n if not isSupportedSfntVersion(offsetTable.sfntVersion):\n raise OTCodecError(\"The offsetTable argument has an unsupported sfntVersion tag.\")\n font = OTFont()\n font.offsetTable = offsetTable\n return font\n # End of createNewFont\n\n\n @staticmethod\n def tryReadFromFile(otFile, offsetInFile: int = 0, ttcIndex: int = None):\n \"\"\"Returns an OffsetTable constructed from data in fileBytes. \n \n Exceptions may be raised if fileBytes is not long enough.\"\"\"\n\n font = OTFont()\n #font.otFile = otFile # Only present when read from a file (Not needed?)\n font.fileBytes = otFile.fileBytes\n if offsetInFile > len(font.fileBytes):\n raise OTCodecError(\"The file offset for the font is greater than the length of the file\")\n font.offsetInFile = offsetInFile\n if ttcIndex is not None and ttcIndex >= otFile.numFonts:\n raise OTCodecError(\"The ttcIndex argument is greater than the last font index (numFonts - 1)\")\n font.ttcIndex = ttcIndex\n font.isWithinTtc = False if ttcIndex is None else True\n font.offsetTable = OffsetTable.tryReadFromFile(font.fileBytes, offsetInFile)\n font.defaultLabel = otFile.path.name if ttcIndex is None \\\n else otFile.path.name + \":\" + str(ttcIndex)\n\n # Simple tables (e.g., hhea) get parsed from the file right away.\n simple_trs = [v for k, v in font.offsetTable.tableRecords.items() \\\n if k in font._earlyReadTables and font.isSupportedTableType(k)]\n for tr in simple_trs:\n font._tryReadTable(tr)\n\n return font\n # End of tryReadFromFile\n\n\n def sfntVersionTag(self):\n return self.offsetTable.sfntVersion\n\n\n def containsTable(self, tag:Tag):\n return (tag in self.offsetTable.tableRecords)\n\n\n def tryGetTableOffset(self, tag:Tag):\n \"\"\"If the specified table is present in the font, gets the offset from the start of the font. \n \n If the specified table is not present, returns None.\n \"\"\"\n tableRecord = self.offsetTable.tryGetTableRecord(tag)\n if tableRecord is None:\n return None\n else:\n return tableRecord.offset\n\n\n @staticmethod\n def isSupportedSfntVersion(tag:Tag):\n if tag not in (b'\\x00\\x01\\x00\\x00', \"OTTO\", \"true\"):\n return False\n else:\n return True\n\n\n @staticmethod\n def isKnownTableType(tag:Tag):\n if tag in (\n # OT tables:\n \"avar\", \"BASE\", \"CBDT\", \"CBLC\", \"CFF \", \"CFF2\", \"cmap\", \"COLR\", \n \"CPAL\", \"cvar\", \"cvt \", \"DSIG\", \"EBDT\", \"EBLC\", \"EBSC\", \"fpgm\", \n \"fvar\", \"gasp\", \"GDEF\", \"glyf\", \"GPOS\", \"GSUB\", \"gvar\", \"hdmx\", \n \"head\", \"hhea\", \"hmtx\", \"HVAR\", \"JSTF\", \"kern\", \"loca\", \"LTSH\", \n \"MATH\", \"maxp\", \"MERG\", \"meta\", \"MVAR\", \"name\", \"OS/2\", \"PCLT\", \n \"post\", \"prep\", \"sbix\", \"STAT\", \"SVG \", \"VDMX\", \"vhea\", \"vmtx\", \n \"VORG\", \"VVAR\",\n\n # Apple-specific tables:\n \"acnt\", \"ankr\", \"bdat\", \"bhed\", \"bloc\", \"bsln\", \"fdsc\", \"feat\", \n \"fmtx\", \"fond\", \"gcid\", \"hsty\", \"just\", \"lcar\", \"ltag\", \"mort\", \n \"morx\", \"opbd\", \"prop\", \"trak\", \"xref\", \"Zapf\", \n\n # SIL Graphite tables:\n \"Feat\", \"Glat\", \"Gloc\", \"Sill\", \"Silf\", \n\n # VOLT, VTT source tables:\n \"TSIV\", \"TSI0\", \"TSI1\", \"TSI2\", \"TSI3\", \"TSI5\"\n ):\n return True\n else:\n return False\n\n\n @staticmethod\n def isSupportedTableType(tag:Tag):\n if tag in (\"COLR\", \"fmtx\", \"head\", \"hhea\", \"maxp\"):\n return True\n else:\n return False\n\n # short, simple tables that get read from a file as soon as the \n # font's OffsetTable is parsed:\n _earlyReadTables = (\"COLR\", \"fmtx\", \"head\", \"hhea\", \"maxp\", \"OS/2\")\n\n _tryReadFromFileSwitch = {\n \"COLR\": Table_COLR.tryReadFromFile,\n \"fmtx\": Table_fmtx.tryReadFromFile,\n \"head\": Table_head.tryReadFromFile,\n \"hhea\": Table_hhea.tryReadFromFile,\n \"maxp\": Table_maxp.tryReadFromFile\n }\n\n def _tryReadTable(self, tableRecord):\n \"\"\"Returns a table of type determined by tableRecord.tableTag, if supported.\"\"\"\n if not self.isSupportedTableType(tableRecord.tableTag):\n return None\n f = self._tryReadFromFileSwitch[tableRecord.tableTag]\n self.tables[tableRecord.tableTag] = f(self, tableRecord)\n\n\n def addTable(self, table):\n # TO DO: implement\n pass\n\n def removeTable(self, tableTag:Tag):\n # TO DO: implement\n pass\n\n# End of class OTFont\n\n\n\nclass TableRecord:\n\n _tableRecordFormat = \">4sLLL\"\n \"\"\" Structure:\n (big-endian) >\n tableTag: Tag L\n checkSum: uint32 L\n offset: uint32 L\n length: uint32 L\n \"\"\"\n size = struct.calcsize(_tableRecordFormat)\n\n\n def __init__(self):\n \"\"\"Initialize an empty TableRecord to allow for creating new instances from\n scratch. To read from a file, TryReadFromBuffer is used.\"\"\"\n self.tableTag = None\n self.checkSum, self.offset, self.length = 0, 0, 0\n\n\n @staticmethod\n def createNewTableRecord(tableTag:Tag, checkSum = 0, offset = 0, length = 0):\n \"\"\"Returns a new TableRecord using specified values.\n \n A tag is required. The checkSum, offset and length values are optional:\n these are only meaningful when a complete table has been created, and can\n be set later.\n \"\"\"\n if tableTag is None:\n raise OTCodecError(\"A Tag for tableTag is required to create a new TableRecord.\")\n tr = TableRecord()\n tr.tableTag, tr.checkSum, tr.offset, tr.length = tableTag, checkSum, offset, length\n return tr\n\n\n @staticmethod\n def tryReadFromBuffer(buffer:bytearray):\n \"\"\"Returns a TableRecord constructed from values in the buffer. Returns None \n if the buffer is the wrong length.\"\"\"\n\n if len(buffer) != TableRecord.size:\n return None\n tr = TableRecord()\n vals = struct.unpack(TableRecord._tableRecordFormat, buffer)\n tr.tableTag = Tag(vals[0])\n tr.checkSum, tr.offset, tr.length = vals[1:4]\n return tr\n # End of tryReadFromBuffer\n\n# End of class TableRecord\n\n\n\nclass OffsetTable:\n\n # fields prior to the TableRecords array\n _offsetTableHeaderFormat = \">4sHHHH\"\n \"\"\" Structure:\n (big-endian) >\n sfntVersion: Tag 4s\n numTables: uint16 H\n searchRange: uint16 H\n entrySelector: uint16 H\n rangeShift: uint16 H\n \"\"\"\n _offsetTableHeaderSize = struct.calcsize(_offsetTableHeaderFormat)\n\n\n def __init__(self):\n self.sfntVersion: Tag = None\n self.numTables, self.searchRange, self.entrySelector, self.rangeShift = 0, 0, 0, 0\n self.tableRecords: dict = {}\n\n\n @staticmethod\n def createNewOffsetTable(sfntVersion:Tag, searchRange = 0, entrySelector = 0, rangeShift = 0):\n \"\"\"Returns a new OffsetTable using the specified values.\n\n A supported sfntVersion tag is required: 0x0100, \"OTTO\" or \"true\". The \n searchRange, entrySelector and rangeShift arguments are optional:\n these are only meaningful when a complete font has been assembled, and\n can be set later.\n\n TableRecords can be added later using AddTableRecord.\"\"\"\n\n if sfntVersion is None:\n raise OTCodecError(\"A Tag for sfntVersion is required to create a new OffsetTable.\")\n if not OTFont.isSupportedSfntVersion(sfntVersion):\n raise OTCodecError(\"The sfntVersion argument is not a supported sfntVersion tag.\")\n ot = OffsetTable()\n ot.sfntVersion, ot.searchRange, ot.entrySelector, ot.rangeShift \\\n = sfntVersion, searchRange, entrySelector, rangeShift\n return ot\n # End of createNewOffsetTable\n\n\n @staticmethod\n def tryReadFromFile(fileBytes:bytearray, offsetInFile: int):\n \"\"\"Returns an OffsetTable constructed from data in fileBytes. \n \n Exceptions may be raised if fileBytes is not long enough.\"\"\"\n\n ot = OffsetTable()\n ot.offsetInFile = offsetInFile\n\n # get the header\n headerBytes = fileBytes[offsetInFile : offsetInFile + OffsetTable._offsetTableHeaderSize]\n if len(headerBytes) < ot._offsetTableHeaderSize:\n raise OTCodecError(\"Unable to read OffsetTable from file at {:#08x}\".format(offsetInFile))\n tmp = struct.unpack(ot._offsetTableHeaderFormat, headerBytes)\n ot.sfntVersion = Tag(tmp[0])\n ot.numTables, ot.searchRange, ot.entrySelector, ot.rangeShift = tmp[1:5]\n\n # get the table records -- we'll wrap BytesIO around fileBytes to provide sequential reading\n filebio = BytesIO(fileBytes)\n filebio.seek(offsetInFile + ot._offsetTableHeaderSize)\n for i in range(ot.numTables):\n recData = filebio.read(TableRecord.size)\n if len(recData) < TableRecord.size:\n raise OTCodecError(\"Unable to read TableRecord from file\")\n record = TableRecord.tryReadFromBuffer(recData)\n ot.tableRecords[record.tableTag] = record\n\n return ot\n # End of TryReadFromFile\n\n\n def tryGetTableRecord(self, tag:Tag):\n \"\"\"Returns the table record matching the specified tag, if present. If not present, returns None.\"\"\"\n if not tag in self.tableRecords:\n return None\n else:\n return self.tableRecords[tag]\n\n\n def addTableRecord(self, tableRecord:TableRecord):\n \"\"\"Adds a TableRecord to the OffsetTable.\n\n The tableRecord.tableTag member must not be None. If a TableRecord is\n already present with the same tableTag, the existing TableRecord is\n replaced.\n \n This can only be used with an OffsetTable instance created anew\n in memory. If called on an instance that was read from a file,\n an exception is raised.\n \"\"\"\n if tableRecord is None:\n raise OTCodecError(\"The tableRecord argument must not be None.\")\n if hasattr(self, \"offsetInFile\"):\n raise OTCodecError(\"Cannot add a TableRecord to an OffsetTable that was read from a file.\")\n if tableRecord.tableTag is None:\n raise OTCodecError(\"Cannot add a TableRecord that doesn't have a tableTag.\")\n self.tableRecords[tableRecord.tableTag] = tableRecord\n # End of addTableRecord\n\n\n def removeTableRecord(self, tableTag:Tag):\n \"\"\"Removes the TableRecord with the specified table Tag, if present.\n\n If no TableRecord with that tag is present, no change is made.\n\n This can only be used with an OffsetTable instance created anew\n in memory. If called on an instance that was read from a file,\n an exception is raised.\n \"\"\"\n if hasattr(self, \"offsetInFile\"):\n raise OTCodecError(\"Cannot remove a TableRecord from an OffsetTable that was read from a file.\")\n if tableTag is None:\n # No-op\n return\n try:\n del self.tableRecords[tableTag]\n except:\n pass # Don't care that it wasn't present\n # End of removeTableRecord\n\n# End of class OffsetTable\n\n\n","repo_name":"PeterConstable/PyOTCodec","sub_path":"PyOTCodec/ot_font.py","file_name":"ot_font.py","file_ext":"py","file_size_in_byte":12378,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"9"} +{"seq_id":"40812558685","text":"#/usr/local/bin python3\n\"\"\"Iterative de novo assembly with read subtraction.\n\ncontig_miner_v2\nHanna Retallack 2/17/2018\nModified from contig_miner.py (Greg Fedewag)\n\nRequirements:\n Python 3.6.4\n magicblast 1.3.0\n PRICE Assembler v1.2\n samtools 0.1.19\n shuf\n\nUsage:\nwith paired read fasta files:\npython3 ~/scripts/contig_miner_v2.py -i $fasta_read1 $fasta_read2 -r $ref -t 16 &> log.cm.out\n\nfasta_1=\"/data/hretallack/mosquito/fuc.CMS-032_R1_10k.fasta\"\nfasta_2=\"/data/hretallack/mosquito/fuc.CMS-032_R2_10k.fasta\"\nref=\"/data/hretallack/databases/mos_viruses/mosquito_fullviruses_v2.fasta\" #or can be an empty fasta file with single header\n\nOR with interleaved fasta file:\npython3 ~/scripts/contig_miner_v2.py -i $fasta_interleaved -r $ref -t 16 &> log.cm.out\n\"\"\"\n\nimport argparse\nimport subprocess\nimport shlex\nimport textwrap\nimport sys\nfrom glob import glob\nimport os\nfrom os import system\n\ndef check_len():\n class InputAction(argparse.Action):\n def __call__(self, parser, namespace, values, option_string=None):\n if not 1 <= len(values) <= 2:\n raise argparse.ArgumentError('Incorrect number of inputs')\n setattr(namespace, self.dest, values)\n return InputAction\n\n\ndef fasta_subsample(fasta, n):\n '''Randomly subsample n reads from a FASTA'''\n #for fastq, use \"awk 'NR % 2 == 0 && NR % 4 != 0 {print }' \"\n subsample_command = '''awk 'NR % 2 == 0 {print }' ''' + f'{fasta} | shuf -n {n} | ' + r'''awk '{print \">\"; print}' > temp_seed_reads.fasta'''\n fasta = 'temp_seed_reads.fasta'\n subprocess.run(subsample_command, shell=True)\n return fasta\n\n\ndef price_contigs(fasta_1, fasta_2, num_threads, loop_count):\n '''Use PRICE to build contigs '''\n print('Building contigs')\n amp_len = 400\n identity_percent = 99\n seed_reads = fasta_subsample(fasta_1, 1000)\n input_steps = 1\n second_input_cycle = 1\n constant_mult = 2\n cycle_count = 10\n sub_assembler_length = 72\n min_overlap = 30\n threshold_scaler = 20\n min_percent_id = 80\n min_len_filter = 500\n output_loop_skip = 10\n untargeted_cycles = 4\n output_name = f'loop_{loop_count}.contigs.fasta'\n return_file = f'loop_{loop_count}.contigs.cycle{cycle_count}.fasta'\n\n #Joe's price magic:\n\n # For PriceTI, my strategy is to reduce the read pool as much as possible, \n # by removing everything you can ahead of time. Then pick 5000 seeds randomly, \n # then run 4 cycles untargeted, followed by 10 cycles targeted. \n # Use -lenf to limit to contigs > 500. Then, collect contigs. Repeat ~5 times. \n # Then, re-seed with all harvested contigs, running in targeted mode to build them out. \n # Use -lenf to limit to 1kb.\n\n #PriceTI-1.2 -icf hku-23kb-seed.fasta 1 1 1 -fpp hku-hits.1.fasta hku-hits.2.fasta 300 99 \n # -mol 30 -a 12 -target 80 8 2 2 -nc 10 -lenf 350 4 -lenf 500 8 -o hku-round2.fasta\n\n price_command = (f'PriceTI -fpp {fasta_1} {fasta_2} {amp_len} {identity_percent} '\n # should the below line be there? Am I using starting reads?\n f'-icf {seed_reads} {input_steps} {second_input_cycle} {constant_mult} ' #+ \\\n f'-nc {cycle_count} '\n f'-dbmax {sub_assembler_length} '\n f'-mol {min_overlap} '\n f'-tol {threshold_scaler} '\n f'-mpi {min_percent_id} '\n f'-lenf 350 4 -lenf 500 8 -lenf {min_len_filter} {cycle_count-1} '\n f'-target 80 {untargeted_cycles} 2 2 ' #runs 6 cycles untargeted\n f'-nco {output_loop_skip} '\n f'-a {num_threads} '\n f'-o {output_name}')\n subprocess.run(shlex.split(price_command),\n stdout=open(f'loop_{loop_count}.price.log', 'w'))\n subprocess.run(f'rm {seed_reads}', shell=True)\n print(price_command)\n return return_file\n\n\ndef get_max_contig_len(contig_file):\n '''Grab max contig length from PRICE output FASTA file\n Returns 0 if fasta file is empty'''\n fasta_file = open(contig_file, 'r')\n l = 0\n for _ in fasta_file:\n if _.startswith('>contig_1'):\n l = _.split('>contig_1 (')[1].split('nt)')[0]\n return int(l)\n\n\ndef align_reads(fasta_1, fasta_2, reference, num_threads, loop_count):\n '''Align reads to the reference or new contigs.'''\n print('Aligning reads to reference')\n sam_file = f'loop_{loop_count}.alignment.sam'\n magicblast_command = (f'magicblast -query {fasta_1} -query_mate {fasta_2} '\n f'-subject {reference} '\n f'-paired '\n #f'-num_threads {num_threads} '\n f'-out {sam_file} ')\n subprocess.run(shlex.split(magicblast_command))\n return sam_file\n\n\ndef process_samfile(samfile, loop_count):\n '''Extract unmapped readpairs from samfile, write to fasta'''\n print('Extracting unmapped readpairs')\n out_R1 = f'loop_{loop_count}.unmapped.1.fasta'\n out_R2 = f'loop_{loop_count}.unmapped.2.fasta'\n\n #From here: https://gist.github.com/darencard/72ddd9e6c08aaff5ff64ca512a04a6dd\n # # R1 unmapped, R2 mapped [flags 69,133...]\n # samtools view -f 4 -F 264\n # # R1 mapped, R2 unmapped [flags 89,137,153...]\n # samtools view -f 8 -F 260\n # # R1 & R2 unmapped [flags 77,141...]\n # samtools view -f 12 -F 256\n\n # grab all possible unmapped readpairs\n os.system(f'samtools view -f 4 -F 264 -S {samfile} > tmp.sam 2> /dev/null')\n os.system(f'samtools view -f 8 -F 260 -S {samfile} >> tmp.sam 2> /dev/null')\n os.system(f'samtools view -f 12 -F 256 -S {samfile} >> tmp.sam 2> /dev/null')\n # write to fasta file\n os.system(r'''samtools view -S tmp.sam -f 0x40 2> /dev/null | awk '{OFS=\"\\t\"; print \">\"$1\"\\n\"$10}' >''' + out_R1 )\n os.system(r'''samtools view -S tmp.sam -f 0x80 2> /dev/null | awk '{OFS=\"\\t\"; print \">\"$1\"\\n\"$10}' >''' + out_R2 )\n os.system(f'rm tmp.sam {samfile}')\n\n with open(out_R1, 'r') as reads:\n num_unmapped = int(sum(1 for line in reads)/2)\n\n return out_R1, out_R2, num_unmapped\n\n\ndef reconcile_contigs(fasta_file_list, read1, read2):\n '''PRICE to assemble contigs in fasta files together with original read files'''\n print('Now combining and extending contigs from all loops: ' + ' '.join(fasta_file_list))\n os.system(f'cat loop_*.contigs.cycle10.fasta > combined.contigs.fasta')\n final_price_command = (f'PriceTI -icf combined.contigs.fasta 1 1 5 '\n f'-fpp {read1} {read2} 400 99 '\n f'-target 80 4 1 1 ' #run 4 cycles untargeted, then alternate\n f'-a 12 -lenf 500 9 '\n f'-nc 10 -nco 10 -o final.contigs.fasta')\n subprocess.run(shlex.split(final_price_command),\n stdout=open('final.price.log', 'w'))\n os.system('rm combined.contigs.fasta')\n os.system('mv final.contigs.cycle10.fasta final.contigs.fasta')\n\n\ndef main():\n in_fasta = args.input\n reference = args.ref\n num_threads = args.threads\n min_read_number = 100\n read_list_len = min_read_number + 1\n loop_count = 0\n unproductive_loops = 0 #counter\n max_unproductive_loops = 5 #3\n max_loops_ever = 20 #10 #temporary halt\n contig_file_list = []\n\n # Handle fasta input\n print(f'Input fasta file: {in_fasta}')\n print(f'Input reference file: {reference}')\n\n if len(in_fasta) == 2 : #assumes read pairs\n print('Assuming paired read files')\n fasta_1 = in_fasta[0]\n fasta_2 = in_fasta[1]\n elif len(in_fasta) == 1 : #assumes interleaved fasta file\n print('Assuming interleaved fasta file')\n os.system(f'cat {in_fasta[0]} | grep -A1 \"/1\" --no-group-separator > temp_R1.fasta')\n os.system(f'cat {in_fasta[0]} | grep -A1 \"/2\" --no-group-separator > temp_R2.fasta')\n fasta_1 = 'temp_R1.fasta'\n fasta_2 = 'temp_R2.fasta'\n\n in_fasta_1 = fasta_1 #save the original in_fasta files for final price step\n in_fasta_2 = fasta_2\n\n # Keep cycling until too many unproductive loops (longest contig is too short), or you don't have enough reads left\n while (read_list_len > min_read_number) and (unproductive_loops < max_unproductive_loops) and (loop_count < max_loops_ever):\n if loop_count>0:\n\n # ---section1--- De novo assembly of remaining unmapped reads\n try:\n built_contigs = price_contigs(fasta_1, fasta_2, num_threads, loop_count)\n except Exception as identifier:\n raise Exception('PRICE failed.')\n\n if os.path.exists(built_contigs) and os.path.getsize(built_contigs) > 0:\n print(f'- PRICE built at least one long contig in loop {loop_count}')\n try:\n max_contig_len = get_max_contig_len(built_contigs)\n print(f'Max contig length = {max_contig_len}')\n except:\n pass\n reference = built_contigs\n contig_file_list.append(built_contigs)\n else:\n print('- PRICE output contig file does not exist or is empty')\n unproductive_loops +=1 #add to counter of unproductive \n print(f'- Number of unproductive loops = {unproductive_loops}')\n continue \n\n #---section2--- do this in first loop and after successful PRICE assemblies\n try:\n sam_mapping = align_reads(fasta_1, fasta_2, reference, num_threads, loop_count)\n unmapped_fasta_1, unmapped_fasta_2, n_unmapped_reads = process_samfile(sam_mapping, loop_count) \n except Exception as identifier:\n raise Exception('Alignment and subtraction failed.')\n\n else:\n fasta_1 = unmapped_fasta_1\n fasta_2 = unmapped_fasta_2\n\n print(f'Loop {loop_count} complete. Unmapped reads remaining = {n_unmapped_reads}.')\n print(f'--- End of loop {loop_count} ---')\n loop_count += 1\n\n print('--- Loops complete ---')\n\n reconcile_contigs(contig_file_list, in_fasta_1, in_fasta_2) #check for redundancy in contigs and output compiled list\n os.system(f'rm loop_*.unmapped.*.fasta') #clean up unmapped reads\n os.system(f'rm temp_R*.fasta')\n os.system(f'rm final.price.log')\n #eventually, clean up other temp files too (cycle10, and price logs)\n\n return\n\n\nif __name__ == '__main__':\n #Greg's argparser thing ... doesn't seem to output help comments?\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter,\n add_help=True)\n parser_input = parser.add_mutually_exclusive_group(required=True)\n # parser_input.add_argument('-i', '--input', type=str, nargs='+', action=check_len(),\n # help='Inputs to start on.')\n parser_input.add_argument('-i', '--input', type=str, nargs='*',\n help='Inputs to start on.')\n parser_input.add_argument('-f', '--folders', type=str,\n help='The folder containing all the sample folders')\n parser.add_argument('-g', '--program', type=str, required=False,\n choices=[], nargs='*',\n help=textwrap.dedent('''\\\n Some help goes here.\n '''))\n parser.add_argument('-r', '--ref', type=str, default=os.path.expanduser('~/.linuxbrew/opt/gmap-gsnap/share'),\n help='The location, and name of the reference for alignment if you are using --input. Just the location if you are using --folders.')\n parser.add_argument('-t', '--threads', type=int, required=False, help='Number of threads to use.', default=1)\n args = parser.parse_args()\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"czbiohub/california-mosquito-study","sub_path":"scripts/contig_miner_v3.py","file_name":"contig_miner_v3.py","file_ext":"py","file_size_in_byte":11835,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"9"} +{"seq_id":"40347153636","text":"#-------def global 'board' ----------\nboard = [\"-\", \"-\", \"-\",\n \"-\", \"-\", \"-\",\n \"-\", \"-\", \"-\"]\n\n# Lets us know if the game is over yet\ngame_still_going = True\n\n# Tells us who the winner is\nwinner = None\n\n# Counts rounds of play\nround = 0\n\n# Tells us who the current player is (X goes first)\ncurrent_player = \"X\"\n\n\ndef game():\n global game_still_going\n while game_still_going:\n playerTurn(current_player)\n gameboard()\n checkWinner()\n flipPlayer()\n\ndef gameboard():\n print(\"\\n\")\n print(board[0] + \" | \" + board[1] + \" | \" + board[2] + \" 1 | 2 | 3\")\n print(board[3] + \" | \" + board[4] + \" | \" + board[5] + \" 4 | 5 | 6\")\n print(board[6] + \" | \" + board[7] + \" | \" + board[8] + \" 7 | 8 | 9\")\n print(\"\\n\")\n\n\ndef playerTurn(player):\n number = input('Podaj miejsce ktore chcesz zaznaczyć: ')\n try:\n number = int(number)\n print(number)\n except:\n print('Podal liczbe nie wyraz!')\n return\n\n if number <= 9 and number > 0:\n if board[number - 1] == '-':\n board[number - 1]=player\n else:\n print('pole jest zajete!')\n else:\n print('Nie ma takiego pola')\n\ndef flipPlayer():\n global current_player\n if current_player == 'X':\n current_player = 'O'\n else:\n current_player = 'X'\n\ndef checkWinner():\n rowWinner()\n colsWinner()\n diagonalWinner()\n\n\ndef rowWinner():\n global game_still_going\n global winner\n row_1 = board[0] == board[1] == board[2] != \"-\"\n row_2 = board[3] == board[4] == board[5] != \"-\"\n row_3 = board[6] == board[7] == board[8] != \"-\"\n\n if row_1 or row_2 or row_3:\n game_still_going = False\n # Return the winner\n if row_1:\n return board[0]\n elif row_2:\n return board[3]\n elif row_3:\n return board[6]\n \ndef colsWinner():\n global game_still_going\n global winner\n column_1 = board[0] == board[3] == board[6] != \"-\"\n column_2 = board[1] == board[4] == board[7] != \"-\"\n column_3 = board[2] == board[5] == board[8] != \"-\"\n\n if column_1 or column_2 or column_3:\n game_still_going = False\n # Return the winner\n if column_1:\n return board[0]\n elif column_2:\n return board[1]\n elif column_3:\n return board[2]\ndef diagonalWinner():\n global game_still_going\n global winner\n diagonal1 = board[0] == board[4] == board[8] != '-'\n diagona2 = board[6] == board[4] == board[0] != '-'\n\n\n\n\ngameboard()\n\ngame()\n\n\n\n","repo_name":"ZoranPandovski/al-go-rithms","sub_path":"games/Python/kaczmarekdaniel-tictactoe.py","file_name":"kaczmarekdaniel-tictactoe.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":1302,"dataset":"github-code","pt":"9"} +{"seq_id":"9688177310","text":"import pygame\n\nfrom animation import AnimateSprite\n\n\nclass Entity(AnimateSprite):\n \"\"\"Assemble le joueur\"\"\"\n\n def __init__(self, name, x, y):\n \"\"\"Crée le joueur\"\"\"\n super().__init__(name)\n self.image = self.get_image(0, 0)\n self.image.set_colorkey([0, 0, 0])\n self.rect = self.image.get_rect()\n self.position = [x, y]\n self.feet = pygame.Rect(0, 0, self.rect.width * 0.5, 12)\n self.old_position = self.position.copy()\n # Réglage de la vitesse de déplacement\n self.speed = 3\n\n def save_location(self): self.old_position = self.position.copy()\n\n def change_animation(self, name):\n self.image = self.images[name]\n self.image.set_colorkey((0, 0, 0))\n\n def move_right(self):\n \"\"\"Déplace le joueur a droite\"\"\"\n self.change_animation(\"right2\")\n self.position[0] += self.speed\n\n def move_left(self):\n \"\"\"Déplace le joueur a gauche\"\"\"\n self.change_animation(\"left2\")\n self.position[0] -= self.speed\n\n def move_up(self):\n \"\"\"Déplace le joueur vers le haut\"\"\"\n self.change_animation(\"up2\")\n self.position[1] -= self.speed\n\n def move_down(self):\n \"\"\"Déplace le joueur vers la droite\"\"\"\n self.change_animation(\"down2\")\n self.position[1] += self.speed\n\n def update(self):\n \"\"\"actualise la position du personnage\"\"\"\n self.rect.topleft = self.position\n self.feet.midbottom = self.rect.midbottom\n\n def move_back(self):\n self.position = self.old_position\n self.rect.topleft = self.position\n self.feet.midbottom = self.rect.midbottom\n\n\nclass Joueur(Entity):\n\n def __init__(self):\n super().__init__(\"Eon\", 0, 0)\n\n\nclass PNJ(Entity):\n\n def __init__(self, name, nb_points):\n super().__init__(name, 0, 0)\n self.nb_points = nb_points\n self.points = []\n self.current_point = 0\n self.name = name\n self.speed = 0.8\n\n def move(self):\n current_point = self.current_point\n target_point = self.current_point + 1\n if target_point >= self.nb_points:\n target_point = 0\n current_rect = self.points[current_point]\n target_rect = self.points[target_point]\n\n if current_rect.y < target_rect.y and abs(current_rect.x - target_rect.x) < 3:\n self.move_down()\n elif current_rect.y > target_rect.y and abs(current_rect.x - target_rect.x) < 3:\n self.move_up()\n elif current_rect.x > target_rect.x and abs(current_rect.y - target_rect.y) < 3:\n self.move_left()\n elif current_rect.x < target_rect.x and abs(current_rect.y - target_rect.y) < 3:\n self.move_right()\n\n if self.rect.colliderect(target_rect):\n self.current_point = target_point\n\n def teleport_spawn(self):\n\n location = self.points[self.current_point]\n self.position[0] = location.x\n self.position[1] = location.y\n self.save_location()\n\n def load_points(self, tmx_data):\n\n for num in range(1, self.nb_points + 1):\n point = tmx_data.get_object_by_name(f'{self.name}_path{num}')\n rect = pygame.Rect(point.x, point.y, point.width, point.height)\n self.points.append(rect)\n","repo_name":"Tintinnc/TP_NSI","sub_path":"src/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"9018170854","text":"class RomanToInt:\n '''\n https://leetcode.com/problems/roman-to-integer/\n '''\n def romanToInt(self, s: str) -> int:\n ints = {\"M\": 1000, \"CM\": 900, \"D\": 500, \"CD\": 400, \"C\": 100, \"XC\": 90, \"L\": 50, \"XL\": 40, \"X\": 10,\n \"IX\": 9, \"V\": 5, \"IV\": 4, \"I\": 1}\n res, idx = 0, 0\n\n # //MMCXL\n for i in ints.keys():\n while (idx < len(s) and s[idx] == i) or (idx+1 < len(s) and s[idx:idx+2] == i):\n res += ints[i]\n if (idx < len(s) and s[idx] == i):\n idx += 1\n else:\n idx += 2\n\n return res\n\nobj = RomanToInt()\ns = \"MCMXCIV\"\nprint(obj.romanToInt(s))","repo_name":"pratikpr/leetcode-py","sub_path":"medium/RomanToInt.py","file_name":"RomanToInt.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"15249550557","text":"from sklearn.cluster import DBSCAN\nfrom utils import to_bool_arr\nimport numpy as np\nfrom PIL import Image\nfrom .cluster import Cluster\n\n\nclass ClusterAnalysis:\n ''' To get results c.image_clusters(areas=True, only_synapses=True)\n '''\n DBSCAN_EPS = 6\n DB_SCAN_MIN_SAMPLES = 4\n MIN_CLUSTER_MEMBERS = 25\n def __init__(self, ves, mem, syn):\n self.ves = to_bool_arr(ves)\n self.mem = to_bool_arr(mem)\n self.syn = to_bool_arr(syn)\n\n self.psyn = self.syn #& self.mem\n self.nsyn = ~self.syn & self.mem\n self.psynpoints = np.asarray(zip(*self.psyn.nonzero()))\n\n self.db = DBSCAN(eps=self.DBSCAN_EPS, min_samples=self.DB_SCAN_MIN_SAMPLES)\n self.db.fit(self.psynpoints)\n\n self.clusters = self._get_clusters()\n\n def _get_clusters(self):\n clus = {}\n labels = self.db.labels_\n for label in set(labels):\n if label==-1:\n continue\n members = self.psynpoints[labels==label]\n if len(members) 40:\n # ang =40\n # if ang < -40:\n # ang = -40\n\n #drift error compensation section\n angle = math.atan2((aimy-GV.currenty1),(aimx-GV.currentx1))\n angle = GV.CurPathAng - angle\n if angle>0:\n GV.Left = True\n else:\n GV.Left = False\n GV.Set_SteerAng = ang\n \ndef LatLongTM(lat,long):\n p = pyproj.Proj(proj='utm', zone=29, ellps='WGS84')\n x,y = p(lat,long)\n return x,y\n","repo_name":"herc11093/GPSLawwn1","sub_path":"LawnMowerGPS1_Python/Auto_Steer_Trig.py","file_name":"Auto_Steer_Trig.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"8427212825","text":"import pygame as pg, pygamebg, random\n(sirina, visina) = (300, 300)\nprozor = pygamebg.open_window(sirina, visina, \"Папир, камен, маказе\")\n\nPAPIR, KAMEN, MAKAZE = 0, 1, 2\nslike = [\n pg.image.load(\"paper.png\"), \n pg.image.load(\"rock.png\"), \n pg.image.load(\"scissors.png\")\n]\nx_slike = sirina // 4 - slike[0].get_width() // 2\ny_slike = visina // 2 - slike[0].get_height() // 2\n\n# znacenje elemenata u listama covek i racunar\nIME, IZBOR, POENI, X_SL, Y_SL, X_TEKST, Y_TEKST = 0, 1, 2, 3, 4, 5, 6\ncovek = [\"Човек\", -1, 0, x_slike, y_slike, 0, 0]\nracunar = [\"Рачунар\", -1, 0, x_slike + sirina//2, y_slike, sirina//2, 0]\nfont = pg.font.SysFont(\"Arial\", 20)\n\ndef crtaj_igraca(igrac):\n if igrac[IZBOR] >= 0:\n prozor.blit(slike[igrac[IZBOR]], (igrac[X_SL], igrac[Y_SL]))\n tekst = igrac[IME] + \": \" + str(igrac[POENI])\n slika_teksta = font.render(tekst, True, pg.Color(\"black\"))\n prozor.blit(slika_teksta, (igrac[X_TEKST], igrac[Y_TEKST]))\n \ndef nov_frejm():\n prozor.fill(pg.Color(\"white\"))\n crtaj_igraca(covek)\n crtaj_igraca(racunar)\n \ndef obradi_dogadjaj(dogadjaj):\n global covek, racunar\n if dogadjaj.type == pg.KEYDOWN:\n pkm = {pg.K_p : PAPIR, pg.K_k : KAMEN, pg.K_m : MAKAZE}\n if dogadjaj.key in pkm.keys():\n covek[IZBOR] = pkm[dogadjaj.key]\n racunar[IZBOR] = random.randint(0, 2)\n if racunar[IZBOR] == (covek[IZBOR] + 1) % 3:\n covek[POENI] += 1\n elif covek[IZBOR] == (racunar[IZBOR] + 1) % 3:\n racunar[POENI] += 1\n \npygamebg.frame_loop(15, nov_frejm, obradi_dogadjaj)\n","repo_name":"Petlja/TxtProgInPythonSrLat","sub_path":"src/PyGame/3_Interaction/3e_Keyboard_events/paper_rock_scissors.py","file_name":"paper_rock_scissors.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"sh","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"3317689639","text":"import sys\nimport os\nsys.path.append(os.path.join(os.getcwd()))\nfrom business.registerBusiness import RegisterBusiness\nfrom selenium import webdriver\nfrom util.excel_util import ExcelUtil\nimport unittest\nimport time\nimport HTMLTestRunner\nimport ddt\n\nex = ExcelUtil()\ndata = ex.get_data()\n@ddt.ddt\nclass FirstDdtCase(unittest.TestCase):\n\t# 用例的前置条件\n\tdef setUp(self):\n\t\toptions = webdriver.ChromeOptions()\n\t\toptions.add_argument('disable-infobars') # 取消 chrome正受到自动测试软件的控制的信息栏\n\t\tself.driver = webdriver.Chrome(chrome_options=options)\n\t\tself.driver.get('http://www.5itest.cn/register?goto=/')\n\t\tself.driver.fullscreen_window() # 全屏打开\n\t\tself.login = RegisterBusiness(self.driver)\n\t\n\t# 后置条件\n\tdef tearDown(self):\n\t\ttime.sleep(2)\n\t\t# 运行报错时保存截图\n\t\tfor case_name, error in self._outcome.errors:\n\t\t\tif error:\n\t\t\t\tcase_name = self._testMethodName\n\t\t\t\tself.driver.save_screenshot(os.path.join(os.getcwd()+\"/report/\"+case_name+\".png\"))\n\t\tprint('---------执行后置方法:关闭浏览器----------')\n\t\tself.driver.close()\n \n\t# 邮箱、用户名、密码、验证码/错误信息定位/错误信息提示\n\t\n\t\n\t'''\t@ddt.data(\n\t\t['1', 'zhou', '111111', '/Users/edz/Documents/lab/imooc/img/CropRegister.png', 'email_error','请输入有效的电子邮件地址'],\n\t\t['1292871494@qq.com', 'zhou', '111111', '/Users/edz/Documents/lab/imooc/img/CropRegister.png', 'email_error','请输入有效的电子邮件地址']\n\n\n\t\t)\n\t\n\t@ddt.unpack\n\tdef test_register_case(self, data):\n\t\temail, name, password, file_name, errElement, errText = data\n\t\tprint(\"file_name:\", file_name)\n\t\temail_error = self.login.register_function(email, name, password, file_name, errElement, errText)\n\t\tself.assertFalse(email_error, \"测试失败\")\n\t\t# if email_error == True:\n\t\t# \tprint('邮箱验证case失败!')'''\n\t\n\t@ddt.data(*data)\n\tdef test_register_case(self, data):\n\t\temail, name, password, file_name, errElement, errText = data\n\t\tprint(\"file_name:\", file_name)\n\t\temail_error = self.login.register_function(email, name, password, file_name, errElement, errText)\n\t\tself.assertFalse(email_error, \"测试失败\")\n\t\t# if email_error == True:\n\t\t# \tprint('邮箱验证case失败!')\n\n\nif __name__ == \"__main__\":\n\tfile_path = os.path.join(os.getcwd()+\"/report/\"+\"first_case.html\")\n\t# 打开报告文件并写入内容\n\tf = open(file_path,'wb')\n\t# 加载测试类中所有标准的测试case\n\tsuite = unittest.TestLoader().loadTestsFromTestCase(FirstDdtCase)\n\trunner = HTMLTestRunner.HTMLTestRunner(stream=f,title=\"This is first report\", description=\"第一个测试报告\", verbosity=2)\n\trunner.run(suite)\n\n","repo_name":"ztly/practice","sub_path":"case/firstDdtCase.py","file_name":"firstDdtCase.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"17502702543","text":"#%%\n\nimport urllib.request, urllib.parse, urllib.error\nimport xml.etree.ElementTree as ET\n\n\n# url = input('Enter - ')\nurl = \"http://py4e-data.dr-chuck.net/comments_1584374.xml\"\nbdata = urllib.request.urlopen(url).read()\nprint(f\"Retrieving {url}\")\n# print(type(bdata))\nsdata=bdata.decode() # convert byte data to string data\n# print(type(sdata))\ntree = ET.fromstring(bdata)\n\ncounts = tree.findall('.//count')\nprint('Count:', len(counts))\ntotal=0\nfor i in counts:\n total+=int(i.text)\n # print(i.text)\nprint(\"Sum:\",total)\n\n# %%\n","repo_name":"Kaito-Kiddo/pythonprogs","sub_path":"xlmparse.py","file_name":"xlmparse.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"761831952","text":"#!/usr/bin/python3.4\n# -*-coding:Utf-8 -*\n'''module to manage preferences of Blender-Render-Manager'''\nfrom save import *\nfrom Preferences.Blender import *\nfrom Preferences.Output import *\n\nclass Preferences:\n\t'''class to manage Blender-Render-Manager preferences'''\n\t\n\t\n\tdef __init__(self, xml= None):\n\t\t'''load preferences object from XML or initialize default one'''\n\t\tif xml is None:\n\t\t\tself.defaultInit()\n\t\telse:\n\t\t\tself.fromXml(xml)\n\t\n\t\n\t\n\t\n\t\n\tdef defaultInit(self):\n\t\t'''initialize default preferences object'''\n\t\t\n\t\tself.blender = Blender() # blender application path\n\t\tself.output = Output() # working directory path\n\t\tself.port = 55814 # socket port to communicate with blender thread\n\t\tself.archiveLimit = 1000 # max number of task to keep in archive list\n\t\tself.logLimit = 100 # max number of session log file to keep\n\t\tself.percentOW = 'always'\n\t\n\t\n\t\n\t\n\t\n\tdef fromXml(self, xml):\n\t\t'''Load preferences from xml'''\n\t\t\n\t\tself.blender = Blender( xml.find('blender') )\n\t\tself.output = Output( xml.find('output') )\n\t\tself.port = int(xml.get('port'))\n\t\tself.archiveLimit = int(xml.get('archive'))\n\t\tself.logLimit = int(xml.get('log'))\n\t\tself.percentOW = xml.get('percentOW')\n\t\n\t\n\t\n\t\n\t\n\tdef toXml(self):\n\t\t'''export to xml'''\n\t\txml= '\\n'\n\t\t\n\t\t#export limit and socket port settings\n\t\txml+= '\\n'\n\t\t\n\t\t# export blender and output path\n\t\txml+= self.blender.toXml() + self.output.toXml() +'\\n'\n\t\t\n\t\treturn xml\n\t\n\t\n\t\n\t\n\t\n\tdef menu(self, log, tasks):\n\t\t'''access function to set preferences'''\n\t\tlog.menuIn('Preferences')\n\t\tchange = False\n\t\t\n\t\twhile True:\n\t\t\tlog.print()\n\t\t\tself.print()\n\t\t\t\n\t\t\tchoice = input('''\\n \\033[4mPreferences Menu :\\033[0m\n1- Edit Blender Path\n2- Edit Work Path\n3- Edit Log Limit\n4- Edit Archive Size Limit\n5- Edit Socket Port\n6- Edit Percentage Overwriting Preferences\n0- Save and quit\n\nmenu choice?''').strip().lower()\n\t\t\t\n\t\t\t#treat available actions\n\t\t\tif choice in ['0', 'q', 'quit', 'cancel']:# quit preferences menu\n\t\t\t\tlog.menuOut()\n\t\t\t\treturn\n\t\t\t\t\n\t\t\telif choice == '1':# edit blender application path\n\t\t\t\tchange = self.blender.menu(log)\n\t\t\t\t\n\t\t\telif choice == '2':# edit working directory path\n\t\t\t\tchange = self.output.menu(log)\n\t\t\t\t\n\t\t\telif choice in ['3', '4']:# edit log or archive limit\n\t\t\t\tchange = self.editLimit(log, choice == '3' )\n\t\t\t\t\n\t\t\telif choice == '5':# edit socket port for blender thread communication\n\t\t\t\tchange = self.editPort(log)\n\t\t\t\t\n\t\t\telif choice == '6':# Edit Percentage Overwriting Preferences\n\t\t\t\tchange = self.editPOW(log)\n\t\t\t\t\n\t\t\telse:# bad choice\n\t\t\t\tlog.error('Unknow request!', False)\n\t\t\t\n\t\t\tif change:# save when preferences have been changed\n\t\t\t\tchange = False\n\t\t\t\tsavePreferences(self)\n\t\t\t\tlog.write('New preferences saved')\n\t\n\t\n\t\n\t\n\t\n\tdef print(self):\n\t\t'''display preference settings'''\n\t\tprint('Blender Path : '+self.blender.path,\\\n\t\t\t\t'Work Path : '+self.output.path,\\\n\t\t\t\t'Socket Port : '+str(self.port),\\\n\t\t\t\t'Session Log Limit : '+str(self.logLimit),\\\n\t\t\t\t'Archive Limit : '+str(self.archiveLimit),\\\n\t\t\t\t'Force 100% resolution : '+self.percentOW,\\\n\t\t\t\tsep='\\n'\n\t\t\t)\n\t\n\t\n\t\n\t\n\t\n\tdef editPort(self, log):\n\t\t'''Set blender communication socket port'''\n\t\tlog.menuIn('Edit Net Port')\n\t\t\n\t\twhile True:\n\t\t\tlog.print()\n\t\t\tchoice = input('\\n\\n Edit Net Port :\\n\\nCurrent port :'\\\n\t\t\t\t\t\t+str(self.port)\\\n\t\t\t\t\t\t+'\\n\\nType a number from 1024 to 65535 or h or q'\\\n\t\t\t\t\t\t\t).strip().lower()# get a new port choice\n\t\t\t\n\t\t\tif choice in ['q', 'quit', 'cancel']:# quit port setting\n\t\t\t\tlog.menuOut()\n\t\t\t\treturn False\n\t\t\t\n\t\t\tif choice in ['h', 'help']:# display help information\n\t\t\t\tlog.menuIn('Help')\n\t\t\t\tlog.print()\n\t\t\t\tinput('\\n\\n Help :\\nWhen Blender Render Manager is running blender to render a picture, it communicate with Blender via a web socket to stay informed of the status. This setting is the port that the script use for the socket. be sure to use a port who is not used by another process.\\n\\nenter to continue\\n')\n\t\t\t\tlog.menuOut()\n\t\t\t\tcontinue\n\t\t\t\n\t\t\ttry:\n\t\t\t\tchoice = int(choice)# try to get an integer\n\t\t\texcept ValueError:\n\t\t\t\tlog.error('integer value expected!',False)\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tif choice < 1024 or choice > 65535:# ensure it's a valid port\n\t\t\t\tlog.error('the port must be between 1024 (exclude) and 65535 (exclude)!',False)\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tself.port = choice # set the new port\n\t\t\tlog.write('the socket port is set to '+str(self.port))\n\t\t\tlog.menuOut()\n\t\t\treturn True# confirm change\n\t\n\t\n\t\n\t\n\t\n\tdef editLimit(self, log, logLim):\n\t\t'''edit log or archive limit'''\n\t\t# get current limit and set good menu\n\t\tif logLim:\n\t\t\tlog.menuIn('Edit Log Limit')\n\t\t\tcurrent = self.logLimit\n\t\telse:\n\t\t\tlog.menuIn('Edit Archive Max Size')\n\t\t\tcurrent = self.archiveLimit\n\t\t\n\t\twhile True:\n\t\t\tlog.print()\n\t\t\tchoice = input('\\n\\nCurrent limit : '+str(current)+'\\n\\nNew limit (0 for unlimited, q to quit) : ').strip().lower()\n\t\t\t\n\t\t\tif choice in ['q', 'quit', 'cancel']:# quit without change anything\n\t\t\t\tlog.menuOut()\n\t\t\t\treturn False\n\t\t\t\n\t\t\ttry:\n\t\t\t\tchoice = int(choice)# try to get Int value\n\t\t\texcept ValueError:\n\t\t\t\tlog.error('Integer value expected!',False)\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tif choice >= 0:\n\t\t\t\tif logLim:# set Log Limit\n\t\t\t\t\tself.logLimit = choice\n\t\t\t\t\tlog.write('Log limit set to '+str(self.logLimit))\n\t\t\t\t\t\n\t\t\t\telse:# set Archive Limit\n\t\t\t\t\tself.archiveLimit = choice\n\t\t\t\t\tlog.write('Archive size set to '+str(self.archiveLimit))\n\t\t\t\t\t\n\t\t\t\tlog.menuOut()\n\t\t\t\treturn True# quit menu and confirm change\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tlog.error('Expect a positive Integer value!')\n\t\n\t\n\t\n\t\n\t\n\tdef editPOW(self, log):\n\t\t'''Edit file resolution percentage overwriting default preferences'''\n\t\tlog.menuIn('Percent Overwriting Preferences')\n\t\twhile True:\n\t\t\tlog.print()\n\t\t\tself.print()\n\t\t\t# get user preferences\n\t\t\tchoice = input('''\\n\\nDo you want to automatically set new task resolution to 100% : \n\t1- Always\n\t2- Never\n\t3- Demand anytime\n\t0- keep setting and leave\n\t\nYour choice : ''').strip().lower()\n\t\t\t\n\t\t\tif choice in ['0', 'q', 'quit', 'cancel']:# quit without change anything\n\t\t\t\tlog.menuOut()\n\t\t\t\treturn False\n\t\t\t\n\t\t\tif choice in[ '1', '2', '3']:\n\t\t\t\tif choice == '1':\n\t\t\t\t\tself.percentOW = 'always'\n\t\t\t\t\tlog.write('Preferences set to always set 100% resolution on new task.')\n\t\t\t\t\t\n\t\t\t\telif choice == '2':\n\t\t\t\t\tself.percentOW = 'never'\n\t\t\t\t\tlog.write('Preferences set to always use original file resolution of new task.')\n\t\t\t\t\t\n\t\t\t\telif choice == '3':\n\t\t\t\t\tself.percentOW = 'ondemand'\n\t\t\t\t\tlog.write('Preferences set to always ask user preferences when a task is added with a file containing scene with a rendering resolution percentage different from 100%.')\n\t\t\t\t\n\t\t\t\tlog.menuOut()\n\t\t\t\treturn True# quit menu and confirm change\n\t\t\t\t\n\t\t\telse:\n\t\t\t\tlog.error('Unvalid choice! Type 1, 2, 3 or 0!')\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n","repo_name":"CaptainDesAstres/Simple-Blender-Render-Manager","sub_path":"Preferences/Preferences.py","file_name":"Preferences.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"74294709413","text":"from mapdata.models import Region\nfrom django.core.management.base import BaseCommand\nimport requests\n\n\ndef literacy_data():\n data_url = \"https://data.gov.in/node/100084/datastore/export/json\"\n response = requests.get(data_url)\n format_data = []\n for d_arr in response.json()['data']:\n format_data.append({\n 'name': d_arr[0],\n })\n return format_data\n\nclass Command(BaseCommand):\n help = 'create states '\n\n def handle(self, *args, **kwargs):\n for obj in literacy_data():\n Region.objects.create(**obj)\n","repo_name":"SiddharthShringi/education","sub_path":"mapdata/management/commands/create_region.py","file_name":"create_region.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"25663197001","text":"with open(\"input10.txt\",\"r\") as input:\n numbers = input.readlines()\n\nfor i,num in enumerate(numbers):\n numbers[i] = int(num.rstrip(\"\\n\"))\n\nstartfrom = 0\ntop = max(numbers)+3\n\nnumbers.sort()\n\n\ndiff1 = 0\ndiff3 = 0\n\n\ndef compare(n1,n2):\n\n global diff1, diff3\n\n if n1 + 1 == n2:\n diff1 += 1\n elif n1 + 3 == n2:\n diff3 += 1\n elif n1 + 3 < n2:\n print(\"Gap between \"+str(n1)+\" and \"+str(n2))\n return False\n\n return True\n\n\ncompare(startfrom, numbers[0])\n\nfor i,num in enumerate(numbers):\n\n if i + 1 < len(numbers):\n\n if not compare(num, numbers[i+1]):\n break\n\n else:\n\n compare(num,top)\n\nprint(\"Diff 1: \"+str(diff1))\nprint(\"Diff 3: \"+str(diff3))\nprint(\"Product: \"+str(diff1*diff3))\n\nnumbers.append(0)\nnumbers.append(top)\n\nnumbers.sort(reverse = True)\nprint(numbers)\n\noptions = {}\ncounts = {}\n\ndef saveoption(i1,i2):\n if not numbers[i1] in options:\n options[numbers[i1]] = []\n options[numbers[i1]].append(numbers[i2])\n\nfor i in range(len(numbers)):\n# print(numbers[i])\n count = 0\n if i-1 >= 0 and numbers[i-1] - 3 <= numbers[i]:\n saveoption(i,i-1)\n print(str(numbers[i-1])+\" - 3 <= \"+str(numbers[i]))\n if i-2 >= 0 and numbers[i-2] - 3 <= numbers[i]:\n saveoption(i,i-2)\n print(str(numbers[i-2])+\" - 3 <= \"+str(numbers[i]))\n if i-3 >= 0 and numbers[i-3] - 3 <= numbers[i]:\n saveoption(i,i-3)\n print(str(numbers[i-3])+\" - 3 <= \"+str(numbers[i]))\n if i-4 >= 0 and numbers[i-4] - 3 <= numbers[i]:\n saveoption(i,i-4)\n print(str(numbers[i-4])+\" - 3 <= \"+str(numbers[i]))\n\nprint(options)\n\nfor num, arr in options.items():\n counts[num] = 0\n for opt in arr:\n if opt in counts:\n counts[num] += counts[opt]\n else:\n counts[num] += 1\n\n\nprint(counts)\n","repo_name":"ru-fu/aoc","sub_path":"aoc2020/day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"30578485964","text":"import requests\r\nimport json\r\n\r\n#common fn for get basic data ============================\r\ndef getBasic_apiData(url, params):\r\n res_data = api_call(url, params)\r\n \r\n try:\r\n data = res_data['data'][0] #get crew_sn on data param\r\n except KeyError: # if no search user id, return none\r\n return None\r\n\r\n return data\r\n#============================================================\r\n\r\ndef api_call(url, params):\r\n res = requests.post(url, data = params) #request Post\r\n res_data = json.loads(res.text) #transform json\r\n return res_data\r\n\r\n#=====logging...=====\r\ndef on_message_log(message, keyword):\r\n print('==========[ on_message log ]==========')\r\n print('request user - ', message.author)\r\n print('request keyword - ', keyword)\r\n print('==========[ on_message log ]==========')\r\n#=====logging...=====","repo_name":"overload-dev/3on3freestyle_bot","sub_path":"controller/commonController.py","file_name":"commonController.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"9"} +{"seq_id":"72656511012","text":"from typing import Callable, Tuple\n\nimport pandas as pd\n\n# p, w_side_down, w_side_up, c\nMSE_Function = Callable[[Tuple[float, float, float, float]], float]\n\n# p, w_side, c\nMSE_Function_Side = Callable[[Tuple[float, float, float]], float]\n\n\n# Generate error function\ndef generate_mse_error_fn(down_data: pd.DataFrame, up_data: pd.DataFrame) -> MSE_Function:\n # sum down_bucket terms\n\n down_terms = list(map(lambda x: training_row_to_mse_term(x[1].to_dict()), down_data.iterrows()))\n up_terms = list(map(lambda x: training_row_to_mse_term(x[1].to_dict()), up_data.iterrows()))\n\n def mse_function(x):\n p = x[0]\n w_side_down = x[1]\n w_side_up = x[2]\n c = x[3]\n\n return sum(\n map(lambda fn: fn(p, w_side_down, c), down_terms)\n ) / len(down_terms) + sum(\n map(lambda fn: fn(p, w_side_up, c), up_terms)\n ) / len(up_terms)\n\n return mse_function\n\n\ndef training_row_to_mse_term(row: dict) -> MSE_Function_Side:\n marginal = row[\"marginal\"]\n cumulative = row[\"cumulative\"]\n is_target = int(row[\"is_target_bucket\"])\n\n if marginal == -1:\n return lambda p, w_side, c: ((w_side * (p ** cumulative) + c) - is_target) ** 2\n\n return lambda p, w_side, c: ((w_side * (1 - p ** marginal) * (p ** cumulative) + c) - is_target) ** 2\n","repo_name":"nielsgroen/sn0l","sub_path":"python/mse.py","file_name":"mse.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"9"} +{"seq_id":"38588794872","text":"'''\nImporting nessecery libraries\n'''\nimport zmq\nimport sys\nfrom zmq import Socket\nimport cv2\nimport json\nimport random\n#############################################################3\n\ndef initConnections(ports=['5556','5557','5558'],ip=\"localhost\"):\n '''\n inistantiate the connection with the master tracket ports\n '''\n context = zmq.Context() \n socket = context.socket(zmq.REQ)\n random.shuffle(ports)\n for port in ports:\n socket.connect (\"tcp://\"+ip+\":%s\" % port)\n print(str(port)) \n print('Done initializing master client ports')\n return socket\n\n#################################################################\n\ndef establishUploadConnection(portNum:str,ip:str):\n context = zmq.Context()\n socket = context.socket(zmq.PUSH)\n socket.connect(\"tcp://\"+ip+\":%s\" % portNum)\n return socket\n\n################################################################\n\ndef readSendVideo(Videopath:str,socket:Socket):\n messagevid={}\n with open(Videopath,'rb') as vfile:\n file=vfile.read()\n messagevid['VIDEO']=file\n messagevid['VIDEO_NAME']=Videopath\n socket.send_pyobj(messagevid)\n return True\n\n###########################################################\ndef uploadFile(videoPath:str,socketClientMaster:Socket):\n '''\n steps :\n 1-request upload 2-recieve information of the data keeper\n 3-establish connection 4-send the video\n ''' \n myMessegeSend={'REQ_TYPE':'upload'} \n socketClientMaster.send_pyobj(myMessegeSend) \n myMessegeRec = socketClientMaster.recv_pyobj()\n if(myMessegeRec['STATUS']=='fail'):\n print('no ports are free at the current state please run again after a while')\n exit()\n portNumberUpload=myMessegeRec['PORT_NUMBER'] \n ip=myMessegeRec['IP'] \n print(myMessegeRec)\n socketClientDataKeeper=establishUploadConnection(portNumberUpload,ip) \n readSendVideo(videoPath,socketClientDataKeeper)\n################################################################# \n\ndef saveVideo(video,videoName:str): \n try:\n with open(videoName,'wb') as myfile:\n myfile.write(video)\n return True\n except:\n return False\n \n\n \n####################################################################\ndef downloadFile(fileName:str,masterSocket:Socket):\n myMessegeSend={'REQ_TYPE':'download'} \n myMessegeSend['FILE_NAME']=fileName\n masterSocket.send_pyobj(myMessegeSend) \n print(\"i have send a message\")\n listMachines=masterSocket.recv_pyobj()\n print(listMachines)\n \n context = zmq.Context() \n downloadSocketDk = context.socket(zmq.REQ) \n for IP,port in listMachines['DK_INFO']:\n print(IP,port)\n downloadSocketDk.connect (\"tcp://\"+str(IP)+\":%s\"%port) \n break \n Message={\"VIDEO_NAME\":fileName}\n downloadSocketDk.send_pyobj(Message)\n video=downloadSocketDk.recv_pyobj()\n print(video)\n saveVideo(video,fileName)\n \n####################################################################### \n\nif __name__ == \"__main__\": \n #uploadSocket=None \n with open('master_tracker_config.json') as f:\n masterInfo = json.load(f)\n #print(masterInfo)\n masterSocket=initConnections(masterInfo['PORT_NUMBERS'],masterInfo['IPv4']) \n typeOfOperation='u'\n fileName='hhhhcat.mp4'\n if(len(sys.argv)>1):\n typeOfOperation=str(sys.argv[1])\n if(len(sys.argv)>2):\n fileName=str(sys.argv[2])\n while True:\n if typeOfOperation=='u':\n uploadFile(fileName,masterSocket)\n elif typeOfOperation=='d':\n downloadFile(fileName,masterSocket) \n typeOfOperation=input('Please enter another operation to perform u:Upload ,d:Donwload ,x:exit')\n if(typeOfOperation=='x'):\n exit()\n elif(typeOfOperation=='u'):\n fileName=print('plesase enter the file name to upload') \n else:\n print('wrong operation please enter another operation char') \n \n \n \n \n \n \n\n\n\n\n\n\n \n","repo_name":"mohamed-mokhtar/Distributed-File-System","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"9"} +{"seq_id":"69996224903","text":"class Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n p_len = len(p)\n s_len = len(s)\n \n if (p_len > s_len): return []\n \n p_freq = [0] * 26\n s_freq = [0] * 26\n sol = []\n \n for i in range(p_len):\n p_freq[ord(p[i]) - ord('a')] += 1\n s_freq[ord(s[i]) - ord('a')] += 1\n \n if p_freq == s_freq: sol.append(0)\n \n for i in range(1, s_len - p_len + 1):\n s_freq[ord(s[i - 1]) - ord('a')] -= 1;\n s_freq[ord(s[i + p_len - 1]) - ord('a')] += 1;\n if p_freq == s_freq: sol.append(i)\n \n return sol;","repo_name":"arjunvuppala123/leetcode_questionsolutions","sub_path":"FAANG_Must_Do_Problems/FindAllAnagramsinaString.py","file_name":"FindAllAnagramsinaString.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"8"} +{"seq_id":"10003192079","text":"# lees rij getallen 9999 om te eindigen\r\n# bereken het gemiddelde\r\n#bereken het kleinste\r\n#bereken het percentage negatieve getallen\r\nteller = 0\r\nteller_negatief = 0\r\nsom = 0\r\ngetal = int(input(\"Geef een getal in: \"))\r\nkleinste = getal\r\nwhile getal != 9999:\r\n som += getal\r\n teller += 1\r\n if getal < kleinste:\r\n kleinste = getal\r\n if getal < 0:\r\n teller_negatief += 1\r\n getal = int(input(\"Geef een getal in: \"))\r\ngemiddelde = som / teller\r\nprint(\"Het gemiddelde is\", gemiddelde)\r\nprint(\"Het kleinste getal is:\", kleinste)\r\npercentage = teller_negatief / getal * 100\r\nprint(\"Het percentage negatieve getallen is\", percentage)","repo_name":"JochenHansoul/pxl","sub_path":"2018/programming essentials/chapters/4_iteraties/4 oefening voorbeeld les.py","file_name":"4 oefening voorbeeld les.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"35528152944","text":"#!/usr/bin/env python3.4\n\n# Gentoo check function\ndef _is_gentoo():\n\t'''\n\tCheck if the project has been initiated from a Gentoo system\n\t'''\n\t\n\tfrom subprocess import call\n\n\t# Grep Gentoo from the releases file.\n\t_dist_check = call(\"grep ^NAME= /etc/*release | awk -F '=' '{print $2}' | grep -q Gentoo\", stdout=None, stderr=None, shell=True)\n\t\n\tdel call\n\n\t# Return 0 in case grep was successful, or 1 otherwise.\n\tif _dist_check == 0:\n\t\tdel _dist_check\n\t\treturn 0\n\telse:\n\t\treturn 1\n\n# Check for superuser privileges\ndef _is_su():\n\t'''\n\tCheck if the project has been initiated with super user permissions\n\t'''\n\t\n\tfrom subprocess import call\n\n\t# The check is very simple. It checks if the $UID is equal to 0. In case it is not, it returns a value of 1\n\t_super_u = call(\"if [[ $(echo $UID) == 0 ]]; then exit 0; else exit\t1; fi\", stdout=None, stderr=None, shell=True)\n\n\tdel call\n\n\t# Test the return value and return either 0 or 1\n\tif _super_u == 0:\n\t\tdel _super_u\n\t\treturn 0\n\telse:\n\t\treturn 1\n\n# Simple input call\ndef portalin(_input):\n\t'''\n\tCalls for a user input.\n\t\tThere are two calls for input\n\t\t\tI \t) The first one requests an input and returns it to the function that requested it\n\t\t\tII \t) The second asks for a user input and does nothing. This one is for visual purpose like (press any key)\n\t'''\n\n\tfrom gpyfunctions.tools.gseout import report_colors\n\t\n\t# Ask for user input\n\tif _input is \"_input\":\n\t\tportin = input(report_colors.YELLOW + \"Input :: <= \" + report_colors.RESET)\n\t\treturn portin\n\n\t# Asks for an input to continue the process.\n\t# The main difference of this one from the above, apart from the stdout text is that it does not return anything.\n\telif _input is \"_key\":\n\t\tportin = input(report_colors.BLUE + \"Press any key to continue\" + report_colors.RESET)\n\n\tdel report_colors\n\n\n# Simple shell call\ndef _shell():\n\t'''\n\tShell function that:\n\t\tExports the current $SHELL of the system\n\t\tInitiates a call subprocess on the given $SHELL\n\t\tResumes the process when the call shell subprocess finishes\n\t'''\n\n\tfrom gpyfunctions.tools.gseout import e_report\n\tfrom os import environ\n\n\t# Export $SHELL\n\tactive_shell = environ['SHELL']\n\t\n\te_report(\"Calling \" + active_shell + \", please exit to resume script\")\n\t\n\t# Import time and wait 3 seconds before initiating a shell\n\timport time\n\ttime.sleep(1.5)\n\t\n\tfrom subprocess import call\n\t\n\t# Open shell terminal with as $SHELL\n\tcall([active_shell], stdout=None, stderr=None, shell=True)\n\te_report(\"Proceeding\")\n\t\n\t# Clear and exit\n\tdel e_report, time, call, active_shell, environ\n\n# Simple clear screen function\ndef _clear():\n\t'''\n\tVery simply screen clear function.\n\t\tWhen called, it executes system(\"clear\") for os module\n\t\tThis function exists only to aid the text menu functions.\n\t'''\n\n\tfrom os import system\n\tsystem(\"clear\")\n\n# Parameter error function\ndef _parameter_error():\n\t'''\n\tParameter miss match error\n\tThis error will be printed before key point actions.\n\tExample: All actions that request write access in the system.\n\t'''\n\n\tfrom gpyfunctions.tools.gseout import die\n\tfrom os import system\n\tdie(\"\"\"\n\t\t[ FATAL ]\n\t\t\n\t\tIf this message is printed while using the Maim Menu\n\t\tThat means essential files are altered or something bad is happening.\n\n\t\tPlease run a health-check from the ~Main Menu~ and a Version check first.\n\t\tIf you see this again after the health/version check, please submit a bug report\n\t\tand stop using the program, or data loss may occur.\n\n\t\tExiting...\n\t\t\"\"\")\n\n\n# Export important project's sub-directories\ndef _gse_path(_gpyfunc_):\n\t'''\n\tThe purpose of this function is to read the given _gpygunc_ variable and export\n\t\tthe all important project's sub-directories\n\t\tThe subdirectories are:\n\t\t\tCCGSE\n\t\t\tCCONFDIR\n\t\t\tCDISTDIR\n\t\t\tCLOCALLG\n\t\t\tCLOGLG\n\t\t\tCSYSROOT\n\t\t\tCLOCALLIB\n\t\t\tCFUNCTIONS\n\t'''\n\n\tfrom os import getcwd, path\n\tfrom sys import exit\n\n\t# Export current working category\n\tCWORKDIR = getcwd()\n\n\tif _gpyfunc_ == 'sys':\n\t\tCWORKDIR = '/usr/lib64/gse'\n\t\tCGSE = CWORKDIR + '/gse.py'\n\t\tCCONFDIR = CWORKDIR + '/config.d'\n\t\tCDISTDIR = '/var/tmp/gse/dist.d'\n\t\tCLOCALLG = CWORKDIR + '/local'\n\t\tCLOGLG = '/var/log/gse'\n\t\tCSYSROOT = '/home/gse'\n\t\tCLOCALLIB = '/var/lib/gse'\n\t\tCFUNCTIONS = CWORKDIR + 'scripts/pyfunctions'\n\n\telif _gpyfunc_ == '.git':\n\t\t# If the project has been git cloned or simply copied to a location\n\t\tCWORKDIR = path.dirname(CWORKDIR)\n\t\tCFUNCTIONS = CWORKDIR+'/scripts/pyfunctions'\n\t\tCGSE = CWORKDIR + '/gse.py'\n\t\tCCONFDIR = CWORKDIR+'/config.d'\n\t\tCDISTDIR = CWORKDIR+'/dist.d'\n\t\tCLOCALLG = CWORKDIR+'/local'\n\t\tCLOGLG = CWORKDIR+'/var/log'\n\t\tCSYSROOT = CWORKDIR+'/sysroot'\n\t\tCLOCALLIB = CWORKDIR+'/var/lib'\n\n\telse:\n\t\tprint(\"\\033[0;31m Could not find project's directory \\033[0;0m\")\n\t\texit(1)\n\n\tdel getcwd, path, exit\n\n\treturn CWORKDIR, CGSE, CFUNCTIONS, CCONFDIR, CDISTDIR, CLOCALLG, CLOGLG, CSYSROOT, CLOCALLIB\n\n\n\n\n","repo_name":"ulfox/GSE","sub_path":"scripts/gpyfunctions/preliminary.py","file_name":"preliminary.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"8"} +{"seq_id":"7261622088","text":"from Node import Node\nfrom LinkedList import LinkedList\n# Access head_node => list.get_head()\n# Check if list is empty => list.is_empty()\n# Node class {int data ; Node next_element;}\n\n# Searches a value in the given list.\n\n\ndef search(lst, value):\n # Write your code here\n if lst.is_empty(): return False\n temp = lst.head_node\n \n while temp.next_element is not None:\n if temp.data == value:\n return True\n temp = temp.next_element\n return temp.data == value\n","repo_name":"Shizuo85/DataStructures-Algorithms","sub_path":"Python/linkedList/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"5305817327","text":"\"\"\"\nYou are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\nModify the matrix directly without creating a new matrix\nEx: input = [[1,2,3],\n [4,5,6],\n [7,8,9]]\nOutput: [[7,4,1],\n [8,5,2],\n [9,6,3]]\n\n\"\"\"\nfrom typing import List\nfrom utils import print_matrix\n\nMOVEMENT_CORDS = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n\n\nclass Solution:\n def switch_next_item(self, matrix, src_number, cur_y, cur_x, movement_index, move_step_start, move_step_end):\n count = 1\n while count < (move_step_end - move_step_start) :\n new_y = cur_y + MOVEMENT_CORDS[movement_index][0]\n new_x = cur_x + MOVEMENT_CORDS[movement_index][1]\n if not (move_step_start <= new_y < move_step_end) or not (move_step_start <= new_x < move_step_end):\n movement_index = (movement_index + 1) % len(MOVEMENT_CORDS)\n continue\n else:\n count += 1\n cur_y, cur_x = new_y, new_x\n\n temp_var = matrix[cur_y][cur_x]\n matrix[cur_y][cur_x] = src_number\n return temp_var, movement_index, cur_y, cur_x\n\n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Solution :\n Runtime - 50%\n Memory - 59%\n\n \"\"\"\n\n len_matrix = len(matrix)\n direction = 0\n no_of_rounds = len_matrix\n for next_y in range(len_matrix-no_of_rounds, len_matrix//2):\n for next_x in range(len_matrix-no_of_rounds, no_of_rounds-1):\n next_item = matrix[next_y][next_x]\n for _ in range(4):\n next_item, direction, next_y, next_x = self.switch_next_item(matrix, next_item, next_y, next_x, direction, len_matrix-no_of_rounds, no_of_rounds)\n no_of_rounds -= 1\n\n\nsquare_matrix = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16]\n]\nSolution().rotate(square_matrix)\nprint_matrix(square_matrix)\n","repo_name":"ishamibrahim/BasicProgramming","sub_path":"LeetCode/42_lc_48_rotate_matrix_image.py","file_name":"42_lc_48_rotate_matrix_image.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"9972972707","text":"import datetime\nimport re\nfrom typing import List\n\nfrom PyQt5.QtCore import QDateTime\nfrom PyQt5.QtNetwork import QNetworkCookie\nfrom PyQt5.QtWebEngineWidgets import QWebEngineProfile, QWebEngineView\nfrom PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QLabel, QMessageBox\nimport json\n\n\n\ndef disable_account(uid:str):\n pass\n\nclass CustomQWebEngine(QWebEngineView):\n\n def __init__(self, *args, **kwargs):\n super(CustomQWebEngine, self).__init__(*args, **kwargs)\n QWebEngineProfile.defaultProfile().setPersistentCookiesPolicy(QWebEngineProfile.NoPersistentCookies)\n QWebEngineProfile.defaultProfile().cookieStore().cookieAdded.connect(self.onCookieAdd)\n QWebEngineProfile.defaultProfile().setHttpUserAgent(\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.122 Safari/537.36\"\n )\n self._cookies = []\n\n def onCookieAdd(self, cookie):\n # Just receive cookie from facebook\n c = QNetworkCookie(cookie)\n # print(\"cookie added\")\n # print(self.get_cookies())\n # print(\"=\"*80)\n if re.search(r'facebook.com', c.domain()):\n name = bytearray(c.name()).decode()\n if name not in [\"ATN\", \"IDE\", '_js_datr', 'checkpoint']:\n self._cookies.append(c)\n if name == 'fr':\n fr_cookie_name_timestamp = None\n try:\n fr_cookie_name_timestamp = c.expirationDate().toPyDateTime().timestamp()\n except:\n fr_cookie_name_timestamp = 1668137438\n x = datetime.timedelta(days=82, seconds=86341, microseconds=72000)\n wd_expiry = fr_cookie_name_timestamp - x.total_seconds()\n # Create wd cookie\n wd_cookie = QNetworkCookie()\n wd_cookie.setName(bytes('wd'.encode()))\n wd_cookie.setPath('/')\n wd_cookie.setValue(bytes('1076x736'.encode()))\n wd_cookie.setDomain('.facebook.com')\n wd_cookie.setExpirationDate(datetime.datetime.fromtimestamp(wd_expiry))\n wd_cookie.setHttpOnly(False)\n wd_cookie.setSecure(True)\n wd_cookie.__setattr__(\"sameSite\", \"Lax\")\n self._cookies.append(wd_cookie)\n\n def setCookies(self, cookies):\n try:\n if cookies and isinstance(cookies, list):\n for cookie in cookies:\n qnet_cookie = QNetworkCookie()\n qnet_cookie.setName(bytes(cookie.get('name').encode()))\n if cookie.get('domain'):\n qnet_cookie.setDomain(cookie.get('domain'))\n else:\n qnet_cookie.setDomain('.facebook.com')\n \n qnet_cookie.setValue(bytes(cookie.get('value').encode()))\n if cookie.get('path'):\n qnet_cookie.setPath(cookie.get('path'))\n else:\n qnet_cookie.setPath(\"/\")\n \n if cookie.get('expiry'):\n expiration_date = QDateTime.fromTime_t(cookie.get('expiry'))\n qnet_cookie.setExpirationDate(expiration_date)\n else:\n expiration_date = QDateTime.fromTime_t(1668137438)\n \n \n if cookie.get('secure'):\n qnet_cookie.setSecure(cookie.get('secure'))\n else:\n qnet_cookie.setSecure(True)\n \n \n if cookie.get('httpOnly'):\n qnet_cookie.setHttpOnly(cookie.get('httpOnly'))\n else:\n qnet_cookie.setHttpOnly(False)\n \n \n QWebEngineProfile.defaultProfile().cookieStore().setCookie(QNetworkCookie(qnet_cookie))\n except Exception as ex:\n dlg = QMessageBox(self)\n dlg.setWindowTitle(\"Thông báo\")\n dlg.setText(f\"Cookie không hợp lệ!\\n {ex}\")\n dlg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)\n dlg.setIcon(QMessageBox.Information)\n button = dlg.exec()\n\n def clean_cookies(self):\n print(\"*\"*80)\n clean_cookies, added = [], []\n try:\n # Create list of cookie keys\n names = set()\n for c in self._cookies:\n name = bytearray(c.name()).decode()\n names.add(name)\n print(names)\n # Find max expiry time for each cookie key\n max_per_name = dict()\n for c_key in names:\n max_per_name[f'{c_key}'] = 973999838\n for c_key in names:\n for c in self._cookies:\n exp = None\n try:\n exp = c.expirationDate().toPyDateTime().timestamp()\n except:\n exp = 1668137438\n \n name = bytearray(c.name()).decode()\n if c_key == name:\n if max_per_name[f'{c_key}'] < exp:\n max_per_name[f'{c_key}'] = exp\n else:\n max_per_name[f'{c_key}'] = exp\n print(max_per_name)\n # Keep cookie keys with max one\n for c in self._cookies:\n exp = None\n exp = None\n try:\n exp = c.expirationDate().toPyDateTime().timestamp()\n except:\n exp = 1668137438\n \n # exp = c.expirationDate().toPyDateTime().timestamp()\n name = bytearray(c.name()).decode()\n if max_per_name[f'{name}'] == exp and name not in added:\n clean_cookies.append(c)\n added.append(name)\n except KeyError:\n pass\n return clean_cookies\n\n def get_cookies(self, except_cookies_name: List[str] = None):\n \"\"\"Get cookies\n Args:\n except_cookies_name (list(str)): list of string cookie name not want to get\n Returns:\n List of cookies\n \"\"\"\n cookies_list = []\n clean_cookies = self.clean_cookies()\n for c in clean_cookies:\n name = bytearray(c.name()).decode()\n exp = None\n try:\n exp = c.expirationDate().toPyDateTime().timestamp()\n except:\n exp = 1668137438\n \n data = {\n \"name\": name,\n \"domain\": c.domain(),\n \"value\": bytearray(c.value()).decode(),\n \"path\": c.path(),\n \"expiry\": exp,\n \"secure\": c.isSecure(),\n \"httpOnly\": c.isHttpOnly(),\n \"sameSite\": \"None\" if name != 'wd' else 'Lax'\n }\n if except_cookies_name is None:\n cookies_list.append(data)\n elif name not in except_cookies_name:\n cookies_list.append(data)\n return cookies_list\n\n\nclass CustomDialog(QDialog):\n def __init__(self, title, message, reject=None, accept=None):\n super().__init__()\n self.title = title\n self.message = message\n self.setWindowTitle(self.title)\n\n QBtn = QDialogButtonBox.Cancel\n if accept:\n QBtn = QDialogButtonBox.Ok\n if all([reject, accept]):\n QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel\n\n self.buttonBox = QDialogButtonBox(QBtn)\n self.buttonBox.rejected.connect(self.reject)\n self.buttonBox.accepted.connect(self.accept)\n\n self.layout = QVBoxLayout()\n message = QLabel(self.message)\n self.layout.addWidget(message)\n self.layout.addWidget(self.buttonBox)\n self.setLayout(self.layout)\n\n\nclass ImportExportLoginInfo:\n def __init__(self, filename, data: dict = None):\n self.filename = filename\n self.data = data\n self.export = self._export\n self.import_ = self._import\n\n def _export(self):\n with open(self.filename, 'w') as f:\n import json, base64\n b = bytes(json.dumps(self.data).encode())\n f.write(base64.b85encode(b).decode())\n f.close()\n\n def _import(self):\n try:\n with open(self.filename, 'r') as f:\n import json, base64\n ct = \"\"\n for line in f.readlines():\n ct += line\n ct = ct.strip()\n b = base64.b85decode(bytes(ct.encode()))\n f.close()\n return json.loads(b.decode())\n except Exception:\n return None\n def _import_json(self):\n try:\n data = self._import()\n if data:\n data = data.replace(\"'\",'\"')\n return json.loads(data)\n except Exception as ex:\n return None\n\n","repo_name":"hspace-biz/fblogin","sub_path":"src/main/python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9256,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"8"} +{"seq_id":"25962330022","text":"import fixtures\nfrom gi import require_version\ntry:\n require_version('UbuntuAppLaunch', '3')\nexcept ValueError:\n require_version('UbuntuAppLaunch', '2')\nfrom gi.repository import GLib, UbuntuAppLaunch\n\nimport json\nimport logging\nimport os\nimport psutil\nimport subprocess\nimport signal\nfrom systemd import journal\nfrom autopilot.utilities import safe_text_content\n\nfrom autopilot._timeout import Timeout\nfrom autopilot._fixtures import FixtureWithDirectAddDetail\nfrom autopilot.application._environment import (\n GtkApplicationEnvironment,\n QtApplicationEnvironment,\n)\nfrom autopilot.introspection import (\n get_proxy_object_for_existing_process,\n)\n\n_logger = logging.getLogger(__name__)\n\n\nclass ApplicationLauncher(FixtureWithDirectAddDetail):\n\n \"\"\"A class that knows how to launch an application with a certain type of\n introspection enabled.\n\n :keyword case_addDetail: addDetail method to use.\n :keyword proxy_base: custom proxy base class to use, defaults to None\n :keyword dbus_bus: dbus bus to use, if set to something other than the\n default ('session') the environment will be patched\n\n \"\"\"\n\n def __init__(self, case_addDetail=None, emulator_base=None,\n dbus_bus='session'):\n super().__init__(case_addDetail)\n self.proxy_base = emulator_base\n self.dbus_bus = dbus_bus\n\n def setUp(self):\n super().setUp()\n if self.dbus_bus != 'session':\n self.useFixture(\n fixtures.EnvironmentVariable(\n \"DBUS_SESSION_BUS_ADDRESS\",\n self.dbus_bus\n )\n )\n\n def launch(self, *arguments):\n raise NotImplementedError(\"Sub-classes must implement this method.\")\n\n\nclass UpstartApplicationLauncher(ApplicationLauncher):\n\n \"\"\"A launcher class that launches applications with UpstartAppLaunch.\"\"\"\n __doc__ += ApplicationLauncher.__doc__\n\n Timeout = object()\n Failed = object()\n Started = object()\n Stopped = object()\n\n def launch(self, app_id, app_uris=[]):\n \"\"\"Launch an application with upstart.\n\n This method launches an application via the ``upstart-app-launch``\n library, on platforms that support it.\n\n Usage is similar to NormalApplicationLauncher::\n\n from autopilot.application import UpstartApplicationLauncher\n launcher = UpstartApplicationLauncher()\n launcher.setUp()\n app_proxy = launcher.launch('gallery-app')\n\n :param app_id: name of the application to launch\n :param app_uris: list of separate application uris to launch\n :raises RuntimeError: If the specified application cannot be launched.\n\n :returns: proxy object for the launched package application\n\n \"\"\"\n if isinstance(app_uris, str):\n app_uris = [app_uris]\n if isinstance(app_uris, bytes):\n app_uris = [app_uris.decode()]\n _logger.info(\n \"Attempting to launch application '%s' with URIs '%s' via \"\n \"upstart-app-launch\",\n app_id,\n ','.join(app_uris)\n )\n state = {}\n state['loop'] = self._get_glib_loop()\n state['expected_app_id'] = app_id\n state['message'] = ''\n\n UbuntuAppLaunch.observer_add_app_failed(self._on_failed, state)\n UbuntuAppLaunch.observer_add_app_started(self._on_started, state)\n UbuntuAppLaunch.observer_add_app_focus(self._on_started, state)\n GLib.timeout_add_seconds(10.0, self._on_timeout, state)\n\n self._launch_app(app_id, app_uris)\n state['loop'].run()\n UbuntuAppLaunch.observer_delete_app_failed(self._on_failed)\n UbuntuAppLaunch.observer_delete_app_started(self._on_started)\n UbuntuAppLaunch.observer_delete_app_focus(self._on_started)\n self._maybe_add_application_cleanups(state)\n self._check_status_error(\n state.get('status', None),\n state.get('message', '')\n )\n pid = self._get_pid_for_launched_app(app_id)\n\n return self._get_proxy_object(pid)\n\n def _get_proxy_object(self, pid):\n return get_proxy_object_for_existing_process(\n dbus_bus=self.dbus_bus,\n emulator_base=self.proxy_base,\n pid=pid\n )\n\n @staticmethod\n def _on_failed(launched_app_id, failure_type, state):\n if launched_app_id == state['expected_app_id']:\n if failure_type == UbuntuAppLaunch.AppFailed.CRASH:\n state['message'] = 'Application crashed.'\n elif failure_type == UbuntuAppLaunch.AppFailed.START_FAILURE:\n state['message'] = 'Application failed to start.'\n state['status'] = UpstartApplicationLauncher.Failed\n state['loop'].quit()\n\n @staticmethod\n def _on_started(launched_app_id, state):\n if launched_app_id == state['expected_app_id']:\n state['status'] = UpstartApplicationLauncher.Started\n state['loop'].quit()\n\n @staticmethod\n def _on_stopped(stopped_app_id, state):\n if stopped_app_id == state['expected_app_id']:\n state['status'] = UpstartApplicationLauncher.Stopped\n state['loop'].quit()\n\n @staticmethod\n def _on_timeout(state):\n state['status'] = UpstartApplicationLauncher.Timeout\n state['loop'].quit()\n\n def _maybe_add_application_cleanups(self, state):\n if state.get('status', None) == UpstartApplicationLauncher.Started:\n app_id = state['expected_app_id']\n self.addCleanup(self._stop_application, app_id)\n self.addCleanup(self._attach_application_log, app_id)\n\n @staticmethod\n def _get_user_unit_match(app_id):\n return 'ubuntu-app-launch-*-%s-*.service' % app_id\n\n def _attach_application_log(self, app_id):\n j = journal.Reader()\n j.log_level(journal.LOG_INFO)\n j.add_match(_SYSTEMD_USER_UNIT=self._get_user_unit_match(app_id))\n log_data = ''\n for i in j:\n log_data += str(i) + '\\n'\n if len(log_data) > 0:\n self.caseAddDetail('Application Log (%s)' % app_id,\n safe_text_content(log_data))\n\n def _stop_application(self, app_id):\n state = {}\n state['loop'] = self._get_glib_loop()\n state['expected_app_id'] = app_id\n\n UbuntuAppLaunch.observer_add_app_stop(self._on_stopped, state)\n GLib.timeout_add_seconds(10.0, self._on_timeout, state)\n\n UbuntuAppLaunch.stop_application(app_id)\n state['loop'].run()\n UbuntuAppLaunch.observer_delete_app_stop(self._on_stopped)\n\n if state.get('status', None) == UpstartApplicationLauncher.Timeout:\n _logger.error(\n \"Timed out waiting for Application with app_id '%s' to stop.\",\n app_id\n )\n\n @staticmethod\n def _get_glib_loop():\n return GLib.MainLoop()\n\n @staticmethod\n def _get_pid_for_launched_app(app_id):\n return UbuntuAppLaunch.get_primary_pid(app_id)\n\n @staticmethod\n def _launch_app(app_name, app_uris):\n UbuntuAppLaunch.start_application_test(app_name, app_uris)\n\n @staticmethod\n def _check_status_error(status, extra_message=''):\n message_parts = []\n if status == UpstartApplicationLauncher.Timeout:\n message_parts.append(\n \"Timed out while waiting for application to launch\"\n )\n elif status == UpstartApplicationLauncher.Failed:\n message_parts.append(\"Application Launch Failed\")\n if message_parts and extra_message:\n message_parts.append(extra_message)\n if message_parts:\n raise RuntimeError(': '.join(message_parts))\n\n\nclass AlreadyLaunchedUpstartLauncher(UpstartApplicationLauncher):\n \"\"\"Launcher that doesn't wait for a proxy object.\n\n This is useful when you are 're-launching' an already running application\n and it's state has changed to suspended.\n\n \"\"\"\n\n def _get_proxy_object(self, pid):\n # Don't wait for a proxy object\n return None\n\n\nclass ClickApplicationLauncher(UpstartApplicationLauncher):\n\n \"\"\"Fixture to manage launching a Click application.\"\"\"\n __doc__ += ApplicationLauncher.__doc__\n\n def launch(self, package_id, app_name=None, app_uris=[]):\n \"\"\"Launch a click package application with introspection enabled.\n\n This method takes care of launching a click package with introspection\n exabled. You probably want to use this method if your application is\n packaged in a click application, or is started via upstart.\n\n Usage is similar to NormalApplicationLauncher.launch::\n\n from autopilot.application import ClickApplicationLauncher\n launcher = ClickApplicationLauncher()\n launcher.setUp()\n app_proxy = launcher.launch('com.ubuntu.dropping-letters')\n\n :param package_id: The Click package name you want to launch. For\n example: ``com.ubuntu.dropping-letters``\n :param app_name: Currently, only one application can be packaged in a\n click package, and this parameter can be left at None. If\n specified, it should be the application name you wish to launch.\n :param app_uris: Parameters used to launch the click package. This\n parameter will be left empty if not used.\n\n :raises RuntimeError: If the specified package_id cannot be found in\n the click package manifest.\n :raises RuntimeError: If the specified app_name cannot be found within\n the specified click package.\n\n :returns: proxy object for the launched package application\n\n \"\"\"\n if isinstance(app_uris, str):\n app_uris = [app_uris]\n if isinstance(app_uris, bytes):\n app_uris = [app_uris.decode()]\n _logger.info(\n \"Attempting to launch click application '%s' from click package \"\n \" '%s' and URIs '%s'\",\n app_name if app_name is not None else \"(default)\",\n package_id,\n ','.join(app_uris)\n )\n app_id = _get_click_app_id(package_id, app_name)\n return super().launch(app_id, app_uris)\n\n\nclass NormalApplicationLauncher(ApplicationLauncher):\n\n \"\"\"Fixture to manage launching an application.\"\"\"\n __doc__ += ApplicationLauncher.__doc__\n\n def launch(self, application, arguments=[], app_type=None, launch_dir=None,\n capture_output=True):\n \"\"\"Launch an application and return a proxy object.\n\n Use this method to launch an application and start testing it. The\n arguments passed in ``arguments`` are used as arguments to the\n application to launch. Additional keyword arguments are used to control\n the manner in which the application is launched.\n\n This fixture is designed to be flexible enough to launch all supported\n types of applications. Autopilot can automatically determine how to\n enable introspection support for dynamically linked binary\n applications. For example, to launch a binary Gtk application, a test\n might start with::\n\n from autopilot.application import NormalApplicationLauncher\n launcher = NormalApplicationLauncher()\n launcher.setUp()\n app_proxy = launcher.launch('gedit')\n\n For use within a testcase, use useFixture:\n\n from autopilot.application import NormalApplicationLauncher\n launcher = self.useFixture(NormalApplicationLauncher())\n app_proxy = launcher.launch('gedit')\n\n Applications can be given command line arguments by supplying an\n ``arguments`` argument to this method. For example, if we want to\n launch ``gedit`` with a certain document loaded, we might do this::\n\n app_proxy = launcher.launch(\n 'gedit', arguments=['/tmp/test-document.txt'])\n\n ... a Qt5 Qml application is launched in a similar fashion::\n\n app_proxy = launcher.launch(\n 'qmlscene', arguments=['my_scene.qml'])\n\n If you wish to launch an application that is not a dynamically linked\n binary, you must specify the application type. For example, a Qt4\n python application might be launched like this::\n\n app_proxy = launcher.launch(\n 'my_qt_app.py', app_type='qt')\n\n Similarly, a python/Gtk application is launched like so::\n\n app_proxy = launcher.launch(\n 'my_gtk_app.py', app_type='gtk')\n\n :param application: The application to launch. The application can be\n specified as:\n\n * A full, absolute path to an executable file.\n (``/usr/bin/gedit``)\n * A relative path to an executable file.\n (``./build/my_app``)\n * An app name, which will be searched for in $PATH (``my_app``)\n\n :keyword arguments: If set, the list of arguments is passed to the\n launched app.\n\n :keyword app_type: If set, provides a hint to autopilot as to which\n kind of introspection to enable. This is needed when the\n application you wish to launch is *not* a dynamically linked\n binary. Valid values are 'gtk' or 'qt'. These strings are case\n insensitive.\n\n :keyword launch_dir: If set to a directory that exists the process\n will be launched from that directory.\n\n :keyword capture_output: If set to True (the default), the process\n output will be captured and attached to the test as test detail.\n\n :return: A proxy object that represents the application. Introspection\n data is retrievable via this object.\n\n \"\"\"\n _logger.info(\n \"Attempting to launch application '%s' with arguments '%s' as a \"\n \"normal process\",\n application,\n ' '.join(arguments)\n )\n app_path = _get_application_path(application)\n app_path, arguments = self._setup_environment(\n app_path, app_type, arguments)\n process = self._launch_application_process(\n app_path, capture_output, launch_dir, arguments)\n proxy_object = get_proxy_object_for_existing_process(\n dbus_bus=self.dbus_bus,\n emulator_base=self.proxy_base,\n process=process,\n pid=process.pid\n )\n proxy_object.set_process(process)\n return proxy_object\n\n def _setup_environment(self, app_path, app_type, arguments):\n app_env = self.useFixture(\n _get_application_environment(app_type, app_path)\n )\n return app_env.prepare_environment(\n app_path,\n list(arguments),\n )\n\n def _launch_application_process(self, app_path, capture_output, cwd,\n arguments):\n process = launch_process(\n app_path,\n arguments,\n capture_output,\n cwd=cwd,\n )\n\n self.addCleanup(self._kill_process_and_attach_logs, process, app_path)\n\n return process\n\n def _kill_process_and_attach_logs(self, process, app_path):\n stdout, stderr, return_code = _kill_process(process)\n self.caseAddDetail(\n 'process-return-code (%s)' % app_path,\n safe_text_content(str(return_code))\n )\n self.caseAddDetail(\n 'process-stdout (%s)' % app_path,\n safe_text_content(stdout)\n )\n self.caseAddDetail(\n 'process-stderr (%s)' % app_path,\n safe_text_content(stderr)\n )\n\n\ndef launch_process(application, args, capture_output=False, **kwargs):\n \"\"\"Launch an autopilot-enabled process and return the process object.\"\"\"\n commandline = [application]\n commandline.extend(args)\n _logger.info(\"Launching process: %r\", commandline)\n cap_mode = None\n if capture_output:\n cap_mode = subprocess.PIPE\n process = subprocess.Popen(\n commandline,\n stdin=subprocess.PIPE,\n stdout=cap_mode,\n stderr=cap_mode,\n close_fds=True,\n preexec_fn=os.setsid,\n universal_newlines=True,\n **kwargs\n )\n return process\n\n\ndef _get_click_app_id(package_id, app_name=None):\n for pkg in _get_click_manifest():\n if pkg['name'] == package_id:\n if app_name is None:\n # py3 dict.keys isn't indexable.\n app_name = list(pkg['hooks'].keys())[0]\n elif app_name not in pkg['hooks']:\n raise RuntimeError(\n \"Application '{}' is not present within the click \"\n \"package '{}'.\".format(app_name, package_id))\n\n return \"{0}_{1}_{2}\".format(package_id, app_name, pkg['version'])\n raise RuntimeError(\n \"Unable to find package '{}' in the click manifest.\"\n .format(package_id)\n )\n\n\ndef _get_click_manifest():\n \"\"\"Return the click package manifest as a python list.\"\"\"\n # get the whole click package manifest every time - it seems fast enough\n # but this is a potential optimisation point for the future:\n click_manifest_str = subprocess.check_output(\n [\"click\", \"list\", \"--manifest\"],\n universal_newlines=True\n )\n return json.loads(click_manifest_str)\n\n\ndef _get_application_environment(app_type=None, app_path=None):\n if app_type is None and app_path is None:\n raise ValueError(\"Must specify either app_type or app_path.\")\n try:\n if app_type is not None:\n return _get_app_env_from_string_hint(app_type)\n else:\n return get_application_launcher_wrapper(app_path)\n except (RuntimeError, ValueError) as e:\n _logger.error(str(e))\n raise RuntimeError(\n \"Autopilot could not determine the correct introspection type \"\n \"to use. You can specify this by providing app_type.\"\n )\n\n\ndef get_application_launcher_wrapper(app_path):\n \"\"\"Return an instance of :class:`ApplicationLauncher` that knows how to\n launch the application at 'app_path'.\n \"\"\"\n # TODO: this is a teeny bit hacky - we call ldd to check whether this\n # application links to certain library. We're assuming that linking to\n # libQt* or libGtk* means the application is introspectable. This excludes\n # any non-dynamically linked executables, which we may need to fix further\n # down the line.\n\n try:\n ldd_output = subprocess.check_output(\n [\"ldd\", app_path],\n universal_newlines=True\n ).strip().lower()\n except subprocess.CalledProcessError as e:\n raise RuntimeError(str(e))\n if 'libqtcore' in ldd_output or 'libqt5core' in ldd_output:\n return QtApplicationEnvironment()\n elif 'libgtk' in ldd_output:\n return GtkApplicationEnvironment()\n return None\n\n\ndef _get_application_path(application):\n try:\n return subprocess.check_output(\n ['which', application],\n universal_newlines=True\n ).strip()\n except subprocess.CalledProcessError as e:\n raise ValueError(\n \"Unable to find path for application {app}: {reason}\"\n .format(app=application, reason=str(e))\n )\n\n\ndef _get_app_env_from_string_hint(hint):\n lower_hint = hint.lower()\n if lower_hint == 'qt':\n return QtApplicationEnvironment()\n elif lower_hint == 'gtk':\n return GtkApplicationEnvironment()\n\n raise ValueError(\"Unknown hint string: {hint}\".format(hint=hint))\n\n\ndef _kill_process(process):\n \"\"\"Kill the process, and return the stdout, stderr and return code.\"\"\"\n stdout_parts = []\n stderr_parts = []\n _logger.info(\"waiting for process to exit.\")\n _attempt_kill_pid(process.pid)\n for _ in Timeout.default():\n tmp_out, tmp_err = process.communicate()\n if isinstance(tmp_out, bytes):\n tmp_out = tmp_out.decode('utf-8', errors='replace')\n if isinstance(tmp_err, bytes):\n tmp_err = tmp_err.decode('utf-8', errors='replace')\n stdout_parts.append(tmp_out)\n stderr_parts.append(tmp_err)\n if not _is_process_running(process.pid):\n break\n else:\n _logger.info(\n \"Killing process group, since it hasn't exited after \"\n \"10 seconds.\"\n )\n _attempt_kill_pid(process.pid, signal.SIGKILL)\n return ''.join(stdout_parts), ''.join(stderr_parts), process.returncode\n\n\ndef _attempt_kill_pid(pid, sig=signal.SIGTERM):\n try:\n _logger.info(\"Killing process %d\", pid)\n os.killpg(pid, sig)\n except OSError:\n _logger.info(\"Appears process has already exited.\")\n\n\ndef _is_process_running(pid):\n return psutil.pid_exists(pid)\n","repo_name":"chenhan1218/autopilot","sub_path":"autopilot/application/_launcher.py","file_name":"_launcher.py","file_ext":"py","file_size_in_byte":20785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"27978355973","text":"from matplotlib import pyplot as plt\nfrom matplotlib.font_manager import FontProperties\n\n\ndef check(line):\n if line.endswith(\"--\\n\"):\n return False\n return True\n\n\ndef plot_watch(memoryList):\n font = FontProperties(fname='../SimHei.ttf')\n\n # 指定大小 dpi指定每英寸像素点,越大越清晰\n plt.figure(figsize=(20, 8), dpi=80)\n plt.title(\"docker启动1min内存变化\" , fontproperties=font)\n\n x=range(len(memoryList))\n plt.plot(x, memoryList)\n\n plt.xlabel(\"时间/s\", fontproperties=font)\n plt.ylabel(\"内存变化/mb\", fontproperties=font)\n\n plt.grid(alpha=0.4)\n\n plt.savefig(\"./docker-memory.png\")\n plt.show()\n\n\ndef process_watch_file(filename):\n f = open(filename, \"r\")\n lines = f.readlines()\n\n memoryList = []\n for line in lines:\n if not check(line):\n continue\n line=line.strip('\\n')\n line=line.strip('M')\n memoryList.append(int(line))\n return memoryList\n\n\nif __name__ == '__main__':\n\n filename = \"./memory-change.txt\"\n memoryList = process_watch_file(filename)\n print(memoryList)\n plot_watch(memoryList)\n","repo_name":"WANNA959/k8s_watch","sub_path":"docker_watch/docker_process.py","file_name":"docker_process.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"17649073391","text":"# Создать телефонный справочник с возможностью импорта и экспорта данных в формате .txt. \n# Фамилия, имя, отчество, номер телефона - данные, которые должны находиться в файле.\n# 1. Программа должна выводить данные\n# 2. Программа должна сохранять данные в\n# текстовом файле\n# 3. Пользователь может ввести одну из\n# характеристик для поиска определенной записи(Например имя или фамилию человека)\n# 4. Использование функций. Ваша программа не должна быть линейной\n\n# save_info = open('/Users/olgadrach/Documents/GB/Python/Seminar/Python_Seminar7/save.txt', 'r', encoding='UTF-8')\n\n# Поиск данных по заданному параметру\ndef print_info(atribut):\n with open('/Users/olgadrach/Documents/GB/Python/Seminar/Python_Seminar7/save.txt', 'r', encoding='UTF-8') as save_info:\n for line in save_info:\n if str(atribut).lower() in str(line).lower():\n print(line)\n # else:\n # print('Ошибочный ввод')\n\n# Запрос у пользователя атрибута для поиска\ndef find_atribut():\n atribut = input('Введите инфо для поиска или оставьте пустым для вывода всех данных: ')\n return atribut\n\n\n# Добавление данных\ndef import_new_data():\n print('Введите новые данные в формате: Имя Фамилия Телефон')\n with open('/Users/olgadrach/Documents/GB/Python/Seminar/Python_Seminar7/save.txt', 'a', encoding='UTF-8') as save_info:\n save_info.writelines(input('Строка ввода: '))\n save_info.write('\\n')\n print('Данные внесены')\n# print_info(find_atribut())\nimport_new_data()","repo_name":"dolchik/Python_Seminar7","sub_path":"Ex_49.py","file_name":"Ex_49.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"7266560926","text":"from flask_api import FlaskAPI\nfrom flask import request\nimport docker\nimport sqlite3\nimport random\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\nimport subprocess\nfrom urllib.parse import urlparse\n\napp = FlaskAPI(__name__)\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/aditya/Projects/nvie_agent/nvie.agent'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////home/ubuntu/nvie_agent/nvie.agent'\nclient = docker.from_env()\ndb = SQLAlchemy(app)\n\ndef uri_validator(x):\n try:\n result = urlparse(x)\n return True\n except:\n return False\nclass ContainerPortMapping(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n env_name = db.Column(db.String(100), unique=True, nullable=False)\n container = db.Column(db.String(100), unique=True, nullable=False)\n port = db.Column(db.Integer(), unique=True, nullable=False)\n old_port = db.Column(db.Integer(), nullable=False)\n\n@app.route('/spawn', methods=['POST'])\ndef index():\n params = request.data\n print(params)\n port_list = ContainerPortMapping.query.with_entities(ContainerPortMapping.port).all()\n port = random.randrange(10000, 65534)\n while port in port_list:\n port = random.randrange(10000, 65534)\n try:\n old_port = params['port']\n env_name = params['env_name']\n gh_repo = params['gh_repo']\n print(\"Pulling\")\n client.images.pull(params['image_name'])\n print(\"Pulled\")\n path = \"\"\n if uri_validator(params['env_name']) and len(params['env_name'].split(\".\")) == 5:\n path = \"/home/ubuntu/storage/\"+params['env_name'].split(\".\")[0]+\"-\"+params['env_name'].split(\".\")[1]+\"-\"+params['env_name'].split(\".\")[2]\n print(path)\n # path = \"/Users/aditya/Projects/nvie_agent/\"+params['env_name'].split(\".\")[0]+\"-\"+params['env_name'].split(\".\")[1]\n try:\n os.mkdir(path)\n subprocess.call(['git','clone',gh_repo, path])\n subprocess.call(['sudo','chmod', '-R', \"777\", path])\n print(\"Cloned and permissioned\")\n except FileExistsError as e1:\n print(e1)\n else:\n return {'status':False, \"desc\":\"Env Name not a valid env URL\"}\n print(\"Running Container\")\n container = client.containers.run(params['image_name'], detach = True, ports = {str(params['port']):port}, volumes= {str(path):{'bind': '/home/nvie', 'mode': 'rw'}}, stdin_open = True, tty = True)\n print(\"Container Run\")\n mapping = ContainerPortMapping(env_name = env_name, container = container.id, port = port, old_port = old_port)\n db.session.add(mapping)\n conf = '''server {\n listen 80;\n server_name '''+str(env_name)+''';\n\n location / {\n proxy_pass http://localhost:'''+str(port)+''';\n }\n}'''\n with open(\"/etc/nginx/conf.d/\"+env_name+\".conf\", \"w\") as file:\n file.write(conf)\n subprocess.call([\"sudo\", \"service\", \"nginx\", \"restart\"])\n db.session.commit()\n print(\"Created Container\")\n except Exception as e:\n print(e)\n return {'status':False}\n print({'status':True,'container_id':container.id, 'container_name':container.name})\n return {'status':True,'container_id':container.id, 'container_name':container.name}\n\n@app.route('/stop', methods=['POST'])\ndef stop():\n try:\n params = request.data\n mapping_list = ContainerPortMapping.query.filter_by(env_name = params['env_name']).first()\n container = client.containers.get(mapping_list.container)\n db.session.delete(mapping_list)\n container.stop()\n db.session.commit()\n except Exception as e:\n return {'status':False}\n return {'status':True, 'container_id':container.id, 'container_name':container.name,'env_name':params['env_name']}\n\n@app.route('/stop-all', methods=['GET'])\ndef stopall():\n try:\n containers = client.containers.list()\n running_containers = []\n for i in containers:\n mapping_list = ContainerPortMapping.query.filter_by(container = i.id).first()\n running_containers.append({'container_name':i.name, 'container_id':i.id, 'env_name':mapping_list.env_name})\n db.session.delete(mapping_list)\n i.stop()\n db.session.commit()\n except Exception as e:\n return {'status':False}\n return {'status':True, 'stopped':running_containers}\n\n@app.route('/running', methods=['GET'])\ndef running():\n containers = client.containers.list()\n running_containers = []\n for i in containers:\n mapping_list = ContainerPortMapping.query.filter_by(container = i.id).first()\n env_name = \"\"\n if mapping_list:\n env_name = mapping_list.env_name\n running_containers.append({'container_name':i.name, 'container_id':i.id, 'env_name':env_name})\n # container.stop()\n return {'status':True, 'running':running_containers}\n\nif __name__=='__main__':\n db.create_all()\n app.run(debug = True,host = '0.0.0.0')\n\n","repo_name":"nvie-us/nvie_agent","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"7251437915","text":"#https://docs.python.org/3/library/asyncio-task.html#example-coroutine-displaying-the-current-date\nimport asyncio\nimport datetime\n\nasync def display_date(loop):\n end_time = loop.time() + 5.0\n while True:\n print(datetime.datetime.now())\n if (loop.time() + 1.0) >= end_time:\n break\n await asyncio.sleep(1)\n\nloop = asyncio.get_event_loop()\n# Blocking call which returns when the display_date() coroutine is done\nloop.run_until_complete(display_date(loop))\nloop.close()\n\n","repo_name":"natenka/asyncio-study-group","sub_path":"tutorials-docs/asyncio_docs/1_coroutine_displaying_the_current_date.py","file_name":"1_coroutine_displaying_the_current_date.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"8"} +{"seq_id":"17763946990","text":"#!/usr/bin/env python\n\nimport datetime\nimport logging\nfrom logging.handlers import RotatingFileHandler\n\nfrom flask import Flask, jsonify, request\n\nimport dao\nfrom connection import pool\nfrom inputs import (FsmtJsonInputs,\n BomDocumentJsonInputs)\n\napp = Flask(__name__)\napp.config.from_object('serverconfig')\nprint(\"call to pool 1\")\npool = pool()\n\nformatter = logging.Formatter(\n \"[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s\")\nhandler = RotatingFileHandler(app.config['LOG_FILENAME'],\n maxBytes=10000000,\n backupCount=5)\nhandler.setLevel(logging.DEBUG)\nhandler.setFormatter(formatter)\napp.logger.addHandler(handler)\n\n# Output the access logs to the same file\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.DEBUG)\nlog.addHandler(handler)\n\n\ndef date_range_helper(request):\n req_sdate = request.args.get('sdate')\n req_edate = request.args.get('edate')\n facility = request.args.get('facility')\n\n if req_sdate:\n sdate = datetime.datetime.strptime(req_sdate, \"%Y-%m-%d\").date()\n else:\n sdate = datetime.datetime.now().date() - datetime.timedelta(days=1000)\n\n if req_edate:\n edate = datetime.datetime.strptime(req_edate, \"%Y-%m-%d\").date()\n else:\n edate = datetime.datetime.now().date() + datetime.timedelta(days=1)\n\n if not facility:\n facility = 'A1'\n\n return sdate, edate, facility\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return \"404 not found\", 404\n\n\n@app.route('/')\ndef hello_world():\n return 'Guildhall MES-API v1'\n\n\n@app.route('/eboms', methods=['GET'])\ndef get_eboms():\n sdate, edate, facility = date_range_helper(request)\n print (sdate, edate, facility)\n return jsonify(dao.EbomList(pool, facility, sdate, edate).to_dict())\n\n\n@app.route('/eboms', methods=['POST'])\ndef post_ebom():\n success = False\n document_id = None\n inputs = BomDocumentJsonInputs(request)\n if not inputs.validate():\n response = jsonify(success=success, errors=inputs.errors), 400\n return response\n else:\n data = request.get_json()\n document = dao.EbomDocument(pool)\n document.from_dict(data)\n document_id = document.init()\n if document_id:\n success = True\n response = jsonify(success=success, message=\"document id=[{0}] created\".format(document_id)), 200\n else:\n response = jsonify(success=success, errors=document.errors), 400\n return response\n\n\n@app.route('/eboms/', methods=['GET'])\ndef get_demand(document_id):\n document = dao.EbomDocument(pool, document_id)\n return jsonify(document.to_dict())\n\n\n@app.route('/eboms/', methods=['DELETE'])\ndef del_demand(document_id):\n document = dao.EbomDocument(pool)\n success = document.delete(document_id)\n if success:\n response = ('', 204)\n else:\n response = jsonify(success=False, errors=document.errors), 400\n return response\n\n\n@app.route('/eboms//body', methods=['PATCH'])\ndef patch_demand_body(document_id):\n data = request.get_json()\n if data:\n d = dao.EbomDocument(pool)\n d.from_dict(data)\n d.reinit(document_id)\n return jsonify(str(document_id))\n else:\n return '', 400\n\n\n@app.route('/eboms//fsmt', methods=['PUT'])\ndef patch_demand_fsmt(document_id):\n success = False\n inputs = FsmtJsonInputs(request)\n\n if not inputs.validate():\n response = jsonify(success=False, errors=inputs.errors), 400\n else:\n data = request.get_json()\n document = dao.EbomDocument(pool)\n\n if data['curr_fsmt'] == 'COMMITTED':\n success = document.commit(document_id)\n response = jsonify(success=success, message=\"document commited\"), 200\n elif data['curr_fsmt'] == 'DECOMMITTED':\n success = document.decommit(document_id)\n response = jsonify(success=success, message=\"document decommited\"), 200\n else:\n return jsonify(success=success, errors=\"incorrect fsmt\"), 400\n\n if not success:\n response = jsonify(success=False, errors=document.errors), 400\n\n if not response:\n response = jsonify(success=success, message=\"unexpected error\"), 400\n\n return response\n\n\n@app.route('/mboms', methods=['GET'])\ndef get_reserves():\n sdate, edate, facility = date_range_helper(request)\n return jsonify(dao.MbomList(pool, facility, sdate, edate).to_dict())\n\n\n@app.route('/mboms', methods=['POST'])\ndef post_reserve():\n success = False\n document_id = None\n inputs = OutboundDocumentJsonInputs(request)\n if not inputs.validate():\n response = jsonify(success=success, errors=inputs.errors), 400\n return response\n else:\n data = request.get_json()\n document = dao.MbomDocument(pool)\n document.from_dict(data)\n document_id = document.init()\n if document_id:\n success = True\n response = jsonify(success=success, message=\"document id=[{0}] created\".format(document_id)), 200\n else:\n response = jsonify(success=success, errors=document.errors), 400\n return response\n\n\n@app.route('/mboms/', methods=['GET'])\ndef get_reserve(document_id):\n document = dao.MbomDocument(pool, document_id)\n return jsonify(document.to_dict())\n\n\n@app.route('/mboms/', methods=['DELETE'])\ndef del_reserve(document_id):\n document = dao.MbomDocument(pool)\n success = document.delete(document_id)\n if success:\n response = ('', 204)\n else:\n response = jsonify(success=False, errors=document.errors), 400\n\n return response\n\n\n@app.route('/mboms//body', methods=['PATCH'])\ndef patch_reserve_body(document_id):\n data = request.get_json()\n if data:\n d = dao.MbomDocument(pool)\n d.from_dict(data)\n d.reinit(document_id)\n return jsonify(str(document_id))\n else:\n return '', 400\n\n\n@app.route('/mboms//fsmt', methods=['PUT'])\ndef patch_reserve_fsmt(document_id):\n success = False\n inputs = FsmtJsonInputs(request)\n\n if not inputs.validate():\n response = jsonify(success=False, errors=inputs.errors), 400\n else:\n data = request.get_json()\n document = dao.MbomDocument(pool)\n\n if data['curr_fsmt'] == 'COMMITTED':\n success = document.commit(document_id)\n response = jsonify(success=success, message=\"document commited\"), 200\n elif data['curr_fsmt'] == 'DECOMMITTED':\n success = document.decommit(document_id)\n response = jsonify(success=success, message=\"document decommited\"), 200\n else:\n return jsonify(success=success, errors=\"incorrect fsmt\"), 400\n\n if not success:\n response = jsonify(success=False, errors=document.errors), 400\n\n if not response:\n response = jsonify(success=success, message=\"unexpected error\"), 400\n\n return response\n\n@app.route('/operations/', methods=['GET'])\ndef get_opertion(document_id):\n document = dao.OperationDocument(pool, document_id)\n #print(type(document.head))\n #print(document.head)\n #print(type(document.body[0]))\n #print(type(document.body))\n return jsonify(document.to_dict())\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"shcherbak/guildhall","sub_path":"api/mes-api/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"8"} +{"seq_id":"29051009444","text":"from easydict import EasyDict as edict\nimport underworld as uw\nfrom underworld import function as fn\n\n\nclass phases():\n \"\"\"\n Class that allows you to create 'phase functions' for a mineral component\n\n \"\"\"\n def __init__(self,name, depths,temps, widths,claps,buoyancies):\n \"\"\"\n Class initialiser.\n\n Parameter\n ---------\n name : str\n 'Component', e.g olivine, pyroxene-garnet\n depths: list\n list of transition depths in model units\n temps: list\n list of transition depths in model units\n Typical scaling will be temps(') = (temps(K) - tempSurf(K))/deltaT(K)\n widths: list\n list of transition temps (temp along adiabat) model units\n claps: list\n list of Clapeyron slopes in model units\n Typical scaling will be claps(') = claps(Pa/K)*slopeFactor\n slopeFactor = (tempscale/(densityscale*gravityscale*lengthscale)\n buoyancies: list\n list of density changes associeated with each phase transition in model units.\n Density change is considered positive if density increseas as depth increases,\n i.e. downward-traversing the phase transition\n Typical scaling will be buoyancies(') = densities(kg/m3)*buoyancyFactor\n buoyancyFactor = (gravityScale*lengthScale**3)/(viscosityScale*diffusivityScale)\n\n Returns\n -------\n mesh : ndp\n Dictionary storing the phase-transition values (ndp referring to non-dimensional parameter)\n\n \"\"\"\n if not len(depths) == len(widths) == len(claps) == len(buoyancies):\n raise ValueError( \"All lists of phase values should be the same length\")\n self.ndp = edict({})\n self.ndp.name = name\n self.ndp.depths = depths\n self.ndp.temps = temps\n self.ndp.widths = widths\n self.ndp.claps = claps\n self.ndp.buoyancies = buoyancies\n\n def nd_reduced_pressure(self, depthFn, temperatureField, depthPh, clapPh, tempPh):\n \"\"\"\n Creates an Underworld function, representing the 'reduced pressure'\n \"\"\"\n\n return (depthFn - depthPh) - clapPh*(temperatureField - tempPh)\n\n def nd_phase(self, reduced_p, widthPh):\n \"\"\"\n Creates an Underworld function, representing the phase function in the domain\n \"\"\"\n return 0.5*(1. + fn.math.tanh(reduced_p/(widthPh)))\n\n def phase_function_sum(self, temperatureField, depthFn):\n \"\"\"\n Creates an Underworld function, representing the Sum of the individual phase functions,\n mainly for testing implementation\n\n Parameter\n ---------\n temperatureField : underworld.mesh._meshvariable.MeshVariable\n mesh variable holding the model temperature field\n depthFn : underworld.function._function\n function representing depth from surface (model dimensions)\n \"\"\"\n\n pf_sum = uw.function.misc.constant(0.)\n\n for phaseId in range(len(self.dp['depths'])):\n #build reduced pressure\n rp = self.nd_reduced_pressure(depthFn,\n temperatureField,\n self.ndp['depths'][phaseId ],\n self.ndp['claps'][phaseId ],\n self.ndp['temps'][phaseId ])\n #build phase function\n pf = self.nd_phase(rp, self.ndp['widths'][phaseId ])\n pf_sum += pf\n\n return pf_sum\n\n def buoyancy_sum(self, temperatureField, depthFn):\n \"\"\"\n Creates an Underworld function, representing the Sum of the individual phase functions...\n and the associated density changes:\n\n pf_sum = Sum_k{ (Ra*delRho_k*pf_k/rho_0*eta_0*delta_t)}\n\n Parameter\n ---------\n temperatureField : underworld.mesh._meshvariable.MeshVariable\n mesh variable holding the model temperature field\n depthFn : underworld.function._function\n function representing depth from surface (model dimensions)\n\n\n \"\"\"\n #bouyancyFactor = (gravityscale*lengthscale**3)/(viscosityscale*diffusivityscale)\n\n pf_sum = uw.function.misc.constant(0.)\n\n for phaseId in range(len(self.ndp['depths'])):\n #build reduced pressure\n rp = self.nd_reduced_pressure(depthFn,\n temperatureField,\n self.ndp['depths'][phaseId ],\n self.ndp['claps'][phaseId ],\n self.ndp['temps'][phaseId ])\n #build phase function\n pf = self.nd_phase(rp, self.ndp['widths'][phaseId ])\n pf_sum += pf*self.ndp['buoyancies'][phaseId ] #we want the dimensional buoyancies here\n\n return pf_sum\n","repo_name":"dansand/UWsubduction","sub_path":"UWsubduction/phases_materials/_phase_utils.py","file_name":"_phase_utils.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"8"} +{"seq_id":"32387787756","text":"import unittest\nimport numpy as np\nimport rclpy\nfrom uuv_thrusters import ThrusterManager\n\nimport launch\nfrom launch import LaunchDescription\nimport launch_testing.actions\nimport launch_ros\nfrom launch_ros.actions import Node\nfrom ament_index_python.packages import get_package_share_directory\nimport os\nimport pathlib\nimport xacro\nimport pytest\nimport threading\nimport time\n\n\nREFERENCE_TAM = np.array([\n [1, 0, 0, 0, 0, 0],\n [0.87758256, 0, -0.47942554, 0.47942554, 0.47942554, 0.87758256],\n [0.87758256, 0.47942554, 0, -0.47942554, 0.87758256, -0.87758256]\n]).T\n\n\ndef ensure_path_exists(full_path):\n dir_name = os.path.dirname(full_path)\n if dir_name:\n try:\n os.makedirs(dir_name)\n except OSError:\n print (\"Creation of the directory %s failed\" % dir_name)\n\n\nclass TestThrusterManagerProportionalCorrect(unittest.TestCase):\n _manager = None\n _thread = None\n \n @classmethod\n def setUpClass(cls):\n parent_file_path = pathlib.Path(__file__).parent \n thruster_manager_yaml = os.path.join(\n str(parent_file_path),\n 'test_vehicle_thruster_manager_proportional.yaml'\n )\n\n xacro_file = os.path.join(\n str(parent_file_path),\n 'test_vehicle_x_axis.urdf.xacro'\n )\n \n doc = xacro.process(xacro_file)\n \n # Initialize the ROS context for the test node\n # FIXME Temp workaround TF for listener subscribing to relative topic\n rclpy.init(args=['--ros-args', '--params-file', thruster_manager_yaml, \n '-r', '__ns:=/test_vehicle', '-r', 'tf:=/tf', '-p', 'robot_description:=%s' % doc])\n\n # Name alias...why cls is not working ?\n _class = TestThrusterManagerProportionalCorrect\n \n _class._manager = ThrusterManager('test_thruster_manager_proportional_correct')\n _class._thread = threading.Thread(target=rclpy.spin, args=(_class._manager,), daemon=True)\n _class._thread.start()\n\n # Wait for the async initialization of the manager to finish\n while not _class._manager.ready:\n time.sleep(0.1)\n\n # =========================================================================\n @classmethod\n def tearDownClass(cls):\n _class = TestThrusterManagerProportionalCorrect\n\n _class._manager.destroy_node()\n # Shutdown the ROS context\n rclpy.shutdown()\n _class._thread.join()\n\n # =========================================================================\n # def setUp(self):\n \n # # =========================================================================\n # def tearDown(self):\n # # self.MANAGER.destroy_node()\n # # self.thread.join()\n\n # =========================================================================\n def test_initialization(self): \n _class = TestThrusterManagerProportionalCorrect\n self.assertEqual(_class._manager.namespace, '/test_vehicle/')\n\n self.assertEqual(_class._manager.config['tf_prefix'].value, 'test_vehicle')\n self.assertEqual(_class._manager.config['base_link'].value, 'base_link')\n self.assertEqual(_class._manager.config['thruster_topic_prefix'].value, 'thrusters/') \n self.assertEqual(_class._manager.config['thruster_frame_base'].value, 'thruster_')\n self.assertEqual(_class._manager.config['thruster_topic_suffix'].value, '/input')\n self.assertEqual(_class._manager.config['timeout'].value, -1)\n self.assertEqual(_class._manager.config['max_thrust'].value, 1000.0)\n self.assertEqual(_class._manager.config['update_rate'].value, 50)\n\n self.assertEqual(_class._manager.n_thrusters, 3)\n\n self.assertEqual(REFERENCE_TAM.shape, _class._manager.configuration_matrix.shape) \n\n self.assertTrue(np.isclose(REFERENCE_TAM, _class._manager.configuration_matrix).all())\n\n # =========================================================================\n def test_thrusters(self):\n _class = TestThrusterManagerProportionalCorrect\n\n self.assertEqual(len(_class._manager.thrusters), 3)\n\n for i in range(len(_class._manager.thrusters)):\n self.assertEqual(_class._manager.thrusters[i].index, i)\n self.assertEqual(_class._manager.thrusters[i].topic, 'thrusters/id_{}/input'.format(i))\n self.assertEqual(_class._manager.thrusters[i].LABEL, 'proportional')\n self.assertTrue(np.isclose(REFERENCE_TAM[:, i].flatten(), _class._manager.thrusters[i].tam_column).all())\n\n # =========================================================================\n def test_processing_gen_forces(self):\n _class = TestThrusterManagerProportionalCorrect\n\n for _ in range(10):\n gen_force = np.random.rand(6) * 100\n thrust_forces = _class._manager.compute_thruster_forces(gen_force)\n\n ref_thrust_forces = np.linalg.pinv(REFERENCE_TAM).dot(gen_force)\n\n self.assertTrue(np.isclose(ref_thrust_forces, thrust_forces).all())\n\n\n# =============================================================================\n@pytest.mark.rostest\ndef generate_test_description():\n #path_to_test = os.path.dirname(__file__)\n file_path = pathlib.Path(__file__)\n # Here, parent first removes the file name\n parent_file_path = pathlib.Path(__file__).parent \n\n thruster_manager_launch = os.path.join(\n get_package_share_directory('uuv_thruster_manager'),\n 'launch',\n 'thruster_manager.launch'\n )\n\n thruster_manager_yaml = os.path.join(\n str(parent_file_path),\n 'test_vehicle_thruster_manager_proportional.yaml'\n )\n\n xacro_file = os.path.join(\n str(parent_file_path),\n 'test_vehicle_x_axis.urdf.xacro'\n )\n\n doc = xacro.process(xacro_file)\n\n joint_state_publisher = launch_ros.actions.Node(\n namespace = 'test_vehicle',\n package=\"joint_state_publisher\",\n executable=\"joint_state_publisher\",\n name=\"joint_state_publisher\",\n output='screen',\n parameters=[{'use_sim_time':False}, {'rate': 100}],\n )\n\n robot_state_description = launch_ros.actions.Node(\n namespace = 'test_vehicle',\n package='robot_state_publisher',\n executable='robot_state_publisher',\n output='screen',\n parameters=[{'use_sim_time':False}, {'robot_description': doc}], # Use subst here\n )\n\n return (\n launch.LaunchDescription([ \n joint_state_publisher,\n robot_state_description,\n launch_testing.actions.ReadyToTest(),\n ])\n )\n","repo_name":"Liquid-ai/Plankton","sub_path":"uuv_control/uuv_thruster_manager/test/test_thruster_manager_proportional_correct.test.py","file_name":"test_thruster_manager_proportional_correct.test.py","file_ext":"py","file_size_in_byte":6617,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"8"} +{"seq_id":"5925413174","text":"\"\"\"\nDemonstrate playing multiple simultaneous tones, which requires making samples which share a common period. These are individually computed in advance, but summed up here together.\n\nFrequencies will not be represented exactly, so that they can line up exactly (small misalignments when repeating sounds will be audible) so we compromise by making a sample size which is small enough to fit in memory, but large enough to hold samples of everything.\n\nRefer to readme.md for wiring.\n\"\"\"\n\n\nfrom machine import I2S\nfrom machine import ADC, Pin\nimport os\nimport time\nfrom ulab import numpy as np\nimport uasyncio as asyncio\n\nideal_sample_counts = [\n (1186, [14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 27]),\n (2461, [29, 31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55]),\n (5474, [65, 69, 73, 77, 82, 87, 92, 97, 103, 109, 116, 123]),\n (6749, [80, 85, 90, 95, 101, 107, 113, 120, 127, 135, 143, 151]),\n (9776, [116, 123, 130, 138, 146, 155, 164, 174, 184, 195, 207, 219]),\n (15599, [185, 196, 208, 220, 233, 247, 262, 277, 294, 311, 330, 349]),\n]\nletters = \"C C# D D# E F F# G G# A A# B\".split()\n\n\nprint(\"precomputing samples...\", end=\"\")\ntick = time.ticks_us()\nnum_samples, note_divisors = ideal_sample_counts[1]\nfilenames = [f\"{num_samples}/{letter}.npy\" for letter in letters]\nif str(num_samples) not in os.listdir():\n t = np.linspace(0, 2 * np.pi, num_samples, endpoint=False)\n os.mkdir(str(num_samples))\n for filename, divisor in zip(filenames, note_divisors):\n np.save(filename, np.sin(t * divisor))\n del(t)\nelse:\n print('found some ready made!...', end='')\nplay_buffer = np.zeros(num_samples, dtype=np.int16)\nplay_view = memoryview(play_buffer.tobytes())\nsum_buffer = play_buffer.copy()\ntock = time.ticks_us()\nprint(f\"computed the samples in {tock-tick} microseconds\")\n\n\npotentiometer = ADC(Pin(26))\nkeys = [Pin(i, Pin.IN, Pin.PULL_UP) for i in range(12)]\n\n\nasync def continuous_loop(audio_out, mv):\n swriter = asyncio.StreamWriter(audio_out)\n while True:\n swriter.write(mv)\n await swriter.drain()\n \nasync def main(audio_out, sum_buffer):\n play = asyncio.create_task(continuous_loop(audio_out, play_view))\n while True:\n sum_buffer[:] = 0\n amplitude = potentiometer.read_u16() / 2\n for key, filename in zip(keys, filenames):\n if not key.value():\n sum_buffer += np.asarray(amplitude * np.load(filename), dtype=np.int16)\n \n play_buffer[:] = sum_buffer\n await asyncio.sleep(0)\n\n\n\ntry:\n audio_out = I2S(\n 0,\n sck=Pin(18),\n ws=Pin(19),\n sd=Pin(20),\n mode=I2S.TX,\n bits=16,\n format=I2S.MONO,\n rate=22_050,\n ibuf=2* num_samples * 2 #bytes/sample,\n )\n asyncio.run(main(audio_out, sum_buffer))\nexcept (KeyboardInterrupt, Exception) as e:\n print(\"caught exception {} {}\".format(type(e).__name__, e))\nfinally:\n audio_out.deinit()\n print(\"Done\")\n","repo_name":"TheDataScienceLabs/DSLab_Fourier","sub_path":"tools/I2S_audio_examples/piano.py","file_name":"piano.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"8"} +{"seq_id":"43386180846","text":"# !/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# import functions\nimport os\nimport sys\nimport argparse\nimport numpy as np\nimport torch\nfrom torch.optim import Adam\nfrom sklearn.linear_model import LogisticRegression\n# ignore warning\nfrom warnings import simplefilter\nfrom sklearn.exceptions import ConvergenceWarning\nimport random\n# project import\nfrom dataset import get_dataloaders, SimCLRDataAugmentation\nfrom loss import align_loss, uniform_loss, joint_entropy_loss, norm\nfrom encoder import StrongEncoder, WeakEncoder\n\n\ndef train(weak_encoder, strong_encoder, train_loader, test_loader, n_epochs, pond):\n # define optimizer\n optimizer = Adam(list(weak_encoder.parameters()) + list(strong_encoder.parameters()), lr=3e-4)\n # data augmentation\n data_aug_pipeline = SimCLRDataAugmentation()\n\n # Train model\n print(\"epoch : 0\")\n test_linear_probe(weak_encoder, strong_encoder, train_loader, test_loader)\n for epoch in range(1, n_epochs):\n weak_encoder.train()\n strong_encoder.train()\n\n train_loss = 0\n for batch_idx, (weak_view, strong_view, _, _) in enumerate(train_loader):\n with torch.no_grad():\n weak_view1 = data_aug_pipeline(weak_view)\n weak_view2 = data_aug_pipeline(weak_view)\n strong_view1 = data_aug_pipeline(strong_view)\n strong_view2 = data_aug_pipeline(strong_view)\n\n # weak_head\n _, weak_head_1 = weak_encoder(weak_view1.cuda())\n _, weak_head_2 = weak_encoder(weak_view2.cuda())\n\n # strong head\n _, common_strong_head_1, _, strong_head_1 = strong_encoder(strong_view1.cuda())\n _, common_strong_head_2, _, strong_head_2 = strong_encoder(strong_view2.cuda())\n\n # weak loss\n weak_align_loss = align_loss(norm(weak_head_1), norm(weak_head_2))\n weak_uniform_loss = (uniform_loss(norm(weak_head_2)) + uniform_loss(norm(weak_head_1))) / 2.0\n weak_loss = weak_align_loss + weak_uniform_loss\n\n # common strong to weak\n common_strong_align_loss = align_loss(norm(weak_head_1.detach()), norm(common_strong_head_1))\n common_strong_align_loss += align_loss(norm(weak_head_2.detach()), norm(common_strong_head_2))\n common_strong_align_loss /= 2.0\n common_strong_uniform_loss = (uniform_loss(norm(common_strong_head_2)) + uniform_loss(norm(common_strong_head_1))) / 2.0\n common_strong_loss = common_strong_align_loss + common_strong_uniform_loss\n\n # strong loss\n strong_align_loss = align_loss(norm(strong_head_1), norm(strong_head_2))\n strong_uniform_loss = (uniform_loss(norm(strong_head_2)) + uniform_loss(norm(strong_head_1))) / 2.0\n strong_loss = strong_align_loss + strong_uniform_loss\n\n # mi minimization loss\n jem_loss = joint_entropy_loss(norm(strong_head_1), norm(weak_head_1.detach()))\n jem_loss = jem_loss + joint_entropy_loss(norm(strong_head_2), norm(weak_head_2.detach()))\n jem_loss = jem_loss / 2.0\n\n loss = strong_loss + common_strong_loss + weak_loss + pond*jem_loss\n\n loss.backward()\n train_loss += loss.item()\n optimizer.step()\n optimizer.zero_grad()\n\n if epoch % 10 == 0:\n print(\"epoch : \", epoch)\n test_linear_probe(weak_encoder, strong_encoder, train_loader, test_loader)\n\n\n# test linear probes\ndef test_linear_probe(weak_encoder, strong_encoder, train_loader, test_loader):\n weak_encoder.eval()\n strong_encoder.eval()\n with torch.no_grad():\n X_train_strong = []\n X_test_strong = []\n X_train_strong_common = []\n X_test_strong_common = []\n X_train_weak = []\n X_test_weak = []\n y_weak_train = []\n y_weak_test = []\n y_strong_train = []\n y_strong_test = []\n for weak_view, strong_view, weak_label, strong_label in train_loader:\n weak_rep, _ = weak_encoder(weak_view.cuda())\n common_strong_rep, _, strong_rep, _ = strong_encoder(strong_view.cuda())\n X_train_strong.extend(strong_rep.cpu().numpy())\n X_train_strong_common.extend(common_strong_rep.cpu().numpy())\n X_train_weak.extend(weak_rep.cpu().numpy())\n y_weak_train.extend(weak_label.cpu().numpy())\n y_strong_train.extend(strong_label.cpu().numpy())\n for weak_view, strong_view, weak_label, strong_label in test_loader:\n weak_rep, _ = weak_encoder(weak_view.cuda())\n common_strong_rep, _, strong_rep, _ = strong_encoder(strong_view.cuda())\n X_test_strong.extend(strong_rep.cpu().numpy())\n X_test_strong_common.extend(common_strong_rep.cpu().numpy())\n X_test_weak.extend(weak_rep.cpu().numpy())\n y_weak_test.extend(weak_label.cpu().numpy())\n y_strong_test.extend(strong_label.cpu().numpy())\n X_train_strong = np.array(X_train_strong)\n X_test_strong = np.array(X_test_strong)\n X_train_strong_common = np.array(X_train_strong_common)\n X_test_strong_common = np.array(X_test_strong_common)\n X_train_weak = np.array(X_train_weak)\n X_test_weak = np.array(X_test_weak)\n y_weak_train = np.array(y_weak_train)\n y_weak_test = np.array(y_weak_test)\n y_strong_train = np.array(y_strong_train)\n y_strong_test = np.array(y_strong_test)\n\n log_reg = LogisticRegression().fit(X_train_strong, y_strong_train)\n log_reg_score = log_reg.score(X_test_strong, y_strong_test)\n print(\"strong evaluated on strong labels (high) : \", log_reg_score)\n\n log_reg = LogisticRegression().fit(X_train_strong, y_weak_train)\n log_reg_score = log_reg.score(X_test_strong, y_weak_test)\n print(\"strong evaluated on weak labels (low) : \", log_reg_score)\n\n log_reg = LogisticRegression().fit(X_train_strong_common, y_strong_train)\n log_reg_score = log_reg.score(X_test_strong_common, y_strong_test)\n print(\"strong common evaluated on strong labels (low) : \", log_reg_score)\n\n log_reg = LogisticRegression().fit(X_train_strong_common, y_weak_train)\n log_reg_score = log_reg.score(X_test_strong_common, y_weak_test)\n print(\"strong common evaluated on weak labels (high) : \", log_reg_score)\n\n log_reg = LogisticRegression().fit(X_train_weak, y_weak_train)\n log_reg_score = log_reg.score(X_test_weak, y_weak_test)\n print(\"weak evaluated on weak labels (high) : \", log_reg_score)\n\n print('-----')\n\n\ndef parse_args(argv):\n parser = argparse.ArgumentParser(\n prog=os.path.basename(__file__),\n description='Train strong encoder')\n parser.add_argument(\n \"-m\", \"--weak_modality\", type=str, required=True, choices=[\"mnist\", \"cifar\"],\n help=\"Weak modality, can be either 'cifar' or 'mnist'\")\n parser.add_argument(\n \"-c\", \"--checkpoint_dir\", type=str, required=True,\n help=\"Directory where models are saved\")\n parser.add_argument(\n \"-p\", \"--ponderation\", type=float, default=100.0,\n help=\"Ponderation of the jem loss.\")\n parser.add_argument(\n \"-w\", \"--weak_size\", type=int, default=32,\n help=\"Latent space size of the weak encoder. Default is 32.\")\n parser.add_argument(\n \"-s\", \"--strong_size\", type=int, default=32,\n help=\"Latent space size of the strong encoder. Default is 32.\")\n parser.add_argument(\n \"-n\", \"--n_epochs\", type=int, default=251,\n help=\"Number of epochs for training. Default is 251.\")\n args = parser.parse_args(argv)\n\n if not os.path.exists(args.checkpoint_dir):\n raise NotADirectoryError(\"Checkpoint directory is not found.\")\n return args\n\n\ndef main(argv):\n simplefilter(\"ignore\", category=ConvergenceWarning)\n random.seed(0)\n\n args = parse_args(argv)\n # hyper-parameter\n weak_modality = args.weak_modality\n weak_size = args.weak_size\n strong_size = args.strong_size\n n_epochs = args.n_epochs\n pond = args.ponderation\n\n # Instantiate Dataset and Data Loader\n train_loader, test_loader = get_dataloaders(weak_modality=weak_modality)\n print(\"WARNING WRONG BATCH SIZE\")\n\n # build model\n weak_encoder = torch.load(os.path.join(args.checkpoint_dir,\n f\"sep_mod_weak_{weak_modality}.pth\")) # WeakEncoder(weak_dim=weak_size).float().cuda()\n strong_encoder = StrongEncoder(common_dim=weak_size, strong_dim=strong_size).float().cuda()\n\n # train model\n train(weak_encoder, strong_encoder, train_loader, test_loader, n_epochs, pond)\n\n # save model\n print(\"Saving model...\")\n recognition_modality = {\"cifar\": \"mnist\", \"mnist\": \"cifar\"}[weak_modality]\n torch.save(strong_encoder, os.path.join(args.checkpoint_dir,\n f\"sep_mod_strong_for_{recognition_modality}_recognition.pth\"))\n print(\"\\n--------\\nREMINDER\\n--------\\n\")\n print(\"WEAK MODALITY : \", weak_modality)\n print(\"STRONG MODALITY : \", recognition_modality)\n\n\nif __name__ == \"__main__\":\n main(argv=sys.argv[1:])\n","repo_name":"PierreAuriau/disentangling_neurodev_factors_from_t1mri","sub_path":"train_strong.py","file_name":"train_strong.py","file_ext":"py","file_size_in_byte":9124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"84226051","text":"def test(a,*b,c):\n total=a+c\n for i in b:\n total=total+i\n h=max(b)\n Max=max(a,h,c)\n k=min(b)\n Min=min(a,h,c)\n print(\"这几个数的和为:\",total)\n print(\"最大值为:\",Max)\n print(\"最小值为:\",Min)\ntest(1,2,3,4,5,c=8)\n\n","repo_name":"skyrookies/spider_learn","sub_path":"day6_10.7/8/8/8.3.py","file_name":"8.3.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"8"} +{"seq_id":"73816932423","text":"from django.shortcuts import render, redirect, get_object_or_404\r\nfrom django.http import HttpResponse\r\nfrom .models import students\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.urls import reverse\r\nfrom django.template import loader\r\n#from django.http import get_object_or_404\r\nfrom django.contrib import messages\r\nfrom .forms import studentform\r\n\r\ndef index(request):\r\n context = {\r\n 'students' : students.objects.all()\r\n }\r\n template =\"student/index.html\"\r\n return render(request, template, context)\r\n #return HttpResponse(\"Schhol Management\")\r\n\r\ndef add_form(request):\r\n if request.method == 'POST':\r\n form = studentform(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n messages.info(request, 'You have succesfully registered ')\r\n return redirect('index')\r\n else:\r\n messages.error(request, 'Invalid data entry, please try again ')\r\n return HttpResponseRedirect('add')\r\n \r\n else:\r\n form = studentform()\r\n return render(request, 'student/add.html', {'form':form})\r\n \r\ndef view_info(request, id):\r\n stu = students.object.get(pk=id)\r\n return HttpResponseRedirect('index')\r\n\r\n\r\ndef update_view(request, id):\r\n # if request.method == \"POST\":\r\n stu= students.objects.get(pk=id)\r\n form = studentform(request.POST, instance=stu)\r\n if form.is_valid():\r\n form.save()\r\n messages.success(request, 'Record succesfully updated ')\r\n return redirect('index')\r\n #return render(request, 'student/update.html', {'form':form,\r\n # 'success':True})\r\n else:\r\n stu = students.objects.get(pk = id)\r\n form = studentform(instance=stu)\r\n return render(request, 'student/update.html', {'form':form})\r\n \r\ndef delete(request, id):\r\n if request.method == \"POST\":\r\n stu = students.objects.get(pk = id)\r\n stu.delete()\r\n messages.warning(request, 'Record succesfully deleted ')\r\n \r\n return HttpResponseRedirect(reverse('index'))\r\n\r\n\r\n","repo_name":"yuramsoft/Django-CRUD-Create-Retrieve-Update-Delete-Operations-using-Function-Basec-View","sub_path":"crud/srm/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"37593416492","text":"from posixpath import split\nfrom typing import List\n\n\nclass vent:\n def __init__(self, vent_definition: str):\n points = vent_definition.split(\" -> \")\n start = [int(point) for point in points[0].split(\",\")]\n end = [int(point) for point in points[1].split(\",\")]\n\n self.points = []\n self.diagonal = False\n\n if start[0] != end[0] and start[1] != end[1]:\n self.diagonal = True\n\n run = end[0] - start[0]\n x_move = 1\n if run < 0:\n x_move = -1\n\n rise = end[1] - start[1]\n y_move = 1\n if rise < 0:\n y_move = -1\n\n for i in range(abs(rise) + 1):\n x = start[0] + (i * x_move)\n y = start[1] + (i * y_move)\n self.points.append([x, y])\n else:\n if start[0] != end[0]:\n if start[0] > end[0]:\n start, end = end, start\n for i in range(end[0] - start[0] + 1):\n self.points.append([start[0] + i, start[1]])\n else:\n if start[1] > end[1]:\n start, end = end, start\n for i in range(end[1] - start[1] + 1):\n self.points.append([start[0], start[1] + i])\n","repo_name":"normanthesquid/advent-of-code-2021","sub_path":"day_05/vent.py","file_name":"vent.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"8"} +{"seq_id":"903863577","text":"#!/usr/bin/env python3\nfrom __future__ import annotations\n\nimport sys\nimport argparse\nimport time\nimport functools\nfrom multiprocessing.pool import ThreadPool\nimport requests\nimport requests.adapters\n\n\ndef connection_pool(size):\n session = requests.Session()\n adapter = requests.adapters.HTTPAdapter(pool_connections=size, pool_maxsize=size)\n session.mount(\"http://\", adapter)\n session.mount(\"https://\", adapter)\n return session\n\n\ndef parse_user_input_headers(headers: list[str]):\n if headers is None:\n return {}\n headers_dict = {}\n for header in headers:\n name, _, value = header.partition(\":\")\n headers_dict[name.strip().lower()] = value.strip()\n return headers_dict\n\n\ndef request_url(\n url,\n session: requests.Session,\n headers,\n check_headers,\n retry_count,\n retry_delay,\n timeout,\n) -> tuple[str, str | None]:\n while retry_count + 1 > 0:\n try:\n response = session.get(\n url,\n timeout=timeout,\n allow_redirects=False,\n headers=headers,\n stream=False,\n )\n except (requests.Timeout, requests.ConnectionError) as err:\n if retry_count > 0:\n time.sleep(retry_delay)\n retry_count -= 1\n continue\n return url, str(err)\n except Exception as err:\n return url, str(err)\n if str(response.status_code)[0] == \"5\":\n if retry_count > 0:\n time.sleep(retry_delay)\n retry_count -= 1\n continue\n return url, \"response status code %d\" % response.status_code\n\n if response.status_code != 200:\n return url, \"response status code %d\" % response.status_code\n if len(response.content) == 0:\n return url, \"response empty\"\n for name, value in check_headers.items():\n received_value = response.headers.get(name)\n if received_value != value:\n if received_value is None:\n header_str = 'no `%s` header' % name\n else:\n header_str = '%s: %s' % (name, received_value)\n return url, \"response headers check failed (%s)\" % header_str\n return url, None\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--input\",\n metavar=\"FILE\",\n type=argparse.FileType(\"r\", encoding=\"utf-8\"),\n required=True,\n help=\"Input file\",\n )\n parser.add_argument(\"--base\", metavar=\"URL\", required=False, help=\"URL base\")\n parser.add_argument(\n \"--threads\",\n type=int,\n required=False,\n default=1,\n help=\"Number of concurrent requests\",\n )\n parser.add_argument(\"--headers\", required=False, nargs=\"+\", help=\"Request headers\")\n parser.add_argument(\n \"--check-headers\", required=False, nargs=\"*\", help=\"Check response headers\"\n )\n parser.add_argument(\n \"--retry-count\",\n default=0,\n type=int,\n help=\"Number of retries for timeouts, connection errors and HTTP 5XX error\",\n )\n parser.add_argument(\n \"--retry-delay\",\n default=1,\n type=int,\n help=\"Delay between retries for --retry-count\",\n )\n parser.add_argument(\n \"--max-errors\", type=int, help=\"Stop program after this many errors\", default=1\n )\n parser.add_argument(\"--no-progress\", action=\"store_true\", default=False)\n parser.add_argument(\"--timeout\", default=60, type=int, help=\"Connect/read timeout\")\n conf = parser.parse_args()\n urls = [url.strip() for url in conf.input.readlines()]\n urls = list(filter(None, urls))\n base = conf.base.rstrip(\"/\")\n if conf.base:\n urls = [base + \"/\" + url.lstrip(\"/\") for url in urls]\n\n session = connection_pool(conf.threads)\n errors_count = 0\n try:\n with ThreadPool(conf.threads) as pool:\n processor = functools.partial(\n request_url,\n session=session,\n headers=parse_user_input_headers(conf.headers),\n check_headers=parse_user_input_headers(conf.check_headers),\n retry_count=conf.retry_count,\n retry_delay=conf.retry_delay,\n timeout=conf.timeout,\n )\n for i, (url, error) in enumerate(pool.imap_unordered(processor, urls), 1):\n if error:\n errors_count += 1\n if not conf.no_progress:\n print(\"\\r\", end=\"\")\n print(url, error)\n if errors_count > conf.max_errors:\n print(\"Too many errors, exiting\")\n break\n if not conf.no_progress:\n print(\"\\r%.2f%%\" % (100 * i / len(urls)), flush=True, end=\"\")\n except KeyboardInterrupt:\n sys.exit(130)\n finally:\n if not conf.no_progress:\n print()\n if errors_count > 0:\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wladich/request_http_cache","sub_path":"request_http_cache.py","file_name":"request_http_cache.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"19249483444","text":"a1 = open('a.txt','r').read()\na2 = open('a.txt','wb')\na2.write(a1.encode('UTF-8'))\na2.close()\n\nb1 = open('b.txt','r').read()\nb2 = open('b.txt','wb')\nb2.write(b1.encode('UTF-8'))\nb2.close()\n\nprint('Done')\n","repo_name":"Nyaasu66/learnpython","sub_path":"testchild/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"39318524415","text":"from openerp.osv import osv\nfrom openerp.report import report_sxw\n\nclass purchase_order_report(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(purchase_order_report, self).__init__(cr, uid, name, context=context)\n\n self.localcontext.update({\n 'set_company_name': self._set_company_name,\n 'set_name': self._set_name,\n 'set_first_name': self._set_first_name,\n 'set_tax_line': self._set_tax_line,\n 'set_quantity': self._set_quantity,\n 'set_taxes': self._set_taxes,\n 'set_description': self._set_description,\n 'set_price_subtotal': self._set_price_subtotal,\n 'set_price_unit': self._set_price_unit,\n 'set_amount': self._set_amount,\n 'set_amount_1': self._set_amount_1,\n 'set_unit_price': self._set_unit_price,\n 'set_total_lenge': self._set_total_lenge,\n 'set_length': self._set_length,\n\n })\n\n def _set_length(self, object):\n length = float(object.zpro_length)\n final = str(length).split('.')\n final_len = final[0] + ',' + final[1]\n return final_len\n\n def _set_total_lenge(self, object):\n tottal_len = object.product_qty * object.zpro_length\n tot_l = str(tottal_len).split('.')\n to_final = tot_l[0] + ',' + tot_l[1]\n return to_final\n\n def _set_unit_price(self, object):\n if object.price_unit:\n ab = object.product_id.zpro_length * object.price_unit\n num = str(ab).split('.')\n price_unit = num[0] + \",\" + num[1]\n\n return price_unit\n\n def _set_amount(self, amount):\n num = str(amount).split('.')\n amount = num[0] + \",\" + num[1]\n return amount\n\n def _set_amount_1(self, object):\n fin_reduction = 0.0\n if object.partner_id.fin_reduction_id:\n fin_reduction = object.partner_id.fin_reduction_id.fin_reduction\n\n amount = (object.amount_untaxed * (fin_reduction / 100))\n num = str(round(amount, 3)).split('.')\n amount = num[0] + \",\" + num[1]\n return amount\n\n def _set_price_subtotal(self, object):\n subtotal = object.price_unit * object.product_qty * object.zpro_length\n num = str(subtotal).split('.')\n price_subtotal = num[0] + \",\" + num[1]\n\n return price_subtotal\n\n def _set_price_unit(self, object):\n num = str(object.price_unit).split('.')\n price_unit = num[0] + \",\" + num[1]\n\n return price_unit\n\n def _set_description(self, object):\n if object.product_id:\n if object.product_id.description_sale:\n desc = object.product_id.description_sale\n return desc[0:80]\n else:\n desc = object.product_id.name\n return desc[0:80]\n return ''\n\n def _set_taxes(self, object):\n taxes = ''\n if object.taxes_id:\n for tax in object.taxes_id:\n if len(object.taxes_id) == 1:\n if tax.amount_type == 'group' and tax.children_tax_ids:\n taxes += str(int(tax.children_tax_ids[0].amount)) + \"%\"\n else:\n taxes += str(int(tax.amount)) + \"%\"\n\n else:\n if tax.amount_type == 'group' and tax.children_tax_ids:\n taxes += \",\" + str(int(tax.children_tax_ids[0].amount)) + \"%\"\n else:\n taxes += \",\" + str(int(tax.amount)) + \"%\"\n if taxes and taxes[0] == ',':\n taxes = taxes[1:]\n return taxes\n# def _set_taxes(self,object):\n# taxes = ''\n# if object.taxes_id:\n# for tax in object.taxes_id:\n# if len(object.taxes_id) == 1:\n# if object.taxes_id.amount_type != 'group':\n# taxes += (str(tax.amount))\n# else:\n# if tax.amount_type == 'group':\n# for child_tax in tax.children_tax_ids:\n# ret = tax.children_tax_ids[0].amount\n# return ret\n# else:\n# if object.taxes_id.amount_type != 'group':\n# taxes += \",\"+ (str(tax.amount))\n# else:\n# if tax.amount_type == 'group':\n# for child_tax in tax.children_tax_ids:\n# ret = tax.children_tax_ids[0].amount\n# return ret\n# return taxes\n\n def _set_quantity(self, object):\n if object.product_id:\n num = str(object.product_qty).split('.')\n qty = num[0] + \",\" + num[1]\n return qty\n return ''\n def _set_tax_line(self,object):\n taxes = []\n data = []\n\n for l in object.order_line:\n if l.taxes_id:\n t = [x.id for x in l.taxes_id[0]]\n if t[0] not in taxes:\n taxes.append(t[0])\n\n tax_data = {}\n for tax in taxes:\n for line in object.order_line:\n if line.taxes_id:\n if line.taxes_id[0].id == tax:\n fin_reduction = 0.0\n if object.partner_id.fin_reduction_id:\n fin_reduction = object.partner_id.fin_reduction_id.fin_reduction\n if line.taxes_id[0].id in tax_data:\n basis = tax_data.get(line.taxes_id[0].id)[1] + line.price_subtotal\n btw = tax_data.get(line.taxes_id[0].id)[2] + round(((line.price_subtotal - (line.price_subtotal * (fin_reduction / 100))) * (round(line.taxes_id[0].amount, 2) / 100)), 2)\n tax_data[line.taxes_id[0].id] = [line.taxes_id[0].description, basis, btw, basis + btw]\n else:\n basis = line.price_subtotal\n btw = round(((line.price_subtotal - (line.price_subtotal * (fin_reduction / 100))) * (round(line.taxes_id[0].amount, 2) / 100)), 2)\n tax_data.update({line.taxes_id[0].id: [line.taxes_id[0].description\n , basis\n , btw\n , (basis + btw)]})\n\n for t in tax_data:\n tmp = str(tax_data[t][1]).split('.')\n qty = tmp[0] + \",\" + tmp[1]\n tax_data[t][1] = qty\n\n tmp = str(tax_data[t][2]).split('.')\n qty = tmp[0] + \",\" + tmp[1]\n tax_data[t][2] = qty\n\n tmp = str(tax_data[t][3]).split('.')\n qty = tmp[0] + \",\" + tmp[1]\n tax_data[t][3] = qty\n\n data.append(tax_data[t])\n\n return data\n\n def _set_company_name(self,object):\n if object.partner_id.is_company:\n return object.partner_id.name\n if not object.partner_id.is_company and object.partner_id.parent_id:\n return object.partner_id.parent_id.name\n return \"\"\n\n def _set_name(self,object):\n name = \"\"\n\n if object.partner_id.is_company and object.partner_id.child_ids and object.partner_id.child_ids[0].name:\n if object.partner_id.child_ids[0].name:\n name = object.partner_id.child_ids[0].name\n if not object.partner_id.child_ids[0].name:\n name = object.partner_id.name\n# if len(object.partner_id.child_ids[0].name.split(' ')) > 1:\n# name = object.partner_id.child_ids[0].name.split(' ')[1]\n# if len(object.partner_id.child_ids[0].name.split(' ')) == 1:\n# name = object.partner_id.child_ids[0].name.split(' ')[0]\n\n if object.partner_id.is_company and not object.partner_id.child_ids:\n name = object.partner_id.name\n# if len(object.partner_id.name.split(' ')) > 1:\n# name = object.partner_id.name.split(' ')[1]\n# if len(object.partner_id.name.split(' ')) == 1:\n# name = object.partner_id.name.split(' ')[0]\n\n if not object.partner_id.is_company:\n if object.partner_id.name:\n name = object.partner_id.name\n# if len(object.partner_id.name.split(' ')) > 1:\n# name = object.partner_id.name.split(' ')[1]\n# if len(object.partner_id.name.split(' ')) == 1:\n# name = object.partner_id.name.split(' ')[0]\n\n return name\n\n def _set_first_name(self,object):\n\n name = \"\"\n if object.partner_id.is_company and object.partner_id.child_ids:\n if len(object.partner_id.child_ids[0].name.split(' ')) > 1:\n name = object.partner_id.child_ids[0].name.split(' ')[0]\n\n if not object.partner_id.is_company and object.partner_id.parent_id:\n if len(object.partner_id.name.split(' ')) > 1:\n name = object.partner_id.name.split(' ')[0]\n\n return name\n\n\n\nclass report_purchase_order_ext (osv.AbstractModel):\n _name = 'report.smt_purchaseorder_report.purchase_order_report'\n _inherit = 'report.abstract_report'\n _template = 'smt_purchaseorder_report.purchase_order_report'\n _wrapped_report_class = purchase_order_report\n","repo_name":"Riya-Sathavara/smeetdesign","sub_path":"smt_purchaseorder_report/report/purchase_order_report.py","file_name":"purchase_order_report.py","file_ext":"py","file_size_in_byte":9492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"27933887505","text":"from django.shortcuts import render\n\nfrom django.http import HttpResponse\nfrom django.template import loader\n\nresult = []\n\n\ndef index(request):\n result.clear()\n template = loader.get_template('myapp/index.html')\n if request.POST.get('calc'):\n print('calculated')\n birth_date = request.POST.get('birthdate', False)\n print(birth_date)\n if birth_date:\n start_engine(birth_date)\n print(result)\n first_num.clear()\n second_num.clear()\n third_num.clear()\n all_numbers.clear()\n destiny_number.clear()\n character.clear()\n energy.clear()\n interest.clear()\n health.clear()\n logic.clear()\n work.clear()\n luck.clear()\n debt.clear()\n memory.clear()\n print(result)\n counter = 0\n for i in result:\n if i == '':\n result[counter] = '—'\n counter+=1\n\n if len(result) >= 1:\n context = {\n 'character': result[0],\n 'energy': result[1],\n 'interest': result[2],\n 'health': result[3],\n 'logic': result[4],\n 'work': result[5],\n 'luck': result[6],\n 'debt': result[7],\n 'memory': result[8],\n 'ustremlennost': result[9],\n 'family': result[10],\n 'stability': result[11],\n 'temperament': result[12],\n 'bit': result[13],\n 'destiny_number': result[14],\n 'additional_numbers': additional_numbers[0],\n 'habbits': result[15],\n 'birth_date': birth_date,\n }\n additional_numbers.clear()\n return render(request, 'myapp/index.html', context=context)\n else:\n return render(request, 'myapp/index.html')\n\n\nfirst_num = []\n\nsecond_num = []\n\nthird_num = []\n\nall_numbers = []\n\ndestiny_number = []\n\nadditional_numbers = []\n\n\ndef start_engine(birth_date):\n birth_date = birth_date.split('.')\n main(birth_date)\n\n\ndef get_destiny_number(birth_date):\n for days in birth_date[0]:\n destiny_number.append(int(days))\n\n for months in birth_date[1]:\n destiny_number.append(int(months))\n\n for years in birth_date[2]:\n destiny_number.append(int(years))\n get_addtitional_numbers(destiny_number, birth_date[0])\n return sum(destiny_number)\n\n\ndef get_addtitional_numbers(destiny_number, birth_date: int):\n birth_date = int(birth_date)\n first_num = sum(destiny_number)\n a = (first_num // 10)\n b = (first_num % 10)\n second_num = a + b\n first_birthdate_num = int(str(abs(birth_date))[0])\n third_num = first_num - 2 * first_birthdate_num\n\n a = (third_num // 10)\n b = (third_num % 10)\n fourth_number = a + b\n additional_number = str(first_num) + '.' + str(second_num) + '.' + str(third_num) + '.' + str(fourth_number)\n additional_numbers.append(additional_number)\n\n\ndef get_first_number(birth_date):\n for days in birth_date[0]:\n first_num.append(int(days))\n\n for months in birth_date[1]:\n first_num.append(int(months))\n\n for years in birth_date[2]:\n first_num.append(int(years))\n\n return sum(first_num)\n\n\ndef get_second_number(first_number):\n second_num.append(first_number // 10)\n second_num.append(first_number % 10)\n return sum(second_num)\n\n\ndef get_third_number(birth_date, first_number):\n for days in birth_date[0]:\n dig = int(days) * 2\n third_number = first_number - dig\n return third_number\n\n\ndef get_fourth_number(third_number):\n third_num.append(third_number // 10)\n third_num.append(third_number % 10)\n return sum(third_num)\n\n\ndef creating_character(birth_date, first_number, second_number, third_number, fourth_number):\n for days in birth_date[0]:\n all_numbers.append(int(days))\n\n for months in birth_date[1]:\n all_numbers.append(int(months))\n\n for years in birth_date[2]:\n all_numbers.append(int(years))\n\n if first_number >= 10:\n all_numbers.append(first_number // 10)\n all_numbers.append(first_number % 10)\n else:\n all_numbers.append(first_number)\n\n if second_number >= 10:\n all_numbers.append(second_number // 10)\n all_numbers.append(second_number % 10)\n else:\n all_numbers.append(second_number)\n\n if third_number >= 10:\n all_numbers.append(third_number // 10)\n all_numbers.append(third_number % 10)\n else:\n all_numbers.append(third_number)\n\n if fourth_number >= 10:\n all_numbers.append(fourth_number // 10)\n all_numbers.append(fourth_number % 10)\n else:\n all_numbers.append(fourth_number)\n\n for number in all_numbers:\n if number == 1:\n character.append('1')\n elif number == 2:\n energy.append('2')\n elif number == 3:\n interest.append('3')\n elif number == 4:\n health.append('4')\n elif number == 5:\n logic.append('5')\n elif number == 6:\n work.append('6')\n elif number == 7:\n luck.append('7')\n elif number == 8:\n debt.append('8')\n elif number == 9:\n memory.append('9')\n\n character_value = ''.join(character)\n energy_value = ''.join(energy)\n interest_value = ''.join(interest)\n health_value = ''.join(health)\n logic_value = ''.join(logic)\n work_value = ''.join(work)\n luck_value = ''.join(luck)\n debt_value = ''.join(debt)\n memory_value = ''.join(memory)\n destiny = get_destiny_number(birth_date)\n second_number = get_second_number(first_number)\n while int(destiny) >= 10 and int(second_number) != 11:\n first_d_number = int(destiny) // 10\n second_d_number = int(destiny) % 10\n destiny = first_d_number + second_d_number\n # print(f'Внутренний квадрат: \\nХарактер: {character_value}\\nЭнергия: {energy_value}\\nИнтерес: {interest_value}'\n # f'\\nЗдоровье: {health_value}\\nЛогика: {logic_value}\\nТруд: {work_value}\\nУдача: {luck_value}\\nДолг: {debt_value}'\n # f'\\nПамять: {memory_value}\\n\\nВнешний квадрат:\\nЦелеустремленность:{len(character) + len(health) + len(luck)}\\n'\n # f'Семья: {len(energy) + len(logic) + len(debt)}\\n'\n # f'Стабильность: {len(interest) + len(work) + len(memory)}\\nТемперамент: {len(interest) + len(logic) + len(luck)}\\n'\n # f'Быт: {len(health) + len(logic) + len(work)}\\nЧисло судьбы: {destiny}')\n\n result.append(character_value), result.append(energy_value), result.append(interest_value), \\\n result.append(health_value), result.append(logic_value), result.append(work_value), result.append(luck_value), \\\n result.append(debt_value), result.append(memory_value), result.append(len(character) + len(health) + len(luck)), \\\n result.append(len(energy) + len(logic) + len(debt)), \\\n result.append(len(interest) + len(work) + len(memory)), \\\n result.append(len(interest) + len(logic) + len(luck)), \\\n result.append(len(health) + len(logic) + len(work)), \\\n result.append(destiny),\n result.append(len(interest) + len(work) + len(memory))\n\n\n# Результат вышестоящей функции должен быть передан в качестве контекста, обработчика шаблонов.\n\ncharacter = []\nenergy = []\ninterest = []\nhealth = []\nlogic = []\nwork = []\nluck = []\ndebt = []\nmemory = []\n\n\ndef main(birth_date):\n first_number = get_first_number(birth_date)\n second_number = get_second_number(first_number)\n third_number = get_third_number(birth_date, first_number)\n fourth_number = get_fourth_number(third_number)\n\n creating_character(birth_date, first_number, second_number, third_number, fourth_number)\n","repo_name":"Romario8841/d_c","sub_path":"destiny_calc/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"8603846172","text":"import pickle\n\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Flatten\nfrom keras.models import Sequential\n\n# LOAD PREVIOUSLY SAVED DATA\nX = pickle.load(open('X.pickle', 'rb'))\ny = pickle.load(open('y.pickle', 'rb'))\n\nX = X / 255\n\nmodel = Sequential([\n Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(150, 150, 1)),\n MaxPooling2D(2, 2),\n\n Conv2D(64, (3, 3), activation='relu'),\n MaxPooling2D(2, 2),\n\n Conv2D(128, (3, 3), activation='relu'),\n MaxPooling2D(2, 2),\n\n Conv2D(128, (3, 3), activation='relu'),\n MaxPooling2D(2, 2),\n\n Flatten(),\n Dense(512, activation='relu'),\n Dense(2, activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(X, y, batch_size=64, epochs=3, validation_split=0.1)\n","repo_name":"LukaKordic/signature-classifier-deep","sub_path":"SignatureConvNet.py","file_name":"SignatureConvNet.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"28654745546","text":"from typing import *\n\nclass Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n if len(s3) != len(s1) + len(s2):\n return False\n \n n = len(s1)\n m = len(s2)\n\n dp = [[False] * (m+1) for _ in range(n+1)]\n\n for i in range(n+1):\n for j in range(m+1):\n if i == 0 and j == 0:\n dp[i][j] = True\n elif i == 0:\n dp[i][j] = dp[j-1] and s2[j-1] == s3[i+j-1]\n elif j == 0:\n dp[i][j] = dp[i-1] and s1[i-1] == s3[i+j-1]\n else:\n dp[i][j] = dp[i-1][j] and s1[i-1] == s3[i+j-1] or dp[i][j-1] and s2[j-1] == s3[i+j-1]\n \n return dp[n][m]\n ","repo_name":"aidardarmesh/leetcode","sub_path":"Problems/97. Interleaving String.py","file_name":"97. Interleaving String.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"8"} +{"seq_id":"15731224446","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import col\n\n\ndef create_df():\n schema = \"`Id` INT, `First` STRING, `Last` STRING, `Url` STRING,\\\n `Published`\\\n STRING, `Hits`\\\n INT, `Campaigns`\\\n ARRAY < STRING > \"\n data = [[1, \"Jules\", \"Damji\", \"https://tinyurl.1\", \"1/4/2016\", 4535, [\"twitter\",\n \"LinkedIn\"]],\n [2, \"Brooke\",\"Wenig\", \"https://tinyurl.2\", \"5/5/2018\", 8908, [\"twitter\",\n \"LinkedIn\"]],\n [3, \"Denny\", \"Lee\", \"https://tinyurl.3\", \"6/7/2019\", 7659, [\"web\",\n \"twitter\", \"FB\", \"LinkedIn\"]],\n [4, \"Tathagata\", \"Das\", \"https://tinyurl.4\", \"5/12/2018\", 10568,\n [\"twitter\", \"FB\"]],\n [5, \"Matei\",\"Zaharia\", \"https://tinyurl.5\", \"5/14/2014\", 40578, [\"web\",\n \"twitter\", \"FB\", \"LinkedIn\"]],\n [6, \"Reynold\", \"Xin\", \"https://tinyurl.6\", \"3/2/2015\", 25568,\n [\"twitter\", \"LinkedIn\"]]\n ]\n\n spark = (SparkSession\n .builder\n .appName(\"CustomDFr\")\n .getOrCreate()\n )\n dataFrame = spark.createDataFrame(data, schema)\n few_dataFrame = (dataFrame\n .select(\"Id\", \"First\")\n .where(col('Id') > 4))\n few_dataFrame.show()\n\n #dataFrame.show()\n\nif __name__ == \"__main__\":\n create_df()","repo_name":"polkadot21/spark","sub_path":"create_dataFrame.py","file_name":"create_dataFrame.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"7173812417","text":"# coding: utf-8\r\n\r\n\r\nimport ConfigParser\r\nimport json\r\nimport os\r\nimport shutil\r\nimport sys\r\nimport argparse\r\nimport re\r\n\r\n\r\nclass CMakeGenerator(object):\r\n\r\n def __init__(self):\r\n self.read_config()\r\n self.build_dir = 'build-({0})-{1}'.format(self.project_type,\r\n self.build_type)\r\n self.print_config()\r\n self.execute()\r\n\r\n def read_config(self):\r\n config = ConfigParser.ConfigParser()\r\n config.read('cmake.ini')\r\n generators = json.loads(config.get('cmake', 'generators'))\r\n default_generator = json.loads(\r\n config.get('cmake', 'default_generator'))\r\n self.project_type = generators[default_generator]\r\n self.build_type = json.loads(config.get('cmake', 'build_type'))\r\n self.delete_cache = json.loads(config.get('cmake', 'delete_cache'))\r\n self.options = json.loads(config.get('cmake', 'options'))\r\n\r\n def print_config(self):\r\n print('Project type: ' + self.project_type)\r\n print('Build type: ' + self.build_type)\r\n print('Delete cache: {}'.format(self.delete_cache))\r\n print('Build directory: ' + self.build_dir)\r\n print('Options: {}'.format(self.options))\r\n\r\n def execute(self):\r\n if os.path.isdir(self.build_dir) is False:\r\n print('creating build director[{}]...'.format(self.build_dir))\r\n os.mkdir(self.build_dir)\r\n if self.delete_cache:\r\n print('deleting cache...')\r\n shutil.rmtree(self.build_dir)\r\n os.mkdir(self.build_dir)\r\n\r\n os.chdir(self.build_dir)\r\n cmd = 'cmake -G\"{0}\" -DCMAKE_BUILD_TYPE={1} .. '.format(\r\n self.project_type, self.build_type)\r\n for option in self.options:\r\n cmd += ' ' + option\r\n print(cmd)\r\n os.system(cmd)\r\n\r\n\r\ndef clean():\r\n for d in [f for f in os.listdir('.') if re.match(r'build-\\(.*\\)-.*', f)]:\r\n print('cleanning {} ...'.format(d))\r\n shutil.rmtree(d)\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--clean', action='store_true', help='clean cmake build cache')\r\n args = parser.parse_args()\r\n if args.clean:\r\n clean()\r\n else:\r\n cmake = CMakeGenerator()\r\n","repo_name":"QianChenglong/cmake-template","sub_path":"cmake.py","file_name":"cmake.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"8"} +{"seq_id":"1616315459","text":"import os\nimport subprocess\nimport shutil\nimport tensorflow as tf\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nfrom .DataLoader import DataLoader\nfrom .Models import MultiViewCNN, SingleViewCNN\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow.keras.losses import CategoricalCrossentropy\nfrom tensorflow.keras.metrics import categorical_accuracy, mean_squared_error\nfrom tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard, EarlyStopping\nfrom tqdm.keras import TqdmCallback\nfrom datetime import datetime\n\n\nclass Trainer:\n\n def __init__(self, settings, model_structure):\n self.settings = settings\n self.model_structure = model_structure\n self.view_mode = None\n if isinstance(self.model_structure, SingleViewCNN):\n self.view_mode = f'svcnn{self.model_structure.view_id}'\n elif isinstance(self.model_structure, MultiViewCNN):\n self.view_mode = 'mvcnn'\n self.model = self.model_structure.model\n self.model_optimizer = SGD(learning_rate=self.settings.lr, momentum=self.settings.momentum)\n self.model_loss = CategoricalCrossentropy()\n self.model_metrics = [categorical_accuracy, mean_squared_error]\n self.train_data_loader = None\n self.test_data_loader = None\n self.train_history = None\n\n def train(self):\n self.model.compile(optimizer=self.model_optimizer, loss=self.model_loss, metrics=self.model_metrics)\n self.model_structure.generate_model_plot(f'{self.view_mode}_model_diagram')\n self.train_data_loader = DataLoader(self.settings, train_test='train', mode=self.view_mode)\n self.test_data_loader = DataLoader(self.settings, train_test='test', mode=self.view_mode)\n working_dir = os.getcwd()\n now = datetime.now()\n log_path = os.path.join(working_dir, \"results\", \"training_logs\", self.view_mode, now.strftime(\"%m%d%Y%H%M%S\"))\n print(f'\\nBeginning training, to monitor open TensorBoard by running the following command: tensorboard --logdir=\"{log_path}\"\\n')\n tensorboard_callback = TensorBoard(log_dir=log_path, histogram_freq=1, update_freq='batch')\n checkpoint_filepath = os.path.join(working_dir, \"results\", \"models\", f\"{self.view_mode}_best_model.h5\")\n os.makedirs(os.path.dirname(checkpoint_filepath), exist_ok=True)\n checkpoint_callback = ModelCheckpoint(filepath=checkpoint_filepath, save_weights_only=True,\n monitor='val_categorical_accuracy', mode='max', save_best_only=True)\n early_stopping_callback = EarlyStopping(monitor='categorical_accuracy', min_delta=0.005, patience=20,\n mode='max')\n tqdm_callback = TqdmCallback(verbose=0)\n self.model.fit(x=self.train_data_loader,\n epochs=self.settings.num_epochs,\n verbose=0,\n validation_data=self.test_data_loader,\n callbacks=[tensorboard_callback,\n checkpoint_callback,\n early_stopping_callback,\n tqdm_callback])\n","repo_name":"gbensoneng/MVCNN-Keras","sub_path":"MVCNN/Trainer.py","file_name":"Trainer.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"17504300211","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\n\nimport pandas as pd\nimport numpy as np\nimport os\nimport glob\nimport time\nimport traceback \nimport sys \nimport warnings\nfrom sqlalchemy import create_engine, text\nimport psycopg2\nimport shutil\nwarnings.filterwarnings('ignore')\nstart_time = time.time() # get start time \npd.set_option('display.max_columns', None)\n# pd.set_option('display.max_rows', None)\n\n\n\n#read whatever files types being ingested \ndef read_anything(path,num):\n #Get all files avaialble in the path (path shall be only 1 file at a time to manage this )\n get_working_files = [x for x in os.listdir(path)]\n# get_working_files = x\n #make this as a function later \n if len(get_working_files) == 0:\n print('My goodman, no files either csv nor excel found, please recheck in path the existence')\n return None\n \n #Excel found \n time_start = time.time()\n# get_types_available = os.path.splitext(get_working_files[0])[1]\n# file_name = os.path.splitext(get_working_files[0])[0]\n for file_name in get_working_files:\n get_types_available = os.path.splitext(file_name)[1]\n if get_types_available.endswith('.xlsx'):\n \n time_start = time.time()\n print('We found excel files, hence we will read it and save to df_master, hold a moment ....')\n df_master = pd.read_excel(path+'/'+file_name,dtype=str,header=num).dropna(how='all')\n\n int_columns = []\n for col in df_master.columns:\n if df_master[col].notnull().all() and df_master[col].str.isdigit().all():\n int_columns.append(col)\n\n df_master[int_columns] = df_master[int_columns].astype(int)\n time_end = time.time()\n\n diff_time = time_end - time_start\n print(f'My performance reading {file_name} file took : {diff_time} seconds')\n return df_master\n\n elif get_types_available.endswith('.csv'):\n print('We found csv files, hence we will read it and save to df_master, hold a moment ....')\n time_start = time.time() \n try:\n df_master = pd.read_csv(os.path.join(path,file_name), skip_blank_lines=True,dtype=str,header=num).dropna(how='all')\n except UnicodeDecodeError:\n # If 'utf-8' fails, try 'ISO-8859-1' encoding\n df_master = pd.read_csv(os.path.join(path,file_name), encoding='ISO-8859-1', skip_blank_lines=True,dtype=str,header=num).dropna(how='all')\n int_columns = []\n for col in df_master.columns:\n if df_master[col].notnull().all() and df_master[col].str.isdigit().all():\n int_columns.append(col)\n df_master[int_columns] = df_master[int_columns].astype(int)\n time_end = time.time()\n diff_time = time_end - time_start\n print(f'My performance reading {file_name} file took : {diff_time} seconds')\n return df_master\n \n print('No suitable files (csv or excel) found in the specified path. Continuing to search...')\n return df_master\n\n\n\n#Query to get user input from UI in db input \n# Schema name and condition values\ndb_params = {\n 'host': '### INSERT IP HERE',\n 'database': '### INSERT',\n 'user': '### INSERT',\n 'password': '### INSERT'\n}\n\nschema_name = 'reference_data'\ntable_name = 'USER_INPUT'\n# Connect to the database\nconn = psycopg2.connect(**db_params)\ncursor = conn.cursor()\n\n# cursor.execute((f'SELECT * from {schema_name}.\"{table_name}\" ORDER BY timestamp_column ')\ncursor.execute(f'''\n SELECT *\n FROM (\n SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS row_num\n FROM {schema_name}.\"{table_name}\"\n ) AS numbered\n''')\nrows= cursor.fetchall()\n\ncolumns = [x[0] for x in cursor.description]\ndf = pd.DataFrame(rows,columns=columns)\n# Close the cursor and the connection\ncursor.close()\nconn.close()\n \n#add function to truncate table each time new data coming in \n\n\n\n\ndf = df.fillna(0).astype('int')\n\n\n\n\n#Get the latest user input data numbered by max row \nmax_row_num = df['row_num'].max()\nmax_row = df[df['row_num'] == max_row_num]\n#MODULE 0 : QUERY SQL TABLE BASED ON USER INPUT VALUE FROM FRONT END \nQUARTER = max_row['quarter'].values[0]\nYEAR = max_row['year'].values[0]\n\n\n\nprint(f'We are cleaning SGTGU Quarter {QUARTER} & Year {YEAR} Survey Data ')\n\n\n\n### PATH DECLARATION (ADJUST FOR HDFS ADN WINDOWS )\n#get t01 latest files path\ncurrent_path = os.getcwd()\nfiles_input_path_t01 = os.path.join(current_path, 'FILES INPUT', 'T01')\nraw_data_t01 = glob.glob(os.path.join(files_input_path_t01, '*.xlsx'))\nget_t01_latest = max(raw_data_t01, key=os.path.getmtime)\n\n# files_input_path_raw = os.path.join(current_path, 'FILES INPUT', 'RAW_DATA')\n# raw_data_raw = glob.glob(os.path.join(files_input_path_raw, '*.xlsx'))\n# get_raw_latest = max(raw_data_raw, key=os.path.getmtime)\nbin_path = os.path.join(current_path, 'BIN')\n\nfiles_input_path_raw = os.path.join(current_path, 'FILES INPUT', 'RAW_DATA')\n\n\n#set output path \nfiles_output_path_result = os.path.join(current_path, 'FILES OUTPUT')\nfiles_output_path_result_final = os.path.join(current_path, 'FILES OUTPUT')\n\n\n\n#Read all files as per list t01 and structure into proper dataframe and exclude all unecessary row \n#Files that need to be read is in sheet number 2 and start reading it from row 6 to avoid messy structure\n\n#t01 \n# df_t01 = pd.read_excel(get_t01_latest,dtype=str,header=5,sheet_name='HEADER_MAIN')\ndf_t01 = pd.read_excel(get_t01_latest,dtype=str,header=5,sheet_name='HEADER_MAIN')\n\n#Read all files as per list t02 and structure into proper dataframe and exclude all unecessary row \n#t02\n# df_t02 = pd.read_excel(get_t01_latest,dtype=str,sheet_name='MSIC2008_MAIN')\ndf_t02 = pd.read_excel(get_t01_latest,dtype=str,sheet_name='MSIC2008_MAIN')\n\n\n# In[9]:\n\n\ndf_t01['NEW_ORDER BY VAR'] = df_t01['NEW_ORDER BY VAR'].astype(int)\ndf_t01_sort = df_t01.sort_values('NEW_ORDER BY VAR')\n\n\n# In[ ]:\n\n\n\n\n\n# In[10]:\n\n\n#Read all files as per list raw and structure into proper dataframe and exclude all unecessary row\n#user to confirm file structure in here. and ile format \n\ndf_raw = read_anything(files_input_path_raw,2)\n\n\n\n\nprint('Reading files success. We are organizing the header according to the files uploaded')\n\n\n\n\n#compare header between t01 against df_raw \n\ndf_raw_col_list = df_raw.columns.to_list()\ndf_old_name_list = df_t01_sort['ORI_EJOB HEADER'].to_list()\ndf_new_name_list = df_t01_sort['NEW_DATASET HEADER'].to_list()\n\n\n\n\ndf_raw_rename = df_raw.rename(columns=dict(zip(df_old_name_list,df_new_name_list)))\ndf_raw_rename_reorg =df_raw_rename.reindex(columns=df_new_name_list)\n\n\n\n\ndf_raw_rename_reorg_check = df_raw_rename_reorg.columns.to_list()\nresult= []\nj = zip(df_raw_rename_reorg_check, df_new_name_list)\nfor x, y in j: \n result.append(x != y)\n \nif any(result):\n print(\"Columns are not renamed and reorganized properly.Please recheck reference file uploaded \")\nelse:\n print(\"Columns are renamed and reorganized successfully according to header references provided.\")\n\n\n\nprint('We are examining MSIC 2008 to fill SECTION_SMPL & SECTION}')\n\n\n\n#get the number of column so to rearrange back column from t02 back to raw main dataframe \nsection_column_number = df_raw_rename_reorg.columns.get_loc('SECTION')\nsection_smpl_column_number = df_raw_rename_reorg.columns.get_loc('SECTION_SMPL')\nmsic2008_column_number = df_raw_rename_reorg.columns.get_loc('MSIC2008')\nmsic2008_smpl_column_number = df_raw_rename_reorg.columns.get_loc('MSIC2008_SMPL')\n\n\n\n\n\n\n\n\n## Add portion to create SECTION_SMPL & SECTION\n\n\n\n\ndf_t02_copy_1 = df_t02.copy()\ndf_t02_copy_2 = df_t02.copy()\n\n\n\n#Create for SECTION_SMPL & MSIC2008_SMPL for join with df raw and fill up SECTION SMPL column \n\n\n\ndf_t02_copy_1 = df_t02_copy_1.rename(columns={'without \\'0\\'':'MSIC2008_SMPL'})\ndf_t02_smpl = df_t02_copy_1[['MSIC2008_SMPL','SECTION']]\ndf_t02_smpl = df_t02_smpl.rename(columns={'SECTION':'SECTION_SMPL'})\n\n\n\noutput_smpl = df_t02_smpl.columns.to_list\nprint(f'success in generating specific column {output_smpl} for t02' )\n\n\n\n#Create for SECTION & MSIC2008 for join with df raw and fill up SECTION SMPL column \n\n\n\n\ndf_t02_copy_2 = df_t02_copy_2.rename(columns={'without \\'0\\'':'MSIC2008'})\ndf_t02_non = df_t02_copy_2[['MSIC2008','SECTION']]\n\n\n\n\noutput_non = df_t02_non.columns.to_list\nprint(f'success in generating specific column {df_t02_non} for t02' )\n\n\n# In[25]:\n\n\n#delete SECTION & SECTION_SMPL in df_raw_rename_reorg\n\ndf_raw_rename_reorg_dropped_section_smpl = df_raw_rename_reorg.drop(['SECTION','SECTION_SMPL'], axis=1)\n\n\n# In[26]:\n\n\ndf_final_raw_data_v1 = df_t02_non.merge(df_raw_rename_reorg_dropped_section_smpl, how ='right', on='MSIC2008')\n\n\n# In[27]:\n\n\ndf_t02_smpl['MSIC2008_SMPL'] = df_t02_smpl['MSIC2008_SMPL'].astype(int)\n\n\n# In[28]:\n\n\ndf_final_raw_data_v2 = df_t02_smpl.merge(df_final_raw_data_v1, how ='right', on='MSIC2008_SMPL')\n\n\n# In[29]:\n\n\ncolumns_to_move = ['SECTION_SMPL','SECTION','MSIC2008','MSIC2008_SMPL']\nnew_indexes = [section_smpl_column_number,section_column_number,msic2008_smpl_column_number,msic2008_column_number,]\n\ncolumns = df_final_raw_data_v2.columns.to_list()\n\n#remove the column in list \nfor column in columns_to_move:\n columns.remove(column)\n \nfor column,index in zip(columns_to_move,new_indexes):\n columns.insert(index,column)\n\ndf_final_raw_data = df_final_raw_data_v2.reindex(columns=columns)\n\n\n# In[30]:\n\n\ndf_final_raw_data.to_csv('testing.csv')\n\n\n# In[31]:\n\n\ndf_temp = df_final_raw_data[['NEWSSID','REGISTERED_NAME','TRADING_NAME']]\ndf = df_final_raw_data.copy()\nyear = df.loc[1,'YEAR']\nquarter = df.loc[1,'QUARTER']\n\n\n# #### MODULE 4 FILL UP STRATA_EMPL COLUMNS ACCORDING TO FILTER OF STRATA_EMPL & SECTION_SMPL \n# \n# IF SECTION_SMPL == C AND F1310 == RANGE(0,5) -> FILL COLUMN STRATA_EMPL= 4\n# IF SECTION_SMPL == C AND F1310 == RANGE(5,75) -> FILL COLUMN STRATA_EMPL= 3\n# IF SECTION_SMPL == C AND F1310 == RANGE(75,201) -> FILL COLUMN STRATA_EMPL= 2\n# IF SECTION_SMPL == C AND F1310 >= 201 -> FILL COLUMN STRATA_EMPL= 1\n# \n# IF SECTION_SMPL != C AND F1310 == RANGE(0,5) -> FILL COLUMN STRATA_EMPL= 4\n# IF SECTION_SMPL != C AND F1310 == RANGE(5,30) -> FILL COLUMN STRATA_EMPL= 3\n# IF SECTION_SMPL != C AND F1310 == RANGE(30,76) -> FILL COLUMN STRATA_EMPL= 2\n# IF SECTION_SMPL != C AND F1310 >= 76 -> FILL COLUMN STRATA_EMPL= 1\n# \n\n# In[32]:\n\n\n#Get dynamic column ending with F1310 \ncolx = [col for col in df_final_raw_data.columns if 'F1310' in col]\n\n\n# In[33]:\n\n\n#update strata_empl value based on filtering of F1310 and SECTION_SMPL\n\ncondition_a_1 = (df_final_raw_data['SECTION_SMPL'] == 'C') & (df_final_raw_data[colx[0]] < 5)\ncondition_a_2 = (df_final_raw_data['SECTION_SMPL'] == 'C') & (df_final_raw_data[colx[0]].isin(range(5,75)))\ncondition_a_3 = (df_final_raw_data['SECTION_SMPL'] == 'C') & (df_final_raw_data[colx[0]].isin(range(75,201)))\ncondition_a_4 = (df_final_raw_data['SECTION_SMPL'] == 'C') & (df_final_raw_data[colx[0]] >= 201)\n\ncondition_list = [\n condition_a_1,\n condition_a_2,\n condition_a_3,\n condition_a_4\n]\ndefault_value = np.nan\nchoices = [4,3,2,1]\ndf_final_raw_data['STRATA_EMPL'] = np.select(condition_list,choices, default=default_value)\n\n\n# In[34]:\n\n\n#update strata_empl value based on filtering of F1310 and SECTION_SMPL\n\ncondition_b_1 = ((df_final_raw_data['SECTION_SMPL'] != 'C') & (df_final_raw_data[colx[0]] < 5)) #& pd.notnull(df_final_raw_data[colx[0]\ncondition_b_2 = ((df_final_raw_data['SECTION_SMPL'] != 'C') & (df_final_raw_data[colx[0]].isin(range(5,30))))\ncondition_b_3 = ((df_final_raw_data['SECTION_SMPL'] != 'C') & (df_final_raw_data[colx[0]].isin(range(30,76))))\ncondition_b_4 = ((df_final_raw_data['SECTION_SMPL'] != 'C') & (df_final_raw_data[colx[0]] >= 76))\n\ncondition_list = [\n condition_b_1,\n condition_b_2,\n condition_b_3,\n condition_b_4\n]\ndefault_value = np.nan\nchoices = [4,3,2,1]\ndf_final_raw_data['STRATA_EMPL'] = np.select(condition_list,choices, default=default_value)\n\n\n# In[ ]:\n\n\n\n\n\n# #### MODULE 5 : \n# ADDING LEADING ZERO TO FRONT SUBSTATE CODE TO COMPLETE 2 DIGITS \n\n# In[35]:\n\n\n# change all column to \ndf_final_raw_data['SUBSTATE_CODE'] = df_final_raw_data['SUBSTATE_CODE'].apply(lambda x: str(int(x)) if pd.notnull(x) and not isinstance(x, str) else '')\n\n# for i, x in enumerate(df_final_raw_data['SUBSTATE_CODE']):\n# if pd.notnull(x):\n# if not isinstance(x, str):\n# df_final_raw_data.loc[i, 'SUBSTATE_CODE'] = str(int(x))\n# else:\n# df_final_raw_data.loc[i, 'SUBSTATE_CODE'] = x\n# else:\n# df_final_raw_data.loc[i, 'SUBSTATE_CODE'] = ''\n \n# isinstance(object, type)\n\n\n# In[36]:\n\n\nchecktypes = df_final_raw_data['SUBSTATE_CODE'].dtype\nprint(f'Column Substate_code changed to dtypes = {checktypes} for the basis of adding leading 0')\n\n\n# In[37]:\n\n\nbefore = df_final_raw_data['SUBSTATE_CODE'].iloc[1]\nprint(f'Check does this meet requirement before changing value this is the unique value list: {before}')\n\n\n# In[38]:\n\n\nfor i, x in enumerate(df_final_raw_data['SUBSTATE_CODE']):\n if x not in ['0','']:\n if len(x) <=2:\n df_final_raw_data.loc[i,'SUBSTATE_CODE']= x.zfill(2)\n\n\n# In[39]:\n\n\nafter = df_final_raw_data['SUBSTATE_CODE'].iloc[1]\nprint(f'Check does this meet requirement after changing value this is the unique value list: {after}')\n\n\n# In[ ]:\n\n\n\n\n\n# ADDING LEADING ZERO TO FRONT NEWSSID TO COMPLETE 12 DIGITS \n\n# In[40]:\n\n\n# # 2 Change flaot to str \n# for i, x in enumerate(df_final_raw_data['NEWSSID']):\n# if pd.notnull(x) and x not in ['0','']:\n# if not isinstance(x,str):\n# df_final_raw_data.loc[i,'NEWSSID'] = str(int(x))\n# else:\n# df_final_raw_data.loc[i,'NEWSSID'] = x\n# else:\n# df_final_raw_data.loc[i, 'SUBSTATE_CODE'] = '' \n\ndf_final_raw_data['NEWSSID'] = df_final_raw_data['NEWSSID'].apply(lambda x: str(int(x)) if pd.notnull(x) and not isinstance(x, str) else '')\n\n\n# In[41]:\n\n\nchecktypes = df_final_raw_data['NEWSSID'].dtype\nprint(f'Column NEWSSID changed to dtypes = {checktypes} for the basis of adding leading 0')\n\n\n# In[42]:\n\n\nbefore = df_final_raw_data['NEWSSID'].iloc[1]\nprint(f'Check for NEWSSID does this meet requirement before changing value this is the unique value list: {before}')\n\n\n# In[43]:\n\n\nfor i, x in enumerate(df_final_raw_data['NEWSSID']):\n if x not in ['','0']:\n if len(x) <= 12 :\n df_final_raw_data.loc[i,'NEWSSID'] = x.zfill(12)\n\n\n# In[44]:\n\n\nafter = df_final_raw_data['NEWSSID'].iloc[1]\n\nprint(f'Check for NEWSSID does this meet requirement before changing value this is the unique value list: {after}')\n\n\n# In[ ]:\n\n\n\n\n\n# ADDING LEADING ZERO TO FRONT MSIC2008_SMPL TO COMPLETE 5 DIGITS \n\n# In[45]:\n\n\ndf_final_raw_data['MSIC2008_SMPL'] = df_final_raw_data['MSIC2008_SMPL'].apply(lambda x: str(int(x)) if pd.notnull(x) and not isinstance(x, str) else '')\nchecktypes = df_final_raw_data['MSIC2008_SMPL'].dtype\nprint(f'Column MSIC2008_SMPL changed to dtypes = {checktypes} for the basis of adding leading 0')\n\n\n# In[46]:\n\n\nbefore = df_final_raw_data['MSIC2008_SMPL'].iloc[1]\nprint(f'Check for MSIC2008_SMPL does this meet requirement before changing value this is the unique value list: {before}')\n\n\n# In[47]:\n\n\nfor i, x in enumerate(df_final_raw_data['MSIC2008_SMPL']):\n if x not in ['','0']:\n if len(x) <= 5 :\n df_final_raw_data.loc[i,'MSIC2008_SMPL'] = x.zfill(12)\n\n\n# In[48]:\n\n\nafter = df_final_raw_data['MSIC2008_SMPL'].iloc[1]\n\nprint(f'Check for MSIC2008_SMPL does this meet requirement before changing value this is the unique value list: {after}')\n\n\n# In[ ]:\n\n\n\n\n\n# ADDING LEADING ZERO TO FRONT MSIC2008 TO COMPLETE 5 DIGITS \n\n# In[49]:\n\n\ndf_final_raw_data['MSIC2008'] = df_final_raw_data['MSIC2008'].apply(lambda x: str(int(x)) if pd.notnull(x) and not isinstance(x, str) else '')\nchecktypes = df_final_raw_data['MSIC2008'].dtype\nprint(f'Column MSIC2008 changed to dtypes = {checktypes} for the basis of adding leading 0')\n\n\n# In[50]:\n\n\nbefore = df_final_raw_data['MSIC2008'].iloc[1]\nprint(f'Check for MSIC2008 does this meet requirement before changing value this is the unique value list: {before}')\n\n\n# In[51]:\n\n\nfor i, x in enumerate(df_final_raw_data['MSIC2008']):\n if x not in ['','0']:\n if len(x) <= 5 :\n df_final_raw_data.loc[i,'MSIC2008'] = x.zfill(12)\n\n\n# In[52]:\n\n\nafter = df_final_raw_data['MSIC2008'].iloc[1]\n\nprint(f'Check for one of the value from MSIC2008, does this meet requirement before changing value this is the unique value list: {after}')\n\n\n# In[ ]:\n\n\n\n\n\n# ADDING LEADING ZERO TO FRONT STATE_CODE TO COMPLETE 5 DIGITS \n\n# In[53]:\n\n\ndf_final_raw_data['STATE_CODE'] = df_final_raw_data['STATE_CODE'].apply(lambda x: str(int(x)) if pd.notnull(x) and not isinstance(x, str) else '')\nchecktypes = df_final_raw_data['STATE_CODE'].dtype\nprint(f'Column STATE_CODE changed to dtypes = {checktypes} for the basis of adding leading 0')\n\n\n# In[54]:\n\n\nbefore = df_final_raw_data['STATE_CODE'].iloc[1]\nprint(f'Check for STATE_CODE does this meet requirement before changing value this is the unique value list: {before}')\n\n\n# In[55]:\n\n\nfor i, x in enumerate(df_final_raw_data['STATE_CODE']):\n if x not in ['','0']:\n if len(x) <= 5 :\n df_final_raw_data.loc[i,'STATE_CODE'] = x.zfill(2)\n\n\n# In[56]:\n\n\nafter = df_final_raw_data['STATE_CODE'].iloc[1]\n\nprint(f'Check for one of the value from STATE_CODE, does this meet requirement before changing value this is the unique value list: {after}')\n\n\n# In[ ]:\n\n\n\n\n\n# ### Module 7 : Summation all category (1-9) for summation of total salaries & wages (Q=L+M+N+O+P)\n\n# In[57]:\n\n\n#Get the starting index of column F0101 in col \ncoly = [col for col in df_final_raw_data.columns if 'F0101' in col]\nfirst_index = df_final_raw_data.columns.get_loc(coly[0])\n\n\n# In[58]:\n\n\nvab_list_mod_8 = [ 'L', 'M', 'N', 'O', 'P','Q']\n#Select column name to manipulate from master dataframe \nselection_col_2 = []\nfor x in df_final_raw_data.columns[first_index:]:\n if x[:1] in vab_list_mod_8:\n selection_col_2.append(x)\n\n\n# In[59]:\n\n\n#assign selection for module 7 into \n\ndf_mod7_1=df_final_raw_data[selection_col_2]\n\n\n# In[60]:\n\n\n#wrangle the data \n#1. List all column from filtered to be appended in list_j\nlist_j = []\nfor x in df_mod7_1.columns:\n y = x[:6]\n list_j.append(y)\n#2. Get the unique list \nlist_j_unique = list(set(list_j)) \n\n#3. Get the unique sorted alphabetically \nsort_alph = ['L','M','N','O','P','Q']\n#Sort the list from unique list into separated set of list to make it easier during loop\n# sample output a = ['L23204', 'M23204', 'N23204', 'O23204', 'P23204', 'Q23204']\nlist_j_sort = sorted(list_j_unique,key=lambda x:(len(x),x[0]))\n\n\nprint(f'{list_j_sort} are the unique partial front string to be re arranged before filtering from main dataframe process')\n\n#make a dictionary from sortation filter so we can filter based on variables \n\ngroup_dict = {}\nfor col_name in list_j_sort:\n end = col_name[-2:]\n#if column name existing int group_dictionary, then append in created list\n if end in group_dict:\n group_dict[end].append(col_name)\n \n#if dont have , then create a new one. \n else: \n group_dict[end] = [col_name]\n\ndynamic_keys = sorted(group_dict.keys())\n\nprint(f'{dynamic_keys} are unique partial string sorted by quarters ascending ')\n\n\n# In[61]:\n\n\n# #Strategy \n# Loop through column_no_q and column_w_q to filter columns based on the conditions.\n# Change the data type of columns in df[sum_this] and df[paste_here] to numeric and fill any missing values with 0.\n# Calculate the sum of each row in df[sum_this] and assign the result to sum_val.\n# Reshape sum_val to a column vector and assign it to df_output[paste_here].\n# Change the data type of columns in df_output[sum_this] and df_output[paste_here] to numeric and fill any missing values with 0.\n# Calculate the sum before the arithmetic expression for df_output[paste_here] and df_output[sum_this] using sum(axis=0) and store them in result_mod7_before and input_mod7_before, respectively.\n# Calculate the sum after the amendment for df_output[paste_here] and df_output[sum_this] using sum(axis=0) and store them in result_mod7_after and input_mod7_after, respectively.\n# Compare result_mod7_after[0] with input_mod7_after to check if the results match and print the corresponding message.\n\n\n# In[62]:\n\n\n# a function to filter data by partial string match and sum based on conditional \ndef process_dataframe(df,group_num,grouping_1,df_output):\n sum_this = []\n paste_here = []\n listx = group_dict[group_num]\n exclude_q = [x for x in listx if 'Q' not in x]\n q_only = [x for x in listx if 'Q' in x]\n # get the list of column available in df to separate \n column_no_q = [x for x in df if any(q in x for q in exclude_q)]\n column_w_q = [x for x in df if any(q in x for q in q_only)]\n \n #Get the list of column that is in list \n #The sample of dictionary as follows : - \n\n # {'04': ['L23204', 'M23204', 'N23204', 'O23204', 'P23204', 'Q23204'],\n # '06': ['L23206', 'M23206', 'N23206', 'O23206', 'P23206', 'Q23206'],\n # '05': ['L23205', 'M23205', 'N23205', 'O23205', 'P23205', 'Q23205']}\n\n # empty frame to insert value for each function run temporary to paste value in df main \n\n #loop to filter from df\n for x in column_no_q:\n for y in group_dict[group_num]:\n if x.endswith(grouping_1) and y in x:\n sum_this.append(x)\n\n for x in column_w_q:\n for y in group_dict[group_num]:\n if x.endswith(grouping_1) and y in x:\n paste_here.append(x)\n \n #change datatype from string to int and sum value from list of sumthis to get the overall value \n df[sum_this] = df[sum_this].apply(pd.to_numeric, errors='coerce')\n df[sum_this] = df[sum_this].fillna(0).astype(int)\n df[paste_here] = df[paste_here].apply(pd.to_numeric, errors='coerce')\n df[paste_here] = df[paste_here].fillna(0).astype(int)\n df_output[sum_this] = df_output[sum_this].apply(pd.to_numeric, errors='coerce')\n df_output[sum_this] = df_output[sum_this].fillna(0).astype(int)\n df_output[paste_here] = df_output[paste_here].apply(pd.to_numeric, errors='coerce')\n df_output[paste_here] = df_output[paste_here].fillna(0).astype(int)\n\n #get the aggreagate of all column in sum_this\n sum_val = df[sum_this].sum(axis=1)\n #paste the aggregate in column QXXX and ending with group_num in df_final_raw as final value \n df_output[paste_here] = sum_val.values.reshape(-1, 1)\n\n #get the column Q in 01 and sum the value column first from main dataframe \n\n #change the dtyps for section affected only from df main so we can sum this \n\n #check & test \n #Get the sum before arimethic expression for df_main as initial value \n result_mod7_before = df_output[paste_here].sum(axis=0)\n input_mod7_before = df_output[sum_this].sum(axis=0)\n input_mod7_before = input_mod7_before.sum()\n \n #get the sum of column after in df_mod7 and after ammendment made in \n result_mod7_after = df_output[paste_here].sum(axis=0)\n input_mod7_after = df_output[sum_this].sum(axis=0)\n input_mod7_after = input_mod7_after.sum()\n\n if result_mod7_after[0] == input_mod7_after:\n print(f'{paste_here} successfully aggregated & match with source value which initially {result_mod7_before[0]} turned to {result_mod7_after[0]}')\n else:\n print(f'{paste_here} warning, result and source do not match, recheck data')\n\n\n# In[63]:\n\n\n#group num is based on dynamic_keys = ['04', '05', '06'] position which is dunamically based on quarter.\n# sum the value based on pulled dataframe and paste the value into df_main into as ouput \ngrouping_1 = ('1','2','3','4','5','6','7','8','9','0')\ngroup_num = dynamic_keys[0]\ndf = df_mod7_1\ndf_output = df_final_raw_data\n\nfor x in grouping_1:\n process_dataframe(df,group_num,x,df_output)\n\n\n# In[64]:\n\n\n#group num is based on dynamic_keys = ['04', '05', '06'] position which is dunamically based on quarter.\n# sum the value based on pulled dataframe and paste the value into df_main into as ouput \ngrouping_1 = ('1','2','3','4','5','6','7','8','9','0')\ngroup_num = dynamic_keys[1]\ndf = df_mod7_1\ndf_output = df_final_raw_data\n\nfor x in grouping_1:\n process_dataframe(df,group_num,x,df_output)\n\n\n# In[65]:\n\n\n#group num is based on dynamic_keys = ['04', '05', '06'] position which is dunamically based on quarter.\n# sum the value based on pulled dataframe and paste the value into df_main into as ouput \ngrouping_1 = ('1','2','3','4','5','6','7','8','9','0')\ngroup_num = dynamic_keys[2]\ndf = df_mod7_1\ndf_output = df_final_raw_data\n\nfor x in grouping_1:\n process_dataframe(df,group_num,x,df_output)\n\n\n# In[ ]:\n\n\n\n\n\n# ### Module 8 : Summation all category (1-9) for summation of total separation (X=D+E+F)\n\n# In[66]:\n\n\nvab_list_mod_9 = ['D','E','F','X']\n#Select column name to manipulate from master dataframe \nselection_col_3 = []\nfor x in df_final_raw_data.columns[first_index:]:\n if x[:1] in vab_list_mod_9:\n selection_col_3.append(x)\n\n\n# In[67]:\n\n\n#filter the column out from main_df \ndf_vabs_mod9= df_final_raw_data[selection_col_3]\n\n#wrangle the data \n#1. List all column from filtered to be appended in list_j\nlist_j = []\nfor x in df_vabs_mod9.columns:\n y = x[:6]\n list_j.append(y)\n#2. Get the unique list \nlist_j_unique = list(set(list_j)) \n\n#3. Get the unique sorted alphabetically \nsort_alph = ['D','E','F','X']\n#Sort the list from unique list into separated set of list to make it easier during loop\n# sample output a = ['L23204', 'M23204', 'N23204', 'O23204', 'P23204', 'Q23204']\nlist_j_sort = sorted(list_j_unique,key=lambda x:(len(x),x[0]))\n\n\nprint(f'{list_j_sort} are the unique partial front string to be re arranged before filtering from main dataframe process')\n\n#make a dictionary from sortation filter so we can filter based on variables \n\ngroup_dict = {}\nfor col_name in list_j_sort:\n end = col_name[-2:]\n#if column name existing int group_dictionary, then append in created list\n if end in group_dict:\n group_dict[end].append(col_name)\n \n#if dont have , then create a new one. \n else: \n group_dict[end] = [col_name]\n\ndynamic_keys = sorted(group_dict.keys())\n\nprint(f'{dynamic_keys} are unique partial string sorted by quarters ascending ')\n\n\n# In[68]:\n\n\n# a function to filter data by partial string match and sum based on conditional \ndef process_dataframe_2(df,group_num,grouping_1,df_output):\n sum_this = []\n paste_here = []\n listx = group_dict[group_num]\n exclude_q = [x for x in listx if 'X' not in x]\n q_only = [x for x in listx if 'X' in x]\n # get the list of column available in df to separate \n column_no_q = [x for x in df if any(q in x for q in exclude_q)]\n column_w_q = [x for x in df if any(q in x for q in q_only)]\n \n #Get the list of column that is in list \n #The sample of dictionary as follows : - \n\n # {'04': ['L23204', 'M23204', 'N23204', 'O23204', 'P23204', 'Q23204'],\n # '06': ['L23206', 'M23206', 'N23206', 'O23206', 'P23206', 'Q23206'],\n # '05': ['L23205', 'M23205', 'N23205', 'O23205', 'P23205', 'Q23205']}\n\n # empty frame to insert value for each function run temporary to paste value in df main \n\n #loop to filter from df\n for x in column_no_q:\n for y in group_dict[group_num]:\n if x.endswith(grouping_1) and y in x:\n sum_this.append(x)\n\n for x in column_w_q:\n for y in group_dict[group_num]:\n if x.endswith(grouping_1) and y in x:\n paste_here.append(x)\n \n #change datatype from string to int and sum value from list of sumthis to get the overall value \n df[sum_this] = df[sum_this].apply(pd.to_numeric, errors='coerce')\n df[sum_this] = df[sum_this].fillna(0).astype(int)\n df[paste_here] = df[paste_here].apply(pd.to_numeric, errors='coerce')\n df[paste_here] = df[paste_here].fillna(0).astype(int)\n df_output[sum_this] = df_output[sum_this].apply(pd.to_numeric, errors='coerce')\n df_output[sum_this] = df_output[sum_this].fillna(0).astype(int)\n df_output[paste_here] = df_output[paste_here].apply(pd.to_numeric, errors='coerce')\n df_output[paste_here] = df_output[paste_here].fillna(0).astype(int)\n\n #get the aggreagate of all column in sum_this\n sum_val = df[sum_this].sum(axis=1)\n \n #paste the aggregate in column QXXX and ending with group_num in df_final_raw as final value \n df_output[paste_here] = sum_val.values.reshape(-1, 1)\n \n# sum_val_df = pd.DataFrame({col: sum_val for col in paste_here})\n\n# df_output[paste_here] = sum_val_df\n\n #get the column Q in 01 and sum the value column first from main dataframe \n\n #change the dtyps for section affected only from df main so we can sum this \n\n #check & test \n #Get the sum before arimethic expression for df_main as initial value \n result_mod7_before = df_output[paste_here].sum(axis=0)\n input_mod7_before = df_output[sum_this].sum(axis=0)\n input_mod7_before = input_mod7_before.sum()\n \n #get the sum of column after in df_mod7 and after ammendment made in \n result_mod7_after = df_output[paste_here].sum(axis=0)\n input_mod7_after = df_output[sum_this].sum(axis=0)\n input_mod7_after = input_mod7_after.sum()\n\n if result_mod7_after[0] == input_mod7_after:\n print(f'{paste_here} successfully aggregated & match with source value which initially {result_mod7_before[0]} turned to {result_mod7_after[0]}')\n else:\n print(f'{paste_here} warning, result and source do not match, recheck data')\n\n\n# In[69]:\n\n\n#group num is based on dynamic_keys = ['04', '05', '06'] position which is dunamically based on quarter.\n# sum the value based on pulled dataframe and paste the value into df_main into as ouput \ngrouping_1 = ('1','2','3','4','5','6','7','8','9','0')\ngroup_num = dynamic_keys[0]\ndf = df_vabs_mod9\ndf_output = df_final_raw_data\n\nfor x in grouping_1:\n process_dataframe_2(df,group_num,x,df_output)\n\n\n# In[70]:\n\n\n#group num is based on dynamic_keys = ['04', '05', '06'] position which is dunamically based on quarter.\n# sum the value based on pulled dataframe and paste the value into df_main into as ouput \ngrouping_1 = ('1','2','3','4','5','6','7','8','9','0')\ngroup_num = dynamic_keys[1]\ndf = df_vabs_mod9\ndf_output = df_final_raw_data\n\nfor x in grouping_1:\n process_dataframe_2(df,group_num,x,df_output)\n\n\n# In[71]:\n\n\n#group num is based on dynamic_keys = ['04', '05', '06'] position which is dunamically based on quarter.\n# sum the value based on pulled dataframe and paste the value into df_main into as ouput \ngrouping_1 = ('1','2','3','4','5','6','7','8','9','0')\ngroup_num = dynamic_keys[2]\ndf = df_vabs_mod9\ndf_output = df_final_raw_data\n\nfor x in grouping_1:\n process_dataframe_2(df,group_num,x,df_output)\n\n\n# In[ ]:\n\n\n\n\n\n# ### Module 9. Summation all category (1-9) for variable A, B, C, D, E, F, G, H, I, J, L, M, N, O, P, R & X \n\n# In[72]:\n\n\n#Plan \n# Refer based on upload files header \n# identify starting and ending of soalan baru bertambah \n# Filter out column for variable in list \n\n# Variables involved A, B, C, D, E, F, G, H, I, J, L, M, N, O, P, R & X\n# Range Criteria (SUM of 1-9) = 10 \n\n\n# from main df -> extract to variable that involve only (df_vabs)\n# from df_vabs run the condition required and replace sum value into column 10 \n# from df_vabs extract only column 10 into df_sum\n# replace the value for all rows that have the same column name through looping, dont merge \n\n\n\n\n# In[73]:\n\n\n#Strategy New \n# Filter affected column based on alphabet inclusive of ammended column X & Q which in module 7 & 8 \n# Filter partial string that is unique \n\n#1. Filter list of column based on variables first \nvab_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'O', 'P','Q', 'R ','X']\nselection_col = ['NEWSSID']\nfor x in df_final_raw_data.columns[first_index:]:\n\n if x[:1] in vab_list:\n selection_col.append(x)\n\n# print(f'This are columns selected {selection_col} for aggreagation process')\n\n\n\ndf_vabs = df_final_raw_data[selection_col]\n\n#1. List all column from filtered to be appended in list_j\nlist_j = []\nfor x in df_vabs.columns:\n y = x[:6]\n list_j.append(y)\n \n#2. Get the unique list \nlist_j_unique = list(set(list_j)) \n\n#3. Get the unique sorted alphabetically \nsort_alph = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L', 'M', 'N', 'O', 'P','Q', 'R ','X']\n#Sort the list from unique list into separated set of list to make it easier during loop\n# sample output a = ['L23204', 'M23204', 'N23204', 'O23204', 'P23204', 'Q23204']\nlist_j_sort = sorted(list_j_unique,key=lambda x:(len(x),x[0]))\n\n\nprint(f'{list_j_sort} are the unique partial front string to be re arranged before filtering from main dataframe process')\n\n#make a dictionary from sortation filter so we can filter based on variables \n\ngroup_dict = {}\nfor col_name in list_j_sort:\n end = col_name[-2:]\n#if column name existing int group_dictionary, then append in created list\n if end in group_dict:\n group_dict[end].append(col_name)\n \n#if dont have , then create a new one. \n else: \n group_dict[end] = [col_name]\n\ndynamic_keys = sorted(group_dict.keys())\n\nprint(f'{dynamic_keys} are unique partial string sorted by quarters ascending ')\n\n\n# In[74]:\n\n\n#From unique dynamic keys ['04', '05', '06', 'SI'] are unique partial string sorted by quarters ascending \n#dynamic_keys\n#From ['A23204', 'A23206', 'A23205', 'B23205', 'B23206', 'B23204', 'C23205', 'C23206', 'C23204', 'D23206', 'D23205', 'D23204', 'E23206', 'E23204', 'E23205', 'F23204', 'F23205', 'F23206', 'G23205', 'G23206', 'G23204', 'H23204', 'H23205', 'H23206', 'I23206', 'I23204', 'I23205', 'J23205', 'J23204', 'J23206', 'L23206', 'L23204', 'L23205', 'M23205', 'M23206', 'M23204', 'NEWSSI', 'N23204', 'N23205', 'N23206', 'O23206', 'O23204', 'O23205', 'P23204', 'P23205', 'P23206', 'Q23206', 'Q23204', 'Q23205', 'X23205', 'X23206', 'X23204'] are the unique partial front string to be re arranged before filtering from main dataframe process\n#group_dict\n\n#Loop based on groupdict[0 to max index]\n# filter column ending with 01 to 09 = col_sum_0109\n# filter column ending with 10 = col_paste_here_10 \n# Axxx04_xxxx01 to Axxx04_xxxx09 .sum(axis=1) = sum_val \n# sum_val\n\n\n\n# In[75]:\n\n\n# Function\ndef aggregate_data(df, df_output, group_num):\n z = [x for x in df if any(q in x for q in y)]\n ending_to_sum = ('1', '2', '3', '4', '5', '6', '7', '8', '9')\n ending_sum = ('0')\n\n listx = group_dict[group_num]\n total_items = len(listx)\n\n #from listx\n listx = group_dict[group_num]\n total_items = len(listx)\n # now we want to loop according to sequence A (01-09).sum()\n for n in range(total_items):\n listx = group_dict[group_num][n]\n for x in listx:\n ending_to_sum_col = []\n ending_sum_col = []\n # tosum_filter_list = [value for value in z if any(value.startswith(prefix) for prefix in listx) and value.endswith(ending_to_sum)]\n tosum_filter_list = [value for value in z if value.startswith(listx) and value.endswith(ending_to_sum)]\n sum_column = [value for value in z if value.startswith(listx) and value.endswith(ending_sum)]\n\n # append in column temporary for we sum it in main_df \n ending_to_sum_col.append(tosum_filter_list)\n ending_sum_col.append(sum_column)\n\n # ending_to_sum_col = ending_to_sum_col[0]\n # ending_sum_col = ending_sum_col[0]\n ending_to_sum_col = ending_to_sum_col[0] if ending_to_sum_col else None\n ending_sum_col = ending_sum_col[0] if ending_sum_col else None\n # in the loop according to list listx A until X we want to get sum and paste the value directly main_df or output_df \n df_output[ending_to_sum_col] = df_output[ending_to_sum_col].apply(pd.to_numeric, errors='coerce')\n df_output[ending_to_sum_col] = df_output[ending_to_sum_col].fillna(0).astype(int)\n\n df_output[ending_sum_col] = df_output[ending_sum_col].apply(pd.to_numeric, errors='coerce')\n df_output[ending_sum_col] = df_output[ending_sum_col].fillna(0).astype(int)\n\n #recheck before sum \n\n result_mod7_before = df_output[ending_sum_col].sum(axis=0)\n input_mod7_before = df_output[ending_to_sum_col].sum(axis=0)\n input_mod7_before = input_mod7_before.sum()\n\n sum_1to9 = df_output[ending_to_sum_col].sum(axis=1)\n df_output[ending_sum_col] = sum_1to9.values.reshape(-1, 1)\n # recheck main_df after sum\n\n result_mod7_after = df_output[ending_sum_col].sum(axis=0)\n input_mod7_after = df_output[ending_to_sum_col].sum(axis=0)\n input_mod7_after = input_mod7_after.sum()\n\n if result_mod7_after[0] == input_mod7_after:\n print(f'{ending_sum_col} successfully aggregated & match with source value which initially source : {result_mod7_before[0]} from {input_mod7_before} & result : {result_mod7_after[0]} from {input_mod7_after}')\n else:\n print(f'{ending_sum_col} warning, result and source do not match, recheck data')\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[76]:\n\n\n# variables list \ndf = df_vabs\ndf_output = df_final_raw_data\ngroup_num = dynamic_keys[0]\naggregate_data(df, df_output, group_num)\n\n\n# In[77]:\n\n\n# variables list \ndf = df_vabs\ndf_output = df_final_raw_data\ngroup_num = dynamic_keys[1]\naggregate_data(df, df_output, group_num)\n\n\n# In[78]:\n\n\n# variables list \ndf = df_vabs\ndf_output = df_final_raw_data\ngroup_num = dynamic_keys[2]\naggregate_data(df, df_output, group_num)\n\n\n# In[79]:\n\n\nQ = str(df_final_raw_data['QUARTER'].unique()[0])\nY = str(df_final_raw_data['YEAR'].unique()[0])\n\n\n# In[80]:\n\n\nengine = create_engine('postgresql+psycopg2://admin:admin@10.251.49.51:5432/postgres')\nconnection = engine.connect()\nprint(connection)\n\n\n# In[81]:\n\n\nschema='production_micro_frd_sgtgu_quarterly'\n\n\n# In[82]:\n\n\n# df_final_raw_data.to_excel(files_output_path_result_final+'FRD_'+Q+'_'+Y'.xlsx')\ndf_final_raw_data.to_sql(f'FRDQ{Q}Y{Y}',con=engine,schema=schema,if_exists='replace',index=False)\n\n\n# In[83]:\n\n\nprint(f'FRDQ{Q}Y{Y} Ingested into Database')\n\n\n# In[84]:\n\n\nend_time = time.time() # get the end time \ntime_running = end_time - start_time # Calculate the time difference\nminutes = time_running / 60 # Convert time_running to minutes\nprint(f'it took {minutes} minutes to run the whole process')\n\n\n# In[85]:\n\n\n#to remove data directly\ndef clear_garbage(path):\n file_avaialble = [x for x in os.listdir(path)]\n\n try:\n for x in file_avaialble:\n os.remove(path+'/'+x)\n y = str(x).upper()\n print(f'{y} excess files from processing has been relocated, contact vendor if you require the files for quality check ')\n except Exception as e:\n print(f'Error relocating the files: {path} - {e}')\n\n\n#move data to clear \ndef mover(path, destination_folder):\n files_available = [x for x in os.listdir(path)]\n\n try:\n for file_name in files_available:\n source_file = os.path.join(path, file_name)\n destination_file = os.path.join(destination_folder, file_name)\n shutil.move(source_file, destination_file)\n y = str(file_name).upper()\n print(f'{y} excess files from processing has been relocated to {destination_folder}. Contact the vendor if you require the files for quality check.')\n except Exception as e:\n print(f'Error relocating the files: {path} - {e}')\n\n\n# In[86]:\n\n\npath = files_input_path_t01\ndestination_folder = bin_path\nmover(path, destination_folder)\n\npath = files_input_path_raw\ndestination_folder = bin_path\nmover(path, destination_folder)\n\n\n\npath = files_output_path_result\ndestination_folder = bin_path\nmover(path, destination_folder)\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"BobbyAxelrods/dosm_cleaning_etl","sub_path":"SGTGU_QUARTERLY/SGTGU_QUATERLY.py","file_name":"SGTGU_QUATERLY.py","file_ext":"py","file_size_in_byte":39886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"36053657967","text":"import logging\nfrom enum import Enum\n\nfrom django.db import models, transaction\nfrom django.db.models.signals import m2m_changed\nfrom django.dispatch import receiver\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.utils.html import escape\nfrom django.utils.safestring import mark_safe\n\nfrom .map import Map\nfrom .match_tag import MatchTag\nfrom .mixins import LockableModelMixin, RandomManagerMixin\nfrom .round import Round\nfrom .user import User\n\n\nlogger = logging.getLogger(__name__)\n\n\n# todo: structure for separate ladder types\nclass Match(models.Model, LockableModelMixin, RandomManagerMixin):\n \"\"\"Represents a match between 2 bots. Usually this is within the context of a round, but doesn't have to be.\"\"\"\n\n map = models.ForeignKey(Map, on_delete=models.PROTECT)\n created = models.DateTimeField(auto_now_add=True, db_index=True)\n # todo: the functionality of the started and first_started fields does not appear to be fully implemented\n started = models.DateTimeField(blank=True, null=True, editable=False, db_index=True)\n first_started = models.DateTimeField(blank=True, null=True, editable=False, db_index=True)\n \"\"\"The first time this match started. Different from the started field when multiple runs are attempted.\"\"\"\n assigned_to = models.ForeignKey(\n User, on_delete=models.PROTECT, blank=True, null=True, related_name=\"assigned_matches\"\n )\n round = models.ForeignKey(Round, on_delete=models.CASCADE, blank=True, null=True)\n requested_by = models.ForeignKey(\n User, on_delete=models.SET_NULL, blank=True, null=True, related_name=\"requested_matches\"\n )\n require_trusted_arenaclient = models.BooleanField(default=True)\n \"\"\"Whether this match should require it be run on a trusted arena client\"\"\"\n tags = models.ManyToManyField(MatchTag, blank=True)\n\n def __str__(self):\n return self.id.__str__()\n\n @property\n def participant1(self):\n return self.matchparticipation_set.get(participant_number=1)\n\n @property\n def participant2(self):\n return self.matchparticipation_set.get(participant_number=2)\n\n @property\n def is_requested(self):\n return self.requested_by is not None\n\n @property\n def status(self):\n from .result import Result # avoid circular import\n\n try:\n finished = self.result is not None\n except Result.DoesNotExist:\n finished = False\n if finished:\n return \"Finished\"\n elif self.started:\n return \"Started\"\n else:\n return \"Queued\"\n\n @staticmethod\n def create(\n round,\n map,\n bot1,\n bot2,\n requested_by=None,\n bot1_use_data=None,\n bot1_update_data=None,\n bot2_use_data=None,\n bot2_update_data=None,\n require_trusted_arenaclient=True,\n ):\n with transaction.atomic():\n if bot1_use_data is None:\n bot1_use_data = bot1.bot_data_enabled\n if bot1_update_data is None:\n bot1_update_data = bot1.bot_data_enabled\n if bot2_use_data is None:\n bot2_use_data = bot2.bot_data_enabled\n if bot2_update_data is None:\n bot2_update_data = bot2.bot_data_enabled\n match = Match.objects.create(\n map=map, round=round, requested_by=requested_by, require_trusted_arenaclient=require_trusted_arenaclient\n )\n # create match participations\n from .match_participation import MatchParticipation # avoid circular reference\n\n MatchParticipation.objects.create(\n match=match,\n participant_number=1,\n bot=bot1,\n use_bot_data=bot1_use_data,\n update_bot_data=bot1_update_data,\n )\n MatchParticipation.objects.create(\n match=match,\n participant_number=2,\n bot=bot2,\n use_bot_data=bot2_use_data,\n update_bot_data=bot2_update_data,\n )\n\n return match\n\n class CancelResult(Enum):\n SUCCESS = 1\n MATCH_DOES_NOT_EXIST = 3\n RESULT_ALREADY_EXISTS = 2\n\n def cancel(self, requesting_user):\n from . import Result\n\n with transaction.atomic():\n try:\n # do this to lock the record\n # select_related() for the round data\n match = Match.objects.select_related(\"round\").select_for_update(of=(\"self\",)).get(pk=self.id)\n except Match.DoesNotExist:\n return Match.CancelResult.MATCH_DOES_NOT_EXIST # should basically not happen, but just in case\n\n if Result.objects.filter(match=match).count() > 0:\n return Match.CancelResult.RESULT_ALREADY_EXISTS\n\n Result.objects.create(match=match, type=\"MatchCancelled\", game_steps=0, submitted_by=requesting_user)\n\n if not match.started:\n now = timezone.now()\n match.started = now\n match.first_started = now\n match.save()\n\n if match.round is not None:\n match.round.update_if_completed()\n\n def get_absolute_url(self):\n return reverse(\"match\", kwargs={\"pk\": self.pk})\n\n def as_html_link(self):\n return mark_safe(f'{escape(self.__str__())}')\n\n\n@receiver(m2m_changed, sender=Match.tags.through)\ndef delete_orphan_match_tags(sender, **kwargs):\n # when something is removed from the m2m:\n if kwargs[\"action\"] == \"post_remove\":\n # select removed tags and check if they are not linked to any Match, and delete it\n for mt in MatchTag.objects.filter(pk__in=kwargs[\"pk_set\"]):\n if not mt.match_set.all():\n mt.delete()\n","repo_name":"aiarena/aiarena-web","sub_path":"aiarena/core/models/match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":5862,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"8"} +{"seq_id":"25248347527","text":"# coding=utf-8\n'''\nCreated on 2016å¹?11æœ?8æ—?\n\n@author: Administrator\n'''\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n\n def levelOrderBottom(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n ans = []\n if root:\n from Queue import Queue\n q = Queue()\n q.put((root, 0))\n current_level = -1\n while not q.empty():\n p, level = q.get()\n if level > current_level:\n ans.append([])\n current_level = level\n ans[level].append(p.val)\n if p.left:\n q.put((p.left, level + 1))\n if p.right:\n q.put((p.right, level + 1))\n return ans[::-1]\n\n","repo_name":"doraemon1293/Leetcode","sub_path":"archive/107BinaryTreeLevelOrderTraversalII.py","file_name":"107BinaryTreeLevelOrderTraversalII.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"70216965382","text":"from matrixgroups import a4group, d10group, d6group\n\n\ndef get_centralizer_str_from_matrix(centralizer):\n if centralizer == d6group.centralizer():\n return \"D6\"\n elif centralizer == d10group.centralizer():\n return \"D10\"\n elif centralizer == a4group.centralizer():\n return \"A4\"\n else:\n raise ValueError(\"Centralizer is not A4, D10, or D6\")\n\n\ndef get_centralizer_from_str(centralizer_str):\n centralizer_str = centralizer_str.upper()\n\n if centralizer_str == \"A4\":\n return a4group.centralizer()\n elif centralizer_str == \"D10\":\n return d10group.centralizer()\n elif centralizer_str == \"D6\":\n return d6group.centralizer()\n else:\n raise ValueError(\"Centralizer String is not A4, D10, or D6\")\n\n\ndef is_centralizer(matrix):\n if matrix in [a4group.centralizer(), d10group.centralizer(), d6group.centralizer()]:\n return True\n\n return False\n","repo_name":"RochX/virus-research-python","sub_path":"matrixgroups/centralizers.py","file_name":"centralizers.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"37182354895","text":"#heading = \"Python: An Introduction, and Python: Advanced\"\n#\n#header, _, subheader = heading.partion(': ')\n#print(header)\n#print(subheader)\n#\n\n\ntags = 'python,coding,programming,development'\nlist_of_tags = tags.split(',')\nprint(list_of_tags)\n #convets to a single list\n #output is a collection\n\nlist_of_tags = tags.split()\nprint(list_of_tags)\n #converts string to list of strings\n\nheading = \"Python: An Introduction, and Python: Advanced\"\n\nheading_list = heading.split(': ')\n\nprint(heading_list)\n#partition returns a tuple and split returns a list\n","repo_name":"opt22/python","sub_path":"excercises/split-str.py","file_name":"split-str.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"25800405466","text":"'''\r\nProgram converts values of Celsius temperatures to Fahrenheit\r\nAuthor: Chloe Moore\r\nClass: SDEV 140-26J\r\nModule: 1\r\nEx: 1\r\n'''\r\n\r\n# 1) Initialization\r\n\r\nc = 0\r\nf = 0\r\nstatement = \"\"\r\n\r\n# 2) get data\r\n\r\nc = float(input(\"Enter the temperature in Celsius: \"))\r\n# c = int(c)\r\n\r\n#3) proccess data - do all the calculations\r\n\r\nf = int(c*(9/5) + 32)\r\nstatement = f\"{c} degrees Centigrade is {f} degrees Fahrenheit.\"\r\n\r\n# 4) output information\r\nprint(statement)\r\n","repo_name":"chmoore90/Ivy_Tech","sub_path":"SDEV140/MooreChloeM01_M01Ex1.py","file_name":"MooreChloeM01_M01Ex1.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"22554888262","text":"import numpy as np\nimport pytest\nfrom tf_agents.specs import TensorSpec\nfrom tf_agents.utils.nest_utils import is_batched_nested_tensors\n\nfrom bellman.environments.reward_model import RewardSpec\nfrom bellman.environments.transition_model.utils import (\n extract_transitions_from_trajectories,\n size,\n)\nfrom tests.tools.bellman.trajectories.trajectory import generate_dummy_trajectories\n\n\ndef test_extract_transitions_from_trajectories(\n observation_space, action_space, batch_size, trajectory_length, predict_state_difference\n):\n trajectories = generate_dummy_trajectories(\n observation_space, action_space, batch_size, trajectory_length\n )\n transitions = extract_transitions_from_trajectories(\n trajectories, observation_space, action_space, predict_state_difference\n )\n\n observation = transitions.observation\n action = transitions.action\n reward = transitions.reward\n next_observation = transitions.next_observation\n\n assert is_batched_nested_tensors(\n tensors=[observation, action, reward, next_observation],\n specs=[observation_space, action_space, RewardSpec, observation_space],\n )\n\n assert (\n observation.shape[0]\n == action.shape[0]\n == reward.shape[0]\n == next_observation.shape[0]\n == (batch_size * (trajectory_length - 1))\n )\n\n\n@pytest.mark.parametrize(\"n_dims\", list(range(10)))\ndef test_size(n_dims):\n shape = np.random.randint(1, 10, (n_dims,))\n\n tensor = np.random.randint(0, 1, shape)\n tensor_spec = TensorSpec(shape)\n\n assert size(tensor_spec) == np.size(tensor)\n","repo_name":"Bellman-devs/bellman","sub_path":"tests/unit/bellman/environments/transition_model/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"8"} +{"seq_id":"31161667006","text":"import json\nfrom user import User\n\nclass Users:\n def __init__(self, filepath):\n self.filepath = filepath\n self.users = self.load_users()\n\n def load_users(self):\n try:\n with open(self.filepath,'r') as f:\n users = json.load(f)\n result = []\n for user in users:\n lUser = User(user['id'],user['name'],user['wow_name'],user['dkp'])\n result.append(lUser)\n return result\n except(IOError,IndexError):\n print('Failed to load user data.')\n\n def save_users(self):\n with open(self.filepath,'w') as f:\n nusers = []\n for user in self.users:\n user_dict = user.__dict__\n nusers.append(user_dict)\n json.dump(nusers,f)\n\n def add_user(self,id,name,wow_name,dkp=50):\n new_user = User(id,name,wow_name,dkp)\n self.users.append(new_user)\n self.save_users()\n return self\n\n \n def find_user(self,authorid):\n '''\n Takes ctx.author.id as a string as input, wraps it in mention syntax to check against database\n And returns the user if the user was found, false otherwise.\n '''\n if str(authorid)[:2] == '<@':\n authorid = str(authorid)[2:-1]\n found = False\n for user in self.users:\n if user.id == ('<@'+str(authorid)+'>'):\n found = True\n break\n if found:\n return user\n else:\n return False\n\n def find_user_w(self,wow_name:str):\n '''\n Takes wow_name as a string as input, wraps it in mention syntax to check against database\n And returns the user if the user was found, false otherwise.\n '''\n found = False\n for user in self.users:\n if user.wow_name == (wow_name):\n found = True\n break\n if found:\n return user\n else:\n return False\n ","repo_name":"swooperior/WoVBot","sub_path":"users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"17162089075","text":"META_INFO = {\r\n 'engine_type' : {\r\n 'search_engine' : True,\r\n },\r\n 'in_development' : True,\r\n\r\n\r\n 'include_in_git' : False,\r\n 'cannot_distribute'\t\t\t: True,\r\n # is available but should not be displayed :)\r\n # I guess that's not quite right right now :)\r\n\r\n}\r\n\r\nDEFAULT_PARAMS = {\r\n 'validation_score_field' : 'maxquant:score',\r\n 'bigger_scores_better' : True,\r\n}\r\n\r\nUSEARCH_PARAM_VALUE_TRANSLATIONS = { }\r\nUSEARCH_PARAM_KEY_VALUE_TRANSLATOR = { }\r\n","repo_name":"bald/ursgal","sub_path":"ursgal/kb/maxquant_1_4_1_2.py","file_name":"maxquant_1_4_1_2.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"8"} +{"seq_id":"5937160407","text":"import tkinter as tk\nfrom inspect import getmembers, isfunction\nimport importlib\nfrom tkinter import ttk\nimport subprocess \n\nclass WindowInitialization:\n \"\"\"Сlass designed to create a window and define its main settings\"\"\"\n def __init__(self, is_root, width, heigth, title, bg, font, font_color, win_icon):\n # Window initialization\n if is_root == True:\n self.window = tk.Tk()\n else: self.window = tk.Toplevel()\n # Window properties\n self.window.minsize(width=width, \n height=heigth)\n self.window.title(title)\n self.window_icon = tk.PhotoImage(file=win_icon)\n self.window.iconphoto(False, self.window_icon)\n # General application style \n self.window.configure(bg=bg)\n self.window.option_add(\"*Font\", font)\n self.window.option_add(\"*foreground\", font_color)\n self.window.option_add(\"*background\", bg)\n self.window.option_add('*TCombobox*Listbox*Background', 'white')\n self.window.option_add('*TCombobox*Listbox*Foreground', 'RoyalBlue4')\n # Radiobutton style\n rbtn_style = ttk.Style()\n rbtn_style.configure('Default.TRadiobutton',\n background=bg,\n font=font,\n foreground=font_color)\n \nclass LabledFrame(tk.Frame):\n \"\"\"Create a frame that contains label and passed object\"\"\"\n def __init__(self, master, lbl_text, display_obj, display_obj_prmt):\n tk.Frame.__init__(self, master)\n self.lbl = tk.Label(master=self, \n text=lbl_text)\n self.display_obj = display_obj(self, display_obj_prmt)\n self.lbl.grid(row = 0, \n column = 0, \n sticky=\"W\",\n pady=(0, 7))\n self.display_obj.grid(row = 1, column = 0)\n\nclass TxtContainerY(tk.Frame):\n \"\"\"Textbox with vertial scroll\"\"\"\n def __init__(self, master, textbox_size=(70,4)):\n tk.Frame.__init__(self, master)\n if textbox_size == None:\n textbox_size = (70,4)\n width, height = textbox_size\n self.txt = tk.Text(self, \n width=width, \n height=height, \n wrap=\"word\", \n borderwidth=0,\n bg=\"white\",\n foreground=\"black\")\n self.txt_vsb = tk.Scrollbar(self, \n orient=\"vertical\", \n command=self.txt.yview)\n self.txt.configure(yscrollcommand=self.txt_vsb.set)\n self.txt.grid(row=0, column=0, sticky=\"nsew\")\n self.txt_vsb.grid(row=0, column=1, sticky=\"ns\")\n self.grid_rowconfigure(0, weight=1)\n self.grid_columnconfigure(0, weight=1)\n self.txt.bind(\"\", self.copy_to_clipboard)\n def copy_to_clipboard(self, event):\n output_text = self.txt.get('1.0', 'end-1c')\n subprocess.run(\"clip\", text=True, input=output_text)\n\nclass TxtContainerXY(tk.Frame):\n \"\"\"Textbox with vertical and horizontal scroll\"\"\"\n def __init__(self, master, textbox_size=(70,6)):\n tk.Frame.__init__(self, master)\n if textbox_size == None:\n textbox_size = (70,4)\n width, height = textbox_size\n self.txt = tk.Text(self, \n width = width, \n height = height, \n wrap = \"none\", \n borderwidth = 0,\n bg = \"white\",\n foreground = \"black\")\n self.txt_vsb = tk.Scrollbar(self, \n orient = \"vertical\", \n command = self.txt.yview)\n self.txt_hsb = tk.Scrollbar(self, \n orient = \"horizontal\", \n command = self.txt.xview)\n self.txt.configure(yscrollcommand = self.txt_vsb.set, \n xscrollcommand = self.txt_hsb.set)\n self.txt.grid(row = 0, column = 0, sticky = \"nsew\")\n self.txt_vsb.grid(row = 0, column = 1, sticky = \"ns\")\n self.txt_hsb.grid(row = 1, column = 0, sticky = \"ew\")\n self.grid_rowconfigure(0, weight = 1)\n self.grid_columnconfigure(0, weight = 1)\n self.txt.bind(\"\", self.copy_to_clipboard)\n def copy_to_clipboard(self, event):\n output_text = self.txt.get('1.0', 'end-1c')\n subprocess.run(\"clip\", text=True, input=output_text)\n\ndef get_algorithms(algorithm_module):\n \"\"\"Get functions that exist in a module\"\"\"\n algorithm_module = importlib.import_module(algorithm_module)\n function_list = getmembers(algorithm_module, isfunction)\n return function_list","repo_name":"Neterlon/python-gui-encryptor","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"8"} +{"seq_id":"26457965364","text":"#! /usr/bin/python3\n\nimport fileinput\nimport sys\nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\n\ndef list_flt(vals):\n a = []\n for val in vals:\n a.append(float(val))\n return a\n\ndef list_avg(vals):\n sum = 0.0\n for val in vals:\n sum += float(val)\n return sum/len(vals)\n\n\nplt.interactive(False)\ni=0\nprevprod = 1000000.0\nfreeze = False\nfroze = False\nfor line in fileinput.input(sys.argv[1]):\n cols = line.split(',');\n if (cols[0] == 'LAM'):\n continue\n majr = float(cols[4])\n minr = float(cols[7])\n a = float(cols[10]) * 180 / math.pi\n z = float(cols[11])\n n = int(cols[12])\n xvals = list_flt(cols[13:13+n])\n yvals = list_flt(cols[13+n:13+2*n])\n xavg = list_avg(xvals)\n yavg = list_avg(yvals)\n\n # make an ellipse object\n factor = 4.605;\n #factor = 5.991 # 95%\n e_big = Ellipse(xy=[xavg,yavg], width=factor*majr, height=factor*minr, angle=a)\n e_big.set_alpha(0.25) # grey line\n e_big.set_facecolor([1,1,1]) # white insides\n\n factor /= math.sqrt(n)\n e_sma = Ellipse(xy=[xavg,yavg], width=factor*majr, height=factor*minr, angle=a)\n e_sma.set_alpha(1.0) # 0=white, 1=black\n e_sma.set_facecolor([1,1,1]) # white insides\n\n # set up a plot; I'm not sure what 'figure' and 'subplot' are\n plt.figure(1).clear()\n plt.subplot(111).add_artist(e_big)\n plt.subplot(111).add_artist(e_sma)\n plt.subplot(111).set_xlim(-15,15)\n plt.subplot(111).set_ylim(-15,15)\n\n # plot the stuff\n plt.plot(xvals, yvals, 'kx') # black x's\n plt.plot(0, 0, 'r+')\n plt.plot(xavg, yavg, 'b+')\n #plt.show()\n\n thisprod = majr * minr\n if thisprod>prevprod and not froze:\n freeze = True\n prevprod = thisprod\n\n nholds = 1\n if freeze:\n nholds = 10\n for holdi in (range(nholds)):\n stri = str(i)\n i += 1\n while len(stri) < 4:\n stri = '0' + stri\n plt.savefig('ell'+stri+'.png');\n print('ell'+stri+'.png');\n if freeze:\n freeze = False\n froze = True\n","repo_name":"sethmerickel/Multi-Image-Geopositioning","sub_path":"scripts/ell.py","file_name":"ell.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"33092035233","text":"from collections import defaultdict\n\nfrom util import *\n\n\ndef parse_input():\n lines = read_input_as_lines()\n for line in lines:\n coord_a, coord_b = line.split(' -> ')\n a_x, a_y = coord_a.split(',')\n b_x, b_y = coord_b.split(',')\n yield (int(a_x), int(a_y)), (int(b_x), int(b_y))\n\n\ndef get_step_delta(a, b):\n if a < b:\n return 1\n elif a == b:\n return 0\n return -1\n\n\ndef get_steps_inclusive(a_x, a_y, b_x, b_y):\n d_x = get_step_delta(a_x, b_x)\n d_y = get_step_delta(a_y, b_y)\n b_x += d_x\n b_y += d_y\n while not (a_x == b_x and a_y == b_y):\n yield a_x, a_y\n a_x += d_x\n a_y += d_y\n\n\ndef get_n_doubly_covered_points(include_diagonals=False):\n covered = defaultdict(int)\n for (a_x, a_y), (b_x, b_y) in parse_input():\n if a_x == b_x or a_y == b_y or include_diagonals:\n for x, y in get_steps_inclusive(a_x, a_y, b_x, b_y):\n covered[(x, y)] += 1\n return len({s for s in covered.keys() if covered[s] > 1})\n\n\ndef part1():\n return get_n_doubly_covered_points()\n\n\ndef part2():\n return get_n_doubly_covered_points(include_diagonals=True)\n\n\nif __name__ == '__main__':\n print(part1())\n print(part2())\n","repo_name":"AbelPelser/AdventOfCode2021","sub_path":"puzzles/Day5/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"7836553339","text":"#!/usr/bin/env python3\n\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport re\nimport subprocess\nimport sys\n\nSOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\n\n\ndef main():\n args = parse_args()\n\n chromedriver_name = {\n 'darwin': 'chromedriver',\n 'win32': 'chromedriver.exe',\n 'linux': 'chromedriver',\n 'linux2': 'chromedriver'\n}\n\n chromedriver_path = os.path.join(\n args.source_root, args.build_dir, chromedriver_name[sys.platform])\n proc = subprocess.Popen([chromedriver_path],\n stdout=subprocess.PIPE, universal_newlines=True)\n try:\n output = proc.stdout.readline()\n except KeyboardInterrupt:\n returncode = 0\n finally:\n proc.terminate()\n\n returncode = 0\n match = re.search(\n '^Starting ChromeDriver [0-9]+.[0-9]+.[0-9]+.[0-9]+ .* on port [0-9]+$',\n output\n )\n\n if match is None:\n returncode = 1\n\n if returncode == 0:\n print('ok ChromeDriver is able to be initialized.')\n\n return returncode\n\n\ndef parse_args():\n parser=argparse.ArgumentParser(description='Test ChromeDriver')\n parser.add_argument('--source-root',\n default=SOURCE_ROOT,\n required=False)\n parser.add_argument('--build-dir',\n default=None,\n required=True)\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"electron/electron","sub_path":"script/verify-chromedriver.py","file_name":"verify-chromedriver.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","stars":109722,"dataset":"github-code","pt":"86"} +{"seq_id":"32105370193","text":"from itertools import chain \nfrom mdutils.mdutils import MdUtils\nimport os\nimport simplejson\n\n\ndef find_table_contents(dicts, indicator, table_name):\n for dictionary in dicts:\n dictionary = list(dictionary.values())[0]\n if dictionary['Indicator'] == indicator and table_name in dictionary.keys():\n rows = dictionary[table_name]\n if isinstance(rows, list):\n table = [list(rows[0].keys())]\n for row in rows:\n values = [value.replace('\\n', ' ').replace('<', '`<').replace('>', '>`') for value in list(row.values())]\n table.append(values)\n else:\n table = [list(rows.keys())]\n values = [value.replace('\\n', ' ').replace('<', '`<').replace('>', '>`') for value in list(rows.values())]\n table.append(values)\n\n return table\n \n return []\n\n\ndef write_md_files():\n with open('content/json/Consolidated.json') as texts_reader, open('content/json/FiltersConsol.json') as filters_reader, open('content/json/PUPlotsConsol.json') as pop_up_reader:\n\n texts = simplejson.load(texts_reader)\n filters = simplejson.load(filters_reader)\n pop_ups = simplejson.load(pop_up_reader)\n\n for text in texts:\n text = list(text.values())[0]\n title = text['PageTitle']\n indicator = text['Indicator']\n file_name = title.replace(' ', '_')\n base_path = f'content/markdown/consolidated'\n\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n\n mdFile = MdUtils(file_name=os.path.join(base_path, file_name), title=title)\n mdFile.new_header(level=1, title=indicator)\n \n mdFile.new_header(level=2, title='Main')\n mdFile.new_paragraph(text['ConsolidatedText_Main'])\n\n main_filter_table = find_table_contents(filters, indicator, 'Main Filters')\n if main_filter_table:\n mdFile.new_line()\n mdFile.new_table(columns=len(main_filter_table[0][:]), rows=len(main_filter_table[:]), \n text=list(chain.from_iterable(main_filter_table)), text_align='left')\n \n mdFile.new_paragraph('
')\n mdFile.new_line()\n mdFile.new_header(level=2, title='Explore')\n mdFile.new_paragraph(text['ConsolidatedText_Explore'])\n\n explore_filter_table = find_table_contents(filters, indicator, 'Explore Filters')\n if explore_filter_table:\n mdFile.new_line()\n mdFile.new_table(columns=len(explore_filter_table[0][:]), rows=len(explore_filter_table[:]), \n text=list(chain.from_iterable(explore_filter_table)), text_align='left')\n\n pop_up_plots_table = find_table_contents(pop_ups, indicator, 'PopUpElements')\n if pop_up_plots_table:\n mdFile.new_paragraph('
')\n mdFile.new_line()\n mdFile.new_header(level=3, title='NUTS Pop Up Plot')\n mdFile.new_table(columns=len(pop_up_plots_table[0][:]), rows=len(pop_up_plots_table[:]), \n text=list(chain.from_iterable(pop_up_plots_table)), text_align='left')\n\n climatology_plots_table = find_table_contents(pop_ups, indicator, 'ClimatologyElements')\n if climatology_plots_table:\n mdFile.new_paragraph('
')\n mdFile.new_line()\n mdFile.new_header(level=3, title='NUTS Climatology Plot')\n mdFile.new_table(columns=len(climatology_plots_table[0][:]), rows=len(climatology_plots_table[:]), \n text=list(chain.from_iterable(climatology_plots_table)), text_align='left')\n \n\n mdFile.create_md_file()\n\n\nif __name__ == '__main__':\n write_md_files()","repo_name":"cedadev/c3s_434_ecde_page_text","sub_path":"code/create_md_files.py","file_name":"create_md_files.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"35482533433","text":"# @Author : TongTong\n\nfrom api.base_api import BaseApi\nfrom common.config import cf\n\n\nclass Wework(BaseApi):\n \"\"\"\n 获取企业微信的access_token,后续应该得写在BaseApi的父类,这个类没啥必要了\n\n CORP_ID:企业微信的企业id\n \"\"\"\n # 通过配置文件获取企业微信的id\n CORP_ID = cf.get_key(\"wwork\", \"corp_id\")\n\n\n def get_token(self, secret):\n \"\"\"\n 获取access_token,不同的应用的秘钥,会产生不同的access_token,所以就封装起来了\n :param secret: 企业微信不同也应用的密码\n :return: access_token的值\n \"\"\"\n data = {\n \"method\": \"GET\",\n \"url\": f\"https://qyapi.weixin.qq.com/cgi-bin/gettoken\",\n \"params\": f\"corpid={self.CORP_ID}&corpsecret={secret}\"\n }\n # 使用send_api,传入data,相当于使用了requests了\n res = self.send_api(data)\n # 获取access_token\n token = res[\"access_token\"]\n return token\n\n\nif __name__ == \"__main__\":\n a = Wework()\n print(a.get_token(\"YC9RRMQcQqGNxapjoeiDIn84mCY7H-aJblz_X9X073U\"))","repo_name":"a376230095/wwork_api_interface_test","sub_path":"api/wework.py","file_name":"wework.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"zh","doc_type":"code","stars":38,"dataset":"github-code","pt":"86"} +{"seq_id":"36001087425","text":"import sys\r\ninput=sys.stdin.readline\r\nK,N=map(int,input().split())\r\ndef turns(x,y,N):\r\n if x<1 or x>N or y<1 or y>N:\r\n return 4*N\r\n if x==N or y==N:\r\n res=4*N\r\n for dx,dy in [(-2,-1),(-1,-2),(-2,1),(1,-2)]:\r\n t=turns(x+dx,y+dy,N)\r\n res=min(res,t)\r\n return 1-res if res<=0 else -1-res\r\n if (x%4==1 or x%4==2) and( y%4==1 or y%4==2):\r\n return -((x+y-1)//4)*2\r\n return ((x+y+1)//4)*2-1\r\n\r\nans=[None for i in range(K)]\r\na=[]\r\nfar=0\r\nfor _ in range(K):\r\n a.append(list(map(int,input().split())))\r\nfor i in range(K):\r\n tnow=turns(a[i][0],a[i][1],N)\r\n if abs(tnow)>abs(far) or (abs(tnow)==far and tnow>0):\r\n far=tnow\r\n res=4*N\r\n ax,ay=0,0\r\n for dx,dy in [(-2,-1),(-1,-2),(-2,1),(1,-2)]:\r\n t=turns(a[i][0]+dx,a[i][1]+dy,N)\r\n if res>t and not(tnow>0 and t>0):\r\n res=t\r\n ax,ay=a[i][0]+dx,a[i][1]+dy\r\n ans[i]=[ax,ay]\r\nif far<0:\r\n print('NO')\r\nelse:\r\n print('YES')\r\n for i in range(K):\r\n print(*ans[i])","repo_name":"jbkarvens/baekjoon","sub_path":"백준/Platinum/3326. Knights/Knights.py","file_name":"Knights.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"27087818104","text":"# Databricks notebook source\nimport datetime\nusers = [\n {\n \"id\": 1,\n \"first_name\": \"Corrie\",\n \"last_name\": \"Van den Oord\",\n \"email\": \"cvandenoord0@etsy.com\",\n \"is_customer\": True,\n \"amount_paid\": 1000.55,\n \"customer_from\": datetime.date(2021, 1, 15),\n \"last_updated_ts\": datetime.datetime(2021, 2, 10, 1, 15, 0)\n },\n {\n \"id\": 2,\n \"first_name\": \"Nikolaus\",\n \"last_name\": \"Brewitt\",\n \"email\": \"nbrewitt1@dailymail.co.uk\",\n \"is_customer\": True,\n \"amount_paid\": 900.0,\n \"customer_from\": datetime.date(2021, 2, 14),\n \"last_updated_ts\": datetime.datetime(2021, 2, 18, 3, 33, 0)\n },\n {\n \"id\": 3,\n \"first_name\": \"Orelie\",\n \"last_name\": \"Penney\",\n \"email\": \"openney2@vistaprint.com\",\n \"is_customer\": True,\n \"amount_paid\": 850.55,\n \"customer_from\": datetime.date(2021, 1, 21),\n \"last_updated_ts\": datetime.datetime(2021, 3, 15, 15, 16, 55)\n },\n {\n \"id\": 4,\n \"first_name\": \"Ashby\",\n \"last_name\": \"Maddocks\",\n \"email\": \"amaddocks3@home.pl\",\n \"is_customer\": False,\n \"last_updated_ts\": datetime.datetime(2021, 4, 10, 17, 45, 30)\n },\n {\n \"id\": 5,\n \"first_name\": \"Kurt\",\n \"last_name\": \"Rome\",\n \"email\": \"krome4@shutterfly.com\",\n \"is_customer\": False,\n \"last_updated_ts\": datetime.datetime(2021, 4, 2, 0, 55, 18)\n }\n]\n\n# COMMAND ----------\n\ndf = spark.createDataFrame([Row(**row) for row in users])\n\n# COMMAND ----------\n\ndf.printSchema\n\n# COMMAND ----------\n\ndf.show()\n\n# COMMAND ----------\n\nimport pandas as pd\n\n# COMMAND ----------\n\npd.DataFrame(users)\n\n# COMMAND ----------\n\nspark.createDataFrame(pd.DataFrame(users)).show()\n\n# COMMAND ----------\n\nfrom pyspark.sql.types import *\n\n\n# COMMAND ----------\n\nfields = StructType([\n StructField('id', IntegerType()),\n StructField('first_name', StringType()),\n StructField('last_name', StringType()),\n StructField('email', StringType()),\n StructField('is_customer', BooleanType()),\n StructField('amount_paid', FloatType()),\n StructField('customer_from', DateType()),\n StructField('last_updated_ts', TimestampType())\n])\n\n# COMMAND ----------\n\nspark.createDataFrame(users, fields).show()\n\n# COMMAND ----------\n\n","repo_name":"kevinbarvaliya/Spark","sub_path":"01 Create Spark Dataframes using Python Collections and Pandas Dataframes/11.Create Spark Dataframe using Pandas Dataframe.py","file_name":"11.Create Spark Dataframe using Pandas Dataframe.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"22072116787","text":"#!/usr/bin/env python3\n\nflag = []\n\nwith open(\"strings2.out\", \"r\") as file:\n lines = file.readlines()\n for i in range(len(lines)):\n flag.append(chr(int(lines[i][0:-1], 16)))\n\nprint('F'+''.join(flag))\n","repo_name":"mstanciu552/thm","sub_path":"basic-malware/strings2.py","file_name":"strings2.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"21109763853","text":"#!/usr/bin/env python3\nimport os\nimport sys\n\n\ndef parse_path(path):\n return path.split(\",\")\n\n\ndef trace_path(path):\n map_ = {}\n pos = (0,0)\n length = 0\n for dir_ in path:\n steps = int(dir_[1:])\n mutation = {\n \"L\": (-1, 0),\n \"U\": (0, 1),\n \"R\": (1, 0),\n \"D\": (0, -1)\n }[dir_[0]]\n\n for x in range(steps):\n pos = (pos[0] + mutation[0], pos[1] + mutation[1])\n length += 1\n if pos not in map_:\n map_[pos] = length\n return map_\n\n\ndef calc_distance(dest):\n return abs(dest[0]) + abs(dest[1])\n\n\ndef gen_maps(paths):\n # trace paths\n parsed_paths = [parse_path(path) for path in paths]\n map1 = trace_path(parsed_paths[0])\n map2 = trace_path(parsed_paths[1])\n crossings = set(map1.keys()) & set(map2.keys())\n\n return map1, map2, crossings\n\n\ndef find_distance(crossings):\n return min([calc_distance(crx) for crx in crossings])\n\n\ndef find_earliest(map1, map2, crossings):\n crossings = set(map1.keys()) & set(map2.keys())\n return min([map1[c] + map2[c] for c in crossings])\n\n\ndef main(inputfile):\n if not os.getenv(\"SKIPASSERT\"):\n assert find_distance(gen_maps([\"R8,U5,L5,D3\", \"U7,R6,D4,L4\"])[2]) == 6\n assert find_distance(gen_maps([\"R75,D30,R83,U83,L12,D49,R71,U7,L72\", \"U62,R66,U55,R34,D71,R55,D58,R83\"])[2]) == 159\n assert find_distance(gen_maps([\"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\", \"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7\"])[2]) == 135\n assert find_earliest(*gen_maps([\"R75,D30,R83,U83,L12,D49,R71,U7,L72\", \"U62,R66,U55,R34,D71,R55,D58,R83\"])) == 610\n assert find_earliest(*gen_maps([\"R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\", \"U98,R91,D20,R16,D67,R40,U7,R15,U6,R7\"])) == 410\n\n with open(inputfile) as rd:\n paths =[x.strip() for x in rd.readlines()]\n map1, map2, crx = gen_maps(paths)\n print(\"One:\", find_distance(crx))\n print(\"Two:\", find_earliest(map1, map2, crx))\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1])\n","repo_name":"pubkraal/Advent","sub_path":"2019/03/03.py","file_name":"03.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"21818584232","text":"# Given two strings s and p, return an array of all the start indices of p's \n# anagrams in s. You may return the answer in any order.\n\n# An Anagram is a word or phrase formed by rearranging the letters of a different\n# word or phrase, typically using all the original letters exactly once.\n\nclass Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n \n alphabet = defaultdict(int)\n result = []\n len_s = len(s)\n len_p = len(p)\n \n # build hashmap of character frequencies\n for char in p:\n alphabet[char] += 1\n \n # return if target string p is longer than s\n if len_p > len_s:\n return result\n \n # initial pass\n for i in range(len_p):\n if s[i] in alphabet:\n alphabet[s[i]] -= 1\n \n for i in range(len_s - len_p + 1):\n \n # check if current window is an anagram (frequencies of all characters = 0)\n if all(alphabet[char_freq] == 0 for char_freq in alphabet):\n result.append(i)\n \n if s[i] in alphabet:\n alphabet[s[i]] += 1\n if i+len_p < len_s and s[i+len_p] in alphabet:\n alphabet[s[i+len_p]] -= 1\n \n \n return result","repo_name":"bennyfungc/lc_sol","sub_path":"medium/438.py","file_name":"438.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"23336153047","text":"import time\n\nimport numpy as np\nimport pygame\n\nfrom src.Fire import Fire\nfrom src.utils import Rotatable\n\nSPEED_DECAY = 0.9\nACCELERATE_SPEED = 10\nDECELERATE_SPEED = 5\nTURN_ANGLE = 5\nMAX_SPEED = 1000\nMIN_SHOOT_TIME = .5\n\n\nclass StarShip(pygame.sprite.Sprite, Rotatable):\n def __init__(self, ):\n super(StarShip, self).__init__()\n\n self.polygon = np.array([\n [0, 5],\n [10, 20],\n [20, 5],\n [15, 0],\n [5, 0],\n\n ])\n ship_size = (20, 20)\n self.surf = pygame.Surface(ship_size, pygame.SRCALPHA)\n self.surf.fill((0, 0, 0, 0)) # Make it transparent\n pygame.draw.polygon(self.surf, (0, 255, 0), self.polygon, 0)\n self.image_org = self.surf.copy()\n self.rect = self.surf.get_rect()\n self.rect.center = (400, 400)\n self.rot_angle = 0\n self.ship_speed = np.array([0, 0], dtype=np.float32)\n\n self.last_shoot_ts = 0\n\n def move(self, fps):\n self.rect.x += self.ship_speed[0] / fps\n self.rect.y += self.ship_speed[1] / fps\n\n def accelerate(self):\n self.ship_speed += ACCELERATE_SPEED * np.array([np.sin(np.radians(self.rot_angle)),\n np.cos(np.radians(self.rot_angle))])\n mag = np.sqrt(np.power(self.ship_speed, 2).sum())\n norm_speed = self.ship_speed / (mag + np.finfo('float').eps)\n mag = np.min((MAX_SPEED, mag))\n self.ship_speed = norm_speed * mag\n\n def decelerate(self):\n self.ship_speed += -DECELERATE_SPEED * np.array([np.sin(np.radians(self.rot_angle)),\n np.cos(np.radians(self.rot_angle))])\n mag = np.sqrt(np.power(self.ship_speed, 2).sum())\n norm_speed = self.ship_speed / (mag + np.finfo('float').eps)\n mag = np.min((MAX_SPEED, mag))\n self.ship_speed = norm_speed * mag if mag > 1 else np.zeros_like(self.ship_speed)\n\n def rotateRight(self):\n self._rotateObject(-TURN_ANGLE)\n\n def rotateLeft(self):\n self._rotateObject(TURN_ANGLE)\n\n def fire(self):\n if time.time() - self.last_shoot_ts <= MIN_SHOOT_TIME:\n return None\n\n self.last_shoot_ts = time.time()\n return Fire(\n self.rect.center[0],\n self.rect.center[1],\n self.rot_angle,\n self.ship_speed\n )\n","repo_name":"simon-pikalov/Ariel_OOP_2020","sub_path":"Classes/week_12/TA/Astroids/src/SimpleShip.py","file_name":"SimpleShip.py","file_ext":"py","file_size_in_byte":2400,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"86"} +{"seq_id":"14173480427","text":"\"\"\"\nThis module contains code for a GUI frontend for searches\n\"\"\"\n\nimport os\nfrom tkinter import *\nfrom tkinter import ttk, filedialog, messagebox\n\nfrom bin.initialize_goat import configs\n\nfrom util import util\nfrom searches import search_obj\nfrom results import intermediate\nfrom gui.util import input_form, gui_util\nfrom gui.searches import new_threaded_search\n#from gui.database import database_gui\n\n# temporary, this should be in the settings eventually\nvalid_algorithms = ['blast','hmmer'] # lowercase like in instance attrs - change eventually?\n\nclass SearchFrame(Frame):\n def __init__(self, parent=None): #query_db, record_db, search_db, result_db, parent=None):\n Frame.__init__(self, parent)\n self.qdb = configs['query_db']\n self.rdb = configs['record_db']\n self.sdb = configs['search_db']\n self.udb = configs['result_db']\n self._dbs = [self.qdb, self.rdb, self.sdb, self.udb]\n\n self.pack(expand=YES, fill=BOTH)\n #self.search = SearchGui(query_db, record_db, self)\n self.search = SearchGui(self.qdb, self.rdb, self)\n self.toolbar = Frame(self)\n self.toolbar.pack(side=BOTTOM, expand=YES, fill=X)\n\n self.parent = parent\n self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose)\n\n self.buttons = [('Cancel', self.onClose, {'side':RIGHT}),\n ('Run', self.onRun, {'side':RIGHT})]\n for (label, action, where) in self.buttons:\n Button(self.toolbar, text=label, command=action).pack(where)\n\n def onClose(self):\n \"\"\"Close without actually running the search\"\"\"\n self.parent.destroy()\n\n def onRun(self):\n \"\"\"Runs the search and populates the necessary files/databases\"\"\"\n params = self.search.param_frame\n sname,location,algorithm,qtype,db_type,ko = params.get_current_values()\n #print(location)\n queries = self.search.query_frame.querybox\n dbs = self.search.db_frame.db_box\n sobj = search_obj.Search( # be explicit for clarity here\n name = sname,\n algorithm = algorithm,\n q_type = qtype,\n db_type = db_type,\n queries = queries.item_list, # equivalent to all queries\n databases = dbs.item_list, # equivalent to all dbs\n keep_output = ko,\n output_location = location)\n self.sdb.add_entry(sobj.name, sobj) # add to DB\n if algorithm == 'blast' or algorithm == 'hmmer':\n window = Toplevel()\n prog_frame = new_threaded_search.ProgressFrame(\n sobj, 'new', window, other_widget=self,\n callback=self.fwd_search_callback)\n prog_frame.run()\n self.onClose()\n\n def fwd_search_callback(self):\n \"\"\"\n Run after search completes successfully; only needs to ensure changes\n are committed; parsing and removal of output files controlled by search\n runner code and dictated by the search object itself\n \"\"\"\n print(\"running callback\")\n configs['threads'].remove_thread() # technically should be only if threaded...\n self.sdb.commit()\n self.udb.commit()\n\nclass SearchGui(ttk.Panedwindow):\n def __init__(self, query_db, record_db, parent=None):\n ttk.Panedwindow.__init__(self, parent, orient=HORIZONTAL)\n self.parent = parent\n self.query_frame = QuerySummaryFrame(self)\n self.param_frame = ParamFrame(self, self.query_frame)\n self.db_frame = DatabaseSummaryFrame(self)\n self.add(self.param_frame)\n self.add(self.query_frame)\n self.add(self.db_frame)\n self.pack(expand=YES, fill=BOTH)\n\nclass ParamFrame(Frame):\n def __init__(self, parent=None, other_widget=None):\n Frame.__init__(self, parent)\n #self.pack(expand=YES, fill=BOTH)\n self.pack()\n self.other = other_widget\n self.curdir = os.getcwd()\n self.entries = input_form.DefaultValueForm(\n [('Name',''), ('Location',self.curdir)],\n self,\n [('Choose Directory', self.onChoose, {'side':RIGHT})])\n self.algorithm = gui_util.ComboBoxFrame(self,\n choices=valid_algorithms,\n labeltext='Algorithm',\n select_function=self.onSelectAlgorithm)\n self.q_type = gui_util.RadioBoxFrame(self,\n [('Protein','protein'), ('Genomic','genomic')],\n labeltext='Query data type')\n self.db_type = gui_util.RadioBoxFrame(self,\n [('Protein','protein'), ('Genomic','genomic')],\n labeltext='Target data type')\n self.keep_output = gui_util.CheckBoxFrame(self, 'Keep output files?')\n\n def onChoose(self):\n \"\"\"Pops up directory choice\"\"\"\n dirpath = filedialog.askdirectory()\n for entry_row in self.entries.row_list:\n if entry_row.label_text == 'Location':\n entry_row.entry.delete(0,'end') # delete previous entry first\n entry_row.entry.insert(0,dirpath)\n\n def onSelectAlgorithm(self):\n \"\"\"\n Called when the value of the combobox frame selection changes. Signals to\n the QuerySummaryFrame to change the query selection, and, if one is open,\n to also change the values of the query choosing window.\n \"\"\"\n new_algorithm = self.algorithm.get()\n self.other.change_algorithm(new_algorithm)\n self.other.update()\n\n def get_current_values(self):\n \"\"\"\n Called from main window before a search; returns a tuple containing all of\n the attributes in the order in which they appear in the window (top-down)\n \"\"\"\n return (self.entries.get('Name'), #name\n self.entries.get('Location'), # location\n self.algorithm.get(), # algorithm\n self.q_type.get(), # query type\n self.db_type.get(), # db type\n self.keep_output.button_checked()) # whether to keep output\n\nclass QuerySummaryFrame(Frame):\n def __init__(self, parent=None, text='Queries', items=None,\n algorithm=None):\n Frame.__init__(self, parent)\n self.qdb = configs['query_db']\n self.querybox = gui_util.ScrollBoxFrame(self, text, items)\n # instance variables for use with listbox and query chooser\n self.prev_algorithm = None\n self.algorithm = algorithm\n self.qdict = {}\n self.query_window = None # store an instance variable\n # toolbar and buttons\n self.toolbar = Frame(self)\n self.toolbar.pack(side=BOTTOM, fill=X)\n self.buttons=[('Remove Query(ies)', self.onRemove, {'side':RIGHT}),\n ('Add Query(ies)', self.onAdd, {'side':RIGHT})]\n for (label, action, where) in self.buttons:\n Button(self.toolbar, text=label, command=action).pack(where)\n\n def change_algorithm(self, algorithm):\n \"\"\"Called from parent window\"\"\"\n if self.algorithm:\n self.prev_algorithm = self.algorithm # store old value before changing\n self.algorithm = algorithm\n\n def update(self):\n \"\"\"\n Called whenever the algorithm selection changes; grabs current value of\n queries in window for storage in an internal dict and then clears the\n window, calling populate to fill it with new values (if present)\n \"\"\"\n if self.prev_algorithm:\n to_stash = []\n for item in self.querybox.item_list:\n to_stash.append([item,'']) # need a tuple, don't care about value\n self.qdict[self.prev_algorithm] = to_stash # store old value\n self.populate()\n #print(self.query_window)\n if self.query_window:\n self.query_window.update(self.algorithm)\n\n def populate(self):\n \"\"\"\n Re-populates the window from internal dict based on algorithm selection.\n Note, may not put any values.\n \"\"\"\n self.querybox.clear()\n if self.algorithm in self.qdict.keys():\n self.querybox.add_items(self.qdict[self.algorithm])\n\n def onRemove(self):\n \"\"\"Removes select entry(ies)\"\"\"\n selected = self.querybox.selection() # 0, 1, or more items\n self.querybox.remove_items(selected) # object itself handles removal\n\n def onAdd(self):\n \"\"\"Add queries\"\"\"\n if self.query_window: # one is already open\n \"\"\"\n Issue here with trying to lift window on re-click; quick perusal online\n suggests this is different for both mac and windows, and might be\n complicated on mac - need to look into this later.\n \"\"\"\n self.query_window.lift() # should bring to front?\n else:\n if self.algorithm:\n window = Toplevel()\n qwindow = QueryWindow(self, window, self.algorithm)\n self.query_window = qwindow\n else:\n messagebox.showwarning('Query Choice Window',\n 'Please choose an algorithm before choosing queries')\n\n def query_window_closed(self):\n \"\"\"Called from query window before close\"\"\"\n self.query_window = None\n\nclass QueryWindow(Frame):\n def __init__(self, other_widget, parent=None, algorithm=None):\n Frame.__init__(self, parent)\n self.pack(expand=YES, fill=BOTH)\n self.qdb = configs['query_db']\n self.qsdb = configs['query_sets']\n self.other = other_widget # ref to send back updates\n # ensure other widget knows it is closed\n self.parent = parent\n self.parent.protocol(\"WM_DELETE_WINDOW\", self.onCancel)\n\n self.algorithm = algorithm\n self.label = Label(self, text='Available {} Queries'.format(self.algorithm))\n self.label.pack(expand=YES, fill=X, side=TOP)\n self.notebook = QuerySearchNotebook(self, self.algorithm)\n # toolbar and buttons\n self.toolbar = Frame(self)\n self.toolbar.pack(side=BOTTOM, expand=YES, fill=X)\n self.buttons = [('Submit', self.onSubmit, {'side':RIGHT}),\n ('Cancel', self.onCancel, {'side':RIGHT})]\n for (label, action, where) in self.buttons:\n Button(self.toolbar, text=label, command=action).pack(where)\n\n def onSubmit(self):\n \"\"\"Checks whether the treeview or list widget is in focus, then checks the\n selection in the relevant widget. Adds (query_id/query_value) pairs to a\n list, checking for duplicates. If the treeview widget is selected, query\n objects are retrieved from the database. Finally, adds selected query(ies)\n to the listbox in the main window, again skipping duplicates\"\"\"\n notebook = self.notebook\n to_add = [] # common list to add to main widget from\n if notebook.select() == str(notebook.qset):\n if messagebox.askyesno(\n message='Add by whole sets?',\n icon='question', title='Add Sets'):\n add_sets = True\n else:\n add_sets = False\n seen = set() # must account for possible multiple instances\n for item_id in notebook.qset.selection(): # one or more items, unlike focus\n item = notebook.qset.item(item_id)\n if item['tags'][0] == 'set':\n set_obj = self.qsdb[item['text']]\n for qid in set_obj.list_entries():\n if not qid in seen:\n to_add.append([qid,''])\n elif item['tags'][0] == 'query':\n if add_sets:\n set_name = notebook.qset.get_ancestors(item_id,[])[0]\n set_obj = self.qsdb[set_name]\n for qid in set_obj.list_entries():\n if not qid in seen:\n to_add.append([qid,''])\n else:\n item_name = item['text']\n if not item_name in seen:\n to_add.append([item_name,''])\n elif notebook.select() == str(notebook.qlist):\n selected = notebook.qlist.selection()\n if len(selected) > 0:\n # no chance for duplicate entries, '' is the 'value'\n to_add.extend([(notebook.qlist.get(index),'') for index in selected])\n # now try adding\n if len(to_add) > 0:\n self.other.querybox.add_items(to_add)\n self.other.query_window_closed() # signal back to parent that child is gone\n self.parent.destroy() # either way, close window\n\n def onCancel(self):\n \"\"\"Quits without adding any queries\"\"\"\n self.other.query_window_closed()\n self.parent.destroy()\n\n def update(self, algorithm):\n \"\"\"\n Called whenever the chosen algorithm in the main GUI window changes.\n Forces label update on window and also calls to child widgets to update\n query list based on the chosen algorithm type.\n \"\"\"\n self.algorithm = algorithm\n self.label['text'] = 'Available {} Queries'.format(self.algorithm)\n self.notebook.update(self.algorithm)\n\nclass QuerySearchNotebook(ttk.Notebook):\n def __init__(self, parent=None, algorithm=None):\n ttk.Notebook.__init__(self, parent)\n self.qdb = configs['query_db']\n self.algorithm = algorithm\n self.qset = QSearchSetViewer(self, self.algorithm)\n self.qlist = QSearchListViewer(self, self.algorithm)\n self.add(self.qset, text='Query Sets')\n self.add(self.qlist, text='All Queries')\n self.pack(expand=YES, fill=BOTH)\n\n def update(self, algorithm):\n \"\"\"Calls change_algorithm and update on child widgets\"\"\"\n self.algorithm = algorithm\n for widget in (self.qset,self.qlist):\n widget.change_algorithm(self.algorithm)\n widget.update()\n\nclass QSearchSetViewer(ttk.Treeview):\n def __init__(self, parent=None, algorithm=None):\n ttk.Treeview.__init__(self, parent)\n self.pack(expand=YES, fill=BOTH)\n self.algorithm = None\n self.qtype = None\n self.qdb = configs['query_db']\n self.qsdb = configs['query_sets']\n # set starting algorithm and qtype\n self.change_algorithm(algorithm)\n # configure and build tree\n self.config(selectmode='extended') # want multiple selection here\n self.make_tree()\n\n def change_algorithm(self, new_algorithm):\n \"\"\"Called to change value of algorithm and qtype\"\"\"\n self.algorithm = new_algorithm\n if self.algorithm == 'blast':\n self.qtype = 'seq'\n elif self.algorithm == 'hmmer':\n self.qtype = 'hmm'\n else:\n self.qtype = 'msa'\n\n def update(self):\n \"\"\"Clear and redraw tree\"\"\"\n for item in self.get_children():\n self.delete(item)\n self.make_tree()\n\n def make_tree(self):\n \"\"\"Builds a treeview display of sets/queries\"\"\"\n counter = util.IDCounter()\n for set_id in self.qsdb.list_entries():\n set_obj = self.qsdb[set_id]\n if set_obj.qtype == self.qtype: # only list sets we care about\n uniq_s = str(counter.get_new_id())\n self.insert('','end',uniq_s,text=set_id,tags=('set'))\n for qid in set_obj.list_entries():\n uniq_q = str(counter.get_new_id())\n self.insert(uniq_s,'end',uniq_q,text=qid,tags=('query'))\n\n def get_ancestors(self, item_id, item_list=[]):\n \"\"\"Recurs until root node to return a list of ancestors\"\"\"\n parent = self.parent(item_id)\n item = self.item(item_id)\n item_name = item['text']\n if item_id == '': # hit root node\n return item_list[::-1]\n else:\n item_list.append(item_name)\n return self.get_ancestors(parent, item_list) # recur\n\nclass QSearchListViewer(gui_util.ScrollBoxFrame):\n def __init__(self, parent=None, algorithm=None):\n gui_util.ScrollBoxFrame.__init__(self, parent)\n self.qdb = configs['query_db']\n self.algorithm = None\n self.qtype = None\n # set starting algorithm and qtype\n self.change_algorithm(algorithm)\n # search through query db to add options\n self.update()\n\n def change_algorithm(self, new_algorithm):\n \"\"\"Called to change value of algorithm and qtype\"\"\"\n self.algorithm = new_algorithm\n if self.algorithm == 'blast':\n self.qtype = 'seq'\n elif self.algorithm == 'hmmer':\n self.qtype = 'hmm'\n else:\n self.qtype = 'msa'\n\n def update(self):\n \"\"\"Clear and re-populate listbox\"\"\"\n self.clear()\n to_display = [] # init with queries in db\n for qid in self.qdb.list_entries():\n qobj = self.qdb[qid]\n if qobj.search_type == self.qtype:\n to_display.append([qid,'']) # here, '' is 'value' as we don't need the obj\n self.add_items(to_display)\n\nclass DatabaseSummaryFrame(Frame):\n def __init__(self, parent=None, text='Database', items=None):\n Frame.__init__(self, parent)\n self.db_box = gui_util.ScrollBoxFrame(self, text, items)\n self.toolbar = Frame(self)\n self.toolbar.pack(side=BOTTOM, fill=X)\n self.buttons=[('Remove Database(s)', self.onRemove, {'side':RIGHT}),\n ('Add Database(s)', self.onAdd, {'side':RIGHT})]\n for (label, action, where) in self.buttons:\n Button(self.toolbar, text=label, command=action).pack(where)\n\n def onRemove(self):\n \"\"\"Removes select entry(ies)\"\"\"\n selected = self.db_box.selection()\n self.db_box.remove_items(selected)\n\n def onAdd(self):\n \"\"\"Adds databases\"\"\"\n window = Toplevel()\n DatabaseWindow(self, window)\n\nclass DatabaseWindow(Frame):\n def __init__(self, other_widget, parent=None):\n Frame.__init__(self, parent)\n self.other = other_widget # ref to send back updates\n self.parent = parent\n self.rdb = configs['record_db']\n self.rsdb = configs['record_sets']\n Label(self, text='Available Databases').pack(expand=YES, fill=X, side=TOP)\n self.notebook = DBSearchNotebook(self)\n self.toolbar = Frame(self)\n self.toolbar.pack(side=BOTTOM, expand=YES, fill=X)\n self.pack(expand=YES, fill=BOTH)\n\n self.buttons = [('Submit', self.onSubmit, {'side':RIGHT}),\n ('Cancel', self.onCancel, {'side':RIGHT})]\n for (label, action, where) in self.buttons:\n Button(self.toolbar, text=label, command=action).pack(where)\n\n def onSubmit(self):\n \"\"\"Adds selected records to the database list in parent widget\"\"\"\n notebook = self.notebook\n to_add = [] # common list to add to main widget frame\n if notebook.select() == str(notebook.rset):\n if messagebox.askyesno(\n message='Add by whole sets?',\n icon='question', title='Add Sets'):\n add_sets = True\n else:\n add_sets = False\n seen = set()\n for item_id in notebook.rset.selection():\n item = notebook.rset.item(item_id)\n if item['tags'][0] == 'set':\n set_obj = self.rsdb[item['text']]\n for rid in set_obj.list_entries():\n if not rid in seen:\n to_add.append([rid,'']) # need a tuple\n elif item['tags'][0] == 'record':\n if add_sets:\n set_name = notebook.rset.get_ancestors(item_id,[])[0] # first item\n set_obj = self.rsdb[set_name]\n for rid in set_obj.list_entries():\n if not rid in seen:\n to_add.append([rid,''])\n else: # adding by individual queries\n item_name = item['text'] # rid\n if not item_name in seen:\n to_add.append([item_name,''])\n elif notebook.select() == str(notebook.rlist):\n selected = notebook.rlist.selection()\n if len(selected) > 0:\n to_add.extend([(notebook.rlist.get(index),'') for index in selected])\n # now try adding\n if len(to_add) > 0:\n self.other.db_box.add_items(to_add)\n self.parent.destroy()\n\n def onCancel(self):\n \"\"\"Quits without adding any records\"\"\"\n self.parent.destroy()\n\nclass DBSearchNotebook(ttk.Notebook):\n def __init__(self, parent):\n ttk.Notebook.__init__(self, parent)\n self.rset = DBSearchSetViewer(self)\n self.rlist = DBSearchListViewer(self)\n self.add(self.rset, text='Record Sets')\n self.add(self.rlist, text='All Records')\n self.pack(expand=YES, fill=BOTH)\n\nclass DBSearchSetViewer(ttk.Treeview):\n def __init__(self, parent):\n ttk.Treeview.__init__(self, parent)\n self.pack(expand=YES, fill=BOTH)\n self.rdb = configs['record_db']\n self.rsdb = configs['record_sets']\n self.config(selectmode='extended')\n self.make_tree()\n\n def make_tree(self):\n \"\"\"Builds a treeview display of sets/records\"\"\"\n counter = util.IDCounter()\n for set_id in self.rsdb.list_entries():\n set_obj = self.rsdb[set_id]\n uniq_s = str(counter.get_new_id())\n self.insert('','end',uniq_s,text=set_id,tags=('set'))\n for rid in set_obj.list_entries():\n uniq_r = str(counter.get_new_id())\n self.insert(uniq_s,'end',uniq_r,text=rid,tags=('record'))\n\n def get_ancestors(self, item_id, item_list=[]):\n \"\"\"Recurs until root node to return a list of ancestors\"\"\"\n parent = self.parent(item_id)\n item = self.item(item_id)\n item_name = item['text']\n if item_id == '': # hit root node\n return item_list[::-1]\n else:\n item_list.append(item_name)\n return self.get_ancestors(parent, item_list) # recur\n\nclass DBSearchListViewer(gui_util.ScrollBoxFrame):\n def __init__(self, parent):\n rdb = configs['record_db']\n to_add = []\n for rid in rdb.list_entries():\n to_add.append([rid,''])\n gui_util.ScrollBoxFrame.__init__(self, parent, items=to_add)\n\n##########################################\n# Interface for running reverse searches #\n##########################################\n\nclass ReverseSearchFrame(Frame):\n def __init__(self, parent=None):\n Frame.__init__(self, parent)\n self.qdb = configs['query_db']\n self.rdb = configs['record_db']\n self.sdb = configs['search_db']\n self.udb = configs['result_db']\n self._dbs = [self.qdb, self.rdb, self.sdb, self.udb]\n\n self.search_name = gui_util.ComboBoxFrame(self,\n choices = list(self.sdb.list_entries()),\n labeltext = 'Forward search to use')\n self.params = ReverseParamFrame(self)\n self.pack(expand=YES,fill=BOTH)\n self.toolbar = Frame(self)\n self.toolbar.pack(side=BOTTOM, expand=YES, fill=X)\n\n self.parent = parent\n self.parent.protocol(\"WM_DELETE_WINDOW\", self.onClose)\n\n self.buttons = [('Cancel', self.onClose, {'side':RIGHT}),\n ('Run', self.onRun, {'side':RIGHT})]\n for (label, action, where) in self.buttons:\n Button(self.toolbar, text=label, command=action).pack(where)\n\n def onClose(self):\n \"\"\"Close without actually running the search\"\"\"\n self.parent.destroy()\n\n def onRun(self):\n \"\"\"Runs the search and populates the necessary files/databases\"\"\"\n fwd_search = self.search_name.selected.get()\n fwd_sobj = self.sdb[fwd_search]\n # Next function call adds search result queries to query database\n intermediate.Search2Queries(fwd_sobj).populate_search_queries()\n # Now get all needed queries\n queries = []\n for uid in fwd_sobj.list_results(): # result ids\n #print(uid)\n uobj = self.udb[uid]\n for qid in uobj.list_queries():\n #print('\\t' + str(qid))\n queries.append(qid)\n print(queries)\n sname,location,algorithm,ko = self.params.get_current_values()\n rev_sobj = search_obj.Search( # be explicit for clarity here\n name = sname,\n algorithm = algorithm,\n q_type = fwd_sobj.db_type, # queries here are the same as the forward db type\n db_type = fwd_sobj.q_type, # conversely, db is the original query type\n queries = queries, # equivalent to all queries\n databases = [], # reverse search, so target_db is on each query!\n keep_output = ko,\n output_location = location)\n self.sdb.add_entry(rev_sobj.name, rev_sobj) # add to DB\n if algorithm == 'blast':\n window = Toplevel()\n prog_frame = new_threaded_search.ProgressFrame(\n rev_sobj, 'rev', window, other_widget=self,\n callback=self.rev_search_callback)\n prog_frame.run()\n self.onClose()\n\n def rev_search_callback(self):\n \"\"\"\n Run after search completes successfully; only needs to ensure changes\n are committed; parsing and removal of output files controlled by search\n runner code and dictated by the search object itself\n \"\"\"\n configs['threads'].remove_thread() # technically should be only if threaded...\n self.sdb.commit()\n self.udb.commit()\n\nclass ReverseParamFrame(Frame):\n \"\"\"Like ParamFrame, but without query and db type options\"\"\"\n def __init__(self, parent=None):\n Frame.__init__(self, parent)\n self.pack()\n self.curdir = os.getcwd()\n self.entries = input_form.DefaultValueForm([\n ('Name',''), ('Location',self.curdir)], self,\n [('Choose Directory', self.onChoose, {'side':RIGHT})])\n self.algorithm = gui_util.RadioBoxFrame(self,\n [('Blast','blast'), ('HMMer','hmmer')],\n labeltext='Algorithm')\n self.keep_output = gui_util.CheckBoxFrame(self, 'Keep output files?')\n\n def onChoose(self):\n \"\"\"Pops up directory choice\"\"\"\n dirpath = filedialog.askdirectory()\n for entry_row in self.entries.row_list:\n if entry_row.label_text == 'Location':\n entry_row.entry.delete(0,'end') # delete previous entry first\n entry_row.entry.insert(0,dirpath)\n\n def get_current_values(self):\n \"\"\"\n Called from main window before a search; returns a tuple containing all of\n the attributes in the order in which they appear in the window (top-down)\n \"\"\"\n return (self.entries.get('Name'), #name\n self.entries.get('Location'), # location\n self.algorithm.get(), # algorithm\n self.keep_output.button_checked()) # whether to keep output\n\n##############################################\n# Code for running reciprocal BLAST searches #\n##############################################\n","repo_name":"chris-klinger/Goat","sub_path":"gui/searches/search_gui.py","file_name":"search_gui.py","file_ext":"py","file_size_in_byte":27333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"43534604581","text":"\"\"\"Leia 4 valores inteiros A, B, C e D. A seguir, se B for maior do que C e se D for maior do que A, e a soma de C com D for maior que a soma de A e B e se C e D, ambos, forem positivos e se a variável A for par escrever a mensagem \"Valores aceitos\", senão escrever \"Valores nao aceitos\".\n\nEntrada\nQuatro números inteiros A, B, C e D.\n\nSaída\nMostre a respectiva mensagem após a validação dos valores.\"\"\"\n\nx = str(input())\nlista = x.split(\" \")\nvalores = []\nfor i in lista:\n valores.append(int(i))\na = valores\n\ncond1= (a[1] > a[2])\ncond2= (a[3] > a[0])\ncond3= ((a[2] + a[3]) > (a[0] + a[1]))\ncond4= (a[2]>0)\ncond5= (a[3]>0)\ncond6= ((a[0]%2)==0)\n\nif cond1 and cond2 and cond3 and cond4 and cond5 and cond6:\n print(\"Valores aceitos\")\nelse: \n print(\"Valores nao aceitos\")\n","repo_name":"GesleyOliveira/BeeCrowd","sub_path":"Iniciante/testeDeSelecao1.py","file_name":"testeDeSelecao1.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"28241499864","text":"import sys\nfrom io import StringIO\n\nimport pytest\n\nfrom src.winning_score import winning_score\n\n\nsys.path.insert(1, \"C:\\\\Users\\\\venge\\\\Projects\\\\rps\\\\src\\\\winning_score.py\")\n\n\n@pytest.mark.parametrize(\"prompt, expected\", [\n (StringIO('1\\n'), 1),\n (StringIO('2\\n'), 2),\n (StringIO('3\\n'), 3),\n (StringIO('15\\n'), 15),\n (StringIO('453\\n'), 453),\n (StringIO('9375\\n'), 9375)\n])\ndef test_winning_score(monkeypatch, prompt, expected):\n monkeypatch.setattr('sys.stdin', prompt)\n assert winning_score() == expected\n","repo_name":"Vasilis421/Rock_Paper_Scissors","sub_path":"tests/test_winning_score.py","file_name":"test_winning_score.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"70280229086","text":"import cv2\n\ndef main():\n\n # imgpath = \"C:\\\\Users\\\\User\\\\Desktop\\\\misc\\\\4.1.04.tiff\"\n imgpath = \"C:\\\\Users\\\\1p2h3\\\\Desktop\\\\openCV\\\\photo\\\\bingsu.tiff\"\n img = cv2.imread(imgpath)\n\n cv2.namedWindow('Lena',cv2.WINDOW_AUTOSIZE)\n ##cv2.imshow('윈도우 이름', 이미지) 윈도우 창에 이미지 보여줌\n cv2.imshow('Lena', img)\n cv2.waitKey(0)\n cv2.destroyWindow('Lena')\n\n # 추가) 창관리 메소드\n # cv2.movewWindow('윈도우이름',x좌표,y좌표) # 창 위치 변경\n # cv2.resizeWindow('윈도우 이름', 100, 100) # 창 크기 변경\n # cv2.destroyAllWindows() # 모든 창 닫기\n\n #그외에도 마우스처리나 키보드 처리 가능능\n\nif __name__ == \"__main__\":\n main()","repo_name":"hees00/OpenCV_study","sub_path":"practice1.py","file_name":"practice1.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"3978248685","text":"\"\"\"\nAdapter Overview\n================\n\nAdapters provide the bridge between the mapped object and the data store.\nThere are several layers to an adapter request and response::\n\n Req Resp\n pyperry.base.Base\n | ^\n V |\n Processors\n | ^\n V |\n Model Bridge\n | ^\n V |\n Middlewares\n | ^\n V |\n Adapter\n \\/\n Database\n\nThe request is initiated by the L{pyperry.base.Base} class and passes through\nthe adapter stack returning a response. Within the stack the request goes\nthrough a series of configurable stack items: processors, and middlewares\nbefore being passed to the appropriate adapter method. That adapter method\nthen executes the requested action and returns the results back through the\nstack until returning to Base.\n\nProcessors and middlewares are ways of customizing requests and responses.\nThere is a middleware that is always installed called the ModelBridge. It\ntakes the raw response of the adapter and converts it to mapped objects. The\nonly difference between a middleware and a processor is that the objects\nreturned to a processor are always instantiated records whereas middlewares\nreceive the raw response.\n\n\"\"\"\nfrom copy import copy\nimport socket\n\nimport pyperry\nfrom pyperry import errors\nfrom pyperry.middlewares.model_bridge import ModelBridge\n\nclass DelayedConfig(object):\n \"\"\"\n Simple class that takes kwargs or a dictionary in initializer and sets\n values to the `config` dictionary. Any values set as callables with an\n arity of 0 will be evaluated when they are accessed. If the callables arity\n is greater than 0, it will not be called automatically.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Set values in kwargs to attributes\"\"\"\n self.config = {}\n\n if len(args) == 1 and isinstance(args[0], DelayedConfig):\n self.config = args[0].config.copy()\n elif len(args) == 1 and isinstance(args[0], dict):\n kwargs.update(args[0])\n\n for k, v in kwargs.items():\n self.config[k] = v\n\n def __getitem__(self, key):\n value = self.config[key]\n\n if callable(value) and value.func_code.co_argcount == 0:\n value = value()\n\n return value\n\n def __setitem__(self, key, value):\n self.config[key] = value\n\n def update(self, config):\n if isinstance(config, DelayedConfig):\n config = config.config\n\n self.config.update(config)\n\n def keys(self):\n return self.config.keys()\n\n def has_key(self, key):\n return key in self.keys()\n\n\nclass AbstractAdapter(object):\n \"\"\"The base class for all adapters\"\"\"\n\n adapter_types = ['read', 'write']\n\n def __init__(self, config=None, **kwargs):\n \"\"\"\n Create a new adapter object with the given configuration.\n \"\"\"\n if config is None:\n config = {}\n\n if isinstance(config, AbstractAdapter):\n self.middlewares = config.middlewares\n self.processors = config.processors\n config = copy(config.config)\n else:\n config.update(kwargs)\n self.middlewares = config.get('middlewares') or []\n self.processors = config.get('processors') or []\n\n self.middlewares = copy(self.middlewares)\n self.processors = copy(self.processors)\n\n self.config = DelayedConfig(config)\n self._stack = None\n #\n # Specifies optional features that are implemented by this adapter\n self.features = {\n 'batch_write': False }\n\n if 'timeout' in self.config.keys():\n socket.setdefaulttimeout(self.config['timeout'])\n\n @property\n def stack(self):\n \"\"\"\n Setup the stack plumbing with the configured stack items\n\n Wrap each stack item (processors and middleware) in reverse order\n around the call to the adapter method. This will allow stack items to\n intercept requests, modify query information and pass it along, do\n things with the results of the query or any combination of these\n things.\n\n \"\"\"\n if self._stack: return self._stack\n\n self._stack = self.execute\n stack_items = (copy(self.processors) +\n [(ModelBridge, {})] +\n copy(self.middlewares))\n stack_items.reverse()\n\n for item in stack_items:\n if not isinstance(item, (list, tuple)):\n item = tuple([item, {}])\n\n klass = item[0]\n config = item[1]\n\n self._stack = klass(self._stack, config)\n\n return self._stack\n\n def reset(self):\n \"\"\"Clear out the stack causing it to be rebuilt on the next request\"\"\"\n self._stack = None\n\n def clear(self):\n \"\"\"Removes all configured middleware and processors and call `reset`\"\"\"\n self.middlewares = []\n self.processors = []\n self.reset()\n\n def __call__(self, **kwargs):\n \"\"\"Makes a request to the stack\"\"\"\n if 'mode' not in kwargs:\n raise errors.ConfigurationError(\"Must pass `mode` to adapter call\")\n pyperry.logger.debug('%s: %s' % (kwargs['mode'], kwargs.keys()))\n result = self.stack(**kwargs)\n\n if kwargs['mode'] is 'read' and not hasattr(result, '__iter__'):\n raise errors.BrokenAdapterStack(\n \"The adapter stack failed to return an iterable object\" )\n\n return result\n\n def execute(self, **kwargs):\n \"\"\"Call read, write, or delete according to the mode kwarg.\"\"\"\n return getattr(self, kwargs['mode'])(**kwargs)\n\n def read(self, **kwargs):\n \"\"\"Read from the datastore with the provided options\"\"\"\n raise NotImplementedError(\"You must define this method in subclasses\")\n\n def write(self, **kwargs):\n \"\"\"Write object's attributes to the datastore\"\"\"\n raise NotImplementedError(\"You must define this method in subclasses\")\n\n def delete(self, **kwargs):\n \"\"\"Delete the object from the datastore\"\"\"\n raise NotImplementedError(\"You must define this method in subclasses\")\n\n def merge(self, source=None, **kwargs):\n if source is None:\n source = {}\n\n new = self.__class__(self)\n\n if isinstance(source, AbstractAdapter):\n new.config.update(source.config)\n new.middlewares += source.middlewares\n new.processors += source.processors\n elif isinstance(source, dict):\n source.update(kwargs)\n new.config.update(source)\n\n return new\n\n","repo_name":"tpett/pyperry","sub_path":"pyperry/adapter/abstract_adapter.py","file_name":"abstract_adapter.py","file_ext":"py","file_size_in_byte":6605,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"86"} +{"seq_id":"28802015272","text":"from numpy import * \nfrom numpy.linalg import inv \nimport matplotlib.pyplot as plt \nfrom math import *\n\nclass Kalman: # Definición de clase, class name_of_the_class\n def _init_(self):\n ####### X[k-1] ###########\n self.x = None \n self.y = None \n self.Vx = None \n self.Vy = None \n self.Ax = None\n self.Ay = None \n ######### Initial Values #############\n self.Dt = None \n self.YawRate = None\n self.cosYawAngle = None \n self.sinYawAngle = None\n self.FA = None \n self.PNC = 2.25 \n self.InitValOfP = 1000\n self.VelStabilityFactor = None \n self.SignedEgoSpeed = None\n self.Overground = None \n self.MountingtoCenterY = None \n self.MountingtoCenterX = None \n self.SignedEgoAcel = None\n self.rangeRad= None \n self.AZang= None\n ############# Kalman´s Parameters ##############\n self.X = None\n self.A = None \n self.P = None \n self.Q = None \n self.H_Dist = None \n self.R = None \n self.I = None \n ############# New X(k-1) ############\n self.Oldx = None\n self.Oldy = None\n self.OldVx = None\n self.OldVy = None \n ###################### Relative Velocities ###########################\n self.VelRelVx = None\n self.VelRelVy = None\n self.RelVelVx = None\n self.RelVelVy = None \n ###################### Aceleration - Framawork ######################\n self.AB1 = None\n self.AB2 = None\n ################ Position prediction ####################\n self.XNew = None\n ############## Velocities prediction #####################\n ################ Aceleration prediction ####################\n #self. = array([[0],[0],[0],[0],[0],[0]]) \n ############# New #######\n self.theta = None # Filtro\n self.T = None # Matriz de transformacion para cambiar de marco de referencia \n self.C= None # vector de coordenadas de los clousters \n self.Clost = None # Vector de las posiciones de los closter medidas desde el ego\n self.Newmarco = None # coordenadas de los closter medidias desde el objeto, cambio de marco de referencia\n self.thetaError = None \n self.E = None # Matriz temporal, me sirve para sacar R \n ######## Me sirve para sacar interpolación lineal ############\n self.maxerror = None \n self.MinError = None\n self.MinRSP = None\n self.MaxRSP = None\n self.MaxAng = None\n #########################################################################################################\n self.J = None # Matriz jacobiana para sacar la actualización de E \n self.Range = None \n self.AgeFactor = None\n self.DGK = None # Denominator Of Kalman´s Gain\n self.PS = None \n self.I = None\n self.XNew = None\n self.X_measurement= None #[x 0 0 y 0 0 ] vector columna informacion del cluster\n\n def set_initialKalVal(self, posx, posy, velx, vely, dt, yawRate, sinYangle, cosYangle, egoSpeed, mountingCenterY, mountingCenterX, egoAccel):\n self.x = posx \n self.y = posy \n self.Vx = velx \n self.Vy = vely \n self.Ax = 0.001\n self.Ay = 0.001\n self.Dt = dt \n self.YawRate = yawRate \n self.cosYawAngle = cosYangle \n self.sinYawAngle = sinYangle\n self.SignedEgoSpeed = egoSpeed\n self.MountingtoCenterY = mountingCenterX\n self.MountingtoCenterX = mountingCenterY\n self.SignedEgoAcel = egoAccel\n self.PNC = 2.25 \n self.InitValOfP = 1000\n self.FA = 1-(0.3*self.Dt) \n self.X = array([self.x,self.Vx,self.Ax,self.y,self.Vy,self.Ay]) \n\n\n\n def Matrix_A_P_Q_H_R_I(self):\n # Transition Matrix \n self.A = array( [ [1, self.Dt, 0, self.YawRate*self.Dt, 0, 0], [0, 1, self.Dt, 0, self.YawRate*self.Dt, 0], \n [0, 0, self.cosYawAngle*self.FA, 0, 0, self.sinYawAngle*self.FA], [-self.YawRate*self.Dt, 0, 0, 1, self.Dt, 0], \n [0, -self.YawRate*self.Dt, 0, 0, 1, self.Dt], [0, 0, -self.sinYawAngle*self.FA, 0, 0, self.cosYawAngle*self.FA] ] )\n # Covariance Matrix of The Process\n self.P = diag( ( self.InitValOfP ,self.InitValOfP ,self.InitValOfP ,self.InitValOfP ,self.InitValOfP ,self.InitValOfP ) )\n # Process Noise Matrix\n self.Q = diag( ( self.PNC*self.Dt*self.Dt , self.PNC*self.Dt*self.Dt, self.PNC*self.Dt*self.Dt, self.PNC*self.Dt*self.Dt,\n self.PNC*self.Dt*self.Dt, self.PNC*self.Dt*self.Dt ) )\n # Transformation Matrix \n #self.H = diag( ( 1 ,1 ,1 ,1 ,1 ,1 ) )\n # Radar Sensitivity\n #self.R = diag( ( 25 ,25 ,6 ,6 ,1 ,1 ) )\n # Identity Matrix\n I = identity(6)\n\n def OldStateVector(self, cyclesLife):\n self.cyclesLife=cyclesLife\n self.Oldx = self.X[0]\n self.Oldy = self.X[3]\n self.Overground = sqrt((self.X[1]**2)+(self.X[4]**2))\n if self.Overground<5:\n self.VelStabilityFactor= interp(cyclesLife, [4, 7], [0.0 ,1.0])\n else:\n self.VelStabilityFactor=1\n self.OldVx = self.X[1]*self.VelStabilityFactor\n self.OldVy = self.X[4]*self.VelStabilityFactor\n\n def RelativeVelocities(self):\n self.VelRelVx = self.OldVx - self.SignedEgoSpeed + self.YawRate*(self.Oldy + self.MountingtoCenterY)\n self.VelRelVy = self.OldVy - self.YawRate*(self.Oldx + self.MountingtoCenterX)\n\n def AceleratioFramework(self):\n self.AB1 = self.X[2]*self.cosYawAngle + self.X[5]*self.sinYawAngle\n self.AB2 = -self.X[2]*self.sinYawAngle + self.X[5]*self.cosYawAngle\n\n def KalmanFilter_Predict(self):\n self.X[0] += self.VelRelVx*self.Dt\n self.X[3] += self.VelRelVy*self.Dt\n self.X[1] += (self.Ax - self.SignedEgoAcel + self.YawRate*self.OldVy)*self.Dt\n self.X[4] += (self.Ay - self.YawRate*self.OldVx)*self.Dt\n self.X[2] *= self.FA\n self.X[5] *= self.FA\n self.P = dot(self.A, dot(self.P, self.A.T))\n \n def CoordinateTransformation(self, dX, dY):#pasar como parametro x0 y x3\n # orientation\n self.theta = atan2(self.X[3], self.X[0])\n # Homogeneous Transformation Matrix\n self.T = array( [ [ cos(self.theta) , -sin(self.theta), self.X[0] ], [ sin(self.theta) , cos(self.theta), self.X[3] ],\n [ 0, 0, 1 ] ] )\n # X[0] and [3] are the centers of the objets\n self.Newmarco = array([dX,dY,1])\n # Newmarco es la medicion de los closter (x,y) desde el ego \n self.Newmarco = dot(self.T,self.Newmarco)\n dist2obj=sqrt((self.Newmarco[0]**2)+(self.Newmarco[1]**2))\n return dist2obj\n # Newmarco ahora mide las coordenadas de los closter desde el marco de referencia del objeto \n def KalmanFilter_Update(self, distX, distY, velX, velY, rangeRad, AZang, ClussinA, CluscosA):\n self.rangeRad=rangeRad\n self.AZang=AZang\n self.I = identity(6)\n self.X_measurement=[distX,0,0,distY,0,0]\n # Corrección de la posición\n # Initialization of matix H for correction of position \n # Transformation Matrix \n self.H_Dist = array( [ [1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0] ] ) \n \n ############################ Calculo de theta ####################################\n self.maxerror = deg2rad(10.0)\n self.MinError = deg2rad(1.25)\n self.thetaError = interp(self.rangeRad,[0,12],[self.maxerror,self.MinError])\n self.MinRSP = deg2rad(70.0)\n self.MaxRSP = deg2rad(80.0)\n self.MaxAng = deg2rad(5.0)\n self.thetaError += interp(self.AZang,[self.MinRSP,self.MaxRSP],[0,self.MaxAng])\n ##################################################################################\n\n ######################## Calculo de la matriz temporal E #########################\n self.E = array( [ [ 0.75**2, 0 ], [ 0, self.thetaError**2 ] ] )\n self.Range = sqrt(distX**2 + distY**2) # Raiz del cuadrado de clust.Dist de (x) y (y)\n self.J = array([[CluscosA,-ClussinA*self.Range], [ClussinA, CluscosA*self.Range]])\n self.E = dot(self.J, dot(self.E, self.J.T)) \n ##################################################################################\n\n ######################## Calculo de la matriz de error R #########################\n self.AgeFactor = interp(self.cyclesLife,[0,10.0],[0.05,1.0])\n self.R = diag( ( self.AgeFactor*self.E[0][0], 0 ,0 ,self.AgeFactor*self.E[1][1] ,0,0 ) )\n \n\n #self.R = array( [ [ self.AgeFactor*self.E[0][0], self.AgeFactor*self.E[0][1] ], \n #[ self.AgeFactor*self.E[1][0], self.AgeFactor*self.E[1][1] ] ] )\n ##################################################################################\n\n ####################### Cálculo de la Gananacia de Kalman ################################\n self.DGK = self.R + dot(self.H_Dist, dot(self.P, self.H_Dist.T)) # Denominator Of Kalman´s Gain\n self.DGK[0][0] = 1/self.DGK[0][0]\n self.DGK[3][3] = 1/self.DGK[3][3]\n self.K = dot(self.P, dot(self.H_Dist.T, self.DGK)) # Kalman´s Gain\n \n self.PS = dot(self.H_Dist,self.X) # Predicted state \n\n self.X = self.X + dot(self.K,(self.X_measurement-self.PS)) # Calculate the current State \n \n self.P = dot((self.I -dot(self.K,self.H_Dist)),self.P)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"SalvadorGuido/Object-Tracking","sub_path":"Kalman.py","file_name":"Kalman.py","file_ext":"py","file_size_in_byte":9578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"19915882609","text":"# LISTAS A UTILIZAR EN MODELOS\n\n# -- CHOICES TIPO DE SERVIDOR --\nTIPO_SERVER = [\n (\"Desarrollo\",\"Desarrollo\"),\n (\"Test\",\"Test\"),\n (\"Pre-Produccion\",\"Pre-Produccion\"),\n (\"Produccion\",\"Produccion\"),\n]\n\n # -- VARIABLES CHOICES OPERATIVOS\nCHOICES_SO = [ # -- LISTA CHOICES OPERATIVOS\n (\"Windows\",\"Windows\"),\n (\"Linux\",\"Linux\"),\n (\"Mac\",\"Mac\"),\n]\n# -------------\n\n# -- VARIABLES CHOICES ESTADO --\nESTADO = [ # -- LISTA CHOICES OPERATIVOS\n (\"Activo\",\"Activo\"),\n (\"Inactivo\",\"Inactivo\"),\n]\n# -------------\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# -- CHOICES ESTADO INCIDENCIAS --\nESTADO_INCIDENCIAS = [\n (\"Recibido\",\"Recibido\"),\n (\"En Proceso\",\"En Proceso\"),\n (\"Finalizado\",\"Finalizado\"),\n]\n# -------------\n\n# -------------\n\n# -- CHOICES SI/NO --\n\nYES_NO = [\n (\"SI\",\"SI\"),\n (\"NO\",\"NO\"),\n]\n# -------------\n# -- CHOICES TIPO EJECUCION --\nat=\"at\"\nde=\"de\"\nTIPO_EJECUCION = [\n (at,\"Atendido\"),\n (de,\"Desatendido\"),\n]\n# -------------\n# -- CHOICES PERIODICIDAD --\n\nPERIODICIDAD = [\n (\"Diario\",\"Diario\"),\n (\"Quincenal\",\"Quincenal\"),\n (\"Mensual\",\"Mensual\"),\n (\"Bimestral\",\"Bimestral\"),\n (\"Trimestral\",\"Trimestral\"),\n (\"Semestral\",\"Semestral\"),\n (\"Anual\",\"Anual\"),\n]\n# -------------\n# -- CHOICES TIPO ESFUERZO --\n\nTIPO_ESFUERZO = [\n (\"Bajo\",\"Bajo\"),\n (\"Medio\",\"Medio\"),\n (\"Alto\",\"Alto\"),\n]\n# ------------\n\n# -------------\nDIAS = [\n (\"Lunes\",\"Lunes\"),\n (\"Martes\",\"Martes\"),\n (\"Miercoles\",\"Miercoles\"),\n (\"Jueves\",\"Jueves\"),\n (\"Viernes\",\"Viernes\"),\n (\"Sabado\",\"Sabado\"),\n (\"Domingo\",\"Domingo\"),\n]\n\nATENDIDO_DESATENDIDO = [\n (\"Atendido\",\"Atendido\"),\n (\"Desatendido\",\"Desatendido\"),\n]\n\n","repo_name":"Excel-ente/RPAdmin","sub_path":"administracion/listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"9461870224","text":"\r\n\r\nclass Employee:\r\n organisation_name = \"GOOGLE\" # Class variable\r\n\r\n def __init__(self, emp_id, name, base_location, deployed_location, designation, salary):\r\n self.emp_id = emp_id\r\n self.name = name\r\n self.base_location = base_location\r\n self.deployed_location = deployed_location\r\n self.designation = designation\r\n self.salary = salary\r\n\r\n def get_employee_details(self):\r\n return f\"Employee ID: {self.emp_id}, Name: {self.name}, Designation: {self.designation}, Salary: {self.salary}\"\r\n\r\n @classmethod\r\n def get_organisation_name(cls):\r\n return cls.organisation_name\r\n\r\n @classmethod\r\n def set_organisation_name(cls, org_name):\r\n cls.organisation_name = org_name\r\n\r\n\r\nclass Manager(Employee):\r\n def __init__(self, emp_id, name, base_location, deployed_location, designation, salary):\r\n super().__init__(emp_id, name, base_location, deployed_location, designation, salary)\r\n self.managed_employees = [] # List to store managed employees\r\n\r\n def perform_appraisal_for_an_employee(self, emp_id, percent_raise):\r\n for employee in self.managed_employees:\r\n if employee.emp_id == emp_id:\r\n employee.salary *= (1 + percent_raise / 100)\r\n\r\n def get_manager_details(self, mgr_id):\r\n return self.get_employee_details() + f\", Managed Employees: {len(self.managed_employees)}\"\r\n\r\n\r\ndef main():\r\n # Create three Employee objects\r\n emp1 = Employee(101, \"tarun\", \"HQ\", \"Branch 1\", \"boss\", 10000)\r\n emp2 = Employee(102, \"trishna\", \"HQ\", \"Branch 2\", \"developer\", 70000)\r\n emp3 = Employee(103, \"sushmita\", \"HQ\", \"Branch 3\", \"admin Enggineer\", 65000)\r\n\r\n # Create a Manager object and add the Employee objects as managed employees\r\n manager = Manager(201, \"shruti\", \"HQ\", \"Branch 1\", \"Manager\", 80000)\r\n manager.managed_employees.extend([emp1, emp2, emp3])\r\n\r\n # Display manager details\r\n print(manager.get_manager_details(201))\r\n\r\n # Perform appraisal for an employee (e.g., 101) under the manager\r\n manager.perform_appraisal_for_an_employee(101, 10)\r\n print(\"After Appraisal:\")\r\n for emp in manager.managed_employees:\r\n print(emp.get_employee_details())\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"tarun-code/python-basics","sub_path":"inheritance_exercise.py","file_name":"inheritance_exercise.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"1393064472","text":"# encoding: utf-8\nfrom __future__ import division, absolute_import, with_statement, print_function\n\nfrom virtparade.utils.objects import Singleton\n\n\nclass ArgumentParser(Singleton):\n args = None\n\n @staticmethod\n def parse(project_name, description, version):\n import argparse\n\n parser = argparse.ArgumentParser(prog=project_name, description=description, formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + version)\n subparsers = parser.add_subparsers(dest='subcommand', help='sub-command help')\n\n # subcommand: run\n parser_run = subparsers.add_parser('run', help='build and run instances')\n parser_run.add_argument('-a', '--all', dest='all', action='store_true', help='build and run all instances')\n parser_run.add_argument('name', nargs='*', help='instance name(s)')\n\n # subcommand: mount\n parser_mount = subparsers.add_parser('mount', help='mount sepecified instance')\n parser_mount.add_argument('name', nargs=1, help='instance name')\n\n # subcommand: rm\n parser_rm = subparsers.add_parser('rm', help='destroy and remove all assets of instances')\n parser_rm.add_argument('--yes-i-really-really-mean-it', dest='sure', action='count', help=argparse.SUPPRESS) # hidden in help\n parser_rm.add_argument('name', nargs='*', help='instance name(s)')\n\n # subcommand: test\n subparsers.add_parser('test', help='test config file')\n\n ArgumentParser.args = parser.parse_args().__dict__\n if ArgumentParser.args['subcommand'] is None: # none subcommand chosen\n parser.print_help()\n","repo_name":"major1201/virtparade","sub_path":"virtparade/args.py","file_name":"args.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"17668729236","text":"import boto3\n\ndef create_rekognition_client(region = 'eu-west-1'):\n\n return boto3.client('rekognition', region)\n\n\ndef detect_labels(client, bucket='lnewfeld', filename=None, image_data=None):\n\n if not ((filename is None) ^ (image_data is None)):\n raise ValueError(\"filename xor image_data must be provided\")\n \n if (image_data is None):\n image = {'S3Object': {'Bucket':bucket, 'Name':filename}}\n else:\n image = {'Bytes': image_data}\n\n #print(\"{}\".format(image))\n return client.detect_labels(Image = image)\n\n\nif __name__ == \"__main__\":\n\n print(\"Creating client...\")\n client = create_rekognition_client()\n\n print(\"Detecting Labels from an image in an S3 bucket...\")\n response = detect_labels(client, filename='lee_fried_gold.jpg')\n\n print('Detected labels...') \n for label in response['Labels']:\n print (label['Name'] + ' : ' + str(label['Confidence']))\n","repo_name":"sparcs360/aws-rekognition","sub_path":"detect_labels_s3_bucket_image.py","file_name":"detect_labels_s3_bucket_image.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"3811670374","text":"from pygments import highlight\r\nfrom pygments.lexers import PythonLexer\r\nfrom pygments.formatters import HtmlFormatter\r\nfrom idlestyles import YourStyle\r\nimport os\r\n\r\nfilename = input(\"Enter file name here: \")\r\nnewfilename = filename[:-3] + \"_highlight.html\"\r\nfile = open(filename, \"r\")\r\nopfile = open(newfilename, \"w\")\r\ncode = file.read()\r\n\r\nresult = \"\\n\"\r\nresult += highlight(code, PythonLexer(), HtmlFormatter(style=YourStyle))\r\n\r\nopfile.write(result)\r\nopfile.close()\r\nfile.close()\r\nos.system(newfilename)\r\n\r\n#print(result)\r\n\r\n#wot\r\n","repo_name":"brein62/computing-stuff","sub_path":"syntax highlighter.py","file_name":"syntax highlighter.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"16636541332","text":"# Based on https://github.com/nutonomy/nuscenes-devkit\r\n# ---------------------------------------------\r\n# Modified by Zhiqi Li\r\n# ---------------------------------------------\r\n\r\nimport mmcv\r\nfrom nuscenes.nuscenes import NuScenes\r\nfrom PIL import Image\r\nfrom nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, transform_matrix\r\nfrom typing import Tuple, List, Iterable\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom matplotlib import rcParams\r\nfrom matplotlib.axes import Axes\r\nfrom pyquaternion import Quaternion\r\nfrom PIL import Image\r\nfrom matplotlib import rcParams\r\nfrom matplotlib.axes import Axes\r\nfrom pyquaternion import Quaternion\r\nfrom tqdm import tqdm\r\nfrom nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud, Box\r\nfrom nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, transform_matrix\r\nfrom nuscenes.eval.common.data_classes import EvalBoxes, EvalBox\r\nfrom nuscenes.eval.detection.data_classes import DetectionBox\r\nfrom nuscenes.eval.detection.utils import category_to_detection_name\r\nfrom nuscenes.eval.detection.render import visualize_sample\r\n\r\n\r\n\r\n\r\ncams = ['CAM_FRONT',\r\n 'CAM_FRONT_RIGHT',\r\n 'CAM_BACK_RIGHT',\r\n 'CAM_BACK',\r\n 'CAM_BACK_LEFT',\r\n 'CAM_FRONT_LEFT']\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud, Box\r\nfrom PIL import Image\r\nfrom matplotlib import rcParams\r\n\r\n\r\ndef render_annotation(\r\n anntoken: str,\r\n margin: float = 10,\r\n view: np.ndarray = np.eye(4),\r\n box_vis_level: BoxVisibility = BoxVisibility.ANY,\r\n out_path: str = 'render.png',\r\n extra_info: bool = False) -> None:\r\n \"\"\"\r\n Render selected annotation.\r\n :param anntoken: Sample_annotation token.\r\n :param margin: How many meters in each direction to include in LIDAR view.\r\n :param view: LIDAR view point.\r\n :param box_vis_level: If sample_data is an image, this sets required visibility for boxes.\r\n :param out_path: Optional path to save the rendered figure to disk.\r\n :param extra_info: Whether to render extra information below camera view.\r\n \"\"\"\r\n ann_record = nusc.get('sample_annotation', anntoken)\r\n sample_record = nusc.get('sample', ann_record['sample_token'])\r\n assert 'LIDAR_TOP' in sample_record['data'].keys(), 'Error: No LIDAR_TOP in data, unable to render.'\r\n\r\n # Figure out which camera the object is fully visible in (this may return nothing).\r\n boxes, cam = [], []\r\n cams = [key for key in sample_record['data'].keys() if 'CAM' in key]\r\n all_bboxes = []\r\n select_cams = []\r\n for cam in cams:\r\n _, boxes, _ = nusc.get_sample_data(sample_record['data'][cam], box_vis_level=box_vis_level,\r\n selected_anntokens=[anntoken])\r\n if len(boxes) > 0:\r\n all_bboxes.append(boxes)\r\n select_cams.append(cam)\r\n # We found an image that matches. Let's abort.\r\n # assert len(boxes) > 0, 'Error: Could not find image where annotation is visible. ' \\\r\n # 'Try using e.g. BoxVisibility.ANY.'\r\n # assert len(boxes) < 2, 'Error: Found multiple annotations. Something is wrong!'\r\n\r\n num_cam = len(all_bboxes)\r\n\r\n fig, axes = plt.subplots(1, num_cam + 1, figsize=(18, 9))\r\n select_cams = [sample_record['data'][cam] for cam in select_cams]\r\n print('bbox in cams:', select_cams)\r\n # Plot LIDAR view.\r\n lidar = sample_record['data']['LIDAR_TOP']\r\n data_path, boxes, camera_intrinsic = nusc.get_sample_data(lidar, selected_anntokens=[anntoken])\r\n LidarPointCloud.from_file(data_path).render_height(axes[0], view=view)\r\n for box in boxes:\r\n c = np.array(get_color(box.name)) / 255.0\r\n box.render(axes[0], view=view, colors=(c, c, c))\r\n corners = view_points(boxes[0].corners(), view, False)[:2, :]\r\n axes[0].set_xlim([np.min(corners[0, :]) - margin, np.max(corners[0, :]) + margin])\r\n axes[0].set_ylim([np.min(corners[1, :]) - margin, np.max(corners[1, :]) + margin])\r\n axes[0].axis('off')\r\n axes[0].set_aspect('equal')\r\n\r\n # Plot CAMERA view.\r\n for i in range(1, num_cam + 1):\r\n cam = select_cams[i - 1]\r\n data_path, boxes, camera_intrinsic = nusc.get_sample_data(cam, selected_anntokens=[anntoken])\r\n im = Image.open(data_path)\r\n axes[i].imshow(im)\r\n axes[i].set_title(nusc.get('sample_data', cam)['channel'])\r\n axes[i].axis('off')\r\n axes[i].set_aspect('equal')\r\n for box in boxes:\r\n c = np.array(get_color(box.name)) / 255.0\r\n box.render(axes[i], view=camera_intrinsic, normalize=True, colors=(c, c, c))\r\n\r\n # Print extra information about the annotation below the camera view.\r\n axes[i].set_xlim(0, im.size[0])\r\n axes[i].set_ylim(im.size[1], 0)\r\n\r\n if extra_info:\r\n rcParams['font.family'] = 'monospace'\r\n\r\n w, l, h = ann_record['size']\r\n category = ann_record['category_name']\r\n lidar_points = ann_record['num_lidar_pts']\r\n radar_points = ann_record['num_radar_pts']\r\n\r\n sample_data_record = nusc.get('sample_data', sample_record['data']['LIDAR_TOP'])\r\n pose_record = nusc.get('ego_pose', sample_data_record['ego_pose_token'])\r\n dist = np.linalg.norm(np.array(pose_record['translation']) - np.array(ann_record['translation']))\r\n\r\n information = ' \\n'.join(['category: {}'.format(category),\r\n '',\r\n '# lidar points: {0:>4}'.format(lidar_points),\r\n '# radar points: {0:>4}'.format(radar_points),\r\n '',\r\n 'distance: {:>7.3f}m'.format(dist),\r\n '',\r\n 'width: {:>7.3f}m'.format(w),\r\n 'length: {:>7.3f}m'.format(l),\r\n 'height: {:>7.3f}m'.format(h)])\r\n\r\n plt.annotate(information, (0, 0), (0, -20), xycoords='axes fraction', textcoords='offset points', va='top')\r\n\r\n if out_path is not None:\r\n plt.savefig(out_path)\r\n\r\n\r\n\r\ndef get_sample_data(sample_data_token: str,\r\n box_vis_level: BoxVisibility = BoxVisibility.ANY,\r\n selected_anntokens=None,\r\n use_flat_vehicle_coordinates: bool = False):\r\n \"\"\"\r\n Returns the data path as well as all annotations related to that sample_data.\r\n Note that the boxes are transformed into the current sensor's coordinate frame.\r\n :param sample_data_token: Sample_data token.\r\n :param box_vis_level: If sample_data is an image, this sets required visibility for boxes.\r\n :param selected_anntokens: If provided only return the selected annotation.\r\n :param use_flat_vehicle_coordinates: Instead of the current sensor's coordinate frame, use ego frame which is\r\n aligned to z-plane in the world.\r\n :return: (data_path, boxes, camera_intrinsic )\r\n \"\"\"\r\n\r\n # Retrieve sensor & pose records\r\n sd_record = nusc.get('sample_data', sample_data_token)\r\n cs_record = nusc.get('calibrated_sensor', sd_record['calibrated_sensor_token'])\r\n sensor_record = nusc.get('sensor', cs_record['sensor_token'])\r\n pose_record = nusc.get('ego_pose', sd_record['ego_pose_token'])\r\n\r\n data_path = nusc.get_sample_data_path(sample_data_token)\r\n\r\n if sensor_record['modality'] == 'camera':\r\n cam_intrinsic = np.array(cs_record['camera_intrinsic'])\r\n imsize = (sd_record['width'], sd_record['height'])\r\n else:\r\n cam_intrinsic = None\r\n imsize = None\r\n\r\n # Retrieve all sample annotations and map to sensor coordinate system.\r\n if selected_anntokens is not None:\r\n boxes = list(map(nusc.get_box, selected_anntokens))\r\n else:\r\n boxes = nusc.get_boxes(sample_data_token)\r\n\r\n # Make list of Box objects including coord system transforms.\r\n box_list = []\r\n for box in boxes:\r\n if use_flat_vehicle_coordinates:\r\n # Move box to ego vehicle coord system parallel to world z plane.\r\n yaw = Quaternion(pose_record['rotation']).yaw_pitch_roll[0]\r\n box.translate(-np.array(pose_record['translation']))\r\n box.rotate(Quaternion(scalar=np.cos(yaw / 2), vector=[0, 0, np.sin(yaw / 2)]).inverse)\r\n else:\r\n # Move box to ego vehicle coord system.\r\n box.translate(-np.array(pose_record['translation']))\r\n box.rotate(Quaternion(pose_record['rotation']).inverse)\r\n\r\n # Move box to sensor coord system.\r\n box.translate(-np.array(cs_record['translation']))\r\n box.rotate(Quaternion(cs_record['rotation']).inverse)\r\n\r\n if sensor_record['modality'] == 'camera' and not \\\r\n box_in_image(box, cam_intrinsic, imsize, vis_level=box_vis_level):\r\n continue\r\n\r\n box_list.append(box)\r\n\r\n return data_path, box_list, cam_intrinsic\r\n\r\n\r\n\r\ndef get_predicted_data(sample_data_token: str,\r\n box_vis_level: BoxVisibility = BoxVisibility.ANY,\r\n selected_anntokens=None,\r\n use_flat_vehicle_coordinates: bool = False,\r\n pred_anns=None\r\n ):\r\n \"\"\"\r\n Returns the data path as well as all annotations related to that sample_data.\r\n Note that the boxes are transformed into the current sensor's coordinate frame.\r\n :param sample_data_token: Sample_data token.\r\n :param box_vis_level: If sample_data is an image, this sets required visibility for boxes.\r\n :param selected_anntokens: If provided only return the selected annotation.\r\n :param use_flat_vehicle_coordinates: Instead of the current sensor's coordinate frame, use ego frame which is\r\n aligned to z-plane in the world.\r\n :return: (data_path, boxes, camera_intrinsic )\r\n \"\"\"\r\n\r\n # Retrieve sensor & pose records\r\n sd_record = nusc.get('sample_data', sample_data_token)\r\n cs_record = nusc.get('calibrated_sensor', sd_record['calibrated_sensor_token'])\r\n sensor_record = nusc.get('sensor', cs_record['sensor_token'])\r\n pose_record = nusc.get('ego_pose', sd_record['ego_pose_token'])\r\n\r\n data_path = nusc.get_sample_data_path(sample_data_token)\r\n\r\n if sensor_record['modality'] == 'camera':\r\n cam_intrinsic = np.array(cs_record['camera_intrinsic'])\r\n imsize = (sd_record['width'], sd_record['height'])\r\n else:\r\n cam_intrinsic = None\r\n imsize = None\r\n\r\n # Retrieve all sample annotations and map to sensor coordinate system.\r\n # if selected_anntokens is not None:\r\n # boxes = list(map(nusc.get_box, selected_anntokens))\r\n # else:\r\n # boxes = nusc.get_boxes(sample_data_token)\r\n boxes = pred_anns\r\n # Make list of Box objects including coord system transforms.\r\n box_list = []\r\n for box in boxes:\r\n if use_flat_vehicle_coordinates:\r\n # Move box to ego vehicle coord system parallel to world z plane.\r\n yaw = Quaternion(pose_record['rotation']).yaw_pitch_roll[0]\r\n box.translate(-np.array(pose_record['translation']))\r\n box.rotate(Quaternion(scalar=np.cos(yaw / 2), vector=[0, 0, np.sin(yaw / 2)]).inverse)\r\n else:\r\n # Move box to ego vehicle coord system.\r\n box.translate(-np.array(pose_record['translation']))\r\n box.rotate(Quaternion(pose_record['rotation']).inverse)\r\n\r\n # Move box to sensor coord system.\r\n box.translate(-np.array(cs_record['translation']))\r\n box.rotate(Quaternion(cs_record['rotation']).inverse)\r\n\r\n if sensor_record['modality'] == 'camera' and not \\\r\n box_in_image(box, cam_intrinsic, imsize, vis_level=box_vis_level):\r\n continue\r\n box_list.append(box)\r\n\r\n return data_path, box_list, cam_intrinsic\r\n\r\n\r\n\r\n\r\ndef lidiar_render(sample_token, data,out_path=None):\r\n bbox_gt_list = []\r\n bbox_pred_list = []\r\n anns = nusc.get('sample', sample_token)['anns']\r\n for ann in anns:\r\n content = nusc.get('sample_annotation', ann)\r\n try:\r\n bbox_gt_list.append(DetectionBox(\r\n sample_token=content['sample_token'],\r\n translation=tuple(content['translation']),\r\n size=tuple(content['size']),\r\n rotation=tuple(content['rotation']),\r\n velocity=nusc.box_velocity(content['token'])[:2],\r\n ego_translation=(0.0, 0.0, 0.0) if 'ego_translation' not in content\r\n else tuple(content['ego_translation']),\r\n num_pts=-1 if 'num_pts' not in content else int(content['num_pts']),\r\n detection_name=category_to_detection_name(content['category_name']),\r\n detection_score=-1.0 if 'detection_score' not in content else float(content['detection_score']),\r\n attribute_name=''))\r\n except:\r\n pass\r\n\r\n bbox_anns = data['results'][sample_token]\r\n for content in bbox_anns:\r\n bbox_pred_list.append(DetectionBox(\r\n sample_token=content['sample_token'],\r\n translation=tuple(content['translation']),\r\n size=tuple(content['size']),\r\n rotation=tuple(content['rotation']),\r\n velocity=tuple(content['velocity']),\r\n ego_translation=(0.0, 0.0, 0.0) if 'ego_translation' not in content\r\n else tuple(content['ego_translation']),\r\n num_pts=-1 if 'num_pts' not in content else int(content['num_pts']),\r\n detection_name=content['detection_name'],\r\n detection_score=-1.0 if 'detection_score' not in content else float(content['detection_score']),\r\n attribute_name=content['attribute_name']))\r\n gt_annotations = EvalBoxes()\r\n pred_annotations = EvalBoxes()\r\n gt_annotations.add_boxes(sample_token, bbox_gt_list)\r\n pred_annotations.add_boxes(sample_token, bbox_pred_list)\r\n print('green is ground truth')\r\n print('blue is the predited result')\r\n visualize_sample(nusc, sample_token, gt_annotations, pred_annotations, savepath=out_path+'_bev')\r\n\r\n\r\ndef get_color(category_name: str):\r\n \"\"\"\r\n Provides the default colors based on the category names.\r\n This method works for the general nuScenes categories, as well as the nuScenes detection categories.\r\n \"\"\"\r\n a = ['noise', 'animal', 'human.pedestrian.adult', 'human.pedestrian.child', 'human.pedestrian.construction_worker',\r\n 'human.pedestrian.personal_mobility', 'human.pedestrian.police_officer', 'human.pedestrian.stroller',\r\n 'human.pedestrian.wheelchair', 'movable_object.barrier', 'movable_object.debris',\r\n 'movable_object.pushable_pullable', 'movable_object.trafficcone', 'static_object.bicycle_rack', 'vehicle.bicycle',\r\n 'vehicle.bus.bendy', 'vehicle.bus.rigid', 'vehicle.car', 'vehicle.construction', 'vehicle.emergency.ambulance',\r\n 'vehicle.emergency.police', 'vehicle.motorcycle', 'vehicle.trailer', 'vehicle.truck', 'flat.driveable_surface',\r\n 'flat.other', 'flat.sidewalk', 'flat.terrain', 'static.manmade', 'static.other', 'static.vegetation',\r\n 'vehicle.ego']\r\n class_names = [\r\n 'car', 'truck', 'construction_vehicle', 'bus', 'trailer', 'barrier',\r\n 'motorcycle', 'bicycle', 'pedestrian', 'traffic_cone'\r\n ]\r\n #print(category_name)\r\n if category_name == 'bicycle':\r\n return nusc.colormap['vehicle.bicycle']\r\n elif category_name == 'construction_vehicle':\r\n return nusc.colormap['vehicle.construction']\r\n elif category_name == 'traffic_cone':\r\n return nusc.colormap['movable_object.trafficcone']\r\n\r\n for key in nusc.colormap.keys():\r\n if category_name in key:\r\n return nusc.colormap[key]\r\n return [0, 0, 0]\r\n\r\n\r\ndef render_sample_data(\r\n sample_toekn: str,\r\n with_anns: bool = True,\r\n box_vis_level: BoxVisibility = BoxVisibility.ANY,\r\n axes_limit: float = 40,\r\n ax=None,\r\n nsweeps: int = 1,\r\n out_path: str = None,\r\n underlay_map: bool = True,\r\n use_flat_vehicle_coordinates: bool = True,\r\n show_lidarseg: bool = False,\r\n show_lidarseg_legend: bool = False,\r\n filter_lidarseg_labels=None,\r\n lidarseg_preds_bin_path: str = None,\r\n verbose: bool = True,\r\n show_panoptic: bool = False,\r\n pred_data=None,\r\n ) -> None:\r\n \"\"\"\r\n Render sample data onto axis.\r\n :param sample_data_token: Sample_data token.\r\n :param with_anns: Whether to draw box annotations.\r\n :param box_vis_level: If sample_data is an image, this sets required visibility for boxes.\r\n :param axes_limit: Axes limit for lidar and radar (measured in meters).\r\n :param ax: Axes onto which to render.\r\n :param nsweeps: Number of sweeps for lidar and radar.\r\n :param out_path: Optional path to save the rendered figure to disk.\r\n :param underlay_map: When set to true, lidar data is plotted onto the map. This can be slow.\r\n :param use_flat_vehicle_coordinates: Instead of the current sensor's coordinate frame, use ego frame which is\r\n aligned to z-plane in the world. Note: Previously this method did not use flat vehicle coordinates, which\r\n can lead to small errors when the vertical axis of the global frame and lidar are not aligned. The new\r\n setting is more correct and rotates the plot by ~90 degrees.\r\n :param show_lidarseg: When set to True, the lidar data is colored with the segmentation labels. When set\r\n to False, the colors of the lidar data represent the distance from the center of the ego vehicle.\r\n :param show_lidarseg_legend: Whether to display the legend for the lidarseg labels in the frame.\r\n :param filter_lidarseg_labels: Only show lidar points which belong to the given list of classes. If None\r\n or the list is empty, all classes will be displayed.\r\n :param lidarseg_preds_bin_path: A path to the .bin file which contains the user's lidar segmentation\r\n predictions for the sample.\r\n :param verbose: Whether to display the image after it is rendered.\r\n :param show_panoptic: When set to True, the lidar data is colored with the panoptic labels. When set\r\n to False, the colors of the lidar data represent the distance from the center of the ego vehicle.\r\n If show_lidarseg is True, show_panoptic will be set to False.\r\n \"\"\"\r\n lidiar_render(sample_toekn, pred_data, out_path=out_path)\r\n sample = nusc.get('sample', sample_toekn)\r\n # sample = data['results'][sample_token_list[0]][0]\r\n cams = [\r\n 'CAM_FRONT_LEFT',\r\n 'CAM_FRONT',\r\n 'CAM_FRONT_RIGHT',\r\n 'CAM_BACK_LEFT',\r\n 'CAM_BACK',\r\n 'CAM_BACK_RIGHT',\r\n ]\r\n if ax is None:\r\n _, ax = plt.subplots(4, 3, figsize=(24, 18))\r\n j = 0\r\n for ind, cam in enumerate(cams):\r\n sample_data_token = sample['data'][cam]\r\n\r\n sd_record = nusc.get('sample_data', sample_data_token)\r\n sensor_modality = sd_record['sensor_modality']\r\n\r\n if sensor_modality in ['lidar', 'radar']:\r\n assert False\r\n elif sensor_modality == 'camera':\r\n # Load boxes and image.\r\n boxes = [Box(record['translation'], record['size'], Quaternion(record['rotation']),\r\n name=record['detection_name'], token='predicted') for record in\r\n pred_data['results'][sample_toekn] if record['detection_score'] > 0.2]\r\n\r\n data_path, boxes_pred, camera_intrinsic = get_predicted_data(sample_data_token,\r\n box_vis_level=box_vis_level, pred_anns=boxes)\r\n _, boxes_gt, _ = nusc.get_sample_data(sample_data_token, box_vis_level=box_vis_level)\r\n if ind == 3:\r\n j += 1\r\n ind = ind % 3\r\n data = Image.open(data_path)\r\n # mmcv.imwrite(np.array(data)[:,:,::-1], f'{cam}.png')\r\n # Init axes.\r\n\r\n # Show image.\r\n ax[j, ind].imshow(data)\r\n ax[j + 2, ind].imshow(data)\r\n\r\n # Show boxes.\r\n if with_anns:\r\n for box in boxes_pred:\r\n c = np.array(get_color(box.name)) / 255.0\r\n box.render(ax[j, ind], view=camera_intrinsic, normalize=True, colors=(c, c, c))\r\n for box in boxes_gt:\r\n c = np.array(get_color(box.name)) / 255.0\r\n box.render(ax[j + 2, ind], view=camera_intrinsic, normalize=True, colors=(c, c, c))\r\n\r\n # Limit visible range.\r\n ax[j, ind].set_xlim(0, data.size[0])\r\n ax[j, ind].set_ylim(data.size[1], 0)\r\n ax[j + 2, ind].set_xlim(0, data.size[0])\r\n ax[j + 2, ind].set_ylim(data.size[1], 0)\r\n\r\n else:\r\n raise ValueError(\"Error: Unknown sensor modality!\")\r\n\r\n ax[j, ind].axis('off')\r\n ax[j, ind].set_title('PRED: {} {labels_type}'.format(\r\n sd_record['channel'], labels_type='(predictions)' if lidarseg_preds_bin_path else ''))\r\n ax[j, ind].set_aspect('equal')\r\n\r\n ax[j + 2, ind].axis('off')\r\n ax[j + 2, ind].set_title('GT:{} {labels_type}'.format(\r\n sd_record['channel'], labels_type='(predictions)' if lidarseg_preds_bin_path else ''))\r\n ax[j + 2, ind].set_aspect('equal')\r\n\r\n if out_path is not None:\r\n plt.savefig(out_path+'_camera', bbox_inches='tight', pad_inches=0, dpi=200)\r\n if verbose:\r\n plt.show()\r\n plt.close()\r\n\r\nif __name__ == '__main__':\r\n nusc = NuScenes(version='v1.0-trainval', dataroot='./data/nuscenes', verbose=True)\r\n # render_annotation('7603b030b42a4b1caa8c443ccc1a7d52')\r\n bevformer_results = mmcv.load('test/bevformer_base/Thu_Jun__9_16_22_37_2022/pts_bbox/results_nusc.json')\r\n sample_token_list = list(bevformer_results['results'].keys())\r\n for id in range(0, 10):\r\n render_sample_data(sample_token_list[id], pred_data=bevformer_results, out_path=sample_token_list[id])\r\n","repo_name":"fundamentalvision/BEVFormer","sub_path":"tools/analysis_tools/visual.py","file_name":"visual.py","file_ext":"py","file_size_in_byte":22347,"program_lang":"python","lang":"en","doc_type":"code","stars":2428,"dataset":"github-code","pt":"86"} +{"seq_id":"41358609733","text":"import cv2 as cv\n\n\ndef main():\n\n\n im = cv.imread(\"iiimg/IMG_1673.jpg\")\n\n gray = cv.CreateImage(cv.GetSize(im), 8, 1)\n edges = cv.CreateImage(cv.GetSize(im), 8, 1)\n\n cv.CvtColor(im, gray, cv.CV_BGR2GRAY)\n cv.Canny(gray, edges, 50, 200, 3)\n cv.Smooth(gray, gray, cv.CV_GAUSSIAN, 9, 9)\n\n storage = cv.CreateMat(im.rows, 1, cv.CV_32FC3)\n\n cv.HoughCircles(edges, storage, cv.CV_HOUGH_GRADIENT, 2, gray.height/4, 200, 100)\n # Now, supposing it found circles, how do I extract the information?\n print(storage.r)\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"MikeYou/opencv_practice","sub_path":"OpenCV_bubble3.py","file_name":"OpenCV_bubble3.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"24626976511","text":"import os\nfrom typing import List\nimport torch\nfrom utils import SobelOperator\nfrom diffusers import (\n StableDiffusionControlNetImg2ImgPipeline,\n ControlNetModel,\n LCMScheduler,\n)\nfrom compel import Compel\nfrom PIL import Image\nimport numpy as np\nfrom inputparams import InputParams\nimport os\n\n\n\nfrom cog import BasePredictor, Input, Path\n\n\nMODEL_CACHE = \"weights_cache\"\n\n\nclass Predictor(BasePredictor):\n def setup(self) -> None:\n \"\"\"Load the model into memory to make running multiple predictions efficient\"\"\"\n # check if MPS is available OSX only M1/M2/M3 chips\n device = \"cuda:0\"\n # change to torch.float16 to save GPU memory\n torch_dtype = torch.float16\n\n self.controlnet_canny = ControlNetModel.from_pretrained(\n \"lllyasviel/control_v11p_sd15_canny\", torch_dtype=torch_dtype\n ).to(device)\n\n self.canny_torch = SobelOperator(device=device)\n\n model_id = \"Linaqruf/anything-v3.0\"\n lcm_lora_id = \"latent-consistency/lcm-lora-sdv1-5\"\n\n self.pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(\n model_id,\n safety_checker=None,\n controlnet=self.controlnet_canny\n )\n\n self.pipe.scheduler = LCMScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.set_progress_bar_config(disable=True)\n self.pipe.to(device=device, dtype=torch_dtype).to(device)\n self.pipe.unet.to(memory_format=torch.channels_last)\n\n self.pipe.load_lora_weights(lcm_lora_id)\n self.pipe.load_lora_weights(\"/root\", weight_name=\"pixel_portraits.safetensors\", adapter_name=\"pixell\")\n self.pipe.set_adapters([\"lora\", \"pixell\"], adapter_weights=[1.0, 1.0])\n\n self.pipe.to(device=device, dtype=torch.float16)\n\n self.compel_proc = Compel(\n tokenizer=self.pipe.tokenizer,\n text_encoder=self.pipe.text_encoder,\n truncate_long_prompts=False,\n )\n\n def predict(\n self,\n image: Path = Input(\n description=\"Input image\",\n default=\"\",\n ),\n prompt: str = Input(\n description=\"Input prompt\",\n default=\"A person, pixel art\",\n ),\n negative_prompt: str = Input(\n description=\"Specify things to not see in the output\",\n default=\"bad quality, low quality\",\n ),\n strength: float = Input(\n description=\"Denoising strength\", ge=0.0, le=1.0, default=0.5\n ),\n guidance_scale: float = Input(\n description=\"CFG scale for guidance\",\n ge=0.0, le=10.0, default=8.0\n ),\n num_inference_steps: int = Input(\n description=\"Number of inference steps\", ge=1, le=50, default=10\n ),\n seed: int = Input(\n description=\"Random seed. Leave blank to randomize the seed\", default=42\n ),\n canny_low_threshold: float = Input(\n description=\"Canny low threshold\", ge=0.0, le=1.0, default=0.31\n ),\n canny_high_threshold: float = Input(\n description=\"Canny high threshold\", ge=0.0, le=1.0, default=0.78\n ),\n controlnet_scale: float = Input(\n description=\"Controlnet scale\", ge=0.0, le=1.0, default=0.8\n ),\n controlnet_start: float = Input(\n description=\"Controlnet start\", ge=0.0, le=1.0, default=0.0\n ),\n controlnet_end: float = Input(\n description=\"Controlnet end\", ge=0.0, le=1.0, default=1.0\n ),\n ) -> List[Path]:\n \"\"\"Run a single prediction on the model\"\"\"\n lcm_steps = 50\n\n if seed is None:\n seed = int.from_bytes(os.urandom(2), \"big\")\n input_image = Image.open(str(image))\n min_dim = min(input_image.size)\n #resizing to square shape because of `RuntimeError: The size of tensor a (_X_) must match the size of tensor b (_Y_) at non-singleton dimension 3` error for non-square images\n input_image = input_image.resize((min_dim,min_dim))\n height = input_image.size[0]\n width = input_image.size[1]\n\n prompt_embeds = self.compel_proc(prompt)\n\n generator = torch.manual_seed(seed)\n\n control_image = self.canny_torch(\n input_image, canny_low_threshold, canny_high_threshold\n )\n results = self.pipe(\n control_image=control_image,\n prompt_embeds=prompt_embeds,\n negative_prompt=negative_prompt,\n generator=generator,\n image=input_image,\n strength=strength,\n num_inference_steps=num_inference_steps,\n guidance_scale=guidance_scale,\n width=width,\n height=height,\n output_type=\"pil\",\n controlnet_conditioning_scale=controlnet_scale,\n control_guidance_start=controlnet_start,\n control_guidance_end=controlnet_end,\n )\n result_image = results.images[0]\n\n return result_image\n","repo_name":"tripathiarpan20/lcm-pixel-portrait-replicate","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"37186777556","text":"class Solution(object):\n def coinChange(self, coins, amount):\n \"\"\"\n :type coins: List[int]\n :type amount: int\n :rtype: int\n \"\"\"\n if amount < 1:\n return 0\n m_rel = [0] * (amount+1)\n\n for i in range(1, amount+1):\n cur_min = -1\n for coin in coins:\n if i >= coin and m_rel[i-coin] != -1:\n tmp_min = 1 + m_rel[i-coin]\n if cur_min == -1:\n cur_min = tmp_min\n else:\n cur_min = tmp_min if tmp_min < cur_min else cur_min\n m_rel[i] = cur_min\n return m_rel[amount]\n\nc = Solution()\nprint(c.coinChange([1, 2, 5], 11))\n","repo_name":"xkoma007/leetcode","sub_path":"322CoinChange.py","file_name":"322CoinChange.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"86"} +{"seq_id":"2877075656","text":"import re\nimport os\nfrom gensim.test.utils import datapath\nfrom gensim.models.word2vec import Text8Corpus\nfrom gensim.models.phrases import Phrases, Phraser\nfrom collections import Counter\nfrom googletrans import Translator\nimport random\nimport faiss\nfrom sklearn import preprocessing\nimport numpy as np\nfrom gensim.models.word2vec import Word2Vec, LineSentence\nfrom gensim.models import KeyedVectors\nfrom gensim.test.utils import get_tmpfile\nimport logging\n\n\n#------------------------------Evaluation------------------------------------\n\ndef evaluate(test_matrix_src, test_matrix_tgt, W, normalize=True, precisions=[1, 5, 10]):\n test_matrix_tgt_projected = test_matrix_src @ W\n test_matrix_tgt_base = test_matrix_tgt\n\n # L2-norm normalization and Euclidean distance search are quadratically proportional to cosine distance\n # -> norm=True (cosine distance/similarity), norm=False (euclidean distance)\n if normalize:\n test_matrix_tgt_projected = preprocessing.normalize(test_matrix_tgt_projected, axis=1, norm='l2')\n test_matrix_tgt_base = preprocessing.normalize(test_matrix_tgt_base, axis=1, norm='l2')\n\n size_tgt = test_matrix_tgt_projected.shape[1]\n index = faiss.IndexFlatL2(size_tgt)\n index.add(test_matrix_tgt_base.astype(np.float32))\n D, I = index.search(test_matrix_tgt_projected.astype(np.float32), 20)\n\n topks = np.zeros(len(precisions))\n for i, k in enumerate(precisions):\n for j in range(I.shape[0]):\n if j in I[j, :k]:\n topks[i] += 1\n\n topks /= (I.shape[0])\n\n for i, prec in enumerate(precisions):\n print(\"The precision@\", prec, \"is:\", np.round(topks[i], 4))\n\n return topks\n\n#----------------------------Lexicon---------------------------\n\ndef get_lexicon(word_vector_tgt: KeyedVectors, src=\"en\", tgt=\"es\", k=5000):\n '''\n Given source and target language, returns a lexicon for the k most frequent\n source words plus additional 1000 for testing using Google Translate\n '''\n # read source corpus\n with open(\"training-monolingual/news.2011.{}.shuffled.tokenized.lowercased.preprocessed.collocation\".format(src),\n 'r') as src_file:\n src_corpus = []\n for i, line in enumerate(src_file):\n src_corpus += line.split()\n\n # get top k frequent words and translations via GT\n counts = Counter(src_corpus)\n counts_sorted = [(l, k) for k, l in sorted([(j, i) for i, j in counts.items()], reverse=True)]\n sorted_words = [wc[0] for wc in counts_sorted]\n lexicon = []\n\n errors = 0\n success = 0\n\n for word in sorted_words:\n translator = Translator()\n translation = translator.translate(word, src=src, dest=tgt).text\n\n try:\n if isinstance(word_vector_tgt[translation.lower()], np.ndarray):\n lexicon.append((word, translation.lower()))\n success += 1\n if success % (k / 10) == 0:\n print(\"Success:\", success)\n\n except KeyError:\n errors += 1\n\n if success == k + 500:\n break\n\n print(\"Total errors\", errors)\n # get training lexicon for linear projection and test lexicon for evaluation\n\n train_lexicon = lexicon[:k]\n test_lexicon = lexicon[k:]\n\n return train_lexicon, test_lexicon\n\ndef get_sublexicon(train_lexicon, test_lexicon, k=2092, test_size=500):\n '''\n Get sublexicon with smaller dimensions for comparability with knowledge graph experiments\n '''\n random.shuffle(train_lexicon)\n random.shuffle(test_lexicon)\n return train_lexicon[:k], test_lexicon[:test_size]\n\n #-------------------------Preprocessing-----------------------------\n\ndef preprocess(filepath):\n '''Creates corpus remedied for punctuation and numerical variation'''\n file = open(filepath, 'rt')\n corpus = file.read()\n file.close()\n\n # remove punctuation\n del_tokens = str.maketrans('', '', '!\"#$%&\\'()*+-/:;<=>?@[\\\\]^_`{|}~')\n corpus = corpus.translate(del_tokens)\n\n # unification of numerical characters\n corpus = re.sub(r\"[-+]?\\d*\\.\\d+|\\d+\", \"NUM\", corpus)\n\n outfile = open(filepath + \".preprocessed\", \"w\")\n\n for line in corpus:\n outfile.write(line)\n\n outfile.close()\n\n\ndef collocation(filepath):\n '''Creates corpus considering collocations, frequent co-occuring bigrams are merged (new york -> new_york)'''\n\n abs_path = os.getcwd() + \"/\"\n corpus = Text8Corpus(datapath(abs_path + filepath))\n phrases = Phrases(corpus)\n collocations = Phraser(phrases)\n text_list = [collocations[line] for line in corpus]\n flattened_list = [i for sub in text_list for i in sub]\n flattened_corpus = \" \".join(flattened_list)\n\n outfile = open(filepath + \".collocation\", \"w\")\n\n for line in flattened_corpus:\n outfile.write(line)\n\n outfile.close()\n\n#--------------------------------------------------------------------------\n\ndef get_emb_matrices(word_vector_src : KeyedVectors, word_vector_tgt : KeyedVectors, lexicon, size_src=800, size_tgt=200, norm_bf=True):\n k = len(lexicon)\n emb_matrix_src = np.zeros((k, size_src))\n emb_matrix_tgt = np.zeros((k, size_tgt))\n\n for i, src_tgt in enumerate(lexicon):\n emb_matrix_src[i, :] = word_vector_src[src_tgt[0]]\n emb_matrix_tgt[i, :] = word_vector_tgt[src_tgt[1]]\n\n if norm_bf:\n emb_matrix_src = preprocessing.normalize(emb_matrix_src, axis=1, norm='l2')\n emb_matrix_tgt = preprocessing.normalize(emb_matrix_tgt, axis=1, norm='l2')\n\n return emb_matrix_src, emb_matrix_tgt\n\ndef get_KeyVec(src = \"en\", tgt = \"es\", size_src=800, size_tgt=200, window=10, create=False, save=True, KG=False):\n '''\n :param src: source language\n :param tgt: target language\n :param size_src: embedding dimension for source language\n :param size_tgt: embedding dimension for target language\n :param window: window size\n :param create: bool - set to True if you want to create KeyedVectors, else KeyedVectors will be loaded\n :param save: bool - if create=True -> set save=True to save created KeyedVectors\n :return: source & target language KeyedVectors\n '''\n abs_path = os.getcwd() + \"/\"\n if KG:\n datapath_src = 'rwalks/rwalk_' + src + \".txt\"\n datapath_tgt = 'rwalks/rwalk_' + tgt + \".txt\"\n\n else:\n datapath_src = 'training-monolingual/news.2011.{}.shuffled.tokenized.lowercased.preprocessed.collocation'.format(src) # , limit=100000)\n datapath_tgt = 'training-monolingual/news.2011.{}.shuffled.tokenized.lowercased.preprocessed.collocation'.format(tgt) # , limit=100000)\n\n source_sentences = LineSentence(datapath_src) # , limit=100000)\n target_sentences = LineSentence(datapath_tgt) # , limit=100000)\n\n if not os.path.exists(\"training-monolingual/kv\"):\n os.makedirs(\"training-monolingual/kv\")\n\n kv_filename_src = abs_path + \"training-monolingual/kv/keyvec_src-{}_dim{}_ws{}.kv\".format(src, size_src, window)\n kv_filename_tgt = abs_path + \"training-monolingual/kv/keyvec_tgt-{}_dim{}_ws{}.kv\".format(tgt, size_tgt, window)\n vecfile_src = get_tmpfile(kv_filename_src)\n vecfile_tgt = get_tmpfile(kv_filename_tgt)\n\n if create:\n source_embedding = Word2Vec(source_sentences, size = size_src, window = window) # generates the word2vec embeddings\n target_embedding = Word2Vec(target_sentences, size = size_tgt, window = window) # generates the word2vec embeddings\n kv_src = source_embedding.wv\n kv_tgt = target_embedding.wv\n\n\n if save:\n kv_src.save(vecfile_src)\n kv_tgt.save(vecfile_tgt)\n\n else:\n assert(os.path.isfile(kv_filename_src) & os.path.isfile(kv_filename_tgt))\n kv_src = KeyedVectors.load(vecfile_src, mmap='r')\n kv_tgt = KeyedVectors.load(vecfile_tgt, mmap='r')\n\n return kv_src, kv_tgt","repo_name":"lschuell/kbp","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7810,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"86"} +{"seq_id":"42194193610","text":"from django.urls import path\nfrom portalapp import views\n\nurlpatterns = [\n path('', views.login, name='login'),\n path('home/', views.home, name='portal'),\n path('submission/', views.submit_task, name='submit_task'),\n path('form/', views.form_data, name='form_data'),\n path('success/', views.form_input, name='form_input'),\n]\n","repo_name":"ACE-VSIT/acewebsite-2018","sub_path":"portalapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"86"} +{"seq_id":"20968624869","text":"# Problem:\n# Write a function to find the longest common prefix string amongst an array of strings.\n# If there is no common prefix, return an empty string \"\".\n#\n# Example:\n# Input: [\"flower\",\"flow\",\"flight\"]\n# Output: \"fl\"\n#\n\n\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if len(strs) == 0:\n return ''\n\n if len(strs) == 1:\n return strs[0]\n\n base_str = strs[0]\n rest_strs = strs[1:]\n\n temp_prefix = ''\n result = ''\n for i in range(len(base_str)):\n temp_prefix += base_str[i]\n if len([ s for s in rest_strs if s.startswith(temp_prefix)]) == len(rest_strs):\n result += base_str[i]\n else:\n break\n\n return result\n\n # horizontal scanning\n def logest_common_prefix_2(self, strs: List[str]) -> str:\n if len(strs) == 0:\n return ''\n\n prefix = strs[0]\n for current_str in strs[1:]:\n while current_str.find(prefix) != 0:\n prefix = prefix[:len(prefix)-1]\n if len(prefix) == 0:\n return ''\n return prefix\n\n\n # divide and conquer\n def longest_common_prefix_3(self, strs: List[str]) -> str:\n def common_prefix(left: str, right: str) -> str:\n min_length = min(len(left), len(right))\n for i in range(min_length):\n if left[i] != right[i]:\n return left[:i]\n return left[:min_length]\n\n def divide_and_conquer(strs: List[str], left_index: int, right_index: int) -> str:\n if (left_index == right_index):\n return strs[left_index]\n\n middle = (l + r) // 2\n lcp_left = divide_and_conquer(strs, l, middle)\n lcp_right = divide_and_conquer(strs, middle+1, right_index)\n\n return common_prefix(lcp_left, lcp_right)\n\n if len(strs) == 0:\n return ''\n\n return divide_and_conquer(strs, 0, len(strs) - 1)","repo_name":"y0ssi10/leetcode","sub_path":"python/longest_common_prefix/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"22094981727","text":"import os\nimport requests\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse\n\n\nclass WebScraper:\n def __init__(self, url):\n self.url = url\n self.domain = urlparse(url).netloc\n self.links_file = os.path.join('scrapped_data', f'{self.domain}.txt')\n self.images_file = os.path.join(\n 'scrapped_data', f'{self.domain}_img.txt')\n\n # Create a directory for scraped data if it doesn't exist\n if not os.path.exists('scrapped_data'):\n os.makedirs('scrapped_data')\n\n def scrape_links(self):\n # Send HTTP request\n response = requests.get(self.url)\n\n # Parse HTML content with Beautiful Soup\n soup = BeautifulSoup(response.content, 'html.parser')\n\n # Find all links on the page\n links = soup.find_all('a')\n\n # Save link URLs and text to a file\n with open(self.links_file, 'w', encoding='utf-8') as f:\n for link in links:\n f.write(f'URL: {link.get(\"href\")}\\nText: {link.text}\\n')\n\n def scrape_images(self):\n # Send HTTP request\n response = requests.get(self.url)\n\n # Parse HTML content with Beautiful Soup\n soup = BeautifulSoup(response.content, 'html.parser')\n\n # Find all image tags on the page\n images = soup.find_all('img')\n\n # Save image URLs to a file\n with open(self.images_file, 'w', encoding='utf-8') as f:\n for img in images:\n f.write(f'{img.get(\"src\")}\\n')\n\n\n# Example usage\nurl = 'https://www.kibo.school'\nscraper = WebScraper(url)\nscraper.scrape_links()\nscraper.scrape_images()\n","repo_name":"iamfaqeehhokyky/Website-Scrapper","sub_path":"Solution/completed.py","file_name":"completed.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"25732526212","text":"\"\"\"\ncreate hash functions for character-based items such as strings.\n\"\"\"\ndef hash(astring,tablesize):\n sum = 0\n for pos in range(len(astring)):\n sum = sum + ord(astring[pos])\n return sum % tablesize\n\n\"\"\"\nWhen using this hash function, anagrams will always be given the same hash value. \nTo remedy this, we could use the position of the character as a weight. \nOne possible way to use the positional value as a weighting factor. \n\"\"\"\ndef hashwithWeight(astring,tablesize):\n sum = 0\n for pos in range(len(astring)):\n sum = sum + ord(astring[pos])*(pos+1)\n return sum % tablesize\n\nprint(hashwithWeight('cat',11))","repo_name":"huiyanglu/DataStructures","sub_path":"5_5_1_Hash_Functions.py","file_name":"5_5_1_Hash_Functions.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"29015800225","text":"age = int(input(\"Enter your Age : \"))\r\n\r\nif age <= 18:\r\n print(\"You are very young to Invest\")\r\n exit(0)\r\nelif age > 60:\r\n print(\"Sorry, You are not eligible for any plan....\")\r\n exit(0)\r\nelse:\r\n income = int(input(\"Enter your Income : \"))\r\n print(\"Congratulations, Here are some suggestions for you....\")\r\n if age <= 40:\r\n if income >= 200000:\r\n ch = 1\r\n else:\r\n ch = 2\r\n elif age > 40:\r\n ch = 2\r\n\r\nif ch == 1:\r\n print(\"Plan A: Invest in Land\")\r\n print(\"Plan B: Invest in Construction\")\r\n print(\"Plan C: Invest your money in share market \")\r\nif ch == 2:\r\n print(\"Plan A: Invest in Saving and Mutual funds\")\r\n print(\"Plan B: Invest in fix deposit 'Save for further expenditure'\")","repo_name":"gunjala09/TE-Practicals","sub_path":"InvestmentChatbot.py","file_name":"InvestmentChatbot.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"2081623888","text":"__author__ = 'sam'\nfrom django.db import models\nfrom datetime import datetime, timedelta, date\nfrom django.conf import settings\nfrom django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin, AbstractUser\nfrom django.contrib.auth.models import Group as _Group\nfrom django.contrib.sites.models import Site\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\nfrom django.utils.http import int_to_base36, urlsafe_base64_encode\nfrom django.utils.translation import ugettext_lazy as _\nfrom django_extensions.db.fields import (AutoSlugField, CreationDateTimeField, ModificationDateTimeField)\nimport json\nfrom django.template.loader import render_to_string\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.mail import EmailMultiAlternatives\nimport calendar\n\n\nclass User(AbstractBaseUser, PermissionsMixin):\n USERNAME_FIELD = 'username'\n slug = AutoSlugField(unique=True, populate_from=('first_name', 'username',))\n username = models.CharField(_('UserName'), max_length=255, unique=True)\n first_name = models.CharField(_('first name'), max_length=30)\n last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True)\n email = models.EmailField(_('Email'), blank=True, null=True, unique=True)\n \n is_staff = models.BooleanField(_('staff status'), default=False,\n help_text=_('Designates whether the user can log into this admin '\n 'site.'))\n\n date_joined = models.DateTimeField(_('date joined'), default=timezone.now, null=True, blank=True)\n last_action = models.DateTimeField(_('last action'), default=timezone.now)\n is_active = models.BooleanField(_('Is Active'), default=True)\n\n objects = UserManager()\n\n\n class Meta:\n verbose_name = _('user')\n verbose_name_plural = _('users')\n ordering = ['first_name', 'last_name']\n\n @models.permalink\n def get_absolute_url(self):\n return ''\n\n @property\n def avatar_url(self):\n if self.user_avatar:\n return self.user_avatar.name\n return 'placeholder/base-avatar.png'\n\n def get_full_name(self):\n \"\"\"\n Returns the first_name plus the last_name, with a space in between.\n \"\"\"\n if self.first_name and self.last_name:\n full_name = '%s %s' % (self.first_name, self.last_name)\n elif self.first_name:\n full_name = '%s' % (self.first_name,)\n else:\n full_name = '%s' % (self.username, )\n\n return full_name.strip()\n\n def get_short_name(self):\n \"Returns the short name for the user.\"\n return self.first_name\n\n def get_signup_url(self):\n return reverse('signup-profile', kwargs={\n 'uidb36': int_to_base36(self.pk),\n 'token': self.get_token()\n })\n\n\n def __unicode__(self):\n return self.username + \" - \" + str(self.get_full_name())\n\n","repo_name":"samsath/cpcc_backend","sub_path":"src/website/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"34705413954","text":"#\n# @lc app=leetcode.cn id=1004 lang=python3\n#\n# [1004] 最大连续1的个数 III\n#\n# https://leetcode-cn.com/problems/max-consecutive-ones-iii/description/\n#\n# algorithms\n# Medium (55.87%)\n# Likes: 143\n# Dislikes: 0\n# Total Accepted: 20.6K\n# Total Submissions: 36.7K\n# Testcase Example: '[1,1,1,0,0,0,1,1,1,1,0]\\n2'\n#\n# 给定一个由若干 0 和 1 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。\n# \n# 返回仅包含 1 的最长(连续)子数组的长度。\n# \n# \n# \n# 示例 1:\n# \n# 输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2\n# 输出:6\n# 解释: \n# [1,1,1,0,0,1,1,1,1,1,1]\n# 粗体数字从 0 翻转到 1,最长的子数组长度为 6。\n# \n# 示例 2:\n# \n# 输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3\n# 输出:10\n# 解释:\n# [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\n# 粗体数字从 0 翻转到 1,最长的子数组长度为 10。\n# \n# \n# \n# 提示:\n# \n# \n# 1 <= A.length <= 20000\n# 0 <= K <= A.length\n# A[i] 为 0 或 1 \n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def longestOnes(self, A: List[int], K: int) -> int:\n l, r = 0, 0\n max_len = 0\n limit = 0\n\n while r < len(A):\n r_val = A[r]\n if r_val == 0:\n limit += 1\n r += 1\n\n while limit > K:\n l_val = A[l]\n if l_val == 0:\n limit -= 1\n l += 1\n max_len = max(max_len, r - l)\n return max_len\n\n\n \n# @lc code=end\n\n","repo_name":"Jaeker0512/gocrack-algorithm","sub_path":"滑动窗口/1004.最大连续-1-的个数-iii.py","file_name":"1004.最大连续-1-的个数-iii.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"31835383013","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Card',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255, null=True, blank=True)),\n ('card_number', models.CharField(max_length=12, null=True, blank=True)),\n ('description', models.CharField(max_length=255, null=True, blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Deck',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255, unique=True, null=True, blank=True)),\n ('description', models.CharField(max_length=255, null=True, blank=True)),\n ('author', models.CharField(max_length=255, null=True, blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='DeckCard',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('quantity', models.IntegerField()),\n ('card', models.ForeignKey(to='cards.Card')),\n ('deck', models.ForeignKey(to='cards.Deck')),\n ],\n ),\n migrations.AddField(\n model_name='deck',\n name='cards',\n field=models.ManyToManyField(to='cards.Card', through='cards.DeckCard'),\n ),\n ]\n","repo_name":"michaelflip/tcgscape","sub_path":"cards/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"86"} +{"seq_id":"23570247614","text":"from typing import List, Optional, Dict\n\nimport boto3\nimport hashlib\nimport os\nimport subprocess\nimport sys\nimport time\n\nfrom ray_release.byod.build_ray import build_ray\nfrom ray_release.config import RELEASE_PACKAGE_DIR\nfrom ray_release.configs.global_config import get_global_config\nfrom ray_release.logger import logger\nfrom ray_release.test import (\n Test,\n DATAPLANE_ECR_REPO,\n DATAPLANE_ECR_ML_REPO,\n)\n\nDATAPLANE_S3_BUCKET = \"ray-release-automation-results\"\nDATAPLANE_FILENAME = \"dataplane_20230718.tgz\"\nDATAPLANE_DIGEST = \"a3ad426b05f5cf1981fe684ccbffc1dded5e1071a99184d1072b7fc7b4daf8bc\"\nBASE_IMAGE_WAIT_TIMEOUT = 7200\nBASE_IMAGE_WAIT_DURATION = 30\nRELEASE_BYOD_DIR = os.path.join(RELEASE_PACKAGE_DIR, \"ray_release/byod\")\nREQUIREMENTS_BYOD = \"requirements_byod\"\nREQUIREMENTS_ML_BYOD = \"requirements_ml_byod\"\n\n\ndef build_champagne_image(\n ray_version: str,\n python_version: str,\n image_type: str,\n) -> str:\n \"\"\"\n Builds the Anyscale champagne image.\n \"\"\"\n _download_dataplane_build_file()\n env = os.environ.copy()\n env[\"DOCKER_BUILDKIT\"] = \"1\"\n if image_type == \"cpu\":\n ray_project = \"ray\"\n anyscale_repo = DATAPLANE_ECR_REPO\n else:\n ray_project = \"ray-ml\"\n anyscale_repo = DATAPLANE_ECR_ML_REPO\n ray_image = f\"rayproject/{ray_project}:{ray_version}-{python_version}-{image_type}\"\n anyscale_image = (\n f\"{get_global_config()['byod_ecr']}/{anyscale_repo}:champagne-{ray_version}\"\n )\n\n logger.info(f\"Building champagne anyscale image from {ray_image}\")\n with open(DATAPLANE_FILENAME, \"rb\") as build_file:\n subprocess.check_call(\n [\n \"docker\",\n \"build\",\n \"--build-arg\",\n f\"BASE_IMAGE={ray_image}\",\n \"-t\",\n anyscale_image,\n \"-\",\n ],\n stdin=build_file,\n stdout=sys.stderr,\n env=env,\n )\n _validate_and_push(anyscale_image)\n\n return anyscale_image\n\n\ndef build_anyscale_custom_byod_image(test: Test) -> None:\n if not test.require_custom_byod_image():\n logger.info(f\"Test {test.get_name()} does not require a custom byod image\")\n return\n byod_image = test.get_anyscale_byod_image()\n if _byod_image_exist(test, base_image=False):\n logger.info(f\"Image {byod_image} already exists\")\n return\n\n env = os.environ.copy()\n env[\"DOCKER_BUILDKIT\"] = \"1\"\n subprocess.check_call(\n [\n \"docker\",\n \"build\",\n \"--build-arg\",\n f\"BASE_IMAGE={test.get_anyscale_base_byod_image()}\",\n \"--build-arg\",\n f\"POST_BUILD_SCRIPT={test.get_byod_post_build_script()}\",\n \"-t\",\n byod_image,\n \"-f\",\n os.path.join(RELEASE_BYOD_DIR, \"byod.custom.Dockerfile\"),\n RELEASE_BYOD_DIR,\n ],\n stdout=sys.stderr,\n env=env,\n )\n _validate_and_push(byod_image)\n\n\ndef build_anyscale_base_byod_images(tests: List[Test]) -> None:\n \"\"\"\n Builds the Anyscale BYOD images for the given tests.\n \"\"\"\n build_ray(tests)\n _download_dataplane_build_file()\n to_be_built = {}\n built = set()\n for test in tests:\n if not test.is_byod_cluster():\n continue\n to_be_built[test.get_anyscale_base_byod_image()] = test\n\n env = os.environ.copy()\n env[\"DOCKER_BUILDKIT\"] = \"1\"\n start = int(time.time())\n # ray images are built on post-merge, so we can wait for them to be available\n while (\n len(built) < len(to_be_built)\n and int(time.time()) - start < BASE_IMAGE_WAIT_TIMEOUT\n ):\n for byod_image, test in to_be_built.items():\n py_version = test.get_python_version()\n if test.use_byod_ml_image():\n byod_requirements = f\"{REQUIREMENTS_ML_BYOD}_{py_version}.txt\"\n else:\n byod_requirements = f\"{REQUIREMENTS_BYOD}_{py_version}.txt\"\n\n if _byod_image_exist(test):\n logger.info(f\"Image {byod_image} already exists\")\n built.add(byod_image)\n continue\n ray_image = test.get_ray_image()\n if not _ray_image_exist(ray_image):\n # TODO(can): instead of waiting for the base image to be built, we can\n # build it ourselves\n timeout = BASE_IMAGE_WAIT_TIMEOUT - (int(time.time()) - start)\n logger.info(\n f\"Image {ray_image} does not exist yet. \"\n f\"Wait for another {timeout}s...\"\n )\n time.sleep(BASE_IMAGE_WAIT_DURATION)\n continue\n logger.info(f\"Building {byod_image} from {ray_image}\")\n with open(DATAPLANE_FILENAME, \"rb\") as build_file:\n subprocess.check_call(\n [\n \"docker\",\n \"build\",\n \"--build-arg\",\n f\"BASE_IMAGE={ray_image}\",\n \"-t\",\n byod_image,\n \"-\",\n ],\n stdin=build_file,\n stdout=sys.stderr,\n env=env,\n )\n subprocess.check_call(\n [\n \"docker\",\n \"build\",\n \"--build-arg\",\n f\"BASE_IMAGE={byod_image}\",\n \"--build-arg\",\n f\"PIP_REQUIREMENTS={byod_requirements}\",\n \"--build-arg\",\n \"DEBIAN_REQUIREMENTS=requirements_debian_byod.txt\",\n \"-t\",\n byod_image,\n \"-f\",\n os.path.join(RELEASE_BYOD_DIR, \"byod.Dockerfile\"),\n RELEASE_BYOD_DIR,\n ],\n stdout=sys.stderr,\n env=env,\n )\n _validate_and_push(byod_image)\n built.add(byod_image)\n\n\ndef _validate_and_push(byod_image: str) -> None:\n \"\"\"\n Validates the given image and pushes it to ECR.\n \"\"\"\n docker_ray_commit = (\n subprocess.check_output(\n [\n \"docker\",\n \"run\",\n \"-ti\",\n \"--entrypoint\",\n \"python\",\n byod_image,\n \"-c\",\n \"import ray; print(ray.__commit__)\",\n ],\n )\n .decode(\"utf-8\")\n .strip()\n )\n if os.environ.get(\"RAY_IMAGE_TAG\"):\n logger.info(f\"Ray commit from image: {docker_ray_commit}\")\n else:\n expected_ray_commit = _get_ray_commit()\n assert (\n docker_ray_commit == expected_ray_commit\n ), f\"Expected ray commit {expected_ray_commit}, found {docker_ray_commit}\"\n logger.info(f\"Pushing image to registry: {byod_image}\")\n subprocess.check_call(\n [\"docker\", \"push\", byod_image],\n stdout=sys.stderr,\n )\n\n\ndef _get_ray_commit(envs: Optional[Dict[str, str]] = None) -> str:\n if envs is None:\n envs = os.environ\n for key in [\n \"RAY_WANT_COMMIT_IN_IMAGE\",\n \"COMMIT_TO_TEST\",\n \"BUILDKITE_COMMIT\",\n ]:\n commit = envs.get(key, \"\")\n if commit:\n return commit\n return \"\"\n\n\ndef _download_dataplane_build_file() -> None:\n \"\"\"\n Downloads the dataplane build file from S3.\n \"\"\"\n s3 = boto3.client(\"s3\")\n s3.download_file(\n Bucket=DATAPLANE_S3_BUCKET,\n Key=DATAPLANE_FILENAME,\n Filename=DATAPLANE_FILENAME,\n )\n with open(DATAPLANE_FILENAME, \"rb\") as build_context:\n digest = hashlib.sha256(build_context.read()).hexdigest()\n assert digest == DATAPLANE_DIGEST, \"Mismatched dataplane digest found!\"\n\n\ndef _ray_image_exist(ray_image: str) -> bool:\n \"\"\"\n Checks if the given image exists in Docker\n \"\"\"\n p = subprocess.run(\n [\"docker\", \"manifest\", \"inspect\", ray_image],\n stdout=sys.stderr,\n stderr=sys.stderr,\n )\n return p.returncode == 0\n\n\ndef _byod_image_exist(test: Test, base_image: bool = True) -> bool:\n \"\"\"\n Checks if the given Anyscale BYOD image exists.\n \"\"\"\n if os.environ.get(\"BYOD_NO_CACHE\", False):\n return False\n if test.is_gce():\n # TODO(can): check image existence on GCE; without this, we'll always rebuild\n return False\n client = boto3.client(\"ecr\", region_name=\"us-west-2\")\n image_tag = (\n test.get_byod_base_image_tag() if base_image else test.get_byod_image_tag()\n )\n try:\n client.describe_images(\n repositoryName=test.get_byod_repo(),\n imageIds=[{\"imageTag\": image_tag}],\n )\n return True\n except client.exceptions.ImageNotFoundException:\n return False\n","repo_name":"ray-project/ray","sub_path":"release/ray_release/byod/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":8917,"program_lang":"python","lang":"en","doc_type":"code","stars":28715,"dataset":"github-code","pt":"86"} +{"seq_id":"6307135113","text":"import random\n\nclass Game:\n\n def get_question(self):\n with open('q.txt', 'r', encoding='utf-8') as f:\n question_list = f.read().splitlines()\n number_question = random.randrange(0, len(question_list))\n question_answer = str(question_list[number_question])\n for i in range(0, len(question_answer)):\n if question_answer[i] == ';':\n answer = question_answer[i + 1:len(question_answer)]\n question = question_answer[0:i]\n return question, answer\n\n def outputinfo(self, answer):\n curent_view = []\n for i in range(0,len(answer)):\n curent_view.append('*')\n print(''.join(curent_view))\n\n while True:\n user = input('Введите букву или назовите слово сразу: ')\n if user == answer:\n print('Вы правильно назвали слово!');break\n if (user in answer):\n print('Есть такая буква в этом слове!')\n for i in range(0,len(answer)):\n if answer[i]==user:\n curent_view[i]=user\n user_answer = ''.join(curent_view)\n else:\n print('Такой буквы нет!')\n if user_answer == answer:\n print('Вы правильно назвали все буквы!');break\n print(user_answer)\n\nclass Player:\n def __init__(self, name, age, motto_in_life):\n self.name = name\n self.age = age\n self.motto_in_life = motto_in_life\n\n def player_info(self):\n print(f'\\nИнформация об игроке: \\n Имя: {self.name}, \\n Возраст: {self.age}, \\n Девиз по жизни: {self.motto_in_life}\\n')\n\nclass Menu:\n\n def menu(self):\n print(\n '\\n====== Капитан-Шоу \"Поле Чудес\" ======\\n 1 - Начать игру \\n 2 - Об игроке \\n 3 - Об игре \\n 0 - Выход \\n')\n code = int(input('Выберите пункт: '))\n if code == 1:\n new_game = Game()\n que, ans = new_game.get_question()\n print(que)\n print(new_game.outputinfo(ans))\n elif code == 0:\n exit('\\nИгра завершена')\n elif code == 2:\n print('Перед началом игры заполните поля: \\n')\n name = input('Введите свое имя: ')\n age = int(input('Введите свой возраст: '))\n motto_in_life = input('Введите девиз по жизни: ')\n if name and age and motto_in_life:\n new_player = Player(name, age, motto_in_life)\n print(new_player.player_info())\n elif code == 3:\n print('\\nИгра разработана черезе TDD\\n')\n else:\n print('Нет такого пункта меню, повторите попытку.')\n menu = Menu()\n\nif __name__ == '__main__':\n menu = Menu()\n menu.menu()\n# new_player = Player('Андрей', 20, 'Все к лучшему!')\n# new_player.player_info()\n\n# new_game = Game()\n# que, ans = new_game.get_question()\n# print(que)\n# print(new_game.outputinfo(ans))","repo_name":"tosvt/TIVPO","sub_path":"Практическая работа 3/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"13024490057","text":"from tools.extraction_tools import extraction_pipeline\nfrom tools.cleaning_tools import cleaning_pipeline\nfrom tools.features_engineering_tools import wgs84_to_web_mercator, zones, season\nimport pandas as pd\nfrom workflow.df_for_figures import create_start_end_df, create_full_tracks_df\n\n\nif __name__ == '__main__':\n\n files_dir = '../files/'\n\n extraction_pipeline(files_dir=files_dir)\n\n cleaning_pipeline(files_dir=files_dir)\n\n file_name = 'df_tracks_after_1970.csv'\n\n file_path = files_dir + file_name\n\n df = pd.read_csv(file_path, index_col=0, dtype={'Hour': str}, parse_dates=['Time'])\n\n print(df.info())\n\n df = wgs84_to_web_mercator(df=df)\n\n df = season(df=df)\n\n df = zones(df=df)\n\n file_name = 'df_tracks_augmented.csv'\n\n file_path = files_dir + file_name\n\n df.to_csv(file_path)\n\n create_full_tracks_df(file_path=file_path)\n\n file_name = 'df_full_tracks_bokeh.csv'\n\n file_path = files_dir + file_name\n\n create_start_end_df(file_path=file_path)\n","repo_name":"MounBen/hurricanes_visualization","sub_path":"workflow/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"2847068739","text":"# Python program for implementation of Bubble Sort\r\n\r\ndef bubbleSort(arr):\r\n\t# Traverse through all array elements\r\n\tfor i in range(len(arr)):\r\n\r\n\t\t# Last i elements are already in place\r\n\t\tfor j in range(0, n-i-1):\r\n\r\n\t\t\t# traverse the array from 0 to n-i-1\r\n\t\t\t# Swap if the element found is greater\r\n\t\t\t# than the next element\r\n\t\t\tif arr[j] > arr[j+1] :\r\n\t\t\t\tarr[j], arr[j+1] = arr[j+1], arr[j]\r\n\r\narr = list()\r\nn = int(input(\"Enter how many elements you want:\"))\r\nprint (\"Enter numbers in array: \")\r\nfor i in range(int(n)):\r\n n = int(input(\"num :\"))\r\n arr.append(int(n))\r\nprint (\"ARRAY: \"),arr\r\n\r\n\r\nbubbleSort(arr)\r\n\r\nprint (\"Sorted array is:\")\r\nfor i in range(len(arr)):\r\n\tprint (\"%d\" %arr[i]), \r\n","repo_name":"ARKAKJSCE/Internship","sub_path":"Exercise-2/bubble sort.py","file_name":"bubble sort.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"37327015293","text":"import cv2\r\nimport numpy as np\r\n\r\ndef read_image(file_path):\r\n image = cv2.imread(file_path)\r\n return image\r\n\r\ndef preprocess_image(image):\r\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n return gray_image\r\n\r\ndef detect_edges(gray_image):\r\n edges = cv2.Canny(gray_image, 100, 200)\r\n return edges\r\n\r\ndef segment_image(gray_image):\r\n ret, thresholded = cv2.threshold(gray_image, 127, 255, cv2.THRESH_BINARY_INV)\r\n contours, hierarchy = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n return contours\r\n\r\ndef find_red_object(image):\r\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n lower_red = np.array([0, 100, 100])\r\n upper_red = np.array([10, 255, 255])\r\n mask = cv2.inRange(hsv, lower_red, upper_red)\r\n contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n \r\n if not contours:\r\n return None\r\n \r\n largest_contour = max(contours, key=cv2.contourArea)\r\n x, y, w, h = cv2.boundingRect(largest_contour)\r\n return x, y, w, h\r\n\r\ndef extract_canopy_size(image):\r\n # Convert the image to grayscale\r\n gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n\r\n # Apply a Gaussian blur to reduce noise\r\n blurred_gray_image = cv2.GaussianBlur(gray_image, (5, 5), 0)\r\n\r\n # Apply the Canny edge detection algorithm\r\n edges = cv2.Canny(blurred_gray_image, 50, 150)\r\n\r\n # Find contours in the edges\r\n contours, hierarchy = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n # Find the largest contour (assuming it's the durian tree canopy)\r\n largest_contour = max(contours, key=cv2.contourArea)\r\n\r\n # Calculate the canopy size\r\n x, y, w, h = cv2.boundingRect(largest_contour)\r\n canopy_size = w * h\r\n\r\n # Return the width, height, and size as a dictionary\r\n return {'width': w, 'height': h, 'size': canopy_size}\r\n\r\ndef analyze_nutrient_content(image):\r\n hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n lower_green = (30, 40, 40)\r\n upper_green = (90, 255, 255)\r\n mask = cv2.inRange(hsv_image, lower_green, upper_green)\r\n return mask\r\n\r\ndef calculate_greenness_index(mask, canopy_size):\r\n green_pixels = cv2.countNonZero(mask)\r\n greenness_index = green_pixels / canopy_size\r\n return greenness_index\r\n\r\n # Custom function to measure stem size\r\ndef measure_stem_size(image, contours):\r\n # You may need to adjust the following parameters based on your specific images\r\n stem_width_range = (5, 50)\r\n stem_height_range = (50, 300)\r\n\r\n stem_contours = []\r\n for contour in contours:\r\n x, y, w, h = cv2.boundingRect(contour)\r\n if stem_width_range[0] <= w <= stem_width_range[1] and stem_height_range[0] <= h <= stem_height_range[1]:\r\n stem_contours.append(contour)\r\n\r\n # Assuming there's only one stem in the image\r\n if len(stem_contours) == 1:\r\n x, y, w, h = cv2.boundingRect(stem_contours[0])\r\n stem_size = (w, h)\r\n return stem_size\r\n else:\r\n return None\r\n\r\n# Custom function to measure plant height\r\ndef measure_height(contours):\r\n topmost = None\r\n bottommost = None\r\n\r\n for contour in contours:\r\n for point in contour:\r\n if topmost is None or point[0][1] < topmost[1]:\r\n topmost = point[0]\r\n if bottommost is None or point[0][1] > bottommost[1]:\r\n bottommost = point[0]\r\n\r\n if topmost is not None and bottommost is not None:\r\n plant_height = bottommost[1] - topmost[1]\r\n return plant_height\r\n else:\r\n return None\r\n\r\n# Custom function to detect deficiencies\r\ndef detect_deficiencies(canopy_size, stem_size, plant_height, greenness_index):\r\n deficiencies = []\r\n\r\n if greenness_index < 0.7:\r\n deficiencies.append(\"low_greenness_index\")\r\n\r\n # Add more deficiency detection conditions here\r\n if canopy_size < 1000: # Adjust the threshold based on your domain knowledge\r\n deficiencies.append(\"small_canopy_size\")\r\n\r\n if stem_size is not None and stem_size[0] < 10: # Adjust the threshold based on your domain knowledge\r\n deficiencies.append(\"thin_stem\")\r\n\r\n if plant_height < 100: # Adjust the threshold based on your domain knowledge\r\n deficiencies.append(\"short_plant_height\")\r\n\r\n return deficiencies\r\n\r\n# Custom function to analyze growth rate\r\ndef analyze_growth_rate(canopy_size, stem_size, plant_height):\r\n # You'll need to store previous measurements to calculate the growth rate\r\n # For this example, let's assume you have a list of previous measurements\r\n previous_measurements = [\r\n {'canopy_size': 1000, 'stem_size': (10, 100), 'plant_height': 120},\r\n {'canopy_size': 1100, 'stem_size': (12, 110), 'plant_height': 130},\r\n # Add more previous measurements here\r\n ]\r\n\r\n # Calculate the average growth rate for each feature\r\n canopy_growth_rate = (canopy_size - previous_measurements[-1]['canopy_size']) / len(previous_measurements)\r\n \r\n if stem_size is not None:\r\n stem_width_growth_rate = (stem_size[0] - previous_measurements[-1]['stem_size'][0]) / len(previous_measurements)\r\n stem_height_growth_rate = (stem_size[1] - previous_measurements[-1]['stem_size'][1]) / len(previous_measurements)\r\n else:\r\n stem_width_growth_rate = None\r\n stem_height_growth_rate = None\r\n\r\n plant_height_growth_rate = (plant_height - previous_measurements[-1]['plant_height']) / len(previous_measurements)\r\n\r\n growth_rate = {\r\n 'canopy_growth_rate': canopy_growth_rate,\r\n 'stem_width_growth_rate': stem_width_growth_rate,\r\n 'stem_height_growth_rate': stem_height_growth_rate,\r\n 'plant_height_growth_rate': plant_height_growth_rate\r\n }\r\n\r\n return growth_rate\r\n\r\n# Custom function to analyze health\r\ndef analyze_health(greenness_index):\r\n # You can use the greenness index to determine the health of the plant\r\n # For example, you can use predefined thresholds\r\n if greenness_index >= 0.7:\r\n health = \"healthy\"\r\n elif greenness_index >= 0.4:\r\n health = \"moderately healthy\"\r\n else:\r\n health = \"unhealthy\"\r\n\r\n return health\r\n\r\n# Custom function to suggest counteractions\r\ndef suggest_counteractions(deficiencies):\r\n counteractions = []\r\n\r\n for deficiency in deficiencies:\r\n if deficiency == \"low_greenness_index\":\r\n counteractions.append(\"apply_nitrogen_fertilizer\")\r\n\r\n # Add more counteractions for other deficiencies here\r\n if deficiency == \"small_canopy_size\":\r\n counteractions.append(\"increase_sunlight_exposure\")\r\n\r\n if deficiency == \"thin_stem\":\r\n counteractions.append(\"apply_phosphorus_fertilizer\")\r\n\r\n if deficiency == \"short_plant_height\":\r\n counteractions.append(\"apply_growth_stimulant\")\r\n\r\n return counteractions\r\n\r\ndef analyze_durian_plant(file_path):\r\n image = read_image(file_path)\r\n gray_image = preprocess_image(image)\r\n edges = detect_edges(gray_image)\r\n contours = segment_image(gray_image)\r\n canopy_data = extract_canopy_size(image)\r\n mask = analyze_nutrient_content(image)\r\n greenness_index = calculate_greenness_index(mask, canopy_data['size'])\r\n\r\n # Measure stem size and height\r\n stem_size = measure_stem_size(image, contours)\r\n plant_height = measure_height(contours)\r\n\r\n # Detect deficiencies and suggest counteractions\r\n deficiencies = detect_deficiencies(canopy_data['size'], stem_size, plant_height, greenness_index)\r\n\r\n # Analyze growth rate and health\r\n growth_rate = analyze_growth_rate(canopy_data['size'], stem_size, plant_height)\r\n health = analyze_health(greenness_index)\r\n\r\n # Detect deficiencies and suggest counteractions\r\n deficiencies = detect_deficiencies(canopy_data['size'], stem_size, plant_height, greenness_index)\r\n counteractions = suggest_counteractions(deficiencies)\r\n\r\n red_object = find_red_object(image)\r\n if red_object is not None:\r\n x, y, w, h = red_object\r\n pixel_to_cm_width = 30 / w\r\n pixel_to_cm_height = 30 / h\r\n else:\r\n # Set default pixel to cm conversion factors if the red reference object is not found\r\n pixel_to_cm_width = 0.1\r\n pixel_to_cm_height = 0.1\r\n\r\n # Convert the canopy_size, stem_size, and plant_height values to centimeters using the conversion factor\r\n canopy_size_cm = canopy_data['size'] * pixel_to_cm_width\r\n\r\n if stem_size is not None:\r\n stem_size_cm = (stem_size[0] * pixel_to_cm_width, stem_size[1] * pixel_to_cm_height)\r\n else:\r\n stem_size_cm = None\r\n\r\n plant_height_cm = plant_height * pixel_to_cm_height\r\n\r\n # Return the results as a dictionary\r\n return {\r\n 'canopy_size_cm': canopy_size_cm,\r\n 'stem_size_cm': stem_size_cm,\r\n 'plant_height_cm': plant_height_cm,\r\n 'canopy_size': canopy_data['size'],\r\n 'stem_size': stem_size,\r\n 'plant_height': plant_height,\r\n 'canopy_width': canopy_data['width'],\r\n 'canopy_height': canopy_data['height'],\r\n 'greenness_index': greenness_index,\r\n 'growth_rate': growth_rate,\r\n 'health': health,\r\n 'deficiencies': deficiencies,\r\n 'counteractions': counteractions\r\n }\r\n\r\nif __name__ == \"__main__\":\r\n file_path = 'D:\\Desktop\\FYP\\duriantrees\\durian_tree1.JPG'\r\n result = analyze_durian_plant(file_path)\r\n print(result)\r\n","repo_name":"malsem/FYP","sub_path":"durian_plant_analysis.py","file_name":"durian_plant_analysis.py","file_ext":"py","file_size_in_byte":9432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"30117045960","text":"import sys\ninput = sys.stdin.readline\nN, M = map(int,input().split())\narr = list(map(int,input().split()))\n\nstart = 0 # 시작 인덱스\nend = 0 # 끝 인덱스\ncnt = 0 # 경우의 수 카운트\nwhile True:\n if sum(arr[start:end+1]) == M : # arr[0:1]부터 시작해서 요소 합이 3이면 경우의수 , 인덱스 증가\n cnt += 1\n start += 1\n end += 1\n if end == N: \n break \n if sum(arr[start:end+1]) < M : # 시작인덱스는 그대로 두고 끝 부분인덱스를 늘려 합이 증가하면서 3에 근접하도록\n end += 1\n if sum(arr[start:end+1]) > M : # 끝 인덱스는 그대로 두고 시작인덱스를 늘려 합이 감소하면서 3에 근접하도록\n start += 1\nprint(cnt)","repo_name":"Junobee25/Algorithm","sub_path":"AlgorithmStudy/Day-08/수의합/수의합.py","file_name":"수의합.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"7682502443","text":"from pwn import *\r\n\r\ncontext.binary = exe = ELF('./chal')\r\nlibc = ELF('./libc.so.6')\r\n\r\nio = remote('amt.rs', 31630)\r\n\r\nio.recvuntil(b'hex: \\n')\r\npayload = b'i'*28 + p32(0xFFFFFFC0)\r\nio.sendline(payload)\r\nflag = bytes.fromhex(io.recvline(keepends=False).decode())\r\nprint(flag)\r\nio.interactive()\r\n","repo_name":"th4s1s/pwn","sub_path":"amateurs/hex_converter/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"6109578747","text":"# 二分查找\r\ndef binary_search(alist, item):\r\n n = len(alist)\r\n up = n - 1\r\n down = 0\r\n mid = (up + down) // 2\r\n\r\n while down <= up:\r\n mid = (up + down) // 2\r\n if alist[mid] < item:\r\n down = mid + 1\r\n elif alist[mid] > item:\r\n up = mid - 1\r\n elif alist[mid] == item:\r\n return True, mid\r\n return False\r\n\r\n\r\ndef binary_search2(alist, item):\r\n n = len(alist)\r\n if n > 0:\r\n mid = n // 2\r\n if alist[mid] == item:\r\n return True\r\n elif item < alist[mid]:\r\n return binary_search2(alist[:mid], item)\r\n else:\r\n return binary_search2(alist[mid+1:], item)\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n li = [17, 20, 26, 31, 44, 54, 55, 77, 93]\r\n print(li)\r\n print(binary_search(li, 31))\r\n","repo_name":"idealslee/Data-Structures-and-Algorithms","sub_path":"15-binary_search.py","file_name":"15-binary_search.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"29242276927","text":"import numpy as np\n\nfrom design_optimisation.create_parameters_file import write_parameters_file\n\ncontrasts = [\n [-1, 1]\n]\n\ncontrasts_names = [\"Contrast 1\"]\n\n# Transitions Constraints\ngroups = [1, 2]\n\ntmp = [\n [1],\n [2]\n]\n\nC1 = 0.0\nC2 = 0.0\ntmn = [\n [C1, 1.0-C1],\n [1.0-C2, C2]\n]\n\nfiles_list = [\"c1-1\", \"c1-2\", \"c1-3\", \"c1-4\", \"c1-5\", \"c1-6\", \"c1-7\", \"c1-8\", \"c1-9\", \"c1-10\",\n \"c2-1\", \"c2-2\", \"c2-3\", \"c2-4\", \"c2-5\", \"c2-6\", \"c2-7\", \"c2-8\"]\ncond_of_files = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2]\ndurations = np.repeat([0.5], 18)\n\nconditions_names = [\"cond1\", \"cond2\"]\n\niti_file = \"/hpc/banco/bastien.c/data/optim/test/ITIs.npy\"\noutput_path = \"/hpc/banco/bastien.c/data/optim/test/unbalanced/\"\nfiles_path = \"./\"\n\ntr = 0.955\nnbr_designs = 2000\n\nwrite_parameters_file(conditions_names, cond_of_files, groups, contrasts, contrasts_names, durations, files_list,\n files_path, iti_file, nbr_designs, tmp, tmn, tr, output_path, verbose=True)\n","repo_name":"BastienCagna/MRI-Design-Optimizer","sub_path":"examples/optimisation/unbalanced_pipeline_test.py","file_name":"unbalanced_pipeline_test.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"37222791323","text":"import os\nimport sys\nimport random\nimport numpy as np\nimport joblib\nimport itertools\nimport matplotlib.pyplot as plt\nfrom collections import Counter\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans, SpectralClustering, AgglomerativeClustering\nfrom gensim.models import Word2Vec\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics.pairwise import cosine_similarity, euclidean_distances\n\nhome = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(home + '/../../../../')\nfrom src.NLP.preprocessing import clean_tweet, stopwords\nfrom src.mysql_utils import MySqlUtils\nfrom src.NLP.similarity import user_query\n\n\ncategories = [\n 'bollywood','politics', 'cricket', 'bigg_boss', 'football', 'machine_learning', 'happy_birthday',\n 'hollywood', 'mobiles', 'food'\n]\n\ncategories_words_removal = {\n 'bollywood': ['#bollywood'],\n 'politics': ['@narendramodi', '@amitshah'],\n 'cricket': ['#indiavssouthafrica', '#SAvsIND', '#indvsa', '#teamindia', '#indvssl', '#slvsind'],\n 'bigg_boss': ['bigg boss', 'bb11'],\n 'football': ['#fcbarcelona', '#chelsea'],\n 'machine_learning': ['#machinelearning', '#bigdata'],\n 'happy_birthday': [],\n 'hollywood': ['#hollywood'],\n 'mobiles': ['redmi note'],\n 'food': ['pasta'],\n}\n\ndef remove_duplicates():\n \"\"\"\n Remove those tweets which are present in more than 1 categories.\n \"\"\"\n for category in categories:\n category_data = joblib.load('data/brand24/%s_tweets.pkl' % (category,))\n unique = []\n for d in category_data:\n if b24_all_tweets.count(d['content']) == 1:\n unique.append(d)\n joblib.dump(unique, 'data/brand24/%s_tweets.pkl' % (category,))\n\n\ndef remove_false_football_tweets():\n football_tweets = joblib.load('data/brand24/football_tweets.pkl')\n correct_tweets = []\n for d in football_tweets:\n if not '#liverpool' in d['content'].lower():\n correct_tweets.append(d)\n joblib.dump(correct_tweets, 'data/brand24/football_tweets.pkl')\n\n\ndef clean_b24_tweet(tweet, category):\n tweet = tweet.lower()\n words_to_remove = categories_words_removal[category]\n for w in words_to_remove:\n tweet = tweet.replace(w.lower(), '')\n\n return tweet\n\n\ndef build_data():\n b24_tweets_labeled = {}\n\n for category in categories:\n tweets = joblib.load('data/brand24/%s_tweets.pkl' % category)\n b24_tweets_labeled[category] = [tweet['content'] for tweet in tweets]\n\n joblib.dump(b24_tweets_labeled, 'src/NLP/junk/testing_on_brand24/data/b24_tweets_labeled.pkl')\n\n\ndef get_b24_tweets():\n b24_tweets_labeled = joblib.load('src/NLP/junk/testing_on_brand24/data/b24_tweets_labeled.pkl')\n tweets_lists = list(b24_tweets_labeled.values())\n b24_all_tweets = list(itertools.chain.from_iterable(tweets_lists))\n print('B24 tweets', len(b24_all_tweets))\n return b24_all_tweets\n\n\ndef get_b24_tweets_sample():\n b24_tweets_labeled = joblib.load('src/NLP/junk/testing_on_brand24/data/b24_tweets_labeled.pkl')\n tweets_lists = list(b24_tweets_labeled.values())\n tweets_lists_random = [random.sample(l, int(0.25*len(l))) for l in tweets_lists]\n b24_all_tweets = list(itertools.chain.from_iterable(tweets_lists_random))\n print('B24 tweets', len(b24_all_tweets))\n return b24_all_tweets\n\n\ndef get_db_tweets(length=500000):\n sql = MySqlUtils()\n users = sql.get_data(user_query)\n users_list = [user['user_handle'] for user in users[:length]]\n print('Query count {}'.format(len(users)))\n query = 'SELECT text FROM tweet where user_handle IN (' + ','.join(\n (\"'{}'\".format(user) for user in users_list)) + ')'\n\n tweets = sql.get_data(query)\n print('DB tweets', len(tweets))\n return tweets\n\n\ndef train_w2v():\n b24_all_tweets = get_b24_tweets()\n db_tweets = [t['text'] for t in get_db_tweets(length=2000)]\n all_tweets = b24_all_tweets + db_tweets\n clean_tweets = [clean_tweet(t, as_string=False) for t in all_tweets]\n model = Word2Vec(sentences=clean_tweets, sg=1, size=200, window=10, min_count=10)\n word_vectors = {}\n for word in model.wv.vocab:\n word_vectors[word] = model[word]\n\n joblib.dump(model, 'src/NLP/junk/testing_on_brand24/data/model.pkl')\n joblib.dump(word_vectors, 'src/NLP/junk/testing_on_brand24/data/word_vectors.pkl')\n\n\ndef cluster_tweets():\n word_vectors = joblib.load('src/NLP/junk/testing_on_brand24/data/word_vectors.pkl')\n all_tweets = get_b24_tweets_sample()\n tweets_categories = get_tweets_categories()\n\n tweet_vectors = {}\n for t in all_tweets:\n tweet_category = tweets_categories[t]\n tweet_word_vectors = []\n tweet_words = clean_tweet(clean_b24_tweet(t, tweet_category)).split()\n for word in tweet_words:\n if word in word_vectors:\n word_vector = word_vectors[word]\n tweet_word_vectors.append(list(word_vector))\n\n if len(tweet_word_vectors) > 0:\n tweet_vector = np.array(tweet_word_vectors).mean(axis=0)\n tweet_vectors[t] = tweet_vector\n\n joblib.dump(tweet_vectors, 'src/NLP/junk/testing_on_brand24/data/tweet_vectors.pkl')\n\n # tweet_vectors = joblib.load('src/NLP/junk/testing_on_brand24/data/tweet_vectors.pkl')\n tweet_vectors_values = list(tweet_vectors.values())\n # b24_tweets_labeled = joblib.load('src/NLP/junk/testing_on_brand24/data/b24_tweets_labeled.pkl')\n # centroids = []\n # for category, tweets in b24_tweets_labeled.items():\n # category_tweet_vectors = []\n # for t in tweets:\n # try:\n # category_tweet_vectors.append(list(tweet_vectors[t]))\n # except Exception as e:\n # pass\n\n # category_centroid = np.array(category_tweet_vectors).mean(axis=0)\n # centroids.append(category_centroid)\n\n # centroids_array = np.array(centroids)\n # pca = PCA(n_components=2).fit(tweet_vectors_values)\n # pca_2d = pca.transform(tweet_vectors_values)\n # joblib.dump(pca_2d, 'src/NLP/junk/testing_on_brand24/data/pca_2d.pkl')\n\n n_clusters = 10\n spectral = SpectralClustering(n_clusters=n_clusters)\n spectral.fit(tweet_vectors_values)\n labels = list(spectral.labels_)\n\n clusters = {}\n for ctr, label in enumerate(labels):\n if label in clusters:\n clusters[label].append(all_tweets[ctr])\n else:\n clusters[label] = [all_tweets[ctr]]\n\n joblib.dump(clusters, 'src/NLP/junk/testing_on_brand24/data/clusters.pkl')\n\n\ndef get_tweets_categories():\n tweets_categories = {}\n b24_tweets_labeled = joblib.load('src/NLP/junk/testing_on_brand24/data/b24_tweets_labeled.pkl')\n for category, tweets_list in b24_tweets_labeled.items():\n for t in tweets_list:\n tweets_categories[t] = category\n\n return tweets_categories\n\n\ndef get_accuracy(clusters_pkl):\n tweet_vectors = joblib.load('src/NLP/junk/testing_on_brand24/data/tweet_vectors.pkl')\n tweets_categories = get_tweets_categories()\n clusters = joblib.load(clusters_pkl)\n predicted_clusters = {}\n for category in categories:\n predicted_clusters[category] = []\n\n ctr = 1\n correct_count = 0\n for label, tweets in clusters.items():\n actual_categories = []\n for t in tweets:\n actual_category = tweets_categories[t]\n actual_categories.append(actual_category)\n print('Cluster ', str(ctr))\n print(Counter(actual_categories))\n accuracy_percent = int((Counter(actual_categories).most_common(1)[0][1]/len(tweets)) * 100)\n print('Cluster length: ', len(tweets))\n print('Accuracy: {}%'.format(accuracy_percent))\n category = Counter(actual_categories).most_common(1)[0][0]\n predicted_clusters[category].append('{}%'.format(accuracy_percent))\n print('\\n')\n correct_count += Counter(actual_categories).most_common(1)[0][1]\n ctr += 1\n\n print('*'*50 + '\\n')\n\n for category, accuracies in predicted_clusters.items():\n print(category)\n print('Clusters: %s' % len(accuracies))\n if len(accuracies) > 0:\n print('Accuracies: %s' % ', '.join(accuracies))\n print('\\n')\n\n overall_accuracy_percent = round((correct_count/len(tweet_vectors)) * 100, 2)\n\n print('*'*50 + '\\n')\n print('Overall accuracy: {}%'.format(overall_accuracy_percent))\n\n\ndef visualize_clusters():\n # word_vectors = joblib.load('src/NLP/junk/testing_on_brand24/data/word_vectors.pkl')\n all_tweets = get_b24_tweets()\n\n # tweet_vectors = {}\n # for t in all_tweets:\n # tweet_word_vectors = []\n # tweet_words = clean_tweet(t).split()\n # for word in tweet_words:\n # if word in word_vectors:\n # word_vector = word_vectors[word]\n # tweet_word_vectors.append(list(word_vector))\n\n # if len(tweet_word_vectors) > 0:\n # tweet_vector = np.array(tweet_word_vectors).mean(axis=0)\n # tweet_vectors[t] = tweet_vector\n\n # joblib.dump(tweet_vectors, 'src/NLP/junk/testing_on_brand24/data/tweet_vectors.pkl')\n\n # tweet_vectors = joblib.load('src/NLP/junk/testing_on_brand24/data/tweet_vectors.pkl')\n # tweet_vectors_values = list(tweet_vectors.values())\n\n # pca = PCA(n_components=2).fit(tweet_vectors_values)\n # pca_2d = pca.transform(tweet_vectors_values)\n\n # joblib.dump(pca_2d, 'src/NLP/junk/testing_on_brand24/data/pca_2d.pkl')\n\n # n_clusters = 10\n # k_means = KMeans(n_clusters=n_clusters, init='k-means++', max_iter=100)\n # k_means.fit(tweet_vectors_values)\n\n # joblib.dump(k_means, 'src/NLP/junk/testing_on_brand24/data/k_means.pkl')\n # k_means = joblib.load('src/NLP/junk/testing_on_brand24/data/k_means.pkl')\n # pca_2d = joblib.load('src/NLP/junk/testing_on_brand24/data/pca_2d.pkl')\n\n # indices = []\n # for ctr,label in enumerate(k_means.labels_):\n # if label == 4:\n # indices.append(ctr)\n\n # fig = plt.figure()\n # ax = fig.add_subplot(1,1,1)\n # ax.set_xlim([-3, 4])\n # ax.set_ylim([-3, 4])\n # plt.scatter(pca_2d[indices, 0], pca_2d[indices, 1])\n # plt.show()\n\n # k_means = joblib.load('src/NLP/junk/testing_on_brand24/data/k_means.pkl')\n # clusters = {}\n # for ctr, label in enumerate(k_means.labels_):\n # if label in clusters:\n # clusters[label].append(all_tweets[ctr])\n # else:\n # clusters[label] = [all_tweets[ctr]]\n\n # joblib.dump(clusters, 'src/NLP/junk/testing_on_brand24/data/clusters.pkl')\n\n b24_tweets_labeled = joblib.load('src/NLP/junk/testing_on_brand24/data/b24_tweets_labeled.pkl')\n tweet_vectors = joblib.load('src/NLP/junk/testing_on_brand24/data/tweet_vectors.pkl')\n tweet_vectors_values = list(tweet_vectors.values())\n tweet_vectors_keys = list(tweet_vectors.keys())\n centroids = []\n\n for category, tweets in b24_tweets_labeled.items():\n category_tweet_vectors = []\n for t in tweets:\n try:\n category_tweet_vectors.append(list(tweet_vectors[t]))\n except Exception as e:\n pass\n\n category_centroid = np.array(category_tweet_vectors).mean(axis=0)\n centroids.append(category_centroid)\n\n # for ctr,pt in enumerate(centroids):\n # print(categories[ctr])\n # dist_2 = np.sum((tweet_vectors_values - pt)**2, axis=1)\n # closest_indices = dist_2.argsort()[:10]\n # for ci in closest_indices:\n # print(tweet_vectors_keys[ci])\n # print('\\n')\n\n\n # pca = PCA(n_components=2).fit(centroids)\n # pca_2d = pca.transform(centroids)\n # plt.scatter(pca_2d[:, 0], pca_2d[:, 1])\n\n # for ctr, category in enumerate(categories):\n # plt.annotate(category, (pca_2d[:, 0][ctr], pca_2d[:, 1][ctr]))\n\n # plt.show()\n\n distances = euclidean_distances(centroids)\n print(distances)\n\n # for category, tweets in b24_tweets_labeled.items():\n # print(category)\n # words = []\n # for t in tweets:\n # words += clean_tweet(clean_b24_tweet(t, category)).split()\n # print(Counter(words).most_common(20))\n\n\nif __name__ == '__main__':\n #build_data()\n #train_w2v()\n cluster_tweets()\n get_accuracy('src/NLP/junk/testing_on_brand24/data/clusters.pkl')\n\n #visualize_clusters()\n # get_accuracy('src/NLP/junk/testing_on_brand24/data/clusters.pkl')\n\n # remove_false_football_tweets()\n","repo_name":"ADITYA727/HeLp_for_ML","sub_path":"src/NLP/junk/testing_on_brand24/test_w2v_on_brand24.py","file_name":"test_w2v_on_brand24.py","file_ext":"py","file_size_in_byte":12449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"72530988128","text":"\"\"\"\nScript to scrape news from kathmandupost.ekantipur.com\nContains:\n kathmandu_post_extractor(): Gives list of news dicts\n \"\"\"\n\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup as BS\nimport requests\n\ntry:\n from flask_final.newslet import parser\nexcept ImportError:\n parser = \"lxml\"\n\nURL = \"https://kathmandupost.ekantipur.com\"\n\n\ndef setup():\n HEADERS = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36\\\n (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36\"\n }\n\n try:\n PAGE = requests.get(URL, headers=HEADERS)\n except Exception as e:\n print(\"Connection refused by the server..\", e)\n\n soup = BS(PAGE.content, parser)\n return soup\n\n\ndef format_date(raw_date):\n org_format = \"%Y/%m/%d\"\n datetime_obj = datetime.strptime(raw_date, org_format)\n dest_format = \"%d %b %Y\"\n date = datetime_obj.strftime(dest_format)\n return date\n\n\ndef kathmandu_post_extractor():\n \"\"\"Extracts the news from https://kathmandupost.ekantipur.com\n with the same order as that of the website\n Retruns:\n A list containing dictionaries of news list[0] has latest\n example of such dictionary is\n {\n \"image_link\": image_link,\n \"title\": title in englist,\n \"raw_date\": date in 23 Mar 2018 format,\n \"source\": \"ekantipur\",\n \"news_link\": full_link,\n \"summary\": summary,\n }\n\n \"\"\"\n soup = setup()\n news_list = []\n column_one = soup.find(\"div\", class_=\"grid-first\")\n column_two = soup.find(\"div\", class_=\"grid-second\")\n column_three = soup.find(\"div\", class_=\"grid-third\")\n latest_column = soup.find(\"div\", class_=\"block--morenews\")\n sources = [column_one, column_two, column_three, latest_column]\n\n for column in sources:\n articles = column.find_all(\"article\")\n\n if column == column_two:\n featured_article = articles[0]\n h3_tag = soup.new_tag(\"h3\")\n featured_article.h2.wrap(h3_tag)\n featured_article.h3.h2.unwrap()\n\n elif column == latest_column:\n for article in articles:\n a_tag = article.a\n a_tag.string = article.h3.string\n article.h3.insert(0, a_tag)\n\n for article in articles:\n href_link = article.h3.a[\"href\"]\n article_link = URL + href_link\n title = article.h3.a.text\n\n raw_date = \"/\".join(href_link.split(\"/\")[2:5])\n date = format_date(raw_date)\n\n image_tag = article.find(\"img\")\n if image_tag:\n image_link = image_tag[\"data-src\"]\n else:\n image_link = None\n\n summary = article.p.text\n\n news_dict = {\n \"title\": title,\n \"source\": \"ekantipur\",\n \"news_link\": article_link,\n \"raw_date\": date,\n \"summary\": summary,\n \"image_link\": image_link,\n }\n\n news_list.append(news_dict)\n\n return news_list\n\n\nif __name__ == \"__main__\":\n kathmandu_post_extractor()\n","repo_name":"hemanta212/Nepali-news-portal-kbd","sub_path":"flask_final/newslet/kathmandupost.py","file_name":"kathmandupost.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"88"} +{"seq_id":"6567228588","text":"import math\n\n\ndef vertical_to_horizontal_fov(\n vertical_fov_in_degrees: float, height: float, width: float\n):\n assert 0 < vertical_fov_in_degrees < 180\n aspect_ratio = width / height\n vertical_fov_in_rads = (math.pi / 180) * vertical_fov_in_degrees\n return (\n (180 / math.pi)\n * math.atan(math.tan(vertical_fov_in_rads * 0.5) * aspect_ratio)\n * 2\n )\n\n\ndef horizontal_to_vertical_fov(\n horizontal_fov_in_degrees: float, height: float, width: float\n):\n return vertical_to_horizontal_fov(\n vertical_fov_in_degrees=horizontal_fov_in_degrees, height=width, width=height,\n )\n\n\ndef round_to_factor(num: float, base: int) -> int:\n \"\"\"Rounds floating point number to the nearest integer multiple of the\n given base. E.g., for floating number 90.1 and integer base 45, the result\n is 90.\n\n # Attributes\n\n num : floating point number to be rounded.\n base: integer base\n \"\"\"\n return round(num / base) * base\n","repo_name":"allenai/robustnav","sub_path":"allenact_plugins/ithor_plugin/ithor_util.py","file_name":"ithor_util.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"88"} +{"seq_id":"37236706616","text":"#python 套接字 socket\n#作用 :实现两个或者多个应用的数据传输\n\n#服务端\nimport socket\nimport os\n#指定服务器的IP地址 和监听端口号\nip_port=('127.0.0.6',9999)\n\n#建立一个套接字,为了服务器与客户端传输信息\ns = socket.socket() #创建对象\n\n#绑定服务器地址和端口号\ns.bind(ip_port)\n\n#设置最大连接数,数字为几 最多为几个连接\ns.listen(5)\n\n#提示服务器端已经开启\nprint('启动socket服务,等待连接...')\n\n#scoket 自动控制拥塞控制,持续开启服务,除非手动关闭\nc,address = s.accept()\n#处理客户端发来的数据,首先接受客户端发来的数据\n# c_data = c.recv(1024).decode('utf-8') #设置最大接收量,以kb为单位\n# print(c_data)\n# print(address)\n\nwhile True:\n # c, address = s.accept()\n\n c_data = c.recv(1024).decode('utf-8')\n print(f\"客户端发送的信息:{c_data}\") #客户端向服务器发送的信息\n\n t1 = input(\"输入发送到客户端的信息:\") #服务器向客户端发送信息\n # print(c_data)\n if t1 == \"1\":\n break\n else:\n #发送信息给客户端\n #①先找到客户端\n #②使用sendall\n c.send(t1.encode())\n\n#关闭服务器\ns.close()\n\n\n\n\n\n\n\n\n\n","repo_name":"zhangmingqiang21/test","sub_path":"Python1903-张明强/taojiezi.py","file_name":"taojiezi.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"23490494716","text":"import sys\n\n# to check if the number is too large to be converted(if i cant use library it will just return as exception )\n# or maybe float('inf')\n\n# table of operators and their strength\nOPERA_TABLE = {\n \"+\": 1, \"-\": 1, \"*\": 2, \"/\": 2, \"^\": 3, \"%\": 4, \"@\": 5, \"$\": 5, \"&\": 5, \"!\": 6, \"~\": 6\n}\n# operators that only need one parameter from their right\nOPERA_BEFORE = ('~')\n# operators that only need one parameter from their left\nOPERA_AFTER = ('!')\n# all the chars (without the operators) that are legal in my code\nLEGAL_TABS = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'e', '.', '(', ')')\nARE_NOT_FOR_NUMBERS = ('(', ')')\n\n\nclass InputCheck:\n def __init__(self, input_string):\n self.input_string = input_string\n\n # check if the expression is empty\n def empty_input(self):\n if self.input_string is \"\":\n print(\"pls enter an expression(it is empty)\")\n return False\n return True\n\n # check max length\n def max_len(self):\n max_length = 800\n if len(self.input_string) > max_length:\n print(\"the expression is too long for my calculator (i support \", max_length, \" chars)\")\n return False\n return True\n\n # check if the expression has illegal chars\n def legal_input(self):\n for char_in_exp in self.input_string:\n if char_in_exp not in LEGAL_TABS:\n if char_in_exp not in OPERA_TABLE.keys():\n print(\"illegal char: \", char_in_exp)\n return False\n return True\n\n # check if the expression has good brackets\n def check_bar(self):\n counter = 0\n counter_bar = 0\n size_of_express = len(self.input_string)\n flag_leg = False\n flag_end = False\n # go through all the expression\n for index_in_exp in range(0, size_of_express):\n if self.input_string[index_in_exp] is '(':\n counter = index_in_exp + 1\n while flag_end is False:\n # reached the end without closing\n if counter > (size_of_express - 1):\n flag_end = True\n # this brackets arent useless\n elif self.input_string[counter].isdigit() or self.input_string[counter] in OPERA_TABLE.keys():\n # is not in the outside brackets\n if counter_bar is 0:\n flag_end = True\n flag_leg = True\n # another brackets\n elif self.input_string[counter] is '(':\n counter_bar += 1\n # end brackets\n elif self.input_string[counter] is ')':\n counter_bar -= 1\n # the checked bracket is closed\n if counter_bar is -1:\n flag_end = True\n counter += 1\n # not legal\n if flag_leg is False:\n print(\"problem with the brackets in this expression\")\n return False\n # continue\n else:\n flag_leg = False\n flag_end = False\n counter_bar = 0\n return True\n\n def check_string(self):\n return self.empty_input() and self.legal_input() and self.check_bar() and self.max_len()\n\n\nclass GetInput:\n\n # @staticmethod\n # remove the spaces from the expression\n def remove_spaces(self, stringToChange):\n stringToChange = stringToChange.replace(\" \", \"\")\n return stringToChange\n\n # remove the double minuses from the expression\n def remove_minuses_son(self, express):\n while express.find(\"++\") is not -1 or express.find(\"--\") is not -1 or express.find(\"+-\") is not -1:\n # remove double ++\n express = express.replace(\"++\", \"+\")\n # two minus is plus\n express = express.replace(\"--\", \"+\")\n # minus plus is minus\n express = express.replace(\"+-\", \"-\")\n # RecursionError\n self.remove_minuses_son(express)\n return express\n\n # remove the double minuses from the expression\n def remove_minuses_father(self, express):\n express = self.remove_minuses_son(express)\n if express[0] is \"+\":\n express = express.replace(express[0], '', 1)\n return express\n\n # check if the character before the plus is not another number or chars that need the plus\n def condition_for_pluses(self, char_to_check):\n if char_to_check.isdigit() is False:\n if char_to_check not in OPERA_AFTER:\n if char_to_check is not 'e':\n if char_to_check is not ')':\n return True\n return False\n\n # check if the input is illegal because of the pluses\n def check_pluses(self, express):\n size_of_express = len(express)\n for index in range(0, size_of_express):\n if express[index] is '+':\n # the first character is +\n if index is 0:\n return False\n else:\n # useless character\n if self.condition_for_pluses(express[index - 1]) is True:\n return False\n return True\n\n # remove the pluses that were maybe created by the function remove_minuses\n def remove_pluses(self, express):\n size_of_express = len(express)\n for index in range(0, size_of_express - 1):\n # reached end\n if index < size_of_express:\n if express[index] is '+':\n if index is 0:\n # delete the + from the start\n express = express[1:]\n size_of_express = len(express)\n index = index - 1\n else:\n if self.condition_for_pluses(express[index - 1]) is True:\n # delete the new created +\n express = express[:index] + express[index + 1:]\n size_of_express = len(express)\n index = index - 1\n return express\n\n def input_getter(self):\n # until the input is good\n while True:\n try:\n exp_input = input(\"Enter your expression:\")\n # remove the spaces\n exp_input = self.remove_spaces(exp_input)\n # it is legal from the check functions in the class InputCheck\n if InputCheck(exp_input).check_string() is True:\n # the pluses here are illegal\n if self.check_pluses(exp_input) is False:\n print(\"sorry wrong uses of + , the calculator doesnt support +number as number\")\n else:\n exp_input = self.remove_minuses_father(exp_input)\n exp_input = self.remove_pluses(exp_input)\n return exp_input\n # out of memory exception\n except MemoryError:\n print(\"out of memory\")\n print(\"please try again\")\n except OverflowError as oe:\n print(\"After the Overflow error\", oe)\n print(\"please try again\")\n except RuntimeError:\n print(\"unexpected error\")\n print(\"please try again\")\n\n # use for tests\n def input_getter_for_test(self, x):\n # until the input is good\n try:\n\n exp_input = x\n # remove the spaces\n exp_input = self.remove_spaces(exp_input)\n # it is legal from the check functions in the class InputCheck\n if InputCheck(exp_input).check_string() is True:\n # the pluses here are illegal\n if self.check_pluses(exp_input) is False:\n print(\"sorry wrong uses of + , the calculator doesnt support +number as number\")\n else:\n exp_input = self.remove_minuses_father(exp_input)\n exp_input = self.remove_pluses(exp_input)\n return exp_input\n # wrong input was found in the pre calculate input validators\n return False\n # out of memory exception\n except MemoryError:\n print(\"out of memory\")\n print(\"please try again\")\n except OverflowError as oe:\n print(\"After the Overflow error\", oe)\n print(\"please try again\")\n except RuntimeError:\n print(\"unexpected error\")\n print(\"please try again\")\n\n\nclass OperatorsFun:\n # check if the number is decimal\n def is_decimal(self, num):\n if ((num - int(num)) > 0) is True:\n return True\n return False\n\n # the size of the answer is too big for my calculator\n def too_long(self, num):\n if sys.float_info.max < num or -sys.float_info.max > num:\n return True\n return False\n\n def plus(self, op1, op2):\n if self.too_long(op1 + op2):\n print(\"the number is too long\")\n return None\n return op1 + op2\n\n def minus(self, op1, op2):\n if self.too_long(op1 - op2):\n print(\"the number is too long\")\n return None\n return op1 - op2\n\n def mul(self, op1, op2):\n if self.too_long(op1 * op2):\n print(\"the number is too long\")\n return None\n return op1 * op2\n\n def dev(self, op1, op2):\n if op2 == 0:\n print(\"its illegal to divide by zero\")\n return None\n if self.too_long(op1 / op2):\n print(\"the number is too long\")\n return None\n return op1 / op2\n\n def mod(self, op1, op2):\n return op1 % op2\n\n def power(self, op1, op2):\n try:\n if self.too_long(op1 ** op2):\n print(\"the number is too long\")\n return None\n except OverflowError as oe:\n print(\"the number is too long\")\n return None\n # neg^dec is complex\n if self.is_decimal(op2) and op1 < 0:\n print(\"complex number are not supported :\", op1, \"^\", op2, \"is complex\")\n return None\n return op1 ** op2\n\n # maximum\n def ma(self, op1, op2):\n if op1 > op2:\n return op1\n else:\n return op2\n\n # minimum\n def mi(self, op1, op2):\n if op1 < op2:\n return op1\n else:\n return op2\n\n def fact(self, op):\n if op < 0:\n print(\"cant factorial a negative number\")\n return None\n if self.is_decimal(op):\n print(\"cant factorial a not neutral number\")\n return None\n facto = 1\n # calculate the factorial\n for factor_mul_to in range(1, int(op) + 1):\n facto = facto * factor_mul_to\n if self.too_long(facto):\n print(\"the number is too long\")\n return None\n return facto\n\n def neg(self, op):\n return op * -1\n\n # average\n def ave(self, op1, op2):\n return (op1 + op2) / 2\n\n def operators_func(self, ope, op1, op2):\n if ope is '+':\n return self.plus(op1, op2)\n elif ope is '-':\n return self.minus(op1, op2)\n elif ope is '*':\n return self.mul(op1, op2)\n elif ope is '/':\n return self.dev(op1, op2)\n elif ope is '^':\n return self.power(op1, op2)\n elif ope is '%':\n return self.mod(op1, op2)\n elif ope is '@':\n return self.ave(op1, op2)\n elif ope is '$':\n return self.ma(op1, op2)\n elif ope is '&':\n return self.mi(op1, op2)\n elif ope is '!':\n return self.fact(op1)\n elif ope is '~':\n return self.neg(op2)\n else:\n print(\"problem\")\n return None\n '''\n return {\n '+': plus(op1, op2),\n '-': minus(op1, op2),\n '*': mul(op1, op2),\n '/': dev(op1, op2),\n '^': power(op1, op2),\n '%': mod(op1, op2),\n '@': ave(op1, op2),\n '$': ma(op1, op2),\n '&': mi(op1, op2),\n '!': fact(op1),\n '~': neg(op1)\n }.get(ope, None) # the operator is not founded\n '''\n\n\nclass SolveTheExpression:\n def __init__(self, expression):\n self.expression = expression\n self.flag_err = False\n self.flag_end = False\n\n # find the index of the next operator to solve\n def find_index_Of_ope(self):\n max_str = -1\n index_temp = -1\n for operator_index in range(0, len(self.expression)):\n # its an operator\n if self.expression[operator_index] in OPERA_TABLE.keys():\n # find the max from the values\n if OPERA_TABLE.get(self.expression[operator_index]) > max_str:\n max_str = OPERA_TABLE.get(self.expression[operator_index])\n index_temp = operator_index\n\n return index_temp\n\n # algorithm: get sort list of indexes of operators from the one of the most priority to least\n '''\n list_of_indexes = []\n max_str = -1\n counter = 0\n index_temp=0\n for op in express:\n if express[op] in OPERA_TABLE.keys():\n counter += 1\n while counter != 0:\n for op in range(0, len(express)):\n if express[op] in OPERA_TABLE.keys():\n if OPERA_TABLE.get(express[op]) > max_str and op not in list_of_indexes:\n max_str = OPERA_TABLE.get(express[op])\n index_temp = op\n list_of_indexes.append(index_temp)\n counter -= 1\n max_str = -1\n index_temp=0\n\n return list_of_indexes\n '''\n\n # check if the member is a number\n def check_if_number(self, index_of_ope, add_index):\n if type(self.expression[index_of_ope + add_index]) == int:\n return True\n if type(self.expression[index_of_ope + add_index]) == float:\n return True\n return False\n\n # remove the exercise and put the answer\n def change_to_answer(self, index_of_ope, minus_index, temp_number, rang):\n for times_to_delete in range(0, rang):\n self.expression.pop(index_of_ope - minus_index)\n self.expression.insert(index_of_ope - minus_index, temp_number)\n\n def ope_in_last(self, index_of_ope):\n # its operator that only needs the number before him\n if self.expression[index_of_ope] in OPERA_AFTER:\n # the member before him is number\n if self.check_if_number(index_of_ope, -1) is True:\n # cant make it shorter\n temp_number = OperatorsFun().operators_func(self.expression[index_of_ope],\n self.expression[index_of_ope - 1], 0)\n # problem during the calculating\n if temp_number is None:\n return None\n self.change_to_answer(index_of_ope, 1, temp_number, 2)\n else:\n print(\"input was bad (operator was done without a number)\")\n self.flag_err = True\n\n else:\n print(\"input was bad (operator was used without reason)\")\n self.flag_err = True\n return 0\n\n def minus_in_first(self, index_of_ope):\n # there is a number after the minus\n if self.check_if_number(index_of_ope, 1) is True:\n # put the negtive number in the place of the minus number\n temp_number = OperatorsFun().minus(0, self.expression[index_of_ope + 1])\n self.change_to_answer(index_of_ope, 0, temp_number, 2)\n else:\n print(\"input was bad (sequence of operators)\")\n self.flag_err = True\n\n # the condition in the while in the \"tilda_counter\" function\n def condition_to_stop_in_tilda(self, index_of_ope, counter_of_neg):\n if self.expression[index_of_ope + counter_of_neg] is '-':\n return True\n if self.expression[index_of_ope + counter_of_neg] is '~':\n return True\n return False\n\n # check which sign should the number after the tilda has\n def tilda_counter(self, index_of_ope):\n counter_of_neg = 0\n # while the operators are - or ~\n while self.condition_to_stop_in_tilda(index_of_ope, counter_of_neg) is True:\n counter_of_neg += 1\n # if there is a number after the operators\n if self.check_if_number(index_of_ope, counter_of_neg) is True:\n return counter_of_neg\n else:\n return -1\n\n def ope_before(self, index_of_ope):\n # its operator that only needs the number after him\n counter_of_neg = self.tilda_counter(index_of_ope)\n # check if it is legal (there was number after the operators)\n if counter_of_neg is -1:\n self.flag_err = True\n else:\n temp_number = self.expression[index_of_ope + counter_of_neg]\n # check which sign should the number have\n if counter_of_neg % 2 is 1:\n temp_number = OperatorsFun().minus(0, self.expression[index_of_ope + counter_of_neg])\n self.change_to_answer(index_of_ope, 0, temp_number, counter_of_neg + 1)\n return 0\n\n def ope_in_mid(self, index_of_ope):\n # the next member is minus\n if self.expression[index_of_ope + 1] is '-':\n # there is a number after the minus\n if self.check_if_number(index_of_ope, 2) is True:\n temp_number = OperatorsFun().minus(0, self.expression[index_of_ope + 2])\n self.change_to_answer(index_of_ope, -1, temp_number, 2)\n else:\n print(\"input was bad (sequence of operators)\")\n self.flag_err = True\n if self.flag_err is False:\n # there is a number after the operator\n if self.check_if_number(index_of_ope, 1) is True:\n # cant make it shorter\n temp_number = OperatorsFun().operators_func(self.expression[index_of_ope],\n self.expression[index_of_ope - 1],\n self.expression[index_of_ope + 1])\n # problem during the calculating\n if temp_number is None:\n return None\n self.change_to_answer(index_of_ope, 1, temp_number, 3)\n else:\n print(\"input was bad (sequence of operators)\")\n self.flag_err = True\n return 0\n\n def solver(self):\n index_of_ope = 0\n temp_number = 0\n # run till the end\n while self.flag_err is False and self.flag_end is False:\n # the answer\n if len(self.expression) is 1:\n if self.check_if_number(0, 0) is True:\n self.flag_end = True\n else:\n print(\"sorry bad input \", self.expression, \" cant be solved\")\n self.flag_err = True\n else:\n index_of_ope = self.find_index_Of_ope()\n # operator is not founded but there are more than one member in the list\n if index_of_ope is -1:\n print(\"input was bad (two numbers without operator)\")\n self.flag_err = True\n # the operator in the last place\n elif index_of_ope is (len(self.expression) - 1):\n if self.ope_in_last(index_of_ope) is None:\n return None\n\n elif index_of_ope is 0:\n # the first member in the list is minus\n if self.expression[index_of_ope] is '-':\n self.minus_in_first(index_of_ope)\n # the first member in the list is operator that need a number after him\n elif self.expression[index_of_ope] in OPERA_BEFORE:\n if self.ope_before(index_of_ope) is None:\n return None\n else:\n print(\"bad input, wrong use of operator in the expression:\", self.expression)\n return None\n # the operator is in the list of the expression and not in the last place\n else:\n # the operator need a number after him\n if self.expression[index_of_ope] in OPERA_BEFORE:\n if self.ope_before(index_of_ope) is None:\n return None\n # the member before him is number\n elif self.check_if_number(index_of_ope, -1) is True:\n # its not a operator that only needs the number before him\n if self.expression[index_of_ope] not in OPERA_AFTER:\n if self.ope_in_mid(index_of_ope) is None:\n return None\n # its a operator that only needs the number before him\n else:\n # cant make it shorter\n temp_number = OperatorsFun().operators_func(self.expression[index_of_ope],\n self.expression[index_of_ope - 1], 0)\n # problem during the calculating\n if temp_number is None:\n return None\n self.change_to_answer(index_of_ope, 1, temp_number, 2)\n else:\n print(\"input was bad (operator was used without reason)\")\n self.flag_err = True\n # it couldn't solve the expression\n if self.flag_err is True:\n return None\n return self.expression\n\n\nclass SolveTheInput:\n\n def __init__(self, expression):\n self.expression = expression\n self.list_of_express = []\n self.counter = 0\n\n # to solve the expression between the brackets\n def list_solve(self):\n if len(self.list_of_express) <= 0:\n print(\"bad input: the brackets arent good\")\n return None\n\n len_of_sub_list = 0\n # get the whole expression that is between the brackets\n while self.list_of_express[len(self.list_of_express) - 1 - len_of_sub_list] != '(':\n if len(self.list_of_express) - len_of_sub_list <= 0:\n print(\"bad input: the brackets arent good\")\n return None\n # next\n len_of_sub_list = len_of_sub_list + 1\n # get the sub expression(the one to solve now)\n temp_expr = self.list_of_express[len(self.list_of_express) - len_of_sub_list:len(self.list_of_express)]\n temp_answer = SolveTheExpression(temp_expr).solver()\n # problem in solving the expression\n if temp_answer is None:\n return None\n # delete from the list the expression\n for times_of_delete in range(0, len_of_sub_list + 1):\n self.list_of_express.pop(len(self.list_of_express) - 1)\n # add the answer\n self.list_of_express.append(temp_answer[0])\n return 0\n\n # check the number before convert\n def check_number(self, string_number):\n # check if there is e\n if string_number.count('e') > 1:\n print(\"bad input: \" + string_number + \" not possible \")\n return False\n elif string_number.count('e') == 1:\n if string_number.find('e') == 0 or string_number.find('e') == (len(string_number) - 1):\n print(\"bad input: \" + string_number + \"not possible \")\n return False\n\n # check if there is .\n if string_number.count('.') > 1:\n print(\"bad input: \" + string_number + \" not possible \")\n return False\n elif string_number.count('.') == 1:\n if string_number.find('.') == 0 or string_number.find('.') == (len(string_number) - 1):\n print(\"bad input: \" + string_number + \" not possible \")\n return False\n\n # check in the number is in possible length\n if sys.float_info.max < float(string_number):\n print(\"the number is too long\")\n return False\n return True\n\n # convert the number\n def create_number_to_stack(self, string_number):\n try:\n return float(string_number)\n except ValueError:\n\n print(\"sorry \" + string_number + \" isn't a number\")\n return None\n\n def check_in_create_number(self, counter2, size_of_express):\n if (self.counter + counter2) < size_of_express:\n if self.expression[self.counter + counter2] in LEGAL_TABS:\n if self.expression[self.counter + counter2] not in ARE_NOT_FOR_NUMBERS:\n return True\n return False\n\n def condition_check_operator_in_e(self, counter2):\n if self.expression[self.counter + counter2 + 1] is '-':\n return True\n if self.expression[self.counter + counter2 + 1] is '+':\n return True\n return False\n\n def is_an_e(self, counter2, size_of_express):\n # if the char is e\n if self.expression[self.counter + counter2] is 'e':\n # and the next char is not the end\n if (self.counter + counter2 + 1) < size_of_express:\n # if the next char is plus or minus\n if self.condition_check_operator_in_e(counter2) is True:\n # if the char after him is not the end\n if (self.counter + counter2 + 2) < size_of_express:\n if self.expression[self.counter + counter2 + 2].isdigit():\n return True\n return None\n return False\n\n # get the number from the whole expression\n def number_in_express(self, size_of_express):\n counter2 = 0\n temp_the_number_string = \"\"\n temp_the_number = 0\n\n # while the chars are chars that are used for create number and it is not the end of the expression\n while self.check_in_create_number(counter2, size_of_express):\n # a number that contain 3\n if self.is_an_e(counter2, size_of_express) is not False:\n # the number can be created\n if self.is_an_e(counter2, size_of_express) is True:\n for add_counter in range(0, 3):\n temp_the_number_string += self.expression[self.counter + counter2]\n counter2 += 1\n else:\n print(\"sorry input is not good, the syntax of e is num1+/-num2 \")\n return None\n else:\n temp_the_number_string += self.expression[self.counter + counter2]\n counter2 += 1\n # problem in creating the number\n if self.check_number(temp_the_number_string) is False:\n return None\n # create te number\n else:\n temp_the_number = self.create_number_to_stack(temp_the_number_string)\n if temp_the_number is None:\n print(\"problem in the input\")\n return None\n else:\n self.list_of_express.append(temp_the_number)\n\n self.counter = self.counter + counter2 - 1\n return 0\n\n def create_stack(self):\n # print(express)\n print(self.expression)\n size_of_express = len(self.expression)\n\n while self.counter < size_of_express:\n # the char is (\n if self.expression[self.counter] is '(':\n self.list_of_express.append(self.expression[self.counter])\n # the char is )\n elif self.expression[self.counter] is ')':\n if self.list_solve() is None:\n return None\n elif self.expression[self.counter].isdigit():\n if self.number_in_express(size_of_express) is None:\n return None\n # the char is a an operator\n else:\n self.list_of_express.append(self.expression[self.counter])\n self.counter += 1\n # problem in solving the expression\n answer_of_the_express = SolveTheExpression(self.list_of_express).solver()\n if answer_of_the_express is None:\n return None\n return answer_of_the_express[0]\n\n\ndef menu():\n print(\"welcome to my calculator\")\n flag_end = False\n # while the user didnt enter stop\n while flag_end is False:\n # get the expression\n express = GetInput().input_getter()\n print(\"the answer is :\", SolveTheInput(express).create_stack())\n print()\n # get if the user want to continue\n try:\n end_input = input(\"enter stop to end the program :\")\n if end_input == \"stop\":\n flag_end = True\n\n # out of memory exception\n except MemoryError:\n print(\"out of memory\")\n print(\"please try again\")\n except OverflowError as oe:\n print(\"After the Overflow error\", oe)\n print(\"please try again\")\n except RuntimeError:\n print(\"unexpected error\")\n print(\"please try again\")\n print()\n\n\nif __name__ == '__main__':\n menu()\n","repo_name":"nirdu/calculator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":29676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"74069898207","text":"import json\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.forms.widgets import Input\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import to_locale, get_language, ugettext as _\nfrom fields import ElfinderFile\nfrom conf import settings as ls\n\nclass ElfinderWidget(Input): \n \"\"\"\n A widget that opens the elfinder file manager for selecting a file.\n ``attrs``\n The TextInput attrs\n ``options``\n Optional. Sets the elfinder (client) configuration options\n ``optionset``\n The key of the ELFINDER_CONNECTOR_OPTION_SETS setting to use as connector settings \n \"\"\"\n input_type = 'hidden'\n \n def __init__(self, optionset, start_path, attrs={'size':'42'}, options={}):\n \n self.options, self.optionset, self.start_path = options, optionset, start_path\n super(ElfinderWidget, self).__init__(attrs)\n \n #locate current locale\n self.current_locale = to_locale(get_language()) \n\n def _media(self):\n \"\"\"\n Set the widget's javascript and css\n \"\"\"\n js = [ls.ELFINDER_JS_URLS[x] for x in sorted(ls.ELFINDER_JS_URLS)] + [ls.ELFINDER_WIDGET_JS_URL]\n screen_css = [ls.ELFINDER_CSS_URLS[x] for x in sorted(ls.ELFINDER_CSS_URLS)] + [ls.ELFINDER_WIDGET_CSS_URL]\n\n #add language file to javascript media\n if not self.current_locale.startswith('en') and self.current_locale in ls.ELFINDER_LANGUAGES:\n js.append('%selfinder.%s.js' % (ls.ELFINDER_LANGUAGES_ROOT_URL, self.current_locale))\n \n return forms.Media(css= {'screen': screen_css}, js = js)\n\n media = property(_media)\n \n def render(self, name, value, attrs=None):\n \"\"\"\n Display the widget\n \"\"\"\n #if self.optionset in ls.ELFINDER_CONNECTOR_OPTION_SETS and 'uploadAllow' in ls.ELFINDER_CONNECTOR_OPTION_SETS[self.optionset] and ls.ELFINDER_CONNECTOR_OPTION_SETS[self.optionset]['uploadAllow']:\n # html = '
(' + _('Allowed mime types: ') + str(ls.ELFINDER_CONNECTOR_OPTION_SETS[self.optionset]['uploadAllow']) + ')
'\n\n #update the elfinder client options\n self.options.update({ \n 'url' : reverse('yawdElfinderConnectorView', args=[\n self.optionset, \n 'default' if self.start_path is None else self.start_path\n ]),\n 'rememberLastDir' : True if not self.start_path else False,\n })\n \n if not 'rmSoundUrl' in self.options:\n self.options['rmSoundUrl'] = '%selfinder/sounds/rm.wav' % settings.STATIC_URL\n \n #update the elfinder client language\n if not self.current_locale.startswith('en') and self.current_locale in ls.ELFINDER_LANGUAGES:\n self.options.update({ 'lang' : self.current_locale })\n\n if value:\n if not isinstance(value, ElfinderFile):\n value = ElfinderFile(hash_=value, optionset=self.optionset)\n file_ = 'file : %s' % json.dumps(value.info)\n else:\n file_ = 'file : {}'\n \n elfinder = 'elfinder : %s' % json.dumps(self.options) \n \n html = ('%(super)s\\n'\n '' % {\n 'super' : super(ElfinderWidget, self).render(name, value, attrs),\n 'id' : attrs['id'],\n 'file' : file_,\n 'elfinder' : elfinder,\n #these keywords are optional, since they are initialized in elfinderwidget\n #we override them for localization purposes\n 'size' : _('Size'),\n 'path' : _('Path'),\n 'link' : _('Link'),\n 'modified' : _('Modified'),\n 'dimensions' : _('Dimensions'),\n 'update' : _('Update'),\n 'set' : _('Set'),\n 'clear' : _('Clear')\n })\n\n return mark_safe(html)\n","repo_name":"alaxli/ansible_ui","sub_path":"desktop/apps/ansible/elfinder/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","stars":329,"dataset":"github-code","pt":"88"} +{"seq_id":"25955731698","text":"from tkinter import *\nfrom random import randrange\n\n# --- Definitions des fonctions gestionnaire d'evenements --- :\ndef drawLine():\n\t\"tracer ligne\"\n\tglobal x1, x2, y1, y2, coul\n\tcan1.create_line(x1, y1, x2, y2, width=2, fill=coul)\n\n# --- Modifications des coordonnees pour ligne suivante --- :\n\ty2, y1 = y2+10, y1-10\n\ndef changeColor():\n\t\"changement aleatoire de la couleur\"\n\tglobal coul\n\tpal=['purple','cyan','maroon','green','red','blue','orange','yellow']\n\tc = randrange(8)\n\tcoul = pal[c]\n\n#----- main_prog ----- :\nx1, y1, x2, y2 = 10, 190, 190, 10\ncoul = 'dark green'\n# Creation du widget principal :\nfen1 = Tk()\n# Creation des widgets esclaves :\ncan1 = Canvas(fen1, bg='dark grey', height=200, width=200)\ncan1.pack(side=LEFT)\nbou1 = Button(fen1, text='Quitter', command=fen1.destroy)\nbou1.pack(side=BOTTOM)\nbou2 = Button(fen1, text='New line', command=drawLine)\nbou2.pack(side=LEFT)\nbou3 = Button(fen1, text='Autre couleur', command=changeColor)\nbou3.pack(side=BOTTOM)\n\nfen1.mainloop()","repo_name":"sle-lieg/python_ex","sub_path":"kint_ex/win.py","file_name":"win.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"23364839439","text":"import sys\ninput = lambda: sys.stdin.readline().rstrip()\n\nN, K = map(int, input().split())\nitems = [list(map(int, input().split())) for _ in range(N)]\nbag = [[0 for _ in range(K+1)] for _ in range(N+1)]\n\nfor i in range(1,N+1):\n for j in range(1, K+1):\n if items[i-1][0] > j:\n bag[i][j] = bag[i-1][j]\n else:\n bag[i][j] = max(items[i-1][1] + bag[i-1][j-items[i-1][0]], bag[i-1][j])\n\nprint(bag[N][K])\n\n\n#time over\n# def inbag(m,n,items,w):\n# global bag,vmax\n# if m == n:\n# return\n# else:\n# for i in range(len(items)):\n# if w > K:\n# break\n# bag.append(items[i])\n# wbag = sum(list(zip(*bag))[0])\n# vbag = sum(list(zip(*bag))[1])\n# if wbag <= K and vbag > vmax:\n# vmax = vbag\n# item = items[i+1:]\n# inbag(m+1, n, item,wbag)\n# bag.pop(-1)\n\n# N, K = map(int, input().split())\n# items = [list(map(int, input().split())) for _ in range(N)]\n# items = sorted(items, key = lambda x: (-x[0], -x[1]))\n# bag = []\n# vmax = 0\n\n# inbag(0,N,items,0)\n\n# print(vmax)","repo_name":"kim-seoyoung/basicprogramming","sub_path":"python/boj12865.py","file_name":"boj12865.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"35182897132","text":"\"\"\"\n座右铭:将来的你一定会感激现在拼命的自己\n@project:正课\n@author:Mr.Chen\n@file:使用类和对象加数据库完成学生信息管理系统.PY\n@ide:PyCharm\n@time:2018-08-03 14:09:12\n\"\"\"\nimport sqlite3\n# 声明一个数据模型类:只包含属性,不包含操作属性的函数\nclass StudentModle(object):\n def __init__(self,db_name,table_name,field_name,field_age,field_score,field_id):\n self.db_name = db_name\n self.table_name = table_name\n self.field_name = field_name\n self.field_age = field_age\n self.field_score = field_score\n self.field_id = field_id\n# 声明一个工具类,工具类一般只包含操作函数,不包含属性\nclass DBManager(object):\n # 定义一个创建库和游标的函数\n # stu_obj:StudentModle类生成的对象\n # stu_obj.db_name:StudentModle类中的db_name属性,对应的就是数据库名称\n def create_connet_and_cursor(self,stu_obj):\n self.connet = sqlite3.connect(stu_obj.db_name)\n self.cursor = self.connet.cursor()\n\n # 定义一个创建表的函数\n def create_table(self,stu_obj):\n create_sql = \"create table if not exists student\"+stu_obj.table_name+\"(%s INTEGER PRIMARY KEY,%s TEXT,%s TEXT,%s TEXT)\"%(stu_obj.field_id,stu_obj.field_name,stu_obj.field_age,stu_obj.field_score)\n self.cursor.execute(create_sql)\n\n # 定义一个添加数据的函数\n def insert_student_info(self,stu_obj):\n name = input('请输入添加学员的姓名:')\n age = int(input('请输入添加学员的姓名:'))\n score = int(input('请输入添加学员的姓名:'))\n inser_sql = \"insert into \"+stu_obj.table_name+\"(%s,%s,%s) values (%s,%s,%s)\"%(stu_obj.field_name,stu_obj.field_age,stu_obj.field_score,name,age,score)\n self.cursor.execute(inser_sql)\n\n # 定义一个查询数据库数据总量的函数\n def get_toble_count(self,stu_obj):\n select_sql=\"select count(*) from %s\"%(stu_obj.table_name)\n res = self.cursor.execute(select_sql)\n count= res.fetchone()[0]\n return count\n # 定义一个能否查询到ID对应数据的函数\n def get_id_true_or_false(self,stu_obj,number):\n select_number = \"select * from %s where id=%d\"%(stu_obj.table_name,number)\n res = self.cursor.execute(select_number)\n result = res.fetchall()\n return len(result)\n\n # 定义一个查询数据的函数\n def select_student_info(self,stu_obj):\n count = self.get_toble_count(stu_obj)\n if count!=0:\n select_sql = \"select * from \"+stu_obj.table_name\n result = self.cursor.execute(select_sql)\n for id,name,age,score in result:\n print(id,'.',name,age,score)\n else:\n print('学员信息为空,无法查询')\n # 定义一个更改数据的函数\n def update_student_info(self,stu_obj):\n count = self.get_toble_count(stu_obj)\n if count!=0:\n self.select_student_info(stu_obj)\n number = int(input('请输入要修改的学员的编号:'))\n while self.get_id_true_or_false(stu_obj,number)==False:\n number = int(input('输入错误,请重新输入要修改的学员编号:'))\n name = input('请输入新的姓名:')\n age = int(input('请输入新的年龄:'))\n score = int(input('请输入新的分数:'))\n update_sql=\"update\"+stu_obj.table_name+\"set %s='%s',%s='%s',%s='%s' where %s=%s\"%(stu_obj.field_name,name,stu_obj.field_age,age,stu_obj.field_score,score,stu_obj.field_id,number)\n self.cursor.execute(update_sql)\n else:\n print('学员信息为空,无法修改')\n # 定义删除数据的函数\n def delect_test(self,stu_obj):\n count= self.get_toble_count(stu_obj)\n if count!=0:\n self.select_student_info(stu_obj)\n print('1-根据学员序号删除学员信息')\n print('2-删除所有学员信息')\n select_number = int(input('请输入你要操作的序号:'))\n while select_number!=1 and select_number!=2:\n select_number = int(input('输入错误,重新输入:'))\n if select_number==1:\n number = int(input('请输入要删除的学员序号:'))\n while self.get_id_true_or_false(stu_obj,number)==False:\n number = int(input('序号输入错误,请重新输入要删除的学员序号:'))\n delect_sql = \"delect from %s where id=%d\"%(stu_obj.table_name,number)\n else:\n delect_sql = \"delect from %s\"%(stu_obj.table_name)\n self.cursor.execute(delect_sql)\n else:\n print('学员信息为空,无法删除')\n # 定义一个关闭数据库连接和游标的函数\n def close_db_and_commit(self):\n self.connet.commit()\n self.cursor.close()\n self.connet.close()\n\n\nif __name__ == '__main__':\n student = StudentModle('Student_Plus.db','student','name','age','score','id')\n db_manager = DBManager()\n db_manager.create_connet_and_cursor(student)\n db_manager.create_table(student)\n while True:\n print('''\n 1-添加学员信息\n 2-修改学员信息\n 3-查询学员信息\n 4-删除学员信息\n 0-退出程序\n ''')\n select_number=int(input('请选择操作序号:'))\n while select_number<0 or select_number>4:\n select_number = int(input('输入错误,请重新选择操作序号:'))\n if select_number==1:\n db_manager.insert_student_info(student)\n elif select_number==2:\n db_manager.update_student_info(student)\n elif select_number==3:\n db_manager.select_student_info(student)\n elif select_number==4:\n db_manager.delect_test(student)\n else:\n db_manager.close_db_and_commit()\n\n\n\n\n\n","repo_name":"qq1295334725/zheng","sub_path":"第二周/8-3/使用类和对象加数据库完成学生信息管理系统.py","file_name":"使用类和对象加数据库完成学生信息管理系统.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"39986739421","text":"from egzP3atesty import runtests\nfrom math import inf\n\nclass Node:\n def __init__(self, wyborcy, koszt, fundusze):\n self.next = None\n self.wyborcy = wyborcy \n self.koszt = koszt \n self.fundusze = fundusze \n self.x = None\n\n\ndef vote(T):\n m = len(T)\n\n votes = 0\n\n for i in range(m):\n wo = tmp = T[i]\n p = wo.fundusze\n n = 0\n while tmp != None:\n tmp = tmp.next\n n += 1\n \n DP = [[None for i in range(p+1)] for i in range(n)]\n votes += rec(wo,p,DP,idx = 0)\n \n return votes\n\n\ndef rec(wo,p,DP,idx):\n\n if wo == None or p == 0:\n return 0\n\n if DP[idx][p] != None:\n return DP[idx][p]\n \n if wo.koszt <= p:\n DP[idx][p] = max(wo.wyborcy + rec(wo.next,p - wo.koszt,DP,idx + 1), rec(wo.next,p,DP,idx+1))\n return DP[idx][p]\n \n elif wo.koszt > p:\n DP[idx][p] = rec(wo.next, p, DP, idx+1)\n return DP[idx][p]\n\ndef wybory(T):\n #tutaj proszę wpisać własną implementację\n return vote(T)\n\nruntests(wybory, all_tests = True)","repo_name":"remekozicki/ASD","sub_path":"do_egz_t2/zadania_wiki_wakacje/egz3a/p3a/egzP3a.py","file_name":"egzP3a.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"8826290584","text":"m = int(input())\ni = 2\nj = 2\nrems = []\nrems2 = []\nn = 2\nwhile i <= m <= 40:\n\trem = int(input())\n\trems.append(rem)\n\ti += 1\nprint(rems)\nwhile rems2 != rems:\n\twhile j <= m <= 40:\n\t\trems2.append(n % j)\n\t\tj += 1\n\tif rems2 != rems:\n\t\tn += 1\n\t\trems2 = []\n\t\tj = 2\nprint(n)","repo_name":"De1f364/tinkoff_summer_internship_2019","sub_path":"ex02/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"29972679178","text":"# This benchmark should be ran on the GPU.\n\nimport timeit\n\nimport diffrax as dfx\nimport jax\nimport jax.lax as lax\nimport jax.numpy as jnp\n\n\n# SETUP\n\nN = 256\nN_steps = 2000\nts = jnp.linspace(0, 1, N_steps + 1)\nu0, v0 = jnp.zeros((N, N)), jnp.zeros((N, N)).at[32, 32].set(1.0)\nfields = (u0, v0)\ndu = lambda t, v, args: -(v**2)\ndv = lambda t, u, args: -jnp.fft.irfft(jnp.sin(jnp.fft.rfft(u)))\nsample = lambda t, y, args: y[0][64, 64] # Some arbitrary sampling function\n\n\ndef speedtest(fn, name):\n fwd = jax.jit(fn)\n bwd = jax.jit(jax.grad(fn))\n integration_times = timeit.repeat(\n lambda: jax.block_until_ready(fwd(fields, ts)), number=1, repeat=10\n )\n print(f\"{name} fwd: {min(integration_times)}\")\n grad_times = timeit.repeat(\n lambda: jax.block_until_ready(bwd(fields, ts)), number=1, repeat=10\n )\n print(f\"{name} fwd+bwd: {min(grad_times)}\")\n\n\n# INTEGRATE WITH scan\n\n\n@jax.checkpoint\ndef body(carry, t):\n u, v, dt = carry\n u = u + du(t, v, None) * dt\n v = v + dv(t, u, None) * dt\n return (u, v, dt), sample(t, (u, v), None)\n\n\ndef scan_fn(fields, t):\n dt = t[1] - t[0]\n carry = (fields[0], fields[1], dt)\n _, values = lax.scan(body, carry, t[:-1])\n return jnp.mean(values**2)\n\n\nspeedtest(scan_fn, \"scan\")\n\n\n# INTEGRATE WITH SemiImplicitEuler\n\n\n@jax.jit\ndef dfx_fn(fields, t):\n return dfx.diffeqsolve(\n terms=(dfx.ODETerm(du), dfx.ODETerm(dv)),\n solver=dfx.SemiImplicitEuler(),\n t0=t[0],\n t1=t[-1],\n dt0=None,\n y0=fields,\n args=None,\n saveat=dfx.SaveAt(steps=True, fn=sample, dense=False),\n stepsize_controller=dfx.StepTo(ts),\n adjoint=dfx.RecursiveCheckpointAdjoint(checkpoints=N_steps),\n max_steps=N_steps,\n throw=False,\n ).ys\n\n\nspeedtest(dfx_fn, \"SemiImplicitEuler\")\n","repo_name":"patrick-kidger/diffrax","sub_path":"benchmarks/against_scan.py","file_name":"against_scan.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":1063,"dataset":"github-code","pt":"88"} +{"seq_id":"23611571477","text":"from app.config.config import db\nfrom sqlalchemy.orm.exc import NoResultFound\n\nuser_categories = db.Table('user_categories',\n db.Column(\"user_id\", db.String, db.ForeignKey(\"user.id\")),\n db.Column(\"category_id\", db.Integer, db.ForeignKey(\"category.id\"))\n )\n\n\nclass Category(db.Model):\n __tablename__ = 'category'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(255), nullable=False, unique=True)\n user_products = db.relationship(\"UserProduct\", back_populates=\"category\")\n\n\nclass CategoryActions:\n model = Category\n\n @classmethod\n def filter(cls, user, **kwargs):\n if 'id' in kwargs and kwargs['id'] is not None:\n return cls.model.query.filter_by(id=kwargs['id']).all()\n else:\n return cls.model.query.all()\n\n @classmethod\n def find_all(cls):\n return cls.model.query.all()\n\n @classmethod\n def find_by_id(cls, id):\n try:\n category = cls.model.query.filter_by(id=id).one()\n return category\n except Exception as e:\n print(e)\n return None\n\n @classmethod\n def find_by_name(cls, name):\n try:\n category = cls.model.query.filter_by(name=name).one()\n return category\n except NoResultFound:\n return None\n\n @classmethod\n def create(cls, name):\n try:\n new_category = cls.model(name=name)\n db.session.add(new_category)\n db.session.commit()\n return new_category\n except Exception as e:\n print(e)\n return None\n","repo_name":"davidmaignan/giftsmarts","sub_path":"app/models/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"43245246776","text":"\"\"\"\nfile: Neural_network.py\nAuthor: Petri Lamminaho\nemail: lammpe77@gmail.com\n\"\"\"\nfrom numpy import random, array, exp, dot\n\nclass Neural_network():\n\n def __init__(self):\n \"\"\"\n constructor\n \"\"\"\n random.seed(1) # antaa ainna samat numerot kun ohjelma käy\n self.synaptic_weights = 2 * random.random((3, 1)) - 1 # luo neutronin jolla on\n # kolme inputtia ja antaa yhden(1) outputi\n#-----------------------------------------------------------------------------------------------------------\n def __sigmoid(self, x):\n \"\"\"\n private function\n sigmoid function pass the data\n and normalize data to 1 or 0\n :param x:\n :return: 1 or 0\n \"\"\"\n return 1 / (1 + exp(-x))\n#--------------------------------------------------------------------------------------------------\n def __sigmoid_derivative(self, x):\n \"\"\"\n private function\n :param x:\n :return derivative function :\n \"\"\"\n return x * (1 - x)\n#----------------------------------------------------------------------------------\n def train(self, training_inputs, training_outputs, num_of_training_iterations):\n \"\"\"\n trains network\n :param training_inputs:\n :param training_outputs:\n :param num_of_training_iterations:\n \"\"\"\n for iteration in range(num_of_training_iterations):\n output = self.think(training_inputs)\n error = training_outputs - output\n #print(\"error:\", error)\n adjustment = dot(training_inputs.T, error * self.__sigmoid_derivative(output))\n # Adjust the weights.\n self.synaptic_weights += adjustment\n #---------------------------------------------------------------------------------------------\n def think(self, inputs):\n \"\"\"\n network \"thinks\"\n network thinks\n :param inputs:\n :return: sigmoid function\n pass the data (inputs) through the network\n single neutron\n \"\"\"\n return self.__sigmoid(dot(inputs, self.synaptic_weights))\n#-------------------------------------------------------------------------------------------------------\n\"\"\"\nmain function \n\"\"\"\n\nif __name__ == \"__main__\":\n nn = Neural_network()\n print(\"random start weights\")\n print(nn.synaptic_weights)\n training_data_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])\n training_data_outputs = array([[0, 1, 1, 0]]).T\n print(\"Training data inputs:\")\n print(training_data_inputs)\n print(\"Training data outputs:\")\n print(training_data_outputs)\n nn.train(training_data_inputs, training_data_outputs, 10000)\n print(\"New weights after training: \")\n print(nn.synaptic_weights)\n\n # Test the neural network with a new input\n print (\"Trying new input data [1, 0, 0 ] -> ?: ( output should be close 1\")\n print(\"result:\",nn.think(array([1, 0, 0]))) #output: 0.99993704\n","repo_name":"pelammin77/neural_network_single_layer","sub_path":"neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"15226298170","text":"import numpy as np\r\nimport os\r\nfrom tensorflow import keras\r\nfrom keras import layers\r\nfrom PIL import Image, ImageOps\r\nfrom numpy import asarray\r\nimport random\r\n\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\r\n\r\n#establish number of images, labels, and image resolution\r\n#create label array for training data and convert to one-hot ecoded form\r\nnumImages = 17\r\nnum_classes = 8\r\ninput_shape = (600,800,1)\r\ny = np.array([7,0,6,2,4,4,7,3,3,0,4,6,6,2,2,4,0])\r\ny = keras.utils.to_categorical(y, num_classes)\r\n\r\n#import first image and convert to grayscale array\r\nfirstImage = Image.open(\"0.jpg\")\r\nfirstGrayImage = ImageOps.grayscale(firstImage)\r\nx = asarray(firstGrayImage)\r\n\r\n#import remaining images and append to array\r\nfor i in range(1,numImages):\r\n filename = str(i) + \".jpg\"\r\n image = Image.open(filename)\r\n grayimage = ImageOps.grayscale(image)\r\n imgdata = asarray(grayimage)\r\n x = np.dstack([x,imgdata])\r\n \r\n#convert x value range to 0-1, format tensor for network\r\nx = x.astype(\"float32\") / 255\r\n\r\n#duplicate data for augmentation\r\nx = np.dstack([x,x,x,x,x,x,x,x,x,x])\r\ny = np.vstack([y,y,y,y,y,y,y,y,y,y])\r\n\r\n#augment data with horizontal and vertical mirroring\r\nfor i in range(numImages*10):\r\n if random.randint(1,4)==2:\r\n x[i] = np.fliplr(x[i])\r\n if random.randint(1,4)==2:\r\n x[i] = np.flipud(x[i])\r\n \r\n\r\n#format data\r\nx = np.expand_dims(x, 2)\r\nx = np.moveaxis(x,3,0)\r\n\r\n\r\n\r\n\r\n#create model - two convolution layers followed by max pooling,\r\n#flatten then dense multi-layer percpetron into output\r\nmodel = keras.Sequential(\r\n [\r\n keras.Input(shape=input_shape),\r\n layers.Conv2D(16, kernel_size=(3,3), activation=\"relu\"),\r\n layers.MaxPooling2D(pool_size=(2,2)),\r\n layers.Conv2D(32, kernel_size=(3,3), activation=\"relu\"),\r\n layers.MaxPooling2D(pool_size=(2,2)),\r\n layers.Flatten(),\r\n layers.Dropout(0.5),\r\n layers.Dense(num_classes, activation=\"softmax\"),\r\n \r\n ]\r\n )\r\n\r\n#print model summary\r\nmodel.summary()\r\n\r\n#define parameters for training\r\nbatch_size = 4\r\nepochs = 3\r\n\r\n#compile and train model\r\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=\"adam\", metrics=[\"accuracy\"])\r\nmodel.fit(x, y, batch_size=batch_size, epochs=epochs, validation_split=0.1)\r\n","repo_name":"elliottdruga/ML-Climber-Grading","sub_path":"handNN.py","file_name":"handNN.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"25263336522","text":"import sys\nfrom ViaBTCAPI.ViaBTCAPI import ViaBTCAPI\n\nMARKET_NAME = \"TESTNET3RINKEBY\"\nEXCHANGE_URL = \"http://localhost:8080/\" # choose to your exchange url\napi = ViaBTCAPI(EXCHANGE_URL)\n\nob = api.order_depth(market=MARKET_NAME)[\"result\"]\nbids = ob[\"bids\"]\nasks = ob[\"asks\"]\nfor price, volume in bids[::-1]:\n print(\"BID\\t price: {}\\t volume: {}\".format(price, volume))\n\nfor price, volume in asks:\n print(\"ASK\\t price: {}\\t volume: {}\".format(price, volume))\n","repo_name":"ohld/python-viabtc-api","sub_path":"examples/show_orderbook.py","file_name":"show_orderbook.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"88"} +{"seq_id":"17716813149","text":"#from range_service import RangeService, RangeResult\nfrom application.range_service import RangeService\nfrom dkhs.manager_perf_on_fund import ManagerPerformance, ManagerPerformanceService\n\nfrom tinydb import TinyDB\nfrom datetime import date\n\ntoday_text = '20171222'#date.today().strftime('%Y%m%d')\n\ndef get_all_fund_code():\n db = TinyDB('data/fundlist_db.json')\n fund_table = db.table('fund')\n return [f['code'] for f in fund_table.all()]\n\ndef archive_fund_performance(archive_name, fund_perf_list):\n print('Archiving to data/'+archive_name+'.json...')\n perf_db = TinyDB('data/'+archive_name+'.json')\n perf_fund_table = perf_db.table('fund')\n perf_db.purge_table('fund')\n perf_fund_table.insert_multiple({\n 'code':f.fund_code, 'name':f.fund_name, 'category':f.category_text,\n 'score':f.score, 'percent':f.score_percent, \n 'suggestion':f.suggestion, 'conclude':f.conclude_statement\n } for f in fund_perf_list)\n print('Archived.')\n\ndef archive_fund_category_performance(archive_name, fund_perf_list):\n print('Archiving to data/'+archive_name+'.json...')\n perf_db = TinyDB('data/'+archive_name+'.json')\n perf_fund_table = perf_db.table('fund')\n perf_db.purge_table('fund')\n perf_fund_table.insert_multiple({\n 'code':f['code'], 'name':f['name'], 'category':f['category'],\n 'score':f['score'], 'percent':f['percent'], \n 'suggestion':f['suggestion'], 'conclude':f['conclude']\n } for f in fund_perf_list)\n print('Archived.') \n\ndef list_fund_performance_archive(archive_name):\n perf_db = TinyDB('data/'+archive_name+'.json') \n fund_table = perf_db.table('fund')\n return fund_table.all()\n\ndef load_all_fund_perform_info(fund_codes_list):\n '''\n download all the performance data from web\n '''\n fund_performance_list = []\n mp_service = ManagerPerformanceService()\n if(len(fund_codes_list) > 0):\n print('loading funds...')\n fund_performance_list = list(filter(lambda f:f.score > 0, [mp_service.get_performance_on_fund(f) for f in fund_codes_list]))\n print('funds loaded')\n return fund_performance_list\n\ndef save_archive_performance_all(performance_list):\n import pyodbc\n cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=.\\\\dblab;DATABASE=richlab;UID=richuser;PWD=1')\n cursor = cnxn.cursor()\n archive_date = '2017-12-22'#date.today().strftime('%Y-%m-%d')\n for p in performance_list:\n cursor.execute(\"insert into dkhs_fund_performance ([code],[archive_date],[score],[score_percent],[suggestion],[conclude],[category]) values (?,?,?,?,?,?,?)\",\n p['code'], today_text, p['score'], p['percent'], p['suggestion'], p['conclude'], p['category'])\n cnxn.commit() \n\n#002906\nfund_codes_list = get_all_fund_code()#['002906','002620','110022','000706','501021','002330']#\nservice = RangeService(fund_codes_list)\n#all_fund_perform_list = load_all_fund_perform_info(fund_codes_list)\n#archive_fund_performance('all_fund_perform_list_'+today_text, all_fund_perform_list)\nservice.fund_performance_list = list_fund_performance_archive('all_fund_perform_list_'+today_text)\n#save_archive_performance_all(service.find_good_funds_score_sort())\n'''\nbest_top500_index_funds = service.find_best_top500_funds(['指数型'])\narchive_fund_category_performance('best_top500_index_funds_'+today_text, best_top500_index_funds)\n\nbest_top500_money_funds = service.find_best_top500_funds(['货币型'])\narchive_fund_category_performance('best_top500_money_funds_'+today_text, best_top500_money_funds)\n\nbest_top500_bond_funds = service.find_best_top500_funds(['债券型'])\narchive_fund_category_performance('best_top500_bond_funds_'+today_text, best_top500_bond_funds)\n\nbest_top500_allstock_funds = service.find_best_top500_funds(['混合型','股票型','指数型'])\narchive_fund_category_performance('best_top500_allstock_funds_'+today_text, best_top500_allstock_funds)\n\nbest_top500_qdii_funds = service.find_best_top500_funds(['QDII'])\narchive_fund_category_performance('best_top500_qdii_funds_'+today_text, best_top500_qdii_funds)\n\nb500_allstock_funds = list_fund_performance_archive('best_top500_allstock_funds_'+today_text)\nprint(b500_allstock_funds)\n\nb500_index_funds = list_fund_performance_archive('best_top500_index_funds_'+today_text)\nprint(b500_index_funds)\n\nbest_top500_allstock_excl_index_funds = service.find_best_top500_funds(['混合型','股票型'])\narchive_fund_category_performance('best_top500_allstock_excl_index_funds_'+today_text, best_top500_allstock_excl_index_funds)\nprint(list_fund_performance_archive('best_top500_allstock_excl_index_funds_'+today_text))\n\nb500_qdii_funds = list_fund_performance_archive('best_top500_qdii_funds_'+today_text)\nprint(b500_qdii_funds)\n\ngood_funds_score_sort_list_allstock = service.find_good_funds_score_sort(['混合型','股票型','指数型'])\narchive_fund_category_performance('good_funds_score_sort_list_allstock_' + today_text + '.json', good_funds_score_sort_list_allstock)\n\ngood_funds_score_sort_list_exc_index = service.find_good_funds_score_sort(['混合型','股票型','指数型'])\narchive_fund_category_performance('good_funds_score_sort_list_exc_index_' + today_text + '.json', good_funds_score_sort_list_exc_index)\n\nprint(good_funds_score_sort_list_allstock)\n#print(good_funds_score_sort_list_exc_index)\n\ngood_funds_score_sort_list_hybrid = service.find_good_funds_score_sort(['混合型'])\n#archive_fund_category_performance('good_funds_score_sort_list_hybrid_'+today_text+'.json', good_funds_score_sort_list_hybrid)\n\ngood_funds_score_sort_list_equity = service.find_good_funds_score_sort(['股票型'])\n#archive_fund_category_performance('good_funds_score_sort_list_equity_'+today_text+'.json', good_funds_score_sort_list_equity)\n\ngood_funds_score_sort_list_index = service.find_good_funds_score_sort(['指数型'])\n#archive_fund_category_performance('good_funds_score_sort_list_index_'+today_text+'.json', good_funds_score_sort_list_index)\n\ngood_funds_score_sort_list_bond = service.find_good_funds_score_sort(['债券型'])\n#archive_fund_category_performance('good_funds_score_sort_list_bond_'+today_text+'.json', good_funds_score_sort_list_bond)\n\nprint(good_funds_score_sort_list_bond)\n'''\n\n","repo_name":"biztudio/richlab","sub_path":"funds/src/service/application/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"5828266690","text":"#\r\n# [215] Kth Largest Element in an Array\r\n#\r\n# https://leetcode.com/problems/kth-largest-element-in-an-array\r\n#\r\n# Medium (38.83%)\r\n# Total Accepted: \r\n# Total Submissions: \r\n# Testcase Example: '[1]\\n1'\r\n#\r\n# Find the kth largest element in an unsorted array. Note that it is the kth\r\n# largest element in the sorted order, not the kth distinct element.\r\n#\r\n# For example,\r\n# Given [3,2,1,5,6,4] and k = 2, return 5.\r\n#\r\n#\r\n# Note: \r\n# You may assume k is always valid, 1 ≤ k ≤ array's length.\r\n#\r\n# Credits:Special thanks to @mithmatt for adding this problem and creating all\r\n# test cases.\r\n#\r\n\r\nimport heapq\r\n\r\n\r\nclass Solution(object):\r\n def findKthLargest(self, nums, k):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type k: int\r\n :rtype: int\r\n \"\"\"\r\n heapq.heapify(nums)\r\n for _ in range(len(nums) - k):\r\n heapq.heappop(nums)\r\n return heapq.heappop(nums)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n sol = Solution()\r\n arr = [3, 2, 1, 5, 6, 4]\r\n assert(sol.findKthLargest(arr, 2) == 5)\r\n","repo_name":"oneshan/Leetcode","sub_path":"accepted/215.kth-largest-element-in-an-array.py","file_name":"215.kth-largest-element-in-an-array.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"6886792379","text":"import re\nimport requests\n\nfrom bs4 import BeautifulSoup, Comment\n\nclass Article:\n def __init__(self, title, media, url):\n self.title = title\n self.media = media\n self.url = url\n self.content = ''\n self.rgxSplitter = re.compile('([.!?:-](?:[\"\\']|(?![0-9])))')\n\n def setContent(self, content):\n self.content = content\n\n def readContent(self):\n def is_splited_sentence(sents):\n return len(sents) > 1\n\n self.del_personal_info()\n docs = self.rgxSplitter.split(self.content)\n\n if not is_splited_sentence(docs): # 본문이 1줄이며, 위 정규식에 따라 split 되지 않음\n yield docs[0]\n else :\n for s in map(lambda a, b: a + b, docs[::2], docs[1::2]):\n if not s: continue\n yield s\n\n def del_personal_info(self):\n rmBracket = re.sub('(\\([^)]*\\)|\\[[^]]*\\])', '', self.content) # 괄호 안 내용 제거\n rmMedia = re.sub(self.media, ' ', rmBracket) # 언론사명 제거\n rmReporter = re.sub('[가-힣]{2,5}\\s?기자', ' ', rmMedia) # 기자 이름 제거\n rmEmail = re.sub('[0-9a-zA-Z]([-_\\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\\.]?[0-9a-zA-Z])*\\.[a-zA-Z]{2,3}', ' ', rmReporter) # 이메일 제거\n\n self.content = rmEmail\n\n\nclass ArticleHtmlParser:\n\n def __init__(self, url, userAgent):\n article_page_response = requests.get(url, headers={'User-Agent': userAgent})\n self.article_html = BeautifulSoup(article_page_response.text, \"html.parser\")\n self.redirectedUrl = self.article_html.find('meta', property='og:url')\n\n def checkUrlValid(self, regEx):\n try:\n return re.match(regEx, self.redirectedUrl['content']) is not None\n except Exception:\n return False\n\n def getUrl(self):\n return self.redirectedUrl['content']\n\n def get_text_without_children(self, tag):\n return ''.join(tag.find_all(text=True, recursive=False)).strip()\n\n def getArticleContent(self, tag, id):\n content = ''\n\n div = self.article_html.find(tag, id=id)\n if div is None:\n raise Exception(\"Page Not Found\")\n\n for element in div(text=lambda text: isinstance(text, Comment)):\n element.extract()\n\n divs = self.article_html.find_all(tag, {\"id\": id})\n\n for i in divs:\n content += self.get_text_without_children(i)\n\n return content\n","repo_name":"aqaqsubin/Article-Summarizer","sub_path":"src/crawl-news/common_module/articleHandler.py","file_name":"articleHandler.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"88"} +{"seq_id":"25591478727","text":"from twilio.rest import TwilioRestClient\r\n\r\naccount_sid = \"AC383235e5ab0c11f6cd6a26637c2aa5a1\" # Your Account SID from www.twilio.com/console\r\nauth_token = \"95faabae29dcd6527f594e3f31584939\" # Your Auth Token from www.twilio.com/console\r\n\r\nclient = TwilioRestClient(account_sid, auth_token)\r\n\r\nmessage = client.messages.create(body=\"Hello from Python\",\r\n to=\"+14156761595\", # Replace with your phone number\r\n from_=\"+14156826577\") # Replace with your Twilio number\r\n\r\nprint(message.sid)\r\n","repo_name":"sudoaman/webdev","sub_path":"Python/sendmessage.py","file_name":"sendmessage.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"874400354","text":"import sys\n\nsys.stdin = open('input.txt')\n\nT = 10\n\n# 중위 순회 함수\ndef inOrder(t, s):\n if s < len(t):\n fst = inOrder(t, s*2)\n scd = t[s]\n lst = inOrder(t, s*2+1)\n \n # 노드에서 왼쪽 노드가 없거나 오른쪽 노드가 없거나 둘 다 없을 수 있으므로\n # 모두 고려\n if fst and lst:\n return fst+scd+lst\n elif fst:\n return fst+scd\n elif lst:\n return scd+lst\n else:\n return scd\n\n\nfor tc in range(1, T + 1):\n # 정점 개수 입력받고 각 정점에 해당하는 알파벳 입력받기\n N = int(input())\n tree = [0] * (N + 1)\n children = [0] * (N + 1)\n \n # 글자 뒤에 들어오는 숫자 처리하며 트리에 추가\n for i in range(N):\n if i <= N // 2:\n node, c, *ch = input().split()\n else:\n node, c = input().split()\n node = int(node)\n tree[node] = c\n children[node] = ch\n\n # 트리 중위순회\n rlt = inOrder(tree, 1)\n\n print(f'#{tc} {rlt}')\n\n","repo_name":"surinkwon/TIL","sub_path":"python/SWEA/1231_중위순회/1231_중위순회.py","file_name":"1231_중위순회.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"30815501902","text":"# Runtime: 2577 ms (Top 35.48%) | Memory: 14.1 MB (Top 20.97%)\nfrom collections import defaultdict\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n def floydwarshall(n, edges):\n D = [[float('inf')]*n for _ in range(n)]\n for u, v in edges:\n D[u-1][v-1] = 1\n D[v-1][u-1] = 1\n for v in range(n):\n D[v][v] = 0\n for k in range(n):\n for i in range(n):\n for j in range(n):\n D[i][j] = min(D[i][j],D[i][k]+D[k][j])\n return D\n\n G = defaultdict(list)\n for v, w in edges:\n G[v-1].append(w-1)\n G[w-1].append(v-1)\n\n def dfs(G, v, V, visited):\n if v in visited: return\n visited.add(v)\n for w in G[v]:\n if w in V:\n dfs(G, w, V, visited)\n\n def check_connected(G, V):\n if not V: return False\n root = next(iter(V))\n visited = set()\n dfs(G, root, V, visited)\n return visited == V\n\n def max_distance(D, V):\n res = 0\n for v in V:\n for w in V:\n res = max(res, D[v][w])\n return res\n\n def solve(include, idx, ans, G, D):\n if idx == n:\n V = set(v for v in range(n) if include[v])\n if check_connected(G, V):\n d = max_distance(D, V)\n if d >= 1:\n ans[d-1] += 1\n else:\n solve(include, idx+1, ans, G, D)\n include[idx] = True\n solve(include, idx+1, ans, G, D)\n include[idx] = False\n\n D = floydwarshall(n, edges)\n include = [False] * n\n ans = [0]*(n-1)\n solve(include, 0, ans, G, D)\n return ans\n","repo_name":"AnasImloul/Leetcode-Solutions","sub_path":"scripts/algorithms/C/Count Subtrees With Max Distance Between Cities/Count Subtrees With Max Distance Between Cities.py","file_name":"Count Subtrees With Max Distance Between Cities.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":334,"dataset":"github-code","pt":"88"} +{"seq_id":"27732788742","text":"import psycopg2\nimport decimal\nimport re\nimport sys\nimport os\nfrom random import choice\n\nfrom .props import *\nfrom lib.print_helper import *\n\nclass ActiveRecord():\n\tproxy_table_class\t\t= None\n\tdebug_mode \t\t\t\t= False\n\tread_only\t\t\t\t= False\n\tlast_queries \t\t\t= dict()\n\ttable_definitions \t\t= dict()\n\ttable_current_step_id \t= dict()\n\trandom_selected_ids\t\t= dict()\n\tnext_cache_size \t\t= False\n\tnext_cache \t\t\t\t= []\n\tnext_filter\t\t\t\t= \" 1=1\"\n\tdefault_filter\t\t\t= False\n\tpluralise \t\t\t\t= True\n\tdefault_selects\t\t\t= \"*\"\n\tchoose_cache_size\t\t= 100\n\tchoose_cache\t\t\t= []\n\tchoose_cache_filter\t\t= \" 1 = 1 \"\n\timport_column_matcher\t= re.compile(\"^[a-z]|_[a-z]\")\n\trelations\t\t\t\t= {}\n\tmodules\t\t\t\t\t= {}\n\ttableClasses\t\t\t= {}\n\t@classmethod\n\tdef connect(self, username, databaseName, password, host=\"localhost\", port=5432):\n\t\tself.conn = psycopg2.connect(\n\t\t\tuser=username, host=host, database=databaseName, password=password, port=port\n\t\t)\n\t# # Connect to remote database.\n\tconn = False\n\t# conn = psycopg2.connect(\n\t\t# host=\"localhost\",\n\t\t# database='main',\n\t\t# user='postgres',\n\t\t# password='t4ba78iop',\n\t\t# port=5432)\n\n\n\tdef __init__(self, props):\n\t\tif isinstance(props, list):\n\t\t\ttempProps = dict()\n\t\t\tfor item in props:\n\t\t\t\ttempProps[item[0]] = item[1]\n\t\t\tprops = tempProps\n\t\tfor col in self.table_definitions[self.table_name()]:\n\t\t\tif col.name not in props:\n\t\t\t\tprops[col.name] = None\t\t\n\t\tself.properties = Props(props)\n\n\tdef __getitem__(self,name):\n\t\treturn self.__getattr__(name)\n\t#Sigh, Python sucks: Pickle needs this but since we use Props()\n\t#for properties it doesn't handle the set implicitly\n\tdef __getstate__(self):\n\t\toutput = dict(properties=dict())\n\t\tfor k, v in self.__dict__[\"properties\"].properties.items():\n\t\t\toutput[\"properties\"][k] = v\n\t\treturn output\n\tdef __setstate__(self,d):\n\t\tself.__dict__ = d\n\t# Dotted attribute access.\n\tdef __getattr__(self, name):\n\t\tif name not in self.__dict__[\"properties\"]:\n\t\t\tif name not in self.__dict__:\n\t\t\t\treturn None\n\t\t\treturn getattr(self, name)\n\t\treturn getattr(self, \"properties\")[name]\n\n\tdef __setitem__(self,name, value):\n\t\tself.__setattr__(name,value)\n\t# Dotted attribute setting.\n\tdef __setattr__(self, name, value):\n\t\tif name == \"properties\":\n\t\t\tself.__dict__[\"properties\"] = value\n\t\t\treturn\n\t\tif name in getattr(self, \"properties\"):\n\t\t\tself.__dict__[\"properties\"][name] = value\n\t\t\treturn\n\t\tself.__dict__[name] = value\n\t\t\n\tdef __str__(self):\n\t\toutput = \"\"\n\t\tfor key in self.table_definitions[self.table_name()]:\n\t\t\tnewKey = str(key.name)\n\t\t\twhile len(newKey) < 25:\n\t\t\t\tnewKey += \" \"\n\t\t\toutput += newKey + str(self[key.name]) + \"\\n\"\n\n\t\treturn output\n\tdef save(self):\n\t\tif self.read_only:\n\t\t\traise Exception(\"%s in READ_ONLY mode\" %(self.table_name()))\n\t\tparams = \"\"\n\t\tinserts = \"\"\n\t\tif not self[\"id\"]:\n\t\t\tfor k, v in self.__dict__[\"properties\"].properties.items():\n\t\t\t\tif v.value is not None:\n\t\t\t\t\tparams += \" \" + __class__.to_value_string(v.value) + \",\"#(str(v.value.replace(\"'\", \"''\")) if v.type is not str else \"'\" + v.value + \"'\") + \",\"\n\t\t\t\t\tinserts += k + \",\"\n\t\telse:\n\t\t\tfor k, v in self.__dict__[\"properties\"].properties.items():\n\t\t\t\tif k != \"id\":\n\t\t\t\t\tif v.value == None:\n\t\t\t\t\t\tvalue = \"NULL\"\n\t\t\t\t\telse:\n\t\t\t\t\t\tvalue = v.value\n\t\t\t\t\tparams += \" \\\"\" + k + \"\\\"=\" + (str(value) if v.type is not str else \"'\" + value + \"'\") + \",\"\n\t\tcur = self.conn.cursor()\n\t\tif self[\"id\"]:\n\t\t\tquery = \"UPDATE %s SET %s WHERE id = %s\" %(self.table_name(), params[:-1], self.id)\n\t\telse:\n\t\t\tquery = \"INSERT INTO %s (%s) VALUES (%s) RETURNING id;\" %(self.table_name(), inserts[:-1], params[:-1])\n\t\tif self.debug_mode:\n\t\t\tPrintHelper.print(query, \"ActiveRecord(%s) debug mode:\" %(self.table_name()))\n\t\tcur.execute(query)\n\t\tself.conn.commit()\n\t\tif not self[\"id\"]:\n\t\t\tself.id= cur.fetchone()[0]\n\t@classmethod\n\tdef find_or_create_by(self, params):\n\t\t#Attempt to find existing and return it\n\t\trecord = self.find_by(params)\n\t\tif record:\n\t\t\treturn record\n\t\t#No project found\n\t\treturn self.create(params)\n\t@classmethod\n\tdef create(self,params):\n\t\tif self.read_only:\n\t\t\traise Exception(\"%s in READ_ONLY mode\" %(self.table_name()))\n\t\t#Build query, exit if it's got invalid property keys\n\t\n\t\tquery = self.params_to_insert_query(params)\n\t\tif not query:\n\t\t\treturn False\n\t\t#Insert\n\t\tif self.debug_mode:\n\t\t\tPrintHelper.print(query, \"ActiveRecord(%s) debug mode:\" %(self.table_name()))\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(query)\n\t\ttry:\n\t\t\tself.conn.commit()\n\t\texcept psycopg2.InternalError as e:\n\t\t\tself.conn.rollback()\n\t\t#Create new record and set id\n\t\tnewRecord = self(params)\n\n\t\tnewRecord.id = int(cur.fetchone()[0])\n\t\t\n\t\treturn newRecord\n\t\n\t@classmethod\n\tdef choose(self):\n\t\tif len(self.choose_cache) == 0:\n\t\t\tself.choose_cache = self.find_all_by(self.choose_cache_filter, limit=self.choose_cache_size)\n\t\treturn choice(self.choose_cache)\n\t@classmethod\n\tdef multiInsert(self,records):\n\t\tif self.read_only:\n\t\t\traise Exception(\"%s in READ_ONLY mode\" %(self.table_name()))\n\t\tquery = \"INSERT INTO %s\" %(self.table_name())\n\t\tif self.debug_mode:\n\t\t\tPrintHelper.print(\"Multi-insert of %s records\" %(len(records)), \"ActiveRecord(%s) debug mode:\" %(self.table_name()))\n\t\tcols = []\n\t\tfor cell in records[0]:\n\t\t\tif type(cell) == str:\n\t\t\t\tcols.append(cell)\n\t\t\telse:\n\t\t\t\tcols.append(cell[0])\n\t\tquery += \"(%s) VALUES \" %(\",\".join(cols))\n\t\tvalues = []\n\t\tfor row in records:\n\t\t\ttemp = []\n\t\t\tif type(row) == dict:\n\t\t\t\tfor column, value in row.items():\n\t\t\t\t\ttemp.append(self.to_value_string(value))\n\t\t\telse:\n\t\t\t\tfor cell in row:\n\t\t\t\t\ttemp.append(self.to_value_string(cell[1]))\n\t\t\tvalues.append(\"(%s)\" %(\",\".join(temp)))\n\t\tquery += \",\".join(values) + \";\"\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(query)\n\t\tself.conn.commit()\n\t@classmethod\n\tdef params_to_insert_query(self,params):\n\t\tinserts = \"\"\n\t\tvalues = \"\"\n\t\ttempParams = params\n\t\tif not isinstance(tempParams, Props):\n\t\t\ttempParams = Props(dict())\n\t\t\tif isinstance(params,dict):\n\t\t\t\tfor k, v in params.items():\n\t\t\t\t\ttempParams[k] = str(v)\n\t\t\telse:\n\t\t\t\tfor item in params:\n\t\t\t\t\ttempParams[item[0]] = item[1]\n\t\tparams = tempParams\n\t\tfor k, v in tempParams.properties.items():\n\t\t\tmatch = False\n\t\t\tfor col in self.table_definitions[self.table_name()]:\n\t\t\t\tif col.name == k:\n\t\t\t\t\tinserts += \"\\\"\" + k + \"\\\",\"\n\t\t\t\t\tvalues += (\"'\" + str(v) + \"'\" if col.type != \"float32\" and col.type != \"int32\" else str(v)) + \",\"\n\t\t\t\t\tmatch = True\n\t\t\t\t\tbreak\t\n\t\t\tif match is False:\n\t\t\t\treturn False\n\t\treturn \"INSERT INTO %s (%s) VALUES (%s)\" %(self.table_name(), inserts[:-1], values[:-1]) + \" RETURNING id;\"\n\t@classmethod\n\tdef random(self, conditions= False):\n\t\tconds = False\n\t\tif self.table_name() not in self.random_selected_ids:\n\t\t\tself.random_selected_ids[self.table_name()] = []\n\t\telse: \n\t\t\tconds = \"id NOT IN (%s) \" %(\",\".join(self.random_selected_ids[self.table_name()]))\n\t\tif conditions:\n\t\t\tif not conds:\n\t\t\t\tconds = conditions\n\t\t\telse:\n\t\t\t\tconds += \" AND %s\" %(conditions)\n\t\trow = self.find_by(conds, sort=\" RANDOM() \") if conds else self.find_by(\"1 = 1\", sort = \" RANDOM()\")\n\t\tself.random_selected_ids[self.table_name()].append(str(row.id))\n\t\treturn row\n\t#Return the results from your last query. Excluding .next()\n\t@classmethod\n\tdef get_results(self):\n\t\tif self.table_name() in self.last_queries:\n\t\t\treturn self.last_queries[self.table_name()]\n\t\treturn []\n\n\t@staticmethod\n\tdef to_value_string(val):\n\t\tif Prop(\"test\",val).type is not str:\n\t\t\treturn \"%s\" %(val)\n\t\treturn \"'%s'\" %(str.replace(val, \"'\", \"''\"))\n\t@staticmethod\n\tdef convert_filter_object(obj):\n\t\tif isinstance(obj, str):\n\t\t\treturn obj\n\t\ttemp = []\n\t\tfor p in obj:\n\t\t\t#Arrays\n\t\t\tif not isinstance(p, str):\n\t\t\t\t#Not NULL\n\t\t\t\tif p[1]:\n\t\t\t\t\ttemp.append(\"%s = %s\" % (p[0], ActiveRecord.to_value_string(p[1])))\n\t\t\t\telse:\t\n\t\t\t\t\ttemp.append(\"%s IS NULL\" % (p[0]))\n\t\t\telse:\n\t\t\t\ttemp.append(p)\n\t\treturn temp\t\t\n\t# Temp method with greedy search.\n\t@classmethod\n\tdef find_dict_by(self, p, limit=False):\n\t\ttemp = self.convert_filter_object(p)\n\t\tr = self.cursor_to_dict_list(self.query_table( False, temp, limit=limit))\n\t\treturn r[0] if len(r) > 0 else None\n\n\t@classmethod\n\tdef find_all_dict_by(self, p, limit=False):\n\t\ttemp = self.convert_filter_object(p)\n\t\treturn self.cursor_to_dict_list(self.query_table( False, temp, limit=limit))\n\n\t\t# return lst\n\t@classmethod\n\tdef find_all_by(self, p, limit=False, sort=False):\n\t\ttemp = self.convert_filter_object(p)\n\t\tr = self.cursor_to_dict_list(self.query_table( False, temp, limit=limit, sort=sort))\n\t\tlst = list()\n\t\tfor a in r:\n\t\t\tlst.append(self(a))\n\t\treturn lst\n\n\t# @classmethod\n\t# def find_all_by(self,p):\n\t\t# temp = self.convert_filter_object(p)\n\t\t# r = self.cursor_to_dict_list(self.query_table( False, temp))\n\t\t# lst = list()\n\t\t# for a in r:\n\t\t\t# lst.append(self(a))\n\t\t# return lst\n\n\t@classmethod\n\tdef find_by(self,p, sort=False):\n\t\ttemp = self.convert_filter_object(p)\n\t\tr = self.cursor_to_dict_list(self.query_table( False, temp, 1, sort=sort))\n\t\treturn self(r[0]) if len(r) != 0 else None\n\n\t#With great power comes great responsibility\n\t# Return every record from a table\n\t@classmethod\n\tdef get_all(self, limit=False, sort=False):\n\t\tself.last_queries[self.table_name()] = self.cursor_to_dict_list(\n\t\tself.query_table( False, False, limit=limit, sort=sort))\n\t\treturn self.last_queries[self.table_name()]\n\n\t#Returns the next record in the database one at a time\n\t# returns false at the end of the table\n\t@classmethod\n\tdef next(self):\n\t\trecord = False\n\t\tif self.next_cache_size is not False:\n\t\t\tif not self.next_cache:\n\t\t\t\tself.next_cache = self.cursor_to_dict_list(self.query_table([],[self.next_filter,\"id > %s\" % (self.table_current_step_id[self.table_name()])], self.next_cache_size, \"id ASC\"))\n\t\t\tif self.next_cache:\n\t\t\t\trecord = self(self.next_cache[0])\n\t\t\t\tself.next_cache.pop(0)\n\t\t\t\tself.table_current_step_id[self.table_name()] = record.id\n\t\telse:\n\t\t\tres = self.cursor_to_dict_list(\n\t\t\t\tself.query_table([],[self.next_filter,\"id > %s\" % (self.table_current_step_id[self.table_name()])], 1, \"id ASC\"))\n\t\t\tif len(res)== 1:\n\t\t\t\trecord = self(res[0])\n\t\t\t\tself.table_current_step_id[self.table_name()] = record.id\n\t\treturn record\n\t#Skip n records and set the current table step to the next id\n\t@classmethod\n\tdef offset_next(self, count):\n\t\tres = self.cursor_to_dict_list(\n\t\tself.query_table([],[\"id = (SELECT id FROM inp_models OFFSET %s LIMIT 1)\" %(count)], 1, \"id ASC\"))\n\t\tif len(res)== 1:\n\t\t\trecord = self(res[0])\n\t\t\tself.table_current_step_id[self.table_name()] = res[0][\"id\"]\n\t\t\treturn record\n\t\treturn False\n\t\t#Reset .next() query counter\n\t@classmethod\n\tdef reset(self):\n\t\tself.table_current_step_id[self.table_name()] = 0\n\t@staticmethod\n\tdef getClassFromTableName(name):\n\t\treturn __class__.tableClasses[name]\n\t\t#PREP method: Pulls database table definitions for the structure and constraints\n\t@staticmethod\n\tdef loadModules():\n\t\tfor file in os.listdir(\"lib/active_record_models\"):\n\t\t\tif \".py\" in file:\n\t\t\t\tname = file.split(\".\")[0]\n\t\t\t\tnameSegments = name.split(\"_\")\n\t\t\t\tclassName \t= \"\"\n\t\t\t\tfor segment in nameSegments:\n\t\t\t\t\tclassName += segment[0].upper() + segment[1:]\n\t\t\t\t__class__.modules[name] = getattr(__import__(\"lib.active_record_models.\" + name, fromlist=[\"\"]), className)\n\n\t@classmethod\n\tdef load(self, autoloader=False):\n\t\tif not self.conn:\n\t\t\tprint(\"Error: Connection has not been established. Call self.conn(n,d,p,..). Exiting\")\n\t\t\texit()\n\t\tif autoloader:\n\t\t\t__class__.loadModules()\n\t\tfor cls in self.__subclasses__():\n\t\t\tself.tableClasses[cls.table_name] = cls\n\t\t\tfor cl in cls.__subclasses__():\n\t\t\t\tself.tableClasses[cl.table_name()] = cl\n\t\t\t\tself.table_definitions[cl.table_name()] = self.list_to_columns(\n\t\t\t\t\tself.reduce_cursor_to_simple_list(cl.get_columns()))\n\t\t\t\tself.table_current_step_id[cl.table_name()] = 0\n\t\t\tself.table_definitions[cls.table_name()] = self.list_to_columns(self.reduce_cursor_to_simple_list(cls.get_columns()))\n\t\t\tself.table_current_step_id[cls.table_name()] = 0\n\t\t\n\t@classmethod\n\tdef loadDependencies(self):\n\t\tfor column in self.table_definitions[self.table_name()]:\n\t\t\tif column.name[-3:] == \"_id\":\n\t\t\t\tnameSegments = column.name.split(\"_\")[0:-1]\n\t\t\t\tlibName\t\t= \"_\".join(nameSegments)\n\t\t\t\tclassName \t= \"\"\n\t\t\t\tfor segment in nameSegments:\n\t\t\t\t\tclassName += segment[0].upper() + segment[1:]\n\t\t\t\t\n\t\t\t\n\t\t# exit()\n\t# #Turn class name into table name\n\t@classmethod\n\tdef table_name(self, forceSingular=False):\n\t\tname = self.proxy_table_class.__name__ if self.proxy_table_class else self.__name__ \n\t\tname = re.sub(\"(?!^[A-Z])([A-Z])\", \"_\\\\1\", name).lower()\n\t\tif self.pluralise and not forceSingular:\n\t\t\tname = name + \"s\"\n\t\treturn name\n\t@classmethod\n\tdef relation_id_name(self):\n\t\treturn self.table_name(forceSingular=True) + \"_id\"\n\n\t@classmethod\n\t# Get list of columns for a given table with passed caveats and sorts\n\tdef get_columns(self, sort=\" 1 \", conds=False):\n\t\t# Translate conditions list\n\t\tcondString = self.to_condition_string(conds)\n\n\t\t# Create cursor and execute query\n\t\tcur = self.conn.cursor()\n\t\tcur.execute(\"\"\"SELECT column_name,\n\t\t\t\t\t\tCASE\n\t\t\t\t\t\tWHEN data_type = 'numeric'\n\t\t\t\t\t\tTHEN 'float32'\n\t\t\t\t\t\tWHEN data_type = 'integer'\n\t\t\t\t\t\tTHEN 'int32'\n\t\t\t\t\t\tELSE 's128'\n\t\t\t\t\t\tEND ndarray_type\n\t\t\t\t\t\tFROM information_schema.columns\n\t\t\t\t\t\tWHERE table_name = '%s' AND %s ORDER BY %s;\"\"\"\n\t\t\t\t\t\t% (self.table_name(), condString, sort))\n\t\treturn cur\n\n\t@classmethod\n\tdef naked_select(self, selects,conds,limit,sort):\n\t\ttemp = self.convert_filter_object(p)\n\t\tr = self.cursor_to_dict_list(self.query_table( False, temp))\n\t\toutput = list()\n\t\tfor row in r:\n\t\t\toutput.append(self(row))\n\t\treturn output\n\t\t\n\t@classmethod\n\t# Generic, single table query method with selection and conditions lists.\n\tdef query_table(self, selects, conds, limit=False, sort=False):\n\t\t\t# table \t-> name of table.\n\t\t\t# selects \t-> list of operations.\n\t\t\t# conds \t-> list of conditionals on selects.\n\t\t\t# limit \t-> number of records to return\n\t\t\t# sort\t\t-> sort order for return (some_column [ASC | DESC], some_other_column [ASC | DESC])\n\n\t\t# Translate conditions list\n\t\tcondString = self.to_condition_string(conds) if not isinstance(conds, str) else conds\n\t\t# Translate selection list\n\t\tif selects:\n\t\t\tselectString = self.to_selects(selects)\n\t\telse:\n\t\t\tselectString = self.default_selects\n\t\tsort = \" ORDER BY %s\" % (sort) if sort else \"\"\n\t\t# Limit\n\t\tlim = \"LIMIT %s\" % (limit) if limit else \"\"\n\t\t# print(condString)\n\t\t# Create cursor and execute query.\n\t\tcur = self.conn.cursor()\n\t\tquery = \"\"\"SELECT %s\n\t\t\tFROM %s\n\t\t\tWHERE %s\n\t\t\t%s\n\t\t\t%s\"\"\" % (selectString, self.table_name(), condString, sort, lim)\n\t\tif ActiveRecord.debug_mode:\n\t\t\tPrintHelper.print(query, \"ActiveRecord(%s) debug mode:\" %(self.table_name()))\n\t\tcur.execute(query)\n\n\t\treturn cur\n\t\n\t@classmethod\n\t# Translate list of strings to Sql (AND) conditions\n\tdef to_condition_string(self,conds):\n\n\t\t# Placeholder\n\t\tcondString = \"\"\n\n\t\t# If a list has been passed build condition string\n\t\tif isinstance(conds, list):\n\t\t\t# Skip initial AND.\n\t\t\tcondString += conds[0]\n\t\t\tconds.pop(0)\n\n\t\t\t# Do the rest (AND)\n\t\t\tfor cond in conds:\n\t\t\t\tcondString += \" AND \" + cond\n\t\tif self.default_filter:\n\t\t\tif condString:\n\t\t\t\tcondString += \" AND \" + self.default_filter\n\t\t\telse:\n\t\t\t\tcondString = self.default_filter\n\t\tif not condString:\n\t\t\tcondString = \"true\"\n\t\treturn condString\n\n\n\t@classmethod\n\t# Translate list to selection string\n\tdef to_selects(self,selects):\n\n\t\t# If a list is passed, build the string\n\t\tif isinstance(selects, list) and len(selects) > 0:\n\t\t\treturn \",\".join(selects)\n\t\t# Debatably dirty: Default to select all\n\t\telse:\n\t\t\treturn \"*\"\n\n\n\t@classmethod\n\t# Translate cursor to simple list removing dud records\n\tdef reduce_cursor_to_simple_list(self, results):\n\t\t# List for broken entries, each entry is a list of empty cell ids\n\t\tbrokenEntries = []\n\t\t# List of complete entries\n\t\tworkingEntries = []\n\t\t# With every entry\n\t\tfor row, entry in enumerate(results.fetchall()):\n\t\t\t# Temp list\n\t\t\tsimpleRow = []\n\t\t\t# Self explanatory, really\n\t\t\tsuccess = True\n\n\t\t# With each cell(column)\n\t\t\tfor cell in entry:\n\t\t\t\t# If it's an empty cell,bail out\n\t\t\t\tif cell is None:\n\t\t\t\t\tsuccess = False\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tsimpleRow.append(float(cell) if type(cell) is decimal.Decimal else cell)\n\t\t\t\t# Append clean row to results list.\n\t\t\tif success:\n\t\t\t\tworkingEntries.append(simpleRow)\n\t\treturn workingEntries\n\n\n\t# Translate Psycopg cursor to dictionary list\n\t@staticmethod\n\tdef cursor_to_dict_list(cursor):\n\t\tlst = list()\n\t\tkeys = cursor.description\n\t\tfor record in cursor.fetchall():\n\t\t\tr = dict()\n\t\t\tfor i, key in enumerate(keys):\n\t\t\t\tr[key.name] = record[i]\n\t\t\tlst.append(r)\n\t\treturn lst\n\n\n\t\t# Create column class for the table_definitions list.\n\t@staticmethod\n\tdef list_to_columns(cols):\n\t\tres = list()\n\t\tfor col in cols:\n\t\t\tres.append(Column(col[0], col[1]))\n\t\treturn res\n\tdef print(self):\n\t\tprint(\"Printing \" + self.table_name() + \" record \" + str(self.id))\n\t\tfor k, v in self.properties.properties.items():\n\t\t\tprint(k + \"\\t\" + str(v.value))\n\n# Simple class for table columns\nclass Column():\n\tdef __init__(self, name, type):\n\t\tself.name = name\n\t\tself.type = type\n\n\n\n","repo_name":"soliverit/active_record_py","sub_path":"lib/active_record.py","file_name":"active_record.py","file_ext":"py","file_size_in_byte":16865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"88"} +{"seq_id":"15963866642","text":"import re\nfrom decimal import Decimal\nfrom datetime import datetime\nimport attr\nfrom lxml import etree\nimport pytz\nfrom pathlib import Path\nfrom zope.interface import implementer\nfrom .. import handhistory as hh\nfrom ..card import Card\nfrom ..hand import Combo\nfrom ..constants import Limit, Game, GameType, Currency, Action, MoneyType\n\n\n__all__ = [\"PokerStarsHandHistory\", \"Notes\"]\n\n\n@implementer(hh.IStreet)\nclass _Street(hh._BaseStreet):\n def _parse_cards(self, boardline):\n self.cards = (Card(boardline[1:3]), Card(boardline[4:6]), Card(boardline[7:9]))\n\n def _parse_actions(self, actionlines):\n actions = []\n for line in actionlines:\n if line.startswith(\"Uncalled bet\"):\n action = self._parse_uncalled(line)\n elif \"collected\" in line:\n action = self._parse_collected(line)\n elif \"doesn't show hand\" in line:\n action = self._parse_muck(line)\n elif ' said, \"' in line: # skip chat lines\n continue\n elif \":\" in line:\n action = self._parse_player_action(line)\n else:\n raise RuntimeError(\"bad action line: \" + line)\n\n actions.append(hh._PlayerAction(*action))\n self.actions = tuple(actions) if actions else None\n\n def _parse_uncalled(self, line):\n first_paren_index = line.find(\"(\")\n second_paren_index = line.find(\")\")\n amount = line[first_paren_index + 1 : second_paren_index]\n name_start_index = line.find(\"to \") + 3\n name = line[name_start_index:]\n return name, Action.RETURN, Decimal(amount)\n\n def _parse_collected(self, line):\n first_space_index = line.find(\" \")\n name = line[:first_space_index]\n second_space_index = line.find(\" \", first_space_index + 1)\n third_space_index = line.find(\" \", second_space_index + 1)\n amount = line[second_space_index + 1 : third_space_index]\n self.pot = Decimal(amount)\n return name, Action.WIN, self.pot\n\n def _parse_muck(self, line):\n colon_index = line.find(\":\")\n name = line[:colon_index]\n return name, Action.MUCK, None\n\n def _parse_player_action(self, line):\n name, _, action = line.partition(\": \")\n action, _, amount = action.partition(\" \")\n amount, _, _ = amount.partition(\" \")\n\n if amount:\n return name, Action(action), Decimal(amount)\n else:\n return name, Action(action), None\n\n\n@implementer(hh.IHandHistory)\nclass PokerStarsHandHistory(hh._SplittableHandHistoryMixin, hh._BaseHandHistory):\n \"\"\"Parses PokerStars Tournament hands.\"\"\"\n\n _DATE_FORMAT = \"%Y/%m/%d %H:%M:%S ET\"\n _TZ = pytz.timezone(\"US/Eastern\") # ET\n _split_re = re.compile(r\" ?\\*\\*\\* ?\\n?|\\n\")\n _header_re = re.compile(\n r\"\"\"\n ^PokerStars\\s+ # Poker Room\n Hand\\s+\\#(?P\\d+):\\s+ # Hand history id\n (Tournament\\s+\\#(?P\\d+),\\s+ # Tournament Number\n ((?PFreeroll)|( # buyin is Freeroll\n \\$?(?P\\d+(\\.\\d+)?) # or buyin\n (\\+\\$?(?P\\d+(\\.\\d+)?))? # and rake\n (\\s+(?P[A-Z]+))? # and currency\n ))\\s+\n )?\n (?P.+?)\\s+ # game\n (?P(?:Pot\\s+|No\\s+|)Limit)\\s+ # limit\n (-\\s+Level\\s+(?P\\S+)\\s+)? # Level (optional)\n \\(\n (((?P\\d+)/(?P\\d+))|( # tournament blinds\n \\$(?P\\d+(\\.\\d+)?)/ # cash small blind\n \\$(?P\\d+(\\.\\d+)?) # cash big blind\n (\\s+(?P\\S+))? # cash currency\n ))\n \\)\\s+\n -\\s+.+?\\s+ # localized date\n \\[(?P.+?)\\] # ET date\n \"\"\",\n re.VERBOSE,\n )\n _table_re = re.compile(\n r\"^Table '(.*)' (\\d+)-max Seat #(?P\r\n\r\n\t\t\t\t\t\"\"\"\r\n\t\t\t\tinfo_column, phonecall_column = st.columns((2,1))\r\n\r\n\t\t\t\twith info_column:\r\n\t\t\t\t\tst.markdown(contact_form, unsafe_allow_html=True)\r\n\t\t\t\t\r\n\t\t\t\twith phonecall_column:\r\n\t\t\t\t\tst_lottie(phonecall_lottie)\r\n\r\n\t\t\t\t#styling the contact form\r\n\t\t\tdef locall_css(filename):\r\n\t\t\t\twith open(filename) as f:\r\n\t\t\t\t\tst.markdown(f\"